ai-helper-agent 2.8.15 → 2.8.16

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.
@@ -7,4 +7,4 @@ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,l as i}from"
7
7
 
8
8
  `+o.join(`
9
9
  `)}function V(e){let t=e.images||[],n=e.imageDescriptions||{},r=t.filter(e=>n[e.index]).length,i=t.filter(e=>!n[e.index]&&!e.overLimit&&(e.dataUrl||e.path)).length;return{described:r,total:t.length,deepReadable:i}}function Ze(e){if(e.imageStatus===`error`)return r(`docImages.previewFail`);let{described:t,total:n,deepReadable:i}=V(e),a=r(`docImages.previewDescribed`,{described:t,total:n});return i>0&&(a+=r(`docImages.previewDeepReadable`,{count:i})),a}function Qe(e){if(e.imageStatus===`error`)return r(`docImages.previewFail`);let{described:t,total:n,deepReadable:i}=V(e),a=r(`docImages.previewCompact`,{described:t,total:n});return i>0&&(a+=r(`docImages.previewCompactDeep`,{count:i})),a}var H=`_docImageSnapshot`;function $e(e){return e.files.reduce((e,t)=>e+(t.imageSource===`local`?t.images.reduce((e,t)=>e+(t.dataUrl?z(t.dataUrl):0),0):0),0)}var U=`chat-images`;function et(e,t=1){let n=Number.isFinite(t)&&t>0?Math.floor(t):1;return(Array.isArray(e)?e:[]).map(e=>e?.compressedUrl||e?.dataUrl||e?.originalUrl||``).filter(e=>!!e).slice(0,L.MAX_CHAT_IMAGE_SNAPSHOT).map((e,t)=>({index:n+t,dataUrl:e}))}function tt(e,t){let n=Number.isFinite(t),i=n?Math.max(1,Math.floor(Number(e)||1)):1,a=Math.max(0,Math.floor(Number(n?t:e)||0));return a<=0?``:`
