ai-helper-agent 2.8.21 → 2.8.23

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,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/context-indicator-Btg9ZLat.js","assets/chunk-CMxvf4Kt.js","assets/model-profiles-ClPgbQ-J.js","assets/i18n-5c8prpFJ.js","assets/voice-shortcut-Dx863RGz.js","assets/session-store-M5mPmMr3.js","assets/version-DOUsnjKq.js","assets/agent-store-CeC2_dkP.js","assets/workspace-manager-CL4JvHkJ.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-5c8prpFJ.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-ClPgbQ-J.js";import{_ as fe,d as pe}from"./session-store-M5mPmMr3.js";import{A as me,C as he,D as ge,E as _e,M as ve,N as ye,O as be,S as xe,T as Se,_ as Ce,a as we,b as Te,c as Ee,d as De,f as Oe,g as ke,h as Ae,i as je,j as Me,k as Ne,l as Pe,m as Fe,n as D,o as Ie,p as Le,r as Re,s as ze,t as Be,u as Ve,v as He,w as Ue,x as We,y as Ge}from"./todo-model--JIghLks.js";import{$ as Ke,A as O,B as qe,D as Je,E as Ye,G as Xe,J as k,K as Ze,L as Qe,M as $e,N as et,O as tt,Q as nt,U as rt,V as it,W as at,X as ot,Z as st,_ as ct,et as lt,g as ut,j as A,k as dt,l as ft,q as pt,t as mt,v as ht,w as gt,y as _t}from"./version-DOUsnjKq.js";import{$ as vt,$n as yt,$r as bt,$t as xt,A as St,An as Ct,Ar as wt,At as Tt,B as Et,Bn as Dt,Br as Ot,Bt as kt,C as At,Cn as jt,Cr as Mt,Ct as Nt,D as Pt,Dn as Ft,Dr as It,Dt as Lt,E as Rt,En as zt,Er as Bt,Et as Vt,F as Ht,Fn as Ut,Fr as Wt,Ft as Gt,G as Kt,Gn as qt,Gr as Jt,Gt as Yt,H as Xt,Hn as Zt,Hr as Qt,Ht as $t,I as en,In as tn,Ir as nn,It as rn,J as an,Jn as on,Jr as sn,Jt as cn,K as ln,Kn as un,Kr as dn,Kt as fn,L as pn,Ln as mn,Lr as hn,Lt as gn,M as _n,Mn as vn,Mr as yn,Mt as bn,N as xn,Nn as Sn,Nr as Cn,Nt as wn,O as Tn,On as En,Or as Dn,Ot as On,P as kn,Pn as An,Pr as jn,Pt as Mn,Q as Nn,Qn as Pn,Qr as Fn,Qt as In,R as Ln,Rn,Rr as zn,Rt as Bn,S as Vn,Sr as Hn,St as Un,T as Wn,Tn as Gn,Tr as Kn,Tt as qn,Un as Jn,Ur as Yn,Ut as Xn,V as Zn,Vn as Qn,Vr as $n,Vt as er,W as tr,Wn as nr,Wr as rr,Wt as ir,X as ar,Xn as or,Xr as sr,Xt as cr,Y as lr,Yn as ur,Yr as dr,Yt as fr,Z as pr,Zn as mr,Zr as hr,Zt as gr,_ as _r,_n as vr,_r as yr,_t as br,a as xr,an as Sr,ar as Cr,at as wr,b as Tr,bn as Er,br as Dr,bt as Or,c as kr,cn as Ar,ct as jr,d as Mr,dn as Nr,dr as Pr,dt as Fr,ei as Ir,en as Lr,er as Rr,et as zr,f as Br,fn as Vr,fr as Hr,ft as Ur,g as Wr,gn as Gr,gr as Kr,gt as qr,h as Jr,hn as Yr,hr as Xr,i as Zr,in as Qr,ir as $r,it as ei,j as ti,jn as ni,jr as ri,jt as ii,k as ai,kn as oi,kt as si,l as ci,ln as li,lr as ui,lt as di,m as fi,mr as pi,mt as mi,n as hi,nn as gi,nr as _i,nt as vi,o as yi,on as bi,or as xi,ot as Si,p as Ci,pn as wi,pr as Ti,pt as Ei,q as Di,qn as Oi,qr as ki,qt as Ai,r as ji,rn as Mi,rr as Ni,rt as Pi,s as Fi,sn as Ii,sr as Li,st as Ri,t as zi,ti as Bi,tn as Vi,tr as Hi,tt as Ui,u as Wi,un as Gi,ur as Ki,ut as qi,v as Ji,vn as Yi,vr as Xi,vt as Zi,w as Qi,wn as $i,wr as ea,wt as ta,x as na,xn as ra,xr as ia,xt as aa,y as oa,yn as sa,yr as ca,yt as la,z as ua,zn as da,zr as fa,zt as pa}from"./context-indicator-Btg9ZLat.js";import{o as ma}from"./agent-store-CeC2_dkP.js";import{O as ha,b as ga,l as _a,p as va,v as ya}from"./workspace-manager-CL4JvHkJ.js";var ba=`panel-observer-`,xa=new Map,Sa=new Set;function Ca(e){typeof e==`function`&&Sa.add(e)}function wa(e){if(!e)return null;let t=xa.get(e);if(t)return t;let n;try{n=chrome.runtime.connect({name:`${ba}${e}`})}catch(e){return r.debug(`[PanelObserver] 建立观察端口失败(忽略):`,e?.message||e),null}xa.set(e,n);try{n.onMessage.addListener(e=>{for(let t of Sa)try{t(e)}catch(e){r.debug(`[PanelObserver] 消息处理异常(忽略):`,e?.message||e)}})}catch(e){r.debug(`[PanelObserver] 观察端口消息监听挂不上(忽略):`,e?.message||e)}try{n.onDisconnect.addListener(()=>{xa.get(e)===n&&xa.delete(e)})}catch(e){r.debug(`[PanelObserver] 观察端口断开监听挂不上(忽略):`,e?.message||e)}return n}function Ta(e){if(!e)return;let t=xa.get(e);if(t){xa.delete(e);try{t.disconnect()}catch(e){r.debug(`[PanelObserver] 关闭观察端口异常(忽略):`,e?.message||e)}}}function Ea({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 Da({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 Oa=!1,ka=new Map,Aa=null,ja=!1,Ma=null,Na=null,Pa=null,Fa=250,Ia=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 La(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 Ra(e,t){let n=new Map;return{start(){On(e,``),Lt(``),si(Date.now()),di(t),qn(t)},chunk(n){On(e,n),Tt(t,n)},restore({html:e}){Ur(t,e)},toolCalls(e,n){typeof n==`string`&&n&&ta(t,n),qi(t,e)},toolResult(e){Fr(e,t)},agentStream(e){Nt(t,n),Ei(n,t,e)},agentStreamDone(e){let t=n.get(e.execId);t&&t.element&&e.exitCode!==0&&t.element.classList.add(`agent-stream-error`)},retrying(e,n){Or(t,e,n)},preselect(e){let n=t.querySelector(`.message-content`);!n||!e.length||e.forEach(e=>n.insertBefore(qr(e),n.firstChild))},final(e,n,r={}){la(t,e,n,r.reflectionScore,r.reasoningContent,r.wasRevised)},error(e,n){la(t,e,n||[])}}}async function za(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-Btg9ZLat.js`).then(e=>e.kr);return{appendMessageToSession:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]));await a(t,i)}function Ba(){E(()=>import(`./context-indicator-Btg9ZLat.js`).then(e=>e.U).then(e=>e.syncPendingSessionsToStorage()),__vite__mapDeps([0,1,2,3,4,5,6,7,8])).catch(e=>r.debug(`[ChatReattach] 同步生成态失败(忽略):`,e?.message||e))}var Va=1e3;function Ha(e){return Promise.race([ii(e),new Promise(e=>setTimeout(()=>e(null),Va))])}function Ua(e,n){let i=br(e);if(i())return!1;let a=jr(e);a.dataset.callId=n,i(a),On(e,``),si(Date.now()),Vt(Date.now()),v.pendingCallApiSessionIds.add(e),v.generatingSessionIds.add(e),Ba();try{document.dispatchEvent(new CustomEvent(`generating-state-changed`))}catch{}let o=Ea({sessionId:e,callId:n,awaitSnapshot:!0,renderer:Ra(e,a),persist:t=>za(t,e,a),emptyFallback:t(`chatMsg.emptyModelReply`),onFinished:()=>{if(ka.get(e)===o){ka.delete(e),Ta(e),v.pendingCallApiSessionIds.delete(e),Ba(),Zi(e);try{document.dispatchEvent(new CustomEvent(`session-cache-invalidate`,{detail:{sessionId:e}}))}catch{}Pn(e)}}});return ka.set(e,o),wa(e),Ha(e).then(t=>{o.finished||ka.get(e)!==o||o.restore(t)}).catch(()=>o.restore(null)),v.activeSessionId===e&&aa(e),r.info(`[ChatReattach] 已接管运行中的任务: sessionId=${e}, callId=${n}`),!0}function Wa(e){let t=ka.get(e);if(!t)return;ka.delete(e),Ta(e);try{t.dispose?.()}catch{}let n=br(e),r=n();try{r?.remove()}catch{}n(null),Zi(e),v.pendingCallApiSessionIds.delete(e),Ba();try{document.dispatchEvent(new CustomEvent(`generating-state-changed`))}catch{}}function Ga(){let e=Aa;e&&Promise.resolve().then(()=>e.syncFromBackground()).catch(e=>r.debug(`[ChatReattach] 对齐后台状态失败(忽略):`,e?.message||e))}function Ka(){!Oa||!Aa||Pa||(Pa=setTimeout(()=>{Pa=null,Ga()},Fa))}var qa=new Map,Ja=3e3,Ya=100,Xa=new Set,Za=new Set([`API_COMPLETE`,`API_ERROR`]);function Qa(e,t){let n=`${e}|${t.callId}`;Xa.has(n)||(Xa.add(n),Xa.size>Ya&&Xa.delete(Xa.values().next().value),Wa(e),Ua(e,t.callId)&&ka.get(e)?.handleMessage(t))}function $a(e,t,n){let r=qa.get(e);if(r){r.messages.push(n);return}r={callId:t,messages:[n]},qa.set(e,r),La(Ja).then(t=>eo(e,t&&t.activeCallIds&&t.activeCallIds[e]||null)).catch(()=>eo(e,null)).finally(()=>{qa.delete(e)})}function eo(e,t){let n=qa.get(e);if(!n)return;let{callId:r,messages:i}=n;if(t===r)Wa(e),Ua(e,r);else if(t===null){let t=i.find(e=>Za.has(e.type));if(!t)return;Qa(e,t);return}else return;let a=ka.get(e);if(!(!a||a.callId!==r))for(let e of i){if(a.finished)break;a.handleMessage(e)}}function to(){if(ja)return;ja=!0;let e=e=>{if(!e)return!1;let t=e.sessionId?ka.get(e.sessionId):null;return t?e.callId&&e.callId!==t.callId?($a(e.sessionId,e.callId,e),!1):(wa(e.sessionId),t.handleMessage(e),!1):(e.callId&&Ia.has(e.type)&&Ka(),!1)};chrome.runtime.onMessage.addListener(e),Ca(e),Ma=e=>{let t=e?.detail?.sessionId;t&&ka.has(t)&&aa(t),Ka()},document.addEventListener(`session-hydrated`,Ma),Na=e=>{let t=e?.detail?.sessionId;t&&ka.has(t)&&aa(t)},document.addEventListener(`chat-history-rendered`,Na)}function no(){return Oa?{syncFromBackground:()=>Aa.syncFromBackground()}:(Oa=!0,to(),Aa=Da({queryRunning:La,hasLocalListener:e=>v.pendingCancelApiMap.has(e),isAttached:(e,t)=>ka.get(e)?.callId===t?(wa(e),!0):!1,attach:(e,t)=>{Ua(e,t)}}),Aa.syncFromBackground(),{syncFromBackground:()=>Aa.syncFromBackground()})}function ro(e){!Oa||!Aa||(e&&v.activeSessionId===e&&aa(e),Aa.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 io=`sessionDockDismissed`,ao=5e3,oo=250,so=1200,co=8,lo=co-1,uo=9e4,fo={running:0,queued:1,done:2},po=new Map,mo=new Map,ho=new Map,go=new Map,_o=new Set,vo=new Set,yo=new Map,bo=new Map,xo=new Set,So=new Set,Co=[],wo=new Set,j=null,M=null,N=null,To=[],Eo=!1,Do=null,Oo=null,ko=!1,Ao=null,jo=null;function Mo(e){return e?Array.isArray(e)?e:e instanceof Set?Array.from(e):[]:[]}function No(e){let t=new Set;for(let n of Mo(e))n&&t.add(h(String(n))||String(n));return t}function Po({phase:e=``,sessionId:t=null,backendRunningIds:n=[],startedAt:r=0,lastUpdateAt:i=0,now:a=Date.now(),staleMs:o=uo}={}){if(e!==`running`||!t||Mo(n).includes(t))return!1;let s=Math.max(Number(r)||0,Number(i)||0);return s?a-s>=o:!1}var Fo=160;function Io(e){let t=String(e??``).replace(/\s+/g,` `).trim();if(!t)return``;let n=Array.from(t);return n.length<=Fo?t:`${n.slice(0,Fo).join(``).trimEnd()}…`}function Lo(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 Ro({phase:e=``,queuedText:t=``,questionText:n=``,title:r=``}={}){let i=e===`queued`?Io(t):``,a=i||Io(n),o=Io(r),s=a||o,c=i?`queued`:a?`question`:s?`title`:``;return{primary:s,sub:a&&!Lo(o,a)?o:``,isQuestion:!!a,from:c}}function zo(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 Bo({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=uo}={}){let te=Mo(s),ne=new Set([...Mo(a),...Mo(o),...te]),_=new Set(Mo(c)),v=new Set(Mo(d)),re=new Set(Mo(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=Po({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=Ro({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=fo[e.phase]-fo[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 Vo(e){return So.has(e)||v.generatingSessionIds.has(e)||v.pendingCallApiSessionIds.has(e)}function Ho(){let e={};try{let t=zn();for(let n of t){let t=Wt(n);t>0&&(e[n]=t)}}catch(e){r.debug(`[SessionDock] read queue counts failed:`,e?.message||e)}return e}function Uo(){let e={};for(let t of v.sessions||[])e[t.id]=t.title||``;for(let[t,n]of yo)e[t]||(e[t]=n);return e}function Wo(){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=mo.get(r)||ho.get(r)||0,a=bo.get(r);if(i&&a&&a.stamp===i){a.text&&(e[r]=a.text,t[r]=a.messageId||``);continue}let o=zo(n.get(r));o.text&&(e[r]=o.text,t[r]=o.messageId)}return{questions:e,anchors:t}}function Go(){let e={};try{for(let t of zn()){let n=fa(t);n?.text&&(e[t]=String(n.text))}}catch(e){r.debug(`[SessionDock] read queued texts failed:`,e?.message||e)}return e}function Ko(e){for(let t of e||[]){let e=t.sessionId;if(!e)continue;let n=t.startedAt||t.doneAt||0,i=bo.get(e),a=!i||i.stamp!==n,o=!t.title;!a&&!o||xo.has(e)||(xo.add(e),y(e).then(t=>{if(t&&((o||!yo.has(e))&&yo.set(e,t.title||``),a)){let r=zo(t);bo.set(e,{text:r.text,messageId:r.messageId,stamp:n})}}).catch(e=>{r.debug(`[SessionDock] hydrate label failed:`,e?.message||e)}).finally(()=>{xo.delete(e),P()}))}}function qo(e){if(!e)return``;let t=new Date(e);return`${String(t.getHours()).padStart(2,`0`)}:${String(t.getMinutes()).padStart(2,`0`)}`}function Jo(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:qo(e.doneAt)}):t(`dock.done`)}function Yo(){let e=v.completedSessionIds;for(let e of new Set([...So,...v.generatingSessionIds,...v.pendingCallApiSessionIds]))mo.has(e)||mo.set(e,Date.now()),ho.delete(e);for(let e of So)vo.delete(e);for(let t of e)!ho.has(t)&&!Vo(t)&&ho.set(t,Date.now());let{questions:t,anchors:n}=Wo(),r=Bo({activeSessionId:v.activeSessionId,titles:Uo(),questions:t,anchors:n,queuedTexts:Go(),generatingIds:v.generatingSessionIds,pendingIds:v.pendingCallApiSessionIds,runningIds:So,completedIds:e,queuedCounts:Ho(),scheduledIds:_o,dismissedIds:vo,nodeInfo:Object.fromEntries(po),startedAt:Object.fromEntries(mo),doneAt:Object.fromEntries(ho),lastUpdateAt:Object.fromEntries(go),now:Date.now()});return Ko(r),r}function Xo(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&&(wo=new Set(n),Ao&&clearTimeout(Ao),Ao=setTimeout(()=>{Ao=null,wo=new Set,P()},so))}function Zo(){if(j||typeof document>`u`)return j;j=document.createElement(`div`),j.className=`session-dock`,j.id=`sessionDock`,j.setAttribute(`role`,`navigation`),document.body.appendChild(j),M=document.createElement(`div`),M.className=`session-dock-tip`,document.body.appendChild(M),Qo();let e=document.getElementById(`chatContainer`);return e&&typeof ResizeObserver<`u`&&new ResizeObserver(Qo).observe(e),window.addEventListener(`resize`,Qo),j}function Qo(){if(!j)return;let e=document.getElementById(`chatContainer`);if(!e)return;let t=e.getBoundingClientRect();j.style.top=`${Math.max(0,Math.round(t.top+8))}px`}function $o(e){xi(e.sessionId,{focusMessageId:e.anchorMessageId||null})}function es(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`),wo.has(e.sessionId)&&n.classList.add(`is-flash`);let r=e.title||t(`dock.unknownSession`),i=e.primary||r,a=Jo(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`,()=>{$o(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(),ps(e.sessionId)}),n.appendChild(r)}return n.addEventListener(`mouseenter`,()=>ts(n,e,a)),n.addEventListener(`mouseleave`,ns),n.addEventListener(`focusin`,()=>ts(n,e,a)),n.addEventListener(`focusout`,ns),n}function ts(e,n,r){if(!M)return;M.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,M.appendChild(i),n.sub){let e=document.createElement(`div`);e.className=`session-dock-tip-sub`,e.textContent=n.sub,M.appendChild(e)}M.appendChild(a);let o=e.getBoundingClientRect();M.style.top=`${Math.round(o.top)}px`,M.style.left=`${Math.round(o.right+8)}px`,M.classList.add(`show`)}function ns(){M&&M.classList.remove(`show`)}function rs(){return N||typeof document>`u`?N:(N=document.createElement(`div`),N.className=`session-dock-overflow`,N.setAttribute(`role`,`menu`),N.addEventListener(`mouseenter`,is),N.addEventListener(`mouseleave`,as),N.addEventListener(`focusin`,is),N.addEventListener(`focusout`,as),document.body.appendChild(N),N)}function is(){jo&&=(clearTimeout(jo),null)}function as(){Eo||(is(),jo=setTimeout(()=>{jo=null,us()},220))}function os(){let e=j?j.querySelector(`.session-dock-more`):null;e&&(e.setAttribute(`aria-expanded`,Eo?`true`:`false`),e.classList.toggle(`is-open`,Eo))}function ss(){let e=rs();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 To){let n=e.primary||e.title||t(`dock.unknownSession`),i=Jo(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`,()=>{us(),$o(e)}),r.appendChild(a)}e.appendChild(r)}function cs(){if(!N||!j)return;let e=j.querySelector(`.session-dock-item--more`);if(!e)return;let t=e.getBoundingClientRect();N.style.left=`${Math.round(t.right+8)}px`;let n=N.offsetHeight||0,r=Math.max(8,window.innerHeight-n-8);N.style.top=`${Math.round(Math.min(Math.max(8,t.top),r))}px`}function ls(){To.length!==0&&rs()&&(is(),ss(),cs(),N.classList.add(`show`),os())}function us(){is(),Eo=!1,N&&N.classList.remove(`show`),os()}function ds(){if(N&&N.classList.contains(`show`)&&Eo){us();return}ls(),Eo=!0,os()}function fs(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`,Eo?`true`:`false`),r.textContent=`+${e.length>99?`99`:e.length}`,r.addEventListener(`click`,()=>ds()),n.appendChild(r),n.addEventListener(`mouseenter`,()=>ls()),n.addEventListener(`mouseleave`,as),n.addEventListener(`focusin`,()=>ls()),n.addEventListener(`focusout`,as),n}function ps(e){e&&(vo.add(e),ms(),P())}function ms(){try{chrome.storage.local.set({[io]:Array.from(vo)}).catch(()=>{})}catch{}}function hs(){try{chrome.storage.local.get([io],e=>{let t=e?.[io];if(Array.isArray(t)){for(let e of t)vo.add(e);P()}})}catch{}}function gs(){if(!Zo())return;let e=Yo();if(Xo(e),Co=e,us(),To=[],j.innerHTML=``,e.length===0){j.classList.remove(`show`),document.body.classList.remove(`has-session-dock`),ns();return}let t=e.length>co?lo:co;To=e.slice(t);for(let n of e.slice(0,t))j.appendChild(es(n));To.length>0&&j.appendChild(fs(To)),j.classList.add(`show`),document.body.classList.add(`has-session-dock`)}function P(){Do||=setTimeout(()=>{Do=null;try{gs()}catch(e){r.warn(`[SessionDock] render failed:`,e?.message||e)}},oo)}function _s(){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=No(t.activeSessionIds)),e()})}catch{e()}})}function vs(e){let t=e?.sessionId;if(!t)return;let n=po.get(t)||{};po.set(t,{nodeName:e.nodeName||n.nodeName||``,subtaskIndex:e.subtaskIndex||n.subtaskIndex||0,subtaskTotal:e.subtaskTotal||n.subtaskTotal||0}),go.set(t,Date.now()),P()}function ys(e){e&&(po.delete(e),mo.delete(e),ho.delete(e),go.delete(e),vo.delete(e),yo.delete(e),bo.delete(e),P())}function bs(){if(!(ko||typeof document>`u`||!Zo())){ko=!0,hs(),document.addEventListener(`generating-state-changed`,P),document.addEventListener(`session-switched`,P),document.addEventListener(`generation-ended`,e=>{let t=e?.detail?.sessionId;t&&!ho.has(t)&&ho.set(t,Date.now()),P()}),document.addEventListener(`session-archived`,e=>ys(e?.detail?.sessionId)),document.addEventListener(`session-deleted`,e=>ys(e?.detail?.sessionId));try{Jt(P)}catch(e){r.debug(`[SessionDock] subscribe queue failed:`,e?.message||e)}try{chrome.runtime.onMessage.addListener(e=>e?e.type===`EXECUTION_STATUS_UPDATE`?(vs(e),!1):e.type===`SCHEDULED_TASK_RUN_STATE`&&e.sessionId?(e.running?_o.add(e.sessionId):_o.delete(e.sessionId),P(),!1):(e.type===`SCHEDULED_SESSION_UPDATED`&&P(),!1):!1)}catch(e){r.debug(`[SessionDock] register runtime listener failed:`,e?.message||e)}document.addEventListener(`visibilitychange`,()=>{if(document.hidden){us();return}_s().then(P)}),document.addEventListener(`keydown`,e=>{e.key===`Escape`&&Eo&&us()}),Oo||=setInterval(()=>{document.hidden||_s().then(P)},ao),_s().then(()=>{for(let e of So)mo.has(e)||mo.set(e,Date.now());gs()})}}function xs(){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=Ye(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=pt(r.length,$e(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=Ye(document.getElementById(`chatContainer`));let e=l?Ye(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=Ye(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=Ze(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,ws=!1,F=[],Ts=``;function Es(){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-DjOAo_Ln.js","assets/chunk-CMxvf4Kt.js","assets/model-profiles-ClPgbQ-J.js","assets/i18n-5c8prpFJ.js","assets/voice-shortcut-Dx863RGz.js","assets/session-store-M5mPmMr3.js","assets/version-DigCzqtw.js","assets/agent-store-CeC2_dkP.js","assets/workspace-manager-CL4JvHkJ.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-5c8prpFJ.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 _,P as ee,R as v,U as te,b as y,c as b,ct as ne,d as x,gt as S,ht as C,i as w,it as T,jt as re,k as ie,q as E,r as ae,rt as oe,u as se,wt as ce,x as D,y as le,zt as ue}from"./model-profiles-ClPgbQ-J.js";import{_ as de,d as fe}from"./session-store-M5mPmMr3.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--JIghLks.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,b as ct,et 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-DigCzqtw.js";import{$ as _t,$n as vt,$r as yt,$t as bt,A as xt,An as St,Ar as Ct,At as wt,B as Tt,Bn as Et,Br as Dt,Bt as Ot,C as kt,Cn as At,Cr as jt,Ct as Mt,D as Nt,Dn as Pt,Dr as Ft,Dt as It,E as Lt,En as Rt,Er as zt,Et as Bt,F as Vt,Fn as Ht,Fr as Ut,Ft as Wt,G as Gt,Gn as Kt,Gr as qt,Gt as Jt,H as Yt,Hn as Xt,Hr as Zt,Ht as Qt,I as $t,In as en,Ir as tn,It as nn,J as rn,Jn as an,Jr as on,Jt as sn,K as cn,Kn as ln,Kr as un,Kt as dn,L as fn,Ln as pn,Lr as mn,Lt as hn,M as gn,Mn as _n,Mr as vn,Mt as yn,N as bn,Nn as xn,Nr as Sn,Nt as Cn,O as wn,On as Tn,Or as En,Ot as Dn,P as On,Pn as kn,Pr as An,Pt as jn,Q as Mn,Qn as Nn,Qr as Pn,Qt as Fn,R as In,Rn as Ln,Rr as Rn,Rt as zn,S as Bn,Sr as Vn,St as Hn,T as Un,Tn as Wn,Tr as Gn,Tt as Kn,Un as qn,Ur as Jn,Ut as Yn,V as Xn,Vn as Zn,Vr as Qn,Vt as $n,W as er,Wn as tr,Wr as nr,Wt as rr,X as ir,Xn as ar,Xr as or,Xt as sr,Y as cr,Yn as lr,Yr as ur,Yt as dr,Z as fr,Zn as pr,Zr as mr,Zt as hr,_ as gr,_n as _r,_r as vr,_t as yr,a as br,an as xr,ar as Sr,at as Cr,b as wr,bn as Tr,br as Er,bt as Dr,c as Or,cn as kr,ct as Ar,d as jr,dn as Mr,dr as Nr,dt as Pr,ei as Fr,en as Ir,er as Lr,et as Rr,f as zr,fn as Br,fr as Vr,ft as Hr,g as Ur,gn as Wr,gr as Gr,gt as Kr,h as qr,hn as Jr,hr as Yr,i as Xr,in as Zr,ir as Qr,it as $r,j as ei,jn as ti,jr as ni,jt as ri,k as ii,kn as ai,kt as oi,l as si,ln as ci,lr as li,lt as ui,m as di,mr as fi,mt as pi,n as mi,nn as hi,nr as gi,nt as _i,o as vi,on as yi,or as bi,ot as xi,p as Si,pn as Ci,pr as wi,pt as Ti,q as Ei,qn as Di,qr as Oi,qt as ki,r as Ai,rn as ji,rr as Mi,rt as Ni,s as Pi,sn as Fi,sr as Ii,st as Li,t as Ri,ti as zi,tn as Bi,tr as Vi,tt as Hi,u as Ui,un as Wi,ur as Gi,ut as Ki,v as qi,vn as Ji,vr as Yi,vt as Xi,w as Zi,wn as Qi,wr as $i,wt as ea,x as ta,xn as na,xr as ra,xt as ia,y as aa,yn as oa,yr as sa,yt as ca,z as la,zn as ua,zr as da,zt as fa}from"./context-indicator-DjOAo_Ln.js";import{o as pa}from"./agent-store-CeC2_dkP.js";import{O as ma,b as ha,l as ga,p as _a,v as va}from"./workspace-manager-CL4JvHkJ.js";var ya=`panel-observer-`,ba=new Map,xa=new Set;function Sa(e){typeof e==`function`&&xa.add(e)}function Ca(e){if(!e)return null;let t=ba.get(e);if(t)return t;let n;try{n=chrome.runtime.connect({name:`${ya}${e}`})}catch(e){return r.debug(`[PanelObserver] 建立观察端口失败(忽略):`,e?.message||e),null}ba.set(e,n);try{n.onMessage.addListener(e=>{for(let t of xa)try{t(e)}catch(e){r.debug(`[PanelObserver] 消息处理异常(忽略):`,e?.message||e)}})}catch(e){r.debug(`[PanelObserver] 观察端口消息监听挂不上(忽略):`,e?.message||e)}try{n.onDisconnect.addListener(()=>{ba.get(e)===n&&ba.delete(e)})}catch(e){r.debug(`[PanelObserver] 观察端口断开监听挂不上(忽略):`,e?.message||e)}return n}function wa(e){if(!e)return;let t=ba.get(e);if(t){ba.delete(e);try{t.disconnect()}catch(e){r.debug(`[PanelObserver] 关闭观察端口异常(忽略):`,e?.message||e)}}}function Ta({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 Ea({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 Da=!1,Oa=new Map,ka=null,Aa=!1,ja=null,Ma=null,Na=null,Pa=250,Fa=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 Ia(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 La(e,t){let n=new Map;return{start(){Dn(e,``),It(``),oi(Date.now()),ui(t),Kn(t)},chunk(n){Dn(e,n),wt(t,n)},restore({html:e}){Hr(t,e)},toolCalls(e,n){typeof n==`string`&&n&&ea(t,n),Ki(t,e)},toolResult(e){Pr(e,t)},agentStream(e){Mt(t,n),Ti(n,t,e)},agentStreamDone(e){let t=n.get(e.execId);t&&t.element&&e.exitCode!==0&&t.element.classList.add(`agent-stream-error`)},retrying(e,n){Dr(t,e,n)},preselect(e){let n=t.querySelector(`.message-content`);!n||!e.length||e.forEach(e=>n.insertBefore(Kr(e),n.firstChild))},final(e,n,r={}){ca(t,e,n,r.reflectionScore,r.reasoningContent,r.wasRevised)},error(e,n){ca(t,e,n||[])}}}async function Ra(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),y.activeSessionId===t){y.messageHistory.push(i);try{document.dispatchEvent(new CustomEvent(`session-cache-invalidate`,{detail:{sessionId:t}}))}catch{}}let{appendMessageToSession:a}=await D(async()=>{let{appendMessageToSession:e}=await import(`./context-indicator-DjOAo_Ln.js`).then(e=>e.kr);return{appendMessageToSession:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]));await a(t,i)}function za(){D(()=>import(`./context-indicator-DjOAo_Ln.js`).then(e=>e.U).then(e=>e.syncPendingSessionsToStorage()),__vite__mapDeps([0,1,2,3,4,5,6,7,8])).catch(e=>r.debug(`[ChatReattach] 同步生成态失败(忽略):`,e?.message||e))}var Ba=1e3;function Va(e){return Promise.race([ri(e),new Promise(e=>setTimeout(()=>e(null),Ba))])}function Ha(e,n){let i=yr(e);if(i())return!1;let a=Ar(e);a.dataset.callId=n,i(a),Dn(e,``),oi(Date.now()),Bt(Date.now()),y.pendingCallApiSessionIds.add(e),y.generatingSessionIds.add(e),za();try{document.dispatchEvent(new CustomEvent(`generating-state-changed`))}catch{}let o=Ta({sessionId:e,callId:n,awaitSnapshot:!0,renderer:La(e,a),persist:t=>Ra(t,e,a),emptyFallback:t(`chatMsg.emptyModelReply`),onFinished:()=>{if(Oa.get(e)===o){Oa.delete(e),wa(e),y.pendingCallApiSessionIds.delete(e),za(),Xi(e);try{document.dispatchEvent(new CustomEvent(`session-cache-invalidate`,{detail:{sessionId:e}}))}catch{}Nn(e)}}});return Oa.set(e,o),Ca(e),Va(e).then(t=>{o.finished||Oa.get(e)!==o||o.restore(t)}).catch(()=>o.restore(null)),y.activeSessionId===e&&ia(e),r.info(`[ChatReattach] 已接管运行中的任务: sessionId=${e}, callId=${n}`),!0}function Ua(e){let t=Oa.get(e);if(!t)return;Oa.delete(e),wa(e);try{t.dispose?.()}catch{}let n=yr(e),r=n();try{r?.remove()}catch{}n(null),Xi(e),y.pendingCallApiSessionIds.delete(e),za();try{document.dispatchEvent(new CustomEvent(`generating-state-changed`))}catch{}}function Wa(){let e=ka;e&&Promise.resolve().then(()=>e.syncFromBackground()).catch(e=>r.debug(`[ChatReattach] 对齐后台状态失败(忽略):`,e?.message||e))}function Ga(){!Da||!ka||Na||(Na=setTimeout(()=>{Na=null,Wa()},Pa))}var Ka=new Map,qa=3e3,Ja=100,Ya=new Set,Xa=new Set([`API_COMPLETE`,`API_ERROR`]);function Za(e,t){let n=`${e}|${t.callId}`;Ya.has(n)||(Ya.add(n),Ya.size>Ja&&Ya.delete(Ya.values().next().value),Ua(e),Ha(e,t.callId)&&Oa.get(e)?.handleMessage(t))}function Qa(e,t,n){let r=Ka.get(e);if(r){r.messages.push(n);return}r={callId:t,messages:[n]},Ka.set(e,r),Ia(qa).then(t=>$a(e,t&&t.activeCallIds&&t.activeCallIds[e]||null)).catch(()=>$a(e,null)).finally(()=>{Ka.delete(e)})}function $a(e,t){let n=Ka.get(e);if(!n)return;let{callId:r,messages:i}=n;if(t===r)Ua(e),Ha(e,r);else if(t===null){let t=i.find(e=>Xa.has(e.type));if(!t)return;Za(e,t);return}else return;let a=Oa.get(e);if(!(!a||a.callId!==r))for(let e of i){if(a.finished)break;a.handleMessage(e)}}function eo(){if(Aa)return;Aa=!0;let e=e=>{if(!e)return!1;let t=e.sessionId?Oa.get(e.sessionId):null;return t?e.callId&&e.callId!==t.callId?(Qa(e.sessionId,e.callId,e),!1):(Ca(e.sessionId),t.handleMessage(e),!1):(e.callId&&Fa.has(e.type)&&Ga(),!1)};chrome.runtime.onMessage.addListener(e),Sa(e),ja=e=>{let t=e?.detail?.sessionId;t&&Oa.has(t)&&ia(t),Ga()},document.addEventListener(`session-hydrated`,ja),Ma=e=>{let t=e?.detail?.sessionId;t&&Oa.has(t)&&ia(t)},document.addEventListener(`chat-history-rendered`,Ma)}function to(){return Da?{syncFromBackground:()=>ka.syncFromBackground()}:(Da=!0,eo(),ka=Ea({queryRunning:Ia,hasLocalListener:e=>y.pendingCancelApiMap.has(e),isAttached:(e,t)=>Oa.get(e)?.callId===t?(Ca(e),!0):!1,attach:(e,t)=>{Ha(e,t)}}),ka.syncFromBackground(),{syncFromBackground:()=>ka.syncFromBackground()})}function no(e){!Da||!ka||(e&&y.activeSessionId===e&&ia(e),ka.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 ro=`sessionDockDismissed`,io=5e3,ao=250,oo=1200,so=8,co=so-1,lo=9e4,uo={running:0,queued:1,done:2},fo=new Map,po=new Map,mo=new Map,ho=new Map,go=new Set,_o=new Set,vo=new Map,yo=new Map,bo=new Set,xo=new Set,So=new Set,Co=[],wo=new Set,M=null,N=null,P=null,To=[],Eo=!1,Do=null,Oo=null,ko=!1,Ao=null,jo=null;function Mo(e){return e?Array.isArray(e)?e:e instanceof Set?Array.from(e):[]:[]}function No(e){let t=new Set;for(let n of Mo(e))n&&t.add(h(String(n))||String(n));return t}function Po({phase:e=``,sessionId:t=null,backendRunningIds:n=[],startedAt:r=0,lastUpdateAt:i=0,now:a=Date.now(),staleMs:o=lo}={}){if(e!==`running`||!t||Mo(n).includes(t))return!1;let s=Math.max(Number(r)||0,Number(i)||0);return s?a-s>=o:!1}var Fo=160;function Io(e){let t=String(e??``).replace(/\s+/g,` `).trim();if(!t)return``;let n=Array.from(t);return n.length<=Fo?t:`${n.slice(0,Fo).join(``).trimEnd()}…`}function Lo(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 Ro({phase:e=``,queuedText:t=``,questionText:n=``,title:r=``}={}){let i=e===`queued`?Io(t):``,a=i||Io(n),o=Io(r),s=a||o,c=i?`queued`:a?`question`:s?`title`:``;return{primary:s,sub:a&&!Lo(o,a)?o:``,isQuestion:!!a,from:c}}function zo(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=re(n.content);if(r&&String(r).trim())return{text:String(r),messageId:n.messageId?String(n.messageId):``}}return{text:``,messageId:``}}function Bo({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:_=lo}={}){let ee=Mo(s),v=new Set([...Mo(a),...Mo(o),...ee]),te=new Set(Mo(c)),y=new Set(Mo(d)),b=new Set(Mo(u)),ne=l||{},x=new Set([...v,...te,...Object.keys(ne)]),S=[];for(let a of x){if(!a||a===e)continue;let o=Number(ne[a])||0,s;if(v.has(a))s=`running`;else if(o>0)s=`queued`;else if(te.has(a))s=`done`;else continue;let c=Po({phase:s,sessionId:a,backendRunningIds:ee,startedAt:p?.[a],lastUpdateAt:h?.[a],now:g,staleMs:_});if(y.has(a)&&(s===`done`||c))continue;let l=f?.[a]||{},u=Ro({phase:s,queuedText:i?.[a]||``,questionText:n?.[a]||``,title:t?.[a]||``});S.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:b.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 S.sort((e,t)=>{let n=uo[e.phase]-uo[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}),S}function Vo(e){return So.has(e)||y.generatingSessionIds.has(e)||y.pendingCallApiSessionIds.has(e)}function Ho(){let e={};try{let t=Rn();for(let n of t){let t=Ut(n);t>0&&(e[n]=t)}}catch(e){r.debug(`[SessionDock] read queue counts failed:`,e?.message||e)}return e}function Uo(){let e={};for(let t of y.sessions||[])e[t.id]=t.title||``;for(let[t,n]of vo)e[t]||(e[t]=n);return e}function Wo(){let e={},t={},n=new Map;for(let e of y.sessions||[])n.set(e.id,e);for(let r of new Set([...So,...y.generatingSessionIds,...y.pendingCallApiSessionIds,...y.completedSessionIds])){let i=po.get(r)||mo.get(r)||0,a=yo.get(r);if(i&&a&&a.stamp===i){a.text&&(e[r]=a.text,t[r]=a.messageId||``);continue}let o=zo(n.get(r));o.text&&(e[r]=o.text,t[r]=o.messageId)}return{questions:e,anchors:t}}function Go(){let e={};try{for(let t of Rn()){let n=da(t);n?.text&&(e[t]=String(n.text))}}catch(e){r.debug(`[SessionDock] read queued texts failed:`,e?.message||e)}return e}function Ko(e){for(let t of e||[]){let e=t.sessionId;if(!e)continue;let n=t.startedAt||t.doneAt||0,i=yo.get(e),a=!i||i.stamp!==n,o=!t.title;!a&&!o||xo.has(e)||(xo.add(e),ne(e).then(t=>{if(t&&((o||!vo.has(e))&&vo.set(e,t.title||``),a)){let r=zo(t);yo.set(e,{text:r.text,messageId:r.messageId,stamp:n})}}).catch(e=>{r.debug(`[SessionDock] hydrate label failed:`,e?.message||e)}).finally(()=>{xo.delete(e),F()}))}}function qo(e){if(!e)return``;let t=new Date(e);return`${String(t.getHours()).padStart(2,`0`)}:${String(t.getMinutes()).padStart(2,`0`)}`}function Jo(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:qo(e.doneAt)}):t(`dock.done`)}function Yo(e){po.set(e,Date.now()),mo.delete(e),yo.delete(e)}function Xo(){let e=new Set([...y.generatingSessionIds,...y.pendingCallApiSessionIds]);for(let t of e)bo.has(t)&&(bo.delete(t),Yo(t));F()}function Zo(){let e=y.completedSessionIds;for(let e of new Set([...So,...y.generatingSessionIds,...y.pendingCallApiSessionIds]))po.has(e)||po.set(e,Date.now()),mo.delete(e);for(let e of So)_o.delete(e);for(let t of e)!mo.has(t)&&!Vo(t)&&mo.set(t,Date.now());let{questions:t,anchors:n}=Wo(),r=Bo({activeSessionId:y.activeSessionId,titles:Uo(),questions:t,anchors:n,queuedTexts:Go(),generatingIds:y.generatingSessionIds,pendingIds:y.pendingCallApiSessionIds,runningIds:So,completedIds:e,queuedCounts:Ho(),scheduledIds:go,dismissedIds:_o,nodeInfo:Object.fromEntries(fo),startedAt:Object.fromEntries(po),doneAt:Object.fromEntries(mo),lastUpdateAt:Object.fromEntries(ho),now:Date.now()});return Ko(r),r}function Qo(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&&(wo=new Set(n),Ao&&clearTimeout(Ao),Ao=setTimeout(()=>{Ao=null,wo=new Set,F()},oo))}function $o(){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),es();let e=document.getElementById(`chatContainer`);return e&&typeof ResizeObserver<`u`&&new ResizeObserver(es).observe(e),window.addEventListener(`resize`,es),M}function es(){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 ts(e){bi(e.sessionId,{focusMessageId:e.anchorMessageId||null})}function ns(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`),wo.has(e.sessionId)&&n.classList.add(`is-flash`);let r=e.title||t(`dock.unknownSession`),i=e.primary||r,a=Jo(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`,()=>{ts(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(),hs(e.sessionId)}),n.appendChild(r)}return n.addEventListener(`mouseenter`,()=>rs(n,e,a)),n.addEventListener(`mouseleave`,is),n.addEventListener(`focusin`,()=>rs(n,e,a)),n.addEventListener(`focusout`,is),n}function rs(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 is(){N&&N.classList.remove(`show`)}function as(){return P||typeof document>`u`?P:(P=document.createElement(`div`),P.className=`session-dock-overflow`,P.setAttribute(`role`,`menu`),P.addEventListener(`mouseenter`,os),P.addEventListener(`mouseleave`,ss),P.addEventListener(`focusin`,os),P.addEventListener(`focusout`,ss),document.body.appendChild(P),P)}function os(){jo&&=(clearTimeout(jo),null)}function ss(){Eo||(os(),jo=setTimeout(()=>{jo=null,fs()},220))}function cs(){let e=M?M.querySelector(`.session-dock-more`):null;e&&(e.setAttribute(`aria-expanded`,Eo?`true`:`false`),e.classList.toggle(`is-open`,Eo))}function ls(){let e=as();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 To){let n=e.primary||e.title||t(`dock.unknownSession`),i=Jo(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`,()=>{fs(),ts(e)}),r.appendChild(a)}e.appendChild(r)}function us(){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 ds(){To.length!==0&&as()&&(os(),ls(),us(),P.classList.add(`show`),cs())}function fs(){os(),Eo=!1,P&&P.classList.remove(`show`),cs()}function ps(){if(P&&P.classList.contains(`show`)&&Eo){fs();return}ds(),Eo=!0,cs()}function ms(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`,Eo?`true`:`false`),r.textContent=`+${e.length>99?`99`:e.length}`,r.addEventListener(`click`,()=>ps()),n.appendChild(r),n.addEventListener(`mouseenter`,()=>ds()),n.addEventListener(`mouseleave`,ss),n.addEventListener(`focusin`,()=>ds()),n.addEventListener(`focusout`,ss),n}function hs(e){e&&(_o.add(e),gs(),F())}function gs(){try{chrome.storage.local.set({[ro]:Array.from(_o)}).catch(()=>{})}catch{}}function _s(){try{chrome.storage.local.get([ro],e=>{let t=e?.[ro];if(Array.isArray(t)){for(let e of t)_o.add(e);F()}})}catch{}}function vs(){if(!$o())return;let e=Zo();if(Qo(e),Co=e,fs(),To=[],M.innerHTML=``,e.length===0){M.classList.remove(`show`),document.body.classList.remove(`has-session-dock`),is();return}let t=e.length>so?co:so;To=e.slice(t);for(let n of e.slice(0,t))M.appendChild(ns(n));To.length>0&&M.appendChild(ms(To)),M.classList.add(`show`),document.body.classList.add(`has-session-dock`)}function F(){Do||=setTimeout(()=>{Do=null;try{vs()}catch(e){r.warn(`[SessionDock] render failed:`,e?.message||e)}},ao)}function ys(){return new Promise(e=>{try{chrome.runtime.sendMessage({type:`QUERY_SESSION_RUNNING`},t=>{if(chrome.runtime.lastError||!t){e();return}if(Array.isArray(t.activeSessionIds)){let e=No(t.activeSessionIds);for(let t of e){if(bo.has(t)){bo.delete(t),Yo(t);continue}So.has(t)||y.generatingSessionIds.has(t)||y.pendingCallApiSessionIds.has(t)||Yo(t)}So=e}e()})}catch{e()}})}function bs(e){let t=e?.sessionId;if(!t)return;let n=fo.get(t)||{};fo.set(t,{nodeName:e.nodeName||n.nodeName||``,subtaskIndex:e.subtaskIndex||n.subtaskIndex||0,subtaskTotal:e.subtaskTotal||n.subtaskTotal||0}),ho.set(t,Date.now()),F()}function xs(e){e&&(fo.delete(e),po.delete(e),mo.delete(e),ho.delete(e),_o.delete(e),vo.delete(e),yo.delete(e),bo.delete(e),F())}function Ss(){if(!(ko||typeof document>`u`||!$o())){ko=!0,_s(),document.addEventListener(`generating-state-changed`,Xo),document.addEventListener(`session-switched`,F),document.addEventListener(`generation-ended`,e=>{let t=e?.detail?.sessionId;t&&(bo.add(t),mo.has(t)||mo.set(t,Date.now())),F()}),document.addEventListener(`session-archived`,e=>xs(e?.detail?.sessionId)),document.addEventListener(`session-deleted`,e=>xs(e?.detail?.sessionId));try{qt(F)}catch(e){r.debug(`[SessionDock] subscribe queue failed:`,e?.message||e)}try{chrome.runtime.onMessage.addListener(e=>e?e.type===`EXECUTION_STATUS_UPDATE`?(bs(e),!1):e.type===`SCHEDULED_TASK_RUN_STATE`&&e.sessionId?(e.running?go.add(e.sessionId):go.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){fs();return}ys().then(F)}),document.addEventListener(`keydown`,e=>{e.key===`Escape`&&Eo&&fs()}),Oo||=setInterval(()=>{document.hidden||ys().then(F)},io),ys().then(()=>{for(let e of So)po.has(e)||po.set(e,Date.now());vs()})}}function Cs(){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){_();return}h(f(o),o.length)}function _(){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(),x()});let n=a.querySelector(`[data-role="nav-search"]`);if(n){let e=()=>{l!==n.value&&(l=n.value,_())};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 ee(){let e=document.activeElement;return e?[r,i,a].some(t=>t&&(t===e||t.contains(e))):!1}function v(){i.classList.remove(`expanded`),a&&a.classList.remove(`expanded`)}function te(){let e=ee();v(),e&&r&&(u=!0,r.focus({preventScroll:!0}),u=!1)}function y(){if(clearTimeout(c),i.classList.add(`expanded`),a){if(a.classList.contains(`expanded`)){g();return}_()?a.classList.add(`expanded`):a.classList.remove(`expanded`)}}function b(e){clearTimeout(c),!s&&(ee()||(e?v():c=setTimeout(v,300)))}function ne(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 x(){ne(!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`,y),r.addEventListener(`mouseleave`,()=>b(!1)),r.addEventListener(`click`,()=>x()),r.addEventListener(`focus`,()=>{u||y()}),r.addEventListener(`blur`,()=>b(!1)),r.addEventListener(`keydown`,e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),x())}),i.addEventListener(`mouseenter`,y),i.addEventListener(`mouseleave`,()=>b(!1)),i.addEventListener(`focusin`,y),a&&(a.addEventListener(`mouseenter`,()=>{d=!0,y()}),a.addEventListener(`mouseleave`,()=>{d=!1,b(!1)}),a.addEventListener(`focusin`,y),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():te()})));{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 S(){let e=a&&a.classList.contains(`expanded`);if(!s&&!e)return!1;if(a&&a.querySelector(`[data-role="nav-search"]`)&&l){l=``,_();let e=a.querySelector(`[data-role="nav-search"]`);return e&&e.focus(),!0}return ne(!1),te(),!0}return{jumpToMessage:p,updateActiveQuestion:g,handleEscape:S,isPinned:()=>s}}function ws(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 Ts=!1,Es=!1,I=[],Ds=``;function Os(){y.searchInputHistory=[],y.searchInputHistoryIndex=-1;try{chrome.storage.local.get([`searchInputHistory`],e=>{e.searchInputHistory&&(y.searchInputHistory=e.searchInputHistory)})}catch{}let e=document.createElement(`div`);e.className=`search-panel-container`,e.id=`searchPanelContainer`,e.innerHTML=`
3
3
  <button class="search-panel-toggle" id="searchPanelToggle" title="${t(`searchPanel.toggleTitle`)}">
4
4
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
5
5
  <circle cx="11" cy="11" r="8"/>
@@ -34,30 +34,30 @@ import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-5c8prpFJ.js"
34
34
  <div class="search-panel-empty">${t(`searchPanel.startSearchHint`)}</div>
35
35
  </div>
36
36
  </div>
37
- `,sr(`search`).appendChild(e),Ds(),r.debug(`[SearchPanel] search panelinitializing`)}function Ds(){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`)?ks():Os()}),i.addEventListener(`click`,()=>{ks()});let s=sn(`search-panel-close-btn`);i.before(s),ki(s,e,{onToggle:t=>{t||Je(e)}}),r.addEventListener(`click`,()=>{n.value=``,r.style.display=`none`,As(),n.focus()}),n.addEventListener(`input`,()=>{let e=n.value.trim();r.style.display=e?``:`none`,e||As()}),n.addEventListener(`keydown`,e=>{if(e.key===`Enter`){e.stopPropagation();let t=n.value.trim();t&&(c(t),js(t))}else if(e.key===`Escape`)v.searchInputHistoryIndex>=0?(v.searchInputHistoryIndex=-1,n.value=``):(e.stopPropagation(),ks());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 c(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&&js(e)}),o.addEventListener(`click`,()=>{o.classList.contains(`active`)||(o.classList.add(`active`),a.classList.remove(`active`));let e=n.value.trim();e&&js(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 zs(n,r)})}function Os(){let e=document.getElementById(`searchPanel`),t=document.getElementById(`searchPanelInput`);e.classList.add(`expanded`),Je(e),t.value.trim()&&F.length===0&&js(t.value.trim()),setTimeout(()=>t.focus(),100)}function ks(){let e=document.getElementById(`searchPanel`);dr(e),e.classList.remove(`expanded`),Xe(e),ws=!0,Cs=!1}function As(){ws=!0,Cs=!1,F=[],Ts=``;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 js(e){if(!e||!e.trim()||(e=e.trim().toLowerCase(),Cs&&Ts===e))return;ws=!0,await new Promise(e=>setTimeout(e,50)),Cs=!0,ws=!1,F=[],Ts=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 Ns(e,n,i):await Ms(e,n,i)}catch(e){r.error(`[SearchPanel] search error:`,e),ws||(n.innerHTML=`<div class="search-panel-empty">${t(`searchPanel.searchError`)}</div>`)}ws||(Cs=!1)}async function Ms(e,n,r){let i=v.activeSessionId;if(!i){n.innerHTML=`<div class="search-panel-empty">${t(`searchPanel.noActiveSession`)}</div>`;return}let a=Ps(v.messageHistory||[],e,i);if(!ws){if(F=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}Is(a,e,n)}}async function Ns(e,n,i){let a=v.activeSessionId,o=await ce(),s=(o||[]).filter(e=>!e.archivedAt);if(ws)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=Ps(v.messageHistory||[],e,a);if(ws)return;let s=o.find(e=>e.id===a)?.title||t(`searchPanel.currentSession`);for(let e of r)c.push({...e,sessionTitle:s});F=[...c],i.textContent=t(`searchPanel.searchingWithCount`,{count:c.length}),Is(F,e,n,!0)}let u=s.filter(e=>e.id!==a);for(let a of u){if(ws)return;try{let r=await y(a.id);if(!r||!r.messageHistory)continue;let o=Ps(r.messageHistory||[],e,a.id);if(o.length>0){for(let e of o)l.push({...e,sessionTitle:a.title||t(`searchPanel.unknownSession`)});F=[...c,...l];let r=c.length+l.length;i.textContent=r>0?t(`searchPanel.countResult`,{count:r}):t(`searchPanel.noResult`),Is(F,e,n)}}catch(e){r.warn(`[SearchPanel] searchsession failed:`,a.id,e)}await new Promise(e=>setTimeout(e,10))}if(ws)return;let d=F.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}Is(F,e,n)}function Ps(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=Fs(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 Fs(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 Is(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">
37
+ `,or(`search`).appendChild(e),ks(),r.debug(`[SearchPanel] search panelinitializing`)}function ks(){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`)?js():As()}),i.addEventListener(`click`,()=>{js()});let s=on(`search-panel-close-btn`);i.before(s),Oi(s,e,{onToggle:t=>{t||$e(e)}}),r.addEventListener(`click`,()=>{n.value=``,r.style.display=`none`,Ms(),n.focus()}),n.addEventListener(`input`,()=>{let e=n.value.trim();r.style.display=e?``:`none`,e||Ms()}),n.addEventListener(`keydown`,e=>{if(e.key===`Enter`){e.stopPropagation();let t=n.value.trim();t&&(c(t),Ns(t))}else if(e.key===`Escape`)y.searchInputHistoryIndex>=0?(y.searchInputHistoryIndex=-1,n.value=``):(e.stopPropagation(),js());else if(e.key===`ArrowUp`){e.preventDefault(),e.stopPropagation();let t=y.searchInputHistory;if(t.length===0)return;y.searchInputHistoryIndex===-1?y.searchInputHistoryIndex=t.length-1:y.searchInputHistoryIndex>0&&y.searchInputHistoryIndex--,n.value=t[y.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=y.searchInputHistory;y.searchInputHistoryIndex>=0&&y.searchInputHistoryIndex<t.length-1?(y.searchInputHistoryIndex++,n.value=t[y.searchInputHistoryIndex]||``,n.selectionStart=n.selectionEnd=n.value.length):(y.searchInputHistoryIndex=-1,n.value=``),r.style.display=n.value?``:`none`}});function c(e){if(!e||!e.trim())return;let t=e.trim(),n=y.searchInputHistory,r=n.indexOf(t);r!==-1&&n.splice(r,1),n.push(t),n.length>20&&n.shift(),y.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&&Ns(e)}),o.addEventListener(`click`,()=>{o.classList.contains(`active`)||(o.classList.add(`active`),a.classList.remove(`active`));let e=n.value.trim();e&&Ns(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 Vs(n,r)})}function As(){let e=document.getElementById(`searchPanel`),t=document.getElementById(`searchPanelInput`);e.classList.add(`expanded`),$e(e),t.value.trim()&&I.length===0&&Ns(t.value.trim()),setTimeout(()=>t.focus(),100)}function js(){let e=document.getElementById(`searchPanel`);ur(e),e.classList.remove(`expanded`),Ze(e),Es=!0,Ts=!1}function Ms(){Es=!0,Ts=!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 Ns(e){if(!e||!e.trim()||(e=e.trim().toLowerCase(),Ts&&Ds===e))return;Es=!0,await new Promise(e=>setTimeout(e,50)),Ts=!0,Es=!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 Fs(e,n,i):await Ps(e,n,i)}catch(e){r.error(`[SearchPanel] search error:`,e),Es||(n.innerHTML=`<div class="search-panel-empty">${t(`searchPanel.searchError`)}</div>`)}Es||(Ts=!1)}async function Ps(e,n,r){let i=y.activeSessionId;if(!i){n.innerHTML=`<div class="search-panel-empty">${t(`searchPanel.noActiveSession`)}</div>`;return}let a=Is(y.messageHistory||[],e,i);if(!Es){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}Rs(a,e,n)}}async function Fs(e,n,i){let a=y.activeSessionId,o=await oe(),s=(o||[]).filter(e=>!e.archivedAt);if(Es)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=Is(y.messageHistory||[],e,a);if(Es)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}),Rs(I,e,n,!0)}let u=s.filter(e=>e.id!==a);for(let a of u){if(Es)return;try{let r=await ne(a.id);if(!r||!r.messageHistory)continue;let o=Is(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`),Rs(I,e,n)}}catch(e){r.warn(`[SearchPanel] searchsession failed:`,a.id,e)}await new Promise(e=>setTimeout(e,10))}if(Es)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}Rs(I,e,n)}function Is(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=Ls(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 Ls(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 Rs(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=y.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
38
  <div class="search-section-title">${t(`searchPanel.currentSessionResults`,{label:l,count:o.length})}</div>
39
- ${Ls(o,n)}
39
+ ${zs(o,n)}
40
40
  </div>`),s.length>0&&(c+=`<div class="search-section">
41
41
  <div class="search-section-title">${t(`searchPanel.otherSessionsResults`,{count:s.length})}</div>
42
- ${Ls(s,n)}
43
- </div>`),r.innerHTML=c}function Ls(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=Rs(A(e.matchPreview),n);return`
44
- <div class="search-result-item" data-session-id="${e.sessionId}" data-message-id="${e.messageId}" title="${A(e.content)}">
42
+ ${zs(s,n)}
43
+ </div>`),r.innerHTML=c}function zs(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===y.activeSessionId,c=Bs(k(e.matchPreview),n);return`
44
+ <div class="search-result-item" data-session-id="${e.sessionId}" data-message-id="${e.messageId}" title="${k(e.content)}">
45
45
  <div class="search-result-header">
46
46
  <span class="search-result-role">${i} ${a}</span>
47
- ${s?``:`<span class="search-result-session" title="${A(o)}">${A(o.length>20?o.substring(0,20)+`...`:o)}</span>`}
47
+ ${s?``:`<span class="search-result-session" title="${k(o)}">${k(o.length>20?o.substring(0,20)+`...`:o)}</span>`}
48
48
  </div>
49
49
  <div class="search-result-preview">${c}</div>
50
50
  </div>
51
- `}).join(``)}function Rs(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 zs(e,n){if(!(!e||!n)){if(v.activeSessionId!==e)try{let n=v.activeSessionId;if(await wt(e)===!1||v.activeSessionId!==e){k(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-Btg9ZLat.js`).then(e=>e.cr);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{k(t(`searchPanel.messageDeleted`),`warning`);try{if(await _(e,n)){F=F.filter(t=>!(t.sessionId===e&&t.messageId===n));let i=document.getElementById(`searchPanelContent`),a=document.getElementById(`searchPanelCount`);i&&F.length>0?(Is(F,Ts,i),a.textContent=t(`searchPanel.countResult`,{count:F.length})):i&&F.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 Bs(e){return chrome.runtime.sendMessage(e)}function Vs(e){return e?new Date(e).toLocaleString(void 0,{month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`}):`—`}function Hs(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 Us(e){return e===`success`?t(`schedPanel.statusSuccess`):e===`failed`?t(`schedPanel.statusFailed`):e===`running`?t(`schedPanel.statusRunning`):``}function Ws(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 Gs(e){let n=e.schedule||{};return n.type===`once`?n.onceMode===`relative`?t(`schedPanel.scheduleTypeOnce`)+` · `+(n.value||``)+t(`schedPanel.minutesSuffix`):t(`schedPanel.scheduleTypeOnce`)+` · `+Vs(new Date(n.value).getTime()):n.type===`interval`?t(`schedPanel.scheduleTypeInterval`)+` · `+(n.value||``):n.type===`cron`?t(`schedPanel.scheduleTypeCron`)+` · `+(n.value||``):``}function Ks(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 qs(){let e=document.getElementById(`chatContainer`);e&&(e.scrollTop=e.scrollHeight)}async function Js(e){if(e){if(v.activeSessionId!==e){let t=v.activeSessionId;try{if(await wt(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-Btg9ZLat.js`).then(e=>e.cr);return{renderSessionTabs:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]));e()}catch{}}setTimeout(qs,500)}}function Ys(){let e=document.createElement(`div`);e.className=`schedule-panel-container`,e.id=`schedulePanelContainer`,e.innerHTML=`
51
+ `}).join(``)}function Bs(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 Vs(e,n){if(!(!e||!n)){if(y.activeSessionId!==e)try{let n=y.activeSessionId;if(await Ct(e)===!1||y.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 D(async()=>{let{renderSessionTabs:e}=await import(`./context-indicator-DjOAo_Ln.js`).then(e=>e.cr);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:y.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 te(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?(Rs(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 Hs(e){return chrome.runtime.sendMessage(e)}function Us(e){return e?new Date(e).toLocaleString(void 0,{month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`}):`—`}function Ws(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 Gs(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 qs(e){let n=e.schedule||{};return n.type===`once`?n.onceMode===`relative`?t(`schedPanel.scheduleTypeOnce`)+` · `+(n.value||``)+t(`schedPanel.minutesSuffix`):t(`schedPanel.scheduleTypeOnce`)+` · `+Us(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 Ys(){let e=document.getElementById(`chatContainer`);e&&(e.scrollTop=e.scrollHeight)}async function Xs(e){if(e){if(y.activeSessionId!==e){let t=y.activeSessionId;try{if(await Ct(e)===!1||y.activeSessionId!==e)return}catch{return}document.dispatchEvent(new CustomEvent(`session-switched`,{detail:{sessionId:e,previousSessionId:t,skipScrollRestore:!0}}));try{let{renderSessionTabs:e}=await D(async()=>{let{renderSessionTabs:e}=await import(`./context-indicator-DjOAo_Ln.js`).then(e=>e.cr);return{renderSessionTabs:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]));e()}catch{}}setTimeout(Ys,500)}}function Zs(){let e=document.createElement(`div`);e.className=`schedule-panel-container`,e.id=`schedulePanelContainer`,e.innerHTML=`
52
52
  <style>
53
53
  .schedule-panel-container { position: relative; display: flex; justify-content: flex-end; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; width: 100%; background: transparent; }
54
- .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; }
55
- .schedule-panel-toggle:hover { background: rgba(var(--success-rgb), 0.24); box-shadow: -2px 2px 8px rgba(var(--success-rgb), 0.2); }
54
+ .schedule-panel-toggle { background: rgba(var(--brand-rgb), 0.14); color: var(--brand-600); 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; }
55
+ .schedule-panel-toggle:hover { background: rgba(var(--brand-rgb), 0.24); box-shadow: -2px 2px 8px rgba(var(--brand-rgb), 0.2); }
56
56
  .schedule-panel-toggle svg { width: 16px; height: 16px; }
57
57
  .schedule-panel-toggle.running svg { animation: sched-icon-spin 1.4s linear infinite; transform-origin: center; transform-box: fill-box; }
58
58
  .schedule-panel-toggle.running { animation: sched-btn-glow 1.4s ease-in-out infinite; }
59
59
  @keyframes sched-icon-spin { to { transform: rotate(360deg); } }
60
- @keyframes sched-btn-glow { 0%, 100% { box-shadow: -2px 2px 8px rgba(var(--success-rgb), 0.3); } 50% { box-shadow: -2px 2px 18px rgba(var(--success-rgb), 0.85); } }
60
+ @keyframes sched-btn-glow { 0%, 100% { box-shadow: -2px 2px 8px rgba(var(--brand-rgb), 0.3); } 50% { box-shadow: -2px 2px 18px rgba(var(--brand-rgb), 0.85); } }
61
61
  .schedule-panel { position: absolute; right: 26px; bottom: -40px; width: 360px; max-height: 70vh; background: rgba(var(--surface-rgb), 1); backdrop-filter: blur(20px); -webkit-backdrop-filter: blur(20px); border: 1px solid var(--border-strong); border-radius: 12px; box-shadow: 0 8px 32px rgba(var(--overlay-rgb), 0.18); display: none; flex-direction: column; overflow: hidden; transform: translateY(var(--clamp-y, 0px)); }
62
62
  .schedule-panel.open { display: flex; }
63
63
  .schedule-panel-header { display: flex; align-items: center; gap: 6px; padding: 10px 14px; border-bottom: 1px solid var(--border-subtle); flex-shrink: 0; }
@@ -155,7 +155,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-5c8prpFJ.js"
155
155
  </div>
156
156
  <div class="schedule-panel-list" id="schedulePanelList"></div>
157
157
  </div>
158
- `,sr(`schedule`).appendChild(e);let n=document.createElement(`div`);n.className=`sched-modal-overlay`,n.id=`scheduleModalOverlay`,n.innerHTML=`
158
+ `,or(`schedule`).appendChild(e);let n=document.createElement(`div`);n.className=`sched-modal-overlay`,n.id=`scheduleModalOverlay`,n.innerHTML=`
159
159
  <div class="sched-modal">
160
160
  <div class="sched-modal-header">
161
161
  <h3 id="scheduleModalTitle"></h3>
@@ -202,25 +202,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-5c8prpFJ.js"
202
202
  <button class="primary" id="scheduleModalSave">${t(`schedPanel.save`)}</button>
203
203
  </div>
204
204
  </div>
205
- `,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`),Je(i),T()):(i.classList.remove(`open`),Xe(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`,fe),f.addEventListener(`click`,fe),p.addEventListener(`click`,me),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 Bs({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">${A(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=>`
205
+ `,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=on(`close-btn`);s.before(c),Oi(c,i,{onToggle:e=>{e||$e(i)}});let l=document.getElementById(`scheduleNewTask`),u=document.getElementById(`schedulePanelList`),d=document.getElementById(`scheduleModalOverlay`),f=document.getElementById(`scheduleModalTitle`),p=document.getElementById(`scheduleModalCancel`),m=document.getElementById(`scheduleModalSave`),h=document.getElementById(`schedFormType`),g=document.getElementById(`schedFormValue`),_=document.getElementById(`schedFormOnceMode`),ee=document.getElementById(`schedOnceModeWrap`),v=document.getElementById(`schedValueLabel`),te=document.getElementById(`schedEndWrap`),b=null,ne=`schedPanelView`,x=`all`,S=`created`,C=[],w=document.getElementById(`schedFilterGroup`),T=document.getElementById(`schedSortSelect`);function re(e){if(typeof e==`number`)return Number.isFinite(e)?e:0;let t=Date.parse(e||``);return Number.isFinite(t)?t:0}function ie(e){return S===`lastRun`?re(e.lastRunAt)||re(e.createdAt):S===`updated`&&re(e.updatedAt)||re(e.createdAt)}function E(){w.querySelectorAll(`.sched-filter-btn`).forEach(e=>{e.classList.toggle(`active`,e.dataset.filter===x)}),T.value=S}function ae(){try{Promise.resolve(chrome.storage.local.set({[ne]:{filter:x,sort:S}})).catch(()=>{})}catch{}}w.addEventListener(`click`,e=>{let t=e.target.closest(`.sched-filter-btn`);!t||t.dataset.filter===x||(x=t.dataset.filter,E(),ae(),le(C))}),T.addEventListener(`change`,()=>{S=T.value,ae(),le(C)}),(async()=>{try{let e=(await chrome.storage.local.get(ne))?.[ne];(e?.filter===`enabled`||e?.filter===`disabled`||e?.filter===`all`)&&(x=e.filter),(e?.sort===`lastRun`||e?.sort===`updated`||e?.sort===`created`)&&(S=e.sort)}catch{}E(),C.length&&le(C)})();function oe(){let e=h.value,n=_.value;ee.style.display=e===`once`?``:`none`,te.style.display=e===`interval`?``:`none`,e===`once`?n===`relative`?(v.textContent=t(`schedPanel.onceModeRelative`),g.type=`text`,g.placeholder=t(`schedPanel.relativeValuePlaceholder`)):(v.textContent=t(`schedPanel.onceModeAbsolute`),g.type=`datetime-local`,g.placeholder=``):e===`interval`?(v.textContent=t(`schedPanel.valueLabelInterval`),g.type=`text`,g.placeholder=t(`schedPanel.intervalValuePlaceholder`)):(v.textContent=t(`schedPanel.valueLabelCron`),g.type=`text`,g.placeholder=t(`schedPanel.cronValuePlaceholder`))}function se(e){e?(i.classList.add(`open`),$e(i),ce()):(ur(i),i.classList.remove(`open`),Ze(i))}r.addEventListener(`click`,()=>{se(!i.classList.contains(`open`))}),s.addEventListener(`click`,()=>se(!1)),h.addEventListener(`change`,oe),_.addEventListener(`change`,oe),document.getElementById(`scheduleModalCloseBtn`).addEventListener(`click`,pe),p.addEventListener(`click`,pe),m.addEventListener(`click`,me),l.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 ce(){try{let e=(await Hs({type:`SCHEDULED_TASK_LIST`}))?.tasks||[];le(e),a.clear(),e.forEach(e=>{e.lastStatus===`running`&&a.add(e.id)}),o()}catch(e){u.innerHTML=`<div class="sched-empty">${k(String(e?.message||e))}</div>`}}function D(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
206
  <div class="sched-run">
207
- <span class="dot ${A(e.status||``)}"></span>
208
- <span class="time">${A(Vs(e.startedAt))}</span>
209
- <span>${A(Us(e.status))}</span>
210
- <span class="dur">${A(Hs(e.durationMs))}</span>
211
- ${e.error?`<span class="err" title="${A(e.error)}">${A(e.error)}</span>`:``}
207
+ <span class="dot ${k(e.status||``)}"></span>
208
+ <span class="time">${k(Us(e.startedAt))}</span>
209
+ <span>${k(Gs(e.status))}</span>
210
+ <span class="dur">${k(Ws(e.durationMs))}</span>
211
+ ${e.error?`<span class="err" title="${k(e.error)}">${k(e.error)}</span>`:``}
212
212
  </div>
213
- `).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`
214
- <div class="sched-item" data-id="${A(e.id)}">
213
+ `).join(``)}</div>`}function le(e){C=Array.isArray(e)?e:[];let n=C.filter(e=>x===`enabled`?e.enabled!==!1:x===`disabled`?e.enabled===!1:!0).slice().sort((e,t)=>{let n=ie(t)-ie(e);return n===0?re(t.createdAt)-re(e.createdAt):n}),r=document.getElementById(`schedulePanelCount`);if(r&&(C.length?x===`all`?r.textContent=`(${C.length})`:r.textContent=`(${n.length}/${C.length})`:r.textContent=``),!C.length){u.innerHTML=`<div class="sched-empty">${t(`schedPanel.empty`)}</div>`;return}if(!n.length){u.innerHTML=`<div class="sched-empty">${t(`schedPanel.emptyFiltered`)}</div>`;return}u.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`
214
+ <div class="sched-item" data-id="${k(e.id)}">
215
215
  <div class="row1">
216
- <span class="name" title="${A(e.name)}">${A(e.name)}</span>
217
- ${Ks(e)}
216
+ <span class="name" title="${k(e.name)}">${k(e.name)}</span>
217
+ ${Js(e)}
218
218
  </div>
219
- ${e.description?`<div class="desc">${A(e.description)}</div>`:``}
220
- <div class="meta">${A(Gs(e))}</div>
221
- <div class="meta">${t(`schedPanel.nextRun`)}: ${A(Vs(e.nextRunAt))}</div>
219
+ ${e.description?`<div class="desc">${k(e.description)}</div>`:``}
220
+ <div class="meta">${k(qs(e))}</div>
221
+ <div class="meta">${t(`schedPanel.nextRun`)}: ${k(Us(e.nextRunAt))}</div>
222
222
  ${r}
223
- <div class="sched-history" data-history style="display:none;">${le(e.runHistory)}</div>
223
+ <div class="sched-history" data-history style="display:none;">${D(e.runHistory)}</div>
224
224
  <div class="actions">
225
225
  <button data-act="toggle" class="${e.enabled?`danger`:`primary`}">${e.enabled?t(`schedPanel.disable`):t(`schedPanel.enable`)}</button>
226
226
  <button data-act="run" class="primary">${t(`schedPanel.runNow`)}</button>
@@ -228,55 +228,55 @@ import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-5c8prpFJ.js"
228
228
  <button data-act="delete" class="danger">${t(`schedPanel.delete`)}</button>
229
229
  </div>
230
230
  </div>
231
- `}).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 Bs({type:`SCHEDULED_TASK_TOGGLE`,id:i,enabled:!e.enabled}),T()}else if(a===`run`){let e=await Bs({type:`SCHEDULED_TASK_RUN_NOW`,id:i});e?.success?(k(t(`schedPanel.runNowToast`),`success`),Js(e.sessionId),setTimeout(T,1500)):k(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 Bs({type:`SCHEDULED_TASK_DELETE`,id:i}),k(t(`schedPanel.deleted`),`success`),T())}});async function ue(){let e=await Bs({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?Ws(e.endAt):``;let n=document.getElementById(`schedFormSession`),r=`<option value="">${t(`schedPanel.sessionAuto`)}</option>`;try{let{list:t}=await pe(),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=A(t.title||t.id);r+=`<option value="${A(t.id)}" ${n}>${i}</option>`}}catch{}n.innerHTML=r,u.classList.add(`open`)}function fe(){u.classList.remove(`open`),_=null}async function me(){let e=document.getElementById(`schedFormName`).value.trim(),n=document.getElementById(`schedFormPrompt`).value.trim(),r=m.value,i=h.value.trim();if(!e){k(t(`schedPanel.nameRequired`),`warning`);return}if(!n){k(t(`schedPanel.promptRequired`),`warning`);return}if(!i){k(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 Bs({type:_?`SCHEDULED_TASK_UPDATE`:`SCHEDULED_TASK_CREATE`,task:_?{...c,id:_.id}:c});e?.success?(k(t(`schedPanel.saved`),`success`),fe(),T()):k(e?.error||t(`schedPanel.createFailed`),`error`)}catch(e){k(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(qs,600))}),chrome.runtime.onMessage.addListener(e=>{e.type===`SCHEDULED_TASKS_CHANGED`&&T().catch(()=>{})}),se(),ce(!1),T().catch(()=>{})}var Xs=`todoStatsLog`,Zs=7;function Qs(e){return String(e).padStart(2,`0`)}function $s(e=Date.now()){let t=new Date(e);return`${t.getFullYear()}-${Qs(t.getMonth()+1)}-${Qs(t.getDate())}`}function ec(e,t){let n=new Date(e);return n.setDate(n.getDate()+t),n.getTime()}function tc(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 nc(e,t=Date.now()){let n=$s(ec(t,-90)),r={};for(let[t,i]of Object.entries(e&&typeof e==`object`?e:{}))t>=n&&(r[t]=i);return r}function rc(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 ic(e,t){let n=rc(e,$s(t)).done>0?t:ec(t,-1),r=0;for(;r<=90&&!(rc(e,$s(n)).done<=0);)r+=1,n=ec(n,-1);return r}function ac(e,t,n=Date.now()){let r=Array.isArray(e)?e.map(We):[],{stats:i}=Ve(r),a=t&&typeof t==`object`?t:{},o=[];for(let e=Zs-1;e>=0;--e){let t=$s(ec(n,-e));o.push({date:t,...rc(a,t)})}return{total:i.total,done:i.done,doing:i.doing,pending:i.pending,overdue:r.filter(e=>Oe(e,n)).length,high:r.filter(e=>e.status!==D.DONE&&e.priority===Be.HIGH).length,doneRate:i.total?Math.round(i.done/i.total*100):0,today:rc(a,$s(n)),week:o,streak:ic(a,n)}}var oc=Promise.resolve();async function sc(){try{if(typeof chrome>`u`||!chrome.storage?.local?.get)return{};let e=await chrome.storage.local.get([Xs]),t=e&&e.todoStatsLog;return t&&typeof t==`object`?t:{}}catch(e){return r.warn(`[Todo] load stats log failed:`,e),{}}}async function cc(e){typeof chrome>`u`||!chrome.storage?.local?.set||await chrome.storage.local.set({[Xs]:e})}function lc(e,t,n=Date.now()){let i=oc.then(async()=>{let r=nc(tc(await sc(),$s(n),e,t));return await cc(r),r});return oc=i.then(()=>void 0,()=>void 0),i.catch(e=>(r.warn(`[Todo] record stat failed:`,e),null))}var uc=new Set,dc=Promise.resolve();function fc(e){let t=dc.then(e);return dc=t.then(()=>void 0,()=>void 0),t}function pc(e){return typeof e==`function`?(uc.add(e),()=>uc.delete(e)):()=>{}}function I(){for(let e of uc)try{e()}catch(e){r.warn(`[Todo] listener failed:`,e)}}async function mc(){try{v.todos=(await C()||[]).map(We).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=[]}I()}function hc(){return Ve(v.todos)}function gc(e){return v.todos.find(t=>t.id===e)||null}function _c(e){v.todos=v.todos.map(t=>t.id===e.id?e:t)}async function vc(e,t={}){let n=String(e||``).trim();if(!n)return null;let i=Ie(n,t);return i.order=ke(v.todos),v.todos=[...v.todos,i],await fc(()=>ie(i)).catch(e=>(r.error(`[Todo] add failed:`,e),!1))?(I(),await lc(`added`,1,i.createdAt),i):(v.todos=v.todos.filter(e=>e.id!==i.id),I(),null)}async function yc(e,t={}){let n=gc(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=Te(t.priority)),t.link!==void 0&&(i.link=Ge(t.link).url),_c(i),await fc(()=>ie(i)).catch(e=>(r.error(`[Todo] update failed:`,e),!1))?(I(),!0):(_c(n),I(),!1)}async function bc(e,t){let n=gc(e);if(!n||!Le(t))return!1;if(n.status===t)return!0;let i=Date.now(),a={...n,status:t,updatedAt:i};return t===D.DONE?(a.completedAt=i,n.status!==D.DONE&&(a.prevStatus=n.status)):n.status===D.DONE&&(a.completedAt=null,a.prevStatus=null),_c(a),await fc(()=>ie(a)).catch(e=>(r.error(`[Todo] set status failed:`,e),!1))?(I(),t===D.DONE&&n.status!==D.DONE?await lc(`done`,1,a.completedAt):n.status===D.DONE&&t!==D.DONE&&await lc(`done`,-1,n.completedAt),!0):(_c(n),I(),!1)}function xc(e){let t=gc(e);return t?bc(e,He(t.status)):Promise.resolve(!1)}function Sc(e){let t=gc(e);return!t||t.status!==D.DONE?Promise.resolve(!1):bc(e,Ue(t))}function Cc(e,t){return yc(e,{priority:Te(t)})}async function wc(e,t){if(!gc(e))return{ok:!1,reason:`missing`};let n=Ge(t);if(!n.valid)return{ok:!1,reason:`invalid`};let r=await yc(e,{link:n.url});return{ok:r,reason:r?``:`save`}}async function Tc(e){let t=gc(e);return t?(v.todos=v.todos.filter(t=>t.id!==e),await fc(()=>w(e)).catch(e=>(r.error(`[Todo] delete failed:`,e),!1))?(I(),!0):(v.todos=[...v.todos,t],I(),!1)):!1}async function Ec(e,t){let{active:n}=hc();if(e===t)return!0;if(e<0||e>=n.length)return!1;let i=_e(he(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 fc(()=>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),I(),!1}return I(),!0}async function Dc(){let{done:e}=hc();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 fc(()=>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],I(),!1}return I(),!0}async function Oc(e,t=`merge`){if(t===`replace`)return kc(e);let n=Ae(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 fc(()=>x(n.addedItems)).catch(e=>(r.error(`[Todo] import merge failed:`,e),!1))?(I(),{ok:!0,added:n.addedItems.length,skipped:n.skipped}):(v.todos=i.filter(e=>!a.has(e.id)),I(),{ok:!1,added:0,skipped:n.skipped})}async function kc(e){let{addedItems:t,skipped:n}=Ae([],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 fc(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))?(I(),{ok:!0,added:t.length,skipped:n}):(v.todos=i,I(),{ok:!1,added:0,skipped:n})}var Ac=[`all`,`active`,`done`],jc={json:{ext:`json`,type:`application/json;charset=utf-8`},md:{ext:`md`,type:`text/markdown;charset=utf-8`}};function Mc(e){return e===`md`?`md`:`json`}function Nc(e){return String(e).padStart(2,`0`)}function Pc(e){let t=new Date(e);return`${t.getFullYear()}-${Nc(t.getMonth()+1)}-${Nc(t.getDate())}`}function Fc(e,t,n=Date.now()){let r=Ac.includes(e)?e:`all`;return`ai-helper-todos${r===`all`?``:`-${r}`}-${Pc(n)}.${jc[Mc(t)].ext}`}function Ic(e,t={}){let n=Ac.includes(t.scope)?t.scope:`all`,r=Mc(t.format),i=t.now||Date.now(),a=r===`md`?we(e,{scope:n,now:i}):JSON.stringify(je(e,{scope:n,now:i}),null,2);return{filename:Fc(n,r,i),blob:new Blob([a],{type:jc[r].type})}}function Lc(e,t={}){let{filename:n,blob:r}=Ic(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 Rc(){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 zc(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 xe(n)}var Bc=`<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>`,Vc=[`all`,`active`,`done`],Hc=[`json`,`md`],Uc=[`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 Wc(e){return`<div class="todo-io-header">
232
- <span class="todo-io-title">${A(e)}</span>
231
+ `}).join(``)}u.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 Hs({type:`SCHEDULED_TASK_TOGGLE`,id:i,enabled:!e.enabled}),ce()}else if(a===`run`){let e=await Hs({type:`SCHEDULED_TASK_RUN_NOW`,id:i});e?.success?(A(t(`schedPanel.runNowToast`),`success`),Xs(e.sessionId),setTimeout(ce,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 Hs({type:`SCHEDULED_TASK_DELETE`,id:i}),A(t(`schedPanel.deleted`),`success`),ce())}});async function ue(){let e=await Hs({type:`SCHEDULED_TASK_LIST`}),t={};return(e?.tasks||[]).forEach(e=>{t[e.id]=e}),t}async function de(e){b=e||null,f.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||``,h.value=e?.schedule?.type||`interval`,_.value=e?.schedule?.onceMode||`relative`,oe(),g.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,d.classList.add(`open`)}function pe(){d.classList.remove(`open`),b=null}async function me(){let e=document.getElementById(`schedFormName`).value.trim(),n=document.getElementById(`schedFormPrompt`).value.trim(),r=h.value,i=g.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:_.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:b?b.enabled:!0};try{let e=await Hs({type:b?`SCHEDULED_TASK_UPDATE`:`SCHEDULED_TASK_CREATE`,task:b?{...c,id:b.id}:c});e?.success?(A(t(`schedPanel.saved`),`success`),pe(),ce()):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`)&&ce().catch(()=>{}),e.sessionId&&e.sessionId===y.activeSessionId&&setTimeout(Ys,600))}),chrome.runtime.onMessage.addListener(e=>{e.type===`SCHEDULED_TASKS_CHANGED`&&ce().catch(()=>{})}),oe(),se(!1),ce().catch(()=>{})}var Qs=`todoStatsLog`,$s=7;function ec(e){return String(e).padStart(2,`0`)}function tc(e=Date.now()){let t=new Date(e);return`${t.getFullYear()}-${ec(t.getMonth()+1)}-${ec(t.getDate())}`}function nc(e,t){let n=new Date(e);return n.setDate(n.getDate()+t),n.getTime()}function rc(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 ic(e,t=Date.now()){let n=tc(nc(t,-90)),r={};for(let[t,i]of Object.entries(e&&typeof e==`object`?e:{}))t>=n&&(r[t]=i);return r}function ac(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 oc(e,t){let n=ac(e,tc(t)).done>0?t:nc(t,-1),r=0;for(;r<=90&&!(ac(e,tc(n)).done<=0);)r+=1,n=nc(n,-1);return r}function sc(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=$s-1;e>=0;--e){let t=tc(nc(n,-e));o.push({date:t,...ac(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:ac(a,tc(n)),week:o,streak:oc(a,n)}}var cc=Promise.resolve();async function lc(){try{if(typeof chrome>`u`||!chrome.storage?.local?.get)return{};let e=await chrome.storage.local.get([Qs]),t=e&&e.todoStatsLog;return t&&typeof t==`object`?t:{}}catch(e){return r.warn(`[Todo] load stats log failed:`,e),{}}}async function uc(e){typeof chrome>`u`||!chrome.storage?.local?.set||await chrome.storage.local.set({[Qs]:e})}function dc(e,t,n=Date.now()){let i=cc.then(async()=>{let r=ic(rc(await lc(),tc(n),e,t));return await uc(r),r});return cc=i.then(()=>void 0,()=>void 0),i.catch(e=>(r.warn(`[Todo] record stat failed:`,e),null))}var fc=new Set,pc=Promise.resolve();function mc(e){let t=pc.then(e);return pc=t.then(()=>void 0,()=>void 0),t}function hc(e){return typeof e==`function`?(fc.add(e),()=>fc.delete(e)):()=>{}}function L(){for(let e of fc)try{e()}catch(e){r.warn(`[Todo] listener failed:`,e)}}async function gc(){try{y.todos=(await T()||[]).map(Ue).filter(e=>e.id&&e.title),r.debug(`[Todo] loaded todos:`,y.todos.length)}catch(e){r.error(`[Todo] load todos failed:`,e),y.todos=[]}L()}function _c(){return Be(y.todos)}function vc(e){return y.todos.find(t=>t.id===e)||null}function yc(e){y.todos=y.todos.map(t=>t.id===e.id?e:t)}async function bc(e,t={}){let n=String(e||``).trim();if(!n)return null;let i=Fe(n,t);return i.order=Oe(y.todos),y.todos=[...y.todos,i],await mc(()=>C(i)).catch(e=>(r.error(`[Todo] add failed:`,e),!1))?(L(),await dc(`added`,1,i.createdAt),i):(y.todos=y.todos.filter(e=>e.id!==i.id),L(),null)}async function xc(e,t={}){let n=vc(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),yc(i),await mc(()=>C(i)).catch(e=>(r.error(`[Todo] update failed:`,e),!1))?(L(),!0):(yc(n),L(),!1)}async function Sc(e,t){let n=vc(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),yc(a),await mc(()=>C(a)).catch(e=>(r.error(`[Todo] set status failed:`,e),!1))?(L(),t===O.DONE&&n.status!==O.DONE?await dc(`done`,1,a.completedAt):n.status===O.DONE&&t!==O.DONE&&await dc(`done`,-1,n.completedAt),!0):(yc(n),L(),!1)}function Cc(e){let t=vc(e);return t?Sc(e,Ve(t.status)):Promise.resolve(!1)}function wc(e){let t=vc(e);return!t||t.status!==O.DONE?Promise.resolve(!1):Sc(e,He(t))}function Tc(e,t){return xc(e,{priority:we(t)})}async function Ec(e,t){if(!vc(e))return{ok:!1,reason:`missing`};let n=We(t);if(!n.valid)return{ok:!1,reason:`invalid`};let r=await xc(e,{link:n.url});return{ok:r,reason:r?``:`save`}}async function Dc(e){let t=vc(e);return t?(y.todos=y.todos.filter(t=>t.id!==e),await mc(()=>E(e)).catch(e=>(r.error(`[Todo] delete failed:`,e),!1))?(L(),!0):(y.todos=[...y.todos,t],L(),!1)):!1}async function Oc(e,t){let{active:n}=_c();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=y.todos;if(y.todos=y.todos.map(e=>a.get(e.id)||e),!await mc(()=>S(i)).catch(e=>(r.error(`[Todo] reorder failed:`,e),!1))){let e=new Map(o.map(e=>[e.id,e.order]));return y.todos=y.todos.map(t=>e.has(t.id)?{...t,order:e.get(t.id)}:t),L(),!1}return L(),!0}async function kc(){let{done:e}=_c();if(e.length===0)return!0;let t=e.map(e=>e.id),n=y.todos;if(y.todos=y.todos.filter(e=>!t.includes(e.id)),!await mc(()=>d(t)).catch(e=>(r.error(`[Todo] clear completed failed:`,e),!1))){let e=new Set(y.todos.map(e=>e.id)),r=n.filter(n=>t.includes(n.id)&&!e.has(n.id));return y.todos=[...y.todos,...r],L(),!1}return L(),!0}async function Ac(e,t=`merge`){if(t===`replace`)return jc(e);let n=ke(y.todos,e);if(n.addedItems.length===0)return{ok:!0,added:0,skipped:n.skipped};let i=y.todos;y.todos=n.todos;let a=new Set(n.addedItems.map(e=>e.id));return await mc(()=>S(n.addedItems)).catch(e=>(r.error(`[Todo] import merge failed:`,e),!1))?(L(),{ok:!0,added:n.addedItems.length,skipped:n.skipped}):(y.todos=i.filter(e=>!a.has(e.id)),L(),{ok:!1,added:0,skipped:n.skipped})}async function jc(e){let{addedItems:t,skipped:n}=ke([],e);if(t.length===0)return{ok:!1,added:0,skipped:n,reason:`empty`};let i=y.todos,a=i.map(e=>e.id);return y.todos=t,await mc(async()=>a.length>0&&!await d(a).catch(e=>(r.error(`[Todo] replace delete failed:`,e),!1))?!1:await S(t).catch(e=>(r.error(`[Todo] replace write failed:`,e),!1))?!0:(a.length>0&&await S(i).catch(()=>!1),!1)).catch(e=>(r.error(`[Todo] replace failed:`,e),!1))?(L(),{ok:!0,added:t.length,skipped:n}):(y.todos=i,L(),{ok:!1,added:0,skipped:n})}var Mc=[`all`,`active`,`done`],Nc={json:{ext:`json`,type:`application/json;charset=utf-8`},md:{ext:`md`,type:`text/markdown;charset=utf-8`}};function Pc(e){return e===`md`?`md`:`json`}function Fc(e){return String(e).padStart(2,`0`)}function Ic(e){let t=new Date(e);return`${t.getFullYear()}-${Fc(t.getMonth()+1)}-${Fc(t.getDate())}`}function Lc(e,t,n=Date.now()){let r=Mc.includes(e)?e:`all`;return`ai-helper-todos${r===`all`?``:`-${r}`}-${Ic(n)}.${Nc[Pc(t)].ext}`}function Rc(e,t={}){let n=Mc.includes(t.scope)?t.scope:`all`,r=Pc(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:Lc(n,r,i),blob:new Blob([a],{type:Nc[r].type})}}function zc(e,t={}){let{filename:n,blob:r}=Rc(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 Bc(){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 Vc(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 Hc=`<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>`,Uc=[`all`,`active`,`done`],Wc=[`json`,`md`],Gc=[`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
+ <span class="todo-io-title">${k(e)}</span>
233
233
  <button type="button" class="todo-io-close" data-io-action="cancel"
234
- title="${O(t(`todoIo.close`))}" aria-label="${O(t(`todoIo.close`))}">${Bc}</button>
235
- </div>`}function Gc(e,n){return`<div class="todo-io-actions">
236
- <button type="button" class="todo-io-btn" data-io-action="cancel">${A(t(`todoIo.cancel`))}</button>
237
- <button type="button" class="todo-io-btn primary" data-io-action="confirm"${n?` disabled`:``}>${A(e)}</button>
238
- </div>`}function Kc({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
- <input type="radio" name="todoIo-${O(e)}" value="${O(t)}"
240
- data-io-field="${O(e)}"${i?` checked`:``} />
234
+ title="${j(t(`todoIo.close`))}" aria-label="${j(t(`todoIo.close`))}">${Hc}</button>
235
+ </div>`}function qc(e,n){return`<div class="todo-io-actions">
236
+ <button type="button" class="todo-io-btn" data-io-action="cancel">${k(t(`todoIo.cancel`))}</button>
237
+ <button type="button" class="todo-io-btn primary" data-io-action="confirm"${n?` disabled`:``}>${k(e)}</button>
238
+ </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
+ <input type="radio" name="todoIo-${j(e)}" value="${j(t)}"
240
+ data-io-field="${j(e)}"${i?` checked`:``} />
241
241
  <span class="todo-io-option-main">
242
- <span class="todo-io-option-label">${A(n)}</span>
243
- ${r?`<span class="todo-io-option-hint">${A(r)}</span>`:``}
242
+ <span class="todo-io-option-label">${k(n)}</span>
243
+ ${r?`<span class="todo-io-option-hint">${k(r)}</span>`:``}
244
244
  </span>
245
245
  ${s}
246
- </label>`}function qc(e,n={}){let r=Vc.includes(e?.scope)?e.scope:`all`,i=Hc.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])=>Kc({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])=>Kc({field:`format`,value:e,label:t,checked:e===i})).join(``);return`<div class="todo-io-card" role="dialog" aria-modal="true" tabindex="-1"
247
- aria-label="${O(t(`todoIo.exportTitle`))}">
248
- ${Wc(t(`todoIo.exportTitle`))}
246
+ </label>`}function Yc(e,n={}){let r=Uc.includes(e?.scope)?e.scope:`all`,i=Wc.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
+ aria-label="${j(t(`todoIo.exportTitle`))}">
248
+ ${Kc(t(`todoIo.exportTitle`))}
249
249
  <div class="todo-io-body">
250
250
  <div class="todo-io-group">
251
- <div class="todo-io-group-label">${A(t(`todoIo.rangeLabel`))}</div>
252
- <div class="todo-io-options" role="radiogroup" aria-label="${O(t(`todoIo.rangeLabel`))}">${o}</div>
251
+ <div class="todo-io-group-label">${k(t(`todoIo.rangeLabel`))}</div>
252
+ <div class="todo-io-options" role="radiogroup" aria-label="${j(t(`todoIo.rangeLabel`))}">${o}</div>
253
253
  </div>
254
254
  <div class="todo-io-group">
255
- <div class="todo-io-group-label">${A(t(`todoIo.formatLabel`))}</div>
256
- <div class="todo-io-options" role="radiogroup" aria-label="${O(t(`todoIo.formatLabel`))}">${s}</div>
255
+ <div class="todo-io-group-label">${k(t(`todoIo.formatLabel`))}</div>
256
+ <div class="todo-io-options" role="radiogroup" aria-label="${j(t(`todoIo.formatLabel`))}">${s}</div>
257
257
  </div>
258
- <p class="todo-io-hint${a?` show`:``}" data-io-hint>${A(t(`todoIo.emptyRange`))}</p>
258
+ <p class="todo-io-hint${a?` show`:``}" data-io-hint>${k(t(`todoIo.emptyRange`))}</p>
259
259
  </div>
260
- ${Gc(t(`todoIo.exportAction`),a)}
261
- </div>`}function Jc(e,n={}){let r=Uc.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])=>Kc({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"
262
- aria-label="${O(t(`todoIo.importTitle`))}">
263
- ${Wc(t(`todoIo.importTitle`))}
260
+ ${qc(t(`todoIo.exportAction`),a)}
261
+ </div>`}function Xc(e,n={}){let r=Gc.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"
262
+ aria-label="${j(t(`todoIo.importTitle`))}">
263
+ ${Kc(t(`todoIo.importTitle`))}
264
264
  <div class="todo-io-body">
265
- <p class="todo-io-summary">${A(t(`todoIo.importSummary`,{count:i,existing:a}))}</p>
265
+ <p class="todo-io-summary">${k(t(`todoIo.importSummary`,{count:i,existing:a}))}</p>
266
266
  <div class="todo-io-group">
267
- <div class="todo-io-group-label">${A(t(`todoIo.modeLabel`))}</div>
268
- <div class="todo-io-options" role="radiogroup" aria-label="${O(t(`todoIo.modeLabel`))}">${o}</div>
267
+ <div class="todo-io-group-label">${k(t(`todoIo.modeLabel`))}</div>
268
+ <div class="todo-io-options" role="radiogroup" aria-label="${j(t(`todoIo.modeLabel`))}">${o}</div>
269
269
  </div>
270
- <p class="todo-io-warn${r===`replace`?` show`:``}" data-io-warn>${A(t(`todoIo.replaceWarn`,{count:i}))}</p>
270
+ <p class="todo-io-warn${r===`replace`?` show`:``}" data-io-warn>${k(t(`todoIo.replaceWarn`,{count:i}))}</p>
271
271
  </div>
272
- ${Gc(t(`todoIo.importAction`),!1)}
273
- </div>`}var L=null,R=null,Yc=null;function Xc(){return L||(L=document.createElement(`div`),L.className=`todo-io-overlay`,L.id=`todoIoOverlay`,L.addEventListener(`click`,e=>{if(e.target===L){el(null);return}let t=e.target.closest?.(`[data-io-action]`);t?.dataset.ioAction===`cancel`?el(null):t?.dataset.ioAction===`confirm`&&$c()}),L.addEventListener(`change`,e=>{if(!R)return;let t=e.target.closest?.(`input[data-io-field]`);t&&(R.state[t.dataset.ioField]=t.value,Qc())}),document.body.appendChild(L),L)}function Zc(){if(!R)return;let e=Xc();e.innerHTML=R.kind===`export`?qc(R.state,R.counts):Jc(R.state,R.info),Qc()}function Qc(){if(!(!R||!L)){if(R.kind===`export`){let e=!Number(R.counts[R.state.scope]||0),t=L.querySelector(`[data-io-action="confirm"]`);t&&(t.disabled=e),L.querySelector(`[data-io-hint]`)?.classList.toggle(`show`,e);return}L.querySelector(`[data-io-warn]`)?.classList.toggle(`show`,R.state.mode===`replace`)}}function $c(){if(R){if(R.kind===`export`){if(!Number(R.counts[R.state.scope]||0))return;el({scope:R.state.scope,format:R.state.format});return}el(R.state.mode)}}function el(e){if(!R)return;let{resolve:t}=R;R=null,L?.classList.remove(`show`),nl(),t(e)}function tl(){Yc||(Yc=e=>{e.key===`Escape`&&(e.stopPropagation(),el(null))},document.addEventListener(`keydown`,Yc))}function nl(){Yc&&=(document.removeEventListener(`keydown`,Yc),null)}function rl(e,t,n){return R&&el(null),new Promise(r=>{R={kind:e,state:t,...n,resolve:r},Zc(),L.classList.add(`show`),tl(),L.querySelector(`.todo-io-card`)?.focus()})}function il({counts:e={},scope:t=`all`,format:n=`json`}={}){return rl(`export`,{scope:Vc.includes(t)?t:`all`,format:Hc.includes(n)?n:`json`},{counts:e})}function al({count:e=0,existing:t=0,mode:n=`merge`}={}){return rl(`import`,{mode:Uc.includes(n)?n:`merge`},{info:{count:e,existing:t}})}o(()=>{R&&(Zc(),L.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 ol={zh:[`日`,`一`,`二`,`三`,`四`,`五`,`六`],en:[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`]},sl=6;function cl(e){let[t,n,r]=String(e||``).split(`-`).map(Number);return!t||!n||!r?null:new Date(t,n-1,r)}function ll(e){let t=cl(e);return t?a()===`en`?`${t.toLocaleString(`en-US`,{month:`short`})} ${t.getDate()}`:`${t.getMonth()+1}月${t.getDate()}日`:String(e||``)}function ul(e){let t=cl(e);return t?(ol[a()]||ol.zh)[t.getDay()]:``}function dl(e,t,n){return`<div class="todo-stats-tile${n?` ${n}`:``}">
272
+ ${qc(t(`todoIo.importAction`),!1)}
273
+ </div>`}var R=null,z=null,Zc=null;function Qc(){return R||(R=document.createElement(`div`),R.className=`todo-io-overlay`,R.id=`todoIoOverlay`,R.addEventListener(`click`,e=>{if(e.target===R){nl(null);return}let t=e.target.closest?.(`[data-io-action]`);t?.dataset.ioAction===`cancel`?nl(null):t?.dataset.ioAction===`confirm`&&tl()}),R.addEventListener(`change`,e=>{if(!z)return;let t=e.target.closest?.(`input[data-io-field]`);t&&(z.state[t.dataset.ioField]=t.value,el())}),document.body.appendChild(R),R)}function $c(){if(!z)return;let e=Qc();e.innerHTML=z.kind===`export`?Yc(z.state,z.counts):Xc(z.state,z.info),el()}function el(){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 tl(){if(z){if(z.kind===`export`){if(!Number(z.counts[z.state.scope]||0))return;nl({scope:z.state.scope,format:z.state.format});return}nl(z.state.mode)}}function nl(e){if(!z)return;let{resolve:t}=z;z=null,R?.classList.remove(`show`),il(),t(e)}function rl(){Zc||(Zc=e=>{e.key===`Escape`&&(e.stopPropagation(),nl(null))},document.addEventListener(`keydown`,Zc))}function il(){Zc&&=(document.removeEventListener(`keydown`,Zc),null)}function al(e,t,n){return z&&nl(null),new Promise(r=>{z={kind:e,state:t,...n,resolve:r},$c(),R.classList.add(`show`),rl(),R.querySelector(`.todo-io-card`)?.focus()})}function ol({counts:e={},scope:t=`all`,format:n=`json`}={}){return al(`export`,{scope:Uc.includes(t)?t:`all`,format:Wc.includes(n)?n:`json`},{counts:e})}function sl({count:e=0,existing:t=0,mode:n=`merge`}={}){return al(`import`,{mode:Gc.includes(n)?n:`merge`},{info:{count:e,existing:t}})}o(()=>{z&&($c(),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 cl={zh:[`日`,`一`,`二`,`三`,`四`,`五`,`六`],en:[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`]},ll=6;function ul(e){let[t,n,r]=String(e||``).split(`-`).map(Number);return!t||!n||!r?null:new Date(t,n-1,r)}function dl(e){let t=ul(e);return t?a()===`en`?`${t.toLocaleString(`en-US`,{month:`short`})} ${t.getDate()}`:`${t.getMonth()+1}月${t.getDate()}日`:String(e||``)}function fl(e){let t=ul(e);return t?(cl[a()]||cl.zh)[t.getDay()]:``}function pl(e,t,n){return`<div class="todo-stats-tile${n?` ${n}`:``}">
274
274
  <span class="todo-stats-tile-value">${e}</span>
275
275
  <span class="todo-stats-tile-label">${t}</span>
276
- </div>`}function fl(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(sl,Math.round(r/n*100));return`<div class="todo-stats-bar-col" title="${t(`todoStats.dayTitle`,{date:ll(e.date),done:r,added:e.added||0})}">
276
+ </div>`}function ml(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(ll,Math.round(r/n*100));return`<div class="todo-stats-bar-col" title="${t(`todoStats.dayTitle`,{date:dl(e.date),done:r,added:e.added||0})}">
277
277
  <span class="todo-stats-bar" style="height:${i}%"></span>
278
- <span class="todo-stats-bar-label">${ul(e.date)}</span>
279
- </div>`}).join(``)}</div>`}function pl(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">
278
+ <span class="todo-stats-bar-label">${fl(e.date)}</span>
279
+ </div>`}).join(``)}</div>`}function hl(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">
280
280
  <div class="todo-stats-rate">
281
281
  <span class="todo-stats-rate-value">${i}%</span>
282
282
  <span class="todo-stats-rate-label">${t(`todoStats.rate`)}</span>
@@ -285,41 +285,41 @@ import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-5c8prpFJ.js"
285
285
  <div class="todo-stats-track"><i style="width:${i}%"></i></div>
286
286
  </div>
287
287
  <div class="todo-stats-tiles">
288
- ${dl(n.pending||0,t(`todoStats.pending`))}
289
- ${dl(n.doing||0,t(`todoStats.doing`),`doing`)}
290
- ${dl(n.done||0,t(`todoStats.done`),`done`)}
291
- ${dl(n.overdue||0,t(`todoStats.overdue`),n.overdue?`alert`:``)}
288
+ ${pl(n.pending||0,t(`todoStats.pending`))}
289
+ ${pl(n.doing||0,t(`todoStats.doing`),`doing`)}
290
+ ${pl(n.done||0,t(`todoStats.done`),`done`)}
291
+ ${pl(n.overdue||0,t(`todoStats.overdue`),n.overdue?`alert`:``)}
292
292
  </div>
293
293
  <div class="todo-stats-section">
294
294
  <div class="todo-stats-section-title">${t(`todoStats.week`)}</div>
295
- ${fl(o)}
295
+ ${ml(o)}
296
296
  </div>
297
297
  <div class="todo-stats-facts">
298
298
  <span>${t(`todoStats.todayAdded`,{n:a.added||0})}</span>
299
299
  <span>${t(`todoStats.todayDone`,{n:a.done||0})}</span>
300
300
  <span>${t(`todoStats.streak`,{n:n.streak||0})}</span>
301
301
  <span>${t(`todoStats.highCount`,{n:n.high||0})}</span>
302
- </div>`}var ml=`<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>`,hl=null,gl=null;function _l(){return hl||(hl=document.createElement(`div`),hl.className=`todo-stats-overlay`,hl.id=`todoStatsOverlay`,hl.addEventListener(`click`,e=>{(e.target===hl||e.target.closest?.(`[data-action="close-stats"]`))&&xl()}),document.body.appendChild(hl),hl)}function vl(e){let n=_l();n.innerHTML=`
303
- <div class="todo-stats-card" role="dialog" aria-modal="true" aria-label="${O(t(`todoStats.title`))}">
302
+ </div>`}var gl=`<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>`,_l=null,vl=null;function yl(){return _l||(_l=document.createElement(`div`),_l.className=`todo-stats-overlay`,_l.id=`todoStatsOverlay`,_l.addEventListener(`click`,e=>{(e.target===_l||e.target.closest?.(`[data-action="close-stats"]`))&&Cl()}),document.body.appendChild(_l),_l)}function bl(e){let n=yl();n.innerHTML=`
303
+ <div class="todo-stats-card" role="dialog" aria-modal="true" aria-label="${j(t(`todoStats.title`))}">
304
304
  <div class="todo-stats-header">
305
305
  <span class="todo-stats-title">${t(`todoStats.title`)}</span>
306
306
  <button type="button" class="todo-stats-close" data-action="close-stats"
307
- title="${O(t(`todoStats.close`))}" aria-label="${O(t(`todoStats.close`))}">${ml}</button>
307
+ title="${j(t(`todoStats.close`))}" aria-label="${j(t(`todoStats.close`))}">${gl}</button>
308
308
  </div>
309
- <div class="todo-stats-body">${pl(e)}</div>
310
- </div>`}async function yl(){let e=await sc(),{active:t,done:n}=hc();vl(ac([...t,...n],e))}async function bl(){await yl();let e=_l();e.classList.add(`show`),gl||(gl=e=>{e.key===`Escape`&&(e.stopPropagation(),xl())},document.addEventListener(`keydown`,gl)),e.querySelector(`.todo-stats-close`)?.focus()}function xl(){hl&&(hl.classList.remove(`show`),gl&&=(document.removeEventListener(`keydown`,gl),null))}o(()=>{hl?.classList.contains(`show`)&&yl()}),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:`待办统计`,fullscreen:`全屏`,exitFullscreen:`退出全屏`}}),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`,fullscreen:`Fullscreen`,exitFullscreen:`Exit fullscreen`}});var Sl=`.input-container`,Cl=160,wl=8,Tl=108,El=220,Dl=6e3,z={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>`,expand:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M8 3H5a2 2 0 0 0-2 2v3"/><path d="M16 3h3a2 2 0 0 1 2 2v3"/><path d="M8 21H5a2 2 0 0 1-2-2v-3"/><path d="M16 21h3a2 2 0 0 0 2-2v-3"/></svg>`,collapse:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 8h3a2 2 0 0 0 2-2V3"/><path d="M21 8h-3a2 2 0 0 1-2-2V3"/><path d="M3 16h3a2 2 0 0 1 2 2v3"/><path d="M21 16h-3a2 2 0 0 0-2 2v3"/></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>`},B=null,V=null,H=null,Ol=null,kl=null,Al=null,jl=null,Ml=null,Nl=null,Pl=null,Fl=null,Il=null,Ll=`active`,Rl=null,U=null,zl=null,W=null,Bl=new Set,Vl=null,Hl=!1,Ul=null,Wl=null,Gl=null,Kl=null,ql=0,Jl=null,Yl=!1,Xl=!1,Zl=new Map,Ql=[`todo-edit-input`,`todo-note-input`,`todo-due-input`,`todo-link-input`],$l={"todo-edit-input":`title`,"todo-note-input":`note`,"todo-due-input":`due`,"todo-link-input":`link`};function eu(){Hl||(Hl=!0,B=document.createElement(`div`),B.className=`todo-panel-container`,B.id=`todoPanelContainer`,B.innerHTML=`
309
+ <div class="todo-stats-body">${hl(e)}</div>
310
+ </div>`}async function xl(){let e=await lc(),{active:t,done:n}=_c();bl(sc([...t,...n],e))}async function Sl(){await xl();let e=yl();e.classList.add(`show`),vl||(vl=e=>{e.key===`Escape`&&(e.stopPropagation(),Cl())},document.addEventListener(`keydown`,vl)),e.querySelector(`.todo-stats-close`)?.focus()}function Cl(){_l&&(_l.classList.remove(`show`),vl&&=(document.removeEventListener(`keydown`,vl),null))}o(()=>{_l?.classList.contains(`show`)&&xl()}),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:`待办统计`,fullscreen:`全屏`,exitFullscreen:`退出全屏`}}),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`,fullscreen:`Fullscreen`,exitFullscreen:`Exit fullscreen`}});var wl=`.input-container`,Tl=160,El=8,Dl=108,Ol=220,kl=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>`,expand:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M8 3H5a2 2 0 0 0-2 2v3"/><path d="M16 3h3a2 2 0 0 1 2 2v3"/><path d="M8 21H5a2 2 0 0 1-2-2v-3"/><path d="M16 21h3a2 2 0 0 0 2-2v-3"/></svg>`,collapse:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 8h3a2 2 0 0 0 2-2V3"/><path d="M21 8h-3a2 2 0 0 1-2-2V3"/><path d="M3 16h3a2 2 0 0 1 2 2v3"/><path d="M21 16h-3a2 2 0 0 0-2 2v3"/></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,Al=null,jl=null,Ml=null,Nl=null,Pl=null,Fl=null,Il=null,Ll=null,Rl=null,zl=`active`,Bl=null,W=null,Vl=null,G=null,Hl=new Set,Ul=null,Wl=!1,Gl=null,Kl=null,ql=null,Jl=null,Yl=0,Xl=null,Zl=!1,Ql=!1,$l=new Map,eu=[`todo-edit-input`,`todo-note-input`,`todo-due-input`,`todo-link-input`],tu={"todo-edit-input":`title`,"todo-note-input":`note`,"todo-due-input":`due`,"todo-link-input":`link`};function nu(){Wl||(Wl=!0,V=document.createElement(`div`),V.className=`todo-panel-container`,V.id=`todoPanelContainer`,V.innerHTML=`
311
311
  <button class="todo-panel-toggle" id="todoPanelToggle" data-i18n-title="todo.toggleTitle" data-i18n-aria-label="todo.toggleTitle">
312
312
  <span class="todo-badge" id="todoBadge" style="display:none;"></span>
313
- ${z.listCheck}
313
+ ${B.listCheck}
314
314
  </button>
315
315
  <div class="todo-panel" id="todoPanel">
316
316
  <div class="todo-panel-header">
317
- <span class="todo-panel-icon">${z.listCheck}</span>
317
+ <span class="todo-panel-icon">${B.listCheck}</span>
318
318
  <span class="todo-panel-title" data-i18n="todo.title"></span>
319
319
  <div class="todo-panel-actions">
320
- <button class="todo-icon-btn todo-fullscreen-btn" data-action="toggle-fullscreen">${z.expand}</button>
321
- <button class="todo-icon-btn" data-action="header-more" data-i18n-title="todo.headerMore" data-i18n-aria-label="todo.headerMore">${z.more}</button>
322
- <button class="todo-icon-btn" data-action="close" data-i18n-title="common.close" data-i18n-aria-label="common.close">${z.close}</button>
320
+ <button class="todo-icon-btn todo-fullscreen-btn" data-action="toggle-fullscreen">${B.expand}</button>
321
+ <button class="todo-icon-btn" data-action="header-more" data-i18n-title="todo.headerMore" data-i18n-aria-label="todo.headerMore">${B.more}</button>
322
+ <button class="todo-icon-btn" data-action="close" data-i18n-title="common.close" data-i18n-aria-label="common.close">${B.close}</button>
323
323
  </div>
324
324
  </div>
325
325
  <div class="todo-progress-row">
@@ -340,125 +340,125 @@ import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-5c8prpFJ.js"
340
340
  </div>
341
341
  <div class="todo-body" id="todoBody"></div>
342
342
  </div>
343
- `,sr(`todo`).appendChild(B),i(B),jl=B.querySelector(`#todoPanelToggle`),V=B.querySelector(`#todoPanel`),H=B.querySelector(`#todoBody`),Ol=B.querySelector(`#todoPanelCount`),kl=B.querySelector(`#todoProgressBar`),Al=B.querySelector(`#todoAddInput`),Ml=B.querySelector(`#todoBadge`),Pl=B.querySelector(`#todoTabActive`),Fl=B.querySelector(`#todoTabDone`),Il=B.querySelector(`.todo-fullscreen-btn`),ou(),Ol.textContent=t(`todo.progressLabel`,{done:0,total:0}),jl.addEventListener(`click`,nu),B.addEventListener(`click`,Mu),B.addEventListener(`change`,ed),B.addEventListener(`keydown`,zu),H.addEventListener(`dragstart`,Ed),H.addEventListener(`dragover`,Dd),H.addEventListener(`drop`,kd),H.addEventListener(`dragend`,Ad),H.addEventListener(`focusout`,td),H.addEventListener(`dblclick`,Xu),H.addEventListener(`focusin`,e=>{let t=e.target.closest?.(`.todo-item`);t?.dataset.id&&(Gl=t.dataset.id)}),B.addEventListener(`pointerdown`,e=>{let t=e.target?.closest?.(`[data-action="link-cancel"]`);if(t){e.preventDefault(),od(t.dataset.id||W);return}let n=e.target?.closest?.(`[data-action="note-cancel"]`);n&&(e.preventDefault(),U=null,G(n.dataset.id),K())}),document.addEventListener(`keydown`,e=>{e.key===`Escape`&&Nl&&ud()}),document.addEventListener(`keydown`,Hu),document.addEventListener(`click`,e=>{Nl&&(Nl.contains(e.target)||ud())},!0),pc(()=>K()),chrome.runtime.onMessage.addListener(e=>{e?.type===`TODO_CHANGED`&&mc().catch(()=>{})}),o(()=>{i(B),K()}),n().then(()=>{i(B),K()}),K())}function tu(){return!!V&&V.classList.contains(`expanded`)}function nu(){tu()?iu():ru()}function ru(){Ll=`active`,Ul=null,ql=0,V.style.removeProperty(`height`),K(),V.classList.add(`expanded`),jl.classList.add(`active`),vu(),_u(),setTimeout(()=>{tu()&&Al.focus()},60)}function iu(){Xl=!1,V.classList.remove(`fullscreen`),ou(),V.classList.remove(`expanded`),jl.classList.remove(`active`),yu(),V.style.removeProperty(`--fit-y`),V.style.removeProperty(`--todo-max-h`),V.style.removeProperty(`height`),ql=0,ud(),sd(),xu()}function au(e){!V||Xl===e||(Xl=e,V.classList.toggle(`fullscreen`,e),ou(),ud(),e?(yu(),V.style.removeProperty(`--fit-y`),V.style.removeProperty(`--todo-max-h`),V.style.removeProperty(`height`),ql=0):(vu(),_u()))}function ou(){if(!Il)return;let e=t(Xl?`todo.exitFullscreen`:`todo.fullscreen`);Il.innerHTML=Xl?z.collapse:z.expand,Il.title=e,Il.setAttribute(`aria-label`,e),Il.setAttribute(`aria-pressed`,String(Xl))}function su(){Ql.forEach(e=>{H.querySelectorAll(`.${e}`).forEach(t=>{let n=t.dataset.id;if(!n)return;let r=Zl.get(n)||{};r[$l[e]]=t.value,Zl.set(n,r)})})}function cu(e){if(Zl.size===0)return;let t=new Set(e.map(e=>e.id));for(let e of[...Zl.keys()])t.has(e)||Zl.delete(e)}function G(e){e?Zl.delete(e):Zl.clear()}function lu(e,t){let n=Zl.get(e);return n&&n[t]!==void 0?n[t]:null}function uu(){let e=document.activeElement;if(!e||!H.contains(e))return null;let t=Ql.find(t=>e.classList.contains(t));return!t||!e.dataset.id?null:{cls:t,id:e.dataset.id,caret:du(e)}}function du(e){try{return e.selectionStart}catch{return null}}function fu(e){return H.querySelector(`.${e.cls}[data-id="${O(e.id)}"]`)}function pu(e){let t=fu(e);if(t&&(t.focus(),e.caret!==null))try{t.selectionStart=t.selectionEnd=e.caret}catch{}}function mu(){if(Rl){ku();return}if(U){let e=fu({cls:`todo-note-input`,id:U});if(!e)return;e.focus(),e.selectionStart=e.selectionEnd=e.value.length;return}if(zl){let e=fu({cls:`todo-due-input`,id:zl});e&&e.focus();return}if(W){let e=fu({cls:`todo-link-input`,id:W});if(!e)return;e.focus(),e.selectionStart=e.selectionEnd=e.value.length}}function K(){if(!H)return;su();let e=uu(),n=document.activeElement?.closest?.(`.todo-item`)?.dataset.id||null,{active:r,done:i,stats:a}=hc();Ol.textContent=t(`todo.progressLabel`,{done:a.done,total:a.total})+(a.doing>0?t(`todo.progressDoing`,{doing:a.doing}):``),kl.style.width=a.total?`${Math.round(a.done/a.total*100)}%`:`0%`,Su(r.length),hu(r.length,i.length),ou();let o=Ll===`done`?i:r,s=[];if(cu([...r,...i]),Ul&&s.push(`<div class="todo-undo">
344
- <span class="todo-undo-text">${A(t(`todo.undoBar`,{title:Ul.title}))}</span>
345
- <button class="todo-mini-btn" data-action="undo-complete" data-id="${O(Ul.id)}">${A(t(`todo.undoAction`))}</button>
346
- </div>`),Ll===`done`&&i.length>0&&s.push(`<button class="todo-clear-done" data-action="clear-completed-btn">
347
- ${z.trash}<span>${A(t(`todo.clearCompleted`))} (${i.length})</span>
348
- </button>`),o.length===0){let e=Ll===`done`;s.push(`<div class="todo-empty">
349
- <div class="todo-empty-title">${A(t(e?`todo.emptyDone`:`todo.empty`))}</div>
350
- <div class="todo-empty-hint">${A(t(e?`todo.emptyDoneHint`:`todo.emptyHint`))}</div>
351
- </div>`)}else s.push(`<div class="todo-list" data-group="${Ll}">${o.map(e=>Ou(e,Ll)).join(``)}</div>`);H.innerHTML=s.join(``);let c=Yl;Yl=!1,e?pu(e):c?mu():n?Ku(n):mu(),_u()}function hu(e,t){if(!Pl||!Fl)return;let n=Ll===`done`;Pl.classList.toggle(`active`,!n),Fl.classList.toggle(`active`,n),Pl.setAttribute(`aria-selected`,String(!n)),Fl.setAttribute(`aria-selected`,String(n)),Pl.querySelector(`.todo-tab-count`).textContent=String(e),Fl.querySelector(`.todo-tab-count`).textContent=String(t)}function gu(){let e=document.querySelector(Sl)?.getBoundingClientRect();return e&&e.height>0&&Number.isFinite(e.top)?e.top:window.innerHeight-Cl}function _u(){!V||!tu()||Xl||(V.style.removeProperty(`--fit-y`),requestAnimationFrame(()=>{if(!V||!tu())return;let e=gu()-wl,t=V.getBoundingClientRect();if(!t.height)return;let n=Math.max(El,Math.floor(e-Tl));V.style.setProperty(`--todo-max-h`,`${n}px`),ql&&(V.style.height=`auto`),ql=Math.min(n,Math.max(ql,V.offsetHeight)),V.style.height=`${ql}px`;let r=Math.floor(e-t.bottom);r&&V.style.setProperty(`--fit-y`,`${r}px`)}))}function vu(){yu(),window.addEventListener(`resize`,_u);let e=document.querySelector(Sl);e&&typeof ResizeObserver<`u`&&(Kl=new ResizeObserver(()=>_u()),Kl.observe(e))}function yu(){window.removeEventListener(`resize`,_u),Kl?.disconnect(),Kl=null}function bu(e){Ul={id:e.id,title:e.title},clearTimeout(Wl),Wl=setTimeout(()=>{Ul=null,K()},Dl)}function xu(){clearTimeout(Wl),Wl=null,Ul=null}function Su(e){Ml&&(e>0?(Ml.textContent=e>99?`99+`:String(e),Ml.style.display=``):Ml.style.display=`none`)}function Cu(e){return e===D.DONE?t(`todo.statusDone`):e===D.DOING?t(`todo.statusDoing`):t(`todo.statusPending`)}function wu(e){let n=t(`todo.statusTip`,{status:Cu(e.status),next:Cu(He(e.status))}),r=e.status===D.DONE?z.check:e.status===D.DOING?`<i></i>`:``;return`<button class="todo-status" data-action="cycle" data-id="${O(e.id)}"
352
- title="${O(n)}" aria-label="${O(n)}">${r}</button>`}function Tu(e){let n=Fe(e);if(!n)return``;let r=t(`todo.openLinkTitle`,{host:n});return`<button class="todo-link-chip" data-action="open-link" data-id="${O(e.id)}"
353
- title="${O(r)}" aria-label="${O(r)}">${z.link}<span>${A(n)}</span></button>`}function Eu(e){let n=Tu(e);if(e.status===D.DONE)return`<div class="todo-meta">${n}<span>${A(ze(e))}</span></div>`;let r=[];if(n&&r.push(n),Number.isFinite(e.dueAt)){let n=Oe(e),i=n?t(`todoTime.overdueStamp`,{date:Ee(e.dueAt)}):Ee(e.dueAt);r.push(`<span class="todo-due${n?` overdue`:``}">${z.alert}${A(i)}</span>`)}let i=Pe(e.createdAt);return i&&r.push(`<span>${A(i)}</span>`),r.length===0?``:`<div class="todo-meta">${r.join(`<span class="todo-sep">·</span>`)}</div>`}function Du(e){let n=Bl.has(e.id),r=U===e.id,i=!!(e.note&&e.note.trim());if(r){let n=lu(e.id,`note`);return`<div class="todo-note-editor">
354
- <textarea class="todo-note-input" data-id="${O(e.id)}" rows="2"
355
- placeholder="${O(t(`todo.notePlaceholder`))}">${A(n===null?e.note||``:n)}</textarea>
343
+ `,or(`todo`).appendChild(V),i(V),Nl=V.querySelector(`#todoPanelToggle`),H=V.querySelector(`#todoPanel`),U=V.querySelector(`#todoBody`),Al=V.querySelector(`#todoPanelCount`),jl=V.querySelector(`#todoProgressBar`),Ml=V.querySelector(`#todoAddInput`),Pl=V.querySelector(`#todoBadge`),Il=V.querySelector(`#todoTabActive`),Ll=V.querySelector(`#todoTabDone`),Rl=V.querySelector(`.todo-fullscreen-btn`),cu(),Al.textContent=t(`todo.progressLabel`,{done:0,total:0}),Nl.addEventListener(`click`,iu),V.addEventListener(`click`,Pu),V.addEventListener(`change`,nd),V.addEventListener(`keydown`,Vu),U.addEventListener(`dragstart`,Od),U.addEventListener(`dragover`,kd),U.addEventListener(`drop`,jd),U.addEventListener(`dragend`,Md),U.addEventListener(`focusout`,rd),U.addEventListener(`dblclick`,Qu),U.addEventListener(`focusin`,e=>{let t=e.target.closest?.(`.todo-item`);t?.dataset.id&&(ql=t.dataset.id)}),V.addEventListener(`pointerdown`,e=>{let t=e.target?.closest?.(`[data-action="link-cancel"]`);if(t){e.preventDefault(),cd(t.dataset.id||G);return}let n=e.target?.closest?.(`[data-action="note-cancel"]`);n&&(e.preventDefault(),W=null,K(n.dataset.id),q())}),document.addEventListener(`keydown`,e=>{e.key===`Escape`&&Fl&&fd()}),document.addEventListener(`keydown`,Wu),document.addEventListener(`click`,e=>{Fl&&(Fl.contains(e.target)||fd())},!0),hc(()=>q()),chrome.runtime.onMessage.addListener(e=>{e?.type===`TODO_CHANGED`&&gc().catch(()=>{})}),o(()=>{i(V),q()}),n().then(()=>{i(V),q()}),q())}function ru(){return!!H&&H.classList.contains(`expanded`)}function iu(){ru()?ou():au()}function au(){zl=`active`,Gl=null,Yl=0,H.style.removeProperty(`height`),q(),H.classList.add(`expanded`),Nl.classList.add(`active`),bu(),yu(),setTimeout(()=>{ru()&&Ml.focus()},60)}function ou(){Ql=!1,H.classList.remove(`fullscreen`),cu(),H.classList.remove(`expanded`),Nl.classList.remove(`active`),xu(),H.style.removeProperty(`--fit-y`),H.style.removeProperty(`--todo-max-h`),H.style.removeProperty(`height`),Yl=0,fd(),ld(),Cu()}function su(e){!H||Ql===e||(Ql=e,H.classList.toggle(`fullscreen`,e),cu(),fd(),e?(xu(),H.style.removeProperty(`--fit-y`),H.style.removeProperty(`--todo-max-h`),H.style.removeProperty(`height`),Yl=0):(bu(),yu()))}function cu(){if(!Rl)return;let e=t(Ql?`todo.exitFullscreen`:`todo.fullscreen`);Rl.innerHTML=Ql?B.collapse:B.expand,Rl.title=e,Rl.setAttribute(`aria-label`,e),Rl.setAttribute(`aria-pressed`,String(Ql))}function lu(){eu.forEach(e=>{U.querySelectorAll(`.${e}`).forEach(t=>{let n=t.dataset.id;if(!n)return;let r=$l.get(n)||{};r[tu[e]]=t.value,$l.set(n,r)})})}function uu(e){if($l.size===0)return;let t=new Set(e.map(e=>e.id));for(let e of[...$l.keys()])t.has(e)||$l.delete(e)}function K(e){e?$l.delete(e):$l.clear()}function du(e,t){let n=$l.get(e);return n&&n[t]!==void 0?n[t]:null}function fu(){let e=document.activeElement;if(!e||!U.contains(e))return null;let t=eu.find(t=>e.classList.contains(t));return!t||!e.dataset.id?null:{cls:t,id:e.dataset.id,caret:pu(e)}}function pu(e){try{return e.selectionStart}catch{return null}}function mu(e){return U.querySelector(`.${e.cls}[data-id="${j(e.id)}"]`)}function hu(e){let t=mu(e);if(t&&(t.focus(),e.caret!==null))try{t.selectionStart=t.selectionEnd=e.caret}catch{}}function gu(){if(Bl){ju();return}if(W){let e=mu({cls:`todo-note-input`,id:W});if(!e)return;e.focus(),e.selectionStart=e.selectionEnd=e.value.length;return}if(Vl){let e=mu({cls:`todo-due-input`,id:Vl});e&&e.focus();return}if(G){let e=mu({cls:`todo-link-input`,id:G});if(!e)return;e.focus(),e.selectionStart=e.selectionEnd=e.value.length}}function q(){if(!U)return;lu();let e=fu(),n=document.activeElement?.closest?.(`.todo-item`)?.dataset.id||null,{active:r,done:i,stats:a}=_c();Al.textContent=t(`todo.progressLabel`,{done:a.done,total:a.total})+(a.doing>0?t(`todo.progressDoing`,{doing:a.doing}):``),jl.style.width=a.total?`${Math.round(a.done/a.total*100)}%`:`0%`,wu(r.length),_u(r.length,i.length),cu();let o=zl===`done`?i:r,s=[];if(uu([...r,...i]),Gl&&s.push(`<div class="todo-undo">
344
+ <span class="todo-undo-text">${k(t(`todo.undoBar`,{title:Gl.title}))}</span>
345
+ <button class="todo-mini-btn" data-action="undo-complete" data-id="${j(Gl.id)}">${k(t(`todo.undoAction`))}</button>
346
+ </div>`),zl===`done`&&i.length>0&&s.push(`<button class="todo-clear-done" data-action="clear-completed-btn">
347
+ ${B.trash}<span>${k(t(`todo.clearCompleted`))} (${i.length})</span>
348
+ </button>`),o.length===0){let e=zl===`done`;s.push(`<div class="todo-empty">
349
+ <div class="todo-empty-title">${k(t(e?`todo.emptyDone`:`todo.empty`))}</div>
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="${zl}">${o.map(e=>Au(e,zl)).join(``)}</div>`);U.innerHTML=s.join(``);let c=Zl;Zl=!1,e?hu(e):c?gu():n?Ju(n):gu(),yu()}function _u(e,t){if(!Il||!Ll)return;let n=zl===`done`;Il.classList.toggle(`active`,!n),Ll.classList.toggle(`active`,n),Il.setAttribute(`aria-selected`,String(!n)),Ll.setAttribute(`aria-selected`,String(n)),Il.querySelector(`.todo-tab-count`).textContent=String(e),Ll.querySelector(`.todo-tab-count`).textContent=String(t)}function vu(){let e=document.querySelector(wl)?.getBoundingClientRect();return e&&e.height>0&&Number.isFinite(e.top)?e.top:window.innerHeight-Tl}function yu(){!H||!ru()||Ql||(H.style.removeProperty(`--fit-y`),requestAnimationFrame(()=>{if(!H||!ru())return;let e=vu()-El,t=H.getBoundingClientRect();if(!t.height)return;let n=Math.max(Ol,Math.floor(e-Dl));H.style.setProperty(`--todo-max-h`,`${n}px`),Yl&&(H.style.height=`auto`),Yl=Math.min(n,Math.max(Yl,H.offsetHeight)),H.style.height=`${Yl}px`;let r=Math.floor(e-t.bottom);r&&H.style.setProperty(`--fit-y`,`${r}px`)}))}function bu(){xu(),window.addEventListener(`resize`,yu);let e=document.querySelector(wl);e&&typeof ResizeObserver<`u`&&(Jl=new ResizeObserver(()=>yu()),Jl.observe(e))}function xu(){window.removeEventListener(`resize`,yu),Jl?.disconnect(),Jl=null}function Su(e){Gl={id:e.id,title:e.title},clearTimeout(Kl),Kl=setTimeout(()=>{Gl=null,q()},kl)}function Cu(){clearTimeout(Kl),Kl=null,Gl=null}function wu(e){Pl&&(e>0?(Pl.textContent=e>99?`99+`:String(e),Pl.style.display=``):Pl.style.display=`none`)}function Tu(e){return e===O.DONE?t(`todo.statusDone`):e===O.DOING?t(`todo.statusDoing`):t(`todo.statusPending`)}function Eu(e){let n=t(`todo.statusTip`,{status:Tu(e.status),next:Tu(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 Du(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 Ou(e){let n=Du(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 ku(e){let n=Hl.has(e.id),r=W===e.id,i=!!(e.note&&e.note.trim());if(r){let n=du(e.id,`note`);return`<div class="todo-note-editor">
354
+ <textarea class="todo-note-input" data-id="${j(e.id)}" rows="2"
355
+ placeholder="${j(t(`todo.notePlaceholder`))}">${k(n===null?e.note||``:n)}</textarea>
356
356
  <div class="todo-note-editor-actions">
357
- <button class="todo-mini-btn" data-action="note-save" data-id="${O(e.id)}">${A(t(`todo.noteSave`))}</button>
358
- <button class="todo-mini-btn ghost" data-action="note-cancel" data-id="${O(e.id)}">${A(t(`todo.noteCancel`))}</button>
357
+ <button class="todo-mini-btn" data-action="note-save" data-id="${j(e.id)}">${k(t(`todo.noteSave`))}</button>
358
+ <button class="todo-mini-btn ghost" data-action="note-cancel" data-id="${j(e.id)}">${k(t(`todo.noteCancel`))}</button>
359
359
  </div>
360
- </div>`}return i?`<button class="todo-note-toggle${n?` open`:``}" data-action="toggle-note" data-id="${O(e.id)}">
361
- ${z.chevron}<span>${A(t(`todo.noteToggle`))}</span>
360
+ </div>`}return i?`<button class="todo-note-toggle${n?` open`:``}" data-action="toggle-note" data-id="${j(e.id)}">
361
+ ${B.chevron}<span>${k(t(`todo.noteToggle`))}</span>
362
362
  </button>
363
- ${n?`<div class="todo-note">${A(e.note)}</div>`:``}`:``}function Ou(e,n){let r=e.status===D.DONE,i=Rl===e.id,a=[`todo-item`];e.status===D.DOING&&a.push(`doing`),r&&a.push(`done`),e.priority&&a.push(`prio-${e.priority}`),zl===e.id&&a.push(`editing-due`);let o=lu(e.id,`title`),s=i?`<input type="text" class="todo-edit-input" data-id="${O(e.id)}" value="${O(o===null?e.title:o)}" />`:`<div class="todo-name">${A(e.title)}</div>`,c=lu(e.id,`due`),l=zl===e.id?`<div class="todo-due-editor">
364
- <input type="date" class="todo-due-input" data-id="${O(e.id)}" value="${O(c===null?Au(e.dueAt):c)}" />
365
- <button class="todo-mini-btn ghost" data-action="due-clear" data-id="${O(e.id)}">${A(t(`todo.clearDue`))}</button>
366
- </div>`:``,u=lu(e.id,`link`),d=W===e.id?`<div class="todo-link-editor">
367
- <input type="text" class="todo-link-input" data-id="${O(e.id)}" autocomplete="off"
368
- placeholder="${O(t(`todo.linkPlaceholder`))}" value="${O(u===null?e.link||``:u)}" />
369
- <button class="todo-mini-btn ghost" data-action="link-cancel" data-id="${O(e.id)}">${A(t(`todo.noteCancel`))}</button>
370
- </div>`:``,f=n===`active`?` draggable="true"`:``,p=Rl===e.id||U===e.id||zl===e.id||W===e.id,m=`
363
+ ${n?`<div class="todo-note">${k(e.note)}</div>`:``}`:``}function Au(e,n){let r=e.status===O.DONE,i=Bl===e.id,a=[`todo-item`];e.status===O.DOING&&a.push(`doing`),r&&a.push(`done`),e.priority&&a.push(`prio-${e.priority}`),Vl===e.id&&a.push(`editing-due`);let o=du(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=du(e.id,`due`),l=Vl===e.id?`<div class="todo-due-editor">
364
+ <input type="date" class="todo-due-input" data-id="${j(e.id)}" value="${j(c===null?Mu(e.dueAt):c)}" />
365
+ <button class="todo-mini-btn ghost" data-action="due-clear" data-id="${j(e.id)}">${k(t(`todo.clearDue`))}</button>
366
+ </div>`:``,u=du(e.id,`link`),d=G===e.id?`<div class="todo-link-editor">
367
+ <input type="text" class="todo-link-input" data-id="${j(e.id)}" autocomplete="off"
368
+ placeholder="${j(t(`todo.linkPlaceholder`))}" value="${j(u===null?e.link||``:u)}" />
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=Bl===e.id||W===e.id||Vl===e.id||G===e.id,m=`
371
371
  <div class="todo-item-actions">
372
- ${r?`<button class="todo-act" data-action="restore" data-id="${O(e.id)}" title="${O(t(`todo.restoreTo`,{status:Cu(Ue(e))}))}" aria-label="${O(t(`todo.restoreTo`,{status:Cu(Ue(e))}))}">${z.undo}</button>`:``}
373
- <button class="todo-act" data-action="edit-title" data-id="${O(e.id)}" title="${O(t(`todo.editItem`))}" aria-label="${O(t(`todo.editItem`))}">${z.edit}</button>
374
- <button class="todo-act" data-action="copy-item" data-id="${O(e.id)}" title="${O(t(`todo.copyItem`))}" aria-label="${O(t(`todo.copyItem`))}">${z.copy}</button>
375
- <button class="todo-act" data-action="fill-item" data-id="${O(e.id)}" title="${O(t(`todo.fillInput`))}" aria-label="${O(t(`todo.fillInput`))}">${z.fill}</button>
376
- <button class="todo-act" data-action="row-more" data-id="${O(e.id)}" title="${O(t(`todo.more`))}" aria-label="${O(t(`todo.more`))}">${z.more}</button>
377
- </div>`;return`<div class="${a.join(` `)}" data-id="${O(e.id)}" data-group="${n}"${f} tabindex="0" data-priority="${O(e.priority||``)}">
378
- ${wu(e)}
372
+ ${r?`<button class="todo-act" data-action="restore" data-id="${j(e.id)}" title="${j(t(`todo.restoreTo`,{status:Tu(He(e))}))}" aria-label="${j(t(`todo.restoreTo`,{status:Tu(He(e))}))}">${B.undo}</button>`:``}
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
+ <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
+ <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
+ <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
+ </div>`;return`<div class="${a.join(` `)}" data-id="${j(e.id)}" data-group="${n}"${f} tabindex="0" data-priority="${j(e.priority||``)}">
378
+ ${Eu(e)}
379
379
  <div class="todo-main">
380
380
  ${s}
381
- ${Du(e)}
381
+ ${ku(e)}
382
382
  ${l}
383
383
  ${d}
384
- ${Eu(e)}
384
+ ${Ou(e)}
385
385
  </div>
386
386
  ${p?``:m}
387
- </div>`}function ku(){let e=H.querySelector(`.todo-edit-input[data-id="${Rl}"]`);e&&(e.focus(),e.selectionStart=e.selectionEnd=e.value.length)}function Au(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&&k(n,`success`);return}k(t(e&&e.reason===`invalid`?`todo.linkInvalid`:`todo.saveFailed`),`error`)})}function ju(e){let n=e&&e.link;if(!n||!De(n)){k(t(`todo.linkInvalid`),`error`);return}try{chrome.tabs.create({url:n})}catch(e){r.warn(`[Todo] open link failed:`,e),k(t(`todo.copyFailed`),`error`)}}function Mu(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(),iu();return;case`fill-item`:e.stopPropagation(),Cd(r);return;case`copy-item`:e.stopPropagation(),wd(r);return;case`header-more`:e.stopPropagation(),gd(t);return;case`toggle-fullscreen`:e.stopPropagation(),au(!Xl);return;case`add`:e.stopPropagation(),nd();return;case`switch-tab`:Pu(t.dataset.tab);return;case`undo-complete`:e.stopPropagation(),Lu(r);return;case`restore`:e.stopPropagation(),Iu(r);return;case`open-link`:e.stopPropagation(),ju(Nu(r));return;case`clear-completed-btn`:e.stopPropagation(),Ru();return;case`cycle`:e.stopPropagation(),q(xc(r));return;case`toggle-note`:e.stopPropagation(),Bl.has(r)?Bl.delete(r):Bl.add(r),K();return;case`edit-title`:e.stopPropagation(),Yu(r);return;case`row-more`:e.stopPropagation(),hd(t,r);return;case`note-save`:e.stopPropagation(),id(r);return;case`note-cancel`:e.stopPropagation(),U=null,G(r),K();return;case`due-clear`:e.stopPropagation(),zl=null,G(r),q(yc(r,{dueAt:null}));return;case`link-cancel`:e.stopPropagation(),od(r);return;default:return}}function Nu(e){let{active:t,done:n}=hc();return[...t,...n].find(t=>t.id===e)||null}function Pu(e){let t=e===`done`?`done`:`active`;t!==Ll&&(Ll=t,sd(),K())}function Fu(e){let t=Nu(e);t&&(bu(t),q(bc(e,D.DONE)))}function Iu(e){let n=Nu(e);if(!n)return;let r=Ue(n);xu(),q(Sc(e),t(`todo.restoredToast`,{status:Cu(r)}))}function Lu(e){Iu(e)}async function Ru(){let{done:e}=hc();e.length!==0&&await cd(t(`todo.clearCompletedConfirmMsg`,{n:e.length}),t(`todo.clearCompletedConfirmTitle`))&&q(Dc(),t(`todo.clearedToast`))}function zu(e){if((e.key===`ArrowUp`||e.key===`ArrowDown`)&&!e.target.closest?.(`input, textarea, [contenteditable="true"]`)&&e.target.closest?.(`.todo-item`)){e.preventDefault(),Gu(e.key===`ArrowDown`?1:-1);return}if(e.target===Al){e.key===`Enter`?(e.preventDefault(),nd()):e.key===`Escape`&&(e.stopPropagation(),Al.value=``,tu()&&iu());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(Rl=null,!n){G(t),K();return}G(t),q(yc(t,{title:n}))}else e.key===`Escape`&&(e.stopPropagation(),Rl=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(),id(e.target.dataset.id)):e.key===`Escape`&&(e.stopPropagation(),U=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(),ad(t,e.target.value)):e.key===`Escape`&&(e.stopPropagation(),od(t))}}var Bu={KeyT:()=>nu(),KeyA:()=>qu(),KeyB:e=>Ju(e),KeyL:e=>Zu(e),KeyD:e=>Qu(e),KeyP:e=>$u(e)},Vu=new Set([`KeyT`,`KeyA`]);function Hu(e){if(!e.altKey||e.shiftKey||e.ctrlKey||e.metaKey)return;let t=Bu[e.code];if(!t)return;if(Vu.has(e.code)){e.preventDefault(),t();return}let n=Wu();n&&(e.preventDefault(),t(n))}function Uu(){return H?Array.from(H.querySelectorAll(`.todo-item`)):[]}function Wu(){if(!tu())return null;let e=document.activeElement?.closest?.(`.todo-item`);if(e?.dataset.id&&H.contains(e))return e.dataset.id;let t=Uu();return Gl&&t.some(e=>e.dataset.id===Gl)?Gl:t[0]?.dataset.id||null}function Gu(e){let t=Uu();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 Ku(e){let t=Uu().find(t=>t.dataset.id===e);t&&t.focus()}function qu(){if(tu()){Al.focus();return}ru()}function Ju(e){U=e,Bl.add(e),Yl=!0,K()}function Yu(e){sd(),Rl=e,Yl=!0,K()}function Xu(e){let t=e.target.closest?.(`.todo-name`);if(t){let n=t.closest(`.todo-item`)?.dataset.id;if(!n)return;e.preventDefault(),Yu(n);return}let n=e.target.closest?.(`.todo-note`);if(n){let t=n.closest(`.todo-item`)?.dataset.id;if(!t)return;e.preventDefault(),Ju(t)}}function Zu(e){W=e,Yl=!0,K()}function Qu(e){let t=Nu(e);t&&(t.status===D.DONE?Iu(e):Fu(e))}function $u(e){let t=Nu(e);t&&q(Cc(e,Ce(t.priority)))}function ed(e){if(e.target.classList?.contains(`todo-link-input`)){let t=e.target.dataset.id;if(!W||W!==t)return;ad(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(zl=null,G(t),!n){q(yc(t,{dueAt:null}));return}let r=new Date(n+`T00:00:00`);q(yc(t,{dueAt:isNaN(r.getTime())?null:r.getTime()}))}function td(e){if(e.target?.classList?.contains(`todo-link-input`)){let t=e.target.dataset.id;if(!W||W!==t)return;ad(t,e.target.value);return}if(e.target?.classList?.contains(`todo-note-input`)){let t=e.target.dataset.id;if(!U||U!==t)return;id(t);return}if(!e.target?.classList?.contains(`todo-edit-input`))return;let n=e.target.dataset.id;if(!Rl||Rl!==n)return;let r=e.target.value.trim();if(Rl=null,!r){G(n),K();return}G(n),yc(n,{title:r}).then(e=>{e?K():k(t(`todo.saveFailed`),`error`)})}async function nd(){let e=Al.value.trim();if(!e)return;Al.value=``,Ll===`done`&&(Ll=`active`);let n=await vc(e);n?requestAnimationFrame(()=>rd(n.id)):k(t(`todo.saveFailed`),`error`),Al.focus()}function rd(e){let t=Uu().find(t=>t.dataset.id===e);if(!t)return;let n=H.getBoundingClientRect(),r=t.getBoundingClientRect();r.bottom>n.bottom-4?H.scrollTop+=r.bottom-n.bottom+4:r.top<n.top+4&&(H.scrollTop-=n.top-r.top+4),t.classList.add(`just-added`),clearTimeout(Jl),Jl=setTimeout(()=>t.classList.remove(`just-added`),1600)}function id(e){if(U!==e)return;let t=H.querySelector(`.todo-note-input[data-id="${O(e)}"]`),n=t?t.value:``;U=null,Bl.delete(e),G(e),q(yc(e,{note:n}))}function ad(e,n){let r=!!Nu(e)?.link;W=null,G(e);let i=String(n||``).trim();q(wc(e,i),t(i?`todo.linkSavedToast`:r?`todo.linkRemovedToast`:`todo.linkSavedToast`))}function od(e){W=null,G(e),K()}function sd(){let e=Rl||U||zl||W;Rl=null,U=null,zl=null,W=null,Yl=!1,G(),e&&K()}async function cd(e,t){return typeof window<`u`&&typeof window.showCustomConfirm==`function`?!!await window.showCustomConfirm(e,t):!1}function ld(){return Nl||(Nl=document.createElement(`div`),Nl.className=`todo-menu`,document.body.appendChild(Nl),Nl.addEventListener(`click`,e=>{let t=e.target.closest(`[data-priority-value]`);if(t){let e=t.dataset.menuId,n=t.dataset.priorityValue||null;ud(),q(Cc(e,n));return}let n=e.target.closest(`[data-menu-action]`);if(!n)return;let{menuAction:r,menuId:i}=n.dataset;ud(),xd(r,i)}),Nl)}function ud(){Nl&&=(Nl.remove(),null)}function dd(e){return e?`<kbd class="todo-menu-kbd">${A(e)}</kbd>`:``}function fd(e,n){if(e.swatches){let r=[[``,t(`todo.priorityNone`)],[Be.LOW,t(`todo.priorityLow`)],[Be.MEDIUM,t(`todo.priorityMedium`)],[Be.HIGH,t(`todo.priorityHigh`)]];return`<div class="todo-menu-row">
388
- <span class="todo-menu-row-label">${A(e.label)}</span>
387
+ </div>`}function ju(){let e=U.querySelector(`.todo-edit-input[data-id="${Bl}"]`);e&&(e.focus(),e.selectionStart=e.selectionEnd=e.value.length)}function Mu(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 Nu(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(),ou();return;case`fill-item`:e.stopPropagation(),Td(r);return;case`copy-item`:e.stopPropagation(),Ed(r);return;case`header-more`:e.stopPropagation(),vd(t);return;case`toggle-fullscreen`:e.stopPropagation(),su(!Ql);return;case`add`:e.stopPropagation(),id();return;case`switch-tab`:Iu(t.dataset.tab);return;case`undo-complete`:e.stopPropagation(),zu(r);return;case`restore`:e.stopPropagation(),Ru(r);return;case`open-link`:e.stopPropagation(),Nu(Fu(r));return;case`clear-completed-btn`:e.stopPropagation(),Bu();return;case`cycle`:e.stopPropagation(),J(Cc(r));return;case`toggle-note`:e.stopPropagation(),Hl.has(r)?Hl.delete(r):Hl.add(r),q();return;case`edit-title`:e.stopPropagation(),Zu(r);return;case`row-more`:e.stopPropagation(),_d(t,r);return;case`note-save`:e.stopPropagation(),od(r);return;case`note-cancel`:e.stopPropagation(),W=null,K(r),q();return;case`due-clear`:e.stopPropagation(),Vl=null,K(r),J(xc(r,{dueAt:null}));return;case`link-cancel`:e.stopPropagation(),cd(r);return;default:return}}function Fu(e){let{active:t,done:n}=_c();return[...t,...n].find(t=>t.id===e)||null}function Iu(e){let t=e===`done`?`done`:`active`;t!==zl&&(zl=t,ld(),q())}function Lu(e){let t=Fu(e);t&&(Su(t),J(Sc(e,O.DONE)))}function Ru(e){let n=Fu(e);if(!n)return;let r=He(n);Cu(),J(wc(e),t(`todo.restoredToast`,{status:Tu(r)}))}function zu(e){Ru(e)}async function Bu(){let{done:e}=_c();e.length!==0&&await ud(t(`todo.clearCompletedConfirmMsg`,{n:e.length}),t(`todo.clearCompletedConfirmTitle`))&&J(kc(),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(),qu(e.key===`ArrowDown`?1:-1);return}if(e.target===Ml){e.key===`Enter`?(e.preventDefault(),id()):e.key===`Escape`&&(e.stopPropagation(),Ml.value=``,ru()&&ou());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(Bl=null,!n){K(t),q();return}K(t),J(xc(t,{title:n}))}else e.key===`Escape`&&(e.stopPropagation(),Bl=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(),od(e.target.dataset.id)):e.key===`Escape`&&(e.stopPropagation(),W=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(),sd(t,e.target.value)):e.key===`Escape`&&(e.stopPropagation(),cd(t))}}var Hu={KeyT:()=>iu(),KeyA:()=>Yu(),KeyB:e=>Xu(e),KeyL:e=>$u(e),KeyD:e=>ed(e),KeyP:e=>td(e)},Uu=new Set([`KeyT`,`KeyA`]);function Wu(e){if(!e.altKey||e.shiftKey||e.ctrlKey||e.metaKey)return;let t=Hu[e.code];if(!t)return;if(Uu.has(e.code)){e.preventDefault(),t();return}let n=Ku();n&&(e.preventDefault(),t(n))}function Gu(){return U?Array.from(U.querySelectorAll(`.todo-item`)):[]}function Ku(){if(!ru())return null;let e=document.activeElement?.closest?.(`.todo-item`);if(e?.dataset.id&&U.contains(e))return e.dataset.id;let t=Gu();return ql&&t.some(e=>e.dataset.id===ql)?ql:t[0]?.dataset.id||null}function qu(e){let t=Gu();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 Ju(e){let t=Gu().find(t=>t.dataset.id===e);t&&t.focus()}function Yu(){if(ru()){Ml.focus();return}au()}function Xu(e){W=e,Hl.add(e),Zl=!0,q()}function Zu(e){ld(),Bl=e,Zl=!0,q()}function Qu(e){let t=e.target.closest?.(`.todo-name`);if(t){let n=t.closest(`.todo-item`)?.dataset.id;if(!n)return;e.preventDefault(),Zu(n);return}let n=e.target.closest?.(`.todo-note`);if(n){let t=n.closest(`.todo-item`)?.dataset.id;if(!t)return;e.preventDefault(),Xu(t)}}function $u(e){G=e,Zl=!0,q()}function ed(e){let t=Fu(e);t&&(t.status===O.DONE?Ru(e):Lu(e))}function td(e){let t=Fu(e);t&&J(Tc(e,Se(t.priority)))}function nd(e){if(e.target.classList?.contains(`todo-link-input`)){let t=e.target.dataset.id;if(!G||G!==t)return;sd(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(Vl=null,K(t),!n){J(xc(t,{dueAt:null}));return}let r=new Date(n+`T00:00:00`);J(xc(t,{dueAt:isNaN(r.getTime())?null:r.getTime()}))}function rd(e){if(e.target?.classList?.contains(`todo-link-input`)){let t=e.target.dataset.id;if(!G||G!==t)return;sd(t,e.target.value);return}if(e.target?.classList?.contains(`todo-note-input`)){let t=e.target.dataset.id;if(!W||W!==t)return;od(t);return}if(!e.target?.classList?.contains(`todo-edit-input`))return;let n=e.target.dataset.id;if(!Bl||Bl!==n)return;let r=e.target.value.trim();if(Bl=null,!r){K(n),q();return}K(n),xc(n,{title:r}).then(e=>{e?q():A(t(`todo.saveFailed`),`error`)})}async function id(){let e=Ml.value.trim();if(!e)return;Ml.value=``,zl===`done`&&(zl=`active`);let n=await bc(e);n?requestAnimationFrame(()=>ad(n.id)):A(t(`todo.saveFailed`),`error`),Ml.focus()}function ad(e){let t=Gu().find(t=>t.dataset.id===e);if(!t)return;let n=U.getBoundingClientRect(),r=t.getBoundingClientRect();r.bottom>n.bottom-4?U.scrollTop+=r.bottom-n.bottom+4:r.top<n.top+4&&(U.scrollTop-=n.top-r.top+4),t.classList.add(`just-added`),clearTimeout(Xl),Xl=setTimeout(()=>t.classList.remove(`just-added`),1600)}function od(e){if(W!==e)return;let t=U.querySelector(`.todo-note-input[data-id="${j(e)}"]`),n=t?t.value:``;W=null,Hl.delete(e),K(e),J(xc(e,{note:n}))}function sd(e,n){let r=!!Fu(e)?.link;G=null,K(e);let i=String(n||``).trim();J(Ec(e,i),t(i?`todo.linkSavedToast`:r?`todo.linkRemovedToast`:`todo.linkSavedToast`))}function cd(e){G=null,K(e),q()}function ld(){let e=Bl||W||Vl||G;Bl=null,W=null,Vl=null,G=null,Zl=!1,K(),e&&q()}async function ud(e,t){return typeof window<`u`&&typeof window.showCustomConfirm==`function`?!!await window.showCustomConfirm(e,t):!1}function dd(){return Fl||(Fl=document.createElement(`div`),Fl.className=`todo-menu`,document.body.appendChild(Fl),Fl.addEventListener(`click`,e=>{let t=e.target.closest(`[data-priority-value]`);if(t){let e=t.dataset.menuId,n=t.dataset.priorityValue||null;fd(),J(Tc(e,n));return}let n=e.target.closest(`[data-menu-action]`);if(!n)return;let{menuAction:r,menuId:i}=n.dataset;fd(),Cd(r,i)}),Fl)}function fd(){Fl&&=(Fl.remove(),null)}function pd(e){return e?`<kbd class="todo-menu-kbd">${k(e)}</kbd>`:``}function md(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
+ <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
- data-priority-value="${O(r)}" data-menu-id="${O(n)}"
392
- title="${O(t(`todo.priorityTitle`,{level:i}))}"
393
- aria-label="${O(i)}"></button>`).join(``)}
394
- ${dd(e.shortcut)}
395
- </div>`}return`${e.divider?`<div class="todo-menu-sep"></div>`:``}<button type="button" data-menu-action="${O(e.action)}" data-menu-id="${O(n||``)}"
391
+ data-priority-value="${j(r)}" data-menu-id="${j(n)}"
392
+ title="${j(t(`todo.priorityTitle`,{level:i}))}"
393
+ aria-label="${j(i)}"></button>`).join(``)}
394
+ ${pd(e.shortcut)}
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>${A(e.label)}</span>${dd(e.shortcut)}
398
- </button>`}function pd(e,t,n){let r=ld();r.innerHTML=t.map((e,t)=>t===0&&e.divider?{...e,divider:!1}:e).map(e=>fd(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 md(e){if(e.status===D.DONE){let n=Ue(e),r=[{action:`restore`,label:t(`todo.restoreTo`,{status:Cu(n)}),icon:z.undo,shortcut:`Alt+D`,divider:!0}];return n!==D.PENDING&&r.push({action:`set-pending`,label:t(`todo.backToPending`),icon:z.circle}),r}return e.status===D.DOING?[{action:`set-done`,label:t(`todo.markDone`),icon:z.check,shortcut:`Alt+D`,divider:!0},{action:`set-pending`,label:t(`todo.backToPending`),icon:z.circle}]:[{action:`set-doing`,label:t(`todo.startDoing`),icon:z.play,divider:!0},{action:`set-done`,label:t(`todo.markDone`),icon:z.check,shortcut:`Alt+D`}]}function hd(e,n){let r=Nu(n);r&&pd(e,[...md(r),{swatches:!0,label:t(`todo.priority`),current:r.priority||``,shortcut:`Alt+P`,divider:!0},{action:`edit-title`,label:t(`todo.editTitleAction`),icon:z.edit,divider:!0},{action:`edit-note`,label:r.note?t(`todo.editNote`):t(`todo.addNote`),icon:z.note,shortcut:`Alt+B`},{action:`set-due`,label:t(`todo.setDue`),icon:z.calendar},{action:`edit-link`,label:r.link?t(`todo.editLink`):t(`todo.addLink`),icon:z.link,shortcut:`Alt+L`},{action:`delete`,label:t(`todo.delete`),icon:z.trash,danger:!0,divider:!0}],n)}function gd(e){let t=_d();t.length!==0&&pd(e,t,``)}function _d(){return[{action:`stats`,label:t(`todo.statsEntry`),icon:z.chart,divider:!0},{action:`export-options`,label:t(`todo.exportEntry`),icon:z.download,divider:!0},{action:`import-options`,label:t(`todo.importEntry`),icon:z.upload}]}async function vd(){let{active:e,done:t}=hc(),n=await il({counts:{all:e.length+t.length,active:e.length,done:t.length}});n&&yd(n.scope,n.format)}function yd(e,n){let{active:i,done:a}=hc(),o=[...i,...a];if(Se(o,e).length===0){k(t(`todo.exportEmptyToast`),`info`);return}try{k(t(`todo.exportedToast`,{name:Lc(o,{scope:e,format:n})}),`success`)}catch(e){r.error(`[Todo] export failed:`,e),k(t(`todo.exportFailedToast`),`error`)}}async function bd(){let e=await Rc();if(!e)return;let n=await zc(e);if(!n.ok){k(t(n.reason===`json`?`todo.importJsonError`:`todo.importFormatError`),`error`);return}let{active:r,done:i}=hc(),a=await al({count:n.todos.length,existing:r.length+i.length});if(!a)return;Ll=`active`,K();let o=await Oc(n.todos,a);if(!o.ok){k(t(o.reason===`empty`?`todo.importEmptyToast`:`todo.importFailedToast`),`error`);return}if(o.added===0){k(t(`todo.importNothingNewToast`,{skipped:o.skipped}),`info`);return}k(t(`todo.importedToast`,{added:o.added,skipped:o.skipped}),`success`)}async function xd(e,n){let r=Nu(n);switch(e){case`set-doing`:q(bc(n,D.DOING));return;case`set-pending`:q(bc(n,D.PENDING));return;case`set-done`:Fu(n);return;case`restore`:Iu(n);return;case`edit-title`:Yu(n);return;case`edit-note`:Ju(n);return;case`set-due`:zl=n,Yl=!0,K();return;case`edit-link`:Zu(n);return;case`stats`:bl();return;case`export-options`:vd();return;case`import-options`:bd();return;case`delete`:await cd(t(`todo.deleteConfirmMsg`,{title:r?.title||``}),t(`todo.deleteConfirmTitle`))&&q(Tc(n),t(`todo.deletedToast`));return;default:}}function Sd(e,t={}){let{active:n,done:r}=hc(),i=[...n,...r].find(t=>t.id===e);return i?Re(i,t):``}function Cd(e){let n=Sd(e);if(!n){k(t(`todo.emptyDigestToast`),`info`);return}let r=document.getElementById(`userInput`);if(!r){k(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,gt(),iu(),k(t(`todo.filledToast`),`success`)}function wd(e){let n=Sd(e,{plain:!0});if(!n){k(t(`todo.emptyDigestToast`),`info`);return}Td(n,t(`todo.copiedToast`))}function Td(e,n){try{navigator.clipboard.writeText(e).then(()=>{k(n,`success`)}).catch(e=>{r.warn(`[Todo] copy failed:`,e),k(t(`todo.copyFailed`),`error`)})}catch(e){r.warn(`[Todo] clipboard unavailable:`,e),k(t(`todo.copyFailed`),`error`)}}function Ed(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`));Vl={id:t.dataset.id,from:r.indexOf(t),list:n},t.classList.add(`dragging`);let{active:i,done:a}=hc(),o=[...i,...a].find(e=>e.id===t.dataset.id);try{e.dataTransfer.effectAllowed=`copyMove`,e.dataTransfer.setData(`text/plain`,Re(o)||t.dataset.id)}catch{}}function Dd(e){if(!Vl)return;e.preventDefault();let t=Vl.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=H.querySelector(`.todo-insert`);return e||(e=document.createElement(`div`),e.className=`todo-insert`,e)}function kd(e){if(!Vl)return;e.preventDefault();let t=Vl.list,n=H.querySelector(`.todo-insert`),r=Vl.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=Vl.from;Ad(),i!==r&&q(Ec(i,r))}function Ad(){Vl=null,H?.querySelectorAll(`.todo-item.dragging`).forEach(e=>e.classList.remove(`dragging`)),H?.querySelector(`.todo-insert`)?.remove()}var jd=`—`,Md=[{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 Nd(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 Pd(e){if(!e)return jd;let t=Date.parse(e);return Number.isNaN(t)?jd:new Date(t).toLocaleString()}function Fd(e){let n=Nd(mt),r=[{label:t(`versionInfo.version`),value:n.version?`v${n.version}`:jd},{label:t(`versionInfo.tag`),value:n.tag||jd},{label:t(`versionInfo.commit`),value:n.commitId?n.commitId.slice(0,8):jd,title:n.commitId,mono:!0},{label:t(`versionInfo.publishedAt`),value:Pd(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 Id(e){e.textContent=``;for(let n of Md){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 Ld(){let e=Nd(mt);return[`AI Helper v${e.version||jd}`,`${t(`versionInfo.tag`)}: ${e.tag||jd}`,`${t(`versionInfo.commit`)}: ${e.commitId||jd}`,`${t(`versionInfo.publishedAt`)}: ${Pd(e.publishedAt)}`].join(`
399
- `)}function Rd(){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`),Fd(a),o&&Id(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(Ld()),k(t(`common.copySuccess`),`success`)}catch{k(t(`common.copyFailed`),`error`)}})}var zd=null;function Bd(){if(!zd)return;zd.classList.remove(`open`);let e=zd.parentElement?zd.parentElement.querySelector(`.section-select-row`):null;e&&e.classList.remove(`open`),zd=null}function Vd(){return`<input type="search" class="section-select-search" placeholder="${t(`sectionSelect.searchPlaceholder`)}" data-i18n-placeholder="sectionSelect.searchPlaceholder" spellcheck="false">`}function Hd(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 Ud(e,t){Bd(),e.classList.add(`open`),t.classList.add(`open`),zd=e;let n=e.querySelector(`.section-select-search`);n&&(n.value=``,Hd(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===zd?Bd():Ud(e,t);return}zd&&!zd.parentElement.contains(e.target)&&Bd()}),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&&Hd(n,t.value)});var Wd=!1;async function Gd(){document.getElementById(`providerList`)&&(Wd||(Wd=!0,Jd(),Yd()),await Kd())}async function Kd(){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=Vd();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(),Bd(),qd(t.id)}),e.appendChild(r)}}async function qd(e){if(e===(await b()).activeProfileId)return;let t=await se(e);t&&(await Kd(),r.debug(`[SidePanel] provider switched:`,t.name))}function Jd(){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 Yd(){chrome.storage.onChanged.addListener((e,t)=>{t===`local`&&(e.modelProfiles||e.activeProfileId)&&Kd()})}var Xd=0;function Zd(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 Qd(e){let t=[];return e.querySelectorAll(`*`).forEach(e=>{getComputedStyle(e).position===`absolute`&&e.getClientRects().length>0&&t.push(e)}),t}function $d(e){e.forEach(e=>{(e.getAnimations?.()||[]).forEach(e=>{e.playState!==`idle`&&e.finish?.()})})}function ef(){Xd||=requestAnimationFrame(()=>{Xd=0,rf()})}function tf(){let e=document.getElementById(`selectionToggleGroup`),t=document.getElementById(`inputAddMenuSwitches`);e&&t&&e.parentElement!==t&&t.appendChild(e)}function nf(){let e=document.getElementById(`selectionToggleGroup`),t=document.querySelector(`.input-bottom-left`);e&&t&&e.parentElement!==t&&t.appendChild(e)}function rf(){let e=document.querySelector(`.input-bottom-row`),t=e?.closest(`.input-container`)||null;if(!(!e||!t)){t.classList.add(`measuring`);try{af(e,t)}finally{t.classList.remove(`measuring`)}}}function af(e,t){t.classList.remove(`temp-collapsed`,`agent-collapsed`,`switches-icon`,`selection-in-menu`),nf();let n=Qd(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]}),$d(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`),tf(),i()}function of(){rf(),window.addEventListener(`resize`,ef);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,ef())}).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=>!Zd(t.target,e)&&!r(t))&&ef()}).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 sf=50,cf=200,lf=200,uf=0,df=null,ff=[];function pf(e){return(e||``).replace(/\\/g,`/`).replace(/\/+/g,`/`)}function mf(e){let t=document.getElementById(`fileAtTitlePath`);if(!t)return;let n=e?pf(e):``;t.textContent=n,t.title=n}async function hf(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(),gf(),await Nr()})),ot(),t.style.display=`block`,n.classList.add(`show`),await _f(e)}function gf(){let e=document.getElementById(`fileAtSelector`),t=document.getElementById(`fileAtDropdown`);e&&(e.style.display=`none`),t&&t.classList.remove(`show`),v.selectedFileAtIndex=-1,df&&=(clearTimeout(df),null),uf++}function _f(e=``){let n=document.getElementById(`fileAtList`);if(!n)return;let i=++uf,a=e.trim();df&&clearTimeout(df);let o=async()=>{try{let e=await ya();if(i!==uf)return;if(mf(e),!e){n.innerHTML=`<div class="prompt-empty">${t(`fileSelector.noWorkspace`)}</div>`,v.selectedFileAtIndex=-1;return}let r;if(r=a?await ha(e,a,cf):((await ga(e)).entries||[]).map(t=>({name:t.name,type:t.type||`file`,size:t.size,mtime:t.mtime,fullPath:pf(`${e}/${t.name}`)})),i!==uf)return;yf(r,a,n,e)}catch(e){if(i!==uf)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>`,df=setTimeout(o,lf)):df=setTimeout(o,0)}function vf(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 yf(e,n,r,i){let a=vf(e,n),o=a.slice(0,sf),s=a.length>sf,c=pf(i);if(o.length===0){r.innerHTML=`<div class="prompt-empty">${t(`fileSelector.noMatch`)}</div>`,v.selectedFileAtIndex=-1;return}if(v.selectedFileAtIndex=0,ff=o,r.innerHTML=o.map((e,t)=>{let n=va(e.name,e.type),r=pf(e.fullPath),i=r.startsWith(c)?r.substring(c.length).replace(/^\//,``):r;return`
400
- <div class="prompt-item ${t===0?`selected`:``}" data-index="${t}" data-path="${A(r)}" title="${A(r)}">
397
+ ${e.icon||``}<span>${k(e.label)}</span>${pd(e.shortcut)}
398
+ </button>`}function hd(e,t,n){let r=dd();r.innerHTML=t.map((e,t)=>t===0&&e.divider?{...e,divider:!1}:e).map(e=>md(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 gd(e){if(e.status===O.DONE){let n=He(e),r=[{action:`restore`,label:t(`todo.restoreTo`,{status:Tu(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 _d(e,n){let r=Fu(n);r&&hd(e,[...gd(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 vd(e){let t=yd();t.length!==0&&hd(e,t,``)}function yd(){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 bd(){let{active:e,done:t}=_c(),n=await ol({counts:{all:e.length+t.length,active:e.length,done:t.length}});n&&xd(n.scope,n.format)}function xd(e,n){let{active:i,done:a}=_c(),o=[...i,...a];if(xe(o,e).length===0){A(t(`todo.exportEmptyToast`),`info`);return}try{A(t(`todo.exportedToast`,{name:zc(o,{scope:e,format:n})}),`success`)}catch(e){r.error(`[Todo] export failed:`,e),A(t(`todo.exportFailedToast`),`error`)}}async function Sd(){let e=await Bc();if(!e)return;let n=await Vc(e);if(!n.ok){A(t(n.reason===`json`?`todo.importJsonError`:`todo.importFormatError`),`error`);return}let{active:r,done:i}=_c(),a=await sl({count:n.todos.length,existing:r.length+i.length});if(!a)return;zl=`active`,q();let o=await Ac(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 Cd(e,n){let r=Fu(n);switch(e){case`set-doing`:J(Sc(n,O.DOING));return;case`set-pending`:J(Sc(n,O.PENDING));return;case`set-done`:Lu(n);return;case`restore`:Ru(n);return;case`edit-title`:Zu(n);return;case`edit-note`:Xu(n);return;case`set-due`:Vl=n,Zl=!0,q();return;case`edit-link`:$u(n);return;case`stats`:Sl();return;case`export-options`:bd();return;case`import-options`:Sd();return;case`delete`:await ud(t(`todo.deleteConfirmMsg`,{title:r?.title||``}),t(`todo.deleteConfirmTitle`))&&J(Dc(n),t(`todo.deletedToast`));return;default:}}function wd(e,t={}){let{active:n,done:r}=_c(),i=[...n,...r].find(t=>t.id===e);return i?Le(i,t):``}function Td(e){let n=wd(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(),ou(),A(t(`todo.filledToast`),`success`)}function Ed(e){let n=wd(e,{plain:!0});if(!n){A(t(`todo.emptyDigestToast`),`info`);return}Dd(n,t(`todo.copiedToast`))}function Dd(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 Od(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`));Ul={id:t.dataset.id,from:r.indexOf(t),list:n},t.classList.add(`dragging`);let{active:i,done:a}=_c(),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 kd(e){if(!Ul)return;e.preventDefault();let t=Ul.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=Ad();r>=n.length?t.appendChild(i):n[r].before(i)}function Ad(){let e=U.querySelector(`.todo-insert`);return e||(e=document.createElement(`div`),e.className=`todo-insert`,e)}function jd(e){if(!Ul)return;e.preventDefault();let t=Ul.list,n=U.querySelector(`.todo-insert`),r=Ul.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=Ul.from;Md(),i!==r&&J(Oc(i,r))}function Md(){Ul=null,U?.querySelectorAll(`.todo-item.dragging`).forEach(e=>e.classList.remove(`dragging`)),U?.querySelector(`.todo-insert`)?.remove()}var Nd=`—`,Pd=[{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 Fd(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 Id(e){if(!e)return Nd;let t=Date.parse(e);return Number.isNaN(t)?Nd:new Date(t).toLocaleString()}function Ld(e){let n=Fd(pt),r=[{label:t(`versionInfo.version`),value:n.version?`v${n.version}`:Nd},{label:t(`versionInfo.tag`),value:n.tag||Nd},{label:t(`versionInfo.commit`),value:n.commitId?n.commitId.slice(0,8):Nd,title:n.commitId,mono:!0},{label:t(`versionInfo.publishedAt`),value:Id(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 Rd(e){e.textContent=``;for(let n of Pd){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 zd(){let e=Fd(pt);return[`AI Helper v${e.version||Nd}`,`${t(`versionInfo.tag`)}: ${e.tag||Nd}`,`${t(`versionInfo.commit`)}: ${e.commitId||Nd}`,`${t(`versionInfo.publishedAt`)}: ${Id(e.publishedAt)}`].join(`
399
+ `)}function Bd(){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`),Ld(a),o&&Rd(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(zd()),A(t(`common.copySuccess`),`success`)}catch{A(t(`common.copyFailed`),`error`)}})}var Vd=null;function Hd(){if(!Vd)return;Vd.classList.remove(`open`);let e=Vd.parentElement?Vd.parentElement.querySelector(`.section-select-row`):null;e&&e.classList.remove(`open`),Vd=null}function Ud(){return`<input type="search" class="section-select-search" placeholder="${t(`sectionSelect.searchPlaceholder`)}" data-i18n-placeholder="sectionSelect.searchPlaceholder" spellcheck="false">`}function Wd(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 Gd(e,t){Hd(),e.classList.add(`open`),t.classList.add(`open`),Vd=e;let n=e.querySelector(`.section-select-search`);n&&(n.value=``,Wd(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===Vd?Hd():Gd(e,t);return}Vd&&!Vd.parentElement.contains(e.target)&&Hd()}),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&&Wd(n,t.value)});var Kd=!1;async function qd(){document.getElementById(`providerList`)&&(Kd||(Kd=!0,Xd(),Zd()),await Jd())}async function Jd(){let e=document.getElementById(`providerList`),t=document.getElementById(`providerSelectValue`),n=document.getElementById(`providerSelectHost`);if(!e)return;let r=await x(),i=r.profiles.find(e=>e.id===r.activeProfileId)||r.profiles[0];t&&(t.textContent=i?i.name:``),n&&(n.textContent=i?se(i.apiBase):``),e.innerHTML=Ud();let a=[...r.profiles].sort((e,t)=>w(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=se(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(),Hd(),Yd(t.id)}),e.appendChild(r)}}async function Yd(e){if(e===(await x()).activeProfileId)return;let t=await ae(e);t&&(await Jd(),r.debug(`[SidePanel] provider switched:`,t.name))}function Xd(){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 Zd(){chrome.storage.onChanged.addListener((e,t)=>{t===`local`&&(e.modelProfiles||e.activeProfileId)&&Jd()})}var Qd=0;function $d(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 ef(e){let t=[];return e.querySelectorAll(`*`).forEach(e=>{getComputedStyle(e).position===`absolute`&&e.getClientRects().length>0&&t.push(e)}),t}function tf(e){e.forEach(e=>{(e.getAnimations?.()||[]).forEach(e=>{e.playState!==`idle`&&e.finish?.()})})}function nf(){Qd||=requestAnimationFrame(()=>{Qd=0,of()})}function rf(){let e=document.getElementById(`selectionToggleGroup`),t=document.getElementById(`inputAddMenuSwitches`);e&&t&&e.parentElement!==t&&t.appendChild(e)}function af(){let e=document.getElementById(`selectionToggleGroup`),t=document.querySelector(`.input-bottom-left`);e&&t&&e.parentElement!==t&&t.appendChild(e)}function of(){let e=document.querySelector(`.input-bottom-row`),t=e?.closest(`.input-container`)||null;if(!(!e||!t)){t.classList.add(`measuring`);try{sf(e,t)}finally{t.classList.remove(`measuring`)}}}function sf(e,t){t.classList.remove(`temp-collapsed`,`agent-collapsed`,`switches-icon`,`selection-in-menu`),af();let n=ef(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]}),tf(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`),rf(),i()}function cf(){of(),window.addEventListener(`resize`,nf);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,nf())}).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=>!$d(t.target,e)&&!r(t))&&nf()}).observe(e,{subtree:!0,childList:!0,characterData:!0})}var lf=`footer-compact`,uf=`footer-compact-ultra`,df=`footer-wrap`,ff=`footer-measuring`,pf=0;function mf(){pf||=requestAnimationFrame(()=>{pf=0,gf()})}function hf(e){if(e.target.nodeType===1&&e.target.closest(`.message-footer`))return!0;for(let t of e.addedNodes)if(t.nodeType===1&&(t.classList?.contains(`message-footer`)||t.querySelector?.(`.message-footer`)||t.closest?.(`.message-footer`)))return!0;return!1}function gf(){let e=document.getElementById(`chatContainer`);if(!e)return;let t=e.querySelectorAll(`.message.assistant .message-footer`);if(t.length){t.forEach(e=>{e.classList.add(ff),e.classList.remove(lf,uf,df)});try{let e=[...t].filter(e=>e.clientWidth>0&&e.scrollWidth>e.clientWidth);e.forEach(e=>e.classList.add(lf)),e=e.filter(e=>e.scrollWidth>e.clientWidth),e.forEach(e=>e.classList.add(uf)),e=e.filter(e=>e.scrollWidth>e.clientWidth),e.forEach(e=>e.classList.add(df))}finally{t.forEach(e=>e.classList.remove(ff))}}}function _f(){let e=document.getElementById(`chatContainer`);if(e){if(gf(),window.addEventListener(`resize`,mf),typeof ResizeObserver<`u`){let t=e.clientWidth;new ResizeObserver(()=>{let n=e.clientWidth;Math.abs(n-t)<1||(t=n,mf())}).observe(e)}typeof MutationObserver<`u`&&new MutationObserver(e=>{e.some(hf)&&mf()}).observe(e,{subtree:!0,childList:!0}),document.fonts?.ready?.then(mf).catch(()=>{})}}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 vf=50,yf=200,bf=200,xf=0,Sf=null,Cf=[];function wf(e){return(e||``).replace(/\\/g,`/`).replace(/\/+/g,`/`)}function Tf(e){let t=document.getElementById(`fileAtTitlePath`);if(!t)return;let n=e?wf(e):``;t.textContent=n,t.title=n}async function Ef(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(),Df(),await Mr()})),ot(),t.style.display=`block`,n.classList.add(`show`),await Of(e)}function Df(){let e=document.getElementById(`fileAtSelector`),t=document.getElementById(`fileAtDropdown`);e&&(e.style.display=`none`),t&&t.classList.remove(`show`),y.selectedFileAtIndex=-1,Sf&&=(clearTimeout(Sf),null),xf++}function Of(e=``){let n=document.getElementById(`fileAtList`);if(!n)return;let i=++xf,a=e.trim();Sf&&clearTimeout(Sf);let o=async()=>{try{let e=await va();if(i!==xf)return;if(Tf(e),!e){n.innerHTML=`<div class="prompt-empty">${t(`fileSelector.noWorkspace`)}</div>`,y.selectedFileAtIndex=-1;return}let r;if(r=a?await ma(e,a,yf):((await ha(e)).entries||[]).map(t=>({name:t.name,type:t.type||`file`,size:t.size,mtime:t.mtime,fullPath:wf(`${e}/${t.name}`)})),i!==xf)return;Af(r,a,n,e)}catch(e){if(i!==xf)return;r.warn(`[FileAtSelector] search failed:`,e.message),n.innerHTML=`<div class="prompt-empty">${t(`fileSelector.loadFailed`,{error:e.message})}</div>`,y.selectedFileAtIndex=-1}};a?(n.innerHTML=`<div class="prompt-empty">${t(`fileSelector.searching`)}</div>`,Sf=setTimeout(o,bf)):Sf=setTimeout(o,0)}function kf(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 Af(e,n,r,i){let a=kf(e,n),o=a.slice(0,vf),s=a.length>vf,c=wf(i);if(o.length===0){r.innerHTML=`<div class="prompt-empty">${t(`fileSelector.noMatch`)}</div>`,y.selectedFileAtIndex=-1;return}if(y.selectedFileAtIndex=0,Cf=o,r.innerHTML=o.map((e,t)=>{let n=_a(e.name,e.type),r=wf(e.fullPath),i=r.startsWith(c)?r.substring(c.length).replace(/^\//,``):r;return`
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
- <span class="prompt-item-content">${A(e.name)}</span>
404
- <span class="file-at-path">${A(i)}</span>
403
+ <span class="prompt-item-content">${k(e.name)}</span>
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:sf}),r.appendChild(e)}r.querySelectorAll(`.prompt-item`).forEach(e=>{e.addEventListener(`click`,()=>{bf(ff.find(t=>t.fullPath===e.dataset.path)||e.dataset.path)})})}function bf(e){if(!(typeof e==`string`?e:e&&e.fullPath))return;let t=document.getElementById(`userInput`);if(t){let e=Hr(t.value,t.selectionStart,`dollar`);e&&(t.value=e.value,t.selectionStart=t.selectionEnd=e.caret),t.focus()}gf(),li([e]),gt()}function xf(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 Sf=null,J=null,Cf=null,wf=null,Tf=null,Y=null,X=null,Ef=[],Df=0,Of=()=>{},kf=[{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`}],Af=new Set([`screenshot`]),jf={prompts:{titleKey:`promptManager.title`,action:()=>xn()},skills:{titleKey:`promptSelector.skillManageTitle`,action:()=>Mf(`toolbox`)},mcp:{titleKey:`promptSelector.mcpManageTitle`,action:()=>Mf(`toolbox`)},pages:{titleKey:`pageSelector.openNewTab`,action:()=>chrome.tabs.create({})},knowledge:{titleKey:`header.manageKnowledge`,action:()=>Mf(`knowledge`)},agents:{titleKey:`header.addEditAssistant`,action:()=>yi(null)},proxies:{titleKey:`header.addEditAgent`,action:()=>Mf(`agent`)},workspace:{titleKey:`workspace.openPanel`,action:()=>Nr()}};function Mf(e){chrome.runtime.sendMessage({type:`OPEN_OPTIONS_PAGE`,hash:e})}function Nf(){if(!Tf)return;let e=X?jf[X]:null;if(!e){Tf.style.display=`none`;return}let n=t(e.titleKey);Tf.title=n,Tf.setAttribute(`aria-label`,n),Tf.style.display=`flex`}function Pf(){wf&&(wf.style.display=Af.has(X)?`none`:``)}function Ff(e={}){if(Of=typeof e.onRequestClose==`function`?e.onRequestClose:()=>{},Sf=document.getElementById(`inputAddPanel`),J=document.getElementById(`inputAddPanelSearch`),Cf=document.getElementById(`inputAddPanelSearchClear`),Tf=document.getElementById(`inputAddPanelManage`),wf=document.getElementById(`inputAddPanelSearchWrap`),Y=document.getElementById(`inputAddPanelList`),!(!Sf||!J||!Y)){if(Tf&&Tf.addEventListener(`click`,()=>{let e=X?jf[X]:null;e&&(Of(),e.action())}),Cf){let e=t(`input.addMenuPanelClear`);Cf.title=e,Cf.setAttribute(`aria-label`,e),Cf.addEventListener(`click`,()=>{J.value=``,Gf(),If(),J.focus()})}J.addEventListener(`input`,()=>{Gf(),If()})}}function If(){Cf&&J&&(Cf.style.display=J.value?`flex`:`none`)}function Lf(){return!!X}function Rf(){return X}function zf(){return!!J&&document.activeElement===J}async function Bf(e){if(!Sf||!e||X===e&&Sf.style.display!==`none`)return;X=e,Nf(),Pf(),J&&(J.value=``,J.placeholder=t(`input.addMenuPanelSearchPlaceholder`),If()),Sf.style.display=`flex`;let n=++Df;Y&&(Y.innerHTML=`<div class="prompt-empty">${t(`input.addMenuPanelLoading`)}</div>`);try{let t=await Hf(e);if(n!==Df)return;Ef=Array.isArray(t)?t:[],Gf()}catch(e){if(n!==Df)return;r.warn(`[InputAddPanel] load failed:`,e&&e.message),Ef=[],Y&&(Y.innerHTML=`<div class="prompt-empty">${t(`input.addMenuPanelEmpty`)}</div>`)}}function Vf(){X=null,Nf(),Pf(),Ef=[],Df++,J&&(J.value=``,If()),Y&&(Y.innerHTML=``),Sf&&(Sf.style.display=`none`)}function Hf(e){switch(e){case`prompts`:return Promise.resolve(v.customPrompts||[]);case`skills`:return Br(!0);case`mcp`:return Mr();case`pages`:return Bn();case`knowledge`:return Yt().then(e=>e.ok?e.collections:[]);case`agents`:return ma();case`proxies`:return fr();case`workspace`:return Uf();case`screenshot`:return Promise.resolve(kf);default:return Promise.resolve([])}}async function Uf(){let e=await ya();if(!e)return[];let t=await ga(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 Wf(e){if(!e)return Ef;let n=e.toLowerCase();return Ef.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(Ai(e)||``).toLowerCase().includes(n)||String(fn(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 Gf(){if(!Y)return;let e=J?J.value.trim():``,n=Wf(e);if(n.length===0){Y.innerHTML=`<div class="prompt-empty">${t(e?`input.addMenuPanelNoMatch`:`input.addMenuPanelEmpty`)}</div>`;return}Y.innerHTML=n.map(e=>Kf(e)).join(``),Y.querySelectorAll(`.input-add-panel-item`).forEach(e=>{e.addEventListener(`click`,t=>qf(t,e))}),Y.querySelectorAll(`img.favicon-img`).forEach(e=>{e.addEventListener(`error`,()=>{e.style.display=`none`})}),X===`proxies`&&n.forEach(e=>Lr(e)),X===`skills`&&_r(),X===`mcp`&&Wr(),X===`knowledge`&&xt()}function Kf(e){switch(X){case`prompts`:return`<div class="prompt-item input-add-panel-item input-add-panel-item-two-line" data-code="${A(e.code)}" title="${O(e.content||``)}">
407
- <span class="input-add-panel-item-title"><span class="input-add-panel-item-inline-icon">${Pt}</span>/${A(e.code)}</span>
408
- <span class="input-add-panel-item-sub">${A(e.content||``)}</span>
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="${A(e.name)}" title="${O(r)}">
410
- <span class="input-add-panel-item-title">🧩 ${A(e.name)}</span>
411
- ${i?`<span class="input-add-panel-item-sub" title="${O(i)}">${A(i)}</span>`:``}
412
- </div>`}case`mcp`:{let n=e.effectiveOpen===!1,r=n?`${e.serverName}\n${t(`skillSelector.mcpInactiveTooltip`)}`:e.serverName;return`<div class="mcp-list-item input-add-panel-item input-add-panel-item-two-line${n?` mcp-list-item-inactive`:``}" data-server-id="${A(e.serverId)}" data-server-name="${A(e.serverName)}" title="${O(r)}">
413
- <span class="input-add-panel-item-title">🔌 ${A(e.serverName)}${n?` <span class="mcp-list-item-badge mcp-badge-inactive">${t(`skillSelector.mcpInactiveBadge`)}</span>`:``}</span>
414
- <span class="input-add-panel-item-sub" title="${O(e.serverId||``)}">${A(e.serverId||``)}</span>
415
- </div>`}case`pages`:{let t=e.title||e.url||``,n=!!(v.selectedPage&&v.selectedPage.id===e.id),r=e.favIconUrl?`<img src="${O(e.favIconUrl)}" width="14" height="14" class="favicon-img" alt="">`:`<span class="input-add-panel-item-inline-icon">🌐</span>`;return`<div class="prompt-item input-add-panel-item input-add-panel-item-two-line" data-tab-id="${e.id}">
416
- <span class="input-add-panel-item-title">${r}${A(t)}</span>
417
- <span class="input-add-panel-item-sub">${A(e.url||``)}</span>
406
+ `}).join(``),s){let e=document.createElement(`div`);e.className=`file-at-truncated`,e.textContent=t(`fileSelector.truncated`,{count:vf}),r.appendChild(e)}r.querySelectorAll(`.prompt-item`).forEach(e=>{e.addEventListener(`click`,()=>{jf(Cf.find(t=>t.fullPath===e.dataset.path)||e.dataset.path)})})}function jf(e){if(!(typeof e==`string`?e:e&&e.fullPath))return;let t=document.getElementById(`userInput`);if(t){let e=Vr(t.value,t.selectionStart,`dollar`);e&&(t.value=e.value,t.selectionStart=t.selectionEnd=e.caret),t.focus()}Df(),ci([e]),rt()}function Mf(e){let t=y.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 Nf=null,Y=null,Pf=null,Ff=null,If=null,Lf=null,X=null,Rf=[],zf=0,Bf=()=>{},Vf=[{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`}],Hf=new Set([`screenshot`]),Uf={prompts:{titleKey:`promptManager.title`,action:()=>bn()},skills:{titleKey:`promptSelector.skillManageTitle`,action:()=>Wf(`toolbox`)},mcp:{titleKey:`promptSelector.mcpManageTitle`,action:()=>Wf(`toolbox`)},pages:{titleKey:`pageSelector.openNewTab`,action:()=>chrome.tabs.create({})},knowledge:{titleKey:`header.manageKnowledge`,action:()=>Wf(`knowledge`)},agents:{titleKey:`header.addEditAssistant`,action:()=>vi(null)},proxies:{titleKey:`header.addEditAgent`,action:()=>Wf(`agent`)},workspace:{titleKey:`workspace.openPanel`,action:()=>Mr()}};function Wf(e){chrome.runtime.sendMessage({type:`OPEN_OPTIONS_PAGE`,hash:e})}function Gf(){if(!If)return;let e=X?Uf[X]:null;if(!e){If.style.display=`none`;return}let n=t(e.titleKey);If.title=n,If.setAttribute(`aria-label`,n),If.style.display=`flex`}function Kf(){Ff&&(Ff.style.display=Hf.has(X)?`none`:``)}function qf(e={}){if(Bf=typeof e.onRequestClose==`function`?e.onRequestClose:()=>{},Nf=document.getElementById(`inputAddPanel`),Y=document.getElementById(`inputAddPanelSearch`),Pf=document.getElementById(`inputAddPanelSearchClear`),If=document.getElementById(`inputAddPanelManage`),Ff=document.getElementById(`inputAddPanelSearchWrap`),Lf=document.getElementById(`inputAddPanelList`),!(!Nf||!Y||!Lf)){if(If&&If.addEventListener(`click`,()=>{let e=X?Uf[X]:null;e&&(Bf(),e.action())}),Pf){let e=t(`input.addMenuPanelClear`);Pf.title=e,Pf.setAttribute(`aria-label`,e),Pf.addEventListener(`click`,()=>{Y.value=``,rp(),Jf(),Y.focus()})}Y.addEventListener(`input`,()=>{rp(),Jf()})}}function Jf(){Pf&&Y&&(Pf.style.display=Y.value?`flex`:`none`)}function Yf(){return!!X}function Xf(){return X}function Zf(){return!!Y&&document.activeElement===Y}async function Qf(e){if(!Nf||!e||X===e&&Nf.style.display!==`none`)return;X=e,Gf(),Kf(),Y&&(Y.value=``,Y.placeholder=t(`input.addMenuPanelSearchPlaceholder`),Jf()),Nf.style.display=`flex`;let n=++zf;Lf&&(Lf.innerHTML=`<div class="prompt-empty">${t(`input.addMenuPanelLoading`)}</div>`);try{let t=await ep(e);if(n!==zf)return;Rf=Array.isArray(t)?t:[],rp()}catch(e){if(n!==zf)return;r.warn(`[InputAddPanel] load failed:`,e&&e.message),Rf=[],Lf&&(Lf.innerHTML=`<div class="prompt-empty">${t(`input.addMenuPanelEmpty`)}</div>`)}}function $f(){X=null,Gf(),Kf(),Rf=[],zf++,Y&&(Y.value=``,Jf()),Lf&&(Lf.innerHTML=``),Nf&&(Nf.style.display=`none`)}function ep(e){switch(e){case`prompts`:return Promise.resolve(y.customPrompts||[]);case`skills`:return zr(!0);case`mcp`:return jr();case`pages`:return zn();case`knowledge`:return Jt().then(e=>e.ok?e.collections:[]);case`agents`:return pa();case`proxies`:return dr();case`workspace`:return tp();case`screenshot`:return Promise.resolve(Vf);default:return Promise.resolve([])}}async function tp(){let e=await va();if(!e)return[];let t=await ha(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 np(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(ki(e)||``).toLowerCase().includes(n)||String(dn(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 rp(){if(!Lf)return;let e=Y?Y.value.trim():``,n=np(e);if(n.length===0){Lf.innerHTML=`<div class="prompt-empty">${t(e?`input.addMenuPanelNoMatch`:`input.addMenuPanelEmpty`)}</div>`;return}Lf.innerHTML=n.map(e=>ip(e)).join(``),Lf.querySelectorAll(`.input-add-panel-item`).forEach(e=>{e.addEventListener(`click`,t=>ap(t,e))}),Lf.querySelectorAll(`img.favicon-img`).forEach(e=>{e.addEventListener(`error`,()=>{e.style.display=`none`})}),X===`proxies`&&n.forEach(e=>Ir(e)),X===`skills`&&gr(),X===`mcp`&&Ur(),X===`knowledge`&&bt()}function ip(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
+ <span class="input-add-panel-item-title"><span class="input-add-panel-item-inline-icon">${Nt}</span>/${k(e.code)}</span>
408
+ <span class="input-add-panel-item-sub">${k(e.content||``)}</span>
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)}">
410
+ <span class="input-add-panel-item-title">🧩 ${k(e.name)}</span>
411
+ ${i?`<span class="input-add-panel-item-sub" title="${j(i)}">${k(i)}</span>`:``}
412
+ </div>`}case`mcp`:{let n=e.effectiveOpen===!1,r=n?`${e.serverName}\n${t(`skillSelector.mcpInactiveTooltip`)}`:e.serverName;return`<div class="mcp-list-item input-add-panel-item input-add-panel-item-two-line${n?` mcp-list-item-inactive`:``}" data-server-id="${k(e.serverId)}" data-server-name="${k(e.serverName)}" title="${j(r)}">
413
+ <span class="input-add-panel-item-title">🔌 ${k(e.serverName)}${n?` <span class="mcp-list-item-badge mcp-badge-inactive">${t(`skillSelector.mcpInactiveBadge`)}</span>`:``}</span>
414
+ <span class="input-add-panel-item-sub" title="${j(e.serverId||``)}">${k(e.serverId||``)}</span>
415
+ </div>`}case`pages`:{let t=e.title||e.url||``,n=!!(y.selectedPage&&y.selectedPage.id===e.id),r=e.favIconUrl?`<img src="${j(e.favIconUrl)}" width="14" height="14" class="favicon-img" alt="">`:`<span class="input-add-panel-item-inline-icon">🌐</span>`;return`<div class="prompt-item input-add-panel-item input-add-panel-item-two-line" data-tab-id="${e.id}">
416
+ <span class="input-add-panel-item-title">${r}${k(t)}</span>
417
+ <span class="input-add-panel-item-sub">${k(e.url||``)}</span>
418
418
  ${n?`<span class="page-selected-mark">✓</span>`:``}
419
- </div>`}case`knowledge`:{let n=e.enabled===!1;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="${A(e.id)}" data-kb-name="${A(e.name||``)}" data-kb-disabled="${n?`1`:`0`}"${n?` title="${O(t(`knowledgeSelector.disabledTooltip`))}"`:``}>
420
- <span class="input-add-panel-item-title">📚 ${A(e.name||``)}${n?` <span class="knowledge-item-badge badge-disabled">${t(`knowledgeSelector.disabledBadge`)}</span>`:``}</span>
421
- <span class="input-add-panel-item-sub">${Vi(e)}</span>
422
- </div>`}case`agents`:{let n=Ai(e),r=fn(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="${A(e.id)}">
423
- <span class="input-add-panel-item-title">${A([e.icon,n].filter(Boolean).join(` `))}</span>
424
- <span class="input-add-panel-item-sub">${A(r||o)}</span>
419
+ </div>`}case`knowledge`:{let n=e.enabled===!1;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
+ <span class="input-add-panel-item-title">📚 ${k(e.name||``)}${n?` <span class="knowledge-item-badge badge-disabled">${t(`knowledgeSelector.disabledBadge`)}</span>`:``}</span>
421
+ <span class="input-add-panel-item-sub">${Bi(e)}</span>
422
+ </div>`}case`agents`:{let n=ki(e),r=dn(e),i=e.id===y.activeAgentId||!y.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
+ <span class="input-add-panel-item-title">${k([e.icon,n].filter(Boolean).join(` `))}</span>
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=cn(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="${A(e.id)}">
427
- <span class="input-add-panel-item-title"><span class="agent-at-dot agent-at-dot-${cr(e,i)}"></span>${A(n)}</span>
428
- <span class="input-add-panel-item-sub">${A(e.url||``)}</span>
426
+ </div>`}case`proxies`:{let n=e.name||t(`promptSelector.unnamedProxy`),r=sn(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-${sr(e,i)}"></span>${k(n)}</span>
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
- </div>`}case`workspace`:{let t=e.type===`directory`;return`<div class="prompt-item input-add-panel-item" data-path="${A(e.fullPath)}" title="${O(e.fullPath)}">
431
- <span class="input-add-panel-item-icon">${va(e.name,e.type)}</span>
432
- <span class="input-add-panel-item-title">${A(e.name)}${t?`/`:``}</span>
433
- ${!t&&e.size!=null?`<span class="input-add-panel-item-sub">${A(_a(e.size))}</span>`:``}
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">${_a(e.name,e.type)}</span>
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(ga(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
- <span class="input-add-panel-item-title">${e.icon} ${A(t(e.nameKey))}</span>
436
- <span class="input-add-panel-item-sub">${A(t(e.descKey))}</span>
437
- <kbd class="input-add-panel-item-kbd">${A(e.kbd)}</kbd>
438
- </div>`;default:return``}}async function qf(e,t){let n=e.ctrlKey||e.metaKey;switch(X){case`prompts`:{let e=t.dataset.code;n?ti(e,{skipTriggerStrip:!0}):_n(e),Of();break}case`skills`:na(t.dataset.skillName,Ef,{clearTrigger:!1}),n&&Of();break;case`mcp`:Tr(t.dataset.serverId,t.dataset.serverName,Ef,{clearTrigger:!1}),n&&Of();break;case`pages`:{let e=Ef.find(e=>String(e.id)===t.dataset.tabId);if(e){kt(e);let t=document.getElementById(`userInput`);t&&t.focus(),gt()}Of();break}case`knowledge`:if(e.target.closest(`.kb-docs-link`)){e.stopPropagation(),Of(),In(t.dataset.kbId);break}Qr({id:t.dataset.kbId,name:t.dataset.kbName,enabled:t.dataset.kbDisabled!==`1`},{clearTrigger:!1}),n&&Of();break;case`agents`:await Mi(t.dataset.agentId,{clearTrigger:!1}),Of();break;case`proxies`:await Sr(t.dataset.proxyId,{clearTrigger:!1}),Of();break;case`workspace`:{let e=Ef.find(e=>e.fullPath===t.dataset.path);if(e){let t=document.getElementById(`userInput`);t&&t.focus(),await li([e]),gt()}Of();break}case`screenshot`:Of(),await(t.dataset.shotAction===`region`?Gr:Yr)();break;default:break}}var Jf=0,Yf=200,Xf=150,Zf={promptTriggerBtn:`prompts`,addMenuSkillBtn:`skills`,addMenuMcpBtn:`mcp`,addMenuPageBtn:`pages`,addMenuKnowledgeBtn:`knowledge`,addMenuAgentBtn:`agents`,addMenuProxyBtn:`proxies`,addMenuWorkspaceBtn:`workspace`,screenshotBtn:`screenshot`};async function Qf(){let e=[{id:`addMenuSkillBtn`,available:()=>At()},{id:`addMenuMcpBtn`,available:()=>Vn()},{id:`addMenuKnowledgeBtn`,available:async()=>(await Yt()).ok},{id:`addMenuProxyBtn`,available:async()=>(await fr()).length>0},{id:`addMenuWorkspaceBtn`,available:async()=>!!await ya()}],t=++Jf;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===Jf&&(r.style.display=i?``:`none`)}))}function $f(){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=Lf()?Rf():null;t.querySelectorAll(`.input-add-item`).forEach(t=>{t.classList.toggle(`panel-active`,!!e&&Zf[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(),Qf()):(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&&(ai(),gr(),gf()),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,!zf()&&(Vf(),s())},Xf)};r&&r.addEventListener(`mouseover`,e=>{if(!u())return;let t=e.target.closest(`.input-add-item`),n=t?Zf[t.id]:null;if(!n){d();return}a&&=(clearTimeout(a),null),!(Lf()&&Rf()===n)&&(i&&clearTimeout(i),i=setTimeout(async()=>{i=null;let e=Bf(n);c(t);try{await e}catch{}c(t),s()},Yf))}),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`,()=>{Lf()&&c()}),[{id:`promptTriggerBtn`,open:()=>kn(``,`prompts`)},{id:`addMenuSkillBtn`,open:()=>kn(``,`skills`)},{id:`addMenuMcpBtn`,open:()=>kn(``,`mcp`)},{id:`addMenuPageBtn`,open:()=>bi(``,`pages`)},{id:`addMenuKnowledgeBtn`,open:()=>bi(``,`knowledge`)},{id:`addMenuAgentBtn`,open:()=>bi(``,`agents`)},{id:`addMenuProxyBtn`,open:()=>bi(``,`proxies`)},{id:`addMenuWorkspaceBtn`,open:()=>hf(``)}].forEach(({id:e,open:t})=>{let n=document.getElementById(e);n&&n.addEventListener(`click`,async e=>{e.stopPropagation(),n.blur(),ai(),gr(),gf();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 ep=`usageTipsEnabled`,tp=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 np=[{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,rp=null,ip=null,ap=null,op=null,sp=!1,cp=null,lp=!0,up=null;function dp(){return v.agentPlatform?.connected===!0}function fp(){let e=a();return np.filter(e=>e.scene!==`agent`||dp()).map(t=>({id:t.id,text:e===`en`?t.en:t.zh}))}function pp(e){let t=e.findIndex(e=>e.id===cp);return t>=0?t:0}function mp(){if(!Z||!rp)return;let e=rp.scrollWidth>rp.clientWidth+1;Z.classList.toggle(`is-truncated`,e)}function hp(e,t){if(!rp||!e.length)return;let n=e[t%e.length];cp=n.id,rp.textContent=n.text,ip&&(ip.textContent=n.text),mp(),rp.classList.remove(`fade-in`),rp.offsetWidth,rp.classList.add(`fade-in`)}function gp(){if(!lp||!Z||Z.style.display===`none`)return;let e=fp();e.length&&hp(e,pp(e)+1)}function _p(){op&&=(clearInterval(op),null)}function vp(){_p(),!(!lp||sp)&&(op=setInterval(gp,tp))}function yp(){if(!lp||!Z)return;let e=fp();if(!e.length){xp();return}e.some(e=>e.id===cp)?hp(e,pp(e)):(cp=null,hp(e,0))}function bp(){if(!Z)return;lp=!0,Z.style.display=``;let e=fp();if(!e.length){xp();return}hp(e,pp(e)),vp()}function xp(){Z&&(Z.style.display=`none`,_p())}function Sp(){Z.addEventListener(`mouseenter`,()=>{sp=!0,_p()}),Z.addEventListener(`mouseleave`,()=>{sp=!1,vp()}),ap.addEventListener(`click`,e=>{e.stopPropagation(),Cp(),k(t(`usageTips.dismissedHint`),`info`,5e3)}),chrome.storage.onChanged.addListener((e,t)=>{t!==`local`||!e[ep]||(e[ep].newValue===!1?(lp=!1,xp()):bp())}),document.addEventListener(`agent-connection-changed`,yp),o(yp),typeof ResizeObserver<`u`&&new ResizeObserver(mp).observe(Z)}function Cp(){lp=!1,xp();try{chrome.storage.local.set({[ep]:!1})}catch{}}function wp(){if(Z=document.getElementById(`usageTipsBar`),rp=document.getElementById(`usageTipsText`),ip=document.getElementById(`usageTipsTooltip`),ap=document.getElementById(`usageTipsDismiss`),!(!Z||!rp||!ip||!ap)){Sp(),up=document.getElementById(`chatContainer`),up&&(up.appendChild(Z),typeof MutationObserver<`u`&&new MutationObserver(()=>{up.querySelectorAll(`.usage-tips-bar`).forEach(e=>{e!==Z&&e.remove()}),(Z.parentNode!==up||Z.nextElementSibling)&&up.appendChild(Z)}).observe(up,{childList:!0}));try{chrome.storage.local.get([ep],e=>{lp=e?.[ep]!==!1,lp?bp():xp()})}catch{bp()}}}function Tp({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(`
435
+ <span class="input-add-panel-item-title">${e.icon} ${k(t(e.nameKey))}</span>
436
+ <span class="input-add-panel-item-sub">${k(t(e.descKey))}</span>
437
+ <kbd class="input-add-panel-item-kbd">${k(e.kbd)}</kbd>
438
+ </div>`;default:return``}}async function ap(e,t){let n=e.ctrlKey||e.metaKey;switch(X){case`prompts`:{let e=t.dataset.code;n?ei(e,{skipTriggerStrip:!0}):gn(e),Bf();break}case`skills`:ta(t.dataset.skillName,Rf,{clearTrigger:!1}),n&&Bf();break;case`mcp`:wr(t.dataset.serverId,t.dataset.serverName,Rf,{clearTrigger:!1}),n&&Bf();break;case`pages`:{let e=Rf.find(e=>String(e.id)===t.dataset.tabId);if(e){Ot(e);let t=document.getElementById(`userInput`);t&&t.focus(),rt()}Bf();break}case`knowledge`:if(e.target.closest(`.kb-docs-link`)){e.stopPropagation(),Bf(),Fn(t.dataset.kbId);break}Zr({id:t.dataset.kbId,name:t.dataset.kbName,enabled:t.dataset.kbDisabled!==`1`},{clearTrigger:!1}),n&&Bf();break;case`agents`:await ji(t.dataset.agentId,{clearTrigger:!1}),Bf();break;case`proxies`:await xr(t.dataset.proxyId,{clearTrigger:!1}),Bf();break;case`workspace`:{let e=Rf.find(e=>e.fullPath===t.dataset.path);if(e){let t=document.getElementById(`userInput`);t&&t.focus(),await ci([e]),rt()}Bf();break}case`screenshot`:Bf(),await(t.dataset.shotAction===`region`?Wr:Jr)();break;default:break}}var op=0,sp=200,cp=150,lp={promptTriggerBtn:`prompts`,addMenuSkillBtn:`skills`,addMenuMcpBtn:`mcp`,addMenuPageBtn:`pages`,addMenuKnowledgeBtn:`knowledge`,addMenuAgentBtn:`agents`,addMenuProxyBtn:`proxies`,addMenuWorkspaceBtn:`workspace`,screenshotBtn:`screenshot`};async function up(){let e=[{id:`addMenuSkillBtn`,available:()=>kt()},{id:`addMenuMcpBtn`,available:()=>Bn()},{id:`addMenuKnowledgeBtn`,available:async()=>(await Jt()).ok},{id:`addMenuProxyBtn`,available:async()=>(await dr()).length>0},{id:`addMenuWorkspaceBtn`,available:async()=>!!await va()}],t=++op;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===op&&(r.style.display=i?``:`none`)}))}function dp(){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=Yf()?Xf():null;t.querySelectorAll(`.input-add-item`).forEach(t=>{t.classList.toggle(`panel-active`,!!e&&lp[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?($f(),s(),up()):(i&&=(clearTimeout(i),null),a&&=(clearTimeout(a),null),$f(),s())},u=()=>t.style.display!==`none`;qf({onRequestClose:()=>l(!1)}),e.addEventListener(`click`,e=>{e.stopPropagation();let t=!u();t&&(ii(),hr(),Df()),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,!Zf()&&($f(),s())},cp)};r&&r.addEventListener(`mouseover`,e=>{if(!u())return;let t=e.target.closest(`.input-add-item`),n=t?lp[t.id]:null;if(!n){d();return}a&&=(clearTimeout(a),null),!(Yf()&&Xf()===n)&&(i&&clearTimeout(i),i=setTimeout(async()=>{i=null;let e=Qf(n);c(t);try{await e}catch{}c(t),s()},sp))}),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`,()=>{Yf()&&c()}),[{id:`promptTriggerBtn`,open:()=>On(``,`prompts`)},{id:`addMenuSkillBtn`,open:()=>On(``,`skills`)},{id:`addMenuMcpBtn`,open:()=>On(``,`mcp`)},{id:`addMenuPageBtn`,open:()=>yi(``,`pages`)},{id:`addMenuKnowledgeBtn`,open:()=>yi(``,`knowledge`)},{id:`addMenuAgentBtn`,open:()=>yi(``,`agents`)},{id:`addMenuProxyBtn`,open:()=>yi(``,`proxies`)},{id:`addMenuWorkspaceBtn`,open:()=>Ef(``)}].forEach(({id:e,open:t})=>{let n=document.getElementById(e);n&&n.addEventListener(`click`,async e=>{e.stopPropagation(),n.blur(),ii(),hr(),Df();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 fp=`usageTipsEnabled`,pp=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 mp=[{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,hp=null,gp=null,_p=null,vp=null,yp=!1,bp=null,xp=!0,Sp=null;function Cp(){return y.agentPlatform?.connected===!0}function wp(){let e=a();return mp.filter(e=>e.scene!==`agent`||Cp()).map(t=>({id:t.id,text:e===`en`?t.en:t.zh}))}function Tp(e){let t=e.findIndex(e=>e.id===bp);return t>=0?t:0}function Ep(){if(!Z||!hp)return;let e=hp.scrollWidth>hp.clientWidth+1;Z.classList.toggle(`is-truncated`,e)}function Dp(e,t){if(!hp||!e.length)return;let n=e[t%e.length];bp=n.id,hp.textContent=n.text,gp&&(gp.textContent=n.text),Ep(),hp.classList.remove(`fade-in`),hp.offsetWidth,hp.classList.add(`fade-in`)}function Op(){if(!xp||!Z||Z.style.display===`none`)return;let e=wp();e.length&&Dp(e,Tp(e)+1)}function kp(){vp&&=(clearInterval(vp),null)}function Ap(){kp(),!(!xp||yp)&&(vp=setInterval(Op,pp))}function jp(){if(!xp||!Z)return;let e=wp();if(!e.length){Np();return}e.some(e=>e.id===bp)?Dp(e,Tp(e)):(bp=null,Dp(e,0))}function Mp(){if(!Z)return;xp=!0,Z.style.display=``;let e=wp();if(!e.length){Np();return}Dp(e,Tp(e)),Ap()}function Np(){Z&&(Z.style.display=`none`,kp())}function Pp(){Z.addEventListener(`mouseenter`,()=>{yp=!0,kp()}),Z.addEventListener(`mouseleave`,()=>{yp=!1,Ap()}),_p.addEventListener(`click`,e=>{e.stopPropagation(),Fp(),A(t(`usageTips.dismissedHint`),`info`,5e3)}),chrome.storage.onChanged.addListener((e,t)=>{t!==`local`||!e[fp]||(e[fp].newValue===!1?(xp=!1,Np()):Mp())}),document.addEventListener(`agent-connection-changed`,jp),o(jp),typeof ResizeObserver<`u`&&new ResizeObserver(Ep).observe(Z)}function Fp(){xp=!1,Np();try{chrome.storage.local.set({[fp]:!1})}catch{}}function Ip(){if(Z=document.getElementById(`usageTipsBar`),hp=document.getElementById(`usageTipsText`),gp=document.getElementById(`usageTipsTooltip`),_p=document.getElementById(`usageTipsDismiss`),!(!Z||!hp||!gp||!_p)){Pp(),Sp=document.getElementById(`chatContainer`),Sp&&(Sp.appendChild(Z),typeof MutationObserver<`u`&&new MutationObserver(()=>{Sp.querySelectorAll(`.usage-tips-bar`).forEach(e=>{e!==Z&&e.remove()}),(Z.parentNode!==Sp||Z.nextElementSibling)&&Sp.appendChild(Z)}).observe(Sp,{childList:!0}));try{chrome.storage.local.get([fp],e=>{xp=e?.[fp]!==!1,xp?Mp():Np()})}catch{Mp()}}}function Lp({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 Ep(e,t){let n;return function(...r){clearTimeout(n),n=setTimeout(()=>{clearTimeout(n),e(...r)},t)}}var Dp=null,Op=null,kp=null,Ap=null,jp=null,Mp=null,Np=null,Pp=null,Fp=null,Ip=null,Lp=!1,Rp=!1,zp=null,Bp={[ri.DISPATCHING]:`queue.statusDispatching`,[ri.INJECTING]:`queue.statusInjecting`,[ri.INJECTED]:`queue.statusInjected`,[ri.DONE]:`queue.statusDone`,[ri.FAILED]:`queue.statusFailed`};function Vp(e){if(e.status===ri.QUEUED)return e.interrupted?t(`queue.statusRecovered`):``;let n=Bp[e.status];return n?t(n):``}function Hp(){return v.activeSessionId}function Up(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(` · `):Rn(e.contextSnapshot)?t(`queue.withContext`):``;return i?`<span class="queue-chip-ctx" title="${A(n&&(n.fileNames||[]).length?n.fileNames.join(`、`):i)}">${A(i)}</span>`:``}function Wp(e,n){let r=Up(e),i=e.status===ri.DISPATCHING,a=Vp(e),o=(a?`<span class="queue-chip-status${i?` running`:``}${e.interrupted?` warning`:``}"${i?` title="${A(t(`queue.statusRunningHint`))}"`:``}>${A(a)}</span>`:``)+r,s=v.isGenerating===!0;return`
441
- <div class="queue-chip" draggable="true" data-id="${A(e.id)}" data-status="${A(e.status)}">
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 zp=null,Bp=null,Vp=null,Hp=null,Up=null,Wp=null,Gp=null,Kp=null,qp=null,Jp=null,Yp=!1,Xp=!1,Zp=null,Qp={[ni.DISPATCHING]:`queue.statusDispatching`,[ni.INJECTING]:`queue.statusInjecting`,[ni.INJECTED]:`queue.statusInjected`,[ni.DONE]:`queue.statusDone`,[ni.FAILED]:`queue.statusFailed`};function $p(e){if(e.status===ni.QUEUED)return e.interrupted?t(`queue.statusRecovered`):``;let n=Qp[e.status];return n?t(n):``}function em(){return y.activeSessionId}function tm(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(` · `):Ln(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 nm(e,n){let r=tm(e),i=e.status===ni.DISPATCHING,a=$p(e),o=(a?`<span class="queue-chip-status${i?` running`:``}${e.interrupted?` warning`:``}"${i?` title="${k(t(`queue.statusRunningHint`))}"`:``}>${k(a)}</span>`:``)+r,s=y.isGenerating===!0;return`
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">
444
- <div class="queue-chip-text" title="${A(e.text)}">${A(e.text)}</div>
444
+ <div class="queue-chip-text" title="${k(e.text)}">${k(e.text)}</div>
445
445
  ${o?`<div class="queue-chip-meta">${o}</div>`:``}
446
446
  </div>
447
447
  <div class="queue-chip-actions">
448
- <button class="queue-chip-btn inject${s?``:` muted`}" type="button" data-act="inject" title="${A(t(s?`queue.inject`:`queue.injectIdleHint`))}">⚡</button>
449
- <button class="queue-chip-btn" type="button" data-act="edit" title="${A(t(`queue.editBack`))}">✎</button>
450
- <button class="queue-chip-btn danger" type="button" data-act="remove" title="${A(t(`queue.delete`))}">✕</button>
448
+ <button class="queue-chip-btn inject${s?``:` muted`}" type="button" data-act="inject" title="${k(t(s?`queue.inject`:`queue.injectIdleHint`))}">⚡</button>
449
+ <button class="queue-chip-btn" type="button" data-act="edit" title="${k(t(`queue.editBack`))}">✎</button>
450
+ <button class="queue-chip-btn danger" type="button" data-act="remove" title="${k(t(`queue.delete`))}">✕</button>
451
451
  </div>
452
- </div>`}function Gp(e){return e.length?e.map(e=>`
453
- <div class="queue-recent-item" data-id="${A(e.id)}">
454
- <span class="queue-recent-status">${A(Vp(e))}</span>
455
- <span class="queue-recent-text" title="${A(e.text)}">${A(e.text)}</span>
456
- <button class="queue-chip-btn" type="button" data-act="requeue" title="${A(t(`queue.requeue`))}">↺</button>
457
- <button class="queue-chip-btn danger" type="button" data-act="forget" title="${A(t(`queue.forgetRecent`))}">✕</button>
458
- </div>`).join(``):`<div class="queue-recent-empty">${A(t(`queue.recentEmpty`))}</div>`}function Kp(e={}){if(!Dp||zp)return;let n=Hp();if(!n){Dp.style.display=`none`;return}let r=Cn(n),i=r.items,a=i.length>0,o=r.recent.filter(e=>e.status===ri.FAILED).length,s=o>0;if(!a&&!s&&(!Rp||r.recent.length===0)){Dp.style.display=`none`;return}if(Dp.style.display=``,Dp.classList.toggle(`empty`,!a),Dp.classList.toggle(`expanded`,Lp&&a),Dp.classList.toggle(`paused`,r.paused),kp&&(a?(kp.textContent=t(`queue.summary`,{count:i.length}),kp.classList.remove(`failed`),kp.removeAttribute(`title`)):s?(kp.textContent=t(`queue.summaryFailed`,{count:o}),kp.classList.add(`failed`),kp.title=t(`queue.summaryFailedHint`)):(kp.textContent=t(`queue.summaryEmpty`),kp.classList.remove(`failed`),kp.removeAttribute(`title`))),Ap&&(Ap.style.display=r.paused?``:`none`,Ap.title=r.pausedReason===`user_stopped`?t(`queue.pausedByStop`):t(`queue.pausedHint`)),jp){let e=r.paused&&i.length>0;jp.style.display=e?``:`none`,jp.textContent=t(`queue.resumeQueue`)}if(Mp){let e=v.isGenerating===!0&&a&&!r.paused;Mp.style.display=e?``:`none`}Np&&(Np.classList.toggle(`active`,Rp),Np.title=t(`queue.recentTitle`)),Fp&&(Fp.style.display=a?``:`none`,Fp.setAttribute(`aria-expanded`,Lp?`true`:`false`),Fp.textContent=Lp?`▲`:`▼`),Op&&(Op.style.display=Lp&&a?``:`none`,Op.innerHTML=a?i.map((e,t)=>Wp(e,t)).join(``):``),Pp&&(Pp.style.display=Rp?``:`none`,Pp.innerHTML=Rp?Gp(r.recent):``),e.flash&&(Dp.classList.remove(`queue-flash`),Dp.offsetWidth,Dp.classList.add(`queue-flash`))}async function qp(e,n={}){let r=Hp();if(!r||!e)return!1;let i=yn(r,e);if(!i)return!1;let a=document.getElementById(`userInput`);if(a&&a.value.trim()){let e=await mn({autoDrain:!1});if(!e.ok)return k(e.error===`queue_full`?t(`queue.queueFull`,{limit:e.limit}):t(`queue.enqueueFailed`),`warning`),!1}else if(tn())return k(t(`queue.inputHasUnsavedContext`),`warning`,4e3),!1;let o=await qt(i);return a&&(a.value=i.text,a.style.height=`auto`,a.dispatchEvent(new Event(`input`)),a.focus()),await Qt(r,e),await nr(e),o.wantsAttachments?k(o.attachments?t(`queue.editBackWithAttachments`):t(`queue.attachmentsMissing`),o.attachments?`success`:`warning`,2500):n.viaShortcut&&k(t(`queue.editTailHint`),`info`,2e3),!0}function Jp(){let e=Hp();if(!e)return!1;let t=Ot(e);return t?(qp(t.id,{viaShortcut:!0}),!0):!1}async function Yp(e,n){let r=Hp();if(!(!r||!n)&&!(jn(r).findIndex(e=>e.id===n)<0))switch(e){case`edit`:await qp(n);break;case`inject`:await Zt(n,r);break;case`remove`:await Qt(r,n),await nr(n),k(t(`queue.deleted`),`info`,1500);break;default:break}}async function Xp(e){let t=Hp();t&&await Yn(t,e)}async function Zp(e,t){if(e.preventDefault(),!zp)return;let n=t?.dataset?.id;if(!n||n===zp)return;let r=Hp();if(!r)return;let i=jn(r).map(e=>e.id),a=i.indexOf(zp);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,zp),await Xp(i)}function Qp(){Op&&(Op.addEventListener(`dragstart`,e=>{let t=e.target.closest?.(`.queue-chip`);if(t){zp=t.dataset.id,t.classList.add(`dragging`);try{e.dataTransfer.effectAllowed=`move`,e.dataTransfer.setData(`text/plain`,zp)}catch{}}}),Op.addEventListener(`dragend`,e=>{let t=e.target.closest?.(`.queue-chip`);t&&t.classList.remove(`dragging`),zp=null,Op.querySelectorAll(`.drag-over-top, .drag-over-bottom`).forEach(e=>{e.classList.remove(`drag-over-top`,`drag-over-bottom`)}),Kp()}),Op.addEventListener(`dragover`,e=>{let t=e.target.closest?.(`.queue-chip`);if(!t||!zp||t.dataset.id===zp)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`);Zp(e,t)}))}function $p(){Op?.addEventListener(`click`,e=>{let t=e.target.closest?.(`.queue-chip-btn`);if(!t||t.disabled)return;let n=t.closest(`.queue-chip`);n&&Yp(t.dataset.act,n.dataset.id)}),Pp?.addEventListener(`click`,async e=>{let n=e.target.closest?.(`.queue-chip-btn`),r=n?.closest(`.queue-recent-item`),i=Hp();if(!n||!r||!i)return;if(n.dataset.act===`forget`){await $n(i,r.dataset.id)&&k(t(`queue.forgotRecent`),`success`,1500);return}if(n.dataset.act!==`requeue`)return;let a=nn(i).find(e=>e.id===r.dataset.id),o=!!(a&&a.attachmentSummary),s=await rr(i,r.dataset.id);if(!s.ok){k(s.error===`queue_full`?t(`queue.queueFull`,{limit:s.limit}):t(`queue.enqueueFailed`),`warning`);return}k(t(o?`queue.requeuedNoAttachments`:`queue.requeued`),o?`warning`:`success`,2500)}),Fp?.addEventListener(`click`,()=>{Lp=!Lp,Kp()}),Ip?.addEventListener(`click`,e=>{e.target.closest?.(`button`)||jn(Hp()||``).length&&(Lp=!Lp,Kp())}),Np?.addEventListener(`click`,()=>{Rp=!Rp,Rp&&(Lp=!0),Kp()}),jp?.addEventListener(`click`,async()=>{await un(),k(t(`queue.resumed`),`success`,1500)}),Mp?.addEventListener(`click`,()=>{document.dispatchEvent(new CustomEvent(`queue-stop-and-send`))}),Qp(),Jt(()=>Kp()),document.addEventListener(`queue-enqueued`,()=>{Lp=!0,Kp({flash:!0})}),document.addEventListener(`session-switched`,()=>{Kp()}),document.addEventListener(`generation-ended`,()=>Kp()),document.addEventListener(`generating-state-changed`,()=>Kp())}async function em(){await hn(),Kp()}async function tm(){if(await hn(),Dp=document.getElementById(`queueStrip`),!Dp){r.warn(`[QueuePanel] #queueStrip not found, queue UI disabled`);return}Op=document.getElementById(`queueList`),kp=document.getElementById(`queueSummary`),Ap=document.getElementById(`queuePausedTag`),jp=document.getElementById(`queueResumeBtn`),Mp=document.getElementById(`queueStopSendBtn`),Np=document.getElementById(`queueRecentBtn`),Pp=document.getElementById(`queueRecent`),Fp=document.getElementById(`queueToggleBtn`),Ip=Dp.querySelector(`.queue-strip-head`),$p(),Kp()}var nm=new Set,rm=new Set,im=new Map,am=30*1e3;function om(e){let t=im.get(e);return t?Date.now()-t<am?!0:(im.delete(e),!1):!1}async function sm(e){let t=h(e)||e;if(!t||nm.has(t)||rm.has(t)||om(t))return null;rm.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 im.set(t,Date.now()),null;n=await r.json()}catch(e){return r.debug(`[WorkdirReconcile] fetch detail failed:`,e?.message||e),im.set(t,Date.now()),null}if(!n?.success||!n.sessionWorkdirSupported)return im.set(t,Date.now()),null;let i=n.sessionWorkdir||null,a=n.defaultWorkdir||n.workdir||null;if(!i||i===a)return im.set(t,Date.now()),null;let o=await p(t);return o.scope===`session`?(im.set(t,Date.now()),null):o.boundWorkdir?await ne(t)?(nm.add(t),r.debug(`[WorkdirReconcile] cleared stale agent binding:`,t,i),{cleaned:!0,workdir:i}):null:await fe(t,i,o.agentId||e.id||null)?(nm.add(t),r.debug(`[WorkdirReconcile] restored session workdir:`,t,i),{adopted:!0,workdir:i}):null}finally{rm.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 cm=1500,Q=null,lm=null,um=``,dm=null,fm=``,pm=``,mm=!1,hm=!1,gm=!1;function _m(e){return(e||``).replace(/[ \t\f\v]+/g,` `).replace(/ *\n */g,`
452
+ </div>`}function rm(e){return e.length?e.map(e=>`
453
+ <div class="queue-recent-item" data-id="${k(e.id)}">
454
+ <span class="queue-recent-status">${k($p(e))}</span>
455
+ <span class="queue-recent-text" title="${k(e.text)}">${k(e.text)}</span>
456
+ <button class="queue-chip-btn" type="button" data-act="requeue" title="${k(t(`queue.requeue`))}">↺</button>
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 im(e={}){if(!zp||Zp)return;let n=em();if(!n){zp.style.display=`none`;return}let r=Sn(n),i=r.items,a=i.length>0,o=r.recent.filter(e=>e.status===ni.FAILED).length,s=o>0;if(!a&&!s&&(!Xp||r.recent.length===0)){zp.style.display=`none`;return}if(zp.style.display=``,zp.classList.toggle(`empty`,!a),zp.classList.toggle(`expanded`,Yp&&a),zp.classList.toggle(`paused`,r.paused),Vp&&(a?(Vp.textContent=t(`queue.summary`,{count:i.length}),Vp.classList.remove(`failed`),Vp.removeAttribute(`title`)):s?(Vp.textContent=t(`queue.summaryFailed`,{count:o}),Vp.classList.add(`failed`),Vp.title=t(`queue.summaryFailedHint`)):(Vp.textContent=t(`queue.summaryEmpty`),Vp.classList.remove(`failed`),Vp.removeAttribute(`title`))),Hp&&(Hp.style.display=r.paused?``:`none`,Hp.title=r.pausedReason===`user_stopped`?t(`queue.pausedByStop`):t(`queue.pausedHint`)),Up){let e=r.paused&&i.length>0;Up.style.display=e?``:`none`,Up.textContent=t(`queue.resumeQueue`)}if(Wp){let e=y.isGenerating===!0&&a&&!r.paused;Wp.style.display=e?``:`none`}Gp&&(Gp.classList.toggle(`active`,Xp),Gp.title=t(`queue.recentTitle`)),qp&&(qp.style.display=a?``:`none`,qp.setAttribute(`aria-expanded`,Yp?`true`:`false`),qp.textContent=Yp?`▲`:`▼`),Bp&&(Bp.style.display=Yp&&a?``:`none`,Bp.innerHTML=a?i.map((e,t)=>nm(e,t)).join(``):``),Kp&&(Kp.style.display=Xp?``:`none`,Kp.innerHTML=Xp?rm(r.recent):``),e.flash&&(zp.classList.remove(`queue-flash`),zp.offsetWidth,zp.classList.add(`queue-flash`))}async function am(e,n={}){let r=em();if(!r||!e)return!1;let i=vn(r,e);if(!i)return!1;let a=document.getElementById(`userInput`);if(a&&a.value.trim()){let e=await pn({autoDrain:!1});if(!e.ok)return A(e.error===`queue_full`?t(`queue.queueFull`,{limit:e.limit}):t(`queue.enqueueFailed`),`warning`),!1}else if(en())return A(t(`queue.inputHasUnsavedContext`),`warning`,4e3),!1;let o=await Kt(i);return a&&(a.value=i.text,a.style.height=`auto`,a.dispatchEvent(new Event(`input`)),a.focus()),await Zt(r,e),await tr(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 om(){let e=em();if(!e)return!1;let t=Dt(e);return t?(am(t.id,{viaShortcut:!0}),!0):!1}async function sm(e,n){let r=em();if(!(!r||!n)&&!(An(r).findIndex(e=>e.id===n)<0))switch(e){case`edit`:await am(n);break;case`inject`:await Xt(n,r);break;case`remove`:await Zt(r,n),await tr(n),A(t(`queue.deleted`),`info`,1500);break;default:break}}async function cm(e){let t=em();t&&await Jn(t,e)}async function lm(e,t){if(e.preventDefault(),!Zp)return;let n=t?.dataset?.id;if(!n||n===Zp)return;let r=em();if(!r)return;let i=An(r).map(e=>e.id),a=i.indexOf(Zp);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,Zp),await cm(i)}function um(){Bp&&(Bp.addEventListener(`dragstart`,e=>{let t=e.target.closest?.(`.queue-chip`);if(t){Zp=t.dataset.id,t.classList.add(`dragging`);try{e.dataTransfer.effectAllowed=`move`,e.dataTransfer.setData(`text/plain`,Zp)}catch{}}}),Bp.addEventListener(`dragend`,e=>{let t=e.target.closest?.(`.queue-chip`);t&&t.classList.remove(`dragging`),Zp=null,Bp.querySelectorAll(`.drag-over-top, .drag-over-bottom`).forEach(e=>{e.classList.remove(`drag-over-top`,`drag-over-bottom`)}),im()}),Bp.addEventListener(`dragover`,e=>{let t=e.target.closest?.(`.queue-chip`);if(!t||!Zp||t.dataset.id===Zp)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)}),Bp.addEventListener(`dragleave`,e=>{let t=e.target.closest?.(`.queue-chip`);t&&t.classList.remove(`drag-over-top`,`drag-over-bottom`)}),Bp.addEventListener(`drop`,e=>{let t=e.target.closest?.(`.queue-chip`);lm(e,t)}))}function dm(){Bp?.addEventListener(`click`,e=>{let t=e.target.closest?.(`.queue-chip-btn`);if(!t||t.disabled)return;let n=t.closest(`.queue-chip`);n&&sm(t.dataset.act,n.dataset.id)}),Kp?.addEventListener(`click`,async e=>{let n=e.target.closest?.(`.queue-chip-btn`),r=n?.closest(`.queue-recent-item`),i=em();if(!n||!r||!i)return;if(n.dataset.act===`forget`){await Qn(i,r.dataset.id)&&A(t(`queue.forgotRecent`),`success`,1500);return}if(n.dataset.act!==`requeue`)return;let a=tn(i).find(e=>e.id===r.dataset.id),o=!!(a&&a.attachmentSummary),s=await nr(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)}),qp?.addEventListener(`click`,()=>{Yp=!Yp,im()}),Jp?.addEventListener(`click`,e=>{e.target.closest?.(`button`)||An(em()||``).length&&(Yp=!Yp,im())}),Gp?.addEventListener(`click`,()=>{Xp=!Xp,Xp&&(Yp=!0),im()}),Up?.addEventListener(`click`,async()=>{await ln(),A(t(`queue.resumed`),`success`,1500)}),Wp?.addEventListener(`click`,()=>{document.dispatchEvent(new CustomEvent(`queue-stop-and-send`))}),um(),qt(()=>im()),document.addEventListener(`queue-enqueued`,()=>{Yp=!0,im({flash:!0})}),document.addEventListener(`session-switched`,()=>{im()}),document.addEventListener(`generation-ended`,()=>im()),document.addEventListener(`generating-state-changed`,()=>im())}async function fm(){await mn(),im()}async function pm(){if(await mn(),zp=document.getElementById(`queueStrip`),!zp){r.warn(`[QueuePanel] #queueStrip not found, queue UI disabled`);return}Bp=document.getElementById(`queueList`),Vp=document.getElementById(`queueSummary`),Hp=document.getElementById(`queuePausedTag`),Up=document.getElementById(`queueResumeBtn`),Wp=document.getElementById(`queueStopSendBtn`),Gp=document.getElementById(`queueRecentBtn`),Kp=document.getElementById(`queueRecent`),qp=document.getElementById(`queueToggleBtn`),Jp=zp.querySelector(`.queue-strip-head`),dm(),im()}var mm=new Set,hm=new Set,gm=new Map,_m=30*1e3;function vm(e){let t=gm.get(e);return t?Date.now()-t<_m?!0:(gm.delete(e),!1):!1}async function ym(e){let t=h(e)||e;if(!t||mm.has(t)||hm.has(t)||vm(t))return null;hm.add(t);try{let e=await ee();if(!e)return null;let n=null;try{let r=await ie(`${e.url}/api/status/detail`,{headers:{Authorization:`Bearer ${e.token}`,"X-AIH-Session-Id":t}});if(!r.ok)return gm.set(t,Date.now()),null;n=await r.json()}catch(e){return r.debug(`[WorkdirReconcile] fetch detail failed:`,e?.message||e),gm.set(t,Date.now()),null}if(!n?.success||!n.sessionWorkdirSupported)return gm.set(t,Date.now()),null;let i=n.sessionWorkdir||null,a=n.defaultWorkdir||n.workdir||null;if(!i||i===a)return gm.set(t,Date.now()),null;let o=await p(t);return o.scope===`session`?(gm.set(t,Date.now()),null):o.boundWorkdir?await v(t)?(mm.add(t),r.debug(`[WorkdirReconcile] cleared stale agent binding:`,t,i),{cleaned:!0,workdir:i}):null:await de(t,i,o.agentId||e.id||null)?(mm.add(t),r.debug(`[WorkdirReconcile] restored session workdir:`,t,i),{adopted:!0,workdir:i}):null}finally{hm.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 bm=1500,Q=null,xm=null,Sm=``,Cm=null,wm=``,Tm=``,Em=!1,Dm=!1,Om=!1;function km(e){return(e||``).replace(/[ \t\f\v]+/g,` `).replace(/ *\n */g,`
459
459
  `).replace(/\n{3,}/g,`
460
460
 
461
- `).trim()}function vm(e,t){if(!e)return{context:``,truncated:!1};let n=e.startContainer?.parentElement?.closest?.(`.message`);if(!n)return{context:``,truncated:!1};let r=_m(n.textContent);if(!r)return{context:``,truncated:!1};let i=c(r);if(i<=cm)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*cm/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)>cm){let e=cm/c(d);d=d.slice(0,Math.floor(d.length*e))}return{context:d,truncated:!0}}function ym(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 bm(){return Q&&document.body.contains(Q)?Q:(Q=document.createElement(`div`),Q.className=`selection-answer-popup`,Q.id=`selectionAnswerPopup`,Q.innerHTML=`
461
+ `).trim()}function Am(e,t){if(!e)return{context:``,truncated:!1};let n=e.startContainer?.parentElement?.closest?.(`.message`);if(!n)return{context:``,truncated:!1};let r=km(n.textContent);if(!r)return{context:``,truncated:!1};let i=c(r);if(i<=bm)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*bm/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)>bm){let e=bm/c(d);d=d.slice(0,Math.floor(d.length*e))}return{context:d,truncated:!0}}function jm(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 Mm(){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,11 +472,11 @@ import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-5c8prpFJ.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`,km),Q.querySelector(`.sap-lock`).addEventListener(`click`,Cm),Q.querySelector(`.sap-copy`).addEventListener(`click`,Nm),Q.querySelector(`.sap-transfer`).addEventListener(`click`,Pm),Q.querySelector(`.sap-regen`).addEventListener(`click`,()=>{dm&&fm&&Im()}),Mm(Q.querySelector(`.sap-header`)),Q)}function xm(){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`),Sm()}function Sm(){if(!Q)return;let e=Q.querySelector(`.sap-lock`);e&&(e.classList.toggle(`locked`,gm),e.title=t(gm?`sidePanel.popupUnlock`:`sidePanel.popupLock`),e.innerHTML=gm?`<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 Cm(){gm=!gm,Sm()}function wm(e,t){let n=bm(),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 Tm(e){let n=bm();xm(),n.querySelector(`.sap-title`).textContent=e||t(`sidePanel.popupTitle`),n.querySelector(`.sap-body`).innerHTML=`<div class="sap-loading">${A(t(`sidePanel.popupLoading`))}</div>`,n.classList.add(`show`),Q.style.display=`block`}function Em(){return!!Q&&Q.classList.contains(`show`)}function Dm(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">${A(e)}</div>`)}function km(){hm&&lm&&chrome.runtime.sendMessage({type:`CANCEL_REACT`,sessionId:lm}).catch(()=>{}),Q&&(Q.classList.remove(`show`),Q.style.display=`none`),lm=null,um=``,hm=!1,gm=!1}function Am(e){if(!Em()||gm||Q.contains(e.target))return;let t=document.getElementById(`selectionFloatingMenu`);t&&t.contains(e.target)||km()}function jm(e){e.key===`Escape`&&(!Em()||gm||km())}function Mm(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 Nm(){um&&navigator.clipboard.writeText(um).then(()=>{k(t(`sidePanel.popupCopied`))}).catch(()=>{let e=document.createElement(`textarea`);e.value=um,document.body.appendChild(e),e.select(),document.execCommand(`copy`),document.body.removeChild(e),k(t(`sidePanel.popupCopied`))})}function Pm(){if(!um||!dm)return;rn()&&wn();let e=um,n=dm.content,r=`${pm?`[${t(`sidePanel.popupContextLabel`)}]\n${pm}\n\n`:``}[${t(`sidePanel.selectedContentLabel`)}]\n${fm}\n\n[${t(`sidePanel.userQuestionLabel`)}]\n${dm.content}`;E(async()=>{let{addMessage:e}=await import(`./context-indicator-Btg9ZLat.js`).then(e=>e.U);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-Btg9ZLat.js`).then(e=>e.kr);return{saveCurrentSession:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8])).then(({saveCurrentSession:e})=>{e()}),Promise.all([E(()=>import(`./context-indicator-Btg9ZLat.js`).then(e=>e.ht),__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}),k(t(`sidePanel.popupTransferred`))})}),km()}function Fm(e,t,n){let{context:r,truncated:i}=vm(n,t);dm=e,fm=t,pm=r,mm=i,Im()}function Im(){um=``,hm=!0,Tm(dm?.content);let e=ym(fm,pm,dm.content,mm);lm=`popup_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,chrome.runtime.sendMessage({type:`SIDEPANEL_POPUP_ASK`,sessionId:lm,messages:e}).catch(e=>{r.error(`[SelectionPopup] sendMessage failed:`,e),Om(t(`sidePanel.popupRequestFailed`)),hm=!1})}var Lm=!1;function Rm(){Lm||(Lm=!0,chrome.runtime.onMessage.addListener(e=>{if(!(!e||!e.type)&&e.type.startsWith(`SIDEPANEL_POPUP_`)&&e.sessionId===lm){if(e.type===`SIDEPANEL_POPUP_STREAM_CHUNK`)e.delta&&(um+=e.delta,Dm(ut(um)));else if(e.type===`SIDEPANEL_POPUP_STREAM_DONE`)hm=!1,e.finalContent&&(um=e.finalContent),Dm(ut(um));else if(e.type===`SIDEPANEL_POPUP_STREAM_ERROR`){if(!hm)return;hm=!1,Om(e.error||t(`sidePanel.popupRequestFailed`))}}}))}function zm(){Rm(),document.addEventListener(`mousedown`,Am),document.addEventListener(`keydown`,jm)}function Bm(e,t,n,r,i){!t||!e||(Rm(),wm(n,r),gm=!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 ge(),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([Me(n),Ne()]);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`,Vm),Q.querySelector(`.sap-lock`).addEventListener(`click`,Fm),Q.querySelector(`.sap-copy`).addEventListener(`click`,Gm),Q.querySelector(`.sap-transfer`).addEventListener(`click`,Km),Q.querySelector(`.sap-regen`).addEventListener(`click`,()=>{Cm&&wm&&Jm()}),Wm(Q.querySelector(`.sap-header`)),Q)}function Nm(){if(!Q)return;Q.querySelector(`.sap-close`).title=t(`sidePanel.popupClose`);let e=Q.querySelector(`.sap-copy`);e.textContent=t(`sidePanel.popupCopy`),e.title=t(`sidePanel.popupCopy`);let n=Q.querySelector(`.sap-transfer`);n.textContent=t(`sidePanel.popupTransfer`),n.title=t(`sidePanel.popupTransfer`);let r=Q.querySelector(`.sap-regen`);r.textContent=t(`sidePanel.popupRegenerate`),r.title=t(`sidePanel.popupRegenerate`),Pm()}function Pm(){if(!Q)return;let e=Q.querySelector(`.sap-lock`);e&&(e.classList.toggle(`locked`,Om),e.title=t(Om?`sidePanel.popupUnlock`:`sidePanel.popupLock`),e.innerHTML=Om?`<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 Fm(){Om=!Om,Pm()}function Im(e,t){let n=Mm(),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 Lm(e){let n=Mm();Nm(),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 zm(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 Bm(e){let t=Q?.querySelector(`.sap-body`);t&&(t.innerHTML=`<div class="sap-error">${k(e)}</div>`)}function Vm(){Dm&&xm&&chrome.runtime.sendMessage({type:`CANCEL_REACT`,sessionId:xm}).catch(()=>{}),Q&&(Q.classList.remove(`show`),Q.style.display=`none`),xm=null,Sm=``,Dm=!1,Om=!1}function Hm(e){if(!Rm()||Om||Q.contains(e.target))return;let t=document.getElementById(`selectionFloatingMenu`);t&&t.contains(e.target)||Vm()}function Um(e){e.key===`Escape`&&(!Rm()||Om||Vm())}function Wm(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 Gm(){Sm&&navigator.clipboard.writeText(Sm).then(()=>{A(t(`sidePanel.popupCopied`))}).catch(()=>{let e=document.createElement(`textarea`);e.value=Sm,document.body.appendChild(e),e.select(),document.execCommand(`copy`),document.body.removeChild(e),A(t(`sidePanel.popupCopied`))})}function Km(){if(!Sm||!Cm)return;nn()&&Cn();let e=Sm,n=Cm.content,r=`${Tm?`[${t(`sidePanel.popupContextLabel`)}]\n${Tm}\n\n`:``}[${t(`sidePanel.selectedContentLabel`)}]\n${wm}\n\n[${t(`sidePanel.userQuestionLabel`)}]\n${Cm.content}`;D(async()=>{let{addMessage:e}=await import(`./context-indicator-DjOAo_Ln.js`).then(e=>e.U);return{addMessage:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8])).then(({addMessage:i})=>{i(`user`,n,!0,[],null,!1,r),y.messageHistory.push({role:`user`,content:r,timestamp:new Date().toISOString()}),i(`assistant`,e,!0),y.messageHistory.push({role:`assistant`,content:e}),D(async()=>{let{saveCurrentSession:e}=await import(`./context-indicator-DjOAo_Ln.js`).then(e=>e.kr);return{saveCurrentSession:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8])).then(({saveCurrentSession:e})=>{e()}),Promise.all([D(()=>import(`./context-indicator-DjOAo_Ln.js`).then(e=>e.ht),__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`))})}),Vm()}function qm(e,t,n){let{context:r,truncated:i}=Am(n,t);Cm=e,wm=t,Tm=r,Em=i,Jm()}function Jm(){Sm=``,Dm=!0,Lm(Cm?.content);let e=jm(wm,Tm,Cm.content,Em);xm=`popup_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,chrome.runtime.sendMessage({type:`SIDEPANEL_POPUP_ASK`,sessionId:xm,messages:e}).catch(e=>{r.error(`[SelectionPopup] sendMessage failed:`,e),Bm(t(`sidePanel.popupRequestFailed`)),Dm=!1})}var Ym=!1;function Xm(){Ym||(Ym=!0,chrome.runtime.onMessage.addListener(e=>{if(!(!e||!e.type)&&e.type.startsWith(`SIDEPANEL_POPUP_`)&&e.sessionId===xm){if(e.type===`SIDEPANEL_POPUP_STREAM_CHUNK`)e.delta&&(Sm+=e.delta,zm(st(Sm)));else if(e.type===`SIDEPANEL_POPUP_STREAM_DONE`)Dm=!1,e.finalContent&&(Sm=e.finalContent),zm(st(Sm));else if(e.type===`SIDEPANEL_POPUP_STREAM_ERROR`){if(!Dm)return;Dm=!1,Bm(e.error||t(`sidePanel.popupRequestFailed`))}}}))}function Zm(){Xm(),document.addEventListener(`mousedown`,Hm),document.addEventListener(`keydown`,Um)}function Qm(e,t,n,r,i){!t||!e||(Xm(),Im(n,r),Om=!1,qm(e,t,i||y.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 $m(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)`,x())})});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),_(e),C(e.records||[]),y(t),x()}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=T(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>
479
- <div style="font-size: 18px; font-weight: 700; color: var(--text-primary);">${S(e.totalTokens)}</div>
479
+ <div style="font-size: 18px; font-weight: 700; color: var(--text-primary);">${w(e.totalTokens)}</div>
480
480
  </div>
481
481
  <div style="background: var(--success-soft-bg); border-radius: 8px; padding: 10px; text-align: center;">
482
482
  <div style="font-size: 10px; color: var(--text-tertiary); margin-bottom: 4px;">${t(`tokenStats.topCardSessionCalls`)}</div>
@@ -486,7 +486,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-5c8prpFJ.js"
486
486
  <div style="font-size: 10px; color: var(--text-tertiary); margin-bottom: 4px;">${t(`tokenStats.topCardContextPeak`)}</div>
487
487
  <div style="font-size: 18px; font-weight: 700; color: ${r};">${(n*100).toFixed(1)}%</div>
488
488
  </div>
489
- </div>`}function ee(e){let n=document.getElementById(`tokenSessionStats`);if(!n)return;if(!e||e.apiCallCount===0){n.innerHTML=`<div style="text-align:center;color:var(--text-tertiary);padding:20px;">${t(`tokenStats.currentSessionNoData`)}</div>`;return}let r=te(e.records||[]),i=ne(e.minContextUsageRate,e.avgContextUsageRate,e.maxContextUsageRate);n.innerHTML=`
489
+ </div>`}function _(e){let n=document.getElementById(`tokenSessionStats`);if(!n)return;if(!e||e.apiCallCount===0){n.innerHTML=`<div style="text-align:center;color:var(--text-tertiary);padding:20px;">${t(`tokenStats.currentSessionNoData`)}</div>`;return}let r=ee(e.records||[]),i=v(e.minContextUsageRate,e.avgContextUsageRate,e.maxContextUsageRate);n.innerHTML=`
490
490
  <div style="margin-bottom: 12px;">
491
491
  <div style="font-size: 11px; color: var(--text-tertiary); margin-bottom: 6px;">${t(`tokenStats.sparklineTitle`)}</div>
492
492
  ${r}
@@ -496,13 +496,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-5c8prpFJ.js"
496
496
  ${i}
497
497
  </div>
498
498
  <div style="display: flex; gap: 10px; font-size: 11px; color: var(--text-secondary);">
499
- <span>Prompt: ${S(e.totalPromptTokens)}</span>
500
- <span>Completion: ${S(e.totalCompletionTokens)}</span>
501
- </div>`}function te(e){if(!e||e.length===0)return`<div style="height: 40px; background: var(--bg-subtle); border-radius: 4px;"></div>`;let t=e.slice(0,20).reverse().map(e=>e.totalTokens||0),n=Math.max(...t,1);return`
499
+ <span>Prompt: ${w(e.totalPromptTokens)}</span>
500
+ <span>Completion: ${w(e.totalCompletionTokens)}</span>
501
+ </div>`}function ee(e){if(!e||e.length===0)return`<div style="height: 40px; background: var(--bg-subtle); border-radius: 4px;"></div>`;let t=e.slice(0,20).reverse().map(e=>e.totalTokens||0),n=Math.max(...t,1);return`
502
502
  <svg viewBox="0 0 280 40" preserveAspectRatio="none" style="width: 100%; height: 40px; display: block; background: var(--bg-subtle); border-radius: 4px;">
503
503
  <polyline points="${t.map((e,r)=>{let i=2+r/(t.length-1||1)*276,a=38-e/n*36;return`${i.toFixed(1)},${a.toFixed(1)}`}).join(` `)}" fill="none" stroke="#667eea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
504
- ${t.map((e,r)=>{let i=2+r/(t.length-1||1)*276,a=38-e/n*36;return`<circle cx="${i.toFixed(1)}" cy="${a.toFixed(1)}" r="2" fill="#667eea"><title>${S(e)} tokens</title></circle>`}).join(``)}
505
- </svg>`}function ne(e,n,r){let i=Math.min((e||0)*100,100),a=Math.min((n||0)*100,100),o=Math.min((r||0)*100,100),s=C(r||0);return`
504
+ ${t.map((e,r)=>{let i=2+r/(t.length-1||1)*276,a=38-e/n*36;return`<circle cx="${i.toFixed(1)}" cy="${a.toFixed(1)}" r="2" fill="#667eea"><title>${w(e)} tokens</title></circle>`}).join(``)}
505
+ </svg>`}function v(e,n,r){let i=Math.min((e||0)*100,100),a=Math.min((n||0)*100,100),o=Math.min((r||0)*100,100),s=T(r||0);return`
506
506
  <div style="position: relative; height: 20px; background: var(--border-subtle); border-radius: 10px; overflow: visible;">
507
507
  <!-- min 到 max 之间的填充 -->
508
508
  <div style="position: absolute; left: ${i}%; width: ${o-i}%; height: 100%; background: ${s}40; border-radius: 10px;"></div>
@@ -521,45 +521,45 @@ import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-5c8prpFJ.js"
521
521
  <span>${t(`tokenStats.min`)}</span>
522
522
  <span>${t(`tokenStats.avg`)}</span>
523
523
  <span>${t(`tokenStats.max`)}</span>
524
- </div>`}function _(e){return{react_loop:`ReAct`,non_stream:t(`tokenStats.callTypeNonStream`),stream:t(`tokenStats.callTypeStream`),reflection:t(`tokenStats.callTypeReflection`),tool_reflection:t(`tokenStats.callTypeToolReflection`),subtask_reflection:t(`tokenStats.callTypeSubtaskReflection`),unknown:`-`}[e]||e}async function v(e){let n=document.getElementById(`tokenDistributionStats`);if(n)try{let[r,i]=await Promise.all([ye(),ve()]),a=e?.totalPromptTokens||0,o=e?.totalCompletionTokens||0;if(a+o===0&&r.length===0){n.innerHTML=`<div style="text-align:center;color:var(--text-tertiary);padding:20px;">${t(`tokenStats.distNoData`)}</div>`;return}n.innerHTML=`
524
+ </div>`}function te(e){return{react_loop:`ReAct`,non_stream:t(`tokenStats.callTypeNonStream`),stream:t(`tokenStats.callTypeStream`),reflection:t(`tokenStats.callTypeReflection`),tool_reflection:t(`tokenStats.callTypeToolReflection`),subtask_reflection:t(`tokenStats.callTypeSubtaskReflection`),unknown:`-`}[e]||e}async function y(e){let n=document.getElementById(`tokenDistributionStats`);if(n)try{let[r,i]=await Promise.all([ve(),_e()]),a=e?.totalPromptTokens||0,o=e?.totalCompletionTokens||0;if(a+o===0&&r.length===0){n.innerHTML=`<div style="text-align:center;color:var(--text-tertiary);padding:20px;">${t(`tokenStats.distNoData`)}</div>`;return}n.innerHTML=`
525
525
  <div style="margin-bottom:16px;">
526
526
  <div style="font-size:12px;font-weight:600;color:var(--text-secondary);margin-bottom:8px;">${t(`tokenStats.distPromptVsCompletion`)}</div>
527
- ${re(a,o)}
527
+ ${b(a,o)}
528
528
  </div>
529
529
  <div style="margin-bottom:16px;">
530
530
  <div style="font-size:12px;font-weight:600;color:var(--text-secondary);margin-bottom:8px;">${t(`tokenStats.distByModel`)}</div>
531
- ${y(r.map(e=>({label:e.model,value:e.totalTokens,percentage:e.percentage})),`#667eea`)}
531
+ ${ne(r.map(e=>({label:e.model,value:e.totalTokens,percentage:e.percentage})),`#667eea`)}
532
532
  </div>
533
533
  <div>
534
534
  <div style="font-size:12px;font-weight:600;color:var(--text-secondary);margin-bottom:8px;">${t(`tokenStats.distByCallType`)}</div>
535
- ${y(i.map(e=>({label:_(e.callType),value:e.totalTokens,percentage:e.percentage})),`#10b981`)}
536
- </div>`}catch(e){r.error(`[TokenStats] render distribution failed:`,e),n.innerHTML=`<div style="text-align:center;color:var(--text-tertiary);padding:20px;">${t(`tokenStats.loadFailed`)}</div>`}}function re(e,n){let r=e+n;if(r===0)return`<div style="text-align:center;color:var(--text-tertiary);font-size:11px;padding:8px;">${t(`tokenStats.distNoData`)}</div>`;let i=e/r*100,a=n/r*100;return`
535
+ ${ne(i.map(e=>({label:te(e.callType),value:e.totalTokens,percentage:e.percentage})),`#10b981`)}
536
+ </div>`}catch(e){r.error(`[TokenStats] render distribution failed:`,e),n.innerHTML=`<div style="text-align:center;color:var(--text-tertiary);padding:20px;">${t(`tokenStats.loadFailed`)}</div>`}}function b(e,n){let r=e+n;if(r===0)return`<div style="text-align:center;color:var(--text-tertiary);font-size:11px;padding:8px;">${t(`tokenStats.distNoData`)}</div>`;let i=e/r*100,a=n/r*100;return`
537
537
  <div style="display:flex;height:22px;border-radius:6px;overflow:hidden;background:var(--border-subtle);">
538
- <div style="width:${i}%;background:var(--brand-500);" title="Prompt: ${S(e)}"></div>
539
- <div style="width:${a}%;background:var(--warning-500);" title="Completion: ${S(n)}"></div>
538
+ <div style="width:${i}%;background:var(--brand-500);" title="Prompt: ${w(e)}"></div>
539
+ <div style="width:${a}%;background:var(--warning-500);" title="Completion: ${w(n)}"></div>
540
540
  </div>
541
541
  <div style="display:flex;justify-content:space-between;margin-top:6px;font-size:11px;">
542
542
  <span style="display:flex;align-items:center;gap:4px;color:var(--text-secondary);">
543
543
  <span style="width:8px;height:8px;border-radius:2px;background:var(--brand-500);display:inline-block;"></span>
544
- ${t(`tokenStats.distPrompt`)} ${S(e)} (${i.toFixed(1)}%)
544
+ ${t(`tokenStats.distPrompt`)} ${w(e)} (${i.toFixed(1)}%)
545
545
  </span>
546
546
  <span style="display:flex;align-items:center;gap:4px;color:var(--text-secondary);">
547
547
  <span style="width:8px;height:8px;border-radius:2px;background:var(--warning-500);display:inline-block;"></span>
548
- ${t(`tokenStats.distCompletion`)} ${S(n)} (${a.toFixed(1)}%)
548
+ ${t(`tokenStats.distCompletion`)} ${w(n)} (${a.toFixed(1)}%)
549
549
  </span>
550
- </div>`}function y(e,n){if(!e||e.length===0)return`<div style="text-align:center;color:var(--text-tertiary);font-size:11px;padding:8px;">${t(`tokenStats.distNoData`)}</div>`;let r=Math.max(...e.map(e=>e.value||0),1);return e.map(e=>{let t=e.value/r*100;return`<div style="margin-bottom:8px;">
550
+ </div>`}function ne(e,n){if(!e||e.length===0)return`<div style="text-align:center;color:var(--text-tertiary);font-size:11px;padding:8px;">${t(`tokenStats.distNoData`)}</div>`;let r=Math.max(...e.map(e=>e.value||0),1);return e.map(e=>{let t=e.value/r*100;return`<div style="margin-bottom:8px;">
551
551
  <div style="display:flex;justify-content:space-between;font-size:11px;color:var(--text-secondary);margin-bottom:3px;">
552
- <span style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:60%;">${A(e.label)}</span>
553
- <span style="color:var(--text-tertiary);">${S(e.value)} · ${(e.percentage||0).toFixed(1)}%</span>
552
+ <span style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:60%;">${k(e.label)}</span>
553
+ <span style="color:var(--text-tertiary);">${w(e.value)} · ${(e.percentage||0).toFixed(1)}%</span>
554
554
  </div>
555
555
  <div style="height:8px;background:var(--border-subtle);border-radius:4px;overflow:hidden;">
556
556
  <div style="height:100%;width:${t}%;background:${n};border-radius:4px;"></div>
557
557
  </div>
558
- </div>`}).join(``)}async function b(){let e=document.getElementById(`tokenGlobalSparkline`),n=document.getElementById(`tokenOverallStats`);if(!e||!n)return;let i=new Date,a=i.toISOString(),o,s;d===`today`?(o=new Date(i.getFullYear(),i.getMonth(),i.getDate()).toISOString(),s=1):d===`week`?(o=new Date(i.getTime()-10080*60*1e3).toISOString(),s=7):d===`month`?(o=new Date(i.getTime()-720*60*60*1e3).toISOString(),s=30):(o=new Date(0).toISOString(),s=365);try{let[r,i]=await Promise.all([be(s),me(o,a)]);if(e.innerHTML=x(r),!i||i.totalApiCalls===0){n.innerHTML=`<div style="text-align:center;color:var(--text-tertiary);padding:16px;font-size:12px;">${t(`tokenStats.globalNoDailyData`)}</div>`;return}n.innerHTML=`
558
+ </div>`}).join(``)}async function x(){let e=document.getElementById(`tokenGlobalSparkline`),n=document.getElementById(`tokenOverallStats`);if(!e||!n)return;let i=new Date,a=i.toISOString(),o,s;d===`today`?(o=new Date(i.getFullYear(),i.getMonth(),i.getDate()).toISOString(),s=1):d===`week`?(o=new Date(i.getTime()-10080*60*1e3).toISOString(),s=7):d===`month`?(o=new Date(i.getTime()-720*60*60*1e3).toISOString(),s=30):(o=new Date(0).toISOString(),s=365);try{let[r,i]=await Promise.all([ye(s),pe(o,a)]);if(e.innerHTML=S(r),!i||i.totalApiCalls===0){n.innerHTML=`<div style="text-align:center;color:var(--text-tertiary);padding:16px;font-size:12px;">${t(`tokenStats.globalNoDailyData`)}</div>`;return}n.innerHTML=`
559
559
  <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:8px;">
560
560
  <div style="background:var(--warning-soft-bg);border-radius:8px;padding:10px;text-align:center;">
561
561
  <div style="font-size:10px;color:var(--text-tertiary);">${t(`tokenStats.globalTotalTokens`)}</div>
562
- <div style="font-size:16px;font-weight:700;color:var(--text-primary);">${S(i.totalTokens)}</div>
562
+ <div style="font-size:16px;font-weight:700;color:var(--text-primary);">${w(i.totalTokens)}</div>
563
563
  </div>
564
564
  <div style="background:var(--info-soft-bg);border-radius:8px;padding:10px;text-align:center;">
565
565
  <div style="font-size:10px;color:var(--text-tertiary);">${t(`tokenStats.globalTotalSessions`)}</div>
@@ -569,21 +569,21 @@ import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-5c8prpFJ.js"
569
569
  <div style="font-size:10px;color:var(--text-tertiary);">${t(`tokenStats.globalTotalApiCalls`)}</div>
570
570
  <div style="font-size:16px;font-weight:700;color:var(--text-primary);">${i.totalApiCalls}</div>
571
571
  </div>
572
- </div>`}catch(e){r.error(`[TokenStats] render global failed:`,e),n.innerHTML=`<div style="text-align:center;color:var(--text-tertiary);padding:16px;font-size:12px;">${t(`tokenStats.loadFailed`)}</div>`}}function x(e){if(!e||e.length===0)return`<div style="height:100%;min-height:80px;background:var(--bg-subtle);border-radius:4px;display:flex;align-items:center;justify-content:center;color:var(--text-tertiary);font-size:11px;">${t(`tokenStats.globalNoDailyData`)}</div>`;let n=e.map(e=>e.totalTokens||0),r=Math.max(...n,1),i=n.length,a=e=>3+(i===1?294/2:e/(i-1)*294),o=e=>167-e/r*164,s=n.map((e,t)=>`${a(t).toFixed(1)},${o(e).toFixed(1)}`).join(` `);return`
572
+ </div>`}catch(e){r.error(`[TokenStats] render global failed:`,e),n.innerHTML=`<div style="text-align:center;color:var(--text-tertiary);padding:16px;font-size:12px;">${t(`tokenStats.loadFailed`)}</div>`}}function S(e){if(!e||e.length===0)return`<div style="height:100%;min-height:80px;background:var(--bg-subtle);border-radius:4px;display:flex;align-items:center;justify-content:center;color:var(--text-tertiary);font-size:11px;">${t(`tokenStats.globalNoDailyData`)}</div>`;let n=e.map(e=>e.totalTokens||0),r=Math.max(...n,1),i=n.length,a=e=>3+(i===1?294/2:e/(i-1)*294),o=e=>167-e/r*164,s=n.map((e,t)=>`${a(t).toFixed(1)},${o(e).toFixed(1)}`).join(` `);return`
573
573
  <svg viewBox="0 0 300 170" preserveAspectRatio="none" style="width:100%;height:100%;display:block;background:var(--bg-subtle);border-radius:4px;">
574
574
  <polygon points="${`${a(0).toFixed(1)},167 ${s} ${a(i-1).toFixed(1)},167`}" fill="#667eea20"/>
575
575
  <polyline points="${s}" fill="none" stroke="#667eea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
576
- ${n.map((t,n)=>`<circle cx="${a(n).toFixed(1)}" cy="${o(t).toFixed(1)}" r="2" fill="#667eea"><title>${e[n].date}: ${S(t)} tokens / ${e[n].apiCalls} calls</title></circle>`).join(``)}
577
- </svg>`}function ie(e){let t=document.getElementById(`tokenRecentCalls`);if(!t)return;if(!e||e.length===0){t.innerHTML=``;return}let n=Math.max(...e.slice(0,10).map(e=>e.totalTokens||0),1);t.innerHTML=e.slice(0,10).map((e,t)=>{let r=new Date(e.timestamp).toLocaleTimeString(`zh-CN`,{hour:`2-digit`,minute:`2-digit`,second:`2-digit`}),i=_(e.callType),a=(e.totalTokens||0)/n*100,o=C(e.contextUsageRate||0);return`<div style="display:flex;align-items:center;gap:6px;padding:5px 0;border-bottom:1px solid var(--bg-subtle);font-size:11px;">
576
+ ${n.map((t,n)=>`<circle cx="${a(n).toFixed(1)}" cy="${o(t).toFixed(1)}" r="2" fill="#667eea"><title>${e[n].date}: ${w(t)} tokens / ${e[n].apiCalls} calls</title></circle>`).join(``)}
577
+ </svg>`}function C(e){let t=document.getElementById(`tokenRecentCalls`);if(!t)return;if(!e||e.length===0){t.innerHTML=``;return}let n=Math.max(...e.slice(0,10).map(e=>e.totalTokens||0),1);t.innerHTML=e.slice(0,10).map((e,t)=>{let r=new Date(e.timestamp).toLocaleTimeString(`zh-CN`,{hour:`2-digit`,minute:`2-digit`,second:`2-digit`}),i=te(e.callType),a=(e.totalTokens||0)/n*100,o=T(e.contextUsageRate||0);return`<div style="display:flex;align-items:center;gap:6px;padding:5px 0;border-bottom:1px solid var(--bg-subtle);font-size:11px;">
578
578
  <span style="color:var(--text-tertiary);width:20px;">#${t+1}</span>
579
579
  <div style="width:40px;height:12px;background:var(--border-subtle);border-radius:2px;overflow:hidden;flex-shrink:0;">
580
580
  <div style="height:100%;width:${a}%;background:${o};"></div>
581
581
  </div>
582
582
  <span style="color:var(--text-secondary);width:55px;">${r}</span>
583
- <span style="background:var(--bg-subtle);padding:1px 5px;border-radius:3px;font-size:9px;color:var(--text-secondary);">${A(i)}</span>
584
- <span style="font-weight:500;color:var(--text-primary);margin-left:auto;">${S(e.totalTokens)}</span>
583
+ <span style="background:var(--bg-subtle);padding:1px 5px;border-radius:3px;font-size:9px;color:var(--text-secondary);">${k(i)}</span>
584
+ <span style="font-weight:500;color:var(--text-primary);margin-left:auto;">${w(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 Hm(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 w(e){return e>=1e6?(e/1e6).toFixed(1)+`M`:e>=1e3?(e/1e3).toFixed(1)+`K`:String(e)}function T(e){return e>=.8?`#ef4444`:e>=.5?`#f59e0b`:`#10b981`}}function eh(e){return(e||[]).map(e=>e.token?{...e,token:ce(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,16 +601,16 @@ 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,Wm(),r.debug(`[SidePanel] auto-compaction config updated:`,v.chatConfig.autoCompaction)),t===`local`&&e.chatPersistSummaryToMemory&&(v.chatConfig.persistSummaryToMemory=e.chatPersistSummaryToMemory.newValue!==!1,Gm(),r.debug(`[SidePanel] persist-summary config updated:`,v.chatConfig.persistSummaryToMemory)),t===`local`&&e.chatMaxMemoryMessages&&(v.chatConfig.maxMemoryMessages=e.chatMaxMemoryMessages.newValue,Um(),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 Um(){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 Wm(){let e=document.getElementById(`autoCompactBtn`);e&&(e.checked=v.chatConfig.autoCompaction===!0)}function Gm(){let e=document.getElementById(`persistSummaryBtn`);e&&(e.checked=v.chatConfig.persistSummaryToMemory!==!1)}function Km(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 qm(){let e=document.getElementById(`memoryLimitDropdown`),n=document.getElementById(`memoryLimitLabel`),r=e?.querySelector(`#memoryLimitInput`);if(!e||!n)return;Um(),n.addEventListener(`click`,Km);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,k(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,k(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,Um(),k(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,Um(),k(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 Jm(e){if(v.activeAgentId&&v.activeAgentId!=="default")try{let{updateAgent:t}=await E(async()=>{let{updateAgent:e}=await import(`./agent-store-CeC2_dkP.js`).then(e=>e.t);return{updateAgent:e}},__vite__mapDeps([7,1,2,3]));await t(v.activeAgentId,{model:e})}catch{}else chrome.storage.local.set({modelName:e}),ue(e)}async function Ym(){try{let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),t=Hm(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=Th(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),sa()}catch{}}async function Xm(e,t,n){if(v.activeAgentId&&v.activeAgentId!=="default")try{let{updateAgent:n}=await E(async()=>{let{updateAgent:e}=await import(`./agent-store-CeC2_dkP.js`).then(e=>e.t);return{updateAgent:e}},__vite__mapDeps([7,1,2,3]));await n(v.activeAgentId,{temperature:e,topP:t})}catch{}else chrome.storage.local.set({temperature:e,topP:t,selectedTempIndex:n})}function Zm(){let e=document.getElementById(`currentModelTag`);if(!e)return;let t=v.currentModel||``;e.textContent=t,e.title=t,e.style.display=t?``:`none`}var Qm=new Set,$m=0;function eh(){let e=document.getElementById(`workdirTag`);e&&(e.dataset.locked=ra(v.activeSessionId)?`true`:`false`)}async function th(){let e=++$m,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!==$m)return;let l=c&&c.workdir||``;if(!l){n.style.display=`none`;return}n.style.display=``,i.textContent=s(l,{homeDir:v.agentPlatform?.homeDir||``}),eh();try{let{getWorkspaceRoot:e}=await E(async()=>{let{getWorkspaceRoot:e}=await import(`./workspace-manager-CL4JvHkJ.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`,sm(a).then(e=>{e&&th()}).catch(e=>r.debug(`[WorkdirTag] reconcile failed:`,e&&e.message))):n.dataset.invalid=i?`true`:`false`}catch{n.dataset.invalid=`false`}if(e===$m&&(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||``}`;Qm.has(e)||(Qm.add(e),k(t(`workdirTag.agentSwitched`),`warning`))}}function nh(){let e=document.getElementById(`workdirTag`);e&&(e.setAttribute(`aria-label`,t(`workdirTag.tagHint`)),e.addEventListener(`click`,async e=>{if(e.stopPropagation(),ra(v.activeSessionId)){eh(),k(t(`workdirTag.lockedHint`),`warning`);return}eh();let{showSwitchWorkdirDialog:n}=await E(async()=>{let{showSwitchWorkdirDialog:e}=await import(`./context-indicator-Btg9ZLat.js`).then(e=>e.mn);return{showSwitchWorkdirDialog:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]));await n({sessionId:v.activeSessionId||null})})),th(),document.addEventListener(`session-switched`,()=>{th()}),document.addEventListener(`session-workdir-changed`,()=>{th()}),document.addEventListener(`agent-model-changed`,()=>{th()}),document.addEventListener(`agent-tools-changed`,()=>{th()}),document.addEventListener(`generating-state-changed`,()=>{eh()}),document.addEventListener(`generation-ended`,()=>{eh()}),Jt(()=>{eh()})}function rh(){let e=document.getElementById(`currentModelTag`);e&&e.addEventListener(`click`,e=>{e.stopPropagation(),document.getElementById(`tempDisplay`)?.click()}),Zm()}function ih(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`),Zm()}function ah(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&&(y.chatConfig.autoCompaction=e.chatAutoCompaction.newValue===!0,nh(),r.debug(`[SidePanel] auto-compaction config updated:`,y.chatConfig.autoCompaction)),t===`local`&&e.chatPersistSummaryToMemory&&(y.chatConfig.persistSummaryToMemory=e.chatPersistSummaryToMemory.newValue!==!1,rh(),r.debug(`[SidePanel] persist-summary config updated:`,y.chatConfig.persistSummaryToMemory)),t===`local`&&e.chatMaxMemoryMessages&&(y.chatConfig.maxMemoryMessages=e.chatMaxMemoryMessages.newValue,th(),r.debug(`[SidePanel] memory limitconfiguration updated:`,y.chatConfig.maxMemoryMessages)),t===`local`&&e.queueAutoCarry&&(y.chatConfig.queueAutoCarry=e.queueAutoCarry.newValue!==!1,r.debug(`[SidePanel] queue auto-carry updated:`,y.chatConfig.queueAutoCarry)),t===`local`&&e.queueAutoCarryEveryNIterations&&(y.chatConfig.queueAutoCarryEveryNIterations=e.queueAutoCarryEveryNIterations.newValue,r.debug(`[SidePanel] queue auto-carry interval updated:`,y.chatConfig.queueAutoCarryEveryNIterations))});function th(){let e=document.getElementById(`memoryLimitLabel`);e&&(y.chatConfig.maxMemoryMessages!==null&&y.chatConfig.maxMemoryMessages!==void 0&&y.chatConfig.maxMemoryMessages>0?e.textContent=y.chatConfig.maxMemoryMessages:e.textContent=t(`sidePanel.memoryLimitAll`),e.title=t(`sidePanel.memoryLimitTitle`))}function nh(){let e=document.getElementById(`autoCompactBtn`);e&&(e.checked=y.chatConfig.autoCompaction===!0)}function rh(){let e=document.getElementById(`persistSummaryBtn`);e&&(e.checked=y.chatConfig.persistSummaryToMemory!==!1)}function ih(e){e.preventDefault(),e.stopPropagation();let t=document.getElementById(`memoryLimitDropdown`);if(t.classList.toggle(`show`),t.classList.contains(`show`)){let e=y.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 ah(){let e=document.getElementById(`memoryLimitDropdown`),n=document.getElementById(`memoryLimitLabel`),r=e?.querySelector(`#memoryLimitInput`);if(!e||!n)return;th(),n.addEventListener(`click`,ih);let i=document.getElementById(`autoCompactBtn`);i&&(i.checked=y.chatConfig.autoCompaction===!0,i.addEventListener(`change`,()=>{let e=i.checked;chrome.storage.local.set({chatAutoCompaction:e},()=>{y.chatConfig.autoCompaction=e,A(t(`sidePanel.configUpdated`),`success`)})}));let a=document.getElementById(`persistSummaryBtn`);a&&(a.checked=y.chatConfig.persistSummaryToMemory!==!1,a.addEventListener(`change`,()=>{let e=a.checked;chrome.storage.local.set({chatPersistSummaryToMemory:e},()=>{y.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},()=>{y.chatConfig.maxMemoryMessages=a,th(),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},()=>{y.chatConfig.maxMemoryMessages=r,th(),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 oh(e){if(y.activeAgentId&&y.activeAgentId!=="default")try{let{updateAgent:t}=await D(async()=>{let{updateAgent:e}=await import(`./agent-store-CeC2_dkP.js`).then(e=>e.t);return{updateAgent:e}},__vite__mapDeps([7,1,2,3]));await t(y.activeAgentId,{model:e})}catch{}else chrome.storage.local.set({modelName:e}),le(e)}async function sh(){try{let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),t=eh(e.pairedAgents),n=e.activeAgentId,r=t.find(e=>e.id===n&&!e.disabled);if(!r){y.agentPlatform={connected:!1},$(y.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){y.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&&y.agentVersions.set(n,t.version),t.workdir&&y.agentWorkdirs.set(n,t.workdir),t.homeDir&&y.agentHomeDirs.set(n,t.homeDir);let e=Lh(t.platformName||t.platform,t.arch);e&&y.agentSystemInfos.set(n,e)}else y.agentPlatform={connected:!1}}else y.agentPlatform={connected:!1}}catch{y.agentPlatform={connected:!1}}else y.agentPlatform={connected:!1};$(y.agentPlatform),oa()}catch{}}async function ch(e,t,n){if(y.activeAgentId&&y.activeAgentId!=="default")try{let{updateAgent:n}=await D(async()=>{let{updateAgent:e}=await import(`./agent-store-CeC2_dkP.js`).then(e=>e.t);return{updateAgent:e}},__vite__mapDeps([7,1,2,3]));await n(y.activeAgentId,{temperature:e,topP:t})}catch{}else chrome.storage.local.set({temperature:e,topP:t,selectedTempIndex:n})}function lh(){let e=document.getElementById(`currentModelTag`);if(!e)return;let t=y.currentModel||``;e.textContent=t,e.title=t,e.style.display=t?``:`none`}var uh=new Set,dh=0;function fh(){let e=document.getElementById(`workdirTag`);e&&(e.dataset.locked=na(y.activeSessionId)?`true`:`false`)}async function ph(){let e=++dh,n=document.getElementById(`workdirTag`),i=document.getElementById(`workdirTagName`);if(!n||!i)return;let a=y.activeSessionId||null,o=Array.isArray(y.enabledTools)&&y.enabledTools.includes(`agent_exec`);if(y.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!==dh)return;let l=c&&c.workdir||``;if(!l){n.style.display=`none`;return}n.style.display=``,i.textContent=s(l,{homeDir:y.agentPlatform?.homeDir||``}),fh();try{let{getWorkspaceRoot:e}=await D(async()=>{let{getWorkspaceRoot:e}=await import(`./workspace-manager-CL4JvHkJ.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`,ym(a).then(e=>{e&&ph()}).catch(e=>r.debug(`[WorkdirTag] reconcile failed:`,e&&e.message))):n.dataset.invalid=i?`true`:`false`}catch{n.dataset.invalid=`false`}if(e===dh&&(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||``}`;uh.has(e)||(uh.add(e),A(t(`workdirTag.agentSwitched`),`warning`))}}function mh(){let e=document.getElementById(`workdirTag`);e&&(e.setAttribute(`aria-label`,t(`workdirTag.tagHint`)),e.addEventListener(`click`,async e=>{if(e.stopPropagation(),na(y.activeSessionId)){fh(),A(t(`workdirTag.lockedHint`),`warning`);return}fh();let{showSwitchWorkdirDialog:n}=await D(async()=>{let{showSwitchWorkdirDialog:e}=await import(`./context-indicator-DjOAo_Ln.js`).then(e=>e.mn);return{showSwitchWorkdirDialog:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]));await n({sessionId:y.activeSessionId||null})})),ph(),document.addEventListener(`session-switched`,()=>{ph()}),document.addEventListener(`session-workdir-changed`,()=>{ph()}),document.addEventListener(`agent-model-changed`,()=>{ph()}),document.addEventListener(`agent-tools-changed`,()=>{ph()}),document.addEventListener(`generating-state-changed`,()=>{fh()}),document.addEventListener(`generation-ended`,()=>{fh()}),qt(()=>{fh()})}function hh(){let e=document.getElementById(`currentModelTag`);e&&e.addEventListener(`click`,e=>{e.stopPropagation(),document.getElementById(`tempDisplay`)?.click()}),lh()}function gh(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`),lh()}function _h(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">
608
- <span class="section-select-value" id="modelSelectValue">${A(v.currentModel||``)}</span>
608
+ <span class="section-select-value" id="modelSelectValue">${k(y.currentModel||``)}</span>
609
609
  <span class="model-ctx-badge" id="modelSelectCtxBadge" style="display:none;"></span>
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=Vd();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">${A(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(),Bd(),v.currentModel=r.name,ih(r.name),Jm(r.name),Zr()}),e.appendChild(n)}}v.customModelMap=l(e),typeof n==`function`&&n()}function oh(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 sh=null,ch=``;function lh(){if(sh&&sh.isConnected)return sh;sh=document.createElement(`div`),sh.className=`selection-floating-menu`,sh.id=`selectionFloatingMenu`,sh.innerHTML=`
613
+ </div>`;let e=i.querySelector(`#modelSelectList`);e.innerHTML=Ud();let n=[...a].sort((e,t)=>w(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:ue(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(),Hd(),y.currentModel=r.name,gh(r.name),oh(r.name),Xr()}),e.appendChild(n)}}y.customModelMap=l(e),typeof n==`function`&&n()}function vh(e,n=t(`sidePanel.selectedPrefix`)){if(!y.enableSelectionQuery)return;y.quotedContextText=``,y.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 yh=null,bh=``;function xh(){if(yh&&yh.isConnected)return yh;yh=document.createElement(`div`),yh.className=`selection-floating-menu`,yh.id=`selectionFloatingMenu`,yh.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=sh.querySelector(`.menu-copy-btn`);return e?.addEventListener(`click`,n=>{n.stopPropagation(),ch&&(tt(ch,e),k(t(`sidePanel.copySelectionDone`),`success`),window.getSelection()?.removeAllRanges(),window.hideFloatingMenu())}),document.body.appendChild(sh),sh}function uh(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=lh();ch=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=yh.querySelector(`.menu-copy-btn`);return e?.addEventListener(`click`,n=>{n.stopPropagation(),bh&&(ut(bh,e),A(t(`sidePanel.copySelectionDone`),`success`),window.getSelection()?.removeAllRanges(),window.hideFloatingMenu())}),document.body.appendChild(yh),yh}function Sh(e,n,i=0,a=0){if(!y.enableSelectionQuery)return;let o=y.customPrompts.filter(e=>e.enabledInMenu===!0);if(o.length===0){r.debug(`[SidePanel] showFloatingMenu skipped: no prompts enabled in menu`);return}let s=xh();bh=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,15 +632,15 @@ 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(),dh(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(),Bm(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(){sh&&sh.classList.remove(`show`),ch=``,v.lastSelectedText=``,v.currentSelectionRange=null};async function dh(e,n){if(!v.enableSelectionQuery)return;if(window.hideFloatingMenu(),v.isGenerating){r.debug(`[SidePanel] generating,please wait...`);return}rn()&&wn(),await _i({state:v,getRatio:()=>zi().usage?.ratio??0,compact:ji}),v.selectedContextText=n,Kt();let i=document.getElementById(`chatContainer`).querySelector(`.welcome-message`);i&&i.remove(),pn(`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}=ua(`user`,e.content,!0,[],null,!1,s);v.messageHistory.push({role:`user`,content:s,messageId:l,timestamp:d}),vi(),Fn(e.content),v.isGenerating=!0;let f=Ln(),p=v.activeSessionId,h=v.currentModel;try{await dt(),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 rt(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=Ir(v.messageHistory.slice(0,-1),{isolateChat:!0,maxMemoryMessages:v.chatConfig.maxMemoryMessages,compaction:v.activeCompaction,historyBudget:i,currentMessage:a});bt(n,o,v.activeCompaction,r),o.historySummaryText&&(n[0]={...n[0],content:n[0].content+`
635
+ `,o.addEventListener(`click`,t=>{t.stopPropagation(),Ch(e,n)}),o.querySelector(`.menu-item-popup-btn`).addEventListener(`click`,t=>{t.stopPropagation();let r=y.currentSelectionRange?y.currentSelectionRange.cloneRange():null;window.getSelection()?.removeAllRanges(),window.hideFloatingMenu(),Qm(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(){yh&&yh.classList.remove(`show`),bh=``,y.lastSelectedText=``,y.currentSelectionRange=null};async function Ch(e,n){if(!y.enableSelectionQuery)return;if(window.hideFloatingMenu(),y.isGenerating){r.debug(`[SidePanel] generating,please wait...`);return}nn()&&Cn(),await gi({state:y,getRatio:()=>Ri().usage?.ratio??0,compact:Ai}),y.selectedContextText=n,Gt();let i=document.getElementById(`chatContainer`).querySelector(`.welcome-message`);i&&i.remove(),fn(`selected`,n,!1);let{compressed:a,wasCompressed:o}=_(n),s=`[${t(`sidePanel.selectedContentLabel`)}${o?t(`sidePanel.selectedContentSummary`):``}]\n${a}\n\n[${t(`sidePanel.userQuestionLabel`)}]\n${e.content}`,{messageId:l,timestamp:d}=la(`user`,e.content,!0,[],null,!1,s);y.messageHistory.push({role:`user`,content:s,messageId:l,timestamp:d}),_i(),Pn(e.content),y.isGenerating=!0;let f=In(),p=y.activeSessionId,h=y.currentModel;try{await Ke(),r.debug(`[SidePanel] sendmessagedebuginfo:`),r.debug(` - isolateChat:`,y.isolateChat),r.debug(` - chatConfig:`,y.chatConfig),r.debug(` - messageHistory.length:`,y.messageHistory.length);let n=[{role:`system`,content:await at(null,{sessionId:p})}];if(y.isolateChat){let e=c(n[0]?.content||``),t=m(h,0,y.customModelMap)-e-4096-2e3,i=Math.floor(t*.7),a=y.messageHistory[y.messageHistory.length-1],o=Fr(y.messageHistory.slice(0,-1),{isolateChat:!0,maxMemoryMessages:y.chatConfig.maxMemoryMessages,compaction:y.activeCompaction,historyBudget:i,currentMessage:a});yt(n,o,y.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 qe(),a,o;try{let t=await Xt(n,h,v.useTools,i);if(a=t.content,o=t.executionLog||[],vt(f),t.wasStreamed)t.streamingMsgId&&(v.messageHistory.push({role:`assistant`,content:a,executionLog:o,messageId:t.streamingMsgId}),vi());else{let{element:e,messageId:t}=ua(`assistant`,a,!0,o);await ht(e),v.messageHistory.push({role:`assistant`,content:a,executionLog:o,messageId:t}),vi()}yt(p,e.content);return}catch(n){vt(f),a=t(`sidePanel.requestFailed`)+(n.message||t(`sidePanel.unknownError`)),o=n.executionLog||[];let{element:r,messageId:i}=ua(`assistant`,a,!0,o);throw v.messageHistory.push({role:`assistant`,content:a,executionLog:o,messageId:i}),vi(),n.message!==t(`chatMsg.errTaskStopped`)&&Rr(p,a,e.content),n}}catch{}finally{Pn(p),document.getElementById(`userInput`).focus()}}var fh=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=Hm(e.pairedAgents),o=s.find(t=>t.id===e.activeAgentId)}catch{}let c=e?.connected===!0;if(c!==fh){fh=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),Sh(o,s,c),!n){let e=document.getElementById(`headerAgentDropdown`);e&&e.style.display!==`none`&&Oh()}wi(c),th(),xh(o,c)}function ph(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 mh(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 hh=3600*1e3,gh=1440*60*1e3,_h=new Map;function vh(e){let n=document.getElementById(`agentDdUpdateBtn`);if(!n)return;let r=e?.current||``,i=e?.latest||``,a=!!i&&mh(i,r)>0;n.classList.toggle(`has-update`,a),n.title=a?t(`sidePanel.agentUpdateAvailable`,{current:r,latest:i}):t(`header.updateAndRestart`)}async function yh(){try{await chrome.storage.local.remove([`agentUpdateCheck`,`agentUpdateCheckUnsupported`])}catch{}vh(null)}async function bh(e,t){let n=null;try{n=(await chrome.storage.local.get(`activeAgentId`)).activeAgentId}catch{}if(n===e&&(vh(t),t))try{await chrome.storage.local.set({agentUpdateCheck:t})}catch{}}async function xh(e,t){if(!t||!e?.id){vh(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<hh){vh(r);return}if(i?.agentId===e.id&&i?.target===n&&i?.checkedAt&&Date.now()-i.checkedAt<gh){vh(null);return}let a=`${e.id}:${n}`;if(_h.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 bh(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 bh(e.id,null);return}}catch{}finally{_h.delete(a)}})();_h.set(a,o),await o}function Sh(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=ph(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=wh(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 Yt(n,h,y.useTools,i);if(a=t.content,o=t.executionLog||[],_t(f),t.wasStreamed)t.streamingMsgId&&(y.messageHistory.push({role:`assistant`,content:a,executionLog:o,messageId:t.streamingMsgId}),_i());else{let{element:e,messageId:t}=la(`assistant`,a,!0,o);await gt(e),y.messageHistory.push({role:`assistant`,content:a,executionLog:o,messageId:t}),_i()}vt(p,e.content);return}catch(n){_t(f),a=t(`sidePanel.requestFailed`)+(n.message||t(`sidePanel.unknownError`)),o=n.executionLog||[];let{element:r,messageId:i}=la(`assistant`,a,!0,o);throw y.messageHistory.push({role:`assistant`,content:a,executionLog:o,messageId:i}),_i(),n.message!==t(`chatMsg.errTaskStopped`)&&Lr(p,a,e.content),n}}catch{}finally{Nn(p),document.getElementById(`userInput`).focus()}}var wh=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=eh(e.pairedAgents),o=s.find(t=>t.id===e.activeAgentId)}catch{}let c=e?.connected===!0;if(c!==wh){wh=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),Ph(o,s,c),!n){let e=document.getElementById(`headerAgentDropdown`);e&&e.style.display!==`none`&&Bh()}Ci(c),ph(),Nh(o,c)}function Th(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 Eh(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 Dh=3600*1e3,Oh=1440*60*1e3,kh=new Map;function Ah(e){let n=document.getElementById(`agentDdUpdateBtn`);if(!n)return;let r=e?.current||``,i=e?.latest||``,a=!!i&&Eh(i,r)>0;n.classList.toggle(`has-update`,a),n.title=a?t(`sidePanel.agentUpdateAvailable`,{current:r,latest:i}):t(`header.updateAndRestart`)}async function jh(){try{await chrome.storage.local.remove([`agentUpdateCheck`,`agentUpdateCheckUnsupported`])}catch{}Ah(null)}async function Mh(e,t){let n=null;try{n=(await chrome.storage.local.get(`activeAgentId`)).activeAgentId}catch{}if(n===e&&(Ah(t),t))try{await chrome.storage.local.set({agentUpdateCheck:t})}catch{}}async function Nh(e,t){if(!t||!e?.id){Ah(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<Dh){Ah(r);return}if(i?.agentId===e.id&&i?.target===n&&i?.checkedAt&&Date.now()-i.checkedAt<Oh){Ah(null);return}let a=`${e.id}:${n}`;if(kh.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 Mh(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 Mh(e.id,null);return}}catch{}finally{kh.delete(a)}})();kh.set(a,o),await o}function Ph(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=y.agentVersions.get(n.id),s=Th(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=y.agentWorkdirs.get(n.id),d=Ih(u,y.agentHomeDirs.get(n.id)),f=y.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">
641
- <div class="agent-dd-item-name"><span class="agent-dd-item-name-text" title="${A(n.name)}">${A(n.name)}</span>${o?`<span class="agent-dd-item-version${s?` warn`:``}" title="${s?A(t(`sidePanel.agentVersionAhead`)):`v${A(o)}`}">v${A(o)}${s?` !`:``}</span>`:``}${f?`<span class="agent-dd-item-sysinfo" title="${A(f)}">${A(f)}</span>`:``}</div>
642
- <span class="agent-dd-item-url" title="${A(n.url||``)}">${A(n.url||``)}</span>
643
- ${d?`<span class="agent-dd-item-workdir" title="${t(`sidePanel.workingDirectory`,{path:A(u)})}">${A(d)}</span>`:``}
641
+ <div class="agent-dd-item-name"><span class="agent-dd-item-name-text" title="${k(n.name)}">${k(n.name)}</span>${o?`<span class="agent-dd-item-version${s?` warn`:``}" title="${s?k(t(`sidePanel.agentVersionAhead`)):`v${k(o)}`}">v${k(o)}${s?` !`:``}</span>`:``}${f?`<span class="agent-dd-item-sysinfo" title="${k(f)}">${k(f)}</span>`:``}</div>
642
+ <span class="agent-dd-item-url" title="${k(n.url||``)}">${k(n.url||``)}</span>
643
+ ${d?`<span class="agent-dd-item-workdir" title="${t(`sidePanel.workingDirectory`,{path:k(u)})}">${k(d)}</span>`:``}
644
644
  </div>
645
645
  <span class="agent-dd-item-status">${l}</span>
646
646
  ${i?`<span class="agent-dd-item-check">&#10003;</span>`:``}
@@ -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 Ch(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 wh(e,t){return e?t&&e.startsWith(t)?`~`+e.substring(t.length):e:``}function Th(e,t){return e||``}function Eh(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 Dh(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=wh(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=Dh;async function Oh(){try{let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),t=Hm(e.pairedAgents),n=e.activeAgentId;await Promise.all(t.filter(e=>!e.disabled).map(async e=>{let t=await Ch(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=Th(t.platformName,t.arch);i&&v.agentSystemInfos.set(e.id,i),t.workdir&&Dh(e.id,t.workdir),Eh(e.id,r),e.id===n&&r!==(v.agentPlatform?.connected===!0)&&(v.agentPlatform={...v.agentPlatform,connected:r},$(v.agentPlatform,!0),r&&kh(e))}))}catch{}}async function kh(e){try{let t=e;if(!t){let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),n=Hm(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),sa();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),Dh(t.id,e.workdir)),e.homeDir&&v.agentHomeDirs.set(t.id,e.homeDir);let n=Th(e.platformName||e.platform,e.arch);n&&v.agentSystemInfos.set(t.id,n),$(v.agentPlatform),sa();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),sa();return}}catch{}v.agentPlatform={...v.agentPlatform,connected:!0},$(v.agentPlatform),sa()}catch{v.agentPlatform={...v.agentPlatform,connected:!0},$(v.agentPlatform),sa()}}var Ah=null;function jh(e,t=20){Ah&&clearInterval(Ah);let n=0;Ah=setInterval(async()=>{if(n++,n>t||!e){clearInterval(Ah),Ah=null;return}try{let t=Hm((await chrome.storage.local.get([`pairedAgents`])).pairedAgents).find(t=>t.id===e);if(!t){clearInterval(Ah),Ah=null;return}let n=await Ch(t.url,t.token);if(n.online){clearInterval(Ah),Ah=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=Th(n.platformName,n.arch);r&&v.agentSystemInfos.set(e,r),n.workdir&&Dh(e,n.workdir),await kh(t),Eh(e,!0)}}catch{}},3e3)}function Mh(){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 Nh(){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||(Mh(),$(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=Hm(n.pairedAgents).find(e=>e.id===n.activeAgentId);r?.url&&(await navigator.clipboard.writeText(r.url),k(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=Hm(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?(k(t(`sidePanel.agentRestarting`),`success`),v.agentPlatform={...v.agentPlatform,connected:!1},await $(v.agentPlatform,!0),r?.id&&Eh(r.id,!1),jh(r?.id)):k(t(`sidePanel.restartFailed`,{error:e?.error||t(`sidePanel.unknownError`)}),`error`)})}catch(e){k(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=Hm(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`))){k(t(`sidePanel.agentUpdating`),`info`);try{chrome.runtime.sendMessage({type:`AGENT_UPDATE`,target:s},async e=>{if(e?.success&&e.upToDate){await yh(),k(e.message||t(`sidePanel.agentAlreadyLatest`),`info`);return}e?.success?(await yh(),k(t(`sidePanel.agentUpdateRestarting`),`success`),v.agentPlatform={...v.agentPlatform,connected:!1},await $(v.agentPlatform,!0),r?.id&&Eh(r.id,!1),jh(r?.id)):k(t(`sidePanel.updateFailed`,{error:e?.error||t(`sidePanel.unknownError`)}),`error`)})}catch(e){k(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=Hm(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?(k(t(`sidePanel.agentStopped`),`success`),v.agentPlatform={...v.agentPlatform,connected:!1},await $(v.agentPlatform,!0),r?.id&&Eh(r.id,!1)):k(t(`sidePanel.stopFailed`,{error:e?.error||t(`sidePanel.unknownError`)}),`error`)})}catch(e){k(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(),k(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=Hm(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 Ph=new Map,Fh=8;function Ih(e,t){for(Ph.has(e)&&Ph.delete(e),Ph.set(e,t);Ph.size>Fh;)Ph.delete(Ph.keys().next().value)}function Lh(e){let t=Ph.get(e);if(t!==void 0)return Ph.delete(e),Ph.set(e,t),t}function Rh(e){Ph.delete(e)}document.addEventListener(`DOMContentLoaded`,async()=>{await nt(),lt(()=>{_t()}),Hi(),await Promise.allSettled([n().then(()=>{i(),ea(),o(()=>{i(),ea()})}),it(),Ui(),Dn()]),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)||ar().catch(()=>{}),n&&ro(t)):t&&(n||It(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&&oh(e.selectedText),Ri(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&&oh(e.selectedText),ln(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),sa(),Xi(),e.connected&&kh()),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),sa(),Xi();return}e.agentId&&(async()=>{try{let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),t=Hm(e.pairedAgents).find(t=>t.id===e.activeAgentId&&!t.disabled);if(!t){v.agentPlatform={connected:!1},$(v.agentPlatform),sa(),Xi(),Vr();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=Th(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=Th(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),sa(),Xi(),Vr()})()}e.type===`SCREENSHOT_RESULT`&&e.dataUrl&&(r.debug(`[SidePanel] received pageshortcutscreenshotresult:`,e.mode),vr(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(Bi[0].temp-v.temperature);for(let n=1;n<Bi.length;n++){let r=Math.abs(Bi[n].temp-v.temperature);r<t&&(t=r,e=n)}return e}function _(){let e=ne();m.innerHTML=Bi.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 Fh(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 Ih(e,t){return e?t&&e.startsWith(t)?`~`+e.substring(t.length):e:``}function Lh(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 zh(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=Ih(n,y.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=zh;async function Bh(){try{let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),t=eh(e.pairedAgents),n=e.activeAgentId;await Promise.all(t.filter(e=>!e.disabled).map(async e=>{let t=await Fh(e.url,e.token),r=t.online;t.version&&y.agentVersions.set(e.id,t.version),t.workdir&&y.agentWorkdirs.set(e.id,t.workdir),t.homeDir&&y.agentHomeDirs.set(e.id,t.homeDir);let i=Lh(t.platformName,t.arch);i&&y.agentSystemInfos.set(e.id,i),t.workdir&&zh(e.id,t.workdir),Rh(e.id,r),e.id===n&&r!==(y.agentPlatform?.connected===!0)&&(y.agentPlatform={...y.agentPlatform,connected:r},$(y.agentPlatform,!0),r&&Vh(e))}))}catch{}}async function Vh(e){try{let t=e;if(!t){let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),n=eh(e.pairedAgents),r=e.activeAgentId;t=n.find(e=>e.id===r&&!e.disabled)}if(!t||!t.url){y.agentPlatform={...y.agentPlatform,connected:!0},$(y.agentPlatform),oa();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){y.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&&y.agentVersions.set(t.id,e.version),e.workdir&&(y.agentWorkdirs.set(t.id,e.workdir),zh(t.id,e.workdir)),e.homeDir&&y.agentHomeDirs.set(t.id,e.homeDir);let n=Lh(e.platformName||e.platform,e.arch);n&&y.agentSystemInfos.set(t.id,n),$(y.agentPlatform),oa();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();y.agentPlatform={platformName:e.platformName||e.platform||`Unknown`,platform:e.platform||`unknown`,arch:e.arch||`unknown`,connected:!0},$(y.agentPlatform),oa();return}}catch{}y.agentPlatform={...y.agentPlatform,connected:!0},$(y.agentPlatform),oa()}catch{y.agentPlatform={...y.agentPlatform,connected:!0},$(y.agentPlatform),oa()}}var Hh=null;function Uh(e,t=20){Hh&&clearInterval(Hh);let n=0;Hh=setInterval(async()=>{if(n++,n>t||!e){clearInterval(Hh),Hh=null;return}try{let t=eh((await chrome.storage.local.get([`pairedAgents`])).pairedAgents).find(t=>t.id===e);if(!t){clearInterval(Hh),Hh=null;return}let n=await Fh(t.url,t.token);if(n.online){clearInterval(Hh),Hh=null,n.version&&y.agentVersions.set(e,n.version),n.workdir&&y.agentWorkdirs.set(e,n.workdir),n.homeDir&&y.agentHomeDirs.set(e,n.homeDir);let r=Lh(n.platformName,n.arch);r&&y.agentSystemInfos.set(e,r),n.workdir&&zh(e,n.workdir),await Vh(t),Rh(e,!0)}}catch{}},3e3)}function Wh(){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 Gh(){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||(Wh(),$(y.agentPlatform||{}),Bh())}),document.addEventListener(`click`,t=>{!n.contains(t.target)&&t.target!==e&&(n.style.display=`none`)}),r.addEventListener(`click`,async e=>{e.stopPropagation(),y.activeAgentId;let n=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),r=eh(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=eh(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`),y.agentPlatform={...y.agentPlatform,connected:!1},await $(y.agentPlatform,!0),r?.id&&Rh(r.id,!1),Uh(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=eh(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 jh(),A(e.message||t(`sidePanel.agentAlreadyLatest`),`info`);return}e?.success?(await jh(),A(t(`sidePanel.agentUpdateRestarting`),`success`),y.agentPlatform={...y.agentPlatform,connected:!1},await $(y.agentPlatform,!0),r?.id&&Rh(r.id,!1),Uh(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=eh(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`),y.agentPlatform={...y.agentPlatform,connected:!1},await $(y.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 Bh(),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=eh(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 Kh=new Map,qh=8;function Jh(e,t){for(Kh.has(e)&&Kh.delete(e),Kh.set(e,t);Kh.size>qh;)Kh.delete(Kh.keys().next().value)}function Yh(e){let t=Kh.get(e);if(t!==void 0)return Kh.delete(e),Kh.set(e,t),t}function Xh(e){Kh.delete(e)}document.addEventListener(`DOMContentLoaded`,async()=>{await Ge(),mt(()=>{ct()}),Vi(),await Promise.allSettled([n().then(()=>{i(),$i(),o(()=>{i(),$i()})}),Ye(),Hi(),En()]),window.__tableBlocks=[],chrome.runtime.onMessage.addListener(e=>{if(e.type===`SCHEDULED_SESSION_UPDATED`){let t=e.sessionId,n=e.phase===`started`;t===y.activeSessionId?(y.generatingSessionIds.has(t)||y.pendingCallApiSessionIds.has(t)||ir().catch(()=>{}),n&&no(t)):t&&(n||Ft(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&&vh(e.selectedText),Li(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)),rn(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&&vh(e.selectedText),cn(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),y.agentPlatform={...y.agentPlatform,connected:e.connected},$(y.agentPlatform),oa(),Yi(),e.connected&&Vh()),e.type===`AGENT_CONNECTION_CHANGED`){if(r.debug(`[SidePanel] recei to Agent connection statuschanged:`,e.connected,e.agentId),!e.connected){y.agentPlatform={connected:!1},$(y.agentPlatform),oa(),Yi();return}e.agentId&&(async()=>{try{let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),t=eh(e.pairedAgents).find(t=>t.id===e.activeAgentId&&!t.disabled);if(!t){y.agentPlatform={connected:!1},$(y.agentPlatform),oa(),Yi(),Br();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){y.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&&y.agentVersions.set(e.activeAgentId,t.version),t.workdir&&y.agentWorkdirs.set(e.activeAgentId,t.workdir),t.homeDir&&y.agentHomeDirs.set(e.activeAgentId,t.homeDir);let n=Lh(t.platformName||t.platform,t.arch);n&&y.agentSystemInfos.set(e.activeAgentId,n)}else y.agentPlatform={connected:!1}}else y.agentPlatform={connected:!1}}catch{y.agentPlatform={connected:!1}}else try{let n=await fetch(`${t.url}/api/status`,{cache:`no-cache`});if(n.ok){let t=await n.json();y.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&&y.agentVersions.set(e.activeAgentId,t.version);let r=Lh(t.platformName||t.platform,t.arch);r&&y.agentSystemInfos.set(e.activeAgentId,r)}else y.agentPlatform={connected:!1}}catch{y.agentPlatform={connected:!1}}}catch{y.agentPlatform={connected:!1}}$(y.agentPlatform),oa(),Yi(),Br()})()}e.type===`SCREENSHOT_RESULT`&&e.dataUrl&&(r.debug(`[SidePanel] received pageshortcutscreenshotresult:`,e.mode),_r(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:`,y.currentTabId);return}y.currentTabId=t.tabId}),chrome.tabs.onUpdated.addListener(async(e,t)=>{t.status===`complete`&&y.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 _(){if(!a||y.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=>{(!y.activeAgentId||y.activeAgentId==="default")&&(e.temperature!==void 0&&(y.temperature=e.temperature),e.topP!==void 0&&(y.topP=e.topP),e.selectedTempIndex!==void 0&&(y.selectedTempIndex=e.selectedTempIndex)),ee()});function ee(){h&&(h.value=y.temperature),g&&(g.value=y.temperature.toFixed(2));let e=document.getElementById(`tempIconValue`);e&&(e.textContent=y.temperature.toFixed(2)),te()}function v(){let e=0,t=Math.abs(zi[0].temp-y.temperature);for(let n=1;n<zi.length;n++){let r=Math.abs(zi[n].temp-y.temperature);r<t&&(t=r,e=n)}return e}function te(){let e=v();m.innerHTML=zi.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,22 +660,22 @@ 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=Bi[e];t&&(v.selectedTempIndex=e,v.temperature=t.temp,te(),Xm(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)),_(),Xm(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)),_(),Xm(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(),oh(t),uh(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,oh(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(),Gd(),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(()=>{}),Ym(),v.enableImageInput=e.enableImageInput||!1,v.imageModelName=e.imageModelName||``,v.imageApiBase=e.imageApiBase||``,v.imageApiKey=le(e.imageApiKey)||``,v.enableFileInput=!0,Er(),sa(),Tn(),ah(e.customModels,()=>{t&&ih(t)})}),chrome.storage.onChanged.addListener((e,t)=>{if(t===`local`){if(e.customModels&&ah(e.customModels.newValue||[],()=>{ih(v.currentModel)}),e.modelName){let t=e.modelName.newValue;t&&(!v.activeAgentId||v.activeAgentId==="default")&&(v.currentModel=t,ih(t))}if(e.enableImageInput&&(v.enableImageInput=e.enableImageInput.newValue,Er()),e.enableFileInput&&(v.enableFileInput=e.enableFileInput.newValue,sa()),e.enableExecutionLog&&(v.chatConfig.enableExecutionLog=e.enableExecutionLog.newValue),e.showMessageTimestamp){let t=e.showMessageTimestamp.newValue!==!1;v.chatConfig.showMessageTimestamp=t,ei(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 ar(),await em();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)),oh(t),setTimeout(()=>{Ri(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&&oh(t),setTimeout(()=>{ln(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=Mn(a);e&&Ih(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=Lh(n),d=v.messageHistory&&v.messageHistory.length>0;if(u&&!l&&d){if(a.innerHTML=u,pr(a),ct(),ft(),!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)})}bn();return}if(a.innerHTML=``,d){if(v.messageHistory.forEach(e=>{e.htmlContent?zr(e.htmlContent,e.messageId,e.resumable):ua(e.role,e.content,!1,e.executionLog||[],e.reflectionScore,e.wasRevised,null,e.messageId,[],e.resumable||!1,e.timestamp??null)}),Et(),Zn(),ct(),ft(),!v.pendingCallApiSessionIds.has(n)){let e=Mn(a);e&&Ih(n,e)}bn()}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(),ne(parseInt(e.dataset.index))})})}function ne(e){let t=zi[e];t&&(y.selectedTempIndex=e,y.temperature=t.temp,ee(),ch(y.temperature,y.topP,y.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)),y.temperature=t,g.value=t.toFixed(2);let n=document.getElementById(`tempIconValue`);n&&(n.textContent=t.toFixed(2)),te(),ch(y.temperature,y.topP,v())}),g.addEventListener(`change`,e=>{e.stopPropagation();let t=parseFloat(e.target.value);isNaN(t)&&(t=0),t=Math.max(0,Math.min(1,t)),y.temperature=t,h.value=t,g.value=t.toFixed(2);let n=document.getElementById(`tempIconValue`);n&&(n.textContent=t.toFixed(2)),te(),ch(y.temperature,y.topP,v())}),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=>{ws(e.target)&&(y.lastMouseX=e.clientX,y.lastMouseY=e.clientY)}),document.addEventListener(`mouseup`,e=>{ws(e.target)&&(y.lastMouseX=e.clientX,y.lastMouseY=e.clientY,y.enableSelectionQuery&&setTimeout(()=>{let e=window.getSelection();if(e&&!e.isCollapsed&&e.toString().trim()){let t=e.toString().trim();ws(e.anchorNode)&&(y.lastSelectedText=t,y.currentSelectionRange=e.getRangeAt(0).cloneRange(),vh(t),Sh(e,t,y.lastMouseX,y.lastMouseY))}else ws(e.anchorNode)||(y.lastSelectedText=``,y.currentSelectionRange=null,window.hideFloatingMenu())},50))});let x=``,S=null;async function C(){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!==x&&(x=n,vh(n.trim())):x=``}}catch{}}function w(){S&&=(clearInterval(S),null),y.enableSelectionQuery&&(S=setInterval(C,500))}w(),chrome.storage.onChanged.addListener((e,t)=>{if(t===`local`&&`enableSelectionQuery`in e){y.enableSelectionQuery=e.enableSelectionQuery.newValue;let t=document.getElementById(`enableSelectionQueryBtn`);t&&(t.checked=y.enableSelectionQuery),w()}}),await b(),qd(),chrome.storage.local.get([`modelName`,`customModels`,`customPrompts`,`systemPrompt`,`inputHistory`,`agentPlatform`,`enableImageInput`,`imageModelName`,`imageApiBase`,`imageApiKey`,`enableFileInput`],e=>{let t=e.modelName;t&&(y.currentModel=t),y.customPrompts=e.customPrompts||[],y.systemPrompt=e.systemPrompt||``,y.inputHistory=e.inputHistory||[],e.agentPlatform&&(y.agentPlatform=e.agentPlatform),$(y.agentPlatform),chrome.runtime.sendMessage({type:`TRIGGER_AGENT_HEALTH_CHECK`}).catch(()=>{}),sh(),y.enableImageInput=e.enableImageInput||!1,y.imageModelName=e.imageModelName||``,y.imageApiBase=e.imageApiBase||``,y.imageApiKey=ce(e.imageApiKey)||``,y.enableFileInput=!0,Tr(),oa(),wn(),_h(e.customModels,()=>{t&&gh(t)})}),chrome.storage.onChanged.addListener((e,t)=>{if(t===`local`){if(e.customModels&&_h(e.customModels.newValue||[],()=>{gh(y.currentModel)}),e.modelName){let t=e.modelName.newValue;t&&(!y.activeAgentId||y.activeAgentId==="default")&&(y.currentModel=t,gh(t))}if(e.enableImageInput&&(y.enableImageInput=e.enableImageInput.newValue,Tr()),e.enableFileInput&&(y.enableFileInput=e.enableFileInput.newValue,oa()),e.enableExecutionLog&&(y.chatConfig.enableExecutionLog=e.enableExecutionLog.newValue),e.showMessageTimestamp){let t=e.showMessageTimestamp.newValue!==!1;y.chatConfig.showMessageTimestamp=t,$r(t)}e.systemPrompt&&(y.systemPrompt=e.systemPrompt.newValue||``),e.imageModelName&&(y.imageModelName=e.imageModelName.newValue||``),e.imageApiBase&&(y.imageApiBase=e.imageApiBase.newValue||``),e.imageApiKey&&(y.imageApiKey=ce(e.imageApiKey.newValue)||``)}}),await ir(),await fm();let T=await chrome.storage.session.get([`pendingSelectionSearch`,`pendingFillInput`,`pendingDirectSend`]),re=[];if(T.pendingSelectionSearch&&T.pendingSelectionSearch.selectedText){let{prompt:e,selectedText:t}=T.pendingSelectionSearch;r.debug(`[SidePanel] pending selected textsearch:`,t?.substring(0,50)),vh(t),setTimeout(()=>{Li(e,t)},500),re.push(`pendingSelectionSearch`)}if(T.pendingFillInput&&T.pendingFillInput.text){let{text:e}=T.pendingFillInput;r.debug(`[SidePanel] pending fill trackasktext:`,e?.substring(0,50)),setTimeout(()=>{rn(e)},500),re.push(`pendingFillInput`)}if(T.pendingDirectSend&&T.pendingDirectSend.text){let{text:e,selectedText:t}=T.pendingDirectSend;r.debug(`[SidePanel] pending directsend text:`,e?.substring(0,50)),t&&vh(t),setTimeout(()=>{cn(e,t||``)},500),re.push(`pendingDirectSend`)}re.length>0&&await chrome.storage.session.remove(re);let ie=document.getElementById(`userInput`);ie&&ie.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&&y.messageHistory?.some(e=>e.resumable);if(i&&!y.pendingCallApiSessionIds.has(i)&&!s){let e=jn(a);e&&Jh(i,e)}let c=document.getElementById(`imagePreviewBar`);y.attachedImages.length>0&&c&&c.style.display===`none`&&(y.attachedImages=[]),y.executionLogListener&&=(chrome.runtime.onMessage.removeListener(y.executionLogListener),null),oe(),o&&o.focus();let l=y.pendingCallApiSessionIds.has(n)&&!!y.pendingCancelApi,u=Yh(n),d=y.messageHistory&&y.messageHistory.length>0;if(u&&!l&&d){if(a.innerHTML=u,fr(a),ht(),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)})}yn();return}if(a.innerHTML=``,d){if(y.messageHistory.forEach(e=>{e.htmlContent?Rr(e.htmlContent,e.messageId,e.resumable):la(e.role,e.content,!1,e.executionLog||[],e.reflectionScore,e.wasRevised,null,e.messageId,[],e.resumable||!1,e.timestamp??null)}),Tt(),Xn(),ht(),dt(),!y.pendingCallApiSessionIds.has(n)){let e=jn(a);e&&Jh(n,e)}yn()}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`),Un(n)),ro(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-Btg9ZLat.js`).then(e=>e.ht);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&&Rh(t)}),document.querySelectorAll(`.model-option`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation();let n=e.dataset.value;v.currentModel=n,ih(n),Jm(n),Zr()})}),document.addEventListener(`agent-model-changed`,()=>{ih(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`),ai()),r&&!r.contains(e.target)&&gr();let a=document.getElementById(`fileAtSelector`);if(a&&!a.contains(e.target)&&gf(),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())||tn();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){Pi();return}se()?mn():mi(s)}),w?.addEventListener(`click`,()=>mi(w));function T(e){if(!v.isGenerating)return!1;let n=v.activeSessionId;return n?da(n)?(Jn(n),mi(w&&w.style.display!==`none`?w:e||s)?(k(t(`queue.stopAndSendStarted`),`success`,2500),!0):(Oi(n),!0)):(k(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||!da(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||!da(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`),fe=document.getElementById(`shortcutsModal`),pe=document.getElementById(`shortcutsCloseBtn`);function me(){fe&&(fe.style.display=`flex`)}function he(){fe&&(fe.style.display=`none`)}de&&de.addEventListener(`click`,e=>{e.stopPropagation(),me();let t=document.getElementById(`headerMoreDropdown`);t&&t.classList.remove(`show`)}),pe&&pe.addEventListener(`click`,he),fe&&fe.addEventListener(`click`,e=>{e.target===fe&&he()});let ge=xs();Gt(),ur({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`?pi():yr()}if(e.key===`Escape`&&on()){e.preventDefault();return}if(!(e.key===`Escape`&&ge.handleEscape())){if(e.key===`Escape`&&fe&&fe.style.display!==`none`){he();return}if(e.altKey&&e.code===`Slash`){e.preventDefault(),me();return}if(e.altKey&&!e.shiftKey&&e.code===`KeyS`&&!e.ctrlKey&&!e.metaKey){e.preventDefault(),Yr();return}if(e.altKey&&e.shiftKey&&e.code===`KeyS`&&!e.ctrlKey&&!e.metaKey){e.preventDefault(),Gr();return}if(or(e)){e.preventDefault(),mr();return}if(e.altKey&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&e.code===`KeyN`){e.preventDefault(),Li();return}if(e.altKey&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&e.code===`KeyW`){e.preventDefault(),Cr();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){Di(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`;ge.jumpToMessage(t,e.ctrlKey||e.metaKey),ge.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($t);for(let e=0;e<t.length;e++)if(r=(r+1)%t.length,n(t[r])){Ii(t[r]);break}return}let r,i;n?(r=document.getElementById(`agentAtList`),i=v.selectedAgentAtIndex):$t===`pages`?(r=document.getElementById(`agentPageList`),i=v.selectedPageIndex):$t===`proxies`?(r=document.getElementById(`agentProxyList`),i=v.selectedProxyAtIndex):$t===`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,Ar(a)):$t===`proxies`?(v.selectedProxyAtIndex=t,Ar(a)):$t===`knowledge`?(v.selectedKnowledgeAtIndex=t,Ar(a)):$t===`pages`?(v.selectedPageIndex=t,er(a)):(v.selectedAgentAtIndex=t,Ar(a));return}else if(e.key===`ArrowUp`){e.preventDefault();let t=i<0||i===0?o-1:i-1;n?(v.selectedAgentAtIndex=t,Ar(a)):$t===`proxies`?(v.selectedProxyAtIndex=t,Ar(a)):$t===`knowledge`?(v.selectedKnowledgeAtIndex=t,Ar(a)):$t===`pages`?(v.selectedPageIndex=t,er(a)):(v.selectedAgentAtIndex=t,Ar(a));return}else if(e.key===`Enter`&&i>=0){e.preventDefault();let t=a[i];if(t.dataset.type===`knowledge`){ir({id:t.dataset.kbId,name:t.dataset.kbName,enabled:t.dataset.kbDisabled!==`1`},{multi:e.ctrlKey||e.metaKey});return}t.click(),(e.ctrlKey||e.metaKey)&&gr();return}else if(e.key===`Escape`){gr();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,xf(n));return}if(e.key===`Enter`&&r>0&&v.selectedFileAtIndex>=0){e.preventDefault(),n[v.selectedFileAtIndex].click();return}if(e.key===`Escape`){e.preventDefault(),gf();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,en(t);return}if(e.key===`ArrowUp`){e.preventDefault(),v.selectedPromptIndex<0||v.selectedPromptIndex===0?v.selectedPromptIndex=r-1:--v.selectedPromptIndex,en(t);return}if(e.key===`Enter`&&v.selectedPromptIndex>=0){e.preventDefault();let n=t[v.selectedPromptIndex],r=e.ctrlKey||e.metaKey;n.dataset.type===`skill`?Wi(n.dataset.skillName,{multi:r}):n.dataset.type===`mcp`?ci(n.dataset.serverId,n.dataset.serverName,{multi:r}):r?ti(n.dataset.code):_n(n.dataset.code);return}if(e.key===`Escape`){ai();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,Rt(t);return}if(e.key===`ArrowUp`){e.preventDefault(),v.selectedSkillIndex<0||v.selectedSkillIndex===0?v.selectedSkillIndex=r-1:--v.selectedSkillIndex,Rt(t);return}if(e.key===`Enter`&&v.selectedSkillIndex>=0){e.preventDefault();let n=t[v.selectedSkillIndex];Wi(n.dataset.skillName,{multi:e.ctrlKey||e.metaKey});return}if(e.key===`Escape`){ai();return}if(e.key===`Tab`){e.preventDefault();let t=document.getElementById(`mcpTab`);t&&t.style.display!==`none`?Qi(`mcp`):Qi(`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,Wn(t);return}if(e.key===`ArrowUp`){e.preventDefault(),v.selectedMcpServiceIndex<0||v.selectedMcpServiceIndex===0?v.selectedMcpServiceIndex=r-1:--v.selectedMcpServiceIndex,Wn(t);return}if(e.key===`Enter`&&v.selectedMcpServiceIndex>=0){e.preventDefault();let n=t[v.selectedMcpServiceIndex];ci(n.dataset.serverId,n.dataset.serverName,{multi:e.ctrlKey||e.metaKey});return}if(e.key===`Escape`){ai();return}if(e.key===`Tab`){e.preventDefault(),Qi(`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(),Qi(`skills`);return}if(n&&n.style.display!==`none`){e.preventDefault(),Qi(`mcp`);return}}if(r!==0&&e.key===`ArrowDown`){e.preventDefault(),v.selectedPromptIndex<0?v.selectedPromptIndex=0:v.selectedPromptIndex=(v.selectedPromptIndex+1)%r,en(t);return}if(e.key===`ArrowUp`){e.preventDefault(),v.selectedPromptIndex<0||v.selectedPromptIndex===0?v.selectedPromptIndex=r-1:--v.selectedPromptIndex,en(t);return}if(e.key===`Enter`&&(e.ctrlKey||e.metaKey)&&v.selectedPromptIndex>=0){e.preventDefault();let n=t[v.selectedPromptIndex].dataset.code;ti(n);return}if(e.key===`Enter`&&v.selectedPromptIndex>=0){e.preventDefault();let n=t[v.selectedPromptIndex].dataset.code;_n(n);return}if(e.key===`Escape`){ai();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()&&!tn()&&Jp()){e.preventDefault();return}if(!c&&!l&&!u){let t=Tp({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(),gf(),v.isGenerating){if(e.altKey){Qn(a.value);return}mn();return}Pi()}}),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&&En(t);break}if(n.kind===`file`&&v.enableFileInput){e.preventDefault();let t=n.getAsFile();t&&Gn([t]);break}}});let _e=document.getElementById(`fileAttachBtn`),ve=document.getElementById(`fileInput`);_e&&ve&&(_e.addEventListener(`click`,()=>{ve.click()}),ve.addEventListener(`change`,async()=>{if(ve.files.length>0){let e=Array.from(ve.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 En(e);else k(t(`sidePanel.imageNotEnabled`)),Gn(n);r.length>0&&Gn(r),ve.value=``}}));let ye=document.querySelector(`.input-wrapper`),be=0;ye&&(ye.addEventListener(`dragenter`,e=>{e.preventDefault(),e.stopPropagation(),be++,ye.classList.add(`drag-over`)}),ye.addEventListener(`dragleave`,e=>{e.preventDefault(),e.stopPropagation(),be--,be<=0&&(be=0,ye.classList.remove(`drag-over`))}),ye.addEventListener(`dragover`,e=>{e.preventDefault(),e.stopPropagation()}),ye.addEventListener(`drop`,async e=>{e.preventDefault(),e.stopPropagation(),be=0,ye.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){li([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 En(e);else k(t(`sidePanel.imageNotEnabled`)),Gn(n);r.length>0&&Gn(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 xe=document.getElementById(`screenshotBtn`);xe&&xe.addEventListener(`click`,async()=>{if(v.enableImageInput)try{await Yr()}catch(e){r.error(`[SidePanel] screenshot failed:`,e),k(t(`sidePanel.screenshotFailed`))}}),oi(),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=Pr({value:t,caret:a.selectionStart});i&&i.key===`dollar`?(ai(),gr(),hf(i.filterText)):i&&i.key===`at`?(ai(),gf(),bi(i.filterText)):i&&i.key===`slash`?(gr(),gf(),n.style.display!==`none`&&r.classList.contains(`show`)?Ht(i.filterText):kn(i.filterText)):(ai(),gr(),gf()),ee()});let Se=Ep((e,t)=>{chrome.storage.local.set({[e]:t})},200);u.addEventListener(`scroll`,()=>{Se(`scrollPosition_`+(v.activeSessionId||`default`),u.scrollTop)}),window.addEventListener(`pagehide`,()=>{chrome.storage.local.set({[`scrollPosition_`+(v.activeSessionId||`default`)]:u.scrollTop})});let Ce=document.getElementById(`headerMoreBtn`),we=document.getElementById(`headerMoreDropdown`);Ce&&we&&(Ce.addEventListener(`click`,e=>{e.stopPropagation(),we.classList.toggle(`show`)}),document.addEventListener(`click`,e=>{!we.contains(e.target)&&e.target!==Ce&&Ae()}));let Te=document.getElementById(`themeToggleBtn`),Ee=document.getElementById(`themeToggleLabel`),De=document.getElementById(`themeSubmenu`),Oe=e=>t(e===`dark`?`settings.themeDark`:e===`system`?`settings.themeSystem`:`settings.themeLight`),ke=()=>{let e=st();Ee&&(Ee.textContent=t(`header.themeToggle`,{theme:Oe(e)})),De&&De.querySelectorAll(`.theme-submenu-item`).forEach(t=>{t.classList.toggle(`active`,t.dataset.themeValue===e)}),Te&&Te.setAttribute(`aria-expanded`,String(!!(De&&De.classList.contains(`show`))))};function Ae(){De&&De.classList.remove(`show`),we&&we.classList.remove(`show`),Te&&Te.setAttribute(`aria-expanded`,`false`)}Te&&De&&(Te.addEventListener(`click`,e=>{e.stopPropagation(),De.classList.toggle(`show`),ke()}),De.querySelectorAll(`.theme-submenu-item`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),Ke(e.dataset.themeValue),Ae()})})),ke(),lt(ke),o(ke),c.addEventListener(`click`,e=>{e.stopPropagation(),Ae(),Si()}),l&&l.addEventListener(`click`,e=>{e.stopPropagation(),Ae(),vn()});let je=document.getElementById(`importChatBtn`);je&&je.addEventListener(`click`,e=>{e.stopPropagation(),Ae(),Sn()});let Me=document.getElementById(`importSessionsFile`);Me&&Me.addEventListener(`change`,e=>{let t=e.target.files[0];t&&Ct(t)});let Ne=document.getElementById(`settingsBtn`);Ne&&Ne.addEventListener(`click`,()=>{chrome.runtime.openOptionsPage()});let Pe=document.getElementById(`headerAgentIndicator`);Pe&&Pe.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 Fe=document.getElementById(`prototypeLibraryBtn`);Fe&&Fe.addEventListener(`click`,e=>{e.stopPropagation(),Ae(),$r()});let D=document.getElementById(`tokenStatsHeaderBtn`);D&&D.addEventListener(`click`,e=>{e.stopPropagation(),Ae(),window.openTokenStats&&window.openTokenStats()});let Ie=document.getElementById(`auditLogBtn`),Le=document.getElementById(`auditLogOverlay`),Re=document.getElementById(`auditLogClose`),ze=document.getElementById(`auditLogRefreshBtn`),Be=document.getElementById(`auditLogCategoryFilter`),Ve=document.getElementById(`auditLogLimit`),He=document.getElementById(`auditLogSearch`),Ue=document.getElementById(`auditLogSearchClear`),We=document.getElementById(`auditLogLoading`),Ge=document.getElementById(`auditLogEmpty`),O=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`)},Ye={info:`INFO`,warn:`WARN`,error:`ERROR`},Xe={info:`audit-level-info`,warn:`audit-level-warn`,error:`audit-level-error`};function Ze(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(!We||!Ge||!O)return;We.style.display=`block`,Ge.style.display=`none`,O.style.display=`none`;let e=Be?.value||null,n=parseInt(Ve?.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(We.style.display=`none`,!r||!r.success){Ge.style.display=`block`,Ge.textContent=t(`sidePanel.auditQueryFailed`,{error:r?.error||t(`sidePanel.unknownError`)});return}qe=r.entries||[],tt()}catch(e){We.style.display=`none`,Ge.style.display=`block`,Ge.textContent=t(`sidePanel.auditLoadFailed`,{error:e.message})}}function tt(){if(!O)return;let e=(He?.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))),Ue&&(Ue.style.display=e?`block`:`none`),We.style.display=`none`,n.length===0){Ge.style.display=`block`,Ge.textContent=t(e?`sidePanel.auditNoMatch`:`sidePanel.auditEmpty`),O.style.display=`none`;return}Ge.style.display=`none`,O.style.display=`block`,O.innerHTML=n.map(e=>{let t=A(Je[e.category]||e.category||`-`),n=A(Ye[e.level]||e.level?.toUpperCase()||`INFO`),r=Xe[e.level]||`audit-level-info`,i=Ze(e.timestamp),a=A($e(e));return`<div class="audit-entry">
669
+ `,a.appendChild(e)}if(r.debug(`[SidePanel] session-switched: pendingTask?`,l,`pendingSessionIds:`,[...y.pendingCallApiSessionIds],`activeSessionId:`,n,`hasCancelApi:`,!!y.pendingCancelApi),l&&(r.debug(`[SidePanel] switch back tobackground task session,rebuildstreamingoutput element`),Hn(n)),no(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 D(async()=>{let{updateScrollButtonState:e}=await import(`./context-indicator-DjOAo_Ln.js`).then(e=>e.ht);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&&Xh(t)}),document.querySelectorAll(`.model-option`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation();let n=e.dataset.value;y.currentModel=n,gh(n),oh(n),Xr()})}),document.addEventListener(`agent-model-changed`,()=>{gh(y.currentModel);let e=document.getElementById(`tempSlider`),t=document.getElementById(`tempNumberInput`),n=document.getElementById(`tempIconValue`);e&&(e.value=y.temperature),t&&(t.value=y.temperature.toFixed(2)),n&&(n.textContent=y.temperature.toFixed(2)),te()}),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`),ii()),r&&!r.contains(e.target)&&hr();let a=document.getElementById(`fileAtSelector`);if(a&&!a.contains(e.target)&&Df(),i&&!i.contains(e.target)){let t=window.getSelection(),n=ws(e.target),r=t&&!t.isCollapsed&&ws(t.anchorNode);(!n||!r)&&window.hideFloatingMenu()}});let E=document.getElementById(`stopCompanionBtn`);function ae(){let e=!!(a&&a.value&&a.value.trim())||en();return y.isGenerating&&e}function oe(){a&&a.value&&a.value.trim();let e=y.isGenerating,n=ae();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=``,E&&(E.style.display=n?``:`none`,E.disabled=!1,E.style.opacity=``,E.style.cursor=``)}s.addEventListener(`click`,()=>{if(!y.isGenerating){Ni();return}ae()?pn():pi(s)}),E?.addEventListener(`click`,()=>pi(E));function se(e){if(!y.isGenerating)return!1;let n=y.activeSessionId;return n?ua(n)?(qn(n),pi(E&&E.style.display!==`none`?E:e||s)?(A(t(`queue.stopAndSendStarted`),`success`,2500),!0):(Di(n),!0)):(A(t(`queue.stopAndSendEmpty`),`warning`,3e3),!1):!1}function le(e,{isPrimarySend:t=!1}={}){if(!e)return;let n=()=>t&&ae();e.addEventListener(`contextmenu`,t=>{n()||!y.isGenerating||!ua(y.activeSessionId)||(t.preventDefault(),se(e))});let r=null,i=()=>{r&&=(clearTimeout(r),null)};e.addEventListener(`pointerdown`,t=>{t.pointerType===`mouse`&&t.button!==0||n()||!y.isGenerating||!ua(y.activeSessionId)||(i(),r=setTimeout(()=>{r=null,se(e)},600))});for(let t of[`pointerup`,`pointerleave`,`pointercancel`])e.addEventListener(t,i)}le(s,{isPrimarySend:!0}),le(E),document.addEventListener(`queue-stop-and-send`,()=>{se(E&&E.style.display!==`none`?E:s)}),document.addEventListener(`generating-state-changed`,oe),a.addEventListener(`input`,oe),document.addEventListener(`input-attachments-changed`,oe),document.addEventListener(`voice-draft-written`,oe);let ue=document.getElementById(`shortcutsBtn`),de=document.getElementById(`shortcutsModal`),fe=document.getElementById(`shortcutsCloseBtn`);function pe(){de&&(de.style.display=`flex`)}function me(){de&&(de.style.display=`none`)}ue&&ue.addEventListener(`click`,e=>{e.stopPropagation(),pe();let t=document.getElementById(`headerMoreDropdown`);t&&t.classList.remove(`show`)}),fe&&fe.addEventListener(`click`,me),de&&de.addEventListener(`click`,e=>{e.target===de&&me()});let he=Cs();Wt(),lr({adjustInputHeight:_}).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():vr()}if(e.key===`Escape`&&an()){e.preventDefault();return}if(!(e.key===`Escape`&&he.handleEscape())){if(e.key===`Escape`&&de&&de.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(),Jr();return}if(e.altKey&&e.shiftKey&&e.code===`KeyS`&&!e.ctrlKey&&!e.metaKey){e.preventDefault(),Wr();return}if(ar(e)){e.preventDefault(),pr();return}if(e.altKey&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&e.code===`KeyN`){e.preventDefault(),Ii();return}if(e.altKey&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&e.code===`KeyW`){e.preventDefault(),Sr();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){Ei(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(Qt);for(let e=0;e<t.length;e++)if(r=(r+1)%t.length,n(t[r])){Fi(t[r]);break}return}let r,i;n?(r=document.getElementById(`agentAtList`),i=y.selectedAgentAtIndex):Qt===`pages`?(r=document.getElementById(`agentPageList`),i=y.selectedPageIndex):Qt===`proxies`?(r=document.getElementById(`agentProxyList`),i=y.selectedProxyAtIndex):Qt===`knowledge`?(r=document.getElementById(`agentKnowledgeList`),i=y.selectedKnowledgeAtIndex):(r=document.getElementById(`agentAtList`),i=y.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?(y.selectedAgentAtIndex=t,kr(a)):Qt===`proxies`?(y.selectedProxyAtIndex=t,kr(a)):Qt===`knowledge`?(y.selectedKnowledgeAtIndex=t,kr(a)):Qt===`pages`?(y.selectedPageIndex=t,$n(a)):(y.selectedAgentAtIndex=t,kr(a));return}else if(e.key===`ArrowUp`){e.preventDefault();let t=i<0||i===0?o-1:i-1;n?(y.selectedAgentAtIndex=t,kr(a)):Qt===`proxies`?(y.selectedProxyAtIndex=t,kr(a)):Qt===`knowledge`?(y.selectedKnowledgeAtIndex=t,kr(a)):Qt===`pages`?(y.selectedPageIndex=t,$n(a)):(y.selectedAgentAtIndex=t,kr(a));return}else if(e.key===`Enter`&&i>=0){e.preventDefault();let t=a[i];if(t.dataset.type===`knowledge`){rr({id:t.dataset.kbId,name:t.dataset.kbName,enabled:t.dataset.kbDisabled!==`1`},{multi:e.ctrlKey||e.metaKey});return}t.click(),(e.ctrlKey||e.metaKey)&&hr();return}else if(e.key===`Escape`){hr();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&&(y.selectedFileAtIndex=e.key===`ArrowDown`?y.selectedFileAtIndex<0?0:(y.selectedFileAtIndex+1)%r:y.selectedFileAtIndex<0||y.selectedFileAtIndex===0?r-1:y.selectedFileAtIndex-1,Mf(n));return}if(e.key===`Enter`&&r>0&&y.selectedFileAtIndex>=0){e.preventDefault(),n[y.selectedFileAtIndex].click();return}if(e.key===`Escape`){e.preventDefault(),Df();return}}if(t.style.display!==`none`&&n.classList.contains(`show`)){if(y.showMergedList){let t=n.querySelectorAll(`#promptList .prompt-item`),r=t.length;if(e.key===`ArrowDown`){e.preventDefault(),y.selectedPromptIndex<0?y.selectedPromptIndex=0:y.selectedPromptIndex=(y.selectedPromptIndex+1)%r,$t(t);return}if(e.key===`ArrowUp`){e.preventDefault(),y.selectedPromptIndex<0||y.selectedPromptIndex===0?y.selectedPromptIndex=r-1:--y.selectedPromptIndex,$t(t);return}if(e.key===`Enter`&&y.selectedPromptIndex>=0){e.preventDefault();let n=t[y.selectedPromptIndex],r=e.ctrlKey||e.metaKey;n.dataset.type===`skill`?Ui(n.dataset.skillName,{multi:r}):n.dataset.type===`mcp`?si(n.dataset.serverId,n.dataset.serverName,{multi:r}):r?ei(n.dataset.code):gn(n.dataset.code);return}if(e.key===`Escape`){ii();return}return}if(y.activeDropdownTab===`skills`){let t=n.querySelectorAll(`#skillList .skill-list-item`),r=t.length;if(e.key===`ArrowDown`){e.preventDefault(),y.selectedSkillIndex<0?y.selectedSkillIndex=0:y.selectedSkillIndex=(y.selectedSkillIndex+1)%r,Lt(t);return}if(e.key===`ArrowUp`){e.preventDefault(),y.selectedSkillIndex<0||y.selectedSkillIndex===0?y.selectedSkillIndex=r-1:--y.selectedSkillIndex,Lt(t);return}if(e.key===`Enter`&&y.selectedSkillIndex>=0){e.preventDefault();let n=t[y.selectedSkillIndex];Ui(n.dataset.skillName,{multi:e.ctrlKey||e.metaKey});return}if(e.key===`Escape`){ii();return}if(e.key===`Tab`){e.preventDefault();let t=document.getElementById(`mcpTab`);t&&t.style.display!==`none`?Zi(`mcp`):Zi(`prompts`);return}return}if(y.activeDropdownTab===`mcp`){let t=n.querySelectorAll(`#mcpList .mcp-list-item`),r=t.length;if(e.key===`ArrowDown`){e.preventDefault(),y.selectedMcpServiceIndex<0?y.selectedMcpServiceIndex=0:y.selectedMcpServiceIndex=(y.selectedMcpServiceIndex+1)%r,Un(t);return}if(e.key===`ArrowUp`){e.preventDefault(),y.selectedMcpServiceIndex<0||y.selectedMcpServiceIndex===0?y.selectedMcpServiceIndex=r-1:--y.selectedMcpServiceIndex,Un(t);return}if(e.key===`Enter`&&y.selectedMcpServiceIndex>=0){e.preventDefault();let n=t[y.selectedMcpServiceIndex];si(n.dataset.serverId,n.dataset.serverName,{multi:e.ctrlKey||e.metaKey});return}if(e.key===`Escape`){ii();return}if(e.key===`Tab`){e.preventDefault(),Zi(`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(),Zi(`skills`);return}if(n&&n.style.display!==`none`){e.preventDefault(),Zi(`mcp`);return}}if(r!==0&&e.key===`ArrowDown`){e.preventDefault(),y.selectedPromptIndex<0?y.selectedPromptIndex=0:y.selectedPromptIndex=(y.selectedPromptIndex+1)%r,$t(t);return}if(e.key===`ArrowUp`){e.preventDefault(),y.selectedPromptIndex<0||y.selectedPromptIndex===0?y.selectedPromptIndex=r-1:--y.selectedPromptIndex,$t(t);return}if(e.key===`Enter`&&(e.ctrlKey||e.metaKey)&&y.selectedPromptIndex>=0){e.preventDefault();let n=t[y.selectedPromptIndex].dataset.code;ei(n);return}if(e.key===`Enter`&&y.selectedPromptIndex>=0){e.preventDefault();let n=t[y.selectedPromptIndex].dataset.code;gn(n);return}if(e.key===`Escape`){ii();return}}if(e.key===`Escape`){y.inputHistoryIndex>=0&&(y.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`&&y.inputHistoryIndex===-1&&!a.value.trim()&&!en()&&om()){e.preventDefault();return}if(!c&&!l&&!u){let t=Lp({key:e.key,value:a.value,caret:a.selectionStart,history:y.inputHistory,index:y.inputHistoryIndex});if(t.handled){e.preventDefault(),y.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(y.isComposing)return;if(e.preventDefault(),Df(),y.isGenerating){if(e.altKey){Zn(a.value);return}pn();return}Ni()}}),a.addEventListener(`compositionstart`,()=>{y.isComposing=!0}),a.addEventListener(`compositionend`,()=>{y.isComposing=!1}),a.addEventListener(`paste`,e=>{let t=e.clipboardData?.items;if(t)for(let n of t){if(n.type.startsWith(`image/`)&&y.enableImageInput){e.preventDefault();let t=n.getAsFile();t&&Tn(t);break}if(n.kind===`file`&&y.enableFileInput){e.preventDefault();let t=n.getAsFile();t&&Wn([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(y.enableImageInput)for(let e of n)await Tn(e);else A(t(`sidePanel.imageNotEnabled`)),Wn(n);r.length>0&&Wn(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){ci([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(y.enableImageInput)for(let e of n)await Tn(e);else A(t(`sidePanel.imageNotEnabled`)),Wn(n);r.length>0&&Wn(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(y.enableImageInput)try{await Jr()}catch(e){r.error(`[SidePanel] screenshot failed:`,e),A(t(`sidePanel.screenshotFailed`))}}),ai(),a.addEventListener(`wheel`,e=>{y.isScrolling=!0;let t=a.style.height||a.offsetHeight+`px`;a.style.height=t,a.scrollHeight<=a.clientHeight+10&&(e.preventDefault(),e.stopPropagation()),setTimeout(()=>{y.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=Nr({value:t,caret:a.selectionStart});i&&i.key===`dollar`?(ii(),hr(),Ef(i.filterText)):i&&i.key===`at`?(ii(),Df(),yi(i.filterText)):i&&i.key===`slash`?(hr(),Df(),n.style.display!==`none`&&r.classList.contains(`show`)?Vt(i.filterText):On(i.filterText)):(ii(),hr(),Df()),_()});let xe=Rp((e,t)=>{chrome.storage.local.set({[e]:t})},200);u.addEventListener(`scroll`,()=>{xe(`scrollPosition_`+(y.activeSessionId||`default`),u.scrollTop)}),window.addEventListener(`pagehide`,()=>{chrome.storage.local.set({[`scrollPosition_`+(y.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(),lt(e.dataset.themeValue),ke()})})),Oe(),mt(Oe),o(Oe),c.addEventListener(`click`,e=>{e.stopPropagation(),ke(),xi()}),l&&l.addEventListener(`click`,e=>{e.stopPropagation(),ke(),_n()});let Ae=document.getElementById(`importChatBtn`);Ae&&Ae.addEventListener(`click`,e=>{e.stopPropagation(),ke(),xn()});let je=document.getElementById(`importSessionsFile`);je&&je.addEventListener(`change`,e=>{let t=e.target.files[0];t&&St(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(),Qr()});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">
670
670
  <div class="audit-entry-header">
671
671
  <span class="audit-time">${i}</span>
672
672
  <span class="audit-level ${r}">${n}</span>
673
673
  <span class="audit-category">${t}</span>
674
- <span class="audit-action">${A(e.action||`-`)}</span>
674
+ <span class="audit-action">${k(e.action||`-`)}</span>
675
675
  </div>
676
676
  ${a?`<div class="audit-details">${a}</div>`:``}
677
- </div>`}).join(``)}function rt(){Le&&(Le.style.display=`flex`,et())}function at(){Le&&(Le.style.display=`none`)}Ie&&Ie.addEventListener(`click`,e=>{e.stopPropagation(),Ae(),rt()}),Re&&Re.addEventListener(`click`,at),ze&&ze.addEventListener(`click`,et),Be&&Be.addEventListener(`change`,et),Ve&&Ve.addEventListener(`change`,et),He&&He.addEventListener(`input`,()=>{tt()}),Ue&&Ue.addEventListener(`click`,()=>{He&&(He.value=``),tt()}),Vm(()=>v.activeSessionId,window.showCustomConfirm);let ut=document.getElementById(`isolateChatBtn`),dt=document.getElementById(`enableToolsBtn`),pt=document.getElementById(`toolsConfigBtn`),mt=`agentEnabledTools_${v.activeAgentId||`default`}`,ht=`agentMcpClosedServers_${v.activeAgentId||`default`}`;chrome.storage.local.get([mt,`enabledTools`,`isolateChat`,`enableSelectionQuery`,`enableTools`,ht,`mcpTools`,`mcpEnabled`,`ragTools`,`ragToolsIntroduced`],e=>{e.isolateChat!==void 0&&(v.isolateChat=e.isolateChat),ut.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-CeC2_dkP.js`).then(e=>e.t);return{getAgent:e}},__vite__mapDeps([7,1,2,3])).then(({getAgent:e})=>e(v.activeAgentId)).then(e=>{v.activeAgentMcpExcludedServerIds=e?e.mcpExcludedServerIds??null:null,Bt()}).catch(()=>{}),v.mcpClosedServers=e[ht]||[];let n=e.ragTools||[],r=e[mt],i=e.enabledTools;if(Array.isArray(r)){let t=Xr(n);v.enabledTools=r.filter(e=>t.has(e));let i=Ti(v.enabledTools,n,e.ragToolsIntroduced);v.enabledTools=i.tools,i.migrated?chrome.storage.local.set({ragToolsIntroduced:!0,[mt]:v.enabledTools}):v.enabledTools.length!==r.length&&chrome.storage.local.set({[mt]:v.enabledTools})}else if(i&&i.length>0){let t=Xr(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=Ti(v.enabledTools,n,e.ragToolsIntroduced);v.enabledTools=o.tools,chrome.storage.local.set({[mt]:v.enabledTools,...o.migrated?{ragToolsIntroduced:!0}:{}})}else{v.enabledTools=f.filter(e=>e.enabled).map(e=>e.id);let t=Ti(v.enabledTools,n,e.ragToolsIntroduced);v.enabledTools=t.tools,t.migrated&&chrome.storage.local.set({ragToolsIntroduced:!0,[mt]:v.enabledTools})}dt&&(dt.checked=v.useTools),Bt(),th(),S()}),ut.addEventListener(`change`,()=>{v.isolateChat=ut.checked,chrome.storage.local.set({isolateChat:v.isolateChat}),r.debug(`[SidePanel] conv memory:`,v.isolateChat?`enabled`:`disabled`)});let gt=document.getElementById(`enableSelectionQueryBtn`);gt&&gt.addEventListener(`change`,()=>{v.enableSelectionQuery=gt.checked,chrome.storage.local.set({enableSelectionQuery:v.enableSelectionQuery}),r.debug(`[SidePanel] text Q&A:`,v.enableSelectionQuery?`enabled`:`disabled`),!v.enableSelectionQuery&&v.selectedContextText&&Kt()}),dt&&dt.addEventListener(`change`,()=>{v.useTools=dt.checked,chrome.storage.local.set({enableTools:v.useTools}),r.debug(`[SidePanel] tool master switch:`,v.useTools?`enabled`:`disabled`),Bt()}),pt&&pt.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),yr()});let vt=document.getElementById(`toolsPopupOverlay`),yt=document.getElementById(`toolsPopupClose`),bt=vt?vt.querySelector(`.modal-container`):null;yt&&yt.addEventListener(`click`,pi),bt&&bt.addEventListener(`click`,e=>{e.stopPropagation()});let xt=document.getElementById(`toolsSearchInput`),St=document.getElementById(`toolsSearchClear`);xt&&xt.addEventListener(`input`,e=>{v.currentSearch=e.target.value.toLowerCase(),St&&(St.style.display=e.target.value?``:`none`),ca()}),St&&St.addEventListener(`click`,()=>{xt&&(xt.value=``,St.style.display=`none`,v.currentSearch=``,ca())});let wt=document.querySelectorAll(`.category-btn`);wt.forEach(e=>{e.addEventListener(`click`,()=>{wt.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,ca()})});let Tt=document.getElementById(`toolsCategories`);Tt&&Tt.addEventListener(`wheel`,e=>{e.preventDefault(),Tt.scrollLeft+=e.deltaY*2},{passive:!1});let Dt=document.getElementById(`toolsSelectAll`),Ot=document.getElementById(`toolsSelectNone`);Dt&&Dt.addEventListener(`click`,()=>{Kr().forEach(e=>{let t=document.getElementById(`tool_`+e.id);t&&(t.checked=!0),v.enabledTools.includes(e.id)||v.enabledTools.push(e.id)}),ia(!0),Hn(),Mt(),Kn()}),Ot&&Ot.addEventListener(`click`,()=>{Kr().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)}),ia(!1),Hn(),Mt(),Kn()});let kt=document.getElementById(`toolsPopupSave`);kt&&kt.addEventListener(`click`,()=>{Dr(),Kn()});let At=document.getElementById(`toolsPreselectToggle`);At&&At.addEventListener(`change`,()=>{chrome.storage.local.set({enableToolPreselect:At.checked},()=>{r.debug(`[SidePanel] toolpre-filter toggle updated:`,At.checked)})});let jt=document.getElementById(`toolConfirmToggle`);jt&&jt.addEventListener(`change`,()=>{chrome.storage.local.set({toolConfirmationEnabled:jt.checked},()=>{r.debug(`[SidePanel] sensitive-operation confirmation toggle updated:`,jt.checked)})});let Nt=document.getElementById(`toolsPopupCancel`);Nt&&Nt.addEventListener(`click`,()=>{pi()});let Pt=document.getElementById(`modalCancelBtn`),Ft=document.getElementById(`modalConfirmBtn`),Lt=document.getElementById(`toolStatsOverlay`),zt=document.getElementById(`toolStatsClose`),Vt=document.getElementById(`toolStatsBtn`);function Ut(){Lt&&(Lt.style.display=`flex`,Xt())}function Wt(){Lt&&(Lt.style.display=`none`)}Vt&&Vt.addEventListener(`click`,e=>{e.stopPropagation(),Ut()}),zt&&zt.addEventListener(`click`,Wt),Lt&&Lt.addEventListener(`click`,e=>{e.target===Lt&&Wt()});let qt=document.getElementById(`toolStatsRefreshBtn`);qt&&qt.addEventListener(`click`,Xt);let Jt=document.getElementById(`toolStatsClearBtn`);Jt&&Jt.addEventListener(`click`,async()=>{await window.showCustomConfirm(t(`sidePanel.clearStatsConfirm`),t(`sidePanel.clearStatsTitle`))&&(await chrome.storage.local.remove([`toolUsageStats`]),Xt())});let Yt={column:`callCount`,asc:!1};async function Xt(){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}),Zt(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="${A(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 Zt(e,t){let n=document.getElementById(`toolStatsTableBody`);if(!n)return;let{column:r,asc:i}=Yt;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=Qe(i);return`<tr>
678
- <td style="padding: 6px 10px; border-bottom: 1px solid var(--border-subtle); color: var(--text-primary);"><code title="${A(a)}">${e}</code></td>
677
+ </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()}),$m(()=>y.activeSessionId,window.showCustomConfirm);let st=document.getElementById(`isolateChatBtn`),j=document.getElementById(`enableToolsBtn`),ut=document.getElementById(`toolsConfigBtn`),ft=`agentEnabledTools_${y.activeAgentId||`default`}`,pt=`agentMcpClosedServers_${y.activeAgentId||`default`}`;chrome.storage.local.get([ft,`enabledTools`,`isolateChat`,`enableSelectionQuery`,`enableTools`,pt,`mcpTools`,`mcpEnabled`,`ragTools`,`ragToolsIntroduced`],e=>{e.isolateChat!==void 0&&(y.isolateChat=e.isolateChat),st.checked=y.isolateChat,e.enableSelectionQuery!==void 0&&(y.enableSelectionQuery=e.enableSelectionQuery);let t=document.getElementById(`enableSelectionQueryBtn`);t&&(t.checked=y.enableSelectionQuery),e.enableTools!==void 0&&(y.useTools=e.enableTools),y.activeAgentId&&D(async()=>{let{getAgent:e}=await import(`./agent-store-CeC2_dkP.js`).then(e=>e.t);return{getAgent:e}},__vite__mapDeps([7,1,2,3])).then(({getAgent:e})=>e(y.activeAgentId)).then(e=>{y.activeAgentMcpExcludedServerIds=e?e.mcpExcludedServerIds??null:null,zt()}).catch(()=>{}),y.mcpClosedServers=e[pt]||[];let n=e.ragTools||[],r=e[ft],i=e.enabledTools;if(Array.isArray(r)){let t=Yr(n);y.enabledTools=r.filter(e=>t.has(e));let i=wi(y.enabledTools,n,e.ragToolsIntroduced);y.enabledTools=i.tools,i.migrated?chrome.storage.local.set({ragToolsIntroduced:!0,[ft]:y.enabledTools}):y.enabledTools.length!==r.length&&chrome.storage.local.set({[ft]:y.enabledTools})}else if(i&&i.length>0){let t=Yr(n),r=i.filter(e=>t.has(e)),a=f.filter(e=>e.enabled&&!r.includes(e.id)).map(e=>e.id);y.enabledTools=[...r,...a];let o=wi(y.enabledTools,n,e.ragToolsIntroduced);y.enabledTools=o.tools,chrome.storage.local.set({[ft]:y.enabledTools,...o.migrated?{ragToolsIntroduced:!0}:{}})}else{y.enabledTools=f.filter(e=>e.enabled).map(e=>e.id);let t=wi(y.enabledTools,n,e.ragToolsIntroduced);y.enabledTools=t.tools,t.migrated&&chrome.storage.local.set({ragToolsIntroduced:!0,[ft]:y.enabledTools})}j&&(j.checked=y.useTools),zt(),ph(),w()}),st.addEventListener(`change`,()=>{y.isolateChat=st.checked,chrome.storage.local.set({isolateChat:y.isolateChat}),r.debug(`[SidePanel] conv memory:`,y.isolateChat?`enabled`:`disabled`)});let gt=document.getElementById(`enableSelectionQueryBtn`);gt&&gt.addEventListener(`change`,()=>{y.enableSelectionQuery=gt.checked,chrome.storage.local.set({enableSelectionQuery:y.enableSelectionQuery}),r.debug(`[SidePanel] text Q&A:`,y.enableSelectionQuery?`enabled`:`disabled`),!y.enableSelectionQuery&&y.selectedContextText&&Gt()}),j&&j.addEventListener(`change`,()=>{y.useTools=j.checked,chrome.storage.local.set({enableTools:y.useTools}),r.debug(`[SidePanel] tool master switch:`,y.useTools?`enabled`:`disabled`),zt()}),ut&&ut.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),vr()});let _t=document.getElementById(`toolsPopupOverlay`),vt=document.getElementById(`toolsPopupClose`),yt=_t?_t.querySelector(`.modal-container`):null;vt&&vt.addEventListener(`click`,fi),yt&&yt.addEventListener(`click`,e=>{e.stopPropagation()});let bt=document.getElementById(`toolsSearchInput`),xt=document.getElementById(`toolsSearchClear`);bt&&bt.addEventListener(`input`,e=>{y.currentSearch=e.target.value.toLowerCase(),xt&&(xt.style.display=e.target.value?``:`none`),sa()}),xt&&xt.addEventListener(`click`,()=>{bt&&(bt.value=``,xt.style.display=`none`,y.currentSearch=``,sa())});let Ct=document.querySelectorAll(`.category-btn`);Ct.forEach(e=>{e.addEventListener(`click`,()=>{Ct.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`,y.currentCategory=e.dataset.category,sa()})});let wt=document.getElementById(`toolsCategories`);wt&&wt.addEventListener(`wheel`,e=>{e.preventDefault(),wt.scrollLeft+=e.deltaY*2},{passive:!1});let Et=document.getElementById(`toolsSelectAll`),Dt=document.getElementById(`toolsSelectNone`);Et&&Et.addEventListener(`click`,()=>{Gr().forEach(e=>{let t=document.getElementById(`tool_`+e.id);t&&(t.checked=!0),y.enabledTools.includes(e.id)||y.enabledTools.push(e.id)}),ra(!0),Vn(),jt(),Gn()}),Dt&&Dt.addEventListener(`click`,()=>{Gr().forEach(e=>{let t=document.getElementById(`tool_`+e.id);t&&(t.checked=!1);let n=y.enabledTools.indexOf(e.id);n>-1&&y.enabledTools.splice(n,1)}),ra(!1),Vn(),jt(),Gn()});let Ot=document.getElementById(`toolsPopupSave`);Ot&&Ot.addEventListener(`click`,()=>{Er(),Gn()});let kt=document.getElementById(`toolsPreselectToggle`);kt&&kt.addEventListener(`change`,()=>{chrome.storage.local.set({enableToolPreselect:kt.checked},()=>{r.debug(`[SidePanel] toolpre-filter toggle updated:`,kt.checked)})});let At=document.getElementById(`toolConfirmToggle`);At&&At.addEventListener(`change`,()=>{chrome.storage.local.set({toolConfirmationEnabled:At.checked},()=>{r.debug(`[SidePanel] sensitive-operation confirmation toggle updated:`,At.checked)})});let Mt=document.getElementById(`toolsPopupCancel`);Mt&&Mt.addEventListener(`click`,()=>{fi()});let Nt=document.getElementById(`modalCancelBtn`),Pt=document.getElementById(`modalConfirmBtn`),It=document.getElementById(`toolStatsOverlay`),Rt=document.getElementById(`toolStatsClose`),Bt=document.getElementById(`toolStatsBtn`);function Ht(){It&&(It.style.display=`flex`,Yt())}function Ut(){It&&(It.style.display=`none`)}Bt&&Bt.addEventListener(`click`,e=>{e.stopPropagation(),Ht()}),Rt&&Rt.addEventListener(`click`,Ut),It&&It.addEventListener(`click`,e=>{e.target===It&&Ut()});let Kt=document.getElementById(`toolStatsRefreshBtn`);Kt&&Kt.addEventListener(`click`,Yt);let qt=document.getElementById(`toolStatsClearBtn`);qt&&qt.addEventListener(`click`,async()=>{await window.showCustomConfirm(t(`sidePanel.clearStatsConfirm`),t(`sidePanel.clearStatsTitle`))&&(await chrome.storage.local.remove([`toolUsageStats`]),Yt())});let Jt={column:`callCount`,asc:!1};async function Yt(){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}),Xt(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 Xt(e,t){let n=document.getElementById(`toolStatsTableBody`);if(!n)return;let{column:r,asc:i}=Jt;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>
678
+ <td style="padding: 6px 10px; border-bottom: 1px solid var(--border-subtle); color: var(--text-primary);"><code title="${k(a)}">${e}</code></td>
679
679
  <td style="padding: 6px 10px; text-align: right; border-bottom: 1px solid var(--border-subtle); color: var(--text-secondary);">${n.callCount}</td>
680
680
  <td style="padding: 6px 10px; text-align: right; border-bottom: 1px solid var(--border-subtle); color: var(--text-secondary);">${n.successCount}</td>
681
681
  <td style="padding: 6px 10px; border-bottom: 1px solid var(--border-subtle);">
@@ -685,4 +685,4 @@ Are you sure you want to stop the agent service? You will not be able to connect
685
685
  <span style="font-size: 12px; color: ${o}; font-weight: 500;">${r.toFixed(0)}%</span>
686
686
  </td>
687
687
  <td style="padding: 6px 10px; text-align: right; border-bottom: 1px solid var(--border-subtle); color: var(--text-tertiary); font-size: 12px;">${s}</td>
688
- </tr>`}).join(``),Qt()}function Qt(){let{column:e,asc:t}=Yt,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;Yt.column===t?Yt.asc=!Yt.asc:(Yt.column=t,Yt.asc=!1),Xt()})}),Pt.addEventListener(`click`,()=>{lr()}),Ft.addEventListener(`click`,()=>{lr(),tr()});let nn=document.getElementById(`confirmModal`);nn.addEventListener(`click`,e=>{e.target===nn&&lr()});let rn=document.getElementById(`selectionClose`);rn&&rn.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),r.debug(`[SidePanel] user clickcloseselected content by button`),Kt(),window.hideFloatingMenu(),v.lastSelectedText=``,v.currentSelectionRange=null}),a.addEventListener(`input`,()=>{})}),at().then(()=>{Um(),ei(v.chatConfig.showMessageTimestamp!==!1),Wm(),Gm()}),document.addEventListener(`DOMContentLoaded`,()=>{qm()}),document.addEventListener(`DOMContentLoaded`,dn),document.addEventListener(`DOMContentLoaded`,hi),document.addEventListener(`DOMContentLoaded`,rh),document.addEventListener(`DOMContentLoaded`,nh),document.addEventListener(`DOMContentLoaded`,of),document.addEventListener(`DOMContentLoaded`,$f),document.addEventListener(`DOMContentLoaded`,wp),document.addEventListener(`DOMContentLoaded`,An),document.addEventListener(`DOMContentLoaded`,async()=>{hr(),no(),await $i(),jt(),await mc(),eu(),Es(),zm(),Ys(),Nh(),Gi(),Rd();let{updateBookmarkButtons:e,updateBookmarkBadge:t}=await E(async()=>{let{updateBookmarkButtons:e,updateBookmarkBadge:t}=await import(`./context-indicator-Btg9ZLat.js`).then(e=>e.Sn);return{updateBookmarkButtons:e,updateBookmarkBadge:t}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]));e(),t()}),document.addEventListener(`DOMContentLoaded`,()=>{bs()}),document.addEventListener(`DOMContentLoaded`,async()=>{Ut(e=>Pi(e)),await Dt(),await tm()});function zh(){Kt(),kr(),Fi(),Xn(),gn(),zt();let e=document.getElementById(`imagePreviewBar`);e&&(e.innerHTML=``,e.style.display=`none`)}function Bh(e){let t=e||{};t.quotedContextText&&wr(t.quotedContextText),t.selectedPage&&kt(t.selectedPage),!t.quotedContextText&&v.selectedContextText&&Nn(),oa(),Ji(),gi(),Yi(),Ft()}document.addEventListener(`queue-context-cleared`,zh),document.addEventListener(`queue-context-restored`,e=>{Bh(e&&e.detail?e.detail.snapshot:null)}),document.addEventListener(`DOMContentLoaded`,St),document.addEventListener(`DOMContentLoaded`,fi),document.addEventListener(`DOMContentLoaded`,Jr),document.addEventListener(`DOMContentLoaded`,Ci),document.addEventListener(`DOMContentLoaded`,pa),document.addEventListener(`DOMContentLoaded`,Ki),document.addEventListener(`DOMContentLoaded`,ui),document.addEventListener(`DOMContentLoaded`,Ni),document.addEventListener(`DOMContentLoaded`,ni),document.addEventListener(`DOMContentLoaded`,()=>xr()),document.addEventListener(`DOMContentLoaded`,async()=>{let{refreshAgentNames:e,initScrollToBottomBtn:t}=await E(async()=>{let{refreshAgentNames:e,initScrollToBottomBtn:t}=await import(`./context-indicator-Btg9ZLat.js`).then(e=>e.ht);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){k(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){k(t(`detach.taskRunning`),`warning`);return}try{let e=(await chrome.windows.getCurrent()).id,n=await Vh();if(n==null){k(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),k(t(`detach.attachFailed`),`error`)}catch(e){r.warn(`[SidePanel] attach failed:`,e?.message),k(t(`detach.attachFailed`),`error`)}})});
688
+ </tr>`}).join(``),Zt()}function Zt(){let{column:e,asc:t}=Jt,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;Jt.column===t?Jt.asc=!Jt.asc:(Jt.column=t,Jt.asc=!1),Yt()})}),Nt.addEventListener(`click`,()=>{cr()}),Pt.addEventListener(`click`,()=>{cr(),er()});let tn=document.getElementById(`confirmModal`);tn.addEventListener(`click`,e=>{e.target===tn&&cr()});let nn=document.getElementById(`selectionClose`);nn&&nn.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),r.debug(`[SidePanel] user clickcloseselected content by button`),Gt(),window.hideFloatingMenu(),y.lastSelectedText=``,y.currentSelectionRange=null}),a.addEventListener(`input`,()=>{})}),Je().then(()=>{th(),$r(y.chatConfig.showMessageTimestamp!==!1),nh(),rh()}),document.addEventListener(`DOMContentLoaded`,()=>{ah()}),document.addEventListener(`DOMContentLoaded`,un),document.addEventListener(`DOMContentLoaded`,mi),document.addEventListener(`DOMContentLoaded`,hh),document.addEventListener(`DOMContentLoaded`,mh),document.addEventListener(`DOMContentLoaded`,cf),document.addEventListener(`DOMContentLoaded`,_f),document.addEventListener(`DOMContentLoaded`,dp),document.addEventListener(`DOMContentLoaded`,Ip),document.addEventListener(`DOMContentLoaded`,kn),document.addEventListener(`DOMContentLoaded`,async()=>{mr(),to(),await Qi(),At(),await gc(),nu(),Os(),Zm(),Zs(),Gh(),Wi(),Bd();let{updateBookmarkButtons:e,updateBookmarkBadge:t}=await D(async()=>{let{updateBookmarkButtons:e,updateBookmarkBadge:t}=await import(`./context-indicator-DjOAo_Ln.js`).then(e=>e.Sn);return{updateBookmarkButtons:e,updateBookmarkBadge:t}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]));e(),t()}),document.addEventListener(`DOMContentLoaded`,()=>{Ss()}),document.addEventListener(`DOMContentLoaded`,async()=>{Ht(e=>Ni(e)),await Et(),await pm()});function Zh(){Gt(),Or(),Pi(),Yn(),hn(),Rt();let e=document.getElementById(`imagePreviewBar`);e&&(e.innerHTML=``,e.style.display=`none`)}function Qh(e){let t=e||{};t.quotedContextText&&Cr(t.quotedContextText),t.selectedPage&&Ot(t.selectedPage),!t.quotedContextText&&y.selectedContextText&&Mn(),aa(),qi(),hi(),Ji(),Pt()}document.addEventListener(`queue-context-cleared`,Zh),document.addEventListener(`queue-context-restored`,e=>{Qh(e&&e.detail?e.detail.snapshot:null)}),document.addEventListener(`DOMContentLoaded`,xt),document.addEventListener(`DOMContentLoaded`,di),document.addEventListener(`DOMContentLoaded`,qr),document.addEventListener(`DOMContentLoaded`,Si),document.addEventListener(`DOMContentLoaded`,fa),document.addEventListener(`DOMContentLoaded`,Gi),document.addEventListener(`DOMContentLoaded`,li),document.addEventListener(`DOMContentLoaded`,Mi),document.addEventListener(`DOMContentLoaded`,ti),document.addEventListener(`DOMContentLoaded`,()=>br()),document.addEventListener(`DOMContentLoaded`,async()=>{let{refreshAgentNames:e,initScrollToBottomBtn:t}=await D(async()=>{let{refreshAgentNames:e,initScrollToBottomBtn:t}=await import(`./context-indicator-DjOAo_Ln.js`).then(e=>e.ht);return{refreshAgentNames:e,initScrollToBottomBtn:t}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]));e(),t()});async function $h(){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=y.pendingCallApiSessionIds&&y.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(y.pendingCallApiSessionIds&&y.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(y.pendingCallApiSessionIds&&y.pendingCallApiSessionIds.size>0){A(t(`detach.taskRunning`),`warning`);return}try{let e=(await chrome.windows.getCurrent()).id,n=await $h();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`)}})});