ai-helper-agent 2.8.9 → 2.8.10
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.
- package/dist/assets/background.js +68 -68
- package/dist/assets/{chat-export-CCgB_PeN.js → chat-export-DduslUlT.js} +1 -1
- package/dist/assets/content.js +48 -41
- package/dist/assets/{context-indicator-CWyjBBv3.js → context-indicator-Bs34HFah.js} +74 -74
- package/dist/assets/options.js +1 -1
- package/dist/assets/side_panel.js +94 -95
- package/dist/assets/{version-DUmOB_mV.js → version-h3EcDzjp.js} +2 -2
- package/dist/manifest.json +1 -1
- package/dist/options.html +1 -1
- package/dist/side_panel.html +2 -2
- package/package.json +1 -1
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/context-indicator-
|
|
2
|
-
import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-DvmxOw8q.js";import{A as s,At as c,Bt as l,Ht as u,J as d,Jt as f,L as p,Lt as m,M as h,Nt as g,Ot as ee,P as te,R as ne,U as _,b as v,c as re,ct as y,d as b,gt as x,ht as ie,i as S,it as C,jt as ae,k as oe,q as w,r as se,rt as ce,u as T,wt as le,x as E,y as ue,zt as de}from"./model-profiles-C3kJEHM6.js";import{_ as D,d as fe}from"./session-store-owqj23pJ.js";import{A as pe,C as me,D as he,E as ge,M as _e,N as ve,O as ye,S as be,T as xe,_ as Se,a as Ce,b as we,c as Te,d as Ee,f as De,g as Oe,h as ke,i as Ae,j as je,k as Me,l as Ne,m as Pe,n as O,o as Fe,p as Ie,r as Le,s as Re,t as ze,u as Be,v as Ve,w as He,x as Ue,y as We}from"./todo-model-DK2Wxmvk.js";import{$ as Ge,A as Ke,D as qe,G as Je,H as Ye,J as Xe,K as Ze,M as k,N as Qe,O as $e,P as et,Q as tt,R as nt,T as rt,V as it,W as at,Y as A,Z as ot,_ as st,et as ct,g as lt,j,k as ut,l as dt,q as ft,t as pt,tt as mt,v as ht,y as gt}from"./version-DUmOB_mV.js";import{$ as _t,$n as vt,$t as yt,A as bt,An as xt,Ar as St,At as Ct,B as wt,Bn as Tt,Br as Et,Bt as Dt,C as Ot,Cn as kt,Cr as At,Ct as jt,D as Mt,Dn as Nt,Dr as Pt,Dt as Ft,E as It,En as Lt,Er as Rt,Et as zt,F as Bt,Fn as Vt,Fr as Ht,Ft as Ut,G as Wt,Gn as Gt,Gt as Kt,H as qt,Hn as Jt,Hr as Yt,Ht as Xt,I as Zt,In as Qt,Ir as $t,It as en,J as tn,Jn as nn,Jt as rn,K as an,Kn as on,Kt as sn,L as cn,Ln as ln,Lr as un,Lt as dn,M as fn,Mn as pn,Mr as mn,Mt as hn,N as gn,Nn as _n,Nr as vn,Nt as yn,O as bn,On as xn,Or as Sn,Ot as Cn,P as wn,Pn as Tn,Pr as En,Pt as Dn,Q as On,Qn as kn,Qt as An,R as jn,Rn as Mn,Rr as Nn,Rt as Pn,S as Fn,Sn as In,Sr as Ln,St as Rn,T as zn,Tn as Bn,Tr as Vn,Tt as Hn,U as Un,Un as Wn,Ur as Gn,Ut as Kn,Vn as qn,Vr as Jn,Vt as Yn,W as Xn,Wn as Zn,Wr as Qn,Wt as $n,X as er,Xn as tr,Xt as nr,Y as rr,Yn as ir,Yt as ar,Z as or,Zn as sr,Zt as cr,_ as lr,_n as ur,_r as dr,_t as fr,a as pr,an as mr,ar as hr,at as gr,b as _r,bn as vr,br as yr,bt as br,c as xr,cr as Sr,ct as Cr,d as wr,dn as Tr,dr as Er,dt as Dr,en as Or,er as kr,et as Ar,f as jr,fn as Mr,fr as Nr,g as Pr,gr as Fr,gt as Ir,h as Lr,hn as Rr,hr as zr,ht as Br,i as Vr,in as Hr,ir as Ur,it as Wr,j as Gr,jn as Kr,jr as qr,jt as Jr,k as Yr,kn as Xr,kr as Zr,kt as Qr,l as $r,ln as ei,lr as ti,lt as ni,m as ri,mn as ii,mr as ai,mt as oi,n as si,nn as ci,nt as li,o as ui,on as di,or as fi,ot as pi,p as mi,pn as hi,pr as gi,pt as _i,q as vi,qn as yi,qt as bi,r as xi,rn as Si,rr as Ci,rt as wi,s as Ti,sn as Ei,sr as Di,st as Oi,t as ki,tn as Ai,tr as ji,tt as Mi,u as Ni,un as Pi,ur as Fi,ut as Ii,v as Li,vn as Ri,vr as zi,vt as Bi,w as Vi,wn as Hi,wr as Ui,wt as Wi,x as Gi,xn as Ki,xt as qi,y as Ji,yn as Yi,yr as Xi,yt as Zi,z as Qi,zn as $i,zr as ea,zt as ta}from"./context-indicator-CWyjBBv3.js";import{o as na}from"./agent-store-QTeMyM9O.js";import{O as ra,b as ia,l as aa,p as oa,v as sa}from"./workspace-manager-DVPkwn2d.js";var ca=`panel-observer-`,la=new Map;function ua(e){if(!e)return null;let t=la.get(e);if(t)return t;let n;try{n=chrome.runtime.connect({name:`${ca}${e}`})}catch(e){return r.debug(`[PanelObserver] 建立观察端口失败(忽略):`,e?.message||e),null}la.set(e,n);try{n.onDisconnect.addListener(()=>{la.get(e)===n&&la.delete(e)})}catch(e){r.debug(`[PanelObserver] 观察端口断开监听挂不上(忽略):`,e?.message||e)}return n}function da(e){if(!e)return;let t=la.get(e);if(t){la.delete(e);try{t.disconnect()}catch(e){r.debug(`[PanelObserver] 关闭观察端口异常(忽略):`,e?.message||e)}}}function fa({sessionId:e,callId:t,renderer:n,persist:i,onFinished:a=()=>{},emptyFallback:o=``,awaitSnapshot:s=!1}){let c=``,l=!1,u=s,d=[],f=n=>!!n&&n.sessionId===e&&n.callId===t,p=e=>{let t=[];for(let n of e){let e=t[t.length-1];n.type===`STREAM_CHUNK`&&e&&e.type===`STREAM_CHUNK`?t[t.length-1]={...n,delta:(e.delta||``)+(n.delta||``)}:t.push(n)}return t},m=()=>{u=!1;let e=p(d);d=[];for(let t of e)g(t)},h=e=>{l=!0,Promise.resolve().then(()=>i(e)).catch(e=>r.warn(`[ChatReattach] 终态落库失败(忽略):`,e?.message||e)).then(()=>{try{a()}catch{}})};return{sessionId:e,callId:t,get finished(){return l},dispose(){l=!0},restore(e){if(!u)return;u=!1;let r=!!e&&e.callId===t,i=r&&typeof e.accumulated==`string`?e.accumulated:``,a=r&&!!e.html;a&&n.restore?.({html:e.html}),c=i,i&&!a&&n.chunk?.(i);let o=p(d);d=[];for(let e of o)g(e)},handleMessage(e){return l||!f(e)?!1:u?e.type===`STREAM_CHUNK`?(d.push(e),!0):e.type===`API_COMPLETE`||e.type===`API_ERROR`?(m(),g(e)):(d.push(e),!0):g(e)}};function g(r){switch(r.type){case`STREAM_START`:return c=``,n.start?.(),!0;case`STREAM_CHUNK`:return c+=r.delta||``,n.chunk?.(c),!0;case`STREAM_TOOL_CALL`:return n.toolCalls?.(r.toolCalls||[],c),!0;case`STREAM_TOOL_RESULT`:return r.result&&n.toolResult?.(r.result),!0;case`AGENT_STREAM`:return r.execId&&n.agentStream?.(r),!0;case`AGENT_STREAM_DONE`:return r.execId&&n.agentStreamDone?.(r),!0;case`API_RETRYING`:return n.retrying?.(r.attempt,r.maxRetries),!0;case`STREAM_PRESELECT`:return n.preselect?.(r.preselectLog||[]),!0;case`EXECUTION_STATUS_UPDATE`:return!0;case`API_COMPLETE`:{let i=r.content&&String(r.content).trim()?r.content:o||c,a=r.executionLog||[],s={reflectionScore:r.reflectionScore,reasoningContent:r.reasoningContent||null,wasRevised:r.wasRevised||!1,budgetEnded:r.budgetEnded===!0};return n.final?.(i,a,s),h({sessionId:e,callId:t,content:i,executionLog:a,...s}),!0}case`API_ERROR`:return n.error?.(r.error||``,r.executionLog||[]),h({sessionId:e,callId:t,error:r.error||``,executionLog:r.executionLog||[]}),!0;default:return!1}}}function pa({queryRunning:e,hasLocalListener:t,isAttached:n,attach:i}){return{async syncFromBackground(){try{let r=await e(),a=r&&r.activeCallIds?r.activeCallIds:{};for(let[e,r]of Object.entries(a))!e||!r||t(e)||n(e,r)||i(e,r)}catch(e){r.debug(`[ChatReattach] 查询后台运行状态失败(忽略):`,e?.message||e)}}}}var ma=!1,ha=new Map,ga=null,_a=!1,va=null,ya=null,ba=null,xa=250,Sa=new Set([`STREAM_START`,`STREAM_CHUNK`,`STREAM_TOOL_CALL`,`STREAM_TOOL_RESULT`,`AGENT_STREAM`,`AGENT_STREAM_DONE`,`API_RETRYING`,`STREAM_PRESELECT`,`EXECUTION_STATUS_UPDATE`,`API_COMPLETE`,`API_ERROR`]);function Ca(e=0){return new Promise((t,n)=>{let r=!1,i=null,a=(e,t)=>{r||(r=!0,i&&clearTimeout(i),e(t))};e>0&&(i=setTimeout(()=>a(t,{}),e));try{chrome.runtime.sendMessage({type:`QUERY_SESSION_RUNNING`},e=>{if(chrome.runtime.lastError){a(n,Error(chrome.runtime.lastError.message));return}a(t,e||{})})}catch(e){a(n,e)}})}function wa(e,t){let n=new Map;return{start(){Hn(e,``),Wi(``),zt(Date.now()),Oi(t),Rn(t)},chunk(n){Hn(e,n),Ft(t,n)},restore({html:e}){Ii(t,e)},toolCalls(e,n){typeof n==`string`&&n&&qi(t,n),Cr(t,e)},toolResult(e){ni(e,t)},agentStream(e){let r=n.get(e.execId);if(!r){let i=_i(e.toolCallId?t.querySelector(`.tool-call-item[data-tool-call-id="${e.toolCallId}"]`):null,t.querySelector(`.stream-content`));r={element:i,codeEl:i.querySelector(`code`),stderrSeparator:null},n.set(e.execId,r),dt()}let i=r.codeEl;if(!i)return;let a=e.data||``;if(a){let t=document.createTextNode(a);if(e.streamType===`stderr`){if(!r.stderrSeparator){let e=document.createTextNode(`
|
|
3
|
-
`);i.appendChild(e),r.stderrSeparator=e}i.appendChild(t)}else r.stderrSeparator?i.insertBefore(t,r.stderrSeparator):i.appendChild(t)}let o=i.parentElement;o&&(o.scrollTop=o.scrollHeight)},agentStreamDone(e){let t=n.get(e.execId);t&&e.exitCode!==0&&t.element.classList.add(`agent-stream-error`)},retrying(e,n){Bi(t,e,n)},preselect(e){let n=t.querySelector(`.message-content`);!n||!e.length||e.forEach(e=>n.insertBefore(oi(e),n.firstChild))},final(e,n,r={}){fr(t,e,n,r.reflectionScore,r.reasoningContent,r.wasRevised)},error(e,n){fr(t,e,n||[])}}}async function Ta(e,t,n){let r=!!e.error,i={role:`assistant`,content:r?e.error:e.content||``,executionLog:e.executionLog||[],reflectionScore:e.reflectionScore,wasRevised:e.wasRevised||!1,callId:e.callId,resumed:!0,resumable:e.budgetEnded?`budget`:!1};if(!r&&n&&(i.messageId=n.dataset.messageId||void 0,i.htmlContent=n.dataset.htmlContent||n.outerHTML),v.activeSessionId===t){v.messageHistory.push(i);try{document.dispatchEvent(new CustomEvent(`session-cache-invalidate`,{detail:{sessionId:t}}))}catch{}}let{appendMessageToSession:a}=await E(async()=>{let{appendMessageToSession:e}=await import(`./context-indicator-CWyjBBv3.js`).then(e=>e.xr);return{appendMessageToSession:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]));await a(t,i)}function Ea(){E(()=>import(`./context-indicator-CWyjBBv3.js`).then(e=>e.V).then(e=>e.syncPendingSessionsToStorage()),__vite__mapDeps([0,1,2,3,4,5,6,7,8])).catch(e=>r.debug(`[ChatReattach] 同步生成态失败(忽略):`,e?.message||e))}var Da=1e3;function Oa(e){return Promise.race([Cn(e),new Promise(e=>setTimeout(()=>e(null),Da))])}function ka(e,n){let i=Br(e);if(i())return!1;let a=pi(e);a.dataset.callId=n,i(a),Hn(e,``),zt(Date.now()),jt(Date.now()),v.pendingCallApiSessionIds.add(e),v.generatingSessionIds.add(e),Ea();try{document.dispatchEvent(new CustomEvent(`generating-state-changed`))}catch{}let o=fa({sessionId:e,callId:n,awaitSnapshot:!0,renderer:wa(e,a),persist:t=>Ta(t,e,a),emptyFallback:t(`chatMsg.emptyModelReply`),onFinished:()=>{if(ha.get(e)===o){ha.delete(e),da(e),v.pendingCallApiSessionIds.delete(e),Ea(),Ir(e);try{document.dispatchEvent(new CustomEvent(`session-cache-invalidate`,{detail:{sessionId:e}}))}catch{}on(e)}}});return ha.set(e,o),ua(e),Oa(e).then(t=>{o.finished||ha.get(e)!==o||o.restore(t)}).catch(()=>o.restore(null)),v.activeSessionId===e&&Zi(e),r.info(`[ChatReattach] 已接管运行中的任务: sessionId=${e}, callId=${n}`),!0}function Aa(e){let t=ha.get(e);if(!t)return;ha.delete(e),da(e);try{t.dispose?.()}catch{}let n=Br(e),r=n();try{r?.remove()}catch{}n(null),Ir(e),v.pendingCallApiSessionIds.delete(e),Ea();try{document.dispatchEvent(new CustomEvent(`generating-state-changed`))}catch{}}function ja(){let e=ga;e&&Promise.resolve().then(()=>e.syncFromBackground()).catch(e=>r.debug(`[ChatReattach] 对齐后台状态失败(忽略):`,e?.message||e))}function Ma(){!ma||!ga||ba||(ba=setTimeout(()=>{ba=null,ja()},xa))}var Na=new Map,Pa=3e3,Fa=100,Ia=new Set,La=new Set([`API_COMPLETE`,`API_ERROR`]);function Ra(e,t){let n=`${e}|${t.callId}`;Ia.has(n)||(Ia.add(n),Ia.size>Fa&&Ia.delete(Ia.values().next().value),Aa(e),ka(e,t.callId)&&ha.get(e)?.handleMessage(t))}function za(e,t,n){let r=Na.get(e);if(r){r.messages.push(n);return}r={callId:t,messages:[n]},Na.set(e,r),Ca(Pa).then(t=>Ba(e,t&&t.activeCallIds&&t.activeCallIds[e]||null)).catch(()=>Ba(e,null)).finally(()=>{Na.delete(e)})}function Ba(e,t){let n=Na.get(e);if(!n)return;let{callId:r,messages:i}=n;if(t===r)Aa(e),ka(e,r);else if(t===null){let t=i.find(e=>La.has(e.type));if(!t)return;Ra(e,t);return}else return;let a=ha.get(e);if(!(!a||a.callId!==r))for(let e of i){if(a.finished)break;a.handleMessage(e)}}function Va(){_a||(_a=!0,chrome.runtime.onMessage.addListener(e=>{if(!e)return!1;let t=e.sessionId?ha.get(e.sessionId):null;return t?e.callId&&e.callId!==t.callId?(za(e.sessionId,e.callId,e),!1):(ua(e.sessionId),t.handleMessage(e),!1):(e.callId&&Sa.has(e.type)&&Ma(),!1)}),va=e=>{let t=e?.detail?.sessionId;t&&ha.has(t)&&Zi(t),Ma()},document.addEventListener(`session-hydrated`,va),ya=e=>{let t=e?.detail?.sessionId;t&&ha.has(t)&&Zi(t)},document.addEventListener(`chat-history-rendered`,ya))}function Ha(){return ma?{syncFromBackground:()=>ga.syncFromBackground()}:(ma=!0,Va(),ga=pa({queryRunning:Ca,hasLocalListener:e=>v.pendingCancelApiMap.has(e),isAttached:(e,t)=>ha.get(e)?.callId===t?(ua(e),!0):!1,attach:(e,t)=>{ka(e,t)}}),ga.syncFromBackground(),{syncFromBackground:()=>ga.syncFromBackground()})}function Ua(e){!ma||!ga||(e&&v.activeSessionId===e&&Zi(e),ga.syncFromBackground())}e(`zh`,{dock:{ariaLabel:`执行中会话`,running:`正在执行`,node:`正在执行:{node}`,subtask:`子任务 {index}/{total}`,queued:`排队 {count} 条`,done:`已完成,点击查看结果`,doneAt:`已完成 {time}`,scheduled:`定时任务`,dismiss:`从停靠条移除`,dismissStale:`移除失效条目`,stale:`状态可能已失效 · 未在限定时间内收到执行更新`,more:`还有 {count} 个`,moreAria:`还有 {count} 个未显示的执行条目`,overflowTitle:`其他执行中的会话`,openSession:`点击进入该会话`,unknownSession:`未知会话`}}),e(`en`,{dock:{ariaLabel:`Running sessions`,running:`Running`,node:`Running: {node}`,subtask:`Subtask {index}/{total}`,queued:`{count} queued`,done:`Finished — click to review`,doneAt:`Finished {time}`,scheduled:`Scheduled task`,dismiss:`Remove from dock`,dismissStale:`Remove stale entry`,stale:`Status may be stale · no execution update in time`,more:`+{count} more`,moreAria:`{count} more running entries not shown`,overflowTitle:`Other active sessions`,openSession:`Click to open this session`,unknownSession:`Unknown session`}});var Wa=`sessionDockDismissed`,Ga=5e3,Ka=250,qa=1200,Ja=8,Ya=Ja-1,Xa=9e4,Za={running:0,queued:1,done:2},Qa=new Map,$a=new Map,eo=new Map,to=new Map,no=new Set,ro=new Set,io=new Map,ao=new Map,oo=new Set,so=new Set,co=[],lo=new Set,M=null,N=null,P=null,uo=[],fo=!1,po=null,mo=null,ho=!1,go=null,_o=null;function vo(e){return e?Array.isArray(e)?e:e instanceof Set?Array.from(e):[]:[]}function yo(e){let t=new Set;for(let n of vo(e))n&&t.add(h(String(n))||String(n));return t}function bo({phase:e=``,sessionId:t=null,backendRunningIds:n=[],startedAt:r=0,lastUpdateAt:i=0,now:a=Date.now(),staleMs:o=Xa}={}){if(e!==`running`||!t||vo(n).includes(t))return!1;let s=Math.max(Number(r)||0,Number(i)||0);return s?a-s>=o:!1}var xo=160;function So(e){let t=String(e??``).replace(/\s+/g,` `).trim();if(!t)return``;let n=Array.from(t);return n.length<=xo?t:`${n.slice(0,xo).join(``).trimEnd()}…`}function Co(e,t){let n=e=>String(e??``).trim().replace(/[…\s.]+$/,``).replace(/\s+/g,``),r=n(e),i=n(t);return!r||!i?!1:r===i||i.startsWith(r)||r.startsWith(i)}function wo({phase:e=``,queuedText:t=``,questionText:n=``,title:r=``}={}){let i=e===`queued`?So(t):``,a=i||So(n),o=So(r),s=a||o,c=i?`queued`:a?`question`:s?`title`:``;return{primary:s,sub:a&&!Co(o,a)?o:``,isQuestion:!!a,from:c}}function To(e){let t=Array.isArray(e?.messageHistory)?e.messageHistory:[];for(let e=t.length-1;e>=0;--e){let n=t[e];if(!n||n.role!==`user`)continue;let r=ae(n.content);if(r&&String(r).trim())return{text:String(r),messageId:n.messageId?String(n.messageId):``}}return{text:``,messageId:``}}function Eo({activeSessionId:e=null,titles:t={},questions:n={},anchors:r={},queuedTexts:i={},generatingIds:a=[],pendingIds:o=[],runningIds:s=[],completedIds:c=[],queuedCounts:l={},scheduledIds:u=[],dismissedIds:d=[],nodeInfo:f={},startedAt:p={},doneAt:m={},lastUpdateAt:h={},now:g=Date.now(),staleMs:ee=Xa}={}){let te=vo(s),ne=new Set([...vo(a),...vo(o),...te]),_=new Set(vo(c)),v=new Set(vo(d)),re=new Set(vo(u)),y=l||{},b=new Set([...ne,..._,...Object.keys(y)]),x=[];for(let a of b){if(!a||a===e)continue;let o=Number(y[a])||0,s;if(ne.has(a))s=`running`;else if(o>0)s=`queued`;else if(_.has(a))s=`done`;else continue;let c=bo({phase:s,sessionId:a,backendRunningIds:te,startedAt:p?.[a],lastUpdateAt:h?.[a],now:g,staleMs:ee});if(v.has(a)&&(s===`done`||c))continue;let l=f?.[a]||{},u=wo({phase:s,queuedText:i?.[a]||``,questionText:n?.[a]||``,title:t?.[a]||``});x.push({sessionId:a,title:t?.[a]||``,primary:u.primary,sub:u.sub,isQuestion:u.isQuestion,anchorMessageId:u.from===`question`?String(r?.[a]||``):``,phase:s,stale:c,source:re.has(a)?`scheduled`:`chat`,queuedCount:o,nodeName:l.nodeName||``,subtaskIndex:l.subtaskIndex||0,subtaskTotal:l.subtaskTotal||0,startedAt:p?.[a]||0,doneAt:m?.[a]||0,lastUpdateAt:h?.[a]||0})}return x.sort((e,t)=>{let n=Za[e.phase]-Za[t.phase];if(n!==0)return n;if(e.stale!==t.stale)return e.stale?1:-1;let r=e.phase===`done`?e.doneAt:e.startedAt,i=t.phase===`done`?t.doneAt:t.startedAt;return r===i?String(e.sessionId).localeCompare(String(t.sessionId)):i-r}),x}function Do(e){return so.has(e)||v.generatingSessionIds.has(e)||v.pendingCallApiSessionIds.has(e)}function Oo(){let e={};try{let t=St();for(let n of t){let t=Pt(n);t>0&&(e[n]=t)}}catch(e){r.debug(`[SessionDock] read queue counts failed:`,e?.message||e)}return e}function ko(){let e={};for(let t of v.sessions||[])e[t.id]=t.title||``;for(let[t,n]of io)e[t]||(e[t]=n);return e}function Ao(){let e={},t={},n=new Map;for(let e of v.sessions||[])n.set(e.id,e);for(let r of new Set([...so,...v.generatingSessionIds,...v.pendingCallApiSessionIds,...v.completedSessionIds])){let i=$a.get(r)||eo.get(r)||0,a=ao.get(r);if(i&&a&&a.stamp===i){a.text&&(e[r]=a.text,t[r]=a.messageId||``);continue}let o=To(n.get(r));o.text&&(e[r]=o.text,t[r]=o.messageId)}return{questions:e,anchors:t}}function jo(){let e={};try{for(let t of St()){let n=qr(t);n?.text&&(e[t]=String(n.text))}}catch(e){r.debug(`[SessionDock] read queued texts failed:`,e?.message||e)}return e}function Mo(e){for(let t of e||[]){let e=t.sessionId;if(!e)continue;let n=t.startedAt||t.doneAt||0,i=ao.get(e),a=!i||i.stamp!==n,o=!t.title;!a&&!o||oo.has(e)||(oo.add(e),y(e).then(t=>{if(t&&((o||!io.has(e))&&io.set(e,t.title||``),a)){let r=To(t);ao.set(e,{text:r.text,messageId:r.messageId,stamp:n})}}).catch(e=>{r.debug(`[SessionDock] hydrate label failed:`,e?.message||e)}).finally(()=>{oo.delete(e),F()}))}}function No(e){if(!e)return``;let t=new Date(e);return`${String(t.getHours()).padStart(2,`0`)}:${String(t.getMinutes()).padStart(2,`0`)}`}function Po(e){if(e.phase===`running`){if(e.stale)return t(`dock.stale`);let n=e.nodeName?t(`dock.node`,{node:e.nodeName}):t(`dock.running`);return e.subtaskTotal>1?`${n} · ${t(`dock.subtask`,{index:e.subtaskIndex,total:e.subtaskTotal})}`:n}return e.phase===`queued`?t(`dock.queued`,{count:e.queuedCount}):e.doneAt?t(`dock.doneAt`,{time:No(e.doneAt)}):t(`dock.done`)}function Fo(){let e=v.completedSessionIds;for(let e of new Set([...so,...v.generatingSessionIds,...v.pendingCallApiSessionIds]))$a.has(e)||$a.set(e,Date.now()),eo.delete(e);for(let e of so)ro.delete(e);for(let t of e)!eo.has(t)&&!Do(t)&&eo.set(t,Date.now());let{questions:t,anchors:n}=Ao(),r=Eo({activeSessionId:v.activeSessionId,titles:ko(),questions:t,anchors:n,queuedTexts:jo(),generatingIds:v.generatingSessionIds,pendingIds:v.pendingCallApiSessionIds,runningIds:so,completedIds:e,queuedCounts:Oo(),scheduledIds:no,dismissedIds:ro,nodeInfo:Object.fromEntries(Qa),startedAt:Object.fromEntries($a),doneAt:Object.fromEntries(eo),lastUpdateAt:Object.fromEntries(to),now:Date.now()});return Mo(r),r}function Io(e){let t=new Set(co.filter(e=>e.phase===`done`).map(e=>e.sessionId)),n=e.filter(e=>e.phase===`done`&&!t.has(e.sessionId)).map(e=>e.sessionId);n.length!==0&&(lo=new Set(n),go&&clearTimeout(go),go=setTimeout(()=>{go=null,lo=new Set,F()},qa))}function Lo(){if(M||typeof document>`u`)return M;M=document.createElement(`div`),M.className=`session-dock`,M.id=`sessionDock`,M.setAttribute(`role`,`navigation`),document.body.appendChild(M),N=document.createElement(`div`),N.className=`session-dock-tip`,document.body.appendChild(N),Ro();let e=document.getElementById(`chatContainer`);return e&&typeof ResizeObserver<`u`&&new ResizeObserver(Ro).observe(e),window.addEventListener(`resize`,Ro),M}function Ro(){if(!M)return;let e=document.getElementById(`chatContainer`);if(!e)return;let t=e.getBoundingClientRect();M.style.top=`${Math.max(0,Math.round(t.top+8))}px`}function zo(e){kr(e.sessionId,{focusMessageId:e.anchorMessageId||null})}function Bo(e){let n=document.createElement(`div`);n.className=`session-dock-item`,n.dataset.sessionId=e.sessionId,n.dataset.phase=e.phase,e.stale&&(n.dataset.stale=`true`),lo.has(e.sessionId)&&n.classList.add(`is-flash`);let r=e.title||t(`dock.unknownSession`),i=e.primary||r,a=Po(e),o=e.phase===`done`?`✓`:Array.from(r)[0]||`?`,s=document.createElement(`button`);if(s.type=`button`,s.className=`session-dock-chip`,s.setAttribute(`aria-label`,`${i} · ${a}`),s.title=``,s.textContent=o,s.addEventListener(`click`,()=>{zo(e)}),n.appendChild(s),e.queuedCount>0&&e.phase!==`done`){let t=document.createElement(`span`);t.className=`session-dock-badge`,t.textContent=String(e.queuedCount>99?`99+`:e.queuedCount),n.appendChild(t)}if(e.source===`scheduled`){let e=document.createElement(`span`);e.className=`session-dock-clock`,n.appendChild(e)}if(e.phase===`done`||e.stale){let r=document.createElement(`button`);r.type=`button`,r.className=`session-dock-dismiss`;let i=e.stale?t(`dock.dismissStale`):t(`dock.dismiss`);r.setAttribute(`aria-label`,i),r.title=i,r.textContent=`×`,r.addEventListener(`click`,t=>{t.stopPropagation(),$o(e.sessionId)}),n.appendChild(r)}return n.addEventListener(`mouseenter`,()=>Vo(n,e,a)),n.addEventListener(`mouseleave`,Ho),n.addEventListener(`focusin`,()=>Vo(n,e,a)),n.addEventListener(`focusout`,Ho),n}function Vo(e,n,r){if(!N)return;N.innerHTML=``;let i=document.createElement(`div`);i.className=`session-dock-tip-title`,i.textContent=n.primary||n.title||t(`dock.unknownSession`);let a=document.createElement(`div`);if(a.className=`session-dock-tip-status`,a.textContent=r,N.appendChild(i),n.sub){let e=document.createElement(`div`);e.className=`session-dock-tip-sub`,e.textContent=n.sub,N.appendChild(e)}N.appendChild(a);let o=e.getBoundingClientRect();N.style.top=`${Math.round(o.top)}px`,N.style.left=`${Math.round(o.right+8)}px`,N.classList.add(`show`)}function Ho(){N&&N.classList.remove(`show`)}function Uo(){return P||typeof document>`u`?P:(P=document.createElement(`div`),P.className=`session-dock-overflow`,P.setAttribute(`role`,`menu`),P.addEventListener(`mouseenter`,Wo),P.addEventListener(`mouseleave`,Go),P.addEventListener(`focusin`,Wo),P.addEventListener(`focusout`,Go),document.body.appendChild(P),P)}function Wo(){_o&&=(clearTimeout(_o),null)}function Go(){fo||(Wo(),_o=setTimeout(()=>{_o=null,Xo()},220))}function Ko(){let e=M?M.querySelector(`.session-dock-more`):null;e&&(e.setAttribute(`aria-expanded`,fo?`true`:`false`),e.classList.toggle(`is-open`,fo))}function qo(){let e=Uo();if(!e)return;e.innerHTML=``;let n=document.createElement(`div`);n.className=`session-dock-overflow-header`,n.textContent=t(`dock.overflowTitle`),e.appendChild(n);let r=document.createElement(`div`);r.className=`session-dock-overflow-list`;for(let e of uo){let n=e.primary||e.title||t(`dock.unknownSession`),i=Po(e),a=document.createElement(`button`);a.type=`button`,a.className=`session-dock-overflow-row`,a.dataset.phase=e.phase,e.stale&&(a.dataset.stale=`true`),a.setAttribute(`aria-label`,`${n} · ${i}`);let o=document.createElement(`span`);o.className=`session-dock-overflow-title`,o.textContent=n;let s=document.createElement(`span`);s.className=`session-dock-overflow-status`,s.textContent=i,a.appendChild(o),a.appendChild(s),a.addEventListener(`click`,()=>{Xo(),zo(e)}),r.appendChild(a)}e.appendChild(r)}function Jo(){if(!P||!M)return;let e=M.querySelector(`.session-dock-item--more`);if(!e)return;let t=e.getBoundingClientRect();P.style.left=`${Math.round(t.right+8)}px`;let n=P.offsetHeight||0,r=Math.max(8,window.innerHeight-n-8);P.style.top=`${Math.round(Math.min(Math.max(8,t.top),r))}px`}function Yo(){uo.length!==0&&Uo()&&(Wo(),qo(),Jo(),P.classList.add(`show`),Ko())}function Xo(){Wo(),fo=!1,P&&P.classList.remove(`show`),Ko()}function Zo(){if(P&&P.classList.contains(`show`)&&fo){Xo();return}Yo(),fo=!0,Ko()}function Qo(e){let n=document.createElement(`div`);n.className=`session-dock-item session-dock-item--more`,n.dataset.count=String(e.length);let r=document.createElement(`button`);return r.type=`button`,r.className=`session-dock-chip session-dock-more`,r.setAttribute(`aria-label`,t(`dock.moreAria`,{count:e.length})),r.setAttribute(`aria-expanded`,fo?`true`:`false`),r.textContent=`+${e.length>99?`99`:e.length}`,r.addEventListener(`click`,()=>Zo()),n.appendChild(r),n.addEventListener(`mouseenter`,()=>Yo()),n.addEventListener(`mouseleave`,Go),n.addEventListener(`focusin`,()=>Yo()),n.addEventListener(`focusout`,Go),n}function $o(e){e&&(ro.add(e),es(),F())}function es(){try{chrome.storage.local.set({[Wa]:Array.from(ro)}).catch(()=>{})}catch{}}function ts(){try{chrome.storage.local.get([Wa],e=>{let t=e?.[Wa];if(Array.isArray(t)){for(let e of t)ro.add(e);F()}})}catch{}}function ns(){if(!Lo())return;let e=Fo();if(Io(e),co=e,Xo(),uo=[],M.innerHTML=``,e.length===0){M.classList.remove(`show`),document.body.classList.remove(`has-session-dock`),Ho();return}let t=e.length>Ja?Ya:Ja;uo=e.slice(t);for(let n of e.slice(0,t))M.appendChild(Bo(n));uo.length>0&&M.appendChild(Qo(uo)),M.classList.add(`show`),document.body.classList.add(`has-session-dock`)}function F(){po||=setTimeout(()=>{po=null;try{ns()}catch(e){r.warn(`[SessionDock] render failed:`,e?.message||e)}},Ka)}function rs(){return new Promise(e=>{try{chrome.runtime.sendMessage({type:`QUERY_SESSION_RUNNING`},t=>{if(chrome.runtime.lastError||!t){e();return}Array.isArray(t.activeSessionIds)&&(so=yo(t.activeSessionIds)),e()})}catch{e()}})}function is(e){let t=e?.sessionId;if(!t)return;let n=Qa.get(t)||{};Qa.set(t,{nodeName:e.nodeName||n.nodeName||``,subtaskIndex:e.subtaskIndex||n.subtaskIndex||0,subtaskTotal:e.subtaskTotal||n.subtaskTotal||0}),to.set(t,Date.now()),F()}function as(e){e&&(Qa.delete(e),$a.delete(e),eo.delete(e),to.delete(e),ro.delete(e),io.delete(e),ao.delete(e),F())}function os(){if(!(ho||typeof document>`u`||!Lo())){ho=!0,ts(),document.addEventListener(`generating-state-changed`,F),document.addEventListener(`session-switched`,F),document.addEventListener(`generation-ended`,e=>{let t=e?.detail?.sessionId;t&&!eo.has(t)&&eo.set(t,Date.now()),F()}),document.addEventListener(`session-archived`,e=>as(e?.detail?.sessionId)),document.addEventListener(`session-deleted`,e=>as(e?.detail?.sessionId));try{un(F)}catch(e){r.debug(`[SessionDock] subscribe queue failed:`,e?.message||e)}try{chrome.runtime.onMessage.addListener(e=>e?e.type===`EXECUTION_STATUS_UPDATE`?(is(e),!1):e.type===`SCHEDULED_TASK_RUN_STATE`&&e.sessionId?(e.running?no.add(e.sessionId):no.delete(e.sessionId),F(),!1):(e.type===`SCHEDULED_SESSION_UPDATED`&&F(),!1):!1)}catch(e){r.debug(`[SessionDock] register runtime listener failed:`,e?.message||e)}document.addEventListener(`visibilitychange`,()=>{if(document.hidden){Xo();return}rs().then(F)}),document.addEventListener(`keydown`,e=>{e.key===`Escape`&&fo&&Xo()}),mo||=setInterval(()=>{document.hidden||rs().then(F)},Ga),rs().then(()=>{for(let e of so)$a.has(e)||$a.set(e,Date.now());ns()})}}function ss(){let e=document.getElementById(`chatNavUp`),n=document.getElementById(`chatNavDown`),r=document.getElementById(`chatNavHotzone`),i=document.getElementById(`chatNavButtons`),a=document.getElementById(`chatNavQuestionPanel`),o=[],s=!1,c=null,l=``,u=!1,d=!1;function f(e){let t=document.getElementById(`chatContainer`);if(!t)return-1;let n=t.getBoundingClientRect();return et(e,n.top,n.bottom)}function p(e,t){let n=document.getElementById(`chatContainer`);if(!n)return`noop`;let r=qe(n);if(r.length===0)return`noop`;let i=n.getBoundingClientRect().top;if(t){if(e===`prev`)r[0].start.scrollIntoView({behavior:`smooth`,block:`start`});else{let e=r[r.length-1].elements;e[e.length-1].scrollIntoView({behavior:`smooth`,block:`end`})}return`jumped`}let a=Xe(r.length,Qe(r,i),e);return a===null?(m(e),`blocked`):(r[a].start.scrollIntoView({behavior:`smooth`,block:`start`}),`jumped`)}function m(t){let r=t===`prev`?e:n;r&&(r.classList.remove(`blocked`),r.offsetWidth,r.classList.add(`blocked`),r.addEventListener(`animationend`,()=>r.classList.remove(`blocked`),{once:!0}))}function h(e,n){let r=a.querySelectorAll(`.chat-nav-question-item`);r.forEach(t=>{Number(t.dataset.groupIndex)===e?(t.classList.add(`current`),t.setAttribute(`aria-current`,`true`)):(t.classList.remove(`current`),t.setAttribute(`aria-current`,`false`))});let i=a.querySelector(`.chat-nav-question-header .count`);i&&(i.textContent=t(`chat.navPosition`,{current:e>=0?e+1:n,total:n}));let o=Array.from(r).find(t=>Number(t.dataset.groupIndex)===e);!d&&e>=0&&o&&o.scrollIntoView({block:`nearest`})}function g(){if(!a||!a.classList.contains(`expanded`))return;o=qe(document.getElementById(`chatContainer`));let e=l?qe(document.getElementById(`chatContainer`)).length:a.querySelectorAll(`.chat-nav-question-item`).length;if(o.length===0){a.innerHTML=``,a.classList.remove(`expanded`);return}if(!l&&e!==o.length){ee();return}h(f(o),o.length)}function ee(){if(!a)return!1;if(o=qe(document.getElementById(`chatContainer`)),o.length===0)return a.innerHTML=``,!1;let e=f(o),t=document.activeElement===a.querySelector(`[data-role="nav-search"]`);a.innerHTML=ft(o,e,s,l),a.querySelector(`.chat-nav-pin`).addEventListener(`click`,e=>{e.stopPropagation(),b()});let n=a.querySelector(`[data-role="nav-search"]`);if(n){let e=()=>{l!==n.value&&(l=n.value,ee())};n.addEventListener(`input`,t=>{t.isComposing||e()}),n.addEventListener(`compositionend`,e),t&&(n.focus(),n.setSelectionRange(n.value.length,n.value.length))}if(e>=0){let t=a.querySelector(`.chat-nav-question-item[data-group-index="${e}"]`);t&&t.scrollIntoView({block:`nearest`})}return!0}function te(){let e=document.activeElement;return e?[r,i,a].some(t=>t&&(t===e||t.contains(e))):!1}function ne(){i.classList.remove(`expanded`),a&&a.classList.remove(`expanded`)}function _(){let e=te();ne(),e&&r&&(u=!0,r.focus({preventScroll:!0}),u=!1)}function v(){if(clearTimeout(c),i.classList.add(`expanded`),a){if(a.classList.contains(`expanded`)){g();return}ee()?a.classList.add(`expanded`):a.classList.remove(`expanded`)}}function re(e){clearTimeout(c),!s&&(te()||(e?ne():c=setTimeout(ne,300)))}function y(e){if(s=e,r&&(r.classList.toggle(`pinned`,e),r.setAttribute(`aria-pressed`,String(e))),a){a.classList.toggle(`pinned`,e);let n=a.querySelector(`.chat-nav-pin`);if(n){let r=t(e?`chat.navUnpinLabel`:`chat.navPinLabel`);n.textContent=r,n.title=r,n.setAttribute(`aria-pressed`,String(e)),n.classList.toggle(`on`,e)}}}function b(){y(!s)}e&&e.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),p(`prev`,e.ctrlKey||e.metaKey),g()}),n&&n.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),p(`next`,e.ctrlKey||e.metaKey),g()}),r&&i&&(r.addEventListener(`mouseenter`,v),r.addEventListener(`mouseleave`,()=>re(!1)),r.addEventListener(`click`,()=>b()),r.addEventListener(`focus`,()=>{u||v()}),r.addEventListener(`blur`,()=>re(!1)),r.addEventListener(`keydown`,e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),b())}),i.addEventListener(`mouseenter`,v),i.addEventListener(`mouseleave`,()=>re(!1)),i.addEventListener(`focusin`,v),a&&(a.addEventListener(`mouseenter`,()=>{d=!0,v()}),a.addEventListener(`mouseleave`,()=>{d=!1,re(!1)}),a.addEventListener(`focusin`,v),a.addEventListener(`keydown`,e=>{if(e.target.matches(`[data-role="nav-search"]`))return;let t=Array.from(a.querySelectorAll(`.chat-nav-question-item`));if(t.length===0)return;let n=t.indexOf(document.activeElement),r=null;e.key===`ArrowDown`?r=Math.min(n+1,t.length-1):e.key===`ArrowUp`?r=n<=0?0:n-1:e.key===`Home`?r=0:e.key===`End`&&(r=t.length-1),r!==null&&(e.preventDefault(),t[r].focus())}),a.addEventListener(`click`,e=>{let t=e.target.closest(`.chat-nav-question-item`);if(!t||!t.dataset.messageId)return;let n=o.find(e=>(e.userElement||e.start).dataset.messageId===t.dataset.messageId);if(!n)return;let r=n.userElement||n.start;r.scrollIntoView({behavior:`instant`,block:`start`}),r.classList.add(`bookmark-highlight`),setTimeout(()=>r.classList.remove(`bookmark-highlight`),2e3),s?g():_()})));{let e=document.getElementById(`chatContainer`);if(e){let t=!1;e.addEventListener(`scroll`,()=>{!a||!a.classList.contains(`expanded`)||t||(t=!0,requestAnimationFrame(()=>{t=!1,g()}))},{passive:!0})}}function x(){let e=a&&a.classList.contains(`expanded`);if(!s&&!e)return!1;if(a&&a.querySelector(`[data-role="nav-search"]`)&&l){l=``,ee();let e=a.querySelector(`[data-role="nav-search"]`);return e&&e.focus(),!0}return y(!1),_(),!0}return{jumpToMessage:p,updateActiveQuestion:g,handleEscape:x,isPinned:()=>s}}function cs(e){if(!e)return!1;let t=e.nodeType===Node.TEXT_NODE?e.parentElement:e;return!!(t&&t.closest&&t.closest(`#chatContainer, .message-fullscreen-body`))}e(`zh`,{searchPanel:{toggleTitle:`消息搜索`,title:`消息搜索`,closeTitle:`关闭`,inputPlaceholder:`搜索消息(支持 & | 组合搜索)...`,clearTitle:`清除`,globalSearchTitle:`在所有会话中搜索`,globalSearch:`全局搜索`,currentSessionTitle:`仅在当前会话中搜索`,currentSession:`当前会话`,startSearchHint:`输入关键词开始搜索`,searching:`搜索中...`,searchingWithCount:`搜索中... {count} 条`,searchError:`搜索出错`,noActiveSession:`没有活跃会话`,noSessionData:`没有会话数据`,noMatch:`未找到匹配消息`,unknownSession:`未知会话`,countResult:`{count} 条`,noResult:`无结果`,searchingSuffix:` (搜索中...)`,currentSessionResults:`当前会话{label} · {count} 条`,otherSessionsResults:`其他会话 · {count} 条`,roleUser:`你`,roleAssistant:`助手`,sessionNotExist:`会话已不存在`,messageDeleted:`消息已被删除`}}),e(`en`,{searchPanel:{toggleTitle:`Search messages`,title:`Message search`,closeTitle:`Close`,inputPlaceholder:`Search messages (supports & | combined search)...`,clearTitle:`Clear`,globalSearchTitle:`Search in all sessions`,globalSearch:`Global search`,currentSessionTitle:`Search in current session only`,currentSession:`Current session`,startSearchHint:`Enter keywords to start searching`,searching:`Searching...`,searchingWithCount:`Searching... {count} found`,searchError:`Search error`,noActiveSession:`No active session`,noSessionData:`No session data`,noMatch:`No matching messages found`,unknownSession:`Unknown session`,countResult:`{count} found`,noResult:`No results`,searchingSuffix:` (searching...)`,currentSessionResults:`Current session{label} · {count} found`,otherSessionsResults:`Other sessions · {count} found`,roleUser:`You`,roleAssistant:`Assistant`,sessionNotExist:`Session no longer exists`,messageDeleted:`Message has been deleted`}});var ls=!1,us=!1,I=[],ds=``;function fs(){v.searchInputHistory=[],v.searchInputHistoryIndex=-1;try{chrome.storage.local.get([`searchInputHistory`],e=>{e.searchInputHistory&&(v.searchInputHistory=e.searchInputHistory)})}catch{}let e=document.createElement(`div`);e.className=`search-panel-container`,e.id=`searchPanelContainer`,e.innerHTML=`
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/context-indicator-Bs34HFah.js","assets/chunk-CMxvf4Kt.js","assets/model-profiles-C3kJEHM6.js","assets/i18n-DvmxOw8q.js","assets/version-h3EcDzjp.js","assets/agent-store-QTeMyM9O.js","assets/session-store-owqj23pJ.js","assets/voice-shortcut-Dtt3nhkz.js","assets/workspace-manager-DVPkwn2d.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-DvmxOw8q.js";import{A as s,At as c,Bt as l,Ht as u,J as d,Jt as f,L as p,Lt as m,M as h,Nt as g,Ot as ee,P as te,R as ne,U as _,b as v,c as re,ct as y,d as b,gt as x,ht as ie,i as S,it as C,jt as ae,k as oe,q as w,r as se,rt as ce,u as T,wt as le,x as E,y as ue,zt as de}from"./model-profiles-C3kJEHM6.js";import{_ as D,d as fe}from"./session-store-owqj23pJ.js";import{A as pe,C as me,D as he,E as ge,M as _e,N as ve,O as ye,S as be,T as xe,_ as Se,a as Ce,b as we,c as Te,d as Ee,f as De,g as Oe,h as ke,i as Ae,j as je,k as Me,l as Ne,m as Pe,n as O,o as Fe,p as Ie,r as Le,s as Re,t as ze,u as Be,v as Ve,w as He,x as Ue,y as We}from"./todo-model-DK2Wxmvk.js";import{$ as Ge,A as Ke,D as qe,G as Je,H as Ye,J as Xe,K as Ze,M as k,N as Qe,O as $e,P as et,Q as tt,R as nt,T as rt,V as it,W as at,Y as A,Z as ot,_ as st,et as ct,g as lt,j,k as ut,l as dt,q as ft,t as pt,tt as mt,v as ht,y as gt}from"./version-h3EcDzjp.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-Bs34HFah.js";import{o as ra}from"./agent-store-QTeMyM9O.js";import{O as ia,b as aa,l as oa,p as sa,v as ca}from"./workspace-manager-DVPkwn2d.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-Bs34HFah.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-Bs34HFah.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 et(e,n.top,n.bottom)}function p(e,t){let n=document.getElementById(`chatContainer`);if(!n)return`noop`;let r=qe(n);if(r.length===0)return`noop`;let i=n.getBoundingClientRect().top;if(t){if(e===`prev`)r[0].start.scrollIntoView({behavior:`smooth`,block:`start`});else{let e=r[r.length-1].elements;e[e.length-1].scrollIntoView({behavior:`smooth`,block:`end`})}return`jumped`}let a=Xe(r.length,Qe(r,i),e);return a===null?(m(e),`blocked`):(r[a].start.scrollIntoView({behavior:`smooth`,block:`start`}),`jumped`)}function m(t){let r=t===`prev`?e:n;r&&(r.classList.remove(`blocked`),r.offsetWidth,r.classList.add(`blocked`),r.addEventListener(`animationend`,()=>r.classList.remove(`blocked`),{once:!0}))}function h(e,n){let r=a.querySelectorAll(`.chat-nav-question-item`);r.forEach(t=>{Number(t.dataset.groupIndex)===e?(t.classList.add(`current`),t.setAttribute(`aria-current`,`true`)):(t.classList.remove(`current`),t.setAttribute(`aria-current`,`false`))});let i=a.querySelector(`.chat-nav-question-header .count`);i&&(i.textContent=t(`chat.navPosition`,{current:e>=0?e+1:n,total:n}));let o=Array.from(r).find(t=>Number(t.dataset.groupIndex)===e);!d&&e>=0&&o&&o.scrollIntoView({block:`nearest`})}function g(){if(!a||!a.classList.contains(`expanded`))return;o=qe(document.getElementById(`chatContainer`));let e=l?qe(document.getElementById(`chatContainer`)).length:a.querySelectorAll(`.chat-nav-question-item`).length;if(o.length===0){a.innerHTML=``,a.classList.remove(`expanded`);return}if(!l&&e!==o.length){ee();return}h(f(o),o.length)}function ee(){if(!a)return!1;if(o=qe(document.getElementById(`chatContainer`)),o.length===0)return a.innerHTML=``,!1;let e=f(o),t=document.activeElement===a.querySelector(`[data-role="nav-search"]`);a.innerHTML=ft(o,e,s,l),a.querySelector(`.chat-nav-pin`).addEventListener(`click`,e=>{e.stopPropagation(),b()});let n=a.querySelector(`[data-role="nav-search"]`);if(n){let e=()=>{l!==n.value&&(l=n.value,ee())};n.addEventListener(`input`,t=>{t.isComposing||e()}),n.addEventListener(`compositionend`,e),t&&(n.focus(),n.setSelectionRange(n.value.length,n.value.length))}if(e>=0){let t=a.querySelector(`.chat-nav-question-item[data-group-index="${e}"]`);t&&t.scrollIntoView({block:`nearest`})}return!0}function te(){let e=document.activeElement;return e?[r,i,a].some(t=>t&&(t===e||t.contains(e))):!1}function ne(){i.classList.remove(`expanded`),a&&a.classList.remove(`expanded`)}function _(){let e=te();ne(),e&&r&&(u=!0,r.focus({preventScroll:!0}),u=!1)}function v(){if(clearTimeout(c),i.classList.add(`expanded`),a){if(a.classList.contains(`expanded`)){g();return}ee()?a.classList.add(`expanded`):a.classList.remove(`expanded`)}}function re(e){clearTimeout(c),!s&&(te()||(e?ne():c=setTimeout(ne,300)))}function y(e){if(s=e,r&&(r.classList.toggle(`pinned`,e),r.setAttribute(`aria-pressed`,String(e))),a){a.classList.toggle(`pinned`,e);let n=a.querySelector(`.chat-nav-pin`);if(n){let r=t(e?`chat.navUnpinLabel`:`chat.navPinLabel`);n.textContent=r,n.title=r,n.setAttribute(`aria-pressed`,String(e)),n.classList.toggle(`on`,e)}}}function b(){y(!s)}e&&e.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),p(`prev`,e.ctrlKey||e.metaKey),g()}),n&&n.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),p(`next`,e.ctrlKey||e.metaKey),g()}),r&&i&&(r.addEventListener(`mouseenter`,v),r.addEventListener(`mouseleave`,()=>re(!1)),r.addEventListener(`click`,()=>b()),r.addEventListener(`focus`,()=>{u||v()}),r.addEventListener(`blur`,()=>re(!1)),r.addEventListener(`keydown`,e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),b())}),i.addEventListener(`mouseenter`,v),i.addEventListener(`mouseleave`,()=>re(!1)),i.addEventListener(`focusin`,v),a&&(a.addEventListener(`mouseenter`,()=>{d=!0,v()}),a.addEventListener(`mouseleave`,()=>{d=!1,re(!1)}),a.addEventListener(`focusin`,v),a.addEventListener(`keydown`,e=>{if(e.target.matches(`[data-role="nav-search"]`))return;let t=Array.from(a.querySelectorAll(`.chat-nav-question-item`));if(t.length===0)return;let n=t.indexOf(document.activeElement),r=null;e.key===`ArrowDown`?r=Math.min(n+1,t.length-1):e.key===`ArrowUp`?r=n<=0?0:n-1:e.key===`Home`?r=0:e.key===`End`&&(r=t.length-1),r!==null&&(e.preventDefault(),t[r].focus())}),a.addEventListener(`click`,e=>{let t=e.target.closest(`.chat-nav-question-item`);if(!t||!t.dataset.messageId)return;let n=o.find(e=>(e.userElement||e.start).dataset.messageId===t.dataset.messageId);if(!n)return;let r=n.userElement||n.start;r.scrollIntoView({behavior:`instant`,block:`start`}),r.classList.add(`bookmark-highlight`),setTimeout(()=>r.classList.remove(`bookmark-highlight`),2e3),s?g():_()})));{let e=document.getElementById(`chatContainer`);if(e){let t=!1;e.addEventListener(`scroll`,()=>{!a||!a.classList.contains(`expanded`)||t||(t=!0,requestAnimationFrame(()=>{t=!1,g()}))},{passive:!0})}}function x(){let e=a&&a.classList.contains(`expanded`);if(!s&&!e)return!1;if(a&&a.querySelector(`[data-role="nav-search"]`)&&l){l=``,ee();let e=a.querySelector(`[data-role="nav-search"]`);return e&&e.focus(),!0}return y(!1),_(),!0}return{jumpToMessage:p,updateActiveQuestion:g,handleEscape:x,isPinned:()=>s}}function 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=`
|
|
4
3
|
<button class="search-panel-toggle" id="searchPanelToggle" title="${t(`searchPanel.toggleTitle`)}">
|
|
5
4
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
6
5
|
<circle cx="11" cy="11" r="8"/>
|
|
@@ -35,13 +34,13 @@ import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-DvmxOw8q.js"
|
|
|
35
34
|
<div class="search-panel-empty">${t(`searchPanel.startSearchHint`)}</div>
|
|
36
35
|
</div>
|
|
37
36
|
</div>
|
|
38
|
-
`,
|
|
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`),$e(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`),Ze(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">
|
|
39
38
|
<div class="search-section-title">${t(`searchPanel.currentSessionResults`,{label:l,count:o.length})}</div>
|
|
40
|
-
${
|
|
39
|
+
${Ts(o,n)}
|
|
41
40
|
</div>`),s.length>0&&(c+=`<div class="search-section">
|
|
42
41
|
<div class="search-section-title">${t(`searchPanel.otherSessionsResults`,{count:s.length})}</div>
|
|
43
|
-
${
|
|
44
|
-
</div>`),r.innerHTML=c}function
|
|
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(k(e.matchPreview),n);return`
|
|
45
44
|
<div class="search-result-item" data-session-id="${e.sessionId}" data-message-id="${e.messageId}" title="${k(e.content)}">
|
|
46
45
|
<div class="search-result-header">
|
|
47
46
|
<span class="search-result-role">${i} ${a}</span>
|
|
@@ -49,7 +48,7 @@ import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-DvmxOw8q.js"
|
|
|
49
48
|
</div>
|
|
50
49
|
<div class="search-result-preview">${c}</div>
|
|
51
50
|
</div>
|
|
52
|
-
`}).join(``)}function
|
|
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-Bs34HFah.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-Bs34HFah.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=`
|
|
53
52
|
<style>
|
|
54
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; }
|
|
55
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; }
|
|
@@ -156,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"
|
|
|
156
155
|
</div>
|
|
157
156
|
<div class="schedule-panel-list" id="schedulePanelList"></div>
|
|
158
157
|
</div>
|
|
159
|
-
`,
|
|
158
|
+
`,Et(`schedule`).appendChild(e);let n=document.createElement(`div`);n.className=`sched-modal-overlay`,n.id=`scheduleModalOverlay`,n.innerHTML=`
|
|
160
159
|
<div class="sched-modal">
|
|
161
160
|
<div class="sched-modal-header">
|
|
162
161
|
<h3 id="scheduleModalTitle"></h3>
|
|
@@ -203,23 +202,23 @@ import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-DvmxOw8q.js"
|
|
|
203
202
|
<button class="primary" id="scheduleModalSave">${t(`schedPanel.save`)}</button>
|
|
204
203
|
</div>
|
|
205
204
|
</div>
|
|
206
|
-
`,document.body.appendChild(n);let r=document.getElementById(`schedulePanelToggle`),i=document.getElementById(`schedulePanel`),a=new Set;function o(){let e=a.size>0;r.classList.toggle(`running`,e),r.title=e?`${t(`schedPanel.toggleTitle`)} · ${t(`schedPanel.toggleRunning`)}`:t(`schedPanel.toggleTitle`)}let s=document.getElementById(`schedulePanelClose`),c=document.getElementById(`scheduleNewTask`),l=document.getElementById(`schedulePanelList`),u=document.getElementById(`scheduleModalOverlay`),d=document.getElementById(`scheduleModalTitle`),f=document.getElementById(`scheduleModalCancel`),p=document.getElementById(`scheduleModalSave`),m=document.getElementById(`schedFormType`),h=document.getElementById(`schedFormValue`),g=document.getElementById(`schedFormOnceMode`),ee=document.getElementById(`schedOnceModeWrap`),te=document.getElementById(`schedValueLabel`),ne=document.getElementById(`schedEndWrap`),_=null,re=`schedPanelView`,y=`all`,b=`created`,x=[],ie=document.getElementById(`schedFilterGroup`),S=document.getElementById(`schedSortSelect`);function C(e){if(typeof e==`number`)return Number.isFinite(e)?e:0;let t=Date.parse(e||``);return Number.isFinite(t)?t:0}function ae(e){return b===`lastRun`?C(e.lastRunAt)||C(e.createdAt):b===`updated`&&C(e.updatedAt)||C(e.createdAt)}function oe(){ie.querySelectorAll(`.sched-filter-btn`).forEach(e=>{e.classList.toggle(`active`,e.dataset.filter===y)}),S.value=b}function w(){try{Promise.resolve(chrome.storage.local.set({[re]:{filter:y,sort:b}})).catch(()=>{})}catch{}}ie.addEventListener(`click`,e=>{let t=e.target.closest(`.sched-filter-btn`);!t||t.dataset.filter===y||(y=t.dataset.filter,oe(),w(),E(x))}),S.addEventListener(`change`,()=>{b=S.value,w(),E(x)}),(async()=>{try{let e=(await chrome.storage.local.get(re))?.[re];(e?.filter===`enabled`||e?.filter===`disabled`||e?.filter===`all`)&&(y=e.filter),(e?.sort===`lastRun`||e?.sort===`updated`||e?.sort===`created`)&&(b=e.sort)}catch{}oe(),x.length&&E(x)})();function se(){let e=m.value,n=g.value;ee.style.display=e===`once`?``:`none`,ne.style.display=e===`interval`?``:`none`,e===`once`?n===`relative`?(te.textContent=t(`schedPanel.onceModeRelative`),h.type=`text`,h.placeholder=t(`schedPanel.relativeValuePlaceholder`)):(te.textContent=t(`schedPanel.onceModeAbsolute`),h.type=`datetime-local`,h.placeholder=``):e===`interval`?(te.textContent=t(`schedPanel.valueLabelInterval`),h.type=`text`,h.placeholder=t(`schedPanel.intervalValuePlaceholder`)):(te.textContent=t(`schedPanel.valueLabelCron`),h.type=`text`,h.placeholder=t(`schedPanel.cronValuePlaceholder`))}function ce(e){e?(i.classList.add(`open`),$e(i),T()):(i.classList.remove(`open`),Ze(i))}r.addEventListener(`click`,()=>{ce(!i.classList.contains(`open`))}),s.addEventListener(`click`,()=>ce(!1)),m.addEventListener(`change`,se),g.addEventListener(`change`,se),document.getElementById(`scheduleModalCloseBtn`).addEventListener(`click`,D),f.addEventListener(`click`,D),p.addEventListener(`click`,pe),c.addEventListener(`click`,()=>de(null)),document.getElementById(`schedUseCurrentPage`).addEventListener(`click`,async()=>{try{let e=(await chrome.tabs.query({active:!0,currentWindow:!0}))?.[0]?.url||``;e&&(document.getElementById(`schedFormUrl`).value=e)}catch{}});async function T(){try{let e=(await
|
|
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`),$e(i),T()):(i.classList.remove(`open`),Ze(i))}r.addEventListener(`click`,()=>{ce(!i.classList.contains(`open`))}),s.addEventListener(`click`,()=>ce(!1)),m.addEventListener(`change`,se),g.addEventListener(`change`,se),document.getElementById(`scheduleModalCloseBtn`).addEventListener(`click`,D),f.addEventListener(`click`,D),p.addEventListener(`click`,pe),c.addEventListener(`click`,()=>de(null)),document.getElementById(`schedUseCurrentPage`).addEventListener(`click`,async()=>{try{let e=(await chrome.tabs.query({active:!0,currentWindow:!0}))?.[0]?.url||``;e&&(document.getElementById(`schedFormUrl`).value=e)}catch{}});async function T(){try{let e=(await 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">${k(String(e?.message||e))}</div>`}}function le(e){return!e||!e.length?`<div class="sched-history"><div class="sched-run">${t(`schedPanel.runHistoryEmpty`)}</div></div>`:`<div class="sched-history">${e.slice().reverse().map(e=>`
|
|
207
206
|
<div class="sched-run">
|
|
208
207
|
<span class="dot ${k(e.status||``)}"></span>
|
|
209
|
-
<span class="time">${k(
|
|
210
|
-
<span>${k(
|
|
211
|
-
<span class="dur">${k(
|
|
208
|
+
<span class="time">${k(ks(e.startedAt))}</span>
|
|
209
|
+
<span>${k(js(e.status))}</span>
|
|
210
|
+
<span class="dur">${k(As(e.durationMs))}</span>
|
|
212
211
|
${e.error?`<span class="err" title="${k(e.error)}">${k(e.error)}</span>`:``}
|
|
213
212
|
</div>
|
|
214
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`
|
|
215
214
|
<div class="sched-item" data-id="${k(e.id)}">
|
|
216
215
|
<div class="row1">
|
|
217
216
|
<span class="name" title="${k(e.name)}">${k(e.name)}</span>
|
|
218
|
-
${
|
|
217
|
+
${Ps(e)}
|
|
219
218
|
</div>
|
|
220
219
|
${e.description?`<div class="desc">${k(e.description)}</div>`:``}
|
|
221
|
-
<div class="meta">${k(
|
|
222
|
-
<div class="meta">${t(`schedPanel.nextRun`)}: ${k(
|
|
220
|
+
<div class="meta">${k(Ns(e))}</div>
|
|
221
|
+
<div class="meta">${t(`schedPanel.nextRun`)}: ${k(ks(e.nextRunAt))}</div>
|
|
223
222
|
${r}
|
|
224
223
|
<div class="sched-history" data-history style="display:none;">${le(e.runHistory)}</div>
|
|
225
224
|
<div class="actions">
|
|
@@ -229,14 +228,14 @@ import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-DvmxOw8q.js"
|
|
|
229
228
|
<button data-act="delete" class="danger">${t(`schedPanel.delete`)}</button>
|
|
230
229
|
</div>
|
|
231
230
|
</div>
|
|
232
|
-
`}).join(``)}l.addEventListener(`click`,async e=>{let n=e.target.closest(`button[data-act]`);if(!n)return;let r=n.closest(`.sched-item`),i=r?.dataset.id;if(!i)return;let a=n.dataset.act;if(a===`toggle`){let e=(await ue())[i];if(!e)return;await Es({type:`SCHEDULED_TASK_TOGGLE`,id:i,enabled:!e.enabled}),T()}else if(a===`run`){let e=await Es({type:`SCHEDULED_TASK_RUN_NOW`,id:i});e?.success?(A(t(`schedPanel.runNowToast`),`success`),Ps(e.sessionId),setTimeout(T,1500)):A(e?.error||t(`schedPanel.createFailed`),`error`)}else if(a===`history`){let e=r.querySelector(`[data-history]`);e&&(e.style.display=e.style.display===`none`?``:`none`)}else if(a===`edit`)de((await ue())[i]);else if(a===`delete`){let e=(await ue())[i];await window.showCustomConfirm(t(`schedPanel.deleteConfirmMsg`,{name:e?.name||``}),t(`schedPanel.deleteConfirmTitle`))&&(await Es({type:`SCHEDULED_TASK_DELETE`,id:i}),A(t(`schedPanel.deleted`),`success`),T())}});async function ue(){let e=await Es({type:`SCHEDULED_TASK_LIST`}),t={};return(e?.tasks||[]).forEach(e=>{t[e.id]=e}),t}async function de(e){_=e||null,d.textContent=t(e?`schedPanel.editTitle`:`schedPanel.newTask`),document.getElementById(`schedFormName`).value=e?.name||``,document.getElementById(`schedFormDesc`).value=e?.description||``,document.getElementById(`schedFormPrompt`).value=e?.prompt||``,document.getElementById(`schedFormUrl`).value=e?.contextUrl||``,m.value=e?.schedule?.type||`interval`,g.value=e?.schedule?.onceMode||`relative`,se(),h.value=e?.schedule?.value||``,document.getElementById(`schedFormContextMode`).value=e?.contextMode||`fetch`,document.getElementById(`schedFormMaxRuns`).value=e?.maxRuns??``,document.getElementById(`schedFormEndAt`).value=e?.endAt?As(e.endAt):``;let n=document.getElementById(`schedFormSession`),r=`<option value="">${t(`schedPanel.sessionAuto`)}</option>`;try{let{list:t}=await fe(),n=[...t].sort((e,t)=>{let n=e.order??0,r=t.order??0;return n===r?new Date(t.createdAt||0)-new Date(e.createdAt||0):r-n});for(let t of n){let n=e?.sessionId===t.id?`selected`:``,i=k(t.title||t.id);r+=`<option value="${k(t.id)}" ${n}>${i}</option>`}}catch{}n.innerHTML=r,u.classList.add(`open`)}function D(){u.classList.remove(`open`),_=null}async function pe(){let e=document.getElementById(`schedFormName`).value.trim(),n=document.getElementById(`schedFormPrompt`).value.trim(),r=m.value,i=h.value.trim();if(!e){A(t(`schedPanel.nameRequired`),`warning`);return}if(!n){A(t(`schedPanel.promptRequired`),`warning`);return}if(!i){A(t(`schedPanel.scheduleRequired`),`warning`);return}let a=r===`interval`&&parseInt(document.getElementById(`schedFormMaxRuns`).value,10)||null,o=r===`interval`?document.getElementById(`schedFormEndAt`).value:``,s=o?new Date(o).getTime():null,c={name:e,description:document.getElementById(`schedFormDesc`).value.trim(),prompt:n,schedule:r===`once`?{type:r,value:i,onceMode:g.value}:{type:r,value:i},contextUrl:document.getElementById(`schedFormUrl`).value.trim()||null,contextMode:document.getElementById(`schedFormContextMode`).value||`fetch`,sessionId:document.getElementById(`schedFormSession`).value||null,maxRuns:a,endAt:s,enabled:_?_.enabled:!0};try{let e=await Es({type:_?`SCHEDULED_TASK_UPDATE`:`SCHEDULED_TASK_CREATE`,task:_?{...c,id:_.id}:c});e?.success?(A(t(`schedPanel.saved`),`success`),D(),T()):A(e?.error||t(`schedPanel.createFailed`),`error`)}catch(e){A(e?.message||t(`schedPanel.createFailed`),`error`)}}chrome.runtime.onMessage.addListener(e=>{e.type===`SCHEDULED_TASK_RUN_STATE`&&e.taskId&&(e.running?a.add(e.taskId):a.delete(e.taskId),o())}),chrome.runtime.onMessage.addListener(e=>{e.type===`SCHEDULED_SESSION_UPDATED`&&(i.classList.contains(`open`)&&T().catch(()=>{}),e.sessionId&&e.sessionId===v.activeSessionId&&setTimeout(Ns,600))}),chrome.runtime.onMessage.addListener(e=>{e.type===`SCHEDULED_TASKS_CHANGED`&&T().catch(()=>{})}),se(),ce(!1),T().catch(()=>{})}var Is=`todoStatsLog`,Ls=7;function Rs(e){return String(e).padStart(2,`0`)}function zs(e=Date.now()){let t=new Date(e);return`${t.getFullYear()}-${Rs(t.getMonth()+1)}-${Rs(t.getDate())}`}function Bs(e,t){let n=new Date(e);return n.setDate(n.getDate()+t),n.getTime()}function Vs(e,t,n,r){let i=e&&typeof e==`object`?e:{},a=i[t]&&typeof i[t]==`object`?i[t]:{},o=(Number.isFinite(a[n])?a[n]:0)+(Number.isFinite(r)?r:0);return{...i,[t]:{...a,[n]:Math.max(0,o)}}}function Hs(e,t=Date.now()){let n=zs(Bs(t,-90)),r={};for(let[t,i]of Object.entries(e&&typeof e==`object`?e:{}))t>=n&&(r[t]=i);return r}function Us(e,t){let n=e&&e[t];return{added:Number.isFinite(n&&n.added)?n.added:0,done:Number.isFinite(n&&n.done)?n.done:0}}function Ws(e,t){let n=Us(e,zs(t)).done>0?t:Bs(t,-1),r=0;for(;r<=90&&!(Us(e,zs(n)).done<=0);)r+=1,n=Bs(n,-1);return r}function Gs(e,t,n=Date.now()){let r=Array.isArray(e)?e.map(Ue):[],{stats:i}=Be(r),a=t&&typeof t==`object`?t:{},o=[];for(let e=Ls-1;e>=0;--e){let t=zs(Bs(n,-e));o.push({date:t,...Us(a,t)})}return{total:i.total,done:i.done,doing:i.doing,pending:i.pending,overdue:r.filter(e=>De(e,n)).length,high:r.filter(e=>e.status!==O.DONE&&e.priority===ze.HIGH).length,doneRate:i.total?Math.round(i.done/i.total*100):0,today:Us(a,zs(n)),week:o,streak:Ws(a,n)}}var Ks=Promise.resolve();async function qs(){try{if(typeof chrome>`u`||!chrome.storage?.local?.get)return{};let e=await chrome.storage.local.get([Is]),t=e&&e.todoStatsLog;return t&&typeof t==`object`?t:{}}catch(e){return r.warn(`[Todo] load stats log failed:`,e),{}}}async function Js(e){typeof chrome>`u`||!chrome.storage?.local?.set||await chrome.storage.local.set({[Is]:e})}function Ys(e,t,n=Date.now()){let i=Ks.then(async()=>{let r=Hs(Vs(await qs(),zs(n),e,t));return await Js(r),r});return Ks=i.then(()=>void 0,()=>void 0),i.catch(e=>(r.warn(`[Todo] record stat failed:`,e),null))}var Xs=new Set,Zs=Promise.resolve();function Qs(e){let t=Zs.then(e);return Zs=t.then(()=>void 0,()=>void 0),t}function $s(e){return typeof e==`function`?(Xs.add(e),()=>Xs.delete(e)):()=>{}}function L(){for(let e of Xs)try{e()}catch(e){r.warn(`[Todo] listener failed:`,e)}}async function ec(){try{v.todos=(await C()||[]).map(Ue).filter(e=>e.id&&e.title),r.debug(`[Todo] loaded todos:`,v.todos.length)}catch(e){r.error(`[Todo] load todos failed:`,e),v.todos=[]}L()}function tc(){return Be(v.todos)}function nc(e){return v.todos.find(t=>t.id===e)||null}function rc(e){v.todos=v.todos.map(t=>t.id===e.id?e:t)}async function ic(e,t={}){let n=String(e||``).trim();if(!n)return null;let i=Fe(n,t);return i.order=Oe(v.todos),v.todos=[...v.todos,i],await Qs(()=>ie(i)).catch(e=>(r.error(`[Todo] add failed:`,e),!1))?(L(),await Ys(`added`,1,i.createdAt),i):(v.todos=v.todos.filter(e=>e.id!==i.id),L(),null)}async function ac(e,t={}){let n=nc(e);if(!n)return!1;let i={...n,updatedAt:Date.now()};if(t.title!==void 0){let e=String(t.title).trim();if(!e)return!1;i.title=e}return t.note!==void 0&&(i.note=String(t.note||``).trim()),t.dueAt!==void 0&&(i.dueAt=Number.isFinite(t.dueAt)?t.dueAt:null),t.priority!==void 0&&(i.priority=we(t.priority)),t.link!==void 0&&(i.link=We(t.link).url),rc(i),await Qs(()=>ie(i)).catch(e=>(r.error(`[Todo] update failed:`,e),!1))?(L(),!0):(rc(n),L(),!1)}async function oc(e,t){let n=nc(e);if(!n||!Ie(t))return!1;if(n.status===t)return!0;let i=Date.now(),a={...n,status:t,updatedAt:i};return t===O.DONE?(a.completedAt=i,n.status!==O.DONE&&(a.prevStatus=n.status)):n.status===O.DONE&&(a.completedAt=null,a.prevStatus=null),rc(a),await Qs(()=>ie(a)).catch(e=>(r.error(`[Todo] set status failed:`,e),!1))?(L(),t===O.DONE&&n.status!==O.DONE?await Ys(`done`,1,a.completedAt):n.status===O.DONE&&t!==O.DONE&&await Ys(`done`,-1,n.completedAt),!0):(rc(n),L(),!1)}function sc(e){let t=nc(e);return t?oc(e,Ve(t.status)):Promise.resolve(!1)}function cc(e){let t=nc(e);return!t||t.status!==O.DONE?Promise.resolve(!1):oc(e,He(t))}function lc(e,t){return ac(e,{priority:we(t)})}async function uc(e,t){if(!nc(e))return{ok:!1,reason:`missing`};let n=We(t);if(!n.valid)return{ok:!1,reason:`invalid`};let r=await ac(e,{link:n.url});return{ok:r,reason:r?``:`save`}}async function dc(e){let t=nc(e);return t?(v.todos=v.todos.filter(t=>t.id!==e),await Qs(()=>w(e)).catch(e=>(r.error(`[Todo] delete failed:`,e),!1))?(L(),!0):(v.todos=[...v.todos,t],L(),!1)):!1}async function fc(e,t){let{active:n}=tc();if(e===t)return!0;if(e<0||e>=n.length)return!1;let i=ge(me(n,e,t)),a=new Map(i.map(e=>[e.id,e])),o=v.todos;if(v.todos=v.todos.map(e=>a.get(e.id)||e),!await Qs(()=>x(i)).catch(e=>(r.error(`[Todo] reorder failed:`,e),!1))){let e=new Map(o.map(e=>[e.id,e.order]));return v.todos=v.todos.map(t=>e.has(t.id)?{...t,order:e.get(t.id)}:t),L(),!1}return L(),!0}async function pc(){let{done:e}=tc();if(e.length===0)return!0;let t=e.map(e=>e.id),n=v.todos;if(v.todos=v.todos.filter(e=>!t.includes(e.id)),!await Qs(()=>d(t)).catch(e=>(r.error(`[Todo] clear completed failed:`,e),!1))){let e=new Set(v.todos.map(e=>e.id)),r=n.filter(n=>t.includes(n.id)&&!e.has(n.id));return v.todos=[...v.todos,...r],L(),!1}return L(),!0}async function mc(e,t=`merge`){if(t===`replace`)return hc(e);let n=ke(v.todos,e);if(n.addedItems.length===0)return{ok:!0,added:0,skipped:n.skipped};let i=v.todos;v.todos=n.todos;let a=new Set(n.addedItems.map(e=>e.id));return await Qs(()=>x(n.addedItems)).catch(e=>(r.error(`[Todo] import merge failed:`,e),!1))?(L(),{ok:!0,added:n.addedItems.length,skipped:n.skipped}):(v.todos=i.filter(e=>!a.has(e.id)),L(),{ok:!1,added:0,skipped:n.skipped})}async function hc(e){let{addedItems:t,skipped:n}=ke([],e);if(t.length===0)return{ok:!1,added:0,skipped:n,reason:`empty`};let i=v.todos,a=i.map(e=>e.id);return v.todos=t,await Qs(async()=>a.length>0&&!await d(a).catch(e=>(r.error(`[Todo] replace delete failed:`,e),!1))?!1:await x(t).catch(e=>(r.error(`[Todo] replace write failed:`,e),!1))?!0:(a.length>0&&await x(i).catch(()=>!1),!1)).catch(e=>(r.error(`[Todo] replace failed:`,e),!1))?(L(),{ok:!0,added:t.length,skipped:n}):(v.todos=i,L(),{ok:!1,added:0,skipped:n})}var gc=[`all`,`active`,`done`],_c={json:{ext:`json`,type:`application/json;charset=utf-8`},md:{ext:`md`,type:`text/markdown;charset=utf-8`}};function vc(e){return e===`md`?`md`:`json`}function yc(e){return String(e).padStart(2,`0`)}function bc(e){let t=new Date(e);return`${t.getFullYear()}-${yc(t.getMonth()+1)}-${yc(t.getDate())}`}function xc(e,t,n=Date.now()){let r=gc.includes(e)?e:`all`;return`ai-helper-todos${r===`all`?``:`-${r}`}-${bc(n)}.${_c[vc(t)].ext}`}function Sc(e,t={}){let n=gc.includes(t.scope)?t.scope:`all`,r=vc(t.format),i=t.now||Date.now(),a=r===`md`?Ce(e,{scope:n,now:i}):JSON.stringify(Ae(e,{scope:n,now:i}),null,2);return{filename:xc(n,r,i),blob:new Blob([a],{type:_c[r].type})}}function Cc(e,t={}){let{filename:n,blob:r}=Sc(e,t),i=URL.createObjectURL(r),a=document.createElement(`a`);return a.href=i,a.download=n,document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(i),n}function wc(){return new Promise(e=>{let t=document.createElement(`input`);t.type=`file`,t.accept=`.json,application/json`,t.style.display=`none`;let n=!1,r=r=>{n||(n=!0,t.remove(),e(r))};t.addEventListener(`change`,()=>r(t.files&&t.files[0]?t.files[0]:null)),t.addEventListener(`cancel`,()=>r(null)),document.body.appendChild(t),t.click()})}async function Tc(e){if(!e||typeof e.text!=`function`)return{ok:!1,reason:`json`};let t=``;try{t=await e.text()}catch{return{ok:!1,reason:`json`}}let n=null;try{n=JSON.parse(t)}catch{return{ok:!1,reason:`json`}}return be(n)}var Ec=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M18 6L6 18"/><path d="M6 6l12 12"/></svg>`,Dc=[`all`,`active`,`done`],Oc=[`json`,`md`],kc=[`merge`,`replace`];e(`zh`,{todoIo:{exportTitle:`导出待办`,importTitle:`导入待办`,close:`关闭`,rangeLabel:`范围`,formatLabel:`格式`,scopeAll:`全部`,scopeActive:`待办`,scopeDone:`已完成`,emptyRange:`这个范围里没有待办`,modeLabel:`方式`,modeMerge:`合并到现有`,modeMergeHint:`重复的条目自动跳过`,modeReplace:`替换全部`,modeReplaceHint:`删除当前 {n} 条,不可撤销`,importSummary:`文件里 {count} 条待办,当前清单 {existing} 条`,replaceWarn:`将删除当前全部待办,并写入文件里的 {count} 条。此操作不可撤销,确定继续吗?`,exportAction:`导出`,importAction:`导入`,cancel:`取消`}}),e(`en`,{todoIo:{exportTitle:`Export todos`,importTitle:`Import todos`,close:`Close`,rangeLabel:`Range`,formatLabel:`Format`,scopeAll:`All`,scopeActive:`To do`,scopeDone:`Done`,emptyRange:`No todos in this range`,modeLabel:`Mode`,modeMerge:`Merge into current`,modeMergeHint:`Duplicates are skipped`,modeReplace:`Replace all`,modeReplaceHint:`Deletes all {n} current todos, cannot be undone`,importSummary:`{count} todos in the file, {existing} in the list now`,replaceWarn:`All current todos will be deleted and {count} todos from the file written in. This cannot be undone. Continue?`,exportAction:`Export`,importAction:`Import`,cancel:`Cancel`}});function Ac(e){return`<div class="todo-io-header">
|
|
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=k(t.title||t.id);r+=`<option value="${k(t.id)}" ${n}>${i}</option>`}}catch{}n.innerHTML=r,u.classList.add(`open`)}function D(){u.classList.remove(`open`),_=null}async function pe(){let e=document.getElementById(`schedFormName`).value.trim(),n=document.getElementById(`schedFormPrompt`).value.trim(),r=m.value,i=h.value.trim();if(!e){A(t(`schedPanel.nameRequired`),`warning`);return}if(!n){A(t(`schedPanel.promptRequired`),`warning`);return}if(!i){A(t(`schedPanel.scheduleRequired`),`warning`);return}let a=r===`interval`&&parseInt(document.getElementById(`schedFormMaxRuns`).value,10)||null,o=r===`interval`?document.getElementById(`schedFormEndAt`).value:``,s=o?new Date(o).getTime():null,c={name:e,description:document.getElementById(`schedFormDesc`).value.trim(),prompt:n,schedule:r===`once`?{type:r,value:i,onceMode:g.value}:{type:r,value:i},contextUrl:document.getElementById(`schedFormUrl`).value.trim()||null,contextMode:document.getElementById(`schedFormContextMode`).value||`fetch`,sessionId:document.getElementById(`schedFormSession`).value||null,maxRuns:a,endAt:s,enabled:_?_.enabled:!0};try{let e=await 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">
|
|
233
232
|
<span class="todo-io-title">${k(e)}</span>
|
|
234
233
|
<button type="button" class="todo-io-close" data-io-action="cancel"
|
|
235
|
-
title="${j(t(`todoIo.close`))}" aria-label="${j(t(`todoIo.close`))}">${
|
|
236
|
-
</div>`}function
|
|
234
|
+
title="${j(t(`todoIo.close`))}" aria-label="${j(t(`todoIo.close`))}">${Oc}</button>
|
|
235
|
+
</div>`}function Nc(e,n){return`<div class="todo-io-actions">
|
|
237
236
|
<button type="button" class="todo-io-btn" data-io-action="cancel">${k(t(`todoIo.cancel`))}</button>
|
|
238
237
|
<button type="button" class="todo-io-btn primary" data-io-action="confirm"${n?` disabled`:``}>${k(e)}</button>
|
|
239
|
-
</div>`}function
|
|
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`:``}">
|
|
240
239
|
<input type="radio" name="todoIo-${j(e)}" value="${j(t)}"
|
|
241
240
|
data-io-field="${j(e)}"${i?` checked`:``} />
|
|
242
241
|
<span class="todo-io-option-main">
|
|
@@ -244,9 +243,9 @@ import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-DvmxOw8q.js"
|
|
|
244
243
|
${r?`<span class="todo-io-option-hint">${k(r)}</span>`:``}
|
|
245
244
|
</span>
|
|
246
245
|
${s}
|
|
247
|
-
</label>`}function
|
|
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"
|
|
248
247
|
aria-label="${j(t(`todoIo.exportTitle`))}">
|
|
249
|
-
${
|
|
248
|
+
${Mc(t(`todoIo.exportTitle`))}
|
|
250
249
|
<div class="todo-io-body">
|
|
251
250
|
<div class="todo-io-group">
|
|
252
251
|
<div class="todo-io-group-label">${k(t(`todoIo.rangeLabel`))}</div>
|
|
@@ -258,10 +257,10 @@ import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-DvmxOw8q.js"
|
|
|
258
257
|
</div>
|
|
259
258
|
<p class="todo-io-hint${a?` show`:``}" data-io-hint>${k(t(`todoIo.emptyRange`))}</p>
|
|
260
259
|
</div>
|
|
261
|
-
${
|
|
262
|
-
</div>`}function
|
|
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"
|
|
263
262
|
aria-label="${j(t(`todoIo.importTitle`))}">
|
|
264
|
-
${
|
|
263
|
+
${Mc(t(`todoIo.importTitle`))}
|
|
265
264
|
<div class="todo-io-body">
|
|
266
265
|
<p class="todo-io-summary">${k(t(`todoIo.importSummary`,{count:i,existing:a}))}</p>
|
|
267
266
|
<div class="todo-io-group">
|
|
@@ -270,14 +269,14 @@ import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-DvmxOw8q.js"
|
|
|
270
269
|
</div>
|
|
271
270
|
<p class="todo-io-warn${r===`replace`?` show`:``}" data-io-warn>${k(t(`todoIo.replaceWarn`,{count:i}))}</p>
|
|
272
271
|
</div>
|
|
273
|
-
${
|
|
274
|
-
</div>`}var
|
|
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}`:``}">
|
|
275
274
|
<span class="todo-stats-tile-value">${e}</span>
|
|
276
275
|
<span class="todo-stats-tile-label">${t}</span>
|
|
277
|
-
</div>`}function
|
|
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})}">
|
|
278
277
|
<span class="todo-stats-bar" style="height:${i}%"></span>
|
|
279
|
-
<span class="todo-stats-bar-label">${
|
|
280
|
-
</div>`}).join(``)}</div>`}function
|
|
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">
|
|
281
280
|
<div class="todo-stats-rate">
|
|
282
281
|
<span class="todo-stats-rate-value">${i}%</span>
|
|
283
282
|
<span class="todo-stats-rate-label">${t(`todoStats.rate`)}</span>
|
|
@@ -286,40 +285,40 @@ import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-DvmxOw8q.js"
|
|
|
286
285
|
<div class="todo-stats-track"><i style="width:${i}%"></i></div>
|
|
287
286
|
</div>
|
|
288
287
|
<div class="todo-stats-tiles">
|
|
289
|
-
${
|
|
290
|
-
${
|
|
291
|
-
${
|
|
292
|
-
${
|
|
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`:``)}
|
|
293
292
|
</div>
|
|
294
293
|
<div class="todo-stats-section">
|
|
295
294
|
<div class="todo-stats-section-title">${t(`todoStats.week`)}</div>
|
|
296
|
-
${
|
|
295
|
+
${el(o)}
|
|
297
296
|
</div>
|
|
298
297
|
<div class="todo-stats-facts">
|
|
299
298
|
<span>${t(`todoStats.todayAdded`,{n:a.added||0})}</span>
|
|
300
299
|
<span>${t(`todoStats.todayDone`,{n:a.done||0})}</span>
|
|
301
300
|
<span>${t(`todoStats.streak`,{n:n.streak||0})}</span>
|
|
302
301
|
<span>${t(`todoStats.highCount`,{n:n.high||0})}</span>
|
|
303
|
-
</div>`}var
|
|
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=`
|
|
304
303
|
<div class="todo-stats-card" role="dialog" aria-modal="true" aria-label="${j(t(`todoStats.title`))}">
|
|
305
304
|
<div class="todo-stats-header">
|
|
306
305
|
<span class="todo-stats-title">${t(`todoStats.title`)}</span>
|
|
307
306
|
<button type="button" class="todo-stats-close" data-action="close-stats"
|
|
308
|
-
title="${j(t(`todoStats.close`))}" aria-label="${j(t(`todoStats.close`))}">${
|
|
307
|
+
title="${j(t(`todoStats.close`))}" aria-label="${j(t(`todoStats.close`))}">${nl}</button>
|
|
309
308
|
</div>
|
|
310
|
-
<div class="todo-stats-body">${
|
|
311
|
-
</div>`}async function
|
|
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=`
|
|
312
311
|
<button class="todo-panel-toggle" id="todoPanelToggle" data-i18n-title="todo.toggleTitle" data-i18n-aria-label="todo.toggleTitle">
|
|
313
312
|
<span class="todo-badge" id="todoBadge" style="display:none;"></span>
|
|
314
|
-
${
|
|
313
|
+
${z.listCheck}
|
|
315
314
|
</button>
|
|
316
315
|
<div class="todo-panel" id="todoPanel">
|
|
317
316
|
<div class="todo-panel-header">
|
|
318
|
-
<span class="todo-panel-icon">${
|
|
317
|
+
<span class="todo-panel-icon">${z.listCheck}</span>
|
|
319
318
|
<span class="todo-panel-title" data-i18n="todo.title"></span>
|
|
320
319
|
<div class="todo-panel-actions">
|
|
321
|
-
<button class="todo-icon-btn" data-action="header-more" data-i18n-title="todo.headerMore" data-i18n-aria-label="todo.headerMore">${
|
|
322
|
-
<button class="todo-icon-btn" data-action="close" data-i18n-title="common.close" data-i18n-aria-label="common.close">${
|
|
320
|
+
<button class="todo-icon-btn" data-action="header-more" data-i18n-title="todo.headerMore" data-i18n-aria-label="todo.headerMore">${z.more}</button>
|
|
321
|
+
<button class="todo-icon-btn" data-action="close" data-i18n-title="common.close" data-i18n-aria-label="common.close">${z.close}</button>
|
|
323
322
|
</div>
|
|
324
323
|
</div>
|
|
325
324
|
<div class="todo-progress-row">
|
|
@@ -340,17 +339,17 @@ import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-DvmxOw8q.js"
|
|
|
340
339
|
</div>
|
|
341
340
|
<div class="todo-body" id="todoBody"></div>
|
|
342
341
|
</div>
|
|
343
|
-
`,
|
|
344
|
-
<span class="todo-undo-text">${k(t(`todo.undoBar`,{title:
|
|
345
|
-
<button class="todo-mini-btn" data-action="undo-complete" data-id="${j(
|
|
346
|
-
</div>`),
|
|
347
|
-
${
|
|
348
|
-
</button>`),o.length===0){let e=
|
|
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="${j(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">${k(t(`todo.undoBar`,{title:Al.title}))}</span>
|
|
344
|
+
<button class="todo-mini-btn" data-action="undo-complete" data-id="${j(Al.id)}">${k(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>${k(t(`todo.clearCompleted`))} (${i.length})</span>
|
|
347
|
+
</button>`),o.length===0){let e=wl===`done`;s.push(`<div class="todo-empty">
|
|
349
348
|
<div class="todo-empty-title">${k(t(e?`todo.emptyDone`:`todo.empty`))}</div>
|
|
350
349
|
<div class="todo-empty-hint">${k(t(e?`todo.emptyDoneHint`:`todo.emptyHint`))}</div>
|
|
351
|
-
</div>`)}else s.push(`<div class="todo-list" data-group="${
|
|
352
|
-
title="${j(n)}" aria-label="${j(n)}">${r}</button>`}function
|
|
353
|
-
title="${j(r)}" aria-label="${j(r)}">${
|
|
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="${j(e.id)}"
|
|
351
|
+
title="${j(n)}" aria-label="${j(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="${j(e.id)}"
|
|
352
|
+
title="${j(r)}" aria-label="${j(r)}">${z.link}<span>${k(n)}</span></button>`}function cu(e){let n=su(e);if(e.status===O.DONE)return`<div class="todo-meta">${n}<span>${k(Re(e))}</span></div>`;let r=[];if(n&&r.push(n),Number.isFinite(e.dueAt)){let n=De(e),i=n?t(`todoTime.overdueStamp`,{date:Te(e.dueAt)}):Te(e.dueAt);r.push(`<span class="todo-due${n?` overdue`:``}">${z.alert}${k(i)}</span>`)}let i=Ne(e.createdAt);return i&&r.push(`<span>${k(i)}</span>`),r.length===0?``:`<div class="todo-meta">${r.join(`<span class="todo-sep">·</span>`)}</div>`}function 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">
|
|
354
353
|
<textarea class="todo-note-input" data-id="${j(e.id)}" rows="2"
|
|
355
354
|
placeholder="${j(t(`todo.notePlaceholder`))}">${k(n===null?e.note||``:n)}</textarea>
|
|
356
355
|
<div class="todo-note-editor-actions">
|
|
@@ -358,52 +357,52 @@ import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-DvmxOw8q.js"
|
|
|
358
357
|
<button class="todo-mini-btn ghost" data-action="note-cancel" data-id="${j(e.id)}">${k(t(`todo.noteCancel`))}</button>
|
|
359
358
|
</div>
|
|
360
359
|
</div>`}return i?`<button class="todo-note-toggle${n?` open`:``}" data-action="toggle-note" data-id="${j(e.id)}">
|
|
361
|
-
${
|
|
360
|
+
${z.chevron}<span>${k(t(`todo.noteToggle`))}</span>
|
|
362
361
|
</button>
|
|
363
|
-
${n?`<div class="todo-note">${k(e.note)}</div>`:``}`:``}function
|
|
364
|
-
<input type="date" class="todo-due-input" data-id="${j(e.id)}" value="${j(c===null?
|
|
362
|
+
${n?`<div class="todo-note">${k(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="${j(e.id)}" value="${j(o===null?e.title:o)}" />`:`<div class="todo-name">${k(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="${j(e.id)}" value="${j(c===null?fu(e.dueAt):c)}" />
|
|
365
364
|
<button class="todo-mini-btn ghost" data-action="due-clear" data-id="${j(e.id)}">${k(t(`todo.clearDue`))}</button>
|
|
366
|
-
</div>`:``,u=
|
|
365
|
+
</div>`:``,u=Gl(e.id,`link`),d=W===e.id?`<div class="todo-link-editor">
|
|
367
366
|
<input type="text" class="todo-link-input" data-id="${j(e.id)}" autocomplete="off"
|
|
368
367
|
placeholder="${j(t(`todo.linkPlaceholder`))}" value="${j(u===null?e.link||``:u)}" />
|
|
369
368
|
<button class="todo-mini-btn ghost" data-action="link-cancel" data-id="${j(e.id)}">${k(t(`todo.noteCancel`))}</button>
|
|
370
|
-
</div>`:``,f=n===`active`?` draggable="true"`:``,p=
|
|
369
|
+
</div>`:``,f=n===`active`?` draggable="true"`:``,p=U===e.id||Tl===e.id||El===e.id||W===e.id,m=`
|
|
371
370
|
<div class="todo-item-actions">
|
|
372
|
-
${r?`<button class="todo-act" data-action="restore" data-id="${j(e.id)}" title="${j(t(`todo.restoreTo`,{status:
|
|
373
|
-
<button class="todo-act" data-action="edit-title" data-id="${j(e.id)}" title="${j(t(`todo.editItem`))}" aria-label="${j(t(`todo.editItem`))}">${
|
|
374
|
-
<button class="todo-act" data-action="copy-item" data-id="${j(e.id)}" title="${j(t(`todo.copyItem`))}" aria-label="${j(t(`todo.copyItem`))}">${
|
|
375
|
-
<button class="todo-act" data-action="fill-item" data-id="${j(e.id)}" title="${j(t(`todo.fillInput`))}" aria-label="${j(t(`todo.fillInput`))}">${
|
|
376
|
-
<button class="todo-act" data-action="row-more" data-id="${j(e.id)}" title="${j(t(`todo.more`))}" aria-label="${j(t(`todo.more`))}">${
|
|
371
|
+
${r?`<button class="todo-act" data-action="restore" data-id="${j(e.id)}" title="${j(t(`todo.restoreTo`,{status:au(He(e))}))}" aria-label="${j(t(`todo.restoreTo`,{status:au(He(e))}))}">${z.undo}</button>`:``}
|
|
372
|
+
<button class="todo-act" data-action="edit-title" data-id="${j(e.id)}" title="${j(t(`todo.editItem`))}" aria-label="${j(t(`todo.editItem`))}">${z.edit}</button>
|
|
373
|
+
<button class="todo-act" data-action="copy-item" data-id="${j(e.id)}" title="${j(t(`todo.copyItem`))}" aria-label="${j(t(`todo.copyItem`))}">${z.copy}</button>
|
|
374
|
+
<button class="todo-act" data-action="fill-item" data-id="${j(e.id)}" title="${j(t(`todo.fillInput`))}" aria-label="${j(t(`todo.fillInput`))}">${z.fill}</button>
|
|
375
|
+
<button class="todo-act" data-action="row-more" data-id="${j(e.id)}" title="${j(t(`todo.more`))}" aria-label="${j(t(`todo.more`))}">${z.more}</button>
|
|
377
376
|
</div>`;return`<div class="${a.join(` `)}" data-id="${j(e.id)}" data-group="${n}"${f} tabindex="0" data-priority="${j(e.priority||``)}">
|
|
378
|
-
${
|
|
377
|
+
${ou(e)}
|
|
379
378
|
<div class="todo-main">
|
|
380
379
|
${s}
|
|
381
|
-
${
|
|
380
|
+
${lu(e)}
|
|
382
381
|
${l}
|
|
383
382
|
${d}
|
|
384
|
-
${
|
|
383
|
+
${cu(e)}
|
|
385
384
|
</div>
|
|
386
385
|
${p?``:m}
|
|
387
|
-
</div>`}function
|
|
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="${j(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">${k(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">
|
|
388
387
|
<span class="todo-menu-row-label">${k(e.label)}</span>
|
|
389
388
|
${r.map(([r,i])=>`
|
|
390
389
|
<button type="button" class="todo-swatch${r?` ${r}`:``}${e.current===r?` active`:``}"
|
|
391
390
|
data-priority-value="${j(r)}" data-menu-id="${j(n)}"
|
|
392
391
|
title="${j(t(`todo.priorityTitle`,{level:i}))}"
|
|
393
392
|
aria-label="${j(i)}"></button>`).join(``)}
|
|
394
|
-
${
|
|
393
|
+
${Wu(e.shortcut)}
|
|
395
394
|
</div>`}return`${e.divider?`<div class="todo-menu-sep"></div>`:``}<button type="button" data-menu-action="${j(e.action)}" data-menu-id="${j(n||``)}"
|
|
396
395
|
class="todo-menu-item${e.danger?` danger`:``}">
|
|
397
|
-
${e.icon||``}<span>${k(e.label)}</span>${
|
|
398
|
-
</button>`}function Gu(e,t,n){let r=Vu();r.innerHTML=t.map((e,t)=>t===0&&e.divider?{...e,divider:!1}:e).map(e=>Wu(e,n)).join(``);let i=e.getBoundingClientRect(),a=r.offsetWidth||168,o=r.offsetHeight||132,s=Math.min(i.right-a,window.innerWidth-a-8);s=Math.max(8,s);let c=i.bottom+4;c+o>window.innerHeight-8&&(c=Math.max(8,i.top-o-4)),r.style.left=`${s}px`,r.style.top=`${c}px`}function Ku(e){if(e.status===O.DONE){let n=He(e),r=[{action:`restore`,label:t(`todo.restoreTo`,{status:iu(n)}),icon:B.undo,shortcut:`Alt+D`,divider:!0}];return n!==O.PENDING&&r.push({action:`set-pending`,label:t(`todo.backToPending`),icon:B.circle}),r}return e.status===O.DOING?[{action:`set-done`,label:t(`todo.markDone`),icon:B.check,shortcut:`Alt+D`,divider:!0},{action:`set-pending`,label:t(`todo.backToPending`),icon:B.circle}]:[{action:`set-doing`,label:t(`todo.startDoing`),icon:B.play,divider:!0},{action:`set-done`,label:t(`todo.markDone`),icon:B.check,shortcut:`Alt+D`}]}function qu(e,n){let r=mu(n);r&&Gu(e,[...Ku(r),{swatches:!0,label:t(`todo.priority`),current:r.priority||``,shortcut:`Alt+P`,divider:!0},{action:`edit-title`,label:t(`todo.editTitleAction`),icon:B.edit,divider:!0},{action:`edit-note`,label:r.note?t(`todo.editNote`):t(`todo.addNote`),icon:B.note,shortcut:`Alt+B`},{action:`set-due`,label:t(`todo.setDue`),icon:B.calendar},{action:`edit-link`,label:r.link?t(`todo.editLink`):t(`todo.addLink`),icon:B.link,shortcut:`Alt+L`},{action:`delete`,label:t(`todo.delete`),icon:B.trash,danger:!0,divider:!0}],n)}function Ju(e){let t=Yu();t.length!==0&&Gu(e,t,``)}function Yu(){return[{action:`stats`,label:t(`todo.statsEntry`),icon:B.chart,divider:!0},{action:`export-options`,label:t(`todo.exportEntry`),icon:B.download,divider:!0},{action:`import-options`,label:t(`todo.importEntry`),icon:B.upload}]}async function Xu(){let{active:e,done:t}=tc(),n=await Wc({counts:{all:e.length+t.length,active:e.length,done:t.length}});n&&Zu(n.scope,n.format)}function Zu(e,n){let{active:i,done:a}=tc(),o=[...i,...a];if(xe(o,e).length===0){A(t(`todo.exportEmptyToast`),`info`);return}try{A(t(`todo.exportedToast`,{name:Cc(o,{scope:e,format:n})}),`success`)}catch(e){r.error(`[Todo] export failed:`,e),A(t(`todo.exportFailedToast`),`error`)}}async function Qu(){let e=await wc();if(!e)return;let n=await Tc(e);if(!n.ok){A(t(n.reason===`json`?`todo.importJsonError`:`todo.importFormatError`),`error`);return}let{active:r,done:i}=tc(),a=await Gc({count:n.todos.length,existing:r.length+i.length});if(!a)return;Sl=`active`,K();let o=await mc(n.todos,a);if(!o.ok){A(t(o.reason===`empty`?`todo.importEmptyToast`:`todo.importFailedToast`),`error`);return}if(o.added===0){A(t(`todo.importNothingNewToast`,{skipped:o.skipped}),`info`);return}A(t(`todo.importedToast`,{added:o.added,skipped:o.skipped}),`success`)}async function $u(e,n){let r=mu(n);switch(e){case`set-doing`:q(oc(n,O.DOING));return;case`set-pending`:q(oc(n,O.PENDING));return;case`set-done`:gu(n);return;case`restore`:_u(n);return;case`edit-title`:Cl=n,K();return;case`edit-note`:wl=n,El.add(n),K(),setTimeout(()=>{let e=U.querySelector(`.todo-note-input[data-id="${n}"]`);e&&(e.focus(),e.selectionStart=e.selectionEnd=e.value.length)},30);return;case`set-due`:Tl=n,K(),setTimeout(()=>{let e=U.querySelector(`.todo-due-input[data-id="${n}"]`);e&&e.focus()},30);return;case`edit-link`:Au(n);return;case`stats`:ol();return;case`export-options`:Xu();return;case`import-options`:Qu();return;case`delete`:await Bu(t(`todo.deleteConfirmMsg`,{title:r?.title||``}),t(`todo.deleteConfirmTitle`))&&q(dc(n),t(`todo.deletedToast`));return;default:}}function ed(e,t={}){let{active:n,done:r}=tc(),i=[...n,...r].find(t=>t.id===e);return i?Le(i,t):``}function td(e){let n=ed(e);if(!n){A(t(`todo.emptyDigestToast`),`info`);return}let r=document.getElementById(`userInput`);if(!r){A(t(`todo.noInputToast`),`error`);return}let i=r.value.replace(/\s+$/,``);r.value=i?`${i}\n\n${n}`:n,r.dispatchEvent(new Event(`input`,{bubbles:!0})),r.focus(),r.selectionStart=r.selectionEnd=r.value.length,rt(),Vl(),A(t(`todo.filledToast`),`success`)}function nd(e){let n=ed(e,{plain:!0});if(!n){A(t(`todo.emptyDigestToast`),`info`);return}rd(n,t(`todo.copiedToast`))}function rd(e,n){try{navigator.clipboard.writeText(e).then(()=>{A(n,`success`)}).catch(e=>{r.warn(`[Todo] copy failed:`,e),A(t(`todo.copyFailed`),`error`)})}catch(e){r.warn(`[Todo] clipboard unavailable:`,e),A(t(`todo.copyFailed`),`error`)}}function id(e){let t=e.target.closest?.(`.todo-item[draggable="true"]`);if(!t)return;let n=t.closest(`.todo-list[data-group="active"]`);if(!n)return;let r=Array.from(n.querySelectorAll(`.todo-item`));Dl={id:t.dataset.id,from:r.indexOf(t),list:n},t.classList.add(`dragging`);let{active:i,done:a}=tc(),o=[...i,...a].find(e=>e.id===t.dataset.id);try{e.dataTransfer.effectAllowed=`copyMove`,e.dataTransfer.setData(`text/plain`,Le(o)||t.dataset.id)}catch{}}function ad(e){if(!Dl)return;e.preventDefault();let t=Dl.list;if(!t||!t.isConnected)return;let n=Array.from(t.querySelectorAll(`.todo-item`)).filter(e=>!e.classList.contains(`dragging`)),r=n.length;for(let t=0;t<n.length;t++){let i=n[t].getBoundingClientRect();if(e.clientY<i.top+i.height/2){r=t;break}}let i=od();r>=n.length?t.appendChild(i):n[r].before(i)}function od(){let e=U.querySelector(`.todo-insert`);return e||(e=document.createElement(`div`),e.className=`todo-insert`,e)}function sd(e){if(!Dl)return;e.preventDefault();let t=Dl.list,n=U.querySelector(`.todo-insert`),r=Dl.from;if(n&&t){let e=Array.from(t.querySelectorAll(`.todo-item`)).filter(e=>!e.classList.contains(`dragging`)),i=e.findIndex(e=>n.compareDocumentPosition(e)&Node.DOCUMENT_POSITION_FOLLOWING);r=i===-1?e.length:i}let i=Dl.from;cd(),i!==r&&q(fc(i,r))}function cd(){Dl=null,U?.querySelectorAll(`.todo-item.dragging`).forEach(e=>e.classList.remove(`dragging`)),U?.querySelector(`.todo-insert`)?.remove()}var ld=`—`,ud=[{labelKey:`versionInfo.website`,url:`https://xiweicheng.github.io/ai-helper/`,icon:`<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 17.93c-3.95-.49-7-3.85-7-7.93 0-.62.08-1.21.21-1.79L9 15v1c0 1.1.9 2 2 2v1.93zm6.9-2.54c-.26-.81-1-1.39-1.9-1.39h-1v-3c0-.55-.45-1-1-1H8v-2h2c.55 0 1-.45 1-1V7h2c1.1 0 2-.9 2-2v-.41c2.93 1.19 5 4.06 5 7.41 0 2.08-.8 3.97-2.1 5.39z"/></svg>`},{labelKey:`versionInfo.discussions`,url:`https://github.com/xiweicheng/ai-helper/discussions`,icon:`<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2z"/></svg>`},{labelKey:`versionInfo.reportIssue`,url:`https://github.com/xiweicheng/ai-helper/issues/new`,icon:`<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M20 8h-2.81c-.45-.78-1.07-1.45-1.82-1.96L17 4.41 15.59 3l-2.17 2.17C12.96 5.06 12.49 5 12 5c-.49 0-.96.06-1.41.17L8.41 3 7 4.41l1.62 1.63C7.88 6.55 7.26 7.22 6.81 8H4v2h2.09c-.05.33-.09.66-.09 1v1H4v2h2v1c0 .34.04.67.09 1H4v2h2.81c1.04 1.79 2.97 3 5.19 3s4.15-1.21 5.19-3H20v-2h-2.09c.05-.33.09-.66.09-1v-1h2v-2h-2v-1c0-.34-.04-.67-.09-1H20V8zm-6 8h-4v-2h4v2zm0-4h-4v-2h4v2z"/></svg>`},{labelKey:`versionInfo.githubRepo`,url:`https://github.com/xiweicheng/ai-helper`,icon:`<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M12 .5C5.73.5.5 5.73.5 12c0 5.08 3.29 9.39 7.86 10.91.58.11.79-.25.79-.56 0-.28-.01-1.02-.02-2-3.2.7-3.88-1.54-3.88-1.54-.52-1.33-1.28-1.69-1.28-1.69-1.04-.71.08-.7.08-.7 1.15.08 1.76 1.19 1.76 1.19 1.03 1.76 2.7 1.25 3.36.96.1-.75.4-1.25.72-1.54-2.55-.29-5.24-1.28-5.24-5.68 0-1.26.45-2.28 1.19-3.09-.12-.29-.52-1.46.11-3.05 0 0 .97-.31 3.18 1.18a11.1 11.1 0 012.9-.39c.98 0 1.97.13 2.9.39 2.2-1.49 3.17-1.18 3.17-1.18.63 1.59.23 2.76.11 3.05.74.81 1.19 1.83 1.19 3.09 0 4.41-2.69 5.38-5.25 5.67.41.35.78 1.05.78 2.12 0 1.53-.01 2.76-.01 3.14 0 .31.21.68.8.56A11.51 11.51 0 0023.5 12C23.5 5.73 18.27.5 12 .5z"/></svg>`},{labelKey:`versionInfo.giteeRepo`,url:`https://gitee.com/xiweicheng/ai-helper`,icon:`<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M11.984 0A12 12 0 000 12a12 12 0 0012 12 12 12 0 0012-12A12 12 0 0012 0zm6.09 5.333c.328 0 .593.266.592.593v1.482a.594.594 0 01-.593.592H9.777c-.982 0-1.778.796-1.778 1.778v5.63c0 .327.266.592.593.592h5.63c.982 0 1.778-.796 1.778-1.778v-.296a.593.593 0 00-.592-.593h-4.15a.592.592 0 01-.592-.592v-1.482a.593.593 0 01.593-.592h6.815c.327 0 .593.265.593.592v3.408a4 4 0 01-4 4H8.444a3.556 3.556 0 01-3.555-3.556V8.89a3.556 3.556 0 013.555-3.556h9.63z"/></svg>`}];function dd(e){let t=e=>typeof e==`string`?e.trim():``,n=e&&typeof e==`object`?e:{};return{version:t(n.version),tag:t(n.tag),commitId:t(n.commitId),publishedAt:t(n.publishedAt)}}function fd(e){if(!e)return ld;let t=Date.parse(e);return Number.isNaN(t)?ld:new Date(t).toLocaleString()}function pd(e){let n=dd(pt),r=[{label:t(`versionInfo.version`),value:n.version?`v${n.version}`:ld},{label:t(`versionInfo.tag`),value:n.tag||ld},{label:t(`versionInfo.commit`),value:n.commitId?n.commitId.slice(0,8):ld,title:n.commitId,mono:!0},{label:t(`versionInfo.publishedAt`),value:fd(n.publishedAt)}];e.textContent=``;for(let t of r){let n=document.createElement(`div`);n.className=`version-info-row`;let r=document.createElement(`div`);r.className=`version-info-label`,r.textContent=t.label;let i=document.createElement(`div`);i.className=t.mono?`version-info-value mono`:`version-info-value`,i.textContent=t.value,t.title&&(i.title=t.title),n.appendChild(r),n.appendChild(i),e.appendChild(n)}}function md(e){e.textContent=``;for(let n of ud){let r=document.createElement(`div`);r.className=`version-info-link`,r.title=n.url;let i=document.createElement(`span`);i.className=`version-info-link-icon`,i.innerHTML=n.icon;let a=document.createElement(`span`);a.className=`version-info-link-label`,a.textContent=t(n.labelKey);let o=document.createElement(`span`);o.className=`version-info-link-arrow`,o.textContent=`↗`,r.appendChild(i),r.appendChild(a),r.appendChild(o),r.addEventListener(`click`,()=>{chrome.tabs.create({url:n.url})}),e.appendChild(r)}}function hd(){let e=dd(pt);return[`AI Helper v${e.version||ld}`,`${t(`versionInfo.tag`)}: ${e.tag||ld}`,`${t(`versionInfo.commit`)}: ${e.commitId||ld}`,`${t(`versionInfo.publishedAt`)}: ${fd(e.publishedAt)}`].join(`
|
|
399
|
-
`)}function
|
|
396
|
+
${e.icon||``}<span>${k(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,rt(),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()})),ot(),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`
|
|
400
399
|
<div class="prompt-item ${t===0?`selected`:``}" data-index="${t}" data-path="${k(r)}" title="${k(r)}">
|
|
401
400
|
<span class="prompt-item-index">${t+1}</span>
|
|
402
401
|
<span class="prompt-item-icon">${n}</span>
|
|
403
402
|
<span class="prompt-item-content">${k(e.name)}</span>
|
|
404
403
|
<span class="file-at-path">${k(i)}</span>
|
|
405
404
|
</div>
|
|
406
|
-
`}).join(``),s){let e=document.createElement(`div`);e.className=`file-at-truncated`,e.textContent=t(`fileSelector.truncated`,{count:
|
|
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]),rt()}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="${k(e.code)}" title="${j(e.content||``)}">
|
|
407
406
|
<span class="input-add-panel-item-title"><span class="input-add-panel-item-inline-icon">${zn}</span>/${k(e.code)}</span>
|
|
408
407
|
<span class="input-add-panel-item-sub">${k(e.content||``)}</span>
|
|
409
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="${k(e.name)}" title="${j(r)}">
|
|
@@ -419,25 +418,25 @@ import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-DvmxOw8q.js"
|
|
|
419
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="${k(e.id)}" data-kb-name="${k(e.name||``)}" data-kb-disabled="${n?`1`:`0`}"${n?` title="${j(t(`knowledgeSelector.disabledTooltip`))}"`:``}>
|
|
420
419
|
<span class="input-add-panel-item-title">📚 ${k(e.name||``)}${n?` <span class="knowledge-item-badge badge-disabled">${t(`knowledgeSelector.disabledBadge`)}</span>`:``}</span>
|
|
421
420
|
<span class="input-add-panel-item-sub">${k(r)}</span>
|
|
422
|
-
</div>`}case`agents`:{let n
|
|
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="${k(e.id)}">
|
|
423
422
|
<span class="input-add-panel-item-title">${k([e.icon,n].filter(Boolean).join(` `))}</span>
|
|
424
423
|
<span class="input-add-panel-item-sub">${k(r||o)}</span>
|
|
425
424
|
${i?`<span class="input-add-panel-item-mark">✓</span>`:``}
|
|
426
|
-
</div>`}case`proxies`:{let n=e.name||t(`promptSelector.unnamedProxy`),r
|
|
427
|
-
<span class="input-add-panel-item-title"><span class="agent-at-dot agent-at-dot-${
|
|
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="${k(e.id)}">
|
|
426
|
+
<span class="input-add-panel-item-title"><span class="agent-at-dot agent-at-dot-${xi(e,i)}"></span>${k(n)}</span>
|
|
428
427
|
<span class="input-add-panel-item-sub">${k(e.url||``)}</span>
|
|
429
428
|
${e.isActive?`<span class="input-add-panel-item-mark">✓</span>`:``}
|
|
430
429
|
</div>`}case`workspace`:{let t=e.type===`directory`;return`<div class="prompt-item input-add-panel-item" data-path="${k(e.fullPath)}" title="${j(e.fullPath)}">
|
|
431
|
-
<span class="input-add-panel-item-icon">${
|
|
430
|
+
<span class="input-add-panel-item-icon">${sa(e.name,e.type)}</span>
|
|
432
431
|
<span class="input-add-panel-item-title">${k(e.name)}${t?`/`:``}</span>
|
|
433
|
-
${!t&&e.size!=null?`<span class="input-add-panel-item-sub">${k(
|
|
432
|
+
${!t&&e.size!=null?`<span class="input-add-panel-item-sub">${k(oa(e.size))}</span>`:``}
|
|
434
433
|
</div>`}case`screenshot`:return`<div class="prompt-item input-add-panel-item input-add-panel-item-two-line" data-shot-action="${e.action}">
|
|
435
434
|
<span class="input-add-panel-item-title">${e.icon} ${k(t(e.nameKey))}</span>
|
|
436
435
|
<span class="input-add-panel-item-sub">${k(t(e.descKey))}</span>
|
|
437
436
|
<kbd class="input-add-panel-item-kbd">${k(e.kbd)}</kbd>
|
|
438
|
-
</div>`;default:return``}}async function Tf(e,t){let n=e.ctrlKey||e.metaKey;switch(X){case`prompts`:{let e=t.dataset.code;n?Yr(e,{skipTriggerStrip:!0}):bt(e),of();break}case`skills`:Ji(t.dataset.skillName,rf,{clearTrigger:!1}),n&&of();break;case`mcp`:Li(t.dataset.serverId,t.dataset.serverName,rf,{clearTrigger:!1}),n&&of();break;case`pages`:{let e=rf.find(e=>String(e.id)===t.dataset.tabId);if(e){dn(e);let t=document.getElementById(`userInput`);t&&t.focus(),rt()}of();break}case`knowledge`:An({id:t.dataset.kbId,name:t.dataset.kbName,enabled:t.dataset.kbDisabled!==`1`},{clearTrigger:!1}),n&&of();break;case`agents`:await cr(t.dataset.agentId,{clearTrigger:!1}),of();break;case`proxies`:await yt(t.dataset.proxyId,{clearTrigger:!1}),of();break;case`workspace`:{let e=rf.find(e=>e.fullPath===t.dataset.path);if(e){let t=document.getElementById(`userInput`);t&&t.focus(),await Si([e]),rt()}of();break}case`screenshot`:of(),await(t.dataset.shotAction===`region`?Pi:ei)();break;default:break}}var Ef=0,Df=200,Of=150,kf={promptTriggerBtn:`prompts`,addMenuSkillBtn:`skills`,addMenuMcpBtn:`mcp`,addMenuPageBtn:`pages`,addMenuKnowledgeBtn:`knowledge`,addMenuAgentBtn:`agents`,addMenuProxyBtn:`proxies`,addMenuWorkspaceBtn:`workspace`,screenshotBtn:`screenshot`};async function Af(){let e=[{id:`addMenuSkillBtn`,available:()=>Gi()},{id:`addMenuMcpBtn`,available:()=>_r()},{id:`addMenuKnowledgeBtn`,available:async()=>(await Yn()).ok},{id:`addMenuProxyBtn`,available:async()=>(await Kt()).length>0},{id:`addMenuWorkspaceBtn`,available:async()=>!!await sa()}],t=++Ef;await Promise.all(e.map(async({id:e,available:n})=>{let r=document.getElementById(e);if(!r)return;let i=!0;try{i=await n()}catch{i=!0}t===Ef&&(r.style.display=i?``:`none`)}))}function jf(){let e=document.getElementById(`inputAddBtn`),t=document.getElementById(`inputAddMenu`);if(!e||!t)return;let n=e.closest(`.input-add-wrapper`),r=t.querySelector(`.input-add-nav`),i=null,a=null,o=!1,s=()=>{let e=hf()?gf():null;t.querySelectorAll(`.input-add-item`).forEach(t=>{t.classList.toggle(`panel-active`,!!e&&kf[t.id]===e)})},c=e=>{let n=document.getElementById(`inputAddPanel`);if(!n||n.style.display===`none`)return;n.style.left=``;let r=t.getBoundingClientRect(),i=n.getBoundingClientRect(),a=r.right+8;a+i.width>window.innerWidth-8&&(a=window.innerWidth-8-i.width),a<8&&(a=8),n.style.left=`${Math.round(a-r.left)}px`;let o=e||t.querySelector(`.input-add-item.panel-active`),s=(o?o.getBoundingClientRect():r).top;s+i.height>r.bottom&&(s=r.bottom-i.height),s<8&&(s=8),n.style.top=`${Math.round(s-r.top-t.clientTop)}px`},l=n=>{t.style.display=n?``:`none`,e.classList.toggle(`open`,n),e.setAttribute(`aria-expanded`,String(n)),n?(yf(),s(),Af()):(i&&=(clearTimeout(i),null),a&&=(clearTimeout(a),null),yf(),s())},u=()=>t.style.display!==`none`;pf({onRequestClose:()=>l(!1)}),e.addEventListener(`click`,e=>{e.stopPropagation();let t=!u();t&&(Mt(),bi(),qd()),l(t)}),t.addEventListener(`click`,e=>{e.target.closest&&e.target.closest(`.input-add-item`)&&l(!1)},!0),document.addEventListener(`click`,e=>{u()&&(n&&n.contains(e.target)||l(!1))});let d=()=>{i&&=(clearTimeout(i),null),a&&clearTimeout(a),a=setTimeout(()=>{a=null,!_f()&&(yf(),s())},Of)};r&&r.addEventListener(`mouseover`,e=>{if(!u())return;let t=e.target.closest(`.input-add-item`),n=t?kf[t.id]:null;if(!n){d();return}a&&=(clearTimeout(a),null),!(hf()&&gf()===n)&&(i&&clearTimeout(i),i=setTimeout(async()=>{i=null;let e=vf(n);c(t);try{await e}catch{}c(t),s()},Df))}),t.addEventListener(`mouseenter`,()=>{o=!0,a&&=(clearTimeout(a),null)}),t.addEventListener(`mouseleave`,()=>{o=!1,d()});let f=document.getElementById(`inputAddPanelSearch`);f&&f.addEventListener(`blur`,()=>{o||d()}),window.addEventListener(`resize`,()=>{hf()&&c()}),[{id:`promptTriggerBtn`,open:()=>fn(``,`prompts`)},{id:`addMenuSkillBtn`,open:()=>fn(``,`skills`)},{id:`addMenuMcpBtn`,open:()=>fn(``,`mcp`)},{id:`addMenuPageBtn`,open:()=>Or(``,`pages`)},{id:`addMenuKnowledgeBtn`,open:()=>Or(``,`knowledge`)},{id:`addMenuAgentBtn`,open:()=>Or(``,`agents`)},{id:`addMenuProxyBtn`,open:()=>Or(``,`proxies`)},{id:`addMenuWorkspaceBtn`,open:()=>Kd(``)}].forEach(({id:e,open:t})=>{let n=document.getElementById(e);n&&n.addEventListener(`click`,async e=>{e.stopPropagation(),n.blur(),Mt(),bi(),qd();try{await t()}catch{}let r=document.getElementById(`userInput`);r&&r.focus()})});let p=document.getElementById(`inputAddMenuSwitches`),m=()=>{let t=p?.querySelector(`input[type="checkbox"]`);e.classList.toggle(`has-active-switch`,!!(t&&t.checked))};p&&(typeof MutationObserver<`u`&&new MutationObserver(m).observe(p,{subtree:!0,childList:!0}),p.addEventListener(`change`,m)),m()}var Mf=`usageTipsEnabled`,Nf=8e3;e(`zh`,{usageTips:{dismiss:`不再显示`,dismissedHint:`已关闭使用技巧提示。想重新看到:设置 → 基础 → 打开「使用技巧提示」`}}),e(`en`,{usageTips:{dismiss:`Don't show again`,dismissedHint:`Tips hidden. To bring them back: Settings → Basic → enable "Usage tips".`}});var Pf=[{id:`slash`,scene:`plugin`,zh:`输入「/」唤起快捷提示,用方向键选择提示词、技能或 MCP,回车直接套用。`,en:`Type "/" to open quick prompts, pick a prompt, skill, or MCP with arrow keys and press Enter.`},{id:`at-page`,scene:`plugin`,zh:`输入「@」可引用当前网页,让 AI 直接基于页面内容回答。`,en:`Type "@" to reference the current page so the AI answers from that content.`},{id:`at-agent`,scene:`plugin`,zh:`「@助手」可以切换不同角色,为不同任务准备不同的身份、提示词与工具。`,en:`"@Assistant" switches roles, giving each task its own persona, prompt, and tool set.`},{id:`history`,scene:`plugin`,zh:`在输入框按「↑ / ↓」翻看历史输入,按 Esc 一键清空当前内容。`,en:`Press ↑ / ↓ in the input box to browse input history, and Esc to clear the current content.`},{id:`goal`,scene:`plugin`,zh:`把目标写成「帮我完成…」,目标模式会自动拆解步骤并持续推进直到达成。`,en:`Write the goal as "Help me finish…" and Goal mode will break it into steps and keep pushing until done.`},{id:`queue`,scene:`plugin`,zh:`任务执行中仍可继续输入,消息会进入队列,不会打断当前任务。`,en:`You can keep typing while a task runs; new messages queue up without interrupting the current task.`},{id:`queue-carry`,scene:`plugin`,zh:`排队时点消息旁的「⚡」,可把队首消息顺带进当前任务,减少来回切换。`,en:`Click "⚡" beside a queued message to fold it into the running task and avoid context switching.`},{id:`prompt-clarify`,scene:`plugin`,zh:`提问时补上背景、目标与限制条件,比只给一句话得到的结果稳定得多。`,en:`Include background, goal, and constraints in your request; results are far more reliable than one-liners.`},{id:`prompt-plan`,scene:`plugin`,zh:`复杂任务先让 AI 列计划:「先给方案,我确认后再动手」,能少走很多弯路。`,en:`For complex work, ask for a plan first: "Propose a plan, then act after I confirm."`},{id:`prompt-split`,scene:`plugin`,zh:`一次只让 AI 做一件事,把大任务拆成小步,成功率更高也更好检查。`,en:`Give the AI one job at a time; splitting big tasks into steps improves success and reviewability.`},{id:`selection`,scene:`plugin`,zh:`在网页上划词后点浮动按钮,可以针对选中的内容单独提问。`,en:`Select text on a page and click the floating button to ask about just that selection.`},{id:`voice`,scene:`plugin`,zh:`点麦克风用语音输入,说完自动转成文字,长问题不必手打。`,en:`Use the mic for voice input: speech is transcribed automatically, so long questions need no typing.`},{id:`image`,scene:`plugin`,zh:`图片可以直接粘贴或拖进输入框,AI 会看图后再回答。`,en:`Paste or drag images into the input box; the AI will look at them before answering.`},{id:`file`,scene:`plugin`,zh:`支持上传 PDF、Word、Excel 等文件,AI 会先提取内容再作答。`,en:`Upload PDF, Word, or Excel files; the AI extracts their content first, then answers.`},{id:`knowledge`,scene:`plugin`,zh:`用「@知识库」引用私有资料,回答会更贴合你的业务与术语。`,en:`Reference private material with "@Knowledge base" to make answers fit your business and terminology.`},{id:`compaction`,scene:`plugin`,zh:`长对话可在基础配置开启自动压缩,上下文接近上限时自动摘要,省 token。`,en:`Enable auto-compaction in Basic settings: near the context limit, long chats are summarized to save tokens.`},{id:`session`,scene:`plugin`,zh:`重要对话可收藏、搜索和导出;也可直接说「搜一下我们以前聊过的 xxx」。`,en:`Bookmark, search, and export important chats; you can also say "Search our past chats for xxx".`},{id:`todo`,scene:`plugin`,zh:`说「帮我加个待办:周五前交方案」,AI 会直接写入待办面板,也能查询、改优先级或标记完成。`,en:`Say "Add a todo: send the proposal by Friday" and the AI writes it into the To-do panel; it can also list, reprioritize, or complete items.`},{id:`todo-remind`,scene:`plugin`,zh:`「待办」本身不会提醒;说「到时间提醒我看这条待办」,AI 会顺手补建一个定时任务。`,en:`Todos do not remind you by themselves; say "Remind me about this todo at that time" and the AI adds a scheduled task.`},{id:`schedule`,scene:`plugin`,zh:`定时任务可直接用对话管理:说「每周一 9 点整理上周数据」,AI 会创建并按点执行,结果写回会话。`,en:`Manage scheduled tasks by chat: say "Every Monday 9am summarize last week" and the AI creates it, runs on time, and posts the result here.`},{id:`schedule-manage`,scene:`plugin`,zh:`说「列出 / 暂停 / 立即执行我的定时任务」,AI 会直接查询并处理,删除前仍会先确认。`,en:`Say "List / pause / run my scheduled tasks now" and the AI queries and handles them, asking before any deletion.`},{id:`tabs`,scene:`plugin`,zh:`说「打开这三个链接,把重复的标签页关掉」,AI 能打开、切换、关闭和刷新标签页。`,en:`Say "Open these three links and close duplicate tabs" and the AI can open, switch, close, and refresh tabs.`},{id:`bookmarks`,scene:`plugin`,zh:`说「找一下我收藏过的 xx」,AI 会检索浏览器书签与历史记录,直接给出链接。`,en:`Say "Find the xx I bookmarked" and the AI searches bookmarks and history, returning the links.`},{id:`extract-data`,scene:`plugin`,zh:`说「把这页的表格整理成 CSV」,AI 会抽取页面上的结构化数据,方便继续加工。`,en:`Say "Turn this page's table into CSV" and the AI extracts structured page data for further use.`},{id:`download`,scene:`plugin`,zh:`说「把这些图片批量下载下来」,AI 会把文件直接保存到本机。`,en:`Say "Download these images" and the AI saves the files to your computer.`},{id:`memory`,scene:`plugin`,zh:`说「帮我记一下…」即存入记忆,需要时问「你还记得…吗」,跨会话都有效。`,en:`Say "Remember this…" to save it; ask "Do you remember…?" later — memory persists across sessions.`},{id:`custom-prompt`,scene:`plugin`,zh:`把常用指令存成自定义提示词,下次用「/」一键调用。`,en:`Save frequent instructions as custom prompts and recall them with "/" next time.`},{id:`kb-ingest`,scene:`plugin`,zh:`说「把这份资料存到知识库」,AI 会自动切分并入库,之后可直接检索。`,en:`Say "Save this into the knowledge base" and the AI chunks and ingests it for later retrieval.`},{id:`clipboard`,scene:`plugin`,zh:`说「把结果复制到剪贴板」,AI 会直接写入,省去手动选中复制。`,en:`Say "Copy the result to my clipboard" and the AI writes it for you.`},{id:`page-highlight`,scene:`plugin`,zh:`说「在页面上高亮 xxx」,AI 会把关键内容标出来,方便讲解或核对。`,en:`Say "Highlight xxx on the page" to mark key content for explanation or review.`},{id:`capture`,scene:`plugin`,zh:`说「截图并分析这个页面」,AI 会截图后交给视觉模型解读图表或界面。`,en:`Say "Screenshot and analyze this page" to have the vision model read charts or UI.`},{id:`preview-ui`,scene:`plugin`,zh:`说「做个界面原型给我看看」,AI 会在侧边栏直接渲染可预览的 HTML。`,en:`Say "Show me a UI prototype" and the AI renders previewable HTML in the side panel.`},{id:`form-fill`,scene:`plugin`,zh:`说「帮我填一下这个表单」,AI 能一次批量填入多个字段。`,en:`Say "Fill out this form" and the AI can fill multiple fields in one go.`},{id:`browser-act`,scene:`plugin`,zh:`说「打开这个链接并帮我点…」,AI 能自动开标签页、点击、输入和翻页。`,en:`Say "Open this link and click …" and the AI can open tabs, click, type, and scroll.`},{id:`clarify`,scene:`plugin`,zh:`加上「拿不准就先问我」,AI 会先给出选项确认,避免理解跑偏。`,en:`Add "Ask me first if unsure" and the AI confirms with options before proceeding.`},{id:`dispatch`,scene:`plugin`,zh:`说「这几件事并行处理」,AI 会拆给子代理并发执行,大任务更快。`,en:`Say "Handle these in parallel" and the AI dispatches sub-agents concurrently.`},{id:`qrcode`,scene:`plugin`,zh:`说「把这个链接生成二维码」,AI 会自动生成并展示出来。`,en:`Say "Turn this link into a QR code" and the AI generates and shows it.`},{id:`notify`,scene:`plugin`,zh:`说「做完后提醒我」,AI 会用桌面通知告知结果,不必一直盯着。`,en:`Say "Notify me when done" and the AI sends a desktop notification.`},{id:`fetch`,scene:`plugin`,zh:`说「帮我抓取这个接口的数据」,AI 可发起 HTTP 请求并整理返回结果。`,en:`Say "Fetch the data from this API" and the AI can send an HTTP request and organize the result.`},{id:`agent-hint`,scene:`plugin`,zh:`连接代理端后,可解锁本机文件读写、命令执行等能力(设置 → 代理页配对)。`,en:`Connecting the agent unlocks local file access and command execution (Settings → Agent to pair).`},{id:`agent-file`,scene:`agent`,zh:`已连接代理端:AI 可以读写你电脑上的文件,直接说「帮我改这个文件」即可。`,en:`Agent connected: the AI can read and write files on your computer — just say "update this file".`},{id:`agent-exec`,scene:`agent`,zh:`已连接代理端:AI 可以执行本机命令、运行脚本,适合构建、测试与批处理。`,en:`Agent connected: the AI can run local commands and scripts for builds, tests, and batch jobs.`},{id:`agent-search`,scene:`agent`,zh:`让 AI「在项目里搜索 xxx」,它会用本机搜索定位代码,比网页检索更准。`,en:`Ask the AI to "search the project for xxx"; local search finds code more accurately than the web.`},{id:`agent-workdir`,scene:`agent`,zh:`在工作目录面板切换目录,AI 的文件操作都会被限制在这个范围内。`,en:`Switch directories in the workspace panel; the AI confinement keeps file operations inside that scope.`},{id:`agent-confirm`,scene:`agent`,zh:`敏感操作会先弹确认,可在基础配置里调整确认策略,兼顾安全与效率。`,en:`Sensitive actions ask for confirmation first; adjust the policy in Basic settings to balance safety and speed.`},{id:`agent-log`,scene:`agent`,zh:`命令执行日志可在日志面板查看;也可说「调出执行日志复盘」,让 AI 提取成功路径与失败教训。`,en:`Review commands in the log panel, or say "Review the execution log" to extract successful paths and lessons.`},{id:`agent-stream`,scene:`agent`,zh:`长命令支持流式输出,执行过程实时可见,不用盯着空白等待。`,en:`Long commands stream their output, so progress is visible in real time instead of a blank wait.`},{id:`agent-multi`,scene:`agent`,zh:`配对了多台电脑时,用「@代理」指定目标,也可以说「切换到另一台电脑的代理」。`,en:`With multiple computers, use "@Agent" to pick one, or just say "Switch to the agent on another computer".`},{id:`agent-offline`,scene:`agent`,zh:`代理端离线时,文件与命令类能力会自动隐藏,避免误发无法执行的任务。`,en:`When the agent is offline, file and command abilities are hidden so tasks are not sent in vain.`},{id:`agent-update`,scene:`agent`,zh:`代理端可在设置 → 代理页一键更新或重启,版本不一致时优先升级。`,en:`Update or restart the agent from Settings → Agent; upgrade first when versions differ.`},{id:`agent-skill`,scene:`agent`,zh:`说「跑一下这个工作流技能」,代理端会执行对应的 Skill。`,en:`Say "Run this workflow skill" and the agent executes the matching Skill.`},{id:`agent-skill-create`,scene:`agent`,zh:`说「把刚才的流程沉淀成技能」,AI 会写成 SKILL.md,下次一句话即可复用。`,en:`Say "Turn that process into a skill" and the AI writes a SKILL.md for one-line reuse next time.`},{id:`agent-trash`,scene:`agent`,zh:`说「从回收站恢复刚删的文件」,代理端可以直接恢复。`,en:`Say "Restore the file I just deleted" and the agent can recover it from its trash.`},{id:`agent-download`,scene:`agent`,zh:`说「把这个文件下载到浏览器」,代理端文件会直接下载到本机。`,en:`Say "Download this file to the browser" and the agent transfers it locally.`}],Z=null,Ff=null,If=null,Lf=null,Rf=null,zf=!1,Bf=null,Vf=!0,Hf=null;function Uf(){return v.agentPlatform?.connected===!0}function Wf(){let e=a();return Pf.filter(e=>e.scene!==`agent`||Uf()).map(t=>({id:t.id,text:e===`en`?t.en:t.zh}))}function Gf(e){let t=e.findIndex(e=>e.id===Bf);return t>=0?t:0}function Kf(){if(!Z||!Ff)return;let e=Ff.scrollWidth>Ff.clientWidth+1;Z.classList.toggle(`is-truncated`,e)}function qf(e,t){if(!Ff||!e.length)return;let n=e[t%e.length];Bf=n.id,Ff.textContent=n.text,If&&(If.textContent=n.text),Kf(),Ff.classList.remove(`fade-in`),Ff.offsetWidth,Ff.classList.add(`fade-in`)}function Jf(){if(!Vf||!Z||Z.style.display===`none`)return;let e=Wf();e.length&&qf(e,Gf(e)+1)}function Yf(){Rf&&=(clearInterval(Rf),null)}function Xf(){Yf(),!(!Vf||zf)&&(Rf=setInterval(Jf,Nf))}function Zf(){if(!Vf||!Z)return;let e=Wf();if(!e.length){$f();return}e.some(e=>e.id===Bf)?qf(e,Gf(e)):(Bf=null,qf(e,0))}function Qf(){if(!Z)return;Vf=!0,Z.style.display=``;let e=Wf();if(!e.length){$f();return}qf(e,Gf(e)),Xf()}function $f(){Z&&(Z.style.display=`none`,Yf())}function ep(){Z.addEventListener(`mouseenter`,()=>{zf=!0,Yf()}),Z.addEventListener(`mouseleave`,()=>{zf=!1,Xf()}),Lf.addEventListener(`click`,e=>{e.stopPropagation(),tp(),A(t(`usageTips.dismissedHint`),`info`,5e3)}),chrome.storage.onChanged.addListener((e,t)=>{t!==`local`||!e[Mf]||(e[Mf].newValue===!1?(Vf=!1,$f()):Qf())}),document.addEventListener(`agent-connection-changed`,Zf),o(Zf),typeof ResizeObserver<`u`&&new ResizeObserver(Kf).observe(Z)}function tp(){Vf=!1,$f();try{chrome.storage.local.set({[Mf]:!1})}catch{}}function np(){if(Z=document.getElementById(`usageTipsBar`),Ff=document.getElementById(`usageTipsText`),If=document.getElementById(`usageTipsTooltip`),Lf=document.getElementById(`usageTipsDismiss`),!(!Z||!Ff||!If||!Lf)){ep(),Hf=document.getElementById(`chatContainer`),Hf&&(Hf.appendChild(Z),typeof MutationObserver<`u`&&new MutationObserver(()=>{Hf.querySelectorAll(`.usage-tips-bar`).forEach(e=>{e!==Z&&e.remove()}),(Z.parentNode!==Hf||Z.nextElementSibling)&&Hf.appendChild(Z)}).observe(Hf,{childList:!0}));try{chrome.storage.local.get([Mf],e=>{Vf=e?.[Mf]!==!1,Vf?Qf():$f()})}catch{Qf()}}}function rp({key:e,value:t=``,caret:n,history:r=[],index:i=-1}={}){if(e!==`ArrowUp`&&e!==`ArrowDown`||!Array.isArray(r)||r.length===0)return{handled:!1};let a=String(t??``),o=Number.isInteger(n)&&n>=0?n:a.length,s=Number.isInteger(i)&&i>=0;if(e===`ArrowUp`){let e=a.lastIndexOf(`
|
|
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(),rt()}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]),rt()}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(`
|
|
439
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(`
|
|
440
|
-
`,o)!==-1)return{handled:!1};let c=Math.min(i,r.length-1);if(c<r.length-1){let e=c+1;return{handled:!0,index:e,value:r[e]}}return{handled:!0,index:-1,value:``}}function
|
|
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="${k(n&&(n.fileNames||[]).length?n.fileNames.join(`、`):i)}">${k(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="${k(t(`queue.statusRunningHint`))}"`:``}>${k(a)}</span>`:``)+r,s=v.isGenerating===!0;return`
|
|
441
440
|
<div class="queue-chip" draggable="true" data-id="${k(e.id)}" data-status="${k(e.status)}">
|
|
442
441
|
<span class="queue-chip-index">${n+1}</span>
|
|
443
442
|
<div class="queue-chip-main">
|
|
@@ -449,16 +448,16 @@ import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-DvmxOw8q.js"
|
|
|
449
448
|
<button class="queue-chip-btn" type="button" data-act="edit" title="${k(t(`queue.editBack`))}">✎</button>
|
|
450
449
|
<button class="queue-chip-btn danger" type="button" data-act="remove" title="${k(t(`queue.delete`))}">✕</button>
|
|
451
450
|
</div>
|
|
452
|
-
</div>`}function
|
|
451
|
+
</div>`}function wp(e){return e.length?e.map(e=>`
|
|
453
452
|
<div class="queue-recent-item" data-id="${k(e.id)}">
|
|
454
|
-
<span class="queue-recent-status">${k(
|
|
453
|
+
<span class="queue-recent-status">${k(bp(e))}</span>
|
|
455
454
|
<span class="queue-recent-text" title="${k(e.text)}">${k(e.text)}</span>
|
|
456
455
|
<button class="queue-chip-btn" type="button" data-act="requeue" title="${k(t(`queue.requeue`))}">↺</button>
|
|
457
456
|
<button class="queue-chip-btn danger" type="button" data-act="forget" title="${k(t(`queue.forgetRecent`))}">✕</button>
|
|
458
|
-
</div>`).join(``):`<div class="queue-recent-empty">${k(t(`queue.recentEmpty`))}</div>`}function
|
|
457
|
+
</div>`).join(``):`<div class="queue-recent-empty">${k(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,`
|
|
459
458
|
`).replace(/\n{3,}/g,`
|
|
460
459
|
|
|
461
|
-
`).trim()}function
|
|
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=`
|
|
462
461
|
<div class="sap-header">
|
|
463
462
|
<span class="sap-title"></span>
|
|
464
463
|
<div class="sap-header-actions">
|
|
@@ -472,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"
|
|
|
472
471
|
<button class="sap-btn sap-transfer"></button>
|
|
473
472
|
<button class="sap-btn sap-regen"></button>
|
|
474
473
|
</div>
|
|
475
|
-
`,document.body.appendChild(Q),Q.querySelector(`.sap-close`).addEventListener(`click`,sm),Q.querySelector(`.sap-lock`).addEventListener(`click`,tm),Q.querySelector(`.sap-copy`).addEventListener(`click`,dm),Q.querySelector(`.sap-transfer`).addEventListener(`click`,fm),Q.querySelector(`.sap-regen`).addEventListener(`click`,()=>{Up&&Wp&&mm()}),um(Q.querySelector(`.sap-header`)),Q)}function $p(){if(!Q)return;Q.querySelector(`.sap-close`).title=t(`sidePanel.popupClose`);let e=Q.querySelector(`.sap-copy`);e.textContent=t(`sidePanel.popupCopy`),e.title=t(`sidePanel.popupCopy`);let n=Q.querySelector(`.sap-transfer`);n.textContent=t(`sidePanel.popupTransfer`),n.title=t(`sidePanel.popupTransfer`);let r=Q.querySelector(`.sap-regen`);r.textContent=t(`sidePanel.popupRegenerate`),r.title=t(`sidePanel.popupRegenerate`),em()}function em(){if(!Q)return;let e=Q.querySelector(`.sap-lock`);e&&(e.classList.toggle(`locked`,Jp),e.title=t(Jp?`sidePanel.popupUnlock`:`sidePanel.popupLock`),e.innerHTML=Jp?`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>`:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 9.9-1"/></svg>`)}function tm(){Jp=!Jp,em()}function nm(e,t){let n=Qp(),r=window.innerWidth,i=window.innerHeight,a=t+12,o=e-320/2;o<8&&(o=8),o+320>r-8&&(o=r-320-8),a+280>i-8&&(a=t-280-12),a<8&&(a=8),n.style.position=`fixed`,n.style.top=a+`px`,n.style.left=o+`px`}function rm(e){let n=Qp();$p(),n.querySelector(`.sap-title`).textContent=e||t(`sidePanel.popupTitle`),n.querySelector(`.sap-body`).innerHTML=`<div class="sap-loading">${k(t(`sidePanel.popupLoading`))}</div>`,n.classList.add(`show`),Q.style.display=`block`}function im(){return!!Q&&Q.classList.contains(`show`)}function am(e,t=!0){let n=Q?.querySelector(`.sap-body`);n&&(n.innerHTML=`<div class="sap-content markdown-body">${e}</div>`,t&&(n.scrollTop=n.scrollHeight))}function om(e){let t=Q?.querySelector(`.sap-body`);t&&(t.innerHTML=`<div class="sap-error">${k(e)}</div>`)}function sm(){qp&&Vp&&chrome.runtime.sendMessage({type:`CANCEL_REACT`,sessionId:Vp}).catch(()=>{}),Q&&(Q.classList.remove(`show`),Q.style.display=`none`),Vp=null,Hp=``,qp=!1,Jp=!1}function cm(e){if(!im()||Jp||Q.contains(e.target))return;let t=document.getElementById(`selectionFloatingMenu`);t&&t.contains(e.target)||sm()}function lm(e){e.key===`Escape`&&(!im()||Jp||sm())}function um(e){let t=!1,n,r,i,a;e.addEventListener(`mousedown`,e=>{if(e.target.closest(`.sap-close, .sap-lock`))return;t=!0,n=e.clientX,r=e.clientY;let o=Q.getBoundingClientRect();i=o.top,a=o.left,e.preventDefault()}),document.addEventListener(`mousemove`,e=>{if(!t)return;let o=e.clientX-n,s=e.clientY-r;Q.style.position=`fixed`,Q.style.top=i+s+`px`,Q.style.left=a+o+`px`}),document.addEventListener(`mouseup`,()=>{t=!1})}function dm(){Hp&&navigator.clipboard.writeText(Hp).then(()=>{A(t(`sidePanel.popupCopied`))}).catch(()=>{let e=document.createElement(`textarea`);e.value=Hp,document.body.appendChild(e),e.select(),document.execCommand(`copy`),document.body.removeChild(e),A(t(`sidePanel.popupCopied`))})}function fm(){if(!Hp||!Up)return;yn()&&Ct();let e=Hp,n=Up.content,r=`${Gp?`[${t(`sidePanel.popupContextLabel`)}]\n${Gp}\n\n`:``}[${t(`sidePanel.selectedContentLabel`)}]\n${Wp}\n\n[${t(`sidePanel.userQuestionLabel`)}]\n${Up.content}`;E(async()=>{let{addMessage:e}=await import(`./context-indicator-CWyjBBv3.js`).then(e=>e.V);return{addMessage:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8])).then(({addMessage:i})=>{i(`user`,n,!0,[],null,!1,r),v.messageHistory.push({role:`user`,content:r,timestamp:new Date().toISOString()}),i(`assistant`,e,!0),v.messageHistory.push({role:`assistant`,content:e}),E(async()=>{let{saveCurrentSession:e}=await import(`./context-indicator-CWyjBBv3.js`).then(e=>e.xr);return{saveCurrentSession:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8])).then(({saveCurrentSession:e})=>{e()}),Promise.all([E(()=>import(`./context-indicator-CWyjBBv3.js`).then(e=>e.ft),__vite__mapDeps([0,1,2,3,4,5,6,7,8])),new Promise(e=>requestAnimationFrame(e))]).then(([{autoScrollToBottom:e}])=>{e(document.getElementById(`chatContainer`),{force:!0,smooth:!0}),A(t(`sidePanel.popupTransferred`))})}),sm()}function pm(e,t,n){let{context:r,truncated:i}=Xp(n,t);Up=e,Wp=t,Gp=r,Kp=i,mm()}function mm(){Hp=``,qp=!0,rm(Up?.content);let e=Zp(Wp,Gp,Up.content,Kp);Vp=`popup_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,chrome.runtime.sendMessage({type:`SIDEPANEL_POPUP_ASK`,sessionId:Vp,messages:e}).catch(e=>{r.error(`[SelectionPopup] sendMessage failed:`,e),om(t(`sidePanel.popupRequestFailed`)),qp=!1})}var hm=!1;function gm(){hm||(hm=!0,chrome.runtime.onMessage.addListener(e=>{if(!(!e||!e.type)&&e.type.startsWith(`SIDEPANEL_POPUP_`)&&e.sessionId===Vp){if(e.type===`SIDEPANEL_POPUP_STREAM_CHUNK`)e.delta&&(Hp+=e.delta,am(lt(Hp)));else if(e.type===`SIDEPANEL_POPUP_STREAM_DONE`)qp=!1,e.finalContent&&(Hp=e.finalContent),am(lt(Hp));else if(e.type===`SIDEPANEL_POPUP_STREAM_ERROR`){if(!qp)return;qp=!1,om(e.error||t(`sidePanel.popupRequestFailed`))}}}))}function _m(){gm(),document.addEventListener(`mousedown`,cm),document.addEventListener(`keydown`,lm)}function vm(e,t,n,r,i){!t||!e||(gm(),nm(n,r),Jp=!1,pm(e,t,i||v.currentSelectionRange))}e(`zh`,{tokenStats:{clearConfirmMessage:`确定要清空所有 Token 使用统计吗?此操作不可撤销。`,loadFailed:`加载失败`,currentSessionNoData:`当前会话暂无数据`,totalTokenUsage:`总 Token 消耗`,apiCallCount:`API 调用次数`,contextUsageRate:`上下文使用率`,max:`最大`,avg:`平均`,min:`最小`,totalTokens:`总 Token`,totalSessions:`总会话数`,totalApiCalls:`总 API 调用`,callTypeNonStream:`普通`,callTypeStream:`流式`,callTypeReflection:`反思`,callTypeToolReflection:`工具反思`,callTypeSubtaskReflection:`子任务反思`,tabTrend:`趋势`,tabDistribution:`分布`,tabGlobal:`全局`,topCardSessionTokens:`本次 Token`,topCardSessionCalls:`本次调用`,topCardContextPeak:`上下文峰值`,sparklineTitle:`最近 20 次调用趋势`,distPromptVsCompletion:`Prompt / Completion 占比`,distPrompt:`Prompt`,distCompletion:`Completion`,distByModel:`按模型分布`,distByCallType:`按调用类型分布`,distNoData:`暂无分布数据`,globalSparklineTitle:`最近 30 天趋势`,globalNoDailyData:`所选范围内暂无数据`,globalTotalTokens:`总 Token`,globalTotalSessions:`总会话数`,globalTotalApiCalls:`总 API 调用`}}),e(`en`,{tokenStats:{clearConfirmMessage:`Are you sure you want to clear all Token usage statistics? This action cannot be undone.`,loadFailed:`Load failed`,currentSessionNoData:`No data for current session`,totalTokenUsage:`Total Token Usage`,apiCallCount:`API Call Count`,contextUsageRate:`Context Usage Rate`,max:`Max`,avg:`Avg`,min:`Min`,totalTokens:`Total Tokens`,totalSessions:`Total Sessions`,totalApiCalls:`Total API Calls`,callTypeNonStream:`Normal`,callTypeStream:`Stream`,callTypeReflection:`Reflection`,callTypeToolReflection:`Tool Reflection`,callTypeSubtaskReflection:`Subtask Reflection`,tabTrend:`Trend`,tabDistribution:`Distribution`,tabGlobal:`Global`,topCardSessionTokens:`Session Tokens`,topCardSessionCalls:`Session Calls`,topCardContextPeak:`Context Peak`,sparklineTitle:`Last 20 Calls Trend`,distPromptVsCompletion:`Prompt / Completion Ratio`,distPrompt:`Prompt`,distCompletion:`Completion`,distByModel:`By Model`,distByCallType:`By Call Type`,distNoData:`No distribution data`,globalSparklineTitle:`Last 30 Days Trend`,globalNoDailyData:`No data in selected range`,globalTotalTokens:`Total Tokens`,globalTotalSessions:`Total Sessions`,globalTotalApiCalls:`Total API Calls`}});function ym(e,n){let i=document.getElementById(`tokenStatsOverlay`),a=document.getElementById(`tokenStatsClose`),o=document.getElementById(`tokenStatsRefreshBtn`),s=document.getElementById(`tokenStatsClearBtn`),c=document.getElementById(`tokenStatsTabNav`),l=document.getElementById(`tokenStatsTopCards`);if(!i)return;let u=`trend`,d=`month`;function f(){i.style.display=`flex`,h()}function p(){i.style.display=`none`}if(window.openTokenStats=f,a&&a.addEventListener(`click`,p),i&&i.addEventListener(`click`,e=>{e.target===i&&p()}),o&&o.addEventListener(`click`,h),s&&s.addEventListener(`click`,async()=>{await n(t(`tokenStats.clearConfirmMessage`),t(`toolStats.clearTitle`))&&(await he(),h())}),c){c.addEventListener(`click`,e=>{let t=e.target.closest(`.token-tab-btn`);if(!t)return;let n=t.dataset.tab;if(n===u)return;c.querySelectorAll(`.token-tab-btn`).forEach(e=>{e.classList.remove(`active`),e.style.borderBottomColor=`transparent`,e.style.color=`var(--text-secondary)`}),t.classList.add(`active`),t.style.borderBottomColor=`var(--brand-500)`,t.style.color=`var(--brand-500)`,document.querySelectorAll(`.token-tab-content`).forEach(e=>{e.style.display=`none`});let r=document.getElementById(`tokenTab${n.charAt(0).toUpperCase()+n.slice(1)}`);r&&(r.style.display=n===`global`?`flex`:``),u=n});let e=c.querySelector(`.token-tab-btn.active`);e&&(e.style.borderBottomColor=`var(--brand-500)`,e.style.color=`var(--brand-500)`)}let m=document.querySelectorAll(`.token-time-range-btn`);m.forEach(e=>{e.addEventListener(`click`,()=>{let t=e.dataset.range;t!==d&&(d=t,m.forEach(e=>{e.classList.remove(`active`),e.style.border=`1px solid var(--border-default)`,e.style.background=`var(--bg-surface)`,e.style.color=`var(--text-secondary)`}),e.classList.add(`active`),e.style.border=`1px solid var(--brand-500)`,e.style.background=`var(--brand-500)`,e.style.color=`var(--text-on-brand)`,b())})});async function h(){let n=e(),i=document.getElementById(`tokenStatsLoading`),a=document.getElementById(`tokenStatsEmpty`),o=document.getElementById(`tokenStatsContent`);i&&(i.style.display=``),a&&(a.style.display=`none`),o&&(o.style.display=`none`),c&&(c.style.display=`none`),l&&(l.style.display=`none`);try{let[e,t]=await Promise.all([je(n),Me()]);if(i&&(i.style.display=`none`),!(t&&t.totalApiCalls>0)){a&&(a.style.display=``);return}o&&(o.style.display=``),c&&(c.style.display=`flex`),l&&(l.style.display=``),g(e),ee(e),ie(e.records||[]),v(t),b()}catch(e){r.error(`[TokenStats] load stats failed:`,e),i&&(i.style.display=`none`),a&&(a.textContent=t(`tokenStats.loadFailed`),a.style.display=``)}}function g(e){if(!l)return;if(!e||e.apiCallCount===0){l.innerHTML=``;return}let n=e.maxContextUsageRate||0,r=C(n);l.innerHTML=`
|
|
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">${k(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">${k(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-Bs34HFah.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-Bs34HFah.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-Bs34HFah.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=`
|
|
476
475
|
<div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 8px;">
|
|
477
476
|
<div style="background: var(--brand-soft-bg); border-radius: 8px; padding: 10px; text-align: center;">
|
|
478
477
|
<div style="font-size: 10px; color: var(--text-tertiary); margin-bottom: 4px;">${t(`tokenStats.topCardSessionTokens`)}</div>
|
|
@@ -583,7 +582,7 @@ import{a as e,c as t,i as n,l as r,n as i,r as a,s as o}from"./i18n-DvmxOw8q.js"
|
|
|
583
582
|
<span style="background:var(--bg-subtle);padding:1px 5px;border-radius:3px;font-size:9px;color:var(--text-secondary);">${k(i)}</span>
|
|
584
583
|
<span style="font-weight:500;color:var(--text-primary);margin-left:auto;">${S(e.totalTokens)}</span>
|
|
585
584
|
<span style="color:${o};font-size:9px;font-weight:500;width:35px;text-align:right;">${((e.contextUsageRate||0)*100).toFixed(1)}%</span>
|
|
586
|
-
</div>`}).join(``)}function S(e){return e>=1e6?(e/1e6).toFixed(1)+`M`:e>=1e3?(e/1e3).toFixed(1)+`K`:String(e)}function C(e){return e>=.8?`#ef4444`:e>=.5?`#f59e0b`:`#10b981`}}function
|
|
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}
|
|
587
586
|
代理地址:{url}
|
|
588
587
|
|
|
589
588
|
确定要重启代理服务吗?重启期间服务将短暂不可用。`,restartAgentTitle:`重启代理`,agentRestarting:`代理服务正在重启...`,restartFailed:`重启失败: {error}`,restartRequestFailed:`重启请求失败: {error}`,updateAgentConfirm:`代理名称:{name}
|
|
@@ -601,7 +600,7 @@ Agent address: {url}
|
|
|
601
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}
|
|
602
601
|
Agent address: {url}
|
|
603
602
|
|
|
604
|
-
Are you sure you want to stop the agent service? You will not be able to connect and will need to manually restart it.`,stopAgentTitle:`Stop Agent`,agentStopped:`Agent service stopped, agent is offline`,stopFailed:`Stop failed: {error}`,stopRequestFailed:`Stop request failed: {error}`,agentStatusRefreshed:`Agent status refreshed`,deleteAgentTitle:`Delete Agent`,deleteAgentConfirm:`Are you sure you want to delete agent "{name}"? This action cannot be undone.`,welcomeTitle:`Start a Conversation`,welcomeSubtitle:`Enter your question and the AI assistant will help you`,sendBtnStop:`Stop generating`,sendBtnSend:`Send`,defaultPromptImage:`Please look at the attached image and describe what you see`,defaultPromptFile:`Please read the attached file and summarize the key points`,defaultPromptAttachments:`Please review the attached image and file and summarize the key points`,defaultPromptKnowledge:`Please answer based on the knowledge base content I referenced`,defaultKnowledgeQuery:`key points summary`,defaultPromptPage:`Please summarize the main content of this page`,defaultPromptSelection:`Please continue based on the content I provided`,defaultPromptContext:`Please continue based on the context I provided`,imageNotEnabled:`Image recognition not enabled, image attached as file`,screenshotFailed:`Screenshot failed, please retry`,auditCategoryAuth:`Auth`,auditCategoryFs:`File`,auditCategoryExec:`Command`,auditCategorySecurity:`Security`,auditCategorySystem:`System`,auditDetailSeparator:`; `,auditQueryFailed:`Query failed: {error}`,auditLoadFailed:`Load failed: {error}`,auditNoMatch:`No matching audit logs`,auditEmpty:`No audit logs`,clearStatsConfirm:`Are you sure you want to clear all tool usage stats? This action cannot be undone.`,clearStatsTitle:`Clear Stats`,toolStatsSummary:`Used {used} tools, unused {unused} tools`,toolStatsLoadFailed:`Load failed`,toolNameDescSeparator:`: `}}),window.showCustomConfirm=function(e,n=t(`sidePanel.confirmAction`)){return new Promise(t=>{let r=document.getElementById(`customConfirmOverlay`),i=document.getElementById(`customConfirmTitle`),a=document.getElementById(`customConfirmMessage`),o=document.getElementById(`customConfirmCancelBtn`),s=document.getElementById(`customConfirmOkBtn`);if(!r||!i||!a||!o||!s){t(confirm(e));return}let c=()=>{r.style.display=`none`,s.removeEventListener(`click`,l),o.removeEventListener(`click`,u),r.removeEventListener(`click`,d),document.removeEventListener(`keydown`,f)},l=()=>{c(),t(!0)},u=()=>{c(),t(!1)},d=e=>{e.target===r&&(c(),t(!1))},f=e=>{e.key===`Enter`?(e.preventDefault(),e.stopPropagation(),l()):e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),u())};i.textContent=n,a.innerHTML=e.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`).replace(/\n/g,`<br>`),r.style.display=`flex`,s.addEventListener(`click`,l),o.addEventListener(`click`,u),r.addEventListener(`click`,d),document.addEventListener(`keydown`,f),requestAnimationFrame(()=>s.focus())})},chrome.storage.onChanged.addListener((e,t)=>{t===`local`&&e.chatAutoCompaction&&(v.chatConfig.autoCompaction=e.chatAutoCompaction.newValue===!0,Sm(),r.debug(`[SidePanel] auto-compaction config updated:`,v.chatConfig.autoCompaction)),t===`local`&&e.chatPersistSummaryToMemory&&(v.chatConfig.persistSummaryToMemory=e.chatPersistSummaryToMemory.newValue!==!1,Cm(),r.debug(`[SidePanel] persist-summary config updated:`,v.chatConfig.persistSummaryToMemory)),t===`local`&&e.chatMaxMemoryMessages&&(v.chatConfig.maxMemoryMessages=e.chatMaxMemoryMessages.newValue,xm(),r.debug(`[SidePanel] memory limitconfiguration updated:`,v.chatConfig.maxMemoryMessages)),t===`local`&&e.queueAutoCarry&&(v.chatConfig.queueAutoCarry=e.queueAutoCarry.newValue!==!1,r.debug(`[SidePanel] queue auto-carry updated:`,v.chatConfig.queueAutoCarry)),t===`local`&&e.queueAutoCarryEveryNIterations&&(v.chatConfig.queueAutoCarryEveryNIterations=e.queueAutoCarryEveryNIterations.newValue,r.debug(`[SidePanel] queue auto-carry interval updated:`,v.chatConfig.queueAutoCarryEveryNIterations))});function xm(){let e=document.getElementById(`memoryLimitLabel`);e&&(v.chatConfig.maxMemoryMessages!==null&&v.chatConfig.maxMemoryMessages!==void 0&&v.chatConfig.maxMemoryMessages>0?e.textContent=v.chatConfig.maxMemoryMessages:e.textContent=t(`sidePanel.memoryLimitAll`),e.title=t(`sidePanel.memoryLimitTitle`))}function Sm(){let e=document.getElementById(`autoCompactBtn`);e&&(e.checked=v.chatConfig.autoCompaction===!0)}function Cm(){let e=document.getElementById(`persistSummaryBtn`);e&&(e.checked=v.chatConfig.persistSummaryToMemory!==!1)}function wm(e){e.preventDefault(),e.stopPropagation();let t=document.getElementById(`memoryLimitDropdown`);if(t.classList.toggle(`show`),t.classList.contains(`show`)){let e=v.chatConfig.maxMemoryMessages;t.querySelectorAll(`.memory-limit-option`).forEach(t=>{t.classList.remove(`selected`);let n=parseInt(t.dataset.value);(e===null&&n===0||e!==null&&e>0&&n===e)&&t.classList.add(`selected`)});let n=t.querySelector(`#memoryLimitInput`);e!==null&&e>0?n.value=e:n.value=``}}function Tm(){let e=document.getElementById(`memoryLimitDropdown`),n=document.getElementById(`memoryLimitLabel`),r=e?.querySelector(`#memoryLimitInput`);if(!e||!n)return;xm(),n.addEventListener(`click`,wm);let i=document.getElementById(`autoCompactBtn`);i&&(i.checked=v.chatConfig.autoCompaction===!0,i.addEventListener(`change`,()=>{let e=i.checked;chrome.storage.local.set({chatAutoCompaction:e},()=>{v.chatConfig.autoCompaction=e,A(t(`sidePanel.configUpdated`),`success`)})}));let a=document.getElementById(`persistSummaryBtn`);a&&(a.checked=v.chatConfig.persistSummaryToMemory!==!1,a.addEventListener(`change`,()=>{let e=a.checked;chrome.storage.local.set({chatPersistSummaryToMemory:e},()=>{v.chatConfig.persistSummaryToMemory=e,A(t(`sidePanel.configUpdated`),`success`)})}));let o=e.querySelectorAll(`.memory-limit-option`);o.forEach(e=>{e.addEventListener(`click`,n=>{n.stopPropagation();let i=parseInt(e.dataset.value),a=i===0?null:i;o.forEach(e=>e.classList.remove(`selected`)),e.classList.add(`selected`),r&&(r.value=i===0?``:i),chrome.storage.local.set({chatMaxMemoryMessages:a},()=>{v.chatConfig.maxMemoryMessages=a,xm(),A(t(`sidePanel.configUpdated`),`success`)})})}),r&&(r.addEventListener(`click`,e=>e.stopPropagation()),r.addEventListener(`mousedown`,e=>e.stopPropagation()),r.addEventListener(`change`,e=>{e.stopPropagation();let n=e.target.value.trim(),r=n&&parseInt(n)>0?parseInt(n):null;o.forEach(e=>e.classList.remove(`selected`)),chrome.storage.local.set({chatMaxMemoryMessages:r},()=>{v.chatConfig.maxMemoryMessages=r,xm(),A(t(`sidePanel.configUpdated`),`success`)})})),document.getElementById(`memoryLimitConfigEntry`)?.addEventListener(`click`,()=>{chrome.runtime.sendMessage({type:`OPEN_OPTIONS_PAGE`,hash:`memory`})}),document.addEventListener(`click`,t=>{!e.contains(t.target)&&t.target!==n&&e.classList.remove(`show`)})}async function Em(e){if(v.activeAgentId&&v.activeAgentId!=="default")try{let{updateAgent:t}=await E(async()=>{let{updateAgent:e}=await import(`./agent-store-QTeMyM9O.js`).then(e=>e.t);return{updateAgent:e}},__vite__mapDeps([5,1,2,3]));await t(v.activeAgentId,{model:e})}catch{}else chrome.storage.local.set({modelName:e}),ue(e)}async function Dm(){try{let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),t=bm(e.pairedAgents),n=e.activeAgentId,r=t.find(e=>e.id===n&&!e.disabled);if(!r){v.agentPlatform={connected:!1},$(v.agentPlatform);return}if(r.token)try{let e=await fetch(`${r.url}/api/status/detail`,{cache:`no-cache`,headers:{Authorization:`Bearer ${r.token}`}});if(e.ok){let t=await e.json();if(t.success){v.agentPlatform={platformName:t.platformName||`Unknown`,platform:t.platform||`unknown`,arch:t.arch||`unknown`,shell:t.shell||`/bin/sh`,homeDir:t.homeDir||``,workdir:t.workdir||``,connected:!0},t.version&&v.agentVersions.set(n,t.version),t.workdir&&v.agentWorkdirs.set(n,t.workdir),t.homeDir&&v.agentHomeDirs.set(n,t.homeDir);let e=rh(t.platformName||t.platform,t.arch);e&&v.agentSystemInfos.set(n,e)}else v.agentPlatform={connected:!1}}else v.agentPlatform={connected:!1}}catch{v.agentPlatform={connected:!1}}else v.agentPlatform={connected:!1};$(v.agentPlatform),hi()}catch{}}async function Om(e,t,n){if(v.activeAgentId&&v.activeAgentId!=="default")try{let{updateAgent:n}=await E(async()=>{let{updateAgent:e}=await import(`./agent-store-QTeMyM9O.js`).then(e=>e.t);return{updateAgent:e}},__vite__mapDeps([5,1,2,3]));await n(v.activeAgentId,{temperature:e,topP:t})}catch{}else chrome.storage.local.set({temperature:e,topP:t,selectedTempIndex:n})}function km(){let e=document.getElementById(`currentModelTag`);if(!e)return;let t=v.currentModel||``;e.textContent=t,e.title=t,e.style.display=t?``:`none`}var Am=new Set,jm=0;function Mm(){let e=document.getElementById(`workdirTag`);e&&(e.dataset.locked=Rr(v.activeSessionId)?`true`:`false`)}async function Nm(){let e=++jm,n=document.getElementById(`workdirTag`),i=document.getElementById(`workdirTagName`);if(!n||!i)return;let a=v.activeSessionId||null,o=Array.isArray(v.enabledTools)&&v.enabledTools.includes(`agent_exec`);if(v.agentPlatform?.connected!==!0||!o){n.style.display=`none`;return}let c=null;try{c=await p(a)}catch(e){r.debug(`[WorkdirTag] resolve failed:`,e&&e.message)}if(e!==jm)return;let l=c&&c.workdir||``;if(!l){n.style.display=`none`;return}n.style.display=``,i.textContent=s(l,{homeDir:v.agentPlatform?.homeDir||``}),Mm();try{let{getWorkspaceRoot:e}=await E(async()=>{let{getWorkspaceRoot:e}=await import(`./workspace-manager-DVPkwn2d.js`).then(e=>e.j);return{getWorkspaceRoot:e}},__vite__mapDeps([8,1,2,3])),t=await e(a),i=!!(t&&t!==l);i&&c.scope==="default"?(n.dataset.invalid=`false`,zp(a).then(e=>{e&&Nm()}).catch(e=>r.debug(`[WorkdirTag] reconcile failed:`,e&&e.message))):n.dataset.invalid=i?`true`:`false`}catch{n.dataset.invalid=`false`}if(e===jm&&(n.title=`${l}${c.scope===`session`?t(`workdirTag.sessionScope`):t(`workdirTag.defaultScope`)}${n.dataset.invalid===`true`?t(`workdirTag.pathMissing`):``}`,c.boundWorkdir&&c.scope==="default")){let e=`${a||``}::${c.agentId||``}`;Am.has(e)||(Am.add(e),A(t(`workdirTag.agentSwitched`),`warning`))}}function Pm(){let e=document.getElementById(`workdirTag`);e&&(e.setAttribute(`aria-label`,t(`workdirTag.tagHint`)),e.addEventListener(`click`,async e=>{if(e.stopPropagation(),Rr(v.activeSessionId)){Mm(),A(t(`workdirTag.lockedHint`),`warning`);return}Mm();let{showSwitchWorkdirDialog:n}=await E(async()=>{let{showSwitchWorkdirDialog:e}=await import(`./context-indicator-CWyjBBv3.js`).then(e=>e.cn);return{showSwitchWorkdirDialog:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]));await n({sessionId:v.activeSessionId||null})})),Nm(),document.addEventListener(`session-switched`,()=>{Nm()}),document.addEventListener(`session-workdir-changed`,()=>{Nm()}),document.addEventListener(`agent-model-changed`,()=>{Nm()}),document.addEventListener(`agent-tools-changed`,()=>{Nm()}),document.addEventListener(`generating-state-changed`,()=>{Mm()}),document.addEventListener(`generation-ended`,()=>{Mm()}),un(()=>{Mm()})}function Fm(){let e=document.getElementById(`currentModelTag`);e&&e.addEventListener(`click`,e=>{e.stopPropagation(),document.getElementById(`tempDisplay`)?.click()}),km()}function Im(e){let t=0;document.querySelectorAll(`.model-option`).forEach(n=>{n.dataset.value===e?(n.classList.add(`selected`),n.querySelector(`.model-option-check`).textContent=`✓`,t=parseInt(n.dataset.contextWindow,10)||0):(n.classList.remove(`selected`),n.querySelector(`.model-option-check`).textContent=``)});let n=document.getElementById(`modelSelectValue`);n&&e&&(n.textContent=e);let r=document.getElementById(`modelSelectCtxBadge`);r&&(t>0?(r.textContent=g(t),r.style.display=``):r.style.display=`none`),km()}function Lm(e,n){let r=document.getElementById(`tempDropdown`);if(!r){typeof n==`function`&&n();return}let i=r.querySelector(`.model-section`),a=[];if((Array.isArray(e)?e:[]).forEach(e=>{typeof e==`string`?a.push({name:e,contextWindow:0}):e&&typeof e==`object`&&e.name&&a.push({name:e.name,contextWindow:e.contextWindow||0})}),i){i.innerHTML=`
|
|
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,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`).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-QTeMyM9O.js`).then(e=>e.t);return{updateAgent:e}},__vite__mapDeps([5,1,2,3]));await t(v.activeAgentId,{model:e})}catch{}else chrome.storage.local.set({modelName:e}),ue(e)}async function 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-QTeMyM9O.js`).then(e=>e.t);return{updateAgent:e}},__vite__mapDeps([5,1,2,3]));await n(v.activeAgentId,{temperature:e,topP:t})}catch{}else chrome.storage.local.set({temperature:e,topP:t,selectedTempIndex:n})}function 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-DVPkwn2d.js`).then(e=>e.j);return{getWorkspaceRoot:e}},__vite__mapDeps([8,1,2,3])),t=await e(a),i=!!(t&&t!==l);i&&c.scope==="default"?(n.dataset.invalid=`false`,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-Bs34HFah.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=`
|
|
605
604
|
<div class="model-section-title" data-i18n="model.selectModel">${t(`model.selectModel`)}</div>
|
|
606
605
|
<div class="section-select" id="modelSelect">
|
|
607
606
|
<div class="section-select-row" id="modelSelectRow">
|
|
@@ -610,7 +609,7 @@ Are you sure you want to stop the agent service? You will not be able to connect
|
|
|
610
609
|
<span class="section-select-caret"></span>
|
|
611
610
|
</div>
|
|
612
611
|
<div class="section-select-list" id="modelSelectList"></div>
|
|
613
|
-
</div>`;let e=i.querySelector(`#modelSelectList`);e.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">${k(r.name)}</span>`;let i=document.createElement(`span`);i.className=`model-option-right`;let a=document.createElement(`span`);a.className=`model-ctx-badge`;let o=r.contextWindow&&r.contextWindow>0;a.textContent=g(o?r.contextWindow:de(r.name)),o||(a.classList.add(`is-auto`),a.title=t(`settings.ctxBadgeAutoTip`)),i.appendChild(a),n.appendChild(i),n.addEventListener(`click`,e=>{e.stopPropagation(),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=`
|
|
614
613
|
<div class="menu-header">
|
|
615
614
|
<span class="menu-header-title"></span>
|
|
616
615
|
<button class="menu-copy-btn" type="button">
|
|
@@ -620,7 +619,7 @@ Are you sure you want to stop the agent service? You will not be able to connect
|
|
|
620
619
|
</button>
|
|
621
620
|
</div>
|
|
622
621
|
<div class="menu-items"></div>
|
|
623
|
-
`;let e=
|
|
622
|
+
`;let e=Bm.querySelector(`.menu-copy-btn`);return e?.addEventListener(`click`,n=>{n.stopPropagation(),Vm&&(ut(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=`
|
|
624
623
|
<span>${r}</span>
|
|
625
624
|
<span class="menu-item-actions">
|
|
626
625
|
<span class="menu-item-code">/${e.code}</span>
|
|
@@ -632,9 +631,9 @@ Are you sure you want to stop the agent service? You will not be able to connect
|
|
|
632
631
|
</svg>
|
|
633
632
|
</button>
|
|
634
633
|
</span>
|
|
635
|
-
`,o.addEventListener(`click`,t=>{t.stopPropagation(),
|
|
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 Ke(),r.debug(`[SidePanel] sendmessagedebuginfo:`),r.debug(` - isolateChat:`,v.isolateChat),r.debug(` - chatConfig:`,v.chatConfig),r.debug(` - messageHistory.length:`,v.messageHistory.length);let n=[{role:`system`,content:await at(null,{sessionId:p})}];if(v.isolateChat){let e=c(n[0]?.content||``),t=m(h,0,v.customModelMap)-e-4096-2e3,i=Math.floor(t*.7),a=v.messageHistory[v.messageHistory.length-1],o=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+`
|
|
636
635
|
|
|
637
|
-
`+o.historySummaryText}),n=[...n,...o.messages];for(let e=0;e<n.length-1;e++)n[e]={...n[e],content:u(n[e].content)}}else n.push({role:`user`,content:s});let i=await it(),a,o;try{let t=await wt(n,h,v.useTools,i);if(a=t.content,o=t.executionLog||[],or(f),t.wasStreamed)t.streamingMsgId&&(v.messageHistory.push({role:`assistant`,content:a,executionLog:o,messageId:t.streamingMsgId}),Ar());else{let{element:e,messageId:t}=
|
|
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 it(),a,o;try{let t=await wt(n,h,v.useTools,i);if(a=t.content,o=t.executionLog||[],or(f),t.wasStreamed)t.streamingMsgId&&(v.messageHistory.push({role:`assistant`,content:a,executionLog:o,messageId:t.streamingMsgId}),Ar());else{let{element:e,messageId:t}=ln(`assistant`,a,!0,o);await ht(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`
|
|
638
637
|
<div class="agent-dd-item${i?` active`:``}${a?` disabled`:``}" data-agent-id="${n.id}">
|
|
639
638
|
<span class="agent-dd-item-dot ${c}"></span>
|
|
640
639
|
<div class="agent-dd-item-info">
|
|
@@ -651,7 +650,7 @@ Are you sure you want to stop the agent service? You will not be able to connect
|
|
|
651
650
|
<button class="agent-dd-tool-btn delete" data-action="delete" data-id="${n.id}" title="${t(`sidePanel.deleteAgentBtn`)}">🗑</button>
|
|
652
651
|
</div>
|
|
653
652
|
</div>
|
|
654
|
-
`}).join(``);let o=document.getElementById(`agentDdRestartBtn`),s=document.getElementById(`agentDdUpdateBtn`),c=document.getElementById(`agentDdStopBtn`),l=!!(e&&r);o&&(o.disabled=!l),s&&(s.disabled=!l),c&&(c.disabled=!l)}async function th(e,t){if(t)try{let n=new AbortController;setTimeout(()=>n.abort(),2e3);let r=await fetch(`${e}/api/status/detail`,{signal:n.signal,headers:{Authorization:`Bearer ${t}`}});if(r.ok){let e=await r.json();if(e.success)return{online:!0,version:e.version||null,workdir:e.workdir||null,homeDir:e.homeDir||null,platformName:e.platformName||e.platform||null,arch:e.arch||null}}}catch{}try{let t=new AbortController;setTimeout(()=>t.abort(),2e3);let n=await fetch(`${e}/api/status`,{signal:t.signal});if(!n.ok)return{online:!1,version:null,workdir:null,homeDir:null,platformName:null,arch:null};let r=await n.json();return{online:!0,version:r.version||null,workdir:null,homeDir:null,platformName:r.platformName||r.platform||null,arch:r.arch||null}}catch{return{online:!1,version:null,workdir:null,homeDir:null,platformName:null,arch:null}}}function nh(e,t){return e?t&&e.startsWith(t)?`~`+e.substring(t.length):e:``}function rh(e,t){return e||``}function ih(e,n){let r=document.querySelector(`.agent-dd-item[data-agent-id="${e}"]`);if(!r)return;let i=r.querySelector(`.agent-dd-item-dot`),a=r.querySelector(`.agent-dd-item-status`),o=r.classList.contains(`active`);i&&(i.classList.remove(`checking`,`connected`,`disconnected`,`online`,`offline`),i.classList.add(o?n?`connected`:`disconnected`:n?`online`:`offline`)),a&&(o?a.textContent=t(n?`sidePanel.agentConnected`:`sidePanel.notConnected`):a.textContent===t(`sidePanel.agentChecking`)&&(a.textContent=t(n?`sidePanel.agentOnline`:`sidePanel.agentOffline`)))}function ah(e,n){if(!n)return;let r=document.querySelector(`.agent-dd-item[data-agent-id="${e}"]`);if(!r)return;let i=r.querySelector(`.agent-dd-item-info`);if(!i)return;let a=nh(n,v.agentHomeDirs.get(e)),o=i.querySelector(`.agent-dd-item-workdir`);o?(o.textContent=a,o.title=t(`sidePanel.workingDirectory`,{path:n})):(o=document.createElement(`span`),o.className=`agent-dd-item-workdir`,o.title=t(`sidePanel.workingDirectory`,{path:n}),o.textContent=a,i.appendChild(o))}window.updateAgentItemWorkdir=ah;async function oh(){try{let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),t=bm(e.pairedAgents),n=e.activeAgentId;await Promise.all(t.filter(e=>!e.disabled).map(async e=>{let t=await th(e.url,e.token),r=t.online;t.version&&v.agentVersions.set(e.id,t.version),t.workdir&&v.agentWorkdirs.set(e.id,t.workdir),t.homeDir&&v.agentHomeDirs.set(e.id,t.homeDir);let i=rh(t.platformName,t.arch);i&&v.agentSystemInfos.set(e.id,i),t.workdir&&ah(e.id,t.workdir),ih(e.id,r),e.id===n&&r!==(v.agentPlatform?.connected===!0)&&(v.agentPlatform={...v.agentPlatform,connected:r},$(v.agentPlatform,!0),r&&sh(e))}))}catch{}}async function sh(e){try{let t=e;if(!t){let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),n=bm(e.pairedAgents),r=e.activeAgentId;t=n.find(e=>e.id===r&&!e.disabled)}if(!t||!t.url){v.agentPlatform={...v.agentPlatform,connected:!0},$(v.agentPlatform),hi();return}if(t.token)try{let e=new AbortController;setTimeout(()=>e.abort(),3e3);let n=await fetch(`${t.url}/api/status/detail`,{signal:e.signal,headers:{Authorization:`Bearer ${t.token}`}});if(n.ok){let e=await n.json();if(e.success){v.agentPlatform={platformName:e.platformName||`Unknown`,platform:e.platform||`unknown`,arch:e.arch||`unknown`,shell:e.shell||`/bin/sh`,homeDir:e.homeDir||``,workdir:e.workdir||``,connected:!0},e.version&&v.agentVersions.set(t.id,e.version),e.workdir&&(v.agentWorkdirs.set(t.id,e.workdir),ah(t.id,e.workdir)),e.homeDir&&v.agentHomeDirs.set(t.id,e.homeDir);let n=rh(e.platformName||e.platform,e.arch);n&&v.agentSystemInfos.set(t.id,n),$(v.agentPlatform),hi();return}}}catch{}try{let e=new AbortController;setTimeout(()=>e.abort(),3e3);let n=await fetch(`${t.url}/api/status`,{signal:e.signal});if(n.ok){let e=await n.json();v.agentPlatform={platformName:e.platformName||e.platform||`Unknown`,platform:e.platform||`unknown`,arch:e.arch||`unknown`,connected:!0},$(v.agentPlatform),hi();return}}catch{}v.agentPlatform={...v.agentPlatform,connected:!0},$(v.agentPlatform),hi()}catch{v.agentPlatform={...v.agentPlatform,connected:!0},$(v.agentPlatform),hi()}}var ch=null;function lh(e,t=20){ch&&clearInterval(ch);let n=0;ch=setInterval(async()=>{if(n++,n>t||!e){clearInterval(ch),ch=null;return}try{let t=bm((await chrome.storage.local.get([`pairedAgents`])).pairedAgents).find(t=>t.id===e);if(!t){clearInterval(ch),ch=null;return}let n=await th(t.url,t.token);if(n.online){clearInterval(ch),ch=null,n.version&&v.agentVersions.set(e,n.version),n.workdir&&v.agentWorkdirs.set(e,n.workdir),n.homeDir&&v.agentHomeDirs.set(e,n.homeDir);let r=rh(n.platformName,n.arch);r&&v.agentSystemInfos.set(e,r),n.workdir&&ah(e,n.workdir),await sh(t),ih(e,!0)}}catch{}},3e3)}function uh(){let e=document.getElementById(`headerAgentDropdown`),t=document.getElementById(`headerAgentWrapper`);if(!e||!t)return;let n=document.body.clientWidth,r=t.getBoundingClientRect(),i=e.offsetWidth;n<312?(e.style.minWidth=n-16+`px`,e.style.maxWidth=n-16+`px`):(e.style.minWidth=``,e.style.maxWidth=``);let a=r.right+20-i,o=n-i-8;a=Math.max(8,Math.min(o,a)),e.style.left=a-r.left+`px`}async function dh(){let e=document.getElementById(`headerAgentTrigger`),n=document.getElementById(`headerAgentDropdown`),r=document.getElementById(`agentDdCopyBtn`),i=document.getElementById(`agentDdAddBtn`),a=document.getElementById(`agentDdRestartBtn`),o=document.getElementById(`agentDdUpdateBtn`),s=document.getElementById(`agentDdStopBtn`),c=document.getElementById(`agentDdRefreshBtn`);if(!e||!n)return;e.addEventListener(`click`,e=>{e.stopPropagation();let t=n.style.display!==`none`;n.style.display=t?`none`:``,t||(uh(),$(v.agentPlatform||{}),oh())}),document.addEventListener(`click`,t=>{!n.contains(t.target)&&t.target!==e&&(n.style.display=`none`)}),r.addEventListener(`click`,async e=>{e.stopPropagation(),v.activeAgentId;let n=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),r=bm(n.pairedAgents).find(e=>e.id===n.activeAgentId);r?.url&&(await navigator.clipboard.writeText(r.url),A(t(`sidePanel.agentAddressCopied`),`success`))}),i.addEventListener(`click`,async()=>{n.style.display=`none`,await chrome.storage.local.set({optionsInitialTab:`agent`});let e=await chrome.tabs.query({}),t=chrome.runtime.getURL(`options/index.html`),r=e.find(e=>e.url&&e.url.startsWith(t));if(r){chrome.tabs.update(r.id,{active:!0});try{chrome.tabs.sendMessage(r.id,{type:`SWITCH_TAB`,tab:`agent`})}catch{}}else chrome.runtime.openOptionsPage()}),a.addEventListener(`click`,async()=>{n.style.display=`none`;let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),r=bm(e.pairedAgents).find(t=>t.id===e.activeAgentId),i=r?.name||t(`sidePanel.unknownAgent`),a=r?.url||t(`sidePanel.unknownAgent`);if(await window.showCustomConfirm(t(`sidePanel.restartAgentConfirm`,{name:i,url:a}),t(`sidePanel.restartAgentTitle`)))try{chrome.runtime.sendMessage({type:`AGENT_RESTART`},async e=>{e?.success?(A(t(`sidePanel.agentRestarting`),`success`),v.agentPlatform={...v.agentPlatform,connected:!1},await $(v.agentPlatform,!0),r?.id&&ih(r.id,!1),lh(r?.id)):A(t(`sidePanel.restartFailed`,{error:e?.error||t(`sidePanel.unknownError`)}),`error`)})}catch(e){A(t(`sidePanel.restartRequestFailed`,{error:e.message}),`error`)}}),o.addEventListener(`click`,async()=>{n.style.display=`none`;let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),r=bm(e.pairedAgents).find(t=>t.id===e.activeAgentId),i=r?.name||t(`sidePanel.unknownAgent`),a=r?.url||t(`sidePanel.unknownAgent`),o=chrome.runtime.getManifest().version,s=`~${o}`,c=o.split(`.`).slice(0,2).join(`.`)+`.x`;if(await window.showCustomConfirm(t(`sidePanel.updateAgentConfirm`,{name:i,url:a,version:c}),t(`sidePanel.updateAgentTitle`))){A(t(`sidePanel.agentUpdating`),`info`);try{chrome.runtime.sendMessage({type:`AGENT_UPDATE`,target:s},async e=>{if(e?.success&&e.upToDate){await Zm(),A(e.message||t(`sidePanel.agentAlreadyLatest`),`info`);return}e?.success?(await Zm(),A(t(`sidePanel.agentUpdateRestarting`),`success`),v.agentPlatform={...v.agentPlatform,connected:!1},await $(v.agentPlatform,!0),r?.id&&ih(r.id,!1),lh(r?.id)):A(t(`sidePanel.updateFailed`,{error:e?.error||t(`sidePanel.unknownError`)}),`error`)})}catch(e){A(t(`sidePanel.updateRequestFailed`,{error:e.message}),`error`)}}}),s.addEventListener(`click`,async()=>{n.style.display=`none`;let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),r=bm(e.pairedAgents).find(t=>t.id===e.activeAgentId),i=r?.name||t(`sidePanel.unknownAgent`),a=r?.url||t(`sidePanel.unknownAgent`);if(await window.showCustomConfirm(t(`sidePanel.stopAgentConfirm`,{name:i,url:a}),t(`sidePanel.stopAgentTitle`)))try{chrome.runtime.sendMessage({type:`AGENT_STOP`},async e=>{e?.success?(A(t(`sidePanel.agentStopped`),`success`),v.agentPlatform={...v.agentPlatform,connected:!1},await $(v.agentPlatform,!0),r?.id&&ih(r.id,!1)):A(t(`sidePanel.stopFailed`,{error:e?.error||t(`sidePanel.unknownError`)}),`error`)})}catch(e){A(t(`sidePanel.stopRequestFailed`,{error:e.message}),`error`)}}),c&&c.addEventListener(`click`,async()=>{document.querySelectorAll(`.agent-dd-item-dot`).forEach(e=>{e.classList.remove(`online`,`offline`),e.classList.add(`checking`)}),document.querySelectorAll(`.agent-dd-item-status`).forEach(e=>{e.textContent=t(`sidePanel.agentChecking`)}),await oh(),A(t(`sidePanel.agentStatusRefreshed`),`success`)}),document.getElementById(`agentDdList`).addEventListener(`click`,async e=>{let t=e.target.closest(`.agent-dd-tool-btn`),n=e.target.closest(`.agent-dd-item`);if(t){e.stopPropagation(),l(t.dataset.action,t.dataset.id);return}n&&!n.classList.contains(`disabled`)&&!n.classList.contains(`active`)&&(e.stopPropagation(),l(`switch`,n.dataset.agentId))});async function l(e,n){let r=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),i=bm(r.pairedAgents);switch(e){case`enable`:i=i.map(e=>e.id===n?{...e,disabled:!1}:e),await chrome.storage.local.set({pairedAgents:i});break;case`disable`:{i=i.map(e=>e.id===n?{...e,disabled:!0}:e);let e=r.activeAgentId;r.activeAgentId===n&&(e=i.find(e=>e.id!==n&&!e.disabled)?.id||null),await chrome.storage.local.set({pairedAgents:i,activeAgentId:e||``}),e?chrome.runtime.sendMessage({type:`AGENT_CONNECTION_CHANGED`,connected:!0,agentId:e}):chrome.runtime.sendMessage({type:`AGENT_CONNECTION_CHANGED`,connected:!1});break}case`switch`:await chrome.storage.local.set({activeAgentId:n}),chrome.runtime.sendMessage({type:`AGENT_CONNECTION_CHANGED`,connected:!0,agentId:n});break;case`disconnect`:await chrome.storage.local.set({activeAgentId:``}),chrome.runtime.sendMessage({type:`AGENT_CONNECTION_CHANGED`,connected:!1});break;case`delete`:{let e=i.find(e=>e.id===n);if(!await window.showCustomConfirm(t(`sidePanel.deleteAgentTitle`),t(`sidePanel.deleteAgentConfirm`,{name:e?.name||n})))return;i=i.filter(e=>e.id!==n);let a=r.activeAgentId===n?i.find(e=>!e.disabled)?.id||null:r.activeAgentId;await chrome.storage.local.set({pairedAgents:i,activeAgentId:a||``}),a?chrome.runtime.sendMessage({type:`AGENT_CONNECTION_CHANGED`,connected:!0,agentId:a}):chrome.runtime.sendMessage({type:`AGENT_CONNECTION_CHANGED`,connected:!1});break}}let a=document.getElementById(`headerAgentDropdown`);a&&(a.style.display=`none`)}}var fh=new Map,ph=8;function mh(e,t){for(fh.has(e)&&fh.delete(e),fh.set(e,t);fh.size>ph;)fh.delete(fh.keys().next().value)}function hh(e){let t=fh.get(e);if(t!==void 0)return fh.delete(e),fh.set(e,t),t}function gh(e){fh.delete(e)}document.addEventListener(`DOMContentLoaded`,async()=>{await Ge(),mt(()=>{gt()}),ir(),await Promise.allSettled([n().then(()=>{i(),Fr(),o(()=>{i(),Fr()})}),Ye(),_t(),yr()]),window.__tableBlocks=[],chrome.runtime.onMessage.addListener(e=>{if(e.type===`SCHEDULED_SESSION_UPDATED`){let t=e.sessionId,n=e.phase===`started`;t===v.activeSessionId?(v.generatingSessionIds.has(t)||v.pendingCallApiSessionIds.has(t)||tn().catch(()=>{}),n&&Ua(t)):t&&(n||Xi(t).catch(()=>{}),document.dispatchEvent(new CustomEvent(`session-cache-invalidate`,{detail:{sessionId:t}})));return}if(e.type===`CLOSE_SIDEPANEL`){r.debug(`[SidePanel] recei to CLOSE_SIDEPANEL,closesidebar`);try{window.close()}catch{}return}if(e.type===`SELECTION_AI_SEARCH`&&e.prompt&&(r.debug(`[SidePanel] received selectedtext AI search:`,e.selectedText?.substring(0,50)),e.selectedText&&Rm(e.selectedText),gr(e.prompt,e.selectedText),chrome.storage.session.remove(`pendingSelectionSearch`).catch(()=>{})),e.type===`FILL_SIDEPANEL_INPUT`&&e.text&&(r.debug(`[SidePanel] received follow-upfill:`,e.text?.substring(0,50)),an(e.text),chrome.storage.session.remove(`pendingFillInput`).catch(()=>{})),e.type===`DIRECT_SEND`&&e.text&&(r.debug(`[SidePanel] received directsend:`,e.text?.substring(0,50)),e.selectedText&&Rm(e.selectedText),Xn(e.text,e.selectedText||``),chrome.storage.session.remove(`pendingDirectSend`).catch(()=>{})),e.type===`AGENT_STATUS_CHANGE`&&(r.debug(`[SidePanel] recei to Agent status change:`,e.connected,e.status),v.agentPlatform={...v.agentPlatform,connected:e.connected},$(v.agentPlatform),hi(),Fi(),e.connected&&sh()),e.type===`AGENT_CONNECTION_CHANGED`){if(r.debug(`[SidePanel] recei to Agent connection statuschanged:`,e.connected,e.agentId),!e.connected){v.agentPlatform={connected:!1},$(v.agentPlatform),hi(),Fi();return}e.agentId&&(async()=>{try{let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),t=bm(e.pairedAgents).find(t=>t.id===e.activeAgentId&&!t.disabled);if(!t){v.agentPlatform={connected:!1},$(v.agentPlatform),hi(),Fi(),di();return}if(t.token)try{let n=await fetch(`${t.url}/api/status/detail`,{cache:`no-cache`,headers:{Authorization:`Bearer ${t.token}`}});if(n.ok){let t=await n.json();if(t.success){v.agentPlatform={platformName:t.platformName||`Unknown`,platform:t.platform||`unknown`,arch:t.arch||`unknown`,shell:t.shell||`/bin/sh`,homeDir:t.homeDir||``,workdir:t.workdir||``,connected:!0},t.version&&v.agentVersions.set(e.activeAgentId,t.version),t.workdir&&v.agentWorkdirs.set(e.activeAgentId,t.workdir),t.homeDir&&v.agentHomeDirs.set(e.activeAgentId,t.homeDir);let n=rh(t.platformName||t.platform,t.arch);n&&v.agentSystemInfos.set(e.activeAgentId,n)}else v.agentPlatform={connected:!1}}else v.agentPlatform={connected:!1}}catch{v.agentPlatform={connected:!1}}else try{let n=await fetch(`${t.url}/api/status`,{cache:`no-cache`});if(n.ok){let t=await n.json();v.agentPlatform={platformName:t.platformName||`Unknown`,platform:t.platform||`unknown`,arch:t.arch||`unknown`,shell:t.shell||`/bin/sh`,homeDir:t.homeDir||``,workdir:t.workdir||``,connected:!0},t.version&&v.agentVersions.set(e.activeAgentId,t.version);let r=rh(t.platformName||t.platform,t.arch);r&&v.agentSystemInfos.set(e.activeAgentId,r)}else v.agentPlatform={connected:!1}}catch{v.agentPlatform={connected:!1}}}catch{v.agentPlatform={connected:!1}}$(v.agentPlatform),hi(),Fi(),di()})()}e.type===`SCREENSHOT_RESULT`&&e.dataUrl&&(r.debug(`[SidePanel] received pageshortcutscreenshotresult:`,e.mode),Tr(e.dataUrl,e.mode,e.rect))});async function e(e){try{let t=await chrome.sidePanel.getOptions({tabId:e});return typeof t?.enabled==`boolean`?t.enabled:(await chrome.sidePanel.getOptions({}))?.enabled!==!1}catch{return!0}}chrome.tabs.onActivated.addListener(async t=>{if(r.debug(`[SidePanel] Tab switch, new Tab ID:`,t.tabId),!await e(t.tabId)){r.debug(`[SidePanel] Tab 无侧边栏,保持 currentTabId:`,v.currentTabId);return}v.currentTabId=t.tabId}),chrome.tabs.onUpdated.addListener(async(e,t)=>{t.status===`complete`&&v.currentTabId===e&&r.debug(`[SidePanel] current Tab page update:`,t)}),typeof marked<`u`&&(marked.setOptions({breaks:!0,gfm:!0}),r.debug(`[SidePanel] Marked library loaded`));let a=document.getElementById(`userInput`),s=document.getElementById(`sendBtn`),c=document.getElementById(`clearChatBtn`),l=document.getElementById(`exportChatBtn`),u=document.getElementById(`chatContainer`),d=document.getElementById(`tempDisplay`),p=document.getElementById(`tempDropdown`),m=document.getElementById(`tempPresetList`),h=document.getElementById(`tempSlider`),g=document.getElementById(`tempNumberInput`);function ee(){if(!a||v.isScrolling)return;a.style.height=`auto`;let e=a.scrollHeight;e<=50?a.style.height=``:a.style.height=Math.min(e,100)+`px`,ot()}chrome.storage.local.get([`temperature`,`topP`,`selectedTempIndex`],e=>{(!v.activeAgentId||v.activeAgentId==="default")&&(e.temperature!==void 0&&(v.temperature=e.temperature),e.topP!==void 0&&(v.topP=e.topP),e.selectedTempIndex!==void 0&&(v.selectedTempIndex=e.selectedTempIndex)),te()});function te(){h&&(h.value=v.temperature),g&&(g.value=v.temperature.toFixed(2));let e=document.getElementById(`tempIconValue`);e&&(e.textContent=v.temperature.toFixed(2)),_()}function ne(){let e=0,t=Math.abs(Qn[0].temp-v.temperature);for(let n=1;n<Qn.length;n++){let r=Math.abs(Qn[n].temp-v.temperature);r<t&&(t=r,e=n)}return e}function _(){let e=ne();m.innerHTML=Qn.map((n,r)=>`
|
|
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 Ge(),mt(()=>{gt()}),tr(),await Promise.allSettled([n().then(()=>{i(),ur(),o(()=>{i(),ur()})}),Ye(),_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`,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(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)=>`
|
|
655
654
|
<div class="temp-preset-item ${r===e?`selected`:``}" data-index="${r}">
|
|
656
655
|
<div class="temp-preset-radio"></div>
|
|
657
656
|
<div class="temp-preset-info">
|
|
@@ -660,15 +659,15 @@ Are you sure you want to stop the agent service? You will not be able to connect
|
|
|
660
659
|
</div>
|
|
661
660
|
<div class="temp-preset-value">${n.temp.toFixed(2)}</div>
|
|
662
661
|
</div>
|
|
663
|
-
`).join(``),m.querySelectorAll(`.temp-preset-item`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),y(parseInt(e.dataset.index))})})}function y(e){let t=
|
|
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=`
|
|
664
663
|
<div class="icon-wrapper">
|
|
665
664
|
<div class="icon">💬</div>
|
|
666
665
|
</div>
|
|
667
666
|
<h2>${t(`sidePanel.welcomeTitle`)}</h2>
|
|
668
667
|
<p>${t(`sidePanel.welcomeSubtitle`)}</p>
|
|
669
|
-
`,a.appendChild(e)}if(r.debug(`[SidePanel] session-switched: pendingTask?`,l,`pendingSessionIds:`,[...v.pendingCallApiSessionIds],`activeSessionId:`,n,`hasCancelApi:`,!!v.pendingCancelApi),l&&(r.debug(`[SidePanel] switch back tobackground task session,rebuildstreamingoutput element`),br(n)),Ua(n),!e.detail?.skipScrollRestore){let e=`scrollPosition_`+(n||`default`);chrome.storage.local.get([e],t=>{t[e]!==void 0&&setTimeout(async()=>{let n=document.getElementById(`chatContainer`);n&&(n.scrollTop=t[e]);let{updateScrollButtonState:r}=await E(async()=>{let{updateScrollButtonState:e}=await import(`./context-indicator-CWyjBBv3.js`).then(e=>e.ft);return{updateScrollButtonState:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]));r()},150)})}}),document.addEventListener(`session-cache-invalidate`,e=>{let{sessionId:t}=e.detail||{};t&&gh(t)}),document.querySelectorAll(`.model-option`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation();let n=e.dataset.value;v.currentModel=n,Im(n),Em(n),Vr()})}),document.addEventListener(`agent-model-changed`,()=>{Im(v.currentModel);let e=document.getElementById(`tempSlider`),t=document.getElementById(`tempNumberInput`),n=document.getElementById(`tempIconValue`);e&&(e.value=v.temperature),t&&(t.value=v.temperature.toFixed(2)),n&&(n.textContent=v.temperature.toFixed(2)),_()}),document.addEventListener(`click`,e=>{let t=document.getElementById(`promptDropdown`),n=document.getElementById(`promptSelector`),r=document.getElementById(`agentAtSelector`),i=document.getElementById(`selectionFloatingMenu`);n.contains(e.target)||(t.classList.remove(`show`),Mt()),r&&!r.contains(e.target)&&bi();let a=document.getElementById(`fileAtSelector`);if(a&&!a.contains(e.target)&&qd(),i&&!i.contains(e.target)){let t=window.getSelection(),n=cs(e.target),r=t&&!t.isCollapsed&&cs(t.anchorNode);(!n||!r)&&window.hideFloatingMenu()}});let w=document.getElementById(`stopCompanionBtn`);function se(){let e=!!(a&&a.value&&a.value.trim())||xt();return v.isGenerating&&e}function ce(){a&&a.value&&a.value.trim();let e=v.isGenerating,n=se();s.classList.toggle(`queue-mode`,n),s.classList.toggle(`stop-mode`,e&&!n),n?(s.innerHTML=`<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h11"/><path d="M3 12h11"/><path d="M3 18h7"/><path d="M17.5 10v8"/><path d="M14.5 15.5L17.5 18.5l3-3"/></svg>`,s.title=t(`queue.enqueueBtn`)):e?(s.innerHTML=`<svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect></svg>`,s.title=t(`sidePanel.sendBtnStop`)):(s.innerHTML=`<svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor"><path d="M12 4l-1.41 1.41L16.17 11H4v2h12.17l-5.58 5.59L12 20l8-8-8-8z"/></svg>`,s.title=t(`sidePanel.sendBtnSend`)),s.disabled=!1,s.style.opacity=``,s.style.cursor=``,w&&(w.style.display=n?``:`none`,w.disabled=!1,w.style.opacity=``,w.style.cursor=``)}s.addEventListener(`click`,()=>{if(!v.isGenerating){Mi();return}se()?Kr():Dr(s)}),w?.addEventListener(`click`,()=>Dr(w));function T(e){if(!v.isGenerating)return!1;let n=v.activeSessionId;return n?_n(n)?(ln(n),Dr(w&&w.style.display!==`none`?w:e||s)?(A(t(`queue.stopAndSendStarted`),`success`,2500),!0):(qn(n),!0)):(A(t(`queue.stopAndSendEmpty`),`warning`,3e3),!1):!1}function ue(e,{isPrimarySend:t=!1}={}){if(!e)return;let n=()=>t&&se();e.addEventListener(`contextmenu`,t=>{n()||!v.isGenerating||!_n(v.activeSessionId)||(t.preventDefault(),T(e))});let r=null,i=()=>{r&&=(clearTimeout(r),null)};e.addEventListener(`pointerdown`,t=>{t.pointerType===`mouse`&&t.button!==0||n()||!v.isGenerating||!_n(v.activeSessionId)||(i(),r=setTimeout(()=>{r=null,T(e)},600))});for(let t of[`pointerup`,`pointerleave`,`pointercancel`])e.addEventListener(t,i)}ue(s,{isPrimarySend:!0}),ue(w),document.addEventListener(`queue-stop-and-send`,()=>{T(w&&w.style.display!==`none`?w:s)}),document.addEventListener(`generating-state-changed`,ce),a.addEventListener(`input`,ce),document.addEventListener(`input-attachments-changed`,ce),document.addEventListener(`voice-draft-written`,ce);let de=document.getElementById(`shortcutsBtn`),D=document.getElementById(`shortcutsModal`),fe=document.getElementById(`shortcutsCloseBtn`);function pe(){D&&(D.style.display=`flex`)}function me(){D&&(D.style.display=`none`)}de&&de.addEventListener(`click`,e=>{e.stopPropagation(),pe();let t=document.getElementById(`headerMoreDropdown`);t&&t.classList.remove(`show`)}),fe&&fe.addEventListener(`click`,me),D&&D.addEventListener(`click`,e=>{e.target===D&&me()});let he=ss();hn(),Wn({adjustInputHeight:ee}).catch(e=>{r.warn(`[SidePanel] initVoiceInput failed:`,e?.message||e)}),document.addEventListener(`keydown`,e=>{if((e.ctrlKey||e.metaKey)&&e.key===`t`){e.preventDefault();let t=document.getElementById(`toolsPopup`);t&&t.style.display!==`none`?fi():ti()}if(e.key===`Escape`&&Jt()){e.preventDefault();return}if(!(e.key===`Escape`&&he.handleEscape())){if(e.key===`Escape`&&D&&D.style.display!==`none`){me();return}if(e.altKey&&e.code===`Slash`){e.preventDefault(),pe();return}if(e.altKey&&!e.shiftKey&&e.code===`KeyS`&&!e.ctrlKey&&!e.metaKey){e.preventDefault(),ei();return}if(e.altKey&&e.shiftKey&&e.code===`KeyS`&&!e.ctrlKey&&!e.metaKey){e.preventDefault(),Pi();return}if(Zn(e)){e.preventDefault(),Gt();return}if(e.altKey&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&e.code===`KeyN`){e.preventDefault(),ji();return}if(e.altKey&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&e.code===`KeyW`){e.preventDefault(),vt();return}if(e.altKey&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&e.code===`KeyE`){e.preventDefault();let t=document.querySelectorAll(`#chatContainer .message.user`),n=t[t.length-1];if(n){Wt(n);let e=document.getElementById(`userInput`);e&&e.focus()}return}if(e.altKey&&(e.key===`ArrowUp`||e.key===`ArrowDown`)){e.preventDefault();let t=e.key===`ArrowUp`?`prev`:`next`;he.jumpToMessage(t,e.ctrlKey||e.metaKey),he.updateActiveQuestion();return}}}),a.addEventListener(`keydown`,e=>{let t=document.getElementById(`promptSelector`),n=document.getElementById(`promptDropdown`),r=document.getElementById(`agentAtSelector`),i=document.getElementById(`agentAtDropdown`);if(r.style.display!==`none`&&i.classList.contains(`show`)){let t=document.getElementById(`agentAtTabs`),n=t&&t.classList.contains(`merged-mode`);if(!n&&e.key===`Tab`){e.preventDefault();let t=Array.from(document.querySelectorAll(`#agentAtTabs .prompt-tab`)).map(e=>e.dataset.tab),n=e=>{let t=document.querySelector(`#agentAtTabs .prompt-tab[data-tab="${e}"]`);return!!t&&t.style.display!==`none`},r=t.indexOf(ta);for(let e=0;e<t.length;e++)if(r=(r+1)%t.length,n(t[r])){Ai(t[r]);break}return}let r,i;n?(r=document.getElementById(`agentAtList`),i=v.selectedAgentAtIndex):ta===`pages`?(r=document.getElementById(`agentPageList`),i=v.selectedPageIndex):ta===`proxies`?(r=document.getElementById(`agentProxyList`),i=v.selectedProxyAtIndex):ta===`knowledge`?(r=document.getElementById(`agentKnowledgeList`),i=v.selectedKnowledgeAtIndex):(r=document.getElementById(`agentAtList`),i=v.selectedAgentAtIndex);let a=r?r.querySelectorAll(`.prompt-item`):[],o=a.length;if(o!==0){if(e.key===`ArrowDown`){e.preventDefault();let t=i<0?0:(i+1)%o;n?(v.selectedAgentAtIndex=t,ci(a)):ta===`proxies`?(v.selectedProxyAtIndex=t,ci(a)):ta===`knowledge`?(v.selectedKnowledgeAtIndex=t,ci(a)):ta===`pages`?(v.selectedPageIndex=t,Pn(a)):(v.selectedAgentAtIndex=t,ci(a));return}else if(e.key===`ArrowUp`){e.preventDefault();let t=i<0||i===0?o-1:i-1;n?(v.selectedAgentAtIndex=t,ci(a)):ta===`proxies`?(v.selectedProxyAtIndex=t,ci(a)):ta===`knowledge`?(v.selectedKnowledgeAtIndex=t,ci(a)):ta===`pages`?(v.selectedPageIndex=t,Pn(a)):(v.selectedAgentAtIndex=t,ci(a));return}else if(e.key===`Enter`&&i>=0){e.preventDefault(),a[i].click(),(e.ctrlKey||e.metaKey)&&bi();return}else if(e.key===`Escape`){bi();return}}}let o=document.getElementById(`fileAtSelector`),s=document.getElementById(`fileAtDropdown`);if(o&&s&&o.style.display!==`none`&&s.classList.contains(`show`)){let t=document.getElementById(`fileAtList`),n=t?t.querySelectorAll(`.prompt-item`):[],r=n.length;if(e.key===`ArrowDown`||e.key===`ArrowUp`){e.preventDefault(),r>0&&(v.selectedFileAtIndex=e.key===`ArrowDown`?v.selectedFileAtIndex<0?0:(v.selectedFileAtIndex+1)%r:v.selectedFileAtIndex<0||v.selectedFileAtIndex===0?r-1:v.selectedFileAtIndex-1,Qd(n));return}if(e.key===`Enter`&&r>0&&v.selectedFileAtIndex>=0){e.preventDefault(),n[v.selectedFileAtIndex].click();return}if(e.key===`Escape`){e.preventDefault(),qd();return}}if(t.style.display!==`none`&&n.classList.contains(`show`)){if(v.showMergedList){let t=n.querySelectorAll(`#promptList .prompt-item`),r=t.length;if(e.key===`ArrowDown`){e.preventDefault(),v.selectedPromptIndex<0?v.selectedPromptIndex=0:v.selectedPromptIndex=(v.selectedPromptIndex+1)%r,wn(t);return}if(e.key===`ArrowUp`){e.preventDefault(),v.selectedPromptIndex<0||v.selectedPromptIndex===0?v.selectedPromptIndex=r-1:--v.selectedPromptIndex,wn(t);return}if(e.key===`Enter`&&v.selectedPromptIndex>=0){e.preventDefault();let n=t[v.selectedPromptIndex];n.dataset.type===`skill`||n.dataset.type===`mcp`?(n.click(),(e.ctrlKey||e.metaKey)&&Mt()):e.ctrlKey||e.metaKey?Yr(n.dataset.code):bt(n.dataset.code);return}if(e.key===`Escape`){Mt();return}return}if(v.activeDropdownTab===`skills`){let t=n.querySelectorAll(`#skillList .skill-list-item`),r=t.length;if(e.key===`ArrowDown`){e.preventDefault(),v.selectedSkillIndex<0?v.selectedSkillIndex=0:v.selectedSkillIndex=(v.selectedSkillIndex+1)%r,Vi(t);return}if(e.key===`ArrowUp`){e.preventDefault(),v.selectedSkillIndex<0||v.selectedSkillIndex===0?v.selectedSkillIndex=r-1:--v.selectedSkillIndex,Vi(t);return}if(e.key===`Enter`&&v.selectedSkillIndex>=0){e.preventDefault(),t[v.selectedSkillIndex].click(),(e.ctrlKey||e.metaKey)&&Mt();return}if(e.key===`Escape`){Mt();return}if(e.key===`Tab`){e.preventDefault();let t=document.getElementById(`mcpTab`);t&&t.style.display!==`none`?Fn(`mcp`):Fn(`prompts`);return}return}if(v.activeDropdownTab===`mcp`){let t=n.querySelectorAll(`#mcpList .mcp-list-item`),r=t.length;if(e.key===`ArrowDown`){e.preventDefault(),v.selectedMcpServiceIndex<0?v.selectedMcpServiceIndex=0:v.selectedMcpServiceIndex=(v.selectedMcpServiceIndex+1)%r,Ot(t);return}if(e.key===`ArrowUp`){e.preventDefault(),v.selectedMcpServiceIndex<0||v.selectedMcpServiceIndex===0?v.selectedMcpServiceIndex=r-1:--v.selectedMcpServiceIndex,Ot(t);return}if(e.key===`Enter`&&v.selectedMcpServiceIndex>=0){e.preventDefault(),t[v.selectedMcpServiceIndex].click(),(e.ctrlKey||e.metaKey)&&Mt();return}if(e.key===`Escape`){Mt();return}if(e.key===`Tab`){e.preventDefault(),Fn(`prompts`);return}return}let t=n.querySelectorAll(`#promptList .prompt-item`),r=t.length;if(e.key===`Tab`){let t=document.getElementById(`skillsTab`),n=document.getElementById(`mcpTab`);if(t&&t.style.display!==`none`){e.preventDefault(),Fn(`skills`);return}if(n&&n.style.display!==`none`){e.preventDefault(),Fn(`mcp`);return}}if(r!==0&&e.key===`ArrowDown`){e.preventDefault(),v.selectedPromptIndex<0?v.selectedPromptIndex=0:v.selectedPromptIndex=(v.selectedPromptIndex+1)%r,wn(t);return}if(e.key===`ArrowUp`){e.preventDefault(),v.selectedPromptIndex<0||v.selectedPromptIndex===0?v.selectedPromptIndex=r-1:--v.selectedPromptIndex,wn(t);return}if(e.key===`Enter`&&(e.ctrlKey||e.metaKey)&&v.selectedPromptIndex>=0){e.preventDefault();let n=t[v.selectedPromptIndex].dataset.code;Yr(n);return}if(e.key===`Enter`&&v.selectedPromptIndex>=0){e.preventDefault();let n=t[v.selectedPromptIndex].dataset.code;bt(n);return}if(e.key===`Escape`){Mt();return}}if(e.key===`Escape`){v.inputHistoryIndex>=0&&(v.inputHistoryIndex=-1),a.value&&(a.value=``,a.style.height=`auto`,a.dispatchEvent(new Event(`input`))),e.preventDefault();return}let c=t.style.display!==`none`&&n.classList.contains(`show`),l=r.style.display!==`none`&&i.classList.contains(`show`),u=o.style.display!==`none`&&s.classList.contains(`show`);if(e.key===`ArrowUp`&&v.inputHistoryIndex===-1&&!a.value.trim()&&!xt()&&Ep()){e.preventDefault();return}if(!c&&!l&&!u){let t=rp({key:e.key,value:a.value,caret:a.selectionStart,history:v.inputHistory,index:v.inputHistoryIndex});if(t.handled){e.preventDefault(),v.inputHistoryIndex=t.index,a.value=t.value,a.dispatchEvent(new Event(`input`)),a.setSelectionRange(t.value.length,t.value.length);return}}if(e.key===`Enter`&&!e.shiftKey){if(v.isComposing)return;if(e.preventDefault(),qd(),v.isGenerating){if(e.altKey){Vt(a.value);return}Kr();return}Mi()}}),a.addEventListener(`compositionstart`,()=>{v.isComposing=!0}),a.addEventListener(`compositionend`,()=>{v.isComposing=!1}),a.addEventListener(`paste`,e=>{let t=e.clipboardData?.items;if(t)for(let n of t){if(n.type.startsWith(`image/`)&&v.enableImageInput){e.preventDefault();let t=n.getAsFile();t&&In(t);break}if(n.kind===`file`&&v.enableFileInput){e.preventDefault();let t=n.getAsFile();t&&Yi([t]);break}}});let ge=document.getElementById(`fileAttachBtn`),_e=document.getElementById(`fileInput`);ge&&_e&&(ge.addEventListener(`click`,()=>{_e.click()}),_e.addEventListener(`change`,async()=>{if(_e.files.length>0){let e=Array.from(_e.files),n=e.filter(e=>e.type.startsWith(`image/`)),r=e.filter(e=>!e.type.startsWith(`image/`));if(n.length>0)if(v.enableImageInput)for(let e of n)await In(e);else A(t(`sidePanel.imageNotEnabled`)),Yi(n);r.length>0&&Yi(r),_e.value=``}}));let ve=document.querySelector(`.input-wrapper`),ye=0;ve&&(ve.addEventListener(`dragenter`,e=>{e.preventDefault(),e.stopPropagation(),ye++,ve.classList.add(`drag-over`)}),ve.addEventListener(`dragleave`,e=>{e.preventDefault(),e.stopPropagation(),ye--,ye<=0&&(ye=0,ve.classList.remove(`drag-over`))}),ve.addEventListener(`dragover`,e=>{e.preventDefault(),e.stopPropagation()}),ve.addEventListener(`drop`,async e=>{e.preventDefault(),e.stopPropagation(),ye=0,ve.classList.remove(`drag-over`);let n=e.dataTransfer.getData(`application/x-workspace-file`);if(n){e.preventDefault();try{let{path:e}=JSON.parse(n);if(e){Si([e]);return}}catch(e){r.warn(`[SidePanel] parse workspace dragdata failed:`,e)}}let i=Array.from(e.dataTransfer.files);if(i.length>0){e.preventDefault();let n=i.filter(e=>e.type.startsWith(`image/`)),r=i.filter(e=>!e.type.startsWith(`image/`));if(n.length>0)if(v.enableImageInput)for(let e of n)await In(e);else A(t(`sidePanel.imageNotEnabled`)),Yi(n);r.length>0&&Yi(r);return}let o=e.dataTransfer.getData(`text/plain`);if(o&&(e.preventDefault(),a)){a.focus();let e=a.selectionStart??a.value.length,t=a.selectionEnd??a.value.length;a.value=a.value.slice(0,e)+o+a.value.slice(t),a.selectionStart=a.selectionEnd=e+o.length,a.dispatchEvent(new Event(`input`))}}));let be=document.getElementById(`screenshotBtn`);be&&be.addEventListener(`click`,async()=>{if(v.enableImageInput)try{await ei()}catch(e){r.error(`[SidePanel] screenshot failed:`,e),A(t(`sidePanel.screenshotFailed`))}}),kt(),a.addEventListener(`wheel`,e=>{v.isScrolling=!0;let t=a.style.height||a.offsetHeight+`px`;a.style.height=t,a.scrollHeight<=a.clientHeight+10&&(e.preventDefault(),e.stopPropagation()),setTimeout(()=>{v.isScrolling=!1},100)},{passive:!1}),a.addEventListener(`input`,e=>{let t=a.value,n=document.getElementById(`promptSelector`),r=document.getElementById(`promptDropdown`);document.getElementById(`agentAtSelector`),document.getElementById(`agentAtDropdown`);let i=t.lastIndexOf(`/`),o=t.lastIndexOf(`@`),s=t.lastIndexOf(`$`),c=e=>{if(e===-1||e!==0&&t[e-1]!==`
|
|
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-Bs34HFah.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]!==`
|
|
670
669
|
`&&t[e-1]!==` `)return!1;let n=t.substring(e+1);return!(n.includes(` `)||n.includes(`
|
|
671
|
-
`))},l=c(i),u=c(o),d=c(s),f=null;if(l&&(f={key:`slash`,index:i}),u&&(!f||o>f.index)&&(f={key:`at`,index:o}),d&&(!f||s>f.index)&&(f={key:`dollar`,index:s}),f&&f.key===`dollar`)Mt(),
|
|
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=tt();Te&&(Te.textContent=t(`header.themeToggle`,{theme:De(e)})),Ee&&Ee.querySelectorAll(`.theme-submenu-item`).forEach(t=>{t.classList.toggle(`active`,t.dataset.themeValue===e)}),we&&we.setAttribute(`aria-expanded`,String(!!(Ee&&Ee.classList.contains(`show`))))};function ke(){Ee&&Ee.classList.remove(`show`),Ce&&Ce.classList.remove(`show`),we&&we.setAttribute(`aria-expanded`,`false`)}we&&Ee&&(we.addEventListener(`click`,e=>{e.stopPropagation(),Ee.classList.toggle(`show`),Oe()}),Ee.querySelectorAll(`.theme-submenu-item`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),ct(e.dataset.themeValue),ke()})})),Oe(),mt(Oe),o(Oe),c.addEventListener(`click`,e=>{e.stopPropagation(),ke(),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`),Ke=document.getElementById(`auditLogList`),qe=[],Je={auth:t(`sidePanel.auditCategoryAuth`),fs:t(`sidePanel.auditCategoryFs`),exec:t(`sidePanel.auditCategoryExec`),security:t(`sidePanel.auditCategorySecurity`),system:t(`sidePanel.auditCategorySystem`)},Xe={info:`INFO`,warn:`WARN`,error:`ERROR`},Ze={info:`audit-level-info`,warn:`audit-level-warn`,error:`audit-level-error`};function Qe(e){if(!e)return`-`;let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())} ${n(t.getHours())}:${n(t.getMinutes())}:${n(t.getSeconds())}`}function $e(e){let n=new Set([`timestamp`,`level`,`category`,`action`]),r=[];for(let[t,i]of Object.entries(e)){if(n.has(t))continue;let e=typeof i==`string`?i:JSON.stringify(i),a=e.length>60?e.slice(0,60)+`...`:e;r.push(`${t}: ${a}`)}return r.join(t(`sidePanel.auditDetailSeparator`))}async function et(){if(!Ue||!We||!Ke)return;Ue.style.display=`block`,We.style.display=`none`,Ke.style.display=`none`;let e=ze?.value||null,n=parseInt(Be?.value||`200`,10);try{let r=await new Promise((t,r)=>{chrome.runtime.sendMessage({type:`QUERY_AUDIT_LOGS`,category:e,limit:n},e=>{chrome.runtime.lastError?r(Error(chrome.runtime.lastError.message)):t(e)})});if(Ue.style.display=`none`,!r||!r.success){We.style.display=`block`,We.textContent=t(`sidePanel.auditQueryFailed`,{error:r?.error||t(`sidePanel.unknownError`)});return}qe=r.entries||[],rt()}catch(e){Ue.style.display=`none`,We.style.display=`block`,We.textContent=t(`sidePanel.auditLoadFailed`,{error:e.message})}}function rt(){if(!Ke)return;let e=(Ve?.value||``).trim().toLowerCase(),n=qe;if(e&&(n=n.filter(t=>[t.action||``,t.category||``,...Object.entries(t).filter(([e])=>![`timestamp`,`level`,`category`,`action`].includes(e)).map(([,e])=>typeof e==`string`?e:JSON.stringify(e))].join(` `).toLowerCase().includes(e))),He&&(He.style.display=e?`block`:`none`),Ue.style.display=`none`,n.length===0){We.style.display=`block`,We.textContent=t(e?`sidePanel.auditNoMatch`:`sidePanel.auditEmpty`),Ke.style.display=`none`;return}We.style.display=`none`,Ke.style.display=`block`,Ke.innerHTML=n.map(e=>{let t=k(Je[e.category]||e.category||`-`),n=k(Xe[e.level]||e.level?.toUpperCase()||`INFO`),r=Ze[e.level]||`audit-level-info`,i=Qe(e.timestamp),a=k($e(e));return`<div class="audit-entry">
|
|
672
671
|
<div class="audit-entry-header">
|
|
673
672
|
<span class="audit-time">${i}</span>
|
|
674
673
|
<span class="audit-level ${r}">${n}</span>
|
|
@@ -676,7 +675,7 @@ Are you sure you want to stop the agent service? You will not be able to connect
|
|
|
676
675
|
<span class="audit-action">${k(e.action||`-`)}</span>
|
|
677
676
|
</div>
|
|
678
677
|
${a?`<div class="audit-details">${a}</div>`:``}
|
|
679
|
-
</div>`}).join(``)}function it(){Ie&&(Ie.style.display=`flex`,et())}function at(){Ie&&(Ie.style.display=`none`)}Fe&&Fe.addEventListener(`click`,e=>{e.stopPropagation(),ke(),it()}),Le&&Le.addEventListener(`click`,at),Re&&Re.addEventListener(`click`,et),ze&&ze.addEventListener(`change`,et),Be&&Be.addEventListener(`change`,et),Ve&&Ve.addEventListener(`input`,()=>{rt()}),He&&He.addEventListener(`click`,()=>{Ve&&(Ve.value=``),rt()}),
|
|
678
|
+
</div>`}).join(``)}function it(){Ie&&(Ie.style.display=`flex`,et())}function at(){Ie&&(Ie.style.display=`none`)}Fe&&Fe.addEventListener(`click`,e=>{e.stopPropagation(),ke(),it()}),Le&&Le.addEventListener(`click`,at),Re&&Re.addEventListener(`click`,et),ze&&ze.addEventListener(`change`,et),Be&&Be.addEventListener(`change`,et),Ve&&Ve.addEventListener(`input`,()=>{rt()}),He&&He.addEventListener(`click`,()=>{Ve&&(Ve.value=``),rt()}),bm(()=>v.activeSessionId,window.showCustomConfirm);let lt=document.getElementById(`isolateChatBtn`),j=document.getElementById(`enableToolsBtn`),ut=document.getElementById(`toolsConfigBtn`),ft=`agentEnabledTools_${v.activeAgentId||`default`}`,pt=`agentMcpClosedServers_${v.activeAgentId||`default`}`;chrome.storage.local.get([ft,`enabledTools`,`isolateChat`,`enableSelectionQuery`,`enableTools`,pt,`mcpTools`,`mcpEnabled`,`ragTools`,`ragToolsIntroduced`],e=>{e.isolateChat!==void 0&&(v.isolateChat=e.isolateChat),lt.checked=v.isolateChat,e.enableSelectionQuery!==void 0&&(v.enableSelectionQuery=e.enableSelectionQuery);let t=document.getElementById(`enableSelectionQueryBtn`);t&&(t.checked=v.enableSelectionQuery),e.enableTools!==void 0&&(v.useTools=e.enableTools),v.activeAgentId&&E(async()=>{let{getAgent:e}=await import(`./agent-store-QTeMyM9O.js`).then(e=>e.t);return{getAgent:e}},__vite__mapDeps([5,1,2,3])).then(({getAgent:e})=>e(v.activeAgentId)).then(e=>{v.activeAgentMcpExcludedServerIds=e?e.mcpExcludedServerIds??null:null,Zi()}).catch(()=>{}),v.mcpClosedServers=e[pt]||[];let n=e.ragTools||[],r=e[ft],i=e.enabledTools;if(Array.isArray(r)){let t=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,[ft]:v.enabledTools}):v.enabledTools.length!==r.length&&chrome.storage.local.set({[ft]: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({[ft]: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,[ft]:v.enabledTools})}j&&(j.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()}),j&&j.addEventListener(`change`,()=>{v.useTools=j.checked,chrome.storage.local.set({enableTools:v.useTools}),r.debug(`[SidePanel] tool master switch:`,v.useTools?`enabled`:`disabled`),Zi()}),ut&&ut.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),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="${k(l[e]||e)}" style="padding: 3px 10px; background: var(--bg-subtle); color: var(--text-disabled); border: 1px solid var(--border-subtle); border-radius: 4px; font-size: 11px;">${e}</code>`).join(``),s.style.display=``),i.style.display=`none`,e.style.display=``}catch(e){r.error(`[SidePanel] loadstats failed:`,e),i.style.display=`none`,a.textContent=t(`sidePanel.toolStatsLoadFailed`),a.style.display=``}}}function 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=nt(i);return`<tr>
|
|
680
679
|
<td style="padding: 6px 10px; border-bottom: 1px solid var(--border-subtle); color: var(--text-primary);"><code title="${k(a)}">${e}</code></td>
|
|
681
680
|
<td style="padding: 6px 10px; text-align: right; border-bottom: 1px solid var(--border-subtle); color: var(--text-secondary);">${n.callCount}</td>
|
|
682
681
|
<td style="padding: 6px 10px; text-align: right; border-bottom: 1px solid var(--border-subtle); color: var(--text-secondary);">${n.successCount}</td>
|
|
@@ -687,4 +686,4 @@ Are you sure you want to stop the agent service? You will not be able to connect
|
|
|
687
686
|
<span style="font-size: 12px; color: ${o}; font-weight: 500;">${r.toFixed(0)}%</span>
|
|
688
687
|
</td>
|
|
689
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>
|
|
690
|
-
</tr>`}).join(``),
|
|
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`,()=>{})}),Je().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-Bs34HFah.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-Bs34HFah.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`)}})});
|