10
- `+r(`docImages.chatImageHint`,{start:i,end:i+a-1,count:a,file:U})}function nt(e){return!e||typeof e!=`string`?e:e.replace(/\n?\[(?:对话图片|Chat images) \d+-\d+ \/ chat-images\][^\n]*/g,``)}async function rt(e,t,n=[]){let r=(await new Promise(e=>chrome.storage.local.get([H],e)))[H]||{},i=(t||[]).filter(e=>e.status===`done`&&(e.images||[]).length>0),a=Array.isArray(r[e]?.files)?r[e].files:[],o=a.find(e=>e.name===U),s=Array.isArray(o?.images)?o.images:[],c=et(n,s.reduce((e,t)=>Math.max(e,Number(t.index)||0),0)+1),l=[...s,...c],u=L.MAX_CHAT_IMAGE_SNAPSHOT,d=l.length>u?l.slice(l.length-u):l,f=c.length>0?{chatStart:c[0].index,chatCount:c.length}:{chatStart:0,chatCount:0},p=new Set(i.map(e=>e.name)),m=[...a.filter(e=>e&&e.name!==`chat-images`&&Array.isArray(e.images)&&!p.has(e.name)),...i].slice(-L.MAX_SESSION_DOC_FILES);if(m.length===0&&d.length===0)delete r[e];else{let t=m.map(e=>({name:e.name,imageSource:e.imageSource,images:e.images.map(e=>{let t={index:e.index,page:e.page??null};return e.path&&(t.path=e.path),e.dataUrl&&(t.dataUrl=e.dataUrl),t})}));d.length>0&&t.push({name:U,imageSource:`local`,images:d}),r[e]={updatedAt:Date.now(),files:t};let n=()=>Object.values(r).reduce((e,t)=>e+$e(t),0);for(;n()>L.SNAPSHOT_BUDGET&&Object.keys(r).length>1;){let t=Object.entries(r).filter(([t])=>t!==e).sort((e,t)=>e[1].updatedAt-t[1].updatedAt)[0];if(!t)break;delete r[t[0]]}n()>L.SNAPSHOT_BUDGET&&r[e]&&r[e].files.forEach(e=>{e.imageSource===`local`&&e.images.forEach(e=>{delete e.dataUrl})})}return await new Promise(e=>chrome.storage.local.set({[H]:r},e)),f}async function it(e){let t=(await new Promise(e=>chrome.storage.local.get([H],e)))[H]||{};t[e]&&(delete t[e],await new Promise(e=>chrome.storage.local.set({[H]:t},e)))}var at=t({appendMessageToSession:()=>pt,archiveCurrentSession:()=>xt,archiveSession:()=>vt,createScheduledSession:()=>Ct,createSession:()=>X,deleteStoreSession:()=>$,duplicateSession:()=>St,hydrateSessionWorkdir:()=>q,importSessions:()=>ft,init:()=>G,listArchivedSessions:()=>bt,loadSessions:()=>K,persistSessionState:()=>dt,renameSession:()=>ht,reorderSessions:()=>gt,saveCurrentSession:()=>J,serializeMessageHistory:()=>Y,setSessionWorkdirBinding:()=>mt,switchToSession:()=>Q,unarchiveSession:()=>yt});n(`zh`,{session:{newSession:`新会话`,importedSession:`导入的会话`,unnamedSession:`未命名会话`,restoredSession:`恢复的会话`,forkSuffix:`分叉`,sourceNotFound:`源会话不存在`,scheduledSession:`定时任务`}}),n(`en`,{session:{newSession:`New session`,importedSession:`Imported session`,unnamedSession:`Unnamed session`,restoredSession:`Restored session`,forkSuffix:`Fork`,sourceNotFound:`Source session not found`,scheduledSession:`Scheduled task`}});async function ot(e){try{await d(e)}catch(e){i.warn(`[session-store] cleanup ReAct checkpoint failed:`,e)}}var W=!1;async function G(){W||(await f(),W=!0,st())}async function st(){try{let e=await b(),t=new Set(e.map(e=>e.id));t.add(`default`);let n=await chrome.storage.local.get(null),r=Object.keys(n).filter(e=>e.startsWith(`scrollPosition_`)&&!t.has(e.slice(15)));r.length>0&&(await chrome.storage.local.remove(r),i.debug(`[session-store] cleanup ${r.length} orphan scrollPosition key:`,r))}catch(e){i.warn(`[session-store] cleanup orphaned scrollPosition failed:`,e)}}async function K({includeArchived:e=!1,withActiveHistory:t=!0}={}){await G();let n=await p(),r=null;try{r=await v()}catch(e){i.error(`[SessionStore] read session summaries failed, fallback to full read:`,e.message)}r||=(await b()).map(e=>o(e)).filter(Boolean);let a=e?r:r.filter(e=>!e.archivedAt);if(a.sort((e,t)=>e.order!==void 0&&t.order!==void 0?e.order-t.order:e.order===void 0?t.order===void 0?new Date(e.createdAt)-new Date(t.createdAt):1:-1),t&&n){let e=await g(n);if(e){let t=a.findIndex(e=>e.id===n);t>=0&&(a[t]=e)}}return{activeSessionId:n,list:a}}function ct(e){return typeof e==`string`?e:Array.isArray(e)?e.filter(e=>e.type===`text`).map(e=>e.text).join(``):``}function q(e){h.sessionWorkdir=e?.workdir||null,h.workdirAgentId=e?.workdirAgentId||null,h.sessionWorkdirOwner=e?.id||null}async function J(){if(!h.activeSessionId)return!1;let e=await g(h.activeSessionId);if(!e)return i.warn(`[SessionStore] saveCurrentSession cannot find currentsession:`,h.activeSessionId),!1;if(e.model=h.currentModel,e.useTools=h.useTools,e.enabledTools=[...h.enabledTools],e.agentId=h.activeAgentId||null,e.temperature=h.temperature,e.topP=h.topP,e.contextCompaction=h.activeCompaction||void 0,e.goalMode=!!h.goalMode,h.sessionWorkdirOwner===h.activeSessionId&&(e.workdir=h.sessionWorkdir||null,e.workdirAgentId=h.sessionWorkdir&&h.workdirAgentId||null),e.messageHistory=Y(h.messageHistory),e.updatedAt=new Date().toISOString(),!e.forkMetadata&&!e.titleManuallySet){let t=h.messageHistory.find(e=>e.role===`user`);t&&(e.title=ct(t.content).substring(0,50).replace(/\n/g,` `))}return await y(e)?!0:(i.error(`[SessionStore] putSession failed, sessionId:`,h.activeSessionId),!1)}function Y(e){return(e||[]).map(e=>({role:e.role,content:e.content||``,executionLog:e.executionLog||[],reflectionScore:e.reflectionScore,wasRevised:e.wasRevised||!1,htmlContent:e.htmlContent||void 0,messageId:e.messageId||void 0,timestamp:e.timestamp||void 0,contextBubbles:e.contextBubbles||void 0,resumable:e.resumable||!1,callId:e.callId||void 0,resumed:e.resumed||void 0}))}function lt(e,t){return!e||!t?!1:e.messageId&&t.messageId?e.messageId===t.messageId:e.role===t.role&&(e.content||``)===(t.content||``)}function ut(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&lt(e[r],t[r]);)r++;return r===0||r===e.length?t:[...t.slice(0,r),...e.slice(r),...t.slice(r)]}async function dt(e,t={}){if(!e)return!1;await G();let n=await g(e);if(!n)return i.warn(`[SessionStore] persistSessionState cannot find session:`,e),!1;let{messageHistory:r,model:a,useTools:o,enabledTools:s,agentId:c,temperature:l,topP:u,activeCompaction:d,workdir:f,workdirAgentId:p,goalMode:m}=t;return a!==void 0&&(n.model=a),o!==void 0&&(n.useTools=o),s!==void 0&&(n.enabledTools=[...s]),c!==void 0&&(n.agentId=c||null),l!==void 0&&(n.temperature=l),u!==void 0&&(n.topP=u),d!==void 0&&(n.contextCompaction=d||void 0),m!==void 0&&(n.goalMode=!!m),f!==void 0&&(n.workdir=f||null),p!==void 0&&(n.workdirAgentId=p||null),r!==void 0&&(n.messageHistory=ut(Array.isArray(n.messageHistory)?n.messageHistory:[],Y(r))),n.updatedAt=new Date().toISOString(),y(n)}async function X(){await G();let e=Z(),t={id:e,title:r(`session.newSession`),model:h.currentModel,useTools:h.useTools,enabledTools:[...h.enabledTools],agentId:h.activeAgentId||null,temperature:h.temperature,topP:h.topP,messageHistory:[],scrollPosition:0,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),order:Date.now(),isGenerating:!1,lastExecutionLog:[],goalMode:!1,workdir:null,workdirAgentId:null};return await y(t),await S(e),h.goalMode=!1,t}async function ft(e){await G();let t=[];for(let n of e){let e={id:Z(),title:n.title||r(`session.importedSession`),model:n.model||h.currentModel,useTools:n.useTools===void 0?!0:n.useTools,enabledTools:n.enabledTools||[...h.enabledTools],temperature:n.temperature===void 0?h.temperature:n.temperature,topP:n.topP===void 0?h.topP:n.topP,agentId:n.agentId||null,messageHistory:(n.messageHistory||[]).map(e=>({role:e.role,content:e.content||``,executionLog:e.executionLog||[],reflectionScore:e.reflectionScore,wasRevised:e.wasRevised||!1,htmlContent:e.htmlContent||void 0,messageId:e.messageId||void 0,timestamp:e.timestamp||void 0})),scrollPosition:0,createdAt:n.createdAt||new Date().toISOString(),updatedAt:new Date().toISOString(),order:Date.now()+t.length,isGenerating:!1,lastExecutionLog:[],workdir:null,workdirAgentId:null};await y(e),t.push(e)}return!await p()&&t.length>0&&await S(t[0].id),t}async function pt(e,t){let n=await g(e);if(!n)return!1;n.messageHistory=n.messageHistory||[];let r={role:t.role,content:t.content||``,executionLog:t.executionLog||[],reflectionScore:t.reflectionScore,wasRevised:t.wasRevised||!1,htmlContent:t.htmlContent||void 0,messageId:t.messageId||void 0,timestamp:t.timestamp||void 0,contextBubbles:t.contextBubbles||void 0,callId:t.callId||void 0,resumed:t.resumed||void 0,resumable:t.resumable===void 0?void 0:t.resumable},i=t.callId||``,a=i?n.messageHistory.findIndex(e=>e&&e.callId===i):-1;if(a>=0){let e=n.messageHistory[a]||{};n.messageHistory[a]={...e,role:r.role||e.role,content:r.content||e.content||``,executionLog:r.executionLog.length>0?r.executionLog:e.executionLog||[],reflectionScore:r.reflectionScore==null?e.reflectionScore:r.reflectionScore,wasRevised:!!(e.wasRevised||r.wasRevised),htmlContent:r.htmlContent||e.htmlContent,messageId:r.messageId||e.messageId,timestamp:r.timestamp||e.timestamp,contextBubbles:r.contextBubbles||e.contextBubbles,callId:i,resumed:r.resumed||e.resumed,resumable:r.resumable===void 0?e.resumable:r.resumable}}else n.messageHistory.push(r);return n.updatedAt=new Date().toISOString(),n.isGenerating=!1,await y(n),!0}function Z(){return`sess_`+Date.now().toString(36)+`_`+Math.random().toString(36).substring(2,8)}async function Q(e){if(e===h.activeSessionId)return;let t=J(),n=chrome.storage.local.get([`modelName`,`temperature`,`topP`]).catch(()=>({})),[r]=await Promise.all([g(e),t]);if(!r)return i.error(`[SessionStore] find not to session:`,e),!1;r.archivedAt&&(delete r.archivedAt,r.order=await _t(),await y(r)),await S(e),h.activeSessionId=e,h.messageHistory=r.messageHistory||[],h.activeCompaction=r.contextCompaction||null,h.currentModel=r.model||h.currentModel,h.temperature=r.temperature===void 0?h.temperature:r.temperature,h.topP=r.topP===void 0?h.topP:r.topP,h.useTools=r.useTools===void 0?h.useTools:r.useTools,h.goalMode=!!r.goalMode,h.activeAgentId=r.agentId||null,q(r);try{let{resetWorkspaceRoot:e}=await x(async()=>{let{resetWorkspaceRoot:e}=await import(`./workspace-manager-Cd4F0wEB.js`).then(e=>e.j);return{resetWorkspaceRoot:e}},__vite__mapDeps([4,1,5,6]));e()}catch(e){i.warn(`[SessionStore] reset workspace root failed:`,e)}try{document.dispatchEvent(new CustomEvent(`session-workdir-changed`,{detail:{sessionId:e,workdir:h.sessionWorkdir,agentId:h.workdirAgentId}}))}catch{}if(r.agentId?chrome.storage.local.set({activeAssistantId:r.agentId}):chrome.storage.local.remove(`activeAssistantId`),r.agentId&&r.agentId!=="default")try{let{getAgent:e}=await x(async()=>{let{getAgent:e}=await import(`./agent-store-grxR4rg1.js`).then(e=>e.t);return{getAgent:e}},__vite__mapDeps([7,1,5,6])),t=await e(r.agentId);t&&(t.model&&(h.currentModel=t.model),t.temperature!==null&&t.temperature!==void 0&&(h.temperature=t.temperature,h.topP=t.topP!==null&&t.topP!==void 0?t.topP:1),document.dispatchEvent(new CustomEvent(`agent-model-changed`)))}catch{}else{let e=await n;e.modelName&&(h.currentModel=e.modelName),e.temperature!==void 0&&(h.temperature=e.temperature),e.topP!==void 0&&(h.topP=e.topP),document.dispatchEvent(new CustomEvent(`agent-model-changed`))}return r.isGenerating&&h.pendingCallApiSessionIds.has(e)?h.generatingSessionIds.add(e):r.isGenerating&&(i.debug(`[SessionStore] detected expiredperiod isGenerating mark,async cleanup:`,e),(async()=>{try{let t=await g(e);t&&(t.isGenerating=!1,await y(t))}catch(e){i.warn(`[SessionStore] cleanup expired isGenerating mark failed:`,e)}})()),r}async function $(e){let t=await b(),n=await p();try{await it(e)}catch{}if(await c(e),chrome.storage.local.remove(`scrollPosition_`+e),await ot(e),u(e).catch(e=>{i.debug(`[SessionStore] unbind session workdir failed:`,e?.message||e)}),n===e){h.sessionWorkdir=null,h.workdirAgentId=null;try{document.dispatchEvent(new CustomEvent(`session-workdir-changed`))}catch{}}try{let t=(await a()).filter(t=>t.sessionId===e);for(let e of t)await s(e.id);t.length>0&&i.info(`[SessionStore] cleaned ${t.length} bookmark (session ${e} deleted)`)}catch(e){i.warn(`[SessionStore] cleanup bookmarks failed:`,e)}if(n===e){let n=[...t].sort((e,t)=>e.order!==void 0&&t.order!==void 0?e.order-t.order:e.order===void 0?t.order===void 0?new Date(e.createdAt)-new Date(t.createdAt):1:-1),r=n.findIndex(t=>t.id===e),i=n.filter(t=>t.id!==e);i.length>0?await S(i[Math.min(r,i.length-1)].id):await S(null)}return!0}async function mt(e,t,n=null){if(!e)return!1;let r=await g(e);if(!r)return i.warn(`[SessionStore] setSessionWorkdirBinding cannot find session:`,e),!1;r.workdir=t||null,r.workdirAgentId=t&&n||null,r.updatedAt=new Date().toISOString(),h.activeSessionId===e&&(h.sessionWorkdir=r.workdir,h.workdirAgentId=r.workdirAgentId,h.sessionWorkdirOwner=e);let a=await y(r);try{document.dispatchEvent(new CustomEvent(`session-workdir-changed`,{detail:{sessionId:e,workdir:r.workdir,agentId:r.workdirAgentId}}))}catch{}return a}async function ht(e,t){let n=await g(e);return n?(n.title=t,n.titleManuallySet=!0,n.updatedAt=new Date().toISOString(),await y(n),!0):!1}async function gt(e){let t=null;try{t=await v()}catch(e){i.error(`[SessionStore] read session summaries failed, fallback to full read:`,e.message)}if(!t){let t=await b(),n=new Map(t.map(e=>[e.id,e])),r=[];return e.forEach((e,t)=>{let i=n.get(e);i&&i.order!==t&&(i.order=t,r.push(i))}),r.length?_(r):!0}let n=new Map(t.map(e=>[e.id,e.order])),r=new Map(e.map((e,t)=>[e,t])),a=e.filter(e=>n.has(e)?n.get(e)!==r.get(e):!1);if(!a.length)return!0;let o=[];for(let e of a){let t=await g(e);t&&(t.order=r.get(e),o.push(t))}return o.length?_(o):!0}async function _t(){let e=await b(),t=-1;for(let n of e)n.archivedAt||typeof n.order==`number`&&n.order>t&&(t=n.order);return t+1}async function vt(e){if(!e)return!1;let t=await g(e);return t?t.archivedAt?!0:(t.archivedAt=new Date().toISOString(),t.isGenerating=!1,y(t)):!1}async function yt(e){if(!e)return!1;let t=await g(e);return!t||!t.archivedAt?!1:(delete t.archivedAt,t.order=await _t(),y(t))}async function bt(){await G();let e=null;try{e=await v()}catch(e){i.error(`[SessionStore] read session summaries failed, fallback to full read:`,e.message)}return(e??await b()).filter(e=>e.archivedAt).sort((e,t)=>new Date(t.archivedAt||0)-new Date(e.archivedAt||0))}async function xt(){if(!h.messageHistory||h.messageHistory.length===0)return;let e=await g(h.activeSessionId);if(!e)return;let t=e.titleManuallySet||e.forkMetadata,n=h.messageHistory.find(e=>e.role===`user`),i=t?e.title||r(`session.unnamedSession`):n?ct(n.content).substring(0,50).replace(/\n/g,` `):e.title||r(`session.unnamedSession`),a=Date.now().toString(36)+Math.random().toString(36).substring(2,8),o=h.messageHistory.map(e=>({role:e.role,content:e.content||``,executionLog:e.executionLog||[],reflectionScore:e.reflectionScore,wasRevised:e.wasRevised||!1,htmlContent:e.htmlContent||void 0})),s=await l();s.push({id:a,title:i,createdAt:new Date().toISOString(),messages:o}),s.length>20&&s.splice(0,s.length-20),await m(s);let c=await X();return await $(e.id),await Q(c.id),!0}async function St(e,t=null){await G();let n=await g(e);if(!n)throw Error(r(`session.sourceNotFound`));let i=Z(),a=new Date().toISOString(),o=n.messageHistory||[],s=!1;if(t){let e=o.findIndex(e=>e.messageId===t);e>=0&&(o=o.slice(0,e+1),s=!0)}let c=o.map(e=>({...e,executionLog:Array.isArray(e.executionLog)?[...e.executionLog]:[],contextBubbles:Array.isArray(e.contextBubbles)?[...e.contextBubbles]:void 0,messageId:`msg_`+Date.now().toString(36)+`_`+Math.random().toString(36).substring(2,8)})),l={...n,id:i,title:`${n.title||r(`session.newSession`)} - ${r(`session.forkSuffix`)}`,messageHistory:c,isGenerating:!1,lastExecutionLog:[],scrollPosition:0,createdAt:a,updatedAt:a,order:Date.now(),forkMetadata:{sourceSessionId:e,forkedAt:a,...s?{upToMessageId:t}:{}}};return await y(l),await S(i),l}async function Ct(e){await G();let t={id:Z(),title:e.name||r(`session.scheduledSession`),model:e.model||null,useTools:e.useTools==null?null:e.useTools,enabledTools:null,agentId:e.agentId||null,temperature:e.temperature==null?null:e.temperature,topP:e.topP==null?null:e.topP,messageHistory:[],scrollPosition:0,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),order:Date.now(),isGenerating:!1,lastExecutionLog:[],scheduledTaskId:e.id,workdir:e.workdir||null,workdirAgentId:e.workdir&&e.workdirAgentId||null};return await y(t),t}export{Oe as $,rt as A,Se as B,Qe as C,Le as D,Ye as E,O as F,Ae as G,ke as H,be as I,xe as J,ye as K,Ee as L,Pe as M,A as N,Ge as O,ue as P,De as Q,Me as R,Xe as S,qe as T,_e as U,F as V,de as W,P as X,ve as Y,je as Z,mt as _,X as a,oe as at,L as b,q as c,K as d,we as et,dt as f,at as g,J as h,Ct as i,C as it,nt as j,ze as k,ft as l,gt as m,xt as n,le as nt,$ as o,ne as ot,ht as p,Te as q,vt as r,D as rt,St as s,te as st,pt as t,w as tt,bt as u,Q as v,Ze as w,tt as x,yt as y,Ne as z};
10
+ `+r(`docImages.chatImageHint`,{start:i,end:i+a-1,count:a,file:U})}function nt(e){return!e||typeof e!=`string`?e:e.replace(/\n?\[(?:对话图片|Chat images) \d+-\d+ \/ chat-images\][^\n]*/g,``)}async function rt(e,t,n=[]){let r=(await new Promise(e=>chrome.storage.local.get([H],e)))[H]||{},i=(t||[]).filter(e=>e.status===`done`&&(e.images||[]).length>0),a=Array.isArray(r[e]?.files)?r[e].files:[],o=a.find(e=>e.name===U),s=Array.isArray(o?.images)?o.images:[],c=et(n,s.reduce((e,t)=>Math.max(e,Number(t.index)||0),0)+1),l=[...s,...c],u=L.MAX_CHAT_IMAGE_SNAPSHOT,d=l.length>u?l.slice(l.length-u):l,f=c.length>0?{chatStart:c[0].index,chatCount:c.length}:{chatStart:0,chatCount:0},p=new Set(i.map(e=>e.name)),m=[...a.filter(e=>e&&e.name!==`chat-images`&&Array.isArray(e.images)&&!p.has(e.name)),...i].slice(-L.MAX_SESSION_DOC_FILES);if(m.length===0&&d.length===0)delete r[e];else{let t=m.map(e=>({name:e.name,imageSource:e.imageSource,images:e.images.map(e=>{let t={index:e.index,page:e.page??null};return e.path&&(t.path=e.path),e.dataUrl&&(t.dataUrl=e.dataUrl),t})}));d.length>0&&t.push({name:U,imageSource:`local`,images:d}),r[e]={updatedAt:Date.now(),files:t};let n=()=>Object.values(r).reduce((e,t)=>e+$e(t),0);for(;n()>L.SNAPSHOT_BUDGET&&Object.keys(r).length>1;){let t=Object.entries(r).filter(([t])=>t!==e).sort((e,t)=>e[1].updatedAt-t[1].updatedAt)[0];if(!t)break;delete r[t[0]]}n()>L.SNAPSHOT_BUDGET&&r[e]&&r[e].files.forEach(e=>{e.imageSource===`local`&&e.images.forEach(e=>{delete e.dataUrl})})}return await new Promise(e=>chrome.storage.local.set({[H]:r},e)),f}async function it(e){let t=(await new Promise(e=>chrome.storage.local.get([H],e)))[H]||{};t[e]&&(delete t[e],await new Promise(e=>chrome.storage.local.set({[H]:t},e)))}var at=t({appendMessageToSession:()=>mt,archiveCurrentSession:()=>St,archiveSession:()=>yt,createScheduledSession:()=>wt,createSession:()=>X,deleteStoreSession:()=>$,duplicateSession:()=>Ct,hydrateSessionWorkdir:()=>q,importSessions:()=>pt,init:()=>G,listArchivedSessions:()=>xt,loadSessions:()=>K,persistSessionState:()=>ft,renameSession:()=>gt,reorderSessions:()=>_t,saveCurrentSession:()=>J,serializeMessageHistory:()=>Y,setSessionWorkdirBinding:()=>ht,switchToSession:()=>Q,unarchiveSession:()=>bt});n(`zh`,{session:{newSession:`新会话`,importedSession:`导入的会话`,unnamedSession:`未命名会话`,restoredSession:`恢复的会话`,forkSuffix:`分叉`,sourceNotFound:`源会话不存在`,scheduledSession:`定时任务`}}),n(`en`,{session:{newSession:`New session`,importedSession:`Imported session`,unnamedSession:`Unnamed session`,restoredSession:`Restored session`,forkSuffix:`Fork`,sourceNotFound:`Source session not found`,scheduledSession:`Scheduled task`}});async function ot(e){try{await d(e)}catch(e){i.warn(`[session-store] cleanup ReAct checkpoint failed:`,e)}}var W=!1;async function G(){W||(await f(),W=!0,st())}async function st(){try{let e=await b(),t=new Set(e.map(e=>e.id));t.add(`default`);let n=await chrome.storage.local.get(null),r=Object.keys(n).filter(e=>e.startsWith(`scrollPosition_`)&&!t.has(e.slice(15)));r.length>0&&(await chrome.storage.local.remove(r),i.debug(`[session-store] cleanup ${r.length} orphan scrollPosition key:`,r))}catch(e){i.warn(`[session-store] cleanup orphaned scrollPosition failed:`,e)}}async function K({includeArchived:e=!1,withActiveHistory:t=!0}={}){await G();let n=await p(),r=null;try{r=await v()}catch(e){i.error(`[SessionStore] read session summaries failed, fallback to full read:`,e.message)}r||=(await b()).map(e=>o(e)).filter(Boolean);let a=e?r:r.filter(e=>!e.archivedAt);if(a.sort((e,t)=>e.order!==void 0&&t.order!==void 0?e.order-t.order:e.order===void 0?t.order===void 0?new Date(e.createdAt)-new Date(t.createdAt):1:-1),t&&n){let e=await g(n);if(e){let t=a.findIndex(e=>e.id===n);t>=0&&(a[t]=e)}}return{activeSessionId:n,list:a}}function ct(e){return typeof e==`string`?e:Array.isArray(e)?e.filter(e=>e.type===`text`).map(e=>e.text).join(``):``}function q(e){h.sessionWorkdir=e?.workdir||null,h.workdirAgentId=e?.workdirAgentId||null,h.sessionWorkdirOwner=e?.id||null}function lt(e){let t=e||[],n=[String(t.length)];for(let e of t){if(!e){n.push(`-`);continue}let t=e.content,r=typeof t==`string`||Array.isArray(t)?t.length:0;n.push([e.role||``,e.messageId||``,e.callId||``,r,e.htmlContent?e.htmlContent.length:0,e.executionLog?e.executionLog.length:0,+!!e.resumable,+!!e.resumed].join(`:`))}return n.join(`|`)}async function J(){if(!h.activeSessionId)return!1;let e=await g(h.activeSessionId);if(!e)return i.warn(`[SessionStore] saveCurrentSession cannot find currentsession:`,h.activeSessionId),!1;let t=lt(e.messageHistory);if(e.model=h.currentModel,e.useTools=h.useTools,e.enabledTools=[...h.enabledTools],e.agentId=h.activeAgentId||null,e.temperature=h.temperature,e.topP=h.topP,e.contextCompaction=h.activeCompaction||void 0,e.goalMode=!!h.goalMode,h.sessionWorkdirOwner===h.activeSessionId&&(e.workdir=h.sessionWorkdir||null,e.workdirAgentId=h.sessionWorkdir&&h.workdirAgentId||null),e.messageHistory=Y(h.messageHistory),!e.forkMetadata&&!e.titleManuallySet){let t=h.messageHistory.find(e=>e.role===`user`);t&&(e.title=ct(t.content).substring(0,50).replace(/\n/g,` `))}return lt(e.messageHistory)!==t&&(e.updatedAt=new Date().toISOString()),await y(e)?!0:(i.error(`[SessionStore] putSession failed, sessionId:`,h.activeSessionId),!1)}function Y(e){return(e||[]).map(e=>({role:e.role,content:e.content||``,executionLog:e.executionLog||[],reflectionScore:e.reflectionScore,wasRevised:e.wasRevised||!1,htmlContent:e.htmlContent||void 0,messageId:e.messageId||void 0,timestamp:e.timestamp||void 0,contextBubbles:e.contextBubbles||void 0,resumable:e.resumable||!1,callId:e.callId||void 0,resumed:e.resumed||void 0}))}function ut(e,t){return!e||!t?!1:e.messageId&&t.messageId?e.messageId===t.messageId:e.role===t.role&&(e.content||``)===(t.content||``)}function dt(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&ut(e[r],t[r]);)r++;return r===0||r===e.length?t:[...t.slice(0,r),...e.slice(r),...t.slice(r)]}async function ft(e,t={}){if(!e)return!1;await G();let n=await g(e);if(!n)return i.warn(`[SessionStore] persistSessionState cannot find session:`,e),!1;let{messageHistory:r,model:a,useTools:o,enabledTools:s,agentId:c,temperature:l,topP:u,activeCompaction:d,workdir:f,workdirAgentId:p,goalMode:m}=t;return a!==void 0&&(n.model=a),o!==void 0&&(n.useTools=o),s!==void 0&&(n.enabledTools=[...s]),c!==void 0&&(n.agentId=c||null),l!==void 0&&(n.temperature=l),u!==void 0&&(n.topP=u),d!==void 0&&(n.contextCompaction=d||void 0),m!==void 0&&(n.goalMode=!!m),f!==void 0&&(n.workdir=f||null),p!==void 0&&(n.workdirAgentId=p||null),r!==void 0&&(n.messageHistory=dt(Array.isArray(n.messageHistory)?n.messageHistory:[],Y(r))),n.updatedAt=new Date().toISOString(),y(n)}async function X(){await G();let e=Z(),t={id:e,title:r(`session.newSession`),model:h.currentModel,useTools:h.useTools,enabledTools:[...h.enabledTools],agentId:h.activeAgentId||null,temperature:h.temperature,topP:h.topP,messageHistory:[],scrollPosition:0,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),order:Date.now(),isGenerating:!1,lastExecutionLog:[],goalMode:!1,workdir:null,workdirAgentId:null};return await y(t),await S(e),h.goalMode=!1,t}async function pt(e){await G();let t=[];for(let n of e){let e={id:Z(),title:n.title||r(`session.importedSession`),model:n.model||h.currentModel,useTools:n.useTools===void 0?!0:n.useTools,enabledTools:n.enabledTools||[...h.enabledTools],temperature:n.temperature===void 0?h.temperature:n.temperature,topP:n.topP===void 0?h.topP:n.topP,agentId:n.agentId||null,messageHistory:(n.messageHistory||[]).map(e=>({role:e.role,content:e.content||``,executionLog:e.executionLog||[],reflectionScore:e.reflectionScore,wasRevised:e.wasRevised||!1,htmlContent:e.htmlContent||void 0,messageId:e.messageId||void 0,timestamp:e.timestamp||void 0})),scrollPosition:0,createdAt:n.createdAt||new Date().toISOString(),updatedAt:new Date().toISOString(),order:Date.now()+t.length,isGenerating:!1,lastExecutionLog:[],workdir:null,workdirAgentId:null};await y(e),t.push(e)}return!await p()&&t.length>0&&await S(t[0].id),t}async function mt(e,t){let n=await g(e);if(!n)return!1;n.messageHistory=n.messageHistory||[];let r={role:t.role,content:t.content||``,executionLog:t.executionLog||[],reflectionScore:t.reflectionScore,wasRevised:t.wasRevised||!1,htmlContent:t.htmlContent||void 0,messageId:t.messageId||void 0,timestamp:t.timestamp||void 0,contextBubbles:t.contextBubbles||void 0,callId:t.callId||void 0,resumed:t.resumed||void 0,resumable:t.resumable===void 0?void 0:t.resumable},i=t.callId||``,a=i?n.messageHistory.findIndex(e=>e&&e.callId===i):-1;if(a>=0){let e=n.messageHistory[a]||{};n.messageHistory[a]={...e,role:r.role||e.role,content:r.content||e.content||``,executionLog:r.executionLog.length>0?r.executionLog:e.executionLog||[],reflectionScore:r.reflectionScore==null?e.reflectionScore:r.reflectionScore,wasRevised:!!(e.wasRevised||r.wasRevised),htmlContent:r.htmlContent||e.htmlContent,messageId:r.messageId||e.messageId,timestamp:r.timestamp||e.timestamp,contextBubbles:r.contextBubbles||e.contextBubbles,callId:i,resumed:r.resumed||e.resumed,resumable:r.resumable===void 0?e.resumable:r.resumable}}else n.messageHistory.push(r);return n.updatedAt=new Date().toISOString(),n.isGenerating=!1,await y(n),!0}function Z(){return`sess_`+Date.now().toString(36)+`_`+Math.random().toString(36).substring(2,8)}async function Q(e){if(e===h.activeSessionId)return;let t=J(),n=chrome.storage.local.get([`modelName`,`temperature`,`topP`]).catch(()=>({})),[r]=await Promise.all([g(e),t]);if(!r)return i.error(`[SessionStore] find not to session:`,e),!1;r.archivedAt&&(delete r.archivedAt,r.order=await vt(),await y(r)),await S(e),h.activeSessionId=e,h.messageHistory=r.messageHistory||[],h.activeCompaction=r.contextCompaction||null,h.currentModel=r.model||h.currentModel,h.temperature=r.temperature===void 0?h.temperature:r.temperature,h.topP=r.topP===void 0?h.topP:r.topP,h.useTools=r.useTools===void 0?h.useTools:r.useTools,h.goalMode=!!r.goalMode,h.activeAgentId=r.agentId||null,q(r);try{let{resetWorkspaceRoot:e}=await x(async()=>{let{resetWorkspaceRoot:e}=await import(`./workspace-manager-Cd4F0wEB.js`).then(e=>e.j);return{resetWorkspaceRoot:e}},__vite__mapDeps([4,1,5,6]));e()}catch(e){i.warn(`[SessionStore] reset workspace root failed:`,e)}try{document.dispatchEvent(new CustomEvent(`session-workdir-changed`,{detail:{sessionId:e,workdir:h.sessionWorkdir,agentId:h.workdirAgentId}}))}catch{}if(r.agentId?chrome.storage.local.set({activeAssistantId:r.agentId}):chrome.storage.local.remove(`activeAssistantId`),r.agentId&&r.agentId!=="default")try{let{getAgent:e}=await x(async()=>{let{getAgent:e}=await import(`./agent-store-grxR4rg1.js`).then(e=>e.t);return{getAgent:e}},__vite__mapDeps([7,1,5,6])),t=await e(r.agentId);t&&(t.model&&(h.currentModel=t.model),t.temperature!==null&&t.temperature!==void 0&&(h.temperature=t.temperature,h.topP=t.topP!==null&&t.topP!==void 0?t.topP:1),document.dispatchEvent(new CustomEvent(`agent-model-changed`)))}catch{}else{let e=await n;e.modelName&&(h.currentModel=e.modelName),e.temperature!==void 0&&(h.temperature=e.temperature),e.topP!==void 0&&(h.topP=e.topP),document.dispatchEvent(new CustomEvent(`agent-model-changed`))}return r.isGenerating&&h.pendingCallApiSessionIds.has(e)?h.generatingSessionIds.add(e):r.isGenerating&&(i.debug(`[SessionStore] detected expiredperiod isGenerating mark,async cleanup:`,e),(async()=>{try{let t=await g(e);t&&(t.isGenerating=!1,await y(t))}catch(e){i.warn(`[SessionStore] cleanup expired isGenerating mark failed:`,e)}})()),r}async function $(e){let t=await b(),n=await p();try{await it(e)}catch{}if(await c(e),chrome.storage.local.remove(`scrollPosition_`+e),await ot(e),u(e).catch(e=>{i.debug(`[SessionStore] unbind session workdir failed:`,e?.message||e)}),n===e){h.sessionWorkdir=null,h.workdirAgentId=null;try{document.dispatchEvent(new CustomEvent(`session-workdir-changed`))}catch{}}try{let t=(await a()).filter(t=>t.sessionId===e);for(let e of t)await s(e.id);t.length>0&&i.info(`[SessionStore] cleaned ${t.length} bookmark (session ${e} deleted)`)}catch(e){i.warn(`[SessionStore] cleanup bookmarks failed:`,e)}if(n===e){let n=[...t].sort((e,t)=>e.order!==void 0&&t.order!==void 0?e.order-t.order:e.order===void 0?t.order===void 0?new Date(e.createdAt)-new Date(t.createdAt):1:-1),r=n.findIndex(t=>t.id===e),i=n.filter(t=>t.id!==e);i.length>0?await S(i[Math.min(r,i.length-1)].id):await S(null)}return!0}async function ht(e,t,n=null){if(!e)return!1;let r=await g(e);if(!r)return i.warn(`[SessionStore] setSessionWorkdirBinding cannot find session:`,e),!1;r.workdir=t||null,r.workdirAgentId=t&&n||null,r.updatedAt=new Date().toISOString(),h.activeSessionId===e&&(h.sessionWorkdir=r.workdir,h.workdirAgentId=r.workdirAgentId,h.sessionWorkdirOwner=e);let a=await y(r);try{document.dispatchEvent(new CustomEvent(`session-workdir-changed`,{detail:{sessionId:e,workdir:r.workdir,agentId:r.workdirAgentId}}))}catch{}return a}async function gt(e,t){let n=await g(e);return n?(n.title=t,n.titleManuallySet=!0,n.updatedAt=new Date().toISOString(),await y(n),!0):!1}async function _t(e){let t=null;try{t=await v()}catch(e){i.error(`[SessionStore] read session summaries failed, fallback to full read:`,e.message)}if(!t){let t=await b(),n=new Map(t.map(e=>[e.id,e])),r=[];return e.forEach((e,t)=>{let i=n.get(e);i&&i.order!==t&&(i.order=t,r.push(i))}),r.length?_(r):!0}let n=new Map(t.map(e=>[e.id,e.order])),r=new Map(e.map((e,t)=>[e,t])),a=e.filter(e=>n.has(e)?n.get(e)!==r.get(e):!1);if(!a.length)return!0;let o=[];for(let e of a){let t=await g(e);t&&(t.order=r.get(e),o.push(t))}return o.length?_(o):!0}async function vt(){let e=await b(),t=-1;for(let n of e)n.archivedAt||typeof n.order==`number`&&n.order>t&&(t=n.order);return t+1}async function yt(e){if(!e)return!1;let t=await g(e);return t?t.archivedAt?!0:(t.archivedAt=new Date().toISOString(),t.isGenerating=!1,y(t)):!1}async function bt(e){if(!e)return!1;let t=await g(e);return!t||!t.archivedAt?!1:(delete t.archivedAt,t.order=await vt(),y(t))}async function xt(){await G();let e=null;try{e=await v()}catch(e){i.error(`[SessionStore] read session summaries failed, fallback to full read:`,e.message)}return(e??await b()).filter(e=>e.archivedAt).sort((e,t)=>new Date(t.archivedAt||0)-new Date(e.archivedAt||0))}async function St(){if(!h.messageHistory||h.messageHistory.length===0)return;let e=await g(h.activeSessionId);if(!e)return;let t=e.titleManuallySet||e.forkMetadata,n=h.messageHistory.find(e=>e.role===`user`),i=t?e.title||r(`session.unnamedSession`):n?ct(n.content).substring(0,50).replace(/\n/g,` `):e.title||r(`session.unnamedSession`),a=Date.now().toString(36)+Math.random().toString(36).substring(2,8),o=h.messageHistory.map(e=>({role:e.role,content:e.content||``,executionLog:e.executionLog||[],reflectionScore:e.reflectionScore,wasRevised:e.wasRevised||!1,htmlContent:e.htmlContent||void 0})),s=await l();s.push({id:a,title:i,createdAt:new Date().toISOString(),messages:o}),s.length>20&&s.splice(0,s.length-20),await m(s);let c=await X();return await $(e.id),await Q(c.id),!0}async function Ct(e,t=null){await G();let n=await g(e);if(!n)throw Error(r(`session.sourceNotFound`));let i=Z(),a=new Date().toISOString(),o=n.messageHistory||[],s=!1;if(t){let e=o.findIndex(e=>e.messageId===t);e>=0&&(o=o.slice(0,e+1),s=!0)}let c=o.map(e=>({...e,executionLog:Array.isArray(e.executionLog)?[...e.executionLog]:[],contextBubbles:Array.isArray(e.contextBubbles)?[...e.contextBubbles]:void 0,messageId:`msg_`+Date.now().toString(36)+`_`+Math.random().toString(36).substring(2,8)})),l={...n,id:i,title:`${n.title||r(`session.newSession`)} - ${r(`session.forkSuffix`)}`,messageHistory:c,isGenerating:!1,lastExecutionLog:[],scrollPosition:0,createdAt:a,updatedAt:a,order:Date.now(),forkMetadata:{sourceSessionId:e,forkedAt:a,...s?{upToMessageId:t}:{}}};return await y(l),await S(i),l}async function wt(e){await G();let t={id:Z(),title:e.name||r(`session.scheduledSession`),model:e.model||null,useTools:e.useTools==null?null:e.useTools,enabledTools:null,agentId:e.agentId||null,temperature:e.temperature==null?null:e.temperature,topP:e.topP==null?null:e.topP,messageHistory:[],scrollPosition:0,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),order:Date.now(),isGenerating:!1,lastExecutionLog:[],scheduledTaskId:e.id,workdir:e.workdir||null,workdirAgentId:e.workdir&&e.workdirAgentId||null};return await y(t),t}export{Oe as $,rt as A,Se as B,Qe as C,Le as D,Ye as E,O as F,Ae as G,ke as H,be as I,xe as J,ye as K,Ee as L,Pe as M,A as N,Ge as O,ue as P,De as Q,Me as R,Xe as S,qe as T,_e as U,F as V,de as W,P as X,ve as Y,je as Z,ht as _,X as a,oe as at,L as b,q as c,K as d,we as et,ft as f,at as g,J as h,wt as i,C as it,nt as j,ze as k,pt as l,_t as m,St as n,le as nt,$ as o,ne as ot,gt as p,Te as q,yt as r,D as rt,Ct as s,te as st,mt as t,w as tt,xt as u,Q as v,Ze as w,tt as x,bt as y,Ne as z};
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/context-indicator-C9LYk-kV.js","assets/chunk-CMxvf4Kt.js","assets/model-profiles-D3W90Gra.js","assets/i18n-XUUSwfZZ.js","assets/voice-shortcut-Dx863RGz.js","assets/session-store-BCeJFqu-.js","assets/version-CXltTqXK.js","assets/agent-store-grxR4rg1.js","assets/workspace-manager-Cd4F0wEB.js"])))=>i.map(i=>d[i]);
2
- import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-XUUSwfZZ.js";import{A as s,At as c,Bt as l,Ht as u,J as d,Jt as f,L as p,Lt as m,M as h,Nt as g,Ot as ee,P as te,R as ne,U as _,b as v,c as re,ct as y,d as b,gt as x,ht as ie,i as S,it as C,jt as ae,k as oe,q as w,r as se,rt as ce,u as T,wt as le,x as E,y as ue,zt as de}from"./model-profiles-D3W90Gra.js";import{_ as D,d as fe}from"./session-store-BCeJFqu-.js";import{A as pe,C as me,D as he,E as ge,M as _e,N as ve,O as ye,S as be,T as xe,_ as Se,a as Ce,b as we,c as Te,d as Ee,f as De,g as Oe,h as ke,i as Ae,j as je,k as Me,l as Ne,m as Pe,n as O,o as Fe,p as Ie,r as Le,s as Re,t as ze,u as Be,v as Ve,w as He,x as Ue,y as We}from"./todo-model-Dpid8jQT.js";import{$ as Ge,A as k,B as Ke,D as qe,E as Je,G as Ye,J as A,K as Xe,L as Ze,M as Qe,N as $e,O as et,Q as tt,U as nt,V as rt,W as it,X as at,Z as ot,_ as st,et as ct,g as lt,j,k as ut,l as dt,q as ft,t as pt,v as mt,w as ht,y as gt}from"./version-CXltTqXK.js";import{$ as _t,$n as vt,$t as yt,A as bt,An as xt,Ar as St,At as Ct,B as wt,Bn as Tt,Br as Et,Bt as Dt,C as Ot,Cn as kt,Cr as At,Ct as jt,D as Mt,Dn as Nt,Dr as Pt,Dt as Ft,E as It,En as Lt,Er as Rt,Et as zt,F as Bt,Fn as Vt,Fr as Ht,Ft as Ut,G as Wt,Gn as Gt,Gr as Kt,Gt as qt,H as Jt,Hn as Yt,Hr as Xt,Ht as Zt,I as Qt,In as $t,Ir as en,It as tn,J as nn,Jn as rn,Jr as an,Jt as on,K as sn,Kn as cn,Kr as ln,Kt as un,L as dn,Ln as fn,Lr as pn,Lt as mn,M as hn,Mn as gn,Mr as _n,Mt as vn,N as yn,Nn as bn,Nr as xn,Nt as Sn,O as Cn,On as wn,Or as Tn,Ot as En,P as Dn,Pn as On,Pr as kn,Pt as An,Q as jn,Qn as Mn,Qt as Nn,R as Pn,Rn as Fn,Rr as In,Rt as Ln,S as Rn,Sn as zn,St as Bn,T as Vn,Tn as Hn,Tr as Un,Tt as Wn,U as Gn,Un as Kn,Ur as qn,Ut as Jn,Vn as Yn,Vr as Xn,Vt as Zn,W as Qn,Wn as $n,Wr as er,Wt as tr,X as nr,Xn as rr,Xt as ir,Y as ar,Yn as or,Yt as sr,Z as cr,Zn as lr,Zt as ur,_ as dr,_r as fr,_t as pr,a as mr,an as hr,ar as gr,at as _r,b as vr,bn as yr,br,bt as xr,c as Sr,cn as Cr,cr as wr,ct as Tr,d as Er,dn as Dr,dr as Or,dt as kr,en as Ar,er as jr,et as Mr,f as Nr,fn as Pr,fr as Fr,ft as Ir,g as Lr,gn as Rr,gr as zr,gt as Br,h as Vr,hn as Hr,hr as Ur,ht as Wr,i as Gr,in as Kr,ir as qr,it as Jr,j as Yr,jn as Xr,jr as Zr,jt as Qr,k as $r,kn as ei,kr as ti,kt as ni,l as ri,lr as ii,lt as ai,m as oi,mn as si,mr as ci,mt as li,n as ui,nn as di,nr as fi,nt as pi,o as mi,on as hi,or as gi,ot as _i,p as vi,pn as yi,pr as bi,q as xi,qn as Si,qr as Ci,qt as wi,r as Ti,rn as Ei,rt as Di,s as Oi,sn as ki,sr as Ai,st as ji,t as Mi,tn as Ni,tr as Pi,tt as Fi,u as Ii,un as Li,ur as Ri,ut as zi,v as Bi,vn as Vi,vr as Hi,vt as Ui,w as Wi,wn as Gi,wr as Ki,wt as qi,x as Ji,xn as Yi,xr as Xi,xt as Zi,y as Qi,yn as $i,yr as ea,yt as ta,z as na,zn as ra,zr as ia,zt as aa}from"./context-indicator-C9LYk-kV.js";import{o as oa}from"./agent-store-grxR4rg1.js";import{O as sa,b as ca,l as la,p as ua,v as da}from"./workspace-manager-Cd4F0wEB.js";var fa=`panel-observer-`,pa=new Map;function ma(e){if(!e)return null;let t=pa.get(e);if(t)return t;let n;try{n=chrome.runtime.connect({name:`${fa}${e}`})}catch(e){return r.debug(`[PanelObserver] 建立观察端口失败(忽略):`,e?.message||e),null}pa.set(e,n);try{n.onDisconnect.addListener(()=>{pa.get(e)===n&&pa.delete(e)})}catch(e){r.debug(`[PanelObserver] 观察端口断开监听挂不上(忽略):`,e?.message||e)}return n}function ha(e){if(!e)return;let t=pa.get(e);if(t){pa.delete(e);try{t.disconnect()}catch(e){r.debug(`[PanelObserver] 关闭观察端口异常(忽略):`,e?.message||e)}}}function ga({sessionId:e,callId:t,renderer:n,persist:i,onFinished:a=()=>{},emptyFallback:o=``,awaitSnapshot:s=!1}){let c=``,l=!1,u=s,d=[],f=n=>!!n&&n.sessionId===e&&n.callId===t,p=e=>{let t=[];for(let n of e){let e=t[t.length-1];n.type===`STREAM_CHUNK`&&e&&e.type===`STREAM_CHUNK`?t[t.length-1]={...n,delta:(e.delta||``)+(n.delta||``)}:t.push(n)}return t},m=()=>{u=!1;let e=p(d);d=[];for(let t of e)g(t)},h=e=>{l=!0,Promise.resolve().then(()=>i(e)).catch(e=>r.warn(`[ChatReattach] 终态落库失败(忽略):`,e?.message||e)).then(()=>{try{a()}catch{}})};return{sessionId:e,callId:t,get finished(){return l},dispose(){l=!0},restore(e){if(!u)return;u=!1;let r=!!e&&e.callId===t,i=r&&typeof e.accumulated==`string`?e.accumulated:``,a=r&&!!e.html;a&&n.restore?.({html:e.html}),c=i,i&&!a&&n.chunk?.(i);let o=p(d);d=[];for(let e of o)g(e)},handleMessage(e){return l||!f(e)?!1:u?e.type===`STREAM_CHUNK`?(d.push(e),!0):e.type===`API_COMPLETE`||e.type===`API_ERROR`?(m(),g(e)):(d.push(e),!0):g(e)}};function g(r){switch(r.type){case`STREAM_START`:return c=``,n.start?.(),!0;case`STREAM_CHUNK`:return c+=r.delta||``,n.chunk?.(c),!0;case`STREAM_TOOL_CALL`:return n.toolCalls?.(r.toolCalls||[],c),!0;case`STREAM_TOOL_RESULT`:return r.result&&n.toolResult?.(r.result),!0;case`AGENT_STREAM`:return r.execId&&n.agentStream?.(r),!0;case`AGENT_STREAM_DONE`:return r.execId&&n.agentStreamDone?.(r),!0;case`API_RETRYING`:return n.retrying?.(r.attempt,r.maxRetries),!0;case`STREAM_PRESELECT`:return n.preselect?.(r.preselectLog||[]),!0;case`EXECUTION_STATUS_UPDATE`:return!0;case`API_COMPLETE`:{let i=r.content&&String(r.content).trim()?r.content:o||c,a=r.executionLog||[],s={reflectionScore:r.reflectionScore,reasoningContent:r.reasoningContent||null,wasRevised:r.wasRevised||!1,budgetEnded:r.budgetEnded===!0};return n.final?.(i,a,s),h({sessionId:e,callId:t,content:i,executionLog:a,...s}),!0}case`API_ERROR`:return n.error?.(r.error||``,r.executionLog||[]),h({sessionId:e,callId:t,error:r.error||``,executionLog:r.executionLog||[]}),!0;default:return!1}}}function _a({queryRunning:e,hasLocalListener:t,isAttached:n,attach:i}){return{async syncFromBackground(){try{let r=await e(),a=r&&r.activeCallIds?r.activeCallIds:{};for(let[e,r]of Object.entries(a))!e||!r||t(e)||n(e,r)||i(e,r)}catch(e){r.debug(`[ChatReattach] 查询后台运行状态失败(忽略):`,e?.message||e)}}}}var va=!1,ya=new Map,ba=null,xa=!1,Sa=null,Ca=null,wa=null,Ta=250,Ea=new Set([`STREAM_START`,`STREAM_CHUNK`,`STREAM_TOOL_CALL`,`STREAM_TOOL_RESULT`,`AGENT_STREAM`,`AGENT_STREAM_DONE`,`API_RETRYING`,`STREAM_PRESELECT`,`EXECUTION_STATUS_UPDATE`,`API_COMPLETE`,`API_ERROR`]);function Da(e=0){return new Promise((t,n)=>{let r=!1,i=null,a=(e,t)=>{r||(r=!0,i&&clearTimeout(i),e(t))};e>0&&(i=setTimeout(()=>a(t,{}),e));try{chrome.runtime.sendMessage({type:`QUERY_SESSION_RUNNING`},e=>{if(chrome.runtime.lastError){a(n,Error(chrome.runtime.lastError.message));return}a(t,e||{})})}catch(e){a(n,e)}})}function Oa(e,t){let n=new Map;return{start(){zt(e,``),Wn(``),Ft(Date.now()),ji(t),jt(t)},chunk(n){zt(e,n),En(t,n)},restore({html:e}){zi(t,e)},toolCalls(e,n){typeof n==`string`&&n&&Bn(t,n),Tr(t,e)},toolResult(e){ai(e,t)},agentStream(e){Zi(t,n),kr(n,t,e)},agentStreamDone(e){let t=n.get(e.execId);t&&t.element&&e.exitCode!==0&&t.element.classList.add(`agent-stream-error`)},retrying(e,n){Ui(t,e,n)},preselect(e){let n=t.querySelector(`.message-content`);!n||!e.length||e.forEach(e=>n.insertBefore(li(e),n.firstChild))},final(e,n,r={}){pr(t,e,n,r.reflectionScore,r.reasoningContent,r.wasRevised)},error(e,n){pr(t,e,n||[])}}}async function ka(e,t,n){let r=!!e.error,i={role:`assistant`,content:r?e.error:e.content||``,executionLog:e.executionLog||[],reflectionScore:e.reflectionScore,wasRevised:e.wasRevised||!1,callId:e.callId,resumed:!0,resumable:e.budgetEnded?`budget`:!1};if(!r&&n&&(i.messageId=n.dataset.messageId||void 0,i.htmlContent=n.dataset.htmlContent||n.outerHTML),v.activeSessionId===t){v.messageHistory.push(i);try{document.dispatchEvent(new CustomEvent(`session-cache-invalidate`,{detail:{sessionId:t}}))}catch{}}let{appendMessageToSession:a}=await E(async()=>{let{appendMessageToSession:e}=await import(`./context-indicator-C9LYk-kV.js`).then(e=>e.Sr);return{appendMessageToSession:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]));await a(t,i)}function Aa(){E(()=>import(`./context-indicator-C9LYk-kV.js`).then(e=>e.V).then(e=>e.syncPendingSessionsToStorage()),__vite__mapDeps([0,1,2,3,4,5,6,7,8])).catch(e=>r.debug(`[ChatReattach] 同步生成态失败(忽略):`,e?.message||e))}var ja=1e3;function Ma(e){return Promise.race([ni(e),new Promise(e=>setTimeout(()=>e(null),ja))])}function Na(e,n){let i=Wr(e);if(i())return!1;let a=_i(e);a.dataset.callId=n,i(a),zt(e,``),Ft(Date.now()),qi(Date.now()),v.pendingCallApiSessionIds.add(e),v.generatingSessionIds.add(e),Aa();try{document.dispatchEvent(new CustomEvent(`generating-state-changed`))}catch{}let o=ga({sessionId:e,callId:n,awaitSnapshot:!0,renderer:Oa(e,a),persist:t=>ka(t,e,a),emptyFallback:t(`chatMsg.emptyModelReply`),onFinished:()=>{if(ya.get(e)===o){ya.delete(e),ha(e),v.pendingCallApiSessionIds.delete(e),Aa(),Br(e);try{document.dispatchEvent(new CustomEvent(`session-cache-invalidate`,{detail:{sessionId:e}}))}catch{}Si(e)}}});return ya.set(e,o),ma(e),Ma(e).then(t=>{o.finished||ya.get(e)!==o||o.restore(t)}).catch(()=>o.restore(null)),v.activeSessionId===e&&ta(e),r.info(`[ChatReattach] 已接管运行中的任务: sessionId=${e}, callId=${n}`),!0}function Pa(e){let t=ya.get(e);if(!t)return;ya.delete(e),ha(e);try{t.dispose?.()}catch{}let n=Wr(e),r=n();try{r?.remove()}catch{}n(null),Br(e),v.pendingCallApiSessionIds.delete(e),Aa();try{document.dispatchEvent(new CustomEvent(`generating-state-changed`))}catch{}}function Fa(){let e=ba;e&&Promise.resolve().then(()=>e.syncFromBackground()).catch(e=>r.debug(`[ChatReattach] 对齐后台状态失败(忽略):`,e?.message||e))}function Ia(){!va||!ba||wa||(wa=setTimeout(()=>{wa=null,Fa()},Ta))}var La=new Map,Ra=3e3,za=100,Ba=new Set,Va=new Set([`API_COMPLETE`,`API_ERROR`]);function Ha(e,t){let n=`${e}|${t.callId}`;Ba.has(n)||(Ba.add(n),Ba.size>za&&Ba.delete(Ba.values().next().value),Pa(e),Na(e,t.callId)&&ya.get(e)?.handleMessage(t))}function Ua(e,t,n){let r=La.get(e);if(r){r.messages.push(n);return}r={callId:t,messages:[n]},La.set(e,r),Da(Ra).then(t=>Wa(e,t&&t.activeCallIds&&t.activeCallIds[e]||null)).catch(()=>Wa(e,null)).finally(()=>{La.delete(e)})}function Wa(e,t){let n=La.get(e);if(!n)return;let{callId:r,messages:i}=n;if(t===r)Pa(e),Na(e,r);else if(t===null){let t=i.find(e=>Va.has(e.type));if(!t)return;Ha(e,t);return}else return;let a=ya.get(e);if(!(!a||a.callId!==r))for(let e of i){if(a.finished)break;a.handleMessage(e)}}function Ga(){xa||(xa=!0,chrome.runtime.onMessage.addListener(e=>{if(!e)return!1;let t=e.sessionId?ya.get(e.sessionId):null;return t?e.callId&&e.callId!==t.callId?(Ua(e.sessionId,e.callId,e),!1):(ma(e.sessionId),t.handleMessage(e),!1):(e.callId&&Ea.has(e.type)&&Ia(),!1)}),Sa=e=>{let t=e?.detail?.sessionId;t&&ya.has(t)&&ta(t),Ia()},document.addEventListener(`session-hydrated`,Sa),Ca=e=>{let t=e?.detail?.sessionId;t&&ya.has(t)&&ta(t)},document.addEventListener(`chat-history-rendered`,Ca))}function Ka(){return va?{syncFromBackground:()=>ba.syncFromBackground()}:(va=!0,Ga(),ba=_a({queryRunning:Da,hasLocalListener:e=>v.pendingCancelApiMap.has(e),isAttached:(e,t)=>ya.get(e)?.callId===t?(ma(e),!0):!1,attach:(e,t)=>{Na(e,t)}}),ba.syncFromBackground(),{syncFromBackground:()=>ba.syncFromBackground()})}function qa(e){!va||!ba||(e&&v.activeSessionId===e&&ta(e),ba.syncFromBackground())}e(`zh`,{dock:{ariaLabel:`执行中会话`,running:`正在执行`,node:`正在执行:{node}`,subtask:`子任务 {index}/{total}`,queued:`排队 {count} 条`,done:`已完成,点击查看结果`,doneAt:`已完成 {time}`,scheduled:`定时任务`,dismiss:`从停靠条移除`,dismissStale:`移除失效条目`,stale:`状态可能已失效 · 未在限定时间内收到执行更新`,more:`还有 {count} 个`,moreAria:`还有 {count} 个未显示的执行条目`,overflowTitle:`其他执行中的会话`,openSession:`点击进入该会话`,unknownSession:`未知会话`}}),e(`en`,{dock:{ariaLabel:`Running sessions`,running:`Running`,node:`Running: {node}`,subtask:`Subtask {index}/{total}`,queued:`{count} queued`,done:`Finished — click to review`,doneAt:`Finished {time}`,scheduled:`Scheduled task`,dismiss:`Remove from dock`,dismissStale:`Remove stale entry`,stale:`Status may be stale · no execution update in time`,more:`+{count} more`,moreAria:`{count} more running entries not shown`,overflowTitle:`Other active sessions`,openSession:`Click to open this session`,unknownSession:`Unknown session`}});var Ja=`sessionDockDismissed`,Ya=5e3,Xa=250,Za=1200,Qa=8,$a=Qa-1,eo=9e4,to={running:0,queued:1,done:2},no=new Map,ro=new Map,io=new Map,ao=new Map,oo=new Set,so=new Set,co=new Map,lo=new Map,uo=new Set,fo=new Set,po=[],mo=new Set,M=null,N=null,P=null,ho=[],go=!1,_o=null,vo=null,yo=!1,bo=null,xo=null;function So(e){return e?Array.isArray(e)?e:e instanceof Set?Array.from(e):[]:[]}function Co(e){let t=new Set;for(let n of So(e))n&&t.add(h(String(n))||String(n));return t}function wo({phase:e=``,sessionId:t=null,backendRunningIds:n=[],startedAt:r=0,lastUpdateAt:i=0,now:a=Date.now(),staleMs:o=eo}={}){if(e!==`running`||!t||So(n).includes(t))return!1;let s=Math.max(Number(r)||0,Number(i)||0);return s?a-s>=o:!1}var To=160;function Eo(e){let t=String(e??``).replace(/\s+/g,` `).trim();if(!t)return``;let n=Array.from(t);return n.length<=To?t:`${n.slice(0,To).join(``).trimEnd()}…`}function Do(e,t){let n=e=>String(e??``).trim().replace(/[…\s.]+$/,``).replace(/\s+/g,``),r=n(e),i=n(t);return!r||!i?!1:r===i||i.startsWith(r)||r.startsWith(i)}function Oo({phase:e=``,queuedText:t=``,questionText:n=``,title:r=``}={}){let i=e===`queued`?Eo(t):``,a=i||Eo(n),o=Eo(r),s=a||o,c=i?`queued`:a?`question`:s?`title`:``;return{primary:s,sub:a&&!Do(o,a)?o:``,isQuestion:!!a,from:c}}function ko(e){let t=Array.isArray(e?.messageHistory)?e.messageHistory:[];for(let e=t.length-1;e>=0;--e){let n=t[e];if(!n||n.role!==`user`)continue;let r=ae(n.content);if(r&&String(r).trim())return{text:String(r),messageId:n.messageId?String(n.messageId):``}}return{text:``,messageId:``}}function Ao({activeSessionId:e=null,titles:t={},questions:n={},anchors:r={},queuedTexts:i={},generatingIds:a=[],pendingIds:o=[],runningIds:s=[],completedIds:c=[],queuedCounts:l={},scheduledIds:u=[],dismissedIds:d=[],nodeInfo:f={},startedAt:p={},doneAt:m={},lastUpdateAt:h={},now:g=Date.now(),staleMs:ee=eo}={}){let te=So(s),ne=new Set([...So(a),...So(o),...te]),_=new Set(So(c)),v=new Set(So(d)),re=new Set(So(u)),y=l||{},b=new Set([...ne,..._,...Object.keys(y)]),x=[];for(let a of b){if(!a||a===e)continue;let o=Number(y[a])||0,s;if(ne.has(a))s=`running`;else if(o>0)s=`queued`;else if(_.has(a))s=`done`;else continue;let c=wo({phase:s,sessionId:a,backendRunningIds:te,startedAt:p?.[a],lastUpdateAt:h?.[a],now:g,staleMs:ee});if(v.has(a)&&(s===`done`||c))continue;let l=f?.[a]||{},u=Oo({phase:s,queuedText:i?.[a]||``,questionText:n?.[a]||``,title:t?.[a]||``});x.push({sessionId:a,title:t?.[a]||``,primary:u.primary,sub:u.sub,isQuestion:u.isQuestion,anchorMessageId:u.from===`question`?String(r?.[a]||``):``,phase:s,stale:c,source:re.has(a)?`scheduled`:`chat`,queuedCount:o,nodeName:l.nodeName||``,subtaskIndex:l.subtaskIndex||0,subtaskTotal:l.subtaskTotal||0,startedAt:p?.[a]||0,doneAt:m?.[a]||0,lastUpdateAt:h?.[a]||0})}return x.sort((e,t)=>{let n=to[e.phase]-to[t.phase];if(n!==0)return n;if(e.stale!==t.stale)return e.stale?1:-1;let r=e.phase===`done`?e.doneAt:e.startedAt,i=t.phase===`done`?t.doneAt:t.startedAt;return r===i?String(e.sessionId).localeCompare(String(t.sessionId)):i-r}),x}function jo(e){return fo.has(e)||v.generatingSessionIds.has(e)||v.pendingCallApiSessionIds.has(e)}function Mo(){let e={};try{let t=Zr();for(let n of t){let t=Tn(n);t>0&&(e[n]=t)}}catch(e){r.debug(`[SessionDock] read queue counts failed:`,e?.message||e)}return e}function No(){let e={};for(let t of v.sessions||[])e[t.id]=t.title||``;for(let[t,n]of co)e[t]||(e[t]=n);return e}function Po(){let e={},t={},n=new Map;for(let e of v.sessions||[])n.set(e.id,e);for(let r of new Set([...fo,...v.generatingSessionIds,...v.pendingCallApiSessionIds,...v.completedSessionIds])){let i=ro.get(r)||io.get(r)||0,a=lo.get(r);if(i&&a&&a.stamp===i){a.text&&(e[r]=a.text,t[r]=a.messageId||``);continue}let o=ko(n.get(r));o.text&&(e[r]=o.text,t[r]=o.messageId)}return{questions:e,anchors:t}}function Fo(){let e={};try{for(let t of Zr()){let n=_n(t);n?.text&&(e[t]=String(n.text))}}catch(e){r.debug(`[SessionDock] read queued texts failed:`,e?.message||e)}return e}function Io(e){for(let t of e||[]){let e=t.sessionId;if(!e)continue;let n=t.startedAt||t.doneAt||0,i=lo.get(e),a=!i||i.stamp!==n,o=!t.title;!a&&!o||uo.has(e)||(uo.add(e),y(e).then(t=>{if(t&&((o||!co.has(e))&&co.set(e,t.title||``),a)){let r=ko(t);lo.set(e,{text:r.text,messageId:r.messageId,stamp:n})}}).catch(e=>{r.debug(`[SessionDock] hydrate label failed:`,e?.message||e)}).finally(()=>{uo.delete(e),F()}))}}function Lo(e){if(!e)return``;let t=new Date(e);return`${String(t.getHours()).padStart(2,`0`)}:${String(t.getMinutes()).padStart(2,`0`)}`}function Ro(e){if(e.phase===`running`){if(e.stale)return t(`dock.stale`);let n=e.nodeName?t(`dock.node`,{node:e.nodeName}):t(`dock.running`);return e.subtaskTotal>1?`${n} · ${t(`dock.subtask`,{index:e.subtaskIndex,total:e.subtaskTotal})}`:n}return e.phase===`queued`?t(`dock.queued`,{count:e.queuedCount}):e.doneAt?t(`dock.doneAt`,{time:Lo(e.doneAt)}):t(`dock.done`)}function zo(){let e=v.completedSessionIds;for(let e of new Set([...fo,...v.generatingSessionIds,...v.pendingCallApiSessionIds]))ro.has(e)||ro.set(e,Date.now()),io.delete(e);for(let e of fo)so.delete(e);for(let t of e)!io.has(t)&&!jo(t)&&io.set(t,Date.now());let{questions:t,anchors:n}=Po(),r=Ao({activeSessionId:v.activeSessionId,titles:No(),questions:t,anchors:n,queuedTexts:Fo(),generatingIds:v.generatingSessionIds,pendingIds:v.pendingCallApiSessionIds,runningIds:fo,completedIds:e,queuedCounts:Mo(),scheduledIds:oo,dismissedIds:so,nodeInfo:Object.fromEntries(no),startedAt:Object.fromEntries(ro),doneAt:Object.fromEntries(io),lastUpdateAt:Object.fromEntries(ao),now:Date.now()});return Io(r),r}function Bo(e){let t=new Set(po.filter(e=>e.phase===`done`).map(e=>e.sessionId)),n=e.filter(e=>e.phase===`done`&&!t.has(e.sessionId)).map(e=>e.sessionId);n.length!==0&&(mo=new Set(n),bo&&clearTimeout(bo),bo=setTimeout(()=>{bo=null,mo=new Set,F()},Za))}function Vo(){if(M||typeof document>`u`)return M;M=document.createElement(`div`),M.className=`session-dock`,M.id=`sessionDock`,M.setAttribute(`role`,`navigation`),document.body.appendChild(M),N=document.createElement(`div`),N.className=`session-dock-tip`,document.body.appendChild(N),Ho();let e=document.getElementById(`chatContainer`);return e&&typeof ResizeObserver<`u`&&new ResizeObserver(Ho).observe(e),window.addEventListener(`resize`,Ho),M}function Ho(){if(!M)return;let e=document.getElementById(`chatContainer`);if(!e)return;let t=e.getBoundingClientRect();M.style.top=`${Math.max(0,Math.round(t.top+8))}px`}function Uo(e){Pi(e.sessionId,{focusMessageId:e.anchorMessageId||null})}function Wo(e){let n=document.createElement(`div`);n.className=`session-dock-item`,n.dataset.sessionId=e.sessionId,n.dataset.phase=e.phase,e.stale&&(n.dataset.stale=`true`),mo.has(e.sessionId)&&n.classList.add(`is-flash`);let r=e.title||t(`dock.unknownSession`),i=e.primary||r,a=Ro(e),o=e.phase===`done`?`✓`:Array.from(r)[0]||`?`,s=document.createElement(`button`);if(s.type=`button`,s.className=`session-dock-chip`,s.setAttribute(`aria-label`,`${i} · ${a}`),s.title=``,s.textContent=o,s.addEventListener(`click`,()=>{Uo(e)}),n.appendChild(s),e.queuedCount>0&&e.phase!==`done`){let t=document.createElement(`span`);t.className=`session-dock-badge`,t.textContent=String(e.queuedCount>99?`99+`:e.queuedCount),n.appendChild(t)}if(e.source===`scheduled`){let e=document.createElement(`span`);e.className=`session-dock-clock`,n.appendChild(e)}if(e.phase===`done`||e.stale){let r=document.createElement(`button`);r.type=`button`,r.className=`session-dock-dismiss`;let i=e.stale?t(`dock.dismissStale`):t(`dock.dismiss`);r.setAttribute(`aria-label`,i),r.title=i,r.textContent=`×`,r.addEventListener(`click`,t=>{t.stopPropagation(),rs(e.sessionId)}),n.appendChild(r)}return n.addEventListener(`mouseenter`,()=>Go(n,e,a)),n.addEventListener(`mouseleave`,Ko),n.addEventListener(`focusin`,()=>Go(n,e,a)),n.addEventListener(`focusout`,Ko),n}function Go(e,n,r){if(!N)return;N.innerHTML=``;let i=document.createElement(`div`);i.className=`session-dock-tip-title`,i.textContent=n.primary||n.title||t(`dock.unknownSession`);let a=document.createElement(`div`);if(a.className=`session-dock-tip-status`,a.textContent=r,N.appendChild(i),n.sub){let e=document.createElement(`div`);e.className=`session-dock-tip-sub`,e.textContent=n.sub,N.appendChild(e)}N.appendChild(a);let o=e.getBoundingClientRect();N.style.top=`${Math.round(o.top)}px`,N.style.left=`${Math.round(o.right+8)}px`,N.classList.add(`show`)}function Ko(){N&&N.classList.remove(`show`)}function qo(){return P||typeof document>`u`?P:(P=document.createElement(`div`),P.className=`session-dock-overflow`,P.setAttribute(`role`,`menu`),P.addEventListener(`mouseenter`,Jo),P.addEventListener(`mouseleave`,Yo),P.addEventListener(`focusin`,Jo),P.addEventListener(`focusout`,Yo),document.body.appendChild(P),P)}function Jo(){xo&&=(clearTimeout(xo),null)}function Yo(){go||(Jo(),xo=setTimeout(()=>{xo=null,es()},220))}function Xo(){let e=M?M.querySelector(`.session-dock-more`):null;e&&(e.setAttribute(`aria-expanded`,go?`true`:`false`),e.classList.toggle(`is-open`,go))}function Zo(){let e=qo();if(!e)return;e.innerHTML=``;let n=document.createElement(`div`);n.className=`session-dock-overflow-header`,n.textContent=t(`dock.overflowTitle`),e.appendChild(n);let r=document.createElement(`div`);r.className=`session-dock-overflow-list`;for(let e of ho){let n=e.primary||e.title||t(`dock.unknownSession`),i=Ro(e),a=document.createElement(`button`);a.type=`button`,a.className=`session-dock-overflow-row`,a.dataset.phase=e.phase,e.stale&&(a.dataset.stale=`true`),a.setAttribute(`aria-label`,`${n} · ${i}`);let o=document.createElement(`span`);o.className=`session-dock-overflow-title`,o.textContent=n;let s=document.createElement(`span`);s.className=`session-dock-overflow-status`,s.textContent=i,a.appendChild(o),a.appendChild(s),a.addEventListener(`click`,()=>{es(),Uo(e)}),r.appendChild(a)}e.appendChild(r)}function Qo(){if(!P||!M)return;let e=M.querySelector(`.session-dock-item--more`);if(!e)return;let t=e.getBoundingClientRect();P.style.left=`${Math.round(t.right+8)}px`;let n=P.offsetHeight||0,r=Math.max(8,window.innerHeight-n-8);P.style.top=`${Math.round(Math.min(Math.max(8,t.top),r))}px`}function $o(){ho.length!==0&&qo()&&(Jo(),Zo(),Qo(),P.classList.add(`show`),Xo())}function es(){Jo(),go=!1,P&&P.classList.remove(`show`),Xo()}function ts(){if(P&&P.classList.contains(`show`)&&go){es();return}$o(),go=!0,Xo()}function ns(e){let n=document.createElement(`div`);n.className=`session-dock-item session-dock-item--more`,n.dataset.count=String(e.length);let r=document.createElement(`button`);return r.type=`button`,r.className=`session-dock-chip session-dock-more`,r.setAttribute(`aria-label`,t(`dock.moreAria`,{count:e.length})),r.setAttribute(`aria-expanded`,go?`true`:`false`),r.textContent=`+${e.length>99?`99`:e.length}`,r.addEventListener(`click`,()=>ts()),n.appendChild(r),n.addEventListener(`mouseenter`,()=>$o()),n.addEventListener(`mouseleave`,Yo),n.addEventListener(`focusin`,()=>$o()),n.addEventListener(`focusout`,Yo),n}function rs(e){e&&(so.add(e),is(),F())}function is(){try{chrome.storage.local.set({[Ja]:Array.from(so)}).catch(()=>{})}catch{}}function as(){try{chrome.storage.local.get([Ja],e=>{let t=e?.[Ja];if(Array.isArray(t)){for(let e of t)so.add(e);F()}})}catch{}}function os(){if(!Vo())return;let e=zo();if(Bo(e),po=e,es(),ho=[],M.innerHTML=``,e.length===0){M.classList.remove(`show`),document.body.classList.remove(`has-session-dock`),Ko();return}let t=e.length>Qa?$a:Qa;ho=e.slice(t);for(let n of e.slice(0,t))M.appendChild(Wo(n));ho.length>0&&M.appendChild(ns(ho)),M.classList.add(`show`),document.body.classList.add(`has-session-dock`)}function F(){_o||=setTimeout(()=>{_o=null;try{os()}catch(e){r.warn(`[SessionDock] render failed:`,e?.message||e)}},Xa)}function ss(){return new Promise(e=>{try{chrome.runtime.sendMessage({type:`QUERY_SESSION_RUNNING`},t=>{if(chrome.runtime.lastError||!t){e();return}Array.isArray(t.activeSessionIds)&&(fo=Co(t.activeSessionIds)),e()})}catch{e()}})}function cs(e){let t=e?.sessionId;if(!t)return;let n=no.get(t)||{};no.set(t,{nodeName:e.nodeName||n.nodeName||``,subtaskIndex:e.subtaskIndex||n.subtaskIndex||0,subtaskTotal:e.subtaskTotal||n.subtaskTotal||0}),ao.set(t,Date.now()),F()}function ls(e){e&&(no.delete(e),ro.delete(e),io.delete(e),ao.delete(e),so.delete(e),co.delete(e),lo.delete(e),F())}function us(){if(!(yo||typeof document>`u`||!Vo())){yo=!0,as(),document.addEventListener(`generating-state-changed`,F),document.addEventListener(`session-switched`,F),document.addEventListener(`generation-ended`,e=>{let t=e?.detail?.sessionId;t&&!io.has(t)&&io.set(t,Date.now()),F()}),document.addEventListener(`session-archived`,e=>ls(e?.detail?.sessionId)),document.addEventListener(`session-deleted`,e=>ls(e?.detail?.sessionId));try{In(F)}catch(e){r.debug(`[SessionDock] subscribe queue failed:`,e?.message||e)}try{chrome.runtime.onMessage.addListener(e=>e?e.type===`EXECUTION_STATUS_UPDATE`?(cs(e),!1):e.type===`SCHEDULED_TASK_RUN_STATE`&&e.sessionId?(e.running?oo.add(e.sessionId):oo.delete(e.sessionId),F(),!1):(e.type===`SCHEDULED_SESSION_UPDATED`&&F(),!1):!1)}catch(e){r.debug(`[SessionDock] register runtime listener failed:`,e?.message||e)}document.addEventListener(`visibilitychange`,()=>{if(document.hidden){es();return}ss().then(F)}),document.addEventListener(`keydown`,e=>{e.key===`Escape`&&go&&es()}),vo||=setInterval(()=>{document.hidden||ss().then(F)},Ya),ss().then(()=>{for(let e of fo)ro.has(e)||ro.set(e,Date.now());os()})}}function ds(){let e=document.getElementById(`chatNavUp`),n=document.getElementById(`chatNavDown`),r=document.getElementById(`chatNavHotzone`),i=document.getElementById(`chatNavButtons`),a=document.getElementById(`chatNavQuestionPanel`),o=[],s=!1,c=null,l=``,u=!1,d=!1;function f(e){let t=document.getElementById(`chatContainer`);if(!t)return-1;let n=t.getBoundingClientRect();return $e(e,n.top,n.bottom)}function p(e,t){let n=document.getElementById(`chatContainer`);if(!n)return`noop`;let r=Je(n);if(r.length===0)return`noop`;let i=n.getBoundingClientRect().top;if(t){if(e===`prev`)r[0].start.scrollIntoView({behavior:`smooth`,block:`start`});else{let e=r[r.length-1].elements;e[e.length-1].scrollIntoView({behavior:`smooth`,block:`end`})}return`jumped`}let a=ft(r.length,Qe(r,i),e);return a===null?(m(e),`blocked`):(r[a].start.scrollIntoView({behavior:`smooth`,block:`start`}),`jumped`)}function m(t){let r=t===`prev`?e:n;r&&(r.classList.remove(`blocked`),r.offsetWidth,r.classList.add(`blocked`),r.addEventListener(`animationend`,()=>r.classList.remove(`blocked`),{once:!0}))}function h(e,n){let r=a.querySelectorAll(`.chat-nav-question-item`);r.forEach(t=>{Number(t.dataset.groupIndex)===e?(t.classList.add(`current`),t.setAttribute(`aria-current`,`true`)):(t.classList.remove(`current`),t.setAttribute(`aria-current`,`false`))});let i=a.querySelector(`.chat-nav-question-header .count`);i&&(i.textContent=t(`chat.navPosition`,{current:e>=0?e+1:n,total:n}));let o=Array.from(r).find(t=>Number(t.dataset.groupIndex)===e);!d&&e>=0&&o&&o.scrollIntoView({block:`nearest`})}function g(){if(!a||!a.classList.contains(`expanded`))return;o=Je(document.getElementById(`chatContainer`));let e=l?Je(document.getElementById(`chatContainer`)).length:a.querySelectorAll(`.chat-nav-question-item`).length;if(o.length===0){a.innerHTML=``,a.classList.remove(`expanded`);return}if(!l&&e!==o.length){ee();return}h(f(o),o.length)}function ee(){if(!a)return!1;if(o=Je(document.getElementById(`chatContainer`)),o.length===0)return a.innerHTML=``,!1;let e=f(o),t=document.activeElement===a.querySelector(`[data-role="nav-search"]`);a.innerHTML=Xe(o,e,s,l),a.querySelector(`.chat-nav-pin`).addEventListener(`click`,e=>{e.stopPropagation(),b()});let n=a.querySelector(`[data-role="nav-search"]`);if(n){let e=()=>{l!==n.value&&(l=n.value,ee())};n.addEventListener(`input`,t=>{t.isComposing||e()}),n.addEventListener(`compositionend`,e),t&&(n.focus(),n.setSelectionRange(n.value.length,n.value.length))}if(e>=0){let t=a.querySelector(`.chat-nav-question-item[data-group-index="${e}"]`);t&&t.scrollIntoView({block:`nearest`})}return!0}function te(){let e=document.activeElement;return e?[r,i,a].some(t=>t&&(t===e||t.contains(e))):!1}function ne(){i.classList.remove(`expanded`),a&&a.classList.remove(`expanded`)}function _(){let e=te();ne(),e&&r&&(u=!0,r.focus({preventScroll:!0}),u=!1)}function v(){if(clearTimeout(c),i.classList.add(`expanded`),a){if(a.classList.contains(`expanded`)){g();return}ee()?a.classList.add(`expanded`):a.classList.remove(`expanded`)}}function re(e){clearTimeout(c),!s&&(te()||(e?ne():c=setTimeout(ne,300)))}function y(e){if(s=e,r&&(r.classList.toggle(`pinned`,e),r.setAttribute(`aria-pressed`,String(e))),a){a.classList.toggle(`pinned`,e);let n=a.querySelector(`.chat-nav-pin`);if(n){let r=t(e?`chat.navUnpinLabel`:`chat.navPinLabel`);n.textContent=r,n.title=r,n.setAttribute(`aria-pressed`,String(e)),n.classList.toggle(`on`,e)}}}function b(){y(!s)}e&&e.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),p(`prev`,e.ctrlKey||e.metaKey),g()}),n&&n.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),p(`next`,e.ctrlKey||e.metaKey),g()}),r&&i&&(r.addEventListener(`mouseenter`,v),r.addEventListener(`mouseleave`,()=>re(!1)),r.addEventListener(`click`,()=>b()),r.addEventListener(`focus`,()=>{u||v()}),r.addEventListener(`blur`,()=>re(!1)),r.addEventListener(`keydown`,e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),b())}),i.addEventListener(`mouseenter`,v),i.addEventListener(`mouseleave`,()=>re(!1)),i.addEventListener(`focusin`,v),a&&(a.addEventListener(`mouseenter`,()=>{d=!0,v()}),a.addEventListener(`mouseleave`,()=>{d=!1,re(!1)}),a.addEventListener(`focusin`,v),a.addEventListener(`keydown`,e=>{if(e.target.matches(`[data-role="nav-search"]`))return;let t=Array.from(a.querySelectorAll(`.chat-nav-question-item`));if(t.length===0)return;let n=t.indexOf(document.activeElement),r=null;e.key===`ArrowDown`?r=Math.min(n+1,t.length-1):e.key===`ArrowUp`?r=n<=0?0:n-1:e.key===`Home`?r=0:e.key===`End`&&(r=t.length-1),r!==null&&(e.preventDefault(),t[r].focus())}),a.addEventListener(`click`,e=>{let t=e.target.closest(`.chat-nav-question-item`);if(!t||!t.dataset.messageId)return;let n=o.find(e=>(e.userElement||e.start).dataset.messageId===t.dataset.messageId);if(!n)return;let r=n.userElement||n.start;r.scrollIntoView({behavior:`instant`,block:`start`}),r.classList.add(`bookmark-highlight`),setTimeout(()=>r.classList.remove(`bookmark-highlight`),2e3),s?g():_()})));{let e=document.getElementById(`chatContainer`);if(e){let t=!1;e.addEventListener(`scroll`,()=>{!a||!a.classList.contains(`expanded`)||t||(t=!0,requestAnimationFrame(()=>{t=!1,g()}))},{passive:!0})}}function x(){let e=a&&a.classList.contains(`expanded`);if(!s&&!e)return!1;if(a&&a.querySelector(`[data-role="nav-search"]`)&&l){l=``,ee();let e=a.querySelector(`[data-role="nav-search"]`);return e&&e.focus(),!0}return y(!1),_(),!0}return{jumpToMessage:p,updateActiveQuestion:g,handleEscape:x,isPinned:()=>s}}function fs(e){if(!e)return!1;let t=e.nodeType===Node.TEXT_NODE?e.parentElement:e;return!!(t&&t.closest&&t.closest(`#chatContainer, .message-fullscreen-body`))}e(`zh`,{searchPanel:{toggleTitle:`消息搜索`,title:`消息搜索`,closeTitle:`关闭`,inputPlaceholder:`搜索消息(支持 & | 组合搜索)...`,clearTitle:`清除`,globalSearchTitle:`在所有会话中搜索`,globalSearch:`全局搜索`,currentSessionTitle:`仅在当前会话中搜索`,currentSession:`当前会话`,startSearchHint:`输入关键词开始搜索`,searching:`搜索中...`,searchingWithCount:`搜索中... {count} 条`,searchError:`搜索出错`,noActiveSession:`没有活跃会话`,noSessionData:`没有会话数据`,noMatch:`未找到匹配消息`,unknownSession:`未知会话`,countResult:`{count} 条`,noResult:`无结果`,searchingSuffix:` (搜索中...)`,currentSessionResults:`当前会话{label} · {count} 条`,otherSessionsResults:`其他会话 · {count} 条`,roleUser:`你`,roleAssistant:`助手`,sessionNotExist:`会话已不存在`,messageDeleted:`消息已被删除`}}),e(`en`,{searchPanel:{toggleTitle:`Search messages`,title:`Message search`,closeTitle:`Close`,inputPlaceholder:`Search messages (supports & | combined search)...`,clearTitle:`Clear`,globalSearchTitle:`Search in all sessions`,globalSearch:`Global search`,currentSessionTitle:`Search in current session only`,currentSession:`Current session`,startSearchHint:`Enter keywords to start searching`,searching:`Searching...`,searchingWithCount:`Searching... {count} found`,searchError:`Search error`,noActiveSession:`No active session`,noSessionData:`No session data`,noMatch:`No matching messages found`,unknownSession:`Unknown session`,countResult:`{count} found`,noResult:`No results`,searchingSuffix:` (searching...)`,currentSessionResults:`Current session{label} · {count} found`,otherSessionsResults:`Other sessions · {count} found`,roleUser:`You`,roleAssistant:`Assistant`,sessionNotExist:`Session no longer exists`,messageDeleted:`Message has been deleted`}});var ps=!1,ms=!1,I=[],hs=``;function gs(){v.searchInputHistory=[],v.searchInputHistoryIndex=-1;try{chrome.storage.local.get([`searchInputHistory`],e=>{e.searchInputHistory&&(v.searchInputHistory=e.searchInputHistory)})}catch{}let e=document.createElement(`div`);e.className=`search-panel-container`,e.id=`searchPanelContainer`,e.innerHTML=`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/context-indicator-u4eOUhKC.js","assets/chunk-CMxvf4Kt.js","assets/model-profiles-D3W90Gra.js","assets/i18n-XUUSwfZZ.js","assets/voice-shortcut-Dx863RGz.js","assets/session-store-Dc1xZXYw.js","assets/version-C3ji0PWC.js","assets/agent-store-grxR4rg1.js","assets/workspace-manager-Cd4F0wEB.js"])))=>i.map(i=>d[i]);
2
+ import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-XUUSwfZZ.js";import{A as s,At as c,Bt as l,Ht as u,J as d,Jt as f,L as p,Lt as m,M as h,Nt as g,Ot as ee,P as te,R as ne,U as _,b as v,c as re,ct as y,d as b,gt as x,ht as ie,i as S,it as C,jt as ae,k as oe,q as w,r as se,rt as ce,u as T,wt as le,x as E,y as ue,zt as de}from"./model-profiles-D3W90Gra.js";import{_ as D,d as fe}from"./session-store-Dc1xZXYw.js";import{A as pe,C as me,D as he,E as ge,M as _e,N as ve,O as ye,S as be,T as xe,_ as Se,a as Ce,b as we,c as Te,d as Ee,f as De,g as Oe,h as ke,i as Ae,j as je,k as Me,l as Ne,m as Pe,n as O,o as Fe,p as Ie,r as Le,s as Re,t as ze,u as Be,v as Ve,w as He,x as Ue,y as We}from"./todo-model-Dpid8jQT.js";import{$ as Ge,A as k,B as Ke,D as qe,E as Je,G as Ye,J as A,K as Xe,L as Ze,M as Qe,N as $e,O as et,Q as tt,U as nt,V as rt,W as it,X as at,Z as ot,_ as st,et as ct,g as lt,j,k as ut,l as dt,q as ft,t as pt,v as mt,w as ht,y as gt}from"./version-C3ji0PWC.js";import{$ as _t,$n as vt,$t as yt,A as bt,An as xt,Ar as St,At as Ct,B as wt,Bn as Tt,Br as Et,Bt as Dt,C as Ot,Cn as kt,Cr as At,Ct as jt,D as Mt,Dn as Nt,Dr as Pt,Dt as Ft,E as It,En as Lt,Er as Rt,Et as zt,F as Bt,Fn as Vt,Fr as Ht,Ft as Ut,G as Wt,Gn as Gt,Gr as Kt,Gt as qt,H as Jt,Hn as Yt,Hr as Xt,Ht as Zt,I as Qt,In as $t,Ir as en,It as tn,J as nn,Jn as rn,Jr as an,Jt as on,K as sn,Kn as cn,Kr as ln,Kt as un,L as dn,Ln as fn,Lr as pn,Lt as mn,M as hn,Mn as gn,Mr as _n,Mt as vn,N as yn,Nn as bn,Nr as xn,Nt as Sn,O as Cn,On as wn,Or as Tn,Ot as En,P as Dn,Pn as On,Pr as kn,Pt as An,Q as jn,Qn as Mn,Qt as Nn,R as Pn,Rn as Fn,Rr as In,Rt as Ln,S as Rn,Sn as zn,St as Bn,T as Vn,Tn as Hn,Tr as Un,Tt as Wn,U as Gn,Un as Kn,Ur as qn,Ut as Jn,Vn as Yn,Vr as Xn,Vt as Zn,W as Qn,Wn as $n,Wr as er,Wt as tr,X as nr,Xn as rr,Xt as ir,Y as ar,Yn as or,Yt as sr,Z as cr,Zn as lr,Zt as ur,_ as dr,_r as fr,_t as pr,a as mr,an as hr,ar as gr,at as _r,b as vr,bn as yr,br,bt as xr,c as Sr,cn as Cr,cr as wr,ct as Tr,d as Er,dn as Dr,dr as Or,dt as kr,en as Ar,er as jr,et as Mr,f as Nr,fn as Pr,fr as Fr,ft as Ir,g as Lr,gn as Rr,gr as zr,gt as Br,h as Vr,hn as Hr,hr as Ur,ht as Wr,i as Gr,in as Kr,ir as qr,it as Jr,j as Yr,jn as Xr,jr as Zr,jt as Qr,k as $r,kn as ei,kr as ti,kt as ni,l as ri,lr as ii,lt as ai,m as oi,mn as si,mr as ci,mt as li,n as ui,nn as di,nr as fi,nt as pi,o as mi,on as hi,or as gi,ot as _i,p as vi,pn as yi,pr as bi,q as xi,qn as Si,qr as Ci,qt as wi,r as Ti,rn as Ei,rt as Di,s as Oi,sn as ki,sr as Ai,st as ji,t as Mi,tn as Ni,tr as Pi,tt as Fi,u as Ii,un as Li,ur as Ri,ut as zi,v as Bi,vn as Vi,vr as Hi,vt as Ui,w as Wi,wn as Gi,wr as Ki,wt as qi,x as Ji,xn as Yi,xr as Xi,xt as Zi,y as Qi,yn as $i,yr as ea,yt as ta,z as na,zn as ra,zr as ia,zt as aa}from"./context-indicator-u4eOUhKC.js";import{o as oa}from"./agent-store-grxR4rg1.js";import{O as sa,b as ca,l as la,p as ua,v as da}from"./workspace-manager-Cd4F0wEB.js";var fa=`panel-observer-`,pa=new Map;function ma(e){if(!e)return null;let t=pa.get(e);if(t)return t;let n;try{n=chrome.runtime.connect({name:`${fa}${e}`})}catch(e){return r.debug(`[PanelObserver] 建立观察端口失败(忽略):`,e?.message||e),null}pa.set(e,n);try{n.onDisconnect.addListener(()=>{pa.get(e)===n&&pa.delete(e)})}catch(e){r.debug(`[PanelObserver] 观察端口断开监听挂不上(忽略):`,e?.message||e)}return n}function ha(e){if(!e)return;let t=pa.get(e);if(t){pa.delete(e);try{t.disconnect()}catch(e){r.debug(`[PanelObserver] 关闭观察端口异常(忽略):`,e?.message||e)}}}function ga({sessionId:e,callId:t,renderer:n,persist:i,onFinished:a=()=>{},emptyFallback:o=``,awaitSnapshot:s=!1}){let c=``,l=!1,u=s,d=[],f=n=>!!n&&n.sessionId===e&&n.callId===t,p=e=>{let t=[];for(let n of e){let e=t[t.length-1];n.type===`STREAM_CHUNK`&&e&&e.type===`STREAM_CHUNK`?t[t.length-1]={...n,delta:(e.delta||``)+(n.delta||``)}:t.push(n)}return t},m=()=>{u=!1;let e=p(d);d=[];for(let t of e)g(t)},h=e=>{l=!0,Promise.resolve().then(()=>i(e)).catch(e=>r.warn(`[ChatReattach] 终态落库失败(忽略):`,e?.message||e)).then(()=>{try{a()}catch{}})};return{sessionId:e,callId:t,get finished(){return l},dispose(){l=!0},restore(e){if(!u)return;u=!1;let r=!!e&&e.callId===t,i=r&&typeof e.accumulated==`string`?e.accumulated:``,a=r&&!!e.html;a&&n.restore?.({html:e.html}),c=i,i&&!a&&n.chunk?.(i);let o=p(d);d=[];for(let e of o)g(e)},handleMessage(e){return l||!f(e)?!1:u?e.type===`STREAM_CHUNK`?(d.push(e),!0):e.type===`API_COMPLETE`||e.type===`API_ERROR`?(m(),g(e)):(d.push(e),!0):g(e)}};function g(r){switch(r.type){case`STREAM_START`:return c=``,n.start?.(),!0;case`STREAM_CHUNK`:return c+=r.delta||``,n.chunk?.(c),!0;case`STREAM_TOOL_CALL`:return n.toolCalls?.(r.toolCalls||[],c),!0;case`STREAM_TOOL_RESULT`:return r.result&&n.toolResult?.(r.result),!0;case`AGENT_STREAM`:return r.execId&&n.agentStream?.(r),!0;case`AGENT_STREAM_DONE`:return r.execId&&n.agentStreamDone?.(r),!0;case`API_RETRYING`:return n.retrying?.(r.attempt,r.maxRetries),!0;case`STREAM_PRESELECT`:return n.preselect?.(r.preselectLog||[]),!0;case`EXECUTION_STATUS_UPDATE`:return!0;case`API_COMPLETE`:{let i=r.content&&String(r.content).trim()?r.content:o||c,a=r.executionLog||[],s={reflectionScore:r.reflectionScore,reasoningContent:r.reasoningContent||null,wasRevised:r.wasRevised||!1,budgetEnded:r.budgetEnded===!0};return n.final?.(i,a,s),h({sessionId:e,callId:t,content:i,executionLog:a,...s}),!0}case`API_ERROR`:return n.error?.(r.error||``,r.executionLog||[]),h({sessionId:e,callId:t,error:r.error||``,executionLog:r.executionLog||[]}),!0;default:return!1}}}function _a({queryRunning:e,hasLocalListener:t,isAttached:n,attach:i}){return{async syncFromBackground(){try{let r=await e(),a=r&&r.activeCallIds?r.activeCallIds:{};for(let[e,r]of Object.entries(a))!e||!r||t(e)||n(e,r)||i(e,r)}catch(e){r.debug(`[ChatReattach] 查询后台运行状态失败(忽略):`,e?.message||e)}}}}var va=!1,ya=new Map,ba=null,xa=!1,Sa=null,Ca=null,wa=null,Ta=250,Ea=new Set([`STREAM_START`,`STREAM_CHUNK`,`STREAM_TOOL_CALL`,`STREAM_TOOL_RESULT`,`AGENT_STREAM`,`AGENT_STREAM_DONE`,`API_RETRYING`,`STREAM_PRESELECT`,`EXECUTION_STATUS_UPDATE`,`API_COMPLETE`,`API_ERROR`]);function Da(e=0){return new Promise((t,n)=>{let r=!1,i=null,a=(e,t)=>{r||(r=!0,i&&clearTimeout(i),e(t))};e>0&&(i=setTimeout(()=>a(t,{}),e));try{chrome.runtime.sendMessage({type:`QUERY_SESSION_RUNNING`},e=>{if(chrome.runtime.lastError){a(n,Error(chrome.runtime.lastError.message));return}a(t,e||{})})}catch(e){a(n,e)}})}function Oa(e,t){let n=new Map;return{start(){zt(e,``),Wn(``),Ft(Date.now()),ji(t),jt(t)},chunk(n){zt(e,n),En(t,n)},restore({html:e}){zi(t,e)},toolCalls(e,n){typeof n==`string`&&n&&Bn(t,n),Tr(t,e)},toolResult(e){ai(e,t)},agentStream(e){Zi(t,n),kr(n,t,e)},agentStreamDone(e){let t=n.get(e.execId);t&&t.element&&e.exitCode!==0&&t.element.classList.add(`agent-stream-error`)},retrying(e,n){Ui(t,e,n)},preselect(e){let n=t.querySelector(`.message-content`);!n||!e.length||e.forEach(e=>n.insertBefore(li(e),n.firstChild))},final(e,n,r={}){pr(t,e,n,r.reflectionScore,r.reasoningContent,r.wasRevised)},error(e,n){pr(t,e,n||[])}}}async function ka(e,t,n){let r=!!e.error,i={role:`assistant`,content:r?e.error:e.content||``,executionLog:e.executionLog||[],reflectionScore:e.reflectionScore,wasRevised:e.wasRevised||!1,callId:e.callId,resumed:!0,resumable:e.budgetEnded?`budget`:!1};if(!r&&n&&(i.messageId=n.dataset.messageId||void 0,i.htmlContent=n.dataset.htmlContent||n.outerHTML),v.activeSessionId===t){v.messageHistory.push(i);try{document.dispatchEvent(new CustomEvent(`session-cache-invalidate`,{detail:{sessionId:t}}))}catch{}}let{appendMessageToSession:a}=await E(async()=>{let{appendMessageToSession:e}=await import(`./context-indicator-u4eOUhKC.js`).then(e=>e.Sr);return{appendMessageToSession:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]));await a(t,i)}function Aa(){E(()=>import(`./context-indicator-u4eOUhKC.js`).then(e=>e.V).then(e=>e.syncPendingSessionsToStorage()),__vite__mapDeps([0,1,2,3,4,5,6,7,8])).catch(e=>r.debug(`[ChatReattach] 同步生成态失败(忽略):`,e?.message||e))}var ja=1e3;function Ma(e){return Promise.race([ni(e),new Promise(e=>setTimeout(()=>e(null),ja))])}function Na(e,n){let i=Wr(e);if(i())return!1;let a=_i(e);a.dataset.callId=n,i(a),zt(e,``),Ft(Date.now()),qi(Date.now()),v.pendingCallApiSessionIds.add(e),v.generatingSessionIds.add(e),Aa();try{document.dispatchEvent(new CustomEvent(`generating-state-changed`))}catch{}let o=ga({sessionId:e,callId:n,awaitSnapshot:!0,renderer:Oa(e,a),persist:t=>ka(t,e,a),emptyFallback:t(`chatMsg.emptyModelReply`),onFinished:()=>{if(ya.get(e)===o){ya.delete(e),ha(e),v.pendingCallApiSessionIds.delete(e),Aa(),Br(e);try{document.dispatchEvent(new CustomEvent(`session-cache-invalidate`,{detail:{sessionId:e}}))}catch{}Si(e)}}});return ya.set(e,o),ma(e),Ma(e).then(t=>{o.finished||ya.get(e)!==o||o.restore(t)}).catch(()=>o.restore(null)),v.activeSessionId===e&&ta(e),r.info(`[ChatReattach] 已接管运行中的任务: sessionId=${e}, callId=${n}`),!0}function Pa(e){let t=ya.get(e);if(!t)return;ya.delete(e),ha(e);try{t.dispose?.()}catch{}let n=Wr(e),r=n();try{r?.remove()}catch{}n(null),Br(e),v.pendingCallApiSessionIds.delete(e),Aa();try{document.dispatchEvent(new CustomEvent(`generating-state-changed`))}catch{}}function Fa(){let e=ba;e&&Promise.resolve().then(()=>e.syncFromBackground()).catch(e=>r.debug(`[ChatReattach] 对齐后台状态失败(忽略):`,e?.message||e))}function Ia(){!va||!ba||wa||(wa=setTimeout(()=>{wa=null,Fa()},Ta))}var La=new Map,Ra=3e3,za=100,Ba=new Set,Va=new Set([`API_COMPLETE`,`API_ERROR`]);function Ha(e,t){let n=`${e}|${t.callId}`;Ba.has(n)||(Ba.add(n),Ba.size>za&&Ba.delete(Ba.values().next().value),Pa(e),Na(e,t.callId)&&ya.get(e)?.handleMessage(t))}function Ua(e,t,n){let r=La.get(e);if(r){r.messages.push(n);return}r={callId:t,messages:[n]},La.set(e,r),Da(Ra).then(t=>Wa(e,t&&t.activeCallIds&&t.activeCallIds[e]||null)).catch(()=>Wa(e,null)).finally(()=>{La.delete(e)})}function Wa(e,t){let n=La.get(e);if(!n)return;let{callId:r,messages:i}=n;if(t===r)Pa(e),Na(e,r);else if(t===null){let t=i.find(e=>Va.has(e.type));if(!t)return;Ha(e,t);return}else return;let a=ya.get(e);if(!(!a||a.callId!==r))for(let e of i){if(a.finished)break;a.handleMessage(e)}}function Ga(){xa||(xa=!0,chrome.runtime.onMessage.addListener(e=>{if(!e)return!1;let t=e.sessionId?ya.get(e.sessionId):null;return t?e.callId&&e.callId!==t.callId?(Ua(e.sessionId,e.callId,e),!1):(ma(e.sessionId),t.handleMessage(e),!1):(e.callId&&Ea.has(e.type)&&Ia(),!1)}),Sa=e=>{let t=e?.detail?.sessionId;t&&ya.has(t)&&ta(t),Ia()},document.addEventListener(`session-hydrated`,Sa),Ca=e=>{let t=e?.detail?.sessionId;t&&ya.has(t)&&ta(t)},document.addEventListener(`chat-history-rendered`,Ca))}function Ka(){return va?{syncFromBackground:()=>ba.syncFromBackground()}:(va=!0,Ga(),ba=_a({queryRunning:Da,hasLocalListener:e=>v.pendingCancelApiMap.has(e),isAttached:(e,t)=>ya.get(e)?.callId===t?(ma(e),!0):!1,attach:(e,t)=>{Na(e,t)}}),ba.syncFromBackground(),{syncFromBackground:()=>ba.syncFromBackground()})}function qa(e){!va||!ba||(e&&v.activeSessionId===e&&ta(e),ba.syncFromBackground())}e(`zh`,{dock:{ariaLabel:`执行中会话`,running:`正在执行`,node:`正在执行:{node}`,subtask:`子任务 {index}/{total}`,queued:`排队 {count} 条`,done:`已完成,点击查看结果`,doneAt:`已完成 {time}`,scheduled:`定时任务`,dismiss:`从停靠条移除`,dismissStale:`移除失效条目`,stale:`状态可能已失效 · 未在限定时间内收到执行更新`,more:`还有 {count} 个`,moreAria:`还有 {count} 个未显示的执行条目`,overflowTitle:`其他执行中的会话`,openSession:`点击进入该会话`,unknownSession:`未知会话`}}),e(`en`,{dock:{ariaLabel:`Running sessions`,running:`Running`,node:`Running: {node}`,subtask:`Subtask {index}/{total}`,queued:`{count} queued`,done:`Finished — click to review`,doneAt:`Finished {time}`,scheduled:`Scheduled task`,dismiss:`Remove from dock`,dismissStale:`Remove stale entry`,stale:`Status may be stale · no execution update in time`,more:`+{count} more`,moreAria:`{count} more running entries not shown`,overflowTitle:`Other active sessions`,openSession:`Click to open this session`,unknownSession:`Unknown session`}});var Ja=`sessionDockDismissed`,Ya=5e3,Xa=250,Za=1200,Qa=8,$a=Qa-1,eo=9e4,to={running:0,queued:1,done:2},no=new Map,ro=new Map,io=new Map,ao=new Map,oo=new Set,so=new Set,co=new Map,lo=new Map,uo=new Set,fo=new Set,po=[],mo=new Set,M=null,N=null,P=null,ho=[],go=!1,_o=null,vo=null,yo=!1,bo=null,xo=null;function So(e){return e?Array.isArray(e)?e:e instanceof Set?Array.from(e):[]:[]}function Co(e){let t=new Set;for(let n of So(e))n&&t.add(h(String(n))||String(n));return t}function wo({phase:e=``,sessionId:t=null,backendRunningIds:n=[],startedAt:r=0,lastUpdateAt:i=0,now:a=Date.now(),staleMs:o=eo}={}){if(e!==`running`||!t||So(n).includes(t))return!1;let s=Math.max(Number(r)||0,Number(i)||0);return s?a-s>=o:!1}var To=160;function Eo(e){let t=String(e??``).replace(/\s+/g,` `).trim();if(!t)return``;let n=Array.from(t);return n.length<=To?t:`${n.slice(0,To).join(``).trimEnd()}…`}function Do(e,t){let n=e=>String(e??``).trim().replace(/[…\s.]+$/,``).replace(/\s+/g,``),r=n(e),i=n(t);return!r||!i?!1:r===i||i.startsWith(r)||r.startsWith(i)}function Oo({phase:e=``,queuedText:t=``,questionText:n=``,title:r=``}={}){let i=e===`queued`?Eo(t):``,a=i||Eo(n),o=Eo(r),s=a||o,c=i?`queued`:a?`question`:s?`title`:``;return{primary:s,sub:a&&!Do(o,a)?o:``,isQuestion:!!a,from:c}}function ko(e){let t=Array.isArray(e?.messageHistory)?e.messageHistory:[];for(let e=t.length-1;e>=0;--e){let n=t[e];if(!n||n.role!==`user`)continue;let r=ae(n.content);if(r&&String(r).trim())return{text:String(r),messageId:n.messageId?String(n.messageId):``}}return{text:``,messageId:``}}function Ao({activeSessionId:e=null,titles:t={},questions:n={},anchors:r={},queuedTexts:i={},generatingIds:a=[],pendingIds:o=[],runningIds:s=[],completedIds:c=[],queuedCounts:l={},scheduledIds:u=[],dismissedIds:d=[],nodeInfo:f={},startedAt:p={},doneAt:m={},lastUpdateAt:h={},now:g=Date.now(),staleMs:ee=eo}={}){let te=So(s),ne=new Set([...So(a),...So(o),...te]),_=new Set(So(c)),v=new Set(So(d)),re=new Set(So(u)),y=l||{},b=new Set([...ne,..._,...Object.keys(y)]),x=[];for(let a of b){if(!a||a===e)continue;let o=Number(y[a])||0,s;if(ne.has(a))s=`running`;else if(o>0)s=`queued`;else if(_.has(a))s=`done`;else continue;let c=wo({phase:s,sessionId:a,backendRunningIds:te,startedAt:p?.[a],lastUpdateAt:h?.[a],now:g,staleMs:ee});if(v.has(a)&&(s===`done`||c))continue;let l=f?.[a]||{},u=Oo({phase:s,queuedText:i?.[a]||``,questionText:n?.[a]||``,title:t?.[a]||``});x.push({sessionId:a,title:t?.[a]||``,primary:u.primary,sub:u.sub,isQuestion:u.isQuestion,anchorMessageId:u.from===`question`?String(r?.[a]||``):``,phase:s,stale:c,source:re.has(a)?`scheduled`:`chat`,queuedCount:o,nodeName:l.nodeName||``,subtaskIndex:l.subtaskIndex||0,subtaskTotal:l.subtaskTotal||0,startedAt:p?.[a]||0,doneAt:m?.[a]||0,lastUpdateAt:h?.[a]||0})}return x.sort((e,t)=>{let n=to[e.phase]-to[t.phase];if(n!==0)return n;if(e.stale!==t.stale)return e.stale?1:-1;let r=e.phase===`done`?e.doneAt:e.startedAt,i=t.phase===`done`?t.doneAt:t.startedAt;return r===i?String(e.sessionId).localeCompare(String(t.sessionId)):i-r}),x}function jo(e){return fo.has(e)||v.generatingSessionIds.has(e)||v.pendingCallApiSessionIds.has(e)}function Mo(){let e={};try{let t=Zr();for(let n of t){let t=Tn(n);t>0&&(e[n]=t)}}catch(e){r.debug(`[SessionDock] read queue counts failed:`,e?.message||e)}return e}function No(){let e={};for(let t of v.sessions||[])e[t.id]=t.title||``;for(let[t,n]of co)e[t]||(e[t]=n);return e}function Po(){let e={},t={},n=new Map;for(let e of v.sessions||[])n.set(e.id,e);for(let r of new Set([...fo,...v.generatingSessionIds,...v.pendingCallApiSessionIds,...v.completedSessionIds])){let i=ro.get(r)||io.get(r)||0,a=lo.get(r);if(i&&a&&a.stamp===i){a.text&&(e[r]=a.text,t[r]=a.messageId||``);continue}let o=ko(n.get(r));o.text&&(e[r]=o.text,t[r]=o.messageId)}return{questions:e,anchors:t}}function Fo(){let e={};try{for(let t of Zr()){let n=_n(t);n?.text&&(e[t]=String(n.text))}}catch(e){r.debug(`[SessionDock] read queued texts failed:`,e?.message||e)}return e}function Io(e){for(let t of e||[]){let e=t.sessionId;if(!e)continue;let n=t.startedAt||t.doneAt||0,i=lo.get(e),a=!i||i.stamp!==n,o=!t.title;!a&&!o||uo.has(e)||(uo.add(e),y(e).then(t=>{if(t&&((o||!co.has(e))&&co.set(e,t.title||``),a)){let r=ko(t);lo.set(e,{text:r.text,messageId:r.messageId,stamp:n})}}).catch(e=>{r.debug(`[SessionDock] hydrate label failed:`,e?.message||e)}).finally(()=>{uo.delete(e),F()}))}}function Lo(e){if(!e)return``;let t=new Date(e);return`${String(t.getHours()).padStart(2,`0`)}:${String(t.getMinutes()).padStart(2,`0`)}`}function Ro(e){if(e.phase===`running`){if(e.stale)return t(`dock.stale`);let n=e.nodeName?t(`dock.node`,{node:e.nodeName}):t(`dock.running`);return e.subtaskTotal>1?`${n} · ${t(`dock.subtask`,{index:e.subtaskIndex,total:e.subtaskTotal})}`:n}return e.phase===`queued`?t(`dock.queued`,{count:e.queuedCount}):e.doneAt?t(`dock.doneAt`,{time:Lo(e.doneAt)}):t(`dock.done`)}function zo(){let e=v.completedSessionIds;for(let e of new Set([...fo,...v.generatingSessionIds,...v.pendingCallApiSessionIds]))ro.has(e)||ro.set(e,Date.now()),io.delete(e);for(let e of fo)so.delete(e);for(let t of e)!io.has(t)&&!jo(t)&&io.set(t,Date.now());let{questions:t,anchors:n}=Po(),r=Ao({activeSessionId:v.activeSessionId,titles:No(),questions:t,anchors:n,queuedTexts:Fo(),generatingIds:v.generatingSessionIds,pendingIds:v.pendingCallApiSessionIds,runningIds:fo,completedIds:e,queuedCounts:Mo(),scheduledIds:oo,dismissedIds:so,nodeInfo:Object.fromEntries(no),startedAt:Object.fromEntries(ro),doneAt:Object.fromEntries(io),lastUpdateAt:Object.fromEntries(ao),now:Date.now()});return Io(r),r}function Bo(e){let t=new Set(po.filter(e=>e.phase===`done`).map(e=>e.sessionId)),n=e.filter(e=>e.phase===`done`&&!t.has(e.sessionId)).map(e=>e.sessionId);n.length!==0&&(mo=new Set(n),bo&&clearTimeout(bo),bo=setTimeout(()=>{bo=null,mo=new Set,F()},Za))}function Vo(){if(M||typeof document>`u`)return M;M=document.createElement(`div`),M.className=`session-dock`,M.id=`sessionDock`,M.setAttribute(`role`,`navigation`),document.body.appendChild(M),N=document.createElement(`div`),N.className=`session-dock-tip`,document.body.appendChild(N),Ho();let e=document.getElementById(`chatContainer`);return e&&typeof ResizeObserver<`u`&&new ResizeObserver(Ho).observe(e),window.addEventListener(`resize`,Ho),M}function Ho(){if(!M)return;let e=document.getElementById(`chatContainer`);if(!e)return;let t=e.getBoundingClientRect();M.style.top=`${Math.max(0,Math.round(t.top+8))}px`}function Uo(e){Pi(e.sessionId,{focusMessageId:e.anchorMessageId||null})}function Wo(e){let n=document.createElement(`div`);n.className=`session-dock-item`,n.dataset.sessionId=e.sessionId,n.dataset.phase=e.phase,e.stale&&(n.dataset.stale=`true`),mo.has(e.sessionId)&&n.classList.add(`is-flash`);let r=e.title||t(`dock.unknownSession`),i=e.primary||r,a=Ro(e),o=e.phase===`done`?`✓`:Array.from(r)[0]||`?`,s=document.createElement(`button`);if(s.type=`button`,s.className=`session-dock-chip`,s.setAttribute(`aria-label`,`${i} · ${a}`),s.title=``,s.textContent=o,s.addEventListener(`click`,()=>{Uo(e)}),n.appendChild(s),e.queuedCount>0&&e.phase!==`done`){let t=document.createElement(`span`);t.className=`session-dock-badge`,t.textContent=String(e.queuedCount>99?`99+`:e.queuedCount),n.appendChild(t)}if(e.source===`scheduled`){let e=document.createElement(`span`);e.className=`session-dock-clock`,n.appendChild(e)}if(e.phase===`done`||e.stale){let r=document.createElement(`button`);r.type=`button`,r.className=`session-dock-dismiss`;let i=e.stale?t(`dock.dismissStale`):t(`dock.dismiss`);r.setAttribute(`aria-label`,i),r.title=i,r.textContent=`×`,r.addEventListener(`click`,t=>{t.stopPropagation(),rs(e.sessionId)}),n.appendChild(r)}return n.addEventListener(`mouseenter`,()=>Go(n,e,a)),n.addEventListener(`mouseleave`,Ko),n.addEventListener(`focusin`,()=>Go(n,e,a)),n.addEventListener(`focusout`,Ko),n}function Go(e,n,r){if(!N)return;N.innerHTML=``;let i=document.createElement(`div`);i.className=`session-dock-tip-title`,i.textContent=n.primary||n.title||t(`dock.unknownSession`);let a=document.createElement(`div`);if(a.className=`session-dock-tip-status`,a.textContent=r,N.appendChild(i),n.sub){let e=document.createElement(`div`);e.className=`session-dock-tip-sub`,e.textContent=n.sub,N.appendChild(e)}N.appendChild(a);let o=e.getBoundingClientRect();N.style.top=`${Math.round(o.top)}px`,N.style.left=`${Math.round(o.right+8)}px`,N.classList.add(`show`)}function Ko(){N&&N.classList.remove(`show`)}function qo(){return P||typeof document>`u`?P:(P=document.createElement(`div`),P.className=`session-dock-overflow`,P.setAttribute(`role`,`menu`),P.addEventListener(`mouseenter`,Jo),P.addEventListener(`mouseleave`,Yo),P.addEventListener(`focusin`,Jo),P.addEventListener(`focusout`,Yo),document.body.appendChild(P),P)}function Jo(){xo&&=(clearTimeout(xo),null)}function Yo(){go||(Jo(),xo=setTimeout(()=>{xo=null,es()},220))}function Xo(){let e=M?M.querySelector(`.session-dock-more`):null;e&&(e.setAttribute(`aria-expanded`,go?`true`:`false`),e.classList.toggle(`is-open`,go))}function Zo(){let e=qo();if(!e)return;e.innerHTML=``;let n=document.createElement(`div`);n.className=`session-dock-overflow-header`,n.textContent=t(`dock.overflowTitle`),e.appendChild(n);let r=document.createElement(`div`);r.className=`session-dock-overflow-list`;for(let e of ho){let n=e.primary||e.title||t(`dock.unknownSession`),i=Ro(e),a=document.createElement(`button`);a.type=`button`,a.className=`session-dock-overflow-row`,a.dataset.phase=e.phase,e.stale&&(a.dataset.stale=`true`),a.setAttribute(`aria-label`,`${n} · ${i}`);let o=document.createElement(`span`);o.className=`session-dock-overflow-title`,o.textContent=n;let s=document.createElement(`span`);s.className=`session-dock-overflow-status`,s.textContent=i,a.appendChild(o),a.appendChild(s),a.addEventListener(`click`,()=>{es(),Uo(e)}),r.appendChild(a)}e.appendChild(r)}function Qo(){if(!P||!M)return;let e=M.querySelector(`.session-dock-item--more`);if(!e)return;let t=e.getBoundingClientRect();P.style.left=`${Math.round(t.right+8)}px`;let n=P.offsetHeight||0,r=Math.max(8,window.innerHeight-n-8);P.style.top=`${Math.round(Math.min(Math.max(8,t.top),r))}px`}function $o(){ho.length!==0&&qo()&&(Jo(),Zo(),Qo(),P.classList.add(`show`),Xo())}function es(){Jo(),go=!1,P&&P.classList.remove(`show`),Xo()}function ts(){if(P&&P.classList.contains(`show`)&&go){es();return}$o(),go=!0,Xo()}function ns(e){let n=document.createElement(`div`);n.className=`session-dock-item session-dock-item--more`,n.dataset.count=String(e.length);let r=document.createElement(`button`);return r.type=`button`,r.className=`session-dock-chip session-dock-more`,r.setAttribute(`aria-label`,t(`dock.moreAria`,{count:e.length})),r.setAttribute(`aria-expanded`,go?`true`:`false`),r.textContent=`+${e.length>99?`99`:e.length}`,r.addEventListener(`click`,()=>ts()),n.appendChild(r),n.addEventListener(`mouseenter`,()=>$o()),n.addEventListener(`mouseleave`,Yo),n.addEventListener(`focusin`,()=>$o()),n.addEventListener(`focusout`,Yo),n}function rs(e){e&&(so.add(e),is(),F())}function is(){try{chrome.storage.local.set({[Ja]:Array.from(so)}).catch(()=>{})}catch{}}function as(){try{chrome.storage.local.get([Ja],e=>{let t=e?.[Ja];if(Array.isArray(t)){for(let e of t)so.add(e);F()}})}catch{}}function os(){if(!Vo())return;let e=zo();if(Bo(e),po=e,es(),ho=[],M.innerHTML=``,e.length===0){M.classList.remove(`show`),document.body.classList.remove(`has-session-dock`),Ko();return}let t=e.length>Qa?$a:Qa;ho=e.slice(t);for(let n of e.slice(0,t))M.appendChild(Wo(n));ho.length>0&&M.appendChild(ns(ho)),M.classList.add(`show`),document.body.classList.add(`has-session-dock`)}function F(){_o||=setTimeout(()=>{_o=null;try{os()}catch(e){r.warn(`[SessionDock] render failed:`,e?.message||e)}},Xa)}function ss(){return new Promise(e=>{try{chrome.runtime.sendMessage({type:`QUERY_SESSION_RUNNING`},t=>{if(chrome.runtime.lastError||!t){e();return}Array.isArray(t.activeSessionIds)&&(fo=Co(t.activeSessionIds)),e()})}catch{e()}})}function cs(e){let t=e?.sessionId;if(!t)return;let n=no.get(t)||{};no.set(t,{nodeName:e.nodeName||n.nodeName||``,subtaskIndex:e.subtaskIndex||n.subtaskIndex||0,subtaskTotal:e.subtaskTotal||n.subtaskTotal||0}),ao.set(t,Date.now()),F()}function ls(e){e&&(no.delete(e),ro.delete(e),io.delete(e),ao.delete(e),so.delete(e),co.delete(e),lo.delete(e),F())}function us(){if(!(yo||typeof document>`u`||!Vo())){yo=!0,as(),document.addEventListener(`generating-state-changed`,F),document.addEventListener(`session-switched`,F),document.addEventListener(`generation-ended`,e=>{let t=e?.detail?.sessionId;t&&!io.has(t)&&io.set(t,Date.now()),F()}),document.addEventListener(`session-archived`,e=>ls(e?.detail?.sessionId)),document.addEventListener(`session-deleted`,e=>ls(e?.detail?.sessionId));try{In(F)}catch(e){r.debug(`[SessionDock] subscribe queue failed:`,e?.message||e)}try{chrome.runtime.onMessage.addListener(e=>e?e.type===`EXECUTION_STATUS_UPDATE`?(cs(e),!1):e.type===`SCHEDULED_TASK_RUN_STATE`&&e.sessionId?(e.running?oo.add(e.sessionId):oo.delete(e.sessionId),F(),!1):(e.type===`SCHEDULED_SESSION_UPDATED`&&F(),!1):!1)}catch(e){r.debug(`[SessionDock] register runtime listener failed:`,e?.message||e)}document.addEventListener(`visibilitychange`,()=>{if(document.hidden){es();return}ss().then(F)}),document.addEventListener(`keydown`,e=>{e.key===`Escape`&&go&&es()}),vo||=setInterval(()=>{document.hidden||ss().then(F)},Ya),ss().then(()=>{for(let e of fo)ro.has(e)||ro.set(e,Date.now());os()})}}function ds(){let e=document.getElementById(`chatNavUp`),n=document.getElementById(`chatNavDown`),r=document.getElementById(`chatNavHotzone`),i=document.getElementById(`chatNavButtons`),a=document.getElementById(`chatNavQuestionPanel`),o=[],s=!1,c=null,l=``,u=!1,d=!1;function f(e){let t=document.getElementById(`chatContainer`);if(!t)return-1;let n=t.getBoundingClientRect();return $e(e,n.top,n.bottom)}function p(e,t){let n=document.getElementById(`chatContainer`);if(!n)return`noop`;let r=Je(n);if(r.length===0)return`noop`;let i=n.getBoundingClientRect().top;if(t){if(e===`prev`)r[0].start.scrollIntoView({behavior:`smooth`,block:`start`});else{let e=r[r.length-1].elements;e[e.length-1].scrollIntoView({behavior:`smooth`,block:`end`})}return`jumped`}let a=ft(r.length,Qe(r,i),e);return a===null?(m(e),`blocked`):(r[a].start.scrollIntoView({behavior:`smooth`,block:`start`}),`jumped`)}function m(t){let r=t===`prev`?e:n;r&&(r.classList.remove(`blocked`),r.offsetWidth,r.classList.add(`blocked`),r.addEventListener(`animationend`,()=>r.classList.remove(`blocked`),{once:!0}))}function h(e,n){let r=a.querySelectorAll(`.chat-nav-question-item`);r.forEach(t=>{Number(t.dataset.groupIndex)===e?(t.classList.add(`current`),t.setAttribute(`aria-current`,`true`)):(t.classList.remove(`current`),t.setAttribute(`aria-current`,`false`))});let i=a.querySelector(`.chat-nav-question-header .count`);i&&(i.textContent=t(`chat.navPosition`,{current:e>=0?e+1:n,total:n}));let o=Array.from(r).find(t=>Number(t.dataset.groupIndex)===e);!d&&e>=0&&o&&o.scrollIntoView({block:`nearest`})}function g(){if(!a||!a.classList.contains(`expanded`))return;o=Je(document.getElementById(`chatContainer`));let e=l?Je(document.getElementById(`chatContainer`)).length:a.querySelectorAll(`.chat-nav-question-item`).length;if(o.length===0){a.innerHTML=``,a.classList.remove(`expanded`);return}if(!l&&e!==o.length){ee();return}h(f(o),o.length)}function ee(){if(!a)return!1;if(o=Je(document.getElementById(`chatContainer`)),o.length===0)return a.innerHTML=``,!1;let e=f(o),t=document.activeElement===a.querySelector(`[data-role="nav-search"]`);a.innerHTML=Xe(o,e,s,l),a.querySelector(`.chat-nav-pin`).addEventListener(`click`,e=>{e.stopPropagation(),b()});let n=a.querySelector(`[data-role="nav-search"]`);if(n){let e=()=>{l!==n.value&&(l=n.value,ee())};n.addEventListener(`input`,t=>{t.isComposing||e()}),n.addEventListener(`compositionend`,e),t&&(n.focus(),n.setSelectionRange(n.value.length,n.value.length))}if(e>=0){let t=a.querySelector(`.chat-nav-question-item[data-group-index="${e}"]`);t&&t.scrollIntoView({block:`nearest`})}return!0}function te(){let e=document.activeElement;return e?[r,i,a].some(t=>t&&(t===e||t.contains(e))):!1}function ne(){i.classList.remove(`expanded`),a&&a.classList.remove(`expanded`)}function _(){let e=te();ne(),e&&r&&(u=!0,r.focus({preventScroll:!0}),u=!1)}function v(){if(clearTimeout(c),i.classList.add(`expanded`),a){if(a.classList.contains(`expanded`)){g();return}ee()?a.classList.add(`expanded`):a.classList.remove(`expanded`)}}function re(e){clearTimeout(c),!s&&(te()||(e?ne():c=setTimeout(ne,300)))}function y(e){if(s=e,r&&(r.classList.toggle(`pinned`,e),r.setAttribute(`aria-pressed`,String(e))),a){a.classList.toggle(`pinned`,e);let n=a.querySelector(`.chat-nav-pin`);if(n){let r=t(e?`chat.navUnpinLabel`:`chat.navPinLabel`);n.textContent=r,n.title=r,n.setAttribute(`aria-pressed`,String(e)),n.classList.toggle(`on`,e)}}}function b(){y(!s)}e&&e.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),p(`prev`,e.ctrlKey||e.metaKey),g()}),n&&n.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),p(`next`,e.ctrlKey||e.metaKey),g()}),r&&i&&(r.addEventListener(`mouseenter`,v),r.addEventListener(`mouseleave`,()=>re(!1)),r.addEventListener(`click`,()=>b()),r.addEventListener(`focus`,()=>{u||v()}),r.addEventListener(`blur`,()=>re(!1)),r.addEventListener(`keydown`,e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),b())}),i.addEventListener(`mouseenter`,v),i.addEventListener(`mouseleave`,()=>re(!1)),i.addEventListener(`focusin`,v),a&&(a.addEventListener(`mouseenter`,()=>{d=!0,v()}),a.addEventListener(`mouseleave`,()=>{d=!1,re(!1)}),a.addEventListener(`focusin`,v),a.addEventListener(`keydown`,e=>{if(e.target.matches(`[data-role="nav-search"]`))return;let t=Array.from(a.querySelectorAll(`.chat-nav-question-item`));if(t.length===0)return;let n=t.indexOf(document.activeElement),r=null;e.key===`ArrowDown`?r=Math.min(n+1,t.length-1):e.key===`ArrowUp`?r=n<=0?0:n-1:e.key===`Home`?r=0:e.key===`End`&&(r=t.length-1),r!==null&&(e.preventDefault(),t[r].focus())}),a.addEventListener(`click`,e=>{let t=e.target.closest(`.chat-nav-question-item`);if(!t||!t.dataset.messageId)return;let n=o.find(e=>(e.userElement||e.start).dataset.messageId===t.dataset.messageId);if(!n)return;let r=n.userElement||n.start;r.scrollIntoView({behavior:`instant`,block:`start`}),r.classList.add(`bookmark-highlight`),setTimeout(()=>r.classList.remove(`bookmark-highlight`),2e3),s?g():_()})));{let e=document.getElementById(`chatContainer`);if(e){let t=!1;e.addEventListener(`scroll`,()=>{!a||!a.classList.contains(`expanded`)||t||(t=!0,requestAnimationFrame(()=>{t=!1,g()}))},{passive:!0})}}function x(){let e=a&&a.classList.contains(`expanded`);if(!s&&!e)return!1;if(a&&a.querySelector(`[data-role="nav-search"]`)&&l){l=``,ee();let e=a.querySelector(`[data-role="nav-search"]`);return e&&e.focus(),!0}return y(!1),_(),!0}return{jumpToMessage:p,updateActiveQuestion:g,handleEscape:x,isPinned:()=>s}}function fs(e){if(!e)return!1;let t=e.nodeType===Node.TEXT_NODE?e.parentElement:e;return!!(t&&t.closest&&t.closest(`#chatContainer, .message-fullscreen-body`))}e(`zh`,{searchPanel:{toggleTitle:`消息搜索`,title:`消息搜索`,closeTitle:`关闭`,inputPlaceholder:`搜索消息(支持 & | 组合搜索)...`,clearTitle:`清除`,globalSearchTitle:`在所有会话中搜索`,globalSearch:`全局搜索`,currentSessionTitle:`仅在当前会话中搜索`,currentSession:`当前会话`,startSearchHint:`输入关键词开始搜索`,searching:`搜索中...`,searchingWithCount:`搜索中... {count} 条`,searchError:`搜索出错`,noActiveSession:`没有活跃会话`,noSessionData:`没有会话数据`,noMatch:`未找到匹配消息`,unknownSession:`未知会话`,countResult:`{count} 条`,noResult:`无结果`,searchingSuffix:` (搜索中...)`,currentSessionResults:`当前会话{label} · {count} 条`,otherSessionsResults:`其他会话 · {count} 条`,roleUser:`你`,roleAssistant:`助手`,sessionNotExist:`会话已不存在`,messageDeleted:`消息已被删除`}}),e(`en`,{searchPanel:{toggleTitle:`Search messages`,title:`Message search`,closeTitle:`Close`,inputPlaceholder:`Search messages (supports & | combined search)...`,clearTitle:`Clear`,globalSearchTitle:`Search in all sessions`,globalSearch:`Global search`,currentSessionTitle:`Search in current session only`,currentSession:`Current session`,startSearchHint:`Enter keywords to start searching`,searching:`Searching...`,searchingWithCount:`Searching... {count} found`,searchError:`Search error`,noActiveSession:`No active session`,noSessionData:`No session data`,noMatch:`No matching messages found`,unknownSession:`Unknown session`,countResult:`{count} found`,noResult:`No results`,searchingSuffix:` (searching...)`,currentSessionResults:`Current session{label} · {count} found`,otherSessionsResults:`Other sessions · {count} found`,roleUser:`You`,roleAssistant:`Assistant`,sessionNotExist:`Session no longer exists`,messageDeleted:`Message has been deleted`}});var ps=!1,ms=!1,I=[],hs=``;function gs(){v.searchInputHistory=[],v.searchInputHistoryIndex=-1;try{chrome.storage.local.get([`searchInputHistory`],e=>{e.searchInputHistory&&(v.searchInputHistory=e.searchInputHistory)})}catch{}let e=document.createElement(`div`);e.className=`search-panel-container`,e.id=`searchPanelContainer`,e.innerHTML=`
3
3
  <button class="search-panel-toggle" id="searchPanelToggle" title="${t(`searchPanel.toggleTitle`)}">
