ai-helper-agent 2.8.8 → 2.8.9

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.
@@ -1,6 +1,6 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/context-indicator-DSJveMWs.js","assets/chunk-CMxvf4Kt.js","assets/model-profiles-C3kJEHM6.js","assets/i18n-DvmxOw8q.js","assets/version-LLHkaYuT.js","assets/agent-store-QTeMyM9O.js","assets/session-store-owqj23pJ.js","assets/voice-shortcut-Dtt3nhkz.js","assets/workspace-manager-DVPkwn2d.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-DvmxOw8q.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-C3kJEHM6.js";import{_ as D,d as fe}from"./session-store-owqj23pJ.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-DK2Wxmvk.js";import{$ as Ge,A as Ke,D as qe,G as Je,H as Ye,J as Xe,K as Ze,M as k,N as Qe,O as $e,P as et,Q as tt,R as nt,T as rt,V as it,W as at,Y as A,Z as ot,_ as st,et as ct,g as lt,j,k as ut,l as dt,q as ft,t as pt,tt as mt,v as ht,y as gt}from"./version-LLHkaYuT.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,Gt as Kt,H as qt,Hn as Jt,Hr as Yt,Ht as Xt,I as Zt,In as Qt,Ir as $t,It as en,J as tn,Jn as nn,Jt as rn,K as an,Kn as on,Kt as sn,L as cn,Ln as ln,Lr as un,Lt as dn,M as fn,Mn as pn,Mr as mn,Mt as hn,N as gn,Nn as _n,Nr as vn,Nt as yn,O as bn,On as xn,Or as Sn,Ot as Cn,P as wn,Pn as Tn,Pr as En,Pt as Dn,Q as On,Qn as kn,Qt as An,R as jn,Rn as Mn,Rr as Nn,Rt as Pn,S as Fn,Sn as In,Sr as Ln,St as Rn,T as zn,Tn as Bn,Tr as Vn,Tt as Hn,U as Un,Un as Wn,Ur as Gn,Ut as Kn,Vn as qn,Vr as Jn,Vt as Yn,W as Xn,Wn as Zn,Wt as Qn,X as $n,Xn as er,Xt as tr,Y as nr,Yn as rr,Yt as ir,Z as ar,Zn as or,Zt as sr,_ as cr,_n as lr,_r as ur,_t as dr,a as fr,an as pr,ar as mr,at as hr,b as gr,bn as _r,bt as vr,c as yr,cn as br,cr as xr,ct as Sr,d as Cr,dn as wr,dr as Tr,dt as Er,en as Dr,er as Or,et as kr,f as Ar,fn as jr,fr as Mr,g as Nr,gn as Pr,gr as Fr,gt as Ir,h as Lr,hr as Rr,ht as zr,i as Br,in as Vr,ir as Hr,it as Ur,j as Wr,jn as Gr,jr as Kr,jt as qr,k as Jr,kn as Yr,kr as Xr,kt as Zr,l as Qr,ln as $r,lr as ei,lt as ti,m as ni,mn as ri,mr as ii,mt as ai,n as oi,nn as si,nr as ci,nt as li,o as ui,on as di,or as fi,ot as pi,p as mi,pn as hi,pr as gi,pt as _i,q as vi,qn as yi,qt as bi,r as xi,rn as Si,rr as Ci,rt as wi,s as Ti,sr as Ei,st as Di,t as Oi,tn as ki,tt as Ai,u as ji,un as Mi,ur as Ni,ut as Pi,v as Fi,vn as Ii,vr as Li,vt as Ri,w as zi,wn as Bi,wr as Vi,wt as Hi,x as Ui,xn as Wi,xr as Gi,xt as Ki,y as qi,yn as Ji,yr as Yi,yt as Xi,z as Zi,zn as Qi,zr as $i,zt as ea}from"./context-indicator-DSJveMWs.js";import{o as ta}from"./agent-store-QTeMyM9O.js";import{O as na,b as ra,l as ia,p as aa,v as oa}from"./workspace-manager-DVPkwn2d.js";var sa=`panel-observer-`,ca=new Map;function la(e){if(!e)return null;let t=ca.get(e);if(t)return t;let n;try{n=chrome.runtime.connect({name:`${sa}${e}`})}catch(e){return r.debug(`[PanelObserver] 建立观察端口失败(忽略):`,e?.message||e),null}ca.set(e,n);try{n.onDisconnect.addListener(()=>{ca.get(e)===n&&ca.delete(e)})}catch(e){r.debug(`[PanelObserver] 观察端口断开监听挂不上(忽略):`,e?.message||e)}return n}function ua(e){if(!e)return;let t=ca.get(e);if(t){ca.delete(e);try{t.disconnect()}catch(e){r.debug(`[PanelObserver] 关闭观察端口异常(忽略):`,e?.message||e)}}}function da({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||[]),!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 fa({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 pa=!1,ma=new Map,ha=null,ga=!1,_a=null,va=null,ya=null,ba=250,xa=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 Sa(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 Ca(e,t){let n=new Map;return{start(){Hi(e,``),jt(``),Hn(Date.now()),Di(t),Ki(t)},chunk(n){Hi(e,n),zt(t,n)},restore({html:e}){Pi(t,e)},toolCalls(e){Sr(t,e)},toolResult(e){ti(e,t)},agentStream(e){let r=n.get(e.execId);r||(r={element:_i(e.toolCallId?t.querySelector(`.tool-call-item[data-tool-call-id="${e.toolCallId}"]`):null,t.querySelector(`.stream-content`)),stdout:``,stderr:``},n.set(e.execId,r),dt());let i=r.element.querySelector(`code`);i&&(e.streamType===`stderr`?r.stderr+=e.data||``:r.stdout+=e.data||``,i.textContent=r.stdout+(r.stderr?`
3
- `+r.stderr:``),i.parentElement.scrollTop=i.parentElement.scrollHeight)},agentStreamDone(e){let t=n.get(e.execId);t&&e.exitCode!==0&&t.element.classList.add(`agent-stream-error`)},retrying(e,n){Ri(t,e,n)},preselect(e){let n=t.querySelector(`.message-content`);!n||!e.length||e.forEach(e=>n.insertBefore(ai(e),n.firstChild))},final(e,n,r={}){dr(t,e,n,r.reflectionScore,r.reasoningContent,r.wasRevised)},error(e,n){dr(t,e,n||[])}}}async function wa(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-DSJveMWs.js`).then(e=>e.br);return{appendMessageToSession:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]));await a(t,i)}function Ta(){E(()=>import(`./context-indicator-DSJveMWs.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 Ea=1e3;function Da(e){return Promise.race([Ft(e),new Promise(e=>setTimeout(()=>e(null),Ea))])}function Oa(e,n){let i=zr(e);if(i())return!1;let a=pi(e);a.dataset.callId=n,i(a),Hi(e,``),Hn(Date.now()),Rn(Date.now()),v.pendingCallApiSessionIds.add(e),v.generatingSessionIds.add(e),Ta();try{document.dispatchEvent(new CustomEvent(`generating-state-changed`))}catch{}let o=da({sessionId:e,callId:n,awaitSnapshot:!0,renderer:Ca(e,a),persist:t=>wa(t,e,a),emptyFallback:t(`chatMsg.emptyModelReply`),onFinished:()=>{if(ma.get(e)===o){ma.delete(e),ua(e),v.pendingCallApiSessionIds.delete(e),Ta(),Ir(e);try{document.dispatchEvent(new CustomEvent(`session-cache-invalidate`,{detail:{sessionId:e}}))}catch{}Gt(e)}}});return ma.set(e,o),la(e),Da(e).then(t=>{o.finished||ma.get(e)!==o||o.restore(t)}).catch(()=>o.restore(null)),v.activeSessionId===e&&Xi(e),r.info(`[ChatReattach] 已接管运行中的任务: sessionId=${e}, callId=${n}`),!0}function ka(e){let t=ma.get(e);if(!t)return;ma.delete(e),ua(e);try{t.dispose?.()}catch{}let n=zr(e),r=n();try{r?.remove()}catch{}n(null),Ir(e),v.pendingCallApiSessionIds.delete(e),Ta();try{document.dispatchEvent(new CustomEvent(`generating-state-changed`))}catch{}}function Aa(){let e=ha;e&&Promise.resolve().then(()=>e.syncFromBackground()).catch(e=>r.debug(`[ChatReattach] 对齐后台状态失败(忽略):`,e?.message||e))}function ja(){!pa||!ha||ya||(ya=setTimeout(()=>{ya=null,Aa()},ba))}var Ma=new Map,Na=3e3,Pa=100,Fa=new Set,Ia=new Set([`API_COMPLETE`,`API_ERROR`]);function La(e,t){let n=`${e}|${t.callId}`;Fa.has(n)||(Fa.add(n),Fa.size>Pa&&Fa.delete(Fa.values().next().value),ka(e),Oa(e,t.callId)&&ma.get(e)?.handleMessage(t))}function Ra(e,t,n){let r=Ma.get(e);if(r){r.messages.push(n);return}r={callId:t,messages:[n]},Ma.set(e,r),Sa(Na).then(t=>za(e,t&&t.activeCallIds&&t.activeCallIds[e]||null)).catch(()=>za(e,null)).finally(()=>{Ma.delete(e)})}function za(e,t){let n=Ma.get(e);if(!n)return;let{callId:r,messages:i}=n;if(t===r)ka(e),Oa(e,r);else if(t===null){let t=i.find(e=>Ia.has(e.type));if(!t)return;La(e,t);return}else return;let a=ma.get(e);if(!(!a||a.callId!==r))for(let e of i){if(a.finished)break;a.handleMessage(e)}}function Ba(){ga||(ga=!0,chrome.runtime.onMessage.addListener(e=>{if(!e)return!1;let t=e.sessionId?ma.get(e.sessionId):null;return t?e.callId&&e.callId!==t.callId?(Ra(e.sessionId,e.callId,e),!1):(la(e.sessionId),t.handleMessage(e),!1):(e.callId&&xa.has(e.type)&&ja(),!1)}),_a=e=>{let t=e?.detail?.sessionId;t&&ma.has(t)&&Xi(t),ja()},document.addEventListener(`session-hydrated`,_a),va=e=>{let t=e?.detail?.sessionId;t&&ma.has(t)&&Xi(t)},document.addEventListener(`chat-history-rendered`,va))}function Va(){return pa?{syncFromBackground:()=>ha.syncFromBackground()}:(pa=!0,Ba(),ha=fa({queryRunning:Sa,hasLocalListener:e=>v.pendingCancelApiMap.has(e),isAttached:(e,t)=>ma.get(e)?.callId===t?(la(e),!0):!1,attach:(e,t)=>{Oa(e,t)}}),ha.syncFromBackground(),{syncFromBackground:()=>ha.syncFromBackground()})}function Ha(e){!pa||!ha||(e&&v.activeSessionId===e&&Xi(e),ha.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 Ua=`sessionDockDismissed`,Wa=5e3,Ga=250,Ka=1200,qa=8,Ja=qa-1,Ya=9e4,Xa={running:0,queued:1,done:2},Za=new Map,Qa=new Map,$a=new Map,eo=new Map,to=new Set,no=new Set,ro=new Map,io=new Map,ao=new Set,oo=new Set,so=[],co=new Set,M=null,N=null,P=null,lo=[],uo=!1,fo=null,po=null,mo=!1,ho=null,go=null;function _o(e){return e?Array.isArray(e)?e:e instanceof Set?Array.from(e):[]:[]}function vo(e){let t=new Set;for(let n of _o(e))n&&t.add(h(String(n))||String(n));return t}function yo({phase:e=``,sessionId:t=null,backendRunningIds:n=[],startedAt:r=0,lastUpdateAt:i=0,now:a=Date.now(),staleMs:o=Ya}={}){if(e!==`running`||!t||_o(n).includes(t))return!1;let s=Math.max(Number(r)||0,Number(i)||0);return s?a-s>=o:!1}var bo=160;function xo(e){let t=String(e??``).replace(/\s+/g,` `).trim();if(!t)return``;let n=Array.from(t);return n.length<=bo?t:`${n.slice(0,bo).join(``).trimEnd()}…`}function So(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 Co({phase:e=``,queuedText:t=``,questionText:n=``,title:r=``}={}){let i=e===`queued`?xo(t):``,a=i||xo(n),o=xo(r),s=a||o,c=i?`queued`:a?`question`:s?`title`:``;return{primary:s,sub:a&&!So(o,a)?o:``,isQuestion:!!a,from:c}}function wo(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 To({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=Ya}={}){let te=_o(s),ne=new Set([..._o(a),..._o(o),...te]),_=new Set(_o(c)),v=new Set(_o(d)),re=new Set(_o(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=yo({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=Co({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=Xa[e.phase]-Xa[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 Eo(e){return oo.has(e)||v.generatingSessionIds.has(e)||v.pendingCallApiSessionIds.has(e)}function Do(){let e={};try{let t=Xr();for(let n of t){let t=Rt(n);t>0&&(e[n]=t)}}catch(e){r.debug(`[SessionDock] read queue counts failed:`,e?.message||e)}return e}function Oo(){let e={};for(let t of v.sessions||[])e[t.id]=t.title||``;for(let[t,n]of ro)e[t]||(e[t]=n);return e}function ko(){let e={},t={},n=new Map;for(let e of v.sessions||[])n.set(e.id,e);for(let r of new Set([...oo,...v.generatingSessionIds,...v.pendingCallApiSessionIds,...v.completedSessionIds])){let i=Qa.get(r)||$a.get(r)||0,a=io.get(r);if(i&&a&&a.stamp===i){a.text&&(e[r]=a.text,t[r]=a.messageId||``);continue}let o=wo(n.get(r));o.text&&(e[r]=o.text,t[r]=o.messageId)}return{questions:e,anchors:t}}function Ao(){let e={};try{for(let t of Xr()){let n=St(t);n?.text&&(e[t]=String(n.text))}}catch(e){r.debug(`[SessionDock] read queued texts failed:`,e?.message||e)}return e}function jo(e){for(let t of e||[]){let e=t.sessionId;if(!e)continue;let n=t.startedAt||t.doneAt||0,i=io.get(e),a=!i||i.stamp!==n,o=!t.title;!a&&!o||ao.has(e)||(ao.add(e),y(e).then(t=>{if(t&&((o||!ro.has(e))&&ro.set(e,t.title||``),a)){let r=wo(t);io.set(e,{text:r.text,messageId:r.messageId,stamp:n})}}).catch(e=>{r.debug(`[SessionDock] hydrate label failed:`,e?.message||e)}).finally(()=>{ao.delete(e),F()}))}}function Mo(e){if(!e)return``;let t=new Date(e);return`${String(t.getHours()).padStart(2,`0`)}:${String(t.getMinutes()).padStart(2,`0`)}`}function No(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:Mo(e.doneAt)}):t(`dock.done`)}function Po(){let e=v.completedSessionIds;for(let e of new Set([...oo,...v.generatingSessionIds,...v.pendingCallApiSessionIds]))Qa.has(e)||Qa.set(e,Date.now()),$a.delete(e);for(let e of oo)no.delete(e);for(let t of e)!$a.has(t)&&!Eo(t)&&$a.set(t,Date.now());let{questions:t,anchors:n}=ko(),r=To({activeSessionId:v.activeSessionId,titles:Oo(),questions:t,anchors:n,queuedTexts:Ao(),generatingIds:v.generatingSessionIds,pendingIds:v.pendingCallApiSessionIds,runningIds:oo,completedIds:e,queuedCounts:Do(),scheduledIds:to,dismissedIds:no,nodeInfo:Object.fromEntries(Za),startedAt:Object.fromEntries(Qa),doneAt:Object.fromEntries($a),lastUpdateAt:Object.fromEntries(eo),now:Date.now()});return jo(r),r}function Fo(e){let t=new Set(so.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&&(co=new Set(n),ho&&clearTimeout(ho),ho=setTimeout(()=>{ho=null,co=new Set,F()},Ka))}function Io(){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),Lo();let e=document.getElementById(`chatContainer`);return e&&typeof ResizeObserver<`u`&&new ResizeObserver(Lo).observe(e),window.addEventListener(`resize`,Lo),M}function Lo(){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 Ro(e){vt(e.sessionId,{focusMessageId:e.anchorMessageId||null})}function zo(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`),co.has(e.sessionId)&&n.classList.add(`is-flash`);let r=e.title||t(`dock.unknownSession`),i=e.primary||r,a=No(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`,()=>{Ro(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(),Qo(e.sessionId)}),n.appendChild(r)}return n.addEventListener(`mouseenter`,()=>Bo(n,e,a)),n.addEventListener(`mouseleave`,Vo),n.addEventListener(`focusin`,()=>Bo(n,e,a)),n.addEventListener(`focusout`,Vo),n}function Bo(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 Vo(){N&&N.classList.remove(`show`)}function Ho(){return P||typeof document>`u`?P:(P=document.createElement(`div`),P.className=`session-dock-overflow`,P.setAttribute(`role`,`menu`),P.addEventListener(`mouseenter`,Uo),P.addEventListener(`mouseleave`,Wo),P.addEventListener(`focusin`,Uo),P.addEventListener(`focusout`,Wo),document.body.appendChild(P),P)}function Uo(){go&&=(clearTimeout(go),null)}function Wo(){uo||(Uo(),go=setTimeout(()=>{go=null,Yo()},220))}function Go(){let e=M?M.querySelector(`.session-dock-more`):null;e&&(e.setAttribute(`aria-expanded`,uo?`true`:`false`),e.classList.toggle(`is-open`,uo))}function Ko(){let e=Ho();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 lo){let n=e.primary||e.title||t(`dock.unknownSession`),i=No(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`,()=>{Yo(),Ro(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 Jo(){lo.length!==0&&Ho()&&(Uo(),Ko(),qo(),P.classList.add(`show`),Go())}function Yo(){Uo(),uo=!1,P&&P.classList.remove(`show`),Go()}function Xo(){if(P&&P.classList.contains(`show`)&&uo){Yo();return}Jo(),uo=!0,Go()}function Zo(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`,uo?`true`:`false`),r.textContent=`+${e.length>99?`99`:e.length}`,r.addEventListener(`click`,()=>Xo()),n.appendChild(r),n.addEventListener(`mouseenter`,()=>Jo()),n.addEventListener(`mouseleave`,Wo),n.addEventListener(`focusin`,()=>Jo()),n.addEventListener(`focusout`,Wo),n}function Qo(e){e&&(no.add(e),$o(),F())}function $o(){try{chrome.storage.local.set({[Ua]:Array.from(no)}).catch(()=>{})}catch{}}function es(){try{chrome.storage.local.get([Ua],e=>{let t=e?.[Ua];if(Array.isArray(t)){for(let e of t)no.add(e);F()}})}catch{}}function ts(){if(!Io())return;let e=Po();if(Fo(e),so=e,Yo(),lo=[],M.innerHTML=``,e.length===0){M.classList.remove(`show`),document.body.classList.remove(`has-session-dock`),Vo();return}let t=e.length>qa?Ja:qa;lo=e.slice(t);for(let n of e.slice(0,t))M.appendChild(zo(n));lo.length>0&&M.appendChild(Zo(lo)),M.classList.add(`show`),document.body.classList.add(`has-session-dock`)}function F(){fo||=setTimeout(()=>{fo=null;try{ts()}catch(e){r.warn(`[SessionDock] render failed:`,e?.message||e)}},Ga)}function ns(){return new Promise(e=>{try{chrome.runtime.sendMessage({type:`QUERY_SESSION_RUNNING`},t=>{if(chrome.runtime.lastError||!t){e();return}Array.isArray(t.activeSessionIds)&&(oo=vo(t.activeSessionIds)),e()})}catch{e()}})}function rs(e){let t=e?.sessionId;if(!t)return;let n=Za.get(t)||{};Za.set(t,{nodeName:e.nodeName||n.nodeName||``,subtaskIndex:e.subtaskIndex||n.subtaskIndex||0,subtaskTotal:e.subtaskTotal||n.subtaskTotal||0}),eo.set(t,Date.now()),F()}function is(e){e&&(Za.delete(e),Qa.delete(e),$a.delete(e),eo.delete(e),no.delete(e),ro.delete(e),io.delete(e),F())}function as(){if(!(mo||typeof document>`u`||!Io())){mo=!0,es(),document.addEventListener(`generating-state-changed`,F),document.addEventListener(`session-switched`,F),document.addEventListener(`generation-ended`,e=>{let t=e?.detail?.sessionId;t&&!$a.has(t)&&$a.set(t,Date.now()),F()}),document.addEventListener(`session-archived`,e=>is(e?.detail?.sessionId)),document.addEventListener(`session-deleted`,e=>is(e?.detail?.sessionId));try{$t(F)}catch(e){r.debug(`[SessionDock] subscribe queue failed:`,e?.message||e)}try{chrome.runtime.onMessage.addListener(e=>e?e.type===`EXECUTION_STATUS_UPDATE`?(rs(e),!1):e.type===`SCHEDULED_TASK_RUN_STATE`&&e.sessionId?(e.running?to.add(e.sessionId):to.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){Yo();return}ns().then(F)}),document.addEventListener(`keydown`,e=>{e.key===`Escape`&&uo&&Yo()}),po||=setInterval(()=>{document.hidden||ns().then(F)},Wa),ns().then(()=>{for(let e of oo)Qa.has(e)||Qa.set(e,Date.now());ts()})}}function os(){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 et(e,n.top,n.bottom)}function p(e,t){let n=document.getElementById(`chatContainer`);if(!n)return`noop`;let r=qe(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=Xe(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=qe(document.getElementById(`chatContainer`));let e=l?qe(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=qe(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=ft(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 ss(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 cs=!1,ls=!1,I=[],us=``;function ds(){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-CWyjBBv3.js","assets/chunk-CMxvf4Kt.js","assets/model-profiles-C3kJEHM6.js","assets/i18n-DvmxOw8q.js","assets/version-DUmOB_mV.js","assets/agent-store-QTeMyM9O.js","assets/session-store-owqj23pJ.js","assets/voice-shortcut-Dtt3nhkz.js","assets/workspace-manager-DVPkwn2d.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-DvmxOw8q.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-C3kJEHM6.js";import{_ as D,d as fe}from"./session-store-owqj23pJ.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-DK2Wxmvk.js";import{$ as Ge,A as Ke,D as qe,G as Je,H as Ye,J as Xe,K as Ze,M as k,N as Qe,O as $e,P as et,Q as tt,R as nt,T as rt,V as it,W as at,Y as A,Z as ot,_ as st,et as ct,g as lt,j,k as ut,l as dt,q as ft,t as pt,tt as mt,v as ht,y as gt}from"./version-DUmOB_mV.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,Gt as Kt,H as qt,Hn as Jt,Hr as Yt,Ht as Xt,I as Zt,In as Qt,Ir as $t,It as en,J as tn,Jn as nn,Jt as rn,K as an,Kn as on,Kt as sn,L as cn,Ln as ln,Lr as un,Lt as dn,M as fn,Mn as pn,Mr as mn,Mt as hn,N as gn,Nn as _n,Nr as vn,Nt as yn,O as bn,On as xn,Or as Sn,Ot as Cn,P as wn,Pn as Tn,Pr as En,Pt as Dn,Q as On,Qn as kn,Qt as An,R as jn,Rn as Mn,Rr as Nn,Rt as Pn,S as Fn,Sn as In,Sr as Ln,St as Rn,T as zn,Tn as Bn,Tr as Vn,Tt as Hn,U as Un,Un as Wn,Ur as Gn,Ut as Kn,Vn as qn,Vr as Jn,Vt as Yn,W as Xn,Wn as Zn,Wr as Qn,Wt as $n,X as er,Xn as tr,Xt as nr,Y as rr,Yn as ir,Yt as ar,Z as or,Zn as sr,Zt as cr,_ as lr,_n as ur,_r as dr,_t as fr,a as pr,an as mr,ar as hr,at as gr,b as _r,bn as vr,br as yr,bt as br,c as xr,cr as Sr,ct as Cr,d as wr,dn as Tr,dr as Er,dt as Dr,en as Or,er as kr,et as Ar,f as jr,fn as Mr,fr as Nr,g as Pr,gr as Fr,gt as Ir,h as Lr,hn as Rr,hr as zr,ht as Br,i as Vr,in as Hr,ir as Ur,it as Wr,j as Gr,jn as Kr,jr as qr,jt as Jr,k as Yr,kn as Xr,kr as Zr,kt as Qr,l as $r,ln as ei,lr as ti,lt as ni,m as ri,mn as ii,mr as ai,mt as oi,n as si,nn as ci,nt as li,o as ui,on as di,or as fi,ot as pi,p as mi,pn as hi,pr as gi,pt as _i,q as vi,qn as yi,qt as bi,r as xi,rn as Si,rr as Ci,rt as wi,s as Ti,sn as Ei,sr as Di,st as Oi,t as ki,tn as Ai,tr as ji,tt as Mi,u as Ni,un as Pi,ur as Fi,ut as Ii,v as Li,vn as Ri,vr as zi,vt as Bi,w as Vi,wn as Hi,wr as Ui,wt as Wi,x as Gi,xn as Ki,xt as qi,y as Ji,yn as Yi,yr as Xi,yt as Zi,z as Qi,zn as $i,zr as ea,zt as ta}from"./context-indicator-CWyjBBv3.js";import{o as na}from"./agent-store-QTeMyM9O.js";import{O as ra,b as ia,l as aa,p as oa,v as sa}from"./workspace-manager-DVPkwn2d.js";var ca=`panel-observer-`,la=new Map;function ua(e){if(!e)return null;let t=la.get(e);if(t)return t;let n;try{n=chrome.runtime.connect({name:`${ca}${e}`})}catch(e){return r.debug(`[PanelObserver] 建立观察端口失败(忽略):`,e?.message||e),null}la.set(e,n);try{n.onDisconnect.addListener(()=>{la.get(e)===n&&la.delete(e)})}catch(e){r.debug(`[PanelObserver] 观察端口断开监听挂不上(忽略):`,e?.message||e)}return n}function da(e){if(!e)return;let t=la.get(e);if(t){la.delete(e);try{t.disconnect()}catch(e){r.debug(`[PanelObserver] 关闭观察端口异常(忽略):`,e?.message||e)}}}function fa({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 pa({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 ma=!1,ha=new Map,ga=null,_a=!1,va=null,ya=null,ba=null,xa=250,Sa=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 Ca(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 wa(e,t){let n=new Map;return{start(){Hn(e,``),Wi(``),zt(Date.now()),Oi(t),Rn(t)},chunk(n){Hn(e,n),Ft(t,n)},restore({html:e}){Ii(t,e)},toolCalls(e,n){typeof n==`string`&&n&&qi(t,n),Cr(t,e)},toolResult(e){ni(e,t)},agentStream(e){let r=n.get(e.execId);if(!r){let i=_i(e.toolCallId?t.querySelector(`.tool-call-item[data-tool-call-id="${e.toolCallId}"]`):null,t.querySelector(`.stream-content`));r={element:i,codeEl:i.querySelector(`code`),stderrSeparator:null},n.set(e.execId,r),dt()}let i=r.codeEl;if(!i)return;let a=e.data||``;if(a){let t=document.createTextNode(a);if(e.streamType===`stderr`){if(!r.stderrSeparator){let e=document.createTextNode(`
3
+ `);i.appendChild(e),r.stderrSeparator=e}i.appendChild(t)}else r.stderrSeparator?i.insertBefore(t,r.stderrSeparator):i.appendChild(t)}let o=i.parentElement;o&&(o.scrollTop=o.scrollHeight)},agentStreamDone(e){let t=n.get(e.execId);t&&e.exitCode!==0&&t.element.classList.add(`agent-stream-error`)},retrying(e,n){Bi(t,e,n)},preselect(e){let n=t.querySelector(`.message-content`);!n||!e.length||e.forEach(e=>n.insertBefore(oi(e),n.firstChild))},final(e,n,r={}){fr(t,e,n,r.reflectionScore,r.reasoningContent,r.wasRevised)},error(e,n){fr(t,e,n||[])}}}async function Ta(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-CWyjBBv3.js`).then(e=>e.xr);return{appendMessageToSession:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]));await a(t,i)}function Ea(){E(()=>import(`./context-indicator-CWyjBBv3.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 Da=1e3;function Oa(e){return Promise.race([Cn(e),new Promise(e=>setTimeout(()=>e(null),Da))])}function ka(e,n){let i=Br(e);if(i())return!1;let a=pi(e);a.dataset.callId=n,i(a),Hn(e,``),zt(Date.now()),jt(Date.now()),v.pendingCallApiSessionIds.add(e),v.generatingSessionIds.add(e),Ea();try{document.dispatchEvent(new CustomEvent(`generating-state-changed`))}catch{}let o=fa({sessionId:e,callId:n,awaitSnapshot:!0,renderer:wa(e,a),persist:t=>Ta(t,e,a),emptyFallback:t(`chatMsg.emptyModelReply`),onFinished:()=>{if(ha.get(e)===o){ha.delete(e),da(e),v.pendingCallApiSessionIds.delete(e),Ea(),Ir(e);try{document.dispatchEvent(new CustomEvent(`session-cache-invalidate`,{detail:{sessionId:e}}))}catch{}on(e)}}});return ha.set(e,o),ua(e),Oa(e).then(t=>{o.finished||ha.get(e)!==o||o.restore(t)}).catch(()=>o.restore(null)),v.activeSessionId===e&&Zi(e),r.info(`[ChatReattach] 已接管运行中的任务: sessionId=${e}, callId=${n}`),!0}function Aa(e){let t=ha.get(e);if(!t)return;ha.delete(e),da(e);try{t.dispose?.()}catch{}let n=Br(e),r=n();try{r?.remove()}catch{}n(null),Ir(e),v.pendingCallApiSessionIds.delete(e),Ea();try{document.dispatchEvent(new CustomEvent(`generating-state-changed`))}catch{}}function ja(){let e=ga;e&&Promise.resolve().then(()=>e.syncFromBackground()).catch(e=>r.debug(`[ChatReattach] 对齐后台状态失败(忽略):`,e?.message||e))}function Ma(){!ma||!ga||ba||(ba=setTimeout(()=>{ba=null,ja()},xa))}var Na=new Map,Pa=3e3,Fa=100,Ia=new Set,La=new Set([`API_COMPLETE`,`API_ERROR`]);function Ra(e,t){let n=`${e}|${t.callId}`;Ia.has(n)||(Ia.add(n),Ia.size>Fa&&Ia.delete(Ia.values().next().value),Aa(e),ka(e,t.callId)&&ha.get(e)?.handleMessage(t))}function za(e,t,n){let r=Na.get(e);if(r){r.messages.push(n);return}r={callId:t,messages:[n]},Na.set(e,r),Ca(Pa).then(t=>Ba(e,t&&t.activeCallIds&&t.activeCallIds[e]||null)).catch(()=>Ba(e,null)).finally(()=>{Na.delete(e)})}function Ba(e,t){let n=Na.get(e);if(!n)return;let{callId:r,messages:i}=n;if(t===r)Aa(e),ka(e,r);else if(t===null){let t=i.find(e=>La.has(e.type));if(!t)return;Ra(e,t);return}else return;let a=ha.get(e);if(!(!a||a.callId!==r))for(let e of i){if(a.finished)break;a.handleMessage(e)}}function Va(){_a||(_a=!0,chrome.runtime.onMessage.addListener(e=>{if(!e)return!1;let t=e.sessionId?ha.get(e.sessionId):null;return t?e.callId&&e.callId!==t.callId?(za(e.sessionId,e.callId,e),!1):(ua(e.sessionId),t.handleMessage(e),!1):(e.callId&&Sa.has(e.type)&&Ma(),!1)}),va=e=>{let t=e?.detail?.sessionId;t&&ha.has(t)&&Zi(t),Ma()},document.addEventListener(`session-hydrated`,va),ya=e=>{let t=e?.detail?.sessionId;t&&ha.has(t)&&Zi(t)},document.addEventListener(`chat-history-rendered`,ya))}function Ha(){return ma?{syncFromBackground:()=>ga.syncFromBackground()}:(ma=!0,Va(),ga=pa({queryRunning:Ca,hasLocalListener:e=>v.pendingCancelApiMap.has(e),isAttached:(e,t)=>ha.get(e)?.callId===t?(ua(e),!0):!1,attach:(e,t)=>{ka(e,t)}}),ga.syncFromBackground(),{syncFromBackground:()=>ga.syncFromBackground()})}function Ua(e){!ma||!ga||(e&&v.activeSessionId===e&&Zi(e),ga.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 Wa=`sessionDockDismissed`,Ga=5e3,Ka=250,qa=1200,Ja=8,Ya=Ja-1,Xa=9e4,Za={running:0,queued:1,done:2},Qa=new Map,$a=new Map,eo=new Map,to=new Map,no=new Set,ro=new Set,io=new Map,ao=new Map,oo=new Set,so=new Set,co=[],lo=new Set,M=null,N=null,P=null,uo=[],fo=!1,po=null,mo=null,ho=!1,go=null,_o=null;function vo(e){return e?Array.isArray(e)?e:e instanceof Set?Array.from(e):[]:[]}function yo(e){let t=new Set;for(let n of vo(e))n&&t.add(h(String(n))||String(n));return t}function bo({phase:e=``,sessionId:t=null,backendRunningIds:n=[],startedAt:r=0,lastUpdateAt:i=0,now:a=Date.now(),staleMs:o=Xa}={}){if(e!==`running`||!t||vo(n).includes(t))return!1;let s=Math.max(Number(r)||0,Number(i)||0);return s?a-s>=o:!1}var xo=160;function So(e){let t=String(e??``).replace(/\s+/g,` `).trim();if(!t)return``;let n=Array.from(t);return n.length<=xo?t:`${n.slice(0,xo).join(``).trimEnd()}…`}function Co(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 wo({phase:e=``,queuedText:t=``,questionText:n=``,title:r=``}={}){let i=e===`queued`?So(t):``,a=i||So(n),o=So(r),s=a||o,c=i?`queued`:a?`question`:s?`title`:``;return{primary:s,sub:a&&!Co(o,a)?o:``,isQuestion:!!a,from:c}}function To(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 Eo({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=Xa}={}){let te=vo(s),ne=new Set([...vo(a),...vo(o),...te]),_=new Set(vo(c)),v=new Set(vo(d)),re=new Set(vo(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=bo({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=wo({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=Za[e.phase]-Za[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 Do(e){return so.has(e)||v.generatingSessionIds.has(e)||v.pendingCallApiSessionIds.has(e)}function Oo(){let e={};try{let t=St();for(let n of t){let t=Pt(n);t>0&&(e[n]=t)}}catch(e){r.debug(`[SessionDock] read queue counts failed:`,e?.message||e)}return e}function ko(){let e={};for(let t of v.sessions||[])e[t.id]=t.title||``;for(let[t,n]of io)e[t]||(e[t]=n);return e}function Ao(){let e={},t={},n=new Map;for(let e of v.sessions||[])n.set(e.id,e);for(let r of new Set([...so,...v.generatingSessionIds,...v.pendingCallApiSessionIds,...v.completedSessionIds])){let i=$a.get(r)||eo.get(r)||0,a=ao.get(r);if(i&&a&&a.stamp===i){a.text&&(e[r]=a.text,t[r]=a.messageId||``);continue}let o=To(n.get(r));o.text&&(e[r]=o.text,t[r]=o.messageId)}return{questions:e,anchors:t}}function jo(){let e={};try{for(let t of St()){let n=qr(t);n?.text&&(e[t]=String(n.text))}}catch(e){r.debug(`[SessionDock] read queued texts failed:`,e?.message||e)}return e}function Mo(e){for(let t of e||[]){let e=t.sessionId;if(!e)continue;let n=t.startedAt||t.doneAt||0,i=ao.get(e),a=!i||i.stamp!==n,o=!t.title;!a&&!o||oo.has(e)||(oo.add(e),y(e).then(t=>{if(t&&((o||!io.has(e))&&io.set(e,t.title||``),a)){let r=To(t);ao.set(e,{text:r.text,messageId:r.messageId,stamp:n})}}).catch(e=>{r.debug(`[SessionDock] hydrate label failed:`,e?.message||e)}).finally(()=>{oo.delete(e),F()}))}}function No(e){if(!e)return``;let t=new Date(e);return`${String(t.getHours()).padStart(2,`0`)}:${String(t.getMinutes()).padStart(2,`0`)}`}function Po(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:No(e.doneAt)}):t(`dock.done`)}function Fo(){let e=v.completedSessionIds;for(let e of new Set([...so,...v.generatingSessionIds,...v.pendingCallApiSessionIds]))$a.has(e)||$a.set(e,Date.now()),eo.delete(e);for(let e of so)ro.delete(e);for(let t of e)!eo.has(t)&&!Do(t)&&eo.set(t,Date.now());let{questions:t,anchors:n}=Ao(),r=Eo({activeSessionId:v.activeSessionId,titles:ko(),questions:t,anchors:n,queuedTexts:jo(),generatingIds:v.generatingSessionIds,pendingIds:v.pendingCallApiSessionIds,runningIds:so,completedIds:e,queuedCounts:Oo(),scheduledIds:no,dismissedIds:ro,nodeInfo:Object.fromEntries(Qa),startedAt:Object.fromEntries($a),doneAt:Object.fromEntries(eo),lastUpdateAt:Object.fromEntries(to),now:Date.now()});return Mo(r),r}function Io(e){let t=new Set(co.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&&(lo=new Set(n),go&&clearTimeout(go),go=setTimeout(()=>{go=null,lo=new Set,F()},qa))}function Lo(){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),Ro();let e=document.getElementById(`chatContainer`);return e&&typeof ResizeObserver<`u`&&new ResizeObserver(Ro).observe(e),window.addEventListener(`resize`,Ro),M}function Ro(){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 zo(e){kr(e.sessionId,{focusMessageId:e.anchorMessageId||null})}function Bo(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`),lo.has(e.sessionId)&&n.classList.add(`is-flash`);let r=e.title||t(`dock.unknownSession`),i=e.primary||r,a=Po(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`,()=>{zo(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(),$o(e.sessionId)}),n.appendChild(r)}return n.addEventListener(`mouseenter`,()=>Vo(n,e,a)),n.addEventListener(`mouseleave`,Ho),n.addEventListener(`focusin`,()=>Vo(n,e,a)),n.addEventListener(`focusout`,Ho),n}function Vo(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 Ho(){N&&N.classList.remove(`show`)}function Uo(){return P||typeof document>`u`?P:(P=document.createElement(`div`),P.className=`session-dock-overflow`,P.setAttribute(`role`,`menu`),P.addEventListener(`mouseenter`,Wo),P.addEventListener(`mouseleave`,Go),P.addEventListener(`focusin`,Wo),P.addEventListener(`focusout`,Go),document.body.appendChild(P),P)}function Wo(){_o&&=(clearTimeout(_o),null)}function Go(){fo||(Wo(),_o=setTimeout(()=>{_o=null,Xo()},220))}function Ko(){let e=M?M.querySelector(`.session-dock-more`):null;e&&(e.setAttribute(`aria-expanded`,fo?`true`:`false`),e.classList.toggle(`is-open`,fo))}function qo(){let e=Uo();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 uo){let n=e.primary||e.title||t(`dock.unknownSession`),i=Po(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`,()=>{Xo(),zo(e)}),r.appendChild(a)}e.appendChild(r)}function Jo(){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 Yo(){uo.length!==0&&Uo()&&(Wo(),qo(),Jo(),P.classList.add(`show`),Ko())}function Xo(){Wo(),fo=!1,P&&P.classList.remove(`show`),Ko()}function Zo(){if(P&&P.classList.contains(`show`)&&fo){Xo();return}Yo(),fo=!0,Ko()}function Qo(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`,fo?`true`:`false`),r.textContent=`+${e.length>99?`99`:e.length}`,r.addEventListener(`click`,()=>Zo()),n.appendChild(r),n.addEventListener(`mouseenter`,()=>Yo()),n.addEventListener(`mouseleave`,Go),n.addEventListener(`focusin`,()=>Yo()),n.addEventListener(`focusout`,Go),n}function $o(e){e&&(ro.add(e),es(),F())}function es(){try{chrome.storage.local.set({[Wa]:Array.from(ro)}).catch(()=>{})}catch{}}function ts(){try{chrome.storage.local.get([Wa],e=>{let t=e?.[Wa];if(Array.isArray(t)){for(let e of t)ro.add(e);F()}})}catch{}}function ns(){if(!Lo())return;let e=Fo();if(Io(e),co=e,Xo(),uo=[],M.innerHTML=``,e.length===0){M.classList.remove(`show`),document.body.classList.remove(`has-session-dock`),Ho();return}let t=e.length>Ja?Ya:Ja;uo=e.slice(t);for(let n of e.slice(0,t))M.appendChild(Bo(n));uo.length>0&&M.appendChild(Qo(uo)),M.classList.add(`show`),document.body.classList.add(`has-session-dock`)}function F(){po||=setTimeout(()=>{po=null;try{ns()}catch(e){r.warn(`[SessionDock] render failed:`,e?.message||e)}},Ka)}function rs(){return new Promise(e=>{try{chrome.runtime.sendMessage({type:`QUERY_SESSION_RUNNING`},t=>{if(chrome.runtime.lastError||!t){e();return}Array.isArray(t.activeSessionIds)&&(so=yo(t.activeSessionIds)),e()})}catch{e()}})}function is(e){let t=e?.sessionId;if(!t)return;let n=Qa.get(t)||{};Qa.set(t,{nodeName:e.nodeName||n.nodeName||``,subtaskIndex:e.subtaskIndex||n.subtaskIndex||0,subtaskTotal:e.subtaskTotal||n.subtaskTotal||0}),to.set(t,Date.now()),F()}function as(e){e&&(Qa.delete(e),$a.delete(e),eo.delete(e),to.delete(e),ro.delete(e),io.delete(e),ao.delete(e),F())}function os(){if(!(ho||typeof document>`u`||!Lo())){ho=!0,ts(),document.addEventListener(`generating-state-changed`,F),document.addEventListener(`session-switched`,F),document.addEventListener(`generation-ended`,e=>{let t=e?.detail?.sessionId;t&&!eo.has(t)&&eo.set(t,Date.now()),F()}),document.addEventListener(`session-archived`,e=>as(e?.detail?.sessionId)),document.addEventListener(`session-deleted`,e=>as(e?.detail?.sessionId));try{un(F)}catch(e){r.debug(`[SessionDock] subscribe queue failed:`,e?.message||e)}try{chrome.runtime.onMessage.addListener(e=>e?e.type===`EXECUTION_STATUS_UPDATE`?(is(e),!1):e.type===`SCHEDULED_TASK_RUN_STATE`&&e.sessionId?(e.running?no.add(e.sessionId):no.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){Xo();return}rs().then(F)}),document.addEventListener(`keydown`,e=>{e.key===`Escape`&&fo&&Xo()}),mo||=setInterval(()=>{document.hidden||rs().then(F)},Ga),rs().then(()=>{for(let e of so)$a.has(e)||$a.set(e,Date.now());ns()})}}function ss(){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 et(e,n.top,n.bottom)}function p(e,t){let n=document.getElementById(`chatContainer`);if(!n)return`noop`;let r=qe(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=Xe(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=qe(document.getElementById(`chatContainer`));let e=l?qe(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=qe(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=ft(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 cs(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 ls=!1,us=!1,I=[],ds=``;function fs(){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=`
4
4
  <button class="search-panel-toggle" id="searchPanelToggle" title="${t(`searchPanel.toggleTitle`)}">
5
5
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
6
6
  <circle cx="11" cy="11" r="8"/>
@@ -35,13 +35,13 @@ import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-DvmxOw8q.js"
35
35
  <div class="search-panel-empty">${t(`searchPanel.startSearchHint`)}</div>
36
36
  </div>
37
37
  </div>
38
- `,Nn(`search`).appendChild(e),fs(),r.debug(`[SearchPanel] search panelinitializing`)}function fs(){document.getElementById(`searchPanelContainer`);let e=document.getElementById(`searchPanel`),t=document.getElementById(`searchPanelToggle`),n=document.getElementById(`searchPanelInput`),r=document.getElementById(`searchPanelClear`),i=document.getElementById(`searchPanelClose`),a=document.getElementById(`searchModeGlobal`),o=document.getElementById(`searchModeCurrent`);t.addEventListener(`click`,()=>{e.classList.contains(`expanded`)?ms():ps()}),i.addEventListener(`click`,()=>{ms()}),r.addEventListener(`click`,()=>{n.value=``,r.style.display=`none`,hs(),n.focus()}),n.addEventListener(`input`,()=>{let e=n.value.trim();r.style.display=e?``:`none`,e||hs()}),n.addEventListener(`keydown`,e=>{if(e.key===`Enter`){e.stopPropagation();let t=n.value.trim();t&&(s(t),gs(t))}else if(e.key===`Escape`)v.searchInputHistoryIndex>=0?(v.searchInputHistoryIndex=-1,n.value=``):(e.stopPropagation(),ms());else if(e.key===`ArrowUp`){e.preventDefault(),e.stopPropagation();let t=v.searchInputHistory;if(t.length===0)return;v.searchInputHistoryIndex===-1?v.searchInputHistoryIndex=t.length-1:v.searchInputHistoryIndex>0&&v.searchInputHistoryIndex--,n.value=t[v.searchInputHistoryIndex]||``,r.style.display=n.value?``:`none`,n.selectionStart=n.selectionEnd=n.value.length}else if(e.key===`ArrowDown`){e.preventDefault(),e.stopPropagation();let t=v.searchInputHistory;v.searchInputHistoryIndex>=0&&v.searchInputHistoryIndex<t.length-1?(v.searchInputHistoryIndex++,n.value=t[v.searchInputHistoryIndex]||``,n.selectionStart=n.selectionEnd=n.value.length):(v.searchInputHistoryIndex=-1,n.value=``),r.style.display=n.value?``:`none`}});function s(e){if(!e||!e.trim())return;let t=e.trim(),n=v.searchInputHistory,r=n.indexOf(t);r!==-1&&n.splice(r,1),n.push(t),n.length>20&&n.shift(),v.searchInputHistoryIndex=-1;try{chrome.storage.local.set({searchInputHistory:n})}catch{}}a.addEventListener(`click`,()=>{a.classList.contains(`active`)||(a.classList.add(`active`),o.classList.remove(`active`));let e=n.value.trim();e&&gs(e)}),o.addEventListener(`click`,()=>{o.classList.contains(`active`)||(o.classList.add(`active`),a.classList.remove(`active`));let e=n.value.trim();e&&gs(e)}),document.getElementById(`searchPanelContent`).addEventListener(`click`,async e=>{let t=e.target.closest(`.search-result-item`);if(!t)return;let n=t.dataset.sessionId,r=t.dataset.messageId;await ws(n,r)})}function ps(){let e=document.getElementById(`searchPanel`),t=document.getElementById(`searchPanelInput`);e.classList.add(`expanded`),$e(e),t.value.trim()&&I.length===0&&gs(t.value.trim()),setTimeout(()=>t.focus(),100)}function ms(){let e=document.getElementById(`searchPanel`);e.classList.remove(`expanded`),Ze(e),ls=!0,cs=!1}function hs(){ls=!0,cs=!1,I=[],us=``;let e=document.getElementById(`searchPanelContent`),n=document.getElementById(`searchPanelCount`);e&&(e.innerHTML=`<div class="search-panel-empty">${t(`searchPanel.startSearchHint`)}</div>`),n&&(n.textContent=``)}async function gs(e){if(!e||!e.trim()||(e=e.trim().toLowerCase(),cs&&us===e))return;ls=!0,await new Promise(e=>setTimeout(e,50)),cs=!0,ls=!1,I=[],us=e;let n=document.getElementById(`searchPanelContent`),i=document.getElementById(`searchPanelCount`);n.innerHTML=`<div class="search-panel-loading">${t(`searchPanel.searching`)}</div>`,i.textContent=``;let a=document.getElementById(`searchModeGlobal`).classList.contains(`active`);try{a?await vs(e,n,i):await _s(e,n,i)}catch(e){r.error(`[SearchPanel] search error:`,e),ls||(n.innerHTML=`<div class="search-panel-empty">${t(`searchPanel.searchError`)}</div>`)}ls||(cs=!1)}async function _s(e,n,r){let i=v.activeSessionId;if(!i){n.innerHTML=`<div class="search-panel-empty">${t(`searchPanel.noActiveSession`)}</div>`;return}let a=ys(v.messageHistory||[],e,i);if(!ls){if(I=a,r.textContent=a.length>0?t(`searchPanel.countResult`,{count:a.length}):t(`searchPanel.noResult`),a.length===0){n.innerHTML=`<div class="search-panel-empty">${t(`searchPanel.noMatch`)}</div>`;return}xs(a,e,n)}}async function vs(e,n,i){let a=v.activeSessionId,o=await ce(),s=(o||[]).filter(e=>!e.archivedAt);if(ls)return;if(!s||s.length===0){n.innerHTML=`<div class="search-panel-empty">${t(`searchPanel.noSessionData`)}</div>`;return}let c=[],l=[];if(a){let r=ys(v.messageHistory||[],e,a);if(ls)return;let s=o.find(e=>e.id===a)?.title||t(`searchPanel.currentSession`);for(let e of r)c.push({...e,sessionTitle:s});I=[...c],i.textContent=t(`searchPanel.searchingWithCount`,{count:c.length}),xs(I,e,n,!0)}let u=s.filter(e=>e.id!==a);for(let a of u){if(ls)return;try{let r=await y(a.id);if(!r||!r.messageHistory)continue;let o=ys(r.messageHistory||[],e,a.id);if(o.length>0){for(let e of o)l.push({...e,sessionTitle:a.title||t(`searchPanel.unknownSession`)});I=[...c,...l];let r=c.length+l.length;i.textContent=r>0?t(`searchPanel.countResult`,{count:r}):t(`searchPanel.noResult`),xs(I,e,n)}}catch(e){r.warn(`[SearchPanel] searchsession failed:`,a.id,e)}await new Promise(e=>setTimeout(e,10))}if(ls)return;let d=I.length;if(i.textContent=d>0?t(`searchPanel.countResult`,{count:d}):t(`searchPanel.noResult`),d===0){n.innerHTML=`<div class="search-panel-empty">${t(`searchPanel.noMatch`)}</div>`;return}xs(I,e,n)}function ys(e,t,n){let r=[];if(!e||e.length===0)return r;let i=t.includes(`&`)||t.includes(`|`);for(let a of e){if(a.role!==`assistant`&&a.role!==`user`)continue;let e=a.messageId||a.id;if(!e)continue;let o=bs(a.content);if(!o)continue;let s=o.toLowerCase(),c=-1,l=t;if(i){let e=t.split(`|`).map(e=>e.trim()).filter(Boolean),n=!1;for(let t of e){let e=t.split(`&`).map(e=>e.trim()).filter(Boolean);if(e.length!==0&&e.every(e=>s.includes(e))){n=!0,l=e[0],c=s.indexOf(l);break}}if(!n)continue}else{if(!s.includes(t))continue;c=s.indexOf(t)}let u=l.length,d=Math.max(0,c-30),f=Math.min(o.length,c+u+30),p=o.substring(d,f);d>0&&(p=`...`+p),f<o.length&&(p+=`...`),r.push({messageId:e,content:o.substring(0,200),role:a.role,sessionId:n,matchPreview:p,query:t})}return r}function bs(e){return e?typeof e==`string`?e.replace(/<[^>]*>/g,``):Array.isArray(e)?e.filter(e=>e.type===`text`).map(e=>e.text||``).join(` `):String(e):``}function xs(e,n,r,i){if(r||=document.getElementById(`searchPanelContent`),!r)return;if(e.length===0){r.innerHTML=`<div class="search-panel-empty">${t(`searchPanel.noMatch`)}</div>`;return}let a=v.activeSessionId,o=e.filter(e=>e.sessionId===a),s=e.filter(e=>e.sessionId!==a),c=``,l=i?t(`searchPanel.searchingSuffix`):``;o.length>0&&(c+=`<div class="search-section">
38
+ `,ea(`search`).appendChild(e),ps(),r.debug(`[SearchPanel] search panelinitializing`)}function ps(){document.getElementById(`searchPanelContainer`);let e=document.getElementById(`searchPanel`),t=document.getElementById(`searchPanelToggle`),n=document.getElementById(`searchPanelInput`),r=document.getElementById(`searchPanelClear`),i=document.getElementById(`searchPanelClose`),a=document.getElementById(`searchModeGlobal`),o=document.getElementById(`searchModeCurrent`);t.addEventListener(`click`,()=>{e.classList.contains(`expanded`)?hs():ms()}),i.addEventListener(`click`,()=>{hs()}),r.addEventListener(`click`,()=>{n.value=``,r.style.display=`none`,gs(),n.focus()}),n.addEventListener(`input`,()=>{let e=n.value.trim();r.style.display=e?``:`none`,e||gs()}),n.addEventListener(`keydown`,e=>{if(e.key===`Enter`){e.stopPropagation();let t=n.value.trim();t&&(s(t),_s(t))}else if(e.key===`Escape`)v.searchInputHistoryIndex>=0?(v.searchInputHistoryIndex=-1,n.value=``):(e.stopPropagation(),hs());else if(e.key===`ArrowUp`){e.preventDefault(),e.stopPropagation();let t=v.searchInputHistory;if(t.length===0)return;v.searchInputHistoryIndex===-1?v.searchInputHistoryIndex=t.length-1:v.searchInputHistoryIndex>0&&v.searchInputHistoryIndex--,n.value=t[v.searchInputHistoryIndex]||``,r.style.display=n.value?``:`none`,n.selectionStart=n.selectionEnd=n.value.length}else if(e.key===`ArrowDown`){e.preventDefault(),e.stopPropagation();let t=v.searchInputHistory;v.searchInputHistoryIndex>=0&&v.searchInputHistoryIndex<t.length-1?(v.searchInputHistoryIndex++,n.value=t[v.searchInputHistoryIndex]||``,n.selectionStart=n.selectionEnd=n.value.length):(v.searchInputHistoryIndex=-1,n.value=``),r.style.display=n.value?``:`none`}});function s(e){if(!e||!e.trim())return;let t=e.trim(),n=v.searchInputHistory,r=n.indexOf(t);r!==-1&&n.splice(r,1),n.push(t),n.length>20&&n.shift(),v.searchInputHistoryIndex=-1;try{chrome.storage.local.set({searchInputHistory:n})}catch{}}a.addEventListener(`click`,()=>{a.classList.contains(`active`)||(a.classList.add(`active`),o.classList.remove(`active`));let e=n.value.trim();e&&_s(e)}),o.addEventListener(`click`,()=>{o.classList.contains(`active`)||(o.classList.add(`active`),a.classList.remove(`active`));let e=n.value.trim();e&&_s(e)}),document.getElementById(`searchPanelContent`).addEventListener(`click`,async e=>{let t=e.target.closest(`.search-result-item`);if(!t)return;let n=t.dataset.sessionId,r=t.dataset.messageId;await Ts(n,r)})}function ms(){let e=document.getElementById(`searchPanel`),t=document.getElementById(`searchPanelInput`);e.classList.add(`expanded`),$e(e),t.value.trim()&&I.length===0&&_s(t.value.trim()),setTimeout(()=>t.focus(),100)}function hs(){let e=document.getElementById(`searchPanel`);e.classList.remove(`expanded`),Ze(e),us=!0,ls=!1}function gs(){us=!0,ls=!1,I=[],ds=``;let e=document.getElementById(`searchPanelContent`),n=document.getElementById(`searchPanelCount`);e&&(e.innerHTML=`<div class="search-panel-empty">${t(`searchPanel.startSearchHint`)}</div>`),n&&(n.textContent=``)}async function _s(e){if(!e||!e.trim()||(e=e.trim().toLowerCase(),ls&&ds===e))return;us=!0,await new Promise(e=>setTimeout(e,50)),ls=!0,us=!1,I=[],ds=e;let n=document.getElementById(`searchPanelContent`),i=document.getElementById(`searchPanelCount`);n.innerHTML=`<div class="search-panel-loading">${t(`searchPanel.searching`)}</div>`,i.textContent=``;let a=document.getElementById(`searchModeGlobal`).classList.contains(`active`);try{a?await ys(e,n,i):await vs(e,n,i)}catch(e){r.error(`[SearchPanel] search error:`,e),us||(n.innerHTML=`<div class="search-panel-empty">${t(`searchPanel.searchError`)}</div>`)}us||(ls=!1)}async function vs(e,n,r){let i=v.activeSessionId;if(!i){n.innerHTML=`<div class="search-panel-empty">${t(`searchPanel.noActiveSession`)}</div>`;return}let a=bs(v.messageHistory||[],e,i);if(!us){if(I=a,r.textContent=a.length>0?t(`searchPanel.countResult`,{count:a.length}):t(`searchPanel.noResult`),a.length===0){n.innerHTML=`<div class="search-panel-empty">${t(`searchPanel.noMatch`)}</div>`;return}Ss(a,e,n)}}async function ys(e,n,i){let a=v.activeSessionId,o=await ce(),s=(o||[]).filter(e=>!e.archivedAt);if(us)return;if(!s||s.length===0){n.innerHTML=`<div class="search-panel-empty">${t(`searchPanel.noSessionData`)}</div>`;return}let c=[],l=[];if(a){let r=bs(v.messageHistory||[],e,a);if(us)return;let s=o.find(e=>e.id===a)?.title||t(`searchPanel.currentSession`);for(let e of r)c.push({...e,sessionTitle:s});I=[...c],i.textContent=t(`searchPanel.searchingWithCount`,{count:c.length}),Ss(I,e,n,!0)}let u=s.filter(e=>e.id!==a);for(let a of u){if(us)return;try{let r=await y(a.id);if(!r||!r.messageHistory)continue;let o=bs(r.messageHistory||[],e,a.id);if(o.length>0){for(let e of o)l.push({...e,sessionTitle:a.title||t(`searchPanel.unknownSession`)});I=[...c,...l];let r=c.length+l.length;i.textContent=r>0?t(`searchPanel.countResult`,{count:r}):t(`searchPanel.noResult`),Ss(I,e,n)}}catch(e){r.warn(`[SearchPanel] searchsession failed:`,a.id,e)}await new Promise(e=>setTimeout(e,10))}if(us)return;let d=I.length;if(i.textContent=d>0?t(`searchPanel.countResult`,{count:d}):t(`searchPanel.noResult`),d===0){n.innerHTML=`<div class="search-panel-empty">${t(`searchPanel.noMatch`)}</div>`;return}Ss(I,e,n)}function bs(e,t,n){let r=[];if(!e||e.length===0)return r;let i=t.includes(`&`)||t.includes(`|`);for(let a of e){if(a.role!==`assistant`&&a.role!==`user`)continue;let e=a.messageId||a.id;if(!e)continue;let o=xs(a.content);if(!o)continue;let s=o.toLowerCase(),c=-1,l=t;if(i){let e=t.split(`|`).map(e=>e.trim()).filter(Boolean),n=!1;for(let t of e){let e=t.split(`&`).map(e=>e.trim()).filter(Boolean);if(e.length!==0&&e.every(e=>s.includes(e))){n=!0,l=e[0],c=s.indexOf(l);break}}if(!n)continue}else{if(!s.includes(t))continue;c=s.indexOf(t)}let u=l.length,d=Math.max(0,c-30),f=Math.min(o.length,c+u+30),p=o.substring(d,f);d>0&&(p=`...`+p),f<o.length&&(p+=`...`),r.push({messageId:e,content:o.substring(0,200),role:a.role,sessionId:n,matchPreview:p,query:t})}return r}function xs(e){return e?typeof e==`string`?e.replace(/<[^>]*>/g,``):Array.isArray(e)?e.filter(e=>e.type===`text`).map(e=>e.text||``).join(` `):String(e):``}function Ss(e,n,r,i){if(r||=document.getElementById(`searchPanelContent`),!r)return;if(e.length===0){r.innerHTML=`<div class="search-panel-empty">${t(`searchPanel.noMatch`)}</div>`;return}let a=v.activeSessionId,o=e.filter(e=>e.sessionId===a),s=e.filter(e=>e.sessionId!==a),c=``,l=i?t(`searchPanel.searchingSuffix`):``;o.length>0&&(c+=`<div class="search-section">
39
39
  <div class="search-section-title">${t(`searchPanel.currentSessionResults`,{label:l,count:o.length})}</div>
40
- ${Ss(o,n)}
40
+ ${Cs(o,n)}
41
41
  </div>`),s.length>0&&(c+=`<div class="search-section">
42
42
  <div class="search-section-title">${t(`searchPanel.otherSessionsResults`,{count:s.length})}</div>
43
- ${Ss(s,n)}
44
- </div>`),r.innerHTML=c}function Ss(e,n){return e.map((e,r)=>{let i=e.role===`user`?`👤`:`🤖`,a=e.role===`user`?t(`searchPanel.roleUser`):t(`searchPanel.roleAssistant`),o=e.sessionTitle||``,s=e.sessionId===v.activeSessionId,c=Cs(k(e.matchPreview),n);return`
43
+ ${Cs(s,n)}
44
+ </div>`),r.innerHTML=c}function Cs(e,n){return e.map((e,r)=>{let i=e.role===`user`?`👤`:`🤖`,a=e.role===`user`?t(`searchPanel.roleUser`):t(`searchPanel.roleAssistant`),o=e.sessionTitle||``,s=e.sessionId===v.activeSessionId,c=ws(k(e.matchPreview),n);return`
45
45
  <div class="search-result-item" data-session-id="${e.sessionId}" data-message-id="${e.messageId}" title="${k(e.content)}">
46
46
  <div class="search-result-header">
47
47
  <span class="search-result-role">${i} ${a}</span>
@@ -49,7 +49,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-DvmxOw8q.js"
49
49
  </div>
50
50
  <div class="search-result-preview">${c}</div>
51
51
  </div>
52
- `}).join(``)}function Cs(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 ws(e,n){if(!(!e||!n)){if(v.activeSessionId!==e)try{let n=v.activeSessionId;if(await Gi(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-DSJveMWs.js`).then(e=>e.tr);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?(xs(I,us,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 Ts(e){return chrome.runtime.sendMessage(e)}function Es(e){return e?new Date(e).toLocaleString(void 0,{month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`}):`—`}function Ds(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 Os(e){return e===`success`?t(`schedPanel.statusSuccess`):e===`failed`?t(`schedPanel.statusFailed`):e===`running`?t(`schedPanel.statusRunning`):``}function ks(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 As(e){let n=e.schedule||{};return n.type===`once`?n.onceMode===`relative`?t(`schedPanel.scheduleTypeOnce`)+` · `+(n.value||``)+t(`schedPanel.minutesSuffix`):t(`schedPanel.scheduleTypeOnce`)+` · `+Es(new Date(n.value).getTime()):n.type===`interval`?t(`schedPanel.scheduleTypeInterval`)+` · `+(n.value||``):n.type===`cron`?t(`schedPanel.scheduleTypeCron`)+` · `+(n.value||``):``}function js(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 Ms(){let e=document.getElementById(`chatContainer`);e&&(e.scrollTop=e.scrollHeight)}async function Ns(e){if(e){if(v.activeSessionId!==e){let t=v.activeSessionId;try{if(await Gi(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-DSJveMWs.js`).then(e=>e.tr);return{renderSessionTabs:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]));e()}catch{}}setTimeout(Ms,500)}}function Ps(){let e=document.createElement(`div`);e.className=`schedule-panel-container`,e.id=`schedulePanelContainer`,e.innerHTML=`
52
+ `}).join(``)}function ws(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 Ts(e,n){if(!(!e||!n)){if(v.activeSessionId!==e)try{let n=v.activeSessionId;if(await Ln(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-CWyjBBv3.js`).then(e=>e.nr);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?(Ss(I,ds,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 Es(e){return chrome.runtime.sendMessage(e)}function Ds(e){return e?new Date(e).toLocaleString(void 0,{month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`}):`—`}function Os(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 ks(e){return e===`success`?t(`schedPanel.statusSuccess`):e===`failed`?t(`schedPanel.statusFailed`):e===`running`?t(`schedPanel.statusRunning`):``}function As(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 js(e){let n=e.schedule||{};return n.type===`once`?n.onceMode===`relative`?t(`schedPanel.scheduleTypeOnce`)+` · `+(n.value||``)+t(`schedPanel.minutesSuffix`):t(`schedPanel.scheduleTypeOnce`)+` · `+Ds(new Date(n.value).getTime()):n.type===`interval`?t(`schedPanel.scheduleTypeInterval`)+` · `+(n.value||``):n.type===`cron`?t(`schedPanel.scheduleTypeCron`)+` · `+(n.value||``):``}function Ms(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 Ns(){let e=document.getElementById(`chatContainer`);e&&(e.scrollTop=e.scrollHeight)}async function Ps(e){if(e){if(v.activeSessionId!==e){let t=v.activeSessionId;try{if(await Ln(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-CWyjBBv3.js`).then(e=>e.nr);return{renderSessionTabs:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]));e()}catch{}}setTimeout(Ns,500)}}function Fs(){let e=document.createElement(`div`);e.className=`schedule-panel-container`,e.id=`schedulePanelContainer`,e.innerHTML=`
53
53
  <style>
54
54
  .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; }
55
55
  .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; }
@@ -156,7 +156,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-DvmxOw8q.js"
156
156
  </div>
157
157
  <div class="schedule-panel-list" id="schedulePanelList"></div>
158
158
  </div>
159
- `,Nn(`schedule`).appendChild(e);let n=document.createElement(`div`);n.className=`sched-modal-overlay`,n.id=`scheduleModalOverlay`,n.innerHTML=`
159
+ `,ea(`schedule`).appendChild(e);let n=document.createElement(`div`);n.className=`sched-modal-overlay`,n.id=`scheduleModalOverlay`,n.innerHTML=`
160
160
  <div class="sched-modal">
161
161
  <div class="sched-modal-header">
162
162
  <h3 id="scheduleModalTitle"></h3>
@@ -203,23 +203,23 @@ import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-DvmxOw8q.js"
203
203
  <button class="primary" id="scheduleModalSave">${t(`schedPanel.save`)}</button>
204
204
  </div>
205
205
  </div>
206
- `,document.body.appendChild(n);let r=document.getElementById(`schedulePanelToggle`),i=document.getElementById(`schedulePanel`),a=new Set;function o(){let e=a.size>0;r.classList.toggle(`running`,e),r.title=e?`${t(`schedPanel.toggleTitle`)} · ${t(`schedPanel.toggleRunning`)}`:t(`schedPanel.toggleTitle`)}let s=document.getElementById(`schedulePanelClose`),c=document.getElementById(`scheduleNewTask`),l=document.getElementById(`schedulePanelList`),u=document.getElementById(`scheduleModalOverlay`),d=document.getElementById(`scheduleModalTitle`),f=document.getElementById(`scheduleModalCancel`),p=document.getElementById(`scheduleModalSave`),m=document.getElementById(`schedFormType`),h=document.getElementById(`schedFormValue`),g=document.getElementById(`schedFormOnceMode`),ee=document.getElementById(`schedOnceModeWrap`),te=document.getElementById(`schedValueLabel`),ne=document.getElementById(`schedEndWrap`),_=null,re=`schedPanelView`,y=`all`,b=`created`,x=[],ie=document.getElementById(`schedFilterGroup`),S=document.getElementById(`schedSortSelect`);function C(e){if(typeof e==`number`)return Number.isFinite(e)?e:0;let t=Date.parse(e||``);return Number.isFinite(t)?t:0}function ae(e){return b===`lastRun`?C(e.lastRunAt)||C(e.createdAt):b===`updated`&&C(e.updatedAt)||C(e.createdAt)}function oe(){ie.querySelectorAll(`.sched-filter-btn`).forEach(e=>{e.classList.toggle(`active`,e.dataset.filter===y)}),S.value=b}function w(){try{Promise.resolve(chrome.storage.local.set({[re]:{filter:y,sort:b}})).catch(()=>{})}catch{}}ie.addEventListener(`click`,e=>{let t=e.target.closest(`.sched-filter-btn`);!t||t.dataset.filter===y||(y=t.dataset.filter,oe(),w(),E(x))}),S.addEventListener(`change`,()=>{b=S.value,w(),E(x)}),(async()=>{try{let e=(await chrome.storage.local.get(re))?.[re];(e?.filter===`enabled`||e?.filter===`disabled`||e?.filter===`all`)&&(y=e.filter),(e?.sort===`lastRun`||e?.sort===`updated`||e?.sort===`created`)&&(b=e.sort)}catch{}oe(),x.length&&E(x)})();function se(){let e=m.value,n=g.value;ee.style.display=e===`once`?``:`none`,ne.style.display=e===`interval`?``:`none`,e===`once`?n===`relative`?(te.textContent=t(`schedPanel.onceModeRelative`),h.type=`text`,h.placeholder=t(`schedPanel.relativeValuePlaceholder`)):(te.textContent=t(`schedPanel.onceModeAbsolute`),h.type=`datetime-local`,h.placeholder=``):e===`interval`?(te.textContent=t(`schedPanel.valueLabelInterval`),h.type=`text`,h.placeholder=t(`schedPanel.intervalValuePlaceholder`)):(te.textContent=t(`schedPanel.valueLabelCron`),h.type=`text`,h.placeholder=t(`schedPanel.cronValuePlaceholder`))}function ce(e){e?(i.classList.add(`open`),$e(i),T()):(i.classList.remove(`open`),Ze(i))}r.addEventListener(`click`,()=>{ce(!i.classList.contains(`open`))}),s.addEventListener(`click`,()=>ce(!1)),m.addEventListener(`change`,se),g.addEventListener(`change`,se),document.getElementById(`scheduleModalCloseBtn`).addEventListener(`click`,D),f.addEventListener(`click`,D),p.addEventListener(`click`,pe),c.addEventListener(`click`,()=>de(null)),document.getElementById(`schedUseCurrentPage`).addEventListener(`click`,async()=>{try{let e=(await chrome.tabs.query({active:!0,currentWindow:!0}))?.[0]?.url||``;e&&(document.getElementById(`schedFormUrl`).value=e)}catch{}});async function T(){try{let e=(await Ts({type:`SCHEDULED_TASK_LIST`}))?.tasks||[];E(e),a.clear(),e.forEach(e=>{e.lastStatus===`running`&&a.add(e.id)}),o()}catch(e){l.innerHTML=`<div class="sched-empty">${k(String(e?.message||e))}</div>`}}function le(e){return!e||!e.length?`<div class="sched-history"><div class="sched-run">${t(`schedPanel.runHistoryEmpty`)}</div></div>`:`<div class="sched-history">${e.slice().reverse().map(e=>`
206
+ `,document.body.appendChild(n);let r=document.getElementById(`schedulePanelToggle`),i=document.getElementById(`schedulePanel`),a=new Set;function o(){let e=a.size>0;r.classList.toggle(`running`,e),r.title=e?`${t(`schedPanel.toggleTitle`)} · ${t(`schedPanel.toggleRunning`)}`:t(`schedPanel.toggleTitle`)}let s=document.getElementById(`schedulePanelClose`),c=document.getElementById(`scheduleNewTask`),l=document.getElementById(`schedulePanelList`),u=document.getElementById(`scheduleModalOverlay`),d=document.getElementById(`scheduleModalTitle`),f=document.getElementById(`scheduleModalCancel`),p=document.getElementById(`scheduleModalSave`),m=document.getElementById(`schedFormType`),h=document.getElementById(`schedFormValue`),g=document.getElementById(`schedFormOnceMode`),ee=document.getElementById(`schedOnceModeWrap`),te=document.getElementById(`schedValueLabel`),ne=document.getElementById(`schedEndWrap`),_=null,re=`schedPanelView`,y=`all`,b=`created`,x=[],ie=document.getElementById(`schedFilterGroup`),S=document.getElementById(`schedSortSelect`);function C(e){if(typeof e==`number`)return Number.isFinite(e)?e:0;let t=Date.parse(e||``);return Number.isFinite(t)?t:0}function ae(e){return b===`lastRun`?C(e.lastRunAt)||C(e.createdAt):b===`updated`&&C(e.updatedAt)||C(e.createdAt)}function oe(){ie.querySelectorAll(`.sched-filter-btn`).forEach(e=>{e.classList.toggle(`active`,e.dataset.filter===y)}),S.value=b}function w(){try{Promise.resolve(chrome.storage.local.set({[re]:{filter:y,sort:b}})).catch(()=>{})}catch{}}ie.addEventListener(`click`,e=>{let t=e.target.closest(`.sched-filter-btn`);!t||t.dataset.filter===y||(y=t.dataset.filter,oe(),w(),E(x))}),S.addEventListener(`change`,()=>{b=S.value,w(),E(x)}),(async()=>{try{let e=(await chrome.storage.local.get(re))?.[re];(e?.filter===`enabled`||e?.filter===`disabled`||e?.filter===`all`)&&(y=e.filter),(e?.sort===`lastRun`||e?.sort===`updated`||e?.sort===`created`)&&(b=e.sort)}catch{}oe(),x.length&&E(x)})();function se(){let e=m.value,n=g.value;ee.style.display=e===`once`?``:`none`,ne.style.display=e===`interval`?``:`none`,e===`once`?n===`relative`?(te.textContent=t(`schedPanel.onceModeRelative`),h.type=`text`,h.placeholder=t(`schedPanel.relativeValuePlaceholder`)):(te.textContent=t(`schedPanel.onceModeAbsolute`),h.type=`datetime-local`,h.placeholder=``):e===`interval`?(te.textContent=t(`schedPanel.valueLabelInterval`),h.type=`text`,h.placeholder=t(`schedPanel.intervalValuePlaceholder`)):(te.textContent=t(`schedPanel.valueLabelCron`),h.type=`text`,h.placeholder=t(`schedPanel.cronValuePlaceholder`))}function ce(e){e?(i.classList.add(`open`),$e(i),T()):(i.classList.remove(`open`),Ze(i))}r.addEventListener(`click`,()=>{ce(!i.classList.contains(`open`))}),s.addEventListener(`click`,()=>ce(!1)),m.addEventListener(`change`,se),g.addEventListener(`change`,se),document.getElementById(`scheduleModalCloseBtn`).addEventListener(`click`,D),f.addEventListener(`click`,D),p.addEventListener(`click`,pe),c.addEventListener(`click`,()=>de(null)),document.getElementById(`schedUseCurrentPage`).addEventListener(`click`,async()=>{try{let e=(await chrome.tabs.query({active:!0,currentWindow:!0}))?.[0]?.url||``;e&&(document.getElementById(`schedFormUrl`).value=e)}catch{}});async function T(){try{let e=(await Es({type:`SCHEDULED_TASK_LIST`}))?.tasks||[];E(e),a.clear(),e.forEach(e=>{e.lastStatus===`running`&&a.add(e.id)}),o()}catch(e){l.innerHTML=`<div class="sched-empty">${k(String(e?.message||e))}</div>`}}function le(e){return!e||!e.length?`<div class="sched-history"><div class="sched-run">${t(`schedPanel.runHistoryEmpty`)}</div></div>`:`<div class="sched-history">${e.slice().reverse().map(e=>`
207
207
  <div class="sched-run">
208
208
  <span class="dot ${k(e.status||``)}"></span>
209
- <span class="time">${k(Es(e.startedAt))}</span>
210
- <span>${k(Os(e.status))}</span>
211
- <span class="dur">${k(Ds(e.durationMs))}</span>
209
+ <span class="time">${k(Ds(e.startedAt))}</span>
210
+ <span>${k(ks(e.status))}</span>
211
+ <span class="dur">${k(Os(e.durationMs))}</span>
212
212
  ${e.error?`<span class="err" title="${k(e.error)}">${k(e.error)}</span>`:``}
213
213
  </div>
214
214
  `).join(``)}</div>`}function E(e){x=Array.isArray(e)?e:[];let n=x.filter(e=>y===`enabled`?e.enabled!==!1:y===`disabled`?e.enabled===!1:!0).slice().sort((e,t)=>{let n=ae(t)-ae(e);return n===0?C(t.createdAt)-C(e.createdAt):n}),r=document.getElementById(`schedulePanelCount`);if(r&&(x.length?y===`all`?r.textContent=`(${x.length})`:r.textContent=`(${n.length}/${x.length})`:r.textContent=``),!x.length){l.innerHTML=`<div class="sched-empty">${t(`schedPanel.empty`)}</div>`;return}if(!n.length){l.innerHTML=`<div class="sched-empty">${t(`schedPanel.emptyFiltered`)}</div>`;return}l.innerHTML=n.map(e=>{let n=e.runHistory?.length||0,r=n>0?`<button class="sched-history-btn" data-act="history">${t(`schedPanel.runCountLabel`,{count:n})}</button>`:``;return`
215
215
  <div class="sched-item" data-id="${k(e.id)}">
216
216
  <div class="row1">
217
217
  <span class="name" title="${k(e.name)}">${k(e.name)}</span>
218
- ${js(e)}
218
+ ${Ms(e)}
219
219
  </div>
220
220
  ${e.description?`<div class="desc">${k(e.description)}</div>`:``}
221
- <div class="meta">${k(As(e))}</div>
222
- <div class="meta">${t(`schedPanel.nextRun`)}: ${k(Es(e.nextRunAt))}</div>
221
+ <div class="meta">${k(js(e))}</div>
222
+ <div class="meta">${t(`schedPanel.nextRun`)}: ${k(Ds(e.nextRunAt))}</div>
223
223
  ${r}
224
224
  <div class="sched-history" data-history style="display:none;">${le(e.runHistory)}</div>
225
225
  <div class="actions">
@@ -229,14 +229,14 @@ import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-DvmxOw8q.js"
229
229
  <button data-act="delete" class="danger">${t(`schedPanel.delete`)}</button>
230
230
  </div>
231
231
  </div>
232
- `}).join(``)}l.addEventListener(`click`,async e=>{let n=e.target.closest(`button[data-act]`);if(!n)return;let r=n.closest(`.sched-item`),i=r?.dataset.id;if(!i)return;let a=n.dataset.act;if(a===`toggle`){let e=(await ue())[i];if(!e)return;await Ts({type:`SCHEDULED_TASK_TOGGLE`,id:i,enabled:!e.enabled}),T()}else if(a===`run`){let e=await Ts({type:`SCHEDULED_TASK_RUN_NOW`,id:i});e?.success?(A(t(`schedPanel.runNowToast`),`success`),Ns(e.sessionId),setTimeout(T,1500)):A(e?.error||t(`schedPanel.createFailed`),`error`)}else if(a===`history`){let e=r.querySelector(`[data-history]`);e&&(e.style.display=e.style.display===`none`?``:`none`)}else if(a===`edit`)de((await ue())[i]);else if(a===`delete`){let e=(await ue())[i];await window.showCustomConfirm(t(`schedPanel.deleteConfirmMsg`,{name:e?.name||``}),t(`schedPanel.deleteConfirmTitle`))&&(await Ts({type:`SCHEDULED_TASK_DELETE`,id:i}),A(t(`schedPanel.deleted`),`success`),T())}});async function ue(){let e=await Ts({type:`SCHEDULED_TASK_LIST`}),t={};return(e?.tasks||[]).forEach(e=>{t[e.id]=e}),t}async function de(e){_=e||null,d.textContent=t(e?`schedPanel.editTitle`:`schedPanel.newTask`),document.getElementById(`schedFormName`).value=e?.name||``,document.getElementById(`schedFormDesc`).value=e?.description||``,document.getElementById(`schedFormPrompt`).value=e?.prompt||``,document.getElementById(`schedFormUrl`).value=e?.contextUrl||``,m.value=e?.schedule?.type||`interval`,g.value=e?.schedule?.onceMode||`relative`,se(),h.value=e?.schedule?.value||``,document.getElementById(`schedFormContextMode`).value=e?.contextMode||`fetch`,document.getElementById(`schedFormMaxRuns`).value=e?.maxRuns??``,document.getElementById(`schedFormEndAt`).value=e?.endAt?ks(e.endAt):``;let n=document.getElementById(`schedFormSession`),r=`<option value="">${t(`schedPanel.sessionAuto`)}</option>`;try{let{list:t}=await fe(),n=[...t].sort((e,t)=>{let n=e.order??0,r=t.order??0;return n===r?new Date(t.createdAt||0)-new Date(e.createdAt||0):r-n});for(let t of n){let n=e?.sessionId===t.id?`selected`:``,i=k(t.title||t.id);r+=`<option value="${k(t.id)}" ${n}>${i}</option>`}}catch{}n.innerHTML=r,u.classList.add(`open`)}function D(){u.classList.remove(`open`),_=null}async function pe(){let e=document.getElementById(`schedFormName`).value.trim(),n=document.getElementById(`schedFormPrompt`).value.trim(),r=m.value,i=h.value.trim();if(!e){A(t(`schedPanel.nameRequired`),`warning`);return}if(!n){A(t(`schedPanel.promptRequired`),`warning`);return}if(!i){A(t(`schedPanel.scheduleRequired`),`warning`);return}let a=r===`interval`&&parseInt(document.getElementById(`schedFormMaxRuns`).value,10)||null,o=r===`interval`?document.getElementById(`schedFormEndAt`).value:``,s=o?new Date(o).getTime():null,c={name:e,description:document.getElementById(`schedFormDesc`).value.trim(),prompt:n,schedule:r===`once`?{type:r,value:i,onceMode:g.value}:{type:r,value:i},contextUrl:document.getElementById(`schedFormUrl`).value.trim()||null,contextMode:document.getElementById(`schedFormContextMode`).value||`fetch`,sessionId:document.getElementById(`schedFormSession`).value||null,maxRuns:a,endAt:s,enabled:_?_.enabled:!0};try{let e=await Ts({type:_?`SCHEDULED_TASK_UPDATE`:`SCHEDULED_TASK_CREATE`,task:_?{...c,id:_.id}:c});e?.success?(A(t(`schedPanel.saved`),`success`),D(),T()):A(e?.error||t(`schedPanel.createFailed`),`error`)}catch(e){A(e?.message||t(`schedPanel.createFailed`),`error`)}}chrome.runtime.onMessage.addListener(e=>{e.type===`SCHEDULED_TASK_RUN_STATE`&&e.taskId&&(e.running?a.add(e.taskId):a.delete(e.taskId),o())}),chrome.runtime.onMessage.addListener(e=>{e.type===`SCHEDULED_SESSION_UPDATED`&&(i.classList.contains(`open`)&&T().catch(()=>{}),e.sessionId&&e.sessionId===v.activeSessionId&&setTimeout(Ms,600))}),chrome.runtime.onMessage.addListener(e=>{e.type===`SCHEDULED_TASKS_CHANGED`&&T().catch(()=>{})}),se(),ce(!1),T().catch(()=>{})}var Fs=`todoStatsLog`,Is=7;function Ls(e){return String(e).padStart(2,`0`)}function Rs(e=Date.now()){let t=new Date(e);return`${t.getFullYear()}-${Ls(t.getMonth()+1)}-${Ls(t.getDate())}`}function zs(e,t){let n=new Date(e);return n.setDate(n.getDate()+t),n.getTime()}function Bs(e,t,n,r){let i=e&&typeof e==`object`?e:{},a=i[t]&&typeof i[t]==`object`?i[t]:{},o=(Number.isFinite(a[n])?a[n]:0)+(Number.isFinite(r)?r:0);return{...i,[t]:{...a,[n]:Math.max(0,o)}}}function Vs(e,t=Date.now()){let n=Rs(zs(t,-90)),r={};for(let[t,i]of Object.entries(e&&typeof e==`object`?e:{}))t>=n&&(r[t]=i);return r}function Hs(e,t){let n=e&&e[t];return{added:Number.isFinite(n&&n.added)?n.added:0,done:Number.isFinite(n&&n.done)?n.done:0}}function Us(e,t){let n=Hs(e,Rs(t)).done>0?t:zs(t,-1),r=0;for(;r<=90&&!(Hs(e,Rs(n)).done<=0);)r+=1,n=zs(n,-1);return r}function Ws(e,t,n=Date.now()){let r=Array.isArray(e)?e.map(Ue):[],{stats:i}=Be(r),a=t&&typeof t==`object`?t:{},o=[];for(let e=Is-1;e>=0;--e){let t=Rs(zs(n,-e));o.push({date:t,...Hs(a,t)})}return{total:i.total,done:i.done,doing:i.doing,pending:i.pending,overdue:r.filter(e=>De(e,n)).length,high:r.filter(e=>e.status!==O.DONE&&e.priority===ze.HIGH).length,doneRate:i.total?Math.round(i.done/i.total*100):0,today:Hs(a,Rs(n)),week:o,streak:Us(a,n)}}var Gs=Promise.resolve();async function Ks(){try{if(typeof chrome>`u`||!chrome.storage?.local?.get)return{};let e=await chrome.storage.local.get([Fs]),t=e&&e.todoStatsLog;return t&&typeof t==`object`?t:{}}catch(e){return r.warn(`[Todo] load stats log failed:`,e),{}}}async function qs(e){typeof chrome>`u`||!chrome.storage?.local?.set||await chrome.storage.local.set({[Fs]:e})}function Js(e,t,n=Date.now()){let i=Gs.then(async()=>{let r=Vs(Bs(await Ks(),Rs(n),e,t));return await qs(r),r});return Gs=i.then(()=>void 0,()=>void 0),i.catch(e=>(r.warn(`[Todo] record stat failed:`,e),null))}var Ys=new Set,Xs=Promise.resolve();function Zs(e){let t=Xs.then(e);return Xs=t.then(()=>void 0,()=>void 0),t}function Qs(e){return typeof e==`function`?(Ys.add(e),()=>Ys.delete(e)):()=>{}}function L(){for(let e of Ys)try{e()}catch(e){r.warn(`[Todo] listener failed:`,e)}}async function $s(){try{v.todos=(await C()||[]).map(Ue).filter(e=>e.id&&e.title),r.debug(`[Todo] loaded todos:`,v.todos.length)}catch(e){r.error(`[Todo] load todos failed:`,e),v.todos=[]}L()}function ec(){return Be(v.todos)}function tc(e){return v.todos.find(t=>t.id===e)||null}function nc(e){v.todos=v.todos.map(t=>t.id===e.id?e:t)}async function rc(e,t={}){let n=String(e||``).trim();if(!n)return null;let i=Fe(n,t);return i.order=Oe(v.todos),v.todos=[...v.todos,i],await Zs(()=>ie(i)).catch(e=>(r.error(`[Todo] add failed:`,e),!1))?(L(),await Js(`added`,1,i.createdAt),i):(v.todos=v.todos.filter(e=>e.id!==i.id),L(),null)}async function ic(e,t={}){let n=tc(e);if(!n)return!1;let i={...n,updatedAt:Date.now()};if(t.title!==void 0){let e=String(t.title).trim();if(!e)return!1;i.title=e}return t.note!==void 0&&(i.note=String(t.note||``).trim()),t.dueAt!==void 0&&(i.dueAt=Number.isFinite(t.dueAt)?t.dueAt:null),t.priority!==void 0&&(i.priority=we(t.priority)),t.link!==void 0&&(i.link=We(t.link).url),nc(i),await Zs(()=>ie(i)).catch(e=>(r.error(`[Todo] update failed:`,e),!1))?(L(),!0):(nc(n),L(),!1)}async function ac(e,t){let n=tc(e);if(!n||!Ie(t))return!1;if(n.status===t)return!0;let i=Date.now(),a={...n,status:t,updatedAt:i};return t===O.DONE?(a.completedAt=i,n.status!==O.DONE&&(a.prevStatus=n.status)):n.status===O.DONE&&(a.completedAt=null,a.prevStatus=null),nc(a),await Zs(()=>ie(a)).catch(e=>(r.error(`[Todo] set status failed:`,e),!1))?(L(),t===O.DONE&&n.status!==O.DONE?await Js(`done`,1,a.completedAt):n.status===O.DONE&&t!==O.DONE&&await Js(`done`,-1,n.completedAt),!0):(nc(n),L(),!1)}function oc(e){let t=tc(e);return t?ac(e,Ve(t.status)):Promise.resolve(!1)}function sc(e){let t=tc(e);return!t||t.status!==O.DONE?Promise.resolve(!1):ac(e,He(t))}function cc(e,t){return ic(e,{priority:we(t)})}async function lc(e,t){if(!tc(e))return{ok:!1,reason:`missing`};let n=We(t);if(!n.valid)return{ok:!1,reason:`invalid`};let r=await ic(e,{link:n.url});return{ok:r,reason:r?``:`save`}}async function uc(e){let t=tc(e);return t?(v.todos=v.todos.filter(t=>t.id!==e),await Zs(()=>w(e)).catch(e=>(r.error(`[Todo] delete failed:`,e),!1))?(L(),!0):(v.todos=[...v.todos,t],L(),!1)):!1}async function dc(e,t){let{active:n}=ec();if(e===t)return!0;if(e<0||e>=n.length)return!1;let i=ge(me(n,e,t)),a=new Map(i.map(e=>[e.id,e])),o=v.todos;if(v.todos=v.todos.map(e=>a.get(e.id)||e),!await Zs(()=>x(i)).catch(e=>(r.error(`[Todo] reorder failed:`,e),!1))){let e=new Map(o.map(e=>[e.id,e.order]));return v.todos=v.todos.map(t=>e.has(t.id)?{...t,order:e.get(t.id)}:t),L(),!1}return L(),!0}async function fc(){let{done:e}=ec();if(e.length===0)return!0;let t=e.map(e=>e.id),n=v.todos;if(v.todos=v.todos.filter(e=>!t.includes(e.id)),!await Zs(()=>d(t)).catch(e=>(r.error(`[Todo] clear completed failed:`,e),!1))){let e=new Set(v.todos.map(e=>e.id)),r=n.filter(n=>t.includes(n.id)&&!e.has(n.id));return v.todos=[...v.todos,...r],L(),!1}return L(),!0}async function pc(e,t=`merge`){if(t===`replace`)return mc(e);let n=ke(v.todos,e);if(n.addedItems.length===0)return{ok:!0,added:0,skipped:n.skipped};let i=v.todos;v.todos=n.todos;let a=new Set(n.addedItems.map(e=>e.id));return await Zs(()=>x(n.addedItems)).catch(e=>(r.error(`[Todo] import merge failed:`,e),!1))?(L(),{ok:!0,added:n.addedItems.length,skipped:n.skipped}):(v.todos=i.filter(e=>!a.has(e.id)),L(),{ok:!1,added:0,skipped:n.skipped})}async function mc(e){let{addedItems:t,skipped:n}=ke([],e);if(t.length===0)return{ok:!1,added:0,skipped:n,reason:`empty`};let i=v.todos,a=i.map(e=>e.id);return v.todos=t,await Zs(async()=>a.length>0&&!await d(a).catch(e=>(r.error(`[Todo] replace delete failed:`,e),!1))?!1:await x(t).catch(e=>(r.error(`[Todo] replace write failed:`,e),!1))?!0:(a.length>0&&await x(i).catch(()=>!1),!1)).catch(e=>(r.error(`[Todo] replace failed:`,e),!1))?(L(),{ok:!0,added:t.length,skipped:n}):(v.todos=i,L(),{ok:!1,added:0,skipped:n})}var hc=[`all`,`active`,`done`],gc={json:{ext:`json`,type:`application/json;charset=utf-8`},md:{ext:`md`,type:`text/markdown;charset=utf-8`}};function _c(e){return e===`md`?`md`:`json`}function vc(e){return String(e).padStart(2,`0`)}function yc(e){let t=new Date(e);return`${t.getFullYear()}-${vc(t.getMonth()+1)}-${vc(t.getDate())}`}function bc(e,t,n=Date.now()){let r=hc.includes(e)?e:`all`;return`ai-helper-todos${r===`all`?``:`-${r}`}-${yc(n)}.${gc[_c(t)].ext}`}function xc(e,t={}){let n=hc.includes(t.scope)?t.scope:`all`,r=_c(t.format),i=t.now||Date.now(),a=r===`md`?Ce(e,{scope:n,now:i}):JSON.stringify(Ae(e,{scope:n,now:i}),null,2);return{filename:bc(n,r,i),blob:new Blob([a],{type:gc[r].type})}}function Sc(e,t={}){let{filename:n,blob:r}=xc(e,t),i=URL.createObjectURL(r),a=document.createElement(`a`);return a.href=i,a.download=n,document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(i),n}function Cc(){return new Promise(e=>{let t=document.createElement(`input`);t.type=`file`,t.accept=`.json,application/json`,t.style.display=`none`;let n=!1,r=r=>{n||(n=!0,t.remove(),e(r))};t.addEventListener(`change`,()=>r(t.files&&t.files[0]?t.files[0]:null)),t.addEventListener(`cancel`,()=>r(null)),document.body.appendChild(t),t.click()})}async function wc(e){if(!e||typeof e.text!=`function`)return{ok:!1,reason:`json`};let t=``;try{t=await e.text()}catch{return{ok:!1,reason:`json`}}let n=null;try{n=JSON.parse(t)}catch{return{ok:!1,reason:`json`}}return be(n)}var Tc=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M18 6L6 18"/><path d="M6 6l12 12"/></svg>`,Ec=[`all`,`active`,`done`],Dc=[`json`,`md`],Oc=[`merge`,`replace`];e(`zh`,{todoIo:{exportTitle:`导出待办`,importTitle:`导入待办`,close:`关闭`,rangeLabel:`范围`,formatLabel:`格式`,scopeAll:`全部`,scopeActive:`待办`,scopeDone:`已完成`,emptyRange:`这个范围里没有待办`,modeLabel:`方式`,modeMerge:`合并到现有`,modeMergeHint:`重复的条目自动跳过`,modeReplace:`替换全部`,modeReplaceHint:`删除当前 {n} 条,不可撤销`,importSummary:`文件里 {count} 条待办,当前清单 {existing} 条`,replaceWarn:`将删除当前全部待办,并写入文件里的 {count} 条。此操作不可撤销,确定继续吗?`,exportAction:`导出`,importAction:`导入`,cancel:`取消`}}),e(`en`,{todoIo:{exportTitle:`Export todos`,importTitle:`Import todos`,close:`Close`,rangeLabel:`Range`,formatLabel:`Format`,scopeAll:`All`,scopeActive:`To do`,scopeDone:`Done`,emptyRange:`No todos in this range`,modeLabel:`Mode`,modeMerge:`Merge into current`,modeMergeHint:`Duplicates are skipped`,modeReplace:`Replace all`,modeReplaceHint:`Deletes all {n} current todos, cannot be undone`,importSummary:`{count} todos in the file, {existing} in the list now`,replaceWarn:`All current todos will be deleted and {count} todos from the file written in. This cannot be undone. Continue?`,exportAction:`Export`,importAction:`Import`,cancel:`Cancel`}});function kc(e){return`<div class="todo-io-header">
232
+ `}).join(``)}l.addEventListener(`click`,async e=>{let n=e.target.closest(`button[data-act]`);if(!n)return;let r=n.closest(`.sched-item`),i=r?.dataset.id;if(!i)return;let a=n.dataset.act;if(a===`toggle`){let e=(await ue())[i];if(!e)return;await Es({type:`SCHEDULED_TASK_TOGGLE`,id:i,enabled:!e.enabled}),T()}else if(a===`run`){let e=await Es({type:`SCHEDULED_TASK_RUN_NOW`,id:i});e?.success?(A(t(`schedPanel.runNowToast`),`success`),Ps(e.sessionId),setTimeout(T,1500)):A(e?.error||t(`schedPanel.createFailed`),`error`)}else if(a===`history`){let e=r.querySelector(`[data-history]`);e&&(e.style.display=e.style.display===`none`?``:`none`)}else if(a===`edit`)de((await ue())[i]);else if(a===`delete`){let e=(await ue())[i];await window.showCustomConfirm(t(`schedPanel.deleteConfirmMsg`,{name:e?.name||``}),t(`schedPanel.deleteConfirmTitle`))&&(await Es({type:`SCHEDULED_TASK_DELETE`,id:i}),A(t(`schedPanel.deleted`),`success`),T())}});async function ue(){let e=await Es({type:`SCHEDULED_TASK_LIST`}),t={};return(e?.tasks||[]).forEach(e=>{t[e.id]=e}),t}async function de(e){_=e||null,d.textContent=t(e?`schedPanel.editTitle`:`schedPanel.newTask`),document.getElementById(`schedFormName`).value=e?.name||``,document.getElementById(`schedFormDesc`).value=e?.description||``,document.getElementById(`schedFormPrompt`).value=e?.prompt||``,document.getElementById(`schedFormUrl`).value=e?.contextUrl||``,m.value=e?.schedule?.type||`interval`,g.value=e?.schedule?.onceMode||`relative`,se(),h.value=e?.schedule?.value||``,document.getElementById(`schedFormContextMode`).value=e?.contextMode||`fetch`,document.getElementById(`schedFormMaxRuns`).value=e?.maxRuns??``,document.getElementById(`schedFormEndAt`).value=e?.endAt?As(e.endAt):``;let n=document.getElementById(`schedFormSession`),r=`<option value="">${t(`schedPanel.sessionAuto`)}</option>`;try{let{list:t}=await fe(),n=[...t].sort((e,t)=>{let n=e.order??0,r=t.order??0;return n===r?new Date(t.createdAt||0)-new Date(e.createdAt||0):r-n});for(let t of n){let n=e?.sessionId===t.id?`selected`:``,i=k(t.title||t.id);r+=`<option value="${k(t.id)}" ${n}>${i}</option>`}}catch{}n.innerHTML=r,u.classList.add(`open`)}function D(){u.classList.remove(`open`),_=null}async function pe(){let e=document.getElementById(`schedFormName`).value.trim(),n=document.getElementById(`schedFormPrompt`).value.trim(),r=m.value,i=h.value.trim();if(!e){A(t(`schedPanel.nameRequired`),`warning`);return}if(!n){A(t(`schedPanel.promptRequired`),`warning`);return}if(!i){A(t(`schedPanel.scheduleRequired`),`warning`);return}let a=r===`interval`&&parseInt(document.getElementById(`schedFormMaxRuns`).value,10)||null,o=r===`interval`?document.getElementById(`schedFormEndAt`).value:``,s=o?new Date(o).getTime():null,c={name:e,description:document.getElementById(`schedFormDesc`).value.trim(),prompt:n,schedule:r===`once`?{type:r,value:i,onceMode:g.value}:{type:r,value:i},contextUrl:document.getElementById(`schedFormUrl`).value.trim()||null,contextMode:document.getElementById(`schedFormContextMode`).value||`fetch`,sessionId:document.getElementById(`schedFormSession`).value||null,maxRuns:a,endAt:s,enabled:_?_.enabled:!0};try{let e=await Es({type:_?`SCHEDULED_TASK_UPDATE`:`SCHEDULED_TASK_CREATE`,task:_?{...c,id:_.id}:c});e?.success?(A(t(`schedPanel.saved`),`success`),D(),T()):A(e?.error||t(`schedPanel.createFailed`),`error`)}catch(e){A(e?.message||t(`schedPanel.createFailed`),`error`)}}chrome.runtime.onMessage.addListener(e=>{e.type===`SCHEDULED_TASK_RUN_STATE`&&e.taskId&&(e.running?a.add(e.taskId):a.delete(e.taskId),o())}),chrome.runtime.onMessage.addListener(e=>{e.type===`SCHEDULED_SESSION_UPDATED`&&(i.classList.contains(`open`)&&T().catch(()=>{}),e.sessionId&&e.sessionId===v.activeSessionId&&setTimeout(Ns,600))}),chrome.runtime.onMessage.addListener(e=>{e.type===`SCHEDULED_TASKS_CHANGED`&&T().catch(()=>{})}),se(),ce(!1),T().catch(()=>{})}var Is=`todoStatsLog`,Ls=7;function Rs(e){return String(e).padStart(2,`0`)}function zs(e=Date.now()){let t=new Date(e);return`${t.getFullYear()}-${Rs(t.getMonth()+1)}-${Rs(t.getDate())}`}function Bs(e,t){let n=new Date(e);return n.setDate(n.getDate()+t),n.getTime()}function Vs(e,t,n,r){let i=e&&typeof e==`object`?e:{},a=i[t]&&typeof i[t]==`object`?i[t]:{},o=(Number.isFinite(a[n])?a[n]:0)+(Number.isFinite(r)?r:0);return{...i,[t]:{...a,[n]:Math.max(0,o)}}}function Hs(e,t=Date.now()){let n=zs(Bs(t,-90)),r={};for(let[t,i]of Object.entries(e&&typeof e==`object`?e:{}))t>=n&&(r[t]=i);return r}function Us(e,t){let n=e&&e[t];return{added:Number.isFinite(n&&n.added)?n.added:0,done:Number.isFinite(n&&n.done)?n.done:0}}function Ws(e,t){let n=Us(e,zs(t)).done>0?t:Bs(t,-1),r=0;for(;r<=90&&!(Us(e,zs(n)).done<=0);)r+=1,n=Bs(n,-1);return r}function Gs(e,t,n=Date.now()){let r=Array.isArray(e)?e.map(Ue):[],{stats:i}=Be(r),a=t&&typeof t==`object`?t:{},o=[];for(let e=Ls-1;e>=0;--e){let t=zs(Bs(n,-e));o.push({date:t,...Us(a,t)})}return{total:i.total,done:i.done,doing:i.doing,pending:i.pending,overdue:r.filter(e=>De(e,n)).length,high:r.filter(e=>e.status!==O.DONE&&e.priority===ze.HIGH).length,doneRate:i.total?Math.round(i.done/i.total*100):0,today:Us(a,zs(n)),week:o,streak:Ws(a,n)}}var Ks=Promise.resolve();async function qs(){try{if(typeof chrome>`u`||!chrome.storage?.local?.get)return{};let e=await chrome.storage.local.get([Is]),t=e&&e.todoStatsLog;return t&&typeof t==`object`?t:{}}catch(e){return r.warn(`[Todo] load stats log failed:`,e),{}}}async function Js(e){typeof chrome>`u`||!chrome.storage?.local?.set||await chrome.storage.local.set({[Is]:e})}function Ys(e,t,n=Date.now()){let i=Ks.then(async()=>{let r=Hs(Vs(await qs(),zs(n),e,t));return await Js(r),r});return Ks=i.then(()=>void 0,()=>void 0),i.catch(e=>(r.warn(`[Todo] record stat failed:`,e),null))}var Xs=new Set,Zs=Promise.resolve();function Qs(e){let t=Zs.then(e);return Zs=t.then(()=>void 0,()=>void 0),t}function $s(e){return typeof e==`function`?(Xs.add(e),()=>Xs.delete(e)):()=>{}}function L(){for(let e of Xs)try{e()}catch(e){r.warn(`[Todo] listener failed:`,e)}}async function ec(){try{v.todos=(await C()||[]).map(Ue).filter(e=>e.id&&e.title),r.debug(`[Todo] loaded todos:`,v.todos.length)}catch(e){r.error(`[Todo] load todos failed:`,e),v.todos=[]}L()}function tc(){return Be(v.todos)}function nc(e){return v.todos.find(t=>t.id===e)||null}function rc(e){v.todos=v.todos.map(t=>t.id===e.id?e:t)}async function ic(e,t={}){let n=String(e||``).trim();if(!n)return null;let i=Fe(n,t);return i.order=Oe(v.todos),v.todos=[...v.todos,i],await Qs(()=>ie(i)).catch(e=>(r.error(`[Todo] add failed:`,e),!1))?(L(),await Ys(`added`,1,i.createdAt),i):(v.todos=v.todos.filter(e=>e.id!==i.id),L(),null)}async function ac(e,t={}){let n=nc(e);if(!n)return!1;let i={...n,updatedAt:Date.now()};if(t.title!==void 0){let e=String(t.title).trim();if(!e)return!1;i.title=e}return t.note!==void 0&&(i.note=String(t.note||``).trim()),t.dueAt!==void 0&&(i.dueAt=Number.isFinite(t.dueAt)?t.dueAt:null),t.priority!==void 0&&(i.priority=we(t.priority)),t.link!==void 0&&(i.link=We(t.link).url),rc(i),await Qs(()=>ie(i)).catch(e=>(r.error(`[Todo] update failed:`,e),!1))?(L(),!0):(rc(n),L(),!1)}async function oc(e,t){let n=nc(e);if(!n||!Ie(t))return!1;if(n.status===t)return!0;let i=Date.now(),a={...n,status:t,updatedAt:i};return t===O.DONE?(a.completedAt=i,n.status!==O.DONE&&(a.prevStatus=n.status)):n.status===O.DONE&&(a.completedAt=null,a.prevStatus=null),rc(a),await Qs(()=>ie(a)).catch(e=>(r.error(`[Todo] set status failed:`,e),!1))?(L(),t===O.DONE&&n.status!==O.DONE?await Ys(`done`,1,a.completedAt):n.status===O.DONE&&t!==O.DONE&&await Ys(`done`,-1,n.completedAt),!0):(rc(n),L(),!1)}function sc(e){let t=nc(e);return t?oc(e,Ve(t.status)):Promise.resolve(!1)}function cc(e){let t=nc(e);return!t||t.status!==O.DONE?Promise.resolve(!1):oc(e,He(t))}function lc(e,t){return ac(e,{priority:we(t)})}async function uc(e,t){if(!nc(e))return{ok:!1,reason:`missing`};let n=We(t);if(!n.valid)return{ok:!1,reason:`invalid`};let r=await ac(e,{link:n.url});return{ok:r,reason:r?``:`save`}}async function dc(e){let t=nc(e);return t?(v.todos=v.todos.filter(t=>t.id!==e),await Qs(()=>w(e)).catch(e=>(r.error(`[Todo] delete failed:`,e),!1))?(L(),!0):(v.todos=[...v.todos,t],L(),!1)):!1}async function fc(e,t){let{active:n}=tc();if(e===t)return!0;if(e<0||e>=n.length)return!1;let i=ge(me(n,e,t)),a=new Map(i.map(e=>[e.id,e])),o=v.todos;if(v.todos=v.todos.map(e=>a.get(e.id)||e),!await Qs(()=>x(i)).catch(e=>(r.error(`[Todo] reorder failed:`,e),!1))){let e=new Map(o.map(e=>[e.id,e.order]));return v.todos=v.todos.map(t=>e.has(t.id)?{...t,order:e.get(t.id)}:t),L(),!1}return L(),!0}async function pc(){let{done:e}=tc();if(e.length===0)return!0;let t=e.map(e=>e.id),n=v.todos;if(v.todos=v.todos.filter(e=>!t.includes(e.id)),!await Qs(()=>d(t)).catch(e=>(r.error(`[Todo] clear completed failed:`,e),!1))){let e=new Set(v.todos.map(e=>e.id)),r=n.filter(n=>t.includes(n.id)&&!e.has(n.id));return v.todos=[...v.todos,...r],L(),!1}return L(),!0}async function mc(e,t=`merge`){if(t===`replace`)return hc(e);let n=ke(v.todos,e);if(n.addedItems.length===0)return{ok:!0,added:0,skipped:n.skipped};let i=v.todos;v.todos=n.todos;let a=new Set(n.addedItems.map(e=>e.id));return await Qs(()=>x(n.addedItems)).catch(e=>(r.error(`[Todo] import merge failed:`,e),!1))?(L(),{ok:!0,added:n.addedItems.length,skipped:n.skipped}):(v.todos=i.filter(e=>!a.has(e.id)),L(),{ok:!1,added:0,skipped:n.skipped})}async function hc(e){let{addedItems:t,skipped:n}=ke([],e);if(t.length===0)return{ok:!1,added:0,skipped:n,reason:`empty`};let i=v.todos,a=i.map(e=>e.id);return v.todos=t,await Qs(async()=>a.length>0&&!await d(a).catch(e=>(r.error(`[Todo] replace delete failed:`,e),!1))?!1:await x(t).catch(e=>(r.error(`[Todo] replace write failed:`,e),!1))?!0:(a.length>0&&await x(i).catch(()=>!1),!1)).catch(e=>(r.error(`[Todo] replace failed:`,e),!1))?(L(),{ok:!0,added:t.length,skipped:n}):(v.todos=i,L(),{ok:!1,added:0,skipped:n})}var gc=[`all`,`active`,`done`],_c={json:{ext:`json`,type:`application/json;charset=utf-8`},md:{ext:`md`,type:`text/markdown;charset=utf-8`}};function vc(e){return e===`md`?`md`:`json`}function yc(e){return String(e).padStart(2,`0`)}function bc(e){let t=new Date(e);return`${t.getFullYear()}-${yc(t.getMonth()+1)}-${yc(t.getDate())}`}function xc(e,t,n=Date.now()){let r=gc.includes(e)?e:`all`;return`ai-helper-todos${r===`all`?``:`-${r}`}-${bc(n)}.${_c[vc(t)].ext}`}function Sc(e,t={}){let n=gc.includes(t.scope)?t.scope:`all`,r=vc(t.format),i=t.now||Date.now(),a=r===`md`?Ce(e,{scope:n,now:i}):JSON.stringify(Ae(e,{scope:n,now:i}),null,2);return{filename:xc(n,r,i),blob:new Blob([a],{type:_c[r].type})}}function Cc(e,t={}){let{filename:n,blob:r}=Sc(e,t),i=URL.createObjectURL(r),a=document.createElement(`a`);return a.href=i,a.download=n,document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(i),n}function wc(){return new Promise(e=>{let t=document.createElement(`input`);t.type=`file`,t.accept=`.json,application/json`,t.style.display=`none`;let n=!1,r=r=>{n||(n=!0,t.remove(),e(r))};t.addEventListener(`change`,()=>r(t.files&&t.files[0]?t.files[0]:null)),t.addEventListener(`cancel`,()=>r(null)),document.body.appendChild(t),t.click()})}async function Tc(e){if(!e||typeof e.text!=`function`)return{ok:!1,reason:`json`};let t=``;try{t=await e.text()}catch{return{ok:!1,reason:`json`}}let n=null;try{n=JSON.parse(t)}catch{return{ok:!1,reason:`json`}}return be(n)}var Ec=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M18 6L6 18"/><path d="M6 6l12 12"/></svg>`,Dc=[`all`,`active`,`done`],Oc=[`json`,`md`],kc=[`merge`,`replace`];e(`zh`,{todoIo:{exportTitle:`导出待办`,importTitle:`导入待办`,close:`关闭`,rangeLabel:`范围`,formatLabel:`格式`,scopeAll:`全部`,scopeActive:`待办`,scopeDone:`已完成`,emptyRange:`这个范围里没有待办`,modeLabel:`方式`,modeMerge:`合并到现有`,modeMergeHint:`重复的条目自动跳过`,modeReplace:`替换全部`,modeReplaceHint:`删除当前 {n} 条,不可撤销`,importSummary:`文件里 {count} 条待办,当前清单 {existing} 条`,replaceWarn:`将删除当前全部待办,并写入文件里的 {count} 条。此操作不可撤销,确定继续吗?`,exportAction:`导出`,importAction:`导入`,cancel:`取消`}}),e(`en`,{todoIo:{exportTitle:`Export todos`,importTitle:`Import todos`,close:`Close`,rangeLabel:`Range`,formatLabel:`Format`,scopeAll:`All`,scopeActive:`To do`,scopeDone:`Done`,emptyRange:`No todos in this range`,modeLabel:`Mode`,modeMerge:`Merge into current`,modeMergeHint:`Duplicates are skipped`,modeReplace:`Replace all`,modeReplaceHint:`Deletes all {n} current todos, cannot be undone`,importSummary:`{count} todos in the file, {existing} in the list now`,replaceWarn:`All current todos will be deleted and {count} todos from the file written in. This cannot be undone. Continue?`,exportAction:`Export`,importAction:`Import`,cancel:`Cancel`}});function Ac(e){return`<div class="todo-io-header">
233
233
  <span class="todo-io-title">${k(e)}</span>
234
234
  <button type="button" class="todo-io-close" data-io-action="cancel"
235
- title="${j(t(`todoIo.close`))}" aria-label="${j(t(`todoIo.close`))}">${Tc}</button>
236
- </div>`}function Ac(e,n){return`<div class="todo-io-actions">
235
+ title="${j(t(`todoIo.close`))}" aria-label="${j(t(`todoIo.close`))}">${Ec}</button>
236
+ </div>`}function jc(e,n){return`<div class="todo-io-actions">
237
237
  <button type="button" class="todo-io-btn" data-io-action="cancel">${k(t(`todoIo.cancel`))}</button>
238
238
  <button type="button" class="todo-io-btn primary" data-io-action="confirm"${n?` disabled`:``}>${k(e)}</button>
239
- </div>`}function jc({field:e,value:t,label:n,hint:r,checked:i,count:a,danger:o}){let s=Number.isFinite(a)?`<em class="todo-io-count" data-io-count="${a}">${a}</em>`:``;return`<label class="todo-io-option${o?` danger`:``}">
239
+ </div>`}function Mc({field:e,value:t,label:n,hint:r,checked:i,count:a,danger:o}){let s=Number.isFinite(a)?`<em class="todo-io-count" data-io-count="${a}">${a}</em>`:``;return`<label class="todo-io-option${o?` danger`:``}">
240
240
  <input type="radio" name="todoIo-${j(e)}" value="${j(t)}"
241
241
  data-io-field="${j(e)}"${i?` checked`:``} />
242
242
  <span class="todo-io-option-main">
@@ -244,9 +244,9 @@ import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-DvmxOw8q.js"
244
244
  ${r?`<span class="todo-io-option-hint">${k(r)}</span>`:``}
245
245
  </span>
246
246
  ${s}
247
- </label>`}function Mc(e,n={}){let r=Ec.includes(e?.scope)?e.scope:`all`,i=Dc.includes(e?.format)?e.format:`json`,a=Number(n[r]||0)===0,o=[[`all`,t(`todoIo.scopeAll`)],[`active`,t(`todoIo.scopeActive`)],[`done`,t(`todoIo.scopeDone`)]].map(([e,t])=>jc({field:`scope`,value:e,label:t,checked:e===r,count:Number(n[e]||0)})).join(``),s=[[`json`,t(`todo.exportJson`)],[`md`,t(`todo.exportMd`)]].map(([e,t])=>jc({field:`format`,value:e,label:t,checked:e===i})).join(``);return`<div class="todo-io-card" role="dialog" aria-modal="true" tabindex="-1"
247
+ </label>`}function Nc(e,n={}){let r=Dc.includes(e?.scope)?e.scope:`all`,i=Oc.includes(e?.format)?e.format:`json`,a=Number(n[r]||0)===0,o=[[`all`,t(`todoIo.scopeAll`)],[`active`,t(`todoIo.scopeActive`)],[`done`,t(`todoIo.scopeDone`)]].map(([e,t])=>Mc({field:`scope`,value:e,label:t,checked:e===r,count:Number(n[e]||0)})).join(``),s=[[`json`,t(`todo.exportJson`)],[`md`,t(`todo.exportMd`)]].map(([e,t])=>Mc({field:`format`,value:e,label:t,checked:e===i})).join(``);return`<div class="todo-io-card" role="dialog" aria-modal="true" tabindex="-1"
248
248
  aria-label="${j(t(`todoIo.exportTitle`))}">
249
- ${kc(t(`todoIo.exportTitle`))}
249
+ ${Ac(t(`todoIo.exportTitle`))}
250
250
  <div class="todo-io-body">
251
251
  <div class="todo-io-group">
252
252
  <div class="todo-io-group-label">${k(t(`todoIo.rangeLabel`))}</div>
@@ -258,10 +258,10 @@ import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-DvmxOw8q.js"
258
258
  </div>
259
259
  <p class="todo-io-hint${a?` show`:``}" data-io-hint>${k(t(`todoIo.emptyRange`))}</p>
260
260
  </div>
261
- ${Ac(t(`todoIo.exportAction`),a)}
262
- </div>`}function Nc(e,n={}){let r=Oc.includes(e?.mode)?e.mode:`merge`,i=Number(n.count||0),a=Number(n.existing||0),o=[[`merge`,t(`todoIo.modeMerge`),t(`todoIo.modeMergeHint`)],[`replace`,t(`todoIo.modeReplace`),t(`todoIo.modeReplaceHint`,{n:a})]].map(([e,t,n])=>jc({field:`mode`,value:e,label:t,hint:n,checked:e===r,danger:e===`replace`})).join(``);return`<div class="todo-io-card" role="dialog" aria-modal="true" tabindex="-1"
261
+ ${jc(t(`todoIo.exportAction`),a)}
262
+ </div>`}function Pc(e,n={}){let r=kc.includes(e?.mode)?e.mode:`merge`,i=Number(n.count||0),a=Number(n.existing||0),o=[[`merge`,t(`todoIo.modeMerge`),t(`todoIo.modeMergeHint`)],[`replace`,t(`todoIo.modeReplace`),t(`todoIo.modeReplaceHint`,{n:a})]].map(([e,t,n])=>Mc({field:`mode`,value:e,label:t,hint:n,checked:e===r,danger:e===`replace`})).join(``);return`<div class="todo-io-card" role="dialog" aria-modal="true" tabindex="-1"
263
263
  aria-label="${j(t(`todoIo.importTitle`))}">
264
- ${kc(t(`todoIo.importTitle`))}
264
+ ${Ac(t(`todoIo.importTitle`))}
265
265
  <div class="todo-io-body">
266
266
  <p class="todo-io-summary">${k(t(`todoIo.importSummary`,{count:i,existing:a}))}</p>
267
267
  <div class="todo-io-group">
@@ -270,14 +270,14 @@ import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-DvmxOw8q.js"
270
270
  </div>
271
271
  <p class="todo-io-warn${r===`replace`?` show`:``}" data-io-warn>${k(t(`todoIo.replaceWarn`,{count:i}))}</p>
272
272
  </div>
273
- ${Ac(t(`todoIo.importAction`),!1)}
274
- </div>`}var R=null,z=null,Pc=null;function Fc(){return R||(R=document.createElement(`div`),R.className=`todo-io-overlay`,R.id=`todoIoOverlay`,R.addEventListener(`click`,e=>{if(e.target===R){zc(null);return}let t=e.target.closest?.(`[data-io-action]`);t?.dataset.ioAction===`cancel`?zc(null):t?.dataset.ioAction===`confirm`&&Rc()}),R.addEventListener(`change`,e=>{if(!z)return;let t=e.target.closest?.(`input[data-io-field]`);t&&(z.state[t.dataset.ioField]=t.value,Lc())}),document.body.appendChild(R),R)}function Ic(){if(!z)return;let e=Fc();e.innerHTML=z.kind===`export`?Mc(z.state,z.counts):Nc(z.state,z.info),Lc()}function Lc(){if(!(!z||!R)){if(z.kind===`export`){let e=!Number(z.counts[z.state.scope]||0),t=R.querySelector(`[data-io-action="confirm"]`);t&&(t.disabled=e),R.querySelector(`[data-io-hint]`)?.classList.toggle(`show`,e);return}R.querySelector(`[data-io-warn]`)?.classList.toggle(`show`,z.state.mode===`replace`)}}function Rc(){if(z){if(z.kind===`export`){if(!Number(z.counts[z.state.scope]||0))return;zc({scope:z.state.scope,format:z.state.format});return}zc(z.state.mode)}}function zc(e){if(!z)return;let{resolve:t}=z;z=null,R?.classList.remove(`show`),Vc(),t(e)}function Bc(){Pc||(Pc=e=>{e.key===`Escape`&&(e.stopPropagation(),zc(null))},document.addEventListener(`keydown`,Pc))}function Vc(){Pc&&=(document.removeEventListener(`keydown`,Pc),null)}function Hc(e,t,n){return z&&zc(null),new Promise(r=>{z={kind:e,state:t,...n,resolve:r},Ic(),R.classList.add(`show`),Bc(),R.querySelector(`.todo-io-card`)?.focus()})}function Uc({counts:e={},scope:t=`all`,format:n=`json`}={}){return Hc(`export`,{scope:Ec.includes(t)?t:`all`,format:Dc.includes(n)?n:`json`},{counts:e})}function Wc({count:e=0,existing:t=0,mode:n=`merge`}={}){return Hc(`import`,{mode:Oc.includes(n)?n:`merge`},{info:{count:e,existing:t}})}o(()=>{z&&(Ic(),R.querySelector(`.todo-io-card`)?.focus())}),e(`zh`,{todoStats:{title:`待办统计`,close:`关闭`,rate:`完成率`,doneOf:`已完成 {done} / {total}`,pending:`待处理`,doing:`处理中`,done:`已完成`,overdue:`逾期`,high:`高优先级`,week:`近 7 天完成`,dayTitle:`{date}:完成 {done} · 新增 {added}`,todayAdded:`今日新增 {n}`,todayDone:`今日完成 {n}`,streak:`连续完成 {n} 天`,highCount:`高优先级 {n}`,empty:`还没有待办,加一条就能看到趋势`}}),e(`en`,{todoStats:{title:`Todo stats`,close:`Close`,rate:`Completion`,doneOf:`{done} of {total} done`,pending:`Pending`,doing:`In progress`,done:`Done`,overdue:`Overdue`,high:`High priority`,week:`Done in last 7 days`,dayTitle:`{date}: {done} done · {added} added`,todayAdded:`{n} added today`,todayDone:`{n} done today`,streak:`{n}-day streak`,highCount:`{n} high priority`,empty:`No todos yet — add one to see the trend`}});var Gc={zh:[`日`,`一`,`二`,`三`,`四`,`五`,`六`],en:[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`]},Kc=6;function qc(e){let[t,n,r]=String(e||``).split(`-`).map(Number);return!t||!n||!r?null:new Date(t,n-1,r)}function Jc(e){let t=qc(e);return t?a()===`en`?`${t.toLocaleString(`en-US`,{month:`short`})} ${t.getDate()}`:`${t.getMonth()+1}月${t.getDate()}日`:String(e||``)}function Yc(e){let t=qc(e);return t?(Gc[a()]||Gc.zh)[t.getDay()]:``}function Xc(e,t,n){return`<div class="todo-stats-tile${n?` ${n}`:``}">
273
+ ${jc(t(`todoIo.importAction`),!1)}
274
+ </div>`}var R=null,z=null,Fc=null;function Ic(){return R||(R=document.createElement(`div`),R.className=`todo-io-overlay`,R.id=`todoIoOverlay`,R.addEventListener(`click`,e=>{if(e.target===R){Bc(null);return}let t=e.target.closest?.(`[data-io-action]`);t?.dataset.ioAction===`cancel`?Bc(null):t?.dataset.ioAction===`confirm`&&zc()}),R.addEventListener(`change`,e=>{if(!z)return;let t=e.target.closest?.(`input[data-io-field]`);t&&(z.state[t.dataset.ioField]=t.value,Rc())}),document.body.appendChild(R),R)}function Lc(){if(!z)return;let e=Ic();e.innerHTML=z.kind===`export`?Nc(z.state,z.counts):Pc(z.state,z.info),Rc()}function Rc(){if(!(!z||!R)){if(z.kind===`export`){let e=!Number(z.counts[z.state.scope]||0),t=R.querySelector(`[data-io-action="confirm"]`);t&&(t.disabled=e),R.querySelector(`[data-io-hint]`)?.classList.toggle(`show`,e);return}R.querySelector(`[data-io-warn]`)?.classList.toggle(`show`,z.state.mode===`replace`)}}function zc(){if(z){if(z.kind===`export`){if(!Number(z.counts[z.state.scope]||0))return;Bc({scope:z.state.scope,format:z.state.format});return}Bc(z.state.mode)}}function Bc(e){if(!z)return;let{resolve:t}=z;z=null,R?.classList.remove(`show`),Hc(),t(e)}function Vc(){Fc||(Fc=e=>{e.key===`Escape`&&(e.stopPropagation(),Bc(null))},document.addEventListener(`keydown`,Fc))}function Hc(){Fc&&=(document.removeEventListener(`keydown`,Fc),null)}function Uc(e,t,n){return z&&Bc(null),new Promise(r=>{z={kind:e,state:t,...n,resolve:r},Lc(),R.classList.add(`show`),Vc(),R.querySelector(`.todo-io-card`)?.focus()})}function Wc({counts:e={},scope:t=`all`,format:n=`json`}={}){return Uc(`export`,{scope:Dc.includes(t)?t:`all`,format:Oc.includes(n)?n:`json`},{counts:e})}function Gc({count:e=0,existing:t=0,mode:n=`merge`}={}){return Uc(`import`,{mode:kc.includes(n)?n:`merge`},{info:{count:e,existing:t}})}o(()=>{z&&(Lc(),R.querySelector(`.todo-io-card`)?.focus())}),e(`zh`,{todoStats:{title:`待办统计`,close:`关闭`,rate:`完成率`,doneOf:`已完成 {done} / {total}`,pending:`待处理`,doing:`处理中`,done:`已完成`,overdue:`逾期`,high:`高优先级`,week:`近 7 天完成`,dayTitle:`{date}:完成 {done} · 新增 {added}`,todayAdded:`今日新增 {n}`,todayDone:`今日完成 {n}`,streak:`连续完成 {n} 天`,highCount:`高优先级 {n}`,empty:`还没有待办,加一条就能看到趋势`}}),e(`en`,{todoStats:{title:`Todo stats`,close:`Close`,rate:`Completion`,doneOf:`{done} of {total} done`,pending:`Pending`,doing:`In progress`,done:`Done`,overdue:`Overdue`,high:`High priority`,week:`Done in last 7 days`,dayTitle:`{date}: {done} done · {added} added`,todayAdded:`{n} added today`,todayDone:`{n} done today`,streak:`{n}-day streak`,highCount:`{n} high priority`,empty:`No todos yet — add one to see the trend`}});var Kc={zh:[`日`,`一`,`二`,`三`,`四`,`五`,`六`],en:[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`]},qc=6;function Jc(e){let[t,n,r]=String(e||``).split(`-`).map(Number);return!t||!n||!r?null:new Date(t,n-1,r)}function Yc(e){let t=Jc(e);return t?a()===`en`?`${t.toLocaleString(`en-US`,{month:`short`})} ${t.getDate()}`:`${t.getMonth()+1}月${t.getDate()}日`:String(e||``)}function Xc(e){let t=Jc(e);return t?(Kc[a()]||Kc.zh)[t.getDay()]:``}function Zc(e,t,n){return`<div class="todo-stats-tile${n?` ${n}`:``}">
275
275
  <span class="todo-stats-tile-value">${e}</span>
276
276
  <span class="todo-stats-tile-label">${t}</span>
277
- </div>`}function Zc(e){let n=e.reduce((e,t)=>Math.max(e,t.done||0),0);return`<div class="todo-stats-week">${e.map(e=>{let r=e.done||0,i=r===0?0:Math.max(Kc,Math.round(r/n*100));return`<div class="todo-stats-bar-col" title="${t(`todoStats.dayTitle`,{date:Jc(e.date),done:r,added:e.added||0})}">
277
+ </div>`}function Qc(e){let n=e.reduce((e,t)=>Math.max(e,t.done||0),0);return`<div class="todo-stats-week">${e.map(e=>{let r=e.done||0,i=r===0?0:Math.max(qc,Math.round(r/n*100));return`<div class="todo-stats-bar-col" title="${t(`todoStats.dayTitle`,{date:Yc(e.date),done:r,added:e.added||0})}">
278
278
  <span class="todo-stats-bar" style="height:${i}%"></span>
279
- <span class="todo-stats-bar-label">${Yc(e.date)}</span>
280
- </div>`}).join(``)}</div>`}function Qc(e){let n=e&&typeof e==`object`?e:{},r=Number(n.total)||0;if(r===0)return`<div class="todo-stats-empty">${t(`todoStats.empty`)}</div>`;let i=Math.min(100,Math.max(0,Number(n.doneRate)||0)),a=n.today||{added:0,done:0},o=Array.isArray(n.week)?n.week:[];return`<div class="todo-stats-hero">
279
+ <span class="todo-stats-bar-label">${Xc(e.date)}</span>
280
+ </div>`}).join(``)}</div>`}function $c(e){let n=e&&typeof e==`object`?e:{},r=Number(n.total)||0;if(r===0)return`<div class="todo-stats-empty">${t(`todoStats.empty`)}</div>`;let i=Math.min(100,Math.max(0,Number(n.doneRate)||0)),a=n.today||{added:0,done:0},o=Array.isArray(n.week)?n.week:[];return`<div class="todo-stats-hero">
281
281
  <div class="todo-stats-rate">
282
282
  <span class="todo-stats-rate-value">${i}%</span>
283
283
  <span class="todo-stats-rate-label">${t(`todoStats.rate`)}</span>
@@ -286,29 +286,29 @@ import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-DvmxOw8q.js"
286
286
  <div class="todo-stats-track"><i style="width:${i}%"></i></div>
287
287
  </div>
288
288
  <div class="todo-stats-tiles">
289
- ${Xc(n.pending||0,t(`todoStats.pending`))}
290
- ${Xc(n.doing||0,t(`todoStats.doing`),`doing`)}
291
- ${Xc(n.done||0,t(`todoStats.done`),`done`)}
292
- ${Xc(n.overdue||0,t(`todoStats.overdue`),n.overdue?`alert`:``)}
289
+ ${Zc(n.pending||0,t(`todoStats.pending`))}
290
+ ${Zc(n.doing||0,t(`todoStats.doing`),`doing`)}
291
+ ${Zc(n.done||0,t(`todoStats.done`),`done`)}
292
+ ${Zc(n.overdue||0,t(`todoStats.overdue`),n.overdue?`alert`:``)}
293
293
  </div>
294
294
  <div class="todo-stats-section">
295
295
  <div class="todo-stats-section-title">${t(`todoStats.week`)}</div>
296
- ${Zc(o)}
296
+ ${Qc(o)}
297
297
  </div>
298
298
  <div class="todo-stats-facts">
299
299
  <span>${t(`todoStats.todayAdded`,{n:a.added||0})}</span>
300
300
  <span>${t(`todoStats.todayDone`,{n:a.done||0})}</span>
301
301
  <span>${t(`todoStats.streak`,{n:n.streak||0})}</span>
302
302
  <span>${t(`todoStats.highCount`,{n:n.high||0})}</span>
303
- </div>`}var $c=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M18 6L6 18"/><path d="M6 6l12 12"/></svg>`,el=null,tl=null;function nl(){return el||(el=document.createElement(`div`),el.className=`todo-stats-overlay`,el.id=`todoStatsOverlay`,el.addEventListener(`click`,e=>{(e.target===el||e.target.closest?.(`[data-action="close-stats"]`))&&ol()}),document.body.appendChild(el),el)}function rl(e){let n=nl();n.innerHTML=`
303
+ </div>`}var el=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M18 6L6 18"/><path d="M6 6l12 12"/></svg>`,tl=null,nl=null;function rl(){return tl||(tl=document.createElement(`div`),tl.className=`todo-stats-overlay`,tl.id=`todoStatsOverlay`,tl.addEventListener(`click`,e=>{(e.target===tl||e.target.closest?.(`[data-action="close-stats"]`))&&sl()}),document.body.appendChild(tl),tl)}function il(e){let n=rl();n.innerHTML=`
304
304
  <div class="todo-stats-card" role="dialog" aria-modal="true" aria-label="${j(t(`todoStats.title`))}">
305
305
  <div class="todo-stats-header">
306
306
  <span class="todo-stats-title">${t(`todoStats.title`)}</span>
307
307
  <button type="button" class="todo-stats-close" data-action="close-stats"
308
- title="${j(t(`todoStats.close`))}" aria-label="${j(t(`todoStats.close`))}">${$c}</button>
308
+ title="${j(t(`todoStats.close`))}" aria-label="${j(t(`todoStats.close`))}">${el}</button>
309
309
  </div>
310
- <div class="todo-stats-body">${Qc(e)}</div>
311
- </div>`}async function il(){let e=await Ks(),{active:t,done:n}=ec();rl(Ws([...t,...n],e))}async function al(){await il();let e=nl();e.classList.add(`show`),tl||(tl=e=>{e.key===`Escape`&&(e.stopPropagation(),ol())},document.addEventListener(`keydown`,tl)),e.querySelector(`.todo-stats-close`)?.focus()}function ol(){el&&(el.classList.remove(`show`),tl&&=(document.removeEventListener(`keydown`,tl),null))}o(()=>{el?.classList.contains(`show`)&&il()}),e(`zh`,{todo:{toggleTitle:`待办`,title:`待办`,fillInput:`填入输入框`,fillInputTitle:`把待办清单填入问答输入框`,placeholder:`添加待办,回车保存`,addTitle:`添加`,empty:`暂无待办`,emptyHint:`在上方输入后回车即可添加`,emptyDone:`还没有已完成的待办`,emptyDoneHint:`把某条标记完成后,它会出现在这里`,tabActive:`待办`,tabDone:`已完成`,progressLabel:`完成 {done} / {total}`,progressDoing:` · 处理中 {doing}`,startDoing:`开始处理`,markDone:`标记完成`,backToPending:`退回待办`,restoreTo:`恢复到{status}`,undoBar:`已标记完成「{title}」`,undoAction:`撤销`,restoredToast:`已恢复到{status}`,priority:`优先级`,priorityHigh:`高`,priorityMedium:`中`,priorityLow:`低`,priorityNone:`无`,priorityTitle:`优先级:{level}`,addLink:`添加链接`,editLink:`编辑链接`,linkPlaceholder:`粘贴链接,回车关联`,linkSavedToast:`已关联链接`,linkRemovedToast:`已移除链接`,linkInvalid:`链接格式不对,仅支持 http/https`,openLinkTitle:`打开 {host}`,statusTip:`当前:{status} · 点击切到{next}`,noteToggle:`备注`,notePlaceholder:`补充备注(可选)`,noteSave:`保存`,noteCancel:`取消`,editTitleAction:`编辑标题`,addNote:`添加备注`,editNote:`编辑备注`,setDue:`设置截止`,clearDue:`清除截止`,delete:`删除`,deleteConfirmTitle:`删除待办`,deleteConfirmMsg:`确定删除「{title}」吗?`,more:`更多操作`,headerMore:`更多`,copyItem:`复制本条`,editItem:`编辑`,clearCompleted:`清除已完成`,clearCompletedConfirmTitle:`清除已完成`,clearCompletedConfirmMsg:`确定删除全部 {n} 条已完成待办吗?`,statusPending:`待处理`,statusDoing:`处理中`,statusDone:`已完成`,filledToast:`已填入输入框`,copiedToast:`已复制到剪贴板`,emptyDigestToast:`暂无可复制的待办`,copyFailed:`复制失败`,noInputToast:`未找到输入框`,saveFailed:`保存失败,请重试`,deletedToast:`已删除`,clearedToast:`已清除已完成`,exportJson:`JSON(可再导入)`,exportMd:`Markdown(可读文本)`,exportEntry:`导出…`,importEntry:`导入…`,exportEmptyToast:`当前范围内没有待办`,exportedToast:`已导出 {name}`,exportFailedToast:`导出失败,请重试`,importJsonError:`不是有效的待办文件:JSON 解析失败`,importFormatError:`文件结构不对,需要待办导出文件`,importEmptyToast:`文件里没有可导入的待办,现有数据已保留`,importNothingNewToast:`没有新增待办({skipped} 条已存在或无效)`,importedToast:`已导入 {added} 条(跳过 {skipped} 条)`,importFailedToast:`导入失败,请重试`,statsEntry:`待办统计`}}),e(`en`,{todo:{toggleTitle:`Todos`,title:`Todos`,fillInput:`To input`,fillInputTitle:`Insert todo list into the chat input`,placeholder:`Add a todo, press Enter`,addTitle:`Add`,empty:`No todos`,emptyHint:`Type above and press Enter to add`,emptyDone:`Nothing completed yet`,emptyDoneHint:`Mark a todo as done and it lands here`,tabActive:`To do`,tabDone:`Done`,progressLabel:`{done} / {total} done`,progressDoing:` · {doing} in progress`,startDoing:`Start`,markDone:`Mark done`,backToPending:`Back to to-do`,restoreTo:`Restore to {status}`,undoBar:`Marked done “{title}”`,undoAction:`Undo`,restoredToast:`Restored to {status}`,priority:`Priority`,priorityHigh:`High`,priorityMedium:`Medium`,priorityLow:`Low`,priorityNone:`None`,priorityTitle:`Priority: {level}`,addLink:`Add link`,editLink:`Edit link`,linkPlaceholder:`Paste a link, press Enter`,linkSavedToast:`Link attached`,linkRemovedToast:`Link removed`,linkInvalid:`Invalid link, only http/https`,openLinkTitle:`Open {host}`,statusTip:`Now: {status} · click for {next}`,noteToggle:`Note`,notePlaceholder:`Add a note (optional)`,noteSave:`Save`,noteCancel:`Cancel`,editTitleAction:`Edit title`,addNote:`Add note`,editNote:`Edit note`,setDue:`Set due date`,clearDue:`Clear due date`,delete:`Delete`,deleteConfirmTitle:`Delete todo`,deleteConfirmMsg:`Delete "{title}"?`,more:`More actions`,headerMore:`More`,copyItem:`Copy this`,editItem:`Edit`,clearCompleted:`Clear completed`,clearCompletedConfirmTitle:`Clear completed`,clearCompletedConfirmMsg:`Delete all {n} completed todos?`,statusPending:`Pending`,statusDoing:`In progress`,statusDone:`Done`,filledToast:`Inserted into input`,copiedToast:`Copied to clipboard`,emptyDigestToast:`Nothing to copy`,copyFailed:`Copy failed`,noInputToast:`Input box not found`,saveFailed:`Failed to save, try again`,deletedToast:`Deleted`,clearedToast:`Completed todos cleared`,exportJson:`JSON (re-importable)`,exportMd:`Markdown (readable)`,exportEntry:`Export…`,importEntry:`Import…`,exportEmptyToast:`Nothing to export in this range`,exportedToast:`Exported {name}`,exportFailedToast:`Export failed, try again`,importJsonError:`Not a valid todo file: JSON parse failed`,importFormatError:`Unexpected file structure, need a todo export file`,importEmptyToast:`No importable todos in the file, existing data kept`,importNothingNewToast:`Nothing new to import ({skipped} existing or invalid)`,importedToast:`Imported {added} todos ({skipped} skipped)`,importFailedToast:`Import failed, try again`,statsEntry:`Statistics`}});var sl=`.input-container`,cl=160,ll=8,ul=108,dl=220,fl=6e3,B={listCheck:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 11l3 3L22 4"/><path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"/></svg>`,more:`<svg viewBox="0 0 24 24" fill="currentColor"><circle cx="5" cy="12" r="1.7"/><circle cx="12" cy="12" r="1.7"/><circle cx="19" cy="12" r="1.7"/></svg>`,close:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M18 6L6 18"/><path d="M6 6l12 12"/></svg>`,fill:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 3v12"/><path d="M8 11l4 4 4-4"/><path d="M4 19h16"/></svg>`,edit:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20h9"/><path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4z"/></svg>`,copy:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="12" height="12" rx="2"/><path d="M5 15V5a2 2 0 0 1 2-2h10"/></svg>`,note:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>`,calendar:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="17" rx="2"/><path d="M8 2v4M16 2v4M3 10h18"/></svg>`,trash:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h18M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6M8 6V4a1 1 0 0 1 1-1h6a1 1 0 0 1 1 1v2"/></svg>`,chevron:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><path d="M9 6l6 6-6 6"/></svg>`,check:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3.5" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6L9 17l-5-5"/></svg>`,alert:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><path d="M12 7v6"/><path d="M12 16.5v.01"/></svg>`,play:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><path d="M10 8.5l6 3.5-6 3.5z"/></svg>`,undo:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 10h11a5 5 0 0 1 0 10H8"/><path d="M7 6l-4 4 4 4"/></svg>`,circle:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="9"/></svg>`,link:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7 0l2-2a5 5 0 0 0-7-7l-1 1"/><path d="M14 11a5 5 0 0 0-7 0l-2 2a5 5 0 0 0 7 7l1-1"/></svg>`,upload:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 17V5"/><path d="M8 9l4-4 4 4"/><path d="M4 20h16"/></svg>`,download:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 5v12"/><path d="M8 13l4 4 4-4"/><path d="M4 20h16"/></svg>`,chart:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M4 20V11"/><path d="M10 20V4"/><path d="M16 20v-6"/></svg>`},V=null,H=null,U=null,pl=null,ml=null,hl=null,gl=null,_l=null,vl=null,yl=null,bl=null,xl=`active`,W=null,Sl=null,Cl=null,G=null,wl=new Set,Tl=null,El=!1,Dl=null,Ol=null,kl=null,Al=null,jl=0,Ml=new Map,Nl=[`todo-edit-input`,`todo-note-input`,`todo-due-input`,`todo-link-input`],Pl={"todo-edit-input":`title`,"todo-note-input":`note`,"todo-due-input":`due`,"todo-link-input":`link`};function Fl(){El||(El=!0,V=document.createElement(`div`),V.className=`todo-panel-container`,V.id=`todoPanelContainer`,V.innerHTML=`
310
+ <div class="todo-stats-body">${$c(e)}</div>
311
+ </div>`}async function al(){let e=await qs(),{active:t,done:n}=tc();il(Gs([...t,...n],e))}async function ol(){await al();let e=rl();e.classList.add(`show`),nl||(nl=e=>{e.key===`Escape`&&(e.stopPropagation(),sl())},document.addEventListener(`keydown`,nl)),e.querySelector(`.todo-stats-close`)?.focus()}function sl(){tl&&(tl.classList.remove(`show`),nl&&=(document.removeEventListener(`keydown`,nl),null))}o(()=>{tl?.classList.contains(`show`)&&al()}),e(`zh`,{todo:{toggleTitle:`待办`,title:`待办`,fillInput:`填入输入框`,fillInputTitle:`把待办清单填入问答输入框`,placeholder:`添加待办,回车保存`,addTitle:`添加`,empty:`暂无待办`,emptyHint:`在上方输入后回车即可添加`,emptyDone:`还没有已完成的待办`,emptyDoneHint:`把某条标记完成后,它会出现在这里`,tabActive:`待办`,tabDone:`已完成`,progressLabel:`完成 {done} / {total}`,progressDoing:` · 处理中 {doing}`,startDoing:`开始处理`,markDone:`标记完成`,backToPending:`退回待办`,restoreTo:`恢复到{status}`,undoBar:`已标记完成「{title}」`,undoAction:`撤销`,restoredToast:`已恢复到{status}`,priority:`优先级`,priorityHigh:`高`,priorityMedium:`中`,priorityLow:`低`,priorityNone:`无`,priorityTitle:`优先级:{level}`,addLink:`添加链接`,editLink:`编辑链接`,linkPlaceholder:`粘贴链接,回车关联`,linkSavedToast:`已关联链接`,linkRemovedToast:`已移除链接`,linkInvalid:`链接格式不对,仅支持 http/https`,openLinkTitle:`打开 {host}`,statusTip:`当前:{status} · 点击切到{next}`,noteToggle:`备注`,notePlaceholder:`补充备注(可选)`,noteSave:`保存`,noteCancel:`取消`,editTitleAction:`编辑标题`,addNote:`添加备注`,editNote:`编辑备注`,setDue:`设置截止`,clearDue:`清除截止`,delete:`删除`,deleteConfirmTitle:`删除待办`,deleteConfirmMsg:`确定删除「{title}」吗?`,more:`更多操作`,headerMore:`更多`,copyItem:`复制本条`,editItem:`编辑`,clearCompleted:`清除已完成`,clearCompletedConfirmTitle:`清除已完成`,clearCompletedConfirmMsg:`确定删除全部 {n} 条已完成待办吗?`,statusPending:`待处理`,statusDoing:`处理中`,statusDone:`已完成`,filledToast:`已填入输入框`,copiedToast:`已复制到剪贴板`,emptyDigestToast:`暂无可复制的待办`,copyFailed:`复制失败`,noInputToast:`未找到输入框`,saveFailed:`保存失败,请重试`,deletedToast:`已删除`,clearedToast:`已清除已完成`,exportJson:`JSON(可再导入)`,exportMd:`Markdown(可读文本)`,exportEntry:`导出…`,importEntry:`导入…`,exportEmptyToast:`当前范围内没有待办`,exportedToast:`已导出 {name}`,exportFailedToast:`导出失败,请重试`,importJsonError:`不是有效的待办文件:JSON 解析失败`,importFormatError:`文件结构不对,需要待办导出文件`,importEmptyToast:`文件里没有可导入的待办,现有数据已保留`,importNothingNewToast:`没有新增待办({skipped} 条已存在或无效)`,importedToast:`已导入 {added} 条(跳过 {skipped} 条)`,importFailedToast:`导入失败,请重试`,statsEntry:`待办统计`}}),e(`en`,{todo:{toggleTitle:`Todos`,title:`Todos`,fillInput:`To input`,fillInputTitle:`Insert todo list into the chat input`,placeholder:`Add a todo, press Enter`,addTitle:`Add`,empty:`No todos`,emptyHint:`Type above and press Enter to add`,emptyDone:`Nothing completed yet`,emptyDoneHint:`Mark a todo as done and it lands here`,tabActive:`To do`,tabDone:`Done`,progressLabel:`{done} / {total} done`,progressDoing:` · {doing} in progress`,startDoing:`Start`,markDone:`Mark done`,backToPending:`Back to to-do`,restoreTo:`Restore to {status}`,undoBar:`Marked done “{title}”`,undoAction:`Undo`,restoredToast:`Restored to {status}`,priority:`Priority`,priorityHigh:`High`,priorityMedium:`Medium`,priorityLow:`Low`,priorityNone:`None`,priorityTitle:`Priority: {level}`,addLink:`Add link`,editLink:`Edit link`,linkPlaceholder:`Paste a link, press Enter`,linkSavedToast:`Link attached`,linkRemovedToast:`Link removed`,linkInvalid:`Invalid link, only http/https`,openLinkTitle:`Open {host}`,statusTip:`Now: {status} · click for {next}`,noteToggle:`Note`,notePlaceholder:`Add a note (optional)`,noteSave:`Save`,noteCancel:`Cancel`,editTitleAction:`Edit title`,addNote:`Add note`,editNote:`Edit note`,setDue:`Set due date`,clearDue:`Clear due date`,delete:`Delete`,deleteConfirmTitle:`Delete todo`,deleteConfirmMsg:`Delete "{title}"?`,more:`More actions`,headerMore:`More`,copyItem:`Copy this`,editItem:`Edit`,clearCompleted:`Clear completed`,clearCompletedConfirmTitle:`Clear completed`,clearCompletedConfirmMsg:`Delete all {n} completed todos?`,statusPending:`Pending`,statusDoing:`In progress`,statusDone:`Done`,filledToast:`Inserted into input`,copiedToast:`Copied to clipboard`,emptyDigestToast:`Nothing to copy`,copyFailed:`Copy failed`,noInputToast:`Input box not found`,saveFailed:`Failed to save, try again`,deletedToast:`Deleted`,clearedToast:`Completed todos cleared`,exportJson:`JSON (re-importable)`,exportMd:`Markdown (readable)`,exportEntry:`Export…`,importEntry:`Import…`,exportEmptyToast:`Nothing to export in this range`,exportedToast:`Exported {name}`,exportFailedToast:`Export failed, try again`,importJsonError:`Not a valid todo file: JSON parse failed`,importFormatError:`Unexpected file structure, need a todo export file`,importEmptyToast:`No importable todos in the file, existing data kept`,importNothingNewToast:`Nothing new to import ({skipped} existing or invalid)`,importedToast:`Imported {added} todos ({skipped} skipped)`,importFailedToast:`Import failed, try again`,statsEntry:`Statistics`}});var cl=`.input-container`,ll=160,ul=8,dl=108,fl=220,pl=6e3,B={listCheck:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 11l3 3L22 4"/><path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"/></svg>`,more:`<svg viewBox="0 0 24 24" fill="currentColor"><circle cx="5" cy="12" r="1.7"/><circle cx="12" cy="12" r="1.7"/><circle cx="19" cy="12" r="1.7"/></svg>`,close:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M18 6L6 18"/><path d="M6 6l12 12"/></svg>`,fill:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 3v12"/><path d="M8 11l4 4 4-4"/><path d="M4 19h16"/></svg>`,edit:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20h9"/><path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4z"/></svg>`,copy:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="12" height="12" rx="2"/><path d="M5 15V5a2 2 0 0 1 2-2h10"/></svg>`,note:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>`,calendar:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="17" rx="2"/><path d="M8 2v4M16 2v4M3 10h18"/></svg>`,trash:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h18M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6M8 6V4a1 1 0 0 1 1-1h6a1 1 0 0 1 1 1v2"/></svg>`,chevron:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><path d="M9 6l6 6-6 6"/></svg>`,check:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3.5" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6L9 17l-5-5"/></svg>`,alert:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><path d="M12 7v6"/><path d="M12 16.5v.01"/></svg>`,play:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><path d="M10 8.5l6 3.5-6 3.5z"/></svg>`,undo:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 10h11a5 5 0 0 1 0 10H8"/><path d="M7 6l-4 4 4 4"/></svg>`,circle:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="9"/></svg>`,link:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7 0l2-2a5 5 0 0 0-7-7l-1 1"/><path d="M14 11a5 5 0 0 0-7 0l-2 2a5 5 0 0 0 7 7l1-1"/></svg>`,upload:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 17V5"/><path d="M8 9l4-4 4 4"/><path d="M4 20h16"/></svg>`,download:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 5v12"/><path d="M8 13l4 4 4-4"/><path d="M4 20h16"/></svg>`,chart:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M4 20V11"/><path d="M10 20V4"/><path d="M16 20v-6"/></svg>`},V=null,H=null,U=null,ml=null,hl=null,gl=null,_l=null,vl=null,yl=null,bl=null,xl=null,Sl=`active`,Cl=null,wl=null,Tl=null,W=null,El=new Set,Dl=null,Ol=!1,kl=null,Al=null,jl=null,Ml=null,Nl=0,Pl=new Map,Fl=[`todo-edit-input`,`todo-note-input`,`todo-due-input`,`todo-link-input`],Il={"todo-edit-input":`title`,"todo-note-input":`note`,"todo-due-input":`due`,"todo-link-input":`link`};function Ll(){Ol||(Ol=!0,V=document.createElement(`div`),V.className=`todo-panel-container`,V.id=`todoPanelContainer`,V.innerHTML=`
312
312
  <button class="todo-panel-toggle" id="todoPanelToggle" data-i18n-title="todo.toggleTitle" data-i18n-aria-label="todo.toggleTitle">
313
313
  <span class="todo-badge" id="todoBadge" style="display:none;"></span>
314
314
  ${B.listCheck}
@@ -340,17 +340,17 @@ import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-DvmxOw8q.js"
340
340
  </div>
341
341
  <div class="todo-body" id="todoBody"></div>
342
342
  </div>
343
- `,Nn(`todo`).appendChild(V),i(V),gl=V.querySelector(`#todoPanelToggle`),H=V.querySelector(`#todoPanel`),U=V.querySelector(`#todoBody`),pl=V.querySelector(`#todoPanelCount`),ml=V.querySelector(`#todoProgressBar`),hl=V.querySelector(`#todoAddInput`),_l=V.querySelector(`#todoBadge`),yl=V.querySelector(`#todoTabActive`),bl=V.querySelector(`#todoTabDone`),pl.textContent=t(`todo.progressLabel`,{done:0,total:0}),gl.addEventListener(`click`,Ll),V.addEventListener(`click`,du),V.addEventListener(`change`,ju),V.addEventListener(`keydown`,vu),U.addEventListener(`dragstart`,nd),U.addEventListener(`dragover`,rd),U.addEventListener(`drop`,ad),U.addEventListener(`dragend`,od),U.addEventListener(`focusout`,Mu),U.addEventListener(`focusin`,e=>{let t=e.target.closest?.(`.todo-item`);t?.dataset.id&&(kl=t.dataset.id)}),V.addEventListener(`pointerdown`,e=>{let t=e.target?.closest?.(`[data-action="link-cancel"]`);t&&(e.preventDefault(),Iu(t.dataset.id||G))}),document.addEventListener(`keydown`,e=>{e.key===`Escape`&&vl&&Bu()}),document.addEventListener(`keydown`,xu),document.addEventListener(`click`,e=>{vl&&(vl.contains(e.target)||Bu())},!0),Qs(()=>q()),chrome.runtime.onMessage.addListener(e=>{e?.type===`TODO_CHANGED`&&$s().catch(()=>{})}),o(()=>{i(V),q()}),n().then(()=>{i(V),q()}),q())}function Il(){return!!H&&H.classList.contains(`expanded`)}function Ll(){Il()?zl():Rl()}function Rl(){xl=`active`,Dl=null,jl=0,H.style.removeProperty(`height`),q(),H.classList.add(`expanded`),gl.classList.add(`active`),Zl(),Xl(),setTimeout(()=>{Il()&&hl.focus()},60)}function zl(){H.classList.remove(`expanded`),gl.classList.remove(`active`),Ql(),H.style.removeProperty(`--fit-y`),H.style.removeProperty(`--todo-max-h`),H.style.removeProperty(`height`),jl=0,Bu(),Lu(),eu()}function Bl(){Nl.forEach(e=>{U.querySelectorAll(`.${e}`).forEach(t=>{let n=t.dataset.id;if(!n)return;let r=Ml.get(n)||{};r[Pl[e]]=t.value,Ml.set(n,r)})})}function Vl(e){if(Ml.size===0)return;let t=new Set(e.map(e=>e.id));for(let e of[...Ml.keys()])t.has(e)||Ml.delete(e)}function K(e){e?Ml.delete(e):Ml.clear()}function Hl(e,t){let n=Ml.get(e);return n&&n[t]!==void 0?n[t]:null}function Ul(){let e=document.activeElement;if(!e||!U.contains(e))return null;let t=Nl.find(t=>e.classList.contains(t));return!t||!e.dataset.id?null:{cls:t,id:e.dataset.id,caret:Wl(e)}}function Wl(e){try{return e.selectionStart}catch{return null}}function Gl(e){return U.querySelector(`.${e.cls}[data-id="${j(e.id)}"]`)}function Kl(e){let t=Gl(e);if(t&&(t.focus(),e.caret!==null))try{t.selectionStart=t.selectionEnd=e.caret}catch{}}function ql(){if(W){cu();return}if(Sl){let e=Gl({cls:`todo-note-input`,id:Sl});e&&e.focus();return}if(Cl){let e=Gl({cls:`todo-due-input`,id:Cl});e&&e.focus();return}if(G){let e=Gl({cls:`todo-link-input`,id:G});if(!e)return;e.focus(),e.selectionStart=e.selectionEnd=e.value.length}}function q(){if(!U)return;Bl();let e=Ul(),n=document.activeElement?.closest?.(`.todo-item`)?.dataset.id||null,{active:r,done:i,stats:a}=ec();pl.textContent=t(`todo.progressLabel`,{done:a.done,total:a.total})+(a.doing>0?t(`todo.progressDoing`,{doing:a.doing}):``),ml.style.width=a.total?`${Math.round(a.done/a.total*100)}%`:`0%`,tu(r.length),Jl(r.length,i.length);let o=xl===`done`?i:r,s=[];if(Vl([...r,...i]),Dl&&s.push(`<div class="todo-undo">
344
- <span class="todo-undo-text">${k(t(`todo.undoBar`,{title:Dl.title}))}</span>
345
- <button class="todo-mini-btn" data-action="undo-complete" data-id="${j(Dl.id)}">${k(t(`todo.undoAction`))}</button>
346
- </div>`),xl===`done`&&i.length>0&&s.push(`<button class="todo-clear-done" data-action="clear-completed-btn">
343
+ `,ea(`todo`).appendChild(V),i(V),_l=V.querySelector(`#todoPanelToggle`),H=V.querySelector(`#todoPanel`),U=V.querySelector(`#todoBody`),ml=V.querySelector(`#todoPanelCount`),hl=V.querySelector(`#todoProgressBar`),gl=V.querySelector(`#todoAddInput`),vl=V.querySelector(`#todoBadge`),bl=V.querySelector(`#todoTabActive`),xl=V.querySelector(`#todoTabDone`),ml.textContent=t(`todo.progressLabel`,{done:0,total:0}),_l.addEventListener(`click`,zl),V.addEventListener(`click`,pu),V.addEventListener(`change`,Nu),V.addEventListener(`keydown`,bu),U.addEventListener(`dragstart`,id),U.addEventListener(`dragover`,ad),U.addEventListener(`drop`,sd),U.addEventListener(`dragend`,cd),U.addEventListener(`focusout`,Pu),U.addEventListener(`focusin`,e=>{let t=e.target.closest?.(`.todo-item`);t?.dataset.id&&(jl=t.dataset.id)}),V.addEventListener(`pointerdown`,e=>{let t=e.target?.closest?.(`[data-action="link-cancel"]`);t&&(e.preventDefault(),Ru(t.dataset.id||W))}),document.addEventListener(`keydown`,e=>{e.key===`Escape`&&yl&&Hu()}),document.addEventListener(`keydown`,Cu),document.addEventListener(`click`,e=>{yl&&(yl.contains(e.target)||Hu())},!0),$s(()=>K()),chrome.runtime.onMessage.addListener(e=>{e?.type===`TODO_CHANGED`&&ec().catch(()=>{})}),o(()=>{i(V),K()}),n().then(()=>{i(V),K()}),K())}function Rl(){return!!H&&H.classList.contains(`expanded`)}function zl(){Rl()?Vl():Bl()}function Bl(){Sl=`active`,kl=null,Nl=0,H.style.removeProperty(`height`),K(),H.classList.add(`expanded`),_l.classList.add(`active`),$l(),Ql(),setTimeout(()=>{Rl()&&gl.focus()},60)}function Vl(){H.classList.remove(`expanded`),_l.classList.remove(`active`),eu(),H.style.removeProperty(`--fit-y`),H.style.removeProperty(`--todo-max-h`),H.style.removeProperty(`height`),Nl=0,Hu(),zu(),nu()}function Hl(){Fl.forEach(e=>{U.querySelectorAll(`.${e}`).forEach(t=>{let n=t.dataset.id;if(!n)return;let r=Pl.get(n)||{};r[Il[e]]=t.value,Pl.set(n,r)})})}function Ul(e){if(Pl.size===0)return;let t=new Set(e.map(e=>e.id));for(let e of[...Pl.keys()])t.has(e)||Pl.delete(e)}function G(e){e?Pl.delete(e):Pl.clear()}function Wl(e,t){let n=Pl.get(e);return n&&n[t]!==void 0?n[t]:null}function Gl(){let e=document.activeElement;if(!e||!U.contains(e))return null;let t=Fl.find(t=>e.classList.contains(t));return!t||!e.dataset.id?null:{cls:t,id:e.dataset.id,caret:Kl(e)}}function Kl(e){try{return e.selectionStart}catch{return null}}function ql(e){return U.querySelector(`.${e.cls}[data-id="${j(e.id)}"]`)}function Jl(e){let t=ql(e);if(t&&(t.focus(),e.caret!==null))try{t.selectionStart=t.selectionEnd=e.caret}catch{}}function Yl(){if(Cl){uu();return}if(wl){let e=ql({cls:`todo-note-input`,id:wl});e&&e.focus();return}if(Tl){let e=ql({cls:`todo-due-input`,id:Tl});e&&e.focus();return}if(W){let e=ql({cls:`todo-link-input`,id:W});if(!e)return;e.focus(),e.selectionStart=e.selectionEnd=e.value.length}}function K(){if(!U)return;Hl();let e=Gl(),n=document.activeElement?.closest?.(`.todo-item`)?.dataset.id||null,{active:r,done:i,stats:a}=tc();ml.textContent=t(`todo.progressLabel`,{done:a.done,total:a.total})+(a.doing>0?t(`todo.progressDoing`,{doing:a.doing}):``),hl.style.width=a.total?`${Math.round(a.done/a.total*100)}%`:`0%`,ru(r.length),Xl(r.length,i.length);let o=Sl===`done`?i:r,s=[];if(Ul([...r,...i]),kl&&s.push(`<div class="todo-undo">
344
+ <span class="todo-undo-text">${k(t(`todo.undoBar`,{title:kl.title}))}</span>
345
+ <button class="todo-mini-btn" data-action="undo-complete" data-id="${j(kl.id)}">${k(t(`todo.undoAction`))}</button>
346
+ </div>`),Sl===`done`&&i.length>0&&s.push(`<button class="todo-clear-done" data-action="clear-completed-btn">
347
347
  ${B.trash}<span>${k(t(`todo.clearCompleted`))} (${i.length})</span>
348
- </button>`),o.length===0){let e=xl===`done`;s.push(`<div class="todo-empty">
348
+ </button>`),o.length===0){let e=Sl===`done`;s.push(`<div class="todo-empty">
349
349
  <div class="todo-empty-title">${k(t(e?`todo.emptyDone`:`todo.empty`))}</div>
350
350
  <div class="todo-empty-hint">${k(t(e?`todo.emptyDoneHint`:`todo.emptyHint`))}</div>
351
- </div>`)}else s.push(`<div class="todo-list" data-group="${xl}">${o.map(e=>su(e,xl)).join(``)}</div>`);U.innerHTML=s.join(``),e?Kl(e):n?Tu(n):ql(),Xl()}function Jl(e,t){if(!yl||!bl)return;let n=xl===`done`;yl.classList.toggle(`active`,!n),bl.classList.toggle(`active`,n),yl.setAttribute(`aria-selected`,String(!n)),bl.setAttribute(`aria-selected`,String(n)),yl.querySelector(`.todo-tab-count`).textContent=String(e),bl.querySelector(`.todo-tab-count`).textContent=String(t)}function Yl(){let e=document.querySelector(sl)?.getBoundingClientRect();return e&&e.height>0&&Number.isFinite(e.top)?e.top:window.innerHeight-cl}function Xl(){!H||!Il()||(H.style.removeProperty(`--fit-y`),requestAnimationFrame(()=>{if(!H||!Il())return;let e=Yl()-ll,t=H.getBoundingClientRect();if(!t.height)return;let n=Math.max(dl,Math.floor(e-ul));H.style.setProperty(`--todo-max-h`,`${n}px`),jl&&(H.style.height=`auto`),jl=Math.min(n,Math.max(jl,H.offsetHeight)),H.style.height=`${jl}px`;let r=Math.floor(e-t.bottom);r&&H.style.setProperty(`--fit-y`,`${r}px`)}))}function Zl(){Ql(),window.addEventListener(`resize`,Xl);let e=document.querySelector(sl);e&&typeof ResizeObserver<`u`&&(Al=new ResizeObserver(()=>Xl()),Al.observe(e))}function Ql(){window.removeEventListener(`resize`,Xl),Al?.disconnect(),Al=null}function $l(e){Dl={id:e.id,title:e.title},clearTimeout(Ol),Ol=setTimeout(()=>{Dl=null,q()},fl)}function eu(){clearTimeout(Ol),Ol=null,Dl=null}function tu(e){_l&&(e>0?(_l.textContent=e>99?`99+`:String(e),_l.style.display=``):_l.style.display=`none`)}function nu(e){return e===O.DONE?t(`todo.statusDone`):e===O.DOING?t(`todo.statusDoing`):t(`todo.statusPending`)}function ru(e){let n=t(`todo.statusTip`,{status:nu(e.status),next:nu(Ve(e.status))}),r=e.status===O.DONE?B.check:e.status===O.DOING?`<i></i>`:``;return`<button class="todo-status" data-action="cycle" data-id="${j(e.id)}"
352
- title="${j(n)}" aria-label="${j(n)}">${r}</button>`}function iu(e){let n=Pe(e);if(!n)return``;let r=t(`todo.openLinkTitle`,{host:n});return`<button class="todo-link-chip" data-action="open-link" data-id="${j(e.id)}"
353
- title="${j(r)}" aria-label="${j(r)}">${B.link}<span>${k(n)}</span></button>`}function au(e){let n=iu(e);if(e.status===O.DONE)return`<div class="todo-meta">${n}<span>${k(Re(e))}</span></div>`;let r=[];if(n&&r.push(n),Number.isFinite(e.dueAt)){let n=De(e),i=n?t(`todoTime.overdueStamp`,{date:Te(e.dueAt)}):Te(e.dueAt);r.push(`<span class="todo-due${n?` overdue`:``}">${B.alert}${k(i)}</span>`)}let i=Ne(e.createdAt);return i&&r.push(`<span>${k(i)}</span>`),r.length===0?``:`<div class="todo-meta">${r.join(`<span class="todo-sep">·</span>`)}</div>`}function ou(e){let n=wl.has(e.id),r=Sl===e.id,i=!!(e.note&&e.note.trim());if(r){let n=Hl(e.id,`note`);return`<div class="todo-note-editor">
351
+ </div>`)}else s.push(`<div class="todo-list" data-group="${Sl}">${o.map(e=>lu(e,Sl)).join(``)}</div>`);U.innerHTML=s.join(``),e?Jl(e):n?Du(n):Yl(),Ql()}function Xl(e,t){if(!bl||!xl)return;let n=Sl===`done`;bl.classList.toggle(`active`,!n),xl.classList.toggle(`active`,n),bl.setAttribute(`aria-selected`,String(!n)),xl.setAttribute(`aria-selected`,String(n)),bl.querySelector(`.todo-tab-count`).textContent=String(e),xl.querySelector(`.todo-tab-count`).textContent=String(t)}function Zl(){let e=document.querySelector(cl)?.getBoundingClientRect();return e&&e.height>0&&Number.isFinite(e.top)?e.top:window.innerHeight-ll}function Ql(){!H||!Rl()||(H.style.removeProperty(`--fit-y`),requestAnimationFrame(()=>{if(!H||!Rl())return;let e=Zl()-ul,t=H.getBoundingClientRect();if(!t.height)return;let n=Math.max(fl,Math.floor(e-dl));H.style.setProperty(`--todo-max-h`,`${n}px`),Nl&&(H.style.height=`auto`),Nl=Math.min(n,Math.max(Nl,H.offsetHeight)),H.style.height=`${Nl}px`;let r=Math.floor(e-t.bottom);r&&H.style.setProperty(`--fit-y`,`${r}px`)}))}function $l(){eu(),window.addEventListener(`resize`,Ql);let e=document.querySelector(cl);e&&typeof ResizeObserver<`u`&&(Ml=new ResizeObserver(()=>Ql()),Ml.observe(e))}function eu(){window.removeEventListener(`resize`,Ql),Ml?.disconnect(),Ml=null}function tu(e){kl={id:e.id,title:e.title},clearTimeout(Al),Al=setTimeout(()=>{kl=null,K()},pl)}function nu(){clearTimeout(Al),Al=null,kl=null}function ru(e){vl&&(e>0?(vl.textContent=e>99?`99+`:String(e),vl.style.display=``):vl.style.display=`none`)}function iu(e){return e===O.DONE?t(`todo.statusDone`):e===O.DOING?t(`todo.statusDoing`):t(`todo.statusPending`)}function au(e){let n=t(`todo.statusTip`,{status:iu(e.status),next:iu(Ve(e.status))}),r=e.status===O.DONE?B.check:e.status===O.DOING?`<i></i>`:``;return`<button class="todo-status" data-action="cycle" data-id="${j(e.id)}"
352
+ title="${j(n)}" aria-label="${j(n)}">${r}</button>`}function ou(e){let n=Pe(e);if(!n)return``;let r=t(`todo.openLinkTitle`,{host:n});return`<button class="todo-link-chip" data-action="open-link" data-id="${j(e.id)}"
353
+ title="${j(r)}" aria-label="${j(r)}">${B.link}<span>${k(n)}</span></button>`}function su(e){let n=ou(e);if(e.status===O.DONE)return`<div class="todo-meta">${n}<span>${k(Re(e))}</span></div>`;let r=[];if(n&&r.push(n),Number.isFinite(e.dueAt)){let n=De(e),i=n?t(`todoTime.overdueStamp`,{date:Te(e.dueAt)}):Te(e.dueAt);r.push(`<span class="todo-due${n?` overdue`:``}">${B.alert}${k(i)}</span>`)}let i=Ne(e.createdAt);return i&&r.push(`<span>${k(i)}</span>`),r.length===0?``:`<div class="todo-meta">${r.join(`<span class="todo-sep">·</span>`)}</div>`}function cu(e){let n=El.has(e.id),r=wl===e.id,i=!!(e.note&&e.note.trim());if(r){let n=Wl(e.id,`note`);return`<div class="todo-note-editor">
354
354
  <textarea class="todo-note-input" data-id="${j(e.id)}" rows="2"
355
355
  placeholder="${j(t(`todo.notePlaceholder`))}">${k(n===null?e.note||``:n)}</textarea>
356
356
  <div class="todo-note-editor-actions">
@@ -360,50 +360,50 @@ import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-DvmxOw8q.js"
360
360
  </div>`}return i?`<button class="todo-note-toggle${n?` open`:``}" data-action="toggle-note" data-id="${j(e.id)}">
361
361
  ${B.chevron}<span>${k(t(`todo.noteToggle`))}</span>
362
362
  </button>
363
- ${n?`<div class="todo-note">${k(e.note)}</div>`:``}`:``}function su(e,n){let r=e.status===O.DONE,i=W===e.id,a=[`todo-item`];e.status===O.DOING&&a.push(`doing`),r&&a.push(`done`),e.priority&&a.push(`prio-${e.priority}`),Cl===e.id&&a.push(`editing-due`);let o=Hl(e.id,`title`),s=i?`<input type="text" class="todo-edit-input" data-id="${j(e.id)}" value="${j(o===null?e.title:o)}" />`:`<div class="todo-name">${k(e.title)}</div>`,c=Hl(e.id,`due`),l=Cl===e.id?`<div class="todo-due-editor">
364
- <input type="date" class="todo-due-input" data-id="${j(e.id)}" value="${j(c===null?lu(e.dueAt):c)}" />
363
+ ${n?`<div class="todo-note">${k(e.note)}</div>`:``}`:``}function lu(e,n){let r=e.status===O.DONE,i=Cl===e.id,a=[`todo-item`];e.status===O.DOING&&a.push(`doing`),r&&a.push(`done`),e.priority&&a.push(`prio-${e.priority}`),Tl===e.id&&a.push(`editing-due`);let o=Wl(e.id,`title`),s=i?`<input type="text" class="todo-edit-input" data-id="${j(e.id)}" value="${j(o===null?e.title:o)}" />`:`<div class="todo-name">${k(e.title)}</div>`,c=Wl(e.id,`due`),l=Tl===e.id?`<div class="todo-due-editor">
364
+ <input type="date" class="todo-due-input" data-id="${j(e.id)}" value="${j(c===null?du(e.dueAt):c)}" />
365
365
  <button class="todo-mini-btn ghost" data-action="due-clear" data-id="${j(e.id)}">${k(t(`todo.clearDue`))}</button>
366
- </div>`:``,u=Hl(e.id,`link`),d=G===e.id?`<div class="todo-link-editor">
366
+ </div>`:``,u=Wl(e.id,`link`),d=W===e.id?`<div class="todo-link-editor">
367
367
  <input type="text" class="todo-link-input" data-id="${j(e.id)}" autocomplete="off"
368
368
  placeholder="${j(t(`todo.linkPlaceholder`))}" value="${j(u===null?e.link||``:u)}" />
369
369
  <button class="todo-mini-btn ghost" data-action="link-cancel" data-id="${j(e.id)}">${k(t(`todo.noteCancel`))}</button>
370
- </div>`:``,f=n===`active`?` draggable="true"`:``,p=W===e.id||Sl===e.id||Cl===e.id||G===e.id,m=`
370
+ </div>`:``,f=n===`active`?` draggable="true"`:``,p=Cl===e.id||wl===e.id||Tl===e.id||W===e.id,m=`
371
371
  <div class="todo-item-actions">
372
- ${r?`<button class="todo-act" data-action="restore" data-id="${j(e.id)}" title="${j(t(`todo.restoreTo`,{status:nu(He(e))}))}" aria-label="${j(t(`todo.restoreTo`,{status:nu(He(e))}))}">${B.undo}</button>`:``}
372
+ ${r?`<button class="todo-act" data-action="restore" data-id="${j(e.id)}" title="${j(t(`todo.restoreTo`,{status:iu(He(e))}))}" aria-label="${j(t(`todo.restoreTo`,{status:iu(He(e))}))}">${B.undo}</button>`:``}
373
373
  <button class="todo-act" data-action="edit-title" data-id="${j(e.id)}" title="${j(t(`todo.editItem`))}" aria-label="${j(t(`todo.editItem`))}">${B.edit}</button>
374
374
  <button class="todo-act" data-action="copy-item" data-id="${j(e.id)}" title="${j(t(`todo.copyItem`))}" aria-label="${j(t(`todo.copyItem`))}">${B.copy}</button>
375
375
  <button class="todo-act" data-action="fill-item" data-id="${j(e.id)}" title="${j(t(`todo.fillInput`))}" aria-label="${j(t(`todo.fillInput`))}">${B.fill}</button>
376
376
  <button class="todo-act" data-action="row-more" data-id="${j(e.id)}" title="${j(t(`todo.more`))}" aria-label="${j(t(`todo.more`))}">${B.more}</button>
377
377
  </div>`;return`<div class="${a.join(` `)}" data-id="${j(e.id)}" data-group="${n}"${f} tabindex="0" data-priority="${j(e.priority||``)}">
378
- ${ru(e)}
378
+ ${au(e)}
379
379
  <div class="todo-main">
380
380
  ${s}
381
- ${ou(e)}
381
+ ${cu(e)}
382
382
  ${l}
383
383
  ${d}
384
- ${au(e)}
384
+ ${su(e)}
385
385
  </div>
386
386
  ${p?``:m}
387
- </div>`}function cu(){let e=U.querySelector(`.todo-edit-input[data-id="${W}"]`);e&&(e.focus(),e.selectionStart=e.selectionEnd=e.value.length)}function lu(e){if(!Number.isFinite(e))return``;let t=new Date(e);if(isNaN(t.getTime()))return``;let n=e=>e<10?`0`+e:String(e);return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())}`}function J(e,n){Promise.resolve(e).then(e=>{if(e===!0||e&&e.ok===!0){n&&A(n,`success`);return}A(t(e&&e.reason===`invalid`?`todo.linkInvalid`:`todo.saveFailed`),`error`)})}function uu(e){let n=e&&e.link;if(!n||!Ee(n)){A(t(`todo.linkInvalid`),`error`);return}try{chrome.tabs.create({url:n})}catch(e){r.warn(`[Todo] open link failed:`,e),A(t(`todo.copyFailed`),`error`)}}function du(e){let t=e.target.closest(`[data-action]`);if(!t)return;let n=t.dataset.action,r=t.dataset.id;switch(n){case`close`:e.stopPropagation(),zl();return;case`fill-item`:e.stopPropagation(),$u(r);return;case`copy-item`:e.stopPropagation(),ed(r);return;case`header-more`:e.stopPropagation(),Ku(t);return;case`add`:e.stopPropagation(),Nu();return;case`switch-tab`:pu(t.dataset.tab);return;case`undo-complete`:e.stopPropagation(),gu(r);return;case`restore`:e.stopPropagation(),hu(r);return;case`open-link`:e.stopPropagation(),uu(fu(r));return;case`clear-completed-btn`:e.stopPropagation(),_u();return;case`cycle`:e.stopPropagation(),J(oc(r));return;case`toggle-note`:e.stopPropagation(),wl.has(r)?wl.delete(r):wl.add(r),q();return;case`edit-title`:e.stopPropagation(),Lu(),W=r,q();return;case`row-more`:e.stopPropagation(),Gu(t,r);return;case`note-save`:e.stopPropagation(),Pu(r);return;case`note-cancel`:e.stopPropagation(),Sl=null,K(r),q();return;case`due-clear`:e.stopPropagation(),Cl=null,K(r),J(ic(r,{dueAt:null}));return;case`link-cancel`:e.stopPropagation(),Iu(r);return;default:return}}function fu(e){let{active:t,done:n}=ec();return[...t,...n].find(t=>t.id===e)||null}function pu(e){let t=e===`done`?`done`:`active`;t!==xl&&(xl=t,Lu(),q())}function mu(e){let t=fu(e);t&&($l(t),J(ac(e,O.DONE)))}function hu(e){let n=fu(e);if(!n)return;let r=He(n);eu(),J(sc(e),t(`todo.restoredToast`,{status:nu(r)}))}function gu(e){hu(e)}async function _u(){let{done:e}=ec();e.length!==0&&await Ru(t(`todo.clearCompletedConfirmMsg`,{n:e.length}),t(`todo.clearCompletedConfirmTitle`))&&J(fc(),t(`todo.clearedToast`))}function vu(e){if((e.key===`ArrowUp`||e.key===`ArrowDown`)&&!e.target.closest?.(`input, textarea, [contenteditable="true"]`)&&e.target.closest?.(`.todo-item`)){e.preventDefault(),wu(e.key===`ArrowDown`?1:-1);return}if(e.target===hl){e.key===`Enter`?(e.preventDefault(),Nu()):e.key===`Escape`&&(e.stopPropagation(),hl.value=``,Il()&&zl());return}if(e.target.classList?.contains(`todo-edit-input`)){let t=e.target.dataset.id;if(e.key===`Enter`){e.preventDefault(),e.stopPropagation();let n=e.target.value.trim();if(W=null,!n){K(t),q();return}K(t),J(ic(t,{title:n}))}else e.key===`Escape`&&(e.stopPropagation(),W=null,K(e.target.dataset.id),q());return}if(e.target.classList?.contains(`todo-note-input`)){e.key===`Enter`&&(e.metaKey||e.ctrlKey)?(e.preventDefault(),e.stopPropagation(),Pu(e.target.dataset.id)):e.key===`Escape`&&(e.stopPropagation(),Sl=null,K(e.target.dataset.id),q());return}if(e.target.classList?.contains(`todo-link-input`)){let t=e.target.dataset.id;e.key===`Enter`?(e.preventDefault(),e.stopPropagation(),Fu(t,e.target.value)):e.key===`Escape`&&(e.stopPropagation(),Iu(t))}}var yu={KeyT:()=>Ll(),KeyA:()=>Eu(),KeyB:e=>Du(e),KeyL:e=>Ou(e),KeyD:e=>ku(e),KeyP:e=>Au(e)},bu=new Set([`KeyT`,`KeyA`]);function xu(e){if(!e.altKey||e.shiftKey||e.ctrlKey||e.metaKey)return;let t=yu[e.code];if(!t)return;if(bu.has(e.code)){e.preventDefault(),t();return}let n=Cu();n&&(e.preventDefault(),t(n))}function Su(){return U?Array.from(U.querySelectorAll(`.todo-item`)):[]}function Cu(){if(!Il())return null;let e=document.activeElement?.closest?.(`.todo-item`);if(e?.dataset.id&&U.contains(e))return e.dataset.id;let t=Su();return kl&&t.some(e=>e.dataset.id===kl)?kl:t[0]?.dataset.id||null}function wu(e){let t=Su();if(t.length===0)return;let n=t.indexOf(document.activeElement?.closest?.(`.todo-item`)),r=n===-1?e>0?t[0]:t[t.length-1]:t[Math.max(0,Math.min(t.length-1,n+e))];r&&r.focus()}function Tu(e){let t=Su().find(t=>t.dataset.id===e);t&&t.focus()}function Eu(){if(Il()){hl.focus();return}Rl()}function Du(e){Sl=e,wl.add(e),q()}function Ou(e){G=e,q()}function ku(e){let t=fu(e);t&&(t.status===O.DONE?hu(e):mu(e))}function Au(e){let t=fu(e);t&&J(cc(e,Se(t.priority)))}function ju(e){if(e.target.classList?.contains(`todo-link-input`)){let t=e.target.dataset.id;if(!G||G!==t)return;Fu(t,e.target.value);return}if(!e.target.classList?.contains(`todo-due-input`))return;let t=e.target.dataset.id,n=e.target.value;if(Cl=null,K(t),!n){J(ic(t,{dueAt:null}));return}let r=new Date(n+`T00:00:00`);J(ic(t,{dueAt:isNaN(r.getTime())?null:r.getTime()}))}function Mu(e){if(e.target?.classList?.contains(`todo-link-input`)){let t=e.target.dataset.id;if(!G||G!==t)return;Fu(t,e.target.value);return}if(!e.target?.classList?.contains(`todo-edit-input`))return;let n=e.target.dataset.id;if(!W||W!==n)return;let r=e.target.value.trim();if(W=null,!r){K(n),q();return}K(n),ic(n,{title:r}).then(e=>{e?q():A(t(`todo.saveFailed`),`error`)})}async function Nu(){let e=hl.value.trim();e&&(hl.value=``,xl===`done`&&(xl=`active`),await rc(e)||A(t(`todo.saveFailed`),`error`),hl.focus())}function Pu(e){let t=U.querySelector(`.todo-note-input[data-id="${j(e)}"]`),n=t?t.value:``;Sl=null,wl.delete(e),K(e),J(ic(e,{note:n}))}function Fu(e,n){let r=!!fu(e)?.link;G=null,K(e);let i=String(n||``).trim();J(lc(e,i),t(i?`todo.linkSavedToast`:r?`todo.linkRemovedToast`:`todo.linkSavedToast`))}function Iu(e){G=null,K(e),q()}function Lu(){let e=W||Sl||Cl||G;W=null,Sl=null,Cl=null,G=null,K(),e&&q()}async function Ru(e,t){return typeof window<`u`&&typeof window.showCustomConfirm==`function`?!!await window.showCustomConfirm(e,t):!1}function zu(){return vl||(vl=document.createElement(`div`),vl.className=`todo-menu`,document.body.appendChild(vl),vl.addEventListener(`click`,e=>{let t=e.target.closest(`[data-priority-value]`);if(t){let e=t.dataset.menuId,n=t.dataset.priorityValue||null;Bu(),J(cc(e,n));return}let n=e.target.closest(`[data-menu-action]`);if(!n)return;let{menuAction:r,menuId:i}=n.dataset;Bu(),Zu(r,i)}),vl)}function Bu(){vl&&=(vl.remove(),null)}function Vu(e){return e?`<kbd class="todo-menu-kbd">${k(e)}</kbd>`:``}function Hu(e,n){if(e.swatches){let r=[[``,t(`todo.priorityNone`)],[ze.LOW,t(`todo.priorityLow`)],[ze.MEDIUM,t(`todo.priorityMedium`)],[ze.HIGH,t(`todo.priorityHigh`)]];return`<div class="todo-menu-row">
387
+ </div>`}function uu(){let e=U.querySelector(`.todo-edit-input[data-id="${Cl}"]`);e&&(e.focus(),e.selectionStart=e.selectionEnd=e.value.length)}function du(e){if(!Number.isFinite(e))return``;let t=new Date(e);if(isNaN(t.getTime()))return``;let n=e=>e<10?`0`+e:String(e);return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())}`}function q(e,n){Promise.resolve(e).then(e=>{if(e===!0||e&&e.ok===!0){n&&A(n,`success`);return}A(t(e&&e.reason===`invalid`?`todo.linkInvalid`:`todo.saveFailed`),`error`)})}function fu(e){let n=e&&e.link;if(!n||!Ee(n)){A(t(`todo.linkInvalid`),`error`);return}try{chrome.tabs.create({url:n})}catch(e){r.warn(`[Todo] open link failed:`,e),A(t(`todo.copyFailed`),`error`)}}function pu(e){let t=e.target.closest(`[data-action]`);if(!t)return;let n=t.dataset.action,r=t.dataset.id;switch(n){case`close`:e.stopPropagation(),Vl();return;case`fill-item`:e.stopPropagation(),td(r);return;case`copy-item`:e.stopPropagation(),nd(r);return;case`header-more`:e.stopPropagation(),Ju(t);return;case`add`:e.stopPropagation(),Fu();return;case`switch-tab`:hu(t.dataset.tab);return;case`undo-complete`:e.stopPropagation(),vu(r);return;case`restore`:e.stopPropagation(),_u(r);return;case`open-link`:e.stopPropagation(),fu(mu(r));return;case`clear-completed-btn`:e.stopPropagation(),yu();return;case`cycle`:e.stopPropagation(),q(sc(r));return;case`toggle-note`:e.stopPropagation(),El.has(r)?El.delete(r):El.add(r),K();return;case`edit-title`:e.stopPropagation(),zu(),Cl=r,K();return;case`row-more`:e.stopPropagation(),qu(t,r);return;case`note-save`:e.stopPropagation(),Iu(r);return;case`note-cancel`:e.stopPropagation(),wl=null,G(r),K();return;case`due-clear`:e.stopPropagation(),Tl=null,G(r),q(ac(r,{dueAt:null}));return;case`link-cancel`:e.stopPropagation(),Ru(r);return;default:return}}function mu(e){let{active:t,done:n}=tc();return[...t,...n].find(t=>t.id===e)||null}function hu(e){let t=e===`done`?`done`:`active`;t!==Sl&&(Sl=t,zu(),K())}function gu(e){let t=mu(e);t&&(tu(t),q(oc(e,O.DONE)))}function _u(e){let n=mu(e);if(!n)return;let r=He(n);nu(),q(cc(e),t(`todo.restoredToast`,{status:iu(r)}))}function vu(e){_u(e)}async function yu(){let{done:e}=tc();e.length!==0&&await Bu(t(`todo.clearCompletedConfirmMsg`,{n:e.length}),t(`todo.clearCompletedConfirmTitle`))&&q(pc(),t(`todo.clearedToast`))}function bu(e){if((e.key===`ArrowUp`||e.key===`ArrowDown`)&&!e.target.closest?.(`input, textarea, [contenteditable="true"]`)&&e.target.closest?.(`.todo-item`)){e.preventDefault(),Eu(e.key===`ArrowDown`?1:-1);return}if(e.target===gl){e.key===`Enter`?(e.preventDefault(),Fu()):e.key===`Escape`&&(e.stopPropagation(),gl.value=``,Rl()&&Vl());return}if(e.target.classList?.contains(`todo-edit-input`)){let t=e.target.dataset.id;if(e.key===`Enter`){e.preventDefault(),e.stopPropagation();let n=e.target.value.trim();if(Cl=null,!n){G(t),K();return}G(t),q(ac(t,{title:n}))}else e.key===`Escape`&&(e.stopPropagation(),Cl=null,G(e.target.dataset.id),K());return}if(e.target.classList?.contains(`todo-note-input`)){e.key===`Enter`&&(e.metaKey||e.ctrlKey)?(e.preventDefault(),e.stopPropagation(),Iu(e.target.dataset.id)):e.key===`Escape`&&(e.stopPropagation(),wl=null,G(e.target.dataset.id),K());return}if(e.target.classList?.contains(`todo-link-input`)){let t=e.target.dataset.id;e.key===`Enter`?(e.preventDefault(),e.stopPropagation(),Lu(t,e.target.value)):e.key===`Escape`&&(e.stopPropagation(),Ru(t))}}var xu={KeyT:()=>zl(),KeyA:()=>Ou(),KeyB:e=>ku(e),KeyL:e=>Au(e),KeyD:e=>ju(e),KeyP:e=>Mu(e)},Su=new Set([`KeyT`,`KeyA`]);function Cu(e){if(!e.altKey||e.shiftKey||e.ctrlKey||e.metaKey)return;let t=xu[e.code];if(!t)return;if(Su.has(e.code)){e.preventDefault(),t();return}let n=Tu();n&&(e.preventDefault(),t(n))}function wu(){return U?Array.from(U.querySelectorAll(`.todo-item`)):[]}function Tu(){if(!Rl())return null;let e=document.activeElement?.closest?.(`.todo-item`);if(e?.dataset.id&&U.contains(e))return e.dataset.id;let t=wu();return jl&&t.some(e=>e.dataset.id===jl)?jl:t[0]?.dataset.id||null}function Eu(e){let t=wu();if(t.length===0)return;let n=t.indexOf(document.activeElement?.closest?.(`.todo-item`)),r=n===-1?e>0?t[0]:t[t.length-1]:t[Math.max(0,Math.min(t.length-1,n+e))];r&&r.focus()}function Du(e){let t=wu().find(t=>t.dataset.id===e);t&&t.focus()}function Ou(){if(Rl()){gl.focus();return}Bl()}function ku(e){wl=e,El.add(e),K()}function Au(e){W=e,K()}function ju(e){let t=mu(e);t&&(t.status===O.DONE?_u(e):gu(e))}function Mu(e){let t=mu(e);t&&q(lc(e,Se(t.priority)))}function Nu(e){if(e.target.classList?.contains(`todo-link-input`)){let t=e.target.dataset.id;if(!W||W!==t)return;Lu(t,e.target.value);return}if(!e.target.classList?.contains(`todo-due-input`))return;let t=e.target.dataset.id,n=e.target.value;if(Tl=null,G(t),!n){q(ac(t,{dueAt:null}));return}let r=new Date(n+`T00:00:00`);q(ac(t,{dueAt:isNaN(r.getTime())?null:r.getTime()}))}function Pu(e){if(e.target?.classList?.contains(`todo-link-input`)){let t=e.target.dataset.id;if(!W||W!==t)return;Lu(t,e.target.value);return}if(!e.target?.classList?.contains(`todo-edit-input`))return;let n=e.target.dataset.id;if(!Cl||Cl!==n)return;let r=e.target.value.trim();if(Cl=null,!r){G(n),K();return}G(n),ac(n,{title:r}).then(e=>{e?K():A(t(`todo.saveFailed`),`error`)})}async function Fu(){let e=gl.value.trim();e&&(gl.value=``,Sl===`done`&&(Sl=`active`),await ic(e)||A(t(`todo.saveFailed`),`error`),gl.focus())}function Iu(e){let t=U.querySelector(`.todo-note-input[data-id="${j(e)}"]`),n=t?t.value:``;wl=null,El.delete(e),G(e),q(ac(e,{note:n}))}function Lu(e,n){let r=!!mu(e)?.link;W=null,G(e);let i=String(n||``).trim();q(uc(e,i),t(i?`todo.linkSavedToast`:r?`todo.linkRemovedToast`:`todo.linkSavedToast`))}function Ru(e){W=null,G(e),K()}function zu(){let e=Cl||wl||Tl||W;Cl=null,wl=null,Tl=null,W=null,G(),e&&K()}async function Bu(e,t){return typeof window<`u`&&typeof window.showCustomConfirm==`function`?!!await window.showCustomConfirm(e,t):!1}function Vu(){return yl||(yl=document.createElement(`div`),yl.className=`todo-menu`,document.body.appendChild(yl),yl.addEventListener(`click`,e=>{let t=e.target.closest(`[data-priority-value]`);if(t){let e=t.dataset.menuId,n=t.dataset.priorityValue||null;Hu(),q(lc(e,n));return}let n=e.target.closest(`[data-menu-action]`);if(!n)return;let{menuAction:r,menuId:i}=n.dataset;Hu(),$u(r,i)}),yl)}function Hu(){yl&&=(yl.remove(),null)}function Uu(e){return e?`<kbd class="todo-menu-kbd">${k(e)}</kbd>`:``}function Wu(e,n){if(e.swatches){let r=[[``,t(`todo.priorityNone`)],[ze.LOW,t(`todo.priorityLow`)],[ze.MEDIUM,t(`todo.priorityMedium`)],[ze.HIGH,t(`todo.priorityHigh`)]];return`<div class="todo-menu-row">
388
388
  <span class="todo-menu-row-label">${k(e.label)}</span>
389
389
  ${r.map(([r,i])=>`
390
390
  <button type="button" class="todo-swatch${r?` ${r}`:``}${e.current===r?` active`:``}"
391
391
  data-priority-value="${j(r)}" data-menu-id="${j(n)}"
392
392
  title="${j(t(`todo.priorityTitle`,{level:i}))}"
393
393
  aria-label="${j(i)}"></button>`).join(``)}
394
- ${Vu(e.shortcut)}
394
+ ${Uu(e.shortcut)}
395
395
  </div>`}return`${e.divider?`<div class="todo-menu-sep"></div>`:``}<button type="button" data-menu-action="${j(e.action)}" data-menu-id="${j(n||``)}"
396
396
  class="todo-menu-item${e.danger?` danger`:``}">
397
- ${e.icon||``}<span>${k(e.label)}</span>${Vu(e.shortcut)}
398
- </button>`}function Uu(e,t,n){let r=zu();r.innerHTML=t.map((e,t)=>t===0&&e.divider?{...e,divider:!1}:e).map(e=>Hu(e,n)).join(``);let i=e.getBoundingClientRect(),a=r.offsetWidth||168,o=r.offsetHeight||132,s=Math.min(i.right-a,window.innerWidth-a-8);s=Math.max(8,s);let c=i.bottom+4;c+o>window.innerHeight-8&&(c=Math.max(8,i.top-o-4)),r.style.left=`${s}px`,r.style.top=`${c}px`}function Wu(e){if(e.status===O.DONE){let n=He(e),r=[{action:`restore`,label:t(`todo.restoreTo`,{status:nu(n)}),icon:B.undo,shortcut:`Alt+D`,divider:!0}];return n!==O.PENDING&&r.push({action:`set-pending`,label:t(`todo.backToPending`),icon:B.circle}),r}return e.status===O.DOING?[{action:`set-done`,label:t(`todo.markDone`),icon:B.check,shortcut:`Alt+D`,divider:!0},{action:`set-pending`,label:t(`todo.backToPending`),icon:B.circle}]:[{action:`set-doing`,label:t(`todo.startDoing`),icon:B.play,divider:!0},{action:`set-done`,label:t(`todo.markDone`),icon:B.check,shortcut:`Alt+D`}]}function Gu(e,n){let r=fu(n);r&&Uu(e,[...Wu(r),{swatches:!0,label:t(`todo.priority`),current:r.priority||``,shortcut:`Alt+P`,divider:!0},{action:`edit-title`,label:t(`todo.editTitleAction`),icon:B.edit,divider:!0},{action:`edit-note`,label:r.note?t(`todo.editNote`):t(`todo.addNote`),icon:B.note,shortcut:`Alt+B`},{action:`set-due`,label:t(`todo.setDue`),icon:B.calendar},{action:`edit-link`,label:r.link?t(`todo.editLink`):t(`todo.addLink`),icon:B.link,shortcut:`Alt+L`},{action:`delete`,label:t(`todo.delete`),icon:B.trash,danger:!0,divider:!0}],n)}function Ku(e){let t=qu();t.length!==0&&Uu(e,t,``)}function qu(){return[{action:`stats`,label:t(`todo.statsEntry`),icon:B.chart,divider:!0},{action:`export-options`,label:t(`todo.exportEntry`),icon:B.download,divider:!0},{action:`import-options`,label:t(`todo.importEntry`),icon:B.upload}]}async function Ju(){let{active:e,done:t}=ec(),n=await Uc({counts:{all:e.length+t.length,active:e.length,done:t.length}});n&&Yu(n.scope,n.format)}function Yu(e,n){let{active:i,done:a}=ec(),o=[...i,...a];if(xe(o,e).length===0){A(t(`todo.exportEmptyToast`),`info`);return}try{A(t(`todo.exportedToast`,{name:Sc(o,{scope:e,format:n})}),`success`)}catch(e){r.error(`[Todo] export failed:`,e),A(t(`todo.exportFailedToast`),`error`)}}async function Xu(){let e=await Cc();if(!e)return;let n=await wc(e);if(!n.ok){A(t(n.reason===`json`?`todo.importJsonError`:`todo.importFormatError`),`error`);return}let{active:r,done:i}=ec(),a=await Wc({count:n.todos.length,existing:r.length+i.length});if(!a)return;xl=`active`,q();let o=await pc(n.todos,a);if(!o.ok){A(t(o.reason===`empty`?`todo.importEmptyToast`:`todo.importFailedToast`),`error`);return}if(o.added===0){A(t(`todo.importNothingNewToast`,{skipped:o.skipped}),`info`);return}A(t(`todo.importedToast`,{added:o.added,skipped:o.skipped}),`success`)}async function Zu(e,n){let r=fu(n);switch(e){case`set-doing`:J(ac(n,O.DOING));return;case`set-pending`:J(ac(n,O.PENDING));return;case`set-done`:mu(n);return;case`restore`:hu(n);return;case`edit-title`:W=n,q();return;case`edit-note`:Sl=n,wl.add(n),q(),setTimeout(()=>{let e=U.querySelector(`.todo-note-input[data-id="${n}"]`);e&&(e.focus(),e.selectionStart=e.selectionEnd=e.value.length)},30);return;case`set-due`:Cl=n,q(),setTimeout(()=>{let e=U.querySelector(`.todo-due-input[data-id="${n}"]`);e&&e.focus()},30);return;case`edit-link`:Ou(n);return;case`stats`:al();return;case`export-options`:Ju();return;case`import-options`:Xu();return;case`delete`:await Ru(t(`todo.deleteConfirmMsg`,{title:r?.title||``}),t(`todo.deleteConfirmTitle`))&&J(uc(n),t(`todo.deletedToast`));return;default:}}function Qu(e,t={}){let{active:n,done:r}=ec(),i=[...n,...r].find(t=>t.id===e);return i?Le(i,t):``}function $u(e){let n=Qu(e);if(!n){A(t(`todo.emptyDigestToast`),`info`);return}let r=document.getElementById(`userInput`);if(!r){A(t(`todo.noInputToast`),`error`);return}let i=r.value.replace(/\s+$/,``);r.value=i?`${i}\n\n${n}`:n,r.dispatchEvent(new Event(`input`,{bubbles:!0})),r.focus(),r.selectionStart=r.selectionEnd=r.value.length,rt(),zl(),A(t(`todo.filledToast`),`success`)}function ed(e){let n=Qu(e,{plain:!0});if(!n){A(t(`todo.emptyDigestToast`),`info`);return}td(n,t(`todo.copiedToast`))}function td(e,n){try{navigator.clipboard.writeText(e).then(()=>{A(n,`success`)}).catch(e=>{r.warn(`[Todo] copy failed:`,e),A(t(`todo.copyFailed`),`error`)})}catch(e){r.warn(`[Todo] clipboard unavailable:`,e),A(t(`todo.copyFailed`),`error`)}}function nd(e){let t=e.target.closest?.(`.todo-item[draggable="true"]`);if(!t)return;let n=t.closest(`.todo-list[data-group="active"]`);if(!n)return;let r=Array.from(n.querySelectorAll(`.todo-item`));Tl={id:t.dataset.id,from:r.indexOf(t),list:n},t.classList.add(`dragging`);let{active:i,done:a}=ec(),o=[...i,...a].find(e=>e.id===t.dataset.id);try{e.dataTransfer.effectAllowed=`copyMove`,e.dataTransfer.setData(`text/plain`,Le(o)||t.dataset.id)}catch{}}function rd(e){if(!Tl)return;e.preventDefault();let t=Tl.list;if(!t||!t.isConnected)return;let n=Array.from(t.querySelectorAll(`.todo-item`)).filter(e=>!e.classList.contains(`dragging`)),r=n.length;for(let t=0;t<n.length;t++){let i=n[t].getBoundingClientRect();if(e.clientY<i.top+i.height/2){r=t;break}}let i=id();r>=n.length?t.appendChild(i):n[r].before(i)}function id(){let e=U.querySelector(`.todo-insert`);return e||(e=document.createElement(`div`),e.className=`todo-insert`,e)}function ad(e){if(!Tl)return;e.preventDefault();let t=Tl.list,n=U.querySelector(`.todo-insert`),r=Tl.from;if(n&&t){let e=Array.from(t.querySelectorAll(`.todo-item`)).filter(e=>!e.classList.contains(`dragging`)),i=e.findIndex(e=>n.compareDocumentPosition(e)&Node.DOCUMENT_POSITION_FOLLOWING);r=i===-1?e.length:i}let i=Tl.from;od(),i!==r&&J(dc(i,r))}function od(){Tl=null,U?.querySelectorAll(`.todo-item.dragging`).forEach(e=>e.classList.remove(`dragging`)),U?.querySelector(`.todo-insert`)?.remove()}var sd=`—`,cd=[{labelKey:`versionInfo.website`,url:`https://xiweicheng.github.io/ai-helper/`,icon:`<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 17.93c-3.95-.49-7-3.85-7-7.93 0-.62.08-1.21.21-1.79L9 15v1c0 1.1.9 2 2 2v1.93zm6.9-2.54c-.26-.81-1-1.39-1.9-1.39h-1v-3c0-.55-.45-1-1-1H8v-2h2c.55 0 1-.45 1-1V7h2c1.1 0 2-.9 2-2v-.41c2.93 1.19 5 4.06 5 7.41 0 2.08-.8 3.97-2.1 5.39z"/></svg>`},{labelKey:`versionInfo.discussions`,url:`https://github.com/xiweicheng/ai-helper/discussions`,icon:`<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2z"/></svg>`},{labelKey:`versionInfo.reportIssue`,url:`https://github.com/xiweicheng/ai-helper/issues/new`,icon:`<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M20 8h-2.81c-.45-.78-1.07-1.45-1.82-1.96L17 4.41 15.59 3l-2.17 2.17C12.96 5.06 12.49 5 12 5c-.49 0-.96.06-1.41.17L8.41 3 7 4.41l1.62 1.63C7.88 6.55 7.26 7.22 6.81 8H4v2h2.09c-.05.33-.09.66-.09 1v1H4v2h2v1c0 .34.04.67.09 1H4v2h2.81c1.04 1.79 2.97 3 5.19 3s4.15-1.21 5.19-3H20v-2h-2.09c.05-.33.09-.66.09-1v-1h2v-2h-2v-1c0-.34-.04-.67-.09-1H20V8zm-6 8h-4v-2h4v2zm0-4h-4v-2h4v2z"/></svg>`},{labelKey:`versionInfo.githubRepo`,url:`https://github.com/xiweicheng/ai-helper`,icon:`<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M12 .5C5.73.5.5 5.73.5 12c0 5.08 3.29 9.39 7.86 10.91.58.11.79-.25.79-.56 0-.28-.01-1.02-.02-2-3.2.7-3.88-1.54-3.88-1.54-.52-1.33-1.28-1.69-1.28-1.69-1.04-.71.08-.7.08-.7 1.15.08 1.76 1.19 1.76 1.19 1.03 1.76 2.7 1.25 3.36.96.1-.75.4-1.25.72-1.54-2.55-.29-5.24-1.28-5.24-5.68 0-1.26.45-2.28 1.19-3.09-.12-.29-.52-1.46.11-3.05 0 0 .97-.31 3.18 1.18a11.1 11.1 0 012.9-.39c.98 0 1.97.13 2.9.39 2.2-1.49 3.17-1.18 3.17-1.18.63 1.59.23 2.76.11 3.05.74.81 1.19 1.83 1.19 3.09 0 4.41-2.69 5.38-5.25 5.67.41.35.78 1.05.78 2.12 0 1.53-.01 2.76-.01 3.14 0 .31.21.68.8.56A11.51 11.51 0 0023.5 12C23.5 5.73 18.27.5 12 .5z"/></svg>`},{labelKey:`versionInfo.giteeRepo`,url:`https://gitee.com/xiweicheng/ai-helper`,icon:`<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M11.984 0A12 12 0 000 12a12 12 0 0012 12 12 12 0 0012-12A12 12 0 0012 0zm6.09 5.333c.328 0 .593.266.592.593v1.482a.594.594 0 01-.593.592H9.777c-.982 0-1.778.796-1.778 1.778v5.63c0 .327.266.592.593.592h5.63c.982 0 1.778-.796 1.778-1.778v-.296a.593.593 0 00-.592-.593h-4.15a.592.592 0 01-.592-.592v-1.482a.593.593 0 01.593-.592h6.815c.327 0 .593.265.593.592v3.408a4 4 0 01-4 4H8.444a3.556 3.556 0 01-3.555-3.556V8.89a3.556 3.556 0 013.555-3.556h9.63z"/></svg>`}];function ld(e){let t=e=>typeof e==`string`?e.trim():``,n=e&&typeof e==`object`?e:{};return{version:t(n.version),tag:t(n.tag),commitId:t(n.commitId),publishedAt:t(n.publishedAt)}}function ud(e){if(!e)return sd;let t=Date.parse(e);return Number.isNaN(t)?sd:new Date(t).toLocaleString()}function dd(e){let n=ld(pt),r=[{label:t(`versionInfo.version`),value:n.version?`v${n.version}`:sd},{label:t(`versionInfo.tag`),value:n.tag||sd},{label:t(`versionInfo.commit`),value:n.commitId?n.commitId.slice(0,8):sd,title:n.commitId,mono:!0},{label:t(`versionInfo.publishedAt`),value:ud(n.publishedAt)}];e.textContent=``;for(let t of r){let n=document.createElement(`div`);n.className=`version-info-row`;let r=document.createElement(`div`);r.className=`version-info-label`,r.textContent=t.label;let i=document.createElement(`div`);i.className=t.mono?`version-info-value mono`:`version-info-value`,i.textContent=t.value,t.title&&(i.title=t.title),n.appendChild(r),n.appendChild(i),e.appendChild(n)}}function fd(e){e.textContent=``;for(let n of cd){let r=document.createElement(`div`);r.className=`version-info-link`,r.title=n.url;let i=document.createElement(`span`);i.className=`version-info-link-icon`,i.innerHTML=n.icon;let a=document.createElement(`span`);a.className=`version-info-link-label`,a.textContent=t(n.labelKey);let o=document.createElement(`span`);o.className=`version-info-link-arrow`,o.textContent=`↗`,r.appendChild(i),r.appendChild(a),r.appendChild(o),r.addEventListener(`click`,()=>{chrome.tabs.create({url:n.url})}),e.appendChild(r)}}function pd(){let e=ld(pt);return[`AI Helper v${e.version||sd}`,`${t(`versionInfo.tag`)}: ${e.tag||sd}`,`${t(`versionInfo.commit`)}: ${e.commitId||sd}`,`${t(`versionInfo.publishedAt`)}: ${ud(e.publishedAt)}`].join(`
399
- `)}function md(){let e=document.getElementById(`versionInfoBtn`),n=document.getElementById(`versionInfoModal`),r=document.getElementById(`versionInfoCloseBtn`),i=document.getElementById(`versionInfoCopyBtn`),a=document.getElementById(`versionInfoList`),o=document.getElementById(`versionInfoLinks`);if(!e||!n||!a)return;let s=()=>{n.style.display=`none`};e.addEventListener(`click`,e=>{e.stopPropagation();let t=document.getElementById(`headerMoreDropdown`);t&&t.classList.remove(`show`),dd(a),o&&fd(o),n.style.display=`flex`}),r&&r.addEventListener(`click`,s),n.addEventListener(`click`,e=>{e.target===n&&s()}),document.addEventListener(`keydown`,e=>{e.key===`Escape`&&n.style.display===`flex`&&s()}),i&&i.addEventListener(`click`,async()=>{try{await navigator.clipboard.writeText(pd()),A(t(`common.copySuccess`),`success`)}catch{A(t(`common.copyFailed`),`error`)}})}var hd=null;function gd(){if(!hd)return;hd.classList.remove(`open`);let e=hd.parentElement?hd.parentElement.querySelector(`.section-select-row`):null;e&&e.classList.remove(`open`),hd=null}function _d(){return`<input type="search" class="section-select-search" placeholder="${t(`sectionSelect.searchPlaceholder`)}" data-i18n-placeholder="sectionSelect.searchPlaceholder" spellcheck="false">`}function vd(e,n){if(!e)return;let r=String(n||``).trim().toLowerCase(),i=Array.from(e.children).filter(e=>e.hasAttribute(`data-value`)),a=0;for(let e of i){let t=!r||e.textContent.toLowerCase().includes(r);e.style.display=t?``:`none`,t&&(a+=1)}let o=e.querySelector(`.section-select-empty`);r&&a===0?(o||(o=document.createElement(`div`),o.className=`section-select-empty`,e.appendChild(o)),o.textContent=t(`sectionSelect.noMatch`)):o&&o.remove()}function yd(e,t){gd(),e.classList.add(`open`),t.classList.add(`open`),hd=e;let n=e.querySelector(`.section-select-search`);n&&(n.value=``,vd(e,``),n.focus())}document.addEventListener(`click`,e=>{let t=e.target.closest(`.section-select-row`);if(t){let e=t.parentElement.querySelector(`.section-select-list`);if(!e)return;e===hd?gd():yd(e,t);return}hd&&!hd.parentElement.contains(e.target)&&gd()}),document.addEventListener(`input`,e=>{let t=e.target;if(!t||!t.classList||!t.classList.contains(`section-select-search`))return;let n=t.closest(`.section-select-list`);n&&vd(n,t.value)});var bd=!1;async function xd(){document.getElementById(`providerList`)&&(bd||(bd=!0,wd(),Td()),await Sd())}async function Sd(){let e=document.getElementById(`providerList`),t=document.getElementById(`providerSelectValue`),n=document.getElementById(`providerSelectHost`);if(!e)return;let r=await b(),i=r.profiles.find(e=>e.id===r.activeProfileId)||r.profiles[0];t&&(t.textContent=i?i.name:``),n&&(n.textContent=i?T(i.apiBase):``),e.innerHTML=_d();let a=[...r.profiles].sort((e,t)=>S(e.name,t.name));for(let t of a){let n=!!i&&t.id===i.id,r=document.createElement(`div`);r.className=`provider-option`+(n?` selected`:``),r.dataset.value=t.id;let a=document.createElement(`span`);a.className=`provider-option-check`,a.textContent=n?`✓`:``,r.appendChild(a);let o=document.createElement(`span`);o.className=`provider-option-left`,o.textContent=t.name,r.appendChild(o);let s=T(t.apiBase);if(s){let e=document.createElement(`span`);e.className=`provider-option-right`,e.textContent=s,r.appendChild(e)}r.addEventListener(`click`,e=>{e.stopPropagation(),gd(),Cd(t.id)}),e.appendChild(r)}}async function Cd(e){if(e===(await b()).activeProfileId)return;let t=await se(e);t&&(await Sd(),r.debug(`[SidePanel] provider switched:`,t.name))}function wd(){let e=document.getElementById(`providerManageBtn`);e&&e.addEventListener(`click`,async e=>{e.stopPropagation();let t=chrome.runtime.getURL(`options.html#basic`),n=await chrome.tabs.query({url:chrome.runtime.getURL(`options.html`)});n.length>0?await chrome.tabs.update(n[0].id,{active:!0,url:t}):await chrome.tabs.create({url:t})})}function Td(){chrome.storage.onChanged.addListener((e,t)=>{t===`local`&&(e.modelProfiles||e.activeProfileId)&&Sd()})}var Ed=0;function Dd(e,t){let n=e&&e.nodeType===1?e:e?e.parentElement:null;for(let e=n;e&&e!==t;e=e.parentElement)if(getComputedStyle(e).position===`absolute`)return!0;return!1}function Od(e){let t=[];return e.querySelectorAll(`*`).forEach(e=>{getComputedStyle(e).position===`absolute`&&e.getClientRects().length>0&&t.push(e)}),t}function kd(e){e.forEach(e=>{(e.getAnimations?.()||[]).forEach(e=>{e.playState!==`idle`&&e.finish?.()})})}function Ad(){Ed||=requestAnimationFrame(()=>{Ed=0,Nd()})}function jd(){let e=document.getElementById(`selectionToggleGroup`),t=document.getElementById(`inputAddMenuSwitches`);e&&t&&e.parentElement!==t&&t.appendChild(e)}function Md(){let e=document.getElementById(`selectionToggleGroup`),t=document.querySelector(`.input-bottom-left`);e&&t&&e.parentElement!==t&&t.appendChild(e)}function Nd(){let e=document.querySelector(`.input-bottom-row`),t=e?.closest(`.input-container`)||null;if(!(!e||!t)){t.classList.add(`measuring`);try{Pd(e,t)}finally{t.classList.remove(`measuring`)}}}function Pd(e,t){t.classList.remove(`temp-collapsed`,`agent-collapsed`,`switches-icon`,`selection-in-menu`),Md();let n=Od(e),r=n.map(e=>e.style.display);n.forEach(e=>{e.style.display=`none`});let i=()=>{n.forEach((e,t)=>{e.style.display=r[t]}),kd(n)};if(e.scrollWidth<=e.clientWidth){i();return}if(t.classList.add(`temp-collapsed`),e.scrollWidth<=e.clientWidth){i();return}if(t.classList.add(`agent-collapsed`),e.scrollWidth<=e.clientWidth){i();return}if(t.classList.add(`switches-icon`),e.scrollWidth<=e.clientWidth){i();return}t.classList.add(`selection-in-menu`),jd(),i()}function Fd(){Nd(),window.addEventListener(`resize`,Ad);let e=document.querySelector(`.input-bottom-row`),t=e?.closest(`.input-container`)||null;if(t&&typeof ResizeObserver<`u`){let e=t.clientWidth;new ResizeObserver(t=>{let n=t[0]?.contentRect?.width??0;Math.abs(n-e)<1||(e=n,Ad())}).observe(t)}e&&typeof MutationObserver<`u`&&new MutationObserver(t=>{let n=document.getElementById(`selectionToggleGroup`),r=e=>!!n&&[...e.addedNodes,...e.removedNodes].includes(n);t.some(t=>!Dd(t.target,e)&&!r(t))&&Ad()}).observe(e,{subtree:!0,childList:!0,characterData:!0})}e(`zh`,{fileSelector:{workspaceTitle:`工作目录`,switchHint:`方向键切换 · Enter添加到文件问答 · Esc取消`,searching:`搜索中...`,noMatch:`没有匹配的文件或目录`,noWorkspace:`暂无工作目录,请先连接 Agent`,loadFailed:`加载失败: {error}`,truncated:`仅显示前 {count} 条,请继续输入以缩小范围`}}),e(`en`,{fileSelector:{workspaceTitle:`Workspace`,switchHint:`↑↓ navigate · Enter attach · Esc cancel`,searching:`Searching...`,noMatch:`No matching file or directory`,noWorkspace:`No workspace directory. Connect an Agent first.`,loadFailed:`Load failed: {error}`,truncated:`Showing top {count} results. Keep typing to narrow down.`}});var Id=50,Ld=200,Rd=200,zd=0,Bd=null,Vd=[];function Hd(e){return(e||``).replace(/\\/g,`/`).replace(/\/+/g,`/`)}function Ud(e){let t=document.getElementById(`fileAtTitlePath`);if(!t)return;let n=e?Hd(e):``;t.textContent=n,t.title=n}async function Wd(e=``){let t=document.getElementById(`fileAtSelector`),n=document.getElementById(`fileAtDropdown`);if(!t||!n)return;n.dataset.focusGuard||(n.dataset.focusGuard=`1`,n.addEventListener(`mousedown`,e=>{e.target.closest(`.prompt-item`)&&e.preventDefault()}));let r=document.getElementById(`fileAtWorkspaceOpenBtn`);r&&!r.dataset.bound&&(r.dataset.bound=`1`,r.addEventListener(`click`,async e=>{e.stopPropagation(),Gd(),await Vr()})),ot(),t.style.display=`block`,n.classList.add(`show`),await Kd(e)}function Gd(){let e=document.getElementById(`fileAtSelector`),t=document.getElementById(`fileAtDropdown`);e&&(e.style.display=`none`),t&&t.classList.remove(`show`),v.selectedFileAtIndex=-1,Bd&&=(clearTimeout(Bd),null),zd++}function Kd(e=``){let n=document.getElementById(`fileAtList`);if(!n)return;let i=++zd,a=e.trim();Bd&&clearTimeout(Bd);let o=async()=>{try{let e=await oa();if(i!==zd)return;if(Ud(e),!e){n.innerHTML=`<div class="prompt-empty">${t(`fileSelector.noWorkspace`)}</div>`,v.selectedFileAtIndex=-1;return}let r;if(r=a?await na(e,a,Ld):((await ra(e)).entries||[]).map(t=>({name:t.name,type:t.type||`file`,size:t.size,mtime:t.mtime,fullPath:Hd(`${e}/${t.name}`)})),i!==zd)return;Jd(r,a,n,e)}catch(e){if(i!==zd)return;r.warn(`[FileAtSelector] search failed:`,e.message),n.innerHTML=`<div class="prompt-empty">${t(`fileSelector.loadFailed`,{error:e.message})}</div>`,v.selectedFileAtIndex=-1}};a?(n.innerHTML=`<div class="prompt-empty">${t(`fileSelector.searching`)}</div>`,Bd=setTimeout(o,Rd)):Bd=setTimeout(o,0)}function qd(e,t){let n=t.toLowerCase();return[...e].sort((e,t)=>{let r=(e.name||``).toLowerCase(),i=(t.name||``).toLowerCase();if(n){let e=+!!r.startsWith(n),t=+!!i.startsWith(n);if(e!==t)return t-e}let a=e.mtime||0,o=t.mtime||0;if(a!==o)return o-a;let s=e.type===`directory`?0:1,c=t.type===`directory`?0:1;return s===c?r.localeCompare(i):s-c})}function Jd(e,n,r,i){let a=qd(e,n),o=a.slice(0,Id),s=a.length>Id,c=Hd(i);if(o.length===0){r.innerHTML=`<div class="prompt-empty">${t(`fileSelector.noMatch`)}</div>`,v.selectedFileAtIndex=-1;return}if(v.selectedFileAtIndex=0,Vd=o,r.innerHTML=o.map((e,t)=>{let n=aa(e.name,e.type),r=Hd(e.fullPath),i=r.startsWith(c)?r.substring(c.length).replace(/^\//,``):r;return`
397
+ ${e.icon||``}<span>${k(e.label)}</span>${Uu(e.shortcut)}
398
+ </button>`}function Gu(e,t,n){let r=Vu();r.innerHTML=t.map((e,t)=>t===0&&e.divider?{...e,divider:!1}:e).map(e=>Wu(e,n)).join(``);let i=e.getBoundingClientRect(),a=r.offsetWidth||168,o=r.offsetHeight||132,s=Math.min(i.right-a,window.innerWidth-a-8);s=Math.max(8,s);let c=i.bottom+4;c+o>window.innerHeight-8&&(c=Math.max(8,i.top-o-4)),r.style.left=`${s}px`,r.style.top=`${c}px`}function Ku(e){if(e.status===O.DONE){let n=He(e),r=[{action:`restore`,label:t(`todo.restoreTo`,{status:iu(n)}),icon:B.undo,shortcut:`Alt+D`,divider:!0}];return n!==O.PENDING&&r.push({action:`set-pending`,label:t(`todo.backToPending`),icon:B.circle}),r}return e.status===O.DOING?[{action:`set-done`,label:t(`todo.markDone`),icon:B.check,shortcut:`Alt+D`,divider:!0},{action:`set-pending`,label:t(`todo.backToPending`),icon:B.circle}]:[{action:`set-doing`,label:t(`todo.startDoing`),icon:B.play,divider:!0},{action:`set-done`,label:t(`todo.markDone`),icon:B.check,shortcut:`Alt+D`}]}function qu(e,n){let r=mu(n);r&&Gu(e,[...Ku(r),{swatches:!0,label:t(`todo.priority`),current:r.priority||``,shortcut:`Alt+P`,divider:!0},{action:`edit-title`,label:t(`todo.editTitleAction`),icon:B.edit,divider:!0},{action:`edit-note`,label:r.note?t(`todo.editNote`):t(`todo.addNote`),icon:B.note,shortcut:`Alt+B`},{action:`set-due`,label:t(`todo.setDue`),icon:B.calendar},{action:`edit-link`,label:r.link?t(`todo.editLink`):t(`todo.addLink`),icon:B.link,shortcut:`Alt+L`},{action:`delete`,label:t(`todo.delete`),icon:B.trash,danger:!0,divider:!0}],n)}function Ju(e){let t=Yu();t.length!==0&&Gu(e,t,``)}function Yu(){return[{action:`stats`,label:t(`todo.statsEntry`),icon:B.chart,divider:!0},{action:`export-options`,label:t(`todo.exportEntry`),icon:B.download,divider:!0},{action:`import-options`,label:t(`todo.importEntry`),icon:B.upload}]}async function Xu(){let{active:e,done:t}=tc(),n=await Wc({counts:{all:e.length+t.length,active:e.length,done:t.length}});n&&Zu(n.scope,n.format)}function Zu(e,n){let{active:i,done:a}=tc(),o=[...i,...a];if(xe(o,e).length===0){A(t(`todo.exportEmptyToast`),`info`);return}try{A(t(`todo.exportedToast`,{name:Cc(o,{scope:e,format:n})}),`success`)}catch(e){r.error(`[Todo] export failed:`,e),A(t(`todo.exportFailedToast`),`error`)}}async function Qu(){let e=await wc();if(!e)return;let n=await Tc(e);if(!n.ok){A(t(n.reason===`json`?`todo.importJsonError`:`todo.importFormatError`),`error`);return}let{active:r,done:i}=tc(),a=await Gc({count:n.todos.length,existing:r.length+i.length});if(!a)return;Sl=`active`,K();let o=await mc(n.todos,a);if(!o.ok){A(t(o.reason===`empty`?`todo.importEmptyToast`:`todo.importFailedToast`),`error`);return}if(o.added===0){A(t(`todo.importNothingNewToast`,{skipped:o.skipped}),`info`);return}A(t(`todo.importedToast`,{added:o.added,skipped:o.skipped}),`success`)}async function $u(e,n){let r=mu(n);switch(e){case`set-doing`:q(oc(n,O.DOING));return;case`set-pending`:q(oc(n,O.PENDING));return;case`set-done`:gu(n);return;case`restore`:_u(n);return;case`edit-title`:Cl=n,K();return;case`edit-note`:wl=n,El.add(n),K(),setTimeout(()=>{let e=U.querySelector(`.todo-note-input[data-id="${n}"]`);e&&(e.focus(),e.selectionStart=e.selectionEnd=e.value.length)},30);return;case`set-due`:Tl=n,K(),setTimeout(()=>{let e=U.querySelector(`.todo-due-input[data-id="${n}"]`);e&&e.focus()},30);return;case`edit-link`:Au(n);return;case`stats`:ol();return;case`export-options`:Xu();return;case`import-options`:Qu();return;case`delete`:await Bu(t(`todo.deleteConfirmMsg`,{title:r?.title||``}),t(`todo.deleteConfirmTitle`))&&q(dc(n),t(`todo.deletedToast`));return;default:}}function ed(e,t={}){let{active:n,done:r}=tc(),i=[...n,...r].find(t=>t.id===e);return i?Le(i,t):``}function td(e){let n=ed(e);if(!n){A(t(`todo.emptyDigestToast`),`info`);return}let r=document.getElementById(`userInput`);if(!r){A(t(`todo.noInputToast`),`error`);return}let i=r.value.replace(/\s+$/,``);r.value=i?`${i}\n\n${n}`:n,r.dispatchEvent(new Event(`input`,{bubbles:!0})),r.focus(),r.selectionStart=r.selectionEnd=r.value.length,rt(),Vl(),A(t(`todo.filledToast`),`success`)}function nd(e){let n=ed(e,{plain:!0});if(!n){A(t(`todo.emptyDigestToast`),`info`);return}rd(n,t(`todo.copiedToast`))}function rd(e,n){try{navigator.clipboard.writeText(e).then(()=>{A(n,`success`)}).catch(e=>{r.warn(`[Todo] copy failed:`,e),A(t(`todo.copyFailed`),`error`)})}catch(e){r.warn(`[Todo] clipboard unavailable:`,e),A(t(`todo.copyFailed`),`error`)}}function id(e){let t=e.target.closest?.(`.todo-item[draggable="true"]`);if(!t)return;let n=t.closest(`.todo-list[data-group="active"]`);if(!n)return;let r=Array.from(n.querySelectorAll(`.todo-item`));Dl={id:t.dataset.id,from:r.indexOf(t),list:n},t.classList.add(`dragging`);let{active:i,done:a}=tc(),o=[...i,...a].find(e=>e.id===t.dataset.id);try{e.dataTransfer.effectAllowed=`copyMove`,e.dataTransfer.setData(`text/plain`,Le(o)||t.dataset.id)}catch{}}function ad(e){if(!Dl)return;e.preventDefault();let t=Dl.list;if(!t||!t.isConnected)return;let n=Array.from(t.querySelectorAll(`.todo-item`)).filter(e=>!e.classList.contains(`dragging`)),r=n.length;for(let t=0;t<n.length;t++){let i=n[t].getBoundingClientRect();if(e.clientY<i.top+i.height/2){r=t;break}}let i=od();r>=n.length?t.appendChild(i):n[r].before(i)}function od(){let e=U.querySelector(`.todo-insert`);return e||(e=document.createElement(`div`),e.className=`todo-insert`,e)}function sd(e){if(!Dl)return;e.preventDefault();let t=Dl.list,n=U.querySelector(`.todo-insert`),r=Dl.from;if(n&&t){let e=Array.from(t.querySelectorAll(`.todo-item`)).filter(e=>!e.classList.contains(`dragging`)),i=e.findIndex(e=>n.compareDocumentPosition(e)&Node.DOCUMENT_POSITION_FOLLOWING);r=i===-1?e.length:i}let i=Dl.from;cd(),i!==r&&q(fc(i,r))}function cd(){Dl=null,U?.querySelectorAll(`.todo-item.dragging`).forEach(e=>e.classList.remove(`dragging`)),U?.querySelector(`.todo-insert`)?.remove()}var ld=`—`,ud=[{labelKey:`versionInfo.website`,url:`https://xiweicheng.github.io/ai-helper/`,icon:`<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 17.93c-3.95-.49-7-3.85-7-7.93 0-.62.08-1.21.21-1.79L9 15v1c0 1.1.9 2 2 2v1.93zm6.9-2.54c-.26-.81-1-1.39-1.9-1.39h-1v-3c0-.55-.45-1-1-1H8v-2h2c.55 0 1-.45 1-1V7h2c1.1 0 2-.9 2-2v-.41c2.93 1.19 5 4.06 5 7.41 0 2.08-.8 3.97-2.1 5.39z"/></svg>`},{labelKey:`versionInfo.discussions`,url:`https://github.com/xiweicheng/ai-helper/discussions`,icon:`<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2z"/></svg>`},{labelKey:`versionInfo.reportIssue`,url:`https://github.com/xiweicheng/ai-helper/issues/new`,icon:`<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M20 8h-2.81c-.45-.78-1.07-1.45-1.82-1.96L17 4.41 15.59 3l-2.17 2.17C12.96 5.06 12.49 5 12 5c-.49 0-.96.06-1.41.17L8.41 3 7 4.41l1.62 1.63C7.88 6.55 7.26 7.22 6.81 8H4v2h2.09c-.05.33-.09.66-.09 1v1H4v2h2v1c0 .34.04.67.09 1H4v2h2.81c1.04 1.79 2.97 3 5.19 3s4.15-1.21 5.19-3H20v-2h-2.09c.05-.33.09-.66.09-1v-1h2v-2h-2v-1c0-.34-.04-.67-.09-1H20V8zm-6 8h-4v-2h4v2zm0-4h-4v-2h4v2z"/></svg>`},{labelKey:`versionInfo.githubRepo`,url:`https://github.com/xiweicheng/ai-helper`,icon:`<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M12 .5C5.73.5.5 5.73.5 12c0 5.08 3.29 9.39 7.86 10.91.58.11.79-.25.79-.56 0-.28-.01-1.02-.02-2-3.2.7-3.88-1.54-3.88-1.54-.52-1.33-1.28-1.69-1.28-1.69-1.04-.71.08-.7.08-.7 1.15.08 1.76 1.19 1.76 1.19 1.03 1.76 2.7 1.25 3.36.96.1-.75.4-1.25.72-1.54-2.55-.29-5.24-1.28-5.24-5.68 0-1.26.45-2.28 1.19-3.09-.12-.29-.52-1.46.11-3.05 0 0 .97-.31 3.18 1.18a11.1 11.1 0 012.9-.39c.98 0 1.97.13 2.9.39 2.2-1.49 3.17-1.18 3.17-1.18.63 1.59.23 2.76.11 3.05.74.81 1.19 1.83 1.19 3.09 0 4.41-2.69 5.38-5.25 5.67.41.35.78 1.05.78 2.12 0 1.53-.01 2.76-.01 3.14 0 .31.21.68.8.56A11.51 11.51 0 0023.5 12C23.5 5.73 18.27.5 12 .5z"/></svg>`},{labelKey:`versionInfo.giteeRepo`,url:`https://gitee.com/xiweicheng/ai-helper`,icon:`<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M11.984 0A12 12 0 000 12a12 12 0 0012 12 12 12 0 0012-12A12 12 0 0012 0zm6.09 5.333c.328 0 .593.266.592.593v1.482a.594.594 0 01-.593.592H9.777c-.982 0-1.778.796-1.778 1.778v5.63c0 .327.266.592.593.592h5.63c.982 0 1.778-.796 1.778-1.778v-.296a.593.593 0 00-.592-.593h-4.15a.592.592 0 01-.592-.592v-1.482a.593.593 0 01.593-.592h6.815c.327 0 .593.265.593.592v3.408a4 4 0 01-4 4H8.444a3.556 3.556 0 01-3.555-3.556V8.89a3.556 3.556 0 013.555-3.556h9.63z"/></svg>`}];function dd(e){let t=e=>typeof e==`string`?e.trim():``,n=e&&typeof e==`object`?e:{};return{version:t(n.version),tag:t(n.tag),commitId:t(n.commitId),publishedAt:t(n.publishedAt)}}function fd(e){if(!e)return ld;let t=Date.parse(e);return Number.isNaN(t)?ld:new Date(t).toLocaleString()}function pd(e){let n=dd(pt),r=[{label:t(`versionInfo.version`),value:n.version?`v${n.version}`:ld},{label:t(`versionInfo.tag`),value:n.tag||ld},{label:t(`versionInfo.commit`),value:n.commitId?n.commitId.slice(0,8):ld,title:n.commitId,mono:!0},{label:t(`versionInfo.publishedAt`),value:fd(n.publishedAt)}];e.textContent=``;for(let t of r){let n=document.createElement(`div`);n.className=`version-info-row`;let r=document.createElement(`div`);r.className=`version-info-label`,r.textContent=t.label;let i=document.createElement(`div`);i.className=t.mono?`version-info-value mono`:`version-info-value`,i.textContent=t.value,t.title&&(i.title=t.title),n.appendChild(r),n.appendChild(i),e.appendChild(n)}}function md(e){e.textContent=``;for(let n of ud){let r=document.createElement(`div`);r.className=`version-info-link`,r.title=n.url;let i=document.createElement(`span`);i.className=`version-info-link-icon`,i.innerHTML=n.icon;let a=document.createElement(`span`);a.className=`version-info-link-label`,a.textContent=t(n.labelKey);let o=document.createElement(`span`);o.className=`version-info-link-arrow`,o.textContent=`↗`,r.appendChild(i),r.appendChild(a),r.appendChild(o),r.addEventListener(`click`,()=>{chrome.tabs.create({url:n.url})}),e.appendChild(r)}}function hd(){let e=dd(pt);return[`AI Helper v${e.version||ld}`,`${t(`versionInfo.tag`)}: ${e.tag||ld}`,`${t(`versionInfo.commit`)}: ${e.commitId||ld}`,`${t(`versionInfo.publishedAt`)}: ${fd(e.publishedAt)}`].join(`
399
+ `)}function gd(){let e=document.getElementById(`versionInfoBtn`),n=document.getElementById(`versionInfoModal`),r=document.getElementById(`versionInfoCloseBtn`),i=document.getElementById(`versionInfoCopyBtn`),a=document.getElementById(`versionInfoList`),o=document.getElementById(`versionInfoLinks`);if(!e||!n||!a)return;let s=()=>{n.style.display=`none`};e.addEventListener(`click`,e=>{e.stopPropagation();let t=document.getElementById(`headerMoreDropdown`);t&&t.classList.remove(`show`),pd(a),o&&md(o),n.style.display=`flex`}),r&&r.addEventListener(`click`,s),n.addEventListener(`click`,e=>{e.target===n&&s()}),document.addEventListener(`keydown`,e=>{e.key===`Escape`&&n.style.display===`flex`&&s()}),i&&i.addEventListener(`click`,async()=>{try{await navigator.clipboard.writeText(hd()),A(t(`common.copySuccess`),`success`)}catch{A(t(`common.copyFailed`),`error`)}})}var _d=null;function vd(){if(!_d)return;_d.classList.remove(`open`);let e=_d.parentElement?_d.parentElement.querySelector(`.section-select-row`):null;e&&e.classList.remove(`open`),_d=null}function yd(){return`<input type="search" class="section-select-search" placeholder="${t(`sectionSelect.searchPlaceholder`)}" data-i18n-placeholder="sectionSelect.searchPlaceholder" spellcheck="false">`}function bd(e,n){if(!e)return;let r=String(n||``).trim().toLowerCase(),i=Array.from(e.children).filter(e=>e.hasAttribute(`data-value`)),a=0;for(let e of i){let t=!r||e.textContent.toLowerCase().includes(r);e.style.display=t?``:`none`,t&&(a+=1)}let o=e.querySelector(`.section-select-empty`);r&&a===0?(o||(o=document.createElement(`div`),o.className=`section-select-empty`,e.appendChild(o)),o.textContent=t(`sectionSelect.noMatch`)):o&&o.remove()}function xd(e,t){vd(),e.classList.add(`open`),t.classList.add(`open`),_d=e;let n=e.querySelector(`.section-select-search`);n&&(n.value=``,bd(e,``),n.focus())}document.addEventListener(`click`,e=>{let t=e.target.closest(`.section-select-row`);if(t){let e=t.parentElement.querySelector(`.section-select-list`);if(!e)return;e===_d?vd():xd(e,t);return}_d&&!_d.parentElement.contains(e.target)&&vd()}),document.addEventListener(`input`,e=>{let t=e.target;if(!t||!t.classList||!t.classList.contains(`section-select-search`))return;let n=t.closest(`.section-select-list`);n&&bd(n,t.value)});var Sd=!1;async function Cd(){document.getElementById(`providerList`)&&(Sd||(Sd=!0,Ed(),Dd()),await wd())}async function wd(){let e=document.getElementById(`providerList`),t=document.getElementById(`providerSelectValue`),n=document.getElementById(`providerSelectHost`);if(!e)return;let r=await b(),i=r.profiles.find(e=>e.id===r.activeProfileId)||r.profiles[0];t&&(t.textContent=i?i.name:``),n&&(n.textContent=i?T(i.apiBase):``),e.innerHTML=yd();let a=[...r.profiles].sort((e,t)=>S(e.name,t.name));for(let t of a){let n=!!i&&t.id===i.id,r=document.createElement(`div`);r.className=`provider-option`+(n?` selected`:``),r.dataset.value=t.id;let a=document.createElement(`span`);a.className=`provider-option-check`,a.textContent=n?`✓`:``,r.appendChild(a);let o=document.createElement(`span`);o.className=`provider-option-left`,o.textContent=t.name,r.appendChild(o);let s=T(t.apiBase);if(s){let e=document.createElement(`span`);e.className=`provider-option-right`,e.textContent=s,r.appendChild(e)}r.addEventListener(`click`,e=>{e.stopPropagation(),vd(),Td(t.id)}),e.appendChild(r)}}async function Td(e){if(e===(await b()).activeProfileId)return;let t=await se(e);t&&(await wd(),r.debug(`[SidePanel] provider switched:`,t.name))}function Ed(){let e=document.getElementById(`providerManageBtn`);e&&e.addEventListener(`click`,async e=>{e.stopPropagation();let t=chrome.runtime.getURL(`options.html#basic`),n=await chrome.tabs.query({url:chrome.runtime.getURL(`options.html`)});n.length>0?await chrome.tabs.update(n[0].id,{active:!0,url:t}):await chrome.tabs.create({url:t})})}function Dd(){chrome.storage.onChanged.addListener((e,t)=>{t===`local`&&(e.modelProfiles||e.activeProfileId)&&wd()})}var Od=0;function kd(e,t){let n=e&&e.nodeType===1?e:e?e.parentElement:null;for(let e=n;e&&e!==t;e=e.parentElement)if(getComputedStyle(e).position===`absolute`)return!0;return!1}function Ad(e){let t=[];return e.querySelectorAll(`*`).forEach(e=>{getComputedStyle(e).position===`absolute`&&e.getClientRects().length>0&&t.push(e)}),t}function jd(e){e.forEach(e=>{(e.getAnimations?.()||[]).forEach(e=>{e.playState!==`idle`&&e.finish?.()})})}function Md(){Od||=requestAnimationFrame(()=>{Od=0,Fd()})}function Nd(){let e=document.getElementById(`selectionToggleGroup`),t=document.getElementById(`inputAddMenuSwitches`);e&&t&&e.parentElement!==t&&t.appendChild(e)}function Pd(){let e=document.getElementById(`selectionToggleGroup`),t=document.querySelector(`.input-bottom-left`);e&&t&&e.parentElement!==t&&t.appendChild(e)}function Fd(){let e=document.querySelector(`.input-bottom-row`),t=e?.closest(`.input-container`)||null;if(!(!e||!t)){t.classList.add(`measuring`);try{Id(e,t)}finally{t.classList.remove(`measuring`)}}}function Id(e,t){t.classList.remove(`temp-collapsed`,`agent-collapsed`,`switches-icon`,`selection-in-menu`),Pd();let n=Ad(e),r=n.map(e=>e.style.display);n.forEach(e=>{e.style.display=`none`});let i=()=>{n.forEach((e,t)=>{e.style.display=r[t]}),jd(n)};if(e.scrollWidth<=e.clientWidth){i();return}if(t.classList.add(`temp-collapsed`),e.scrollWidth<=e.clientWidth){i();return}if(t.classList.add(`agent-collapsed`),e.scrollWidth<=e.clientWidth){i();return}if(t.classList.add(`switches-icon`),e.scrollWidth<=e.clientWidth){i();return}t.classList.add(`selection-in-menu`),Nd(),i()}function Ld(){Fd(),window.addEventListener(`resize`,Md);let e=document.querySelector(`.input-bottom-row`),t=e?.closest(`.input-container`)||null;if(t&&typeof ResizeObserver<`u`){let e=t.clientWidth;new ResizeObserver(t=>{let n=t[0]?.contentRect?.width??0;Math.abs(n-e)<1||(e=n,Md())}).observe(t)}e&&typeof MutationObserver<`u`&&new MutationObserver(t=>{let n=document.getElementById(`selectionToggleGroup`),r=e=>!!n&&[...e.addedNodes,...e.removedNodes].includes(n);t.some(t=>!kd(t.target,e)&&!r(t))&&Md()}).observe(e,{subtree:!0,childList:!0,characterData:!0})}e(`zh`,{fileSelector:{workspaceTitle:`工作目录`,switchHint:`方向键切换 · Enter添加到文件问答 · Esc取消`,searching:`搜索中...`,noMatch:`没有匹配的文件或目录`,noWorkspace:`暂无工作目录,请先连接 Agent`,loadFailed:`加载失败: {error}`,truncated:`仅显示前 {count} 条,请继续输入以缩小范围`}}),e(`en`,{fileSelector:{workspaceTitle:`Workspace`,switchHint:`↑↓ navigate · Enter attach · Esc cancel`,searching:`Searching...`,noMatch:`No matching file or directory`,noWorkspace:`No workspace directory. Connect an Agent first.`,loadFailed:`Load failed: {error}`,truncated:`Showing top {count} results. Keep typing to narrow down.`}});var Rd=50,zd=200,Bd=200,Vd=0,Hd=null,Ud=[];function Wd(e){return(e||``).replace(/\\/g,`/`).replace(/\/+/g,`/`)}function Gd(e){let t=document.getElementById(`fileAtTitlePath`);if(!t)return;let n=e?Wd(e):``;t.textContent=n,t.title=n}async function Kd(e=``){let t=document.getElementById(`fileAtSelector`),n=document.getElementById(`fileAtDropdown`);if(!t||!n)return;n.dataset.focusGuard||(n.dataset.focusGuard=`1`,n.addEventListener(`mousedown`,e=>{e.target.closest(`.prompt-item`)&&e.preventDefault()}));let r=document.getElementById(`fileAtWorkspaceOpenBtn`);r&&!r.dataset.bound&&(r.dataset.bound=`1`,r.addEventListener(`click`,async e=>{e.stopPropagation(),qd(),await mr()})),ot(),t.style.display=`block`,n.classList.add(`show`),await Jd(e)}function qd(){let e=document.getElementById(`fileAtSelector`),t=document.getElementById(`fileAtDropdown`);e&&(e.style.display=`none`),t&&t.classList.remove(`show`),v.selectedFileAtIndex=-1,Hd&&=(clearTimeout(Hd),null),Vd++}function Jd(e=``){let n=document.getElementById(`fileAtList`);if(!n)return;let i=++Vd,a=e.trim();Hd&&clearTimeout(Hd);let o=async()=>{try{let e=await sa();if(i!==Vd)return;if(Gd(e),!e){n.innerHTML=`<div class="prompt-empty">${t(`fileSelector.noWorkspace`)}</div>`,v.selectedFileAtIndex=-1;return}let r;if(r=a?await ra(e,a,zd):((await ia(e)).entries||[]).map(t=>({name:t.name,type:t.type||`file`,size:t.size,mtime:t.mtime,fullPath:Wd(`${e}/${t.name}`)})),i!==Vd)return;Xd(r,a,n,e)}catch(e){if(i!==Vd)return;r.warn(`[FileAtSelector] search failed:`,e.message),n.innerHTML=`<div class="prompt-empty">${t(`fileSelector.loadFailed`,{error:e.message})}</div>`,v.selectedFileAtIndex=-1}};a?(n.innerHTML=`<div class="prompt-empty">${t(`fileSelector.searching`)}</div>`,Hd=setTimeout(o,Bd)):Hd=setTimeout(o,0)}function Yd(e,t){let n=t.toLowerCase();return[...e].sort((e,t)=>{let r=(e.name||``).toLowerCase(),i=(t.name||``).toLowerCase();if(n){let e=+!!r.startsWith(n),t=+!!i.startsWith(n);if(e!==t)return t-e}let a=e.mtime||0,o=t.mtime||0;if(a!==o)return o-a;let s=e.type===`directory`?0:1,c=t.type===`directory`?0:1;return s===c?r.localeCompare(i):s-c})}function Xd(e,n,r,i){let a=Yd(e,n),o=a.slice(0,Rd),s=a.length>Rd,c=Wd(i);if(o.length===0){r.innerHTML=`<div class="prompt-empty">${t(`fileSelector.noMatch`)}</div>`,v.selectedFileAtIndex=-1;return}if(v.selectedFileAtIndex=0,Ud=o,r.innerHTML=o.map((e,t)=>{let n=oa(e.name,e.type),r=Wd(e.fullPath),i=r.startsWith(c)?r.substring(c.length).replace(/^\//,``):r;return`
400
400
  <div class="prompt-item ${t===0?`selected`:``}" data-index="${t}" data-path="${k(r)}" title="${k(r)}">
401
401
  <span class="prompt-item-index">${t+1}</span>
402
402
  <span class="prompt-item-icon">${n}</span>
403
403
  <span class="prompt-item-content">${k(e.name)}</span>
404
404
  <span class="file-at-path">${k(i)}</span>
405
405
  </div>
406
- `}).join(``),s){let e=document.createElement(`div`);e.className=`file-at-truncated`,e.textContent=t(`fileSelector.truncated`,{count:Id}),r.appendChild(e)}r.querySelectorAll(`.prompt-item`).forEach(e=>{e.addEventListener(`click`,()=>{Yd(Vd.find(t=>t.fullPath===e.dataset.path)||e.dataset.path)})})}function Yd(e){if(!(typeof e==`string`?e:e&&e.fullPath))return;let t=document.getElementById(`userInput`),n=t?t.value:``,r=n.lastIndexOf(`$`);r!==-1&&(t.value=n.substring(0,r)),t&&(t.focus(),t.selectionStart=t.selectionEnd=t.value.length),Gd(),si([e]),rt()}function Xd(e){let t=v.selectedFileAtIndex;e.forEach((e,n)=>{n===t?(e.classList.add(`selected`),e.scrollIntoView({block:`nearest`})):e.classList.remove(`selected`)})}e(`zh`,{input:{addMenuPanelSearchPlaceholder:`搜索…`,addMenuPanelClear:`清除`,addMenuPanelLoading:`加载中…`,addMenuPanelEmpty:`暂无可用内容`,addMenuPanelNoMatch:`没有匹配项`}}),e(`en`,{input:{addMenuPanelSearchPlaceholder:`Search…`,addMenuPanelClear:`Clear`,addMenuPanelLoading:`Loading…`,addMenuPanelEmpty:`No items available`,addMenuPanelNoMatch:`No matches`}});var Zd=null,Y=null,Qd=null,$d=null,ef=null,tf=null,X=null,nf=[],rf=0,af=()=>{},of=[{action:`full`,icon:`📷`,nameKey:`input.addMenuScreenshotFull`,descKey:`input.addMenuScreenshotFullDesc`,kbd:`Alt+S`},{action:`region`,icon:`✂️`,nameKey:`input.addMenuScreenshotRegion`,descKey:`input.addMenuScreenshotRegionDesc`,kbd:`Alt+Shift+S`}],sf=new Set([`screenshot`]),cf={prompts:{titleKey:`promptManager.title`,action:()=>Wr()},skills:{titleKey:`promptSelector.skillManageTitle`,action:()=>lf(`toolbox`)},mcp:{titleKey:`promptSelector.mcpManageTitle`,action:()=>lf(`toolbox`)},pages:{titleKey:`pageSelector.openNewTab`,action:()=>chrome.tabs.create({})},knowledge:{titleKey:`header.manageKnowledge`,action:()=>lf(`knowledge`)},agents:{titleKey:`header.addEditAssistant`,action:()=>ui(null)},proxies:{titleKey:`header.addEditAgent`,action:()=>lf(`agent`)},workspace:{titleKey:`workspace.openPanel`,action:()=>Vr()}};function lf(e){chrome.runtime.sendMessage({type:`OPEN_OPTIONS_PAGE`,hash:e})}function uf(){if(!ef)return;let e=X?cf[X]:null;if(!e){ef.style.display=`none`;return}let n=t(e.titleKey);ef.title=n,ef.setAttribute(`aria-label`,n),ef.style.display=`flex`}function df(){$d&&($d.style.display=sf.has(X)?`none`:``)}function ff(e={}){if(af=typeof e.onRequestClose==`function`?e.onRequestClose:()=>{},Zd=document.getElementById(`inputAddPanel`),Y=document.getElementById(`inputAddPanelSearch`),Qd=document.getElementById(`inputAddPanelSearchClear`),ef=document.getElementById(`inputAddPanelManage`),$d=document.getElementById(`inputAddPanelSearchWrap`),tf=document.getElementById(`inputAddPanelList`),!(!Zd||!Y||!tf)){if(ef&&ef.addEventListener(`click`,()=>{let e=X?cf[X]:null;e&&(af(),e.action())}),Qd){let e=t(`input.addMenuPanelClear`);Qd.title=e,Qd.setAttribute(`aria-label`,e),Qd.addEventListener(`click`,()=>{Y.value=``,Sf(),pf(),Y.focus()})}Y.addEventListener(`input`,()=>{Sf(),pf()})}}function pf(){Qd&&Y&&(Qd.style.display=Y.value?`flex`:`none`)}function mf(){return!!X}function hf(){return X}function gf(){return!!Y&&document.activeElement===Y}async function _f(e){if(!Zd||!e||X===e&&Zd.style.display!==`none`)return;X=e,uf(),df(),Y&&(Y.value=``,Y.placeholder=t(`input.addMenuPanelSearchPlaceholder`),pf()),Zd.style.display=`flex`;let n=++rf;tf&&(tf.innerHTML=`<div class="prompt-empty">${t(`input.addMenuPanelLoading`)}</div>`);try{let t=await yf(e);if(n!==rf)return;nf=Array.isArray(t)?t:[],Sf()}catch(e){if(n!==rf)return;r.warn(`[InputAddPanel] load failed:`,e&&e.message),nf=[],tf&&(tf.innerHTML=`<div class="prompt-empty">${t(`input.addMenuPanelEmpty`)}</div>`)}}function vf(){X=null,uf(),df(),nf=[],rf++,Y&&(Y.value=``,pf()),tf&&(tf.innerHTML=``),Zd&&(Zd.style.display=`none`)}function yf(e){switch(e){case`prompts`:return Promise.resolve(v.customPrompts||[]);case`skills`:return ji(!0);case`mcp`:return Qr();case`pages`:return Dn();case`knowledge`:return Dt().then(e=>e.ok?e.collections:[]);case`agents`:return ta();case`proxies`:return Qn();case`workspace`:return bf();case`screenshot`:return Promise.resolve(of);default:return Promise.resolve([])}}async function bf(){let e=await oa();if(!e)return[];let t=await ra(e),n=t&&t.entries||[],r=String(e).replace(/\\/g,`/`).replace(/\/+/g,`/`);return n.map(e=>({name:e.name,type:e.type||`file`,size:e.size,mtime:e.mtime,fullPath:`${r}/${e.name}`.replace(/\/+/g,`/`)})).sort((e,t)=>{let n=e.mtime||0,r=t.mtime||0;if(n!==r)return r-n;let i=e.type===`directory`?0:1,a=t.type===`directory`?0:1;return i===a?String(e.name).localeCompare(String(t.name)):i-a})}function xf(e){if(!e)return nf;let n=e.toLowerCase();return nf.filter(e=>{switch(X){case`prompts`:return String(e.code||``).toLowerCase().includes(n)||String(e.content||``).toLowerCase().includes(n);case`skills`:return String(e.name||``).toLowerCase().includes(n)||String(e.description||``).toLowerCase().includes(n);case`mcp`:return String(e.serverName||``).toLowerCase().includes(n)||String(e.serverId||``).toLowerCase().includes(n);case`pages`:return String(e.title||``).toLowerCase().includes(n)||String(e.url||``).toLowerCase().includes(n);case`knowledge`:return String(e.name||``).toLowerCase().includes(n)||String(e.description||``).toLowerCase().includes(n);case`agents`:return String(Xt(e)||``).toLowerCase().includes(n)||String(Yn(e)||``).toLowerCase().includes(n);case`proxies`:return String(e.name||``).toLowerCase().includes(n)||String(e.url||``).toLowerCase().includes(n);case`workspace`:return String(e.name||``).toLowerCase().includes(n);case`screenshot`:return t(e.nameKey).toLowerCase().includes(n)||t(e.descKey).toLowerCase().includes(n);default:return!0}})}function Sf(){if(!tf)return;let e=Y?Y.value.trim():``,n=xf(e);if(n.length===0){tf.innerHTML=`<div class="prompt-empty">${t(e?`input.addMenuPanelNoMatch`:`input.addMenuPanelEmpty`)}</div>`;return}tf.innerHTML=n.map(e=>Cf(e)).join(``),tf.querySelectorAll(`.input-add-panel-item`).forEach(e=>{e.addEventListener(`click`,t=>wf(t,e))}),tf.querySelectorAll(`img.favicon-img`).forEach(e=>{e.addEventListener(`error`,()=>{e.style.display=`none`})}),X===`proxies`&&n.forEach(e=>rn(e)),X===`skills`&&Lr(),X===`mcp`&&ni(),X===`knowledge`&&bi()}function Cf(e){switch(X){case`prompts`:return`<div class="prompt-item input-add-panel-item input-add-panel-item-two-line" data-code="${k(e.code)}" title="${j(e.content||``)}">
406
+ `}).join(``),s){let e=document.createElement(`div`);e.className=`file-at-truncated`,e.textContent=t(`fileSelector.truncated`,{count:Rd}),r.appendChild(e)}r.querySelectorAll(`.prompt-item`).forEach(e=>{e.addEventListener(`click`,()=>{Zd(Ud.find(t=>t.fullPath===e.dataset.path)||e.dataset.path)})})}function Zd(e){if(!(typeof e==`string`?e:e&&e.fullPath))return;let t=document.getElementById(`userInput`),n=t?t.value:``,r=n.lastIndexOf(`$`);r!==-1&&(t.value=n.substring(0,r)),t&&(t.focus(),t.selectionStart=t.selectionEnd=t.value.length),qd(),Si([e]),rt()}function Qd(e){let t=v.selectedFileAtIndex;e.forEach((e,n)=>{n===t?(e.classList.add(`selected`),e.scrollIntoView({block:`nearest`})):e.classList.remove(`selected`)})}e(`zh`,{input:{addMenuPanelSearchPlaceholder:`搜索…`,addMenuPanelClear:`清除`,addMenuPanelLoading:`加载中…`,addMenuPanelEmpty:`暂无可用内容`,addMenuPanelNoMatch:`没有匹配项`}}),e(`en`,{input:{addMenuPanelSearchPlaceholder:`Search…`,addMenuPanelClear:`Clear`,addMenuPanelLoading:`Loading…`,addMenuPanelEmpty:`No items available`,addMenuPanelNoMatch:`No matches`}});var $d=null,J=null,ef=null,tf=null,nf=null,Y=null,X=null,rf=[],af=0,of=()=>{},sf=[{action:`full`,icon:`📷`,nameKey:`input.addMenuScreenshotFull`,descKey:`input.addMenuScreenshotFullDesc`,kbd:`Alt+S`},{action:`region`,icon:`✂️`,nameKey:`input.addMenuScreenshotRegion`,descKey:`input.addMenuScreenshotRegionDesc`,kbd:`Alt+Shift+S`}],cf=new Set([`screenshot`]),lf={prompts:{titleKey:`promptManager.title`,action:()=>Gr()},skills:{titleKey:`promptSelector.skillManageTitle`,action:()=>uf(`toolbox`)},mcp:{titleKey:`promptSelector.mcpManageTitle`,action:()=>uf(`toolbox`)},pages:{titleKey:`pageSelector.openNewTab`,action:()=>chrome.tabs.create({})},knowledge:{titleKey:`header.manageKnowledge`,action:()=>uf(`knowledge`)},agents:{titleKey:`header.addEditAssistant`,action:()=>ui(null)},proxies:{titleKey:`header.addEditAgent`,action:()=>uf(`agent`)},workspace:{titleKey:`workspace.openPanel`,action:()=>mr()}};function uf(e){chrome.runtime.sendMessage({type:`OPEN_OPTIONS_PAGE`,hash:e})}function df(){if(!nf)return;let e=X?lf[X]:null;if(!e){nf.style.display=`none`;return}let n=t(e.titleKey);nf.title=n,nf.setAttribute(`aria-label`,n),nf.style.display=`flex`}function ff(){tf&&(tf.style.display=cf.has(X)?`none`:``)}function pf(e={}){if(of=typeof e.onRequestClose==`function`?e.onRequestClose:()=>{},$d=document.getElementById(`inputAddPanel`),J=document.getElementById(`inputAddPanelSearch`),ef=document.getElementById(`inputAddPanelSearchClear`),nf=document.getElementById(`inputAddPanelManage`),tf=document.getElementById(`inputAddPanelSearchWrap`),Y=document.getElementById(`inputAddPanelList`),!(!$d||!J||!Y)){if(nf&&nf.addEventListener(`click`,()=>{let e=X?lf[X]:null;e&&(of(),e.action())}),ef){let e=t(`input.addMenuPanelClear`);ef.title=e,ef.setAttribute(`aria-label`,e),ef.addEventListener(`click`,()=>{J.value=``,Cf(),mf(),J.focus()})}J.addEventListener(`input`,()=>{Cf(),mf()})}}function mf(){ef&&J&&(ef.style.display=J.value?`flex`:`none`)}function hf(){return!!X}function gf(){return X}function _f(){return!!J&&document.activeElement===J}async function vf(e){if(!$d||!e||X===e&&$d.style.display!==`none`)return;X=e,df(),ff(),J&&(J.value=``,J.placeholder=t(`input.addMenuPanelSearchPlaceholder`),mf()),$d.style.display=`flex`;let n=++af;Y&&(Y.innerHTML=`<div class="prompt-empty">${t(`input.addMenuPanelLoading`)}</div>`);try{let t=await bf(e);if(n!==af)return;rf=Array.isArray(t)?t:[],Cf()}catch(e){if(n!==af)return;r.warn(`[InputAddPanel] load failed:`,e&&e.message),rf=[],Y&&(Y.innerHTML=`<div class="prompt-empty">${t(`input.addMenuPanelEmpty`)}</div>`)}}function yf(){X=null,df(),ff(),rf=[],af++,J&&(J.value=``,mf()),Y&&(Y.innerHTML=``),$d&&($d.style.display=`none`)}function bf(e){switch(e){case`prompts`:return Promise.resolve(v.customPrompts||[]);case`skills`:return Ni(!0);case`mcp`:return $r();case`pages`:return Ut();case`knowledge`:return Yn().then(e=>e.ok?e.collections:[]);case`agents`:return na();case`proxies`:return Kt();case`workspace`:return xf();case`screenshot`:return Promise.resolve(sf);default:return Promise.resolve([])}}async function xf(){let e=await sa();if(!e)return[];let t=await ia(e),n=t&&t.entries||[],r=String(e).replace(/\\/g,`/`).replace(/\/+/g,`/`);return n.map(e=>({name:e.name,type:e.type||`file`,size:e.size,mtime:e.mtime,fullPath:`${r}/${e.name}`.replace(/\/+/g,`/`)})).sort((e,t)=>{let n=e.mtime||0,r=t.mtime||0;if(n!==r)return r-n;let i=e.type===`directory`?0:1,a=t.type===`directory`?0:1;return i===a?String(e.name).localeCompare(String(t.name)):i-a})}function Sf(e){if(!e)return rf;let n=e.toLowerCase();return rf.filter(e=>{switch(X){case`prompts`:return String(e.code||``).toLowerCase().includes(n)||String(e.content||``).toLowerCase().includes(n);case`skills`:return String(e.name||``).toLowerCase().includes(n)||String(e.description||``).toLowerCase().includes(n);case`mcp`:return String(e.serverName||``).toLowerCase().includes(n)||String(e.serverId||``).toLowerCase().includes(n);case`pages`:return String(e.title||``).toLowerCase().includes(n)||String(e.url||``).toLowerCase().includes(n);case`knowledge`:return String(e.name||``).toLowerCase().includes(n)||String(e.description||``).toLowerCase().includes(n);case`agents`:return String(Kn(e)||``).toLowerCase().includes(n)||String(Xt(e)||``).toLowerCase().includes(n);case`proxies`:return String(e.name||``).toLowerCase().includes(n)||String(e.url||``).toLowerCase().includes(n);case`workspace`:return String(e.name||``).toLowerCase().includes(n);case`screenshot`:return t(e.nameKey).toLowerCase().includes(n)||t(e.descKey).toLowerCase().includes(n);default:return!0}})}function Cf(){if(!Y)return;let e=J?J.value.trim():``,n=Sf(e);if(n.length===0){Y.innerHTML=`<div class="prompt-empty">${t(e?`input.addMenuPanelNoMatch`:`input.addMenuPanelEmpty`)}</div>`;return}Y.innerHTML=n.map(e=>wf(e)).join(``),Y.querySelectorAll(`.input-add-panel-item`).forEach(e=>{e.addEventListener(`click`,t=>Tf(t,e))}),Y.querySelectorAll(`img.favicon-img`).forEach(e=>{e.addEventListener(`error`,()=>{e.style.display=`none`})}),X===`proxies`&&n.forEach(e=>ar(e)),X===`skills`&&Lr(),X===`mcp`&&ri(),X===`knowledge`&&rn()}function wf(e){switch(X){case`prompts`:return`<div class="prompt-item input-add-panel-item input-add-panel-item-two-line" data-code="${k(e.code)}" title="${j(e.content||``)}">
407
407
  <span class="input-add-panel-item-title"><span class="input-add-panel-item-inline-icon">${zn}</span>/${k(e.code)}</span>
408
408
  <span class="input-add-panel-item-sub">${k(e.content||``)}</span>
409
409
  </div>`;case`skills`:{let n=e.enabled===!1,r=n?`${e.name}\n${t(`skillSelector.disabledTooltip`)}`:e.name,i=e.description||``;return`<div class="skill-list-item input-add-panel-item input-add-panel-item-two-line${n?` skill-list-item-disabled`:``}" data-skill-name="${k(e.name)}" title="${j(r)}">
@@ -419,25 +419,25 @@ import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-DvmxOw8q.js"
419
419
  </div>`}case`knowledge`:{let n=e.enabled===!1,r=t(`knowledgeSelector.docChunk`,{docs:e.documentCount||0,chunks:e.chunkCount||0});return`<div class="prompt-item input-add-panel-item input-add-panel-item-two-line prompt-item-knowledge${n?` knowledge-item-disabled`:``}" data-kb-id="${k(e.id)}" data-kb-name="${k(e.name||``)}" data-kb-disabled="${n?`1`:`0`}"${n?` title="${j(t(`knowledgeSelector.disabledTooltip`))}"`:``}>
420
420
  <span class="input-add-panel-item-title">📚 ${k(e.name||``)}${n?` <span class="knowledge-item-badge badge-disabled">${t(`knowledgeSelector.disabledBadge`)}</span>`:``}</span>
421
421
  <span class="input-add-panel-item-sub">${k(r)}</span>
422
- </div>`}case`agents`:{let n=Xt(e),r=Yn(e),i=e.id===v.activeAgentId||!v.activeAgentId&&e.id==="default",a=e.toolIds?e.toolIds.length:e.toolIds===null?null:0,o=a===null?t(`promptSelector.inheritGlobal`):t(`promptSelector.toolCount`,{count:a});return`<div class="prompt-item input-add-panel-item input-add-panel-item-two-line" data-agent-id="${k(e.id)}">
422
+ </div>`}case`agents`:{let n=Kn(e),r=Xt(e),i=e.id===v.activeAgentId||!v.activeAgentId&&e.id==="default",a=e.toolIds?e.toolIds.length:e.toolIds===null?null:0,o=a===null?t(`promptSelector.inheritGlobal`):t(`promptSelector.toolCount`,{count:a});return`<div class="prompt-item input-add-panel-item input-add-panel-item-two-line" data-agent-id="${k(e.id)}">
423
423
  <span class="input-add-panel-item-title">${k([e.icon,n].filter(Boolean).join(` `))}</span>
424
424
  <span class="input-add-panel-item-sub">${k(r||o)}</span>
425
425
  ${i?`<span class="input-add-panel-item-mark">✓</span>`:``}
426
- </div>`}case`proxies`:{let n=e.name||t(`promptSelector.unnamedProxy`),r=Kn(e),i=r?r.online:!1;return`<div class="prompt-item prompt-item-proxy input-add-panel-item input-add-panel-item-two-line${e.isDisabled?` agent-disabled`:``}" data-proxy-id="${k(e.id)}">
427
- <span class="input-add-panel-item-title"><span class="agent-at-dot agent-at-dot-${Kt(e,i)}"></span>${k(n)}</span>
426
+ </div>`}case`proxies`:{let n=e.name||t(`promptSelector.unnamedProxy`),r=$n(e),i=r?r.online:!1;return`<div class="prompt-item prompt-item-proxy input-add-panel-item input-add-panel-item-two-line${e.isDisabled?` agent-disabled`:``}" data-proxy-id="${k(e.id)}">
427
+ <span class="input-add-panel-item-title"><span class="agent-at-dot agent-at-dot-${sn(e,i)}"></span>${k(n)}</span>
428
428
  <span class="input-add-panel-item-sub">${k(e.url||``)}</span>
429
429
  ${e.isActive?`<span class="input-add-panel-item-mark">✓</span>`:``}
430
430
  </div>`}case`workspace`:{let t=e.type===`directory`;return`<div class="prompt-item input-add-panel-item" data-path="${k(e.fullPath)}" title="${j(e.fullPath)}">
431
- <span class="input-add-panel-item-icon">${aa(e.name,e.type)}</span>
431
+ <span class="input-add-panel-item-icon">${oa(e.name,e.type)}</span>
432
432
  <span class="input-add-panel-item-title">${k(e.name)}${t?`/`:``}</span>
433
- ${!t&&e.size!=null?`<span class="input-add-panel-item-sub">${k(ia(e.size))}</span>`:``}
433
+ ${!t&&e.size!=null?`<span class="input-add-panel-item-sub">${k(aa(e.size))}</span>`:``}
434
434
  </div>`}case`screenshot`:return`<div class="prompt-item input-add-panel-item input-add-panel-item-two-line" data-shot-action="${e.action}">
435
435
  <span class="input-add-panel-item-title">${e.icon} ${k(t(e.nameKey))}</span>
436
436
  <span class="input-add-panel-item-sub">${k(t(e.descKey))}</span>
437
437
  <kbd class="input-add-panel-item-kbd">${k(e.kbd)}</kbd>
438
- </div>`;default:return``}}async function wf(e,t){let n=e.ctrlKey||e.metaKey;switch(X){case`prompts`:{let e=t.dataset.code;n?Jr(e,{skipTriggerStrip:!0}):bt(e),af();break}case`skills`:qi(t.dataset.skillName,nf,{clearTrigger:!1}),n&&af();break;case`mcp`:Fi(t.dataset.serverId,t.dataset.serverName,nf,{clearTrigger:!1}),n&&af();break;case`pages`:{let e=nf.find(e=>String(e.id)===t.dataset.tabId);if(e){en(e);let t=document.getElementById(`userInput`);t&&t.focus(),rt()}af();break}case`knowledge`:sr({id:t.dataset.kbId,name:t.dataset.kbName,enabled:t.dataset.kbDisabled!==`1`},{clearTrigger:!1}),n&&af();break;case`agents`:await tr(t.dataset.agentId,{clearTrigger:!1}),af();break;case`proxies`:await An(t.dataset.proxyId,{clearTrigger:!1}),af();break;case`workspace`:{let e=nf.find(e=>e.fullPath===t.dataset.path);if(e){let t=document.getElementById(`userInput`);t&&t.focus(),await si([e]),rt()}af();break}case`screenshot`:af(),await(t.dataset.shotAction===`region`?$r:br)();break;default:break}}var Tf=0,Ef=200,Df=150,Of={promptTriggerBtn:`prompts`,addMenuSkillBtn:`skills`,addMenuMcpBtn:`mcp`,addMenuPageBtn:`pages`,addMenuKnowledgeBtn:`knowledge`,addMenuAgentBtn:`agents`,addMenuProxyBtn:`proxies`,addMenuWorkspaceBtn:`workspace`,screenshotBtn:`screenshot`};async function kf(){let e=[{id:`addMenuSkillBtn`,available:()=>Ui()},{id:`addMenuMcpBtn`,available:()=>gr()},{id:`addMenuKnowledgeBtn`,available:async()=>(await Dt()).ok},{id:`addMenuProxyBtn`,available:async()=>(await Qn()).length>0},{id:`addMenuWorkspaceBtn`,available:async()=>!!await oa()}],t=++Tf;await Promise.all(e.map(async({id:e,available:n})=>{let r=document.getElementById(e);if(!r)return;let i=!0;try{i=await n()}catch{i=!0}t===Tf&&(r.style.display=i?``:`none`)}))}function Af(){let e=document.getElementById(`inputAddBtn`),t=document.getElementById(`inputAddMenu`);if(!e||!t)return;let n=e.closest(`.input-add-wrapper`),r=t.querySelector(`.input-add-nav`),i=null,a=null,o=!1,s=()=>{let e=mf()?hf():null;t.querySelectorAll(`.input-add-item`).forEach(t=>{t.classList.toggle(`panel-active`,!!e&&Of[t.id]===e)})},c=e=>{let n=document.getElementById(`inputAddPanel`);if(!n||n.style.display===`none`)return;n.style.left=``;let r=t.getBoundingClientRect(),i=n.getBoundingClientRect(),a=r.right+8;a+i.width>window.innerWidth-8&&(a=window.innerWidth-8-i.width),a<8&&(a=8),n.style.left=`${Math.round(a-r.left)}px`;let o=e||t.querySelector(`.input-add-item.panel-active`),s=(o?o.getBoundingClientRect():r).top;s+i.height>r.bottom&&(s=r.bottom-i.height),s<8&&(s=8),n.style.top=`${Math.round(s-r.top-t.clientTop)}px`},l=n=>{t.style.display=n?``:`none`,e.classList.toggle(`open`,n),e.setAttribute(`aria-expanded`,String(n)),n?(vf(),s(),kf()):(i&&=(clearTimeout(i),null),a&&=(clearTimeout(a),null),vf(),s())},u=()=>t.style.display!==`none`;ff({onRequestClose:()=>l(!1)}),e.addEventListener(`click`,e=>{e.stopPropagation();let t=!u();t&&(Mt(),sn(),Gd()),l(t)}),t.addEventListener(`click`,e=>{e.target.closest&&e.target.closest(`.input-add-item`)&&l(!1)},!0),document.addEventListener(`click`,e=>{u()&&(n&&n.contains(e.target)||l(!1))});let d=()=>{i&&=(clearTimeout(i),null),a&&clearTimeout(a),a=setTimeout(()=>{a=null,!gf()&&(vf(),s())},Df)};r&&r.addEventListener(`mouseover`,e=>{if(!u())return;let t=e.target.closest(`.input-add-item`),n=t?Of[t.id]:null;if(!n){d();return}a&&=(clearTimeout(a),null),!(mf()&&hf()===n)&&(i&&clearTimeout(i),i=setTimeout(async()=>{i=null;let e=_f(n);c(t);try{await e}catch{}c(t),s()},Ef))}),t.addEventListener(`mouseenter`,()=>{o=!0,a&&=(clearTimeout(a),null)}),t.addEventListener(`mouseleave`,()=>{o=!1,d()});let f=document.getElementById(`inputAddPanelSearch`);f&&f.addEventListener(`blur`,()=>{o||d()}),window.addEventListener(`resize`,()=>{mf()&&c()}),[{id:`promptTriggerBtn`,open:()=>fn(``,`prompts`)},{id:`addMenuSkillBtn`,open:()=>fn(``,`skills`)},{id:`addMenuMcpBtn`,open:()=>fn(``,`mcp`)},{id:`addMenuPageBtn`,open:()=>yt(``,`pages`)},{id:`addMenuKnowledgeBtn`,open:()=>yt(``,`knowledge`)},{id:`addMenuAgentBtn`,open:()=>yt(``,`agents`)},{id:`addMenuProxyBtn`,open:()=>yt(``,`proxies`)},{id:`addMenuWorkspaceBtn`,open:()=>Wd(``)}].forEach(({id:e,open:t})=>{let n=document.getElementById(e);n&&n.addEventListener(`click`,async e=>{e.stopPropagation(),n.blur(),Mt(),sn(),Gd();try{await t()}catch{}let r=document.getElementById(`userInput`);r&&r.focus()})});let p=document.getElementById(`inputAddMenuSwitches`),m=()=>{let t=p?.querySelector(`input[type="checkbox"]`);e.classList.toggle(`has-active-switch`,!!(t&&t.checked))};p&&(typeof MutationObserver<`u`&&new MutationObserver(m).observe(p,{subtree:!0,childList:!0}),p.addEventListener(`change`,m)),m()}var jf=`usageTipsEnabled`,Mf=8e3;e(`zh`,{usageTips:{dismiss:`不再显示`,dismissedHint:`已关闭使用技巧提示。想重新看到:设置 → 基础 → 打开「使用技巧提示」`}}),e(`en`,{usageTips:{dismiss:`Don't show again`,dismissedHint:`Tips hidden. To bring them back: Settings → Basic → enable "Usage tips".`}});var Nf=[{id:`slash`,scene:`plugin`,zh:`输入「/」唤起快捷提示,用方向键选择提示词、技能或 MCP,回车直接套用。`,en:`Type "/" to open quick prompts, pick a prompt, skill, or MCP with arrow keys and press Enter.`},{id:`at-page`,scene:`plugin`,zh:`输入「@」可引用当前网页,让 AI 直接基于页面内容回答。`,en:`Type "@" to reference the current page so the AI answers from that content.`},{id:`at-agent`,scene:`plugin`,zh:`「@助手」可以切换不同角色,为不同任务准备不同的身份、提示词与工具。`,en:`"@Assistant" switches roles, giving each task its own persona, prompt, and tool set.`},{id:`history`,scene:`plugin`,zh:`在输入框按「↑ / ↓」翻看历史输入,按 Esc 一键清空当前内容。`,en:`Press ↑ / ↓ in the input box to browse input history, and Esc to clear the current content.`},{id:`goal`,scene:`plugin`,zh:`把目标写成「帮我完成…」,目标模式会自动拆解步骤并持续推进直到达成。`,en:`Write the goal as "Help me finish…" and Goal mode will break it into steps and keep pushing until done.`},{id:`queue`,scene:`plugin`,zh:`任务执行中仍可继续输入,消息会进入队列,不会打断当前任务。`,en:`You can keep typing while a task runs; new messages queue up without interrupting the current task.`},{id:`queue-carry`,scene:`plugin`,zh:`排队时点消息旁的「⚡」,可把队首消息顺带进当前任务,减少来回切换。`,en:`Click "⚡" beside a queued message to fold it into the running task and avoid context switching.`},{id:`prompt-clarify`,scene:`plugin`,zh:`提问时补上背景、目标与限制条件,比只给一句话得到的结果稳定得多。`,en:`Include background, goal, and constraints in your request; results are far more reliable than one-liners.`},{id:`prompt-plan`,scene:`plugin`,zh:`复杂任务先让 AI 列计划:「先给方案,我确认后再动手」,能少走很多弯路。`,en:`For complex work, ask for a plan first: "Propose a plan, then act after I confirm."`},{id:`prompt-split`,scene:`plugin`,zh:`一次只让 AI 做一件事,把大任务拆成小步,成功率更高也更好检查。`,en:`Give the AI one job at a time; splitting big tasks into steps improves success and reviewability.`},{id:`selection`,scene:`plugin`,zh:`在网页上划词后点浮动按钮,可以针对选中的内容单独提问。`,en:`Select text on a page and click the floating button to ask about just that selection.`},{id:`voice`,scene:`plugin`,zh:`点麦克风用语音输入,说完自动转成文字,长问题不必手打。`,en:`Use the mic for voice input: speech is transcribed automatically, so long questions need no typing.`},{id:`image`,scene:`plugin`,zh:`图片可以直接粘贴或拖进输入框,AI 会看图后再回答。`,en:`Paste or drag images into the input box; the AI will look at them before answering.`},{id:`file`,scene:`plugin`,zh:`支持上传 PDF、Word、Excel 等文件,AI 会先提取内容再作答。`,en:`Upload PDF, Word, or Excel files; the AI extracts their content first, then answers.`},{id:`knowledge`,scene:`plugin`,zh:`用「@知识库」引用私有资料,回答会更贴合你的业务与术语。`,en:`Reference private material with "@Knowledge base" to make answers fit your business and terminology.`},{id:`compaction`,scene:`plugin`,zh:`长对话可在基础配置开启自动压缩,上下文接近上限时自动摘要,省 token。`,en:`Enable auto-compaction in Basic settings: near the context limit, long chats are summarized to save tokens.`},{id:`session`,scene:`plugin`,zh:`重要对话可收藏、搜索和导出;也可直接说「搜一下我们以前聊过的 xxx」。`,en:`Bookmark, search, and export important chats; you can also say "Search our past chats for xxx".`},{id:`todo`,scene:`plugin`,zh:`说「帮我加个待办:周五前交方案」,AI 会直接写入待办面板,也能查询、改优先级或标记完成。`,en:`Say "Add a todo: send the proposal by Friday" and the AI writes it into the To-do panel; it can also list, reprioritize, or complete items.`},{id:`todo-remind`,scene:`plugin`,zh:`「待办」本身不会提醒;说「到时间提醒我看这条待办」,AI 会顺手补建一个定时任务。`,en:`Todos do not remind you by themselves; say "Remind me about this todo at that time" and the AI adds a scheduled task.`},{id:`schedule`,scene:`plugin`,zh:`定时任务可直接用对话管理:说「每周一 9 点整理上周数据」,AI 会创建并按点执行,结果写回会话。`,en:`Manage scheduled tasks by chat: say "Every Monday 9am summarize last week" and the AI creates it, runs on time, and posts the result here.`},{id:`schedule-manage`,scene:`plugin`,zh:`说「列出 / 暂停 / 立即执行我的定时任务」,AI 会直接查询并处理,删除前仍会先确认。`,en:`Say "List / pause / run my scheduled tasks now" and the AI queries and handles them, asking before any deletion.`},{id:`tabs`,scene:`plugin`,zh:`说「打开这三个链接,把重复的标签页关掉」,AI 能打开、切换、关闭和刷新标签页。`,en:`Say "Open these three links and close duplicate tabs" and the AI can open, switch, close, and refresh tabs.`},{id:`bookmarks`,scene:`plugin`,zh:`说「找一下我收藏过的 xx」,AI 会检索浏览器书签与历史记录,直接给出链接。`,en:`Say "Find the xx I bookmarked" and the AI searches bookmarks and history, returning the links.`},{id:`extract-data`,scene:`plugin`,zh:`说「把这页的表格整理成 CSV」,AI 会抽取页面上的结构化数据,方便继续加工。`,en:`Say "Turn this page's table into CSV" and the AI extracts structured page data for further use.`},{id:`download`,scene:`plugin`,zh:`说「把这些图片批量下载下来」,AI 会把文件直接保存到本机。`,en:`Say "Download these images" and the AI saves the files to your computer.`},{id:`memory`,scene:`plugin`,zh:`说「帮我记一下…」即存入记忆,需要时问「你还记得…吗」,跨会话都有效。`,en:`Say "Remember this…" to save it; ask "Do you remember…?" later — memory persists across sessions.`},{id:`custom-prompt`,scene:`plugin`,zh:`把常用指令存成自定义提示词,下次用「/」一键调用。`,en:`Save frequent instructions as custom prompts and recall them with "/" next time.`},{id:`kb-ingest`,scene:`plugin`,zh:`说「把这份资料存到知识库」,AI 会自动切分并入库,之后可直接检索。`,en:`Say "Save this into the knowledge base" and the AI chunks and ingests it for later retrieval.`},{id:`clipboard`,scene:`plugin`,zh:`说「把结果复制到剪贴板」,AI 会直接写入,省去手动选中复制。`,en:`Say "Copy the result to my clipboard" and the AI writes it for you.`},{id:`page-highlight`,scene:`plugin`,zh:`说「在页面上高亮 xxx」,AI 会把关键内容标出来,方便讲解或核对。`,en:`Say "Highlight xxx on the page" to mark key content for explanation or review.`},{id:`capture`,scene:`plugin`,zh:`说「截图并分析这个页面」,AI 会截图后交给视觉模型解读图表或界面。`,en:`Say "Screenshot and analyze this page" to have the vision model read charts or UI.`},{id:`preview-ui`,scene:`plugin`,zh:`说「做个界面原型给我看看」,AI 会在侧边栏直接渲染可预览的 HTML。`,en:`Say "Show me a UI prototype" and the AI renders previewable HTML in the side panel.`},{id:`form-fill`,scene:`plugin`,zh:`说「帮我填一下这个表单」,AI 能一次批量填入多个字段。`,en:`Say "Fill out this form" and the AI can fill multiple fields in one go.`},{id:`browser-act`,scene:`plugin`,zh:`说「打开这个链接并帮我点…」,AI 能自动开标签页、点击、输入和翻页。`,en:`Say "Open this link and click …" and the AI can open tabs, click, type, and scroll.`},{id:`clarify`,scene:`plugin`,zh:`加上「拿不准就先问我」,AI 会先给出选项确认,避免理解跑偏。`,en:`Add "Ask me first if unsure" and the AI confirms with options before proceeding.`},{id:`dispatch`,scene:`plugin`,zh:`说「这几件事并行处理」,AI 会拆给子代理并发执行,大任务更快。`,en:`Say "Handle these in parallel" and the AI dispatches sub-agents concurrently.`},{id:`qrcode`,scene:`plugin`,zh:`说「把这个链接生成二维码」,AI 会自动生成并展示出来。`,en:`Say "Turn this link into a QR code" and the AI generates and shows it.`},{id:`notify`,scene:`plugin`,zh:`说「做完后提醒我」,AI 会用桌面通知告知结果,不必一直盯着。`,en:`Say "Notify me when done" and the AI sends a desktop notification.`},{id:`fetch`,scene:`plugin`,zh:`说「帮我抓取这个接口的数据」,AI 可发起 HTTP 请求并整理返回结果。`,en:`Say "Fetch the data from this API" and the AI can send an HTTP request and organize the result.`},{id:`agent-hint`,scene:`plugin`,zh:`连接代理端后,可解锁本机文件读写、命令执行等能力(设置 → 代理页配对)。`,en:`Connecting the agent unlocks local file access and command execution (Settings → Agent to pair).`},{id:`agent-file`,scene:`agent`,zh:`已连接代理端:AI 可以读写你电脑上的文件,直接说「帮我改这个文件」即可。`,en:`Agent connected: the AI can read and write files on your computer — just say "update this file".`},{id:`agent-exec`,scene:`agent`,zh:`已连接代理端:AI 可以执行本机命令、运行脚本,适合构建、测试与批处理。`,en:`Agent connected: the AI can run local commands and scripts for builds, tests, and batch jobs.`},{id:`agent-search`,scene:`agent`,zh:`让 AI「在项目里搜索 xxx」,它会用本机搜索定位代码,比网页检索更准。`,en:`Ask the AI to "search the project for xxx"; local search finds code more accurately than the web.`},{id:`agent-workdir`,scene:`agent`,zh:`在工作目录面板切换目录,AI 的文件操作都会被限制在这个范围内。`,en:`Switch directories in the workspace panel; the AI confinement keeps file operations inside that scope.`},{id:`agent-confirm`,scene:`agent`,zh:`敏感操作会先弹确认,可在基础配置里调整确认策略,兼顾安全与效率。`,en:`Sensitive actions ask for confirmation first; adjust the policy in Basic settings to balance safety and speed.`},{id:`agent-log`,scene:`agent`,zh:`命令执行日志可在日志面板查看;也可说「调出执行日志复盘」,让 AI 提取成功路径与失败教训。`,en:`Review commands in the log panel, or say "Review the execution log" to extract successful paths and lessons.`},{id:`agent-stream`,scene:`agent`,zh:`长命令支持流式输出,执行过程实时可见,不用盯着空白等待。`,en:`Long commands stream their output, so progress is visible in real time instead of a blank wait.`},{id:`agent-multi`,scene:`agent`,zh:`配对了多台电脑时,用「@代理」指定目标,也可以说「切换到另一台电脑的代理」。`,en:`With multiple computers, use "@Agent" to pick one, or just say "Switch to the agent on another computer".`},{id:`agent-offline`,scene:`agent`,zh:`代理端离线时,文件与命令类能力会自动隐藏,避免误发无法执行的任务。`,en:`When the agent is offline, file and command abilities are hidden so tasks are not sent in vain.`},{id:`agent-update`,scene:`agent`,zh:`代理端可在设置 → 代理页一键更新或重启,版本不一致时优先升级。`,en:`Update or restart the agent from Settings → Agent; upgrade first when versions differ.`},{id:`agent-skill`,scene:`agent`,zh:`说「跑一下这个工作流技能」,代理端会执行对应的 Skill。`,en:`Say "Run this workflow skill" and the agent executes the matching Skill.`},{id:`agent-skill-create`,scene:`agent`,zh:`说「把刚才的流程沉淀成技能」,AI 会写成 SKILL.md,下次一句话即可复用。`,en:`Say "Turn that process into a skill" and the AI writes a SKILL.md for one-line reuse next time.`},{id:`agent-trash`,scene:`agent`,zh:`说「从回收站恢复刚删的文件」,代理端可以直接恢复。`,en:`Say "Restore the file I just deleted" and the agent can recover it from its trash.`},{id:`agent-download`,scene:`agent`,zh:`说「把这个文件下载到浏览器」,代理端文件会直接下载到本机。`,en:`Say "Download this file to the browser" and the agent transfers it locally.`}],Z=null,Pf=null,Ff=null,If=null,Lf=null,Rf=!1,zf=null,Bf=!0,Vf=null;function Hf(){return v.agentPlatform?.connected===!0}function Uf(){let e=a();return Nf.filter(e=>e.scene!==`agent`||Hf()).map(t=>({id:t.id,text:e===`en`?t.en:t.zh}))}function Wf(e){let t=e.findIndex(e=>e.id===zf);return t>=0?t:0}function Gf(){if(!Z||!Pf)return;let e=Pf.scrollWidth>Pf.clientWidth+1;Z.classList.toggle(`is-truncated`,e)}function Kf(e,t){if(!Pf||!e.length)return;let n=e[t%e.length];zf=n.id,Pf.textContent=n.text,Ff&&(Ff.textContent=n.text),Gf(),Pf.classList.remove(`fade-in`),Pf.offsetWidth,Pf.classList.add(`fade-in`)}function qf(){if(!Bf||!Z||Z.style.display===`none`)return;let e=Uf();e.length&&Kf(e,Wf(e)+1)}function Jf(){Lf&&=(clearInterval(Lf),null)}function Yf(){Jf(),!(!Bf||Rf)&&(Lf=setInterval(qf,Mf))}function Xf(){if(!Bf||!Z)return;let e=Uf();if(!e.length){Qf();return}e.some(e=>e.id===zf)?Kf(e,Wf(e)):(zf=null,Kf(e,0))}function Zf(){if(!Z)return;Bf=!0,Z.style.display=``;let e=Uf();if(!e.length){Qf();return}Kf(e,Wf(e)),Yf()}function Qf(){Z&&(Z.style.display=`none`,Jf())}function $f(){Z.addEventListener(`mouseenter`,()=>{Rf=!0,Jf()}),Z.addEventListener(`mouseleave`,()=>{Rf=!1,Yf()}),If.addEventListener(`click`,e=>{e.stopPropagation(),ep(),A(t(`usageTips.dismissedHint`),`info`,5e3)}),chrome.storage.onChanged.addListener((e,t)=>{t!==`local`||!e[jf]||(e[jf].newValue===!1?(Bf=!1,Qf()):Zf())}),document.addEventListener(`agent-connection-changed`,Xf),o(Xf),typeof ResizeObserver<`u`&&new ResizeObserver(Gf).observe(Z)}function ep(){Bf=!1,Qf();try{chrome.storage.local.set({[jf]:!1})}catch{}}function tp(){if(Z=document.getElementById(`usageTipsBar`),Pf=document.getElementById(`usageTipsText`),Ff=document.getElementById(`usageTipsTooltip`),If=document.getElementById(`usageTipsDismiss`),!(!Z||!Pf||!Ff||!If)){$f(),Vf=document.getElementById(`chatContainer`),Vf&&(Vf.appendChild(Z),typeof MutationObserver<`u`&&new MutationObserver(()=>{Vf.querySelectorAll(`.usage-tips-bar`).forEach(e=>{e!==Z&&e.remove()}),(Z.parentNode!==Vf||Z.nextElementSibling)&&Vf.appendChild(Z)}).observe(Vf,{childList:!0}));try{chrome.storage.local.get([jf],e=>{Bf=e?.[jf]!==!1,Bf?Zf():Qf()})}catch{Zf()}}}function np({key:e,value:t=``,caret:n,history:r=[],index:i=-1}={}){if(e!==`ArrowUp`&&e!==`ArrowDown`||!Array.isArray(r)||r.length===0)return{handled:!1};let a=String(t??``),o=Number.isInteger(n)&&n>=0?n:a.length,s=Number.isInteger(i)&&i>=0;if(e===`ArrowUp`){let e=a.lastIndexOf(`
438
+ </div>`;default:return``}}async function Tf(e,t){let n=e.ctrlKey||e.metaKey;switch(X){case`prompts`:{let e=t.dataset.code;n?Yr(e,{skipTriggerStrip:!0}):bt(e),of();break}case`skills`:Ji(t.dataset.skillName,rf,{clearTrigger:!1}),n&&of();break;case`mcp`:Li(t.dataset.serverId,t.dataset.serverName,rf,{clearTrigger:!1}),n&&of();break;case`pages`:{let e=rf.find(e=>String(e.id)===t.dataset.tabId);if(e){dn(e);let t=document.getElementById(`userInput`);t&&t.focus(),rt()}of();break}case`knowledge`:An({id:t.dataset.kbId,name:t.dataset.kbName,enabled:t.dataset.kbDisabled!==`1`},{clearTrigger:!1}),n&&of();break;case`agents`:await cr(t.dataset.agentId,{clearTrigger:!1}),of();break;case`proxies`:await yt(t.dataset.proxyId,{clearTrigger:!1}),of();break;case`workspace`:{let e=rf.find(e=>e.fullPath===t.dataset.path);if(e){let t=document.getElementById(`userInput`);t&&t.focus(),await Si([e]),rt()}of();break}case`screenshot`:of(),await(t.dataset.shotAction===`region`?Pi:ei)();break;default:break}}var Ef=0,Df=200,Of=150,kf={promptTriggerBtn:`prompts`,addMenuSkillBtn:`skills`,addMenuMcpBtn:`mcp`,addMenuPageBtn:`pages`,addMenuKnowledgeBtn:`knowledge`,addMenuAgentBtn:`agents`,addMenuProxyBtn:`proxies`,addMenuWorkspaceBtn:`workspace`,screenshotBtn:`screenshot`};async function Af(){let e=[{id:`addMenuSkillBtn`,available:()=>Gi()},{id:`addMenuMcpBtn`,available:()=>_r()},{id:`addMenuKnowledgeBtn`,available:async()=>(await Yn()).ok},{id:`addMenuProxyBtn`,available:async()=>(await Kt()).length>0},{id:`addMenuWorkspaceBtn`,available:async()=>!!await sa()}],t=++Ef;await Promise.all(e.map(async({id:e,available:n})=>{let r=document.getElementById(e);if(!r)return;let i=!0;try{i=await n()}catch{i=!0}t===Ef&&(r.style.display=i?``:`none`)}))}function jf(){let e=document.getElementById(`inputAddBtn`),t=document.getElementById(`inputAddMenu`);if(!e||!t)return;let n=e.closest(`.input-add-wrapper`),r=t.querySelector(`.input-add-nav`),i=null,a=null,o=!1,s=()=>{let e=hf()?gf():null;t.querySelectorAll(`.input-add-item`).forEach(t=>{t.classList.toggle(`panel-active`,!!e&&kf[t.id]===e)})},c=e=>{let n=document.getElementById(`inputAddPanel`);if(!n||n.style.display===`none`)return;n.style.left=``;let r=t.getBoundingClientRect(),i=n.getBoundingClientRect(),a=r.right+8;a+i.width>window.innerWidth-8&&(a=window.innerWidth-8-i.width),a<8&&(a=8),n.style.left=`${Math.round(a-r.left)}px`;let o=e||t.querySelector(`.input-add-item.panel-active`),s=(o?o.getBoundingClientRect():r).top;s+i.height>r.bottom&&(s=r.bottom-i.height),s<8&&(s=8),n.style.top=`${Math.round(s-r.top-t.clientTop)}px`},l=n=>{t.style.display=n?``:`none`,e.classList.toggle(`open`,n),e.setAttribute(`aria-expanded`,String(n)),n?(yf(),s(),Af()):(i&&=(clearTimeout(i),null),a&&=(clearTimeout(a),null),yf(),s())},u=()=>t.style.display!==`none`;pf({onRequestClose:()=>l(!1)}),e.addEventListener(`click`,e=>{e.stopPropagation();let t=!u();t&&(Mt(),bi(),qd()),l(t)}),t.addEventListener(`click`,e=>{e.target.closest&&e.target.closest(`.input-add-item`)&&l(!1)},!0),document.addEventListener(`click`,e=>{u()&&(n&&n.contains(e.target)||l(!1))});let d=()=>{i&&=(clearTimeout(i),null),a&&clearTimeout(a),a=setTimeout(()=>{a=null,!_f()&&(yf(),s())},Of)};r&&r.addEventListener(`mouseover`,e=>{if(!u())return;let t=e.target.closest(`.input-add-item`),n=t?kf[t.id]:null;if(!n){d();return}a&&=(clearTimeout(a),null),!(hf()&&gf()===n)&&(i&&clearTimeout(i),i=setTimeout(async()=>{i=null;let e=vf(n);c(t);try{await e}catch{}c(t),s()},Df))}),t.addEventListener(`mouseenter`,()=>{o=!0,a&&=(clearTimeout(a),null)}),t.addEventListener(`mouseleave`,()=>{o=!1,d()});let f=document.getElementById(`inputAddPanelSearch`);f&&f.addEventListener(`blur`,()=>{o||d()}),window.addEventListener(`resize`,()=>{hf()&&c()}),[{id:`promptTriggerBtn`,open:()=>fn(``,`prompts`)},{id:`addMenuSkillBtn`,open:()=>fn(``,`skills`)},{id:`addMenuMcpBtn`,open:()=>fn(``,`mcp`)},{id:`addMenuPageBtn`,open:()=>Or(``,`pages`)},{id:`addMenuKnowledgeBtn`,open:()=>Or(``,`knowledge`)},{id:`addMenuAgentBtn`,open:()=>Or(``,`agents`)},{id:`addMenuProxyBtn`,open:()=>Or(``,`proxies`)},{id:`addMenuWorkspaceBtn`,open:()=>Kd(``)}].forEach(({id:e,open:t})=>{let n=document.getElementById(e);n&&n.addEventListener(`click`,async e=>{e.stopPropagation(),n.blur(),Mt(),bi(),qd();try{await t()}catch{}let r=document.getElementById(`userInput`);r&&r.focus()})});let p=document.getElementById(`inputAddMenuSwitches`),m=()=>{let t=p?.querySelector(`input[type="checkbox"]`);e.classList.toggle(`has-active-switch`,!!(t&&t.checked))};p&&(typeof MutationObserver<`u`&&new MutationObserver(m).observe(p,{subtree:!0,childList:!0}),p.addEventListener(`change`,m)),m()}var Mf=`usageTipsEnabled`,Nf=8e3;e(`zh`,{usageTips:{dismiss:`不再显示`,dismissedHint:`已关闭使用技巧提示。想重新看到:设置 → 基础 → 打开「使用技巧提示」`}}),e(`en`,{usageTips:{dismiss:`Don't show again`,dismissedHint:`Tips hidden. To bring them back: Settings → Basic → enable "Usage tips".`}});var Pf=[{id:`slash`,scene:`plugin`,zh:`输入「/」唤起快捷提示,用方向键选择提示词、技能或 MCP,回车直接套用。`,en:`Type "/" to open quick prompts, pick a prompt, skill, or MCP with arrow keys and press Enter.`},{id:`at-page`,scene:`plugin`,zh:`输入「@」可引用当前网页,让 AI 直接基于页面内容回答。`,en:`Type "@" to reference the current page so the AI answers from that content.`},{id:`at-agent`,scene:`plugin`,zh:`「@助手」可以切换不同角色,为不同任务准备不同的身份、提示词与工具。`,en:`"@Assistant" switches roles, giving each task its own persona, prompt, and tool set.`},{id:`history`,scene:`plugin`,zh:`在输入框按「↑ / ↓」翻看历史输入,按 Esc 一键清空当前内容。`,en:`Press ↑ / ↓ in the input box to browse input history, and Esc to clear the current content.`},{id:`goal`,scene:`plugin`,zh:`把目标写成「帮我完成…」,目标模式会自动拆解步骤并持续推进直到达成。`,en:`Write the goal as "Help me finish…" and Goal mode will break it into steps and keep pushing until done.`},{id:`queue`,scene:`plugin`,zh:`任务执行中仍可继续输入,消息会进入队列,不会打断当前任务。`,en:`You can keep typing while a task runs; new messages queue up without interrupting the current task.`},{id:`queue-carry`,scene:`plugin`,zh:`排队时点消息旁的「⚡」,可把队首消息顺带进当前任务,减少来回切换。`,en:`Click "⚡" beside a queued message to fold it into the running task and avoid context switching.`},{id:`prompt-clarify`,scene:`plugin`,zh:`提问时补上背景、目标与限制条件,比只给一句话得到的结果稳定得多。`,en:`Include background, goal, and constraints in your request; results are far more reliable than one-liners.`},{id:`prompt-plan`,scene:`plugin`,zh:`复杂任务先让 AI 列计划:「先给方案,我确认后再动手」,能少走很多弯路。`,en:`For complex work, ask for a plan first: "Propose a plan, then act after I confirm."`},{id:`prompt-split`,scene:`plugin`,zh:`一次只让 AI 做一件事,把大任务拆成小步,成功率更高也更好检查。`,en:`Give the AI one job at a time; splitting big tasks into steps improves success and reviewability.`},{id:`selection`,scene:`plugin`,zh:`在网页上划词后点浮动按钮,可以针对选中的内容单独提问。`,en:`Select text on a page and click the floating button to ask about just that selection.`},{id:`voice`,scene:`plugin`,zh:`点麦克风用语音输入,说完自动转成文字,长问题不必手打。`,en:`Use the mic for voice input: speech is transcribed automatically, so long questions need no typing.`},{id:`image`,scene:`plugin`,zh:`图片可以直接粘贴或拖进输入框,AI 会看图后再回答。`,en:`Paste or drag images into the input box; the AI will look at them before answering.`},{id:`file`,scene:`plugin`,zh:`支持上传 PDF、Word、Excel 等文件,AI 会先提取内容再作答。`,en:`Upload PDF, Word, or Excel files; the AI extracts their content first, then answers.`},{id:`knowledge`,scene:`plugin`,zh:`用「@知识库」引用私有资料,回答会更贴合你的业务与术语。`,en:`Reference private material with "@Knowledge base" to make answers fit your business and terminology.`},{id:`compaction`,scene:`plugin`,zh:`长对话可在基础配置开启自动压缩,上下文接近上限时自动摘要,省 token。`,en:`Enable auto-compaction in Basic settings: near the context limit, long chats are summarized to save tokens.`},{id:`session`,scene:`plugin`,zh:`重要对话可收藏、搜索和导出;也可直接说「搜一下我们以前聊过的 xxx」。`,en:`Bookmark, search, and export important chats; you can also say "Search our past chats for xxx".`},{id:`todo`,scene:`plugin`,zh:`说「帮我加个待办:周五前交方案」,AI 会直接写入待办面板,也能查询、改优先级或标记完成。`,en:`Say "Add a todo: send the proposal by Friday" and the AI writes it into the To-do panel; it can also list, reprioritize, or complete items.`},{id:`todo-remind`,scene:`plugin`,zh:`「待办」本身不会提醒;说「到时间提醒我看这条待办」,AI 会顺手补建一个定时任务。`,en:`Todos do not remind you by themselves; say "Remind me about this todo at that time" and the AI adds a scheduled task.`},{id:`schedule`,scene:`plugin`,zh:`定时任务可直接用对话管理:说「每周一 9 点整理上周数据」,AI 会创建并按点执行,结果写回会话。`,en:`Manage scheduled tasks by chat: say "Every Monday 9am summarize last week" and the AI creates it, runs on time, and posts the result here.`},{id:`schedule-manage`,scene:`plugin`,zh:`说「列出 / 暂停 / 立即执行我的定时任务」,AI 会直接查询并处理,删除前仍会先确认。`,en:`Say "List / pause / run my scheduled tasks now" and the AI queries and handles them, asking before any deletion.`},{id:`tabs`,scene:`plugin`,zh:`说「打开这三个链接,把重复的标签页关掉」,AI 能打开、切换、关闭和刷新标签页。`,en:`Say "Open these three links and close duplicate tabs" and the AI can open, switch, close, and refresh tabs.`},{id:`bookmarks`,scene:`plugin`,zh:`说「找一下我收藏过的 xx」,AI 会检索浏览器书签与历史记录,直接给出链接。`,en:`Say "Find the xx I bookmarked" and the AI searches bookmarks and history, returning the links.`},{id:`extract-data`,scene:`plugin`,zh:`说「把这页的表格整理成 CSV」,AI 会抽取页面上的结构化数据,方便继续加工。`,en:`Say "Turn this page's table into CSV" and the AI extracts structured page data for further use.`},{id:`download`,scene:`plugin`,zh:`说「把这些图片批量下载下来」,AI 会把文件直接保存到本机。`,en:`Say "Download these images" and the AI saves the files to your computer.`},{id:`memory`,scene:`plugin`,zh:`说「帮我记一下…」即存入记忆,需要时问「你还记得…吗」,跨会话都有效。`,en:`Say "Remember this…" to save it; ask "Do you remember…?" later — memory persists across sessions.`},{id:`custom-prompt`,scene:`plugin`,zh:`把常用指令存成自定义提示词,下次用「/」一键调用。`,en:`Save frequent instructions as custom prompts and recall them with "/" next time.`},{id:`kb-ingest`,scene:`plugin`,zh:`说「把这份资料存到知识库」,AI 会自动切分并入库,之后可直接检索。`,en:`Say "Save this into the knowledge base" and the AI chunks and ingests it for later retrieval.`},{id:`clipboard`,scene:`plugin`,zh:`说「把结果复制到剪贴板」,AI 会直接写入,省去手动选中复制。`,en:`Say "Copy the result to my clipboard" and the AI writes it for you.`},{id:`page-highlight`,scene:`plugin`,zh:`说「在页面上高亮 xxx」,AI 会把关键内容标出来,方便讲解或核对。`,en:`Say "Highlight xxx on the page" to mark key content for explanation or review.`},{id:`capture`,scene:`plugin`,zh:`说「截图并分析这个页面」,AI 会截图后交给视觉模型解读图表或界面。`,en:`Say "Screenshot and analyze this page" to have the vision model read charts or UI.`},{id:`preview-ui`,scene:`plugin`,zh:`说「做个界面原型给我看看」,AI 会在侧边栏直接渲染可预览的 HTML。`,en:`Say "Show me a UI prototype" and the AI renders previewable HTML in the side panel.`},{id:`form-fill`,scene:`plugin`,zh:`说「帮我填一下这个表单」,AI 能一次批量填入多个字段。`,en:`Say "Fill out this form" and the AI can fill multiple fields in one go.`},{id:`browser-act`,scene:`plugin`,zh:`说「打开这个链接并帮我点…」,AI 能自动开标签页、点击、输入和翻页。`,en:`Say "Open this link and click …" and the AI can open tabs, click, type, and scroll.`},{id:`clarify`,scene:`plugin`,zh:`加上「拿不准就先问我」,AI 会先给出选项确认,避免理解跑偏。`,en:`Add "Ask me first if unsure" and the AI confirms with options before proceeding.`},{id:`dispatch`,scene:`plugin`,zh:`说「这几件事并行处理」,AI 会拆给子代理并发执行,大任务更快。`,en:`Say "Handle these in parallel" and the AI dispatches sub-agents concurrently.`},{id:`qrcode`,scene:`plugin`,zh:`说「把这个链接生成二维码」,AI 会自动生成并展示出来。`,en:`Say "Turn this link into a QR code" and the AI generates and shows it.`},{id:`notify`,scene:`plugin`,zh:`说「做完后提醒我」,AI 会用桌面通知告知结果,不必一直盯着。`,en:`Say "Notify me when done" and the AI sends a desktop notification.`},{id:`fetch`,scene:`plugin`,zh:`说「帮我抓取这个接口的数据」,AI 可发起 HTTP 请求并整理返回结果。`,en:`Say "Fetch the data from this API" and the AI can send an HTTP request and organize the result.`},{id:`agent-hint`,scene:`plugin`,zh:`连接代理端后,可解锁本机文件读写、命令执行等能力(设置 → 代理页配对)。`,en:`Connecting the agent unlocks local file access and command execution (Settings → Agent to pair).`},{id:`agent-file`,scene:`agent`,zh:`已连接代理端:AI 可以读写你电脑上的文件,直接说「帮我改这个文件」即可。`,en:`Agent connected: the AI can read and write files on your computer — just say "update this file".`},{id:`agent-exec`,scene:`agent`,zh:`已连接代理端:AI 可以执行本机命令、运行脚本,适合构建、测试与批处理。`,en:`Agent connected: the AI can run local commands and scripts for builds, tests, and batch jobs.`},{id:`agent-search`,scene:`agent`,zh:`让 AI「在项目里搜索 xxx」,它会用本机搜索定位代码,比网页检索更准。`,en:`Ask the AI to "search the project for xxx"; local search finds code more accurately than the web.`},{id:`agent-workdir`,scene:`agent`,zh:`在工作目录面板切换目录,AI 的文件操作都会被限制在这个范围内。`,en:`Switch directories in the workspace panel; the AI confinement keeps file operations inside that scope.`},{id:`agent-confirm`,scene:`agent`,zh:`敏感操作会先弹确认,可在基础配置里调整确认策略,兼顾安全与效率。`,en:`Sensitive actions ask for confirmation first; adjust the policy in Basic settings to balance safety and speed.`},{id:`agent-log`,scene:`agent`,zh:`命令执行日志可在日志面板查看;也可说「调出执行日志复盘」,让 AI 提取成功路径与失败教训。`,en:`Review commands in the log panel, or say "Review the execution log" to extract successful paths and lessons.`},{id:`agent-stream`,scene:`agent`,zh:`长命令支持流式输出,执行过程实时可见,不用盯着空白等待。`,en:`Long commands stream their output, so progress is visible in real time instead of a blank wait.`},{id:`agent-multi`,scene:`agent`,zh:`配对了多台电脑时,用「@代理」指定目标,也可以说「切换到另一台电脑的代理」。`,en:`With multiple computers, use "@Agent" to pick one, or just say "Switch to the agent on another computer".`},{id:`agent-offline`,scene:`agent`,zh:`代理端离线时,文件与命令类能力会自动隐藏,避免误发无法执行的任务。`,en:`When the agent is offline, file and command abilities are hidden so tasks are not sent in vain.`},{id:`agent-update`,scene:`agent`,zh:`代理端可在设置 → 代理页一键更新或重启,版本不一致时优先升级。`,en:`Update or restart the agent from Settings → Agent; upgrade first when versions differ.`},{id:`agent-skill`,scene:`agent`,zh:`说「跑一下这个工作流技能」,代理端会执行对应的 Skill。`,en:`Say "Run this workflow skill" and the agent executes the matching Skill.`},{id:`agent-skill-create`,scene:`agent`,zh:`说「把刚才的流程沉淀成技能」,AI 会写成 SKILL.md,下次一句话即可复用。`,en:`Say "Turn that process into a skill" and the AI writes a SKILL.md for one-line reuse next time.`},{id:`agent-trash`,scene:`agent`,zh:`说「从回收站恢复刚删的文件」,代理端可以直接恢复。`,en:`Say "Restore the file I just deleted" and the agent can recover it from its trash.`},{id:`agent-download`,scene:`agent`,zh:`说「把这个文件下载到浏览器」,代理端文件会直接下载到本机。`,en:`Say "Download this file to the browser" and the agent transfers it locally.`}],Z=null,Ff=null,If=null,Lf=null,Rf=null,zf=!1,Bf=null,Vf=!0,Hf=null;function Uf(){return v.agentPlatform?.connected===!0}function Wf(){let e=a();return Pf.filter(e=>e.scene!==`agent`||Uf()).map(t=>({id:t.id,text:e===`en`?t.en:t.zh}))}function Gf(e){let t=e.findIndex(e=>e.id===Bf);return t>=0?t:0}function Kf(){if(!Z||!Ff)return;let e=Ff.scrollWidth>Ff.clientWidth+1;Z.classList.toggle(`is-truncated`,e)}function qf(e,t){if(!Ff||!e.length)return;let n=e[t%e.length];Bf=n.id,Ff.textContent=n.text,If&&(If.textContent=n.text),Kf(),Ff.classList.remove(`fade-in`),Ff.offsetWidth,Ff.classList.add(`fade-in`)}function Jf(){if(!Vf||!Z||Z.style.display===`none`)return;let e=Wf();e.length&&qf(e,Gf(e)+1)}function Yf(){Rf&&=(clearInterval(Rf),null)}function Xf(){Yf(),!(!Vf||zf)&&(Rf=setInterval(Jf,Nf))}function Zf(){if(!Vf||!Z)return;let e=Wf();if(!e.length){$f();return}e.some(e=>e.id===Bf)?qf(e,Gf(e)):(Bf=null,qf(e,0))}function Qf(){if(!Z)return;Vf=!0,Z.style.display=``;let e=Wf();if(!e.length){$f();return}qf(e,Gf(e)),Xf()}function $f(){Z&&(Z.style.display=`none`,Yf())}function ep(){Z.addEventListener(`mouseenter`,()=>{zf=!0,Yf()}),Z.addEventListener(`mouseleave`,()=>{zf=!1,Xf()}),Lf.addEventListener(`click`,e=>{e.stopPropagation(),tp(),A(t(`usageTips.dismissedHint`),`info`,5e3)}),chrome.storage.onChanged.addListener((e,t)=>{t!==`local`||!e[Mf]||(e[Mf].newValue===!1?(Vf=!1,$f()):Qf())}),document.addEventListener(`agent-connection-changed`,Zf),o(Zf),typeof ResizeObserver<`u`&&new ResizeObserver(Kf).observe(Z)}function tp(){Vf=!1,$f();try{chrome.storage.local.set({[Mf]:!1})}catch{}}function np(){if(Z=document.getElementById(`usageTipsBar`),Ff=document.getElementById(`usageTipsText`),If=document.getElementById(`usageTipsTooltip`),Lf=document.getElementById(`usageTipsDismiss`),!(!Z||!Ff||!If||!Lf)){ep(),Hf=document.getElementById(`chatContainer`),Hf&&(Hf.appendChild(Z),typeof MutationObserver<`u`&&new MutationObserver(()=>{Hf.querySelectorAll(`.usage-tips-bar`).forEach(e=>{e!==Z&&e.remove()}),(Z.parentNode!==Hf||Z.nextElementSibling)&&Hf.appendChild(Z)}).observe(Hf,{childList:!0}));try{chrome.storage.local.get([Mf],e=>{Vf=e?.[Mf]!==!1,Vf?Qf():$f()})}catch{Qf()}}}function rp({key:e,value:t=``,caret:n,history:r=[],index:i=-1}={}){if(e!==`ArrowUp`&&e!==`ArrowDown`||!Array.isArray(r)||r.length===0)return{handled:!1};let a=String(t??``),o=Number.isInteger(n)&&n>=0?n:a.length,s=Number.isInteger(i)&&i>=0;if(e===`ArrowUp`){let e=a.lastIndexOf(`
439
439
  `,o-1)===-1;if(!s&&!e)return{handled:!1};let t=s?Math.min(i,r.length-1):r.length,n=Math.max(0,t-1);return{handled:!0,index:n,value:r[n]}}if(!s||a.indexOf(`
440
- `,o)!==-1)return{handled:!1};let c=Math.min(i,r.length-1);if(c<r.length-1){let e=c+1;return{handled:!0,index:e,value:r[e]}}return{handled:!0,index:-1,value:``}}function rp(e,t){let n;return function(...r){clearTimeout(n),n=setTimeout(()=>{clearTimeout(n),e(...r)},t)}}var ip=null,ap=null,op=null,sp=null,cp=null,lp=null,up=null,dp=null,fp=null,pp=null,mp=!1,hp=!1,gp=null,_p={[Ln.DISPATCHING]:`queue.statusDispatching`,[Ln.INJECTING]:`queue.statusInjecting`,[Ln.INJECTED]:`queue.statusInjected`,[Ln.DONE]:`queue.statusDone`,[Ln.FAILED]:`queue.statusFailed`};function vp(e){if(e.status===Ln.QUEUED)return e.interrupted?t(`queue.statusRecovered`):``;let n=_p[e.status];return n?t(n):``}function yp(){return v.activeSessionId}function bp(e){let n=e.attachmentSummary||e.contextSnapshot&&e.contextSnapshot.attachmentSummary||null,r=[];n&&(n.imageCount&&r.push(t(`queue.withImages`,{count:n.imageCount})),n.fileCount&&r.push(t(`queue.withFiles`,{count:n.fileCount})));let i=r.length?r.join(` · `):Gr(e.contextSnapshot)?t(`queue.withContext`):``;return i?`<span class="queue-chip-ctx" title="${k(n&&(n.fileNames||[]).length?n.fileNames.join(`、`):i)}">${k(i)}</span>`:``}function xp(e,n){let r=bp(e),i=e.status===Ln.DISPATCHING,a=vp(e),o=(a?`<span class="queue-chip-status${i?` running`:``}${e.interrupted?` warning`:``}"${i?` title="${k(t(`queue.statusRunningHint`))}"`:``}>${k(a)}</span>`:``)+r,s=v.isGenerating===!0;return`
440
+ `,o)!==-1)return{handled:!1};let c=Math.min(i,r.length-1);if(c<r.length-1){let e=c+1;return{handled:!0,index:e,value:r[e]}}return{handled:!0,index:-1,value:``}}function ip(e,t){let n;return function(...r){clearTimeout(n),n=setTimeout(()=>{clearTimeout(n),e(...r)},t)}}var ap=null,op=null,sp=null,cp=null,lp=null,up=null,dp=null,fp=null,pp=null,mp=null,hp=!1,gp=!1,_p=null,vp={[At.DISPATCHING]:`queue.statusDispatching`,[At.INJECTING]:`queue.statusInjecting`,[At.INJECTED]:`queue.statusInjected`,[At.DONE]:`queue.statusDone`,[At.FAILED]:`queue.statusFailed`};function yp(e){if(e.status===At.QUEUED)return e.interrupted?t(`queue.statusRecovered`):``;let n=vp[e.status];return n?t(n):``}function bp(){return v.activeSessionId}function xp(e){let n=e.attachmentSummary||e.contextSnapshot&&e.contextSnapshot.attachmentSummary||null,r=[];n&&(n.imageCount&&r.push(t(`queue.withImages`,{count:n.imageCount})),n.fileCount&&r.push(t(`queue.withFiles`,{count:n.fileCount})));let i=r.length?r.join(` · `):pn(e.contextSnapshot)?t(`queue.withContext`):``;return i?`<span class="queue-chip-ctx" title="${k(n&&(n.fileNames||[]).length?n.fileNames.join(`、`):i)}">${k(i)}</span>`:``}function Sp(e,n){let r=xp(e),i=e.status===At.DISPATCHING,a=yp(e),o=(a?`<span class="queue-chip-status${i?` running`:``}${e.interrupted?` warning`:``}"${i?` title="${k(t(`queue.statusRunningHint`))}"`:``}>${k(a)}</span>`:``)+r,s=v.isGenerating===!0;return`
441
441
  <div class="queue-chip" draggable="true" data-id="${k(e.id)}" data-status="${k(e.status)}">
442
442
  <span class="queue-chip-index">${n+1}</span>
443
443
  <div class="queue-chip-main">
@@ -449,16 +449,16 @@ import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-DvmxOw8q.js"
449
449
  <button class="queue-chip-btn" type="button" data-act="edit" title="${k(t(`queue.editBack`))}">✎</button>
450
450
  <button class="queue-chip-btn danger" type="button" data-act="remove" title="${k(t(`queue.delete`))}">✕</button>
451
451
  </div>
452
- </div>`}function Sp(e){return e.length?e.map(e=>`
452
+ </div>`}function Cp(e){return e.length?e.map(e=>`
453
453
  <div class="queue-recent-item" data-id="${k(e.id)}">
454
- <span class="queue-recent-status">${k(vp(e))}</span>
454
+ <span class="queue-recent-status">${k(yp(e))}</span>
455
455
  <span class="queue-recent-text" title="${k(e.text)}">${k(e.text)}</span>
456
456
  <button class="queue-chip-btn" type="button" data-act="requeue" title="${k(t(`queue.requeue`))}">↺</button>
457
457
  <button class="queue-chip-btn danger" type="button" data-act="forget" title="${k(t(`queue.forgetRecent`))}">✕</button>
458
- </div>`).join(``):`<div class="queue-recent-empty">${k(t(`queue.recentEmpty`))}</div>`}function Cp(e={}){if(!ip||gp)return;let n=yp();if(!n){ip.style.display=`none`;return}let r=Vi(n),i=r.items,a=i.length>0,o=r.recent.filter(e=>e.status===Ln.FAILED).length,s=o>0;if(!a&&!s&&(!hp||r.recent.length===0)){ip.style.display=`none`;return}if(ip.style.display=``,ip.classList.toggle(`empty`,!a),ip.classList.toggle(`expanded`,mp&&a),ip.classList.toggle(`paused`,r.paused),op&&(a?(op.textContent=t(`queue.summary`,{count:i.length}),op.classList.remove(`failed`),op.removeAttribute(`title`)):s?(op.textContent=t(`queue.summaryFailed`,{count:o}),op.classList.add(`failed`),op.title=t(`queue.summaryFailedHint`)):(op.textContent=t(`queue.summaryEmpty`),op.classList.remove(`failed`),op.removeAttribute(`title`))),sp&&(sp.style.display=r.paused?``:`none`,sp.title=r.pausedReason===`user_stopped`?t(`queue.pausedByStop`):t(`queue.pausedHint`)),cp){let e=r.paused&&i.length>0;cp.style.display=e?``:`none`,cp.textContent=t(`queue.resumeQueue`)}if(lp){let e=v.isGenerating===!0&&a&&!r.paused;lp.style.display=e?``:`none`}up&&(up.classList.toggle(`active`,hp),up.title=t(`queue.recentTitle`)),fp&&(fp.style.display=a?``:`none`,fp.setAttribute(`aria-expanded`,mp?`true`:`false`),fp.textContent=mp?`▲`:`▼`),ap&&(ap.style.display=mp&&a?``:`none`,ap.innerHTML=a?i.map((e,t)=>xp(e,t)).join(``):``),dp&&(dp.style.display=hp?``:`none`,dp.innerHTML=hp?Sp(r.recent):``),e.flash&&(ip.classList.remove(`queue-flash`),ip.offsetWidth,ip.classList.add(`queue-flash`))}async function wp(e,n={}){let r=yp();if(!r||!e)return!1;let i=At(r,e);if(!i)return!1;let a=document.getElementById(`userInput`);if(a&&a.value.trim()){let e=await xt({autoDrain:!1});if(!e.ok)return A(e.error===`queue_full`?t(`queue.queueFull`,{limit:e.limit}):t(`queue.enqueueFailed`),`warning`),!1}else if(Yr())return A(t(`queue.inputHasUnsavedContext`),`warning`,4e3),!1;let o=await Mn(i);return a&&(a.value=i.text,a.style.height=`auto`,a.dispatchEvent(new Event(`input`)),a.focus()),await vn(r,e),await ln(e),o.wantsAttachments?A(o.attachments?t(`queue.editBackWithAttachments`):t(`queue.attachmentsMissing`),o.attachments?`success`:`warning`,2500):n.viaShortcut&&A(t(`queue.editTailHint`),`info`,2e3),!0}function Tp(){let e=yp();if(!e)return!1;let t=Kr(e);return t?(wp(t.id,{viaShortcut:!0}),!0):!1}async function Ep(e,n){let r=yp();if(!(!r||!n)&&!(Vn(r).findIndex(e=>e.id===n)<0))switch(e){case`edit`:await wp(n);break;case`inject`:await Vt(n,r);break;case`remove`:await vn(r,n),await ln(n),A(t(`queue.deleted`),`info`,1500);break;default:break}}async function Dp(e){let t=yp();t&&await En(t,e)}async function Op(e,t){if(e.preventDefault(),!gp)return;let n=t?.dataset?.id;if(!n||n===gp)return;let r=yp();if(!r)return;let i=Vn(r).map(e=>e.id),a=i.indexOf(gp);if(a<0)return;i.splice(a,1);let o=t.getBoundingClientRect(),s=e.clientY-o.top>o.height/2,c=i.indexOf(n);c<0?c=i.length:s&&(c+=1),i.splice(c,0,gp),await Dp(i)}function kp(){ap&&(ap.addEventListener(`dragstart`,e=>{let t=e.target.closest?.(`.queue-chip`);if(t){gp=t.dataset.id,t.classList.add(`dragging`);try{e.dataTransfer.effectAllowed=`move`,e.dataTransfer.setData(`text/plain`,gp)}catch{}}}),ap.addEventListener(`dragend`,e=>{let t=e.target.closest?.(`.queue-chip`);t&&t.classList.remove(`dragging`),gp=null,ap.querySelectorAll(`.drag-over-top, .drag-over-bottom`).forEach(e=>{e.classList.remove(`drag-over-top`,`drag-over-bottom`)}),Cp()}),ap.addEventListener(`dragover`,e=>{let t=e.target.closest?.(`.queue-chip`);if(!t||!gp||t.dataset.id===gp)return;e.preventDefault();let n=t.getBoundingClientRect(),r=e.clientY-n.top>n.height/2;t.classList.toggle(`drag-over-bottom`,r),t.classList.toggle(`drag-over-top`,!r)}),ap.addEventListener(`dragleave`,e=>{let t=e.target.closest?.(`.queue-chip`);t&&t.classList.remove(`drag-over-top`,`drag-over-bottom`)}),ap.addEventListener(`drop`,e=>{let t=e.target.closest?.(`.queue-chip`);Op(e,t)}))}function Ap(){ap?.addEventListener(`click`,e=>{let t=e.target.closest?.(`.queue-chip-btn`);if(!t||t.disabled)return;let n=t.closest(`.queue-chip`);n&&Ep(t.dataset.act,n.dataset.id)}),dp?.addEventListener(`click`,async e=>{let n=e.target.closest?.(`.queue-chip-btn`),r=n?.closest(`.queue-recent-item`),i=yp();if(!n||!r||!i)return;if(n.dataset.act===`forget`){await mn(i,r.dataset.id)&&A(t(`queue.forgotRecent`),`success`,1500);return}if(n.dataset.act!==`requeue`)return;let a=Pt(i).find(e=>e.id===r.dataset.id),o=!!(a&&a.attachmentSummary),s=await Ht(i,r.dataset.id);if(!s.ok){A(s.error===`queue_full`?t(`queue.queueFull`,{limit:s.limit}):t(`queue.enqueueFailed`),`warning`);return}A(t(o?`queue.requeuedNoAttachments`:`queue.requeued`),o?`warning`:`success`,2500)}),fp?.addEventListener(`click`,()=>{mp=!mp,Cp()}),pp?.addEventListener(`click`,e=>{e.target.closest?.(`button`)||Vn(yp()||``).length&&(mp=!mp,Cp())}),up?.addEventListener(`click`,()=>{hp=!hp,hp&&(mp=!0),Cp()}),cp?.addEventListener(`click`,async()=>{await Qi(),A(t(`queue.resumed`),`success`,1500)}),lp?.addEventListener(`click`,()=>{document.dispatchEvent(new CustomEvent(`queue-stop-and-send`))}),kp(),$t(()=>Cp()),document.addEventListener(`queue-enqueued`,()=>{mp=!0,Cp({flash:!0})}),document.addEventListener(`session-switched`,()=>{Cp()}),document.addEventListener(`generation-ended`,()=>Cp()),document.addEventListener(`generating-state-changed`,()=>Cp())}async function jp(){await Sn(),Cp()}async function Mp(){if(await Sn(),ip=document.getElementById(`queueStrip`),!ip){r.warn(`[QueuePanel] #queueStrip not found, queue UI disabled`);return}ap=document.getElementById(`queueList`),op=document.getElementById(`queueSummary`),sp=document.getElementById(`queuePausedTag`),cp=document.getElementById(`queueResumeBtn`),lp=document.getElementById(`queueStopSendBtn`),up=document.getElementById(`queueRecentBtn`),dp=document.getElementById(`queueRecent`),fp=document.getElementById(`queueToggleBtn`),pp=ip.querySelector(`.queue-strip-head`),Ap(),Cp()}var Np=new Set,Pp=new Set,Fp=new Map,Ip=30*1e3;function Lp(e){let t=Fp.get(e);return t?Date.now()-t<Ip?!0:(Fp.delete(e),!1):!1}async function Rp(e){let t=h(e)||e;if(!t||Np.has(t)||Pp.has(t)||Lp(t))return null;Pp.add(t);try{let e=await te();if(!e)return null;let n=null;try{let r=await oe(`${e.url}/api/status/detail`,{headers:{Authorization:`Bearer ${e.token}`,"X-AIH-Session-Id":t}});if(!r.ok)return Fp.set(t,Date.now()),null;n=await r.json()}catch(e){return r.debug(`[WorkdirReconcile] fetch detail failed:`,e?.message||e),Fp.set(t,Date.now()),null}if(!n?.success||!n.sessionWorkdirSupported)return Fp.set(t,Date.now()),null;let i=n.sessionWorkdir||null,a=n.defaultWorkdir||n.workdir||null;if(!i||i===a)return Fp.set(t,Date.now()),null;let o=await p(t);return o.scope===`session`?(Fp.set(t,Date.now()),null):o.boundWorkdir?await ne(t)?(Np.add(t),r.debug(`[WorkdirReconcile] cleared stale agent binding:`,t,i),{cleaned:!0,workdir:i}):null:await D(t,i,o.agentId||e.id||null)?(Np.add(t),r.debug(`[WorkdirReconcile] restored session workdir:`,t,i),{adopted:!0,workdir:i}):null}finally{Pp.delete(t)}}e(`zh`,{sidePanel:{popupTitle:`浮层解答`,popupTooltip:`浮层解答(不进入对话)`,popupLoading:`思考中...`,popupCopy:`复制`,popupCopied:`已复制到剪贴板`,popupTransfer:`转入对话`,popupTransferred:`已转入对话`,popupRegenerate:`重新生成`,popupClose:`关闭`,popupLock:`锁定(不随点击外部关闭)`,popupUnlock:`解锁(可点击外部关闭)`,popupRequestFailed:`请求失败`,popupContextLabel:`上下文`,popupContextTruncated:`(已截断)`,popupSystemPrompt:`用户在阅读 AI 回答时选中了其中的片段,希望理解选中内容。请结合上下文,只针对选中片段回答,简洁清楚,不要展开与选中内容无关的长论述。`}}),e(`en`,{sidePanel:{popupTitle:`Popup Answer`,popupTooltip:`Answer in popup (not in conversation)`,popupLoading:`Thinking...`,popupCopy:`Copy`,popupCopied:`Copied to clipboard`,popupTransfer:`Move to chat`,popupTransferred:`Moved to chat`,popupRegenerate:`Regenerate`,popupClose:`Close`,popupLock:`Lock (keep open on outside click)`,popupUnlock:`Unlock (close on outside click)`,popupRequestFailed:`Request failed`,popupContextLabel:`Context`,popupContextTruncated:`(truncated)`,popupSystemPrompt:`The user selected a fragment while reading an AI answer and wants to understand it. Using the surrounding context, answer only about the selected fragment, concisely and clearly, without expanding into unrelated long discussion.`}});var zp=1500,Q=null,Bp=null,Vp=``,Hp=null,Up=``,Wp=``,Gp=!1,Kp=!1,qp=!1;function Jp(e){return(e||``).replace(/[ \t\f\v]+/g,` `).replace(/ *\n */g,`
458
+ </div>`).join(``):`<div class="queue-recent-empty">${k(t(`queue.recentEmpty`))}</div>`}function wp(e={}){if(!ap||_p)return;let n=bp();if(!n){ap.style.display=`none`;return}let r=Vn(n),i=r.items,a=i.length>0,o=r.recent.filter(e=>e.status===At.FAILED).length,s=o>0;if(!a&&!s&&(!gp||r.recent.length===0)){ap.style.display=`none`;return}if(ap.style.display=``,ap.classList.toggle(`empty`,!a),ap.classList.toggle(`expanded`,hp&&a),ap.classList.toggle(`paused`,r.paused),sp&&(a?(sp.textContent=t(`queue.summary`,{count:i.length}),sp.classList.remove(`failed`),sp.removeAttribute(`title`)):s?(sp.textContent=t(`queue.summaryFailed`,{count:o}),sp.classList.add(`failed`),sp.title=t(`queue.summaryFailedHint`)):(sp.textContent=t(`queue.summaryEmpty`),sp.classList.remove(`failed`),sp.removeAttribute(`title`))),cp&&(cp.style.display=r.paused?``:`none`,cp.title=r.pausedReason===`user_stopped`?t(`queue.pausedByStop`):t(`queue.pausedHint`)),lp){let e=r.paused&&i.length>0;lp.style.display=e?``:`none`,lp.textContent=t(`queue.resumeQueue`)}if(up){let e=v.isGenerating===!0&&a&&!r.paused;up.style.display=e?``:`none`}dp&&(dp.classList.toggle(`active`,gp),dp.title=t(`queue.recentTitle`)),pp&&(pp.style.display=a?``:`none`,pp.setAttribute(`aria-expanded`,hp?`true`:`false`),pp.textContent=hp?`▲`:`▼`),op&&(op.style.display=hp&&a?``:`none`,op.innerHTML=a?i.map((e,t)=>Sp(e,t)).join(``):``),fp&&(fp.style.display=gp?``:`none`,fp.innerHTML=gp?Cp(r.recent):``),e.flash&&(ap.classList.remove(`queue-flash`),ap.offsetWidth,ap.classList.add(`queue-flash`))}async function Tp(e,n={}){let r=bp();if(!r||!e)return!1;let i=Ui(r,e);if(!i)return!1;let a=document.getElementById(`userInput`);if(a&&a.value.trim()){let e=await Kr({autoDrain:!1});if(!e.ok)return A(e.error===`queue_full`?t(`queue.queueFull`,{limit:e.limit}):t(`queue.enqueueFailed`),`warning`),!1}else if(xt())return A(t(`queue.inputHasUnsavedContext`),`warning`,4e3),!1;let o=await $i(i);return a&&(a.value=i.text,a.style.height=`auto`,a.dispatchEvent(new Event(`input`)),a.focus()),await En(r,e),await Mn(e),o.wantsAttachments?A(o.attachments?t(`queue.editBackWithAttachments`):t(`queue.attachmentsMissing`),o.attachments?`success`:`warning`,2500):n.viaShortcut&&A(t(`queue.editTailHint`),`info`,2e3),!0}function Ep(){let e=bp();if(!e)return!1;let t=mn(e);return t?(Tp(t.id,{viaShortcut:!0}),!0):!1}async function Dp(e,n){let r=bp();if(!(!r||!n)&&!(Rt(r).findIndex(e=>e.id===n)<0))switch(e){case`edit`:await Tp(n);break;case`inject`:await Qt(n,r);break;case`remove`:await En(r,n),await Mn(n),A(t(`queue.deleted`),`info`,1500);break;default:break}}async function Op(e){let t=bp();t&&await Ht(t,e)}async function kp(e,t){if(e.preventDefault(),!_p)return;let n=t?.dataset?.id;if(!n||n===_p)return;let r=bp();if(!r)return;let i=Rt(r).map(e=>e.id),a=i.indexOf(_p);if(a<0)return;i.splice(a,1);let o=t.getBoundingClientRect(),s=e.clientY-o.top>o.height/2,c=i.indexOf(n);c<0?c=i.length:s&&(c+=1),i.splice(c,0,_p),await Op(i)}function Ap(){op&&(op.addEventListener(`dragstart`,e=>{let t=e.target.closest?.(`.queue-chip`);if(t){_p=t.dataset.id,t.classList.add(`dragging`);try{e.dataTransfer.effectAllowed=`move`,e.dataTransfer.setData(`text/plain`,_p)}catch{}}}),op.addEventListener(`dragend`,e=>{let t=e.target.closest?.(`.queue-chip`);t&&t.classList.remove(`dragging`),_p=null,op.querySelectorAll(`.drag-over-top, .drag-over-bottom`).forEach(e=>{e.classList.remove(`drag-over-top`,`drag-over-bottom`)}),wp()}),op.addEventListener(`dragover`,e=>{let t=e.target.closest?.(`.queue-chip`);if(!t||!_p||t.dataset.id===_p)return;e.preventDefault();let n=t.getBoundingClientRect(),r=e.clientY-n.top>n.height/2;t.classList.toggle(`drag-over-bottom`,r),t.classList.toggle(`drag-over-top`,!r)}),op.addEventListener(`dragleave`,e=>{let t=e.target.closest?.(`.queue-chip`);t&&t.classList.remove(`drag-over-top`,`drag-over-bottom`)}),op.addEventListener(`drop`,e=>{let t=e.target.closest?.(`.queue-chip`);kp(e,t)}))}function jp(){op?.addEventListener(`click`,e=>{let t=e.target.closest?.(`.queue-chip-btn`);if(!t||t.disabled)return;let n=t.closest(`.queue-chip`);n&&Dp(t.dataset.act,n.dataset.id)}),fp?.addEventListener(`click`,async e=>{let n=e.target.closest?.(`.queue-chip-btn`),r=n?.closest(`.queue-recent-item`),i=bp();if(!n||!r||!i)return;if(n.dataset.act===`forget`){await vn(i,r.dataset.id)&&A(t(`queue.forgotRecent`),`success`,1500);return}if(n.dataset.act!==`requeue`)return;let a=Sn(i).find(e=>e.id===r.dataset.id),o=!!(a&&a.attachmentSummary),s=await $t(i,r.dataset.id);if(!s.ok){A(s.error===`queue_full`?t(`queue.queueFull`,{limit:s.limit}):t(`queue.enqueueFailed`),`warning`);return}A(t(o?`queue.requeuedNoAttachments`:`queue.requeued`),o?`warning`:`success`,2500)}),pp?.addEventListener(`click`,()=>{hp=!hp,wp()}),mp?.addEventListener(`click`,e=>{e.target.closest?.(`button`)||Rt(bp()||``).length&&(hp=!hp,wp())}),dp?.addEventListener(`click`,()=>{gp=!gp,gp&&(hp=!0),wp()}),lp?.addEventListener(`click`,async()=>{await Tt(),A(t(`queue.resumed`),`success`,1500)}),up?.addEventListener(`click`,()=>{document.dispatchEvent(new CustomEvent(`queue-stop-and-send`))}),Ap(),un(()=>wp()),document.addEventListener(`queue-enqueued`,()=>{hp=!0,wp({flash:!0})}),document.addEventListener(`session-switched`,()=>{wp()}),document.addEventListener(`generation-ended`,()=>wp()),document.addEventListener(`generating-state-changed`,()=>wp())}async function Mp(){await Zr(),wp()}async function Np(){if(await Zr(),ap=document.getElementById(`queueStrip`),!ap){r.warn(`[QueuePanel] #queueStrip not found, queue UI disabled`);return}op=document.getElementById(`queueList`),sp=document.getElementById(`queueSummary`),cp=document.getElementById(`queuePausedTag`),lp=document.getElementById(`queueResumeBtn`),up=document.getElementById(`queueStopSendBtn`),dp=document.getElementById(`queueRecentBtn`),fp=document.getElementById(`queueRecent`),pp=document.getElementById(`queueToggleBtn`),mp=ap.querySelector(`.queue-strip-head`),jp(),wp()}var Pp=new Set,Fp=new Set,Ip=new Map,Lp=30*1e3;function Rp(e){let t=Ip.get(e);return t?Date.now()-t<Lp?!0:(Ip.delete(e),!1):!1}async function zp(e){let t=h(e)||e;if(!t||Pp.has(t)||Fp.has(t)||Rp(t))return null;Fp.add(t);try{let e=await te();if(!e)return null;let n=null;try{let r=await oe(`${e.url}/api/status/detail`,{headers:{Authorization:`Bearer ${e.token}`,"X-AIH-Session-Id":t}});if(!r.ok)return Ip.set(t,Date.now()),null;n=await r.json()}catch(e){return r.debug(`[WorkdirReconcile] fetch detail failed:`,e?.message||e),Ip.set(t,Date.now()),null}if(!n?.success||!n.sessionWorkdirSupported)return Ip.set(t,Date.now()),null;let i=n.sessionWorkdir||null,a=n.defaultWorkdir||n.workdir||null;if(!i||i===a)return Ip.set(t,Date.now()),null;let o=await p(t);return o.scope===`session`?(Ip.set(t,Date.now()),null):o.boundWorkdir?await ne(t)?(Pp.add(t),r.debug(`[WorkdirReconcile] cleared stale agent binding:`,t,i),{cleaned:!0,workdir:i}):null:await D(t,i,o.agentId||e.id||null)?(Pp.add(t),r.debug(`[WorkdirReconcile] restored session workdir:`,t,i),{adopted:!0,workdir:i}):null}finally{Fp.delete(t)}}e(`zh`,{sidePanel:{popupTitle:`浮层解答`,popupTooltip:`浮层解答(不进入对话)`,popupLoading:`思考中...`,popupCopy:`复制`,popupCopied:`已复制到剪贴板`,popupTransfer:`转入对话`,popupTransferred:`已转入对话`,popupRegenerate:`重新生成`,popupClose:`关闭`,popupLock:`锁定(不随点击外部关闭)`,popupUnlock:`解锁(可点击外部关闭)`,popupRequestFailed:`请求失败`,popupContextLabel:`上下文`,popupContextTruncated:`(已截断)`,popupSystemPrompt:`用户在阅读 AI 回答时选中了其中的片段,希望理解选中内容。请结合上下文,只针对选中片段回答,简洁清楚,不要展开与选中内容无关的长论述。`}}),e(`en`,{sidePanel:{popupTitle:`Popup Answer`,popupTooltip:`Answer in popup (not in conversation)`,popupLoading:`Thinking...`,popupCopy:`Copy`,popupCopied:`Copied to clipboard`,popupTransfer:`Move to chat`,popupTransferred:`Moved to chat`,popupRegenerate:`Regenerate`,popupClose:`Close`,popupLock:`Lock (keep open on outside click)`,popupUnlock:`Unlock (close on outside click)`,popupRequestFailed:`Request failed`,popupContextLabel:`Context`,popupContextTruncated:`(truncated)`,popupSystemPrompt:`The user selected a fragment while reading an AI answer and wants to understand it. Using the surrounding context, answer only about the selected fragment, concisely and clearly, without expanding into unrelated long discussion.`}});var Bp=1500,Q=null,Vp=null,Hp=``,Up=null,Wp=``,Gp=``,Kp=!1,qp=!1,Jp=!1;function Yp(e){return(e||``).replace(/[ \t\f\v]+/g,` `).replace(/ *\n */g,`
459
459
  `).replace(/\n{3,}/g,`
460
460
 
461
- `).trim()}function Yp(e,t){if(!e)return{context:``,truncated:!1};let n=e.startContainer?.parentElement?.closest?.(`.message`);if(!n)return{context:``,truncated:!1};let r=Jp(n.textContent);if(!r)return{context:``,truncated:!1};let i=c(r);if(i<=zp)return{context:r,truncated:!1};let a=r.indexOf(t),o=a>=0?a+t.length/2:r.length/2,s=Math.floor(r.length*zp/Math.max(i,1)),l=Math.max(0,Math.floor(o-s/2)),u=Math.min(r.length,l+s);if(a>=0){let e=a+t.length;a<l&&(l=Math.max(0,a-50)),e>u&&(u=Math.min(r.length,e+50))}let d=r.slice(l,u).trim();if(c(d)>zp){let e=zp/c(d);d=d.slice(0,Math.floor(d.length*e))}return{context:d,truncated:!0}}function Xp(e,n,r,i){let a=t(`sidePanel.popupSystemPrompt`),o=``;return n&&(o+=`[${t(`sidePanel.popupContextLabel`)}${i?t(`sidePanel.popupContextTruncated`):``}]\n${n}\n\n`),o+=`[${t(`sidePanel.selectedContentLabel`)}]\n${e}\n\n`,o+=`[${t(`sidePanel.userQuestionLabel`)}]\n${r}`,[{role:`system`,content:a},{role:`user`,content:o}]}function Zp(){return Q&&document.body.contains(Q)?Q:(Q=document.createElement(`div`),Q.className=`selection-answer-popup`,Q.id=`selectionAnswerPopup`,Q.innerHTML=`
461
+ `).trim()}function Xp(e,t){if(!e)return{context:``,truncated:!1};let n=e.startContainer?.parentElement?.closest?.(`.message`);if(!n)return{context:``,truncated:!1};let r=Yp(n.textContent);if(!r)return{context:``,truncated:!1};let i=c(r);if(i<=Bp)return{context:r,truncated:!1};let a=r.indexOf(t),o=a>=0?a+t.length/2:r.length/2,s=Math.floor(r.length*Bp/Math.max(i,1)),l=Math.max(0,Math.floor(o-s/2)),u=Math.min(r.length,l+s);if(a>=0){let e=a+t.length;a<l&&(l=Math.max(0,a-50)),e>u&&(u=Math.min(r.length,e+50))}let d=r.slice(l,u).trim();if(c(d)>Bp){let e=Bp/c(d);d=d.slice(0,Math.floor(d.length*e))}return{context:d,truncated:!0}}function Zp(e,n,r,i){let a=t(`sidePanel.popupSystemPrompt`),o=``;return n&&(o+=`[${t(`sidePanel.popupContextLabel`)}${i?t(`sidePanel.popupContextTruncated`):``}]\n${n}\n\n`),o+=`[${t(`sidePanel.selectedContentLabel`)}]\n${e}\n\n`,o+=`[${t(`sidePanel.userQuestionLabel`)}]\n${r}`,[{role:`system`,content:a},{role:`user`,content:o}]}function Qp(){return Q&&document.body.contains(Q)?Q:(Q=document.createElement(`div`),Q.className=`selection-answer-popup`,Q.id=`selectionAnswerPopup`,Q.innerHTML=`
462
462
  <div class="sap-header">
463
463
  <span class="sap-title"></span>
464
464
  <div class="sap-header-actions">
@@ -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-DvmxOw8q.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`,om),Q.querySelector(`.sap-lock`).addEventListener(`click`,em),Q.querySelector(`.sap-copy`).addEventListener(`click`,um),Q.querySelector(`.sap-transfer`).addEventListener(`click`,dm),Q.querySelector(`.sap-regen`).addEventListener(`click`,()=>{Hp&&Up&&pm()}),lm(Q.querySelector(`.sap-header`)),Q)}function Qp(){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`),$p()}function $p(){if(!Q)return;let e=Q.querySelector(`.sap-lock`);e&&(e.classList.toggle(`locked`,qp),e.title=t(qp?`sidePanel.popupUnlock`:`sidePanel.popupLock`),e.innerHTML=qp?`<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 em(){qp=!qp,$p()}function tm(e,t){let n=Zp(),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 nm(e){let n=Zp();Qp(),n.querySelector(`.sap-title`).textContent=e||t(`sidePanel.popupTitle`),n.querySelector(`.sap-body`).innerHTML=`<div class="sap-loading">${k(t(`sidePanel.popupLoading`))}</div>`,n.classList.add(`show`),Q.style.display=`block`}function rm(){return!!Q&&Q.classList.contains(`show`)}function im(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 am(e){let t=Q?.querySelector(`.sap-body`);t&&(t.innerHTML=`<div class="sap-error">${k(e)}</div>`)}function om(){Kp&&Bp&&chrome.runtime.sendMessage({type:`CANCEL_REACT`,sessionId:Bp}).catch(()=>{}),Q&&(Q.classList.remove(`show`),Q.style.display=`none`),Bp=null,Vp=``,Kp=!1,qp=!1}function sm(e){if(!rm()||qp||Q.contains(e.target))return;let t=document.getElementById(`selectionFloatingMenu`);t&&t.contains(e.target)||om()}function cm(e){e.key===`Escape`&&(!rm()||qp||om())}function lm(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 um(){Vp&&navigator.clipboard.writeText(Vp).then(()=>{A(t(`sidePanel.popupCopied`))}).catch(()=>{let e=document.createElement(`textarea`);e.value=Vp,document.body.appendChild(e),e.select(),document.execCommand(`copy`),document.body.removeChild(e),A(t(`sidePanel.popupCopied`))})}function dm(){if(!Vp||!Hp)return;hn()&&Zr();let e=Vp,n=Hp.content,r=`${Wp?`[${t(`sidePanel.popupContextLabel`)}]\n${Wp}\n\n`:``}[${t(`sidePanel.selectedContentLabel`)}]\n${Up}\n\n[${t(`sidePanel.userQuestionLabel`)}]\n${Hp.content}`;E(async()=>{let{addMessage:e}=await import(`./context-indicator-DSJveMWs.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-DSJveMWs.js`).then(e=>e.br);return{saveCurrentSession:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8])).then(({saveCurrentSession:e})=>{e()}),Promise.all([E(()=>import(`./context-indicator-DSJveMWs.js`).then(e=>e.ft),__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`))})}),om()}function fm(e,t,n){let{context:r,truncated:i}=Yp(n,t);Hp=e,Up=t,Wp=r,Gp=i,pm()}function pm(){Vp=``,Kp=!0,nm(Hp?.content);let e=Xp(Up,Wp,Hp.content,Gp);Bp=`popup_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,chrome.runtime.sendMessage({type:`SIDEPANEL_POPUP_ASK`,sessionId:Bp,messages:e}).catch(e=>{r.error(`[SelectionPopup] sendMessage failed:`,e),am(t(`sidePanel.popupRequestFailed`)),Kp=!1})}var mm=!1;function hm(){mm||(mm=!0,chrome.runtime.onMessage.addListener(e=>{if(!(!e||!e.type)&&e.type.startsWith(`SIDEPANEL_POPUP_`)&&e.sessionId===Bp){if(e.type===`SIDEPANEL_POPUP_STREAM_CHUNK`)e.delta&&(Vp+=e.delta,im(lt(Vp)));else if(e.type===`SIDEPANEL_POPUP_STREAM_DONE`)Kp=!1,e.finalContent&&(Vp=e.finalContent),im(lt(Vp));else if(e.type===`SIDEPANEL_POPUP_STREAM_ERROR`){if(!Kp)return;Kp=!1,am(e.error||t(`sidePanel.popupRequestFailed`))}}}))}function gm(){hm(),document.addEventListener(`mousedown`,sm),document.addEventListener(`keydown`,cm)}function _m(e,t,n,r,i){!t||!e||(hm(),tm(n,r),qp=!1,fm(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 vm(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`,sm),Q.querySelector(`.sap-lock`).addEventListener(`click`,tm),Q.querySelector(`.sap-copy`).addEventListener(`click`,dm),Q.querySelector(`.sap-transfer`).addEventListener(`click`,fm),Q.querySelector(`.sap-regen`).addEventListener(`click`,()=>{Up&&Wp&&mm()}),um(Q.querySelector(`.sap-header`)),Q)}function $p(){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`),em()}function em(){if(!Q)return;let e=Q.querySelector(`.sap-lock`);e&&(e.classList.toggle(`locked`,Jp),e.title=t(Jp?`sidePanel.popupUnlock`:`sidePanel.popupLock`),e.innerHTML=Jp?`<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 tm(){Jp=!Jp,em()}function nm(e,t){let n=Qp(),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 rm(e){let n=Qp();$p(),n.querySelector(`.sap-title`).textContent=e||t(`sidePanel.popupTitle`),n.querySelector(`.sap-body`).innerHTML=`<div class="sap-loading">${k(t(`sidePanel.popupLoading`))}</div>`,n.classList.add(`show`),Q.style.display=`block`}function im(){return!!Q&&Q.classList.contains(`show`)}function am(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 om(e){let t=Q?.querySelector(`.sap-body`);t&&(t.innerHTML=`<div class="sap-error">${k(e)}</div>`)}function sm(){qp&&Vp&&chrome.runtime.sendMessage({type:`CANCEL_REACT`,sessionId:Vp}).catch(()=>{}),Q&&(Q.classList.remove(`show`),Q.style.display=`none`),Vp=null,Hp=``,qp=!1,Jp=!1}function cm(e){if(!im()||Jp||Q.contains(e.target))return;let t=document.getElementById(`selectionFloatingMenu`);t&&t.contains(e.target)||sm()}function lm(e){e.key===`Escape`&&(!im()||Jp||sm())}function um(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 dm(){Hp&&navigator.clipboard.writeText(Hp).then(()=>{A(t(`sidePanel.popupCopied`))}).catch(()=>{let e=document.createElement(`textarea`);e.value=Hp,document.body.appendChild(e),e.select(),document.execCommand(`copy`),document.body.removeChild(e),A(t(`sidePanel.popupCopied`))})}function fm(){if(!Hp||!Up)return;yn()&&Ct();let e=Hp,n=Up.content,r=`${Gp?`[${t(`sidePanel.popupContextLabel`)}]\n${Gp}\n\n`:``}[${t(`sidePanel.selectedContentLabel`)}]\n${Wp}\n\n[${t(`sidePanel.userQuestionLabel`)}]\n${Up.content}`;E(async()=>{let{addMessage:e}=await import(`./context-indicator-CWyjBBv3.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-CWyjBBv3.js`).then(e=>e.xr);return{saveCurrentSession:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8])).then(({saveCurrentSession:e})=>{e()}),Promise.all([E(()=>import(`./context-indicator-CWyjBBv3.js`).then(e=>e.ft),__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`))})}),sm()}function pm(e,t,n){let{context:r,truncated:i}=Xp(n,t);Up=e,Wp=t,Gp=r,Kp=i,mm()}function mm(){Hp=``,qp=!0,rm(Up?.content);let e=Zp(Wp,Gp,Up.content,Kp);Vp=`popup_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,chrome.runtime.sendMessage({type:`SIDEPANEL_POPUP_ASK`,sessionId:Vp,messages:e}).catch(e=>{r.error(`[SelectionPopup] sendMessage failed:`,e),om(t(`sidePanel.popupRequestFailed`)),qp=!1})}var hm=!1;function gm(){hm||(hm=!0,chrome.runtime.onMessage.addListener(e=>{if(!(!e||!e.type)&&e.type.startsWith(`SIDEPANEL_POPUP_`)&&e.sessionId===Vp){if(e.type===`SIDEPANEL_POPUP_STREAM_CHUNK`)e.delta&&(Hp+=e.delta,am(lt(Hp)));else if(e.type===`SIDEPANEL_POPUP_STREAM_DONE`)qp=!1,e.finalContent&&(Hp=e.finalContent),am(lt(Hp));else if(e.type===`SIDEPANEL_POPUP_STREAM_ERROR`){if(!qp)return;qp=!1,om(e.error||t(`sidePanel.popupRequestFailed`))}}}))}function _m(){gm(),document.addEventListener(`mousedown`,cm),document.addEventListener(`keydown`,lm)}function vm(e,t,n,r,i){!t||!e||(gm(),nm(n,r),Jp=!1,pm(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 ym(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>
@@ -583,7 +583,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-DvmxOw8q.js"
583
583
  <span style="background:var(--bg-subtle);padding:1px 5px;border-radius:3px;font-size:9px;color:var(--text-secondary);">${k(i)}</span>
584
584
  <span style="font-weight:500;color:var(--text-primary);margin-left:auto;">${S(e.totalTokens)}</span>
585
585
  <span style="color:${o};font-size:9px;font-weight:500;width:35px;text-align:right;">${((e.contextUsageRate||0)*100).toFixed(1)}%</span>
586
- </div>`}).join(``)}function S(e){return e>=1e6?(e/1e6).toFixed(1)+`M`:e>=1e3?(e/1e3).toFixed(1)+`K`:String(e)}function C(e){return e>=.8?`#ef4444`:e>=.5?`#f59e0b`:`#10b981`}}function ym(e){return(e||[]).map(e=>e.token?{...e,token:le(e.token)}:e)}e(`zh`,{sidePanel:{confirmAction:`确认操作`,memoryLimitAll:`全`,memoryLimitTitle:`点击设置记忆历史限制条数`,configUpdated:`✅ 配置已更新`,selectedPrefix:`📌 已选中`,askBasedOnSelection:`基于选中内容提问`,copySelectionTooltip:`复制选中内容`,copySelectionDone:`已复制选中内容`,selectedContentLabel:`选中内容`,selectedContentSummary:`摘要`,userQuestionLabel:`用户问题`,requestFailed:`❌ 请求失败:`,unknownError:`未知错误`,notConnected:`未连接`,noPairedAgents:`暂无已配对代理`,agentDisabled:`已停用`,agentConnected:`已连接`,agentChecking:`检测中...`,agentOnline:`在线`,agentOffline:`离线`,enableAgent:`启用`,disableAgent:`停用`,disconnectAgent:`断开`,connectAgent:`连接`,deleteAgentBtn:`删除`,workingDirectory:`工作目录: {path}`,agentAddressCopied:`已复制代理地址`,unknownAgent:`未知`,restartAgentConfirm:`代理名称:{name}
586
+ </div>`}).join(``)}function S(e){return e>=1e6?(e/1e6).toFixed(1)+`M`:e>=1e3?(e/1e3).toFixed(1)+`K`:String(e)}function C(e){return e>=.8?`#ef4444`:e>=.5?`#f59e0b`:`#10b981`}}function bm(e){return(e||[]).map(e=>e.token?{...e,token:le(e.token)}:e)}e(`zh`,{sidePanel:{confirmAction:`确认操作`,memoryLimitAll:`全`,memoryLimitTitle:`点击设置记忆历史限制条数`,configUpdated:`✅ 配置已更新`,selectedPrefix:`📌 已选中`,askBasedOnSelection:`基于选中内容提问`,copySelectionTooltip:`复制选中内容`,copySelectionDone:`已复制选中内容`,selectedContentLabel:`选中内容`,selectedContentSummary:`摘要`,userQuestionLabel:`用户问题`,requestFailed:`❌ 请求失败:`,unknownError:`未知错误`,notConnected:`未连接`,noPairedAgents:`暂无已配对代理`,agentDisabled:`已停用`,agentConnected:`已连接`,agentChecking:`检测中...`,agentOnline:`在线`,agentOffline:`离线`,enableAgent:`启用`,disableAgent:`停用`,disconnectAgent:`断开`,connectAgent:`连接`,deleteAgentBtn:`删除`,workingDirectory:`工作目录: {path}`,agentAddressCopied:`已复制代理地址`,unknownAgent:`未知`,restartAgentConfirm:`代理名称:{name}
587
587
  代理地址:{url}
588
588
 
589
589
  确定要重启代理服务吗?重启期间服务将短暂不可用。`,restartAgentTitle:`重启代理`,agentRestarting:`代理服务正在重启...`,restartFailed:`重启失败: {error}`,restartRequestFailed:`重启请求失败: {error}`,updateAgentConfirm:`代理名称:{name}
@@ -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,xm(),r.debug(`[SidePanel] auto-compaction config updated:`,v.chatConfig.autoCompaction)),t===`local`&&e.chatPersistSummaryToMemory&&(v.chatConfig.persistSummaryToMemory=e.chatPersistSummaryToMemory.newValue!==!1,Sm(),r.debug(`[SidePanel] persist-summary config updated:`,v.chatConfig.persistSummaryToMemory)),t===`local`&&e.chatMaxMemoryMessages&&(v.chatConfig.maxMemoryMessages=e.chatMaxMemoryMessages.newValue,bm(),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 bm(){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 xm(){let e=document.getElementById(`autoCompactBtn`);e&&(e.checked=v.chatConfig.autoCompaction===!0)}function Sm(){let e=document.getElementById(`persistSummaryBtn`);e&&(e.checked=v.chatConfig.persistSummaryToMemory!==!1)}function Cm(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 wm(){let e=document.getElementById(`memoryLimitDropdown`),n=document.getElementById(`memoryLimitLabel`),r=e?.querySelector(`#memoryLimitInput`);if(!e||!n)return;bm(),n.addEventListener(`click`,Cm);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,bm(),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,bm(),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 Tm(e){if(v.activeAgentId&&v.activeAgentId!=="default")try{let{updateAgent:t}=await E(async()=>{let{updateAgent:e}=await import(`./agent-store-QTeMyM9O.js`).then(e=>e.t);return{updateAgent:e}},__vite__mapDeps([5,1,2,3]));await t(v.activeAgentId,{model:e})}catch{}else chrome.storage.local.set({modelName:e}),ue(e)}async function Em(){try{let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),t=ym(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=nh(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),jr()}catch{}}async function Dm(e,t,n){if(v.activeAgentId&&v.activeAgentId!=="default")try{let{updateAgent:n}=await E(async()=>{let{updateAgent:e}=await import(`./agent-store-QTeMyM9O.js`).then(e=>e.t);return{updateAgent:e}},__vite__mapDeps([5,1,2,3]));await n(v.activeAgentId,{temperature:e,topP:t})}catch{}else chrome.storage.local.set({temperature:e,topP:t,selectedTempIndex:n})}function Om(){let e=document.getElementById(`currentModelTag`);if(!e)return;let t=v.currentModel||``;e.textContent=t,e.title=t,e.style.display=t?``:`none`}var km=new Set,Am=0;function jm(){let e=document.getElementById(`workdirTag`);e&&(e.dataset.locked=ri(v.activeSessionId)?`true`:`false`)}async function Mm(){let e=++Am,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!==Am)return;let l=c&&c.workdir||``;if(!l){n.style.display=`none`;return}n.style.display=``,i.textContent=s(l,{homeDir:v.agentPlatform?.homeDir||``}),jm();try{let{getWorkspaceRoot:e}=await E(async()=>{let{getWorkspaceRoot:e}=await import(`./workspace-manager-DVPkwn2d.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`,Rp(a).then(e=>{e&&Mm()}).catch(e=>r.debug(`[WorkdirTag] reconcile failed:`,e&&e.message))):n.dataset.invalid=i?`true`:`false`}catch{n.dataset.invalid=`false`}if(e===Am&&(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||``}`;km.has(e)||(km.add(e),A(t(`workdirTag.agentSwitched`),`warning`))}}function Nm(){let e=document.getElementById(`workdirTag`);e&&(e.setAttribute(`aria-label`,t(`workdirTag.tagHint`)),e.addEventListener(`click`,async e=>{if(e.stopPropagation(),ri(v.activeSessionId)){jm(),A(t(`workdirTag.lockedHint`),`warning`);return}jm();let{showSwitchWorkdirDialog:n}=await E(async()=>{let{showSwitchWorkdirDialog:e}=await import(`./context-indicator-DSJveMWs.js`).then(e=>e.sn);return{showSwitchWorkdirDialog:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]));await n({sessionId:v.activeSessionId||null})})),Mm(),document.addEventListener(`session-switched`,()=>{Mm()}),document.addEventListener(`session-workdir-changed`,()=>{Mm()}),document.addEventListener(`agent-model-changed`,()=>{Mm()}),document.addEventListener(`agent-tools-changed`,()=>{Mm()}),document.addEventListener(`generating-state-changed`,()=>{jm()}),document.addEventListener(`generation-ended`,()=>{jm()}),$t(()=>{jm()})}function Pm(){let e=document.getElementById(`currentModelTag`);e&&e.addEventListener(`click`,e=>{e.stopPropagation(),document.getElementById(`tempDisplay`)?.click()}),Om()}function Fm(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`),Om()}function Im(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,Sm(),r.debug(`[SidePanel] auto-compaction config updated:`,v.chatConfig.autoCompaction)),t===`local`&&e.chatPersistSummaryToMemory&&(v.chatConfig.persistSummaryToMemory=e.chatPersistSummaryToMemory.newValue!==!1,Cm(),r.debug(`[SidePanel] persist-summary config updated:`,v.chatConfig.persistSummaryToMemory)),t===`local`&&e.chatMaxMemoryMessages&&(v.chatConfig.maxMemoryMessages=e.chatMaxMemoryMessages.newValue,xm(),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 xm(){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 Sm(){let e=document.getElementById(`autoCompactBtn`);e&&(e.checked=v.chatConfig.autoCompaction===!0)}function Cm(){let e=document.getElementById(`persistSummaryBtn`);e&&(e.checked=v.chatConfig.persistSummaryToMemory!==!1)}function wm(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 Tm(){let e=document.getElementById(`memoryLimitDropdown`),n=document.getElementById(`memoryLimitLabel`),r=e?.querySelector(`#memoryLimitInput`);if(!e||!n)return;xm(),n.addEventListener(`click`,wm);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,xm(),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,xm(),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 Em(e){if(v.activeAgentId&&v.activeAgentId!=="default")try{let{updateAgent:t}=await E(async()=>{let{updateAgent:e}=await import(`./agent-store-QTeMyM9O.js`).then(e=>e.t);return{updateAgent:e}},__vite__mapDeps([5,1,2,3]));await t(v.activeAgentId,{model:e})}catch{}else chrome.storage.local.set({modelName:e}),ue(e)}async function Dm(){try{let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),t=bm(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=rh(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),hi()}catch{}}async function Om(e,t,n){if(v.activeAgentId&&v.activeAgentId!=="default")try{let{updateAgent:n}=await E(async()=>{let{updateAgent:e}=await import(`./agent-store-QTeMyM9O.js`).then(e=>e.t);return{updateAgent:e}},__vite__mapDeps([5,1,2,3]));await n(v.activeAgentId,{temperature:e,topP:t})}catch{}else chrome.storage.local.set({temperature:e,topP:t,selectedTempIndex:n})}function km(){let e=document.getElementById(`currentModelTag`);if(!e)return;let t=v.currentModel||``;e.textContent=t,e.title=t,e.style.display=t?``:`none`}var Am=new Set,jm=0;function Mm(){let e=document.getElementById(`workdirTag`);e&&(e.dataset.locked=Rr(v.activeSessionId)?`true`:`false`)}async function Nm(){let e=++jm,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!==jm)return;let l=c&&c.workdir||``;if(!l){n.style.display=`none`;return}n.style.display=``,i.textContent=s(l,{homeDir:v.agentPlatform?.homeDir||``}),Mm();try{let{getWorkspaceRoot:e}=await E(async()=>{let{getWorkspaceRoot:e}=await import(`./workspace-manager-DVPkwn2d.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`,zp(a).then(e=>{e&&Nm()}).catch(e=>r.debug(`[WorkdirTag] reconcile failed:`,e&&e.message))):n.dataset.invalid=i?`true`:`false`}catch{n.dataset.invalid=`false`}if(e===jm&&(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||``}`;Am.has(e)||(Am.add(e),A(t(`workdirTag.agentSwitched`),`warning`))}}function Pm(){let e=document.getElementById(`workdirTag`);e&&(e.setAttribute(`aria-label`,t(`workdirTag.tagHint`)),e.addEventListener(`click`,async e=>{if(e.stopPropagation(),Rr(v.activeSessionId)){Mm(),A(t(`workdirTag.lockedHint`),`warning`);return}Mm();let{showSwitchWorkdirDialog:n}=await E(async()=>{let{showSwitchWorkdirDialog:e}=await import(`./context-indicator-CWyjBBv3.js`).then(e=>e.cn);return{showSwitchWorkdirDialog:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]));await n({sessionId:v.activeSessionId||null})})),Nm(),document.addEventListener(`session-switched`,()=>{Nm()}),document.addEventListener(`session-workdir-changed`,()=>{Nm()}),document.addEventListener(`agent-model-changed`,()=>{Nm()}),document.addEventListener(`agent-tools-changed`,()=>{Nm()}),document.addEventListener(`generating-state-changed`,()=>{Mm()}),document.addEventListener(`generation-ended`,()=>{Mm()}),un(()=>{Mm()})}function Fm(){let e=document.getElementById(`currentModelTag`);e&&e.addEventListener(`click`,e=>{e.stopPropagation(),document.getElementById(`tempDisplay`)?.click()}),km()}function Im(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`),km()}function Lm(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">
@@ -610,7 +610,7 @@ Are you sure you want to stop the agent service? You will not be able to connect
610
610
  <span class="section-select-caret"></span>
611
611
  </div>
612
612
  <div class="section-select-list" id="modelSelectList"></div>
613
- </div>`;let e=i.querySelector(`#modelSelectList`);e.innerHTML=_d();let n=[...a].sort((e,t)=>S(e.name,t.name));for(let r of n){let n=document.createElement(`div`);n.className=`model-option`,n.dataset.value=r.name,r.contextWindow&&r.contextWindow>0&&(n.dataset.contextWindow=r.contextWindow),n.innerHTML=`<span class="model-option-check"></span><span class="model-option-left">${k(r.name)}</span>`;let i=document.createElement(`span`);i.className=`model-option-right`;let a=document.createElement(`span`);a.className=`model-ctx-badge`;let o=r.contextWindow&&r.contextWindow>0;a.textContent=g(o?r.contextWindow:de(r.name)),o||(a.classList.add(`is-auto`),a.title=t(`settings.ctxBadgeAutoTip`)),i.appendChild(a),n.appendChild(i),n.addEventListener(`click`,e=>{e.stopPropagation(),gd(),v.currentModel=r.name,Fm(r.name),Tm(r.name),Br()}),e.appendChild(n)}}v.customModelMap=l(e),typeof n==`function`&&n()}function Lm(e,n=t(`sidePanel.selectedPrefix`)){if(!v.enableSelectionQuery)return;v.quotedContextText=``,v.selectedContextText=e;let r=document.getElementById(`selectionIndicator`),i=document.getElementById(`selectionText`),a=document.getElementById(`userInput`);if(r&&i&&a){let t;t=e.length>100?e.substring(0,100)+`...`:e.length>50?e.substring(0,50)+`...`:e,i.textContent=`${n}: ${t}`,r.classList.add(`show`)}}var Rm=null,zm=``;function Bm(){if(Rm&&Rm.isConnected)return Rm;Rm=document.createElement(`div`),Rm.className=`selection-floating-menu`,Rm.id=`selectionFloatingMenu`,Rm.innerHTML=`
613
+ </div>`;let e=i.querySelector(`#modelSelectList`);e.innerHTML=yd();let n=[...a].sort((e,t)=>S(e.name,t.name));for(let r of n){let n=document.createElement(`div`);n.className=`model-option`,n.dataset.value=r.name,r.contextWindow&&r.contextWindow>0&&(n.dataset.contextWindow=r.contextWindow),n.innerHTML=`<span class="model-option-check"></span><span class="model-option-left">${k(r.name)}</span>`;let i=document.createElement(`span`);i.className=`model-option-right`;let a=document.createElement(`span`);a.className=`model-ctx-badge`;let o=r.contextWindow&&r.contextWindow>0;a.textContent=g(o?r.contextWindow:de(r.name)),o||(a.classList.add(`is-auto`),a.title=t(`settings.ctxBadgeAutoTip`)),i.appendChild(a),n.appendChild(i),n.addEventListener(`click`,e=>{e.stopPropagation(),vd(),v.currentModel=r.name,Im(r.name),Em(r.name),Vr()}),e.appendChild(n)}}v.customModelMap=l(e),typeof n==`function`&&n()}function Rm(e,n=t(`sidePanel.selectedPrefix`)){if(!v.enableSelectionQuery)return;v.quotedContextText=``,v.selectedContextText=e;let r=document.getElementById(`selectionIndicator`),i=document.getElementById(`selectionText`),a=document.getElementById(`userInput`);if(r&&i&&a){let t;t=e.length>100?e.substring(0,100)+`...`:e.length>50?e.substring(0,50)+`...`:e,i.textContent=`${n}: ${t}`,r.classList.add(`show`)}}var zm=null,Bm=``;function Vm(){if(zm&&zm.isConnected)return zm;zm=document.createElement(`div`),zm.className=`selection-floating-menu`,zm.id=`selectionFloatingMenu`,zm.innerHTML=`
614
614
  <div class="menu-header">
615
615
  <span class="menu-header-title"></span>
616
616
  <button class="menu-copy-btn" type="button">
@@ -620,7 +620,7 @@ Are you sure you want to stop the agent service? You will not be able to connect
620
620
  </button>
621
621
  </div>
622
622
  <div class="menu-items"></div>
623
- `;let e=Rm.querySelector(`.menu-copy-btn`);return e?.addEventListener(`click`,n=>{n.stopPropagation(),zm&&(ut(zm,e),A(t(`sidePanel.copySelectionDone`),`success`),window.getSelection()?.removeAllRanges(),window.hideFloatingMenu())}),document.body.appendChild(Rm),Rm}function Vm(e,n,i=0,a=0){if(!v.enableSelectionQuery)return;let o=v.customPrompts.filter(e=>e.enabledInMenu===!0);if(o.length===0){r.debug(`[SidePanel] showFloatingMenu skipped: no prompts enabled in menu`);return}let s=Bm();zm=n||``,s.querySelector(`.menu-header-title`).textContent=t(`sidePanel.askBasedOnSelection`);let c=s.querySelector(`.menu-copy-btn`);c&&(c.title=t(`sidePanel.copySelectionTooltip`));let l=s.querySelector(`.menu-items`);l.innerHTML=``,o.forEach(e=>{let r=e.content.length>10?e.content.substring(0,10)+`...`:e.content,o=document.createElement(`div`);o.className=`menu-item`,o.innerHTML=`
623
+ `;let e=zm.querySelector(`.menu-copy-btn`);return e?.addEventListener(`click`,n=>{n.stopPropagation(),Bm&&(ut(Bm,e),A(t(`sidePanel.copySelectionDone`),`success`),window.getSelection()?.removeAllRanges(),window.hideFloatingMenu())}),document.body.appendChild(zm),zm}function Hm(e,n,i=0,a=0){if(!v.enableSelectionQuery)return;let o=v.customPrompts.filter(e=>e.enabledInMenu===!0);if(o.length===0){r.debug(`[SidePanel] showFloatingMenu skipped: no prompts enabled in menu`);return}let s=Vm();Bm=n||``,s.querySelector(`.menu-header-title`).textContent=t(`sidePanel.askBasedOnSelection`);let c=s.querySelector(`.menu-copy-btn`);c&&(c.title=t(`sidePanel.copySelectionTooltip`));let l=s.querySelector(`.menu-items`);l.innerHTML=``,o.forEach(e=>{let r=e.content.length>10?e.content.substring(0,10)+`...`:e.content,o=document.createElement(`div`);o.className=`menu-item`,o.innerHTML=`
624
624
  <span>${r}</span>
625
625
  <span class="menu-item-actions">
626
626
  <span class="menu-item-code">/${e.code}</span>
@@ -632,9 +632,9 @@ Are you sure you want to stop the agent service? You will not be able to connect
632
632
  </svg>
633
633
  </button>
634
634
  </span>
635
- `,o.addEventListener(`click`,t=>{t.stopPropagation(),Hm(e,n)}),o.querySelector(`.menu-item-popup-btn`).addEventListener(`click`,t=>{t.stopPropagation();let r=v.currentSelectionRange?v.currentSelectionRange.cloneRange():null;window.getSelection()?.removeAllRanges(),window.hideFloatingMenu(),_m(e,n,i,a,r)}),l.appendChild(o)});let u=window.innerWidth,d=window.innerHeight,f=40+o.length*36,p=a-f-30,m=i-20;p<8&&(p=a+30),m+180>u-8&&(m=i-180-30,m<8&&(m=i+20)),m<8&&(m=8),p+f>d-8&&(p=a-f-30,p<8&&(p=8)),s.style.top=p+`px`,s.style.left=m+`px`,s.style.maxHeight=Math.max(120,d-p-20)+`px`,s.classList.add(`show`)}window.hideFloatingMenu=function(){Rm&&Rm.classList.remove(`show`),zm=``,v.lastSelectedText=``,v.currentSelectionRange=null};async function Hm(e,n){if(!v.enableSelectionQuery)return;if(window.hideFloatingMenu(),v.isGenerating){r.debug(`[SidePanel] generating,please wait...`);return}hn()&&Zr(),await rr({state:v,getRatio:()=>Oi().usage?.ratio??0,compact:xi}),v.selectedContextText=n,Un();let i=document.getElementById(`chatContainer`).querySelector(`.welcome-message`);i&&i.remove(),Bt(`selected`,n,!1);let{compressed:a,wasCompressed:o}=ee(n),s=`[${t(`sidePanel.selectedContentLabel`)}${o?t(`sidePanel.selectedContentSummary`):``}]\n${a}\n\n[${t(`sidePanel.userQuestionLabel`)}]\n${e.content}`,{messageId:l,timestamp:d}=cn(`user`,e.content,!0,[],null,!1,s);v.messageHistory.push({role:`user`,content:s,messageId:l,timestamp:d}),kr(),Et(e.content),v.isGenerating=!0;let f=Zt(),p=v.activeSessionId,h=v.currentModel;try{await Ke(),r.debug(`[SidePanel] sendmessagedebuginfo:`),r.debug(` - isolateChat:`,v.isolateChat),r.debug(` - chatConfig:`,v.chatConfig),r.debug(` - messageHistory.length:`,v.messageHistory.length);let n=[{role:`system`,content:await at(null,{sessionId:p})}];if(v.isolateChat){let e=c(n[0]?.content||``),t=m(h,0,v.customModelMap)-e-4096-2e3,i=Math.floor(t*.7),a=v.messageHistory[v.messageHistory.length-1],o=Yt(v.messageHistory.slice(0,-1),{isolateChat:!0,maxMemoryMessages:v.chatConfig.maxMemoryMessages,compaction:v.activeCompaction,historyBudget:i,currentMessage:a});Jn(n,o,v.activeCompaction,r),o.historySummaryText&&(n[0]={...n[0],content:n[0].content+`
635
+ `,o.addEventListener(`click`,t=>{t.stopPropagation(),Um(e,n)}),o.querySelector(`.menu-item-popup-btn`).addEventListener(`click`,t=>{t.stopPropagation();let r=v.currentSelectionRange?v.currentSelectionRange.cloneRange():null;window.getSelection()?.removeAllRanges(),window.hideFloatingMenu(),vm(e,n,i,a,r)}),l.appendChild(o)});let u=window.innerWidth,d=window.innerHeight,f=40+o.length*36,p=a-f-30,m=i-20;p<8&&(p=a+30),m+180>u-8&&(m=i-180-30,m<8&&(m=i+20)),m<8&&(m=8),p+f>d-8&&(p=a-f-30,p<8&&(p=8)),s.style.top=p+`px`,s.style.left=m+`px`,s.style.maxHeight=Math.max(120,d-p-20)+`px`,s.classList.add(`show`)}window.hideFloatingMenu=function(){zm&&zm.classList.remove(`show`),Bm=``,v.lastSelectedText=``,v.currentSelectionRange=null};async function Um(e,n){if(!v.enableSelectionQuery)return;if(window.hideFloatingMenu(),v.isGenerating){r.debug(`[SidePanel] generating,please wait...`);return}yn()&&Ct(),await tr({state:v,getRatio:()=>ki().usage?.ratio??0,compact:xi}),v.selectedContextText=n,Un();let i=document.getElementById(`chatContainer`).querySelector(`.welcome-message`);i&&i.remove(),Bt(`selected`,n,!1);let{compressed:a,wasCompressed:o}=ee(n),s=`[${t(`sidePanel.selectedContentLabel`)}${o?t(`sidePanel.selectedContentSummary`):``}]\n${a}\n\n[${t(`sidePanel.userQuestionLabel`)}]\n${e.content}`,{messageId:l,timestamp:d}=cn(`user`,e.content,!0,[],null,!1,s);v.messageHistory.push({role:`user`,content:s,messageId:l,timestamp:d}),Ar(),Jn(e.content),v.isGenerating=!0;let f=Zt(),p=v.activeSessionId,h=v.currentModel;try{await Ke(),r.debug(`[SidePanel] sendmessagedebuginfo:`),r.debug(` - isolateChat:`,v.isolateChat),r.debug(` - chatConfig:`,v.chatConfig),r.debug(` - messageHistory.length:`,v.messageHistory.length);let n=[{role:`system`,content:await at(null,{sessionId:p})}];if(v.isolateChat){let e=c(n[0]?.content||``),t=m(h,0,v.customModelMap)-e-4096-2e3,i=Math.floor(t*.7),a=v.messageHistory[v.messageHistory.length-1],o=Gn(v.messageHistory.slice(0,-1),{isolateChat:!0,maxMemoryMessages:v.chatConfig.maxMemoryMessages,compaction:v.activeCompaction,historyBudget:i,currentMessage:a});Yt(n,o,v.activeCompaction,r),o.historySummaryText&&(n[0]={...n[0],content:n[0].content+`
636
636
 
637
- `+o.historySummaryText}),n=[...n,...o.messages];for(let e=0;e<n.length-1;e++)n[e]={...n[e],content:u(n[e].content)}}else n.push({role:`user`,content:s});let i=await it(),a,o;try{let t=await wt(n,h,v.useTools,i);if(a=t.content,o=t.executionLog||[],ar(f),t.wasStreamed)t.streamingMsgId&&(v.messageHistory.push({role:`assistant`,content:a,executionLog:o,messageId:t.streamingMsgId}),kr());else{let{element:e,messageId:t}=cn(`assistant`,a,!0,o);await ht(e),v.messageHistory.push({role:`assistant`,content:a,executionLog:o,messageId:t}),kr()}on(p,e.content);return}catch(n){ar(f),a=t(`sidePanel.requestFailed`)+(n.message||t(`sidePanel.unknownError`)),o=n.executionLog||[];let{element:r,messageId:i}=cn(`assistant`,a,!0,o);throw v.messageHistory.push({role:`assistant`,content:a,executionLog:o,messageId:i}),kr(),n.message!==t(`chatMsg.errTaskStopped`)&&yi(p,a,e.content),n}}catch{}finally{Gt(p),document.getElementById(`userInput`).focus()}}var Um=null;async function $(e,n=!1){let r=document.getElementById(`headerAgentDot`),i=document.getElementById(`headerAgentName`),a=document.getElementById(`headerAgentTrigger`);if(!r||!i)return;let o=null,s=[];try{let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]);s=ym(e.pairedAgents),o=s.find(t=>t.id===e.activeAgentId)}catch{}let c=e?.connected===!0;if(c!==Um){Um=c;try{document.dispatchEvent(new CustomEvent(`agent-connection-changed`,{detail:{connected:c}}))}catch{}}if(!c||!o?(r.className=`header-agent-dot disconnected`,i.textContent=o?o.name.length>12?o.name.substring(0,12)+`...`:o.name:t(`sidePanel.notConnected`),i.classList.toggle(`truncated`,!!o),a.title=o?o.name:``):(r.className=`header-agent-dot connected`,i.textContent=o.name.length>12?o.name.substring(0,12)+`...`:o.name,i.classList.toggle(`truncated`,o.name.length>12),a.title=o.name),$m(o,s,c),!n){let e=document.getElementById(`headerAgentDropdown`);e&&e.style.display!==`none`&&ah()}di(c),Mm(),Qm(o,c)}function Wm(e,t){if(!e||!t)return!1;let n=String(e).split(`.`).map(Number),r=String(t).split(`.`).map(Number);return!Number.isFinite(n[0])||!Number.isFinite(r[0])?!1:n[0]===r[0]?(n[1]||0)>(r[1]||0):n[0]>r[0]}function Gm(e,t){let n=String(e).split(`.`).map(Number),r=String(t).split(`.`).map(Number);for(let e=0;e<3;e++){let t=(n[e]||0)-(r[e]||0);if(t)return t}return 0}var Km=3600*1e3,qm=1440*60*1e3,Jm=new Map;function Ym(e){let n=document.getElementById(`agentDdUpdateBtn`);if(!n)return;let r=e?.current||``,i=e?.latest||``,a=!!i&&Gm(i,r)>0;n.classList.toggle(`has-update`,a),n.title=a?t(`sidePanel.agentUpdateAvailable`,{current:r,latest:i}):t(`header.updateAndRestart`)}async function Xm(){try{await chrome.storage.local.remove([`agentUpdateCheck`,`agentUpdateCheckUnsupported`])}catch{}Ym(null)}async function Zm(e,t){let n=null;try{n=(await chrome.storage.local.get(`activeAgentId`)).activeAgentId}catch{}if(n===e&&(Ym(t),t))try{await chrome.storage.local.set({agentUpdateCheck:t})}catch{}}async function Qm(e,t){if(!t||!e?.id){Ym(null);return}let n=`~${chrome.runtime.getManifest().version}`,r=null,i=null;try{let e=await chrome.storage.local.get([`agentUpdateCheck`,`agentUpdateCheckUnsupported`]);r=e.agentUpdateCheck,i=e.agentUpdateCheckUnsupported}catch{}if(r?.agentId===e.id&&r?.target===n&&r?.checkedAt&&Date.now()-r.checkedAt<Km){Ym(r);return}if(i?.agentId===e.id&&i?.target===n&&i?.checkedAt&&Date.now()-i.checkedAt<qm){Ym(null);return}let a=`${e.id}:${n}`;if(Jm.has(a))return;let o=(async()=>{try{let t=await new Promise(e=>{chrome.runtime.sendMessage({type:`AGENT_UPDATE_CHECK`,target:n},t=>{e(chrome.runtime.lastError?null:t)})});if(t?.success&&t.latest){await Zm(e.id,{agentId:e.id,target:n,checkedAt:Date.now(),current:t.current||``,latest:t.latest});return}if(t?.httpStatus===404){try{await chrome.storage.local.set({agentUpdateCheckUnsupported:{agentId:e.id,target:n,checkedAt:Date.now()}})}catch{}await Zm(e.id,null);return}}catch{}finally{Jm.delete(a)}})();Jm.set(a,o),await o}function $m(e,n,r){let i=document.getElementById(`agentDdList`),a=document.getElementById(`agentDdCopyRow`);if(!i||!a)return;if(e?.url?(a.style.display=``,a.querySelector(`.agent-dd-copy-label`).textContent=e.url):a.style.display=`none`,n.length===0){i.innerHTML=`<div class="agent-dd-empty">`+t(`sidePanel.noPairedAgents`)+`</div>`;let e=document.getElementById(`agentDdRestartBtn`),n=document.getElementById(`agentDdUpdateBtn`),r=document.getElementById(`agentDdStopBtn`);e&&(e.disabled=!0),n&&(n.disabled=!0),r&&(r.disabled=!0);return}i.innerHTML=n.map(n=>{let i=n.id===e?.id,a=!!n.disabled,o=v.agentVersions.get(n.id),s=Wm(o,chrome.runtime.getManifest().version),c,l;a?(c=`disabled`,l=t(`sidePanel.agentDisabled`)):i?(c=r?`connected`:`disconnected`,l=t(r?`sidePanel.agentConnected`:`sidePanel.notConnected`)):(c=`checking`,l=t(`sidePanel.agentChecking`));let u=v.agentWorkdirs.get(n.id),d=th(u,v.agentHomeDirs.get(n.id)),f=v.agentSystemInfos.get(n.id);return`
637
+ `+o.historySummaryText}),n=[...n,...o.messages];for(let e=0;e<n.length-1;e++)n[e]={...n[e],content:u(n[e].content)}}else n.push({role:`user`,content:s});let i=await it(),a,o;try{let t=await wt(n,h,v.useTools,i);if(a=t.content,o=t.executionLog||[],or(f),t.wasStreamed)t.streamingMsgId&&(v.messageHistory.push({role:`assistant`,content:a,executionLog:o,messageId:t.streamingMsgId}),Ar());else{let{element:e,messageId:t}=cn(`assistant`,a,!0,o);await ht(e),v.messageHistory.push({role:`assistant`,content:a,executionLog:o,messageId:t}),Ar()}yi(p,e.content);return}catch(n){or(f),a=t(`sidePanel.requestFailed`)+(n.message||t(`sidePanel.unknownError`)),o=n.executionLog||[];let{element:r,messageId:i}=cn(`assistant`,a,!0,o);throw v.messageHistory.push({role:`assistant`,content:a,executionLog:o,messageId:i}),Ar(),n.message!==t(`chatMsg.errTaskStopped`)&&nn(p,a,e.content),n}}catch{}finally{on(p),document.getElementById(`userInput`).focus()}}var Wm=null;async function $(e,n=!1){let r=document.getElementById(`headerAgentDot`),i=document.getElementById(`headerAgentName`),a=document.getElementById(`headerAgentTrigger`);if(!r||!i)return;let o=null,s=[];try{let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]);s=bm(e.pairedAgents),o=s.find(t=>t.id===e.activeAgentId)}catch{}let c=e?.connected===!0;if(c!==Wm){Wm=c;try{document.dispatchEvent(new CustomEvent(`agent-connection-changed`,{detail:{connected:c}}))}catch{}}if(!c||!o?(r.className=`header-agent-dot disconnected`,i.textContent=o?o.name.length>12?o.name.substring(0,12)+`...`:o.name:t(`sidePanel.notConnected`),i.classList.toggle(`truncated`,!!o),a.title=o?o.name:``):(r.className=`header-agent-dot connected`,i.textContent=o.name.length>12?o.name.substring(0,12)+`...`:o.name,i.classList.toggle(`truncated`,o.name.length>12),a.title=o.name),eh(o,s,c),!n){let e=document.getElementById(`headerAgentDropdown`);e&&e.style.display!==`none`&&oh()}Ei(c),Nm(),$m(o,c)}function Gm(e,t){if(!e||!t)return!1;let n=String(e).split(`.`).map(Number),r=String(t).split(`.`).map(Number);return!Number.isFinite(n[0])||!Number.isFinite(r[0])?!1:n[0]===r[0]?(n[1]||0)>(r[1]||0):n[0]>r[0]}function Km(e,t){let n=String(e).split(`.`).map(Number),r=String(t).split(`.`).map(Number);for(let e=0;e<3;e++){let t=(n[e]||0)-(r[e]||0);if(t)return t}return 0}var qm=3600*1e3,Jm=1440*60*1e3,Ym=new Map;function Xm(e){let n=document.getElementById(`agentDdUpdateBtn`);if(!n)return;let r=e?.current||``,i=e?.latest||``,a=!!i&&Km(i,r)>0;n.classList.toggle(`has-update`,a),n.title=a?t(`sidePanel.agentUpdateAvailable`,{current:r,latest:i}):t(`header.updateAndRestart`)}async function Zm(){try{await chrome.storage.local.remove([`agentUpdateCheck`,`agentUpdateCheckUnsupported`])}catch{}Xm(null)}async function Qm(e,t){let n=null;try{n=(await chrome.storage.local.get(`activeAgentId`)).activeAgentId}catch{}if(n===e&&(Xm(t),t))try{await chrome.storage.local.set({agentUpdateCheck:t})}catch{}}async function $m(e,t){if(!t||!e?.id){Xm(null);return}let n=`~${chrome.runtime.getManifest().version}`,r=null,i=null;try{let e=await chrome.storage.local.get([`agentUpdateCheck`,`agentUpdateCheckUnsupported`]);r=e.agentUpdateCheck,i=e.agentUpdateCheckUnsupported}catch{}if(r?.agentId===e.id&&r?.target===n&&r?.checkedAt&&Date.now()-r.checkedAt<qm){Xm(r);return}if(i?.agentId===e.id&&i?.target===n&&i?.checkedAt&&Date.now()-i.checkedAt<Jm){Xm(null);return}let a=`${e.id}:${n}`;if(Ym.has(a))return;let o=(async()=>{try{let t=await new Promise(e=>{chrome.runtime.sendMessage({type:`AGENT_UPDATE_CHECK`,target:n},t=>{e(chrome.runtime.lastError?null:t)})});if(t?.success&&t.latest){await Qm(e.id,{agentId:e.id,target:n,checkedAt:Date.now(),current:t.current||``,latest:t.latest});return}if(t?.httpStatus===404){try{await chrome.storage.local.set({agentUpdateCheckUnsupported:{agentId:e.id,target:n,checkedAt:Date.now()}})}catch{}await Qm(e.id,null);return}}catch{}finally{Ym.delete(a)}})();Ym.set(a,o),await o}function eh(e,n,r){let i=document.getElementById(`agentDdList`),a=document.getElementById(`agentDdCopyRow`);if(!i||!a)return;if(e?.url?(a.style.display=``,a.querySelector(`.agent-dd-copy-label`).textContent=e.url):a.style.display=`none`,n.length===0){i.innerHTML=`<div class="agent-dd-empty">`+t(`sidePanel.noPairedAgents`)+`</div>`;let e=document.getElementById(`agentDdRestartBtn`),n=document.getElementById(`agentDdUpdateBtn`),r=document.getElementById(`agentDdStopBtn`);e&&(e.disabled=!0),n&&(n.disabled=!0),r&&(r.disabled=!0);return}i.innerHTML=n.map(n=>{let i=n.id===e?.id,a=!!n.disabled,o=v.agentVersions.get(n.id),s=Gm(o,chrome.runtime.getManifest().version),c,l;a?(c=`disabled`,l=t(`sidePanel.agentDisabled`)):i?(c=r?`connected`:`disconnected`,l=t(r?`sidePanel.agentConnected`:`sidePanel.notConnected`)):(c=`checking`,l=t(`sidePanel.agentChecking`));let u=v.agentWorkdirs.get(n.id),d=nh(u,v.agentHomeDirs.get(n.id)),f=v.agentSystemInfos.get(n.id);return`
638
638
  <div class="agent-dd-item${i?` active`:``}${a?` disabled`:``}" data-agent-id="${n.id}">
639
639
  <span class="agent-dd-item-dot ${c}"></span>
640
640
  <div class="agent-dd-item-info">
@@ -651,7 +651,7 @@ Are you sure you want to stop the agent service? You will not be able to connect
651
651
  <button class="agent-dd-tool-btn delete" data-action="delete" data-id="${n.id}" title="${t(`sidePanel.deleteAgentBtn`)}">🗑</button>
652
652
  </div>
653
653
  </div>
654
- `}).join(``);let o=document.getElementById(`agentDdRestartBtn`),s=document.getElementById(`agentDdUpdateBtn`),c=document.getElementById(`agentDdStopBtn`),l=!!(e&&r);o&&(o.disabled=!l),s&&(s.disabled=!l),c&&(c.disabled=!l)}async function eh(e,t){if(t)try{let n=new AbortController;setTimeout(()=>n.abort(),2e3);let r=await fetch(`${e}/api/status/detail`,{signal:n.signal,headers:{Authorization:`Bearer ${t}`}});if(r.ok){let e=await r.json();if(e.success)return{online:!0,version:e.version||null,workdir:e.workdir||null,homeDir:e.homeDir||null,platformName:e.platformName||e.platform||null,arch:e.arch||null}}}catch{}try{let t=new AbortController;setTimeout(()=>t.abort(),2e3);let n=await fetch(`${e}/api/status`,{signal:t.signal});if(!n.ok)return{online:!1,version:null,workdir:null,homeDir:null,platformName:null,arch:null};let r=await n.json();return{online:!0,version:r.version||null,workdir:null,homeDir:null,platformName:r.platformName||r.platform||null,arch:r.arch||null}}catch{return{online:!1,version:null,workdir:null,homeDir:null,platformName:null,arch:null}}}function th(e,t){return e?t&&e.startsWith(t)?`~`+e.substring(t.length):e:``}function nh(e,t){return e||``}function rh(e,n){let r=document.querySelector(`.agent-dd-item[data-agent-id="${e}"]`);if(!r)return;let i=r.querySelector(`.agent-dd-item-dot`),a=r.querySelector(`.agent-dd-item-status`),o=r.classList.contains(`active`);i&&(i.classList.remove(`checking`,`connected`,`disconnected`,`online`,`offline`),i.classList.add(o?n?`connected`:`disconnected`:n?`online`:`offline`)),a&&(o?a.textContent=t(n?`sidePanel.agentConnected`:`sidePanel.notConnected`):a.textContent===t(`sidePanel.agentChecking`)&&(a.textContent=t(n?`sidePanel.agentOnline`:`sidePanel.agentOffline`)))}function ih(e,n){if(!n)return;let r=document.querySelector(`.agent-dd-item[data-agent-id="${e}"]`);if(!r)return;let i=r.querySelector(`.agent-dd-item-info`);if(!i)return;let a=th(n,v.agentHomeDirs.get(e)),o=i.querySelector(`.agent-dd-item-workdir`);o?(o.textContent=a,o.title=t(`sidePanel.workingDirectory`,{path:n})):(o=document.createElement(`span`),o.className=`agent-dd-item-workdir`,o.title=t(`sidePanel.workingDirectory`,{path:n}),o.textContent=a,i.appendChild(o))}window.updateAgentItemWorkdir=ih;async function ah(){try{let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),t=ym(e.pairedAgents),n=e.activeAgentId;await Promise.all(t.filter(e=>!e.disabled).map(async e=>{let t=await eh(e.url,e.token),r=t.online;t.version&&v.agentVersions.set(e.id,t.version),t.workdir&&v.agentWorkdirs.set(e.id,t.workdir),t.homeDir&&v.agentHomeDirs.set(e.id,t.homeDir);let i=nh(t.platformName,t.arch);i&&v.agentSystemInfos.set(e.id,i),t.workdir&&ih(e.id,t.workdir),rh(e.id,r),e.id===n&&r!==(v.agentPlatform?.connected===!0)&&(v.agentPlatform={...v.agentPlatform,connected:r},$(v.agentPlatform,!0),r&&oh(e))}))}catch{}}async function oh(e){try{let t=e;if(!t){let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),n=ym(e.pairedAgents),r=e.activeAgentId;t=n.find(e=>e.id===r&&!e.disabled)}if(!t||!t.url){v.agentPlatform={...v.agentPlatform,connected:!0},$(v.agentPlatform),jr();return}if(t.token)try{let e=new AbortController;setTimeout(()=>e.abort(),3e3);let n=await fetch(`${t.url}/api/status/detail`,{signal:e.signal,headers:{Authorization:`Bearer ${t.token}`}});if(n.ok){let e=await n.json();if(e.success){v.agentPlatform={platformName:e.platformName||`Unknown`,platform:e.platform||`unknown`,arch:e.arch||`unknown`,shell:e.shell||`/bin/sh`,homeDir:e.homeDir||``,workdir:e.workdir||``,connected:!0},e.version&&v.agentVersions.set(t.id,e.version),e.workdir&&(v.agentWorkdirs.set(t.id,e.workdir),ih(t.id,e.workdir)),e.homeDir&&v.agentHomeDirs.set(t.id,e.homeDir);let n=nh(e.platformName||e.platform,e.arch);n&&v.agentSystemInfos.set(t.id,n),$(v.agentPlatform),jr();return}}}catch{}try{let e=new AbortController;setTimeout(()=>e.abort(),3e3);let n=await fetch(`${t.url}/api/status`,{signal:e.signal});if(n.ok){let e=await n.json();v.agentPlatform={platformName:e.platformName||e.platform||`Unknown`,platform:e.platform||`unknown`,arch:e.arch||`unknown`,connected:!0},$(v.agentPlatform),jr();return}}catch{}v.agentPlatform={...v.agentPlatform,connected:!0},$(v.agentPlatform),jr()}catch{v.agentPlatform={...v.agentPlatform,connected:!0},$(v.agentPlatform),jr()}}var sh=null;function ch(e,t=20){sh&&clearInterval(sh);let n=0;sh=setInterval(async()=>{if(n++,n>t||!e){clearInterval(sh),sh=null;return}try{let t=ym((await chrome.storage.local.get([`pairedAgents`])).pairedAgents).find(t=>t.id===e);if(!t){clearInterval(sh),sh=null;return}let n=await eh(t.url,t.token);if(n.online){clearInterval(sh),sh=null,n.version&&v.agentVersions.set(e,n.version),n.workdir&&v.agentWorkdirs.set(e,n.workdir),n.homeDir&&v.agentHomeDirs.set(e,n.homeDir);let r=nh(n.platformName,n.arch);r&&v.agentSystemInfos.set(e,r),n.workdir&&ih(e,n.workdir),await oh(t),rh(e,!0)}}catch{}},3e3)}function lh(){let e=document.getElementById(`headerAgentDropdown`),t=document.getElementById(`headerAgentWrapper`);if(!e||!t)return;let n=document.body.clientWidth,r=t.getBoundingClientRect(),i=e.offsetWidth;n<312?(e.style.minWidth=n-16+`px`,e.style.maxWidth=n-16+`px`):(e.style.minWidth=``,e.style.maxWidth=``);let a=r.right+20-i,o=n-i-8;a=Math.max(8,Math.min(o,a)),e.style.left=a-r.left+`px`}async function uh(){let e=document.getElementById(`headerAgentTrigger`),n=document.getElementById(`headerAgentDropdown`),r=document.getElementById(`agentDdCopyBtn`),i=document.getElementById(`agentDdAddBtn`),a=document.getElementById(`agentDdRestartBtn`),o=document.getElementById(`agentDdUpdateBtn`),s=document.getElementById(`agentDdStopBtn`),c=document.getElementById(`agentDdRefreshBtn`);if(!e||!n)return;e.addEventListener(`click`,e=>{e.stopPropagation();let t=n.style.display!==`none`;n.style.display=t?`none`:``,t||(lh(),$(v.agentPlatform||{}),ah())}),document.addEventListener(`click`,t=>{!n.contains(t.target)&&t.target!==e&&(n.style.display=`none`)}),r.addEventListener(`click`,async e=>{e.stopPropagation(),v.activeAgentId;let n=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),r=ym(n.pairedAgents).find(e=>e.id===n.activeAgentId);r?.url&&(await navigator.clipboard.writeText(r.url),A(t(`sidePanel.agentAddressCopied`),`success`))}),i.addEventListener(`click`,async()=>{n.style.display=`none`,await chrome.storage.local.set({optionsInitialTab:`agent`});let e=await chrome.tabs.query({}),t=chrome.runtime.getURL(`options/index.html`),r=e.find(e=>e.url&&e.url.startsWith(t));if(r){chrome.tabs.update(r.id,{active:!0});try{chrome.tabs.sendMessage(r.id,{type:`SWITCH_TAB`,tab:`agent`})}catch{}}else chrome.runtime.openOptionsPage()}),a.addEventListener(`click`,async()=>{n.style.display=`none`;let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),r=ym(e.pairedAgents).find(t=>t.id===e.activeAgentId),i=r?.name||t(`sidePanel.unknownAgent`),a=r?.url||t(`sidePanel.unknownAgent`);if(await window.showCustomConfirm(t(`sidePanel.restartAgentConfirm`,{name:i,url:a}),t(`sidePanel.restartAgentTitle`)))try{chrome.runtime.sendMessage({type:`AGENT_RESTART`},async e=>{e?.success?(A(t(`sidePanel.agentRestarting`),`success`),v.agentPlatform={...v.agentPlatform,connected:!1},await $(v.agentPlatform,!0),r?.id&&rh(r.id,!1),ch(r?.id)):A(t(`sidePanel.restartFailed`,{error:e?.error||t(`sidePanel.unknownError`)}),`error`)})}catch(e){A(t(`sidePanel.restartRequestFailed`,{error:e.message}),`error`)}}),o.addEventListener(`click`,async()=>{n.style.display=`none`;let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),r=ym(e.pairedAgents).find(t=>t.id===e.activeAgentId),i=r?.name||t(`sidePanel.unknownAgent`),a=r?.url||t(`sidePanel.unknownAgent`),o=chrome.runtime.getManifest().version,s=`~${o}`,c=o.split(`.`).slice(0,2).join(`.`)+`.x`;if(await window.showCustomConfirm(t(`sidePanel.updateAgentConfirm`,{name:i,url:a,version:c}),t(`sidePanel.updateAgentTitle`))){A(t(`sidePanel.agentUpdating`),`info`);try{chrome.runtime.sendMessage({type:`AGENT_UPDATE`,target:s},async e=>{if(e?.success&&e.upToDate){await Xm(),A(e.message||t(`sidePanel.agentAlreadyLatest`),`info`);return}e?.success?(await Xm(),A(t(`sidePanel.agentUpdateRestarting`),`success`),v.agentPlatform={...v.agentPlatform,connected:!1},await $(v.agentPlatform,!0),r?.id&&rh(r.id,!1),ch(r?.id)):A(t(`sidePanel.updateFailed`,{error:e?.error||t(`sidePanel.unknownError`)}),`error`)})}catch(e){A(t(`sidePanel.updateRequestFailed`,{error:e.message}),`error`)}}}),s.addEventListener(`click`,async()=>{n.style.display=`none`;let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),r=ym(e.pairedAgents).find(t=>t.id===e.activeAgentId),i=r?.name||t(`sidePanel.unknownAgent`),a=r?.url||t(`sidePanel.unknownAgent`);if(await window.showCustomConfirm(t(`sidePanel.stopAgentConfirm`,{name:i,url:a}),t(`sidePanel.stopAgentTitle`)))try{chrome.runtime.sendMessage({type:`AGENT_STOP`},async e=>{e?.success?(A(t(`sidePanel.agentStopped`),`success`),v.agentPlatform={...v.agentPlatform,connected:!1},await $(v.agentPlatform,!0),r?.id&&rh(r.id,!1)):A(t(`sidePanel.stopFailed`,{error:e?.error||t(`sidePanel.unknownError`)}),`error`)})}catch(e){A(t(`sidePanel.stopRequestFailed`,{error:e.message}),`error`)}}),c&&c.addEventListener(`click`,async()=>{document.querySelectorAll(`.agent-dd-item-dot`).forEach(e=>{e.classList.remove(`online`,`offline`),e.classList.add(`checking`)}),document.querySelectorAll(`.agent-dd-item-status`).forEach(e=>{e.textContent=t(`sidePanel.agentChecking`)}),await ah(),A(t(`sidePanel.agentStatusRefreshed`),`success`)}),document.getElementById(`agentDdList`).addEventListener(`click`,async e=>{let t=e.target.closest(`.agent-dd-tool-btn`),n=e.target.closest(`.agent-dd-item`);if(t){e.stopPropagation(),l(t.dataset.action,t.dataset.id);return}n&&!n.classList.contains(`disabled`)&&!n.classList.contains(`active`)&&(e.stopPropagation(),l(`switch`,n.dataset.agentId))});async function l(e,n){let r=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),i=ym(r.pairedAgents);switch(e){case`enable`:i=i.map(e=>e.id===n?{...e,disabled:!1}:e),await chrome.storage.local.set({pairedAgents:i});break;case`disable`:{i=i.map(e=>e.id===n?{...e,disabled:!0}:e);let e=r.activeAgentId;r.activeAgentId===n&&(e=i.find(e=>e.id!==n&&!e.disabled)?.id||null),await chrome.storage.local.set({pairedAgents:i,activeAgentId:e||``}),e?chrome.runtime.sendMessage({type:`AGENT_CONNECTION_CHANGED`,connected:!0,agentId:e}):chrome.runtime.sendMessage({type:`AGENT_CONNECTION_CHANGED`,connected:!1});break}case`switch`:await chrome.storage.local.set({activeAgentId:n}),chrome.runtime.sendMessage({type:`AGENT_CONNECTION_CHANGED`,connected:!0,agentId:n});break;case`disconnect`:await chrome.storage.local.set({activeAgentId:``}),chrome.runtime.sendMessage({type:`AGENT_CONNECTION_CHANGED`,connected:!1});break;case`delete`:{let e=i.find(e=>e.id===n);if(!await window.showCustomConfirm(t(`sidePanel.deleteAgentTitle`),t(`sidePanel.deleteAgentConfirm`,{name:e?.name||n})))return;i=i.filter(e=>e.id!==n);let a=r.activeAgentId===n?i.find(e=>!e.disabled)?.id||null:r.activeAgentId;await chrome.storage.local.set({pairedAgents:i,activeAgentId:a||``}),a?chrome.runtime.sendMessage({type:`AGENT_CONNECTION_CHANGED`,connected:!0,agentId:a}):chrome.runtime.sendMessage({type:`AGENT_CONNECTION_CHANGED`,connected:!1});break}}let a=document.getElementById(`headerAgentDropdown`);a&&(a.style.display=`none`)}}var dh=new Map,fh=8;function ph(e,t){for(dh.has(e)&&dh.delete(e),dh.set(e,t);dh.size>fh;)dh.delete(dh.keys().next().value)}function mh(e){let t=dh.get(e);if(t!==void 0)return dh.delete(e),dh.set(e,t),t}function hh(e){dh.delete(e)}document.addEventListener(`DOMContentLoaded`,async()=>{await Ge(),mt(()=>{gt()}),nn(),await Promise.allSettled([n().then(()=>{i(),Rr(),o(()=>{i(),Rr()})}),Ye(),_t(),Yi()]),window.__tableBlocks=[],chrome.runtime.onMessage.addListener(e=>{if(e.type===`SCHEDULED_SESSION_UPDATED`){let t=e.sessionId,n=e.phase===`started`;t===v.activeSessionId?(v.generatingSessionIds.has(t)||v.pendingCallApiSessionIds.has(t)||tn().catch(()=>{}),n&&Ha(t)):t&&(n||Li(t).catch(()=>{}),document.dispatchEvent(new CustomEvent(`session-cache-invalidate`,{detail:{sessionId:t}})));return}if(e.type===`CLOSE_SIDEPANEL`){r.debug(`[SidePanel] recei to CLOSE_SIDEPANEL,closesidebar`);try{window.close()}catch{}return}if(e.type===`SELECTION_AI_SEARCH`&&e.prompt&&(r.debug(`[SidePanel] received selectedtext AI search:`,e.selectedText?.substring(0,50)),e.selectedText&&Lm(e.selectedText),hr(e.prompt,e.selectedText),chrome.storage.session.remove(`pendingSelectionSearch`).catch(()=>{})),e.type===`FILL_SIDEPANEL_INPUT`&&e.text&&(r.debug(`[SidePanel] received follow-upfill:`,e.text?.substring(0,50)),an(e.text),chrome.storage.session.remove(`pendingFillInput`).catch(()=>{})),e.type===`DIRECT_SEND`&&e.text&&(r.debug(`[SidePanel] received directsend:`,e.text?.substring(0,50)),e.selectedText&&Lm(e.selectedText),Xn(e.text,e.selectedText||``),chrome.storage.session.remove(`pendingDirectSend`).catch(()=>{})),e.type===`AGENT_STATUS_CHANGE`&&(r.debug(`[SidePanel] recei to Agent status change:`,e.connected,e.status),v.agentPlatform={...v.agentPlatform,connected:e.connected},$(v.agentPlatform),jr(),ei(),e.connected&&oh()),e.type===`AGENT_CONNECTION_CHANGED`){if(r.debug(`[SidePanel] recei to Agent connection statuschanged:`,e.connected,e.agentId),!e.connected){v.agentPlatform={connected:!1},$(v.agentPlatform),jr(),ei();return}e.agentId&&(async()=>{try{let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),t=ym(e.pairedAgents).find(t=>t.id===e.activeAgentId&&!t.disabled);if(!t){v.agentPlatform={connected:!1},$(v.agentPlatform),jr(),ei(),pr();return}if(t.token)try{let n=await fetch(`${t.url}/api/status/detail`,{cache:`no-cache`,headers:{Authorization:`Bearer ${t.token}`}});if(n.ok){let t=await n.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(e.activeAgentId,t.version),t.workdir&&v.agentWorkdirs.set(e.activeAgentId,t.workdir),t.homeDir&&v.agentHomeDirs.set(e.activeAgentId,t.homeDir);let n=nh(t.platformName||t.platform,t.arch);n&&v.agentSystemInfos.set(e.activeAgentId,n)}else v.agentPlatform={connected:!1}}else v.agentPlatform={connected:!1}}catch{v.agentPlatform={connected:!1}}else try{let n=await fetch(`${t.url}/api/status`,{cache:`no-cache`});if(n.ok){let t=await n.json();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(e.activeAgentId,t.version);let r=nh(t.platformName||t.platform,t.arch);r&&v.agentSystemInfos.set(e.activeAgentId,r)}else v.agentPlatform={connected:!1}}catch{v.agentPlatform={connected:!1}}}catch{v.agentPlatform={connected:!1}}$(v.agentPlatform),jr(),ei(),pr()})()}e.type===`SCREENSHOT_RESULT`&&e.dataUrl&&(r.debug(`[SidePanel] received pageshortcutscreenshotresult:`,e.mode),Mi(e.dataUrl,e.mode,e.rect))});async function e(e){try{let t=await chrome.sidePanel.getOptions({tabId:e});return typeof t?.enabled==`boolean`?t.enabled:(await chrome.sidePanel.getOptions({}))?.enabled!==!1}catch{return!0}}chrome.tabs.onActivated.addListener(async t=>{if(r.debug(`[SidePanel] Tab switch, new Tab ID:`,t.tabId),!await e(t.tabId)){r.debug(`[SidePanel] Tab 无侧边栏,保持 currentTabId:`,v.currentTabId);return}v.currentTabId=t.tabId}),chrome.tabs.onUpdated.addListener(async(e,t)=>{t.status===`complete`&&v.currentTabId===e&&r.debug(`[SidePanel] current Tab page update:`,t)}),typeof marked<`u`&&(marked.setOptions({breaks:!0,gfm:!0}),r.debug(`[SidePanel] Marked library loaded`));let a=document.getElementById(`userInput`),s=document.getElementById(`sendBtn`),c=document.getElementById(`clearChatBtn`),l=document.getElementById(`exportChatBtn`),u=document.getElementById(`chatContainer`),d=document.getElementById(`tempDisplay`),p=document.getElementById(`tempDropdown`),m=document.getElementById(`tempPresetList`),h=document.getElementById(`tempSlider`),g=document.getElementById(`tempNumberInput`);function ee(){if(!a||v.isScrolling)return;a.style.height=`auto`;let e=a.scrollHeight;e<=50?a.style.height=``:a.style.height=Math.min(e,100)+`px`,ot()}chrome.storage.local.get([`temperature`,`topP`,`selectedTempIndex`],e=>{(!v.activeAgentId||v.activeAgentId==="default")&&(e.temperature!==void 0&&(v.temperature=e.temperature),e.topP!==void 0&&(v.topP=e.topP),e.selectedTempIndex!==void 0&&(v.selectedTempIndex=e.selectedTempIndex)),te()});function te(){h&&(h.value=v.temperature),g&&(g.value=v.temperature.toFixed(2));let e=document.getElementById(`tempIconValue`);e&&(e.textContent=v.temperature.toFixed(2)),_()}function ne(){let e=0,t=Math.abs(Gn[0].temp-v.temperature);for(let n=1;n<Gn.length;n++){let r=Math.abs(Gn[n].temp-v.temperature);r<t&&(t=r,e=n)}return e}function _(){let e=ne();m.innerHTML=Gn.map((n,r)=>`
654
+ `}).join(``);let o=document.getElementById(`agentDdRestartBtn`),s=document.getElementById(`agentDdUpdateBtn`),c=document.getElementById(`agentDdStopBtn`),l=!!(e&&r);o&&(o.disabled=!l),s&&(s.disabled=!l),c&&(c.disabled=!l)}async function th(e,t){if(t)try{let n=new AbortController;setTimeout(()=>n.abort(),2e3);let r=await fetch(`${e}/api/status/detail`,{signal:n.signal,headers:{Authorization:`Bearer ${t}`}});if(r.ok){let e=await r.json();if(e.success)return{online:!0,version:e.version||null,workdir:e.workdir||null,homeDir:e.homeDir||null,platformName:e.platformName||e.platform||null,arch:e.arch||null}}}catch{}try{let t=new AbortController;setTimeout(()=>t.abort(),2e3);let n=await fetch(`${e}/api/status`,{signal:t.signal});if(!n.ok)return{online:!1,version:null,workdir:null,homeDir:null,platformName:null,arch:null};let r=await n.json();return{online:!0,version:r.version||null,workdir:null,homeDir:null,platformName:r.platformName||r.platform||null,arch:r.arch||null}}catch{return{online:!1,version:null,workdir:null,homeDir:null,platformName:null,arch:null}}}function nh(e,t){return e?t&&e.startsWith(t)?`~`+e.substring(t.length):e:``}function rh(e,t){return e||``}function ih(e,n){let r=document.querySelector(`.agent-dd-item[data-agent-id="${e}"]`);if(!r)return;let i=r.querySelector(`.agent-dd-item-dot`),a=r.querySelector(`.agent-dd-item-status`),o=r.classList.contains(`active`);i&&(i.classList.remove(`checking`,`connected`,`disconnected`,`online`,`offline`),i.classList.add(o?n?`connected`:`disconnected`:n?`online`:`offline`)),a&&(o?a.textContent=t(n?`sidePanel.agentConnected`:`sidePanel.notConnected`):a.textContent===t(`sidePanel.agentChecking`)&&(a.textContent=t(n?`sidePanel.agentOnline`:`sidePanel.agentOffline`)))}function ah(e,n){if(!n)return;let r=document.querySelector(`.agent-dd-item[data-agent-id="${e}"]`);if(!r)return;let i=r.querySelector(`.agent-dd-item-info`);if(!i)return;let a=nh(n,v.agentHomeDirs.get(e)),o=i.querySelector(`.agent-dd-item-workdir`);o?(o.textContent=a,o.title=t(`sidePanel.workingDirectory`,{path:n})):(o=document.createElement(`span`),o.className=`agent-dd-item-workdir`,o.title=t(`sidePanel.workingDirectory`,{path:n}),o.textContent=a,i.appendChild(o))}window.updateAgentItemWorkdir=ah;async function oh(){try{let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),t=bm(e.pairedAgents),n=e.activeAgentId;await Promise.all(t.filter(e=>!e.disabled).map(async e=>{let t=await th(e.url,e.token),r=t.online;t.version&&v.agentVersions.set(e.id,t.version),t.workdir&&v.agentWorkdirs.set(e.id,t.workdir),t.homeDir&&v.agentHomeDirs.set(e.id,t.homeDir);let i=rh(t.platformName,t.arch);i&&v.agentSystemInfos.set(e.id,i),t.workdir&&ah(e.id,t.workdir),ih(e.id,r),e.id===n&&r!==(v.agentPlatform?.connected===!0)&&(v.agentPlatform={...v.agentPlatform,connected:r},$(v.agentPlatform,!0),r&&sh(e))}))}catch{}}async function sh(e){try{let t=e;if(!t){let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),n=bm(e.pairedAgents),r=e.activeAgentId;t=n.find(e=>e.id===r&&!e.disabled)}if(!t||!t.url){v.agentPlatform={...v.agentPlatform,connected:!0},$(v.agentPlatform),hi();return}if(t.token)try{let e=new AbortController;setTimeout(()=>e.abort(),3e3);let n=await fetch(`${t.url}/api/status/detail`,{signal:e.signal,headers:{Authorization:`Bearer ${t.token}`}});if(n.ok){let e=await n.json();if(e.success){v.agentPlatform={platformName:e.platformName||`Unknown`,platform:e.platform||`unknown`,arch:e.arch||`unknown`,shell:e.shell||`/bin/sh`,homeDir:e.homeDir||``,workdir:e.workdir||``,connected:!0},e.version&&v.agentVersions.set(t.id,e.version),e.workdir&&(v.agentWorkdirs.set(t.id,e.workdir),ah(t.id,e.workdir)),e.homeDir&&v.agentHomeDirs.set(t.id,e.homeDir);let n=rh(e.platformName||e.platform,e.arch);n&&v.agentSystemInfos.set(t.id,n),$(v.agentPlatform),hi();return}}}catch{}try{let e=new AbortController;setTimeout(()=>e.abort(),3e3);let n=await fetch(`${t.url}/api/status`,{signal:e.signal});if(n.ok){let e=await n.json();v.agentPlatform={platformName:e.platformName||e.platform||`Unknown`,platform:e.platform||`unknown`,arch:e.arch||`unknown`,connected:!0},$(v.agentPlatform),hi();return}}catch{}v.agentPlatform={...v.agentPlatform,connected:!0},$(v.agentPlatform),hi()}catch{v.agentPlatform={...v.agentPlatform,connected:!0},$(v.agentPlatform),hi()}}var ch=null;function lh(e,t=20){ch&&clearInterval(ch);let n=0;ch=setInterval(async()=>{if(n++,n>t||!e){clearInterval(ch),ch=null;return}try{let t=bm((await chrome.storage.local.get([`pairedAgents`])).pairedAgents).find(t=>t.id===e);if(!t){clearInterval(ch),ch=null;return}let n=await th(t.url,t.token);if(n.online){clearInterval(ch),ch=null,n.version&&v.agentVersions.set(e,n.version),n.workdir&&v.agentWorkdirs.set(e,n.workdir),n.homeDir&&v.agentHomeDirs.set(e,n.homeDir);let r=rh(n.platformName,n.arch);r&&v.agentSystemInfos.set(e,r),n.workdir&&ah(e,n.workdir),await sh(t),ih(e,!0)}}catch{}},3e3)}function uh(){let e=document.getElementById(`headerAgentDropdown`),t=document.getElementById(`headerAgentWrapper`);if(!e||!t)return;let n=document.body.clientWidth,r=t.getBoundingClientRect(),i=e.offsetWidth;n<312?(e.style.minWidth=n-16+`px`,e.style.maxWidth=n-16+`px`):(e.style.minWidth=``,e.style.maxWidth=``);let a=r.right+20-i,o=n-i-8;a=Math.max(8,Math.min(o,a)),e.style.left=a-r.left+`px`}async function dh(){let e=document.getElementById(`headerAgentTrigger`),n=document.getElementById(`headerAgentDropdown`),r=document.getElementById(`agentDdCopyBtn`),i=document.getElementById(`agentDdAddBtn`),a=document.getElementById(`agentDdRestartBtn`),o=document.getElementById(`agentDdUpdateBtn`),s=document.getElementById(`agentDdStopBtn`),c=document.getElementById(`agentDdRefreshBtn`);if(!e||!n)return;e.addEventListener(`click`,e=>{e.stopPropagation();let t=n.style.display!==`none`;n.style.display=t?`none`:``,t||(uh(),$(v.agentPlatform||{}),oh())}),document.addEventListener(`click`,t=>{!n.contains(t.target)&&t.target!==e&&(n.style.display=`none`)}),r.addEventListener(`click`,async e=>{e.stopPropagation(),v.activeAgentId;let n=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),r=bm(n.pairedAgents).find(e=>e.id===n.activeAgentId);r?.url&&(await navigator.clipboard.writeText(r.url),A(t(`sidePanel.agentAddressCopied`),`success`))}),i.addEventListener(`click`,async()=>{n.style.display=`none`,await chrome.storage.local.set({optionsInitialTab:`agent`});let e=await chrome.tabs.query({}),t=chrome.runtime.getURL(`options/index.html`),r=e.find(e=>e.url&&e.url.startsWith(t));if(r){chrome.tabs.update(r.id,{active:!0});try{chrome.tabs.sendMessage(r.id,{type:`SWITCH_TAB`,tab:`agent`})}catch{}}else chrome.runtime.openOptionsPage()}),a.addEventListener(`click`,async()=>{n.style.display=`none`;let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),r=bm(e.pairedAgents).find(t=>t.id===e.activeAgentId),i=r?.name||t(`sidePanel.unknownAgent`),a=r?.url||t(`sidePanel.unknownAgent`);if(await window.showCustomConfirm(t(`sidePanel.restartAgentConfirm`,{name:i,url:a}),t(`sidePanel.restartAgentTitle`)))try{chrome.runtime.sendMessage({type:`AGENT_RESTART`},async e=>{e?.success?(A(t(`sidePanel.agentRestarting`),`success`),v.agentPlatform={...v.agentPlatform,connected:!1},await $(v.agentPlatform,!0),r?.id&&ih(r.id,!1),lh(r?.id)):A(t(`sidePanel.restartFailed`,{error:e?.error||t(`sidePanel.unknownError`)}),`error`)})}catch(e){A(t(`sidePanel.restartRequestFailed`,{error:e.message}),`error`)}}),o.addEventListener(`click`,async()=>{n.style.display=`none`;let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),r=bm(e.pairedAgents).find(t=>t.id===e.activeAgentId),i=r?.name||t(`sidePanel.unknownAgent`),a=r?.url||t(`sidePanel.unknownAgent`),o=chrome.runtime.getManifest().version,s=`~${o}`,c=o.split(`.`).slice(0,2).join(`.`)+`.x`;if(await window.showCustomConfirm(t(`sidePanel.updateAgentConfirm`,{name:i,url:a,version:c}),t(`sidePanel.updateAgentTitle`))){A(t(`sidePanel.agentUpdating`),`info`);try{chrome.runtime.sendMessage({type:`AGENT_UPDATE`,target:s},async e=>{if(e?.success&&e.upToDate){await Zm(),A(e.message||t(`sidePanel.agentAlreadyLatest`),`info`);return}e?.success?(await Zm(),A(t(`sidePanel.agentUpdateRestarting`),`success`),v.agentPlatform={...v.agentPlatform,connected:!1},await $(v.agentPlatform,!0),r?.id&&ih(r.id,!1),lh(r?.id)):A(t(`sidePanel.updateFailed`,{error:e?.error||t(`sidePanel.unknownError`)}),`error`)})}catch(e){A(t(`sidePanel.updateRequestFailed`,{error:e.message}),`error`)}}}),s.addEventListener(`click`,async()=>{n.style.display=`none`;let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),r=bm(e.pairedAgents).find(t=>t.id===e.activeAgentId),i=r?.name||t(`sidePanel.unknownAgent`),a=r?.url||t(`sidePanel.unknownAgent`);if(await window.showCustomConfirm(t(`sidePanel.stopAgentConfirm`,{name:i,url:a}),t(`sidePanel.stopAgentTitle`)))try{chrome.runtime.sendMessage({type:`AGENT_STOP`},async e=>{e?.success?(A(t(`sidePanel.agentStopped`),`success`),v.agentPlatform={...v.agentPlatform,connected:!1},await $(v.agentPlatform,!0),r?.id&&ih(r.id,!1)):A(t(`sidePanel.stopFailed`,{error:e?.error||t(`sidePanel.unknownError`)}),`error`)})}catch(e){A(t(`sidePanel.stopRequestFailed`,{error:e.message}),`error`)}}),c&&c.addEventListener(`click`,async()=>{document.querySelectorAll(`.agent-dd-item-dot`).forEach(e=>{e.classList.remove(`online`,`offline`),e.classList.add(`checking`)}),document.querySelectorAll(`.agent-dd-item-status`).forEach(e=>{e.textContent=t(`sidePanel.agentChecking`)}),await oh(),A(t(`sidePanel.agentStatusRefreshed`),`success`)}),document.getElementById(`agentDdList`).addEventListener(`click`,async e=>{let t=e.target.closest(`.agent-dd-tool-btn`),n=e.target.closest(`.agent-dd-item`);if(t){e.stopPropagation(),l(t.dataset.action,t.dataset.id);return}n&&!n.classList.contains(`disabled`)&&!n.classList.contains(`active`)&&(e.stopPropagation(),l(`switch`,n.dataset.agentId))});async function l(e,n){let r=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),i=bm(r.pairedAgents);switch(e){case`enable`:i=i.map(e=>e.id===n?{...e,disabled:!1}:e),await chrome.storage.local.set({pairedAgents:i});break;case`disable`:{i=i.map(e=>e.id===n?{...e,disabled:!0}:e);let e=r.activeAgentId;r.activeAgentId===n&&(e=i.find(e=>e.id!==n&&!e.disabled)?.id||null),await chrome.storage.local.set({pairedAgents:i,activeAgentId:e||``}),e?chrome.runtime.sendMessage({type:`AGENT_CONNECTION_CHANGED`,connected:!0,agentId:e}):chrome.runtime.sendMessage({type:`AGENT_CONNECTION_CHANGED`,connected:!1});break}case`switch`:await chrome.storage.local.set({activeAgentId:n}),chrome.runtime.sendMessage({type:`AGENT_CONNECTION_CHANGED`,connected:!0,agentId:n});break;case`disconnect`:await chrome.storage.local.set({activeAgentId:``}),chrome.runtime.sendMessage({type:`AGENT_CONNECTION_CHANGED`,connected:!1});break;case`delete`:{let e=i.find(e=>e.id===n);if(!await window.showCustomConfirm(t(`sidePanel.deleteAgentTitle`),t(`sidePanel.deleteAgentConfirm`,{name:e?.name||n})))return;i=i.filter(e=>e.id!==n);let a=r.activeAgentId===n?i.find(e=>!e.disabled)?.id||null:r.activeAgentId;await chrome.storage.local.set({pairedAgents:i,activeAgentId:a||``}),a?chrome.runtime.sendMessage({type:`AGENT_CONNECTION_CHANGED`,connected:!0,agentId:a}):chrome.runtime.sendMessage({type:`AGENT_CONNECTION_CHANGED`,connected:!1});break}}let a=document.getElementById(`headerAgentDropdown`);a&&(a.style.display=`none`)}}var fh=new Map,ph=8;function mh(e,t){for(fh.has(e)&&fh.delete(e),fh.set(e,t);fh.size>ph;)fh.delete(fh.keys().next().value)}function hh(e){let t=fh.get(e);if(t!==void 0)return fh.delete(e),fh.set(e,t),t}function gh(e){fh.delete(e)}document.addEventListener(`DOMContentLoaded`,async()=>{await Ge(),mt(()=>{gt()}),ir(),await Promise.allSettled([n().then(()=>{i(),Fr(),o(()=>{i(),Fr()})}),Ye(),_t(),yr()]),window.__tableBlocks=[],chrome.runtime.onMessage.addListener(e=>{if(e.type===`SCHEDULED_SESSION_UPDATED`){let t=e.sessionId,n=e.phase===`started`;t===v.activeSessionId?(v.generatingSessionIds.has(t)||v.pendingCallApiSessionIds.has(t)||tn().catch(()=>{}),n&&Ua(t)):t&&(n||Xi(t).catch(()=>{}),document.dispatchEvent(new CustomEvent(`session-cache-invalidate`,{detail:{sessionId:t}})));return}if(e.type===`CLOSE_SIDEPANEL`){r.debug(`[SidePanel] recei to CLOSE_SIDEPANEL,closesidebar`);try{window.close()}catch{}return}if(e.type===`SELECTION_AI_SEARCH`&&e.prompt&&(r.debug(`[SidePanel] received selectedtext AI search:`,e.selectedText?.substring(0,50)),e.selectedText&&Rm(e.selectedText),gr(e.prompt,e.selectedText),chrome.storage.session.remove(`pendingSelectionSearch`).catch(()=>{})),e.type===`FILL_SIDEPANEL_INPUT`&&e.text&&(r.debug(`[SidePanel] received follow-upfill:`,e.text?.substring(0,50)),an(e.text),chrome.storage.session.remove(`pendingFillInput`).catch(()=>{})),e.type===`DIRECT_SEND`&&e.text&&(r.debug(`[SidePanel] received directsend:`,e.text?.substring(0,50)),e.selectedText&&Rm(e.selectedText),Xn(e.text,e.selectedText||``),chrome.storage.session.remove(`pendingDirectSend`).catch(()=>{})),e.type===`AGENT_STATUS_CHANGE`&&(r.debug(`[SidePanel] recei to Agent status change:`,e.connected,e.status),v.agentPlatform={...v.agentPlatform,connected:e.connected},$(v.agentPlatform),hi(),Fi(),e.connected&&sh()),e.type===`AGENT_CONNECTION_CHANGED`){if(r.debug(`[SidePanel] recei to Agent connection statuschanged:`,e.connected,e.agentId),!e.connected){v.agentPlatform={connected:!1},$(v.agentPlatform),hi(),Fi();return}e.agentId&&(async()=>{try{let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),t=bm(e.pairedAgents).find(t=>t.id===e.activeAgentId&&!t.disabled);if(!t){v.agentPlatform={connected:!1},$(v.agentPlatform),hi(),Fi(),di();return}if(t.token)try{let n=await fetch(`${t.url}/api/status/detail`,{cache:`no-cache`,headers:{Authorization:`Bearer ${t.token}`}});if(n.ok){let t=await n.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(e.activeAgentId,t.version),t.workdir&&v.agentWorkdirs.set(e.activeAgentId,t.workdir),t.homeDir&&v.agentHomeDirs.set(e.activeAgentId,t.homeDir);let n=rh(t.platformName||t.platform,t.arch);n&&v.agentSystemInfos.set(e.activeAgentId,n)}else v.agentPlatform={connected:!1}}else v.agentPlatform={connected:!1}}catch{v.agentPlatform={connected:!1}}else try{let n=await fetch(`${t.url}/api/status`,{cache:`no-cache`});if(n.ok){let t=await n.json();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(e.activeAgentId,t.version);let r=rh(t.platformName||t.platform,t.arch);r&&v.agentSystemInfos.set(e.activeAgentId,r)}else v.agentPlatform={connected:!1}}catch{v.agentPlatform={connected:!1}}}catch{v.agentPlatform={connected:!1}}$(v.agentPlatform),hi(),Fi(),di()})()}e.type===`SCREENSHOT_RESULT`&&e.dataUrl&&(r.debug(`[SidePanel] received pageshortcutscreenshotresult:`,e.mode),Tr(e.dataUrl,e.mode,e.rect))});async function e(e){try{let t=await chrome.sidePanel.getOptions({tabId:e});return typeof t?.enabled==`boolean`?t.enabled:(await chrome.sidePanel.getOptions({}))?.enabled!==!1}catch{return!0}}chrome.tabs.onActivated.addListener(async t=>{if(r.debug(`[SidePanel] Tab switch, new Tab ID:`,t.tabId),!await e(t.tabId)){r.debug(`[SidePanel] Tab 无侧边栏,保持 currentTabId:`,v.currentTabId);return}v.currentTabId=t.tabId}),chrome.tabs.onUpdated.addListener(async(e,t)=>{t.status===`complete`&&v.currentTabId===e&&r.debug(`[SidePanel] current Tab page update:`,t)}),typeof marked<`u`&&(marked.setOptions({breaks:!0,gfm:!0}),r.debug(`[SidePanel] Marked library loaded`));let a=document.getElementById(`userInput`),s=document.getElementById(`sendBtn`),c=document.getElementById(`clearChatBtn`),l=document.getElementById(`exportChatBtn`),u=document.getElementById(`chatContainer`),d=document.getElementById(`tempDisplay`),p=document.getElementById(`tempDropdown`),m=document.getElementById(`tempPresetList`),h=document.getElementById(`tempSlider`),g=document.getElementById(`tempNumberInput`);function ee(){if(!a||v.isScrolling)return;a.style.height=`auto`;let e=a.scrollHeight;e<=50?a.style.height=``:a.style.height=Math.min(e,100)+`px`,ot()}chrome.storage.local.get([`temperature`,`topP`,`selectedTempIndex`],e=>{(!v.activeAgentId||v.activeAgentId==="default")&&(e.temperature!==void 0&&(v.temperature=e.temperature),e.topP!==void 0&&(v.topP=e.topP),e.selectedTempIndex!==void 0&&(v.selectedTempIndex=e.selectedTempIndex)),te()});function te(){h&&(h.value=v.temperature),g&&(g.value=v.temperature.toFixed(2));let e=document.getElementById(`tempIconValue`);e&&(e.textContent=v.temperature.toFixed(2)),_()}function ne(){let e=0,t=Math.abs(Qn[0].temp-v.temperature);for(let n=1;n<Qn.length;n++){let r=Math.abs(Qn[n].temp-v.temperature);r<t&&(t=r,e=n)}return e}function _(){let e=ne();m.innerHTML=Qn.map((n,r)=>`
655
655
  <div class="temp-preset-item ${r===e?`selected`:``}" data-index="${r}">
656
656
  <div class="temp-preset-radio"></div>
657
657
  <div class="temp-preset-info">
@@ -660,15 +660,15 @@ Are you sure you want to stop the agent service? You will not be able to connect
660
660
  </div>
661
661
  <div class="temp-preset-value">${n.temp.toFixed(2)}</div>
662
662
  </div>
663
- `).join(``),m.querySelectorAll(`.temp-preset-item`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),y(parseInt(e.dataset.index))})})}function y(e){let t=Gn[e];t&&(v.selectedTempIndex=e,v.temperature=t.temp,te(),Dm(v.temperature,v.topP,v.selectedTempIndex))}h.addEventListener(`input`,e=>{e.stopPropagation();let t=parseFloat(e.target.value);isNaN(t)&&(t=0),t=Math.max(0,Math.min(1,t)),v.temperature=t,g.value=t.toFixed(2);let n=document.getElementById(`tempIconValue`);n&&(n.textContent=t.toFixed(2)),_(),Dm(v.temperature,v.topP,ne())}),g.addEventListener(`change`,e=>{e.stopPropagation();let t=parseFloat(e.target.value);isNaN(t)&&(t=0),t=Math.max(0,Math.min(1,t)),v.temperature=t,h.value=t,g.value=t.toFixed(2);let n=document.getElementById(`tempIconValue`);n&&(n.textContent=t.toFixed(2)),_(),Dm(v.temperature,v.topP,ne())}),d&&p&&(d.addEventListener(`click`,e=>{e.stopPropagation(),p.classList.toggle(`show`)}),document.addEventListener(`click`,e=>{let t=document.querySelector(`.temp-selector`);t&&!t.contains(e.target)&&p.classList.remove(`show`)})),document.addEventListener(`mousedown`,e=>{ss(e.target)&&(v.lastMouseX=e.clientX,v.lastMouseY=e.clientY)}),document.addEventListener(`mouseup`,e=>{ss(e.target)&&(v.lastMouseX=e.clientX,v.lastMouseY=e.clientY,v.enableSelectionQuery&&setTimeout(()=>{let e=window.getSelection();if(e&&!e.isCollapsed&&e.toString().trim()){let t=e.toString().trim();ss(e.anchorNode)&&(v.lastSelectedText=t,v.currentSelectionRange=e.getRangeAt(0).cloneRange(),Lm(t),Vm(e,t,v.lastMouseX,v.lastMouseY))}else ss(e.anchorNode)||(v.lastSelectedText=``,v.currentSelectionRange=null,window.hideFloatingMenu())},50))});let b=``,x=null;async function ie(){try{let e=await new Promise(e=>{chrome.tabs.query({active:!0,currentWindow:!0},t=>e(t))});if(e&&e.length>0){let t=await new Promise(t=>{chrome.tabs.sendMessage(e[0].id,{action:`getSelectedText`},e=>{chrome.runtime.lastError?(console.debug(`[SidePanel] content script not loaded or unreachable:`,chrome.runtime.lastError.message),t(null)):t(e)})});if(!t)return;let n=t?.text||``;n&&n.trim()?n!==b&&(b=n,Lm(n.trim())):b=``}}catch{}}function S(){x&&=(clearInterval(x),null),v.enableSelectionQuery&&(x=setInterval(ie,500))}S(),chrome.storage.onChanged.addListener((e,t)=>{if(t===`local`&&`enableSelectionQuery`in e){v.enableSelectionQuery=e.enableSelectionQuery.newValue;let t=document.getElementById(`enableSelectionQueryBtn`);t&&(t.checked=v.enableSelectionQuery),S()}}),await re(),xd(),chrome.storage.local.get([`modelName`,`customModels`,`customPrompts`,`systemPrompt`,`inputHistory`,`agentPlatform`,`enableImageInput`,`imageModelName`,`imageApiBase`,`imageApiKey`,`enableFileInput`],e=>{let t=e.modelName;t&&(v.currentModel=t),v.customPrompts=e.customPrompts||[],v.systemPrompt=e.systemPrompt||``,v.inputHistory=e.inputHistory||[],e.agentPlatform&&(v.agentPlatform=e.agentPlatform),$(v.agentPlatform),chrome.runtime.sendMessage({type:`TRIGGER_AGENT_HEALTH_CHECK`}).catch(()=>{}),Em(),v.enableImageInput=e.enableImageInput||!1,v.imageModelName=e.imageModelName||``,v.imageApiBase=e.imageApiBase||``,v.imageApiKey=le(e.imageApiKey)||``,v.enableFileInput=!0,hi(),jr(),It(),Im(e.customModels,()=>{t&&Fm(t)})}),chrome.storage.onChanged.addListener((e,t)=>{if(t===`local`){if(e.customModels&&Im(e.customModels.newValue||[],()=>{Fm(v.currentModel)}),e.modelName){let t=e.modelName.newValue;t&&(!v.activeAgentId||v.activeAgentId==="default")&&(v.currentModel=t,Fm(t))}if(e.enableImageInput&&(v.enableImageInput=e.enableImageInput.newValue,hi()),e.enableFileInput&&(v.enableFileInput=e.enableFileInput.newValue,jr()),e.enableExecutionLog&&(v.chatConfig.enableExecutionLog=e.enableExecutionLog.newValue),e.showMessageTimestamp){let t=e.showMessageTimestamp.newValue!==!1;v.chatConfig.showMessageTimestamp=t,li(t)}e.systemPrompt&&(v.systemPrompt=e.systemPrompt.newValue||``),e.imageModelName&&(v.imageModelName=e.imageModelName.newValue||``),e.imageApiBase&&(v.imageApiBase=e.imageApiBase.newValue||``),e.imageApiKey&&(v.imageApiKey=le(e.imageApiKey.newValue)||``)}}),await tn(),await jp();let C=await chrome.storage.session.get([`pendingSelectionSearch`,`pendingFillInput`,`pendingDirectSend`]),ae=[];if(C.pendingSelectionSearch&&C.pendingSelectionSearch.selectedText){let{prompt:e,selectedText:t}=C.pendingSelectionSearch;r.debug(`[SidePanel] pending selected textsearch:`,t?.substring(0,50)),Lm(t),setTimeout(()=>{hr(e,t)},500),ae.push(`pendingSelectionSearch`)}if(C.pendingFillInput&&C.pendingFillInput.text){let{text:e}=C.pendingFillInput;r.debug(`[SidePanel] pending fill trackasktext:`,e?.substring(0,50)),setTimeout(()=>{an(e)},500),ae.push(`pendingFillInput`)}if(C.pendingDirectSend&&C.pendingDirectSend.text){let{text:e,selectedText:t}=C.pendingDirectSend;r.debug(`[SidePanel] pending directsend text:`,e?.substring(0,50)),t&&Lm(t),setTimeout(()=>{Xn(e,t||``)},500),ae.push(`pendingDirectSend`)}ae.length>0&&await chrome.storage.session.remove(ae);let oe=document.getElementById(`userInput`);oe&&oe.focus(),document.addEventListener(`session-switched`,e=>{let{sessionId:n,previousSessionId:i}=e.detail||{},a=document.getElementById(`chatContainer`),o=document.getElementById(`userInput`);if(!a)return;let s=i&&v.messageHistory?.some(e=>e.resumable);if(i&&!v.pendingCallApiSessionIds.has(i)&&!s){let e=Ct(a);e&&ph(i,e)}let c=document.getElementById(`imagePreviewBar`);v.attachedImages.length>0&&c&&c.style.display===`none`&&(v.attachedImages=[]),v.executionLogListener&&=(chrome.runtime.onMessage.removeListener(v.executionLogListener),null),ce(),o&&o.focus();let l=v.pendingCallApiSessionIds.has(n)&&!!v.pendingCancelApi,u=mh(n),d=v.messageHistory&&v.messageHistory.length>0;if(u&&!l&&d){if(a.innerHTML=u,nr(a),st(),dt(),!e.detail?.skipScrollRestore){let e=`scrollPosition_`+(n||`default`);chrome.storage.local.get([e],t=>{t[e]!==void 0&&setTimeout(()=>{let n=document.getElementById(`chatContainer`);n&&(n.scrollTop=t[e])},150)})}Cn();return}if(a.innerHTML=``,d){if(v.messageHistory.forEach(e=>{e.htmlContent?On(e.htmlContent,e.messageId,e.resumable):cn(e.role,e.content,!1,e.executionLog||[],e.reflectionScore,e.wasRevised,null,e.messageId,[],e.resumable||!1,e.timestamp??null)}),jn(),Zi(),st(),dt(),!v.pendingCallApiSessionIds.has(n)){let e=Ct(a);e&&ph(n,e)}Cn()}else{let e=document.createElement(`div`);e.className=`welcome-message`,e.innerHTML=`
663
+ `).join(``),m.querySelectorAll(`.temp-preset-item`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),y(parseInt(e.dataset.index))})})}function y(e){let t=Qn[e];t&&(v.selectedTempIndex=e,v.temperature=t.temp,te(),Om(v.temperature,v.topP,v.selectedTempIndex))}h.addEventListener(`input`,e=>{e.stopPropagation();let t=parseFloat(e.target.value);isNaN(t)&&(t=0),t=Math.max(0,Math.min(1,t)),v.temperature=t,g.value=t.toFixed(2);let n=document.getElementById(`tempIconValue`);n&&(n.textContent=t.toFixed(2)),_(),Om(v.temperature,v.topP,ne())}),g.addEventListener(`change`,e=>{e.stopPropagation();let t=parseFloat(e.target.value);isNaN(t)&&(t=0),t=Math.max(0,Math.min(1,t)),v.temperature=t,h.value=t,g.value=t.toFixed(2);let n=document.getElementById(`tempIconValue`);n&&(n.textContent=t.toFixed(2)),_(),Om(v.temperature,v.topP,ne())}),d&&p&&(d.addEventListener(`click`,e=>{e.stopPropagation(),p.classList.toggle(`show`)}),document.addEventListener(`click`,e=>{let t=document.querySelector(`.temp-selector`);t&&!t.contains(e.target)&&p.classList.remove(`show`)})),document.addEventListener(`mousedown`,e=>{cs(e.target)&&(v.lastMouseX=e.clientX,v.lastMouseY=e.clientY)}),document.addEventListener(`mouseup`,e=>{cs(e.target)&&(v.lastMouseX=e.clientX,v.lastMouseY=e.clientY,v.enableSelectionQuery&&setTimeout(()=>{let e=window.getSelection();if(e&&!e.isCollapsed&&e.toString().trim()){let t=e.toString().trim();cs(e.anchorNode)&&(v.lastSelectedText=t,v.currentSelectionRange=e.getRangeAt(0).cloneRange(),Rm(t),Hm(e,t,v.lastMouseX,v.lastMouseY))}else cs(e.anchorNode)||(v.lastSelectedText=``,v.currentSelectionRange=null,window.hideFloatingMenu())},50))});let b=``,x=null;async function ie(){try{let e=await new Promise(e=>{chrome.tabs.query({active:!0,currentWindow:!0},t=>e(t))});if(e&&e.length>0){let t=await new Promise(t=>{chrome.tabs.sendMessage(e[0].id,{action:`getSelectedText`},e=>{chrome.runtime.lastError?(console.debug(`[SidePanel] content script not loaded or unreachable:`,chrome.runtime.lastError.message),t(null)):t(e)})});if(!t)return;let n=t?.text||``;n&&n.trim()?n!==b&&(b=n,Rm(n.trim())):b=``}}catch{}}function S(){x&&=(clearInterval(x),null),v.enableSelectionQuery&&(x=setInterval(ie,500))}S(),chrome.storage.onChanged.addListener((e,t)=>{if(t===`local`&&`enableSelectionQuery`in e){v.enableSelectionQuery=e.enableSelectionQuery.newValue;let t=document.getElementById(`enableSelectionQueryBtn`);t&&(t.checked=v.enableSelectionQuery),S()}}),await re(),Cd(),chrome.storage.local.get([`modelName`,`customModels`,`customPrompts`,`systemPrompt`,`inputHistory`,`agentPlatform`,`enableImageInput`,`imageModelName`,`imageApiBase`,`imageApiKey`,`enableFileInput`],e=>{let t=e.modelName;t&&(v.currentModel=t),v.customPrompts=e.customPrompts||[],v.systemPrompt=e.systemPrompt||``,v.inputHistory=e.inputHistory||[],e.agentPlatform&&(v.agentPlatform=e.agentPlatform),$(v.agentPlatform),chrome.runtime.sendMessage({type:`TRIGGER_AGENT_HEALTH_CHECK`}).catch(()=>{}),Dm(),v.enableImageInput=e.enableImageInput||!1,v.imageModelName=e.imageModelName||``,v.imageApiBase=e.imageApiBase||``,v.imageApiKey=le(e.imageApiKey)||``,v.enableFileInput=!0,ii(),hi(),It(),Lm(e.customModels,()=>{t&&Im(t)})}),chrome.storage.onChanged.addListener((e,t)=>{if(t===`local`){if(e.customModels&&Lm(e.customModels.newValue||[],()=>{Im(v.currentModel)}),e.modelName){let t=e.modelName.newValue;t&&(!v.activeAgentId||v.activeAgentId==="default")&&(v.currentModel=t,Im(t))}if(e.enableImageInput&&(v.enableImageInput=e.enableImageInput.newValue,ii()),e.enableFileInput&&(v.enableFileInput=e.enableFileInput.newValue,hi()),e.enableExecutionLog&&(v.chatConfig.enableExecutionLog=e.enableExecutionLog.newValue),e.showMessageTimestamp){let t=e.showMessageTimestamp.newValue!==!1;v.chatConfig.showMessageTimestamp=t,li(t)}e.systemPrompt&&(v.systemPrompt=e.systemPrompt.newValue||``),e.imageModelName&&(v.imageModelName=e.imageModelName.newValue||``),e.imageApiBase&&(v.imageApiBase=e.imageApiBase.newValue||``),e.imageApiKey&&(v.imageApiKey=le(e.imageApiKey.newValue)||``)}}),await tn(),await Mp();let C=await chrome.storage.session.get([`pendingSelectionSearch`,`pendingFillInput`,`pendingDirectSend`]),ae=[];if(C.pendingSelectionSearch&&C.pendingSelectionSearch.selectedText){let{prompt:e,selectedText:t}=C.pendingSelectionSearch;r.debug(`[SidePanel] pending selected textsearch:`,t?.substring(0,50)),Rm(t),setTimeout(()=>{gr(e,t)},500),ae.push(`pendingSelectionSearch`)}if(C.pendingFillInput&&C.pendingFillInput.text){let{text:e}=C.pendingFillInput;r.debug(`[SidePanel] pending fill trackasktext:`,e?.substring(0,50)),setTimeout(()=>{an(e)},500),ae.push(`pendingFillInput`)}if(C.pendingDirectSend&&C.pendingDirectSend.text){let{text:e,selectedText:t}=C.pendingDirectSend;r.debug(`[SidePanel] pending directsend text:`,e?.substring(0,50)),t&&Rm(t),setTimeout(()=>{Xn(e,t||``)},500),ae.push(`pendingDirectSend`)}ae.length>0&&await chrome.storage.session.remove(ae);let oe=document.getElementById(`userInput`);oe&&oe.focus(),document.addEventListener(`session-switched`,e=>{let{sessionId:n,previousSessionId:i}=e.detail||{},a=document.getElementById(`chatContainer`),o=document.getElementById(`userInput`);if(!a)return;let s=i&&v.messageHistory?.some(e=>e.resumable);if(i&&!v.pendingCallApiSessionIds.has(i)&&!s){let e=Jr(a);e&&mh(i,e)}let c=document.getElementById(`imagePreviewBar`);v.attachedImages.length>0&&c&&c.style.display===`none`&&(v.attachedImages=[]),v.executionLogListener&&=(chrome.runtime.onMessage.removeListener(v.executionLogListener),null),ce(),o&&o.focus();let l=v.pendingCallApiSessionIds.has(n)&&!!v.pendingCancelApi,u=hh(n),d=v.messageHistory&&v.messageHistory.length>0;if(u&&!l&&d){if(a.innerHTML=u,rr(a),st(),dt(),!e.detail?.skipScrollRestore){let e=`scrollPosition_`+(n||`default`);chrome.storage.local.get([e],t=>{t[e]!==void 0&&setTimeout(()=>{let n=document.getElementById(`chatContainer`);n&&(n.scrollTop=t[e])},150)})}Qr();return}if(a.innerHTML=``,d){if(v.messageHistory.forEach(e=>{e.htmlContent?On(e.htmlContent,e.messageId,e.resumable):cn(e.role,e.content,!1,e.executionLog||[],e.reflectionScore,e.wasRevised,null,e.messageId,[],e.resumable||!1,e.timestamp??null)}),jn(),Qi(),st(),dt(),!v.pendingCallApiSessionIds.has(n)){let e=Jr(a);e&&mh(n,e)}Qr()}else{let e=document.createElement(`div`);e.className=`welcome-message`,e.innerHTML=`
664
664
  <div class="icon-wrapper">
665
665
  <div class="icon">💬</div>
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`),vr(n)),Ha(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-DSJveMWs.js`).then(e=>e.ft);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&&hh(t)}),document.querySelectorAll(`.model-option`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation();let n=e.dataset.value;v.currentModel=n,Fm(n),Tm(n),Br()})}),document.addEventListener(`agent-model-changed`,()=>{Fm(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)&&sn();let a=document.getElementById(`fileAtSelector`);if(a&&!a.contains(e.target)&&Gd(),i&&!i.contains(e.target)){let t=window.getSelection(),n=ss(e.target),r=t&&!t.isCollapsed&&ss(t.anchorNode);(!n||!r)&&window.hideFloatingMenu()}});let w=document.getElementById(`stopCompanionBtn`);function se(){let e=!!(a&&a.value&&a.value.trim())||Yr();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){Ai();return}se()?xt():Er(s)}),w?.addEventListener(`click`,()=>Er(w));function T(e){if(!v.isGenerating)return!1;let n=v.activeSessionId;return n?pn(n)?(Qt(n),Er(w&&w.style.display!==`none`?w:e||s)?(A(t(`queue.stopAndSendStarted`),`success`,2500),!0):(Tt(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||!pn(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||!pn(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=os();qr(),Jt({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`?mr():xr()}if(e.key===`Escape`&&qn()){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(),br();return}if(e.altKey&&e.shiftKey&&e.code===`KeyS`&&!e.ctrlKey&&!e.metaKey){e.preventDefault(),$r();return}if(Wn(e)){e.preventDefault(),Zn();return}if(e.altKey&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&e.code===`KeyN`){e.preventDefault(),Or();return}if(e.altKey&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&e.code===`KeyW`){e.preventDefault(),kn();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(Pn);for(let e=0;e<t.length;e++)if(r=(r+1)%t.length,n(t[r])){Dr(t[r]);break}return}let r,i;n?(r=document.getElementById(`agentAtList`),i=v.selectedAgentAtIndex):Pn===`pages`?(r=document.getElementById(`agentPageList`),i=v.selectedPageIndex):Pn===`proxies`?(r=document.getElementById(`agentProxyList`),i=v.selectedProxyAtIndex):Pn===`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,ki(a)):Pn===`proxies`?(v.selectedProxyAtIndex=t,ki(a)):Pn===`knowledge`?(v.selectedKnowledgeAtIndex=t,ki(a)):Pn===`pages`?(v.selectedPageIndex=t,dn(a)):(v.selectedAgentAtIndex=t,ki(a));return}else if(e.key===`ArrowUp`){e.preventDefault();let t=i<0||i===0?o-1:i-1;n?(v.selectedAgentAtIndex=t,ki(a)):Pn===`proxies`?(v.selectedProxyAtIndex=t,ki(a)):Pn===`knowledge`?(v.selectedKnowledgeAtIndex=t,ki(a)):Pn===`pages`?(v.selectedPageIndex=t,dn(a)):(v.selectedAgentAtIndex=t,ki(a));return}else if(e.key===`Enter`&&i>=0){e.preventDefault(),a[i].click(),(e.ctrlKey||e.metaKey)&&sn();return}else if(e.key===`Escape`){sn();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,Xd(n));return}if(e.key===`Enter`&&r>0&&v.selectedFileAtIndex>=0){e.preventDefault(),n[v.selectedFileAtIndex].click();return}if(e.key===`Escape`){e.preventDefault(),Gd();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,wn(t);return}if(e.key===`ArrowUp`){e.preventDefault(),v.selectedPromptIndex<0||v.selectedPromptIndex===0?v.selectedPromptIndex=r-1:--v.selectedPromptIndex,wn(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?Jr(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,zi(t);return}if(e.key===`ArrowUp`){e.preventDefault(),v.selectedSkillIndex<0||v.selectedSkillIndex===0?v.selectedSkillIndex=r-1:--v.selectedSkillIndex,zi(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`?Fn(`mcp`):Fn(`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(),Fn(`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(),Fn(`skills`);return}if(n&&n.style.display!==`none`){e.preventDefault(),Fn(`mcp`);return}}if(r!==0&&e.key===`ArrowDown`){e.preventDefault(),v.selectedPromptIndex<0?v.selectedPromptIndex=0:v.selectedPromptIndex=(v.selectedPromptIndex+1)%r,wn(t);return}if(e.key===`ArrowUp`){e.preventDefault(),v.selectedPromptIndex<0||v.selectedPromptIndex===0?v.selectedPromptIndex=r-1:--v.selectedPromptIndex,wn(t);return}if(e.key===`Enter`&&(e.ctrlKey||e.metaKey)&&v.selectedPromptIndex>=0){e.preventDefault();let n=t[v.selectedPromptIndex].dataset.code;Jr(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()&&!Yr()&&Tp()){e.preventDefault();return}if(!c&&!l&&!u){let t=np({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(),Gd(),v.isGenerating){if(e.altKey){Tn(a.value);return}xt();return}Ai()}}),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&&Wi(t);break}if(n.kind===`file`&&v.enableFileInput){e.preventDefault();let t=n.getAsFile();t&&Ii([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 Wi(e);else A(t(`sidePanel.imageNotEnabled`)),Ii(n);r.length>0&&Ii(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){si([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 Wi(e);else A(t(`sidePanel.imageNotEnabled`)),Ii(n);r.length>0&&Ii(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 br()}catch(e){r.error(`[SidePanel] screenshot failed:`,e),A(t(`sidePanel.screenshotFailed`))}}),In(),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`),br(n)),Ua(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-CWyjBBv3.js`).then(e=>e.ft);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&&gh(t)}),document.querySelectorAll(`.model-option`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation();let n=e.dataset.value;v.currentModel=n,Im(n),Em(n),Vr()})}),document.addEventListener(`agent-model-changed`,()=>{Im(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)&&bi();let a=document.getElementById(`fileAtSelector`);if(a&&!a.contains(e.target)&&qd(),i&&!i.contains(e.target)){let t=window.getSelection(),n=cs(e.target),r=t&&!t.isCollapsed&&cs(t.anchorNode);(!n||!r)&&window.hideFloatingMenu()}});let w=document.getElementById(`stopCompanionBtn`);function se(){let e=!!(a&&a.value&&a.value.trim())||xt();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){Mi();return}se()?Kr():Dr(s)}),w?.addEventListener(`click`,()=>Dr(w));function T(e){if(!v.isGenerating)return!1;let n=v.activeSessionId;return n?_n(n)?(ln(n),Dr(w&&w.style.display!==`none`?w:e||s)?(A(t(`queue.stopAndSendStarted`),`success`,2500),!0):(qn(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||!_n(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||!_n(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=ss();hn(),Wn({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`?fi():ti()}if(e.key===`Escape`&&Jt()){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(),ei();return}if(e.altKey&&e.shiftKey&&e.code===`KeyS`&&!e.ctrlKey&&!e.metaKey){e.preventDefault(),Pi();return}if(Zn(e)){e.preventDefault(),Gt();return}if(e.altKey&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&e.code===`KeyN`){e.preventDefault(),ji();return}if(e.altKey&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&e.code===`KeyW`){e.preventDefault(),vt();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(ta);for(let e=0;e<t.length;e++)if(r=(r+1)%t.length,n(t[r])){Ai(t[r]);break}return}let r,i;n?(r=document.getElementById(`agentAtList`),i=v.selectedAgentAtIndex):ta===`pages`?(r=document.getElementById(`agentPageList`),i=v.selectedPageIndex):ta===`proxies`?(r=document.getElementById(`agentProxyList`),i=v.selectedProxyAtIndex):ta===`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,ci(a)):ta===`proxies`?(v.selectedProxyAtIndex=t,ci(a)):ta===`knowledge`?(v.selectedKnowledgeAtIndex=t,ci(a)):ta===`pages`?(v.selectedPageIndex=t,Pn(a)):(v.selectedAgentAtIndex=t,ci(a));return}else if(e.key===`ArrowUp`){e.preventDefault();let t=i<0||i===0?o-1:i-1;n?(v.selectedAgentAtIndex=t,ci(a)):ta===`proxies`?(v.selectedProxyAtIndex=t,ci(a)):ta===`knowledge`?(v.selectedKnowledgeAtIndex=t,ci(a)):ta===`pages`?(v.selectedPageIndex=t,Pn(a)):(v.selectedAgentAtIndex=t,ci(a));return}else if(e.key===`Enter`&&i>=0){e.preventDefault(),a[i].click(),(e.ctrlKey||e.metaKey)&&bi();return}else if(e.key===`Escape`){bi();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,Qd(n));return}if(e.key===`Enter`&&r>0&&v.selectedFileAtIndex>=0){e.preventDefault(),n[v.selectedFileAtIndex].click();return}if(e.key===`Escape`){e.preventDefault(),qd();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,wn(t);return}if(e.key===`ArrowUp`){e.preventDefault(),v.selectedPromptIndex<0||v.selectedPromptIndex===0?v.selectedPromptIndex=r-1:--v.selectedPromptIndex,wn(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?Yr(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,Vi(t);return}if(e.key===`ArrowUp`){e.preventDefault(),v.selectedSkillIndex<0||v.selectedSkillIndex===0?v.selectedSkillIndex=r-1:--v.selectedSkillIndex,Vi(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`?Fn(`mcp`):Fn(`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(),Fn(`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(),Fn(`skills`);return}if(n&&n.style.display!==`none`){e.preventDefault(),Fn(`mcp`);return}}if(r!==0&&e.key===`ArrowDown`){e.preventDefault(),v.selectedPromptIndex<0?v.selectedPromptIndex=0:v.selectedPromptIndex=(v.selectedPromptIndex+1)%r,wn(t);return}if(e.key===`ArrowUp`){e.preventDefault(),v.selectedPromptIndex<0||v.selectedPromptIndex===0?v.selectedPromptIndex=r-1:--v.selectedPromptIndex,wn(t);return}if(e.key===`Enter`&&(e.ctrlKey||e.metaKey)&&v.selectedPromptIndex>=0){e.preventDefault();let n=t[v.selectedPromptIndex].dataset.code;Yr(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()&&!xt()&&Ep()){e.preventDefault();return}if(!c&&!l&&!u){let t=rp({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(),qd(),v.isGenerating){if(e.altKey){Vt(a.value);return}Kr();return}Mi()}}),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&&In(t);break}if(n.kind===`file`&&v.enableFileInput){e.preventDefault();let t=n.getAsFile();t&&Yi([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 In(e);else A(t(`sidePanel.imageNotEnabled`)),Yi(n);r.length>0&&Yi(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){Si([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 In(e);else A(t(`sidePanel.imageNotEnabled`)),Yi(n);r.length>0&&Yi(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 ei()}catch(e){r.error(`[SidePanel] screenshot failed:`,e),A(t(`sidePanel.screenshotFailed`))}}),kt(),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
- `))},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(),sn(),Wd(t.substring(s+1));else if(f&&f.key===`at`)Mt(),Gd(),yt(t.substring(o+1));else if(f&&f.key===`slash`){sn(),Gd();let e=t.substring(i+1);n.style.display!==`none`&&r.classList.contains(`show`)?gn(e):fn(e)}else Mt(),sn(),Gd();ee()});let xe=rp((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=tt();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(),ct(e.dataset.themeValue),ke()})})),Oe(),mt(Oe),o(Oe),c.addEventListener(`click`,e=>{e.stopPropagation(),ke(),Ur()}),l&&l.addEventListener(`click`,e=>{e.stopPropagation(),ke(),Bn()});let Ae=document.getElementById(`importChatBtn`);Ae&&Ae.addEventListener(`click`,e=>{e.stopPropagation(),ke(),Lt()});let je=document.getElementById(`importSessionsFile`);je&&je.addEventListener(`change`,e=>{let t=e.target.files[0];t&&kt(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(),or()});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`),Ke=document.getElementById(`auditLogList`),qe=[],Je={auth:t(`sidePanel.auditCategoryAuth`),fs:t(`sidePanel.auditCategoryFs`),exec:t(`sidePanel.auditCategoryExec`),security:t(`sidePanel.auditCategorySecurity`),system:t(`sidePanel.auditCategorySystem`)},Xe={info:`INFO`,warn:`WARN`,error:`ERROR`},Ze={info:`audit-level-info`,warn:`audit-level-warn`,error:`audit-level-error`};function Qe(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 $e(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 et(){if(!Ue||!We||!Ke)return;Ue.style.display=`block`,We.style.display=`none`,Ke.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}qe=r.entries||[],rt()}catch(e){Ue.style.display=`none`,We.style.display=`block`,We.textContent=t(`sidePanel.auditLoadFailed`,{error:e.message})}}function rt(){if(!Ke)return;let e=(Ve?.value||``).trim().toLowerCase(),n=qe;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`),Ke.style.display=`none`;return}We.style.display=`none`,Ke.style.display=`block`,Ke.innerHTML=n.map(e=>{let t=k(Je[e.category]||e.category||`-`),n=k(Xe[e.level]||e.level?.toUpperCase()||`INFO`),r=Ze[e.level]||`audit-level-info`,i=Qe(e.timestamp),a=k($e(e));return`<div class="audit-entry">
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(),bi(),Kd(t.substring(s+1));else if(f&&f.key===`at`)Mt(),qd(),Or(t.substring(o+1));else if(f&&f.key===`slash`){bi(),qd();let e=t.substring(i+1);n.style.display!==`none`&&r.classList.contains(`show`)?gn(e):fn(e)}else Mt(),bi(),qd();ee()});let xe=ip((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=tt();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(),ct(e.dataset.themeValue),ke()})})),Oe(),mt(Oe),o(Oe),c.addEventListener(`click`,e=>{e.stopPropagation(),ke(),Wr()}),l&&l.addEventListener(`click`,e=>{e.stopPropagation(),ke(),Lt()});let Ae=document.getElementById(`importChatBtn`);Ae&&Ae.addEventListener(`click`,e=>{e.stopPropagation(),ke(),Nt()});let je=document.getElementById(`importSessionsFile`);je&&je.addEventListener(`change`,e=>{let t=e.target.files[0];t&&Hi(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(),kn()});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`),Ke=document.getElementById(`auditLogList`),qe=[],Je={auth:t(`sidePanel.auditCategoryAuth`),fs:t(`sidePanel.auditCategoryFs`),exec:t(`sidePanel.auditCategoryExec`),security:t(`sidePanel.auditCategorySecurity`),system:t(`sidePanel.auditCategorySystem`)},Xe={info:`INFO`,warn:`WARN`,error:`ERROR`},Ze={info:`audit-level-info`,warn:`audit-level-warn`,error:`audit-level-error`};function Qe(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 $e(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 et(){if(!Ue||!We||!Ke)return;Ue.style.display=`block`,We.style.display=`none`,Ke.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}qe=r.entries||[],rt()}catch(e){Ue.style.display=`none`,We.style.display=`block`,We.textContent=t(`sidePanel.auditLoadFailed`,{error:e.message})}}function rt(){if(!Ke)return;let e=(Ve?.value||``).trim().toLowerCase(),n=qe;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`),Ke.style.display=`none`;return}We.style.display=`none`,Ke.style.display=`block`,Ke.innerHTML=n.map(e=>{let t=k(Je[e.category]||e.category||`-`),n=k(Xe[e.level]||e.level?.toUpperCase()||`INFO`),r=Ze[e.level]||`audit-level-info`,i=Qe(e.timestamp),a=k($e(e));return`<div class="audit-entry">
672
672
  <div class="audit-entry-header">
673
673
  <span class="audit-time">${i}</span>
674
674
  <span class="audit-level ${r}">${n}</span>
@@ -676,7 +676,7 @@ Are you sure you want to stop the agent service? You will not be able to connect
676
676
  <span class="audit-action">${k(e.action||`-`)}</span>
677
677
  </div>
678
678
  ${a?`<div class="audit-details">${a}</div>`:``}
679
- </div>`}).join(``)}function it(){Ie&&(Ie.style.display=`flex`,et())}function at(){Ie&&(Ie.style.display=`none`)}Fe&&Fe.addEventListener(`click`,e=>{e.stopPropagation(),ke(),it()}),Le&&Le.addEventListener(`click`,at),Re&&Re.addEventListener(`click`,et),ze&&ze.addEventListener(`change`,et),Be&&Be.addEventListener(`change`,et),Ve&&Ve.addEventListener(`input`,()=>{rt()}),He&&He.addEventListener(`click`,()=>{Ve&&(Ve.value=``),rt()}),vm(()=>v.activeSessionId,window.showCustomConfirm);let lt=document.getElementById(`isolateChatBtn`),j=document.getElementById(`enableToolsBtn`),ut=document.getElementById(`toolsConfigBtn`),ft=`agentEnabledTools_${v.activeAgentId||`default`}`,pt=`agentMcpClosedServers_${v.activeAgentId||`default`}`;chrome.storage.local.get([ft,`enabledTools`,`isolateChat`,`enableSelectionQuery`,`enableTools`,pt,`mcpTools`,`mcpEnabled`,`ragTools`,`ragToolsIntroduced`],e=>{e.isolateChat!==void 0&&(v.isolateChat=e.isolateChat),lt.checked=v.isolateChat,e.enableSelectionQuery!==void 0&&(v.enableSelectionQuery=e.enableSelectionQuery);let t=document.getElementById(`enableSelectionQueryBtn`);t&&(t.checked=v.enableSelectionQuery),e.enableTools!==void 0&&(v.useTools=e.enableTools),v.activeAgentId&&E(async()=>{let{getAgent:e}=await import(`./agent-store-QTeMyM9O.js`).then(e=>e.t);return{getAgent:e}},__vite__mapDeps([5,1,2,3])).then(({getAgent:e})=>e(v.activeAgentId)).then(e=>{v.activeAgentMcpExcludedServerIds=e?e.mcpExcludedServerIds??null:null,ur()}).catch(()=>{}),v.mcpClosedServers=e[pt]||[];let n=e.ragTools||[],r=e[ft],i=e.enabledTools;if(Array.isArray(r)){let t=fi(n);v.enabledTools=r.filter(e=>t.has(e));let i=Hr(v.enabledTools,n,e.ragToolsIntroduced);v.enabledTools=i.tools,i.migrated?chrome.storage.local.set({ragToolsIntroduced:!0,[ft]:v.enabledTools}):v.enabledTools.length!==r.length&&chrome.storage.local.set({[ft]:v.enabledTools})}else if(i&&i.length>0){let t=fi(n),r=i.filter(e=>t.has(e)),a=f.filter(e=>e.enabled&&!r.includes(e.id)).map(e=>e.id);v.enabledTools=[...r,...a];let o=Hr(v.enabledTools,n,e.ragToolsIntroduced);v.enabledTools=o.tools,chrome.storage.local.set({[ft]:v.enabledTools,...o.migrated?{ragToolsIntroduced:!0}:{}})}else{v.enabledTools=f.filter(e=>e.enabled).map(e=>e.id);let t=Hr(v.enabledTools,n,e.ragToolsIntroduced);v.enabledTools=t.tools,t.migrated&&chrome.storage.local.set({ragToolsIntroduced:!0,[ft]:v.enabledTools})}j&&(j.checked=v.useTools),ur(),Mm(),S()}),lt.addEventListener(`change`,()=>{v.isolateChat=lt.checked,chrome.storage.local.set({isolateChat:v.isolateChat}),r.debug(`[SidePanel] conv memory:`,v.isolateChat?`enabled`:`disabled`)});let ht=document.getElementById(`enableSelectionQueryBtn`);ht&&ht.addEventListener(`change`,()=>{v.enableSelectionQuery=ht.checked,chrome.storage.local.set({enableSelectionQuery:v.enableSelectionQuery}),r.debug(`[SidePanel] text Q&A:`,v.enableSelectionQuery?`enabled`:`disabled`),!v.enableSelectionQuery&&v.selectedContextText&&Un()}),j&&j.addEventListener(`change`,()=>{v.useTools=j.checked,chrome.storage.local.set({enableTools:v.useTools}),r.debug(`[SidePanel] tool master switch:`,v.useTools?`enabled`:`disabled`),ur()}),ut&&ut.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),xr()});let vt=document.getElementById(`toolsPopupOverlay`),St=document.getElementById(`toolsPopupClose`),wt=vt?vt.querySelector(`.modal-container`):null;St&&St.addEventListener(`click`,mr),wt&&wt.addEventListener(`click`,e=>{e.stopPropagation()});let Et=document.getElementById(`toolsSearchInput`),Dt=document.getElementById(`toolsSearchClear`);Et&&Et.addEventListener(`input`,e=>{v.currentSearch=e.target.value.toLowerCase(),Dt&&(Dt.style.display=e.target.value?``:`none`),Ni()}),Dt&&Dt.addEventListener(`click`,()=>{Et&&(Et.value=``,Dt.style.display=`none`,v.currentSearch=``,Ni())});let At=document.querySelectorAll(`.category-btn`);At.forEach(e=>{e.addEventListener(`click`,()=>{At.forEach(e=>{e.classList.remove(`active`),e.classList.contains(`category-all`)?(e.style.background=`var(--brand-violet-soft-bg)`,e.style.color=`var(--brand-500)`,e.style.borderColor=`var(--brand-violet-soft-border)`):(e.style.background=`var(--bg-surface)`,e.style.color=`var(--text-secondary)`,e.style.borderColor=`var(--border-subtle)`)}),e.classList.add(`active`),e.style.background=`linear-gradient(135deg, var(--brand-500) 0%, var(--brand-accent) 100%)`,e.style.color=`var(--text-on-brand)`,e.style.borderColor=`transparent`,v.currentCategory=e.dataset.category,Ni()})});let jt=document.getElementById(`toolsCategories`);jt&&jt.addEventListener(`wheel`,e=>{e.preventDefault(),jt.scrollLeft+=e.deltaY*2},{passive:!1});let Nt=document.getElementById(`toolsSelectAll`),Pt=document.getElementById(`toolsSelectNone`);Nt&&Nt.addEventListener(`click`,()=>{Ei().forEach(e=>{let t=document.getElementById(`tool_`+e.id);t&&(t.checked=!0),v.enabledTools.includes(e.id)||v.enabledTools.push(e.id)}),Mr(!0),gi(),ii(),Fr()}),Pt&&Pt.addEventListener(`click`,()=>{Ei().forEach(e=>{let t=document.getElementById(`tool_`+e.id);t&&(t.checked=!1);let n=v.enabledTools.indexOf(e.id);n>-1&&v.enabledTools.splice(n,1)}),Mr(!1),gi(),ii(),Fr()});let Ft=document.getElementById(`toolsPopupSave`);Ft&&Ft.addEventListener(`click`,()=>{Tr(),Fr()});let Rt=document.getElementById(`toolsPreselectToggle`);Rt&&Rt.addEventListener(`change`,()=>{chrome.storage.local.set({enableToolPreselect:Rt.checked},()=>{r.debug(`[SidePanel] toolpre-filter toggle updated:`,Rt.checked)})});let zt=document.getElementById(`toolConfirmToggle`);zt&&zt.addEventListener(`change`,()=>{chrome.storage.local.set({toolConfirmationEnabled:zt.checked},()=>{r.debug(`[SidePanel] sensitive-operation confirmation toggle updated:`,zt.checked)})});let Bt=document.getElementById(`toolsPopupCancel`);Bt&&Bt.addEventListener(`click`,()=>{mr()});let Vt=document.getElementById(`modalCancelBtn`),Ht=document.getElementById(`modalConfirmBtn`),Ut=document.getElementById(`toolStatsOverlay`),Gt=document.getElementById(`toolStatsClose`),Kt=document.getElementById(`toolStatsBtn`);function Yt(){Ut&&(Ut.style.display=`flex`,rn())}function Xt(){Ut&&(Ut.style.display=`none`)}Kt&&Kt.addEventListener(`click`,e=>{e.stopPropagation(),Yt()}),Gt&&Gt.addEventListener(`click`,Xt),Ut&&Ut.addEventListener(`click`,e=>{e.target===Ut&&Xt()});let Zt=document.getElementById(`toolStatsRefreshBtn`);Zt&&Zt.addEventListener(`click`,rn);let $t=document.getElementById(`toolStatsClearBtn`);$t&&$t.addEventListener(`click`,async()=>{await window.showCustomConfirm(t(`sidePanel.clearStatsConfirm`),t(`sidePanel.clearStatsTitle`))&&(await chrome.storage.local.remove([`toolUsageStats`]),rn())});let en={column:`callCount`,asc:!1};async function rn(){let e=document.getElementById(`toolStatsTable`),n=document.getElementById(`toolStatsTableBody`),i=document.getElementById(`toolStatsLoading`),a=document.getElementById(`toolStatsEmpty`),o=document.getElementById(`toolStatsSummary`),s=document.getElementById(`toolStatsUnusedSection`),c=document.getElementById(`toolStatsUnusedList`);if(!(!e||!n||!i||!a)){e.style.display=`none`,a.style.display=`none`,s&&(s.style.display=`none`),o&&(o.textContent=``),i.style.display=``;try{let n=(await chrome.storage.local.get([`toolUsageStats`])).toolUsageStats||{},r=Object.entries(n);if(r.length===0){i.style.display=`none`,a.style.display=``;return}let l={};f.forEach(e=>{l[e.id]=e.name?`${e.name}${t(`sidePanel.toolNameDescSeparator`)}${e.description||``}`:e.description||e.id}),on(r,l);let u=f.map(e=>e.id),d=new Set(r.map(([e])=>e)),p=u.filter(e=>!d.has(e)),m=r.length,h=p.length;o&&(o.textContent=t(`sidePanel.toolStatsSummary`,{used:m,unused:h})),s&&c&&h>0&&(c.innerHTML=p.sort((e,t)=>e.toLowerCase().localeCompare(t.toLowerCase())).map(e=>`<code title="${k(l[e]||e)}" style="padding: 3px 10px; background: var(--bg-subtle); color: var(--text-disabled); border: 1px solid var(--border-subtle); border-radius: 4px; font-size: 11px;">${e}</code>`).join(``),s.style.display=``),i.style.display=`none`,e.style.display=``}catch(e){r.error(`[SidePanel] loadstats failed:`,e),i.style.display=`none`,a.textContent=t(`sidePanel.toolStatsLoadFailed`),a.style.display=``}}}function on(e,t){let n=document.getElementById(`toolStatsTableBody`);if(!n)return;let{column:r,asc:i}=en;n.innerHTML=[...e].sort((e,t)=>{let[n,a]=e,[o,s]=t,c=a.callCount>0?a.successCount/a.callCount*100:0,l=s.callCount>0?s.successCount/s.callCount*100:0,u=a.callCount>0?a.totalDuration/a.callCount:0,d=s.callCount>0?s.totalDuration/s.callCount:0,f=0;switch(r){case`name`:f=n.toLowerCase().localeCompare(o.toLowerCase());break;case`callCount`:f=a.callCount-s.callCount;break;case`successCount`:f=a.successCount-s.successCount;break;case`successRate`:f=c-l;break;case`duration`:f=u-d;break}return i?f:-f}).map(([e,n])=>{let r=n.callCount>0?n.successCount/n.callCount*100:0,i=n.callCount>0?n.totalDuration/n.callCount:0,a=t[e]||e,o=`#38a169`;r<60?o=`#e53e3e`:r<85&&(o=`#d69e2e`);let s=nt(i);return`<tr>
679
+ </div>`}).join(``)}function it(){Ie&&(Ie.style.display=`flex`,et())}function at(){Ie&&(Ie.style.display=`none`)}Fe&&Fe.addEventListener(`click`,e=>{e.stopPropagation(),ke(),it()}),Le&&Le.addEventListener(`click`,at),Re&&Re.addEventListener(`click`,et),ze&&ze.addEventListener(`change`,et),Be&&Be.addEventListener(`change`,et),Ve&&Ve.addEventListener(`input`,()=>{rt()}),He&&He.addEventListener(`click`,()=>{Ve&&(Ve.value=``),rt()}),ym(()=>v.activeSessionId,window.showCustomConfirm);let lt=document.getElementById(`isolateChatBtn`),j=document.getElementById(`enableToolsBtn`),ut=document.getElementById(`toolsConfigBtn`),ft=`agentEnabledTools_${v.activeAgentId||`default`}`,pt=`agentMcpClosedServers_${v.activeAgentId||`default`}`;chrome.storage.local.get([ft,`enabledTools`,`isolateChat`,`enableSelectionQuery`,`enableTools`,pt,`mcpTools`,`mcpEnabled`,`ragTools`,`ragToolsIntroduced`],e=>{e.isolateChat!==void 0&&(v.isolateChat=e.isolateChat),lt.checked=v.isolateChat,e.enableSelectionQuery!==void 0&&(v.enableSelectionQuery=e.enableSelectionQuery);let t=document.getElementById(`enableSelectionQueryBtn`);t&&(t.checked=v.enableSelectionQuery),e.enableTools!==void 0&&(v.useTools=e.enableTools),v.activeAgentId&&E(async()=>{let{getAgent:e}=await import(`./agent-store-QTeMyM9O.js`).then(e=>e.t);return{getAgent:e}},__vite__mapDeps([5,1,2,3])).then(({getAgent:e})=>e(v.activeAgentId)).then(e=>{v.activeAgentMcpExcludedServerIds=e?e.mcpExcludedServerIds??null:null,zi()}).catch(()=>{}),v.mcpClosedServers=e[pt]||[];let n=e.ragTools||[],r=e[ft],i=e.enabledTools;if(Array.isArray(r)){let t=Di(n);v.enabledTools=r.filter(e=>t.has(e));let i=hr(v.enabledTools,n,e.ragToolsIntroduced);v.enabledTools=i.tools,i.migrated?chrome.storage.local.set({ragToolsIntroduced:!0,[ft]:v.enabledTools}):v.enabledTools.length!==r.length&&chrome.storage.local.set({[ft]:v.enabledTools})}else if(i&&i.length>0){let t=Di(n),r=i.filter(e=>t.has(e)),a=f.filter(e=>e.enabled&&!r.includes(e.id)).map(e=>e.id);v.enabledTools=[...r,...a];let o=hr(v.enabledTools,n,e.ragToolsIntroduced);v.enabledTools=o.tools,chrome.storage.local.set({[ft]:v.enabledTools,...o.migrated?{ragToolsIntroduced:!0}:{}})}else{v.enabledTools=f.filter(e=>e.enabled).map(e=>e.id);let t=hr(v.enabledTools,n,e.ragToolsIntroduced);v.enabledTools=t.tools,t.migrated&&chrome.storage.local.set({ragToolsIntroduced:!0,[ft]:v.enabledTools})}j&&(j.checked=v.useTools),zi(),Nm(),S()}),lt.addEventListener(`change`,()=>{v.isolateChat=lt.checked,chrome.storage.local.set({isolateChat:v.isolateChat}),r.debug(`[SidePanel] conv memory:`,v.isolateChat?`enabled`:`disabled`)});let ht=document.getElementById(`enableSelectionQueryBtn`);ht&&ht.addEventListener(`change`,()=>{v.enableSelectionQuery=ht.checked,chrome.storage.local.set({enableSelectionQuery:v.enableSelectionQuery}),r.debug(`[SidePanel] text Q&A:`,v.enableSelectionQuery?`enabled`:`disabled`),!v.enableSelectionQuery&&v.selectedContextText&&Un()}),j&&j.addEventListener(`change`,()=>{v.useTools=j.checked,chrome.storage.local.set({enableTools:v.useTools}),r.debug(`[SidePanel] tool master switch:`,v.useTools?`enabled`:`disabled`),zi()}),ut&&ut.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),ti()});let yt=document.getElementById(`toolsPopupOverlay`),St=document.getElementById(`toolsPopupClose`),Ct=yt?yt.querySelector(`.modal-container`):null;St&&St.addEventListener(`click`,fi),Ct&&Ct.addEventListener(`click`,e=>{e.stopPropagation()});let wt=document.getElementById(`toolsSearchInput`),Tt=document.getElementById(`toolsSearchClear`);wt&&wt.addEventListener(`input`,e=>{v.currentSearch=e.target.value.toLowerCase(),Tt&&(Tt.style.display=e.target.value?``:`none`),Er()}),Tt&&Tt.addEventListener(`click`,()=>{wt&&(wt.value=``,Tt.style.display=`none`,v.currentSearch=``,Er())});let Et=document.querySelectorAll(`.category-btn`);Et.forEach(e=>{e.addEventListener(`click`,()=>{Et.forEach(e=>{e.classList.remove(`active`),e.classList.contains(`category-all`)?(e.style.background=`var(--brand-violet-soft-bg)`,e.style.color=`var(--brand-500)`,e.style.borderColor=`var(--brand-violet-soft-border)`):(e.style.background=`var(--bg-surface)`,e.style.color=`var(--text-secondary)`,e.style.borderColor=`var(--border-subtle)`)}),e.classList.add(`active`),e.style.background=`linear-gradient(135deg, var(--brand-500) 0%, var(--brand-accent) 100%)`,e.style.color=`var(--text-on-brand)`,e.style.borderColor=`transparent`,v.currentCategory=e.dataset.category,Er()})});let Dt=document.getElementById(`toolsCategories`);Dt&&Dt.addEventListener(`wheel`,e=>{e.preventDefault(),Dt.scrollLeft+=e.deltaY*2},{passive:!1});let At=document.getElementById(`toolsSelectAll`),jt=document.getElementById(`toolsSelectNone`);At&&At.addEventListener(`click`,()=>{Sr().forEach(e=>{let t=document.getElementById(`tool_`+e.id);t&&(t.checked=!0),v.enabledTools.includes(e.id)||v.enabledTools.push(e.id)}),gi(!0),ai(),zr(),dr()}),jt&&jt.addEventListener(`click`,()=>{Sr().forEach(e=>{let t=document.getElementById(`tool_`+e.id);t&&(t.checked=!1);let n=v.enabledTools.indexOf(e.id);n>-1&&v.enabledTools.splice(n,1)}),gi(!1),ai(),zr(),dr()});let Pt=document.getElementById(`toolsPopupSave`);Pt&&Pt.addEventListener(`click`,()=>{Nr(),dr()});let Ft=document.getElementById(`toolsPreselectToggle`);Ft&&Ft.addEventListener(`change`,()=>{chrome.storage.local.set({enableToolPreselect:Ft.checked},()=>{r.debug(`[SidePanel] toolpre-filter toggle updated:`,Ft.checked)})});let Rt=document.getElementById(`toolConfirmToggle`);Rt&&Rt.addEventListener(`change`,()=>{chrome.storage.local.set({toolConfirmationEnabled:Rt.checked},()=>{r.debug(`[SidePanel] sensitive-operation confirmation toggle updated:`,Rt.checked)})});let zt=document.getElementById(`toolsPopupCancel`);zt&&zt.addEventListener(`click`,()=>{fi()});let Bt=document.getElementById(`modalCancelBtn`),Ht=document.getElementById(`modalConfirmBtn`),Ut=document.getElementById(`toolStatsOverlay`),Kt=document.getElementById(`toolStatsClose`),Yt=document.getElementById(`toolStatsBtn`);function Xt(){Ut&&(Ut.style.display=`flex`,nn())}function Zt(){Ut&&(Ut.style.display=`none`)}Yt&&Yt.addEventListener(`click`,e=>{e.stopPropagation(),Xt()}),Kt&&Kt.addEventListener(`click`,Zt),Ut&&Ut.addEventListener(`click`,e=>{e.target===Ut&&Zt()});let Qt=document.getElementById(`toolStatsRefreshBtn`);Qt&&Qt.addEventListener(`click`,nn);let $t=document.getElementById(`toolStatsClearBtn`);$t&&$t.addEventListener(`click`,async()=>{await window.showCustomConfirm(t(`sidePanel.clearStatsConfirm`),t(`sidePanel.clearStatsTitle`))&&(await chrome.storage.local.remove([`toolUsageStats`]),nn())});let en={column:`callCount`,asc:!1};async function nn(){let e=document.getElementById(`toolStatsTable`),n=document.getElementById(`toolStatsTableBody`),i=document.getElementById(`toolStatsLoading`),a=document.getElementById(`toolStatsEmpty`),o=document.getElementById(`toolStatsSummary`),s=document.getElementById(`toolStatsUnusedSection`),c=document.getElementById(`toolStatsUnusedList`);if(!(!e||!n||!i||!a)){e.style.display=`none`,a.style.display=`none`,s&&(s.style.display=`none`),o&&(o.textContent=``),i.style.display=``;try{let n=(await chrome.storage.local.get([`toolUsageStats`])).toolUsageStats||{},r=Object.entries(n);if(r.length===0){i.style.display=`none`,a.style.display=``;return}let l={};f.forEach(e=>{l[e.id]=e.name?`${e.name}${t(`sidePanel.toolNameDescSeparator`)}${e.description||``}`:e.description||e.id}),rn(r,l);let u=f.map(e=>e.id),d=new Set(r.map(([e])=>e)),p=u.filter(e=>!d.has(e)),m=r.length,h=p.length;o&&(o.textContent=t(`sidePanel.toolStatsSummary`,{used:m,unused:h})),s&&c&&h>0&&(c.innerHTML=p.sort((e,t)=>e.toLowerCase().localeCompare(t.toLowerCase())).map(e=>`<code title="${k(l[e]||e)}" style="padding: 3px 10px; background: var(--bg-subtle); color: var(--text-disabled); border: 1px solid var(--border-subtle); border-radius: 4px; font-size: 11px;">${e}</code>`).join(``),s.style.display=``),i.style.display=`none`,e.style.display=``}catch(e){r.error(`[SidePanel] loadstats failed:`,e),i.style.display=`none`,a.textContent=t(`sidePanel.toolStatsLoadFailed`),a.style.display=``}}}function rn(e,t){let n=document.getElementById(`toolStatsTableBody`);if(!n)return;let{column:r,asc:i}=en;n.innerHTML=[...e].sort((e,t)=>{let[n,a]=e,[o,s]=t,c=a.callCount>0?a.successCount/a.callCount*100:0,l=s.callCount>0?s.successCount/s.callCount*100:0,u=a.callCount>0?a.totalDuration/a.callCount:0,d=s.callCount>0?s.totalDuration/s.callCount:0,f=0;switch(r){case`name`:f=n.toLowerCase().localeCompare(o.toLowerCase());break;case`callCount`:f=a.callCount-s.callCount;break;case`successCount`:f=a.successCount-s.successCount;break;case`successRate`:f=c-l;break;case`duration`:f=u-d;break}return i?f:-f}).map(([e,n])=>{let r=n.callCount>0?n.successCount/n.callCount*100:0,i=n.callCount>0?n.totalDuration/n.callCount:0,a=t[e]||e,o=`#38a169`;r<60?o=`#e53e3e`:r<85&&(o=`#d69e2e`);let s=nt(i);return`<tr>
680
680
  <td style="padding: 6px 10px; border-bottom: 1px solid var(--border-subtle); color: var(--text-primary);"><code title="${k(a)}">${e}</code></td>
681
681
  <td style="padding: 6px 10px; text-align: right; border-bottom: 1px solid var(--border-subtle); color: var(--text-secondary);">${n.callCount}</td>
682
682
  <td style="padding: 6px 10px; text-align: right; border-bottom: 1px solid var(--border-subtle); color: var(--text-secondary);">${n.successCount}</td>
@@ -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),rn()})}),Vt.addEventListener(`click`,()=>{vi()}),Ht.addEventListener(`click`,()=>{vi(),qt()});let un=document.getElementById(`confirmModal`);un.addEventListener(`click`,e=>{e.target===un&&vi()});let mn=document.getElementById(`selectionClose`);mn&&mn.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),r.debug(`[SidePanel] user clickcloseselected content by button`),Un(),window.hideFloatingMenu(),v.lastSelectedText=``,v.currentSelectionRange=null}),a.addEventListener(`input`,()=>{})}),Je().then(()=>{bm(),li(v.chatConfig.showMessageTimestamp!==!1),xm(),Sm()}),document.addEventListener(`DOMContentLoaded`,()=>{wm()}),document.addEventListener(`DOMContentLoaded`,un),document.addEventListener(`DOMContentLoaded`,oi),document.addEventListener(`DOMContentLoaded`,Pm),document.addEventListener(`DOMContentLoaded`,Nm),document.addEventListener(`DOMContentLoaded`,Fd),document.addEventListener(`DOMContentLoaded`,Af),document.addEventListener(`DOMContentLoaded`,tp),document.addEventListener(`DOMContentLoaded`,Nt),document.addEventListener(`DOMContentLoaded`,async()=>{$i(),Va(),await lr(),Pr(),await $s(),Fl(),ds(),gm(),Ps(),uh(),Si(),md();let{updateBookmarkButtons:e,updateBookmarkBadge:t}=await E(async()=>{let{updateBookmarkButtons:e,updateBookmarkBadge:t}=await import(`./context-indicator-DSJveMWs.js`).then(e=>e.hn);return{updateBookmarkButtons:e,updateBookmarkBadge:t}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]));e(),t()}),document.addEventListener(`DOMContentLoaded`,()=>{as()}),document.addEventListener(`DOMContentLoaded`,async()=>{xn(e=>Ai(e)),await _n(),await Mp()});function gh(){Un(),yr(),Ti(),ea(),yn(),Ji();let e=document.getElementById(`imagePreviewBar`);e&&(e.innerHTML=``,e.style.display=`none`)}function _h(e){let t=e||{};t.quotedContextText&&wi(t.quotedContextText),t.selectedPage&&en(t.selectedPage),!t.quotedContextText&&v.selectedContextText&&$n(),cr(),Nr(),ir(),wr(),_r()}document.addEventListener(`queue-context-cleared`,gh),document.addEventListener(`queue-context-restored`,e=>{_h(e&&e.detail?e.detail.snapshot:null)}),document.addEventListener(`DOMContentLoaded`,bn),document.addEventListener(`DOMContentLoaded`,Ar),document.addEventListener(`DOMContentLoaded`,mi),document.addEventListener(`DOMContentLoaded`,Cr),document.addEventListener(`DOMContentLoaded`,Ut),document.addEventListener(`DOMContentLoaded`,Ci),document.addEventListener(`DOMContentLoaded`,ci),document.addEventListener(`DOMContentLoaded`,er),document.addEventListener(`DOMContentLoaded`,Bi),document.addEventListener(`DOMContentLoaded`,()=>fr()),document.addEventListener(`DOMContentLoaded`,async()=>{let{refreshAgentNames:e,initScrollToBottomBtn:t}=await E(async()=>{let{refreshAgentNames:e,initScrollToBottomBtn:t}=await import(`./context-indicator-DSJveMWs.js`).then(e=>e.ft);return{refreshAgentNames:e,initScrollToBottomBtn:t}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]));e(),t()});async function vh(){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 vh();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(``),on()}function on(){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),nn()})}),Bt.addEventListener(`click`,()=>{vi()}),Ht.addEventListener(`click`,()=>{vi(),qt()});let sn=document.getElementById(`confirmModal`);sn.addEventListener(`click`,e=>{e.target===sn&&vi()});let un=document.getElementById(`selectionClose`);un&&un.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),r.debug(`[SidePanel] user clickcloseselected content by button`),Un(),window.hideFloatingMenu(),v.lastSelectedText=``,v.currentSelectionRange=null}),a.addEventListener(`input`,()=>{})}),Je().then(()=>{xm(),li(v.chatConfig.showMessageTimestamp!==!1),Sm(),Cm()}),document.addEventListener(`DOMContentLoaded`,()=>{Tm()}),document.addEventListener(`DOMContentLoaded`,Nn),document.addEventListener(`DOMContentLoaded`,si),document.addEventListener(`DOMContentLoaded`,Fm),document.addEventListener(`DOMContentLoaded`,Pm),document.addEventListener(`DOMContentLoaded`,Ld),document.addEventListener(`DOMContentLoaded`,jf),document.addEventListener(`DOMContentLoaded`,np),document.addEventListener(`DOMContentLoaded`,xn),document.addEventListener(`DOMContentLoaded`,async()=>{Et(),Ha(),await Ri(),ur(),await ec(),Ll(),fs(),_m(),Fs(),dh(),Hr(),gd();let{updateBookmarkButtons:e,updateBookmarkBadge:t}=await E(async()=>{let{updateBookmarkButtons:e,updateBookmarkBadge:t}=await import(`./context-indicator-CWyjBBv3.js`).then(e=>e.gn);return{updateBookmarkButtons:e,updateBookmarkBadge:t}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]));e(),t()}),document.addEventListener(`DOMContentLoaded`,()=>{os()}),document.addEventListener(`DOMContentLoaded`,async()=>{Xr(e=>Mi(e)),await Tn(),await Np()});function _h(){Un(),xr(),Ti(),Dt(),Dn(),vr();let e=document.getElementById(`imagePreviewBar`);e&&(e.innerHTML=``,e.style.display=`none`)}function vh(e){let t=e||{};t.quotedContextText&&wi(t.quotedContextText),t.selectedPage&&dn(t.selectedPage),!t.quotedContextText&&v.selectedContextText&&er(),lr(),Pr(),nr(),Mr(),Ki()}document.addEventListener(`queue-context-cleared`,_h),document.addEventListener(`queue-context-restored`,e=>{vh(e&&e.detail?e.detail.snapshot:null)}),document.addEventListener(`DOMContentLoaded`,bn),document.addEventListener(`DOMContentLoaded`,jr),document.addEventListener(`DOMContentLoaded`,mi),document.addEventListener(`DOMContentLoaded`,wr),document.addEventListener(`DOMContentLoaded`,en),document.addEventListener(`DOMContentLoaded`,Ur),document.addEventListener(`DOMContentLoaded`,Ci),document.addEventListener(`DOMContentLoaded`,sr),document.addEventListener(`DOMContentLoaded`,Bn),document.addEventListener(`DOMContentLoaded`,()=>pr()),document.addEventListener(`DOMContentLoaded`,async()=>{let{refreshAgentNames:e,initScrollToBottomBtn:t}=await E(async()=>{let{refreshAgentNames:e,initScrollToBottomBtn:t}=await import(`./context-indicator-CWyjBBv3.js`).then(e=>e.ft);return{refreshAgentNames:e,initScrollToBottomBtn:t}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]));e(),t()});async function yh(){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 yh();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`)}})});