ai-helper-agent 2.8.24 → 2.8.25

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-BPCvEgPs.js","assets/chunk-CMxvf4Kt.js","assets/model-profiles-BAmMy51B.js","assets/i18n-C_EX21mG.js","assets/voice-shortcut-Dx863RGz.js","assets/session-store-BeCUrwzf.js","assets/model-fetcher-CZwR4oYA.js","assets/agent-store-C4yiT4AA.js","assets/workspace-manager-DFPFAowW.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-C_EX21mG.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-BAmMy51B.js";import{_ as de,d as fe}from"./session-store-BeCUrwzf.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-Drp9BwnD.js";import{$ as Ge,A as Ke,B as qe,G as Je,H as Ye,K as Xe,L as Ze,M as Qe,U as k,V as $e,W as A,X as et,at as tt,dt as nt,et as rt,ft as it,it as at,j as ot,k as st,lt as ct,n as lt,nt as ut,ot as dt,pt as ft,rt as pt,st as j,ut as mt,x as ht,z as gt}from"./model-fetcher-CZwR4oYA.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-BPCvEgPs.js";import{o as pa}from"./agent-store-C4yiT4AA.js";import{O as ma,b as ha,l as ga,p as _a,v as va}from"./workspace-manager-DFPFAowW.js";import{n as ya,t as ba}from"./onboarding-wizard-CfmkIg0F.js";var xa=`panel-observer-`,Sa=new Map,Ca=new Set;function wa(e){typeof e==`function`&&Ca.add(e)}function Ta(e){if(!e)return null;let t=Sa.get(e);if(t)return t;let n;try{n=chrome.runtime.connect({name:`${xa}${e}`})}catch(e){return r.debug(`[PanelObserver] 建立观察端口失败(忽略):`,e?.message||e),null}Sa.set(e,n);try{n.onMessage.addListener(e=>{for(let t of Ca)try{t(e)}catch(e){r.debug(`[PanelObserver] 消息处理异常(忽略):`,e?.message||e)}})}catch(e){r.debug(`[PanelObserver] 观察端口消息监听挂不上(忽略):`,e?.message||e)}try{n.onDisconnect.addListener(()=>{Sa.get(e)===n&&Sa.delete(e)})}catch(e){r.debug(`[PanelObserver] 观察端口断开监听挂不上(忽略):`,e?.message||e)}return n}function Ea(e){if(!e)return;let t=Sa.get(e);if(t){Sa.delete(e);try{t.disconnect()}catch(e){r.debug(`[PanelObserver] 关闭观察端口异常(忽略):`,e?.message||e)}}}function Da({sessionId:e,callId:t,renderer:n,persist:i,onFinished:a=()=>{},emptyFallback:o=``,awaitSnapshot:s=!1}){let c=``,l=!1,u=s,d=[],f=n=>!!n&&n.sessionId===e&&n.callId===t,p=e=>{let t=[];for(let n of e){let e=t[t.length-1];n.type===`STREAM_CHUNK`&&e&&e.type===`STREAM_CHUNK`?t[t.length-1]={...n,delta:(e.delta||``)+(n.delta||``)}:t.push(n)}return t},m=()=>{u=!1;let e=p(d);d=[];for(let t of e)g(t)},h=e=>{l=!0,Promise.resolve().then(()=>i(e)).catch(e=>r.warn(`[ChatReattach] 终态落库失败(忽略):`,e?.message||e)).then(()=>{try{a()}catch{}})};return{sessionId:e,callId:t,get finished(){return l},dispose(){l=!0},restore(e){if(!u)return;u=!1;let r=!!e&&e.callId===t,i=r&&typeof e.accumulated==`string`?e.accumulated:``,a=r&&!!e.html;a&&n.restore?.({html:e.html}),c=i,i&&!a&&n.chunk?.(i);let o=p(d);d=[];for(let e of o)g(e)},handleMessage(e){return l||!f(e)?!1:u?e.type===`STREAM_CHUNK`?(d.push(e),!0):e.type===`API_COMPLETE`||e.type===`API_ERROR`?(m(),g(e)):(d.push(e),!0):g(e)}};function g(r){switch(r.type){case`STREAM_START`:return c=``,n.start?.(),!0;case`STREAM_CHUNK`:return c+=r.delta||``,n.chunk?.(c),!0;case`STREAM_TOOL_CALL`:return n.toolCalls?.(r.toolCalls||[],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 Oa({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 ka=!1,Aa=new Map,ja=null,Ma=!1,Na=null,Pa=null,Fa=null,Ia=250,La=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 Ra(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 za(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 Ba(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-BPCvEgPs.js`).then(e=>e.kr);return{appendMessageToSession:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]));await a(t,i)}function Va(){D(()=>import(`./context-indicator-BPCvEgPs.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 Ha=1e3;function Ua(e){return Promise.race([ri(e),new Promise(e=>setTimeout(()=>e(null),Ha))])}function Wa(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),Va();try{document.dispatchEvent(new CustomEvent(`generating-state-changed`))}catch{}let o=Da({sessionId:e,callId:n,awaitSnapshot:!0,renderer:za(e,a),persist:t=>Ba(t,e,a),emptyFallback:t(`chatMsg.emptyModelReply`),onFinished:()=>{if(Aa.get(e)===o){Aa.delete(e),Ea(e),y.pendingCallApiSessionIds.delete(e),Va(),Xi(e);try{document.dispatchEvent(new CustomEvent(`session-cache-invalidate`,{detail:{sessionId:e}}))}catch{}Nn(e)}}});return Aa.set(e,o),Ta(e),Ua(e).then(t=>{o.finished||Aa.get(e)!==o||o.restore(t)}).catch(()=>o.restore(null)),y.activeSessionId===e&&ia(e),r.info(`[ChatReattach] 已接管运行中的任务: sessionId=${e}, callId=${n}`),!0}function Ga(e){let t=Aa.get(e);if(!t)return;Aa.delete(e),Ea(e);try{t.dispose?.()}catch{}let n=yr(e),r=n();try{r?.remove()}catch{}n(null),Xi(e),y.pendingCallApiSessionIds.delete(e),Va();try{document.dispatchEvent(new CustomEvent(`generating-state-changed`))}catch{}}function Ka(){let e=ja;e&&Promise.resolve().then(()=>e.syncFromBackground()).catch(e=>r.debug(`[ChatReattach] 对齐后台状态失败(忽略):`,e?.message||e))}function qa(){!ka||!ja||Fa||(Fa=setTimeout(()=>{Fa=null,Ka()},Ia))}var Ja=new Map,Ya=3e3,Xa=100,Za=new Set,Qa=new Set([`API_COMPLETE`,`API_ERROR`]);function $a(e,t){let n=`${e}|${t.callId}`;Za.has(n)||(Za.add(n),Za.size>Xa&&Za.delete(Za.values().next().value),Ga(e),Wa(e,t.callId)&&Aa.get(e)?.handleMessage(t))}function eo(e,t,n){let r=Ja.get(e);if(r){r.messages.push(n);return}r={callId:t,messages:[n]},Ja.set(e,r),Ra(Ya).then(t=>to(e,t&&t.activeCallIds&&t.activeCallIds[e]||null)).catch(()=>to(e,null)).finally(()=>{Ja.delete(e)})}function to(e,t){let n=Ja.get(e);if(!n)return;let{callId:r,messages:i}=n;if(t===r)Ga(e),Wa(e,r);else if(t===null){let t=i.find(e=>Qa.has(e.type));if(!t)return;$a(e,t);return}else return;let a=Aa.get(e);if(!(!a||a.callId!==r))for(let e of i){if(a.finished)break;a.handleMessage(e)}}function no(){if(Ma)return;Ma=!0;let e=e=>{if(!e)return!1;let t=e.sessionId?Aa.get(e.sessionId):null;return t?e.callId&&e.callId!==t.callId?(eo(e.sessionId,e.callId,e),!1):(Ta(e.sessionId),t.handleMessage(e),!1):(e.callId&&La.has(e.type)&&qa(),!1)};chrome.runtime.onMessage.addListener(e),wa(e),Na=e=>{let t=e?.detail?.sessionId;t&&Aa.has(t)&&ia(t),qa()},document.addEventListener(`session-hydrated`,Na),Pa=e=>{let t=e?.detail?.sessionId;t&&Aa.has(t)&&ia(t)},document.addEventListener(`chat-history-rendered`,Pa)}function ro(){return ka?{syncFromBackground:()=>ja.syncFromBackground()}:(ka=!0,no(),ja=Oa({queryRunning:Ra,hasLocalListener:e=>y.pendingCancelApiMap.has(e),isAttached:(e,t)=>Aa.get(e)?.callId===t?(Ta(e),!0):!1,attach:(e,t)=>{Wa(e,t)}}),ja.syncFromBackground(),{syncFromBackground:()=>ja.syncFromBackground()})}function io(e){!ka||!ja||(e&&y.activeSessionId===e&&ia(e),ja.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 ao=`sessionDockDismissed`,oo=5e3,so=250,co=1200,lo=8,uo=lo-1,fo=9e4,po={running:0,queued:1,done:2},mo=new Map,ho=new Map,go=new Map,_o=new Map,vo=new Set,yo=new Set,bo=new Map,xo=new Map,So=new Set,Co=new Set,wo=new Set,To=[],Eo=new Set,M=null,N=null,P=null,Do=[],Oo=!1,ko=null,Ao=null,jo=!1,Mo=null,No=null;function Po(e){return e?Array.isArray(e)?e:e instanceof Set?Array.from(e):[]:[]}function Fo(e){let t=new Set;for(let n of Po(e))n&&t.add(h(String(n))||String(n));return t}function Io({phase:e=``,sessionId:t=null,backendRunningIds:n=[],startedAt:r=0,lastUpdateAt:i=0,now:a=Date.now(),staleMs:o=fo}={}){if(e!==`running`||!t||Po(n).includes(t))return!1;let s=Math.max(Number(r)||0,Number(i)||0);return s?a-s>=o:!1}var Lo=160;function Ro(e){let t=String(e??``).replace(/\s+/g,` `).trim();if(!t)return``;let n=Array.from(t);return n.length<=Lo?t:`${n.slice(0,Lo).join(``).trimEnd()}…`}function zo(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 Bo({phase:e=``,queuedText:t=``,questionText:n=``,title:r=``}={}){let i=e===`queued`?Ro(t):``,a=i||Ro(n),o=Ro(r),s=a||o,c=i?`queued`:a?`question`:s?`title`:``;return{primary:s,sub:a&&!zo(o,a)?o:``,isQuestion:!!a,from:c}}function Vo(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 Ho({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:_=fo}={}){let ee=Po(s),v=new Set([...Po(a),...Po(o),...ee]),te=new Set(Po(c)),y=new Set(Po(d)),b=new Set(Po(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=Io({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=Bo({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=po[e.phase]-po[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 Uo(e){return wo.has(e)||y.generatingSessionIds.has(e)||y.pendingCallApiSessionIds.has(e)}function Wo(){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 Go(){let e={};for(let t of y.sessions||[])e[t.id]=t.title||``;for(let[t,n]of bo)e[t]||(e[t]=n);return e}function Ko(){let e={},t={},n=new Map;for(let e of y.sessions||[])n.set(e.id,e);for(let r of new Set([...wo,...y.generatingSessionIds,...y.pendingCallApiSessionIds,...y.completedSessionIds])){let i=ho.get(r)||go.get(r)||0,a=xo.get(r);if(i&&a&&a.stamp===i){a.text&&(e[r]=a.text,t[r]=a.messageId||``);continue}let o=Vo(n.get(r));o.text&&(e[r]=o.text,t[r]=o.messageId)}return{questions:e,anchors:t}}function qo(){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 Jo(e){for(let t of e||[]){let e=t.sessionId;if(!e)continue;let n=t.startedAt||t.doneAt||0,i=xo.get(e),a=!i||i.stamp!==n,o=!t.title;!a&&!o||Co.has(e)||(Co.add(e),ne(e).then(t=>{if(t&&((o||!bo.has(e))&&bo.set(e,t.title||``),a)){let r=Vo(t);xo.set(e,{text:r.text,messageId:r.messageId,stamp:n})}}).catch(e=>{r.debug(`[SessionDock] hydrate label failed:`,e?.message||e)}).finally(()=>{Co.delete(e),F()}))}}function Yo(e){if(!e)return``;let t=new Date(e);return`${String(t.getHours()).padStart(2,`0`)}:${String(t.getMinutes()).padStart(2,`0`)}`}function Xo(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:Yo(e.doneAt)}):t(`dock.done`)}function Zo(e){ho.set(e,Date.now()),go.delete(e),xo.delete(e)}function Qo(){let e=new Set([...y.generatingSessionIds,...y.pendingCallApiSessionIds]);for(let t of e)So.has(t)&&(So.delete(t),Zo(t));F()}function $o(){let e=y.completedSessionIds;for(let e of new Set([...wo,...y.generatingSessionIds,...y.pendingCallApiSessionIds]))ho.has(e)||ho.set(e,Date.now()),go.delete(e);for(let e of wo)yo.delete(e);for(let t of e)!go.has(t)&&!Uo(t)&&go.set(t,Date.now());let{questions:t,anchors:n}=Ko(),r=Ho({activeSessionId:y.activeSessionId,titles:Go(),questions:t,anchors:n,queuedTexts:qo(),generatingIds:y.generatingSessionIds,pendingIds:y.pendingCallApiSessionIds,runningIds:wo,completedIds:e,queuedCounts:Wo(),scheduledIds:vo,dismissedIds:yo,nodeInfo:Object.fromEntries(mo),startedAt:Object.fromEntries(ho),doneAt:Object.fromEntries(go),lastUpdateAt:Object.fromEntries(_o),now:Date.now()});return Jo(r),r}function es(e){let t=new Set(To.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&&(Eo=new Set(n),Mo&&clearTimeout(Mo),Mo=setTimeout(()=>{Mo=null,Eo=new Set,F()},co))}function ts(){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),ns();let e=document.getElementById(`chatContainer`);return e&&typeof ResizeObserver<`u`&&new ResizeObserver(ns).observe(e),window.addEventListener(`resize`,ns),M}function ns(){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 rs(e){bi(e.sessionId,{focusMessageId:e.anchorMessageId||null})}function is(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`),Eo.has(e.sessionId)&&n.classList.add(`is-flash`);let r=e.title||t(`dock.unknownSession`),i=e.primary||r,a=Xo(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`,()=>{rs(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(),_s(e.sessionId)}),n.appendChild(r)}return n.addEventListener(`mouseenter`,()=>as(n,e,a)),n.addEventListener(`mouseleave`,os),n.addEventListener(`focusin`,()=>as(n,e,a)),n.addEventListener(`focusout`,os),n}function as(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 os(){N&&N.classList.remove(`show`)}function ss(){return P||typeof document>`u`?P:(P=document.createElement(`div`),P.className=`session-dock-overflow`,P.setAttribute(`role`,`menu`),P.addEventListener(`mouseenter`,cs),P.addEventListener(`mouseleave`,ls),P.addEventListener(`focusin`,cs),P.addEventListener(`focusout`,ls),document.body.appendChild(P),P)}function cs(){No&&=(clearTimeout(No),null)}function ls(){Oo||(cs(),No=setTimeout(()=>{No=null,ms()},220))}function us(){let e=M?M.querySelector(`.session-dock-more`):null;e&&(e.setAttribute(`aria-expanded`,Oo?`true`:`false`),e.classList.toggle(`is-open`,Oo))}function ds(){let e=ss();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 Do){let n=e.primary||e.title||t(`dock.unknownSession`),i=Xo(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`,()=>{ms(),rs(e)}),r.appendChild(a)}e.appendChild(r)}function fs(){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 ps(){Do.length!==0&&ss()&&(cs(),ds(),fs(),P.classList.add(`show`),us())}function ms(){cs(),Oo=!1,P&&P.classList.remove(`show`),us()}function hs(){if(P&&P.classList.contains(`show`)&&Oo){ms();return}ps(),Oo=!0,us()}function gs(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`,Oo?`true`:`false`),r.textContent=`+${e.length>99?`99`:e.length}`,r.addEventListener(`click`,()=>hs()),n.appendChild(r),n.addEventListener(`mouseenter`,()=>ps()),n.addEventListener(`mouseleave`,ls),n.addEventListener(`focusin`,()=>ps()),n.addEventListener(`focusout`,ls),n}function _s(e){e&&(yo.add(e),vs(),F())}function vs(){try{chrome.storage.local.set({[ao]:Array.from(yo)}).catch(()=>{})}catch{}}function ys(){try{chrome.storage.local.get([ao],e=>{let t=e?.[ao];if(Array.isArray(t)){for(let e of t)yo.add(e);F()}})}catch{}}function bs(){if(!ts())return;let e=$o();if(es(e),To=e,ms(),Do=[],M.innerHTML=``,e.length===0){M.classList.remove(`show`),document.body.classList.remove(`has-session-dock`),os();return}let t=e.length>lo?uo:lo;Do=e.slice(t);for(let n of e.slice(0,t))M.appendChild(is(n));Do.length>0&&M.appendChild(gs(Do)),M.classList.add(`show`),document.body.classList.add(`has-session-dock`)}function F(){ko||=setTimeout(()=>{ko=null;try{bs()}catch(e){r.warn(`[SessionDock] render failed:`,e?.message||e)}},so)}function xs(){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=Fo(t.activeSessionIds);for(let t of e){if(So.has(t)){So.delete(t),Zo(t);continue}wo.has(t)||y.generatingSessionIds.has(t)||y.pendingCallApiSessionIds.has(t)||Zo(t)}wo=e}e()})}catch{e()}})}function Ss(e){let t=e?.sessionId;if(!t)return;let n=mo.get(t)||{};mo.set(t,{nodeName:e.nodeName||n.nodeName||``,subtaskIndex:e.subtaskIndex||n.subtaskIndex||0,subtaskTotal:e.subtaskTotal||n.subtaskTotal||0}),_o.set(t,Date.now()),F()}function Cs(e){e&&(mo.delete(e),ho.delete(e),go.delete(e),_o.delete(e),yo.delete(e),bo.delete(e),xo.delete(e),So.delete(e),F())}function ws(){if(!(jo||typeof document>`u`||!ts())){jo=!0,ys(),document.addEventListener(`generating-state-changed`,Qo),document.addEventListener(`session-switched`,F),document.addEventListener(`generation-ended`,e=>{let t=e?.detail?.sessionId;t&&(So.add(t),go.has(t)||go.set(t,Date.now())),F()}),document.addEventListener(`session-archived`,e=>Cs(e?.detail?.sessionId)),document.addEventListener(`session-deleted`,e=>Cs(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`?(Ss(e),!1):e.type===`SCHEDULED_TASK_RUN_STATE`&&e.sessionId?(e.running?vo.add(e.sessionId):vo.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){ms();return}xs().then(F)}),document.addEventListener(`keydown`,e=>{e.key===`Escape`&&Oo&&ms()}),Ao||=setInterval(()=>{document.hidden||xs().then(F)},oo),xs().then(()=>{for(let e of wo)ho.has(e)||ho.set(e,Date.now());bs()})}}function Ts(){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 Xe(e,n.top,n.bottom)}function p(e,t){let n=document.getElementById(`chatContainer`);if(!n)return`noop`;let r=gt(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=dt(r.length,Je(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=gt(document.getElementById(`chatContainer`));let e=l?gt(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=gt(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=tt(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 Es(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 Ds=!1,Os=!1,I=[],ks=``;function As(){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=`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/context-indicator-CF1oNqcX.js","assets/chunk-CMxvf4Kt.js","assets/model-profiles-F10jtx7B.js","assets/i18n-CnrKkEL4.js","assets/voice-shortcut-Dx863RGz.js","assets/session-store-CQLag4VS.js","assets/model-fetcher-CRFUAGOA.js","assets/agent-store-kLwTRAYA.js","assets/workspace-manager-Dk95w-Hj.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-CnrKkEL4.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-F10jtx7B.js";import{_ as de,d as fe}from"./session-store-CQLag4VS.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-BfQ2Ghen.js";import{$ as Ge,A as Ke,B as qe,G as Je,H as Ye,K as Xe,L as Ze,M as Qe,U as k,V as $e,W as A,X as et,at as tt,dt as nt,et as rt,ft as it,it as at,j as ot,k as st,lt as ct,n as lt,nt as ut,ot as dt,pt as ft,rt as pt,st as j,ut as mt,x as ht,z as gt}from"./model-fetcher-CRFUAGOA.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-CF1oNqcX.js";import{o as pa}from"./agent-store-kLwTRAYA.js";import{O as ma,b as ha,l as ga,p as _a,v as va}from"./workspace-manager-Dk95w-Hj.js";import{n as ya,t as ba}from"./onboarding-wizard-CyPO03S7.js";var xa=`panel-observer-`,Sa=new Map,Ca=new Set;function wa(e){typeof e==`function`&&Ca.add(e)}function Ta(e){if(!e)return null;let t=Sa.get(e);if(t)return t;let n;try{n=chrome.runtime.connect({name:`${xa}${e}`})}catch(e){return r.debug(`[PanelObserver] 建立观察端口失败(忽略):`,e?.message||e),null}Sa.set(e,n);try{n.onMessage.addListener(e=>{for(let t of Ca)try{t(e)}catch(e){r.debug(`[PanelObserver] 消息处理异常(忽略):`,e?.message||e)}})}catch(e){r.debug(`[PanelObserver] 观察端口消息监听挂不上(忽略):`,e?.message||e)}try{n.onDisconnect.addListener(()=>{Sa.get(e)===n&&Sa.delete(e)})}catch(e){r.debug(`[PanelObserver] 观察端口断开监听挂不上(忽略):`,e?.message||e)}return n}function Ea(e){if(!e)return;let t=Sa.get(e);if(t){Sa.delete(e);try{t.disconnect()}catch(e){r.debug(`[PanelObserver] 关闭观察端口异常(忽略):`,e?.message||e)}}}function Da({sessionId:e,callId:t,renderer:n,persist:i,onFinished:a=()=>{},emptyFallback:o=``,awaitSnapshot:s=!1}){let c=``,l=!1,u=s,d=[],f=n=>!!n&&n.sessionId===e&&n.callId===t,p=e=>{let t=[];for(let n of e){let e=t[t.length-1];n.type===`STREAM_CHUNK`&&e&&e.type===`STREAM_CHUNK`?t[t.length-1]={...n,delta:(e.delta||``)+(n.delta||``)}:t.push(n)}return t},m=()=>{u=!1;let e=p(d);d=[];for(let t of e)g(t)},h=e=>{l=!0,Promise.resolve().then(()=>i(e)).catch(e=>r.warn(`[ChatReattach] 终态落库失败(忽略):`,e?.message||e)).then(()=>{try{a()}catch{}})};return{sessionId:e,callId:t,get finished(){return l},dispose(){l=!0},restore(e){if(!u)return;u=!1;let r=!!e&&e.callId===t,i=r&&typeof e.accumulated==`string`?e.accumulated:``,a=r&&!!e.html;a&&n.restore?.({html:e.html}),c=i,i&&!a&&n.chunk?.(i);let o=p(d);d=[];for(let e of o)g(e)},handleMessage(e){return l||!f(e)?!1:u?e.type===`STREAM_CHUNK`?(d.push(e),!0):e.type===`API_COMPLETE`||e.type===`API_ERROR`?(m(),g(e)):(d.push(e),!0):g(e)}};function g(r){switch(r.type){case`STREAM_START`:return c=``,n.start?.(),!0;case`STREAM_CHUNK`:return c+=r.delta||``,n.chunk?.(c),!0;case`STREAM_TOOL_CALL`:return n.toolCalls?.(r.toolCalls||[],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 Oa({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 ka=!1,Aa=new Map,ja=null,Ma=!1,Na=null,Pa=null,Fa=null,Ia=250,La=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 Ra(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 za(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 Ba(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-CF1oNqcX.js`).then(e=>e.kr);return{appendMessageToSession:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]));await a(t,i)}function Va(){D(()=>import(`./context-indicator-CF1oNqcX.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 Ha=1e3;function Ua(e){return Promise.race([ri(e),new Promise(e=>setTimeout(()=>e(null),Ha))])}function Wa(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),Va();try{document.dispatchEvent(new CustomEvent(`generating-state-changed`))}catch{}let o=Da({sessionId:e,callId:n,awaitSnapshot:!0,renderer:za(e,a),persist:t=>Ba(t,e,a),emptyFallback:t(`chatMsg.emptyModelReply`),onFinished:()=>{if(Aa.get(e)===o){Aa.delete(e),Ea(e),y.pendingCallApiSessionIds.delete(e),Va(),Xi(e);try{document.dispatchEvent(new CustomEvent(`session-cache-invalidate`,{detail:{sessionId:e}}))}catch{}Nn(e)}}});return Aa.set(e,o),Ta(e),Ua(e).then(t=>{o.finished||Aa.get(e)!==o||o.restore(t)}).catch(()=>o.restore(null)),y.activeSessionId===e&&ia(e),r.info(`[ChatReattach] 已接管运行中的任务: sessionId=${e}, callId=${n}`),!0}function Ga(e){let t=Aa.get(e);if(!t)return;Aa.delete(e),Ea(e);try{t.dispose?.()}catch{}let n=yr(e),r=n();try{r?.remove()}catch{}n(null),Xi(e),y.pendingCallApiSessionIds.delete(e),Va();try{document.dispatchEvent(new CustomEvent(`generating-state-changed`))}catch{}}function Ka(){let e=ja;e&&Promise.resolve().then(()=>e.syncFromBackground()).catch(e=>r.debug(`[ChatReattach] 对齐后台状态失败(忽略):`,e?.message||e))}function qa(){!ka||!ja||Fa||(Fa=setTimeout(()=>{Fa=null,Ka()},Ia))}var Ja=new Map,Ya=3e3,Xa=100,Za=new Set,Qa=new Set([`API_COMPLETE`,`API_ERROR`]);function $a(e,t){let n=`${e}|${t.callId}`;Za.has(n)||(Za.add(n),Za.size>Xa&&Za.delete(Za.values().next().value),Ga(e),Wa(e,t.callId)&&Aa.get(e)?.handleMessage(t))}function eo(e,t,n){let r=Ja.get(e);if(r){r.messages.push(n);return}r={callId:t,messages:[n]},Ja.set(e,r),Ra(Ya).then(t=>to(e,t&&t.activeCallIds&&t.activeCallIds[e]||null)).catch(()=>to(e,null)).finally(()=>{Ja.delete(e)})}function to(e,t){let n=Ja.get(e);if(!n)return;let{callId:r,messages:i}=n;if(t===r)Ga(e),Wa(e,r);else if(t===null){let t=i.find(e=>Qa.has(e.type));if(!t)return;$a(e,t);return}else return;let a=Aa.get(e);if(!(!a||a.callId!==r))for(let e of i){if(a.finished)break;a.handleMessage(e)}}function no(){if(Ma)return;Ma=!0;let e=e=>{if(!e)return!1;let t=e.sessionId?Aa.get(e.sessionId):null;return t?e.callId&&e.callId!==t.callId?(eo(e.sessionId,e.callId,e),!1):(Ta(e.sessionId),t.handleMessage(e),!1):(e.callId&&La.has(e.type)&&qa(),!1)};chrome.runtime.onMessage.addListener(e),wa(e),Na=e=>{let t=e?.detail?.sessionId;t&&Aa.has(t)&&ia(t),qa()},document.addEventListener(`session-hydrated`,Na),Pa=e=>{let t=e?.detail?.sessionId;t&&Aa.has(t)&&ia(t)},document.addEventListener(`chat-history-rendered`,Pa)}function ro(){return ka?{syncFromBackground:()=>ja.syncFromBackground()}:(ka=!0,no(),ja=Oa({queryRunning:Ra,hasLocalListener:e=>y.pendingCancelApiMap.has(e),isAttached:(e,t)=>Aa.get(e)?.callId===t?(Ta(e),!0):!1,attach:(e,t)=>{Wa(e,t)}}),ja.syncFromBackground(),{syncFromBackground:()=>ja.syncFromBackground()})}function io(e){!ka||!ja||(e&&y.activeSessionId===e&&ia(e),ja.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 ao=`sessionDockDismissed`,oo=5e3,so=250,co=1200,lo=8,uo=lo-1,fo=9e4,po={running:0,queued:1,done:2},mo=new Map,ho=new Map,go=new Map,_o=new Map,vo=new Set,yo=new Set,bo=new Map,xo=new Map,So=new Set,Co=new Set,wo=new Set,To=[],Eo=new Set,M=null,Do=null,N=null,Oo=[],ko=!1,Ao=null,jo=null,Mo=!1,No=null,Po=null;function Fo(e){return e?Array.isArray(e)?e:e instanceof Set?Array.from(e):[]:[]}function Io(e){let t=new Set;for(let n of Fo(e))n&&t.add(h(String(n))||String(n));return t}function Lo({phase:e=``,sessionId:t=null,backendRunningIds:n=[],startedAt:r=0,lastUpdateAt:i=0,now:a=Date.now(),staleMs:o=fo}={}){if(e!==`running`||!t||Fo(n).includes(t))return!1;let s=Math.max(Number(r)||0,Number(i)||0);return s?a-s>=o:!1}var Ro=160;function zo(e){let t=String(e??``).replace(/\s+/g,` `).trim();if(!t)return``;let n=Array.from(t);return n.length<=Ro?t:`${n.slice(0,Ro).join(``).trimEnd()}…`}function Bo(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 Vo({phase:e=``,queuedText:t=``,questionText:n=``,title:r=``}={}){let i=e===`queued`?zo(t):``,a=i||zo(n),o=zo(r),s=a||o,c=i?`queued`:a?`question`:s?`title`:``;return{primary:s,sub:a&&!Bo(o,a)?o:``,isQuestion:!!a,from:c}}function Ho(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 Uo({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:_=fo}={}){let ee=Fo(s),v=new Set([...Fo(a),...Fo(o),...ee]),te=new Set(Fo(c)),y=new Set(Fo(d)),b=new Set(Fo(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=Lo({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=Vo({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=po[e.phase]-po[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 Wo(e){return wo.has(e)||y.generatingSessionIds.has(e)||y.pendingCallApiSessionIds.has(e)}function Go(){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 Ko(){let e={};for(let t of y.sessions||[])e[t.id]=t.title||``;for(let[t,n]of bo)e[t]||(e[t]=n);return e}function qo(){let e={},t={},n=new Map;for(let e of y.sessions||[])n.set(e.id,e);for(let r of new Set([...wo,...y.generatingSessionIds,...y.pendingCallApiSessionIds,...y.completedSessionIds])){let i=ho.get(r)||go.get(r)||0,a=xo.get(r);if(i&&a&&a.stamp===i){a.text&&(e[r]=a.text,t[r]=a.messageId||``);continue}let o=Ho(n.get(r));o.text&&(e[r]=o.text,t[r]=o.messageId)}return{questions:e,anchors:t}}function Jo(){let e={};try{for(let t of 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 Yo(e){for(let t of e||[]){let e=t.sessionId;if(!e)continue;let n=t.startedAt||t.doneAt||0,i=xo.get(e),a=!i||i.stamp!==n,o=!t.title;!a&&!o||Co.has(e)||(Co.add(e),ne(e).then(t=>{if(t&&((o||!bo.has(e))&&bo.set(e,t.title||``),a)){let r=Ho(t);xo.set(e,{text:r.text,messageId:r.messageId,stamp:n})}}).catch(e=>{r.debug(`[SessionDock] hydrate label failed:`,e?.message||e)}).finally(()=>{Co.delete(e),P()}))}}function Xo(e){if(!e)return``;let t=new Date(e);return`${String(t.getHours()).padStart(2,`0`)}:${String(t.getMinutes()).padStart(2,`0`)}`}function Zo(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:Xo(e.doneAt)}):t(`dock.done`)}function Qo(e){ho.set(e,Date.now()),go.delete(e),xo.delete(e)}function $o(){let e=new Set([...y.generatingSessionIds,...y.pendingCallApiSessionIds]);for(let t of e)So.has(t)&&(So.delete(t),Qo(t));P()}function es(){let e=y.completedSessionIds;for(let e of new Set([...wo,...y.generatingSessionIds,...y.pendingCallApiSessionIds]))ho.has(e)||ho.set(e,Date.now()),go.delete(e);for(let e of wo)yo.delete(e);for(let t of e)!go.has(t)&&!Wo(t)&&go.set(t,Date.now());let{questions:t,anchors:n}=qo(),r=Uo({activeSessionId:y.activeSessionId,titles:Ko(),questions:t,anchors:n,queuedTexts:Jo(),generatingIds:y.generatingSessionIds,pendingIds:y.pendingCallApiSessionIds,runningIds:wo,completedIds:e,queuedCounts:Go(),scheduledIds:vo,dismissedIds:yo,nodeInfo:Object.fromEntries(mo),startedAt:Object.fromEntries(ho),doneAt:Object.fromEntries(go),lastUpdateAt:Object.fromEntries(_o),now:Date.now()});return Yo(r),r}function ts(e){let t=new Set(To.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&&(Eo=new Set(n),No&&clearTimeout(No),No=setTimeout(()=>{No=null,Eo=new Set,P()},co))}function ns(){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),Do=document.createElement(`div`),Do.className=`session-dock-tip`,document.body.appendChild(Do),rs();let e=document.getElementById(`chatContainer`);return e&&typeof ResizeObserver<`u`&&new ResizeObserver(rs).observe(e),window.addEventListener(`resize`,rs),M}function rs(){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 is(e){bi(e.sessionId,{focusMessageId:e.anchorMessageId||null})}function as(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`),Eo.has(e.sessionId)&&n.classList.add(`is-flash`);let r=e.title||t(`dock.unknownSession`),i=e.primary||r,a=Zo(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`,()=>{is(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(),vs(e.sessionId)}),n.appendChild(r)}return n.addEventListener(`mouseenter`,()=>os(n,e,a)),n.addEventListener(`mouseleave`,ss),n.addEventListener(`focusin`,()=>os(n,e,a)),n.addEventListener(`focusout`,ss),n}function os(e,n,r){if(!Do)return;Do.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,Do.appendChild(i),n.sub){let e=document.createElement(`div`);e.className=`session-dock-tip-sub`,e.textContent=n.sub,Do.appendChild(e)}Do.appendChild(a);let o=e.getBoundingClientRect();Do.style.top=`${Math.round(o.top)}px`,Do.style.left=`${Math.round(o.right+8)}px`,Do.classList.add(`show`)}function ss(){Do&&Do.classList.remove(`show`)}function cs(){return N||typeof document>`u`?N:(N=document.createElement(`div`),N.className=`session-dock-overflow`,N.setAttribute(`role`,`menu`),N.addEventListener(`mouseenter`,ls),N.addEventListener(`mouseleave`,us),N.addEventListener(`focusin`,ls),N.addEventListener(`focusout`,us),document.body.appendChild(N),N)}function ls(){Po&&=(clearTimeout(Po),null)}function us(){ko||(ls(),Po=setTimeout(()=>{Po=null,hs()},220))}function ds(){let e=M?M.querySelector(`.session-dock-more`):null;e&&(e.setAttribute(`aria-expanded`,ko?`true`:`false`),e.classList.toggle(`is-open`,ko))}function fs(){let e=cs();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 Oo){let n=e.primary||e.title||t(`dock.unknownSession`),i=Zo(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`,()=>{hs(),is(e)}),r.appendChild(a)}e.appendChild(r)}function ps(){if(!N||!M)return;let e=M.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 ms(){Oo.length!==0&&cs()&&(ls(),fs(),ps(),N.classList.add(`show`),ds())}function hs(){ls(),ko=!1,N&&N.classList.remove(`show`),ds()}function gs(){if(N&&N.classList.contains(`show`)&&ko){hs();return}ms(),ko=!0,ds()}function _s(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`,ko?`true`:`false`),r.textContent=`+${e.length>99?`99`:e.length}`,r.addEventListener(`click`,()=>gs()),n.appendChild(r),n.addEventListener(`mouseenter`,()=>ms()),n.addEventListener(`mouseleave`,us),n.addEventListener(`focusin`,()=>ms()),n.addEventListener(`focusout`,us),n}function vs(e){e&&(yo.add(e),ys(),P())}function ys(){try{chrome.storage.local.set({[ao]:Array.from(yo)}).catch(()=>{})}catch{}}function bs(){try{chrome.storage.local.get([ao],e=>{let t=e?.[ao];if(Array.isArray(t)){for(let e of t)yo.add(e);P()}})}catch{}}function xs(){if(!ns())return;let e=es();if(ts(e),To=e,hs(),Oo=[],M.innerHTML=``,e.length===0){M.classList.remove(`show`),document.body.classList.remove(`has-session-dock`),ss();return}let t=e.length>lo?uo:lo;Oo=e.slice(t);for(let n of e.slice(0,t))M.appendChild(as(n));Oo.length>0&&M.appendChild(_s(Oo)),M.classList.add(`show`),document.body.classList.add(`has-session-dock`)}function P(){Ao||=setTimeout(()=>{Ao=null;try{xs()}catch(e){r.warn(`[SessionDock] render failed:`,e?.message||e)}},so)}function Ss(){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=Io(t.activeSessionIds);for(let t of e){if(So.has(t)){So.delete(t),Qo(t);continue}wo.has(t)||y.generatingSessionIds.has(t)||y.pendingCallApiSessionIds.has(t)||Qo(t)}wo=e}e()})}catch{e()}})}function Cs(e){let t=e?.sessionId;if(!t)return;let n=mo.get(t)||{};mo.set(t,{nodeName:e.nodeName||n.nodeName||``,subtaskIndex:e.subtaskIndex||n.subtaskIndex||0,subtaskTotal:e.subtaskTotal||n.subtaskTotal||0}),_o.set(t,Date.now()),P()}function ws(e){e&&(mo.delete(e),ho.delete(e),go.delete(e),_o.delete(e),yo.delete(e),bo.delete(e),xo.delete(e),So.delete(e),P())}function Ts(){if(!(Mo||typeof document>`u`||!ns())){Mo=!0,bs(),document.addEventListener(`generating-state-changed`,$o),document.addEventListener(`session-switched`,P),document.addEventListener(`generation-ended`,e=>{let t=e?.detail?.sessionId;t&&(So.add(t),go.has(t)||go.set(t,Date.now())),P()}),document.addEventListener(`session-archived`,e=>ws(e?.detail?.sessionId)),document.addEventListener(`session-deleted`,e=>ws(e?.detail?.sessionId));try{qt(P)}catch(e){r.debug(`[SessionDock] subscribe queue failed:`,e?.message||e)}try{chrome.runtime.onMessage.addListener(e=>e?e.type===`EXECUTION_STATUS_UPDATE`?(Cs(e),!1):e.type===`SCHEDULED_TASK_RUN_STATE`&&e.sessionId?(e.running?vo.add(e.sessionId):vo.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){hs();return}Ss().then(P)}),document.addEventListener(`keydown`,e=>{e.key===`Escape`&&ko&&hs()}),jo||=setInterval(()=>{document.hidden||Ss().then(P)},oo),Ss().then(()=>{for(let e of wo)ho.has(e)||ho.set(e,Date.now());xs()})}}function Es(){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 Xe(e,n.top,n.bottom)}function p(e,t){let n=document.getElementById(`chatContainer`);if(!n)return`noop`;let r=gt(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=dt(r.length,Je(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=gt(document.getElementById(`chatContainer`));let e=l?gt(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=gt(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=tt(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})}}let S=null;function C(){let e=document.getElementById(`chatContainer`);return!!e&&!!e.querySelector(`.message.user`)}function w(){let e=C();r&&r.classList.toggle(`chat-nav-empty`,!e),i&&i.classList.toggle(`chat-nav-empty`,!e),a&&a.classList.toggle(`chat-nav-empty`,!e),!e&&S!==!1&&(ne(!1),v(),l=``,a&&(a.innerHTML=``)),S=e}{let e=document.getElementById(`chatContainer`);if(e){let t=!1,n=()=>{t||(t=!0,requestAnimationFrame(()=>{t=!1,w()}))};new MutationObserver(n).observe(e,{childList:!0,subtree:!0}),document.addEventListener(`session-switched`,n),w()}}function T(){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:T,isPinned:()=>s}}function Ds(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 Os=!1,ks=!1,F=[],As=``;function js(){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,13 +34,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-C_EX21mG.js"
34
34
  <div class="search-panel-empty">${t(`searchPanel.startSearchHint`)}</div>
35
35
  </div>
36
36
  </div>
37
- `,or(`search`).appendChild(e),js(),r.debug(`[SearchPanel] search panelinitializing`)}function js(){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`)?Ns():Ms()}),i.addEventListener(`click`,()=>{Ns()});let s=on(`search-panel-close-btn`);i.before(s),Oi(s,e,{onToggle:t=>{t||qe(e)}}),r.addEventListener(`click`,()=>{n.value=``,r.style.display=`none`,Ps(),n.focus()}),n.addEventListener(`input`,()=>{let e=n.value.trim();r.style.display=e?``:`none`,e||Ps()}),n.addEventListener(`keydown`,e=>{if(e.key===`Enter`){e.stopPropagation();let t=n.value.trim();t&&(c(t),Fs(t))}else if(e.key===`Escape`)y.searchInputHistoryIndex>=0?(y.searchInputHistoryIndex=-1,n.value=``):(e.stopPropagation(),Ns());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&&Fs(e)}),o.addEventListener(`click`,()=>{o.classList.contains(`active`)||(o.classList.add(`active`),a.classList.remove(`active`));let e=n.value.trim();e&&Fs(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 Us(n,r)})}function Ms(){let e=document.getElementById(`searchPanel`),t=document.getElementById(`searchPanelInput`);e.classList.add(`expanded`),qe(e),t.value.trim()&&I.length===0&&Fs(t.value.trim()),setTimeout(()=>t.focus(),100)}function Ns(){let e=document.getElementById(`searchPanel`);ur(e),e.classList.remove(`expanded`),at(e),Os=!0,Ds=!1}function Ps(){Os=!0,Ds=!1,I=[],ks=``;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 Fs(e){if(!e||!e.trim()||(e=e.trim().toLowerCase(),Ds&&ks===e))return;Os=!0,await new Promise(e=>setTimeout(e,50)),Ds=!0,Os=!1,I=[],ks=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 Ls(e,n,i):await Is(e,n,i)}catch(e){r.error(`[SearchPanel] search error:`,e),Os||(n.innerHTML=`<div class="search-panel-empty">${t(`searchPanel.searchError`)}</div>`)}Os||(Ds=!1)}async function Is(e,n,r){let i=y.activeSessionId;if(!i){n.innerHTML=`<div class="search-panel-empty">${t(`searchPanel.noActiveSession`)}</div>`;return}let a=Rs(y.messageHistory||[],e,i);if(!Os){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}Bs(a,e,n)}}async function Ls(e,n,i){let a=y.activeSessionId,o=await oe(),s=(o||[]).filter(e=>!e.archivedAt);if(Os)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=Rs(y.messageHistory||[],e,a);if(Os)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}),Bs(I,e,n,!0)}let u=s.filter(e=>e.id!==a);for(let a of u){if(Os)return;try{let r=await ne(a.id);if(!r||!r.messageHistory)continue;let o=Rs(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`),Bs(I,e,n)}}catch(e){r.warn(`[SearchPanel] searchsession failed:`,a.id,e)}await new Promise(e=>setTimeout(e,10))}if(Os)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}Bs(I,e,n)}function Rs(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=zs(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 zs(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 Bs(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">
37
+ `,or(`search`).appendChild(e),Ms(),r.debug(`[SearchPanel] search panelinitializing`)}function Ms(){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`)?Ps():Ns()}),i.addEventListener(`click`,()=>{Ps()});let s=on(`search-panel-close-btn`);i.before(s),Oi(s,e,{onToggle:t=>{t||qe(e)}}),r.addEventListener(`click`,()=>{n.value=``,r.style.display=`none`,Fs(),n.focus()}),n.addEventListener(`input`,()=>{let e=n.value.trim();r.style.display=e?``:`none`,e||Fs()}),n.addEventListener(`keydown`,e=>{if(e.key===`Enter`){e.stopPropagation();let t=n.value.trim();t&&(c(t),Is(t))}else if(e.key===`Escape`)y.searchInputHistoryIndex>=0?(y.searchInputHistoryIndex=-1,n.value=``):(e.stopPropagation(),Ps());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&&Is(e)}),o.addEventListener(`click`,()=>{o.classList.contains(`active`)||(o.classList.add(`active`),a.classList.remove(`active`));let e=n.value.trim();e&&Is(e)}),document.getElementById(`searchPanelContent`).addEventListener(`click`,async e=>{let t=e.target.closest(`.search-result-item`);if(!t)return;let n=t.dataset.sessionId,r=t.dataset.messageId;await Ws(n,r)})}function Ns(){let e=document.getElementById(`searchPanel`),t=document.getElementById(`searchPanelInput`);e.classList.add(`expanded`),qe(e),t.value.trim()&&F.length===0&&Is(t.value.trim()),setTimeout(()=>t.focus(),100)}function Ps(){let e=document.getElementById(`searchPanel`);ur(e),e.classList.remove(`expanded`),at(e),ks=!0,Os=!1}function Fs(){ks=!0,Os=!1,F=[],As=``;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 Is(e){if(!e||!e.trim()||(e=e.trim().toLowerCase(),Os&&As===e))return;ks=!0,await new Promise(e=>setTimeout(e,50)),Os=!0,ks=!1,F=[],As=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 Rs(e,n,i):await Ls(e,n,i)}catch(e){r.error(`[SearchPanel] search error:`,e),ks||(n.innerHTML=`<div class="search-panel-empty">${t(`searchPanel.searchError`)}</div>`)}ks||(Os=!1)}async function Ls(e,n,r){let i=y.activeSessionId;if(!i){n.innerHTML=`<div class="search-panel-empty">${t(`searchPanel.noActiveSession`)}</div>`;return}let a=zs(y.messageHistory||[],e,i);if(!ks){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}Vs(a,e,n)}}async function Rs(e,n,i){let a=y.activeSessionId,o=await oe(),s=(o||[]).filter(e=>!e.archivedAt);if(ks)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=zs(y.messageHistory||[],e,a);if(ks)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}),Vs(F,e,n,!0)}let u=s.filter(e=>e.id!==a);for(let a of u){if(ks)return;try{let r=await ne(a.id);if(!r||!r.messageHistory)continue;let o=zs(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`),Vs(F,e,n)}}catch(e){r.warn(`[SearchPanel] searchsession failed:`,a.id,e)}await new Promise(e=>setTimeout(e,10))}if(ks)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}Vs(F,e,n)}function zs(e,t,n){let r=[];if(!e||e.length===0)return r;let i=t.includes(`&`)||t.includes(`|`);for(let a of e){if(a.role!==`assistant`&&a.role!==`user`)continue;let e=a.messageId||a.id;if(!e)continue;let o=Bs(a.content);if(!o)continue;let s=o.toLowerCase(),c=-1,l=t;if(i){let e=t.split(`|`).map(e=>e.trim()).filter(Boolean),n=!1;for(let t of e){let e=t.split(`&`).map(e=>e.trim()).filter(Boolean);if(e.length!==0&&e.every(e=>s.includes(e))){n=!0,l=e[0],c=s.indexOf(l);break}}if(!n)continue}else{if(!s.includes(t))continue;c=s.indexOf(t)}let u=l.length,d=Math.max(0,c-30),f=Math.min(o.length,c+u+30),p=o.substring(d,f);d>0&&(p=`...`+p),f<o.length&&(p+=`...`),r.push({messageId:e,content:o.substring(0,200),role:a.role,sessionId:n,matchPreview:p,query:t})}return r}function Bs(e){return e?typeof e==`string`?e.replace(/<[^>]*>/g,``):Array.isArray(e)?e.filter(e=>e.type===`text`).map(e=>e.text||``).join(` `):String(e):``}function Vs(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
- ${Vs(o,n)}
39
+ ${Hs(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
- ${Vs(s,n)}
43
- </div>`),r.innerHTML=c}function Vs(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=Hs(A(e.matchPreview),n);return`
42
+ ${Hs(s,n)}
43
+ </div>`),r.innerHTML=c}function Hs(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=Us(A(e.matchPreview),n);return`
44
44
  <div class="search-result-item" data-session-id="${e.sessionId}" data-message-id="${e.messageId}" title="${A(e.content)}">
45
45
  <div class="search-result-header">
46
46
  <span class="search-result-role">${i} ${a}</span>
@@ -48,7 +48,7 @@ import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-C_EX21mG.js"
48
48
  </div>
49
49
  <div class="search-result-preview">${c}</div>
50
50
  </div>
51
- `}).join(``)}function Hs(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 Us(e,n){if(!(!e||!n)){if(y.activeSessionId!==e)try{let n=y.activeSessionId;if(await Ct(e)===!1||y.activeSessionId!==e){j(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-BPCvEgPs.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{j(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?(Bs(I,ks,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 Ws(e){return chrome.runtime.sendMessage(e)}function Gs(e){return e?new Date(e).toLocaleString(void 0,{month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`}):`—`}function Ks(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 qs(e){return e===`success`?t(`schedPanel.statusSuccess`):e===`failed`?t(`schedPanel.statusFailed`):e===`running`?t(`schedPanel.statusRunning`):``}function Js(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 Ys(e){let n=e.schedule||{};return n.type===`once`?n.onceMode===`relative`?t(`schedPanel.scheduleTypeOnce`)+` · `+(n.value||``)+t(`schedPanel.minutesSuffix`):t(`schedPanel.scheduleTypeOnce`)+` · `+Gs(new Date(n.value).getTime()):n.type===`interval`?t(`schedPanel.scheduleTypeInterval`)+` · `+(n.value||``):n.type===`cron`?t(`schedPanel.scheduleTypeCron`)+` · `+(n.value||``):``}function Xs(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 Zs(){let e=document.getElementById(`chatContainer`);e&&(e.scrollTop=e.scrollHeight)}async function Qs(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-BPCvEgPs.js`).then(e=>e.cr);return{renderSessionTabs:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]));e()}catch{}}setTimeout(Zs,500)}}function $s(){let e=document.createElement(`div`);e.className=`schedule-panel-container`,e.id=`schedulePanelContainer`,e.innerHTML=`
51
+ `}).join(``)}function Us(e,t){if(!t)return e;let n=t.split(/[&|]/).map(e=>e.trim()).filter(Boolean);if(n.length===0)return e;let r=n.map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)),i=RegExp(`(${r.join(`|`)})`,`gi`);return e.replace(i,`<mark class="search-highlight-match">$1</mark>`)}async function Ws(e,n){if(!(!e||!n)){if(y.activeSessionId!==e)try{let n=y.activeSessionId;if(await Ct(e)===!1||y.activeSessionId!==e){j(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-CF1oNqcX.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{j(t(`searchPanel.messageDeleted`),`warning`);try{if(await te(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?(Vs(F,As,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 Gs(e){return chrome.runtime.sendMessage(e)}function Ks(e){return e?new Date(e).toLocaleString(void 0,{month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`}):`—`}function qs(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 Js(e){return e===`success`?t(`schedPanel.statusSuccess`):e===`failed`?t(`schedPanel.statusFailed`):e===`running`?t(`schedPanel.statusRunning`):``}function Ys(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 Xs(e){let n=e.schedule||{};return n.type===`once`?n.onceMode===`relative`?t(`schedPanel.scheduleTypeOnce`)+` · `+(n.value||``)+t(`schedPanel.minutesSuffix`):t(`schedPanel.scheduleTypeOnce`)+` · `+Ks(new Date(n.value).getTime()):n.type===`interval`?t(`schedPanel.scheduleTypeInterval`)+` · `+(n.value||``):n.type===`cron`?t(`schedPanel.scheduleTypeCron`)+` · `+(n.value||``):``}function Zs(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 $s(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-CF1oNqcX.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 ec(){let e=document.createElement(`div`);e.className=`schedule-panel-container`,e.id=`schedulePanelContainer`,e.innerHTML=`
52
52
  <style>
53
53
  .schedule-panel-container { position: relative; display: flex; justify-content: flex-end; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; width: 100%; background: transparent; }
54
54
  .schedule-panel-toggle { background: rgba(var(--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; }
@@ -202,23 +202,23 @@ import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-C_EX21mG.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=on(`close-btn`);s.before(c),Oi(c,i,{onToggle:e=>{e||qe(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`),qe(i),ce()):(ur(i),i.classList.remove(`open`),at(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 Ws({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">${A(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=>`
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||qe(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`),qe(i),ce()):(ur(i),i.classList.remove(`open`),at(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 Gs({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">${A(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
207
  <span class="dot ${A(e.status||``)}"></span>
208
- <span class="time">${A(Gs(e.startedAt))}</span>
209
- <span>${A(qs(e.status))}</span>
210
- <span class="dur">${A(Ks(e.durationMs))}</span>
208
+ <span class="time">${A(Ks(e.startedAt))}</span>
209
+ <span>${A(Js(e.status))}</span>
210
+ <span class="dur">${A(qs(e.durationMs))}</span>
211
211
  ${e.error?`<span class="err" title="${A(e.error)}">${A(e.error)}</span>`:``}
212
212
  </div>
213
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
214
  <div class="sched-item" data-id="${A(e.id)}">
215
215
  <div class="row1">
216
216
  <span class="name" title="${A(e.name)}">${A(e.name)}</span>
217
- ${Xs(e)}
217
+ ${Zs(e)}
218
218
  </div>
219
219
  ${e.description?`<div class="desc">${A(e.description)}</div>`:``}
220
- <div class="meta">${A(Ys(e))}</div>
221
- <div class="meta">${t(`schedPanel.nextRun`)}: ${A(Gs(e.nextRunAt))}</div>
220
+ <div class="meta">${A(Xs(e))}</div>
221
+ <div class="meta">${t(`schedPanel.nextRun`)}: ${A(Ks(e.nextRunAt))}</div>
222
222
  ${r}
223
223
  <div class="sched-history" data-history style="display:none;">${D(e.runHistory)}</div>
224
224
  <div class="actions">
@@ -228,14 +228,14 @@ import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-C_EX21mG.js"
228
228
  <button data-act="delete" class="danger">${t(`schedPanel.delete`)}</button>
229
229
  </div>
230
230
  </div>
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 Ws({type:`SCHEDULED_TASK_TOGGLE`,id:i,enabled:!e.enabled}),ce()}else if(a===`run`){let e=await Ws({type:`SCHEDULED_TASK_RUN_NOW`,id:i});e?.success?(j(t(`schedPanel.runNowToast`),`success`),Qs(e.sessionId),setTimeout(ce,1500)):j(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 Ws({type:`SCHEDULED_TASK_DELETE`,id:i}),j(t(`schedPanel.deleted`),`success`),ce())}});async function ue(){let e=await Ws({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?Js(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=A(t.title||t.id);r+=`<option value="${A(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){j(t(`schedPanel.nameRequired`),`warning`);return}if(!n){j(t(`schedPanel.promptRequired`),`warning`);return}if(!i){j(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 Ws({type:b?`SCHEDULED_TASK_UPDATE`:`SCHEDULED_TASK_CREATE`,task:b?{...c,id:b.id}:c});e?.success?(j(t(`schedPanel.saved`),`success`),pe(),ce()):j(e?.error||t(`schedPanel.createFailed`),`error`)}catch(e){j(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(Zs,600))}),chrome.runtime.onMessage.addListener(e=>{e.type===`SCHEDULED_TASKS_CHANGED`&&ce().catch(()=>{})}),oe(),se(!1),ce().catch(()=>{})}var ec=`todoStatsLog`,tc=7;function nc(e){return String(e).padStart(2,`0`)}function rc(e=Date.now()){let t=new Date(e);return`${t.getFullYear()}-${nc(t.getMonth()+1)}-${nc(t.getDate())}`}function ic(e,t){let n=new Date(e);return n.setDate(n.getDate()+t),n.getTime()}function ac(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 oc(e,t=Date.now()){let n=rc(ic(t,-90)),r={};for(let[t,i]of Object.entries(e&&typeof e==`object`?e:{}))t>=n&&(r[t]=i);return r}function sc(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 cc(e,t){let n=sc(e,rc(t)).done>0?t:ic(t,-1),r=0;for(;r<=90&&!(sc(e,rc(n)).done<=0);)r+=1,n=ic(n,-1);return r}function lc(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=tc-1;e>=0;--e){let t=rc(ic(n,-e));o.push({date:t,...sc(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:sc(a,rc(n)),week:o,streak:cc(a,n)}}var uc=Promise.resolve();async function dc(){try{if(typeof chrome>`u`||!chrome.storage?.local?.get)return{};let e=await chrome.storage.local.get([ec]),t=e&&e.todoStatsLog;return t&&typeof t==`object`?t:{}}catch(e){return r.warn(`[Todo] load stats log failed:`,e),{}}}async function fc(e){typeof chrome>`u`||!chrome.storage?.local?.set||await chrome.storage.local.set({[ec]:e})}function pc(e,t,n=Date.now()){let i=uc.then(async()=>{let r=oc(ac(await dc(),rc(n),e,t));return await fc(r),r});return uc=i.then(()=>void 0,()=>void 0),i.catch(e=>(r.warn(`[Todo] record stat failed:`,e),null))}var mc=new Set,hc=Promise.resolve();function gc(e){let t=hc.then(e);return hc=t.then(()=>void 0,()=>void 0),t}function _c(e){return typeof e==`function`?(mc.add(e),()=>mc.delete(e)):()=>{}}function L(){for(let e of mc)try{e()}catch(e){r.warn(`[Todo] listener failed:`,e)}}async function vc(){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 yc(){return Be(y.todos)}function bc(e){return y.todos.find(t=>t.id===e)||null}function xc(e){y.todos=y.todos.map(t=>t.id===e.id?e:t)}async function Sc(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 gc(()=>C(i)).catch(e=>(r.error(`[Todo] add failed:`,e),!1))?(L(),await pc(`added`,1,i.createdAt),i):(y.todos=y.todos.filter(e=>e.id!==i.id),L(),null)}async function Cc(e,t={}){let n=bc(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),xc(i),await gc(()=>C(i)).catch(e=>(r.error(`[Todo] update failed:`,e),!1))?(L(),!0):(xc(n),L(),!1)}async function wc(e,t){let n=bc(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),xc(a),await gc(()=>C(a)).catch(e=>(r.error(`[Todo] set status failed:`,e),!1))?(L(),t===O.DONE&&n.status!==O.DONE?await pc(`done`,1,a.completedAt):n.status===O.DONE&&t!==O.DONE&&await pc(`done`,-1,n.completedAt),!0):(xc(n),L(),!1)}function Tc(e){let t=bc(e);return t?wc(e,Ve(t.status)):Promise.resolve(!1)}function Ec(e){let t=bc(e);return!t||t.status!==O.DONE?Promise.resolve(!1):wc(e,He(t))}function Dc(e,t){return Cc(e,{priority:we(t)})}async function Oc(e,t){if(!bc(e))return{ok:!1,reason:`missing`};let n=We(t);if(!n.valid)return{ok:!1,reason:`invalid`};let r=await Cc(e,{link:n.url});return{ok:r,reason:r?``:`save`}}async function kc(e){let t=bc(e);return t?(y.todos=y.todos.filter(t=>t.id!==e),await gc(()=>E(e)).catch(e=>(r.error(`[Todo] delete failed:`,e),!1))?(L(),!0):(y.todos=[...y.todos,t],L(),!1)):!1}async function Ac(e,t){let{active:n}=yc();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 gc(()=>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 jc(){let{done:e}=yc();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 gc(()=>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 Mc(e,t=`merge`){if(t===`replace`)return Nc(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 gc(()=>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 Nc(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 gc(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 Pc=[`all`,`active`,`done`],Fc={json:{ext:`json`,type:`application/json;charset=utf-8`},md:{ext:`md`,type:`text/markdown;charset=utf-8`}};function Ic(e){return e===`md`?`md`:`json`}function Lc(e){return String(e).padStart(2,`0`)}function Rc(e){let t=new Date(e);return`${t.getFullYear()}-${Lc(t.getMonth()+1)}-${Lc(t.getDate())}`}function zc(e,t,n=Date.now()){let r=Pc.includes(e)?e:`all`;return`ai-helper-todos${r===`all`?``:`-${r}`}-${Rc(n)}.${Fc[Ic(t)].ext}`}function Bc(e,t={}){let n=Pc.includes(t.scope)?t.scope:`all`,r=Ic(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:zc(n,r,i),blob:new Blob([a],{type:Fc[r].type})}}function Vc(e,t={}){let{filename:n,blob:r}=Bc(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 Hc(){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 Uc(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 Wc=`<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>`,Gc=[`all`,`active`,`done`],Kc=[`json`,`md`],qc=[`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 Jc(e){return`<div class="todo-io-header">
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 Gs({type:`SCHEDULED_TASK_TOGGLE`,id:i,enabled:!e.enabled}),ce()}else if(a===`run`){let e=await Gs({type:`SCHEDULED_TASK_RUN_NOW`,id:i});e?.success?(j(t(`schedPanel.runNowToast`),`success`),$s(e.sessionId),setTimeout(ce,1500)):j(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 Gs({type:`SCHEDULED_TASK_DELETE`,id:i}),j(t(`schedPanel.deleted`),`success`),ce())}});async function ue(){let e=await Gs({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?Ys(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=A(t.title||t.id);r+=`<option value="${A(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){j(t(`schedPanel.nameRequired`),`warning`);return}if(!n){j(t(`schedPanel.promptRequired`),`warning`);return}if(!i){j(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 Gs({type:b?`SCHEDULED_TASK_UPDATE`:`SCHEDULED_TASK_CREATE`,task:b?{...c,id:b.id}:c});e?.success?(j(t(`schedPanel.saved`),`success`),pe(),ce()):j(e?.error||t(`schedPanel.createFailed`),`error`)}catch(e){j(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(Qs,600))}),chrome.runtime.onMessage.addListener(e=>{e.type===`SCHEDULED_TASKS_CHANGED`&&ce().catch(()=>{})}),oe(),se(!1),ce().catch(()=>{})}var tc=`todoStatsLog`,nc=7;function rc(e){return String(e).padStart(2,`0`)}function ic(e=Date.now()){let t=new Date(e);return`${t.getFullYear()}-${rc(t.getMonth()+1)}-${rc(t.getDate())}`}function ac(e,t){let n=new Date(e);return n.setDate(n.getDate()+t),n.getTime()}function oc(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 sc(e,t=Date.now()){let n=ic(ac(t,-90)),r={};for(let[t,i]of Object.entries(e&&typeof e==`object`?e:{}))t>=n&&(r[t]=i);return r}function cc(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 lc(e,t){let n=cc(e,ic(t)).done>0?t:ac(t,-1),r=0;for(;r<=90&&!(cc(e,ic(n)).done<=0);)r+=1,n=ac(n,-1);return r}function uc(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=nc-1;e>=0;--e){let t=ic(ac(n,-e));o.push({date:t,...cc(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:cc(a,ic(n)),week:o,streak:lc(a,n)}}var dc=Promise.resolve();async function fc(){try{if(typeof chrome>`u`||!chrome.storage?.local?.get)return{};let e=await chrome.storage.local.get([tc]),t=e&&e.todoStatsLog;return t&&typeof t==`object`?t:{}}catch(e){return r.warn(`[Todo] load stats log failed:`,e),{}}}async function pc(e){typeof chrome>`u`||!chrome.storage?.local?.set||await chrome.storage.local.set({[tc]:e})}function mc(e,t,n=Date.now()){let i=dc.then(async()=>{let r=sc(oc(await fc(),ic(n),e,t));return await pc(r),r});return dc=i.then(()=>void 0,()=>void 0),i.catch(e=>(r.warn(`[Todo] record stat failed:`,e),null))}var hc=new Set,gc=Promise.resolve();function _c(e){let t=gc.then(e);return gc=t.then(()=>void 0,()=>void 0),t}function vc(e){return typeof e==`function`?(hc.add(e),()=>hc.delete(e)):()=>{}}function I(){for(let e of hc)try{e()}catch(e){r.warn(`[Todo] listener failed:`,e)}}async function yc(){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=[]}I()}function bc(){return Be(y.todos)}function xc(e){return y.todos.find(t=>t.id===e)||null}function Sc(e){y.todos=y.todos.map(t=>t.id===e.id?e:t)}async function Cc(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 _c(()=>C(i)).catch(e=>(r.error(`[Todo] add failed:`,e),!1))?(I(),await mc(`added`,1,i.createdAt),i):(y.todos=y.todos.filter(e=>e.id!==i.id),I(),null)}async function wc(e,t={}){let n=xc(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),Sc(i),await _c(()=>C(i)).catch(e=>(r.error(`[Todo] update failed:`,e),!1))?(I(),!0):(Sc(n),I(),!1)}async function Tc(e,t){let n=xc(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),Sc(a),await _c(()=>C(a)).catch(e=>(r.error(`[Todo] set status failed:`,e),!1))?(I(),t===O.DONE&&n.status!==O.DONE?await mc(`done`,1,a.completedAt):n.status===O.DONE&&t!==O.DONE&&await mc(`done`,-1,n.completedAt),!0):(Sc(n),I(),!1)}function Ec(e){let t=xc(e);return t?Tc(e,Ve(t.status)):Promise.resolve(!1)}function Dc(e){let t=xc(e);return!t||t.status!==O.DONE?Promise.resolve(!1):Tc(e,He(t))}function Oc(e,t){return wc(e,{priority:we(t)})}async function kc(e,t){if(!xc(e))return{ok:!1,reason:`missing`};let n=We(t);if(!n.valid)return{ok:!1,reason:`invalid`};let r=await wc(e,{link:n.url});return{ok:r,reason:r?``:`save`}}async function Ac(e){let t=xc(e);return t?(y.todos=y.todos.filter(t=>t.id!==e),await _c(()=>E(e)).catch(e=>(r.error(`[Todo] delete failed:`,e),!1))?(I(),!0):(y.todos=[...y.todos,t],I(),!1)):!1}async function jc(e,t){let{active:n}=bc();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 _c(()=>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),I(),!1}return I(),!0}async function Mc(){let{done:e}=bc();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 _c(()=>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],I(),!1}return I(),!0}async function Nc(e,t=`merge`){if(t===`replace`)return Pc(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 _c(()=>S(n.addedItems)).catch(e=>(r.error(`[Todo] import merge failed:`,e),!1))?(I(),{ok:!0,added:n.addedItems.length,skipped:n.skipped}):(y.todos=i.filter(e=>!a.has(e.id)),I(),{ok:!1,added:0,skipped:n.skipped})}async function Pc(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 _c(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))?(I(),{ok:!0,added:t.length,skipped:n}):(y.todos=i,I(),{ok:!1,added:0,skipped:n})}var Fc=[`all`,`active`,`done`],Ic={json:{ext:`json`,type:`application/json;charset=utf-8`},md:{ext:`md`,type:`text/markdown;charset=utf-8`}};function Lc(e){return e===`md`?`md`:`json`}function Rc(e){return String(e).padStart(2,`0`)}function zc(e){let t=new Date(e);return`${t.getFullYear()}-${Rc(t.getMonth()+1)}-${Rc(t.getDate())}`}function Bc(e,t,n=Date.now()){let r=Fc.includes(e)?e:`all`;return`ai-helper-todos${r===`all`?``:`-${r}`}-${zc(n)}.${Ic[Lc(t)].ext}`}function Vc(e,t={}){let n=Fc.includes(t.scope)?t.scope:`all`,r=Lc(t.format),i=t.now||Date.now(),a=r===`md`?Ce(e,{scope:n,now:i}):JSON.stringify(Ae(e,{scope:n,now:i}),null,2);return{filename:Bc(n,r,i),blob:new Blob([a],{type:Ic[r].type})}}function Hc(e,t={}){let{filename:n,blob:r}=Vc(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 Uc(){return new Promise(e=>{let t=document.createElement(`input`);t.type=`file`,t.accept=`.json,application/json`,t.style.display=`none`;let n=!1,r=r=>{n||(n=!0,t.remove(),e(r))};t.addEventListener(`change`,()=>r(t.files&&t.files[0]?t.files[0]:null)),t.addEventListener(`cancel`,()=>r(null)),document.body.appendChild(t),t.click()})}async function Wc(e){if(!e||typeof e.text!=`function`)return{ok:!1,reason:`json`};let t=``;try{t=await e.text()}catch{return{ok:!1,reason:`json`}}let n=null;try{n=JSON.parse(t)}catch{return{ok:!1,reason:`json`}}return be(n)}var Gc=`<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>`,Kc=[`all`,`active`,`done`],qc=[`json`,`md`],Jc=[`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 Yc(e){return`<div class="todo-io-header">
232
232
  <span class="todo-io-title">${A(e)}</span>
233
233
  <button type="button" class="todo-io-close" data-io-action="cancel"
234
- title="${k(t(`todoIo.close`))}" aria-label="${k(t(`todoIo.close`))}">${Wc}</button>
235
- </div>`}function Yc(e,n){return`<div class="todo-io-actions">
234
+ title="${k(t(`todoIo.close`))}" aria-label="${k(t(`todoIo.close`))}">${Gc}</button>
235
+ </div>`}function Xc(e,n){return`<div class="todo-io-actions">
236
236
  <button type="button" class="todo-io-btn" data-io-action="cancel">${A(t(`todoIo.cancel`))}</button>
237
237
  <button type="button" class="todo-io-btn primary" data-io-action="confirm"${n?` disabled`:``}>${A(e)}</button>
238
- </div>`}function Xc({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`:``}">
238
+ </div>`}function Zc({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
239
  <input type="radio" name="todoIo-${k(e)}" value="${k(t)}"
240
240
  data-io-field="${k(e)}"${i?` checked`:``} />
241
241
  <span class="todo-io-option-main">
@@ -243,9 +243,9 @@ import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-C_EX21mG.js"
243
243
  ${r?`<span class="todo-io-option-hint">${A(r)}</span>`:``}
244
244
  </span>
245
245
  ${s}
246
- </label>`}function Zc(e,n={}){let r=Gc.includes(e?.scope)?e.scope:`all`,i=Kc.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])=>Xc({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])=>Xc({field:`format`,value:e,label:t,checked:e===i})).join(``);return`<div class="todo-io-card" role="dialog" aria-modal="true" tabindex="-1"
246
+ </label>`}function Qc(e,n={}){let r=Kc.includes(e?.scope)?e.scope:`all`,i=qc.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])=>Zc({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])=>Zc({field:`format`,value:e,label:t,checked:e===i})).join(``);return`<div class="todo-io-card" role="dialog" aria-modal="true" tabindex="-1"
247
247
  aria-label="${k(t(`todoIo.exportTitle`))}">
248
- ${Jc(t(`todoIo.exportTitle`))}
248
+ ${Yc(t(`todoIo.exportTitle`))}
249
249
  <div class="todo-io-body">
250
250
  <div class="todo-io-group">
251
251
  <div class="todo-io-group-label">${A(t(`todoIo.rangeLabel`))}</div>
@@ -257,10 +257,10 @@ import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-C_EX21mG.js"
257
257
  </div>
258
258
  <p class="todo-io-hint${a?` show`:``}" data-io-hint>${A(t(`todoIo.emptyRange`))}</p>
259
259
  </div>
260
- ${Yc(t(`todoIo.exportAction`),a)}
261
- </div>`}function Qc(e,n={}){let r=qc.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])=>Xc({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"
260
+ ${Xc(t(`todoIo.exportAction`),a)}
261
+ </div>`}function $c(e,n={}){let r=Jc.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])=>Zc({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
262
  aria-label="${k(t(`todoIo.importTitle`))}">
263
- ${Jc(t(`todoIo.importTitle`))}
263
+ ${Yc(t(`todoIo.importTitle`))}
264
264
  <div class="todo-io-body">
265
265
  <p class="todo-io-summary">${A(t(`todoIo.importSummary`,{count:i,existing:a}))}</p>
266
266
  <div class="todo-io-group">
@@ -269,14 +269,14 @@ import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-C_EX21mG.js"
269
269
  </div>
270
270
  <p class="todo-io-warn${r===`replace`?` show`:``}" data-io-warn>${A(t(`todoIo.replaceWarn`,{count:i}))}</p>
271
271
  </div>
272
- ${Yc(t(`todoIo.importAction`),!1)}
273
- </div>`}var R=null,z=null,$c=null;function el(){return R||(R=document.createElement(`div`),R.className=`todo-io-overlay`,R.id=`todoIoOverlay`,R.addEventListener(`click`,e=>{if(e.target===R){il(null);return}let t=e.target.closest?.(`[data-io-action]`);t?.dataset.ioAction===`cancel`?il(null):t?.dataset.ioAction===`confirm`&&rl()}),R.addEventListener(`change`,e=>{if(!z)return;let t=e.target.closest?.(`input[data-io-field]`);t&&(z.state[t.dataset.ioField]=t.value,nl())}),document.body.appendChild(R),R)}function tl(){if(!z)return;let e=el();e.innerHTML=z.kind===`export`?Zc(z.state,z.counts):Qc(z.state,z.info),nl()}function nl(){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 rl(){if(z){if(z.kind===`export`){if(!Number(z.counts[z.state.scope]||0))return;il({scope:z.state.scope,format:z.state.format});return}il(z.state.mode)}}function il(e){if(!z)return;let{resolve:t}=z;z=null,R?.classList.remove(`show`),ol(),t(e)}function al(){$c||($c=e=>{e.key===`Escape`&&(e.stopPropagation(),il(null))},document.addEventListener(`keydown`,$c))}function ol(){$c&&=(document.removeEventListener(`keydown`,$c),null)}function sl(e,t,n){return z&&il(null),new Promise(r=>{z={kind:e,state:t,...n,resolve:r},tl(),R.classList.add(`show`),al(),R.querySelector(`.todo-io-card`)?.focus()})}function cl({counts:e={},scope:t=`all`,format:n=`json`}={}){return sl(`export`,{scope:Gc.includes(t)?t:`all`,format:Kc.includes(n)?n:`json`},{counts:e})}function ll({count:e=0,existing:t=0,mode:n=`merge`}={}){return sl(`import`,{mode:qc.includes(n)?n:`merge`},{info:{count:e,existing:t}})}o(()=>{z&&(tl(),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 ul={zh:[`日`,`一`,`二`,`三`,`四`,`五`,`六`],en:[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`]},dl=6;function fl(e){let[t,n,r]=String(e||``).split(`-`).map(Number);return!t||!n||!r?null:new Date(t,n-1,r)}function pl(e){let t=fl(e);return t?a()===`en`?`${t.toLocaleString(`en-US`,{month:`short`})} ${t.getDate()}`:`${t.getMonth()+1}月${t.getDate()}日`:String(e||``)}function ml(e){let t=fl(e);return t?(ul[a()]||ul.zh)[t.getDay()]:``}function hl(e,t,n){return`<div class="todo-stats-tile${n?` ${n}`:``}">
272
+ ${Xc(t(`todoIo.importAction`),!1)}
273
+ </div>`}var L=null,R=null,el=null;function tl(){return L||(L=document.createElement(`div`),L.className=`todo-io-overlay`,L.id=`todoIoOverlay`,L.addEventListener(`click`,e=>{if(e.target===L){al(null);return}let t=e.target.closest?.(`[data-io-action]`);t?.dataset.ioAction===`cancel`?al(null):t?.dataset.ioAction===`confirm`&&il()}),L.addEventListener(`change`,e=>{if(!R)return;let t=e.target.closest?.(`input[data-io-field]`);t&&(R.state[t.dataset.ioField]=t.value,rl())}),document.body.appendChild(L),L)}function nl(){if(!R)return;let e=tl();e.innerHTML=R.kind===`export`?Qc(R.state,R.counts):$c(R.state,R.info),rl()}function rl(){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 il(){if(R){if(R.kind===`export`){if(!Number(R.counts[R.state.scope]||0))return;al({scope:R.state.scope,format:R.state.format});return}al(R.state.mode)}}function al(e){if(!R)return;let{resolve:t}=R;R=null,L?.classList.remove(`show`),sl(),t(e)}function ol(){el||(el=e=>{e.key===`Escape`&&(e.stopPropagation(),al(null))},document.addEventListener(`keydown`,el))}function sl(){el&&=(document.removeEventListener(`keydown`,el),null)}function cl(e,t,n){return R&&al(null),new Promise(r=>{R={kind:e,state:t,...n,resolve:r},nl(),L.classList.add(`show`),ol(),L.querySelector(`.todo-io-card`)?.focus()})}function ll({counts:e={},scope:t=`all`,format:n=`json`}={}){return cl(`export`,{scope:Kc.includes(t)?t:`all`,format:qc.includes(n)?n:`json`},{counts:e})}function ul({count:e=0,existing:t=0,mode:n=`merge`}={}){return cl(`import`,{mode:Jc.includes(n)?n:`merge`},{info:{count:e,existing:t}})}o(()=>{R&&(nl(),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 dl={zh:[`日`,`一`,`二`,`三`,`四`,`五`,`六`],en:[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`]},fl=6;function pl(e){let[t,n,r]=String(e||``).split(`-`).map(Number);return!t||!n||!r?null:new Date(t,n-1,r)}function ml(e){let t=pl(e);return t?a()===`en`?`${t.toLocaleString(`en-US`,{month:`short`})} ${t.getDate()}`:`${t.getMonth()+1}月${t.getDate()}日`:String(e||``)}function hl(e){let t=pl(e);return t?(dl[a()]||dl.zh)[t.getDay()]:``}function gl(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 gl(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(dl,Math.round(r/n*100));return`<div class="todo-stats-bar-col" title="${t(`todoStats.dayTitle`,{date:pl(e.date),done:r,added:e.added||0})}">
276
+ </div>`}function _l(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(fl,Math.round(r/n*100));return`<div class="todo-stats-bar-col" title="${t(`todoStats.dayTitle`,{date:ml(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">${ml(e.date)}</span>
279
- </div>`}).join(``)}</div>`}function _l(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">${hl(e.date)}</span>
279
+ </div>`}).join(``)}</div>`}function vl(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-C_EX21mG.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
- ${hl(n.pending||0,t(`todoStats.pending`))}
289
- ${hl(n.doing||0,t(`todoStats.doing`),`doing`)}
290
- ${hl(n.done||0,t(`todoStats.done`),`done`)}
291
- ${hl(n.overdue||0,t(`todoStats.overdue`),n.overdue?`alert`:``)}
288
+ ${gl(n.pending||0,t(`todoStats.pending`))}
289
+ ${gl(n.doing||0,t(`todoStats.doing`),`doing`)}
290
+ ${gl(n.done||0,t(`todoStats.done`),`done`)}
291
+ ${gl(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
- ${gl(o)}
295
+ ${_l(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 vl=`<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>`,yl=null,bl=null;function xl(){return yl||(yl=document.createElement(`div`),yl.className=`todo-stats-overlay`,yl.id=`todoStatsOverlay`,yl.addEventListener(`click`,e=>{(e.target===yl||e.target.closest?.(`[data-action="close-stats"]`))&&Tl()}),document.body.appendChild(yl),yl)}function Sl(e){let n=xl();n.innerHTML=`
302
+ </div>`}var yl=`<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>`,bl=null,xl=null;function Sl(){return bl||(bl=document.createElement(`div`),bl.className=`todo-stats-overlay`,bl.id=`todoStatsOverlay`,bl.addEventListener(`click`,e=>{(e.target===bl||e.target.closest?.(`[data-action="close-stats"]`))&&El()}),document.body.appendChild(bl),bl)}function Cl(e){let n=Sl();n.innerHTML=`
303
303
  <div class="todo-stats-card" role="dialog" aria-modal="true" aria-label="${k(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="${k(t(`todoStats.close`))}" aria-label="${k(t(`todoStats.close`))}">${vl}</button>
307
+ title="${k(t(`todoStats.close`))}" aria-label="${k(t(`todoStats.close`))}">${yl}</button>
308
308
  </div>
309
- <div class="todo-stats-body">${_l(e)}</div>
310
- </div>`}async function Cl(){let e=await dc(),{active:t,done:n}=yc();Sl(lc([...t,...n],e))}async function wl(){await Cl();let e=xl();e.classList.add(`show`),bl||(bl=e=>{e.key===`Escape`&&(e.stopPropagation(),Tl())},document.addEventListener(`keydown`,bl)),e.querySelector(`.todo-stats-close`)?.focus()}function Tl(){yl&&(yl.classList.remove(`show`),bl&&=(document.removeEventListener(`keydown`,bl),null))}o(()=>{yl?.classList.contains(`show`)&&Cl()}),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 El=`.input-container`,Dl=160,Ol=8,kl=108,Al=220,jl=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,Ml=null,Nl=null,Pl=null,Fl=null,Il=null,Ll=null,Rl=null,zl=null,Bl=null,Vl=`active`,Hl=null,W=null,Ul=null,G=null,Wl=new Set,Gl=null,Kl=!1,ql=null,Jl=null,Yl=null,Xl=null,Zl=0,Ql=null,$l=!1,eu=!1,tu=new Map,nu=[`todo-edit-input`,`todo-note-input`,`todo-due-input`,`todo-link-input`],ru={"todo-edit-input":`title`,"todo-note-input":`note`,"todo-due-input":`due`,"todo-link-input":`link`};function iu(){Kl||(Kl=!0,V=document.createElement(`div`),V.className=`todo-panel-container`,V.id=`todoPanelContainer`,V.innerHTML=`
309
+ <div class="todo-stats-body">${vl(e)}</div>
310
+ </div>`}async function wl(){let e=await fc(),{active:t,done:n}=bc();Cl(uc([...t,...n],e))}async function Tl(){await wl();let e=Sl();e.classList.add(`show`),xl||(xl=e=>{e.key===`Escape`&&(e.stopPropagation(),El())},document.addEventListener(`keydown`,xl)),e.querySelector(`.todo-stats-close`)?.focus()}function El(){bl&&(bl.classList.remove(`show`),xl&&=(document.removeEventListener(`keydown`,xl),null))}o(()=>{bl?.classList.contains(`show`)&&wl()}),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 Dl=`.input-container`,Ol=160,kl=8,Al=108,jl=220,Ml=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,Nl=null,Pl=null,Fl=null,Il=null,Ll=null,Rl=null,zl=null,Bl=null,Vl=null,Hl=`active`,Ul=null,U=null,Wl=null,W=null,Gl=new Set,Kl=null,ql=!1,Jl=null,Yl=null,Xl=null,Zl=null,Ql=0,$l=null,eu=!1,tu=!1,nu=new Map,ru=[`todo-edit-input`,`todo-note-input`,`todo-due-input`,`todo-link-input`],iu={"todo-edit-input":`title`,"todo-note-input":`note`,"todo-due-input":`due`,"todo-link-input":`link`};function au(){ql||(ql=!0,B=document.createElement(`div`),B.className=`todo-panel-container`,B.id=`todoPanelContainer`,B.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
- ${B.listCheck}
313
+ ${z.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">${B.listCheck}</span>
317
+ <span class="todo-panel-icon">${z.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">${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>
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>
323
323
  </div>
324
324
  </div>
325
325
  <div class="todo-progress-row">
@@ -340,17 +340,17 @@ import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-C_EX21mG.js"
340
340
  </div>
341
341
  <div class="todo-body" id="todoBody"></div>
342
342
  </div>
343
- `,or(`todo`).appendChild(V),i(V),Fl=V.querySelector(`#todoPanelToggle`),H=V.querySelector(`#todoPanel`),U=V.querySelector(`#todoBody`),Ml=V.querySelector(`#todoPanelCount`),Nl=V.querySelector(`#todoProgressBar`),Pl=V.querySelector(`#todoAddInput`),Il=V.querySelector(`#todoBadge`),Rl=V.querySelector(`#todoTabActive`),zl=V.querySelector(`#todoTabDone`),Bl=V.querySelector(`.todo-fullscreen-btn`),uu(),Ml.textContent=t(`todo.progressLabel`,{done:0,total:0}),Fl.addEventListener(`click`,ou),V.addEventListener(`click`,Iu),V.addEventListener(`change`,id),V.addEventListener(`keydown`,Uu),U.addEventListener(`dragstart`,Ad),U.addEventListener(`dragover`,jd),U.addEventListener(`drop`,Nd),U.addEventListener(`dragend`,Pd),U.addEventListener(`focusout`,ad),U.addEventListener(`dblclick`,ed),U.addEventListener(`focusin`,e=>{let t=e.target.closest?.(`.todo-item`);t?.dataset.id&&(Yl=t.dataset.id)}),V.addEventListener(`pointerdown`,e=>{let t=e.target?.closest?.(`[data-action="link-cancel"]`);if(t){e.preventDefault(),ud(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`&&Ll&&md()}),document.addEventListener(`keydown`,Ku),document.addEventListener(`click`,e=>{Ll&&(Ll.contains(e.target)||md())},!0),_c(()=>q()),chrome.runtime.onMessage.addListener(e=>{e?.type===`TODO_CHANGED`&&vc().catch(()=>{})}),o(()=>{i(V),q()}),n().then(()=>{i(V),q()}),q())}function au(){return!!H&&H.classList.contains(`expanded`)}function ou(){au()?cu():su()}function su(){Vl=`active`,ql=null,Zl=0,H.style.removeProperty(`height`),q(),H.classList.add(`expanded`),Fl.classList.add(`active`),Su(),xu(),setTimeout(()=>{au()&&Pl.focus()},60)}function cu(){eu=!1,H.classList.remove(`fullscreen`),uu(),H.classList.remove(`expanded`),Fl.classList.remove(`active`),Cu(),H.style.removeProperty(`--fit-y`),H.style.removeProperty(`--todo-max-h`),H.style.removeProperty(`height`),Zl=0,md(),dd(),Tu()}function lu(e){!H||eu===e||(eu=e,H.classList.toggle(`fullscreen`,e),uu(),md(),e?(Cu(),H.style.removeProperty(`--fit-y`),H.style.removeProperty(`--todo-max-h`),H.style.removeProperty(`height`),Zl=0):(Su(),xu()))}function uu(){if(!Bl)return;let e=t(eu?`todo.exitFullscreen`:`todo.fullscreen`);Bl.innerHTML=eu?B.collapse:B.expand,Bl.title=e,Bl.setAttribute(`aria-label`,e),Bl.setAttribute(`aria-pressed`,String(eu))}function du(){nu.forEach(e=>{U.querySelectorAll(`.${e}`).forEach(t=>{let n=t.dataset.id;if(!n)return;let r=tu.get(n)||{};r[ru[e]]=t.value,tu.set(n,r)})})}function fu(e){if(tu.size===0)return;let t=new Set(e.map(e=>e.id));for(let e of[...tu.keys()])t.has(e)||tu.delete(e)}function K(e){e?tu.delete(e):tu.clear()}function pu(e,t){let n=tu.get(e);return n&&n[t]!==void 0?n[t]:null}function mu(){let e=document.activeElement;if(!e||!U.contains(e))return null;let t=nu.find(t=>e.classList.contains(t));return!t||!e.dataset.id?null:{cls:t,id:e.dataset.id,caret:hu(e)}}function hu(e){try{return e.selectionStart}catch{return null}}function gu(e){return U.querySelector(`.${e.cls}[data-id="${k(e.id)}"]`)}function _u(e){let t=gu(e);if(t&&(t.focus(),e.caret!==null))try{t.selectionStart=t.selectionEnd=e.caret}catch{}}function vu(){if(Hl){Nu();return}if(W){let e=gu({cls:`todo-note-input`,id:W});if(!e)return;e.focus(),e.selectionStart=e.selectionEnd=e.value.length;return}if(Ul){let e=gu({cls:`todo-due-input`,id:Ul});e&&e.focus();return}if(G){let e=gu({cls:`todo-link-input`,id:G});if(!e)return;e.focus(),e.selectionStart=e.selectionEnd=e.value.length}}function q(){if(!U)return;du();let e=mu(),n=document.activeElement?.closest?.(`.todo-item`)?.dataset.id||null,{active:r,done:i,stats:a}=yc();Ml.textContent=t(`todo.progressLabel`,{done:a.done,total:a.total})+(a.doing>0?t(`todo.progressDoing`,{doing:a.doing}):``),Nl.style.width=a.total?`${Math.round(a.done/a.total*100)}%`:`0%`,Eu(r.length),yu(r.length,i.length),uu();let o=Vl===`done`?i:r,s=[];if(fu([...r,...i]),ql&&s.push(`<div class="todo-undo">
344
- <span class="todo-undo-text">${A(t(`todo.undoBar`,{title:ql.title}))}</span>
345
- <button class="todo-mini-btn" data-action="undo-complete" data-id="${k(ql.id)}">${A(t(`todo.undoAction`))}</button>
346
- </div>`),Vl===`done`&&i.length>0&&s.push(`<button class="todo-clear-done" data-action="clear-completed-btn">
347
- ${B.trash}<span>${A(t(`todo.clearCompleted`))} (${i.length})</span>
348
- </button>`),o.length===0){let e=Vl===`done`;s.push(`<div class="todo-empty">
343
+ `,or(`todo`).appendChild(B),i(B),Il=B.querySelector(`#todoPanelToggle`),V=B.querySelector(`#todoPanel`),H=B.querySelector(`#todoBody`),Nl=B.querySelector(`#todoPanelCount`),Pl=B.querySelector(`#todoProgressBar`),Fl=B.querySelector(`#todoAddInput`),Ll=B.querySelector(`#todoBadge`),zl=B.querySelector(`#todoTabActive`),Bl=B.querySelector(`#todoTabDone`),Vl=B.querySelector(`.todo-fullscreen-btn`),du(),Nl.textContent=t(`todo.progressLabel`,{done:0,total:0}),Il.addEventListener(`click`,su),B.addEventListener(`click`,Lu),B.addEventListener(`change`,ad),B.addEventListener(`keydown`,Wu),H.addEventListener(`dragstart`,jd),H.addEventListener(`dragover`,Md),H.addEventListener(`drop`,Pd),H.addEventListener(`dragend`,Fd),H.addEventListener(`focusout`,od),H.addEventListener(`dblclick`,td),H.addEventListener(`focusin`,e=>{let t=e.target.closest?.(`.todo-item`);t?.dataset.id&&(Xl=t.dataset.id)}),B.addEventListener(`pointerdown`,e=>{let t=e.target?.closest?.(`[data-action="link-cancel"]`);if(t){e.preventDefault(),dd(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`&&Rl&&hd()}),document.addEventListener(`keydown`,qu),document.addEventListener(`click`,e=>{Rl&&(Rl.contains(e.target)||hd())},!0),vc(()=>K()),chrome.runtime.onMessage.addListener(e=>{e?.type===`TODO_CHANGED`&&yc().catch(()=>{})}),o(()=>{i(B),K()}),n().then(()=>{i(B),K()}),K())}function ou(){return!!V&&V.classList.contains(`expanded`)}function su(){ou()?lu():cu()}function cu(){Hl=`active`,Jl=null,Ql=0,V.style.removeProperty(`height`),K(),V.classList.add(`expanded`),Il.classList.add(`active`),Cu(),Su(),setTimeout(()=>{ou()&&Fl.focus()},60)}function lu(){tu=!1,V.classList.remove(`fullscreen`),du(),V.classList.remove(`expanded`),Il.classList.remove(`active`),wu(),V.style.removeProperty(`--fit-y`),V.style.removeProperty(`--todo-max-h`),V.style.removeProperty(`height`),Ql=0,hd(),fd(),Eu()}function uu(e){!V||tu===e||(tu=e,V.classList.toggle(`fullscreen`,e),du(),hd(),e?(wu(),V.style.removeProperty(`--fit-y`),V.style.removeProperty(`--todo-max-h`),V.style.removeProperty(`height`),Ql=0):(Cu(),Su()))}function du(){if(!Vl)return;let e=t(tu?`todo.exitFullscreen`:`todo.fullscreen`);Vl.innerHTML=tu?z.collapse:z.expand,Vl.title=e,Vl.setAttribute(`aria-label`,e),Vl.setAttribute(`aria-pressed`,String(tu))}function fu(){ru.forEach(e=>{H.querySelectorAll(`.${e}`).forEach(t=>{let n=t.dataset.id;if(!n)return;let r=nu.get(n)||{};r[iu[e]]=t.value,nu.set(n,r)})})}function pu(e){if(nu.size===0)return;let t=new Set(e.map(e=>e.id));for(let e of[...nu.keys()])t.has(e)||nu.delete(e)}function G(e){e?nu.delete(e):nu.clear()}function mu(e,t){let n=nu.get(e);return n&&n[t]!==void 0?n[t]:null}function hu(){let e=document.activeElement;if(!e||!H.contains(e))return null;let t=ru.find(t=>e.classList.contains(t));return!t||!e.dataset.id?null:{cls:t,id:e.dataset.id,caret:gu(e)}}function gu(e){try{return e.selectionStart}catch{return null}}function _u(e){return H.querySelector(`.${e.cls}[data-id="${k(e.id)}"]`)}function vu(e){let t=_u(e);if(t&&(t.focus(),e.caret!==null))try{t.selectionStart=t.selectionEnd=e.caret}catch{}}function yu(){if(Ul){Pu();return}if(U){let e=_u({cls:`todo-note-input`,id:U});if(!e)return;e.focus(),e.selectionStart=e.selectionEnd=e.value.length;return}if(Wl){let e=_u({cls:`todo-due-input`,id:Wl});e&&e.focus();return}if(W){let e=_u({cls:`todo-link-input`,id:W});if(!e)return;e.focus(),e.selectionStart=e.selectionEnd=e.value.length}}function K(){if(!H)return;fu();let e=hu(),n=document.activeElement?.closest?.(`.todo-item`)?.dataset.id||null,{active:r,done:i,stats:a}=bc();Nl.textContent=t(`todo.progressLabel`,{done:a.done,total:a.total})+(a.doing>0?t(`todo.progressDoing`,{doing:a.doing}):``),Pl.style.width=a.total?`${Math.round(a.done/a.total*100)}%`:`0%`,Du(r.length),bu(r.length,i.length),du();let o=Hl===`done`?i:r,s=[];if(pu([...r,...i]),Jl&&s.push(`<div class="todo-undo">
344
+ <span class="todo-undo-text">${A(t(`todo.undoBar`,{title:Jl.title}))}</span>
345
+ <button class="todo-mini-btn" data-action="undo-complete" data-id="${k(Jl.id)}">${A(t(`todo.undoAction`))}</button>
346
+ </div>`),Hl===`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=Hl===`done`;s.push(`<div class="todo-empty">
349
349
  <div class="todo-empty-title">${A(t(e?`todo.emptyDone`:`todo.empty`))}</div>
350
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="${Vl}">${o.map(e=>Mu(e,Vl)).join(``)}</div>`);U.innerHTML=s.join(``);let c=$l;$l=!1,e?_u(e):c?vu():n?Xu(n):vu(),xu()}function yu(e,t){if(!Rl||!zl)return;let n=Vl===`done`;Rl.classList.toggle(`active`,!n),zl.classList.toggle(`active`,n),Rl.setAttribute(`aria-selected`,String(!n)),zl.setAttribute(`aria-selected`,String(n)),Rl.querySelector(`.todo-tab-count`).textContent=String(e),zl.querySelector(`.todo-tab-count`).textContent=String(t)}function bu(){let e=document.querySelector(El)?.getBoundingClientRect();return e&&e.height>0&&Number.isFinite(e.top)?e.top:window.innerHeight-Dl}function xu(){!H||!au()||eu||(H.style.removeProperty(`--fit-y`),requestAnimationFrame(()=>{if(!H||!au())return;let e=bu()-Ol,t=H.getBoundingClientRect();if(!t.height)return;let n=Math.max(Al,Math.floor(e-kl));H.style.setProperty(`--todo-max-h`,`${n}px`),Zl&&(H.style.height=`auto`),Zl=Math.min(n,Math.max(Zl,H.offsetHeight)),H.style.height=`${Zl}px`;let r=Math.floor(e-t.bottom);r&&H.style.setProperty(`--fit-y`,`${r}px`)}))}function Su(){Cu(),window.addEventListener(`resize`,xu);let e=document.querySelector(El);e&&typeof ResizeObserver<`u`&&(Xl=new ResizeObserver(()=>xu()),Xl.observe(e))}function Cu(){window.removeEventListener(`resize`,xu),Xl?.disconnect(),Xl=null}function wu(e){ql={id:e.id,title:e.title},clearTimeout(Jl),Jl=setTimeout(()=>{ql=null,q()},jl)}function Tu(){clearTimeout(Jl),Jl=null,ql=null}function Eu(e){Il&&(e>0?(Il.textContent=e>99?`99+`:String(e),Il.style.display=``):Il.style.display=`none`)}function Du(e){return e===O.DONE?t(`todo.statusDone`):e===O.DOING?t(`todo.statusDoing`):t(`todo.statusPending`)}function Ou(e){let n=t(`todo.statusTip`,{status:Du(e.status),next:Du(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="${k(e.id)}"
352
- title="${k(n)}" aria-label="${k(n)}">${r}</button>`}function ku(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="${k(e.id)}"
353
- title="${k(r)}" aria-label="${k(r)}">${B.link}<span>${A(n)}</span></button>`}function Au(e){let n=ku(e);if(e.status===O.DONE)return`<div class="todo-meta">${n}<span>${A(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}${A(i)}</span>`)}let i=Ne(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 ju(e){let n=Wl.has(e.id),r=W===e.id,i=!!(e.note&&e.note.trim());if(r){let n=pu(e.id,`note`);return`<div class="todo-note-editor">
351
+ </div>`)}else s.push(`<div class="todo-list" data-group="${Hl}">${o.map(e=>Nu(e,Hl)).join(``)}</div>`);H.innerHTML=s.join(``);let c=eu;eu=!1,e?vu(e):c?yu():n?Zu(n):yu(),Su()}function bu(e,t){if(!zl||!Bl)return;let n=Hl===`done`;zl.classList.toggle(`active`,!n),Bl.classList.toggle(`active`,n),zl.setAttribute(`aria-selected`,String(!n)),Bl.setAttribute(`aria-selected`,String(n)),zl.querySelector(`.todo-tab-count`).textContent=String(e),Bl.querySelector(`.todo-tab-count`).textContent=String(t)}function xu(){let e=document.querySelector(Dl)?.getBoundingClientRect();return e&&e.height>0&&Number.isFinite(e.top)?e.top:window.innerHeight-Ol}function Su(){!V||!ou()||tu||(V.style.removeProperty(`--fit-y`),requestAnimationFrame(()=>{if(!V||!ou())return;let e=xu()-kl,t=V.getBoundingClientRect();if(!t.height)return;let n=Math.max(jl,Math.floor(e-Al));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 Cu(){wu(),window.addEventListener(`resize`,Su);let e=document.querySelector(Dl);e&&typeof ResizeObserver<`u`&&(Zl=new ResizeObserver(()=>Su()),Zl.observe(e))}function wu(){window.removeEventListener(`resize`,Su),Zl?.disconnect(),Zl=null}function Tu(e){Jl={id:e.id,title:e.title},clearTimeout(Yl),Yl=setTimeout(()=>{Jl=null,K()},Ml)}function Eu(){clearTimeout(Yl),Yl=null,Jl=null}function Du(e){Ll&&(e>0?(Ll.textContent=e>99?`99+`:String(e),Ll.style.display=``):Ll.style.display=`none`)}function Ou(e){return e===O.DONE?t(`todo.statusDone`):e===O.DOING?t(`todo.statusDoing`):t(`todo.statusPending`)}function ku(e){let n=t(`todo.statusTip`,{status:Ou(e.status),next:Ou(Ve(e.status))}),r=e.status===O.DONE?z.check:e.status===O.DOING?`<i></i>`:``;return`<button class="todo-status" data-action="cycle" data-id="${k(e.id)}"
352
+ title="${k(n)}" aria-label="${k(n)}">${r}</button>`}function Au(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="${k(e.id)}"
353
+ title="${k(r)}" aria-label="${k(r)}">${z.link}<span>${A(n)}</span></button>`}function ju(e){let n=Au(e);if(e.status===O.DONE)return`<div class="todo-meta">${n}<span>${A(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`:``}">${z.alert}${A(i)}</span>`)}let i=Ne(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 Mu(e){let n=Gl.has(e.id),r=U===e.id,i=!!(e.note&&e.note.trim());if(r){let n=mu(e.id,`note`);return`<div class="todo-note-editor">
354
354
  <textarea class="todo-note-input" data-id="${k(e.id)}" rows="2"
355
355
  placeholder="${k(t(`todo.notePlaceholder`))}">${A(n===null?e.note||``:n)}</textarea>
356
356
  <div class="todo-note-editor-actions">
@@ -358,52 +358,52 @@ import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-C_EX21mG.js"
358
358
  <button class="todo-mini-btn ghost" data-action="note-cancel" data-id="${k(e.id)}">${A(t(`todo.noteCancel`))}</button>
359
359
  </div>
360
360
  </div>`}return i?`<button class="todo-note-toggle${n?` open`:``}" data-action="toggle-note" data-id="${k(e.id)}">
361
- ${B.chevron}<span>${A(t(`todo.noteToggle`))}</span>
361
+ ${z.chevron}<span>${A(t(`todo.noteToggle`))}</span>
362
362
  </button>
363
- ${n?`<div class="todo-note">${A(e.note)}</div>`:``}`:``}function Mu(e,n){let r=e.status===O.DONE,i=Hl===e.id,a=[`todo-item`];e.status===O.DOING&&a.push(`doing`),r&&a.push(`done`),e.priority&&a.push(`prio-${e.priority}`),Ul===e.id&&a.push(`editing-due`);let o=pu(e.id,`title`),s=i?`<input type="text" class="todo-edit-input" data-id="${k(e.id)}" value="${k(o===null?e.title:o)}" />`:`<div class="todo-name">${A(e.title)}</div>`,c=pu(e.id,`due`),l=Ul===e.id?`<div class="todo-due-editor">
364
- <input type="date" class="todo-due-input" data-id="${k(e.id)}" value="${k(c===null?Pu(e.dueAt):c)}" />
363
+ ${n?`<div class="todo-note">${A(e.note)}</div>`:``}`:``}function Nu(e,n){let r=e.status===O.DONE,i=Ul===e.id,a=[`todo-item`];e.status===O.DOING&&a.push(`doing`),r&&a.push(`done`),e.priority&&a.push(`prio-${e.priority}`),Wl===e.id&&a.push(`editing-due`);let o=mu(e.id,`title`),s=i?`<input type="text" class="todo-edit-input" data-id="${k(e.id)}" value="${k(o===null?e.title:o)}" />`:`<div class="todo-name">${A(e.title)}</div>`,c=mu(e.id,`due`),l=Wl===e.id?`<div class="todo-due-editor">
364
+ <input type="date" class="todo-due-input" data-id="${k(e.id)}" value="${k(c===null?Fu(e.dueAt):c)}" />
365
365
  <button class="todo-mini-btn ghost" data-action="due-clear" data-id="${k(e.id)}">${A(t(`todo.clearDue`))}</button>
366
- </div>`:``,u=pu(e.id,`link`),d=G===e.id?`<div class="todo-link-editor">
366
+ </div>`:``,u=mu(e.id,`link`),d=W===e.id?`<div class="todo-link-editor">
367
367
  <input type="text" class="todo-link-input" data-id="${k(e.id)}" autocomplete="off"
368
368
  placeholder="${k(t(`todo.linkPlaceholder`))}" value="${k(u===null?e.link||``:u)}" />
369
369
  <button class="todo-mini-btn ghost" data-action="link-cancel" data-id="${k(e.id)}">${A(t(`todo.noteCancel`))}</button>
370
- </div>`:``,f=n===`active`?` draggable="true"`:``,p=Hl===e.id||W===e.id||Ul===e.id||G===e.id,m=`
370
+ </div>`:``,f=n===`active`?` draggable="true"`:``,p=Ul===e.id||U===e.id||Wl===e.id||W===e.id,m=`
371
371
  <div class="todo-item-actions">
372
- ${r?`<button class="todo-act" data-action="restore" data-id="${k(e.id)}" title="${k(t(`todo.restoreTo`,{status:Du(He(e))}))}" aria-label="${k(t(`todo.restoreTo`,{status:Du(He(e))}))}">${B.undo}</button>`:``}
373
- <button class="todo-act" data-action="edit-title" data-id="${k(e.id)}" title="${k(t(`todo.editItem`))}" aria-label="${k(t(`todo.editItem`))}">${B.edit}</button>
374
- <button class="todo-act" data-action="copy-item" data-id="${k(e.id)}" title="${k(t(`todo.copyItem`))}" aria-label="${k(t(`todo.copyItem`))}">${B.copy}</button>
375
- <button class="todo-act" data-action="fill-item" data-id="${k(e.id)}" title="${k(t(`todo.fillInput`))}" aria-label="${k(t(`todo.fillInput`))}">${B.fill}</button>
376
- <button class="todo-act" data-action="row-more" data-id="${k(e.id)}" title="${k(t(`todo.more`))}" aria-label="${k(t(`todo.more`))}">${B.more}</button>
372
+ ${r?`<button class="todo-act" data-action="restore" data-id="${k(e.id)}" title="${k(t(`todo.restoreTo`,{status:Ou(He(e))}))}" aria-label="${k(t(`todo.restoreTo`,{status:Ou(He(e))}))}">${z.undo}</button>`:``}
373
+ <button class="todo-act" data-action="edit-title" data-id="${k(e.id)}" title="${k(t(`todo.editItem`))}" aria-label="${k(t(`todo.editItem`))}">${z.edit}</button>
374
+ <button class="todo-act" data-action="copy-item" data-id="${k(e.id)}" title="${k(t(`todo.copyItem`))}" aria-label="${k(t(`todo.copyItem`))}">${z.copy}</button>
375
+ <button class="todo-act" data-action="fill-item" data-id="${k(e.id)}" title="${k(t(`todo.fillInput`))}" aria-label="${k(t(`todo.fillInput`))}">${z.fill}</button>
376
+ <button class="todo-act" data-action="row-more" data-id="${k(e.id)}" title="${k(t(`todo.more`))}" aria-label="${k(t(`todo.more`))}">${z.more}</button>
377
377
  </div>`;return`<div class="${a.join(` `)}" data-id="${k(e.id)}" data-group="${n}"${f} tabindex="0" data-priority="${k(e.priority||``)}">
378
- ${Ou(e)}
378
+ ${ku(e)}
379
379
  <div class="todo-main">
380
380
  ${s}
381
- ${ju(e)}
381
+ ${Mu(e)}
382
382
  ${l}
383
383
  ${d}
384
- ${Au(e)}
384
+ ${ju(e)}
385
385
  </div>
386
386
  ${p?``:m}
387
- </div>`}function Nu(){let e=U.querySelector(`.todo-edit-input[data-id="${Hl}"]`);e&&(e.focus(),e.selectionStart=e.selectionEnd=e.value.length)}function Pu(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&&j(n,`success`);return}j(t(e&&e.reason===`invalid`?`todo.linkInvalid`:`todo.saveFailed`),`error`)})}function Fu(e){let n=e&&e.link;if(!n||!Ee(n)){j(t(`todo.linkInvalid`),`error`);return}try{chrome.tabs.create({url:n})}catch(e){r.warn(`[Todo] open link failed:`,e),j(t(`todo.copyFailed`),`error`)}}function Iu(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(),cu();return;case`fill-item`:e.stopPropagation(),Dd(r);return;case`copy-item`:e.stopPropagation(),Od(r);return;case`header-more`:e.stopPropagation(),bd(t);return;case`toggle-fullscreen`:e.stopPropagation(),lu(!eu);return;case`add`:e.stopPropagation(),od();return;case`switch-tab`:Ru(t.dataset.tab);return;case`undo-complete`:e.stopPropagation(),Vu(r);return;case`restore`:e.stopPropagation(),Bu(r);return;case`open-link`:e.stopPropagation(),Fu(Lu(r));return;case`clear-completed-btn`:e.stopPropagation(),Hu();return;case`cycle`:e.stopPropagation(),J(Tc(r));return;case`toggle-note`:e.stopPropagation(),Wl.has(r)?Wl.delete(r):Wl.add(r),q();return;case`edit-title`:e.stopPropagation(),$u(r);return;case`row-more`:e.stopPropagation(),yd(t,r);return;case`note-save`:e.stopPropagation(),cd(r);return;case`note-cancel`:e.stopPropagation(),W=null,K(r),q();return;case`due-clear`:e.stopPropagation(),Ul=null,K(r),J(Cc(r,{dueAt:null}));return;case`link-cancel`:e.stopPropagation(),ud(r);return;default:return}}function Lu(e){let{active:t,done:n}=yc();return[...t,...n].find(t=>t.id===e)||null}function Ru(e){let t=e===`done`?`done`:`active`;t!==Vl&&(Vl=t,dd(),q())}function zu(e){let t=Lu(e);t&&(wu(t),J(wc(e,O.DONE)))}function Bu(e){let n=Lu(e);if(!n)return;let r=He(n);Tu(),J(Ec(e),t(`todo.restoredToast`,{status:Du(r)}))}function Vu(e){Bu(e)}async function Hu(){let{done:e}=yc();e.length!==0&&await fd(t(`todo.clearCompletedConfirmMsg`,{n:e.length}),t(`todo.clearCompletedConfirmTitle`))&&J(jc(),t(`todo.clearedToast`))}function Uu(e){if((e.key===`ArrowUp`||e.key===`ArrowDown`)&&!e.target.closest?.(`input, textarea, [contenteditable="true"]`)&&e.target.closest?.(`.todo-item`)){e.preventDefault(),Yu(e.key===`ArrowDown`?1:-1);return}if(e.target===Pl){e.key===`Enter`?(e.preventDefault(),od()):e.key===`Escape`&&(e.stopPropagation(),Pl.value=``,au()&&cu());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(Hl=null,!n){K(t),q();return}K(t),J(Cc(t,{title:n}))}else e.key===`Escape`&&(e.stopPropagation(),Hl=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(),cd(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(),ld(t,e.target.value)):e.key===`Escape`&&(e.stopPropagation(),ud(t))}}var Wu={KeyT:()=>ou(),KeyA:()=>Zu(),KeyB:e=>Qu(e),KeyL:e=>td(e),KeyD:e=>nd(e),KeyP:e=>rd(e)},Gu=new Set([`KeyT`,`KeyA`]);function Ku(e){if(!e.altKey||e.shiftKey||e.ctrlKey||e.metaKey)return;let t=Wu[e.code];if(!t)return;if(Gu.has(e.code)){e.preventDefault(),t();return}let n=Ju();n&&(e.preventDefault(),t(n))}function qu(){return U?Array.from(U.querySelectorAll(`.todo-item`)):[]}function Ju(){if(!au())return null;let e=document.activeElement?.closest?.(`.todo-item`);if(e?.dataset.id&&U.contains(e))return e.dataset.id;let t=qu();return Yl&&t.some(e=>e.dataset.id===Yl)?Yl:t[0]?.dataset.id||null}function Yu(e){let t=qu();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 Xu(e){let t=qu().find(t=>t.dataset.id===e);t&&t.focus()}function Zu(){if(au()){Pl.focus();return}su()}function Qu(e){W=e,Wl.add(e),$l=!0,q()}function $u(e){dd(),Hl=e,$l=!0,q()}function ed(e){let t=e.target.closest?.(`.todo-name`);if(t){let n=t.closest(`.todo-item`)?.dataset.id;if(!n)return;e.preventDefault(),$u(n);return}let n=e.target.closest?.(`.todo-note`);if(n){let t=n.closest(`.todo-item`)?.dataset.id;if(!t)return;e.preventDefault(),Qu(t)}}function td(e){G=e,$l=!0,q()}function nd(e){let t=Lu(e);t&&(t.status===O.DONE?Bu(e):zu(e))}function rd(e){let t=Lu(e);t&&J(Dc(e,Se(t.priority)))}function id(e){if(e.target.classList?.contains(`todo-link-input`)){let t=e.target.dataset.id;if(!G||G!==t)return;ld(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(Ul=null,K(t),!n){J(Cc(t,{dueAt:null}));return}let r=new Date(n+`T00:00:00`);J(Cc(t,{dueAt:isNaN(r.getTime())?null:r.getTime()}))}function ad(e){if(e.target?.classList?.contains(`todo-link-input`)){let t=e.target.dataset.id;if(!G||G!==t)return;ld(t,e.target.value);return}if(e.target?.classList?.contains(`todo-note-input`)){let t=e.target.dataset.id;if(!W||W!==t)return;cd(t);return}if(!e.target?.classList?.contains(`todo-edit-input`))return;let n=e.target.dataset.id;if(!Hl||Hl!==n)return;let r=e.target.value.trim();if(Hl=null,!r){K(n),q();return}K(n),Cc(n,{title:r}).then(e=>{e?q():j(t(`todo.saveFailed`),`error`)})}async function od(){let e=Pl.value.trim();if(!e)return;Pl.value=``,Vl===`done`&&(Vl=`active`);let n=await Sc(e);n?requestAnimationFrame(()=>sd(n.id)):j(t(`todo.saveFailed`),`error`),Pl.focus()}function sd(e){let t=qu().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(Ql),Ql=setTimeout(()=>t.classList.remove(`just-added`),1600)}function cd(e){if(W!==e)return;let t=U.querySelector(`.todo-note-input[data-id="${k(e)}"]`),n=t?t.value:``;W=null,Wl.delete(e),K(e),J(Cc(e,{note:n}))}function ld(e,n){let r=!!Lu(e)?.link;G=null,K(e);let i=String(n||``).trim();J(Oc(e,i),t(i?`todo.linkSavedToast`:r?`todo.linkRemovedToast`:`todo.linkSavedToast`))}function ud(e){G=null,K(e),q()}function dd(){let e=Hl||W||Ul||G;Hl=null,W=null,Ul=null,G=null,$l=!1,K(),e&&q()}async function fd(e,t){return typeof window<`u`&&typeof window.showCustomConfirm==`function`?!!await window.showCustomConfirm(e,t):!1}function pd(){return Ll||(Ll=document.createElement(`div`),Ll.className=`todo-menu`,document.body.appendChild(Ll),Ll.addEventListener(`click`,e=>{let t=e.target.closest(`[data-priority-value]`);if(t){let e=t.dataset.menuId,n=t.dataset.priorityValue||null;md(),J(Dc(e,n));return}let n=e.target.closest(`[data-menu-action]`);if(!n)return;let{menuAction:r,menuId:i}=n.dataset;md(),Td(r,i)}),Ll)}function md(){Ll&&=(Ll.remove(),null)}function hd(e){return e?`<kbd class="todo-menu-kbd">${A(e)}</kbd>`:``}function gd(e,n){if(e.swatches){let r=[[``,t(`todo.priorityNone`)],[ze.LOW,t(`todo.priorityLow`)],[ze.MEDIUM,t(`todo.priorityMedium`)],[ze.HIGH,t(`todo.priorityHigh`)]];return`<div class="todo-menu-row">
387
+ </div>`}function Pu(){let e=H.querySelector(`.todo-edit-input[data-id="${Ul}"]`);e&&(e.focus(),e.selectionStart=e.selectionEnd=e.value.length)}function Fu(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&&j(n,`success`);return}j(t(e&&e.reason===`invalid`?`todo.linkInvalid`:`todo.saveFailed`),`error`)})}function Iu(e){let n=e&&e.link;if(!n||!Ee(n)){j(t(`todo.linkInvalid`),`error`);return}try{chrome.tabs.create({url:n})}catch(e){r.warn(`[Todo] open link failed:`,e),j(t(`todo.copyFailed`),`error`)}}function Lu(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(),lu();return;case`fill-item`:e.stopPropagation(),Od(r);return;case`copy-item`:e.stopPropagation(),kd(r);return;case`header-more`:e.stopPropagation(),xd(t);return;case`toggle-fullscreen`:e.stopPropagation(),uu(!tu);return;case`add`:e.stopPropagation(),sd();return;case`switch-tab`:zu(t.dataset.tab);return;case`undo-complete`:e.stopPropagation(),Hu(r);return;case`restore`:e.stopPropagation(),Vu(r);return;case`open-link`:e.stopPropagation(),Iu(Ru(r));return;case`clear-completed-btn`:e.stopPropagation(),Uu();return;case`cycle`:e.stopPropagation(),q(Ec(r));return;case`toggle-note`:e.stopPropagation(),Gl.has(r)?Gl.delete(r):Gl.add(r),K();return;case`edit-title`:e.stopPropagation(),ed(r);return;case`row-more`:e.stopPropagation(),bd(t,r);return;case`note-save`:e.stopPropagation(),ld(r);return;case`note-cancel`:e.stopPropagation(),U=null,G(r),K();return;case`due-clear`:e.stopPropagation(),Wl=null,G(r),q(wc(r,{dueAt:null}));return;case`link-cancel`:e.stopPropagation(),dd(r);return;default:return}}function Ru(e){let{active:t,done:n}=bc();return[...t,...n].find(t=>t.id===e)||null}function zu(e){let t=e===`done`?`done`:`active`;t!==Hl&&(Hl=t,fd(),K())}function Bu(e){let t=Ru(e);t&&(Tu(t),q(Tc(e,O.DONE)))}function Vu(e){let n=Ru(e);if(!n)return;let r=He(n);Eu(),q(Dc(e),t(`todo.restoredToast`,{status:Ou(r)}))}function Hu(e){Vu(e)}async function Uu(){let{done:e}=bc();e.length!==0&&await pd(t(`todo.clearCompletedConfirmMsg`,{n:e.length}),t(`todo.clearCompletedConfirmTitle`))&&q(Mc(),t(`todo.clearedToast`))}function Wu(e){if((e.key===`ArrowUp`||e.key===`ArrowDown`)&&!e.target.closest?.(`input, textarea, [contenteditable="true"]`)&&e.target.closest?.(`.todo-item`)){e.preventDefault(),Xu(e.key===`ArrowDown`?1:-1);return}if(e.target===Fl){e.key===`Enter`?(e.preventDefault(),sd()):e.key===`Escape`&&(e.stopPropagation(),Fl.value=``,ou()&&lu());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(Ul=null,!n){G(t),K();return}G(t),q(wc(t,{title:n}))}else e.key===`Escape`&&(e.stopPropagation(),Ul=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(),ld(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(),ud(t,e.target.value)):e.key===`Escape`&&(e.stopPropagation(),dd(t))}}var Gu={KeyT:()=>su(),KeyA:()=>Qu(),KeyB:e=>$u(e),KeyL:e=>nd(e),KeyD:e=>rd(e),KeyP:e=>id(e)},Ku=new Set([`KeyT`,`KeyA`]);function qu(e){if(!e.altKey||e.shiftKey||e.ctrlKey||e.metaKey)return;let t=Gu[e.code];if(!t)return;if(Ku.has(e.code)){e.preventDefault(),t();return}let n=Yu();n&&(e.preventDefault(),t(n))}function Ju(){return H?Array.from(H.querySelectorAll(`.todo-item`)):[]}function Yu(){if(!ou())return null;let e=document.activeElement?.closest?.(`.todo-item`);if(e?.dataset.id&&H.contains(e))return e.dataset.id;let t=Ju();return Xl&&t.some(e=>e.dataset.id===Xl)?Xl:t[0]?.dataset.id||null}function Xu(e){let t=Ju();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 Zu(e){let t=Ju().find(t=>t.dataset.id===e);t&&t.focus()}function Qu(){if(ou()){Fl.focus();return}cu()}function $u(e){U=e,Gl.add(e),eu=!0,K()}function ed(e){fd(),Ul=e,eu=!0,K()}function td(e){let t=e.target.closest?.(`.todo-name`);if(t){let n=t.closest(`.todo-item`)?.dataset.id;if(!n)return;e.preventDefault(),ed(n);return}let n=e.target.closest?.(`.todo-note`);if(n){let t=n.closest(`.todo-item`)?.dataset.id;if(!t)return;e.preventDefault(),$u(t)}}function nd(e){W=e,eu=!0,K()}function rd(e){let t=Ru(e);t&&(t.status===O.DONE?Vu(e):Bu(e))}function id(e){let t=Ru(e);t&&q(Oc(e,Se(t.priority)))}function ad(e){if(e.target.classList?.contains(`todo-link-input`)){let t=e.target.dataset.id;if(!W||W!==t)return;ud(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(Wl=null,G(t),!n){q(wc(t,{dueAt:null}));return}let r=new Date(n+`T00:00:00`);q(wc(t,{dueAt:isNaN(r.getTime())?null:r.getTime()}))}function od(e){if(e.target?.classList?.contains(`todo-link-input`)){let t=e.target.dataset.id;if(!W||W!==t)return;ud(t,e.target.value);return}if(e.target?.classList?.contains(`todo-note-input`)){let t=e.target.dataset.id;if(!U||U!==t)return;ld(t);return}if(!e.target?.classList?.contains(`todo-edit-input`))return;let n=e.target.dataset.id;if(!Ul||Ul!==n)return;let r=e.target.value.trim();if(Ul=null,!r){G(n),K();return}G(n),wc(n,{title:r}).then(e=>{e?K():j(t(`todo.saveFailed`),`error`)})}async function sd(){let e=Fl.value.trim();if(!e)return;Fl.value=``,Hl===`done`&&(Hl=`active`);let n=await Cc(e);n?requestAnimationFrame(()=>cd(n.id)):j(t(`todo.saveFailed`),`error`),Fl.focus()}function cd(e){let t=Ju().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($l),$l=setTimeout(()=>t.classList.remove(`just-added`),1600)}function ld(e){if(U!==e)return;let t=H.querySelector(`.todo-note-input[data-id="${k(e)}"]`),n=t?t.value:``;U=null,Gl.delete(e),G(e),q(wc(e,{note:n}))}function ud(e,n){let r=!!Ru(e)?.link;W=null,G(e);let i=String(n||``).trim();q(kc(e,i),t(i?`todo.linkSavedToast`:r?`todo.linkRemovedToast`:`todo.linkSavedToast`))}function dd(e){W=null,G(e),K()}function fd(){let e=Ul||U||Wl||W;Ul=null,U=null,Wl=null,W=null,eu=!1,G(),e&&K()}async function pd(e,t){return typeof window<`u`&&typeof window.showCustomConfirm==`function`?!!await window.showCustomConfirm(e,t):!1}function md(){return Rl||(Rl=document.createElement(`div`),Rl.className=`todo-menu`,document.body.appendChild(Rl),Rl.addEventListener(`click`,e=>{let t=e.target.closest(`[data-priority-value]`);if(t){let e=t.dataset.menuId,n=t.dataset.priorityValue||null;hd(),q(Oc(e,n));return}let n=e.target.closest(`[data-menu-action]`);if(!n)return;let{menuAction:r,menuId:i}=n.dataset;hd(),Ed(r,i)}),Rl)}function hd(){Rl&&=(Rl.remove(),null)}function gd(e){return e?`<kbd class="todo-menu-kbd">${A(e)}</kbd>`:``}function _d(e,n){if(e.swatches){let r=[[``,t(`todo.priorityNone`)],[ze.LOW,t(`todo.priorityLow`)],[ze.MEDIUM,t(`todo.priorityMedium`)],[ze.HIGH,t(`todo.priorityHigh`)]];return`<div class="todo-menu-row">
388
388
  <span class="todo-menu-row-label">${A(e.label)}</span>
389
389
  ${r.map(([r,i])=>`
390
390
  <button type="button" class="todo-swatch${r?` ${r}`:``}${e.current===r?` active`:``}"
391
391
  data-priority-value="${k(r)}" data-menu-id="${k(n)}"
392
392
  title="${k(t(`todo.priorityTitle`,{level:i}))}"
393
393
  aria-label="${k(i)}"></button>`).join(``)}
394
- ${hd(e.shortcut)}
394
+ ${gd(e.shortcut)}
395
395
  </div>`}return`${e.divider?`<div class="todo-menu-sep"></div>`:``}<button type="button" data-menu-action="${k(e.action)}" data-menu-id="${k(n||``)}"
396
396
  class="todo-menu-item${e.danger?` danger`:``}">
397
- ${e.icon||``}<span>${A(e.label)}</span>${hd(e.shortcut)}
398
- </button>`}function _d(e,t,n){let r=pd();r.innerHTML=t.map((e,t)=>t===0&&e.divider?{...e,divider:!1}:e).map(e=>gd(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 vd(e){if(e.status===O.DONE){let n=He(e),r=[{action:`restore`,label:t(`todo.restoreTo`,{status:Du(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 yd(e,n){let r=Lu(n);r&&_d(e,[...vd(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 bd(e){let t=xd();t.length!==0&&_d(e,t,``)}function xd(){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 Sd(){let{active:e,done:t}=yc(),n=await cl({counts:{all:e.length+t.length,active:e.length,done:t.length}});n&&Cd(n.scope,n.format)}function Cd(e,n){let{active:i,done:a}=yc(),o=[...i,...a];if(xe(o,e).length===0){j(t(`todo.exportEmptyToast`),`info`);return}try{j(t(`todo.exportedToast`,{name:Vc(o,{scope:e,format:n})}),`success`)}catch(e){r.error(`[Todo] export failed:`,e),j(t(`todo.exportFailedToast`),`error`)}}async function wd(){let e=await Hc();if(!e)return;let n=await Uc(e);if(!n.ok){j(t(n.reason===`json`?`todo.importJsonError`:`todo.importFormatError`),`error`);return}let{active:r,done:i}=yc(),a=await ll({count:n.todos.length,existing:r.length+i.length});if(!a)return;Vl=`active`,q();let o=await Mc(n.todos,a);if(!o.ok){j(t(o.reason===`empty`?`todo.importEmptyToast`:`todo.importFailedToast`),`error`);return}if(o.added===0){j(t(`todo.importNothingNewToast`,{skipped:o.skipped}),`info`);return}j(t(`todo.importedToast`,{added:o.added,skipped:o.skipped}),`success`)}async function Td(e,n){let r=Lu(n);switch(e){case`set-doing`:J(wc(n,O.DOING));return;case`set-pending`:J(wc(n,O.PENDING));return;case`set-done`:zu(n);return;case`restore`:Bu(n);return;case`edit-title`:$u(n);return;case`edit-note`:Qu(n);return;case`set-due`:Ul=n,$l=!0,q();return;case`edit-link`:td(n);return;case`stats`:wl();return;case`export-options`:Sd();return;case`import-options`:wd();return;case`delete`:await fd(t(`todo.deleteConfirmMsg`,{title:r?.title||``}),t(`todo.deleteConfirmTitle`))&&J(kc(n),t(`todo.deletedToast`));return;default:}}function Ed(e,t={}){let{active:n,done:r}=yc(),i=[...n,...r].find(t=>t.id===e);return i?Le(i,t):``}function Dd(e){let n=Ed(e);if(!n){j(t(`todo.emptyDigestToast`),`info`);return}let r=document.getElementById(`userInput`);if(!r){j(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,Ze(),cu(),j(t(`todo.filledToast`),`success`)}function Od(e){let n=Ed(e,{plain:!0});if(!n){j(t(`todo.emptyDigestToast`),`info`);return}kd(n,t(`todo.copiedToast`))}function kd(e,n){try{navigator.clipboard.writeText(e).then(()=>{j(n,`success`)}).catch(e=>{r.warn(`[Todo] copy failed:`,e),j(t(`todo.copyFailed`),`error`)})}catch(e){r.warn(`[Todo] clipboard unavailable:`,e),j(t(`todo.copyFailed`),`error`)}}function Ad(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`));Gl={id:t.dataset.id,from:r.indexOf(t),list:n},t.classList.add(`dragging`);let{active:i,done:a}=yc(),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 jd(e){if(!Gl)return;e.preventDefault();let t=Gl.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=Md();r>=n.length?t.appendChild(i):n[r].before(i)}function Md(){let e=U.querySelector(`.todo-insert`);return e||(e=document.createElement(`div`),e.className=`todo-insert`,e)}function Nd(e){if(!Gl)return;e.preventDefault();let t=Gl.list,n=U.querySelector(`.todo-insert`),r=Gl.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=Gl.from;Pd(),i!==r&&J(Ac(i,r))}function Pd(){Gl=null,U?.querySelectorAll(`.todo-item.dragging`).forEach(e=>e.classList.remove(`dragging`)),U?.querySelector(`.todo-insert`)?.remove()}var Fd=`—`,Id=[{labelKey:`versionInfo.website`,url:`https://xiweicheng.github.io/ai-helper/`,icon:`<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 17.93c-3.95-.49-7-3.85-7-7.93 0-.62.08-1.21.21-1.79L9 15v1c0 1.1.9 2 2 2v1.93zm6.9-2.54c-.26-.81-1-1.39-1.9-1.39h-1v-3c0-.55-.45-1-1-1H8v-2h2c.55 0 1-.45 1-1V7h2c1.1 0 2-.9 2-2v-.41c2.93 1.19 5 4.06 5 7.41 0 2.08-.8 3.97-2.1 5.39z"/></svg>`},{labelKey:`versionInfo.discussions`,url:`https://github.com/xiweicheng/ai-helper/discussions`,icon:`<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2z"/></svg>`},{labelKey:`versionInfo.reportIssue`,url:`https://github.com/xiweicheng/ai-helper/issues/new`,icon:`<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M20 8h-2.81c-.45-.78-1.07-1.45-1.82-1.96L17 4.41 15.59 3l-2.17 2.17C12.96 5.06 12.49 5 12 5c-.49 0-.96.06-1.41.17L8.41 3 7 4.41l1.62 1.63C7.88 6.55 7.26 7.22 6.81 8H4v2h2.09c-.05.33-.09.66-.09 1v1H4v2h2v1c0 .34.04.67.09 1H4v2h2.81c1.04 1.79 2.97 3 5.19 3s4.15-1.21 5.19-3H20v-2h-2.09c.05-.33.09-.66.09-1v-1h2v-2h-2v-1c0-.34-.04-.67-.09-1H20V8zm-6 8h-4v-2h4v2zm0-4h-4v-2h4v2z"/></svg>`},{labelKey:`versionInfo.githubRepo`,url:`https://github.com/xiweicheng/ai-helper`,icon:`<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M12 .5C5.73.5.5 5.73.5 12c0 5.08 3.29 9.39 7.86 10.91.58.11.79-.25.79-.56 0-.28-.01-1.02-.02-2-3.2.7-3.88-1.54-3.88-1.54-.52-1.33-1.28-1.69-1.28-1.69-1.04-.71.08-.7.08-.7 1.15.08 1.76 1.19 1.76 1.19 1.03 1.76 2.7 1.25 3.36.96.1-.75.4-1.25.72-1.54-2.55-.29-5.24-1.28-5.24-5.68 0-1.26.45-2.28 1.19-3.09-.12-.29-.52-1.46.11-3.05 0 0 .97-.31 3.18 1.18a11.1 11.1 0 012.9-.39c.98 0 1.97.13 2.9.39 2.2-1.49 3.17-1.18 3.17-1.18.63 1.59.23 2.76.11 3.05.74.81 1.19 1.83 1.19 3.09 0 4.41-2.69 5.38-5.25 5.67.41.35.78 1.05.78 2.12 0 1.53-.01 2.76-.01 3.14 0 .31.21.68.8.56A11.51 11.51 0 0023.5 12C23.5 5.73 18.27.5 12 .5z"/></svg>`},{labelKey:`versionInfo.giteeRepo`,url:`https://gitee.com/xiweicheng/ai-helper`,icon:`<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M11.984 0A12 12 0 000 12a12 12 0 0012 12 12 12 0 0012-12A12 12 0 0012 0zm6.09 5.333c.328 0 .593.266.592.593v1.482a.594.594 0 01-.593.592H9.777c-.982 0-1.778.796-1.778 1.778v5.63c0 .327.266.592.593.592h5.63c.982 0 1.778-.796 1.778-1.778v-.296a.593.593 0 00-.592-.593h-4.15a.592.592 0 01-.592-.592v-1.482a.593.593 0 01.593-.592h6.815c.327 0 .593.265.593.592v3.408a4 4 0 01-4 4H8.444a3.556 3.556 0 01-3.555-3.556V8.89a3.556 3.556 0 013.555-3.556h9.63z"/></svg>`}];function Ld(e){let t=e=>typeof e==`string`?e.trim():``,n=e&&typeof e==`object`?e:{};return{version:t(n.version),tag:t(n.tag),commitId:t(n.commitId),publishedAt:t(n.publishedAt)}}function Rd(e){if(!e)return Fd;let t=Date.parse(e);return Number.isNaN(t)?Fd:new Date(t).toLocaleString()}function zd(e){let n=Ld(lt),r=[{label:t(`versionInfo.version`),value:n.version?`v${n.version}`:Fd},{label:t(`versionInfo.tag`),value:n.tag||Fd},{label:t(`versionInfo.commit`),value:n.commitId?n.commitId.slice(0,8):Fd,title:n.commitId,mono:!0},{label:t(`versionInfo.publishedAt`),value:Rd(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 Bd(e){e.textContent=``;for(let n of Id){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 Vd(){let e=Ld(lt);return[`AI Helper v${e.version||Fd}`,`${t(`versionInfo.tag`)}: ${e.tag||Fd}`,`${t(`versionInfo.commit`)}: ${e.commitId||Fd}`,`${t(`versionInfo.publishedAt`)}: ${Rd(e.publishedAt)}`].join(`
399
- `)}function Hd(){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`),zd(a),o&&Bd(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(Vd()),j(t(`common.copySuccess`),`success`)}catch{j(t(`common.copyFailed`),`error`)}})}var Ud=null;function Wd(){if(!Ud)return;Ud.classList.remove(`open`);let e=Ud.parentElement?Ud.parentElement.querySelector(`.section-select-row`):null;e&&e.classList.remove(`open`),Ud=null}function Gd(){return`<input type="search" class="section-select-search" placeholder="${t(`sectionSelect.searchPlaceholder`)}" data-i18n-placeholder="sectionSelect.searchPlaceholder" spellcheck="false">`}function Kd(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 qd(e,t){Wd(),e.classList.add(`open`),t.classList.add(`open`),Ud=e;let n=e.querySelector(`.section-select-search`);n&&(n.value=``,Kd(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===Ud?Wd():qd(e,t);return}Ud&&!Ud.parentElement.contains(e.target)&&Wd()}),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&&Kd(n,t.value)});var Jd=!1;async function Yd(){document.getElementById(`providerList`)&&(Jd||(Jd=!0,Qd(),$d()),await Xd())}async function Xd(){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=Gd();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(),Wd(),Zd(t.id)}),e.appendChild(r)}}async function Zd(e){if(e===(await x()).activeProfileId)return;let t=await ae(e);t&&(await Xd(),r.debug(`[SidePanel] provider switched:`,t.name))}function Qd(){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 $d(){chrome.storage.onChanged.addListener((e,t)=>{t===`local`&&(e.modelProfiles||e.activeProfileId)&&Xd()})}var ef=0;function tf(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 nf(e){let t=[];return e.querySelectorAll(`*`).forEach(e=>{getComputedStyle(e).position===`absolute`&&e.getClientRects().length>0&&t.push(e)}),t}function rf(e){e.forEach(e=>{(e.getAnimations?.()||[]).forEach(e=>{e.playState!==`idle`&&e.finish?.()})})}function af(){ef||=requestAnimationFrame(()=>{ef=0,cf()})}function of(){let e=document.getElementById(`selectionToggleGroup`),t=document.getElementById(`inputAddMenuSwitches`);e&&t&&e.parentElement!==t&&t.appendChild(e)}function sf(){let e=document.getElementById(`selectionToggleGroup`),t=document.querySelector(`.input-bottom-left`);e&&t&&e.parentElement!==t&&t.appendChild(e)}function cf(){let e=document.querySelector(`.input-bottom-row`),t=e?.closest(`.input-container`)||null;if(!(!e||!t)){t.classList.add(`measuring`);try{lf(e,t)}finally{t.classList.remove(`measuring`)}}}function lf(e,t){t.classList.remove(`temp-collapsed`,`agent-collapsed`,`switches-icon`,`selection-in-menu`),sf();let n=nf(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]}),rf(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`),of(),i()}function uf(){cf(),window.addEventListener(`resize`,af);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,af())}).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=>!tf(t.target,e)&&!r(t))&&af()}).observe(e,{subtree:!0,childList:!0,characterData:!0})}var df=`footer-compact`,ff=`footer-compact-ultra`,pf=`footer-wrap`,mf=`footer-measuring`,hf=0;function gf(){hf||=requestAnimationFrame(()=>{hf=0,vf()})}function _f(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 vf(){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(mf),e.classList.remove(df,ff,pf)});try{let e=[...t].filter(e=>e.clientWidth>0&&e.scrollWidth>e.clientWidth);e.forEach(e=>e.classList.add(df)),e=e.filter(e=>e.scrollWidth>e.clientWidth),e.forEach(e=>e.classList.add(ff)),e=e.filter(e=>e.scrollWidth>e.clientWidth),e.forEach(e=>e.classList.add(pf))}finally{t.forEach(e=>e.classList.remove(mf))}}}function yf(){let e=document.getElementById(`chatContainer`);if(e){if(vf(),window.addEventListener(`resize`,gf),typeof ResizeObserver<`u`){let t=e.clientWidth;new ResizeObserver(()=>{let n=e.clientWidth;Math.abs(n-t)<1||(t=n,gf())}).observe(e)}typeof MutationObserver<`u`&&new MutationObserver(e=>{e.some(_f)&&gf()}).observe(e,{subtree:!0,childList:!0}),document.fonts?.ready?.then(gf).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 bf=50,xf=200,Sf=200,Cf=0,wf=null,Tf=[];function Ef(e){return(e||``).replace(/\\/g,`/`).replace(/\/+/g,`/`)}function Df(e){let t=document.getElementById(`fileAtTitlePath`);if(!t)return;let n=e?Ef(e):``;t.textContent=n,t.title=n}async function Of(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(),kf(),await Mr()})),ct(),t.style.display=`block`,n.classList.add(`show`),await Af(e)}function kf(){let e=document.getElementById(`fileAtSelector`),t=document.getElementById(`fileAtDropdown`);e&&(e.style.display=`none`),t&&t.classList.remove(`show`),y.selectedFileAtIndex=-1,wf&&=(clearTimeout(wf),null),Cf++}function Af(e=``){let n=document.getElementById(`fileAtList`);if(!n)return;let i=++Cf,a=e.trim();wf&&clearTimeout(wf);let o=async()=>{try{let e=await va();if(i!==Cf)return;if(Df(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,xf):((await ha(e)).entries||[]).map(t=>({name:t.name,type:t.type||`file`,size:t.size,mtime:t.mtime,fullPath:Ef(`${e}/${t.name}`)})),i!==Cf)return;Mf(r,a,n,e)}catch(e){if(i!==Cf)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>`,wf=setTimeout(o,Sf)):wf=setTimeout(o,0)}function jf(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 Mf(e,n,r,i){let a=jf(e,n),o=a.slice(0,bf),s=a.length>bf,c=Ef(i);if(o.length===0){r.innerHTML=`<div class="prompt-empty">${t(`fileSelector.noMatch`)}</div>`,y.selectedFileAtIndex=-1;return}if(y.selectedFileAtIndex=0,Tf=o,r.innerHTML=o.map((e,t)=>{let n=_a(e.name,e.type),r=Ef(e.fullPath),i=r.startsWith(c)?r.substring(c.length).replace(/^\//,``):r;return`
397
+ ${e.icon||``}<span>${A(e.label)}</span>${gd(e.shortcut)}
398
+ </button>`}function vd(e,t,n){let r=md();r.innerHTML=t.map((e,t)=>t===0&&e.divider?{...e,divider:!1}:e).map(e=>_d(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 yd(e){if(e.status===O.DONE){let n=He(e),r=[{action:`restore`,label:t(`todo.restoreTo`,{status:Ou(n)}),icon:z.undo,shortcut:`Alt+D`,divider:!0}];return n!==O.PENDING&&r.push({action:`set-pending`,label:t(`todo.backToPending`),icon:z.circle}),r}return e.status===O.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 bd(e,n){let r=Ru(n);r&&vd(e,[...yd(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 xd(e){let t=Sd();t.length!==0&&vd(e,t,``)}function Sd(){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 Cd(){let{active:e,done:t}=bc(),n=await ll({counts:{all:e.length+t.length,active:e.length,done:t.length}});n&&wd(n.scope,n.format)}function wd(e,n){let{active:i,done:a}=bc(),o=[...i,...a];if(xe(o,e).length===0){j(t(`todo.exportEmptyToast`),`info`);return}try{j(t(`todo.exportedToast`,{name:Hc(o,{scope:e,format:n})}),`success`)}catch(e){r.error(`[Todo] export failed:`,e),j(t(`todo.exportFailedToast`),`error`)}}async function Td(){let e=await Uc();if(!e)return;let n=await Wc(e);if(!n.ok){j(t(n.reason===`json`?`todo.importJsonError`:`todo.importFormatError`),`error`);return}let{active:r,done:i}=bc(),a=await ul({count:n.todos.length,existing:r.length+i.length});if(!a)return;Hl=`active`,K();let o=await Nc(n.todos,a);if(!o.ok){j(t(o.reason===`empty`?`todo.importEmptyToast`:`todo.importFailedToast`),`error`);return}if(o.added===0){j(t(`todo.importNothingNewToast`,{skipped:o.skipped}),`info`);return}j(t(`todo.importedToast`,{added:o.added,skipped:o.skipped}),`success`)}async function Ed(e,n){let r=Ru(n);switch(e){case`set-doing`:q(Tc(n,O.DOING));return;case`set-pending`:q(Tc(n,O.PENDING));return;case`set-done`:Bu(n);return;case`restore`:Vu(n);return;case`edit-title`:ed(n);return;case`edit-note`:$u(n);return;case`set-due`:Wl=n,eu=!0,K();return;case`edit-link`:nd(n);return;case`stats`:Tl();return;case`export-options`:Cd();return;case`import-options`:Td();return;case`delete`:await pd(t(`todo.deleteConfirmMsg`,{title:r?.title||``}),t(`todo.deleteConfirmTitle`))&&q(Ac(n),t(`todo.deletedToast`));return;default:}}function Dd(e,t={}){let{active:n,done:r}=bc(),i=[...n,...r].find(t=>t.id===e);return i?Le(i,t):``}function Od(e){let n=Dd(e);if(!n){j(t(`todo.emptyDigestToast`),`info`);return}let r=document.getElementById(`userInput`);if(!r){j(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,Ze(),lu(),j(t(`todo.filledToast`),`success`)}function kd(e){let n=Dd(e,{plain:!0});if(!n){j(t(`todo.emptyDigestToast`),`info`);return}Ad(n,t(`todo.copiedToast`))}function Ad(e,n){try{navigator.clipboard.writeText(e).then(()=>{j(n,`success`)}).catch(e=>{r.warn(`[Todo] copy failed:`,e),j(t(`todo.copyFailed`),`error`)})}catch(e){r.warn(`[Todo] clipboard unavailable:`,e),j(t(`todo.copyFailed`),`error`)}}function jd(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`));Kl={id:t.dataset.id,from:r.indexOf(t),list:n},t.classList.add(`dragging`);let{active:i,done:a}=bc(),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 Md(e){if(!Kl)return;e.preventDefault();let t=Kl.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=Nd();r>=n.length?t.appendChild(i):n[r].before(i)}function Nd(){let e=H.querySelector(`.todo-insert`);return e||(e=document.createElement(`div`),e.className=`todo-insert`,e)}function Pd(e){if(!Kl)return;e.preventDefault();let t=Kl.list,n=H.querySelector(`.todo-insert`),r=Kl.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=Kl.from;Fd(),i!==r&&q(jc(i,r))}function Fd(){Kl=null,H?.querySelectorAll(`.todo-item.dragging`).forEach(e=>e.classList.remove(`dragging`)),H?.querySelector(`.todo-insert`)?.remove()}var Id=`—`,Ld=[{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 Rd(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 zd(e){if(!e)return Id;let t=Date.parse(e);return Number.isNaN(t)?Id:new Date(t).toLocaleString()}function Bd(e){let n=Rd(lt),r=[{label:t(`versionInfo.version`),value:n.version?`v${n.version}`:Id},{label:t(`versionInfo.tag`),value:n.tag||Id},{label:t(`versionInfo.commit`),value:n.commitId?n.commitId.slice(0,8):Id,title:n.commitId,mono:!0},{label:t(`versionInfo.publishedAt`),value:zd(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 Vd(e){e.textContent=``;for(let n of Ld){let r=document.createElement(`div`);r.className=`version-info-link`,r.title=n.url;let i=document.createElement(`span`);i.className=`version-info-link-icon`,i.innerHTML=n.icon;let a=document.createElement(`span`);a.className=`version-info-link-label`,a.textContent=t(n.labelKey);let o=document.createElement(`span`);o.className=`version-info-link-arrow`,o.textContent=`↗`,r.appendChild(i),r.appendChild(a),r.appendChild(o),r.addEventListener(`click`,()=>{chrome.tabs.create({url:n.url})}),e.appendChild(r)}}function Hd(){let e=Rd(lt);return[`AI Helper v${e.version||Id}`,`${t(`versionInfo.tag`)}: ${e.tag||Id}`,`${t(`versionInfo.commit`)}: ${e.commitId||Id}`,`${t(`versionInfo.publishedAt`)}: ${zd(e.publishedAt)}`].join(`
399
+ `)}function Ud(){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`),Bd(a),o&&Vd(o),n.style.display=`flex`}),r&&r.addEventListener(`click`,s),n.addEventListener(`click`,e=>{e.target===n&&s()}),document.addEventListener(`keydown`,e=>{e.key===`Escape`&&n.style.display===`flex`&&s()}),i&&i.addEventListener(`click`,async()=>{try{await navigator.clipboard.writeText(Hd()),j(t(`common.copySuccess`),`success`)}catch{j(t(`common.copyFailed`),`error`)}})}var Wd=null;function Gd(){if(!Wd)return;Wd.classList.remove(`open`);let e=Wd.parentElement?Wd.parentElement.querySelector(`.section-select-row`):null;e&&e.classList.remove(`open`),Wd=null}function Kd(){return`<input type="search" class="section-select-search" placeholder="${t(`sectionSelect.searchPlaceholder`)}" data-i18n-placeholder="sectionSelect.searchPlaceholder" spellcheck="false">`}function qd(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 Jd(e,t){Gd(),e.classList.add(`open`),t.classList.add(`open`),Wd=e;let n=e.querySelector(`.section-select-search`);n&&(n.value=``,qd(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===Wd?Gd():Jd(e,t);return}Wd&&!Wd.parentElement.contains(e.target)&&Gd()}),document.addEventListener(`input`,e=>{let t=e.target;if(!t||!t.classList||!t.classList.contains(`section-select-search`))return;let n=t.closest(`.section-select-list`);n&&qd(n,t.value)});var Yd=!1;async function Xd(){document.getElementById(`providerList`)&&(Yd||(Yd=!0,$d(),ef()),await Zd())}async function Zd(){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=Kd();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(),Gd(),Qd(t.id)}),e.appendChild(r)}}async function Qd(e){if(e===(await x()).activeProfileId)return;let t=await ae(e);t&&(await Zd(),r.debug(`[SidePanel] provider switched:`,t.name))}function $d(){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 ef(){chrome.storage.onChanged.addListener((e,t)=>{t===`local`&&(e.modelProfiles||e.activeProfileId)&&Zd()})}var tf=0;function nf(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 rf(e){let t=[];return e.querySelectorAll(`*`).forEach(e=>{getComputedStyle(e).position===`absolute`&&e.getClientRects().length>0&&t.push(e)}),t}function af(e){e.forEach(e=>{(e.getAnimations?.()||[]).forEach(e=>{e.playState!==`idle`&&e.finish?.()})})}function of(){tf||=requestAnimationFrame(()=>{tf=0,lf()})}function sf(){let e=document.getElementById(`selectionToggleGroup`),t=document.getElementById(`inputAddMenuSwitches`);e&&e.classList.contains(`more-menu-hidden`)||e&&t&&e.parentElement!==t&&t.appendChild(e)}function cf(){let e=document.getElementById(`selectionToggleGroup`),t=document.querySelector(`.input-bottom-left`);e&&t&&e.parentElement!==t&&t.appendChild(e)}function lf(){let e=document.querySelector(`.input-bottom-row`),t=e?.closest(`.input-container`)||null;if(!(!e||!t)){t.classList.add(`measuring`);try{uf(e,t)}finally{t.classList.remove(`measuring`)}}}function uf(e,t){t.classList.remove(`temp-collapsed`,`agent-collapsed`,`switches-icon`,`selection-in-menu`),cf();let n=rf(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]}),af(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`),sf(),i()}function df(){lf(),window.addEventListener(`resize`,of);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,of())}).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=>!nf(t.target,e)&&!r(t))&&of()}).observe(e,{subtree:!0,childList:!0,characterData:!0})}var ff=`footer-compact`,pf=`footer-compact-ultra`,mf=`footer-wrap`,hf=`footer-measuring`,gf=0;function _f(){gf||=requestAnimationFrame(()=>{gf=0,yf()})}function vf(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 yf(){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(hf),e.classList.remove(ff,pf,mf)});try{let e=[...t].filter(e=>e.clientWidth>0&&e.scrollWidth>e.clientWidth);e.forEach(e=>e.classList.add(ff)),e=e.filter(e=>e.scrollWidth>e.clientWidth),e.forEach(e=>e.classList.add(pf)),e=e.filter(e=>e.scrollWidth>e.clientWidth),e.forEach(e=>e.classList.add(mf))}finally{t.forEach(e=>e.classList.remove(hf))}}}function bf(){let e=document.getElementById(`chatContainer`);if(e){if(yf(),window.addEventListener(`resize`,_f),typeof ResizeObserver<`u`){let t=e.clientWidth;new ResizeObserver(()=>{let n=e.clientWidth;Math.abs(n-t)<1||(t=n,_f())}).observe(e)}typeof MutationObserver<`u`&&new MutationObserver(e=>{e.some(vf)&&_f()}).observe(e,{subtree:!0,childList:!0}),document.fonts?.ready?.then(_f).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 xf=50,Sf=200,Cf=200,wf=0,Tf=null,Ef=[];function Df(e){return(e||``).replace(/\\/g,`/`).replace(/\/+/g,`/`)}function Of(e){let t=document.getElementById(`fileAtTitlePath`);if(!t)return;let n=e?Df(e):``;t.textContent=n,t.title=n}async function kf(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(),Af(),await Mr()})),ct(),t.style.display=`block`,n.classList.add(`show`),await jf(e)}function Af(){let e=document.getElementById(`fileAtSelector`),t=document.getElementById(`fileAtDropdown`);e&&(e.style.display=`none`),t&&t.classList.remove(`show`),y.selectedFileAtIndex=-1,Tf&&=(clearTimeout(Tf),null),wf++}function jf(e=``){let n=document.getElementById(`fileAtList`);if(!n)return;let i=++wf,a=e.trim();Tf&&clearTimeout(Tf);let o=async()=>{try{let e=await va();if(i!==wf)return;if(Of(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,Sf):((await ha(e)).entries||[]).map(t=>({name:t.name,type:t.type||`file`,size:t.size,mtime:t.mtime,fullPath:Df(`${e}/${t.name}`)})),i!==wf)return;Nf(r,a,n,e)}catch(e){if(i!==wf)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>`,Tf=setTimeout(o,Cf)):Tf=setTimeout(o,0)}function Mf(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 Nf(e,n,r,i){let a=Mf(e,n),o=a.slice(0,xf),s=a.length>xf,c=Df(i);if(o.length===0){r.innerHTML=`<div class="prompt-empty">${t(`fileSelector.noMatch`)}</div>`,y.selectedFileAtIndex=-1;return}if(y.selectedFileAtIndex=0,Ef=o,r.innerHTML=o.map((e,t)=>{let n=_a(e.name,e.type),r=Df(e.fullPath),i=r.startsWith(c)?r.substring(c.length).replace(/^\//,``):r;return`
400
400
  <div class="prompt-item ${t===0?`selected`:``}" data-index="${t}" data-path="${A(r)}" title="${A(r)}">
401
401
  <span class="prompt-item-index">${t+1}</span>
402
402
  <span class="prompt-item-icon">${n}</span>
403
403
  <span class="prompt-item-content">${A(e.name)}</span>
404
404
  <span class="file-at-path">${A(i)}</span>
405
405
  </div>
406
- `}).join(``),s){let e=document.createElement(`div`);e.className=`file-at-truncated`,e.textContent=t(`fileSelector.truncated`,{count:bf}),r.appendChild(e)}r.querySelectorAll(`.prompt-item`).forEach(e=>{e.addEventListener(`click`,()=>{Nf(Tf.find(t=>t.fullPath===e.dataset.path)||e.dataset.path)})})}function Nf(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()}kf(),ci([e]),Ze()}function Pf(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 Ff=null,Y=null,If=null,Lf=null,Rf=null,zf=null,X=null,Bf=[],Vf=0,Hf=()=>{},Uf=[{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`}],Wf=new Set([`screenshot`]),Gf={prompts:{titleKey:`promptManager.title`,action:()=>bn()},skills:{titleKey:`promptSelector.skillManageTitle`,action:()=>Kf(`toolbox`)},mcp:{titleKey:`promptSelector.mcpManageTitle`,action:()=>Kf(`toolbox`)},pages:{titleKey:`pageSelector.openNewTab`,action:()=>chrome.tabs.create({})},knowledge:{titleKey:`header.manageKnowledge`,action:()=>Kf(`knowledge`)},agents:{titleKey:`header.addEditAssistant`,action:()=>vi(null)},proxies:{titleKey:`header.addEditAgent`,action:()=>Kf(`agent`)},workspace:{titleKey:`workspace.openPanel`,action:()=>Mr()}};function Kf(e){chrome.runtime.sendMessage({type:`OPEN_OPTIONS_PAGE`,hash:e})}function qf(){if(!Rf)return;let e=X?Gf[X]:null;if(!e){Rf.style.display=`none`;return}let n=t(e.titleKey);Rf.title=n,Rf.setAttribute(`aria-label`,n),Rf.style.display=`flex`}function Jf(){Lf&&(Lf.style.display=Wf.has(X)?`none`:``)}function Yf(e={}){if(Hf=typeof e.onRequestClose==`function`?e.onRequestClose:()=>{},Ff=document.getElementById(`inputAddPanel`),Y=document.getElementById(`inputAddPanelSearch`),If=document.getElementById(`inputAddPanelSearchClear`),Rf=document.getElementById(`inputAddPanelManage`),Lf=document.getElementById(`inputAddPanelSearchWrap`),zf=document.getElementById(`inputAddPanelList`),!(!Ff||!Y||!zf)){if(Rf&&Rf.addEventListener(`click`,()=>{let e=X?Gf[X]:null;e&&(Hf(),e.action())}),If){let e=t(`input.addMenuPanelClear`);If.title=e,If.setAttribute(`aria-label`,e),If.addEventListener(`click`,()=>{Y.value=``,ap(),Xf(),Y.focus()})}Y.addEventListener(`input`,()=>{ap(),Xf()})}}function Xf(){If&&Y&&(If.style.display=Y.value?`flex`:`none`)}function Zf(){return!!X}function Qf(){return X}function $f(){return!!Y&&document.activeElement===Y}async function ep(e){if(!Ff||!e||X===e&&Ff.style.display!==`none`)return;X=e,qf(),Jf(),Y&&(Y.value=``,Y.placeholder=t(`input.addMenuPanelSearchPlaceholder`),Xf()),Ff.style.display=`flex`;let n=++Vf;zf&&(zf.innerHTML=`<div class="prompt-empty">${t(`input.addMenuPanelLoading`)}</div>`);try{let t=await np(e);if(n!==Vf)return;Bf=Array.isArray(t)?t:[],ap()}catch(e){if(n!==Vf)return;r.warn(`[InputAddPanel] load failed:`,e&&e.message),Bf=[],zf&&(zf.innerHTML=`<div class="prompt-empty">${t(`input.addMenuPanelEmpty`)}</div>`)}}function tp(){X=null,qf(),Jf(),Bf=[],Vf++,Y&&(Y.value=``,Xf()),zf&&(zf.innerHTML=``),Ff&&(Ff.style.display=`none`)}function np(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 rp();case`screenshot`:return Promise.resolve(Uf);default:return Promise.resolve([])}}async function rp(){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 ip(e){if(!e)return Bf;let n=e.toLowerCase();return Bf.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 ap(){if(!zf)return;let e=Y?Y.value.trim():``,n=ip(e);if(n.length===0){zf.innerHTML=`<div class="prompt-empty">${t(e?`input.addMenuPanelNoMatch`:`input.addMenuPanelEmpty`)}</div>`;return}zf.innerHTML=n.map(e=>op(e)).join(``),zf.querySelectorAll(`.input-add-panel-item`).forEach(e=>{e.addEventListener(`click`,t=>sp(t,e))}),zf.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 op(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="${k(e.content||``)}">
406
+ `}).join(``),s){let e=document.createElement(`div`);e.className=`file-at-truncated`,e.textContent=t(`fileSelector.truncated`,{count:xf}),r.appendChild(e)}r.querySelectorAll(`.prompt-item`).forEach(e=>{e.addEventListener(`click`,()=>{Pf(Ef.find(t=>t.fullPath===e.dataset.path)||e.dataset.path)})})}function Pf(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()}Af(),ci([e]),Ze()}function Ff(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 If=null,J=null,Lf=null,Rf=null,zf=null,Y=null,X=null,Bf=[],Vf=0,Hf=()=>{},Uf=[{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`}],Wf=new Set([`screenshot`]),Gf={prompts:{titleKey:`promptManager.title`,action:()=>bn()},skills:{titleKey:`promptSelector.skillManageTitle`,action:()=>Kf(`toolbox`)},mcp:{titleKey:`promptSelector.mcpManageTitle`,action:()=>Kf(`toolbox`)},pages:{titleKey:`pageSelector.openNewTab`,action:()=>chrome.tabs.create({})},knowledge:{titleKey:`header.manageKnowledge`,action:()=>Kf(`knowledge`)},agents:{titleKey:`header.addEditAssistant`,action:()=>vi(null)},proxies:{titleKey:`header.addEditAgent`,action:()=>Kf(`agent`)},workspace:{titleKey:`workspace.openPanel`,action:()=>Mr()}};function Kf(e){chrome.runtime.sendMessage({type:`OPEN_OPTIONS_PAGE`,hash:e})}function qf(){if(!zf)return;let e=X?Gf[X]:null;if(!e){zf.style.display=`none`;return}let n=t(e.titleKey);zf.title=n,zf.setAttribute(`aria-label`,n),zf.style.display=`flex`}function Jf(){Rf&&(Rf.style.display=Wf.has(X)?`none`:``)}function Yf(e={}){if(Hf=typeof e.onRequestClose==`function`?e.onRequestClose:()=>{},If=document.getElementById(`inputAddPanel`),J=document.getElementById(`inputAddPanelSearch`),Lf=document.getElementById(`inputAddPanelSearchClear`),zf=document.getElementById(`inputAddPanelManage`),Rf=document.getElementById(`inputAddPanelSearchWrap`),Y=document.getElementById(`inputAddPanelList`),!(!If||!J||!Y)){if(zf&&zf.addEventListener(`click`,()=>{let e=X?Gf[X]:null;e&&(Hf(),e.action())}),Lf){let e=t(`input.addMenuPanelClear`);Lf.title=e,Lf.setAttribute(`aria-label`,e),Lf.addEventListener(`click`,()=>{J.value=``,ap(),Xf(),J.focus()})}J.addEventListener(`input`,()=>{ap(),Xf()})}}function Xf(){Lf&&J&&(Lf.style.display=J.value?`flex`:`none`)}function Zf(){return!!X}function Qf(){return X}function $f(){return!!J&&document.activeElement===J}async function ep(e){if(!If||!e||X===e&&If.style.display!==`none`)return;X=e,qf(),Jf(),J&&(J.value=``,J.placeholder=t(`input.addMenuPanelSearchPlaceholder`),Xf()),If.style.display=`flex`;let n=++Vf;Y&&(Y.innerHTML=`<div class="prompt-empty">${t(`input.addMenuPanelLoading`)}</div>`);try{let t=await np(e);if(n!==Vf)return;Bf=Array.isArray(t)?t:[],ap()}catch(e){if(n!==Vf)return;r.warn(`[InputAddPanel] load failed:`,e&&e.message),Bf=[],Y&&(Y.innerHTML=`<div class="prompt-empty">${t(`input.addMenuPanelEmpty`)}</div>`)}}function tp(){X=null,qf(),Jf(),Bf=[],Vf++,J&&(J.value=``,Xf()),Y&&(Y.innerHTML=``),If&&(If.style.display=`none`)}function np(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 rp();case`screenshot`:return Promise.resolve(Uf);default:return Promise.resolve([])}}async function rp(){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 ip(e){if(!e)return Bf;let n=e.toLowerCase();return Bf.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 ap(){if(!Y)return;let e=J?J.value.trim():``,n=ip(e);if(n.length===0){Y.innerHTML=`<div class="prompt-empty">${t(e?`input.addMenuPanelNoMatch`:`input.addMenuPanelEmpty`)}</div>`;return}Y.innerHTML=n.map(e=>op(e)).join(``),Y.querySelectorAll(`.input-add-panel-item`).forEach(e=>{e.addEventListener(`click`,t=>sp(t,e))}),Y.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 op(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="${k(e.content||``)}">
407
407
  <span class="input-add-panel-item-title"><span class="input-add-panel-item-inline-icon">${Nt}</span>/${A(e.code)}</span>
408
408
  <span class="input-add-panel-item-sub">${A(e.content||``)}</span>
409
409
  </div>`;case`skills`:{let n=e.enabled===!1,r=n?`${e.name}\n${t(`skillSelector.disabledTooltip`)}`:e.name,i=e.description||``;return`<div class="skill-list-item input-add-panel-item input-add-panel-item-two-line${n?` skill-list-item-disabled`:``}" data-skill-name="${A(e.name)}" title="${k(r)}">
@@ -435,7 +435,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-C_EX21mG.js"
435
435
  <span class="input-add-panel-item-title">${e.icon} ${A(t(e.nameKey))}</span>
436
436
  <span class="input-add-panel-item-sub">${A(t(e.descKey))}</span>
437
437
  <kbd class="input-add-panel-item-kbd">${A(e.kbd)}</kbd>
438
- </div>`;default:return``}}async function sp(e,t){let n=e.ctrlKey||e.metaKey;switch(X){case`prompts`:{let e=t.dataset.code;n?ei(e,{skipTriggerStrip:!0}):gn(e),Hf();break}case`skills`:ta(t.dataset.skillName,Bf,{clearTrigger:!1}),n&&Hf();break;case`mcp`:wr(t.dataset.serverId,t.dataset.serverName,Bf,{clearTrigger:!1}),n&&Hf();break;case`pages`:{let e=Bf.find(e=>String(e.id)===t.dataset.tabId);if(e){Ot(e);let t=document.getElementById(`userInput`);t&&t.focus(),Ze()}Hf();break}case`knowledge`:if(e.target.closest(`.kb-docs-link`)){e.stopPropagation(),Hf(),Fn(t.dataset.kbId);break}Zr({id:t.dataset.kbId,name:t.dataset.kbName,enabled:t.dataset.kbDisabled!==`1`},{clearTrigger:!1}),n&&Hf();break;case`agents`:await ji(t.dataset.agentId,{clearTrigger:!1}),Hf();break;case`proxies`:await xr(t.dataset.proxyId,{clearTrigger:!1}),Hf();break;case`workspace`:{let e=Bf.find(e=>e.fullPath===t.dataset.path);if(e){let t=document.getElementById(`userInput`);t&&t.focus(),await ci([e]),Ze()}Hf();break}case`screenshot`:Hf(),await(t.dataset.shotAction===`region`?Wr:Jr)();break;default:break}}var cp=0,lp=200,up=150,dp={promptTriggerBtn:`prompts`,addMenuSkillBtn:`skills`,addMenuMcpBtn:`mcp`,addMenuPageBtn:`pages`,addMenuKnowledgeBtn:`knowledge`,addMenuAgentBtn:`agents`,addMenuProxyBtn:`proxies`,addMenuWorkspaceBtn:`workspace`,screenshotBtn:`screenshot`};async function fp(){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=++cp;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===cp&&(r.style.display=i?``:`none`)}))}function pp(){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=Zf()?Qf():null;t.querySelectorAll(`.input-add-item`).forEach(t=>{t.classList.toggle(`panel-active`,!!e&&dp[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?(tp(),s(),fp()):(i&&=(clearTimeout(i),null),a&&=(clearTimeout(a),null),tp(),s())},u=()=>t.style.display!==`none`;Yf({onRequestClose:()=>l(!1)}),e.addEventListener(`click`,e=>{e.stopPropagation();let t=!u();t&&(ii(),hr(),kf()),l(t)}),t.addEventListener(`click`,e=>{e.target.closest&&e.target.closest(`.input-add-item`)&&l(!1)},!0),document.addEventListener(`click`,e=>{u()&&(n&&n.contains(e.target)||l(!1))});let d=()=>{i&&=(clearTimeout(i),null),a&&clearTimeout(a),a=setTimeout(()=>{a=null,!$f()&&(tp(),s())},up)};r&&r.addEventListener(`mouseover`,e=>{if(!u())return;let t=e.target.closest(`.input-add-item`),n=t?dp[t.id]:null;if(!n){d();return}a&&=(clearTimeout(a),null),!(Zf()&&Qf()===n)&&(i&&clearTimeout(i),i=setTimeout(async()=>{i=null;let e=ep(n);c(t);try{await e}catch{}c(t),s()},lp))}),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`,()=>{Zf()&&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:()=>Of(``)}].forEach(({id:e,open:t})=>{let n=document.getElementById(e);n&&n.addEventListener(`click`,async e=>{e.stopPropagation(),n.blur(),ii(),hr(),kf();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 mp=`usageTipsEnabled`,hp=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 gp=[{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,_p=null,vp=null,yp=null,bp=null,xp=!1,Sp=null,Cp=!0,wp=null;function Tp(){return y.agentPlatform?.connected===!0}function Ep(){let e=a();return gp.filter(e=>e.scene!==`agent`||Tp()).map(t=>({id:t.id,text:e===`en`?t.en:t.zh}))}function Dp(e){let t=e.findIndex(e=>e.id===Sp);return t>=0?t:0}function Op(){if(!Z||!_p)return;let e=_p.scrollWidth>_p.clientWidth+1;Z.classList.toggle(`is-truncated`,e)}function kp(e,t){if(!_p||!e.length)return;let n=e[t%e.length];Sp=n.id,_p.textContent=n.text,vp&&(vp.textContent=n.text),Op(),_p.classList.remove(`fade-in`),_p.offsetWidth,_p.classList.add(`fade-in`)}function Ap(){if(!Cp||!Z||Z.style.display===`none`)return;let e=Ep();e.length&&kp(e,Dp(e)+1)}function jp(){bp&&=(clearInterval(bp),null)}function Mp(){jp(),!(!Cp||xp)&&(bp=setInterval(Ap,hp))}function Np(){if(!Cp||!Z)return;let e=Ep();if(!e.length){Fp();return}e.some(e=>e.id===Sp)?kp(e,Dp(e)):(Sp=null,kp(e,0))}function Pp(){if(!Z)return;Cp=!0,Z.style.display=``;let e=Ep();if(!e.length){Fp();return}kp(e,Dp(e)),Mp()}function Fp(){Z&&(Z.style.display=`none`,jp())}function Ip(){Z.addEventListener(`mouseenter`,()=>{xp=!0,jp()}),Z.addEventListener(`mouseleave`,()=>{xp=!1,Mp()}),yp.addEventListener(`click`,e=>{e.stopPropagation(),Lp(),j(t(`usageTips.dismissedHint`),`info`,5e3)}),chrome.storage.onChanged.addListener((e,t)=>{t!==`local`||!e[mp]||(e[mp].newValue===!1?(Cp=!1,Fp()):Pp())}),document.addEventListener(`agent-connection-changed`,Np),o(Np),typeof ResizeObserver<`u`&&new ResizeObserver(Op).observe(Z)}function Lp(){Cp=!1,Fp();try{chrome.storage.local.set({[mp]:!1})}catch{}}function Rp(){if(Z=document.getElementById(`usageTipsBar`),_p=document.getElementById(`usageTipsText`),vp=document.getElementById(`usageTipsTooltip`),yp=document.getElementById(`usageTipsDismiss`),!(!Z||!_p||!vp||!yp)){Ip(),wp=document.getElementById(`chatContainer`),wp&&(wp.appendChild(Z),typeof MutationObserver<`u`&&new MutationObserver(()=>{wp.querySelectorAll(`.usage-tips-bar`).forEach(e=>{e!==Z&&e.remove()}),(Z.parentNode!==wp||Z.nextElementSibling)&&wp.appendChild(Z)}).observe(wp,{childList:!0}));try{chrome.storage.local.get([mp],e=>{Cp=e?.[mp]!==!1,Cp?Pp():Fp()})}catch{Pp()}}}function zp({key:e,value:t=``,caret:n,history:r=[],index:i=-1}={}){if(e!==`ArrowUp`&&e!==`ArrowDown`||!Array.isArray(r)||r.length===0)return{handled:!1};let a=String(t??``),o=Number.isInteger(n)&&n>=0?n:a.length,s=Number.isInteger(i)&&i>=0;if(e===`ArrowUp`){let e=a.lastIndexOf(`
438
+ </div>`;default:return``}}async function sp(e,t){let n=e.ctrlKey||e.metaKey;switch(X){case`prompts`:{let e=t.dataset.code;n?ei(e,{skipTriggerStrip:!0}):gn(e),Hf();break}case`skills`:ta(t.dataset.skillName,Bf,{clearTrigger:!1}),n&&Hf();break;case`mcp`:wr(t.dataset.serverId,t.dataset.serverName,Bf,{clearTrigger:!1}),n&&Hf();break;case`pages`:{let e=Bf.find(e=>String(e.id)===t.dataset.tabId);if(e){Ot(e);let t=document.getElementById(`userInput`);t&&t.focus(),Ze()}Hf();break}case`knowledge`:if(e.target.closest(`.kb-docs-link`)){e.stopPropagation(),Hf(),Fn(t.dataset.kbId);break}Zr({id:t.dataset.kbId,name:t.dataset.kbName,enabled:t.dataset.kbDisabled!==`1`},{clearTrigger:!1}),n&&Hf();break;case`agents`:await ji(t.dataset.agentId,{clearTrigger:!1}),Hf();break;case`proxies`:await xr(t.dataset.proxyId,{clearTrigger:!1}),Hf();break;case`workspace`:{let e=Bf.find(e=>e.fullPath===t.dataset.path);if(e){let t=document.getElementById(`userInput`);t&&t.focus(),await ci([e]),Ze()}Hf();break}case`screenshot`:Hf(),await(t.dataset.shotAction===`region`?Wr:Jr)();break;default:break}}var cp=0,lp=200,up=150,dp={promptTriggerBtn:`prompts`,addMenuSkillBtn:`skills`,addMenuMcpBtn:`mcp`,addMenuPageBtn:`pages`,addMenuKnowledgeBtn:`knowledge`,addMenuAgentBtn:`agents`,addMenuProxyBtn:`proxies`,addMenuWorkspaceBtn:`workspace`,screenshotBtn:`screenshot`};async function fp(){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=++cp;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===cp&&(r.style.display=i?``:`none`)}))}function pp(){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=Zf()?Qf():null;t.querySelectorAll(`.input-add-item`).forEach(t=>{t.classList.toggle(`panel-active`,!!e&&dp[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?(tp(),s(),fp()):(i&&=(clearTimeout(i),null),a&&=(clearTimeout(a),null),tp(),s())},u=()=>t.style.display!==`none`;Yf({onRequestClose:()=>l(!1)}),e.addEventListener(`click`,e=>{e.stopPropagation();let t=!u();t&&(ii(),hr(),Af()),l(t)}),t.addEventListener(`click`,e=>{e.target.closest&&e.target.closest(`.input-add-item`)&&l(!1)},!0),document.addEventListener(`click`,e=>{u()&&(n&&n.contains(e.target)||l(!1))});let d=()=>{i&&=(clearTimeout(i),null),a&&clearTimeout(a),a=setTimeout(()=>{a=null,!$f()&&(tp(),s())},up)};r&&r.addEventListener(`mouseover`,e=>{if(!u())return;let t=e.target.closest(`.input-add-item`),n=t?dp[t.id]:null;if(!n){d();return}a&&=(clearTimeout(a),null),!(Zf()&&Qf()===n)&&(i&&clearTimeout(i),i=setTimeout(async()=>{i=null;let e=ep(n);c(t);try{await e}catch{}c(t),s()},lp))}),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`,()=>{Zf()&&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:()=>kf(``)}].forEach(({id:e,open:t})=>{let n=document.getElementById(e);n&&n.addEventListener(`click`,async e=>{e.stopPropagation(),n.blur(),ii(),hr(),Af();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 mp=`usageTipsEnabled`,hp=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 gp=[{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,_p=null,vp=null,yp=null,bp=null,xp=!1,Sp=null,Cp=!0,wp=null;function Tp(){return y.agentPlatform?.connected===!0}function Ep(){let e=a();return gp.filter(e=>e.scene!==`agent`||Tp()).map(t=>({id:t.id,text:e===`en`?t.en:t.zh}))}function Dp(e){let t=e.findIndex(e=>e.id===Sp);return t>=0?t:0}function Op(){if(!Z||!_p)return;let e=_p.scrollWidth>_p.clientWidth+1;Z.classList.toggle(`is-truncated`,e)}function kp(e,t){if(!_p||!e.length)return;let n=e[t%e.length];Sp=n.id,_p.textContent=n.text,vp&&(vp.textContent=n.text),Op(),_p.classList.remove(`fade-in`),_p.offsetWidth,_p.classList.add(`fade-in`)}function Ap(){if(!Cp||!Z||Z.style.display===`none`)return;let e=Ep();e.length&&kp(e,Dp(e)+1)}function jp(){bp&&=(clearInterval(bp),null)}function Mp(){jp(),!(!Cp||xp)&&(bp=setInterval(Ap,hp))}function Np(){if(!Cp||!Z)return;let e=Ep();if(!e.length){Fp();return}e.some(e=>e.id===Sp)?kp(e,Dp(e)):(Sp=null,kp(e,0))}function Pp(){if(!Z)return;Cp=!0,Z.style.display=``;let e=Ep();if(!e.length){Fp();return}kp(e,Dp(e)),Mp()}function Fp(){Z&&(Z.style.display=`none`,jp())}function Ip(){Z.addEventListener(`mouseenter`,()=>{xp=!0,jp()}),Z.addEventListener(`mouseleave`,()=>{xp=!1,Mp()}),yp.addEventListener(`click`,e=>{e.stopPropagation(),Lp(),j(t(`usageTips.dismissedHint`),`info`,5e3)}),chrome.storage.onChanged.addListener((e,t)=>{t!==`local`||!e[mp]||(e[mp].newValue===!1?(Cp=!1,Fp()):Pp())}),document.addEventListener(`agent-connection-changed`,Np),o(Np),typeof ResizeObserver<`u`&&new ResizeObserver(Op).observe(Z)}function Lp(){Cp=!1,Fp();try{chrome.storage.local.set({[mp]:!1})}catch{}}function Rp(){if(Z=document.getElementById(`usageTipsBar`),_p=document.getElementById(`usageTipsText`),vp=document.getElementById(`usageTipsTooltip`),yp=document.getElementById(`usageTipsDismiss`),!(!Z||!_p||!vp||!yp)){Ip(),wp=document.getElementById(`chatContainer`),wp&&(wp.appendChild(Z),typeof MutationObserver<`u`&&new MutationObserver(()=>{wp.querySelectorAll(`.usage-tips-bar`).forEach(e=>{e!==Z&&e.remove()}),(Z.parentNode!==wp||Z.nextElementSibling)&&wp.appendChild(Z)}).observe(wp,{childList:!0}));try{chrome.storage.local.get([mp],e=>{Cp=e?.[mp]!==!1,Cp?Pp():Fp()})}catch{Pp()}}}function zp({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
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 Bp(e,t){let n;return function(...r){clearTimeout(n),n=setTimeout(()=>{clearTimeout(n),e(...r)},t)}}var Vp=null,Hp=null,Up=null,Wp=null,Gp=null,Kp=null,qp=null,Jp=null,Yp=null,Xp=null,Zp=!1,Qp=!1,$p=null,em={[ni.DISPATCHING]:`queue.statusDispatching`,[ni.INJECTING]:`queue.statusInjecting`,[ni.INJECTED]:`queue.statusInjected`,[ni.DONE]:`queue.statusDone`,[ni.FAILED]:`queue.statusFailed`};function tm(e){if(e.status===ni.QUEUED)return e.interrupted?t(`queue.statusRecovered`):``;let n=em[e.status];return n?t(n):``}function nm(){return y.activeSessionId}function rm(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="${A(n&&(n.fileNames||[]).length?n.fileNames.join(`、`):i)}">${A(i)}</span>`:``}function im(e,n){let r=rm(e),i=e.status===ni.DISPATCHING,a=tm(e),o=(a?`<span class="queue-chip-status${i?` running`:``}${e.interrupted?` warning`:``}"${i?` title="${A(t(`queue.statusRunningHint`))}"`:``}>${A(a)}</span>`:``)+r,s=y.isGenerating===!0;return`
441
441
  <div class="queue-chip" draggable="true" data-id="${A(e.id)}" data-status="${A(e.status)}">
@@ -472,7 +472,7 @@ import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-C_EX21mG.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`,Um),Q.querySelector(`.sap-lock`).addEventListener(`click`,Lm),Q.querySelector(`.sap-copy`).addEventListener(`click`,qm),Q.querySelector(`.sap-transfer`).addEventListener(`click`,Jm),Q.querySelector(`.sap-regen`).addEventListener(`click`,()=>{Tm&&Em&&Xm()}),Km(Q.querySelector(`.sap-header`)),Q)}function Fm(){if(!Q)return;Q.querySelector(`.sap-close`).title=t(`sidePanel.popupClose`);let e=Q.querySelector(`.sap-copy`);e.textContent=t(`sidePanel.popupCopy`),e.title=t(`sidePanel.popupCopy`);let n=Q.querySelector(`.sap-transfer`);n.textContent=t(`sidePanel.popupTransfer`),n.title=t(`sidePanel.popupTransfer`);let r=Q.querySelector(`.sap-regen`);r.textContent=t(`sidePanel.popupRegenerate`),r.title=t(`sidePanel.popupRegenerate`),Im()}function Im(){if(!Q)return;let e=Q.querySelector(`.sap-lock`);e&&(e.classList.toggle(`locked`,Am),e.title=t(Am?`sidePanel.popupUnlock`:`sidePanel.popupLock`),e.innerHTML=Am?`<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 Lm(){Am=!Am,Im()}function Rm(e,t){let n=Pm(),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 zm(e){let n=Pm();Fm(),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 Bm(){return!!Q&&Q.classList.contains(`show`)}function Vm(e,t=!0){let n=Q?.querySelector(`.sap-body`);n&&(n.innerHTML=`<div class="sap-content markdown-body">${e}</div>`,t&&(n.scrollTop=n.scrollHeight))}function Hm(e){let t=Q?.querySelector(`.sap-body`);t&&(t.innerHTML=`<div class="sap-error">${A(e)}</div>`)}function Um(){km&&Cm&&chrome.runtime.sendMessage({type:`CANCEL_REACT`,sessionId:Cm}).catch(()=>{}),Q&&(Q.classList.remove(`show`),Q.style.display=`none`),Cm=null,wm=``,km=!1,Am=!1}function Wm(e){if(!Bm()||Am||Q.contains(e.target))return;let t=document.getElementById(`selectionFloatingMenu`);t&&t.contains(e.target)||Um()}function Gm(e){e.key===`Escape`&&(!Bm()||Am||Um())}function Km(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 qm(){wm&&navigator.clipboard.writeText(wm).then(()=>{j(t(`sidePanel.popupCopied`))}).catch(()=>{let e=document.createElement(`textarea`);e.value=wm,document.body.appendChild(e),e.select(),document.execCommand(`copy`),document.body.removeChild(e),j(t(`sidePanel.popupCopied`))})}function Jm(){if(!wm||!Tm)return;nn()&&Cn();let e=wm,n=Tm.content,r=`${Dm?`[${t(`sidePanel.popupContextLabel`)}]\n${Dm}\n\n`:``}[${t(`sidePanel.selectedContentLabel`)}]\n${Em}\n\n[${t(`sidePanel.userQuestionLabel`)}]\n${Tm.content}`;D(async()=>{let{addMessage:e}=await import(`./context-indicator-BPCvEgPs.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-BPCvEgPs.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-BPCvEgPs.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}),j(t(`sidePanel.popupTransferred`))})}),Um()}function Ym(e,t,n){let{context:r,truncated:i}=Mm(n,t);Tm=e,Em=t,Dm=r,Om=i,Xm()}function Xm(){wm=``,km=!0,zm(Tm?.content);let e=Nm(Em,Dm,Tm.content,Om);Cm=`popup_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,chrome.runtime.sendMessage({type:`SIDEPANEL_POPUP_ASK`,sessionId:Cm,messages:e}).catch(e=>{r.error(`[SelectionPopup] sendMessage failed:`,e),Hm(t(`sidePanel.popupRequestFailed`)),km=!1})}var Zm=!1;function Qm(){Zm||(Zm=!0,chrome.runtime.onMessage.addListener(e=>{if(!(!e||!e.type)&&e.type.startsWith(`SIDEPANEL_POPUP_`)&&e.sessionId===Cm){if(e.type===`SIDEPANEL_POPUP_STREAM_CHUNK`)e.delta&&(wm+=e.delta,Vm(st(wm)));else if(e.type===`SIDEPANEL_POPUP_STREAM_DONE`)km=!1,e.finalContent&&(wm=e.finalContent),Vm(st(wm));else if(e.type===`SIDEPANEL_POPUP_STREAM_ERROR`){if(!km)return;km=!1,Hm(e.error||t(`sidePanel.popupRequestFailed`))}}}))}function $m(){Qm(),document.addEventListener(`mousedown`,Wm),document.addEventListener(`keydown`,Gm)}function eh(e,t,n,r,i){!t||!e||(Qm(),Rm(n,r),Am=!1,Ym(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 th(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=`
475
+ `,document.body.appendChild(Q),Q.querySelector(`.sap-close`).addEventListener(`click`,Um),Q.querySelector(`.sap-lock`).addEventListener(`click`,Lm),Q.querySelector(`.sap-copy`).addEventListener(`click`,qm),Q.querySelector(`.sap-transfer`).addEventListener(`click`,Jm),Q.querySelector(`.sap-regen`).addEventListener(`click`,()=>{Tm&&Em&&Xm()}),Km(Q.querySelector(`.sap-header`)),Q)}function Fm(){if(!Q)return;Q.querySelector(`.sap-close`).title=t(`sidePanel.popupClose`);let e=Q.querySelector(`.sap-copy`);e.textContent=t(`sidePanel.popupCopy`),e.title=t(`sidePanel.popupCopy`);let n=Q.querySelector(`.sap-transfer`);n.textContent=t(`sidePanel.popupTransfer`),n.title=t(`sidePanel.popupTransfer`);let r=Q.querySelector(`.sap-regen`);r.textContent=t(`sidePanel.popupRegenerate`),r.title=t(`sidePanel.popupRegenerate`),Im()}function Im(){if(!Q)return;let e=Q.querySelector(`.sap-lock`);e&&(e.classList.toggle(`locked`,Am),e.title=t(Am?`sidePanel.popupUnlock`:`sidePanel.popupLock`),e.innerHTML=Am?`<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 Lm(){Am=!Am,Im()}function Rm(e,t){let n=Pm(),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 zm(e){let n=Pm();Fm(),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 Bm(){return!!Q&&Q.classList.contains(`show`)}function Vm(e,t=!0){let n=Q?.querySelector(`.sap-body`);n&&(n.innerHTML=`<div class="sap-content markdown-body">${e}</div>`,t&&(n.scrollTop=n.scrollHeight))}function Hm(e){let t=Q?.querySelector(`.sap-body`);t&&(t.innerHTML=`<div class="sap-error">${A(e)}</div>`)}function Um(){km&&Cm&&chrome.runtime.sendMessage({type:`CANCEL_REACT`,sessionId:Cm}).catch(()=>{}),Q&&(Q.classList.remove(`show`),Q.style.display=`none`),Cm=null,wm=``,km=!1,Am=!1}function Wm(e){if(!Bm()||Am||Q.contains(e.target))return;let t=document.getElementById(`selectionFloatingMenu`);t&&t.contains(e.target)||Um()}function Gm(e){e.key===`Escape`&&(!Bm()||Am||Um())}function Km(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 qm(){wm&&navigator.clipboard.writeText(wm).then(()=>{j(t(`sidePanel.popupCopied`))}).catch(()=>{let e=document.createElement(`textarea`);e.value=wm,document.body.appendChild(e),e.select(),document.execCommand(`copy`),document.body.removeChild(e),j(t(`sidePanel.popupCopied`))})}function Jm(){if(!wm||!Tm)return;nn()&&Cn();let e=wm,n=Tm.content,r=`${Dm?`[${t(`sidePanel.popupContextLabel`)}]\n${Dm}\n\n`:``}[${t(`sidePanel.selectedContentLabel`)}]\n${Em}\n\n[${t(`sidePanel.userQuestionLabel`)}]\n${Tm.content}`;D(async()=>{let{addMessage:e}=await import(`./context-indicator-CF1oNqcX.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-CF1oNqcX.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-CF1oNqcX.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}),j(t(`sidePanel.popupTransferred`))})}),Um()}function Ym(e,t,n){let{context:r,truncated:i}=Mm(n,t);Tm=e,Em=t,Dm=r,Om=i,Xm()}function Xm(){wm=``,km=!0,zm(Tm?.content);let e=Nm(Em,Dm,Tm.content,Om);Cm=`popup_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,chrome.runtime.sendMessage({type:`SIDEPANEL_POPUP_ASK`,sessionId:Cm,messages:e}).catch(e=>{r.error(`[SelectionPopup] sendMessage failed:`,e),Hm(t(`sidePanel.popupRequestFailed`)),km=!1})}var Zm=!1;function Qm(){Zm||(Zm=!0,chrome.runtime.onMessage.addListener(e=>{if(!(!e||!e.type)&&e.type.startsWith(`SIDEPANEL_POPUP_`)&&e.sessionId===Cm){if(e.type===`SIDEPANEL_POPUP_STREAM_CHUNK`)e.delta&&(wm+=e.delta,Vm(st(wm)));else if(e.type===`SIDEPANEL_POPUP_STREAM_DONE`)km=!1,e.finalContent&&(wm=e.finalContent),Vm(st(wm));else if(e.type===`SIDEPANEL_POPUP_STREAM_ERROR`){if(!km)return;km=!1,Hm(e.error||t(`sidePanel.popupRequestFailed`))}}}))}function $m(){Qm(),document.addEventListener(`mousedown`,Wm),document.addEventListener(`keydown`,Gm)}function eh(e,t,n,r,i){!t||!e||(Qm(),Rm(n,r),Am=!1,Ym(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 th(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>
@@ -601,7 +601,7 @@ Agent address: {url}
601
601
  Are you sure you want to update the agent? It will install the latest patch version within the {version} minor range compatible with this extension, then restart the service. The service will be unavailable during update.`,updateAgentTitle:`Update Agent`,agentUpdating:`Updating agent (may take a few minutes)...`,agentUpdateRestarting:`Agent is updating and restarting...`,agentVersionAhead:`Agent version is newer than this extension. Please update the extension from the store first`,agentAlreadyLatest:`Already at the latest compatible version`,agentUpdateAvailable:`Update available: v{current} → v{latest}`,updateFailed:`Update failed: {error}`,updateRequestFailed:`Update request failed: {error}`,stopAgentConfirm:`Agent name: {name}
602
602
  Agent address: {url}
603
603
 
604
- Are you sure you want to stop the agent service? You will not be able to connect and will need to manually restart it.`,stopAgentTitle:`Stop Agent`,agentStopped:`Agent service stopped, agent is offline`,stopFailed:`Stop failed: {error}`,stopRequestFailed:`Stop request failed: {error}`,agentStatusRefreshed:`Agent status refreshed`,deleteAgentTitle:`Delete Agent`,deleteAgentConfirm:`Are you sure you want to delete agent "{name}"? This action cannot be undone.`,welcomeTitle:`Start a Conversation`,welcomeSubtitle:`Enter your question and the AI assistant will help you`,sendBtnStop:`Stop generating`,sendBtnSend:`Send`,defaultPromptImage:`Please look at the attached image and describe what you see`,defaultPromptFile:`Please read the attached file and summarize the key points`,defaultPromptAttachments:`Please review the attached image and file and summarize the key points`,defaultPromptKnowledge:`Please answer based on the knowledge base content I referenced`,defaultKnowledgeQuery:`key points summary`,defaultPromptPage:`Please summarize the main content of this page`,defaultPromptSelection:`Please continue based on the content I provided`,defaultPromptContext:`Please continue based on the context I provided`,imageNotEnabled:`Image recognition not enabled, image attached as file`,screenshotFailed:`Screenshot failed, please retry`,auditCategoryAuth:`Auth`,auditCategoryFs:`File`,auditCategoryExec:`Command`,auditCategorySecurity:`Security`,auditCategorySystem:`System`,auditDetailSeparator:`; `,auditQueryFailed:`Query failed: {error}`,auditLoadFailed:`Load failed: {error}`,auditNoMatch:`No matching audit logs`,auditEmpty:`No audit logs`,clearStatsConfirm:`Are you sure you want to clear all tool usage stats? This action cannot be undone.`,clearStatsTitle:`Clear Stats`,toolStatsSummary:`Used {used} tools, unused {unused} tools`,toolStatsLoadFailed:`Load failed`,toolNameDescSeparator:`: `}}),window.showCustomConfirm=function(e,n=t(`sidePanel.confirmAction`)){return new Promise(t=>{let r=document.getElementById(`customConfirmOverlay`),i=document.getElementById(`customConfirmTitle`),a=document.getElementById(`customConfirmMessage`),o=document.getElementById(`customConfirmCancelBtn`),s=document.getElementById(`customConfirmOkBtn`);if(!r||!i||!a||!o||!s){t(confirm(e));return}let c=()=>{r.style.display=`none`,s.removeEventListener(`click`,l),o.removeEventListener(`click`,u),r.removeEventListener(`click`,d),document.removeEventListener(`keydown`,f)},l=()=>{c(),t(!0)},u=()=>{c(),t(!1)},d=e=>{e.target===r&&(c(),t(!1))},f=e=>{e.key===`Enter`?(e.preventDefault(),e.stopPropagation(),l()):e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),u())};i.textContent=n,a.innerHTML=e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`).replace(/'/g,`&#39;`).replace(/\n/g,`<br>`),r.style.display=`flex`,s.addEventListener(`click`,l),o.addEventListener(`click`,u),r.addEventListener(`click`,d),document.addEventListener(`keydown`,f),requestAnimationFrame(()=>s.focus())})},chrome.storage.onChanged.addListener((e,t)=>{t===`local`&&e.chatAutoCompaction&&(y.chatConfig.autoCompaction=e.chatAutoCompaction.newValue===!0,ih(),r.debug(`[SidePanel] auto-compaction config updated:`,y.chatConfig.autoCompaction)),t===`local`&&e.chatPersistSummaryToMemory&&(y.chatConfig.persistSummaryToMemory=e.chatPersistSummaryToMemory.newValue!==!1,ah(),r.debug(`[SidePanel] persist-summary config updated:`,y.chatConfig.persistSummaryToMemory)),t===`local`&&e.chatMaxMemoryMessages&&(y.chatConfig.maxMemoryMessages=e.chatMaxMemoryMessages.newValue,rh(),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 rh(){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 ih(){let e=document.getElementById(`autoCompactBtn`);e&&(e.checked=y.chatConfig.autoCompaction===!0)}function ah(){let e=document.getElementById(`persistSummaryBtn`);e&&(e.checked=y.chatConfig.persistSummaryToMemory!==!1)}function oh(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 sh(){let e=document.getElementById(`memoryLimitDropdown`),n=document.getElementById(`memoryLimitLabel`),r=e?.querySelector(`#memoryLimitInput`);if(!e||!n)return;rh(),n.addEventListener(`click`,oh);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,j(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,j(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,rh(),j(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,rh(),j(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 ch(e){if(y.activeAgentId&&y.activeAgentId!=="default")try{let{updateAgent:t}=await D(async()=>{let{updateAgent:e}=await import(`./agent-store-C4yiT4AA.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 lh(){try{let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),t=nh(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=zh(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 uh(e,t,n){if(y.activeAgentId&&y.activeAgentId!=="default")try{let{updateAgent:n}=await D(async()=>{let{updateAgent:e}=await import(`./agent-store-C4yiT4AA.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 dh(){let e=document.getElementById(`currentModelTag`);if(!e)return;let t=y.currentModel||``;e.textContent=t,e.title=t,e.style.display=t?``:`none`}var fh=new Set,ph=0;function mh(){let e=document.getElementById(`workdirTag`);e&&(e.dataset.locked=na(y.activeSessionId)?`true`:`false`)}async function hh(){let e=++ph,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!==ph)return;let l=c&&c.workdir||``;if(!l){n.style.display=`none`;return}n.style.display=``,i.textContent=s(l,{homeDir:y.agentPlatform?.homeDir||``}),mh();try{let{getWorkspaceRoot:e}=await D(async()=>{let{getWorkspaceRoot:e}=await import(`./workspace-manager-DFPFAowW.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`,xm(a).then(e=>{e&&hh()}).catch(e=>r.debug(`[WorkdirTag] reconcile failed:`,e&&e.message))):n.dataset.invalid=i?`true`:`false`}catch{n.dataset.invalid=`false`}if(e===ph&&(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||``}`;fh.has(e)||(fh.add(e),j(t(`workdirTag.agentSwitched`),`warning`))}}function gh(){let e=document.getElementById(`workdirTag`);e&&(e.setAttribute(`aria-label`,t(`workdirTag.tagHint`)),e.addEventListener(`click`,async e=>{if(e.stopPropagation(),na(y.activeSessionId)){mh(),j(t(`workdirTag.lockedHint`),`warning`);return}mh();let{showSwitchWorkdirDialog:n}=await D(async()=>{let{showSwitchWorkdirDialog:e}=await import(`./context-indicator-BPCvEgPs.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})})),hh(),document.addEventListener(`session-switched`,()=>{hh()}),document.addEventListener(`session-workdir-changed`,()=>{hh()}),document.addEventListener(`agent-model-changed`,()=>{hh()}),document.addEventListener(`agent-tools-changed`,()=>{hh()}),document.addEventListener(`generating-state-changed`,()=>{mh()}),document.addEventListener(`generation-ended`,()=>{mh()}),qt(()=>{mh()})}function _h(){let e=document.getElementById(`currentModelTag`);e&&e.addEventListener(`click`,e=>{e.stopPropagation(),document.getElementById(`tempDisplay`)?.click()}),dh()}function vh(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`),dh()}function yh(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,ih(),r.debug(`[SidePanel] auto-compaction config updated:`,y.chatConfig.autoCompaction)),t===`local`&&e.chatPersistSummaryToMemory&&(y.chatConfig.persistSummaryToMemory=e.chatPersistSummaryToMemory.newValue!==!1,ah(),r.debug(`[SidePanel] persist-summary config updated:`,y.chatConfig.persistSummaryToMemory)),t===`local`&&e.chatMaxMemoryMessages&&(y.chatConfig.maxMemoryMessages=e.chatMaxMemoryMessages.newValue,rh(),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 rh(){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 ih(){let e=document.getElementById(`autoCompactBtn`);e&&(e.checked=y.chatConfig.autoCompaction===!0)}function ah(){let e=document.getElementById(`persistSummaryBtn`);e&&(e.checked=y.chatConfig.persistSummaryToMemory!==!1)}function oh(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 sh(){let e=document.getElementById(`memoryLimitDropdown`),n=document.getElementById(`memoryLimitLabel`),r=e?.querySelector(`#memoryLimitInput`);if(!e||!n)return;rh(),n.addEventListener(`click`,oh);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,j(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,j(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,rh(),j(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,rh(),j(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 ch(e){if(y.activeAgentId&&y.activeAgentId!=="default")try{let{updateAgent:t}=await D(async()=>{let{updateAgent:e}=await import(`./agent-store-kLwTRAYA.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 lh(){try{let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),t=nh(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=Bh(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 uh(e,t,n){if(y.activeAgentId&&y.activeAgentId!=="default")try{let{updateAgent:n}=await D(async()=>{let{updateAgent:e}=await import(`./agent-store-kLwTRAYA.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 dh(){let e=document.getElementById(`currentModelTag`);if(!e)return;let n=y.currentModel||``;e.textContent=n,e.title=n?`${n} · ${t(`toggle.modelSettings`)}`:``,e.style.display=n?``:`none`}var fh=new Set,ph=0;function mh(){let e=document.getElementById(`workdirTag`);e&&(e.dataset.locked=na(y.activeSessionId)?`true`:`false`)}async function hh(){let e=++ph,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!==ph)return;let l=c&&c.workdir||``;if(!l){n.style.display=`none`;return}n.style.display=``,i.textContent=s(l,{homeDir:y.agentPlatform?.homeDir||``}),mh();try{let{getWorkspaceRoot:e}=await D(async()=>{let{getWorkspaceRoot:e}=await import(`./workspace-manager-Dk95w-Hj.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`,xm(a).then(e=>{e&&hh()}).catch(e=>r.debug(`[WorkdirTag] reconcile failed:`,e&&e.message))):n.dataset.invalid=i?`true`:`false`}catch{n.dataset.invalid=`false`}if(e===ph&&(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||``}`;fh.has(e)||(fh.add(e),j(t(`workdirTag.agentSwitched`),`warning`))}}function gh(){let e=document.getElementById(`workdirTag`);e&&(e.setAttribute(`aria-label`,t(`workdirTag.tagHint`)),e.addEventListener(`click`,async e=>{if(e.stopPropagation(),na(y.activeSessionId)){mh(),j(t(`workdirTag.lockedHint`),`warning`);return}mh();let{showSwitchWorkdirDialog:n}=await D(async()=>{let{showSwitchWorkdirDialog:e}=await import(`./context-indicator-CF1oNqcX.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})})),hh(),document.addEventListener(`session-switched`,()=>{hh()}),document.addEventListener(`session-workdir-changed`,()=>{hh()}),document.addEventListener(`agent-model-changed`,()=>{hh()}),document.addEventListener(`agent-tools-changed`,()=>{hh()}),document.addEventListener(`generating-state-changed`,()=>{mh()}),document.addEventListener(`generation-ended`,()=>{mh()}),qt(()=>{mh()})}function _h(){let e=document.getElementById(`currentModelTag`);e&&(e.setAttribute(`aria-haspopup`,`true`),e.addEventListener(`click`,e=>{e.stopPropagation(),document.getElementById(`moreOptionsDropdown`)?.classList.remove(`show`),document.getElementById(`moreOptionsBtn`)?.setAttribute(`aria-expanded`,`false`),document.getElementById(`tempDisplay`)?.click()})),dh()}function vh(){let e=document.getElementById(`moreOptionsBtn`),t=document.getElementById(`moreOptionsDropdown`);if(!e||!t)return;let n=document.getElementById(`goalModeBtn`),r=document.getElementById(`enableSelectionQueryBtn`),i=document.getElementById(`moreGoalRow`),a=document.getElementById(`moreGoalToggle`),o=document.getElementById(`moreSelectionToggle`),s=document.getElementById(`moreFlagGoal`),c=document.getElementById(`moreFlagSelection`),l=()=>{let e=!!n&&n.style.display!==`none`,t=e&&!!n.checked,i=!!r&&r.checked;s&&(s.hidden=!e,s.classList.toggle(`on`,t)),c&&c.classList.toggle(`on`,i)},u=()=>{a&&n&&(a.checked=n.checked),o&&r&&(o.checked=r.checked),i&&n&&(i.hidden=n.style.display===`none`),l()},d=()=>{t.classList.remove(`show`),e.setAttribute(`aria-expanded`,`false`)},f=()=>{if(!t.classList.contains(`show`))return;let n=e.getBoundingClientRect(),r=(t.parentElement||e).getBoundingClientRect(),i=e.closest(`.input-container`),a=i?i.getBoundingClientRect():{left:8,right:window.innerWidth-8},o=t.offsetWidth||252,s=a.left+8,c=Math.max(s,a.right-o-8),l=Math.min(Math.max(s,n.left),c);t.style.left=`${Math.round(l-r.left)}px`};e.addEventListener(`click`,()=>{let n=!t.classList.contains(`show`);t.classList.toggle(`show`,n),e.setAttribute(`aria-expanded`,String(n)),n&&(u(),f())}),window.addEventListener(`resize`,f),t.addEventListener(`click`,e=>e.stopPropagation()),document.addEventListener(`click`,i=>{t.contains(i.target)||e.contains(i.target)||i.target===n||i.target===r||d()}),document.addEventListener(`keydown`,n=>{n.key===`Escape`&&t.classList.contains(`show`)&&(d(),e.focus())});let p=(e,t)=>{!e||!t||(e.addEventListener(`change`,()=>{t.checked!==e.checked&&t.click(),setTimeout(()=>{e.checked=t.checked,l()},0)}),t.addEventListener(`change`,()=>{e.checked=t.checked,l()}))};p(a,n),p(o,r),document.addEventListener(`session-switched`,()=>{setTimeout(u,0)}),u(),[0,80,250,600,1200,2e3].forEach(e=>setTimeout(u,e))}function yh(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`),dh()}function bh(e,n){let r=document.getElementById(`tempDropdown`);if(!r){typeof n==`function`&&n();return}let i=r.querySelector(`.model-section`),a=[];if((Array.isArray(e)?e:[]).forEach(e=>{typeof e==`string`?a.push({name:e,contextWindow:0}):e&&typeof e==`object`&&e.name&&a.push({name:e.name,contextWindow:e.contextWindow||0})}),i){i.innerHTML=`
605
605
  <div class="model-section-title" data-i18n="model.selectModel">${t(`model.selectModel`)}</div>
606
606
  <div class="section-select" id="modelSelect">
607
607
  <div class="section-select-row" id="modelSelectRow">
@@ -610,7 +610,7 @@ Are you sure you want to stop the agent service? You will not be able to connect
610
610
  <span class="section-select-caret"></span>
611
611
  </div>
612
612
  <div class="section-select-list" id="modelSelectList"></div>
613
- </div>`;let e=i.querySelector(`#modelSelectList`);e.innerHTML=Gd();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">${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: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(),Wd(),y.currentModel=r.name,vh(r.name),ch(r.name),Xr()}),e.appendChild(n)}}y.customModelMap=l(e),typeof n==`function`&&n()}function bh(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 xh=null,Sh=``;function Ch(){if(xh&&xh.isConnected)return xh;xh=document.createElement(`div`),xh.className=`selection-floating-menu`,xh.id=`selectionFloatingMenu`,xh.innerHTML=`
613
+ </div>`;let e=i.querySelector(`#modelSelectList`);e.innerHTML=Kd();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">${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: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(),Gd(),y.currentModel=r.name,yh(r.name),ch(r.name),Xr()}),e.appendChild(n)}}y.customModelMap=l(e),typeof n==`function`&&n()}function xh(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 Sh=null,Ch=``;function wh(){if(Sh&&Sh.isConnected)return Sh;Sh=document.createElement(`div`),Sh.className=`selection-floating-menu`,Sh.id=`selectionFloatingMenu`,Sh.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=xh.querySelector(`.menu-copy-btn`);return e?.addEventListener(`click`,n=>{n.stopPropagation(),Sh&&($e(Sh,e),j(t(`sidePanel.copySelectionDone`),`success`),window.getSelection()?.removeAllRanges(),window.hideFloatingMenu())}),document.body.appendChild(xh),xh}function wh(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=Ch();Sh=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=Sh.querySelector(`.menu-copy-btn`);return e?.addEventListener(`click`,n=>{n.stopPropagation(),Ch&&($e(Ch,e),j(t(`sidePanel.copySelectionDone`),`success`),window.getSelection()?.removeAllRanges(),window.hideFloatingMenu())}),document.body.appendChild(Sh),Sh}function Th(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=wh();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=`
624
624
  <span>${r}</span>
625
625
  <span class="menu-item-actions">
626
626
  <span class="menu-item-code">/${e.code}</span>
@@ -632,9 +632,9 @@ Are you sure you want to stop the agent service? You will not be able to connect
632
632
  </svg>
633
633
  </button>
634
634
  </span>
635
- `,o.addEventListener(`click`,t=>{t.stopPropagation(),Th(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(),eh(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(){xh&&xh.classList.remove(`show`),Sh=``,y.lastSelectedText=``,y.currentSelectionRange=null};async function Th(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 Ye(),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 ut(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+`
635
+ `,o.addEventListener(`click`,t=>{t.stopPropagation(),Eh(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(),eh(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=``,y.lastSelectedText=``,y.currentSelectionRange=null};async function Eh(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 Ye(),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 ut(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 Ge(),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 ot(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 Eh=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=nh(e.pairedAgents),o=s.find(t=>t.id===e.activeAgentId)}catch{}let c=e?.connected===!0;if(c!==Eh){Eh=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),Ih(o,s,c),!n){let e=document.getElementById(`headerAgentDropdown`);e&&e.style.display!==`none`&&Hh()}Ci(c),hh(),Fh(o,c)}function Dh(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 Oh(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 kh=3600*1e3,Ah=1440*60*1e3,jh=new Map;function Mh(e){let n=document.getElementById(`agentDdUpdateBtn`);if(!n)return;let r=e?.current||``,i=e?.latest||``,a=!!i&&Oh(i,r)>0;n.classList.toggle(`has-update`,a),n.title=a?t(`sidePanel.agentUpdateAvailable`,{current:r,latest:i}):t(`header.updateAndRestart`)}async function Nh(){try{await chrome.storage.local.remove([`agentUpdateCheck`,`agentUpdateCheckUnsupported`])}catch{}Mh(null)}async function Ph(e,t){let n=null;try{n=(await chrome.storage.local.get(`activeAgentId`)).activeAgentId}catch{}if(n===e&&(Mh(t),t))try{await chrome.storage.local.set({agentUpdateCheck:t})}catch{}}async function Fh(e,t){if(!t||!e?.id){Mh(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<kh){Mh(r);return}if(i?.agentId===e.id&&i?.target===n&&i?.checkedAt&&Date.now()-i.checkedAt<Ah){Mh(null);return}let a=`${e.id}:${n}`;if(jh.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 Ph(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 Ph(e.id,null);return}}catch{}finally{jh.delete(a)}})();jh.set(a,o),await o}function Ih(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=Dh(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=Rh(u,y.agentHomeDirs.get(n.id)),f=y.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 Ge(),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 ot(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 Dh=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=nh(e.pairedAgents),o=s.find(t=>t.id===e.activeAgentId)}catch{}let c=e?.connected===!0;if(c!==Dh){Dh=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),Lh(o,s,c),!n){let e=document.getElementById(`headerAgentDropdown`);e&&e.style.display!==`none`&&Uh()}Ci(c),hh(),Ih(o,c)}function Oh(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 kh(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 Ah=3600*1e3,jh=1440*60*1e3,Mh=new Map;function Nh(e){let n=document.getElementById(`agentDdUpdateBtn`);if(!n)return;let r=e?.current||``,i=e?.latest||``,a=!!i&&kh(i,r)>0;n.classList.toggle(`has-update`,a),n.title=a?t(`sidePanel.agentUpdateAvailable`,{current:r,latest:i}):t(`header.updateAndRestart`)}async function Ph(){try{await chrome.storage.local.remove([`agentUpdateCheck`,`agentUpdateCheckUnsupported`])}catch{}Nh(null)}async function Fh(e,t){let n=null;try{n=(await chrome.storage.local.get(`activeAgentId`)).activeAgentId}catch{}if(n===e&&(Nh(t),t))try{await chrome.storage.local.set({agentUpdateCheck:t})}catch{}}async function Ih(e,t){if(!t||!e?.id){Nh(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<Ah){Nh(r);return}if(i?.agentId===e.id&&i?.target===n&&i?.checkedAt&&Date.now()-i.checkedAt<jh){Nh(null);return}let a=`${e.id}:${n}`;if(Mh.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 Fh(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 Fh(e.id,null);return}}catch{}finally{Mh.delete(a)}})();Mh.set(a,o),await o}function Lh(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=Oh(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=zh(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">
@@ -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 Lh(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 Rh(e,t){return e?t&&e.startsWith(t)?`~`+e.substring(t.length):e:``}function zh(e,t){return e||``}function Bh(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 Vh(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=Rh(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=Vh;async function Hh(){try{let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),t=nh(e.pairedAgents),n=e.activeAgentId;await Promise.all(t.filter(e=>!e.disabled).map(async e=>{let t=await Lh(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=zh(t.platformName,t.arch);i&&y.agentSystemInfos.set(e.id,i),t.workdir&&Vh(e.id,t.workdir),Bh(e.id,r),e.id===n&&r!==(y.agentPlatform?.connected===!0)&&(y.agentPlatform={...y.agentPlatform,connected:r},$(y.agentPlatform,!0),r&&Uh(e))}))}catch{}}async function Uh(e){try{let t=e;if(!t){let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),n=nh(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),Vh(t.id,e.workdir)),e.homeDir&&y.agentHomeDirs.set(t.id,e.homeDir);let n=zh(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 Wh=null;function Gh(e,t=20){Wh&&clearInterval(Wh);let n=0;Wh=setInterval(async()=>{if(n++,n>t||!e){clearInterval(Wh),Wh=null;return}try{let t=nh((await chrome.storage.local.get([`pairedAgents`])).pairedAgents).find(t=>t.id===e);if(!t){clearInterval(Wh),Wh=null;return}let n=await Lh(t.url,t.token);if(n.online){clearInterval(Wh),Wh=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=zh(n.platformName,n.arch);r&&y.agentSystemInfos.set(e,r),n.workdir&&Vh(e,n.workdir),await Uh(t),Bh(e,!0)}}catch{}},3e3)}function Kh(){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 qh(){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||(Kh(),$(y.agentPlatform||{}),Hh())}),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=nh(n.pairedAgents).find(e=>e.id===n.activeAgentId);r?.url&&(await navigator.clipboard.writeText(r.url),j(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=nh(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?(j(t(`sidePanel.agentRestarting`),`success`),y.agentPlatform={...y.agentPlatform,connected:!1},await $(y.agentPlatform,!0),r?.id&&Bh(r.id,!1),Gh(r?.id)):j(t(`sidePanel.restartFailed`,{error:e?.error||t(`sidePanel.unknownError`)}),`error`)})}catch(e){j(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=nh(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`))){j(t(`sidePanel.agentUpdating`),`info`);try{chrome.runtime.sendMessage({type:`AGENT_UPDATE`,target:s},async e=>{if(e?.success&&e.upToDate){await Nh(),j(e.message||t(`sidePanel.agentAlreadyLatest`),`info`);return}e?.success?(await Nh(),j(t(`sidePanel.agentUpdateRestarting`),`success`),y.agentPlatform={...y.agentPlatform,connected:!1},await $(y.agentPlatform,!0),r?.id&&Bh(r.id,!1),Gh(r?.id)):j(t(`sidePanel.updateFailed`,{error:e?.error||t(`sidePanel.unknownError`)}),`error`)})}catch(e){j(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=nh(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?(j(t(`sidePanel.agentStopped`),`success`),y.agentPlatform={...y.agentPlatform,connected:!1},await $(y.agentPlatform,!0),r?.id&&Bh(r.id,!1)):j(t(`sidePanel.stopFailed`,{error:e?.error||t(`sidePanel.unknownError`)}),`error`)})}catch(e){j(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 Hh(),j(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=nh(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 Jh=new Map,Yh=8;function Xh(e,t){for(Jh.has(e)&&Jh.delete(e),Jh.set(e,t);Jh.size>Yh;)Jh.delete(Jh.keys().next().value)}function Zh(e){let t=Jh.get(e);if(t!==void 0)return Jh.delete(e),Jh.set(e,t),t}function Qh(e){Jh.delete(e)}document.addEventListener(`DOMContentLoaded`,async()=>{await nt(),ft(()=>{Qe()}),Vi(),await Promise.allSettled([n().then(()=>{i(),$i(),o(()=>{i(),$i()})}),rt(),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&&io(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&&bh(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&&bh(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&&Uh()),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=nh(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=zh(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=zh(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`,ct()}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)=>`
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 Rh(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 zh(e,t){return e?t&&e.startsWith(t)?`~`+e.substring(t.length):e:``}function Bh(e,t){return e||``}function Vh(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 Hh(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=zh(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=Hh;async function Uh(){try{let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),t=nh(e.pairedAgents),n=e.activeAgentId;await Promise.all(t.filter(e=>!e.disabled).map(async e=>{let t=await Rh(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=Bh(t.platformName,t.arch);i&&y.agentSystemInfos.set(e.id,i),t.workdir&&Hh(e.id,t.workdir),Vh(e.id,r),e.id===n&&r!==(y.agentPlatform?.connected===!0)&&(y.agentPlatform={...y.agentPlatform,connected:r},$(y.agentPlatform,!0),r&&Wh(e))}))}catch{}}async function Wh(e){try{let t=e;if(!t){let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),n=nh(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),Hh(t.id,e.workdir)),e.homeDir&&y.agentHomeDirs.set(t.id,e.homeDir);let n=Bh(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 Gh=null;function Kh(e,t=20){Gh&&clearInterval(Gh);let n=0;Gh=setInterval(async()=>{if(n++,n>t||!e){clearInterval(Gh),Gh=null;return}try{let t=nh((await chrome.storage.local.get([`pairedAgents`])).pairedAgents).find(t=>t.id===e);if(!t){clearInterval(Gh),Gh=null;return}let n=await Rh(t.url,t.token);if(n.online){clearInterval(Gh),Gh=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=Bh(n.platformName,n.arch);r&&y.agentSystemInfos.set(e,r),n.workdir&&Hh(e,n.workdir),await Wh(t),Vh(e,!0)}}catch{}},3e3)}function qh(){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 Jh(){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||(qh(),$(y.agentPlatform||{}),Uh())}),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=nh(n.pairedAgents).find(e=>e.id===n.activeAgentId);r?.url&&(await navigator.clipboard.writeText(r.url),j(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=nh(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?(j(t(`sidePanel.agentRestarting`),`success`),y.agentPlatform={...y.agentPlatform,connected:!1},await $(y.agentPlatform,!0),r?.id&&Vh(r.id,!1),Kh(r?.id)):j(t(`sidePanel.restartFailed`,{error:e?.error||t(`sidePanel.unknownError`)}),`error`)})}catch(e){j(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=nh(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`))){j(t(`sidePanel.agentUpdating`),`info`);try{chrome.runtime.sendMessage({type:`AGENT_UPDATE`,target:s},async e=>{if(e?.success&&e.upToDate){await Ph(),j(e.message||t(`sidePanel.agentAlreadyLatest`),`info`);return}e?.success?(await Ph(),j(t(`sidePanel.agentUpdateRestarting`),`success`),y.agentPlatform={...y.agentPlatform,connected:!1},await $(y.agentPlatform,!0),r?.id&&Vh(r.id,!1),Kh(r?.id)):j(t(`sidePanel.updateFailed`,{error:e?.error||t(`sidePanel.unknownError`)}),`error`)})}catch(e){j(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=nh(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?(j(t(`sidePanel.agentStopped`),`success`),y.agentPlatform={...y.agentPlatform,connected:!1},await $(y.agentPlatform,!0),r?.id&&Vh(r.id,!1)):j(t(`sidePanel.stopFailed`,{error:e?.error||t(`sidePanel.unknownError`)}),`error`)})}catch(e){j(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 Uh(),j(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=nh(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 Yh=new Map,Xh=8;function Zh(e,t){for(Yh.has(e)&&Yh.delete(e),Yh.set(e,t);Yh.size>Xh;)Yh.delete(Yh.keys().next().value)}function Qh(e){let t=Yh.get(e);if(t!==void 0)return Yh.delete(e),Yh.set(e,t),t}function $h(e){Yh.delete(e)}document.addEventListener(`DOMContentLoaded`,async()=>{await nt(),ft(()=>{Qe()}),Vi(),await Promise.allSettled([n().then(()=>{i(),$i(),o(()=>{i(),$i()})}),rt(),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&&io(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&&xh(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&&xh(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&&Wh()),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=nh(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=Bh(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=Bh(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`,ct()}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,13 +660,13 @@ 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(),ne(parseInt(e.dataset.index))})})}function ne(e){let t=zi[e];t&&(y.selectedTempIndex=e,y.temperature=t.temp,ee(),uh(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(),uh(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(),uh(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=>{Es(e.target)&&(y.lastMouseX=e.clientX,y.lastMouseY=e.clientY)}),document.addEventListener(`mouseup`,e=>{Es(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();Es(e.anchorNode)&&(y.lastSelectedText=t,y.currentSelectionRange=e.getRangeAt(0).cloneRange(),bh(t),wh(e,t,y.lastMouseX,y.lastMouseY))}else Es(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,bh(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(),Yd(),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(()=>{}),lh(),y.enableImageInput=e.enableImageInput||!1,y.imageModelName=e.imageModelName||``,y.imageApiBase=e.imageApiBase||``,y.imageApiKey=ce(e.imageApiKey)||``,y.enableFileInput=!0,Tr(),oa(),wn(),yh(e.customModels,()=>{t&&vh(t)})}),chrome.storage.onChanged.addListener((e,t)=>{if(t===`local`){if(e.customModels&&yh(e.customModels.newValue||[],()=>{vh(y.currentModel)}),e.modelName){let t=e.modelName.newValue;t&&(!y.activeAgentId||y.activeAgentId==="default")&&(y.currentModel=t,vh(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 mm();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)),bh(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&&bh(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&&Xh(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=Zh(n),d=y.messageHistory&&y.messageHistory.length>0;if(u&&!l&&d){if(a.innerHTML=u,fr(a),Ke(),ht(),!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(),Ke(),ht(),!y.pendingCallApiSessionIds.has(n)){let e=jn(a);e&&Xh(n,e)}yn()}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(),uh(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(),uh(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(),uh(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=>{Ds(e.target)&&(y.lastMouseX=e.clientX,y.lastMouseY=e.clientY)}),document.addEventListener(`mouseup`,e=>{Ds(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();Ds(e.anchorNode)&&(y.lastSelectedText=t,y.currentSelectionRange=e.getRangeAt(0).cloneRange(),xh(t),Th(e,t,y.lastMouseX,y.lastMouseY))}else Ds(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,xh(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(),Xd(),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(()=>{}),lh(),y.enableImageInput=e.enableImageInput||!1,y.imageModelName=e.imageModelName||``,y.imageApiBase=e.imageApiBase||``,y.imageApiKey=ce(e.imageApiKey)||``,y.enableFileInput=!0,Tr(),oa(),wn(),bh(e.customModels,()=>{t&&yh(t)})}),chrome.storage.onChanged.addListener((e,t)=>{if(t===`local`){if(e.customModels&&bh(e.customModels.newValue||[],()=>{yh(y.currentModel)}),e.modelName){let t=e.modelName.newValue;t&&(!y.activeAgentId||y.activeAgentId==="default")&&(y.currentModel=t,yh(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 mm();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)),xh(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&&xh(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&&Zh(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=Qh(n),d=y.messageHistory&&y.messageHistory.length>0;if(u&&!l&&d){if(a.innerHTML=u,fr(a),Ke(),ht(),!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(),Ke(),ht(),!y.pendingCallApiSessionIds.has(n)){let e=jn(a);e&&Zh(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:`,[...y.pendingCallApiSessionIds],`activeSessionId:`,n,`hasCancelApi:`,!!y.pendingCancelApi),l&&(r.debug(`[SidePanel] switch back tobackground task session,rebuildstreamingoutput element`),Hn(n)),io(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-BPCvEgPs.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&&Qh(t)}),document.querySelectorAll(`.model-option`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation();let n=e.dataset.value;y.currentModel=n,vh(n),ch(n),Xr()})}),document.addEventListener(`agent-model-changed`,()=>{vh(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)&&kf(),i&&!i.contains(e.target)){let t=window.getSelection(),n=Es(e.target),r=t&&!t.isCollapsed&&Es(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)?(j(t(`queue.stopAndSendStarted`),`success`,2500),!0):(Di(n),!0)):(j(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=Ts();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,Pf(n));return}if(e.key===`Enter`&&r>0&&y.selectedFileAtIndex>=0){e.preventDefault(),n[y.selectedFileAtIndex].click();return}if(e.key===`Escape`){e.preventDefault(),kf();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()&&cm()){e.preventDefault();return}if(!c&&!l&&!u){let t=zp({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(),kf(),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 j(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 j(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),j(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(),Of(i.filterText)):i&&i.key===`at`?(ii(),kf(),yi(i.filterText)):i&&i.key===`slash`?(hr(),kf(),n.style.display!==`none`&&r.classList.contains(`show`)?Vt(i.filterText):On(i.filterText)):(ii(),hr(),kf()),_()});let xe=Bp((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=mt();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(),it(e.dataset.themeValue),ke()})})),Oe(),ft(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`),Ge=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 k(e){let n=new Set([`timestamp`,`level`,`category`,`action`]),r=[];for(let[t,i]of Object.entries(e)){if(n.has(t))continue;let e=typeof i==`string`?i:JSON.stringify(i),a=e.length>60?e.slice(0,60)+`...`:e;r.push(`${t}: ${a}`)}return r.join(t(`sidePanel.auditDetailSeparator`))}async function $e(){if(!Ue||!We||!Ge)return;Ue.style.display=`block`,We.style.display=`none`,Ge.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||[],tt()}catch(e){Ue.style.display=`none`,We.style.display=`block`,We.textContent=t(`sidePanel.auditLoadFailed`,{error:e.message})}}function tt(){if(!Ge)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`),Ge.style.display=`none`;return}We.style.display=`none`,Ge.style.display=`block`,Ge.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(k(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)),io(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-CF1oNqcX.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&&$h(t)}),document.querySelectorAll(`.model-option`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation();let n=e.dataset.value;y.currentModel=n,yh(n),ch(n),Xr()})}),document.addEventListener(`agent-model-changed`,()=>{yh(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)&&Af(),i&&!i.contains(e.target)){let t=window.getSelection(),n=Ds(e.target),r=t&&!t.isCollapsed&&Ds(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)?(j(t(`queue.stopAndSendStarted`),`success`,2500),!0):(Di(n),!0)):(j(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=Es();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,Ff(n));return}if(e.key===`Enter`&&r>0&&y.selectedFileAtIndex>=0){e.preventDefault(),n[y.selectedFileAtIndex].click();return}if(e.key===`Escape`){e.preventDefault(),Af();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()&&cm()){e.preventDefault();return}if(!c&&!l&&!u){let t=zp({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(),Af(),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 j(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 j(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),j(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(),kf(i.filterText)):i&&i.key===`at`?(ii(),Af(),yi(i.filterText)):i&&i.key===`slash`?(hr(),Af(),n.style.display!==`none`&&r.classList.contains(`show`)?Vt(i.filterText):On(i.filterText)):(ii(),hr(),Af()),_()});let xe=Bp((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=mt();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(),it(e.dataset.themeValue),ke()})})),Oe(),ft(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`),Ge=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 k(e){let n=new Set([`timestamp`,`level`,`category`,`action`]),r=[];for(let[t,i]of Object.entries(e)){if(n.has(t))continue;let e=typeof i==`string`?i:JSON.stringify(i),a=e.length>60?e.slice(0,60)+`...`:e;r.push(`${t}: ${a}`)}return r.join(t(`sidePanel.auditDetailSeparator`))}async function $e(){if(!Ue||!We||!Ge)return;Ue.style.display=`block`,We.style.display=`none`,Ge.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||[],tt()}catch(e){Ue.style.display=`none`,We.style.display=`block`,We.textContent=t(`sidePanel.auditLoadFailed`,{error:e.message})}}function tt(){if(!Ge)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`),Ge.style.display=`none`;return}We.style.display=`none`,Ge.style.display=`block`,Ge.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(k(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>
@@ -674,7 +674,7 @@ Are you sure you want to stop the agent service? You will not be able to connect
674
674
  <span class="audit-action">${A(e.action||`-`)}</span>
675
675
  </div>
676
676
  ${a?`<div class="audit-details">${a}</div>`:``}
677
- </div>`}).join(``)}function at(){Ie&&(Ie.style.display=`flex`,$e())}function ot(){Ie&&(Ie.style.display=`none`)}Fe&&Fe.addEventListener(`click`,e=>{e.stopPropagation(),ke(),at()}),Le&&Le.addEventListener(`click`,ot),Re&&Re.addEventListener(`click`,$e),ze&&ze.addEventListener(`change`,$e),Be&&Be.addEventListener(`change`,$e),Ve&&Ve.addEventListener(`input`,()=>{tt()}),He&&He.addEventListener(`click`,()=>{Ve&&(Ve.value=``),tt()}),th(()=>y.activeSessionId,window.showCustomConfirm);let st=document.getElementById(`isolateChatBtn`),lt=document.getElementById(`enableToolsBtn`),ut=document.getElementById(`toolsConfigBtn`),dt=`agentEnabledTools_${y.activeAgentId||`default`}`,pt=`agentMcpClosedServers_${y.activeAgentId||`default`}`;chrome.storage.local.get([dt,`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-C4yiT4AA.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[dt],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,[dt]:y.enabledTools}):y.enabledTools.length!==r.length&&chrome.storage.local.set({[dt]: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({[dt]: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,[dt]:y.enabledTools})}lt&&(lt.checked=y.useTools),zt(),hh(),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()}),lt&&lt.addEventListener(`change`,()=>{y.useTools=lt.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="${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 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=et(i);return`<tr>
677
+ </div>`}).join(``)}function at(){Ie&&(Ie.style.display=`flex`,$e())}function ot(){Ie&&(Ie.style.display=`none`)}Fe&&Fe.addEventListener(`click`,e=>{e.stopPropagation(),ke(),at()}),Le&&Le.addEventListener(`click`,ot),Re&&Re.addEventListener(`click`,$e),ze&&ze.addEventListener(`change`,$e),Be&&Be.addEventListener(`change`,$e),Ve&&Ve.addEventListener(`input`,()=>{tt()}),He&&He.addEventListener(`click`,()=>{Ve&&(Ve.value=``),tt()}),th(()=>y.activeSessionId,window.showCustomConfirm);let st=document.getElementById(`isolateChatBtn`),lt=document.getElementById(`enableToolsBtn`),ut=document.getElementById(`toolsConfigBtn`),dt=`agentEnabledTools_${y.activeAgentId||`default`}`,pt=`agentMcpClosedServers_${y.activeAgentId||`default`}`;chrome.storage.local.get([dt,`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-kLwTRAYA.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[dt],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,[dt]:y.enabledTools}):y.enabledTools.length!==r.length&&chrome.storage.local.set({[dt]: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({[dt]: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,[dt]:y.enabledTools})}lt&&(lt.checked=y.useTools),zt(),hh(),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()}),lt&&lt.addEventListener(`change`,()=>{y.useTools=lt.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="${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 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=et(i);return`<tr>
678
678
  <td style="padding: 6px 10px; border-bottom: 1px solid var(--border-subtle); color: var(--text-primary);"><code title="${A(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>
@@ -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(``),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`,()=>{})}),pt().then(()=>{rh(),$r(y.chatConfig.showMessageTimestamp!==!1),ih(),ah()}),document.addEventListener(`DOMContentLoaded`,()=>{sh()}),document.addEventListener(`DOMContentLoaded`,un),document.addEventListener(`DOMContentLoaded`,mi),document.addEventListener(`DOMContentLoaded`,_h),document.addEventListener(`DOMContentLoaded`,gh),document.addEventListener(`DOMContentLoaded`,uf),document.addEventListener(`DOMContentLoaded`,yf),document.addEventListener(`DOMContentLoaded`,pp),document.addEventListener(`DOMContentLoaded`,Rp),document.addEventListener(`DOMContentLoaded`,async()=>{try{ba(),await ya()}catch{}}),document.addEventListener(`DOMContentLoaded`,kn),document.addEventListener(`DOMContentLoaded`,async()=>{mr(),ro(),await Qi(),At(),await vc(),iu(),As(),$m(),$s(),qh(),Wi(),Hd();let{updateBookmarkButtons:e,updateBookmarkBadge:t}=await D(async()=>{let{updateBookmarkButtons:e,updateBookmarkBadge:t}=await import(`./context-indicator-BPCvEgPs.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`,()=>{ws()}),document.addEventListener(`DOMContentLoaded`,async()=>{Ht(e=>Ni(e)),await Et(),await hm()});function $h(){Gt(),Or(),Pi(),Yn(),hn(),Rt();let e=document.getElementById(`imagePreviewBar`);e&&(e.innerHTML=``,e.style.display=`none`)}function eg(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`,$h),document.addEventListener(`queue-context-restored`,e=>{eg(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-BPCvEgPs.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 tg(){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){j(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){j(t(`detach.taskRunning`),`warning`);return}try{let e=(await chrome.windows.getCurrent()).id,n=await tg();if(n==null){j(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),j(t(`detach.attachFailed`),`error`)}catch(e){r.warn(`[SidePanel] attach failed:`,e?.message),j(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`,()=>{})}),pt().then(()=>{rh(),$r(y.chatConfig.showMessageTimestamp!==!1),ih(),ah()}),document.addEventListener(`DOMContentLoaded`,()=>{sh()}),document.addEventListener(`DOMContentLoaded`,un),document.addEventListener(`DOMContentLoaded`,mi),document.addEventListener(`DOMContentLoaded`,_h),document.addEventListener(`DOMContentLoaded`,vh),document.addEventListener(`DOMContentLoaded`,gh),document.addEventListener(`DOMContentLoaded`,df),document.addEventListener(`DOMContentLoaded`,bf),document.addEventListener(`DOMContentLoaded`,pp),document.addEventListener(`DOMContentLoaded`,Rp),document.addEventListener(`DOMContentLoaded`,async()=>{try{ba(),await ya()}catch{}}),document.addEventListener(`DOMContentLoaded`,kn),document.addEventListener(`DOMContentLoaded`,async()=>{mr(),ro(),await Qi(),At(),await yc(),au(),js(),$m(),ec(),Jh(),Wi(),Ud();let{updateBookmarkButtons:e,updateBookmarkBadge:t}=await D(async()=>{let{updateBookmarkButtons:e,updateBookmarkBadge:t}=await import(`./context-indicator-CF1oNqcX.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`,()=>{Ts()}),document.addEventListener(`DOMContentLoaded`,async()=>{Ht(e=>Ni(e)),await Et(),await hm()});function eg(){Gt(),Or(),Pi(),Yn(),hn(),Rt();let e=document.getElementById(`imagePreviewBar`);e&&(e.innerHTML=``,e.style.display=`none`)}function tg(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`,eg),document.addEventListener(`queue-context-restored`,e=>{tg(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-CF1oNqcX.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 ng(){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){j(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){j(t(`detach.taskRunning`),`warning`);return}try{let e=(await chrome.windows.getCurrent()).id,n=await ng();if(n==null){j(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),j(t(`detach.attachFailed`),`error`)}catch(e){r.warn(`[SidePanel] attach failed:`,e?.message),j(t(`detach.attachFailed`),`error`)}})});