4
4
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
5
5
  <circle cx="11" cy="11" r="8"/>
@@ -48,7 +48,7 @@ import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-XUUSwfZZ.js"
48
48
  </div>
49
49
  <div class="search-result-preview">${c}</div>
50
50
  </div>
51
- `}).join(``)}function Os(e,t){if(!t)return e;let n=t.split(/[&|]/).map(e=>e.trim()).filter(Boolean);if(n.length===0)return e;let r=n.map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)),i=RegExp(`(${r.join(`|`)})`,`gi`);return e.replace(i,`<mark class="search-highlight-match">$1</mark>`)}async function ks(e,n){if(!(!e||!n)){if(v.activeSessionId!==e)try{let n=v.activeSessionId;if(await At(e)===!1||v.activeSessionId!==e){A(t(`searchPanel.sessionNotExist`),`warning`);return}document.dispatchEvent(new CustomEvent(`session-switched`,{detail:{sessionId:e,previousSessionId:n,skipScrollRestore:!0}}));try{let{renderSessionTabs:e}=await E(async()=>{let{renderSessionTabs:e}=await import(`./context-indicator-C9LYk-kV.js`).then(e=>e.rr);return{renderSessionTabs:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]));e()}catch(e){r.warn(`[SearchPanel] refreshsessionTab failed:`,e)}}catch(e){r.error(`[SearchPanel] switchsession failed:`,e);return}setTimeout(async()=>{let i=document.getElementById(`chatContainer`);if(!i){r.warn(`[SearchPanel] chatContainer not found`);return}let a=i.querySelector(`.message[data-message-id="${n}"]`);if(a||=i.querySelector(`[data-message-id="${n}"]`),!a){let t=Array.from(i.querySelectorAll(`[data-message-id]`),e=>e.dataset.messageId);r.warn(`[SearchPanel] positionmessage failed`,{targetSessionId:e,activeSessionId:v.activeSessionId,targetMessageId:n,typeOfMessageId:typeof n,messageIdLength:n.length,domMessageIds:t,chatContainerHtmlLen:i.innerHTML.length})}if(a)a.scrollIntoView({behavior:`instant`,block:`nearest`}),a.classList.add(`bookmark-highlight`),setTimeout(()=>{a.classList.remove(`bookmark-highlight`)},2e3);else{A(t(`searchPanel.messageDeleted`),`warning`);try{if(await _(e,n)){I=I.filter(t=>!(t.sessionId===e&&t.messageId===n));let i=document.getElementById(`searchPanelContent`),a=document.getElementById(`searchPanelCount`);i&&I.length>0?(Es(I,hs,i),a.textContent=t(`searchPanel.countResult`,{count:I.length})):i&&I.length===0&&(i.innerHTML=`<div class="search-panel-empty">${t(`searchPanel.noMatch`)}</div>`,a&&(a.textContent=t(`searchPanel.noResult`))),r.debug(`[SearchPanel] cleaned IndexedDB dirtydata:`,e,n)}}catch(e){r.warn(`[SearchPanel] cleanupdirtydata failed:`,e)}}},500)}}e(`zh`,{schedPanel:{toggleTitle:`定时任务`,toggleRunning:`执行中`,title:`定时任务`,newTask:`新建任务`,close:`关闭`,empty:`暂无定时任务`,nameLabel:`任务名称`,descLabel:`任务描述(可选)`,promptLabel:`任务指令`,scheduleLabel:`定时规则`,scheduleTypeOnce:`一次性`,scheduleTypeInterval:`间隔`,scheduleTypeCron:`Cron 表达式`,intervalValuePlaceholder:`例如:30m / 2h / 1d`,cronValuePlaceholder:`例如:0 9 * * *`,relativeValuePlaceholder:`例如:30`,onceModeLabel:`执行方式`,onceModeRelative:`多少分钟后`,onceModeAbsolute:`指定时间点`,valueLabelInterval:`间隔时间`,valueLabelCron:`Cron 表达式`,minutesSuffix:` 分钟后`,contextUrlLabel:`上下文网页地址(可选)`,useCurrentPage:`使用当前页面`,sessionLabel:`宿主会话`,sessionAuto:`自动(会话被删时自动新建)`,save:`保存`,cancel:`取消`,edit:`编辑`,editTitle:`编辑任务`,delete:`删除`,runNow:`立即执行`,enable:`启用`,disable:`停用`,statusSuccess:`成功`,statusFailed:`失败`,statusRunning:`运行中`,statusDisabled:`已停用`,nextRun:`下次执行`,deleted:`任务已删除`,saved:`任务已保存`,runNowToast:`已触发执行`,deleteConfirmTitle:`删除定时任务`,deleteConfirmMsg:`确定删除任务「{name}」吗?`,createFailed:`创建任务失败`,nameRequired:`请填写任务名称`,promptRequired:`请填写任务指令`,scheduleRequired:`请填写定时规则`,loading:`加载中...`,contextModeLabel:`网页上下文方式`,contextModeFetch:`抓取网页正文`,contextModeUrlOnly:`仅使用 URL(不抓正文)`,maxRunsLabel:`最多执行次数(可选)`,endAtLabel:`截止时间(可选)`,runHistoryLabel:`运行历史`,runHistoryEmpty:`暂无运行记录`,runCountLabel:`运行历史 ({count})`,filterAll:`全部`,filterEnabled:`启用中`,filterDisabled:`已停用`,sortLabel:`排序`,sortCreated:`创建时间`,sortLastRun:`最近执行`,sortUpdated:`更新时间`,emptyFiltered:`没有符合筛选条件的任务`}}),e(`en`,{schedPanel:{toggleTitle:`Scheduled tasks`,toggleRunning:`Running`,title:`Scheduled tasks`,newTask:`New task`,close:`Close`,empty:`No scheduled tasks`,nameLabel:`Name`,descLabel:`Description (optional)`,promptLabel:`Prompt`,scheduleLabel:`Schedule`,scheduleTypeOnce:`Once`,scheduleTypeInterval:`Interval`,scheduleTypeCron:`Cron expression`,intervalValuePlaceholder:`e.g. 30m / 2h / 1d`,cronValuePlaceholder:`e.g. 0 9 * * *`,relativeValuePlaceholder:`e.g. 30`,onceModeLabel:`Run mode`,onceModeRelative:`After some minutes`,onceModeAbsolute:`At specific time`,valueLabelInterval:`Interval`,valueLabelCron:`Cron expression`,minutesSuffix:` minutes later`,contextUrlLabel:`Context page URL (optional)`,useCurrentPage:`Use current page`,sessionLabel:`Host session`,sessionAuto:`Auto (recreate if deleted)`,save:`Save`,cancel:`Cancel`,edit:`Edit`,editTitle:`Edit task`,delete:`Delete`,runNow:`Run now`,enable:`Enable`,disable:`Disable`,statusSuccess:`Success`,statusFailed:`Failed`,statusRunning:`Running`,statusDisabled:`Disabled`,nextRun:`Next run`,deleted:`Task deleted`,saved:`Task saved`,runNowToast:`Execution triggered`,deleteConfirmTitle:`Delete scheduled task`,deleteConfirmMsg:`Delete task "{name}"?`,createFailed:`Failed to create task`,nameRequired:`Name is required`,promptRequired:`Prompt is required`,scheduleRequired:`Schedule is required`,loading:`Loading...`,contextModeLabel:`Page context mode`,contextModeFetch:`Fetch page content`,contextModeUrlOnly:`URL only`,maxRunsLabel:`Max runs (optional)`,endAtLabel:`End time (optional)`,runHistoryLabel:`Run history`,runHistoryEmpty:`No runs yet`,runCountLabel:`Run history ({count})`,filterAll:`All`,filterEnabled:`Enabled`,filterDisabled:`Disabled`,sortLabel:`Sort`,sortCreated:`Created`,sortLastRun:`Last run`,sortUpdated:`Updated`,emptyFiltered:`No tasks match the filter`}});function As(e){return chrome.runtime.sendMessage(e)}function js(e){return e?new Date(e).toLocaleString(void 0,{month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`}):`—`}function Ms(e){return e==null?``:e<1e3?e+`ms`:e<6e4?(e/1e3).toFixed(1).replace(/\.0$/,``)+`s`:(e/6e4).toFixed(1).replace(/\.0$/,``)+`min`}function Ns(e){return e===`success`?t(`schedPanel.statusSuccess`):e===`failed`?t(`schedPanel.statusFailed`):e===`running`?t(`schedPanel.statusRunning`):``}function Ps(e){if(!e)return``;let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())}T${n(t.getHours())}:${n(t.getMinutes())}`}function Fs(e){let n=e.schedule||{};return n.type===`once`?n.onceMode===`relative`?t(`schedPanel.scheduleTypeOnce`)+` · `+(n.value||``)+t(`schedPanel.minutesSuffix`):t(`schedPanel.scheduleTypeOnce`)+` · `+js(new Date(n.value).getTime()):n.type===`interval`?t(`schedPanel.scheduleTypeInterval`)+` · `+(n.value||``):n.type===`cron`?t(`schedPanel.scheduleTypeCron`)+` · `+(n.value||``):``}function Is(e){return e.enabled?e.lastStatus===`running`?`<span class="sched-badge running">${t(`schedPanel.statusRunning`)}</span>`:e.lastStatus===`failed`?`<span class="sched-badge failed">${t(`schedPanel.statusFailed`)}</span>`:e.lastStatus===`success`?`<span class="sched-badge success">${t(`schedPanel.statusSuccess`)}</span>`:``:`<span class="sched-badge muted">${t(`schedPanel.statusDisabled`)}</span>`}function Ls(){let e=document.getElementById(`chatContainer`);e&&(e.scrollTop=e.scrollHeight)}async function Rs(e){if(e){if(v.activeSessionId!==e){let t=v.activeSessionId;try{if(await At(e)===!1||v.activeSessionId!==e)return}catch{return}document.dispatchEvent(new CustomEvent(`session-switched`,{detail:{sessionId:e,previousSessionId:t,skipScrollRestore:!0}}));try{let{renderSessionTabs:e}=await E(async()=>{let{renderSessionTabs:e}=await import(`./context-indicator-C9LYk-kV.js`).then(e=>e.rr);return{renderSessionTabs:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]));e()}catch{}}setTimeout(Ls,500)}}function zs(){let e=document.createElement(`div`);e.className=`schedule-panel-container`,e.id=`schedulePanelContainer`,e.innerHTML=`
51
+ `}).join(``)}function Os(e,t){if(!t)return e;let n=t.split(/[&|]/).map(e=>e.trim()).filter(Boolean);if(n.length===0)return e;let r=n.map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)),i=RegExp(`(${r.join(`|`)})`,`gi`);return e.replace(i,`<mark class="search-highlight-match">$1</mark>`)}async function ks(e,n){if(!(!e||!n)){if(v.activeSessionId!==e)try{let n=v.activeSessionId;if(await At(e)===!1||v.activeSessionId!==e){A(t(`searchPanel.sessionNotExist`),`warning`);return}document.dispatchEvent(new CustomEvent(`session-switched`,{detail:{sessionId:e,previousSessionId:n,skipScrollRestore:!0}}));try{let{renderSessionTabs:e}=await E(async()=>{let{renderSessionTabs:e}=await import(`./context-indicator-u4eOUhKC.js`).then(e=>e.rr);return{renderSessionTabs:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]));e()}catch(e){r.warn(`[SearchPanel] refreshsessionTab failed:`,e)}}catch(e){r.error(`[SearchPanel] switchsession failed:`,e);return}setTimeout(async()=>{let i=document.getElementById(`chatContainer`);if(!i){r.warn(`[SearchPanel] chatContainer not found`);return}let a=i.querySelector(`.message[data-message-id="${n}"]`);if(a||=i.querySelector(`[data-message-id="${n}"]`),!a){let t=Array.from(i.querySelectorAll(`[data-message-id]`),e=>e.dataset.messageId);r.warn(`[SearchPanel] positionmessage failed`,{targetSessionId:e,activeSessionId:v.activeSessionId,targetMessageId:n,typeOfMessageId:typeof n,messageIdLength:n.length,domMessageIds:t,chatContainerHtmlLen:i.innerHTML.length})}if(a)a.scrollIntoView({behavior:`instant`,block:`nearest`}),a.classList.add(`bookmark-highlight`),setTimeout(()=>{a.classList.remove(`bookmark-highlight`)},2e3);else{A(t(`searchPanel.messageDeleted`),`warning`);try{if(await _(e,n)){I=I.filter(t=>!(t.sessionId===e&&t.messageId===n));let i=document.getElementById(`searchPanelContent`),a=document.getElementById(`searchPanelCount`);i&&I.length>0?(Es(I,hs,i),a.textContent=t(`searchPanel.countResult`,{count:I.length})):i&&I.length===0&&(i.innerHTML=`<div class="search-panel-empty">${t(`searchPanel.noMatch`)}</div>`,a&&(a.textContent=t(`searchPanel.noResult`))),r.debug(`[SearchPanel] cleaned IndexedDB dirtydata:`,e,n)}}catch(e){r.warn(`[SearchPanel] cleanupdirtydata failed:`,e)}}},500)}}e(`zh`,{schedPanel:{toggleTitle:`定时任务`,toggleRunning:`执行中`,title:`定时任务`,newTask:`新建任务`,close:`关闭`,empty:`暂无定时任务`,nameLabel:`任务名称`,descLabel:`任务描述(可选)`,promptLabel:`任务指令`,scheduleLabel:`定时规则`,scheduleTypeOnce:`一次性`,scheduleTypeInterval:`间隔`,scheduleTypeCron:`Cron 表达式`,intervalValuePlaceholder:`例如:30m / 2h / 1d`,cronValuePlaceholder:`例如:0 9 * * *`,relativeValuePlaceholder:`例如:30`,onceModeLabel:`执行方式`,onceModeRelative:`多少分钟后`,onceModeAbsolute:`指定时间点`,valueLabelInterval:`间隔时间`,valueLabelCron:`Cron 表达式`,minutesSuffix:` 分钟后`,contextUrlLabel:`上下文网页地址(可选)`,useCurrentPage:`使用当前页面`,sessionLabel:`宿主会话`,sessionAuto:`自动(会话被删时自动新建)`,save:`保存`,cancel:`取消`,edit:`编辑`,editTitle:`编辑任务`,delete:`删除`,runNow:`立即执行`,enable:`启用`,disable:`停用`,statusSuccess:`成功`,statusFailed:`失败`,statusRunning:`运行中`,statusDisabled:`已停用`,nextRun:`下次执行`,deleted:`任务已删除`,saved:`任务已保存`,runNowToast:`已触发执行`,deleteConfirmTitle:`删除定时任务`,deleteConfirmMsg:`确定删除任务「{name}」吗?`,createFailed:`创建任务失败`,nameRequired:`请填写任务名称`,promptRequired:`请填写任务指令`,scheduleRequired:`请填写定时规则`,loading:`加载中...`,contextModeLabel:`网页上下文方式`,contextModeFetch:`抓取网页正文`,contextModeUrlOnly:`仅使用 URL(不抓正文)`,maxRunsLabel:`最多执行次数(可选)`,endAtLabel:`截止时间(可选)`,runHistoryLabel:`运行历史`,runHistoryEmpty:`暂无运行记录`,runCountLabel:`运行历史 ({count})`,filterAll:`全部`,filterEnabled:`启用中`,filterDisabled:`已停用`,sortLabel:`排序`,sortCreated:`创建时间`,sortLastRun:`最近执行`,sortUpdated:`更新时间`,emptyFiltered:`没有符合筛选条件的任务`}}),e(`en`,{schedPanel:{toggleTitle:`Scheduled tasks`,toggleRunning:`Running`,title:`Scheduled tasks`,newTask:`New task`,close:`Close`,empty:`No scheduled tasks`,nameLabel:`Name`,descLabel:`Description (optional)`,promptLabel:`Prompt`,scheduleLabel:`Schedule`,scheduleTypeOnce:`Once`,scheduleTypeInterval:`Interval`,scheduleTypeCron:`Cron expression`,intervalValuePlaceholder:`e.g. 30m / 2h / 1d`,cronValuePlaceholder:`e.g. 0 9 * * *`,relativeValuePlaceholder:`e.g. 30`,onceModeLabel:`Run mode`,onceModeRelative:`After some minutes`,onceModeAbsolute:`At specific time`,valueLabelInterval:`Interval`,valueLabelCron:`Cron expression`,minutesSuffix:` minutes later`,contextUrlLabel:`Context page URL (optional)`,useCurrentPage:`Use current page`,sessionLabel:`Host session`,sessionAuto:`Auto (recreate if deleted)`,save:`Save`,cancel:`Cancel`,edit:`Edit`,editTitle:`Edit task`,delete:`Delete`,runNow:`Run now`,enable:`Enable`,disable:`Disable`,statusSuccess:`Success`,statusFailed:`Failed`,statusRunning:`Running`,statusDisabled:`Disabled`,nextRun:`Next run`,deleted:`Task deleted`,saved:`Task saved`,runNowToast:`Execution triggered`,deleteConfirmTitle:`Delete scheduled task`,deleteConfirmMsg:`Delete task "{name}"?`,createFailed:`Failed to create task`,nameRequired:`Name is required`,promptRequired:`Prompt is required`,scheduleRequired:`Schedule is required`,loading:`Loading...`,contextModeLabel:`Page context mode`,contextModeFetch:`Fetch page content`,contextModeUrlOnly:`URL only`,maxRunsLabel:`Max runs (optional)`,endAtLabel:`End time (optional)`,runHistoryLabel:`Run history`,runHistoryEmpty:`No runs yet`,runCountLabel:`Run history ({count})`,filterAll:`All`,filterEnabled:`Enabled`,filterDisabled:`Disabled`,sortLabel:`Sort`,sortCreated:`Created`,sortLastRun:`Last run`,sortUpdated:`Updated`,emptyFiltered:`No tasks match the filter`}});function As(e){return chrome.runtime.sendMessage(e)}function js(e){return e?new Date(e).toLocaleString(void 0,{month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`}):`—`}function Ms(e){return e==null?``:e<1e3?e+`ms`:e<6e4?(e/1e3).toFixed(1).replace(/\.0$/,``)+`s`:(e/6e4).toFixed(1).replace(/\.0$/,``)+`min`}function Ns(e){return e===`success`?t(`schedPanel.statusSuccess`):e===`failed`?t(`schedPanel.statusFailed`):e===`running`?t(`schedPanel.statusRunning`):``}function Ps(e){if(!e)return``;let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())}T${n(t.getHours())}:${n(t.getMinutes())}`}function Fs(e){let n=e.schedule||{};return n.type===`once`?n.onceMode===`relative`?t(`schedPanel.scheduleTypeOnce`)+` · `+(n.value||``)+t(`schedPanel.minutesSuffix`):t(`schedPanel.scheduleTypeOnce`)+` · `+js(new Date(n.value).getTime()):n.type===`interval`?t(`schedPanel.scheduleTypeInterval`)+` · `+(n.value||``):n.type===`cron`?t(`schedPanel.scheduleTypeCron`)+` · `+(n.value||``):``}function Is(e){return e.enabled?e.lastStatus===`running`?`<span class="sched-badge running">${t(`schedPanel.statusRunning`)}</span>`:e.lastStatus===`failed`?`<span class="sched-badge failed">${t(`schedPanel.statusFailed`)}</span>`:e.lastStatus===`success`?`<span class="sched-badge success">${t(`schedPanel.statusSuccess`)}</span>`:``:`<span class="sched-badge muted">${t(`schedPanel.statusDisabled`)}</span>`}function Ls(){let e=document.getElementById(`chatContainer`);e&&(e.scrollTop=e.scrollHeight)}async function Rs(e){if(e){if(v.activeSessionId!==e){let t=v.activeSessionId;try{if(await At(e)===!1||v.activeSessionId!==e)return}catch{return}document.dispatchEvent(new CustomEvent(`session-switched`,{detail:{sessionId:e,previousSessionId:t,skipScrollRestore:!0}}));try{let{renderSessionTabs:e}=await E(async()=>{let{renderSessionTabs:e}=await import(`./context-indicator-u4eOUhKC.js`).then(e=>e.rr);return{renderSessionTabs:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]));e()}catch{}}setTimeout(Ls,500)}}function zs(){let e=document.createElement(`div`);e.className=`schedule-panel-container`,e.id=`schedulePanelContainer`,e.innerHTML=`
52
52
  <style>
