ai-helper-agent 2.8.12 → 2.8.13

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-BSGa1g7l.js","assets/chunk-CMxvf4Kt.js","assets/model-profiles-CqsAD3Fd.js","assets/i18n-DvmxOw8q.js","assets/voice-shortcut-Dx863RGz.js","assets/session-store-DfBABQNR.js","assets/version-Dc9zhEVX.js","assets/agent-store-CE4-QMOA.js","assets/workspace-manager-D6xww21F.js"])))=>i.map(i=>d[i]);
2
- import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-DvmxOw8q.js";import{A as s,At as c,Bt as l,Ht as u,J as d,Jt as f,L as p,Lt as m,M as h,Nt as g,Ot as ee,P as te,R as ne,U as _,b as v,c as re,ct as y,d as b,gt as x,ht as ie,i as S,it as C,jt as ae,k as oe,q as w,r as se,rt as ce,u as le,wt as ue,x as T,y as de,zt as fe}from"./model-profiles-CqsAD3Fd.js";import{_ as E,d as pe}from"./session-store-DfBABQNR.js";import{A as me,C as he,D as ge,E as _e,M as ve,N as ye,O as be,S as xe,T as Se,_ as Ce,a as we,b as Te,c as Ee,d as De,f as Oe,g as ke,h as Ae,i as je,j as Me,k as Ne,l as Pe,m as Fe,n as D,o as Ie,p as Le,r as Re,s as ze,t as Be,u as Ve,v as He,w as Ue,x as We,y as Ge}from"./todo-model-DLDokK9s.js";import{$ as Ke,A as O,B as qe,D as Je,E as Ye,G as Xe,J as k,K as Ze,L as Qe,M as $e,N as et,O as tt,Q as nt,U as rt,V as it,W as at,X as ot,Z as st,_ as ct,et as lt,g as ut,j as A,k as dt,l as ft,q as pt,t as mt,v as ht,w as gt,y as _t}from"./version-Dc9zhEVX.js";import{$ as vt,$n 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,Ct as jt,D as Mt,Dn as Nt,Dr as Pt,Dt as Ft,E as It,En as Lt,Er as Rt,Et as zt,F as Bt,Fn as Vt,Fr as Ht,Ft as Ut,G as Wt,Gn as Gt,Gr as Kt,Gt as qt,H as Jt,Hn as Yt,Hr as Xt,Ht as Zt,I as Qt,In as $t,Ir as en,It as tn,J as nn,Jn as rn,Jt as an,K as on,Kn as sn,Kr as cn,Kt as ln,L as un,Ln as dn,Lr as fn,Lt as pn,M as mn,Mn as hn,Mr as gn,Mt as _n,N as vn,Nn as yn,Nr as bn,Nt as xn,O as Sn,On as Cn,Or as wn,Ot as Tn,P as En,Pn as Dn,Pr as On,Pt as kn,Q as An,Qn as jn,Qt as Mn,R as Nn,Rn as Pn,Rr as Fn,Rt as In,S as Ln,Sn as Rn,Sr as zn,St as Bn,T as Vn,Tn as Hn,Tr as Un,Tt as Wn,U as Gn,Un as Kn,Ur as qn,Ut as Jn,Vn as Yn,Vr as Xn,Vt as Zn,W as Qn,Wn as $n,Wr as er,Wt as tr,X as nr,Xn as rr,Xt as ir,Y as ar,Yn as or,Yt as sr,Z as cr,Zn as lr,Zt as ur,_ as dr,_n as fr,_r as pr,_t as mr,a as hr,an as gr,ar as _r,at as vr,b as yr,bn as br,br as xr,bt as Sr,c as Cr,cn as wr,cr as Tr,ct as Er,d as Dr,dn as Or,dr as kr,dt as Ar,en as jr,er as Mr,et as Nr,f as Pr,fn as Fr,fr as Ir,ft as Lr,g as Rr,gn as zr,gr as Br,gt as Vr,h as Hr,hn as Ur,hr as Wr,ht as Gr,i as Kr,in as qr,it as Jr,j as Yr,jn as Xr,jr as Zr,jt as Qr,k as $r,kn as ei,kr as ti,kt as ni,l as ri,ln as ii,lr as ai,lt as oi,m as si,mn as ci,mr as li,mt as ui,n as di,nn as fi,nr as pi,nt as mi,o as hi,on as gi,or as _i,ot as vi,p as yi,pn as bi,pr as xi,q as Si,qn as Ci,qt as wi,r as Ti,rn as Ei,rr as Di,rt as Oi,s as ki,sn as Ai,sr as ji,st as Mi,t as Ni,tn as Pi,tr as Fi,tt as Ii,u as Li,ur as Ri,ut as zi,v as Bi,vr as Vi,vt as Hi,w as Ui,wn as Wi,wr as Gi,wt as Ki,x as qi,xn as Ji,xr as Yi,xt as Xi,y as Zi,yn as Qi,yr as $i,yt as ea,z as ta,zn as na,zr as ra,zt as ia}from"./context-indicator-BSGa1g7l.js";import{o as aa}from"./agent-store-CE4-QMOA.js";import{O as oa,b as sa,l as ca,p as la,v as ua}from"./workspace-manager-D6xww21F.js";var da=`panel-observer-`,fa=new Set([`STREAM_START`,`STREAM_CHUNK`,`STREAM_TOOL_CALL`,`STREAM_DONE`]),pa=new Map,ma=new Set;function ha(e){typeof e==`function`&&ma.add(e)}function ga(e){if(!e)return null;let t=pa.get(e);if(t)return t;let n;try{n=chrome.runtime.connect({name:`${da}${e}`})}catch(e){return r.debug(`[PanelObserver] 建立观察端口失败(忽略):`,e?.message||e),null}pa.set(e,n);try{n.onMessage.addListener(e=>{if(!e||!fa.has(e.type)||ma.size===0)return;let t=!0;for(let n of ma)try{n(e)}catch(e){t=!1,r.debug(`[PanelObserver] 消息处理异常(忽略):`,e?.message||e)}if(t&&e.seq)try{n.postMessage({type:`STREAM_CHUNK_ACK`,sessionId:e.sessionId,callId:e.callId,seq:e.seq})}catch(e){r.debug(`[PanelObserver] ACK 回发失败(忽略):`,e?.message||e)}})}catch(e){r.debug(`[PanelObserver] 消息监听挂不上(忽略):`,e?.message||e)}try{n.onDisconnect.addListener(()=>{pa.get(e)===n&&pa.delete(e)})}catch(e){r.debug(`[PanelObserver] 观察端口断开监听挂不上(忽略):`,e?.message||e)}return n}function _a(e){if(!e)return;let t=pa.get(e);if(t){pa.delete(e);try{t.disconnect()}catch(e){r.debug(`[PanelObserver] 关闭观察端口异常(忽略):`,e?.message||e)}}}function va({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 ya({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 ba=!1,xa=new Map,Sa=null,Ca=!1,wa=null,Ta=null,Ea=null,Da=250,Oa=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 ka(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 Aa(e,t){let n=new Map;return{start(){zt(e,``),Wn(``),Ft(Date.now()),Mi(t),jt(t)},chunk(n){zt(e,n),Tn(t,n)},restore({html:e}){zi(t,e)},toolCalls(e,n){typeof n==`string`&&n&&Bn(t,n),Er(t,e)},toolResult(e){oi(e,t)},agentStream(e){Xi(t,n),Ar(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){Hi(t,e,n)},preselect(e){let n=t.querySelector(`.message-content`);!n||!e.length||e.forEach(e=>n.insertBefore(ui(e),n.firstChild))},final(e,n,r={}){mr(t,e,n,r.reflectionScore,r.reasoningContent,r.wasRevised)},error(e,n){mr(t,e,n||[])}}}async function ja(e,t,n){let r=!!e.error,i={role:`assistant`,content:r?e.error:e.content||``,executionLog:e.executionLog||[],reflectionScore:e.reflectionScore,wasRevised:e.wasRevised||!1,callId:e.callId,resumed:!0,resumable:e.budgetEnded?`budget`:!1};if(!r&&n&&(i.messageId=n.dataset.messageId||void 0,i.htmlContent=n.dataset.htmlContent||n.outerHTML),v.activeSessionId===t){v.messageHistory.push(i);try{document.dispatchEvent(new CustomEvent(`session-cache-invalidate`,{detail:{sessionId:t}}))}catch{}}let{appendMessageToSession:a}=await T(async()=>{let{appendMessageToSession:e}=await import(`./context-indicator-BSGa1g7l.js`).then(e=>e.Cr);return{appendMessageToSession:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]));await a(t,i)}function Ma(){T(()=>import(`./context-indicator-BSGa1g7l.js`).then(e=>e.V).then(e=>e.syncPendingSessionsToStorage()),__vite__mapDeps([0,1,2,3,4,5,6,7,8])).catch(e=>r.debug(`[ChatReattach] 同步生成态失败(忽略):`,e?.message||e))}var Na=1e3;function Pa(e){return Promise.race([ni(e),new Promise(e=>setTimeout(()=>e(null),Na))])}function Fa(e,n){let i=Gr(e);if(i())return!1;let a=vi(e);a.dataset.callId=n,i(a),zt(e,``),Ft(Date.now()),Ki(Date.now()),v.pendingCallApiSessionIds.add(e),v.generatingSessionIds.add(e),Ma();try{document.dispatchEvent(new CustomEvent(`generating-state-changed`))}catch{}let o=va({sessionId:e,callId:n,awaitSnapshot:!0,renderer:Aa(e,a),persist:t=>ja(t,e,a),emptyFallback:t(`chatMsg.emptyModelReply`),onFinished:()=>{if(xa.get(e)===o){xa.delete(e),_a(e),v.pendingCallApiSessionIds.delete(e),Ma(),Vr(e);try{document.dispatchEvent(new CustomEvent(`session-cache-invalidate`,{detail:{sessionId:e}}))}catch{}rn(e)}}});return xa.set(e,o),ga(e),Pa(e).then(t=>{o.finished||xa.get(e)!==o||o.restore(t)}).catch(()=>o.restore(null)),v.activeSessionId===e&&ea(e),r.info(`[ChatReattach] 已接管运行中的任务: sessionId=${e}, callId=${n}`),!0}function Ia(e){let t=xa.get(e);if(!t)return;xa.delete(e),_a(e);try{t.dispose?.()}catch{}let n=Gr(e),r=n();try{r?.remove()}catch{}n(null),Vr(e),v.pendingCallApiSessionIds.delete(e),Ma();try{document.dispatchEvent(new CustomEvent(`generating-state-changed`))}catch{}}function La(){let e=Sa;e&&Promise.resolve().then(()=>e.syncFromBackground()).catch(e=>r.debug(`[ChatReattach] 对齐后台状态失败(忽略):`,e?.message||e))}function Ra(){!ba||!Sa||Ea||(Ea=setTimeout(()=>{Ea=null,La()},Da))}var za=new Map,Ba=3e3,Va=100,Ha=new Set,Ua=new Set([`API_COMPLETE`,`API_ERROR`]);function Wa(e,t){let n=`${e}|${t.callId}`;Ha.has(n)||(Ha.add(n),Ha.size>Va&&Ha.delete(Ha.values().next().value),Ia(e),Fa(e,t.callId)&&xa.get(e)?.handleMessage(t))}function Ga(e,t,n){let r=za.get(e);if(r){r.messages.push(n);return}r={callId:t,messages:[n]},za.set(e,r),ka(Ba).then(t=>Ka(e,t&&t.activeCallIds&&t.activeCallIds[e]||null)).catch(()=>Ka(e,null)).finally(()=>{za.delete(e)})}function Ka(e,t){let n=za.get(e);if(!n)return;let{callId:r,messages:i}=n;if(t===r)Ia(e),Fa(e,r);else if(t===null){let t=i.find(e=>Ua.has(e.type));if(!t)return;Wa(e,t);return}else return;let a=xa.get(e);if(!(!a||a.callId!==r))for(let e of i){if(a.finished)break;a.handleMessage(e)}}function qa(){if(Ca)return;Ca=!0;let e=e=>{if(!e||e.seq&&Oa.has(e.type)&&!Ut(`reattach:${e.sessionId}:${e.callId}`,e.seq))return!1;let t=e.sessionId?xa.get(e.sessionId):null;return t?e.callId&&e.callId!==t.callId?(Ga(e.sessionId,e.callId,e),!1):(ga(e.sessionId),t.handleMessage(e),!1):(e.callId&&Oa.has(e.type)&&Ra(),!1)};chrome.runtime.onMessage.addListener(e),ha(e),wa=e=>{let t=e?.detail?.sessionId;t&&xa.has(t)&&ea(t),Ra()},document.addEventListener(`session-hydrated`,wa),Ta=e=>{let t=e?.detail?.sessionId;t&&xa.has(t)&&ea(t)},document.addEventListener(`chat-history-rendered`,Ta)}function Ja(){return ba?{syncFromBackground:()=>Sa.syncFromBackground()}:(ba=!0,qa(),Sa=ya({queryRunning:ka,hasLocalListener:e=>v.pendingCancelApiMap.has(e),isAttached:(e,t)=>xa.get(e)?.callId===t?(ga(e),!0):!1,attach:(e,t)=>{Fa(e,t)}}),Sa.syncFromBackground(),{syncFromBackground:()=>Sa.syncFromBackground()})}function Ya(e){!ba||!Sa||(e&&v.activeSessionId===e&&ea(e),Sa.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 Xa=`sessionDockDismissed`,Za=5e3,Qa=250,$a=1200,eo=8,to=eo-1,no=9e4,ro={running:0,queued:1,done:2},io=new Map,ao=new Map,oo=new Map,so=new Map,co=new Set,lo=new Set,uo=new Map,fo=new Map,po=new Set,mo=new Set,ho=[],go=new Set,j=null,M=null,N=null,_o=[],vo=!1,yo=null,bo=null,xo=!1,So=null,Co=null;function wo(e){return e?Array.isArray(e)?e:e instanceof Set?Array.from(e):[]:[]}function To(e){let t=new Set;for(let n of wo(e))n&&t.add(h(String(n))||String(n));return t}function Eo({phase:e=``,sessionId:t=null,backendRunningIds:n=[],startedAt:r=0,lastUpdateAt:i=0,now:a=Date.now(),staleMs:o=no}={}){if(e!==`running`||!t||wo(n).includes(t))return!1;let s=Math.max(Number(r)||0,Number(i)||0);return s?a-s>=o:!1}var Do=160;function Oo(e){let t=String(e??``).replace(/\s+/g,` `).trim();if(!t)return``;let n=Array.from(t);return n.length<=Do?t:`${n.slice(0,Do).join(``).trimEnd()}…`}function ko(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 Ao({phase:e=``,queuedText:t=``,questionText:n=``,title:r=``}={}){let i=e===`queued`?Oo(t):``,a=i||Oo(n),o=Oo(r),s=a||o,c=i?`queued`:a?`question`:s?`title`:``;return{primary:s,sub:a&&!ko(o,a)?o:``,isQuestion:!!a,from:c}}function jo(e){let t=Array.isArray(e?.messageHistory)?e.messageHistory:[];for(let e=t.length-1;e>=0;--e){let n=t[e];if(!n||n.role!==`user`)continue;let r=ae(n.content);if(r&&String(r).trim())return{text:String(r),messageId:n.messageId?String(n.messageId):``}}return{text:``,messageId:``}}function Mo({activeSessionId:e=null,titles:t={},questions:n={},anchors:r={},queuedTexts:i={},generatingIds:a=[],pendingIds:o=[],runningIds:s=[],completedIds:c=[],queuedCounts:l={},scheduledIds:u=[],dismissedIds:d=[],nodeInfo:f={},startedAt:p={},doneAt:m={},lastUpdateAt:h={},now:g=Date.now(),staleMs:ee=no}={}){let te=wo(s),ne=new Set([...wo(a),...wo(o),...te]),_=new Set(wo(c)),v=new Set(wo(d)),re=new Set(wo(u)),y=l||{},b=new Set([...ne,..._,...Object.keys(y)]),x=[];for(let a of b){if(!a||a===e)continue;let o=Number(y[a])||0,s;if(ne.has(a))s=`running`;else if(o>0)s=`queued`;else if(_.has(a))s=`done`;else continue;let c=Eo({phase:s,sessionId:a,backendRunningIds:te,startedAt:p?.[a],lastUpdateAt:h?.[a],now:g,staleMs:ee});if(v.has(a)&&(s===`done`||c))continue;let l=f?.[a]||{},u=Ao({phase:s,queuedText:i?.[a]||``,questionText:n?.[a]||``,title:t?.[a]||``});x.push({sessionId:a,title:t?.[a]||``,primary:u.primary,sub:u.sub,isQuestion:u.isQuestion,anchorMessageId:u.from===`question`?String(r?.[a]||``):``,phase:s,stale:c,source:re.has(a)?`scheduled`:`chat`,queuedCount:o,nodeName:l.nodeName||``,subtaskIndex:l.subtaskIndex||0,subtaskTotal:l.subtaskTotal||0,startedAt:p?.[a]||0,doneAt:m?.[a]||0,lastUpdateAt:h?.[a]||0})}return x.sort((e,t)=>{let n=ro[e.phase]-ro[t.phase];if(n!==0)return n;if(e.stale!==t.stale)return e.stale?1:-1;let r=e.phase===`done`?e.doneAt:e.startedAt,i=t.phase===`done`?t.doneAt:t.startedAt;return r===i?String(e.sessionId).localeCompare(String(t.sessionId)):i-r}),x}function No(e){return mo.has(e)||v.generatingSessionIds.has(e)||v.pendingCallApiSessionIds.has(e)}function Po(){let e={};try{let t=gn();for(let n of t){let t=ti(n);t>0&&(e[n]=t)}}catch(e){r.debug(`[SessionDock] read queue counts failed:`,e?.message||e)}return e}function Fo(){let e={};for(let t of v.sessions||[])e[t.id]=t.title||``;for(let[t,n]of uo)e[t]||(e[t]=n);return e}function Io(){let e={},t={},n=new Map;for(let e of v.sessions||[])n.set(e.id,e);for(let r of new Set([...mo,...v.generatingSessionIds,...v.pendingCallApiSessionIds,...v.completedSessionIds])){let i=ao.get(r)||oo.get(r)||0,a=fo.get(r);if(i&&a&&a.stamp===i){a.text&&(e[r]=a.text,t[r]=a.messageId||``);continue}let o=jo(n.get(r));o.text&&(e[r]=o.text,t[r]=o.messageId)}return{questions:e,anchors:t}}function Lo(){let e={};try{for(let t of gn()){let n=bn(t);n?.text&&(e[t]=String(n.text))}}catch(e){r.debug(`[SessionDock] read queued texts failed:`,e?.message||e)}return e}function Ro(e){for(let t of e||[]){let e=t.sessionId;if(!e)continue;let n=t.startedAt||t.doneAt||0,i=fo.get(e),a=!i||i.stamp!==n,o=!t.title;!a&&!o||po.has(e)||(po.add(e),y(e).then(t=>{if(t&&((o||!uo.has(e))&&uo.set(e,t.title||``),a)){let r=jo(t);fo.set(e,{text:r.text,messageId:r.messageId,stamp:n})}}).catch(e=>{r.debug(`[SessionDock] hydrate label failed:`,e?.message||e)}).finally(()=>{po.delete(e),P()}))}}function zo(e){if(!e)return``;let t=new Date(e);return`${String(t.getHours()).padStart(2,`0`)}:${String(t.getMinutes()).padStart(2,`0`)}`}function Bo(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:zo(e.doneAt)}):t(`dock.done`)}function Vo(){let e=v.completedSessionIds;for(let e of new Set([...mo,...v.generatingSessionIds,...v.pendingCallApiSessionIds]))ao.has(e)||ao.set(e,Date.now()),oo.delete(e);for(let e of mo)lo.delete(e);for(let t of e)!oo.has(t)&&!No(t)&&oo.set(t,Date.now());let{questions:t,anchors:n}=Io(),r=Mo({activeSessionId:v.activeSessionId,titles:Fo(),questions:t,anchors:n,queuedTexts:Lo(),generatingIds:v.generatingSessionIds,pendingIds:v.pendingCallApiSessionIds,runningIds:mo,completedIds:e,queuedCounts:Po(),scheduledIds:co,dismissedIds:lo,nodeInfo:Object.fromEntries(io),startedAt:Object.fromEntries(ao),doneAt:Object.fromEntries(oo),lastUpdateAt:Object.fromEntries(so),now:Date.now()});return Ro(r),r}function Ho(e){let t=new Set(ho.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&&(go=new Set(n),So&&clearTimeout(So),So=setTimeout(()=>{So=null,go=new Set,P()},$a))}function Uo(){if(j||typeof document>`u`)return j;j=document.createElement(`div`),j.className=`session-dock`,j.id=`sessionDock`,j.setAttribute(`role`,`navigation`),document.body.appendChild(j),M=document.createElement(`div`),M.className=`session-dock-tip`,document.body.appendChild(M),Wo();let e=document.getElementById(`chatContainer`);return e&&typeof ResizeObserver<`u`&&new ResizeObserver(Wo).observe(e),window.addEventListener(`resize`,Wo),j}function Wo(){if(!j)return;let e=document.getElementById(`chatContainer`);if(!e)return;let t=e.getBoundingClientRect();j.style.top=`${Math.max(0,Math.round(t.top+8))}px`}function Go(e){pi(e.sessionId,{focusMessageId:e.anchorMessageId||null})}function Ko(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`),go.has(e.sessionId)&&n.classList.add(`is-flash`);let r=e.title||t(`dock.unknownSession`),i=e.primary||r,a=Bo(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`,()=>{Go(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(),as(e.sessionId)}),n.appendChild(r)}return n.addEventListener(`mouseenter`,()=>qo(n,e,a)),n.addEventListener(`mouseleave`,Jo),n.addEventListener(`focusin`,()=>qo(n,e,a)),n.addEventListener(`focusout`,Jo),n}function qo(e,n,r){if(!M)return;M.innerHTML=``;let i=document.createElement(`div`);i.className=`session-dock-tip-title`,i.textContent=n.primary||n.title||t(`dock.unknownSession`);let a=document.createElement(`div`);if(a.className=`session-dock-tip-status`,a.textContent=r,M.appendChild(i),n.sub){let e=document.createElement(`div`);e.className=`session-dock-tip-sub`,e.textContent=n.sub,M.appendChild(e)}M.appendChild(a);let o=e.getBoundingClientRect();M.style.top=`${Math.round(o.top)}px`,M.style.left=`${Math.round(o.right+8)}px`,M.classList.add(`show`)}function Jo(){M&&M.classList.remove(`show`)}function Yo(){return N||typeof document>`u`?N:(N=document.createElement(`div`),N.className=`session-dock-overflow`,N.setAttribute(`role`,`menu`),N.addEventListener(`mouseenter`,Xo),N.addEventListener(`mouseleave`,Zo),N.addEventListener(`focusin`,Xo),N.addEventListener(`focusout`,Zo),document.body.appendChild(N),N)}function Xo(){Co&&=(clearTimeout(Co),null)}function Zo(){vo||(Xo(),Co=setTimeout(()=>{Co=null,ns()},220))}function Qo(){let e=j?j.querySelector(`.session-dock-more`):null;e&&(e.setAttribute(`aria-expanded`,vo?`true`:`false`),e.classList.toggle(`is-open`,vo))}function $o(){let e=Yo();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 _o){let n=e.primary||e.title||t(`dock.unknownSession`),i=Bo(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`,()=>{ns(),Go(e)}),r.appendChild(a)}e.appendChild(r)}function es(){if(!N||!j)return;let e=j.querySelector(`.session-dock-item--more`);if(!e)return;let t=e.getBoundingClientRect();N.style.left=`${Math.round(t.right+8)}px`;let n=N.offsetHeight||0,r=Math.max(8,window.innerHeight-n-8);N.style.top=`${Math.round(Math.min(Math.max(8,t.top),r))}px`}function ts(){_o.length!==0&&Yo()&&(Xo(),$o(),es(),N.classList.add(`show`),Qo())}function ns(){Xo(),vo=!1,N&&N.classList.remove(`show`),Qo()}function rs(){if(N&&N.classList.contains(`show`)&&vo){ns();return}ts(),vo=!0,Qo()}function is(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`,vo?`true`:`false`),r.textContent=`+${e.length>99?`99`:e.length}`,r.addEventListener(`click`,()=>rs()),n.appendChild(r),n.addEventListener(`mouseenter`,()=>ts()),n.addEventListener(`mouseleave`,Zo),n.addEventListener(`focusin`,()=>ts()),n.addEventListener(`focusout`,Zo),n}function as(e){e&&(lo.add(e),os(),P())}function os(){try{chrome.storage.local.set({[Xa]:Array.from(lo)}).catch(()=>{})}catch{}}function ss(){try{chrome.storage.local.get([Xa],e=>{let t=e?.[Xa];if(Array.isArray(t)){for(let e of t)lo.add(e);P()}})}catch{}}function cs(){if(!Uo())return;let e=Vo();if(Ho(e),ho=e,ns(),_o=[],j.innerHTML=``,e.length===0){j.classList.remove(`show`),document.body.classList.remove(`has-session-dock`),Jo();return}let t=e.length>eo?to:eo;_o=e.slice(t);for(let n of e.slice(0,t))j.appendChild(Ko(n));_o.length>0&&j.appendChild(is(_o)),j.classList.add(`show`),document.body.classList.add(`has-session-dock`)}function P(){yo||=setTimeout(()=>{yo=null;try{cs()}catch(e){r.warn(`[SessionDock] render failed:`,e?.message||e)}},Qa)}function ls(){return new Promise(e=>{try{chrome.runtime.sendMessage({type:`QUERY_SESSION_RUNNING`},t=>{if(chrome.runtime.lastError||!t){e();return}Array.isArray(t.activeSessionIds)&&(mo=To(t.activeSessionIds)),e()})}catch{e()}})}function us(e){let t=e?.sessionId;if(!t)return;let n=io.get(t)||{};io.set(t,{nodeName:e.nodeName||n.nodeName||``,subtaskIndex:e.subtaskIndex||n.subtaskIndex||0,subtaskTotal:e.subtaskTotal||n.subtaskTotal||0}),so.set(t,Date.now()),P()}function ds(e){e&&(io.delete(e),ao.delete(e),oo.delete(e),so.delete(e),lo.delete(e),uo.delete(e),fo.delete(e),P())}function fs(){if(!(xo||typeof document>`u`||!Uo())){xo=!0,ss(),document.addEventListener(`generating-state-changed`,P),document.addEventListener(`session-switched`,P),document.addEventListener(`generation-ended`,e=>{let t=e?.detail?.sessionId;t&&!oo.has(t)&&oo.set(t,Date.now()),P()}),document.addEventListener(`session-archived`,e=>ds(e?.detail?.sessionId)),document.addEventListener(`session-deleted`,e=>ds(e?.detail?.sessionId));try{ra(P)}catch(e){r.debug(`[SessionDock] subscribe queue failed:`,e?.message||e)}try{chrome.runtime.onMessage.addListener(e=>e?e.type===`EXECUTION_STATUS_UPDATE`?(us(e),!1):e.type===`SCHEDULED_TASK_RUN_STATE`&&e.sessionId?(e.running?co.add(e.sessionId):co.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){ns();return}ls().then(P)}),document.addEventListener(`keydown`,e=>{e.key===`Escape`&&vo&&ns()}),bo||=setInterval(()=>{document.hidden||ls().then(P)},Za),ls().then(()=>{for(let e of mo)ao.has(e)||ao.set(e,Date.now());cs()})}}function ps(){let e=document.getElementById(`chatNavUp`),n=document.getElementById(`chatNavDown`),r=document.getElementById(`chatNavHotzone`),i=document.getElementById(`chatNavButtons`),a=document.getElementById(`chatNavQuestionPanel`),o=[],s=!1,c=null,l=``,u=!1,d=!1;function f(e){let t=document.getElementById(`chatContainer`);if(!t)return-1;let n=t.getBoundingClientRect();return et(e,n.top,n.bottom)}function p(e,t){let n=document.getElementById(`chatContainer`);if(!n)return`noop`;let r=Ye(n);if(r.length===0)return`noop`;let i=n.getBoundingClientRect().top;if(t){if(e===`prev`)r[0].start.scrollIntoView({behavior:`smooth`,block:`start`});else{let e=r[r.length-1].elements;e[e.length-1].scrollIntoView({behavior:`smooth`,block:`end`})}return`jumped`}let a=pt(r.length,$e(r,i),e);return a===null?(m(e),`blocked`):(r[a].start.scrollIntoView({behavior:`smooth`,block:`start`}),`jumped`)}function m(t){let r=t===`prev`?e:n;r&&(r.classList.remove(`blocked`),r.offsetWidth,r.classList.add(`blocked`),r.addEventListener(`animationend`,()=>r.classList.remove(`blocked`),{once:!0}))}function h(e,n){let r=a.querySelectorAll(`.chat-nav-question-item`);r.forEach(t=>{Number(t.dataset.groupIndex)===e?(t.classList.add(`current`),t.setAttribute(`aria-current`,`true`)):(t.classList.remove(`current`),t.setAttribute(`aria-current`,`false`))});let i=a.querySelector(`.chat-nav-question-header .count`);i&&(i.textContent=t(`chat.navPosition`,{current:e>=0?e+1:n,total:n}));let o=Array.from(r).find(t=>Number(t.dataset.groupIndex)===e);!d&&e>=0&&o&&o.scrollIntoView({block:`nearest`})}function g(){if(!a||!a.classList.contains(`expanded`))return;o=Ye(document.getElementById(`chatContainer`));let e=l?Ye(document.getElementById(`chatContainer`)).length:a.querySelectorAll(`.chat-nav-question-item`).length;if(o.length===0){a.innerHTML=``,a.classList.remove(`expanded`);return}if(!l&&e!==o.length){ee();return}h(f(o),o.length)}function ee(){if(!a)return!1;if(o=Ye(document.getElementById(`chatContainer`)),o.length===0)return a.innerHTML=``,!1;let e=f(o),t=document.activeElement===a.querySelector(`[data-role="nav-search"]`);a.innerHTML=Ze(o,e,s,l),a.querySelector(`.chat-nav-pin`).addEventListener(`click`,e=>{e.stopPropagation(),b()});let n=a.querySelector(`[data-role="nav-search"]`);if(n){let e=()=>{l!==n.value&&(l=n.value,ee())};n.addEventListener(`input`,t=>{t.isComposing||e()}),n.addEventListener(`compositionend`,e),t&&(n.focus(),n.setSelectionRange(n.value.length,n.value.length))}if(e>=0){let t=a.querySelector(`.chat-nav-question-item[data-group-index="${e}"]`);t&&t.scrollIntoView({block:`nearest`})}return!0}function te(){let e=document.activeElement;return e?[r,i,a].some(t=>t&&(t===e||t.contains(e))):!1}function ne(){i.classList.remove(`expanded`),a&&a.classList.remove(`expanded`)}function _(){let e=te();ne(),e&&r&&(u=!0,r.focus({preventScroll:!0}),u=!1)}function v(){if(clearTimeout(c),i.classList.add(`expanded`),a){if(a.classList.contains(`expanded`)){g();return}ee()?a.classList.add(`expanded`):a.classList.remove(`expanded`)}}function re(e){clearTimeout(c),!s&&(te()||(e?ne():c=setTimeout(ne,300)))}function y(e){if(s=e,r&&(r.classList.toggle(`pinned`,e),r.setAttribute(`aria-pressed`,String(e))),a){a.classList.toggle(`pinned`,e);let n=a.querySelector(`.chat-nav-pin`);if(n){let r=t(e?`chat.navUnpinLabel`:`chat.navPinLabel`);n.textContent=r,n.title=r,n.setAttribute(`aria-pressed`,String(e)),n.classList.toggle(`on`,e)}}}function b(){y(!s)}e&&e.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),p(`prev`,e.ctrlKey||e.metaKey),g()}),n&&n.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),p(`next`,e.ctrlKey||e.metaKey),g()}),r&&i&&(r.addEventListener(`mouseenter`,v),r.addEventListener(`mouseleave`,()=>re(!1)),r.addEventListener(`click`,()=>b()),r.addEventListener(`focus`,()=>{u||v()}),r.addEventListener(`blur`,()=>re(!1)),r.addEventListener(`keydown`,e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),b())}),i.addEventListener(`mouseenter`,v),i.addEventListener(`mouseleave`,()=>re(!1)),i.addEventListener(`focusin`,v),a&&(a.addEventListener(`mouseenter`,()=>{d=!0,v()}),a.addEventListener(`mouseleave`,()=>{d=!1,re(!1)}),a.addEventListener(`focusin`,v),a.addEventListener(`keydown`,e=>{if(e.target.matches(`[data-role="nav-search"]`))return;let t=Array.from(a.querySelectorAll(`.chat-nav-question-item`));if(t.length===0)return;let n=t.indexOf(document.activeElement),r=null;e.key===`ArrowDown`?r=Math.min(n+1,t.length-1):e.key===`ArrowUp`?r=n<=0?0:n-1:e.key===`Home`?r=0:e.key===`End`&&(r=t.length-1),r!==null&&(e.preventDefault(),t[r].focus())}),a.addEventListener(`click`,e=>{let t=e.target.closest(`.chat-nav-question-item`);if(!t||!t.dataset.messageId)return;let n=o.find(e=>(e.userElement||e.start).dataset.messageId===t.dataset.messageId);if(!n)return;let r=n.userElement||n.start;r.scrollIntoView({behavior:`instant`,block:`start`}),r.classList.add(`bookmark-highlight`),setTimeout(()=>r.classList.remove(`bookmark-highlight`),2e3),s?g():_()})));{let e=document.getElementById(`chatContainer`);if(e){let t=!1;e.addEventListener(`scroll`,()=>{!a||!a.classList.contains(`expanded`)||t||(t=!0,requestAnimationFrame(()=>{t=!1,g()}))},{passive:!0})}}function x(){let e=a&&a.classList.contains(`expanded`);if(!s&&!e)return!1;if(a&&a.querySelector(`[data-role="nav-search"]`)&&l){l=``,ee();let e=a.querySelector(`[data-role="nav-search"]`);return e&&e.focus(),!0}return y(!1),_(),!0}return{jumpToMessage:p,updateActiveQuestion:g,handleEscape:x,isPinned:()=>s}}function ms(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 hs=!1,gs=!1,F=[],_s=``;function vs(){v.searchInputHistory=[],v.searchInputHistoryIndex=-1;try{chrome.storage.local.get([`searchInputHistory`],e=>{e.searchInputHistory&&(v.searchInputHistory=e.searchInputHistory)})}catch{}let e=document.createElement(`div`);e.className=`search-panel-container`,e.id=`searchPanelContainer`,e.innerHTML=`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/context-indicator-C9mzVLvn.js","assets/chunk-CMxvf4Kt.js","assets/model-profiles-CnoNptrq.js","assets/i18n-DvmxOw8q.js","assets/voice-shortcut-Dx863RGz.js","assets/session-store-D1DoNmsx.js","assets/version-COKYeDot.js","assets/agent-store-BirQwOYv.js","assets/workspace-manager-C6QooYXS.js"])))=>i.map(i=>d[i]);
2
+ import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-DvmxOw8q.js";import{A as s,At as c,Bt as l,Ht as u,J as d,Jt as f,L as p,Lt as m,M as h,Nt as g,Ot as ee,P as te,R as ne,U as _,b as v,c as re,ct as y,d as b,gt as x,ht as ie,i as S,it as C,jt as ae,k as oe,q as w,r as se,rt as ce,u as T,wt as le,x as E,y as ue,zt as de}from"./model-profiles-CnoNptrq.js";import{_ as D,d as fe}from"./session-store-D1DoNmsx.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-9Y3xlrBG.js";import{$ as Ge,A as k,B as Ke,D as qe,E as Je,G as Ye,J as A,K as Xe,L as Ze,M as Qe,N as $e,O as et,Q as tt,U as nt,V as rt,W as it,X as at,Z as ot,_ as st,et as ct,g as lt,j,k as ut,l as dt,q as ft,t as pt,v as mt,w as ht,y as gt}from"./version-COKYeDot.js";import{$ as _t,$n as vt,$t as yt,A as bt,An as xt,Ar as St,At as Ct,B as wt,Bn as Tt,Br as Et,Bt as Dt,C as Ot,Cn as kt,Cr as At,Ct as jt,D as Mt,Dn as Nt,Dr as Pt,Dt as Ft,E as It,En as Lt,Er as Rt,Et as zt,F as Bt,Fn as Vt,Fr as Ht,Ft as Ut,G as Wt,Gn as Gt,Gr as Kt,Gt as qt,H as Jt,Hn as Yt,Hr as Xt,Ht as Zt,I as Qt,In as $t,Ir as en,It as tn,J as nn,Jn as rn,Jt as an,K as on,Kn as sn,Kt as cn,L as ln,Ln as un,Lr as dn,Lt as fn,M as pn,Mn as mn,Mr as hn,Mt as gn,N as _n,Nn as vn,Nr as yn,Nt as bn,O as xn,On as Sn,Or as Cn,Ot as wn,P as Tn,Pn as En,Pr as Dn,Pt as On,Q as kn,Qn as An,Qt as jn,R as Mn,Rn as Nn,Rr as Pn,Rt as Fn,S as In,Sn as Ln,St as Rn,T as zn,Tn as Bn,Tr as Vn,Tt as Hn,U as Un,Un as Wn,Ur as Gn,Ut as Kn,Vn as qn,Vr as Jn,Vt as Yn,W as Xn,Wn as Zn,Wr as Qn,Wt as $n,X as er,Xn as tr,Xt as nr,Y as rr,Yn as ir,Yt as ar,Z as or,Zn as sr,Zt as cr,_ as lr,_r as ur,_t as dr,a as fr,an as pr,ar as mr,at as hr,b as gr,bn as _r,br as vr,bt as yr,c as br,cn as xr,cr as Sr,ct as Cr,d as wr,dn as Tr,dr as Er,dt as Dr,en as Or,er as kr,et as Ar,f as jr,fn as Mr,fr as Nr,ft as Pr,g as Fr,gn as Ir,gr as Lr,gt as Rr,h as zr,hn as Br,hr as Vr,ht as Hr,i as Ur,in as Wr,ir as Gr,it as Kr,j as qr,jn as Jr,jr as Yr,jt as Xr,k as Zr,kn as Qr,kr as $r,kt as ei,l as ti,lr as ni,lt as ri,m as ii,mn as ai,mr as oi,mt as si,n as ci,nn as li,nr as ui,nt as di,o as fi,on as pi,or as mi,ot as hi,p as gi,pn as _i,pr as vi,q as yi,qn as bi,qt as xi,r as Si,rn as Ci,rt as wi,s as Ti,sn as Ei,sr as Di,st as Oi,t as ki,tn as Ai,tr as ji,tt as Mi,u as Ni,un as Pi,ur as Fi,ut as Ii,v as Li,vn as Ri,vr as zi,vt as Bi,w as Vi,wn as Hi,wr as Ui,wt as Wi,x as Gi,xn as Ki,xr as qi,xt as Ji,y as Yi,yn as Xi,yr as Zi,yt as Qi,z as $i,zn as ea,zr as ta,zt as na}from"./context-indicator-C9mzVLvn.js";import{o as ra}from"./agent-store-BirQwOYv.js";import{O as ia,b as aa,l as oa,p as sa,v as ca}from"./workspace-manager-C6QooYXS.js";var la=`panel-observer-`,ua=new Map;function da(e){if(!e)return null;let t=ua.get(e);if(t)return t;let n;try{n=chrome.runtime.connect({name:`${la}${e}`})}catch(e){return r.debug(`[PanelObserver] 建立观察端口失败(忽略):`,e?.message||e),null}ua.set(e,n);try{n.onDisconnect.addListener(()=>{ua.get(e)===n&&ua.delete(e)})}catch(e){r.debug(`[PanelObserver] 观察端口断开监听挂不上(忽略):`,e?.message||e)}return n}function fa(e){if(!e)return;let t=ua.get(e);if(t){ua.delete(e);try{t.disconnect()}catch(e){r.debug(`[PanelObserver] 关闭观察端口异常(忽略):`,e?.message||e)}}}function pa({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 ma({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 ha=!1,ga=new Map,_a=null,va=!1,ya=null,ba=null,xa=null,Sa=250,Ca=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 wa(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 Ta(e,t){let n=new Map;return{start(){zt(e,``),Hn(``),Ft(Date.now()),Oi(t),jt(t)},chunk(n){zt(e,n),wn(t,n)},restore({html:e}){Ii(t,e)},toolCalls(e,n){typeof n==`string`&&n&&Rn(t,n),Cr(t,e)},toolResult(e){ri(e,t)},agentStream(e){Ji(t,n),Dr(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){Bi(t,e,n)},preselect(e){let n=t.querySelector(`.message-content`);!n||!e.length||e.forEach(e=>n.insertBefore(si(e),n.firstChild))},final(e,n,r={}){dr(t,e,n,r.reflectionScore,r.reasoningContent,r.wasRevised)},error(e,n){dr(t,e,n||[])}}}async function Ea(e,t,n){let r=!!e.error,i={role:`assistant`,content:r?e.error:e.content||``,executionLog:e.executionLog||[],reflectionScore:e.reflectionScore,wasRevised:e.wasRevised||!1,callId:e.callId,resumed:!0,resumable:e.budgetEnded?`budget`:!1};if(!r&&n&&(i.messageId=n.dataset.messageId||void 0,i.htmlContent=n.dataset.htmlContent||n.outerHTML),v.activeSessionId===t){v.messageHistory.push(i);try{document.dispatchEvent(new CustomEvent(`session-cache-invalidate`,{detail:{sessionId:t}}))}catch{}}let{appendMessageToSession:a}=await E(async()=>{let{appendMessageToSession:e}=await import(`./context-indicator-C9mzVLvn.js`).then(e=>e.Sr);return{appendMessageToSession:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]));await a(t,i)}function Da(){E(()=>import(`./context-indicator-C9mzVLvn.js`).then(e=>e.V).then(e=>e.syncPendingSessionsToStorage()),__vite__mapDeps([0,1,2,3,4,5,6,7,8])).catch(e=>r.debug(`[ChatReattach] 同步生成态失败(忽略):`,e?.message||e))}var Oa=1e3;function ka(e){return Promise.race([ei(e),new Promise(e=>setTimeout(()=>e(null),Oa))])}function Aa(e,n){let i=Hr(e);if(i())return!1;let a=hi(e);a.dataset.callId=n,i(a),zt(e,``),Ft(Date.now()),Wi(Date.now()),v.pendingCallApiSessionIds.add(e),v.generatingSessionIds.add(e),Da();try{document.dispatchEvent(new CustomEvent(`generating-state-changed`))}catch{}let o=pa({sessionId:e,callId:n,awaitSnapshot:!0,renderer:Ta(e,a),persist:t=>Ea(t,e,a),emptyFallback:t(`chatMsg.emptyModelReply`),onFinished:()=>{if(ga.get(e)===o){ga.delete(e),fa(e),v.pendingCallApiSessionIds.delete(e),Da(),Rr(e);try{document.dispatchEvent(new CustomEvent(`session-cache-invalidate`,{detail:{sessionId:e}}))}catch{}bi(e)}}});return ga.set(e,o),da(e),ka(e).then(t=>{o.finished||ga.get(e)!==o||o.restore(t)}).catch(()=>o.restore(null)),v.activeSessionId===e&&Qi(e),r.info(`[ChatReattach] 已接管运行中的任务: sessionId=${e}, callId=${n}`),!0}function ja(e){let t=ga.get(e);if(!t)return;ga.delete(e),fa(e);try{t.dispose?.()}catch{}let n=Hr(e),r=n();try{r?.remove()}catch{}n(null),Rr(e),v.pendingCallApiSessionIds.delete(e),Da();try{document.dispatchEvent(new CustomEvent(`generating-state-changed`))}catch{}}function Ma(){let e=_a;e&&Promise.resolve().then(()=>e.syncFromBackground()).catch(e=>r.debug(`[ChatReattach] 对齐后台状态失败(忽略):`,e?.message||e))}function Na(){!ha||!_a||xa||(xa=setTimeout(()=>{xa=null,Ma()},Sa))}var Pa=new Map,Fa=3e3,Ia=100,La=new Set,Ra=new Set([`API_COMPLETE`,`API_ERROR`]);function za(e,t){let n=`${e}|${t.callId}`;La.has(n)||(La.add(n),La.size>Ia&&La.delete(La.values().next().value),ja(e),Aa(e,t.callId)&&ga.get(e)?.handleMessage(t))}function Ba(e,t,n){let r=Pa.get(e);if(r){r.messages.push(n);return}r={callId:t,messages:[n]},Pa.set(e,r),wa(Fa).then(t=>Va(e,t&&t.activeCallIds&&t.activeCallIds[e]||null)).catch(()=>Va(e,null)).finally(()=>{Pa.delete(e)})}function Va(e,t){let n=Pa.get(e);if(!n)return;let{callId:r,messages:i}=n;if(t===r)ja(e),Aa(e,r);else if(t===null){let t=i.find(e=>Ra.has(e.type));if(!t)return;za(e,t);return}else return;let a=ga.get(e);if(!(!a||a.callId!==r))for(let e of i){if(a.finished)break;a.handleMessage(e)}}function Ha(){va||(va=!0,chrome.runtime.onMessage.addListener(e=>{if(!e)return!1;let t=e.sessionId?ga.get(e.sessionId):null;return t?e.callId&&e.callId!==t.callId?(Ba(e.sessionId,e.callId,e),!1):(da(e.sessionId),t.handleMessage(e),!1):(e.callId&&Ca.has(e.type)&&Na(),!1)}),ya=e=>{let t=e?.detail?.sessionId;t&&ga.has(t)&&Qi(t),Na()},document.addEventListener(`session-hydrated`,ya),ba=e=>{let t=e?.detail?.sessionId;t&&ga.has(t)&&Qi(t)},document.addEventListener(`chat-history-rendered`,ba))}function Ua(){return ha?{syncFromBackground:()=>_a.syncFromBackground()}:(ha=!0,Ha(),_a=ma({queryRunning:wa,hasLocalListener:e=>v.pendingCancelApiMap.has(e),isAttached:(e,t)=>ga.get(e)?.callId===t?(da(e),!0):!1,attach:(e,t)=>{Aa(e,t)}}),_a.syncFromBackground(),{syncFromBackground:()=>_a.syncFromBackground()})}function Wa(e){!ha||!_a||(e&&v.activeSessionId===e&&Qi(e),_a.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 Ga=`sessionDockDismissed`,Ka=5e3,qa=250,Ja=1200,Ya=8,Xa=Ya-1,Za=9e4,Qa={running:0,queued:1,done:2},$a=new Map,eo=new Map,to=new Map,no=new Map,ro=new Set,io=new Set,ao=new Map,oo=new Map,so=new Set,co=new Set,lo=[],uo=new Set,M=null,fo=null,N=null,po=[],mo=!1,ho=null,go=null,_o=!1,vo=null,yo=null;function bo(e){return e?Array.isArray(e)?e:e instanceof Set?Array.from(e):[]:[]}function xo(e){let t=new Set;for(let n of bo(e))n&&t.add(h(String(n))||String(n));return t}function So({phase:e=``,sessionId:t=null,backendRunningIds:n=[],startedAt:r=0,lastUpdateAt:i=0,now:a=Date.now(),staleMs:o=Za}={}){if(e!==`running`||!t||bo(n).includes(t))return!1;let s=Math.max(Number(r)||0,Number(i)||0);return s?a-s>=o:!1}var Co=160;function wo(e){let t=String(e??``).replace(/\s+/g,` `).trim();if(!t)return``;let n=Array.from(t);return n.length<=Co?t:`${n.slice(0,Co).join(``).trimEnd()}…`}function To(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 Eo({phase:e=``,queuedText:t=``,questionText:n=``,title:r=``}={}){let i=e===`queued`?wo(t):``,a=i||wo(n),o=wo(r),s=a||o,c=i?`queued`:a?`question`:s?`title`:``;return{primary:s,sub:a&&!To(o,a)?o:``,isQuestion:!!a,from:c}}function Do(e){let t=Array.isArray(e?.messageHistory)?e.messageHistory:[];for(let e=t.length-1;e>=0;--e){let n=t[e];if(!n||n.role!==`user`)continue;let r=ae(n.content);if(r&&String(r).trim())return{text:String(r),messageId:n.messageId?String(n.messageId):``}}return{text:``,messageId:``}}function Oo({activeSessionId:e=null,titles:t={},questions:n={},anchors:r={},queuedTexts:i={},generatingIds:a=[],pendingIds:o=[],runningIds:s=[],completedIds:c=[],queuedCounts:l={},scheduledIds:u=[],dismissedIds:d=[],nodeInfo:f={},startedAt:p={},doneAt:m={},lastUpdateAt:h={},now:g=Date.now(),staleMs:ee=Za}={}){let te=bo(s),ne=new Set([...bo(a),...bo(o),...te]),_=new Set(bo(c)),v=new Set(bo(d)),re=new Set(bo(u)),y=l||{},b=new Set([...ne,..._,...Object.keys(y)]),x=[];for(let a of b){if(!a||a===e)continue;let o=Number(y[a])||0,s;if(ne.has(a))s=`running`;else if(o>0)s=`queued`;else if(_.has(a))s=`done`;else continue;let c=So({phase:s,sessionId:a,backendRunningIds:te,startedAt:p?.[a],lastUpdateAt:h?.[a],now:g,staleMs:ee});if(v.has(a)&&(s===`done`||c))continue;let l=f?.[a]||{},u=Eo({phase:s,queuedText:i?.[a]||``,questionText:n?.[a]||``,title:t?.[a]||``});x.push({sessionId:a,title:t?.[a]||``,primary:u.primary,sub:u.sub,isQuestion:u.isQuestion,anchorMessageId:u.from===`question`?String(r?.[a]||``):``,phase:s,stale:c,source:re.has(a)?`scheduled`:`chat`,queuedCount:o,nodeName:l.nodeName||``,subtaskIndex:l.subtaskIndex||0,subtaskTotal:l.subtaskTotal||0,startedAt:p?.[a]||0,doneAt:m?.[a]||0,lastUpdateAt:h?.[a]||0})}return x.sort((e,t)=>{let n=Qa[e.phase]-Qa[t.phase];if(n!==0)return n;if(e.stale!==t.stale)return e.stale?1:-1;let r=e.phase===`done`?e.doneAt:e.startedAt,i=t.phase===`done`?t.doneAt:t.startedAt;return r===i?String(e.sessionId).localeCompare(String(t.sessionId)):i-r}),x}function ko(e){return co.has(e)||v.generatingSessionIds.has(e)||v.pendingCallApiSessionIds.has(e)}function Ao(){let e={};try{let t=Yr();for(let n of t){let t=Cn(n);t>0&&(e[n]=t)}}catch(e){r.debug(`[SessionDock] read queue counts failed:`,e?.message||e)}return e}function jo(){let e={};for(let t of v.sessions||[])e[t.id]=t.title||``;for(let[t,n]of ao)e[t]||(e[t]=n);return e}function Mo(){let e={},t={},n=new Map;for(let e of v.sessions||[])n.set(e.id,e);for(let r of new Set([...co,...v.generatingSessionIds,...v.pendingCallApiSessionIds,...v.completedSessionIds])){let i=eo.get(r)||to.get(r)||0,a=oo.get(r);if(i&&a&&a.stamp===i){a.text&&(e[r]=a.text,t[r]=a.messageId||``);continue}let o=Do(n.get(r));o.text&&(e[r]=o.text,t[r]=o.messageId)}return{questions:e,anchors:t}}function No(){let e={};try{for(let t of Yr()){let n=hn(t);n?.text&&(e[t]=String(n.text))}}catch(e){r.debug(`[SessionDock] read queued texts failed:`,e?.message||e)}return e}function Po(e){for(let t of e||[]){let e=t.sessionId;if(!e)continue;let n=t.startedAt||t.doneAt||0,i=oo.get(e),a=!i||i.stamp!==n,o=!t.title;!a&&!o||so.has(e)||(so.add(e),y(e).then(t=>{if(t&&((o||!ao.has(e))&&ao.set(e,t.title||``),a)){let r=Do(t);oo.set(e,{text:r.text,messageId:r.messageId,stamp:n})}}).catch(e=>{r.debug(`[SessionDock] hydrate label failed:`,e?.message||e)}).finally(()=>{so.delete(e),P()}))}}function Fo(e){if(!e)return``;let t=new Date(e);return`${String(t.getHours()).padStart(2,`0`)}:${String(t.getMinutes()).padStart(2,`0`)}`}function Io(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:Fo(e.doneAt)}):t(`dock.done`)}function Lo(){let e=v.completedSessionIds;for(let e of new Set([...co,...v.generatingSessionIds,...v.pendingCallApiSessionIds]))eo.has(e)||eo.set(e,Date.now()),to.delete(e);for(let e of co)io.delete(e);for(let t of e)!to.has(t)&&!ko(t)&&to.set(t,Date.now());let{questions:t,anchors:n}=Mo(),r=Oo({activeSessionId:v.activeSessionId,titles:jo(),questions:t,anchors:n,queuedTexts:No(),generatingIds:v.generatingSessionIds,pendingIds:v.pendingCallApiSessionIds,runningIds:co,completedIds:e,queuedCounts:Ao(),scheduledIds:ro,dismissedIds:io,nodeInfo:Object.fromEntries($a),startedAt:Object.fromEntries(eo),doneAt:Object.fromEntries(to),lastUpdateAt:Object.fromEntries(no),now:Date.now()});return Po(r),r}function Ro(e){let t=new Set(lo.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&&(uo=new Set(n),vo&&clearTimeout(vo),vo=setTimeout(()=>{vo=null,uo=new Set,P()},Ja))}function zo(){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),fo=document.createElement(`div`),fo.className=`session-dock-tip`,document.body.appendChild(fo),Bo();let e=document.getElementById(`chatContainer`);return e&&typeof ResizeObserver<`u`&&new ResizeObserver(Bo).observe(e),window.addEventListener(`resize`,Bo),M}function Bo(){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 Vo(e){ji(e.sessionId,{focusMessageId:e.anchorMessageId||null})}function Ho(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`),uo.has(e.sessionId)&&n.classList.add(`is-flash`);let r=e.title||t(`dock.unknownSession`),i=e.primary||r,a=Io(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`,()=>{Vo(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(),ts(e.sessionId)}),n.appendChild(r)}return n.addEventListener(`mouseenter`,()=>Uo(n,e,a)),n.addEventListener(`mouseleave`,Wo),n.addEventListener(`focusin`,()=>Uo(n,e,a)),n.addEventListener(`focusout`,Wo),n}function Uo(e,n,r){if(!fo)return;fo.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,fo.appendChild(i),n.sub){let e=document.createElement(`div`);e.className=`session-dock-tip-sub`,e.textContent=n.sub,fo.appendChild(e)}fo.appendChild(a);let o=e.getBoundingClientRect();fo.style.top=`${Math.round(o.top)}px`,fo.style.left=`${Math.round(o.right+8)}px`,fo.classList.add(`show`)}function Wo(){fo&&fo.classList.remove(`show`)}function Go(){return N||typeof document>`u`?N:(N=document.createElement(`div`),N.className=`session-dock-overflow`,N.setAttribute(`role`,`menu`),N.addEventListener(`mouseenter`,Ko),N.addEventListener(`mouseleave`,qo),N.addEventListener(`focusin`,Ko),N.addEventListener(`focusout`,qo),document.body.appendChild(N),N)}function Ko(){yo&&=(clearTimeout(yo),null)}function qo(){mo||(Ko(),yo=setTimeout(()=>{yo=null,Qo()},220))}function Jo(){let e=M?M.querySelector(`.session-dock-more`):null;e&&(e.setAttribute(`aria-expanded`,mo?`true`:`false`),e.classList.toggle(`is-open`,mo))}function Yo(){let e=Go();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 po){let n=e.primary||e.title||t(`dock.unknownSession`),i=Io(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`,()=>{Qo(),Vo(e)}),r.appendChild(a)}e.appendChild(r)}function Xo(){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 Zo(){po.length!==0&&Go()&&(Ko(),Yo(),Xo(),N.classList.add(`show`),Jo())}function Qo(){Ko(),mo=!1,N&&N.classList.remove(`show`),Jo()}function $o(){if(N&&N.classList.contains(`show`)&&mo){Qo();return}Zo(),mo=!0,Jo()}function es(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`,mo?`true`:`false`),r.textContent=`+${e.length>99?`99`:e.length}`,r.addEventListener(`click`,()=>$o()),n.appendChild(r),n.addEventListener(`mouseenter`,()=>Zo()),n.addEventListener(`mouseleave`,qo),n.addEventListener(`focusin`,()=>Zo()),n.addEventListener(`focusout`,qo),n}function ts(e){e&&(io.add(e),ns(),P())}function ns(){try{chrome.storage.local.set({[Ga]:Array.from(io)}).catch(()=>{})}catch{}}function rs(){try{chrome.storage.local.get([Ga],e=>{let t=e?.[Ga];if(Array.isArray(t)){for(let e of t)io.add(e);P()}})}catch{}}function is(){if(!zo())return;let e=Lo();if(Ro(e),lo=e,Qo(),po=[],M.innerHTML=``,e.length===0){M.classList.remove(`show`),document.body.classList.remove(`has-session-dock`),Wo();return}let t=e.length>Ya?Xa:Ya;po=e.slice(t);for(let n of e.slice(0,t))M.appendChild(Ho(n));po.length>0&&M.appendChild(es(po)),M.classList.add(`show`),document.body.classList.add(`has-session-dock`)}function P(){ho||=setTimeout(()=>{ho=null;try{is()}catch(e){r.warn(`[SessionDock] render failed:`,e?.message||e)}},qa)}function as(){return new Promise(e=>{try{chrome.runtime.sendMessage({type:`QUERY_SESSION_RUNNING`},t=>{if(chrome.runtime.lastError||!t){e();return}Array.isArray(t.activeSessionIds)&&(co=xo(t.activeSessionIds)),e()})}catch{e()}})}function os(e){let t=e?.sessionId;if(!t)return;let n=$a.get(t)||{};$a.set(t,{nodeName:e.nodeName||n.nodeName||``,subtaskIndex:e.subtaskIndex||n.subtaskIndex||0,subtaskTotal:e.subtaskTotal||n.subtaskTotal||0}),no.set(t,Date.now()),P()}function ss(e){e&&($a.delete(e),eo.delete(e),to.delete(e),no.delete(e),io.delete(e),ao.delete(e),oo.delete(e),P())}function cs(){if(!(_o||typeof document>`u`||!zo())){_o=!0,rs(),document.addEventListener(`generating-state-changed`,P),document.addEventListener(`session-switched`,P),document.addEventListener(`generation-ended`,e=>{let t=e?.detail?.sessionId;t&&!to.has(t)&&to.set(t,Date.now()),P()}),document.addEventListener(`session-archived`,e=>ss(e?.detail?.sessionId)),document.addEventListener(`session-deleted`,e=>ss(e?.detail?.sessionId));try{Pn(P)}catch(e){r.debug(`[SessionDock] subscribe queue failed:`,e?.message||e)}try{chrome.runtime.onMessage.addListener(e=>e?e.type===`EXECUTION_STATUS_UPDATE`?(os(e),!1):e.type===`SCHEDULED_TASK_RUN_STATE`&&e.sessionId?(e.running?ro.add(e.sessionId):ro.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){Qo();return}as().then(P)}),document.addEventListener(`keydown`,e=>{e.key===`Escape`&&mo&&Qo()}),go||=setInterval(()=>{document.hidden||as().then(P)},Ka),as().then(()=>{for(let e of co)eo.has(e)||eo.set(e,Date.now());is()})}}function ls(){let e=document.getElementById(`chatNavUp`),n=document.getElementById(`chatNavDown`),r=document.getElementById(`chatNavHotzone`),i=document.getElementById(`chatNavButtons`),a=document.getElementById(`chatNavQuestionPanel`),o=[],s=!1,c=null,l=``,u=!1,d=!1;function f(e){let t=document.getElementById(`chatContainer`);if(!t)return-1;let n=t.getBoundingClientRect();return $e(e,n.top,n.bottom)}function p(e,t){let n=document.getElementById(`chatContainer`);if(!n)return`noop`;let r=Je(n);if(r.length===0)return`noop`;let i=n.getBoundingClientRect().top;if(t){if(e===`prev`)r[0].start.scrollIntoView({behavior:`smooth`,block:`start`});else{let e=r[r.length-1].elements;e[e.length-1].scrollIntoView({behavior:`smooth`,block:`end`})}return`jumped`}let a=ft(r.length,Qe(r,i),e);return a===null?(m(e),`blocked`):(r[a].start.scrollIntoView({behavior:`smooth`,block:`start`}),`jumped`)}function m(t){let r=t===`prev`?e:n;r&&(r.classList.remove(`blocked`),r.offsetWidth,r.classList.add(`blocked`),r.addEventListener(`animationend`,()=>r.classList.remove(`blocked`),{once:!0}))}function h(e,n){let r=a.querySelectorAll(`.chat-nav-question-item`);r.forEach(t=>{Number(t.dataset.groupIndex)===e?(t.classList.add(`current`),t.setAttribute(`aria-current`,`true`)):(t.classList.remove(`current`),t.setAttribute(`aria-current`,`false`))});let i=a.querySelector(`.chat-nav-question-header .count`);i&&(i.textContent=t(`chat.navPosition`,{current:e>=0?e+1:n,total:n}));let o=Array.from(r).find(t=>Number(t.dataset.groupIndex)===e);!d&&e>=0&&o&&o.scrollIntoView({block:`nearest`})}function g(){if(!a||!a.classList.contains(`expanded`))return;o=Je(document.getElementById(`chatContainer`));let e=l?Je(document.getElementById(`chatContainer`)).length:a.querySelectorAll(`.chat-nav-question-item`).length;if(o.length===0){a.innerHTML=``,a.classList.remove(`expanded`);return}if(!l&&e!==o.length){ee();return}h(f(o),o.length)}function ee(){if(!a)return!1;if(o=Je(document.getElementById(`chatContainer`)),o.length===0)return a.innerHTML=``,!1;let e=f(o),t=document.activeElement===a.querySelector(`[data-role="nav-search"]`);a.innerHTML=Xe(o,e,s,l),a.querySelector(`.chat-nav-pin`).addEventListener(`click`,e=>{e.stopPropagation(),b()});let n=a.querySelector(`[data-role="nav-search"]`);if(n){let e=()=>{l!==n.value&&(l=n.value,ee())};n.addEventListener(`input`,t=>{t.isComposing||e()}),n.addEventListener(`compositionend`,e),t&&(n.focus(),n.setSelectionRange(n.value.length,n.value.length))}if(e>=0){let t=a.querySelector(`.chat-nav-question-item[data-group-index="${e}"]`);t&&t.scrollIntoView({block:`nearest`})}return!0}function te(){let e=document.activeElement;return e?[r,i,a].some(t=>t&&(t===e||t.contains(e))):!1}function ne(){i.classList.remove(`expanded`),a&&a.classList.remove(`expanded`)}function _(){let e=te();ne(),e&&r&&(u=!0,r.focus({preventScroll:!0}),u=!1)}function v(){if(clearTimeout(c),i.classList.add(`expanded`),a){if(a.classList.contains(`expanded`)){g();return}ee()?a.classList.add(`expanded`):a.classList.remove(`expanded`)}}function re(e){clearTimeout(c),!s&&(te()||(e?ne():c=setTimeout(ne,300)))}function y(e){if(s=e,r&&(r.classList.toggle(`pinned`,e),r.setAttribute(`aria-pressed`,String(e))),a){a.classList.toggle(`pinned`,e);let n=a.querySelector(`.chat-nav-pin`);if(n){let r=t(e?`chat.navUnpinLabel`:`chat.navPinLabel`);n.textContent=r,n.title=r,n.setAttribute(`aria-pressed`,String(e)),n.classList.toggle(`on`,e)}}}function b(){y(!s)}e&&e.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),p(`prev`,e.ctrlKey||e.metaKey),g()}),n&&n.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),p(`next`,e.ctrlKey||e.metaKey),g()}),r&&i&&(r.addEventListener(`mouseenter`,v),r.addEventListener(`mouseleave`,()=>re(!1)),r.addEventListener(`click`,()=>b()),r.addEventListener(`focus`,()=>{u||v()}),r.addEventListener(`blur`,()=>re(!1)),r.addEventListener(`keydown`,e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),b())}),i.addEventListener(`mouseenter`,v),i.addEventListener(`mouseleave`,()=>re(!1)),i.addEventListener(`focusin`,v),a&&(a.addEventListener(`mouseenter`,()=>{d=!0,v()}),a.addEventListener(`mouseleave`,()=>{d=!1,re(!1)}),a.addEventListener(`focusin`,v),a.addEventListener(`keydown`,e=>{if(e.target.matches(`[data-role="nav-search"]`))return;let t=Array.from(a.querySelectorAll(`.chat-nav-question-item`));if(t.length===0)return;let n=t.indexOf(document.activeElement),r=null;e.key===`ArrowDown`?r=Math.min(n+1,t.length-1):e.key===`ArrowUp`?r=n<=0?0:n-1:e.key===`Home`?r=0:e.key===`End`&&(r=t.length-1),r!==null&&(e.preventDefault(),t[r].focus())}),a.addEventListener(`click`,e=>{let t=e.target.closest(`.chat-nav-question-item`);if(!t||!t.dataset.messageId)return;let n=o.find(e=>(e.userElement||e.start).dataset.messageId===t.dataset.messageId);if(!n)return;let r=n.userElement||n.start;r.scrollIntoView({behavior:`instant`,block:`start`}),r.classList.add(`bookmark-highlight`),setTimeout(()=>r.classList.remove(`bookmark-highlight`),2e3),s?g():_()})));{let e=document.getElementById(`chatContainer`);if(e){let t=!1;e.addEventListener(`scroll`,()=>{!a||!a.classList.contains(`expanded`)||t||(t=!0,requestAnimationFrame(()=>{t=!1,g()}))},{passive:!0})}}function x(){let e=a&&a.classList.contains(`expanded`);if(!s&&!e)return!1;if(a&&a.querySelector(`[data-role="nav-search"]`)&&l){l=``,ee();let e=a.querySelector(`[data-role="nav-search"]`);return e&&e.focus(),!0}return y(!1),_(),!0}return{jumpToMessage:p,updateActiveQuestion:g,handleEscape:x,isPinned:()=>s}}function us(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,fs=!1,F=[],ps=``;function ms(){v.searchInputHistory=[],v.searchInputHistoryIndex=-1;try{chrome.storage.local.get([`searchInputHistory`],e=>{e.searchInputHistory&&(v.searchInputHistory=e.searchInputHistory)})}catch{}let e=document.createElement(`div`);e.className=`search-panel-container`,e.id=`searchPanelContainer`,e.innerHTML=`
3
3
  <button class="search-panel-toggle" id="searchPanelToggle" title="${t(`searchPanel.toggleTitle`)}">
4
4
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
5
5
  <circle cx="11" cy="11" r="8"/>
@@ -34,21 +34,21 @@ import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-DvmxOw8q.js"
34
34
  <div class="search-panel-empty">${t(`searchPanel.startSearchHint`)}</div>
35
35
  </div>
36
36
  </div>
37
- `,Xn(`search`).appendChild(e),ys(),r.debug(`[SearchPanel] search panelinitializing`)}function ys(){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`)?xs():bs()}),i.addEventListener(`click`,()=>{xs()}),r.addEventListener(`click`,()=>{n.value=``,r.style.display=`none`,Ss(),n.focus()}),n.addEventListener(`input`,()=>{let e=n.value.trim();r.style.display=e?``:`none`,e||Ss()}),n.addEventListener(`keydown`,e=>{if(e.key===`Enter`){e.stopPropagation();let t=n.value.trim();t&&(s(t),Cs(t))}else if(e.key===`Escape`)v.searchInputHistoryIndex>=0?(v.searchInputHistoryIndex=-1,n.value=``):(e.stopPropagation(),xs());else if(e.key===`ArrowUp`){e.preventDefault(),e.stopPropagation();let t=v.searchInputHistory;if(t.length===0)return;v.searchInputHistoryIndex===-1?v.searchInputHistoryIndex=t.length-1:v.searchInputHistoryIndex>0&&v.searchInputHistoryIndex--,n.value=t[v.searchInputHistoryIndex]||``,r.style.display=n.value?``:`none`,n.selectionStart=n.selectionEnd=n.value.length}else if(e.key===`ArrowDown`){e.preventDefault(),e.stopPropagation();let t=v.searchInputHistory;v.searchInputHistoryIndex>=0&&v.searchInputHistoryIndex<t.length-1?(v.searchInputHistoryIndex++,n.value=t[v.searchInputHistoryIndex]||``,n.selectionStart=n.selectionEnd=n.value.length):(v.searchInputHistoryIndex=-1,n.value=``),r.style.display=n.value?``:`none`}});function s(e){if(!e||!e.trim())return;let t=e.trim(),n=v.searchInputHistory,r=n.indexOf(t);r!==-1&&n.splice(r,1),n.push(t),n.length>20&&n.shift(),v.searchInputHistoryIndex=-1;try{chrome.storage.local.set({searchInputHistory:n})}catch{}}a.addEventListener(`click`,()=>{a.classList.contains(`active`)||(a.classList.add(`active`),o.classList.remove(`active`));let e=n.value.trim();e&&Cs(e)}),o.addEventListener(`click`,()=>{o.classList.contains(`active`)||(o.classList.add(`active`),a.classList.remove(`active`));let e=n.value.trim();e&&Cs(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 js(n,r)})}function bs(){let e=document.getElementById(`searchPanel`),t=document.getElementById(`searchPanelInput`);e.classList.add(`expanded`),Je(e),t.value.trim()&&F.length===0&&Cs(t.value.trim()),setTimeout(()=>t.focus(),100)}function xs(){let e=document.getElementById(`searchPanel`);e.classList.remove(`expanded`),Xe(e),gs=!0,hs=!1}function Ss(){gs=!0,hs=!1,F=[],_s=``;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 Cs(e){if(!e||!e.trim()||(e=e.trim().toLowerCase(),hs&&_s===e))return;gs=!0,await new Promise(e=>setTimeout(e,50)),hs=!0,gs=!1,F=[],_s=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 Ts(e,n,i):await ws(e,n,i)}catch(e){r.error(`[SearchPanel] search error:`,e),gs||(n.innerHTML=`<div class="search-panel-empty">${t(`searchPanel.searchError`)}</div>`)}gs||(hs=!1)}async function ws(e,n,r){let i=v.activeSessionId;if(!i){n.innerHTML=`<div class="search-panel-empty">${t(`searchPanel.noActiveSession`)}</div>`;return}let a=Es(v.messageHistory||[],e,i);if(!gs){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}Os(a,e,n)}}async function Ts(e,n,i){let a=v.activeSessionId,o=await ce(),s=(o||[]).filter(e=>!e.archivedAt);if(gs)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=Es(v.messageHistory||[],e,a);if(gs)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}),Os(F,e,n,!0)}let u=s.filter(e=>e.id!==a);for(let a of u){if(gs)return;try{let r=await y(a.id);if(!r||!r.messageHistory)continue;let o=Es(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`),Os(F,e,n)}}catch(e){r.warn(`[SearchPanel] searchsession failed:`,a.id,e)}await new Promise(e=>setTimeout(e,10))}if(gs)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}Os(F,e,n)}function Es(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=Ds(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 Ds(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 Os(e,n,r,i){if(r||=document.getElementById(`searchPanelContent`),!r)return;if(e.length===0){r.innerHTML=`<div class="search-panel-empty">${t(`searchPanel.noMatch`)}</div>`;return}let a=v.activeSessionId,o=e.filter(e=>e.sessionId===a),s=e.filter(e=>e.sessionId!==a),c=``,l=i?t(`searchPanel.searchingSuffix`):``;o.length>0&&(c+=`<div class="search-section">
37
+ `,Et(`search`).appendChild(e),hs(),r.debug(`[SearchPanel] search panelinitializing`)}function hs(){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`)?_s():gs()}),i.addEventListener(`click`,()=>{_s()}),r.addEventListener(`click`,()=>{n.value=``,r.style.display=`none`,vs(),n.focus()}),n.addEventListener(`input`,()=>{let e=n.value.trim();r.style.display=e?``:`none`,e||vs()}),n.addEventListener(`keydown`,e=>{if(e.key===`Enter`){e.stopPropagation();let t=n.value.trim();t&&(s(t),ys(t))}else if(e.key===`Escape`)v.searchInputHistoryIndex>=0?(v.searchInputHistoryIndex=-1,n.value=``):(e.stopPropagation(),_s());else if(e.key===`ArrowUp`){e.preventDefault(),e.stopPropagation();let t=v.searchInputHistory;if(t.length===0)return;v.searchInputHistoryIndex===-1?v.searchInputHistoryIndex=t.length-1:v.searchInputHistoryIndex>0&&v.searchInputHistoryIndex--,n.value=t[v.searchInputHistoryIndex]||``,r.style.display=n.value?``:`none`,n.selectionStart=n.selectionEnd=n.value.length}else if(e.key===`ArrowDown`){e.preventDefault(),e.stopPropagation();let t=v.searchInputHistory;v.searchInputHistoryIndex>=0&&v.searchInputHistoryIndex<t.length-1?(v.searchInputHistoryIndex++,n.value=t[v.searchInputHistoryIndex]||``,n.selectionStart=n.selectionEnd=n.value.length):(v.searchInputHistoryIndex=-1,n.value=``),r.style.display=n.value?``:`none`}});function s(e){if(!e||!e.trim())return;let t=e.trim(),n=v.searchInputHistory,r=n.indexOf(t);r!==-1&&n.splice(r,1),n.push(t),n.length>20&&n.shift(),v.searchInputHistoryIndex=-1;try{chrome.storage.local.set({searchInputHistory:n})}catch{}}a.addEventListener(`click`,()=>{a.classList.contains(`active`)||(a.classList.add(`active`),o.classList.remove(`active`));let e=n.value.trim();e&&ys(e)}),o.addEventListener(`click`,()=>{o.classList.contains(`active`)||(o.classList.add(`active`),a.classList.remove(`active`));let e=n.value.trim();e&&ys(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 Ds(n,r)})}function gs(){let e=document.getElementById(`searchPanel`),t=document.getElementById(`searchPanelInput`);e.classList.add(`expanded`),qe(e),t.value.trim()&&F.length===0&&ys(t.value.trim()),setTimeout(()=>t.focus(),100)}function _s(){let e=document.getElementById(`searchPanel`);e.classList.remove(`expanded`),Ye(e),fs=!0,ds=!1}function vs(){fs=!0,ds=!1,F=[],ps=``;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 ys(e){if(!e||!e.trim()||(e=e.trim().toLowerCase(),ds&&ps===e))return;fs=!0,await new Promise(e=>setTimeout(e,50)),ds=!0,fs=!1,F=[],ps=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 xs(e,n,i):await bs(e,n,i)}catch(e){r.error(`[SearchPanel] search error:`,e),fs||(n.innerHTML=`<div class="search-panel-empty">${t(`searchPanel.searchError`)}</div>`)}fs||(ds=!1)}async function bs(e,n,r){let i=v.activeSessionId;if(!i){n.innerHTML=`<div class="search-panel-empty">${t(`searchPanel.noActiveSession`)}</div>`;return}let a=Ss(v.messageHistory||[],e,i);if(!fs){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}ws(a,e,n)}}async function xs(e,n,i){let a=v.activeSessionId,o=await ce(),s=(o||[]).filter(e=>!e.archivedAt);if(fs)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=Ss(v.messageHistory||[],e,a);if(fs)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}),ws(F,e,n,!0)}let u=s.filter(e=>e.id!==a);for(let a of u){if(fs)return;try{let r=await y(a.id);if(!r||!r.messageHistory)continue;let o=Ss(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`),ws(F,e,n)}}catch(e){r.warn(`[SearchPanel] searchsession failed:`,a.id,e)}await new Promise(e=>setTimeout(e,10))}if(fs)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}ws(F,e,n)}function Ss(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=Cs(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 Cs(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 ws(e,n,r,i){if(r||=document.getElementById(`searchPanelContent`),!r)return;if(e.length===0){r.innerHTML=`<div class="search-panel-empty">${t(`searchPanel.noMatch`)}</div>`;return}let a=v.activeSessionId,o=e.filter(e=>e.sessionId===a),s=e.filter(e=>e.sessionId!==a),c=``,l=i?t(`searchPanel.searchingSuffix`):``;o.length>0&&(c+=`<div class="search-section">
38
38
  <div class="search-section-title">${t(`searchPanel.currentSessionResults`,{label:l,count:o.length})}</div>
39
- ${ks(o,n)}
39
+ ${Ts(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
- ${ks(s,n)}
43
- </div>`),r.innerHTML=c}function ks(e,n){return e.map((e,r)=>{let i=e.role===`user`?`👤`:`🤖`,a=e.role===`user`?t(`searchPanel.roleUser`):t(`searchPanel.roleAssistant`),o=e.sessionTitle||``,s=e.sessionId===v.activeSessionId,c=As(A(e.matchPreview),n);return`
44
- <div class="search-result-item" data-session-id="${e.sessionId}" data-message-id="${e.messageId}" title="${A(e.content)}">
42
+ ${Ts(s,n)}
43
+ </div>`),r.innerHTML=c}function Ts(e,n){return e.map((e,r)=>{let i=e.role===`user`?`👤`:`🤖`,a=e.role===`user`?t(`searchPanel.roleUser`):t(`searchPanel.roleAssistant`),o=e.sessionTitle||``,s=e.sessionId===v.activeSessionId,c=Es(j(e.matchPreview),n);return`
44
+ <div class="search-result-item" data-session-id="${e.sessionId}" data-message-id="${e.messageId}" title="${j(e.content)}">
45
45
  <div class="search-result-header">
46
46
  <span class="search-result-role">${i} ${a}</span>
47
- ${s?``:`<span class="search-result-session" title="${A(o)}">${A(o.length>20?o.substring(0,20)+`...`:o)}</span>`}
47
+ ${s?``:`<span class="search-result-session" title="${j(o)}">${j(o.length>20?o.substring(0,20)+`...`:o)}</span>`}
48
48
  </div>
49
49
  <div class="search-result-preview">${c}</div>
50
50
  </div>
51
- `}).join(``)}function As(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 js(e,n){if(!(!e||!n)){if(v.activeSessionId!==e)try{let n=v.activeSessionId;if(await Gi(e)===!1||v.activeSessionId!==e){k(t(`searchPanel.sessionNotExist`),`warning`);return}document.dispatchEvent(new CustomEvent(`session-switched`,{detail:{sessionId:e,previousSessionId:n,skipScrollRestore:!0}}));try{let{renderSessionTabs:e}=await T(async()=>{let{renderSessionTabs:e}=await import(`./context-indicator-BSGa1g7l.js`).then(e=>e.ir);return{renderSessionTabs:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]));e()}catch(e){r.warn(`[SearchPanel] refreshsessionTab failed:`,e)}}catch(e){r.error(`[SearchPanel] switchsession failed:`,e);return}setTimeout(async()=>{let i=document.getElementById(`chatContainer`);if(!i){r.warn(`[SearchPanel] chatContainer not found`);return}let a=i.querySelector(`.message[data-message-id="${n}"]`);if(a||=i.querySelector(`[data-message-id="${n}"]`),!a){let t=Array.from(i.querySelectorAll(`[data-message-id]`),e=>e.dataset.messageId);r.warn(`[SearchPanel] positionmessage failed`,{targetSessionId:e,activeSessionId:v.activeSessionId,targetMessageId:n,typeOfMessageId:typeof n,messageIdLength:n.length,domMessageIds:t,chatContainerHtmlLen:i.innerHTML.length})}if(a)a.scrollIntoView({behavior:`instant`,block:`nearest`}),a.classList.add(`bookmark-highlight`),setTimeout(()=>{a.classList.remove(`bookmark-highlight`)},2e3);else{k(t(`searchPanel.messageDeleted`),`warning`);try{if(await _(e,n)){F=F.filter(t=>!(t.sessionId===e&&t.messageId===n));let i=document.getElementById(`searchPanelContent`),a=document.getElementById(`searchPanelCount`);i&&F.length>0?(Os(F,_s,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 Ms(e){return chrome.runtime.sendMessage(e)}function Ns(e){return e?new Date(e).toLocaleString(void 0,{month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`}):`—`}function Ps(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 Fs(e){return e===`success`?t(`schedPanel.statusSuccess`):e===`failed`?t(`schedPanel.statusFailed`):e===`running`?t(`schedPanel.statusRunning`):``}function Is(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 Ls(e){let n=e.schedule||{};return n.type===`once`?n.onceMode===`relative`?t(`schedPanel.scheduleTypeOnce`)+` · `+(n.value||``)+t(`schedPanel.minutesSuffix`):t(`schedPanel.scheduleTypeOnce`)+` · `+Ns(new Date(n.value).getTime()):n.type===`interval`?t(`schedPanel.scheduleTypeInterval`)+` · `+(n.value||``):n.type===`cron`?t(`schedPanel.scheduleTypeCron`)+` · `+(n.value||``):``}function Rs(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 Bs(e){if(e){if(v.activeSessionId!==e){let t=v.activeSessionId;try{if(await Gi(e)===!1||v.activeSessionId!==e)return}catch{return}document.dispatchEvent(new CustomEvent(`session-switched`,{detail:{sessionId:e,previousSessionId:t,skipScrollRestore:!0}}));try{let{renderSessionTabs:e}=await T(async()=>{let{renderSessionTabs:e}=await import(`./context-indicator-BSGa1g7l.js`).then(e=>e.ir);return{renderSessionTabs:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]));e()}catch{}}setTimeout(zs,500)}}function Vs(){let e=document.createElement(`div`);e.className=`schedule-panel-container`,e.id=`schedulePanelContainer`,e.innerHTML=`
51
+ `}).join(``)}function Es(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 Ds(e,n){if(!(!e||!n)){if(v.activeSessionId!==e)try{let n=v.activeSessionId;if(await At(e)===!1||v.activeSessionId!==e){A(t(`searchPanel.sessionNotExist`),`warning`);return}document.dispatchEvent(new CustomEvent(`session-switched`,{detail:{sessionId:e,previousSessionId:n,skipScrollRestore:!0}}));try{let{renderSessionTabs:e}=await E(async()=>{let{renderSessionTabs:e}=await import(`./context-indicator-C9mzVLvn.js`).then(e=>e.rr);return{renderSessionTabs:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]));e()}catch(e){r.warn(`[SearchPanel] refreshsessionTab failed:`,e)}}catch(e){r.error(`[SearchPanel] switchsession failed:`,e);return}setTimeout(async()=>{let i=document.getElementById(`chatContainer`);if(!i){r.warn(`[SearchPanel] chatContainer not found`);return}let a=i.querySelector(`.message[data-message-id="${n}"]`);if(a||=i.querySelector(`[data-message-id="${n}"]`),!a){let t=Array.from(i.querySelectorAll(`[data-message-id]`),e=>e.dataset.messageId);r.warn(`[SearchPanel] positionmessage failed`,{targetSessionId:e,activeSessionId:v.activeSessionId,targetMessageId:n,typeOfMessageId:typeof n,messageIdLength:n.length,domMessageIds:t,chatContainerHtmlLen:i.innerHTML.length})}if(a)a.scrollIntoView({behavior:`instant`,block:`nearest`}),a.classList.add(`bookmark-highlight`),setTimeout(()=>{a.classList.remove(`bookmark-highlight`)},2e3);else{A(t(`searchPanel.messageDeleted`),`warning`);try{if(await _(e,n)){F=F.filter(t=>!(t.sessionId===e&&t.messageId===n));let i=document.getElementById(`searchPanelContent`),a=document.getElementById(`searchPanelCount`);i&&F.length>0?(ws(F,ps,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 Os(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 As(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 Ms(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 Ns(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 Ps(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 Fs(){let e=document.getElementById(`chatContainer`);e&&(e.scrollTop=e.scrollHeight)}async function Is(e){if(e){if(v.activeSessionId!==e){let t=v.activeSessionId;try{if(await At(e)===!1||v.activeSessionId!==e)return}catch{return}document.dispatchEvent(new CustomEvent(`session-switched`,{detail:{sessionId:e,previousSessionId:t,skipScrollRestore:!0}}));try{let{renderSessionTabs:e}=await E(async()=>{let{renderSessionTabs:e}=await import(`./context-indicator-C9mzVLvn.js`).then(e=>e.rr);return{renderSessionTabs:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]));e()}catch{}}setTimeout(Fs,500)}}function Ls(){let e=document.createElement(`div`);e.className=`schedule-panel-container`,e.id=`schedulePanelContainer`,e.innerHTML=`
52
52
  <style>
53
53
  .schedule-panel-container { position: relative; display: flex; justify-content: flex-end; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; width: 100%; background: transparent; }
54
54
  .schedule-panel-toggle { background: rgba(var(--success-rgb), 0.14); color: var(--success-strong); border: none; border-radius: 6px 0 0 6px; padding: 8px 4px; cursor: pointer; font-size: 14px; box-shadow: -1px 1px 4px rgba(var(--overlay-rgb), 0.12); transition: all 0.3s ease; display: flex; align-items: center; justify-content: center; }
@@ -155,7 +155,7 @@ import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-DvmxOw8q.js"
155
155
  </div>
156
156
  <div class="schedule-panel-list" id="schedulePanelList"></div>
157
157
  </div>
158
- `,Xn(`schedule`).appendChild(e);let n=document.createElement(`div`);n.className=`sched-modal-overlay`,n.id=`scheduleModalOverlay`,n.innerHTML=`
158
+ `,Et(`schedule`).appendChild(e);let n=document.createElement(`div`);n.className=`sched-modal-overlay`,n.id=`scheduleModalOverlay`,n.innerHTML=`
159
159
  <div class="sched-modal">
160
160
  <div class="sched-modal-header">
161
161
  <h3 id="scheduleModalTitle"></h3>
@@ -202,25 +202,25 @@ import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-DvmxOw8q.js"
202
202
  <button class="primary" id="scheduleModalSave">${t(`schedPanel.save`)}</button>
203
203
  </div>
204
204
  </div>
205
- `,document.body.appendChild(n);let r=document.getElementById(`schedulePanelToggle`),i=document.getElementById(`schedulePanel`),a=new Set;function o(){let e=a.size>0;r.classList.toggle(`running`,e),r.title=e?`${t(`schedPanel.toggleTitle`)} · ${t(`schedPanel.toggleRunning`)}`:t(`schedPanel.toggleTitle`)}let s=document.getElementById(`schedulePanelClose`),c=document.getElementById(`scheduleNewTask`),l=document.getElementById(`schedulePanelList`),u=document.getElementById(`scheduleModalOverlay`),d=document.getElementById(`scheduleModalTitle`),f=document.getElementById(`scheduleModalCancel`),p=document.getElementById(`scheduleModalSave`),m=document.getElementById(`schedFormType`),h=document.getElementById(`schedFormValue`),g=document.getElementById(`schedFormOnceMode`),ee=document.getElementById(`schedOnceModeWrap`),te=document.getElementById(`schedValueLabel`),ne=document.getElementById(`schedEndWrap`),_=null,re=`schedPanelView`,y=`all`,b=`created`,x=[],ie=document.getElementById(`schedFilterGroup`),S=document.getElementById(`schedSortSelect`);function C(e){if(typeof e==`number`)return Number.isFinite(e)?e:0;let t=Date.parse(e||``);return Number.isFinite(t)?t:0}function ae(e){return b===`lastRun`?C(e.lastRunAt)||C(e.createdAt):b===`updated`&&C(e.updatedAt)||C(e.createdAt)}function oe(){ie.querySelectorAll(`.sched-filter-btn`).forEach(e=>{e.classList.toggle(`active`,e.dataset.filter===y)}),S.value=b}function w(){try{Promise.resolve(chrome.storage.local.set({[re]:{filter:y,sort:b}})).catch(()=>{})}catch{}}ie.addEventListener(`click`,e=>{let t=e.target.closest(`.sched-filter-btn`);!t||t.dataset.filter===y||(y=t.dataset.filter,oe(),w(),T(x))}),S.addEventListener(`change`,()=>{b=S.value,w(),T(x)}),(async()=>{try{let e=(await chrome.storage.local.get(re))?.[re];(e?.filter===`enabled`||e?.filter===`disabled`||e?.filter===`all`)&&(y=e.filter),(e?.sort===`lastRun`||e?.sort===`updated`||e?.sort===`created`)&&(b=e.sort)}catch{}oe(),x.length&&T(x)})();function se(){let e=m.value,n=g.value;ee.style.display=e===`once`?``:`none`,ne.style.display=e===`interval`?``:`none`,e===`once`?n===`relative`?(te.textContent=t(`schedPanel.onceModeRelative`),h.type=`text`,h.placeholder=t(`schedPanel.relativeValuePlaceholder`)):(te.textContent=t(`schedPanel.onceModeAbsolute`),h.type=`datetime-local`,h.placeholder=``):e===`interval`?(te.textContent=t(`schedPanel.valueLabelInterval`),h.type=`text`,h.placeholder=t(`schedPanel.intervalValuePlaceholder`)):(te.textContent=t(`schedPanel.valueLabelCron`),h.type=`text`,h.placeholder=t(`schedPanel.cronValuePlaceholder`))}function ce(e){e?(i.classList.add(`open`),Je(i),le()):(i.classList.remove(`open`),Xe(i))}r.addEventListener(`click`,()=>{ce(!i.classList.contains(`open`))}),s.addEventListener(`click`,()=>ce(!1)),m.addEventListener(`change`,se),g.addEventListener(`change`,se),document.getElementById(`scheduleModalCloseBtn`).addEventListener(`click`,E),f.addEventListener(`click`,E),p.addEventListener(`click`,me),c.addEventListener(`click`,()=>fe(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 le(){try{let e=(await Ms({type:`SCHEDULED_TASK_LIST`}))?.tasks||[];T(e),a.clear(),e.forEach(e=>{e.lastStatus===`running`&&a.add(e.id)}),o()}catch(e){l.innerHTML=`<div class="sched-empty">${A(String(e?.message||e))}</div>`}}function ue(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=document.getElementById(`scheduleNewTask`),l=document.getElementById(`schedulePanelList`),u=document.getElementById(`scheduleModalOverlay`),d=document.getElementById(`scheduleModalTitle`),f=document.getElementById(`scheduleModalCancel`),p=document.getElementById(`scheduleModalSave`),m=document.getElementById(`schedFormType`),h=document.getElementById(`schedFormValue`),g=document.getElementById(`schedFormOnceMode`),ee=document.getElementById(`schedOnceModeWrap`),te=document.getElementById(`schedValueLabel`),ne=document.getElementById(`schedEndWrap`),_=null,re=`schedPanelView`,y=`all`,b=`created`,x=[],ie=document.getElementById(`schedFilterGroup`),S=document.getElementById(`schedSortSelect`);function C(e){if(typeof e==`number`)return Number.isFinite(e)?e:0;let t=Date.parse(e||``);return Number.isFinite(t)?t:0}function ae(e){return b===`lastRun`?C(e.lastRunAt)||C(e.createdAt):b===`updated`&&C(e.updatedAt)||C(e.createdAt)}function oe(){ie.querySelectorAll(`.sched-filter-btn`).forEach(e=>{e.classList.toggle(`active`,e.dataset.filter===y)}),S.value=b}function w(){try{Promise.resolve(chrome.storage.local.set({[re]:{filter:y,sort:b}})).catch(()=>{})}catch{}}ie.addEventListener(`click`,e=>{let t=e.target.closest(`.sched-filter-btn`);!t||t.dataset.filter===y||(y=t.dataset.filter,oe(),w(),E(x))}),S.addEventListener(`change`,()=>{b=S.value,w(),E(x)}),(async()=>{try{let e=(await chrome.storage.local.get(re))?.[re];(e?.filter===`enabled`||e?.filter===`disabled`||e?.filter===`all`)&&(y=e.filter),(e?.sort===`lastRun`||e?.sort===`updated`||e?.sort===`created`)&&(b=e.sort)}catch{}oe(),x.length&&E(x)})();function se(){let e=m.value,n=g.value;ee.style.display=e===`once`?``:`none`,ne.style.display=e===`interval`?``:`none`,e===`once`?n===`relative`?(te.textContent=t(`schedPanel.onceModeRelative`),h.type=`text`,h.placeholder=t(`schedPanel.relativeValuePlaceholder`)):(te.textContent=t(`schedPanel.onceModeAbsolute`),h.type=`datetime-local`,h.placeholder=``):e===`interval`?(te.textContent=t(`schedPanel.valueLabelInterval`),h.type=`text`,h.placeholder=t(`schedPanel.intervalValuePlaceholder`)):(te.textContent=t(`schedPanel.valueLabelCron`),h.type=`text`,h.placeholder=t(`schedPanel.cronValuePlaceholder`))}function ce(e){e?(i.classList.add(`open`),qe(i),T()):(i.classList.remove(`open`),Ye(i))}r.addEventListener(`click`,()=>{ce(!i.classList.contains(`open`))}),s.addEventListener(`click`,()=>ce(!1)),m.addEventListener(`change`,se),g.addEventListener(`change`,se),document.getElementById(`scheduleModalCloseBtn`).addEventListener(`click`,D),f.addEventListener(`click`,D),p.addEventListener(`click`,pe),c.addEventListener(`click`,()=>de(null)),document.getElementById(`schedUseCurrentPage`).addEventListener(`click`,async()=>{try{let e=(await chrome.tabs.query({active:!0,currentWindow:!0}))?.[0]?.url||``;e&&(document.getElementById(`schedFormUrl`).value=e)}catch{}});async function T(){try{let e=(await Os({type:`SCHEDULED_TASK_LIST`}))?.tasks||[];E(e),a.clear(),e.forEach(e=>{e.lastStatus===`running`&&a.add(e.id)}),o()}catch(e){l.innerHTML=`<div class="sched-empty">${j(String(e?.message||e))}</div>`}}function le(e){return!e||!e.length?`<div class="sched-history"><div class="sched-run">${t(`schedPanel.runHistoryEmpty`)}</div></div>`:`<div class="sched-history">${e.slice().reverse().map(e=>`
206
206
  <div class="sched-run">
207
- <span class="dot ${A(e.status||``)}"></span>
208
- <span class="time">${A(Ns(e.startedAt))}</span>
209
- <span>${A(Fs(e.status))}</span>
210
- <span class="dur">${A(Ps(e.durationMs))}</span>
211
- ${e.error?`<span class="err" title="${A(e.error)}">${A(e.error)}</span>`:``}
207
+ <span class="dot ${j(e.status||``)}"></span>
208
+ <span class="time">${j(ks(e.startedAt))}</span>
209
+ <span>${j(js(e.status))}</span>
210
+ <span class="dur">${j(As(e.durationMs))}</span>
211
+ ${e.error?`<span class="err" title="${j(e.error)}">${j(e.error)}</span>`:``}
212
212
  </div>
213
- `).join(``)}</div>`}function T(e){x=Array.isArray(e)?e:[];let n=x.filter(e=>y===`enabled`?e.enabled!==!1:y===`disabled`?e.enabled===!1:!0).slice().sort((e,t)=>{let n=ae(t)-ae(e);return n===0?C(t.createdAt)-C(e.createdAt):n}),r=document.getElementById(`schedulePanelCount`);if(r&&(x.length?y===`all`?r.textContent=`(${x.length})`:r.textContent=`(${n.length}/${x.length})`:r.textContent=``),!x.length){l.innerHTML=`<div class="sched-empty">${t(`schedPanel.empty`)}</div>`;return}if(!n.length){l.innerHTML=`<div class="sched-empty">${t(`schedPanel.emptyFiltered`)}</div>`;return}l.innerHTML=n.map(e=>{let n=e.runHistory?.length||0,r=n>0?`<button class="sched-history-btn" data-act="history">${t(`schedPanel.runCountLabel`,{count:n})}</button>`:``;return`
214
- <div class="sched-item" data-id="${A(e.id)}">
213
+ `).join(``)}</div>`}function E(e){x=Array.isArray(e)?e:[];let n=x.filter(e=>y===`enabled`?e.enabled!==!1:y===`disabled`?e.enabled===!1:!0).slice().sort((e,t)=>{let n=ae(t)-ae(e);return n===0?C(t.createdAt)-C(e.createdAt):n}),r=document.getElementById(`schedulePanelCount`);if(r&&(x.length?y===`all`?r.textContent=`(${x.length})`:r.textContent=`(${n.length}/${x.length})`:r.textContent=``),!x.length){l.innerHTML=`<div class="sched-empty">${t(`schedPanel.empty`)}</div>`;return}if(!n.length){l.innerHTML=`<div class="sched-empty">${t(`schedPanel.emptyFiltered`)}</div>`;return}l.innerHTML=n.map(e=>{let n=e.runHistory?.length||0,r=n>0?`<button class="sched-history-btn" data-act="history">${t(`schedPanel.runCountLabel`,{count:n})}</button>`:``;return`
214
+ <div class="sched-item" data-id="${j(e.id)}">
215
215
  <div class="row1">
216
- <span class="name" title="${A(e.name)}">${A(e.name)}</span>
217
- ${Rs(e)}
216
+ <span class="name" title="${j(e.name)}">${j(e.name)}</span>
217
+ ${Ps(e)}
218
218
  </div>
219
- ${e.description?`<div class="desc">${A(e.description)}</div>`:``}
220
- <div class="meta">${A(Ls(e))}</div>
221
- <div class="meta">${t(`schedPanel.nextRun`)}: ${A(Ns(e.nextRunAt))}</div>
219
+ ${e.description?`<div class="desc">${j(e.description)}</div>`:``}
220
+ <div class="meta">${j(Ns(e))}</div>
221
+ <div class="meta">${t(`schedPanel.nextRun`)}: ${j(ks(e.nextRunAt))}</div>
222
222
  ${r}
223
- <div class="sched-history" data-history style="display:none;">${ue(e.runHistory)}</div>
223
+ <div class="sched-history" data-history style="display:none;">${le(e.runHistory)}</div>
224
224
  <div class="actions">
225
225
  <button data-act="toggle" class="${e.enabled?`danger`:`primary`}">${e.enabled?t(`schedPanel.disable`):t(`schedPanel.enable`)}</button>
226
226
  <button data-act="run" class="primary">${t(`schedPanel.runNow`)}</button>
@@ -228,55 +228,55 @@ import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-DvmxOw8q.js"
228
228
  <button data-act="delete" class="danger">${t(`schedPanel.delete`)}</button>
229
229
  </div>
230
230
  </div>
231
- `}).join(``)}l.addEventListener(`click`,async e=>{let n=e.target.closest(`button[data-act]`);if(!n)return;let r=n.closest(`.sched-item`),i=r?.dataset.id;if(!i)return;let a=n.dataset.act;if(a===`toggle`){let e=(await de())[i];if(!e)return;await Ms({type:`SCHEDULED_TASK_TOGGLE`,id:i,enabled:!e.enabled}),le()}else if(a===`run`){let e=await Ms({type:`SCHEDULED_TASK_RUN_NOW`,id:i});e?.success?(k(t(`schedPanel.runNowToast`),`success`),Bs(e.sessionId),setTimeout(le,1500)):k(e?.error||t(`schedPanel.createFailed`),`error`)}else if(a===`history`){let e=r.querySelector(`[data-history]`);e&&(e.style.display=e.style.display===`none`?``:`none`)}else if(a===`edit`)fe((await de())[i]);else if(a===`delete`){let e=(await de())[i];await window.showCustomConfirm(t(`schedPanel.deleteConfirmMsg`,{name:e?.name||``}),t(`schedPanel.deleteConfirmTitle`))&&(await Ms({type:`SCHEDULED_TASK_DELETE`,id:i}),k(t(`schedPanel.deleted`),`success`),le())}});async function de(){let e=await Ms({type:`SCHEDULED_TASK_LIST`}),t={};return(e?.tasks||[]).forEach(e=>{t[e.id]=e}),t}async function fe(e){_=e||null,d.textContent=t(e?`schedPanel.editTitle`:`schedPanel.newTask`),document.getElementById(`schedFormName`).value=e?.name||``,document.getElementById(`schedFormDesc`).value=e?.description||``,document.getElementById(`schedFormPrompt`).value=e?.prompt||``,document.getElementById(`schedFormUrl`).value=e?.contextUrl||``,m.value=e?.schedule?.type||`interval`,g.value=e?.schedule?.onceMode||`relative`,se(),h.value=e?.schedule?.value||``,document.getElementById(`schedFormContextMode`).value=e?.contextMode||`fetch`,document.getElementById(`schedFormMaxRuns`).value=e?.maxRuns??``,document.getElementById(`schedFormEndAt`).value=e?.endAt?Is(e.endAt):``;let n=document.getElementById(`schedFormSession`),r=`<option value="">${t(`schedPanel.sessionAuto`)}</option>`;try{let{list:t}=await pe(),n=[...t].sort((e,t)=>{let n=e.order??0,r=t.order??0;return n===r?new Date(t.createdAt||0)-new Date(e.createdAt||0):r-n});for(let t of n){let n=e?.sessionId===t.id?`selected`:``,i=A(t.title||t.id);r+=`<option value="${A(t.id)}" ${n}>${i}</option>`}}catch{}n.innerHTML=r,u.classList.add(`open`)}function E(){u.classList.remove(`open`),_=null}async function me(){let e=document.getElementById(`schedFormName`).value.trim(),n=document.getElementById(`schedFormPrompt`).value.trim(),r=m.value,i=h.value.trim();if(!e){k(t(`schedPanel.nameRequired`),`warning`);return}if(!n){k(t(`schedPanel.promptRequired`),`warning`);return}if(!i){k(t(`schedPanel.scheduleRequired`),`warning`);return}let a=r===`interval`&&parseInt(document.getElementById(`schedFormMaxRuns`).value,10)||null,o=r===`interval`?document.getElementById(`schedFormEndAt`).value:``,s=o?new Date(o).getTime():null,c={name:e,description:document.getElementById(`schedFormDesc`).value.trim(),prompt:n,schedule:r===`once`?{type:r,value:i,onceMode:g.value}:{type:r,value:i},contextUrl:document.getElementById(`schedFormUrl`).value.trim()||null,contextMode:document.getElementById(`schedFormContextMode`).value||`fetch`,sessionId:document.getElementById(`schedFormSession`).value||null,maxRuns:a,endAt:s,enabled:_?_.enabled:!0};try{let e=await Ms({type:_?`SCHEDULED_TASK_UPDATE`:`SCHEDULED_TASK_CREATE`,task:_?{...c,id:_.id}:c});e?.success?(k(t(`schedPanel.saved`),`success`),E(),le()):k(e?.error||t(`schedPanel.createFailed`),`error`)}catch(e){k(e?.message||t(`schedPanel.createFailed`),`error`)}}chrome.runtime.onMessage.addListener(e=>{e.type===`SCHEDULED_TASK_RUN_STATE`&&e.taskId&&(e.running?a.add(e.taskId):a.delete(e.taskId),o())}),chrome.runtime.onMessage.addListener(e=>{e.type===`SCHEDULED_SESSION_UPDATED`&&(i.classList.contains(`open`)&&le().catch(()=>{}),e.sessionId&&e.sessionId===v.activeSessionId&&setTimeout(zs,600))}),chrome.runtime.onMessage.addListener(e=>{e.type===`SCHEDULED_TASKS_CHANGED`&&le().catch(()=>{})}),se(),ce(!1),le().catch(()=>{})}var Hs=`todoStatsLog`,Us=7;function Ws(e){return String(e).padStart(2,`0`)}function Gs(e=Date.now()){let t=new Date(e);return`${t.getFullYear()}-${Ws(t.getMonth()+1)}-${Ws(t.getDate())}`}function Ks(e,t){let n=new Date(e);return n.setDate(n.getDate()+t),n.getTime()}function qs(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 Js(e,t=Date.now()){let n=Gs(Ks(t,-90)),r={};for(let[t,i]of Object.entries(e&&typeof e==`object`?e:{}))t>=n&&(r[t]=i);return r}function Ys(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 Xs(e,t){let n=Ys(e,Gs(t)).done>0?t:Ks(t,-1),r=0;for(;r<=90&&!(Ys(e,Gs(n)).done<=0);)r+=1,n=Ks(n,-1);return r}function Zs(e,t,n=Date.now()){let r=Array.isArray(e)?e.map(We):[],{stats:i}=Ve(r),a=t&&typeof t==`object`?t:{},o=[];for(let e=Us-1;e>=0;--e){let t=Gs(Ks(n,-e));o.push({date:t,...Ys(a,t)})}return{total:i.total,done:i.done,doing:i.doing,pending:i.pending,overdue:r.filter(e=>Oe(e,n)).length,high:r.filter(e=>e.status!==D.DONE&&e.priority===Be.HIGH).length,doneRate:i.total?Math.round(i.done/i.total*100):0,today:Ys(a,Gs(n)),week:o,streak:Xs(a,n)}}var Qs=Promise.resolve();async function $s(){try{if(typeof chrome>`u`||!chrome.storage?.local?.get)return{};let e=await chrome.storage.local.get([Hs]),t=e&&e.todoStatsLog;return t&&typeof t==`object`?t:{}}catch(e){return r.warn(`[Todo] load stats log failed:`,e),{}}}async function ec(e){typeof chrome>`u`||!chrome.storage?.local?.set||await chrome.storage.local.set({[Hs]:e})}function tc(e,t,n=Date.now()){let i=Qs.then(async()=>{let r=Js(qs(await $s(),Gs(n),e,t));return await ec(r),r});return Qs=i.then(()=>void 0,()=>void 0),i.catch(e=>(r.warn(`[Todo] record stat failed:`,e),null))}var nc=new Set,rc=Promise.resolve();function ic(e){let t=rc.then(e);return rc=t.then(()=>void 0,()=>void 0),t}function ac(e){return typeof e==`function`?(nc.add(e),()=>nc.delete(e)):()=>{}}function I(){for(let e of nc)try{e()}catch(e){r.warn(`[Todo] listener failed:`,e)}}async function oc(){try{v.todos=(await C()||[]).map(We).filter(e=>e.id&&e.title),r.debug(`[Todo] loaded todos:`,v.todos.length)}catch(e){r.error(`[Todo] load todos failed:`,e),v.todos=[]}I()}function sc(){return Ve(v.todos)}function cc(e){return v.todos.find(t=>t.id===e)||null}function lc(e){v.todos=v.todos.map(t=>t.id===e.id?e:t)}async function uc(e,t={}){let n=String(e||``).trim();if(!n)return null;let i=Ie(n,t);return i.order=ke(v.todos),v.todos=[...v.todos,i],await ic(()=>ie(i)).catch(e=>(r.error(`[Todo] add failed:`,e),!1))?(I(),await tc(`added`,1,i.createdAt),i):(v.todos=v.todos.filter(e=>e.id!==i.id),I(),null)}async function dc(e,t={}){let n=cc(e);if(!n)return!1;let i={...n,updatedAt:Date.now()};if(t.title!==void 0){let e=String(t.title).trim();if(!e)return!1;i.title=e}return t.note!==void 0&&(i.note=String(t.note||``).trim()),t.dueAt!==void 0&&(i.dueAt=Number.isFinite(t.dueAt)?t.dueAt:null),t.priority!==void 0&&(i.priority=Te(t.priority)),t.link!==void 0&&(i.link=Ge(t.link).url),lc(i),await ic(()=>ie(i)).catch(e=>(r.error(`[Todo] update failed:`,e),!1))?(I(),!0):(lc(n),I(),!1)}async function fc(e,t){let n=cc(e);if(!n||!Le(t))return!1;if(n.status===t)return!0;let i=Date.now(),a={...n,status:t,updatedAt:i};return t===D.DONE?(a.completedAt=i,n.status!==D.DONE&&(a.prevStatus=n.status)):n.status===D.DONE&&(a.completedAt=null,a.prevStatus=null),lc(a),await ic(()=>ie(a)).catch(e=>(r.error(`[Todo] set status failed:`,e),!1))?(I(),t===D.DONE&&n.status!==D.DONE?await tc(`done`,1,a.completedAt):n.status===D.DONE&&t!==D.DONE&&await tc(`done`,-1,n.completedAt),!0):(lc(n),I(),!1)}function pc(e){let t=cc(e);return t?fc(e,He(t.status)):Promise.resolve(!1)}function mc(e){let t=cc(e);return!t||t.status!==D.DONE?Promise.resolve(!1):fc(e,Ue(t))}function hc(e,t){return dc(e,{priority:Te(t)})}async function gc(e,t){if(!cc(e))return{ok:!1,reason:`missing`};let n=Ge(t);if(!n.valid)return{ok:!1,reason:`invalid`};let r=await dc(e,{link:n.url});return{ok:r,reason:r?``:`save`}}async function _c(e){let t=cc(e);return t?(v.todos=v.todos.filter(t=>t.id!==e),await ic(()=>w(e)).catch(e=>(r.error(`[Todo] delete failed:`,e),!1))?(I(),!0):(v.todos=[...v.todos,t],I(),!1)):!1}async function vc(e,t){let{active:n}=sc();if(e===t)return!0;if(e<0||e>=n.length)return!1;let i=_e(he(n,e,t)),a=new Map(i.map(e=>[e.id,e])),o=v.todos;if(v.todos=v.todos.map(e=>a.get(e.id)||e),!await ic(()=>x(i)).catch(e=>(r.error(`[Todo] reorder failed:`,e),!1))){let e=new Map(o.map(e=>[e.id,e.order]));return v.todos=v.todos.map(t=>e.has(t.id)?{...t,order:e.get(t.id)}:t),I(),!1}return I(),!0}async function yc(){let{done:e}=sc();if(e.length===0)return!0;let t=e.map(e=>e.id),n=v.todos;if(v.todos=v.todos.filter(e=>!t.includes(e.id)),!await ic(()=>d(t)).catch(e=>(r.error(`[Todo] clear completed failed:`,e),!1))){let e=new Set(v.todos.map(e=>e.id)),r=n.filter(n=>t.includes(n.id)&&!e.has(n.id));return v.todos=[...v.todos,...r],I(),!1}return I(),!0}async function bc(e,t=`merge`){if(t===`replace`)return xc(e);let n=Ae(v.todos,e);if(n.addedItems.length===0)return{ok:!0,added:0,skipped:n.skipped};let i=v.todos;v.todos=n.todos;let a=new Set(n.addedItems.map(e=>e.id));return await ic(()=>x(n.addedItems)).catch(e=>(r.error(`[Todo] import merge failed:`,e),!1))?(I(),{ok:!0,added:n.addedItems.length,skipped:n.skipped}):(v.todos=i.filter(e=>!a.has(e.id)),I(),{ok:!1,added:0,skipped:n.skipped})}async function xc(e){let{addedItems:t,skipped:n}=Ae([],e);if(t.length===0)return{ok:!1,added:0,skipped:n,reason:`empty`};let i=v.todos,a=i.map(e=>e.id);return v.todos=t,await ic(async()=>a.length>0&&!await d(a).catch(e=>(r.error(`[Todo] replace delete failed:`,e),!1))?!1:await x(t).catch(e=>(r.error(`[Todo] replace write failed:`,e),!1))?!0:(a.length>0&&await x(i).catch(()=>!1),!1)).catch(e=>(r.error(`[Todo] replace failed:`,e),!1))?(I(),{ok:!0,added:t.length,skipped:n}):(v.todos=i,I(),{ok:!1,added:0,skipped:n})}var Sc=[`all`,`active`,`done`],Cc={json:{ext:`json`,type:`application/json;charset=utf-8`},md:{ext:`md`,type:`text/markdown;charset=utf-8`}};function wc(e){return e===`md`?`md`:`json`}function Tc(e){return String(e).padStart(2,`0`)}function Ec(e){let t=new Date(e);return`${t.getFullYear()}-${Tc(t.getMonth()+1)}-${Tc(t.getDate())}`}function Dc(e,t,n=Date.now()){let r=Sc.includes(e)?e:`all`;return`ai-helper-todos${r===`all`?``:`-${r}`}-${Ec(n)}.${Cc[wc(t)].ext}`}function Oc(e,t={}){let n=Sc.includes(t.scope)?t.scope:`all`,r=wc(t.format),i=t.now||Date.now(),a=r===`md`?we(e,{scope:n,now:i}):JSON.stringify(je(e,{scope:n,now:i}),null,2);return{filename:Dc(n,r,i),blob:new Blob([a],{type:Cc[r].type})}}function kc(e,t={}){let{filename:n,blob:r}=Oc(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 Ac(){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 jc(e){if(!e||typeof e.text!=`function`)return{ok:!1,reason:`json`};let t=``;try{t=await e.text()}catch{return{ok:!1,reason:`json`}}let n=null;try{n=JSON.parse(t)}catch{return{ok:!1,reason:`json`}}return xe(n)}var Mc=`<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>`,Nc=[`all`,`active`,`done`],Pc=[`json`,`md`],Fc=[`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 Ic(e){return`<div class="todo-io-header">
232
- <span class="todo-io-title">${A(e)}</span>
231
+ `}).join(``)}l.addEventListener(`click`,async e=>{let n=e.target.closest(`button[data-act]`);if(!n)return;let r=n.closest(`.sched-item`),i=r?.dataset.id;if(!i)return;let a=n.dataset.act;if(a===`toggle`){let e=(await ue())[i];if(!e)return;await Os({type:`SCHEDULED_TASK_TOGGLE`,id:i,enabled:!e.enabled}),T()}else if(a===`run`){let e=await Os({type:`SCHEDULED_TASK_RUN_NOW`,id:i});e?.success?(A(t(`schedPanel.runNowToast`),`success`),Is(e.sessionId),setTimeout(T,1500)):A(e?.error||t(`schedPanel.createFailed`),`error`)}else if(a===`history`){let e=r.querySelector(`[data-history]`);e&&(e.style.display=e.style.display===`none`?``:`none`)}else if(a===`edit`)de((await ue())[i]);else if(a===`delete`){let e=(await ue())[i];await window.showCustomConfirm(t(`schedPanel.deleteConfirmMsg`,{name:e?.name||``}),t(`schedPanel.deleteConfirmTitle`))&&(await Os({type:`SCHEDULED_TASK_DELETE`,id:i}),A(t(`schedPanel.deleted`),`success`),T())}});async function ue(){let e=await Os({type:`SCHEDULED_TASK_LIST`}),t={};return(e?.tasks||[]).forEach(e=>{t[e.id]=e}),t}async function de(e){_=e||null,d.textContent=t(e?`schedPanel.editTitle`:`schedPanel.newTask`),document.getElementById(`schedFormName`).value=e?.name||``,document.getElementById(`schedFormDesc`).value=e?.description||``,document.getElementById(`schedFormPrompt`).value=e?.prompt||``,document.getElementById(`schedFormUrl`).value=e?.contextUrl||``,m.value=e?.schedule?.type||`interval`,g.value=e?.schedule?.onceMode||`relative`,se(),h.value=e?.schedule?.value||``,document.getElementById(`schedFormContextMode`).value=e?.contextMode||`fetch`,document.getElementById(`schedFormMaxRuns`).value=e?.maxRuns??``,document.getElementById(`schedFormEndAt`).value=e?.endAt?Ms(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=j(t.title||t.id);r+=`<option value="${j(t.id)}" ${n}>${i}</option>`}}catch{}n.innerHTML=r,u.classList.add(`open`)}function D(){u.classList.remove(`open`),_=null}async function pe(){let e=document.getElementById(`schedFormName`).value.trim(),n=document.getElementById(`schedFormPrompt`).value.trim(),r=m.value,i=h.value.trim();if(!e){A(t(`schedPanel.nameRequired`),`warning`);return}if(!n){A(t(`schedPanel.promptRequired`),`warning`);return}if(!i){A(t(`schedPanel.scheduleRequired`),`warning`);return}let a=r===`interval`&&parseInt(document.getElementById(`schedFormMaxRuns`).value,10)||null,o=r===`interval`?document.getElementById(`schedFormEndAt`).value:``,s=o?new Date(o).getTime():null,c={name:e,description:document.getElementById(`schedFormDesc`).value.trim(),prompt:n,schedule:r===`once`?{type:r,value:i,onceMode:g.value}:{type:r,value:i},contextUrl:document.getElementById(`schedFormUrl`).value.trim()||null,contextMode:document.getElementById(`schedFormContextMode`).value||`fetch`,sessionId:document.getElementById(`schedFormSession`).value||null,maxRuns:a,endAt:s,enabled:_?_.enabled:!0};try{let e=await Os({type:_?`SCHEDULED_TASK_UPDATE`:`SCHEDULED_TASK_CREATE`,task:_?{...c,id:_.id}:c});e?.success?(A(t(`schedPanel.saved`),`success`),D(),T()):A(e?.error||t(`schedPanel.createFailed`),`error`)}catch(e){A(e?.message||t(`schedPanel.createFailed`),`error`)}}chrome.runtime.onMessage.addListener(e=>{e.type===`SCHEDULED_TASK_RUN_STATE`&&e.taskId&&(e.running?a.add(e.taskId):a.delete(e.taskId),o())}),chrome.runtime.onMessage.addListener(e=>{e.type===`SCHEDULED_SESSION_UPDATED`&&(i.classList.contains(`open`)&&T().catch(()=>{}),e.sessionId&&e.sessionId===v.activeSessionId&&setTimeout(Fs,600))}),chrome.runtime.onMessage.addListener(e=>{e.type===`SCHEDULED_TASKS_CHANGED`&&T().catch(()=>{})}),se(),ce(!1),T().catch(()=>{})}var Rs=`todoStatsLog`,zs=7;function Bs(e){return String(e).padStart(2,`0`)}function Vs(e=Date.now()){let t=new Date(e);return`${t.getFullYear()}-${Bs(t.getMonth()+1)}-${Bs(t.getDate())}`}function Hs(e,t){let n=new Date(e);return n.setDate(n.getDate()+t),n.getTime()}function Us(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 Ws(e,t=Date.now()){let n=Vs(Hs(t,-90)),r={};for(let[t,i]of Object.entries(e&&typeof e==`object`?e:{}))t>=n&&(r[t]=i);return r}function Gs(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 Ks(e,t){let n=Gs(e,Vs(t)).done>0?t:Hs(t,-1),r=0;for(;r<=90&&!(Gs(e,Vs(n)).done<=0);)r+=1,n=Hs(n,-1);return r}function qs(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=zs-1;e>=0;--e){let t=Vs(Hs(n,-e));o.push({date:t,...Gs(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:Gs(a,Vs(n)),week:o,streak:Ks(a,n)}}var Js=Promise.resolve();async function Ys(){try{if(typeof chrome>`u`||!chrome.storage?.local?.get)return{};let e=await chrome.storage.local.get([Rs]),t=e&&e.todoStatsLog;return t&&typeof t==`object`?t:{}}catch(e){return r.warn(`[Todo] load stats log failed:`,e),{}}}async function Xs(e){typeof chrome>`u`||!chrome.storage?.local?.set||await chrome.storage.local.set({[Rs]:e})}function Zs(e,t,n=Date.now()){let i=Js.then(async()=>{let r=Ws(Us(await Ys(),Vs(n),e,t));return await Xs(r),r});return Js=i.then(()=>void 0,()=>void 0),i.catch(e=>(r.warn(`[Todo] record stat failed:`,e),null))}var Qs=new Set,$s=Promise.resolve();function ec(e){let t=$s.then(e);return $s=t.then(()=>void 0,()=>void 0),t}function tc(e){return typeof e==`function`?(Qs.add(e),()=>Qs.delete(e)):()=>{}}function I(){for(let e of Qs)try{e()}catch(e){r.warn(`[Todo] listener failed:`,e)}}async function nc(){try{v.todos=(await C()||[]).map(Ue).filter(e=>e.id&&e.title),r.debug(`[Todo] loaded todos:`,v.todos.length)}catch(e){r.error(`[Todo] load todos failed:`,e),v.todos=[]}I()}function rc(){return Be(v.todos)}function ic(e){return v.todos.find(t=>t.id===e)||null}function ac(e){v.todos=v.todos.map(t=>t.id===e.id?e:t)}async function oc(e,t={}){let n=String(e||``).trim();if(!n)return null;let i=Fe(n,t);return i.order=Oe(v.todos),v.todos=[...v.todos,i],await ec(()=>ie(i)).catch(e=>(r.error(`[Todo] add failed:`,e),!1))?(I(),await Zs(`added`,1,i.createdAt),i):(v.todos=v.todos.filter(e=>e.id!==i.id),I(),null)}async function sc(e,t={}){let n=ic(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),ac(i),await ec(()=>ie(i)).catch(e=>(r.error(`[Todo] update failed:`,e),!1))?(I(),!0):(ac(n),I(),!1)}async function cc(e,t){let n=ic(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),ac(a),await ec(()=>ie(a)).catch(e=>(r.error(`[Todo] set status failed:`,e),!1))?(I(),t===O.DONE&&n.status!==O.DONE?await Zs(`done`,1,a.completedAt):n.status===O.DONE&&t!==O.DONE&&await Zs(`done`,-1,n.completedAt),!0):(ac(n),I(),!1)}function lc(e){let t=ic(e);return t?cc(e,Ve(t.status)):Promise.resolve(!1)}function uc(e){let t=ic(e);return!t||t.status!==O.DONE?Promise.resolve(!1):cc(e,He(t))}function dc(e,t){return sc(e,{priority:we(t)})}async function fc(e,t){if(!ic(e))return{ok:!1,reason:`missing`};let n=We(t);if(!n.valid)return{ok:!1,reason:`invalid`};let r=await sc(e,{link:n.url});return{ok:r,reason:r?``:`save`}}async function pc(e){let t=ic(e);return t?(v.todos=v.todos.filter(t=>t.id!==e),await ec(()=>w(e)).catch(e=>(r.error(`[Todo] delete failed:`,e),!1))?(I(),!0):(v.todos=[...v.todos,t],I(),!1)):!1}async function mc(e,t){let{active:n}=rc();if(e===t)return!0;if(e<0||e>=n.length)return!1;let i=ge(me(n,e,t)),a=new Map(i.map(e=>[e.id,e])),o=v.todos;if(v.todos=v.todos.map(e=>a.get(e.id)||e),!await ec(()=>x(i)).catch(e=>(r.error(`[Todo] reorder failed:`,e),!1))){let e=new Map(o.map(e=>[e.id,e.order]));return v.todos=v.todos.map(t=>e.has(t.id)?{...t,order:e.get(t.id)}:t),I(),!1}return I(),!0}async function hc(){let{done:e}=rc();if(e.length===0)return!0;let t=e.map(e=>e.id),n=v.todos;if(v.todos=v.todos.filter(e=>!t.includes(e.id)),!await ec(()=>d(t)).catch(e=>(r.error(`[Todo] clear completed failed:`,e),!1))){let e=new Set(v.todos.map(e=>e.id)),r=n.filter(n=>t.includes(n.id)&&!e.has(n.id));return v.todos=[...v.todos,...r],I(),!1}return I(),!0}async function gc(e,t=`merge`){if(t===`replace`)return _c(e);let n=ke(v.todos,e);if(n.addedItems.length===0)return{ok:!0,added:0,skipped:n.skipped};let i=v.todos;v.todos=n.todos;let a=new Set(n.addedItems.map(e=>e.id));return await ec(()=>x(n.addedItems)).catch(e=>(r.error(`[Todo] import merge failed:`,e),!1))?(I(),{ok:!0,added:n.addedItems.length,skipped:n.skipped}):(v.todos=i.filter(e=>!a.has(e.id)),I(),{ok:!1,added:0,skipped:n.skipped})}async function _c(e){let{addedItems:t,skipped:n}=ke([],e);if(t.length===0)return{ok:!1,added:0,skipped:n,reason:`empty`};let i=v.todos,a=i.map(e=>e.id);return v.todos=t,await ec(async()=>a.length>0&&!await d(a).catch(e=>(r.error(`[Todo] replace delete failed:`,e),!1))?!1:await x(t).catch(e=>(r.error(`[Todo] replace write failed:`,e),!1))?!0:(a.length>0&&await x(i).catch(()=>!1),!1)).catch(e=>(r.error(`[Todo] replace failed:`,e),!1))?(I(),{ok:!0,added:t.length,skipped:n}):(v.todos=i,I(),{ok:!1,added:0,skipped:n})}var vc=[`all`,`active`,`done`],yc={json:{ext:`json`,type:`application/json;charset=utf-8`},md:{ext:`md`,type:`text/markdown;charset=utf-8`}};function bc(e){return e===`md`?`md`:`json`}function xc(e){return String(e).padStart(2,`0`)}function Sc(e){let t=new Date(e);return`${t.getFullYear()}-${xc(t.getMonth()+1)}-${xc(t.getDate())}`}function Cc(e,t,n=Date.now()){let r=vc.includes(e)?e:`all`;return`ai-helper-todos${r===`all`?``:`-${r}`}-${Sc(n)}.${yc[bc(t)].ext}`}function wc(e,t={}){let n=vc.includes(t.scope)?t.scope:`all`,r=bc(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:Cc(n,r,i),blob:new Blob([a],{type:yc[r].type})}}function Tc(e,t={}){let{filename:n,blob:r}=wc(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 Ec(){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 Dc(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 Oc=`<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`],Ac=[`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 Mc(e){return`<div class="todo-io-header">
232
+ <span class="todo-io-title">${j(e)}</span>
233
233
  <button type="button" class="todo-io-close" data-io-action="cancel"
234
- title="${O(t(`todoIo.close`))}" aria-label="${O(t(`todoIo.close`))}">${Mc}</button>
235
- </div>`}function Lc(e,n){return`<div class="todo-io-actions">
236
- <button type="button" class="todo-io-btn" data-io-action="cancel">${A(t(`todoIo.cancel`))}</button>
237
- <button type="button" class="todo-io-btn primary" data-io-action="confirm"${n?` disabled`:``}>${A(e)}</button>
238
- </div>`}function Rc({field:e,value:t,label:n,hint:r,checked:i,count:a,danger:o}){let s=Number.isFinite(a)?`<em class="todo-io-count" data-io-count="${a}">${a}</em>`:``;return`<label class="todo-io-option${o?` danger`:``}">
239
- <input type="radio" name="todoIo-${O(e)}" value="${O(t)}"
240
- data-io-field="${O(e)}"${i?` checked`:``} />
234
+ title="${k(t(`todoIo.close`))}" aria-label="${k(t(`todoIo.close`))}">${Oc}</button>
235
+ </div>`}function Nc(e,n){return`<div class="todo-io-actions">
236
+ <button type="button" class="todo-io-btn" data-io-action="cancel">${j(t(`todoIo.cancel`))}</button>
237
+ <button type="button" class="todo-io-btn primary" data-io-action="confirm"${n?` disabled`:``}>${j(e)}</button>
238
+ </div>`}function Pc({field:e,value:t,label:n,hint:r,checked:i,count:a,danger:o}){let s=Number.isFinite(a)?`<em class="todo-io-count" data-io-count="${a}">${a}</em>`:``;return`<label class="todo-io-option${o?` danger`:``}">
239
+ <input type="radio" name="todoIo-${k(e)}" value="${k(t)}"
240
+ data-io-field="${k(e)}"${i?` checked`:``} />
241
241
  <span class="todo-io-option-main">
242
- <span class="todo-io-option-label">${A(n)}</span>
243
- ${r?`<span class="todo-io-option-hint">${A(r)}</span>`:``}
242
+ <span class="todo-io-option-label">${j(n)}</span>
243
+ ${r?`<span class="todo-io-option-hint">${j(r)}</span>`:``}
244
244
  </span>
245
245
  ${s}
246
- </label>`}function zc(e,n={}){let r=Nc.includes(e?.scope)?e.scope:`all`,i=Pc.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])=>Rc({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])=>Rc({field:`format`,value:e,label:t,checked:e===i})).join(``);return`<div class="todo-io-card" role="dialog" aria-modal="true" tabindex="-1"
247
- aria-label="${O(t(`todoIo.exportTitle`))}">
248
- ${Ic(t(`todoIo.exportTitle`))}
246
+ </label>`}function Fc(e,n={}){let r=kc.includes(e?.scope)?e.scope:`all`,i=Ac.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])=>Pc({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])=>Pc({field:`format`,value:e,label:t,checked:e===i})).join(``);return`<div class="todo-io-card" role="dialog" aria-modal="true" tabindex="-1"
247
+ aria-label="${k(t(`todoIo.exportTitle`))}">
248
+ ${Mc(t(`todoIo.exportTitle`))}
249
249
  <div class="todo-io-body">
250
250
  <div class="todo-io-group">
251
- <div class="todo-io-group-label">${A(t(`todoIo.rangeLabel`))}</div>
252
- <div class="todo-io-options" role="radiogroup" aria-label="${O(t(`todoIo.rangeLabel`))}">${o}</div>
251
+ <div class="todo-io-group-label">${j(t(`todoIo.rangeLabel`))}</div>
252
+ <div class="todo-io-options" role="radiogroup" aria-label="${k(t(`todoIo.rangeLabel`))}">${o}</div>
253
253
  </div>
254
254
  <div class="todo-io-group">
255
- <div class="todo-io-group-label">${A(t(`todoIo.formatLabel`))}</div>
256
- <div class="todo-io-options" role="radiogroup" aria-label="${O(t(`todoIo.formatLabel`))}">${s}</div>
255
+ <div class="todo-io-group-label">${j(t(`todoIo.formatLabel`))}</div>
256
+ <div class="todo-io-options" role="radiogroup" aria-label="${k(t(`todoIo.formatLabel`))}">${s}</div>
257
257
  </div>
258
- <p class="todo-io-hint${a?` show`:``}" data-io-hint>${A(t(`todoIo.emptyRange`))}</p>
258
+ <p class="todo-io-hint${a?` show`:``}" data-io-hint>${j(t(`todoIo.emptyRange`))}</p>
259
259
  </div>
260
- ${Lc(t(`todoIo.exportAction`),a)}
261
- </div>`}function Bc(e,n={}){let r=Fc.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])=>Rc({field:`mode`,value:e,label:t,hint:n,checked:e===r,danger:e===`replace`})).join(``);return`<div class="todo-io-card" role="dialog" aria-modal="true" tabindex="-1"
262
- aria-label="${O(t(`todoIo.importTitle`))}">
263
- ${Ic(t(`todoIo.importTitle`))}
260
+ ${Nc(t(`todoIo.exportAction`),a)}
261
+ </div>`}function Ic(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])=>Pc({field:`mode`,value:e,label:t,hint:n,checked:e===r,danger:e===`replace`})).join(``);return`<div class="todo-io-card" role="dialog" aria-modal="true" tabindex="-1"
262
+ aria-label="${k(t(`todoIo.importTitle`))}">
263
+ ${Mc(t(`todoIo.importTitle`))}
264
264
  <div class="todo-io-body">
265
- <p class="todo-io-summary">${A(t(`todoIo.importSummary`,{count:i,existing:a}))}</p>
265
+ <p class="todo-io-summary">${j(t(`todoIo.importSummary`,{count:i,existing:a}))}</p>
266
266
  <div class="todo-io-group">
267
- <div class="todo-io-group-label">${A(t(`todoIo.modeLabel`))}</div>
268
- <div class="todo-io-options" role="radiogroup" aria-label="${O(t(`todoIo.modeLabel`))}">${o}</div>
267
+ <div class="todo-io-group-label">${j(t(`todoIo.modeLabel`))}</div>
268
+ <div class="todo-io-options" role="radiogroup" aria-label="${k(t(`todoIo.modeLabel`))}">${o}</div>
269
269
  </div>
270
- <p class="todo-io-warn${r===`replace`?` show`:``}" data-io-warn>${A(t(`todoIo.replaceWarn`,{count:i}))}</p>
270
+ <p class="todo-io-warn${r===`replace`?` show`:``}" data-io-warn>${j(t(`todoIo.replaceWarn`,{count:i}))}</p>
271
271
  </div>
272
- ${Lc(t(`todoIo.importAction`),!1)}
273
- </div>`}var L=null,R=null,Vc=null;function Hc(){return L||(L=document.createElement(`div`),L.className=`todo-io-overlay`,L.id=`todoIoOverlay`,L.addEventListener(`click`,e=>{if(e.target===L){Kc(null);return}let t=e.target.closest?.(`[data-io-action]`);t?.dataset.ioAction===`cancel`?Kc(null):t?.dataset.ioAction===`confirm`&&Gc()}),L.addEventListener(`change`,e=>{if(!R)return;let t=e.target.closest?.(`input[data-io-field]`);t&&(R.state[t.dataset.ioField]=t.value,Wc())}),document.body.appendChild(L),L)}function Uc(){if(!R)return;let e=Hc();e.innerHTML=R.kind===`export`?zc(R.state,R.counts):Bc(R.state,R.info),Wc()}function Wc(){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 Gc(){if(R){if(R.kind===`export`){if(!Number(R.counts[R.state.scope]||0))return;Kc({scope:R.state.scope,format:R.state.format});return}Kc(R.state.mode)}}function Kc(e){if(!R)return;let{resolve:t}=R;R=null,L?.classList.remove(`show`),Jc(),t(e)}function qc(){Vc||(Vc=e=>{e.key===`Escape`&&(e.stopPropagation(),Kc(null))},document.addEventListener(`keydown`,Vc))}function Jc(){Vc&&=(document.removeEventListener(`keydown`,Vc),null)}function Yc(e,t,n){return R&&Kc(null),new Promise(r=>{R={kind:e,state:t,...n,resolve:r},Uc(),L.classList.add(`show`),qc(),L.querySelector(`.todo-io-card`)?.focus()})}function Xc({counts:e={},scope:t=`all`,format:n=`json`}={}){return Yc(`export`,{scope:Nc.includes(t)?t:`all`,format:Pc.includes(n)?n:`json`},{counts:e})}function Zc({count:e=0,existing:t=0,mode:n=`merge`}={}){return Yc(`import`,{mode:Fc.includes(n)?n:`merge`},{info:{count:e,existing:t}})}o(()=>{R&&(Uc(),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 Qc={zh:[`日`,`一`,`二`,`三`,`四`,`五`,`六`],en:[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`]},$c=6;function el(e){let[t,n,r]=String(e||``).split(`-`).map(Number);return!t||!n||!r?null:new Date(t,n-1,r)}function tl(e){let t=el(e);return t?a()===`en`?`${t.toLocaleString(`en-US`,{month:`short`})} ${t.getDate()}`:`${t.getMonth()+1}月${t.getDate()}日`:String(e||``)}function nl(e){let t=el(e);return t?(Qc[a()]||Qc.zh)[t.getDay()]:``}function rl(e,t,n){return`<div class="todo-stats-tile${n?` ${n}`:``}">
272
+ ${Nc(t(`todoIo.importAction`),!1)}
273
+ </div>`}var L=null,R=null,Lc=null;function Rc(){return L||(L=document.createElement(`div`),L.className=`todo-io-overlay`,L.id=`todoIoOverlay`,L.addEventListener(`click`,e=>{if(e.target===L){Hc(null);return}let t=e.target.closest?.(`[data-io-action]`);t?.dataset.ioAction===`cancel`?Hc(null):t?.dataset.ioAction===`confirm`&&Vc()}),L.addEventListener(`change`,e=>{if(!R)return;let t=e.target.closest?.(`input[data-io-field]`);t&&(R.state[t.dataset.ioField]=t.value,Bc())}),document.body.appendChild(L),L)}function zc(){if(!R)return;let e=Rc();e.innerHTML=R.kind===`export`?Fc(R.state,R.counts):Ic(R.state,R.info),Bc()}function Bc(){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 Vc(){if(R){if(R.kind===`export`){if(!Number(R.counts[R.state.scope]||0))return;Hc({scope:R.state.scope,format:R.state.format});return}Hc(R.state.mode)}}function Hc(e){if(!R)return;let{resolve:t}=R;R=null,L?.classList.remove(`show`),Wc(),t(e)}function Uc(){Lc||(Lc=e=>{e.key===`Escape`&&(e.stopPropagation(),Hc(null))},document.addEventListener(`keydown`,Lc))}function Wc(){Lc&&=(document.removeEventListener(`keydown`,Lc),null)}function Gc(e,t,n){return R&&Hc(null),new Promise(r=>{R={kind:e,state:t,...n,resolve:r},zc(),L.classList.add(`show`),Uc(),L.querySelector(`.todo-io-card`)?.focus()})}function Kc({counts:e={},scope:t=`all`,format:n=`json`}={}){return Gc(`export`,{scope:kc.includes(t)?t:`all`,format:Ac.includes(n)?n:`json`},{counts:e})}function qc({count:e=0,existing:t=0,mode:n=`merge`}={}){return Gc(`import`,{mode:jc.includes(n)?n:`merge`},{info:{count:e,existing:t}})}o(()=>{R&&(zc(),L.querySelector(`.todo-io-card`)?.focus())}),e(`zh`,{todoStats:{title:`待办统计`,close:`关闭`,rate:`完成率`,doneOf:`已完成 {done} / {total}`,pending:`待处理`,doing:`处理中`,done:`已完成`,overdue:`逾期`,high:`高优先级`,week:`近 7 天完成`,dayTitle:`{date}:完成 {done} · 新增 {added}`,todayAdded:`今日新增 {n}`,todayDone:`今日完成 {n}`,streak:`连续完成 {n} 天`,highCount:`高优先级 {n}`,empty:`还没有待办,加一条就能看到趋势`}}),e(`en`,{todoStats:{title:`Todo stats`,close:`Close`,rate:`Completion`,doneOf:`{done} of {total} done`,pending:`Pending`,doing:`In progress`,done:`Done`,overdue:`Overdue`,high:`High priority`,week:`Done in last 7 days`,dayTitle:`{date}: {done} done · {added} added`,todayAdded:`{n} added today`,todayDone:`{n} done today`,streak:`{n}-day streak`,highCount:`{n} high priority`,empty:`No todos yet — add one to see the trend`}});var Jc={zh:[`日`,`一`,`二`,`三`,`四`,`五`,`六`],en:[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`]},Yc=6;function Xc(e){let[t,n,r]=String(e||``).split(`-`).map(Number);return!t||!n||!r?null:new Date(t,n-1,r)}function Zc(e){let t=Xc(e);return t?a()===`en`?`${t.toLocaleString(`en-US`,{month:`short`})} ${t.getDate()}`:`${t.getMonth()+1}月${t.getDate()}日`:String(e||``)}function Qc(e){let t=Xc(e);return t?(Jc[a()]||Jc.zh)[t.getDay()]:``}function $c(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 il(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($c,Math.round(r/n*100));return`<div class="todo-stats-bar-col" title="${t(`todoStats.dayTitle`,{date:tl(e.date),done:r,added:e.added||0})}">
276
+ </div>`}function el(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(Yc,Math.round(r/n*100));return`<div class="todo-stats-bar-col" title="${t(`todoStats.dayTitle`,{date:Zc(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">${nl(e.date)}</span>
279
- </div>`}).join(``)}</div>`}function al(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">${Qc(e.date)}</span>
279
+ </div>`}).join(``)}</div>`}function tl(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,29 +285,29 @@ import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-DvmxOw8q.js"
285
285
  <div class="todo-stats-track"><i style="width:${i}%"></i></div>
286
286
  </div>
287
287
  <div class="todo-stats-tiles">
288
- ${rl(n.pending||0,t(`todoStats.pending`))}
289
- ${rl(n.doing||0,t(`todoStats.doing`),`doing`)}
290
- ${rl(n.done||0,t(`todoStats.done`),`done`)}
291
- ${rl(n.overdue||0,t(`todoStats.overdue`),n.overdue?`alert`:``)}
288
+ ${$c(n.pending||0,t(`todoStats.pending`))}
289
+ ${$c(n.doing||0,t(`todoStats.doing`),`doing`)}
290
+ ${$c(n.done||0,t(`todoStats.done`),`done`)}
291
+ ${$c(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
- ${il(o)}
295
+ ${el(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 ol=`<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>`,sl=null,cl=null;function ll(){return sl||(sl=document.createElement(`div`),sl.className=`todo-stats-overlay`,sl.id=`todoStatsOverlay`,sl.addEventListener(`click`,e=>{(e.target===sl||e.target.closest?.(`[data-action="close-stats"]`))&&pl()}),document.body.appendChild(sl),sl)}function ul(e){let n=ll();n.innerHTML=`
303
- <div class="todo-stats-card" role="dialog" aria-modal="true" aria-label="${O(t(`todoStats.title`))}">
302
+ </div>`}var nl=`<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>`,rl=null,il=null;function al(){return rl||(rl=document.createElement(`div`),rl.className=`todo-stats-overlay`,rl.id=`todoStatsOverlay`,rl.addEventListener(`click`,e=>{(e.target===rl||e.target.closest?.(`[data-action="close-stats"]`))&&ll()}),document.body.appendChild(rl),rl)}function ol(e){let n=al();n.innerHTML=`
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="${O(t(`todoStats.close`))}" aria-label="${O(t(`todoStats.close`))}">${ol}</button>
307
+ title="${k(t(`todoStats.close`))}" aria-label="${k(t(`todoStats.close`))}">${nl}</button>
308
308
  </div>
309
- <div class="todo-stats-body">${al(e)}</div>
310
- </div>`}async function dl(){let e=await $s(),{active:t,done:n}=sc();ul(Zs([...t,...n],e))}async function fl(){await dl();let e=ll();e.classList.add(`show`),cl||(cl=e=>{e.key===`Escape`&&(e.stopPropagation(),pl())},document.addEventListener(`keydown`,cl)),e.querySelector(`.todo-stats-close`)?.focus()}function pl(){sl&&(sl.classList.remove(`show`),cl&&=(document.removeEventListener(`keydown`,cl),null))}o(()=>{sl?.classList.contains(`show`)&&dl()}),e(`zh`,{todo:{toggleTitle:`待办`,title:`待办`,fillInput:`填入输入框`,fillInputTitle:`把待办清单填入问答输入框`,placeholder:`添加待办,回车保存`,addTitle:`添加`,empty:`暂无待办`,emptyHint:`在上方输入后回车即可添加`,emptyDone:`还没有已完成的待办`,emptyDoneHint:`把某条标记完成后,它会出现在这里`,tabActive:`待办`,tabDone:`已完成`,progressLabel:`完成 {done} / {total}`,progressDoing:` · 处理中 {doing}`,startDoing:`开始处理`,markDone:`标记完成`,backToPending:`退回待办`,restoreTo:`恢复到{status}`,undoBar:`已标记完成「{title}」`,undoAction:`撤销`,restoredToast:`已恢复到{status}`,priority:`优先级`,priorityHigh:`高`,priorityMedium:`中`,priorityLow:`低`,priorityNone:`无`,priorityTitle:`优先级:{level}`,addLink:`添加链接`,editLink:`编辑链接`,linkPlaceholder:`粘贴链接,回车关联`,linkSavedToast:`已关联链接`,linkRemovedToast:`已移除链接`,linkInvalid:`链接格式不对,仅支持 http/https`,openLinkTitle:`打开 {host}`,statusTip:`当前:{status} · 点击切到{next}`,noteToggle:`备注`,notePlaceholder:`补充备注(可选)`,noteSave:`保存`,noteCancel:`取消`,editTitleAction:`编辑标题`,addNote:`添加备注`,editNote:`编辑备注`,setDue:`设置截止`,clearDue:`清除截止`,delete:`删除`,deleteConfirmTitle:`删除待办`,deleteConfirmMsg:`确定删除「{title}」吗?`,more:`更多操作`,headerMore:`更多`,copyItem:`复制本条`,editItem:`编辑`,clearCompleted:`清除已完成`,clearCompletedConfirmTitle:`清除已完成`,clearCompletedConfirmMsg:`确定删除全部 {n} 条已完成待办吗?`,statusPending:`待处理`,statusDoing:`处理中`,statusDone:`已完成`,filledToast:`已填入输入框`,copiedToast:`已复制到剪贴板`,emptyDigestToast:`暂无可复制的待办`,copyFailed:`复制失败`,noInputToast:`未找到输入框`,saveFailed:`保存失败,请重试`,deletedToast:`已删除`,clearedToast:`已清除已完成`,exportJson:`JSON(可再导入)`,exportMd:`Markdown(可读文本)`,exportEntry:`导出…`,importEntry:`导入…`,exportEmptyToast:`当前范围内没有待办`,exportedToast:`已导出 {name}`,exportFailedToast:`导出失败,请重试`,importJsonError:`不是有效的待办文件:JSON 解析失败`,importFormatError:`文件结构不对,需要待办导出文件`,importEmptyToast:`文件里没有可导入的待办,现有数据已保留`,importNothingNewToast:`没有新增待办({skipped} 条已存在或无效)`,importedToast:`已导入 {added} 条(跳过 {skipped} 条)`,importFailedToast:`导入失败,请重试`,statsEntry:`待办统计`}}),e(`en`,{todo:{toggleTitle:`Todos`,title:`Todos`,fillInput:`To input`,fillInputTitle:`Insert todo list into the chat input`,placeholder:`Add a todo, press Enter`,addTitle:`Add`,empty:`No todos`,emptyHint:`Type above and press Enter to add`,emptyDone:`Nothing completed yet`,emptyDoneHint:`Mark a todo as done and it lands here`,tabActive:`To do`,tabDone:`Done`,progressLabel:`{done} / {total} done`,progressDoing:` · {doing} in progress`,startDoing:`Start`,markDone:`Mark done`,backToPending:`Back to to-do`,restoreTo:`Restore to {status}`,undoBar:`Marked done “{title}”`,undoAction:`Undo`,restoredToast:`Restored to {status}`,priority:`Priority`,priorityHigh:`High`,priorityMedium:`Medium`,priorityLow:`Low`,priorityNone:`None`,priorityTitle:`Priority: {level}`,addLink:`Add link`,editLink:`Edit link`,linkPlaceholder:`Paste a link, press Enter`,linkSavedToast:`Link attached`,linkRemovedToast:`Link removed`,linkInvalid:`Invalid link, only http/https`,openLinkTitle:`Open {host}`,statusTip:`Now: {status} · click for {next}`,noteToggle:`Note`,notePlaceholder:`Add a note (optional)`,noteSave:`Save`,noteCancel:`Cancel`,editTitleAction:`Edit title`,addNote:`Add note`,editNote:`Edit note`,setDue:`Set due date`,clearDue:`Clear due date`,delete:`Delete`,deleteConfirmTitle:`Delete todo`,deleteConfirmMsg:`Delete "{title}"?`,more:`More actions`,headerMore:`More`,copyItem:`Copy this`,editItem:`Edit`,clearCompleted:`Clear completed`,clearCompletedConfirmTitle:`Clear completed`,clearCompletedConfirmMsg:`Delete all {n} completed todos?`,statusPending:`Pending`,statusDoing:`In progress`,statusDone:`Done`,filledToast:`Inserted into input`,copiedToast:`Copied to clipboard`,emptyDigestToast:`Nothing to copy`,copyFailed:`Copy failed`,noInputToast:`Input box not found`,saveFailed:`Failed to save, try again`,deletedToast:`Deleted`,clearedToast:`Completed todos cleared`,exportJson:`JSON (re-importable)`,exportMd:`Markdown (readable)`,exportEntry:`Export…`,importEntry:`Import…`,exportEmptyToast:`Nothing to export in this range`,exportedToast:`Exported {name}`,exportFailedToast:`Export failed, try again`,importJsonError:`Not a valid todo file: JSON parse failed`,importFormatError:`Unexpected file structure, need a todo export file`,importEmptyToast:`No importable todos in the file, existing data kept`,importNothingNewToast:`Nothing new to import ({skipped} existing or invalid)`,importedToast:`Imported {added} todos ({skipped} skipped)`,importFailedToast:`Import failed, try again`,statsEntry:`Statistics`}});var ml=`.input-container`,hl=160,gl=8,_l=108,vl=220,yl=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>`,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,bl=null,xl=null,Sl=null,Cl=null,wl=null,Tl=null,El=null,Dl=null,Ol=`active`,U=null,kl=null,Al=null,W=null,jl=new Set,Ml=null,Nl=!1,Pl=null,Fl=null,Il=null,Ll=null,Rl=0,zl=new Map,Bl=[`todo-edit-input`,`todo-note-input`,`todo-due-input`,`todo-link-input`],Vl={"todo-edit-input":`title`,"todo-note-input":`note`,"todo-due-input":`due`,"todo-link-input":`link`};function Hl(){Nl||(Nl=!0,B=document.createElement(`div`),B.className=`todo-panel-container`,B.id=`todoPanelContainer`,B.innerHTML=`
309
+ <div class="todo-stats-body">${tl(e)}</div>
310
+ </div>`}async function sl(){let e=await Ys(),{active:t,done:n}=rc();ol(qs([...t,...n],e))}async function cl(){await sl();let e=al();e.classList.add(`show`),il||(il=e=>{e.key===`Escape`&&(e.stopPropagation(),ll())},document.addEventListener(`keydown`,il)),e.querySelector(`.todo-stats-close`)?.focus()}function ll(){rl&&(rl.classList.remove(`show`),il&&=(document.removeEventListener(`keydown`,il),null))}o(()=>{rl?.classList.contains(`show`)&&sl()}),e(`zh`,{todo:{toggleTitle:`待办`,title:`待办`,fillInput:`填入输入框`,fillInputTitle:`把待办清单填入问答输入框`,placeholder:`添加待办,回车保存`,addTitle:`添加`,empty:`暂无待办`,emptyHint:`在上方输入后回车即可添加`,emptyDone:`还没有已完成的待办`,emptyDoneHint:`把某条标记完成后,它会出现在这里`,tabActive:`待办`,tabDone:`已完成`,progressLabel:`完成 {done} / {total}`,progressDoing:` · 处理中 {doing}`,startDoing:`开始处理`,markDone:`标记完成`,backToPending:`退回待办`,restoreTo:`恢复到{status}`,undoBar:`已标记完成「{title}」`,undoAction:`撤销`,restoredToast:`已恢复到{status}`,priority:`优先级`,priorityHigh:`高`,priorityMedium:`中`,priorityLow:`低`,priorityNone:`无`,priorityTitle:`优先级:{level}`,addLink:`添加链接`,editLink:`编辑链接`,linkPlaceholder:`粘贴链接,回车关联`,linkSavedToast:`已关联链接`,linkRemovedToast:`已移除链接`,linkInvalid:`链接格式不对,仅支持 http/https`,openLinkTitle:`打开 {host}`,statusTip:`当前:{status} · 点击切到{next}`,noteToggle:`备注`,notePlaceholder:`补充备注(可选)`,noteSave:`保存`,noteCancel:`取消`,editTitleAction:`编辑标题`,addNote:`添加备注`,editNote:`编辑备注`,setDue:`设置截止`,clearDue:`清除截止`,delete:`删除`,deleteConfirmTitle:`删除待办`,deleteConfirmMsg:`确定删除「{title}」吗?`,more:`更多操作`,headerMore:`更多`,copyItem:`复制本条`,editItem:`编辑`,clearCompleted:`清除已完成`,clearCompletedConfirmTitle:`清除已完成`,clearCompletedConfirmMsg:`确定删除全部 {n} 条已完成待办吗?`,statusPending:`待处理`,statusDoing:`处理中`,statusDone:`已完成`,filledToast:`已填入输入框`,copiedToast:`已复制到剪贴板`,emptyDigestToast:`暂无可复制的待办`,copyFailed:`复制失败`,noInputToast:`未找到输入框`,saveFailed:`保存失败,请重试`,deletedToast:`已删除`,clearedToast:`已清除已完成`,exportJson:`JSON(可再导入)`,exportMd:`Markdown(可读文本)`,exportEntry:`导出…`,importEntry:`导入…`,exportEmptyToast:`当前范围内没有待办`,exportedToast:`已导出 {name}`,exportFailedToast:`导出失败,请重试`,importJsonError:`不是有效的待办文件:JSON 解析失败`,importFormatError:`文件结构不对,需要待办导出文件`,importEmptyToast:`文件里没有可导入的待办,现有数据已保留`,importNothingNewToast:`没有新增待办({skipped} 条已存在或无效)`,importedToast:`已导入 {added} 条(跳过 {skipped} 条)`,importFailedToast:`导入失败,请重试`,statsEntry:`待办统计`}}),e(`en`,{todo:{toggleTitle:`Todos`,title:`Todos`,fillInput:`To input`,fillInputTitle:`Insert todo list into the chat input`,placeholder:`Add a todo, press Enter`,addTitle:`Add`,empty:`No todos`,emptyHint:`Type above and press Enter to add`,emptyDone:`Nothing completed yet`,emptyDoneHint:`Mark a todo as done and it lands here`,tabActive:`To do`,tabDone:`Done`,progressLabel:`{done} / {total} done`,progressDoing:` · {doing} in progress`,startDoing:`Start`,markDone:`Mark done`,backToPending:`Back to to-do`,restoreTo:`Restore to {status}`,undoBar:`Marked done “{title}”`,undoAction:`Undo`,restoredToast:`Restored to {status}`,priority:`Priority`,priorityHigh:`High`,priorityMedium:`Medium`,priorityLow:`Low`,priorityNone:`None`,priorityTitle:`Priority: {level}`,addLink:`Add link`,editLink:`Edit link`,linkPlaceholder:`Paste a link, press Enter`,linkSavedToast:`Link attached`,linkRemovedToast:`Link removed`,linkInvalid:`Invalid link, only http/https`,openLinkTitle:`Open {host}`,statusTip:`Now: {status} · click for {next}`,noteToggle:`Note`,notePlaceholder:`Add a note (optional)`,noteSave:`Save`,noteCancel:`Cancel`,editTitleAction:`Edit title`,addNote:`Add note`,editNote:`Edit note`,setDue:`Set due date`,clearDue:`Clear due date`,delete:`Delete`,deleteConfirmTitle:`Delete todo`,deleteConfirmMsg:`Delete "{title}"?`,more:`More actions`,headerMore:`More`,copyItem:`Copy this`,editItem:`Edit`,clearCompleted:`Clear completed`,clearCompletedConfirmTitle:`Clear completed`,clearCompletedConfirmMsg:`Delete all {n} completed todos?`,statusPending:`Pending`,statusDoing:`In progress`,statusDone:`Done`,filledToast:`Inserted into input`,copiedToast:`Copied to clipboard`,emptyDigestToast:`Nothing to copy`,copyFailed:`Copy failed`,noInputToast:`Input box not found`,saveFailed:`Failed to save, try again`,deletedToast:`Deleted`,clearedToast:`Completed todos cleared`,exportJson:`JSON (re-importable)`,exportMd:`Markdown (readable)`,exportEntry:`Export…`,importEntry:`Import…`,exportEmptyToast:`Nothing to export in this range`,exportedToast:`Exported {name}`,exportFailedToast:`Export failed, try again`,importJsonError:`Not a valid todo file: JSON parse failed`,importFormatError:`Unexpected file structure, need a todo export file`,importEmptyToast:`No importable todos in the file, existing data kept`,importNothingNewToast:`Nothing new to import ({skipped} existing or invalid)`,importedToast:`Imported {added} todos ({skipped} skipped)`,importFailedToast:`Import failed, try again`,statsEntry:`Statistics`}});var ul=`.input-container`,dl=160,fl=8,pl=108,ml=220,hl=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>`,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,gl=null,_l=null,vl=null,yl=null,bl=null,xl=null,Sl=null,Cl=null,wl=`active`,U=null,Tl=null,El=null,W=null,Dl=new Set,Ol=null,kl=!1,Al=null,jl=null,Ml=null,Nl=null,Pl=0,Fl=new Map,Il=[`todo-edit-input`,`todo-note-input`,`todo-due-input`,`todo-link-input`],Ll={"todo-edit-input":`title`,"todo-note-input":`note`,"todo-due-input":`due`,"todo-link-input":`link`};function Rl(){kl||(kl=!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
313
  ${z.listCheck}
@@ -339,125 +339,125 @@ import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-DvmxOw8q.js"
339
339
  </div>
340
340
  <div class="todo-body" id="todoBody"></div>
341
341
  </div>
342
- `,Xn(`todo`).appendChild(B),i(B),Cl=B.querySelector(`#todoPanelToggle`),V=B.querySelector(`#todoPanel`),H=B.querySelector(`#todoBody`),bl=B.querySelector(`#todoPanelCount`),xl=B.querySelector(`#todoProgressBar`),Sl=B.querySelector(`#todoAddInput`),wl=B.querySelector(`#todoBadge`),El=B.querySelector(`#todoTabActive`),Dl=B.querySelector(`#todoTabDone`),bl.textContent=t(`todo.progressLabel`,{done:0,total:0}),Cl.addEventListener(`click`,Wl),B.addEventListener(`click`,vu),B.addEventListener(`change`,Ru),B.addEventListener(`keydown`,Tu),H.addEventListener(`dragstart`,ld),H.addEventListener(`dragover`,ud),H.addEventListener(`drop`,fd),H.addEventListener(`dragend`,pd),H.addEventListener(`focusout`,zu),H.addEventListener(`focusin`,e=>{let t=e.target.closest?.(`.todo-item`);t?.dataset.id&&(Il=t.dataset.id)}),B.addEventListener(`pointerdown`,e=>{let t=e.target?.closest?.(`[data-action="link-cancel"]`);t&&(e.preventDefault(),Uu(t.dataset.id||W))}),document.addEventListener(`keydown`,e=>{e.key===`Escape`&&Tl&&qu()}),document.addEventListener(`keydown`,Ou),document.addEventListener(`click`,e=>{Tl&&(Tl.contains(e.target)||qu())},!0),ac(()=>K()),chrome.runtime.onMessage.addListener(e=>{e?.type===`TODO_CHANGED`&&oc().catch(()=>{})}),o(()=>{i(B),K()}),n().then(()=>{i(B),K()}),K())}function Ul(){return!!V&&V.classList.contains(`expanded`)}function Wl(){Ul()?Kl():Gl()}function Gl(){Ol=`active`,Pl=null,Rl=0,V.style.removeProperty(`height`),K(),V.classList.add(`expanded`),Cl.classList.add(`active`),iu(),ru(),setTimeout(()=>{Ul()&&Sl.focus()},60)}function Kl(){V.classList.remove(`expanded`),Cl.classList.remove(`active`),au(),V.style.removeProperty(`--fit-y`),V.style.removeProperty(`--todo-max-h`),V.style.removeProperty(`height`),Rl=0,qu(),Wu(),su()}function ql(){Bl.forEach(e=>{H.querySelectorAll(`.${e}`).forEach(t=>{let n=t.dataset.id;if(!n)return;let r=zl.get(n)||{};r[Vl[e]]=t.value,zl.set(n,r)})})}function Jl(e){if(zl.size===0)return;let t=new Set(e.map(e=>e.id));for(let e of[...zl.keys()])t.has(e)||zl.delete(e)}function G(e){e?zl.delete(e):zl.clear()}function Yl(e,t){let n=zl.get(e);return n&&n[t]!==void 0?n[t]:null}function Xl(){let e=document.activeElement;if(!e||!H.contains(e))return null;let t=Bl.find(t=>e.classList.contains(t));return!t||!e.dataset.id?null:{cls:t,id:e.dataset.id,caret:Zl(e)}}function Zl(e){try{return e.selectionStart}catch{return null}}function Ql(e){return H.querySelector(`.${e.cls}[data-id="${O(e.id)}"]`)}function $l(e){let t=Ql(e);if(t&&(t.focus(),e.caret!==null))try{t.selectionStart=t.selectionEnd=e.caret}catch{}}function eu(){if(U){hu();return}if(kl){let e=Ql({cls:`todo-note-input`,id:kl});e&&e.focus();return}if(Al){let e=Ql({cls:`todo-due-input`,id:Al});e&&e.focus();return}if(W){let e=Ql({cls:`todo-link-input`,id:W});if(!e)return;e.focus(),e.selectionStart=e.selectionEnd=e.value.length}}function K(){if(!H)return;ql();let e=Xl(),n=document.activeElement?.closest?.(`.todo-item`)?.dataset.id||null,{active:r,done:i,stats:a}=sc();bl.textContent=t(`todo.progressLabel`,{done:a.done,total:a.total})+(a.doing>0?t(`todo.progressDoing`,{doing:a.doing}):``),xl.style.width=a.total?`${Math.round(a.done/a.total*100)}%`:`0%`,cu(r.length),tu(r.length,i.length);let o=Ol===`done`?i:r,s=[];if(Jl([...r,...i]),Pl&&s.push(`<div class="todo-undo">
343
- <span class="todo-undo-text">${A(t(`todo.undoBar`,{title:Pl.title}))}</span>
344
- <button class="todo-mini-btn" data-action="undo-complete" data-id="${O(Pl.id)}">${A(t(`todo.undoAction`))}</button>
345
- </div>`),Ol===`done`&&i.length>0&&s.push(`<button class="todo-clear-done" data-action="clear-completed-btn">
346
- ${z.trash}<span>${A(t(`todo.clearCompleted`))} (${i.length})</span>
347
- </button>`),o.length===0){let e=Ol===`done`;s.push(`<div class="todo-empty">
348
- <div class="todo-empty-title">${A(t(e?`todo.emptyDone`:`todo.empty`))}</div>
349
- <div class="todo-empty-hint">${A(t(e?`todo.emptyDoneHint`:`todo.emptyHint`))}</div>
350
- </div>`)}else s.push(`<div class="todo-list" data-group="${Ol}">${o.map(e=>mu(e,Ol)).join(``)}</div>`);H.innerHTML=s.join(``),e?$l(e):n?Mu(n):eu(),ru()}function tu(e,t){if(!El||!Dl)return;let n=Ol===`done`;El.classList.toggle(`active`,!n),Dl.classList.toggle(`active`,n),El.setAttribute(`aria-selected`,String(!n)),Dl.setAttribute(`aria-selected`,String(n)),El.querySelector(`.todo-tab-count`).textContent=String(e),Dl.querySelector(`.todo-tab-count`).textContent=String(t)}function nu(){let e=document.querySelector(ml)?.getBoundingClientRect();return e&&e.height>0&&Number.isFinite(e.top)?e.top:window.innerHeight-hl}function ru(){!V||!Ul()||(V.style.removeProperty(`--fit-y`),requestAnimationFrame(()=>{if(!V||!Ul())return;let e=nu()-gl,t=V.getBoundingClientRect();if(!t.height)return;let n=Math.max(vl,Math.floor(e-_l));V.style.setProperty(`--todo-max-h`,`${n}px`),Rl&&(V.style.height=`auto`),Rl=Math.min(n,Math.max(Rl,V.offsetHeight)),V.style.height=`${Rl}px`;let r=Math.floor(e-t.bottom);r&&V.style.setProperty(`--fit-y`,`${r}px`)}))}function iu(){au(),window.addEventListener(`resize`,ru);let e=document.querySelector(ml);e&&typeof ResizeObserver<`u`&&(Ll=new ResizeObserver(()=>ru()),Ll.observe(e))}function au(){window.removeEventListener(`resize`,ru),Ll?.disconnect(),Ll=null}function ou(e){Pl={id:e.id,title:e.title},clearTimeout(Fl),Fl=setTimeout(()=>{Pl=null,K()},yl)}function su(){clearTimeout(Fl),Fl=null,Pl=null}function cu(e){wl&&(e>0?(wl.textContent=e>99?`99+`:String(e),wl.style.display=``):wl.style.display=`none`)}function lu(e){return e===D.DONE?t(`todo.statusDone`):e===D.DOING?t(`todo.statusDoing`):t(`todo.statusPending`)}function uu(e){let n=t(`todo.statusTip`,{status:lu(e.status),next:lu(He(e.status))}),r=e.status===D.DONE?z.check:e.status===D.DOING?`<i></i>`:``;return`<button class="todo-status" data-action="cycle" data-id="${O(e.id)}"
351
- title="${O(n)}" aria-label="${O(n)}">${r}</button>`}function du(e){let n=Fe(e);if(!n)return``;let r=t(`todo.openLinkTitle`,{host:n});return`<button class="todo-link-chip" data-action="open-link" data-id="${O(e.id)}"
352
- title="${O(r)}" aria-label="${O(r)}">${z.link}<span>${A(n)}</span></button>`}function fu(e){let n=du(e);if(e.status===D.DONE)return`<div class="todo-meta">${n}<span>${A(ze(e))}</span></div>`;let r=[];if(n&&r.push(n),Number.isFinite(e.dueAt)){let n=Oe(e),i=n?t(`todoTime.overdueStamp`,{date:Ee(e.dueAt)}):Ee(e.dueAt);r.push(`<span class="todo-due${n?` overdue`:``}">${z.alert}${A(i)}</span>`)}let i=Pe(e.createdAt);return i&&r.push(`<span>${A(i)}</span>`),r.length===0?``:`<div class="todo-meta">${r.join(`<span class="todo-sep">·</span>`)}</div>`}function pu(e){let n=jl.has(e.id),r=kl===e.id,i=!!(e.note&&e.note.trim());if(r){let n=Yl(e.id,`note`);return`<div class="todo-note-editor">
353
- <textarea class="todo-note-input" data-id="${O(e.id)}" rows="2"
354
- placeholder="${O(t(`todo.notePlaceholder`))}">${A(n===null?e.note||``:n)}</textarea>
342
+ `,Et(`todo`).appendChild(B),i(B),yl=B.querySelector(`#todoPanelToggle`),V=B.querySelector(`#todoPanel`),H=B.querySelector(`#todoBody`),gl=B.querySelector(`#todoPanelCount`),_l=B.querySelector(`#todoProgressBar`),vl=B.querySelector(`#todoAddInput`),bl=B.querySelector(`#todoBadge`),Sl=B.querySelector(`#todoTabActive`),Cl=B.querySelector(`#todoTabDone`),gl.textContent=t(`todo.progressLabel`,{done:0,total:0}),yl.addEventListener(`click`,Bl),B.addEventListener(`click`,mu),B.addEventListener(`change`,Pu),B.addEventListener(`keydown`,xu),H.addEventListener(`dragstart`,ad),H.addEventListener(`dragover`,od),H.addEventListener(`drop`,cd),H.addEventListener(`dragend`,ld),H.addEventListener(`focusout`,Fu),H.addEventListener(`focusin`,e=>{let t=e.target.closest?.(`.todo-item`);t?.dataset.id&&(Ml=t.dataset.id)}),B.addEventListener(`pointerdown`,e=>{let t=e.target?.closest?.(`[data-action="link-cancel"]`);t&&(e.preventDefault(),zu(t.dataset.id||W))}),document.addEventListener(`keydown`,e=>{e.key===`Escape`&&xl&&Uu()}),document.addEventListener(`keydown`,wu),document.addEventListener(`click`,e=>{xl&&(xl.contains(e.target)||Uu())},!0),tc(()=>K()),chrome.runtime.onMessage.addListener(e=>{e?.type===`TODO_CHANGED`&&nc().catch(()=>{})}),o(()=>{i(B),K()}),n().then(()=>{i(B),K()}),K())}function zl(){return!!V&&V.classList.contains(`expanded`)}function Bl(){zl()?Hl():Vl()}function Vl(){wl=`active`,Al=null,Pl=0,V.style.removeProperty(`height`),K(),V.classList.add(`expanded`),yl.classList.add(`active`),eu(),$l(),setTimeout(()=>{zl()&&vl.focus()},60)}function Hl(){V.classList.remove(`expanded`),yl.classList.remove(`active`),tu(),V.style.removeProperty(`--fit-y`),V.style.removeProperty(`--todo-max-h`),V.style.removeProperty(`height`),Pl=0,Uu(),Bu(),ru()}function Ul(){Il.forEach(e=>{H.querySelectorAll(`.${e}`).forEach(t=>{let n=t.dataset.id;if(!n)return;let r=Fl.get(n)||{};r[Ll[e]]=t.value,Fl.set(n,r)})})}function Wl(e){if(Fl.size===0)return;let t=new Set(e.map(e=>e.id));for(let e of[...Fl.keys()])t.has(e)||Fl.delete(e)}function G(e){e?Fl.delete(e):Fl.clear()}function Gl(e,t){let n=Fl.get(e);return n&&n[t]!==void 0?n[t]:null}function Kl(){let e=document.activeElement;if(!e||!H.contains(e))return null;let t=Il.find(t=>e.classList.contains(t));return!t||!e.dataset.id?null:{cls:t,id:e.dataset.id,caret:ql(e)}}function ql(e){try{return e.selectionStart}catch{return null}}function Jl(e){return H.querySelector(`.${e.cls}[data-id="${k(e.id)}"]`)}function Yl(e){let t=Jl(e);if(t&&(t.focus(),e.caret!==null))try{t.selectionStart=t.selectionEnd=e.caret}catch{}}function Xl(){if(U){du();return}if(Tl){let e=Jl({cls:`todo-note-input`,id:Tl});e&&e.focus();return}if(El){let e=Jl({cls:`todo-due-input`,id:El});e&&e.focus();return}if(W){let e=Jl({cls:`todo-link-input`,id:W});if(!e)return;e.focus(),e.selectionStart=e.selectionEnd=e.value.length}}function K(){if(!H)return;Ul();let e=Kl(),n=document.activeElement?.closest?.(`.todo-item`)?.dataset.id||null,{active:r,done:i,stats:a}=rc();gl.textContent=t(`todo.progressLabel`,{done:a.done,total:a.total})+(a.doing>0?t(`todo.progressDoing`,{doing:a.doing}):``),_l.style.width=a.total?`${Math.round(a.done/a.total*100)}%`:`0%`,iu(r.length),Zl(r.length,i.length);let o=wl===`done`?i:r,s=[];if(Wl([...r,...i]),Al&&s.push(`<div class="todo-undo">
343
+ <span class="todo-undo-text">${j(t(`todo.undoBar`,{title:Al.title}))}</span>
344
+ <button class="todo-mini-btn" data-action="undo-complete" data-id="${k(Al.id)}">${j(t(`todo.undoAction`))}</button>
345
+ </div>`),wl===`done`&&i.length>0&&s.push(`<button class="todo-clear-done" data-action="clear-completed-btn">
346
+ ${z.trash}<span>${j(t(`todo.clearCompleted`))} (${i.length})</span>
347
+ </button>`),o.length===0){let e=wl===`done`;s.push(`<div class="todo-empty">
348
+ <div class="todo-empty-title">${j(t(e?`todo.emptyDone`:`todo.empty`))}</div>
349
+ <div class="todo-empty-hint">${j(t(e?`todo.emptyDoneHint`:`todo.emptyHint`))}</div>
350
+ </div>`)}else s.push(`<div class="todo-list" data-group="${wl}">${o.map(e=>uu(e,wl)).join(``)}</div>`);H.innerHTML=s.join(``),e?Yl(e):n?Ou(n):Xl(),$l()}function Zl(e,t){if(!Sl||!Cl)return;let n=wl===`done`;Sl.classList.toggle(`active`,!n),Cl.classList.toggle(`active`,n),Sl.setAttribute(`aria-selected`,String(!n)),Cl.setAttribute(`aria-selected`,String(n)),Sl.querySelector(`.todo-tab-count`).textContent=String(e),Cl.querySelector(`.todo-tab-count`).textContent=String(t)}function Ql(){let e=document.querySelector(ul)?.getBoundingClientRect();return e&&e.height>0&&Number.isFinite(e.top)?e.top:window.innerHeight-dl}function $l(){!V||!zl()||(V.style.removeProperty(`--fit-y`),requestAnimationFrame(()=>{if(!V||!zl())return;let e=Ql()-fl,t=V.getBoundingClientRect();if(!t.height)return;let n=Math.max(ml,Math.floor(e-pl));V.style.setProperty(`--todo-max-h`,`${n}px`),Pl&&(V.style.height=`auto`),Pl=Math.min(n,Math.max(Pl,V.offsetHeight)),V.style.height=`${Pl}px`;let r=Math.floor(e-t.bottom);r&&V.style.setProperty(`--fit-y`,`${r}px`)}))}function eu(){tu(),window.addEventListener(`resize`,$l);let e=document.querySelector(ul);e&&typeof ResizeObserver<`u`&&(Nl=new ResizeObserver(()=>$l()),Nl.observe(e))}function tu(){window.removeEventListener(`resize`,$l),Nl?.disconnect(),Nl=null}function nu(e){Al={id:e.id,title:e.title},clearTimeout(jl),jl=setTimeout(()=>{Al=null,K()},hl)}function ru(){clearTimeout(jl),jl=null,Al=null}function iu(e){bl&&(e>0?(bl.textContent=e>99?`99+`:String(e),bl.style.display=``):bl.style.display=`none`)}function au(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:au(e.status),next:au(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)}"
351
+ title="${k(n)}" aria-label="${k(n)}">${r}</button>`}function su(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)}"
352
+ title="${k(r)}" aria-label="${k(r)}">${z.link}<span>${j(n)}</span></button>`}function cu(e){let n=su(e);if(e.status===O.DONE)return`<div class="todo-meta">${n}<span>${j(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}${j(i)}</span>`)}let i=Ne(e.createdAt);return i&&r.push(`<span>${j(i)}</span>`),r.length===0?``:`<div class="todo-meta">${r.join(`<span class="todo-sep">·</span>`)}</div>`}function lu(e){let n=Dl.has(e.id),r=Tl===e.id,i=!!(e.note&&e.note.trim());if(r){let n=Gl(e.id,`note`);return`<div class="todo-note-editor">
353
+ <textarea class="todo-note-input" data-id="${k(e.id)}" rows="2"
354
+ placeholder="${k(t(`todo.notePlaceholder`))}">${j(n===null?e.note||``:n)}</textarea>
355
355
  <div class="todo-note-editor-actions">
356
- <button class="todo-mini-btn" data-action="note-save" data-id="${O(e.id)}">${A(t(`todo.noteSave`))}</button>
357
- <button class="todo-mini-btn ghost" data-action="note-cancel" data-id="${O(e.id)}">${A(t(`todo.noteCancel`))}</button>
356
+ <button class="todo-mini-btn" data-action="note-save" data-id="${k(e.id)}">${j(t(`todo.noteSave`))}</button>
357
+ <button class="todo-mini-btn ghost" data-action="note-cancel" data-id="${k(e.id)}">${j(t(`todo.noteCancel`))}</button>
358
358
  </div>
359
- </div>`}return i?`<button class="todo-note-toggle${n?` open`:``}" data-action="toggle-note" data-id="${O(e.id)}">
360
- ${z.chevron}<span>${A(t(`todo.noteToggle`))}</span>
359
+ </div>`}return i?`<button class="todo-note-toggle${n?` open`:``}" data-action="toggle-note" data-id="${k(e.id)}">
360
+ ${z.chevron}<span>${j(t(`todo.noteToggle`))}</span>
361
361
  </button>
362
- ${n?`<div class="todo-note">${A(e.note)}</div>`:``}`:``}function mu(e,n){let r=e.status===D.DONE,i=U===e.id,a=[`todo-item`];e.status===D.DOING&&a.push(`doing`),r&&a.push(`done`),e.priority&&a.push(`prio-${e.priority}`),Al===e.id&&a.push(`editing-due`);let o=Yl(e.id,`title`),s=i?`<input type="text" class="todo-edit-input" data-id="${O(e.id)}" value="${O(o===null?e.title:o)}" />`:`<div class="todo-name">${A(e.title)}</div>`,c=Yl(e.id,`due`),l=Al===e.id?`<div class="todo-due-editor">
363
- <input type="date" class="todo-due-input" data-id="${O(e.id)}" value="${O(c===null?gu(e.dueAt):c)}" />
364
- <button class="todo-mini-btn ghost" data-action="due-clear" data-id="${O(e.id)}">${A(t(`todo.clearDue`))}</button>
365
- </div>`:``,u=Yl(e.id,`link`),d=W===e.id?`<div class="todo-link-editor">
366
- <input type="text" class="todo-link-input" data-id="${O(e.id)}" autocomplete="off"
367
- placeholder="${O(t(`todo.linkPlaceholder`))}" value="${O(u===null?e.link||``:u)}" />
368
- <button class="todo-mini-btn ghost" data-action="link-cancel" data-id="${O(e.id)}">${A(t(`todo.noteCancel`))}</button>
369
- </div>`:``,f=n===`active`?` draggable="true"`:``,p=U===e.id||kl===e.id||Al===e.id||W===e.id,m=`
362
+ ${n?`<div class="todo-note">${j(e.note)}</div>`:``}`:``}function uu(e,n){let r=e.status===O.DONE,i=U===e.id,a=[`todo-item`];e.status===O.DOING&&a.push(`doing`),r&&a.push(`done`),e.priority&&a.push(`prio-${e.priority}`),El===e.id&&a.push(`editing-due`);let o=Gl(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">${j(e.title)}</div>`,c=Gl(e.id,`due`),l=El===e.id?`<div class="todo-due-editor">
363
+ <input type="date" class="todo-due-input" data-id="${k(e.id)}" value="${k(c===null?fu(e.dueAt):c)}" />
364
+ <button class="todo-mini-btn ghost" data-action="due-clear" data-id="${k(e.id)}">${j(t(`todo.clearDue`))}</button>
365
+ </div>`:``,u=Gl(e.id,`link`),d=W===e.id?`<div class="todo-link-editor">
366
+ <input type="text" class="todo-link-input" data-id="${k(e.id)}" autocomplete="off"
367
+ placeholder="${k(t(`todo.linkPlaceholder`))}" value="${k(u===null?e.link||``:u)}" />
368
+ <button class="todo-mini-btn ghost" data-action="link-cancel" data-id="${k(e.id)}">${j(t(`todo.noteCancel`))}</button>
369
+ </div>`:``,f=n===`active`?` draggable="true"`:``,p=U===e.id||Tl===e.id||El===e.id||W===e.id,m=`
370
370
  <div class="todo-item-actions">
371
- ${r?`<button class="todo-act" data-action="restore" data-id="${O(e.id)}" title="${O(t(`todo.restoreTo`,{status:lu(Ue(e))}))}" aria-label="${O(t(`todo.restoreTo`,{status:lu(Ue(e))}))}">${z.undo}</button>`:``}
372
- <button class="todo-act" data-action="edit-title" data-id="${O(e.id)}" title="${O(t(`todo.editItem`))}" aria-label="${O(t(`todo.editItem`))}">${z.edit}</button>
373
- <button class="todo-act" data-action="copy-item" data-id="${O(e.id)}" title="${O(t(`todo.copyItem`))}" aria-label="${O(t(`todo.copyItem`))}">${z.copy}</button>
374
- <button class="todo-act" data-action="fill-item" data-id="${O(e.id)}" title="${O(t(`todo.fillInput`))}" aria-label="${O(t(`todo.fillInput`))}">${z.fill}</button>
375
- <button class="todo-act" data-action="row-more" data-id="${O(e.id)}" title="${O(t(`todo.more`))}" aria-label="${O(t(`todo.more`))}">${z.more}</button>
376
- </div>`;return`<div class="${a.join(` `)}" data-id="${O(e.id)}" data-group="${n}"${f} tabindex="0" data-priority="${O(e.priority||``)}">
377
- ${uu(e)}
371
+ ${r?`<button class="todo-act" data-action="restore" data-id="${k(e.id)}" title="${k(t(`todo.restoreTo`,{status:au(He(e))}))}" aria-label="${k(t(`todo.restoreTo`,{status:au(He(e))}))}">${z.undo}</button>`:``}
372
+ <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>
373
+ <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>
374
+ <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>
375
+ <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>
376
+ </div>`;return`<div class="${a.join(` `)}" data-id="${k(e.id)}" data-group="${n}"${f} tabindex="0" data-priority="${k(e.priority||``)}">
377
+ ${ou(e)}
378
378
  <div class="todo-main">
379
379
  ${s}
380
- ${pu(e)}
380
+ ${lu(e)}
381
381
  ${l}
382
382
  ${d}
383
- ${fu(e)}
383
+ ${cu(e)}
384
384
  </div>
385
385
  ${p?``:m}
386
- </div>`}function hu(){let e=H.querySelector(`.todo-edit-input[data-id="${U}"]`);e&&(e.focus(),e.selectionStart=e.selectionEnd=e.value.length)}function gu(e){if(!Number.isFinite(e))return``;let t=new Date(e);if(isNaN(t.getTime()))return``;let n=e=>e<10?`0`+e:String(e);return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())}`}function q(e,n){Promise.resolve(e).then(e=>{if(e===!0||e&&e.ok===!0){n&&k(n,`success`);return}k(t(e&&e.reason===`invalid`?`todo.linkInvalid`:`todo.saveFailed`),`error`)})}function _u(e){let n=e&&e.link;if(!n||!De(n)){k(t(`todo.linkInvalid`),`error`);return}try{chrome.tabs.create({url:n})}catch(e){r.warn(`[Todo] open link failed:`,e),k(t(`todo.copyFailed`),`error`)}}function vu(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(),Kl();return;case`fill-item`:e.stopPropagation(),od(r);return;case`copy-item`:e.stopPropagation(),sd(r);return;case`header-more`:e.stopPropagation(),$u(t);return;case`add`:e.stopPropagation(),Bu();return;case`switch-tab`:bu(t.dataset.tab);return;case`undo-complete`:e.stopPropagation(),Cu(r);return;case`restore`:e.stopPropagation(),Su(r);return;case`open-link`:e.stopPropagation(),_u(yu(r));return;case`clear-completed-btn`:e.stopPropagation(),wu();return;case`cycle`:e.stopPropagation(),q(pc(r));return;case`toggle-note`:e.stopPropagation(),jl.has(r)?jl.delete(r):jl.add(r),K();return;case`edit-title`:e.stopPropagation(),Wu(),U=r,K();return;case`row-more`:e.stopPropagation(),Qu(t,r);return;case`note-save`:e.stopPropagation(),Vu(r);return;case`note-cancel`:e.stopPropagation(),kl=null,G(r),K();return;case`due-clear`:e.stopPropagation(),Al=null,G(r),q(dc(r,{dueAt:null}));return;case`link-cancel`:e.stopPropagation(),Uu(r);return;default:return}}function yu(e){let{active:t,done:n}=sc();return[...t,...n].find(t=>t.id===e)||null}function bu(e){let t=e===`done`?`done`:`active`;t!==Ol&&(Ol=t,Wu(),K())}function xu(e){let t=yu(e);t&&(ou(t),q(fc(e,D.DONE)))}function Su(e){let n=yu(e);if(!n)return;let r=Ue(n);su(),q(mc(e),t(`todo.restoredToast`,{status:lu(r)}))}function Cu(e){Su(e)}async function wu(){let{done:e}=sc();e.length!==0&&await Gu(t(`todo.clearCompletedConfirmMsg`,{n:e.length}),t(`todo.clearCompletedConfirmTitle`))&&q(yc(),t(`todo.clearedToast`))}function Tu(e){if((e.key===`ArrowUp`||e.key===`ArrowDown`)&&!e.target.closest?.(`input, textarea, [contenteditable="true"]`)&&e.target.closest?.(`.todo-item`)){e.preventDefault(),ju(e.key===`ArrowDown`?1:-1);return}if(e.target===Sl){e.key===`Enter`?(e.preventDefault(),Bu()):e.key===`Escape`&&(e.stopPropagation(),Sl.value=``,Ul()&&Kl());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(U=null,!n){G(t),K();return}G(t),q(dc(t,{title:n}))}else e.key===`Escape`&&(e.stopPropagation(),U=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(),Vu(e.target.dataset.id)):e.key===`Escape`&&(e.stopPropagation(),kl=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(),Hu(t,e.target.value)):e.key===`Escape`&&(e.stopPropagation(),Uu(t))}}var Eu={KeyT:()=>Wl(),KeyA:()=>Nu(),KeyB:e=>Pu(e),KeyL:e=>Fu(e),KeyD:e=>Iu(e),KeyP:e=>Lu(e)},Du=new Set([`KeyT`,`KeyA`]);function Ou(e){if(!e.altKey||e.shiftKey||e.ctrlKey||e.metaKey)return;let t=Eu[e.code];if(!t)return;if(Du.has(e.code)){e.preventDefault(),t();return}let n=Au();n&&(e.preventDefault(),t(n))}function ku(){return H?Array.from(H.querySelectorAll(`.todo-item`)):[]}function Au(){if(!Ul())return null;let e=document.activeElement?.closest?.(`.todo-item`);if(e?.dataset.id&&H.contains(e))return e.dataset.id;let t=ku();return Il&&t.some(e=>e.dataset.id===Il)?Il:t[0]?.dataset.id||null}function ju(e){let t=ku();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 Mu(e){let t=ku().find(t=>t.dataset.id===e);t&&t.focus()}function Nu(){if(Ul()){Sl.focus();return}Gl()}function Pu(e){kl=e,jl.add(e),K()}function Fu(e){W=e,K()}function Iu(e){let t=yu(e);t&&(t.status===D.DONE?Su(e):xu(e))}function Lu(e){let t=yu(e);t&&q(hc(e,Ce(t.priority)))}function Ru(e){if(e.target.classList?.contains(`todo-link-input`)){let t=e.target.dataset.id;if(!W||W!==t)return;Hu(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(Al=null,G(t),!n){q(dc(t,{dueAt:null}));return}let r=new Date(n+`T00:00:00`);q(dc(t,{dueAt:isNaN(r.getTime())?null:r.getTime()}))}function zu(e){if(e.target?.classList?.contains(`todo-link-input`)){let t=e.target.dataset.id;if(!W||W!==t)return;Hu(t,e.target.value);return}if(!e.target?.classList?.contains(`todo-edit-input`))return;let n=e.target.dataset.id;if(!U||U!==n)return;let r=e.target.value.trim();if(U=null,!r){G(n),K();return}G(n),dc(n,{title:r}).then(e=>{e?K():k(t(`todo.saveFailed`),`error`)})}async function Bu(){let e=Sl.value.trim();e&&(Sl.value=``,Ol===`done`&&(Ol=`active`),await uc(e)||k(t(`todo.saveFailed`),`error`),Sl.focus())}function Vu(e){let t=H.querySelector(`.todo-note-input[data-id="${O(e)}"]`),n=t?t.value:``;kl=null,jl.delete(e),G(e),q(dc(e,{note:n}))}function Hu(e,n){let r=!!yu(e)?.link;W=null,G(e);let i=String(n||``).trim();q(gc(e,i),t(i?`todo.linkSavedToast`:r?`todo.linkRemovedToast`:`todo.linkSavedToast`))}function Uu(e){W=null,G(e),K()}function Wu(){let e=U||kl||Al||W;U=null,kl=null,Al=null,W=null,G(),e&&K()}async function Gu(e,t){return typeof window<`u`&&typeof window.showCustomConfirm==`function`?!!await window.showCustomConfirm(e,t):!1}function Ku(){return Tl||(Tl=document.createElement(`div`),Tl.className=`todo-menu`,document.body.appendChild(Tl),Tl.addEventListener(`click`,e=>{let t=e.target.closest(`[data-priority-value]`);if(t){let e=t.dataset.menuId,n=t.dataset.priorityValue||null;qu(),q(hc(e,n));return}let n=e.target.closest(`[data-menu-action]`);if(!n)return;let{menuAction:r,menuId:i}=n.dataset;qu(),id(r,i)}),Tl)}function qu(){Tl&&=(Tl.remove(),null)}function Ju(e){return e?`<kbd class="todo-menu-kbd">${A(e)}</kbd>`:``}function Yu(e,n){if(e.swatches){let r=[[``,t(`todo.priorityNone`)],[Be.LOW,t(`todo.priorityLow`)],[Be.MEDIUM,t(`todo.priorityMedium`)],[Be.HIGH,t(`todo.priorityHigh`)]];return`<div class="todo-menu-row">
387
- <span class="todo-menu-row-label">${A(e.label)}</span>
386
+ </div>`}function du(){let e=H.querySelector(`.todo-edit-input[data-id="${U}"]`);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&&A(n,`success`);return}A(t(e&&e.reason===`invalid`?`todo.linkInvalid`:`todo.saveFailed`),`error`)})}function pu(e){let n=e&&e.link;if(!n||!Ee(n)){A(t(`todo.linkInvalid`),`error`);return}try{chrome.tabs.create({url:n})}catch(e){r.warn(`[Todo] open link failed:`,e),A(t(`todo.copyFailed`),`error`)}}function mu(e){let t=e.target.closest(`[data-action]`);if(!t)return;let n=t.dataset.action,r=t.dataset.id;switch(n){case`close`:e.stopPropagation(),Hl();return;case`fill-item`:e.stopPropagation(),nd(r);return;case`copy-item`:e.stopPropagation(),rd(r);return;case`header-more`:e.stopPropagation(),Yu(t);return;case`add`:e.stopPropagation(),Iu();return;case`switch-tab`:gu(t.dataset.tab);return;case`undo-complete`:e.stopPropagation(),yu(r);return;case`restore`:e.stopPropagation(),vu(r);return;case`open-link`:e.stopPropagation(),pu(hu(r));return;case`clear-completed-btn`:e.stopPropagation(),bu();return;case`cycle`:e.stopPropagation(),q(lc(r));return;case`toggle-note`:e.stopPropagation(),Dl.has(r)?Dl.delete(r):Dl.add(r),K();return;case`edit-title`:e.stopPropagation(),Bu(),U=r,K();return;case`row-more`:e.stopPropagation(),Ju(t,r);return;case`note-save`:e.stopPropagation(),Lu(r);return;case`note-cancel`:e.stopPropagation(),Tl=null,G(r),K();return;case`due-clear`:e.stopPropagation(),El=null,G(r),q(sc(r,{dueAt:null}));return;case`link-cancel`:e.stopPropagation(),zu(r);return;default:return}}function hu(e){let{active:t,done:n}=rc();return[...t,...n].find(t=>t.id===e)||null}function gu(e){let t=e===`done`?`done`:`active`;t!==wl&&(wl=t,Bu(),K())}function _u(e){let t=hu(e);t&&(nu(t),q(cc(e,O.DONE)))}function vu(e){let n=hu(e);if(!n)return;let r=He(n);ru(),q(uc(e),t(`todo.restoredToast`,{status:au(r)}))}function yu(e){vu(e)}async function bu(){let{done:e}=rc();e.length!==0&&await Vu(t(`todo.clearCompletedConfirmMsg`,{n:e.length}),t(`todo.clearCompletedConfirmTitle`))&&q(hc(),t(`todo.clearedToast`))}function xu(e){if((e.key===`ArrowUp`||e.key===`ArrowDown`)&&!e.target.closest?.(`input, textarea, [contenteditable="true"]`)&&e.target.closest?.(`.todo-item`)){e.preventDefault(),Du(e.key===`ArrowDown`?1:-1);return}if(e.target===vl){e.key===`Enter`?(e.preventDefault(),Iu()):e.key===`Escape`&&(e.stopPropagation(),vl.value=``,zl()&&Hl());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(U=null,!n){G(t),K();return}G(t),q(sc(t,{title:n}))}else e.key===`Escape`&&(e.stopPropagation(),U=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(),Lu(e.target.dataset.id)):e.key===`Escape`&&(e.stopPropagation(),Tl=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(),Ru(t,e.target.value)):e.key===`Escape`&&(e.stopPropagation(),zu(t))}}var Su={KeyT:()=>Bl(),KeyA:()=>ku(),KeyB:e=>Au(e),KeyL:e=>ju(e),KeyD:e=>Mu(e),KeyP:e=>Nu(e)},Cu=new Set([`KeyT`,`KeyA`]);function wu(e){if(!e.altKey||e.shiftKey||e.ctrlKey||e.metaKey)return;let t=Su[e.code];if(!t)return;if(Cu.has(e.code)){e.preventDefault(),t();return}let n=Eu();n&&(e.preventDefault(),t(n))}function Tu(){return H?Array.from(H.querySelectorAll(`.todo-item`)):[]}function Eu(){if(!zl())return null;let e=document.activeElement?.closest?.(`.todo-item`);if(e?.dataset.id&&H.contains(e))return e.dataset.id;let t=Tu();return Ml&&t.some(e=>e.dataset.id===Ml)?Ml:t[0]?.dataset.id||null}function Du(e){let t=Tu();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 Ou(e){let t=Tu().find(t=>t.dataset.id===e);t&&t.focus()}function ku(){if(zl()){vl.focus();return}Vl()}function Au(e){Tl=e,Dl.add(e),K()}function ju(e){W=e,K()}function Mu(e){let t=hu(e);t&&(t.status===O.DONE?vu(e):_u(e))}function Nu(e){let t=hu(e);t&&q(dc(e,Se(t.priority)))}function Pu(e){if(e.target.classList?.contains(`todo-link-input`)){let t=e.target.dataset.id;if(!W||W!==t)return;Ru(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(El=null,G(t),!n){q(sc(t,{dueAt:null}));return}let r=new Date(n+`T00:00:00`);q(sc(t,{dueAt:isNaN(r.getTime())?null:r.getTime()}))}function Fu(e){if(e.target?.classList?.contains(`todo-link-input`)){let t=e.target.dataset.id;if(!W||W!==t)return;Ru(t,e.target.value);return}if(!e.target?.classList?.contains(`todo-edit-input`))return;let n=e.target.dataset.id;if(!U||U!==n)return;let r=e.target.value.trim();if(U=null,!r){G(n),K();return}G(n),sc(n,{title:r}).then(e=>{e?K():A(t(`todo.saveFailed`),`error`)})}async function Iu(){let e=vl.value.trim();e&&(vl.value=``,wl===`done`&&(wl=`active`),await oc(e)||A(t(`todo.saveFailed`),`error`),vl.focus())}function Lu(e){let t=H.querySelector(`.todo-note-input[data-id="${k(e)}"]`),n=t?t.value:``;Tl=null,Dl.delete(e),G(e),q(sc(e,{note:n}))}function Ru(e,n){let r=!!hu(e)?.link;W=null,G(e);let i=String(n||``).trim();q(fc(e,i),t(i?`todo.linkSavedToast`:r?`todo.linkRemovedToast`:`todo.linkSavedToast`))}function zu(e){W=null,G(e),K()}function Bu(){let e=U||Tl||El||W;U=null,Tl=null,El=null,W=null,G(),e&&K()}async function Vu(e,t){return typeof window<`u`&&typeof window.showCustomConfirm==`function`?!!await window.showCustomConfirm(e,t):!1}function Hu(){return xl||(xl=document.createElement(`div`),xl.className=`todo-menu`,document.body.appendChild(xl),xl.addEventListener(`click`,e=>{let t=e.target.closest(`[data-priority-value]`);if(t){let e=t.dataset.menuId,n=t.dataset.priorityValue||null;Uu(),q(dc(e,n));return}let n=e.target.closest(`[data-menu-action]`);if(!n)return;let{menuAction:r,menuId:i}=n.dataset;Uu(),ed(r,i)}),xl)}function Uu(){xl&&=(xl.remove(),null)}function Wu(e){return e?`<kbd class="todo-menu-kbd">${j(e)}</kbd>`:``}function Gu(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
+ <span class="todo-menu-row-label">${j(e.label)}</span>
388
388
  ${r.map(([r,i])=>`
389
389
  <button type="button" class="todo-swatch${r?` ${r}`:``}${e.current===r?` active`:``}"
390
- data-priority-value="${O(r)}" data-menu-id="${O(n)}"
391
- title="${O(t(`todo.priorityTitle`,{level:i}))}"
392
- aria-label="${O(i)}"></button>`).join(``)}
393
- ${Ju(e.shortcut)}
394
- </div>`}return`${e.divider?`<div class="todo-menu-sep"></div>`:``}<button type="button" data-menu-action="${O(e.action)}" data-menu-id="${O(n||``)}"
390
+ data-priority-value="${k(r)}" data-menu-id="${k(n)}"
391
+ title="${k(t(`todo.priorityTitle`,{level:i}))}"
392
+ aria-label="${k(i)}"></button>`).join(``)}
393
+ ${Wu(e.shortcut)}
394
+ </div>`}return`${e.divider?`<div class="todo-menu-sep"></div>`:``}<button type="button" data-menu-action="${k(e.action)}" data-menu-id="${k(n||``)}"
395
395
  class="todo-menu-item${e.danger?` danger`:``}">
396
- ${e.icon||``}<span>${A(e.label)}</span>${Ju(e.shortcut)}
397
- </button>`}function Xu(e,t,n){let r=Ku();r.innerHTML=t.map((e,t)=>t===0&&e.divider?{...e,divider:!1}:e).map(e=>Yu(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 Zu(e){if(e.status===D.DONE){let n=Ue(e),r=[{action:`restore`,label:t(`todo.restoreTo`,{status:lu(n)}),icon:z.undo,shortcut:`Alt+D`,divider:!0}];return n!==D.PENDING&&r.push({action:`set-pending`,label:t(`todo.backToPending`),icon:z.circle}),r}return e.status===D.DOING?[{action:`set-done`,label:t(`todo.markDone`),icon:z.check,shortcut:`Alt+D`,divider:!0},{action:`set-pending`,label:t(`todo.backToPending`),icon:z.circle}]:[{action:`set-doing`,label:t(`todo.startDoing`),icon:z.play,divider:!0},{action:`set-done`,label:t(`todo.markDone`),icon:z.check,shortcut:`Alt+D`}]}function Qu(e,n){let r=yu(n);r&&Xu(e,[...Zu(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 $u(e){let t=ed();t.length!==0&&Xu(e,t,``)}function ed(){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 td(){let{active:e,done:t}=sc(),n=await Xc({counts:{all:e.length+t.length,active:e.length,done:t.length}});n&&nd(n.scope,n.format)}function nd(e,n){let{active:i,done:a}=sc(),o=[...i,...a];if(Se(o,e).length===0){k(t(`todo.exportEmptyToast`),`info`);return}try{k(t(`todo.exportedToast`,{name:kc(o,{scope:e,format:n})}),`success`)}catch(e){r.error(`[Todo] export failed:`,e),k(t(`todo.exportFailedToast`),`error`)}}async function rd(){let e=await Ac();if(!e)return;let n=await jc(e);if(!n.ok){k(t(n.reason===`json`?`todo.importJsonError`:`todo.importFormatError`),`error`);return}let{active:r,done:i}=sc(),a=await Zc({count:n.todos.length,existing:r.length+i.length});if(!a)return;Ol=`active`,K();let o=await bc(n.todos,a);if(!o.ok){k(t(o.reason===`empty`?`todo.importEmptyToast`:`todo.importFailedToast`),`error`);return}if(o.added===0){k(t(`todo.importNothingNewToast`,{skipped:o.skipped}),`info`);return}k(t(`todo.importedToast`,{added:o.added,skipped:o.skipped}),`success`)}async function id(e,n){let r=yu(n);switch(e){case`set-doing`:q(fc(n,D.DOING));return;case`set-pending`:q(fc(n,D.PENDING));return;case`set-done`:xu(n);return;case`restore`:Su(n);return;case`edit-title`:U=n,K();return;case`edit-note`:kl=n,jl.add(n),K(),setTimeout(()=>{let e=H.querySelector(`.todo-note-input[data-id="${n}"]`);e&&(e.focus(),e.selectionStart=e.selectionEnd=e.value.length)},30);return;case`set-due`:Al=n,K(),setTimeout(()=>{let e=H.querySelector(`.todo-due-input[data-id="${n}"]`);e&&e.focus()},30);return;case`edit-link`:Fu(n);return;case`stats`:fl();return;case`export-options`:td();return;case`import-options`:rd();return;case`delete`:await Gu(t(`todo.deleteConfirmMsg`,{title:r?.title||``}),t(`todo.deleteConfirmTitle`))&&q(_c(n),t(`todo.deletedToast`));return;default:}}function ad(e,t={}){let{active:n,done:r}=sc(),i=[...n,...r].find(t=>t.id===e);return i?Re(i,t):``}function od(e){let n=ad(e);if(!n){k(t(`todo.emptyDigestToast`),`info`);return}let r=document.getElementById(`userInput`);if(!r){k(t(`todo.noInputToast`),`error`);return}let i=r.value.replace(/\s+$/,``);r.value=i?`${i}\n\n${n}`:n,r.dispatchEvent(new Event(`input`,{bubbles:!0})),r.focus(),r.selectionStart=r.selectionEnd=r.value.length,gt(),Kl(),k(t(`todo.filledToast`),`success`)}function sd(e){let n=ad(e,{plain:!0});if(!n){k(t(`todo.emptyDigestToast`),`info`);return}cd(n,t(`todo.copiedToast`))}function cd(e,n){try{navigator.clipboard.writeText(e).then(()=>{k(n,`success`)}).catch(e=>{r.warn(`[Todo] copy failed:`,e),k(t(`todo.copyFailed`),`error`)})}catch(e){r.warn(`[Todo] clipboard unavailable:`,e),k(t(`todo.copyFailed`),`error`)}}function ld(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`));Ml={id:t.dataset.id,from:r.indexOf(t),list:n},t.classList.add(`dragging`);let{active:i,done:a}=sc(),o=[...i,...a].find(e=>e.id===t.dataset.id);try{e.dataTransfer.effectAllowed=`copyMove`,e.dataTransfer.setData(`text/plain`,Re(o)||t.dataset.id)}catch{}}function ud(e){if(!Ml)return;e.preventDefault();let t=Ml.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=dd();r>=n.length?t.appendChild(i):n[r].before(i)}function dd(){let e=H.querySelector(`.todo-insert`);return e||(e=document.createElement(`div`),e.className=`todo-insert`,e)}function fd(e){if(!Ml)return;e.preventDefault();let t=Ml.list,n=H.querySelector(`.todo-insert`),r=Ml.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=Ml.from;pd(),i!==r&&q(vc(i,r))}function pd(){Ml=null,H?.querySelectorAll(`.todo-item.dragging`).forEach(e=>e.classList.remove(`dragging`)),H?.querySelector(`.todo-insert`)?.remove()}var md=`—`,hd=[{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 gd(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 _d(e){if(!e)return md;let t=Date.parse(e);return Number.isNaN(t)?md:new Date(t).toLocaleString()}function vd(e){let n=gd(mt),r=[{label:t(`versionInfo.version`),value:n.version?`v${n.version}`:md},{label:t(`versionInfo.tag`),value:n.tag||md},{label:t(`versionInfo.commit`),value:n.commitId?n.commitId.slice(0,8):md,title:n.commitId,mono:!0},{label:t(`versionInfo.publishedAt`),value:_d(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 yd(e){e.textContent=``;for(let n of hd){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 bd(){let e=gd(mt);return[`AI Helper v${e.version||md}`,`${t(`versionInfo.tag`)}: ${e.tag||md}`,`${t(`versionInfo.commit`)}: ${e.commitId||md}`,`${t(`versionInfo.publishedAt`)}: ${_d(e.publishedAt)}`].join(`
398
- `)}function xd(){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`),vd(a),o&&yd(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(bd()),k(t(`common.copySuccess`),`success`)}catch{k(t(`common.copyFailed`),`error`)}})}var Sd=null;function Cd(){if(!Sd)return;Sd.classList.remove(`open`);let e=Sd.parentElement?Sd.parentElement.querySelector(`.section-select-row`):null;e&&e.classList.remove(`open`),Sd=null}function wd(){return`<input type="search" class="section-select-search" placeholder="${t(`sectionSelect.searchPlaceholder`)}" data-i18n-placeholder="sectionSelect.searchPlaceholder" spellcheck="false">`}function Td(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 Ed(e,t){Cd(),e.classList.add(`open`),t.classList.add(`open`),Sd=e;let n=e.querySelector(`.section-select-search`);n&&(n.value=``,Td(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===Sd?Cd():Ed(e,t);return}Sd&&!Sd.parentElement.contains(e.target)&&Cd()}),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&&Td(n,t.value)});var Dd=!1;async function Od(){document.getElementById(`providerList`)&&(Dd||(Dd=!0,jd(),Md()),await kd())}async function kd(){let e=document.getElementById(`providerList`),t=document.getElementById(`providerSelectValue`),n=document.getElementById(`providerSelectHost`);if(!e)return;let r=await b(),i=r.profiles.find(e=>e.id===r.activeProfileId)||r.profiles[0];t&&(t.textContent=i?i.name:``),n&&(n.textContent=i?le(i.apiBase):``),e.innerHTML=wd();let a=[...r.profiles].sort((e,t)=>S(e.name,t.name));for(let t of a){let n=!!i&&t.id===i.id,r=document.createElement(`div`);r.className=`provider-option`+(n?` selected`:``),r.dataset.value=t.id;let a=document.createElement(`span`);a.className=`provider-option-check`,a.textContent=n?`✓`:``,r.appendChild(a);let o=document.createElement(`span`);o.className=`provider-option-left`,o.textContent=t.name,r.appendChild(o);let s=le(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(),Cd(),Ad(t.id)}),e.appendChild(r)}}async function Ad(e){if(e===(await b()).activeProfileId)return;let t=await se(e);t&&(await kd(),r.debug(`[SidePanel] provider switched:`,t.name))}function jd(){let e=document.getElementById(`providerManageBtn`);e&&e.addEventListener(`click`,async e=>{e.stopPropagation();let t=chrome.runtime.getURL(`options.html#basic`),n=await chrome.tabs.query({url:chrome.runtime.getURL(`options.html`)});n.length>0?await chrome.tabs.update(n[0].id,{active:!0,url:t}):await chrome.tabs.create({url:t})})}function Md(){chrome.storage.onChanged.addListener((e,t)=>{t===`local`&&(e.modelProfiles||e.activeProfileId)&&kd()})}var Nd=0;function Pd(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 Fd(e){let t=[];return e.querySelectorAll(`*`).forEach(e=>{getComputedStyle(e).position===`absolute`&&e.getClientRects().length>0&&t.push(e)}),t}function Id(e){e.forEach(e=>{(e.getAnimations?.()||[]).forEach(e=>{e.playState!==`idle`&&e.finish?.()})})}function Ld(){Nd||=requestAnimationFrame(()=>{Nd=0,Bd()})}function Rd(){let e=document.getElementById(`selectionToggleGroup`),t=document.getElementById(`inputAddMenuSwitches`);e&&t&&e.parentElement!==t&&t.appendChild(e)}function zd(){let e=document.getElementById(`selectionToggleGroup`),t=document.querySelector(`.input-bottom-left`);e&&t&&e.parentElement!==t&&t.appendChild(e)}function Bd(){let e=document.querySelector(`.input-bottom-row`),t=e?.closest(`.input-container`)||null;if(!(!e||!t)){t.classList.add(`measuring`);try{Vd(e,t)}finally{t.classList.remove(`measuring`)}}}function Vd(e,t){t.classList.remove(`temp-collapsed`,`agent-collapsed`,`switches-icon`,`selection-in-menu`),zd();let n=Fd(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]}),Id(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`),Rd(),i()}function Hd(){Bd(),window.addEventListener(`resize`,Ld);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,Ld())}).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=>!Pd(t.target,e)&&!r(t))&&Ld()}).observe(e,{subtree:!0,childList:!0,characterData:!0})}e(`zh`,{fileSelector:{workspaceTitle:`工作目录`,switchHint:`方向键切换 · Enter添加到文件问答 · Esc取消`,searching:`搜索中...`,noMatch:`没有匹配的文件或目录`,noWorkspace:`暂无工作目录,请先连接 Agent`,loadFailed:`加载失败: {error}`,truncated:`仅显示前 {count} 条,请继续输入以缩小范围`}}),e(`en`,{fileSelector:{workspaceTitle:`Workspace`,switchHint:`↑↓ navigate · Enter attach · Esc cancel`,searching:`Searching...`,noMatch:`No matching file or directory`,noWorkspace:`No workspace directory. Connect an Agent first.`,loadFailed:`Load failed: {error}`,truncated:`Showing top {count} results. Keep typing to narrow down.`}});var Ud=50,Wd=200,Gd=200,Kd=0,qd=null,Jd=[];function Yd(e){return(e||``).replace(/\\/g,`/`).replace(/\/+/g,`/`)}function Xd(e){let t=document.getElementById(`fileAtTitlePath`);if(!t)return;let n=e?Yd(e):``;t.textContent=n,t.title=n}async function Zd(e=``){let t=document.getElementById(`fileAtSelector`),n=document.getElementById(`fileAtDropdown`);if(!t||!n)return;n.dataset.focusGuard||(n.dataset.focusGuard=`1`,n.addEventListener(`mousedown`,e=>{e.target.closest(`.prompt-item`)&&e.preventDefault()}));let r=document.getElementById(`fileAtWorkspaceOpenBtn`);r&&!r.dataset.bound&&(r.dataset.bound=`1`,r.addEventListener(`click`,async e=>{e.stopPropagation(),Qd(),await Ai()})),ot(),t.style.display=`block`,n.classList.add(`show`),await $d(e)}function Qd(){let e=document.getElementById(`fileAtSelector`),t=document.getElementById(`fileAtDropdown`);e&&(e.style.display=`none`),t&&t.classList.remove(`show`),v.selectedFileAtIndex=-1,qd&&=(clearTimeout(qd),null),Kd++}function $d(e=``){let n=document.getElementById(`fileAtList`);if(!n)return;let i=++Kd,a=e.trim();qd&&clearTimeout(qd);let o=async()=>{try{let e=await ua();if(i!==Kd)return;if(Xd(e),!e){n.innerHTML=`<div class="prompt-empty">${t(`fileSelector.noWorkspace`)}</div>`,v.selectedFileAtIndex=-1;return}let r;if(r=a?await oa(e,a,Wd):((await sa(e)).entries||[]).map(t=>({name:t.name,type:t.type||`file`,size:t.size,mtime:t.mtime,fullPath:Yd(`${e}/${t.name}`)})),i!==Kd)return;tf(r,a,n,e)}catch(e){if(i!==Kd)return;r.warn(`[FileAtSelector] search failed:`,e.message),n.innerHTML=`<div class="prompt-empty">${t(`fileSelector.loadFailed`,{error:e.message})}</div>`,v.selectedFileAtIndex=-1}};a?(n.innerHTML=`<div class="prompt-empty">${t(`fileSelector.searching`)}</div>`,qd=setTimeout(o,Gd)):qd=setTimeout(o,0)}function ef(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 tf(e,n,r,i){let a=ef(e,n),o=a.slice(0,Ud),s=a.length>Ud,c=Yd(i);if(o.length===0){r.innerHTML=`<div class="prompt-empty">${t(`fileSelector.noMatch`)}</div>`,v.selectedFileAtIndex=-1;return}if(v.selectedFileAtIndex=0,Jd=o,r.innerHTML=o.map((e,t)=>{let n=la(e.name,e.type),r=Yd(e.fullPath),i=r.startsWith(c)?r.substring(c.length).replace(/^\//,``):r;return`
399
- <div class="prompt-item ${t===0?`selected`:``}" data-index="${t}" data-path="${A(r)}" title="${A(r)}">
396
+ ${e.icon||``}<span>${j(e.label)}</span>${Wu(e.shortcut)}
397
+ </button>`}function Ku(e,t,n){let r=Hu();r.innerHTML=t.map((e,t)=>t===0&&e.divider?{...e,divider:!1}:e).map(e=>Gu(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 qu(e){if(e.status===O.DONE){let n=He(e),r=[{action:`restore`,label:t(`todo.restoreTo`,{status:au(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 Ju(e,n){let r=hu(n);r&&Ku(e,[...qu(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 Yu(e){let t=Xu();t.length!==0&&Ku(e,t,``)}function Xu(){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 Zu(){let{active:e,done:t}=rc(),n=await Kc({counts:{all:e.length+t.length,active:e.length,done:t.length}});n&&Qu(n.scope,n.format)}function Qu(e,n){let{active:i,done:a}=rc(),o=[...i,...a];if(xe(o,e).length===0){A(t(`todo.exportEmptyToast`),`info`);return}try{A(t(`todo.exportedToast`,{name:Tc(o,{scope:e,format:n})}),`success`)}catch(e){r.error(`[Todo] export failed:`,e),A(t(`todo.exportFailedToast`),`error`)}}async function $u(){let e=await Ec();if(!e)return;let n=await Dc(e);if(!n.ok){A(t(n.reason===`json`?`todo.importJsonError`:`todo.importFormatError`),`error`);return}let{active:r,done:i}=rc(),a=await qc({count:n.todos.length,existing:r.length+i.length});if(!a)return;wl=`active`,K();let o=await gc(n.todos,a);if(!o.ok){A(t(o.reason===`empty`?`todo.importEmptyToast`:`todo.importFailedToast`),`error`);return}if(o.added===0){A(t(`todo.importNothingNewToast`,{skipped:o.skipped}),`info`);return}A(t(`todo.importedToast`,{added:o.added,skipped:o.skipped}),`success`)}async function ed(e,n){let r=hu(n);switch(e){case`set-doing`:q(cc(n,O.DOING));return;case`set-pending`:q(cc(n,O.PENDING));return;case`set-done`:_u(n);return;case`restore`:vu(n);return;case`edit-title`:U=n,K();return;case`edit-note`:Tl=n,Dl.add(n),K(),setTimeout(()=>{let e=H.querySelector(`.todo-note-input[data-id="${n}"]`);e&&(e.focus(),e.selectionStart=e.selectionEnd=e.value.length)},30);return;case`set-due`:El=n,K(),setTimeout(()=>{let e=H.querySelector(`.todo-due-input[data-id="${n}"]`);e&&e.focus()},30);return;case`edit-link`:ju(n);return;case`stats`:cl();return;case`export-options`:Zu();return;case`import-options`:$u();return;case`delete`:await Vu(t(`todo.deleteConfirmMsg`,{title:r?.title||``}),t(`todo.deleteConfirmTitle`))&&q(pc(n),t(`todo.deletedToast`));return;default:}}function td(e,t={}){let{active:n,done:r}=rc(),i=[...n,...r].find(t=>t.id===e);return i?Le(i,t):``}function nd(e){let n=td(e);if(!n){A(t(`todo.emptyDigestToast`),`info`);return}let r=document.getElementById(`userInput`);if(!r){A(t(`todo.noInputToast`),`error`);return}let i=r.value.replace(/\s+$/,``);r.value=i?`${i}\n\n${n}`:n,r.dispatchEvent(new Event(`input`,{bubbles:!0})),r.focus(),r.selectionStart=r.selectionEnd=r.value.length,ht(),Hl(),A(t(`todo.filledToast`),`success`)}function rd(e){let n=td(e,{plain:!0});if(!n){A(t(`todo.emptyDigestToast`),`info`);return}id(n,t(`todo.copiedToast`))}function id(e,n){try{navigator.clipboard.writeText(e).then(()=>{A(n,`success`)}).catch(e=>{r.warn(`[Todo] copy failed:`,e),A(t(`todo.copyFailed`),`error`)})}catch(e){r.warn(`[Todo] clipboard unavailable:`,e),A(t(`todo.copyFailed`),`error`)}}function 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`));Ol={id:t.dataset.id,from:r.indexOf(t),list:n},t.classList.add(`dragging`);let{active:i,done:a}=rc(),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 od(e){if(!Ol)return;e.preventDefault();let t=Ol.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=sd();r>=n.length?t.appendChild(i):n[r].before(i)}function sd(){let e=H.querySelector(`.todo-insert`);return e||(e=document.createElement(`div`),e.className=`todo-insert`,e)}function cd(e){if(!Ol)return;e.preventDefault();let t=Ol.list,n=H.querySelector(`.todo-insert`),r=Ol.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=Ol.from;ld(),i!==r&&q(mc(i,r))}function ld(){Ol=null,H?.querySelectorAll(`.todo-item.dragging`).forEach(e=>e.classList.remove(`dragging`)),H?.querySelector(`.todo-insert`)?.remove()}var ud=`—`,dd=[{labelKey:`versionInfo.website`,url:`https://xiweicheng.github.io/ai-helper/`,icon:`<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 17.93c-3.95-.49-7-3.85-7-7.93 0-.62.08-1.21.21-1.79L9 15v1c0 1.1.9 2 2 2v1.93zm6.9-2.54c-.26-.81-1-1.39-1.9-1.39h-1v-3c0-.55-.45-1-1-1H8v-2h2c.55 0 1-.45 1-1V7h2c1.1 0 2-.9 2-2v-.41c2.93 1.19 5 4.06 5 7.41 0 2.08-.8 3.97-2.1 5.39z"/></svg>`},{labelKey:`versionInfo.discussions`,url:`https://github.com/xiweicheng/ai-helper/discussions`,icon:`<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2z"/></svg>`},{labelKey:`versionInfo.reportIssue`,url:`https://github.com/xiweicheng/ai-helper/issues/new`,icon:`<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M20 8h-2.81c-.45-.78-1.07-1.45-1.82-1.96L17 4.41 15.59 3l-2.17 2.17C12.96 5.06 12.49 5 12 5c-.49 0-.96.06-1.41.17L8.41 3 7 4.41l1.62 1.63C7.88 6.55 7.26 7.22 6.81 8H4v2h2.09c-.05.33-.09.66-.09 1v1H4v2h2v1c0 .34.04.67.09 1H4v2h2.81c1.04 1.79 2.97 3 5.19 3s4.15-1.21 5.19-3H20v-2h-2.09c.05-.33.09-.66.09-1v-1h2v-2h-2v-1c0-.34-.04-.67-.09-1H20V8zm-6 8h-4v-2h4v2zm0-4h-4v-2h4v2z"/></svg>`},{labelKey:`versionInfo.githubRepo`,url:`https://github.com/xiweicheng/ai-helper`,icon:`<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M12 .5C5.73.5.5 5.73.5 12c0 5.08 3.29 9.39 7.86 10.91.58.11.79-.25.79-.56 0-.28-.01-1.02-.02-2-3.2.7-3.88-1.54-3.88-1.54-.52-1.33-1.28-1.69-1.28-1.69-1.04-.71.08-.7.08-.7 1.15.08 1.76 1.19 1.76 1.19 1.03 1.76 2.7 1.25 3.36.96.1-.75.4-1.25.72-1.54-2.55-.29-5.24-1.28-5.24-5.68 0-1.26.45-2.28 1.19-3.09-.12-.29-.52-1.46.11-3.05 0 0 .97-.31 3.18 1.18a11.1 11.1 0 012.9-.39c.98 0 1.97.13 2.9.39 2.2-1.49 3.17-1.18 3.17-1.18.63 1.59.23 2.76.11 3.05.74.81 1.19 1.83 1.19 3.09 0 4.41-2.69 5.38-5.25 5.67.41.35.78 1.05.78 2.12 0 1.53-.01 2.76-.01 3.14 0 .31.21.68.8.56A11.51 11.51 0 0023.5 12C23.5 5.73 18.27.5 12 .5z"/></svg>`},{labelKey:`versionInfo.giteeRepo`,url:`https://gitee.com/xiweicheng/ai-helper`,icon:`<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M11.984 0A12 12 0 000 12a12 12 0 0012 12 12 12 0 0012-12A12 12 0 0012 0zm6.09 5.333c.328 0 .593.266.592.593v1.482a.594.594 0 01-.593.592H9.777c-.982 0-1.778.796-1.778 1.778v5.63c0 .327.266.592.593.592h5.63c.982 0 1.778-.796 1.778-1.778v-.296a.593.593 0 00-.592-.593h-4.15a.592.592 0 01-.592-.592v-1.482a.593.593 0 01.593-.592h6.815c.327 0 .593.265.593.592v3.408a4 4 0 01-4 4H8.444a3.556 3.556 0 01-3.555-3.556V8.89a3.556 3.556 0 013.555-3.556h9.63z"/></svg>`}];function fd(e){let t=e=>typeof e==`string`?e.trim():``,n=e&&typeof e==`object`?e:{};return{version:t(n.version),tag:t(n.tag),commitId:t(n.commitId),publishedAt:t(n.publishedAt)}}function pd(e){if(!e)return ud;let t=Date.parse(e);return Number.isNaN(t)?ud:new Date(t).toLocaleString()}function md(e){let n=fd(pt),r=[{label:t(`versionInfo.version`),value:n.version?`v${n.version}`:ud},{label:t(`versionInfo.tag`),value:n.tag||ud},{label:t(`versionInfo.commit`),value:n.commitId?n.commitId.slice(0,8):ud,title:n.commitId,mono:!0},{label:t(`versionInfo.publishedAt`),value:pd(n.publishedAt)}];e.textContent=``;for(let t of r){let n=document.createElement(`div`);n.className=`version-info-row`;let r=document.createElement(`div`);r.className=`version-info-label`,r.textContent=t.label;let i=document.createElement(`div`);i.className=t.mono?`version-info-value mono`:`version-info-value`,i.textContent=t.value,t.title&&(i.title=t.title),n.appendChild(r),n.appendChild(i),e.appendChild(n)}}function hd(e){e.textContent=``;for(let n of dd){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 gd(){let e=fd(pt);return[`AI Helper v${e.version||ud}`,`${t(`versionInfo.tag`)}: ${e.tag||ud}`,`${t(`versionInfo.commit`)}: ${e.commitId||ud}`,`${t(`versionInfo.publishedAt`)}: ${pd(e.publishedAt)}`].join(`
398
+ `)}function _d(){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`),md(a),o&&hd(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(gd()),A(t(`common.copySuccess`),`success`)}catch{A(t(`common.copyFailed`),`error`)}})}var vd=null;function yd(){if(!vd)return;vd.classList.remove(`open`);let e=vd.parentElement?vd.parentElement.querySelector(`.section-select-row`):null;e&&e.classList.remove(`open`),vd=null}function bd(){return`<input type="search" class="section-select-search" placeholder="${t(`sectionSelect.searchPlaceholder`)}" data-i18n-placeholder="sectionSelect.searchPlaceholder" spellcheck="false">`}function xd(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 Sd(e,t){yd(),e.classList.add(`open`),t.classList.add(`open`),vd=e;let n=e.querySelector(`.section-select-search`);n&&(n.value=``,xd(e,``),n.focus())}document.addEventListener(`click`,e=>{let t=e.target.closest(`.section-select-row`);if(t){let e=t.parentElement.querySelector(`.section-select-list`);if(!e)return;e===vd?yd():Sd(e,t);return}vd&&!vd.parentElement.contains(e.target)&&yd()}),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&&xd(n,t.value)});var Cd=!1;async function wd(){document.getElementById(`providerList`)&&(Cd||(Cd=!0,Dd(),Od()),await Td())}async function Td(){let e=document.getElementById(`providerList`),t=document.getElementById(`providerSelectValue`),n=document.getElementById(`providerSelectHost`);if(!e)return;let r=await b(),i=r.profiles.find(e=>e.id===r.activeProfileId)||r.profiles[0];t&&(t.textContent=i?i.name:``),n&&(n.textContent=i?T(i.apiBase):``),e.innerHTML=bd();let a=[...r.profiles].sort((e,t)=>S(e.name,t.name));for(let t of a){let n=!!i&&t.id===i.id,r=document.createElement(`div`);r.className=`provider-option`+(n?` selected`:``),r.dataset.value=t.id;let a=document.createElement(`span`);a.className=`provider-option-check`,a.textContent=n?`✓`:``,r.appendChild(a);let o=document.createElement(`span`);o.className=`provider-option-left`,o.textContent=t.name,r.appendChild(o);let s=T(t.apiBase);if(s){let e=document.createElement(`span`);e.className=`provider-option-right`,e.textContent=s,r.appendChild(e)}r.addEventListener(`click`,e=>{e.stopPropagation(),yd(),Ed(t.id)}),e.appendChild(r)}}async function Ed(e){if(e===(await b()).activeProfileId)return;let t=await se(e);t&&(await Td(),r.debug(`[SidePanel] provider switched:`,t.name))}function Dd(){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 Od(){chrome.storage.onChanged.addListener((e,t)=>{t===`local`&&(e.modelProfiles||e.activeProfileId)&&Td()})}var kd=0;function Ad(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 jd(e){let t=[];return e.querySelectorAll(`*`).forEach(e=>{getComputedStyle(e).position===`absolute`&&e.getClientRects().length>0&&t.push(e)}),t}function Md(e){e.forEach(e=>{(e.getAnimations?.()||[]).forEach(e=>{e.playState!==`idle`&&e.finish?.()})})}function Nd(){kd||=requestAnimationFrame(()=>{kd=0,Id()})}function Pd(){let e=document.getElementById(`selectionToggleGroup`),t=document.getElementById(`inputAddMenuSwitches`);e&&t&&e.parentElement!==t&&t.appendChild(e)}function Fd(){let e=document.getElementById(`selectionToggleGroup`),t=document.querySelector(`.input-bottom-left`);e&&t&&e.parentElement!==t&&t.appendChild(e)}function Id(){let e=document.querySelector(`.input-bottom-row`),t=e?.closest(`.input-container`)||null;if(!(!e||!t)){t.classList.add(`measuring`);try{Ld(e,t)}finally{t.classList.remove(`measuring`)}}}function Ld(e,t){t.classList.remove(`temp-collapsed`,`agent-collapsed`,`switches-icon`,`selection-in-menu`),Fd();let n=jd(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]}),Md(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`),Pd(),i()}function Rd(){Id(),window.addEventListener(`resize`,Nd);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,Nd())}).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=>!Ad(t.target,e)&&!r(t))&&Nd()}).observe(e,{subtree:!0,childList:!0,characterData:!0})}e(`zh`,{fileSelector:{workspaceTitle:`工作目录`,switchHint:`方向键切换 · Enter添加到文件问答 · Esc取消`,searching:`搜索中...`,noMatch:`没有匹配的文件或目录`,noWorkspace:`暂无工作目录,请先连接 Agent`,loadFailed:`加载失败: {error}`,truncated:`仅显示前 {count} 条,请继续输入以缩小范围`}}),e(`en`,{fileSelector:{workspaceTitle:`Workspace`,switchHint:`↑↓ navigate · Enter attach · Esc cancel`,searching:`Searching...`,noMatch:`No matching file or directory`,noWorkspace:`No workspace directory. Connect an Agent first.`,loadFailed:`Load failed: {error}`,truncated:`Showing top {count} results. Keep typing to narrow down.`}});var zd=50,Bd=200,Vd=200,Hd=0,Ud=null,Wd=[];function Gd(e){return(e||``).replace(/\\/g,`/`).replace(/\/+/g,`/`)}function Kd(e){let t=document.getElementById(`fileAtTitlePath`);if(!t)return;let n=e?Gd(e):``;t.textContent=n,t.title=n}async function qd(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(),Jd(),await pi()})),at(),t.style.display=`block`,n.classList.add(`show`),await Yd(e)}function Jd(){let e=document.getElementById(`fileAtSelector`),t=document.getElementById(`fileAtDropdown`);e&&(e.style.display=`none`),t&&t.classList.remove(`show`),v.selectedFileAtIndex=-1,Ud&&=(clearTimeout(Ud),null),Hd++}function Yd(e=``){let n=document.getElementById(`fileAtList`);if(!n)return;let i=++Hd,a=e.trim();Ud&&clearTimeout(Ud);let o=async()=>{try{let e=await ca();if(i!==Hd)return;if(Kd(e),!e){n.innerHTML=`<div class="prompt-empty">${t(`fileSelector.noWorkspace`)}</div>`,v.selectedFileAtIndex=-1;return}let r;if(r=a?await ia(e,a,Bd):((await aa(e)).entries||[]).map(t=>({name:t.name,type:t.type||`file`,size:t.size,mtime:t.mtime,fullPath:Gd(`${e}/${t.name}`)})),i!==Hd)return;Zd(r,a,n,e)}catch(e){if(i!==Hd)return;r.warn(`[FileAtSelector] search failed:`,e.message),n.innerHTML=`<div class="prompt-empty">${t(`fileSelector.loadFailed`,{error:e.message})}</div>`,v.selectedFileAtIndex=-1}};a?(n.innerHTML=`<div class="prompt-empty">${t(`fileSelector.searching`)}</div>`,Ud=setTimeout(o,Vd)):Ud=setTimeout(o,0)}function Xd(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 Zd(e,n,r,i){let a=Xd(e,n),o=a.slice(0,zd),s=a.length>zd,c=Gd(i);if(o.length===0){r.innerHTML=`<div class="prompt-empty">${t(`fileSelector.noMatch`)}</div>`,v.selectedFileAtIndex=-1;return}if(v.selectedFileAtIndex=0,Wd=o,r.innerHTML=o.map((e,t)=>{let n=sa(e.name,e.type),r=Gd(e.fullPath),i=r.startsWith(c)?r.substring(c.length).replace(/^\//,``):r;return`
399
+ <div class="prompt-item ${t===0?`selected`:``}" data-index="${t}" data-path="${j(r)}" title="${j(r)}">
400
400
  <span class="prompt-item-index">${t+1}</span>
401
401
  <span class="prompt-item-icon">${n}</span>
402
- <span class="prompt-item-content">${A(e.name)}</span>
403
- <span class="file-at-path">${A(i)}</span>
402
+ <span class="prompt-item-content">${j(e.name)}</span>
403
+ <span class="file-at-path">${j(i)}</span>
404
404
  </div>
405
- `}).join(``),s){let e=document.createElement(`div`);e.className=`file-at-truncated`,e.textContent=t(`fileSelector.truncated`,{count:Ud}),r.appendChild(e)}r.querySelectorAll(`.prompt-item`).forEach(e=>{e.addEventListener(`click`,()=>{nf(Jd.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`),n=t?t.value:``,r=n.lastIndexOf(`$`);r!==-1&&(t.value=n.substring(0,r)),t&&(t.focus(),t.selectionStart=t.selectionEnd=t.value.length),Qd(),gr([e]),gt()}function rf(e){let t=v.selectedFileAtIndex;e.forEach((e,n)=>{n===t?(e.classList.add(`selected`),e.scrollIntoView({block:`nearest`})):e.classList.remove(`selected`)})}e(`zh`,{input:{addMenuPanelSearchPlaceholder:`搜索…`,addMenuPanelClear:`清除`,addMenuPanelLoading:`加载中…`,addMenuPanelEmpty:`暂无可用内容`,addMenuPanelNoMatch:`没有匹配项`}}),e(`en`,{input:{addMenuPanelSearchPlaceholder:`Search…`,addMenuPanelClear:`Clear`,addMenuPanelLoading:`Loading…`,addMenuPanelEmpty:`No items available`,addMenuPanelNoMatch:`No matches`}});var af=null,J=null,of=null,sf=null,cf=null,Y=null,X=null,lf=[],uf=0,df=()=>{},ff=[{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`}],pf=new Set([`screenshot`]),mf={prompts:{titleKey:`promptManager.title`,action:()=>Yr()},skills:{titleKey:`promptSelector.skillManageTitle`,action:()=>hf(`toolbox`)},mcp:{titleKey:`promptSelector.mcpManageTitle`,action:()=>hf(`toolbox`)},pages:{titleKey:`pageSelector.openNewTab`,action:()=>chrome.tabs.create({})},knowledge:{titleKey:`header.manageKnowledge`,action:()=>hf(`knowledge`)},agents:{titleKey:`header.addEditAssistant`,action:()=>hi(null)},proxies:{titleKey:`header.addEditAgent`,action:()=>hf(`agent`)},workspace:{titleKey:`workspace.openPanel`,action:()=>Ai()}};function hf(e){chrome.runtime.sendMessage({type:`OPEN_OPTIONS_PAGE`,hash:e})}function gf(){if(!cf)return;let e=X?mf[X]:null;if(!e){cf.style.display=`none`;return}let n=t(e.titleKey);cf.title=n,cf.setAttribute(`aria-label`,n),cf.style.display=`flex`}function _f(){sf&&(sf.style.display=pf.has(X)?`none`:``)}function vf(e={}){if(df=typeof e.onRequestClose==`function`?e.onRequestClose:()=>{},af=document.getElementById(`inputAddPanel`),J=document.getElementById(`inputAddPanelSearch`),of=document.getElementById(`inputAddPanelSearchClear`),cf=document.getElementById(`inputAddPanelManage`),sf=document.getElementById(`inputAddPanelSearchWrap`),Y=document.getElementById(`inputAddPanelList`),!(!af||!J||!Y)){if(cf&&cf.addEventListener(`click`,()=>{let e=X?mf[X]:null;e&&(df(),e.action())}),of){let e=t(`input.addMenuPanelClear`);of.title=e,of.setAttribute(`aria-label`,e),of.addEventListener(`click`,()=>{J.value=``,Of(),yf(),J.focus()})}J.addEventListener(`input`,()=>{Of(),yf()})}}function yf(){of&&J&&(of.style.display=J.value?`flex`:`none`)}function bf(){return!!X}function xf(){return X}function Sf(){return!!J&&document.activeElement===J}async function Cf(e){if(!af||!e||X===e&&af.style.display!==`none`)return;X=e,gf(),_f(),J&&(J.value=``,J.placeholder=t(`input.addMenuPanelSearchPlaceholder`),yf()),af.style.display=`flex`;let n=++uf;Y&&(Y.innerHTML=`<div class="prompt-empty">${t(`input.addMenuPanelLoading`)}</div>`);try{let t=await Tf(e);if(n!==uf)return;lf=Array.isArray(t)?t:[],Of()}catch(e){if(n!==uf)return;r.warn(`[InputAddPanel] load failed:`,e&&e.message),lf=[],Y&&(Y.innerHTML=`<div class="prompt-empty">${t(`input.addMenuPanelEmpty`)}</div>`)}}function wf(){X=null,gf(),_f(),lf=[],uf++,J&&(J.value=``,yf()),Y&&(Y.innerHTML=``),af&&(af.style.display=`none`)}function Tf(e){switch(e){case`prompts`:return Promise.resolve(v.customPrompts||[]);case`skills`:return Li(!0);case`mcp`:return ri();case`pages`:return pn();case`knowledge`:return Jn().then(e=>e.ok?e.collections:[]);case`agents`:return aa();case`proxies`:return wi();case`workspace`:return Ef();case`screenshot`:return Promise.resolve(ff);default:return Promise.resolve([])}}async function Ef(){let e=await ua();if(!e)return[];let t=await sa(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 Df(e){if(!e)return lf;let n=e.toLowerCase();return lf.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(qt(e)||``).toLowerCase().includes(n)||String(tr(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 Of(){if(!Y)return;let e=J?J.value.trim():``,n=Df(e);if(n.length===0){Y.innerHTML=`<div class="prompt-empty">${t(e?`input.addMenuPanelNoMatch`:`input.addMenuPanelEmpty`)}</div>`;return}Y.innerHTML=n.map(e=>kf(e)).join(``),Y.querySelectorAll(`.input-add-panel-item`).forEach(e=>{e.addEventListener(`click`,t=>Af(t,e))}),Y.querySelectorAll(`img.favicon-img`).forEach(e=>{e.addEventListener(`error`,()=>{e.style.display=`none`})}),X===`proxies`&&n.forEach(e=>ur(e)),X===`skills`&&Hr(),X===`mcp`&&si(),X===`knowledge`&&ir()}function kf(e){switch(X){case`prompts`:return`<div class="prompt-item input-add-panel-item input-add-panel-item-two-line" data-code="${A(e.code)}" title="${O(e.content||``)}">
406
- <span class="input-add-panel-item-title"><span class="input-add-panel-item-inline-icon">${Vn}</span>/${A(e.code)}</span>
407
- <span class="input-add-panel-item-sub">${A(e.content||``)}</span>
408
- </div>`;case`skills`:{let n=e.enabled===!1,r=n?`${e.name}\n${t(`skillSelector.disabledTooltip`)}`:e.name,i=e.description||``;return`<div class="skill-list-item input-add-panel-item input-add-panel-item-two-line${n?` skill-list-item-disabled`:``}" data-skill-name="${A(e.name)}" title="${O(r)}">
409
- <span class="input-add-panel-item-title">🧩 ${A(e.name)}</span>
410
- ${i?`<span class="input-add-panel-item-sub" title="${O(i)}">${A(i)}</span>`:``}
411
- </div>`}case`mcp`:{let n=e.effectiveOpen===!1,r=n?`${e.serverName}\n${t(`skillSelector.mcpInactiveTooltip`)}`:e.serverName;return`<div class="mcp-list-item input-add-panel-item input-add-panel-item-two-line${n?` mcp-list-item-inactive`:``}" data-server-id="${A(e.serverId)}" data-server-name="${A(e.serverName)}" title="${O(r)}">
412
- <span class="input-add-panel-item-title">🔌 ${A(e.serverName)}${n?` <span class="mcp-list-item-badge mcp-badge-inactive">${t(`skillSelector.mcpInactiveBadge`)}</span>`:``}</span>
413
- <span class="input-add-panel-item-sub" title="${O(e.serverId||``)}">${A(e.serverId||``)}</span>
414
- </div>`}case`pages`:{let t=e.title||e.url||``,n=!!(v.selectedPage&&v.selectedPage.id===e.id),r=e.favIconUrl?`<img src="${O(e.favIconUrl)}" width="14" height="14" class="favicon-img" alt="">`:`<span class="input-add-panel-item-inline-icon">🌐</span>`;return`<div class="prompt-item input-add-panel-item input-add-panel-item-two-line" data-tab-id="${e.id}">
415
- <span class="input-add-panel-item-title">${r}${A(t)}</span>
416
- <span class="input-add-panel-item-sub">${A(e.url||``)}</span>
405
+ `}).join(``),s){let e=document.createElement(`div`);e.className=`file-at-truncated`,e.textContent=t(`fileSelector.truncated`,{count:zd}),r.appendChild(e)}r.querySelectorAll(`.prompt-item`).forEach(e=>{e.addEventListener(`click`,()=>{Qd(Wd.find(t=>t.fullPath===e.dataset.path)||e.dataset.path)})})}function Qd(e){if(!(typeof e==`string`?e:e&&e.fullPath))return;let t=document.getElementById(`userInput`),n=t?t.value:``,r=n.lastIndexOf(`$`);r!==-1&&(t.value=n.substring(0,r)),t&&(t.focus(),t.selectionStart=t.selectionEnd=t.value.length),Jd(),Wr([e]),ht()}function $d(e){let t=v.selectedFileAtIndex;e.forEach((e,n)=>{n===t?(e.classList.add(`selected`),e.scrollIntoView({block:`nearest`})):e.classList.remove(`selected`)})}e(`zh`,{input:{addMenuPanelSearchPlaceholder:`搜索…`,addMenuPanelClear:`清除`,addMenuPanelLoading:`加载中…`,addMenuPanelEmpty:`暂无可用内容`,addMenuPanelNoMatch:`没有匹配项`}}),e(`en`,{input:{addMenuPanelSearchPlaceholder:`Search…`,addMenuPanelClear:`Clear`,addMenuPanelLoading:`Loading…`,addMenuPanelEmpty:`No items available`,addMenuPanelNoMatch:`No matches`}});var ef=null,J=null,tf=null,nf=null,rf=null,Y=null,X=null,af=[],of=0,sf=()=>{},cf=[{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`}],lf=new Set([`screenshot`]),uf={prompts:{titleKey:`promptManager.title`,action:()=>qr()},skills:{titleKey:`promptSelector.skillManageTitle`,action:()=>df(`toolbox`)},mcp:{titleKey:`promptSelector.mcpManageTitle`,action:()=>df(`toolbox`)},pages:{titleKey:`pageSelector.openNewTab`,action:()=>chrome.tabs.create({})},knowledge:{titleKey:`header.manageKnowledge`,action:()=>df(`knowledge`)},agents:{titleKey:`header.addEditAssistant`,action:()=>fi(null)},proxies:{titleKey:`header.addEditAgent`,action:()=>df(`agent`)},workspace:{titleKey:`workspace.openPanel`,action:()=>pi()}};function df(e){chrome.runtime.sendMessage({type:`OPEN_OPTIONS_PAGE`,hash:e})}function ff(){if(!rf)return;let e=X?uf[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 pf(){nf&&(nf.style.display=lf.has(X)?`none`:``)}function mf(e={}){if(sf=typeof e.onRequestClose==`function`?e.onRequestClose:()=>{},ef=document.getElementById(`inputAddPanel`),J=document.getElementById(`inputAddPanelSearch`),tf=document.getElementById(`inputAddPanelSearchClear`),rf=document.getElementById(`inputAddPanelManage`),nf=document.getElementById(`inputAddPanelSearchWrap`),Y=document.getElementById(`inputAddPanelList`),!(!ef||!J||!Y)){if(rf&&rf.addEventListener(`click`,()=>{let e=X?uf[X]:null;e&&(sf(),e.action())}),tf){let e=t(`input.addMenuPanelClear`);tf.title=e,tf.setAttribute(`aria-label`,e),tf.addEventListener(`click`,()=>{J.value=``,wf(),hf(),J.focus()})}J.addEventListener(`input`,()=>{wf(),hf()})}}function hf(){tf&&J&&(tf.style.display=J.value?`flex`:`none`)}function gf(){return!!X}function _f(){return X}function vf(){return!!J&&document.activeElement===J}async function yf(e){if(!ef||!e||X===e&&ef.style.display!==`none`)return;X=e,ff(),pf(),J&&(J.value=``,J.placeholder=t(`input.addMenuPanelSearchPlaceholder`),hf()),ef.style.display=`flex`;let n=++of;Y&&(Y.innerHTML=`<div class="prompt-empty">${t(`input.addMenuPanelLoading`)}</div>`);try{let t=await xf(e);if(n!==of)return;af=Array.isArray(t)?t:[],wf()}catch(e){if(n!==of)return;r.warn(`[InputAddPanel] load failed:`,e&&e.message),af=[],Y&&(Y.innerHTML=`<div class="prompt-empty">${t(`input.addMenuPanelEmpty`)}</div>`)}}function bf(){X=null,ff(),pf(),af=[],of++,J&&(J.value=``,hf()),Y&&(Y.innerHTML=``),ef&&(ef.style.display=`none`)}function xf(e){switch(e){case`prompts`:return Promise.resolve(v.customPrompts||[]);case`skills`:return Ni(!0);case`mcp`:return ti();case`pages`:return tn();case`knowledge`:return Zt().then(e=>e.ok?e.collections:[]);case`agents`:return ra();case`proxies`:return cn();case`workspace`:return Sf();case`screenshot`:return Promise.resolve(cf);default:return Promise.resolve([])}}async function Sf(){let e=await ca();if(!e)return[];let t=await aa(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 Cf(e){if(!e)return af;let n=e.toLowerCase();return af.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($n(e)||``).toLowerCase().includes(n)||String(Kn(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 wf(){if(!Y)return;let e=J?J.value.trim():``,n=Cf(e);if(n.length===0){Y.innerHTML=`<div class="prompt-empty">${t(e?`input.addMenuPanelNoMatch`:`input.addMenuPanelEmpty`)}</div>`;return}Y.innerHTML=n.map(e=>Tf(e)).join(``),Y.querySelectorAll(`.input-add-panel-item`).forEach(e=>{e.addEventListener(`click`,t=>Ef(t,e))}),Y.querySelectorAll(`img.favicon-img`).forEach(e=>{e.addEventListener(`error`,()=>{e.style.display=`none`})}),X===`proxies`&&n.forEach(e=>nr(e)),X===`skills`&&zr(),X===`mcp`&&ii(),X===`knowledge`&&ar()}function Tf(e){switch(X){case`prompts`:return`<div class="prompt-item input-add-panel-item input-add-panel-item-two-line" data-code="${j(e.code)}" title="${k(e.content||``)}">
406
+ <span class="input-add-panel-item-title"><span class="input-add-panel-item-inline-icon">${zn}</span>/${j(e.code)}</span>
407
+ <span class="input-add-panel-item-sub">${j(e.content||``)}</span>
408
+ </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="${j(e.name)}" title="${k(r)}">
409
+ <span class="input-add-panel-item-title">🧩 ${j(e.name)}</span>
410
+ ${i?`<span class="input-add-panel-item-sub" title="${k(i)}">${j(i)}</span>`:``}
411
+ </div>`}case`mcp`:{let n=e.effectiveOpen===!1,r=n?`${e.serverName}\n${t(`skillSelector.mcpInactiveTooltip`)}`:e.serverName;return`<div class="mcp-list-item input-add-panel-item input-add-panel-item-two-line${n?` mcp-list-item-inactive`:``}" data-server-id="${j(e.serverId)}" data-server-name="${j(e.serverName)}" title="${k(r)}">
412
+ <span class="input-add-panel-item-title">🔌 ${j(e.serverName)}${n?` <span class="mcp-list-item-badge mcp-badge-inactive">${t(`skillSelector.mcpInactiveBadge`)}</span>`:``}</span>
413
+ <span class="input-add-panel-item-sub" title="${k(e.serverId||``)}">${j(e.serverId||``)}</span>
414
+ </div>`}case`pages`:{let t=e.title||e.url||``,n=!!(v.selectedPage&&v.selectedPage.id===e.id),r=e.favIconUrl?`<img src="${k(e.favIconUrl)}" width="14" height="14" class="favicon-img" alt="">`:`<span class="input-add-panel-item-inline-icon">🌐</span>`;return`<div class="prompt-item input-add-panel-item input-add-panel-item-two-line" data-tab-id="${e.id}">
415
+ <span class="input-add-panel-item-title">${r}${j(t)}</span>
416
+ <span class="input-add-panel-item-sub">${j(e.url||``)}</span>
417
417
  ${n?`<span class="page-selected-mark">✓</span>`:``}
418
- </div>`}case`knowledge`:{let n=e.enabled===!1,r=t(`knowledgeSelector.docChunk`,{docs:e.documentCount||0,chunks:e.chunkCount||0});return`<div class="prompt-item input-add-panel-item input-add-panel-item-two-line prompt-item-knowledge${n?` knowledge-item-disabled`:``}" data-kb-id="${A(e.id)}" data-kb-name="${A(e.name||``)}" data-kb-disabled="${n?`1`:`0`}"${n?` title="${O(t(`knowledgeSelector.disabledTooltip`))}"`:``}>
419
- <span class="input-add-panel-item-title">📚 ${A(e.name||``)}${n?` <span class="knowledge-item-badge badge-disabled">${t(`knowledgeSelector.disabledBadge`)}</span>`:``}</span>
420
- <span class="input-add-panel-item-sub">${A(r)}</span>
421
- </div>`}case`agents`:{let n=qt(e),r=tr(e),i=e.id===v.activeAgentId||!v.activeAgentId&&e.id==="default",a=e.toolIds?e.toolIds.length:e.toolIds===null?null:0,o=a===null?t(`promptSelector.inheritGlobal`):t(`promptSelector.toolCount`,{count:a});return`<div class="prompt-item input-add-panel-item input-add-panel-item-two-line" data-agent-id="${A(e.id)}">
422
- <span class="input-add-panel-item-title">${A([e.icon,n].filter(Boolean).join(` `))}</span>
423
- <span class="input-add-panel-item-sub">${A(r||o)}</span>
418
+ </div>`}case`knowledge`:{let n=e.enabled===!1,r=t(`knowledgeSelector.docChunk`,{docs:e.documentCount||0,chunks:e.chunkCount||0});return`<div class="prompt-item input-add-panel-item input-add-panel-item-two-line prompt-item-knowledge${n?` knowledge-item-disabled`:``}" data-kb-id="${j(e.id)}" data-kb-name="${j(e.name||``)}" data-kb-disabled="${n?`1`:`0`}"${n?` title="${k(t(`knowledgeSelector.disabledTooltip`))}"`:``}>
419
+ <span class="input-add-panel-item-title">📚 ${j(e.name||``)}${n?` <span class="knowledge-item-badge badge-disabled">${t(`knowledgeSelector.disabledBadge`)}</span>`:``}</span>
420
+ <span class="input-add-panel-item-sub">${j(r)}</span>
421
+ </div>`}case`agents`:{let n=$n(e),r=Kn(e),i=e.id===v.activeAgentId||!v.activeAgentId&&e.id==="default",a=e.toolIds?e.toolIds.length:e.toolIds===null?null:0,o=a===null?t(`promptSelector.inheritGlobal`):t(`promptSelector.toolCount`,{count:a});return`<div class="prompt-item input-add-panel-item input-add-panel-item-two-line" data-agent-id="${j(e.id)}">
422
+ <span class="input-add-panel-item-title">${j([e.icon,n].filter(Boolean).join(` `))}</span>
423
+ <span class="input-add-panel-item-sub">${j(r||o)}</span>
424
424
  ${i?`<span class="input-add-panel-item-mark">✓</span>`:``}
425
- </div>`}case`proxies`:{let n=e.name||t(`promptSelector.unnamedProxy`),r=ln(e),i=r?r.online:!1;return`<div class="prompt-item prompt-item-proxy input-add-panel-item input-add-panel-item-two-line${e.isDisabled?` agent-disabled`:``}" data-proxy-id="${A(e.id)}">
426
- <span class="input-add-panel-item-title"><span class="agent-at-dot agent-at-dot-${an(e,i)}"></span>${A(n)}</span>
427
- <span class="input-add-panel-item-sub">${A(e.url||``)}</span>
425
+ </div>`}case`proxies`:{let n=e.name||t(`promptSelector.unnamedProxy`),r=qt(e),i=r?r.online:!1;return`<div class="prompt-item prompt-item-proxy input-add-panel-item input-add-panel-item-two-line${e.isDisabled?` agent-disabled`:``}" data-proxy-id="${j(e.id)}">
426
+ <span class="input-add-panel-item-title"><span class="agent-at-dot agent-at-dot-${xi(e,i)}"></span>${j(n)}</span>
427
+ <span class="input-add-panel-item-sub">${j(e.url||``)}</span>
428
428
  ${e.isActive?`<span class="input-add-panel-item-mark">✓</span>`:``}
429
- </div>`}case`workspace`:{let t=e.type===`directory`;return`<div class="prompt-item input-add-panel-item" data-path="${A(e.fullPath)}" title="${O(e.fullPath)}">
430
- <span class="input-add-panel-item-icon">${la(e.name,e.type)}</span>
431
- <span class="input-add-panel-item-title">${A(e.name)}${t?`/`:``}</span>
432
- ${!t&&e.size!=null?`<span class="input-add-panel-item-sub">${A(ca(e.size))}</span>`:``}
429
+ </div>`}case`workspace`:{let t=e.type===`directory`;return`<div class="prompt-item input-add-panel-item" data-path="${j(e.fullPath)}" title="${k(e.fullPath)}">
430
+ <span class="input-add-panel-item-icon">${sa(e.name,e.type)}</span>
431
+ <span class="input-add-panel-item-title">${j(e.name)}${t?`/`:``}</span>
432
+ ${!t&&e.size!=null?`<span class="input-add-panel-item-sub">${j(oa(e.size))}</span>`:``}
433
433
  </div>`}case`screenshot`:return`<div class="prompt-item input-add-panel-item input-add-panel-item-two-line" data-shot-action="${e.action}">
434
- <span class="input-add-panel-item-title">${e.icon} ${A(t(e.nameKey))}</span>
435
- <span class="input-add-panel-item-sub">${A(t(e.descKey))}</span>
436
- <kbd class="input-add-panel-item-kbd">${A(e.kbd)}</kbd>
437
- </div>`;default:return``}}async function Af(e,t){let n=e.ctrlKey||e.metaKey;switch(X){case`prompts`:{let e=t.dataset.code;n?$r(e,{skipTriggerStrip:!0}):xt(e),df();break}case`skills`:Zi(t.dataset.skillName,lf,{clearTrigger:!1}),n&&df();break;case`mcp`:Bi(t.dataset.serverId,t.dataset.serverName,lf,{clearTrigger:!1}),n&&df();break;case`pages`:{let e=lf.find(e=>String(e.id)===t.dataset.tabId);if(e){ia(e);let t=document.getElementById(`userInput`);t&&t.focus(),gt()}df();break}case`knowledge`:jr({id:t.dataset.kbId,name:t.dataset.kbName,enabled:t.dataset.kbDisabled!==`1`},{clearTrigger:!1}),n&&df();break;case`agents`:await bt(t.dataset.agentId,{clearTrigger:!1}),df();break;case`proxies`:await Pi(t.dataset.proxyId,{clearTrigger:!1}),df();break;case`workspace`:{let e=lf.find(e=>e.fullPath===t.dataset.path);if(e){let t=document.getElementById(`userInput`);t&&t.focus(),await gr([e]),gt()}df();break}case`screenshot`:df(),await(t.dataset.shotAction===`region`?Fr:Or)();break;default:break}}var jf=0,Mf=200,Nf=150,Pf={promptTriggerBtn:`prompts`,addMenuSkillBtn:`skills`,addMenuMcpBtn:`mcp`,addMenuPageBtn:`pages`,addMenuKnowledgeBtn:`knowledge`,addMenuAgentBtn:`agents`,addMenuProxyBtn:`proxies`,addMenuWorkspaceBtn:`workspace`,screenshotBtn:`screenshot`};async function Ff(){let e=[{id:`addMenuSkillBtn`,available:()=>qi()},{id:`addMenuMcpBtn`,available:()=>yr()},{id:`addMenuKnowledgeBtn`,available:async()=>(await Jn()).ok},{id:`addMenuProxyBtn`,available:async()=>(await wi()).length>0},{id:`addMenuWorkspaceBtn`,available:async()=>!!await ua()}],t=++jf;await Promise.all(e.map(async({id:e,available:n})=>{let r=document.getElementById(e);if(!r)return;let i=!0;try{i=await n()}catch{i=!0}t===jf&&(r.style.display=i?``:`none`)}))}function If(){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=bf()?xf():null;t.querySelectorAll(`.input-add-item`).forEach(t=>{t.classList.toggle(`panel-active`,!!e&&Pf[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?(wf(),s(),Ff()):(i&&=(clearTimeout(i),null),a&&=(clearTimeout(a),null),wf(),s())},u=()=>t.style.display!==`none`;vf({onRequestClose:()=>l(!1)}),e.addEventListener(`click`,e=>{e.stopPropagation();let t=!u();t&&(Mt(),sr(),Qd()),l(t)}),t.addEventListener(`click`,e=>{e.target.closest&&e.target.closest(`.input-add-item`)&&l(!1)},!0),document.addEventListener(`click`,e=>{u()&&(n&&n.contains(e.target)||l(!1))});let d=()=>{i&&=(clearTimeout(i),null),a&&clearTimeout(a),a=setTimeout(()=>{a=null,!Sf()&&(wf(),s())},Nf)};r&&r.addEventListener(`mouseover`,e=>{if(!u())return;let t=e.target.closest(`.input-add-item`),n=t?Pf[t.id]:null;if(!n){d();return}a&&=(clearTimeout(a),null),!(bf()&&xf()===n)&&(i&&clearTimeout(i),i=setTimeout(async()=>{i=null;let e=Cf(n);c(t);try{await e}catch{}c(t),s()},Mf))}),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`,()=>{bf()&&c()}),[{id:`promptTriggerBtn`,open:()=>mn(``,`prompts`)},{id:`addMenuSkillBtn`,open:()=>mn(``,`skills`)},{id:`addMenuMcpBtn`,open:()=>mn(``,`mcp`)},{id:`addMenuPageBtn`,open:()=>fi(``,`pages`)},{id:`addMenuKnowledgeBtn`,open:()=>fi(``,`knowledge`)},{id:`addMenuAgentBtn`,open:()=>fi(``,`agents`)},{id:`addMenuProxyBtn`,open:()=>fi(``,`proxies`)},{id:`addMenuWorkspaceBtn`,open:()=>Zd(``)}].forEach(({id:e,open:t})=>{let n=document.getElementById(e);n&&n.addEventListener(`click`,async e=>{e.stopPropagation(),n.blur(),Mt(),sr(),Qd();try{await t()}catch{}let r=document.getElementById(`userInput`);r&&r.focus()})});let p=document.getElementById(`inputAddMenuSwitches`),m=()=>{let t=p?.querySelector(`input[type="checkbox"]`);e.classList.toggle(`has-active-switch`,!!(t&&t.checked))};p&&(typeof MutationObserver<`u`&&new MutationObserver(m).observe(p,{subtree:!0,childList:!0}),p.addEventListener(`change`,m)),m()}var Lf=`usageTipsEnabled`,Rf=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 zf=[{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,Bf=null,Vf=null,Hf=null,Uf=null,Wf=!1,Gf=null,Kf=!0,qf=null;function Jf(){return v.agentPlatform?.connected===!0}function Yf(){let e=a();return zf.filter(e=>e.scene!==`agent`||Jf()).map(t=>({id:t.id,text:e===`en`?t.en:t.zh}))}function Xf(e){let t=e.findIndex(e=>e.id===Gf);return t>=0?t:0}function Zf(){if(!Z||!Bf)return;let e=Bf.scrollWidth>Bf.clientWidth+1;Z.classList.toggle(`is-truncated`,e)}function Qf(e,t){if(!Bf||!e.length)return;let n=e[t%e.length];Gf=n.id,Bf.textContent=n.text,Vf&&(Vf.textContent=n.text),Zf(),Bf.classList.remove(`fade-in`),Bf.offsetWidth,Bf.classList.add(`fade-in`)}function $f(){if(!Kf||!Z||Z.style.display===`none`)return;let e=Yf();e.length&&Qf(e,Xf(e)+1)}function ep(){Uf&&=(clearInterval(Uf),null)}function tp(){ep(),!(!Kf||Wf)&&(Uf=setInterval($f,Rf))}function np(){if(!Kf||!Z)return;let e=Yf();if(!e.length){ip();return}e.some(e=>e.id===Gf)?Qf(e,Xf(e)):(Gf=null,Qf(e,0))}function rp(){if(!Z)return;Kf=!0,Z.style.display=``;let e=Yf();if(!e.length){ip();return}Qf(e,Xf(e)),tp()}function ip(){Z&&(Z.style.display=`none`,ep())}function ap(){Z.addEventListener(`mouseenter`,()=>{Wf=!0,ep()}),Z.addEventListener(`mouseleave`,()=>{Wf=!1,tp()}),Hf.addEventListener(`click`,e=>{e.stopPropagation(),op(),k(t(`usageTips.dismissedHint`),`info`,5e3)}),chrome.storage.onChanged.addListener((e,t)=>{t!==`local`||!e[Lf]||(e[Lf].newValue===!1?(Kf=!1,ip()):rp())}),document.addEventListener(`agent-connection-changed`,np),o(np),typeof ResizeObserver<`u`&&new ResizeObserver(Zf).observe(Z)}function op(){Kf=!1,ip();try{chrome.storage.local.set({[Lf]:!1})}catch{}}function sp(){if(Z=document.getElementById(`usageTipsBar`),Bf=document.getElementById(`usageTipsText`),Vf=document.getElementById(`usageTipsTooltip`),Hf=document.getElementById(`usageTipsDismiss`),!(!Z||!Bf||!Vf||!Hf)){ap(),qf=document.getElementById(`chatContainer`),qf&&(qf.appendChild(Z),typeof MutationObserver<`u`&&new MutationObserver(()=>{qf.querySelectorAll(`.usage-tips-bar`).forEach(e=>{e!==Z&&e.remove()}),(Z.parentNode!==qf||Z.nextElementSibling)&&qf.appendChild(Z)}).observe(qf,{childList:!0}));try{chrome.storage.local.get([Lf],e=>{Kf=e?.[Lf]!==!1,Kf?rp():ip()})}catch{rp()}}}function cp({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(`
434
+ <span class="input-add-panel-item-title">${e.icon} ${j(t(e.nameKey))}</span>
435
+ <span class="input-add-panel-item-sub">${j(t(e.descKey))}</span>
436
+ <kbd class="input-add-panel-item-kbd">${j(e.kbd)}</kbd>
437
+ </div>`;default:return``}}async function Ef(e,t){let n=e.ctrlKey||e.metaKey;switch(X){case`prompts`:{let e=t.dataset.code;n?Zr(e,{skipTriggerStrip:!0}):bt(e),sf();break}case`skills`:Yi(t.dataset.skillName,af,{clearTrigger:!1}),n&&sf();break;case`mcp`:Li(t.dataset.serverId,t.dataset.serverName,af,{clearTrigger:!1}),n&&sf();break;case`pages`:{let e=af.find(e=>String(e.id)===t.dataset.tabId);if(e){Fn(e);let t=document.getElementById(`userInput`);t&&t.focus(),ht()}sf();break}case`knowledge`:yt({id:t.dataset.kbId,name:t.dataset.kbName,enabled:t.dataset.kbDisabled!==`1`},{clearTrigger:!1}),n&&sf();break;case`agents`:await jn(t.dataset.agentId,{clearTrigger:!1}),sf();break;case`proxies`:await Or(t.dataset.proxyId,{clearTrigger:!1}),sf();break;case`workspace`:{let e=af.find(e=>e.fullPath===t.dataset.path);if(e){let t=document.getElementById(`userInput`);t&&t.focus(),await Wr([e]),ht()}sf();break}case`screenshot`:sf(),await(t.dataset.shotAction===`region`?Tr:Pi)();break;default:break}}var Df=0,Of=200,kf=150,Af={promptTriggerBtn:`prompts`,addMenuSkillBtn:`skills`,addMenuMcpBtn:`mcp`,addMenuPageBtn:`pages`,addMenuKnowledgeBtn:`knowledge`,addMenuAgentBtn:`agents`,addMenuProxyBtn:`proxies`,addMenuWorkspaceBtn:`workspace`,screenshotBtn:`screenshot`};async function jf(){let e=[{id:`addMenuSkillBtn`,available:()=>Gi()},{id:`addMenuMcpBtn`,available:()=>gr()},{id:`addMenuKnowledgeBtn`,available:async()=>(await Zt()).ok},{id:`addMenuProxyBtn`,available:async()=>(await cn()).length>0},{id:`addMenuWorkspaceBtn`,available:async()=>!!await ca()}],t=++Df;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===Df&&(r.style.display=i?``:`none`)}))}function Mf(){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=gf()?_f():null;t.querySelectorAll(`.input-add-item`).forEach(t=>{t.classList.toggle(`panel-active`,!!e&&Af[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?(bf(),s(),jf()):(i&&=(clearTimeout(i),null),a&&=(clearTimeout(a),null),bf(),s())},u=()=>t.style.display!==`none`;mf({onRequestClose:()=>l(!1)}),e.addEventListener(`click`,e=>{e.stopPropagation();let t=!u();t&&(Mt(),an(),Jd()),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,!vf()&&(bf(),s())},kf)};r&&r.addEventListener(`mouseover`,e=>{if(!u())return;let t=e.target.closest(`.input-add-item`),n=t?Af[t.id]:null;if(!n){d();return}a&&=(clearTimeout(a),null),!(gf()&&_f()===n)&&(i&&clearTimeout(i),i=setTimeout(async()=>{i=null;let e=yf(n);c(t);try{await e}catch{}c(t),s()},Of))}),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`,()=>{gf()&&c()}),[{id:`promptTriggerBtn`,open:()=>pn(``,`prompts`)},{id:`addMenuSkillBtn`,open:()=>pn(``,`skills`)},{id:`addMenuMcpBtn`,open:()=>pn(``,`mcp`)},{id:`addMenuPageBtn`,open:()=>Ai(``,`pages`)},{id:`addMenuKnowledgeBtn`,open:()=>Ai(``,`knowledge`)},{id:`addMenuAgentBtn`,open:()=>Ai(``,`agents`)},{id:`addMenuProxyBtn`,open:()=>Ai(``,`proxies`)},{id:`addMenuWorkspaceBtn`,open:()=>qd(``)}].forEach(({id:e,open:t})=>{let n=document.getElementById(e);n&&n.addEventListener(`click`,async e=>{e.stopPropagation(),n.blur(),Mt(),an(),Jd();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 Nf=`usageTipsEnabled`,Pf=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 Ff=[{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,If=null,Lf=null,Rf=null,zf=null,Bf=!1,Vf=null,Hf=!0,Uf=null;function Wf(){return v.agentPlatform?.connected===!0}function Gf(){let e=a();return Ff.filter(e=>e.scene!==`agent`||Wf()).map(t=>({id:t.id,text:e===`en`?t.en:t.zh}))}function Kf(e){let t=e.findIndex(e=>e.id===Vf);return t>=0?t:0}function qf(){if(!Z||!If)return;let e=If.scrollWidth>If.clientWidth+1;Z.classList.toggle(`is-truncated`,e)}function Jf(e,t){if(!If||!e.length)return;let n=e[t%e.length];Vf=n.id,If.textContent=n.text,Lf&&(Lf.textContent=n.text),qf(),If.classList.remove(`fade-in`),If.offsetWidth,If.classList.add(`fade-in`)}function Yf(){if(!Hf||!Z||Z.style.display===`none`)return;let e=Gf();e.length&&Jf(e,Kf(e)+1)}function Xf(){zf&&=(clearInterval(zf),null)}function Zf(){Xf(),!(!Hf||Bf)&&(zf=setInterval(Yf,Pf))}function Qf(){if(!Hf||!Z)return;let e=Gf();if(!e.length){ep();return}e.some(e=>e.id===Vf)?Jf(e,Kf(e)):(Vf=null,Jf(e,0))}function $f(){if(!Z)return;Hf=!0,Z.style.display=``;let e=Gf();if(!e.length){ep();return}Jf(e,Kf(e)),Zf()}function ep(){Z&&(Z.style.display=`none`,Xf())}function tp(){Z.addEventListener(`mouseenter`,()=>{Bf=!0,Xf()}),Z.addEventListener(`mouseleave`,()=>{Bf=!1,Zf()}),Rf.addEventListener(`click`,e=>{e.stopPropagation(),np(),A(t(`usageTips.dismissedHint`),`info`,5e3)}),chrome.storage.onChanged.addListener((e,t)=>{t!==`local`||!e[Nf]||(e[Nf].newValue===!1?(Hf=!1,ep()):$f())}),document.addEventListener(`agent-connection-changed`,Qf),o(Qf),typeof ResizeObserver<`u`&&new ResizeObserver(qf).observe(Z)}function np(){Hf=!1,ep();try{chrome.storage.local.set({[Nf]:!1})}catch{}}function rp(){if(Z=document.getElementById(`usageTipsBar`),If=document.getElementById(`usageTipsText`),Lf=document.getElementById(`usageTipsTooltip`),Rf=document.getElementById(`usageTipsDismiss`),!(!Z||!If||!Lf||!Rf)){tp(),Uf=document.getElementById(`chatContainer`),Uf&&(Uf.appendChild(Z),typeof MutationObserver<`u`&&new MutationObserver(()=>{Uf.querySelectorAll(`.usage-tips-bar`).forEach(e=>{e!==Z&&e.remove()}),(Z.parentNode!==Uf||Z.nextElementSibling)&&Uf.appendChild(Z)}).observe(Uf,{childList:!0}));try{chrome.storage.local.get([Nf],e=>{Hf=e?.[Nf]!==!1,Hf?$f():ep()})}catch{$f()}}}function ip({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
438
  `,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(`
439
- `,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 lp(e,t){let n;return function(...r){clearTimeout(n),n=setTimeout(()=>{clearTimeout(n),e(...r)},t)}}var up=null,dp=null,fp=null,pp=null,mp=null,hp=null,gp=null,_p=null,vp=null,yp=null,bp=!1,xp=!1,Sp=null,Cp={[Un.DISPATCHING]:`queue.statusDispatching`,[Un.INJECTING]:`queue.statusInjecting`,[Un.INJECTED]:`queue.statusInjected`,[Un.DONE]:`queue.statusDone`,[Un.FAILED]:`queue.statusFailed`};function wp(e){if(e.status===Un.QUEUED)return e.interrupted?t(`queue.statusRecovered`):``;let n=Cp[e.status];return n?t(n):``}function Tp(){return v.activeSessionId}function Ep(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(` · `):Dn(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 Dp(e,n){let r=Ep(e),i=e.status===Un.DISPATCHING,a=wp(e),o=(a?`<span class="queue-chip-status${i?` running`:``}${e.interrupted?` warning`:``}"${i?` title="${A(t(`queue.statusRunningHint`))}"`:``}>${A(a)}</span>`:``)+r,s=v.isGenerating===!0;return`
440
- <div class="queue-chip" draggable="true" data-id="${A(e.id)}" data-status="${A(e.status)}">
439
+ `,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 ap(e,t){let n;return function(...r){clearTimeout(n),n=setTimeout(()=>{clearTimeout(n),e(...r)},t)}}var op=null,sp=null,cp=null,lp=null,up=null,dp=null,fp=null,pp=null,mp=null,hp=null,gp=!1,_p=!1,vp=null,yp={[Ui.DISPATCHING]:`queue.statusDispatching`,[Ui.INJECTING]:`queue.statusInjecting`,[Ui.INJECTED]:`queue.statusInjected`,[Ui.DONE]:`queue.statusDone`,[Ui.FAILED]:`queue.statusFailed`};function bp(e){if(e.status===Ui.QUEUED)return e.interrupted?t(`queue.statusRecovered`):``;let n=yp[e.status];return n?t(n):``}function xp(){return v.activeSessionId}function Sp(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(` · `):vn(e.contextSnapshot)?t(`queue.withContext`):``;return i?`<span class="queue-chip-ctx" title="${j(n&&(n.fileNames||[]).length?n.fileNames.join(`、`):i)}">${j(i)}</span>`:``}function Cp(e,n){let r=Sp(e),i=e.status===Ui.DISPATCHING,a=bp(e),o=(a?`<span class="queue-chip-status${i?` running`:``}${e.interrupted?` warning`:``}"${i?` title="${j(t(`queue.statusRunningHint`))}"`:``}>${j(a)}</span>`:``)+r,s=v.isGenerating===!0;return`
440
+ <div class="queue-chip" draggable="true" data-id="${j(e.id)}" data-status="${j(e.status)}">
441
441
  <span class="queue-chip-index">${n+1}</span>
442
442
  <div class="queue-chip-main">
443
- <div class="queue-chip-text" title="${A(e.text)}">${A(e.text)}</div>
443
+ <div class="queue-chip-text" title="${j(e.text)}">${j(e.text)}</div>
444
444
  ${o?`<div class="queue-chip-meta">${o}</div>`:``}
445
445
  </div>
446
446
  <div class="queue-chip-actions">
447
- <button class="queue-chip-btn inject${s?``:` muted`}" type="button" data-act="inject" title="${A(t(s?`queue.inject`:`queue.injectIdleHint`))}">⚡</button>
448
- <button class="queue-chip-btn" type="button" data-act="edit" title="${A(t(`queue.editBack`))}">✎</button>
449
- <button class="queue-chip-btn danger" type="button" data-act="remove" title="${A(t(`queue.delete`))}">✕</button>
447
+ <button class="queue-chip-btn inject${s?``:` muted`}" type="button" data-act="inject" title="${j(t(s?`queue.inject`:`queue.injectIdleHint`))}">⚡</button>
448
+ <button class="queue-chip-btn" type="button" data-act="edit" title="${j(t(`queue.editBack`))}">✎</button>
449
+ <button class="queue-chip-btn danger" type="button" data-act="remove" title="${j(t(`queue.delete`))}">✕</button>
450
450
  </div>
451
- </div>`}function Op(e){return e.length?e.map(e=>`
452
- <div class="queue-recent-item" data-id="${A(e.id)}">
453
- <span class="queue-recent-status">${A(wp(e))}</span>
454
- <span class="queue-recent-text" title="${A(e.text)}">${A(e.text)}</span>
455
- <button class="queue-chip-btn" type="button" data-act="requeue" title="${A(t(`queue.requeue`))}">↺</button>
456
- <button class="queue-chip-btn danger" type="button" data-act="forget" title="${A(t(`queue.forgetRecent`))}">✕</button>
457
- </div>`).join(``):`<div class="queue-recent-empty">${A(t(`queue.recentEmpty`))}</div>`}function kp(e={}){if(!up||Sp)return;let n=Tp();if(!n){up.style.display=`none`;return}let r=Pt(n),i=r.items,a=i.length>0,o=r.recent.filter(e=>e.status===Un.FAILED).length,s=o>0;if(!a&&!s&&(!xp||r.recent.length===0)){up.style.display=`none`;return}if(up.style.display=``,up.classList.toggle(`empty`,!a),up.classList.toggle(`expanded`,bp&&a),up.classList.toggle(`paused`,r.paused),fp&&(a?(fp.textContent=t(`queue.summary`,{count:i.length}),fp.classList.remove(`failed`),fp.removeAttribute(`title`)):s?(fp.textContent=t(`queue.summaryFailed`,{count:o}),fp.classList.add(`failed`),fp.title=t(`queue.summaryFailedHint`)):(fp.textContent=t(`queue.summaryEmpty`),fp.classList.remove(`failed`),fp.removeAttribute(`title`))),pp&&(pp.style.display=r.paused?``:`none`,pp.title=r.pausedReason===`user_stopped`?t(`queue.pausedByStop`):t(`queue.pausedHint`)),mp){let e=r.paused&&i.length>0;mp.style.display=e?``:`none`,mp.textContent=t(`queue.resumeQueue`)}if(hp){let e=v.isGenerating===!0&&a&&!r.paused;hp.style.display=e?``:`none`}gp&&(gp.classList.toggle(`active`,xp),gp.title=t(`queue.recentTitle`)),vp&&(vp.style.display=a?``:`none`,vp.setAttribute(`aria-expanded`,bp?`true`:`false`),vp.textContent=bp?`▲`:`▼`),dp&&(dp.style.display=bp&&a?``:`none`,dp.innerHTML=a?i.map((e,t)=>Dp(e,t)).join(``):``),_p&&(_p.style.display=xp?``:`none`,_p.innerHTML=xp?Op(r.recent):``),e.flash&&(up.classList.remove(`queue-flash`),up.offsetWidth,up.classList.add(`queue-flash`))}async function Ap(e,n={}){let r=Tp();if(!r||!e)return!1;let i=Rt(r,e);if(!i)return!1;let a=document.getElementById(`userInput`);if(a&&a.value.trim()){let e=await yn({autoDrain:!1});if(!e.ok)return k(e.error===`queue_full`?t(`queue.queueFull`,{limit:e.limit}):t(`queue.enqueueFailed`),`warning`),!1}else if(hn())return k(t(`queue.inputHasUnsavedContext`),`warning`,4e3),!1;let o=await Yn(i);return a&&(a.value=i.text,a.style.height=`auto`,a.dispatchEvent(new Event(`input`)),a.focus()),await en(r,e),await Et(e),o.wantsAttachments?k(o.attachments?t(`queue.editBackWithAttachments`):t(`queue.attachmentsMissing`),o.attachments?`success`:`warning`,2500):n.viaShortcut&&k(t(`queue.editTailHint`),`info`,2e3),!0}function jp(){let e=Tp();if(!e)return!1;let t=On(e);return t?(Ap(t.id,{viaShortcut:!0}),!0):!1}async function Mp(e,n){let r=Tp();if(!(!r||!n)&&!(wn(r).findIndex(e=>e.id===n)<0))switch(e){case`edit`:await Ap(n);break;case`inject`:await Pn(n,r);break;case`remove`:await en(r,n),await Et(n),k(t(`queue.deleted`),`info`,1500);break;default:break}}async function Np(e){let t=Tp();t&&await fn(t,e)}async function Pp(e,t){if(e.preventDefault(),!Sp)return;let n=t?.dataset?.id;if(!n||n===Sp)return;let r=Tp();if(!r)return;let i=wn(r).map(e=>e.id),a=i.indexOf(Sp);if(a<0)return;i.splice(a,1);let o=t.getBoundingClientRect(),s=e.clientY-o.top>o.height/2,c=i.indexOf(n);c<0?c=i.length:s&&(c+=1),i.splice(c,0,Sp),await Np(i)}function Fp(){dp&&(dp.addEventListener(`dragstart`,e=>{let t=e.target.closest?.(`.queue-chip`);if(t){Sp=t.dataset.id,t.classList.add(`dragging`);try{e.dataTransfer.effectAllowed=`move`,e.dataTransfer.setData(`text/plain`,Sp)}catch{}}}),dp.addEventListener(`dragend`,e=>{let t=e.target.closest?.(`.queue-chip`);t&&t.classList.remove(`dragging`),Sp=null,dp.querySelectorAll(`.drag-over-top, .drag-over-bottom`).forEach(e=>{e.classList.remove(`drag-over-top`,`drag-over-bottom`)}),kp()}),dp.addEventListener(`dragover`,e=>{let t=e.target.closest?.(`.queue-chip`);if(!t||!Sp||t.dataset.id===Sp)return;e.preventDefault();let n=t.getBoundingClientRect(),r=e.clientY-n.top>n.height/2;t.classList.toggle(`drag-over-bottom`,r),t.classList.toggle(`drag-over-top`,!r)}),dp.addEventListener(`dragleave`,e=>{let t=e.target.closest?.(`.queue-chip`);t&&t.classList.remove(`drag-over-top`,`drag-over-bottom`)}),dp.addEventListener(`drop`,e=>{let t=e.target.closest?.(`.queue-chip`);Pp(e,t)}))}function Ip(){dp?.addEventListener(`click`,e=>{let t=e.target.closest?.(`.queue-chip-btn`);if(!t||t.disabled)return;let n=t.closest(`.queue-chip`);n&&Mp(t.dataset.act,n.dataset.id)}),_p?.addEventListener(`click`,async e=>{let n=e.target.closest?.(`.queue-chip-btn`),r=n?.closest(`.queue-recent-item`),i=Tp();if(!n||!r||!i)return;if(n.dataset.act===`forget`){await Ht(i,r.dataset.id)&&k(t(`queue.forgotRecent`),`success`,1500);return}if(n.dataset.act!==`requeue`)return;let a=Ct(i).find(e=>e.id===r.dataset.id),o=!!(a&&a.attachmentSummary),s=await Fn(i,r.dataset.id);if(!s.ok){k(s.error===`queue_full`?t(`queue.queueFull`,{limit:s.limit}):t(`queue.enqueueFailed`),`warning`);return}k(t(o?`queue.requeuedNoAttachments`:`queue.requeued`),o?`warning`:`success`,2500)}),vp?.addEventListener(`click`,()=>{bp=!bp,kp()}),yp?.addEventListener(`click`,e=>{e.target.closest?.(`button`)||wn(Tp()||``).length&&(bp=!bp,kp())}),gp?.addEventListener(`click`,()=>{xp=!xp,xp&&(bp=!0),kp()}),mp?.addEventListener(`click`,async()=>{await Yt(),k(t(`queue.resumed`),`success`,1500)}),hp?.addEventListener(`click`,()=>{document.dispatchEvent(new CustomEvent(`queue-stop-and-send`))}),Fp(),ra(()=>kp()),document.addEventListener(`queue-enqueued`,()=>{bp=!0,kp({flash:!0})}),document.addEventListener(`session-switched`,()=>{kp()}),document.addEventListener(`generation-ended`,()=>kp()),document.addEventListener(`generating-state-changed`,()=>kp())}async function Lp(){await Zr(),kp()}async function Rp(){if(await Zr(),up=document.getElementById(`queueStrip`),!up){r.warn(`[QueuePanel] #queueStrip not found, queue UI disabled`);return}dp=document.getElementById(`queueList`),fp=document.getElementById(`queueSummary`),pp=document.getElementById(`queuePausedTag`),mp=document.getElementById(`queueResumeBtn`),hp=document.getElementById(`queueStopSendBtn`),gp=document.getElementById(`queueRecentBtn`),_p=document.getElementById(`queueRecent`),vp=document.getElementById(`queueToggleBtn`),yp=up.querySelector(`.queue-strip-head`),Ip(),kp()}var zp=new Set,Bp=new Set,Vp=new Map,Hp=30*1e3;function Up(e){let t=Vp.get(e);return t?Date.now()-t<Hp?!0:(Vp.delete(e),!1):!1}async function Wp(e){let t=h(e)||e;if(!t||zp.has(t)||Bp.has(t)||Up(t))return null;Bp.add(t);try{let e=await te();if(!e)return null;let n=null;try{let r=await oe(`${e.url}/api/status/detail`,{headers:{Authorization:`Bearer ${e.token}`,"X-AIH-Session-Id":t}});if(!r.ok)return Vp.set(t,Date.now()),null;n=await r.json()}catch(e){return r.debug(`[WorkdirReconcile] fetch detail failed:`,e?.message||e),Vp.set(t,Date.now()),null}if(!n?.success||!n.sessionWorkdirSupported)return Vp.set(t,Date.now()),null;let i=n.sessionWorkdir||null,a=n.defaultWorkdir||n.workdir||null;if(!i||i===a)return Vp.set(t,Date.now()),null;let o=await p(t);return o.scope===`session`?(Vp.set(t,Date.now()),null):o.boundWorkdir?await ne(t)?(zp.add(t),r.debug(`[WorkdirReconcile] cleared stale agent binding:`,t,i),{cleaned:!0,workdir:i}):null:await E(t,i,o.agentId||e.id||null)?(zp.add(t),r.debug(`[WorkdirReconcile] restored session workdir:`,t,i),{adopted:!0,workdir:i}):null}finally{Bp.delete(t)}}e(`zh`,{sidePanel:{popupTitle:`浮层解答`,popupTooltip:`浮层解答(不进入对话)`,popupLoading:`思考中...`,popupCopy:`复制`,popupCopied:`已复制到剪贴板`,popupTransfer:`转入对话`,popupTransferred:`已转入对话`,popupRegenerate:`重新生成`,popupClose:`关闭`,popupLock:`锁定(不随点击外部关闭)`,popupUnlock:`解锁(可点击外部关闭)`,popupRequestFailed:`请求失败`,popupContextLabel:`上下文`,popupContextTruncated:`(已截断)`,popupSystemPrompt:`用户在阅读 AI 回答时选中了其中的片段,希望理解选中内容。请结合上下文,只针对选中片段回答,简洁清楚,不要展开与选中内容无关的长论述。`}}),e(`en`,{sidePanel:{popupTitle:`Popup Answer`,popupTooltip:`Answer in popup (not in conversation)`,popupLoading:`Thinking...`,popupCopy:`Copy`,popupCopied:`Copied to clipboard`,popupTransfer:`Move to chat`,popupTransferred:`Moved to chat`,popupRegenerate:`Regenerate`,popupClose:`Close`,popupLock:`Lock (keep open on outside click)`,popupUnlock:`Unlock (close on outside click)`,popupRequestFailed:`Request failed`,popupContextLabel:`Context`,popupContextTruncated:`(truncated)`,popupSystemPrompt:`The user selected a fragment while reading an AI answer and wants to understand it. Using the surrounding context, answer only about the selected fragment, concisely and clearly, without expanding into unrelated long discussion.`}});var Gp=1500,Q=null,Kp=null,qp=``,Jp=null,Yp=``,Xp=``,Zp=!1,Qp=!1,$p=!1;function em(e){return(e||``).replace(/[ \t\f\v]+/g,` `).replace(/ *\n */g,`
451
+ </div>`}function wp(e){return e.length?e.map(e=>`
452
+ <div class="queue-recent-item" data-id="${j(e.id)}">
453
+ <span class="queue-recent-status">${j(bp(e))}</span>
454
+ <span class="queue-recent-text" title="${j(e.text)}">${j(e.text)}</span>
455
+ <button class="queue-chip-btn" type="button" data-act="requeue" title="${j(t(`queue.requeue`))}">↺</button>
456
+ <button class="queue-chip-btn danger" type="button" data-act="forget" title="${j(t(`queue.forgetRecent`))}">✕</button>
457
+ </div>`).join(``):`<div class="queue-recent-empty">${j(t(`queue.recentEmpty`))}</div>`}function Tp(e={}){if(!op||vp)return;let n=xp();if(!n){op.style.display=`none`;return}let r=Rt(n),i=r.items,a=i.length>0,o=r.recent.filter(e=>e.status===Ui.FAILED).length,s=o>0;if(!a&&!s&&(!_p||r.recent.length===0)){op.style.display=`none`;return}if(op.style.display=``,op.classList.toggle(`empty`,!a),op.classList.toggle(`expanded`,gp&&a),op.classList.toggle(`paused`,r.paused),cp&&(a?(cp.textContent=t(`queue.summary`,{count:i.length}),cp.classList.remove(`failed`),cp.removeAttribute(`title`)):s?(cp.textContent=t(`queue.summaryFailed`,{count:o}),cp.classList.add(`failed`),cp.title=t(`queue.summaryFailedHint`)):(cp.textContent=t(`queue.summaryEmpty`),cp.classList.remove(`failed`),cp.removeAttribute(`title`))),lp&&(lp.style.display=r.paused?``:`none`,lp.title=r.pausedReason===`user_stopped`?t(`queue.pausedByStop`):t(`queue.pausedHint`)),up){let e=r.paused&&i.length>0;up.style.display=e?``:`none`,up.textContent=t(`queue.resumeQueue`)}if(dp){let e=v.isGenerating===!0&&a&&!r.paused;dp.style.display=e?``:`none`}fp&&(fp.classList.toggle(`active`,_p),fp.title=t(`queue.recentTitle`)),mp&&(mp.style.display=a?``:`none`,mp.setAttribute(`aria-expanded`,gp?`true`:`false`),mp.textContent=gp?`▲`:`▼`),sp&&(sp.style.display=gp&&a?``:`none`,sp.innerHTML=a?i.map((e,t)=>Cp(e,t)).join(``):``),pp&&(pp.style.display=_p?``:`none`,pp.innerHTML=_p?wp(r.recent):``),e.flash&&(op.classList.remove(`queue-flash`),op.offsetWidth,op.classList.add(`queue-flash`))}async function Ep(e,n={}){let r=xp();if(!r||!e)return!1;let i=Vn(r,e);if(!i)return!1;let a=document.getElementById(`userInput`);if(a&&a.value.trim()){let e=await mn({autoDrain:!1});if(!e.ok)return A(e.error===`queue_full`?t(`queue.queueFull`,{limit:e.limit}):t(`queue.enqueueFailed`),`warning`),!1}else if(Jr())return A(t(`queue.inputHasUnsavedContext`),`warning`,4e3),!1;let o=await Tt(i);return a&&(a.value=i.text,a.style.height=`auto`,a.dispatchEvent(new Event(`input`)),a.focus()),await Ht(r,e),await ea(e),o.wantsAttachments?A(o.attachments?t(`queue.editBackWithAttachments`):t(`queue.attachmentsMissing`),o.attachments?`success`:`warning`,2500):n.viaShortcut&&A(t(`queue.editTailHint`),`info`,2e3),!0}function Dp(){let e=xp();if(!e)return!1;let t=yn(e);return t?(Ep(t.id,{viaShortcut:!0}),!0):!1}async function Op(e,n){let r=xp();if(!(!r||!n)&&!(Pt(r).findIndex(e=>e.id===n)<0))switch(e){case`edit`:await Ep(n);break;case`inject`:await un(n,r);break;case`remove`:await Ht(r,n),await ea(n),A(t(`queue.deleted`),`info`,1500);break;default:break}}async function kp(e){let t=xp();t&&await en(t,e)}async function Ap(e,t){if(e.preventDefault(),!vp)return;let n=t?.dataset?.id;if(!n||n===vp)return;let r=xp();if(!r)return;let i=Pt(r).map(e=>e.id),a=i.indexOf(vp);if(a<0)return;i.splice(a,1);let o=t.getBoundingClientRect(),s=e.clientY-o.top>o.height/2,c=i.indexOf(n);c<0?c=i.length:s&&(c+=1),i.splice(c,0,vp),await kp(i)}function jp(){sp&&(sp.addEventListener(`dragstart`,e=>{let t=e.target.closest?.(`.queue-chip`);if(t){vp=t.dataset.id,t.classList.add(`dragging`);try{e.dataTransfer.effectAllowed=`move`,e.dataTransfer.setData(`text/plain`,vp)}catch{}}}),sp.addEventListener(`dragend`,e=>{let t=e.target.closest?.(`.queue-chip`);t&&t.classList.remove(`dragging`),vp=null,sp.querySelectorAll(`.drag-over-top, .drag-over-bottom`).forEach(e=>{e.classList.remove(`drag-over-top`,`drag-over-bottom`)}),Tp()}),sp.addEventListener(`dragover`,e=>{let t=e.target.closest?.(`.queue-chip`);if(!t||!vp||t.dataset.id===vp)return;e.preventDefault();let n=t.getBoundingClientRect(),r=e.clientY-n.top>n.height/2;t.classList.toggle(`drag-over-bottom`,r),t.classList.toggle(`drag-over-top`,!r)}),sp.addEventListener(`dragleave`,e=>{let t=e.target.closest?.(`.queue-chip`);t&&t.classList.remove(`drag-over-top`,`drag-over-bottom`)}),sp.addEventListener(`drop`,e=>{let t=e.target.closest?.(`.queue-chip`);Ap(e,t)}))}function Mp(){sp?.addEventListener(`click`,e=>{let t=e.target.closest?.(`.queue-chip-btn`);if(!t||t.disabled)return;let n=t.closest(`.queue-chip`);n&&Op(t.dataset.act,n.dataset.id)}),pp?.addEventListener(`click`,async e=>{let n=e.target.closest?.(`.queue-chip-btn`),r=n?.closest(`.queue-recent-item`),i=xp();if(!n||!r||!i)return;if(n.dataset.act===`forget`){await Dn(i,r.dataset.id)&&A(t(`queue.forgotRecent`),`success`,1500);return}if(n.dataset.act!==`requeue`)return;let a=$r(i).find(e=>e.id===r.dataset.id),o=!!(a&&a.attachmentSummary),s=await dn(i,r.dataset.id);if(!s.ok){A(s.error===`queue_full`?t(`queue.queueFull`,{limit:s.limit}):t(`queue.enqueueFailed`),`warning`);return}A(t(o?`queue.requeuedNoAttachments`:`queue.requeued`),o?`warning`:`success`,2500)}),mp?.addEventListener(`click`,()=>{gp=!gp,Tp()}),hp?.addEventListener(`click`,e=>{e.target.closest?.(`button`)||Pt(xp()||``).length&&(gp=!gp,Tp())}),fp?.addEventListener(`click`,()=>{_p=!_p,_p&&(gp=!0),Tp()}),up?.addEventListener(`click`,async()=>{await qn(),A(t(`queue.resumed`),`success`,1500)}),dp?.addEventListener(`click`,()=>{document.dispatchEvent(new CustomEvent(`queue-stop-and-send`))}),jp(),Pn(()=>Tp()),document.addEventListener(`queue-enqueued`,()=>{gp=!0,Tp({flash:!0})}),document.addEventListener(`session-switched`,()=>{Tp()}),document.addEventListener(`generation-ended`,()=>Tp()),document.addEventListener(`generating-state-changed`,()=>Tp())}async function Np(){await St(),Tp()}async function Pp(){if(await St(),op=document.getElementById(`queueStrip`),!op){r.warn(`[QueuePanel] #queueStrip not found, queue UI disabled`);return}sp=document.getElementById(`queueList`),cp=document.getElementById(`queueSummary`),lp=document.getElementById(`queuePausedTag`),up=document.getElementById(`queueResumeBtn`),dp=document.getElementById(`queueStopSendBtn`),fp=document.getElementById(`queueRecentBtn`),pp=document.getElementById(`queueRecent`),mp=document.getElementById(`queueToggleBtn`),hp=op.querySelector(`.queue-strip-head`),Mp(),Tp()}var Fp=new Set,Ip=new Set,Lp=new Map,Rp=30*1e3;function zp(e){let t=Lp.get(e);return t?Date.now()-t<Rp?!0:(Lp.delete(e),!1):!1}async function Bp(e){let t=h(e)||e;if(!t||Fp.has(t)||Ip.has(t)||zp(t))return null;Ip.add(t);try{let e=await te();if(!e)return null;let n=null;try{let r=await oe(`${e.url}/api/status/detail`,{headers:{Authorization:`Bearer ${e.token}`,"X-AIH-Session-Id":t}});if(!r.ok)return Lp.set(t,Date.now()),null;n=await r.json()}catch(e){return r.debug(`[WorkdirReconcile] fetch detail failed:`,e?.message||e),Lp.set(t,Date.now()),null}if(!n?.success||!n.sessionWorkdirSupported)return Lp.set(t,Date.now()),null;let i=n.sessionWorkdir||null,a=n.defaultWorkdir||n.workdir||null;if(!i||i===a)return Lp.set(t,Date.now()),null;let o=await p(t);return o.scope===`session`?(Lp.set(t,Date.now()),null):o.boundWorkdir?await ne(t)?(Fp.add(t),r.debug(`[WorkdirReconcile] cleared stale agent binding:`,t,i),{cleaned:!0,workdir:i}):null:await D(t,i,o.agentId||e.id||null)?(Fp.add(t),r.debug(`[WorkdirReconcile] restored session workdir:`,t,i),{adopted:!0,workdir:i}):null}finally{Ip.delete(t)}}e(`zh`,{sidePanel:{popupTitle:`浮层解答`,popupTooltip:`浮层解答(不进入对话)`,popupLoading:`思考中...`,popupCopy:`复制`,popupCopied:`已复制到剪贴板`,popupTransfer:`转入对话`,popupTransferred:`已转入对话`,popupRegenerate:`重新生成`,popupClose:`关闭`,popupLock:`锁定(不随点击外部关闭)`,popupUnlock:`解锁(可点击外部关闭)`,popupRequestFailed:`请求失败`,popupContextLabel:`上下文`,popupContextTruncated:`(已截断)`,popupSystemPrompt:`用户在阅读 AI 回答时选中了其中的片段,希望理解选中内容。请结合上下文,只针对选中片段回答,简洁清楚,不要展开与选中内容无关的长论述。`}}),e(`en`,{sidePanel:{popupTitle:`Popup Answer`,popupTooltip:`Answer in popup (not in conversation)`,popupLoading:`Thinking...`,popupCopy:`Copy`,popupCopied:`Copied to clipboard`,popupTransfer:`Move to chat`,popupTransferred:`Moved to chat`,popupRegenerate:`Regenerate`,popupClose:`Close`,popupLock:`Lock (keep open on outside click)`,popupUnlock:`Unlock (close on outside click)`,popupRequestFailed:`Request failed`,popupContextLabel:`Context`,popupContextTruncated:`(truncated)`,popupSystemPrompt:`The user selected a fragment while reading an AI answer and wants to understand it. Using the surrounding context, answer only about the selected fragment, concisely and clearly, without expanding into unrelated long discussion.`}});var Vp=1500,Q=null,Hp=null,Up=``,Wp=null,Gp=``,Kp=``,qp=!1,Jp=!1,Yp=!1;function Xp(e){return(e||``).replace(/[ \t\f\v]+/g,` `).replace(/ *\n */g,`
458
458
  `).replace(/\n{3,}/g,`
459
459
 
460
- `).trim()}function tm(e,t){if(!e)return{context:``,truncated:!1};let n=e.startContainer?.parentElement?.closest?.(`.message`);if(!n)return{context:``,truncated:!1};let r=em(n.textContent);if(!r)return{context:``,truncated:!1};let i=c(r);if(i<=Gp)return{context:r,truncated:!1};let a=r.indexOf(t),o=a>=0?a+t.length/2:r.length/2,s=Math.floor(r.length*Gp/Math.max(i,1)),l=Math.max(0,Math.floor(o-s/2)),u=Math.min(r.length,l+s);if(a>=0){let e=a+t.length;a<l&&(l=Math.max(0,a-50)),e>u&&(u=Math.min(r.length,e+50))}let d=r.slice(l,u).trim();if(c(d)>Gp){let e=Gp/c(d);d=d.slice(0,Math.floor(d.length*e))}return{context:d,truncated:!0}}function nm(e,n,r,i){let a=t(`sidePanel.popupSystemPrompt`),o=``;return n&&(o+=`[${t(`sidePanel.popupContextLabel`)}${i?t(`sidePanel.popupContextTruncated`):``}]\n${n}\n\n`),o+=`[${t(`sidePanel.selectedContentLabel`)}]\n${e}\n\n`,o+=`[${t(`sidePanel.userQuestionLabel`)}]\n${r}`,[{role:`system`,content:a},{role:`user`,content:o}]}function rm(){return Q&&document.body.contains(Q)?Q:(Q=document.createElement(`div`),Q.className=`selection-answer-popup`,Q.id=`selectionAnswerPopup`,Q.innerHTML=`
460
+ `).trim()}function Zp(e,t){if(!e)return{context:``,truncated:!1};let n=e.startContainer?.parentElement?.closest?.(`.message`);if(!n)return{context:``,truncated:!1};let r=Xp(n.textContent);if(!r)return{context:``,truncated:!1};let i=c(r);if(i<=Vp)return{context:r,truncated:!1};let a=r.indexOf(t),o=a>=0?a+t.length/2:r.length/2,s=Math.floor(r.length*Vp/Math.max(i,1)),l=Math.max(0,Math.floor(o-s/2)),u=Math.min(r.length,l+s);if(a>=0){let e=a+t.length;a<l&&(l=Math.max(0,a-50)),e>u&&(u=Math.min(r.length,e+50))}let d=r.slice(l,u).trim();if(c(d)>Vp){let e=Vp/c(d);d=d.slice(0,Math.floor(d.length*e))}return{context:d,truncated:!0}}function Qp(e,n,r,i){let a=t(`sidePanel.popupSystemPrompt`),o=``;return n&&(o+=`[${t(`sidePanel.popupContextLabel`)}${i?t(`sidePanel.popupContextTruncated`):``}]\n${n}\n\n`),o+=`[${t(`sidePanel.selectedContentLabel`)}]\n${e}\n\n`,o+=`[${t(`sidePanel.userQuestionLabel`)}]\n${r}`,[{role:`system`,content:a},{role:`user`,content:o}]}function $p(){return Q&&document.body.contains(Q)?Q:(Q=document.createElement(`div`),Q.className=`selection-answer-popup`,Q.id=`selectionAnswerPopup`,Q.innerHTML=`
461
461
  <div class="sap-header">
462
462
  <span class="sap-title"></span>
463
463
  <div class="sap-header-actions">
@@ -471,7 +471,7 @@ import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-DvmxOw8q.js"
471
471
  <button class="sap-btn sap-transfer"></button>
472
472
  <button class="sap-btn sap-regen"></button>
473
473
  </div>
474
- `,document.body.appendChild(Q),Q.querySelector(`.sap-close`).addEventListener(`click`,fm),Q.querySelector(`.sap-lock`).addEventListener(`click`,om),Q.querySelector(`.sap-copy`).addEventListener(`click`,gm),Q.querySelector(`.sap-transfer`).addEventListener(`click`,_m),Q.querySelector(`.sap-regen`).addEventListener(`click`,()=>{Jp&&Yp&&ym()}),hm(Q.querySelector(`.sap-header`)),Q)}function im(){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`),am()}function am(){if(!Q)return;let e=Q.querySelector(`.sap-lock`);e&&(e.classList.toggle(`locked`,$p),e.title=t($p?`sidePanel.popupUnlock`:`sidePanel.popupLock`),e.innerHTML=$p?`<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 om(){$p=!$p,am()}function sm(e,t){let n=rm(),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 cm(e){let n=rm();im(),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 lm(){return!!Q&&Q.classList.contains(`show`)}function um(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 dm(e){let t=Q?.querySelector(`.sap-body`);t&&(t.innerHTML=`<div class="sap-error">${A(e)}</div>`)}function fm(){Qp&&Kp&&chrome.runtime.sendMessage({type:`CANCEL_REACT`,sessionId:Kp}).catch(()=>{}),Q&&(Q.classList.remove(`show`),Q.style.display=`none`),Kp=null,qp=``,Qp=!1,$p=!1}function pm(e){if(!lm()||$p||Q.contains(e.target))return;let t=document.getElementById(`selectionFloatingMenu`);t&&t.contains(e.target)||fm()}function mm(e){e.key===`Escape`&&(!lm()||$p||fm())}function hm(e){let t=!1,n,r,i,a;e.addEventListener(`mousedown`,e=>{if(e.target.closest(`.sap-close, .sap-lock`))return;t=!0,n=e.clientX,r=e.clientY;let o=Q.getBoundingClientRect();i=o.top,a=o.left,e.preventDefault()}),document.addEventListener(`mousemove`,e=>{if(!t)return;let o=e.clientX-n,s=e.clientY-r;Q.style.position=`fixed`,Q.style.top=i+s+`px`,Q.style.left=a+o+`px`}),document.addEventListener(`mouseup`,()=>{t=!1})}function gm(){qp&&navigator.clipboard.writeText(qp).then(()=>{k(t(`sidePanel.popupCopied`))}).catch(()=>{let e=document.createElement(`textarea`);e.value=qp,document.body.appendChild(e),e.select(),document.execCommand(`copy`),document.body.removeChild(e),k(t(`sidePanel.popupCopied`))})}function _m(){if(!qp||!Jp)return;kn()&&Qr();let e=qp,n=Jp.content,r=`${Xp?`[${t(`sidePanel.popupContextLabel`)}]\n${Xp}\n\n`:``}[${t(`sidePanel.selectedContentLabel`)}]\n${Yp}\n\n[${t(`sidePanel.userQuestionLabel`)}]\n${Jp.content}`;T(async()=>{let{addMessage:e}=await import(`./context-indicator-BSGa1g7l.js`).then(e=>e.V);return{addMessage:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8])).then(({addMessage:i})=>{i(`user`,n,!0,[],null,!1,r),v.messageHistory.push({role:`user`,content:r,timestamp:new Date().toISOString()}),i(`assistant`,e,!0),v.messageHistory.push({role:`assistant`,content:e}),T(async()=>{let{saveCurrentSession:e}=await import(`./context-indicator-BSGa1g7l.js`).then(e=>e.Cr);return{saveCurrentSession:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8])).then(({saveCurrentSession:e})=>{e()}),Promise.all([T(()=>import(`./context-indicator-BSGa1g7l.js`).then(e=>e.pt),__vite__mapDeps([0,1,2,3,4,5,6,7,8])),new Promise(e=>requestAnimationFrame(e))]).then(([{autoScrollToBottom:e}])=>{e(document.getElementById(`chatContainer`),{force:!0,smooth:!0}),k(t(`sidePanel.popupTransferred`))})}),fm()}function vm(e,t,n){let{context:r,truncated:i}=tm(n,t);Jp=e,Yp=t,Xp=r,Zp=i,ym()}function ym(){qp=``,Qp=!0,cm(Jp?.content);let e=nm(Yp,Xp,Jp.content,Zp);Kp=`popup_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,chrome.runtime.sendMessage({type:`SIDEPANEL_POPUP_ASK`,sessionId:Kp,messages:e}).catch(e=>{r.error(`[SelectionPopup] sendMessage failed:`,e),dm(t(`sidePanel.popupRequestFailed`)),Qp=!1})}var bm=!1;function xm(){bm||(bm=!0,chrome.runtime.onMessage.addListener(e=>{if(!(!e||!e.type)&&e.type.startsWith(`SIDEPANEL_POPUP_`)&&e.sessionId===Kp){if(e.type===`SIDEPANEL_POPUP_STREAM_CHUNK`)e.delta&&(qp+=e.delta,um(ut(qp)));else if(e.type===`SIDEPANEL_POPUP_STREAM_DONE`)Qp=!1,e.finalContent&&(qp=e.finalContent),um(ut(qp));else if(e.type===`SIDEPANEL_POPUP_STREAM_ERROR`){if(!Qp)return;Qp=!1,dm(e.error||t(`sidePanel.popupRequestFailed`))}}}))}function Sm(){xm(),document.addEventListener(`mousedown`,pm),document.addEventListener(`keydown`,mm)}function Cm(e,t,n,r,i){!t||!e||(xm(),sm(n,r),$p=!1,vm(e,t,i||v.currentSelectionRange))}e(`zh`,{tokenStats:{clearConfirmMessage:`确定要清空所有 Token 使用统计吗?此操作不可撤销。`,loadFailed:`加载失败`,currentSessionNoData:`当前会话暂无数据`,totalTokenUsage:`总 Token 消耗`,apiCallCount:`API 调用次数`,contextUsageRate:`上下文使用率`,max:`最大`,avg:`平均`,min:`最小`,totalTokens:`总 Token`,totalSessions:`总会话数`,totalApiCalls:`总 API 调用`,callTypeNonStream:`普通`,callTypeStream:`流式`,callTypeReflection:`反思`,callTypeToolReflection:`工具反思`,callTypeSubtaskReflection:`子任务反思`,tabTrend:`趋势`,tabDistribution:`分布`,tabGlobal:`全局`,topCardSessionTokens:`本次 Token`,topCardSessionCalls:`本次调用`,topCardContextPeak:`上下文峰值`,sparklineTitle:`最近 20 次调用趋势`,distPromptVsCompletion:`Prompt / Completion 占比`,distPrompt:`Prompt`,distCompletion:`Completion`,distByModel:`按模型分布`,distByCallType:`按调用类型分布`,distNoData:`暂无分布数据`,globalSparklineTitle:`最近 30 天趋势`,globalNoDailyData:`所选范围内暂无数据`,globalTotalTokens:`总 Token`,globalTotalSessions:`总会话数`,globalTotalApiCalls:`总 API 调用`}}),e(`en`,{tokenStats:{clearConfirmMessage:`Are you sure you want to clear all Token usage statistics? This action cannot be undone.`,loadFailed:`Load failed`,currentSessionNoData:`No data for current session`,totalTokenUsage:`Total Token Usage`,apiCallCount:`API Call Count`,contextUsageRate:`Context Usage Rate`,max:`Max`,avg:`Avg`,min:`Min`,totalTokens:`Total Tokens`,totalSessions:`Total Sessions`,totalApiCalls:`Total API Calls`,callTypeNonStream:`Normal`,callTypeStream:`Stream`,callTypeReflection:`Reflection`,callTypeToolReflection:`Tool Reflection`,callTypeSubtaskReflection:`Subtask Reflection`,tabTrend:`Trend`,tabDistribution:`Distribution`,tabGlobal:`Global`,topCardSessionTokens:`Session Tokens`,topCardSessionCalls:`Session Calls`,topCardContextPeak:`Context Peak`,sparklineTitle:`Last 20 Calls Trend`,distPromptVsCompletion:`Prompt / Completion Ratio`,distPrompt:`Prompt`,distCompletion:`Completion`,distByModel:`By Model`,distByCallType:`By Call Type`,distNoData:`No distribution data`,globalSparklineTitle:`Last 30 Days Trend`,globalNoDailyData:`No data in selected range`,globalTotalTokens:`Total Tokens`,globalTotalSessions:`Total Sessions`,globalTotalApiCalls:`Total API Calls`}});function wm(e,n){let i=document.getElementById(`tokenStatsOverlay`),a=document.getElementById(`tokenStatsClose`),o=document.getElementById(`tokenStatsRefreshBtn`),s=document.getElementById(`tokenStatsClearBtn`),c=document.getElementById(`tokenStatsTabNav`),l=document.getElementById(`tokenStatsTopCards`);if(!i)return;let u=`trend`,d=`month`;function f(){i.style.display=`flex`,h()}function p(){i.style.display=`none`}if(window.openTokenStats=f,a&&a.addEventListener(`click`,p),i&&i.addEventListener(`click`,e=>{e.target===i&&p()}),o&&o.addEventListener(`click`,h),s&&s.addEventListener(`click`,async()=>{await n(t(`tokenStats.clearConfirmMessage`),t(`toolStats.clearTitle`))&&(await ge(),h())}),c){c.addEventListener(`click`,e=>{let t=e.target.closest(`.token-tab-btn`);if(!t)return;let n=t.dataset.tab;if(n===u)return;c.querySelectorAll(`.token-tab-btn`).forEach(e=>{e.classList.remove(`active`),e.style.borderBottomColor=`transparent`,e.style.color=`var(--text-secondary)`}),t.classList.add(`active`),t.style.borderBottomColor=`var(--brand-500)`,t.style.color=`var(--brand-500)`,document.querySelectorAll(`.token-tab-content`).forEach(e=>{e.style.display=`none`});let r=document.getElementById(`tokenTab${n.charAt(0).toUpperCase()+n.slice(1)}`);r&&(r.style.display=n===`global`?`flex`:``),u=n});let e=c.querySelector(`.token-tab-btn.active`);e&&(e.style.borderBottomColor=`var(--brand-500)`,e.style.color=`var(--brand-500)`)}let m=document.querySelectorAll(`.token-time-range-btn`);m.forEach(e=>{e.addEventListener(`click`,()=>{let t=e.dataset.range;t!==d&&(d=t,m.forEach(e=>{e.classList.remove(`active`),e.style.border=`1px solid var(--border-default)`,e.style.background=`var(--bg-surface)`,e.style.color=`var(--text-secondary)`}),e.classList.add(`active`),e.style.border=`1px solid var(--brand-500)`,e.style.background=`var(--brand-500)`,e.style.color=`var(--text-on-brand)`,b())})});async function h(){let n=e(),i=document.getElementById(`tokenStatsLoading`),a=document.getElementById(`tokenStatsEmpty`),o=document.getElementById(`tokenStatsContent`);i&&(i.style.display=``),a&&(a.style.display=`none`),o&&(o.style.display=`none`),c&&(c.style.display=`none`),l&&(l.style.display=`none`);try{let[e,t]=await Promise.all([Me(n),Ne()]);if(i&&(i.style.display=`none`),!(t&&t.totalApiCalls>0)){a&&(a.style.display=``);return}o&&(o.style.display=``),c&&(c.style.display=`flex`),l&&(l.style.display=``),g(e),ee(e),ie(e.records||[]),v(t),b()}catch(e){r.error(`[TokenStats] load stats failed:`,e),i&&(i.style.display=`none`),a&&(a.textContent=t(`tokenStats.loadFailed`),a.style.display=``)}}function g(e){if(!l)return;if(!e||e.apiCallCount===0){l.innerHTML=``;return}let n=e.maxContextUsageRate||0,r=C(n);l.innerHTML=`
474
+ `,document.body.appendChild(Q),Q.querySelector(`.sap-close`).addEventListener(`click`,cm),Q.querySelector(`.sap-lock`).addEventListener(`click`,nm),Q.querySelector(`.sap-copy`).addEventListener(`click`,fm),Q.querySelector(`.sap-transfer`).addEventListener(`click`,pm),Q.querySelector(`.sap-regen`).addEventListener(`click`,()=>{Wp&&Gp&&hm()}),dm(Q.querySelector(`.sap-header`)),Q)}function em(){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`),tm()}function tm(){if(!Q)return;let e=Q.querySelector(`.sap-lock`);e&&(e.classList.toggle(`locked`,Yp),e.title=t(Yp?`sidePanel.popupUnlock`:`sidePanel.popupLock`),e.innerHTML=Yp?`<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 nm(){Yp=!Yp,tm()}function rm(e,t){let n=$p(),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 im(e){let n=$p();em(),n.querySelector(`.sap-title`).textContent=e||t(`sidePanel.popupTitle`),n.querySelector(`.sap-body`).innerHTML=`<div class="sap-loading">${j(t(`sidePanel.popupLoading`))}</div>`,n.classList.add(`show`),Q.style.display=`block`}function am(){return!!Q&&Q.classList.contains(`show`)}function om(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 sm(e){let t=Q?.querySelector(`.sap-body`);t&&(t.innerHTML=`<div class="sap-error">${j(e)}</div>`)}function cm(){Jp&&Hp&&chrome.runtime.sendMessage({type:`CANCEL_REACT`,sessionId:Hp}).catch(()=>{}),Q&&(Q.classList.remove(`show`),Q.style.display=`none`),Hp=null,Up=``,Jp=!1,Yp=!1}function lm(e){if(!am()||Yp||Q.contains(e.target))return;let t=document.getElementById(`selectionFloatingMenu`);t&&t.contains(e.target)||cm()}function um(e){e.key===`Escape`&&(!am()||Yp||cm())}function dm(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 fm(){Up&&navigator.clipboard.writeText(Up).then(()=>{A(t(`sidePanel.popupCopied`))}).catch(()=>{let e=document.createElement(`textarea`);e.value=Up,document.body.appendChild(e),e.select(),document.execCommand(`copy`),document.body.removeChild(e),A(t(`sidePanel.popupCopied`))})}function pm(){if(!Up||!Wp)return;On()&&Xr();let e=Up,n=Wp.content,r=`${Kp?`[${t(`sidePanel.popupContextLabel`)}]\n${Kp}\n\n`:``}[${t(`sidePanel.selectedContentLabel`)}]\n${Gp}\n\n[${t(`sidePanel.userQuestionLabel`)}]\n${Wp.content}`;E(async()=>{let{addMessage:e}=await import(`./context-indicator-C9mzVLvn.js`).then(e=>e.V);return{addMessage:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8])).then(({addMessage:i})=>{i(`user`,n,!0,[],null,!1,r),v.messageHistory.push({role:`user`,content:r,timestamp:new Date().toISOString()}),i(`assistant`,e,!0),v.messageHistory.push({role:`assistant`,content:e}),E(async()=>{let{saveCurrentSession:e}=await import(`./context-indicator-C9mzVLvn.js`).then(e=>e.Sr);return{saveCurrentSession:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8])).then(({saveCurrentSession:e})=>{e()}),Promise.all([E(()=>import(`./context-indicator-C9mzVLvn.js`).then(e=>e.pt),__vite__mapDeps([0,1,2,3,4,5,6,7,8])),new Promise(e=>requestAnimationFrame(e))]).then(([{autoScrollToBottom:e}])=>{e(document.getElementById(`chatContainer`),{force:!0,smooth:!0}),A(t(`sidePanel.popupTransferred`))})}),cm()}function mm(e,t,n){let{context:r,truncated:i}=Zp(n,t);Wp=e,Gp=t,Kp=r,qp=i,hm()}function hm(){Up=``,Jp=!0,im(Wp?.content);let e=Qp(Gp,Kp,Wp.content,qp);Hp=`popup_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,chrome.runtime.sendMessage({type:`SIDEPANEL_POPUP_ASK`,sessionId:Hp,messages:e}).catch(e=>{r.error(`[SelectionPopup] sendMessage failed:`,e),sm(t(`sidePanel.popupRequestFailed`)),Jp=!1})}var gm=!1;function _m(){gm||(gm=!0,chrome.runtime.onMessage.addListener(e=>{if(!(!e||!e.type)&&e.type.startsWith(`SIDEPANEL_POPUP_`)&&e.sessionId===Hp){if(e.type===`SIDEPANEL_POPUP_STREAM_CHUNK`)e.delta&&(Up+=e.delta,om(lt(Up)));else if(e.type===`SIDEPANEL_POPUP_STREAM_DONE`)Jp=!1,e.finalContent&&(Up=e.finalContent),om(lt(Up));else if(e.type===`SIDEPANEL_POPUP_STREAM_ERROR`){if(!Jp)return;Jp=!1,sm(e.error||t(`sidePanel.popupRequestFailed`))}}}))}function vm(){_m(),document.addEventListener(`mousedown`,lm),document.addEventListener(`keydown`,um)}function ym(e,t,n,r,i){!t||!e||(_m(),rm(n,r),Yp=!1,mm(e,t,i||v.currentSelectionRange))}e(`zh`,{tokenStats:{clearConfirmMessage:`确定要清空所有 Token 使用统计吗?此操作不可撤销。`,loadFailed:`加载失败`,currentSessionNoData:`当前会话暂无数据`,totalTokenUsage:`总 Token 消耗`,apiCallCount:`API 调用次数`,contextUsageRate:`上下文使用率`,max:`最大`,avg:`平均`,min:`最小`,totalTokens:`总 Token`,totalSessions:`总会话数`,totalApiCalls:`总 API 调用`,callTypeNonStream:`普通`,callTypeStream:`流式`,callTypeReflection:`反思`,callTypeToolReflection:`工具反思`,callTypeSubtaskReflection:`子任务反思`,tabTrend:`趋势`,tabDistribution:`分布`,tabGlobal:`全局`,topCardSessionTokens:`本次 Token`,topCardSessionCalls:`本次调用`,topCardContextPeak:`上下文峰值`,sparklineTitle:`最近 20 次调用趋势`,distPromptVsCompletion:`Prompt / Completion 占比`,distPrompt:`Prompt`,distCompletion:`Completion`,distByModel:`按模型分布`,distByCallType:`按调用类型分布`,distNoData:`暂无分布数据`,globalSparklineTitle:`最近 30 天趋势`,globalNoDailyData:`所选范围内暂无数据`,globalTotalTokens:`总 Token`,globalTotalSessions:`总会话数`,globalTotalApiCalls:`总 API 调用`}}),e(`en`,{tokenStats:{clearConfirmMessage:`Are you sure you want to clear all Token usage statistics? This action cannot be undone.`,loadFailed:`Load failed`,currentSessionNoData:`No data for current session`,totalTokenUsage:`Total Token Usage`,apiCallCount:`API Call Count`,contextUsageRate:`Context Usage Rate`,max:`Max`,avg:`Avg`,min:`Min`,totalTokens:`Total Tokens`,totalSessions:`Total Sessions`,totalApiCalls:`Total API Calls`,callTypeNonStream:`Normal`,callTypeStream:`Stream`,callTypeReflection:`Reflection`,callTypeToolReflection:`Tool Reflection`,callTypeSubtaskReflection:`Subtask Reflection`,tabTrend:`Trend`,tabDistribution:`Distribution`,tabGlobal:`Global`,topCardSessionTokens:`Session Tokens`,topCardSessionCalls:`Session Calls`,topCardContextPeak:`Context Peak`,sparklineTitle:`Last 20 Calls Trend`,distPromptVsCompletion:`Prompt / Completion Ratio`,distPrompt:`Prompt`,distCompletion:`Completion`,distByModel:`By Model`,distByCallType:`By Call Type`,distNoData:`No distribution data`,globalSparklineTitle:`Last 30 Days Trend`,globalNoDailyData:`No data in selected range`,globalTotalTokens:`Total Tokens`,globalTotalSessions:`Total Sessions`,globalTotalApiCalls:`Total API Calls`}});function bm(e,n){let i=document.getElementById(`tokenStatsOverlay`),a=document.getElementById(`tokenStatsClose`),o=document.getElementById(`tokenStatsRefreshBtn`),s=document.getElementById(`tokenStatsClearBtn`),c=document.getElementById(`tokenStatsTabNav`),l=document.getElementById(`tokenStatsTopCards`);if(!i)return;let u=`trend`,d=`month`;function f(){i.style.display=`flex`,h()}function p(){i.style.display=`none`}if(window.openTokenStats=f,a&&a.addEventListener(`click`,p),i&&i.addEventListener(`click`,e=>{e.target===i&&p()}),o&&o.addEventListener(`click`,h),s&&s.addEventListener(`click`,async()=>{await n(t(`tokenStats.clearConfirmMessage`),t(`toolStats.clearTitle`))&&(await he(),h())}),c){c.addEventListener(`click`,e=>{let t=e.target.closest(`.token-tab-btn`);if(!t)return;let n=t.dataset.tab;if(n===u)return;c.querySelectorAll(`.token-tab-btn`).forEach(e=>{e.classList.remove(`active`),e.style.borderBottomColor=`transparent`,e.style.color=`var(--text-secondary)`}),t.classList.add(`active`),t.style.borderBottomColor=`var(--brand-500)`,t.style.color=`var(--brand-500)`,document.querySelectorAll(`.token-tab-content`).forEach(e=>{e.style.display=`none`});let r=document.getElementById(`tokenTab${n.charAt(0).toUpperCase()+n.slice(1)}`);r&&(r.style.display=n===`global`?`flex`:``),u=n});let e=c.querySelector(`.token-tab-btn.active`);e&&(e.style.borderBottomColor=`var(--brand-500)`,e.style.color=`var(--brand-500)`)}let m=document.querySelectorAll(`.token-time-range-btn`);m.forEach(e=>{e.addEventListener(`click`,()=>{let t=e.dataset.range;t!==d&&(d=t,m.forEach(e=>{e.classList.remove(`active`),e.style.border=`1px solid var(--border-default)`,e.style.background=`var(--bg-surface)`,e.style.color=`var(--text-secondary)`}),e.classList.add(`active`),e.style.border=`1px solid var(--brand-500)`,e.style.background=`var(--brand-500)`,e.style.color=`var(--text-on-brand)`,b())})});async function h(){let n=e(),i=document.getElementById(`tokenStatsLoading`),a=document.getElementById(`tokenStatsEmpty`),o=document.getElementById(`tokenStatsContent`);i&&(i.style.display=``),a&&(a.style.display=`none`),o&&(o.style.display=`none`),c&&(c.style.display=`none`),l&&(l.style.display=`none`);try{let[e,t]=await Promise.all([je(n),Me()]);if(i&&(i.style.display=`none`),!(t&&t.totalApiCalls>0)){a&&(a.style.display=``);return}o&&(o.style.display=``),c&&(c.style.display=`flex`),l&&(l.style.display=``),g(e),ee(e),ie(e.records||[]),v(t),b()}catch(e){r.error(`[TokenStats] load stats failed:`,e),i&&(i.style.display=`none`),a&&(a.textContent=t(`tokenStats.loadFailed`),a.style.display=``)}}function g(e){if(!l)return;if(!e||e.apiCallCount===0){l.innerHTML=``;return}let n=e.maxContextUsageRate||0,r=C(n);l.innerHTML=`
475
475
  <div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 8px;">
476
476
  <div style="background: var(--brand-soft-bg); border-radius: 8px; padding: 10px; text-align: center;">
477
477
  <div style="font-size: 10px; color: var(--text-tertiary); margin-bottom: 4px;">${t(`tokenStats.topCardSessionTokens`)}</div>
@@ -520,7 +520,7 @@ import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-DvmxOw8q.js"
520
520
  <span>${t(`tokenStats.min`)}</span>
521
521
  <span>${t(`tokenStats.avg`)}</span>
522
522
  <span>${t(`tokenStats.max`)}</span>
523
- </div>`}function _(e){return{react_loop:`ReAct`,non_stream:t(`tokenStats.callTypeNonStream`),stream:t(`tokenStats.callTypeStream`),reflection:t(`tokenStats.callTypeReflection`),tool_reflection:t(`tokenStats.callTypeToolReflection`),subtask_reflection:t(`tokenStats.callTypeSubtaskReflection`),unknown:`-`}[e]||e}async function v(e){let n=document.getElementById(`tokenDistributionStats`);if(n)try{let[r,i]=await Promise.all([ye(),ve()]),a=e?.totalPromptTokens||0,o=e?.totalCompletionTokens||0;if(a+o===0&&r.length===0){n.innerHTML=`<div style="text-align:center;color:var(--text-tertiary);padding:20px;">${t(`tokenStats.distNoData`)}</div>`;return}n.innerHTML=`
523
+ </div>`}function _(e){return{react_loop:`ReAct`,non_stream:t(`tokenStats.callTypeNonStream`),stream:t(`tokenStats.callTypeStream`),reflection:t(`tokenStats.callTypeReflection`),tool_reflection:t(`tokenStats.callTypeToolReflection`),subtask_reflection:t(`tokenStats.callTypeSubtaskReflection`),unknown:`-`}[e]||e}async function v(e){let n=document.getElementById(`tokenDistributionStats`);if(n)try{let[r,i]=await Promise.all([ve(),_e()]),a=e?.totalPromptTokens||0,o=e?.totalCompletionTokens||0;if(a+o===0&&r.length===0){n.innerHTML=`<div style="text-align:center;color:var(--text-tertiary);padding:20px;">${t(`tokenStats.distNoData`)}</div>`;return}n.innerHTML=`
524
524
  <div style="margin-bottom:16px;">
525
525
  <div style="font-size:12px;font-weight:600;color:var(--text-secondary);margin-bottom:8px;">${t(`tokenStats.distPromptVsCompletion`)}</div>
526
526
  ${re(a,o)}
@@ -548,13 +548,13 @@ import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-DvmxOw8q.js"
548
548
  </span>
549
549
  </div>`}function y(e,n){if(!e||e.length===0)return`<div style="text-align:center;color:var(--text-tertiary);font-size:11px;padding:8px;">${t(`tokenStats.distNoData`)}</div>`;let r=Math.max(...e.map(e=>e.value||0),1);return e.map(e=>{let t=e.value/r*100;return`<div style="margin-bottom:8px;">
550
550
  <div style="display:flex;justify-content:space-between;font-size:11px;color:var(--text-secondary);margin-bottom:3px;">
551
- <span style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:60%;">${A(e.label)}</span>
551
+ <span style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:60%;">${j(e.label)}</span>
552
552
  <span style="color:var(--text-tertiary);">${S(e.value)} · ${(e.percentage||0).toFixed(1)}%</span>
553
553
  </div>
554
554
  <div style="height:8px;background:var(--border-subtle);border-radius:4px;overflow:hidden;">
555
555
  <div style="height:100%;width:${t}%;background:${n};border-radius:4px;"></div>
556
556
  </div>
557
- </div>`}).join(``)}async function b(){let e=document.getElementById(`tokenGlobalSparkline`),n=document.getElementById(`tokenOverallStats`);if(!e||!n)return;let i=new Date,a=i.toISOString(),o,s;d===`today`?(o=new Date(i.getFullYear(),i.getMonth(),i.getDate()).toISOString(),s=1):d===`week`?(o=new Date(i.getTime()-10080*60*1e3).toISOString(),s=7):d===`month`?(o=new Date(i.getTime()-720*60*60*1e3).toISOString(),s=30):(o=new Date(0).toISOString(),s=365);try{let[r,i]=await Promise.all([be(s),me(o,a)]);if(e.innerHTML=x(r),!i||i.totalApiCalls===0){n.innerHTML=`<div style="text-align:center;color:var(--text-tertiary);padding:16px;font-size:12px;">${t(`tokenStats.globalNoDailyData`)}</div>`;return}n.innerHTML=`
557
+ </div>`}).join(``)}async function b(){let e=document.getElementById(`tokenGlobalSparkline`),n=document.getElementById(`tokenOverallStats`);if(!e||!n)return;let i=new Date,a=i.toISOString(),o,s;d===`today`?(o=new Date(i.getFullYear(),i.getMonth(),i.getDate()).toISOString(),s=1):d===`week`?(o=new Date(i.getTime()-10080*60*1e3).toISOString(),s=7):d===`month`?(o=new Date(i.getTime()-720*60*60*1e3).toISOString(),s=30):(o=new Date(0).toISOString(),s=365);try{let[r,i]=await Promise.all([ye(s),pe(o,a)]);if(e.innerHTML=x(r),!i||i.totalApiCalls===0){n.innerHTML=`<div style="text-align:center;color:var(--text-tertiary);padding:16px;font-size:12px;">${t(`tokenStats.globalNoDailyData`)}</div>`;return}n.innerHTML=`
558
558
  <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:8px;">
559
559
  <div style="background:var(--warning-soft-bg);border-radius:8px;padding:10px;text-align:center;">
560
560
  <div style="font-size:10px;color:var(--text-tertiary);">${t(`tokenStats.globalTotalTokens`)}</div>
@@ -579,10 +579,10 @@ import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-DvmxOw8q.js"
579
579
  <div style="height:100%;width:${a}%;background:${o};"></div>
580
580
  </div>
581
581
  <span style="color:var(--text-secondary);width:55px;">${r}</span>
582
- <span style="background:var(--bg-subtle);padding:1px 5px;border-radius:3px;font-size:9px;color:var(--text-secondary);">${A(i)}</span>
582
+ <span style="background:var(--bg-subtle);padding:1px 5px;border-radius:3px;font-size:9px;color:var(--text-secondary);">${j(i)}</span>
583
583
  <span style="font-weight:500;color:var(--text-primary);margin-left:auto;">${S(e.totalTokens)}</span>
584
584
  <span style="color:${o};font-size:9px;font-weight:500;width:35px;text-align:right;">${((e.contextUsageRate||0)*100).toFixed(1)}%</span>
585
- </div>`}).join(``)}function S(e){return e>=1e6?(e/1e6).toFixed(1)+`M`:e>=1e3?(e/1e3).toFixed(1)+`K`:String(e)}function C(e){return e>=.8?`#ef4444`:e>=.5?`#f59e0b`:`#10b981`}}function Tm(e){return(e||[]).map(e=>e.token?{...e,token:ue(e.token)}:e)}e(`zh`,{sidePanel:{confirmAction:`确认操作`,memoryLimitAll:`全`,memoryLimitTitle:`点击设置记忆历史限制条数`,configUpdated:`✅ 配置已更新`,selectedPrefix:`📌 已选中`,askBasedOnSelection:`基于选中内容提问`,copySelectionTooltip:`复制选中内容`,copySelectionDone:`已复制选中内容`,selectedContentLabel:`选中内容`,selectedContentSummary:`摘要`,userQuestionLabel:`用户问题`,requestFailed:`❌ 请求失败:`,unknownError:`未知错误`,notConnected:`未连接`,noPairedAgents:`暂无已配对代理`,agentDisabled:`已停用`,agentConnected:`已连接`,agentChecking:`检测中...`,agentOnline:`在线`,agentOffline:`离线`,enableAgent:`启用`,disableAgent:`停用`,disconnectAgent:`断开`,connectAgent:`连接`,deleteAgentBtn:`删除`,workingDirectory:`工作目录: {path}`,agentAddressCopied:`已复制代理地址`,unknownAgent:`未知`,restartAgentConfirm:`代理名称:{name}
585
+ </div>`}).join(``)}function S(e){return e>=1e6?(e/1e6).toFixed(1)+`M`:e>=1e3?(e/1e3).toFixed(1)+`K`:String(e)}function C(e){return e>=.8?`#ef4444`:e>=.5?`#f59e0b`:`#10b981`}}function xm(e){return(e||[]).map(e=>e.token?{...e,token:le(e.token)}:e)}e(`zh`,{sidePanel:{confirmAction:`确认操作`,memoryLimitAll:`全`,memoryLimitTitle:`点击设置记忆历史限制条数`,configUpdated:`✅ 配置已更新`,selectedPrefix:`📌 已选中`,askBasedOnSelection:`基于选中内容提问`,copySelectionTooltip:`复制选中内容`,copySelectionDone:`已复制选中内容`,selectedContentLabel:`选中内容`,selectedContentSummary:`摘要`,userQuestionLabel:`用户问题`,requestFailed:`❌ 请求失败:`,unknownError:`未知错误`,notConnected:`未连接`,noPairedAgents:`暂无已配对代理`,agentDisabled:`已停用`,agentConnected:`已连接`,agentChecking:`检测中...`,agentOnline:`在线`,agentOffline:`离线`,enableAgent:`启用`,disableAgent:`停用`,disconnectAgent:`断开`,connectAgent:`连接`,deleteAgentBtn:`删除`,workingDirectory:`工作目录: {path}`,agentAddressCopied:`已复制代理地址`,unknownAgent:`未知`,restartAgentConfirm:`代理名称:{name}
586
586
  代理地址:{url}
587
587
 
588
588
  确定要重启代理服务吗?重启期间服务将短暂不可用。`,restartAgentTitle:`重启代理`,agentRestarting:`代理服务正在重启...`,restartFailed:`重启失败: {error}`,restartRequestFailed:`重启请求失败: {error}`,updateAgentConfirm:`代理名称:{name}
@@ -600,16 +600,16 @@ Agent address: {url}
600
600
  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}
601
601
  Agent address: {url}
602
602
 
603
- Are you sure you want to stop the agent service? You will not be able to connect and will need to manually restart it.`,stopAgentTitle:`Stop Agent`,agentStopped:`Agent service stopped, agent is offline`,stopFailed:`Stop failed: {error}`,stopRequestFailed:`Stop request failed: {error}`,agentStatusRefreshed:`Agent status refreshed`,deleteAgentTitle:`Delete Agent`,deleteAgentConfirm:`Are you sure you want to delete agent "{name}"? This action cannot be undone.`,welcomeTitle:`Start a Conversation`,welcomeSubtitle:`Enter your question and the AI assistant will help you`,sendBtnStop:`Stop generating`,sendBtnSend:`Send`,defaultPromptImage:`Please look at the attached image and describe what you see`,defaultPromptFile:`Please read the attached file and summarize the key points`,defaultPromptAttachments:`Please review the attached image and file and summarize the key points`,defaultPromptKnowledge:`Please answer based on the knowledge base content I referenced`,defaultKnowledgeQuery:`key points summary`,defaultPromptPage:`Please summarize the main content of this page`,defaultPromptSelection:`Please continue based on the content I provided`,defaultPromptContext:`Please continue based on the context I provided`,imageNotEnabled:`Image recognition not enabled, image attached as file`,screenshotFailed:`Screenshot failed, please retry`,auditCategoryAuth:`Auth`,auditCategoryFs:`File`,auditCategoryExec:`Command`,auditCategorySecurity:`Security`,auditCategorySystem:`System`,auditDetailSeparator:`; `,auditQueryFailed:`Query failed: {error}`,auditLoadFailed:`Load failed: {error}`,auditNoMatch:`No matching audit logs`,auditEmpty:`No audit logs`,clearStatsConfirm:`Are you sure you want to clear all tool usage stats? This action cannot be undone.`,clearStatsTitle:`Clear Stats`,toolStatsSummary:`Used {used} tools, unused {unused} tools`,toolStatsLoadFailed:`Load failed`,toolNameDescSeparator:`: `}}),window.showCustomConfirm=function(e,n=t(`sidePanel.confirmAction`)){return new Promise(t=>{let r=document.getElementById(`customConfirmOverlay`),i=document.getElementById(`customConfirmTitle`),a=document.getElementById(`customConfirmMessage`),o=document.getElementById(`customConfirmCancelBtn`),s=document.getElementById(`customConfirmOkBtn`);if(!r||!i||!a||!o||!s){t(confirm(e));return}let c=()=>{r.style.display=`none`,s.removeEventListener(`click`,l),o.removeEventListener(`click`,u),r.removeEventListener(`click`,d),document.removeEventListener(`keydown`,f)},l=()=>{c(),t(!0)},u=()=>{c(),t(!1)},d=e=>{e.target===r&&(c(),t(!1))},f=e=>{e.key===`Enter`?(e.preventDefault(),e.stopPropagation(),l()):e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),u())};i.textContent=n,a.innerHTML=e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`).replace(/'/g,`&#39;`).replace(/\n/g,`<br>`),r.style.display=`flex`,s.addEventListener(`click`,l),o.addEventListener(`click`,u),r.addEventListener(`click`,d),document.addEventListener(`keydown`,f),requestAnimationFrame(()=>s.focus())})},chrome.storage.onChanged.addListener((e,t)=>{t===`local`&&e.chatAutoCompaction&&(v.chatConfig.autoCompaction=e.chatAutoCompaction.newValue===!0,Dm(),r.debug(`[SidePanel] auto-compaction config updated:`,v.chatConfig.autoCompaction)),t===`local`&&e.chatPersistSummaryToMemory&&(v.chatConfig.persistSummaryToMemory=e.chatPersistSummaryToMemory.newValue!==!1,Om(),r.debug(`[SidePanel] persist-summary config updated:`,v.chatConfig.persistSummaryToMemory)),t===`local`&&e.chatMaxMemoryMessages&&(v.chatConfig.maxMemoryMessages=e.chatMaxMemoryMessages.newValue,Em(),r.debug(`[SidePanel] memory limitconfiguration updated:`,v.chatConfig.maxMemoryMessages)),t===`local`&&e.queueAutoCarry&&(v.chatConfig.queueAutoCarry=e.queueAutoCarry.newValue!==!1,r.debug(`[SidePanel] queue auto-carry updated:`,v.chatConfig.queueAutoCarry)),t===`local`&&e.queueAutoCarryEveryNIterations&&(v.chatConfig.queueAutoCarryEveryNIterations=e.queueAutoCarryEveryNIterations.newValue,r.debug(`[SidePanel] queue auto-carry interval updated:`,v.chatConfig.queueAutoCarryEveryNIterations))});function Em(){let e=document.getElementById(`memoryLimitLabel`);e&&(v.chatConfig.maxMemoryMessages!==null&&v.chatConfig.maxMemoryMessages!==void 0&&v.chatConfig.maxMemoryMessages>0?e.textContent=v.chatConfig.maxMemoryMessages:e.textContent=t(`sidePanel.memoryLimitAll`),e.title=t(`sidePanel.memoryLimitTitle`))}function Dm(){let e=document.getElementById(`autoCompactBtn`);e&&(e.checked=v.chatConfig.autoCompaction===!0)}function Om(){let e=document.getElementById(`persistSummaryBtn`);e&&(e.checked=v.chatConfig.persistSummaryToMemory!==!1)}function km(e){e.preventDefault(),e.stopPropagation();let t=document.getElementById(`memoryLimitDropdown`);if(t.classList.toggle(`show`),t.classList.contains(`show`)){let e=v.chatConfig.maxMemoryMessages;t.querySelectorAll(`.memory-limit-option`).forEach(t=>{t.classList.remove(`selected`);let n=parseInt(t.dataset.value);(e===null&&n===0||e!==null&&e>0&&n===e)&&t.classList.add(`selected`)});let n=t.querySelector(`#memoryLimitInput`);e!==null&&e>0?n.value=e:n.value=``}}function Am(){let e=document.getElementById(`memoryLimitDropdown`),n=document.getElementById(`memoryLimitLabel`),r=e?.querySelector(`#memoryLimitInput`);if(!e||!n)return;Em(),n.addEventListener(`click`,km);let i=document.getElementById(`autoCompactBtn`);i&&(i.checked=v.chatConfig.autoCompaction===!0,i.addEventListener(`change`,()=>{let e=i.checked;chrome.storage.local.set({chatAutoCompaction:e},()=>{v.chatConfig.autoCompaction=e,k(t(`sidePanel.configUpdated`),`success`)})}));let a=document.getElementById(`persistSummaryBtn`);a&&(a.checked=v.chatConfig.persistSummaryToMemory!==!1,a.addEventListener(`change`,()=>{let e=a.checked;chrome.storage.local.set({chatPersistSummaryToMemory:e},()=>{v.chatConfig.persistSummaryToMemory=e,k(t(`sidePanel.configUpdated`),`success`)})}));let o=e.querySelectorAll(`.memory-limit-option`);o.forEach(e=>{e.addEventListener(`click`,n=>{n.stopPropagation();let i=parseInt(e.dataset.value),a=i===0?null:i;o.forEach(e=>e.classList.remove(`selected`)),e.classList.add(`selected`),r&&(r.value=i===0?``:i),chrome.storage.local.set({chatMaxMemoryMessages:a},()=>{v.chatConfig.maxMemoryMessages=a,Em(),k(t(`sidePanel.configUpdated`),`success`)})})}),r&&(r.addEventListener(`click`,e=>e.stopPropagation()),r.addEventListener(`mousedown`,e=>e.stopPropagation()),r.addEventListener(`change`,e=>{e.stopPropagation();let n=e.target.value.trim(),r=n&&parseInt(n)>0?parseInt(n):null;o.forEach(e=>e.classList.remove(`selected`)),chrome.storage.local.set({chatMaxMemoryMessages:r},()=>{v.chatConfig.maxMemoryMessages=r,Em(),k(t(`sidePanel.configUpdated`),`success`)})})),document.getElementById(`memoryLimitConfigEntry`)?.addEventListener(`click`,()=>{chrome.runtime.sendMessage({type:`OPEN_OPTIONS_PAGE`,hash:`memory`})}),document.addEventListener(`click`,t=>{!e.contains(t.target)&&t.target!==n&&e.classList.remove(`show`)})}async function jm(e){if(v.activeAgentId&&v.activeAgentId!=="default")try{let{updateAgent:t}=await T(async()=>{let{updateAgent:e}=await import(`./agent-store-CE4-QMOA.js`).then(e=>e.t);return{updateAgent:e}},__vite__mapDeps([7,1,2,3]));await t(v.activeAgentId,{model:e})}catch{}else chrome.storage.local.set({modelName:e}),de(e)}async function Mm(){try{let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),t=Tm(e.pairedAgents),n=e.activeAgentId,r=t.find(e=>e.id===n&&!e.disabled);if(!r){v.agentPlatform={connected:!1},$(v.agentPlatform);return}if(r.token)try{let e=await fetch(`${r.url}/api/status/detail`,{cache:`no-cache`,headers:{Authorization:`Bearer ${r.token}`}});if(e.ok){let t=await e.json();if(t.success){v.agentPlatform={platformName:t.platformName||`Unknown`,platform:t.platform||`unknown`,arch:t.arch||`unknown`,shell:t.shell||`/bin/sh`,homeDir:t.homeDir||``,workdir:t.workdir||``,connected:!0},t.version&&v.agentVersions.set(n,t.version),t.workdir&&v.agentWorkdirs.set(n,t.workdir),t.homeDir&&v.agentHomeDirs.set(n,t.homeDir);let e=ch(t.platformName||t.platform,t.arch);e&&v.agentSystemInfos.set(n,e)}else v.agentPlatform={connected:!1}}else v.agentPlatform={connected:!1}}catch{v.agentPlatform={connected:!1}}else v.agentPlatform={connected:!1};$(v.agentPlatform),Ur()}catch{}}async function Nm(e,t,n){if(v.activeAgentId&&v.activeAgentId!=="default")try{let{updateAgent:n}=await T(async()=>{let{updateAgent:e}=await import(`./agent-store-CE4-QMOA.js`).then(e=>e.t);return{updateAgent:e}},__vite__mapDeps([7,1,2,3]));await n(v.activeAgentId,{temperature:e,topP:t})}catch{}else chrome.storage.local.set({temperature:e,topP:t,selectedTempIndex:n})}function Pm(){let e=document.getElementById(`currentModelTag`);if(!e)return;let t=v.currentModel||``;e.textContent=t,e.title=t,e.style.display=t?``:`none`}var Fm=new Set,Im=0;function Lm(){let e=document.getElementById(`workdirTag`);e&&(e.dataset.locked=fr(v.activeSessionId)?`true`:`false`)}async function Rm(){let e=++Im,n=document.getElementById(`workdirTag`),i=document.getElementById(`workdirTagName`);if(!n||!i)return;let a=v.activeSessionId||null,o=Array.isArray(v.enabledTools)&&v.enabledTools.includes(`agent_exec`);if(v.agentPlatform?.connected!==!0||!o){n.style.display=`none`;return}let c=null;try{c=await p(a)}catch(e){r.debug(`[WorkdirTag] resolve failed:`,e&&e.message)}if(e!==Im)return;let l=c&&c.workdir||``;if(!l){n.style.display=`none`;return}n.style.display=``,i.textContent=s(l,{homeDir:v.agentPlatform?.homeDir||``}),Lm();try{let{getWorkspaceRoot:e}=await T(async()=>{let{getWorkspaceRoot:e}=await import(`./workspace-manager-D6xww21F.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`,Wp(a).then(e=>{e&&Rm()}).catch(e=>r.debug(`[WorkdirTag] reconcile failed:`,e&&e.message))):n.dataset.invalid=i?`true`:`false`}catch{n.dataset.invalid=`false`}if(e===Im&&(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||``}`;Fm.has(e)||(Fm.add(e),k(t(`workdirTag.agentSwitched`),`warning`))}}function zm(){let e=document.getElementById(`workdirTag`);e&&(e.setAttribute(`aria-label`,t(`workdirTag.tagHint`)),e.addEventListener(`click`,async e=>{if(e.stopPropagation(),fr(v.activeSessionId)){Lm(),k(t(`workdirTag.lockedHint`),`warning`);return}Lm();let{showSwitchWorkdirDialog:n}=await T(async()=>{let{showSwitchWorkdirDialog:e}=await import(`./context-indicator-BSGa1g7l.js`).then(e=>e.un);return{showSwitchWorkdirDialog:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]));await n({sessionId:v.activeSessionId||null})})),Rm(),document.addEventListener(`session-switched`,()=>{Rm()}),document.addEventListener(`session-workdir-changed`,()=>{Rm()}),document.addEventListener(`agent-model-changed`,()=>{Rm()}),document.addEventListener(`agent-tools-changed`,()=>{Rm()}),document.addEventListener(`generating-state-changed`,()=>{Lm()}),document.addEventListener(`generation-ended`,()=>{Lm()}),ra(()=>{Lm()})}function Bm(){let e=document.getElementById(`currentModelTag`);e&&e.addEventListener(`click`,e=>{e.stopPropagation(),document.getElementById(`tempDisplay`)?.click()}),Pm()}function Vm(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`),Pm()}function Hm(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=`
603
+ Are you sure you want to stop the agent service? You will not be able to connect and will need to manually restart it.`,stopAgentTitle:`Stop Agent`,agentStopped:`Agent service stopped, agent is offline`,stopFailed:`Stop failed: {error}`,stopRequestFailed:`Stop request failed: {error}`,agentStatusRefreshed:`Agent status refreshed`,deleteAgentTitle:`Delete Agent`,deleteAgentConfirm:`Are you sure you want to delete agent "{name}"? This action cannot be undone.`,welcomeTitle:`Start a Conversation`,welcomeSubtitle:`Enter your question and the AI assistant will help you`,sendBtnStop:`Stop generating`,sendBtnSend:`Send`,defaultPromptImage:`Please look at the attached image and describe what you see`,defaultPromptFile:`Please read the attached file and summarize the key points`,defaultPromptAttachments:`Please review the attached image and file and summarize the key points`,defaultPromptKnowledge:`Please answer based on the knowledge base content I referenced`,defaultKnowledgeQuery:`key points summary`,defaultPromptPage:`Please summarize the main content of this page`,defaultPromptSelection:`Please continue based on the content I provided`,defaultPromptContext:`Please continue based on the context I provided`,imageNotEnabled:`Image recognition not enabled, image attached as file`,screenshotFailed:`Screenshot failed, please retry`,auditCategoryAuth:`Auth`,auditCategoryFs:`File`,auditCategoryExec:`Command`,auditCategorySecurity:`Security`,auditCategorySystem:`System`,auditDetailSeparator:`; `,auditQueryFailed:`Query failed: {error}`,auditLoadFailed:`Load failed: {error}`,auditNoMatch:`No matching audit logs`,auditEmpty:`No audit logs`,clearStatsConfirm:`Are you sure you want to clear all tool usage stats? This action cannot be undone.`,clearStatsTitle:`Clear Stats`,toolStatsSummary:`Used {used} tools, unused {unused} tools`,toolStatsLoadFailed:`Load failed`,toolNameDescSeparator:`: `}}),window.showCustomConfirm=function(e,n=t(`sidePanel.confirmAction`)){return new Promise(t=>{let r=document.getElementById(`customConfirmOverlay`),i=document.getElementById(`customConfirmTitle`),a=document.getElementById(`customConfirmMessage`),o=document.getElementById(`customConfirmCancelBtn`),s=document.getElementById(`customConfirmOkBtn`);if(!r||!i||!a||!o||!s){t(confirm(e));return}let c=()=>{r.style.display=`none`,s.removeEventListener(`click`,l),o.removeEventListener(`click`,u),r.removeEventListener(`click`,d),document.removeEventListener(`keydown`,f)},l=()=>{c(),t(!0)},u=()=>{c(),t(!1)},d=e=>{e.target===r&&(c(),t(!1))},f=e=>{e.key===`Enter`?(e.preventDefault(),e.stopPropagation(),l()):e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),u())};i.textContent=n,a.innerHTML=e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`).replace(/'/g,`&#39;`).replace(/\n/g,`<br>`),r.style.display=`flex`,s.addEventListener(`click`,l),o.addEventListener(`click`,u),r.addEventListener(`click`,d),document.addEventListener(`keydown`,f),requestAnimationFrame(()=>s.focus())})},chrome.storage.onChanged.addListener((e,t)=>{t===`local`&&e.chatAutoCompaction&&(v.chatConfig.autoCompaction=e.chatAutoCompaction.newValue===!0,Cm(),r.debug(`[SidePanel] auto-compaction config updated:`,v.chatConfig.autoCompaction)),t===`local`&&e.chatPersistSummaryToMemory&&(v.chatConfig.persistSummaryToMemory=e.chatPersistSummaryToMemory.newValue!==!1,wm(),r.debug(`[SidePanel] persist-summary config updated:`,v.chatConfig.persistSummaryToMemory)),t===`local`&&e.chatMaxMemoryMessages&&(v.chatConfig.maxMemoryMessages=e.chatMaxMemoryMessages.newValue,Sm(),r.debug(`[SidePanel] memory limitconfiguration updated:`,v.chatConfig.maxMemoryMessages)),t===`local`&&e.queueAutoCarry&&(v.chatConfig.queueAutoCarry=e.queueAutoCarry.newValue!==!1,r.debug(`[SidePanel] queue auto-carry updated:`,v.chatConfig.queueAutoCarry)),t===`local`&&e.queueAutoCarryEveryNIterations&&(v.chatConfig.queueAutoCarryEveryNIterations=e.queueAutoCarryEveryNIterations.newValue,r.debug(`[SidePanel] queue auto-carry interval updated:`,v.chatConfig.queueAutoCarryEveryNIterations))});function Sm(){let e=document.getElementById(`memoryLimitLabel`);e&&(v.chatConfig.maxMemoryMessages!==null&&v.chatConfig.maxMemoryMessages!==void 0&&v.chatConfig.maxMemoryMessages>0?e.textContent=v.chatConfig.maxMemoryMessages:e.textContent=t(`sidePanel.memoryLimitAll`),e.title=t(`sidePanel.memoryLimitTitle`))}function Cm(){let e=document.getElementById(`autoCompactBtn`);e&&(e.checked=v.chatConfig.autoCompaction===!0)}function wm(){let e=document.getElementById(`persistSummaryBtn`);e&&(e.checked=v.chatConfig.persistSummaryToMemory!==!1)}function Tm(e){e.preventDefault(),e.stopPropagation();let t=document.getElementById(`memoryLimitDropdown`);if(t.classList.toggle(`show`),t.classList.contains(`show`)){let e=v.chatConfig.maxMemoryMessages;t.querySelectorAll(`.memory-limit-option`).forEach(t=>{t.classList.remove(`selected`);let n=parseInt(t.dataset.value);(e===null&&n===0||e!==null&&e>0&&n===e)&&t.classList.add(`selected`)});let n=t.querySelector(`#memoryLimitInput`);e!==null&&e>0?n.value=e:n.value=``}}function Em(){let e=document.getElementById(`memoryLimitDropdown`),n=document.getElementById(`memoryLimitLabel`),r=e?.querySelector(`#memoryLimitInput`);if(!e||!n)return;Sm(),n.addEventListener(`click`,Tm);let i=document.getElementById(`autoCompactBtn`);i&&(i.checked=v.chatConfig.autoCompaction===!0,i.addEventListener(`change`,()=>{let e=i.checked;chrome.storage.local.set({chatAutoCompaction:e},()=>{v.chatConfig.autoCompaction=e,A(t(`sidePanel.configUpdated`),`success`)})}));let a=document.getElementById(`persistSummaryBtn`);a&&(a.checked=v.chatConfig.persistSummaryToMemory!==!1,a.addEventListener(`change`,()=>{let e=a.checked;chrome.storage.local.set({chatPersistSummaryToMemory:e},()=>{v.chatConfig.persistSummaryToMemory=e,A(t(`sidePanel.configUpdated`),`success`)})}));let o=e.querySelectorAll(`.memory-limit-option`);o.forEach(e=>{e.addEventListener(`click`,n=>{n.stopPropagation();let i=parseInt(e.dataset.value),a=i===0?null:i;o.forEach(e=>e.classList.remove(`selected`)),e.classList.add(`selected`),r&&(r.value=i===0?``:i),chrome.storage.local.set({chatMaxMemoryMessages:a},()=>{v.chatConfig.maxMemoryMessages=a,Sm(),A(t(`sidePanel.configUpdated`),`success`)})})}),r&&(r.addEventListener(`click`,e=>e.stopPropagation()),r.addEventListener(`mousedown`,e=>e.stopPropagation()),r.addEventListener(`change`,e=>{e.stopPropagation();let n=e.target.value.trim(),r=n&&parseInt(n)>0?parseInt(n):null;o.forEach(e=>e.classList.remove(`selected`)),chrome.storage.local.set({chatMaxMemoryMessages:r},()=>{v.chatConfig.maxMemoryMessages=r,Sm(),A(t(`sidePanel.configUpdated`),`success`)})})),document.getElementById(`memoryLimitConfigEntry`)?.addEventListener(`click`,()=>{chrome.runtime.sendMessage({type:`OPEN_OPTIONS_PAGE`,hash:`memory`})}),document.addEventListener(`click`,t=>{!e.contains(t.target)&&t.target!==n&&e.classList.remove(`show`)})}async function Dm(e){if(v.activeAgentId&&v.activeAgentId!=="default")try{let{updateAgent:t}=await E(async()=>{let{updateAgent:e}=await import(`./agent-store-BirQwOYv.js`).then(e=>e.t);return{updateAgent:e}},__vite__mapDeps([7,1,2,3]));await t(v.activeAgentId,{model:e})}catch{}else chrome.storage.local.set({modelName:e}),ue(e)}async function Om(){try{let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),t=xm(e.pairedAgents),n=e.activeAgentId,r=t.find(e=>e.id===n&&!e.disabled);if(!r){v.agentPlatform={connected:!1},$(v.agentPlatform);return}if(r.token)try{let e=await fetch(`${r.url}/api/status/detail`,{cache:`no-cache`,headers:{Authorization:`Bearer ${r.token}`}});if(e.ok){let t=await e.json();if(t.success){v.agentPlatform={platformName:t.platformName||`Unknown`,platform:t.platform||`unknown`,arch:t.arch||`unknown`,shell:t.shell||`/bin/sh`,homeDir:t.homeDir||``,workdir:t.workdir||``,connected:!0},t.version&&v.agentVersions.set(n,t.version),t.workdir&&v.agentWorkdirs.set(n,t.workdir),t.homeDir&&v.agentHomeDirs.set(n,t.homeDir);let e=ih(t.platformName||t.platform,t.arch);e&&v.agentSystemInfos.set(n,e)}else v.agentPlatform={connected:!1}}else v.agentPlatform={connected:!1}}catch{v.agentPlatform={connected:!1}}else v.agentPlatform={connected:!1};$(v.agentPlatform),ai()}catch{}}async function km(e,t,n){if(v.activeAgentId&&v.activeAgentId!=="default")try{let{updateAgent:n}=await E(async()=>{let{updateAgent:e}=await import(`./agent-store-BirQwOYv.js`).then(e=>e.t);return{updateAgent:e}},__vite__mapDeps([7,1,2,3]));await n(v.activeAgentId,{temperature:e,topP:t})}catch{}else chrome.storage.local.set({temperature:e,topP:t,selectedTempIndex:n})}function Am(){let e=document.getElementById(`currentModelTag`);if(!e)return;let t=v.currentModel||``;e.textContent=t,e.title=t,e.style.display=t?``:`none`}var jm=new Set,Mm=0;function Nm(){let e=document.getElementById(`workdirTag`);e&&(e.dataset.locked=Ir(v.activeSessionId)?`true`:`false`)}async function Pm(){let e=++Mm,n=document.getElementById(`workdirTag`),i=document.getElementById(`workdirTagName`);if(!n||!i)return;let a=v.activeSessionId||null,o=Array.isArray(v.enabledTools)&&v.enabledTools.includes(`agent_exec`);if(v.agentPlatform?.connected!==!0||!o){n.style.display=`none`;return}let c=null;try{c=await p(a)}catch(e){r.debug(`[WorkdirTag] resolve failed:`,e&&e.message)}if(e!==Mm)return;let l=c&&c.workdir||``;if(!l){n.style.display=`none`;return}n.style.display=``,i.textContent=s(l,{homeDir:v.agentPlatform?.homeDir||``}),Nm();try{let{getWorkspaceRoot:e}=await E(async()=>{let{getWorkspaceRoot:e}=await import(`./workspace-manager-C6QooYXS.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`,Bp(a).then(e=>{e&&Pm()}).catch(e=>r.debug(`[WorkdirTag] reconcile failed:`,e&&e.message))):n.dataset.invalid=i?`true`:`false`}catch{n.dataset.invalid=`false`}if(e===Mm&&(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||``}`;jm.has(e)||(jm.add(e),A(t(`workdirTag.agentSwitched`),`warning`))}}function Fm(){let e=document.getElementById(`workdirTag`);e&&(e.setAttribute(`aria-label`,t(`workdirTag.tagHint`)),e.addEventListener(`click`,async e=>{if(e.stopPropagation(),Ir(v.activeSessionId)){Nm(),A(t(`workdirTag.lockedHint`),`warning`);return}Nm();let{showSwitchWorkdirDialog:n}=await E(async()=>{let{showSwitchWorkdirDialog:e}=await import(`./context-indicator-C9mzVLvn.js`).then(e=>e.ln);return{showSwitchWorkdirDialog:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]));await n({sessionId:v.activeSessionId||null})})),Pm(),document.addEventListener(`session-switched`,()=>{Pm()}),document.addEventListener(`session-workdir-changed`,()=>{Pm()}),document.addEventListener(`agent-model-changed`,()=>{Pm()}),document.addEventListener(`agent-tools-changed`,()=>{Pm()}),document.addEventListener(`generating-state-changed`,()=>{Nm()}),document.addEventListener(`generation-ended`,()=>{Nm()}),Pn(()=>{Nm()})}function Im(){let e=document.getElementById(`currentModelTag`);e&&e.addEventListener(`click`,e=>{e.stopPropagation(),document.getElementById(`tempDisplay`)?.click()}),Am()}function Lm(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`),Am()}function Rm(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
604
  <div class="model-section-title" data-i18n="model.selectModel">${t(`model.selectModel`)}</div>
605
605
  <div class="section-select" id="modelSelect">
606
606
  <div class="section-select-row" id="modelSelectRow">
607
- <span class="section-select-value" id="modelSelectValue">${A(v.currentModel||``)}</span>
607
+ <span class="section-select-value" id="modelSelectValue">${j(v.currentModel||``)}</span>
608
608
  <span class="model-ctx-badge" id="modelSelectCtxBadge" style="display:none;"></span>
609
609
  <span class="section-select-caret"></span>
610
610
  </div>
611
611
  <div class="section-select-list" id="modelSelectList"></div>
612
- </div>`;let e=i.querySelector(`#modelSelectList`);e.innerHTML=wd();let n=[...a].sort((e,t)=>S(e.name,t.name));for(let r of n){let n=document.createElement(`div`);n.className=`model-option`,n.dataset.value=r.name,r.contextWindow&&r.contextWindow>0&&(n.dataset.contextWindow=r.contextWindow),n.innerHTML=`<span class="model-option-check"></span><span class="model-option-left">${A(r.name)}</span>`;let i=document.createElement(`span`);i.className=`model-option-right`;let a=document.createElement(`span`);a.className=`model-ctx-badge`;let o=r.contextWindow&&r.contextWindow>0;a.textContent=g(o?r.contextWindow:fe(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(),Cd(),v.currentModel=r.name,Vm(r.name),jm(r.name),Kr()}),e.appendChild(n)}}v.customModelMap=l(e),typeof n==`function`&&n()}function Um(e,n=t(`sidePanel.selectedPrefix`)){if(!v.enableSelectionQuery)return;v.quotedContextText=``,v.selectedContextText=e;let r=document.getElementById(`selectionIndicator`),i=document.getElementById(`selectionText`),a=document.getElementById(`userInput`);if(r&&i&&a){let t;t=e.length>100?e.substring(0,100)+`...`:e.length>50?e.substring(0,50)+`...`:e,i.textContent=`${n}: ${t}`,r.classList.add(`show`)}}var Wm=null,Gm=``;function Km(){if(Wm&&Wm.isConnected)return Wm;Wm=document.createElement(`div`),Wm.className=`selection-floating-menu`,Wm.id=`selectionFloatingMenu`,Wm.innerHTML=`
612
+ </div>`;let e=i.querySelector(`#modelSelectList`);e.innerHTML=bd();let n=[...a].sort((e,t)=>S(e.name,t.name));for(let r of n){let n=document.createElement(`div`);n.className=`model-option`,n.dataset.value=r.name,r.contextWindow&&r.contextWindow>0&&(n.dataset.contextWindow=r.contextWindow),n.innerHTML=`<span class="model-option-check"></span><span class="model-option-left">${j(r.name)}</span>`;let i=document.createElement(`span`);i.className=`model-option-right`;let a=document.createElement(`span`);a.className=`model-ctx-badge`;let o=r.contextWindow&&r.contextWindow>0;a.textContent=g(o?r.contextWindow:de(r.name)),o||(a.classList.add(`is-auto`),a.title=t(`settings.ctxBadgeAutoTip`)),i.appendChild(a),n.appendChild(i),n.addEventListener(`click`,e=>{e.stopPropagation(),yd(),v.currentModel=r.name,Lm(r.name),Dm(r.name),Ur()}),e.appendChild(n)}}v.customModelMap=l(e),typeof n==`function`&&n()}function zm(e,n=t(`sidePanel.selectedPrefix`)){if(!v.enableSelectionQuery)return;v.quotedContextText=``,v.selectedContextText=e;let r=document.getElementById(`selectionIndicator`),i=document.getElementById(`selectionText`),a=document.getElementById(`userInput`);if(r&&i&&a){let t;t=e.length>100?e.substring(0,100)+`...`:e.length>50?e.substring(0,50)+`...`:e,i.textContent=`${n}: ${t}`,r.classList.add(`show`)}}var Bm=null,Vm=``;function Hm(){if(Bm&&Bm.isConnected)return Bm;Bm=document.createElement(`div`),Bm.className=`selection-floating-menu`,Bm.id=`selectionFloatingMenu`,Bm.innerHTML=`
613
613
  <div class="menu-header">
614
614
  <span class="menu-header-title"></span>
615
615
  <button class="menu-copy-btn" type="button">
@@ -619,7 +619,7 @@ Are you sure you want to stop the agent service? You will not be able to connect
619
619
  </button>
620
620
  </div>
621
621
  <div class="menu-items"></div>
622
- `;let e=Wm.querySelector(`.menu-copy-btn`);return e?.addEventListener(`click`,n=>{n.stopPropagation(),Gm&&(tt(Gm,e),k(t(`sidePanel.copySelectionDone`),`success`),window.getSelection()?.removeAllRanges(),window.hideFloatingMenu())}),document.body.appendChild(Wm),Wm}function qm(e,n,i=0,a=0){if(!v.enableSelectionQuery)return;let o=v.customPrompts.filter(e=>e.enabledInMenu===!0);if(o.length===0){r.debug(`[SidePanel] showFloatingMenu skipped: no prompts enabled in menu`);return}let s=Km();Gm=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=`
622
+ `;let e=Bm.querySelector(`.menu-copy-btn`);return e?.addEventListener(`click`,n=>{n.stopPropagation(),Vm&&(et(Vm,e),A(t(`sidePanel.copySelectionDone`),`success`),window.getSelection()?.removeAllRanges(),window.hideFloatingMenu())}),document.body.appendChild(Bm),Bm}function Um(e,n,i=0,a=0){if(!v.enableSelectionQuery)return;let o=v.customPrompts.filter(e=>e.enabledInMenu===!0);if(o.length===0){r.debug(`[SidePanel] showFloatingMenu skipped: no prompts enabled in menu`);return}let s=Hm();Vm=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
623
  <span>${r}</span>
624
624
  <span class="menu-item-actions">
625
625
  <span class="menu-item-code">/${e.code}</span>
@@ -631,15 +631,15 @@ Are you sure you want to stop the agent service? You will not be able to connect
631
631
  </svg>
632
632
  </button>
633
633
  </span>
634
- `,o.addEventListener(`click`,t=>{t.stopPropagation(),Jm(e,n)}),o.querySelector(`.menu-item-popup-btn`).addEventListener(`click`,t=>{t.stopPropagation();let r=v.currentSelectionRange?v.currentSelectionRange.cloneRange():null;window.getSelection()?.removeAllRanges(),window.hideFloatingMenu(),Cm(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(){Wm&&Wm.classList.remove(`show`),Gm=``,v.lastSelectedText=``,v.currentSelectionRange=null};async function Jm(e,n){if(!v.enableSelectionQuery)return;if(window.hideFloatingMenu(),v.isGenerating){r.debug(`[SidePanel] generating,please wait...`);return}kn()&&Qr(),await jn({state:v,getRatio:()=>Ni().usage?.ratio??0,compact:Ti}),v.selectedContextText=n,Gn();let i=document.getElementById(`chatContainer`).querySelector(`.welcome-message`);i&&i.remove(),Bt(`selected`,n,!1);let{compressed:a,wasCompressed:o}=ee(n),s=`[${t(`sidePanel.selectedContentLabel`)}${o?t(`sidePanel.selectedContentSummary`):``}]\n${a}\n\n[${t(`sidePanel.userQuestionLabel`)}]\n${e.content}`,{messageId:l,timestamp:d}=un(`user`,e.content,!0,[],null,!1,s);v.messageHistory.push({role:`user`,content:s,messageId:l,timestamp:d}),Nr(),qn(e.content),v.isGenerating=!0;let f=Qt(),p=v.activeSessionId,h=v.currentModel;try{await dt(),r.debug(`[SidePanel] sendmessagedebuginfo:`),r.debug(` - isolateChat:`,v.isolateChat),r.debug(` - chatConfig:`,v.chatConfig),r.debug(` - messageHistory.length:`,v.messageHistory.length);let n=[{role:`system`,content:await rt(null,{sessionId:p})}];if(v.isolateChat){let e=c(n[0]?.content||``),t=m(h,0,v.customModelMap)-e-4096-2e3,i=Math.floor(t*.7),a=v.messageHistory[v.messageHistory.length-1],o=Kt(v.messageHistory.slice(0,-1),{isolateChat:!0,maxMemoryMessages:v.chatConfig.maxMemoryMessages,compaction:v.activeCompaction,historyBudget:i,currentMessage:a});er(n,o,v.activeCompaction,r),o.historySummaryText&&(n[0]={...n[0],content:n[0].content+`
634
+ `,o.addEventListener(`click`,t=>{t.stopPropagation(),Wm(e,n)}),o.querySelector(`.menu-item-popup-btn`).addEventListener(`click`,t=>{t.stopPropagation();let r=v.currentSelectionRange?v.currentSelectionRange.cloneRange():null;window.getSelection()?.removeAllRanges(),window.hideFloatingMenu(),ym(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(){Bm&&Bm.classList.remove(`show`),Vm=``,v.lastSelectedText=``,v.currentSelectionRange=null};async function Wm(e,n){if(!v.enableSelectionQuery)return;if(window.hideFloatingMenu(),v.isGenerating){r.debug(`[SidePanel] generating,please wait...`);return}On()&&Xr(),await sr({state:v,getRatio:()=>ki().usage?.ratio??0,compact:Si}),v.selectedContextText=n,Un();let i=document.getElementById(`chatContainer`).querySelector(`.welcome-message`);i&&i.remove(),Bt(`selected`,n,!1);let{compressed:a,wasCompressed:o}=ee(n),s=`[${t(`sidePanel.selectedContentLabel`)}${o?t(`sidePanel.selectedContentSummary`):``}]\n${a}\n\n[${t(`sidePanel.userQuestionLabel`)}]\n${e.content}`,{messageId:l,timestamp:d}=ln(`user`,e.content,!0,[],null,!1,s);v.messageHistory.push({role:`user`,content:s,messageId:l,timestamp:d}),Ar(),Xt(e.content),v.isGenerating=!0;let f=Qt(),p=v.activeSessionId,h=v.currentModel;try{await ut(),r.debug(`[SidePanel] sendmessagedebuginfo:`),r.debug(` - isolateChat:`,v.isolateChat),r.debug(` - chatConfig:`,v.chatConfig),r.debug(` - messageHistory.length:`,v.messageHistory.length);let n=[{role:`system`,content:await nt(null,{sessionId:p})}];if(v.isolateChat){let e=c(n[0]?.content||``),t=m(h,0,v.customModelMap)-e-4096-2e3,i=Math.floor(t*.7),a=v.messageHistory[v.messageHistory.length-1],o=Qn(v.messageHistory.slice(0,-1),{isolateChat:!0,maxMemoryMessages:v.chatConfig.maxMemoryMessages,compaction:v.activeCompaction,historyBudget:i,currentMessage:a});Gn(n,o,v.activeCompaction,r),o.historySummaryText&&(n[0]={...n[0],content:n[0].content+`
635
635
 
636
- `+o.historySummaryText}),n=[...n,...o.messages];for(let e=0;e<n.length-1;e++)n[e]={...n[e],content:u(n[e].content)}}else n.push({role:`user`,content:s});let i=await qe(),a,o;try{let t=await Tt(n,h,v.useTools,i);if(a=t.content,o=t.executionLog||[],cr(f),t.wasStreamed)t.streamingMsgId&&(v.messageHistory.push({role:`assistant`,content:a,executionLog:o,messageId:t.streamingMsgId}),Nr());else{let{element:e,messageId:t}=un(`assistant`,a,!0,o);await ht(e),v.messageHistory.push({role:`assistant`,content:a,executionLog:o,messageId:t}),Nr()}or(p,e.content);return}catch(n){cr(f),a=t(`sidePanel.requestFailed`)+(n.message||t(`sidePanel.unknownError`)),o=n.executionLog||[];let{element:r,messageId:i}=un(`assistant`,a,!0,o);throw v.messageHistory.push({role:`assistant`,content:a,executionLog:o,messageId:i}),Nr(),n.message!==t(`chatMsg.errTaskStopped`)&&rr(p,a,e.content),n}}catch{}finally{rn(p),document.getElementById(`userInput`).focus()}}var Ym=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=Tm(e.pairedAgents),o=s.find(t=>t.id===e.activeAgentId)}catch{}let c=e?.connected===!0;if(c!==Ym){Ym=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),ah(o,s,c),!n){let e=document.getElementById(`headerAgentDropdown`);e&&e.style.display!==`none`&&dh()}ii(c),Rm(),ih(o,c)}function Xm(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 Zm(e,t){let n=String(e).split(`.`).map(Number),r=String(t).split(`.`).map(Number);for(let e=0;e<3;e++){let t=(n[e]||0)-(r[e]||0);if(t)return t}return 0}var Qm=3600*1e3,$m=1440*60*1e3,eh=new Map;function th(e){let n=document.getElementById(`agentDdUpdateBtn`);if(!n)return;let r=e?.current||``,i=e?.latest||``,a=!!i&&Zm(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{}th(null)}async function rh(e,t){let n=null;try{n=(await chrome.storage.local.get(`activeAgentId`)).activeAgentId}catch{}if(n===e&&(th(t),t))try{await chrome.storage.local.set({agentUpdateCheck:t})}catch{}}async function ih(e,t){if(!t||!e?.id){th(null);return}let n=`~${chrome.runtime.getManifest().version}`,r=null,i=null;try{let e=await chrome.storage.local.get([`agentUpdateCheck`,`agentUpdateCheckUnsupported`]);r=e.agentUpdateCheck,i=e.agentUpdateCheckUnsupported}catch{}if(r?.agentId===e.id&&r?.target===n&&r?.checkedAt&&Date.now()-r.checkedAt<Qm){th(r);return}if(i?.agentId===e.id&&i?.target===n&&i?.checkedAt&&Date.now()-i.checkedAt<$m){th(null);return}let a=`${e.id}:${n}`;if(eh.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 rh(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 rh(e.id,null);return}}catch{}finally{eh.delete(a)}})();eh.set(a,o),await o}function ah(e,n,r){let i=document.getElementById(`agentDdList`),a=document.getElementById(`agentDdCopyRow`);if(!i||!a)return;if(e?.url?(a.style.display=``,a.querySelector(`.agent-dd-copy-label`).textContent=e.url):a.style.display=`none`,n.length===0){i.innerHTML=`<div class="agent-dd-empty">`+t(`sidePanel.noPairedAgents`)+`</div>`;let e=document.getElementById(`agentDdRestartBtn`),n=document.getElementById(`agentDdUpdateBtn`),r=document.getElementById(`agentDdStopBtn`);e&&(e.disabled=!0),n&&(n.disabled=!0),r&&(r.disabled=!0);return}i.innerHTML=n.map(n=>{let i=n.id===e?.id,a=!!n.disabled,o=v.agentVersions.get(n.id),s=Xm(o,chrome.runtime.getManifest().version),c,l;a?(c=`disabled`,l=t(`sidePanel.agentDisabled`)):i?(c=r?`connected`:`disconnected`,l=t(r?`sidePanel.agentConnected`:`sidePanel.notConnected`)):(c=`checking`,l=t(`sidePanel.agentChecking`));let u=v.agentWorkdirs.get(n.id),d=sh(u,v.agentHomeDirs.get(n.id)),f=v.agentSystemInfos.get(n.id);return`
636
+ `+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 Ke(),a,o;try{let t=await wt(n,h,v.useTools,i);if(a=t.content,o=t.executionLog||[],or(f),t.wasStreamed)t.streamingMsgId&&(v.messageHistory.push({role:`assistant`,content:a,executionLog:o,messageId:t.streamingMsgId}),Ar());else{let{element:e,messageId:t}=ln(`assistant`,a,!0,o);await mt(e),v.messageHistory.push({role:`assistant`,content:a,executionLog:o,messageId:t}),Ar()}rn(p,e.content);return}catch(n){or(f),a=t(`sidePanel.requestFailed`)+(n.message||t(`sidePanel.unknownError`)),o=n.executionLog||[];let{element:r,messageId:i}=ln(`assistant`,a,!0,o);throw v.messageHistory.push({role:`assistant`,content:a,executionLog:o,messageId:i}),Ar(),n.message!==t(`chatMsg.errTaskStopped`)&&ir(p,a,e.content),n}}catch{}finally{bi(p),document.getElementById(`userInput`).focus()}}var Gm=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=xm(e.pairedAgents),o=s.find(t=>t.id===e.activeAgentId)}catch{}let c=e?.connected===!0;if(c!==Gm){Gm=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),th(o,s,c),!n){let e=document.getElementById(`headerAgentDropdown`);e&&e.style.display!==`none`&&sh()}xr(c),Pm(),eh(o,c)}function Km(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 qm(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 Jm=3600*1e3,Ym=1440*60*1e3,Xm=new Map;function Zm(e){let n=document.getElementById(`agentDdUpdateBtn`);if(!n)return;let r=e?.current||``,i=e?.latest||``,a=!!i&&qm(i,r)>0;n.classList.toggle(`has-update`,a),n.title=a?t(`sidePanel.agentUpdateAvailable`,{current:r,latest:i}):t(`header.updateAndRestart`)}async function Qm(){try{await chrome.storage.local.remove([`agentUpdateCheck`,`agentUpdateCheckUnsupported`])}catch{}Zm(null)}async function $m(e,t){let n=null;try{n=(await chrome.storage.local.get(`activeAgentId`)).activeAgentId}catch{}if(n===e&&(Zm(t),t))try{await chrome.storage.local.set({agentUpdateCheck:t})}catch{}}async function eh(e,t){if(!t||!e?.id){Zm(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<Jm){Zm(r);return}if(i?.agentId===e.id&&i?.target===n&&i?.checkedAt&&Date.now()-i.checkedAt<Ym){Zm(null);return}let a=`${e.id}:${n}`;if(Xm.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 $m(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 $m(e.id,null);return}}catch{}finally{Xm.delete(a)}})();Xm.set(a,o),await o}function th(e,n,r){let i=document.getElementById(`agentDdList`),a=document.getElementById(`agentDdCopyRow`);if(!i||!a)return;if(e?.url?(a.style.display=``,a.querySelector(`.agent-dd-copy-label`).textContent=e.url):a.style.display=`none`,n.length===0){i.innerHTML=`<div class="agent-dd-empty">`+t(`sidePanel.noPairedAgents`)+`</div>`;let e=document.getElementById(`agentDdRestartBtn`),n=document.getElementById(`agentDdUpdateBtn`),r=document.getElementById(`agentDdStopBtn`);e&&(e.disabled=!0),n&&(n.disabled=!0),r&&(r.disabled=!0);return}i.innerHTML=n.map(n=>{let i=n.id===e?.id,a=!!n.disabled,o=v.agentVersions.get(n.id),s=Km(o,chrome.runtime.getManifest().version),c,l;a?(c=`disabled`,l=t(`sidePanel.agentDisabled`)):i?(c=r?`connected`:`disconnected`,l=t(r?`sidePanel.agentConnected`:`sidePanel.notConnected`)):(c=`checking`,l=t(`sidePanel.agentChecking`));let u=v.agentWorkdirs.get(n.id),d=rh(u,v.agentHomeDirs.get(n.id)),f=v.agentSystemInfos.get(n.id);return`
637
637
  <div class="agent-dd-item${i?` active`:``}${a?` disabled`:``}" data-agent-id="${n.id}">
638
638
  <span class="agent-dd-item-dot ${c}"></span>
639
639
  <div class="agent-dd-item-info">
640
- <div class="agent-dd-item-name"><span class="agent-dd-item-name-text" title="${A(n.name)}">${A(n.name)}</span>${o?`<span class="agent-dd-item-version${s?` warn`:``}" title="${s?A(t(`sidePanel.agentVersionAhead`)):`v${A(o)}`}">v${A(o)}${s?` !`:``}</span>`:``}${f?`<span class="agent-dd-item-sysinfo" title="${A(f)}">${A(f)}</span>`:``}</div>
641
- <span class="agent-dd-item-url" title="${A(n.url||``)}">${A(n.url||``)}</span>
642
- ${d?`<span class="agent-dd-item-workdir" title="${t(`sidePanel.workingDirectory`,{path:A(u)})}">${A(d)}</span>`:``}
640
+ <div class="agent-dd-item-name"><span class="agent-dd-item-name-text" title="${j(n.name)}">${j(n.name)}</span>${o?`<span class="agent-dd-item-version${s?` warn`:``}" title="${s?j(t(`sidePanel.agentVersionAhead`)):`v${j(o)}`}">v${j(o)}${s?` !`:``}</span>`:``}${f?`<span class="agent-dd-item-sysinfo" title="${j(f)}">${j(f)}</span>`:``}</div>
641
+ <span class="agent-dd-item-url" title="${j(n.url||``)}">${j(n.url||``)}</span>
642
+ ${d?`<span class="agent-dd-item-workdir" title="${t(`sidePanel.workingDirectory`,{path:j(u)})}">${j(d)}</span>`:``}
643
643
  </div>
644
644
  <span class="agent-dd-item-status">${l}</span>
645
645
  ${i?`<span class="agent-dd-item-check">&#10003;</span>`:``}
@@ -650,7 +650,7 @@ Are you sure you want to stop the agent service? You will not be able to connect
650
650
  <button class="agent-dd-tool-btn delete" data-action="delete" data-id="${n.id}" title="${t(`sidePanel.deleteAgentBtn`)}">🗑</button>
651
651
  </div>
652
652
  </div>
653
- `}).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 oh(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 sh(e,t){return e?t&&e.startsWith(t)?`~`+e.substring(t.length):e:``}function ch(e,t){return e||``}function lh(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 uh(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=sh(n,v.agentHomeDirs.get(e)),o=i.querySelector(`.agent-dd-item-workdir`);o?(o.textContent=a,o.title=t(`sidePanel.workingDirectory`,{path:n})):(o=document.createElement(`span`),o.className=`agent-dd-item-workdir`,o.title=t(`sidePanel.workingDirectory`,{path:n}),o.textContent=a,i.appendChild(o))}window.updateAgentItemWorkdir=uh;async function dh(){try{let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),t=Tm(e.pairedAgents),n=e.activeAgentId;await Promise.all(t.filter(e=>!e.disabled).map(async e=>{let t=await oh(e.url,e.token),r=t.online;t.version&&v.agentVersions.set(e.id,t.version),t.workdir&&v.agentWorkdirs.set(e.id,t.workdir),t.homeDir&&v.agentHomeDirs.set(e.id,t.homeDir);let i=ch(t.platformName,t.arch);i&&v.agentSystemInfos.set(e.id,i),t.workdir&&uh(e.id,t.workdir),lh(e.id,r),e.id===n&&r!==(v.agentPlatform?.connected===!0)&&(v.agentPlatform={...v.agentPlatform,connected:r},$(v.agentPlatform,!0),r&&fh(e))}))}catch{}}async function fh(e){try{let t=e;if(!t){let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),n=Tm(e.pairedAgents),r=e.activeAgentId;t=n.find(e=>e.id===r&&!e.disabled)}if(!t||!t.url){v.agentPlatform={...v.agentPlatform,connected:!0},$(v.agentPlatform),Ur();return}if(t.token)try{let e=new AbortController;setTimeout(()=>e.abort(),3e3);let n=await fetch(`${t.url}/api/status/detail`,{signal:e.signal,headers:{Authorization:`Bearer ${t.token}`}});if(n.ok){let e=await n.json();if(e.success){v.agentPlatform={platformName:e.platformName||`Unknown`,platform:e.platform||`unknown`,arch:e.arch||`unknown`,shell:e.shell||`/bin/sh`,homeDir:e.homeDir||``,workdir:e.workdir||``,connected:!0},e.version&&v.agentVersions.set(t.id,e.version),e.workdir&&(v.agentWorkdirs.set(t.id,e.workdir),uh(t.id,e.workdir)),e.homeDir&&v.agentHomeDirs.set(t.id,e.homeDir);let n=ch(e.platformName||e.platform,e.arch);n&&v.agentSystemInfos.set(t.id,n),$(v.agentPlatform),Ur();return}}}catch{}try{let e=new AbortController;setTimeout(()=>e.abort(),3e3);let n=await fetch(`${t.url}/api/status`,{signal:e.signal});if(n.ok){let e=await n.json();v.agentPlatform={platformName:e.platformName||e.platform||`Unknown`,platform:e.platform||`unknown`,arch:e.arch||`unknown`,connected:!0},$(v.agentPlatform),Ur();return}}catch{}v.agentPlatform={...v.agentPlatform,connected:!0},$(v.agentPlatform),Ur()}catch{v.agentPlatform={...v.agentPlatform,connected:!0},$(v.agentPlatform),Ur()}}var ph=null;function mh(e,t=20){ph&&clearInterval(ph);let n=0;ph=setInterval(async()=>{if(n++,n>t||!e){clearInterval(ph),ph=null;return}try{let t=Tm((await chrome.storage.local.get([`pairedAgents`])).pairedAgents).find(t=>t.id===e);if(!t){clearInterval(ph),ph=null;return}let n=await oh(t.url,t.token);if(n.online){clearInterval(ph),ph=null,n.version&&v.agentVersions.set(e,n.version),n.workdir&&v.agentWorkdirs.set(e,n.workdir),n.homeDir&&v.agentHomeDirs.set(e,n.homeDir);let r=ch(n.platformName,n.arch);r&&v.agentSystemInfos.set(e,r),n.workdir&&uh(e,n.workdir),await fh(t),lh(e,!0)}}catch{}},3e3)}function hh(){let e=document.getElementById(`headerAgentDropdown`),t=document.getElementById(`headerAgentWrapper`);if(!e||!t)return;let n=document.body.clientWidth,r=t.getBoundingClientRect(),i=e.offsetWidth;n<312?(e.style.minWidth=n-16+`px`,e.style.maxWidth=n-16+`px`):(e.style.minWidth=``,e.style.maxWidth=``);let a=r.right+20-i,o=n-i-8;a=Math.max(8,Math.min(o,a)),e.style.left=a-r.left+`px`}async function gh(){let e=document.getElementById(`headerAgentTrigger`),n=document.getElementById(`headerAgentDropdown`),r=document.getElementById(`agentDdCopyBtn`),i=document.getElementById(`agentDdAddBtn`),a=document.getElementById(`agentDdRestartBtn`),o=document.getElementById(`agentDdUpdateBtn`),s=document.getElementById(`agentDdStopBtn`),c=document.getElementById(`agentDdRefreshBtn`);if(!e||!n)return;e.addEventListener(`click`,e=>{e.stopPropagation();let t=n.style.display!==`none`;n.style.display=t?`none`:``,t||(hh(),$(v.agentPlatform||{}),dh())}),document.addEventListener(`click`,t=>{!n.contains(t.target)&&t.target!==e&&(n.style.display=`none`)}),r.addEventListener(`click`,async e=>{e.stopPropagation(),v.activeAgentId;let n=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),r=Tm(n.pairedAgents).find(e=>e.id===n.activeAgentId);r?.url&&(await navigator.clipboard.writeText(r.url),k(t(`sidePanel.agentAddressCopied`),`success`))}),i.addEventListener(`click`,async()=>{n.style.display=`none`,await chrome.storage.local.set({optionsInitialTab:`agent`});let e=await chrome.tabs.query({}),t=chrome.runtime.getURL(`options/index.html`),r=e.find(e=>e.url&&e.url.startsWith(t));if(r){chrome.tabs.update(r.id,{active:!0});try{chrome.tabs.sendMessage(r.id,{type:`SWITCH_TAB`,tab:`agent`})}catch{}}else chrome.runtime.openOptionsPage()}),a.addEventListener(`click`,async()=>{n.style.display=`none`;let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),r=Tm(e.pairedAgents).find(t=>t.id===e.activeAgentId),i=r?.name||t(`sidePanel.unknownAgent`),a=r?.url||t(`sidePanel.unknownAgent`);if(await window.showCustomConfirm(t(`sidePanel.restartAgentConfirm`,{name:i,url:a}),t(`sidePanel.restartAgentTitle`)))try{chrome.runtime.sendMessage({type:`AGENT_RESTART`},async e=>{e?.success?(k(t(`sidePanel.agentRestarting`),`success`),v.agentPlatform={...v.agentPlatform,connected:!1},await $(v.agentPlatform,!0),r?.id&&lh(r.id,!1),mh(r?.id)):k(t(`sidePanel.restartFailed`,{error:e?.error||t(`sidePanel.unknownError`)}),`error`)})}catch(e){k(t(`sidePanel.restartRequestFailed`,{error:e.message}),`error`)}}),o.addEventListener(`click`,async()=>{n.style.display=`none`;let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),r=Tm(e.pairedAgents).find(t=>t.id===e.activeAgentId),i=r?.name||t(`sidePanel.unknownAgent`),a=r?.url||t(`sidePanel.unknownAgent`),o=chrome.runtime.getManifest().version,s=`~${o}`,c=o.split(`.`).slice(0,2).join(`.`)+`.x`;if(await window.showCustomConfirm(t(`sidePanel.updateAgentConfirm`,{name:i,url:a,version:c}),t(`sidePanel.updateAgentTitle`))){k(t(`sidePanel.agentUpdating`),`info`);try{chrome.runtime.sendMessage({type:`AGENT_UPDATE`,target:s},async e=>{if(e?.success&&e.upToDate){await nh(),k(e.message||t(`sidePanel.agentAlreadyLatest`),`info`);return}e?.success?(await nh(),k(t(`sidePanel.agentUpdateRestarting`),`success`),v.agentPlatform={...v.agentPlatform,connected:!1},await $(v.agentPlatform,!0),r?.id&&lh(r.id,!1),mh(r?.id)):k(t(`sidePanel.updateFailed`,{error:e?.error||t(`sidePanel.unknownError`)}),`error`)})}catch(e){k(t(`sidePanel.updateRequestFailed`,{error:e.message}),`error`)}}}),s.addEventListener(`click`,async()=>{n.style.display=`none`;let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),r=Tm(e.pairedAgents).find(t=>t.id===e.activeAgentId),i=r?.name||t(`sidePanel.unknownAgent`),a=r?.url||t(`sidePanel.unknownAgent`);if(await window.showCustomConfirm(t(`sidePanel.stopAgentConfirm`,{name:i,url:a}),t(`sidePanel.stopAgentTitle`)))try{chrome.runtime.sendMessage({type:`AGENT_STOP`},async e=>{e?.success?(k(t(`sidePanel.agentStopped`),`success`),v.agentPlatform={...v.agentPlatform,connected:!1},await $(v.agentPlatform,!0),r?.id&&lh(r.id,!1)):k(t(`sidePanel.stopFailed`,{error:e?.error||t(`sidePanel.unknownError`)}),`error`)})}catch(e){k(t(`sidePanel.stopRequestFailed`,{error:e.message}),`error`)}}),c&&c.addEventListener(`click`,async()=>{document.querySelectorAll(`.agent-dd-item-dot`).forEach(e=>{e.classList.remove(`online`,`offline`),e.classList.add(`checking`)}),document.querySelectorAll(`.agent-dd-item-status`).forEach(e=>{e.textContent=t(`sidePanel.agentChecking`)}),await dh(),k(t(`sidePanel.agentStatusRefreshed`),`success`)}),document.getElementById(`agentDdList`).addEventListener(`click`,async e=>{let t=e.target.closest(`.agent-dd-tool-btn`),n=e.target.closest(`.agent-dd-item`);if(t){e.stopPropagation(),l(t.dataset.action,t.dataset.id);return}n&&!n.classList.contains(`disabled`)&&!n.classList.contains(`active`)&&(e.stopPropagation(),l(`switch`,n.dataset.agentId))});async function l(e,n){let r=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),i=Tm(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 _h=new Map,vh=8;function yh(e,t){for(_h.has(e)&&_h.delete(e),_h.set(e,t);_h.size>vh;)_h.delete(_h.keys().next().value)}function bh(e){let t=_h.get(e);if(t!==void 0)return _h.delete(e),_h.set(e,t),t}function xh(e){_h.delete(e)}document.addEventListener(`DOMContentLoaded`,async()=>{await nt(),lt(()=>{_t()}),lr(),await Promise.allSettled([n().then(()=>{i(),Vi(),o(()=>{i(),Vi()})}),it(),vt(),zn()]),window.__tableBlocks=[],chrome.runtime.onMessage.addListener(e=>{if(e.type===`SCHEDULED_SESSION_UPDATED`){let t=e.sessionId,n=e.phase===`started`;t===v.activeSessionId?(v.generatingSessionIds.has(t)||v.pendingCallApiSessionIds.has(t)||nn().catch(()=>{}),n&&Ya(t)):t&&(n||Yi(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&&Um(e.selectedText),vr(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)),on(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&&Um(e.selectedText),Qn(e.text,e.selectedText||``),chrome.storage.session.remove(`pendingDirectSend`).catch(()=>{})),e.type===`AGENT_STATUS_CHANGE`&&(r.debug(`[SidePanel] recei to Agent status change:`,e.connected,e.status),v.agentPlatform={...v.agentPlatform,connected:e.connected},$(v.agentPlatform),Ur(),Ir(),e.connected&&fh()),e.type===`AGENT_CONNECTION_CHANGED`){if(r.debug(`[SidePanel] recei to Agent connection statuschanged:`,e.connected,e.agentId),!e.connected){v.agentPlatform={connected:!1},$(v.agentPlatform),Ur(),Ir();return}e.agentId&&(async()=>{try{let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),t=Tm(e.pairedAgents).find(t=>t.id===e.activeAgentId&&!t.disabled);if(!t){v.agentPlatform={connected:!1},$(v.agentPlatform),Ur(),Ir(),wr();return}if(t.token)try{let n=await fetch(`${t.url}/api/status/detail`,{cache:`no-cache`,headers:{Authorization:`Bearer ${t.token}`}});if(n.ok){let t=await n.json();if(t.success){v.agentPlatform={platformName:t.platformName||`Unknown`,platform:t.platform||`unknown`,arch:t.arch||`unknown`,shell:t.shell||`/bin/sh`,homeDir:t.homeDir||``,workdir:t.workdir||``,connected:!0},t.version&&v.agentVersions.set(e.activeAgentId,t.version),t.workdir&&v.agentWorkdirs.set(e.activeAgentId,t.workdir),t.homeDir&&v.agentHomeDirs.set(e.activeAgentId,t.homeDir);let n=ch(t.platformName||t.platform,t.arch);n&&v.agentSystemInfos.set(e.activeAgentId,n)}else v.agentPlatform={connected:!1}}else v.agentPlatform={connected:!1}}catch{v.agentPlatform={connected:!1}}else try{let n=await fetch(`${t.url}/api/status`,{cache:`no-cache`});if(n.ok){let t=await n.json();v.agentPlatform={platformName:t.platformName||`Unknown`,platform:t.platform||`unknown`,arch:t.arch||`unknown`,shell:t.shell||`/bin/sh`,homeDir:t.homeDir||``,workdir:t.workdir||``,connected:!0},t.version&&v.agentVersions.set(e.activeAgentId,t.version);let r=ch(t.platformName||t.platform,t.arch);r&&v.agentSystemInfos.set(e.activeAgentId,r)}else v.agentPlatform={connected:!1}}catch{v.agentPlatform={connected:!1}}}catch{v.agentPlatform={connected:!1}}$(v.agentPlatform),Ur(),Ir(),wr()})()}e.type===`SCREENSHOT_RESULT`&&e.dataUrl&&(r.debug(`[SidePanel] received pageshortcutscreenshotresult:`,e.mode),bi(e.dataUrl,e.mode,e.rect))});async function e(e){try{let t=await chrome.sidePanel.getOptions({tabId:e});return typeof t?.enabled==`boolean`?t.enabled:(await chrome.sidePanel.getOptions({}))?.enabled!==!1}catch{return!0}}chrome.tabs.onActivated.addListener(async t=>{if(r.debug(`[SidePanel] Tab switch, new Tab ID:`,t.tabId),!await e(t.tabId)){r.debug(`[SidePanel] Tab 无侧边栏,保持 currentTabId:`,v.currentTabId);return}v.currentTabId=t.tabId}),chrome.tabs.onUpdated.addListener(async(e,t)=>{t.status===`complete`&&v.currentTabId===e&&r.debug(`[SidePanel] current Tab page update:`,t)}),typeof marked<`u`&&(marked.setOptions({breaks:!0,gfm:!0}),r.debug(`[SidePanel] Marked library loaded`));let a=document.getElementById(`userInput`),s=document.getElementById(`sendBtn`),c=document.getElementById(`clearChatBtn`),l=document.getElementById(`exportChatBtn`),u=document.getElementById(`chatContainer`),d=document.getElementById(`tempDisplay`),p=document.getElementById(`tempDropdown`),m=document.getElementById(`tempPresetList`),h=document.getElementById(`tempSlider`),g=document.getElementById(`tempNumberInput`);function ee(){if(!a||v.isScrolling)return;a.style.height=`auto`;let e=a.scrollHeight;e<=50?a.style.height=``:a.style.height=Math.min(e,100)+`px`,ot()}chrome.storage.local.get([`temperature`,`topP`,`selectedTempIndex`],e=>{(!v.activeAgentId||v.activeAgentId==="default")&&(e.temperature!==void 0&&(v.temperature=e.temperature),e.topP!==void 0&&(v.topP=e.topP),e.selectedTempIndex!==void 0&&(v.selectedTempIndex=e.selectedTempIndex)),te()});function te(){h&&(h.value=v.temperature),g&&(g.value=v.temperature.toFixed(2));let e=document.getElementById(`tempIconValue`);e&&(e.textContent=v.temperature.toFixed(2)),_()}function ne(){let e=0,t=Math.abs(cn[0].temp-v.temperature);for(let n=1;n<cn.length;n++){let r=Math.abs(cn[n].temp-v.temperature);r<t&&(t=r,e=n)}return e}function _(){let e=ne();m.innerHTML=cn.map((n,r)=>`
653
+ `}).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 nh(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 ih(e,t){return e||``}function ah(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 oh(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,v.agentHomeDirs.get(e)),o=i.querySelector(`.agent-dd-item-workdir`);o?(o.textContent=a,o.title=t(`sidePanel.workingDirectory`,{path:n})):(o=document.createElement(`span`),o.className=`agent-dd-item-workdir`,o.title=t(`sidePanel.workingDirectory`,{path:n}),o.textContent=a,i.appendChild(o))}window.updateAgentItemWorkdir=oh;async function sh(){try{let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),t=xm(e.pairedAgents),n=e.activeAgentId;await Promise.all(t.filter(e=>!e.disabled).map(async e=>{let t=await nh(e.url,e.token),r=t.online;t.version&&v.agentVersions.set(e.id,t.version),t.workdir&&v.agentWorkdirs.set(e.id,t.workdir),t.homeDir&&v.agentHomeDirs.set(e.id,t.homeDir);let i=ih(t.platformName,t.arch);i&&v.agentSystemInfos.set(e.id,i),t.workdir&&oh(e.id,t.workdir),ah(e.id,r),e.id===n&&r!==(v.agentPlatform?.connected===!0)&&(v.agentPlatform={...v.agentPlatform,connected:r},$(v.agentPlatform,!0),r&&ch(e))}))}catch{}}async function ch(e){try{let t=e;if(!t){let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),n=xm(e.pairedAgents),r=e.activeAgentId;t=n.find(e=>e.id===r&&!e.disabled)}if(!t||!t.url){v.agentPlatform={...v.agentPlatform,connected:!0},$(v.agentPlatform),ai();return}if(t.token)try{let e=new AbortController;setTimeout(()=>e.abort(),3e3);let n=await fetch(`${t.url}/api/status/detail`,{signal:e.signal,headers:{Authorization:`Bearer ${t.token}`}});if(n.ok){let e=await n.json();if(e.success){v.agentPlatform={platformName:e.platformName||`Unknown`,platform:e.platform||`unknown`,arch:e.arch||`unknown`,shell:e.shell||`/bin/sh`,homeDir:e.homeDir||``,workdir:e.workdir||``,connected:!0},e.version&&v.agentVersions.set(t.id,e.version),e.workdir&&(v.agentWorkdirs.set(t.id,e.workdir),oh(t.id,e.workdir)),e.homeDir&&v.agentHomeDirs.set(t.id,e.homeDir);let n=ih(e.platformName||e.platform,e.arch);n&&v.agentSystemInfos.set(t.id,n),$(v.agentPlatform),ai();return}}}catch{}try{let e=new AbortController;setTimeout(()=>e.abort(),3e3);let n=await fetch(`${t.url}/api/status`,{signal:e.signal});if(n.ok){let e=await n.json();v.agentPlatform={platformName:e.platformName||e.platform||`Unknown`,platform:e.platform||`unknown`,arch:e.arch||`unknown`,connected:!0},$(v.agentPlatform),ai();return}}catch{}v.agentPlatform={...v.agentPlatform,connected:!0},$(v.agentPlatform),ai()}catch{v.agentPlatform={...v.agentPlatform,connected:!0},$(v.agentPlatform),ai()}}var lh=null;function uh(e,t=20){lh&&clearInterval(lh);let n=0;lh=setInterval(async()=>{if(n++,n>t||!e){clearInterval(lh),lh=null;return}try{let t=xm((await chrome.storage.local.get([`pairedAgents`])).pairedAgents).find(t=>t.id===e);if(!t){clearInterval(lh),lh=null;return}let n=await nh(t.url,t.token);if(n.online){clearInterval(lh),lh=null,n.version&&v.agentVersions.set(e,n.version),n.workdir&&v.agentWorkdirs.set(e,n.workdir),n.homeDir&&v.agentHomeDirs.set(e,n.homeDir);let r=ih(n.platformName,n.arch);r&&v.agentSystemInfos.set(e,r),n.workdir&&oh(e,n.workdir),await ch(t),ah(e,!0)}}catch{}},3e3)}function dh(){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 fh(){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||(dh(),$(v.agentPlatform||{}),sh())}),document.addEventListener(`click`,t=>{!n.contains(t.target)&&t.target!==e&&(n.style.display=`none`)}),r.addEventListener(`click`,async e=>{e.stopPropagation(),v.activeAgentId;let n=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),r=xm(n.pairedAgents).find(e=>e.id===n.activeAgentId);r?.url&&(await navigator.clipboard.writeText(r.url),A(t(`sidePanel.agentAddressCopied`),`success`))}),i.addEventListener(`click`,async()=>{n.style.display=`none`,await chrome.storage.local.set({optionsInitialTab:`agent`});let e=await chrome.tabs.query({}),t=chrome.runtime.getURL(`options/index.html`),r=e.find(e=>e.url&&e.url.startsWith(t));if(r){chrome.tabs.update(r.id,{active:!0});try{chrome.tabs.sendMessage(r.id,{type:`SWITCH_TAB`,tab:`agent`})}catch{}}else chrome.runtime.openOptionsPage()}),a.addEventListener(`click`,async()=>{n.style.display=`none`;let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),r=xm(e.pairedAgents).find(t=>t.id===e.activeAgentId),i=r?.name||t(`sidePanel.unknownAgent`),a=r?.url||t(`sidePanel.unknownAgent`);if(await window.showCustomConfirm(t(`sidePanel.restartAgentConfirm`,{name:i,url:a}),t(`sidePanel.restartAgentTitle`)))try{chrome.runtime.sendMessage({type:`AGENT_RESTART`},async e=>{e?.success?(A(t(`sidePanel.agentRestarting`),`success`),v.agentPlatform={...v.agentPlatform,connected:!1},await $(v.agentPlatform,!0),r?.id&&ah(r.id,!1),uh(r?.id)):A(t(`sidePanel.restartFailed`,{error:e?.error||t(`sidePanel.unknownError`)}),`error`)})}catch(e){A(t(`sidePanel.restartRequestFailed`,{error:e.message}),`error`)}}),o.addEventListener(`click`,async()=>{n.style.display=`none`;let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),r=xm(e.pairedAgents).find(t=>t.id===e.activeAgentId),i=r?.name||t(`sidePanel.unknownAgent`),a=r?.url||t(`sidePanel.unknownAgent`),o=chrome.runtime.getManifest().version,s=`~${o}`,c=o.split(`.`).slice(0,2).join(`.`)+`.x`;if(await window.showCustomConfirm(t(`sidePanel.updateAgentConfirm`,{name:i,url:a,version:c}),t(`sidePanel.updateAgentTitle`))){A(t(`sidePanel.agentUpdating`),`info`);try{chrome.runtime.sendMessage({type:`AGENT_UPDATE`,target:s},async e=>{if(e?.success&&e.upToDate){await Qm(),A(e.message||t(`sidePanel.agentAlreadyLatest`),`info`);return}e?.success?(await Qm(),A(t(`sidePanel.agentUpdateRestarting`),`success`),v.agentPlatform={...v.agentPlatform,connected:!1},await $(v.agentPlatform,!0),r?.id&&ah(r.id,!1),uh(r?.id)):A(t(`sidePanel.updateFailed`,{error:e?.error||t(`sidePanel.unknownError`)}),`error`)})}catch(e){A(t(`sidePanel.updateRequestFailed`,{error:e.message}),`error`)}}}),s.addEventListener(`click`,async()=>{n.style.display=`none`;let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),r=xm(e.pairedAgents).find(t=>t.id===e.activeAgentId),i=r?.name||t(`sidePanel.unknownAgent`),a=r?.url||t(`sidePanel.unknownAgent`);if(await window.showCustomConfirm(t(`sidePanel.stopAgentConfirm`,{name:i,url:a}),t(`sidePanel.stopAgentTitle`)))try{chrome.runtime.sendMessage({type:`AGENT_STOP`},async e=>{e?.success?(A(t(`sidePanel.agentStopped`),`success`),v.agentPlatform={...v.agentPlatform,connected:!1},await $(v.agentPlatform,!0),r?.id&&ah(r.id,!1)):A(t(`sidePanel.stopFailed`,{error:e?.error||t(`sidePanel.unknownError`)}),`error`)})}catch(e){A(t(`sidePanel.stopRequestFailed`,{error:e.message}),`error`)}}),c&&c.addEventListener(`click`,async()=>{document.querySelectorAll(`.agent-dd-item-dot`).forEach(e=>{e.classList.remove(`online`,`offline`),e.classList.add(`checking`)}),document.querySelectorAll(`.agent-dd-item-status`).forEach(e=>{e.textContent=t(`sidePanel.agentChecking`)}),await sh(),A(t(`sidePanel.agentStatusRefreshed`),`success`)}),document.getElementById(`agentDdList`).addEventListener(`click`,async e=>{let t=e.target.closest(`.agent-dd-tool-btn`),n=e.target.closest(`.agent-dd-item`);if(t){e.stopPropagation(),l(t.dataset.action,t.dataset.id);return}n&&!n.classList.contains(`disabled`)&&!n.classList.contains(`active`)&&(e.stopPropagation(),l(`switch`,n.dataset.agentId))});async function l(e,n){let r=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),i=xm(r.pairedAgents);switch(e){case`enable`:i=i.map(e=>e.id===n?{...e,disabled:!1}:e),await chrome.storage.local.set({pairedAgents:i});break;case`disable`:{i=i.map(e=>e.id===n?{...e,disabled:!0}:e);let e=r.activeAgentId;r.activeAgentId===n&&(e=i.find(e=>e.id!==n&&!e.disabled)?.id||null),await chrome.storage.local.set({pairedAgents:i,activeAgentId:e||``}),e?chrome.runtime.sendMessage({type:`AGENT_CONNECTION_CHANGED`,connected:!0,agentId:e}):chrome.runtime.sendMessage({type:`AGENT_CONNECTION_CHANGED`,connected:!1});break}case`switch`:await chrome.storage.local.set({activeAgentId:n}),chrome.runtime.sendMessage({type:`AGENT_CONNECTION_CHANGED`,connected:!0,agentId:n});break;case`disconnect`:await chrome.storage.local.set({activeAgentId:``}),chrome.runtime.sendMessage({type:`AGENT_CONNECTION_CHANGED`,connected:!1});break;case`delete`:{let e=i.find(e=>e.id===n);if(!await window.showCustomConfirm(t(`sidePanel.deleteAgentTitle`),t(`sidePanel.deleteAgentConfirm`,{name:e?.name||n})))return;i=i.filter(e=>e.id!==n);let a=r.activeAgentId===n?i.find(e=>!e.disabled)?.id||null:r.activeAgentId;await chrome.storage.local.set({pairedAgents:i,activeAgentId:a||``}),a?chrome.runtime.sendMessage({type:`AGENT_CONNECTION_CHANGED`,connected:!0,agentId:a}):chrome.runtime.sendMessage({type:`AGENT_CONNECTION_CHANGED`,connected:!1});break}}let a=document.getElementById(`headerAgentDropdown`);a&&(a.style.display=`none`)}}var ph=new Map,mh=8;function hh(e,t){for(ph.has(e)&&ph.delete(e),ph.set(e,t);ph.size>mh;)ph.delete(ph.keys().next().value)}function gh(e){let t=ph.get(e);if(t!==void 0)return ph.delete(e),ph.set(e,t),t}function _h(e){ph.delete(e)}document.addEventListener(`DOMContentLoaded`,async()=>{await tt(),ct(()=>{gt()}),tr(),await Promise.allSettled([n().then(()=>{i(),ur(),o(()=>{i(),ur()})}),rt(),_t(),qi()]),window.__tableBlocks=[],chrome.runtime.onMessage.addListener(e=>{if(e.type===`SCHEDULED_SESSION_UPDATED`){let t=e.sessionId,n=e.phase===`started`;t===v.activeSessionId?(v.generatingSessionIds.has(t)||v.pendingCallApiSessionIds.has(t)||nn().catch(()=>{}),n&&Wa(t)):t&&(n||vr(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&&zm(e.selectedText),hr(e.prompt,e.selectedText),chrome.storage.session.remove(`pendingSelectionSearch`).catch(()=>{})),e.type===`FILL_SIDEPANEL_INPUT`&&e.text&&(r.debug(`[SidePanel] received follow-upfill:`,e.text?.substring(0,50)),on(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&&zm(e.selectedText),Xn(e.text,e.selectedText||``),chrome.storage.session.remove(`pendingDirectSend`).catch(()=>{})),e.type===`AGENT_STATUS_CHANGE`&&(r.debug(`[SidePanel] recei to Agent status change:`,e.connected,e.status),v.agentPlatform={...v.agentPlatform,connected:e.connected},$(v.agentPlatform),ai(),Er(),e.connected&&ch()),e.type===`AGENT_CONNECTION_CHANGED`){if(r.debug(`[SidePanel] recei to Agent connection statuschanged:`,e.connected,e.agentId),!e.connected){v.agentPlatform={connected:!1},$(v.agentPlatform),ai(),Er();return}e.agentId&&(async()=>{try{let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),t=xm(e.pairedAgents).find(t=>t.id===e.activeAgentId&&!t.disabled);if(!t){v.agentPlatform={connected:!1},$(v.agentPlatform),ai(),Er(),Ei();return}if(t.token)try{let n=await fetch(`${t.url}/api/status/detail`,{cache:`no-cache`,headers:{Authorization:`Bearer ${t.token}`}});if(n.ok){let t=await n.json();if(t.success){v.agentPlatform={platformName:t.platformName||`Unknown`,platform:t.platform||`unknown`,arch:t.arch||`unknown`,shell:t.shell||`/bin/sh`,homeDir:t.homeDir||``,workdir:t.workdir||``,connected:!0},t.version&&v.agentVersions.set(e.activeAgentId,t.version),t.workdir&&v.agentWorkdirs.set(e.activeAgentId,t.workdir),t.homeDir&&v.agentHomeDirs.set(e.activeAgentId,t.homeDir);let n=ih(t.platformName||t.platform,t.arch);n&&v.agentSystemInfos.set(e.activeAgentId,n)}else v.agentPlatform={connected:!1}}else v.agentPlatform={connected:!1}}catch{v.agentPlatform={connected:!1}}else try{let n=await fetch(`${t.url}/api/status`,{cache:`no-cache`});if(n.ok){let t=await n.json();v.agentPlatform={platformName:t.platformName||`Unknown`,platform:t.platform||`unknown`,arch:t.arch||`unknown`,shell:t.shell||`/bin/sh`,homeDir:t.homeDir||``,workdir:t.workdir||``,connected:!0},t.version&&v.agentVersions.set(e.activeAgentId,t.version);let r=ih(t.platformName||t.platform,t.arch);r&&v.agentSystemInfos.set(e.activeAgentId,r)}else v.agentPlatform={connected:!1}}catch{v.agentPlatform={connected:!1}}}catch{v.agentPlatform={connected:!1}}$(v.agentPlatform),ai(),Er(),Ei()})()}e.type===`SCREENSHOT_RESULT`&&e.dataUrl&&(r.debug(`[SidePanel] received pageshortcutscreenshotresult:`,e.mode),Mr(e.dataUrl,e.mode,e.rect))});async function e(e){try{let t=await chrome.sidePanel.getOptions({tabId:e});return typeof t?.enabled==`boolean`?t.enabled:(await chrome.sidePanel.getOptions({}))?.enabled!==!1}catch{return!0}}chrome.tabs.onActivated.addListener(async t=>{if(r.debug(`[SidePanel] Tab switch, new Tab ID:`,t.tabId),!await e(t.tabId)){r.debug(`[SidePanel] Tab 无侧边栏,保持 currentTabId:`,v.currentTabId);return}v.currentTabId=t.tabId}),chrome.tabs.onUpdated.addListener(async(e,t)=>{t.status===`complete`&&v.currentTabId===e&&r.debug(`[SidePanel] current Tab page update:`,t)}),typeof marked<`u`&&(marked.setOptions({breaks:!0,gfm:!0}),r.debug(`[SidePanel] Marked library loaded`));let a=document.getElementById(`userInput`),s=document.getElementById(`sendBtn`),c=document.getElementById(`clearChatBtn`),l=document.getElementById(`exportChatBtn`),u=document.getElementById(`chatContainer`),d=document.getElementById(`tempDisplay`),p=document.getElementById(`tempDropdown`),m=document.getElementById(`tempPresetList`),h=document.getElementById(`tempSlider`),g=document.getElementById(`tempNumberInput`);function ee(){if(!a||v.isScrolling)return;a.style.height=`auto`;let e=a.scrollHeight;e<=50?a.style.height=``:a.style.height=Math.min(e,100)+`px`,at()}chrome.storage.local.get([`temperature`,`topP`,`selectedTempIndex`],e=>{(!v.activeAgentId||v.activeAgentId==="default")&&(e.temperature!==void 0&&(v.temperature=e.temperature),e.topP!==void 0&&(v.topP=e.topP),e.selectedTempIndex!==void 0&&(v.selectedTempIndex=e.selectedTempIndex)),te()});function te(){h&&(h.value=v.temperature),g&&(g.value=v.temperature.toFixed(2));let e=document.getElementById(`tempIconValue`);e&&(e.textContent=v.temperature.toFixed(2)),_()}function ne(){let e=0,t=Math.abs(Kt[0].temp-v.temperature);for(let n=1;n<Kt.length;n++){let r=Math.abs(Kt[n].temp-v.temperature);r<t&&(t=r,e=n)}return e}function _(){let e=ne();m.innerHTML=Kt.map((n,r)=>`
654
654
  <div class="temp-preset-item ${r===e?`selected`:``}" data-index="${r}">
655
655
  <div class="temp-preset-radio"></div>
656
656
  <div class="temp-preset-info">
@@ -659,24 +659,24 @@ Are you sure you want to stop the agent service? You will not be able to connect
659
659
  </div>
660
660
  <div class="temp-preset-value">${n.temp.toFixed(2)}</div>
661
661
  </div>
662
- `).join(``),m.querySelectorAll(`.temp-preset-item`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),y(parseInt(e.dataset.index))})})}function y(e){let t=cn[e];t&&(v.selectedTempIndex=e,v.temperature=t.temp,te(),Nm(v.temperature,v.topP,v.selectedTempIndex))}h.addEventListener(`input`,e=>{e.stopPropagation();let t=parseFloat(e.target.value);isNaN(t)&&(t=0),t=Math.max(0,Math.min(1,t)),v.temperature=t,g.value=t.toFixed(2);let n=document.getElementById(`tempIconValue`);n&&(n.textContent=t.toFixed(2)),_(),Nm(v.temperature,v.topP,ne())}),g.addEventListener(`change`,e=>{e.stopPropagation();let t=parseFloat(e.target.value);isNaN(t)&&(t=0),t=Math.max(0,Math.min(1,t)),v.temperature=t,h.value=t,g.value=t.toFixed(2);let n=document.getElementById(`tempIconValue`);n&&(n.textContent=t.toFixed(2)),_(),Nm(v.temperature,v.topP,ne())}),d&&p&&(d.addEventListener(`click`,e=>{e.stopPropagation(),p.classList.toggle(`show`)}),document.addEventListener(`click`,e=>{let t=document.querySelector(`.temp-selector`);t&&!t.contains(e.target)&&p.classList.remove(`show`)})),document.addEventListener(`mousedown`,e=>{ms(e.target)&&(v.lastMouseX=e.clientX,v.lastMouseY=e.clientY)}),document.addEventListener(`mouseup`,e=>{ms(e.target)&&(v.lastMouseX=e.clientX,v.lastMouseY=e.clientY,v.enableSelectionQuery&&setTimeout(()=>{let e=window.getSelection();if(e&&!e.isCollapsed&&e.toString().trim()){let t=e.toString().trim();ms(e.anchorNode)&&(v.lastSelectedText=t,v.currentSelectionRange=e.getRangeAt(0).cloneRange(),Um(t),qm(e,t,v.lastMouseX,v.lastMouseY))}else ms(e.anchorNode)||(v.lastSelectedText=``,v.currentSelectionRange=null,window.hideFloatingMenu())},50))});let b=``,x=null;async function ie(){try{let e=await new Promise(e=>{chrome.tabs.query({active:!0,currentWindow:!0},t=>e(t))});if(e&&e.length>0){let t=await new Promise(t=>{chrome.tabs.sendMessage(e[0].id,{action:`getSelectedText`},e=>{chrome.runtime.lastError?(console.debug(`[SidePanel] content script not loaded or unreachable:`,chrome.runtime.lastError.message),t(null)):t(e)})});if(!t)return;let n=t?.text||``;n&&n.trim()?n!==b&&(b=n,Um(n.trim())):b=``}}catch{}}function S(){x&&=(clearInterval(x),null),v.enableSelectionQuery&&(x=setInterval(ie,500))}S(),chrome.storage.onChanged.addListener((e,t)=>{if(t===`local`&&`enableSelectionQuery`in e){v.enableSelectionQuery=e.enableSelectionQuery.newValue;let t=document.getElementById(`enableSelectionQueryBtn`);t&&(t.checked=v.enableSelectionQuery),S()}}),await re(),Od(),chrome.storage.local.get([`modelName`,`customModels`,`customPrompts`,`systemPrompt`,`inputHistory`,`agentPlatform`,`enableImageInput`,`imageModelName`,`imageApiBase`,`imageApiKey`,`enableFileInput`],e=>{let t=e.modelName;t&&(v.currentModel=t),v.customPrompts=e.customPrompts||[],v.systemPrompt=e.systemPrompt||``,v.inputHistory=e.inputHistory||[],e.agentPlatform&&(v.agentPlatform=e.agentPlatform),$(v.agentPlatform),chrome.runtime.sendMessage({type:`TRIGGER_AGENT_HEALTH_CHECK`}).catch(()=>{}),Mm(),v.enableImageInput=e.enableImageInput||!1,v.imageModelName=e.imageModelName||``,v.imageApiBase=e.imageApiBase||``,v.imageApiKey=ue(e.imageApiKey)||``,v.enableFileInput=!0,zr(),Ur(),It(),Hm(e.customModels,()=>{t&&Vm(t)})}),chrome.storage.onChanged.addListener((e,t)=>{if(t===`local`){if(e.customModels&&Hm(e.customModels.newValue||[],()=>{Vm(v.currentModel)}),e.modelName){let t=e.modelName.newValue;t&&(!v.activeAgentId||v.activeAgentId==="default")&&(v.currentModel=t,Vm(t))}if(e.enableImageInput&&(v.enableImageInput=e.enableImageInput.newValue,zr()),e.enableFileInput&&(v.enableFileInput=e.enableFileInput.newValue,Ur()),e.enableExecutionLog&&(v.chatConfig.enableExecutionLog=e.enableExecutionLog.newValue),e.showMessageTimestamp){let t=e.showMessageTimestamp.newValue!==!1;v.chatConfig.showMessageTimestamp=t,mi(t)}e.systemPrompt&&(v.systemPrompt=e.systemPrompt.newValue||``),e.imageModelName&&(v.imageModelName=e.imageModelName.newValue||``),e.imageApiBase&&(v.imageApiBase=e.imageApiBase.newValue||``),e.imageApiKey&&(v.imageApiKey=ue(e.imageApiKey.newValue)||``)}}),await nn(),await Lp();let C=await chrome.storage.session.get([`pendingSelectionSearch`,`pendingFillInput`,`pendingDirectSend`]),ae=[];if(C.pendingSelectionSearch&&C.pendingSelectionSearch.selectedText){let{prompt:e,selectedText:t}=C.pendingSelectionSearch;r.debug(`[SidePanel] pending selected textsearch:`,t?.substring(0,50)),Um(t),setTimeout(()=>{vr(e,t)},500),ae.push(`pendingSelectionSearch`)}if(C.pendingFillInput&&C.pendingFillInput.text){let{text:e}=C.pendingFillInput;r.debug(`[SidePanel] pending fill trackasktext:`,e?.substring(0,50)),setTimeout(()=>{on(e)},500),ae.push(`pendingFillInput`)}if(C.pendingDirectSend&&C.pendingDirectSend.text){let{text:e,selectedText:t}=C.pendingDirectSend;r.debug(`[SidePanel] pending directsend text:`,e?.substring(0,50)),t&&Um(t),setTimeout(()=>{Qn(e,t||``)},500),ae.push(`pendingDirectSend`)}ae.length>0&&await chrome.storage.session.remove(ae);let oe=document.getElementById(`userInput`);oe&&oe.focus(),document.addEventListener(`session-switched`,e=>{let{sessionId:n,previousSessionId:i}=e.detail||{},a=document.getElementById(`chatContainer`),o=document.getElementById(`userInput`);if(!a)return;let s=i&&v.messageHistory?.some(e=>e.resumable);if(i&&!v.pendingCallApiSessionIds.has(i)&&!s){let e=_n(a);e&&yh(i,e)}let c=document.getElementById(`imagePreviewBar`);v.attachedImages.length>0&&c&&c.style.display===`none`&&(v.attachedImages=[]),v.executionLogListener&&=(chrome.runtime.onMessage.removeListener(v.executionLogListener),null),ce(),o&&o.focus();let l=v.pendingCallApiSessionIds.has(n)&&!!v.pendingCancelApi,u=bh(n),d=v.messageHistory&&v.messageHistory.length>0;if(u&&!l&&d){if(a.innerHTML=u,ar(a),ct(),ft(),!e.detail?.skipScrollRestore){let e=`scrollPosition_`+(n||`default`);chrome.storage.local.get([e],t=>{t[e]!==void 0&&setTimeout(()=>{let n=document.getElementById(`chatContainer`);n&&(n.scrollTop=t[e])},150)})}wt();return}if(a.innerHTML=``,d){if(v.messageHistory.forEach(e=>{e.htmlContent?An(e.htmlContent,e.messageId,e.resumable):un(e.role,e.content,!1,e.executionLog||[],e.reflectionScore,e.wasRevised,null,e.messageId,[],e.resumable||!1,e.timestamp??null)}),Nn(),ta(),ct(),ft(),!v.pendingCallApiSessionIds.has(n)){let e=_n(a);e&&yh(n,e)}wt()}else{let e=document.createElement(`div`);e.className=`welcome-message`,e.innerHTML=`
662
+ `).join(``),m.querySelectorAll(`.temp-preset-item`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),y(parseInt(e.dataset.index))})})}function y(e){let t=Kt[e];t&&(v.selectedTempIndex=e,v.temperature=t.temp,te(),km(v.temperature,v.topP,v.selectedTempIndex))}h.addEventListener(`input`,e=>{e.stopPropagation();let t=parseFloat(e.target.value);isNaN(t)&&(t=0),t=Math.max(0,Math.min(1,t)),v.temperature=t,g.value=t.toFixed(2);let n=document.getElementById(`tempIconValue`);n&&(n.textContent=t.toFixed(2)),_(),km(v.temperature,v.topP,ne())}),g.addEventListener(`change`,e=>{e.stopPropagation();let t=parseFloat(e.target.value);isNaN(t)&&(t=0),t=Math.max(0,Math.min(1,t)),v.temperature=t,h.value=t,g.value=t.toFixed(2);let n=document.getElementById(`tempIconValue`);n&&(n.textContent=t.toFixed(2)),_(),km(v.temperature,v.topP,ne())}),d&&p&&(d.addEventListener(`click`,e=>{e.stopPropagation(),p.classList.toggle(`show`)}),document.addEventListener(`click`,e=>{let t=document.querySelector(`.temp-selector`);t&&!t.contains(e.target)&&p.classList.remove(`show`)})),document.addEventListener(`mousedown`,e=>{us(e.target)&&(v.lastMouseX=e.clientX,v.lastMouseY=e.clientY)}),document.addEventListener(`mouseup`,e=>{us(e.target)&&(v.lastMouseX=e.clientX,v.lastMouseY=e.clientY,v.enableSelectionQuery&&setTimeout(()=>{let e=window.getSelection();if(e&&!e.isCollapsed&&e.toString().trim()){let t=e.toString().trim();us(e.anchorNode)&&(v.lastSelectedText=t,v.currentSelectionRange=e.getRangeAt(0).cloneRange(),zm(t),Um(e,t,v.lastMouseX,v.lastMouseY))}else us(e.anchorNode)||(v.lastSelectedText=``,v.currentSelectionRange=null,window.hideFloatingMenu())},50))});let b=``,x=null;async function ie(){try{let e=await new Promise(e=>{chrome.tabs.query({active:!0,currentWindow:!0},t=>e(t))});if(e&&e.length>0){let t=await new Promise(t=>{chrome.tabs.sendMessage(e[0].id,{action:`getSelectedText`},e=>{chrome.runtime.lastError?(console.debug(`[SidePanel] content script not loaded or unreachable:`,chrome.runtime.lastError.message),t(null)):t(e)})});if(!t)return;let n=t?.text||``;n&&n.trim()?n!==b&&(b=n,zm(n.trim())):b=``}}catch{}}function S(){x&&=(clearInterval(x),null),v.enableSelectionQuery&&(x=setInterval(ie,500))}S(),chrome.storage.onChanged.addListener((e,t)=>{if(t===`local`&&`enableSelectionQuery`in e){v.enableSelectionQuery=e.enableSelectionQuery.newValue;let t=document.getElementById(`enableSelectionQueryBtn`);t&&(t.checked=v.enableSelectionQuery),S()}}),await re(),wd(),chrome.storage.local.get([`modelName`,`customModels`,`customPrompts`,`systemPrompt`,`inputHistory`,`agentPlatform`,`enableImageInput`,`imageModelName`,`imageApiBase`,`imageApiKey`,`enableFileInput`],e=>{let t=e.modelName;t&&(v.currentModel=t),v.customPrompts=e.customPrompts||[],v.systemPrompt=e.systemPrompt||``,v.inputHistory=e.inputHistory||[],e.agentPlatform&&(v.agentPlatform=e.agentPlatform),$(v.agentPlatform),chrome.runtime.sendMessage({type:`TRIGGER_AGENT_HEALTH_CHECK`}).catch(()=>{}),Om(),v.enableImageInput=e.enableImageInput||!1,v.imageModelName=e.imageModelName||``,v.imageApiBase=e.imageApiBase||``,v.imageApiKey=le(e.imageApiKey)||``,v.enableFileInput=!0,Br(),ai(),It(),Rm(e.customModels,()=>{t&&Lm(t)})}),chrome.storage.onChanged.addListener((e,t)=>{if(t===`local`){if(e.customModels&&Rm(e.customModels.newValue||[],()=>{Lm(v.currentModel)}),e.modelName){let t=e.modelName.newValue;t&&(!v.activeAgentId||v.activeAgentId==="default")&&(v.currentModel=t,Lm(t))}if(e.enableImageInput&&(v.enableImageInput=e.enableImageInput.newValue,Br()),e.enableFileInput&&(v.enableFileInput=e.enableFileInput.newValue,ai()),e.enableExecutionLog&&(v.chatConfig.enableExecutionLog=e.enableExecutionLog.newValue),e.showMessageTimestamp){let t=e.showMessageTimestamp.newValue!==!1;v.chatConfig.showMessageTimestamp=t,di(t)}e.systemPrompt&&(v.systemPrompt=e.systemPrompt.newValue||``),e.imageModelName&&(v.imageModelName=e.imageModelName.newValue||``),e.imageApiBase&&(v.imageApiBase=e.imageApiBase.newValue||``),e.imageApiKey&&(v.imageApiKey=le(e.imageApiKey.newValue)||``)}}),await nn(),await Np();let C=await chrome.storage.session.get([`pendingSelectionSearch`,`pendingFillInput`,`pendingDirectSend`]),ae=[];if(C.pendingSelectionSearch&&C.pendingSelectionSearch.selectedText){let{prompt:e,selectedText:t}=C.pendingSelectionSearch;r.debug(`[SidePanel] pending selected textsearch:`,t?.substring(0,50)),zm(t),setTimeout(()=>{hr(e,t)},500),ae.push(`pendingSelectionSearch`)}if(C.pendingFillInput&&C.pendingFillInput.text){let{text:e}=C.pendingFillInput;r.debug(`[SidePanel] pending fill trackasktext:`,e?.substring(0,50)),setTimeout(()=>{on(e)},500),ae.push(`pendingFillInput`)}if(C.pendingDirectSend&&C.pendingDirectSend.text){let{text:e,selectedText:t}=C.pendingDirectSend;r.debug(`[SidePanel] pending directsend text:`,e?.substring(0,50)),t&&zm(t),setTimeout(()=>{Xn(e,t||``)},500),ae.push(`pendingDirectSend`)}ae.length>0&&await chrome.storage.session.remove(ae);let oe=document.getElementById(`userInput`);oe&&oe.focus(),document.addEventListener(`session-switched`,e=>{let{sessionId:n,previousSessionId:i}=e.detail||{},a=document.getElementById(`chatContainer`),o=document.getElementById(`userInput`);if(!a)return;let s=i&&v.messageHistory?.some(e=>e.resumable);if(i&&!v.pendingCallApiSessionIds.has(i)&&!s){let e=gn(a);e&&hh(i,e)}let c=document.getElementById(`imagePreviewBar`);v.attachedImages.length>0&&c&&c.style.display===`none`&&(v.attachedImages=[]),v.executionLogListener&&=(chrome.runtime.onMessage.removeListener(v.executionLogListener),null),ce(),o&&o.focus();let l=v.pendingCallApiSessionIds.has(n)&&!!v.pendingCancelApi,u=gh(n),d=v.messageHistory&&v.messageHistory.length>0;if(u&&!l&&d){if(a.innerHTML=u,rr(a),st(),dt(),!e.detail?.skipScrollRestore){let e=`scrollPosition_`+(n||`default`);chrome.storage.local.get([e],t=>{t[e]!==void 0&&setTimeout(()=>{let n=document.getElementById(`chatContainer`);n&&(n.scrollTop=t[e])},150)})}Ct();return}if(a.innerHTML=``,d){if(v.messageHistory.forEach(e=>{e.htmlContent?kn(e.htmlContent,e.messageId,e.resumable):ln(e.role,e.content,!1,e.executionLog||[],e.reflectionScore,e.wasRevised,null,e.messageId,[],e.resumable||!1,e.timestamp??null)}),Mn(),$i(),st(),dt(),!v.pendingCallApiSessionIds.has(n)){let e=gn(a);e&&hh(n,e)}Ct()}else{let e=document.createElement(`div`);e.className=`welcome-message`,e.innerHTML=`
663
663
  <div class="icon-wrapper">
664
664
  <div class="icon">💬</div>
665
665
  </div>
666
666
  <h2>${t(`sidePanel.welcomeTitle`)}</h2>
667
667
  <p>${t(`sidePanel.welcomeSubtitle`)}</p>
668
- `,a.appendChild(e)}if(r.debug(`[SidePanel] session-switched: pendingTask?`,l,`pendingSessionIds:`,[...v.pendingCallApiSessionIds],`activeSessionId:`,n,`hasCancelApi:`,!!v.pendingCancelApi),l&&(r.debug(`[SidePanel] switch back tobackground task session,rebuildstreamingoutput element`),Sr(n)),Ya(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 T(async()=>{let{updateScrollButtonState:e}=await import(`./context-indicator-BSGa1g7l.js`).then(e=>e.pt);return{updateScrollButtonState:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]));r()},150)})}}),document.addEventListener(`session-cache-invalidate`,e=>{let{sessionId:t}=e.detail||{};t&&xh(t)}),document.querySelectorAll(`.model-option`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation();let n=e.dataset.value;v.currentModel=n,Vm(n),jm(n),Kr()})}),document.addEventListener(`agent-model-changed`,()=>{Vm(v.currentModel);let e=document.getElementById(`tempSlider`),t=document.getElementById(`tempNumberInput`),n=document.getElementById(`tempIconValue`);e&&(e.value=v.temperature),t&&(t.value=v.temperature.toFixed(2)),n&&(n.textContent=v.temperature.toFixed(2)),_()}),document.addEventListener(`click`,e=>{let t=document.getElementById(`promptDropdown`),n=document.getElementById(`promptSelector`),r=document.getElementById(`agentAtSelector`),i=document.getElementById(`selectionFloatingMenu`);n.contains(e.target)||(t.classList.remove(`show`),Mt()),r&&!r.contains(e.target)&&sr();let a=document.getElementById(`fileAtSelector`);if(a&&!a.contains(e.target)&&Qd(),i&&!i.contains(e.target)){let t=window.getSelection(),n=ms(e.target),r=t&&!t.isCollapsed&&ms(t.anchorNode);(!n||!r)&&window.hideFloatingMenu()}});let w=document.getElementById(`stopCompanionBtn`);function se(){let e=!!(a&&a.value&&a.value.trim())||hn();return v.isGenerating&&e}function ce(){a&&a.value&&a.value.trim();let e=v.isGenerating,n=se();s.classList.toggle(`queue-mode`,n),s.classList.toggle(`stop-mode`,e&&!n),n?(s.innerHTML=`<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h11"/><path d="M3 12h11"/><path d="M3 18h7"/><path d="M17.5 10v8"/><path d="M14.5 15.5L17.5 18.5l3-3"/></svg>`,s.title=t(`queue.enqueueBtn`)):e?(s.innerHTML=`<svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect></svg>`,s.title=t(`sidePanel.sendBtnStop`)):(s.innerHTML=`<svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor"><path d="M12 4l-1.41 1.41L16.17 11H4v2h12.17l-5.58 5.59L12 20l8-8-8-8z"/></svg>`,s.title=t(`sidePanel.sendBtnSend`)),s.disabled=!1,s.style.opacity=``,s.style.cursor=``,w&&(w.style.display=n?``:`none`,w.disabled=!1,w.style.opacity=``,w.style.cursor=``)}s.addEventListener(`click`,()=>{if(!v.isGenerating){Ii();return}se()?yn():Lr(s)}),w?.addEventListener(`click`,()=>Lr(w));function le(e){if(!v.isGenerating)return!1;let n=v.activeSessionId;return n?Vt(n)?(na(n),Lr(w&&w.style.display!==`none`?w:e||s)?(k(t(`queue.stopAndSendStarted`),`success`,2500),!0):(Kn(n),!0)):(k(t(`queue.stopAndSendEmpty`),`warning`,3e3),!1):!1}function de(e,{isPrimarySend:t=!1}={}){if(!e)return;let n=()=>t&&se();e.addEventListener(`contextmenu`,t=>{n()||!v.isGenerating||!Vt(v.activeSessionId)||(t.preventDefault(),le(e))});let r=null,i=()=>{r&&=(clearTimeout(r),null)};e.addEventListener(`pointerdown`,t=>{t.pointerType===`mouse`&&t.button!==0||n()||!v.isGenerating||!Vt(v.activeSessionId)||(i(),r=setTimeout(()=>{r=null,le(e)},600))});for(let t of[`pointerup`,`pointerleave`,`pointercancel`])e.addEventListener(t,i)}de(s,{isPrimarySend:!0}),de(w),document.addEventListener(`queue-stop-and-send`,()=>{le(w&&w.style.display!==`none`?w:s)}),document.addEventListener(`generating-state-changed`,ce),a.addEventListener(`input`,ce),document.addEventListener(`input-attachments-changed`,ce),document.addEventListener(`voice-draft-written`,ce);let fe=document.getElementById(`shortcutsBtn`),E=document.getElementById(`shortcutsModal`),pe=document.getElementById(`shortcutsCloseBtn`);function me(){E&&(E.style.display=`flex`)}function he(){E&&(E.style.display=`none`)}fe&&fe.addEventListener(`click`,e=>{e.stopPropagation(),me();let t=document.getElementById(`headerMoreDropdown`);t&&t.classList.remove(`show`)}),pe&&pe.addEventListener(`click`,he),E&&E.addEventListener(`click`,e=>{e.target===E&&he()});let ge=ps();xn(),Gt({adjustInputHeight:ee}).catch(e=>{r.warn(`[SidePanel] initVoiceInput failed:`,e?.message||e)}),document.addEventListener(`keydown`,e=>{if((e.ctrlKey||e.metaKey)&&e.key===`t`){e.preventDefault();let t=document.getElementById(`toolsPopup`);t&&t.style.display!==`none`?Tr():kr()}if(e.key===`Escape`&&$n()){e.preventDefault();return}if(!(e.key===`Escape`&&ge.handleEscape())){if(e.key===`Escape`&&E&&E.style.display!==`none`){he();return}if(e.altKey&&e.code===`Slash`){e.preventDefault(),me();return}if(e.altKey&&!e.shiftKey&&e.code===`KeyS`&&!e.ctrlKey&&!e.metaKey){e.preventDefault(),Or();return}if(e.altKey&&e.shiftKey&&e.code===`KeyS`&&!e.ctrlKey&&!e.metaKey){e.preventDefault(),Fr();return}if(sn(e)){e.preventDefault(),Ci();return}if(e.altKey&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&e.code===`KeyN`){e.preventDefault(),Di();return}if(e.altKey&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&e.code===`KeyW`){e.preventDefault(),Fi();return}if(e.altKey&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&e.code===`KeyE`){e.preventDefault();let t=document.querySelectorAll(`#chatContainer .message.user`),n=t[t.length-1];if(n){Wt(n);let e=document.getElementById(`userInput`);e&&e.focus()}return}if(e.altKey&&(e.key===`ArrowUp`||e.key===`ArrowDown`)){e.preventDefault();let t=e.key===`ArrowUp`?`prev`:`next`;ge.jumpToMessage(t,e.ctrlKey||e.metaKey),ge.updateActiveQuestion();return}}}),a.addEventListener(`keydown`,e=>{let t=document.getElementById(`promptSelector`),n=document.getElementById(`promptDropdown`),r=document.getElementById(`agentAtSelector`),i=document.getElementById(`agentAtDropdown`);if(r.style.display!==`none`&&i.classList.contains(`show`)){let t=document.getElementById(`agentAtTabs`),n=t&&t.classList.contains(`merged-mode`);if(!n&&e.key===`Tab`){e.preventDefault();let t=Array.from(document.querySelectorAll(`#agentAtTabs .prompt-tab`)).map(e=>e.dataset.tab),n=e=>{let t=document.querySelector(`#agentAtTabs .prompt-tab[data-tab="${e}"]`);return!!t&&t.style.display!==`none`},r=t.indexOf(Zn);for(let e=0;e<t.length;e++)if(r=(r+1)%t.length,n(t[r])){Ei(t[r]);break}return}let r,i;n?(r=document.getElementById(`agentAtList`),i=v.selectedAgentAtIndex):Zn===`pages`?(r=document.getElementById(`agentPageList`),i=v.selectedPageIndex):Zn===`proxies`?(r=document.getElementById(`agentProxyList`),i=v.selectedProxyAtIndex):Zn===`knowledge`?(r=document.getElementById(`agentKnowledgeList`),i=v.selectedKnowledgeAtIndex):(r=document.getElementById(`agentAtList`),i=v.selectedAgentAtIndex);let a=r?r.querySelectorAll(`.prompt-item`):[],o=a.length;if(o!==0){if(e.key===`ArrowDown`){e.preventDefault();let t=i<0?0:(i+1)%o;n?(v.selectedAgentAtIndex=t,qr(a)):Zn===`proxies`?(v.selectedProxyAtIndex=t,qr(a)):Zn===`knowledge`?(v.selectedKnowledgeAtIndex=t,qr(a)):Zn===`pages`?(v.selectedPageIndex=t,Ot(a)):(v.selectedAgentAtIndex=t,qr(a));return}else if(e.key===`ArrowUp`){e.preventDefault();let t=i<0||i===0?o-1:i-1;n?(v.selectedAgentAtIndex=t,qr(a)):Zn===`proxies`?(v.selectedProxyAtIndex=t,qr(a)):Zn===`knowledge`?(v.selectedKnowledgeAtIndex=t,qr(a)):Zn===`pages`?(v.selectedPageIndex=t,Ot(a)):(v.selectedAgentAtIndex=t,qr(a));return}else if(e.key===`Enter`&&i>=0){e.preventDefault(),a[i].click(),(e.ctrlKey||e.metaKey)&&sr();return}else if(e.key===`Escape`){sr();return}}}let o=document.getElementById(`fileAtSelector`),s=document.getElementById(`fileAtDropdown`);if(o&&s&&o.style.display!==`none`&&s.classList.contains(`show`)){let t=document.getElementById(`fileAtList`),n=t?t.querySelectorAll(`.prompt-item`):[],r=n.length;if(e.key===`ArrowDown`||e.key===`ArrowUp`){e.preventDefault(),r>0&&(v.selectedFileAtIndex=e.key===`ArrowDown`?v.selectedFileAtIndex<0?0:(v.selectedFileAtIndex+1)%r:v.selectedFileAtIndex<0||v.selectedFileAtIndex===0?r-1:v.selectedFileAtIndex-1,rf(n));return}if(e.key===`Enter`&&r>0&&v.selectedFileAtIndex>=0){e.preventDefault(),n[v.selectedFileAtIndex].click();return}if(e.key===`Escape`){e.preventDefault(),Qd();return}}if(t.style.display!==`none`&&n.classList.contains(`show`)){if(v.showMergedList){let t=n.querySelectorAll(`#promptList .prompt-item`),r=t.length;if(e.key===`ArrowDown`){e.preventDefault(),v.selectedPromptIndex<0?v.selectedPromptIndex=0:v.selectedPromptIndex=(v.selectedPromptIndex+1)%r,En(t);return}if(e.key===`ArrowUp`){e.preventDefault(),v.selectedPromptIndex<0||v.selectedPromptIndex===0?v.selectedPromptIndex=r-1:--v.selectedPromptIndex,En(t);return}if(e.key===`Enter`&&v.selectedPromptIndex>=0){e.preventDefault();let n=t[v.selectedPromptIndex];n.dataset.type===`skill`||n.dataset.type===`mcp`?(n.click(),(e.ctrlKey||e.metaKey)&&Mt()):e.ctrlKey||e.metaKey?$r(n.dataset.code):xt(n.dataset.code);return}if(e.key===`Escape`){Mt();return}return}if(v.activeDropdownTab===`skills`){let t=n.querySelectorAll(`#skillList .skill-list-item`),r=t.length;if(e.key===`ArrowDown`){e.preventDefault(),v.selectedSkillIndex<0?v.selectedSkillIndex=0:v.selectedSkillIndex=(v.selectedSkillIndex+1)%r,Ui(t);return}if(e.key===`ArrowUp`){e.preventDefault(),v.selectedSkillIndex<0||v.selectedSkillIndex===0?v.selectedSkillIndex=r-1:--v.selectedSkillIndex,Ui(t);return}if(e.key===`Enter`&&v.selectedSkillIndex>=0){e.preventDefault(),t[v.selectedSkillIndex].click(),(e.ctrlKey||e.metaKey)&&Mt();return}if(e.key===`Escape`){Mt();return}if(e.key===`Tab`){e.preventDefault();let t=document.getElementById(`mcpTab`);t&&t.style.display!==`none`?Ln(`mcp`):Ln(`prompts`);return}return}if(v.activeDropdownTab===`mcp`){let t=n.querySelectorAll(`#mcpList .mcp-list-item`),r=t.length;if(e.key===`ArrowDown`){e.preventDefault(),v.selectedMcpServiceIndex<0?v.selectedMcpServiceIndex=0:v.selectedMcpServiceIndex=(v.selectedMcpServiceIndex+1)%r,kt(t);return}if(e.key===`ArrowUp`){e.preventDefault(),v.selectedMcpServiceIndex<0||v.selectedMcpServiceIndex===0?v.selectedMcpServiceIndex=r-1:--v.selectedMcpServiceIndex,kt(t);return}if(e.key===`Enter`&&v.selectedMcpServiceIndex>=0){e.preventDefault(),t[v.selectedMcpServiceIndex].click(),(e.ctrlKey||e.metaKey)&&Mt();return}if(e.key===`Escape`){Mt();return}if(e.key===`Tab`){e.preventDefault(),Ln(`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(),Ln(`skills`);return}if(n&&n.style.display!==`none`){e.preventDefault(),Ln(`mcp`);return}}if(r!==0&&e.key===`ArrowDown`){e.preventDefault(),v.selectedPromptIndex<0?v.selectedPromptIndex=0:v.selectedPromptIndex=(v.selectedPromptIndex+1)%r,En(t);return}if(e.key===`ArrowUp`){e.preventDefault(),v.selectedPromptIndex<0||v.selectedPromptIndex===0?v.selectedPromptIndex=r-1:--v.selectedPromptIndex,En(t);return}if(e.key===`Enter`&&(e.ctrlKey||e.metaKey)&&v.selectedPromptIndex>=0){e.preventDefault();let n=t[v.selectedPromptIndex].dataset.code;$r(n);return}if(e.key===`Enter`&&v.selectedPromptIndex>=0){e.preventDefault();let n=t[v.selectedPromptIndex].dataset.code;xt(n);return}if(e.key===`Escape`){Mt();return}}if(e.key===`Escape`){v.inputHistoryIndex>=0&&(v.inputHistoryIndex=-1),a.value&&(a.value=``,a.style.height=`auto`,a.dispatchEvent(new Event(`input`))),e.preventDefault();return}let c=t.style.display!==`none`&&n.classList.contains(`show`),l=r.style.display!==`none`&&i.classList.contains(`show`),u=o.style.display!==`none`&&s.classList.contains(`show`);if(e.key===`ArrowUp`&&v.inputHistoryIndex===-1&&!a.value.trim()&&!hn()&&jp()){e.preventDefault();return}if(!c&&!l&&!u){let t=cp({key:e.key,value:a.value,caret:a.selectionStart,history:v.inputHistory,index:v.inputHistoryIndex});if(t.handled){e.preventDefault(),v.inputHistoryIndex=t.index,a.value=t.value,a.dispatchEvent(new Event(`input`)),a.setSelectionRange(t.value.length,t.value.length);return}}if(e.key===`Enter`&&!e.shiftKey){if(v.isComposing)return;if(e.preventDefault(),Qd(),v.isGenerating){if(e.altKey){dn(a.value);return}yn();return}Ii()}}),a.addEventListener(`compositionstart`,()=>{v.isComposing=!0}),a.addEventListener(`compositionend`,()=>{v.isComposing=!1}),a.addEventListener(`paste`,e=>{let t=e.clipboardData?.items;if(t)for(let n of t){if(n.type.startsWith(`image/`)&&v.enableImageInput){e.preventDefault();let t=n.getAsFile();t&&Wi(t);break}if(n.kind===`file`&&v.enableFileInput){e.preventDefault();let t=n.getAsFile();t&&Ji([t]);break}}});let _e=document.getElementById(`fileAttachBtn`),ve=document.getElementById(`fileInput`);_e&&ve&&(_e.addEventListener(`click`,()=>{ve.click()}),ve.addEventListener(`change`,async()=>{if(ve.files.length>0){let e=Array.from(ve.files),n=e.filter(e=>e.type.startsWith(`image/`)),r=e.filter(e=>!e.type.startsWith(`image/`));if(n.length>0)if(v.enableImageInput)for(let e of n)await Wi(e);else k(t(`sidePanel.imageNotEnabled`)),Ji(n);r.length>0&&Ji(r),ve.value=``}}));let ye=document.querySelector(`.input-wrapper`),be=0;ye&&(ye.addEventListener(`dragenter`,e=>{e.preventDefault(),e.stopPropagation(),be++,ye.classList.add(`drag-over`)}),ye.addEventListener(`dragleave`,e=>{e.preventDefault(),e.stopPropagation(),be--,be<=0&&(be=0,ye.classList.remove(`drag-over`))}),ye.addEventListener(`dragover`,e=>{e.preventDefault(),e.stopPropagation()}),ye.addEventListener(`drop`,async e=>{e.preventDefault(),e.stopPropagation(),be=0,ye.classList.remove(`drag-over`);let n=e.dataTransfer.getData(`application/x-workspace-file`);if(n){e.preventDefault();try{let{path:e}=JSON.parse(n);if(e){gr([e]);return}}catch(e){r.warn(`[SidePanel] parse workspace dragdata failed:`,e)}}let i=Array.from(e.dataTransfer.files);if(i.length>0){e.preventDefault();let n=i.filter(e=>e.type.startsWith(`image/`)),r=i.filter(e=>!e.type.startsWith(`image/`));if(n.length>0)if(v.enableImageInput)for(let e of n)await Wi(e);else k(t(`sidePanel.imageNotEnabled`)),Ji(n);r.length>0&&Ji(r);return}let o=e.dataTransfer.getData(`text/plain`);if(o&&(e.preventDefault(),a)){a.focus();let e=a.selectionStart??a.value.length,t=a.selectionEnd??a.value.length;a.value=a.value.slice(0,e)+o+a.value.slice(t),a.selectionStart=a.selectionEnd=e+o.length,a.dispatchEvent(new Event(`input`))}}));let xe=document.getElementById(`screenshotBtn`);xe&&xe.addEventListener(`click`,async()=>{if(v.enableImageInput)try{await Or()}catch(e){r.error(`[SidePanel] screenshot failed:`,e),k(t(`sidePanel.screenshotFailed`))}}),Hn(),a.addEventListener(`wheel`,e=>{v.isScrolling=!0;let t=a.style.height||a.offsetHeight+`px`;a.style.height=t,a.scrollHeight<=a.clientHeight+10&&(e.preventDefault(),e.stopPropagation()),setTimeout(()=>{v.isScrolling=!1},100)},{passive:!1}),a.addEventListener(`input`,e=>{let t=a.value,n=document.getElementById(`promptSelector`),r=document.getElementById(`promptDropdown`);document.getElementById(`agentAtSelector`),document.getElementById(`agentAtDropdown`);let i=t.lastIndexOf(`/`),o=t.lastIndexOf(`@`),s=t.lastIndexOf(`$`),c=e=>{if(e===-1||e!==0&&t[e-1]!==`
668
+ `,a.appendChild(e)}if(r.debug(`[SidePanel] session-switched: pendingTask?`,l,`pendingSessionIds:`,[...v.pendingCallApiSessionIds],`activeSessionId:`,n,`hasCancelApi:`,!!v.pendingCancelApi),l&&(r.debug(`[SidePanel] switch back tobackground task session,rebuildstreamingoutput element`),yr(n)),Wa(n),!e.detail?.skipScrollRestore){let e=`scrollPosition_`+(n||`default`);chrome.storage.local.get([e],t=>{t[e]!==void 0&&setTimeout(async()=>{let n=document.getElementById(`chatContainer`);n&&(n.scrollTop=t[e]);let{updateScrollButtonState:r}=await E(async()=>{let{updateScrollButtonState:e}=await import(`./context-indicator-C9mzVLvn.js`).then(e=>e.pt);return{updateScrollButtonState:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]));r()},150)})}}),document.addEventListener(`session-cache-invalidate`,e=>{let{sessionId:t}=e.detail||{};t&&_h(t)}),document.querySelectorAll(`.model-option`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation();let n=e.dataset.value;v.currentModel=n,Lm(n),Dm(n),Ur()})}),document.addEventListener(`agent-model-changed`,()=>{Lm(v.currentModel);let e=document.getElementById(`tempSlider`),t=document.getElementById(`tempNumberInput`),n=document.getElementById(`tempIconValue`);e&&(e.value=v.temperature),t&&(t.value=v.temperature.toFixed(2)),n&&(n.textContent=v.temperature.toFixed(2)),_()}),document.addEventListener(`click`,e=>{let t=document.getElementById(`promptDropdown`),n=document.getElementById(`promptSelector`),r=document.getElementById(`agentAtSelector`),i=document.getElementById(`selectionFloatingMenu`);n.contains(e.target)||(t.classList.remove(`show`),Mt()),r&&!r.contains(e.target)&&an();let a=document.getElementById(`fileAtSelector`);if(a&&!a.contains(e.target)&&Jd(),i&&!i.contains(e.target)){let t=window.getSelection(),n=us(e.target),r=t&&!t.isCollapsed&&us(t.anchorNode);(!n||!r)&&window.hideFloatingMenu()}});let w=document.getElementById(`stopCompanionBtn`);function se(){let e=!!(a&&a.value&&a.value.trim())||Jr();return v.isGenerating&&e}function ce(){a&&a.value&&a.value.trim();let e=v.isGenerating,n=se();s.classList.toggle(`queue-mode`,n),s.classList.toggle(`stop-mode`,e&&!n),n?(s.innerHTML=`<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h11"/><path d="M3 12h11"/><path d="M3 18h7"/><path d="M17.5 10v8"/><path d="M14.5 15.5L17.5 18.5l3-3"/></svg>`,s.title=t(`queue.enqueueBtn`)):e?(s.innerHTML=`<svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect></svg>`,s.title=t(`sidePanel.sendBtnStop`)):(s.innerHTML=`<svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor"><path d="M12 4l-1.41 1.41L16.17 11H4v2h12.17l-5.58 5.59L12 20l8-8-8-8z"/></svg>`,s.title=t(`sidePanel.sendBtnSend`)),s.disabled=!1,s.style.opacity=``,s.style.cursor=``,w&&(w.style.display=n?``:`none`,w.disabled=!1,w.style.opacity=``,w.style.cursor=``)}s.addEventListener(`click`,()=>{if(!v.isGenerating){Mi();return}se()?mn():Pr(s)}),w?.addEventListener(`click`,()=>Pr(w));function T(e){if(!v.isGenerating)return!1;let n=v.activeSessionId;return n?En(n)?(Nn(n),Pr(w&&w.style.display!==`none`?w:e||s)?(A(t(`queue.stopAndSendStarted`),`success`,2500),!0):(Yt(n),!0)):(A(t(`queue.stopAndSendEmpty`),`warning`,3e3),!1):!1}function ue(e,{isPrimarySend:t=!1}={}){if(!e)return;let n=()=>t&&se();e.addEventListener(`contextmenu`,t=>{n()||!v.isGenerating||!En(v.activeSessionId)||(t.preventDefault(),T(e))});let r=null,i=()=>{r&&=(clearTimeout(r),null)};e.addEventListener(`pointerdown`,t=>{t.pointerType===`mouse`&&t.button!==0||n()||!v.isGenerating||!En(v.activeSessionId)||(i(),r=setTimeout(()=>{r=null,T(e)},600))});for(let t of[`pointerup`,`pointerleave`,`pointercancel`])e.addEventListener(t,i)}ue(s,{isPrimarySend:!0}),ue(w),document.addEventListener(`queue-stop-and-send`,()=>{T(w&&w.style.display!==`none`?w:s)}),document.addEventListener(`generating-state-changed`,ce),a.addEventListener(`input`,ce),document.addEventListener(`input-attachments-changed`,ce),document.addEventListener(`voice-draft-written`,ce);let de=document.getElementById(`shortcutsBtn`),D=document.getElementById(`shortcutsModal`),fe=document.getElementById(`shortcutsCloseBtn`);function pe(){D&&(D.style.display=`flex`)}function me(){D&&(D.style.display=`none`)}de&&de.addEventListener(`click`,e=>{e.stopPropagation(),pe();let t=document.getElementById(`headerMoreDropdown`);t&&t.classList.remove(`show`)}),fe&&fe.addEventListener(`click`,me),D&&D.addEventListener(`click`,e=>{e.target===D&&me()});let he=ls();bn(),Zn({adjustInputHeight:ee}).catch(e=>{r.warn(`[SidePanel] initVoiceInput failed:`,e?.message||e)}),document.addEventListener(`keydown`,e=>{if((e.ctrlKey||e.metaKey)&&e.key===`t`){e.preventDefault();let t=document.getElementById(`toolsPopup`);t&&t.style.display!==`none`?Di():Fi()}if(e.key===`Escape`&&Wn()){e.preventDefault();return}if(!(e.key===`Escape`&&he.handleEscape())){if(e.key===`Escape`&&D&&D.style.display!==`none`){me();return}if(e.altKey&&e.code===`Slash`){e.preventDefault(),pe();return}if(e.altKey&&!e.shiftKey&&e.code===`KeyS`&&!e.ctrlKey&&!e.metaKey){e.preventDefault(),Pi();return}if(e.altKey&&e.shiftKey&&e.code===`KeyS`&&!e.ctrlKey&&!e.metaKey){e.preventDefault(),Tr();return}if(Gt(e)){e.preventDefault(),sn();return}if(e.altKey&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&e.code===`KeyN`){e.preventDefault(),ui();return}if(e.altKey&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&e.code===`KeyW`){e.preventDefault(),kr();return}if(e.altKey&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&e.code===`KeyE`){e.preventDefault();let t=document.querySelectorAll(`#chatContainer .message.user`),n=t[t.length-1];if(n){Wt(n);let e=document.getElementById(`userInput`);e&&e.focus()}return}if(e.altKey&&(e.key===`ArrowUp`||e.key===`ArrowDown`)){e.preventDefault();let t=e.key===`ArrowUp`?`prev`:`next`;he.jumpToMessage(t,e.ctrlKey||e.metaKey),he.updateActiveQuestion();return}}}),a.addEventListener(`keydown`,e=>{let t=document.getElementById(`promptSelector`),n=document.getElementById(`promptDropdown`),r=document.getElementById(`agentAtSelector`),i=document.getElementById(`agentAtDropdown`);if(r.style.display!==`none`&&i.classList.contains(`show`)){let t=document.getElementById(`agentAtTabs`),n=t&&t.classList.contains(`merged-mode`);if(!n&&e.key===`Tab`){e.preventDefault();let t=Array.from(document.querySelectorAll(`#agentAtTabs .prompt-tab`)).map(e=>e.dataset.tab),n=e=>{let t=document.querySelector(`#agentAtTabs .prompt-tab[data-tab="${e}"]`);return!!t&&t.style.display!==`none`},r=t.indexOf(Dt);for(let e=0;e<t.length;e++)if(r=(r+1)%t.length,n(t[r])){li(t[r]);break}return}let r,i;n?(r=document.getElementById(`agentAtList`),i=v.selectedAgentAtIndex):Dt===`pages`?(r=document.getElementById(`agentPageList`),i=v.selectedPageIndex):Dt===`proxies`?(r=document.getElementById(`agentProxyList`),i=v.selectedProxyAtIndex):Dt===`knowledge`?(r=document.getElementById(`agentKnowledgeList`),i=v.selectedKnowledgeAtIndex):(r=document.getElementById(`agentAtList`),i=v.selectedAgentAtIndex);let a=r?r.querySelectorAll(`.prompt-item`):[],o=a.length;if(o!==0){if(e.key===`ArrowDown`){e.preventDefault();let t=i<0?0:(i+1)%o;n?(v.selectedAgentAtIndex=t,Ci(a)):Dt===`proxies`?(v.selectedProxyAtIndex=t,Ci(a)):Dt===`knowledge`?(v.selectedKnowledgeAtIndex=t,Ci(a)):Dt===`pages`?(v.selectedPageIndex=t,na(a)):(v.selectedAgentAtIndex=t,Ci(a));return}else if(e.key===`ArrowUp`){e.preventDefault();let t=i<0||i===0?o-1:i-1;n?(v.selectedAgentAtIndex=t,Ci(a)):Dt===`proxies`?(v.selectedProxyAtIndex=t,Ci(a)):Dt===`knowledge`?(v.selectedKnowledgeAtIndex=t,Ci(a)):Dt===`pages`?(v.selectedPageIndex=t,na(a)):(v.selectedAgentAtIndex=t,Ci(a));return}else if(e.key===`Enter`&&i>=0){e.preventDefault(),a[i].click(),(e.ctrlKey||e.metaKey)&&an();return}else if(e.key===`Escape`){an();return}}}let o=document.getElementById(`fileAtSelector`),s=document.getElementById(`fileAtDropdown`);if(o&&s&&o.style.display!==`none`&&s.classList.contains(`show`)){let t=document.getElementById(`fileAtList`),n=t?t.querySelectorAll(`.prompt-item`):[],r=n.length;if(e.key===`ArrowDown`||e.key===`ArrowUp`){e.preventDefault(),r>0&&(v.selectedFileAtIndex=e.key===`ArrowDown`?v.selectedFileAtIndex<0?0:(v.selectedFileAtIndex+1)%r:v.selectedFileAtIndex<0||v.selectedFileAtIndex===0?r-1:v.selectedFileAtIndex-1,$d(n));return}if(e.key===`Enter`&&r>0&&v.selectedFileAtIndex>=0){e.preventDefault(),n[v.selectedFileAtIndex].click();return}if(e.key===`Escape`){e.preventDefault(),Jd();return}}if(t.style.display!==`none`&&n.classList.contains(`show`)){if(v.showMergedList){let t=n.querySelectorAll(`#promptList .prompt-item`),r=t.length;if(e.key===`ArrowDown`){e.preventDefault(),v.selectedPromptIndex<0?v.selectedPromptIndex=0:v.selectedPromptIndex=(v.selectedPromptIndex+1)%r,Tn(t);return}if(e.key===`ArrowUp`){e.preventDefault(),v.selectedPromptIndex<0||v.selectedPromptIndex===0?v.selectedPromptIndex=r-1:--v.selectedPromptIndex,Tn(t);return}if(e.key===`Enter`&&v.selectedPromptIndex>=0){e.preventDefault();let n=t[v.selectedPromptIndex];n.dataset.type===`skill`||n.dataset.type===`mcp`?(n.click(),(e.ctrlKey||e.metaKey)&&Mt()):e.ctrlKey||e.metaKey?Zr(n.dataset.code):bt(n.dataset.code);return}if(e.key===`Escape`){Mt();return}return}if(v.activeDropdownTab===`skills`){let t=n.querySelectorAll(`#skillList .skill-list-item`),r=t.length;if(e.key===`ArrowDown`){e.preventDefault(),v.selectedSkillIndex<0?v.selectedSkillIndex=0:v.selectedSkillIndex=(v.selectedSkillIndex+1)%r,Vi(t);return}if(e.key===`ArrowUp`){e.preventDefault(),v.selectedSkillIndex<0||v.selectedSkillIndex===0?v.selectedSkillIndex=r-1:--v.selectedSkillIndex,Vi(t);return}if(e.key===`Enter`&&v.selectedSkillIndex>=0){e.preventDefault(),t[v.selectedSkillIndex].click(),(e.ctrlKey||e.metaKey)&&Mt();return}if(e.key===`Escape`){Mt();return}if(e.key===`Tab`){e.preventDefault();let t=document.getElementById(`mcpTab`);t&&t.style.display!==`none`?In(`mcp`):In(`prompts`);return}return}if(v.activeDropdownTab===`mcp`){let t=n.querySelectorAll(`#mcpList .mcp-list-item`),r=t.length;if(e.key===`ArrowDown`){e.preventDefault(),v.selectedMcpServiceIndex<0?v.selectedMcpServiceIndex=0:v.selectedMcpServiceIndex=(v.selectedMcpServiceIndex+1)%r,Ot(t);return}if(e.key===`ArrowUp`){e.preventDefault(),v.selectedMcpServiceIndex<0||v.selectedMcpServiceIndex===0?v.selectedMcpServiceIndex=r-1:--v.selectedMcpServiceIndex,Ot(t);return}if(e.key===`Enter`&&v.selectedMcpServiceIndex>=0){e.preventDefault(),t[v.selectedMcpServiceIndex].click(),(e.ctrlKey||e.metaKey)&&Mt();return}if(e.key===`Escape`){Mt();return}if(e.key===`Tab`){e.preventDefault(),In(`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(),In(`skills`);return}if(n&&n.style.display!==`none`){e.preventDefault(),In(`mcp`);return}}if(r!==0&&e.key===`ArrowDown`){e.preventDefault(),v.selectedPromptIndex<0?v.selectedPromptIndex=0:v.selectedPromptIndex=(v.selectedPromptIndex+1)%r,Tn(t);return}if(e.key===`ArrowUp`){e.preventDefault(),v.selectedPromptIndex<0||v.selectedPromptIndex===0?v.selectedPromptIndex=r-1:--v.selectedPromptIndex,Tn(t);return}if(e.key===`Enter`&&(e.ctrlKey||e.metaKey)&&v.selectedPromptIndex>=0){e.preventDefault();let n=t[v.selectedPromptIndex].dataset.code;Zr(n);return}if(e.key===`Enter`&&v.selectedPromptIndex>=0){e.preventDefault();let n=t[v.selectedPromptIndex].dataset.code;bt(n);return}if(e.key===`Escape`){Mt();return}}if(e.key===`Escape`){v.inputHistoryIndex>=0&&(v.inputHistoryIndex=-1),a.value&&(a.value=``,a.style.height=`auto`,a.dispatchEvent(new Event(`input`))),e.preventDefault();return}let c=t.style.display!==`none`&&n.classList.contains(`show`),l=r.style.display!==`none`&&i.classList.contains(`show`),u=o.style.display!==`none`&&s.classList.contains(`show`);if(e.key===`ArrowUp`&&v.inputHistoryIndex===-1&&!a.value.trim()&&!Jr()&&Dp()){e.preventDefault();return}if(!c&&!l&&!u){let t=ip({key:e.key,value:a.value,caret:a.selectionStart,history:v.inputHistory,index:v.inputHistoryIndex});if(t.handled){e.preventDefault(),v.inputHistoryIndex=t.index,a.value=t.value,a.dispatchEvent(new Event(`input`)),a.setSelectionRange(t.value.length,t.value.length);return}}if(e.key===`Enter`&&!e.shiftKey){if(v.isComposing)return;if(e.preventDefault(),Jd(),v.isGenerating){if(e.altKey){$t(a.value);return}mn();return}Mi()}}),a.addEventListener(`compositionstart`,()=>{v.isComposing=!0}),a.addEventListener(`compositionend`,()=>{v.isComposing=!1}),a.addEventListener(`paste`,e=>{let t=e.clipboardData?.items;if(t)for(let n of t){if(n.type.startsWith(`image/`)&&v.enableImageInput){e.preventDefault();let t=n.getAsFile();t&&kt(t);break}if(n.kind===`file`&&v.enableFileInput){e.preventDefault();let t=n.getAsFile();t&&_r([t]);break}}});let ge=document.getElementById(`fileAttachBtn`),_e=document.getElementById(`fileInput`);ge&&_e&&(ge.addEventListener(`click`,()=>{_e.click()}),_e.addEventListener(`change`,async()=>{if(_e.files.length>0){let e=Array.from(_e.files),n=e.filter(e=>e.type.startsWith(`image/`)),r=e.filter(e=>!e.type.startsWith(`image/`));if(n.length>0)if(v.enableImageInput)for(let e of n)await kt(e);else A(t(`sidePanel.imageNotEnabled`)),_r(n);r.length>0&&_r(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){Wr([e]);return}}catch(e){r.warn(`[SidePanel] parse workspace dragdata failed:`,e)}}let i=Array.from(e.dataTransfer.files);if(i.length>0){e.preventDefault();let n=i.filter(e=>e.type.startsWith(`image/`)),r=i.filter(e=>!e.type.startsWith(`image/`));if(n.length>0)if(v.enableImageInput)for(let e of n)await kt(e);else A(t(`sidePanel.imageNotEnabled`)),_r(n);r.length>0&&_r(r);return}let o=e.dataTransfer.getData(`text/plain`);if(o&&(e.preventDefault(),a)){a.focus();let e=a.selectionStart??a.value.length,t=a.selectionEnd??a.value.length;a.value=a.value.slice(0,e)+o+a.value.slice(t),a.selectionStart=a.selectionEnd=e+o.length,a.dispatchEvent(new Event(`input`))}}));let be=document.getElementById(`screenshotBtn`);be&&be.addEventListener(`click`,async()=>{if(v.enableImageInput)try{await Pi()}catch(e){r.error(`[SidePanel] screenshot failed:`,e),A(t(`sidePanel.screenshotFailed`))}}),Hi(),a.addEventListener(`wheel`,e=>{v.isScrolling=!0;let t=a.style.height||a.offsetHeight+`px`;a.style.height=t,a.scrollHeight<=a.clientHeight+10&&(e.preventDefault(),e.stopPropagation()),setTimeout(()=>{v.isScrolling=!1},100)},{passive:!1}),a.addEventListener(`input`,e=>{let t=a.value,n=document.getElementById(`promptSelector`),r=document.getElementById(`promptDropdown`);document.getElementById(`agentAtSelector`),document.getElementById(`agentAtDropdown`);let i=t.lastIndexOf(`/`),o=t.lastIndexOf(`@`),s=t.lastIndexOf(`$`),c=e=>{if(e===-1||e!==0&&t[e-1]!==`
669
669
  `&&t[e-1]!==` `)return!1;let n=t.substring(e+1);return!(n.includes(` `)||n.includes(`
670
- `))},l=c(i),u=c(o),d=c(s),f=null;if(l&&(f={key:`slash`,index:i}),u&&(!f||o>f.index)&&(f={key:`at`,index:o}),d&&(!f||s>f.index)&&(f={key:`dollar`,index:s}),f&&f.key===`dollar`)Mt(),sr(),Zd(t.substring(s+1));else if(f&&f.key===`at`)Mt(),Qd(),fi(t.substring(o+1));else if(f&&f.key===`slash`){sr(),Qd();let e=t.substring(i+1);n.style.display!==`none`&&r.classList.contains(`show`)?vn(e):mn(e)}else Mt(),sr(),Qd();ee()});let Se=lp((e,t)=>{chrome.storage.local.set({[e]:t})},200);u.addEventListener(`scroll`,()=>{Se(`scrollPosition_`+(v.activeSessionId||`default`),u.scrollTop)}),window.addEventListener(`pagehide`,()=>{chrome.storage.local.set({[`scrollPosition_`+(v.activeSessionId||`default`)]:u.scrollTop})});let Ce=document.getElementById(`headerMoreBtn`),we=document.getElementById(`headerMoreDropdown`);Ce&&we&&(Ce.addEventListener(`click`,e=>{e.stopPropagation(),we.classList.toggle(`show`)}),document.addEventListener(`click`,e=>{!we.contains(e.target)&&e.target!==Ce&&Ae()}));let Te=document.getElementById(`themeToggleBtn`),Ee=document.getElementById(`themeToggleLabel`),De=document.getElementById(`themeSubmenu`),Oe=e=>t(e===`dark`?`settings.themeDark`:e===`system`?`settings.themeSystem`:`settings.themeLight`),ke=()=>{let e=st();Ee&&(Ee.textContent=t(`header.themeToggle`,{theme:Oe(e)})),De&&De.querySelectorAll(`.theme-submenu-item`).forEach(t=>{t.classList.toggle(`active`,t.dataset.themeValue===e)}),Te&&Te.setAttribute(`aria-expanded`,String(!!(De&&De.classList.contains(`show`))))};function Ae(){De&&De.classList.remove(`show`),we&&we.classList.remove(`show`),Te&&Te.setAttribute(`aria-expanded`,`false`)}Te&&De&&(Te.addEventListener(`click`,e=>{e.stopPropagation(),De.classList.toggle(`show`),ke()}),De.querySelectorAll(`.theme-submenu-item`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),Ke(e.dataset.themeValue),Ae()})})),ke(),lt(ke),o(ke),c.addEventListener(`click`,e=>{e.stopPropagation(),Ae(),Jr()}),l&&l.addEventListener(`click`,e=>{e.stopPropagation(),Ae(),Cn()});let je=document.getElementById(`importChatBtn`);je&&je.addEventListener(`click`,e=>{e.stopPropagation(),Ae(),ei()});let Me=document.getElementById(`importSessionsFile`);Me&&Me.addEventListener(`change`,e=>{let t=e.target.files[0];t&&Lt(t)});let Ne=document.getElementById(`settingsBtn`);Ne&&Ne.addEventListener(`click`,()=>{chrome.runtime.openOptionsPage()});let Pe=document.getElementById(`headerAgentIndicator`);Pe&&Pe.addEventListener(`click`,async()=>{let e=chrome.runtime.getURL(`options.html#agent`),t=await chrome.tabs.query({url:chrome.runtime.getURL(`options.html`)});t.length>0?await chrome.tabs.update(t[0].id,{active:!0,url:e}):await chrome.tabs.create({url:e})});let Fe=document.getElementById(`prototypeLibraryBtn`);Fe&&Fe.addEventListener(`click`,e=>{e.stopPropagation(),Ae(),Mr()});let D=document.getElementById(`tokenStatsHeaderBtn`);D&&D.addEventListener(`click`,e=>{e.stopPropagation(),Ae(),window.openTokenStats&&window.openTokenStats()});let Ie=document.getElementById(`auditLogBtn`),Le=document.getElementById(`auditLogOverlay`),Re=document.getElementById(`auditLogClose`),ze=document.getElementById(`auditLogRefreshBtn`),Be=document.getElementById(`auditLogCategoryFilter`),Ve=document.getElementById(`auditLogLimit`),He=document.getElementById(`auditLogSearch`),Ue=document.getElementById(`auditLogSearchClear`),We=document.getElementById(`auditLogLoading`),Ge=document.getElementById(`auditLogEmpty`),O=document.getElementById(`auditLogList`),qe=[],Je={auth:t(`sidePanel.auditCategoryAuth`),fs:t(`sidePanel.auditCategoryFs`),exec:t(`sidePanel.auditCategoryExec`),security:t(`sidePanel.auditCategorySecurity`),system:t(`sidePanel.auditCategorySystem`)},Ye={info:`INFO`,warn:`WARN`,error:`ERROR`},Xe={info:`audit-level-info`,warn:`audit-level-warn`,error:`audit-level-error`};function Ze(e){if(!e)return`-`;let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())} ${n(t.getHours())}:${n(t.getMinutes())}:${n(t.getSeconds())}`}function $e(e){let n=new Set([`timestamp`,`level`,`category`,`action`]),r=[];for(let[t,i]of Object.entries(e)){if(n.has(t))continue;let e=typeof i==`string`?i:JSON.stringify(i),a=e.length>60?e.slice(0,60)+`...`:e;r.push(`${t}: ${a}`)}return r.join(t(`sidePanel.auditDetailSeparator`))}async function et(){if(!We||!Ge||!O)return;We.style.display=`block`,Ge.style.display=`none`,O.style.display=`none`;let e=Be?.value||null,n=parseInt(Ve?.value||`200`,10);try{let r=await new Promise((t,r)=>{chrome.runtime.sendMessage({type:`QUERY_AUDIT_LOGS`,category:e,limit:n},e=>{chrome.runtime.lastError?r(Error(chrome.runtime.lastError.message)):t(e)})});if(We.style.display=`none`,!r||!r.success){Ge.style.display=`block`,Ge.textContent=t(`sidePanel.auditQueryFailed`,{error:r?.error||t(`sidePanel.unknownError`)});return}qe=r.entries||[],tt()}catch(e){We.style.display=`none`,Ge.style.display=`block`,Ge.textContent=t(`sidePanel.auditLoadFailed`,{error:e.message})}}function tt(){if(!O)return;let e=(He?.value||``).trim().toLowerCase(),n=qe;if(e&&(n=n.filter(t=>[t.action||``,t.category||``,...Object.entries(t).filter(([e])=>![`timestamp`,`level`,`category`,`action`].includes(e)).map(([,e])=>typeof e==`string`?e:JSON.stringify(e))].join(` `).toLowerCase().includes(e))),Ue&&(Ue.style.display=e?`block`:`none`),We.style.display=`none`,n.length===0){Ge.style.display=`block`,Ge.textContent=t(e?`sidePanel.auditNoMatch`:`sidePanel.auditEmpty`),O.style.display=`none`;return}Ge.style.display=`none`,O.style.display=`block`,O.innerHTML=n.map(e=>{let t=A(Je[e.category]||e.category||`-`),n=A(Ye[e.level]||e.level?.toUpperCase()||`INFO`),r=Xe[e.level]||`audit-level-info`,i=Ze(e.timestamp),a=A($e(e));return`<div class="audit-entry">
670
+ `))},l=c(i),u=c(o),d=c(s),f=null;if(l&&(f={key:`slash`,index:i}),u&&(!f||o>f.index)&&(f={key:`at`,index:o}),d&&(!f||s>f.index)&&(f={key:`dollar`,index:s}),f&&f.key===`dollar`)Mt(),an(),qd(t.substring(s+1));else if(f&&f.key===`at`)Mt(),Jd(),Ai(t.substring(o+1));else if(f&&f.key===`slash`){an(),Jd();let e=t.substring(i+1);n.style.display!==`none`&&r.classList.contains(`show`)?_n(e):pn(e)}else Mt(),an(),Jd();ee()});let xe=ap((e,t)=>{chrome.storage.local.set({[e]:t})},200);u.addEventListener(`scroll`,()=>{xe(`scrollPosition_`+(v.activeSessionId||`default`),u.scrollTop)}),window.addEventListener(`pagehide`,()=>{chrome.storage.local.set({[`scrollPosition_`+(v.activeSessionId||`default`)]:u.scrollTop})});let Se=document.getElementById(`headerMoreBtn`),Ce=document.getElementById(`headerMoreDropdown`);Se&&Ce&&(Se.addEventListener(`click`,e=>{e.stopPropagation(),Ce.classList.toggle(`show`)}),document.addEventListener(`click`,e=>{!Ce.contains(e.target)&&e.target!==Se&&ke()}));let we=document.getElementById(`themeToggleBtn`),Te=document.getElementById(`themeToggleLabel`),Ee=document.getElementById(`themeSubmenu`),De=e=>t(e===`dark`?`settings.themeDark`:e===`system`?`settings.themeSystem`:`settings.themeLight`),Oe=()=>{let e=ot();Te&&(Te.textContent=t(`header.themeToggle`,{theme:De(e)})),Ee&&Ee.querySelectorAll(`.theme-submenu-item`).forEach(t=>{t.classList.toggle(`active`,t.dataset.themeValue===e)}),we&&we.setAttribute(`aria-expanded`,String(!!(Ee&&Ee.classList.contains(`show`))))};function ke(){Ee&&Ee.classList.remove(`show`),Ce&&Ce.classList.remove(`show`),we&&we.setAttribute(`aria-expanded`,`false`)}we&&Ee&&(we.addEventListener(`click`,e=>{e.stopPropagation(),Ee.classList.toggle(`show`),Oe()}),Ee.querySelectorAll(`.theme-submenu-item`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),Ge(e.dataset.themeValue),ke()})})),Oe(),ct(Oe),o(Oe),c.addEventListener(`click`,e=>{e.stopPropagation(),ke(),Kr()}),l&&l.addEventListener(`click`,e=>{e.stopPropagation(),ke(),Nt()});let Ae=document.getElementById(`importChatBtn`);Ae&&Ae.addEventListener(`click`,e=>{e.stopPropagation(),ke(),Sn()});let je=document.getElementById(`importSessionsFile`);je&&je.addEventListener(`change`,e=>{let t=e.target.files[0];t&&Bn(t)});let Me=document.getElementById(`settingsBtn`);Me&&Me.addEventListener(`click`,()=>{chrome.runtime.openOptionsPage()});let Ne=document.getElementById(`headerAgentIndicator`);Ne&&Ne.addEventListener(`click`,async()=>{let e=chrome.runtime.getURL(`options.html#agent`),t=await chrome.tabs.query({url:chrome.runtime.getURL(`options.html`)});t.length>0?await chrome.tabs.update(t[0].id,{active:!0,url:e}):await chrome.tabs.create({url:e})});let Pe=document.getElementById(`prototypeLibraryBtn`);Pe&&Pe.addEventListener(`click`,e=>{e.stopPropagation(),ke(),vt()});let O=document.getElementById(`tokenStatsHeaderBtn`);O&&O.addEventListener(`click`,e=>{e.stopPropagation(),ke(),window.openTokenStats&&window.openTokenStats()});let Fe=document.getElementById(`auditLogBtn`),Ie=document.getElementById(`auditLogOverlay`),Le=document.getElementById(`auditLogClose`),Re=document.getElementById(`auditLogRefreshBtn`),ze=document.getElementById(`auditLogCategoryFilter`),Be=document.getElementById(`auditLogLimit`),Ve=document.getElementById(`auditLogSearch`),He=document.getElementById(`auditLogSearchClear`),Ue=document.getElementById(`auditLogLoading`),We=document.getElementById(`auditLogEmpty`),k=document.getElementById(`auditLogList`),Ke=[],qe={auth:t(`sidePanel.auditCategoryAuth`),fs:t(`sidePanel.auditCategoryFs`),exec:t(`sidePanel.auditCategoryExec`),security:t(`sidePanel.auditCategorySecurity`),system:t(`sidePanel.auditCategorySystem`)},Je={info:`INFO`,warn:`WARN`,error:`ERROR`},Ye={info:`audit-level-info`,warn:`audit-level-warn`,error:`audit-level-error`};function Xe(e){if(!e)return`-`;let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())} ${n(t.getHours())}:${n(t.getMinutes())}:${n(t.getSeconds())}`}function Qe(e){let n=new Set([`timestamp`,`level`,`category`,`action`]),r=[];for(let[t,i]of Object.entries(e)){if(n.has(t))continue;let e=typeof i==`string`?i:JSON.stringify(i),a=e.length>60?e.slice(0,60)+`...`:e;r.push(`${t}: ${a}`)}return r.join(t(`sidePanel.auditDetailSeparator`))}async function $e(){if(!Ue||!We||!k)return;Ue.style.display=`block`,We.style.display=`none`,k.style.display=`none`;let e=ze?.value||null,n=parseInt(Be?.value||`200`,10);try{let r=await new Promise((t,r)=>{chrome.runtime.sendMessage({type:`QUERY_AUDIT_LOGS`,category:e,limit:n},e=>{chrome.runtime.lastError?r(Error(chrome.runtime.lastError.message)):t(e)})});if(Ue.style.display=`none`,!r||!r.success){We.style.display=`block`,We.textContent=t(`sidePanel.auditQueryFailed`,{error:r?.error||t(`sidePanel.unknownError`)});return}Ke=r.entries||[],et()}catch(e){Ue.style.display=`none`,We.style.display=`block`,We.textContent=t(`sidePanel.auditLoadFailed`,{error:e.message})}}function et(){if(!k)return;let e=(Ve?.value||``).trim().toLowerCase(),n=Ke;if(e&&(n=n.filter(t=>[t.action||``,t.category||``,...Object.entries(t).filter(([e])=>![`timestamp`,`level`,`category`,`action`].includes(e)).map(([,e])=>typeof e==`string`?e:JSON.stringify(e))].join(` `).toLowerCase().includes(e))),He&&(He.style.display=e?`block`:`none`),Ue.style.display=`none`,n.length===0){We.style.display=`block`,We.textContent=t(e?`sidePanel.auditNoMatch`:`sidePanel.auditEmpty`),k.style.display=`none`;return}We.style.display=`none`,k.style.display=`block`,k.innerHTML=n.map(e=>{let t=j(qe[e.category]||e.category||`-`),n=j(Je[e.level]||e.level?.toUpperCase()||`INFO`),r=Ye[e.level]||`audit-level-info`,i=Xe(e.timestamp),a=j(Qe(e));return`<div class="audit-entry">
671
671
  <div class="audit-entry-header">
672
672
  <span class="audit-time">${i}</span>
673
673
  <span class="audit-level ${r}">${n}</span>
674
674
  <span class="audit-category">${t}</span>
675
- <span class="audit-action">${A(e.action||`-`)}</span>
675
+ <span class="audit-action">${j(e.action||`-`)}</span>
676
676
  </div>
677
677
  ${a?`<div class="audit-details">${a}</div>`:``}
678
- </div>`}).join(``)}function rt(){Le&&(Le.style.display=`flex`,et())}function at(){Le&&(Le.style.display=`none`)}Ie&&Ie.addEventListener(`click`,e=>{e.stopPropagation(),Ae(),rt()}),Re&&Re.addEventListener(`click`,at),ze&&ze.addEventListener(`click`,et),Be&&Be.addEventListener(`change`,et),Ve&&Ve.addEventListener(`change`,et),He&&He.addEventListener(`input`,()=>{tt()}),Ue&&Ue.addEventListener(`click`,()=>{He&&(He.value=``),tt()}),wm(()=>v.activeSessionId,window.showCustomConfirm);let ut=document.getElementById(`isolateChatBtn`),dt=document.getElementById(`enableToolsBtn`),pt=document.getElementById(`toolsConfigBtn`),mt=`agentEnabledTools_${v.activeAgentId||`default`}`,ht=`agentMcpClosedServers_${v.activeAgentId||`default`}`;chrome.storage.local.get([mt,`enabledTools`,`isolateChat`,`enableSelectionQuery`,`enableTools`,ht,`mcpTools`,`mcpEnabled`,`ragTools`,`ragToolsIntroduced`],e=>{e.isolateChat!==void 0&&(v.isolateChat=e.isolateChat),ut.checked=v.isolateChat,e.enableSelectionQuery!==void 0&&(v.enableSelectionQuery=e.enableSelectionQuery);let t=document.getElementById(`enableSelectionQueryBtn`);t&&(t.checked=v.enableSelectionQuery),e.enableTools!==void 0&&(v.useTools=e.enableTools),v.activeAgentId&&T(async()=>{let{getAgent:e}=await import(`./agent-store-CE4-QMOA.js`).then(e=>e.t);return{getAgent:e}},__vite__mapDeps([7,1,2,3])).then(({getAgent:e})=>e(v.activeAgentId)).then(e=>{v.activeAgentMcpExcludedServerIds=e?e.mcpExcludedServerIds??null:null,xr()}).catch(()=>{}),v.mcpClosedServers=e[ht]||[];let n=e.ragTools||[],r=e[mt],i=e.enabledTools;if(Array.isArray(r)){let t=ai(n);v.enabledTools=r.filter(e=>t.has(e));let i=ji(v.enabledTools,n,e.ragToolsIntroduced);v.enabledTools=i.tools,i.migrated?chrome.storage.local.set({ragToolsIntroduced:!0,[mt]:v.enabledTools}):v.enabledTools.length!==r.length&&chrome.storage.local.set({[mt]:v.enabledTools})}else if(i&&i.length>0){let t=ai(n),r=i.filter(e=>t.has(e)),a=f.filter(e=>e.enabled&&!r.includes(e.id)).map(e=>e.id);v.enabledTools=[...r,...a];let o=ji(v.enabledTools,n,e.ragToolsIntroduced);v.enabledTools=o.tools,chrome.storage.local.set({[mt]:v.enabledTools,...o.migrated?{ragToolsIntroduced:!0}:{}})}else{v.enabledTools=f.filter(e=>e.enabled).map(e=>e.id);let t=ji(v.enabledTools,n,e.ragToolsIntroduced);v.enabledTools=t.tools,t.migrated&&chrome.storage.local.set({ragToolsIntroduced:!0,[mt]:v.enabledTools})}dt&&(dt.checked=v.useTools),xr(),Rm(),S()}),ut.addEventListener(`change`,()=>{v.isolateChat=ut.checked,chrome.storage.local.set({isolateChat:v.isolateChat}),r.debug(`[SidePanel] conv memory:`,v.isolateChat?`enabled`:`disabled`)});let gt=document.getElementById(`enableSelectionQueryBtn`);gt&&gt.addEventListener(`change`,()=>{v.enableSelectionQuery=gt.checked,chrome.storage.local.set({enableSelectionQuery:v.enableSelectionQuery}),r.debug(`[SidePanel] text Q&A:`,v.enableSelectionQuery?`enabled`:`disabled`),!v.enableSelectionQuery&&v.selectedContextText&&Gn()}),dt&&dt.addEventListener(`change`,()=>{v.useTools=dt.checked,chrome.storage.local.set({enableTools:v.useTools}),r.debug(`[SidePanel] tool master switch:`,v.useTools?`enabled`:`disabled`),xr()}),pt&&pt.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),kr()});let yt=document.getElementById(`toolsPopupOverlay`),bt=document.getElementById(`toolsPopupClose`),St=yt?yt.querySelector(`.modal-container`):null;bt&&bt.addEventListener(`click`,Tr),St&&St.addEventListener(`click`,e=>{e.stopPropagation()});let Ct=document.getElementById(`toolsSearchInput`),Tt=document.getElementById(`toolsSearchClear`);Ct&&Ct.addEventListener(`input`,e=>{v.currentSearch=e.target.value.toLowerCase(),Tt&&(Tt.style.display=e.target.value?``:`none`),xi()}),Tt&&Tt.addEventListener(`click`,()=>{Ct&&(Ct.value=``,Tt.style.display=`none`,v.currentSearch=``,xi())});let Et=document.querySelectorAll(`.category-btn`);Et.forEach(e=>{e.addEventListener(`click`,()=>{Et.forEach(e=>{e.classList.remove(`active`),e.classList.contains(`category-all`)?(e.style.background=`var(--brand-violet-soft-bg)`,e.style.color=`var(--brand-500)`,e.style.borderColor=`var(--brand-violet-soft-border)`):(e.style.background=`var(--bg-surface)`,e.style.color=`var(--text-secondary)`,e.style.borderColor=`var(--border-subtle)`)}),e.classList.add(`active`),e.style.background=`linear-gradient(135deg, var(--brand-500) 0%, var(--brand-accent) 100%)`,e.style.color=`var(--text-on-brand)`,e.style.borderColor=`transparent`,v.currentCategory=e.dataset.category,xi()})});let Dt=document.getElementById(`toolsCategories`);Dt&&Dt.addEventListener(`wheel`,e=>{e.preventDefault(),Dt.scrollLeft+=e.deltaY*2},{passive:!1});let At=document.getElementById(`toolsSelectAll`),jt=document.getElementById(`toolsSelectNone`);At&&At.addEventListener(`click`,()=>{Ri().forEach(e=>{let t=document.getElementById(`tool_`+e.id);t&&(t.checked=!0),v.enabledTools.includes(e.id)||v.enabledTools.push(e.id)}),Wr(!0),Br(),pr(),$i()}),jt&&jt.addEventListener(`click`,()=>{Ri().forEach(e=>{let t=document.getElementById(`tool_`+e.id);t&&(t.checked=!1);let n=v.enabledTools.indexOf(e.id);n>-1&&v.enabledTools.splice(n,1)}),Wr(!1),Br(),pr(),$i()});let Nt=document.getElementById(`toolsPopupSave`);Nt&&Nt.addEventListener(`click`,()=>{li(),$i()});let Pt=document.getElementById(`toolsPreselectToggle`);Pt&&Pt.addEventListener(`change`,()=>{chrome.storage.local.set({enableToolPreselect:Pt.checked},()=>{r.debug(`[SidePanel] toolpre-filter toggle updated:`,Pt.checked)})});let Ft=document.getElementById(`toolConfirmToggle`);Ft&&Ft.addEventListener(`change`,()=>{chrome.storage.local.set({toolConfirmationEnabled:Ft.checked},()=>{r.debug(`[SidePanel] sensitive-operation confirmation toggle updated:`,Ft.checked)})});let Rt=document.getElementById(`toolsPopupCancel`);Rt&&Rt.addEventListener(`click`,()=>{Tr()});let zt=document.getElementById(`modalCancelBtn`),Bt=document.getElementById(`modalConfirmBtn`),Ht=document.getElementById(`toolStatsOverlay`),Ut=document.getElementById(`toolStatsClose`),Kt=document.getElementById(`toolStatsBtn`);function qt(){Ht&&(Ht.style.display=`flex`,$t())}function Yt(){Ht&&(Ht.style.display=`none`)}Kt&&Kt.addEventListener(`click`,e=>{e.stopPropagation(),qt()}),Ut&&Ut.addEventListener(`click`,Yt),Ht&&Ht.addEventListener(`click`,e=>{e.target===Ht&&Yt()});let Xt=document.getElementById(`toolStatsRefreshBtn`);Xt&&Xt.addEventListener(`click`,$t);let Zt=document.getElementById(`toolStatsClearBtn`);Zt&&Zt.addEventListener(`click`,async()=>{await window.showCustomConfirm(t(`sidePanel.clearStatsConfirm`),t(`sidePanel.clearStatsTitle`))&&(await chrome.storage.local.remove([`toolUsageStats`]),$t())});let Qt={column:`callCount`,asc:!1};async function $t(){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}),en(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 en(e,t){let n=document.getElementById(`toolStatsTableBody`);if(!n)return;let{column:r,asc:i}=Qt;n.innerHTML=[...e].sort((e,t)=>{let[n,a]=e,[o,s]=t,c=a.callCount>0?a.successCount/a.callCount*100:0,l=s.callCount>0?s.successCount/s.callCount*100:0,u=a.callCount>0?a.totalDuration/a.callCount:0,d=s.callCount>0?s.totalDuration/s.callCount:0,f=0;switch(r){case`name`:f=n.toLowerCase().localeCompare(o.toLowerCase());break;case`callCount`:f=a.callCount-s.callCount;break;case`successCount`:f=a.successCount-s.successCount;break;case`successRate`:f=c-l;break;case`duration`:f=u-d;break}return i?f:-f}).map(([e,n])=>{let r=n.callCount>0?n.successCount/n.callCount*100:0,i=n.callCount>0?n.totalDuration/n.callCount:0,a=t[e]||e,o=`#38a169`;r<60?o=`#e53e3e`:r<85&&(o=`#d69e2e`);let s=Qe(i);return`<tr>
679
- <td style="padding: 6px 10px; border-bottom: 1px solid var(--border-subtle); color: var(--text-primary);"><code title="${A(a)}">${e}</code></td>
678
+ </div>`}).join(``)}function nt(){Ie&&(Ie.style.display=`flex`,$e())}function it(){Ie&&(Ie.style.display=`none`)}Fe&&Fe.addEventListener(`click`,e=>{e.stopPropagation(),ke(),nt()}),Le&&Le.addEventListener(`click`,it),Re&&Re.addEventListener(`click`,$e),ze&&ze.addEventListener(`change`,$e),Be&&Be.addEventListener(`change`,$e),Ve&&Ve.addEventListener(`input`,()=>{et()}),He&&He.addEventListener(`click`,()=>{Ve&&(Ve.value=``),et()}),bm(()=>v.activeSessionId,window.showCustomConfirm);let lt=document.getElementById(`isolateChatBtn`),ut=document.getElementById(`enableToolsBtn`),ft=document.getElementById(`toolsConfigBtn`),pt=`agentEnabledTools_${v.activeAgentId||`default`}`,mt=`agentMcpClosedServers_${v.activeAgentId||`default`}`;chrome.storage.local.get([pt,`enabledTools`,`isolateChat`,`enableSelectionQuery`,`enableTools`,mt,`mcpTools`,`mcpEnabled`,`ragTools`,`ragToolsIntroduced`],e=>{e.isolateChat!==void 0&&(v.isolateChat=e.isolateChat),lt.checked=v.isolateChat,e.enableSelectionQuery!==void 0&&(v.enableSelectionQuery=e.enableSelectionQuery);let t=document.getElementById(`enableSelectionQueryBtn`);t&&(t.checked=v.enableSelectionQuery),e.enableTools!==void 0&&(v.useTools=e.enableTools),v.activeAgentId&&E(async()=>{let{getAgent:e}=await import(`./agent-store-BirQwOYv.js`).then(e=>e.t);return{getAgent:e}},__vite__mapDeps([7,1,2,3])).then(({getAgent:e})=>e(v.activeAgentId)).then(e=>{v.activeAgentMcpExcludedServerIds=e?e.mcpExcludedServerIds??null:null,Zi()}).catch(()=>{}),v.mcpClosedServers=e[mt]||[];let n=e.ragTools||[],r=e[pt],i=e.enabledTools;if(Array.isArray(r)){let t=Sr(n);v.enabledTools=r.filter(e=>t.has(e));let i=mi(v.enabledTools,n,e.ragToolsIntroduced);v.enabledTools=i.tools,i.migrated?chrome.storage.local.set({ragToolsIntroduced:!0,[pt]:v.enabledTools}):v.enabledTools.length!==r.length&&chrome.storage.local.set({[pt]:v.enabledTools})}else if(i&&i.length>0){let t=Sr(n),r=i.filter(e=>t.has(e)),a=f.filter(e=>e.enabled&&!r.includes(e.id)).map(e=>e.id);v.enabledTools=[...r,...a];let o=mi(v.enabledTools,n,e.ragToolsIntroduced);v.enabledTools=o.tools,chrome.storage.local.set({[pt]:v.enabledTools,...o.migrated?{ragToolsIntroduced:!0}:{}})}else{v.enabledTools=f.filter(e=>e.enabled).map(e=>e.id);let t=mi(v.enabledTools,n,e.ragToolsIntroduced);v.enabledTools=t.tools,t.migrated&&chrome.storage.local.set({ragToolsIntroduced:!0,[pt]:v.enabledTools})}ut&&(ut.checked=v.useTools),Zi(),Pm(),S()}),lt.addEventListener(`change`,()=>{v.isolateChat=lt.checked,chrome.storage.local.set({isolateChat:v.isolateChat}),r.debug(`[SidePanel] conv memory:`,v.isolateChat?`enabled`:`disabled`)});let ht=document.getElementById(`enableSelectionQueryBtn`);ht&&ht.addEventListener(`change`,()=>{v.enableSelectionQuery=ht.checked,chrome.storage.local.set({enableSelectionQuery:v.enableSelectionQuery}),r.debug(`[SidePanel] text Q&A:`,v.enableSelectionQuery?`enabled`:`disabled`),!v.enableSelectionQuery&&v.selectedContextText&&Un()}),ut&&ut.addEventListener(`change`,()=>{v.useTools=ut.checked,chrome.storage.local.set({enableTools:v.useTools}),r.debug(`[SidePanel] tool master switch:`,v.useTools?`enabled`:`disabled`),Zi()}),ft&&ft.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),Fi()});let yt=document.getElementById(`toolsPopupOverlay`),xt=document.getElementById(`toolsPopupClose`),St=yt?yt.querySelector(`.modal-container`):null;xt&&xt.addEventListener(`click`,Di),St&&St.addEventListener(`click`,e=>{e.stopPropagation()});let wt=document.getElementById(`toolsSearchInput`),Tt=document.getElementById(`toolsSearchClear`);wt&&wt.addEventListener(`input`,e=>{v.currentSearch=e.target.value.toLowerCase(),Tt&&(Tt.style.display=e.target.value?``:`none`),Nr()}),Tt&&Tt.addEventListener(`click`,()=>{wt&&(wt.value=``,Tt.style.display=`none`,v.currentSearch=``,Nr())});let Et=document.querySelectorAll(`.category-btn`);Et.forEach(e=>{e.addEventListener(`click`,()=>{Et.forEach(e=>{e.classList.remove(`active`),e.classList.contains(`category-all`)?(e.style.background=`var(--brand-violet-soft-bg)`,e.style.color=`var(--brand-500)`,e.style.borderColor=`var(--brand-violet-soft-border)`):(e.style.background=`var(--bg-surface)`,e.style.color=`var(--text-secondary)`,e.style.borderColor=`var(--border-subtle)`)}),e.classList.add(`active`),e.style.background=`linear-gradient(135deg, var(--brand-500) 0%, var(--brand-accent) 100%)`,e.style.color=`var(--text-on-brand)`,e.style.borderColor=`transparent`,v.currentCategory=e.dataset.category,Nr()})});let At=document.getElementById(`toolsCategories`);At&&At.addEventListener(`wheel`,e=>{e.preventDefault(),At.scrollLeft+=e.deltaY*2},{passive:!1});let jt=document.getElementById(`toolsSelectAll`),Pt=document.getElementById(`toolsSelectNone`);jt&&jt.addEventListener(`click`,()=>{ni().forEach(e=>{let t=document.getElementById(`tool_`+e.id);t&&(t.checked=!0),v.enabledTools.includes(e.id)||v.enabledTools.push(e.id)}),oi(!0),Vr(),Lr(),zi()}),Pt&&Pt.addEventListener(`click`,()=>{ni().forEach(e=>{let t=document.getElementById(`tool_`+e.id);t&&(t.checked=!1);let n=v.enabledTools.indexOf(e.id);n>-1&&v.enabledTools.splice(n,1)}),oi(!1),Vr(),Lr(),zi()});let Ft=document.getElementById(`toolsPopupSave`);Ft&&Ft.addEventListener(`click`,()=>{vi(),zi()});let Lt=document.getElementById(`toolsPreselectToggle`);Lt&&Lt.addEventListener(`change`,()=>{chrome.storage.local.set({enableToolPreselect:Lt.checked},()=>{r.debug(`[SidePanel] toolpre-filter toggle updated:`,Lt.checked)})});let Rt=document.getElementById(`toolConfirmToggle`);Rt&&Rt.addEventListener(`change`,()=>{chrome.storage.local.set({toolConfirmationEnabled:Rt.checked},()=>{r.debug(`[SidePanel] sensitive-operation confirmation toggle updated:`,Rt.checked)})});let zt=document.getElementById(`toolsPopupCancel`);zt&&zt.addEventListener(`click`,()=>{Di()});let Bt=document.getElementById(`modalCancelBtn`),Vt=document.getElementById(`modalConfirmBtn`),Ht=document.getElementById(`toolStatsOverlay`),Ut=document.getElementById(`toolStatsClose`),qt=document.getElementById(`toolStatsBtn`);function Xt(){Ht&&(Ht.style.display=`flex`,rn())}function Zt(){Ht&&(Ht.style.display=`none`)}qt&&qt.addEventListener(`click`,e=>{e.stopPropagation(),Xt()}),Ut&&Ut.addEventListener(`click`,Zt),Ht&&Ht.addEventListener(`click`,e=>{e.target===Ht&&Zt()});let Qt=document.getElementById(`toolStatsRefreshBtn`);Qt&&Qt.addEventListener(`click`,rn);let en=document.getElementById(`toolStatsClearBtn`);en&&en.addEventListener(`click`,async()=>{await window.showCustomConfirm(t(`sidePanel.clearStatsConfirm`),t(`sidePanel.clearStatsTitle`))&&(await chrome.storage.local.remove([`toolUsageStats`]),rn())});let tn={column:`callCount`,asc:!1};async function rn(){let e=document.getElementById(`toolStatsTable`),n=document.getElementById(`toolStatsTableBody`),i=document.getElementById(`toolStatsLoading`),a=document.getElementById(`toolStatsEmpty`),o=document.getElementById(`toolStatsSummary`),s=document.getElementById(`toolStatsUnusedSection`),c=document.getElementById(`toolStatsUnusedList`);if(!(!e||!n||!i||!a)){e.style.display=`none`,a.style.display=`none`,s&&(s.style.display=`none`),o&&(o.textContent=``),i.style.display=``;try{let n=(await chrome.storage.local.get([`toolUsageStats`])).toolUsageStats||{},r=Object.entries(n);if(r.length===0){i.style.display=`none`,a.style.display=``;return}let l={};f.forEach(e=>{l[e.id]=e.name?`${e.name}${t(`sidePanel.toolNameDescSeparator`)}${e.description||``}`:e.description||e.id}),cn(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="${j(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 cn(e,t){let n=document.getElementById(`toolStatsTableBody`);if(!n)return;let{column:r,asc:i}=tn;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=Ze(i);return`<tr>
679
+ <td style="padding: 6px 10px; border-bottom: 1px solid var(--border-subtle); color: var(--text-primary);"><code title="${j(a)}">${e}</code></td>
680
680
  <td style="padding: 6px 10px; text-align: right; border-bottom: 1px solid var(--border-subtle); color: var(--text-secondary);">${n.callCount}</td>
681
681
  <td style="padding: 6px 10px; text-align: right; border-bottom: 1px solid var(--border-subtle); color: var(--text-secondary);">${n.successCount}</td>
682
682
  <td style="padding: 6px 10px; border-bottom: 1px solid var(--border-subtle);">
@@ -686,4 +686,4 @@ Are you sure you want to stop the agent service? You will not be able to connect
686
686
  <span style="font-size: 12px; color: ${o}; font-weight: 500;">${r.toFixed(0)}%</span>
687
687
  </td>
688
688
  <td style="padding: 6px 10px; text-align: right; border-bottom: 1px solid var(--border-subtle); color: var(--text-tertiary); font-size: 12px;">${s}</td>
689
- </tr>`}).join(``),tn()}function tn(){let{column:e,asc:t}=Qt,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;Qt.column===t?Qt.asc=!Qt.asc:(Qt.column=t,Qt.asc=!1),$t()})}),zt.addEventListener(`click`,()=>{Si()}),Bt.addEventListener(`click`,()=>{Si(),Jt()});let rn=document.getElementById(`confirmModal`);rn.addEventListener(`click`,e=>{e.target===rn&&Si()});let an=document.getElementById(`selectionClose`);an&&an.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),r.debug(`[SidePanel] user clickcloseselected content by button`),Gn(),window.hideFloatingMenu(),v.lastSelectedText=``,v.currentSelectionRange=null}),a.addEventListener(`input`,()=>{})}),at().then(()=>{Em(),mi(v.chatConfig.showMessageTimestamp!==!1),Dm(),Om()}),document.addEventListener(`DOMContentLoaded`,()=>{Am()}),document.addEventListener(`DOMContentLoaded`,Dt),document.addEventListener(`DOMContentLoaded`,di),document.addEventListener(`DOMContentLoaded`,Bm),document.addEventListener(`DOMContentLoaded`,zm),document.addEventListener(`DOMContentLoaded`,Hd),document.addEventListener(`DOMContentLoaded`,If),document.addEventListener(`DOMContentLoaded`,sp),document.addEventListener(`DOMContentLoaded`,St),document.addEventListener(`DOMContentLoaded`,async()=>{Xt(),Ja(),await br(),Qi(),await oc(),Hl(),vs(),Sm(),Vs(),gh(),gi(),xd();let{updateBookmarkButtons:e,updateBookmarkBadge:t}=await T(async()=>{let{updateBookmarkButtons:e,updateBookmarkBadge:t}=await import(`./context-indicator-BSGa1g7l.js`).then(e=>e.vn);return{updateBookmarkButtons:e,updateBookmarkBadge:t}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]));e(),t()}),document.addEventListener(`DOMContentLoaded`,()=>{fs()}),document.addEventListener(`DOMContentLoaded`,async()=>{Xr(e=>Ii(e)),await $t(),await Rp()});function Sh(){Gn(),Cr(),ki(),Zt(),tn(),Rn();let e=document.getElementById(`imagePreviewBar`);e&&(e.innerHTML=``,e.style.display=`none`)}function Ch(e){let t=e||{};t.quotedContextText&&Oi(t.quotedContextText),t.selectedPage&&ia(t.selectedPage),!t.quotedContextText&&v.selectedContextText&&nr(),dr(),Rr(),Mn(),ci(),At()}document.addEventListener(`queue-context-cleared`,Sh),document.addEventListener(`queue-context-restored`,e=>{Ch(e&&e.detail?e.detail.snapshot:null)}),document.addEventListener(`DOMContentLoaded`,Sn),document.addEventListener(`DOMContentLoaded`,Pr),document.addEventListener(`DOMContentLoaded`,yi),document.addEventListener(`DOMContentLoaded`,Dr),document.addEventListener(`DOMContentLoaded`,In),document.addEventListener(`DOMContentLoaded`,_i),document.addEventListener(`DOMContentLoaded`,_r),document.addEventListener(`DOMContentLoaded`,yt),document.addEventListener(`DOMContentLoaded`,Nt),document.addEventListener(`DOMContentLoaded`,()=>hr()),document.addEventListener(`DOMContentLoaded`,async()=>{let{refreshAgentNames:e,initScrollToBottomBtn:t}=await T(async()=>{let{refreshAgentNames:e,initScrollToBottomBtn:t}=await import(`./context-indicator-BSGa1g7l.js`).then(e=>e.pt);return{refreshAgentNames:e,initScrollToBottomBtn:t}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]));e(),t()});async function wh(){try{let e=(await chrome.storage.local.get(`_detachOriginTabId`))?._detachOriginTabId;if(typeof e==`number`)try{let t=await chrome.tabs.get(e);if(t?.id!=null)return t.id}catch{}}catch{}try{let e=(await chrome.windows.getAll({populate:!0})||[]).filter(e=>e.type===`normal`);return((e.find(e=>e.focused)||e[0])?.tabs||[]).find(e=>e.active)?.id??null}catch{return null}}document.addEventListener(`DOMContentLoaded`,()=>{let e=new URLSearchParams(window.location.search).has(`popup`),n=document.getElementById(`detachBtn`),i=document.getElementById(`attachBtn`),a=e?i:n;e?i&&(i.style.display=`flex`):n&&(n.style.display=`flex`);let o=()=>{if(!a)return;let n=v.pendingCallApiSessionIds&&v.pendingCallApiSessionIds.size>0;a.disabled=n,a.style.opacity=n?`0.35`:``,a.style.cursor=n?`not-allowed`:`pointer`,a.title=t(n?`detach.taskRunning`:e?`header.attachTitle`:`header.detachTitle`)};o(),document.addEventListener(`generating-state-changed`,o),n&&n.addEventListener(`click`,async()=>{if(v.pendingCallApiSessionIds&&v.pendingCallApiSessionIds.size>0){k(t(`detach.taskRunning`),`warning`);return}try{if((await chrome.runtime.sendMessage({type:`DETACH_SIDEPANEL`,width:window.innerWidth}))?.success)try{window.close()}catch{}}catch(e){r.warn(`[SidePanel] detach failed:`,e?.message)}}),i&&i.addEventListener(`click`,async()=>{if(v.pendingCallApiSessionIds&&v.pendingCallApiSessionIds.size>0){k(t(`detach.taskRunning`),`warning`);return}try{let e=(await chrome.windows.getCurrent()).id,n=await wh();if(n==null){k(t(`detach.attachFailed`),`error`);return}let i=await chrome.runtime.sendMessage({type:`ATTACH_SIDEPANEL`,windowId:e,tabId:n});if(i?.success)try{window.close()}catch{}else r.warn(`[SidePanel] attach rejected:`,i?.error),k(t(`detach.attachFailed`),`error`)}catch(e){r.warn(`[SidePanel] attach failed:`,e?.message),k(t(`detach.attachFailed`),`error`)}})});
689
+ </tr>`}).join(``),un()}function un(){let{column:e,asc:t}=tn,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;tn.column===t?tn.asc=!tn.asc:(tn.column=t,tn.asc=!1),rn()})}),Bt.addEventListener(`click`,()=>{yi()}),Vt.addEventListener(`click`,()=>{yi(),Jt()});let dn=document.getElementById(`confirmModal`);dn.addEventListener(`click`,e=>{e.target===dn&&yi()});let fn=document.getElementById(`selectionClose`);fn&&fn.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),r.debug(`[SidePanel] user clickcloseselected content by button`),Un(),window.hideFloatingMenu(),v.lastSelectedText=``,v.currentSelectionRange=null}),a.addEventListener(`input`,()=>{})}),it().then(()=>{Sm(),di(v.chatConfig.showMessageTimestamp!==!1),Cm(),wm()}),document.addEventListener(`DOMContentLoaded`,()=>{Em()}),document.addEventListener(`DOMContentLoaded`,ta),document.addEventListener(`DOMContentLoaded`,ci),document.addEventListener(`DOMContentLoaded`,Im),document.addEventListener(`DOMContentLoaded`,Fm),document.addEventListener(`DOMContentLoaded`,Rd),document.addEventListener(`DOMContentLoaded`,Mf),document.addEventListener(`DOMContentLoaded`,rp),document.addEventListener(`DOMContentLoaded`,Qr),document.addEventListener(`DOMContentLoaded`,async()=>{Jn(),Ua(),await Xi(),Ri(),await nc(),Rl(),ms(),vm(),Ls(),fh(),pr(),_d();let{updateBookmarkButtons:e,updateBookmarkBadge:t}=await E(async()=>{let{updateBookmarkButtons:e,updateBookmarkBadge:t}=await import(`./context-indicator-C9mzVLvn.js`).then(e=>e._n);return{updateBookmarkButtons:e,updateBookmarkBadge:t}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]));e(),t()}),document.addEventListener(`DOMContentLoaded`,()=>{cs()}),document.addEventListener(`DOMContentLoaded`,async()=>{xt(e=>Mi(e)),await Vt(),await Pp()});function vh(){Un(),br(),Ti(),Yn(),Ut(),Ki();let e=document.getElementById(`imagePreviewBar`);e&&(e.innerHTML=``,e.style.display=`none`)}function yh(e){let t=e||{};t.quotedContextText&&wi(t.quotedContextText),t.selectedPage&&Fn(t.selectedPage),!t.quotedContextText&&v.selectedContextText&&er(),lr(),Fr(),cr(),_i(),Ln()}document.addEventListener(`queue-context-cleared`,vh),document.addEventListener(`queue-context-restored`,e=>{yh(e&&e.detail?e.detail.snapshot:null)}),document.addEventListener(`DOMContentLoaded`,xn),document.addEventListener(`DOMContentLoaded`,jr),document.addEventListener(`DOMContentLoaded`,gi),document.addEventListener(`DOMContentLoaded`,wr),document.addEventListener(`DOMContentLoaded`,fn),document.addEventListener(`DOMContentLoaded`,mr),document.addEventListener(`DOMContentLoaded`,Gr),document.addEventListener(`DOMContentLoaded`,An),document.addEventListener(`DOMContentLoaded`,Lt),document.addEventListener(`DOMContentLoaded`,()=>fr()),document.addEventListener(`DOMContentLoaded`,async()=>{let{refreshAgentNames:e,initScrollToBottomBtn:t}=await E(async()=>{let{refreshAgentNames:e,initScrollToBottomBtn:t}=await import(`./context-indicator-C9mzVLvn.js`).then(e=>e.pt);return{refreshAgentNames:e,initScrollToBottomBtn:t}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]));e(),t()});async function bh(){try{let e=(await chrome.storage.local.get(`_detachOriginTabId`))?._detachOriginTabId;if(typeof e==`number`)try{let t=await chrome.tabs.get(e);if(t?.id!=null)return t.id}catch{}}catch{}try{let e=(await chrome.windows.getAll({populate:!0})||[]).filter(e=>e.type===`normal`);return((e.find(e=>e.focused)||e[0])?.tabs||[]).find(e=>e.active)?.id??null}catch{return null}}document.addEventListener(`DOMContentLoaded`,()=>{let e=new URLSearchParams(window.location.search).has(`popup`),n=document.getElementById(`detachBtn`),i=document.getElementById(`attachBtn`),a=e?i:n;e?i&&(i.style.display=`flex`):n&&(n.style.display=`flex`);let o=()=>{if(!a)return;let n=v.pendingCallApiSessionIds&&v.pendingCallApiSessionIds.size>0;a.disabled=n,a.style.opacity=n?`0.35`:``,a.style.cursor=n?`not-allowed`:`pointer`,a.title=t(n?`detach.taskRunning`:e?`header.attachTitle`:`header.detachTitle`)};o(),document.addEventListener(`generating-state-changed`,o),n&&n.addEventListener(`click`,async()=>{if(v.pendingCallApiSessionIds&&v.pendingCallApiSessionIds.size>0){A(t(`detach.taskRunning`),`warning`);return}try{if((await chrome.runtime.sendMessage({type:`DETACH_SIDEPANEL`,width:window.innerWidth}))?.success)try{window.close()}catch{}}catch(e){r.warn(`[SidePanel] detach failed:`,e?.message)}}),i&&i.addEventListener(`click`,async()=>{if(v.pendingCallApiSessionIds&&v.pendingCallApiSessionIds.size>0){A(t(`detach.taskRunning`),`warning`);return}try{let e=(await chrome.windows.getCurrent()).id,n=await bh();if(n==null){A(t(`detach.attachFailed`),`error`);return}let i=await chrome.runtime.sendMessage({type:`ATTACH_SIDEPANEL`,windowId:e,tabId:n});if(i?.success)try{window.close()}catch{}else r.warn(`[SidePanel] attach rejected:`,i?.error),A(t(`detach.attachFailed`),`error`)}catch(e){r.warn(`[SidePanel] attach failed:`,e?.message),A(t(`detach.attachFailed`),`error`)}})});