53
53
  .schedule-panel-container { position: relative; display: flex; justify-content: flex-end; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; width: 100%; background: transparent; }
54
54
  .schedule-panel-toggle { background: rgba(var(--success-rgb), 0.14); color: var(--success-strong); border: none; border-radius: 6px 0 0 6px; padding: 8px 4px; cursor: pointer; font-size: 14px; box-shadow: -1px 1px 4px rgba(var(--overlay-rgb), 0.12); transition: all 0.3s ease; display: flex; align-items: center; justify-content: center; }
@@ -472,7 +472,7 @@ import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-XUUSwfZZ.js"
472
472
  <button class="sap-btn sap-transfer"></button>
473
473
  <button class="sap-btn sap-regen"></button>
474
474
  </div>
475
- `,document.body.appendChild(Q),Q.querySelector(`.sap-close`).addEventListener(`click`,bm),Q.querySelector(`.sap-lock`).addEventListener(`click`,mm),Q.querySelector(`.sap-copy`).addEventListener(`click`,wm),Q.querySelector(`.sap-transfer`).addEventListener(`click`,Tm),Q.querySelector(`.sap-regen`).addEventListener(`click`,()=>{nm&&rm&&Dm()}),Cm(Q.querySelector(`.sap-header`)),Q)}function fm(){if(!Q)return;Q.querySelector(`.sap-close`).title=t(`sidePanel.popupClose`);let e=Q.querySelector(`.sap-copy`);e.textContent=t(`sidePanel.popupCopy`),e.title=t(`sidePanel.popupCopy`);let n=Q.querySelector(`.sap-transfer`);n.textContent=t(`sidePanel.popupTransfer`),n.title=t(`sidePanel.popupTransfer`);let r=Q.querySelector(`.sap-regen`);r.textContent=t(`sidePanel.popupRegenerate`),r.title=t(`sidePanel.popupRegenerate`),pm()}function pm(){if(!Q)return;let e=Q.querySelector(`.sap-lock`);e&&(e.classList.toggle(`locked`,sm),e.title=t(sm?`sidePanel.popupUnlock`:`sidePanel.popupLock`),e.innerHTML=sm?`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>`:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 9.9-1"/></svg>`)}function mm(){sm=!sm,pm()}function hm(e,t){let n=dm(),r=window.innerWidth,i=window.innerHeight,a=t+12,o=e-320/2;o<8&&(o=8),o+320>r-8&&(o=r-320-8),a+280>i-8&&(a=t-280-12),a<8&&(a=8),n.style.position=`fixed`,n.style.top=a+`px`,n.style.left=o+`px`}function gm(e){let n=dm();fm(),n.querySelector(`.sap-title`).textContent=e||t(`sidePanel.popupTitle`),n.querySelector(`.sap-body`).innerHTML=`<div class="sap-loading">${j(t(`sidePanel.popupLoading`))}</div>`,n.classList.add(`show`),Q.style.display=`block`}function _m(){return!!Q&&Q.classList.contains(`show`)}function vm(e,t=!0){let n=Q?.querySelector(`.sap-body`);n&&(n.innerHTML=`<div class="sap-content markdown-body">${e}</div>`,t&&(n.scrollTop=n.scrollHeight))}function ym(e){let t=Q?.querySelector(`.sap-body`);t&&(t.innerHTML=`<div class="sap-error">${j(e)}</div>`)}function bm(){om&&em&&chrome.runtime.sendMessage({type:`CANCEL_REACT`,sessionId:em}).catch(()=>{}),Q&&(Q.classList.remove(`show`),Q.style.display=`none`),em=null,tm=``,om=!1,sm=!1}function xm(e){if(!_m()||sm||Q.contains(e.target))return;let t=document.getElementById(`selectionFloatingMenu`);t&&t.contains(e.target)||bm()}function Sm(e){e.key===`Escape`&&(!_m()||sm||bm())}function Cm(e){let t=!1,n,r,i,a;e.addEventListener(`mousedown`,e=>{if(e.target.closest(`.sap-close, .sap-lock`))return;t=!0,n=e.clientX,r=e.clientY;let o=Q.getBoundingClientRect();i=o.top,a=o.left,e.preventDefault()}),document.addEventListener(`mousemove`,e=>{if(!t)return;let o=e.clientX-n,s=e.clientY-r;Q.style.position=`fixed`,Q.style.top=i+s+`px`,Q.style.left=a+o+`px`}),document.addEventListener(`mouseup`,()=>{t=!1})}function wm(){tm&&navigator.clipboard.writeText(tm).then(()=>{A(t(`sidePanel.popupCopied`))}).catch(()=>{let e=document.createElement(`textarea`);e.value=tm,document.body.appendChild(e),e.select(),document.execCommand(`copy`),document.body.removeChild(e),A(t(`sidePanel.popupCopied`))})}function Tm(){if(!tm||!nm)return;An()&&Qr();let e=tm,n=nm.content,r=`${im?`[${t(`sidePanel.popupContextLabel`)}]\n${im}\n\n`:``}[${t(`sidePanel.selectedContentLabel`)}]\n${rm}\n\n[${t(`sidePanel.userQuestionLabel`)}]\n${nm.content}`;E(async()=>{let{addMessage:e}=await import(`./context-indicator-C9LYk-kV.js`).then(e=>e.V);return{addMessage:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8])).then(({addMessage:i})=>{i(`user`,n,!0,[],null,!1,r),v.messageHistory.push({role:`user`,content:r,timestamp:new Date().toISOString()}),i(`assistant`,e,!0),v.messageHistory.push({role:`assistant`,content:e}),E(async()=>{let{saveCurrentSession:e}=await import(`./context-indicator-C9LYk-kV.js`).then(e=>e.Sr);return{saveCurrentSession:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8])).then(({saveCurrentSession:e})=>{e()}),Promise.all([E(()=>import(`./context-indicator-C9LYk-kV.js`).then(e=>e.pt),__vite__mapDeps([0,1,2,3,4,5,6,7,8])),new Promise(e=>requestAnimationFrame(e))]).then(([{autoScrollToBottom:e}])=>{e(document.getElementById(`chatContainer`),{force:!0,smooth:!0}),A(t(`sidePanel.popupTransferred`))})}),bm()}function Em(e,t,n){let{context:r,truncated:i}=lm(n,t);nm=e,rm=t,im=r,am=i,Dm()}function Dm(){tm=``,om=!0,gm(nm?.content);let e=um(rm,im,nm.content,am);em=`popup_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,chrome.runtime.sendMessage({type:`SIDEPANEL_POPUP_ASK`,sessionId:em,messages:e}).catch(e=>{r.error(`[SelectionPopup] sendMessage failed:`,e),ym(t(`sidePanel.popupRequestFailed`)),om=!1})}var Om=!1;function km(){Om||(Om=!0,chrome.runtime.onMessage.addListener(e=>{if(!(!e||!e.type)&&e.type.startsWith(`SIDEPANEL_POPUP_`)&&e.sessionId===em){if(e.type===`SIDEPANEL_POPUP_STREAM_CHUNK`)e.delta&&(tm+=e.delta,vm(lt(tm)));else if(e.type===`SIDEPANEL_POPUP_STREAM_DONE`)om=!1,e.finalContent&&(tm=e.finalContent),vm(lt(tm));else if(e.type===`SIDEPANEL_POPUP_STREAM_ERROR`){if(!om)return;om=!1,ym(e.error||t(`sidePanel.popupRequestFailed`))}}}))}function Am(){km(),document.addEventListener(`mousedown`,xm),document.addEventListener(`keydown`,Sm)}function jm(e,t,n,r,i){!t||!e||(km(),hm(n,r),sm=!1,Em(e,t,i||v.currentSelectionRange))}e(`zh`,{tokenStats:{clearConfirmMessage:`确定要清空所有 Token 使用统计吗?此操作不可撤销。`,loadFailed:`加载失败`,currentSessionNoData:`当前会话暂无数据`,totalTokenUsage:`总 Token 消耗`,apiCallCount:`API 调用次数`,contextUsageRate:`上下文使用率`,max:`最大`,avg:`平均`,min:`最小`,totalTokens:`总 Token`,totalSessions:`总会话数`,totalApiCalls:`总 API 调用`,callTypeNonStream:`普通`,callTypeStream:`流式`,callTypeReflection:`反思`,callTypeToolReflection:`工具反思`,callTypeSubtaskReflection:`子任务反思`,tabTrend:`趋势`,tabDistribution:`分布`,tabGlobal:`全局`,topCardSessionTokens:`本次 Token`,topCardSessionCalls:`本次调用`,topCardContextPeak:`上下文峰值`,sparklineTitle:`最近 20 次调用趋势`,distPromptVsCompletion:`Prompt / Completion 占比`,distPrompt:`Prompt`,distCompletion:`Completion`,distByModel:`按模型分布`,distByCallType:`按调用类型分布`,distNoData:`暂无分布数据`,globalSparklineTitle:`最近 30 天趋势`,globalNoDailyData:`所选范围内暂无数据`,globalTotalTokens:`总 Token`,globalTotalSessions:`总会话数`,globalTotalApiCalls:`总 API 调用`}}),e(`en`,{tokenStats:{clearConfirmMessage:`Are you sure you want to clear all Token usage statistics? This action cannot be undone.`,loadFailed:`Load failed`,currentSessionNoData:`No data for current session`,totalTokenUsage:`Total Token Usage`,apiCallCount:`API Call Count`,contextUsageRate:`Context Usage Rate`,max:`Max`,avg:`Avg`,min:`Min`,totalTokens:`Total Tokens`,totalSessions:`Total Sessions`,totalApiCalls:`Total API Calls`,callTypeNonStream:`Normal`,callTypeStream:`Stream`,callTypeReflection:`Reflection`,callTypeToolReflection:`Tool Reflection`,callTypeSubtaskReflection:`Subtask Reflection`,tabTrend:`Trend`,tabDistribution:`Distribution`,tabGlobal:`Global`,topCardSessionTokens:`Session Tokens`,topCardSessionCalls:`Session Calls`,topCardContextPeak:`Context Peak`,sparklineTitle:`Last 20 Calls Trend`,distPromptVsCompletion:`Prompt / Completion Ratio`,distPrompt:`Prompt`,distCompletion:`Completion`,distByModel:`By Model`,distByCallType:`By Call Type`,distNoData:`No distribution data`,globalSparklineTitle:`Last 30 Days Trend`,globalNoDailyData:`No data in selected range`,globalTotalTokens:`Total Tokens`,globalTotalSessions:`Total Sessions`,globalTotalApiCalls:`Total API Calls`}});function Mm(e,n){let i=document.getElementById(`tokenStatsOverlay`),a=document.getElementById(`tokenStatsClose`),o=document.getElementById(`tokenStatsRefreshBtn`),s=document.getElementById(`tokenStatsClearBtn`),c=document.getElementById(`tokenStatsTabNav`),l=document.getElementById(`tokenStatsTopCards`);if(!i)return;let u=`trend`,d=`month`;function f(){i.style.display=`flex`,h()}function p(){i.style.display=`none`}if(window.openTokenStats=f,a&&a.addEventListener(`click`,p),i&&i.addEventListener(`click`,e=>{e.target===i&&p()}),o&&o.addEventListener(`click`,h),s&&s.addEventListener(`click`,async()=>{await n(t(`tokenStats.clearConfirmMessage`),t(`toolStats.clearTitle`))&&(await he(),h())}),c){c.addEventListener(`click`,e=>{let t=e.target.closest(`.token-tab-btn`);if(!t)return;let n=t.dataset.tab;if(n===u)return;c.querySelectorAll(`.token-tab-btn`).forEach(e=>{e.classList.remove(`active`),e.style.borderBottomColor=`transparent`,e.style.color=`var(--text-secondary)`}),t.classList.add(`active`),t.style.borderBottomColor=`var(--brand-500)`,t.style.color=`var(--brand-500)`,document.querySelectorAll(`.token-tab-content`).forEach(e=>{e.style.display=`none`});let r=document.getElementById(`tokenTab${n.charAt(0).toUpperCase()+n.slice(1)}`);r&&(r.style.display=n===`global`?`flex`:``),u=n});let e=c.querySelector(`.token-tab-btn.active`);e&&(e.style.borderBottomColor=`var(--brand-500)`,e.style.color=`var(--brand-500)`)}let m=document.querySelectorAll(`.token-time-range-btn`);m.forEach(e=>{e.addEventListener(`click`,()=>{let t=e.dataset.range;t!==d&&(d=t,m.forEach(e=>{e.classList.remove(`active`),e.style.border=`1px solid var(--border-default)`,e.style.background=`var(--bg-surface)`,e.style.color=`var(--text-secondary)`}),e.classList.add(`active`),e.style.border=`1px solid var(--brand-500)`,e.style.background=`var(--brand-500)`,e.style.color=`var(--text-on-brand)`,b())})});async function h(){let n=e(),i=document.getElementById(`tokenStatsLoading`),a=document.getElementById(`tokenStatsEmpty`),o=document.getElementById(`tokenStatsContent`);i&&(i.style.display=``),a&&(a.style.display=`none`),o&&(o.style.display=`none`),c&&(c.style.display=`none`),l&&(l.style.display=`none`);try{let[e,t]=await Promise.all([je(n),Me()]);if(i&&(i.style.display=`none`),!(t&&t.totalApiCalls>0)){a&&(a.style.display=``);return}o&&(o.style.display=``),c&&(c.style.display=`flex`),l&&(l.style.display=``),g(e),ee(e),ie(e.records||[]),v(t),b()}catch(e){r.error(`[TokenStats] load stats failed:`,e),i&&(i.style.display=`none`),a&&(a.textContent=t(`tokenStats.loadFailed`),a.style.display=``)}}function g(e){if(!l)return;if(!e||e.apiCallCount===0){l.innerHTML=``;return}let n=e.maxContextUsageRate||0,r=C(n);l.innerHTML=`
475
+ `,document.body.appendChild(Q),Q.querySelector(`.sap-close`).addEventListener(`click`,bm),Q.querySelector(`.sap-lock`).addEventListener(`click`,mm),Q.querySelector(`.sap-copy`).addEventListener(`click`,wm),Q.querySelector(`.sap-transfer`).addEventListener(`click`,Tm),Q.querySelector(`.sap-regen`).addEventListener(`click`,()=>{nm&&rm&&Dm()}),Cm(Q.querySelector(`.sap-header`)),Q)}function fm(){if(!Q)return;Q.querySelector(`.sap-close`).title=t(`sidePanel.popupClose`);let e=Q.querySelector(`.sap-copy`);e.textContent=t(`sidePanel.popupCopy`),e.title=t(`sidePanel.popupCopy`);let n=Q.querySelector(`.sap-transfer`);n.textContent=t(`sidePanel.popupTransfer`),n.title=t(`sidePanel.popupTransfer`);let r=Q.querySelector(`.sap-regen`);r.textContent=t(`sidePanel.popupRegenerate`),r.title=t(`sidePanel.popupRegenerate`),pm()}function pm(){if(!Q)return;let e=Q.querySelector(`.sap-lock`);e&&(e.classList.toggle(`locked`,sm),e.title=t(sm?`sidePanel.popupUnlock`:`sidePanel.popupLock`),e.innerHTML=sm?`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>`:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 9.9-1"/></svg>`)}function mm(){sm=!sm,pm()}function hm(e,t){let n=dm(),r=window.innerWidth,i=window.innerHeight,a=t+12,o=e-320/2;o<8&&(o=8),o+320>r-8&&(o=r-320-8),a+280>i-8&&(a=t-280-12),a<8&&(a=8),n.style.position=`fixed`,n.style.top=a+`px`,n.style.left=o+`px`}function gm(e){let n=dm();fm(),n.querySelector(`.sap-title`).textContent=e||t(`sidePanel.popupTitle`),n.querySelector(`.sap-body`).innerHTML=`<div class="sap-loading">${j(t(`sidePanel.popupLoading`))}</div>`,n.classList.add(`show`),Q.style.display=`block`}function _m(){return!!Q&&Q.classList.contains(`show`)}function vm(e,t=!0){let n=Q?.querySelector(`.sap-body`);n&&(n.innerHTML=`<div class="sap-content markdown-body">${e}</div>`,t&&(n.scrollTop=n.scrollHeight))}function ym(e){let t=Q?.querySelector(`.sap-body`);t&&(t.innerHTML=`<div class="sap-error">${j(e)}</div>`)}function bm(){om&&em&&chrome.runtime.sendMessage({type:`CANCEL_REACT`,sessionId:em}).catch(()=>{}),Q&&(Q.classList.remove(`show`),Q.style.display=`none`),em=null,tm=``,om=!1,sm=!1}function xm(e){if(!_m()||sm||Q.contains(e.target))return;let t=document.getElementById(`selectionFloatingMenu`);t&&t.contains(e.target)||bm()}function Sm(e){e.key===`Escape`&&(!_m()||sm||bm())}function Cm(e){let t=!1,n,r,i,a;e.addEventListener(`mousedown`,e=>{if(e.target.closest(`.sap-close, .sap-lock`))return;t=!0,n=e.clientX,r=e.clientY;let o=Q.getBoundingClientRect();i=o.top,a=o.left,e.preventDefault()}),document.addEventListener(`mousemove`,e=>{if(!t)return;let o=e.clientX-n,s=e.clientY-r;Q.style.position=`fixed`,Q.style.top=i+s+`px`,Q.style.left=a+o+`px`}),document.addEventListener(`mouseup`,()=>{t=!1})}function wm(){tm&&navigator.clipboard.writeText(tm).then(()=>{A(t(`sidePanel.popupCopied`))}).catch(()=>{let e=document.createElement(`textarea`);e.value=tm,document.body.appendChild(e),e.select(),document.execCommand(`copy`),document.body.removeChild(e),A(t(`sidePanel.popupCopied`))})}function Tm(){if(!tm||!nm)return;An()&&Qr();let e=tm,n=nm.content,r=`${im?`[${t(`sidePanel.popupContextLabel`)}]\n${im}\n\n`:``}[${t(`sidePanel.selectedContentLabel`)}]\n${rm}\n\n[${t(`sidePanel.userQuestionLabel`)}]\n${nm.content}`;E(async()=>{let{addMessage:e}=await import(`./context-indicator-u4eOUhKC.js`).then(e=>e.V);return{addMessage:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8])).then(({addMessage:i})=>{i(`user`,n,!0,[],null,!1,r),v.messageHistory.push({role:`user`,content:r,timestamp:new Date().toISOString()}),i(`assistant`,e,!0),v.messageHistory.push({role:`assistant`,content:e}),E(async()=>{let{saveCurrentSession:e}=await import(`./context-indicator-u4eOUhKC.js`).then(e=>e.Sr);return{saveCurrentSession:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8])).then(({saveCurrentSession:e})=>{e()}),Promise.all([E(()=>import(`./context-indicator-u4eOUhKC.js`).then(e=>e.pt),__vite__mapDeps([0,1,2,3,4,5,6,7,8])),new Promise(e=>requestAnimationFrame(e))]).then(([{autoScrollToBottom:e}])=>{e(document.getElementById(`chatContainer`),{force:!0,smooth:!0}),A(t(`sidePanel.popupTransferred`))})}),bm()}function Em(e,t,n){let{context:r,truncated:i}=lm(n,t);nm=e,rm=t,im=r,am=i,Dm()}function Dm(){tm=``,om=!0,gm(nm?.content);let e=um(rm,im,nm.content,am);em=`popup_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,chrome.runtime.sendMessage({type:`SIDEPANEL_POPUP_ASK`,sessionId:em,messages:e}).catch(e=>{r.error(`[SelectionPopup] sendMessage failed:`,e),ym(t(`sidePanel.popupRequestFailed`)),om=!1})}var Om=!1;function km(){Om||(Om=!0,chrome.runtime.onMessage.addListener(e=>{if(!(!e||!e.type)&&e.type.startsWith(`SIDEPANEL_POPUP_`)&&e.sessionId===em){if(e.type===`SIDEPANEL_POPUP_STREAM_CHUNK`)e.delta&&(tm+=e.delta,vm(lt(tm)));else if(e.type===`SIDEPANEL_POPUP_STREAM_DONE`)om=!1,e.finalContent&&(tm=e.finalContent),vm(lt(tm));else if(e.type===`SIDEPANEL_POPUP_STREAM_ERROR`){if(!om)return;om=!1,ym(e.error||t(`sidePanel.popupRequestFailed`))}}}))}function Am(){km(),document.addEventListener(`mousedown`,xm),document.addEventListener(`keydown`,Sm)}function jm(e,t,n,r,i){!t||!e||(km(),hm(n,r),sm=!1,Em(e,t,i||v.currentSelectionRange))}e(`zh`,{tokenStats:{clearConfirmMessage:`确定要清空所有 Token 使用统计吗?此操作不可撤销。`,loadFailed:`加载失败`,currentSessionNoData:`当前会话暂无数据`,totalTokenUsage:`总 Token 消耗`,apiCallCount:`API 调用次数`,contextUsageRate:`上下文使用率`,max:`最大`,avg:`平均`,min:`最小`,totalTokens:`总 Token`,totalSessions:`总会话数`,totalApiCalls:`总 API 调用`,callTypeNonStream:`普通`,callTypeStream:`流式`,callTypeReflection:`反思`,callTypeToolReflection:`工具反思`,callTypeSubtaskReflection:`子任务反思`,tabTrend:`趋势`,tabDistribution:`分布`,tabGlobal:`全局`,topCardSessionTokens:`本次 Token`,topCardSessionCalls:`本次调用`,topCardContextPeak:`上下文峰值`,sparklineTitle:`最近 20 次调用趋势`,distPromptVsCompletion:`Prompt / Completion 占比`,distPrompt:`Prompt`,distCompletion:`Completion`,distByModel:`按模型分布`,distByCallType:`按调用类型分布`,distNoData:`暂无分布数据`,globalSparklineTitle:`最近 30 天趋势`,globalNoDailyData:`所选范围内暂无数据`,globalTotalTokens:`总 Token`,globalTotalSessions:`总会话数`,globalTotalApiCalls:`总 API 调用`}}),e(`en`,{tokenStats:{clearConfirmMessage:`Are you sure you want to clear all Token usage statistics? This action cannot be undone.`,loadFailed:`Load failed`,currentSessionNoData:`No data for current session`,totalTokenUsage:`Total Token Usage`,apiCallCount:`API Call Count`,contextUsageRate:`Context Usage Rate`,max:`Max`,avg:`Avg`,min:`Min`,totalTokens:`Total Tokens`,totalSessions:`Total Sessions`,totalApiCalls:`Total API Calls`,callTypeNonStream:`Normal`,callTypeStream:`Stream`,callTypeReflection:`Reflection`,callTypeToolReflection:`Tool Reflection`,callTypeSubtaskReflection:`Subtask Reflection`,tabTrend:`Trend`,tabDistribution:`Distribution`,tabGlobal:`Global`,topCardSessionTokens:`Session Tokens`,topCardSessionCalls:`Session Calls`,topCardContextPeak:`Context Peak`,sparklineTitle:`Last 20 Calls Trend`,distPromptVsCompletion:`Prompt / Completion Ratio`,distPrompt:`Prompt`,distCompletion:`Completion`,distByModel:`By Model`,distByCallType:`By Call Type`,distNoData:`No distribution data`,globalSparklineTitle:`Last 30 Days Trend`,globalNoDailyData:`No data in selected range`,globalTotalTokens:`Total Tokens`,globalTotalSessions:`Total Sessions`,globalTotalApiCalls:`Total API Calls`}});function Mm(e,n){let i=document.getElementById(`tokenStatsOverlay`),a=document.getElementById(`tokenStatsClose`),o=document.getElementById(`tokenStatsRefreshBtn`),s=document.getElementById(`tokenStatsClearBtn`),c=document.getElementById(`tokenStatsTabNav`),l=document.getElementById(`tokenStatsTopCards`);if(!i)return;let u=`trend`,d=`month`;function f(){i.style.display=`flex`,h()}function p(){i.style.display=`none`}if(window.openTokenStats=f,a&&a.addEventListener(`click`,p),i&&i.addEventListener(`click`,e=>{e.target===i&&p()}),o&&o.addEventListener(`click`,h),s&&s.addEventListener(`click`,async()=>{await n(t(`tokenStats.clearConfirmMessage`),t(`toolStats.clearTitle`))&&(await he(),h())}),c){c.addEventListener(`click`,e=>{let t=e.target.closest(`.token-tab-btn`);if(!t)return;let n=t.dataset.tab;if(n===u)return;c.querySelectorAll(`.token-tab-btn`).forEach(e=>{e.classList.remove(`active`),e.style.borderBottomColor=`transparent`,e.style.color=`var(--text-secondary)`}),t.classList.add(`active`),t.style.borderBottomColor=`var(--brand-500)`,t.style.color=`var(--brand-500)`,document.querySelectorAll(`.token-tab-content`).forEach(e=>{e.style.display=`none`});let r=document.getElementById(`tokenTab${n.charAt(0).toUpperCase()+n.slice(1)}`);r&&(r.style.display=n===`global`?`flex`:``),u=n});let e=c.querySelector(`.token-tab-btn.active`);e&&(e.style.borderBottomColor=`var(--brand-500)`,e.style.color=`var(--brand-500)`)}let m=document.querySelectorAll(`.token-time-range-btn`);m.forEach(e=>{e.addEventListener(`click`,()=>{let t=e.dataset.range;t!==d&&(d=t,m.forEach(e=>{e.classList.remove(`active`),e.style.border=`1px solid var(--border-default)`,e.style.background=`var(--bg-surface)`,e.style.color=`var(--text-secondary)`}),e.classList.add(`active`),e.style.border=`1px solid var(--brand-500)`,e.style.background=`var(--brand-500)`,e.style.color=`var(--text-on-brand)`,b())})});async function h(){let n=e(),i=document.getElementById(`tokenStatsLoading`),a=document.getElementById(`tokenStatsEmpty`),o=document.getElementById(`tokenStatsContent`);i&&(i.style.display=``),a&&(a.style.display=`none`),o&&(o.style.display=`none`),c&&(c.style.display=`none`),l&&(l.style.display=`none`);try{let[e,t]=await Promise.all([je(n),Me()]);if(i&&(i.style.display=`none`),!(t&&t.totalApiCalls>0)){a&&(a.style.display=``);return}o&&(o.style.display=``),c&&(c.style.display=`flex`),l&&(l.style.display=``),g(e),ee(e),ie(e.records||[]),v(t),b()}catch(e){r.error(`[TokenStats] load stats failed:`,e),i&&(i.style.display=`none`),a&&(a.textContent=t(`tokenStats.loadFailed`),a.style.display=``)}}function g(e){if(!l)return;if(!e||e.apiCallCount===0){l.innerHTML=``;return}let n=e.maxContextUsageRate||0,r=C(n);l.innerHTML=`
476
476
  <div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 8px;">
477
477
  <div style="background: var(--brand-soft-bg); border-radius: 8px; padding: 10px; text-align: center;">
478
478
  <div style="font-size: 10px; color: var(--text-tertiary); margin-bottom: 4px;">${t(`tokenStats.topCardSessionTokens`)}</div>
@@ -601,7 +601,7 @@ Agent address: {url}
601
601
  Are you sure you want to update the agent? It will install the latest patch version within the {version} minor range compatible with this extension, then restart the service. The service will be unavailable during update.`,updateAgentTitle:`Update Agent`,agentUpdating:`Updating agent (may take a few minutes)...`,agentUpdateRestarting:`Agent is updating and restarting...`,agentVersionAhead:`Agent version is newer than this extension. Please update the extension from the store first`,agentAlreadyLatest:`Already at the latest compatible version`,agentUpdateAvailable:`Update available: v{current} → v{latest}`,updateFailed:`Update failed: {error}`,updateRequestFailed:`Update request failed: {error}`,stopAgentConfirm:`Agent name: {name}
602
602
  Agent address: {url}
603
603
 
604
- Are you sure you want to stop the agent service? You will not be able to connect and will need to manually restart it.`,stopAgentTitle:`Stop Agent`,agentStopped:`Agent service stopped, agent is offline`,stopFailed:`Stop failed: {error}`,stopRequestFailed:`Stop request failed: {error}`,agentStatusRefreshed:`Agent status refreshed`,deleteAgentTitle:`Delete Agent`,deleteAgentConfirm:`Are you sure you want to delete agent "{name}"? This action cannot be undone.`,welcomeTitle:`Start a Conversation`,welcomeSubtitle:`Enter your question and the AI assistant will help you`,sendBtnStop:`Stop generating`,sendBtnSend:`Send`,defaultPromptImage:`Please look at the attached image and describe what you see`,defaultPromptFile:`Please read the attached file and summarize the key points`,defaultPromptAttachments:`Please review the attached image and file and summarize the key points`,defaultPromptKnowledge:`Please answer based on the knowledge base content I referenced`,defaultKnowledgeQuery:`key points summary`,defaultPromptPage:`Please summarize the main content of this page`,defaultPromptSelection:`Please continue based on the content I provided`,defaultPromptContext:`Please continue based on the context I provided`,imageNotEnabled:`Image recognition not enabled, image attached as file`,screenshotFailed:`Screenshot failed, please retry`,auditCategoryAuth:`Auth`,auditCategoryFs:`File`,auditCategoryExec:`Command`,auditCategorySecurity:`Security`,auditCategorySystem:`System`,auditDetailSeparator:`; `,auditQueryFailed:`Query failed: {error}`,auditLoadFailed:`Load failed: {error}`,auditNoMatch:`No matching audit logs`,auditEmpty:`No audit logs`,clearStatsConfirm:`Are you sure you want to clear all tool usage stats? This action cannot be undone.`,clearStatsTitle:`Clear Stats`,toolStatsSummary:`Used {used} tools, unused {unused} tools`,toolStatsLoadFailed:`Load failed`,toolNameDescSeparator:`: `}}),window.showCustomConfirm=function(e,n=t(`sidePanel.confirmAction`)){return new Promise(t=>{let r=document.getElementById(`customConfirmOverlay`),i=document.getElementById(`customConfirmTitle`),a=document.getElementById(`customConfirmMessage`),o=document.getElementById(`customConfirmCancelBtn`),s=document.getElementById(`customConfirmOkBtn`);if(!r||!i||!a||!o||!s){t(confirm(e));return}let c=()=>{r.style.display=`none`,s.removeEventListener(`click`,l),o.removeEventListener(`click`,u),r.removeEventListener(`click`,d),document.removeEventListener(`keydown`,f)},l=()=>{c(),t(!0)},u=()=>{c(),t(!1)},d=e=>{e.target===r&&(c(),t(!1))},f=e=>{e.key===`Enter`?(e.preventDefault(),e.stopPropagation(),l()):e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),u())};i.textContent=n,a.innerHTML=e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`).replace(/'/g,`&#39;`).replace(/\n/g,`<br>`),r.style.display=`flex`,s.addEventListener(`click`,l),o.addEventListener(`click`,u),r.addEventListener(`click`,d),document.addEventListener(`keydown`,f),requestAnimationFrame(()=>s.focus())})},chrome.storage.onChanged.addListener((e,t)=>{t===`local`&&e.chatAutoCompaction&&(v.chatConfig.autoCompaction=e.chatAutoCompaction.newValue===!0,Fm(),r.debug(`[SidePanel] auto-compaction config updated:`,v.chatConfig.autoCompaction)),t===`local`&&e.chatPersistSummaryToMemory&&(v.chatConfig.persistSummaryToMemory=e.chatPersistSummaryToMemory.newValue!==!1,Im(),r.debug(`[SidePanel] persist-summary config updated:`,v.chatConfig.persistSummaryToMemory)),t===`local`&&e.chatMaxMemoryMessages&&(v.chatConfig.maxMemoryMessages=e.chatMaxMemoryMessages.newValue,Pm(),r.debug(`[SidePanel] memory limitconfiguration updated:`,v.chatConfig.maxMemoryMessages)),t===`local`&&e.queueAutoCarry&&(v.chatConfig.queueAutoCarry=e.queueAutoCarry.newValue!==!1,r.debug(`[SidePanel] queue auto-carry updated:`,v.chatConfig.queueAutoCarry)),t===`local`&&e.queueAutoCarryEveryNIterations&&(v.chatConfig.queueAutoCarryEveryNIterations=e.queueAutoCarryEveryNIterations.newValue,r.debug(`[SidePanel] queue auto-carry interval updated:`,v.chatConfig.queueAutoCarryEveryNIterations))});function Pm(){let e=document.getElementById(`memoryLimitLabel`);e&&(v.chatConfig.maxMemoryMessages!==null&&v.chatConfig.maxMemoryMessages!==void 0&&v.chatConfig.maxMemoryMessages>0?e.textContent=v.chatConfig.maxMemoryMessages:e.textContent=t(`sidePanel.memoryLimitAll`),e.title=t(`sidePanel.memoryLimitTitle`))}function Fm(){let e=document.getElementById(`autoCompactBtn`);e&&(e.checked=v.chatConfig.autoCompaction===!0)}function Im(){let e=document.getElementById(`persistSummaryBtn`);e&&(e.checked=v.chatConfig.persistSummaryToMemory!==!1)}function Lm(e){e.preventDefault(),e.stopPropagation();let t=document.getElementById(`memoryLimitDropdown`);if(t.classList.toggle(`show`),t.classList.contains(`show`)){let e=v.chatConfig.maxMemoryMessages;t.querySelectorAll(`.memory-limit-option`).forEach(t=>{t.classList.remove(`selected`);let n=parseInt(t.dataset.value);(e===null&&n===0||e!==null&&e>0&&n===e)&&t.classList.add(`selected`)});let n=t.querySelector(`#memoryLimitInput`);e!==null&&e>0?n.value=e:n.value=``}}function Rm(){let e=document.getElementById(`memoryLimitDropdown`),n=document.getElementById(`memoryLimitLabel`),r=e?.querySelector(`#memoryLimitInput`);if(!e||!n)return;Pm(),n.addEventListener(`click`,Lm);let i=document.getElementById(`autoCompactBtn`);i&&(i.checked=v.chatConfig.autoCompaction===!0,i.addEventListener(`change`,()=>{let e=i.checked;chrome.storage.local.set({chatAutoCompaction:e},()=>{v.chatConfig.autoCompaction=e,A(t(`sidePanel.configUpdated`),`success`)})}));let a=document.getElementById(`persistSummaryBtn`);a&&(a.checked=v.chatConfig.persistSummaryToMemory!==!1,a.addEventListener(`change`,()=>{let e=a.checked;chrome.storage.local.set({chatPersistSummaryToMemory:e},()=>{v.chatConfig.persistSummaryToMemory=e,A(t(`sidePanel.configUpdated`),`success`)})}));let o=e.querySelectorAll(`.memory-limit-option`);o.forEach(e=>{e.addEventListener(`click`,n=>{n.stopPropagation();let i=parseInt(e.dataset.value),a=i===0?null:i;o.forEach(e=>e.classList.remove(`selected`)),e.classList.add(`selected`),r&&(r.value=i===0?``:i),chrome.storage.local.set({chatMaxMemoryMessages:a},()=>{v.chatConfig.maxMemoryMessages=a,Pm(),A(t(`sidePanel.configUpdated`),`success`)})})}),r&&(r.addEventListener(`click`,e=>e.stopPropagation()),r.addEventListener(`mousedown`,e=>e.stopPropagation()),r.addEventListener(`change`,e=>{e.stopPropagation();let n=e.target.value.trim(),r=n&&parseInt(n)>0?parseInt(n):null;o.forEach(e=>e.classList.remove(`selected`)),chrome.storage.local.set({chatMaxMemoryMessages:r},()=>{v.chatConfig.maxMemoryMessages=r,Pm(),A(t(`sidePanel.configUpdated`),`success`)})})),document.getElementById(`memoryLimitConfigEntry`)?.addEventListener(`click`,()=>{chrome.runtime.sendMessage({type:`OPEN_OPTIONS_PAGE`,hash:`memory`})}),document.addEventListener(`click`,t=>{!e.contains(t.target)&&t.target!==n&&e.classList.remove(`show`)})}async function zm(e){if(v.activeAgentId&&v.activeAgentId!=="default")try{let{updateAgent:t}=await E(async()=>{let{updateAgent:e}=await import(`./agent-store-grxR4rg1.js`).then(e=>e.t);return{updateAgent:e}},__vite__mapDeps([7,1,2,3]));await t(v.activeAgentId,{model:e})}catch{}else chrome.storage.local.set({modelName:e}),ue(e)}async function Bm(){try{let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),t=Nm(e.pairedAgents),n=e.activeAgentId,r=t.find(e=>e.id===n&&!e.disabled);if(!r){v.agentPlatform={connected:!1},$(v.agentPlatform);return}if(r.token)try{let e=await fetch(`${r.url}/api/status/detail`,{cache:`no-cache`,headers:{Authorization:`Bearer ${r.token}`}});if(e.ok){let t=await e.json();if(t.success){v.agentPlatform={platformName:t.platformName||`Unknown`,platform:t.platform||`unknown`,arch:t.arch||`unknown`,shell:t.shell||`/bin/sh`,homeDir:t.homeDir||``,workdir:t.workdir||``,connected:!0},t.version&&v.agentVersions.set(n,t.version),t.workdir&&v.agentWorkdirs.set(n,t.workdir),t.homeDir&&v.agentHomeDirs.set(n,t.homeDir);let e=gh(t.platformName||t.platform,t.arch);e&&v.agentSystemInfos.set(n,e)}else v.agentPlatform={connected:!1}}else v.agentPlatform={connected:!1}}catch{v.agentPlatform={connected:!1}}else v.agentPlatform={connected:!1};$(v.agentPlatform),si()}catch{}}async function Vm(e,t,n){if(v.activeAgentId&&v.activeAgentId!=="default")try{let{updateAgent:n}=await E(async()=>{let{updateAgent:e}=await import(`./agent-store-grxR4rg1.js`).then(e=>e.t);return{updateAgent:e}},__vite__mapDeps([7,1,2,3]));await n(v.activeAgentId,{temperature:e,topP:t})}catch{}else chrome.storage.local.set({temperature:e,topP:t,selectedTempIndex:n})}function Hm(){let e=document.getElementById(`currentModelTag`);if(!e)return;let t=v.currentModel||``;e.textContent=t,e.title=t,e.style.display=t?``:`none`}var Um=new Set,Wm=0;function Gm(){let e=document.getElementById(`workdirTag`);e&&(e.dataset.locked=Rr(v.activeSessionId)?`true`:`false`)}async function Km(){let e=++Wm,n=document.getElementById(`workdirTag`),i=document.getElementById(`workdirTagName`);if(!n||!i)return;let a=v.activeSessionId||null,o=Array.isArray(v.enabledTools)&&v.enabledTools.includes(`agent_exec`);if(v.agentPlatform?.connected!==!0||!o){n.style.display=`none`;return}let c=null;try{c=await p(a)}catch(e){r.debug(`[WorkdirTag] resolve failed:`,e&&e.message)}if(e!==Wm)return;let l=c&&c.workdir||``;if(!l){n.style.display=`none`;return}n.style.display=``,i.textContent=s(l,{homeDir:v.agentPlatform?.homeDir||``}),Gm();try{let{getWorkspaceRoot:e}=await E(async()=>{let{getWorkspaceRoot:e}=await import(`./workspace-manager-Cd4F0wEB.js`).then(e=>e.j);return{getWorkspaceRoot:e}},__vite__mapDeps([8,1,2,3])),t=await e(a),i=!!(t&&t!==l);i&&c.scope==="default"?(n.dataset.invalid=`false`,Qp(a).then(e=>{e&&Km()}).catch(e=>r.debug(`[WorkdirTag] reconcile failed:`,e&&e.message))):n.dataset.invalid=i?`true`:`false`}catch{n.dataset.invalid=`false`}if(e===Wm&&(n.title=`${l}${c.scope===`session`?t(`workdirTag.sessionScope`):t(`workdirTag.defaultScope`)}${n.dataset.invalid===`true`?t(`workdirTag.pathMissing`):``}`,c.boundWorkdir&&c.scope==="default")){let e=`${a||``}::${c.agentId||``}`;Um.has(e)||(Um.add(e),A(t(`workdirTag.agentSwitched`),`warning`))}}function qm(){let e=document.getElementById(`workdirTag`);e&&(e.setAttribute(`aria-label`,t(`workdirTag.tagHint`)),e.addEventListener(`click`,async e=>{if(e.stopPropagation(),Rr(v.activeSessionId)){Gm(),A(t(`workdirTag.lockedHint`),`warning`);return}Gm();let{showSwitchWorkdirDialog:n}=await E(async()=>{let{showSwitchWorkdirDialog:e}=await import(`./context-indicator-C9LYk-kV.js`).then(e=>e.ln);return{showSwitchWorkdirDialog:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]));await n({sessionId:v.activeSessionId||null})})),Km(),document.addEventListener(`session-switched`,()=>{Km()}),document.addEventListener(`session-workdir-changed`,()=>{Km()}),document.addEventListener(`agent-model-changed`,()=>{Km()}),document.addEventListener(`agent-tools-changed`,()=>{Km()}),document.addEventListener(`generating-state-changed`,()=>{Gm()}),document.addEventListener(`generation-ended`,()=>{Gm()}),In(()=>{Gm()})}function Jm(){let e=document.getElementById(`currentModelTag`);e&&e.addEventListener(`click`,e=>{e.stopPropagation(),document.getElementById(`tempDisplay`)?.click()}),Hm()}function Ym(e){let t=0;document.querySelectorAll(`.model-option`).forEach(n=>{n.dataset.value===e?(n.classList.add(`selected`),n.querySelector(`.model-option-check`).textContent=`✓`,t=parseInt(n.dataset.contextWindow,10)||0):(n.classList.remove(`selected`),n.querySelector(`.model-option-check`).textContent=``)});let n=document.getElementById(`modelSelectValue`);n&&e&&(n.textContent=e);let r=document.getElementById(`modelSelectCtxBadge`);r&&(t>0?(r.textContent=g(t),r.style.display=``):r.style.display=`none`),Hm()}function Xm(e,n){let r=document.getElementById(`tempDropdown`);if(!r){typeof n==`function`&&n();return}let i=r.querySelector(`.model-section`),a=[];if((Array.isArray(e)?e:[]).forEach(e=>{typeof e==`string`?a.push({name:e,contextWindow:0}):e&&typeof e==`object`&&e.name&&a.push({name:e.name,contextWindow:e.contextWindow||0})}),i){i.innerHTML=`
604
+ Are you sure you want to stop the agent service? You will not be able to connect and will need to manually restart it.`,stopAgentTitle:`Stop Agent`,agentStopped:`Agent service stopped, agent is offline`,stopFailed:`Stop failed: {error}`,stopRequestFailed:`Stop request failed: {error}`,agentStatusRefreshed:`Agent status refreshed`,deleteAgentTitle:`Delete Agent`,deleteAgentConfirm:`Are you sure you want to delete agent "{name}"? This action cannot be undone.`,welcomeTitle:`Start a Conversation`,welcomeSubtitle:`Enter your question and the AI assistant will help you`,sendBtnStop:`Stop generating`,sendBtnSend:`Send`,defaultPromptImage:`Please look at the attached image and describe what you see`,defaultPromptFile:`Please read the attached file and summarize the key points`,defaultPromptAttachments:`Please review the attached image and file and summarize the key points`,defaultPromptKnowledge:`Please answer based on the knowledge base content I referenced`,defaultKnowledgeQuery:`key points summary`,defaultPromptPage:`Please summarize the main content of this page`,defaultPromptSelection:`Please continue based on the content I provided`,defaultPromptContext:`Please continue based on the context I provided`,imageNotEnabled:`Image recognition not enabled, image attached as file`,screenshotFailed:`Screenshot failed, please retry`,auditCategoryAuth:`Auth`,auditCategoryFs:`File`,auditCategoryExec:`Command`,auditCategorySecurity:`Security`,auditCategorySystem:`System`,auditDetailSeparator:`; `,auditQueryFailed:`Query failed: {error}`,auditLoadFailed:`Load failed: {error}`,auditNoMatch:`No matching audit logs`,auditEmpty:`No audit logs`,clearStatsConfirm:`Are you sure you want to clear all tool usage stats? This action cannot be undone.`,clearStatsTitle:`Clear Stats`,toolStatsSummary:`Used {used} tools, unused {unused} tools`,toolStatsLoadFailed:`Load failed`,toolNameDescSeparator:`: `}}),window.showCustomConfirm=function(e,n=t(`sidePanel.confirmAction`)){return new Promise(t=>{let r=document.getElementById(`customConfirmOverlay`),i=document.getElementById(`customConfirmTitle`),a=document.getElementById(`customConfirmMessage`),o=document.getElementById(`customConfirmCancelBtn`),s=document.getElementById(`customConfirmOkBtn`);if(!r||!i||!a||!o||!s){t(confirm(e));return}let c=()=>{r.style.display=`none`,s.removeEventListener(`click`,l),o.removeEventListener(`click`,u),r.removeEventListener(`click`,d),document.removeEventListener(`keydown`,f)},l=()=>{c(),t(!0)},u=()=>{c(),t(!1)},d=e=>{e.target===r&&(c(),t(!1))},f=e=>{e.key===`Enter`?(e.preventDefault(),e.stopPropagation(),l()):e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),u())};i.textContent=n,a.innerHTML=e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`).replace(/'/g,`&#39;`).replace(/\n/g,`<br>`),r.style.display=`flex`,s.addEventListener(`click`,l),o.addEventListener(`click`,u),r.addEventListener(`click`,d),document.addEventListener(`keydown`,f),requestAnimationFrame(()=>s.focus())})},chrome.storage.onChanged.addListener((e,t)=>{t===`local`&&e.chatAutoCompaction&&(v.chatConfig.autoCompaction=e.chatAutoCompaction.newValue===!0,Fm(),r.debug(`[SidePanel] auto-compaction config updated:`,v.chatConfig.autoCompaction)),t===`local`&&e.chatPersistSummaryToMemory&&(v.chatConfig.persistSummaryToMemory=e.chatPersistSummaryToMemory.newValue!==!1,Im(),r.debug(`[SidePanel] persist-summary config updated:`,v.chatConfig.persistSummaryToMemory)),t===`local`&&e.chatMaxMemoryMessages&&(v.chatConfig.maxMemoryMessages=e.chatMaxMemoryMessages.newValue,Pm(),r.debug(`[SidePanel] memory limitconfiguration updated:`,v.chatConfig.maxMemoryMessages)),t===`local`&&e.queueAutoCarry&&(v.chatConfig.queueAutoCarry=e.queueAutoCarry.newValue!==!1,r.debug(`[SidePanel] queue auto-carry updated:`,v.chatConfig.queueAutoCarry)),t===`local`&&e.queueAutoCarryEveryNIterations&&(v.chatConfig.queueAutoCarryEveryNIterations=e.queueAutoCarryEveryNIterations.newValue,r.debug(`[SidePanel] queue auto-carry interval updated:`,v.chatConfig.queueAutoCarryEveryNIterations))});function Pm(){let e=document.getElementById(`memoryLimitLabel`);e&&(v.chatConfig.maxMemoryMessages!==null&&v.chatConfig.maxMemoryMessages!==void 0&&v.chatConfig.maxMemoryMessages>0?e.textContent=v.chatConfig.maxMemoryMessages:e.textContent=t(`sidePanel.memoryLimitAll`),e.title=t(`sidePanel.memoryLimitTitle`))}function Fm(){let e=document.getElementById(`autoCompactBtn`);e&&(e.checked=v.chatConfig.autoCompaction===!0)}function Im(){let e=document.getElementById(`persistSummaryBtn`);e&&(e.checked=v.chatConfig.persistSummaryToMemory!==!1)}function Lm(e){e.preventDefault(),e.stopPropagation();let t=document.getElementById(`memoryLimitDropdown`);if(t.classList.toggle(`show`),t.classList.contains(`show`)){let e=v.chatConfig.maxMemoryMessages;t.querySelectorAll(`.memory-limit-option`).forEach(t=>{t.classList.remove(`selected`);let n=parseInt(t.dataset.value);(e===null&&n===0||e!==null&&e>0&&n===e)&&t.classList.add(`selected`)});let n=t.querySelector(`#memoryLimitInput`);e!==null&&e>0?n.value=e:n.value=``}}function Rm(){let e=document.getElementById(`memoryLimitDropdown`),n=document.getElementById(`memoryLimitLabel`),r=e?.querySelector(`#memoryLimitInput`);if(!e||!n)return;Pm(),n.addEventListener(`click`,Lm);let i=document.getElementById(`autoCompactBtn`);i&&(i.checked=v.chatConfig.autoCompaction===!0,i.addEventListener(`change`,()=>{let e=i.checked;chrome.storage.local.set({chatAutoCompaction:e},()=>{v.chatConfig.autoCompaction=e,A(t(`sidePanel.configUpdated`),`success`)})}));let a=document.getElementById(`persistSummaryBtn`);a&&(a.checked=v.chatConfig.persistSummaryToMemory!==!1,a.addEventListener(`change`,()=>{let e=a.checked;chrome.storage.local.set({chatPersistSummaryToMemory:e},()=>{v.chatConfig.persistSummaryToMemory=e,A(t(`sidePanel.configUpdated`),`success`)})}));let o=e.querySelectorAll(`.memory-limit-option`);o.forEach(e=>{e.addEventListener(`click`,n=>{n.stopPropagation();let i=parseInt(e.dataset.value),a=i===0?null:i;o.forEach(e=>e.classList.remove(`selected`)),e.classList.add(`selected`),r&&(r.value=i===0?``:i),chrome.storage.local.set({chatMaxMemoryMessages:a},()=>{v.chatConfig.maxMemoryMessages=a,Pm(),A(t(`sidePanel.configUpdated`),`success`)})})}),r&&(r.addEventListener(`click`,e=>e.stopPropagation()),r.addEventListener(`mousedown`,e=>e.stopPropagation()),r.addEventListener(`change`,e=>{e.stopPropagation();let n=e.target.value.trim(),r=n&&parseInt(n)>0?parseInt(n):null;o.forEach(e=>e.classList.remove(`selected`)),chrome.storage.local.set({chatMaxMemoryMessages:r},()=>{v.chatConfig.maxMemoryMessages=r,Pm(),A(t(`sidePanel.configUpdated`),`success`)})})),document.getElementById(`memoryLimitConfigEntry`)?.addEventListener(`click`,()=>{chrome.runtime.sendMessage({type:`OPEN_OPTIONS_PAGE`,hash:`memory`})}),document.addEventListener(`click`,t=>{!e.contains(t.target)&&t.target!==n&&e.classList.remove(`show`)})}async function zm(e){if(v.activeAgentId&&v.activeAgentId!=="default")try{let{updateAgent:t}=await E(async()=>{let{updateAgent:e}=await import(`./agent-store-grxR4rg1.js`).then(e=>e.t);return{updateAgent:e}},__vite__mapDeps([7,1,2,3]));await t(v.activeAgentId,{model:e})}catch{}else chrome.storage.local.set({modelName:e}),ue(e)}async function Bm(){try{let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),t=Nm(e.pairedAgents),n=e.activeAgentId,r=t.find(e=>e.id===n&&!e.disabled);if(!r){v.agentPlatform={connected:!1},$(v.agentPlatform);return}if(r.token)try{let e=await fetch(`${r.url}/api/status/detail`,{cache:`no-cache`,headers:{Authorization:`Bearer ${r.token}`}});if(e.ok){let t=await e.json();if(t.success){v.agentPlatform={platformName:t.platformName||`Unknown`,platform:t.platform||`unknown`,arch:t.arch||`unknown`,shell:t.shell||`/bin/sh`,homeDir:t.homeDir||``,workdir:t.workdir||``,connected:!0},t.version&&v.agentVersions.set(n,t.version),t.workdir&&v.agentWorkdirs.set(n,t.workdir),t.homeDir&&v.agentHomeDirs.set(n,t.homeDir);let e=gh(t.platformName||t.platform,t.arch);e&&v.agentSystemInfos.set(n,e)}else v.agentPlatform={connected:!1}}else v.agentPlatform={connected:!1}}catch{v.agentPlatform={connected:!1}}else v.agentPlatform={connected:!1};$(v.agentPlatform),si()}catch{}}async function Vm(e,t,n){if(v.activeAgentId&&v.activeAgentId!=="default")try{let{updateAgent:n}=await E(async()=>{let{updateAgent:e}=await import(`./agent-store-grxR4rg1.js`).then(e=>e.t);return{updateAgent:e}},__vite__mapDeps([7,1,2,3]));await n(v.activeAgentId,{temperature:e,topP:t})}catch{}else chrome.storage.local.set({temperature:e,topP:t,selectedTempIndex:n})}function Hm(){let e=document.getElementById(`currentModelTag`);if(!e)return;let t=v.currentModel||``;e.textContent=t,e.title=t,e.style.display=t?``:`none`}var Um=new Set,Wm=0;function Gm(){let e=document.getElementById(`workdirTag`);e&&(e.dataset.locked=Rr(v.activeSessionId)?`true`:`false`)}async function Km(){let e=++Wm,n=document.getElementById(`workdirTag`),i=document.getElementById(`workdirTagName`);if(!n||!i)return;let a=v.activeSessionId||null,o=Array.isArray(v.enabledTools)&&v.enabledTools.includes(`agent_exec`);if(v.agentPlatform?.connected!==!0||!o){n.style.display=`none`;return}let c=null;try{c=await p(a)}catch(e){r.debug(`[WorkdirTag] resolve failed:`,e&&e.message)}if(e!==Wm)return;let l=c&&c.workdir||``;if(!l){n.style.display=`none`;return}n.style.display=``,i.textContent=s(l,{homeDir:v.agentPlatform?.homeDir||``}),Gm();try{let{getWorkspaceRoot:e}=await E(async()=>{let{getWorkspaceRoot:e}=await import(`./workspace-manager-Cd4F0wEB.js`).then(e=>e.j);return{getWorkspaceRoot:e}},__vite__mapDeps([8,1,2,3])),t=await e(a),i=!!(t&&t!==l);i&&c.scope==="default"?(n.dataset.invalid=`false`,Qp(a).then(e=>{e&&Km()}).catch(e=>r.debug(`[WorkdirTag] reconcile failed:`,e&&e.message))):n.dataset.invalid=i?`true`:`false`}catch{n.dataset.invalid=`false`}if(e===Wm&&(n.title=`${l}${c.scope===`session`?t(`workdirTag.sessionScope`):t(`workdirTag.defaultScope`)}${n.dataset.invalid===`true`?t(`workdirTag.pathMissing`):``}`,c.boundWorkdir&&c.scope==="default")){let e=`${a||``}::${c.agentId||``}`;Um.has(e)||(Um.add(e),A(t(`workdirTag.agentSwitched`),`warning`))}}function qm(){let e=document.getElementById(`workdirTag`);e&&(e.setAttribute(`aria-label`,t(`workdirTag.tagHint`)),e.addEventListener(`click`,async e=>{if(e.stopPropagation(),Rr(v.activeSessionId)){Gm(),A(t(`workdirTag.lockedHint`),`warning`);return}Gm();let{showSwitchWorkdirDialog:n}=await E(async()=>{let{showSwitchWorkdirDialog:e}=await import(`./context-indicator-u4eOUhKC.js`).then(e=>e.ln);return{showSwitchWorkdirDialog:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]));await n({sessionId:v.activeSessionId||null})})),Km(),document.addEventListener(`session-switched`,()=>{Km()}),document.addEventListener(`session-workdir-changed`,()=>{Km()}),document.addEventListener(`agent-model-changed`,()=>{Km()}),document.addEventListener(`agent-tools-changed`,()=>{Km()}),document.addEventListener(`generating-state-changed`,()=>{Gm()}),document.addEventListener(`generation-ended`,()=>{Gm()}),In(()=>{Gm()})}function Jm(){let e=document.getElementById(`currentModelTag`);e&&e.addEventListener(`click`,e=>{e.stopPropagation(),document.getElementById(`tempDisplay`)?.click()}),Hm()}function Ym(e){let t=0;document.querySelectorAll(`.model-option`).forEach(n=>{n.dataset.value===e?(n.classList.add(`selected`),n.querySelector(`.model-option-check`).textContent=`✓`,t=parseInt(n.dataset.contextWindow,10)||0):(n.classList.remove(`selected`),n.querySelector(`.model-option-check`).textContent=``)});let n=document.getElementById(`modelSelectValue`);n&&e&&(n.textContent=e);let r=document.getElementById(`modelSelectCtxBadge`);r&&(t>0?(r.textContent=g(t),r.style.display=``):r.style.display=`none`),Hm()}function Xm(e,n){let r=document.getElementById(`tempDropdown`);if(!r){typeof n==`function`&&n();return}let i=r.querySelector(`.model-section`),a=[];if((Array.isArray(e)?e:[]).forEach(e=>{typeof e==`string`?a.push({name:e,contextWindow:0}):e&&typeof e==`object`&&e.name&&a.push({name:e.name,contextWindow:e.contextWindow||0})}),i){i.innerHTML=`
605
605
  <div class="model-section-title" data-i18n="model.selectModel">${t(`model.selectModel`)}</div>
606
606
  <div class="section-select" id="modelSelect">
607
607
  <div class="section-select-row" id="modelSelectRow">
@@ -666,7 +666,7 @@ Are you sure you want to stop the agent service? You will not be able to connect
666
666
  </div>
667
667
  <h2>${t(`sidePanel.welcomeTitle`)}</h2>
668
668
  <p>${t(`sidePanel.welcomeSubtitle`)}</p>
669
- `,a.appendChild(e)}if(r.debug(`[SidePanel] session-switched: pendingTask?`,l,`pendingSessionIds:`,[...v.pendingCallApiSessionIds],`activeSessionId:`,n,`hasCancelApi:`,!!v.pendingCancelApi),l&&(r.debug(`[SidePanel] switch back tobackground task session,rebuildstreamingoutput element`),xr(n)),qa(n),!e.detail?.skipScrollRestore){let e=`scrollPosition_`+(n||`default`);chrome.storage.local.get([e],t=>{t[e]!==void 0&&setTimeout(async()=>{let n=document.getElementById(`chatContainer`);n&&(n.scrollTop=t[e]);let{updateScrollButtonState:r}=await E(async()=>{let{updateScrollButtonState:e}=await import(`./context-indicator-C9LYk-kV.js`).then(e=>e.pt);return{updateScrollButtonState:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]));r()},150)})}}),document.addEventListener(`session-cache-invalidate`,e=>{let{sessionId:t}=e.detail||{};t&&kh(t)}),document.querySelectorAll(`.model-option`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation();let n=e.dataset.value;v.currentModel=n,Ym(n),zm(n),Gr()})}),document.addEventListener(`agent-model-changed`,()=>{Ym(v.currentModel);let e=document.getElementById(`tempSlider`),t=document.getElementById(`tempNumberInput`),n=document.getElementById(`tempIconValue`);e&&(e.value=v.temperature),t&&(t.value=v.temperature.toFixed(2)),n&&(n.textContent=v.temperature.toFixed(2)),_()}),document.addEventListener(`click`,e=>{let t=document.getElementById(`promptDropdown`),n=document.getElementById(`promptSelector`),r=document.getElementById(`agentAtSelector`),i=document.getElementById(`selectionFloatingMenu`);n.contains(e.target)||(t.classList.remove(`show`),Mt()),r&&!r.contains(e.target)&&on();let a=document.getElementById(`fileAtSelector`);if(a&&!a.contains(e.target)&&of(),i&&!i.contains(e.target)){let t=window.getSelection(),n=fs(e.target),r=t&&!t.isCollapsed&&fs(t.anchorNode);(!n||!r)&&window.hideFloatingMenu()}});let w=document.getElementById(`stopCompanionBtn`);function se(){let e=!!(a&&a.value&&a.value.trim())||Xr();return v.isGenerating&&e}function ce(){a&&a.value&&a.value.trim();let e=v.isGenerating,n=se();s.classList.toggle(`queue-mode`,n),s.classList.toggle(`stop-mode`,e&&!n),n?(s.innerHTML=`<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h11"/><path d="M3 12h11"/><path d="M3 18h7"/><path d="M17.5 10v8"/><path d="M14.5 15.5L17.5 18.5l3-3"/></svg>`,s.title=t(`queue.enqueueBtn`)):e?(s.innerHTML=`<svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect></svg>`,s.title=t(`sidePanel.sendBtnStop`)):(s.innerHTML=`<svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor"><path d="M12 4l-1.41 1.41L16.17 11H4v2h12.17l-5.58 5.59L12 20l8-8-8-8z"/></svg>`,s.title=t(`sidePanel.sendBtnSend`)),s.disabled=!1,s.style.opacity=``,s.style.cursor=``,w&&(w.style.display=n?``:`none`,w.disabled=!1,w.style.opacity=``,w.style.cursor=``)}s.addEventListener(`click`,()=>{if(!v.isGenerating){Fi();return}se()?gn():Ir(s)}),w?.addEventListener(`click`,()=>Ir(w));function T(e){if(!v.isGenerating)return!1;let n=v.activeSessionId;return n?On(n)?(Fn(n),Ir(w&&w.style.display!==`none`?w:e||s)?(A(t(`queue.stopAndSendStarted`),`success`,2500),!0):(Yt(n),!0)):(A(t(`queue.stopAndSendEmpty`),`warning`,3e3),!1):!1}function ue(e,{isPrimarySend:t=!1}={}){if(!e)return;let n=()=>t&&se();e.addEventListener(`contextmenu`,t=>{n()||!v.isGenerating||!On(v.activeSessionId)||(t.preventDefault(),T(e))});let r=null,i=()=>{r&&=(clearTimeout(r),null)};e.addEventListener(`pointerdown`,t=>{t.pointerType===`mouse`&&t.button!==0||n()||!v.isGenerating||!On(v.activeSessionId)||(i(),r=setTimeout(()=>{r=null,T(e)},600))});for(let t of[`pointerup`,`pointerleave`,`pointercancel`])e.addEventListener(t,i)}ue(s,{isPrimarySend:!0}),ue(w),document.addEventListener(`queue-stop-and-send`,()=>{T(w&&w.style.display!==`none`?w:s)}),document.addEventListener(`generating-state-changed`,ce),a.addEventListener(`input`,ce),document.addEventListener(`input-attachments-changed`,ce),document.addEventListener(`voice-draft-written`,ce);let de=document.getElementById(`shortcutsBtn`),D=document.getElementById(`shortcutsModal`),fe=document.getElementById(`shortcutsCloseBtn`);function pe(){D&&(D.style.display=`flex`)}function me(){D&&(D.style.display=`none`)}de&&de.addEventListener(`click`,e=>{e.stopPropagation(),pe();let t=document.getElementById(`headerMoreDropdown`);t&&t.classList.remove(`show`)}),fe&&fe.addEventListener(`click`,me),D&&D.addEventListener(`click`,e=>{e.target===D&&me()});let he=ds();Sn(),$n({adjustInputHeight:ee}).catch(e=>{r.warn(`[SidePanel] initVoiceInput failed:`,e?.message||e)}),document.addEventListener(`keydown`,e=>{if((e.ctrlKey||e.metaKey)&&e.key===`t`){e.preventDefault();let t=document.getElementById(`toolsPopup`);t&&t.style.display!==`none`?Ai():Ri()}if(e.key===`Escape`&&Kn()){e.preventDefault();return}if(!(e.key===`Escape`&&he.handleEscape())){if(e.key===`Escape`&&D&&D.style.display!==`none`){me();return}if(e.altKey&&e.code===`Slash`){e.preventDefault(),pe();return}if(e.altKey&&!e.shiftKey&&e.code===`KeyS`&&!e.ctrlKey&&!e.metaKey){e.preventDefault(),Li();return}if(e.altKey&&e.shiftKey&&e.code===`KeyS`&&!e.ctrlKey&&!e.metaKey){e.preventDefault(),Dr();return}if(Gt(e)){e.preventDefault(),cn();return}if(e.altKey&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&e.code===`KeyN`){e.preventDefault(),fi();return}if(e.altKey&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&e.code===`KeyW`){e.preventDefault(),jr();return}if(e.altKey&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&e.code===`KeyE`){e.preventDefault();let t=document.querySelectorAll(`#chatContainer .message.user`),n=t[t.length-1];if(n){Wt(n);let e=document.getElementById(`userInput`);e&&e.focus()}return}if(e.altKey&&(e.key===`ArrowUp`||e.key===`ArrowDown`)){e.preventDefault();let t=e.key===`ArrowUp`?`prev`:`next`;he.jumpToMessage(t,e.ctrlKey||e.metaKey),he.updateActiveQuestion();return}}}),a.addEventListener(`keydown`,e=>{let t=document.getElementById(`promptSelector`),n=document.getElementById(`promptDropdown`),r=document.getElementById(`agentAtSelector`),i=document.getElementById(`agentAtDropdown`);if(r.style.display!==`none`&&i.classList.contains(`show`)){let t=document.getElementById(`agentAtTabs`),n=t&&t.classList.contains(`merged-mode`);if(!n&&e.key===`Tab`){e.preventDefault();let t=Array.from(document.querySelectorAll(`#agentAtTabs .prompt-tab`)).map(e=>e.dataset.tab),n=e=>{let t=document.querySelector(`#agentAtTabs .prompt-tab[data-tab="${e}"]`);return!!t&&t.style.display!==`none`},r=t.indexOf(Dt);for(let e=0;e<t.length;e++)if(r=(r+1)%t.length,n(t[r])){di(t[r]);break}return}let r,i;n?(r=document.getElementById(`agentAtList`),i=v.selectedAgentAtIndex):Dt===`pages`?(r=document.getElementById(`agentPageList`),i=v.selectedPageIndex):Dt===`proxies`?(r=document.getElementById(`agentProxyList`),i=v.selectedProxyAtIndex):Dt===`knowledge`?(r=document.getElementById(`agentKnowledgeList`),i=v.selectedKnowledgeAtIndex):(r=document.getElementById(`agentAtList`),i=v.selectedAgentAtIndex);let a=r?r.querySelectorAll(`.prompt-item`):[],o=a.length;if(o!==0){if(e.key===`ArrowDown`){e.preventDefault();let t=i<0?0:(i+1)%o;n?(v.selectedAgentAtIndex=t,Ei(a)):Dt===`proxies`?(v.selectedProxyAtIndex=t,Ei(a)):Dt===`knowledge`?(v.selectedKnowledgeAtIndex=t,Ei(a)):Dt===`pages`?(v.selectedPageIndex=t,aa(a)):(v.selectedAgentAtIndex=t,Ei(a));return}else if(e.key===`ArrowUp`){e.preventDefault();let t=i<0||i===0?o-1:i-1;n?(v.selectedAgentAtIndex=t,Ei(a)):Dt===`proxies`?(v.selectedProxyAtIndex=t,Ei(a)):Dt===`knowledge`?(v.selectedKnowledgeAtIndex=t,Ei(a)):Dt===`pages`?(v.selectedPageIndex=t,aa(a)):(v.selectedAgentAtIndex=t,Ei(a));return}else if(e.key===`Enter`&&i>=0){e.preventDefault(),a[i].click(),(e.ctrlKey||e.metaKey)&&on();return}else if(e.key===`Escape`){on();return}}}let o=document.getElementById(`fileAtSelector`),s=document.getElementById(`fileAtDropdown`);if(o&&s&&o.style.display!==`none`&&s.classList.contains(`show`)){let t=document.getElementById(`fileAtList`),n=t?t.querySelectorAll(`.prompt-item`):[],r=n.length;if(e.key===`ArrowDown`||e.key===`ArrowUp`){e.preventDefault(),r>0&&(v.selectedFileAtIndex=e.key===`ArrowDown`?v.selectedFileAtIndex<0?0:(v.selectedFileAtIndex+1)%r:v.selectedFileAtIndex<0||v.selectedFileAtIndex===0?r-1:v.selectedFileAtIndex-1,df(n));return}if(e.key===`Enter`&&r>0&&v.selectedFileAtIndex>=0){e.preventDefault(),n[v.selectedFileAtIndex].click();return}if(e.key===`Escape`){e.preventDefault(),of();return}}if(t.style.display!==`none`&&n.classList.contains(`show`)){if(v.showMergedList){let t=n.querySelectorAll(`#promptList .prompt-item`),r=t.length;if(e.key===`ArrowDown`){e.preventDefault(),v.selectedPromptIndex<0?v.selectedPromptIndex=0:v.selectedPromptIndex=(v.selectedPromptIndex+1)%r,Dn(t);return}if(e.key===`ArrowUp`){e.preventDefault(),v.selectedPromptIndex<0||v.selectedPromptIndex===0?v.selectedPromptIndex=r-1:--v.selectedPromptIndex,Dn(t);return}if(e.key===`Enter`&&v.selectedPromptIndex>=0){e.preventDefault();let n=t[v.selectedPromptIndex];n.dataset.type===`skill`||n.dataset.type===`mcp`?(n.click(),(e.ctrlKey||e.metaKey)&&Mt()):e.ctrlKey||e.metaKey?$r(n.dataset.code):bt(n.dataset.code);return}if(e.key===`Escape`){Mt();return}return}if(v.activeDropdownTab===`skills`){let t=n.querySelectorAll(`#skillList .skill-list-item`),r=t.length;if(e.key===`ArrowDown`){e.preventDefault(),v.selectedSkillIndex<0?v.selectedSkillIndex=0:v.selectedSkillIndex=(v.selectedSkillIndex+1)%r,Wi(t);return}if(e.key===`ArrowUp`){e.preventDefault(),v.selectedSkillIndex<0||v.selectedSkillIndex===0?v.selectedSkillIndex=r-1:--v.selectedSkillIndex,Wi(t);return}if(e.key===`Enter`&&v.selectedSkillIndex>=0){e.preventDefault(),t[v.selectedSkillIndex].click(),(e.ctrlKey||e.metaKey)&&Mt();return}if(e.key===`Escape`){Mt();return}if(e.key===`Tab`){e.preventDefault();let t=document.getElementById(`mcpTab`);t&&t.style.display!==`none`?Rn(`mcp`):Rn(`prompts`);return}return}if(v.activeDropdownTab===`mcp`){let t=n.querySelectorAll(`#mcpList .mcp-list-item`),r=t.length;if(e.key===`ArrowDown`){e.preventDefault(),v.selectedMcpServiceIndex<0?v.selectedMcpServiceIndex=0:v.selectedMcpServiceIndex=(v.selectedMcpServiceIndex+1)%r,Ot(t);return}if(e.key===`ArrowUp`){e.preventDefault(),v.selectedMcpServiceIndex<0||v.selectedMcpServiceIndex===0?v.selectedMcpServiceIndex=r-1:--v.selectedMcpServiceIndex,Ot(t);return}if(e.key===`Enter`&&v.selectedMcpServiceIndex>=0){e.preventDefault(),t[v.selectedMcpServiceIndex].click(),(e.ctrlKey||e.metaKey)&&Mt();return}if(e.key===`Escape`){Mt();return}if(e.key===`Tab`){e.preventDefault(),Rn(`prompts`);return}return}let t=n.querySelectorAll(`#promptList .prompt-item`),r=t.length;if(e.key===`Tab`){let t=document.getElementById(`skillsTab`),n=document.getElementById(`mcpTab`);if(t&&t.style.display!==`none`){e.preventDefault(),Rn(`skills`);return}if(n&&n.style.display!==`none`){e.preventDefault(),Rn(`mcp`);return}}if(r!==0&&e.key===`ArrowDown`){e.preventDefault(),v.selectedPromptIndex<0?v.selectedPromptIndex=0:v.selectedPromptIndex=(v.selectedPromptIndex+1)%r,Dn(t);return}if(e.key===`ArrowUp`){e.preventDefault(),v.selectedPromptIndex<0||v.selectedPromptIndex===0?v.selectedPromptIndex=r-1:--v.selectedPromptIndex,Dn(t);return}if(e.key===`Enter`&&(e.ctrlKey||e.metaKey)&&v.selectedPromptIndex>=0){e.preventDefault();let n=t[v.selectedPromptIndex].dataset.code;$r(n);return}if(e.key===`Enter`&&v.selectedPromptIndex>=0){e.preventDefault();let n=t[v.selectedPromptIndex].dataset.code;bt(n);return}if(e.key===`Escape`){Mt();return}}if(e.key===`Escape`){v.inputHistoryIndex>=0&&(v.inputHistoryIndex=-1),a.value&&(a.value=``,a.style.height=`auto`,a.dispatchEvent(new Event(`input`))),e.preventDefault();return}let c=t.style.display!==`none`&&n.classList.contains(`show`),l=r.style.display!==`none`&&i.classList.contains(`show`),u=o.style.display!==`none`&&s.classList.contains(`show`);if(e.key===`ArrowUp`&&v.inputHistoryIndex===-1&&!a.value.trim()&&!Xr()&&zp()){e.preventDefault();return}if(!c&&!l&&!u){let t=gp({key:e.key,value:a.value,caret:a.selectionStart,history:v.inputHistory,index:v.inputHistoryIndex});if(t.handled){e.preventDefault(),v.inputHistoryIndex=t.index,a.value=t.value,a.dispatchEvent(new Event(`input`)),a.setSelectionRange(t.value.length,t.value.length);return}}if(e.key===`Enter`&&!e.shiftKey){if(v.isComposing)return;if(e.preventDefault(),of(),v.isGenerating){if(e.altKey){$t(a.value);return}gn();return}Fi()}}),a.addEventListener(`compositionstart`,()=>{v.isComposing=!0}),a.addEventListener(`compositionend`,()=>{v.isComposing=!1}),a.addEventListener(`paste`,e=>{let t=e.clipboardData?.items;if(t)for(let n of t){if(n.type.startsWith(`image/`)&&v.enableImageInput){e.preventDefault();let t=n.getAsFile();t&&kt(t);break}if(n.kind===`file`&&v.enableFileInput){e.preventDefault();let t=n.getAsFile();t&&yr([t]);break}}});let ge=document.getElementById(`fileAttachBtn`),_e=document.getElementById(`fileInput`);ge&&_e&&(ge.addEventListener(`click`,()=>{_e.click()}),_e.addEventListener(`change`,async()=>{if(_e.files.length>0){let e=Array.from(_e.files),n=e.filter(e=>e.type.startsWith(`image/`)),r=e.filter(e=>!e.type.startsWith(`image/`));if(n.length>0)if(v.enableImageInput)for(let e of n)await kt(e);else A(t(`sidePanel.imageNotEnabled`)),yr(n);r.length>0&&yr(r),_e.value=``}}));let ve=document.querySelector(`.input-wrapper`),ye=0;ve&&(ve.addEventListener(`dragenter`,e=>{e.preventDefault(),e.stopPropagation(),ye++,ve.classList.add(`drag-over`)}),ve.addEventListener(`dragleave`,e=>{e.preventDefault(),e.stopPropagation(),ye--,ye<=0&&(ye=0,ve.classList.remove(`drag-over`))}),ve.addEventListener(`dragover`,e=>{e.preventDefault(),e.stopPropagation()}),ve.addEventListener(`drop`,async e=>{e.preventDefault(),e.stopPropagation(),ye=0,ve.classList.remove(`drag-over`);let n=e.dataTransfer.getData(`application/x-workspace-file`);if(n){e.preventDefault();try{let{path:e}=JSON.parse(n);if(e){Kr([e]);return}}catch(e){r.warn(`[SidePanel] parse workspace dragdata failed:`,e)}}let i=Array.from(e.dataTransfer.files);if(i.length>0){e.preventDefault();let n=i.filter(e=>e.type.startsWith(`image/`)),r=i.filter(e=>!e.type.startsWith(`image/`));if(n.length>0)if(v.enableImageInput)for(let e of n)await kt(e);else A(t(`sidePanel.imageNotEnabled`)),yr(n);r.length>0&&yr(r);return}let o=e.dataTransfer.getData(`text/plain`);if(o&&(e.preventDefault(),a)){a.focus();let e=a.selectionStart??a.value.length,t=a.selectionEnd??a.value.length;a.value=a.value.slice(0,e)+o+a.value.slice(t),a.selectionStart=a.selectionEnd=e+o.length,a.dispatchEvent(new Event(`input`))}}));let be=document.getElementById(`screenshotBtn`);be&&be.addEventListener(`click`,async()=>{if(v.enableImageInput)try{await Li()}catch(e){r.error(`[SidePanel] screenshot failed:`,e),A(t(`sidePanel.screenshotFailed`))}}),Gi(),a.addEventListener(`wheel`,e=>{v.isScrolling=!0;let t=a.style.height||a.offsetHeight+`px`;a.style.height=t,a.scrollHeight<=a.clientHeight+10&&(e.preventDefault(),e.stopPropagation()),setTimeout(()=>{v.isScrolling=!1},100)},{passive:!1}),a.addEventListener(`input`,e=>{let t=a.value,n=document.getElementById(`promptSelector`),r=document.getElementById(`promptDropdown`);document.getElementById(`agentAtSelector`),document.getElementById(`agentAtDropdown`);let i=t.lastIndexOf(`/`),o=t.lastIndexOf(`@`),s=t.lastIndexOf(`$`),c=e=>{if(e===-1||e!==0&&t[e-1]!==`
669
+ `,a.appendChild(e)}if(r.debug(`[SidePanel] session-switched: pendingTask?`,l,`pendingSessionIds:`,[...v.pendingCallApiSessionIds],`activeSessionId:`,n,`hasCancelApi:`,!!v.pendingCancelApi),l&&(r.debug(`[SidePanel] switch back tobackground task session,rebuildstreamingoutput element`),xr(n)),qa(n),!e.detail?.skipScrollRestore){let e=`scrollPosition_`+(n||`default`);chrome.storage.local.get([e],t=>{t[e]!==void 0&&setTimeout(async()=>{let n=document.getElementById(`chatContainer`);n&&(n.scrollTop=t[e]);let{updateScrollButtonState:r}=await E(async()=>{let{updateScrollButtonState:e}=await import(`./context-indicator-u4eOUhKC.js`).then(e=>e.pt);return{updateScrollButtonState:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]));r()},150)})}}),document.addEventListener(`session-cache-invalidate`,e=>{let{sessionId:t}=e.detail||{};t&&kh(t)}),document.querySelectorAll(`.model-option`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation();let n=e.dataset.value;v.currentModel=n,Ym(n),zm(n),Gr()})}),document.addEventListener(`agent-model-changed`,()=>{Ym(v.currentModel);let e=document.getElementById(`tempSlider`),t=document.getElementById(`tempNumberInput`),n=document.getElementById(`tempIconValue`);e&&(e.value=v.temperature),t&&(t.value=v.temperature.toFixed(2)),n&&(n.textContent=v.temperature.toFixed(2)),_()}),document.addEventListener(`click`,e=>{let t=document.getElementById(`promptDropdown`),n=document.getElementById(`promptSelector`),r=document.getElementById(`agentAtSelector`),i=document.getElementById(`selectionFloatingMenu`);n.contains(e.target)||(t.classList.remove(`show`),Mt()),r&&!r.contains(e.target)&&on();let a=document.getElementById(`fileAtSelector`);if(a&&!a.contains(e.target)&&of(),i&&!i.contains(e.target)){let t=window.getSelection(),n=fs(e.target),r=t&&!t.isCollapsed&&fs(t.anchorNode);(!n||!r)&&window.hideFloatingMenu()}});let w=document.getElementById(`stopCompanionBtn`);function se(){let e=!!(a&&a.value&&a.value.trim())||Xr();return v.isGenerating&&e}function ce(){a&&a.value&&a.value.trim();let e=v.isGenerating,n=se();s.classList.toggle(`queue-mode`,n),s.classList.toggle(`stop-mode`,e&&!n),n?(s.innerHTML=`<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h11"/><path d="M3 12h11"/><path d="M3 18h7"/><path d="M17.5 10v8"/><path d="M14.5 15.5L17.5 18.5l3-3"/></svg>`,s.title=t(`queue.enqueueBtn`)):e?(s.innerHTML=`<svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect></svg>`,s.title=t(`sidePanel.sendBtnStop`)):(s.innerHTML=`<svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor"><path d="M12 4l-1.41 1.41L16.17 11H4v2h12.17l-5.58 5.59L12 20l8-8-8-8z"/></svg>`,s.title=t(`sidePanel.sendBtnSend`)),s.disabled=!1,s.style.opacity=``,s.style.cursor=``,w&&(w.style.display=n?``:`none`,w.disabled=!1,w.style.opacity=``,w.style.cursor=``)}s.addEventListener(`click`,()=>{if(!v.isGenerating){Fi();return}se()?gn():Ir(s)}),w?.addEventListener(`click`,()=>Ir(w));function T(e){if(!v.isGenerating)return!1;let n=v.activeSessionId;return n?On(n)?(Fn(n),Ir(w&&w.style.display!==`none`?w:e||s)?(A(t(`queue.stopAndSendStarted`),`success`,2500),!0):(Yt(n),!0)):(A(t(`queue.stopAndSendEmpty`),`warning`,3e3),!1):!1}function ue(e,{isPrimarySend:t=!1}={}){if(!e)return;let n=()=>t&&se();e.addEventListener(`contextmenu`,t=>{n()||!v.isGenerating||!On(v.activeSessionId)||(t.preventDefault(),T(e))});let r=null,i=()=>{r&&=(clearTimeout(r),null)};e.addEventListener(`pointerdown`,t=>{t.pointerType===`mouse`&&t.button!==0||n()||!v.isGenerating||!On(v.activeSessionId)||(i(),r=setTimeout(()=>{r=null,T(e)},600))});for(let t of[`pointerup`,`pointerleave`,`pointercancel`])e.addEventListener(t,i)}ue(s,{isPrimarySend:!0}),ue(w),document.addEventListener(`queue-stop-and-send`,()=>{T(w&&w.style.display!==`none`?w:s)}),document.addEventListener(`generating-state-changed`,ce),a.addEventListener(`input`,ce),document.addEventListener(`input-attachments-changed`,ce),document.addEventListener(`voice-draft-written`,ce);let de=document.getElementById(`shortcutsBtn`),D=document.getElementById(`shortcutsModal`),fe=document.getElementById(`shortcutsCloseBtn`);function pe(){D&&(D.style.display=`flex`)}function me(){D&&(D.style.display=`none`)}de&&de.addEventListener(`click`,e=>{e.stopPropagation(),pe();let t=document.getElementById(`headerMoreDropdown`);t&&t.classList.remove(`show`)}),fe&&fe.addEventListener(`click`,me),D&&D.addEventListener(`click`,e=>{e.target===D&&me()});let he=ds();Sn(),$n({adjustInputHeight:ee}).catch(e=>{r.warn(`[SidePanel] initVoiceInput failed:`,e?.message||e)}),document.addEventListener(`keydown`,e=>{if((e.ctrlKey||e.metaKey)&&e.key===`t`){e.preventDefault();let t=document.getElementById(`toolsPopup`);t&&t.style.display!==`none`?Ai():Ri()}if(e.key===`Escape`&&Kn()){e.preventDefault();return}if(!(e.key===`Escape`&&he.handleEscape())){if(e.key===`Escape`&&D&&D.style.display!==`none`){me();return}if(e.altKey&&e.code===`Slash`){e.preventDefault(),pe();return}if(e.altKey&&!e.shiftKey&&e.code===`KeyS`&&!e.ctrlKey&&!e.metaKey){e.preventDefault(),Li();return}if(e.altKey&&e.shiftKey&&e.code===`KeyS`&&!e.ctrlKey&&!e.metaKey){e.preventDefault(),Dr();return}if(Gt(e)){e.preventDefault(),cn();return}if(e.altKey&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&e.code===`KeyN`){e.preventDefault(),fi();return}if(e.altKey&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&e.code===`KeyW`){e.preventDefault(),jr();return}if(e.altKey&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&e.code===`KeyE`){e.preventDefault();let t=document.querySelectorAll(`#chatContainer .message.user`),n=t[t.length-1];if(n){Wt(n);let e=document.getElementById(`userInput`);e&&e.focus()}return}if(e.altKey&&(e.key===`ArrowUp`||e.key===`ArrowDown`)){e.preventDefault();let t=e.key===`ArrowUp`?`prev`:`next`;he.jumpToMessage(t,e.ctrlKey||e.metaKey),he.updateActiveQuestion();return}}}),a.addEventListener(`keydown`,e=>{let t=document.getElementById(`promptSelector`),n=document.getElementById(`promptDropdown`),r=document.getElementById(`agentAtSelector`),i=document.getElementById(`agentAtDropdown`);if(r.style.display!==`none`&&i.classList.contains(`show`)){let t=document.getElementById(`agentAtTabs`),n=t&&t.classList.contains(`merged-mode`);if(!n&&e.key===`Tab`){e.preventDefault();let t=Array.from(document.querySelectorAll(`#agentAtTabs .prompt-tab`)).map(e=>e.dataset.tab),n=e=>{let t=document.querySelector(`#agentAtTabs .prompt-tab[data-tab="${e}"]`);return!!t&&t.style.display!==`none`},r=t.indexOf(Dt);for(let e=0;e<t.length;e++)if(r=(r+1)%t.length,n(t[r])){di(t[r]);break}return}let r,i;n?(r=document.getElementById(`agentAtList`),i=v.selectedAgentAtIndex):Dt===`pages`?(r=document.getElementById(`agentPageList`),i=v.selectedPageIndex):Dt===`proxies`?(r=document.getElementById(`agentProxyList`),i=v.selectedProxyAtIndex):Dt===`knowledge`?(r=document.getElementById(`agentKnowledgeList`),i=v.selectedKnowledgeAtIndex):(r=document.getElementById(`agentAtList`),i=v.selectedAgentAtIndex);let a=r?r.querySelectorAll(`.prompt-item`):[],o=a.length;if(o!==0){if(e.key===`ArrowDown`){e.preventDefault();let t=i<0?0:(i+1)%o;n?(v.selectedAgentAtIndex=t,Ei(a)):Dt===`proxies`?(v.selectedProxyAtIndex=t,Ei(a)):Dt===`knowledge`?(v.selectedKnowledgeAtIndex=t,Ei(a)):Dt===`pages`?(v.selectedPageIndex=t,aa(a)):(v.selectedAgentAtIndex=t,Ei(a));return}else if(e.key===`ArrowUp`){e.preventDefault();let t=i<0||i===0?o-1:i-1;n?(v.selectedAgentAtIndex=t,Ei(a)):Dt===`proxies`?(v.selectedProxyAtIndex=t,Ei(a)):Dt===`knowledge`?(v.selectedKnowledgeAtIndex=t,Ei(a)):Dt===`pages`?(v.selectedPageIndex=t,aa(a)):(v.selectedAgentAtIndex=t,Ei(a));return}else if(e.key===`Enter`&&i>=0){e.preventDefault(),a[i].click(),(e.ctrlKey||e.metaKey)&&on();return}else if(e.key===`Escape`){on();return}}}let o=document.getElementById(`fileAtSelector`),s=document.getElementById(`fileAtDropdown`);if(o&&s&&o.style.display!==`none`&&s.classList.contains(`show`)){let t=document.getElementById(`fileAtList`),n=t?t.querySelectorAll(`.prompt-item`):[],r=n.length;if(e.key===`ArrowDown`||e.key===`ArrowUp`){e.preventDefault(),r>0&&(v.selectedFileAtIndex=e.key===`ArrowDown`?v.selectedFileAtIndex<0?0:(v.selectedFileAtIndex+1)%r:v.selectedFileAtIndex<0||v.selectedFileAtIndex===0?r-1:v.selectedFileAtIndex-1,df(n));return}if(e.key===`Enter`&&r>0&&v.selectedFileAtIndex>=0){e.preventDefault(),n[v.selectedFileAtIndex].click();return}if(e.key===`Escape`){e.preventDefault(),of();return}}if(t.style.display!==`none`&&n.classList.contains(`show`)){if(v.showMergedList){let t=n.querySelectorAll(`#promptList .prompt-item`),r=t.length;if(e.key===`ArrowDown`){e.preventDefault(),v.selectedPromptIndex<0?v.selectedPromptIndex=0:v.selectedPromptIndex=(v.selectedPromptIndex+1)%r,Dn(t);return}if(e.key===`ArrowUp`){e.preventDefault(),v.selectedPromptIndex<0||v.selectedPromptIndex===0?v.selectedPromptIndex=r-1:--v.selectedPromptIndex,Dn(t);return}if(e.key===`Enter`&&v.selectedPromptIndex>=0){e.preventDefault();let n=t[v.selectedPromptIndex];n.dataset.type===`skill`||n.dataset.type===`mcp`?(n.click(),(e.ctrlKey||e.metaKey)&&Mt()):e.ctrlKey||e.metaKey?$r(n.dataset.code):bt(n.dataset.code);return}if(e.key===`Escape`){Mt();return}return}if(v.activeDropdownTab===`skills`){let t=n.querySelectorAll(`#skillList .skill-list-item`),r=t.length;if(e.key===`ArrowDown`){e.preventDefault(),v.selectedSkillIndex<0?v.selectedSkillIndex=0:v.selectedSkillIndex=(v.selectedSkillIndex+1)%r,Wi(t);return}if(e.key===`ArrowUp`){e.preventDefault(),v.selectedSkillIndex<0||v.selectedSkillIndex===0?v.selectedSkillIndex=r-1:--v.selectedSkillIndex,Wi(t);return}if(e.key===`Enter`&&v.selectedSkillIndex>=0){e.preventDefault(),t[v.selectedSkillIndex].click(),(e.ctrlKey||e.metaKey)&&Mt();return}if(e.key===`Escape`){Mt();return}if(e.key===`Tab`){e.preventDefault();let t=document.getElementById(`mcpTab`);t&&t.style.display!==`none`?Rn(`mcp`):Rn(`prompts`);return}return}if(v.activeDropdownTab===`mcp`){let t=n.querySelectorAll(`#mcpList .mcp-list-item`),r=t.length;if(e.key===`ArrowDown`){e.preventDefault(),v.selectedMcpServiceIndex<0?v.selectedMcpServiceIndex=0:v.selectedMcpServiceIndex=(v.selectedMcpServiceIndex+1)%r,Ot(t);return}if(e.key===`ArrowUp`){e.preventDefault(),v.selectedMcpServiceIndex<0||v.selectedMcpServiceIndex===0?v.selectedMcpServiceIndex=r-1:--v.selectedMcpServiceIndex,Ot(t);return}if(e.key===`Enter`&&v.selectedMcpServiceIndex>=0){e.preventDefault(),t[v.selectedMcpServiceIndex].click(),(e.ctrlKey||e.metaKey)&&Mt();return}if(e.key===`Escape`){Mt();return}if(e.key===`Tab`){e.preventDefault(),Rn(`prompts`);return}return}let t=n.querySelectorAll(`#promptList .prompt-item`),r=t.length;if(e.key===`Tab`){let t=document.getElementById(`skillsTab`),n=document.getElementById(`mcpTab`);if(t&&t.style.display!==`none`){e.preventDefault(),Rn(`skills`);return}if(n&&n.style.display!==`none`){e.preventDefault(),Rn(`mcp`);return}}if(r!==0&&e.key===`ArrowDown`){e.preventDefault(),v.selectedPromptIndex<0?v.selectedPromptIndex=0:v.selectedPromptIndex=(v.selectedPromptIndex+1)%r,Dn(t);return}if(e.key===`ArrowUp`){e.preventDefault(),v.selectedPromptIndex<0||v.selectedPromptIndex===0?v.selectedPromptIndex=r-1:--v.selectedPromptIndex,Dn(t);return}if(e.key===`Enter`&&(e.ctrlKey||e.metaKey)&&v.selectedPromptIndex>=0){e.preventDefault();let n=t[v.selectedPromptIndex].dataset.code;$r(n);return}if(e.key===`Enter`&&v.selectedPromptIndex>=0){e.preventDefault();let n=t[v.selectedPromptIndex].dataset.code;bt(n);return}if(e.key===`Escape`){Mt();return}}if(e.key===`Escape`){v.inputHistoryIndex>=0&&(v.inputHistoryIndex=-1),a.value&&(a.value=``,a.style.height=`auto`,a.dispatchEvent(new Event(`input`))),e.preventDefault();return}let c=t.style.display!==`none`&&n.classList.contains(`show`),l=r.style.display!==`none`&&i.classList.contains(`show`),u=o.style.display!==`none`&&s.classList.contains(`show`);if(e.key===`ArrowUp`&&v.inputHistoryIndex===-1&&!a.value.trim()&&!Xr()&&zp()){e.preventDefault();return}if(!c&&!l&&!u){let t=gp({key:e.key,value:a.value,caret:a.selectionStart,history:v.inputHistory,index:v.inputHistoryIndex});if(t.handled){e.preventDefault(),v.inputHistoryIndex=t.index,a.value=t.value,a.dispatchEvent(new Event(`input`)),a.setSelectionRange(t.value.length,t.value.length);return}}if(e.key===`Enter`&&!e.shiftKey){if(v.isComposing)return;if(e.preventDefault(),of(),v.isGenerating){if(e.altKey){$t(a.value);return}gn();return}Fi()}}),a.addEventListener(`compositionstart`,()=>{v.isComposing=!0}),a.addEventListener(`compositionend`,()=>{v.isComposing=!1}),a.addEventListener(`paste`,e=>{let t=e.clipboardData?.items;if(t)for(let n of t){if(n.type.startsWith(`image/`)&&v.enableImageInput){e.preventDefault();let t=n.getAsFile();t&&kt(t);break}if(n.kind===`file`&&v.enableFileInput){e.preventDefault();let t=n.getAsFile();t&&yr([t]);break}}});let ge=document.getElementById(`fileAttachBtn`),_e=document.getElementById(`fileInput`);ge&&_e&&(ge.addEventListener(`click`,()=>{_e.click()}),_e.addEventListener(`change`,async()=>{if(_e.files.length>0){let e=Array.from(_e.files),n=e.filter(e=>e.type.startsWith(`image/`)),r=e.filter(e=>!e.type.startsWith(`image/`));if(n.length>0)if(v.enableImageInput)for(let e of n)await kt(e);else A(t(`sidePanel.imageNotEnabled`)),yr(n);r.length>0&&yr(r),_e.value=``}}));let ve=document.querySelector(`.input-wrapper`),ye=0;ve&&(ve.addEventListener(`dragenter`,e=>{e.preventDefault(),e.stopPropagation(),ye++,ve.classList.add(`drag-over`)}),ve.addEventListener(`dragleave`,e=>{e.preventDefault(),e.stopPropagation(),ye--,ye<=0&&(ye=0,ve.classList.remove(`drag-over`))}),ve.addEventListener(`dragover`,e=>{e.preventDefault(),e.stopPropagation()}),ve.addEventListener(`drop`,async e=>{e.preventDefault(),e.stopPropagation(),ye=0,ve.classList.remove(`drag-over`);let n=e.dataTransfer.getData(`application/x-workspace-file`);if(n){e.preventDefault();try{let{path:e}=JSON.parse(n);if(e){Kr([e]);return}}catch(e){r.warn(`[SidePanel] parse workspace dragdata failed:`,e)}}let i=Array.from(e.dataTransfer.files);if(i.length>0){e.preventDefault();let n=i.filter(e=>e.type.startsWith(`image/`)),r=i.filter(e=>!e.type.startsWith(`image/`));if(n.length>0)if(v.enableImageInput)for(let e of n)await kt(e);else A(t(`sidePanel.imageNotEnabled`)),yr(n);r.length>0&&yr(r);return}let o=e.dataTransfer.getData(`text/plain`);if(o&&(e.preventDefault(),a)){a.focus();let e=a.selectionStart??a.value.length,t=a.selectionEnd??a.value.length;a.value=a.value.slice(0,e)+o+a.value.slice(t),a.selectionStart=a.selectionEnd=e+o.length,a.dispatchEvent(new Event(`input`))}}));let be=document.getElementById(`screenshotBtn`);be&&be.addEventListener(`click`,async()=>{if(v.enableImageInput)try{await Li()}catch(e){r.error(`[SidePanel] screenshot failed:`,e),A(t(`sidePanel.screenshotFailed`))}}),Gi(),a.addEventListener(`wheel`,e=>{v.isScrolling=!0;let t=a.style.height||a.offsetHeight+`px`;a.style.height=t,a.scrollHeight<=a.clientHeight+10&&(e.preventDefault(),e.stopPropagation()),setTimeout(()=>{v.isScrolling=!1},100)},{passive:!1}),a.addEventListener(`input`,e=>{let t=a.value,n=document.getElementById(`promptSelector`),r=document.getElementById(`promptDropdown`);document.getElementById(`agentAtSelector`),document.getElementById(`agentAtDropdown`);let i=t.lastIndexOf(`/`),o=t.lastIndexOf(`@`),s=t.lastIndexOf(`$`),c=e=>{if(e===-1||e!==0&&t[e-1]!==`
670
670
  `&&t[e-1]!==` `)return!1;let n=t.substring(e+1);return!(n.includes(` `)||n.includes(`
671
671
  `))},l=c(i),u=c(o),d=c(s),f=null;if(l&&(f={key:`slash`,index:i}),u&&(!f||o>f.index)&&(f={key:`at`,index:o}),d&&(!f||s>f.index)&&(f={key:`dollar`,index:s}),f&&f.key===`dollar`)Mt(),on(),af(t.substring(s+1));else if(f&&f.key===`at`)Mt(),of(),Ni(t.substring(o+1));else if(f&&f.key===`slash`){on(),of();let e=t.substring(i+1);n.style.display!==`none`&&r.classList.contains(`show`)?yn(e):hn(e)}else Mt(),on(),of();ee()});let xe=_p((e,t)=>{chrome.storage.local.set({[e]:t})},200);u.addEventListener(`scroll`,()=>{xe(`scrollPosition_`+(v.activeSessionId||`default`),u.scrollTop)}),window.addEventListener(`pagehide`,()=>{chrome.storage.local.set({[`scrollPosition_`+(v.activeSessionId||`default`)]:u.scrollTop})});let Se=document.getElementById(`headerMoreBtn`),Ce=document.getElementById(`headerMoreDropdown`);Se&&Ce&&(Se.addEventListener(`click`,e=>{e.stopPropagation(),Ce.classList.toggle(`show`)}),document.addEventListener(`click`,e=>{!Ce.contains(e.target)&&e.target!==Se&&ke()}));let we=document.getElementById(`themeToggleBtn`),Te=document.getElementById(`themeToggleLabel`),Ee=document.getElementById(`themeSubmenu`),De=e=>t(e===`dark`?`settings.themeDark`:e===`system`?`settings.themeSystem`:`settings.themeLight`),Oe=()=>{let e=ot();Te&&(Te.textContent=t(`header.themeToggle`,{theme:De(e)})),Ee&&Ee.querySelectorAll(`.theme-submenu-item`).forEach(t=>{t.classList.toggle(`active`,t.dataset.themeValue===e)}),we&&we.setAttribute(`aria-expanded`,String(!!(Ee&&Ee.classList.contains(`show`))))};function ke(){Ee&&Ee.classList.remove(`show`),Ce&&Ce.classList.remove(`show`),we&&we.setAttribute(`aria-expanded`,`false`)}we&&Ee&&(we.addEventListener(`click`,e=>{e.stopPropagation(),Ee.classList.toggle(`show`),Oe()}),Ee.querySelectorAll(`.theme-submenu-item`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),Ge(e.dataset.themeValue),ke()})})),Oe(),ct(Oe),o(Oe),c.addEventListener(`click`,e=>{e.stopPropagation(),ke(),Jr()}),l&&l.addEventListener(`click`,e=>{e.stopPropagation(),ke(),Nt()});let Ae=document.getElementById(`importChatBtn`);Ae&&Ae.addEventListener(`click`,e=>{e.stopPropagation(),ke(),wn()});let je=document.getElementById(`importSessionsFile`);je&&je.addEventListener(`change`,e=>{let t=e.target.files[0];t&&Hn(t)});let Me=document.getElementById(`settingsBtn`);Me&&Me.addEventListener(`click`,()=>{chrome.runtime.openOptionsPage()});let Ne=document.getElementById(`headerAgentIndicator`);Ne&&Ne.addEventListener(`click`,async()=>{let e=chrome.runtime.getURL(`options.html#agent`),t=await chrome.tabs.query({url:chrome.runtime.getURL(`options.html`)});t.length>0?await chrome.tabs.update(t[0].id,{active:!0,url:e}):await chrome.tabs.create({url:e})});let Pe=document.getElementById(`prototypeLibraryBtn`);Pe&&Pe.addEventListener(`click`,e=>{e.stopPropagation(),ke(),vt()});let O=document.getElementById(`tokenStatsHeaderBtn`);O&&O.addEventListener(`click`,e=>{e.stopPropagation(),ke(),window.openTokenStats&&window.openTokenStats()});let Fe=document.getElementById(`auditLogBtn`),Ie=document.getElementById(`auditLogOverlay`),Le=document.getElementById(`auditLogClose`),Re=document.getElementById(`auditLogRefreshBtn`),ze=document.getElementById(`auditLogCategoryFilter`),Be=document.getElementById(`auditLogLimit`),Ve=document.getElementById(`auditLogSearch`),He=document.getElementById(`auditLogSearchClear`),Ue=document.getElementById(`auditLogLoading`),We=document.getElementById(`auditLogEmpty`),k=document.getElementById(`auditLogList`),Ke=[],qe={auth:t(`sidePanel.auditCategoryAuth`),fs:t(`sidePanel.auditCategoryFs`),exec:t(`sidePanel.auditCategoryExec`),security:t(`sidePanel.auditCategorySecurity`),system:t(`sidePanel.auditCategorySystem`)},Je={info:`INFO`,warn:`WARN`,error:`ERROR`},Ye={info:`audit-level-info`,warn:`audit-level-warn`,error:`audit-level-error`};function Xe(e){if(!e)return`-`;let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())} ${n(t.getHours())}:${n(t.getMinutes())}:${n(t.getSeconds())}`}function Qe(e){let n=new Set([`timestamp`,`level`,`category`,`action`]),r=[];for(let[t,i]of Object.entries(e)){if(n.has(t))continue;let e=typeof i==`string`?i:JSON.stringify(i),a=e.length>60?e.slice(0,60)+`...`:e;r.push(`${t}: ${a}`)}return r.join(t(`sidePanel.auditDetailSeparator`))}async function $e(){if(!Ue||!We||!k)return;Ue.style.display=`block`,We.style.display=`none`,k.style.display=`none`;let e=ze?.value||null,n=parseInt(Be?.value||`200`,10);try{let r=await new Promise((t,r)=>{chrome.runtime.sendMessage({type:`QUERY_AUDIT_LOGS`,category:e,limit:n},e=>{chrome.runtime.lastError?r(Error(chrome.runtime.lastError.message)):t(e)})});if(Ue.style.display=`none`,!r||!r.success){We.style.display=`block`,We.textContent=t(`sidePanel.auditQueryFailed`,{error:r?.error||t(`sidePanel.unknownError`)});return}Ke=r.entries||[],et()}catch(e){Ue.style.display=`none`,We.style.display=`block`,We.textContent=t(`sidePanel.auditLoadFailed`,{error:e.message})}}function et(){if(!k)return;let e=(Ve?.value||``).trim().toLowerCase(),n=Ke;if(e&&(n=n.filter(t=>[t.action||``,t.category||``,...Object.entries(t).filter(([e])=>![`timestamp`,`level`,`category`,`action`].includes(e)).map(([,e])=>typeof e==`string`?e:JSON.stringify(e))].join(` `).toLowerCase().includes(e))),He&&(He.style.display=e?`block`:`none`),Ue.style.display=`none`,n.length===0){We.style.display=`block`,We.textContent=t(e?`sidePanel.auditNoMatch`:`sidePanel.auditEmpty`),k.style.display=`none`;return}We.style.display=`none`,k.style.display=`block`,k.innerHTML=n.map(e=>{let t=j(qe[e.category]||e.category||`-`),n=j(Je[e.level]||e.level?.toUpperCase()||`INFO`),r=Ye[e.level]||`audit-level-info`,i=Xe(e.timestamp),a=j(Qe(e));return`<div class="audit-entry">
672
672
  <div class="audit-entry-header">
@@ -687,4 +687,4 @@ Are you sure you want to stop the agent service? You will not be able to connect
687
687
  <span style="font-size: 12px; color: ${o}; font-weight: 500;">${r.toFixed(0)}%</span>
688
688
  </td>
689
689
  <td style="padding: 6px 10px; text-align: right; border-bottom: 1px solid var(--border-subtle); color: var(--text-tertiary); font-size: 12px;">${s}</td>
690
- </tr>`}).join(``),ln()}function ln(){let{column:e,asc:t}=en,n=[`name`,`callCount`,`successCount`,`successRate`,`duration`],r={name:`sortByName`,callCount:`sortByCallCount`,successCount:`sortBySuccessCount`,successRate:`sortBySuccessRate`,duration:`sortByDuration`};n.forEach(n=>{let i=document.getElementById(r[n]);if(!i)return;let a=i.querySelector(`.sort-indicator`);a&&(n===e?(a.textContent=t?`▲`:`▼`,a.style.color=`var(--brand-500)`):(a.textContent=``,a.style.color=``))})}document.querySelectorAll(`#toolStatsTable th[data-sort]`).forEach(e=>{e.addEventListener(`click`,()=>{let t=e.dataset.sort;en.column===t?en.asc=!en.asc:(en.column=t,en.asc=!1),tn()})}),Bt.addEventListener(`click`,()=>{xi()}),Vt.addEventListener(`click`,()=>{xi(),Jt()});let un=document.getElementById(`confirmModal`);un.addEventListener(`click`,e=>{e.target===un&&xi()});let fn=document.getElementById(`selectionClose`);fn&&fn.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),r.debug(`[SidePanel] user clickcloseselected content by button`),Gn(),window.hideFloatingMenu(),v.lastSelectedText=``,v.currentSelectionRange=null}),a.addEventListener(`input`,()=>{})}),it().then(()=>{Pm(),pi(v.chatConfig.showMessageTimestamp!==!1),Fm(),Im()}),document.addEventListener(`DOMContentLoaded`,()=>{Rm()}),document.addEventListener(`DOMContentLoaded`,ia),document.addEventListener(`DOMContentLoaded`,ui),document.addEventListener(`DOMContentLoaded`,Jm),document.addEventListener(`DOMContentLoaded`,qm),document.addEventListener(`DOMContentLoaded`,Yd),document.addEventListener(`DOMContentLoaded`,Wf),document.addEventListener(`DOMContentLoaded`,hp),document.addEventListener(`DOMContentLoaded`,ei),document.addEventListener(`DOMContentLoaded`,async()=>{er(),Ka(),await $i(),Vi(),await ic(),Wl(),gs(),Am(),zs(),wh(),hr(),Od();let{updateBookmarkButtons:e,updateBookmarkBadge:t}=await E(async()=>{let{updateBookmarkButtons:e,updateBookmarkBadge:t}=await import(`./context-indicator-C9LYk-kV.js`).then(e=>e._n);return{updateBookmarkButtons:e,updateBookmarkBadge:t}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]));e(),t()}),document.addEventListener(`DOMContentLoaded`,()=>{us()}),document.addEventListener(`DOMContentLoaded`,async()=>{xt(e=>Fi(e)),await Vt(),await Kp()});function Ah(){Gn(),Sr(),Oi(),Zn(),Ut(),Yi();let e=document.getElementById(`imagePreviewBar`);e&&(e.innerHTML=``,e.style.display=`none`)}function jh(e){let t=e||{};t.quotedContextText&&Di(t.quotedContextText),t.selectedPage&&Ln(t.selectedPage),!t.quotedContextText&&v.selectedContextText&&nr(),dr(),Lr(),ur(),yi(),zn()}document.addEventListener(`queue-context-cleared`,Ah),document.addEventListener(`queue-context-restored`,e=>{jh(e&&e.detail?e.detail.snapshot:null)}),document.addEventListener(`DOMContentLoaded`,Cn),document.addEventListener(`DOMContentLoaded`,Nr),document.addEventListener(`DOMContentLoaded`,vi),document.addEventListener(`DOMContentLoaded`,Er),document.addEventListener(`DOMContentLoaded`,mn),document.addEventListener(`DOMContentLoaded`,gr),document.addEventListener(`DOMContentLoaded`,qr),document.addEventListener(`DOMContentLoaded`,Mn),document.addEventListener(`DOMContentLoaded`,Lt),document.addEventListener(`DOMContentLoaded`,()=>mr()),document.addEventListener(`DOMContentLoaded`,async()=>{let{refreshAgentNames:e,initScrollToBottomBtn:t}=await E(async()=>{let{refreshAgentNames:e,initScrollToBottomBtn:t}=await import(`./context-indicator-C9LYk-kV.js`).then(e=>e.pt);return{refreshAgentNames:e,initScrollToBottomBtn:t}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]));e(),t()});async function Mh(){try{let e=(await chrome.storage.local.get(`_detachOriginTabId`))?._detachOriginTabId;if(typeof e==`number`)try{let t=await chrome.tabs.get(e);if(t?.id!=null)return t.id}catch{}}catch{}try{let e=(await chrome.windows.getAll({populate:!0})||[]).filter(e=>e.type===`normal`);return((e.find(e=>e.focused)||e[0])?.tabs||[]).find(e=>e.active)?.id??null}catch{return null}}document.addEventListener(`DOMContentLoaded`,()=>{let e=new URLSearchParams(window.location.search).has(`popup`),n=document.getElementById(`detachBtn`),i=document.getElementById(`attachBtn`),a=e?i:n;e?i&&(i.style.display=`flex`):n&&(n.style.display=`flex`);let o=()=>{if(!a)return;let n=v.pendingCallApiSessionIds&&v.pendingCallApiSessionIds.size>0;a.disabled=n,a.style.opacity=n?`0.35`:``,a.style.cursor=n?`not-allowed`:`pointer`,a.title=t(n?`detach.taskRunning`:e?`header.attachTitle`:`header.detachTitle`)};o(),document.addEventListener(`generating-state-changed`,o),n&&n.addEventListener(`click`,async()=>{if(v.pendingCallApiSessionIds&&v.pendingCallApiSessionIds.size>0){A(t(`detach.taskRunning`),`warning`);return}try{if((await chrome.runtime.sendMessage({type:`DETACH_SIDEPANEL`,width:window.innerWidth}))?.success)try{window.close()}catch{}}catch(e){r.warn(`[SidePanel] detach failed:`,e?.message)}}),i&&i.addEventListener(`click`,async()=>{if(v.pendingCallApiSessionIds&&v.pendingCallApiSessionIds.size>0){A(t(`detach.taskRunning`),`warning`);return}try{let e=(await chrome.windows.getCurrent()).id,n=await Mh();if(n==null){A(t(`detach.attachFailed`),`error`);return}let i=await chrome.runtime.sendMessage({type:`ATTACH_SIDEPANEL`,windowId:e,tabId:n});if(i?.success)try{window.close()}catch{}else r.warn(`[SidePanel] attach rejected:`,i?.error),A(t(`detach.attachFailed`),`error`)}catch(e){r.warn(`[SidePanel] attach failed:`,e?.message),A(t(`detach.attachFailed`),`error`)}})});
690
+ </tr>`}).join(``),ln()}function ln(){let{column:e,asc:t}=en,n=[`name`,`callCount`,`successCount`,`successRate`,`duration`],r={name:`sortByName`,callCount:`sortByCallCount`,successCount:`sortBySuccessCount`,successRate:`sortBySuccessRate`,duration:`sortByDuration`};n.forEach(n=>{let i=document.getElementById(r[n]);if(!i)return;let a=i.querySelector(`.sort-indicator`);a&&(n===e?(a.textContent=t?`▲`:`▼`,a.style.color=`var(--brand-500)`):(a.textContent=``,a.style.color=``))})}document.querySelectorAll(`#toolStatsTable th[data-sort]`).forEach(e=>{e.addEventListener(`click`,()=>{let t=e.dataset.sort;en.column===t?en.asc=!en.asc:(en.column=t,en.asc=!1),tn()})}),Bt.addEventListener(`click`,()=>{xi()}),Vt.addEventListener(`click`,()=>{xi(),Jt()});let un=document.getElementById(`confirmModal`);un.addEventListener(`click`,e=>{e.target===un&&xi()});let fn=document.getElementById(`selectionClose`);fn&&fn.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),r.debug(`[SidePanel] user clickcloseselected content by button`),Gn(),window.hideFloatingMenu(),v.lastSelectedText=``,v.currentSelectionRange=null}),a.addEventListener(`input`,()=>{})}),it().then(()=>{Pm(),pi(v.chatConfig.showMessageTimestamp!==!1),Fm(),Im()}),document.addEventListener(`DOMContentLoaded`,()=>{Rm()}),document.addEventListener(`DOMContentLoaded`,ia),document.addEventListener(`DOMContentLoaded`,ui),document.addEventListener(`DOMContentLoaded`,Jm),document.addEventListener(`DOMContentLoaded`,qm),document.addEventListener(`DOMContentLoaded`,Yd),document.addEventListener(`DOMContentLoaded`,Wf),document.addEventListener(`DOMContentLoaded`,hp),document.addEventListener(`DOMContentLoaded`,ei),document.addEventListener(`DOMContentLoaded`,async()=>{er(),Ka(),await $i(),Vi(),await ic(),Wl(),gs(),Am(),zs(),wh(),hr(),Od();let{updateBookmarkButtons:e,updateBookmarkBadge:t}=await E(async()=>{let{updateBookmarkButtons:e,updateBookmarkBadge:t}=await import(`./context-indicator-u4eOUhKC.js`).then(e=>e._n);return{updateBookmarkButtons:e,updateBookmarkBadge:t}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]));e(),t()}),document.addEventListener(`DOMContentLoaded`,()=>{us()}),document.addEventListener(`DOMContentLoaded`,async()=>{xt(e=>Fi(e)),await Vt(),await Kp()});function Ah(){Gn(),Sr(),Oi(),Zn(),Ut(),Yi();let e=document.getElementById(`imagePreviewBar`);e&&(e.innerHTML=``,e.style.display=`none`)}function jh(e){let t=e||{};t.quotedContextText&&Di(t.quotedContextText),t.selectedPage&&Ln(t.selectedPage),!t.quotedContextText&&v.selectedContextText&&nr(),dr(),Lr(),ur(),yi(),zn()}document.addEventListener(`queue-context-cleared`,Ah),document.addEventListener(`queue-context-restored`,e=>{jh(e&&e.detail?e.detail.snapshot:null)}),document.addEventListener(`DOMContentLoaded`,Cn),document.addEventListener(`DOMContentLoaded`,Nr),document.addEventListener(`DOMContentLoaded`,vi),document.addEventListener(`DOMContentLoaded`,Er),document.addEventListener(`DOMContentLoaded`,mn),document.addEventListener(`DOMContentLoaded`,gr),document.addEventListener(`DOMContentLoaded`,qr),document.addEventListener(`DOMContentLoaded`,Mn),document.addEventListener(`DOMContentLoaded`,Lt),document.addEventListener(`DOMContentLoaded`,()=>mr()),document.addEventListener(`DOMContentLoaded`,async()=>{let{refreshAgentNames:e,initScrollToBottomBtn:t}=await E(async()=>{let{refreshAgentNames:e,initScrollToBottomBtn:t}=await import(`./context-indicator-u4eOUhKC.js`).then(e=>e.pt);return{refreshAgentNames:e,initScrollToBottomBtn:t}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]));e(),t()});async function Mh(){try{let e=(await chrome.storage.local.get(`_detachOriginTabId`))?._detachOriginTabId;if(typeof e==`number`)try{let t=await chrome.tabs.get(e);if(t?.id!=null)return t.id}catch{}}catch{}try{let e=(await chrome.windows.getAll({populate:!0})||[]).filter(e=>e.type===`normal`);return((e.find(e=>e.focused)||e[0])?.tabs||[]).find(e=>e.active)?.id??null}catch{return null}}document.addEventListener(`DOMContentLoaded`,()=>{let e=new URLSearchParams(window.location.search).has(`popup`),n=document.getElementById(`detachBtn`),i=document.getElementById(`attachBtn`),a=e?i:n;e?i&&(i.style.display=`flex`):n&&(n.style.display=`flex`);let o=()=>{if(!a)return;let n=v.pendingCallApiSessionIds&&v.pendingCallApiSessionIds.size>0;a.disabled=n,a.style.opacity=n?`0.35`:``,a.style.cursor=n?`not-allowed`:`pointer`,a.title=t(n?`detach.taskRunning`:e?`header.attachTitle`:`header.detachTitle`)};o(),document.addEventListener(`generating-state-changed`,o),n&&n.addEventListener(`click`,async()=>{if(v.pendingCallApiSessionIds&&v.pendingCallApiSessionIds.size>0){A(t(`detach.taskRunning`),`warning`);return}try{if((await chrome.runtime.sendMessage({type:`DETACH_SIDEPANEL`,width:window.innerWidth}))?.success)try{window.close()}catch{}}catch(e){r.warn(`[SidePanel] detach failed:`,e?.message)}}),i&&i.addEventListener(`click`,async()=>{if(v.pendingCallApiSessionIds&&v.pendingCallApiSessionIds.size>0){A(t(`detach.taskRunning`),`warning`);return}try{let e=(await chrome.windows.getCurrent()).id,n=await Mh();if(n==null){A(t(`detach.attachFailed`),`error`);return}let i=await chrome.runtime.sendMessage({type:`ATTACH_SIDEPANEL`,windowId:e,tabId:n});if(i?.success)try{window.close()}catch{}else r.warn(`[SidePanel] attach rejected:`,i?.error),A(t(`detach.attachFailed`),`error`)}catch(e){r.warn(`[SidePanel] attach failed:`,e?.message),A(t(`detach.attachFailed`),`error`)}})});