ai-helper-agent 2.7.6 → 2.7.7
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/README.md +1 -1
- package/README.zh-CN.md +1 -1
- package/bin/agent.js +20 -31
- package/dist/assets/{agent-store-1fyaAv9T.js → agent-store-CXWql6bl.js} +1 -1
- package/dist/assets/background.js +1 -1
- package/dist/assets/{chat-export-CmaDpmwW.js → chat-export-CDzJ0eSb.js} +1 -1
- package/dist/assets/content.js +2 -2
- package/dist/assets/{i18n-DQnIL9xy.js → i18n-Cy3JvhaK.js} +2 -2
- package/dist/assets/markdown-render-D1Pi8x7U.js +61 -0
- package/dist/assets/{model-profiles-D31rvEiY.js → model-profiles-DmaxlVkA.js} +1 -1
- package/dist/assets/{options-d_q5bb5y.css → options-CM9dPi9P.css} +1 -1
- package/dist/assets/options.js +92 -88
- package/dist/assets/{page-snapshot-renderer-B9y0q0s6.js → page-snapshot-renderer-WxUYrhBW.js} +1 -1
- package/dist/assets/{session-store-xr0nYACs.js → session-store-DKG2vsne.js} +3 -3
- package/dist/assets/side_panel.css +1 -1
- package/dist/assets/side_panel.js +149 -142
- package/dist/assets/{utils-DVhZvlZX.js → utils-7ghENN5I.js} +1 -1
- package/dist/assets/version-D_r0xXpL.js +3 -0
- package/dist/assets/{workspace-manager-DfSFPqwp.js → workspace-manager-CZeD2gWf.js} +1 -1
- package/dist/manifest.json +1 -1
- package/dist/offscreen/offscreen.js +2 -2
- package/dist/options.html +6 -4
- package/dist/side_panel.html +11 -13
- package/package.json +1 -1
- package/src/autostart.js +206 -0
- package/src/locales/cli.json +8 -2
- package/dist/assets/markdown-render-CDJ7FW_o.js +0 -63
- package/dist/assets/version-CHQCdVOZ.js +0 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/agent-store-
|
|
2
|
-
import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,i,l as a,n as o,r as s,s as c}from"./i18n-
|
|
3
|
-
...[历史摘要已截断]`:e)}return{messages:[...h,o],keptHistory:h,compactionApplied:c,trimmedCount:y,historySummaryText:_}}function Un(e,t){return!t||!t.summary?e:`${e}\n\n${r(`contextUsage.compactionInjection`,{count:t.compressedCount||0})}\n${t.summary}`}function Wn(e,t,n,r){return t?.compactionApplied&&n?.summary?e[0]={...e[0],content:Un(e[0].content,n)}:n?.summary&&r?.warn(`[SidePanel] contextCompaction invalid (upToMessageId not found), ignored this send`),e}function Gn({model:e,customModelMap:t=null,systemPromptText:n=``,toolCount:r=0,history:i=[],inputText:a=``,maxMemoryMessages:o=null,compaction:s=null,isolateChat:c=!0,userConfiguredWindow:l=0}={}){let d=g(e,l,t),p=d-f(n)-y-zn,m=Math.floor(Math.max(p,0)*Bn),h={role:`user`,content:a},_=c?s:null,v=Hn(i,{isolateChat:c,maxMemoryMessages:o,compaction:_,historyBudget:m,currentMessage:h}),x=f(v.compactionApplied?Un(n,_):n),S=r*200,C=b(v.keptHistory),w=a&&a.trim()?b([h]):0,T=x+S+C+w,E=u(T,d);return{usedTokens:T,contextWindow:d,ratio:d>0?T/d:0,level:E.level,breakdown:{system:x,tools:S,history:C,input:w,outputReserve:y,safetyMargin:zn,selectedCount:v.keptHistory.length,totalCount:i.length,trimmedCount:v.trimmedCount,compactionApplied:v.compactionApplied,compactionInvalid:!!(_&&_.summary&&!v.compactionApplied),historyBudget:m}}}function Kn(e,{maxMemoryMessages:t=null,compaction:n=null}={}){let r=Hn(e,{isolateChat:!0,maxMemoryMessages:t,compaction:n,historyBudget:1/0,currentMessage:null}),i=[],a=!!(r.compactionApplied&&n?.summary);a&&i.push({role:`user`,content:`【已有摘要】\n${n.summary}`});for(let e of r.keptHistory){let t=v(e.content);i.push({role:e.role,content:typeof t==`string`?t:JSON.stringify(t??``)||``})}return{material:i,includedCount:r.keptHistory.length,hasOldSummary:a}}function qn(e){if(!e||!e.trim()||e.trim()==`/`)return;let t=e.trim(),n=N.inputHistory.indexOf(t);n!==-1&&N.inputHistory.splice(n,1),N.inputHistory.push(t),N.inputHistory.length>20&&N.inputHistory.shift(),Jn()}function Jn(){try{chrome.storage.local.set({inputHistory:N.inputHistory}),a.debug(`[SidePanel] input history saved,count:`,N.inputHistory.length)}catch(e){a.error(`[SidePanel] saveinput history failed:`,e)}}var Yn=[`workspace`,`bookmark`,`toc`,`search`,`todo`,`schedule`],Xn=`.workspace-panel.expanded, .bookmark-panel.expanded, .message-toc-panel.expanded, .search-panel.expanded, .schedule-panel.open`,Zn=null,Qn=null;function $n(){if(Zn)return Zn;Zn=document.createElement(`div`),Zn.className=`side-rail`,Zn.id=`sideRail`,Zn.innerHTML=Yn.map(e=>`<div class="side-rail-slot" data-slot="${e}"></div>`).join(``),document.body.appendChild(Zn),tr();let e=document.getElementById(`chatContainer`);return e&&typeof ResizeObserver<`u`&&new ResizeObserver(tr).observe(e),window.addEventListener(`resize`,tr),Zn}function er(e){return(Zn||$n()).querySelector(`.side-rail-slot[data-slot="${e}"]`)}function tr(){if(!Zn)return;let e=document.getElementById(`chatContainer`);if(!e)return;let t=e.getBoundingClientRect(),n=window.innerHeight;Zn.style.top=`${Math.max(0,Math.round(t.top))}px`,Zn.style.bottom=`${Math.max(0,Math.round(n-t.bottom))}px`,nr()}function nr(){Qn&&clearTimeout(Qn),Qn=setTimeout(()=>{Qn=null,document.querySelectorAll(Xn).forEach(
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/agent-store-CXWql6bl.js","assets/chunk-CMxvf4Kt.js","assets/session-store-DKG2vsne.js","assets/model-profiles-DmaxlVkA.js","assets/i18n-Cy3JvhaK.js","assets/pdf-DnVqBaAN.js","assets/__vite-browser-external-CM3Eme-n.js","assets/lib-YwkWjNcC.js","assets/jszip.min-DO6SOhXU.js","assets/dist-DuuG_8Br.js","assets/chat-export-CDzJ0eSb.js","assets/dist-BUuoW_84.js","assets/markdown-render-D1Pi8x7U.js","assets/version-D_r0xXpL.js","assets/utils-7ghENN5I.js","assets/workspace-manager-CZeD2gWf.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,i,l as a,n as o,r as s,s as c}from"./i18n-Cy3JvhaK.js";import{A as l,C as u,D as d,E as f,F as p,G as m,I as h,N as g,P as _,R as v,S as y,T as b,W as x,b as S,c as C,d as w,i as T,k as E,r as D,u as O,w as k,y as A,z as j}from"./model-profiles-DmaxlVkA.js";import{A as ee,At as te,C as ne,D as re,E as ie,Et as ae,F as oe,G as se,Ht as ce,Kt as le,Lt as ue,M as de,N as M,Nt as fe,O as pe,Ot as me,P as he,Pt as ge,Rt as _e,S as ve,T as ye,Tt as be,Ut as xe,Vt as Se,Xt as Ce,Yt as we,_ as Te,a as Ee,an as De,b as N,c as Oe,d as ke,dt as Ae,en as je,f as Me,ft as Ne,h as Pe,ht as Fe,j as Ie,k as Le,l as Re,lt as ze,m as Be,mt as Ve,n as He,nn as Ue,o as We,on as Ge,p as Ke,pt as qe,r as Je,rn as Ye,s as Xe,t as Ze,tn as Qe,u as $e,un as et,ut as tt,v as nt,w as rt,x as it,y as at}from"./session-store-DKG2vsne.js";import{a as ot,n as st,r as ct,t as lt}from"./voice-shortcut-Dtt3nhkz.js";import{d as ut,f as dt,i as ft,l as pt,m as mt,n as ht,p as gt,t as _t}from"./version-D_r0xXpL.js";import{a as vt,c as yt,i as bt,n as xt,o as St,r as Ct,s as wt}from"./agent-store-CXWql6bl.js";import{C as Tt,E as Et,S as Dt,T as Ot,_ as kt,a as At,b as jt,c as P,d as Mt,f as Nt,g as Pt,h as Ft,i as It,l as Lt,m as F,n as Rt,o as zt,p as Bt,r as Vt,s as I,t as Ht,u as Ut,v as Wt,w as L,x as Gt,y as Kt}from"./utils-7ghENN5I.js";import{a as qt,c as Jt,d as Yt,f as Xt,h as Zt,i as Qt,l as $t,m as en,n as tn,o as nn,p as rn,r as an,s as on,t as sn,u as cn}from"./markdown-render-D1Pi8x7U.js";import{C as ln,E as un,O as dn,S as fn,T as pn,_ as mn,a as hn,b as gn,c as _n,d as vn,f as yn,g as bn,h as xn,i as Sn,l as Cn,m as wn,n as Tn,o as En,p as Dn,r as On,s as kn,t as An,u as jn,v as Mn,w as Nn,x as Pn,y as Fn}from"./workspace-manager-CZeD2gWf.js";var In=he.map(e=>e.id),Ln=[...new Set([...m,`mcp`,`knowledge`])],Rn=[{labelKey:`presetMode.preciseLabel`,tipKey:`presetMode.preciseTip`,temp:.2,topP:1},{labelKey:`presetMode.generalLabel`,tipKey:`presetMode.generalTip`,temp:.45,topP:.9},{labelKey:`presetMode.divergentLabel`,tipKey:`presetMode.divergentTip`,temp:.65,topP:.9},{labelKey:`presetMode.creativeLabel`,tipKey:`presetMode.creativeTip`,temp:.9,topP:.9}];n(`zh`,{contextUsage:{compactionInjection:`[上下文摘要|压缩了{count}条历史]`}}),n(`en`,{contextUsage:{compactionInjection:`[Context Summary | {count} messages compacted]`}});var zn=2e3,Bn=.7,Vn=1e3;function Hn(e,{isolateChat:t=!0,maxMemoryMessages:n=null,compaction:r=null,historyBudget:i=1/0,currentMessage:a=null}={}){let o=a||{role:`user`,content:``};if(!t)return{messages:[o],keptHistory:[],compactionApplied:!1,trimmedCount:0,historySummaryText:null};let s=Array.isArray(e)?e:[],c=!1,u=-1;r&&r.summary&&r.upToMessageId&&(u=s.findIndex(e=>e.messageId===r.upToMessageId),c=u>=0);let d=s,p=s.map((e,t)=>t);n&&n>0&&s.length>n&&(d=s.slice(s.length-n),p=p.slice(s.length-n));let m=[];for(let e=0;e<d.length;e++)c&&p[e]<=u||m.push(d[e]);let h=[],g=b([o]);for(let e=m.length-1;e>=0;e--){let t=m[e],n=b([{...t,content:v(t.content)}]);if(g+n<=i)h.unshift(t),g+=n;else break}let _=null,y=m.length-h.length;if(y>0){let e=l(m.slice(0,y));e&&(_=f(e)>Vn?e.substring(0,Vn*4)+`
|
|
3
|
+
...[历史摘要已截断]`:e)}return{messages:[...h,o],keptHistory:h,compactionApplied:c,trimmedCount:y,historySummaryText:_}}function Un(e,t){return!t||!t.summary?e:`${e}\n\n${r(`contextUsage.compactionInjection`,{count:t.compressedCount||0})}\n${t.summary}`}function Wn(e,t,n,r){return t?.compactionApplied&&n?.summary?e[0]={...e[0],content:Un(e[0].content,n)}:n?.summary&&r?.warn(`[SidePanel] contextCompaction invalid (upToMessageId not found), ignored this send`),e}function Gn({model:e,customModelMap:t=null,systemPromptText:n=``,toolCount:r=0,history:i=[],inputText:a=``,maxMemoryMessages:o=null,compaction:s=null,isolateChat:c=!0,userConfiguredWindow:l=0}={}){let d=g(e,l,t),p=d-f(n)-y-zn,m=Math.floor(Math.max(p,0)*Bn),h={role:`user`,content:a},_=c?s:null,v=Hn(i,{isolateChat:c,maxMemoryMessages:o,compaction:_,historyBudget:m,currentMessage:h}),x=f(v.compactionApplied?Un(n,_):n),S=r*200,C=b(v.keptHistory),w=a&&a.trim()?b([h]):0,T=x+S+C+w,E=u(T,d);return{usedTokens:T,contextWindow:d,ratio:d>0?T/d:0,level:E.level,breakdown:{system:x,tools:S,history:C,input:w,outputReserve:y,safetyMargin:zn,selectedCount:v.keptHistory.length,totalCount:i.length,trimmedCount:v.trimmedCount,compactionApplied:v.compactionApplied,compactionInvalid:!!(_&&_.summary&&!v.compactionApplied),historyBudget:m}}}function Kn(e,{maxMemoryMessages:t=null,compaction:n=null}={}){let r=Hn(e,{isolateChat:!0,maxMemoryMessages:t,compaction:n,historyBudget:1/0,currentMessage:null}),i=[],a=!!(r.compactionApplied&&n?.summary);a&&i.push({role:`user`,content:`【已有摘要】\n${n.summary}`});for(let e of r.keptHistory){let t=v(e.content);i.push({role:e.role,content:typeof t==`string`?t:JSON.stringify(t??``)||``})}return{material:i,includedCount:r.keptHistory.length,hasOldSummary:a}}function qn(e){if(!e||!e.trim()||e.trim()==`/`)return;let t=e.trim(),n=N.inputHistory.indexOf(t);n!==-1&&N.inputHistory.splice(n,1),N.inputHistory.push(t),N.inputHistory.length>20&&N.inputHistory.shift(),Jn()}function Jn(){try{chrome.storage.local.set({inputHistory:N.inputHistory}),a.debug(`[SidePanel] input history saved,count:`,N.inputHistory.length)}catch(e){a.error(`[SidePanel] saveinput history failed:`,e)}}var Yn=[`workspace`,`bookmark`,`toc`,`search`,`todo`,`schedule`],Xn=`.workspace-panel.expanded, .bookmark-panel.expanded, .message-toc-panel.expanded, .search-panel.expanded, .schedule-panel.open`,Zn=null,Qn=null;function $n(){if(Zn)return Zn;Zn=document.createElement(`div`),Zn.className=`side-rail`,Zn.id=`sideRail`,Zn.innerHTML=Yn.map(e=>`<div class="side-rail-slot" data-slot="${e}"></div>`).join(``),document.body.appendChild(Zn),tr();let e=document.getElementById(`chatContainer`);return e&&typeof ResizeObserver<`u`&&new ResizeObserver(tr).observe(e),window.addEventListener(`resize`,tr),Zn}function er(e){return(Zn||$n()).querySelector(`.side-rail-slot[data-slot="${e}"]`)}function tr(){if(!Zn)return;let e=document.getElementById(`chatContainer`);if(!e)return;let t=e.getBoundingClientRect(),n=window.innerHeight;Zn.style.top=`${Math.max(0,Math.round(t.top))}px`,Zn.style.bottom=`${Math.max(0,Math.round(n-t.bottom))}px`,nr()}function nr(){Qn&&clearTimeout(Qn),Qn=setTimeout(()=>{Qn=null,document.querySelectorAll(Xn).forEach(It)},120)}n(`zh`,{messageToc:{toggleTitle:`显示目录(H{count}个标题)`,title:`目录`,headingCount:`{count} 个`,lock:`锁定目录(不自动收起)`,unlock:`解锁目录`,close:`关闭目录`}}),n(`en`,{messageToc:{toggleTitle:`Show table of contents (H{count} headings)`,title:`Contents`,headingCount:`{count}`,lock:`Pin table of contents`,unlock:`Unpin table of contents`,close:`Close table of contents`}});var rr=`messageTocLocked`,ir=!1,ar=`<svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 9.9-1"/></svg>`,or=`<svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>`;function sr(e){e&&(e.innerHTML=ir?or:ar,e.title=r(ir?`messageToc.unlock`:`messageToc.lock`),e.classList.toggle(`locked`,ir))}function cr(){try{let e=chrome.storage?.local?.set?.({[rr]:ir});e&&typeof e.catch==`function`&&e.catch(()=>{})}catch{}}function lr(){document.addEventListener(`mouseover`,ur,!0),document.addEventListener(`mouseout`,dr,!0);try{let e=chrome.storage?.local?.get?.(rr);e&&typeof e.then==`function`?e.then(e=>{ir=!!(e&&e[rr])}).catch(()=>{}):e&&typeof e==`object`&&(ir=!!e[rr])}catch{}a.debug(`[SidePanel] messagedirectory featureinitializing`)}function ur(e){if(!(e.target instanceof Element))return;if(e.target.closest(`.message-toc-container`)){N.isMouseOverToc=!0;return}let t=e.target.closest(`.message.assistant`),n=e.target.closest(`.workspace-preview-markdown`);if(!t&&!n)return;let r=t||n,i=r.querySelectorAll(`.markdown-body h1, .markdown-body h2, .markdown-body h3, .markdown-body h4, .markdown-body h5, .markdown-body h6`);if(i.length===0){ir||pr();return}fr(r,i)}function dr(e){if(!(e.target instanceof Element))return;if(e.target.closest(`.message-toc-container`)){N.isMouseOverToc=!1,N.tocHideTimer&&=(clearTimeout(N.tocHideTimer),null);return}let t=e.target.closest(`.message.assistant`),n=e.target.closest(`.workspace-preview-markdown`);if(!t&&!n||ir)return;let r=e.relatedTarget;r&&(r.closest(`.message-toc-container`)||r.closest(`.message.assistant`)||r.closest(`.workspace-preview-markdown`))||N.isMouseOverToc||(N.tocHideTimer&&clearTimeout(N.tocHideTimer),N.tocHideTimer=setTimeout(()=>{N.isMouseOverToc||pr(),N.tocHideTimer=null},800))}function fr(e,t){let n=Array.from(t);N.messageTocContainer&&pr(),n.forEach((e,t)=>{e.id||=`toc-heading-${Date.now()}-${t}`});let i=document.createElement(`div`);i.className=`message-toc-container`,i.dataset.headingsCount=n.length;let a=0,o=n.map(e=>{let t=parseInt(e.tagName.charAt(1)),n=e.textContent.trim(),r=n.length>30?n.substring(0,30)+`...`:n,i=`H${t}`;return a++,`
|
|
4
4
|
<li class="message-toc-item level-${t}"
|
|
5
5
|
data-target="${e.id}"
|
|
6
6
|
data-anchor="${i}"
|
|
@@ -26,7 +26,7 @@ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,i,l as a,n a
|
|
|
26
26
|
</ul>
|
|
27
27
|
</div>
|
|
28
28
|
</div>
|
|
29
|
-
`;let s=e.closest(`.message-fullscreen-overlay`),c=e.closest(`.workspace-preview-overlay.fullscreen`);(s?s.querySelector(`.message-fullscreen-rail`)||er(`toc`):c&&c.querySelector(`.workspace-preview-rail`)||er(`toc`)).appendChild(i),N.messageTocContainer=i;let l=i.querySelector(`.message-toc-toggle`),u=i.querySelector(`.message-toc-panel`);ir&&(u.classList.add(`expanded`,`locked`),Ft(u));let d=i.querySelector(`.message-toc-lock`);d.addEventListener(`click`,e=>{e.stopPropagation(),ir=!ir,cr(),sr(d),ir?(u.classList.add(`expanded`,`locked`),Ft(u)):u.classList.remove(`locked`)}),i.querySelector(`.message-toc-close`).addEventListener(`click`,e=>{e.stopPropagation(),ir&&(ir=!1,cr()),pr()}),l.addEventListener(`mouseenter`,()=>{u.classList.add(`expanded`),Ft(u)}),l.addEventListener(`click`,()=>{u.classList.toggle(`expanded`)?Ft(u):Wt(u)}),u.addEventListener(`mouseenter`,()=>{u.classList.add(`expanded`)}),i.querySelectorAll(`.message-toc-item`).forEach(e=>{e.addEventListener(`click`,()=>{let t=e.dataset.target,n=document.getElementById(t);n&&(n.scrollIntoView({behavior:`smooth`,block:`start`}),n.classList.add(`toc-highlight`),setTimeout(()=>{n.classList.remove(`toc-highlight`)},1500))})})}function pr(){N.tocHideTimer&&=(clearTimeout(N.tocHideTimer),null),N.messageTocContainer&&=(N.messageTocContainer.remove(),null)}var mr=`promptQueues`,hr=1,gr=30*1e3,_r=15*1e3,vr=20,R={QUEUED:`queued`,DISPATCHING:`dispatching`,INJECTING:`injecting`,INJECTED:`injected`,DONE:`done`,FAILED:`failed`};new Set([R.INJECTED,R.DONE,R.FAILED]);var yr={async get(e){let t=await chrome.storage.local.get(e);return t?t[e]:void 0},async set(e){await chrome.storage.local.set(e)}};function br(){return{version:hr,sessions:{}}}var z=br(),xr=!1,Sr=null,Cr=!1,wr=``,Tr=new Set,Er=new Set;function Dr(){return{items:[],recent:[],paused:!1,pausedReason:null}}function Or(e){return e?(z.sessions[e]||(z.sessions[e]=Dr()),z.sessions[e]):Dr()}function kr(){return JSON.stringify(z)}function Ar(e,t){for(let n of Er)try{n(e,t)}catch(e){a.error(`[QueueStore] listener failed:`,e?.message)}}function jr(){return typeof crypto<`u`&&typeof crypto.randomUUID==`function`?`q_`+crypto.randomUUID():`q_`+Date.now().toString(36)+`_`+Math.random().toString(36).slice(2,8)}function Mr(e){return e.reduce((e,t)=>Math.max(e,Number(t.order)||0),0)+1}function Nr(e,t){let n=e.indexOf(t);n<0||(e.splice(n,1),e.unshift(t),Pr(e))}function Pr(e){e.forEach((e,t)=>{e.order=t+1})}function Fr(e){return e.slice().sort((e,t)=>(Number(e.order)||0)-(Number(t.order)||0))}async function Ir(e){if(Cr)return a.error(`[QueueStore] persist skipped in degraded mode:`,e),!1;let t=kr();wr=t,Lr(t);try{await yr.set({[mr]:z})}catch(e){a.error(`[QueueStore] persist failed:`,e?.message)}Ar(e)}function Lr(e){if(Tr.add(e),Tr.size<=vr)return;let t=Tr.values().next().value;Tr.delete(t)}function Rr(e,{recoverInterrupted:t=!0}={}){let n=br();if(!e||typeof e!=`object`)return n;let r=e.sessions&&typeof e.sessions==`object`?e.sessions:{};for(let[e,i]of Object.entries(r)){let r=Array.isArray(i?.items)?i.items:[],a=Array.isArray(i?.recent)?i.recent.slice(0,30):[],o=!1;for(let e of r)!e||typeof e!=`object`||t&&(e.status===R.DISPATCHING||e.status===R.INJECTING)&&(e.status=R.QUEUED,e.interrupted=!0,e.previousStatus=e.previousStatus||R.DISPATCHING,e.leaseOwner=null,e.leaseUntil=0,o=!0);let s=Fr(r);if(o){let e=s.filter(e=>e.interrupted),t=s.filter(e=>!e.interrupted);s.splice(0,s.length,...e,...t)}Pr(s);let c=s.slice(0,20),l=s.slice(20);for(let e of l.reverse())a.unshift(si({...e,status:R.FAILED,lastError:`over_limit`}));n.sessions[e]={items:c,recent:a.slice(0,30),paused:i?.paused===!0,pausedReason:i?.pausedReason||null}}return n}function zr(){return Cr}async function Br(){return xr?z:Sr||(Sr=(async()=>{let e;try{e=await yr.get(mr)}catch(e){return Cr=!0,Sr=null,a.error(`[QueueStore] load failed, enter degraded mode:`,e?.message),z}return z=Rr(e),xr=!0,Cr=!1,wr=kr(),z})(),Sr)}function Vr(){typeof chrome>`u`||!chrome.storage?.onChanged?.addListener||chrome.storage.onChanged.addListener((e,t)=>{if(t!==`local`||!e?.[mr])return;let n=e[mr].newValue;if(!n)return;let r=JSON.stringify(n);Tr.has(r)||r===wr||(z=Rr(n,{recoverInterrupted:!1}),xr=!0,wr=r,Ar(`external`,null))})}function Hr(e){return typeof e==`function`?(Er.add(e),()=>Er.delete(e)):()=>{}}function Ur(e){let t=z.sessions[e];return t?Fr(t.items):[]}function Wr(e,t=30){let n=z.sessions[e];return n?n.recent.slice(0,t):[]}function Gr(e){let t=z.sessions[e];return t?{items:Fr(t.items),recent:t.recent.slice(),paused:t.paused===!0,pausedReason:t.pausedReason||null}:Dr()}function Kr(e){return Ur(e).filter(e=>e.status===R.QUEUED).length}function qr(e){return Ur(e).find(e=>e.status===R.QUEUED)||null}function Jr(e){let t=z.sessions[e];if(!t)return null;for(let e=t.items.length-1;e>=0;--e)if(t.items[e].status===R.QUEUED)return t.items[e];return null}function Yr(e,t){let n=z.sessions[e];return n&&n.items.find(e=>e.id===t)||null}function Xr(){return Object.keys(z.sessions).filter(e=>(z.sessions[e]?.items?.length||0)>0)}function Zr(e){return z.sessions[e]?.paused===!0}async function Qr({sessionId:e,text:t,contextSnapshot:n=null,hasContext:r=!1,attachmentSummary:i=null,source:a=`manual`}){if(!e)return{ok:!1,error:`missing_session`};let o=String(t||``).trim();if(!o)return{ok:!1,error:`empty`};if(await Br(),Cr)return{ok:!1,error:`storage_unavailable`};let s=Or(e);if(s.items.length>=20)return{ok:!1,error:`queue_full`,limit:20};let c={id:jr(),sessionId:e,text:o,contextSnapshot:n||null,attachmentSummary:i||null,hasContext:r===!0,status:R.QUEUED,order:Mr(s.items),createdAt:Date.now(),updatedAt:Date.now(),attempts:0,lastError:null,source:a,interrupted:!1,leaseOwner:null,leaseUntil:0,injectRequestedAt:0,injectDeadlineAt:0,injectedIntoCallId:null,absorbedIteration:null};return s.items.push(c),await Ir(`enqueue`),{ok:!0,item:c,position:s.items.length}}async function $r(e,t){let n=z.sessions[e];if(!n)return!1;let r=n.items.findIndex(e=>e.id===t);return r<0?!1:(n.items.splice(r,1),Pr(n.items),await Ir(`remove`),!0)}async function ei(e,t){let n=z.sessions[e];if(!n||!Array.isArray(t))return!1;let r=new Map(n.items.map(e=>[e.id,e])),i=[];for(let e of t){let t=r.get(e);t&&!i.includes(t)&&i.push(t)}for(let e of Fr(n.items))i.includes(e)||i.push(e);return n.items=i,Pr(n.items),await Ir(`reorder`),!0}async function ti(e,t,n,r={}){let i=Yr(e,t);return i?(i.status=n,Object.assign(i,r,{updatedAt:Date.now()}),await Ir(`status`),!0):!1}async function ni(e,t,n=_r){let r=Yr(e,t);return r?(r.previousStatus=r.status,r.status=R.INJECTING,r.injectRequestedAt=Date.now(),r.injectDeadlineAt=Date.now()+n,r.updatedAt=Date.now(),await Ir(`inject:request`),!0):!1}async function ri(e,t,n=`error`,r=null){let i=z.sessions[e];if(!i)return!1;let a=i.items.find(e=>e.id===t);return a?(a.status=R.QUEUED,a.injectDeadlineAt=0,a.updatedAt=Date.now(),a.lastError=r||n,a.rollbackReason=n,Nr(i.items,a),await Ir(`inject:rollback`),!0):!1}async function ii(e,t,{status:n,note:r=null,callId:i=null,iteration:a=null}={}){let o=z.sessions[e];if(!o)return!1;let s=o.items.findIndex(e=>e.id===t);if(s<0)return!1;let[c]=o.items.splice(s,1);return Pr(o.items),c.status=n||R.DONE,c.settledAt=Date.now(),c.settleNote=r,i&&(c.injectedIntoCallId=i),a!=null&&(c.absorbedIteration=a),o.recent.unshift(si(c)),o.recent=o.recent.slice(0,30),await Ir(`settle`),!0}async function ai(e,t){let n=z.sessions[e];if(!n)return{ok:!1,error:`missing_session`};let r=n.recent.findIndex(e=>e.id===t);if(r<0)return{ok:!1,error:`not_found`};if(n.items.length>=20)return{ok:!1,error:`queue_full`,limit:20};let[i]=n.recent.splice(r,1),a={...i,status:R.QUEUED,order:Mr(n.items),attempts:0,lastError:null,interrupted:!1,rollbackReason:null,settledAt:null,leaseOwner:null,leaseUntil:0,injectDeadlineAt:0,updatedAt:Date.now()};return n.items.push(a),await Ir(`requeue`),{ok:!0,item:a}}async function oi(e,t){let n=z.sessions[e];if(!n)return!1;let r=n.recent.findIndex(e=>e.id===t);return r<0?!1:(n.recent.splice(r,1),await Ir(`recent-remove`),!0)}function si(e){let{leaseOwner:t,leaseUntil:n,injectDeadlineAt:r,contextSnapshot:i,...a}=e;return{...a,hasContext:e.hasContext===!0,contextDropped:!!i}}async function ci(e,t=`user_stopped`){let n=Or(e);return n.paused?!1:(n.paused=!0,n.pausedReason=t,await Ir(`pause`),!0)}async function li(e){let t=z.sessions[e];return!t||!t.paused?!1:(t.paused=!1,t.pausedReason=null,await Ir(`resume`),!0)}async function ui(e,t,n){let r=Yr(e,t);if(!r)return!1;let i=Date.now();return r.leaseOwner&&r.leaseOwner!==n&&Number(r.leaseUntil)>i?!1:(r.leaseOwner=n,r.leaseUntil=i+gr,await Ir(`lease`),!0)}async function di(e){let t=z.sessions[e];if(!t)return 0;let n=t.items.length+t.recent.length;return delete z.sessions[e],n>0&&await Ir(`drop-session`),n}var fi=`ai-helper-queue-attachments`,pi=1,mi=`attachments`,hi=null,gi=null;function _i(){return new Promise((e,t)=>{let n=indexedDB.open(fi,pi);n.onupgradeneeded=e=>{let t=e.target.result;t.objectStoreNames.contains(mi)||t.createObjectStore(mi,{keyPath:`id`}).createIndex(`sessionId`,`sessionId`,{unique:!1})},n.onsuccess=t=>{let n=t.target.result;n.onversionchange=()=>{try{n.close()}catch{}hi=null},e(n)},n.onerror=()=>t(n.error||Error(`idb_open_failed`)),n.onblocked=()=>{}})}function vi(){return hi||=_i(),hi}function yi(e,t){return vi().then(n=>new Promise((r,i)=>{let a;try{a=n.transaction(mi,e)}catch(e){hi=null,i(e);return}let o=a.objectStore(mi),s=null,c=e=>{s=e};try{t(o,c)}catch(e){i(e);return}a.oncomplete=()=>r(s),a.onerror=()=>i(a.error||Error(`idb_tx_failed`)),a.onabort=()=>i(a.error||Error(`idb_tx_aborted`))}))}function bi(){return{async put(e){await yi(`readwrite`,t=>{t.put(e)})},async get(e){return yi(`readonly`,(t,n)=>{let r=t.get(e);r.onsuccess=()=>n(r.result||null)})},async remove(e){await yi(`readwrite`,t=>{t.delete(e)})},async removeBySession(e){await yi(`readwrite`,t=>{let n=t.index(`sessionId`).getAllKeys(e);n.onsuccess=()=>{for(let e of n.result||[])t.delete(e)}})},async allKeys(){return yi(`readonly`,(e,t)=>{let n=e.getAllKeys();n.onsuccess=()=>t(n.result||[])})}}}function xi(){return gi||bi()}function Si(e){return e==null?0:typeof e==`string`?e.length:typeof e==`number`||typeof e==`boolean`?8:Array.isArray(e)?e.reduce((e,t)=>e+Si(t),0):typeof e==`object`?Object.values(e).reduce((e,t)=>e+Si(t),0):0}function Ci(e){let t=e&&e.attachedImages||[],n=e&&e.attachedFiles||[];return!t.length&&!n.length?null:{imageCount:t.length,fileCount:n.length,fileNames:n.map(e=>e.name).filter(Boolean).slice(0,5)}}async function wi(e,t,{images:n=[],files:r=[]}={}){if(!e)return{ok:!1,reason:`missing_id`};if(!n.length&&!r.length)return{ok:!0,skipped:!0};let i=Si(n)+Si(r);if(i>26214400)return{ok:!1,reason:`too_large`,size:i};try{return await xi().put({id:e,sessionId:t||null,size:i,images:n,files:r,updatedAt:Date.now()}),{ok:!0,size:i}}catch(e){return{ok:!1,reason:`idb_error`,message:e?.message||String(e)}}}async function Ti(e){if(!e)return null;try{let t=await xi().get(e);return t?{images:t.images||[],files:t.files||[]}:null}catch{return null}}async function Ei(e){if(!e)return!1;try{return await xi().remove(e),!0}catch{return!1}}async function Di(e){if(!e)return!1;try{return await xi().removeBySession(e),!0}catch{return!1}}async function Oi(e){let t=e instanceof Set?e:new Set(e||[]);try{let e=await xi().allKeys(),n=0;for(let r of e||[])t.has(r)||(await xi().remove(r),n+=1);return n}catch{return 0}}var ki=t({appendMessageToSession:()=>Zi,archiveCurrentSession:()=>Wi,archiveSession:()=>qi,clearSessionCompleted:()=>Pi,createSession:()=>zi,deleteArchivedSession:()=>Yi,deleteSession:()=>Vi,duplicateSession:()=>Qi,hydrateSessionWorkdir:()=>Li,importSessions:()=>Xi,isSessionArchivable:()=>Ki,loadArchivedSessions:()=>Gi,loadSessions:()=>Fi,markSessionCompleted:()=>Ni,persistSessionState:()=>Ri,renameSession:()=>Hi,reorderSessions:()=>Ui,restoreCompletedSessions:()=>ji,restoreSession:()=>Ji,saveCurrentSession:()=>Ii,switchToSession:()=>Bi}),Ai=`completedSessionIds`;async function ji(){try{let e=(await chrome.storage.local.get([Ai]))[Ai]||[];N.completedSessionIds=new Set(e)}catch(e){a.warn(`[SessionManager] restore completedSessionIds failed:`,e)}}async function Mi(){try{await chrome.storage.local.set({[Ai]:Array.from(N.completedSessionIds)})}catch(e){a.warn(`[SessionManager] persist completedSessionIds failed:`,e)}}async function Ni(e){e&&e!==N.activeSessionId&&(N.completedSessionIds.has(e)||(N.completedSessionIds.add(e),await Mi(),document.dispatchEvent(new CustomEvent(`generating-state-changed`))))}async function Pi(e){e&&N.completedSessionIds.has(e)&&(N.completedSessionIds.delete(e),await Mi(),document.dispatchEvent(new CustomEvent(`generating-state-changed`)))}async function Fi(){return ke()}async function Ii(){return Pe()}function Li(e){return Oe(e)}async function Ri(e,t){return Me(e,t)}async function zi(){return Ee()}async function Bi(e){return nt(e)}async function Vi(e){await di(e)>0&&Di(e);let t=await We(e);try{chrome.runtime.sendMessage({type:`DROP_GOAL`,sessionId:e},()=>{chrome.runtime.lastError&&a.debug(`[SessionManager] DROP_GOAL skipped:`,chrome.runtime.lastError.message)})}catch(e){a.debug(`[SessionManager] DROP_GOAL send failed:`,e?.message)}return N.completedSessionIds.has(e)&&(N.completedSessionIds.delete(e),await Mi()),t}async function Hi(e,t){return Ke(e,t)}async function Ui(e){return Be(e)}async function Wi(){return He()}async function Gi(){return $e()}function Ki(e){return e?N.generatingSessionIds.has(e)||N.pendingCallApiSessionIds.has(e)?{ok:!1,reason:`running`}:Kr(e)>0?{ok:!1,reason:`queued`}:{ok:!0}:{ok:!1,reason:`missing`}}async function qi(e){let t=Ki(e);return t.ok?await Je(e)?(N.completedSessionIds.has(e)&&(N.completedSessionIds.delete(e),await Mi(),document.dispatchEvent(new CustomEvent(`generating-state-changed`))),{ok:!0}):{ok:!1,reason:`missing`}:t}async function Ji(e){return at(e)}async function Yi(e){return Vi(e)}async function Xi(e){return Re(e)}async function Zi(e,t){return Ze(e,t)}async function Qi(e,t=null){return Xe(e,t)}n(`zh`,{toolPanel:{agentRestrictedBanner:`当前 Agent 限制了可用工具,部分工具已禁用`,noMatch:`没有匹配的工具`,enabledCount:`已启用 {enabled}/{total} 个工具`,toolsEnabled:`工具已启用`,allToolsDisabled:`所有工具已禁用`,toggleBtnEnabled:`禁用所有工具`,toggleBtnDisabled:`启用所有工具`,mcpServiceToolCount:`{count} 个工具`,mcpServiceExpand:`展开/收起工具列表`,mcpExcludedByAgent:`已被当前助手排除,可在助手编辑中调整`,categorySelectAllHint:`对该分类下可见项全选/取消全选`,stateOn:`已开启`,stateOff:`已关闭`,stateLine:`{name}:{state}`}}),n(`en`,{toolPanel:{agentRestrictedBanner:`Current agent has restricted available tools, some tools are disabled`,noMatch:`No matching tools`,enabledCount:`{enabled}/{total} tools enabled`,toolsEnabled:`Tools enabled`,allToolsDisabled:`All tools disabled`,toggleBtnEnabled:`Disable all tools`,toggleBtnDisabled:`Enable all tools`,mcpServiceToolCount:`{count} tools`,mcpServiceExpand:`Show/hide tool list`,mcpExcludedByAgent:`Excluded by current assistant; adjust in assistant editor`,categorySelectAllHint:`Select/deselect all visible items in this category`,stateOn:`On`,stateOff:`Off`,stateLine:`{name}: {state}`}});var $i=[],ea=[];function ta(e){if(!e)return``;let t=`tool.${e.id}`,n=r(t);return n===t?e.description||``:n}function na(e){if(!e)return``;let t=e.description||``;if(t.startsWith(`[MCP:`)){let e=t.indexOf(`]`);e!==-1&&(t=t.slice(e+1).trim())}return t===(e.name||``)?``:t}async function ra(){try{let e=await chrome.runtime.sendMessage({type:`GET_MCP_TOOLS`});if(e?.success&&e.tools)return $i=e.tools,$i}catch{}try{return $i=(await chrome.storage.local.get([`mcpTools`])).mcpTools||[],$i}catch{return $i=[],[]}}async function ia(){try{ea=(await chrome.storage.local.get([`ragTools`])).ragTools||[]}catch{ea=[]}return ea}async function aa(){let e=`agentMcpClosedServers_${N.activeAgentId||`default`}`;try{N.mcpClosedServers=(await chrome.storage.local.get([e]))[e]||[]}catch{N.mcpClosedServers=[]}try{let{getAgent:e}=await M(async()=>{let{getAgent:e}=await import(`./agent-store-1fyaAv9T.js`).then(e=>e.t);return{getAgent:e}},__vite__mapDeps([0,1,2,3,4])),t=N.activeAgentId?await e(N.activeAgentId):null;N.activeAgentMcpExcludedServerIds=t?t.mcpExcludedServerIds??null:null}catch{}}var oa=!1,sa=!0;chrome.storage.local.get([`enableToolPreselect`,`toolConfirmationEnabled`],e=>{oa=e.enableToolPreselect===!0,sa=e.toolConfirmationEnabled!==!1,Na()}),chrome.storage.onChanged.addListener((e,t)=>{if(t!==`local`)return;let n=!1;e.mcpTools&&($i=e.mcpTools.newValue||[],a.debug(`[SidePanel] MCP toolcache updated:`,$i.length,``),n=!0),e.ragTools&&(ea=e.ragTools.newValue||[],a.debug(`[SidePanel] RAG toolcache updated:`,ea.length),n=!0),e.mcpEnabled&&(ca=e.mcpEnabled.newValue===!0,a.debug(`[SidePanel] MCP globaltoggle changed:`,ca),n=!0),e.skillsEnabled&&(la=e.skillsEnabled.newValue!==!1,a.debug(`[SidePanel] Skill global toggle changed:`,la),n=!0),e.enableImageInput&&(ua=e.enableImageInput.newValue===!0,a.debug(`[SidePanel] 图片识别全局开关变更:`,ua),n=!0);let r=!1;e.enableToolPreselect&&(oa=e.enableToolPreselect.newValue===!0,r=!0),e.toolConfirmationEnabled&&(sa=e.toolConfirmationEnabled.newValue!==!1,r=!0),r&&Na(),n&&(document.getElementById(`toolsPopupOverlay`)?.classList.contains(`show`)&&(Oa(),ka(),ba()),Ma())}),ra().then(()=>Ma()),ia().then(()=>Ma());var ca=!1,la=!0,ua=!1;chrome.storage.local.get([`mcpEnabled`,`skillsEnabled`,`enableImageInput`],e=>{ca=e.mcpEnabled===!0,la=e.skillsEnabled!==!1,ua=e.enableImageInput===!0,Ma()});function da(){let e=[...x,...ea],t=N.activeAgentToolIds,n=e;if(t!=null){let r=new Set(t);n=e.filter(e=>r.has(e.id))}return la||(n=n.filter(e=>e.id!==`agent_skill`)),N.agentPlatform?.connected!==!0&&(n=n.filter(e=>!e.id.startsWith(`agent_`)&&!e.id.startsWith(`knowledge_`))),ua||(n=n.filter(e=>e.id!==`read_image`)),n}function fa(){if(!ca||N.agentPlatform?.connected!==!0)return[];let e=new Map;return $i.forEach(t=>{let n=t.serverId||`unknown`;e.has(n)||e.set(n,{serverId:n,serverName:t.serverName||n,tools:[],toolCount:0});let r=e.get(n);r.tools.push(t),r.toolCount++}),Array.from(e.values())}function pa(e){return Array.isArray(N.mcpClosedServers)&&N.mcpClosedServers.includes(e)}function ma(e){return Array.isArray(N.activeAgentMcpExcludedServerIds)&&N.activeAgentMcpExcludedServerIds.includes(e)}function ha(e){return!pa(e)&&!ma(e)}function ga(){if(N.currentCategory!==`all`&&N.currentCategory!==`mcp`)return[];let e=fa();if(N.currentSearch){let t=N.currentSearch;e=e.filter(e=>(e.serverName||``).toLowerCase().includes(t)||(e.serverId||``).toLowerCase().includes(t)||e.tools.some(e=>(e.name||``).toLowerCase().includes(t)||ta(e).toLowerCase().includes(t)))}return e}function _a(e,t){Array.isArray(N.mcpClosedServers)||(N.mcpClosedServers=[]);let n=N.mcpClosedServers.indexOf(e);t?n>-1&&N.mcpClosedServers.splice(n,1):n===-1&&N.mcpClosedServers.push(e)}async function va(){let e=document.getElementById(`toolsPopupOverlay`);if(!e)return;N.currentCategory=`all`,N.currentSearch=``;let t=document.getElementById(`toolsSearchInput`);t&&(t.value=``),await ra(),await ia(),await aa(),Oa(),ka(),chrome.storage.local.get([`enableToolPreselect`,`toolConfirmationEnabled`],e=>{let t=document.getElementById(`toolsPreselectToggle`);t&&(t.checked=e.enableToolPreselect===void 0?!1:e.enableToolPreselect);let n=document.getElementById(`toolConfirmToggle`);n&&(n.checked=e.toolConfirmationEnabled===void 0?!0:e.toolConfirmationEnabled)}),document.querySelectorAll(`.category-btn`).forEach(e=>{e.classList.remove(`active`),e.classList.contains(`category-all`)?(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`):(e.style.background=`var(--bg-surface)`,e.style.color=`var(--text-secondary)`,e.style.borderColor=`var(--border-subtle)`)}),ba(),e.classList.add(`show`),a.debug(`[SidePanel] opentool popup`)}function ya(){let e=document.getElementById(`toolsPopupOverlay`);e&&(document.querySelectorAll(`.category-btn`).forEach(e=>{e.classList.remove(`active`),e.style.background=``,e.style.color=``,e.style.borderColor=``}),e.classList.remove(`show`),a.debug(`[SidePanel] closetool popup`))}function ba(){let e=document.getElementById(`toolsPopupList`);if(!e)return;e.innerHTML=``;let t=da();if(N.activeAgentToolIds!==null&&N.activeAgentToolIds!==void 0){let t=document.createElement(`div`);t.className=`popup-tool-agent-banner`,t.innerHTML=`<span>${r(`toolPanel.agentRestrictedBanner`)}</span>`,e.appendChild(t)}let n={};t.forEach(e=>{if(N.currentCategory!==`all`&&e.category!==N.currentCategory)return;if(N.currentSearch){let t=e.name.toLowerCase().includes(N.currentSearch),n=ta(e).toLowerCase().includes(N.currentSearch);if(!t&&!n)return}let t=e.category||`other`;n[t]||(n[t]=[]),n[t].push(e)});let i=ga();if(Ln.forEach(a=>{let o=a===`mcp`,s=n[a]||[],c=o?i:[];if(o?c.length===0:s.length===0)return;let l;if(o)l=`${c.filter(e=>ha(e.serverId)).length}/${c.length}`;else{let e=t.filter(e=>e.category===a);l=`${e.filter(e=>N.enabledTools.includes(e.id)).length}/${e.length}`}let u=document.createElement(`div`);u.className=`popup-tool-category-group`,u.dataset.category=a;let d=document.createElement(`div`);d.className=`popup-tool-category`,d.dataset.category=a;let f=N.collapsedCategories[a]||!1;d.innerHTML=`
|
|
29
|
+
`;let s=e.closest(`.message-fullscreen-overlay`),c=e.closest(`.workspace-preview-overlay.fullscreen`);(s?s.querySelector(`.message-fullscreen-rail`)||er(`toc`):c&&c.querySelector(`.workspace-preview-rail`)||er(`toc`)).appendChild(i),N.messageTocContainer=i;let l=i.querySelector(`.message-toc-toggle`),u=i.querySelector(`.message-toc-panel`);ir&&(u.classList.add(`expanded`,`locked`),It(u));let d=i.querySelector(`.message-toc-lock`);d.addEventListener(`click`,e=>{e.stopPropagation(),ir=!ir,cr(),sr(d),ir?(u.classList.add(`expanded`,`locked`),It(u)):u.classList.remove(`locked`)}),i.querySelector(`.message-toc-close`).addEventListener(`click`,e=>{e.stopPropagation(),ir&&(ir=!1,cr()),pr()}),l.addEventListener(`mouseenter`,()=>{u.classList.add(`expanded`),It(u)}),l.addEventListener(`click`,()=>{u.classList.toggle(`expanded`)?It(u):Gt(u)}),u.addEventListener(`mouseenter`,()=>{u.classList.add(`expanded`)}),i.querySelectorAll(`.message-toc-item`).forEach(e=>{e.addEventListener(`click`,()=>{let t=e.dataset.target,n=document.getElementById(t);n&&(n.scrollIntoView({behavior:`smooth`,block:`start`}),n.classList.add(`toc-highlight`),setTimeout(()=>{n.classList.remove(`toc-highlight`)},1500))})})}function pr(){N.tocHideTimer&&=(clearTimeout(N.tocHideTimer),null),N.messageTocContainer&&=(N.messageTocContainer.remove(),null)}var mr=`promptQueues`,hr=1,gr=30*1e3,_r=15*1e3,vr=20,R={QUEUED:`queued`,DISPATCHING:`dispatching`,INJECTING:`injecting`,INJECTED:`injected`,DONE:`done`,FAILED:`failed`};new Set([R.INJECTED,R.DONE,R.FAILED]);var yr={async get(e){let t=await chrome.storage.local.get(e);return t?t[e]:void 0},async set(e){await chrome.storage.local.set(e)}};function br(){return{version:hr,sessions:{}}}var z=br(),xr=!1,Sr=null,Cr=!1,wr=``,Tr=new Set,Er=new Set;function Dr(){return{items:[],recent:[],paused:!1,pausedReason:null}}function Or(e){return e?(z.sessions[e]||(z.sessions[e]=Dr()),z.sessions[e]):Dr()}function kr(){return JSON.stringify(z)}function Ar(e,t){for(let n of Er)try{n(e,t)}catch(e){a.error(`[QueueStore] listener failed:`,e?.message)}}function jr(){return typeof crypto<`u`&&typeof crypto.randomUUID==`function`?`q_`+crypto.randomUUID():`q_`+Date.now().toString(36)+`_`+Math.random().toString(36).slice(2,8)}function Mr(e){return e.reduce((e,t)=>Math.max(e,Number(t.order)||0),0)+1}function Nr(e,t){let n=e.indexOf(t);n<0||(e.splice(n,1),e.unshift(t),Pr(e))}function Pr(e){e.forEach((e,t)=>{e.order=t+1})}function Fr(e){return e.slice().sort((e,t)=>(Number(e.order)||0)-(Number(t.order)||0))}async function Ir(e){if(Cr)return a.error(`[QueueStore] persist skipped in degraded mode:`,e),!1;let t=kr();wr=t,Lr(t);try{await yr.set({[mr]:z})}catch(e){a.error(`[QueueStore] persist failed:`,e?.message)}Ar(e)}function Lr(e){if(Tr.add(e),Tr.size<=vr)return;let t=Tr.values().next().value;Tr.delete(t)}function Rr(e,{recoverInterrupted:t=!0}={}){let n=br();if(!e||typeof e!=`object`)return n;let r=e.sessions&&typeof e.sessions==`object`?e.sessions:{};for(let[e,i]of Object.entries(r)){let r=Array.isArray(i?.items)?i.items:[],a=Array.isArray(i?.recent)?i.recent.slice(0,30):[],o=!1;for(let e of r)!e||typeof e!=`object`||t&&(e.status===R.DISPATCHING||e.status===R.INJECTING)&&(e.status=R.QUEUED,e.interrupted=!0,e.previousStatus=e.previousStatus||R.DISPATCHING,e.leaseOwner=null,e.leaseUntil=0,o=!0);let s=Fr(r);if(o){let e=s.filter(e=>e.interrupted),t=s.filter(e=>!e.interrupted);s.splice(0,s.length,...e,...t)}Pr(s);let c=s.slice(0,20),l=s.slice(20);for(let e of l.reverse())a.unshift(si({...e,status:R.FAILED,lastError:`over_limit`}));n.sessions[e]={items:c,recent:a.slice(0,30),paused:i?.paused===!0,pausedReason:i?.pausedReason||null}}return n}function zr(){return Cr}async function Br(){return xr?z:Sr||(Sr=(async()=>{let e;try{e=await yr.get(mr)}catch(e){return Cr=!0,Sr=null,a.error(`[QueueStore] load failed, enter degraded mode:`,e?.message),z}return z=Rr(e),xr=!0,Cr=!1,wr=kr(),z})(),Sr)}function Vr(){typeof chrome>`u`||!chrome.storage?.onChanged?.addListener||chrome.storage.onChanged.addListener((e,t)=>{if(t!==`local`||!e?.[mr])return;let n=e[mr].newValue;if(!n)return;let r=JSON.stringify(n);Tr.has(r)||r===wr||(z=Rr(n,{recoverInterrupted:!1}),xr=!0,wr=r,Ar(`external`,null))})}function Hr(e){return typeof e==`function`?(Er.add(e),()=>Er.delete(e)):()=>{}}function Ur(e){let t=z.sessions[e];return t?Fr(t.items):[]}function Wr(e,t=30){let n=z.sessions[e];return n?n.recent.slice(0,t):[]}function Gr(e){let t=z.sessions[e];return t?{items:Fr(t.items),recent:t.recent.slice(),paused:t.paused===!0,pausedReason:t.pausedReason||null}:Dr()}function Kr(e){return Ur(e).filter(e=>e.status===R.QUEUED).length}function qr(e){return Ur(e).find(e=>e.status===R.QUEUED)||null}function Jr(e){let t=z.sessions[e];if(!t)return null;for(let e=t.items.length-1;e>=0;--e)if(t.items[e].status===R.QUEUED)return t.items[e];return null}function Yr(e,t){let n=z.sessions[e];return n&&n.items.find(e=>e.id===t)||null}function Xr(){return Object.keys(z.sessions).filter(e=>(z.sessions[e]?.items?.length||0)>0)}function Zr(e){return z.sessions[e]?.paused===!0}async function Qr({sessionId:e,text:t,contextSnapshot:n=null,hasContext:r=!1,attachmentSummary:i=null,source:a=`manual`}){if(!e)return{ok:!1,error:`missing_session`};let o=String(t||``).trim();if(!o)return{ok:!1,error:`empty`};if(await Br(),Cr)return{ok:!1,error:`storage_unavailable`};let s=Or(e);if(s.items.length>=20)return{ok:!1,error:`queue_full`,limit:20};let c={id:jr(),sessionId:e,text:o,contextSnapshot:n||null,attachmentSummary:i||null,hasContext:r===!0,status:R.QUEUED,order:Mr(s.items),createdAt:Date.now(),updatedAt:Date.now(),attempts:0,lastError:null,source:a,interrupted:!1,leaseOwner:null,leaseUntil:0,injectRequestedAt:0,injectDeadlineAt:0,injectedIntoCallId:null,absorbedIteration:null};return s.items.push(c),await Ir(`enqueue`),{ok:!0,item:c,position:s.items.length}}async function $r(e,t){let n=z.sessions[e];if(!n)return!1;let r=n.items.findIndex(e=>e.id===t);return r<0?!1:(n.items.splice(r,1),Pr(n.items),await Ir(`remove`),!0)}async function ei(e,t){let n=z.sessions[e];if(!n||!Array.isArray(t))return!1;let r=new Map(n.items.map(e=>[e.id,e])),i=[];for(let e of t){let t=r.get(e);t&&!i.includes(t)&&i.push(t)}for(let e of Fr(n.items))i.includes(e)||i.push(e);return n.items=i,Pr(n.items),await Ir(`reorder`),!0}async function ti(e,t,n,r={}){let i=Yr(e,t);return i?(i.status=n,Object.assign(i,r,{updatedAt:Date.now()}),await Ir(`status`),!0):!1}async function ni(e,t,n=_r){let r=Yr(e,t);return r?(r.previousStatus=r.status,r.status=R.INJECTING,r.injectRequestedAt=Date.now(),r.injectDeadlineAt=Date.now()+n,r.updatedAt=Date.now(),await Ir(`inject:request`),!0):!1}async function ri(e,t,n=`error`,r=null){let i=z.sessions[e];if(!i)return!1;let a=i.items.find(e=>e.id===t);return a?(a.status=R.QUEUED,a.injectDeadlineAt=0,a.updatedAt=Date.now(),a.lastError=r||n,a.rollbackReason=n,Nr(i.items,a),await Ir(`inject:rollback`),!0):!1}async function ii(e,t,{status:n,note:r=null,callId:i=null,iteration:a=null}={}){let o=z.sessions[e];if(!o)return!1;let s=o.items.findIndex(e=>e.id===t);if(s<0)return!1;let[c]=o.items.splice(s,1);return Pr(o.items),c.status=n||R.DONE,c.settledAt=Date.now(),c.settleNote=r,i&&(c.injectedIntoCallId=i),a!=null&&(c.absorbedIteration=a),o.recent.unshift(si(c)),o.recent=o.recent.slice(0,30),await Ir(`settle`),!0}async function ai(e,t){let n=z.sessions[e];if(!n)return{ok:!1,error:`missing_session`};let r=n.recent.findIndex(e=>e.id===t);if(r<0)return{ok:!1,error:`not_found`};if(n.items.length>=20)return{ok:!1,error:`queue_full`,limit:20};let[i]=n.recent.splice(r,1),a={...i,status:R.QUEUED,order:Mr(n.items),attempts:0,lastError:null,interrupted:!1,rollbackReason:null,settledAt:null,leaseOwner:null,leaseUntil:0,injectDeadlineAt:0,updatedAt:Date.now()};return n.items.push(a),await Ir(`requeue`),{ok:!0,item:a}}async function oi(e,t){let n=z.sessions[e];if(!n)return!1;let r=n.recent.findIndex(e=>e.id===t);return r<0?!1:(n.recent.splice(r,1),await Ir(`recent-remove`),!0)}function si(e){let{leaseOwner:t,leaseUntil:n,injectDeadlineAt:r,contextSnapshot:i,...a}=e;return{...a,hasContext:e.hasContext===!0,contextDropped:!!i}}async function ci(e,t=`user_stopped`){let n=Or(e);return n.paused?!1:(n.paused=!0,n.pausedReason=t,await Ir(`pause`),!0)}async function li(e){let t=z.sessions[e];return!t||!t.paused?!1:(t.paused=!1,t.pausedReason=null,await Ir(`resume`),!0)}async function ui(e,t,n){let r=Yr(e,t);if(!r)return!1;let i=Date.now();return r.leaseOwner&&r.leaseOwner!==n&&Number(r.leaseUntil)>i?!1:(r.leaseOwner=n,r.leaseUntil=i+gr,await Ir(`lease`),!0)}async function di(e){let t=z.sessions[e];if(!t)return 0;let n=t.items.length+t.recent.length;return delete z.sessions[e],n>0&&await Ir(`drop-session`),n}var fi=`ai-helper-queue-attachments`,pi=1,mi=`attachments`,hi=null,gi=null;function _i(){return new Promise((e,t)=>{let n=indexedDB.open(fi,pi);n.onupgradeneeded=e=>{let t=e.target.result;t.objectStoreNames.contains(mi)||t.createObjectStore(mi,{keyPath:`id`}).createIndex(`sessionId`,`sessionId`,{unique:!1})},n.onsuccess=t=>{let n=t.target.result;n.onversionchange=()=>{try{n.close()}catch{}hi=null},e(n)},n.onerror=()=>t(n.error||Error(`idb_open_failed`)),n.onblocked=()=>{}})}function vi(){return hi||=_i(),hi}function yi(e,t){return vi().then(n=>new Promise((r,i)=>{let a;try{a=n.transaction(mi,e)}catch(e){hi=null,i(e);return}let o=a.objectStore(mi),s=null,c=e=>{s=e};try{t(o,c)}catch(e){i(e);return}a.oncomplete=()=>r(s),a.onerror=()=>i(a.error||Error(`idb_tx_failed`)),a.onabort=()=>i(a.error||Error(`idb_tx_aborted`))}))}function bi(){return{async put(e){await yi(`readwrite`,t=>{t.put(e)})},async get(e){return yi(`readonly`,(t,n)=>{let r=t.get(e);r.onsuccess=()=>n(r.result||null)})},async remove(e){await yi(`readwrite`,t=>{t.delete(e)})},async removeBySession(e){await yi(`readwrite`,t=>{let n=t.index(`sessionId`).getAllKeys(e);n.onsuccess=()=>{for(let e of n.result||[])t.delete(e)}})},async allKeys(){return yi(`readonly`,(e,t)=>{let n=e.getAllKeys();n.onsuccess=()=>t(n.result||[])})}}}function xi(){return gi||bi()}function Si(e){return e==null?0:typeof e==`string`?e.length:typeof e==`number`||typeof e==`boolean`?8:Array.isArray(e)?e.reduce((e,t)=>e+Si(t),0):typeof e==`object`?Object.values(e).reduce((e,t)=>e+Si(t),0):0}function Ci(e){let t=e&&e.attachedImages||[],n=e&&e.attachedFiles||[];return!t.length&&!n.length?null:{imageCount:t.length,fileCount:n.length,fileNames:n.map(e=>e.name).filter(Boolean).slice(0,5)}}async function wi(e,t,{images:n=[],files:r=[]}={}){if(!e)return{ok:!1,reason:`missing_id`};if(!n.length&&!r.length)return{ok:!0,skipped:!0};let i=Si(n)+Si(r);if(i>26214400)return{ok:!1,reason:`too_large`,size:i};try{return await xi().put({id:e,sessionId:t||null,size:i,images:n,files:r,updatedAt:Date.now()}),{ok:!0,size:i}}catch(e){return{ok:!1,reason:`idb_error`,message:e?.message||String(e)}}}async function Ti(e){if(!e)return null;try{let t=await xi().get(e);return t?{images:t.images||[],files:t.files||[]}:null}catch{return null}}async function Ei(e){if(!e)return!1;try{return await xi().remove(e),!0}catch{return!1}}async function Di(e){if(!e)return!1;try{return await xi().removeBySession(e),!0}catch{return!1}}async function Oi(e){let t=e instanceof Set?e:new Set(e||[]);try{let e=await xi().allKeys(),n=0;for(let r of e||[])t.has(r)||(await xi().remove(r),n+=1);return n}catch{return 0}}var ki=t({appendMessageToSession:()=>Zi,archiveCurrentSession:()=>Wi,archiveSession:()=>qi,clearSessionCompleted:()=>Pi,createSession:()=>zi,deleteArchivedSession:()=>Yi,deleteSession:()=>Vi,duplicateSession:()=>Qi,hydrateSessionWorkdir:()=>Li,importSessions:()=>Xi,isSessionArchivable:()=>Ki,loadArchivedSessions:()=>Gi,loadSessions:()=>Fi,markSessionCompleted:()=>Ni,persistSessionState:()=>Ri,renameSession:()=>Hi,reorderSessions:()=>Ui,restoreCompletedSessions:()=>ji,restoreSession:()=>Ji,saveCurrentSession:()=>Ii,switchToSession:()=>Bi}),Ai=`completedSessionIds`;async function ji(){try{let e=(await chrome.storage.local.get([Ai]))[Ai]||[];N.completedSessionIds=new Set(e)}catch(e){a.warn(`[SessionManager] restore completedSessionIds failed:`,e)}}async function Mi(){try{await chrome.storage.local.set({[Ai]:Array.from(N.completedSessionIds)})}catch(e){a.warn(`[SessionManager] persist completedSessionIds failed:`,e)}}async function Ni(e){e&&e!==N.activeSessionId&&(N.completedSessionIds.has(e)||(N.completedSessionIds.add(e),await Mi(),document.dispatchEvent(new CustomEvent(`generating-state-changed`))))}async function Pi(e){e&&N.completedSessionIds.has(e)&&(N.completedSessionIds.delete(e),await Mi(),document.dispatchEvent(new CustomEvent(`generating-state-changed`)))}async function Fi(){return ke()}async function Ii(){return Pe()}function Li(e){return Oe(e)}async function Ri(e,t){return Me(e,t)}async function zi(){return Ee()}async function Bi(e){return nt(e)}async function Vi(e){await di(e)>0&&Di(e);let t=await We(e);try{chrome.runtime.sendMessage({type:`DROP_GOAL`,sessionId:e},()=>{chrome.runtime.lastError&&a.debug(`[SessionManager] DROP_GOAL skipped:`,chrome.runtime.lastError.message)})}catch(e){a.debug(`[SessionManager] DROP_GOAL send failed:`,e?.message)}return N.completedSessionIds.has(e)&&(N.completedSessionIds.delete(e),await Mi()),t}async function Hi(e,t){return Ke(e,t)}async function Ui(e){return Be(e)}async function Wi(){return He()}async function Gi(){return $e()}function Ki(e){return e?N.generatingSessionIds.has(e)||N.pendingCallApiSessionIds.has(e)?{ok:!1,reason:`running`}:Kr(e)>0?{ok:!1,reason:`queued`}:{ok:!0}:{ok:!1,reason:`missing`}}async function qi(e){let t=Ki(e);return t.ok?await Je(e)?(N.completedSessionIds.has(e)&&(N.completedSessionIds.delete(e),await Mi(),document.dispatchEvent(new CustomEvent(`generating-state-changed`))),{ok:!0}):{ok:!1,reason:`missing`}:t}async function Ji(e){return at(e)}async function Yi(e){return Vi(e)}async function Xi(e){return Re(e)}async function Zi(e,t){return Ze(e,t)}async function Qi(e,t=null){return Xe(e,t)}n(`zh`,{toolPanel:{agentRestrictedBanner:`当前 Agent 限制了可用工具,部分工具已禁用`,noMatch:`没有匹配的工具`,enabledCount:`已启用 {enabled}/{total} 个工具`,toolsEnabled:`工具已启用`,allToolsDisabled:`所有工具已禁用`,toggleBtnEnabled:`禁用所有工具`,toggleBtnDisabled:`启用所有工具`,mcpServiceToolCount:`{count} 个工具`,mcpServiceExpand:`展开/收起工具列表`,mcpExcludedByAgent:`已被当前助手排除,可在助手编辑中调整`,categorySelectAllHint:`对该分类下可见项全选/取消全选`,stateOn:`已开启`,stateOff:`已关闭`,stateLine:`{name}:{state}`}}),n(`en`,{toolPanel:{agentRestrictedBanner:`Current agent has restricted available tools, some tools are disabled`,noMatch:`No matching tools`,enabledCount:`{enabled}/{total} tools enabled`,toolsEnabled:`Tools enabled`,allToolsDisabled:`All tools disabled`,toggleBtnEnabled:`Disable all tools`,toggleBtnDisabled:`Enable all tools`,mcpServiceToolCount:`{count} tools`,mcpServiceExpand:`Show/hide tool list`,mcpExcludedByAgent:`Excluded by current assistant; adjust in assistant editor`,categorySelectAllHint:`Select/deselect all visible items in this category`,stateOn:`On`,stateOff:`Off`,stateLine:`{name}: {state}`}});var $i=[],ea=[];function ta(e){if(!e)return``;let t=`tool.${e.id}`,n=r(t);return n===t?e.description||``:n}function na(e){if(!e)return``;let t=e.description||``;if(t.startsWith(`[MCP:`)){let e=t.indexOf(`]`);e!==-1&&(t=t.slice(e+1).trim())}return t===(e.name||``)?``:t}async function ra(){try{let e=await chrome.runtime.sendMessage({type:`GET_MCP_TOOLS`});if(e?.success&&e.tools)return $i=e.tools,$i}catch{}try{return $i=(await chrome.storage.local.get([`mcpTools`])).mcpTools||[],$i}catch{return $i=[],[]}}async function ia(){try{ea=(await chrome.storage.local.get([`ragTools`])).ragTools||[]}catch{ea=[]}return ea}async function aa(){let e=`agentMcpClosedServers_${N.activeAgentId||`default`}`;try{N.mcpClosedServers=(await chrome.storage.local.get([e]))[e]||[]}catch{N.mcpClosedServers=[]}try{let{getAgent:e}=await M(async()=>{let{getAgent:e}=await import(`./agent-store-CXWql6bl.js`).then(e=>e.t);return{getAgent:e}},__vite__mapDeps([0,1,2,3,4])),t=N.activeAgentId?await e(N.activeAgentId):null;N.activeAgentMcpExcludedServerIds=t?t.mcpExcludedServerIds??null:null}catch{}}var oa=!1,sa=!0;chrome.storage.local.get([`enableToolPreselect`,`toolConfirmationEnabled`],e=>{oa=e.enableToolPreselect===!0,sa=e.toolConfirmationEnabled!==!1,Na()}),chrome.storage.onChanged.addListener((e,t)=>{if(t!==`local`)return;let n=!1;e.mcpTools&&($i=e.mcpTools.newValue||[],a.debug(`[SidePanel] MCP toolcache updated:`,$i.length,``),n=!0),e.ragTools&&(ea=e.ragTools.newValue||[],a.debug(`[SidePanel] RAG toolcache updated:`,ea.length),n=!0),e.mcpEnabled&&(ca=e.mcpEnabled.newValue===!0,a.debug(`[SidePanel] MCP globaltoggle changed:`,ca),n=!0),e.skillsEnabled&&(la=e.skillsEnabled.newValue!==!1,a.debug(`[SidePanel] Skill global toggle changed:`,la),n=!0),e.enableImageInput&&(ua=e.enableImageInput.newValue===!0,a.debug(`[SidePanel] 图片识别全局开关变更:`,ua),n=!0);let r=!1;e.enableToolPreselect&&(oa=e.enableToolPreselect.newValue===!0,r=!0),e.toolConfirmationEnabled&&(sa=e.toolConfirmationEnabled.newValue!==!1,r=!0),r&&Na(),n&&(document.getElementById(`toolsPopupOverlay`)?.classList.contains(`show`)&&(Oa(),ka(),ba()),Ma())}),ra().then(()=>Ma()),ia().then(()=>Ma());var ca=!1,la=!0,ua=!1;chrome.storage.local.get([`mcpEnabled`,`skillsEnabled`,`enableImageInput`],e=>{ca=e.mcpEnabled===!0,la=e.skillsEnabled!==!1,ua=e.enableImageInput===!0,Ma()});function da(){let e=[...x,...ea],t=N.activeAgentToolIds,n=e;if(t!=null){let r=new Set(t);n=e.filter(e=>r.has(e.id))}return la||(n=n.filter(e=>e.id!==`agent_skill`)),N.agentPlatform?.connected!==!0&&(n=n.filter(e=>!e.id.startsWith(`agent_`)&&!e.id.startsWith(`knowledge_`))),ua||(n=n.filter(e=>e.id!==`read_image`)),n}function fa(){if(!ca||N.agentPlatform?.connected!==!0)return[];let e=new Map;return $i.forEach(t=>{let n=t.serverId||`unknown`;e.has(n)||e.set(n,{serverId:n,serverName:t.serverName||n,tools:[],toolCount:0});let r=e.get(n);r.tools.push(t),r.toolCount++}),Array.from(e.values())}function pa(e){return Array.isArray(N.mcpClosedServers)&&N.mcpClosedServers.includes(e)}function ma(e){return Array.isArray(N.activeAgentMcpExcludedServerIds)&&N.activeAgentMcpExcludedServerIds.includes(e)}function ha(e){return!pa(e)&&!ma(e)}function ga(){if(N.currentCategory!==`all`&&N.currentCategory!==`mcp`)return[];let e=fa();if(N.currentSearch){let t=N.currentSearch;e=e.filter(e=>(e.serverName||``).toLowerCase().includes(t)||(e.serverId||``).toLowerCase().includes(t)||e.tools.some(e=>(e.name||``).toLowerCase().includes(t)||ta(e).toLowerCase().includes(t)))}return e}function _a(e,t){Array.isArray(N.mcpClosedServers)||(N.mcpClosedServers=[]);let n=N.mcpClosedServers.indexOf(e);t?n>-1&&N.mcpClosedServers.splice(n,1):n===-1&&N.mcpClosedServers.push(e)}async function va(){let e=document.getElementById(`toolsPopupOverlay`);if(!e)return;N.currentCategory=`all`,N.currentSearch=``;let t=document.getElementById(`toolsSearchInput`);t&&(t.value=``),await ra(),await ia(),await aa(),Oa(),ka(),chrome.storage.local.get([`enableToolPreselect`,`toolConfirmationEnabled`],e=>{let t=document.getElementById(`toolsPreselectToggle`);t&&(t.checked=e.enableToolPreselect===void 0?!1:e.enableToolPreselect);let n=document.getElementById(`toolConfirmToggle`);n&&(n.checked=e.toolConfirmationEnabled===void 0?!0:e.toolConfirmationEnabled)}),document.querySelectorAll(`.category-btn`).forEach(e=>{e.classList.remove(`active`),e.classList.contains(`category-all`)?(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`):(e.style.background=`var(--bg-surface)`,e.style.color=`var(--text-secondary)`,e.style.borderColor=`var(--border-subtle)`)}),ba(),e.classList.add(`show`),a.debug(`[SidePanel] opentool popup`)}function ya(){let e=document.getElementById(`toolsPopupOverlay`);e&&(document.querySelectorAll(`.category-btn`).forEach(e=>{e.classList.remove(`active`),e.style.background=``,e.style.color=``,e.style.borderColor=``}),e.classList.remove(`show`),a.debug(`[SidePanel] closetool popup`))}function ba(){let e=document.getElementById(`toolsPopupList`);if(!e)return;e.innerHTML=``;let t=da();if(N.activeAgentToolIds!==null&&N.activeAgentToolIds!==void 0){let t=document.createElement(`div`);t.className=`popup-tool-agent-banner`,t.innerHTML=`<span>${r(`toolPanel.agentRestrictedBanner`)}</span>`,e.appendChild(t)}let n={};t.forEach(e=>{if(N.currentCategory!==`all`&&e.category!==N.currentCategory)return;if(N.currentSearch){let t=e.name.toLowerCase().includes(N.currentSearch),n=ta(e).toLowerCase().includes(N.currentSearch);if(!t&&!n)return}let t=e.category||`other`;n[t]||(n[t]=[]),n[t].push(e)});let i=ga();if(Ln.forEach(a=>{let o=a===`mcp`,s=n[a]||[],c=o?i:[];if(o?c.length===0:s.length===0)return;let l;if(o)l=`${c.filter(e=>ha(e.serverId)).length}/${c.length}`;else{let e=t.filter(e=>e.category===a);l=`${e.filter(e=>N.enabledTools.includes(e.id)).length}/${e.length}`}let u=document.createElement(`div`);u.className=`popup-tool-category-group`,u.dataset.category=a;let d=document.createElement(`div`);d.className=`popup-tool-category`,d.dataset.category=a;let f=N.collapsedCategories[a]||!1;d.innerHTML=`
|
|
30
30
|
<span class="category-expand-icon">${f?`▶`:`▼`}</span>
|
|
31
31
|
<span class="category-name">${r(`toolCategory.`+a)}</span>
|
|
32
32
|
<span class="category-count">${l}</span>
|
|
@@ -57,7 +57,7 @@ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,i,l as a,n a
|
|
|
57
57
|
`,i.addEventListener(`click`,()=>Co(t)),g.appendChild(i)}),i)){let e=document.createElement(`div`);e.className=`clarify-option-item`,e.dataset.index=-1,e.setAttribute(`role`,`radio`),e.setAttribute(`aria-checked`,`false`),e.setAttribute(`tabindex`,`-1`),e.innerHTML=`
|
|
58
58
|
<div class="clarify-option-radio"></div>
|
|
59
59
|
<div class="clarify-option-content clarify-option-other">${r(`clarify.otherOption`)}</div>
|
|
60
|
-
`,e.addEventListener(`click`,()=>Co(-1)),g.appendChild(e);let t=document.getElementById(`clarifyCustomInput`);t&&g.appendChild(t)}let _=document.getElementById(`clarifyCustomInput`);_&&_.classList.remove(`show`);let v=document.getElementById(`clarifyAdditionalInfo`);v&&v.classList.toggle(`show`,o);let y=document.getElementById(`clarifyCustomTextarea`);y&&(y.value=``);let b=document.getElementById(`clarifyAdditionalTextarea`);b&&(b.value=``),l.classList.add(`show`);let x=document.querySelector(`#clarifyContainer .clarify-content`),S=document.querySelector(`#clarifyContainer .clarify-header`);return x&&(x.scrollTop=0),S&&S.classList.remove(`scrolled`),to=null,no=!1,co(),oo(s),a.debug(`[SidePanel] clarification dialogshown:`,e.toolCallId,t),!0}function ho(){if(eo)return!0;if($a.length===0)return!1;let e=$a.shift();return mo(e)?(eo=e,Za(Qa,e),!0):(a.error(`[SidePanel] clarify overlay missing, settle as unanswered:`,e.toolCallId),go(e),L(r(`clarify.dropped`),`warning`),!1)}function go(e){Promise.resolve(chrome.runtime.sendMessage({type:`CLARIFY_RESPONSE`,toolCallId:e.toolCallId,selectedOption:-1,customInput:``,additionalInfo:``})).catch(e=>{a.debug(`[SidePanel] send unanswered clarify response failed:`,e?.message)})}function _o(){if($a.length>0){Ga(Qa);return}vo(),Ka(Qa)}function vo(){let e=document.getElementById(`clarifyOverlay`);e&&e.classList.remove(`show`),N.currentClarifyToolCallId=null,N.currentClarifySessionId=null,so()}function yo(){eo=null,_o()}function bo(e,t){return!!e.toolCallId&&e.toolCallId===t.toolCallId&&(e.sessionId||null)===(t.sessionId||null)&&e.question===t.question}function xo(e){let t={...e,sessionId:e.sessionId||null};if(a.debug(`[SidePanel] showclarification dialog:`,t.toolCallId,e),eo&&bo(eo,t)){a.debug(`[SidePanel] duplicate clarify request, ignored:`,t.toolCallId);return}if($a.some(e=>bo(e,t))){a.debug(`[SidePanel] queued duplicate clarify, ignored:`,t.toolCallId);return}$a.push(t),Ga(Qa),po(),Ya(Qa)}function So(){if(eo){yo();return}vo()}function Co(e){document.querySelectorAll(`.clarify-option-item`).forEach(e=>{e.classList.remove(`selected`),e.setAttribute(`aria-checked`,`false`),e.setAttribute(`tabindex`,`-1`)});let t=document.querySelector(`.clarify-option-item[data-index="${e}"]`);t&&(t.classList.add(`selected`),t.setAttribute(`aria-checked`,`true`),t.setAttribute(`tabindex`,`0`));let n=document.getElementById(`clarifyCustomInput`);if(n)if(e===-1){n.classList.add(`show`);let e=document.getElementById(`clarifyCustomTextarea`);e&&e.focus()}else n.classList.remove(`show`);a.debug(`[SidePanel] selectclarificationselect :`,e)}function wo(){if(!eo){a.error(`[SidePanel] no has currenttool callID`);return}let e=eo.toolCallId,t=eo.sessionId,n=-1;document.querySelectorAll(`.clarify-option-item`).forEach((e,t)=>{e.classList.contains(`selected`)&&(n=parseInt(e.dataset.index))});let r=document.getElementById(`clarifyCustomTextarea`),i=r?r.value.trim():``,o=document.getElementById(`clarifyAdditionalTextarea`),s=o?o.value.trim():``,c={type:`CLARIFY_RESPONSE`,toolCallId:e,sessionId:t,selectedOption:n,customInput:i,additionalInfo:s};a.debug(`[SidePanel] send clarificationresponse:`,c),chrome.runtime.sendMessage(c),yo()}function To(){if(eo){let e={type:`CLARIFY_RESPONSE`,toolCallId:eo.toolCallId,sessionId:eo.sessionId,selectedOption:-1,customInput:``,additionalInfo:``};chrome.runtime.sendMessage(e)}So()}function Eo(e){return e?.reason===`timeout`&&e?.defaultOption||null}function Do(e){a.debug(`[SidePanel] received clarificationtimeoutnotification:`,e);let t=e?.toolCallId;if(!t){if(e?.sessionId&&N.currentClarifySessionId&&e.sessionId!==N.currentClarifySessionId){a.debug(`[SidePanel] clarificationtimeoutfrom othersession,ignore`);return}if(!eo)return;Oo(Eo(e));return}if(eo&&eo.toolCallId===t){Oo(Eo(e));return}let n=$a.findIndex(e=>e.toolCallId===t);n>=0&&(a.debug(`[SidePanel] drop queued clarify (already settled by background):`,t),$a.splice(n,1),po(),Ya(Qa))}function Oo(e=null){let t=eo?.question;yo(),L(e?r(`clarify.timedOutDefaulted`,{option:e}):`${r(`clarify.timedOut`)}${t?`:${t}`:``}`,`warning`),io(`error`)}Wa(Qa,{present:ho,pendingCount:()=>$a.length,refresh:po});function ko(){let e=document.getElementById(`clarifyConfirmBtn`);e&&e.addEventListener(`click`,wo);let t=document.getElementById(`clarifyCancelBtn`);t&&t.addEventListener(`click`,To);let n=document.getElementById(`clarifyExtendBtn`);n&&n.addEventListener(`click`,lo);let r=document.querySelector(`#clarifyContainer .clarify-content`),i=document.querySelector(`#clarifyContainer .clarify-header`);r&&i&&r.addEventListener(`scroll`,()=>{i.classList.toggle(`scrolled`,r.scrollTop>2)}),chrome.runtime.onMessage.addListener((e,t,n)=>{e.type===`SHOW_CLARIFY_DIALOG`?(a.debug(`[SidePanel] received clarificationrequested :`,e,`currently activesession:`,N.activeSessionId),xo(e.data),n({success:!0})):e.type===`PLAY_NOTIFICATION_SOUND`?(a.debug(`[SidePanel] recei to play soundrequested :`,e),io(e.soundType),n({success:!0})):e.type===`CLARIFY_TIMEOUT`?Do(e):e.type===`CLARIFY_EXTENDED`&&uo(e)}),a.debug(`[SidePanel] clarification dialogeventinitializing`)}var Ao=Ba.CONFIRM,jo=[],Mo=null,No=null,Po=null;function Fo(e){let t=Math.floor(e/60),n=e%60;return`${t}:${String(n).padStart(2,`0`)}`}function Io(){No&&=(clearInterval(No),null),Po&&=(clearTimeout(Po),null)}function Lo(e,t){return!!e.toolCallId&&e.toolCallId===t.toolCallId&&(e.sessionId||null)===(t.sessionId||null)&&JSON.stringify(e.args??null)===JSON.stringify(t.args??null)}function Ro(e){let t=e.message||r(`dialog.confirmAction`,{name:e.toolLabel||e.toolName}),n=jo.length,i=Xa(Ao),a=t;return n>0&&(a+=` ${r(`dialog.pendingQueue`,{count:n})}`),i>0&&(a+=` ${r(`dialog.otherPending`,{count:i})}`),a}function zo(e){let{toolName:t,toolLabel:n,args:i,timeout:o=3e5}=e;N.currentConfirmToolCallId=e.toolCallId,N.currentConfirmSessionId=e.sessionId||null;let s=document.getElementById(`confirmOverlay`);if(!s)return!1;document.getElementById(`confirmToolName`).textContent=n||t;let c=document.getElementById(`confirmArgsSummary`);if(c&&i){let e=Object.entries(i).filter(([e,t])=>t!=null&&t!==``).slice(0,5);e.length>0?(c.innerHTML=e.map(([e,t])=>{let n=typeof t==`string`?t:JSON.stringify(t),r=n.length>80?n.substring(0,80)+`...`:n;return`<span class="confirm-arg" style="margin-right: 8px;"${n.length>80?` title="${n.replace(/"/g,`"`)}"`:``}><strong>${e}:</strong> ${r}</span>`}).join(`、 `),c.style.display=`block`):c.style.display=`none`}let l=document.getElementById(`confirmMessage`);l&&(l.textContent=Ro(e)),Io();let u=Math.floor(o/1e3),d=document.getElementById(`confirmCountdownText`),f=document.getElementById(`confirmCountdown`);return d&&f&&(f.classList.remove(`warning`),f.style.display=`flex`,d.textContent=r(`dialog.remainingTime`,{time:Fo(u)}),No=setInterval(()=>{if(u--,u<=0){clearInterval(No),No=null,d.textContent=r(`dialog.remainingTime`,{time:`0:00`});return}d.textContent=r(`dialog.remainingTime`,{time:Fo(u)}),u<=30&&f.classList.add(`warning`)},1e3)),s.style.display=`flex`,Po=setTimeout(()=>{a.debug(`[SidePanel] confirm dialogtimeout,autodeny`),Go(!1,`single`)},o),!0}function Bo(){if(Mo)return!0;if(jo.length===0)return!1;let e=jo.shift();return zo(e)?(Mo=e,Za(Ao,e),!0):(e.resolve&&e.resolve(!1),!1)}function Vo(){let e=document.getElementById(`confirmOverlay`);e&&(e.style.display=`none`);let t=document.getElementById(`confirmCountdown`);t&&(t.classList.remove(`warning`),t.style.display=`none`),N.currentConfirmToolCallId=null,N.currentConfirmSessionId=null}function Ho(){if(jo.length>0){Ga(Ao);return}Vo(),Ka(Ao)}function Uo(e){let t=Mo?.resolve;Mo=null,Io(),t&&t(e),Ho()}function Wo(e){let t={...e,sessionId:e.sessionId||null};return a.debug(`[SidePanel] showconfirm dialog:`,t.toolName,e),Mo&&Lo(Mo,t)?(a.debug(`[SidePanel] duplicate confirm request, ignored:`,t.toolCallId),Promise.resolve(!1)):jo.some(e=>Lo(e,t))?(a.debug(`[SidePanel] queued duplicate confirm, ignored:`,t.toolCallId),Promise.resolve(!1)):new Promise(e=>{jo.push({...t,resolve:e}),Ga(Ao),Mo&&Ko(),Ya(Ao)})}function Go(e,t=`single`){if(!Mo)return;let n=Mo.toolCallId,r=Mo.sessionId;Io(),chrome.runtime.sendMessage({type:`TOOL_CONFIRMATION_RESPONSE`,toolCallId:n,confirmed:e,scope:t,sessionId:r}).catch(e=>{a.debug(`[SidePanel] send confirmationresponse failed:`,e.message)}),Uo(e)}function Ko(){if(!Mo)return;let e=document.getElementById(`confirmMessage`);e&&(e.textContent=Ro(Mo))}function qo(e){let t=e?.toolCallId;if(!t)return;if(Mo&&Mo.toolCallId===t){a.debug(`[SidePanel] dismiss active confirm dialog (already settled by background):`,t),Uo(!1);return}let n=jo.findIndex(e=>e.toolCallId===t);if(n>=0){a.debug(`[SidePanel] drop queued confirm dialog (already settled by background):`,t);let[e]=jo.splice(n,1);e.resolve&&e.resolve(!1),Ko(),Ya(Ao)}}Wa(Ao,{present:Bo,pendingCount:()=>jo.length,refresh:()=>{Mo&&Ko()}});function Jo(){let e=document.getElementById(`confirmApproveOnceBtn`),t=document.getElementById(`confirmApproveLoopBtn`),n=document.getElementById(`confirmDenyBtn`);e&&e.addEventListener(`click`,()=>Go(!0,`single`)),t&&t.addEventListener(`click`,()=>Go(!0,`loop`)),n&&n.addEventListener(`click`,()=>Go(!1,`single`)),chrome.runtime.onMessage.addListener((e,t,n)=>e.type===`SHOW_CONFIRM_DIALOG`?(Wo(e.data),n({received:!0}),!1):e.type===`DISMISS_CONFIRM_DIALOG`?(qo(e.data),n({received:!0}),!1):!1)}var Yo=t({closeCurrentSession:()=>ac,handleDuplicateSession:()=>Xs,handleSessionSwitch:()=>Ys,newSession:()=>ns,renderSessionTabs:()=>es});n(`zh`,{session:{newSession:`新会话`,closeSession:`关闭会话`,taskCompleted:`任务已完成`,closeAllCount:`关闭全部({count})`,noMatch:`未找到匹配的会话`,rename:`重命名`,duplicate:`复制会话`,confirmCloseMessageWithTitle:`确定要关闭会话 "{title}" 吗?`,confirmCloseAllMessage:`确定要关闭所有 {count} 个会话吗?`,confirmCloseAllTitle:`关闭全部会话`,forkedFrom:`已从 "{title}" 分叉`,forkedSession:`已复制会话 "{title}"`,operationFailed:`操作失败:{message}`,sessionListTitle:`会话列表`,closeGroupAll:`全部关闭`,confirmCloseGroupMessage:`确定要关闭“{group}”下的 {count} 个会话吗?`,today:`今天`,yesterday:`昨天`,last7Days:`近 7 天`,earlier:`更早`,todayFormat:`今天 {hour}:{minute}`,yesterdayFormat:`昨天 {hour}:{minute}`,daysAgo:`{count} 天前`,archive:`归档会话`,archiveEntry:`归档区`,archiveEntryTitle:`查看归档会话`,archivePanelTitle:`归档区`,archiveSearchPlaceholder:`搜索归档会话...`,archiveEmpty:`暂无归档会话`,archiveNoMatch:`未找到匹配的归档会话`,archiveHint:`归档只是移出视野,随时可以恢复`,archiveBusyRunning:`该会话任务还在执行,完成后再归档`,archiveBusyQueued:`该会话还有排队任务,先清空队列再归档`,archived:`已归档到归档区`,archivedRestored:`已恢复会话「{title}」`,archivedAt:`归档于 {time}`,restore:`恢复`,restoreTitle:`恢复到会话列表`,deleteForever:`彻底删除`,confirmDeleteForeverTitle:`彻底删除会话`,confirmDeleteForeverMessage:`「{title}」将被彻底删除,消息与执行记录都无法恢复。确定继续吗?`,archiveDeleted:`已彻底删除会话「{title}」`,backToSessionList:`返回会话列表`}}),n(`en`,{session:{newSession:`New Session`,closeSession:`Close Session`,taskCompleted:`Task completed`,closeAllCount:`Close All ({count})`,noMatch:`No matching sessions found`,rename:`Rename`,duplicate:`Duplicate`,confirmCloseMessageWithTitle:`Are you sure you want to close session "{title}"?`,confirmCloseAllMessage:`Are you sure you want to close all {count} sessions?`,confirmCloseAllTitle:`Close All Sessions`,forkedFrom:`Forked from "{title}"`,forkedSession:`Duplicated session "{title}"`,operationFailed:`Operation failed: {message}`,sessionListTitle:`Sessions`,closeGroupAll:`Close all`,confirmCloseGroupMessage:`Are you sure you want to close {count} sessions in "{group}"?`,today:`Today`,yesterday:`Yesterday`,last7Days:`Last 7 days`,earlier:`Earlier`,todayFormat:`Today {hour}:{minute}`,yesterdayFormat:`Yesterday {hour}:{minute}`,daysAgo:`{count}d ago`,archive:`Archive session`,archiveEntry:`Archived`,archiveEntryTitle:`View archived sessions`,archivePanelTitle:`Archived sessions`,archiveSearchPlaceholder:`Search archived sessions...`,archiveEmpty:`No archived sessions`,archiveNoMatch:`No archived sessions found`,archiveHint:`Archiving only hides a session — you can restore it anytime`,archiveBusyRunning:`This session is still running. Archive it when it finishes`,archiveBusyQueued:`This session still has queued tasks. Clear the queue first`,archived:`Moved to archive`,archivedRestored:`Session "{title}" restored`,archivedAt:`Archived {time}`,restore:`Restore`,restoreTitle:`Restore to session list`,deleteForever:`Delete permanently`,confirmDeleteForeverTitle:`Delete session permanently`,confirmDeleteForeverMessage:`"{title}" will be permanently deleted. Messages and execution logs cannot be recovered. Continue?`,archiveDeleted:`Session "{title}" permanently deleted`,backToSessionList:`Back to sessions`}});var B={visible:!1,highlightIndex:-1,filteredSessions:[]},Xo={draggedId:null,sourceType:null};function Zo(e){if(!e)return``;let t=new Date(e),n=new Date,i=new Date(n.getFullYear(),n.getMonth(),n.getDate()).getTime(),a=t.getTime();if(a>=i)return r(`session.todayFormat`,{hour:String(t.getHours()).padStart(2,`0`),minute:String(t.getMinutes()).padStart(2,`0`)});if(a>=i-864e5)return r(`session.yesterdayFormat`,{hour:String(t.getHours()).padStart(2,`0`),minute:String(t.getMinutes()).padStart(2,`0`)});let o=Math.floor((i-a)/864e5);return o<=7?r(`session.daysAgo`,{count:o}):t.getFullYear()===n.getFullYear()?`${t.getMonth()+1}/${t.getDate()}`:`${t.getFullYear()}/${t.getMonth()+1}/${t.getDate()}`}function Qo(e){return e.sort((e,t)=>{let n=e.updatedAt?new Date(e.updatedAt).getTime():0;return(t.updatedAt?new Date(t.updatedAt).getTime():0)-n})}function $o(e){if(!e)return`earlier`;let t=new Date(e),n=new Date,r=new Date(n.getFullYear(),n.getMonth(),n.getDate()).getTime(),i=t.getTime();return i>=r?`today`:i>=r-864e5?`yesterday`:Math.floor((r-i)/864e5)<=7?`last7Days`:`earlier`}async function es(e=null){let t=e||await Fi();N.sessions=t.list,N.activeSessionId=t.activeSessionId;let n=document.getElementById(`sessionTabs`),i=document.getElementById(`sessionTabsScroll`),a=document.getElementById(`sessionTabsActions`);!n||!i||!a||(i.style.opacity=``,i.innerHTML=``,t.list.forEach(e=>{let t=document.createElement(`div`);t.className=`session-tab`,t.dataset.sessionId=e.id,e.id===N.activeSessionId&&t.classList.add(`active`),t.title=e.title;let n=document.createElement(`span`);n.className=`session-tab-title`,n.textContent=e.title||r(`session.newSession`),t.appendChild(n);let a=document.createElement(`span`);if(a.className=`session-tab-close`,a.innerHTML=`✕`,a.title=r(`session.closeSession`),a.addEventListener(`click`,async t=>{if(t.stopPropagation(),(e.id===N.activeSessionId?N.messageHistory?.length||0:e.messageHistory?.length||0)===0){ws(await Cs(e.id)),await ic();return}tc(e,async()=>{await ic()})}),t.appendChild(a),e.isGenerating||N.generatingSessionIds.has(e.id)){let e=document.createElement(`span`);e.className=`session-tab-indicator`,t.appendChild(e)}else if(N.completedSessionIds.has(e.id)&&e.id!==N.activeSessionId){let e=document.createElement(`span`);e.className=`session-tab-completed-indicator`,e.title=r(`session.taskCompleted`),t.appendChild(e)}let o=Kr(e.id);if(o>0){let e=document.createElement(`span`);e.className=`session-tab-queue-badge`,e.textContent=String(o>99?`99+`:o),e.title=r(`queue.badgeTitle`,{count:o}),t.appendChild(e)}t.addEventListener(`click`,async n=>{if(n.preventDefault(),e.id!==N.activeSessionId&&!Gs){Gs=!0,i.querySelectorAll(`.session-tab.active`).forEach(e=>e.classList.remove(`active`)),t.classList.add(`active`);try{await Ys(e.id)}finally{Gs=!1,N.activeSessionId!==e.id&&es({list:N.sessions,activeSessionId:N.activeSessionId})}}}),t.addEventListener(`contextmenu`,t=>{t.preventDefault(),nc(t,e)}),t.addEventListener(`mousedown`,async t=>{t.button===1&&(t.preventDefault(),t.stopPropagation(),ws(await Cs(e.id)),await ic())}),t.draggable=!0,t.addEventListener(`dragstart`,t=>ds(t,e.id)),t.addEventListener(`dragover`,e=>fs(e)),t.addEventListener(`dragleave`,e=>ps(e)),t.addEventListener(`drop`,t=>ms(t,e.id)),t.addEventListener(`dragend`,e=>hs(e)),i.appendChild(t)}),ts(),rs(),Os(),Ws(),$s(i),os(i),ss(i),us(i))}function ts(){let e=document.getElementById(`sessionTabsMore`);if(!e)return;let t=e.cloneNode(!0);e.parentNode.replaceChild(t,e),t.addEventListener(`click`,e=>{e.stopPropagation(),gs()})}async function ns(){let e=N.activeSessionId;await Ii();let t=await zi();N.activeSessionId=t.id,N.messageHistory=[],N.activeCompaction=null,Li(t),document.dispatchEvent(new CustomEvent(`session-switched`,{detail:{sessionId:t.id,previousSessionId:e}})),es()}function rs(){let e=document.getElementById(`sessionTabsAdd`);if(!e)return;let t=e.cloneNode(!0);e.parentNode.replaceChild(t,e),t.addEventListener(`click`,()=>ns())}var is=0,as=0;function os(e){let t=document.getElementById(`sessionTabsMore`);if(!t)return;let n=e.scrollWidth>e.clientWidth;t.style.display=n||is>0?`flex`:`none`}async function ss(e){let t=++as,n;try{n=await Gi()}catch{return}t===as&&(is=n.length,os(e))}var cs=null;function ls(){if(cs)return;let e=document.getElementById(`sessionTabsScroll`);e&&(cs=new ResizeObserver(()=>{requestAnimationFrame(()=>{os(e)})}),cs.observe(e))}function us(e){let t=e.querySelector(`.session-tab.active`);if(t){let n=t.offsetLeft,r=t.offsetWidth;e.scrollLeft=n-(e.clientWidth-r)/2}e.style.opacity=`1`}function ds(e,t){Xo.draggedId=t,Xo.sourceType=`tab`,e.dataTransfer.effectAllowed=`move`,e.dataTransfer.setData(`text/plain`,t),e.currentTarget.classList.add(`dragging`)}function fs(e){e.preventDefault(),e.dataTransfer.dropEffect=`move`,e.currentTarget.classList.add(`drag-over`)}function ps(e){e.currentTarget.classList.remove(`drag-over`)}async function ms(e,t){e.preventDefault(),e.currentTarget.classList.remove(`drag-over`);let n=Xo.draggedId;if(!n||n===t)return;let r=N.sessions||[],i=r.findIndex(e=>e.id===n),a=r.findIndex(e=>e.id===t);if(i===-1||a===-1)return;let o=[...r],[s]=o.splice(i,1);o.splice(a,0,s),N.sessions=o,await Ui(o.map(e=>e.id)),es()}function hs(e){e.currentTarget.classList.remove(`dragging`),document.querySelectorAll(`.session-tab.drag-over`).forEach(e=>e.classList.remove(`drag-over`)),Xo.draggedId=null,Xo.sourceType=null}function gs(){B.visible?vs():_s()}async function _s(){let e=document.getElementById(`sessionTabsMore`),t=document.getElementById(`sessionDropdown`);if(!e||!t)return;let n=await Fi();N.sessions=n.list,N.activeSessionId=n.activeSessionId,B.filteredSessions=Qo([...n.list]),B.highlightIndex=-1,B.visible=!0,Is(),bs(),t.classList.add(`show`);let r=document.getElementById(`sessionDropdownCloseBtn`);r&&(r.onclick=()=>vs());let i=document.getElementById(`sessionDropdownSearch`),a=document.getElementById(`sessionDropdownSearchClear`);i&&(i.value=B.lastSearchText||``,ys(),B.lastSearchText&&xs(B.lastSearchText),setTimeout(()=>i.focus(),50),i.oninput=()=>{B.lastSearchText=i.value,ys(),xs(i.value)},i.onkeydown=e=>{ks(e)}),a&&(a.onclick=()=>{i&&(i.value=``,B.lastSearchText=``,ys(),xs(``),i.focus())}),e.classList.add(`active`)}function vs(){let e=document.getElementById(`sessionTabsMore`),t=document.getElementById(`sessionDropdown`);t&&t.classList.remove(`show`),e&&e.classList.remove(`active`);let n=document.getElementById(`sessionDropdownSearch`);n&&(B.lastSearchText=n.value,n.oninput=null,n.onkeydown=null);let r=document.getElementById(`sessionDropdownSearchClear`);r&&(r.onclick=null),B.visible=!1,B.highlightIndex=-1,B.filteredSessions=[]}function ys(){let e=document.getElementById(`sessionDropdownSearch`),t=document.getElementById(`sessionDropdownSearchClear`);t&&e&&(t.style.display=e.value?`flex`:`none`)}function bs(){let e=document.getElementById(`sessionDropdownList`);if(!e)return;e.innerHTML=``;let t=document.getElementById(`sessionDropdownCloseAll`);if(t){let e=(N.sessions||[]).length;t.textContent=r(`session.closeAllCount`,{count:e})}if(B.filteredSessions.length===0){let t=document.createElement(`div`);t.className=`session-dropdown-empty`,t.textContent=r(`session.noMatch`),e.appendChild(t);return}let n={today:r(`session.today`),yesterday:r(`session.yesterday`),last7Days:r(`session.last7Days`),earlier:r(`session.earlier`)},i={};B.filteredSessions.forEach(e=>{let t=$o(e.updatedAt);i[t]=(i[t]||0)+1});let a=null;B.filteredSessions.forEach((t,o)=>{let s=$o(t.updatedAt);if(s!==a){a=s;let t=document.createElement(`div`);t.className=`session-dropdown-group-header`;let o=document.createElement(`span`);if(o.textContent=n[s]||s,t.appendChild(o),(i[s]||0)>0){let e=document.createElement(`button`);e.className=`session-dropdown-group-close`,e.textContent=r(`session.closeGroupAll`),e.onclick=e=>{e.stopPropagation(),Ds(s,n[s]||s)},t.appendChild(e)}e.appendChild(t)}let c=document.createElement(`div`);if(c.className=`session-dropdown-item`,c.dataset.sessionId=t.id,c.dataset.index=o,t.id===N.activeSessionId&&c.classList.add(`active`),o===B.highlightIndex&&c.classList.add(`highlighted`),N.completedSessionIds.has(t.id)&&t.id!==N.activeSessionId&&!t.isGenerating&&!N.generatingSessionIds.has(t.id)){let e=document.createElement(`span`);e.className=`session-dropdown-item-completed`,e.title=r(`session.taskCompleted`),c.appendChild(e)}let l=Kr(t.id);if(l>0){let e=document.createElement(`span`);e.className=`session-dropdown-item-queue`,e.textContent=String(l>99?`99+`:l),e.title=r(`queue.badgeTitle`,{count:l}),c.appendChild(e)}let u=document.createElement(`span`);u.className=`session-dropdown-item-icon`,u.innerHTML=`<svg width="13" height="13" 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>`,c.appendChild(u);let d=document.createElement(`span`);if(d.className=`session-dropdown-item-title`,d.textContent=t.title||r(`session.newSession`),d.title=t.title||r(`session.newSession`),c.appendChild(d),t.id===N.activeSessionId){let e=document.createElement(`span`);e.className=`session-dropdown-item-check`,e.innerHTML=`<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>`,c.appendChild(e)}let f=document.createElement(`span`);f.className=`session-dropdown-item-time`,f.textContent=Zo(t.updatedAt),c.appendChild(f);let p=document.createElement(`span`);p.className=`session-dropdown-item-actions`;let m=document.createElement(`span`);m.className=`session-dropdown-item-rename`,m.title=r(`session.rename`),m.innerHTML=`<svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>`,m.addEventListener(`click`,e=>{e.stopPropagation(),e.preventDefault(),ec(t)}),p.appendChild(m);let h=document.createElement(`span`);h.className=`session-dropdown-item-duplicate`,h.title=r(`session.duplicate`),h.innerHTML=`<svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="6" cy="6" r="2.5"/><circle cx="6" cy="18" r="2.5"/><circle cx="18" cy="6" r="2.5"/><path d="M6 8.5v7"/><path d="M18 8.5c0 4-6 3.5-6 3.5"/></svg>`,h.addEventListener(`click`,async e=>{e.stopPropagation(),e.preventDefault(),await Xs(t.id);let n=await Fi();N.sessions=n.list,N.activeSessionId=n.activeSessionId,xs(document.getElementById(`sessionDropdownSearch`)?.value||``)}),p.appendChild(h);let g=document.createElement(`span`);g.className=`session-dropdown-item-archive`,g.title=r(`session.archive`),g.innerHTML=`<svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 8v13H3V8"/><rect x="1" y="3" width="22" height="5"/><line x1="10" y1="12" x2="14" y2="12"/></svg>`,g.addEventListener(`click`,async e=>{e.stopPropagation(),e.preventDefault(),await Ps(t.id),xs(document.getElementById(`sessionDropdownSearch`)?.value||``)}),p.appendChild(g);let _=document.createElement(`span`);_.className=`session-dropdown-item-close`,_.innerHTML=`✕`,_.title=r(`session.closeSession`),_.addEventListener(`click`,async e=>{e.stopPropagation(),e.preventDefault(),await Ts(t.id)}),p.appendChild(_),c.appendChild(p),c.addEventListener(`click`,async e=>{e.preventDefault(),await Ss(t.id)}),e.appendChild(c)})}function xs(e){let t=N.sessions||[],n;if(!e.trim())n=[...t];else{let i=e.trim().toLowerCase();n=t.filter(e=>(e.title||r(`session.newSession`)).toLowerCase().includes(i))}B.filteredSessions=Qo(n),B.highlightIndex=-1,bs()}async function Ss(e){vs(),e!==N.activeSessionId&&await Ys(e)}async function Cs(e){let t=Kr(e)+Wr(e).length;return await Vi(e),t}function ws(e){e<=0||L(r(`queue.sessionDropped`,{count:e}),`info`,3e3)}async function Ts(e){let t=(N.sessions||[]).find(t=>t.id===e);t&&((e===N.activeSessionId?N.messageHistory?.length||0:t.messageHistory?.length||0)>0&&!await js(r(`session.confirmCloseMessageWithTitle`,{title:t.title}),r(`session.closeSession`))||(ws(await Cs(e)),await ic(),xs(document.getElementById(`sessionDropdownSearch`)?.value||``)))}async function Es(){let e=N.sessions||[];if(e.length===0||!await js(r(`session.confirmCloseAllMessage`,{count:e.length}),r(`session.confirmCloseAllTitle`)))return;let t=0;for(let n of e)t+=await Cs(n.id);ws(t),await ic(),xs(document.getElementById(`sessionDropdownSearch`)?.value||``)}async function Ds(e,t){let n=(N.sessions||[]).filter(t=>$o(t.updatedAt)===e);if(n.length===0||!await js(r(`session.confirmCloseGroupMessage`,{group:t,count:n.length}),r(`session.closeSession`)))return;let i=0;for(let e of n)i+=await Cs(e.id);ws(i),await ic(),xs(document.getElementById(`sessionDropdownSearch`)?.value||``)}function Os(){let e=document.getElementById(`sessionDropdownCloseAll`),t=document.getElementById(`sessionDropdown`);if(t){if(e){let t=e.cloneNode(!0);e.parentNode.replaceChild(t,e),t.addEventListener(`click`,async e=>{e.stopPropagation(),await Es()})}t.addEventListener(`click`,e=>{e.stopPropagation()})}}function ks(e){if(!B.visible)return;let t=B.filteredSessions.length;if(t===0){e.key===`Escape`&&vs();return}switch(e.key){case`ArrowDown`:e.preventDefault(),B.highlightIndex=Math.min(B.highlightIndex+1,t-1),bs(),As();break;case`ArrowUp`:e.preventDefault(),B.highlightIndex=Math.max(B.highlightIndex-1,0),bs(),As();break;case`Enter`:if(e.preventDefault(),B.highlightIndex>=0&&B.highlightIndex<t){let e=B.filteredSessions[B.highlightIndex];Ss(e.id)}break;case`Escape`:e.preventDefault(),vs();break}}function As(){let e=document.querySelector(`.session-dropdown-item.highlighted`);e&&e.scrollIntoView({block:`nearest`})}function js(e,t){return new Promise(t=>{let n=document.getElementById(`sessionDeleteModal`),r=document.getElementById(`sessionDeleteMessage`),i=document.getElementById(`sessionDeleteConfirmBtn`),a=document.getElementById(`sessionDeleteCancelBtn`),o=document.getElementById(`sessionDeleteCloseBtn`);if(!n||!r){t(!1);return}r.textContent=e;let s=()=>{n.classList.remove(`show`),i.removeEventListener(`click`,c),a.removeEventListener(`click`,l),o.removeEventListener(`click`,l)},c=()=>{s(),t(!0)},l=()=>{s(),t(!1)};i.addEventListener(`click`,c),a.addEventListener(`click`,l),o.addEventListener(`click`,l),n.classList.add(`show`)})}var Ms=``,Ns=!1;async function Ps(e){if(!e)return;let t=Ki(e);if(!t.ok){t.reason===`running`?L(r(`session.archiveBusyRunning`),`warning`):t.reason===`queued`&&L(r(`session.archiveBusyQueued`),`warning`);return}let n=e===N.activeSessionId,i=await qi(e);if(!i?.ok){i?.reason===`running`?L(r(`session.archiveBusyRunning`),`warning`):i?.reason===`queued`?L(r(`session.archiveBusyQueued`),`warning`):L(r(`session.operationFailed`,{message:i?.reason||`unknown`}),`error`);return}if(document.dispatchEvent(new CustomEvent(`session-archived`,{detail:{sessionId:e}})),n)await Fs(e);else{let e=await Fi();N.sessions=e.list,es(e)}await Is(),L(r(`session.archived`),`info`)}async function Fs(e){let t=Qo([...(await Fi()).list]).filter(t=>t.id!==e);if(t.length>0){await Ys(t[0].id);return}await zi(),await ic()}async function Is(){let e=document.getElementById(`sessionArchiveEntryCount`);if(!e)return;let t=await Gi();is=t.length;let n=document.getElementById(`sessionTabsScroll`);n&&os(n),t.length>0?(e.textContent=String(t.length>99?`99+`:t.length),e.hidden=!1):(e.textContent=``,e.hidden=!0)}async function Ls(){let e=document.getElementById(`sessionArchivePanel`);if(!e)return;Ws(),Ms=``;let t=document.getElementById(`sessionArchiveSearch`);t&&(t.value=``),zs(),await Bs(),e.classList.add(`show`),vs()}function Rs(){let e=document.getElementById(`sessionArchivePanel`);e&&e.classList.remove(`show`)}function zs(){let e=document.getElementById(`sessionArchiveSearchClear`);e&&(e.style.display=Ms?`flex`:`none`)}async function Bs(){let e=document.getElementById(`sessionArchiveList`);if(!e)return;let t=await Gi(),n=Ms.trim().toLowerCase(),i=n?t.filter(e=>(e.title||``).toLowerCase().includes(n)):t;if(e.innerHTML=``,i.length===0){let t=document.createElement(`div`);t.className=`session-dropdown-empty`,t.textContent=r(n?`session.archiveNoMatch`:`session.archiveEmpty`),e.appendChild(t);return}let a={today:r(`session.today`),yesterday:r(`session.yesterday`),last7Days:r(`session.last7Days`),earlier:r(`session.earlier`)},o=null;i.forEach(t=>{let n=$o(t.archivedAt);if(n!==o){o=n;let t=document.createElement(`div`);t.className=`session-dropdown-group-header`;let r=document.createElement(`span`);r.textContent=a[n]||n,t.appendChild(r),e.appendChild(t)}e.appendChild(Vs(t))})}function Vs(e){let t=document.createElement(`div`);t.className=`session-dropdown-item session-archive-item`,t.dataset.sessionId=e.id,t.title=e.title||r(`session.newSession`);let n=document.createElement(`span`);n.className=`session-dropdown-item-icon`,n.innerHTML=`<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 8v13H3V8"/><rect x="1" y="3" width="22" height="5"/><line x1="10" y1="12" x2="14" y2="12"/></svg>`,t.appendChild(n);let i=document.createElement(`span`);i.className=`session-dropdown-item-title`,i.textContent=e.title||r(`session.newSession`),t.appendChild(i);let a=document.createElement(`span`);a.className=`session-dropdown-item-time`,a.textContent=r(`session.archivedAt`,{time:Zo(e.archivedAt)}),t.appendChild(a);let o=document.createElement(`span`);o.className=`session-dropdown-item-actions`;let s=document.createElement(`span`);s.className=`session-dropdown-item-restore`,s.title=r(`session.restoreTitle`),s.innerHTML=`<svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 14 4 9 9 4"/><path d="M20 20v-7a4 4 0 0 0-4-4H4"/></svg>`,s.addEventListener(`click`,async t=>{t.stopPropagation(),await Hs(e.id)}),o.appendChild(s);let c=document.createElement(`span`);return c.className=`session-dropdown-item-delete`,c.title=r(`session.deleteForever`),c.innerHTML=`✕`,c.addEventListener(`click`,async t=>{t.stopPropagation(),await Us(e)}),o.appendChild(c),t.appendChild(o),t.addEventListener(`click`,async()=>{await Hs(e.id,{enter:!0})}),t}async function Hs(e,{enter:t=!1}={}){if(!await Ji(e)){L(r(`session.operationFailed`,{message:`not found`}),`error`),await Bs();return}let n=await Fi();N.sessions=n.list;let i=n.list.find(t=>t.id===e)?.title||r(`session.newSession`);Rs(),await Bs(),await Is(),t?await Ys(e):es(n),L(r(`session.archivedRestored`,{title:i}),`success`)}async function Us(e){let t=e.title||r(`session.newSession`);await js(r(`session.confirmDeleteForeverMessage`,{title:t}),r(`session.confirmDeleteForeverTitle`))&&(await Yi(e.id),await Bs(),await Is(),document.dispatchEvent(new CustomEvent(`session-deleted`,{detail:{sessionId:e.id}})),L(r(`session.archiveDeleted`,{title:t}),`success`))}function Ws(){if(Ns)return;let e=document.getElementById(`sessionArchivePanel`),t=document.getElementById(`sessionArchiveEntry`);if(!e||!t)return;Ns=!0,t.addEventListener(`click`,()=>{Ls()});let n=document.getElementById(`sessionArchiveBackBtn`);n&&n.addEventListener(`click`,()=>{Rs(),_s()});let r=document.getElementById(`sessionArchiveCloseBtn`);r&&r.addEventListener(`click`,()=>Rs());let i=document.getElementById(`sessionArchiveSearch`),a=document.getElementById(`sessionArchiveSearchClear`);i&&(i.addEventListener(`input`,()=>{Ms=i.value,zs(),Bs()}),i.addEventListener(`keydown`,e=>{e.key===`Escape`&&(e.stopPropagation(),Rs(),_s())})),a&&a.addEventListener(`click`,()=>{i&&(i.value=``,Ms=``,zs(),Bs(),i.focus())}),document.addEventListener(`session-archived`,()=>{e.classList.contains(`show`)&&Bs()}),document.addEventListener(`session-deleted`,()=>{e.classList.contains(`show`)&&Bs()})}var Gs=!1,Ks=500;function qs(e){let t=`scrollPosition_${e||`default`}`;chrome.storage.local.get([t],e=>{let n=document.getElementById(`chatContainer`);n&&e[t]!==void 0&&(n.scrollTop=e[t]),M(async()=>{let{updateScrollButtonState:e}=await Promise.resolve().then(()=>hS);return{updateScrollButtonState:e}},void 0).then(({updateScrollButtonState:e})=>e()).catch(()=>{})})}function Js(e,t){setTimeout(()=>{N.activeSessionId===e&&(Ht(t)||qs(e))},Ks)}async function Ys(e,{focusMessageId:t=null}={}){let n=N.activeSessionId;if(!await Bi(e))return;let r=`agentEnabledTools_${N.activeAgentId||`default`}`,i=`agentMcpClosedServers_${N.activeAgentId||`default`}`,[a,o,s,c]=await Promise.all([Fi(),chrome.storage.local.get([i,`ragTools`,`ragToolsIntroduced`]),chrome.storage.local.get([r,`enabledTools`]),N.activeAgentId?_t(N.activeAgentId):Promise.resolve(null)]);N.sessions=a.list,N.activeSessionId=e;let l=o.ragTools||[];N.mcpClosedServers=o[i]||[];let u=!!s[r],d=s[r]||s.enabledTools;if(u||d&&d.length>0){let e=Fa(l),t=d.filter(t=>e.has(t));if(u)N.enabledTools=t;else{let e=x.filter(e=>e.enabled&&!t.includes(e.id)).map(e=>e.id);N.enabledTools=[...t,...e]}let n=Pa(N.enabledTools,l,o.ragToolsIntroduced);N.enabledTools=n.tools,N.enabledTools.length!==d.length&&chrome.storage.local.set({[r]:N.enabledTools,...n.migrated?{ragToolsIntroduced:!0}:{}})}else{N.enabledTools=x.filter(e=>e.enabled).map(e=>e.id);let e=Pa(N.enabledTools,l,o.ragToolsIntroduced);N.enabledTools=e.tools,e.migrated&&chrome.storage.local.set({ragToolsIntroduced:!0,[r]:N.enabledTools})}N.activeAgentToolIds=c?c.toolIds:null,N.activeAgentMcpExcludedServerIds=c?c.mcpExcludedServerIds??null:null,document.dispatchEvent(new CustomEvent(`session-switched`,{detail:{sessionId:e,previousSessionId:n,...t?{skipScrollRestore:!0}:{}}})),Pi(e),es(a),Zs(),wT();try{let{refreshBookmarkPanel:e,updateBookmarkButtons:t}=await M(async()=>{let{refreshBookmarkPanel:e,updateBookmarkButtons:t}=await Promise.resolve().then(()=>Rm);return{refreshBookmarkPanel:e,updateBookmarkButtons:t}},void 0);e(),setTimeout(()=>t(),100)}catch{}let f=document.getElementById(`toolsPopupOverlay`);f&&f.classList.contains(`show`)&&(ba(),Oa(),ka()),Ma(),t&&Js(e,t)}async function Xs(e,t=null){if(e)try{let n=await Qi(e,t);await Ys(n.id),L(r(t?`session.forkedFrom`:`session.forkedSession`,{title:n.title}),`success`)}catch(e){a.error(`[SessionUI] copy/forksession failed:`,e),L(r(`session.operationFailed`,{message:e.message}),`error`)}}function Zs(){let e=document.querySelector(`.model-display`);e&&N.currentModel&&(e.textContent=N.currentModel);let t=document.getElementById(`enableToolsBtn`);t&&(t.checked=N.useTools);let n=document.getElementById(`tempIconValue`);n&&N.temperature!==void 0&&(n.textContent=N.temperature.toFixed(2))}var Qs=new WeakSet;function $s(e){Qs.has(e)||(Qs.add(e),e.addEventListener(`wheel`,t=>{e.scrollWidth<=e.clientWidth||(t.preventDefault(),e.scrollLeft+=t.deltaY)},{passive:!1}))}function ec(e){let t=document.getElementById(`sessionRenameModal`),n=document.getElementById(`sessionRenameInput`),r=document.getElementById(`sessionRenameConfirmBtn`),i=document.getElementById(`sessionRenameCancelBtn`),a=document.getElementById(`sessionRenameCloseBtn`);if(!t||!n)return;n.value=e.title;let o=()=>{t.classList.remove(`show`),r.removeEventListener(`click`,s),i.removeEventListener(`click`,c),a.removeEventListener(`click`,c)},s=async()=>{let t=n.value.trim();if(t&&t!==e.title){await Hi(e.id,t),es();let n=await Fi();N.sessions=n.list,N.activeSessionId=n.activeSessionId,xs(document.getElementById(`sessionDropdownSearch`)?.value||``)}o()},c=()=>{o()};r.addEventListener(`click`,s),i.addEventListener(`click`,c),a.addEventListener(`click`,c),n.onkeydown=e=>{e.key===`Enter`?s():e.key===`Escape`&&c()},t.classList.add(`show`),setTimeout(()=>{n.focus(),n.select()},50)}function tc(e,t){let n=document.getElementById(`sessionDeleteModal`),i=document.getElementById(`sessionDeleteMessage`),a=document.getElementById(`sessionDeleteConfirmBtn`),o=document.getElementById(`sessionDeleteCancelBtn`),s=document.getElementById(`sessionDeleteCloseBtn`);if(!n||!i)return;i.textContent=r(`session.confirmCloseMessageWithTitle`,{title:e.title});let c=()=>{n.classList.remove(`show`),a.removeEventListener(`click`,l),o.removeEventListener(`click`,u),s.removeEventListener(`click`,u)},l=async()=>{ws(await Cs(e.id)),t&&await t(),c()},u=()=>{c()};a.addEventListener(`click`,l),o.addEventListener(`click`,u),s.addEventListener(`click`,u),n.classList.add(`show`),requestAnimationFrame(()=>a.focus())}function nc(e,t){let n=document.querySelector(`.session-context-menu`);n&&n.remove();let i=document.createElement(`div`);i.className=`session-context-menu`,i.style.left=e.clientX+`px`,i.style.top=e.clientY+`px`;let a=rc(r(`session.rename`),`<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>`,()=>{i.remove(),ec(t)});i.appendChild(a);let o=rc(r(`session.duplicate`),`<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="6" cy="6" r="2.5"/><circle cx="6" cy="18" r="2.5"/><circle cx="18" cy="6" r="2.5"/><path d="M6 8.5v7"/><path d="M18 8.5c0 4-6 3.5-6 3.5"/></svg>`,()=>{i.remove(),Xs(t.id)});i.appendChild(o);let s=rc(r(`session.archive`),`<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 8v13H3V8"/><rect x="1" y="3" width="22" height="5"/><line x1="10" y1="12" x2="14" y2="12"/></svg>`,async()=>{i.remove(),await Ps(t.id)});i.appendChild(s);let c=rc(r(`session.closeSession`),`<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>`,async()=>{if(i.remove(),(t.id===N.activeSessionId?N.messageHistory?.length||0:t.messageHistory?.length||0)===0){ws(await Cs(t.id)),await ic();return}tc(t,async()=>{await ic()})},`danger`);i.appendChild(c),document.body.appendChild(i);let l=e=>{i.contains(e.target)||(i.remove(),document.removeEventListener(`click`,l))};setTimeout(()=>document.addEventListener(`click`,l),0)}function rc(e,t=``,n,r=``){let i=document.createElement(`div`);return i.className=`session-context-menu-item `+r,t?i.innerHTML=`${t}<span>${e}</span>`:i.textContent=e,i.addEventListener(`click`,n),i}async function ic(){let e=N.activeSessionId,t=await Fi();t.activeSessionId||(await zi(),t=await Fi()),N.activeSessionId=t.activeSessionId,N.sessions=t.list;let n=t.list.find(e=>e.id===t.activeSessionId);if(N.messageHistory=n&&n.messageHistory||[],N.activeCompaction=n?.contextCompaction||null,Li(n),N.activeAgentId=n&&n.agentId||null,N.activeAgentId){let e=await _t(N.activeAgentId);N.activeAgentToolIds=e?e.toolIds:null,N.activeAgentMcpExcludedServerIds=e?e.mcpExcludedServerIds??null:null}else N.activeAgentToolIds=null,N.activeAgentMcpExcludedServerIds=null;document.dispatchEvent(new CustomEvent(`session-switched`,{detail:{sessionId:N.activeSessionId,previousSessionId:e}})),es(),await wT()}async function ac(){let e=N.activeSessionId;if(!e)return;let t=N.sessions?.find(t=>t.id===e);if(t){if((N.messageHistory?.length||0)===0){ws(await Cs(e)),await ic();return}tc(t,async()=>{await ic()})}}document.addEventListener(`generating-state-changed`,()=>{es()}),document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,ls):ls(),[`<svg viewBox="0 0 16 16" fill="currentColor">`,`<path d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 0 1 0 1.5h-1.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-1.5a.75.75 0 0 1 1.5 0v1.5A1.75 1.75 0 0 1 9.25 16h-7.5A1.75 1.75 0 0 1 0 14.25zM5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0 1 14.25 11h-7.5A1.75 1.75 0 0 1 5 9.25zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25z"/>`,`</svg>`].join(``),[`<svg viewBox="0 0 16 16" fill="currentColor">`,`<path d="M12.146.146a.5.5 0 0 1 .708 0l2.5 2.5a.5.5 0 0 1 0 .708l-10 10a.5.5 0 0 1-.168.11l-5 2a.5.5 0 0 1-.65-.65l2-5a.5.5 0 0 1 .11-.168l10-10zM11.207 2.5 13.5 4.793 14.793 3.5 12.5 1.207 11.207 2.5zm1.586 3L10.5 3.207 4 9.707V10h.5a.5.5 0 0 1 .5.5v.5h.5a.5.5 0 0 1 .5.5v.5h.293l6.5-6.5zm-9.761 5.175-.106.106-1.528 3.821 3.821-1.528.106-.106A.5.5 0 0 1 5 12h.5a.5.5 0 0 1 .5.5v.5a.5.5 0 0 1-.5.5h-.5a.5.5 0 0 1-.468-.325z"/>`,`</svg>`].join(``),[`<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="10"></circle>`,`<polyline points="12 6 12 12 16 14"></polyline>`,`</svg>`].join(``),[`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">`,`<line x1="18" y1="6" x2="6" y2="18"></line>`,`<line x1="6" y1="6" x2="18" y2="18"></line>`,`</svg>`].join(``),[`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">`,`<polyline points="7 13 12 18 17 13"></polyline>`,`<polyline points="7 6 12 11 17 6"></polyline>`,`</svg>`].join(``);var oc=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>`,sc=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>`,cc=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>`,lc=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>`,uc=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>`,dc=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>`;[`<svg class="tool-call-icon exec" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">`,`<polyline points="4 17 10 11 4 5"/><line x1="12" y1="19" x2="20" y2="19"/>`,`</svg>`].join(``),[`<svg class="tool-call-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">`,`<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>`,`<polyline points="14 2 14 8 20 8"/>`,`</svg>`].join(``),[`<svg class="tool-call-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">`,`<circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/>`,`</svg>`].join(``),[`<svg class="tool-call-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">`,`<path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/>`,`</svg>`].join(``),n(`zh`,{uiProto:{defaultTitle:`原型`,optimizePrompt:`请帮我优化这个UI原型界面 {id}({title}),`,loadFailed:`加载失败`,noDescription:`暂无描述`,previewInPanel:`面板内预览`,continueOptimizeTitle:`继续优化`,downloadPrototype:`下载原型`,confirmDeleteTitle:`确认删除`,confirmDeleteMessage:`确定删除原型 "{title}" 吗?此操作不可撤销。`,deleteFailed:`删除失败: {message}`,justNow:`刚刚`,minutesAgo:`{count} 分钟前`,hoursAgo:`{count} 小时前`}}),n(`en`,{uiProto:{defaultTitle:`Prototype`,optimizePrompt:`Please help me optimize this UI prototype {id} ({title}), `,loadFailed:`Load failed`,noDescription:`No description`,previewInPanel:`Preview in panel`,continueOptimizeTitle:`Continue optimizing`,downloadPrototype:`Download prototype`,confirmDeleteTitle:`Confirm delete`,confirmDeleteMessage:`Are you sure you want to delete prototype "{title}"? This action cannot be undone.`,deleteFailed:`Delete failed: {message}`,justNow:`Just now`,minutesAgo:`{count} minutes ago`,hoursAgo:`{count} hours ago`}});var fc=null,pc=1,mc=.25,hc=2,gc=.1;function _c(e){let t=e.trim();return/^\s*<!DOCTYPE\s/i.test(t)||/^\s*<html[\s>]/i.test(t)?/<\/head>/i.test(t)?t.replace(/<\/head>/i,`<style>html,body{overflow:auto!important;height:auto!important;}</style></head>`):/<body[\s>]/i.test(t)?t.replace(/<body([\s>])/i,`<body$1<style>html,body{overflow:auto!important;height:auto!important;}</style>`):t:`<!DOCTYPE html>
|
|
60
|
+
`,e.addEventListener(`click`,()=>Co(-1)),g.appendChild(e);let t=document.getElementById(`clarifyCustomInput`);t&&g.appendChild(t)}let _=document.getElementById(`clarifyCustomInput`);_&&_.classList.remove(`show`);let v=document.getElementById(`clarifyAdditionalInfo`);v&&v.classList.toggle(`show`,o);let y=document.getElementById(`clarifyCustomTextarea`);y&&(y.value=``);let b=document.getElementById(`clarifyAdditionalTextarea`);b&&(b.value=``),l.classList.add(`show`);let x=document.querySelector(`#clarifyContainer .clarify-content`),S=document.querySelector(`#clarifyContainer .clarify-header`);return x&&(x.scrollTop=0),S&&S.classList.remove(`scrolled`),to=null,no=!1,co(),oo(s),a.debug(`[SidePanel] clarification dialogshown:`,e.toolCallId,t),!0}function ho(){if(eo)return!0;if($a.length===0)return!1;let e=$a.shift();return mo(e)?(eo=e,Za(Qa,e),!0):(a.error(`[SidePanel] clarify overlay missing, settle as unanswered:`,e.toolCallId),go(e),L(r(`clarify.dropped`),`warning`),!1)}function go(e){Promise.resolve(chrome.runtime.sendMessage({type:`CLARIFY_RESPONSE`,toolCallId:e.toolCallId,selectedOption:-1,customInput:``,additionalInfo:``})).catch(e=>{a.debug(`[SidePanel] send unanswered clarify response failed:`,e?.message)})}function _o(){if($a.length>0){Ga(Qa);return}vo(),Ka(Qa)}function vo(){let e=document.getElementById(`clarifyOverlay`);e&&e.classList.remove(`show`),N.currentClarifyToolCallId=null,N.currentClarifySessionId=null,so()}function yo(){eo=null,_o()}function bo(e,t){return!!e.toolCallId&&e.toolCallId===t.toolCallId&&(e.sessionId||null)===(t.sessionId||null)&&e.question===t.question}function xo(e){let t={...e,sessionId:e.sessionId||null};if(a.debug(`[SidePanel] showclarification dialog:`,t.toolCallId,e),eo&&bo(eo,t)){a.debug(`[SidePanel] duplicate clarify request, ignored:`,t.toolCallId);return}if($a.some(e=>bo(e,t))){a.debug(`[SidePanel] queued duplicate clarify, ignored:`,t.toolCallId);return}$a.push(t),Ga(Qa),po(),Ya(Qa)}function So(){if(eo){yo();return}vo()}function Co(e){document.querySelectorAll(`.clarify-option-item`).forEach(e=>{e.classList.remove(`selected`),e.setAttribute(`aria-checked`,`false`),e.setAttribute(`tabindex`,`-1`)});let t=document.querySelector(`.clarify-option-item[data-index="${e}"]`);t&&(t.classList.add(`selected`),t.setAttribute(`aria-checked`,`true`),t.setAttribute(`tabindex`,`0`));let n=document.getElementById(`clarifyCustomInput`);if(n)if(e===-1){n.classList.add(`show`);let e=document.getElementById(`clarifyCustomTextarea`);e&&e.focus()}else n.classList.remove(`show`);a.debug(`[SidePanel] selectclarificationselect :`,e)}function wo(){if(!eo){a.error(`[SidePanel] no has currenttool callID`);return}let e=eo.toolCallId,t=eo.sessionId,n=-1;document.querySelectorAll(`.clarify-option-item`).forEach((e,t)=>{e.classList.contains(`selected`)&&(n=parseInt(e.dataset.index))});let r=document.getElementById(`clarifyCustomTextarea`),i=r?r.value.trim():``,o=document.getElementById(`clarifyAdditionalTextarea`),s=o?o.value.trim():``,c={type:`CLARIFY_RESPONSE`,toolCallId:e,sessionId:t,selectedOption:n,customInput:i,additionalInfo:s};a.debug(`[SidePanel] send clarificationresponse:`,c),chrome.runtime.sendMessage(c),yo()}function To(){if(eo){let e={type:`CLARIFY_RESPONSE`,toolCallId:eo.toolCallId,sessionId:eo.sessionId,selectedOption:-1,customInput:``,additionalInfo:``};chrome.runtime.sendMessage(e)}So()}function Eo(e){return e?.reason===`timeout`&&e?.defaultOption||null}function Do(e){a.debug(`[SidePanel] received clarificationtimeoutnotification:`,e);let t=e?.toolCallId;if(!t){if(e?.sessionId&&N.currentClarifySessionId&&e.sessionId!==N.currentClarifySessionId){a.debug(`[SidePanel] clarificationtimeoutfrom othersession,ignore`);return}if(!eo)return;Oo(Eo(e));return}if(eo&&eo.toolCallId===t){Oo(Eo(e));return}let n=$a.findIndex(e=>e.toolCallId===t);n>=0&&(a.debug(`[SidePanel] drop queued clarify (already settled by background):`,t),$a.splice(n,1),po(),Ya(Qa))}function Oo(e=null){let t=eo?.question;yo(),L(e?r(`clarify.timedOutDefaulted`,{option:e}):`${r(`clarify.timedOut`)}${t?`:${t}`:``}`,`warning`),io(`error`)}Wa(Qa,{present:ho,pendingCount:()=>$a.length,refresh:po});function ko(){let e=document.getElementById(`clarifyConfirmBtn`);e&&e.addEventListener(`click`,wo);let t=document.getElementById(`clarifyCancelBtn`);t&&t.addEventListener(`click`,To);let n=document.getElementById(`clarifyExtendBtn`);n&&n.addEventListener(`click`,lo);let r=document.querySelector(`#clarifyContainer .clarify-content`),i=document.querySelector(`#clarifyContainer .clarify-header`);r&&i&&r.addEventListener(`scroll`,()=>{i.classList.toggle(`scrolled`,r.scrollTop>2)}),chrome.runtime.onMessage.addListener((e,t,n)=>{e.type===`SHOW_CLARIFY_DIALOG`?(a.debug(`[SidePanel] received clarificationrequested :`,e,`currently activesession:`,N.activeSessionId),xo(e.data),n({success:!0})):e.type===`PLAY_NOTIFICATION_SOUND`?(a.debug(`[SidePanel] recei to play soundrequested :`,e),io(e.soundType),n({success:!0})):e.type===`CLARIFY_TIMEOUT`?Do(e):e.type===`CLARIFY_EXTENDED`&&uo(e)}),a.debug(`[SidePanel] clarification dialogeventinitializing`)}var Ao=Ba.CONFIRM,jo=[],Mo=null,No=null,Po=null;function Fo(e){let t=Math.floor(e/60),n=e%60;return`${t}:${String(n).padStart(2,`0`)}`}function Io(){No&&=(clearInterval(No),null),Po&&=(clearTimeout(Po),null)}function Lo(e,t){return!!e.toolCallId&&e.toolCallId===t.toolCallId&&(e.sessionId||null)===(t.sessionId||null)&&JSON.stringify(e.args??null)===JSON.stringify(t.args??null)}function Ro(e){let t=e.message||r(`dialog.confirmAction`,{name:e.toolLabel||e.toolName}),n=jo.length,i=Xa(Ao),a=t;return n>0&&(a+=` ${r(`dialog.pendingQueue`,{count:n})}`),i>0&&(a+=` ${r(`dialog.otherPending`,{count:i})}`),a}function zo(e){let{toolName:t,toolLabel:n,args:i,timeout:o=3e5}=e;N.currentConfirmToolCallId=e.toolCallId,N.currentConfirmSessionId=e.sessionId||null;let s=document.getElementById(`confirmOverlay`);if(!s)return!1;document.getElementById(`confirmToolName`).textContent=n||t;let c=document.getElementById(`confirmArgsSummary`);if(c&&i){let e=Object.entries(i).filter(([e,t])=>t!=null&&t!==``).slice(0,5);e.length>0?(c.innerHTML=e.map(([e,t])=>{let n=typeof t==`string`?t:JSON.stringify(t),r=n.length>80?n.substring(0,80)+`...`:n;return`<span class="confirm-arg" style="margin-right: 8px;"${n.length>80?` title="${n.replace(/"/g,`"`)}"`:``}><strong>${e}:</strong> ${r}</span>`}).join(`、 `),c.style.display=`block`):c.style.display=`none`}let l=document.getElementById(`confirmMessage`);l&&(l.textContent=Ro(e)),Io();let u=Math.floor(o/1e3),d=document.getElementById(`confirmCountdownText`),f=document.getElementById(`confirmCountdown`);return d&&f&&(f.classList.remove(`warning`),f.style.display=`flex`,d.textContent=r(`dialog.remainingTime`,{time:Fo(u)}),No=setInterval(()=>{if(u--,u<=0){clearInterval(No),No=null,d.textContent=r(`dialog.remainingTime`,{time:`0:00`});return}d.textContent=r(`dialog.remainingTime`,{time:Fo(u)}),u<=30&&f.classList.add(`warning`)},1e3)),s.style.display=`flex`,Po=setTimeout(()=>{a.debug(`[SidePanel] confirm dialogtimeout,autodeny`),Go(!1,`single`)},o),!0}function Bo(){if(Mo)return!0;if(jo.length===0)return!1;let e=jo.shift();return zo(e)?(Mo=e,Za(Ao,e),!0):(e.resolve&&e.resolve(!1),!1)}function Vo(){let e=document.getElementById(`confirmOverlay`);e&&(e.style.display=`none`);let t=document.getElementById(`confirmCountdown`);t&&(t.classList.remove(`warning`),t.style.display=`none`),N.currentConfirmToolCallId=null,N.currentConfirmSessionId=null}function Ho(){if(jo.length>0){Ga(Ao);return}Vo(),Ka(Ao)}function Uo(e){let t=Mo?.resolve;Mo=null,Io(),t&&t(e),Ho()}function Wo(e){let t={...e,sessionId:e.sessionId||null};return a.debug(`[SidePanel] showconfirm dialog:`,t.toolName,e),Mo&&Lo(Mo,t)?(a.debug(`[SidePanel] duplicate confirm request, ignored:`,t.toolCallId),Promise.resolve(!1)):jo.some(e=>Lo(e,t))?(a.debug(`[SidePanel] queued duplicate confirm, ignored:`,t.toolCallId),Promise.resolve(!1)):new Promise(e=>{jo.push({...t,resolve:e}),Ga(Ao),Mo&&Ko(),Ya(Ao)})}function Go(e,t=`single`){if(!Mo)return;let n=Mo.toolCallId,r=Mo.sessionId;Io(),chrome.runtime.sendMessage({type:`TOOL_CONFIRMATION_RESPONSE`,toolCallId:n,confirmed:e,scope:t,sessionId:r}).catch(e=>{a.debug(`[SidePanel] send confirmationresponse failed:`,e.message)}),Uo(e)}function Ko(){if(!Mo)return;let e=document.getElementById(`confirmMessage`);e&&(e.textContent=Ro(Mo))}function qo(e){let t=e?.toolCallId;if(!t)return;if(Mo&&Mo.toolCallId===t){a.debug(`[SidePanel] dismiss active confirm dialog (already settled by background):`,t),Uo(!1);return}let n=jo.findIndex(e=>e.toolCallId===t);if(n>=0){a.debug(`[SidePanel] drop queued confirm dialog (already settled by background):`,t);let[e]=jo.splice(n,1);e.resolve&&e.resolve(!1),Ko(),Ya(Ao)}}Wa(Ao,{present:Bo,pendingCount:()=>jo.length,refresh:()=>{Mo&&Ko()}});function Jo(){let e=document.getElementById(`confirmApproveOnceBtn`),t=document.getElementById(`confirmApproveLoopBtn`),n=document.getElementById(`confirmDenyBtn`);e&&e.addEventListener(`click`,()=>Go(!0,`single`)),t&&t.addEventListener(`click`,()=>Go(!0,`loop`)),n&&n.addEventListener(`click`,()=>Go(!1,`single`)),chrome.runtime.onMessage.addListener((e,t,n)=>e.type===`SHOW_CONFIRM_DIALOG`?(Wo(e.data),n({received:!0}),!1):e.type===`DISMISS_CONFIRM_DIALOG`?(qo(e.data),n({received:!0}),!1):!1)}var Yo=t({closeCurrentSession:()=>ac,handleDuplicateSession:()=>Xs,handleSessionSwitch:()=>Ys,newSession:()=>ns,renderSessionTabs:()=>es});n(`zh`,{session:{newSession:`新会话`,closeSession:`关闭会话`,taskCompleted:`任务已完成`,closeAllCount:`关闭全部({count})`,noMatch:`未找到匹配的会话`,rename:`重命名`,duplicate:`复制会话`,confirmCloseMessageWithTitle:`确定要关闭会话 "{title}" 吗?`,confirmCloseAllMessage:`确定要关闭所有 {count} 个会话吗?`,confirmCloseAllTitle:`关闭全部会话`,forkedFrom:`已从 "{title}" 分叉`,forkedSession:`已复制会话 "{title}"`,operationFailed:`操作失败:{message}`,sessionListTitle:`会话列表`,closeGroupAll:`全部关闭`,confirmCloseGroupMessage:`确定要关闭“{group}”下的 {count} 个会话吗?`,today:`今天`,yesterday:`昨天`,last7Days:`近 7 天`,earlier:`更早`,todayFormat:`今天 {hour}:{minute}`,yesterdayFormat:`昨天 {hour}:{minute}`,daysAgo:`{count} 天前`,archive:`归档会话`,archiveEntry:`归档区`,archiveEntryTitle:`查看归档会话`,archivePanelTitle:`归档区`,archiveSearchPlaceholder:`搜索归档会话...`,archiveEmpty:`暂无归档会话`,archiveNoMatch:`未找到匹配的归档会话`,archiveHint:`归档只是移出视野,随时可以恢复`,archiveBusyRunning:`该会话任务还在执行,完成后再归档`,archiveBusyQueued:`该会话还有排队任务,先清空队列再归档`,archived:`已归档到归档区`,archivedRestored:`已恢复会话「{title}」`,archivedAt:`归档于 {time}`,restore:`恢复`,restoreTitle:`恢复到会话列表`,deleteForever:`彻底删除`,confirmDeleteForeverTitle:`彻底删除会话`,confirmDeleteForeverMessage:`「{title}」将被彻底删除,消息与执行记录都无法恢复。确定继续吗?`,archiveDeleted:`已彻底删除会话「{title}」`,backToSessionList:`返回会话列表`}}),n(`en`,{session:{newSession:`New Session`,closeSession:`Close Session`,taskCompleted:`Task completed`,closeAllCount:`Close All ({count})`,noMatch:`No matching sessions found`,rename:`Rename`,duplicate:`Duplicate`,confirmCloseMessageWithTitle:`Are you sure you want to close session "{title}"?`,confirmCloseAllMessage:`Are you sure you want to close all {count} sessions?`,confirmCloseAllTitle:`Close All Sessions`,forkedFrom:`Forked from "{title}"`,forkedSession:`Duplicated session "{title}"`,operationFailed:`Operation failed: {message}`,sessionListTitle:`Sessions`,closeGroupAll:`Close all`,confirmCloseGroupMessage:`Are you sure you want to close {count} sessions in "{group}"?`,today:`Today`,yesterday:`Yesterday`,last7Days:`Last 7 days`,earlier:`Earlier`,todayFormat:`Today {hour}:{minute}`,yesterdayFormat:`Yesterday {hour}:{minute}`,daysAgo:`{count}d ago`,archive:`Archive session`,archiveEntry:`Archived`,archiveEntryTitle:`View archived sessions`,archivePanelTitle:`Archived sessions`,archiveSearchPlaceholder:`Search archived sessions...`,archiveEmpty:`No archived sessions`,archiveNoMatch:`No archived sessions found`,archiveHint:`Archiving only hides a session — you can restore it anytime`,archiveBusyRunning:`This session is still running. Archive it when it finishes`,archiveBusyQueued:`This session still has queued tasks. Clear the queue first`,archived:`Moved to archive`,archivedRestored:`Session "{title}" restored`,archivedAt:`Archived {time}`,restore:`Restore`,restoreTitle:`Restore to session list`,deleteForever:`Delete permanently`,confirmDeleteForeverTitle:`Delete session permanently`,confirmDeleteForeverMessage:`"{title}" will be permanently deleted. Messages and execution logs cannot be recovered. Continue?`,archiveDeleted:`Session "{title}" permanently deleted`,backToSessionList:`Back to sessions`}});var B={visible:!1,highlightIndex:-1,filteredSessions:[]},Xo={draggedId:null,sourceType:null};function Zo(e){if(!e)return``;let t=new Date(e),n=new Date,i=new Date(n.getFullYear(),n.getMonth(),n.getDate()).getTime(),a=t.getTime();if(a>=i)return r(`session.todayFormat`,{hour:String(t.getHours()).padStart(2,`0`),minute:String(t.getMinutes()).padStart(2,`0`)});if(a>=i-864e5)return r(`session.yesterdayFormat`,{hour:String(t.getHours()).padStart(2,`0`),minute:String(t.getMinutes()).padStart(2,`0`)});let o=Math.floor((i-a)/864e5);return o<=7?r(`session.daysAgo`,{count:o}):t.getFullYear()===n.getFullYear()?`${t.getMonth()+1}/${t.getDate()}`:`${t.getFullYear()}/${t.getMonth()+1}/${t.getDate()}`}function Qo(e){return e.sort((e,t)=>{let n=e.updatedAt?new Date(e.updatedAt).getTime():0;return(t.updatedAt?new Date(t.updatedAt).getTime():0)-n})}function $o(e){if(!e)return`earlier`;let t=new Date(e),n=new Date,r=new Date(n.getFullYear(),n.getMonth(),n.getDate()).getTime(),i=t.getTime();return i>=r?`today`:i>=r-864e5?`yesterday`:Math.floor((r-i)/864e5)<=7?`last7Days`:`earlier`}async function es(e=null){let t=e||await Fi();N.sessions=t.list,N.activeSessionId=t.activeSessionId;let n=document.getElementById(`sessionTabs`),i=document.getElementById(`sessionTabsScroll`),a=document.getElementById(`sessionTabsActions`);!n||!i||!a||(i.style.opacity=``,i.innerHTML=``,t.list.forEach(e=>{let t=document.createElement(`div`);t.className=`session-tab`,t.dataset.sessionId=e.id,e.id===N.activeSessionId&&t.classList.add(`active`),t.title=e.title;let n=document.createElement(`span`);n.className=`session-tab-title`,n.textContent=e.title||r(`session.newSession`),t.appendChild(n);let a=document.createElement(`span`);if(a.className=`session-tab-close`,a.innerHTML=`✕`,a.title=r(`session.closeSession`),a.addEventListener(`click`,async t=>{if(t.stopPropagation(),(e.id===N.activeSessionId?N.messageHistory?.length||0:e.messageHistory?.length||0)===0){ws(await Cs(e.id)),await ic();return}tc(e,async()=>{await ic()})}),t.appendChild(a),e.isGenerating||N.generatingSessionIds.has(e.id)){let e=document.createElement(`span`);e.className=`session-tab-indicator`,t.appendChild(e)}else if(N.completedSessionIds.has(e.id)&&e.id!==N.activeSessionId){let e=document.createElement(`span`);e.className=`session-tab-completed-indicator`,e.title=r(`session.taskCompleted`),t.appendChild(e)}let o=Kr(e.id);if(o>0){let e=document.createElement(`span`);e.className=`session-tab-queue-badge`,e.textContent=String(o>99?`99+`:o),e.title=r(`queue.badgeTitle`,{count:o}),t.appendChild(e)}t.addEventListener(`click`,async n=>{if(n.preventDefault(),e.id!==N.activeSessionId&&!Gs){Gs=!0,i.querySelectorAll(`.session-tab.active`).forEach(e=>e.classList.remove(`active`)),t.classList.add(`active`);try{await Ys(e.id)}finally{Gs=!1,N.activeSessionId!==e.id&&es({list:N.sessions,activeSessionId:N.activeSessionId})}}}),t.addEventListener(`contextmenu`,t=>{t.preventDefault(),nc(t,e)}),t.addEventListener(`mousedown`,async t=>{t.button===1&&(t.preventDefault(),t.stopPropagation(),ws(await Cs(e.id)),await ic())}),t.draggable=!0,t.addEventListener(`dragstart`,t=>ds(t,e.id)),t.addEventListener(`dragover`,e=>fs(e)),t.addEventListener(`dragleave`,e=>ps(e)),t.addEventListener(`drop`,t=>ms(t,e.id)),t.addEventListener(`dragend`,e=>hs(e)),i.appendChild(t)}),ts(),rs(),Os(),Ws(),$s(i),os(i),ss(i),us(i))}function ts(){let e=document.getElementById(`sessionTabsMore`);if(!e)return;let t=e.cloneNode(!0);e.parentNode.replaceChild(t,e),t.addEventListener(`click`,e=>{e.stopPropagation(),gs()})}async function ns(){let e=N.activeSessionId;await Ii();let t=await zi();N.activeSessionId=t.id,N.messageHistory=[],N.activeCompaction=null,Li(t),document.dispatchEvent(new CustomEvent(`session-switched`,{detail:{sessionId:t.id,previousSessionId:e}})),es()}function rs(){let e=document.getElementById(`sessionTabsAdd`);if(!e)return;let t=e.cloneNode(!0);e.parentNode.replaceChild(t,e),t.addEventListener(`click`,()=>ns())}var is=0,as=0;function os(e){let t=document.getElementById(`sessionTabsMore`);if(!t)return;let n=e.scrollWidth>e.clientWidth;t.style.display=n||is>0?`flex`:`none`}async function ss(e){let t=++as,n;try{n=await Gi()}catch{return}t===as&&(is=n.length,os(e))}var cs=null;function ls(){if(cs)return;let e=document.getElementById(`sessionTabsScroll`);e&&(cs=new ResizeObserver(()=>{requestAnimationFrame(()=>{os(e)})}),cs.observe(e))}function us(e){let t=e.querySelector(`.session-tab.active`);if(t){let n=t.offsetLeft,r=t.offsetWidth;e.scrollLeft=n-(e.clientWidth-r)/2}e.style.opacity=`1`}function ds(e,t){Xo.draggedId=t,Xo.sourceType=`tab`,e.dataTransfer.effectAllowed=`move`,e.dataTransfer.setData(`text/plain`,t),e.currentTarget.classList.add(`dragging`)}function fs(e){e.preventDefault(),e.dataTransfer.dropEffect=`move`,e.currentTarget.classList.add(`drag-over`)}function ps(e){e.currentTarget.classList.remove(`drag-over`)}async function ms(e,t){e.preventDefault(),e.currentTarget.classList.remove(`drag-over`);let n=Xo.draggedId;if(!n||n===t)return;let r=N.sessions||[],i=r.findIndex(e=>e.id===n),a=r.findIndex(e=>e.id===t);if(i===-1||a===-1)return;let o=[...r],[s]=o.splice(i,1);o.splice(a,0,s),N.sessions=o,await Ui(o.map(e=>e.id)),es()}function hs(e){e.currentTarget.classList.remove(`dragging`),document.querySelectorAll(`.session-tab.drag-over`).forEach(e=>e.classList.remove(`drag-over`)),Xo.draggedId=null,Xo.sourceType=null}function gs(){B.visible?vs():_s()}async function _s(){let e=document.getElementById(`sessionTabsMore`),t=document.getElementById(`sessionDropdown`);if(!e||!t)return;let n=await Fi();N.sessions=n.list,N.activeSessionId=n.activeSessionId,B.filteredSessions=Qo([...n.list]),B.highlightIndex=-1,B.visible=!0,Is(),bs(),t.classList.add(`show`);let r=document.getElementById(`sessionDropdownCloseBtn`);r&&(r.onclick=()=>vs());let i=document.getElementById(`sessionDropdownSearch`),a=document.getElementById(`sessionDropdownSearchClear`);i&&(i.value=B.lastSearchText||``,ys(),B.lastSearchText&&xs(B.lastSearchText),setTimeout(()=>i.focus(),50),i.oninput=()=>{B.lastSearchText=i.value,ys(),xs(i.value)},i.onkeydown=e=>{ks(e)}),a&&(a.onclick=()=>{i&&(i.value=``,B.lastSearchText=``,ys(),xs(``),i.focus())}),e.classList.add(`active`)}function vs(){let e=document.getElementById(`sessionTabsMore`),t=document.getElementById(`sessionDropdown`);t&&t.classList.remove(`show`),e&&e.classList.remove(`active`);let n=document.getElementById(`sessionDropdownSearch`);n&&(B.lastSearchText=n.value,n.oninput=null,n.onkeydown=null);let r=document.getElementById(`sessionDropdownSearchClear`);r&&(r.onclick=null),B.visible=!1,B.highlightIndex=-1,B.filteredSessions=[]}function ys(){let e=document.getElementById(`sessionDropdownSearch`),t=document.getElementById(`sessionDropdownSearchClear`);t&&e&&(t.style.display=e.value?`flex`:`none`)}function bs(){let e=document.getElementById(`sessionDropdownList`);if(!e)return;e.innerHTML=``;let t=document.getElementById(`sessionDropdownCloseAll`);if(t){let e=(N.sessions||[]).length;t.textContent=r(`session.closeAllCount`,{count:e})}if(B.filteredSessions.length===0){let t=document.createElement(`div`);t.className=`session-dropdown-empty`,t.textContent=r(`session.noMatch`),e.appendChild(t);return}let n={today:r(`session.today`),yesterday:r(`session.yesterday`),last7Days:r(`session.last7Days`),earlier:r(`session.earlier`)},i={};B.filteredSessions.forEach(e=>{let t=$o(e.updatedAt);i[t]=(i[t]||0)+1});let a=null;B.filteredSessions.forEach((t,o)=>{let s=$o(t.updatedAt);if(s!==a){a=s;let t=document.createElement(`div`);t.className=`session-dropdown-group-header`;let o=document.createElement(`span`);if(o.textContent=n[s]||s,t.appendChild(o),(i[s]||0)>0){let e=document.createElement(`button`);e.className=`session-dropdown-group-close`,e.textContent=r(`session.closeGroupAll`),e.onclick=e=>{e.stopPropagation(),Ds(s,n[s]||s)},t.appendChild(e)}e.appendChild(t)}let c=document.createElement(`div`);if(c.className=`session-dropdown-item`,c.dataset.sessionId=t.id,c.dataset.index=o,t.id===N.activeSessionId&&c.classList.add(`active`),o===B.highlightIndex&&c.classList.add(`highlighted`),N.completedSessionIds.has(t.id)&&t.id!==N.activeSessionId&&!t.isGenerating&&!N.generatingSessionIds.has(t.id)){let e=document.createElement(`span`);e.className=`session-dropdown-item-completed`,e.title=r(`session.taskCompleted`),c.appendChild(e)}let l=Kr(t.id);if(l>0){let e=document.createElement(`span`);e.className=`session-dropdown-item-queue`,e.textContent=String(l>99?`99+`:l),e.title=r(`queue.badgeTitle`,{count:l}),c.appendChild(e)}let u=document.createElement(`span`);u.className=`session-dropdown-item-icon`,u.innerHTML=`<svg width="13" height="13" 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>`,c.appendChild(u);let d=document.createElement(`span`);if(d.className=`session-dropdown-item-title`,d.textContent=t.title||r(`session.newSession`),d.title=t.title||r(`session.newSession`),c.appendChild(d),t.id===N.activeSessionId){let e=document.createElement(`span`);e.className=`session-dropdown-item-check`,e.innerHTML=`<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>`,c.appendChild(e)}let f=document.createElement(`span`);f.className=`session-dropdown-item-time`,f.textContent=Zo(t.updatedAt),c.appendChild(f);let p=document.createElement(`span`);p.className=`session-dropdown-item-actions`;let m=document.createElement(`span`);m.className=`session-dropdown-item-rename`,m.title=r(`session.rename`),m.innerHTML=`<svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>`,m.addEventListener(`click`,e=>{e.stopPropagation(),e.preventDefault(),ec(t)}),p.appendChild(m);let h=document.createElement(`span`);h.className=`session-dropdown-item-duplicate`,h.title=r(`session.duplicate`),h.innerHTML=`<svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="6" cy="6" r="2.5"/><circle cx="6" cy="18" r="2.5"/><circle cx="18" cy="6" r="2.5"/><path d="M6 8.5v7"/><path d="M18 8.5c0 4-6 3.5-6 3.5"/></svg>`,h.addEventListener(`click`,async e=>{e.stopPropagation(),e.preventDefault(),await Xs(t.id);let n=await Fi();N.sessions=n.list,N.activeSessionId=n.activeSessionId,xs(document.getElementById(`sessionDropdownSearch`)?.value||``)}),p.appendChild(h);let g=document.createElement(`span`);g.className=`session-dropdown-item-archive`,g.title=r(`session.archive`),g.innerHTML=`<svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 8v13H3V8"/><rect x="1" y="3" width="22" height="5"/><line x1="10" y1="12" x2="14" y2="12"/></svg>`,g.addEventListener(`click`,async e=>{e.stopPropagation(),e.preventDefault(),await Ps(t.id),xs(document.getElementById(`sessionDropdownSearch`)?.value||``)}),p.appendChild(g);let _=document.createElement(`span`);_.className=`session-dropdown-item-close`,_.innerHTML=`✕`,_.title=r(`session.closeSession`),_.addEventListener(`click`,async e=>{e.stopPropagation(),e.preventDefault(),await Ts(t.id)}),p.appendChild(_),c.appendChild(p),c.addEventListener(`click`,async e=>{e.preventDefault(),await Ss(t.id)}),e.appendChild(c)})}function xs(e){let t=N.sessions||[],n;if(!e.trim())n=[...t];else{let i=e.trim().toLowerCase();n=t.filter(e=>(e.title||r(`session.newSession`)).toLowerCase().includes(i))}B.filteredSessions=Qo(n),B.highlightIndex=-1,bs()}async function Ss(e){vs(),e!==N.activeSessionId&&await Ys(e)}async function Cs(e){let t=Kr(e)+Wr(e).length;return await Vi(e),t}function ws(e){e<=0||L(r(`queue.sessionDropped`,{count:e}),`info`,3e3)}async function Ts(e){let t=(N.sessions||[]).find(t=>t.id===e);t&&((e===N.activeSessionId?N.messageHistory?.length||0:t.messageHistory?.length||0)>0&&!await js(r(`session.confirmCloseMessageWithTitle`,{title:t.title}),r(`session.closeSession`))||(ws(await Cs(e)),await ic(),xs(document.getElementById(`sessionDropdownSearch`)?.value||``)))}async function Es(){let e=N.sessions||[];if(e.length===0||!await js(r(`session.confirmCloseAllMessage`,{count:e.length}),r(`session.confirmCloseAllTitle`)))return;let t=0;for(let n of e)t+=await Cs(n.id);ws(t),await ic(),xs(document.getElementById(`sessionDropdownSearch`)?.value||``)}async function Ds(e,t){let n=(N.sessions||[]).filter(t=>$o(t.updatedAt)===e);if(n.length===0||!await js(r(`session.confirmCloseGroupMessage`,{group:t,count:n.length}),r(`session.closeSession`)))return;let i=0;for(let e of n)i+=await Cs(e.id);ws(i),await ic(),xs(document.getElementById(`sessionDropdownSearch`)?.value||``)}function Os(){let e=document.getElementById(`sessionDropdownCloseAll`),t=document.getElementById(`sessionDropdown`);if(t){if(e){let t=e.cloneNode(!0);e.parentNode.replaceChild(t,e),t.addEventListener(`click`,async e=>{e.stopPropagation(),await Es()})}t.addEventListener(`click`,e=>{e.stopPropagation()})}}function ks(e){if(!B.visible)return;let t=B.filteredSessions.length;if(t===0){e.key===`Escape`&&vs();return}switch(e.key){case`ArrowDown`:e.preventDefault(),B.highlightIndex=Math.min(B.highlightIndex+1,t-1),bs(),As();break;case`ArrowUp`:e.preventDefault(),B.highlightIndex=Math.max(B.highlightIndex-1,0),bs(),As();break;case`Enter`:if(e.preventDefault(),B.highlightIndex>=0&&B.highlightIndex<t){let e=B.filteredSessions[B.highlightIndex];Ss(e.id)}break;case`Escape`:e.preventDefault(),vs();break}}function As(){let e=document.querySelector(`.session-dropdown-item.highlighted`);e&&e.scrollIntoView({block:`nearest`})}function js(e,t){return new Promise(t=>{let n=document.getElementById(`sessionDeleteModal`),r=document.getElementById(`sessionDeleteMessage`),i=document.getElementById(`sessionDeleteConfirmBtn`),a=document.getElementById(`sessionDeleteCancelBtn`),o=document.getElementById(`sessionDeleteCloseBtn`);if(!n||!r){t(!1);return}r.textContent=e;let s=()=>{n.classList.remove(`show`),i.removeEventListener(`click`,c),a.removeEventListener(`click`,l),o.removeEventListener(`click`,l)},c=()=>{s(),t(!0)},l=()=>{s(),t(!1)};i.addEventListener(`click`,c),a.addEventListener(`click`,l),o.addEventListener(`click`,l),n.classList.add(`show`)})}var Ms=``,Ns=!1;async function Ps(e){if(!e)return;let t=Ki(e);if(!t.ok){t.reason===`running`?L(r(`session.archiveBusyRunning`),`warning`):t.reason===`queued`&&L(r(`session.archiveBusyQueued`),`warning`);return}let n=e===N.activeSessionId,i=await qi(e);if(!i?.ok){i?.reason===`running`?L(r(`session.archiveBusyRunning`),`warning`):i?.reason===`queued`?L(r(`session.archiveBusyQueued`),`warning`):L(r(`session.operationFailed`,{message:i?.reason||`unknown`}),`error`);return}if(document.dispatchEvent(new CustomEvent(`session-archived`,{detail:{sessionId:e}})),n)await Fs(e);else{let e=await Fi();N.sessions=e.list,es(e)}await Is(),L(r(`session.archived`),`info`)}async function Fs(e){let t=Qo([...(await Fi()).list]).filter(t=>t.id!==e);if(t.length>0){await Ys(t[0].id);return}await zi(),await ic()}async function Is(){let e=document.getElementById(`sessionArchiveEntryCount`);if(!e)return;let t=await Gi();is=t.length;let n=document.getElementById(`sessionTabsScroll`);n&&os(n),t.length>0?(e.textContent=String(t.length>99?`99+`:t.length),e.hidden=!1):(e.textContent=``,e.hidden=!0)}async function Ls(){let e=document.getElementById(`sessionArchivePanel`);if(!e)return;Ws(),Ms=``;let t=document.getElementById(`sessionArchiveSearch`);t&&(t.value=``),zs(),await Bs(),e.classList.add(`show`),vs()}function Rs(){let e=document.getElementById(`sessionArchivePanel`);e&&e.classList.remove(`show`)}function zs(){let e=document.getElementById(`sessionArchiveSearchClear`);e&&(e.style.display=Ms?`flex`:`none`)}async function Bs(){let e=document.getElementById(`sessionArchiveList`);if(!e)return;let t=await Gi(),n=Ms.trim().toLowerCase(),i=n?t.filter(e=>(e.title||``).toLowerCase().includes(n)):t;if(e.innerHTML=``,i.length===0){let t=document.createElement(`div`);t.className=`session-dropdown-empty`,t.textContent=r(n?`session.archiveNoMatch`:`session.archiveEmpty`),e.appendChild(t);return}let a={today:r(`session.today`),yesterday:r(`session.yesterday`),last7Days:r(`session.last7Days`),earlier:r(`session.earlier`)},o=null;i.forEach(t=>{let n=$o(t.archivedAt);if(n!==o){o=n;let t=document.createElement(`div`);t.className=`session-dropdown-group-header`;let r=document.createElement(`span`);r.textContent=a[n]||n,t.appendChild(r),e.appendChild(t)}e.appendChild(Vs(t))})}function Vs(e){let t=document.createElement(`div`);t.className=`session-dropdown-item session-archive-item`,t.dataset.sessionId=e.id,t.title=e.title||r(`session.newSession`);let n=document.createElement(`span`);n.className=`session-dropdown-item-icon`,n.innerHTML=`<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 8v13H3V8"/><rect x="1" y="3" width="22" height="5"/><line x1="10" y1="12" x2="14" y2="12"/></svg>`,t.appendChild(n);let i=document.createElement(`span`);i.className=`session-dropdown-item-title`,i.textContent=e.title||r(`session.newSession`),t.appendChild(i);let a=document.createElement(`span`);a.className=`session-dropdown-item-time`,a.textContent=r(`session.archivedAt`,{time:Zo(e.archivedAt)}),t.appendChild(a);let o=document.createElement(`span`);o.className=`session-dropdown-item-actions`;let s=document.createElement(`span`);s.className=`session-dropdown-item-restore`,s.title=r(`session.restoreTitle`),s.innerHTML=`<svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 14 4 9 9 4"/><path d="M20 20v-7a4 4 0 0 0-4-4H4"/></svg>`,s.addEventListener(`click`,async t=>{t.stopPropagation(),await Hs(e.id)}),o.appendChild(s);let c=document.createElement(`span`);return c.className=`session-dropdown-item-delete`,c.title=r(`session.deleteForever`),c.innerHTML=`✕`,c.addEventListener(`click`,async t=>{t.stopPropagation(),await Us(e)}),o.appendChild(c),t.appendChild(o),t.addEventListener(`click`,async()=>{await Hs(e.id,{enter:!0})}),t}async function Hs(e,{enter:t=!1}={}){if(!await Ji(e)){L(r(`session.operationFailed`,{message:`not found`}),`error`),await Bs();return}let n=await Fi();N.sessions=n.list;let i=n.list.find(t=>t.id===e)?.title||r(`session.newSession`);Rs(),await Bs(),await Is(),t?await Ys(e):es(n),L(r(`session.archivedRestored`,{title:i}),`success`)}async function Us(e){let t=e.title||r(`session.newSession`);await js(r(`session.confirmDeleteForeverMessage`,{title:t}),r(`session.confirmDeleteForeverTitle`))&&(await Yi(e.id),await Bs(),await Is(),document.dispatchEvent(new CustomEvent(`session-deleted`,{detail:{sessionId:e.id}})),L(r(`session.archiveDeleted`,{title:t}),`success`))}function Ws(){if(Ns)return;let e=document.getElementById(`sessionArchivePanel`),t=document.getElementById(`sessionArchiveEntry`);if(!e||!t)return;Ns=!0,t.addEventListener(`click`,()=>{Ls()});let n=document.getElementById(`sessionArchiveBackBtn`);n&&n.addEventListener(`click`,()=>{Rs(),_s()});let r=document.getElementById(`sessionArchiveCloseBtn`);r&&r.addEventListener(`click`,()=>Rs());let i=document.getElementById(`sessionArchiveSearch`),a=document.getElementById(`sessionArchiveSearchClear`);i&&(i.addEventListener(`input`,()=>{Ms=i.value,zs(),Bs()}),i.addEventListener(`keydown`,e=>{e.key===`Escape`&&(e.stopPropagation(),Rs(),_s())})),a&&a.addEventListener(`click`,()=>{i&&(i.value=``,Ms=``,zs(),Bs(),i.focus())}),document.addEventListener(`session-archived`,()=>{e.classList.contains(`show`)&&Bs()}),document.addEventListener(`session-deleted`,()=>{e.classList.contains(`show`)&&Bs()})}var Gs=!1,Ks=500;function qs(e){let t=`scrollPosition_${e||`default`}`;chrome.storage.local.get([t],e=>{let n=document.getElementById(`chatContainer`);n&&e[t]!==void 0&&(n.scrollTop=e[t]),M(async()=>{let{updateScrollButtonState:e}=await Promise.resolve().then(()=>hS);return{updateScrollButtonState:e}},void 0).then(({updateScrollButtonState:e})=>e()).catch(()=>{})})}function Js(e,t){setTimeout(()=>{N.activeSessionId===e&&(Ut(t)||qs(e))},Ks)}async function Ys(e,{focusMessageId:t=null}={}){let n=N.activeSessionId;if(!await Bi(e))return;let r=`agentEnabledTools_${N.activeAgentId||`default`}`,i=`agentMcpClosedServers_${N.activeAgentId||`default`}`,[a,o,s,c]=await Promise.all([Fi(),chrome.storage.local.get([i,`ragTools`,`ragToolsIntroduced`]),chrome.storage.local.get([r,`enabledTools`]),N.activeAgentId?vt(N.activeAgentId):Promise.resolve(null)]);N.sessions=a.list,N.activeSessionId=e;let l=o.ragTools||[];N.mcpClosedServers=o[i]||[];let u=!!s[r],d=s[r]||s.enabledTools;if(u||d&&d.length>0){let e=Fa(l),t=d.filter(t=>e.has(t));if(u)N.enabledTools=t;else{let e=x.filter(e=>e.enabled&&!t.includes(e.id)).map(e=>e.id);N.enabledTools=[...t,...e]}let n=Pa(N.enabledTools,l,o.ragToolsIntroduced);N.enabledTools=n.tools,N.enabledTools.length!==d.length&&chrome.storage.local.set({[r]:N.enabledTools,...n.migrated?{ragToolsIntroduced:!0}:{}})}else{N.enabledTools=x.filter(e=>e.enabled).map(e=>e.id);let e=Pa(N.enabledTools,l,o.ragToolsIntroduced);N.enabledTools=e.tools,e.migrated&&chrome.storage.local.set({ragToolsIntroduced:!0,[r]:N.enabledTools})}N.activeAgentToolIds=c?c.toolIds:null,N.activeAgentMcpExcludedServerIds=c?c.mcpExcludedServerIds??null:null,document.dispatchEvent(new CustomEvent(`session-switched`,{detail:{sessionId:e,previousSessionId:n,...t?{skipScrollRestore:!0}:{}}})),Pi(e),es(a),Zs(),wT();try{let{refreshBookmarkPanel:e,updateBookmarkButtons:t}=await M(async()=>{let{refreshBookmarkPanel:e,updateBookmarkButtons:t}=await Promise.resolve().then(()=>Rm);return{refreshBookmarkPanel:e,updateBookmarkButtons:t}},void 0);e(),setTimeout(()=>t(),100)}catch{}let f=document.getElementById(`toolsPopupOverlay`);f&&f.classList.contains(`show`)&&(ba(),Oa(),ka()),Ma(),t&&Js(e,t)}async function Xs(e,t=null){if(e)try{let n=await Qi(e,t);await Ys(n.id),L(r(t?`session.forkedFrom`:`session.forkedSession`,{title:n.title}),`success`)}catch(e){a.error(`[SessionUI] copy/forksession failed:`,e),L(r(`session.operationFailed`,{message:e.message}),`error`)}}function Zs(){let e=document.querySelector(`.model-display`);e&&N.currentModel&&(e.textContent=N.currentModel);let t=document.getElementById(`enableToolsBtn`);t&&(t.checked=N.useTools);let n=document.getElementById(`tempIconValue`);n&&N.temperature!==void 0&&(n.textContent=N.temperature.toFixed(2))}var Qs=new WeakSet;function $s(e){Qs.has(e)||(Qs.add(e),e.addEventListener(`wheel`,t=>{e.scrollWidth<=e.clientWidth||(t.preventDefault(),e.scrollLeft+=t.deltaY)},{passive:!1}))}function ec(e){let t=document.getElementById(`sessionRenameModal`),n=document.getElementById(`sessionRenameInput`),r=document.getElementById(`sessionRenameConfirmBtn`),i=document.getElementById(`sessionRenameCancelBtn`),a=document.getElementById(`sessionRenameCloseBtn`);if(!t||!n)return;n.value=e.title;let o=()=>{t.classList.remove(`show`),r.removeEventListener(`click`,s),i.removeEventListener(`click`,c),a.removeEventListener(`click`,c)},s=async()=>{let t=n.value.trim();if(t&&t!==e.title){await Hi(e.id,t),es();let n=await Fi();N.sessions=n.list,N.activeSessionId=n.activeSessionId,xs(document.getElementById(`sessionDropdownSearch`)?.value||``)}o()},c=()=>{o()};r.addEventListener(`click`,s),i.addEventListener(`click`,c),a.addEventListener(`click`,c),n.onkeydown=e=>{e.key===`Enter`?s():e.key===`Escape`&&c()},t.classList.add(`show`),setTimeout(()=>{n.focus(),n.select()},50)}function tc(e,t){let n=document.getElementById(`sessionDeleteModal`),i=document.getElementById(`sessionDeleteMessage`),a=document.getElementById(`sessionDeleteConfirmBtn`),o=document.getElementById(`sessionDeleteCancelBtn`),s=document.getElementById(`sessionDeleteCloseBtn`);if(!n||!i)return;i.textContent=r(`session.confirmCloseMessageWithTitle`,{title:e.title});let c=()=>{n.classList.remove(`show`),a.removeEventListener(`click`,l),o.removeEventListener(`click`,u),s.removeEventListener(`click`,u)},l=async()=>{ws(await Cs(e.id)),t&&await t(),c()},u=()=>{c()};a.addEventListener(`click`,l),o.addEventListener(`click`,u),s.addEventListener(`click`,u),n.classList.add(`show`),requestAnimationFrame(()=>a.focus())}function nc(e,t){let n=document.querySelector(`.session-context-menu`);n&&n.remove();let i=document.createElement(`div`);i.className=`session-context-menu`,i.style.left=e.clientX+`px`,i.style.top=e.clientY+`px`;let a=rc(r(`session.rename`),`<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>`,()=>{i.remove(),ec(t)});i.appendChild(a);let o=rc(r(`session.duplicate`),`<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="6" cy="6" r="2.5"/><circle cx="6" cy="18" r="2.5"/><circle cx="18" cy="6" r="2.5"/><path d="M6 8.5v7"/><path d="M18 8.5c0 4-6 3.5-6 3.5"/></svg>`,()=>{i.remove(),Xs(t.id)});i.appendChild(o);let s=rc(r(`session.archive`),`<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 8v13H3V8"/><rect x="1" y="3" width="22" height="5"/><line x1="10" y1="12" x2="14" y2="12"/></svg>`,async()=>{i.remove(),await Ps(t.id)});i.appendChild(s);let c=rc(r(`session.closeSession`),`<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>`,async()=>{if(i.remove(),(t.id===N.activeSessionId?N.messageHistory?.length||0:t.messageHistory?.length||0)===0){ws(await Cs(t.id)),await ic();return}tc(t,async()=>{await ic()})},`danger`);i.appendChild(c),document.body.appendChild(i);let l=e=>{i.contains(e.target)||(i.remove(),document.removeEventListener(`click`,l))};setTimeout(()=>document.addEventListener(`click`,l),0)}function rc(e,t=``,n,r=``){let i=document.createElement(`div`);return i.className=`session-context-menu-item `+r,t?i.innerHTML=`${t}<span>${e}</span>`:i.textContent=e,i.addEventListener(`click`,n),i}async function ic(){let e=N.activeSessionId,t=await Fi();t.activeSessionId||(await zi(),t=await Fi()),N.activeSessionId=t.activeSessionId,N.sessions=t.list;let n=t.list.find(e=>e.id===t.activeSessionId);if(N.messageHistory=n&&n.messageHistory||[],N.activeCompaction=n?.contextCompaction||null,Li(n),N.activeAgentId=n&&n.agentId||null,N.activeAgentId){let e=await vt(N.activeAgentId);N.activeAgentToolIds=e?e.toolIds:null,N.activeAgentMcpExcludedServerIds=e?e.mcpExcludedServerIds??null:null}else N.activeAgentToolIds=null,N.activeAgentMcpExcludedServerIds=null;document.dispatchEvent(new CustomEvent(`session-switched`,{detail:{sessionId:N.activeSessionId,previousSessionId:e}})),es(),await wT()}async function ac(){let e=N.activeSessionId;if(!e)return;let t=N.sessions?.find(t=>t.id===e);if(t){if((N.messageHistory?.length||0)===0){ws(await Cs(e)),await ic();return}tc(t,async()=>{await ic()})}}document.addEventListener(`generating-state-changed`,()=>{es()}),document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,ls):ls(),[`<svg viewBox="0 0 16 16" fill="currentColor">`,`<path d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 0 1 0 1.5h-1.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-1.5a.75.75 0 0 1 1.5 0v1.5A1.75 1.75 0 0 1 9.25 16h-7.5A1.75 1.75 0 0 1 0 14.25zM5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0 1 14.25 11h-7.5A1.75 1.75 0 0 1 5 9.25zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25z"/>`,`</svg>`].join(``),[`<svg viewBox="0 0 16 16" fill="currentColor">`,`<path d="M12.146.146a.5.5 0 0 1 .708 0l2.5 2.5a.5.5 0 0 1 0 .708l-10 10a.5.5 0 0 1-.168.11l-5 2a.5.5 0 0 1-.65-.65l2-5a.5.5 0 0 1 .11-.168l10-10zM11.207 2.5 13.5 4.793 14.793 3.5 12.5 1.207 11.207 2.5zm1.586 3L10.5 3.207 4 9.707V10h.5a.5.5 0 0 1 .5.5v.5h.5a.5.5 0 0 1 .5.5v.5h.293l6.5-6.5zm-9.761 5.175-.106.106-1.528 3.821 3.821-1.528.106-.106A.5.5 0 0 1 5 12h.5a.5.5 0 0 1 .5.5v.5a.5.5 0 0 1-.5.5h-.5a.5.5 0 0 1-.468-.325z"/>`,`</svg>`].join(``),[`<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="10"></circle>`,`<polyline points="12 6 12 12 16 14"></polyline>`,`</svg>`].join(``),[`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">`,`<line x1="18" y1="6" x2="6" y2="18"></line>`,`<line x1="6" y1="6" x2="18" y2="18"></line>`,`</svg>`].join(``),[`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">`,`<polyline points="7 13 12 18 17 13"></polyline>`,`<polyline points="7 6 12 11 17 6"></polyline>`,`</svg>`].join(``);var oc=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>`,sc=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>`,cc=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>`,lc=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>`,uc=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>`,dc=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>`;[`<svg class="tool-call-icon exec" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">`,`<polyline points="4 17 10 11 4 5"/><line x1="12" y1="19" x2="20" y2="19"/>`,`</svg>`].join(``),[`<svg class="tool-call-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">`,`<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>`,`<polyline points="14 2 14 8 20 8"/>`,`</svg>`].join(``),[`<svg class="tool-call-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">`,`<circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/>`,`</svg>`].join(``),[`<svg class="tool-call-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">`,`<path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/>`,`</svg>`].join(``),n(`zh`,{uiProto:{defaultTitle:`原型`,optimizePrompt:`请帮我优化这个UI原型界面 {id}({title}),`,loadFailed:`加载失败`,noDescription:`暂无描述`,previewInPanel:`面板内预览`,continueOptimizeTitle:`继续优化`,downloadPrototype:`下载原型`,confirmDeleteTitle:`确认删除`,confirmDeleteMessage:`确定删除原型 "{title}" 吗?此操作不可撤销。`,deleteFailed:`删除失败: {message}`,justNow:`刚刚`,minutesAgo:`{count} 分钟前`,hoursAgo:`{count} 小时前`}}),n(`en`,{uiProto:{defaultTitle:`Prototype`,optimizePrompt:`Please help me optimize this UI prototype {id} ({title}), `,loadFailed:`Load failed`,noDescription:`No description`,previewInPanel:`Preview in panel`,continueOptimizeTitle:`Continue optimizing`,downloadPrototype:`Download prototype`,confirmDeleteTitle:`Confirm delete`,confirmDeleteMessage:`Are you sure you want to delete prototype "{title}"? This action cannot be undone.`,deleteFailed:`Delete failed: {message}`,justNow:`Just now`,minutesAgo:`{count} minutes ago`,hoursAgo:`{count} hours ago`}});var fc=null,pc=1,mc=.25,hc=2,gc=.1;function _c(e){let t=e.trim();return/^\s*<!DOCTYPE\s/i.test(t)||/^\s*<html[\s>]/i.test(t)?/<\/head>/i.test(t)?t.replace(/<\/head>/i,`<style>html,body{overflow:auto!important;height:auto!important;}</style></head>`):/<body[\s>]/i.test(t)?t.replace(/<body([\s>])/i,`<body$1<style>html,body{overflow:auto!important;height:auto!important;}</style>`):t:`<!DOCTYPE html>
|
|
61
61
|
<html>
|
|
62
62
|
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head>
|
|
63
63
|
<body style="margin:0;padding:0;overflow:auto;">${t}</body>
|
|
@@ -91,7 +91,7 @@ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,i,l as a,n a
|
|
|
91
91
|
</button>
|
|
92
92
|
</div>
|
|
93
93
|
</div>
|
|
94
|
-
`}).join(``),t.querySelectorAll(`.prototype-library-item`).forEach(e=>{let t=e.querySelector(`.prototype-library-item-info`),n=e.querySelector(`.prototype-library-item-open`),i=e.querySelector(`.prototype-library-item-local-open`),o=e.querySelector(`.prototype-library-item-optimize`),s=e.querySelector(`.prototype-library-item-delete`),c=e.querySelector(`.prototype-library-item-download`);t&&t.addEventListener(`click`,()=>{let t=e.dataset.id;Cc(t)}),n&&n.addEventListener(`click`,t=>{t.stopPropagation();let n=e.dataset.id;Cc(n)}),i&&i.addEventListener(`click`,e=>{e.stopPropagation();let t=i.dataset.path;chrome.runtime.sendMessage({type:`OPEN_LOCAL_PROTOTYPE`,path:t},e=>{e?.success||a.error(`[SidePanel] local browseropen failed:`,e?.error)})}),o&&o.addEventListener(`click`,t=>{t.stopPropagation();let n=o.dataset.id;kc(n,e.querySelector(`.prototype-library-item-title`)?.textContent||r(`uiProto.defaultTitle`)),Oc()}),s&&s.addEventListener(`click`,t=>{t.stopPropagation();let n=s.dataset.id;jc(n,e.querySelector(`.prototype-library-item-title`)?.textContent||r(`uiProto.defaultTitle`))}),c&&c.addEventListener(`click`,e=>{e.stopPropagation();let t=c.dataset.id;Ac(t)})})))}function Dc(e){let t=()=>{let t=document.getElementById(`prototypeLibrarySearch`),n=document.getElementById(`prototypeLibrarySort`),r=(t?.value||``).trim().toLowerCase(),i=n?.value||`createdAt_desc`,a=e;r&&(a=e.filter(e=>(e.title||``).toLowerCase().includes(r)||(e.description||``).toLowerCase().includes(r)));let[o,s]=i.split(`_`);a=[...a].sort((e,t)=>{let n;return n=o===`title`?(e.title||``).localeCompare(t.title||``,`zh-CN`):(e.createdAt||0)-(t.createdAt||0),s===`desc`?-n:n}),Ec(a)},n=document.getElementById(`prototypeLibrarySearch`),r=document.getElementById(`prototypeLibrarySort`);if(n){let e=n.cloneNode(!0);n.parentNode.replaceChild(e,n),e.addEventListener(`input`,t)}if(r){let e=r.cloneNode(!0);r.parentNode.replaceChild(e,r),e.addEventListener(`change`,t)}}function Oc(){let e=document.getElementById(`prototypeLibraryModal`);e&&e.classList.remove(`show`),a.debug(`[SidePanel] prototype page libraryhidden`)}function kc(e,t){let n=document.getElementById(`userInput`);n&&(n.value=r(`uiProto.optimizePrompt`,{id:e,title:t}),n.focus(),n.style.height=`auto`,n.style.height=n.scrollHeight+`px`),a.debug(`[SidePanel] from prototype page librarycontinue optimizeprototype:`,e)}async function Ac(e){try{let t=await Qe(e);if(!t||!t.html){a.error(`[SidePanel] download prototype failed:not foundprototype`,e);return}let n=_c(t.html),r=new Blob([n],{type:`text/html`}),i=URL.createObjectURL(r),o=document.createElement(`a`);o.href=i,o.download=(t.title||`prototype`).replace(/[^a-zA-Z0-9\u4e00-\u9fa5_-]/g,`_`)+`.html`,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(i),a.debug(`[SidePanel] prototype fromprototypelibrarydownload:`,o.download)}catch(e){a.error(`[SidePanel] download prototype failed:`,e)}}async function jc(e,t){if(await Mc(r(`uiProto.confirmDeleteTitle`),r(`uiProto.confirmDeleteMessage`,{title:t}),r(`common.delete`)))try{let t=await Qe(e);await xe(e),a.debug(`[SidePanel] prototype deleted:`,e),t?.localPath&&chrome.runtime.sendMessage({type:`DELETE_LOCAL_PROTOTYPE`,path:t.localPath},e=>{e?.success?a.debug(`[SidePanel] local prototypefile deleted:`,t.localPath):a.warn(`[SidePanel] local prototypefiledelete failed:`,e?.error)}),Tc()}catch(e){a.error(`[SidePanel] delete prototype failed:`,e),alert(r(`uiProto.deleteFailed`,{message:e.message}))}}function Mc(e,t,n=r(`common.confirm`)){return new Promise(r=>{let i=document.getElementById(`genericConfirmModal`),a=document.getElementById(`genericConfirmTitle`),o=document.getElementById(`genericConfirmMessage`),s=document.getElementById(`genericConfirmOkBtn`),c=document.getElementById(`genericConfirmCancelBtn`);if(!i){r(confirm(t));return}a.textContent=e,o.textContent=t,s.textContent=n;let l=()=>{i.classList.remove(`show`),s.removeEventListener(`click`,u),c.removeEventListener(`click`,d)},u=()=>{l(),r(!0)},d=()=>{l(),r(!1)};s.addEventListener(`click`,u),c.addEventListener(`click`,d),i.classList.add(`show`)})}function Nc(e){let t=document.createElement(`div`);return t.textContent=e,t.innerHTML}function Pc(e){if(!e)return``;let t=new Date(e),n=new Date-t;return n<6e4?r(`uiProto.justNow`):n<36e5?r(`uiProto.minutesAgo`,{count:Math.floor(n/6e4)}):n<864e5?r(`uiProto.hoursAgo`,{count:Math.floor(n/36e5)}):t.toLocaleDateString(`zh-CN`)}function Fc(e){pc=Math.max(mc,Math.min(hc,e)),pc=Math.round(pc*100)/100;let t=document.getElementById(`prototypeIframe`),n=document.getElementById(`prototypeZoomLevel`);t&&(t.style.zoom=pc),n&&(n.textContent=Math.round(pc*100)+`%`,pc===1?n.classList.remove(`zoomed`):n.classList.add(`zoomed`))}function Ic(){Fc(pc+gc),zc()}function Lc(){Fc(pc-gc),zc()}function Rc(){Fc(1)}function zc(){let e=document.getElementById(`prototypeZoomLevel`);e&&(e.classList.add(`flash`),setTimeout(()=>e.classList.remove(`flash`),150))}function Bc(e){!e.ctrlKey&&!e.metaKey||(e.preventDefault(),e.deltaY<0?Ic():Lc())}function Vc(e){(e.ctrlKey||e.metaKey)&&e.key===`0`&&(e.preventDefault(),Rc())}function Hc(){let e=document.getElementById(`prototypeCloseBtn`);e&&e.addEventListener(`click`,yc);let t=document.getElementById(`prototypeDownloadBtn`);t&&t.addEventListener(`click`,xc);let n=document.getElementById(`prototypeOpenTabBtn`);n&&n.addEventListener(`click`,Sc);let r=document.getElementById(`prototypeLocalOpenBtn`);r&&r.addEventListener(`click`,()=>{let e=r.dataset.path;e&&chrome.runtime.sendMessage({type:`OPEN_LOCAL_PROTOTYPE`,path:e},e=>{e?.success||a.error(`[SidePanel] local browseropen failed:`,e?.error)})});let i=document.getElementById(`prototypeContinueBtn`);i&&i.addEventListener(`click`,bc);let o=document.getElementById(`prototypeZoomInBtn`);o&&o.addEventListener(`click`,Ic);let s=document.getElementById(`prototypeZoomOutBtn`);s&&s.addEventListener(`click`,Lc);let c=document.getElementById(`prototypeZoomLevel`);c&&c.addEventListener(`click`,Rc);let l=document.getElementById(`prototypeContent`);l&&l.addEventListener(`wheel`,Bc,{passive:!1}),document.addEventListener(`keydown`,Vc);let u=document.getElementById(`prototypeLibraryCloseBtn`);u&&u.addEventListener(`click`,Oc),chrome.runtime.onMessage.addListener((e,t,n)=>{e.type===`SHOW_UI_PROTOTYPE`&&(a.debug(`[SidePanel] received showprototyperequested :`,e),e.data.localOpened?a.debug(`[SidePanel] prototype inagent-side browseropen,skip popup`):e.data.isRemoteAgent?(a.debug(`[SidePanel] remoteagent,will use browserlabelpageautoopenprototype`),wc(e.data.prototypeId)):Cc(e.data.prototypeId),n({success:!0}))}),a.debug(`[SidePanel] UI prototype moduleeventinitializing`)}var Uc={enabled:!1,thresholdRatio:.85,minPending:4,maxFailures:2};function Wc(e,t){let n=Number(e);return Number.isFinite(n)&&n>0&&n<=1?n:t}function Gc(e,t){let n=Number(e);return Number.isFinite(n)&&n>=0?Math.floor(n):t}function Kc({enabled:e,ratio:t,thresholdRatio:n,pendingCount:r,minPending:i,isGenerating:a,isolateChat:o}={}){if(!e||a||!o)return!1;let s=Wc(n,Uc.thresholdRatio),c=Gc(i,Uc.minPending);return!Number.isFinite(t)||t<s?!1:Gc(r,0)>=c}function qc(e){let t=e?.messageHistory||[],n=e?.activeCompaction?.upToMessageId;if(!n)return t.length;let r=t.findIndex(e=>e.messageId===n);return r===-1?t.length:t.length-r-1}var Jc=0;function Yc(){Jc=0}async function Xc({state:e,getRatio:t,compact:n}={}){let r=e?.chatConfig||{},i=r.autoCompaction===!0;if(!i)return{attempted:!1,success:!1,reason:`disabled`};if(Jc>=Uc.maxFailures)return{attempted:!1,success:!1,reason:`backoff`};let o;try{o=Number(t?t():NaN)}catch(e){return a.warn(`[AutoCompaction] usage compute failed, send continues:`,e?.message),{attempted:!1,success:!1,reason:`usage_unavailable`}}let s=qc(e);if(!Kc({enabled:i,ratio:o,thresholdRatio:r.autoCompactionThreshold,pendingCount:s,isGenerating:!!e?.isGenerating,isolateChat:!!e?.isolateChat}))return{attempted:!1,success:!1,reason:`not_needed`};a.debug(`[AutoCompaction] triggered`,{ratio:o,pendingCount:s});let c=null;try{c=await n({silent:!0})}catch(e){return a.warn(`[AutoCompaction] compact threw, send continues:`,e?.message),Jc++,{attempted:!0,success:!1,reason:`exception`}}return c?.success?(Yc(),{attempted:!0,success:!0}):(Jc++,a.debug(`[AutoCompaction] skipped send:`,c?.reason),{attempted:!0,success:!1,reason:c?.reason||`failed`})}var Zc=null,Qc=`global`,$c=new Map;function el(){try{chrome.windows?.getCurrent?.().then?.(e=>{e?.id!=null&&(Zc=e.id)}).catch?.(e=>{a.debug(`[PanelContext] query current window failed:`,e?.message)})}catch(e){a.debug(`[PanelContext] init window query failed:`,e?.message)}try{chrome.storage?.local?.get?.([`sidePanelScope`],e=>{Qc=e?.sidePanelScope===`tab-specific`?`tab-specific`:`global`}),chrome.storage?.onChanged?.addListener?.((e,t)=>{t!==`local`||!e?.sidePanelScope||(Qc=e.sidePanelScope.newValue===`tab-specific`?`tab-specific`:`global`)})}catch(e){a.debug(`[PanelContext] init scope mirror failed:`,e?.message)}}function tl(){return Zc}function nl(e){e&&typeof N.currentTabId==`number`&&$c.set(e,N.currentTabId)}function rl(e,t){e&&(typeof t==`number`?$c.set(e,t):$c.delete(e))}function il(e){if(!e)return null;let t=$c.get(e);return typeof t==`number`?t:null}function al(e){let t=null;try{t=typeof document<`u`?!!document.hidden:null}catch{}return{windowId:Zc,hostTabId:il(e),scope:Qc,panelHidden:t}}var ol=0,sl=500,cl=[{frequency:523.25,startTime:0,duration:.12,type:`sine`,gain:.3},{frequency:659.25,startTime:.09,duration:.12,type:`sine`,gain:.3},{frequency:783.99,startTime:.18,duration:.22,type:`sine`,gain:.35}],ll=[{frequency:440,startTime:0,duration:.16,type:`square`,gain:.22},{frequency:349.23,startTime:.14,duration:.3,type:`square`,gain:.22}],ul=[`#FF3B30`,`#FF9500`,`#FFCC00`,`#34C759`,`#00C7BE`,`#007AFF`,`#AF52DE`,`#FF2D55`],dl=120,fl=4e3,pl=600,ml=1e3,hl=.25,gl=.99,_l=.3,vl=.6,yl=9999;function bl(){return new Promise(e=>{try{chrome.storage.local.get([`completionSoundEnabled`,`completionConfettiEnabled`],t=>{e({soundEnabled:t?.completionSoundEnabled!==!1,confettiEnabled:t?.completionConfettiEnabled!==!1})})}catch(t){a.debug(`[CompletionFeedback] read config failed, use defaults:`,t?.message),e({soundEnabled:!0,confettiEnabled:!0})}})}function xl(e){try{let t=window.AudioContext||window.webkitAudioContext;if(!t){a.debug(`[CompletionFeedback] AudioContext unavailable`);return}let n=new t;n.state===`suspended`&&typeof n.resume==`function`&&n.resume().catch(()=>{});let r=n.currentTime,i=0;for(let t of e){let e=n.createOscillator(),a=n.createGain();e.type=t.type||`sine`,e.frequency.value=t.frequency;let o=r+t.startTime,s=o+t.duration;a.gain.setValueAtTime(1e-4,o),a.gain.exponentialRampToValueAtTime(t.gain,o+.012),a.gain.exponentialRampToValueAtTime(1e-4,s),e.connect(a),a.connect(n.destination),e.start(o),e.stop(s+.02),s>i&&(i=s)}let o=Math.max(0,(i-r)*1e3)+200;setTimeout(()=>{try{n.close()}catch{}},o)}catch(e){a.debug(`[CompletionFeedback] play tone failed:`,e?.message)}}function Sl(){xl(cl),a.debug(`[CompletionFeedback] success sound played`)}function Cl(){xl(ll),a.debug(`[CompletionFeedback] failure sound played`)}function wl(){try{return typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches}catch{return!1}}function Tl(){try{if(!document.body)return;let e=window.innerWidth,t=window.innerHeight;if(e<=0||t<=0)return;let n=document.createElement(`canvas`);n.style.cssText=`position:fixed;inset:0;pointer-events:none;z-index:${yl};`;let r=window.devicePixelRatio||1;n.width=Math.floor(e*r),n.height=Math.floor(t*r),n.style.width=e+`px`,n.style.height=t+`px`,document.body.appendChild(n);let i=n.getContext(`2d`);if(!i){n.remove();return}i.scale(r,r);let o=[{x:e*.15,y:t+10,baseAngle:-Math.PI/2+_l},{x:e*.85,y:t+10,baseAngle:-Math.PI/2-_l}],s=[],c=0,l=0,u=performance.now(),d=e=>{let t=Math.min(dl,Math.floor(Math.min(e,pl)/pl*dl));for(;c<t;){let e=o[c%o.length],t=e.baseAngle+(Math.random()-.5)*vl,n=12+Math.random()*8,r=4+Math.random()*4;s.push({x:e.x+(Math.random()-.5)*20,y:e.y,vx:Math.cos(t)*n,vy:Math.sin(t)*n,size:r,color:ul[Math.floor(Math.random()*ul.length)],rotation:Math.random()*Math.PI*2,rotationSpeed:(Math.random()-.5)*.3,shape:Math.random()<.5?`rect`:`circle`}),c++}},f=r=>{let a=r-u;if(a>=fl){cancelAnimationFrame(l),n.remove();return}d(a),i.clearRect(0,0,e,t);let o=fl-ml,c=a>o?Math.max(0,1-(a-o)/ml):1;for(let n=s.length-1;n>=0;n--){let r=s[n];if(r.vy+=hl,r.vx*=gl,r.vy*=gl,r.x+=r.vx,r.y+=r.vy,r.rotation+=r.rotationSpeed,r.y-r.size>t||r.x+r.size<0||r.x-r.size>e){s.splice(n,1);continue}i.save(),i.globalAlpha=c,i.translate(r.x,r.y),i.rotate(r.rotation),i.fillStyle=r.color,r.shape===`rect`?i.fillRect(-r.size/2,-r.size/2,r.size,r.size*.6):(i.beginPath(),i.arc(0,0,r.size/2,0,Math.PI*2),i.fill()),i.restore()}l=requestAnimationFrame(f)};l=requestAnimationFrame(f),a.debug(`[CompletionFeedback] confetti launched`)}catch(e){a.debug(`[CompletionFeedback] launch confetti failed:`,e?.message)}}function El(e,t,n,r){try{chrome.runtime.sendMessage({type:`TASK_FEEDBACK_NOTIFY`,success:e,sessionId:t||null,error:n||``,question:r||``,panel:al(t)})?.catch?.(()=>{})}catch(e){a.debug(`[CompletionFeedback] desktop notify failed:`,e?.message)}}async function Dl(e=null,t=``){try{let n=Date.now();if(n-ol<sl){a.debug(`[CompletionFeedback] throttled, skip`);return}ol=n;let{soundEnabled:r,confettiEnabled:i}=await bl();r&&Sl(),i&&!wl()&&Tl(),El(!0,e,``,t)}catch(e){a.debug(`[CompletionFeedback] unexpected error:`,e?.message||e)}}async function Ol(e=null,t=``,n=``){try{let r=Date.now();if(r-ol<sl){a.debug(`[CompletionFeedback] throttled, skip`);return}ol=r;let{soundEnabled:i}=await bl();i&&Cl(),El(!1,e,t,n)}catch(e){a.debug(`[CompletionFeedback] unexpected error:`,e?.message||e)}}var kl=new Set;function Al(e){return typeof e==`function`?(kl.add(e),()=>kl.delete(e)):()=>{}}function jl(e){let t=e||N.activeSessionId;if(t){N.generatingSessionIds.delete(t);try{Ni(t)}catch(e){a.warn(`[GenerationLifecycle] markSessionCompleted failed:`,e?.message)}typeof document<`u`&&typeof CustomEvent==`function`&&(document.dispatchEvent(new CustomEvent(`generating-state-changed`)),document.dispatchEvent(new CustomEvent(`generation-ended`,{detail:{sessionId:t}})));for(let e of kl)try{e(t)}catch(e){a.error(`[GenerationLifecycle] end handler failed:`,e?.message)}}}function Ml(e){let t=Number(e);return!Number.isFinite(t)||t<=0?3:Math.min(20,Math.max(1,Math.round(t)))}function Nl(){return{callId:null,carried:0,lastIteration:null}}function Pl(e){let t=0;for(let n of e||[]){let e=Number(n&&n.iteration);Number.isFinite(e)&&e>t&&(t=e)}return t}function Fl(e){let{tracker:t,callId:n=null,iteration:r,everyN:i,enabled:a=!0,hasCandidate:o=!0}=e||{},s=t&&typeof t==`object`?{callId:t.callId??null,carried:Number(t.carried)||0,lastIteration:t.lastIteration??null}:Nl(),c=Number(r);if(!Number.isFinite(c)||c<=0)return{carry:!1,reason:`invalid_iteration`,tracker:s};let l=!!n&&!!s.callId&&n!==s.callId,u=s.lastIteration!=null&&c<s.lastIteration;if((l||u)&&(s=Nl()),n&&!s.callId&&(s={...s,callId:n}),!a)return{carry:!1,reason:`disabled`,tracker:s};if(c<2)return{carry:!1,reason:`too_early`,tracker:s};if(!o)return{carry:!1,reason:`no_candidate`,tracker:s};if(s.carried>=3)return{carry:!1,reason:`call_limit`,tracker:s};let d=Ml(i);return s.lastIteration!=null&&c-s.lastIteration<d?{carry:!1,reason:`interval_not_reached`,tracker:s}:{carry:!0,reason:`carry`,tracker:{callId:s.callId||n||null,carried:s.carried,lastIteration:c}}}function Il(e,{callId:t=null}={}){let n=e&&typeof e==`object`?e:Nl();return t&&n.callId&&t!==n.callId?n:{...n,carried:(Number(n.carried)||0)+1}}var Ll=/[\p{P}\p{S}]/gu;function Rl(e){return Array.isArray(e)?e.map(e=>e&&e.text||``).join(``):``}function zl(e){return String(e||``).replace(/[\s\u3000]/g,``).replace(Ll,``)}function Bl(e,t){if(!Array.isArray(e))return e;let n=t&&t.id,r=t&&typeof t.text==`string`?t.text:null;if(r===null||typeof n!=`number`)return e;let i=!1,a=e.map(e=>!e||e.id!==n||e.state===`locked`?e:(i=!0,{...e,text:r}));return i?a:e}function Vl(e,t,n){let r=String(t||``),i=String(n||``),a={lockedIds:[],shift:0,items:e,len:r.length};if(r===i||!Array.isArray(e)||e.length===0)return a;let o=0,s=Math.min(r.length,i.length);for(;o<s&&r[o]===i[o];)o++;let c=0,l=Math.min(r.length-o,i.length-o);for(;c<l&&r[r.length-1-c]===i[i.length-1-c];)c++;let u=o,d=r.length-c;if(u>=r.length&&d>=r.length){let t=e[e.length-1],n=t&&t.text?t.text.length:0,a=i.slice(Math.max(0,r.length-n)),o=e.map((t,n)=>n===e.length-1?{...t,text:a}:t);return{lockedIds:[t.id],shift:0,items:o,len:i.length}}let f=[],p=0;for(let t of e){let e=(t&&t.text?t.text:``).length;u<p+e&&d>p&&f.push(t.id),p+=e}if(f.length===0)return{lockedIds:[],shift:u===0?i.length-r.length:0,items:e,len:r.length};let m=i.length-r.length,h=d+m,g=e=>e<=u?e:e>=d?e+m:u+Math.min(e-u,Math.max(0,h-u)),_=0;return{lockedIds:f,shift:0,items:e.map(e=>{let t=(e&&e.text?e.text:``).length,n=g(_),r=g(_+t);return _+=t,{...e,text:i.slice(n,r)}}),len:i.length}}function Hl(e,t){if(!Array.isArray(e)||e.length===0)return{items:Array.isArray(e)?e:[],changed:0,takeAll:!1};let n=Rl(e),r=String(t||``);if(!r)return{items:e,changed:0,takeAll:!1};let i=zl(n),a=zl(r);if(i===a)return{items:e,changed:0,takeAll:!1};if(Math.abs(i.length-a.length)+Ul(i,a)>2||i.length!==a.length)return e.some(e=>e&&e.state===`locked`)?{items:e,changed:0,takeAll:!1}:{items:[{id:e[0]&&typeof e[0].id==`number`?e[0].id:null,text:r,state:`refined`}],changed:1,takeAll:!0};let o=n.split(``),s=0,c=0;for(let e=0;e<o.length;e++)zl(o[e])!==``&&(s<a.length&&o[e]!==a[s]&&(o[e]=a[s],c+=1),s+=1);if(c===0)return{items:e,changed:0,takeAll:!1};let l=o.join(``),u=0;return{items:e.map(e=>{let t=(e&&e.text?e.text:``).length,n=e&&e.state===`locked`?e.text:l.slice(u,u+t);return u+=t,e&&e.state===`locked`?e:{...e,text:n}}),changed:c,takeAll:!1}}function Ul(e,t){if(e.length!==t.length)return 2**53-1;let n=0;for(let r=0;r<e.length;r++)e[r]!==t[r]&&(n+=1);return n}n(`zh`,{voice:{start:`语音输入(开始录音)`,stop:`结束录音并转写`,recording:`正在录音`,listening:`正在聆听…`,transcribing:`正在转写…`,cancel:`取消录音`,done:`完成`,noSpeech:`没有听到声音`,noResult:`未识别到语音`,micDenied:`麦克风未授权`,micDeniedHelp:`侧边栏里浏览器不会弹授权框,请到配置页「语音输入 → 麦克风权限」授权一次`,micDeniedAction:`去授权`,micDeniedActionTitle:`打开配置页授权麦克风(侧边栏内无法弹出授权框)`,unavailable:`语音功能不可用`,modelMissing:`缺少语音模型`,modelMissingHelp:`请在配置页「语音」Tab 中导入模型包`,busy:`有语音任务正在进行`,failed:`语音识别失败`,connectionLost:`连接中断`,tooShort:`录音太短`,maxDuration:`已达单次录音时长上限,正在转写…`,unsupported:`当前浏览器不支持录音`,keyRightAlt:`右侧 Alt`,keyRightCtrl:`右侧 Ctrl`,btnTitle:`语音输入({keys})`,deviceFallback:`原麦克风不可用,已改用系统默认`,refineListening:`正在听…(已定稿 {n} 句)`,refineCorrecting:`正在校正…`,refineCorrected:`已校正 {n} 处`,refineDegraded:`本机性能有限,已关闭逐句精修(松手后仍会整体校正)`}}),n(`en`,{voice:{start:`Voice input (start recording)`,stop:`Stop and transcribe`,recording:`Recording`,listening:`Listening…`,transcribing:`Transcribing…`,cancel:`Cancel recording`,done:`Done`,noSpeech:`No sound detected`,noResult:`No speech recognised`,micDenied:`Microphone not granted`,micDeniedHelp:`The browser cannot prompt inside the side panel — grant it once in Options → Voice Input → Microphone permission`,micDeniedAction:`Grant access`,micDeniedActionTitle:`Open options to grant microphone access (the side panel cannot show the prompt)`,unavailable:`Voice input unavailable`,modelMissing:`Speech model missing`,modelMissingHelp:`Import a model pack in the Options "Voice" tab`,busy:`Another voice task is running`,failed:`Speech recognition failed`,connectionLost:`Connection lost`,tooShort:`Recording too short`,maxDuration:`Recording length limit reached, transcribing…`,unsupported:`Recording is not supported in this browser`,keyRightAlt:`Right Alt`,keyRightCtrl:`Right Ctrl`,btnTitle:`Voice input ({keys})`,deviceFallback:`Selected microphone unavailable — using the system default`,refineListening:`Listening… ({n} sentences finalized)`,refineCorrecting:`Refining…`,refineCorrected:`{n} correction(s) applied`,refineDegraded:`This machine is too slow for per-sentence refinement (the final pass still runs)`}});var Wl=15e3,Gl=16e3,Kl=2500,ql=.008,Jl=350,Yl=24,V={input:null,btn:null,bar:null,wave:null,timerEl:null,statusEl:null,permBtn:null,barEls:[],status:null,armed:!1,phase:`idle`,port:null,stream:null,ctx:null,node:null,source:null,startedAt:0,timer:null,silentSince:0,silenceWarned:!1,draft:null,lastText:``,appliedText:``,appliedValue:``,openText:``,mute:null,programmatic:!1,draftSupported:!0,finishWaitTimer:null,adjustInputHeight:null,shortcutCfg:{...lt},shortcutTrigger:null,shortcutBound:!1,deviceFellBack:!1};function Xl(e){return typeof e==`string`?e:``}function Zl(e){let t=Math.max(0,Math.floor(e/1e3));return`${String(Math.floor(t/60)).padStart(2,`0`)}:${String(t%60).padStart(2,`0`)}`}function Ql(e){let t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),n=``,r=32768;for(let e=0;e<t.length;e+=r)n+=String.fromCharCode.apply(null,t.subarray(e,e+r));return btoa(n)}function $l(e,t,n){if(t===n)return e;let r=t/n,i=Math.floor(e.length/r),a=new Float32Array(i);for(let t=0;t<i;t++){let n=t*r,i=Math.floor(n),o=n-i,s=e[i]||0;a[t]=s+((e[i+1]===void 0?s:e[i+1])-s)*o}return a}function eu(e){let t=new Int16Array(e.length);for(let n=0;n<e.length;n++){let r=e[n]<-1?-1:e[n]>1?1:e[n];t[n]=r<0?r*32768:r*32767}return t}async function tu(e=!1){try{let t=await chrome.runtime.sendMessage({type:`ASR_GET_STATUS`,force:e});if(t&&t.success&&t.status)return V.status=t.status,V.status}catch(e){a.debug(`[Voice] status fetch failed:`,e?.message||e)}return V.status=null,null}function nu(e){return!e||e.success===!1?!1:typeof e.available==`boolean`?e.available:e.deps?.ready===!0&&e.modelsReady===!0&&e.enabled===!0}function ru({value:e,draft:t,text:n,caret:r,canReplace:i=!0}){let a=typeof e==`string`?e:``;if(!t)return{value:a,caret:a.length,len:0};if(!i){let e=typeof r==`number`?Math.min(Math.max(0,r),a.length):a.length;return{value:a.slice(0,e)+n+a.slice(e),caret:e+n.length,len:0}}let o=Math.min(Math.max(0,t.start),a.length),s=Math.min(Math.max(o,t.start+t.len),a.length);return{value:a.slice(0,o)+n+a.slice(s),caret:o+n.length,len:n.length}}function iu({value:e,draft:t,canReplace:n=!0}){let r=typeof e==`string`?e:``;if(!t||!n||t.len<=0)return{value:r,caret:r.length};let i=Math.min(Math.max(0,t.start),r.length),a=Math.min(Math.max(i,t.start+t.len),r.length);return{value:r.slice(0,i)+r.slice(a),caret:i}}function au(e){return!e||e.isComposing||e.repeat?!1:e.altKey===!0&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&e.code===`KeyV`}async function ou(){return V.armed=nu(await tu()),V.btn&&(V.btn.style.display=V.armed?``:`none`),!V.armed&&V.phase!==`idle`&&Lu({rollback:!0}),V.armed}function su(){if(!V.draft||!V.input)return;let e=Rl(V.draft.items),t=V.input.value,n=Xl(V.appliedValue),r=V.draft.start,i=r+e.length,a=0;for(;a<n.length&&a<t.length&&n[a]===t[a];)a+=1;let o=0,s=Math.min(n.length-a,t.length-a);for(;o<s&&n[n.length-1-o]===t[t.length-1-o];)o+=1;let c=a;if(n.length-o<=r){V.draft.start=Math.max(0,r+(t.length-n.length));return}if(c>i)return;let l=Math.max(0,n.length-i),u=t.slice(r,Math.max(r,t.length-l)),d=Vl(V.draft.items,e,u);d.shift&&(V.draft.start+=d.shift),d.lockedIds.length!==0&&(V.draft.items=d.items.map(e=>d.lockedIds.includes(e.id)?{...e,state:`locked`}:e),V.draft.len=d.len)}function cu(){let e=V.input;if(!e)return{start:0,len:0,items:[]};let t=typeof e.selectionStart==`number`?e.selectionStart:e.value.length,n=typeof e.selectionEnd==`number`?e.selectionEnd:t;return t!==n&&e.setRangeText(``,t,n,`end`),{start:t,len:0,items:[]}}function lu(e,t){let n=Xl(e),r=Xl(t);return r?n?r.startsWith(n)?r.slice(n.length):null:r:``}function uu(e,t){let n=V.input;if(n){V.programmatic=!0,V.appliedValue=e,n.value=e;try{n.setSelectionRange(t,t)}catch{}V.programmatic=!1;try{document.dispatchEvent(new CustomEvent(`voice-draft-written`))}catch{}try{V.adjustInputHeight?.()}catch{}try{n.focus()}catch{}}}function du(e=!1){let t=V.input;if(!t||!V.draft)return;let n=Rl(V.draft.items);if(!e&&n===Xl(V.appliedText))return;let r=typeof t.selectionStart==`number`?t.selectionStart:void 0,i=V.draft.start,a=i+V.draft.len,o=ru({value:t.value,draft:{start:i,len:V.draft.len},text:n,caret:r,canReplace:V.draftSupported});typeof r==`number`&&r>i&&r<a&&(o.caret=i+Math.min(r-i,n.length)),V.draft.len=n.length,V.appliedText=n,uu(o.value,o.caret)}function fu(e){if(!V.input||!V.draft)return;let t=Array.isArray(V.draft.items)?V.draft.items:[],n=t.findIndex(e=>e.id===null),r=Xl(e);if(n>=0&&t[n].state===`locked`){let e=lu(V.openText,r);if(V.openText=r,!e)return;V.draft.items=t.map((t,r)=>r===n?{...t,text:t.text+e}:t)}else V.openText=r,V.draft.items=n>=0?t.map((e,t)=>t===n?{...e,text:r}:e):t.concat([{id:null,text:r,state:`draft`}]);du()}function pu(){let e=V.input;if(!e||!V.draft)return;let t=Array.isArray(V.draft.items)&&V.draft.items.some(e=>e.state===`locked`)?{value:e.value,caret:e.value.length}:iu({value:e.value,draft:V.draft,canReplace:V.draftSupported});if(t.value!==e.value){V.programmatic=!0,V.appliedValue=t.value,e.value=t.value;let n=Math.min(t.caret,e.value.length);try{e.setSelectionRange(n,n)}catch{}V.programmatic=!1;try{V.adjustInputHeight?.()}catch{}}V.draft=null,V.lastText=``,V.appliedText=``,V.openText=``}function mu(){if(V.wave){V.wave.textContent=``,V.barEls=[];for(let e=0;e<Yl;e++){let e=document.createElement(`i`);V.wave.appendChild(e),V.barEls.push(e)}}}function hu(e,t=``){V.statusEl&&(V.statusEl.textContent=e,V.statusEl.className=`voice-recorder-status`+(t?` is-${t}`:``))}function gu(){V.bar&&(V.bar.classList.add(`show`),V.bar.removeAttribute(`aria-hidden`))}function _u(e){V.permBtn&&(V.permBtn.style.display=e?``:`none`)}function vu(){let e=document.activeElement;if(!(!V.bar||!e||!V.bar.contains(e))){if(V.input&&typeof V.input.focus==`function`)try{V.input.focus({preventScroll:!0});return}catch{}try{e.blur()}catch{}}}function yu(){V.bar&&(typeof document>`u`||!document.body||(vu(),_u(!1),V.bar.classList.remove(`show`),V.bar.setAttribute(`aria-hidden`,`true`),V.barEls.forEach(e=>{e.style.height=``,e.style.opacity=``}),V.timerEl&&(V.timerEl.textContent=`00:00`)))}function bu(e){if(!V.barEls.length)return;let t=Math.min(1,Math.sqrt(Math.max(0,e))*6);for(let e=0;e<V.barEls.length-1;e++)V.barEls[e].style.height=V.barEls[e+1].style.height,V.barEls[e].style.opacity=V.barEls[e+1].style.opacity;let n=V.barEls[V.barEls.length-1];n.style.height=`${Math.max(2,Math.round(t*18))}px`,n.style.opacity=t>.06?`1`:`0.35`}function xu(e){V.btn&&(V.btn.classList.toggle(`recording`,e),V.btn.setAttribute(`aria-pressed`,e?`true`:`false`),V.btn.setAttribute(`aria-label`,r(e?`voice.stop`:`voice.start`)),V.btn.title=r(e?`voice.stop`:`voice.start`))}function Su(e){document.body?.classList.toggle(`voice-recording-active`,!!e)}function Cu(){if(V.port)return V.port;try{let e=chrome.runtime.connect({name:`asr`});return e.onMessage.addListener(zu),e.onDisconnect.addListener(()=>{V.port=null,(V.phase===`recording`||V.phase===`finalizing`)&&(Mu(),Nu(),V.draft=null,V.lastText=``,xu(!1),Su(!1),hu(r(`voice.connectionLost`),`warn`),setTimeout(()=>{V.phase===`idle`&&yu()},3500))}),V.port=e,e}catch(e){return a.warn(`[Voice] connect port failed:`,e?.message||e),null}}function wu(e,t){if(bu(t),Tu(t),V.port)try{V.port.postMessage({type:`audio`,data:Ql(e)})}catch(e){a.debug(`[Voice] post audio failed:`,e?.message||e)}}function Tu(e){if(V.phase!==`recording`&&V.phase!==`starting`)return;if(e>=ql){V.silentSince=0,V.silenceWarned&&(V.silenceWarned=!1,hu(r(`voice.listening`)));return}let t=Date.now();if(!V.silentSince){V.silentSince=t;return}V.silenceWarned||t-V.silentSince>=Kl&&(V.silenceWarned=!0,hu(r(`voice.noSpeech`),`warn`))}var Eu=[`voice-capture-worklet.js`,`dist/voice-capture-worklet.js`],Du;async function Ou(){if(Du!==void 0)return Du;for(let e of Eu){let t=``;try{t=chrome.runtime.getURL(e)}catch{continue}try{let e=await fetch(t);if(e&&e.ok)return Du=t,t}catch{}}return Du=null,null}async function ku(e,t){let n=await Ou();if(!n)throw Error(`worklet not found in extension`);await e.audioWorklet.addModule(n);let r=new AudioWorkletNode(e,`voice-capture`),i=Math.abs(e.sampleRate-Gl)>1;r.port.onmessage=t=>{let n=t.data;if(!n||n.type!==`chunk`||!n.pcm)return;let r=new Int16Array(n.pcm);if(i){let t=new Float32Array(r.length);for(let e=0;e<r.length;e++)t[e]=r[e]/32768;r=eu($l(t,e.sampleRate,Gl))}wu(r,n.rms||0)},t.connect(r),V.node=r}function Au(e,t){let n=e.createScriptProcessor(4096,1,1),r=Math.abs(e.sampleRate-Gl)>1;n.onaudioprocess=t=>{let n=t.inputBuffer.getChannelData(0),i=new Float32Array(n);r&&(i=$l(i,e.sampleRate,Gl));let a=0;for(let e=0;e<i.length;e++)a+=i[e]*i[e];wu(eu(i),Math.sqrt(a/Math.max(1,i.length)))},t.connect(n);let i=e.createGain();i.gain.value=0,n.connect(i),i.connect(e.destination),V.mute=i,V.node=n}async function ju(){if(!navigator.mediaDevices?.getUserMedia)throw hu(r(`voice.unsupported`),`warn`),Error(`unsupported`);let e=await pt(await ft());V.stream=e.stream,V.deviceFellBack=e.fellBack===!0;let t=window.AudioContext||window.webkitAudioContext,n;try{n=new t({sampleRate:Gl})}catch{n=new t}if(n.state===`suspended`)try{await n.resume()}catch{}V.ctx=n;let i=n.createMediaStreamSource(e.stream);V.source=i;try{await ku(n,i)}catch(e){a.warn(`[Voice] worklet unavailable, fallback to ScriptProcessor:`,e?.message||e),Au(n,i)}}function Mu(){V.timer&&=(clearInterval(V.timer),null);try{V.node?.port?.close?.()}catch{}try{V.node?.disconnect?.()}catch{}try{V.mute?.disconnect?.()}catch{}try{V.source?.disconnect?.()}catch{}try{V.stream?.getTracks?.().forEach(e=>e.stop())}catch{}try{V.ctx?.close?.()}catch{}V.node=null,V.mute=null,V.source=null,V.stream=null,V.ctx=null}function Nu(){V.finishWaitTimer&&=(clearTimeout(V.finishWaitTimer),null),V.phase=`idle`}function Pu(){let e=()=>{let e=Date.now()-V.startedAt;V.timerEl&&(V.timerEl.textContent=Zl(e));let t=V.status;e>=(t&&t.maxRecordingMs||300*1e3)&&Iu(`stop`)};V.timer&&clearInterval(V.timer),V.timer=setInterval(e,200),e()}async function Fu(e={}){if(V.phase!==`idle`||!V.armed&&!e.force&&(await ou(),!V.armed||V.phase!==`idle`))return!1;V.phase=`starting`,V.lastText=``,V.appliedText=``,V.openText=``,V.draft=cu(),V.appliedValue=V.input?V.input.value:``,V.draftSupported=!0,V.silentSince=0,V.silenceWarned=!1,gu(),hu(r(`voice.listening`)),xu(!0),Su(!0);let t=Cu();if(!t)return hu(r(`voice.failed`),`warn`),Nu(),xu(!1),Su(!1),!1;try{await ju()}catch(e){if(V.phase!==`starting`)return Mu(),!1;let n=e?.name||``,i=n===`NotAllowedError`||n===`SecurityError`;i?(hu(r(`voice.micDenied`),`warn`),_u(!0)):hu(r(`voice.failed`),`warn`),Mu(),Nu(),xu(!1),Su(!1);try{t.postMessage({type:`cancel`})}catch{}return setTimeout(()=>{V.phase===`idle`&&yu()},i?12e3:4e3),!1}if(V.phase!==`starting`)return Mu(),!1;V.startedAt=Date.now(),V.phase=`recording`,hu(r(`voice.listening`)),V.deviceFellBack&&(V.deviceFellBack=!1,hu(r(`voice.deviceFallback`),`warn`),setTimeout(()=>{V.phase===`recording`&&hu(r(`voice.listening`))},4e3)),Pu();try{t.postMessage({type:`start`,language:V.status&&V.status.language||`auto`})}catch(e){a.debug(`[Voice] post start failed:`,e?.message||e)}return!0}function Iu(e){if(V.phase!==`recording`)return;V.phase=`finalizing`;let t=Date.now()-V.startedAt;if(Mu(),xu(!1),Su(!1),e===`cancel`){try{V.port?.postMessage({type:`cancel`})}catch{}pu(),Nu(),yu();return}if(t<Jl&&!V.lastText){try{V.port?.postMessage({type:`cancel`})}catch{}pu(),hu(r(`voice.tooShort`),`warn`),Nu(),setTimeout(()=>{V.phase===`idle`&&yu()},2200);return}hu(r(`voice.transcribing`));try{V.port?.postMessage({type:`stop`})}catch{}V.finishWaitTimer&&clearTimeout(V.finishWaitTimer),V.finishWaitTimer=setTimeout(()=>{V.phase===`finalizing`&&Ru(V.lastText,{fallback:!0})},6e4)}function Lu({rollback:e=!0}={}){if(V.phase===`idle`)return!1;let t=V.phase===`recording`||V.phase===`finalizing`;if(V.phase=`finalizing`,Mu(),t)try{V.port?.postMessage({type:`cancel`})}catch{}return e&&pu(),Nu(),xu(!1),Su(!1),yu(),!0}function Ru(e,t={}){let n=Xl(e).trim();if(!n){pu(),hu(r(`voice.noResult`),`warn`),Nu(),setTimeout(()=>{V.phase===`idle`&&yu()},2200);return}if(!V.draft){let e=V.input;if(e){let t=typeof e.selectionStart==`number`?e.selectionStart:e.value.length;uu(e.value.slice(0,t)+n+e.value.slice(t),t+n.length)}hu(r(`voice.done`)),Nu(),setTimeout(()=>{V.phase===`idle`&&yu()},1200);return}let i=Array.isArray(t.texts)?t.texts.filter(e=>typeof e==`string`&&e.trim()):[];i.length>1&&!V.draft.items.some(e=>e.id!==null||e.state===`locked`)&&(V.draft.items=i.map((e,t)=>({id:t+1,text:e,state:`refined`}))),V.draft.items.length===0&&(V.draft.items=[{id:null,text:n,state:`refined`}]);let{items:o,changed:s,takeAll:c}=Hl(V.draft.items,n);V.draft.items=o,du(!0),c&&a.debug(`[Voice] final text took over the whole draft`),V.draft=null,V.lastText=``,V.appliedText=``,V.openText=``,Nu(),hu(s>0?r(`voice.refineCorrected`,{n:s}):r(`voice.done`)),setTimeout(()=>{V.phase===`idle`&&yu()},s>0?1800:1200)}function zu(e){if(!(!e||typeof e.type!=`string`)){if(e.type===`ready`){e.draft===!1&&V.phase===`recording`&&a.debug(`[Voice] online model missing, draft disabled`);return}if(e.type===`partial`){if(V.phase!==`recording`&&V.phase!==`finalizing`)return;V.lastText=Xl(e.text),fu(typeof e.open==`string`?e.open:V.lastText);return}if(e.type===`endpoint`)return V.phase!==`recording`&&V.phase,void 0;if(e.type===`sentence`){if(V.phase!==`recording`&&V.phase!==`finalizing`||!V.draft||typeof e.id!=`number`)return;let t=typeof e.refined==`string`&&e.refined?e.refined:null,n=Array.isArray(V.draft.items)?V.draft.items:[],i=n.findIndex(e=>e.id===null),a=n;if(!t&&i>=0){let t=n[i];a=n.map((n,r)=>r===i?t.state===`locked`?{...n,id:e.id}:{id:e.id,text:Xl(e.draft)||n.text,state:`draft`}:n),V.openText=``}if(t&&(a.some(t=>t.id===e.id)?a=Bl(a,{id:e.id,text:t}).map(t=>t.id===e.id&&t.state!==`locked`?{...t,state:`refined`}:t):a.some(e=>e.id===null)||(a=a.concat([{id:e.id,text:t,state:`refined`}]))),a!==n&&(V.draft.items=a,du()),t&&V.phase===`recording`){let e=V.draft.items.filter(e=>e.id!==null&&e.state===`refined`).length;hu(r(`voice.refineListening`,{n:e}))}return}if(e.type===`refine`){e.enabled===!1&&(V.phase===`recording`||V.phase===`finalizing`)&&hu(r(`voice.refineDegraded`),`warn`);return}if(e.type===`final`){if(V.phase!==`recording`&&V.phase!==`finalizing`)return;Ru(e.text||V.lastText,{fallback:e.fallback===!0,texts:e.texts});return}if(e.type===`closed`){V.phase===`finalizing`&&Ru(V.lastText,{fallback:!0});return}if(e.type===`error`){let t=e.code||`internal`;if(t===`max_duration`){V.phase===`recording`&&Iu(`stop`),hu(r(`voice.maxDuration`),`warn`);return}hu(t===`busy`?r(`voice.busy`):t===`model_missing`?`${r(`voice.modelMissing`)} — ${r(`voice.modelMissingHelp`)}`:r(`voice.failed`),`warn`),Mu(),(V.phase===`recording`||V.phase===`finalizing`)&&pu(),Nu(),xu(!1),Su(!1),t===`model_missing`&&ou(),setTimeout(()=>{V.phase===`idle`&&yu()},3500)}}}async function Bu(){return V.phase===`recording`?(Iu(`stop`),!0):V.phase===`starting`||V.phase===`finalizing`?!1:Fu()}function Vu(){return V.phase===`recording`||V.phase===`starting`||V.phase===`finalizing`}function Hu(){return Vu()?Lu({rollback:!0}):!1}function Uu(){return V.phase===`idle`?!1:Lu({rollback:!1})}async function Wu(){try{let e=(await chrome.storage.session?.get?.(`pendingVoiceStart`))?.pendingVoiceStart;return!(!e||(await chrome.storage.session.remove(`pendingVoiceStart`),typeof e!=`number`||Date.now()-e>Wl))}catch{return!1}}function Gu(){if(!V.btn)return;let e=[`Alt+V`];V.shortcutCfg.rightAlt&&e.push(r(`voice.keyRightAlt`)),V.shortcutCfg.rightCtrl&&e.push(r(`voice.keyRightCtrl`));let t=r(`voice.btnTitle`,{keys:e.join(` / `)});V.btn.title=t,V.btn.setAttribute(`aria-label`,t)}async function Ku(){if(V.shortcutCfg=await ct(),V.shortcutTrigger||=st(()=>V.shortcutCfg),Gu(),V.shortcutBound)return;V.shortcutBound=!0,document.addEventListener(`keydown`,e=>{V.shortcutTrigger?.onKeyDown(e)===`cancel`&&e.preventDefault()},!0),document.addEventListener(`keyup`,e=>{V.shortcutTrigger?.onKeyUp(e)===`trigger`&&(!V.armed&&V.phase===`idle`||(e.preventDefault(),Bu()))},!0),window.addEventListener(`blur`,()=>{V.shortcutTrigger?.reset()}),ot(e=>{V.shortcutCfg=e,Gu()});let e=async()=>{try{let e=await ct();if(e.rightAlt===V.shortcutCfg.rightAlt&&e.rightCtrl===V.shortcutCfg.rightCtrl)return;V.shortcutCfg=e,Gu()}catch{}};window.addEventListener(`focus`,()=>{e()}),document.addEventListener(`visibilitychange`,()=>{document.hidden||e()})}async function qu(e={}){if(V.input=document.getElementById(`userInput`),V.btn=document.getElementById(`voiceInputBtn`),V.bar=document.getElementById(`voiceRecorderBar`),V.wave=document.getElementById(`voiceWave`),V.timerEl=document.getElementById(`voiceTimer`),V.statusEl=document.getElementById(`voiceStatusText`),V.permBtn=document.getElementById(`voicePermBtn`),V.adjustInputHeight=typeof e.adjustInputHeight==`function`?e.adjustInputHeight:null,!V.input||!V.btn){a.debug(`[Voice] input or button missing, skip init`);return}mu(),xu(!1),hu(r(`voice.listening`)),await Ku(),V.btn.addEventListener(`click`,e=>{e.preventDefault(),Bu()}),document.getElementById(`voiceCancelBtn`)?.addEventListener(`click`,e=>{e.preventDefault(),Lu({rollback:!0})}),document.getElementById(`voiceDoneBtn`)?.addEventListener(`click`,e=>{e.preventDefault(),Iu(`stop`)}),V.permBtn?.addEventListener(`click`,e=>{e.preventDefault();try{chrome.runtime.sendMessage({type:`OPEN_OPTIONS_PAGE`,hash:`asr`}).catch?.(()=>{})}catch{}hu(r(`voice.micDeniedHelp`),`warn`),_u(!1)}),V.input.addEventListener(`input`,()=>{V.programmatic||(V.phase===`recording`||V.phase===`finalizing`)&&su()}),chrome.runtime.onMessage.addListener((e,t,n)=>e?.type===`VOICE_TOGGLE`?(Bu(),n?.({success:!0}),!1):(e?.type===`ASR_STATUS_CHANGED`&&ou(),!1)),window.addEventListener(`pagehide`,()=>{Uu()}),document.addEventListener(`visibilitychange`,()=>{document.hidden&&V.phase===`recording`&&Uu()}),await ou()&&await Wu()&&setTimeout(()=>{Bu()},220)}var Ju=`panel_`+Date.now().toString(36)+`_`+Math.random().toString(36).slice(2,8),Yu=new Set,Xu=new Set,Zu=null,Qu=new Map,$u=`queue-context-cleared`,ed=`queue-context-restored`;function td(e){Zu=e}function nd(e){return N.generatingSessionIds.has(e||N.activeSessionId)}function rd(){return{quotedContextText:N.quotedContextText||``,selectedContextText:N.selectedContextText||``,selectedSkills:(N.selectedSkills||[]).slice(),selectedMcpServices:(N.selectedMcpServices||[]).slice(),knowledgeRefs:(N.knowledgeRefs||[]).slice(),selectedPage:N.selectedPage?{...N.selectedPage}:null,attachedImages:(N.attachedImages||[]).slice(),attachedFiles:(N.attachedFiles||[]).slice()}}function id(e){return e?e.attachmentSummary||(e.attachedImages||[]).length||(e.attachedFiles||[]).length?!0:!!(e.quotedContextText&&e.quotedContextText.trim()||e.selectedContextText&&e.selectedContextText.trim()||(e.selectedSkills||[]).length||(e.selectedMcpServices||[]).length||(e.knowledgeRefs||[]).length||e.selectedPage):!1}function ad(){return id(rd())}function od(){let e=rd();return id(e)&&cd(),e}function sd(e){e&&(e.quotedContextText&&(N.quotedContextText=e.quotedContextText),e.selectedContextText&&(N.selectedContextText=e.selectedContextText),(e.selectedSkills||[]).length&&(N.selectedSkills=e.selectedSkills.slice()),(e.selectedMcpServices||[]).length&&(N.selectedMcpServices=e.selectedMcpServices.slice()),(e.knowledgeRefs||[]).length&&(N.knowledgeRefs=e.knowledgeRefs.slice()),e.selectedPage&&(N.selectedPage={...e.selectedPage}),(e.attachedImages||[]).length&&(N.attachedImages=e.attachedImages.slice()),(e.attachedFiles||[]).length&&(N.attachedFiles=e.attachedFiles.slice()))}function cd(){let e=(N.attachedImages||[]).length>0;if(N.quotedContextText=``,N.selectedContextText=``,N.selectedSkills=[],N.selectedMcpServices=[],N.knowledgeRefs=[],N.selectedPage=null,N.attachedImages=[],N.attachedFiles=[],e){let e=document.getElementById(`imagePreviewBar`);e&&(e.innerHTML=``,e.style.display=`none`)}document.dispatchEvent(new CustomEvent($u))}var ld=new Set([`pending`,`extracting`]);function ud(){return(N.attachedFiles||[]).some(e=>ld.has(e&&e.status))}function dd(e){let t=e&&e.attachedImages||[],n=(e&&e.attachedFiles||[]).map(e=>{if(!e||typeof e.dataUrl!=`string`||!e.dataUrl.startsWith(`blob:`))return e;let t={...e};return delete t.dataUrl,t}),r={...e||{}};return delete r.attachedImages,delete r.attachedFiles,r.attachmentSummary=Ci({attachedImages:t,attachedFiles:n}),{light:r,heavy:t.length||n.length?{images:t,files:n}:null}}async function fd(e){if(!e)return{ok:!1,attachments:!1,wantsAttachments:!1};let t=await Ti(e.id)||Qu.get(e.id)||null,n=!!(e.attachmentSummary||e.contextSnapshot&&e.contextSnapshot.attachmentSummary);return sd({...e.contextSnapshot||{},attachedImages:t&&t.images||[],attachedFiles:t&&t.files||[]}),document.dispatchEvent(new CustomEvent(ed,{detail:{snapshot:e.contextSnapshot||{}}})),{ok:!0,attachments:!!t,wantsAttachments:n}}async function pd(e){return e?(Qu.delete(e),Ei(e)):!1}async function md({autoDrain:e=!0}={}){let t=document.getElementById(`userInput`),n=(t?.value||``).trim();if(!n)return{ok:!1,error:`empty`};Uu();let i=N.activeSessionId;if(!i)return L(r(`queue.noSession`),`error`),{ok:!1,error:`missing_session`};if(ud())return L(r(`queue.filesStillExtracting`),`warning`,4e3),{ok:!1,error:`files_extracting`};let a=od(),{light:o,heavy:s}=dd(a),c=await Qr({sessionId:i,text:n,contextSnapshot:o,hasContext:id(o),attachmentSummary:o.attachmentSummary,source:`manual`});return c.ok?(s&&((await wi(c.item.id,i,s)).ok||(Qu.set(c.item.id,s),L(r(`queue.attachmentsVolatile`),`warning`,5e3))),t&&(t.value=``,t.style.height=`auto`,t.dispatchEvent(new Event(`input`)),t.focus()),L(r(`queue.enqueued`,{position:c.position}),`success`),document.dispatchEvent(new CustomEvent(`queue-enqueued`,{detail:{sessionId:i,item:c.item}})),e&&!nd(i)&&!Zr(i)&&gd(i),c):(sd(a),document.dispatchEvent(new CustomEvent(ed,{detail:{snapshot:a}})),c.error===`queue_full`?L(r(`queue.queueFull`,{limit:c.limit}),`warning`):L(r(`queue.enqueueFailed`),`error`),c)}async function hd(e){try{let{list:t}=await Fi(),n=(t||[]).find(t=>t.id===e);return n?{messageHistory:Array.isArray(n.messageHistory)?n.messageHistory.slice():[],model:n.model,useTools:n.useTools,enabledTools:Array.isArray(n.enabledTools)?n.enabledTools.slice():n.enabledTools,agentId:n.agentId,temperature:n.temperature,topP:n.topP,contextCompaction:n.contextCompaction,workdir:n.workdir||null,workdirAgentId:n.workdirAgentId||null}:null}catch(e){return a.warn(`[QueueRunner] load session state failed:`,e?.message||e),null}}async function gd(e){let t=e||N.activeSessionId;if(!(!t||!Zu)){if(Yu.has(t)){Xu.add(t);return}Yu.add(t);try{do Xu.delete(t),await _d(t);while(Xu.has(t)&&!Zr(t))}finally{Yu.delete(t)}}}async function _d(e){if(nd(e)||Zr(e))return;let t=qr(e);if(!t)return;if((t.attempts||0)>=5){await ii(e,t.id,{status:R.FAILED,note:`too_many_attempts`}),L(r(`queue.tooManyAttempts`,{count:5}),`error`,5e3);return}if(!await ui(e,t.id,Ju)){a.debug(`[QueueRunner] lease held by another panel, skip:`,t.id);return}await ti(e,t.id,R.DISPATCHING,{attempts:(t.attempts||0)+1,lastError:null});let n=await Ti(t.id)||Qu.get(t.id)||null;Qu.delete(t.id);let i=!!t.attachmentSummary&&!n;i&&L(r(`queue.attachmentsMissing`),`warning`,5e3);let o={quotedContextText:``,selectedContextText:``,selectedSkills:[],selectedMcpServices:[],knowledgeRefs:[],selectedPage:null,...t.contextSnapshot||{},attachedImages:n&&n.images||[],attachedFiles:n&&n.files||[]},s=e===N.activeSessionId,c=null;if(!s&&(c=await hd(e),!c)){let t=await di(e);t&&a.warn(`[QueueRunner] dropped queue of deleted session:`,e,t);return}let l={ok:!0};try{let n={text:t.text,fromQueue:!0,sessionId:e,context:o};s||(n.sessionState=c),l=await Zu(n)||{ok:!0}}catch(e){l={ok:!1,reason:e?.message||`dispatch_error`},a.error(`[QueueRunner] dispatch failed:`,e?.message||e)}Yr(e,t.id)?l.ok===!1?l.delivered?(await ii(e,t.id,{status:R.FAILED,note:l.reason||`failed`}),await Ei(t.id)):(await ri(e,t.id,`dispatch_failed`,l.reason||`dispatch_failed`),Xu.delete(e)):(await ii(e,t.id,{status:R.DONE,note:i?`relayed_no_attachments`:`relayed`}),await Ei(t.id)):a.debug(`[QueueRunner] item removed during dispatch, drop result:`,t.id)}var vd=new Set;function yd(e){let t=e||N.activeSessionId;return t?(vd.add(t),t):null}function bd(e){let t=e||N.activeSessionId;return!!(t&&qr(t))}async function xd(e){let t=e||N.activeSessionId;t&&(vd.delete(t),await li(t),await gd(t))}function Sd(e){Zr(e)||gd(e)}var Cd=new Map,wd=new Set,Td=new Map,Ed=new Map;function Dd(e){let t=e&&e.attachmentSummary;return t?(t.imageCount||0)>0||(t.fileCount||0)>0:!1}function Od(e,t){return`${e}\u0000${t}`}function kd(e,t){let n=Od(e,t),r=Cd.get(n);r&&(clearTimeout(r),Cd.delete(n))}async function Ad(e,t,n,r){kd(e,t);let i=Yr(e,t);!i||i.status!==R.INJECTING||(await ri(e,t,n,n),r&&L(r,`warning`,4e3))}function jd(e,t,n){return new Promise(r=>{let i=!1,a=e=>{i||(i=!0,r(e))},o=setTimeout(()=>a(null),2e3);try{chrome.runtime.sendMessage({type:`INJECT_MESSAGE`,sessionId:e,itemId:t,text:n},e=>{if(clearTimeout(o),chrome.runtime.lastError){a(null);return}a(e||null)})}catch{clearTimeout(o),a(null)}})}async function Md(e,t,n={}){let i=t||N.activeSessionId,a=n.auto===!0;if(!i||!e)return{ok:!1,error:`missing_session`};let o=Yr(i,e);if(!o)return{ok:!1,error:`not_found`};if(o.status!==R.QUEUED)return{ok:!1,error:`not_queued`};if(Dd(o))return a||L(r(`queue.injectNoAttachments`),`warning`,4e3),{ok:!1,error:`has_attachments`};let s=Od(i,e);if(wd.has(s))return{ok:!1,error:`in_flight`};wd.add(s);try{await ni(i,e),Cd.set(s,setTimeout(()=>{Ad(i,e,`timeout`,r(`queue.injectTimeout`))},_r));let t=await jd(i,e,o.text);if(!t)return{ok:!0,pending:!0};if(!t.accepted){let n=t.reason||`rejected`;return await Ad(i,e,n,r(n===`no_running_task`?`queue.injectNoTask`:`queue.injectFailed`)),{ok:!1,error:n}}return a?i===N.activeSessionId&&L(r(`queue.autoCarried`,{iteration:n.iteration??`?`}),`success`,2500):L(r(`queue.injectAccepted`),`success`,2500),{ok:!0,pending:!0}}finally{wd.delete(s)}}function Nd(e){let t=document.getElementById(`userInput`);t&&t.value.trim()===e&&(t.value=``,t.style.height=`auto`,t.dispatchEvent(new Event(`input`)),t.focus())}async function Pd(e){let t=N.activeSessionId,n=String(e||``).trim();if(!t||!n)return{ok:!1,error:`empty`};if(Uu(),!nd(t))return L(r(`queue.injectNoTask`),`warning`,3e3),{ok:!1,error:`no_running_task`};let i=`adhoc_`+Date.now().toString(36)+`_`+Math.random().toString(36).slice(2,7),a=setTimeout(()=>{Td.has(i)&&(Td.delete(i),L(r(`queue.injectTimeoutAdhoc`),`warning`,4e3))},_r);Td.set(i,{text:n,timer:a});let o=await jd(t,i,n);return o&&!o.accepted?(clearTimeout(a),Td.delete(i),L(o.reason===`no_running_task`?r(`queue.injectNoTask`):r(`queue.injectFailed`),`warning`,4e3),{ok:!1,error:o.reason}):(o&&o.accepted&&L(r(`queue.injectAccepted`),`success`,2500),{ok:!0,pending:!0})}function Fd(e){let t=e?.sessionId,n=Array.isArray(e?.items)?e.items:[];if(!t||n.length===0)return;let i=0;for(let r of n){let n=Td.get(r);if(n){clearTimeout(n.timer),Td.delete(r),Nd(n.text);continue}kd(t,r),Yr(t,r)&&(i++,ii(t,r,{status:R.INJECTED,note:`injected`,callId:e.callId||null,iteration:e.iteration??null}))}i>0&&t===N.activeSessionId&&L(r(`queue.injected`),`success`,2500),document.dispatchEvent(new CustomEvent(`queue-injected`,{detail:{sessionId:t,items:n,iteration:e.iteration??null}}))}function Id(e){let t=e?.sessionId,n=Array.isArray(e?.items)?e.items:[];if(!t||n.length===0)return;let i=e.reason||`rejected`,a=r(i===`task_ended`?`queue.injectNoTask`:`queue.injectFailed`);for(let e of n){let r=Td.get(e);if(r){clearTimeout(r.timer),Td.delete(e);continue}Ad(t,e,i,e===n[0]?a:null)}}function Ld(e){let t=e?.sessionId;if(!t||e.isSubtask===!0||Zr(t))return;let n=Pl(e.executionLog);if(!n)return;let r=qr(t),i=r&&!Dd(r)?r:null,o=N.chatConfig||{},s=Fl({tracker:Ed.get(t),callId:e.callId||null,iteration:n,everyN:o.queueAutoCarryEveryNIterations,enabled:o.queueAutoCarry!==!1,hasCandidate:!!i});if(Ed.set(t,s.tracker),!s.carry)return;a.debug(`[QueueRunner] auto carry item`,i.id,`at iteration`,n,`session`,t);let c=e.callId||null;Md(i.id,t,{auto:!0,iteration:n}).then(e=>{!e||e.ok!==!0||Ed.set(t,Il(Ed.get(t),{callId:c}))})}function Rd(e){!e||typeof e!=`object`||(e.type===`INJECT_ABSORBED`?Fd(e):e.type===`INJECT_REJECTED`?Id(e):e.type===`EXECUTION_STATUS_UPDATE`&&Ld(e))}async function zd(){try{if(zr()){a.warn(`[QueueRunner] skip attachment prune in degraded mode`);return}let e=new Set;for(let t of Xr())for(let n of Ur(t))e.add(n.id);let t=await Oi(e);t&&a.debug(`[QueueRunner] pruned orphan attachments:`,t)}catch(e){a.warn(`[QueueRunner] prune orphan attachments failed:`,e?.message||e)}}var Bd=!1,Vd=null,Hd=[];function Ud(e,t){document.addEventListener(e,t),Hd.push([e,t])}var Wd=1500;function Gd(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,t(e))},i=setTimeout(()=>r(null),Wd);try{chrome.runtime.sendMessage({type:`QUERY_SESSION_RUNNING`,sessionId:e},e=>{if(clearTimeout(i),chrome.runtime.lastError){r(null);return}r(!!(e&&e.running))})}catch{clearTimeout(i),r(null)}})}async function Kd(){if(!N.activeSessionId)return!1;let e=Xr();if(e.length===0)return!0;let t=!1;for(let n of e){if(Zr(n)||nd(n)||!qr(n))continue;let e=await Gd(n);if(e===null){t=!0;continue}if(!e&&!(Zr(n)||nd(n)))return await gd(n),!0}return!t}function qd(){if(Vd)return;let e=0,t=async()=>{if(Vd=null,++e>25)return;let n=!1;try{n=await Kd()}catch(e){a.warn(`[QueueRunner] auto-resume attempt failed:`,e?.message||e)}n||(Vd=setTimeout(t,800))};Vd=setTimeout(t,300)}async function Jd({autoResume:e=!0}={}){Bd||(Bd=!0,await Br(),Vr(),zd(),Al(Sd),typeof chrome<`u`&&chrome.runtime?.onMessage?.addListener&&chrome.runtime.onMessage.addListener(Rd),Ud(`task-stop-requested`,e=>{let t=e?.detail?.sessionId||N.activeSessionId;if(t){if(vd.delete(t)){li(t).then(()=>gd(t));return}ci(t,`user_stopped`)}}),Ud(`generating-state-changed`,()=>{let e=N.activeSessionId;if(e){if(N.isGenerating&&Zr(e)){li(e);return}for(let e of Xr())if(!(Zr(e)||nd(e))&&qr(e)){gd(e);break}}}),Ud(`session-switched`,()=>qd()),Ud(`visibilitychange`,()=>{document.visibilityState===`visible`&&qd()}),e&&qd())}async function Yd(e){let t=e||N.activeSessionId;t&&(await li(t),await gd(t))}var Xd=[/(?:按|按照|以|用|走|使用|开启|启用|切换?到)\s*(?:goal|目标)\s*模式/i,/(?:进入|改成|改为|设为|设置为|切换到)\s*(?:goal|目标)\s*模式/i,/\b(?:in|use|using|enable|enter|switch\s+to|with)\s+(?:the\s+)?goal\s+mode\b/i,/(?:无人值守|不用管我|别停下来|不要停|直到(?:我|你)(?:叫停|喊停))/,/\bunattended\b|\bwithout\s+(?:me|supervision)\b|\bdon'?t\s+stop\s+until\b/i,/(?:持续|一直|连续)(?:执行|跑|做|干|尝试|迭代)\s*(?:到|直到)/,/(?:跑到|做到|干到|做到)(?:完成|通过|结束|成功)/,/\bkeep\s+(?:working|going|trying|iterating)\s+until\b/i,/\brun\s+until\s+(?:done|complete|passing|it\s+passes)\b/i],Zd=[/直到\s*[^。;;\n]{1,40}?(?:全部|都)?(?:通过|完成|跑通|变绿)/,/(?:确保|保证)\s*[^。;;\n]{1,40}?(?:通过|跑通|可用)/,/\buntil\s+[^.;\n]{1,40}?(?:pass|passes|green|works)\b/i],Qd=/(?:不要|不用|不必|无需|取消|关闭|停用|停止|退出|不按|不以|别|不)\s*$/,$d=/\b(?:do\s+not|don'?t|does\s+not|doesn'?t|never|avoid|without|no\s+need\s+to)\s+(?:(?:use|using|enable|enabling|enter|entering|switch(?:ing)?\s+to|turn\s+on|activate|run(?:\s+in)?|go(?:\s+with)?)\s*)?$/i,ef=2e3,tf=40;function nf(e,t,n){let r=[];for(let i of t){let t=i.flags.includes(`g`)?i.flags:`${i.flags}g`,a=new RegExp(i.source,t),o;for(;(o=a.exec(e))!==null&&o[0].length!==0;){let t=e.slice(Math.max(0,o.index-tf),o.index);if(!(n&&(Qd.test(t)||$d.test(t)))&&(r.push(o[0].trim()),o[0].length===0))break}}return r}function rf(e){let t={detected:!1,strength:`none`,matches:[]};if(typeof e!=`string`)return t;let n=e.trim();if(!n)return t;let r=n.slice(0,ef),i=nf(r,Xd,!0);if(i.length>0)return{detected:!0,strength:`strong`,matches:af(i).slice(0,3)};let a=nf(r,Zd,!0);return a.length>0?{detected:!1,strength:`weak`,matches:af(a).slice(0,3)}:t}function af(e){let t=new Set,n=[];for(let r of e){let e=r.toLowerCase();t.has(e)||(t.add(e),n.push(r))}return n}function of(e){if(typeof e!=`string`)return``;let t=e,n=nf(e.slice(0,ef),Xd,!0);for(let e of n)e&&(t=t.replace(e,` `));return t=t.replace(/^[\s,,。.、::;;-]+/,``).trim(),t||e.trim()}var sf={active:`goal.statusActive`,paused:`goal.statusPaused`,achieved:`goal.statusAchieved`,unmet:`goal.statusUnmet`,budget_limited:`goal.statusBudgetLimited`,cleared:`goal.statusCleared`},cf=new Set([`achieved`,`unmet`,`cleared`]),H=null;function lf(e){return document.getElementById(e)}function uf(e){let t=sf[e];return t?r(t):String(e||``)}function df(e){return!!e&&cf.has(e.status)}function ff(e){return new Promise(t=>{try{chrome.runtime.sendMessage(e,e=>{if(chrome.runtime.lastError){a.debug(`[GoalPanel] message failed:`,chrome.runtime.lastError.message),t(null);return}t(e||null)})}catch(e){a.debug(`[GoalPanel] message threw:`,e?.message),t(null)}})}function pf(e){return ff({type:`SET_GOAL`,...e})}function mf(){if(!H)return;let e=N.goalSnapshot,t=N.goalMode;H.toggle.checked=t;let n=t&&!!e&&(e.status===`paused`||e.status===`budget_limited`);H.group&&(H.group.dataset.goalIdle=n?`1`:``);let i=t||e&&!df(e);if(H.bar.style.display=i?``:`none`,!i)return;if(H.bar.dataset.status=e?e.status:`none`,H.status.textContent=e?uf(e.status):``,H.status.style.display=e?``:`none`,e){H.objective.textContent=e.objective||``,H.objective.title=e.objective||``;let t=se(e,r);n&&e.status===`paused`&&t.push(r(`goal.pausedHintInline`)),H.meta.textContent=t.join(` · `)}else H.objective.textContent=r(`goal.startHint`),H.objective.title=``,H.meta.textContent=``;let a=!!e&&e.status===`active`&&e.autoApprove===!0;H.approve.style.display=a?``:`none`;let o=!!e&&e.status===`active`,s=!!e&&(e.status===`paused`||e.status===`budget_limited`);H.pause.style.display=o?``:`none`,H.resume.style.display=s?``:`none`,H.edit.style.display=e?``:`none`,H.clear.style.display=e?``:`none`}function hf(){return N.activeSessionId||null}async function gf(e=hf()){if(!e)return N.goalSnapshot=null,mf(),null;let t=await ff({type:`GET_GOAL`,sessionId:e});return e===hf()?(N.goalSnapshot=t?.goal||null,mf(),N.goalSnapshot):null}var _f=null;async function vf(){return _f||(_f=await new Promise(e=>{try{chrome.storage.local.get([`goalConfig`],t=>e(t?.goalConfig||{}))}catch(t){a.debug(`[GoalPanel] read goalConfig failed:`,t?.message),e({})}}),_f)}async function yf(){let e=lf(`goalGroup`);if(!e)return;let t=await vf();e.style.display=t.enabled===!1?`none`:``}async function bf({sessionId:e=hf(),text:t=``,attachments:n=[]}={}){if(!e||!String(t||``).trim())return null;let i=await vf(),a=!!N.goalMode;if(i.enabled===!1)return a&&L(r(`goal.disabledHint`),`warning`),null;let o=t;if(!a){if(i.intentDetection===!1)return null;let e=rf(t);if(!e.detected)return e.strength===`weak`&&L(r(`goal.intentHint`),`info`,6e3),null;o=String(of(t)||``).trim()||t}let s=await pf({sessionId:e,action:`set`,objective:o,attachments:Array.isArray(n)?n:[],createdBy:a?`toggle`:`intent`,autoApprove:a});return!s||s.success===!1?(s?.disabled&&L(r(`goal.disabledHint`),`warning`),null):(a||L(r(`goal.intentDetected`),`info`,6e3),e===hf()?(N.goalSnapshot=s.goal||null,mf(),s.goal||null):s.goal||null)}function xf(e={}){let t=[],n=Array.isArray(e.attachedImages)?e.attachedImages.length:0;n>0&&t.push({kind:`image`,name:r(`goal.attachmentImage`,{count:n})});for(let n of Array.isArray(e.attachedFiles)?e.attachedFiles:[])!n||n.status!==`done`||!n.name||t.push({kind:`file`,name:String(n.name),detail:n.agentPath?`workspace file`:`inline text`});let i=e.selectedPage;i&&(i.title||i.url)&&t.push({kind:`page`,name:String(i.title||i.url),detail:i.id==null?``:`tab ${i.id}`});for(let n of Array.isArray(e.knowledgeRefs)?e.knowledgeRefs:[])n&&n.name&&t.push({kind:`knowledge`,name:String(n.name)});return t}function Sf(){N.goalSnapshot=null,mf()}function Cf(){return mf(),gf()}function wf(e=``){return new Promise(t=>{let n=document.createElement(`div`);n.className=`modal-overlay show`,n.innerHTML=`
|
|
94
|
+
`}).join(``),t.querySelectorAll(`.prototype-library-item`).forEach(e=>{let t=e.querySelector(`.prototype-library-item-info`),n=e.querySelector(`.prototype-library-item-open`),i=e.querySelector(`.prototype-library-item-local-open`),o=e.querySelector(`.prototype-library-item-optimize`),s=e.querySelector(`.prototype-library-item-delete`),c=e.querySelector(`.prototype-library-item-download`);t&&t.addEventListener(`click`,()=>{let t=e.dataset.id;Cc(t)}),n&&n.addEventListener(`click`,t=>{t.stopPropagation();let n=e.dataset.id;Cc(n)}),i&&i.addEventListener(`click`,e=>{e.stopPropagation();let t=i.dataset.path;chrome.runtime.sendMessage({type:`OPEN_LOCAL_PROTOTYPE`,path:t},e=>{e?.success||a.error(`[SidePanel] local browseropen failed:`,e?.error)})}),o&&o.addEventListener(`click`,t=>{t.stopPropagation();let n=o.dataset.id;kc(n,e.querySelector(`.prototype-library-item-title`)?.textContent||r(`uiProto.defaultTitle`)),Oc()}),s&&s.addEventListener(`click`,t=>{t.stopPropagation();let n=s.dataset.id;jc(n,e.querySelector(`.prototype-library-item-title`)?.textContent||r(`uiProto.defaultTitle`))}),c&&c.addEventListener(`click`,e=>{e.stopPropagation();let t=c.dataset.id;Ac(t)})})))}function Dc(e){let t=()=>{let t=document.getElementById(`prototypeLibrarySearch`),n=document.getElementById(`prototypeLibrarySort`),r=(t?.value||``).trim().toLowerCase(),i=n?.value||`createdAt_desc`,a=e;r&&(a=e.filter(e=>(e.title||``).toLowerCase().includes(r)||(e.description||``).toLowerCase().includes(r)));let[o,s]=i.split(`_`);a=[...a].sort((e,t)=>{let n;return n=o===`title`?(e.title||``).localeCompare(t.title||``,`zh-CN`):(e.createdAt||0)-(t.createdAt||0),s===`desc`?-n:n}),Ec(a)},n=document.getElementById(`prototypeLibrarySearch`),r=document.getElementById(`prototypeLibrarySort`);if(n){let e=n.cloneNode(!0);n.parentNode.replaceChild(e,n),e.addEventListener(`input`,t)}if(r){let e=r.cloneNode(!0);r.parentNode.replaceChild(e,r),e.addEventListener(`change`,t)}}function Oc(){let e=document.getElementById(`prototypeLibraryModal`);e&&e.classList.remove(`show`),a.debug(`[SidePanel] prototype page libraryhidden`)}function kc(e,t){let n=document.getElementById(`userInput`);n&&(n.value=r(`uiProto.optimizePrompt`,{id:e,title:t}),n.focus(),n.style.height=`auto`,n.style.height=n.scrollHeight+`px`),a.debug(`[SidePanel] from prototype page librarycontinue optimizeprototype:`,e)}async function Ac(e){try{let t=await Qe(e);if(!t||!t.html){a.error(`[SidePanel] download prototype failed:not foundprototype`,e);return}let n=_c(t.html),r=new Blob([n],{type:`text/html`}),i=URL.createObjectURL(r),o=document.createElement(`a`);o.href=i,o.download=(t.title||`prototype`).replace(/[^a-zA-Z0-9\u4e00-\u9fa5_-]/g,`_`)+`.html`,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(i),a.debug(`[SidePanel] prototype fromprototypelibrarydownload:`,o.download)}catch(e){a.error(`[SidePanel] download prototype failed:`,e)}}async function jc(e,t){if(await Mc(r(`uiProto.confirmDeleteTitle`),r(`uiProto.confirmDeleteMessage`,{title:t}),r(`common.delete`)))try{let t=await Qe(e);await xe(e),a.debug(`[SidePanel] prototype deleted:`,e),t?.localPath&&chrome.runtime.sendMessage({type:`DELETE_LOCAL_PROTOTYPE`,path:t.localPath},e=>{e?.success?a.debug(`[SidePanel] local prototypefile deleted:`,t.localPath):a.warn(`[SidePanel] local prototypefiledelete failed:`,e?.error)}),Tc()}catch(e){a.error(`[SidePanel] delete prototype failed:`,e),alert(r(`uiProto.deleteFailed`,{message:e.message}))}}function Mc(e,t,n=r(`common.confirm`)){return new Promise(r=>{let i=document.getElementById(`genericConfirmModal`),a=document.getElementById(`genericConfirmTitle`),o=document.getElementById(`genericConfirmMessage`),s=document.getElementById(`genericConfirmOkBtn`),c=document.getElementById(`genericConfirmCancelBtn`);if(!i){r(confirm(t));return}a.textContent=e,o.textContent=t,s.textContent=n;let l=()=>{i.classList.remove(`show`),s.removeEventListener(`click`,u),c.removeEventListener(`click`,d)},u=()=>{l(),r(!0)},d=()=>{l(),r(!1)};s.addEventListener(`click`,u),c.addEventListener(`click`,d),i.classList.add(`show`)})}function Nc(e){let t=document.createElement(`div`);return t.textContent=e,t.innerHTML}function Pc(e){if(!e)return``;let t=new Date(e),n=new Date-t;return n<6e4?r(`uiProto.justNow`):n<36e5?r(`uiProto.minutesAgo`,{count:Math.floor(n/6e4)}):n<864e5?r(`uiProto.hoursAgo`,{count:Math.floor(n/36e5)}):t.toLocaleDateString(`zh-CN`)}function Fc(e){pc=Math.max(mc,Math.min(hc,e)),pc=Math.round(pc*100)/100;let t=document.getElementById(`prototypeIframe`),n=document.getElementById(`prototypeZoomLevel`);t&&(t.style.zoom=pc),n&&(n.textContent=Math.round(pc*100)+`%`,pc===1?n.classList.remove(`zoomed`):n.classList.add(`zoomed`))}function Ic(){Fc(pc+gc),zc()}function Lc(){Fc(pc-gc),zc()}function Rc(){Fc(1)}function zc(){let e=document.getElementById(`prototypeZoomLevel`);e&&(e.classList.add(`flash`),setTimeout(()=>e.classList.remove(`flash`),150))}function Bc(e){!e.ctrlKey&&!e.metaKey||(e.preventDefault(),e.deltaY<0?Ic():Lc())}function Vc(e){(e.ctrlKey||e.metaKey)&&e.key===`0`&&(e.preventDefault(),Rc())}function Hc(){let e=document.getElementById(`prototypeCloseBtn`);e&&e.addEventListener(`click`,yc);let t=document.getElementById(`prototypeDownloadBtn`);t&&t.addEventListener(`click`,xc);let n=document.getElementById(`prototypeOpenTabBtn`);n&&n.addEventListener(`click`,Sc);let r=document.getElementById(`prototypeLocalOpenBtn`);r&&r.addEventListener(`click`,()=>{let e=r.dataset.path;e&&chrome.runtime.sendMessage({type:`OPEN_LOCAL_PROTOTYPE`,path:e},e=>{e?.success||a.error(`[SidePanel] local browseropen failed:`,e?.error)})});let i=document.getElementById(`prototypeContinueBtn`);i&&i.addEventListener(`click`,bc);let o=document.getElementById(`prototypeZoomInBtn`);o&&o.addEventListener(`click`,Ic);let s=document.getElementById(`prototypeZoomOutBtn`);s&&s.addEventListener(`click`,Lc);let c=document.getElementById(`prototypeZoomLevel`);c&&c.addEventListener(`click`,Rc);let l=document.getElementById(`prototypeContent`);l&&l.addEventListener(`wheel`,Bc,{passive:!1}),document.addEventListener(`keydown`,Vc);let u=document.getElementById(`prototypeLibraryCloseBtn`);u&&u.addEventListener(`click`,Oc),chrome.runtime.onMessage.addListener((e,t,n)=>{e.type===`SHOW_UI_PROTOTYPE`&&(a.debug(`[SidePanel] received showprototyperequested :`,e),e.data.localOpened?a.debug(`[SidePanel] prototype inagent-side browseropen,skip popup`):e.data.isRemoteAgent?(a.debug(`[SidePanel] remoteagent,will use browserlabelpageautoopenprototype`),wc(e.data.prototypeId)):Cc(e.data.prototypeId),n({success:!0}))}),a.debug(`[SidePanel] UI prototype moduleeventinitializing`)}var Uc={enabled:!1,thresholdRatio:.85,minPending:4,maxFailures:2};function Wc(e,t){let n=Number(e);return Number.isFinite(n)&&n>0&&n<=1?n:t}function Gc(e,t){let n=Number(e);return Number.isFinite(n)&&n>=0?Math.floor(n):t}function Kc({enabled:e,ratio:t,thresholdRatio:n,pendingCount:r,minPending:i,isGenerating:a,isolateChat:o}={}){if(!e||a||!o)return!1;let s=Wc(n,Uc.thresholdRatio),c=Gc(i,Uc.minPending);return!Number.isFinite(t)||t<s?!1:Gc(r,0)>=c}function qc(e){let t=e?.messageHistory||[],n=e?.activeCompaction?.upToMessageId;if(!n)return t.length;let r=t.findIndex(e=>e.messageId===n);return r===-1?t.length:t.length-r-1}var Jc=0;function Yc(){Jc=0}async function Xc({state:e,getRatio:t,compact:n}={}){let r=e?.chatConfig||{},i=r.autoCompaction===!0;if(!i)return{attempted:!1,success:!1,reason:`disabled`};if(Jc>=Uc.maxFailures)return{attempted:!1,success:!1,reason:`backoff`};let o;try{o=Number(t?t():NaN)}catch(e){return a.warn(`[AutoCompaction] usage compute failed, send continues:`,e?.message),{attempted:!1,success:!1,reason:`usage_unavailable`}}let s=qc(e);if(!Kc({enabled:i,ratio:o,thresholdRatio:r.autoCompactionThreshold,pendingCount:s,isGenerating:!!e?.isGenerating,isolateChat:!!e?.isolateChat}))return{attempted:!1,success:!1,reason:`not_needed`};a.debug(`[AutoCompaction] triggered`,{ratio:o,pendingCount:s});let c=null;try{c=await n({silent:!0})}catch(e){return a.warn(`[AutoCompaction] compact threw, send continues:`,e?.message),Jc++,{attempted:!0,success:!1,reason:`exception`}}return c?.success?(Yc(),{attempted:!0,success:!0}):(Jc++,a.debug(`[AutoCompaction] skipped send:`,c?.reason),{attempted:!0,success:!1,reason:c?.reason||`failed`})}var Zc=null,Qc=`global`,$c=new Map;function el(){try{chrome.windows?.getCurrent?.().then?.(e=>{e?.id!=null&&(Zc=e.id)}).catch?.(e=>{a.debug(`[PanelContext] query current window failed:`,e?.message)})}catch(e){a.debug(`[PanelContext] init window query failed:`,e?.message)}try{chrome.storage?.local?.get?.([`sidePanelScope`],e=>{Qc=e?.sidePanelScope===`tab-specific`?`tab-specific`:`global`}),chrome.storage?.onChanged?.addListener?.((e,t)=>{t!==`local`||!e?.sidePanelScope||(Qc=e.sidePanelScope.newValue===`tab-specific`?`tab-specific`:`global`)})}catch(e){a.debug(`[PanelContext] init scope mirror failed:`,e?.message)}}function tl(){return Zc}function nl(e){e&&typeof N.currentTabId==`number`&&$c.set(e,N.currentTabId)}function rl(e,t){e&&(typeof t==`number`?$c.set(e,t):$c.delete(e))}function il(e){if(!e)return null;let t=$c.get(e);return typeof t==`number`?t:null}function al(e){let t=null;try{t=typeof document<`u`?!!document.hidden:null}catch{}return{windowId:Zc,hostTabId:il(e),scope:Qc,panelHidden:t}}var ol=0,sl=500,cl=[{frequency:523.25,startTime:0,duration:.12,type:`sine`,gain:.3},{frequency:659.25,startTime:.09,duration:.12,type:`sine`,gain:.3},{frequency:783.99,startTime:.18,duration:.22,type:`sine`,gain:.35}],ll=[{frequency:440,startTime:0,duration:.16,type:`square`,gain:.22},{frequency:349.23,startTime:.14,duration:.3,type:`square`,gain:.22}],ul=[`#FF3B30`,`#FF9500`,`#FFCC00`,`#34C759`,`#00C7BE`,`#007AFF`,`#AF52DE`,`#FF2D55`],dl=120,fl=4e3,pl=600,ml=1e3,hl=.25,gl=.99,_l=.3,vl=.6,yl=9999;function bl(){return new Promise(e=>{try{chrome.storage.local.get([`completionSoundEnabled`,`completionConfettiEnabled`],t=>{e({soundEnabled:t?.completionSoundEnabled!==!1,confettiEnabled:t?.completionConfettiEnabled!==!1})})}catch(t){a.debug(`[CompletionFeedback] read config failed, use defaults:`,t?.message),e({soundEnabled:!0,confettiEnabled:!0})}})}function xl(e){try{let t=window.AudioContext||window.webkitAudioContext;if(!t){a.debug(`[CompletionFeedback] AudioContext unavailable`);return}let n=new t;n.state===`suspended`&&typeof n.resume==`function`&&n.resume().catch(()=>{});let r=n.currentTime,i=0;for(let t of e){let e=n.createOscillator(),a=n.createGain();e.type=t.type||`sine`,e.frequency.value=t.frequency;let o=r+t.startTime,s=o+t.duration;a.gain.setValueAtTime(1e-4,o),a.gain.exponentialRampToValueAtTime(t.gain,o+.012),a.gain.exponentialRampToValueAtTime(1e-4,s),e.connect(a),a.connect(n.destination),e.start(o),e.stop(s+.02),s>i&&(i=s)}let o=Math.max(0,(i-r)*1e3)+200;setTimeout(()=>{try{n.close()}catch{}},o)}catch(e){a.debug(`[CompletionFeedback] play tone failed:`,e?.message)}}function Sl(){xl(cl),a.debug(`[CompletionFeedback] success sound played`)}function Cl(){xl(ll),a.debug(`[CompletionFeedback] failure sound played`)}function wl(){try{return typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches}catch{return!1}}function Tl(){try{if(!document.body)return;let e=window.innerWidth,t=window.innerHeight;if(e<=0||t<=0)return;let n=document.createElement(`canvas`);n.style.cssText=`position:fixed;inset:0;pointer-events:none;z-index:${yl};`;let r=window.devicePixelRatio||1;n.width=Math.floor(e*r),n.height=Math.floor(t*r),n.style.width=e+`px`,n.style.height=t+`px`,document.body.appendChild(n);let i=n.getContext(`2d`);if(!i){n.remove();return}i.scale(r,r);let o=[{x:e*.15,y:t+10,baseAngle:-Math.PI/2+_l},{x:e*.85,y:t+10,baseAngle:-Math.PI/2-_l}],s=[],c=0,l=0,u=performance.now(),d=e=>{let t=Math.min(dl,Math.floor(Math.min(e,pl)/pl*dl));for(;c<t;){let e=o[c%o.length],t=e.baseAngle+(Math.random()-.5)*vl,n=12+Math.random()*8,r=4+Math.random()*4;s.push({x:e.x+(Math.random()-.5)*20,y:e.y,vx:Math.cos(t)*n,vy:Math.sin(t)*n,size:r,color:ul[Math.floor(Math.random()*ul.length)],rotation:Math.random()*Math.PI*2,rotationSpeed:(Math.random()-.5)*.3,shape:Math.random()<.5?`rect`:`circle`}),c++}},f=r=>{let a=r-u;if(a>=fl){cancelAnimationFrame(l),n.remove();return}d(a),i.clearRect(0,0,e,t);let o=fl-ml,c=a>o?Math.max(0,1-(a-o)/ml):1;for(let n=s.length-1;n>=0;n--){let r=s[n];if(r.vy+=hl,r.vx*=gl,r.vy*=gl,r.x+=r.vx,r.y+=r.vy,r.rotation+=r.rotationSpeed,r.y-r.size>t||r.x+r.size<0||r.x-r.size>e){s.splice(n,1);continue}i.save(),i.globalAlpha=c,i.translate(r.x,r.y),i.rotate(r.rotation),i.fillStyle=r.color,r.shape===`rect`?i.fillRect(-r.size/2,-r.size/2,r.size,r.size*.6):(i.beginPath(),i.arc(0,0,r.size/2,0,Math.PI*2),i.fill()),i.restore()}l=requestAnimationFrame(f)};l=requestAnimationFrame(f),a.debug(`[CompletionFeedback] confetti launched`)}catch(e){a.debug(`[CompletionFeedback] launch confetti failed:`,e?.message)}}function El(e,t,n,r){try{chrome.runtime.sendMessage({type:`TASK_FEEDBACK_NOTIFY`,success:e,sessionId:t||null,error:n||``,question:r||``,panel:al(t)})?.catch?.(()=>{})}catch(e){a.debug(`[CompletionFeedback] desktop notify failed:`,e?.message)}}async function Dl(e=null,t=``){try{let n=Date.now();if(n-ol<sl){a.debug(`[CompletionFeedback] throttled, skip`);return}ol=n;let{soundEnabled:r,confettiEnabled:i}=await bl();r&&Sl(),i&&!wl()&&Tl(),El(!0,e,``,t)}catch(e){a.debug(`[CompletionFeedback] unexpected error:`,e?.message||e)}}async function Ol(e=null,t=``,n=``){try{let r=Date.now();if(r-ol<sl){a.debug(`[CompletionFeedback] throttled, skip`);return}ol=r;let{soundEnabled:i}=await bl();i&&Cl(),El(!1,e,t,n)}catch(e){a.debug(`[CompletionFeedback] unexpected error:`,e?.message||e)}}var kl=new Set;function Al(e){return typeof e==`function`?(kl.add(e),()=>kl.delete(e)):()=>{}}function jl(e){let t=e||N.activeSessionId;if(t){N.generatingSessionIds.delete(t);try{Ni(t)}catch(e){a.warn(`[GenerationLifecycle] markSessionCompleted failed:`,e?.message)}typeof document<`u`&&typeof CustomEvent==`function`&&(document.dispatchEvent(new CustomEvent(`generating-state-changed`)),document.dispatchEvent(new CustomEvent(`generation-ended`,{detail:{sessionId:t}})));for(let e of kl)try{e(t)}catch(e){a.error(`[GenerationLifecycle] end handler failed:`,e?.message)}}}function Ml(e){let t=Number(e);return!Number.isFinite(t)||t<=0?3:Math.min(20,Math.max(1,Math.round(t)))}function Nl(){return{callId:null,carried:0,lastIteration:null}}function Pl(e){let t=0;for(let n of e||[]){let e=Number(n&&n.iteration);Number.isFinite(e)&&e>t&&(t=e)}return t}function Fl(e){let{tracker:t,callId:n=null,iteration:r,everyN:i,enabled:a=!0,hasCandidate:o=!0}=e||{},s=t&&typeof t==`object`?{callId:t.callId??null,carried:Number(t.carried)||0,lastIteration:t.lastIteration??null}:Nl(),c=Number(r);if(!Number.isFinite(c)||c<=0)return{carry:!1,reason:`invalid_iteration`,tracker:s};let l=!!n&&!!s.callId&&n!==s.callId,u=s.lastIteration!=null&&c<s.lastIteration;if((l||u)&&(s=Nl()),n&&!s.callId&&(s={...s,callId:n}),!a)return{carry:!1,reason:`disabled`,tracker:s};if(c<2)return{carry:!1,reason:`too_early`,tracker:s};if(!o)return{carry:!1,reason:`no_candidate`,tracker:s};if(s.carried>=3)return{carry:!1,reason:`call_limit`,tracker:s};let d=Ml(i);return s.lastIteration!=null&&c-s.lastIteration<d?{carry:!1,reason:`interval_not_reached`,tracker:s}:{carry:!0,reason:`carry`,tracker:{callId:s.callId||n||null,carried:s.carried,lastIteration:c}}}function Il(e,{callId:t=null}={}){let n=e&&typeof e==`object`?e:Nl();return t&&n.callId&&t!==n.callId?n:{...n,carried:(Number(n.carried)||0)+1}}var Ll=/[\p{P}\p{S}]/gu;function Rl(e){return Array.isArray(e)?e.map(e=>e&&e.text||``).join(``):``}function zl(e){return String(e||``).replace(/[\s\u3000]/g,``).replace(Ll,``)}function Bl(e,t){if(!Array.isArray(e))return e;let n=t&&t.id,r=t&&typeof t.text==`string`?t.text:null;if(r===null||typeof n!=`number`)return e;let i=!1,a=e.map(e=>!e||e.id!==n||e.state===`locked`?e:(i=!0,{...e,text:r}));return i?a:e}function Vl(e,t,n){let r=String(t||``),i=String(n||``),a={lockedIds:[],shift:0,items:e,len:r.length};if(r===i||!Array.isArray(e)||e.length===0)return a;let o=0,s=Math.min(r.length,i.length);for(;o<s&&r[o]===i[o];)o++;let c=0,l=Math.min(r.length-o,i.length-o);for(;c<l&&r[r.length-1-c]===i[i.length-1-c];)c++;let u=o,d=r.length-c;if(u>=r.length&&d>=r.length){let t=e[e.length-1],n=t&&t.text?t.text.length:0,a=i.slice(Math.max(0,r.length-n)),o=e.map((t,n)=>n===e.length-1?{...t,text:a}:t);return{lockedIds:[t.id],shift:0,items:o,len:i.length}}let f=[],p=0;for(let t of e){let e=(t&&t.text?t.text:``).length;u<p+e&&d>p&&f.push(t.id),p+=e}if(f.length===0)return{lockedIds:[],shift:u===0?i.length-r.length:0,items:e,len:r.length};let m=i.length-r.length,h=d+m,g=e=>e<=u?e:e>=d?e+m:u+Math.min(e-u,Math.max(0,h-u)),_=0;return{lockedIds:f,shift:0,items:e.map(e=>{let t=(e&&e.text?e.text:``).length,n=g(_),r=g(_+t);return _+=t,{...e,text:i.slice(n,r)}}),len:i.length}}function Hl(e,t){if(!Array.isArray(e)||e.length===0)return{items:Array.isArray(e)?e:[],changed:0,takeAll:!1};let n=Rl(e),r=String(t||``);if(!r)return{items:e,changed:0,takeAll:!1};let i=zl(n),a=zl(r);if(i===a)return{items:e,changed:0,takeAll:!1};if(Math.abs(i.length-a.length)+Ul(i,a)>2||i.length!==a.length)return e.some(e=>e&&e.state===`locked`)?{items:e,changed:0,takeAll:!1}:{items:[{id:e[0]&&typeof e[0].id==`number`?e[0].id:null,text:r,state:`refined`}],changed:1,takeAll:!0};let o=n.split(``),s=0,c=0;for(let e=0;e<o.length;e++)zl(o[e])!==``&&(s<a.length&&o[e]!==a[s]&&(o[e]=a[s],c+=1),s+=1);if(c===0)return{items:e,changed:0,takeAll:!1};let l=o.join(``),u=0;return{items:e.map(e=>{let t=(e&&e.text?e.text:``).length,n=e&&e.state===`locked`?e.text:l.slice(u,u+t);return u+=t,e&&e.state===`locked`?e:{...e,text:n}}),changed:c,takeAll:!1}}function Ul(e,t){if(e.length!==t.length)return 2**53-1;let n=0;for(let r=0;r<e.length;r++)e[r]!==t[r]&&(n+=1);return n}n(`zh`,{voice:{start:`语音输入(开始录音)`,stop:`结束录音并转写`,recording:`正在录音`,listening:`正在聆听…`,transcribing:`正在转写…`,cancel:`取消录音`,done:`完成`,noSpeech:`没有听到声音`,noResult:`未识别到语音`,micDenied:`麦克风未授权`,micDeniedHelp:`侧边栏里浏览器不会弹授权框,请到配置页「语音输入 → 麦克风权限」授权一次`,micDeniedAction:`去授权`,micDeniedActionTitle:`打开配置页授权麦克风(侧边栏内无法弹出授权框)`,unavailable:`语音功能不可用`,modelMissing:`缺少语音模型`,modelMissingHelp:`请在配置页「语音」Tab 中导入模型包`,busy:`有语音任务正在进行`,failed:`语音识别失败`,connectionLost:`连接中断`,tooShort:`录音太短`,maxDuration:`已达单次录音时长上限,正在转写…`,unsupported:`当前浏览器不支持录音`,keyRightAlt:`右侧 Alt`,keyRightCtrl:`右侧 Ctrl`,btnTitle:`语音输入({keys})`,deviceFallback:`原麦克风不可用,已改用系统默认`,refineListening:`正在听…(已定稿 {n} 句)`,refineCorrecting:`正在校正…`,refineCorrected:`已校正 {n} 处`,refineDegraded:`本机性能有限,已关闭逐句精修(松手后仍会整体校正)`}}),n(`en`,{voice:{start:`Voice input (start recording)`,stop:`Stop and transcribe`,recording:`Recording`,listening:`Listening…`,transcribing:`Transcribing…`,cancel:`Cancel recording`,done:`Done`,noSpeech:`No sound detected`,noResult:`No speech recognised`,micDenied:`Microphone not granted`,micDeniedHelp:`The browser cannot prompt inside the side panel — grant it once in Options → Voice Input → Microphone permission`,micDeniedAction:`Grant access`,micDeniedActionTitle:`Open options to grant microphone access (the side panel cannot show the prompt)`,unavailable:`Voice input unavailable`,modelMissing:`Speech model missing`,modelMissingHelp:`Import a model pack in the Options "Voice" tab`,busy:`Another voice task is running`,failed:`Speech recognition failed`,connectionLost:`Connection lost`,tooShort:`Recording too short`,maxDuration:`Recording length limit reached, transcribing…`,unsupported:`Recording is not supported in this browser`,keyRightAlt:`Right Alt`,keyRightCtrl:`Right Ctrl`,btnTitle:`Voice input ({keys})`,deviceFallback:`Selected microphone unavailable — using the system default`,refineListening:`Listening… ({n} sentences finalized)`,refineCorrecting:`Refining…`,refineCorrected:`{n} correction(s) applied`,refineDegraded:`This machine is too slow for per-sentence refinement (the final pass still runs)`}});var Wl=15e3,Gl=16e3,Kl=2500,ql=.008,Jl=350,Yl=24,V={input:null,btn:null,bar:null,wave:null,timerEl:null,statusEl:null,permBtn:null,barEls:[],status:null,armed:!1,phase:`idle`,port:null,stream:null,ctx:null,node:null,source:null,startedAt:0,timer:null,silentSince:0,silenceWarned:!1,draft:null,lastText:``,appliedText:``,appliedValue:``,openText:``,mute:null,programmatic:!1,draftSupported:!0,finishWaitTimer:null,adjustInputHeight:null,shortcutCfg:{...lt},shortcutTrigger:null,shortcutBound:!1,deviceFellBack:!1};function Xl(e){return typeof e==`string`?e:``}function Zl(e){let t=Math.max(0,Math.floor(e/1e3));return`${String(Math.floor(t/60)).padStart(2,`0`)}:${String(t%60).padStart(2,`0`)}`}function Ql(e){let t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),n=``,r=32768;for(let e=0;e<t.length;e+=r)n+=String.fromCharCode.apply(null,t.subarray(e,e+r));return btoa(n)}function $l(e,t,n){if(t===n)return e;let r=t/n,i=Math.floor(e.length/r),a=new Float32Array(i);for(let t=0;t<i;t++){let n=t*r,i=Math.floor(n),o=n-i,s=e[i]||0;a[t]=s+((e[i+1]===void 0?s:e[i+1])-s)*o}return a}function eu(e){let t=new Int16Array(e.length);for(let n=0;n<e.length;n++){let r=e[n]<-1?-1:e[n]>1?1:e[n];t[n]=r<0?r*32768:r*32767}return t}async function tu(e=!1){try{let t=await chrome.runtime.sendMessage({type:`ASR_GET_STATUS`,force:e});if(t&&t.success&&t.status)return V.status=t.status,V.status}catch(e){a.debug(`[Voice] status fetch failed:`,e?.message||e)}return V.status=null,null}function nu(e){return!e||e.success===!1?!1:typeof e.available==`boolean`?e.available:e.deps?.ready===!0&&e.modelsReady===!0&&e.enabled===!0}function ru({value:e,draft:t,text:n,caret:r,canReplace:i=!0}){let a=typeof e==`string`?e:``;if(!t)return{value:a,caret:a.length,len:0};if(!i){let e=typeof r==`number`?Math.min(Math.max(0,r),a.length):a.length;return{value:a.slice(0,e)+n+a.slice(e),caret:e+n.length,len:0}}let o=Math.min(Math.max(0,t.start),a.length),s=Math.min(Math.max(o,t.start+t.len),a.length);return{value:a.slice(0,o)+n+a.slice(s),caret:o+n.length,len:n.length}}function iu({value:e,draft:t,canReplace:n=!0}){let r=typeof e==`string`?e:``;if(!t||!n||t.len<=0)return{value:r,caret:r.length};let i=Math.min(Math.max(0,t.start),r.length),a=Math.min(Math.max(i,t.start+t.len),r.length);return{value:r.slice(0,i)+r.slice(a),caret:i}}function au(e){return!e||e.isComposing||e.repeat?!1:e.altKey===!0&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&e.code===`KeyV`}async function ou(){return V.armed=nu(await tu()),V.btn&&(V.btn.style.display=V.armed?``:`none`),!V.armed&&V.phase!==`idle`&&Lu({rollback:!0}),V.armed}function su(){if(!V.draft||!V.input)return;let e=Rl(V.draft.items),t=V.input.value,n=Xl(V.appliedValue),r=V.draft.start,i=r+e.length,a=0;for(;a<n.length&&a<t.length&&n[a]===t[a];)a+=1;let o=0,s=Math.min(n.length-a,t.length-a);for(;o<s&&n[n.length-1-o]===t[t.length-1-o];)o+=1;let c=a;if(n.length-o<=r){V.draft.start=Math.max(0,r+(t.length-n.length));return}if(c>i)return;let l=Math.max(0,n.length-i),u=t.slice(r,Math.max(r,t.length-l)),d=Vl(V.draft.items,e,u);d.shift&&(V.draft.start+=d.shift),d.lockedIds.length!==0&&(V.draft.items=d.items.map(e=>d.lockedIds.includes(e.id)?{...e,state:`locked`}:e),V.draft.len=d.len)}function cu(){let e=V.input;if(!e)return{start:0,len:0,items:[]};let t=typeof e.selectionStart==`number`?e.selectionStart:e.value.length,n=typeof e.selectionEnd==`number`?e.selectionEnd:t;return t!==n&&e.setRangeText(``,t,n,`end`),{start:t,len:0,items:[]}}function lu(e,t){let n=Xl(e),r=Xl(t);return r?n?r.startsWith(n)?r.slice(n.length):null:r:``}function uu(e,t){let n=V.input;if(n){V.programmatic=!0,V.appliedValue=e,n.value=e;try{n.setSelectionRange(t,t)}catch{}V.programmatic=!1;try{document.dispatchEvent(new CustomEvent(`voice-draft-written`))}catch{}try{V.adjustInputHeight?.()}catch{}try{n.focus()}catch{}}}function du(e=!1){let t=V.input;if(!t||!V.draft)return;let n=Rl(V.draft.items);if(!e&&n===Xl(V.appliedText))return;let r=typeof t.selectionStart==`number`?t.selectionStart:void 0,i=V.draft.start,a=i+V.draft.len,o=ru({value:t.value,draft:{start:i,len:V.draft.len},text:n,caret:r,canReplace:V.draftSupported});typeof r==`number`&&r>i&&r<a&&(o.caret=i+Math.min(r-i,n.length)),V.draft.len=n.length,V.appliedText=n,uu(o.value,o.caret)}function fu(e){if(!V.input||!V.draft)return;let t=Array.isArray(V.draft.items)?V.draft.items:[],n=t.findIndex(e=>e.id===null),r=Xl(e);if(n>=0&&t[n].state===`locked`){let e=lu(V.openText,r);if(V.openText=r,!e)return;V.draft.items=t.map((t,r)=>r===n?{...t,text:t.text+e}:t)}else V.openText=r,V.draft.items=n>=0?t.map((e,t)=>t===n?{...e,text:r}:e):t.concat([{id:null,text:r,state:`draft`}]);du()}function pu(){let e=V.input;if(!e||!V.draft)return;let t=Array.isArray(V.draft.items)&&V.draft.items.some(e=>e.state===`locked`)?{value:e.value,caret:e.value.length}:iu({value:e.value,draft:V.draft,canReplace:V.draftSupported});if(t.value!==e.value){V.programmatic=!0,V.appliedValue=t.value,e.value=t.value;let n=Math.min(t.caret,e.value.length);try{e.setSelectionRange(n,n)}catch{}V.programmatic=!1;try{V.adjustInputHeight?.()}catch{}}V.draft=null,V.lastText=``,V.appliedText=``,V.openText=``}function mu(){if(V.wave){V.wave.textContent=``,V.barEls=[];for(let e=0;e<Yl;e++){let e=document.createElement(`i`);V.wave.appendChild(e),V.barEls.push(e)}}}function hu(e,t=``){V.statusEl&&(V.statusEl.textContent=e,V.statusEl.className=`voice-recorder-status`+(t?` is-${t}`:``))}function gu(){V.bar&&(V.bar.classList.add(`show`),V.bar.removeAttribute(`aria-hidden`))}function _u(e){V.permBtn&&(V.permBtn.style.display=e?``:`none`)}function vu(){let e=document.activeElement;if(!(!V.bar||!e||!V.bar.contains(e))){if(V.input&&typeof V.input.focus==`function`)try{V.input.focus({preventScroll:!0});return}catch{}try{e.blur()}catch{}}}function yu(){V.bar&&(typeof document>`u`||!document.body||(vu(),_u(!1),V.bar.classList.remove(`show`),V.bar.setAttribute(`aria-hidden`,`true`),V.barEls.forEach(e=>{e.style.height=``,e.style.opacity=``}),V.timerEl&&(V.timerEl.textContent=`00:00`)))}function bu(e){if(!V.barEls.length)return;let t=Math.min(1,Math.sqrt(Math.max(0,e))*6);for(let e=0;e<V.barEls.length-1;e++)V.barEls[e].style.height=V.barEls[e+1].style.height,V.barEls[e].style.opacity=V.barEls[e+1].style.opacity;let n=V.barEls[V.barEls.length-1];n.style.height=`${Math.max(2,Math.round(t*18))}px`,n.style.opacity=t>.06?`1`:`0.35`}function xu(e){V.btn&&(V.btn.classList.toggle(`recording`,e),V.btn.setAttribute(`aria-pressed`,e?`true`:`false`),V.btn.setAttribute(`aria-label`,r(e?`voice.stop`:`voice.start`)),V.btn.title=r(e?`voice.stop`:`voice.start`))}function Su(e){document.body?.classList.toggle(`voice-recording-active`,!!e)}function Cu(){if(V.port)return V.port;try{let e=chrome.runtime.connect({name:`asr`});return e.onMessage.addListener(zu),e.onDisconnect.addListener(()=>{V.port=null,(V.phase===`recording`||V.phase===`finalizing`)&&(Mu(),Nu(),V.draft=null,V.lastText=``,xu(!1),Su(!1),hu(r(`voice.connectionLost`),`warn`),setTimeout(()=>{V.phase===`idle`&&yu()},3500))}),V.port=e,e}catch(e){return a.warn(`[Voice] connect port failed:`,e?.message||e),null}}function wu(e,t){if(bu(t),Tu(t),V.port)try{V.port.postMessage({type:`audio`,data:Ql(e)})}catch(e){a.debug(`[Voice] post audio failed:`,e?.message||e)}}function Tu(e){if(V.phase!==`recording`&&V.phase!==`starting`)return;if(e>=ql){V.silentSince=0,V.silenceWarned&&(V.silenceWarned=!1,hu(r(`voice.listening`)));return}let t=Date.now();if(!V.silentSince){V.silentSince=t;return}V.silenceWarned||t-V.silentSince>=Kl&&(V.silenceWarned=!0,hu(r(`voice.noSpeech`),`warn`))}var Eu=[`voice-capture-worklet.js`,`dist/voice-capture-worklet.js`],Du;async function Ou(){if(Du!==void 0)return Du;for(let e of Eu){let t=``;try{t=chrome.runtime.getURL(e)}catch{continue}try{let e=await fetch(t);if(e&&e.ok)return Du=t,t}catch{}}return Du=null,null}async function ku(e,t){let n=await Ou();if(!n)throw Error(`worklet not found in extension`);await e.audioWorklet.addModule(n);let r=new AudioWorkletNode(e,`voice-capture`),i=Math.abs(e.sampleRate-Gl)>1;r.port.onmessage=t=>{let n=t.data;if(!n||n.type!==`chunk`||!n.pcm)return;let r=new Int16Array(n.pcm);if(i){let t=new Float32Array(r.length);for(let e=0;e<r.length;e++)t[e]=r[e]/32768;r=eu($l(t,e.sampleRate,Gl))}wu(r,n.rms||0)},t.connect(r),V.node=r}function Au(e,t){let n=e.createScriptProcessor(4096,1,1),r=Math.abs(e.sampleRate-Gl)>1;n.onaudioprocess=t=>{let n=t.inputBuffer.getChannelData(0),i=new Float32Array(n);r&&(i=$l(i,e.sampleRate,Gl));let a=0;for(let e=0;e<i.length;e++)a+=i[e]*i[e];wu(eu(i),Math.sqrt(a/Math.max(1,i.length)))},t.connect(n);let i=e.createGain();i.gain.value=0,n.connect(i),i.connect(e.destination),V.mute=i,V.node=n}async function ju(){if(!navigator.mediaDevices?.getUserMedia)throw hu(r(`voice.unsupported`),`warn`),Error(`unsupported`);let e=await ht(await ft());V.stream=e.stream,V.deviceFellBack=e.fellBack===!0;let t=window.AudioContext||window.webkitAudioContext,n;try{n=new t({sampleRate:Gl})}catch{n=new t}if(n.state===`suspended`)try{await n.resume()}catch{}V.ctx=n;let i=n.createMediaStreamSource(e.stream);V.source=i;try{await ku(n,i)}catch(e){a.warn(`[Voice] worklet unavailable, fallback to ScriptProcessor:`,e?.message||e),Au(n,i)}}function Mu(){V.timer&&=(clearInterval(V.timer),null);try{V.node?.port?.close?.()}catch{}try{V.node?.disconnect?.()}catch{}try{V.mute?.disconnect?.()}catch{}try{V.source?.disconnect?.()}catch{}try{V.stream?.getTracks?.().forEach(e=>e.stop())}catch{}try{V.ctx?.close?.()}catch{}V.node=null,V.mute=null,V.source=null,V.stream=null,V.ctx=null}function Nu(){V.finishWaitTimer&&=(clearTimeout(V.finishWaitTimer),null),V.phase=`idle`}function Pu(){let e=()=>{let e=Date.now()-V.startedAt;V.timerEl&&(V.timerEl.textContent=Zl(e));let t=V.status;e>=(t&&t.maxRecordingMs||300*1e3)&&Iu(`stop`)};V.timer&&clearInterval(V.timer),V.timer=setInterval(e,200),e()}async function Fu(e={}){if(V.phase!==`idle`||!V.armed&&!e.force&&(await ou(),!V.armed||V.phase!==`idle`))return!1;V.phase=`starting`,V.lastText=``,V.appliedText=``,V.openText=``,V.draft=cu(),V.appliedValue=V.input?V.input.value:``,V.draftSupported=!0,V.silentSince=0,V.silenceWarned=!1,gu(),hu(r(`voice.listening`)),xu(!0),Su(!0);let t=Cu();if(!t)return hu(r(`voice.failed`),`warn`),Nu(),xu(!1),Su(!1),!1;try{await ju()}catch(e){if(V.phase!==`starting`)return Mu(),!1;let n=e?.name||``,i=n===`NotAllowedError`||n===`SecurityError`;i?(hu(r(`voice.micDenied`),`warn`),_u(!0)):hu(r(`voice.failed`),`warn`),Mu(),Nu(),xu(!1),Su(!1);try{t.postMessage({type:`cancel`})}catch{}return setTimeout(()=>{V.phase===`idle`&&yu()},i?12e3:4e3),!1}if(V.phase!==`starting`)return Mu(),!1;V.startedAt=Date.now(),V.phase=`recording`,hu(r(`voice.listening`)),V.deviceFellBack&&(V.deviceFellBack=!1,hu(r(`voice.deviceFallback`),`warn`),setTimeout(()=>{V.phase===`recording`&&hu(r(`voice.listening`))},4e3)),Pu();try{t.postMessage({type:`start`,language:V.status&&V.status.language||`auto`})}catch(e){a.debug(`[Voice] post start failed:`,e?.message||e)}return!0}function Iu(e){if(V.phase!==`recording`)return;V.phase=`finalizing`;let t=Date.now()-V.startedAt;if(Mu(),xu(!1),Su(!1),e===`cancel`){try{V.port?.postMessage({type:`cancel`})}catch{}pu(),Nu(),yu();return}if(t<Jl&&!V.lastText){try{V.port?.postMessage({type:`cancel`})}catch{}pu(),hu(r(`voice.tooShort`),`warn`),Nu(),setTimeout(()=>{V.phase===`idle`&&yu()},2200);return}hu(r(`voice.transcribing`));try{V.port?.postMessage({type:`stop`})}catch{}V.finishWaitTimer&&clearTimeout(V.finishWaitTimer),V.finishWaitTimer=setTimeout(()=>{V.phase===`finalizing`&&Ru(V.lastText,{fallback:!0})},6e4)}function Lu({rollback:e=!0}={}){if(V.phase===`idle`)return!1;let t=V.phase===`recording`||V.phase===`finalizing`;if(V.phase=`finalizing`,Mu(),t)try{V.port?.postMessage({type:`cancel`})}catch{}return e&&pu(),Nu(),xu(!1),Su(!1),yu(),!0}function Ru(e,t={}){let n=Xl(e).trim();if(!n){pu(),hu(r(`voice.noResult`),`warn`),Nu(),setTimeout(()=>{V.phase===`idle`&&yu()},2200);return}if(!V.draft){let e=V.input;if(e){let t=typeof e.selectionStart==`number`?e.selectionStart:e.value.length;uu(e.value.slice(0,t)+n+e.value.slice(t),t+n.length)}hu(r(`voice.done`)),Nu(),setTimeout(()=>{V.phase===`idle`&&yu()},1200);return}let i=Array.isArray(t.texts)?t.texts.filter(e=>typeof e==`string`&&e.trim()):[];i.length>1&&!V.draft.items.some(e=>e.id!==null||e.state===`locked`)&&(V.draft.items=i.map((e,t)=>({id:t+1,text:e,state:`refined`}))),V.draft.items.length===0&&(V.draft.items=[{id:null,text:n,state:`refined`}]);let{items:o,changed:s,takeAll:c}=Hl(V.draft.items,n);V.draft.items=o,du(!0),c&&a.debug(`[Voice] final text took over the whole draft`),V.draft=null,V.lastText=``,V.appliedText=``,V.openText=``,Nu(),hu(s>0?r(`voice.refineCorrected`,{n:s}):r(`voice.done`)),setTimeout(()=>{V.phase===`idle`&&yu()},s>0?1800:1200)}function zu(e){if(!(!e||typeof e.type!=`string`)){if(e.type===`ready`){e.draft===!1&&V.phase===`recording`&&a.debug(`[Voice] online model missing, draft disabled`);return}if(e.type===`partial`){if(V.phase!==`recording`&&V.phase!==`finalizing`)return;V.lastText=Xl(e.text),fu(typeof e.open==`string`?e.open:V.lastText);return}if(e.type===`endpoint`)return V.phase!==`recording`&&V.phase,void 0;if(e.type===`sentence`){if(V.phase!==`recording`&&V.phase!==`finalizing`||!V.draft||typeof e.id!=`number`)return;let t=typeof e.refined==`string`&&e.refined?e.refined:null,n=Array.isArray(V.draft.items)?V.draft.items:[],i=n.findIndex(e=>e.id===null),a=n;if(!t&&i>=0){let t=n[i];a=n.map((n,r)=>r===i?t.state===`locked`?{...n,id:e.id}:{id:e.id,text:Xl(e.draft)||n.text,state:`draft`}:n),V.openText=``}if(t&&(a.some(t=>t.id===e.id)?a=Bl(a,{id:e.id,text:t}).map(t=>t.id===e.id&&t.state!==`locked`?{...t,state:`refined`}:t):a.some(e=>e.id===null)||(a=a.concat([{id:e.id,text:t,state:`refined`}]))),a!==n&&(V.draft.items=a,du()),t&&V.phase===`recording`){let e=V.draft.items.filter(e=>e.id!==null&&e.state===`refined`).length;hu(r(`voice.refineListening`,{n:e}))}return}if(e.type===`refine`){e.enabled===!1&&(V.phase===`recording`||V.phase===`finalizing`)&&hu(r(`voice.refineDegraded`),`warn`);return}if(e.type===`final`){if(V.phase!==`recording`&&V.phase!==`finalizing`)return;Ru(e.text||V.lastText,{fallback:e.fallback===!0,texts:e.texts});return}if(e.type===`closed`){V.phase===`finalizing`&&Ru(V.lastText,{fallback:!0});return}if(e.type===`error`){let t=e.code||`internal`;if(t===`max_duration`){V.phase===`recording`&&Iu(`stop`),hu(r(`voice.maxDuration`),`warn`);return}hu(t===`busy`?r(`voice.busy`):t===`model_missing`?`${r(`voice.modelMissing`)} — ${r(`voice.modelMissingHelp`)}`:r(`voice.failed`),`warn`),Mu(),(V.phase===`recording`||V.phase===`finalizing`)&&pu(),Nu(),xu(!1),Su(!1),t===`model_missing`&&ou(),setTimeout(()=>{V.phase===`idle`&&yu()},3500)}}}async function Bu(){return V.phase===`recording`?(Iu(`stop`),!0):V.phase===`starting`||V.phase===`finalizing`?!1:Fu()}function Vu(){return V.phase===`recording`||V.phase===`starting`||V.phase===`finalizing`}function Hu(){return Vu()?Lu({rollback:!0}):!1}function Uu(){return V.phase===`idle`?!1:Lu({rollback:!1})}async function Wu(){try{let e=(await chrome.storage.session?.get?.(`pendingVoiceStart`))?.pendingVoiceStart;return!(!e||(await chrome.storage.session.remove(`pendingVoiceStart`),typeof e!=`number`||Date.now()-e>Wl))}catch{return!1}}function Gu(){if(!V.btn)return;let e=[`Alt+V`];V.shortcutCfg.rightAlt&&e.push(r(`voice.keyRightAlt`)),V.shortcutCfg.rightCtrl&&e.push(r(`voice.keyRightCtrl`));let t=r(`voice.btnTitle`,{keys:e.join(` / `)});V.btn.title=t,V.btn.setAttribute(`aria-label`,t)}async function Ku(){if(V.shortcutCfg=await ct(),V.shortcutTrigger||=st(()=>V.shortcutCfg),Gu(),V.shortcutBound)return;V.shortcutBound=!0,document.addEventListener(`keydown`,e=>{V.shortcutTrigger?.onKeyDown(e)===`cancel`&&e.preventDefault()},!0),document.addEventListener(`keyup`,e=>{V.shortcutTrigger?.onKeyUp(e)===`trigger`&&(!V.armed&&V.phase===`idle`||(e.preventDefault(),Bu()))},!0),window.addEventListener(`blur`,()=>{V.shortcutTrigger?.reset()}),ot(e=>{V.shortcutCfg=e,Gu()});let e=async()=>{try{let e=await ct();if(e.rightAlt===V.shortcutCfg.rightAlt&&e.rightCtrl===V.shortcutCfg.rightCtrl)return;V.shortcutCfg=e,Gu()}catch{}};window.addEventListener(`focus`,()=>{e()}),document.addEventListener(`visibilitychange`,()=>{document.hidden||e()})}async function qu(e={}){if(V.input=document.getElementById(`userInput`),V.btn=document.getElementById(`voiceInputBtn`),V.bar=document.getElementById(`voiceRecorderBar`),V.wave=document.getElementById(`voiceWave`),V.timerEl=document.getElementById(`voiceTimer`),V.statusEl=document.getElementById(`voiceStatusText`),V.permBtn=document.getElementById(`voicePermBtn`),V.adjustInputHeight=typeof e.adjustInputHeight==`function`?e.adjustInputHeight:null,!V.input||!V.btn){a.debug(`[Voice] input or button missing, skip init`);return}mu(),xu(!1),hu(r(`voice.listening`)),await Ku(),V.btn.addEventListener(`click`,e=>{e.preventDefault(),Bu()}),document.getElementById(`voiceCancelBtn`)?.addEventListener(`click`,e=>{e.preventDefault(),Lu({rollback:!0})}),document.getElementById(`voiceDoneBtn`)?.addEventListener(`click`,e=>{e.preventDefault(),Iu(`stop`)}),V.permBtn?.addEventListener(`click`,e=>{e.preventDefault();try{chrome.runtime.sendMessage({type:`OPEN_OPTIONS_PAGE`,hash:`asr`}).catch?.(()=>{})}catch{}hu(r(`voice.micDeniedHelp`),`warn`),_u(!1)}),V.input.addEventListener(`input`,()=>{V.programmatic||(V.phase===`recording`||V.phase===`finalizing`)&&su()}),chrome.runtime.onMessage.addListener((e,t,n)=>e?.type===`VOICE_TOGGLE`?(Bu(),n?.({success:!0}),!1):(e?.type===`ASR_STATUS_CHANGED`&&ou(),!1)),window.addEventListener(`pagehide`,()=>{Uu()}),document.addEventListener(`visibilitychange`,()=>{document.hidden&&V.phase===`recording`&&Uu()}),await ou()&&await Wu()&&setTimeout(()=>{Bu()},220)}var Ju=`panel_`+Date.now().toString(36)+`_`+Math.random().toString(36).slice(2,8),Yu=new Set,Xu=new Set,Zu=null,Qu=new Map,$u=`queue-context-cleared`,ed=`queue-context-restored`;function td(e){Zu=e}function nd(e){return N.generatingSessionIds.has(e||N.activeSessionId)}function rd(){return{quotedContextText:N.quotedContextText||``,selectedContextText:N.selectedContextText||``,selectedSkills:(N.selectedSkills||[]).slice(),selectedMcpServices:(N.selectedMcpServices||[]).slice(),knowledgeRefs:(N.knowledgeRefs||[]).slice(),selectedPage:N.selectedPage?{...N.selectedPage}:null,attachedImages:(N.attachedImages||[]).slice(),attachedFiles:(N.attachedFiles||[]).slice()}}function id(e){return e?e.attachmentSummary||(e.attachedImages||[]).length||(e.attachedFiles||[]).length?!0:!!(e.quotedContextText&&e.quotedContextText.trim()||e.selectedContextText&&e.selectedContextText.trim()||(e.selectedSkills||[]).length||(e.selectedMcpServices||[]).length||(e.knowledgeRefs||[]).length||e.selectedPage):!1}function ad(){return id(rd())}function od(){let e=rd();return id(e)&&cd(),e}function sd(e){e&&(e.quotedContextText&&(N.quotedContextText=e.quotedContextText),e.selectedContextText&&(N.selectedContextText=e.selectedContextText),(e.selectedSkills||[]).length&&(N.selectedSkills=e.selectedSkills.slice()),(e.selectedMcpServices||[]).length&&(N.selectedMcpServices=e.selectedMcpServices.slice()),(e.knowledgeRefs||[]).length&&(N.knowledgeRefs=e.knowledgeRefs.slice()),e.selectedPage&&(N.selectedPage={...e.selectedPage}),(e.attachedImages||[]).length&&(N.attachedImages=e.attachedImages.slice()),(e.attachedFiles||[]).length&&(N.attachedFiles=e.attachedFiles.slice()))}function cd(){let e=(N.attachedImages||[]).length>0;if(N.quotedContextText=``,N.selectedContextText=``,N.selectedSkills=[],N.selectedMcpServices=[],N.knowledgeRefs=[],N.selectedPage=null,N.attachedImages=[],N.attachedFiles=[],e){let e=document.getElementById(`imagePreviewBar`);e&&(e.innerHTML=``,e.style.display=`none`)}document.dispatchEvent(new CustomEvent($u))}var ld=new Set([`pending`,`extracting`]);function ud(){return(N.attachedFiles||[]).some(e=>ld.has(e&&e.status))}function dd(e){let t=e&&e.attachedImages||[],n=(e&&e.attachedFiles||[]).map(e=>{if(!e||typeof e.dataUrl!=`string`||!e.dataUrl.startsWith(`blob:`))return e;let t={...e};return delete t.dataUrl,t}),r={...e||{}};return delete r.attachedImages,delete r.attachedFiles,r.attachmentSummary=Ci({attachedImages:t,attachedFiles:n}),{light:r,heavy:t.length||n.length?{images:t,files:n}:null}}async function fd(e){if(!e)return{ok:!1,attachments:!1,wantsAttachments:!1};let t=await Ti(e.id)||Qu.get(e.id)||null,n=!!(e.attachmentSummary||e.contextSnapshot&&e.contextSnapshot.attachmentSummary);return sd({...e.contextSnapshot||{},attachedImages:t&&t.images||[],attachedFiles:t&&t.files||[]}),document.dispatchEvent(new CustomEvent(ed,{detail:{snapshot:e.contextSnapshot||{}}})),{ok:!0,attachments:!!t,wantsAttachments:n}}async function pd(e){return e?(Qu.delete(e),Ei(e)):!1}async function md({autoDrain:e=!0}={}){let t=document.getElementById(`userInput`),n=(t?.value||``).trim();if(!n)return{ok:!1,error:`empty`};Uu();let i=N.activeSessionId;if(!i)return L(r(`queue.noSession`),`error`),{ok:!1,error:`missing_session`};if(ud())return L(r(`queue.filesStillExtracting`),`warning`,4e3),{ok:!1,error:`files_extracting`};let a=od(),{light:o,heavy:s}=dd(a),c=await Qr({sessionId:i,text:n,contextSnapshot:o,hasContext:id(o),attachmentSummary:o.attachmentSummary,source:`manual`});return c.ok?(s&&((await wi(c.item.id,i,s)).ok||(Qu.set(c.item.id,s),L(r(`queue.attachmentsVolatile`),`warning`,5e3))),t&&(t.value=``,t.style.height=`auto`,t.dispatchEvent(new Event(`input`)),t.focus()),L(r(`queue.enqueued`,{position:c.position}),`success`),document.dispatchEvent(new CustomEvent(`queue-enqueued`,{detail:{sessionId:i,item:c.item}})),e&&!nd(i)&&!Zr(i)&&gd(i),c):(sd(a),document.dispatchEvent(new CustomEvent(ed,{detail:{snapshot:a}})),c.error===`queue_full`?L(r(`queue.queueFull`,{limit:c.limit}),`warning`):L(r(`queue.enqueueFailed`),`error`),c)}async function hd(e){try{let{list:t}=await Fi(),n=(t||[]).find(t=>t.id===e);return n?{messageHistory:Array.isArray(n.messageHistory)?n.messageHistory.slice():[],model:n.model,useTools:n.useTools,enabledTools:Array.isArray(n.enabledTools)?n.enabledTools.slice():n.enabledTools,agentId:n.agentId,temperature:n.temperature,topP:n.topP,contextCompaction:n.contextCompaction,workdir:n.workdir||null,workdirAgentId:n.workdirAgentId||null}:null}catch(e){return a.warn(`[QueueRunner] load session state failed:`,e?.message||e),null}}async function gd(e){let t=e||N.activeSessionId;if(!(!t||!Zu)){if(Yu.has(t)){Xu.add(t);return}Yu.add(t);try{do Xu.delete(t),await _d(t);while(Xu.has(t)&&!Zr(t))}finally{Yu.delete(t)}}}async function _d(e){if(nd(e)||Zr(e))return;let t=qr(e);if(!t)return;if((t.attempts||0)>=5){await ii(e,t.id,{status:R.FAILED,note:`too_many_attempts`}),L(r(`queue.tooManyAttempts`,{count:5}),`error`,5e3);return}if(!await ui(e,t.id,Ju)){a.debug(`[QueueRunner] lease held by another panel, skip:`,t.id);return}await ti(e,t.id,R.DISPATCHING,{attempts:(t.attempts||0)+1,lastError:null});let n=await Ti(t.id)||Qu.get(t.id)||null;Qu.delete(t.id);let i=!!t.attachmentSummary&&!n;i&&L(r(`queue.attachmentsMissing`),`warning`,5e3);let o={quotedContextText:``,selectedContextText:``,selectedSkills:[],selectedMcpServices:[],knowledgeRefs:[],selectedPage:null,...t.contextSnapshot||{},attachedImages:n&&n.images||[],attachedFiles:n&&n.files||[]},s=e===N.activeSessionId,c=null;if(!s&&(c=await hd(e),!c)){let t=await di(e);t&&a.warn(`[QueueRunner] dropped queue of deleted session:`,e,t);return}let l={ok:!0};try{let n={text:t.text,fromQueue:!0,sessionId:e,context:o};s||(n.sessionState=c),l=await Zu(n)||{ok:!0}}catch(e){l={ok:!1,reason:e?.message||`dispatch_error`},a.error(`[QueueRunner] dispatch failed:`,e?.message||e)}Yr(e,t.id)?l.ok===!1?l.delivered?(await ii(e,t.id,{status:R.FAILED,note:l.reason||`failed`}),await Ei(t.id)):(await ri(e,t.id,`dispatch_failed`,l.reason||`dispatch_failed`),Xu.delete(e)):(await ii(e,t.id,{status:R.DONE,note:i?`relayed_no_attachments`:`relayed`}),await Ei(t.id)):a.debug(`[QueueRunner] item removed during dispatch, drop result:`,t.id)}var vd=new Set;function yd(e){let t=e||N.activeSessionId;return t?(vd.add(t),t):null}function bd(e){let t=e||N.activeSessionId;return!!(t&&qr(t))}async function xd(e){let t=e||N.activeSessionId;t&&(vd.delete(t),await li(t),await gd(t))}function Sd(e){Zr(e)||gd(e)}var Cd=new Map,wd=new Set,Td=new Map,Ed=new Map;function Dd(e){let t=e&&e.attachmentSummary;return t?(t.imageCount||0)>0||(t.fileCount||0)>0:!1}function Od(e,t){return`${e}\u0000${t}`}function kd(e,t){let n=Od(e,t),r=Cd.get(n);r&&(clearTimeout(r),Cd.delete(n))}async function Ad(e,t,n,r){kd(e,t);let i=Yr(e,t);!i||i.status!==R.INJECTING||(await ri(e,t,n,n),r&&L(r,`warning`,4e3))}function jd(e,t,n){return new Promise(r=>{let i=!1,a=e=>{i||(i=!0,r(e))},o=setTimeout(()=>a(null),2e3);try{chrome.runtime.sendMessage({type:`INJECT_MESSAGE`,sessionId:e,itemId:t,text:n},e=>{if(clearTimeout(o),chrome.runtime.lastError){a(null);return}a(e||null)})}catch{clearTimeout(o),a(null)}})}async function Md(e,t,n={}){let i=t||N.activeSessionId,a=n.auto===!0;if(!i||!e)return{ok:!1,error:`missing_session`};let o=Yr(i,e);if(!o)return{ok:!1,error:`not_found`};if(o.status!==R.QUEUED)return{ok:!1,error:`not_queued`};if(Dd(o))return a||L(r(`queue.injectNoAttachments`),`warning`,4e3),{ok:!1,error:`has_attachments`};let s=Od(i,e);if(wd.has(s))return{ok:!1,error:`in_flight`};wd.add(s);try{await ni(i,e),Cd.set(s,setTimeout(()=>{Ad(i,e,`timeout`,r(`queue.injectTimeout`))},_r));let t=await jd(i,e,o.text);if(!t)return{ok:!0,pending:!0};if(!t.accepted){let n=t.reason||`rejected`;return await Ad(i,e,n,r(n===`no_running_task`?`queue.injectNoTask`:`queue.injectFailed`)),{ok:!1,error:n}}return a?i===N.activeSessionId&&L(r(`queue.autoCarried`,{iteration:n.iteration??`?`}),`success`,2500):L(r(`queue.injectAccepted`),`success`,2500),{ok:!0,pending:!0}}finally{wd.delete(s)}}function Nd(e){let t=document.getElementById(`userInput`);t&&t.value.trim()===e&&(t.value=``,t.style.height=`auto`,t.dispatchEvent(new Event(`input`)),t.focus())}async function Pd(e){let t=N.activeSessionId,n=String(e||``).trim();if(!t||!n)return{ok:!1,error:`empty`};if(Uu(),!nd(t))return L(r(`queue.injectNoTask`),`warning`,3e3),{ok:!1,error:`no_running_task`};let i=`adhoc_`+Date.now().toString(36)+`_`+Math.random().toString(36).slice(2,7),a=setTimeout(()=>{Td.has(i)&&(Td.delete(i),L(r(`queue.injectTimeoutAdhoc`),`warning`,4e3))},_r);Td.set(i,{text:n,timer:a});let o=await jd(t,i,n);return o&&!o.accepted?(clearTimeout(a),Td.delete(i),L(o.reason===`no_running_task`?r(`queue.injectNoTask`):r(`queue.injectFailed`),`warning`,4e3),{ok:!1,error:o.reason}):(o&&o.accepted&&L(r(`queue.injectAccepted`),`success`,2500),{ok:!0,pending:!0})}function Fd(e){let t=e?.sessionId,n=Array.isArray(e?.items)?e.items:[];if(!t||n.length===0)return;let i=0;for(let r of n){let n=Td.get(r);if(n){clearTimeout(n.timer),Td.delete(r),Nd(n.text);continue}kd(t,r),Yr(t,r)&&(i++,ii(t,r,{status:R.INJECTED,note:`injected`,callId:e.callId||null,iteration:e.iteration??null}))}i>0&&t===N.activeSessionId&&L(r(`queue.injected`),`success`,2500),document.dispatchEvent(new CustomEvent(`queue-injected`,{detail:{sessionId:t,items:n,iteration:e.iteration??null}}))}function Id(e){let t=e?.sessionId,n=Array.isArray(e?.items)?e.items:[];if(!t||n.length===0)return;let i=e.reason||`rejected`,a=r(i===`task_ended`?`queue.injectNoTask`:`queue.injectFailed`);for(let e of n){let r=Td.get(e);if(r){clearTimeout(r.timer),Td.delete(e);continue}Ad(t,e,i,e===n[0]?a:null)}}function Ld(e){let t=e?.sessionId;if(!t||e.isSubtask===!0||Zr(t))return;let n=Pl(e.executionLog);if(!n)return;let r=qr(t),i=r&&!Dd(r)?r:null,o=N.chatConfig||{},s=Fl({tracker:Ed.get(t),callId:e.callId||null,iteration:n,everyN:o.queueAutoCarryEveryNIterations,enabled:o.queueAutoCarry!==!1,hasCandidate:!!i});if(Ed.set(t,s.tracker),!s.carry)return;a.debug(`[QueueRunner] auto carry item`,i.id,`at iteration`,n,`session`,t);let c=e.callId||null;Md(i.id,t,{auto:!0,iteration:n}).then(e=>{!e||e.ok!==!0||Ed.set(t,Il(Ed.get(t),{callId:c}))})}function Rd(e){!e||typeof e!=`object`||(e.type===`INJECT_ABSORBED`?Fd(e):e.type===`INJECT_REJECTED`?Id(e):e.type===`EXECUTION_STATUS_UPDATE`&&Ld(e))}async function zd(){try{if(zr()){a.warn(`[QueueRunner] skip attachment prune in degraded mode`);return}let e=new Set;for(let t of Xr())for(let n of Ur(t))e.add(n.id);let t=await Oi(e);t&&a.debug(`[QueueRunner] pruned orphan attachments:`,t)}catch(e){a.warn(`[QueueRunner] prune orphan attachments failed:`,e?.message||e)}}var Bd=!1,Vd=null,Hd=[];function Ud(e,t){document.addEventListener(e,t),Hd.push([e,t])}var Wd=1500;function Gd(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,t(e))},i=setTimeout(()=>r(null),Wd);try{chrome.runtime.sendMessage({type:`QUERY_SESSION_RUNNING`,sessionId:e},e=>{if(clearTimeout(i),chrome.runtime.lastError){r(null);return}r(!!(e&&e.running))})}catch{clearTimeout(i),r(null)}})}async function Kd(){if(!N.activeSessionId)return!1;let e=Xr();if(e.length===0)return!0;let t=!1;for(let n of e){if(Zr(n)||nd(n)||!qr(n))continue;let e=await Gd(n);if(e===null){t=!0;continue}if(!e&&!(Zr(n)||nd(n)))return await gd(n),!0}return!t}function qd(){if(Vd)return;let e=0,t=async()=>{if(Vd=null,++e>25)return;let n=!1;try{n=await Kd()}catch(e){a.warn(`[QueueRunner] auto-resume attempt failed:`,e?.message||e)}n||(Vd=setTimeout(t,800))};Vd=setTimeout(t,300)}async function Jd({autoResume:e=!0}={}){Bd||(Bd=!0,await Br(),Vr(),zd(),Al(Sd),typeof chrome<`u`&&chrome.runtime?.onMessage?.addListener&&chrome.runtime.onMessage.addListener(Rd),Ud(`task-stop-requested`,e=>{let t=e?.detail?.sessionId||N.activeSessionId;if(t){if(vd.delete(t)){li(t).then(()=>gd(t));return}ci(t,`user_stopped`)}}),Ud(`generating-state-changed`,()=>{let e=N.activeSessionId;if(e){if(N.isGenerating&&Zr(e)){li(e);return}for(let e of Xr())if(!(Zr(e)||nd(e))&&qr(e)){gd(e);break}}}),Ud(`session-switched`,()=>qd()),Ud(`visibilitychange`,()=>{document.visibilityState===`visible`&&qd()}),e&&qd())}async function Yd(e){let t=e||N.activeSessionId;t&&(await li(t),await gd(t))}var Xd=[/(?:按|按照|以|用|走|使用|开启|启用|切换?到)\s*(?:goal|目标)\s*模式/i,/(?:进入|改成|改为|设为|设置为|切换到)\s*(?:goal|目标)\s*模式/i,/\b(?:in|use|using|enable|enter|switch\s+to|with)\s+(?:the\s+)?goal\s+mode\b/i,/(?:无人值守|不用管我|别停下来|不要停|直到(?:我|你)(?:叫停|喊停))/,/\bunattended\b|\bwithout\s+(?:me|supervision)\b|\bdon'?t\s+stop\s+until\b/i,/(?:持续|一直|连续)(?:执行|跑|做|干|尝试|迭代)\s*(?:到|直到)/,/(?:跑到|做到|干到|做到)(?:完成|通过|结束|成功)/,/\bkeep\s+(?:working|going|trying|iterating)\s+until\b/i,/\brun\s+until\s+(?:done|complete|passing|it\s+passes)\b/i],Zd=[/直到\s*[^。;;\n]{1,40}?(?:全部|都)?(?:通过|完成|跑通|变绿)/,/(?:确保|保证)\s*[^。;;\n]{1,40}?(?:通过|跑通|可用)/,/\buntil\s+[^.;\n]{1,40}?(?:pass|passes|green|works)\b/i],Qd=/(?:不要|不用|不必|无需|取消|关闭|停用|停止|退出|不按|不以|别|不)\s*$/,$d=/\b(?:do\s+not|don'?t|does\s+not|doesn'?t|never|avoid|without|no\s+need\s+to)\s+(?:(?:use|using|enable|enabling|enter|entering|switch(?:ing)?\s+to|turn\s+on|activate|run(?:\s+in)?|go(?:\s+with)?)\s*)?$/i,ef=2e3,tf=40;function nf(e,t,n){let r=[];for(let i of t){let t=i.flags.includes(`g`)?i.flags:`${i.flags}g`,a=new RegExp(i.source,t),o;for(;(o=a.exec(e))!==null&&o[0].length!==0;){let t=e.slice(Math.max(0,o.index-tf),o.index);if(!(n&&(Qd.test(t)||$d.test(t)))&&(r.push(o[0].trim()),o[0].length===0))break}}return r}function rf(e){let t={detected:!1,strength:`none`,matches:[]};if(typeof e!=`string`)return t;let n=e.trim();if(!n)return t;let r=n.slice(0,ef),i=nf(r,Xd,!0);if(i.length>0)return{detected:!0,strength:`strong`,matches:af(i).slice(0,3)};let a=nf(r,Zd,!0);return a.length>0?{detected:!1,strength:`weak`,matches:af(a).slice(0,3)}:t}function af(e){let t=new Set,n=[];for(let r of e){let e=r.toLowerCase();t.has(e)||(t.add(e),n.push(r))}return n}function of(e){if(typeof e!=`string`)return``;let t=e,n=nf(e.slice(0,ef),Xd,!0);for(let e of n)e&&(t=t.replace(e,` `));return t=t.replace(/^[\s,,。.、::;;-]+/,``).trim(),t||e.trim()}var sf={active:`goal.statusActive`,paused:`goal.statusPaused`,achieved:`goal.statusAchieved`,unmet:`goal.statusUnmet`,budget_limited:`goal.statusBudgetLimited`,cleared:`goal.statusCleared`},cf=new Set([`achieved`,`unmet`,`cleared`]),H=null;function lf(e){return document.getElementById(e)}function uf(e){let t=sf[e];return t?r(t):String(e||``)}function df(e){return!!e&&cf.has(e.status)}function ff(e){return new Promise(t=>{try{chrome.runtime.sendMessage(e,e=>{if(chrome.runtime.lastError){a.debug(`[GoalPanel] message failed:`,chrome.runtime.lastError.message),t(null);return}t(e||null)})}catch(e){a.debug(`[GoalPanel] message threw:`,e?.message),t(null)}})}function pf(e){return ff({type:`SET_GOAL`,...e})}function mf(){if(!H)return;let e=N.goalSnapshot,t=N.goalMode;H.toggle.checked=t;let n=t&&!!e&&(e.status===`paused`||e.status===`budget_limited`);H.group&&(H.group.dataset.goalIdle=n?`1`:``);let i=t||e&&!df(e);if(H.bar.style.display=i?``:`none`,!i)return;if(H.bar.dataset.status=e?e.status:`none`,H.status.textContent=e?uf(e.status):``,H.status.style.display=e?``:`none`,e){H.objective.textContent=e.objective||``,H.objective.title=e.objective||``;let t=se(e,r);n&&e.status===`paused`&&t.push(r(`goal.pausedHintInline`)),H.meta.textContent=t.join(` · `)}else H.objective.textContent=r(`goal.startHint`),H.objective.title=``,H.meta.textContent=``;let a=!!e&&e.status===`active`&&e.autoApprove===!0;H.approve.style.display=a?``:`none`;let o=!!e&&e.status===`active`,s=!!e&&(e.status===`paused`||e.status===`budget_limited`);H.pause.style.display=o?``:`none`,H.resume.style.display=s?``:`none`,H.edit.style.display=e?``:`none`,H.clear.style.display=e?``:`none`}function hf(){return N.activeSessionId||null}async function gf(e=hf()){if(!e)return N.goalSnapshot=null,mf(),null;let t=await ff({type:`GET_GOAL`,sessionId:e});return e===hf()?(N.goalSnapshot=t?.goal||null,mf(),N.goalSnapshot):null}var _f=null;async function vf(){return _f||(_f=await new Promise(e=>{try{chrome.storage.local.get([`goalConfig`],t=>e(t?.goalConfig||{}))}catch(t){a.debug(`[GoalPanel] read goalConfig failed:`,t?.message),e({})}}),_f)}async function yf(){let e=lf(`goalGroup`);if(!e)return;let t=await vf();e.style.display=t.enabled===!1?`none`:``}async function bf({sessionId:e=hf(),text:t=``,attachments:n=[]}={}){if(!e||!String(t||``).trim())return null;let i=await vf(),a=!!N.goalMode;if(i.enabled===!1)return a&&L(r(`goal.disabledHint`),`warning`),null;let o=t;if(!a){if(i.intentDetection===!1)return null;let e=rf(t);if(!e.detected)return e.strength===`weak`&&L(r(`goal.intentHint`),`info`,6e3),null;o=String(of(t)||``).trim()||t}let s=await pf({sessionId:e,action:`set`,objective:o,attachments:Array.isArray(n)?n:[],createdBy:a?`toggle`:`intent`,autoApprove:a});return!s||s.success===!1?(s?.disabled&&L(r(`goal.disabledHint`),`warning`),null):(a||L(r(`goal.intentDetected`),`info`,6e3),e===hf()?(N.goalSnapshot=s.goal||null,mf(),s.goal||null):s.goal||null)}function xf(e={}){let t=[],n=Array.isArray(e.attachedImages)?e.attachedImages.length:0;n>0&&t.push({kind:`image`,name:r(`goal.attachmentImage`,{count:n})});for(let n of Array.isArray(e.attachedFiles)?e.attachedFiles:[])!n||n.status!==`done`||!n.name||t.push({kind:`file`,name:String(n.name),detail:n.agentPath?`workspace file`:`inline text`});let i=e.selectedPage;i&&(i.title||i.url)&&t.push({kind:`page`,name:String(i.title||i.url),detail:i.id==null?``:`tab ${i.id}`});for(let n of Array.isArray(e.knowledgeRefs)?e.knowledgeRefs:[])n&&n.name&&t.push({kind:`knowledge`,name:String(n.name)});return t}function Sf(){N.goalSnapshot=null,mf()}function Cf(){return mf(),gf()}function wf(e=``){return new Promise(t=>{let n=document.createElement(`div`);n.className=`modal-overlay show`,n.innerHTML=`
|
|
95
95
|
<div class="modal-container" style="min-width:320px;">
|
|
96
96
|
<div class="modal-title">${P(r(`goal.editTitle`))}</div>
|
|
97
97
|
<input type="text" class="goal-edit-input" value="${P(e)}"
|
|
@@ -113,7 +113,7 @@ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,i,l as a,n a
|
|
|
113
113
|
<span class="node-icon">${m}</span>
|
|
114
114
|
<span class="iteration-badge">[${t+1}/${n}]</span>
|
|
115
115
|
<span class="node-name" title="${P(e.nodeName||r(`execLog.unknownNode`))}">${_}</span>
|
|
116
|
-
<span class="duration-badge" title="${r(`execLog.durationTitle`)}">${
|
|
116
|
+
<span class="duration-badge" title="${r(`execLog.durationTitle`)}">${Bt(e.duration||0)}</span>
|
|
117
117
|
</div>
|
|
118
118
|
|
|
119
119
|
<div class="timeline-details">
|
|
@@ -319,7 +319,7 @@ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,i,l as a,n a
|
|
|
319
319
|
<span class="node-icon">${f}</span>
|
|
320
320
|
<span class="iteration-badge">[${t+1}/${n}]</span>
|
|
321
321
|
<span class="node-name" title="${P(e.nodeName||r(`execLog.unknownNode`))}">${h}</span>
|
|
322
|
-
<span class="duration-badge" title="${r(`execLog.durationTitle`)}">${
|
|
322
|
+
<span class="duration-badge" title="${r(`execLog.durationTitle`)}">${Bt(e.duration)}</span>
|
|
323
323
|
</div>
|
|
324
324
|
|
|
325
325
|
<div class="timeline-details">
|
|
@@ -463,7 +463,7 @@ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,i,l as a,n a
|
|
|
463
463
|
<span class="node-icon">${m}</span>
|
|
464
464
|
<span class="iteration-badge">[${a+1}/${e.length}]</span>
|
|
465
465
|
<span class="node-name" title="${P(i.nodeName||r(`execLog.unknownNode`))}">${_}</span>
|
|
466
|
-
<span class="duration-badge" title="${r(`execLog.durationTitle`)}">${
|
|
466
|
+
<span class="duration-badge" title="${r(`execLog.durationTitle`)}">${Bt(i.duration)}</span>
|
|
467
467
|
</div>
|
|
468
468
|
|
|
469
469
|
<div class="timeline-details">
|
|
@@ -728,7 +728,7 @@ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,i,l as a,n a
|
|
|
728
728
|
<div class="bookmark-panel-empty">${r(`bookmark.empty`)}</div>
|
|
729
729
|
</div>
|
|
730
730
|
</div>
|
|
731
|
-
`,er(`bookmark`).appendChild(e);let t=document.getElementById(`bookmarkPanelToggle`),n=document.getElementById(`bookmarkPanel`),i=document.getElementById(`bookmarkSearchInput`),o=document.getElementById(`bookmarkPanelClose`);N.bookmarkSearchHistory=[],N.bookmarkSearchHistoryIndex=-1;try{chrome.storage.local.get([`bookmarkSearchHistory`],e=>{e.bookmarkSearchHistory&&(N.bookmarkSearchHistory=e.bookmarkSearchHistory)})}catch{}function s(e){if(!e||!e.trim())return;let t=e.trim(),n=N.bookmarkSearchHistory,r=n.indexOf(t);r!==-1&&n.splice(r,1),n.push(t),n.length>20&&n.shift(),N.bookmarkSearchHistoryIndex=-1;try{chrome.storage.local.set({bookmarkSearchHistory:n})}catch{}}t.addEventListener(`click`,()=>{n.classList.contains(`expanded`)?(n.classList.remove(`expanded`),
|
|
731
|
+
`,er(`bookmark`).appendChild(e);let t=document.getElementById(`bookmarkPanelToggle`),n=document.getElementById(`bookmarkPanel`),i=document.getElementById(`bookmarkSearchInput`),o=document.getElementById(`bookmarkPanelClose`);N.bookmarkSearchHistory=[],N.bookmarkSearchHistoryIndex=-1;try{chrome.storage.local.get([`bookmarkSearchHistory`],e=>{e.bookmarkSearchHistory&&(N.bookmarkSearchHistory=e.bookmarkSearchHistory)})}catch{}function s(e){if(!e||!e.trim())return;let t=e.trim(),n=N.bookmarkSearchHistory,r=n.indexOf(t);r!==-1&&n.splice(r,1),n.push(t),n.length>20&&n.shift(),N.bookmarkSearchHistoryIndex=-1;try{chrome.storage.local.set({bookmarkSearchHistory:n})}catch{}}t.addEventListener(`click`,()=>{n.classList.contains(`expanded`)?(n.classList.remove(`expanded`),Gt(n)):(Bm(i.value),n.classList.add(`expanded`),It(n))}),o.addEventListener(`click`,()=>{n.classList.remove(`expanded`),Gt(n)});let c=document.getElementById(`bookmarkSearchClear`);i.addEventListener(`input`,()=>{let e=i.value.trim();Bm(e),c.style.display=e?``:`none`}),c.addEventListener(`click`,()=>{i.value=``,c.style.display=`none`,N.bookmarkSearchHistoryIndex=-1,Bm()}),i.addEventListener(`keydown`,e=>{if(e.key===`Enter`){e.preventDefault();let t=i.value.trim();t&&(s(t),Bm(t))}else if(e.key===`Escape`)N.bookmarkSearchHistoryIndex>=0&&(N.bookmarkSearchHistoryIndex=-1,i.value=``,Bm(),c.style.display=`none`);else if(e.key===`ArrowUp`){e.preventDefault();let t=N.bookmarkSearchHistory;if(t.length===0)return;N.bookmarkSearchHistoryIndex===-1?N.bookmarkSearchHistoryIndex=t.length-1:N.bookmarkSearchHistoryIndex>0&&N.bookmarkSearchHistoryIndex--,i.value=t[N.bookmarkSearchHistoryIndex]||``,c.style.display=i.value?``:`none`,Bm(i.value)}else if(e.key===`ArrowDown`){e.preventDefault();let t=N.bookmarkSearchHistory;N.bookmarkSearchHistoryIndex>=0&&N.bookmarkSearchHistoryIndex<t.length-1?(N.bookmarkSearchHistoryIndex++,i.value=t[N.bookmarkSearchHistoryIndex]||``):(N.bookmarkSearchHistoryIndex=-1,i.value=``),c.style.display=i.value?``:`none`,Bm(i.value)}}),document.getElementById(`bookmarkPanelContent`).addEventListener(`click`,async e=>{let t=e.target.closest(`.bookmark-item`);if(!t)return;let n=t.dataset.bookmarkId,r=t.dataset.sessionId,i=t.dataset.messageId;if(e.target.closest(`.bookmark-item-remove`)){e.stopPropagation(),await Fm(n),Bm(),Gm();return}if(e.target.closest(`.bookmark-item-pin`)){e.stopPropagation();let t=N.bookmarks.find(e=>e.id===n);t&&(await Im(n,!t.pinned),Bm());return}await Um(r,i)}),a.debug(`[BookmarkPanel] bookmark panelinitializing`)}function Bm(e){let t=document.getElementById(`bookmarkPanelContent`),n=document.getElementById(`bookmarkPanelCount`);if(!t||!n)return;let i=N.activeSessionId,a=Lm(i),o=i?N.bookmarks.filter(e=>e.sessionId!==i).sort((e,t)=>e.pinned&&!t.pinned?-1:!e.pinned&&t.pinned?1:t.createdAt-e.createdAt):[],s=(e||``).trim(),c=s.toLowerCase(),l=c.includes(`&`)||c.includes(`|`);if(s){let e=e=>{let t=((e.content||``)+` `+(e.sessionTitle||``)).toLowerCase();if(l){let e=c.split(`|`).map(e=>e.trim()).filter(Boolean);for(let n of e){let e=n.split(`&`).map(e=>e.trim()).filter(Boolean);if(e.length!==0&&e.every(e=>t.includes(e)))return!0}return!1}return t.includes(c)};a=a.filter(e),o=o.filter(e)}let u=N.bookmarks.length,d=a.length+o.length;if(c?n.textContent=r(`bookmark.searchCount`,{filtered:d,total:u}):n.textContent=u>0?r(`bookmark.countResult`,{count:u}):``,u===0){t.innerHTML=`<div class="bookmark-panel-empty">${r(`bookmark.empty`)}</div>`,Wm();return}if(c&&d===0){t.innerHTML=`<div class="bookmark-panel-empty">${r(`bookmark.noMatch`)}</div>`,Wm();return}let f=``;a.length>0&&(f+=`<div class="bookmark-section">
|
|
732
732
|
<div class="bookmark-section-title">${r(`searchPanel.currentSession`)}</div>
|
|
733
733
|
${Vm(a,c)}
|
|
734
734
|
</div>`),o.length>0&&(f+=`<div class="bookmark-section">
|
|
@@ -755,7 +755,7 @@ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,i,l as a,n a
|
|
|
755
755
|
</button>
|
|
756
756
|
</div>
|
|
757
757
|
</div>
|
|
758
|
-
`}).join(``)}function Hm(e,t){if(!t)return e;let n=P(e),r=t.split(/[&|]/).map(e=>e.trim()).filter(Boolean);if(r.length===0)return n;let i=r.map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)),a=RegExp(`(${i.join(`|`)})`,`gi`);return n.replace(a,`<mark class="bookmark-highlight-match">$1</mark>`)}async function Um(e,t){if(!(!e||!t)){if(N.activeSessionId!==e)try{let n=N.activeSessionId;if(await Bi(e)===!1||N.activeSessionId!==e){await Pm(e,t),Bm(),L(r(`bookmark.sessionNotExistToast`),`warning`);return}document.dispatchEvent(new CustomEvent(`session-switched`,{detail:{sessionId:e,previousSessionId:n,skipScrollRestore:!0}}));try{let{renderSessionTabs:e}=await M(async()=>{let{renderSessionTabs:e}=await Promise.resolve().then(()=>Yo);return{renderSessionTabs:e}},void 0);e()}catch(e){a.warn(`[BookmarkPanel] refreshsessionTab failed:`,e)}}catch(e){a.error(`[BookmarkPanel] switchsession failed:`,e);return}setTimeout(()=>{let n=document.getElementById(`chatContainer`);if(!n)return;let i=n.querySelector(`.message[data-message-id="${t}"]`);i?(i.scrollIntoView({behavior:`instant`,block:`nearest`}),i.classList.add(`bookmark-highlight`),setTimeout(()=>{i.classList.remove(`bookmark-highlight`)},2e3)):Pm(e,t).then(()=>{Bm(),L(r(`bookmark.messageNotExistToast`),`warning`)})},500)}}function Wm(){let e=document.getElementById(`bookmarkPanelContainer`),t=N.bookmarks.length;e&&(e.style.display=t>0?``:`none`)}function Gm(){let e=document.getElementById(`chatContainer`);e&&e.querySelectorAll(`.message.assistant`).forEach(e=>{let t=e.querySelector(`.bookmark-btn`);if(!t)return;let n=e.dataset.messageId,r=N.activeSessionId;Km(t,r,n)})}function Km(e,t,n){Mm(t,n)?(e.classList.add(`bookmarked`),e.title=r(`bookmark.removeBookmarkTitle`),e.querySelector(`svg`).setAttribute(`fill`,`currentColor`)):(e.classList.remove(`bookmarked`),e.title=r(`bookmark.addBookmarkTitle`),e.querySelector(`svg`).setAttribute(`fill`,`none`))}function qm(e){let t=e||N.activeSessionId;return t?!!(N.generatingSessionIds?.has(t)||Kr(t)>0):!1}n(`zh`,{imageHelper:{uploadToAgentTitle:`上传文件到Agent工作目录,大模型通过工具直接操作`,uploadAndExtractTitle:`上传文件并提取文本内容(支持PDF/Word/Excel/文本等)`,clickToEnlarge:`点击查看大图`,removeImage:`移除图片`,enableImageInputFirst:`请先开启图片输入功能`,screenshotSuccess:`截图成功`,screenshotFailed:`截图失败,请重试`,noActiveTab:`无法获取当前标签页`,cropFailed:`裁剪失败,请重试`,regionScreenshotFailed:`区域截图失败,请确保页面已加载且未被浏览器限制`,imageLoadFailed:`图片加载失败`,screenshotProcessFailed:`截图处理失败,请重试`}}),n(`en`,{imageHelper:{uploadToAgentTitle:`Upload files to Agent workspace; the model operates on them directly via tools`,uploadAndExtractTitle:`Upload files and extract text content (supports PDF/Word/Excel/text, etc.)`,clickToEnlarge:`Click to enlarge`,removeImage:`Remove image`,enableImageInputFirst:`Please enable image input first`,screenshotSuccess:`Screenshot captured`,screenshotFailed:`Screenshot failed, please retry`,noActiveTab:`Unable to get the current tab`,cropFailed:`Cropping failed, please retry`,regionScreenshotFailed:`Region screenshot failed. Make sure the page is loaded and not restricted by the browser.`,imageLoadFailed:`Image load failed`,screenshotProcessFailed:`Screenshot processing failed, please retry`}});function Jm(){let e=document.getElementById(`imagePreviewBar`),t=document.getElementById(`screenshotBtn`);e&&(e.style.display=N.attachedImages.length>0?``:`none`),t&&(N.enableImageInput?t.style.removeProperty(`display`):t.style.display=`none`),Ym(),N.enableImageInput||(N.attachedImages=[]),Zm()}function Ym(){let e=document.getElementById(`userInput`);e&&e.style.removeProperty(`padding-right`)}function Xm(){let e=document.getElementById(`fileAttachBtn`),t=document.getElementById(`fileInput`);e&&(e.style.display=N.enableFileInput?``:`none`),t&&(N.agentPlatform?.connected?(t.accept=`*`,e&&(e.title=r(`imageHelper.uploadToAgentTitle`))):(t.accept=`.pdf,.docx,.xlsx,.xls,.txt,.md,.json,.js,.jsx,.ts,.tsx,.html,.css,.scss,.less,.xml,.yaml,.yml,.py,.java,.c,.cpp,.h,.go,.rs,.rb,.php,.sql,.sh,.bash,.zsh,.cfg,.ini,.toml,.conf,.log,.csv,.tsv,.env,.vue,.svelte,.astro,.rtf`,e&&(e.title=r(`imageHelper.uploadAndExtractTitle`)))),Ym(),N.enableFileInput||Om()}function Zm(){let e=document.getElementById(`imagePreviewBar`);if(e){if(e.innerHTML=``,N.attachedImages.length===0){e.style.display=`none`;return}e.style.display=``,N.attachedImages.forEach((t,n)=>{let i=document.createElement(`div`);i.className=`image-preview-item`;let a=document.createElement(`img`);a.src=t.dataUrl||t.compressedUrl||t.originalUrl,a.className=`image-preview-thumb`,a.title=r(`imageHelper.clickToEnlarge`),a.style.cursor=`zoom-in`,a.addEventListener(`click`,()=>{jp(t.originalUrl||t.dataUrl||t.compressedUrl,a)});let o=document.createElement(`button`);o.className=`image-preview-remove`,o.innerHTML=`×`,o.title=r(`imageHelper.removeImage`),o.addEventListener(`click`,e=>{e.stopPropagation(),N.attachedImages.splice(n,1),Zm()}),i.appendChild(a),i.appendChild(o),e.appendChild(i)})}}async function Qm(){if(!N.enableImageInput){L(r(`imageHelper.enableImageInputFirst`));return}try{let e=await chrome.runtime.sendMessage({type:`CAPTURE_TAB`});e?.dataUrl&&(zp(await(await fetch(e.dataUrl)).blob()),L(r(`imageHelper.screenshotSuccess`)))}catch(e){a.error(`[SidePanel] full page screenshot failed:`,e),L(r(`imageHelper.screenshotFailed`))}}async function $m(){let e=await Ot();if(!e){L(r(`imageHelper.noActiveTab`));return}try{let t=await chrome.tabs.sendMessage(e,{type:`START_REGION_SELECTION`});if(!t)return;a.debug(`[SidePanel] regionselectresult:`,t);let n=await chrome.runtime.sendMessage({type:`CAPTURE_TAB`});if(!n?.dataUrl){L(r(`imageHelper.screenshotFailed`));return}let i=await eh(n.dataUrl,t);if(!i){L(r(`imageHelper.cropFailed`));return}zp(await(await fetch(i)).blob())}catch(e){a.error(`[SidePanel] region screenshot failed:`,e),L(r(`imageHelper.regionScreenshotFailed`))}}function eh(e,t){return new Promise((n,i)=>{let a=new Image;a.onload=()=>{let e=document.createElement(`canvas`),r=window.devicePixelRatio||1,i=t.x*r,o=t.y*r,s=t.width*r,c=t.height*r;e.width=s,e.height=c,e.getContext(`2d`,{willReadFrequently:!0}).drawImage(a,i,o,s,c,0,0,s,c),n(e.toDataURL(`image/jpeg`,.85))},a.onerror=()=>i(Error(r(`imageHelper.imageLoadFailed`))),a.src=e})}async function th(e,t,n){if(!N.enableImageInput){L(r(`imageHelper.enableImageInputFirst`));return}try{let i=e;t===`region`&&n&&(i=await eh(e,n)),zp(await(await fetch(i)).blob()),L(r(`imageHelper.screenshotSuccess`))}catch(e){a.error(`[SidePanel] pageshortcutscreenshotprocessing failed:`,e),L(r(`imageHelper.screenshotProcessFailed`))}}var nh=t({attachFilesForQuestion:()=>uy,closePreview:()=>K_,closeWorkspacePanel:()=>Pv,closeWorkspacePreview:()=>Nv,initWorkspacePanel:()=>Th,locateFileInWorkspace:()=>jv,openWorkspacePanel:()=>Kh,previewArtifactFile:()=>Mv,refreshWorkspacePanel:()=>wv,resetAndRefreshWorkspace:()=>Tv,resolveWorkspaceAbsolutePath:()=>Fv,showSwitchWorkdirDialog:()=>Qv,updateWorkspacePanelVisibility:()=>Ev});n(`zh`,{workspace:{workDir:`工作目录`,closePanel:`关闭面板`,embedMode:`嵌入模式`,floatMode:`浮窗模式`,openPanel:`打开工作目录面板`,narrowViewportHint:`视口过窄,已切回浮窗模式`,switchWorkdir:`切换工作目录`,backToParent:`返回上级目录`,uploadToCurrent:`上传文件到当前目录`,newFolder:`新建文件夹`,askSelectedFiles:`基于选中的文件进行问答`,downloadSelected:`下载选中的文件/目录(多选打包为ZIP)`,deleteSelected:`删除选中的文件`,clearSearch:`清除`,search:`搜索`,searchPlaceholder:`搜索...`,selectAllToggle:`全选/取消全选`,colName:`文件名`,colSize:`大小`,colTime:`修改时间`,noMatch:`未找到匹配的文件`,dirEmpty:`此目录为空`,noWorkspace:`无法获取工作目录,请确认 Agent 已连接`,loadDirFailed:`加载目录失败`,refreshFailed:`无法刷新,请确认 Agent 已连接`,agentNotConnected:`Agent 未连接`,agentNotConnectedUpload:`Agent 未连接,无法上传`,unsupportedFileType:`不支持的文件类型`,unknownError:`未知错误`,copiedFileName:`已复制文件名: {name}`,copiedPath:`已复制路径: {path}`,copyFailed:`复制失败`,copiedToClipboard:`已复制到剪贴板`,copyFailedManual:`复制失败,请手动选择复制`,getContentFailed:`获取内容失败`,codeCopiedToClipboard:`代码已复制到剪贴板`,copyUnsupportedType:`此文件类型不支持复制文本内容`,copiedToClipboardShort:`已复制到剪贴板`,clickToCopy:`点击复制`,preview:`预览`,previewBtn:`预览`,details:`详情`,download:`下载`,downloadFile:`下载文件`,rename:`重命名`,askFile:`基于文件问答`,delete:`删除`,copyAll:`复制`,copyAllTitle:`复制全部内容`,toggleRenderPreview:`切换渲染预览`,openInBrowser:`在浏览器中打开`,openInBrowserBtn:`在浏览器中打开`,fullscreenPreview:`全屏预览`,exitFullscreen:`退出全屏`,enterEditMode:`进入编辑模式`,edit:`编辑`,save:`保存`,saveChanges:`保存修改 (Ctrl+S)`,cancelChanges:`取消修改 (Esc)`,closePreview:`关闭预览`,close:`关闭`,confirm:`确定`,cancel:`取消`,switchToSourcePreview:`切换为源码预览`,switchToRenderPreview:`切换为渲染预览`,markdownRendered:`Markdown 渲染`,lineCount:`{count} 行`,linesModified:`{count} 行 · 已修改`,truncatedHint:`(仅显示前 {shown} 行,共 {total} 行,请下载查看完整内容)`,fileTooLargeNoPreview:`文件过大 ({size}),不支持预览,请直接下载`,fileTooLargeOpenInBrowser:`文件过大 ({size}),无法内置预览,请点击上方「在浏览器中打开」按钮查看`,previewFailed:`预览失败: {error}`,openFailed:`打开失败: {error}`,documentEmpty:`(文档为空)`,pptxEmptyOrFailed:`PPTX 文件为空或解析失败`,pageCount:`{count} 页`,prevPage:`上一页`,nextPage:`下一页`,zoomOut:`缩小`,zoomIn:`放大`,fitPage:`适应页面`,originalSize:`原始大小`,imageLoadFailed:`图片加载失败`,parsingExcel:`正在解析 Excel 文件...`,loadingData:`正在加载数据...`,requestFailed:`请求失败: {error}`,parseFailed:`解析失败: {error}`,noSheetsInWorkbook:`工作簿中没有工作表`,sheetNotFound:`未找到工作表数据`,emptySheet:`(空工作表)`,xlsxTruncatedHint:`仅显示前 {shown} 行,共 {total} 行,请下载查看完整内容`,unsupportedMediaHint:`⚠ 浏览器不支持播放此格式({ext}),请下载后使用本地播放器查看。`,uploading:`上传中...`,downloadInProgress:`下载中`,uploadInProgress:`上传中`,cancelUpload:`取消上传`,downloadCanceled:`下载已取消`,downloadFailed:`下载失败`,downloadFailedWithError:`下载失败: {error}`,savingToLocal:`正在由浏览器保存至本地...`,savedToLocal:`已保存至本地`,downloaded:`已下载: {name}`,downloadedCount:`已下载 {count} 个文件`,downloadedZip:`已下载 {count} 个文件(ZIP 压缩包)`,fileCount:`{count} 个文件`,uploadCanceled:`已取消上传`,uploadSuccessCount:`成功 {count}`,uploadSkippedCount:`跳过 {count}`,uploadFailedCount:`失败 {count}`,uploadComplete:`上传完成`,uploadCompleteWithStats:`上传完成 · {stats}`,uploadedFiles:`成功上传 {count} 个文件`,filesSkipped:`{count} 个文件已存在,跳过上传`,filesUploadFailed:`{count} 个文件上传失败`,uploadFailed:`上传失败`,uploadFailedWithStatus:`上传失败 ({status})`,parseResponseFailed:`解析响应失败`,networkError:`网络错误`,cannotMoveToSubdir:`不能将目录移动到其子目录中`,moving:`移动中...`,movedToDir:`"{name}" 已移动到目标目录`,movedToTarget:`"{name}" 已移动到 "{target}"`,moveFailed:`移动失败: {error}`,searching:`搜索中...`,confirmDeleteDir:`确定要删除目录 "{name}" 及其所有内容吗?
|
|
758
|
+
`}).join(``)}function Hm(e,t){if(!t)return e;let n=P(e),r=t.split(/[&|]/).map(e=>e.trim()).filter(Boolean);if(r.length===0)return n;let i=r.map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)),a=RegExp(`(${i.join(`|`)})`,`gi`);return n.replace(a,`<mark class="bookmark-highlight-match">$1</mark>`)}async function Um(e,t){if(!(!e||!t)){if(N.activeSessionId!==e)try{let n=N.activeSessionId;if(await Bi(e)===!1||N.activeSessionId!==e){await Pm(e,t),Bm(),L(r(`bookmark.sessionNotExistToast`),`warning`);return}document.dispatchEvent(new CustomEvent(`session-switched`,{detail:{sessionId:e,previousSessionId:n,skipScrollRestore:!0}}));try{let{renderSessionTabs:e}=await M(async()=>{let{renderSessionTabs:e}=await Promise.resolve().then(()=>Yo);return{renderSessionTabs:e}},void 0);e()}catch(e){a.warn(`[BookmarkPanel] refreshsessionTab failed:`,e)}}catch(e){a.error(`[BookmarkPanel] switchsession failed:`,e);return}setTimeout(()=>{let n=document.getElementById(`chatContainer`);if(!n)return;let i=n.querySelector(`.message[data-message-id="${t}"]`);i?(i.scrollIntoView({behavior:`instant`,block:`nearest`}),i.classList.add(`bookmark-highlight`),setTimeout(()=>{i.classList.remove(`bookmark-highlight`)},2e3)):Pm(e,t).then(()=>{Bm(),L(r(`bookmark.messageNotExistToast`),`warning`)})},500)}}function Wm(){let e=document.getElementById(`bookmarkPanelContainer`),t=N.bookmarks.length;e&&(e.style.display=t>0?``:`none`)}function Gm(){let e=document.getElementById(`chatContainer`);e&&e.querySelectorAll(`.message.assistant`).forEach(e=>{let t=e.querySelector(`.bookmark-btn`);if(!t)return;let n=e.dataset.messageId,r=N.activeSessionId;Km(t,r,n)})}function Km(e,t,n){Mm(t,n)?(e.classList.add(`bookmarked`),e.title=r(`bookmark.removeBookmarkTitle`),e.querySelector(`svg`).setAttribute(`fill`,`currentColor`)):(e.classList.remove(`bookmarked`),e.title=r(`bookmark.addBookmarkTitle`),e.querySelector(`svg`).setAttribute(`fill`,`none`))}function qm(e){let t=e||N.activeSessionId;return t?!!(N.generatingSessionIds?.has(t)||Kr(t)>0):!1}n(`zh`,{imageHelper:{uploadToAgentTitle:`上传文件到Agent工作目录,大模型通过工具直接操作`,uploadAndExtractTitle:`上传文件并提取文本内容(支持PDF/Word/Excel/文本等)`,clickToEnlarge:`点击查看大图`,removeImage:`移除图片`,enableImageInputFirst:`请先开启图片输入功能`,screenshotSuccess:`截图成功`,screenshotFailed:`截图失败,请重试`,noActiveTab:`无法获取当前标签页`,cropFailed:`裁剪失败,请重试`,regionScreenshotFailed:`区域截图失败,请确保页面已加载且未被浏览器限制`,imageLoadFailed:`图片加载失败`,screenshotProcessFailed:`截图处理失败,请重试`}}),n(`en`,{imageHelper:{uploadToAgentTitle:`Upload files to Agent workspace; the model operates on them directly via tools`,uploadAndExtractTitle:`Upload files and extract text content (supports PDF/Word/Excel/text, etc.)`,clickToEnlarge:`Click to enlarge`,removeImage:`Remove image`,enableImageInputFirst:`Please enable image input first`,screenshotSuccess:`Screenshot captured`,screenshotFailed:`Screenshot failed, please retry`,noActiveTab:`Unable to get the current tab`,cropFailed:`Cropping failed, please retry`,regionScreenshotFailed:`Region screenshot failed. Make sure the page is loaded and not restricted by the browser.`,imageLoadFailed:`Image load failed`,screenshotProcessFailed:`Screenshot processing failed, please retry`}});function Jm(){let e=document.getElementById(`imagePreviewBar`),t=document.getElementById(`screenshotBtn`);e&&(e.style.display=N.attachedImages.length>0?``:`none`),t&&(N.enableImageInput?t.style.removeProperty(`display`):t.style.display=`none`),Ym(),N.enableImageInput||(N.attachedImages=[]),Zm()}function Ym(){let e=document.getElementById(`userInput`);e&&e.style.removeProperty(`padding-right`)}function Xm(){let e=document.getElementById(`fileAttachBtn`),t=document.getElementById(`fileInput`);e&&(e.style.display=N.enableFileInput?``:`none`),t&&(N.agentPlatform?.connected?(t.accept=`*`,e&&(e.title=r(`imageHelper.uploadToAgentTitle`))):(t.accept=`.pdf,.docx,.xlsx,.xls,.txt,.md,.json,.js,.jsx,.ts,.tsx,.html,.css,.scss,.less,.xml,.yaml,.yml,.py,.java,.c,.cpp,.h,.go,.rs,.rb,.php,.sql,.sh,.bash,.zsh,.cfg,.ini,.toml,.conf,.log,.csv,.tsv,.env,.vue,.svelte,.astro,.rtf`,e&&(e.title=r(`imageHelper.uploadAndExtractTitle`)))),Ym(),N.enableFileInput||Om()}function Zm(){let e=document.getElementById(`imagePreviewBar`);if(e){if(e.innerHTML=``,N.attachedImages.length===0){e.style.display=`none`;return}e.style.display=``,N.attachedImages.forEach((t,n)=>{let i=document.createElement(`div`);i.className=`image-preview-item`;let a=document.createElement(`img`);a.src=t.dataUrl||t.compressedUrl||t.originalUrl,a.className=`image-preview-thumb`,a.title=r(`imageHelper.clickToEnlarge`),a.style.cursor=`zoom-in`,a.addEventListener(`click`,()=>{jp(t.originalUrl||t.dataUrl||t.compressedUrl,a)});let o=document.createElement(`button`);o.className=`image-preview-remove`,o.innerHTML=`×`,o.title=r(`imageHelper.removeImage`),o.addEventListener(`click`,e=>{e.stopPropagation(),N.attachedImages.splice(n,1),Zm()}),i.appendChild(a),i.appendChild(o),e.appendChild(i)})}}async function Qm(){if(!N.enableImageInput){L(r(`imageHelper.enableImageInputFirst`));return}try{let e=await chrome.runtime.sendMessage({type:`CAPTURE_TAB`});e?.dataUrl&&(zp(await(await fetch(e.dataUrl)).blob()),L(r(`imageHelper.screenshotSuccess`)))}catch(e){a.error(`[SidePanel] full page screenshot failed:`,e),L(r(`imageHelper.screenshotFailed`))}}async function $m(){let e=await kt();if(!e){L(r(`imageHelper.noActiveTab`));return}try{let t=await chrome.tabs.sendMessage(e,{type:`START_REGION_SELECTION`});if(!t)return;a.debug(`[SidePanel] regionselectresult:`,t);let n=await chrome.runtime.sendMessage({type:`CAPTURE_TAB`});if(!n?.dataUrl){L(r(`imageHelper.screenshotFailed`));return}let i=await eh(n.dataUrl,t);if(!i){L(r(`imageHelper.cropFailed`));return}zp(await(await fetch(i)).blob())}catch(e){a.error(`[SidePanel] region screenshot failed:`,e),L(r(`imageHelper.regionScreenshotFailed`))}}function eh(e,t){return new Promise((n,i)=>{let a=new Image;a.onload=()=>{let e=document.createElement(`canvas`),r=window.devicePixelRatio||1,i=t.x*r,o=t.y*r,s=t.width*r,c=t.height*r;e.width=s,e.height=c,e.getContext(`2d`,{willReadFrequently:!0}).drawImage(a,i,o,s,c,0,0,s,c),n(e.toDataURL(`image/jpeg`,.85))},a.onerror=()=>i(Error(r(`imageHelper.imageLoadFailed`))),a.src=e})}async function th(e,t,n){if(!N.enableImageInput){L(r(`imageHelper.enableImageInputFirst`));return}try{let i=e;t===`region`&&n&&(i=await eh(e,n)),zp(await(await fetch(i)).blob()),L(r(`imageHelper.screenshotSuccess`))}catch(e){a.error(`[SidePanel] pageshortcutscreenshotprocessing failed:`,e),L(r(`imageHelper.screenshotProcessFailed`))}}var nh=t({attachFilesForQuestion:()=>uy,closePreview:()=>K_,closeWorkspacePanel:()=>Pv,closeWorkspacePreview:()=>Nv,initWorkspacePanel:()=>Th,locateFileInWorkspace:()=>jv,openWorkspacePanel:()=>Kh,previewArtifactFile:()=>Mv,refreshWorkspacePanel:()=>wv,resetAndRefreshWorkspace:()=>Tv,resolveWorkspaceAbsolutePath:()=>Fv,showSwitchWorkdirDialog:()=>Qv,updateWorkspacePanelVisibility:()=>Ev});n(`zh`,{workspace:{workDir:`工作目录`,closePanel:`关闭面板`,embedMode:`嵌入模式`,floatMode:`浮窗模式`,openPanel:`打开工作目录面板`,narrowViewportHint:`视口过窄,已切回浮窗模式`,switchWorkdir:`切换工作目录`,backToParent:`返回上级目录`,uploadToCurrent:`上传文件到当前目录`,newFolder:`新建文件夹`,askSelectedFiles:`基于选中的文件进行问答`,downloadSelected:`下载选中的文件/目录(多选打包为ZIP)`,deleteSelected:`删除选中的文件`,clearSearch:`清除`,search:`搜索`,searchPlaceholder:`搜索...`,selectAllToggle:`全选/取消全选`,colName:`文件名`,colSize:`大小`,colTime:`修改时间`,noMatch:`未找到匹配的文件`,dirEmpty:`此目录为空`,noWorkspace:`无法获取工作目录,请确认 Agent 已连接`,loadDirFailed:`加载目录失败`,refreshFailed:`无法刷新,请确认 Agent 已连接`,agentNotConnected:`Agent 未连接`,agentNotConnectedUpload:`Agent 未连接,无法上传`,unsupportedFileType:`不支持的文件类型`,unknownError:`未知错误`,copiedFileName:`已复制文件名: {name}`,copiedPath:`已复制路径: {path}`,copyFailed:`复制失败`,copiedToClipboard:`已复制到剪贴板`,copyFailedManual:`复制失败,请手动选择复制`,getContentFailed:`获取内容失败`,codeCopiedToClipboard:`代码已复制到剪贴板`,copyUnsupportedType:`此文件类型不支持复制文本内容`,copiedToClipboardShort:`已复制到剪贴板`,clickToCopy:`点击复制`,preview:`预览`,previewBtn:`预览`,details:`详情`,download:`下载`,downloadFile:`下载文件`,rename:`重命名`,askFile:`基于文件问答`,delete:`删除`,copyAll:`复制`,copyAllTitle:`复制全部内容`,toggleRenderPreview:`切换渲染预览`,openInBrowser:`在浏览器中打开`,openInBrowserBtn:`在浏览器中打开`,fullscreenPreview:`全屏预览`,exitFullscreen:`退出全屏`,enterEditMode:`进入编辑模式`,edit:`编辑`,save:`保存`,saveChanges:`保存修改 (Ctrl+S)`,cancelChanges:`取消修改 (Esc)`,closePreview:`关闭预览`,close:`关闭`,confirm:`确定`,cancel:`取消`,switchToSourcePreview:`切换为源码预览`,switchToRenderPreview:`切换为渲染预览`,markdownRendered:`Markdown 渲染`,lineCount:`{count} 行`,linesModified:`{count} 行 · 已修改`,truncatedHint:`(仅显示前 {shown} 行,共 {total} 行,请下载查看完整内容)`,fileTooLargeNoPreview:`文件过大 ({size}),不支持预览,请直接下载`,fileTooLargeOpenInBrowser:`文件过大 ({size}),无法内置预览,请点击上方「在浏览器中打开」按钮查看`,previewFailed:`预览失败: {error}`,openFailed:`打开失败: {error}`,documentEmpty:`(文档为空)`,pptxEmptyOrFailed:`PPTX 文件为空或解析失败`,pageCount:`{count} 页`,prevPage:`上一页`,nextPage:`下一页`,zoomOut:`缩小`,zoomIn:`放大`,fitPage:`适应页面`,originalSize:`原始大小`,imageLoadFailed:`图片加载失败`,parsingExcel:`正在解析 Excel 文件...`,loadingData:`正在加载数据...`,requestFailed:`请求失败: {error}`,parseFailed:`解析失败: {error}`,noSheetsInWorkbook:`工作簿中没有工作表`,sheetNotFound:`未找到工作表数据`,emptySheet:`(空工作表)`,xlsxTruncatedHint:`仅显示前 {shown} 行,共 {total} 行,请下载查看完整内容`,unsupportedMediaHint:`⚠ 浏览器不支持播放此格式({ext}),请下载后使用本地播放器查看。`,uploading:`上传中...`,downloadInProgress:`下载中`,uploadInProgress:`上传中`,cancelUpload:`取消上传`,downloadCanceled:`下载已取消`,downloadFailed:`下载失败`,downloadFailedWithError:`下载失败: {error}`,savingToLocal:`正在由浏览器保存至本地...`,savedToLocal:`已保存至本地`,downloaded:`已下载: {name}`,downloadedCount:`已下载 {count} 个文件`,downloadedZip:`已下载 {count} 个文件(ZIP 压缩包)`,fileCount:`{count} 个文件`,uploadCanceled:`已取消上传`,uploadSuccessCount:`成功 {count}`,uploadSkippedCount:`跳过 {count}`,uploadFailedCount:`失败 {count}`,uploadComplete:`上传完成`,uploadCompleteWithStats:`上传完成 · {stats}`,uploadedFiles:`成功上传 {count} 个文件`,filesSkipped:`{count} 个文件已存在,跳过上传`,filesUploadFailed:`{count} 个文件上传失败`,uploadFailed:`上传失败`,uploadFailedWithStatus:`上传失败 ({status})`,parseResponseFailed:`解析响应失败`,networkError:`网络错误`,cannotMoveToSubdir:`不能将目录移动到其子目录中`,moving:`移动中...`,movedToDir:`"{name}" 已移动到目标目录`,movedToTarget:`"{name}" 已移动到 "{target}"`,moveFailed:`移动失败: {error}`,searching:`搜索中...`,confirmDeleteDir:`确定要删除目录 "{name}" 及其所有内容吗?
|
|
759
759
|
|
|
760
760
|
路径: {path}
|
|
761
761
|
类型: 目录
|
|
@@ -1000,7 +1000,7 @@ It is this session's directory or the agent default, so it stays accessible (wor
|
|
|
1000
1000
|
<div class="workspace-preview-rail" id="workspacePreviewRail"></div>
|
|
1001
1001
|
</div>
|
|
1002
1002
|
</div>
|
|
1003
|
-
`,er(`workspace`).appendChild(e),Eh(),document.addEventListener(`session-switched`,()=>{ty().catch(e=>a.warn(`[WorkspacePanel] sync after session switch failed`,e))}),document.addEventListener(`session-workdir-changed`,e=>{let t=e.detail?.sessionId;t&&t!==N.activeSessionId||ty().catch(e=>a.warn(`[WorkspacePanel] sync after workdir change failed`,e))}),document.addEventListener(`session-hydrated`,()=>{ty().catch(e=>a.warn(`[WorkspacePanel] sync after session hydrated failed`,e))}),Hv(),gv(),Bh(),Vh(),Wh(),a.debug(`[WorkspacePanel] workspace panelinitializing`)}function Eh(){document.getElementById(`workspacePanelContainer`);let e=document.getElementById(`workspacePanel`);document.getElementById(`workspacePanelToggle`).addEventListener(`click`,async t=>{t.stopPropagation(),e.classList.contains(`expanded`)?qh():await Kh()}),document.getElementById(`workspacePanelClose`).addEventListener(`click`,e=>{e.stopPropagation(),qh()}),document.getElementById(`workspacePanelModeBtn`).addEventListener(`click`,async e=>{e.stopPropagation(),await zh()});let t=document.getElementById(`workspaceSwitchBtn`);t&&t.addEventListener(`click`,async e=>{e.stopPropagation(),await Qv()}),document.getElementById(`workspaceBackBtn`).addEventListener(`click`,e=>{e.stopPropagation(),vv()}),document.getElementById(`workspaceRefreshBtn`).addEventListener(`click`,e=>{e.stopPropagation(),yv()}),document.getElementById(`workspaceUploadBtn`).addEventListener(`click`,e=>{e.stopPropagation(),nv()}),document.getElementById(`workspaceNewFolderBtn`).addEventListener(`click`,e=>{e.stopPropagation(),cy()}),document.getElementById(`workspaceAskBtn`).addEventListener(`click`,e=>{e.stopPropagation(),dy()}),document.getElementById(`workspaceDownloadDirBtn`).addEventListener(`click`,e=>{e.stopPropagation(),ev()}),document.getElementById(`workspaceBatchDeleteBtn`).addEventListener(`click`,e=>{e.stopPropagation(),Jv()});let n=document.getElementById(`workspaceSearchInput`),i=document.getElementById(`workspaceToolbar`),a=i.querySelector(`.workspace-search-box`);function o(){return i.clientWidth<188}function s(){n.value.trim()?(a.classList.add(`search-box-expanded`),o()&&i.classList.add(`search-focused`)):(a.classList.remove(`search-box-expanded`),i.classList.remove(`search-focused`))}n.addEventListener(`input`,e=>{Wv(e),s()}),n.addEventListener(`focus`,()=>{o()&&i.classList.add(`search-focused`)}),n.addEventListener(`blur`,()=>{n.value.trim()||i.classList.remove(`search-focused`)}),n.addEventListener(`keydown`,e=>{if(e.key===`Enter`)e.stopPropagation(),Gv();else if(e.key===`Escape`)e.stopPropagation(),Kv();else if(e.key===`ArrowUp`){if(e.preventDefault(),Bv.length===0)return;Vv===-1?Vv=Bv.length-1:Vv>0&&Vv--,n.value=Bv[Vv],Lv=n.value.trim(),document.getElementById(`workspaceSearchClear`).style.display=Lv?``:`none`}else e.key===`ArrowDown`&&(e.preventDefault(),Vv===-1||Vv>=Bv.length-1?(Vv=-1,n.value=``,Lv=``,document.getElementById(`workspaceSearchClear`).style.display=`none`):(Vv++,n.value=Bv[Vv],Lv=n.value.trim(),document.getElementById(`workspaceSearchClear`).style.display=Lv?``:`none`))}),document.getElementById(`workspaceSearchBtn`).addEventListener(`click`,()=>{n.focus(),Gv()}),document.getElementById(`workspaceSearchClear`).addEventListener(`click`,Kv),document.getElementById(`workspacePanel`).querySelectorAll(`.workspace-file-header .sortable`).forEach(e=>{e.addEventListener(`click`,()=>{let t=e.dataset.sort;vh.field===t?vh.asc=!vh.asc:(vh.field=t,vh.asc=!0),Cg(),dg()})}),document.getElementById(`workspaceSelectAll`).addEventListener(`click`,xg),document.getElementById(`workspacePanelContent`).addEventListener(`click`,vg),document.getElementById(`workspacePanelContent`).addEventListener(`dblclick`,yg),document.getElementById(`workspacePanelContent`).addEventListener(`keydown`,_g),document.getElementById(`workspacePanelContent`).tabIndex=0,document.getElementById(`workspacePanelContent`).addEventListener(`dragstart`,gg);let c=null;document.getElementById(`workspacePanelContent`).addEventListener(`scroll`,()=>{sg&&(c&&cancelAnimationFrame(c),c=requestAnimationFrame(()=>{c=null,document.getElementById(`workspacePanelContent`).scrollTop!==cg&&ug()}))}),document.getElementById(`workspacePreviewClose`).addEventListener(`click`,()=>K_()),document.getElementById(`workspacePreviewCopyBtn`).addEventListener(`click`,e=>F_(e)),document.getElementById(`workspacePreviewDownloadBtn`).addEventListener(`click`,R_),document.getElementById(`workspacePreviewOpenBrowserBtn`).addEventListener(`click`,z_),document.getElementById(`workspacePreviewFullscreenBtn`).addEventListener(`click`,V_),document.getElementById(`workspacePreviewMdToggleBtn`).addEventListener(`click`,H_),document.getElementById(`workspacePreviewEditBtn`).addEventListener(`click`,q_),document.getElementById(`workspacePreviewSaveBtn`).addEventListener(`click`,J_),document.getElementById(`workspacePreviewCancelBtn`).addEventListener(`click`,Y_),w_(),document.addEventListener(`keydown`,Q_),document.getElementById(`workspacePreviewFilename`).addEventListener(`click`,async e=>{let t=document.getElementById(`workspacePreviewArea`),n=t.dataset.previewName,i=t.dataset.previewPath;if(n){if((e.ctrlKey||e.metaKey)&&!e.shiftKey){e.preventDefault();try{await navigator.clipboard.writeText(n),L(r(`workspace.copiedFileName`,{name:n}))}catch{L(r(`workspace.copyFailed`),`error`)}}else if((e.ctrlKey||e.metaKey)&&e.shiftKey){if(e.preventDefault(),!i)return;try{await navigator.clipboard.writeText(i),L(r(`workspace.copiedPath`,{path:i}))}catch{L(r(`workspace.copyFailed`),`error`)}}}}),hv(),chrome.storage.local.onChanged.addListener(_v);let l=document.createElement(`input`);l.type=`file`,l.multiple=!0,l.id=`workspaceFileInput`,l.style.display=`none`,l.addEventListener(`change`,rv),document.body.appendChild(l)}var Dh=[];function Oh(e){ih.push(e),ih.length>ah&&ih.shift()}function kh(e){if(!e||typeof e!=`string`)return`unnamed`;let t=e.replace(/[<>:"|?*\\/\x00-\x1f]/g,`_`);return t=t.replace(/\.+$/,``),t=t.trim(),t||=`unnamed`,t}function Ah(e,t){let n=J(e);if(!t)return n;let r=t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);return n.replace(RegExp(`(${r})`,`gi`),`<mark class="search-highlight">$1</mark>`)}var jh=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M15 3v18"/></svg>`,Mh=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M15 3v18"/><path d="m8 9-3 3 3 3"/></svg>`;function Nh(){let e=document.getElementById(`mainRow`),t=e?e.clientWidth:window.innerWidth;return Math.max(oh,t-sh)}function Ph(e){return Math.max(oh,Math.min(e,Nh()))}function Fh(e){let t=document.getElementById(`workspacePanelModeBtn`);t&&(t.title=r(e?`workspace.floatMode`:`workspace.embedMode`),t.innerHTML=e?Mh:jh)}function Ih(){let e=document.getElementById(`workspacePanelContainer`);if(!e)return;let t=document.getElementById(`mainRow`);t&&e.parentElement!==t&&t.appendChild(e),e.classList.add(`embedded`),e.style.setProperty(`--ws-embed-width`,`${mh}px`),Fh(!0)}function Lh(){let e=document.getElementById(`workspacePanelContainer`);if(!e)return;e.classList.remove(`embedded`);let t=er(`workspace`);t&&e.parentElement!==t&&t.appendChild(e),Fh(!1)}async function Rh(){try{await chrome.storage.local.set({[uh]:ph,[dh]:mh})}catch(e){a.warn(`[WorkspacePanel] persist embed state failed`,e)}}async function zh(){if(ph){ph=!1,gh=!1,hh=!1,Lh(),await Rh();return}let e=document.getElementById(`mainRow`);if((e?e.clientWidth:window.innerWidth)<ch){L(r(`workspace.narrowViewportHint`),`error`);return}document.getElementById(`workspacePanel`).classList.contains(`expanded`)||await Gh(),mh=Ph(mh),Ih(),ph=!0,gh=!0,hh=!1,await Rh()}function Bh(){let e=document.getElementById(`workspacePanelContainer`),t=document.createElement(`div`);t.className=`workspace-embed-divider`,t.id=`workspaceEmbedDivider`,e.appendChild(t),t.addEventListener(`mousedown`,t=>{t.preventDefault();let n=t.clientX,r=mh;e.classList.add(`resizing`);function i(t){let i=Ph(r+(n-t.clientX));mh=i,e.style.setProperty(`--ws-embed-width`,`${i}px`)}function a(){document.removeEventListener(`mousemove`,i),document.removeEventListener(`mouseup`,a),e.classList.remove(`resizing`),Rh()}document.addEventListener(`mousemove`,i),document.addEventListener(`mouseup`,a)})}function Vh(){let e=document.getElementById(`mainRow`);!e||typeof ResizeObserver>`u`||new ResizeObserver(()=>{if(ph){e.clientWidth<ch&&(hh=!1,ph=!1,gh=!1,Lh(),Rh(),L(r(`workspace.narrowViewportHint`),`error`));return}hh&&e.clientWidth>=ch&&Uh()}).observe(e)}async function Hh(){if(ph)return!0;let e=document.getElementById(`workspacePanelContainer`);if(e&&e.style.display===`none`)return!1;let t=document.getElementById(`mainRow`);return(t?t.clientWidth:window.innerWidth)<ch?!1:(mh=Ph(mh),document.getElementById(`workspacePanel`).classList.contains(`expanded`)||await Gh(),Ih(),ph=!0,!0)}function Uh(){hh=!1,Hh().then(e=>{e||(hh=!0)}).catch(e=>{a.warn(`[WorkspacePanel] deferred embed restore failed`,e),hh=!0})}async function Wh(){try{let e=await chrome.storage.local.get([uh,dh,fh]);if(typeof e[dh]==`number`&&e[dh]>=oh&&(mh=Math.round(e[dh])),!e[uh]||(gh=!0,e[fh]===!1)||(await new Promise(e=>{let t=!1,n=()=>{t||(t=!0,e())};requestAnimationFrame(()=>requestAnimationFrame(n)),setTimeout(n,500)}),await Hh()))return;hh=!0}catch(e){a.warn(`[WorkspacePanel] restore embed state failed`,e)}}async function Gh(){let e=document.getElementById(`workspacePanel`);e.classList.contains(`expanded`)||(e.classList.add(`expanded`),Ft(e),chrome.storage.local.set({[fh]:!0}).catch(()=>{}),await gv(),K||await Jh())}async function Kh(){let e=document.getElementById(`workspacePanel`);if(!(!e||e.classList.contains(`expanded`)))if(Sh=!1,gh){let e=document.getElementById(`mainRow`);if((e?e.clientWidth:window.innerWidth)<ch){await Gh(),L(r(`workspace.narrowViewportHint`),`error`);return}await Gh(),mh=Ph(mh),Ih(),ph=!0,hh=!1,await Rh()}else await Gh()}function qh(){Iv()}async function Jh(){let e=await bn();if(!e){Sv(r(`workspace.noWorkspace`));return}rh=e,ih=[],Yh(e)}async function Yh(e){K=e,q.clear(),bv(),xv(),my(),Cg(),zv&&Lv?(Rv=await Nn(e,Lv),dg()):await tg(e),Sg()}var Xh=new Map,Zh=3e4,Qh=20;function $h(e){let t=Xh.get(e);return t?Date.now()-t.timestamp>=Zh?(Xh.delete(e),null):(Xh.delete(e),Xh.set(e,t),t):null}function eg(e,t){Xh.has(e)&&Xh.delete(e),Xh.set(e,t),Xh.size>Qh&&Xh.delete(Xh.keys().next().value)}async function tg(e){let t=document.getElementById(`workspacePanelContent`);t.innerHTML=`<div class="workspace-panel-loading">${r(`common.loading`)}</div>`;let n=$h(e);if(n){Dh=n.entries,dg();return}let i=await mn(e);if(!i.success){Sv(i.error||r(`workspace.loadDirFailed`));return}Dh=(i.entries||[]).map(t=>({...t,path:ng(`${e}/${t.name}`)})),eg(e,{entries:Dh,timestamp:Date.now()}),dg()}function ng(e){return(e||``).replace(/\\/g,`/`).replace(/\/+/g,`/`)}function rg(e){Xh.delete(e)}var ig=200,ag=32,og=5,sg=null,cg=0;function lg(e){let t=vn(e.name,e.type),n=e.type===`directory`?`—`:kn(e.size),i=_n(e.mtime),a=e.type===`file`&&pn(e.name),o=zv?e.fullPath:ng(`${K}/${e.name}`),s=q.has(o),c=zv&&e.matchPath!==K?ng(e.matchPath).replace(ng(rh),``).replace(/^\//,``)+`/`+e.name:``,l=zv?Ah(e.name,Lv):J(e.name);return`
|
|
1003
|
+
`,er(`workspace`).appendChild(e),Eh(),document.addEventListener(`session-switched`,()=>{ty().catch(e=>a.warn(`[WorkspacePanel] sync after session switch failed`,e))}),document.addEventListener(`session-workdir-changed`,e=>{let t=e.detail?.sessionId;t&&t!==N.activeSessionId||ty().catch(e=>a.warn(`[WorkspacePanel] sync after workdir change failed`,e))}),document.addEventListener(`session-hydrated`,()=>{ty().catch(e=>a.warn(`[WorkspacePanel] sync after session hydrated failed`,e))}),Hv(),gv(),Bh(),Vh(),Wh(),a.debug(`[WorkspacePanel] workspace panelinitializing`)}function Eh(){document.getElementById(`workspacePanelContainer`);let e=document.getElementById(`workspacePanel`);document.getElementById(`workspacePanelToggle`).addEventListener(`click`,async t=>{t.stopPropagation(),e.classList.contains(`expanded`)?qh():await Kh()}),document.getElementById(`workspacePanelClose`).addEventListener(`click`,e=>{e.stopPropagation(),qh()}),document.getElementById(`workspacePanelModeBtn`).addEventListener(`click`,async e=>{e.stopPropagation(),await zh()});let t=document.getElementById(`workspaceSwitchBtn`);t&&t.addEventListener(`click`,async e=>{e.stopPropagation(),await Qv()}),document.getElementById(`workspaceBackBtn`).addEventListener(`click`,e=>{e.stopPropagation(),vv()}),document.getElementById(`workspaceRefreshBtn`).addEventListener(`click`,e=>{e.stopPropagation(),yv()}),document.getElementById(`workspaceUploadBtn`).addEventListener(`click`,e=>{e.stopPropagation(),nv()}),document.getElementById(`workspaceNewFolderBtn`).addEventListener(`click`,e=>{e.stopPropagation(),cy()}),document.getElementById(`workspaceAskBtn`).addEventListener(`click`,e=>{e.stopPropagation(),dy()}),document.getElementById(`workspaceDownloadDirBtn`).addEventListener(`click`,e=>{e.stopPropagation(),ev()}),document.getElementById(`workspaceBatchDeleteBtn`).addEventListener(`click`,e=>{e.stopPropagation(),Jv()});let n=document.getElementById(`workspaceSearchInput`),i=document.getElementById(`workspaceToolbar`),a=i.querySelector(`.workspace-search-box`);function o(){return i.clientWidth<188}function s(){n.value.trim()?(a.classList.add(`search-box-expanded`),o()&&i.classList.add(`search-focused`)):(a.classList.remove(`search-box-expanded`),i.classList.remove(`search-focused`))}n.addEventListener(`input`,e=>{Wv(e),s()}),n.addEventListener(`focus`,()=>{o()&&i.classList.add(`search-focused`)}),n.addEventListener(`blur`,()=>{n.value.trim()||i.classList.remove(`search-focused`)}),n.addEventListener(`keydown`,e=>{if(e.key===`Enter`)e.stopPropagation(),Gv();else if(e.key===`Escape`)e.stopPropagation(),Kv();else if(e.key===`ArrowUp`){if(e.preventDefault(),Bv.length===0)return;Vv===-1?Vv=Bv.length-1:Vv>0&&Vv--,n.value=Bv[Vv],Lv=n.value.trim(),document.getElementById(`workspaceSearchClear`).style.display=Lv?``:`none`}else e.key===`ArrowDown`&&(e.preventDefault(),Vv===-1||Vv>=Bv.length-1?(Vv=-1,n.value=``,Lv=``,document.getElementById(`workspaceSearchClear`).style.display=`none`):(Vv++,n.value=Bv[Vv],Lv=n.value.trim(),document.getElementById(`workspaceSearchClear`).style.display=Lv?``:`none`))}),document.getElementById(`workspaceSearchBtn`).addEventListener(`click`,()=>{n.focus(),Gv()}),document.getElementById(`workspaceSearchClear`).addEventListener(`click`,Kv),document.getElementById(`workspacePanel`).querySelectorAll(`.workspace-file-header .sortable`).forEach(e=>{e.addEventListener(`click`,()=>{let t=e.dataset.sort;vh.field===t?vh.asc=!vh.asc:(vh.field=t,vh.asc=!0),Cg(),dg()})}),document.getElementById(`workspaceSelectAll`).addEventListener(`click`,xg),document.getElementById(`workspacePanelContent`).addEventListener(`click`,vg),document.getElementById(`workspacePanelContent`).addEventListener(`dblclick`,yg),document.getElementById(`workspacePanelContent`).addEventListener(`keydown`,_g),document.getElementById(`workspacePanelContent`).tabIndex=0,document.getElementById(`workspacePanelContent`).addEventListener(`dragstart`,gg);let c=null;document.getElementById(`workspacePanelContent`).addEventListener(`scroll`,()=>{sg&&(c&&cancelAnimationFrame(c),c=requestAnimationFrame(()=>{c=null,document.getElementById(`workspacePanelContent`).scrollTop!==cg&&ug()}))}),document.getElementById(`workspacePreviewClose`).addEventListener(`click`,()=>K_()),document.getElementById(`workspacePreviewCopyBtn`).addEventListener(`click`,e=>F_(e)),document.getElementById(`workspacePreviewDownloadBtn`).addEventListener(`click`,R_),document.getElementById(`workspacePreviewOpenBrowserBtn`).addEventListener(`click`,z_),document.getElementById(`workspacePreviewFullscreenBtn`).addEventListener(`click`,V_),document.getElementById(`workspacePreviewMdToggleBtn`).addEventListener(`click`,H_),document.getElementById(`workspacePreviewEditBtn`).addEventListener(`click`,q_),document.getElementById(`workspacePreviewSaveBtn`).addEventListener(`click`,J_),document.getElementById(`workspacePreviewCancelBtn`).addEventListener(`click`,Y_),w_(),document.addEventListener(`keydown`,Q_),document.getElementById(`workspacePreviewFilename`).addEventListener(`click`,async e=>{let t=document.getElementById(`workspacePreviewArea`),n=t.dataset.previewName,i=t.dataset.previewPath;if(n){if((e.ctrlKey||e.metaKey)&&!e.shiftKey){e.preventDefault();try{await navigator.clipboard.writeText(n),L(r(`workspace.copiedFileName`,{name:n}))}catch{L(r(`workspace.copyFailed`),`error`)}}else if((e.ctrlKey||e.metaKey)&&e.shiftKey){if(e.preventDefault(),!i)return;try{await navigator.clipboard.writeText(i),L(r(`workspace.copiedPath`,{path:i}))}catch{L(r(`workspace.copyFailed`),`error`)}}}}),hv(),chrome.storage.local.onChanged.addListener(_v);let l=document.createElement(`input`);l.type=`file`,l.multiple=!0,l.id=`workspaceFileInput`,l.style.display=`none`,l.addEventListener(`change`,rv),document.body.appendChild(l)}var Dh=[];function Oh(e){ih.push(e),ih.length>ah&&ih.shift()}function kh(e){if(!e||typeof e!=`string`)return`unnamed`;let t=e.replace(/[<>:"|?*\\/\x00-\x1f]/g,`_`);return t=t.replace(/\.+$/,``),t=t.trim(),t||=`unnamed`,t}function Ah(e,t){let n=J(e);if(!t)return n;let r=t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);return n.replace(RegExp(`(${r})`,`gi`),`<mark class="search-highlight">$1</mark>`)}var jh=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M15 3v18"/></svg>`,Mh=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M15 3v18"/><path d="m8 9-3 3 3 3"/></svg>`;function Nh(){let e=document.getElementById(`mainRow`),t=e?e.clientWidth:window.innerWidth;return Math.max(oh,t-sh)}function Ph(e){return Math.max(oh,Math.min(e,Nh()))}function Fh(e){let t=document.getElementById(`workspacePanelModeBtn`);t&&(t.title=r(e?`workspace.floatMode`:`workspace.embedMode`),t.innerHTML=e?Mh:jh)}function Ih(){let e=document.getElementById(`workspacePanelContainer`);if(!e)return;let t=document.getElementById(`mainRow`);t&&e.parentElement!==t&&t.appendChild(e),e.classList.add(`embedded`),e.style.setProperty(`--ws-embed-width`,`${mh}px`),Fh(!0)}function Lh(){let e=document.getElementById(`workspacePanelContainer`);if(!e)return;e.classList.remove(`embedded`);let t=er(`workspace`);t&&e.parentElement!==t&&t.appendChild(e),Fh(!1)}async function Rh(){try{await chrome.storage.local.set({[uh]:ph,[dh]:mh})}catch(e){a.warn(`[WorkspacePanel] persist embed state failed`,e)}}async function zh(){if(ph){ph=!1,gh=!1,hh=!1,Lh(),await Rh();return}let e=document.getElementById(`mainRow`);if((e?e.clientWidth:window.innerWidth)<ch){L(r(`workspace.narrowViewportHint`),`error`);return}document.getElementById(`workspacePanel`).classList.contains(`expanded`)||await Gh(),mh=Ph(mh),Ih(),ph=!0,gh=!0,hh=!1,await Rh()}function Bh(){let e=document.getElementById(`workspacePanelContainer`),t=document.createElement(`div`);t.className=`workspace-embed-divider`,t.id=`workspaceEmbedDivider`,e.appendChild(t),t.addEventListener(`mousedown`,t=>{t.preventDefault();let n=t.clientX,r=mh;e.classList.add(`resizing`);function i(t){let i=Ph(r+(n-t.clientX));mh=i,e.style.setProperty(`--ws-embed-width`,`${i}px`)}function a(){document.removeEventListener(`mousemove`,i),document.removeEventListener(`mouseup`,a),e.classList.remove(`resizing`),Rh()}document.addEventListener(`mousemove`,i),document.addEventListener(`mouseup`,a)})}function Vh(){let e=document.getElementById(`mainRow`);!e||typeof ResizeObserver>`u`||new ResizeObserver(()=>{if(ph){e.clientWidth<ch&&(hh=!1,ph=!1,gh=!1,Lh(),Rh(),L(r(`workspace.narrowViewportHint`),`error`));return}hh&&e.clientWidth>=ch&&Uh()}).observe(e)}async function Hh(){if(ph)return!0;let e=document.getElementById(`workspacePanelContainer`);if(e&&e.style.display===`none`)return!1;let t=document.getElementById(`mainRow`);return(t?t.clientWidth:window.innerWidth)<ch?!1:(mh=Ph(mh),document.getElementById(`workspacePanel`).classList.contains(`expanded`)||await Gh(),Ih(),ph=!0,!0)}function Uh(){hh=!1,Hh().then(e=>{e||(hh=!0)}).catch(e=>{a.warn(`[WorkspacePanel] deferred embed restore failed`,e),hh=!0})}async function Wh(){try{let e=await chrome.storage.local.get([uh,dh,fh]);if(typeof e[dh]==`number`&&e[dh]>=oh&&(mh=Math.round(e[dh])),!e[uh]||(gh=!0,e[fh]===!1)||(await new Promise(e=>{let t=!1,n=()=>{t||(t=!0,e())};requestAnimationFrame(()=>requestAnimationFrame(n)),setTimeout(n,500)}),await Hh()))return;hh=!0}catch(e){a.warn(`[WorkspacePanel] restore embed state failed`,e)}}async function Gh(){let e=document.getElementById(`workspacePanel`);e.classList.contains(`expanded`)||(e.classList.add(`expanded`),It(e),chrome.storage.local.set({[fh]:!0}).catch(()=>{}),await gv(),K||await Jh())}async function Kh(){let e=document.getElementById(`workspacePanel`);if(!(!e||e.classList.contains(`expanded`)))if(Sh=!1,gh){let e=document.getElementById(`mainRow`);if((e?e.clientWidth:window.innerWidth)<ch){await Gh(),L(r(`workspace.narrowViewportHint`),`error`);return}await Gh(),mh=Ph(mh),Ih(),ph=!0,hh=!1,await Rh()}else await Gh()}function qh(){Iv()}async function Jh(){let e=await bn();if(!e){Sv(r(`workspace.noWorkspace`));return}rh=e,ih=[],Yh(e)}async function Yh(e){K=e,q.clear(),bv(),xv(),my(),Cg(),zv&&Lv?(Rv=await Nn(e,Lv),dg()):await tg(e),Sg()}var Xh=new Map,Zh=3e4,Qh=20;function $h(e){let t=Xh.get(e);return t?Date.now()-t.timestamp>=Zh?(Xh.delete(e),null):(Xh.delete(e),Xh.set(e,t),t):null}function eg(e,t){Xh.has(e)&&Xh.delete(e),Xh.set(e,t),Xh.size>Qh&&Xh.delete(Xh.keys().next().value)}async function tg(e){let t=document.getElementById(`workspacePanelContent`);t.innerHTML=`<div class="workspace-panel-loading">${r(`common.loading`)}</div>`;let n=$h(e);if(n){Dh=n.entries,dg();return}let i=await mn(e);if(!i.success){Sv(i.error||r(`workspace.loadDirFailed`));return}Dh=(i.entries||[]).map(t=>({...t,path:ng(`${e}/${t.name}`)})),eg(e,{entries:Dh,timestamp:Date.now()}),dg()}function ng(e){return(e||``).replace(/\\/g,`/`).replace(/\/+/g,`/`)}function rg(e){Xh.delete(e)}var ig=200,ag=32,og=5,sg=null,cg=0;function lg(e){let t=vn(e.name,e.type),n=e.type===`directory`?`—`:kn(e.size),i=_n(e.mtime),a=e.type===`file`&&pn(e.name),o=zv?e.fullPath:ng(`${K}/${e.name}`),s=q.has(o),c=zv&&e.matchPath!==K?ng(e.matchPath).replace(ng(rh),``).replace(/^\//,``)+`/`+e.name:``,l=zv?Ah(e.name,Lv):J(e.name);return`
|
|
1004
1004
|
<div class="workspace-file-item ${e.type} ${s?`selected`:``}" data-path="${J(o)}" data-type="${e.type}" data-name="${J(e.name)}" draggable="true">
|
|
1005
1005
|
<span class="workspace-file-select" data-action="select">
|
|
1006
1006
|
<span class="workspace-checkbox ${s?`checked`:``}"></span>
|
|
@@ -1047,7 +1047,7 @@ It is this session's directory or the agent default, so it stays accessible (wor
|
|
|
1047
1047
|
</div>
|
|
1048
1048
|
</div>
|
|
1049
1049
|
</div>
|
|
1050
|
-
`;let u=document.getElementById(`pdfViewport`),d=document.getElementById(`pdfPan`),f=document.getElementById(`pdfCanvas`),p=document.getElementById(`pdfZoomInfo`);function m(){d.style.transform=`translate(${Vg}px, ${Hg}px) scale(${zg})`,p.textContent=Math.round(Rg*100)+`%`,Ug||(u.style.cursor=Rg>Bg?`grab`:`default`)}function h(){Rg<=Bg&&(Vg=0,Hg=0)}function g(e,t,n){let r=Rg;if(Rg=Math.max(.05,Math.min(5,e)),zg=Rg/Yg,t!==void 0&&n!==void 0){let e=u.getBoundingClientRect(),i=t-e.left-e.width/2,a=n-e.top-e.height/2,o=Rg/r;Vg=i-o*(i-Vg),Hg=a-o*(a-Hg)}h(),m(),_()}function _(){Jg&&clearTimeout(Jg),Jg=setTimeout(()=>{v()},180)}async function v(){if(!Ig)return;let e=await Ig.getPage(Lg),t=window.devicePixelRatio||1,n=Math.max(Rg,1);Yg=n;let r=e.getViewport({scale:n});f.width=Math.floor(r.width*t),f.height=Math.floor(r.height*t),f.style.width=r.width+`px`,f.style.height=r.height+`px`;let i=f.getContext(`2d`);i.setTransform(t,0,0,t,0,0),await e.render({canvasContext:i,viewport:r}).promise;let a=e.getViewport({scale:1}),o=u.clientWidth,s=u.clientHeight;Bg=o>0&&s>0&&a.width>0&&a.height>0?Math.min((o-24)/a.width,(s-24)/a.height):1,zg=Rg/n,Rg<Bg*1.05&&Rg>Bg*.95&&(Rg=Bg,zg=Bg/n,Vg=0,Hg=0),h(),m();let c=document.getElementById(`pdfPrevPage`),l=document.getElementById(`pdfNextPage`),d=document.getElementById(`pdfPageInput`);c&&(c.disabled=Lg<=1),l&&(l.disabled=Lg>=Ig.numPages),d&&(d.value=Lg)}await v(),u.addEventListener(`wheel`,e=>{e.preventDefault();let t=-e.deltaY*.005;g(Rg+t*Rg,e.clientX,e.clientY)},{passive:!1}),u.addEventListener(`mousedown`,e=>{e.button===0&&(Ug=!0,Wg=e.clientX,Gg=e.clientY,Kg=Vg,qg=Hg,u.style.cursor=`grabbing`,e.preventDefault())}),wh(o,`mousemove`,e=>{Ug&&(Vg=Kg+(e.clientX-Wg),Hg=qg+(e.clientY-Gg),h(),m())}),wh(o,`mouseup`,()=>{Ug&&(Ug=!1,u.style.cursor=Rg>Bg?`grab`:`default`)}),document.getElementById(`pdfPrevPage`).addEventListener(`click`,()=>{Lg>1&&(Lg--,v())}),document.getElementById(`pdfNextPage`).addEventListener(`click`,()=>{Lg<l&&(Lg++,v())}),document.getElementById(`pdfPageInput`).addEventListener(`change`,e=>{let t=parseInt(e.target.value,10);t>=1&&t<=l&&(Lg=t,v())}),document.getElementById(`pdfZoomIn`).addEventListener(`click`,()=>{let e=u.getBoundingClientRect();g(Rg*1.25,e.left+e.width/2,e.top+e.height/2)}),document.getElementById(`pdfZoomOut`).addEventListener(`click`,()=>{let e=u.getBoundingClientRect();g(Rg/1.25,e.left+e.width/2,e.top+e.height/2)}),document.getElementById(`pdfZoomFit`).addEventListener(`click`,()=>{Rg=Bg,Vg=0,Hg=0,v()}),u.addEventListener(`dblclick`,()=>{Rg=Bg,Vg=0,Hg=0,v()}),wh(o,`resize`,()=>{Ig&&v()})}async function Zg(t,n){let i=await(await M(async()=>{let{default:t}=await import(`./lib-YwkWjNcC.js`).then(t=>e(t.default,1));return{default:t}},__vite__mapDeps([7,1,8,6]))).default.convertToHtml({arrayBuffer:t},{styleMap:[`p[style-name='Heading 1'] => h1:fresh`,`p[style-name='Heading 2'] => h2:fresh`,`p[style-name='Heading 3'] => h3:fresh`,`r[style-name='Strong'] => strong`,`r[style-name='Emphasis'] => em`]}),a=i.value||`<p>${r(`workspace.documentEmpty`)}</p>`,o=
|
|
1050
|
+
`;let u=document.getElementById(`pdfViewport`),d=document.getElementById(`pdfPan`),f=document.getElementById(`pdfCanvas`),p=document.getElementById(`pdfZoomInfo`);function m(){d.style.transform=`translate(${Vg}px, ${Hg}px) scale(${zg})`,p.textContent=Math.round(Rg*100)+`%`,Ug||(u.style.cursor=Rg>Bg?`grab`:`default`)}function h(){Rg<=Bg&&(Vg=0,Hg=0)}function g(e,t,n){let r=Rg;if(Rg=Math.max(.05,Math.min(5,e)),zg=Rg/Yg,t!==void 0&&n!==void 0){let e=u.getBoundingClientRect(),i=t-e.left-e.width/2,a=n-e.top-e.height/2,o=Rg/r;Vg=i-o*(i-Vg),Hg=a-o*(a-Hg)}h(),m(),_()}function _(){Jg&&clearTimeout(Jg),Jg=setTimeout(()=>{v()},180)}async function v(){if(!Ig)return;let e=await Ig.getPage(Lg),t=window.devicePixelRatio||1,n=Math.max(Rg,1);Yg=n;let r=e.getViewport({scale:n});f.width=Math.floor(r.width*t),f.height=Math.floor(r.height*t),f.style.width=r.width+`px`,f.style.height=r.height+`px`;let i=f.getContext(`2d`);i.setTransform(t,0,0,t,0,0),await e.render({canvasContext:i,viewport:r}).promise;let a=e.getViewport({scale:1}),o=u.clientWidth,s=u.clientHeight;Bg=o>0&&s>0&&a.width>0&&a.height>0?Math.min((o-24)/a.width,(s-24)/a.height):1,zg=Rg/n,Rg<Bg*1.05&&Rg>Bg*.95&&(Rg=Bg,zg=Bg/n,Vg=0,Hg=0),h(),m();let c=document.getElementById(`pdfPrevPage`),l=document.getElementById(`pdfNextPage`),d=document.getElementById(`pdfPageInput`);c&&(c.disabled=Lg<=1),l&&(l.disabled=Lg>=Ig.numPages),d&&(d.value=Lg)}await v(),u.addEventListener(`wheel`,e=>{e.preventDefault();let t=-e.deltaY*.005;g(Rg+t*Rg,e.clientX,e.clientY)},{passive:!1}),u.addEventListener(`mousedown`,e=>{e.button===0&&(Ug=!0,Wg=e.clientX,Gg=e.clientY,Kg=Vg,qg=Hg,u.style.cursor=`grabbing`,e.preventDefault())}),wh(o,`mousemove`,e=>{Ug&&(Vg=Kg+(e.clientX-Wg),Hg=qg+(e.clientY-Gg),h(),m())}),wh(o,`mouseup`,()=>{Ug&&(Ug=!1,u.style.cursor=Rg>Bg?`grab`:`default`)}),document.getElementById(`pdfPrevPage`).addEventListener(`click`,()=>{Lg>1&&(Lg--,v())}),document.getElementById(`pdfNextPage`).addEventListener(`click`,()=>{Lg<l&&(Lg++,v())}),document.getElementById(`pdfPageInput`).addEventListener(`change`,e=>{let t=parseInt(e.target.value,10);t>=1&&t<=l&&(Lg=t,v())}),document.getElementById(`pdfZoomIn`).addEventListener(`click`,()=>{let e=u.getBoundingClientRect();g(Rg*1.25,e.left+e.width/2,e.top+e.height/2)}),document.getElementById(`pdfZoomOut`).addEventListener(`click`,()=>{let e=u.getBoundingClientRect();g(Rg/1.25,e.left+e.width/2,e.top+e.height/2)}),document.getElementById(`pdfZoomFit`).addEventListener(`click`,()=>{Rg=Bg,Vg=0,Hg=0,v()}),u.addEventListener(`dblclick`,()=>{Rg=Bg,Vg=0,Hg=0,v()}),wh(o,`resize`,()=>{Ig&&v()})}async function Zg(t,n){let i=await(await M(async()=>{let{default:t}=await import(`./lib-YwkWjNcC.js`).then(t=>e(t.default,1));return{default:t}},__vite__mapDeps([7,1,8,6]))).default.convertToHtml({arrayBuffer:t},{styleMap:[`p[style-name='Heading 1'] => h1:fresh`,`p[style-name='Heading 2'] => h2:fresh`,`p[style-name='Heading 3'] => h3:fresh`,`r[style-name='Strong'] => strong`,`r[style-name='Emphasis'] => em`]}),a=i.value||`<p>${r(`workspace.documentEmpty`)}</p>`,o=pt.sanitize(a,{ALLOWED_TAGS:`h1.h2.h3.h4.h5.h6.p.br.strong.em.u.s.a.img.table.thead.tbody.tr.td.th.ul.ol.li.blockquote.pre.code.hr.sup.sub`.split(`.`),ALLOWED_ATTR:[`href`,`src`,`alt`,`title`,`style`]}),s=i.messages?i.messages.filter(e=>e.type===`error`):[];s.length>0?n.innerHTML=`<div class="workspace-preview-docx">${o}<div class="docx-warnings">${s.map(e=>`<div class="docx-warning">⚠ ${J(e.message)}</div>`).join(``)}</div></div>`:n.innerHTML=`<div class="workspace-preview-docx">${o}</div>`}var Qg=[],$g=0,e_=1,t_=1,n_=0,r_=0,i_=!1,a_=0,o_=0,s_=0,c_=0;async function l_(e,t,n,i,a){i.dataset.previewType=`pptx`;let{pptxToHtml:o}=await M(async()=>{let{pptxToHtml:e}=await import(`./dist-DuuG_8Br.js`);return{pptxToHtml:e}},__vite__mapDeps([9,1,8]));if(Qg=await o(e,{width:960,height:540,scaleToFit:!0,letterbox:!0}),$g=0,e_=1,t_=1,n_=0,r_=0,!Qg||Qg.length===0){n.innerHTML=`<div class="workspace-panel-error">${r(`workspace.pptxEmptyOrFailed`)}</div>`;return}let s=Qg.length;document.getElementById(`workspacePreviewLineCount`).textContent=r(`workspace.pageCount`,{count:s}),n.innerHTML=`
|
|
1051
1051
|
<div class="pptx-wrap">
|
|
1052
1052
|
<div class="pptx-toolbar">
|
|
1053
1053
|
<button class="pptx-toolbar-btn" id="pptxPrevSlide" title="${r(`workspace.prevPage`)}" disabled>
|
|
@@ -1076,7 +1076,7 @@ It is this session's directory or the agent default, so it stays accessible (wor
|
|
|
1076
1076
|
</div>
|
|
1077
1077
|
</div>
|
|
1078
1078
|
</div>
|
|
1079
|
-
`,f_();let c=document.getElementById(`pptxViewport`),l=document.getElementById(`pptxPan`),u=document.getElementById(`pptxZoomInfo`);function d(){l.style.transform=`translate(${n_}px, ${r_}px) scale(${e_})`,u.textContent=Math.round(e_*100)+`%`,i_||(c.style.cursor=e_>t_?`grab`:`default`)}function f(){e_<=t_&&(n_=0,r_=0)}function p(e,t,n){let r=e_;if(e_=Math.max(.05,Math.min(5,e)),t!==void 0&&n!==void 0){let e=c.getBoundingClientRect(),i=t-e.left-e.width/2,a=n-e.top-e.height/2,o=e_/r;n_=i-o*(i-n_),r_=a-o*(a-r_)}e_<t_*1.05&&e_>t_*.95&&(e_=t_,n_=0,r_=0),f(),d()}c.addEventListener(`wheel`,e=>{e.preventDefault();let t=-e.deltaY*.005;p(e_+t*e_,e.clientX,e.clientY)},{passive:!1}),c.addEventListener(`mousedown`,e=>{e.button===0&&(i_=!0,a_=e.clientX,o_=e.clientY,s_=n_,c_=r_,c.style.cursor=`grabbing`,e.preventDefault())}),wh(a,`mousemove`,e=>{i_&&(n_=s_+(e.clientX-a_),r_=c_+(e.clientY-o_),f(),d())}),wh(a,`mouseup`,()=>{i_&&(i_=!1,c.style.cursor=e_>t_?`grab`:`default`)}),document.getElementById(`pptxPrevSlide`).addEventListener(`click`,()=>{$g>0&&($g--,f_())}),document.getElementById(`pptxNextSlide`).addEventListener(`click`,()=>{$g<s-1&&($g++,f_())}),document.getElementById(`pptxZoomIn`).addEventListener(`click`,()=>{let e=c.getBoundingClientRect();p(e_*1.25,e.left+e.width/2,e.top+e.height/2)}),document.getElementById(`pptxZoomOut`).addEventListener(`click`,()=>{let e=c.getBoundingClientRect();p(e_/1.25,e.left+e.width/2,e.top+e.height/2)}),document.getElementById(`pptxZoomFit`).addEventListener(`click`,()=>{requestAnimationFrame(()=>{u_(),e_=t_,n_=0,r_=0,l.style.transform=`translate(0px, 0px) scale(${t_})`,u.textContent=Math.round(t_*100)+`%`,c.style.cursor=`default`})}),c.addEventListener(`dblclick`,()=>{requestAnimationFrame(()=>{u_(),e_=t_,n_=0,r_=0,l.style.transform=`translate(0px, 0px) scale(${t_})`,u.textContent=Math.round(t_*100)+`%`,c.style.cursor=`default`})}),wh(a,`resize`,()=>{!Qg||Qg.length===0||requestAnimationFrame(()=>{d_()})})}function u_(){let e=document.getElementById(`pptxViewport`),t=document.getElementById(`pptxSlideContainer`);if(!e||!t)return;let n=parseFloat(t.style.width)||960,r=parseFloat(t.style.height)||540,i=e.clientWidth,a=e.clientHeight;t_=i>0&&a>0&&n>0&&r>0?Math.min((i-8)/n,(a-8)/r):1}function d_(){let e=document.getElementById(`pptxViewport`),t=document.getElementById(`pptxPan`),n=document.getElementById(`pptxZoomInfo`);if(!e||!t)return;let r=t_;u_(),e_<=r*1.05&&(e_=t_,n_=0,r_=0),t.style.transform=`translate(${n_}px, ${r_}px) scale(${e_})`,n&&(n.textContent=Math.round(e_*100)+`%`),i_||(e.style.cursor=e_>t_?`grab`:`default`)}function f_(){let e=document.getElementById(`pptxSlideContainer`),t=document.getElementById(`pptxPan`);if(!e||!t||$g<0||$g>=Qg.length)return;t.style.transform=`scale(1)`;let n=Qg[$g],r=
|
|
1079
|
+
`,f_();let c=document.getElementById(`pptxViewport`),l=document.getElementById(`pptxPan`),u=document.getElementById(`pptxZoomInfo`);function d(){l.style.transform=`translate(${n_}px, ${r_}px) scale(${e_})`,u.textContent=Math.round(e_*100)+`%`,i_||(c.style.cursor=e_>t_?`grab`:`default`)}function f(){e_<=t_&&(n_=0,r_=0)}function p(e,t,n){let r=e_;if(e_=Math.max(.05,Math.min(5,e)),t!==void 0&&n!==void 0){let e=c.getBoundingClientRect(),i=t-e.left-e.width/2,a=n-e.top-e.height/2,o=e_/r;n_=i-o*(i-n_),r_=a-o*(a-r_)}e_<t_*1.05&&e_>t_*.95&&(e_=t_,n_=0,r_=0),f(),d()}c.addEventListener(`wheel`,e=>{e.preventDefault();let t=-e.deltaY*.005;p(e_+t*e_,e.clientX,e.clientY)},{passive:!1}),c.addEventListener(`mousedown`,e=>{e.button===0&&(i_=!0,a_=e.clientX,o_=e.clientY,s_=n_,c_=r_,c.style.cursor=`grabbing`,e.preventDefault())}),wh(a,`mousemove`,e=>{i_&&(n_=s_+(e.clientX-a_),r_=c_+(e.clientY-o_),f(),d())}),wh(a,`mouseup`,()=>{i_&&(i_=!1,c.style.cursor=e_>t_?`grab`:`default`)}),document.getElementById(`pptxPrevSlide`).addEventListener(`click`,()=>{$g>0&&($g--,f_())}),document.getElementById(`pptxNextSlide`).addEventListener(`click`,()=>{$g<s-1&&($g++,f_())}),document.getElementById(`pptxZoomIn`).addEventListener(`click`,()=>{let e=c.getBoundingClientRect();p(e_*1.25,e.left+e.width/2,e.top+e.height/2)}),document.getElementById(`pptxZoomOut`).addEventListener(`click`,()=>{let e=c.getBoundingClientRect();p(e_/1.25,e.left+e.width/2,e.top+e.height/2)}),document.getElementById(`pptxZoomFit`).addEventListener(`click`,()=>{requestAnimationFrame(()=>{u_(),e_=t_,n_=0,r_=0,l.style.transform=`translate(0px, 0px) scale(${t_})`,u.textContent=Math.round(t_*100)+`%`,c.style.cursor=`default`})}),c.addEventListener(`dblclick`,()=>{requestAnimationFrame(()=>{u_(),e_=t_,n_=0,r_=0,l.style.transform=`translate(0px, 0px) scale(${t_})`,u.textContent=Math.round(t_*100)+`%`,c.style.cursor=`default`})}),wh(a,`resize`,()=>{!Qg||Qg.length===0||requestAnimationFrame(()=>{d_()})})}function u_(){let e=document.getElementById(`pptxViewport`),t=document.getElementById(`pptxSlideContainer`);if(!e||!t)return;let n=parseFloat(t.style.width)||960,r=parseFloat(t.style.height)||540,i=e.clientWidth,a=e.clientHeight;t_=i>0&&a>0&&n>0&&r>0?Math.min((i-8)/n,(a-8)/r):1}function d_(){let e=document.getElementById(`pptxViewport`),t=document.getElementById(`pptxPan`),n=document.getElementById(`pptxZoomInfo`);if(!e||!t)return;let r=t_;u_(),e_<=r*1.05&&(e_=t_,n_=0,r_=0),t.style.transform=`translate(${n_}px, ${r_}px) scale(${e_})`,n&&(n.textContent=Math.round(e_*100)+`%`),i_||(e.style.cursor=e_>t_?`grab`:`default`)}function f_(){let e=document.getElementById(`pptxSlideContainer`),t=document.getElementById(`pptxPan`);if(!e||!t||$g<0||$g>=Qg.length)return;t.style.transform=`scale(1)`;let n=Qg[$g],r=pt.sanitize(n,{ALLOWED_TAGS:`div.span.p.a.img.svg.path.circle.rect.line.polyline.polygon.ellipse.g.defs.linearGradient.radialGradient.stop.text.tspan.table.thead.tbody.tr.td.th.br.h1.h2.h3.h4.h5.h6.ul.ol.li.strong.em.b.i.u`.split(`.`),ALLOWED_ATTR:`class.style.id.src.alt.width.height.href.target.d.fill.stroke.stroke-width.transform.viewBox.x.y.cx.cy.r.rx.ry.x1.y1.x2.y2.points.opacity.font-size.font-family.text-anchor.dominant-baseline.clip-path.preserveAspectRatio.xmlns`.split(`.`)});e.style.width=``,e.style.height=``,e.innerHTML=r;let i=e.firstElementChild;i?(e.style.width=(i.offsetWidth||960)+`px`,e.style.height=(i.offsetHeight||540)+`px`):(e.style.width=`960px`,e.style.height=`540px`),u_(),e_=t_,n_=0,r_=0,t.style.transform=`translate(0px, 0px) scale(${t_})`;let a=document.getElementById(`pptxZoomInfo`);a&&(a.textContent=Math.round(e_*100)+`%`);let o=document.getElementById(`pptxViewport`);o&&!i_&&(o.style.cursor=`default`);let s=document.getElementById(`pptxPrevSlide`),c=document.getElementById(`pptxNextSlide`),l=document.getElementById(`pptxSlideNum`);s&&(s.disabled=$g<=0),c&&(c.disabled=$g>=Qg.length-1),l&&(l.textContent=$g+1)}var p_=[],m_=0;async function h_(e,t,n){t.innerHTML=`<div class="workspace-panel-empty">${r(`workspace.parsingExcel`)}</div>`;let i=n.dataset.previewPath,a;try{let e=await Cn();if(!e)throw Error(r(`workspace.agentNotPaired`));a=await(await fetch(`${e.url}/api/fs/preview-xlsx`,{method:`POST`,headers:{"Content-Type":`application/json`,...An(e)},body:JSON.stringify({path:i,maxRows:500})})).json()}catch(e){t.innerHTML=`<div class="workspace-panel-error">${r(`workspace.requestFailed`,{error:J(e.message)})}</div>`;return}if(!a.success){t.innerHTML=`<div class="workspace-panel-error">${r(`workspace.parseFailed`,{error:J(a.error||r(`workspace.unknownError`))})}</div>`;return}let{sheets:o}=a.data;if(!o||o.length===0){t.innerHTML=`<div class="workspace-panel-error">${r(`workspace.noSheetsInWorkbook`)}</div>`;return}p_=o,m_=0,n.dataset.previewType=`xlsx`,n.dataset.previewSheets=JSON.stringify(o.map(e=>e.name)),t.classList.add(`xlsx-mode`);let s=`<div class="xlsx-sheet-tabs" id="xlsxSheetTabs">`;o.forEach((e,t)=>{s+=`<button class="xlsx-sheet-tab${t===0?` active`:``}" data-sheet="${t}">${J(e.name)}</button>`}),s+=`</div>`,t.innerHTML=s+`<div class="xlsx-sheet-content" id="xlsxSheetContent"><div class="workspace-panel-empty">${r(`workspace.loadingData`)}</div></div>`,document.getElementById(`xlsxSheetTabs`).addEventListener(`click`,e=>{let t=e.target.closest(`.xlsx-sheet-tab`);if(!t)return;let n=parseInt(t.dataset.sheet,10);n!==m_&&(document.querySelectorAll(`.xlsx-sheet-tab`).forEach(e=>e.classList.remove(`active`)),t.classList.add(`active`),g_(n))}),await g_(0)}async function g_(e){let t=document.getElementById(`xlsxSheetContent`);if(!t)return;m_=e;let n=p_[e];if(!n){t.innerHTML=`<div class="workspace-panel-error">${r(`workspace.sheetNotFound`)}</div>`;return}__(n.rows,n.colCount,n.totalRows,t)}function __(e,t,n,i){let a=i.querySelector(`.xlsx-table-scrollbar-mirror`);if(a&&a.remove(),!e||e.length===0){i.innerHTML=`<div class="workspace-panel-empty">${r(`workspace.emptySheet`)}</div>`;return}let o=e[0],s=`<div class="xlsx-table-scroll" id="xlsxTableScroll"><table class="xlsx-preview-table"><thead><tr>`;for(let e of o)s+=`<th>${J(String(e??``))}</th>`;s+=`</tr></thead><tbody>`;for(let n=1;n<e.length;n++){s+=`<tr>`;for(let r=0;r<t;r++)s+=`<td>${J(String(e[n][r]??``))}</td>`;s+=`</tr>`}s+=`</tbody></table></div>`,n>Ng&&(s+=`<div class="xlsx-truncated-msg">${r(`workspace.xlsxTruncatedHint`,{shown:Ng,total:n})}</div>`),i.innerHTML=s;let c=i.querySelector(`#xlsxTableScroll`);if(c){let e=document.createElement(`div`);e.className=`xlsx-table-scrollbar-mirror`,e.innerHTML=`<div class="xlsx-table-scrollbar-mirror-inner" style="width:${c.scrollWidth}px;"></div>`;let t=!1;c.addEventListener(`scroll`,()=>{if(t){t=!1;return}t=!0,e.scrollLeft=c.scrollLeft}),e.addEventListener(`scroll`,()=>{if(t){t=!1;return}t=!0,c.scrollLeft=e.scrollLeft}),i.appendChild(e)}}async function v_(e,t,n,i){let a={png:`image/png`,jpg:`image/jpeg`,jpeg:`image/jpeg`,gif:`image/gif`,webp:`image/webp`,bmp:`image/bmp`,ico:`image/x-icon`}[(t.split(`.`).pop()||``).toLowerCase()]||`image/png`,o=new Blob([e],{type:a}),s=URL.createObjectURL(o);n.innerHTML=`
|
|
1080
1080
|
<div class="image-preview-wrap">
|
|
1081
1081
|
<div class="image-preview-toolbar">
|
|
1082
1082
|
<button class="image-preview-btn" id="imgZoomOut" title="${r(`workspace.zoomOut`)}">
|
|
@@ -1110,8 +1110,8 @@ It is this session's directory or the agent default, so it stays accessible (wor
|
|
|
1110
1110
|
<source src="${c}" type="${J(o)}">
|
|
1111
1111
|
</audio>
|
|
1112
1112
|
<div id="mediaUnsupportedHint" style="display:none;">${u}</div>
|
|
1113
|
-
</div>`;let d=i.querySelector(`video, audio`),f=i.querySelector(`#mediaUnsupportedHint`);if(d){let e=()=>{d.style.display=`none`,f&&(f.style.display=`block`)};d.addEventListener(`error`,e),i.querySelectorAll(`source`).forEach(t=>t.addEventListener(`error`,e))}}var x_=!1;function S_(e,t){let n=e.getBoundingClientRect();t.style.top=n.bottom+4+`px`;let r=n.right-160;t.style.left=Math.max(4,r)+`px`,t.style.right=`auto`}function C_(e,t){S_(e,t),t.classList.add(`show`)}function w_(){let e=document.getElementById(`workspacePreviewExportMenu`),t=document.getElementById(`workspacePreviewExportBtn`),n=document.getElementById(`workspacePreviewExportDropdown`);if(!e||!t||!n)return;document.body.appendChild(n),t.addEventListener(`click`,e=>{e.stopPropagation(),n.classList.contains(`show`)?n.classList.remove(`show`):C_(t,n)});let r=null,i=null;e.addEventListener(`mouseenter`,()=>{i&&=(clearTimeout(i),null),r=setTimeout(()=>{C_(t,n)},200)}),e.addEventListener(`mouseleave`,()=>{r&&=(clearTimeout(r),null),i=setTimeout(()=>{!e.matches(`:hover`)&&!n.matches(`:hover`)&&n.classList.remove(`show`)},300)}),n.addEventListener(`mouseenter`,()=>{i&&=(clearTimeout(i),null)}),n.addEventListener(`mouseleave`,()=>{i=setTimeout(()=>{!e.matches(`:hover`)&&!n.matches(`:hover`)&&n.classList.remove(`show`)},200)}),n.querySelectorAll(`.ws-export-dropdown-item`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation();let r=e.dataset.exportType;n.classList.remove(`show`),E_(r)})}),document.addEventListener(`click`,t=>{!e.contains(t.target)&&!n.contains(t.target)&&n.classList.remove(`show`)});let a=()=>{n.classList.contains(`show`)&&S_(t,n)};document.getElementById(`workspacePreviewContent`)?.addEventListener(`scroll`,a),window.addEventListener(`resize`,a)}function T_(){return document.getElementById(`workspacePreviewArea`).dataset.markdownText||``}async function E_(e){if(x_)return;x_=!0;let t=document.getElementById(`workspacePreviewExportBtn`);document.getElementById(`workspacePreviewExportMenu`);let n=document.getElementById(`workspacePreviewExportDropdown`),i=document.getElementById(`workspacePreviewArea`).dataset.previewName||`export`,o=t.innerHTML;t.innerHTML=`<svg viewBox="0 0 24 24" fill="none" style="animation: spin 0.8s linear infinite; width: 14px; height: 14px; flex-shrink: 0;"><circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-dasharray="31.4" stroke-dashoffset="10" opacity="0.25"/><circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-dasharray="31.4" stroke-dashoffset="10"/></svg>`,t.disabled=!0,t.style.opacity=`0.6`;try{switch(e){case`docx`:await k_(i);break;case`pdf`:await j_(i);break;case`image`:await M_(i);break;case`md`:N_(i);break}}catch(e){a.error(`[WorkspacePanel] export failed:`,e),L(r(`chatExport.exportFailed`,{message:e.message}),`error`)}finally{x_=!1,t.innerHTML=o,t.disabled=!1,t.style.opacity=`1`,n.classList.remove(`show`)}}async function D_(e){if(typeof mermaid>`u`)return;let{renderMermaidInContainer:t,convertSvgsToImages:n}=await M(async()=>{let{renderMermaidInContainer:e,convertSvgsToImages:t}=await import(`./chat-export-
|
|
1114
|
-
`),n=[];for(let e of t){if(/^[\s\|:\-]+$/.test(e.replace(/\|/g,``)))continue;let t=
|
|
1113
|
+
</div>`;let d=i.querySelector(`video, audio`),f=i.querySelector(`#mediaUnsupportedHint`);if(d){let e=()=>{d.style.display=`none`,f&&(f.style.display=`block`)};d.addEventListener(`error`,e),i.querySelectorAll(`source`).forEach(t=>t.addEventListener(`error`,e))}}var x_=!1;function S_(e,t){let n=e.getBoundingClientRect();t.style.top=n.bottom+4+`px`;let r=n.right-160;t.style.left=Math.max(4,r)+`px`,t.style.right=`auto`}function C_(e,t){S_(e,t),t.classList.add(`show`)}function w_(){let e=document.getElementById(`workspacePreviewExportMenu`),t=document.getElementById(`workspacePreviewExportBtn`),n=document.getElementById(`workspacePreviewExportDropdown`);if(!e||!t||!n)return;document.body.appendChild(n),t.addEventListener(`click`,e=>{e.stopPropagation(),n.classList.contains(`show`)?n.classList.remove(`show`):C_(t,n)});let r=null,i=null;e.addEventListener(`mouseenter`,()=>{i&&=(clearTimeout(i),null),r=setTimeout(()=>{C_(t,n)},200)}),e.addEventListener(`mouseleave`,()=>{r&&=(clearTimeout(r),null),i=setTimeout(()=>{!e.matches(`:hover`)&&!n.matches(`:hover`)&&n.classList.remove(`show`)},300)}),n.addEventListener(`mouseenter`,()=>{i&&=(clearTimeout(i),null)}),n.addEventListener(`mouseleave`,()=>{i=setTimeout(()=>{!e.matches(`:hover`)&&!n.matches(`:hover`)&&n.classList.remove(`show`)},200)}),n.querySelectorAll(`.ws-export-dropdown-item`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation();let r=e.dataset.exportType;n.classList.remove(`show`),E_(r)})}),document.addEventListener(`click`,t=>{!e.contains(t.target)&&!n.contains(t.target)&&n.classList.remove(`show`)});let a=()=>{n.classList.contains(`show`)&&S_(t,n)};document.getElementById(`workspacePreviewContent`)?.addEventListener(`scroll`,a),window.addEventListener(`resize`,a)}function T_(){return document.getElementById(`workspacePreviewArea`).dataset.markdownText||``}async function E_(e){if(x_)return;x_=!0;let t=document.getElementById(`workspacePreviewExportBtn`);document.getElementById(`workspacePreviewExportMenu`);let n=document.getElementById(`workspacePreviewExportDropdown`),i=document.getElementById(`workspacePreviewArea`).dataset.previewName||`export`,o=t.innerHTML;t.innerHTML=`<svg viewBox="0 0 24 24" fill="none" style="animation: spin 0.8s linear infinite; width: 14px; height: 14px; flex-shrink: 0;"><circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-dasharray="31.4" stroke-dashoffset="10" opacity="0.25"/><circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-dasharray="31.4" stroke-dashoffset="10"/></svg>`,t.disabled=!0,t.style.opacity=`0.6`;try{switch(e){case`docx`:await k_(i);break;case`pdf`:await j_(i);break;case`image`:await M_(i);break;case`md`:N_(i);break}}catch(e){a.error(`[WorkspacePanel] export failed:`,e),L(r(`chatExport.exportFailed`,{message:e.message}),`error`)}finally{x_=!1,t.innerHTML=o,t.disabled=!1,t.style.opacity=`1`,n.classList.remove(`show`)}}async function D_(e){if(typeof mermaid>`u`)return;let{renderMermaidInContainer:t,convertSvgsToImages:n}=await M(async()=>{let{renderMermaidInContainer:e,convertSvgsToImages:t}=await import(`./chat-export-CDzJ0eSb.js`);return{renderMermaidInContainer:e,convertSvgsToImages:t}},__vite__mapDeps([10,11,1,4,12,2,3,13,14,0]));await t(e),await n(e)}async function O_(e){if(typeof mermaid>`u`||!/```mermaid/i.test(e))return e;let{renderMermaidInContainer:t,convertSvgsToImages:n}=await M(async()=>{let{renderMermaidInContainer:e,convertSvgsToImages:t}=await import(`./chat-export-CDzJ0eSb.js`);return{renderMermaidInContainer:e,convertSvgsToImages:t}},__vite__mapDeps([10,11,1,4,12,2,3,13,14,0]));try{let r=on(e),i=document.createElement(`div`);i.style.cssText=`position:fixed;left:-9999px;top:-9999px;`,i.innerHTML=r,document.body.appendChild(i),await t(i),await n(i);let a=i.querySelectorAll(`.mermaid`),o=[];for(let e of a){let t=e.querySelector(`img`);t&&t.src&&t.src.startsWith(`data:`)?o.push(t.src):o.push(null)}if(document.body.removeChild(i),o.length===0)return e;let s=0;return e.replace(/```\s*mermaid\s*[\r\n]+([\s\S]*?)```/gi,e=>{let t=o[s];return s++,t?``:e})}catch(t){return a.warn(`[WorkspacePanel] Mermaid pre-render failed:`,t.message),e}}async function k_(e){let{Packer:t}=await M(async()=>{let{Packer:e}=await import(`./dist-BUuoW_84.js`);return{Packer:e}},__vite__mapDeps([11,1])),{createDocxDocument:n}=await M(async()=>{let{createDocxDocument:e}=await import(`./chat-export-CDzJ0eSb.js`);return{createDocxDocument:e}},__vite__mapDeps([10,11,1,4,12,2,3,13,14,0])),i=T_();if(!i){L(r(`chatExport.noContent`),`error`);return}i=await O_(i);let a=n(await A_(i)),o=await t.toBlob(a),s=`word-${new Date().getTime()}.docx`;P_(o,s),L(r(`workspace.downloaded`,{name:s}),`success`)}async function A_(e){let{Document:t,Packer:n,Paragraph:r,TextRun:i,HeadingLevel:a,Table:o,TableRow:s,TableCell:c,AlignmentType:l,WidthType:u,BorderStyle:d,ImageRun:f,ExternalHyperlink:p,convertInchesToTwip:m}=await M(async()=>{let{Document:e,Packer:t,Paragraph:n,TextRun:r,HeadingLevel:i,Table:a,TableRow:o,TableCell:s,AlignmentType:c,WidthType:l,BorderStyle:u,ImageRun:d,ExternalHyperlink:f,convertInchesToTwip:p}=await import(`./dist-BUuoW_84.js`);return{Document:e,Packer:t,Paragraph:n,TextRun:r,HeadingLevel:i,Table:a,TableRow:o,TableCell:s,AlignmentType:c,WidthType:l,BorderStyle:u,ImageRun:d,ExternalHyperlink:f,convertInchesToTwip:p}},__vite__mapDeps([11,1])),{createTextRuns:h,sanitizeDocxText:g,nextDocxImageId:_,isDocxEmbeddableImageType:v}=await M(async()=>{let{createTextRuns:e,sanitizeDocxText:t,nextDocxImageId:n,isDocxEmbeddableImageType:r}=await import(`./chat-export-CDzJ0eSb.js`);return{createTextRuns:e,sanitizeDocxText:t,nextDocxImageId:n,isDocxEmbeddableImageType:r}},__vite__mapDeps([10,11,1,4,12,2,3,13,14,0]));if(!e||!e.trim())return[new r({children:[new i({text:``})]})];let y=[],b=g(e),x=[];b=b.replace(/```(\w*)\n([\s\S]*?)```/g,(e,t,n)=>{let r=x.length;return x.push({lang:t||``,code:n.trimEnd()}),`\n\n%%CODEBLOCK_${r}%%\n\n`});let S=[];b=b.replace(/<table[\s\S]*?<\/table>/gi,e=>{let t=S.length;return S.push(e),`\n\n%%HTMLTABLE_${t}%%\n\n`});let C=[];b=b.replace(/(?:^\|.+\|\s*$\n)+^\|[\s\-:|]+\|\s*$\n(?:^\|.+\|\s*$\n?)+/gm,e=>{let t=C.length;return C.push(e),`\n\n%%MDTABLE_${t}%%\n\n`});let w=b.split(/\n{2,}/).filter(e=>e.trim());function T(e){if(!e)return[];let t=/(\*\*(.+?)\*\*|(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)|__(.+?)__|(?<!_)_(?!_)(.+?)(?<!_)_(?!_)|`([^`]+)`|\[([^\]]+)\]\(([^)]+)\)|!\[([^\]]*)\]\(([^)]+)\))/,n=[],r=e;for(;r.length>0;){let e=r.match(t);if(!e){n.push(...h(r));break}let a=e.index;a>0&&n.push(...h(r.slice(0,a)));let o=e[1];if(e[2]!==void 0)n.push(...h(e[2],{bold:!0}));else if(e[3]!==void 0)n.push(...h(e[3],{italics:!0}));else if(e[4]!==void 0)n.push(...h(e[4],{bold:!0}));else if(e[5]!==void 0)n.push(...h(e[5],{italics:!0}));else if(e[6]!==void 0)n.push(new i({text:e[6],font:`Consolas`,size:20}));else if(e[7]!==void 0)n.push(new p({children:[new i({text:e[7],style:`Hyperlink`})],link:e[8]}));else if(e[9]!==void 0){let t=e[10];if(t.startsWith(`data:`))try{let[r,a]=t.split(`,`),o=r.match(/data:(image\/(\w+))/);if(o&&a&&v(o[2])){let t=atob(a),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);n.push(new f({data:r,transformation:{width:400,height:300},type:o[2],altText:{id:_(),name:e[9]||`image`}}))}else n.push(new i({text:`[Image: `+(e[9]||`image`)+`]`,italics:!0,color:`999999`}))}catch{n.push(new i({text:`[Image]`,italics:!0,color:`999999`}))}else n.push(new i({text:`[Image: `+(e[9]||t)+`]`,italics:!0,color:`999999`}))}r=r.slice(a+o.length)}return n}function E(e){let t=new DOMParser().parseFromString(e,`text/html`),n=[];return t.querySelectorAll(`tr`).forEach(e=>{let t=[];e.querySelectorAll(`th, td`).forEach(e=>t.push(e.textContent.trim())),t.length>0&&n.push(t)}),n}function D(e){let t=e.trim().split(`
|
|
1114
|
+
`),n=[];for(let e of t){if(/^[\s\|:\-]+$/.test(e.replace(/\|/g,``)))continue;let t=Xt(e).slice(1,-1).map(e=>e.trim());t.length>0&&n.push(t)}return n}function O(e){if(e.length===0)return new r({children:[]});let t=Math.max(...e.map(e=>e.length));return new o({rows:e.map((e,n)=>{let i=[];for(let a=0;a<t;a++){let o=e[a]||``;i.push(new c({children:[new r({children:T(o),spacing:{before:40,after:40}})],shading:n===0?{fill:`F2F2F2`}:void 0,width:{size:Math.round(100/t*100)/100,type:u.PERCENTAGE}}))}return new s({children:i})}),width:{size:100,type:u.PERCENTAGE},borders:{top:{style:d.SINGLE,size:1,color:`DDDDDD`},bottom:{style:d.SINGLE,size:1,color:`DDDDDD`},left:{style:d.SINGLE,size:1,color:`DDDDDD`},right:{style:d.SINGLE,size:1,color:`DDDDDD`},insideHorizontal:{style:d.SINGLE,size:1,color:`DDDDDD`},insideVertical:{style:d.SINGLE,size:1,color:`DDDDDD`}}})}for(let e of w){let t=e.trim(),n=t.match(/^%%CODEBLOCK_(\d+)%%$/);if(n){let{lang:e,code:t}=x[parseInt(n[1])],a=e?`${e} code`:`code`;y.push(new r({children:[new i({text:a,bold:!0,font:`Consolas`,size:18})]}));let o=t.split(`
|
|
1115
1115
|
`);for(let e of o)y.push(new r({children:[new i({text:e||` `,font:`Consolas`,size:18})],spacing:{before:0,after:0,line:240},shading:{fill:`F5F5F5`}}));y.push(new r({children:[new i({text:``})]}));continue}let o=t.match(/^%%HTMLTABLE_(\d+)%%$/);if(o){let e=E(S[parseInt(o[1])]);e.length>0&&(y.push(O(e)),y.push(new r({children:[new i({text:``})]})));continue}let s=t.match(/^%%MDTABLE_(\d+)%%$/);if(s){let e=D(C[parseInt(s[1])]);y.push(O(e)),y.push(new r({children:[new i({text:``})]}));continue}let c=t.match(/^(#{1,6})\s+(.+)/);if(c){let e={1:a.HEADING_1,2:a.HEADING_2,3:a.HEADING_3,4:a.HEADING_4,5:a.HEADING_5,6:a.HEADING_6};y.push(new r({children:T(c[2]),heading:e[c[1].length]||a.HEADING_1,border:{bottom:{style:d.SINGLE,size:6,color:`EAECEF`}}}));let n=t.slice(c[0].length).replace(/^\n+/,``).trim();n&&y.push(new r({children:T(n),spacing:{before:60,after:60}}));continue}if(/^(---|\*\*\*|___)\s*$/.test(t)){y.push(new r({children:[],border:{bottom:{style:d.SINGLE,size:6,color:`CCCCCC`}},spacing:{before:200,after:200}}));continue}if(/^[\-\*\+]\s+/.test(t)){let t=e.split(/\n(?=[\-\*\+]\s+)/);for(let e of t)y.push(new r({children:T(e.replace(/^[\-\*\+]\s+/,``)),bullet:{level:0},spacing:{before:40,after:40}}));continue}if(/^\d+\.\s+/.test(t)){let t=e.split(/\n(?=\d+\.\s+)/);for(let e of t)y.push(new r({children:T(e.replace(/^\d+\.\s+/,``)),numbering:{reference:`default`,level:0},spacing:{before:40,after:40}}));continue}if(t.startsWith(`>`)){let t=e.split(`
|
|
1116
1116
|
`).map(e=>e.replace(/^>\s?/,``)).join(`
|
|
1117
1117
|
`);y.push(new r({children:T(t),indent:{left:m(.5)},border:{left:{style:d.SINGLE,size:12,color:`CCCCCC`}},spacing:{before:60,after:60}}));continue}let l=T(t);y.push(new r({children:l.length>0?l:h(t),spacing:{before:60,after:60}}))}return y}async function j_(e){let{jsPDF:t,html2canvas:n}=await Zt();if(!t||!n){L(r(`chatExport.pdfLibNotLoaded`),`error`);return}let i=T_();if(!i){L(r(`chatExport.noContent`),`error`);return}let o=document.createElement(`div`);o.style.cssText=`position:fixed;left:-9999px;top:-9999px;width:515px;padding:40px;background:white;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI','PingFang SC','Hiragino Sans GB','Microsoft YaHei',sans-serif;font-size:12px;line-height:1.6;color:#333;box-sizing:border-box;`,o.innerHTML=`<div class="markdown-body">${on(i)}</div>`,document.body.appendChild(o),await D_(o);let s=o.scrollHeight,c=Math.ceil(s/762);n(o,{scale:2,useCORS:!0,logging:!1,backgroundColor:`#ffffff`,willReadFrequently:!0}).then(e=>{let n=new t({orientation:`portrait`,unit:`px`,format:[595,842],compress:!0}),i=e.width,a=e.height,l=a/s,u=762*l;for(let t=0;t<c;t++){t>0&&n.addPage();let r=t*u,o=Math.min(r+u,a)-r,s=document.createElement(`canvas`);s.width=i,s.height=o;let c=s.getContext(`2d`,{willReadFrequently:!0});c.fillStyle=`#ffffff`,c.fillRect(0,0,s.width,s.height),c.drawImage(e,0,r,i,o,0,0,i,o);let d,f;try{d=s.toDataURL(`image/jpeg`,.85),f=`JPEG`}catch{d=s.toDataURL(`image/png`),f=`PNG`}let p=o/l;n.addImage(d,f,0,0,595,p,void 0,`FAST`)}let d=`pdf-${new Date().getTime()}.pdf`;n.save(d),document.body.removeChild(o),L(r(`workspace.downloaded`,{name:d}),`success`)}).catch(e=>{a.error(`[WorkspacePanel] PDF export failed:`,e),L(r(`chatExport.exportFailed`,{message:e.message}),`error`),document.body.removeChild(o)})}async function M_(e){let t=await en();if(!t){L(r(`chatExport.imageLibNotLoaded`),`error`);return}let n=document.getElementById(`workspacePreviewContent`).querySelector(`.workspace-preview-markdown`);if(!n){L(r(`chatExport.noContent`),`error`);return}let i=n.cloneNode(!0),o=document.createElement(`div`);o.style.cssText=`position:fixed;left:-9999px;top:-9999px;width:800px;padding:40px;background:white;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Hiragino Sans GB","Microsoft YaHei",sans-serif;font-size:14px;line-height:1.6;color:#333;box-sizing:border-box;`,o.appendChild(i),document.body.appendChild(o),await D_(o),await new Promise(e=>requestAnimationFrame(()=>requestAnimationFrame(e)));try{let e=(await t(o,{scale:2,useCORS:!0,logging:!1,backgroundColor:`#ffffff`,willReadFrequently:!0})).toDataURL(`image/jpeg`,.92),n=document.createElement(`a`);n.href=e;let i=`image-${new Date().getTime()}.jpg`;n.download=i,document.body.appendChild(n),n.click(),document.body.removeChild(n),L(r(`workspace.downloaded`,{name:i}),`success`)}catch(e){a.error(`[WorkspacePanel] image export failed:`,e),L(r(`chatExport.exportFailed`,{message:e.message}),`error`)}finally{document.body.removeChild(o)}}function N_(e){let t=T_();if(!t){L(r(`chatExport.noContent`),`error`);return}let n=t.replace(/\r\n/g,`
|
|
@@ -1140,7 +1140,7 @@ It is this session's directory or the agent default, so it stays accessible (wor
|
|
|
1140
1140
|
</style>
|
|
1141
1141
|
</head><body>${e}</body></html>`}async function R_(){let e=document.getElementById(`workspacePreviewArea`),t=e.dataset.previewPath,n=e.dataset.previewName;t&&await $_(t,n)}async function z_(){let e=document.getElementById(`workspacePreviewArea`).dataset.previewPath;if(e)try{let t=await On(e);if(!t.success){L(r(`workspace.requestFailed`,{error:t.error}),`error`);return}let n=URL.createObjectURL(t.blob);window.open(n,`_blank`),setTimeout(()=>URL.revokeObjectURL(n),6e4),L(r(`workspace.openInBrowser`),`success`)}catch(e){L(r(`workspace.openFailed`,{error:e.message}),`error`)}}function B_(e,t){let n=e.querySelector(`.workspace-preview-md-icon-preview`),r=e.querySelector(`.workspace-preview-md-icon-source`);n&&(n.style.display=t?`none`:``),r&&(r.style.display=t?``:`none`)}function V_(){let e=document.getElementById(`workspacePreviewArea`),t=document.getElementById(`workspacePanel`),n=document.getElementById(`workspacePreviewFullscreenBtn`),i=e.classList.toggle(`fullscreen`);if(pr(),i)t.classList.add(`preview-fullscreen`),n.innerHTML=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="14" height="14"><path d="M8 3v3a2 2 0 0 1-2 2H3m18 0h-3a2 2 0 0 1-2-2V3m0 18v-3a2 2 0 0 1 2-2h3M3 16h3a2 2 0 0 1 2 2v3"/></svg>`,n.title=r(`workspace.exitFullscreen`);else{t.classList.remove(`preview-fullscreen`),n.innerHTML=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="14" height="14"><path d="M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"/></svg>`,n.title=r(`workspace.fullscreenPreview`);let e=document.getElementById(`workspacePreviewRail`);e&&e.querySelectorAll(`.message-toc-container`).forEach(e=>e.remove())}}function H_(){let e=document.getElementById(`workspacePreviewArea`),t=document.getElementById(`workspacePreviewContent`),n=document.getElementById(`workspacePreviewMdToggleBtn`),i=document.getElementById(`workspacePreviewLineCount`),a=document.getElementById(`workspacePreviewCopyBtn`),o=document.getElementById(`workspacePreviewDownloadBtn`),s=document.getElementById(`workspacePreviewExportMenu`);pr();let c=t.classList.toggle(`markdown-rendered`),l=e.dataset.markdownText||``;if(c)n.classList.add(`active`),n.title=r(`workspace.switchToSourcePreview`),B_(n,!0),a.style.display=``,o&&(o.style.display=`none`),s&&(s.style.display=``),t.innerHTML=`<div class="markdown-body workspace-preview-markdown">${on(l)}</div>`,W_(t),G_(t),an(),i.textContent=``;else{n.classList.remove(`active`),n.title=r(`workspace.switchToRenderPreview`),B_(n,!1),a.style.display=``,o&&(o.style.display=``),s&&(s.style.display=`none`);let c=Cv(e.dataset.previewName||``),u=(l||``).split(`
|
|
1142
1142
|
`);i.textContent=r(`workspace.lineCount`,{count:u.length});let d=`<table class="workspace-preview-code-table"><tbody>`;for(let e=0;e<u.length;e++)d+=`<tr><td class="line-num">${e+1}</td><td class="line-content"><code class="${c}">${J(u[e])}</code></td></tr>`;d+=`</tbody></table>`,t.innerHTML=d}U_(c)}function U_(e){let t=document.getElementById(`workspacePreviewCopyBtn`);t&&(e?t.title=r(`workspace.copyAllTitle`)+`
|
|
1143
|
-
`+r(`workspace.copyMarkdownHint`):t.title=r(`workspace.copyAllTitle`))}async function W_(e){if(typeof mermaid>`u`)return;let t=e.querySelectorAll(`.mermaid`);for(let e of t){if(e.querySelector(`svg`))continue;let t=e.getAttribute(`data-raw-code`),n=t?decodeURIComponent(t):e.textContent||``;try{await mermaid.run({nodes:[e]}),typeof tn==`function`&&tn(e)}catch{e.textContent=n}}}function G_(e){e.querySelectorAll(`.code-copy-btn`).forEach(e=>{e.dataset.bound||(e.dataset.bound=`true`,e.addEventListener(`click`,t=>{t.stopPropagation();let n=e.closest(`.code-block-container`);if(n){let t=n.querySelector(`pre code`);t&&
|
|
1143
|
+
`+r(`workspace.copyMarkdownHint`):t.title=r(`workspace.copyAllTitle`))}async function W_(e){if(typeof mermaid>`u`)return;let t=e.querySelectorAll(`.mermaid`);for(let e of t){if(e.querySelector(`svg`))continue;let t=e.getAttribute(`data-raw-code`),n=t?decodeURIComponent(t):e.textContent||``;try{await mermaid.run({nodes:[e]}),typeof tn==`function`&&tn(e)}catch{e.textContent=n}}}function G_(e){e.querySelectorAll(`.code-copy-btn`).forEach(e=>{e.dataset.bound||(e.dataset.bound=`true`,e.addEventListener(`click`,t=>{t.stopPropagation();let n=e.closest(`.code-block-container`);if(n){let t=n.querySelector(`pre code`);t&&At(t.textContent||``,e)}}))}),e.dataset.ctrlClickBound||(e.dataset.ctrlClickBound=`true`,e.addEventListener(`click`,e=>{if(!e.ctrlKey&&!e.metaKey||e.button!==0)return;let t=e.target.closest(`code`);if(!t){let n=e.target.closest(`pre`);if(n&&(t=n.querySelector(`code`)),!t){let n=e.target.closest(`.code-block-container`);n&&(t=n.querySelector(`code`))}}if(!t||e.target.closest(`.code-copy-btn`))return;e.preventDefault();let n=t.textContent;n&&navigator.clipboard.writeText(n).then(()=>{L(r(`workspace.codeCopiedToClipboard`),`success`)}).catch(()=>{let e=document.createElement(`textarea`);e.value=n,e.style.position=`fixed`,e.style.left=`-999999px`,document.body.appendChild(e),e.select(),document.execCommand(`copy`),document.body.removeChild(e),L(r(`workspace.codeCopiedToClipboard`),`success`)})}))}async function K_(e=!1){let t=document.getElementById(`workspacePreviewArea`);if(!e&&t.dataset.editMode===`true`&&t.classList.contains(`has-unsaved`)&&!await Z_(r(`workspace.actionClosePreview`)))return!1;X_(!1),Ch&&=(Ch.abort(),null);let n=document.getElementById(`workspacePanel`),i=document.getElementById(`workspacePreviewContent`);i.classList.remove(`xlsx-mode`),i.classList.remove(`markdown-rendered`),delete t.dataset.markdownText;let a=document.getElementById(`workspacePreviewMdToggleBtn`);if(a&&(a.classList.remove(`active`),a.style.display=`none`,B_(a,!1)),t.classList.contains(`fullscreen`)){t.classList.remove(`fullscreen`),n.classList.remove(`preview-fullscreen`);let e=document.getElementById(`workspacePreviewFullscreenBtn`);e&&(e.innerHTML=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="14" height="14"><path d="M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"/></svg>`,e.title=r(`workspace.fullscreenPreview`))}pr();let o=document.getElementById(`workspacePreviewRail`);o&&o.querySelectorAll(`.message-toc-container`).forEach(e=>e.remove()),Ig&&=(Ig.destroy(),null),Lg=1,zg=1,y_&&=(URL.revokeObjectURL(y_),null);let s=document.getElementById(`workspacePreviewExportMenu`);s&&(s.style.display=`none`);let c=document.getElementById(`workspacePreviewCopyBtn`);return c&&(c.title=r(`workspace.copyAllTitle`)),t.style.display=`none`,document.getElementById(`workspacePreviewContent`).innerHTML=``,Sh&&(Sh=!1,Iv(!1)),!0}function q_(){let e=document.getElementById(`workspacePreviewArea`),t=document.getElementById(`workspacePreviewContent`),n=document.getElementById(`workspacePreviewEditBtn`),i=document.getElementById(`workspacePreviewSaveBtn`),a=document.getElementById(`workspacePreviewCancelBtn`),o=document.getElementById(`workspacePreviewCopyBtn`),s=document.getElementById(`workspacePreviewDownloadBtn`),c=document.getElementById(`workspacePreviewMdToggleBtn`);document.getElementById(`workspacePreviewFullscreenBtn`);let l=document.getElementById(`workspacePreviewLineCount`),u=document.getElementById(`workspacePreviewFilename`),d=e.dataset.origContent||``;e.dataset.editMode=`true`,i.title=r(`workspace.saveChanges`),i.disabled=!1,o.style.display=`none`,s.style.display=`none`,c.style.display=`none`,n.style.display=`none`;let f=document.getElementById(`workspacePreviewExportMenu`);f&&(f.style.display=`none`),i.style.display=``,a.style.display=``,t.innerHTML=`<textarea class="workspace-preview-editor" id="workspacePreviewEditor" spellcheck="false"></textarea>`;let p=t.querySelector(`#workspacePreviewEditor`);p.value=d,p.focus(),p.setSelectionRange(p.value.length,p.value.length),l.textContent=r(`workspace.lineCount`,{count:d.split(`
|
|
1144
1144
|
`).length}),u.classList.add(`modified`),u.textContent=(e.dataset.previewName||``)+` *`,p.addEventListener(`input`,()=>{p.value===d?(e.classList.remove(`has-unsaved`),l.textContent=r(`workspace.lineCount`,{count:p.value.split(`
|
|
1145
1145
|
`).length})):(e.classList.add(`has-unsaved`),l.textContent=r(`workspace.linesModified`,{count:p.value.split(`
|
|
1146
1146
|
`).length}))})}async function J_(){let e=document.getElementById(`workspacePreviewArea`),t=document.getElementById(`workspacePreviewEditor`);if(!t)return;let n=e.dataset.previewPath,i=t.value;if(i===(e.dataset.origContent||``)){Y_();return}let o=document.getElementById(`workspacePreviewSaveBtn`),s=o.title;o.title=r(`workspace.saving`),o.disabled=!0;try{let t=await dn(n,i);if(t.success){a.info(`[WorkspacePanel] file save successful:`,n),L(r(`workspace.saveSuccess`)),e.dataset.origContent=i,X_(!1);let t=e.dataset.previewName;await Fg(n,t)}else a.error(`[WorkspacePanel] filesave failed:`,n,t.error),L(r(`workspace.saveFailedWithError`,{error:t.error||r(`workspace.unknownError`)})),o.title=s,o.disabled=!1}catch(e){a.error(`[WorkspacePanel] file saveexception:`,n,e),L(r(`workspace.saveFailedWithError`,{error:e.message||e})),o.title=s,o.disabled=!1}}async function Y_(){let e=document.getElementById(`workspacePreviewArea`);if(e.classList.contains(`has-unsaved`)&&!await Z_(r(`workspace.actionCancelEdit`)))return;X_(!0);let t=e.dataset.previewPath,n=e.dataset.previewName;t&&n&&await Fg(t,n)}function X_(e){let t=document.getElementById(`workspacePreviewArea`),n=document.getElementById(`workspacePreviewFilename`),r=document.getElementById(`workspacePreviewSaveBtn`),i=document.getElementById(`workspacePreviewCancelBtn`);delete t.dataset.editMode,t.classList.remove(`has-unsaved`),n.classList.remove(`modified`),r.style.display=`none`,i.style.display=`none`}async function Z_(e){return typeof window.showCustomConfirm==`function`?await window.showCustomConfirm(r(`workspace.discardChangesPrompt`,{action:e}),r(`workspace.unsavedChanges`)):window.confirm(r(`workspace.discardChangesPrompt`,{action:e}))}function Q_(e){let t=document.getElementById(`workspacePreviewArea`);if(t.style.display===`none`)return;if(t.dataset.editMode===`true`){(e.ctrlKey||e.metaKey)&&e.key===`s`&&(e.preventDefault(),J_()),e.key===`Escape`&&(e.preventDefault(),Y_());return}let n=(e.target?.tagName||``).toLowerCase();if(n===`input`||n===`textarea`||e.target?.isContentEditable)return;let r=t.dataset.previewType;if(!(r!==`pdf`&&r!==`pptx`)){if(e.key===`ArrowLeft`){e.preventDefault();let t=document.getElementById(r===`pdf`?`pdfPrevPage`:`pptxPrevSlide`);t&&!t.disabled&&t.click()}else if(e.key===`ArrowRight`){e.preventDefault();let t=document.getElementById(r===`pdf`?`pdfNextPage`:`pptxNextSlide`);t&&!t.disabled&&t.click()}}}async function $_(e,t){if(yh)return;yh=!0,iv(!0);let n=ov(e),i=new AbortController,a=[],o=()=>{if(a.length<2)return 0;let e=a[0],t=a[a.length-1],n=(t.time-e.time)/1e3;return n<=0?0:(t.loaded-e.loaded)/n},s=uv(()=>i.abort());s.classList.add(`download-mode`),dv(s,{percent:0,fileName:t,loaded:0,totalBytes:0,speed:0});try{let c=await Sn(e,({loaded:e,total:r,percent:i})=>{sv(n,i);let c=Date.now();a.push({time:c,loaded:e}),a.length>8&&a.shift(),dv(s,{percent:i,fileName:t,loaded:e,totalBytes:r,speed:o()})},i.signal);if(c.aborted){fv(s,r(`workspace.downloadCanceled`),!0),L(r(`workspace.downloadCanceled`),`info`);return}if(!c.success){fv(s,r(`workspace.downloadFailed`),!0),L(r(`workspace.downloadFailedWithError`,{error:c.error}),`error`);return}tv(c.blob,c.name||t),dv(s,{percent:100,fileName:t,loaded:c.blob.size,totalBytes:c.blob.size,speed:0,statusText:r(`workspace.savingToLocal`)}),setTimeout(()=>{fv(s,r(`workspace.savedToLocal`),!1)},1500),L(r(`workspace.downloaded`,{name:c.name||t}),`success`)}catch(e){e.name===`AbortError`?(fv(s,r(`workspace.downloadCanceled`),!0),L(r(`workspace.downloadCanceled`),`info`)):(fv(s,r(`workspace.downloadFailed`),!0),L(r(`workspace.downloadFailedWithError`,{error:e.message}),`error`))}finally{setTimeout(()=>cv(n),600),yh=!1,iv(!1)}}async function ev(){if(q.size===0||yh)return;let e=Array.from(q);if(e.length===1){let t=e[0].split(/[\\/]/).pop();await $_(e[0],t);return}yh=!0,iv(!0);let t=new AbortController,n=[],i=()=>{if(n.length<2)return 0;let e=n[0],t=n[n.length-1],r=(t.time-e.time)/1e3;return r<=0?0:(t.loaded-e.loaded)/r},a=r(`workspace.fileCount`,{count:e.length}),o=uv(()=>t.abort());o.classList.add(`download-mode`),dv(o,{percent:0,fileName:a,loaded:0,totalBytes:0,speed:0});try{let s=await En(e,({loaded:e,total:t,percent:r})=>{let s=Date.now();n.push({time:s,loaded:e}),n.length>8&&n.shift(),dv(o,{percent:r,fileName:a,loaded:e,totalBytes:t,speed:i()})},t.signal);if(s.aborted){fv(o,r(`workspace.downloadCanceled`),!0),L(r(`workspace.downloadCanceled`),`info`);return}s.success&&s.blob?(tv(s.blob,s.name||`workspace.zip`),fv(o,r(`workspace.downloadedCount`,{count:e.length}),!1),L(r(`workspace.downloadedZip`,{count:e.length}),`success`)):(fv(o,r(`workspace.downloadFailed`),!0),L(r(`workspace.downloadFailedWithError`,{error:s.error||r(`workspace.unknownError`)}),`error`))}catch(e){e.name===`AbortError`?(fv(o,r(`workspace.downloadCanceled`),!0),L(r(`workspace.downloadCanceled`),`info`)):(fv(o,r(`workspace.downloadFailed`),!0),L(r(`workspace.downloadFailedWithError`,{error:e.message}),`error`))}finally{yh=!1,iv(!1)}}function tv(e,t){let n=URL.createObjectURL(e),r=document.createElement(`a`);r.href=n,r.download=t,document.body.appendChild(r),r.click(),document.body.removeChild(r),setTimeout(()=>URL.revokeObjectURL(n),6e4)}function nv(){let e=document.getElementById(`workspaceFileInput`);e&&e.click()}async function rv(e){let t=e.target.files;if(!t||t.length===0)return;let n=Array.from(t);e.target.value=``,await mv(n)}function iv(e){document.querySelectorAll(`.workspace-file-btn.download`).forEach(t=>{t.disabled=e});let t=document.getElementById(`workspaceDownloadDirBtn`);t&&(t.disabled=e||q.size===0);let n=document.getElementById(`workspacePreviewDownloadBtn`);n&&(n.disabled=e)}var av=new Map;function ov(e){return av.set(e,0),lv(),e}function sv(e,t){if(!e)return;let n=e;av.set(n,t);let r=Array.from(document.querySelectorAll(`.workspace-file-item`)).find(e=>e.dataset.path===n);if(r){let e=r.querySelector(`.workspace-file-progress`);e||(e=document.createElement(`div`),e.className=`workspace-file-progress`,e.innerHTML=`<div class="workspace-file-progress-bar"></div>`,r.appendChild(e));let n=e.querySelector(`.workspace-file-progress-bar`);n&&(n.style.width=t+`%`)}}function cv(e){if(!e)return;let t=e;av.delete(t);let n=Array.from(document.querySelectorAll(`.workspace-file-item`)).find(e=>e.dataset.path===t);if(n){let e=n.querySelector(`.workspace-file-progress`);e&&e.remove()}}function lv(){for(let[e,t]of av){let n=Array.from(document.querySelectorAll(`.workspace-file-item`)).find(t=>t.dataset.path===e);if(n&&!n.querySelector(`.workspace-file-progress`)){let e=document.createElement(`div`);e.className=`workspace-file-progress`,e.innerHTML=`<div class="workspace-file-progress-bar" style="width:${t}%"></div>`,n.appendChild(e)}}}function uv(e){let t=document.createElement(`div`);t.className=`workspace-upload-progress`,t.innerHTML=`
|
|
@@ -1160,7 +1160,7 @@ It is this session's directory or the agent default, so it stays accessible (wor
|
|
|
1160
1160
|
<span class="workspace-upload-progress-bytes"></span>
|
|
1161
1161
|
<span class="workspace-upload-progress-speed"></span>
|
|
1162
1162
|
</div>
|
|
1163
|
-
`,document.body.appendChild(t);let n=t.querySelector(`.workspace-upload-progress-cancel`);return n&&n.addEventListener(`click`,()=>{n.style.display=`none`,typeof e==`function`&&e()}),t}function dv(e,t){if(!e)return;let{percent:n,completed:i,total:a,fileName:o,loaded:s,totalBytes:c,speed:l,statusText:u}=t,d=e.querySelector(`.workspace-upload-progress-title`),f=e.querySelector(`.workspace-upload-progress-file`),p=e.querySelector(`.workspace-upload-progress-bar`),m=e.querySelector(`.workspace-upload-progress-bytes`),h=e.querySelector(`.workspace-upload-progress-speed`),g=e.classList.contains(`download-mode`)?r(`workspace.downloadInProgress`):r(`workspace.uploadInProgress`);d&&(u?d.textContent=u:i!=null&&a!=null?d.textContent=`${g} ${i}/${a} · ${n}%`:d.textContent=`${g} ${n}%`),f&&o&&(f.textContent=o,f.title=o),p&&(p.style.width=n+`%`),m&&(s!=null&&c!=null&&c>0?m.textContent=`${kn(s)} / ${kn(c)}`:s!=null&&(m.textContent=kn(s))),h&&(h.textContent=l>0?`${kn(l)}/s`:``)}function fv(e,t,n){if(!e)return;let r=e.querySelector(`.workspace-upload-progress-title`),i=e.querySelector(`.workspace-upload-progress-cancel`),a=e.querySelector(`.workspace-upload-progress-bar`);i&&(i.style.display=`none`),r&&(r.textContent=t),a&&!n&&(a.style.width=`100%`),e.classList.add(`workspace-upload-progress-done`),n&&e.classList.add(`workspace-upload-progress-error`),setTimeout(()=>{try{e.remove()}catch{}},1500)}function pv(e){let t=document.getElementById(`workspaceUploadBtn`);t&&(t.disabled=e,e?(t.dataset.originalHtml=t.innerHTML,t.innerHTML=`<span class="workspace-upload-spinner"></span>`):t.dataset.originalHtml&&(t.innerHTML=t.dataset.originalHtml,delete t.dataset.originalHtml));let n=document.getElementById(`workspacePanel`);n&&n.classList.toggle(`upload-in-progress`,e)}async function mv(e){let t=Array.from(e);if(t.length===0||bh)return;bh=!0,pv(!0);let n=await Cn();if(!n){L(r(`workspace.agentNotConnectedUpload`),`error`),bh=!1,pv(!1);return}let i=new Set;try{let e=await mn(K);e.success&&Array.isArray(e.entries)&&(i=new Set(e.entries.map(e=>e.name)))}catch{}let a=0,o=0,s=0,c=t.reduce((e,t)=>e+t.size,0),l=Array(t.length).fill(0),u=new Set,d=!1,f=``,p=[],m=()=>{if(p.length<2)return 0;let e=p[0],t=p[p.length-1],n=(t.time-e.time)/1e3;return n<=0?0:(t.loaded-e.loaded)/n},h=uv(()=>{d=!0;for(let e of u)try{e.abort()}catch{}u.clear()}),g=e=>{e&&(f=e);let n=l.reduce((e,t)=>e+t,0),r=c>0?Math.round(n/c*100):0,i=Date.now();p.push({time:i,loaded:n}),p.length>8&&p.shift(),dv(h,{percent:r,completed:a+o+s,total:t.length,fileName:f,loaded:n,totalBytes:c,speed:m()})};g();for(let e=0;e<t.length&&!d;e+=3){let c=t.slice(e,e+3),f=await Promise.allSettled(c.map(async(t,a)=>{let o=e+a,s=kh(t.name),c=ng(`${K}/${s}`);if(i.has(s))throw l[o]=t.size,g(s),Error(`__SKIPPED__`);if(d)throw Error(`__CANCELLED__`);await new Promise((e,i)=>{let a=new XMLHttpRequest;u.add(a);let s=`${n.url}/api/fs/upload-stream?path=${encodeURIComponent(c)}`;a.open(`POST`,s);for(let[e,t]of Object.entries(An(n)))a.setRequestHeader(e,t);a.upload.onprogress=e=>{e.lengthComputable&&(l[o]=e.loaded,g(t.name))},a.onload=()=>{if(u.delete(a),d){i(Error(`__CANCELLED__`));return}if(a.status>=200&&a.status<300)try{let n=JSON.parse(a.responseText);n.success?(l[o]=t.size,g(t.name),e()):i(Error(n.error||r(`workspace.uploadFailed`)))}catch{i(Error(r(`workspace.parseResponseFailed`)))}else try{let e=JSON.parse(a.responseText);i(Error(e.error||r(`workspace.uploadFailedWithStatus`,{status:a.status})))}catch{i(Error(r(`workspace.uploadFailedWithStatus`,{status:a.status})))}},a.onerror=()=>{u.delete(a),i(Error(d?`__CANCELLED__`:r(`workspace.networkError`)))},a.onabort=()=>{u.delete(a),i(Error(`__CANCELLED__`))},a.send(t)})}));for(let e of f)if(e.status===`fulfilled`)a++;else{let t=e.reason&&e.reason.message?e.reason.message:``;t.includes(`__SKIPPED__`)||t.includes(`已存在`)?o++:t.includes(`__CANCELLED__`)||s++}}let _,v=!1;if(d)_=r(`workspace.uploadCanceled`),v=!0;else{let e=[];a>0&&e.push(r(`workspace.uploadSuccessCount`,{count:a})),o>0&&e.push(r(`workspace.uploadSkippedCount`,{count:o})),s>0&&e.push(r(`workspace.uploadFailedCount`,{count:s})),_=e.length>0?r(`workspace.uploadCompleteWithStats`,{stats:e.join(` / `)}):r(`workspace.uploadComplete`),v=s>0}fv(h,_,v),a>0&&L(r(`workspace.uploadedFiles`,{count:a}),`success`),o>0&&L(r(`workspace.filesSkipped`,{count:o}),`info`),s>0&&L(r(`workspace.filesUploadFailed`,{count:s}),`error`),d&&L(r(`workspace.uploadCanceled`),`info`),bh=!1,pv(!1),a>0&&(await yv(),fy(t[t.length-1].name))}function hv(){let e=document.getElementById(`workspacePanel`);if(!e)return;let t=document.getElementById(`workspacePanelContent`);t.addEventListener(`dragstart`,e=>{let t=e.target.closest(`.workspace-file-item`);if(!t)return;let n=t.dataset.path,r=t.dataset.name;e.dataTransfer.setData(`application/x-workspace-move`,JSON.stringify({path:n,name:r})),e.dataTransfer.effectAllowed=`move`,t.classList.add(`dragging`);let i=()=>{t.classList.remove(`dragging`),t.removeEventListener(`dragend`,i)};t.addEventListener(`dragend`,i)}),t.addEventListener(`dragover`,n=>{n.preventDefault(),n.stopPropagation();let r=n.target.closest(`.workspace-file-item.directory`);t.querySelectorAll(`.workspace-file-item.directory.drop-target`).forEach(e=>e.classList.remove(`drop-target`)),r?(n.dataTransfer.dropEffect=n.dataTransfer.types.includes(`application/x-workspace-move`)?`move`:`copy`,r.classList.add(`drop-target`),e.classList.remove(`drag-over`)):n.dataTransfer.types.includes(`application/x-workspace-move`)||e.classList.add(`drag-over`)}),t.addEventListener(`dragleave`,n=>{n.preventDefault(),n.stopPropagation(),t.querySelectorAll(`.workspace-file-item.directory.drop-target`).forEach(e=>e.classList.remove(`drop-target`)),e.classList.remove(`drag-over`)}),t.addEventListener(`drop`,async n=>{n.preventDefault(),n.stopPropagation();let i=n.target.closest(`.workspace-file-item.directory`);if(t.querySelectorAll(`.workspace-file-item.directory.drop-target`).forEach(e=>e.classList.remove(`drop-target`)),e.classList.remove(`drag-over`),i&&n.dataTransfer.types.includes(`application/x-workspace-move`)){try{let e=JSON.parse(n.dataTransfer.getData(`application/x-workspace-move`)),t=e.path,a=i.dataset.path,o=e.name,s=ng(t),c=ng(a);if(s===c)return;if(s.startsWith(c+`/`)){L(r(`workspace.cannotMoveToSubdir`),`error`);return}L(r(`workspace.moving`),`info`);let l=await Mn(t,a);if(l.success){L(r(`workspace.movedToDir`,{name:o}),`success`),rg(K),rg(a);let e=a.split(/[\\/]/).pop();await yv(),fy(e)}else L(r(`workspace.moveFailed`,{error:l.error}),`error`)}catch(e){L(r(`workspace.moveFailed`,{error:e.message}),`error`)}return}if(i&&n.dataTransfer.files&&n.dataTransfer.files.length>0){let e=i.dataset.path;e.split(/[\\/]/).pop(),Oh(K),K=e,await mv(n.dataTransfer.files),bv(),xv();return}if(n.dataTransfer.files&&n.dataTransfer.files.length>0){await mv(n.dataTransfer.files);return}}),e.addEventListener(`dragover`,t=>{t.preventDefault(),t.stopPropagation(),!t.dataTransfer.types.includes(`application/x-workspace-move`)&&e.classList.add(`drag-over`)}),e.addEventListener(`dragleave`,t=>{t.preventDefault(),t.stopPropagation(),!t.dataTransfer.types.includes(`application/x-workspace-move`)&&e.classList.remove(`drag-over`)}),e.addEventListener(`drop`,async t=>{if(t.preventDefault(),t.stopPropagation(),t.dataTransfer.types.includes(`application/x-workspace-move`))return;e.classList.remove(`drag-over`);let n=t.dataTransfer.files;!n||n.length===0||await mv(n)})}async function gv(){try{let e=document.getElementById(`workspaceAgentName`);if(!e)return;let t=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),n=t.pairedAgents||[],r=t.activeAgentId;if(r){let t=n.find(e=>e.id===r);if(t&&t.name){e.textContent=` · ${t.name}`,e.style.display=``;return}}e.textContent=``,e.style.display=`none`}catch(e){a.debug(`[WorkspacePanel] update agentname failed:`,e)}}async function _v(e,t){if(t===`local`&&!(!e.pairedAgents&&!e.activeAgentId)&&(await gv(),e.activeAgentId?.newValue!==e.activeAgentId?.oldValue)){a.debug(`[WorkspacePanel] Agent changed,refreshworking directory`),ln(),rh=null,K=null,ih=[],q.clear(),Lv=``,Rv=[],zv=!1,Xh.clear();let e=document.getElementById(`workspacePanel`);e&&e.classList.contains(`expanded`)&&await Jh()}}async function vv(){if(ih.length===0)return;let e=ih.pop();q.clear(),await Yh(e)}async function yv(e){if(!K){let e=rh||await bn();if(!e){L(r(`workspace.refreshFailed`),`error`);return}rh=e,K=e}if(rg(K),q.clear(),my(),zv&&Lv?(Rv=await Nn(K,Lv),dg()):await tg(K),K_(),Sg(),e!==void 0){let t=document.getElementById(`workspacePanelContent`);t&&requestAnimationFrame(()=>{t.scrollTop=e})}}function bv(){let e=document.getElementById(`workspaceBreadcrumb`);if(!K){e.innerHTML=``;return}let t=ng(K).split(`/`).filter(Boolean),n=rh?ng(rh).replace(/\/$/,``):null,i=``,a=``;for(let e=0;e<t.length;e++){a=e===0?/^[a-zA-Z]:$/.test(t[e])?t[e]+`/`:`/`+t[e]:(a.endsWith(`/`)?a:a+`/`)+t[e];let r=e===t.length-1,o=!n||a===n||a.startsWith(n+`/`);e>0&&(i+=`<span class="workspace-breadcrumb-sep">/</span>`),r?i+=`<span class="workspace-breadcrumb-current">${J(t[e])}</span>`:o?i+=`<span class="workspace-breadcrumb-link" data-path="${J(a)}">${J(t[e])}</span>`:i+=`<span class="workspace-breadcrumb-disabled">${J(t[e])}</span>`}e.innerHTML=i||`<span class="workspace-breadcrumb-current">/</span>`,e.querySelectorAll(`.workspace-breadcrumb-link`).forEach(e=>{e.addEventListener(`click`,async t=>{t.stopPropagation();let n=e.dataset.path,r=ih.findIndex(e=>e===n);ih=r>=0?ih.slice(0,r):[],q.clear(),await Yh(n)}),e.addEventListener(`dragover`,t=>{t.dataTransfer.types.includes(`application/x-workspace-move`)&&(t.preventDefault(),t.stopPropagation(),t.dataTransfer.dropEffect=`move`,e.classList.add(`drop-target`))}),e.addEventListener(`dragleave`,t=>{t.preventDefault(),t.stopPropagation(),e.classList.remove(`drop-target`)}),e.addEventListener(`drop`,async t=>{if(t.preventDefault(),t.stopPropagation(),e.classList.remove(`drop-target`),t.dataTransfer.types.includes(`application/x-workspace-move`))try{let n=JSON.parse(t.dataTransfer.getData(`application/x-workspace-move`)),i=n.path,a=e.dataset.path,o=n.name,s=ng(i),c=ng(a);if(s===c)return;if(c.startsWith(s+`/`)){L(r(`workspace.cannotMoveToSubdir`),`error`);return}L(r(`workspace.moving`),`info`);let l=await Mn(i,a);l.success?(L(r(`workspace.movedToTarget`,{name:o,target:a.split(/[\\/]/).pop()}),`success`),rg(K),rg(a),await yv()):L(r(`workspace.moveFailed`,{error:l.error}),`error`)}catch(e){L(r(`workspace.moveFailed`,{error:e.message}),`error`)}})})}function xv(){let e=document.getElementById(`workspaceBackBtn`);e.disabled=!(rh&&K&&K!==rh)}function Sv(e){let t=document.getElementById(`workspacePanelContent`);t.innerHTML=`<div class="workspace-panel-error">${J(e)}</div>`}function J(e){return e?String(e).replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`):``}function Cv(e){let t=(e.split(`.`).pop()||``).toLowerCase(),n={js:`javascript`,mjs:`javascript`,ts:`typescript`,jsx:`jsx`,tsx:`tsx`,html:`html`,htm:`html`,css:`css`,scss:`scss`,less:`less`,json:`json`,xml:`xml`,yaml:`yaml`,yml:`yaml`,py:`python`,java:`java`,c:`c`,cpp:`cpp`,h:`c`,go:`go`,rs:`rust`,rb:`ruby`,php:`php`,sql:`sql`,sh:`bash`,bash:`bash`,zsh:`bash`,md:`markdown`,vue:`html`,svelte:`html`};return n[t]?`language-${n[t]}`:``}async function wv(){K&&await tg(K)}async function Tv(){ln(),rh=null,K=null,ih=[],q.clear(),Lv=``,Rv=[],zv=!1,Xh.clear();let e=document.getElementById(`workspacePanel`);e&&e.classList.contains(`expanded`)&&await Jh()}function Ev(e){let t=document.getElementById(`workspacePanelContainer`);if(t)if(e){t.style.display=``;let e=document.getElementById(`workspacePanel`),n=!!(e&&e.classList.contains(`expanded`));ph&&e&&!n?Gh().catch(e=>a.warn(`[WorkspacePanel] reopen panel after reconnect failed`,e)):n&&!K&&Jh().catch(e=>a.warn(`[WorkspacePanel] navigate after reconnect failed`,e)),hh&&Uh()}else t.style.display=`none`,Iv(!0)}function Dv(e,t){let n=t.toLowerCase(),r=e.toLowerCase();return r===n?``:r.startsWith(n+`/`)?e.substring(t.length+1):null}function Ov(e,t){let n=t.split(`/`).filter(Boolean).pop();if(!n)return null;let r=e.lastIndexOf(`/`+n);if(r===-1)return null;let i=e.substring(r+n.length+1);return i===``?``:i}function kv(e,t){if(!e)return null;let n=ng(t);if(!n)return null;let r=ng(e).trim();if(!r||r===`.`||r===`~`||r.startsWith(`~/`))return null;if(!(r.startsWith(`/`)||/^[a-zA-Z]:\//.test(r)))return n+`/`+r;let i=Dv(r,n);return i===null&&(i=Ov(r,n)),i===null?null:i===``?n:n+`/`+i}async function Av(e){if(!(e===`~`||e&&e.startsWith(`~/`)))return e;try{let t=await Dn();if(t)return ng(e===`~`?t:t+`/`+e.slice(2))}catch{}return e}async function jv(e){if(!e)return;let t=document.getElementById(`workspacePanel`),n=document.getElementById(`workspacePanelContainer`);if(!t||!n)return;if(t.classList.add(`expanded`),Ft(t),n.classList.add(`click-opened`),rh||=await bn(),!rh){Sv(r(`workspace.noWorkspace`));return}let i=kv(await Av(e),rh);if(!i){Sv(r(`artifacts.locateFailed`));return}let a=i.lastIndexOf(`/`),o=a>0?i.substring(0,a):rh,s=a>0?i.substring(a+1):i;rg(o),await Yh(o);let c=e=>{let t=()=>{let t=null;return document.querySelectorAll(`.workspace-file-item`).forEach(n=>{n.dataset.name===e&&(t=n)}),t},n=t();if(n||!sg)return n;let r=sg.sorted.findIndex(t=>t.name===e);if(r<0)return null;let i=document.getElementById(`workspacePanelContent`);if(!i)return null;let{itemHeight:a}=sg;return i.scrollTop=Math.max(0,r*a-i.clientHeight/2+a/2),ug(),t()};setTimeout(async()=>{let e=c(s);e||=(rg(o),await Yh(o),await new Promise(e=>setTimeout(e,300)),c(s)),e?(e.classList.add(`highlighted`),e.scrollIntoView({behavior:`smooth`,block:`center`}),setTimeout(()=>e.classList.remove(`highlighted`),3e3)):L(r(`artifacts.fileNotFound`))},300)}async function Mv(e,t){if(!e)return;let n=document.getElementById(`workspacePanel`),i=document.getElementById(`workspacePanelContainer`);if(!n||!i)return;let a=n.classList.contains(`expanded`);if(n.classList.add(`expanded`),Ft(n),i.classList.add(`click-opened`),rh||=await bn(),!rh){Sv(r(`workspace.noWorkspace`));return}let o=kv(await Av(e),rh);if(!o){Sv(r(`artifacts.locateFailed`));return}await K_(!0),await Fg(o,t),Sh=!a}async function Nv(){await K_(!0)}function Pv(){Iv(!0)}async function Fv(e){return!e||(rh||=await bn(),!rh)?null:kv(await Av(e),rh)}async function Iv(e=!1){if(e&&await K_(!0)===!1)return;let t=document.getElementById(`workspacePanel`),n=document.getElementById(`workspacePanelContainer`);t&&(t.classList.remove(`expanded`),Wt(t),e||chrome.storage.local.set({[fh]:!1}).catch(()=>{})),n&&(n.classList.remove(`hover-expanded`),n.classList.remove(`click-opened`),ph&&!e&&(ph=!1,hh=!1,n.classList.add(`closing-no-anim`),Lh(),requestAnimationFrame(()=>n.classList.remove(`closing-no-anim`))))}var Lv=``,Rv=[],zv=!1,Bv=[],Vv=-1;function Hv(){try{chrome.storage.local.get([`workspaceSearchHistory`],e=>{Bv=e.workspaceSearchHistory||[]})}catch{}}function Uv(e){if(!e.trim())return;let t=Bv.indexOf(e);t!==-1&&Bv.splice(t,1),Bv.push(e),Bv.length>20&&Bv.shift();try{chrome.storage.local.set({workspaceSearchHistory:Bv})}catch{}}function Wv(e){Lv=e.target.value.trim();let t=document.getElementById(`workspaceSearchClear`);t.style.display=Lv?``:`none`}async function Gv(){if(!Lv){zv=!1,Rv=[],dg(),Sg();return}Uv(Lv),Vv=-1,L(r(`workspace.searching`),`info`),Rv=await Nn(K,Lv),zv=!0,dg(),Sg()}async function Kv(){let e=document.getElementById(`workspaceSearchInput`),t=document.getElementById(`workspaceToolbar`),n=t.querySelector(`.workspace-search-box`);e.value=``,Lv=``,zv=!1,Rv=[],q.clear(),document.getElementById(`workspaceSearchClear`).style.display=`none`,t.classList.remove(`search-focused`),n.classList.remove(`search-box-expanded`),e.blur(),await tg(K),Sg(),my()}async function qv(e,t,n){let i=n===`directory`,a=r(i?`workspace.confirmDeleteDir`:`workspace.confirmDeleteFile`,{name:t,path:e});if(typeof window.showCustomConfirm!=`function`){if(!confirm(a))return}else if(!await window.showCustomConfirm(a,r(`workspace.confirmDeleteTitle`)))return;let o=document.getElementById(`workspacePanelContent`),s=o?o.scrollTop:0;try{let t=await Cn();if(!t){L(r(`workspace.agentNotConnected`),`error`);return}let n=await(await fetch(`${t.url}/api/fs/delete`,{method:`POST`,headers:{"Content-Type":`application/json`,...An(t)},body:JSON.stringify({path:e})})).json();n.success?(L(r(i?`workspace.dirDeleted`:`workspace.fileDeleted`),`success`),q.delete(e),my(),await yv(s)):L(r(`workspace.deleteFailedWithError`,{error:n.error||r(`workspace.unknownError`)}),`error`)}catch(e){L(r(`workspace.deleteFailedWithError`,{error:e.message}),`error`)}}async function Jv(){if(q.size===0)return;let e=Array.from(q),t=e.map(e=>{let t=Dh.find(t=>t.path===e)||Rv.find(t=>t.fullPath===e);return t?t.name:e.split(/[\\/]/).pop()}),n=t.slice(0,5).map(e=>`• ${e}`).join(`
|
|
1163
|
+
`,document.body.appendChild(t);let n=t.querySelector(`.workspace-upload-progress-cancel`);return n&&n.addEventListener(`click`,()=>{n.style.display=`none`,typeof e==`function`&&e()}),t}function dv(e,t){if(!e)return;let{percent:n,completed:i,total:a,fileName:o,loaded:s,totalBytes:c,speed:l,statusText:u}=t,d=e.querySelector(`.workspace-upload-progress-title`),f=e.querySelector(`.workspace-upload-progress-file`),p=e.querySelector(`.workspace-upload-progress-bar`),m=e.querySelector(`.workspace-upload-progress-bytes`),h=e.querySelector(`.workspace-upload-progress-speed`),g=e.classList.contains(`download-mode`)?r(`workspace.downloadInProgress`):r(`workspace.uploadInProgress`);d&&(u?d.textContent=u:i!=null&&a!=null?d.textContent=`${g} ${i}/${a} · ${n}%`:d.textContent=`${g} ${n}%`),f&&o&&(f.textContent=o,f.title=o),p&&(p.style.width=n+`%`),m&&(s!=null&&c!=null&&c>0?m.textContent=`${kn(s)} / ${kn(c)}`:s!=null&&(m.textContent=kn(s))),h&&(h.textContent=l>0?`${kn(l)}/s`:``)}function fv(e,t,n){if(!e)return;let r=e.querySelector(`.workspace-upload-progress-title`),i=e.querySelector(`.workspace-upload-progress-cancel`),a=e.querySelector(`.workspace-upload-progress-bar`);i&&(i.style.display=`none`),r&&(r.textContent=t),a&&!n&&(a.style.width=`100%`),e.classList.add(`workspace-upload-progress-done`),n&&e.classList.add(`workspace-upload-progress-error`),setTimeout(()=>{try{e.remove()}catch{}},1500)}function pv(e){let t=document.getElementById(`workspaceUploadBtn`);t&&(t.disabled=e,e?(t.dataset.originalHtml=t.innerHTML,t.innerHTML=`<span class="workspace-upload-spinner"></span>`):t.dataset.originalHtml&&(t.innerHTML=t.dataset.originalHtml,delete t.dataset.originalHtml));let n=document.getElementById(`workspacePanel`);n&&n.classList.toggle(`upload-in-progress`,e)}async function mv(e){let t=Array.from(e);if(t.length===0||bh)return;bh=!0,pv(!0);let n=await Cn();if(!n){L(r(`workspace.agentNotConnectedUpload`),`error`),bh=!1,pv(!1);return}let i=new Set;try{let e=await mn(K);e.success&&Array.isArray(e.entries)&&(i=new Set(e.entries.map(e=>e.name)))}catch{}let a=0,o=0,s=0,c=t.reduce((e,t)=>e+t.size,0),l=Array(t.length).fill(0),u=new Set,d=!1,f=``,p=[],m=()=>{if(p.length<2)return 0;let e=p[0],t=p[p.length-1],n=(t.time-e.time)/1e3;return n<=0?0:(t.loaded-e.loaded)/n},h=uv(()=>{d=!0;for(let e of u)try{e.abort()}catch{}u.clear()}),g=e=>{e&&(f=e);let n=l.reduce((e,t)=>e+t,0),r=c>0?Math.round(n/c*100):0,i=Date.now();p.push({time:i,loaded:n}),p.length>8&&p.shift(),dv(h,{percent:r,completed:a+o+s,total:t.length,fileName:f,loaded:n,totalBytes:c,speed:m()})};g();for(let e=0;e<t.length&&!d;e+=3){let c=t.slice(e,e+3),f=await Promise.allSettled(c.map(async(t,a)=>{let o=e+a,s=kh(t.name),c=ng(`${K}/${s}`);if(i.has(s))throw l[o]=t.size,g(s),Error(`__SKIPPED__`);if(d)throw Error(`__CANCELLED__`);await new Promise((e,i)=>{let a=new XMLHttpRequest;u.add(a);let s=`${n.url}/api/fs/upload-stream?path=${encodeURIComponent(c)}`;a.open(`POST`,s);for(let[e,t]of Object.entries(An(n)))a.setRequestHeader(e,t);a.upload.onprogress=e=>{e.lengthComputable&&(l[o]=e.loaded,g(t.name))},a.onload=()=>{if(u.delete(a),d){i(Error(`__CANCELLED__`));return}if(a.status>=200&&a.status<300)try{let n=JSON.parse(a.responseText);n.success?(l[o]=t.size,g(t.name),e()):i(Error(n.error||r(`workspace.uploadFailed`)))}catch{i(Error(r(`workspace.parseResponseFailed`)))}else try{let e=JSON.parse(a.responseText);i(Error(e.error||r(`workspace.uploadFailedWithStatus`,{status:a.status})))}catch{i(Error(r(`workspace.uploadFailedWithStatus`,{status:a.status})))}},a.onerror=()=>{u.delete(a),i(Error(d?`__CANCELLED__`:r(`workspace.networkError`)))},a.onabort=()=>{u.delete(a),i(Error(`__CANCELLED__`))},a.send(t)})}));for(let e of f)if(e.status===`fulfilled`)a++;else{let t=e.reason&&e.reason.message?e.reason.message:``;t.includes(`__SKIPPED__`)||t.includes(`已存在`)?o++:t.includes(`__CANCELLED__`)||s++}}let _,v=!1;if(d)_=r(`workspace.uploadCanceled`),v=!0;else{let e=[];a>0&&e.push(r(`workspace.uploadSuccessCount`,{count:a})),o>0&&e.push(r(`workspace.uploadSkippedCount`,{count:o})),s>0&&e.push(r(`workspace.uploadFailedCount`,{count:s})),_=e.length>0?r(`workspace.uploadCompleteWithStats`,{stats:e.join(` / `)}):r(`workspace.uploadComplete`),v=s>0}fv(h,_,v),a>0&&L(r(`workspace.uploadedFiles`,{count:a}),`success`),o>0&&L(r(`workspace.filesSkipped`,{count:o}),`info`),s>0&&L(r(`workspace.filesUploadFailed`,{count:s}),`error`),d&&L(r(`workspace.uploadCanceled`),`info`),bh=!1,pv(!1),a>0&&(await yv(),fy(t[t.length-1].name))}function hv(){let e=document.getElementById(`workspacePanel`);if(!e)return;let t=document.getElementById(`workspacePanelContent`);t.addEventListener(`dragstart`,e=>{let t=e.target.closest(`.workspace-file-item`);if(!t)return;let n=t.dataset.path,r=t.dataset.name;e.dataTransfer.setData(`application/x-workspace-move`,JSON.stringify({path:n,name:r})),e.dataTransfer.effectAllowed=`move`,t.classList.add(`dragging`);let i=()=>{t.classList.remove(`dragging`),t.removeEventListener(`dragend`,i)};t.addEventListener(`dragend`,i)}),t.addEventListener(`dragover`,n=>{n.preventDefault(),n.stopPropagation();let r=n.target.closest(`.workspace-file-item.directory`);t.querySelectorAll(`.workspace-file-item.directory.drop-target`).forEach(e=>e.classList.remove(`drop-target`)),r?(n.dataTransfer.dropEffect=n.dataTransfer.types.includes(`application/x-workspace-move`)?`move`:`copy`,r.classList.add(`drop-target`),e.classList.remove(`drag-over`)):n.dataTransfer.types.includes(`application/x-workspace-move`)||e.classList.add(`drag-over`)}),t.addEventListener(`dragleave`,n=>{n.preventDefault(),n.stopPropagation(),t.querySelectorAll(`.workspace-file-item.directory.drop-target`).forEach(e=>e.classList.remove(`drop-target`)),e.classList.remove(`drag-over`)}),t.addEventListener(`drop`,async n=>{n.preventDefault(),n.stopPropagation();let i=n.target.closest(`.workspace-file-item.directory`);if(t.querySelectorAll(`.workspace-file-item.directory.drop-target`).forEach(e=>e.classList.remove(`drop-target`)),e.classList.remove(`drag-over`),i&&n.dataTransfer.types.includes(`application/x-workspace-move`)){try{let e=JSON.parse(n.dataTransfer.getData(`application/x-workspace-move`)),t=e.path,a=i.dataset.path,o=e.name,s=ng(t),c=ng(a);if(s===c)return;if(s.startsWith(c+`/`)){L(r(`workspace.cannotMoveToSubdir`),`error`);return}L(r(`workspace.moving`),`info`);let l=await Mn(t,a);if(l.success){L(r(`workspace.movedToDir`,{name:o}),`success`),rg(K),rg(a);let e=a.split(/[\\/]/).pop();await yv(),fy(e)}else L(r(`workspace.moveFailed`,{error:l.error}),`error`)}catch(e){L(r(`workspace.moveFailed`,{error:e.message}),`error`)}return}if(i&&n.dataTransfer.files&&n.dataTransfer.files.length>0){let e=i.dataset.path;e.split(/[\\/]/).pop(),Oh(K),K=e,await mv(n.dataTransfer.files),bv(),xv();return}if(n.dataTransfer.files&&n.dataTransfer.files.length>0){await mv(n.dataTransfer.files);return}}),e.addEventListener(`dragover`,t=>{t.preventDefault(),t.stopPropagation(),!t.dataTransfer.types.includes(`application/x-workspace-move`)&&e.classList.add(`drag-over`)}),e.addEventListener(`dragleave`,t=>{t.preventDefault(),t.stopPropagation(),!t.dataTransfer.types.includes(`application/x-workspace-move`)&&e.classList.remove(`drag-over`)}),e.addEventListener(`drop`,async t=>{if(t.preventDefault(),t.stopPropagation(),t.dataTransfer.types.includes(`application/x-workspace-move`))return;e.classList.remove(`drag-over`);let n=t.dataTransfer.files;!n||n.length===0||await mv(n)})}async function gv(){try{let e=document.getElementById(`workspaceAgentName`);if(!e)return;let t=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),n=t.pairedAgents||[],r=t.activeAgentId;if(r){let t=n.find(e=>e.id===r);if(t&&t.name){e.textContent=` · ${t.name}`,e.style.display=``;return}}e.textContent=``,e.style.display=`none`}catch(e){a.debug(`[WorkspacePanel] update agentname failed:`,e)}}async function _v(e,t){if(t===`local`&&!(!e.pairedAgents&&!e.activeAgentId)&&(await gv(),e.activeAgentId?.newValue!==e.activeAgentId?.oldValue)){a.debug(`[WorkspacePanel] Agent changed,refreshworking directory`),ln(),rh=null,K=null,ih=[],q.clear(),Lv=``,Rv=[],zv=!1,Xh.clear();let e=document.getElementById(`workspacePanel`);e&&e.classList.contains(`expanded`)&&await Jh()}}async function vv(){if(ih.length===0)return;let e=ih.pop();q.clear(),await Yh(e)}async function yv(e){if(!K){let e=rh||await bn();if(!e){L(r(`workspace.refreshFailed`),`error`);return}rh=e,K=e}if(rg(K),q.clear(),my(),zv&&Lv?(Rv=await Nn(K,Lv),dg()):await tg(K),K_(),Sg(),e!==void 0){let t=document.getElementById(`workspacePanelContent`);t&&requestAnimationFrame(()=>{t.scrollTop=e})}}function bv(){let e=document.getElementById(`workspaceBreadcrumb`);if(!K){e.innerHTML=``;return}let t=ng(K).split(`/`).filter(Boolean),n=rh?ng(rh).replace(/\/$/,``):null,i=``,a=``;for(let e=0;e<t.length;e++){a=e===0?/^[a-zA-Z]:$/.test(t[e])?t[e]+`/`:`/`+t[e]:(a.endsWith(`/`)?a:a+`/`)+t[e];let r=e===t.length-1,o=!n||a===n||a.startsWith(n+`/`);e>0&&(i+=`<span class="workspace-breadcrumb-sep">/</span>`),r?i+=`<span class="workspace-breadcrumb-current">${J(t[e])}</span>`:o?i+=`<span class="workspace-breadcrumb-link" data-path="${J(a)}">${J(t[e])}</span>`:i+=`<span class="workspace-breadcrumb-disabled">${J(t[e])}</span>`}e.innerHTML=i||`<span class="workspace-breadcrumb-current">/</span>`,e.querySelectorAll(`.workspace-breadcrumb-link`).forEach(e=>{e.addEventListener(`click`,async t=>{t.stopPropagation();let n=e.dataset.path,r=ih.findIndex(e=>e===n);ih=r>=0?ih.slice(0,r):[],q.clear(),await Yh(n)}),e.addEventListener(`dragover`,t=>{t.dataTransfer.types.includes(`application/x-workspace-move`)&&(t.preventDefault(),t.stopPropagation(),t.dataTransfer.dropEffect=`move`,e.classList.add(`drop-target`))}),e.addEventListener(`dragleave`,t=>{t.preventDefault(),t.stopPropagation(),e.classList.remove(`drop-target`)}),e.addEventListener(`drop`,async t=>{if(t.preventDefault(),t.stopPropagation(),e.classList.remove(`drop-target`),t.dataTransfer.types.includes(`application/x-workspace-move`))try{let n=JSON.parse(t.dataTransfer.getData(`application/x-workspace-move`)),i=n.path,a=e.dataset.path,o=n.name,s=ng(i),c=ng(a);if(s===c)return;if(c.startsWith(s+`/`)){L(r(`workspace.cannotMoveToSubdir`),`error`);return}L(r(`workspace.moving`),`info`);let l=await Mn(i,a);l.success?(L(r(`workspace.movedToTarget`,{name:o,target:a.split(/[\\/]/).pop()}),`success`),rg(K),rg(a),await yv()):L(r(`workspace.moveFailed`,{error:l.error}),`error`)}catch(e){L(r(`workspace.moveFailed`,{error:e.message}),`error`)}})})}function xv(){let e=document.getElementById(`workspaceBackBtn`);e.disabled=!(rh&&K&&K!==rh)}function Sv(e){let t=document.getElementById(`workspacePanelContent`);t.innerHTML=`<div class="workspace-panel-error">${J(e)}</div>`}function J(e){return e?String(e).replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`):``}function Cv(e){let t=(e.split(`.`).pop()||``).toLowerCase(),n={js:`javascript`,mjs:`javascript`,ts:`typescript`,jsx:`jsx`,tsx:`tsx`,html:`html`,htm:`html`,css:`css`,scss:`scss`,less:`less`,json:`json`,xml:`xml`,yaml:`yaml`,yml:`yaml`,py:`python`,java:`java`,c:`c`,cpp:`cpp`,h:`c`,go:`go`,rs:`rust`,rb:`ruby`,php:`php`,sql:`sql`,sh:`bash`,bash:`bash`,zsh:`bash`,md:`markdown`,vue:`html`,svelte:`html`};return n[t]?`language-${n[t]}`:``}async function wv(){K&&await tg(K)}async function Tv(){ln(),rh=null,K=null,ih=[],q.clear(),Lv=``,Rv=[],zv=!1,Xh.clear();let e=document.getElementById(`workspacePanel`);e&&e.classList.contains(`expanded`)&&await Jh()}function Ev(e){let t=document.getElementById(`workspacePanelContainer`);if(t)if(e){t.style.display=``;let e=document.getElementById(`workspacePanel`),n=!!(e&&e.classList.contains(`expanded`));ph&&e&&!n?Gh().catch(e=>a.warn(`[WorkspacePanel] reopen panel after reconnect failed`,e)):n&&!K&&Jh().catch(e=>a.warn(`[WorkspacePanel] navigate after reconnect failed`,e)),hh&&Uh()}else t.style.display=`none`,Iv(!0)}function Dv(e,t){let n=t.toLowerCase(),r=e.toLowerCase();return r===n?``:r.startsWith(n+`/`)?e.substring(t.length+1):null}function Ov(e,t){let n=t.split(`/`).filter(Boolean).pop();if(!n)return null;let r=e.lastIndexOf(`/`+n);if(r===-1)return null;let i=e.substring(r+n.length+1);return i===``?``:i}function kv(e,t){if(!e)return null;let n=ng(t);if(!n)return null;let r=ng(e).trim();if(!r||r===`.`||r===`~`||r.startsWith(`~/`))return null;if(!(r.startsWith(`/`)||/^[a-zA-Z]:\//.test(r)))return n+`/`+r;let i=Dv(r,n);return i===null&&(i=Ov(r,n)),i===null?null:i===``?n:n+`/`+i}async function Av(e){if(!(e===`~`||e&&e.startsWith(`~/`)))return e;try{let t=await Dn();if(t)return ng(e===`~`?t:t+`/`+e.slice(2))}catch{}return e}async function jv(e){if(!e)return;let t=document.getElementById(`workspacePanel`),n=document.getElementById(`workspacePanelContainer`);if(!t||!n)return;if(t.classList.add(`expanded`),It(t),n.classList.add(`click-opened`),rh||=await bn(),!rh){Sv(r(`workspace.noWorkspace`));return}let i=kv(await Av(e),rh);if(!i){Sv(r(`artifacts.locateFailed`));return}let a=i.lastIndexOf(`/`),o=a>0?i.substring(0,a):rh,s=a>0?i.substring(a+1):i;rg(o),await Yh(o);let c=e=>{let t=()=>{let t=null;return document.querySelectorAll(`.workspace-file-item`).forEach(n=>{n.dataset.name===e&&(t=n)}),t},n=t();if(n||!sg)return n;let r=sg.sorted.findIndex(t=>t.name===e);if(r<0)return null;let i=document.getElementById(`workspacePanelContent`);if(!i)return null;let{itemHeight:a}=sg;return i.scrollTop=Math.max(0,r*a-i.clientHeight/2+a/2),ug(),t()};setTimeout(async()=>{let e=c(s);e||=(rg(o),await Yh(o),await new Promise(e=>setTimeout(e,300)),c(s)),e?(e.classList.add(`highlighted`),e.scrollIntoView({behavior:`smooth`,block:`center`}),setTimeout(()=>e.classList.remove(`highlighted`),3e3)):L(r(`artifacts.fileNotFound`))},300)}async function Mv(e,t){if(!e)return;let n=document.getElementById(`workspacePanel`),i=document.getElementById(`workspacePanelContainer`);if(!n||!i)return;let a=n.classList.contains(`expanded`);if(n.classList.add(`expanded`),It(n),i.classList.add(`click-opened`),rh||=await bn(),!rh){Sv(r(`workspace.noWorkspace`));return}let o=kv(await Av(e),rh);if(!o){Sv(r(`artifacts.locateFailed`));return}await K_(!0),await Fg(o,t),Sh=!a}async function Nv(){await K_(!0)}function Pv(){Iv(!0)}async function Fv(e){return!e||(rh||=await bn(),!rh)?null:kv(await Av(e),rh)}async function Iv(e=!1){if(e&&await K_(!0)===!1)return;let t=document.getElementById(`workspacePanel`),n=document.getElementById(`workspacePanelContainer`);t&&(t.classList.remove(`expanded`),Gt(t),e||chrome.storage.local.set({[fh]:!1}).catch(()=>{})),n&&(n.classList.remove(`hover-expanded`),n.classList.remove(`click-opened`),ph&&!e&&(ph=!1,hh=!1,n.classList.add(`closing-no-anim`),Lh(),requestAnimationFrame(()=>n.classList.remove(`closing-no-anim`))))}var Lv=``,Rv=[],zv=!1,Bv=[],Vv=-1;function Hv(){try{chrome.storage.local.get([`workspaceSearchHistory`],e=>{Bv=e.workspaceSearchHistory||[]})}catch{}}function Uv(e){if(!e.trim())return;let t=Bv.indexOf(e);t!==-1&&Bv.splice(t,1),Bv.push(e),Bv.length>20&&Bv.shift();try{chrome.storage.local.set({workspaceSearchHistory:Bv})}catch{}}function Wv(e){Lv=e.target.value.trim();let t=document.getElementById(`workspaceSearchClear`);t.style.display=Lv?``:`none`}async function Gv(){if(!Lv){zv=!1,Rv=[],dg(),Sg();return}Uv(Lv),Vv=-1,L(r(`workspace.searching`),`info`),Rv=await Nn(K,Lv),zv=!0,dg(),Sg()}async function Kv(){let e=document.getElementById(`workspaceSearchInput`),t=document.getElementById(`workspaceToolbar`),n=t.querySelector(`.workspace-search-box`);e.value=``,Lv=``,zv=!1,Rv=[],q.clear(),document.getElementById(`workspaceSearchClear`).style.display=`none`,t.classList.remove(`search-focused`),n.classList.remove(`search-box-expanded`),e.blur(),await tg(K),Sg(),my()}async function qv(e,t,n){let i=n===`directory`,a=r(i?`workspace.confirmDeleteDir`:`workspace.confirmDeleteFile`,{name:t,path:e});if(typeof window.showCustomConfirm!=`function`){if(!confirm(a))return}else if(!await window.showCustomConfirm(a,r(`workspace.confirmDeleteTitle`)))return;let o=document.getElementById(`workspacePanelContent`),s=o?o.scrollTop:0;try{let t=await Cn();if(!t){L(r(`workspace.agentNotConnected`),`error`);return}let n=await(await fetch(`${t.url}/api/fs/delete`,{method:`POST`,headers:{"Content-Type":`application/json`,...An(t)},body:JSON.stringify({path:e})})).json();n.success?(L(r(i?`workspace.dirDeleted`:`workspace.fileDeleted`),`success`),q.delete(e),my(),await yv(s)):L(r(`workspace.deleteFailedWithError`,{error:n.error||r(`workspace.unknownError`)}),`error`)}catch(e){L(r(`workspace.deleteFailedWithError`,{error:e.message}),`error`)}}async function Jv(){if(q.size===0)return;let e=Array.from(q),t=e.map(e=>{let t=Dh.find(t=>t.path===e)||Rv.find(t=>t.fullPath===e);return t?t.name:e.split(/[\\/]/).pop()}),n=t.slice(0,5).map(e=>`• ${e}`).join(`
|
|
1164
1164
|
`)+(t.length>5?r(`workspace.batchNamesMore`,{count:t.length}):``),i=r(`workspace.confirmBatchDelete`,{count:e.length,names:n});if(typeof window.showCustomConfirm!=`function`){if(!confirm(i))return}else if(!await window.showCustomConfirm(i,r(`workspace.confirmBatchDeleteTitle`)))return;let a=document.getElementById(`workspacePanelContent`),o=a?a.scrollTop:0;try{let t=await Cn();if(!t){L(r(`workspace.agentNotConnected`),`error`);return}let n=0,i=0;for(let r of e)try{(await(await fetch(`${t.url}/api/fs/delete`,{method:`POST`,headers:{"Content-Type":`application/json`,...An(t)},body:JSON.stringify({path:r})})).json()).success?(q.delete(r),n++):i++}catch{i++}n>0?(L(r(`workspace.deletedCount`,{success:n,failed:i>0?r(`workspace.deletedCountFailed`,{count:i}):``}),i>0?`warning`:`success`),my(),await yv(o)):L(r(`workspace.deleteFailed`),`error`)}catch(e){L(r(`workspace.deleteFailedWithError`,{error:e.message}),`error`)}}function Yv(e,t){let n=[{bit:256,ch:`r`},{bit:128,ch:`w`},{bit:64,ch:`x`},{bit:32,ch:`r`},{bit:16,ch:`w`},{bit:8,ch:`x`},{bit:4,ch:`r`},{bit:2,ch:`w`},{bit:1,ch:`x`}],r=t?`d`:`-`;for(let t of n)r+=e&t.bit?t.ch:`-`,t.ch===`x`&&e&t.bit<<9&&(r=r.slice(0,-1)+(t.ch===`x`?`s`:`S`));let i=(e&511).toString(8).padStart(3,`0`);return`${r} (${i})`}async function Xv(e,t,n){let i=document.createElement(`div`);i.className=`modal-overlay show`,i.innerHTML=`
|
|
1165
1165
|
<div class="modal-container file-info-modal">
|
|
1166
1166
|
<button class="file-info-close" title="${r(`workspace.close`)}" style="position:absolute;top:10px;right:12px;background:none;border:none;font-size:20px;color:var(--text-tertiary);cursor:pointer;padding:4px 8px;line-height:1;transition:color 0.15s ease;">×</button>
|
|
@@ -1203,7 +1203,7 @@ It is this session's directory or the agent default, so it stays accessible (wor
|
|
|
1203
1203
|
<span style="flex:1;">${J(e)}</span>
|
|
1204
1204
|
${t?a:``}${n?o:``}
|
|
1205
1205
|
${i?`<button class="switch-workdir-remove" data-remove-path="${J(e)}" title="${r(`workspace.removeFromAllowed`)}" style="flex-shrink:0;background:none;border:none;color:var(--danger-500);cursor:pointer;font-size:16px;line-height:1;padding:2px 6px;border-radius:4px;">×</button>`:``}
|
|
1206
|
-
</div>`}).join(``)}C(),b&&b.addEventListener(`change`,()=>{a.querySelectorAll(`.switch-workdir-item.current`).forEach(e=>{e.style.cursor=T(e.dataset.path)?`pointer`:`default`})});async function w(e){let t=d(e,l)||d(e,c);if(!await window.showCustomConfirm(r(t?`workspace.confirmRemoveStillUsable`:`workspace.confirmRemovePath`,{path:e}),r(`workspace.confirmRemovePathTitle`)))return;let n=await Pn(e);n.success?(u=Array.isArray(n.allowedPaths)?n.allowedPaths:u.filter(t=>t!==e),C(),L(r(t?`workspace.removedStillUsable`:`workspace.removedFromAllowed`),`success`)):L(r(`workspace.removeFailedWithError`,{error:n.error||r(`workspace.unknownError`)}),`error`)}let T=e=>{if(!(b&&b.checked))return!1;let t=e=>String(e||``).replace(/\\/g,`/`).toLowerCase();return!l||t(e)!==t(l)};a.addEventListener(`click`,e=>{let t=e.target.closest(`.switch-workdir-remove`);if(t){e.stopPropagation(),w(t.dataset.removePath);return}let n=e.target.closest(`.switch-workdir-item`);n&&(n.classList.contains(`current`)&&!T(n.dataset.path)||E(n.dataset.path))});async function E(n){if(!n){L(r(`workspace.selectOrInputPath`),`error`);return}n=n.trim();let a=e=>e.replace(/\\/g,`/`).toLowerCase(),o=(e,t)=>!!e&&!!t&&a(e)===a(t),s=!!(b&&b.checked);if(o(n,c)){if(s&&!o(n,l)){S(),e(await iy(n));return}L(r(`workspace.alreadyCurrentWorkdir`),`info`),S(),e(!1);return}let d=i?t:null,f=!d||s;!u.some(e=>{let t=a(n),r=a(e);return t===r||t.startsWith(r+`/`)})&&f&&!await window.showCustomConfirm(r(`workspace.confirmSwitchToNewDefault`,{path:n}),r(`workspace.confirmSwitchToNewTitle`))||(S(),e(await ay(n,{sessionId:d,setAsDefault:s})))}y&&y.addEventListener(`click`,async()=>{y.disabled=!0,S(),e(await oy(t,{sessionSupported:i}))}),g.addEventListener(`click`,()=>E(m.value)),h.addEventListener(`click`,()=>{S(),e(!1)}),_.addEventListener(`click`,()=>{S(),e(!1)}),_.addEventListener(`mouseenter`,()=>{_.style.color=`var(--text-primary)`,_.style.background=`var(--border-subtle)`}),_.addEventListener(`mouseleave`,()=>{_.style.color=`var(--text-tertiary)`,_.style.background=`transparent`}),m.addEventListener(`keydown`,t=>{t.key===`Enter`&&(t.preventDefault(),E(m.value)),t.key===`Escape`&&(S(),e(!1))}),n.addEventListener(`click`,e=>{e.target===n&&e.stopPropagation()}),setTimeout(()=>m.focus(),50)})}function $v(){rh=null,K=null,ih=[],q.clear(),Lv=``,Rv=[],zv=!1,Xh.clear();let e=document.getElementById(`workspaceSearchInput`);e&&(e.value=``);let t=document.getElementById(`workspaceSearchClear`);t&&(t.style.display=`none`);let n=document.getElementById(`workspaceToolbar`);if(n){n.classList.remove(`search-focused`);let e=n.querySelector(`.workspace-search-box`);e&&e.classList.remove(`search-box-expanded`)}}var ey=0;async function ty(){let e=++ey;if(N.agentPlatform?.connected!==!0){ln(),$v();return}await gv();let t=rh;ln();let n=null;try{n=await bn()}catch(e){a.warn(`[WorkspacePanel] resolve root for session failed:`,e?.message||e)}if(e!==ey||t&&n&&t===n)return;$v();let r=document.getElementById(`workspacePreviewArea`);if(r&&r.dataset.previewPath&&(Sh=!1,await K_(!0)),await Promise.resolve(),e!==ey)return;let i=document.getElementById(`workspacePanel`);!i||!i.classList.contains(`expanded`)||await Jh()}async function ny(e,t){document.dispatchEvent(new CustomEvent(`session-workdir-changed`,{detail:{sessionId:e,workdir:t}}))}async function ry(e){N.defaultWorkdir=e,N.agentPlatform&&={...N.agentPlatform,workdir:e};try{let{activeAgentId:t}=await chrome.storage.local.get([`activeAgentId`]);t&&(N.agentWorkdirs.set(t,e),typeof window.updateAgentItemWorkdir==`function`&&window.updateAgentItemWorkdir(t,e))}catch(e){a.debug(`[WorkspacePanel] sync dropdown column table workdir failed:`,e)}}async function iy(e){let t=await un(e,{sessionId:null});return t.success?(await ry(t.workdir),await ny(null,t.workdir),L(r(`workspace.setAsDefaultDone`,{path:t.workdir}),`success`),!0):(L(r(`workspace.switchFailedWithError`,{error:t.error||r(`workspace.unknownError`)}),`error`),!1)}async function ay(e,t={}){let n=t.sessionId===void 0?N.activeSessionId||null:t.sessionId,i=t.setAsDefault===!0,o=await un(e,{sessionId:n});if(!o.success)return L(r(`workspace.switchFailedWithError`,{error:o.error||r(`workspace.unknownError`)}),`error`),!1;if(n)try{let{setSessionWorkdirBinding:e}=await M(async()=>{let{setSessionWorkdirBinding:e}=await import(`./session-store-xr0nYACs.js`).then(e=>e.g);return{setSessionWorkdirBinding:e}},__vite__mapDeps([2,1,3,4])),t=(await Cn())?.id||null;await e(n,o.workdir,t)}catch(e){a.warn(`[WorkspacePanel] persist session workdir failed:`,e)}let s=!1;if(i){let e=await un(o.workdir,{sessionId:null});e.success?s=!0:L(r(`workspace.switchFailedWithError`,{error:e.error||r(`workspace.unknownError`)}),`error`)}return(!n||i)&&await ry(o.workdir),await ny(n,o.workdir),L(r(s?`workspace.switchedToAndSetDefault`:`workspace.switchedTo`,{path:o.workdir}),`success`),!0}async function oy(e,t={}){if(!e)return!1;let{unbindSessionWorkdirRemote:n}=await M(async()=>{let{unbindSessionWorkdirRemote:e}=await import(`./session-store-xr0nYACs.js`).then(e=>e.Ft);return{unbindSessionWorkdirRemote:e}},__vite__mapDeps([2,1,3,4]));if(await n(e)===null&&t.sessionSupported)return L(r(`workspace.switchFailedWithError`,{error:r(`workspace.unknownError`)}),`error`),!1;try{let{setSessionWorkdirBinding:t}=await M(async()=>{let{setSessionWorkdirBinding:e}=await import(`./session-store-xr0nYACs.js`).then(e=>e.g);return{setSessionWorkdirBinding:e}},__vite__mapDeps([2,1,3,4]));await t(e,null,null)}catch(e){a.warn(`[WorkspacePanel] clear session workdir failed:`,e)}return await ny(e,``),L(r(`workdirTag.restoredDefault`),`success`),!0}async function sy(e,t,n){let i=t,a=``,o=t.lastIndexOf(`.`);n!==`directory`&&o>0&&(i=t.substring(0,o),a=t.substring(o));let s=await Zv(r(n===`directory`?`workspace.renameDir`:`workspace.renameFile`),i,r(`workspace.inputNewName`));if(!s||s===i)return;let c=s+a;try{let t=await fn(e,c);t.success?(L(r(`workspace.renamedTo`,{name:c}),`success`),rg(K),await yv(),fy(c)):L(r(`workspace.renameFailedWithError`,{error:t.error}),`error`)}catch(e){L(r(`workspace.renameFailedWithError`,{error:e.message}),`error`)}}async function cy(){if(!K)return;let e=await Zv(r(`workspace.newFolderTitle`),``,r(`workspace.inputFolderName`));if(!e)return;let t=ng(`${K}/${e}`);try{let n=await Tn(t);n.success?(L(r(`workspace.folderCreated`,{name:e}),`success`),rg(K),await yv(),fy(e)):L(r(`workspace.createFailedWithError`,{error:n.error}),`error`)}catch(e){L(r(`workspace.createFailedWithError`,{error:e.message}),`error`)}}async function ly(e){return new Promise((t,n)=>{let i=new Image,a=URL.createObjectURL(e);i.onload=()=>{URL.revokeObjectURL(a);let n=new FileReader;n.onloadend=()=>{let e=n.result,r=i.width,a=i.height,o=Math.max(r,a),s,c;o<=768?(s=o,c=.75):o<=1280?(s=768,c=.7):o<=2560?(s=1024,c=.65):o<=3840?(s=1280,c=.6):(s=1280,c=.55);let l=r,u=a;o>s&&(r>a?(u=Math.round(s/r*a),l=s):(l=Math.round(s/a*r),u=s));let d=document.createElement(`canvas`);d.width=l,d.height=u;let f=d.getContext(`2d`);f.imageSmoothingEnabled=!0,f.imageSmoothingQuality=`high`,f.drawImage(i,0,0,l,u),t({originalUrl:e,compressedUrl:d.toDataURL(`image/jpeg`,c)})},n.readAsDataURL(e)},i.onerror=()=>{URL.revokeObjectURL(a),n(Error(r(`workspace.imageLoadFailed`)))},i.src=a})}async function uy(e){let t=[],n=[];for(let r of e){let e=r&&typeof r==`object`,i=e?r.fullPath||r.path:r,a=i.split(/[\\/]/).pop(),o;e?o=r:(o=Dh.find(e=>e.path===i),o||=Rv.find(e=>e.fullPath===i));let s=o?o.size:0,c=wn(a);if(c.startsWith(`image/`)&&N.enableImageInput)n.push({name:a,size:s,type:c,path:i});else{let e={name:a,size:s,type:c,text:``,status:`done`,agentPath:i};t.push(e)}}for(let e of n)try{let t=await Cn();if(t){let n=await fetch(`${t.url}/api/fs/download-stream`,{method:`POST`,headers:{"Content-Type":`application/json`,...An(t)},body:JSON.stringify({path:e.path})});if(n.ok){let{originalUrl:e,compressedUrl:t}=await ly(await n.blob());N.attachedImages.some(e=>e.compressedUrl===t)||N.attachedImages.push({originalUrl:e,compressedUrl:t})}}}catch{}for(let e of t)N.attachedFiles.some(t=>t.name===e.name&&t.agentPath===e.agentPath)||N.attachedFiles.push(e);km(),Zm();let i=t.length+n.length;i>0&&(!N.enableImageInput&&t.some(e=>e.type?.startsWith(`image/`))?L(r(`workspace.addedFilesToQuestionNoImage`,{count:i}),`success`):L(r(`workspace.addedFilesToQuestion`,{count:i}),`success`))}async function dy(){q.size!==0&&await uy(Array.from(q))}function fy(e,t=0){let n=document.getElementById(`workspacePanelContent`);if(!n)return;if(sg){let t=sg.sorted.findIndex(t=>t.name===e);if(t>=0){let r=sg.itemHeight;n.scrollTop=Math.max(0,t*r-n.clientHeight/2+r/2),ug();let i=Array.from(n.querySelectorAll(`.workspace-file-item`)).find(t=>t.dataset.name===e);i&&(i.classList.add(`highlight-new`),setTimeout(()=>i.classList.remove(`highlight-new`),2e3));return}}let r=Array.from(n.querySelectorAll(`.workspace-file-item`)).find(t=>t.dataset.name===e);r?(r.scrollIntoView({behavior:`smooth`,block:`center`}),r.classList.add(`highlight-new`),setTimeout(()=>r.classList.remove(`highlight-new`),2e3)):t<5&&setTimeout(()=>fy(e,t+1),150)}function py(){let e=document.getElementById(`workspaceAskBtn`);q.size===0?e.style.display=`none`:e.style.display=``}function my(){let e=document.getElementById(`workspaceDownloadDirBtn`),t=document.getElementById(`workspaceBatchDeleteBtn`),n=document.getElementById(`workspaceSelectedCount`);q.size===0?(e.style.display=`none`,t.style.display=`none`,n.style.display=`none`):(e.style.display=``,t.style.display=``,n.style.display=``,n.textContent=r(`workspace.selectedCount`,{count:q.size}),e.disabled=yh),py()}n(`zh`,{artifacts:{btnTitle:`文件产物({count})`,modalTitle:`本次任务的文件产物`,emptyHint:`本次任务没有产生文件产物`,fileCol:`文件`,sizeCol:`大小`,typeCol:`类型`,timeCol:`时间`,actionCol:`操作`,locate:`定位到文件`,preview:`预览`,closeBtn:`关闭`,typeWrite:`写入`,typeDelete:`删除`,typeCreate:`创建`,typeEdit:`编辑`,typeOther:`操作`,noWorkspace:`无法获取工作目录,请确认 Agent 已连接`,locateFailed:`定位文件失败`,fileNotFound:`目录已定位,但未找到该文件(可能已被删除)`,previewFailed:`预览文件失败`,previewNotSupported:`此文件类型不支持预览`,totalCount:`共 {count} 个文件`,badgeLabel:`产物`,download:`下载`,downloadFailed:`下载失败`,copyFileName:`复制文件名`,copyFilePath:`复制文件路径`,copiedName:`已复制文件名:{name}`,copiedPath:`已复制文件路径`,dblClickHint:`双击文件名可预览`,sortHint:`点击排序`,serialCol:`序号`}}),n(`en`,{artifacts:{btnTitle:`Artifacts ({count})`,modalTitle:`File Artifacts of This Task`,emptyHint:`No file artifacts produced in this task`,fileCol:`File`,sizeCol:`Size`,typeCol:`Type`,timeCol:`Time`,actionCol:`Actions`,locate:`Locate File`,preview:`Preview`,closeBtn:`Close`,typeWrite:`Write`,typeDelete:`Delete`,typeCreate:`Create`,typeEdit:`Edit`,typeOther:`Op`,noWorkspace:`Unable to access working directory. Please confirm the Agent is connected.`,locateFailed:`Failed to locate file`,fileNotFound:`Directory located, but file not found (may have been deleted)`,previewFailed:`Failed to preview file`,previewNotSupported:`Preview not supported for this file type`,totalCount:`{count} files in total`,badgeLabel:`Artifacts`,download:`Download`,downloadFailed:`Download failed`,copyFileName:`Copy File Name`,copyFilePath:`Copy File Path`,copiedName:`Copied file name: {name}`,copiedPath:`File path copied`,dblClickHint:`Double-click to preview`,sortHint:`Click to sort`,serialCol:`#`}});function hy(e){let t=(e||``).replace(/\\/g,`/`).replace(/\/+/g,`/`),n=t.replace(/\/+$/,``);return n?/^[A-Za-z]:$/.test(n)?n+`/`:n:t?`/`:``}function gy(e){if(!e)return``;let t=hy(e).replace(/\/+$/,``).split(`/`);return t[t.length-1]||``}function _y(e){if(!e)return``;let t=gy(e),n=t.lastIndexOf(`.`);return n>0?t.substring(n+1).toLowerCase():``}function vy(e){return String(e??``).replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`)}function yy(e,t){let n=new Set(t),r=[],i=0,a=``;for(let t of e)t===`{`?i++:t===`}`&&(i=Math.max(0,i-1)),i===0&&n.has(t)?(r.push(a),a=``):a+=t;return r.push(a),r}function by(e){let t=e.indexOf(`{`);if(t===-1)return[e];let n=0,r=-1;for(let i=t;i<e.length;i++)if(e[i]===`{`)n++;else if(e[i]===`}`&&(n--,n===0)){r=i;break}if(r===-1)return[e];let i=e.substring(0,t),a=e.substring(t+1,r),o=e.substring(r+1),s=yy(a,`,`).map(e=>e.trim());if(s.length<=1)return[e];let c=[];for(let e of s)for(let t of by(e))for(let e of by(o))c.push(i+t+e);return c}function xy(e,t){let n=[],r=new Set;for(let i of e)if(i)for(let e of by(i)){if(!e)continue;let i=t(e);!i||r.has(i)||(r.add(i),n.push(i))}return n}function Sy(e){if(!e)return null;let t=e;if(typeof t==`string`)try{t=JSON.parse(t)}catch{let e=t.match(/["']?path["']?\s*[:=]\s*["']([^"']+)["']/i);return e?e[1]:null}return t&&typeof t==`object`&&(t.path||t.filePath||t.file_path||t.result?.path)||null}function Cy(e){let t=[],n=0,r=``;for(let i=0;i<e.length;i++){let a=e[i];if(a===`{`?n++:a===`}`&&(n=Math.max(0,n-1)),n===0&&a===`<`&&e[i+1]===`<`){let t=wy(e,i);if(t>i){r+=e.substring(i,t),i=t-1;continue}}n===0&&a===`;`?(t.push(r),r=``):n===0&&a===`&`&&e[i+1]===`&`?(t.push(r),r=``,i++):r+=a}return t.push(r),t}function wy(e,t){let n=e.substring(t).match(/^<<-?\s*['"]?([A-Za-z_][A-Za-z0-9_]*)['"]?/);if(!n)return-1;let r=n[1],i=t+n[0].length,a=e.substring(i),o=RegExp(`\\n\\s*`+r.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)+`\\s*(?=\\n|$)`),s=a.match(o);return s?i+s.index+s[0].length:-1}function Ty(e){let t=hy(e||``).replace(/\/$/,``);if(!t)return``;let n=t.lastIndexOf(`/`);return n>0?t.substring(0,n):``}var Ey=new Set([`du`,`df`,`stat`,`wc`,`file`,`cat`,`head`,`tail`,`grep`,`rg`]);function Dy(e){if(!e||typeof e!=`string`)return!1;let t=Cy(e);if(t.length===0)return!1;for(let e of t){let t=e.trim().split(/\s+/).filter(Boolean);for(;t.length&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(t[0]);)t.shift();if(!t.length)continue;let n=t[0].split(`/`).pop().toLowerCase();if(n===`sudo`&&t.length>1&&(n=t[1].split(`/`).pop().toLowerCase()),!Ey.has(n))return!1}return!0}function Oy(e,t){let n=t=>e===t||e.startsWith(t.endsWith(`/`)?t:t+`/`);return[...t].some(n)}function ky(e,t){if(!e||typeof e!=`string`)return t||``;let n=t||``;for(let t of Cy(e)){let e=t.trim().match(/^cd\s+(.+?)\s*$/);if(!e)continue;let r=e[1].trim().replace(/^['"]|['"]$/g,``);n=r.startsWith(`/`)||r.startsWith(`~/`)?r:r===`..`?n?hy(n).replace(/\/[^/]+$/,``)||`/`:`..`:hy(n?n.replace(/\/$/,``)+`/`+r:r)}return n}function Ay(e,t){if(!e||typeof e!=`string`)return[];let n=[],r=t||``,i=Cy(e);for(let e of i){let t=e.trim();if(!t)continue;let i=t.replace(/"[^"]*"/g,`""`).replace(/'[^']*'/g,`''`),a=t.match(/^cd\s+(.+?)\s*$/);if(a){let e=a[1].trim().replace(/^['"]|['"]$/g,``);r=e.startsWith(`/`)||e.startsWith(`~/`)?e:e===`..`?r?hy(r).replace(/\/[^/]+$/,``)||`/`:`..`:hy(r?r.replace(/\/$/,``)+`/`+e:e);continue}let o=e=>(e=e.replace(/^['"]|['"]$/g,``),!e.startsWith(`/`)&&!e.startsWith(`~/`)&&r&&(e=hy(r.replace(/\/$/,``)+`/`+e)),hy(e)),s=t.match(/^(\S+)\s+.*<<-?\s*['"]?([A-Za-z_][A-Za-z0-9_]*)['"]?\s*\n([\s\S]*?)\n\s*\2\s*$/);if(s){let e=s[1].split(`/`).pop().toLowerCase(),t=s[3],r=null;if(/^python[\d.]*$/.test(e)?r=`py`:/^(ba)?sh$/.test(e)&&(r=`sh`),r){for(let e of jy(t,r))e&&n.push({path:o(e),isDir:!1});continue}}let c=i.match(/^mkdir\s+(?:-[a-z]+\s+)*(.+?)$/);if(c){let e=xy(yy(c[1],` `).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`-`)&&e!==`""`&&e!==`''`),o);for(let t of e)n.push({path:t,isDir:!0});continue}let l=i.match(/^touch\s+(.+)$/);if(l){let e=xy(yy(l[1],` `).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`-`)&&e!==`""`&&e!==`''`),o);for(let t of e)n.push({path:t,isDir:!1});continue}let u=null,d=i.match(/\s[>]{1,2}\s*['"]?([^\s|&;'"]+)['"]?\s*$/);if(d&&(u=d[1]),!u){let e=i.match(/^cat\s+>\s*['"]?([^\s|&;'"]+)['"]?/);e&&(u=e[1])}if(!u){let e=t.match(/^cp\s+(?:-[a-zA-Z]+\s+)*(?:.+?\s+)+?['"]?([^\s|&;'"]+)['"]?\s*$/);e&&(u=e[1])}if(!u){let e=i.match(/tee\s+(?:-[a-zA-Z]+\s+)*['"]?([^\s|&;'"]+)['"]?/);e&&(u=e[1])}if(u){let e=xy([u],o);for(let t of e)n.push({path:t,isDir:!1})}}return n}function jy(e,t){if(!e||typeof e!=`string`)return[];let n=[],r=e.split(`
|
|
1206
|
+
</div>`}).join(``)}C(),b&&b.addEventListener(`change`,()=>{a.querySelectorAll(`.switch-workdir-item.current`).forEach(e=>{e.style.cursor=T(e.dataset.path)?`pointer`:`default`})});async function w(e){let t=d(e,l)||d(e,c);if(!await window.showCustomConfirm(r(t?`workspace.confirmRemoveStillUsable`:`workspace.confirmRemovePath`,{path:e}),r(`workspace.confirmRemovePathTitle`)))return;let n=await Pn(e);n.success?(u=Array.isArray(n.allowedPaths)?n.allowedPaths:u.filter(t=>t!==e),C(),L(r(t?`workspace.removedStillUsable`:`workspace.removedFromAllowed`),`success`)):L(r(`workspace.removeFailedWithError`,{error:n.error||r(`workspace.unknownError`)}),`error`)}let T=e=>{if(!(b&&b.checked))return!1;let t=e=>String(e||``).replace(/\\/g,`/`).toLowerCase();return!l||t(e)!==t(l)};a.addEventListener(`click`,e=>{let t=e.target.closest(`.switch-workdir-remove`);if(t){e.stopPropagation(),w(t.dataset.removePath);return}let n=e.target.closest(`.switch-workdir-item`);n&&(n.classList.contains(`current`)&&!T(n.dataset.path)||E(n.dataset.path))});async function E(n){if(!n){L(r(`workspace.selectOrInputPath`),`error`);return}n=n.trim();let a=e=>e.replace(/\\/g,`/`).toLowerCase(),o=(e,t)=>!!e&&!!t&&a(e)===a(t),s=!!(b&&b.checked);if(o(n,c)){if(s&&!o(n,l)){S(),e(await iy(n));return}L(r(`workspace.alreadyCurrentWorkdir`),`info`),S(),e(!1);return}let d=i?t:null,f=!d||s;!u.some(e=>{let t=a(n),r=a(e);return t===r||t.startsWith(r+`/`)})&&f&&!await window.showCustomConfirm(r(`workspace.confirmSwitchToNewDefault`,{path:n}),r(`workspace.confirmSwitchToNewTitle`))||(S(),e(await ay(n,{sessionId:d,setAsDefault:s})))}y&&y.addEventListener(`click`,async()=>{y.disabled=!0,S(),e(await oy(t,{sessionSupported:i}))}),g.addEventListener(`click`,()=>E(m.value)),h.addEventListener(`click`,()=>{S(),e(!1)}),_.addEventListener(`click`,()=>{S(),e(!1)}),_.addEventListener(`mouseenter`,()=>{_.style.color=`var(--text-primary)`,_.style.background=`var(--border-subtle)`}),_.addEventListener(`mouseleave`,()=>{_.style.color=`var(--text-tertiary)`,_.style.background=`transparent`}),m.addEventListener(`keydown`,t=>{t.key===`Enter`&&(t.preventDefault(),E(m.value)),t.key===`Escape`&&(S(),e(!1))}),n.addEventListener(`click`,e=>{e.target===n&&e.stopPropagation()}),setTimeout(()=>m.focus(),50)})}function $v(){rh=null,K=null,ih=[],q.clear(),Lv=``,Rv=[],zv=!1,Xh.clear();let e=document.getElementById(`workspaceSearchInput`);e&&(e.value=``);let t=document.getElementById(`workspaceSearchClear`);t&&(t.style.display=`none`);let n=document.getElementById(`workspaceToolbar`);if(n){n.classList.remove(`search-focused`);let e=n.querySelector(`.workspace-search-box`);e&&e.classList.remove(`search-box-expanded`)}}var ey=0;async function ty(){let e=++ey;if(N.agentPlatform?.connected!==!0){ln(),$v();return}await gv();let t=rh;ln();let n=null;try{n=await bn()}catch(e){a.warn(`[WorkspacePanel] resolve root for session failed:`,e?.message||e)}if(e!==ey||t&&n&&t===n)return;$v();let r=document.getElementById(`workspacePreviewArea`);if(r&&r.dataset.previewPath&&(Sh=!1,await K_(!0)),await Promise.resolve(),e!==ey)return;let i=document.getElementById(`workspacePanel`);!i||!i.classList.contains(`expanded`)||await Jh()}async function ny(e,t){document.dispatchEvent(new CustomEvent(`session-workdir-changed`,{detail:{sessionId:e,workdir:t}}))}async function ry(e){N.defaultWorkdir=e,N.agentPlatform&&={...N.agentPlatform,workdir:e};try{let{activeAgentId:t}=await chrome.storage.local.get([`activeAgentId`]);t&&(N.agentWorkdirs.set(t,e),typeof window.updateAgentItemWorkdir==`function`&&window.updateAgentItemWorkdir(t,e))}catch(e){a.debug(`[WorkspacePanel] sync dropdown column table workdir failed:`,e)}}async function iy(e){let t=await un(e,{sessionId:null});return t.success?(await ry(t.workdir),await ny(null,t.workdir),L(r(`workspace.setAsDefaultDone`,{path:t.workdir}),`success`),!0):(L(r(`workspace.switchFailedWithError`,{error:t.error||r(`workspace.unknownError`)}),`error`),!1)}async function ay(e,t={}){let n=t.sessionId===void 0?N.activeSessionId||null:t.sessionId,i=t.setAsDefault===!0,o=await un(e,{sessionId:n});if(!o.success)return L(r(`workspace.switchFailedWithError`,{error:o.error||r(`workspace.unknownError`)}),`error`),!1;if(n)try{let{setSessionWorkdirBinding:e}=await M(async()=>{let{setSessionWorkdirBinding:e}=await import(`./session-store-DKG2vsne.js`).then(e=>e.g);return{setSessionWorkdirBinding:e}},__vite__mapDeps([2,1,3,4])),t=(await Cn())?.id||null;await e(n,o.workdir,t)}catch(e){a.warn(`[WorkspacePanel] persist session workdir failed:`,e)}let s=!1;if(i){let e=await un(o.workdir,{sessionId:null});e.success?s=!0:L(r(`workspace.switchFailedWithError`,{error:e.error||r(`workspace.unknownError`)}),`error`)}return(!n||i)&&await ry(o.workdir),await ny(n,o.workdir),L(r(s?`workspace.switchedToAndSetDefault`:`workspace.switchedTo`,{path:o.workdir}),`success`),!0}async function oy(e,t={}){if(!e)return!1;let{unbindSessionWorkdirRemote:n}=await M(async()=>{let{unbindSessionWorkdirRemote:e}=await import(`./session-store-DKG2vsne.js`).then(e=>e.Ft);return{unbindSessionWorkdirRemote:e}},__vite__mapDeps([2,1,3,4]));if(await n(e)===null&&t.sessionSupported)return L(r(`workspace.switchFailedWithError`,{error:r(`workspace.unknownError`)}),`error`),!1;try{let{setSessionWorkdirBinding:t}=await M(async()=>{let{setSessionWorkdirBinding:e}=await import(`./session-store-DKG2vsne.js`).then(e=>e.g);return{setSessionWorkdirBinding:e}},__vite__mapDeps([2,1,3,4]));await t(e,null,null)}catch(e){a.warn(`[WorkspacePanel] clear session workdir failed:`,e)}return await ny(e,``),L(r(`workdirTag.restoredDefault`),`success`),!0}async function sy(e,t,n){let i=t,a=``,o=t.lastIndexOf(`.`);n!==`directory`&&o>0&&(i=t.substring(0,o),a=t.substring(o));let s=await Zv(r(n===`directory`?`workspace.renameDir`:`workspace.renameFile`),i,r(`workspace.inputNewName`));if(!s||s===i)return;let c=s+a;try{let t=await fn(e,c);t.success?(L(r(`workspace.renamedTo`,{name:c}),`success`),rg(K),await yv(),fy(c)):L(r(`workspace.renameFailedWithError`,{error:t.error}),`error`)}catch(e){L(r(`workspace.renameFailedWithError`,{error:e.message}),`error`)}}async function cy(){if(!K)return;let e=await Zv(r(`workspace.newFolderTitle`),``,r(`workspace.inputFolderName`));if(!e)return;let t=ng(`${K}/${e}`);try{let n=await Tn(t);n.success?(L(r(`workspace.folderCreated`,{name:e}),`success`),rg(K),await yv(),fy(e)):L(r(`workspace.createFailedWithError`,{error:n.error}),`error`)}catch(e){L(r(`workspace.createFailedWithError`,{error:e.message}),`error`)}}async function ly(e){return new Promise((t,n)=>{let i=new Image,a=URL.createObjectURL(e);i.onload=()=>{URL.revokeObjectURL(a);let n=new FileReader;n.onloadend=()=>{let e=n.result,r=i.width,a=i.height,o=Math.max(r,a),s,c;o<=768?(s=o,c=.75):o<=1280?(s=768,c=.7):o<=2560?(s=1024,c=.65):o<=3840?(s=1280,c=.6):(s=1280,c=.55);let l=r,u=a;o>s&&(r>a?(u=Math.round(s/r*a),l=s):(l=Math.round(s/a*r),u=s));let d=document.createElement(`canvas`);d.width=l,d.height=u;let f=d.getContext(`2d`);f.imageSmoothingEnabled=!0,f.imageSmoothingQuality=`high`,f.drawImage(i,0,0,l,u),t({originalUrl:e,compressedUrl:d.toDataURL(`image/jpeg`,c)})},n.readAsDataURL(e)},i.onerror=()=>{URL.revokeObjectURL(a),n(Error(r(`workspace.imageLoadFailed`)))},i.src=a})}async function uy(e){let t=[],n=[];for(let r of e){let e=r&&typeof r==`object`,i=e?r.fullPath||r.path:r,a=i.split(/[\\/]/).pop(),o;e?o=r:(o=Dh.find(e=>e.path===i),o||=Rv.find(e=>e.fullPath===i));let s=o?o.size:0,c=wn(a);if(c.startsWith(`image/`)&&N.enableImageInput)n.push({name:a,size:s,type:c,path:i});else{let e={name:a,size:s,type:c,text:``,status:`done`,agentPath:i};t.push(e)}}for(let e of n)try{let t=await Cn();if(t){let n=await fetch(`${t.url}/api/fs/download-stream`,{method:`POST`,headers:{"Content-Type":`application/json`,...An(t)},body:JSON.stringify({path:e.path})});if(n.ok){let{originalUrl:e,compressedUrl:t}=await ly(await n.blob());N.attachedImages.some(e=>e.compressedUrl===t)||N.attachedImages.push({originalUrl:e,compressedUrl:t})}}}catch{}for(let e of t)N.attachedFiles.some(t=>t.name===e.name&&t.agentPath===e.agentPath)||N.attachedFiles.push(e);km(),Zm();let i=t.length+n.length;i>0&&(!N.enableImageInput&&t.some(e=>e.type?.startsWith(`image/`))?L(r(`workspace.addedFilesToQuestionNoImage`,{count:i}),`success`):L(r(`workspace.addedFilesToQuestion`,{count:i}),`success`))}async function dy(){q.size!==0&&await uy(Array.from(q))}function fy(e,t=0){let n=document.getElementById(`workspacePanelContent`);if(!n)return;if(sg){let t=sg.sorted.findIndex(t=>t.name===e);if(t>=0){let r=sg.itemHeight;n.scrollTop=Math.max(0,t*r-n.clientHeight/2+r/2),ug();let i=Array.from(n.querySelectorAll(`.workspace-file-item`)).find(t=>t.dataset.name===e);i&&(i.classList.add(`highlight-new`),setTimeout(()=>i.classList.remove(`highlight-new`),2e3));return}}let r=Array.from(n.querySelectorAll(`.workspace-file-item`)).find(t=>t.dataset.name===e);r?(r.scrollIntoView({behavior:`smooth`,block:`center`}),r.classList.add(`highlight-new`),setTimeout(()=>r.classList.remove(`highlight-new`),2e3)):t<5&&setTimeout(()=>fy(e,t+1),150)}function py(){let e=document.getElementById(`workspaceAskBtn`);q.size===0?e.style.display=`none`:e.style.display=``}function my(){let e=document.getElementById(`workspaceDownloadDirBtn`),t=document.getElementById(`workspaceBatchDeleteBtn`),n=document.getElementById(`workspaceSelectedCount`);q.size===0?(e.style.display=`none`,t.style.display=`none`,n.style.display=`none`):(e.style.display=``,t.style.display=``,n.style.display=``,n.textContent=r(`workspace.selectedCount`,{count:q.size}),e.disabled=yh),py()}n(`zh`,{artifacts:{btnTitle:`文件产物({count})`,modalTitle:`本次任务的文件产物`,emptyHint:`本次任务没有产生文件产物`,fileCol:`文件`,sizeCol:`大小`,typeCol:`类型`,timeCol:`时间`,actionCol:`操作`,locate:`定位到文件`,preview:`预览`,closeBtn:`关闭`,typeWrite:`写入`,typeDelete:`删除`,typeCreate:`创建`,typeEdit:`编辑`,typeOther:`操作`,noWorkspace:`无法获取工作目录,请确认 Agent 已连接`,locateFailed:`定位文件失败`,fileNotFound:`目录已定位,但未找到该文件(可能已被删除)`,previewFailed:`预览文件失败`,previewNotSupported:`此文件类型不支持预览`,totalCount:`共 {count} 个文件`,badgeLabel:`产物`,download:`下载`,downloadFailed:`下载失败`,copyFileName:`复制文件名`,copyFilePath:`复制文件路径`,copiedName:`已复制文件名:{name}`,copiedPath:`已复制文件路径`,dblClickHint:`双击文件名可预览`,sortHint:`点击排序`,serialCol:`序号`}}),n(`en`,{artifacts:{btnTitle:`Artifacts ({count})`,modalTitle:`File Artifacts of This Task`,emptyHint:`No file artifacts produced in this task`,fileCol:`File`,sizeCol:`Size`,typeCol:`Type`,timeCol:`Time`,actionCol:`Actions`,locate:`Locate File`,preview:`Preview`,closeBtn:`Close`,typeWrite:`Write`,typeDelete:`Delete`,typeCreate:`Create`,typeEdit:`Edit`,typeOther:`Op`,noWorkspace:`Unable to access working directory. Please confirm the Agent is connected.`,locateFailed:`Failed to locate file`,fileNotFound:`Directory located, but file not found (may have been deleted)`,previewFailed:`Failed to preview file`,previewNotSupported:`Preview not supported for this file type`,totalCount:`{count} files in total`,badgeLabel:`Artifacts`,download:`Download`,downloadFailed:`Download failed`,copyFileName:`Copy File Name`,copyFilePath:`Copy File Path`,copiedName:`Copied file name: {name}`,copiedPath:`File path copied`,dblClickHint:`Double-click to preview`,sortHint:`Click to sort`,serialCol:`#`}});function hy(e){let t=(e||``).replace(/\\/g,`/`).replace(/\/+/g,`/`),n=t.replace(/\/+$/,``);return n?/^[A-Za-z]:$/.test(n)?n+`/`:n:t?`/`:``}function gy(e){if(!e)return``;let t=hy(e).replace(/\/+$/,``).split(`/`);return t[t.length-1]||``}function _y(e){if(!e)return``;let t=gy(e),n=t.lastIndexOf(`.`);return n>0?t.substring(n+1).toLowerCase():``}function vy(e){return String(e??``).replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`)}function yy(e,t){let n=new Set(t),r=[],i=0,a=``;for(let t of e)t===`{`?i++:t===`}`&&(i=Math.max(0,i-1)),i===0&&n.has(t)?(r.push(a),a=``):a+=t;return r.push(a),r}function by(e){let t=e.indexOf(`{`);if(t===-1)return[e];let n=0,r=-1;for(let i=t;i<e.length;i++)if(e[i]===`{`)n++;else if(e[i]===`}`&&(n--,n===0)){r=i;break}if(r===-1)return[e];let i=e.substring(0,t),a=e.substring(t+1,r),o=e.substring(r+1),s=yy(a,`,`).map(e=>e.trim());if(s.length<=1)return[e];let c=[];for(let e of s)for(let t of by(e))for(let e of by(o))c.push(i+t+e);return c}function xy(e,t){let n=[],r=new Set;for(let i of e)if(i)for(let e of by(i)){if(!e)continue;let i=t(e);!i||r.has(i)||(r.add(i),n.push(i))}return n}function Sy(e){if(!e)return null;let t=e;if(typeof t==`string`)try{t=JSON.parse(t)}catch{let e=t.match(/["']?path["']?\s*[:=]\s*["']([^"']+)["']/i);return e?e[1]:null}return t&&typeof t==`object`&&(t.path||t.filePath||t.file_path||t.result?.path)||null}function Cy(e){let t=[],n=0,r=``;for(let i=0;i<e.length;i++){let a=e[i];if(a===`{`?n++:a===`}`&&(n=Math.max(0,n-1)),n===0&&a===`<`&&e[i+1]===`<`){let t=wy(e,i);if(t>i){r+=e.substring(i,t),i=t-1;continue}}n===0&&a===`;`?(t.push(r),r=``):n===0&&a===`&`&&e[i+1]===`&`?(t.push(r),r=``,i++):r+=a}return t.push(r),t}function wy(e,t){let n=e.substring(t).match(/^<<-?\s*['"]?([A-Za-z_][A-Za-z0-9_]*)['"]?/);if(!n)return-1;let r=n[1],i=t+n[0].length,a=e.substring(i),o=RegExp(`\\n\\s*`+r.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)+`\\s*(?=\\n|$)`),s=a.match(o);return s?i+s.index+s[0].length:-1}function Ty(e){let t=hy(e||``).replace(/\/$/,``);if(!t)return``;let n=t.lastIndexOf(`/`);return n>0?t.substring(0,n):``}var Ey=new Set([`du`,`df`,`stat`,`wc`,`file`,`cat`,`head`,`tail`,`grep`,`rg`]);function Dy(e){if(!e||typeof e!=`string`)return!1;let t=Cy(e);if(t.length===0)return!1;for(let e of t){let t=e.trim().split(/\s+/).filter(Boolean);for(;t.length&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(t[0]);)t.shift();if(!t.length)continue;let n=t[0].split(`/`).pop().toLowerCase();if(n===`sudo`&&t.length>1&&(n=t[1].split(`/`).pop().toLowerCase()),!Ey.has(n))return!1}return!0}function Oy(e,t){let n=t=>e===t||e.startsWith(t.endsWith(`/`)?t:t+`/`);return[...t].some(n)}function ky(e,t){if(!e||typeof e!=`string`)return t||``;let n=t||``;for(let t of Cy(e)){let e=t.trim().match(/^cd\s+(.+?)\s*$/);if(!e)continue;let r=e[1].trim().replace(/^['"]|['"]$/g,``);n=r.startsWith(`/`)||r.startsWith(`~/`)?r:r===`..`?n?hy(n).replace(/\/[^/]+$/,``)||`/`:`..`:hy(n?n.replace(/\/$/,``)+`/`+r:r)}return n}function Ay(e,t){if(!e||typeof e!=`string`)return[];let n=[],r=t||``,i=Cy(e);for(let e of i){let t=e.trim();if(!t)continue;let i=t.replace(/"[^"]*"/g,`""`).replace(/'[^']*'/g,`''`),a=t.match(/^cd\s+(.+?)\s*$/);if(a){let e=a[1].trim().replace(/^['"]|['"]$/g,``);r=e.startsWith(`/`)||e.startsWith(`~/`)?e:e===`..`?r?hy(r).replace(/\/[^/]+$/,``)||`/`:`..`:hy(r?r.replace(/\/$/,``)+`/`+e:e);continue}let o=e=>(e=e.replace(/^['"]|['"]$/g,``),!e.startsWith(`/`)&&!e.startsWith(`~/`)&&r&&(e=hy(r.replace(/\/$/,``)+`/`+e)),hy(e)),s=t.match(/^(\S+)\s+.*<<-?\s*['"]?([A-Za-z_][A-Za-z0-9_]*)['"]?\s*\n([\s\S]*?)\n\s*\2\s*$/);if(s){let e=s[1].split(`/`).pop().toLowerCase(),t=s[3],r=null;if(/^python[\d.]*$/.test(e)?r=`py`:/^(ba)?sh$/.test(e)&&(r=`sh`),r){for(let e of jy(t,r))e&&n.push({path:o(e),isDir:!1});continue}}let c=i.match(/^mkdir\s+(?:-[a-z]+\s+)*(.+?)$/);if(c){let e=xy(yy(c[1],` `).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`-`)&&e!==`""`&&e!==`''`),o);for(let t of e)n.push({path:t,isDir:!0});continue}let l=i.match(/^touch\s+(.+)$/);if(l){let e=xy(yy(l[1],` `).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`-`)&&e!==`""`&&e!==`''`),o);for(let t of e)n.push({path:t,isDir:!1});continue}let u=null,d=i.match(/\s[>]{1,2}\s*['"]?([^\s|&;'"]+)['"]?\s*$/);if(d&&(u=d[1]),!u){let e=i.match(/^cat\s+>\s*['"]?([^\s|&;'"]+)['"]?/);e&&(u=e[1])}if(!u){let e=t.match(/^cp\s+(?:-[a-zA-Z]+\s+)*(?:.+?\s+)+?['"]?([^\s|&;'"]+)['"]?\s*$/);e&&(u=e[1])}if(!u){let e=i.match(/tee\s+(?:-[a-zA-Z]+\s+)*['"]?([^\s|&;'"]+)['"]?/);e&&(u=e[1])}if(u){let e=xy([u],o);for(let t of e)n.push({path:t,isDir:!1})}}return n}function jy(e,t){if(!e||typeof e!=`string`)return[];let n=[],r=e.split(`
|
|
1207
1207
|
`);if([`sh`,`bash`,`zsh`].includes(t))for(let e of r){let t=e.trim();if(!t||t.startsWith(`#`))continue;let r=[...t.matchAll(/[>]{1,2}\s*['"]?([^\s|&;>'"]+)['"]?/g)];for(let e of r)e[1]&&!e[1].startsWith(`/dev/`)&&n.push(e[1]);let i=t.match(/^mkdir\s+(?:-[a-z]+\s+)*(.+?)$/);if(i){let e=yy(i[1],` `).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`-`));n.push(...e)}let a=t.match(/^touch\s+(.+)$/);if(a){let e=yy(a[1],` `).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`-`));n.push(...e)}let o=t.match(/^cp\s+(?:-[a-zA-Z]+\s+)*(?:.+?\s+)+?['"]?([^\s|&;'"]+)['"]?\s*$/);o&&n.push(o[1]);let s=t.match(/tee\s+(?:-[a-zA-Z]+\s+)*['"]?([^\s|&;'"]+)['"]?/);s&&n.push(s[1])}else if(t===`bat`||t===`cmd`)for(let e of r){let t=e.trim().replace(/^@/,``);if(!t||(t.toUpperCase(),/^REM\b/i.test(t)||t.startsWith(`::`))||/^ECHO\b/i.test(t)&&!/[>]{1,2}/.test(t))continue;let r=[...t.matchAll(/[>]{1,2}\s*"?([^\s|&;>"]+)"?/g)];for(let e of r)e[1]&&e[1].toUpperCase()!==`NUL`&&n.push(e[1]);let i=t.match(/^(?:mkdir|md)\s+(?:"([^"]+)"|(\S+))/i);i&&n.push(i[1]||i[2]);let a=t.match(/^copy\s+(?:\/\S+\s+)*(?:.+?\s+)+?"?([^\s|&;"]+)"?\s*$/i);a&&n.push(a[1]);let o=t.match(/^xcopy\s+(?:\/\S+\s+)*(?:"[^"]+"|\S+)\s+(?:"([^"]+)"|(\S+))/i);o&&n.push(o[1]||o[2])}else if(t===`ps1`)for(let e of r){let t=e.trim();if(!t||t.startsWith(`#`))continue;let r=[...t.matchAll(/[>]{1,2}\s*"?([^\s|;>'"]+)"?/g)];for(let e of r)e[1]&&e[1].toUpperCase()!==`NUL`&&n.push(e[1]);let i=t.match(/(?:Set-Content|Out-File|Add-Content)\s+(?:-[\w]+\s+)*"?([^";\s|]+)"?/i);i&&n.push(i[1]);let a=t.match(/New-Item\s+(?:-[\w]+\s+)*-Path\s+"?([^";\s|]+)"?/i);a&&n.push(a[1]);let o=t.match(/New-Item\s+"?([^";\s|]+)"?\s+(?:-[\w]+\s+)*-ItemType/i);o&&n.push(o[1]);let s=t.match(/Copy-Item\s+(?:-[\w]+\s+)*"?([^";\s|]+)"?\s+(?:-[\w]+\s+)*-Destination\s+"?([^";\s|]+)"?/i);s&&n.push(s[2]);let c=t.match(/Move-Item\s+(?:-[\w]+\s+)*"?([^";\s|]+)"?\s+(?:-[\w]+\s+)*-Destination\s+"?([^";\s|]+)"?/i);c&&n.push(c[2])}else if(t===`py`)for(let e of r){let t=e.trim();if(!t||t.startsWith(`#`))continue;let r=t.match(/open\s*\(\s*['"]([^'"]+)['"]\s*,\s*['"][wax][+]?['"]/);r&&n.push(r[1]);let i=t.match(/os\.(?:makedirs|mkdir)\s*\(\s*['"]([^'"]+)['"]/);i&&n.push(i[1]);let a=t.match(/shutil\.(?:copy2?|move)\s*\([^,]+,\s*['"]([^'"]+)['"]/);a&&n.push(a[1]);let o=t.match(/Path\s*\(\s*['"]([^'"]+)['"]\s*\)\s*\.\s*(?:write_text|write_bytes|touch|mkdir)/);o&&n.push(o[1])}let i=new Set;return n.filter(e=>!e||i.has(e)||(i.add(e),/\$[\w({]|%[\w]+%/.test(e))?!1:e.includes(`/`)||e.includes(`\\`)||e.includes(`.`))}function My(e,t,n){if(!e||typeof e!=`string`||e.startsWith(`{`)||e.startsWith(`[`))return[];let r=e.split(/\s+/).filter(Boolean);if(r.length===0)return[];let i=new Set([`total`,`.`,`..`,`...`,`.git`,`.DS_Store`,`node_modules`,`__pycache__`,`.learnings`,`dist`,`.trae`]),a=r.some(e=>/^[d-][rwx-]{9}[@+*]?$/.test(e)),o=n?[...n.matchAll(/find\b[\s\S]*?-type\s+([df])/g)].map(e=>e[1]):[],s=o.length===1?o[0]:null,c=/[<>"'`|&;()[\]*?#!]/,l=new Map,u=(e,t)=>{!e||i.has(e)||/^\d+$/.test(e)||c.test(e)||(!l.has(e)||t)&&l.set(e,t)},d=e=>e.startsWith(`/`)?hy(e):hy((t?t.replace(/\/$/,``)+`/`:``)+e),f=e=>!(e.split(`/`).pop()||``).includes(`.`);if(r.some(e=>/^\.\/([^:]+):$/.test(e)&&e.length>3)){let e=new Set;for(let t of r){let n=t.match(/^\.\/([^:]+):$/);n&&n[1]&&e.add(n[1])}let t=null;for(let n of r){let r=n.match(/^\.\/([^:]+):$/);if(r&&r[1]){t=r[1],u(t,!0);continue}if(n.startsWith(`./`)){let t=n.slice(2);t&&!i.has(t)&&u(t,e.has(t)||f(t)&&s!==`f`);continue}if(!(i.has(n)||n.startsWith(`-`)||a||n.endsWith(`...`)))if(t===null)(n.includes(`.`)||e.has(n))&&u(n,e.has(n));else{if(n.includes(`/`)){u(n,e.has(n)||f(n));continue}let r=t+`/`+n;u(r,e.has(r)||f(r))}}}else for(let e of r){if(i.has(e)||e.startsWith(`-`)||e.startsWith(`=`)||e.endsWith(`...`)||e.includes(`:`)||e.includes(`=`)||/^\d+$/.test(e)||/^[\d.]+[KMGTPE]?B?$/i.test(e))continue;let t=null;if(e.startsWith(`./`)){if(e.length<=2)continue;t=e.slice(2)}else if(a)continue;else{if(!e.includes(`/`)&&!/^.+\.[a-zA-Z0-9]+$/.test(e))continue;t=e}!t||i.has(t)||u(t,f(t)&&s!==`f`)}let p=[];for(let[e,t]of l)p.push({path:d(e),isDir:t});return p}function Ny(e){if(!e||typeof e!=`string`)return[];let t=[],n=/cat\s+>\s*['"]?(\S+)['"]?\s*<<-?\s*['"]?([A-Za-z_][A-Za-z0-9_]*)['"]?\s*\n([\s\S]*?)\n\s*\2\s*(?=\n|$)/g,r;for(;(r=n.exec(e))!==null;){let e=r[1],n=_y(e);[`sh`,`bash`,`zsh`,`bat`,`cmd`,`ps1`,`py`].includes(n)&&t.push({path:hy(e),content:r[3],ext:n})}return t}function Py(e,t){if(!e||typeof e!=`string`)return null;let n=e.trim();for(let e of t){let t=gy(e).replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),r=e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),i=e.replace(/\//g,`\\`).replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);if(RegExp(`(?:^|[;\\s&|])(?:ba)?sh\\s+.*${t}|(?:^|[;\\s&|])python[23]?\\s+.*${t}|(?:^|[;\\s&|])node\\s+.*${t}|(?:^|[;\\s&|])\\.?/${t}|(?:^|[;\\s&|])cmd(?:\\.exe)?\\s+(?:/c|/k)\\s+.*${t}|(?:^|[;\\s&|])(?:powershell|pwsh)(?:\\.exe)?\\s+(?:-[\w-]+\\s+)*-File\\s+.*${t}|(?:^|[;\\s&|])${r}|(?:^|[;\\s&|])${i}`).test(n))return e}return null}function Fy(e,t){if(!e||typeof e!=`string`)return[];let n=[],r=t||``,i=e=>(e=e.replace(/^['"]|['"]$/g,``),!e.startsWith(`/`)&&!e.startsWith(`~/`)&&!/^[A-Za-z]:[\\/]/.test(e)&&r&&(e=hy(r.replace(/\/$/,``)+`/`+e)),hy(e)),a=Cy(e);for(let e of a){let t=e.trim();if(!t)continue;let a=t.match(/^cd\s+(?:\/[dD]\s+)?(.+?)\s*$/);if(a){let e=a[1].trim().replace(/^['"]|['"]$/g,``);r=e.startsWith(`/`)||/^[A-Za-z]:/.test(e)?hy(e):e.startsWith(`~/`)?e:e===`..`?r?hy(r).replace(/\/[^/]+$/,``)||`/`:`..`:hy(r?r.replace(/\/$/,``)+`/`+e:e);continue}let o=t.match(/^rm\s+((?:-[a-zA-Z]+\s+)*)(.+)$/);if(o){let e=o[1],t=o[2],r=/r|R/i.test(e),a=xy(yy(t,` `).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`-`)),i);for(let e of a)n.push({path:e,isDir:r});continue}let s=t.match(/^(?:del|erase)\s+((?:\/[a-zA-Z]+\s+)*)(.+)$/i);if(s){s[1];let e=s[2],t=xy(yy(e,` `).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`/`)),i);for(let e of t)n.push({path:e,isDir:!1});continue}let c=t.match(/^(?:rmdir|rd)\s+((?:\/[a-zA-Z]+\s+)*)(.+)$/i);if(c){let e=c[1],t=c[2],r=/s|S/i.test(e),a=xy(yy(t,` `).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`/`)),i);for(let e of a)n.push({path:e,isDir:r});continue}let l=t.match(/^Remove-Item\s+((?:-[\w-]+\s+)*(?:"[^"]+"|\S+)?(?:\s+(?:-[\w-]+\s+)*(?:"[^"]+"|\S+))*)/i);if(l){let e=l[1],t=/-Recurse/i.test(e),r=xy([...e.matchAll(/(?:"([^"]+)"|(?<![-\/])(\S+))/g)].map(e=>e[1]||e[2]).filter(e=>e&&!e.startsWith(`-`)),i);for(let e of r)n.push({path:e,isDir:t});continue}}return n}function Iy(e){if(!Array.isArray(e)||e.length===0)return[];let t=[],n=new Set,r=[...e].sort((e,t)=>new Date(e.timestamp||0)-new Date(t.timestamp||0)),i=new Map;for(let e of r)if(!(e.nodeType!==`tool_exec`||e.status===`failed`)){if(e.action?.name===`agent_file`){let t=e.action.params;if(typeof t==`string`)try{t=JSON.parse(t)}catch{continue}if(!t||t.action!==`write`||typeof t.content!=`string`)continue;let n=hy(t.path||t.filePath||``),r=_y(n);[`sh`,`bash`,`zsh`,`bat`,`cmd`,`ps1`,`py`].includes(r)&&i.set(n,{content:t.content,ext:r})}else if(e.action?.name===`agent_exec`){let t=e.action.params,n=typeof t==`string`?t:t&&typeof t==`object`?t.command:null;if(typeof n==`string`)for(let e of Ny(n))i.has(e.path)||i.set(e.path,{content:e.content,ext:e.ext})}}let a=[...i.keys()],o=new Map,s=(e,t)=>!t||e==null||t.timestamp==null?!0:new Date(t.timestamp||0).getTime()>=new Date(e||0).getTime(),c=new Set,l=!1;for(let e of r){if(e.nodeType!==`tool_exec`||!e.action)continue;let r=e.action.name||``,s=e.action.params;if(s==null)continue;if(typeof s==`string`)try{s=JSON.parse(s)}catch{continue}if(typeof s!=`object`)continue;if(r===`agent_exec`){let u=s.command||``;if(!u)continue;let d=Py(u,a);if(d&&e.status!==`failed`){let a=i.get(d);if(a){let i=jy(a.content,a.ext);for(let a of i){if(!a)continue;let i=(a.startsWith(`/`),hy(a));if(n.has(i)){let e=t.findIndex(e=>e.path===i);e>=0&&t.splice(e,1)}n.add(i),t.push({path:i,fileName:gy(i),toolName:r,action:`typeCreate`,size:0,timestamp:e.timestamp||null,status:e.status||`unknown`,type:`file`})}}}if(e.status!==`failed`){let t=Fy(u,s.cwd);for(let n of t)o.set(n.path,{isDir:n.isDir,timestamp:e.timestamp})}let f=Ay(u,s.cwd);for(let e of f)if(e&&e.path){let t=e.isDir?e.path:Ty(e.path);t&&c.add(t)}for(let i of f){let a=i&&i.path;if(a){if(n.has(a)){let e=t.findIndex(e=>e.path===a);e>=0&&t.splice(e,1)}n.add(a),e.status!==`failed`&&t.push({path:a,fileName:gy(a),toolName:r,action:`typeCreate`,size:0,timestamp:e.timestamp||null,status:e.status||`unknown`,type:i.isDir?`directory`:`file`})}}let p=f.length>0||!!d||/<<-?/.test(u);if(e.status!==`failed`&&typeof e.observation==`string`){let i=ky(u,s.cwd);/\bcd\s/.test(u)&&i&&(p||l)&&c.add(hy(i));let a=My(e.observation,i,u);a.length>0&&!p&&(a=Dy(u)?[]:a.filter(e=>Oy(e.path,c)));for(let i of a){if(n.has(i.path)){let e=t.findIndex(e=>e.path===i.path);e>=0&&t.splice(e,1)}n.add(i.path),t.push({path:i.path,fileName:gy(i.path),toolName:r,action:`typeCreate`,size:0,timestamp:e.timestamp||null,status:e.status||`unknown`,type:i.isDir?`directory`:`file`})}}e.status!==`failed`&&p&&(l=!0);continue}let u=null,d=`typeOther`;if(r===`agent_file`){let t=s.action;if(t===`write`)u=s.path||s.filePath,d=`typeWrite`;else if(t===`delete`){let t=hy(s.path||s.filePath||``);t&&e.status!==`failed`&&o.set(t,{isDir:!1,timestamp:e.timestamp});continue}else continue}else if(r===`file_upload`)u=s.path||s.filePath||s.filename,d=`typeCreate`;else if(r===`download_file`)continue;else s.file_path&&(s.content!==void 0||s.action===`write`||s.action===`create`)&&(u=s.file_path,d=s.action===`create`?`typeCreate`:`typeWrite`);if(!u)continue;let f=hy(Sy(e.observation)||u);if(!f)continue;if(n.has(f)){let e=t.findIndex(e=>e.path===f);e>=0&&t.splice(e,1)}if(n.add(f),e.status===`failed`)continue;let p=Ty(f);p&&c.add(p),l=!0;let m=0;if(e.observation){let t=e.observation;if(typeof t==`string`)try{t=JSON.parse(t)}catch{}t&&typeof t==`object`&&(m=t.size||t.fileSize||t.file_size||0)}t.push({path:f,fileName:gy(f),toolName:r,action:d,size:m,timestamp:e.timestamp||null,status:e.status||`unknown`,type:`file`})}if(o.size>0){let e=[...o.keys()],n=(e,t)=>{if(e===t)return!0;let n=e.startsWith(`/`),r=t.startsWith(`/`);return n&&!r?e.endsWith(`/`+t)||e.endsWith(t):r&&!n?t.endsWith(`/`+e)||t.endsWith(e):!1};for(let r of t)r.deleted||(o.has(r.path)&&s(r.timestamp,o.get(r.path))||e.some(e=>{let t=o.get(e);return s(r.timestamp,t)?n(r.path,e)?!0:t&&t.isDir&&(r.path.startsWith(e+`/`)||r.path.startsWith(e+`\\`)):!1}))&&(r.deleted=!0)}return t.filter(e=>e&&e.fileName)}function Ly(e){if(!e||typeof e!=`string`)return[];let t=[],n=new Set,r=/\[\[artifact:([^\]|]+)(?:\|([^\]]*))?\]\]/g,i;for(;(i=r.exec(e))!==null;){let e=(i[1]||``).trim(),r=(i[2]||``).trim();if(!e||/\$\{?[A-Za-z_][A-Za-z0-9_]*\}?|%[A-Za-z0-9_]+%/.test(e))continue;let a=Ry(e);!a||n.has(a)||(n.add(a),t.push({path:e,note:r}))}return t}function Ry(e){return hy(e).replace(/^\.\//,``)}function zy(e,t){let n=(e||[]).map(e=>({...e,source:e.source||`static`})),r=n.map(e=>Ry(e.path));for(let e of t||[]){let t=Ry(e.path);if(!t)continue;let i=gy(e.path);if(!i)continue;let a=r.indexOf(t);if(a===-1&&(a=r.findIndex(e=>e.endsWith(`/`+t))),a!==-1){let t=n[a];t&&e.note&&!t.note&&(t.note=e.note);continue}r.push(t),n.push({path:e.path,fileName:i,toolName:`declared`,action:`typeCreate`,size:0,timestamp:null,status:`unknown`,type:`file`,source:`declared`,note:e.note||``})}return n}function By(e,t){return zy(Iy(e),Ly(t))}function Vy(e){try{return pn(e)}catch{return!1}}var Hy=null,Uy=null,Wy=null,Gy=1;function Ky(e){if(!e)return`—`;let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${n(t.getHours())}:${n(t.getMinutes())}:${n(t.getSeconds())}`}function qy(e){if(!Wy)return e;let t=Gy;return[...e].sort((e,n)=>{let r,i;return Wy===`name`?(r=(e.fileName||e.path||``).toLowerCase(),i=(n.fileName||n.path||``).toLowerCase()):Wy===`type`?(r=e.type||`file`,i=n.type||`file`):(r=new Date(e.timestamp||0).getTime(),i=new Date(n.timestamp||0).getTime()),r<i?-t:r>i?t:0})}function Jy(e,t){let n=vn(e.fileName,e.type),i=r(`artifacts.${e.action}`),a=Ky(e.timestamp),o=Vy(e.fileName),s=`${vy(e.path)} · ${r(`artifacts.dblClickHint`)}`;return`
|
|
1208
1208
|
<tr class="artifacts-row" data-idx="${t}" data-path="${vy(e.path)}" data-name="${vy(e.fileName)}">
|
|
1209
1209
|
<td class="col-index">${t+1}</td>
|
|
@@ -1242,7 +1242,7 @@ It is this session's directory or the agent default, so it stays accessible (wor
|
|
|
1242
1242
|
</button>`:``}
|
|
1243
1243
|
</td>
|
|
1244
1244
|
</tr>
|
|
1245
|
-
`}function Yy(e,t){e.querySelectorAll(`.artifacts-row`).forEach(e=>{let n=t[parseInt(e.dataset.idx,10)];if(!n)return;e.addEventListener(`click`,e=>{e.target.closest(`.artifact-action-btn`)||e.target.closest(`.artifact-copy-btn`)||(clearTimeout(Uy),Uy=setTimeout(()=>{Uy=null,Nv().catch(()=>{}),jv(n.path).catch(e=>{a.error(`[Artifacts] locate failed:`,e)})},250))});let i=e.querySelector(`.artifact-name`);i&&i.addEventListener(`dblclick`,e=>{e.stopPropagation(),e.preventDefault(),clearTimeout(Uy),Uy=null,Vy(n.fileName)&&Mv(n.path,n.fileName).catch(e=>{a.error(`[Artifacts] preview failed:`,e)})});let o=e.querySelector(`.artifact-copy-btn`);o&&o.addEventListener(`click`,async e=>{e.stopPropagation();let t=e.ctrlKey||e.metaKey,i=n.fileName;t&&(i=await Fv(n.path)||n.path),
|
|
1245
|
+
`}function Yy(e,t){e.querySelectorAll(`.artifacts-row`).forEach(e=>{let n=t[parseInt(e.dataset.idx,10)];if(!n)return;e.addEventListener(`click`,e=>{e.target.closest(`.artifact-action-btn`)||e.target.closest(`.artifact-copy-btn`)||(clearTimeout(Uy),Uy=setTimeout(()=>{Uy=null,Nv().catch(()=>{}),jv(n.path).catch(e=>{a.error(`[Artifacts] locate failed:`,e)})},250))});let i=e.querySelector(`.artifact-name`);i&&i.addEventListener(`dblclick`,e=>{e.stopPropagation(),e.preventDefault(),clearTimeout(Uy),Uy=null,Vy(n.fileName)&&Mv(n.path,n.fileName).catch(e=>{a.error(`[Artifacts] preview failed:`,e)})});let o=e.querySelector(`.artifact-copy-btn`);o&&o.addEventListener(`click`,async e=>{e.stopPropagation();let t=e.ctrlKey||e.metaKey,i=n.fileName;t&&(i=await Fv(n.path)||n.path),At(i,o),L(t?r(`artifacts.copiedPath`):r(`artifacts.copiedName`,{name:n.fileName}),`success`)});let s=e.querySelector(`.download-btn`);s&&s.addEventListener(`click`,e=>{e.stopPropagation(),Zy(n)}),e.querySelectorAll(`.locate-btn, .preview-btn`).forEach(e=>{e.addEventListener(`click`,async t=>{if(t.stopPropagation(),e.classList.contains(`locate-btn`)){Nv().catch(()=>{});try{await jv(n.path)}catch(e){a.error(`[Artifacts] locate failed:`,e)}}else if(e.classList.contains(`preview-btn`))try{await Mv(n.path,n.fileName)}catch(e){a.error(`[Artifacts] preview failed:`,e)}})})})}function Xy(e,t){let n=qy(t),r=e.querySelector(`.artifacts-table tbody`);r.innerHTML=n.map((e,t)=>Jy(e,t)).join(``),e.querySelectorAll(`.artifacts-table th.sortable`).forEach(e=>{let t=e.dataset.sort;e.classList.toggle(`sorted-asc`,t===Wy&&Gy===1),e.classList.toggle(`sorted-desc`,t===Wy&&Gy===-1)}),Yy(e,n)}async function Zy(e){let t=null;try{t=e.type===`directory`?await hn([e.path]):await On(e.path)}catch(e){t={success:!1,error:e.message}}if(!t||!t.success){let e=t&&t.error?`: ${t.error}`:``;L(r(`artifacts.downloadFailed`)+e,`error`);return}let n=URL.createObjectURL(t.blob),i=document.createElement(`a`),a=t.name||gy(e.path)||`workspace.zip`;if(e.type===`directory`){let t=gy(e.path);t&&(a=t.replace(/\.zip$/i,``)+`.zip`)}i.href=n,i.download=a,document.body.appendChild(i),i.click(),i.remove(),setTimeout(()=>URL.revokeObjectURL(n),5e3)}function Qy(e,t){if(!t)return!0;let n=hy(e||``);if(!n||n.startsWith(`~/`)||n===`~`)return!1;if(!(n.startsWith(`/`)||/^[a-zA-Z]:\//.test(n)))return!0;let r=n.toLowerCase(),i=t.toLowerCase();return r===i||r.startsWith(i+`/`)}function $y(e,t){return!t||!(e===`~`||e&&e.startsWith(`~/`))?e:hy(e===`~`?t:t+`/`+e.slice(2))}function eb(e,t){let n=e.querySelector(`.artifacts-modal-count`);n&&(n.textContent=r(`artifacts.totalCount`,{count:t.length}))}async function tb(e){if(!e||e.length===0)return!1;let t=null;try{let e=await bn();e&&(t=hy(e))}catch{}let n=null;try{n=await Dn()}catch{}let r=!1;if(t)for(let i=e.length-1;i>=0;i--){let a=e[i];Qy($y(a.path,n),t)||(e.splice(i,1),r=!0)}if(e.length===0)return r;try{let t=new Map;await Promise.all(e.map(async e=>{let n=e.path;try{let t=await Fv(e.path);t&&(n=t)}catch{}t.has(n)||t.set(n,[]),t.get(n).push(e.path)}));let n=[...t.keys()];if(n.length===0)return r;let i=await chrome.runtime.sendMessage({type:`CHECK_FILES_EXIST`,paths:n});if(!i||!i.success||!i.results)return r;let a=new Set;for(let[e,n]of t)if(i.results[e]===!1)for(let e of n)a.add(e);if(a.size>0)for(let t=e.length-1;t>=0;t--)a.has(e[t].path)&&(e.splice(t,1),r=!0)}catch{}return r}function nb(e,t){if(!e)return;let n=e.querySelector(`.artifacts-btn-count`);t>0?(n&&(n.textContent=t),e.title=r(`artifacts.btnTitle`,{count:t}),e.style.display=``):e.style.display=`none`}function rb(e,t){!e||e.length===0||!t||tb(e).then(n=>{n&&nb(t,e.length)}).catch(()=>{})}function ib(e){if(!e)return 0;for(let t=e.length-1;t>=0;t--)e[t].deleted&&e.splice(t,1);return e.length}function ab(e,t){if(ob(),!e)return;for(let t=e.length-1;t>=0;t--)e[t].deleted&&e.splice(t,1);if(e.length===0){nb(t,0);return}Wy=null,Gy=1,Hy=document.createElement(`div`),Hy.className=`artifacts-modal-overlay`,Hy.id=`artifactsModalOverlay`;let n=document.createElement(`div`);n.className=`artifacts-modal`;let i=document.createElement(`div`);i.className=`artifacts-modal-header`,i.innerHTML=`
|
|
1246
1246
|
<div class="artifacts-modal-title">
|
|
1247
1247
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="width:18px;height:18px;color:var(--info-500);">
|
|
1248
1248
|
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
|
|
@@ -1265,7 +1265,7 @@ It is this session's directory or the agent default, so it stays accessible (wor
|
|
|
1265
1265
|
</tr>
|
|
1266
1266
|
</thead>
|
|
1267
1267
|
<tbody></tbody>
|
|
1268
|
-
`,a.appendChild(o);let s=document.createElement(`div`);s.className=`artifacts-modal-footer`;let c=document.createElement(`button`);c.className=`artifacts-modal-close-btn`,c.textContent=r(`artifacts.closeBtn`),c.addEventListener(`click`,ob),s.appendChild(c),n.appendChild(i),n.appendChild(a),n.appendChild(s),Hy.appendChild(n);let l=document.body,u=document.getElementById(`workspacePanelContainer`);if(u&&u.classList.contains(`embedded`)){let e=document.getElementById(`mainLeft`);e&&(Hy.classList.add(`embedded-mode`),e.style.position=`relative`,l=e)}l.appendChild(Hy),document.getElementById(`artifactsModalClose`).addEventListener(`click`,ob);let d=e=>{e.key===`Escape`&&(ob(),document.removeEventListener(`keydown`,d))};document.addEventListener(`keydown`,d),o.querySelectorAll(`th.sortable`).forEach(t=>{t.addEventListener(`click`,()=>{let r=t.dataset.sort;Wy===r?Gy=-Gy:(Wy=r,Gy=1),Xy(n,e)})}),Xy(n,e),tb(e).then(i=>{if(!(!i||!Hy)){if(e.length===0){let t=n.querySelector(`.artifacts-table tbody`);t&&(t.innerHTML=`<tr><td colspan="5" class="artifacts-empty">${r(`artifacts.emptyHint`)}</td></tr>`),eb(n,e)}else eb(n,e),Xy(n,e);nb(t,e.length)}}).catch(()=>{})}function ob(){Uy&&=(clearTimeout(Uy),null),Hy&&=(Hy.remove(),null)}n(`zh`,{promptSelector:{noMatchAgent:`没有匹配的 Agent`,inheritGlobal:`继承全局设置`,editAgentTitle:`编辑此 Agent`,deleteAgentTitle:`删除此 Agent`,noMatchProxy:`没有匹配的代理`,unnamedProxy:`未命名代理`,enableTitle:`启用此代理`,disableTitle:`禁用此代理`,noMatchAll:`没有匹配的 Agent、网页或代理`,noTitle:`无标题`,proxyAddress:`代理地址`,deleteProxyTitle:`删除此代理`,confirmDeleteProxy:`确定要删除此代理吗?`},knowledgeSelector:{disabled:`知识库检索已关闭(可在设置页「知识库」中开启)`,notAvailable:`知识库不可用(请确认代理已连接、检索依赖已安装)`,noCollections:`暂无知识库(可在设置页「知识库」中创建)`,docChunk:`{docs} 文档 · {chunks} 分块`,disabledBadge:`已停用`,disabledTooltip:`已停用(大模型不会自主检索该库),仍可手动 @ 引用`,manualSuffix:`手动引用`}}),n(`en`,{promptSelector:{noMatchAgent:`No matching agent`,inheritGlobal:`Inherit global settings`,editAgentTitle:`Edit this agent`,deleteAgentTitle:`Delete this agent`,noMatchProxy:`No matching proxy`,unnamedProxy:`Unnamed proxy`,enableTitle:`Enable this proxy`,disableTitle:`Disable this proxy`,noMatchAll:`No matching agent, page or proxy`,noTitle:`Untitled`,proxyAddress:`Proxy address`,deleteProxyTitle:`Delete this proxy`,confirmDeleteProxy:`Are you sure you want to delete this proxy?`},knowledgeSelector:{disabled:`Knowledge retrieval is turned off (you can enable it in Settings - Knowledge)`,notAvailable:`Knowledge base unavailable (check the agent connection and installed retrieval dependencies)`,noCollections:`No knowledge base yet (create one in Settings - Knowledge)`,docChunk:`{docs} docs · {chunks} chunks`,disabledBadge:`Disabled`,disabledTooltip:`Disabled (the model won't search this knowledge base autonomously); you can still reference it manually via @`,manualSuffix:`manual`}});var sb=`pages`;async function cb(){try{let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]);return(e.pairedAgents||[]).map(t=>({...t,isActive:t.id===e.activeAgentId,isDisabled:!!t.disabled}))}catch{return[]}}var lb=!1;async function ub(e=``,t=null){let n=document.getElementById(`agentAtSelector`),r=document.getElementById(`agentAtDropdown`);
|
|
1268
|
+
`,a.appendChild(o);let s=document.createElement(`div`);s.className=`artifacts-modal-footer`;let c=document.createElement(`button`);c.className=`artifacts-modal-close-btn`,c.textContent=r(`artifacts.closeBtn`),c.addEventListener(`click`,ob),s.appendChild(c),n.appendChild(i),n.appendChild(a),n.appendChild(s),Hy.appendChild(n);let l=document.body,u=document.getElementById(`workspacePanelContainer`);if(u&&u.classList.contains(`embedded`)){let e=document.getElementById(`mainLeft`);e&&(Hy.classList.add(`embedded-mode`),e.style.position=`relative`,l=e)}l.appendChild(Hy),document.getElementById(`artifactsModalClose`).addEventListener(`click`,ob);let d=e=>{e.key===`Escape`&&(ob(),document.removeEventListener(`keydown`,d))};document.addEventListener(`keydown`,d),o.querySelectorAll(`th.sortable`).forEach(t=>{t.addEventListener(`click`,()=>{let r=t.dataset.sort;Wy===r?Gy=-Gy:(Wy=r,Gy=1),Xy(n,e)})}),Xy(n,e),tb(e).then(i=>{if(!(!i||!Hy)){if(e.length===0){let t=n.querySelector(`.artifacts-table tbody`);t&&(t.innerHTML=`<tr><td colspan="5" class="artifacts-empty">${r(`artifacts.emptyHint`)}</td></tr>`),eb(n,e)}else eb(n,e),Xy(n,e);nb(t,e.length)}}).catch(()=>{})}function ob(){Uy&&=(clearTimeout(Uy),null),Hy&&=(Hy.remove(),null)}n(`zh`,{promptSelector:{noMatchAgent:`没有匹配的 Agent`,inheritGlobal:`继承全局设置`,editAgentTitle:`编辑此 Agent`,deleteAgentTitle:`删除此 Agent`,noMatchProxy:`没有匹配的代理`,unnamedProxy:`未命名代理`,enableTitle:`启用此代理`,disableTitle:`禁用此代理`,noMatchAll:`没有匹配的 Agent、网页或代理`,noTitle:`无标题`,proxyAddress:`代理地址`,deleteProxyTitle:`删除此代理`,confirmDeleteProxy:`确定要删除此代理吗?`},knowledgeSelector:{disabled:`知识库检索已关闭(可在设置页「知识库」中开启)`,notAvailable:`知识库不可用(请确认代理已连接、检索依赖已安装)`,noCollections:`暂无知识库(可在设置页「知识库」中创建)`,docChunk:`{docs} 文档 · {chunks} 分块`,disabledBadge:`已停用`,disabledTooltip:`已停用(大模型不会自主检索该库),仍可手动 @ 引用`,manualSuffix:`手动引用`}}),n(`en`,{promptSelector:{noMatchAgent:`No matching agent`,inheritGlobal:`Inherit global settings`,editAgentTitle:`Edit this agent`,deleteAgentTitle:`Delete this agent`,noMatchProxy:`No matching proxy`,unnamedProxy:`Unnamed proxy`,enableTitle:`Enable this proxy`,disableTitle:`Disable this proxy`,noMatchAll:`No matching agent, page or proxy`,noTitle:`Untitled`,proxyAddress:`Proxy address`,deleteProxyTitle:`Delete this proxy`,confirmDeleteProxy:`Are you sure you want to delete this proxy?`},knowledgeSelector:{disabled:`Knowledge retrieval is turned off (you can enable it in Settings - Knowledge)`,notAvailable:`Knowledge base unavailable (check the agent connection and installed retrieval dependencies)`,noCollections:`No knowledge base yet (create one in Settings - Knowledge)`,docChunk:`{docs} docs · {chunks} chunks`,disabledBadge:`Disabled`,disabledTooltip:`Disabled (the model won't search this knowledge base autonomously); you can still reference it manually via @`,manualSuffix:`manual`}});var sb=`pages`;async function cb(){try{let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]);return(e.pairedAgents||[]).map(t=>({...t,isActive:t.id===e.activeAgentId,isDisabled:!!t.disabled}))}catch{return[]}}var lb=!1;async function ub(e=``,t=null){let n=document.getElementById(`agentAtSelector`),r=document.getElementById(`agentAtDropdown`);Et(),n.style.display=`block`,r.classList.add(`show`),pb(),t?await mb(t):await hb(e),db()}async function db(){try{let[e,t,n,i]=await Promise.all([St(),qb(),cb(),Vb()]),a=document.querySelector(`#agentAtTabs .prompt-tab[data-tab="agents"]`),o=document.querySelector(`#agentAtTabs .prompt-tab[data-tab="pages"]`),s=document.querySelector(`#agentAtTabs .prompt-tab[data-tab="proxies"]`),c=document.querySelector(`#agentAtTabs .prompt-tab[data-tab="knowledge"]`);a&&(a.textContent=r(`promptSelector.agentsCount`,{count:e.length})),o&&(o.textContent=r(`promptSelector.pagesCount`,{count:t.length})),s&&(s.textContent=r(`promptSelector.proxiesCount`,{count:n.length}),s.style.display=n.length>0?``:`none`),c&&(c.textContent=r(`promptSelector.knowledgeCount`,{count:i.collections.length}),c.style.display=i.ok?``:`none`,!i.ok&&sb===`knowledge`&&mb(`pages`))}catch{}}function fb(){let e=document.getElementById(`agentAtSelector`),t=document.getElementById(`agentAtDropdown`);e.style.display=`none`,t.classList.remove(`show`),N.selectedAgentAtIndex=-1,N.selectedPageIndex=-1,N.selectedProxyAtIndex=-1,N.selectedKnowledgeAtIndex=-1}function pb(){let e=document.getElementById(`agentAtDropdown`);if(!e||e.dataset.initialized)return;e.dataset.initialized=`1`,e.addEventListener(`mousedown`,e=>{e.target.closest(`.prompt-item, .prompt-tab, .skill-list-item, .mcp-list-item`)&&e.preventDefault()});let t=document.getElementById(`agentAtTabs`);t&&t.querySelectorAll(`.prompt-tab`).forEach(e=>{e.addEventListener(`click`,()=>{mb(e.dataset.tab)})}),e.addEventListener(`click`,async e=>{if(e.target.closest(`#agentAddBtn`)){e.stopPropagation(),fb(),HT(null);return}if(e.target.closest(`#proxyAddBtn`)){e.stopPropagation(),fb(),chrome.runtime.sendMessage({type:`OPEN_OPTIONS_PAGE`,hash:`agent`});return}if(e.target.closest(`#knowledgeAddBtn`)){e.stopPropagation(),fb(),chrome.runtime.sendMessage({type:`OPEN_OPTIONS_PAGE`,hash:`knowledge`});return}if(e.target.closest(`#pageAddBtn`)){e.stopPropagation(),fb(),chrome.tabs.create({});return}let t=e.target.closest(`.agent-edit-btn`);if(t){e.stopPropagation();let n=t.dataset.agentId;fb(),HT(n);return}let n=e.target.closest(`.agent-delete-btn`);if(n){e.stopPropagation();let t=n.dataset.agentId;if(await cE(t)){let e=document.getElementById(`userInput`);await hb(e?gb(e.value):``)}}})}async function mb(e){sb=e;let t=document.getElementById(`agentAtTabs`);t&&t.querySelectorAll(`.prompt-tab`).forEach(t=>{t.classList.toggle(`active`,t.dataset.tab===e)});let n=document.getElementById(`agentAtList`),r=document.getElementById(`agentPageList`),i=document.getElementById(`agentProxyList`),a=document.getElementById(`agentKnowledgeList`);n&&(n.style.display=e===`agents`?``:`none`),r&&(r.style.display=e===`pages`?``:`none`),i&&(i.style.display=e===`proxies`?``:`none`),a&&(a.style.display=e===`knowledge`?``:`none`);let o=document.getElementById(`agentAtDropdown`);o&&o.setAttribute(`data-active-tab`,e);let s=document.getElementById(`userInput`);s&&s.focus(),await hb(s?gb(s.value):``)}async function hb(e=``){let t=document.getElementById(`agentAtTabs`),n=document.getElementById(`agentPageList`),r=document.getElementById(`agentAtList`),i=document.getElementById(`agentProxyList`),a=document.getElementById(`agentKnowledgeList`);if(e){lb=!0,t&&t.classList.add(`merged-mode`),n&&(n.style.display=`none`),i&&(i.style.display=`none`),a&&(a.style.display=`none`),r&&(r.style.display=``),await Db(e);let o=document.getElementById(`agentAtDropdown`);o&&o.setAttribute(`data-active-tab`,`merged`)}else{lb=!1,t&&t.classList.remove(`merged-mode`),t&&t.querySelectorAll(`.prompt-tab`).forEach(e=>{e.classList.toggle(`active`,e.dataset.tab===sb)}),n&&(n.style.display=sb===`pages`?``:`none`),r&&(r.style.display=sb===`agents`?``:`none`),i&&(i.style.display=sb===`proxies`?``:`none`),a&&(a.style.display=sb===`knowledge`?``:`none`);let e=document.getElementById(`agentAtDropdown`);e&&e.setAttribute(`data-active-tab`,sb),sb===`pages`?await Jb(``):sb===`proxies`?await Eb(``):sb===`knowledge`?await Hb(``):await yb(``)}}function gb(e){let t=e.lastIndexOf(`@`);return t===-1?``:e.substring(t+1)}function _b(e){return e.id==="default"?r(`agentMgr.defaultAgentName`):e.name}function vb(e){return e.id==="default"?r(`agentMgr.defaultAgentDesc`):e.description}async function yb(e=``){let t=document.getElementById(`agentAtList`);if(!t)return;let n=await St(),i=(e||``).toLowerCase(),a=n.filter(t=>{if(!e)return!0;let n=_b(t),r=vb(t);return n&&n.toLowerCase().includes(i)||r&&r.toLowerCase().includes(i)});if(a.length===0){t.innerHTML=`<div class="prompt-empty">${r(`promptSelector.noMatchAgent`)}</div>`,N.selectedAgentAtIndex=-1;return}N.selectedAgentAtIndex=0,t.innerHTML=a.map((e,t)=>{let n=e.id===N.activeAgentId||!N.activeAgentId&&e.id==="default",i=e.toolIds?e.toolIds.length:e.toolIds===null?null:0,a=i===null?r(`promptSelector.inheritGlobal`):r(`promptSelector.toolCount`,{count:i}),o=_b(e),s=vb(e);return`
|
|
1269
1269
|
<div class="prompt-item ${t===0?`selected`:``} ${n?`agent-at-active`:``}"
|
|
1270
1270
|
data-index="${t}" data-agent-id="${P(e.id)}">
|
|
1271
1271
|
<span class="prompt-item-index">${t+1}</span>
|
|
@@ -1291,7 +1291,7 @@ It is this session's directory or the agent default, so it stays accessible (wor
|
|
|
1291
1291
|
${a?`<span class="proxy-enable-btn" data-action="enable" data-id="${P(e.id)}" title="${r(`promptSelector.enableTitle`)}">▶</span>`:`<span class="proxy-disable-btn" data-action="disable" data-id="${P(e.id)}" title="${r(`promptSelector.disableTitle`)}">⏸</span>`}
|
|
1292
1292
|
<span class="proxy-delete-btn" data-action="delete" data-id="${P(e.id)}" title="${r(`common.delete`)}">✕</span>
|
|
1293
1293
|
</div>
|
|
1294
|
-
`}).join(``),t.querySelectorAll(`.prompt-item`).forEach(e=>{e.addEventListener(`click`,async t=>{let n=t.target.closest(`.proxy-disable-btn, .proxy-delete-btn, .proxy-enable-btn`);if(n){t.stopPropagation(),await Kb(n.dataset.action,n.dataset.id);return}await Ub(e.dataset.proxyId)})}),a.forEach(e=>Tb(e))}async function Db(e=``){let t=document.getElementById(`agentAtList`);if(!t)return;let n=e.toLowerCase(),[i,a,o,s]=await Promise.all([
|
|
1294
|
+
`}).join(``),t.querySelectorAll(`.prompt-item`).forEach(e=>{e.addEventListener(`click`,async t=>{let n=t.target.closest(`.proxy-disable-btn, .proxy-delete-btn, .proxy-enable-btn`);if(n){t.stopPropagation(),await Kb(n.dataset.action,n.dataset.id);return}await Ub(e.dataset.proxyId)})}),a.forEach(e=>Tb(e))}async function Db(e=``){let t=document.getElementById(`agentAtList`);if(!t)return;let n=e.toLowerCase(),[i,a,o,s]=await Promise.all([St(),qb(),cb(),Vb()]),c=i.filter(e=>{let t=_b(e),r=vb(e);return t&&t.toLowerCase().includes(n)||r&&r.toLowerCase().includes(n)}),l=a.filter(e=>{if(!e.url)return!1;let t=(e.title||``).toLowerCase().includes(n),r=e.url.toLowerCase().includes(n);return t||r}),u=o.filter(e=>e.name.toLowerCase().includes(n)||e.url&&e.url.toLowerCase().includes(n)),d=s.ok?s.collections.filter(e=>e.name&&e.name.toLowerCase().includes(n)||e.description&&e.description.toLowerCase().includes(n)):[],f=c.length+l.length+u.length+d.length,p=document.getElementById(`agentAtMergedTitle`);if(p&&(p.textContent=r(`promptSelector.mergedTitleCount`,{count:f})),f===0){t.innerHTML=`<div class="prompt-empty">${r(`promptSelector.noMatchAll`)}</div>`,N.selectedAgentAtIndex=-1;return}N.selectedAgentAtIndex=0;let m=``,h=0;c.forEach(e=>{let t=e.id===N.activeAgentId||!N.activeAgentId&&e.id==="default",n=e.toolIds?e.toolIds.length:e.toolIds===null?null:0,i=n===null?r(`promptSelector.inheritGlobal`):r(`promptSelector.toolCount`,{count:n}),a=_b(e),o=vb(e);m+=`
|
|
1295
1295
|
<div class="prompt-item${h===0?` selected`:``}${t?` agent-at-active`:``}"
|
|
1296
1296
|
data-index="${h}" data-type="agent" data-agent-id="${P(e.id)}">
|
|
1297
1297
|
<span class="prompt-item-index">${h+1}</span>
|
|
@@ -1335,7 +1335,7 @@ It is this session's directory or the agent default, so it stays accessible (wor
|
|
|
1335
1335
|
${t?`<span class="agent-item-actions"><span class="agent-active-mark">✓</span></span>`:``}
|
|
1336
1336
|
${n?`<span class="proxy-enable-btn" data-action="enable" data-id="${P(e.id)}" title="${r(`promptSelector.enableTitle`)}">▶</span>`:`<span class="proxy-disable-btn" data-action="disable" data-id="${P(e.id)}" title="${r(`promptSelector.disableTitle`)}">⏸</span>`}
|
|
1337
1337
|
<span class="proxy-delete-btn" data-action="delete" data-id="${P(e.id)}" title="${r(`common.delete`)}">✕</span>
|
|
1338
|
-
</div>`,h++}),t.innerHTML=m,t.querySelectorAll(`img.favicon-img`).forEach(e=>{e.addEventListener(`error`,()=>{e.style.display=`none`})}),u.forEach(e=>Tb(e)),t.querySelectorAll(`.prompt-item`).forEach(e=>{e.addEventListener(`click`,async t=>{let n=t.target.closest(`.page-action-btn`);if(n){t.stopPropagation(),$b(parseInt(n.dataset.tabId),n.dataset.action);return}let r=t.target.closest(`.proxy-disable-btn, .proxy-delete-btn, .proxy-enable-btn`);if(r){t.stopPropagation(),await Kb(r.dataset.action,r.dataset.id);return}if(t.target.closest(`.agent-edit-btn`)||t.target.closest(`.agent-delete-btn`))return;let i=e.dataset.type;i===`agent`?await jb(e.dataset.agentId):i===`page`?Mb(parseInt(e.dataset.tabId)):i===`knowledge`?(Pb({id:e.dataset.kbId,name:e.dataset.kbName,enabled:e.dataset.kbDisabled!==`1`}),(t.ctrlKey||t.metaKey)&&fb()):i===`proxy`&&await Ub(e.dataset.proxyId)})})}function Ob(e){let t;t=lb?N.selectedAgentAtIndex:sb===`proxies`?N.selectedProxyAtIndex:sb===`knowledge`?N.selectedKnowledgeAtIndex:N.selectedAgentAtIndex,e.forEach((e,n)=>{n===t?(e.classList.add(`selected`),e.scrollIntoView({block:`nearest`})):e.classList.remove(`selected`)})}function kb(){let e=document.getElementById(`userInput`);if(!e)return;let t=e.value,n=t.lastIndexOf(`@`);n!==-1&&(e.value=t.substring(0,n)),e.focus(),e.selectionStart=e.selectionEnd=e.value.length}function Ab(){let e=document.getElementById(`userInput`);e&&(e.focus(),e.selectionStart=e.selectionEnd=e.value.length)}async function jb(e,{clearTrigger:t=!0}={}){t?kb():Ab(),fb(),await OT(e),
|
|
1338
|
+
</div>`,h++}),t.innerHTML=m,t.querySelectorAll(`img.favicon-img`).forEach(e=>{e.addEventListener(`error`,()=>{e.style.display=`none`})}),u.forEach(e=>Tb(e)),t.querySelectorAll(`.prompt-item`).forEach(e=>{e.addEventListener(`click`,async t=>{let n=t.target.closest(`.page-action-btn`);if(n){t.stopPropagation(),$b(parseInt(n.dataset.tabId),n.dataset.action);return}let r=t.target.closest(`.proxy-disable-btn, .proxy-delete-btn, .proxy-enable-btn`);if(r){t.stopPropagation(),await Kb(r.dataset.action,r.dataset.id);return}if(t.target.closest(`.agent-edit-btn`)||t.target.closest(`.agent-delete-btn`))return;let i=e.dataset.type;i===`agent`?await jb(e.dataset.agentId):i===`page`?Mb(parseInt(e.dataset.tabId)):i===`knowledge`?(Pb({id:e.dataset.kbId,name:e.dataset.kbName,enabled:e.dataset.kbDisabled!==`1`}),(t.ctrlKey||t.metaKey)&&fb()):i===`proxy`&&await Ub(e.dataset.proxyId)})})}function Ob(e){let t;t=lb?N.selectedAgentAtIndex:sb===`proxies`?N.selectedProxyAtIndex:sb===`knowledge`?N.selectedKnowledgeAtIndex:N.selectedAgentAtIndex,e.forEach((e,n)=>{n===t?(e.classList.add(`selected`),e.scrollIntoView({block:`nearest`})):e.classList.remove(`selected`)})}function kb(){let e=document.getElementById(`userInput`);if(!e)return;let t=e.value,n=t.lastIndexOf(`@`);n!==-1&&(e.value=t.substring(0,n)),e.focus(),e.selectionStart=e.selectionEnd=e.value.length}function Ab(){let e=document.getElementById(`userInput`);e&&(e.focus(),e.selectionStart=e.selectionEnd=e.value.length)}async function jb(e,{clearTrigger:t=!0}={}){t?kb():Ab(),fb(),await OT(e),Ht()}function Mb(e){kb(),chrome.tabs.get(e,e=>{if(chrome.runtime.lastError||!e){a.error(`[AgentAtSelector] getlabelpageinfo failed:`,chrome.runtime.lastError);return}Xb(e),fb();let t=document.getElementById(`userInput`);t&&(t.focus(),Ht())})}function Nb(){let e=new Set(N.knowledgeRefs.map(e=>e.id));document.querySelectorAll(`.prompt-item-knowledge`).forEach(t=>{let n=e.has(t.dataset.kbId);t.classList.toggle(`agent-at-active`,n),t.classList.toggle(`picked`,n)})}function Pb(e,{clearTrigger:t=!0}={}){t?kb():Ab();let n=N.knowledgeRefs.findIndex(t=>t.id===e.id);n>=0?N.knowledgeRefs.splice(n,1):N.knowledgeRefs.push({id:e.id,name:e.name||e.id,enabled:e.enabled!==!1}),Nb(),Lb(),Ht()}function Fb(e){N.knowledgeRefs=N.knowledgeRefs.filter(t=>t.id!==e),Nb(),Lb()}function Ib(){N.knowledgeRefs=[],Nb(),Lb()}function Lb(){let e=document.getElementById(`knowledgeIndicator`);if(e){if(N.knowledgeRefs.length===0){e.style.display=`none`,e.innerHTML=``;return}e.innerHTML=N.knowledgeRefs.map(e=>{let t=e.enabled===!1,n=t?`${e.name} (${r(`knowledgeSelector.manualSuffix`)})`:e.name;return`
|
|
1339
1339
|
<span class="knowledge-chip${t?` knowledge-chip-manual`:``}">
|
|
1340
1340
|
<span class="knowledge-chip-name" title="${P(t?r(`knowledgeSelector.disabledTooltip`):e.name)}">📚 ${P(n)}</span>
|
|
1341
1341
|
<button class="knowledge-chip-close" data-kb-id="${P(e.id)}" title="${r(`common.delete`)}">✕</button>
|
|
@@ -1350,7 +1350,7 @@ It is this session's directory or the agent default, so it stays accessible (wor
|
|
|
1350
1350
|
${a?`<span class="knowledge-item-badge badge-disabled">${r(`knowledgeSelector.disabledBadge`)}</span>`:``}
|
|
1351
1351
|
<span class="prompt-item-code">${P(i)}</span>
|
|
1352
1352
|
</div>
|
|
1353
|
-
`}).join(``),t.querySelectorAll(`.prompt-item`).forEach(e=>{e.addEventListener(`click`,t=>{Pb({id:e.dataset.kbId,name:e.dataset.kbName,enabled:e.dataset.kbDisabled!==`1`}),(t.ctrlKey||t.metaKey)&&fb()})})}async function Ub(e,{clearTrigger:t=!0}={}){t?kb():Ab(),fb();try{await chrome.storage.local.set({activeAgentId:e}),chrome.runtime.sendMessage({type:`AGENT_CONNECTION_CHANGED`,connected:!0,agentId:e}),a.debug(`[AgentAtSelector] switched to agent:`,e)}catch(e){a.error(`[AgentAtSelector] switchagent failed:`,e)}
|
|
1353
|
+
`}).join(``),t.querySelectorAll(`.prompt-item`).forEach(e=>{e.addEventListener(`click`,t=>{Pb({id:e.dataset.kbId,name:e.dataset.kbName,enabled:e.dataset.kbDisabled!==`1`}),(t.ctrlKey||t.metaKey)&&fb()})})}async function Ub(e,{clearTrigger:t=!0}={}){t?kb():Ab(),fb();try{await chrome.storage.local.set({activeAgentId:e}),chrome.runtime.sendMessage({type:`AGENT_CONNECTION_CHANGED`,connected:!0,agentId:e}),a.debug(`[AgentAtSelector] switched to agent:`,e)}catch(e){a.error(`[AgentAtSelector] switchagent failed:`,e)}Ht()}var Wb=!1;function Gb(){Wb||(Wb=!0,chrome.tabs.onActivated.addListener(()=>{let e=document.getElementById(`agentAtSelector`);if(!e||e.style.display!==`block`||sb!==`pages`&&!lb)return;let t=document.getElementById(`userInput`);hb(t?gb(t.value):``)}))}Gb();async function Kb(e,t){let n=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),i=n.pairedAgents||[];switch(e){case`enable`:i=i.map(e=>e.id===t?{...e,disabled:!1}:e),await chrome.storage.local.set({pairedAgents:i});break;case`disable`:{i=i.map(e=>e.id===t?{...e,disabled:!0}:e);let e=n.activeAgentId;n.activeAgentId===t&&(e=i.find(e=>e.id!==t&&!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`delete`:{let e=i.find(e=>e.id===t),a=e?.url?`\n${r(`promptSelector.proxyAddress`)}: ${e.url}`:``;if(!await window.showCustomConfirm(r(`promptSelector.deleteProxyTitle`),r(`promptSelector.confirmDeleteProxy`,{name:e?.name||t,urlInfo:a})))return;i=i.filter(e=>e.id!==t);let o=n.activeAgentId===t?i.find(e=>!e.disabled)?.id||null:n.activeAgentId;await chrome.storage.local.set({pairedAgents:i,activeAgentId:o||``}),o?chrome.runtime.sendMessage({type:`AGENT_CONNECTION_CHANGED`,connected:!0,agentId:o}):chrome.runtime.sendMessage({type:`AGENT_CONNECTION_CHANGED`,connected:!1});break}}let a=document.getElementById(`userInput`);await hb(a?gb(a.value):``)}n(`zh`,{pageSelector:{noOpenPages:`暂无打开的网页`,noTitle:`无标题`,currentTab:`当前`,openNewTab:`新建标签页`,interpretPage:`解读`,summarizePage:`总结`,translatePage:`翻译`,interpretMsg:`解读一下当前网页`,summarizeMsg:`总结一下当前网页`,translateMsg:`翻译一下当前网页`}}),n(`en`,{pageSelector:{noOpenPages:`No open pages`,noTitle:`Untitled`,currentTab:`Current`,openNewTab:`Open new tab`,interpretPage:`Interpret`,summarizePage:`Summarize`,translatePage:`Translate`,interpretMsg:`Interpret the current webpage`,summarizeMsg:`Summarize the current webpage`,translateMsg:`Translate the current webpage`}});async function qb(){try{return[...await chrome.tabs.query({currentWindow:!0})].sort((e,t)=>e.active===t.active?0:e.active?-1:1)}catch(e){return a.error(`[PageSelector] getlabelpage failed:`,e),[]}}async function Jb(e=``){let t=document.getElementById(`agentPageList`);if(!t)return;let n=await qb(),i=e.toLowerCase(),a=n.filter(t=>{if(!t.url)return!1;if(!e)return!0;let n=(t.title||``).toLowerCase().includes(i),r=t.url.toLowerCase().includes(i);return n||r});if(a.length===0){t.innerHTML=`<div class="prompt-empty">${r(`pageSelector.noOpenPages`)}</div>`,N.selectedPageIndex=-1;return}N.selectedPageIndex=0;let o=N.selectedPage?N.selectedPage.id:null;t.innerHTML=a.map((e,t)=>{let n=e.title||r(`pageSelector.noTitle`),i=e.url||``,a=e.favIconUrl?`<img src="${P(e.favIconUrl)}" width="16" height="16" style="flex-shrink:0;" class="favicon-img">`:`<span style="font-size:14px;flex-shrink:0;">🌐</span>`,s=e.active?`<span class="current-tab-badge">${r(`pageSelector.currentTab`)}</span>`:``,c=e.id===o;return`
|
|
1354
1354
|
<div class="prompt-item prompt-item-page ${t===0?`selected`:``}"
|
|
1355
1355
|
data-index="${t}" data-tab-id="${e.id}">
|
|
1356
1356
|
<span class="prompt-item-index">${t+1}</span>
|
|
@@ -1365,7 +1365,7 @@ It is this session's directory or the agent default, so it stays accessible (wor
|
|
|
1365
1365
|
<span class="page-action-btn" data-action="translate" data-tab-id="${e.id}" title="${r(`pageSelector.translatePage`)}">${r(`pageSelector.translatePage`)}</span>
|
|
1366
1366
|
</span>
|
|
1367
1367
|
</div>
|
|
1368
|
-
`}).join(``),t.querySelectorAll(`img.favicon-img`).forEach(e=>{e.addEventListener(`error`,()=>{e.style.display=`none`})}),t.querySelectorAll(`.prompt-item`).forEach(e=>{e.addEventListener(`click`,t=>{let n=t.target.closest(`.page-action-btn`);if(n){t.stopPropagation(),$b(parseInt(n.dataset.tabId),n.dataset.action);return}Qb(parseInt(e.dataset.tabId))})})}function Yb(e){e.forEach((e,t)=>{t===N.selectedPageIndex?(e.classList.add(`selected`),e.scrollIntoView({block:`nearest`})):e.classList.remove(`selected`)})}function Xb(e){N.selectedPage={id:e.id,title:e.title||r(`pageSelector.noTitle`),url:e.url||``,favIconUrl:e.favIconUrl||``};let t=document.getElementById(`pageIndicator`),n=document.getElementById(`pageIndicatorName`);if(t&&n){let e=N.selectedPage.title&&N.selectedPage.title!==r(`pageSelector.noTitle`)?N.selectedPage.title:``,i=N.selectedPage.url||``;e&&i?n.textContent=`${e} · ${i}`:n.textContent=e||i,t.style.display=`flex`}}function Zb(){N.selectedPage=null,N.selectedPageIndex=-1;let e=document.getElementById(`pageIndicator`);e&&(e.style.display=`none`)}function Qb(e){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),chrome.tabs.get(e,e=>{if(chrome.runtime.lastError||!e){a.error(`[PageSelector] getlabelpageinfo failed:`,chrome.runtime.lastError);return}Xb(e),fb(),t&&(t.focus(),Vt())})}function $b(e,t){let n={interpret:r(`pageSelector.interpretMsg`),summarize:r(`pageSelector.summarizeMsg`),translate:r(`pageSelector.translateMsg`)}[t];n&&chrome.tabs.get(e,e=>{if(chrome.runtime.lastError||!e){a.error(`[PageSelector] get tab info failed:`,chrome.runtime.lastError);return}Xb(e),fb();let t=document.getElementById(`userInput`);t&&(t.value=n,Vt()),XC()})}function ex(){let e=document.getElementById(`pageIndicatorClose`);e&&e.addEventListener(`click`,()=>{Zb()})}n(`zh`,{msgFullscreen:{title:`全屏阅读`,btnTitle:`全屏查看本回答 (Alt+双击 / Alt+F)`,btnLabel:`全屏`,copy:`复制`,copyTitle:`复制回答内容(Ctrl/⌘+点击复制富文本)`,export:`导出`,exportTitle:`导出下载本回答`,exportWord:`导出 Word`,exportPdf:`导出 PDF`,exportImage:`导出图片`,exportMarkdown:`导出 Markdown`,close:`退出全屏`,closeTitle:`退出全屏 (Esc)`}}),n(`en`,{msgFullscreen:{title:`Fullscreen Reading`,btnTitle:`View this answer fullscreen (Alt+Double-click / Alt+F)`,btnLabel:`Fullscreen`,copy:`Copy`,copyTitle:`Copy answer (Ctrl/Cmd+click for rich text)`,export:`Export`,exportTitle:`Export / download this answer`,exportWord:`Export Word`,exportPdf:`Export PDF`,exportImage:`Export Image`,exportMarkdown:`Export Markdown`,close:`Exit fullscreen`,closeTitle:`Exit fullscreen (Esc)`}});var tx=`messageFullscreenOverlay`,nx=`messageFullscreenBody`,rx=`messageFullscreenTitle`,ix=`messageFullscreenCopyBtn`,ax=`messageFullscreenCloseBtn`,ox=`messageFullscreenExportBtn`,sx=`messageFullscreenExportDropdown`,cx=null,lx=null,ux=null,dx=!1,fx=null,px=!1;function mx(){return cx!==null}function hx(e){return!e||mx()?null:e.innerHTML}function gx(){let e=document.querySelectorAll(`#chatContainer .message.assistant`);return e.length?e[e.length-1]:null}function _x(){let e=document.createElement(`button`);return e.className=`fullscreen-btn`,e.title=r(`msgFullscreen.btnTitle`),e.innerHTML=[`<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" width="14" height="14">`,`<path d="M6 2H2v4M10 2h4v4M6 14H2v-4M10 14h4v-4"/>`,`</svg>`,`<span>${r(`msgFullscreen.btnLabel`)}</span>`].join(``),e}function vx(){let e=document.getElementById(tx),t=document.getElementById(nx);return!e||!t?(a.warn(`[MsgFullscreen] overlay/body element missing`),null):{overlay:e,body:t,title:document.getElementById(rx),copyBtn:document.getElementById(ix),closeBtn:document.getElementById(ax)}}function yx(e){if(!e)return;let t=vx();if(t&&cx!==e){if(!cx){let e=document.getElementById(`chatContainer`);fx=e?e.scrollTop:null}cx&&(px=!0,bx(),px=!1),lx=document.createComment(`msg-fullscreen-anchor`),e.parentNode.insertBefore(lx,e),e.dataset.fullscreen=`1`,t.body.appendChild(e),cx=e,t.overlay.style.display=`flex`,document.body.classList.add(`message-fullscreen-viewing`),t.title&&(t.title.textContent=r(`msgFullscreen.title`)),t.copyBtn&&(t.copyBtn.title=r(`msgFullscreen.copyTitle`)),t.closeBtn&&(t.closeBtn.title=r(`msgFullscreen.closeTitle`)),Ax(),Sx(t.body)}}function bx(){if(!cx)return;let e=vx();if(wx(),jx(),lx&&lx.parentNode)lx.parentNode.insertBefore(cx,lx);else if(e){let e=document.getElementById(`chatContainer`);e&&e.appendChild(cx)}if(lx&&lx.parentNode&&lx.parentNode.removeChild(lx),delete cx.dataset.fullscreen,cx=null,lx=null,e){e.overlay.style.display=`none`,e.body.innerHTML=``;let t=e.overlay.querySelector(`.message-fullscreen-rail`);t&&t.querySelectorAll(`.message-toc-container`).forEach(e=>e.remove())}if(document.body.classList.remove(`message-fullscreen-viewing`),!px&&fx!==null){let e=document.getElementById(`chatContainer`);e&&(e.scrollTop=fx),fx=null}}function xx(e){if(cx&&cx===e){bx();return}yx(e||gx())}function Sx(e){wx(),dx=!1,e.scrollTop=e.scrollHeight,e.addEventListener(`scroll`,Cx,{passive:!0}),typeof ResizeObserver<`u`&&(ux=new ResizeObserver(()=>{dx||(e.scrollTop=e.scrollHeight)}),ux.observe(e.firstElementChild||e))}function Cx(){let e=document.getElementById(nx);e&&(dx=e.scrollHeight-e.scrollTop-e.clientHeight>60)}function wx(){let e=document.getElementById(nx);e&&e.removeEventListener(`scroll`,Cx),ux&&=(ux.disconnect(),null)}function Tx(e){if(e.altKey&&!e.ctrlKey&&!e.metaKey&&!e.shiftKey&&e.code===`KeyF`){e.preventDefault(),cx?bx():yx(gx());return}e.key===`Escape`&&cx&&(e.preventDefault(),e.stopImmediatePropagation(),bx())}function Ex(e){if(!e.altKey||e.ctrlKey||e.metaKey||e.shiftKey)return;let t=e.target.closest?.(`#chatContainer .message.assistant`);t&&(e.preventDefault(),xx(t))}async function Dx(e){if(!cx)return;let{copyAssistantMessage:t}=await M(async()=>{let{copyAssistantMessage:e}=await Promise.resolve().then(()=>Px);return{copyAssistantMessage:e}},void 0);t(cx,document.getElementById(ix),e)}var Ox={docx:`<path d="M4 1.5h6L13 4.5v10H4z"/><path d="M10 1.5v3h3"/><path d="M6 8h4M6 10.5h4"/>`,pdf:`<path d="M4 1.5h6L13 4.5v10H4z"/><path d="M10 1.5v3h3"/><path d="M6.5 11.5c2-1 2.5-4 1-4s-1 4 2 4"/>`,image:`<rect x="2.5" y="3" width="11" height="10" rx="1.2"/><circle cx="6" cy="6.5" r="1"/><path d="M13.5 10 10 6.5 4.5 12.5"/>`,markdown:`<path d="M2.5 12V4l3 3 3-3v8"/><path d="M12.5 4v6m0 0 2-2.2m-2 2.2L10.5 7.8"/>`};function kx(){let e=document.createElement(`div`);e.className=`message-fullscreen-export`;let t=document.createElement(`button`);t.className=`message-fullscreen-icon-btn`,t.id=ox,t.type=`button`,t.title=r(`msgFullscreen.exportTitle`),t.innerHTML=[`<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" width="16" height="16">`,`<path d="M8 2v8m0 0 3-3M8 10 5 7M2.5 13.5h11"/>`,`</svg>`,`<span>${r(`msgFullscreen.export`)}</span>`,`<svg class="dropdown-arrow" width="8" height="6" viewBox="0 0 8 6" fill="currentColor"><path d="M0 0l4 6 4-6z"/></svg>`].join(``);let n=document.createElement(`div`);n.className=`message-fullscreen-export-dropdown`,n.id=sx;let i=e=>`<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round">${Ox[e]}</svg>`;n.innerHTML=[`<button class="export-dropdown-item export-docx-item" type="button">${i(`docx`)}<span>${r(`msgFullscreen.exportWord`)}</span></button>`,`<button class="export-dropdown-item export-pdf-item" type="button">${i(`pdf`)}<span>${r(`msgFullscreen.exportPdf`)}</span></button>`,`<button class="export-dropdown-item export-image-item" type="button">${i(`image`)}<span>${r(`msgFullscreen.exportImage`)}</span></button>`,`<button class="export-dropdown-item export-md-item" type="button">${i(`markdown`)}<span>${r(`msgFullscreen.exportMarkdown`)}</span></button>`].join(``),t.addEventListener(`click`,e=>{e.stopPropagation(),n.classList.toggle(`show`)});let a=(e,t)=>{let r=n.querySelector(e);r.addEventListener(`click`,async e=>{e.stopPropagation(),cx&&(n.classList.remove(`show`),(await M(()=>import(`./chat-export-CmaDpmwW.js`),__vite__mapDeps([10,11,1,12,2,3,4,13,14,0])))[t](cx,r,n))})};return a(`.export-docx-item`,`exportAssistantMessageToDocx`),a(`.export-pdf-item`,`exportAssistantMessageToPdf`),a(`.export-image-item`,`exportAssistantMessageToImage`),a(`.export-md-item`,`exportAssistantMessageToMarkdown`),e.appendChild(t),e.appendChild(n),e}function Ax(){if(document.getElementById(ox))return;let e=document.getElementById(ax),t=e?e.parentNode:document.querySelector(`.message-fullscreen-actions`);t&&t.insertBefore(kx(),e||null)}function jx(){let e=document.getElementById(sx);e&&e.classList.remove(`show`)}var Mx=!1;function Nx(){Mx||(Mx=!0,document.addEventListener(`click`,e=>{let t=document.getElementById(sx);t&&t.classList.contains(`show`)&&!e.target.closest?.(`.message-fullscreen-export`)&&t.classList.remove(`show`);let n=e.target.closest?.(`.fullscreen-btn`);if(n){e.stopPropagation(),xx(n.closest(`.message`));return}if(e.target.closest?.(`#messageFullscreenCloseBtn`)){e.stopPropagation(),bx();return}e.target.closest?.(`#messageFullscreenCopyBtn`)&&(e.stopPropagation(),Dx(e))},!0),document.addEventListener(`keydown`,Tx,!0),document.addEventListener(`dblclick`,Ex,!0))}var Px=t({copyAssistantMessage:()=>Lx,copyMessage:()=>Ix,copyRichText:()=>Bx,fallbackCopyRichText:()=>Hx,fallbackCopyText:()=>zx,quoteAndAsk:()=>Gx,setQuoteContextInjector:()=>Wx,showCopySuccess:()=>Rx,wrapHtmlWithStyles:()=>Vx});n(`zh`,{chatCopy:{copiedMarkdown:`已复制 Markdown`,copiedRich:`已复制富文本`,copyFailedManual:`复制失败,请手动复制`}}),n(`en`,{chatCopy:{copiedMarkdown:`Markdown copied`,copiedRich:`Rich text copied`,copyFailedManual:`Copy failed, please copy manually`}});function Fx(e){let t=e.querySelectorAll(`.mermaid`),n=null;for(let e of t)try{if(!n&&e._pngDataUrl){let t=e._pngDataUrl.split(`,`)[1]||``,r=atob(t),i=r.length,a=new Uint8Array(i);for(let e=0;e<i;e++)a[e]=r.charCodeAt(e);n=new Blob([a],{type:`image/png`})}let t=e.getAttribute(`data-raw-code`),r=t?decodeURIComponent(t):e.dataset.rawMermaidCode||(e.textContent||``).trim();if(r){let t=r.split(`
|
|
1368
|
+
`}).join(``),t.querySelectorAll(`img.favicon-img`).forEach(e=>{e.addEventListener(`error`,()=>{e.style.display=`none`})}),t.querySelectorAll(`.prompt-item`).forEach(e=>{e.addEventListener(`click`,t=>{let n=t.target.closest(`.page-action-btn`);if(n){t.stopPropagation(),$b(parseInt(n.dataset.tabId),n.dataset.action);return}Qb(parseInt(e.dataset.tabId))})})}function Yb(e){e.forEach((e,t)=>{t===N.selectedPageIndex?(e.classList.add(`selected`),e.scrollIntoView({block:`nearest`})):e.classList.remove(`selected`)})}function Xb(e){N.selectedPage={id:e.id,title:e.title||r(`pageSelector.noTitle`),url:e.url||``,favIconUrl:e.favIconUrl||``};let t=document.getElementById(`pageIndicator`),n=document.getElementById(`pageIndicatorName`);if(t&&n){let e=N.selectedPage.title&&N.selectedPage.title!==r(`pageSelector.noTitle`)?N.selectedPage.title:``,i=N.selectedPage.url||``;e&&i?n.textContent=`${e} · ${i}`:n.textContent=e||i,t.style.display=`flex`}}function Zb(){N.selectedPage=null,N.selectedPageIndex=-1;let e=document.getElementById(`pageIndicator`);e&&(e.style.display=`none`)}function Qb(e){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),chrome.tabs.get(e,e=>{if(chrome.runtime.lastError||!e){a.error(`[PageSelector] getlabelpageinfo failed:`,chrome.runtime.lastError);return}Xb(e),fb(),t&&(t.focus(),Ht())})}function $b(e,t){let n={interpret:r(`pageSelector.interpretMsg`),summarize:r(`pageSelector.summarizeMsg`),translate:r(`pageSelector.translateMsg`)}[t];n&&chrome.tabs.get(e,e=>{if(chrome.runtime.lastError||!e){a.error(`[PageSelector] get tab info failed:`,chrome.runtime.lastError);return}Xb(e),fb();let t=document.getElementById(`userInput`);t&&(t.value=n,Ht()),XC()})}function ex(){let e=document.getElementById(`pageIndicatorClose`);e&&e.addEventListener(`click`,()=>{Zb()})}n(`zh`,{msgFullscreen:{title:`全屏阅读`,btnTitle:`全屏查看本回答 (Alt+双击 / Alt+F)`,btnLabel:`全屏`,copy:`复制`,copyTitle:`复制回答内容(Ctrl/⌘+点击复制富文本)`,export:`导出`,exportTitle:`导出下载本回答`,exportWord:`导出 Word`,exportPdf:`导出 PDF`,exportImage:`导出图片`,exportMarkdown:`导出 Markdown`,close:`退出全屏`,closeTitle:`退出全屏 (Esc)`}}),n(`en`,{msgFullscreen:{title:`Fullscreen Reading`,btnTitle:`View this answer fullscreen (Alt+Double-click / Alt+F)`,btnLabel:`Fullscreen`,copy:`Copy`,copyTitle:`Copy answer (Ctrl/Cmd+click for rich text)`,export:`Export`,exportTitle:`Export / download this answer`,exportWord:`Export Word`,exportPdf:`Export PDF`,exportImage:`Export Image`,exportMarkdown:`Export Markdown`,close:`Exit fullscreen`,closeTitle:`Exit fullscreen (Esc)`}});var tx=`messageFullscreenOverlay`,nx=`messageFullscreenBody`,rx=`messageFullscreenTitle`,ix=`messageFullscreenCopyBtn`,ax=`messageFullscreenCloseBtn`,ox=`messageFullscreenExportBtn`,sx=`messageFullscreenExportDropdown`,cx=null,lx=null,ux=null,dx=!1,fx=null,px=!1;function mx(){return cx!==null}function hx(e){return!e||mx()?null:e.innerHTML}function gx(){let e=document.querySelectorAll(`#chatContainer .message.assistant`);return e.length?e[e.length-1]:null}function _x(){let e=document.createElement(`button`);return e.className=`fullscreen-btn`,e.title=r(`msgFullscreen.btnTitle`),e.innerHTML=[`<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" width="14" height="14">`,`<path d="M6 2H2v4M10 2h4v4M6 14H2v-4M10 14h4v-4"/>`,`</svg>`,`<span>${r(`msgFullscreen.btnLabel`)}</span>`].join(``),e}function vx(){let e=document.getElementById(tx),t=document.getElementById(nx);return!e||!t?(a.warn(`[MsgFullscreen] overlay/body element missing`),null):{overlay:e,body:t,title:document.getElementById(rx),copyBtn:document.getElementById(ix),closeBtn:document.getElementById(ax)}}function yx(e){if(!e)return;let t=vx();if(t&&cx!==e){if(!cx){let e=document.getElementById(`chatContainer`);fx=e?e.scrollTop:null}cx&&(px=!0,bx(),px=!1),lx=document.createComment(`msg-fullscreen-anchor`),e.parentNode.insertBefore(lx,e),e.dataset.fullscreen=`1`,t.body.appendChild(e),cx=e,t.overlay.style.display=`flex`,document.body.classList.add(`message-fullscreen-viewing`),t.title&&(t.title.textContent=r(`msgFullscreen.title`)),t.copyBtn&&(t.copyBtn.title=r(`msgFullscreen.copyTitle`)),t.closeBtn&&(t.closeBtn.title=r(`msgFullscreen.closeTitle`)),Ax(),Sx(t.body)}}function bx(){if(!cx)return;let e=vx();if(wx(),jx(),lx&&lx.parentNode)lx.parentNode.insertBefore(cx,lx);else if(e){let e=document.getElementById(`chatContainer`);e&&e.appendChild(cx)}if(lx&&lx.parentNode&&lx.parentNode.removeChild(lx),delete cx.dataset.fullscreen,cx=null,lx=null,e){e.overlay.style.display=`none`,e.body.innerHTML=``;let t=e.overlay.querySelector(`.message-fullscreen-rail`);t&&t.querySelectorAll(`.message-toc-container`).forEach(e=>e.remove())}if(document.body.classList.remove(`message-fullscreen-viewing`),!px&&fx!==null){let e=document.getElementById(`chatContainer`);e&&(e.scrollTop=fx),fx=null}}function xx(e){if(cx&&cx===e){bx();return}yx(e||gx())}function Sx(e){wx(),dx=!1,e.scrollTop=e.scrollHeight,e.addEventListener(`scroll`,Cx,{passive:!0}),typeof ResizeObserver<`u`&&(ux=new ResizeObserver(()=>{dx||(e.scrollTop=e.scrollHeight)}),ux.observe(e.firstElementChild||e))}function Cx(){let e=document.getElementById(nx);e&&(dx=e.scrollHeight-e.scrollTop-e.clientHeight>60)}function wx(){let e=document.getElementById(nx);e&&e.removeEventListener(`scroll`,Cx),ux&&=(ux.disconnect(),null)}function Tx(e){if(e.altKey&&!e.ctrlKey&&!e.metaKey&&!e.shiftKey&&e.code===`KeyF`){e.preventDefault(),cx?bx():yx(gx());return}e.key===`Escape`&&cx&&(e.preventDefault(),e.stopImmediatePropagation(),bx())}function Ex(e){if(!e.altKey||e.ctrlKey||e.metaKey||e.shiftKey)return;let t=e.target.closest?.(`#chatContainer .message.assistant`);t&&(e.preventDefault(),xx(t))}async function Dx(e){if(!cx)return;let{copyAssistantMessage:t}=await M(async()=>{let{copyAssistantMessage:e}=await Promise.resolve().then(()=>Px);return{copyAssistantMessage:e}},void 0);t(cx,document.getElementById(ix),e)}var Ox={docx:`<path d="M4 1.5h6L13 4.5v10H4z"/><path d="M10 1.5v3h3"/><path d="M6 8h4M6 10.5h4"/>`,pdf:`<path d="M4 1.5h6L13 4.5v10H4z"/><path d="M10 1.5v3h3"/><path d="M6.5 11.5c2-1 2.5-4 1-4s-1 4 2 4"/>`,image:`<rect x="2.5" y="3" width="11" height="10" rx="1.2"/><circle cx="6" cy="6.5" r="1"/><path d="M13.5 10 10 6.5 4.5 12.5"/>`,markdown:`<path d="M2.5 12V4l3 3 3-3v8"/><path d="M12.5 4v6m0 0 2-2.2m-2 2.2L10.5 7.8"/>`};function kx(){let e=document.createElement(`div`);e.className=`message-fullscreen-export`;let t=document.createElement(`button`);t.className=`message-fullscreen-icon-btn`,t.id=ox,t.type=`button`,t.title=r(`msgFullscreen.exportTitle`),t.innerHTML=[`<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" width="16" height="16">`,`<path d="M8 2v8m0 0 3-3M8 10 5 7M2.5 13.5h11"/>`,`</svg>`,`<span>${r(`msgFullscreen.export`)}</span>`,`<svg class="dropdown-arrow" width="8" height="6" viewBox="0 0 8 6" fill="currentColor"><path d="M0 0l4 6 4-6z"/></svg>`].join(``);let n=document.createElement(`div`);n.className=`message-fullscreen-export-dropdown`,n.id=sx;let i=e=>`<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round">${Ox[e]}</svg>`;n.innerHTML=[`<button class="export-dropdown-item export-docx-item" type="button">${i(`docx`)}<span>${r(`msgFullscreen.exportWord`)}</span></button>`,`<button class="export-dropdown-item export-pdf-item" type="button">${i(`pdf`)}<span>${r(`msgFullscreen.exportPdf`)}</span></button>`,`<button class="export-dropdown-item export-image-item" type="button">${i(`image`)}<span>${r(`msgFullscreen.exportImage`)}</span></button>`,`<button class="export-dropdown-item export-md-item" type="button">${i(`markdown`)}<span>${r(`msgFullscreen.exportMarkdown`)}</span></button>`].join(``),t.addEventListener(`click`,e=>{e.stopPropagation(),n.classList.toggle(`show`)});let a=(e,t)=>{let r=n.querySelector(e);r.addEventListener(`click`,async e=>{e.stopPropagation(),cx&&(n.classList.remove(`show`),(await M(()=>import(`./chat-export-CDzJ0eSb.js`),__vite__mapDeps([10,11,1,4,12,2,3,13,14,0])))[t](cx,r,n))})};return a(`.export-docx-item`,`exportAssistantMessageToDocx`),a(`.export-pdf-item`,`exportAssistantMessageToPdf`),a(`.export-image-item`,`exportAssistantMessageToImage`),a(`.export-md-item`,`exportAssistantMessageToMarkdown`),e.appendChild(t),e.appendChild(n),e}function Ax(){if(document.getElementById(ox))return;let e=document.getElementById(ax),t=e?e.parentNode:document.querySelector(`.message-fullscreen-actions`);t&&t.insertBefore(kx(),e||null)}function jx(){let e=document.getElementById(sx);e&&e.classList.remove(`show`)}var Mx=!1;function Nx(){Mx||(Mx=!0,document.addEventListener(`click`,e=>{let t=document.getElementById(sx);t&&t.classList.contains(`show`)&&!e.target.closest?.(`.message-fullscreen-export`)&&t.classList.remove(`show`);let n=e.target.closest?.(`.fullscreen-btn`);if(n){e.stopPropagation(),xx(n.closest(`.message`));return}if(e.target.closest?.(`#messageFullscreenCloseBtn`)){e.stopPropagation(),bx();return}e.target.closest?.(`#messageFullscreenCopyBtn`)&&(e.stopPropagation(),Dx(e))},!0),document.addEventListener(`keydown`,Tx,!0),document.addEventListener(`dblclick`,Ex,!0))}var Px=t({copyAssistantMessage:()=>Lx,copyMessage:()=>Ix,copyRichText:()=>Bx,fallbackCopyRichText:()=>Hx,fallbackCopyText:()=>zx,quoteAndAsk:()=>Gx,setQuoteContextInjector:()=>Wx,showCopySuccess:()=>Rx,wrapHtmlWithStyles:()=>Vx});n(`zh`,{chatCopy:{copiedMarkdown:`已复制 Markdown`,copiedRich:`已复制富文本`,copyFailedManual:`复制失败,请手动复制`}}),n(`en`,{chatCopy:{copiedMarkdown:`Markdown copied`,copiedRich:`Rich text copied`,copyFailedManual:`Copy failed, please copy manually`}});function Fx(e){let t=e.querySelectorAll(`.mermaid`),n=null;for(let e of t)try{if(!n&&e._pngDataUrl){let t=e._pngDataUrl.split(`,`)[1]||``,r=atob(t),i=r.length,a=new Uint8Array(i);for(let e=0;e<i;e++)a[e]=r.charCodeAt(e);n=new Blob([a],{type:`image/png`})}let t=e.getAttribute(`data-raw-code`),r=t?decodeURIComponent(t):e.dataset.rawMermaidCode||(e.textContent||``).trim();if(r){let t=r.split(`
|
|
1369
1369
|
`),n=document.createElement(`pre`);n.appendChild(document.createTextNode(t[0]||``));for(let e=1;e<t.length;e++)n.appendChild(document.createElement(`br`)),n.appendChild(document.createTextNode(t[e]));e.parentNode.replaceChild(n,e)}else e.remove()}catch(t){a.warn(`[SidePanel] Mermaid chartprocessing failed,remove:`,t.message),e.remove()}return{html:e.innerHTML,firstPngBlob:n}}function Ix(e,t){try{let n=e.dataset.textContent_||e.dataset.rawContent||``;navigator.clipboard.writeText(n).then(()=>{let e=t.innerHTML;t.innerHTML=`
|
|
1370
1370
|
<svg width="14" height="14" viewBox="0 0 16 16" fill="currentColor">
|
|
1371
1371
|
<path d="M13.78 4.22a.75.75 0 0 1 0 1.06l-7.25 7.25a.75.75 0 0 1-1.06 0L2.22 9.28a.75.75 0 0 1 1.06-1.06L6 10.94l6.72-6.72a.75.75 0 0 1 1.06 0z"/>
|
|
@@ -1478,7 +1478,7 @@ It is this session's directory or the agent default, so it stays accessible (wor
|
|
|
1478
1478
|
</div>
|
|
1479
1479
|
</div>
|
|
1480
1480
|
</div>
|
|
1481
|
-
`,document.body.appendChild(i),i.querySelector(`.ri-close`).addEventListener(`click`,()=>i.remove()),i.addEventListener(`click`,e=>{e.target===i&&i.remove()});let w=t.getBoundingClientRect(),T=i.querySelector(`.reflection-info-panel`),E=Math.min(window.innerHeight-40,560),D=w.right-380;D<10&&(D=10),D+380>window.innerWidth-10&&(D=window.innerWidth-380-10);let O=w.bottom+6;O+E>window.innerHeight-10&&(O=w.top-E-6),O<10&&(O=10),T.style.left=D+`px`,T.style.top=O+`px`,T.style.maxHeight=E+`px`}function qx(e){let t=document.querySelector(`.execution-log-panel`);t&&t.remove();let n=document.createElement(`div`);n.className=`execution-log-panel`;let i=e.reduce((e,t)=>e+(t.duration||0),0),a=e.filter(e=>e.status===`success`).length,o=e.filter(e=>e.status===`failed`).length,s=e.filter(e=>e.nodeType===`subtask`).length,c=e.filter(e=>e.nodeType===`subtask`&&e.status===`success`).length,l=e.filter(e=>e.nodeType===`tool_exec`&&e.action?.name===`plan_task`&&e.status===`success`).length,u=e.filter(e=>e.nodeType===`reflection`).find(e=>e.reflectionType===`post`),d=u&&u.overallScore!=null?`${u.overallScore}/10`:r(`chatPanels.scoreUnavailable`),f=
|
|
1481
|
+
`,document.body.appendChild(i),i.querySelector(`.ri-close`).addEventListener(`click`,()=>i.remove()),i.addEventListener(`click`,e=>{e.target===i&&i.remove()});let w=t.getBoundingClientRect(),T=i.querySelector(`.reflection-info-panel`),E=Math.min(window.innerHeight-40,560),D=w.right-380;D<10&&(D=10),D+380>window.innerWidth-10&&(D=window.innerWidth-380-10);let O=w.bottom+6;O+E>window.innerHeight-10&&(O=w.top-E-6),O<10&&(O=10),T.style.left=D+`px`,T.style.top=O+`px`,T.style.maxHeight=E+`px`}function qx(e){let t=document.querySelector(`.execution-log-panel`);t&&t.remove();let n=document.createElement(`div`);n.className=`execution-log-panel`;let i=e.reduce((e,t)=>e+(t.duration||0),0),a=e.filter(e=>e.status===`success`).length,o=e.filter(e=>e.status===`failed`).length,s=e.filter(e=>e.nodeType===`subtask`).length,c=e.filter(e=>e.nodeType===`subtask`&&e.status===`success`).length,l=e.filter(e=>e.nodeType===`tool_exec`&&e.action?.name===`plan_task`&&e.status===`success`).length,u=e.filter(e=>e.nodeType===`reflection`).find(e=>e.reflectionType===`post`),d=u&&u.overallScore!=null?`${u.overallScore}/10`:r(`chatPanels.scoreUnavailable`),f=Rt(e);n.innerHTML=`
|
|
1482
1482
|
<div class="log-container">
|
|
1483
1483
|
<div class="log-header">
|
|
1484
1484
|
<div class="log-title">
|
|
@@ -1498,13 +1498,13 @@ It is this session's directory or the agent default, so it stays accessible (wor
|
|
|
1498
1498
|
</div>
|
|
1499
1499
|
|
|
1500
1500
|
<div class="log-summary">
|
|
1501
|
-
<div class="summary-item" title="${r(`chatPanels.totalDurationTitle`,{duration:
|
|
1501
|
+
<div class="summary-item" title="${r(`chatPanels.totalDurationTitle`,{duration:Bt(i)})}">
|
|
1502
1502
|
<svg class="summary-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
1503
1503
|
<circle cx="12" cy="12" r="10"></circle>
|
|
1504
1504
|
<polyline points="12 6 12 12 16 14"></polyline>
|
|
1505
1505
|
</svg>
|
|
1506
1506
|
<span class="summary-label">${r(`chatPanels.totalDuration`)}</span>
|
|
1507
|
-
<span class="summary-value">${
|
|
1507
|
+
<span class="summary-value">${Bt(i)}</span>
|
|
1508
1508
|
</div>
|
|
1509
1509
|
${f?`
|
|
1510
1510
|
<div class="summary-item token-summary" title="${r(`chatPanels.tokenUsageTitle`,{total:F(f.totalTokens),prompt:F(f.promptTokens),completion:F(f.completionTokens)})}">
|
|
@@ -1565,11 +1565,11 @@ It is this session's directory or the agent default, so it stays accessible (wor
|
|
|
1565
1565
|
<polygon points="5 3 19 12 5 21 5 3"></polygon>
|
|
1566
1566
|
</svg>
|
|
1567
1567
|
<span>${r(`chatMsg.resumeTaskBtn`)}</span>
|
|
1568
|
-
`,o.addEventListener(`click`,async e=>{if(e.stopPropagation(),o.disabled)return;let t=await Jx({budgetEnded:a});t!==null&&(o.disabled=!0,o.style.opacity=`0.6`,o.style.cursor=`not-allowed`,$x(N.activeSessionId,t).finally(()=>{o.disabled=!1,o.style.opacity=``,o.style.cursor=``}))}),n.appendChild(o),e.dataset.resumable=String(t),Xx(e,N.activeSessionId),o}async function Qx(){let e=N.activeSessionId;if(!e||N.pendingCallApiSessionIds&&N.pendingCallApiSessionIds.has(e))return;let t=N.messageHistory.some(e=>e.resumable),n=document.getElementById(`chatContainer`),i=n&&n.querySelector(`.resume-task-btn`);if(!(t&&i))try{let i=await chrome.runtime.sendMessage({type:`GET_CHECKPOINT`,sessionId:e});if(i?.exists){a.debug(`[SidePanel] found abandoned checkpoint,auto addrestorehint card`),document.dispatchEvent(new CustomEvent(`session-cache-invalidate`,{detail:{sessionId:e}}));let o=i.checkpoint,s=o.updatedAt?
|
|
1568
|
+
`,o.addEventListener(`click`,async e=>{if(e.stopPropagation(),o.disabled)return;let t=await Jx({budgetEnded:a});t!==null&&(o.disabled=!0,o.style.opacity=`0.6`,o.style.cursor=`not-allowed`,$x(N.activeSessionId,t).finally(()=>{o.disabled=!1,o.style.opacity=``,o.style.cursor=``}))}),n.appendChild(o),e.dataset.resumable=String(t),Xx(e,N.activeSessionId),o}async function Qx(){let e=N.activeSessionId;if(!e||N.pendingCallApiSessionIds&&N.pendingCallApiSessionIds.has(e))return;let t=N.messageHistory.some(e=>e.resumable),n=document.getElementById(`chatContainer`),i=n&&n.querySelector(`.resume-task-btn`);if(!(t&&i))try{let i=await chrome.runtime.sendMessage({type:`GET_CHECKPOINT`,sessionId:e});if(i?.exists){a.debug(`[SidePanel] found abandoned checkpoint,auto addrestorehint card`),document.dispatchEvent(new CustomEvent(`session-cache-invalidate`,{detail:{sessionId:e}}));let o=i.checkpoint,s=o.updatedAt?Bt(Date.now()-o.updatedAt):``,c=r(`chatResume.taskInterrupted`,{elapsed:s?r(`chatResume.interruptedAgo`,{duration:s}):``});if(t){let e=N.messageHistory.find(e=>e.resumable);if(e&&(e.content=c,OC()),n){let e=n.querySelector(`.message[data-resumable]:not([data-resumable="false"])`);if(!e){let t=n.querySelectorAll(`.message.assistant`);for(let n of t)if((n.textContent||``).includes(`任务执行被中断`)){e=n;break}}e&&e.remove()}}let{element:l,messageId:u}=iw(`assistant`,c,!0,[],null,!1,null,null,[],!0);t||(N.messageHistory.push({role:`assistant`,content:c,executionLog:[],messageId:u,resumable:!0,interrupted:!0}),OC()),Xx(l,e)}}catch(e){a.warn(`[SidePanel] check abandoned checkpoint failed:`,e.message)}}async function $x(e,t=``){if(!e)return a.warn(`[SidePanel] resumeTask: missing sessionId`),!1;if(N.activeSessionId!==e)return a.warn(`[SidePanel] resumeTask: currently activesessionwith targetsession not consistent,please switch firstto targetsession`),!1;if(N.pendingCallApiSessionIds&&N.pendingCallApiSessionIds.has(e))return a.warn(`[SidePanel] resumeTask: currentsession has ongoingtask`),!1;a.debug(`[SidePanel] resumeTask: startrestoretask, sessionId:`,e,`userGuidance:`,t?`"${t.substring(0,50)}..."`:`( no )`);try{let t=await chrome.runtime.sendMessage({type:`GET_CHECKPOINT`,sessionId:e});if(!t?.exists){a.warn(`[SidePanel] resumeTask: checkpoint not found, no way to restore, sessionId:`,e);let t=r(`chatResume.checkpointNotFound`),{messageId:n}=iw(`assistant`,t,!0,[]);return N.messageHistory.push({role:`assistant`,content:t,executionLog:[],messageId:n,resumable:!1,resumed:!0}),OC(),Yx(e),!1}a.debug(`[SidePanel] resumeTask: checkpoint verified, iteration:`,t.checkpoint?.iteration)}catch(e){a.warn(`[SidePanel] resumeTask: verify checkpoint hourcommunication failed,continue tryrestore:`,e.message)}let n=e,i=uw();N.isGenerating=!0;let o=``,s=[],c=null,l=!1,u=!1,d=!1,f=null,p=null;try{let e=await yw(null,null,!1,{},{resumeFromCheckpoint:!0,userGuidance:t,loadingId:i});o=e.content,s=e.executionLog||[],c=e.reflectionScore,l=e.wasRevised||!1,u=e.wasStreamed||!1,f=e.streamingHtml||null,e.streamingConnected!==void 0&&e.streamingConnected,p=e.streamingMsgId||null,d=e.budgetEnded===!0}catch(e){if(N.activeSessionId!==n){let t=e.message===r(`chatMsg.errTaskStopped`),a=!!e.checkpoint||e.swRestarted||t;return t?Zi(n,{role:`assistant`,content:r(`chatResume.taskCancelled`),executionLog:e.executionLog||[],resumable:a,resumed:!0}):e.swRestarted?Zi(n,{role:`assistant`,content:r(`chatResume.swRestarted`),executionLog:e.executionLog||[],resumable:a,resumed:!0}):Zi(n,{role:`assistant`,content:r(`chatResume.resumeFailed`,{message:e.message||r(`chatResume.unknownError`)}),executionLog:e.executionLog||[],resumable:!1,resumed:!0}),document.dispatchEvent(new CustomEvent(`session-cache-invalidate`,{detail:{sessionId:n}})),dw(i),!1}if(e.message===r(`chatMsg.errTaskStopped`)){dw(i);let{messageId:t}=iw(`assistant`,r(`chatResume.taskCancelled`),!1,e.executionLog||[]);return N.messageHistory.push({role:`assistant`,content:r(`chatResume.taskCancelled`),executionLog:e.executionLog||[],messageId:t,resumable:!0,resumed:!0}),OC(),!1}if(e.swRestarted){dw(i);let t=!!e.checkpoint,{messageId:n}=iw(`assistant`,r(`chatResume.swRestarted`),!1,e.executionLog||[]);return N.messageHistory.push({role:`assistant`,content:r(`chatResume.swRestarted`),executionLog:e.executionLog||[],messageId:n,resumable:t,resumed:!0}),OC(),!1}dw(i);let t=r(`chatResume.resumeFailed`,{message:e.message||r(`chatResume.unknownError`)}),{element:a,messageId:o}=iw(`assistant`,t,!0,e.executionLog||[]);return N.messageHistory.push({role:`assistant`,content:t,executionLog:e.executionLog||[],messageId:o,resumable:!1,resumed:!0}),OC(),!1}finally{jl(n)}Yx(n);let m=d?`budget`:!1;if(N.activeSessionId!==n){let e={role:`assistant`,content:o,executionLog:s,reflectionScore:c,wasRevised:l,resumable:m,resumed:!0};return u&&f&&(e.htmlContent=f),Zi(n,e),document.dispatchEvent(new CustomEvent(`session-cache-invalidate`,{detail:{sessionId:n}})),dw(i),!0}if(u&&f){let e=p;return N.messageHistory.push({role:`assistant`,content:o,executionLog:s,reflectionScore:c,wasRevised:l,resumable:m,messageId:e,resumed:!0,htmlContent:f}),OC(),m&&Zx(e?document.querySelector(`[data-message-id="${e}"]`):null,m),!0}dw(i);let{element:h,messageId:g}=iw(`assistant`,o,!0,s,c,l,null,null,[],m);return N.messageHistory.push({role:`assistant`,content:o,executionLog:s,reflectionScore:c,wasRevised:l,resumable:m,messageId:g,resumed:!0}),OC(),h&&cn(h),!0}var eS=300*1024,tS=typeof TextEncoder<`u`?new TextEncoder:null;function nS(e){return e?tS?tS.encode(e).length:e.length*3:0}var rS=`streamSnap|`,iS=e=>`${rS}${e}`,aS=new Map,oS=null;function sS(){return typeof chrome<`u`&&chrome.storage&&chrome.storage.session&&typeof chrome.storage.session.set==`function`}function cS(){if(oS||typeof window>`u`||!window.addEventListener||typeof document>`u`||!document.addEventListener)return;let e=()=>{fS()},t=()=>{document.visibilityState===`hidden`&&e()};oS={pagehide:e,onVisibility:t},window.addEventListener(`pagehide`,e),document.addEventListener(`visibilitychange`,t)}function lS(e,t,n){if(!e||!t||typeof n!=`function`||!sS())return;cS();let r=aS.get(e)||{};r.callId=t,r.read=n,r.timer||=setTimeout(()=>{let t=aS.get(e);t&&(t.timer=null,uS(e).catch(()=>{}))},700),aS.set(e,r)}async function uS(e){let t=aS.get(e);if(!t||(t.timer&&=(clearTimeout(t.timer),null),!sS()))return;let n;try{n=t.read()||{}}catch(e){a.debug(`[StreamSnapshot] 读取气泡内容失败(忽略):`,e?.message||e);return}let r=typeof n.html==`string`?n.html:``,i=typeof n.accumulated==`string`?n.accumulated:``,o=r,s=nS(r);s>307200&&(a.warn(`[StreamSnapshot] 快照 HTML ${s} 字节超过上限 ${eS},本次只存正文(接管后看不到工具卡片等富结构)`),o=``),await chrome.storage.session.set({[iS(e)]:{sessionId:e,callId:t.callId,html:o,accumulated:i,ts:Date.now()}})}function dS(e){let t=aS.get(e);t&&(t.timer&&clearTimeout(t.timer),aS.delete(e))}function fS(){return Promise.all([...aS.keys()].map(e=>uS(e).catch(e=>{a.debug(`[StreamSnapshot] 卸载前刷盘失败(忽略):`,e?.message||e)})))}async function pS(e){if(!e||!sS())return null;try{let t=await chrome.storage.session.get(iS(e)),n=t&&t[iS(e)];return!n||!n.callId?null:Date.now()-(n.ts||0)>18e5?(await mS(e),null):n}catch(e){return a.debug(`[StreamSnapshot] 读取快照失败(忽略):`,e?.message||e),null}}async function mS(e){let t=aS.get(e);if(t&&t.timer&&clearTimeout(t.timer),aS.delete(e),sS())try{await chrome.storage.session.remove(iS(e))}catch(e){a.debug(`[StreamSnapshot] 清除快照失败(忽略):`,e?.message||e)}}var hS=t({addStreamingMessage:()=>QS,appendThinkingIndicator:()=>nC,appendToolCallItems:()=>sC,appendToolResult:()=>uC,applyStreamSnapshot:()=>eC,autoScrollToBottom:()=>CS,bindProcessHeaderClick:()=>kS,cancelStreamingTask:()=>pC,createAgentStreamOutput:()=>lC,createCodeBlockHtml:()=>cC,createPreSelectCard:()=>dC,createStreamingElementAccessor:()=>RS,deleteStreamingState:()=>zS,finalizeCancelledStream:()=>mC,finalizeStreamingMessage:()=>fC,getPendingPreselectLog:()=>HS,getProcessStartTime:()=>KS,getReasoningContent:()=>JS,getStreamedContent:()=>BS,getThinkingStartTime:()=>WS,initScrollToBottomBtn:()=>ES,markStreamingRetrying:()=>tC,mountStreamingElement:()=>iC,notifyNonStreamContentArrived:()=>DS,reconnectStreamingElement:()=>aC,refreshAgentNames:()=>AS,resetScrollState:()=>TS,scrollStreamingToBottom:()=>wS,setPendingPreselectLog:()=>US,setProcessStartTime:()=>qS,setReasoningContent:()=>YS,setStreamedContent:()=>VS,setThinkingStartTime:()=>GS,updateScrollButtonState:()=>xS,updateStreamingMessage:()=>oC});n(`zh`,{chatStream:{thinking:`思考中...`,outputting:`输出中...`,retrying:`连接异常,正在重试 ({attempt}/{max})...`,stopGenerating:`停止生成`,thinkingResult:`思考结果`,toolActionOperate:`操作`,toolActionUpload:`上传`,toolActionDownload:`下载`,toolActionRequest:`请求`,toolActionInteract:`交互`,toolActionFill:`填写`,toolActionDispatch:`分派`,toolActionPreview:`预览`,toolActionRead:`读取`,toolActionWrite:`写入`,terminateCommand:`终止命令`,abortWaiting:`终止等待(跳过当前工具执行等待,不终止实际进程)`,executing:`执行中...`,terminating:`正在终止...`,copyCode:`复制代码`,truncatedTitle:`原始结果过大,已截断显示`,truncatedNote:`(输出过长已截断)`,noOutput:`(无输出)`,execFailed:`执行失败`,clickToExpand:`
|
|
1569
1569
|
... (点击展开查看完整输出)`,execResult:`执行结果`,statusFailed:`失败`,statusCompleted:`完成`,preselectFiltered:`从 {total} 个工具中筛选出 <strong>{count}</strong> 个:`,preselectSkippedAll:`跳过筛选({reason}),使用全部工具`,preselectSkippedCount:`跳过筛选({reason}),工具总数 {count}`,preselectDirectAnswer:`模型直接回答:`,toolPreselect:`工具预筛选`,toolsAfterFilter:`筛选后工具数:<strong>{count}</strong>`,listSeparator:`、`,totalNodes:`总节点`,successLabel:`成功`,failedLabel:`失败`,tokenLabel:`Token`,tokenUsageTitle:`Token 消耗: {total} (Prompt: {prompt}, Completion: {completion})`,thinkingProcess:`思考过程`,copyMarkdown:`复制 Markdown 内容 (Ctrl/Cmd + 点击复制富文本)`,copy:`复制`,quoteTitle:`引用该内容问答`,quote:`引用`,export:`导出`,exportWord:`导出 Word`,exportPdf:`导出 PDF`,exportImage:`导出图片`,exportMarkdown:`导出 Markdown`,executionLog:`执行日志`,reflectionRoundsTag:` ({count}轮)`,qualityAssessmentTitle:`AI 质量评估: {score}/10{rounds}
|
|
1570
1570
|
点击查看评估详情`,reflectionFailedTitle:`反思评估失败(点击查看执行日志)`,reflectionFailedBadge:`⚠️ 反思失败`,prototypeOpenedLocal:`已在本地浏览器打开,点击可在面板内查看`,viewUiPrototype:`查看 UI 原型`,bookmarkMessage:`收藏消息`,removeBookmark:`取消收藏`,forkSession:`从此处分叉会话(仅复制到此条消息)`,deleteMessage:`删除消息`,stopping:`停止中...`,taskStopped:`任务已被用户停止`,cancelled:`已取消`}}),n(`en`,{chatStream:{thinking:`Thinking...`,outputting:`Outputting...`,retrying:`Connection unstable, retrying ({attempt}/{max})...`,stopGenerating:`Stop generating`,thinkingResult:`Thinking result`,toolActionOperate:`Operate`,toolActionUpload:`Upload`,toolActionDownload:`Download`,toolActionRequest:`Request`,toolActionInteract:`Interact`,toolActionFill:`Fill`,toolActionDispatch:`Dispatch`,toolActionPreview:`Preview`,toolActionRead:`Read`,toolActionWrite:`Write`,terminateCommand:`Terminate command`,abortWaiting:`Abort waiting (skip current tool wait, does not terminate the actual process)`,executing:`Executing...`,terminating:`Terminating...`,copyCode:`Copy code`,truncatedTitle:`Original result too large, truncated for display`,truncatedNote:`(output too long, truncated)`,noOutput:`(no output)`,execFailed:`Execution failed`,clickToExpand:`
|
|
1571
1571
|
... (click to expand and view full output)`,execResult:`Execution result`,statusFailed:`Failed`,statusCompleted:`Completed`,preselectFiltered:`Filtered <strong>{count}</strong> of {total} tools: `,preselectSkippedAll:`Skipped filtering ({reason}), using all tools`,preselectSkippedCount:`Skipped filtering ({reason}), total tools: {count}`,preselectDirectAnswer:`Model direct answer: `,toolPreselect:`Tool Pre-filter`,toolsAfterFilter:`Tools after filtering: <strong>{count}</strong>`,listSeparator:`, `,totalNodes:`Total nodes`,successLabel:`Success`,failedLabel:`Failed`,tokenLabel:`Token`,tokenUsageTitle:`Token usage: {total} (Prompt: {prompt}, Completion: {completion})`,thinkingProcess:`Thinking process`,copyMarkdown:`Copy Markdown content (Ctrl/Cmd + click to copy rich text)`,copy:`Copy`,quoteTitle:`Quote this content for Q&A`,quote:`Quote`,export:`Export`,exportWord:`Export Word`,exportPdf:`Export PDF`,exportImage:`Export Image`,exportMarkdown:`Export Markdown`,executionLog:`Execution log`,reflectionRoundsTag:` ({count} rounds)`,qualityAssessmentTitle:`AI quality assessment: {score}/10{rounds}
|
|
1572
|
-
Click to view assessment details`,reflectionFailedTitle:`Reflection assessment failed (click to view execution log)`,reflectionFailedBadge:`⚠️ Reflection failed`,prototypeOpenedLocal:`Already opened in local browser, click to view in panel`,viewUiPrototype:`View UI prototype`,bookmarkMessage:`Bookmark message`,removeBookmark:`Remove bookmark`,forkSession:`Fork session from here (copy up to this message only)`,deleteMessage:`Delete message`,stopping:`Stopping...`,taskStopped:`Task stopped by user`,cancelled:`Cancelled`}});var gS=new Map,_S=!1,vS=!1,yS=!1,bS=!1;function xS(){let e=document.getElementById(`scrollToBottomBtn`),t=document.getElementById(`scrollToBottomBadge`);if(!e)return;let n=document.getElementById(`chatContainer`);if(!n)return;let r=n.scrollHeight-n.scrollTop-n.clientHeight<80;r?(e.classList.remove(`visible`),bS=!1):e.classList.add(`visible`),t&&(bS&&!r?(t.classList.add(`active`),N.isGenerating?t.classList.add(`pulsing`):t.classList.remove(`pulsing`)):t.classList.remove(`active`,`pulsing`))}function SS(){if(yS)return;let e=document.getElementById(`chatContainer`);e&&(yS=!0,e.addEventListener(`scroll`,()=>{if(_S)return;let t=e.scrollHeight-e.scrollTop-e.clientHeight<80;vS=!t,t?bS=!1:N.isGenerating&&(bS=!0),xS()},{passive:!0}),document.addEventListener(`generating-state-changed`,()=>{N.isGenerating&&(bS=!0),requestAnimationFrame(()=>xS())}))}function CS(e,t={}){if(!e)return;SS();let{force:n=!1,smooth:r=!1}=t;if(!n&&vS){bS=!0,xS();return}if(_S=!0,r){e.scrollTo({top:e.scrollHeight,behavior:`smooth`}),requestAnimationFrame(()=>{_S=!1});return}e.scrollTop=e.scrollHeight,requestAnimationFrame(()=>{vS||(e.scrollTop=e.scrollHeight),requestAnimationFrame(()=>{_S=!1})})}function wS(e){if(!e||!e.isConnected)return;let t=document.getElementById(`chatContainer`);t&&CS(t)}function TS(){vS=!1,bS=!1,N.isGenerating&&(bS=!0),xS()}function ES(){SS();let e=document.getElementById(`scrollToBottomBtn`);if(!e||e.dataset.bound)return;e.dataset.bound=`1`;let t=localStorage.getItem(`scrollBtnPosition`)||`center`;e.classList.add(`pos-${t}`);let n=!1,r=0,i=0,a=!1,o=0,s=!1;function c(){let t=document.getElementById(`chatContainer`);if(!t)return;let n=t.clientWidth,r={left:n/6,center:n/2,right:n*5/6},i=`center`,a=1/0;for(let[e,t]of Object.entries(r)){let n=Math.abs(o-t);n<a&&(a=n,i=e)}e.classList.remove(`pos-left`,`pos-center`,`pos-right`),e.classList.add(`pos-${i}`),e.style.left=``,e.style.marginLeft=``,e.style.right=``,localStorage.setItem(`scrollBtnPosition`,i)}function l(){let t=document.getElementById(`chatContainer`),n=e.getBoundingClientRect(),a=t?t.getBoundingClientRect():null,o=a?n.left-a.left+n.width/2:r;e.classList.remove(`pos-left`,`pos-center`,`pos-right`),e.style.left=`${o}px`,e.style.marginLeft=`0`,e.style.right=`auto`,e.classList.add(`dragging`),i=o,s=!0}function u(e){e.type===`mousedown`&&e.button!==0||(e.preventDefault(),n=!0,a=!1,s=!1,r=e.touches?e.touches[0].clientX:e.clientX)}function d(t){if(!n)return;let c=t.touches?t.touches[0].clientX:t.clientX;if(!s){if(Math.abs(c-r)<=3)return;a=!0,l()}let u=document.getElementById(`chatContainer`);if(!u)return;let d=u.getBoundingClientRect(),f=i+(c-r),p=e.offsetWidth/2;f=Math.max(p,Math.min(d.width-p,f)),o=f,e.style.left=`${f}px`}function f(){if(n){if(n=!1,a)e.classList.remove(`dragging`),c();else{s&&(e.classList.remove(`dragging`),e.style.left=``,e.style.marginLeft=``,e.style.right=``);let t=document.getElementById(`chatContainer`);t&&(vS=!1,bS=!1,xS(),CS(t,{force:!0,smooth:!0}))}a=!1,s=!1}}e.addEventListener(`mousedown`,u),e.addEventListener(`touchstart`,u,{passive:!1}),document.addEventListener(`mousemove`,d),document.addEventListener(`touchmove`,d,{passive:!1}),document.addEventListener(`mouseup`,f),document.addEventListener(`touchend`,f),xS()}function DS(){SS();let e=document.getElementById(`chatContainer`);e&&(e.scrollHeight-e.scrollTop-e.clientHeight<80||(bS=!0),xS())}function OS(e,t){let n=e.querySelector(`.thinking-process-content`);if(!n)return;e.dataset.activeFilter=t,e.querySelectorAll(`.thinking-process-stat[data-filter]`).forEach(e=>{e.classList.toggle(`active`,e.dataset.filter===t)});let r=e=>t===`all`||e===t;n.querySelectorAll(`.tool-call-item`).forEach(e=>{e.classList.contains(`preselect-card`)||(e.style.display=r(e.dataset.status)?``:`none`)}),n.querySelectorAll(`.thinking-badge`).forEach(e=>{let t=r(e.dataset.status||`success`);e.style.display=t?``:`none`;let n=e.nextElementSibling;n&&n.classList.contains(`thinking-content`)&&(n.style.display=t?``:`none`)}),n.querySelectorAll(`.thinking-content`).forEach(e=>{let t=e.previousElementSibling;t&&t.classList.contains(`thinking-badge`)||(e.style.display=r(`success`)?``:`none`)})}function kS(e){if(!e||e._filterBound)return;e._filterBound=!0;let t=[``,`success`,`failed`];e.querySelectorAll(`.thinking-process-stat`).forEach((e,n)=>{t[n]&&(e.dataset.filter=t[n],e.classList.add(`filterable`))}),e.querySelectorAll(`.token-stat`).forEach(e=>{e.style.cursor=`pointer`}),e.addEventListener(`click`,t=>{if(t.ctrlKey||t.metaKey)return;let n=t.target.closest(`.thinking-process-stat`),r=e.closest(`.thinking-process`);if(r){if(n&&n.classList.contains(`token-stat`)){let e=r.closest(`.message`);if(e)try{let t=e.dataset.executionLog,r=
|
|
1572
|
+
Click to view assessment details`,reflectionFailedTitle:`Reflection assessment failed (click to view execution log)`,reflectionFailedBadge:`⚠️ Reflection failed`,prototypeOpenedLocal:`Already opened in local browser, click to view in panel`,viewUiPrototype:`View UI prototype`,bookmarkMessage:`Bookmark message`,removeBookmark:`Remove bookmark`,forkSession:`Fork session from here (copy up to this message only)`,deleteMessage:`Delete message`,stopping:`Stopping...`,taskStopped:`Task stopped by user`,cancelled:`Cancelled`}});var gS=new Map,_S=!1,vS=!1,yS=!1,bS=!1;function xS(){let e=document.getElementById(`scrollToBottomBtn`),t=document.getElementById(`scrollToBottomBadge`);if(!e)return;let n=document.getElementById(`chatContainer`);if(!n)return;let r=n.scrollHeight-n.scrollTop-n.clientHeight<80;r?(e.classList.remove(`visible`),bS=!1):e.classList.add(`visible`),t&&(bS&&!r?(t.classList.add(`active`),N.isGenerating?t.classList.add(`pulsing`):t.classList.remove(`pulsing`)):t.classList.remove(`active`,`pulsing`))}function SS(){if(yS)return;let e=document.getElementById(`chatContainer`);e&&(yS=!0,e.addEventListener(`scroll`,()=>{if(_S)return;let t=e.scrollHeight-e.scrollTop-e.clientHeight<80;vS=!t,t?bS=!1:N.isGenerating&&(bS=!0),xS()},{passive:!0}),document.addEventListener(`generating-state-changed`,()=>{N.isGenerating&&(bS=!0),requestAnimationFrame(()=>xS())}))}function CS(e,t={}){if(!e)return;SS();let{force:n=!1,smooth:r=!1}=t;if(!n&&vS){bS=!0,xS();return}if(_S=!0,r){e.scrollTo({top:e.scrollHeight,behavior:`smooth`}),requestAnimationFrame(()=>{_S=!1});return}e.scrollTop=e.scrollHeight,requestAnimationFrame(()=>{vS||(e.scrollTop=e.scrollHeight),requestAnimationFrame(()=>{_S=!1})})}function wS(e){if(!e||!e.isConnected)return;let t=document.getElementById(`chatContainer`);t&&CS(t)}function TS(){vS=!1,bS=!1,N.isGenerating&&(bS=!0),xS()}function ES(){SS();let e=document.getElementById(`scrollToBottomBtn`);if(!e||e.dataset.bound)return;e.dataset.bound=`1`;let t=localStorage.getItem(`scrollBtnPosition`)||`center`;e.classList.add(`pos-${t}`);let n=!1,r=0,i=0,a=!1,o=0,s=!1;function c(){let t=document.getElementById(`chatContainer`);if(!t)return;let n=t.clientWidth,r={left:n/6,center:n/2,right:n*5/6},i=`center`,a=1/0;for(let[e,t]of Object.entries(r)){let n=Math.abs(o-t);n<a&&(a=n,i=e)}e.classList.remove(`pos-left`,`pos-center`,`pos-right`),e.classList.add(`pos-${i}`),e.style.left=``,e.style.marginLeft=``,e.style.right=``,localStorage.setItem(`scrollBtnPosition`,i)}function l(){let t=document.getElementById(`chatContainer`),n=e.getBoundingClientRect(),a=t?t.getBoundingClientRect():null,o=a?n.left-a.left+n.width/2:r;e.classList.remove(`pos-left`,`pos-center`,`pos-right`),e.style.left=`${o}px`,e.style.marginLeft=`0`,e.style.right=`auto`,e.classList.add(`dragging`),i=o,s=!0}function u(e){e.type===`mousedown`&&e.button!==0||(e.preventDefault(),n=!0,a=!1,s=!1,r=e.touches?e.touches[0].clientX:e.clientX)}function d(t){if(!n)return;let c=t.touches?t.touches[0].clientX:t.clientX;if(!s){if(Math.abs(c-r)<=3)return;a=!0,l()}let u=document.getElementById(`chatContainer`);if(!u)return;let d=u.getBoundingClientRect(),f=i+(c-r),p=e.offsetWidth/2;f=Math.max(p,Math.min(d.width-p,f)),o=f,e.style.left=`${f}px`}function f(){if(n){if(n=!1,a)e.classList.remove(`dragging`),c();else{s&&(e.classList.remove(`dragging`),e.style.left=``,e.style.marginLeft=``,e.style.right=``);let t=document.getElementById(`chatContainer`);t&&(vS=!1,bS=!1,xS(),CS(t,{force:!0,smooth:!0}))}a=!1,s=!1}}e.addEventListener(`mousedown`,u),e.addEventListener(`touchstart`,u,{passive:!1}),document.addEventListener(`mousemove`,d),document.addEventListener(`touchmove`,d,{passive:!1}),document.addEventListener(`mouseup`,f),document.addEventListener(`touchend`,f),xS()}function DS(){SS();let e=document.getElementById(`chatContainer`);e&&(e.scrollHeight-e.scrollTop-e.clientHeight<80||(bS=!0),xS())}function OS(e,t){let n=e.querySelector(`.thinking-process-content`);if(!n)return;e.dataset.activeFilter=t,e.querySelectorAll(`.thinking-process-stat[data-filter]`).forEach(e=>{e.classList.toggle(`active`,e.dataset.filter===t)});let r=e=>t===`all`||e===t;n.querySelectorAll(`.tool-call-item`).forEach(e=>{e.classList.contains(`preselect-card`)||(e.style.display=r(e.dataset.status)?``:`none`)}),n.querySelectorAll(`.thinking-badge`).forEach(e=>{let t=r(e.dataset.status||`success`);e.style.display=t?``:`none`;let n=e.nextElementSibling;n&&n.classList.contains(`thinking-content`)&&(n.style.display=t?``:`none`)}),n.querySelectorAll(`.thinking-content`).forEach(e=>{let t=e.previousElementSibling;t&&t.classList.contains(`thinking-badge`)||(e.style.display=r(`success`)?``:`none`)})}function kS(e){if(!e||e._filterBound)return;e._filterBound=!0;let t=[``,`success`,`failed`];e.querySelectorAll(`.thinking-process-stat`).forEach((e,n)=>{t[n]&&(e.dataset.filter=t[n],e.classList.add(`filterable`))}),e.querySelectorAll(`.token-stat`).forEach(e=>{e.style.cursor=`pointer`}),e.addEventListener(`click`,t=>{if(t.ctrlKey||t.metaKey)return;let n=t.target.closest(`.thinking-process-stat`),r=e.closest(`.thinking-process`);if(r){if(n&&n.classList.contains(`token-stat`)){let e=r.closest(`.message`);if(e)try{let t=e.dataset.executionLog,r=Rt(t?JSON.parse(t):[]);r&&Ot(r,n)}catch{}return}n&&n.dataset.filter?OS(r,r.dataset.activeFilter===n.dataset.filter?`all`:n.dataset.filter):r.classList.toggle(`collapsed`)}});let n=e.closest(`.thinking-process`);n&&OS(n,n.dataset.activeFilter||`all`)}async function AS(){try{let{getAllAgents:e}=await M(async()=>{let{getAllAgents:e}=await import(`./agent-store-CXWql6bl.js`).then(e=>e.t);return{getAllAgents:e}},__vite__mapDeps([0,1,2,3,4])),t=await e();gS.clear();for(let e of t)gS.set(e.id,e.name||e.id)}catch{}}function jS(e){return gS.get(e)||e}var MS=new Map,NS=new Map,PS=null,FS=0,IS=0,LS=``;function RS(e){return t=>t===void 0?MS.get(e)||null:(MS.set(e,t),t)}function zS(e){MS.delete(e),NS.delete(e),mS(e)}function BS(e){return NS.get(e)||``}function VS(e,t){if(NS.set(e,t),!t){dS(e);return}$S(MS.get(e))}function HS(){return PS}function US(e){PS=e}function WS(){return FS}function GS(e){FS=e}function KS(){return IS}function qS(e){IS=e}function JS(){return LS}function YS(e){LS=e}function XS(){return`
|
|
1573
1573
|
<svg class="thinking-icon pulse-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
1574
1574
|
<path d="M12 2a3 3 0 0 0-3 3v1a3 3 0 0 0 3 3 3 3 0 0 1 3 3v1a3 3 0 0 1-3 3 3 3 0 0 0-3 3v1a3 3 0 0 0 3 3"/>
|
|
1575
1575
|
<circle cx="8" cy="12" r="1.5"/>
|
|
@@ -1590,7 +1590,7 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
|
|
|
1590
1590
|
<div class="thinking-indicator">${XS()}</div>
|
|
1591
1591
|
<div class="stream-status hidden"></div>
|
|
1592
1592
|
</div>
|
|
1593
|
-
`,(!e||e===N.activeSessionId)&&t&&(t.appendChild(n),TS(),xS(),requestAnimationFrame(()=>{CS(t,{force:!0})})),ZS(n),n}function $S(e){let t=e?.dataset?.sessionId,n=e?.dataset?.callId;!t||!n||lS(t,n,()=>({html:e.innerHTML,accumulated:BS(t)}))}function eC(e,t){return!e||!t?!1:(e.innerHTML=t,ZS(e),e.querySelectorAll(`.tool-call-header`).forEach(e=>{e.addEventListener(`click`,t=>{t.ctrlKey||t.metaKey||e.closest(`.tool-call-item`)?.classList.toggle(`expanded`)})}),e.querySelectorAll(`.tool-call-result`).forEach(e=>{let t=e.querySelector(`code`),n=t?.dataset.fullContent;if(!n||n.length<=500)return;let r=t.textContent||``,i=!1;e.style.cursor=`pointer`,e.addEventListener(`click`,e=>{e.ctrlKey||e.metaKey||(e.stopPropagation(),i=!i,t.textContent=i?n:r)})}),sn(),!0)}function tC(e,t,n){let i=e?.querySelector(`.thinking-indicator:not(.hidden) .thinking-label`);return i?(i.textContent=r(`chatStream.retrying`,{attempt:t,max:n}),i.dataset.retrying=`1`,!0):!1}function nC(e){let t=e?.querySelector(`.stream-content`);if(!t||e.querySelector(`.thinking-indicator:not(.hidden)`))return null;let n=document.createElement(`div`);return n.className=`thinking-indicator`,n.innerHTML=XS(),t.appendChild(n),ZS(n),n}function rC(e,t,n){if(e.contains(n)){let r=n.previousElementSibling;r&&r.classList.contains(`thinking-content`)?e.insertBefore(t,r):e.insertBefore(t,n);return}let r=e.querySelectorAll(`.thinking-content`),i=r[r.length-1],a=i?i.nextElementSibling:null;i&&(!a||!a.classList.contains(`thinking-badge`))?e.insertBefore(t,i):e.appendChild(t)}function iC(e){let t=MS.get(e);if(!t||t.dataset.sessionId&&t.dataset.sessionId!==e)return!1;let n=document.getElementById(`chatContainer`);return n?(n.appendChild(t),requestAnimationFrame(()=>{n.scrollTop=n.scrollHeight}),!0):!1}function aC(e){let t=MS.get(e);if(!t||t.dataset.sessionId&&t.dataset.sessionId!==e)return;let n=document.getElementById(`chatContainer`);if(!n)return;n.appendChild(t);let i=NS.get(e)||``;if(i){oC(t,i);let e=t.querySelector(`.stream-content`);t.querySelectorAll(`.thinking-indicator:not(.hidden)`).forEach(t=>{if(t.classList.add(`hidden`),!e)return;let n=document.createElement(`span`);n.className=`thinking-badge`,n.dataset.status=`success`,n.innerHTML=`<svg class="thinking-icon-static" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 2a3 3 0 0 0-3 3v1a3 3 0 0 0 3 3 3 3 0 0 1 3 3v1a3 3 0 0 1-3 3 3 3 0 0 0-3 3v1a3 3 0 0 0 3 3"/><circle cx="8" cy="12" r="1.5"/><circle cx="16" cy="12" r="1.5"/></svg>`+r(`chatStream.thinkingResult`),rC(e,n,t)})}requestAnimationFrame(()=>{n.scrollTop=n.scrollHeight})}function oC(e,t){let n=e.querySelector(`.stream-content`);if(!n)return;let i=n.querySelector(`.thinking-indicator:not(.hidden)`)||e.querySelector(`.thinking-indicator:not(.hidden)`);if(i){let e=i.querySelector(`.thinking-label`);if(e&&(e.textContent===r(`chatStream.thinking`)||e.dataset.retrying===`1`)&&(e.textContent=r(`chatStream.outputting`),delete e.dataset.retrying),n.contains(i)){let e=i.previousElementSibling;if(e&&e.classList.contains(`thinking-content`))e.innerHTML=
|
|
1593
|
+
`,(!e||e===N.activeSessionId)&&t&&(t.appendChild(n),TS(),xS(),requestAnimationFrame(()=>{CS(t,{force:!0})})),ZS(n),n}function $S(e){let t=e?.dataset?.sessionId,n=e?.dataset?.callId;!t||!n||lS(t,n,()=>({html:e.innerHTML,accumulated:BS(t)}))}function eC(e,t){return!e||!t?!1:(e.innerHTML=t,ZS(e),e.querySelectorAll(`.tool-call-header`).forEach(e=>{e.addEventListener(`click`,t=>{t.ctrlKey||t.metaKey||e.closest(`.tool-call-item`)?.classList.toggle(`expanded`)})}),e.querySelectorAll(`.tool-call-result`).forEach(e=>{let t=e.querySelector(`code`),n=t?.dataset.fullContent;if(!n||n.length<=500)return;let r=t.textContent||``,i=!1;e.style.cursor=`pointer`,e.addEventListener(`click`,e=>{e.ctrlKey||e.metaKey||(e.stopPropagation(),i=!i,t.textContent=i?n:r)})}),sn(),!0)}function tC(e,t,n){let i=e?.querySelector(`.thinking-indicator:not(.hidden) .thinking-label`);return i?(i.textContent=r(`chatStream.retrying`,{attempt:t,max:n}),i.dataset.retrying=`1`,!0):!1}function nC(e){let t=e?.querySelector(`.stream-content`);if(!t||e.querySelector(`.thinking-indicator:not(.hidden)`))return null;let n=document.createElement(`div`);return n.className=`thinking-indicator`,n.innerHTML=XS(),t.appendChild(n),ZS(n),n}function rC(e,t,n){if(e.contains(n)){let r=n.previousElementSibling;r&&r.classList.contains(`thinking-content`)?e.insertBefore(t,r):e.insertBefore(t,n);return}let r=e.querySelectorAll(`.thinking-content`),i=r[r.length-1],a=i?i.nextElementSibling:null;i&&(!a||!a.classList.contains(`thinking-badge`))?e.insertBefore(t,i):e.appendChild(t)}function iC(e){let t=MS.get(e);if(!t||t.dataset.sessionId&&t.dataset.sessionId!==e)return!1;let n=document.getElementById(`chatContainer`);return n?(n.appendChild(t),requestAnimationFrame(()=>{n.scrollTop=n.scrollHeight}),!0):!1}function aC(e){let t=MS.get(e);if(!t||t.dataset.sessionId&&t.dataset.sessionId!==e)return;let n=document.getElementById(`chatContainer`);if(!n)return;n.appendChild(t);let i=NS.get(e)||``;if(i){oC(t,i);let e=t.querySelector(`.stream-content`);t.querySelectorAll(`.thinking-indicator:not(.hidden)`).forEach(t=>{if(t.classList.add(`hidden`),!e)return;let n=document.createElement(`span`);n.className=`thinking-badge`,n.dataset.status=`success`,n.innerHTML=`<svg class="thinking-icon-static" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 2a3 3 0 0 0-3 3v1a3 3 0 0 0 3 3 3 3 0 0 1 3 3v1a3 3 0 0 1-3 3 3 3 0 0 0-3 3v1a3 3 0 0 0 3 3"/><circle cx="8" cy="12" r="1.5"/><circle cx="16" cy="12" r="1.5"/></svg>`+r(`chatStream.thinkingResult`),rC(e,n,t)})}requestAnimationFrame(()=>{n.scrollTop=n.scrollHeight})}function oC(e,t){let n=e.querySelector(`.stream-content`);if(!n)return;let i=n.querySelector(`.thinking-indicator:not(.hidden)`)||e.querySelector(`.thinking-indicator:not(.hidden)`);if(i){let e=i.querySelector(`.thinking-label`);if(e&&(e.textContent===r(`chatStream.thinking`)||e.dataset.retrying===`1`)&&(e.textContent=r(`chatStream.outputting`),delete e.dataset.retrying),n.contains(i)){let e=i.previousElementSibling;if(e&&e.classList.contains(`thinking-content`))e.innerHTML=Jt(t);else{let e=document.createElement(`div`);e.className=`thinking-content`,e.innerHTML=Jt(t),n.insertBefore(e,i)}}else{let e=n.querySelectorAll(`.thinking-content`);if(e.length===0){let e=document.createElement(`div`);e.className=`thinking-content`,e.innerHTML=Jt(t),n.appendChild(e)}else{let r=e[e.length-1],i=r.nextElementSibling;if(!i||!i.classList.contains(`thinking-badge`))r.innerHTML=Jt(t);else{let e=document.createElement(`div`);e.className=`thinking-content`,e.innerHTML=Jt(t),n.appendChild(e)}}}}else{let e=n.querySelectorAll(`.thinking-badge`);if(e.length>0){let n=e[e.length-1],r=n.nextElementSibling;if(r&&r.classList.contains(`thinking-content`))r.innerHTML=Jt(t);else{let e=document.createElement(`div`);e.className=`thinking-content`,e.innerHTML=Jt(t),n.after(e)}}else{let e=document.createElement(`div`);e.className=`thinking-content`,e.innerHTML=Jt(t),n.appendChild(e)}}$S(e),e.isConnected&&requestAnimationFrame(()=>{let e=document.getElementById(`chatContainer`);e&&CS(e)})}function sC(e,t){if(!e||!t?.length)return;let n=e.querySelector(`.stream-content`);if(!n)return;let i=e.querySelector(`.thinking-indicator:not(.hidden)`);if(i){let e=FS>0?Bt(Date.now()-FS):``,t=document.createElement(`span`);t.className=`thinking-badge`,t.innerHTML=`<svg class="thinking-icon-static" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 2a3 3 0 0 0-3 3v1a3 3 0 0 0 3 3 3 3 0 0 1 3 3v1a3 3 0 0 1-3 3 3 3 0 0 0-3 3v1a3 3 0 0 0 3 3"/><circle cx="8" cy="12" r="1.5"/><circle cx="16" cy="12" r="1.5"/></svg>${r(`chatStream.thinkingResult`)}${e?` <span class="thinking-duration">`+e+`</span>`:``}`,t.dataset.status=`success`,rC(n,t,i),i.classList.add(`hidden`),n.contains(i)||i.remove()}let a={execute_command:{metaType:`exec`},agent_exec:{metaType:`exec`},agent_file:{metaType:`file`,action:r(`chatStream.toolActionOperate`)},file_upload:{metaType:`file`,action:r(`chatStream.toolActionUpload`)},download_file:{metaType:`file`,action:r(`chatStream.toolActionDownload`)},fetch_url:{metaType:`web`,action:r(`chatStream.toolActionRequest`)},interact_element:{metaType:`web`,action:r(`chatStream.toolActionInteract`)},fill_form:{metaType:`web`,action:r(`chatStream.toolActionFill`)},manage_tab:{metaType:`web`,action:r(`chatStream.toolActionOperate`)},search_browser_data:{metaType:`search`},search_in_page:{metaType:`search`},dispatch_task:{metaType:`subagent`,action:r(`chatStream.toolActionDispatch`)},exec_log:{metaType:`search`},preview_ui:{metaType:`web`,action:r(`chatStream.toolActionPreview`)}};t.filter(e=>e&&typeof e==`object`).forEach(e=>{let t=e.function?.name||`unknown`,i=a[t]||{metaType:`other`},o;try{o=JSON.parse(e.function?.arguments||`{}`)}catch{o={raw:e.function?.arguments||``}}let s=JSON.stringify(o,null,2),c=``,l=``;if(i.metaType===`exec`){let e=o.command||o.cmd||JSON.stringify(o);l=e,c=`<code class="tool-call-cmd">$ ${P(e)}</code>`}else if(i.metaType===`file`){let e=o.file_path||o.filePath||o.path||o.filename||o.fileName||o.url||``,n=i.action===r(`chatStream.toolActionRead`)?`📖`:i.action===r(`chatStream.toolActionWrite`)?`📝`:i.action===r(`chatStream.toolActionUpload`)?`📤`:`📥`;l=e||t,c=`<span class="tool-call-file">${n} ${P(e)||P(t)}</span>`}else if(i.metaType===`web`){let e=o.url||o.href||o.selector||``;l=e||JSON.stringify(o),c=`<span class="tool-call-web">${P(i.action)}: ${P(e)||P(JSON.stringify(o).substring(0,80))}</span>`}else if(i.metaType===`search`){let e=o.query||o.keyword||o.text||``;l=e||t,c=`<span class="tool-call-search">🔍 ${P(e)||P(t)}</span>`}else if(i.metaType===`subagent`){let e=o.subAgentId||o.agent_id||``,t=e?jS(e):``,n=(o.task||``).substring(0,80);t&&t!==e?(l=`${t} (${e}): ${n}`,c=`<span class="tool-call-subagent">🤖 <strong>${P(t)}</strong> <span class="tool-call-subagent-id">(${P(e)})</span>: ${P(n)}</span>`):(l=`${e}: ${n}`,c=`<span class="tool-call-subagent">🤖 <strong>${P(e)}</strong>: ${P(n)}</span>`)}else{let e=Object.keys(o);if(e.length===0)l=t,c=`<span>${P(t)}</span>`;else if(e.length===1){let t=JSON.stringify(o[e[0]]);l=`${e[0]}: ${t}`,c=`<span>${P(e[0])}: ${P(t.substring(0,80))}</span>`}else l=e.map(e=>`${e}=${JSON.stringify(o[e])}`).join(`, `),c=`<span>${e.slice(0,2).map(e=>`${P(e)}=${P(JSON.stringify(o[e]).substring(0,30))}`).join(`, `)}${e.length>2?` ...`:``}</span>`}let u=i.metaType===`exec`?`<svg class="tool-call-icon exec" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
1594
1594
|
<polyline points="4 17 10 11 4 5"/><line x1="12" y1="19" x2="20" y2="19"/>
|
|
1595
1595
|
</svg>`:i.metaType===`file`?`<svg class="tool-call-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
1596
1596
|
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
|
|
@@ -1634,14 +1634,14 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
|
|
|
1634
1634
|
<span class="tool-result-status ${e.success?`success`:`fail`}">
|
|
1635
1635
|
${e.success?`<svg viewBox="0 0 24 24" fill="currentColor" width="16" height="16"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/></svg>`:`<svg viewBox="0 0 24 24" fill="currentColor" width="16" height="16"><path d="M12 2C6.47 2 2 6.47 2 12s4.47 10 10 10 10-4.47 10-10S17.53 2 12 2zm5 13.59L15.59 17 12 13.41 8.41 17 7 15.59 10.59 12 7 8.41 8.41 7 12 10.59 15.59 7 17 8.41 13.41 12 17 15.59z"/></svg>`}
|
|
1636
1636
|
</span>
|
|
1637
|
-
${e.duration?`<span class="tool-result-duration">${
|
|
1637
|
+
${e.duration?`<span class="tool-result-duration">${Bt(e.duration)}</span>`:``}
|
|
1638
1638
|
${c}
|
|
1639
1639
|
`,f=u.querySelector(`.tool-call-chevron`);if(f?f.insertAdjacentHTML(`beforebegin`,d):u.insertAdjacentHTML(`beforeend`,d),!l||!e.success){let t=e.content||(e.success?r(`chatStream.noOutput`):r(`chatStream.execFailed`)),n=t.length>500?t.substring(0,500)+r(`chatStream.clickToExpand`):t,a=t,o=document.createElement(`div`);if(o.className=`tool-call-result`,o.innerHTML=`
|
|
1640
1640
|
<div class="tool-result-title">${r(`chatStream.execResult`)}</div>
|
|
1641
1641
|
<div class="tool-result-content">
|
|
1642
1642
|
${cC(P(n))}
|
|
1643
1643
|
</div>
|
|
1644
|
-
`,a.length>500){let e=o.querySelector(`code`);e.dataset.fullContent=a;let t=!1;o.style.cursor=`pointer`,o.addEventListener(`click`,r=>{r.ctrlKey||r.metaKey||(t=!t,e.textContent=t?a:n)})}let s=i.querySelector(`.tool-call-body`);s?s.appendChild(o):i.appendChild(o)}sn(),$S(t),t.isConnected&&requestAnimationFrame(()=>{let e=document.getElementById(`chatContainer`);e&&CS(e)})};s>0?setTimeout(c,s):c()}function dC(e){let t=document.createElement(`div`);t.className=`tool-call-item preselect-card`+(N.chatConfig?.streamExpandTools?` expanded`:``);let n=e.status===`failed`,i=``,a=``;if(e.action?.params?.selected){let t=e.action.params.selected;i=`<div class="tool-call-summary"><span>${r(`chatStream.preselectFiltered`,{total:e.apiRequest?.toolCount||`?`,count:t.length})}</span></div>`,a=`<span class="preselect-summary">${t.map(e=>`<code>${P(e)}</code>`).join(r(`chatStream.listSeparator`))}</span>`}else e.action?.name===`all_tools`?(i=`<div class="tool-call-summary"><span>${P(e.action.params.reason||``)}</span></div>`,a=`<span class="preselect-summary">${r(`chatStream.preselectSkippedAll`,{reason:P(e.action.params.reason||``)})}</span>`):e.action?.name===`skip`?(i=`<div class="tool-call-summary"><span>${P(e.action.params.reason||``)}</span></div>`,a=`<span class="preselect-summary">${r(`chatStream.preselectSkippedCount`,{reason:P(e.action.params.reason||``),count:e.action.params.toolCount||`?`})}</span>`):e.error?(i=`<div class="tool-call-summary"><span style="color:var(--danger-500);">${P(e.error)}</span></div>`,a=`<span class="preselect-summary" style="color:var(--danger-500);">${P(e.error)}</span>`):e.thought&&(i=`<div class="tool-call-summary"><span>${r(`chatStream.preselectDirectAnswer`)}</span></div>`,a=`<span class="preselect-summary">${r(`chatStream.preselectDirectAnswer`)}${P(e.thought).substring(0,200)}</span>`);let o=e.duration?
|
|
1644
|
+
`,a.length>500){let e=o.querySelector(`code`);e.dataset.fullContent=a;let t=!1;o.style.cursor=`pointer`,o.addEventListener(`click`,r=>{r.ctrlKey||r.metaKey||(t=!t,e.textContent=t?a:n)})}let s=i.querySelector(`.tool-call-body`);s?s.appendChild(o):i.appendChild(o)}sn(),$S(t),t.isConnected&&requestAnimationFrame(()=>{let e=document.getElementById(`chatContainer`);e&&CS(e)})};s>0?setTimeout(c,s):c()}function dC(e){let t=document.createElement(`div`);t.className=`tool-call-item preselect-card`+(N.chatConfig?.streamExpandTools?` expanded`:``);let n=e.status===`failed`,i=``,a=``;if(e.action?.params?.selected){let t=e.action.params.selected;i=`<div class="tool-call-summary"><span>${r(`chatStream.preselectFiltered`,{total:e.apiRequest?.toolCount||`?`,count:t.length})}</span></div>`,a=`<span class="preselect-summary">${t.map(e=>`<code>${P(e)}</code>`).join(r(`chatStream.listSeparator`))}</span>`}else e.action?.name===`all_tools`?(i=`<div class="tool-call-summary"><span>${P(e.action.params.reason||``)}</span></div>`,a=`<span class="preselect-summary">${r(`chatStream.preselectSkippedAll`,{reason:P(e.action.params.reason||``)})}</span>`):e.action?.name===`skip`?(i=`<div class="tool-call-summary"><span>${P(e.action.params.reason||``)}</span></div>`,a=`<span class="preselect-summary">${r(`chatStream.preselectSkippedCount`,{reason:P(e.action.params.reason||``),count:e.action.params.toolCount||`?`})}</span>`):e.error?(i=`<div class="tool-call-summary"><span style="color:var(--danger-500);">${P(e.error)}</span></div>`,a=`<span class="preselect-summary" style="color:var(--danger-500);">${P(e.error)}</span>`):e.thought&&(i=`<div class="tool-call-summary"><span>${r(`chatStream.preselectDirectAnswer`)}</span></div>`,a=`<span class="preselect-summary">${r(`chatStream.preselectDirectAnswer`)}${P(e.thought).substring(0,200)}</span>`);let o=e.duration?Bt(e.duration):``,s=n?`<svg viewBox="0 0 24 24" fill="currentColor" width="16" height="16"><path d="M12 2C6.47 2 2 6.47 2 12s4.47 10 10 10 10-4.47 10-10S17.53 2 12 2zm5 13.59L15.59 17 12 13.41 8.41 17 7 15.59 10.59 12 7 8.41 8.41 7 12 10.59 15.59 7 17 8.41 13.41 12 17 15.59z"/></svg>`:`<svg viewBox="0 0 24 24" fill="currentColor" width="16" height="16"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/></svg>`;return t.innerHTML=`
|
|
1645
1645
|
<div class="tool-call-header">
|
|
1646
1646
|
<svg class="tool-call-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
1647
1647
|
<circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/>
|
|
@@ -1656,7 +1656,7 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
|
|
|
1656
1656
|
${a}
|
|
1657
1657
|
${e.apiResponse?.toolCountAfter===void 0?``:`<div class="preselect-meta">${r(`chatStream.toolsAfterFilter`,{count:e.apiResponse.toolCountAfter})}</div>`}
|
|
1658
1658
|
</div>
|
|
1659
|
-
`,t.querySelector(`.tool-call-header`).addEventListener(`click`,e=>{e.ctrlKey||e.metaKey||t.classList.toggle(`expanded`)}),t}function fC(e,t,n=[],i=null,o=null,s=!1){if(!e)return;e.dataset.sessionId&&mS(e.dataset.sessionId);let c=e.querySelector(`.message-content`),l=e.querySelector(`.stream-content`),u=e.querySelector(`.thinking-indicator:not(.hidden)`);if(u&&l){let e=FS>0?
|
|
1659
|
+
`,t.querySelector(`.tool-call-header`).addEventListener(`click`,e=>{e.ctrlKey||e.metaKey||t.classList.toggle(`expanded`)}),t}function fC(e,t,n=[],i=null,o=null,s=!1){if(!e)return;e.dataset.sessionId&&mS(e.dataset.sessionId);let c=e.querySelector(`.message-content`),l=e.querySelector(`.stream-content`),u=e.querySelector(`.thinking-indicator:not(.hidden)`);if(u&&l){let e=FS>0?Bt(Date.now()-FS):``,t=document.createElement(`span`);if(t.className=`thinking-badge`,t.innerHTML=`<svg class="thinking-icon-static" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 2a3 3 0 0 0-3 3v1a3 3 0 0 0 3 3 3 3 0 0 1 3 3v1a3 3 0 0 1-3 3 3 3 0 0 0-3 3v1a3 3 0 0 0 3 3"/><circle cx="8" cy="12" r="1.5"/><circle cx="16" cy="12" r="1.5"/></svg>${r(`chatStream.thinkingResult`)}${e?` <span class="thinking-duration">`+e+`</span>`:``}`,t.dataset.status=`success`,l.contains(u)){let e=u.previousElementSibling;e&&e.classList.contains(`thinking-content`)?l.insertBefore(t,e):l.insertBefore(t,u),u.classList.add(`hidden`)}else{let e=l.querySelectorAll(`.thinking-content`);if(e.length>0){let n=e[e.length-1],r=n.nextElementSibling;!r||!r.classList.contains(`thinking-badge`)?l.insertBefore(t,n):l.appendChild(t)}else l.appendChild(t);u.classList.add(`hidden`),u.remove()}}e.querySelectorAll(`.thinking-indicator`).forEach(e=>e.classList.add(`hidden`));let d=e.querySelector(`.stream-status`);if(d&&d.remove(),e.classList.remove(`streaming`),c&&c.querySelector(`.tool-call-item`)||l&&l.querySelector(`.tool-call-item`)){let e=IS>0?Bt(Date.now()-IS):``,i=(n||[]).filter(e=>e.nodeType===`api_call`||e.nodeType===`tool_exec`),o=i.filter(e=>e.status===`success`).length,u=i.filter(e=>e.status===`failed`).length,d=i.length,f=Rt(n),p=document.createElement(`div`);p.className=`thinking-process collapsed`;let m=document.createElement(`div`);m.className=`thinking-process-header`;let h=d>0?`
|
|
1660
1660
|
<span class="thinking-process-stat">
|
|
1661
1661
|
<span class="stat-icon node-icon">◉</span>
|
|
1662
1662
|
<span class="stat-label">${r(`chatStream.totalNodes`)}</span>
|
|
@@ -1691,7 +1691,7 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
|
|
|
1691
1691
|
<svg class="thinking-process-chevron" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
1692
1692
|
<polyline points="6 9 12 15 18 9"/>
|
|
1693
1693
|
</svg>
|
|
1694
|
-
`,f){let e=m.querySelector(`.token-stat`);e&&(e.style.cursor=`pointer`,e.addEventListener(`click`,t=>{t.stopPropagation(),
|
|
1694
|
+
`,f){let e=m.querySelector(`.token-stat`);e&&(e.style.cursor=`pointer`,e.addEventListener(`click`,t=>{t.stopPropagation(),Ot(f,e)}))}let _=document.createElement(`div`);_.className=`thinking-process-body`;let v=document.createElement(`div`);if(v.className=`thinking-process-content`,_.appendChild(v),l)for(;l.firstChild;)v.appendChild(l.firstChild);c.querySelectorAll(`.tool-call-item`).forEach(e=>v.appendChild(e)),v.querySelectorAll(`.preselect-card`).forEach(e=>e.remove());let y=(n||[]).filter(e=>e.nodeType===`preselect`);a.debug(`[finalizeStreamingMessage] executionLog length:`,(n||[]).length,`preselectEntries:`,y.length),y.forEach(e=>{a.debug(`[finalizeStreamingMessage] creating preselect card for entry:`,e);let t=dC(e);v.insertBefore(t,v.firstChild)});let b=v.querySelectorAll(`.thinking-content`),x=yC(t).trim();if(b.length>0){let e=b[b.length-1],t=e.textContent.trim();if(!s||s&&t===x){let t=e.previousElementSibling;for(;t;){if(t.classList.contains(`thinking-badge`)){t.remove();break}t=t.previousElementSibling}e.remove()}}if(v.children.length>0&&v.textContent.trim()){p.appendChild(m),p.appendChild(_);let e=document.createElement(`div`);e.className=`final-answer`;let n=yC(t);n&&n.trim()&&(e.innerHTML=Jt(n));let r=c.querySelector(`.thinking-indicator`);r&&r.remove(),l&&(l.innerHTML=``),c.appendChild(p),c.appendChild(e),kS(m)}else{let e=c.querySelector(`.thinking-indicator`);if(e&&e.remove(),l){let e=yC(t);e&&e.trim()&&(l.innerHTML=Jt(e))}}}else if(l){let e=yC(t);if(l.querySelector(`.thinking-content`)){let t=IS>0?Bt(Date.now()-IS):``,i=(n||[]).filter(e=>e.nodeType===`api_call`||e.nodeType===`tool_exec`),a=i.filter(e=>e.status===`success`).length,o=i.filter(e=>e.status===`failed`).length,u=i.length,d=Rt(n),f=document.createElement(`div`);f.className=`thinking-process collapsed`;let p=document.createElement(`div`);p.className=`thinking-process-header`;let m=u>0?`
|
|
1695
1695
|
<span class="thinking-process-stat">
|
|
1696
1696
|
<span class="stat-icon node-icon">◉</span>
|
|
1697
1697
|
<span class="stat-label">${r(`chatStream.totalNodes`)}</span>
|
|
@@ -1726,7 +1726,7 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
|
|
|
1726
1726
|
<svg class="thinking-process-chevron" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
1727
1727
|
<polyline points="6 9 12 15 18 9"/>
|
|
1728
1728
|
</svg>
|
|
1729
|
-
`,d){let e=p.querySelector(`.token-stat`);e&&(e.style.cursor=`pointer`,e.addEventListener(`click`,t=>{t.stopPropagation(),Dt(d,e)}))}let g=document.createElement(`div`);g.className=`thinking-process-body`;let _=document.createElement(`div`);for(_.className=`thinking-process-content`,g.appendChild(_);l.firstChild;)_.appendChild(l.firstChild);let v=_.querySelectorAll(`.thinking-content`),y=e.trim();if(v.length>0){let e=v[v.length-1],t=e.textContent.trim();if(!s||s&&t===y){let t=e.previousElementSibling;for(;t;){if(t.classList.contains(`thinking-badge`)){t.remove();break}t=t.previousElementSibling}e.remove()}}if(_.children.length>0&&_.textContent.trim()){f.appendChild(p),f.appendChild(g);let t=document.createElement(`div`);t.className=`final-answer`,e&&e.trim()&&(t.innerHTML=qt(e));let n=c.querySelector(`.thinking-indicator`);n&&n.remove(),c.appendChild(f),c.appendChild(t),kS(p)}else{let t=c.querySelector(`.thinking-indicator`);t&&t.remove(),e&&e.trim()&&(l.innerHTML=qt(e))}}else e&&e.trim()&&(l.innerHTML=qt(e))}e.classList.add(`assistant`,`message`),e.dataset.rawContent=typeof t==`string`?rn(t):JSON.stringify(t),e.dataset.textContent_=rn(yC(t)),e.dataset.executionLog=JSON.stringify(n);let f=document.createElement(`div`);f.className=`message-footer`;let p=document.createElement(`button`);p.className=`copy-btn`,p.title=r(`chatStream.copyMarkdown`),p.innerHTML=[`<svg viewBox="0 0 16 16" fill="currentColor">`,`<path d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 0 1 0 1.5h-1.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-1.5a.75.75 0 0 1 1.5 0v1.5A1.75 1.75 0 0 1 9.25 16h-7.5A1.75 1.75 0 0 1 0 14.25zM5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0 1 14.25 11h-7.5A1.75 1.75 0 0 1 5 9.25zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25z"/>`,`</svg>`,`<span>`+r(`chatStream.copy`)+`</span>`].join(``),p.addEventListener(`click`,t=>{t.stopPropagation(),Lx(e,p,t)}),f.appendChild(p);let m=document.createElement(`button`);m.className=`quote-btn`,m.title=r(`chatStream.quoteTitle`),m.innerHTML=[`<svg t="1781246498458" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="9645" width="14" height="14"><path d="M156.09136 606.57001a457.596822 457.596822 0 0 1 221.680239-392.516385 50.844091 50.844091 0 1 1 50.844091 86.943396 355.90864 355.90864 0 0 0-138.804369 152.532274h16.77855a152.532274 152.532274 0 1 1-152.532274 152.532274z m406.752731 0a457.596822 457.596822 0 0 1 221.680239-392.007944 50.844091 50.844091 0 1 1 50.844091 86.943396 355.90864 355.90864 0 0 0-138.804369 152.532274h16.77855a152.532274 152.532274 0 1 1-152.532274 152.532274z" fill="#8a8a8a" p-id="9646"></path></svg>`,`<span>`+r(`chatStream.quote`)+`</span>`].join(``),m.addEventListener(`click`,t=>{t.stopPropagation(),Gx(e)}),f.appendChild(m),f.appendChild(_x());let h=document.createElement(`div`);h.className=`export-menu-container`;let g=document.createElement(`button`);g.className=`export-trigger-btn`,g.innerHTML=`<svg t="1781245244396" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5115" width="14" height="14"><path d="M496.213333 739.84c2.133333 2.133333 4.693333 3.84 7.68 5.12 0.853333 0.426667 2.133333 0.426667 2.986667 0.853333 1.706667 0.426667 2.986667 0.853333 4.693333 0.853334 5.546667 0 11.093333-2.133333 14.933334-6.4l256-256c8.533333-8.533333 8.533333-21.76 0-30.293334s-21.76-8.533333-30.293334 0L533.333333 674.133333V128c0-11.946667-9.386667-21.333333-21.333333-21.333333s-21.333333 9.386667-21.333333 21.333333v545.706667l-219.306667-219.306667c-8.533333-8.533333-21.76-8.533333-30.293333 0s-8.533333 21.76 0 30.293333l255.146666 255.146667zM768 874.666667H256c-11.946667 0-21.333333 9.386667-21.333333 21.333333s9.386667 21.333333 21.333333 21.333333h512c11.946667 0 21.333333-9.386667 21.333333-21.333333s-9.386667-21.333333-21.333333-21.333333z" fill="#8a8a8a" p-id="5116"></path></svg><span>`+r(`chatStream.export`)+`</span><svg class="dropdown-arrow" width="8" height="6" viewBox="0 0 8 6" fill="currentColor"><path d="M0 0l4 6 4-6z"/></svg>`;let _=document.createElement(`div`);_.className=`export-dropdown`,_.innerHTML=[`<button class="export-dropdown-item export-docx-item" type="button">`,`<svg t="1781245550030" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6544" width="32" height="32"><path d="M747.936 901.171H276.819c-72.2 0-130.953-55.224-130.953-123.078V244.721c0-67.854 58.752-123.078 130.953-123.078h383.525c6.597 0 12.937 2.505 17.795 6.954l192.363 178.046c5.317 4.96 8.386 11.914 8.386 19.227v452.223c0 67.854-58.752 123.078-130.952 123.078zM276.819 174.004c-43.31 0-78.592 31.703-78.592 70.717v533.372c0 39.015 35.282 70.718 78.592 70.718h471.117c43.31 0 78.592-31.703 78.592-70.718V337.324l-176.461-163.32H276.819z" fill="#8a8a8a" p-id="6545"></path><path d="M830.567 331.546H669.446c-14.471 0-26.18-11.71-26.18-26.181V156.209c0-14.471 11.709-26.18 26.18-26.18s26.181 11.709 26.181 26.18v122.976h134.94c14.471 0 26.181 11.709 26.181 26.18s-11.711 26.181-26.181 26.181z" fill="#8a8a8a" p-id="6546"></path><path d="M730.214 428.749l-92.04 343.616h-53.179L511.363 498.29l-75.677 274.074h-53.179l-92.04-343.616h49.088l69.542 255.667 69.541-255.667h63.406l69.541 255.667 69.541-255.667h49.088z" fill="#8a8a8a" p-id="6547"></path></svg>`,`<span>`+r(`chatStream.exportWord`)+`</span>`,`</button>`,`<button class="export-dropdown-item export-pdf-item" type="button">`,`<svg t="1781245863206" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="8152" width="32" height="32"><path d="M582.4 864H170.666667c-6.4 0-10.666667-4.266667-10.666667-10.666667V170.666667c0-6.4 4.266667-10.666667 10.666667-10.666667h309.333333V320c0 40.533333 34.133333 74.666667 74.666667 74.666667h160v38.4c0 17.066667 14.933333 32 32 32s32-14.933333 32-32V298.666667c0-8.533333-4.266667-17.066667-8.533334-23.466667l-170.666666-170.666667c-6.4-6.4-14.933333-8.533333-23.466667-8.533333H170.666667C130.133333 96 96 130.133333 96 170.666667v682.666666c0 40.533333 34.133333 74.666667 74.666667 74.666667h411.733333c17.066667 0 32-14.933333 32-32s-14.933333-32-32-32z m132.266667-550.4v17.066667H554.666667c-6.4 0-10.666667-4.266667-10.666667-10.666667V160h19.2l151.466667 153.6z" fill="#8a8a8a" p-id="8153"></path><path d="M332.8 533.333333c-12.8 0-19.2 2.133333-25.6 6.4-6.4 4.266667-8.533333 12.8-8.533333 23.466667v206.933333c0 6.4 2.133333 12.8 6.4 19.2 4.266667 4.266667 10.666667 8.533333 21.333333 8.533334s17.066667-4.266667 21.333333-8.533334c4.266667-4.266667 6.4-10.666667 6.4-19.2v-64h32c57.6 0 89.6-29.866667 89.6-87.466666 0-27.733333-8.533333-51.2-23.466666-64-14.933333-14.933333-36.266667-21.333333-66.133334-21.333334h-53.333333z m87.466667 85.333334c0 12.8-2.133333 23.466667-8.533334 27.733333-4.266667 4.266667-14.933333 8.533333-27.733333 8.533333h-32v-70.4H384c12.8 0 21.333333 2.133333 27.733333 8.533334 6.4 4.266667 8.533333 12.8 8.533334 25.6zM667.733333 571.733333c-8.533333-12.8-21.333333-21.333333-34.133333-29.866666-14.933333-4.266667-32-8.533333-51.2-8.533334h-61.866667c-8.533333 0-17.066667 0-23.466666 8.533334-2.133333 4.266667-4.266667 10.666667-4.266667 19.2V768c0 8.533333 2.133333 14.933333 4.266667 19.2 6.4 8.533333 14.933333 8.533333 23.466666 8.533333h64c19.2 0 34.133333-4.266667 49.066667-10.666666 12.8-6.4 25.6-17.066667 34.133333-29.866667 8.533333-12.8 14.933333-25.6 19.2-42.666667 4.266667-14.933333 6.4-32 6.4-49.066666 0-17.066667-2.133333-34.133333-6.4-49.066667-4.266667-14.933333-10.666667-29.866667-19.2-42.666667z m-42.666666 153.6c-8.533333 12.8-21.333333 19.2-38.4 19.2h-38.4v-160H576c21.333333 0 38.4 6.4 46.933333 19.2 10.666667 12.8 14.933333 34.133333 14.933334 59.733334 2.133333 27.733333-4.266667 46.933333-12.8 61.866666zM851.2 533.333333h-106.666667c-8.533333 0-17.066667 2.133333-21.333333 6.4-6.4 4.266667-8.533333 12.8-8.533333 21.333334v209.066666c0 6.4 2.133333 12.8 6.4 17.066667 4.266667 6.4 10.666667 8.533333 21.333333 8.533333 8.533333 0 17.066667-2.133333 21.333333-8.533333 2.133333-4.266667 6.4-8.533333 6.4-19.2v-85.333333h72.533334c12.8 0 23.466667-6.4 25.6-17.066667 2.133333-8.533333 2.133333-14.933333 0-17.066667-2.133333-4.266667-6.4-17.066667-25.6-17.066666H768v-49.066667h81.066667c8.533333 0 14.933333-2.133333 19.2-4.266667 4.266667-2.133333 8.533333-8.533333 8.533333-21.333333 2.133333-12.8-8.533333-23.466667-25.6-23.466667z" fill="#8a8a8a" p-id="8154"></path></svg>`,`<span>`+r(`chatStream.exportPdf`)+`</span>`,`</button>`,`<button class="export-dropdown-item export-image-item" type="button">`,`<svg t="1784207887308" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5993" width="32" height="32"><path d="M400.696 268.795c-17.249 0-31.233 13.986-31.233 31.233v30.471c0 17.249 13.986 31.233 31.233 31.233s31.233-13.986 31.233-31.233v-30.471c0-17.249-13.985-31.233-31.233-31.233z" fill="#8a8a8a" p-id="5994"></path><path d="M623.649 361.734c17.249 0 31.234-13.986 31.234-31.233v-30.471c0-17.249-13.986-31.233-31.234-31.233s-31.233 13.986-31.233 31.233v30.471c-0.001 17.248 13.985 31.233 31.233 31.233z" fill="#8a8a8a" p-id="5995"></path><path d="M438.295 388.804c-14.656 9.104-19.155 28.362-10.050 43.013 11.209 18.047 41.976 48.59 86.157 48.59 43.958 0 75.1-30.313 86.574-48.223 9.303-14.529 5.068-33.847-9.455-43.15-14.539-9.298-33.852-5.068-43.15 9.455-0.122 0.199-13.38 19.45-33.969 19.45-20.009 0-32.444-18.128-33.278-19.373-9.166-14.423-28.28-18.805-42.829-9.761z" fill="#8a8a8a" p-id="5996"></path><path d="M824.508503 116.690676 571.592236 116.690676c-17.248849 0-31.233352 13.985526-31.233352 31.233352s13.985526 31.233352 31.233352 31.233352l252.916267 0c40.181141 0 72.878844 32.692586 72.878844 72.878844l0 396.966057-189.334159-165.29465c-12.20088-10.655687-30.517037-10.207479-42.173518 0.9967L468.578048 674.16231 309.521472 517.519714c-11.895935-11.70253-30.903847-12.002358-43.154869-0.645706L126.957507 646.163629l0-394.126382c0-40.186258 32.692586-72.878844 72.878844-72.878844l252.916267 0c17.248849 0 31.233352-13.985526 31.233352-31.233352S470.000444 116.690676 452.751594 116.690676L199.836351 116.690676c-74.632791 0-135.346571 60.71378-135.346571 135.346571l0 520.56405c0 74.632791 60.71378 135.346571 135.346571 135.346571l252.916267 0c17.248849 0 31.233352-13.985526 31.233352-31.233352s-13.985526-31.233352-31.233352-31.233352L199.836351 845.481164c-40.186258 0-72.878844-32.692586-72.878844-72.878844l0-41.23924 160.003134-148.385539 159.428036 157.007917c12.048407 11.865235 31.361265 11.981892 43.546795 0.274246l198.576661-190.68697 208.876238 182.346001 0 40.683585c0 40.186258-32.697703 72.878844-72.878844 72.878844L571.592236 845.481164c-17.248849 0-31.233352 13.985526-31.233352 31.233352s13.985526 31.233352 31.233352 31.233352l252.916267 0c74.627674 0 135.346571-60.71378 135.346571-135.346571L959.855074 252.037247C959.855074 177.404456 899.136178 116.690676 824.508503 116.690676z" fill="#8a8a8a" p-id="5997"></path></svg>`,`<span>`+r(`chatStream.exportImage`)+`</span>`,`</button>`,`<button class="export-dropdown-item export-md-item" type="button">`,`<svg t="1784038824502" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1666" width="32" height="32"><path d="M601.216 85.333333a42.666667 42.666667 0 0 1 30.485333 12.821334l209.450667 213.973333a42.666667 42.666667 0 0 1 12.181333 29.866667V853.333333a85.333333 85.333333 0 0 1-85.333333 85.333334H256a85.333333 85.333333 0 0 1-85.333333-85.333334V170.666667a85.333333 85.333333 0 0 1 85.333333-85.333334h345.216z m-35.584 64H256a21.333333 21.333333 0 0 0-21.333333 21.333334v682.666666a21.333333 21.333333 0 0 0 21.333333 21.333334h512a21.333333 21.333333 0 0 0 21.333333-21.333334V395.413333h-191.68a32 32 0 0 1-32-32L565.632 149.333333z m64 38.186667v143.893333h140.821333L629.632 187.52z" fill="#8a8a8a" p-id="1667"></path><path d="M384.341333 800l-3.072-0.106667a32 32 0 0 1-29.162666-34.624l21.973333-256c2.752-32.256 46.165333-40.490667 60.544-11.477333l77.290667 156.010667 78.805333-156.224c14.08-27.925333 55.082667-20.906667 60.074667 8.789333l0.384 3.050667 20.714666 256a32 32 0 0 1-63.786666 5.162666l-11.541334-142.549333-56.341333 111.722667c-11.413333 22.613333-42.88 23.381333-55.744 2.517333l-1.493333-2.730667-54.912-110.826666-12.181334 142.016a32 32 0 0 1-31.552 29.269333z" fill="#8a8a8a" p-id="1668"></path></svg>`,`<span>`+r(`chatStream.exportMarkdown`)+`</span>`,`</button>`].join(``);let v=_.querySelector(`.export-docx-item`);v.addEventListener(`click`,async t=>{t.stopPropagation();let{exportAssistantMessageToDocx:n}=await M(async()=>{let{exportAssistantMessageToDocx:e}=await import(`./chat-export-CmaDpmwW.js`);return{exportAssistantMessageToDocx:e}},__vite__mapDeps([10,11,1,12,2,3,4,13,14,0]));n(e,v,_)});let y=_.querySelector(`.export-md-item`);y.addEventListener(`click`,async t=>{t.stopPropagation();let{exportAssistantMessageToMarkdown:n}=await M(async()=>{let{exportAssistantMessageToMarkdown:e}=await import(`./chat-export-CmaDpmwW.js`);return{exportAssistantMessageToMarkdown:e}},__vite__mapDeps([10,11,1,12,2,3,4,13,14,0]));n(e,y,_)});let b=_.querySelector(`.export-pdf-item`);b.addEventListener(`click`,async t=>{t.stopPropagation();let{exportAssistantMessageToPdf:n}=await M(async()=>{let{exportAssistantMessageToPdf:e}=await import(`./chat-export-CmaDpmwW.js`);return{exportAssistantMessageToPdf:e}},__vite__mapDeps([10,11,1,12,2,3,4,13,14,0]));n(e,b,_)});let x=_.querySelector(`.export-image-item`);x.addEventListener(`click`,async t=>{t.stopPropagation();let{exportAssistantMessageToImage:n}=await M(async()=>{let{exportAssistantMessageToImage:e}=await import(`./chat-export-CmaDpmwW.js`);return{exportAssistantMessageToImage:e}},__vite__mapDeps([10,11,1,12,2,3,4,13,14,0]));n(e,x,_)}),g.addEventListener(`click`,e=>{e.stopPropagation(),document.querySelectorAll(`.export-dropdown.show`).forEach(e=>{e!==_&&e.classList.remove(`show`)}),_.classList.toggle(`show`)});let S=null;h.addEventListener(`mouseenter`,()=>{S=setTimeout(()=>{document.querySelectorAll(`.export-dropdown.show`).forEach(e=>{e!==_&&e.classList.remove(`show`)}),_.classList.add(`show`)},300)}),h.addEventListener(`mouseleave`,()=>{S&&=(clearTimeout(S),null),setTimeout(()=>{!h.matches(`:hover`)&&!_.matches(`:hover`)&&_.classList.remove(`show`)},100)}),h.appendChild(g),h.appendChild(_),f.appendChild(h);let C=document.createElement(`div`);C.className=`footer-right-actions`,C.style.marginLeft=`auto`,C.style.display=`flex`,C.style.alignItems=`center`,C.style.gap=`8px`;let w=Lt(n);if(w){let e=document.createElement(`span`);e.className=`token-usage-tag`,e.title=r(`chatStream.tokenUsageTitle`,{total:F(w.totalTokens),prompt:F(w.promptTokens),completion:F(w.completionTokens)}),e.innerHTML=`<span class="token-tag-icon">⬤</span><span class="token-tag-value">${F(w.totalTokens)}</span>`,e.style.cursor=`pointer`,e.addEventListener(`click`,t=>{t.stopPropagation(),Dt(w,e)}),C.appendChild(e)}let T=Ly(t),E=By(n,t);if(T.length&&(e.dataset.declaredArtifacts=JSON.stringify(T)),ib(E),E.length>0){let e=document.createElement(`button`);e.className=`artifacts-btn`,e.type=`button`,e.title=r(`artifacts.btnTitle`,{count:E.length}),e.innerHTML=`
|
|
1729
|
+
`,d){let e=p.querySelector(`.token-stat`);e&&(e.style.cursor=`pointer`,e.addEventListener(`click`,t=>{t.stopPropagation(),Ot(d,e)}))}let g=document.createElement(`div`);g.className=`thinking-process-body`;let _=document.createElement(`div`);for(_.className=`thinking-process-content`,g.appendChild(_);l.firstChild;)_.appendChild(l.firstChild);let v=_.querySelectorAll(`.thinking-content`),y=e.trim();if(v.length>0){let e=v[v.length-1],t=e.textContent.trim();if(!s||s&&t===y){let t=e.previousElementSibling;for(;t;){if(t.classList.contains(`thinking-badge`)){t.remove();break}t=t.previousElementSibling}e.remove()}}if(_.children.length>0&&_.textContent.trim()){f.appendChild(p),f.appendChild(g);let t=document.createElement(`div`);t.className=`final-answer`,e&&e.trim()&&(t.innerHTML=Jt(e));let n=c.querySelector(`.thinking-indicator`);n&&n.remove(),c.appendChild(f),c.appendChild(t),kS(p)}else{let t=c.querySelector(`.thinking-indicator`);t&&t.remove(),e&&e.trim()&&(l.innerHTML=Jt(e))}}else e&&e.trim()&&(l.innerHTML=Jt(e))}e.classList.add(`assistant`,`message`),e.dataset.rawContent=typeof t==`string`?rn(t):JSON.stringify(t),e.dataset.textContent_=rn(yC(t)),e.dataset.executionLog=JSON.stringify(n);let f=document.createElement(`div`);f.className=`message-footer`;let p=document.createElement(`button`);p.className=`copy-btn`,p.title=r(`chatStream.copyMarkdown`),p.innerHTML=[`<svg viewBox="0 0 16 16" fill="currentColor">`,`<path d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 0 1 0 1.5h-1.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-1.5a.75.75 0 0 1 1.5 0v1.5A1.75 1.75 0 0 1 9.25 16h-7.5A1.75 1.75 0 0 1 0 14.25zM5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0 1 14.25 11h-7.5A1.75 1.75 0 0 1 5 9.25zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25z"/>`,`</svg>`,`<span>`+r(`chatStream.copy`)+`</span>`].join(``),p.addEventListener(`click`,t=>{t.stopPropagation(),Lx(e,p,t)}),f.appendChild(p);let m=document.createElement(`button`);m.className=`quote-btn`,m.title=r(`chatStream.quoteTitle`),m.innerHTML=[`<svg t="1781246498458" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="9645" width="14" height="14"><path d="M156.09136 606.57001a457.596822 457.596822 0 0 1 221.680239-392.516385 50.844091 50.844091 0 1 1 50.844091 86.943396 355.90864 355.90864 0 0 0-138.804369 152.532274h16.77855a152.532274 152.532274 0 1 1-152.532274 152.532274z m406.752731 0a457.596822 457.596822 0 0 1 221.680239-392.007944 50.844091 50.844091 0 1 1 50.844091 86.943396 355.90864 355.90864 0 0 0-138.804369 152.532274h16.77855a152.532274 152.532274 0 1 1-152.532274 152.532274z" fill="#8a8a8a" p-id="9646"></path></svg>`,`<span>`+r(`chatStream.quote`)+`</span>`].join(``),m.addEventListener(`click`,t=>{t.stopPropagation(),Gx(e)}),f.appendChild(m),f.appendChild(_x());let h=document.createElement(`div`);h.className=`export-menu-container`;let g=document.createElement(`button`);g.className=`export-trigger-btn`,g.innerHTML=`<svg t="1781245244396" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5115" width="14" height="14"><path d="M496.213333 739.84c2.133333 2.133333 4.693333 3.84 7.68 5.12 0.853333 0.426667 2.133333 0.426667 2.986667 0.853333 1.706667 0.426667 2.986667 0.853333 4.693333 0.853334 5.546667 0 11.093333-2.133333 14.933334-6.4l256-256c8.533333-8.533333 8.533333-21.76 0-30.293334s-21.76-8.533333-30.293334 0L533.333333 674.133333V128c0-11.946667-9.386667-21.333333-21.333333-21.333333s-21.333333 9.386667-21.333333 21.333333v545.706667l-219.306667-219.306667c-8.533333-8.533333-21.76-8.533333-30.293333 0s-8.533333 21.76 0 30.293333l255.146666 255.146667zM768 874.666667H256c-11.946667 0-21.333333 9.386667-21.333333 21.333333s9.386667 21.333333 21.333333 21.333333h512c11.946667 0 21.333333-9.386667 21.333333-21.333333s-9.386667-21.333333-21.333333-21.333333z" fill="#8a8a8a" p-id="5116"></path></svg><span>`+r(`chatStream.export`)+`</span><svg class="dropdown-arrow" width="8" height="6" viewBox="0 0 8 6" fill="currentColor"><path d="M0 0l4 6 4-6z"/></svg>`;let _=document.createElement(`div`);_.className=`export-dropdown`,_.innerHTML=[`<button class="export-dropdown-item export-docx-item" type="button">`,`<svg t="1781245550030" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6544" width="32" height="32"><path d="M747.936 901.171H276.819c-72.2 0-130.953-55.224-130.953-123.078V244.721c0-67.854 58.752-123.078 130.953-123.078h383.525c6.597 0 12.937 2.505 17.795 6.954l192.363 178.046c5.317 4.96 8.386 11.914 8.386 19.227v452.223c0 67.854-58.752 123.078-130.952 123.078zM276.819 174.004c-43.31 0-78.592 31.703-78.592 70.717v533.372c0 39.015 35.282 70.718 78.592 70.718h471.117c43.31 0 78.592-31.703 78.592-70.718V337.324l-176.461-163.32H276.819z" fill="#8a8a8a" p-id="6545"></path><path d="M830.567 331.546H669.446c-14.471 0-26.18-11.71-26.18-26.181V156.209c0-14.471 11.709-26.18 26.18-26.18s26.181 11.709 26.181 26.18v122.976h134.94c14.471 0 26.181 11.709 26.181 26.18s-11.711 26.181-26.181 26.181z" fill="#8a8a8a" p-id="6546"></path><path d="M730.214 428.749l-92.04 343.616h-53.179L511.363 498.29l-75.677 274.074h-53.179l-92.04-343.616h49.088l69.542 255.667 69.541-255.667h63.406l69.541 255.667 69.541-255.667h49.088z" fill="#8a8a8a" p-id="6547"></path></svg>`,`<span>`+r(`chatStream.exportWord`)+`</span>`,`</button>`,`<button class="export-dropdown-item export-pdf-item" type="button">`,`<svg t="1781245863206" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="8152" width="32" height="32"><path d="M582.4 864H170.666667c-6.4 0-10.666667-4.266667-10.666667-10.666667V170.666667c0-6.4 4.266667-10.666667 10.666667-10.666667h309.333333V320c0 40.533333 34.133333 74.666667 74.666667 74.666667h160v38.4c0 17.066667 14.933333 32 32 32s32-14.933333 32-32V298.666667c0-8.533333-4.266667-17.066667-8.533334-23.466667l-170.666666-170.666667c-6.4-6.4-14.933333-8.533333-23.466667-8.533333H170.666667C130.133333 96 96 130.133333 96 170.666667v682.666666c0 40.533333 34.133333 74.666667 74.666667 74.666667h411.733333c17.066667 0 32-14.933333 32-32s-14.933333-32-32-32z m132.266667-550.4v17.066667H554.666667c-6.4 0-10.666667-4.266667-10.666667-10.666667V160h19.2l151.466667 153.6z" fill="#8a8a8a" p-id="8153"></path><path d="M332.8 533.333333c-12.8 0-19.2 2.133333-25.6 6.4-6.4 4.266667-8.533333 12.8-8.533333 23.466667v206.933333c0 6.4 2.133333 12.8 6.4 19.2 4.266667 4.266667 10.666667 8.533333 21.333333 8.533334s17.066667-4.266667 21.333333-8.533334c4.266667-4.266667 6.4-10.666667 6.4-19.2v-64h32c57.6 0 89.6-29.866667 89.6-87.466666 0-27.733333-8.533333-51.2-23.466666-64-14.933333-14.933333-36.266667-21.333333-66.133334-21.333334h-53.333333z m87.466667 85.333334c0 12.8-2.133333 23.466667-8.533334 27.733333-4.266667 4.266667-14.933333 8.533333-27.733333 8.533333h-32v-70.4H384c12.8 0 21.333333 2.133333 27.733333 8.533334 6.4 4.266667 8.533333 12.8 8.533334 25.6zM667.733333 571.733333c-8.533333-12.8-21.333333-21.333333-34.133333-29.866666-14.933333-4.266667-32-8.533333-51.2-8.533334h-61.866667c-8.533333 0-17.066667 0-23.466666 8.533334-2.133333 4.266667-4.266667 10.666667-4.266667 19.2V768c0 8.533333 2.133333 14.933333 4.266667 19.2 6.4 8.533333 14.933333 8.533333 23.466666 8.533333h64c19.2 0 34.133333-4.266667 49.066667-10.666666 12.8-6.4 25.6-17.066667 34.133333-29.866667 8.533333-12.8 14.933333-25.6 19.2-42.666667 4.266667-14.933333 6.4-32 6.4-49.066666 0-17.066667-2.133333-34.133333-6.4-49.066667-4.266667-14.933333-10.666667-29.866667-19.2-42.666667z m-42.666666 153.6c-8.533333 12.8-21.333333 19.2-38.4 19.2h-38.4v-160H576c21.333333 0 38.4 6.4 46.933333 19.2 10.666667 12.8 14.933333 34.133333 14.933334 59.733334 2.133333 27.733333-4.266667 46.933333-12.8 61.866666zM851.2 533.333333h-106.666667c-8.533333 0-17.066667 2.133333-21.333333 6.4-6.4 4.266667-8.533333 12.8-8.533333 21.333334v209.066666c0 6.4 2.133333 12.8 6.4 17.066667 4.266667 6.4 10.666667 8.533333 21.333333 8.533333 8.533333 0 17.066667-2.133333 21.333333-8.533333 2.133333-4.266667 6.4-8.533333 6.4-19.2v-85.333333h72.533334c12.8 0 23.466667-6.4 25.6-17.066667 2.133333-8.533333 2.133333-14.933333 0-17.066667-2.133333-4.266667-6.4-17.066667-25.6-17.066666H768v-49.066667h81.066667c8.533333 0 14.933333-2.133333 19.2-4.266667 4.266667-2.133333 8.533333-8.533333 8.533333-21.333333 2.133333-12.8-8.533333-23.466667-25.6-23.466667z" fill="#8a8a8a" p-id="8154"></path></svg>`,`<span>`+r(`chatStream.exportPdf`)+`</span>`,`</button>`,`<button class="export-dropdown-item export-image-item" type="button">`,`<svg t="1784207887308" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5993" width="32" height="32"><path d="M400.696 268.795c-17.249 0-31.233 13.986-31.233 31.233v30.471c0 17.249 13.986 31.233 31.233 31.233s31.233-13.986 31.233-31.233v-30.471c0-17.249-13.985-31.233-31.233-31.233z" fill="#8a8a8a" p-id="5994"></path><path d="M623.649 361.734c17.249 0 31.234-13.986 31.234-31.233v-30.471c0-17.249-13.986-31.233-31.234-31.233s-31.233 13.986-31.233 31.233v30.471c-0.001 17.248 13.985 31.233 31.233 31.233z" fill="#8a8a8a" p-id="5995"></path><path d="M438.295 388.804c-14.656 9.104-19.155 28.362-10.050 43.013 11.209 18.047 41.976 48.59 86.157 48.59 43.958 0 75.1-30.313 86.574-48.223 9.303-14.529 5.068-33.847-9.455-43.15-14.539-9.298-33.852-5.068-43.15 9.455-0.122 0.199-13.38 19.45-33.969 19.45-20.009 0-32.444-18.128-33.278-19.373-9.166-14.423-28.28-18.805-42.829-9.761z" fill="#8a8a8a" p-id="5996"></path><path d="M824.508503 116.690676 571.592236 116.690676c-17.248849 0-31.233352 13.985526-31.233352 31.233352s13.985526 31.233352 31.233352 31.233352l252.916267 0c40.181141 0 72.878844 32.692586 72.878844 72.878844l0 396.966057-189.334159-165.29465c-12.20088-10.655687-30.517037-10.207479-42.173518 0.9967L468.578048 674.16231 309.521472 517.519714c-11.895935-11.70253-30.903847-12.002358-43.154869-0.645706L126.957507 646.163629l0-394.126382c0-40.186258 32.692586-72.878844 72.878844-72.878844l252.916267 0c17.248849 0 31.233352-13.985526 31.233352-31.233352S470.000444 116.690676 452.751594 116.690676L199.836351 116.690676c-74.632791 0-135.346571 60.71378-135.346571 135.346571l0 520.56405c0 74.632791 60.71378 135.346571 135.346571 135.346571l252.916267 0c17.248849 0 31.233352-13.985526 31.233352-31.233352s-13.985526-31.233352-31.233352-31.233352L199.836351 845.481164c-40.186258 0-72.878844-32.692586-72.878844-72.878844l0-41.23924 160.003134-148.385539 159.428036 157.007917c12.048407 11.865235 31.361265 11.981892 43.546795 0.274246l198.576661-190.68697 208.876238 182.346001 0 40.683585c0 40.186258-32.697703 72.878844-72.878844 72.878844L571.592236 845.481164c-17.248849 0-31.233352 13.985526-31.233352 31.233352s13.985526 31.233352 31.233352 31.233352l252.916267 0c74.627674 0 135.346571-60.71378 135.346571-135.346571L959.855074 252.037247C959.855074 177.404456 899.136178 116.690676 824.508503 116.690676z" fill="#8a8a8a" p-id="5997"></path></svg>`,`<span>`+r(`chatStream.exportImage`)+`</span>`,`</button>`,`<button class="export-dropdown-item export-md-item" type="button">`,`<svg t="1784038824502" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1666" width="32" height="32"><path d="M601.216 85.333333a42.666667 42.666667 0 0 1 30.485333 12.821334l209.450667 213.973333a42.666667 42.666667 0 0 1 12.181333 29.866667V853.333333a85.333333 85.333333 0 0 1-85.333333 85.333334H256a85.333333 85.333333 0 0 1-85.333333-85.333334V170.666667a85.333333 85.333333 0 0 1 85.333333-85.333334h345.216z m-35.584 64H256a21.333333 21.333333 0 0 0-21.333333 21.333334v682.666666a21.333333 21.333333 0 0 0 21.333333 21.333334h512a21.333333 21.333333 0 0 0 21.333333-21.333334V395.413333h-191.68a32 32 0 0 1-32-32L565.632 149.333333z m64 38.186667v143.893333h140.821333L629.632 187.52z" fill="#8a8a8a" p-id="1667"></path><path d="M384.341333 800l-3.072-0.106667a32 32 0 0 1-29.162666-34.624l21.973333-256c2.752-32.256 46.165333-40.490667 60.544-11.477333l77.290667 156.010667 78.805333-156.224c14.08-27.925333 55.082667-20.906667 60.074667 8.789333l0.384 3.050667 20.714666 256a32 32 0 0 1-63.786666 5.162666l-11.541334-142.549333-56.341333 111.722667c-11.413333 22.613333-42.88 23.381333-55.744 2.517333l-1.493333-2.730667-54.912-110.826666-12.181334 142.016a32 32 0 0 1-31.552 29.269333z" fill="#8a8a8a" p-id="1668"></path></svg>`,`<span>`+r(`chatStream.exportMarkdown`)+`</span>`,`</button>`].join(``);let v=_.querySelector(`.export-docx-item`);v.addEventListener(`click`,async t=>{t.stopPropagation();let{exportAssistantMessageToDocx:n}=await M(async()=>{let{exportAssistantMessageToDocx:e}=await import(`./chat-export-CDzJ0eSb.js`);return{exportAssistantMessageToDocx:e}},__vite__mapDeps([10,11,1,4,12,2,3,13,14,0]));n(e,v,_)});let y=_.querySelector(`.export-md-item`);y.addEventListener(`click`,async t=>{t.stopPropagation();let{exportAssistantMessageToMarkdown:n}=await M(async()=>{let{exportAssistantMessageToMarkdown:e}=await import(`./chat-export-CDzJ0eSb.js`);return{exportAssistantMessageToMarkdown:e}},__vite__mapDeps([10,11,1,4,12,2,3,13,14,0]));n(e,y,_)});let b=_.querySelector(`.export-pdf-item`);b.addEventListener(`click`,async t=>{t.stopPropagation();let{exportAssistantMessageToPdf:n}=await M(async()=>{let{exportAssistantMessageToPdf:e}=await import(`./chat-export-CDzJ0eSb.js`);return{exportAssistantMessageToPdf:e}},__vite__mapDeps([10,11,1,4,12,2,3,13,14,0]));n(e,b,_)});let x=_.querySelector(`.export-image-item`);x.addEventListener(`click`,async t=>{t.stopPropagation();let{exportAssistantMessageToImage:n}=await M(async()=>{let{exportAssistantMessageToImage:e}=await import(`./chat-export-CDzJ0eSb.js`);return{exportAssistantMessageToImage:e}},__vite__mapDeps([10,11,1,4,12,2,3,13,14,0]));n(e,x,_)}),g.addEventListener(`click`,e=>{e.stopPropagation(),document.querySelectorAll(`.export-dropdown.show`).forEach(e=>{e!==_&&e.classList.remove(`show`)}),_.classList.toggle(`show`)});let S=null;h.addEventListener(`mouseenter`,()=>{S=setTimeout(()=>{document.querySelectorAll(`.export-dropdown.show`).forEach(e=>{e!==_&&e.classList.remove(`show`)}),_.classList.add(`show`)},300)}),h.addEventListener(`mouseleave`,()=>{S&&=(clearTimeout(S),null),setTimeout(()=>{!h.matches(`:hover`)&&!_.matches(`:hover`)&&_.classList.remove(`show`)},100)}),h.appendChild(g),h.appendChild(_),f.appendChild(h);let C=document.createElement(`div`);C.className=`footer-right-actions`,C.style.marginLeft=`auto`,C.style.display=`flex`,C.style.alignItems=`center`,C.style.gap=`8px`;let w=Rt(n);if(w){let e=document.createElement(`span`);e.className=`token-usage-tag`,e.title=r(`chatStream.tokenUsageTitle`,{total:F(w.totalTokens),prompt:F(w.promptTokens),completion:F(w.completionTokens)}),e.innerHTML=`<span class="token-tag-icon">⬤</span><span class="token-tag-value">${F(w.totalTokens)}</span>`,e.style.cursor=`pointer`,e.addEventListener(`click`,t=>{t.stopPropagation(),Ot(w,e)}),C.appendChild(e)}let T=Ly(t),E=By(n,t);if(T.length&&(e.dataset.declaredArtifacts=JSON.stringify(T)),ib(E),E.length>0){let e=document.createElement(`button`);e.className=`artifacts-btn`,e.type=`button`,e.title=r(`artifacts.btnTitle`,{count:E.length}),e.innerHTML=`
|
|
1730
1730
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="14" height="14">
|
|
1731
1731
|
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
|
|
1732
1732
|
<polyline points="14 2 14 8 20 8"/>
|
|
@@ -1752,7 +1752,7 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
|
|
|
1752
1752
|
点击查看评估详情`,reflectionFailedTitle:`反思评估失败(点击查看执行日志)`,reflectionFailedBadge:`⚠️ 反思失败`,prototypeLocalOpened:`已在本地浏览器打开,点击可在面板内查看`,prototypeView:`查看 UI 原型`,bookmarkMessage:`收藏消息`,unbookmarkMessage:`取消收藏`,forkSession:`从此处分叉会话(仅复制到此条消息)`,deleteMessageTitle:`删除消息`,resumeTaskTitle:`从上次中断处继续执行任务`,resumeTaskTitleBudget:`执行预算已用完(部分完成):点击后可在新的预算下接着未完成的部分继续`,resumeTaskBtn:`继续执行`,clickToEnlarge:`点击查看大图`,fileExtracting:` 提取中...`,fileFailed:` 失败`,fileExtractFailed:`提取失败`,copyMessageTitle:`复制消息内容`,editAndResend:`编辑后重新发送`,thinking:`思考中...`,stopTask:`停止任务`,viewExecutionLog:`查看执行日志`,preparing:`准备中...`,emptyModelReply:`模型未返回任何内容。若你发送了图片,请确认所选模型支持视觉识别(图片识别需选择支持多模态视觉的模型),或更换模型后重试。`,stopping:`停止中...`,copyCode:`复制代码`,aborting:`正在终止...`,terminateCommandTitle:`终止命令执行`,terminateCommandPrompt:`请选择终止方式:`,terminateWaitTitle:`终止等待`,terminateWaitDesc:`仅停止等待命令输出,后台进程继续运行。<br/>适用于挂起型服务(如 npm run dev)。`,terminateCommandBtnTitle:`终止命令`,terminateCommandBtnDesc:`直接终止后台命令进程,释放资源。`,confirmDeleteMessage:`确认删除消息`,deleteMessageWarning:`删除后消息将从对话历史中移除,且无法恢复。`,confirmDelete:`确认删除`,quotedContextLabel:`💬 已引用: {text}`,selectedContextLabel:`📌 已选中: {text}`,subtaskDone:`完成`,subtaskFailed:`失败`,subtaskPartial:`部分完成`,subtaskFailReason:`中断原因:{error}`,subtaskExecuting:`执行中...`,subtaskPending:`待执行`,subtaskDescLabel:`任务描述:`,subtaskResultLabel:`产出摘要:`,subtaskAllDone:`✓ 全部完成`,subtaskReplaySkipped:`已跳过重放`,subtaskReplaySkippedHint:`中断前已成功完成,本轮未重复执行,写操作不会二次生效`,subtaskFilterEmpty:`当前过滤下无匹配节点`,subtaskFilterHint:`点击按此状态过滤节点,再点取消`,subtaskStatOtherHint:`已取消 / 未完成节点(用户拒绝确认、任务终止时仍在执行等),点击过滤`,subtaskPartialFail:`✗ {success}/{total} 完成,{fail} 个节点失败`,unknownNode:`未知`,stopGeneration:`停止生成`,toolResultTitle:`执行结果`,reflectionInProgress:`质量评估中...`,cannotGetMessageContent:`无法获取消息内容`,editFailed:`编辑失败: {message}`,errTaskStopped:`任务已被用户停止`,errTaskReplaced:`任务已被新请求替代`,errSwRestarted:`后台服务异常重启,API 调用已中断`,errTimeout:`请求超时({seconds}秒)`,cancelBtn:`取消`}}),n(`en`,{chatMsg:{searchPrompt:`Search`,exportWord:`Export Word`,exportPdf:`Export PDF`,exportImage:`Export Image`,exportMarkdown:`Export Markdown`,executionLogTitle:`Execution Log`,revisedTag:`Revised`,roundsTag:` ({count} rounds)`,revisedSuffix:` (Revised)`,scoreBadgeTitle:`AI Quality Assessment: {score}/10{rounds}{revised}
|
|
1753
1753
|
Click to view assessment details`,reflectionFailedTitle:`Reflection assessment failed (click to view execution log)`,reflectionFailedBadge:`⚠️ Reflection Failed`,prototypeLocalOpened:`Opened in local browser, click to view in panel`,prototypeView:`View UI Prototype`,bookmarkMessage:`Bookmark message`,unbookmarkMessage:`Remove bookmark`,forkSession:`Fork session from here (copy up to this message only)`,deleteMessageTitle:`Delete message`,resumeTaskTitle:`Resume task from last interruption`,resumeTaskTitleBudget:`Execution budget exhausted (partially complete): click to continue the unfinished parts with a fresh budget`,resumeTaskBtn:`Resume`,clickToEnlarge:`Click to view full size`,fileExtracting:` extracting...`,fileFailed:` failed`,fileExtractFailed:`Extraction failed`,copyMessageTitle:`Copy message content`,editAndResend:`Edit and resend`,thinking:`Thinking...`,stopTask:`Stop task`,viewExecutionLog:`View execution log`,preparing:`Preparing...`,emptyModelReply:`The model returned no content. If you sent an image, make sure the selected model supports vision (image recognition requires a multimodal vision model), or switch model and retry.`,stopping:`Stopping...`,copyCode:`Copy code`,aborting:`Aborting...`,terminateCommandTitle:`Terminate Command Execution`,terminateCommandPrompt:`Please select a termination method:`,terminateWaitTitle:`Stop Waiting`,terminateWaitDesc:`Only stop waiting for command output; the background process continues running.<br/>Suitable for hanging services (e.g. npm run dev).`,terminateCommandBtnTitle:`Terminate Command`,terminateCommandBtnDesc:`Directly terminate the background command process and release resources.`,confirmDeleteMessage:`Confirm Delete Message`,deleteMessageWarning:`After deletion, the message will be removed from the conversation history and cannot be recovered.`,confirmDelete:`Confirm Delete`,quotedContextLabel:`💬 Quoted: {text}`,selectedContextLabel:`📌 Selected: {text}`,subtaskDone:`Done`,subtaskFailed:`Failed`,subtaskPartial:`Partial`,subtaskFailReason:`Interrupted: {error}`,subtaskExecuting:`Executing...`,subtaskPending:`Pending`,subtaskDescLabel:`Description: `,subtaskResultLabel:`Output summary: `,subtaskAllDone:`✓ All done`,subtaskReplaySkipped:`replay skipped`,subtaskReplaySkippedHint:`Already completed before the interruption; not re-run this round, so side effects do not apply twice`,subtaskFilterEmpty:`No nodes match this filter`,subtaskFilterHint:`Click to filter nodes by this status, click again to clear`,subtaskStatOtherHint:`Cancelled / unfinished nodes (denied confirmations, still running when the task ended). Click to filter`,subtaskPartialFail:`✗ {success}/{total} done, {fail} nodes failed`,unknownNode:`Unknown`,stopGeneration:`Stop generation`,toolResultTitle:`Execution Result`,reflectionInProgress:`Assessing quality...`,cannotGetMessageContent:`Cannot get message content`,editFailed:`Edit failed: {message}`,errTaskStopped:`Task stopped by user`,errTaskReplaced:`Task replaced by new request`,errSwRestarted:`Background service restarted unexpectedly, API call interrupted`,errTimeout:`Request timeout ({seconds}s)`,cancelBtn:`Cancel`}});var gC=`pendingCallApiSessions`;function _C(){chrome.storage.session.set({[gC]:[...N.pendingCallApiSessionIds]}).catch(()=>{})}async function vC(){try{let e=await chrome.storage.session.get([gC]);e[gC]&&Array.isArray(e[gC])&&(N.pendingCallApiSessionIds=new Set(e[gC]))}catch{}}function yC(e){if(Array.isArray(e))return e.filter(e=>e.type===`text`).map(e=>e.text).join(``);if(typeof e==`string`&&e.startsWith(`[`))try{let t=JSON.parse(e);if(Array.isArray(t))return t.filter(e=>e.type===`text`).map(e=>e.text).join(``)}catch{}return e}function bC(e){let t=yC(e);N.quotedContextText=t;let n=document.getElementById(`selectionIndicator`),i=document.getElementById(`selectionText`),a=document.getElementById(`userInput`);if(n&&i&&a){let e;e=t.length>100?t.substring(0,100)+`...`:t.length>50?t.substring(0,50)+`...`:t,i.textContent=r(`chat.quotedPrefix`,{text:e}),n.classList.add(`show`)}}function xC(){let e=document.getElementById(`selectionIndicator`),t=document.getElementById(`selectionText`);if(!e||!t)return;let n=(N.quotedContextText||``).trim(),i=(N.selectedContextText||``).trim(),a=n||i;if(!a){e.classList.remove(`show`);return}let o;o=a.length>100?a.substring(0,100)+`...`:a.length>50?a.substring(0,50)+`...`:a,t.textContent=r(n?`chatMsg.quotedContextLabel`:`chatMsg.selectedContextLabel`,{text:o}),e.classList.add(`show`)}function SC(){a.debug(`[SidePanel] clear selectedcontenttext `),N.selectedContextText=``,N.quotedContextText=``;let e=document.getElementById(`selectionIndicator`),t=document.getElementById(`userInput`);if(e&&(e.classList.remove(`show`),a.debug(`[SidePanel] hiddenselected contentprompt`)),typeof window.hideFloatingMenu==`function`&&window.hideFloatingMenu(),t&&t.value.startsWith(`[选中内容]`)){let e=t.value.split(`
|
|
1754
1754
|
`),n=e.findIndex(e=>e.startsWith(`[用户问题]`));n===-1?t.value=``:t.value=e.slice(n+1).join(`
|
|
1755
|
-
`).trim()}}var CC,wC=new Promise(e=>{CC=e});function TC(){N.activeSessionId&&document.dispatchEvent(new CustomEvent(`session-hydrated`,{detail:{sessionId:N.activeSessionId,workdir:N.sessionWorkdir||null}}))}async function EC(){try{await DC()}finally{CC(),document.dispatchEvent(new CustomEvent(`chat-history-rendered`,{detail:{sessionId:N.activeSessionId||null}}))}}async function DC(){let e=await Fi();if(e.activeSessionId&&e.list.length>0){N.activeSessionId=e.activeSessionId,N.sessions=e.list;let t=e.list.find(t=>t.id===e.activeSessionId);if(t){if(N.messageHistory=t.messageHistory||[],N.activeCompaction=t.contextCompaction||null,Li(t),TC(),N.currentModel=t.model||N.currentModel,N.useTools=t.useTools===void 0?N.useTools:t.useTools,N.temperature=t.temperature===void 0?N.temperature:t.temperature,N.topP=t.topP===void 0?N.topP:t.topP,N.activeAgentId=t.agentId||null,N.activeAgentId&&N.activeAgentId!=="default"){try{let{getAgent:e}=await M(async()=>{let{getAgent:e}=await import(`./agent-store-
|
|
1755
|
+
`).trim()}}var CC,wC=new Promise(e=>{CC=e});function TC(){N.activeSessionId&&document.dispatchEvent(new CustomEvent(`session-hydrated`,{detail:{sessionId:N.activeSessionId,workdir:N.sessionWorkdir||null}}))}async function EC(){try{await DC()}finally{CC(),document.dispatchEvent(new CustomEvent(`chat-history-rendered`,{detail:{sessionId:N.activeSessionId||null}}))}}async function DC(){let e=await Fi();if(e.activeSessionId&&e.list.length>0){N.activeSessionId=e.activeSessionId,N.sessions=e.list;let t=e.list.find(t=>t.id===e.activeSessionId);if(t){if(N.messageHistory=t.messageHistory||[],N.activeCompaction=t.contextCompaction||null,Li(t),TC(),N.currentModel=t.model||N.currentModel,N.useTools=t.useTools===void 0?N.useTools:t.useTools,N.temperature=t.temperature===void 0?N.temperature:t.temperature,N.topP=t.topP===void 0?N.topP:t.topP,N.activeAgentId=t.agentId||null,N.activeAgentId&&N.activeAgentId!=="default"){try{let{getAgent:e}=await M(async()=>{let{getAgent:e}=await import(`./agent-store-CXWql6bl.js`).then(e=>e.t);return{getAgent:e}},__vite__mapDeps([0,1,2,3,4])),t=await e(N.activeAgentId);t&&(N.activeAgentMcpExcludedServerIds=t.mcpExcludedServerIds??null,t.model&&(N.currentModel=t.model),t.temperature!==null&&t.temperature!==void 0&&(N.temperature=t.temperature,N.topP=t.topP!==null&&t.topP!==void 0?t.topP:1),document.dispatchEvent(new CustomEvent(`agent-model-changed`)))}catch{}N.activeAgentMcpExcludedServerIds=null}else{N.activeAgentMcpExcludedServerIds=null;try{let e=await chrome.storage.local.get([`modelName`,`temperature`,`topP`]);e.modelName&&(N.currentModel=e.modelName),e.temperature!==void 0&&(N.temperature=e.temperature),e.topP!==void 0&&(N.topP=e.topP)}catch{}document.dispatchEvent(new CustomEvent(`agent-model-changed`))}let e=`agentMcpClosedServers_${N.activeAgentId||`default`}`;N.mcpClosedServers=(await chrome.storage.local.get([e]))[e]||[]}let n=document.getElementById(`chatContainer`);n&&n.querySelectorAll(`.message, .user-context-bubble`).forEach(e=>e.remove()),N.messageHistory.forEach(e=>{let t=e.wasRevised;if(!t&&e.executionLog)try{t=(typeof e.executionLog==`string`?JSON.parse(e.executionLog):e.executionLog).some(e=>e.nodeType===`reflection`&&e.reflectionType===`post`&&e.action?.decision===`revised`)}catch{}if(e.role===`user`&&e.contextBubbles&&Array.isArray(e.contextBubbles)&&e.contextBubbles.forEach(e=>{let t=``;switch(e.type){case`skill`:t=r(`contextBubble.bubbleSkill`,{name:e.name,desc:e.description?`:`+e.description:``});break;case`mcp`:t=r(`contextBubble.bubbleMcp`,{name:e.serverName});break;case`page`:t=r(`contextBubble.bubblePage`,{title:e.title,url:e.url});break;case`file`:t=`${e.name} (${fm(e.size||0)})`;break;case`knowledge`:{let t=Array.isArray(e.refs)?e.refs:[];t.length>0&&FC(t,e.failed===!0);break}}t&&e.type!==`file`&&ew(e.type,t,!1)}),e.htmlContent)pw(e.htmlContent,e.messageId,e.resumable);else{let n=(e.contextBubbles||[]).filter(e=>e.type===`file`).map(e=>({name:e.name,size:e.size||0,type:e.fileType||``}));iw(e.role,e.content,!1,e.executionLog||[],e.reflectionScore,t,null,e.messageId,n,e.resumable,e.timestamp??null)}}),sw(),lw(),qt();let i=document.querySelector(`.welcome-message`);i&&N.messageHistory.length>0&&i.remove(),$t(),sn(),NE(),e.activeSessionId===N.activeSessionId?es(e):es(),await Qx();let a=`scrollPosition_`+(N.activeSessionId||`default`);chrome.storage.local.get([a],e=>{e[a]!==void 0&&setTimeout(()=>{let t=document.getElementById(`chatContainer`);t.scrollTop=e[a]},100)})}else{await zi();let e=await Fi();e.activeSessionId&&(N.activeSessionId=e.activeSessionId,N.sessions=e.list,Li(e.list.find(t=>t.id===e.activeSessionId)),TC()),es(e)}}function OC(){try{Ii().catch(e=>{a.error(`[SidePanel] save currentsession failed:`,e)})}catch(e){a.error(`[SidePanel] save conversationhistory exception:`,e)}}async function kC(){try{await Ii()}catch(e){a.error(`[SidePanel] save conversationhistory exception:`,e)}}function AC(){N.messageHistory&&N.messageHistory.length>0&&Wi().then(()=>{N.messageHistory=[],N.activeCompaction=null;let e=document.getElementById(`chatContainer`);if(e){e.innerHTML=``;let t=document.createElement(`div`);t.className=`welcome-message`,t.innerHTML=`
|
|
1756
1756
|
<div class="icon-wrapper">
|
|
1757
1757
|
<div class="icon">💬</div>
|
|
1758
1758
|
</div>
|
|
@@ -1766,9 +1766,9 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
|
|
|
1766
1766
|
${HC}${VC}${`<span class="subtask-badge">${e.index+1}/${t}</span>`}<span class="subtask-name" title="${I(n)}">${P(e.name||``)}</span><span class="subtask-status-pending">${r(`chatMsg.subtaskPending`)}</span>
|
|
1767
1767
|
</div>
|
|
1768
1768
|
<div class="subtask-detail-body">${i}</div>
|
|
1769
|
-
`}function GC(e){!e||e._clickDelegated||(e._clickDelegated=!0,e.addEventListener(`click`,t=>{let n=t.target.closest(`[data-node-filter]`);if(n){t.stopPropagation(),e._nodeFilter=zC(e._nodeFilter||null,n.dataset.nodeFilter),e._nodeFilter&&e.classList.add(`subtask-expanded`),e._renderNodes?.();return}t.target.closest(`.subtask-header`)&&e.classList.toggle(`subtask-expanded`)}))}function KC(e,t){let n=Number(t.dataset.subtaskIndex),r=Array.from(e.querySelectorAll(`.subtask-progress[data-subtask-index]`)).find(e=>Number(e.dataset.subtaskIndex)>n);r?e.insertBefore(t,r):e.appendChild(t)}function qC(e){let t=e||r(`chatResume.unknownError`),n=t.toLowerCase();return n.includes(`network`)||n.includes(`failed to fetch`)||n.includes(`load failed`)?r(`chat.networkError`):n.includes(`timeout`)||t.includes(`超时`)?r(`chat.timeoutError`,{message:t}):r(`chat.requestFailed`,{message:t})}var JC=Object.freeze({quotedContextText:``,selectedContextText:``,selectedSkills:[],selectedMcpServices:[],knowledgeRefs:[],selectedPage:null,attachedFiles:[],attachedImages:[]});function YC(){return{quotedContextText:N.quotedContextText||``,selectedContextText:N.selectedContextText||``,selectedSkills:(N.selectedSkills||[]).slice(),selectedMcpServices:(N.selectedMcpServices||[]).slice(),knowledgeRefs:(N.knowledgeRefs||[]).slice(),selectedPage:N.selectedPage||null,attachedFiles:(N.attachedFiles||[]).slice(),attachedImages:(N.attachedImages||[]).slice()}}async function XC(e={}){await wC;let t=document.getElementById(`userInput`),n=document.getElementById(`chatContainer`),i=e.sessionId||N.activeSessionId,o=i===N.activeSessionId,s=o?null:e.sessionState||{},c=o?N.messageHistory:s.messageHistory||[],l=e.context||(o?YC():JC),d=!e.context,p=o?N.currentModel:s.model||N.currentModel,m=o||s.useTools===void 0?N.useTools:s.useTools,h=o?N.enabledTools:s.enabledTools||N.enabledTools,_=o?N.activeCompaction:s.contextCompaction||null,v=String(e.text==null?t?.value||``:e.text).trim();if(!v)return{ok:!1,reason:`empty`};if(e.fromQueue||Uu(),N.generatingSessionIds.has(i))return{ok:!1,reason:`generating`};if(Yx(i),chrome.runtime.sendMessage({type:`DELETE_CHECKPOINT`,sessionId:i}),o&&await Xc({state:N,getRatio:()=>vE().usage?.ratio??0,compact:DE}),o){let e=n?.querySelector(`.welcome-message`);e&&e.remove()}let y=v,x=l.selectedContextText&&l.selectedContextText.trim(),S=l.quotedContextText&&l.quotedContextText.trim(),C=[];if(S){let e=l.quotedContextText.trim(),{compressed:t,wasCompressed:n}=k(e);y=`[引用内容${n?`摘要`:``}]\n${t}\n\n[用户问题]\n${v}`,o&&ew(`quoted`,e,!1),C.push({type:`quoted`,text:e}),o&&d&&N.quotedContextText===l.quotedContextText&&(N.quotedContextText=``)}else if(x){let e=l.selectedContextText.trim(),{compressed:t,wasCompressed:n}=k(e);y=`[选中内容${n?`摘要`:``}]\n${t}\n\n[用户问题]\n${v}`,o&&ew(`selected`,e,!1),C.push({type:`selected`,text:e}),o&&d&&N.selectedContextText===l.selectedContextText&&(N.selectedContextText=``)}let w=await lT(l.selectedSkills);if(w){y=w+y;for(let e of l.selectedSkills||[])o&&ew(`skill`,r(`contextBubble.bubbleSkill`,{name:e.name,desc:e.description?`:`+e.description:``}),!1),C.push({type:`skill`,name:e.name,description:e.description||``});if(o){let e=new Set(l.selectedSkills||[]),t=N.selectedSkills.filter(t=>!e.has(t));t.length!==N.selectedSkills.length&&(N.selectedSkills=t,N.selectedSkillIndex=-1,rT(),iT())}}let T=null,E=gT(l.selectedMcpServices);if(E){let e=(l.selectedMcpServices||[]).map(e=>e.serverId).filter(Boolean);T=e.length>0?e:null,y=E+y;for(let e of l.selectedMcpServices||[])o&&ew(`mcp`,r(`contextBubble.bubbleMcp`,{name:e.serverName}),!1),C.push({type:`mcp`,serverName:e.serverName,serverId:e.serverId||``});if(o){let e=new Set(l.selectedMcpServices||[]),t=N.selectedMcpServices.filter(t=>!e.has(t));t.length!==N.selectedMcpServices.length&&(N.selectedMcpServices=t,N.selectedMcpServiceIndex=-1,_T(),vT())}}if((l.knowledgeRefs||[]).length>0){let e=l.knowledgeRefs.slice();o&&(N.isGenerating=!0);let t=o?ew(`knowledge`,r(`contextBubble.bubbleKnowledgeSearching`),!0):null,n=null;try{n=await PC(v,e)}catch(e){a.warn(`[SidePanel] knowledge search failed:`,e)}if(t&&t.parentNode&&t.remove(),n&&(y=n.text+y,o&&FC(n.refs,n.failed===!0),C.push({type:`knowledge`,refs:n.refs,failed:n.failed||void 0})),o){let t=new Set(e),n=N.knowledgeRefs.filter(e=>!t.has(e));n.length!==N.knowledgeRefs.length&&(N.knowledgeRefs=n,Nb(),Lb())}}if(l.selectedPage){let e=l.selectedPage;y=`[网页上下文]\n标题: ${e.title}\nURL: ${e.url}\ntabId: ${e.id}\n`+y,o&&ew(`page`,r(`contextBubble.bubblePage`,{title:e.title,url:e.url}),!1),C.push({type:`page`,title:e.title,url:e.url}),o&&N.selectedPage===l.selectedPage&&Zb()}let D=!1,O=(l.attachedFiles||[]).slice();if(O.length>0){let e=Am(O);e&&(y+=e),O.forEach(e=>{e.status===`done`&&C.push({type:`file`,name:e.name,size:e.size,fileType:e.type})})}let A=(l.attachedImages||[]).slice(),ee=null;if(O.length>0||A.length>0)try{ee=await Ie(i,O,A)}catch(e){a.warn(`[Chat] save doc image snapshot failed:`,e.message)}let te=ve(ee?.chatStart,ee?.chatCount);te&&(y+=te);let ne=`msg_`+Date.now().toString(36)+`_`+Math.random().toString(36).substring(2,8),re=new Date().toISOString(),ie={role:`user`,content:Vp(y,l.attachedImages),messageId:ne,timestamp:re,contextBubbles:C};o?(iw(`user`,Vp(v,l.attachedImages),!0,[],null,!1,y,ne,O,!1,re),N.messageHistory.push(ie),OC(),qn(v),N.inputHistoryIndex=-1):c.push(ie),D=!0,o&&!e.fromQueue&&(t.value=``,t.style.height=`auto`),o&&(x||S)&&(!N.quotedContextText&&!N.selectedContextText?SC():xC()),N.generatingSessionIds.add(i),document.dispatchEvent(new CustomEvent(`generating-state-changed`));let ae=o?uw():null,oe=N.enableImageInput&&(l.attachedImages||[]).length>0&&N.imageModelName||p;if(o&&(l.attachedImages||[]).length>0){let e=new Set(l.attachedImages),t=N.attachedImages.filter(t=>!e.has(t));t.length!==N.attachedImages.length&&(N.attachedImages=t,Bp())}if(o&&O.length>0){let e=new Set(O),t=N.attachedFiles.filter(t=>!e.has(t));if(t.length!==N.attachedFiles.length){for(let t of N.attachedFiles)e.has(t)&&t.dataUrl&&URL.revokeObjectURL(t.dataUrl);N.attachedFiles=t,km()}}let se=e=>{if(!o){c.push(e);return}if(N.activeSessionId!==i){Zi(i,e);return}N.messageHistory.push(e)};try{await
|
|
1769
|
+
`}function GC(e){!e||e._clickDelegated||(e._clickDelegated=!0,e.addEventListener(`click`,t=>{let n=t.target.closest(`[data-node-filter]`);if(n){t.stopPropagation(),e._nodeFilter=zC(e._nodeFilter||null,n.dataset.nodeFilter),e._nodeFilter&&e.classList.add(`subtask-expanded`),e._renderNodes?.();return}t.target.closest(`.subtask-header`)&&e.classList.toggle(`subtask-expanded`)}))}function KC(e,t){let n=Number(t.dataset.subtaskIndex),r=Array.from(e.querySelectorAll(`.subtask-progress[data-subtask-index]`)).find(e=>Number(e.dataset.subtaskIndex)>n);r?e.insertBefore(t,r):e.appendChild(t)}function qC(e){let t=e||r(`chatResume.unknownError`),n=t.toLowerCase();return n.includes(`network`)||n.includes(`failed to fetch`)||n.includes(`load failed`)?r(`chat.networkError`):n.includes(`timeout`)||t.includes(`超时`)?r(`chat.timeoutError`,{message:t}):r(`chat.requestFailed`,{message:t})}var JC=Object.freeze({quotedContextText:``,selectedContextText:``,selectedSkills:[],selectedMcpServices:[],knowledgeRefs:[],selectedPage:null,attachedFiles:[],attachedImages:[]});function YC(){return{quotedContextText:N.quotedContextText||``,selectedContextText:N.selectedContextText||``,selectedSkills:(N.selectedSkills||[]).slice(),selectedMcpServices:(N.selectedMcpServices||[]).slice(),knowledgeRefs:(N.knowledgeRefs||[]).slice(),selectedPage:N.selectedPage||null,attachedFiles:(N.attachedFiles||[]).slice(),attachedImages:(N.attachedImages||[]).slice()}}async function XC(e={}){await wC;let t=document.getElementById(`userInput`),n=document.getElementById(`chatContainer`),i=e.sessionId||N.activeSessionId,o=i===N.activeSessionId,s=o?null:e.sessionState||{},c=o?N.messageHistory:s.messageHistory||[],l=e.context||(o?YC():JC),d=!e.context,p=o?N.currentModel:s.model||N.currentModel,m=o||s.useTools===void 0?N.useTools:s.useTools,h=o?N.enabledTools:s.enabledTools||N.enabledTools,_=o?N.activeCompaction:s.contextCompaction||null,v=String(e.text==null?t?.value||``:e.text).trim();if(!v)return{ok:!1,reason:`empty`};if(e.fromQueue||Uu(),N.generatingSessionIds.has(i))return{ok:!1,reason:`generating`};if(Yx(i),chrome.runtime.sendMessage({type:`DELETE_CHECKPOINT`,sessionId:i}),o&&await Xc({state:N,getRatio:()=>vE().usage?.ratio??0,compact:DE}),o){let e=n?.querySelector(`.welcome-message`);e&&e.remove()}let y=v,x=l.selectedContextText&&l.selectedContextText.trim(),S=l.quotedContextText&&l.quotedContextText.trim(),C=[];if(S){let e=l.quotedContextText.trim(),{compressed:t,wasCompressed:n}=k(e);y=`[引用内容${n?`摘要`:``}]\n${t}\n\n[用户问题]\n${v}`,o&&ew(`quoted`,e,!1),C.push({type:`quoted`,text:e}),o&&d&&N.quotedContextText===l.quotedContextText&&(N.quotedContextText=``)}else if(x){let e=l.selectedContextText.trim(),{compressed:t,wasCompressed:n}=k(e);y=`[选中内容${n?`摘要`:``}]\n${t}\n\n[用户问题]\n${v}`,o&&ew(`selected`,e,!1),C.push({type:`selected`,text:e}),o&&d&&N.selectedContextText===l.selectedContextText&&(N.selectedContextText=``)}let w=await lT(l.selectedSkills);if(w){y=w+y;for(let e of l.selectedSkills||[])o&&ew(`skill`,r(`contextBubble.bubbleSkill`,{name:e.name,desc:e.description?`:`+e.description:``}),!1),C.push({type:`skill`,name:e.name,description:e.description||``});if(o){let e=new Set(l.selectedSkills||[]),t=N.selectedSkills.filter(t=>!e.has(t));t.length!==N.selectedSkills.length&&(N.selectedSkills=t,N.selectedSkillIndex=-1,rT(),iT())}}let T=null,E=gT(l.selectedMcpServices);if(E){let e=(l.selectedMcpServices||[]).map(e=>e.serverId).filter(Boolean);T=e.length>0?e:null,y=E+y;for(let e of l.selectedMcpServices||[])o&&ew(`mcp`,r(`contextBubble.bubbleMcp`,{name:e.serverName}),!1),C.push({type:`mcp`,serverName:e.serverName,serverId:e.serverId||``});if(o){let e=new Set(l.selectedMcpServices||[]),t=N.selectedMcpServices.filter(t=>!e.has(t));t.length!==N.selectedMcpServices.length&&(N.selectedMcpServices=t,N.selectedMcpServiceIndex=-1,_T(),vT())}}if((l.knowledgeRefs||[]).length>0){let e=l.knowledgeRefs.slice();o&&(N.isGenerating=!0);let t=o?ew(`knowledge`,r(`contextBubble.bubbleKnowledgeSearching`),!0):null,n=null;try{n=await PC(v,e)}catch(e){a.warn(`[SidePanel] knowledge search failed:`,e)}if(t&&t.parentNode&&t.remove(),n&&(y=n.text+y,o&&FC(n.refs,n.failed===!0),C.push({type:`knowledge`,refs:n.refs,failed:n.failed||void 0})),o){let t=new Set(e),n=N.knowledgeRefs.filter(e=>!t.has(e));n.length!==N.knowledgeRefs.length&&(N.knowledgeRefs=n,Nb(),Lb())}}if(l.selectedPage){let e=l.selectedPage;y=`[网页上下文]\n标题: ${e.title}\nURL: ${e.url}\ntabId: ${e.id}\n`+y,o&&ew(`page`,r(`contextBubble.bubblePage`,{title:e.title,url:e.url}),!1),C.push({type:`page`,title:e.title,url:e.url}),o&&N.selectedPage===l.selectedPage&&Zb()}let D=!1,O=(l.attachedFiles||[]).slice();if(O.length>0){let e=Am(O);e&&(y+=e),O.forEach(e=>{e.status===`done`&&C.push({type:`file`,name:e.name,size:e.size,fileType:e.type})})}let A=(l.attachedImages||[]).slice(),ee=null;if(O.length>0||A.length>0)try{ee=await Ie(i,O,A)}catch(e){a.warn(`[Chat] save doc image snapshot failed:`,e.message)}let te=ve(ee?.chatStart,ee?.chatCount);te&&(y+=te);let ne=`msg_`+Date.now().toString(36)+`_`+Math.random().toString(36).substring(2,8),re=new Date().toISOString(),ie={role:`user`,content:Vp(y,l.attachedImages),messageId:ne,timestamp:re,contextBubbles:C};o?(iw(`user`,Vp(v,l.attachedImages),!0,[],null,!1,y,ne,O,!1,re),N.messageHistory.push(ie),OC(),qn(v),N.inputHistoryIndex=-1):c.push(ie),D=!0,o&&!e.fromQueue&&(t.value=``,t.style.height=`auto`),o&&(x||S)&&(!N.quotedContextText&&!N.selectedContextText?SC():xC()),N.generatingSessionIds.add(i),document.dispatchEvent(new CustomEvent(`generating-state-changed`));let ae=o?uw():null,oe=N.enableImageInput&&(l.attachedImages||[]).length>0&&N.imageModelName||p;if(o&&(l.attachedImages||[]).length>0){let e=new Set(l.attachedImages),t=N.attachedImages.filter(t=>!e.has(t));t.length!==N.attachedImages.length&&(N.attachedImages=t,Bp())}if(o&&O.length>0){let e=new Set(O),t=N.attachedFiles.filter(t=>!e.has(t));if(t.length!==N.attachedFiles.length){for(let t of N.attachedFiles)e.has(t)&&t.dataUrl&&URL.revokeObjectURL(t.dataUrl);N.attachedFiles=t,km()}}let se=e=>{if(!o){c.push(e);return}if(N.activeSessionId!==i){Zi(i,e);return}N.messageHistory.push(e)};try{await zt();let e=await lE(o?N.activeAgentId:s.agentId||null),t=uE(e),n=e?.skillIds??null;o&&(N.activeAgentToolIds=t,N.activeAgentSkillIds=n,N.activeAgentMcpExcludedServerIds=e?e.mcpExcludedServerIds??null:null);let d={agentId:o?N.activeAgentId:s.agentId||null,agentToolIds:t,agentSkillIds:n,agentMcpExcludedServerIds:e?e.mcpExcludedServerIds??null:null};a.debug(`[SidePanel] sendmessagedebuginfo:`),a.debug(` - agent:`,e?e.name:`default assistant`),a.debug(` - agentToolIds:`,t),a.debug(` - isolateChat:`,N.isolateChat),a.debug(` - chatConfig:`,N.chatConfig),a.debug(` - messageHistory.length:`,c.length);let p=[{role:`system`,content:await Kt(e,{sessionId:i})}];if(N.isolateChat){let e=f(p[0]?.content||``),t=g(oe,0,N.customModelMap)-e-4096-2e3;Math.floor(t*.7);let n=c[c.length-1],r=Hn(c.slice(0,-1),{isolateChat:!0,maxMemoryMessages:N.chatConfig.maxMemoryMessages,compaction:_,currentMessage:n});Wn(p,r,_,a),r.historySummaryText&&(p[0]={...p[0],content:p[0].content+`
|
|
1770
1770
|
|
|
1771
|
-
`+r.historySummaryText}),a.debug(`[SidePanel] history selection: keep ${r.keptHistory.length}/${c.length-1}, trimmed ${r.trimmedCount}, compactionApplied: ${r.compactionApplied}`),p=[...p,...r.messages];for(let e=0;e<p.length-1;e++)p[e]={...p[e],content:Hp(p[e].content)}}else{let e=Vp(y,l.attachedImages);p.push({role:`user`,content:e})}let x=await
|
|
1771
|
+
`+r.historySummaryText}),a.debug(`[SidePanel] history selection: keep ${r.keptHistory.length}/${c.length-1}, trimmed ${r.trimmedCount}, compactionApplied: ${r.compactionApplied}`),p=[...p,...r.messages];for(let e=0;e<p.length-1;e++)p[e]={...p[e],content:Hp(p[e].content)}}else{let e=Vp(y,l.attachedImages);p.push({role:`user`,content:e})}let x=await Pt(o?null:{temperature:s.temperature,topP:s.topP});if(o&&(x._loadingId=ae),o)try{let e=await bf({sessionId:i,text:v,attachments:xf(l)});e&&(x.goal=e)}catch(e){a.warn(`[SidePanel] prepare goal for send failed:`,e?.message)}let S=b(p),C=g(oe,0,N.customModelMap),w=u(S,C);if(a.debug(`[SidePanel] send context: ${S} tokens (message: ${p.length} ), pressure: ${w.level}(${Math.round(w.ratio*100)}%)`),w.level===`critical`){a.warn(`[SidePanel] context pressure too high,maindynamictrimming...`);let e=f(p[0]?.content||``),t=await vw(T),n=(h.length+t)*200,r=C-e-n-4096-2e3,i=j(p,Math.max(r,2e3),{generateSummary:!1});p=i.messages,a.warn(`[SidePanel] proactively trimmed: ${S} → ${b(p)} tokens (${i.trimmedCount} )`)}let E,D,O,k=!1,A=!1,ee=null,te=!0,ne=null,re=!1;try{let e=await yw(p,oe,m,x,{forcedMcpServerIds:T,sessionId:i,agent:d});E=e.content,D=e.executionLog||[],O=e.reflectionScore,k=e.wasRevised||!1,A=e.wasStreamed||!1,ee=e.streamingHtml||null,te=e.streamingConnected===void 0?!0:e.streamingConnected,ne=e.streamingMsgId||null,re=e.budgetEnded===!0}catch(e){if(!o||N.activeSessionId!==i){let t=!!e.checkpoint||e.swRestarted||e.message===r(`chatMsg.errTaskStopped`);return se({role:`assistant`,content:e.message===r(`chatMsg.errTaskStopped`)?r(`chatResume.taskCancelled`):e.swRestarted?r(`chat.taskInterruptedSwRestart`):qC(e.message),executionLog:e.executionLog||[],resumable:t}),document.dispatchEvent(new CustomEvent(`session-cache-invalidate`,{detail:{sessionId:i}})),ae&&dw(ae),N.substituteLoadingIds.delete(i),{ok:!1,delivered:!0,reason:`inactive`}}if(e.message===r(`chatMsg.errTaskStopped`)){ae&&dw(ae),N.substituteLoadingIds.delete(i);let{messageId:t}=iw(`assistant`,r(`chatResume.taskCancelled`),!1,e.executionLog||[],null,!1,null,null,[],!0);return N.messageHistory.push({role:`assistant`,content:r(`chatResume.taskCancelled`),executionLog:e.executionLog||[],messageId:t,resumable:!0}),OC(),{ok:!1,delivered:!0,reason:`cancelled`}}if(e.swRestarted){ae&&dw(ae),N.substituteLoadingIds.delete(i);let t=!!e.checkpoint,{messageId:n}=iw(`assistant`,r(`chat.taskInterruptedSwRestart`),!1,e.executionLog||[],null,!1,null,null,[],t);return N.messageHistory.push({role:`assistant`,content:r(`chat.taskInterruptedSwRestart`),executionLog:e.executionLog||[],messageId:n,resumable:t}),OC(),Ol(i,r(`chat.taskInterruptedSwRestart`),v),{ok:!1,delivered:!0,reason:`sw_restarted`}}ae&&dw(ae),N.substituteLoadingIds.delete(i),E=qC(e.message),D=e.executionLog||[];let{messageId:t}=iw(`assistant`,E,!0,D,O,!1,null,null,[],!0);return N.messageHistory.push({role:`assistant`,content:E,executionLog:D,reflectionScore:O,messageId:t,resumable:!0}),Ol(i,E,v),{ok:!1,delivered:!0,reason:`error`}}if(!o||N.activeSessionId!==i){let e={role:`assistant`,content:E,executionLog:D,reflectionScore:O,wasRevised:k,resumable:re?`budget`:!1,messageId:ne||`msg_`+Date.now().toString(36)+`_`+Math.random().toString(36).substring(2,8)};return A&&ee&&(e.htmlContent=ee),se(e),document.dispatchEvent(new CustomEvent(`session-cache-invalidate`,{detail:{sessionId:i}})),ae&&dw(ae),N.substituteLoadingIds.delete(i),{ok:!0,delivered:!0}}let ie=null;if(!A||!ee)if(ae&&dw(ae),N.substituteLoadingIds.has(i)&&(dw(N.substituteLoadingIds.get(i)),N.substituteLoadingIds.delete(i)),A)N.substituteLoadingIds.has(i)&&(dw(N.substituteLoadingIds.get(i)),N.substituteLoadingIds.delete(i)),ie=ne;else{let{element:e,messageId:t}=iw(`assistant`,E,!0,D,O,k,null,null,[],re?`budget`:!1);ie=t,await cn(e),DS()}else ie=ne;re&&Zx(ie?document.querySelector(`[data-message-id="${ie}"]`):null,`budget`);let ce={role:`assistant`,content:E,executionLog:D,reflectionScore:O,wasRevised:k,resumable:re?`budget`:!1,messageId:ie};if(A&&ee&&(ce.htmlContent=ee,!te&&!document.querySelector(`[data-message-id="${ie}"]`))){pw(ee,ie,re?`budget`:!1),sw(),lw();let e=document.getElementById(`chatContainer`);e&&(e.scrollTop=e.scrollHeight)}return N.messageHistory.push(ce),Dl(i,v),{ok:!0,delivered:!0}}catch(e){return a.error(`[SidePanel] sendMessage exception:`,e?.message||e),{ok:!1,delivered:D,reason:e?.message||`exception`}}finally{o?OC():(await Ri(i,{messageHistory:c,model:s.model,useTools:s.useTools,enabledTools:s.enabledTools,agentId:s.agentId,temperature:s.temperature,topP:s.topP,activeCompaction:s.contextCompaction,workdir:s.workdir,workdirAgentId:s.workdirAgentId,goalMode:s.goalMode}),document.dispatchEvent(new CustomEvent(`session-cache-invalidate`,{detail:{sessionId:i}}))),jl(i),o&&t.focus()}}function ZC(e,t){let n=document.getElementById(`userInput`);if(!t||N.isGenerating){a.debug(`[SidePanel] triggerSelectionSearch skip:`,{hasText:!!t,isGenerating:N.isGenerating});return}N.selectedContextText=t,N.quotedContextText=``,n.value=r(`chatMsg.searchPrompt`),n.dispatchEvent(new Event(`input`)),XC()}function QC(e){let t=document.getElementById(`userInput`);!t||!e||(t.value=e,t.dispatchEvent(new Event(`input`)),t.focus())}async function $C(e,t=``){await wC;let n=document.getElementById(`userInput`);if(!(!n||!e)){if(t&&(N.selectedContextText=t,N.quotedContextText=``),N.isGenerating){n.value=e,n.dispatchEvent(new Event(`input`)),await md();return}n.value=e,n.dispatchEvent(new Event(`input`)),n.focus(),XC()}}function ew(e,t,n=!0,i=null){let a=document.getElementById(`chatContainer`),o=document.createElement(`div`);o.className=`user-context-bubble`,o.dataset.role=`context`;let s=e===`quoted`?`💬`:e===`skill`?`🧩`:e===`mcp`?`🔌`:e===`page`?`🌐`:e===`file`?`📎`:e===`knowledge`?`📚`:`📌`,c=r(e===`quoted`?`contextBubble.labelQuoted`:e===`skill`?`contextBubble.labelSkill`:e===`mcp`?`contextBubble.labelMcp`:e===`page`?`contextBubble.labelPage`:e===`file`?`contextBubble.labelFile`:e===`knowledge`?`contextBubble.labelKnowledge`:`contextBubble.labelSelection`),l=P(t);if(e===`knowledge`&&Array.isArray(i)&&i.length>0){let e=i.map(e=>{let t=typeof e.score==`number`?e.score.toFixed(3):``,n=t?`<span class="kb-bubble-hit-score">${t}</span>`:``,i=e.truncated?`<span class="kb-bubble-hit-truncated" title="${r(`contextBubble.kbHitTruncatedTitle`)}">${r(`contextBubble.kbHitTruncated`,{total:e.fullLength||0,kept:NC})}</span>`:``;return`<div class="kb-bubble-hit"><div class="kb-bubble-hit-text" title="${r(`contextBubble.kbHitToggle`)}">${n}${P(e.content||``)}</div>${i}</div>`}).join(``),n=i.filter(e=>e.truncated).length,a=n>0?`<span class="kb-bubble-truncated-badge">${r(`contextBubble.kbHitTruncatedBadge`,{count:n})}</span>`:``;l=`<div class="kb-bubble-summary">${P(t)}${a}</div>${e}`}o.innerHTML=`
|
|
1772
1772
|
<div class="context-bubble-inner">
|
|
1773
1773
|
<div class="context-bubble-header" title="${r(`contextBubble.clickToExpand`)}">
|
|
1774
1774
|
<span class="context-icon">${s}</span>
|
|
@@ -1776,7 +1776,7 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
|
|
|
1776
1776
|
</div>
|
|
1777
1777
|
<div class="context-bubble-content">${l}</div>
|
|
1778
1778
|
</div>
|
|
1779
|
-
`;let u=o.querySelector(`.context-bubble-header`),d=o.querySelector(`.context-bubble-content`);return u.addEventListener(`click`,e=>{e.stopPropagation(),d.classList.toggle(`expanded`)}),e===`knowledge`&&o.querySelectorAll(`.kb-bubble-hit-text`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),e.classList.toggle(`expanded`)})}),a.appendChild(o),n&&(a.scrollTop=a.scrollHeight),o}function tw(e){let t=e,n;do n=t,t=t.replace(/^\[(?:已选技能|Selected skill): [^\]]+\]\n[\s\S]*?(?:请根据上述技能说明[\s\S]*?处理以下问题[::]|Please use the relevant tools[\s\S]*?handle the following problem[.:])\s*\n/,``).replace(/^\[(?:已选技能|Selected skill): [^\]]+\]\n(?:请|Please)[^\n]*(?:处理以下问题|handle the following problem)[^。\n]*。?\s*\n/,``);while(t!==n);return t}function nw(e){let t=e,n;do n=t,t=t.replace(/^\[(?:已选MCP服务|Selected MCP service):\s*[^\]]+\]\n(?:请使用「[^」]+」MCP服务来处理以下问题:|Please use the "[^"]+" MCP service to handle the following problem:)\s*\n/,``);while(t!==n);return t}var rw=e=>!!e&&e.dataset.resumable===`budget`;function iw(e,t,n=!0,i=[],o=null,s=!1,c=null,l=null,u=[],d=!1,f=void 0){let p=document.getElementById(`chatContainer`),m=document.createElement(`div`);m.className=`message ${e}`;let h=f===void 0?new Date().toISOString():f||null;h&&(m.dataset.timestamp=h);let g=l||`msg_`+Date.now().toString(36)+`_`+Math.random().toString(36).substring(2,8);m.dataset.messageId=g;let _=Array.isArray(t)?t.filter(e=>e.type===`text`).map(e=>e.text).join(``):t,v=e===`user`?de(_):_,y=Array.isArray(t)&&t.some(e=>e.type===`image_url`);m.dataset.rawContent=Array.isArray(t)?JSON.stringify(t):rn(t),m.dataset.textContent_=rn(e===`user`?de(c||v):c||v);let b=v;if(m.dataset.executionLog=JSON.stringify(i),s&&(m.dataset.wasRevised=`true`),e===`assistant`){m.innerHTML=qt(t);let e=document.createElement(`div`);e.className=`message-footer`;let n=document.createElement(`button`);n.className=`copy-btn`,n.title=r(`chatStream.copyMarkdown`),n.innerHTML=[`<svg viewBox="0 0 16 16" fill="currentColor">`,`<path d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 0 1 0 1.5h-1.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-1.5a.75.75 0 0 1 1.5 0v1.5A1.75 1.75 0 0 1 9.25 16h-7.5A1.75 1.75 0 0 1 0 14.25zM5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0 1 14.25 11h-7.5A1.75 1.75 0 0 1 5 9.25zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25z"/>`,`</svg>`,`<span>${r(`common.copy`)}</span>`].join(``),n.addEventListener(`click`,e=>{e.stopPropagation(),Lx(m,n,e)}),e.appendChild(n);let c=document.createElement(`button`);c.className=`quote-btn`,c.title=r(`chat.quoteTitle`),c.innerHTML=[`<svg t="1781246498458" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="9645" width="14" height="14"><path d="M156.09136 606.57001a457.596822 457.596822 0 0 1 221.680239-392.516385 50.844091 50.844091 0 1 1 50.844091 86.943396 355.90864 355.90864 0 0 0-138.804369 152.532274h16.77855a152.532274 152.532274 0 1 1-152.532274 152.532274z m406.752731 0a457.596822 457.596822 0 0 1 221.680239-392.007944 50.844091 50.844091 0 1 1 50.844091 86.943396 355.90864 355.90864 0 0 0-138.804369 152.532274h16.77855a152.532274 152.532274 0 1 1-152.532274 152.532274z" fill="#8a8a8a" p-id="9646"></path></svg>`,`<span>${r(`chat.quote`)}</span>`].join(``),c.addEventListener(`click`,e=>{e.stopPropagation(),Gx(m)}),e.appendChild(c),e.appendChild(_x());let l=document.createElement(`div`);l.className=`export-menu-container`;let u=document.createElement(`button`);u.className=`export-trigger-btn`,u.innerHTML=`<svg t="1781245244396" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5115" width="14" height="14"><path d="M496.213333 739.84c2.133333 2.133333 4.693333 3.84 7.68 5.12 0.853333 0.426667 2.133333 0.426667 2.986667 0.853333 1.706667 0.426667 2.986667 0.853333 4.693333 0.853334 5.546667 0 11.093333-2.133333 14.933334-6.4l256-256c8.533333-8.533333 8.533333-21.76 0-30.293334s-21.76-8.533333-30.293334 0L533.333333 674.133333V128c0-11.946667-9.386667-21.333333-21.333333-21.333333s-21.333333 9.386667-21.333333 21.333333v545.706667l-219.306667-219.306667c-8.533333-8.533333-21.76-8.533333-30.293333 0s-8.533333 21.76 0 30.293333l255.146666 255.146667zM768 874.666667H256c-11.946667 0-21.333333 9.386667-21.333333 21.333333s9.386667 21.333333 21.333333 21.333333h512c11.946667 0 21.333333-9.386667 21.333333-21.333333s-9.386667-21.333333-21.333333-21.333333z" fill="#8a8a8a" p-id="5116"></path></svg><span>${r(`chat.export`)}</span><svg class="dropdown-arrow" width="8" height="6" viewBox="0 0 8 6" fill="currentColor"><path d="M0 0l4 6 4-6z"/></svg>`;let f=document.createElement(`div`);f.className=`export-dropdown`,f.innerHTML=[`<button class="export-dropdown-item export-docx-item" type="button">`,`<svg t="1781245550030" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6544" width="32" height="32"><path d="M747.936 901.171H276.819c-72.2 0-130.953-55.224-130.953-123.078V244.721c0-67.854 58.752-123.078 130.953-123.078h383.525c6.597 0 12.937 2.505 17.795 6.954l192.363 178.046c5.317 4.96 8.386 11.914 8.386 19.227v452.223c0 67.854-58.752 123.078-130.952 123.078zM276.819 174.004c-43.31 0-78.592 31.703-78.592 70.717v533.372c0 39.015 35.282 70.718 78.592 70.718h471.117c43.31 0 78.592-31.703 78.592-70.718V337.324l-176.461-163.32H276.819z" fill="#8a8a8a" p-id="6545"></path><path d="M830.567 331.546H669.446c-14.471 0-26.18-11.71-26.18-26.181V156.209c0-14.471 11.709-26.18 26.18-26.18s26.181 11.709 26.181 26.18v122.976h134.94c14.471 0 26.181 11.709 26.181 26.18s-11.711 26.181-26.181 26.181z" fill="#8a8a8a" p-id="6546"></path><path d="M730.214 428.749l-92.04 343.616h-53.179L511.363 498.29l-75.677 274.074h-53.179l-92.04-343.616h49.088l69.542 255.667 69.541-255.667h63.406l69.541 255.667 69.541-255.667h49.088z" fill="#8a8a8a" p-id="6547"></path></svg>`,`<span>${r(`chatMsg.exportWord`)}</span>`,`</button>`,`<button class="export-dropdown-item export-pdf-item" type="button">`,`<svg t="1781245863206" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="8152" width="32" height="32"><path d="M582.4 864H170.666667c-6.4 0-10.666667-4.266667-10.666667-10.666667V170.666667c0-6.4 4.266667-10.666667 10.666667-10.666667h309.333333V320c0 40.533333 34.133333 74.666667 74.666667 74.666667h160v38.4c0 17.066667 14.933333 32 32 32s32-14.933333 32-32V298.666667c0-8.533333-4.266667-17.066667-8.533334-23.466667l-170.666666-170.666667c-6.4-6.4-14.933333-8.533333-23.466667-8.533333H170.666667C130.133333 96 96 130.133333 96 170.666667v682.666666c0 40.533333 34.133333 74.666667 74.666667 74.666667h411.733333c17.066667 0 32-14.933333 32-32s-14.933333-32-32-32z m132.266667-550.4v17.066667H554.666667c-6.4 0-10.666667-4.266667-10.666667-10.666667V160h19.2l151.466667 153.6z" fill="#8a8a8a" p-id="8153"></path><path d="M332.8 533.333333c-12.8 0-19.2 2.133333-25.6 6.4-6.4 4.266667-8.533333 12.8-8.533333 23.466667v206.933333c0 6.4 2.133333 12.8 6.4 19.2 4.266667 4.266667 10.666667 8.533333 21.333333 8.533334s17.066667-4.266667 21.333333-8.533334c4.266667-4.266667 6.4-10.666667 6.4-19.2v-64h32c57.6 0 89.6-29.866667 89.6-87.466666 0-27.733333-8.533333-51.2-23.466666-64-14.933333-14.933333-36.266667-21.333333-66.133334-21.333334h-53.333333z m87.466667 85.333334c0 12.8-2.133333 23.466667-8.533334 27.733333-4.266667 4.266667-14.933333 8.533333-27.733333 8.533333h-32v-70.4H384c12.8 0 21.333333 2.133333 27.733333 8.533334 6.4 4.266667 8.533333 12.8 8.533334 25.6zM667.733333 571.733333c-8.533333-12.8-21.333333-21.333333-34.133333-29.866666-14.933333-4.266667-32-8.533333-51.2-8.533334h-61.866667c-8.533333 0-17.066667 0-23.466666 8.533334-2.133333 4.266667-4.266667 10.666667-4.266667 19.2V768c0 8.533333 2.133333 14.933333 4.266667 19.2 6.4 8.533333 14.933333 8.533333 23.466666 8.533333h64c19.2 0 34.133333-4.266667 49.066667-10.666666 12.8-6.4 25.6-17.066667 34.133333-29.866667 8.533333-12.8 14.933333-25.6 19.2-42.666667 4.266667-14.933333 6.4-32 6.4-49.066666 0-17.066667-2.133333-34.133333-6.4-49.066667-4.266667-14.933333-10.666667-29.866667-19.2-42.666667z m-42.666666 153.6c-8.533333 12.8-21.333333 19.2-38.4 19.2h-38.4v-160H576c21.333333 0 38.4 6.4 46.933333 19.2 10.666667 12.8 14.933333 34.133333 14.933334 59.733334 2.133333 27.733333-4.266667 46.933333-12.8 61.866666zM851.2 533.333333h-106.666667c-8.533333 0-17.066667 2.133333-21.333333 6.4-6.4 4.266667-8.533333 12.8-8.533333 21.333334v209.066666c0 6.4 2.133333 12.8 6.4 17.066667 4.266667 6.4 10.666667 8.533333 21.333333 8.533333 8.533333 0 17.066667-2.133333 21.333333-8.533333 2.133333-4.266667 6.4-8.533333 6.4-19.2v-85.333333h72.533334c12.8 0 23.466667-6.4 25.6-17.066667 2.133333-8.533333 2.133333-14.933333 0-17.066667-2.133333-4.266667-6.4-17.066667-25.6-17.066666H768v-49.066667h81.066667c8.533333 0 14.933333-2.133333 19.2-4.266667 4.266667-2.133333 8.533333-8.533333 8.533333-21.333333 2.133333-12.8-8.533333-23.466667-25.6-23.466667z" fill="#8a8a8a" p-id="8154"></path></svg>`,`<span>${r(`chatMsg.exportPdf`)}</span>`,`</button>`,`<button class="export-dropdown-item export-image-item" type="button">`,`<svg t="1784207887308" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5993" width="32" height="32"><path d="M400.696 268.795c-17.249 0-31.233 13.986-31.233 31.233v30.471c0 17.249 13.986 31.233 31.233 31.233s31.233-13.986 31.233-31.233v-30.471c0-17.249-13.985-31.233-31.233-31.233z" fill="#8a8a8a" p-id="5994"></path><path d="M623.649 361.734c17.249 0 31.234-13.986 31.234-31.233v-30.471c0-17.249-13.986-31.233-31.234-31.233s-31.233 13.986-31.233 31.233v30.471c-0.001 17.248 13.985 31.233 31.233 31.233z" fill="#8a8a8a" p-id="5995"></path><path d="M438.295 388.804c-14.656 9.104-19.155 28.362-10.050 43.013 11.209 18.047 41.976 48.59 86.157 48.59 43.958 0 75.1-30.313 86.574-48.223 9.303-14.529 5.068-33.847-9.455-43.15-14.539-9.298-33.852-5.068-43.15 9.455-0.122 0.199-13.38 19.45-33.969 19.45-20.009 0-32.444-18.128-33.278-19.373-9.166-14.423-28.28-18.805-42.829-9.761z" fill="#8a8a8a" p-id="5996"></path><path d="M824.508503 116.690676 571.592236 116.690676c-17.248849 0-31.233352 13.985526-31.233352 31.233352s13.985526 31.233352 31.233352 31.233352l252.916267 0c40.181141 0 72.878844 32.692586 72.878844 72.878844l0 396.966057-189.334159-165.29465c-12.20088-10.655687-30.517037-10.207479-42.173518 0.9967L468.578048 674.16231 309.521472 517.519714c-11.895935-11.70253-30.903847-12.002358-43.154869-0.645706L126.957507 646.163629l0-394.126382c0-40.186258 32.692586-72.878844 72.878844-72.878844l252.916267 0c17.248849 0 31.233352-13.985526 31.233352-31.233352S470.000444 116.690676 452.751594 116.690676L199.836351 116.690676c-74.632791 0-135.346571 60.71378-135.346571 135.346571l0 520.56405c0 74.632791 60.71378 135.346571 135.346571 135.346571l252.916267 0c17.248849 0 31.233352-13.985526 31.233352-31.233352s-13.985526-31.233352-31.233352-31.233352L199.836351 845.481164c-40.186258 0-72.878844-32.692586-72.878844-72.878844l0-41.23924 160.003134-148.385539 159.428036 157.007917c12.048407 11.865235 31.361265 11.981892 43.546795 0.274246l198.576661-190.68697 208.876238 182.346001 0 40.683585c0 40.186258-32.697703 72.878844-72.878844 72.878844L571.592236 845.481164c-17.248849 0-31.233352 13.985526-31.233352 31.233352s13.985526 31.233352 31.233352 31.233352l252.916267 0c74.627674 0 135.346571-60.71378 135.346571-135.346571L959.855074 252.037247C959.855074 177.404456 899.136178 116.690676 824.508503 116.690676z" fill="#8a8a8a" p-id="5997"></path></svg>`,`<span>${r(`chatMsg.exportImage`)}</span>`,`</button>`,`<button class="export-dropdown-item export-md-item" type="button">`,`<svg t="1784038824502" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1666" width="32" height="32"><path d="M601.216 85.333333a42.666667 42.666667 0 0 1 30.485333 12.821334l209.450667 213.973333a42.666667 42.666667 0 0 1 12.181333 29.866667V853.333333a85.333333 85.333333 0 0 1-85.333333 85.333334H256a85.333333 85.333333 0 0 1-85.333333-85.333334V170.666667a85.333333 85.333333 0 0 1 85.333333-85.333334h345.216z m-35.584 64H256a21.333333 21.333333 0 0 0-21.333333 21.333334v682.666666a21.333333 21.333333 0 0 0 21.333333 21.333334h512a21.333333 21.333333 0 0 0 21.333333-21.333334V395.413333h-191.68a32 32 0 0 1-32-32L565.632 149.333333z m64 38.186667v143.893333h140.821333L629.632 187.52z" fill="#8a8a8a" p-id="1667"></path><path d="M384.341333 800l-3.072-0.106667a32 32 0 0 1-29.162666-34.624l21.973333-256c2.752-32.256 46.165333-40.490667 60.544-11.477333l77.290667 156.010667 78.805333-156.224c14.08-27.925333 55.082667-20.906667 60.074667 8.789333l0.384 3.050667 20.714666 256a32 32 0 0 1-63.786666 5.162666l-11.541334-142.549333-56.341333 111.722667c-11.413333 22.613333-42.88 23.381333-55.744 2.517333l-1.493333-2.730667-54.912-110.826666-12.181334 142.016a32 32 0 0 1-31.552 29.269333z" fill="#8a8a8a" p-id="1668"></path></svg>`,`<span>${r(`chatMsg.exportMarkdown`)}</span>`,`</button>`].join(``);let p=f.querySelector(`.export-docx-item`);p.addEventListener(`click`,async e=>{e.stopPropagation();let{exportAssistantMessageToDocx:t}=await M(async()=>{let{exportAssistantMessageToDocx:e}=await import(`./chat-export-CmaDpmwW.js`);return{exportAssistantMessageToDocx:e}},__vite__mapDeps([10,11,1,12,2,3,4,13,14,0]));t(m,p,f)});let h=f.querySelector(`.export-md-item`);h.addEventListener(`click`,async e=>{e.stopPropagation();let{exportAssistantMessageToMarkdown:t}=await M(async()=>{let{exportAssistantMessageToMarkdown:e}=await import(`./chat-export-CmaDpmwW.js`);return{exportAssistantMessageToMarkdown:e}},__vite__mapDeps([10,11,1,12,2,3,4,13,14,0]));t(m,h,f)});let _=f.querySelector(`.export-pdf-item`);_.addEventListener(`click`,async e=>{e.stopPropagation();let{exportAssistantMessageToPdf:t}=await M(async()=>{let{exportAssistantMessageToPdf:e}=await import(`./chat-export-CmaDpmwW.js`);return{exportAssistantMessageToPdf:e}},__vite__mapDeps([10,11,1,12,2,3,4,13,14,0]));t(m,_,f)});let v=f.querySelector(`.export-image-item`);v.addEventListener(`click`,async e=>{e.stopPropagation();let{exportAssistantMessageToImage:t}=await M(async()=>{let{exportAssistantMessageToImage:e}=await import(`./chat-export-CmaDpmwW.js`);return{exportAssistantMessageToImage:e}},__vite__mapDeps([10,11,1,12,2,3,4,13,14,0]));t(m,v,f)}),u.addEventListener(`click`,e=>{e.stopPropagation(),document.querySelectorAll(`.export-dropdown.show`).forEach(e=>{e!==f&&e.classList.remove(`show`)}),f.classList.toggle(`show`)});let y=null;l.addEventListener(`mouseenter`,()=>{y=setTimeout(()=>{document.querySelectorAll(`.export-dropdown.show`).forEach(e=>{e!==f&&e.classList.remove(`show`)}),f.classList.add(`show`)},300)}),l.addEventListener(`mouseleave`,()=>{y&&=(clearTimeout(y),null),setTimeout(()=>{!l.matches(`:hover`)&&!f.matches(`:hover`)&&f.classList.remove(`show`)},100)}),l.appendChild(u),l.appendChild(f),e.appendChild(l);let b=document.createElement(`div`);b.className=`footer-right-actions`,b.style.marginLeft=`auto`,b.style.display=`flex`,b.style.alignItems=`center`,b.style.gap=`8px`;let x=Lt(i);if(x){let e=document.createElement(`span`);e.className=`token-usage-tag`,e.title=r(`chatStream.tokenUsageTitle`,{total:F(x.totalTokens),prompt:F(x.promptTokens),completion:F(x.completionTokens)}),e.innerHTML=`<span class="token-tag-icon">⬤</span><span class="token-tag-value">${F(x.totalTokens)}</span>`,e.style.cursor=`pointer`,e.addEventListener(`click`,t=>{t.stopPropagation(),Dt(x,e)}),b.appendChild(e)}let S=i&&i.length>0,C=o!=null,w=i?i.filter(e=>e.nodeType===`reflection`&&e.reflectionType===`post`&&e.status===`success`).length:0;sw(),lw(),Kt();let T=i?.find(e=>e.nodeType===`reflection`&&e.reflectionType===`post`),E=Ly(t),D=By(i,t);if(E.length&&(m.dataset.declaredArtifacts=JSON.stringify(E)),ib(D),console.log(`[addMessage] executionLog entries:`,i?.length,`| agent_file entries:`,i?.filter(e=>e.nodeType===`tool_exec`&&e.action?.name===`agent_file`).length,`| artifacts:`,D.length),D.length>0){let e=document.createElement(`button`);e.className=`artifacts-btn`,e.type=`button`,e.title=r(`artifacts.btnTitle`,{count:D.length}),e.innerHTML=`
|
|
1779
|
+
`;let u=o.querySelector(`.context-bubble-header`),d=o.querySelector(`.context-bubble-content`);return u.addEventListener(`click`,e=>{e.stopPropagation(),d.classList.toggle(`expanded`)}),e===`knowledge`&&o.querySelectorAll(`.kb-bubble-hit-text`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),e.classList.toggle(`expanded`)})}),a.appendChild(o),n&&(a.scrollTop=a.scrollHeight),o}function tw(e){let t=e,n;do n=t,t=t.replace(/^\[(?:已选技能|Selected skill): [^\]]+\]\n[\s\S]*?(?:请根据上述技能说明[\s\S]*?处理以下问题[::]|Please use the relevant tools[\s\S]*?handle the following problem[.:])\s*\n/,``).replace(/^\[(?:已选技能|Selected skill): [^\]]+\]\n(?:请|Please)[^\n]*(?:处理以下问题|handle the following problem)[^。\n]*。?\s*\n/,``);while(t!==n);return t}function nw(e){let t=e,n;do n=t,t=t.replace(/^\[(?:已选MCP服务|Selected MCP service):\s*[^\]]+\]\n(?:请使用「[^」]+」MCP服务来处理以下问题:|Please use the "[^"]+" MCP service to handle the following problem:)\s*\n/,``);while(t!==n);return t}var rw=e=>!!e&&e.dataset.resumable===`budget`;function iw(e,t,n=!0,i=[],o=null,s=!1,c=null,l=null,u=[],d=!1,f=void 0){let p=document.getElementById(`chatContainer`),m=document.createElement(`div`);m.className=`message ${e}`;let h=f===void 0?new Date().toISOString():f||null;h&&(m.dataset.timestamp=h);let g=l||`msg_`+Date.now().toString(36)+`_`+Math.random().toString(36).substring(2,8);m.dataset.messageId=g;let _=Array.isArray(t)?t.filter(e=>e.type===`text`).map(e=>e.text).join(``):t,v=e===`user`?de(_):_,y=Array.isArray(t)&&t.some(e=>e.type===`image_url`);m.dataset.rawContent=Array.isArray(t)?JSON.stringify(t):rn(t),m.dataset.textContent_=rn(e===`user`?de(c||v):c||v);let b=v;if(m.dataset.executionLog=JSON.stringify(i),s&&(m.dataset.wasRevised=`true`),e===`assistant`){m.innerHTML=Jt(t);let e=document.createElement(`div`);e.className=`message-footer`;let n=document.createElement(`button`);n.className=`copy-btn`,n.title=r(`chatStream.copyMarkdown`),n.innerHTML=[`<svg viewBox="0 0 16 16" fill="currentColor">`,`<path d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 0 1 0 1.5h-1.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-1.5a.75.75 0 0 1 1.5 0v1.5A1.75 1.75 0 0 1 9.25 16h-7.5A1.75 1.75 0 0 1 0 14.25zM5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0 1 14.25 11h-7.5A1.75 1.75 0 0 1 5 9.25zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25z"/>`,`</svg>`,`<span>${r(`common.copy`)}</span>`].join(``),n.addEventListener(`click`,e=>{e.stopPropagation(),Lx(m,n,e)}),e.appendChild(n);let c=document.createElement(`button`);c.className=`quote-btn`,c.title=r(`chat.quoteTitle`),c.innerHTML=[`<svg t="1781246498458" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="9645" width="14" height="14"><path d="M156.09136 606.57001a457.596822 457.596822 0 0 1 221.680239-392.516385 50.844091 50.844091 0 1 1 50.844091 86.943396 355.90864 355.90864 0 0 0-138.804369 152.532274h16.77855a152.532274 152.532274 0 1 1-152.532274 152.532274z m406.752731 0a457.596822 457.596822 0 0 1 221.680239-392.007944 50.844091 50.844091 0 1 1 50.844091 86.943396 355.90864 355.90864 0 0 0-138.804369 152.532274h16.77855a152.532274 152.532274 0 1 1-152.532274 152.532274z" fill="#8a8a8a" p-id="9646"></path></svg>`,`<span>${r(`chat.quote`)}</span>`].join(``),c.addEventListener(`click`,e=>{e.stopPropagation(),Gx(m)}),e.appendChild(c),e.appendChild(_x());let l=document.createElement(`div`);l.className=`export-menu-container`;let u=document.createElement(`button`);u.className=`export-trigger-btn`,u.innerHTML=`<svg t="1781245244396" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5115" width="14" height="14"><path d="M496.213333 739.84c2.133333 2.133333 4.693333 3.84 7.68 5.12 0.853333 0.426667 2.133333 0.426667 2.986667 0.853333 1.706667 0.426667 2.986667 0.853333 4.693333 0.853334 5.546667 0 11.093333-2.133333 14.933334-6.4l256-256c8.533333-8.533333 8.533333-21.76 0-30.293334s-21.76-8.533333-30.293334 0L533.333333 674.133333V128c0-11.946667-9.386667-21.333333-21.333333-21.333333s-21.333333 9.386667-21.333333 21.333333v545.706667l-219.306667-219.306667c-8.533333-8.533333-21.76-8.533333-30.293333 0s-8.533333 21.76 0 30.293333l255.146666 255.146667zM768 874.666667H256c-11.946667 0-21.333333 9.386667-21.333333 21.333333s9.386667 21.333333 21.333333 21.333333h512c11.946667 0 21.333333-9.386667 21.333333-21.333333s-9.386667-21.333333-21.333333-21.333333z" fill="#8a8a8a" p-id="5116"></path></svg><span>${r(`chat.export`)}</span><svg class="dropdown-arrow" width="8" height="6" viewBox="0 0 8 6" fill="currentColor"><path d="M0 0l4 6 4-6z"/></svg>`;let f=document.createElement(`div`);f.className=`export-dropdown`,f.innerHTML=[`<button class="export-dropdown-item export-docx-item" type="button">`,`<svg t="1781245550030" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6544" width="32" height="32"><path d="M747.936 901.171H276.819c-72.2 0-130.953-55.224-130.953-123.078V244.721c0-67.854 58.752-123.078 130.953-123.078h383.525c6.597 0 12.937 2.505 17.795 6.954l192.363 178.046c5.317 4.96 8.386 11.914 8.386 19.227v452.223c0 67.854-58.752 123.078-130.952 123.078zM276.819 174.004c-43.31 0-78.592 31.703-78.592 70.717v533.372c0 39.015 35.282 70.718 78.592 70.718h471.117c43.31 0 78.592-31.703 78.592-70.718V337.324l-176.461-163.32H276.819z" fill="#8a8a8a" p-id="6545"></path><path d="M830.567 331.546H669.446c-14.471 0-26.18-11.71-26.18-26.181V156.209c0-14.471 11.709-26.18 26.18-26.18s26.181 11.709 26.181 26.18v122.976h134.94c14.471 0 26.181 11.709 26.181 26.18s-11.711 26.181-26.181 26.181z" fill="#8a8a8a" p-id="6546"></path><path d="M730.214 428.749l-92.04 343.616h-53.179L511.363 498.29l-75.677 274.074h-53.179l-92.04-343.616h49.088l69.542 255.667 69.541-255.667h63.406l69.541 255.667 69.541-255.667h49.088z" fill="#8a8a8a" p-id="6547"></path></svg>`,`<span>${r(`chatMsg.exportWord`)}</span>`,`</button>`,`<button class="export-dropdown-item export-pdf-item" type="button">`,`<svg t="1781245863206" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="8152" width="32" height="32"><path d="M582.4 864H170.666667c-6.4 0-10.666667-4.266667-10.666667-10.666667V170.666667c0-6.4 4.266667-10.666667 10.666667-10.666667h309.333333V320c0 40.533333 34.133333 74.666667 74.666667 74.666667h160v38.4c0 17.066667 14.933333 32 32 32s32-14.933333 32-32V298.666667c0-8.533333-4.266667-17.066667-8.533334-23.466667l-170.666666-170.666667c-6.4-6.4-14.933333-8.533333-23.466667-8.533333H170.666667C130.133333 96 96 130.133333 96 170.666667v682.666666c0 40.533333 34.133333 74.666667 74.666667 74.666667h411.733333c17.066667 0 32-14.933333 32-32s-14.933333-32-32-32z m132.266667-550.4v17.066667H554.666667c-6.4 0-10.666667-4.266667-10.666667-10.666667V160h19.2l151.466667 153.6z" fill="#8a8a8a" p-id="8153"></path><path d="M332.8 533.333333c-12.8 0-19.2 2.133333-25.6 6.4-6.4 4.266667-8.533333 12.8-8.533333 23.466667v206.933333c0 6.4 2.133333 12.8 6.4 19.2 4.266667 4.266667 10.666667 8.533333 21.333333 8.533334s17.066667-4.266667 21.333333-8.533334c4.266667-4.266667 6.4-10.666667 6.4-19.2v-64h32c57.6 0 89.6-29.866667 89.6-87.466666 0-27.733333-8.533333-51.2-23.466666-64-14.933333-14.933333-36.266667-21.333333-66.133334-21.333334h-53.333333z m87.466667 85.333334c0 12.8-2.133333 23.466667-8.533334 27.733333-4.266667 4.266667-14.933333 8.533333-27.733333 8.533333h-32v-70.4H384c12.8 0 21.333333 2.133333 27.733333 8.533334 6.4 4.266667 8.533333 12.8 8.533334 25.6zM667.733333 571.733333c-8.533333-12.8-21.333333-21.333333-34.133333-29.866666-14.933333-4.266667-32-8.533333-51.2-8.533334h-61.866667c-8.533333 0-17.066667 0-23.466666 8.533334-2.133333 4.266667-4.266667 10.666667-4.266667 19.2V768c0 8.533333 2.133333 14.933333 4.266667 19.2 6.4 8.533333 14.933333 8.533333 23.466666 8.533333h64c19.2 0 34.133333-4.266667 49.066667-10.666666 12.8-6.4 25.6-17.066667 34.133333-29.866667 8.533333-12.8 14.933333-25.6 19.2-42.666667 4.266667-14.933333 6.4-32 6.4-49.066666 0-17.066667-2.133333-34.133333-6.4-49.066667-4.266667-14.933333-10.666667-29.866667-19.2-42.666667z m-42.666666 153.6c-8.533333 12.8-21.333333 19.2-38.4 19.2h-38.4v-160H576c21.333333 0 38.4 6.4 46.933333 19.2 10.666667 12.8 14.933333 34.133333 14.933334 59.733334 2.133333 27.733333-4.266667 46.933333-12.8 61.866666zM851.2 533.333333h-106.666667c-8.533333 0-17.066667 2.133333-21.333333 6.4-6.4 4.266667-8.533333 12.8-8.533333 21.333334v209.066666c0 6.4 2.133333 12.8 6.4 17.066667 4.266667 6.4 10.666667 8.533333 21.333333 8.533333 8.533333 0 17.066667-2.133333 21.333333-8.533333 2.133333-4.266667 6.4-8.533333 6.4-19.2v-85.333333h72.533334c12.8 0 23.466667-6.4 25.6-17.066667 2.133333-8.533333 2.133333-14.933333 0-17.066667-2.133333-4.266667-6.4-17.066667-25.6-17.066666H768v-49.066667h81.066667c8.533333 0 14.933333-2.133333 19.2-4.266667 4.266667-2.133333 8.533333-8.533333 8.533333-21.333333 2.133333-12.8-8.533333-23.466667-25.6-23.466667z" fill="#8a8a8a" p-id="8154"></path></svg>`,`<span>${r(`chatMsg.exportPdf`)}</span>`,`</button>`,`<button class="export-dropdown-item export-image-item" type="button">`,`<svg t="1784207887308" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5993" width="32" height="32"><path d="M400.696 268.795c-17.249 0-31.233 13.986-31.233 31.233v30.471c0 17.249 13.986 31.233 31.233 31.233s31.233-13.986 31.233-31.233v-30.471c0-17.249-13.985-31.233-31.233-31.233z" fill="#8a8a8a" p-id="5994"></path><path d="M623.649 361.734c17.249 0 31.234-13.986 31.234-31.233v-30.471c0-17.249-13.986-31.233-31.234-31.233s-31.233 13.986-31.233 31.233v30.471c-0.001 17.248 13.985 31.233 31.233 31.233z" fill="#8a8a8a" p-id="5995"></path><path d="M438.295 388.804c-14.656 9.104-19.155 28.362-10.050 43.013 11.209 18.047 41.976 48.59 86.157 48.59 43.958 0 75.1-30.313 86.574-48.223 9.303-14.529 5.068-33.847-9.455-43.15-14.539-9.298-33.852-5.068-43.15 9.455-0.122 0.199-13.38 19.45-33.969 19.45-20.009 0-32.444-18.128-33.278-19.373-9.166-14.423-28.28-18.805-42.829-9.761z" fill="#8a8a8a" p-id="5996"></path><path d="M824.508503 116.690676 571.592236 116.690676c-17.248849 0-31.233352 13.985526-31.233352 31.233352s13.985526 31.233352 31.233352 31.233352l252.916267 0c40.181141 0 72.878844 32.692586 72.878844 72.878844l0 396.966057-189.334159-165.29465c-12.20088-10.655687-30.517037-10.207479-42.173518 0.9967L468.578048 674.16231 309.521472 517.519714c-11.895935-11.70253-30.903847-12.002358-43.154869-0.645706L126.957507 646.163629l0-394.126382c0-40.186258 32.692586-72.878844 72.878844-72.878844l252.916267 0c17.248849 0 31.233352-13.985526 31.233352-31.233352S470.000444 116.690676 452.751594 116.690676L199.836351 116.690676c-74.632791 0-135.346571 60.71378-135.346571 135.346571l0 520.56405c0 74.632791 60.71378 135.346571 135.346571 135.346571l252.916267 0c17.248849 0 31.233352-13.985526 31.233352-31.233352s-13.985526-31.233352-31.233352-31.233352L199.836351 845.481164c-40.186258 0-72.878844-32.692586-72.878844-72.878844l0-41.23924 160.003134-148.385539 159.428036 157.007917c12.048407 11.865235 31.361265 11.981892 43.546795 0.274246l198.576661-190.68697 208.876238 182.346001 0 40.683585c0 40.186258-32.697703 72.878844-72.878844 72.878844L571.592236 845.481164c-17.248849 0-31.233352 13.985526-31.233352 31.233352s13.985526 31.233352 31.233352 31.233352l252.916267 0c74.627674 0 135.346571-60.71378 135.346571-135.346571L959.855074 252.037247C959.855074 177.404456 899.136178 116.690676 824.508503 116.690676z" fill="#8a8a8a" p-id="5997"></path></svg>`,`<span>${r(`chatMsg.exportImage`)}</span>`,`</button>`,`<button class="export-dropdown-item export-md-item" type="button">`,`<svg t="1784038824502" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1666" width="32" height="32"><path d="M601.216 85.333333a42.666667 42.666667 0 0 1 30.485333 12.821334l209.450667 213.973333a42.666667 42.666667 0 0 1 12.181333 29.866667V853.333333a85.333333 85.333333 0 0 1-85.333333 85.333334H256a85.333333 85.333333 0 0 1-85.333333-85.333334V170.666667a85.333333 85.333333 0 0 1 85.333333-85.333334h345.216z m-35.584 64H256a21.333333 21.333333 0 0 0-21.333333 21.333334v682.666666a21.333333 21.333333 0 0 0 21.333333 21.333334h512a21.333333 21.333333 0 0 0 21.333333-21.333334V395.413333h-191.68a32 32 0 0 1-32-32L565.632 149.333333z m64 38.186667v143.893333h140.821333L629.632 187.52z" fill="#8a8a8a" p-id="1667"></path><path d="M384.341333 800l-3.072-0.106667a32 32 0 0 1-29.162666-34.624l21.973333-256c2.752-32.256 46.165333-40.490667 60.544-11.477333l77.290667 156.010667 78.805333-156.224c14.08-27.925333 55.082667-20.906667 60.074667 8.789333l0.384 3.050667 20.714666 256a32 32 0 0 1-63.786666 5.162666l-11.541334-142.549333-56.341333 111.722667c-11.413333 22.613333-42.88 23.381333-55.744 2.517333l-1.493333-2.730667-54.912-110.826666-12.181334 142.016a32 32 0 0 1-31.552 29.269333z" fill="#8a8a8a" p-id="1668"></path></svg>`,`<span>${r(`chatMsg.exportMarkdown`)}</span>`,`</button>`].join(``);let p=f.querySelector(`.export-docx-item`);p.addEventListener(`click`,async e=>{e.stopPropagation();let{exportAssistantMessageToDocx:t}=await M(async()=>{let{exportAssistantMessageToDocx:e}=await import(`./chat-export-CDzJ0eSb.js`);return{exportAssistantMessageToDocx:e}},__vite__mapDeps([10,11,1,4,12,2,3,13,14,0]));t(m,p,f)});let h=f.querySelector(`.export-md-item`);h.addEventListener(`click`,async e=>{e.stopPropagation();let{exportAssistantMessageToMarkdown:t}=await M(async()=>{let{exportAssistantMessageToMarkdown:e}=await import(`./chat-export-CDzJ0eSb.js`);return{exportAssistantMessageToMarkdown:e}},__vite__mapDeps([10,11,1,4,12,2,3,13,14,0]));t(m,h,f)});let _=f.querySelector(`.export-pdf-item`);_.addEventListener(`click`,async e=>{e.stopPropagation();let{exportAssistantMessageToPdf:t}=await M(async()=>{let{exportAssistantMessageToPdf:e}=await import(`./chat-export-CDzJ0eSb.js`);return{exportAssistantMessageToPdf:e}},__vite__mapDeps([10,11,1,4,12,2,3,13,14,0]));t(m,_,f)});let v=f.querySelector(`.export-image-item`);v.addEventListener(`click`,async e=>{e.stopPropagation();let{exportAssistantMessageToImage:t}=await M(async()=>{let{exportAssistantMessageToImage:e}=await import(`./chat-export-CDzJ0eSb.js`);return{exportAssistantMessageToImage:e}},__vite__mapDeps([10,11,1,4,12,2,3,13,14,0]));t(m,v,f)}),u.addEventListener(`click`,e=>{e.stopPropagation(),document.querySelectorAll(`.export-dropdown.show`).forEach(e=>{e!==f&&e.classList.remove(`show`)}),f.classList.toggle(`show`)});let y=null;l.addEventListener(`mouseenter`,()=>{y=setTimeout(()=>{document.querySelectorAll(`.export-dropdown.show`).forEach(e=>{e!==f&&e.classList.remove(`show`)}),f.classList.add(`show`)},300)}),l.addEventListener(`mouseleave`,()=>{y&&=(clearTimeout(y),null),setTimeout(()=>{!l.matches(`:hover`)&&!f.matches(`:hover`)&&f.classList.remove(`show`)},100)}),l.appendChild(u),l.appendChild(f),e.appendChild(l);let b=document.createElement(`div`);b.className=`footer-right-actions`,b.style.marginLeft=`auto`,b.style.display=`flex`,b.style.alignItems=`center`,b.style.gap=`8px`;let x=Rt(i);if(x){let e=document.createElement(`span`);e.className=`token-usage-tag`,e.title=r(`chatStream.tokenUsageTitle`,{total:F(x.totalTokens),prompt:F(x.promptTokens),completion:F(x.completionTokens)}),e.innerHTML=`<span class="token-tag-icon">⬤</span><span class="token-tag-value">${F(x.totalTokens)}</span>`,e.style.cursor=`pointer`,e.addEventListener(`click`,t=>{t.stopPropagation(),Ot(x,e)}),b.appendChild(e)}let S=i&&i.length>0,C=o!=null,w=i?i.filter(e=>e.nodeType===`reflection`&&e.reflectionType===`post`&&e.status===`success`).length:0;sw(),lw(),qt();let T=i?.find(e=>e.nodeType===`reflection`&&e.reflectionType===`post`),E=Ly(t),D=By(i,t);if(E.length&&(m.dataset.declaredArtifacts=JSON.stringify(E)),ib(D),console.log(`[addMessage] executionLog entries:`,i?.length,`| agent_file entries:`,i?.filter(e=>e.nodeType===`tool_exec`&&e.action?.name===`agent_file`).length,`| artifacts:`,D.length),D.length>0){let e=document.createElement(`button`);e.className=`artifacts-btn`,e.type=`button`,e.title=r(`artifacts.btnTitle`,{count:D.length}),e.innerHTML=`
|
|
1780
1780
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="14" height="14">
|
|
1781
1781
|
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
|
|
1782
1782
|
<polyline points="14 2 14 8 20 8"/>
|
|
@@ -1803,7 +1803,7 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
|
|
|
1803
1803
|
<polyline points="3 6 5 6 21 6"></polyline>
|
|
1804
1804
|
<path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
|
|
1805
1805
|
</svg>
|
|
1806
|
-
`,l.addEventListener(`click`,e=>{e.stopPropagation(),_w(m)}),o.appendChild(l),m.appendChild(o),h){m.classList.add(`has-time`);let e=document.createElement(`time`);e.className=`message-time`,e.dateTime=h,e.textContent=
|
|
1806
|
+
`,l.addEventListener(`click`,e=>{e.stopPropagation(),_w(m)}),o.appendChild(l),m.appendChild(o),h){m.classList.add(`has-time`);let e=document.createElement(`time`);e.className=`message-time`,e.dateTime=h,e.textContent=Mt(h),e.title=Nt(h),m.appendChild(e)}}if(p.appendChild(m),m._pendingContext){let{type:e,contextText:t}=m._pendingContext,n=ew(e,t,!1);p.insertBefore(n,m),delete m._pendingContext}return n&&CS(p,{smooth:!0}),e===`assistant`&&sn(),{element:m,messageId:g,timestamp:h}}function aw(e){let t=document.getElementById(`chatContainer`);t&&t.classList.toggle(`timestamps-hidden`,e===!1)}var ow=!1;function sw(){if(ow)return;let e=document.getElementById(`chatContainer`);e&&(e.addEventListener(`click`,e=>{let t=e.target.closest(`.execution-log-btn`);if(!t)return;let n=t.closest(`.message`);if(!n)return;e.preventDefault(),e.stopPropagation();let r=n.dataset.executionLog;if(r)try{let e=JSON.parse(r);a.debug(`[chat-manager] exec log buttonclick(delegate), entries:`,e.length),qx(e)}catch(e){a.error(`[chat-manager] parse executionLog failed:`,e)}}),ow=!0)}var cw=!1;function lw(){if(cw)return;let e=document.getElementById(`chatContainer`);e&&(e.addEventListener(`click`,e=>{let t=e.target.closest(`.reflection-score-btn`);if(!t)return;e.preventDefault(),e.stopPropagation();let n=t.dataset.reflectionData;if(n)try{Kx(JSON.parse(n),t)}catch(e){a.error(`[chat-manager] parse reflectionData failed:`,e)}}),cw=!0)}function uw(){let e=document.getElementById(`chatContainer`),t=`loading-`+Date.now(),n=document.createElement(`div`);n.className=`loading-message`,n.id=t,n.innerHTML=`
|
|
1807
1807
|
<div class="loading-content">
|
|
1808
1808
|
<div class="loading-dots">
|
|
1809
1809
|
<span></span>
|
|
@@ -1839,11 +1839,11 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
|
|
|
1839
1839
|
<svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
|
|
1840
1840
|
<path d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 0 1 0 1.5h-1.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-1.5a.75.75 0 0 1 1.5 0v1.5A1.75 1.75 0 0 1 9.25 16h-7.5A1.75 1.75 0 0 1 0 14.25zM5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0 1 14.25 11h-7.5A1.75 1.75 0 0 1 5 9.25zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25z"/>
|
|
1841
1841
|
</svg>
|
|
1842
|
-
</button>`,e.parentElement.insertBefore(t,e),t.appendChild(e)}),s.querySelectorAll(`.subtask-progress`).forEach(e=>{GC(e)}),s.querySelectorAll(`.tool-call-terminate-btn, .agent-stream-terminate-btn`).forEach(e=>{e.addEventListener(`click`,e=>{e.stopPropagation(),hw(N.activeSessionId)})}),s.querySelectorAll(`.tool-call-abort-btn`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),chrome.runtime.sendMessage({type:`ABORT_CURRENT_TOOL`,sessionId:N.activeSessionId}),e.disabled=!0,e.title=r(`chatMsg.aborting`)})});let l=s.querySelector(`.message-footer`);if(l){let e=l.querySelector(`.copy-btn`);e&&e.addEventListener(`click`,t=>{t.stopPropagation(),Lx(s,e,t)});let t=l.querySelector(`.quote-btn`);t&&t.addEventListener(`click`,e=>{e.stopPropagation(),Gx(s)});let n=l.querySelector(`.export-trigger-btn`),r=l.querySelector(`.export-dropdown`);n&&r&&(n.addEventListener(`click`,e=>{e.stopPropagation(),document.querySelectorAll(`.export-dropdown.show`).forEach(e=>{e!==r&&e.classList.remove(`show`)}),r.classList.toggle(`show`)}),r.querySelector(`.export-docx-item`)?.addEventListener(`click`,async e=>{e.stopPropagation();let t=e.currentTarget,{exportAssistantMessageToDocx:n}=await M(async()=>{let{exportAssistantMessageToDocx:e}=await import(`./chat-export-
|
|
1842
|
+
</button>`,e.parentElement.insertBefore(t,e),t.appendChild(e)}),s.querySelectorAll(`.subtask-progress`).forEach(e=>{GC(e)}),s.querySelectorAll(`.tool-call-terminate-btn, .agent-stream-terminate-btn`).forEach(e=>{e.addEventListener(`click`,e=>{e.stopPropagation(),hw(N.activeSessionId)})}),s.querySelectorAll(`.tool-call-abort-btn`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),chrome.runtime.sendMessage({type:`ABORT_CURRENT_TOOL`,sessionId:N.activeSessionId}),e.disabled=!0,e.title=r(`chatMsg.aborting`)})});let l=s.querySelector(`.message-footer`);if(l){let e=l.querySelector(`.copy-btn`);e&&e.addEventListener(`click`,t=>{t.stopPropagation(),Lx(s,e,t)});let t=l.querySelector(`.quote-btn`);t&&t.addEventListener(`click`,e=>{e.stopPropagation(),Gx(s)});let n=l.querySelector(`.export-trigger-btn`),r=l.querySelector(`.export-dropdown`);n&&r&&(n.addEventListener(`click`,e=>{e.stopPropagation(),document.querySelectorAll(`.export-dropdown.show`).forEach(e=>{e!==r&&e.classList.remove(`show`)}),r.classList.toggle(`show`)}),r.querySelector(`.export-docx-item`)?.addEventListener(`click`,async e=>{e.stopPropagation();let t=e.currentTarget,{exportAssistantMessageToDocx:n}=await M(async()=>{let{exportAssistantMessageToDocx:e}=await import(`./chat-export-CDzJ0eSb.js`);return{exportAssistantMessageToDocx:e}},__vite__mapDeps([10,11,1,4,12,2,3,13,14,0]));n(s,t,r)}),r.querySelector(`.export-md-item`)?.addEventListener(`click`,async e=>{e.stopPropagation();let t=e.currentTarget,{exportAssistantMessageToMarkdown:n}=await M(async()=>{let{exportAssistantMessageToMarkdown:e}=await import(`./chat-export-CDzJ0eSb.js`);return{exportAssistantMessageToMarkdown:e}},__vite__mapDeps([10,11,1,4,12,2,3,13,14,0]));n(s,t,r)}),r.querySelector(`.export-pdf-item`)?.addEventListener(`click`,async e=>{e.stopPropagation();let t=e.currentTarget,{exportAssistantMessageToPdf:n}=await M(async()=>{let{exportAssistantMessageToPdf:e}=await import(`./chat-export-CDzJ0eSb.js`);return{exportAssistantMessageToPdf:e}},__vite__mapDeps([10,11,1,4,12,2,3,13,14,0]));n(s,t,r)}),r.querySelector(`.export-image-item`)?.addEventListener(`click`,async e=>{e.stopPropagation();let t=e.currentTarget,{exportAssistantMessageToImage:n}=await M(async()=>{let{exportAssistantMessageToImage:e}=await import(`./chat-export-CDzJ0eSb.js`);return{exportAssistantMessageToImage:e}},__vite__mapDeps([10,11,1,4,12,2,3,13,14,0]));n(s,t,r)}));let i=l.querySelector(`.prototype-btn-small`);if(i){let e=(()=>{try{let e=s.dataset.executionLog;return e?JSON.parse(e):[]}catch{return[]}})().find(e=>e.nodeType===`tool_exec`&&e.action?.name===`preview_ui`||e.action?.name===`preview_preview_ui`&&e.status===`success`);e&&i.addEventListener(`click`,()=>{let t=e.prototypeId;if(!t&&e.observation)try{t=(typeof e.observation==`string`?JSON.parse(e.observation):e.observation)?.prototypeId}catch{}t?Cc(t):a.error(`[SidePanel] not found prototypeId,entry keys:`,Object.keys(e),`observation:`,e.observation)})}let o=l.querySelector(`.bookmark-btn`);o&&(Km(o,N.activeSessionId,s.dataset.messageId),o.addEventListener(`click`,async e=>{e.stopPropagation();let t=N.activeSessionId,n=s.dataset.messageId;if(o.classList.contains(`bookmarked`)){await Pm(t,n),Km(o,t,n);let{refreshBookmarkPanel:e}=await M(async()=>{let{refreshBookmarkPanel:e}=await Promise.resolve().then(()=>Rm);return{refreshBookmarkPanel:e}},void 0);e()}else{await Nm(t,n,s.dataset.textContent_||``,N.sessions.find(e=>e.id===t)?.title||``),Km(o,t,n);let{refreshBookmarkPanel:e}=await M(async()=>{let{refreshBookmarkPanel:e}=await Promise.resolve().then(()=>Rm);return{refreshBookmarkPanel:e}},void 0);e()}}));let c=l.querySelector(`.delete-btn`);c&&c.addEventListener(`click`,e=>{e.stopPropagation(),_w(s)});let u=l.querySelector(`.fork-btn`);u&&u.addEventListener(`click`,async e=>{e.stopPropagation();let t=s.dataset.messageId;t&&await Xs(N.activeSessionId,t)});let d=l.querySelector(`.resume-task-btn`);d&&d.addEventListener(`click`,async e=>{if(e.stopPropagation(),d.disabled)return;let t=await Jx({budgetEnded:rw(s)});t!==null&&(d.disabled=!0,d.style.opacity=`0.6`,d.style.cursor=`not-allowed`,$x(N.activeSessionId,t).finally(()=>{d.disabled=!1,d.style.opacity=``,d.style.cursor=``}))}),fw(s);let f=l.querySelector(`.token-usage-tag`);f&&!f._clickBound&&(f._clickBound=!0,f.style.cursor=`pointer`,f.addEventListener(`click`,e=>{e.stopPropagation();try{let e=s.dataset.executionLog,t=Rt(e?JSON.parse(e):[]);t&&Ot(t,f)}catch{}}))}let u=s.querySelector(`.message-toolbar`);if(u){let e=u.querySelector(`.edit-btn`);e&&e.addEventListener(`click`,e=>{e.stopPropagation(),bw(s)});let t=u.querySelector(`.copy-btn`);t&&t.addEventListener(`click`,e=>{e.stopPropagation(),Ix(s,t)});let n=u.querySelector(`.delete-btn`);n&&n.addEventListener(`click`,e=>{e.stopPropagation(),_w(s)})}s.querySelectorAll(`.user-message-image`).forEach(e=>{e.addEventListener(`click`,()=>{jp(e.src,e)})}),i.appendChild(s),NE()}function mw(e){e.querySelectorAll(`.tool-call-body > pre, .tool-result-content > pre, .agent-stream-output > pre`).forEach(e=>{if(e.parentElement.classList.contains(`code-block-container`))return;let t=document.createElement(`div`);t.className=`code-block-container`,t.style.position=`relative`,t.innerHTML=`<button class="code-copy-btn" title="${r(`chatMsg.copyCode`)}">
|
|
1843
1843
|
<svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
|
|
1844
1844
|
<path d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 0 1 0 1.5h-1.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-1.5a.75.75 0 0 1 1.5 0v1.5A1.75 1.75 0 0 1 9.25 16h-7.5A1.75 1.75 0 0 1 0 14.25zM5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0 1 14.25 11h-7.5A1.75 1.75 0 0 1 5 9.25zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25z"/>
|
|
1845
1845
|
</svg>
|
|
1846
|
-
</button>`,e.parentElement.insertBefore(t,e),t.appendChild(e)}),e.querySelectorAll(`.thinking-process-header`).forEach(e=>{kS(e)}),e.querySelectorAll(`.tool-call-header`).forEach(e=>{e.addEventListener(`click`,t=>{if(t.ctrlKey||t.metaKey)return;let n=e.closest(`.tool-call-item`);n&&n.classList.toggle(`expanded`)})}),e.querySelectorAll(`.tool-call-result`).forEach(e=>{let t=e.querySelector(`code`);if(!t)return;let n=t.dataset.fullContent;if(!n||n.length<=500)return;let r=t.textContent||``,i=!1;e.style.cursor=`pointer`,e.addEventListener(`click`,e=>{e.ctrlKey||e.metaKey||(e.stopPropagation(),i=!i,t.textContent=i?n:r)})}),e.querySelectorAll(`.subtask-progress`).forEach(e=>{GC(e)}),e.querySelectorAll(`.tool-call-terminate-btn, .agent-stream-terminate-btn`).forEach(e=>{e.addEventListener(`click`,e=>{e.stopPropagation(),hw(N.activeSessionId)})}),e.querySelectorAll(`.tool-call-abort-btn`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),chrome.runtime.sendMessage({type:`ABORT_CURRENT_TOOL`,sessionId:N.activeSessionId}),e.disabled=!0,e.title=r(`chatMsg.aborting`)})}),e.querySelectorAll(`.message-footer`).forEach(e=>{let t=e.closest(`.message`);if(!t)return;let n=e.querySelector(`.copy-btn`);n&&n.addEventListener(`click`,e=>{e.stopPropagation(),Lx(t,n,e)});let r=e.querySelector(`.quote-btn`);r&&r.addEventListener(`click`,e=>{e.stopPropagation(),Gx(t)});let i=e.querySelector(`.export-trigger-btn`),a=e.querySelector(`.export-dropdown`);i&&a&&(i.addEventListener(`click`,e=>{e.stopPropagation(),document.querySelectorAll(`.export-dropdown.show`).forEach(e=>{e!==a&&e.classList.remove(`show`)}),a.classList.toggle(`show`)}),a.querySelector(`.export-docx-item`)?.addEventListener(`click`,async e=>{e.stopPropagation();let n=e.currentTarget,{exportAssistantMessageToDocx:r}=await M(async()=>{let{exportAssistantMessageToDocx:e}=await import(`./chat-export-
|
|
1846
|
+
</button>`,e.parentElement.insertBefore(t,e),t.appendChild(e)}),e.querySelectorAll(`.thinking-process-header`).forEach(e=>{kS(e)}),e.querySelectorAll(`.tool-call-header`).forEach(e=>{e.addEventListener(`click`,t=>{if(t.ctrlKey||t.metaKey)return;let n=e.closest(`.tool-call-item`);n&&n.classList.toggle(`expanded`)})}),e.querySelectorAll(`.tool-call-result`).forEach(e=>{let t=e.querySelector(`code`);if(!t)return;let n=t.dataset.fullContent;if(!n||n.length<=500)return;let r=t.textContent||``,i=!1;e.style.cursor=`pointer`,e.addEventListener(`click`,e=>{e.ctrlKey||e.metaKey||(e.stopPropagation(),i=!i,t.textContent=i?n:r)})}),e.querySelectorAll(`.subtask-progress`).forEach(e=>{GC(e)}),e.querySelectorAll(`.tool-call-terminate-btn, .agent-stream-terminate-btn`).forEach(e=>{e.addEventListener(`click`,e=>{e.stopPropagation(),hw(N.activeSessionId)})}),e.querySelectorAll(`.tool-call-abort-btn`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),chrome.runtime.sendMessage({type:`ABORT_CURRENT_TOOL`,sessionId:N.activeSessionId}),e.disabled=!0,e.title=r(`chatMsg.aborting`)})}),e.querySelectorAll(`.message-footer`).forEach(e=>{let t=e.closest(`.message`);if(!t)return;let n=e.querySelector(`.copy-btn`);n&&n.addEventListener(`click`,e=>{e.stopPropagation(),Lx(t,n,e)});let r=e.querySelector(`.quote-btn`);r&&r.addEventListener(`click`,e=>{e.stopPropagation(),Gx(t)});let i=e.querySelector(`.export-trigger-btn`),a=e.querySelector(`.export-dropdown`);i&&a&&(i.addEventListener(`click`,e=>{e.stopPropagation(),document.querySelectorAll(`.export-dropdown.show`).forEach(e=>{e!==a&&e.classList.remove(`show`)}),a.classList.toggle(`show`)}),a.querySelector(`.export-docx-item`)?.addEventListener(`click`,async e=>{e.stopPropagation();let n=e.currentTarget,{exportAssistantMessageToDocx:r}=await M(async()=>{let{exportAssistantMessageToDocx:e}=await import(`./chat-export-CDzJ0eSb.js`);return{exportAssistantMessageToDocx:e}},__vite__mapDeps([10,11,1,4,12,2,3,13,14,0]));r(t,n,a)}),a.querySelector(`.export-md-item`)?.addEventListener(`click`,async e=>{e.stopPropagation();let n=e.currentTarget,{exportAssistantMessageToMarkdown:r}=await M(async()=>{let{exportAssistantMessageToMarkdown:e}=await import(`./chat-export-CDzJ0eSb.js`);return{exportAssistantMessageToMarkdown:e}},__vite__mapDeps([10,11,1,4,12,2,3,13,14,0]));r(t,n,a)}),a.querySelector(`.export-pdf-item`)?.addEventListener(`click`,async e=>{e.stopPropagation();let n=e.currentTarget,{exportAssistantMessageToPdf:r}=await M(async()=>{let{exportAssistantMessageToPdf:e}=await import(`./chat-export-CDzJ0eSb.js`);return{exportAssistantMessageToPdf:e}},__vite__mapDeps([10,11,1,4,12,2,3,13,14,0]));r(t,n,a)}),a.querySelector(`.export-image-item`)?.addEventListener(`click`,async e=>{e.stopPropagation();let n=e.currentTarget,{exportAssistantMessageToImage:r}=await M(async()=>{let{exportAssistantMessageToImage:e}=await import(`./chat-export-CDzJ0eSb.js`);return{exportAssistantMessageToImage:e}},__vite__mapDeps([10,11,1,4,12,2,3,13,14,0]));r(t,n,a)}));let o=e.querySelector(`.prototype-btn-small`);if(o){let e=(()=>{try{let e=t.dataset.executionLog;return e?JSON.parse(e):[]}catch{return[]}})().find(e=>e.nodeType===`tool_exec`&&e.action?.name===`preview_ui`||e.action?.name===`preview_preview_ui`&&e.status===`success`);e&&o.addEventListener(`click`,()=>{let t=e.prototypeId;if(!t&&e.observation)try{t=(typeof e.observation==`string`?JSON.parse(e.observation):e.observation)?.prototypeId}catch{}t&&Cc(t)})}let s=e.querySelector(`.bookmark-btn`);s&&(Km(s,N.activeSessionId,t.dataset.messageId),s.addEventListener(`click`,async e=>{e.stopPropagation();let n=N.activeSessionId,r=t.dataset.messageId;if(s.classList.contains(`bookmarked`)){await Pm(n,r),Km(s,n,r);let{refreshBookmarkPanel:e}=await M(async()=>{let{refreshBookmarkPanel:e}=await Promise.resolve().then(()=>Rm);return{refreshBookmarkPanel:e}},void 0);e()}else{await Nm(n,r,t.dataset.textContent_||``,N.sessions.find(e=>e.id===n)?.title||``),Km(s,n,r);let{refreshBookmarkPanel:e}=await M(async()=>{let{refreshBookmarkPanel:e}=await Promise.resolve().then(()=>Rm);return{refreshBookmarkPanel:e}},void 0);e()}}));let c=e.querySelector(`.delete-btn`);c&&c.addEventListener(`click`,e=>{e.stopPropagation(),_w(t)});let l=e.querySelector(`.fork-btn`);l&&l.addEventListener(`click`,async e=>{e.stopPropagation();let n=t.dataset.messageId;n&&await Xs(N.activeSessionId,n)});let u=e.querySelector(`.resume-task-btn`);u&&u.addEventListener(`click`,async e=>{if(e.stopPropagation(),u.disabled)return;let n=await Jx({budgetEnded:rw(t)});n!==null&&(u.disabled=!0,u.style.opacity=`0.6`,u.style.cursor=`not-allowed`,$x(N.activeSessionId,n).finally(()=>{u.disabled=!1,u.style.opacity=``,u.style.cursor=``}))}),fw(t);let d=e.querySelector(`.token-usage-tag`);d&&!d._clickBound&&(d._clickBound=!0,d.style.cursor=`pointer`,d.addEventListener(`click`,e=>{e.stopPropagation();try{let e=t.dataset.executionLog,n=Rt(e?JSON.parse(e):[]);n&&Ot(n,d)}catch{}}))}),e.querySelectorAll(`.message-toolbar`).forEach(e=>{let t=e.closest(`.message`);if(!t)return;let n=e.querySelector(`.edit-btn`);n&&n.addEventListener(`click`,e=>{e.stopPropagation(),bw(t)});let r=e.querySelector(`.copy-btn`);r&&r.addEventListener(`click`,e=>{e.stopPropagation(),Ix(t,r)});let i=e.querySelector(`.delete-btn`);i&&i.addEventListener(`click`,e=>{e.stopPropagation(),_w(t)})}),e.querySelectorAll(`.user-message-image`).forEach(e=>{e.addEventListener(`click`,()=>{jp(e.src,e)})}),e.querySelectorAll(`.mermaid-controls`).forEach(e=>e.remove()),an(),sw(),lw(),NE()}function hw(e){return new Promise(t=>{let n=document.querySelector(`.command-terminate-overlay`);n&&n.remove();let i=document.createElement(`div`);i.className=`command-terminate-overlay`,i.innerHTML=`
|
|
1847
1847
|
<div class="command-terminate-modal">
|
|
1848
1848
|
<div class="command-terminate-header">
|
|
1849
1849
|
<div class="command-terminate-icon">⏹</div>
|
|
@@ -1895,7 +1895,7 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
|
|
|
1895
1895
|
<h2>${r(`chat.welcomeTitle`)}</h2>
|
|
1896
1896
|
<p>${r(`chat.welcomeSubtitle`)}</p>
|
|
1897
1897
|
</div>
|
|
1898
|
-
`),await kC(),n&&N.activeSessionId&&_e(N.activeSessionId,n).then(e=>{e||a.warn(`[SidePanel] IndexedDB messagecleanup failed, messageId:`,n)}).catch(e=>{a.error(`[SidePanel] IndexedDB messagecleanup exception:`,e)}),a.debug(`[SidePanel] deletedmessage: ${i}, messageId: ${n}`)}async function vw(e=null){try{let{mcpTools:t}=await chrome.storage.local.get([`mcpTools`]),n=t||[],r=new Set(Array.isArray(N.mcpClosedServers)?N.mcpClosedServers:[]),i=new Set(Array.isArray(N.activeAgentMcpExcludedServerIds)?N.activeAgentMcpExcludedServerIds:[]),a=new Set(Array.isArray(e)?e:[]);return n.filter(e=>{let t=e.serverId||`unknown`;return a.has(t)?!0:!r.has(t)&&!i.has(t)}).length}catch{return 0}}async function yw(e,t,n=!1,i={},o={}){let{resumeFromCheckpoint:s=!1,userGuidance:c=``,loadingId:l=null,forcedMcpServerIds:u=null,sessionId:d=null,agent:f=null}=o,p=f?f.agentId:N.activeAgentId,m=f?f.agentToolIds:N.activeAgentToolIds,h=f?f.agentSkillIds:N.activeAgentSkillIds,g=f?f.agentMcpExcludedServerIds:N.activeAgentMcpExcludedServerIds,_=await
|
|
1898
|
+
`),await kC(),n&&N.activeSessionId&&_e(N.activeSessionId,n).then(e=>{e||a.warn(`[SidePanel] IndexedDB messagecleanup failed, messageId:`,n)}).catch(e=>{a.error(`[SidePanel] IndexedDB messagecleanup exception:`,e)}),a.debug(`[SidePanel] deletedmessage: ${i}, messageId: ${n}`)}async function vw(e=null){try{let{mcpTools:t}=await chrome.storage.local.get([`mcpTools`]),n=t||[],r=new Set(Array.isArray(N.mcpClosedServers)?N.mcpClosedServers:[]),i=new Set(Array.isArray(N.activeAgentMcpExcludedServerIds)?N.activeAgentMcpExcludedServerIds:[]),a=new Set(Array.isArray(e)?e:[]);return n.filter(e=>{let t=e.serverId||`unknown`;return a.has(t)?!0:!r.has(t)&&!i.has(t)}).length}catch{return 0}}async function yw(e,t,n=!1,i={},o={}){let{resumeFromCheckpoint:s=!1,userGuidance:c=``,loadingId:l=null,forcedMcpServerIds:u=null,sessionId:d=null,agent:f=null}=o,p=f?f.agentId:N.activeAgentId,m=f?f.agentToolIds:N.activeAgentToolIds,h=f?f.agentSkillIds:N.activeAgentSkillIds,g=f?f.agentMcpExcludedServerIds:N.activeAgentMcpExcludedServerIds,_=await Wt(),v=(_.toolTimeout||0)+3*(_.apiTimeout||0)+6e4,y=_.loopTimeout+v,b=await new Promise(e=>{chrome.storage.local.get(`reflectionConfig`,t=>{e(t.reflectionConfig||{enabled:!1})})}),x=d||N.activeSessionId,S=s?`resume_${Date.now()}_${Math.random().toString(36).substring(2,8)}`:`call_${Date.now()}_${Math.random().toString(36).substring(2,8)}`;if(a.debug(`[SidePanel] callApi: generating callId: ${S}${s?` (restoremode)`:``}`),s&&l&&(i={...i,_loadingId:l}),N.pendingCancelApiMap&&N.pendingCancelApiMap.has(x)){a.debug(`[SidePanel] callApi: detectedsession has ongoing API call with , first cancelold`);let e=N.pendingCancelApiMap.get(x);e&&e({message:r(`chatMsg.errTaskReplaced`),executionLog:[]})}N.pendingCallApiSessionIds&&N.pendingCallApiSessionIds.has(x)&&(N.pendingCallApiSessionIds.delete(x),_C());let C=RS(x),w=chrome.runtime.connect({name:`keepalive-`+x});a.debug(`[SidePanel] keepalive portconnected, sessionId:`,x),nl(x);try{let e=tl();w.postMessage({type:`KEEPALIVE_IDENTITY`,identity:e==null?null:{windowId:e}})}catch{}let T={restarted:!1,rejectFn:null,cleanup:null,checkpoint:null};w.onMessage.addListener(e=>{if(e.type===`HOST_TAB_RESOLVED`&&e.sessionId===x){rl(x,e.hostTabId);return}e.type===`SW_RESTARTED`&&e.sessionId===x&&(a.warn(`[SidePanel] ⚠️ recei to SW_RESTARTED notification,background re started,API call lost`),T.restarted=!0,T.checkpoint=e.checkpoint||null,T.rejectFn&&T.cleanup&&(T.cleanup(),T.rejectFn({message:r(`chatMsg.errSwRestarted`),executionLog:[],checkpoint:T.checkpoint,swRestarted:!0}))),e.type===`SHOW_CLARIFY_DIALOG`?xo(e.data):e.type===`CLARIFY_TIMEOUT`?Do(e):e.type===`CLARIFY_EXTENDED`?uo(e):e.type===`SHOW_CONFIRM_DIALOG`?Wo(e.data):e.type===`DISMISS_CONFIRM_DIALOG`&&qo(e.data)});let E={timeoutId:null,removeListener:()=>{}},D=()=>{try{w.disconnect()}catch{}E.timeoutId&&=(clearTimeout(E.timeoutId),null),E.removeListener(),N.pendingCancelApiMap.delete(x),N.pendingCallApiSessionIds.delete(x),zS(x),_C()};return new Promise((o,l)=>{if(T.cleanup=D,T.rejectFn=l,T.restarted){D(),l({message:r(`chatMsg.errSwRestarted`),executionLog:[],checkpoint:T.checkpoint,swRestarted:!0});return}let d=[],f=Math.round(_.loopTimeout/1e3);C(null),US(null),qS(0);let v=``,w={},O=e=>{C()&&mC(C()),D(),(!e.executionLog||e.executionLog.length===0||d.length>0)&&(e.executionLog=d),l(e)};N.pendingCancelApiMap.set(x,O),N.pendingCallApiSessionIds.add(x),_C(),a.debug(`[SidePanel] callApi: add pendingCallApiSessionIds, mySessionId =`,x,`, set:`,[...N.pendingCallApiSessionIds]),E.timeoutId=setTimeout(()=>{O({message:r(`chatMsg.errTimeout`,{seconds:f}),executionLog:d}),chrome.runtime.sendMessage({type:`CANCEL_REACT`,tabId:N.currentTabId,sessionId:x}).catch(e=>{a.debug(`[SidePanel] sendcancelrequest failed:`,e.message)})},y);let k=Date.now(),A=0,j=null,ee=()=>{j===null&&E.timeoutId!==null&&(j=Date.now(),clearTimeout(E.timeoutId),E.timeoutId=null,a.debug(`[SidePanel] before sidetimeoutpaused (waitinguser response:clarification/sensitive toolconfirm)`))},te=()=>{if(j!==null){let e=Date.now()-j;A+=e,j=null;let t=Date.now()-k,n=y+A-t;if(n<=0){O({message:r(`chatMsg.errTimeout`,{seconds:f}),executionLog:d});return}E.timeoutId=setTimeout(()=>{O({message:r(`chatMsg.errTimeout`,{seconds:f}),executionLog:d}),chrome.runtime.sendMessage({type:`CANCEL_REACT`,tabId:N.currentTabId,sessionId:x}).catch(e=>{a.debug(`[SidePanel] sendcancelrequest failed:`,e.message)})},n),a.debug(`[SidePanel] before sidetimeoutrestored,pause duration:`,Math.round(e/1e3),`s,remaining time:`,Math.round(n/1e3),`s`)}},ne=e=>{if(e.sessionId&&e.sessionId!==x||e.callId&&e.callId!==S)return!1;if(e.type===`EXECUTION_STATUS_UPDATE`){let t=e.executionLog||[];if(t.length>0&&t.forEach(e=>{let t=d.findIndex(t=>t.id===e.id);t===-1?d.push(e):d[t]={...d[t],...e}}),e.subtaskTotal&&e.subtaskTotal>0){let t=C();if(t){let n=t.querySelector(`.stream-content`);if(n){let t=e.subtaskIndex??0,i=UC(d);i&&[...i.items].sort((e,t)=>e.index-t.index).forEach(r=>{if(r.index===t)return;let a=`.subtask-progress[data-subtask-index="${r.index}"]`;if(n.querySelector(a))return;let o=document.createElement(`div`);o.className=`subtask-progress subtask-progress-pending`,o.dataset.subtaskIndex=r.index,o.innerHTML=WC(r,i.total||e.subtaskTotal),KC(n,o),GC(o)});let a=`.subtask-progress[data-subtask-index="${t}"]`,o=n.querySelector(a),s=o?o.classList.contains(`subtask-expanded`):!1;o||(o=document.createElement(`div`),o.className=`subtask-progress`,o.dataset.subtaskIndex=t,KC(n,o));let c=VC,l=t+1,u=e.subtaskTotal,f=e.subtaskName||``,p=`<span class="subtask-badge">${l}/${u}</span>`,m=HC,h=e.status!==`success`&&e.status!==`failed`,g=d.filter(e=>e.subtaskIndex===t&&e.nodeType!==`subtask`),_=LC(g),v=_.total,y=_.success,b=_.failed,x=_.other,S=g.find(e=>e.status===`processing`),C=IC(e.status,y,v),w=i?i.items.find(e=>e.index===t):null,T=w&&w.description?String(w.description).replace(/\s+/g,` `).trim():``,E=d.find(e=>e.subtaskIndex===t&&e.nodeType===`subtask`),D=RC(d,t)?`<span class="subtask-replay-skipped" title="${I(r(`chatMsg.subtaskReplaySkippedHint`))}">${r(`chatMsg.subtaskReplaySkipped`)}</span>`:``;o.classList.remove(`subtask-progress-pending`);let O=``;e.status===`success`?(O=`<span class="subtask-status-done">${r(`chatMsg.subtaskDone`)}</span>`,o.classList.add(`subtask-progress-done`),o.classList.remove(`subtask-progress-active`)):C===`partial`?(O=`<span class="subtask-status-partial">${r(`chatMsg.subtaskPartial`)}</span>`,o.classList.add(`subtask-progress-failed`),o.classList.remove(`subtask-progress-active`)):e.status===`failed`?(O=`<span class="subtask-status-failed">${r(`chatMsg.subtaskFailed`)}</span>`,o.classList.add(`subtask-progress-failed`),o.classList.remove(`subtask-progress-active`)):(O=`<span class="subtask-status-label"><span class="subtask-spinner"></span>${r(`chatMsg.subtaskExecuting`)}</span>`,o.classList.add(`subtask-progress-active`));let k=``;if(h&&v>0){let e=S?S.nodeType===`tool_exec`?`🔧`:S.nodeType===`api_call`?`📡`:S.nodeType===`reflection`?`🎯`:S.nodeType===`preselect`?`🔍`:`○`:`○`,t=S?P(S.nodeName||``):r(`chatMsg.preparing`),n=S?Lf(S):``;k=`<div class="subtask-progress-line">
|
|
1899
1899
|
<span class="subtask-current-node"><span class="subtask-current-spinner"></span><span class="node-label">${e} ${t}</span>${n?` <span class="subtask-current-cmd" title="${I(n)}">${P(n)}</span>`:``}</span>
|
|
1900
1900
|
<span class="subtask-node-stats">
|
|
1901
1901
|
<span class="subtask-stat-total">${v}</span>
|
|
@@ -1923,7 +1923,7 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
|
|
|
1923
1923
|
</div>
|
|
1924
1924
|
${k}
|
|
1925
1925
|
<div class="subtask-detail-body"></div>
|
|
1926
|
-
`,s&&o.classList.add(`subtask-expanded`);let A=o.querySelector(`.subtask-detail-body`);o._renderNodes=()=>{if(!A)return;let e=[];T&&e.push(`<div class="subtask-detail-desc"><span class="subtask-detail-label">${r(`chatMsg.subtaskDescLabel`)}</span>${P(T)}</div>`);let n=E&&E.result?String(E.result).trim():``;n&&e.push(`<div class="subtask-detail-result"><span class="subtask-detail-label">${r(`chatMsg.subtaskResultLabel`)}</span>${P(n)}</div>`);let i=d.filter(e=>e.subtaskIndex===t&&e.nodeType!==`subtask`),a=BC(i,o._nodeFilter),s=``;i.length>0&&a.length===0?s=`<div class="subtask-node-empty">${P(r(`chatMsg.subtaskFilterEmpty`))}</div>`:a.length>0&&(s=a.map(e=>{let t=e.nodeType===`tool_exec`?`🔧`:e.nodeType===`api_call`?`📡`:e.nodeType===`reflection`?`🎯`:e.nodeType===`preselect`?`🔍`:`○`,n=e.status===`success`?`✓`:e.status===`failed`?`✗`:h?`<span class="subtask-node-spinner"></span>`:`○`,i=e.status===`success`?`done`:e.status===`failed`?`failed`:`processing`,a=e.duration?
|
|
1926
|
+
`,s&&o.classList.add(`subtask-expanded`);let A=o.querySelector(`.subtask-detail-body`);o._renderNodes=()=>{if(!A)return;let e=[];T&&e.push(`<div class="subtask-detail-desc"><span class="subtask-detail-label">${r(`chatMsg.subtaskDescLabel`)}</span>${P(T)}</div>`);let n=E&&E.result?String(E.result).trim():``;n&&e.push(`<div class="subtask-detail-result"><span class="subtask-detail-label">${r(`chatMsg.subtaskResultLabel`)}</span>${P(n)}</div>`);let i=d.filter(e=>e.subtaskIndex===t&&e.nodeType!==`subtask`),a=BC(i,o._nodeFilter),s=``;i.length>0&&a.length===0?s=`<div class="subtask-node-empty">${P(r(`chatMsg.subtaskFilterEmpty`))}</div>`:a.length>0&&(s=a.map(e=>{let t=e.nodeType===`tool_exec`?`🔧`:e.nodeType===`api_call`?`📡`:e.nodeType===`reflection`?`🎯`:e.nodeType===`preselect`?`🔍`:`○`,n=e.status===`success`?`✓`:e.status===`failed`?`✗`:h?`<span class="subtask-node-spinner"></span>`:`○`,i=e.status===`success`?`done`:e.status===`failed`?`failed`:`processing`,a=e.duration?Bt(e.duration):``,o=P(e.nodeName||r(`chatMsg.unknownNode`)),s=``;if(e.nodeType===`tool_exec`){let t=Lf(e);t&&(s=`<span class="subtask-node-cmd" title="${I(t)}">${P(t)}</span>`)}return`<div class="subtask-node ${i}">
|
|
1927
1927
|
<span class="subtask-node-icon">${t}</span>
|
|
1928
1928
|
<span class="subtask-node-status">${n}</span>
|
|
1929
1929
|
<span class="subtask-node-name">${o}${s}</span>
|
|
@@ -1942,9 +1942,9 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
|
|
|
1942
1942
|
</svg>
|
|
1943
1943
|
</button>
|
|
1944
1944
|
`;let n=t.querySelector(`.streaming-stop-btn`);n&&n.addEventListener(`click`,e=>{e.stopPropagation(),pC(n)}),e.appendChild(t)}}}else if(C(QS(x)),qS(Date.now()),HS()&&HS().length>0){let e=C().querySelector(`.message-content`);HS().forEach(t=>{let n=dC(t);e.insertBefore(n,e.firstChild)}),US(null)}return C().dataset.callId=S,v=``,VS(x,``),GS(Date.now()),YS(``),wS(C()),!1}if(e.type===`STREAM_CHUNK`)return C()&&(v+=e.delta,VS(x,v),C().isConnected&&oC(C(),v)),!1;if(e.type===`STREAM_TOOL_CALL`)return C()||(C(QS(x)),qS(Date.now())),C()&&e.toolCalls?.length>0&&sC(C(),e.toolCalls),!1;if(e.type===`STREAM_TOOL_RESULT`)return C()&&e.result&&uC(e.result,C()),!1;if(e.type===`AGENT_STREAM`){if(C()&&e.execId){let t=w[e.execId];if(!t){let n=C();t={element:lC(e.toolCallId?n.querySelector(`.tool-call-item[data-tool-call-id="${e.toolCallId}"]`):null,n.querySelector(`.stream-content`)),stdout:``,stderr:``},w[e.execId]=t,sn()}let n=t.element.querySelector(`code`);n&&(e.streamType===`stderr`?t.stderr+=e.data:t.stdout+=e.data,n.textContent=t.stdout+(t.stderr?`
|
|
1945
|
-
`+t.stderr:``),n.parentElement.scrollTop=n.parentElement.scrollHeight)}return!1}if(e.type===`AGENT_STREAM_DONE`){if(e.execId){let t=w[e.execId];t&&e.exitCode!==0&&t.element.classList.add(`agent-stream-error`)}return!1}if(e.type===`STREAM_DONE`){if(C()){let e=C().querySelector(`.stream-status`);e&&(b?.enabled?e.textContent=r(`chatMsg.reflectionInProgress`):e.textContent=``)}return!1}if(e.type===`API_COMPLETE`){let t=e.content&&String(e.content).trim()?e.content:r(`chatMsg.emptyModelReply`);C()&&fC(C(),t,e.executionLog||[],e.reflectionScore,e.reasoningContent,e.wasRevised);let n=C(),i=!!n,a=n?n.dataset.htmlContent||n.outerHTML:null,s=n?n.isConnected:!1,c=n?n.dataset.messageId:null;return D(),console.log(`[callApi API_COMPLETE] wasStreamed:`,i,`| message.executionLog entries:`,e.executionLog?.length||0,`| local executionLog entries:`,d.length,`| agent_file entries:`,(e.executionLog||d)?.filter(e=>e.nodeType===`tool_exec`&&e.action?.name===`agent_file`).length||0),o({content:t,executionLog:e.executionLog||d,reflectionScore:e.reflectionScore,wasStreamed:i,wasRevised:e.wasRevised,streamingHtml:a,streamingConnected:s,streamingMsgId:c,budgetEnded:e.budgetEnded===!0}),!1}else if(e.type===`API_ERROR`){let t=C();return t&&t.isConnected&&t.remove(),D(),l({message:e.error,executionLog:e.executionLog||d}),!1}return!1};if(chrome.runtime.onMessage.addListener(ne),E.removeListener=()=>{chrome.runtime.onMessage.removeListener(ne)},s)a.debug(`[SidePanel] send RESUME_REACT message,sessionId:`,x,`userGuidance:`,c?`"${c.substring(0,50)}..."`:`( no )`,`timeout:`,y),chrome.runtime.sendMessage({type:`RESUME_REACT`,sessionId:x,callId:S,userGuidance:c||``});else{let r=e.some(e=>Array.isArray(e.content)&&e.content.some(e=>e&&e.type===`image_url`));a.debug(`[SidePanel] send CALL_API message,useTools:`,n,`tabId:`,N.currentTabId,`sessionId:`,x,`apiParams:`,i,`timeout:`,y),chrome.runtime.sendMessage({type:`CALL_API`,sessionId:x,messages:e,model:t,useTools:n,tabId:N.currentTabId,apiParams:i,agentId:p,agentToolIds:m,agentSkillIds:h,forcedMcpServerIds:Array.isArray(u)&&u.length>0?u:null,agentMcpExcludedServerIds:g??null,callId:S,imageApiBase:N.enableImageInput&&r&&N.imageApiBase||``,imageApiKey:N.enableImageInput&&r&&N.imageApiKey||``})}})}function bw(e){try{let t=e.dataset.rawContent||``,n=e.dataset.textContent_||``;if(!n&&!t){L(r(`chatMsg.cannotGetMessageContent`),`error`);return}let i=[];if(t.startsWith(`[`))try{let e=JSON.parse(t);if(Array.isArray(e)){let t=e.filter(e=>e.type===`image_url`);for(let e of t){let t=e.image_url.original_url||e.image_url.url;i.push({originalUrl:t,compressedUrl:e.image_url.url,width:e.image_url.width,height:e.image_url.height})}}}catch{}i.length>0&&(N.attachedImages=i,Bp());let o=[];if(e.dataset.attachedFiles)try{let t=JSON.parse(e.dataset.attachedFiles);for(let e of t)o.push({name:e.name,size:e.size,type:e.type,text:e.text||``,status:e.status||`done`,agentPath:e.agentPath||``})}catch{}o.length>0&&(N.attachedFiles=o,M(()=>Promise.resolve().then(()=>cm).then(e=>{e.renderFilePreviews()}),void 0));let s=n.match(/^\[网页上下文\]\n标题: (.+)\nURL: (.+)\ntabId: (\d+)\n/);if(s){Zb(),N.selectedPage={id:parseInt(s[3]),title:s[1],url:s[2],favIconUrl:``};let e=document.getElementById(`pageIndicator`),t=document.getElementById(`pageIndicatorName`);if(e&&t){let n=s[1],r=s[2];n&&n!==`无标题`&&r?t.textContent=`${n} · ${r}`:t.textContent=n||r,e.style.display=`flex`}}let c=n.match(/\[知识库检索结果\](引用: ([^)]+))/);if(c){let e=c[1].split(`、`).map(e=>e.trim()).filter(Boolean);e.length>0&&(Ib(),N.knowledgeRefs=e.map(e=>({id:``,name:e})),Lb(),Vb().then(e=>{if(e&&e.ok){let t=new Map((e.collections||[]).map(e=>[e.name,e]));N.knowledgeRefs=N.knowledgeRefs.map(e=>{if(e.id)return e;let n=t.get(e.name);return{id:n?.id||``,name:e.name,enabled:n?n.enabled!==!1:!0}}),Lb()}}).catch(()=>{}))}let l=Array.from(new Set([...n.matchAll(/\[(?:已选技能|Selected skill):\s*([^\n\]]+)\]/g)].map(e=>e[1].split(` - `)[0].trim()).filter(Boolean)));l.length>0&&(nT(),N.selectedSkills=l.map(e=>({name:e,description:``,type:`agent`})),rT());let u=Array.from(new Set([...n.matchAll(/\[(?:已选MCP服务|Selected MCP service):\s*([^\n\]]+)\]/g)].map(e=>e[1].split(` - `)[0].trim()).filter(Boolean)));u.length>0&&(hT(),N.selectedMcpServices=u.map(e=>({serverId:``,serverName:e,toolCount:0})),_T(),chrome.storage.local.get([`mcpTools`],e=>{let t=e.mcpTools||[];u.forEach(e=>{let n=N.selectedMcpServices.find(t=>t.serverName===e);if(!n||n.serverId)return;let r=t.find(t=>(t.serverName||``)===e)||t.find(t=>(t.serverName||``).startsWith(e));r&&(n.serverId=r.serverId||``,n.toolCount=t.filter(e=>e.serverId===r.serverId).length)}),_T()}));let d=n;s&&(d=d.replace(/^\[网页上下文\]\n标题: .+\nURL: .+\ntabId: \d+\n/,``)),c&&(d=d.replace(/\[知识库检索结果\][^\n]*\n[\s\S]*?\[\/知识库检索结果\]\n\n?/,``)),u.length>0&&(d=nw(d)),l.length>0&&(d=tw(d));let f=N.quotedContextText,p=N.selectedContextText;N.quotedContextText=``,N.selectedContextText=``;let m=d.match(/^\[引用内容(?:摘要)?\]\n([\s\S]+?)\n\n\[用户问题\]\n([\s\S]*)$/),h=d.match(/^\[选中内容(?:摘要)?\]\n([\s\S]+?)\n\n\[用户问题\]\n([\s\S]*)$/),g=m||h,_=d;if(g){let e=m?`quoted`:`selected`,t=g[1].trim(),n=g[2].trim();if(o.length>0){let e=n.search(/\n\n\[(?:工作目录)?文件(?:内容)?:/);e!==-1&&(n=n.substring(0,e).trim())}let i=document.getElementById(`selectionIndicator`),a=document.getElementById(`selectionText`);if(i&&a){let n;n=t.length>100?t.substring(0,100)+`...`:t.length>50?t.substring(0,50)+`...`:t,e===`quoted`?(N.quotedContextText=t,N.selectedContextText=p,a.textContent=r(`chatMsg.quotedContextLabel`,{text:n})):(N.selectedContextText=t,N.quotedContextText=f,a.textContent=r(`chatMsg.selectedContextLabel`,{text:n})),i.classList.add(`show`)}_=n}else if(N.quotedContextText=f,N.selectedContextText=p,o.length>0){let e=_.search(/\n\n\[(?:工作目录)?文件(?:内容)?:/);e!==-1&&(_=_.substring(0,e).trim())}let v=document.getElementById(`userInput`);v.value=_,
|
|
1945
|
+
`+t.stderr:``),n.parentElement.scrollTop=n.parentElement.scrollHeight)}return!1}if(e.type===`AGENT_STREAM_DONE`){if(e.execId){let t=w[e.execId];t&&e.exitCode!==0&&t.element.classList.add(`agent-stream-error`)}return!1}if(e.type===`STREAM_DONE`){if(C()){let e=C().querySelector(`.stream-status`);e&&(b?.enabled?e.textContent=r(`chatMsg.reflectionInProgress`):e.textContent=``)}return!1}if(e.type===`API_COMPLETE`){let t=e.content&&String(e.content).trim()?e.content:r(`chatMsg.emptyModelReply`);C()&&fC(C(),t,e.executionLog||[],e.reflectionScore,e.reasoningContent,e.wasRevised);let n=C(),i=!!n,a=n?n.dataset.htmlContent||n.outerHTML:null,s=n?n.isConnected:!1,c=n?n.dataset.messageId:null;return D(),console.log(`[callApi API_COMPLETE] wasStreamed:`,i,`| message.executionLog entries:`,e.executionLog?.length||0,`| local executionLog entries:`,d.length,`| agent_file entries:`,(e.executionLog||d)?.filter(e=>e.nodeType===`tool_exec`&&e.action?.name===`agent_file`).length||0),o({content:t,executionLog:e.executionLog||d,reflectionScore:e.reflectionScore,wasStreamed:i,wasRevised:e.wasRevised,streamingHtml:a,streamingConnected:s,streamingMsgId:c,budgetEnded:e.budgetEnded===!0}),!1}else if(e.type===`API_ERROR`){let t=C();return t&&t.isConnected&&t.remove(),D(),l({message:e.error,executionLog:e.executionLog||d}),!1}return!1};if(chrome.runtime.onMessage.addListener(ne),E.removeListener=()=>{chrome.runtime.onMessage.removeListener(ne)},s)a.debug(`[SidePanel] send RESUME_REACT message,sessionId:`,x,`userGuidance:`,c?`"${c.substring(0,50)}..."`:`( no )`,`timeout:`,y),chrome.runtime.sendMessage({type:`RESUME_REACT`,sessionId:x,callId:S,userGuidance:c||``});else{let r=e.some(e=>Array.isArray(e.content)&&e.content.some(e=>e&&e.type===`image_url`));a.debug(`[SidePanel] send CALL_API message,useTools:`,n,`tabId:`,N.currentTabId,`sessionId:`,x,`apiParams:`,i,`timeout:`,y),chrome.runtime.sendMessage({type:`CALL_API`,sessionId:x,messages:e,model:t,useTools:n,tabId:N.currentTabId,apiParams:i,agentId:p,agentToolIds:m,agentSkillIds:h,forcedMcpServerIds:Array.isArray(u)&&u.length>0?u:null,agentMcpExcludedServerIds:g??null,callId:S,imageApiBase:N.enableImageInput&&r&&N.imageApiBase||``,imageApiKey:N.enableImageInput&&r&&N.imageApiKey||``})}})}function bw(e){try{let t=e.dataset.rawContent||``,n=e.dataset.textContent_||``;if(!n&&!t){L(r(`chatMsg.cannotGetMessageContent`),`error`);return}let i=[];if(t.startsWith(`[`))try{let e=JSON.parse(t);if(Array.isArray(e)){let t=e.filter(e=>e.type===`image_url`);for(let e of t){let t=e.image_url.original_url||e.image_url.url;i.push({originalUrl:t,compressedUrl:e.image_url.url,width:e.image_url.width,height:e.image_url.height})}}}catch{}i.length>0&&(N.attachedImages=i,Bp());let o=[];if(e.dataset.attachedFiles)try{let t=JSON.parse(e.dataset.attachedFiles);for(let e of t)o.push({name:e.name,size:e.size,type:e.type,text:e.text||``,status:e.status||`done`,agentPath:e.agentPath||``})}catch{}o.length>0&&(N.attachedFiles=o,M(()=>Promise.resolve().then(()=>cm).then(e=>{e.renderFilePreviews()}),void 0));let s=n.match(/^\[网页上下文\]\n标题: (.+)\nURL: (.+)\ntabId: (\d+)\n/);if(s){Zb(),N.selectedPage={id:parseInt(s[3]),title:s[1],url:s[2],favIconUrl:``};let e=document.getElementById(`pageIndicator`),t=document.getElementById(`pageIndicatorName`);if(e&&t){let n=s[1],r=s[2];n&&n!==`无标题`&&r?t.textContent=`${n} · ${r}`:t.textContent=n||r,e.style.display=`flex`}}let c=n.match(/\[知识库检索结果\](引用: ([^)]+))/);if(c){let e=c[1].split(`、`).map(e=>e.trim()).filter(Boolean);e.length>0&&(Ib(),N.knowledgeRefs=e.map(e=>({id:``,name:e})),Lb(),Vb().then(e=>{if(e&&e.ok){let t=new Map((e.collections||[]).map(e=>[e.name,e]));N.knowledgeRefs=N.knowledgeRefs.map(e=>{if(e.id)return e;let n=t.get(e.name);return{id:n?.id||``,name:e.name,enabled:n?n.enabled!==!1:!0}}),Lb()}}).catch(()=>{}))}let l=Array.from(new Set([...n.matchAll(/\[(?:已选技能|Selected skill):\s*([^\n\]]+)\]/g)].map(e=>e[1].split(` - `)[0].trim()).filter(Boolean)));l.length>0&&(nT(),N.selectedSkills=l.map(e=>({name:e,description:``,type:`agent`})),rT());let u=Array.from(new Set([...n.matchAll(/\[(?:已选MCP服务|Selected MCP service):\s*([^\n\]]+)\]/g)].map(e=>e[1].split(` - `)[0].trim()).filter(Boolean)));u.length>0&&(hT(),N.selectedMcpServices=u.map(e=>({serverId:``,serverName:e,toolCount:0})),_T(),chrome.storage.local.get([`mcpTools`],e=>{let t=e.mcpTools||[];u.forEach(e=>{let n=N.selectedMcpServices.find(t=>t.serverName===e);if(!n||n.serverId)return;let r=t.find(t=>(t.serverName||``)===e)||t.find(t=>(t.serverName||``).startsWith(e));r&&(n.serverId=r.serverId||``,n.toolCount=t.filter(e=>e.serverId===r.serverId).length)}),_T()}));let d=n;s&&(d=d.replace(/^\[网页上下文\]\n标题: .+\nURL: .+\ntabId: \d+\n/,``)),c&&(d=d.replace(/\[知识库检索结果\][^\n]*\n[\s\S]*?\[\/知识库检索结果\]\n\n?/,``)),u.length>0&&(d=nw(d)),l.length>0&&(d=tw(d));let f=N.quotedContextText,p=N.selectedContextText;N.quotedContextText=``,N.selectedContextText=``;let m=d.match(/^\[引用内容(?:摘要)?\]\n([\s\S]+?)\n\n\[用户问题\]\n([\s\S]*)$/),h=d.match(/^\[选中内容(?:摘要)?\]\n([\s\S]+?)\n\n\[用户问题\]\n([\s\S]*)$/),g=m||h,_=d;if(g){let e=m?`quoted`:`selected`,t=g[1].trim(),n=g[2].trim();if(o.length>0){let e=n.search(/\n\n\[(?:工作目录)?文件(?:内容)?:/);e!==-1&&(n=n.substring(0,e).trim())}let i=document.getElementById(`selectionIndicator`),a=document.getElementById(`selectionText`);if(i&&a){let n;n=t.length>100?t.substring(0,100)+`...`:t.length>50?t.substring(0,50)+`...`:t,e===`quoted`?(N.quotedContextText=t,N.selectedContextText=p,a.textContent=r(`chatMsg.quotedContextLabel`,{text:n})):(N.selectedContextText=t,N.quotedContextText=f,a.textContent=r(`chatMsg.selectedContextLabel`,{text:n})),i.classList.add(`show`)}_=n}else if(N.quotedContextText=f,N.selectedContextText=p,o.length>0){let e=_.search(/\n\n\[(?:工作目录)?文件(?:内容)?:/);e!==-1&&(_=_.substring(0,e).trim())}let v=document.getElementById(`userInput`);v.value=_,Ht(),v.focus(),v.selectionStart=v.selectionEnd=v.value.length,a.debug(`[SidePanel] loadedmessagecontent to input box,waitingafter user editsend`)}catch(e){a.error(`[SidePanel] editmessage failed:`,e),L(r(`chatMsg.editFailed`,{message:e.message}),`error`)}}n(`zh`,{promptMgr:{promptsTabCount:`提示词 ({count})`,skillsTabCount:`技能 ({count})`,mcpTabCount:`MCP ({count})`,noMatchPrompt:`暂无匹配的提示词`,mergedHeaderHint:`方向键切换 · Enter发送/选择 · Ctrl+Enter带入/选中并关闭 · Esc取消`,noMatchResult:`暂无匹配结果`,requestFailed:`❌ 请求失败:{message}`,emptyPromptHint:`暂无提示词,请添加`,menuDisplayTitle:`菜单显示`,codeAndContentRequired:`请填写编码和内容`,codeExists:`编码已存在`,saveChanges:`保存修改`,confirmDeletePrompt:`确定要删除提示词 "/{code}" 吗?`}}),n(`en`,{promptMgr:{promptsTabCount:`Prompts ({count})`,skillsTabCount:`Skills ({count})`,mcpTabCount:`MCP ({count})`,noMatchPrompt:`No matching prompts`,mergedHeaderHint:`Arrow keys to switch · Enter to send/select · Ctrl+Enter to insert/select & close · Esc to cancel`,noMatchResult:`No matching results`,requestFailed:`❌ Request failed: {message}`,emptyPromptHint:`No prompts yet, please add one`,menuDisplayTitle:`Show in menu`,codeAndContentRequired:`Please fill in both code and content`,codeExists:`Code already exists`,saveChanges:`Save changes`,confirmDeletePrompt:`Are you sure you want to delete prompt "/{code}"?`}});var xw=`<svg viewBox="0 0 1024 1024" width="12" height="12" fill="currentColor"><path d="M674.56 231.552l101.568 56.96-56.896-101.632 56.96-101.568-101.632 56.896-101.632-56.896 56.96 101.568-56.896 101.632 101.568-56.96zM186.944 629.76l-101.504-56.896 56.832 101.632-56.832 101.568 101.504-56.96 101.632 56.96-56.896-101.568 56.896-101.568-101.568 56.832zM85.44 85.312l56.832 101.568-56.832 101.632 101.504-56.96 101.632 56.96L231.68 186.88l56.896-101.568-101.568 56.896-101.568-56.896z m351.872 438.016l-99.2-99.136L424.32 337.984l99.072 99.264-86.08 86.144m-41.856-223.04L300.352 395.392a40.448 40.448 0 0 0 0 57.28l474.24 474.112a40.448 40.448 0 0 0 57.344 0l94.912-95.04a40.448 40.448 0 0 0 0-57.344L452.736 300.288a40.448 40.448 0 0 0-57.28 0z"/></svg>`;function Sw(){a.debug(`[SidePanel] clear selectedcontenttext `),N.selectedContextText=``,N.quotedContextText=``;let e=document.getElementById(`selectionIndicator`),t=document.getElementById(`userInput`);if(e&&(e.classList.remove(`show`),a.debug(`[SidePanel] hiddenselected contentprompt`)),typeof window.hideFloatingMenu==`function`&&window.hideFloatingMenu(),t&&t.value.startsWith(`[选中内容]`)){let e=t.value.split(`
|
|
1946
1946
|
`),n=0;for(let t=0;t<e.length;t++)if(e[t].startsWith(`[用户问题]`)){n=t;break}n>0&&(t.value=e.slice(n).join(`
|
|
1947
|
-
`),t.dispatchEvent(new Event(`input`)),a.debug(`[SidePanel] removedinput box selected content before suffix`))}N.lastSelectedText=``,N.currentSelectionRange=null}function Cw(){let e=document.getElementById(`promptManageList`).querySelectorAll(`.prompt-manage-item`);e.forEach(t=>{t.addEventListener(`dragstart`,e=>{N.draggedItemIndex=parseInt(t.dataset.index),t.classList.add(`dragging`),e.dataTransfer.effectAllowed=`move`,e.dataTransfer.setData(`text/plain`,N.draggedItemIndex)}),t.addEventListener(`dragend`,()=>{t.classList.remove(`dragging`),e.forEach(e=>e.classList.remove(`drag-over`)),N.draggedItemIndex=null}),t.addEventListener(`dragover`,e=>{e.preventDefault(),e.dataTransfer.dropEffect=`move`,t.classList.add(`drag-over`)}),t.addEventListener(`dragleave`,()=>{t.classList.remove(`drag-over`)}),t.addEventListener(`drop`,e=>{e.stopPropagation(),e.preventDefault();let n=parseInt(t.dataset.index);if(N.draggedItemIndex!==null&&N.draggedItemIndex!==n){let e=N.customPrompts[N.draggedItemIndex];N.customPrompts.splice(N.draggedItemIndex,1),N.customPrompts.splice(n,0,e),chrome.storage.local.set({customPrompts:N.customPrompts}),Iw()}t.classList.remove(`drag-over`)})})}function ww(){let e=document.querySelector(`#promptDropdown .prompt-dropdown-header`);if(!e||e.querySelector(`.prompt-manage-btn`))return;let t=document.createElement(`button`);t.className=`prompt-manage-btn`,t.title=r(`promptManager.title`),t.style.fontSize=`13px`,t.innerHTML=`✚`,t.addEventListener(`click`,e=>{e.stopPropagation(),Pw()}),e.appendChild(t)}async function Tw(e=``,t=null){let n=document.getElementById(`promptSelector`),r=document.getElementById(`promptDropdown`);
|
|
1947
|
+
`),t.dispatchEvent(new Event(`input`)),a.debug(`[SidePanel] removedinput box selected content before suffix`))}N.lastSelectedText=``,N.currentSelectionRange=null}function Cw(){let e=document.getElementById(`promptManageList`).querySelectorAll(`.prompt-manage-item`);e.forEach(t=>{t.addEventListener(`dragstart`,e=>{N.draggedItemIndex=parseInt(t.dataset.index),t.classList.add(`dragging`),e.dataTransfer.effectAllowed=`move`,e.dataTransfer.setData(`text/plain`,N.draggedItemIndex)}),t.addEventListener(`dragend`,()=>{t.classList.remove(`dragging`),e.forEach(e=>e.classList.remove(`drag-over`)),N.draggedItemIndex=null}),t.addEventListener(`dragover`,e=>{e.preventDefault(),e.dataTransfer.dropEffect=`move`,t.classList.add(`drag-over`)}),t.addEventListener(`dragleave`,()=>{t.classList.remove(`drag-over`)}),t.addEventListener(`drop`,e=>{e.stopPropagation(),e.preventDefault();let n=parseInt(t.dataset.index);if(N.draggedItemIndex!==null&&N.draggedItemIndex!==n){let e=N.customPrompts[N.draggedItemIndex];N.customPrompts.splice(N.draggedItemIndex,1),N.customPrompts.splice(n,0,e),chrome.storage.local.set({customPrompts:N.customPrompts}),Iw()}t.classList.remove(`drag-over`)})})}function ww(){let e=document.querySelector(`#promptDropdown .prompt-dropdown-header`);if(!e||e.querySelector(`.prompt-manage-btn`))return;let t=document.createElement(`button`);t.className=`prompt-manage-btn`,t.title=r(`promptManager.title`),t.style.fontSize=`13px`,t.innerHTML=`✚`,t.addEventListener(`click`,e=>{e.stopPropagation(),Pw()}),e.appendChild(t)}async function Tw(e=``,t=null){let n=document.getElementById(`promptSelector`),r=document.getElementById(`promptDropdown`);Et(),n.style.display=`block`,r.classList.add(`show`);let i=document.getElementById(`skillsTab`),a=document.getElementById(`mcpTab`),o=i?await Yw():!1,s=a?await uT():!1;if(i&&(i.style.display=o?`block`:`none`),a&&(a.style.display=s?`block`:`none`),Dw(o,s),e)await Aw(e);else{let n=t||N.lastActiveDropdownTab||`prompts`,r=document.querySelector(`#promptDropdownTabs .prompt-tab[data-tab="${n}"]`),i=`prompts`;if(r&&r.style.display!==`none`)i=n;else{let e=document.querySelectorAll(`#promptDropdownTabs .prompt-tab`);for(let t of e)if(t.style.display!==`none`){i=t.dataset.tab;break}}await oT(i),kw(e)}}function Ew(){let e=document.getElementById(`promptSelector`),t=document.getElementById(`promptDropdown`);e.style.display=`none`,t.classList.remove(`show`),N.selectedPromptIndex=-1,N.showMergedList=!1;let n=document.getElementById(`promptDropdownTabs`);n&&n.classList.remove(`merged-mode`)}async function Dw(e,t){try{let n=N.customPrompts.length,i=document.querySelector(`#promptDropdownTabs .prompt-tab[data-tab="prompts"]`);if(i&&(i.textContent=r(`promptMgr.promptsTabCount`,{count:n})),e){let e=await Zw(),t=document.getElementById(`skillsTab`);t&&(t.textContent=r(`promptMgr.skillsTabCount`,{count:e.length}))}if(t){let e=await dT(),t=document.getElementById(`mcpTab`);t&&(t.textContent=r(`promptMgr.mcpTabCount`,{count:e.length}))}}catch{}}function Ow(e=``){e?Aw(e):kw(e)}function kw(e=``){let t=document.getElementById(`promptList`),n=e.toLowerCase(),i=N.customPrompts.filter(t=>e?t.code.toLowerCase().includes(n)||t.content.toLowerCase().includes(n):!0);if(i.length===0){t.innerHTML=`<div class="prompt-empty">${r(`promptMgr.noMatchPrompt`)}</div>`,N.selectedPromptIndex=-1;return}N.selectedPromptIndex=0,t.innerHTML=i.map((e,t)=>`
|
|
1948
1948
|
<div class="prompt-item ${t===N.selectedPromptIndex?`selected`:``}" data-index="${t}" data-code="${e.code}">
|
|
1949
1949
|
<span class="prompt-item-index">${t+1}</span>
|
|
1950
1950
|
<span class="prompt-item-icon">${xw}</span>
|
|
@@ -1973,9 +1973,9 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
|
|
|
1973
1973
|
`){e=t;break}s=e===-1?i.substring(0,o).trimEnd():i.substring(0,e+1).trimEnd()}r.value=s+(s&&!s.endsWith(`
|
|
1974
1974
|
`)?`
|
|
1975
1975
|
|
|
1976
|
-
`:``)+n.content,r.focus(),r.selectionStart=r.selectionEnd=r.value.length,Ew(),
|
|
1976
|
+
`:``)+n.content,r.focus(),r.selectionStart=r.selectionEnd=r.value.length,Ew(),Ht(),a.debug(`[SidePanel] trackaddpromptword to input box:`,n.code,n.content)}async function Nw(e){let t=N.customPrompts.find(t=>t.code===e);if(!t)return;if(N.isGenerating){a.debug(`[SidePanel] generating,please wait...`);return}let n=document.getElementById(`userInput`)?.value||``,i={quotedContextText:N.quotedContextText||``,selectedContextText:N.selectedContextText||``,selectedSkills:N.selectedSkills.slice(),selectedMcpServices:N.selectedMcpServices.slice(),knowledgeRefs:N.knowledgeRefs.slice(),selectedPage:N.selectedPage,attachedImages:N.attachedImages.slice(),attachedFiles:N.attachedFiles.slice()};await Xc({state:N,getRatio:()=>vE().usage?.ratio??0,compact:DE}),Ew();let o=document.getElementById(`chatContainer`).querySelector(`.welcome-message`);o&&o.remove();let s=t.content,c=i.selectedContextText&&i.selectedContextText.trim(),l=i.quotedContextText&&i.quotedContextText.trim(),u=[];if(l){let e=i.quotedContextText.trim(),{compressed:n,wasCompressed:r}=k(e);s=`[引用内容${r?`摘要`:``}]\n${n}\n\n[用户问题]\n${t.content}`,ew(`quoted`,e,!1),u.push({type:`quoted`,text:e}),N.quotedContextText===i.quotedContextText&&(N.quotedContextText=``)}else if(c){let e=i.selectedContextText.trim(),{compressed:n,wasCompressed:r}=k(e);s=`[选中内容${r?`摘要`:``}]\n${n}\n\n[用户问题]\n${t.content}`,ew(`selected`,e,!1),u.push({type:`selected`,text:e}),N.selectedContextText===i.selectedContextText&&(N.selectedContextText=``)}let d=i.selectedSkills,f=await lT(d);if(f){s=f+s;for(let e of d)ew(`skill`,r(`contextBubble.bubbleSkill`,{name:e.name,desc:e.description?`:`+e.description:``}),!1),u.push({type:`skill`,name:e.name,description:e.description||``});let e=new Set(d),t=N.selectedSkills.filter(t=>!e.has(t));t.length!==N.selectedSkills.length&&(N.selectedSkills=t,N.selectedSkillIndex=-1,rT(),iT())}let p=null,m=i.selectedMcpServices,h=gT(m);if(h){let e=m.map(e=>e.serverId).filter(Boolean);p=e.length>0?e:null,s=h+s;for(let e of m)ew(`mcp`,r(`contextBubble.bubbleMcp`,{name:e.serverName}),!1),u.push({type:`mcp`,serverName:e.serverName,serverId:e.serverId||``});let t=new Set(m),n=N.selectedMcpServices.filter(e=>!t.has(e));n.length!==N.selectedMcpServices.length&&(N.selectedMcpServices=n,N.selectedMcpServiceIndex=-1,_T(),vT())}let g=i.knowledgeRefs;if(g.length>0){let e=ew(`knowledge`,r(`contextBubble.bubbleKnowledgeSearching`),!1),n=null;try{n=await PC(t.content,g)}catch(e){a.warn(`[SidePanel] knowledge search failed:`,e)}e&&e.parentNode&&e.remove(),n&&(s=n.text+s,FC(n.refs,n.failed===!0),u.push({type:`knowledge`,refs:n.refs,failed:n.failed||void 0}));let i=new Set(g),o=N.knowledgeRefs.filter(e=>!i.has(e));o.length!==N.knowledgeRefs.length&&(N.knowledgeRefs=o,Nb(),Lb())}let v=i.selectedPage;v&&(s=`[网页上下文]\n标题: ${v.title}\nURL: ${v.url}\ntabId: ${v.id}\n`+s,ew(`page`,r(`contextBubble.bubblePage`,{title:v.title,url:v.url}),!1),u.push({type:`page`,title:v.title,url:v.url}),N.selectedPage===v&&Zb()),(c||l)&&(!N.quotedContextText&&!N.selectedContextText?Sw():xC());let y=i.attachedFiles,b=(i.attachedImages||[]).slice();if(y.length>0){let e=Am(y);e&&(s+=e),y.forEach(e=>{e.status===`done`&&u.push({type:`file`,name:e.name,size:e.size,fileType:e.type})})}let x=null;if(y.length>0||b.length>0)try{x=await Ie(N.activeSessionId,y,b)}catch(e){a.warn(`[Prompt] save doc image snapshot failed:`,e.message)}let S=ve(x?.chatStart,x?.chatCount);S&&(s+=S);let C=Vp(s,b),{messageId:w,timestamp:T}=iw(`user`,Vp(t.content,b),!0,[],null,!1,s,null,y);N.messageHistory.push({role:`user`,content:C,messageId:w,timestamp:T,contextBubbles:u}),OC(),qn(t.content);let E=document.getElementById(`userInput`);E.value===n&&(E.value=``,E.style.height=`auto`),N.isGenerating=!0;let D=uw(),O=N.activeSessionId,A=N.enableImageInput&&b.length>0&&N.imageModelName||N.currentModel;if(b.length>0){let e=new Set(b),t=N.attachedImages.filter(t=>!e.has(t));t.length!==N.attachedImages.length&&(N.attachedImages=t,Bp())}if(y.length>0){let e=new Set(y),t=N.attachedFiles.filter(t=>!e.has(t));if(t.length!==N.attachedFiles.length){for(let t of N.attachedFiles)e.has(t)&&t.dataUrl&&URL.revokeObjectURL(t.dataUrl);N.attachedFiles=t,km()}}try{await zt(),a.debug(`[SidePanel] sendmessagedebuginfo:`),a.debug(` - isolateChat:`,N.isolateChat),a.debug(` - chatConfig:`,N.chatConfig),a.debug(` - messageHistory.length:`,N.messageHistory.length);let e=[{role:`system`,content:await Kt(null,{sessionId:O})}];if(N.isolateChat){let t=_(A,N.enabledTools.length||50,0,N.customModelMap),n=Math.floor(t*.7),r=N.messageHistory[N.messageHistory.length-1],i=Hn(N.messageHistory.slice(0,-1),{isolateChat:!0,maxMemoryMessages:N.chatConfig.maxMemoryMessages,compaction:N.activeCompaction,historyBudget:n,currentMessage:r});Wn(e,i,N.activeCompaction,a),i.historySummaryText&&(e[0]={...e[0],content:e[0].content+`
|
|
1977
1977
|
|
|
1978
|
-
`+i.historySummaryText}),e=[...e,...i.messages];for(let t=0;t<e.length-1;t++)e[t]={...e[t],content:Hp(e[t].content)}}else e.push({role:`user`,content:C});let n=await
|
|
1978
|
+
`+i.historySummaryText}),e=[...e,...i.messages];for(let t=0;t<e.length-1;t++)e[t]={...e[t],content:Hp(e[t].content)}}else e.push({role:`user`,content:C});let n=await Pt(),i,o,s=!1,c=null,l=null;try{let t=await yw(e,A,N.useTools,n,{forcedMcpServerIds:p});i=t.content,o=t.executionLog||[],s=t.wasStreamed||!1,c=t.streamingHtml||null,t.streamingConnected!==void 0&&t.streamingConnected,l=t.streamingMsgId||null}catch(e){dw(D),i=r(`promptMgr.requestFailed`,{message:e.message||r(`agentConfig.unknownError`)}),o=e.executionLog||[];let{element:n,messageId:a}=iw(`assistant`,i,!0,o);throw N.messageHistory.push({role:`assistant`,content:i,executionLog:o,messageId:a}),OC(),e.message!==r(`chatMsg.errTaskStopped`)&&Ol(O,i,t.content),e}let u=null;if(!s||!c)if(dw(D),s)u=l;else{let{element:e,messageId:t}=iw(`assistant`,i,!0,o);u=t,await cn(e)}else u=l;N.messageHistory.push({role:`assistant`,content:i,executionLog:o,messageId:u}),OC(),Dl(O,t.content)}catch{}finally{jl(O),E.focus()}}function Pw(){document.getElementById(`promptManageModal`).classList.add(`show`),Iw()}function Fw(){document.getElementById(`promptManageModal`).classList.remove(`show`);let e=document.getElementById(`editPromptIndex`),t=document.getElementById(`newPromptCode`),n=document.getElementById(`newPromptContent`),i=document.getElementById(`promptManageAddBtn`);e&&(e.value=``),t&&(t.value=``),n&&(n.value=``),i&&(i.textContent=r(`promptManager.addPrompt`),i.style.background=`var(--brand-500)`)}function Iw(){let e=document.getElementById(`promptManageList`);if(N.customPrompts.length===0){e.innerHTML=`<div class="prompt-empty">${r(`promptMgr.emptyPromptHint`)}</div>`;return}e.innerHTML=N.customPrompts.map((e,t)=>`
|
|
1979
1979
|
<div class="prompt-manage-item" draggable="true" data-index="${t}">
|
|
1980
1980
|
<div class="prompt-manage-item-left">
|
|
1981
1981
|
<span class="prompt-drag-handle" title="${r(`toolbar.dragSort`)}">⋮⋮</span>
|
|
@@ -2022,7 +2022,7 @@ Please use the "{name}" MCP service to handle the following problem:
|
|
|
2022
2022
|
<span class="skill-list-item-badge">${n}</span>
|
|
2023
2023
|
${a?`<span class="skill-list-item-badge badge-disabled">${r(`skillSelector.disabledBadge`)}</span>`:``}
|
|
2024
2024
|
</div>
|
|
2025
|
-
`}).join(``),t.querySelectorAll(`.skill-list-item`).forEach(e=>{e.addEventListener(`click`,t=>{let r=e.dataset.skillName;tT(r,n),(t.ctrlKey||t.metaKey)&&Ew()})}),iT()}function $w(e){e.forEach((e,t)=>{t===N.selectedSkillIndex?(e.classList.add(`selected`),e.scrollIntoView({block:`nearest`})):e.classList.remove(`selected`)})}function eT(){let e=document.getElementById(`userInput`);if(!e)return;let t=e.value,n=t.lastIndexOf(`/`);n!==-1&&(e.value=t.substring(0,n)),e.focus(),e.selectionStart=e.selectionEnd=e.value.length,
|
|
2025
|
+
`}).join(``),t.querySelectorAll(`.skill-list-item`).forEach(e=>{e.addEventListener(`click`,t=>{let r=e.dataset.skillName;tT(r,n),(t.ctrlKey||t.metaKey)&&Ew()})}),iT()}function $w(e){e.forEach((e,t)=>{t===N.selectedSkillIndex?(e.classList.add(`selected`),e.scrollIntoView({block:`nearest`})):e.classList.remove(`selected`)})}function eT(){let e=document.getElementById(`userInput`);if(!e)return;let t=e.value,n=t.lastIndexOf(`/`);n!==-1&&(e.value=t.substring(0,n)),e.focus(),e.selectionStart=e.selectionEnd=e.value.length,Ht()}function tT(e,t,{clearTrigger:n=!0}={}){let r=t.find(t=>t.name===e);if(!r)return;let i=N.selectedSkills.findIndex(t=>t.name===e);if(i>=0?N.selectedSkills.splice(i,1):N.selectedSkills.push({name:r.name,description:r.description||``,type:r.type||`agent`,stepCount:r.stepCount||0,parameters:r.parameters||{},enabled:r.enabled!==!1}),iT(),rT(),n)eT();else{let e=document.getElementById(`userInput`);e&&(e.focus(),e.selectionStart=e.selectionEnd=e.value.length),Ht()}a.debug(`[SidePanel] skill toggled:`,r.name,`count:`,N.selectedSkills.length)}function nT(){N.selectedSkills=[],N.selectedSkillIndex=-1,rT(),iT(),a.debug(`[SidePanel] skill clearedselect`)}function rT(){let e=document.getElementById(`skillIndicator`);if(e){if(N.selectedSkills.length===0){e.style.display=`none`,e.innerHTML=``;return}e.innerHTML=N.selectedSkills.map(e=>{let t=e.enabled===!1,n=t?`${e.name} (${r(`skillSelector.manualUseSuffix`)})`:e.name,i=t?r(`skillSelector.disabledTooltip`):e.name;return`
|
|
2026
2026
|
<span class="ref-chip skill-ref-chip${t?` skill-ref-chip-manual`:``}">
|
|
2027
2027
|
<span class="ref-chip-name" title="${I(i)}">🧩 ${P(n)}</span>
|
|
2028
2028
|
<button class="ref-chip-close" data-skill-name="${I(e.name)}" title="${r(`common.delete`)}">✕</button>
|
|
@@ -2041,7 +2041,7 @@ Please use the "{name}" MCP service to handle the following problem:
|
|
|
2041
2041
|
${n?`<span class="mcp-list-item-badge mcp-badge-inactive">${r(`skillSelector.mcpInactiveBadge`)}</span>`:``}
|
|
2042
2042
|
<span class="mcp-list-item-badge">${r(`promptSelector.toolCount`,{count:e.toolCount})}</span>
|
|
2043
2043
|
</div>
|
|
2044
|
-
`}).join(``),t.querySelectorAll(`.mcp-list-item`).forEach(e=>{e.addEventListener(`click`,t=>{let r=e.dataset.serverId,i=e.dataset.serverName;mT(r,i,n),(t.ctrlKey||t.metaKey)&&Ew()})}),vT()}function pT(e){e.forEach((e,t)=>{t===N.selectedMcpServiceIndex?(e.classList.add(`selected`),e.scrollIntoView({block:`nearest`})):e.classList.remove(`selected`)})}function mT(e,t,n,{clearTrigger:r=!0}={}){let i=n?.find(t=>t.serverId===e)?.toolCount||0,o=t||e,s=N.selectedMcpServices.findIndex(e=>e.serverName===o);if(s>=0?N.selectedMcpServices.splice(s,1):N.selectedMcpServices.push({serverId:e,serverName:o,toolCount:i}),vT(),_T(),r)eT();else{let e=document.getElementById(`userInput`);e&&(e.focus(),e.selectionStart=e.selectionEnd=e.value.length),
|
|
2044
|
+
`}).join(``),t.querySelectorAll(`.mcp-list-item`).forEach(e=>{e.addEventListener(`click`,t=>{let r=e.dataset.serverId,i=e.dataset.serverName;mT(r,i,n),(t.ctrlKey||t.metaKey)&&Ew()})}),vT()}function pT(e){e.forEach((e,t)=>{t===N.selectedMcpServiceIndex?(e.classList.add(`selected`),e.scrollIntoView({block:`nearest`})):e.classList.remove(`selected`)})}function mT(e,t,n,{clearTrigger:r=!0}={}){let i=n?.find(t=>t.serverId===e)?.toolCount||0,o=t||e,s=N.selectedMcpServices.findIndex(e=>e.serverName===o);if(s>=0?N.selectedMcpServices.splice(s,1):N.selectedMcpServices.push({serverId:e,serverName:o,toolCount:i}),vT(),_T(),r)eT();else{let e=document.getElementById(`userInput`);e&&(e.focus(),e.selectionStart=e.selectionEnd=e.value.length),Ht()}a.debug(`[SidePanel] MCP service toggled:`,o,`count:`,N.selectedMcpServices.length)}function hT(){N.selectedMcpServices=[],N.selectedMcpServiceIndex=-1,_T(),vT(),a.debug(`[SidePanel] cleared MCP serviceselect`)}function gT(e){let t=e||N.selectedMcpServices||[];return t.length===0?``:t.map(e=>r(`skillSelector.selectedMcpContext`,{name:e.serverName})).join(`
|
|
2045
2045
|
`)}function _T(){let e=document.getElementById(`mcpIndicator`);if(e){if(N.selectedMcpServices.length===0){e.style.display=`none`,e.innerHTML=``;return}e.innerHTML=N.selectedMcpServices.map(e=>`
|
|
2046
2046
|
<span class="ref-chip mcp-ref-chip">
|
|
2047
2047
|
<span class="ref-chip-name" title="${I(e.serverName)}">🔌 ${P(e.serverName)}</span>
|
|
@@ -2049,7 +2049,7 @@ Please use the "{name}" MCP service to handle the following problem:
|
|
|
2049
2049
|
</span>
|
|
2050
2050
|
`).join(``),e.querySelectorAll(`.ref-chip-close`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),N.selectedMcpServices=N.selectedMcpServices.filter(t=>t.serverName!==e.dataset.serverName),_T(),vT()})}),e.style.display=`flex`}}function vT(){let e=new Set(N.selectedMcpServices.map(e=>e.serverName));document.querySelectorAll(`.mcp-list-item, .merged-mcp-item`).forEach(t=>{t.classList.toggle(`picked`,e.has(t.dataset.serverName))})}function yT(){let e=document.getElementById(`mcpIndicatorClose`);e&&e.addEventListener(`click`,hT)}function bT(){let e=document.getElementById(`promptDropdownHeader`);if(!e||e.querySelector(`.mcp-manage-btn`))return;let t=document.createElement(`button`);t.className=`mcp-manage-btn`,t.title=r(`promptSelector.mcpManageTitle`),t.style.display=`none`,t.style.fontSize=`13px`,t.innerHTML=`✚`,t.addEventListener(`click`,e=>{e.stopPropagation(),chrome.runtime.sendMessage({type:`OPEN_OPTIONS_PAGE`,hash:`toolbox`})}),e.appendChild(t)}var xT=[[`🀄`,`mahjong tile red dragon`,`symbols`,`麻将,红中`],[`🃏`,`playing card black joker`,`symbols`,``],[`🅰`,`negative squared latin capital letter a`,`symbols`,``],[`🅱`,`negative squared latin capital letter b`,`symbols`,``],[`🅾`,`negative squared latin capital letter o`,`symbols`,``],[`🅿`,`negative squared latin capital letter p`,`symbols`,``],[`🆎`,`negative squared ab`,`symbols`,``],[`🆑`,`squared cl`,`symbols`,``],[`🆒`,`squared cool`,`symbols`,``],[`🆓`,`squared free`,`symbols`,``],[`🆔`,`squared id`,`symbols`,``],[`🆕`,`squared new`,`symbols`,``],[`🆖`,`squared ng`,`symbols`,``],[`🆗`,`squared ok`,`symbols`,``],[`🆘`,`squared sos`,`symbols`,``],[`🆙`,`squared up with exclamation mark`,`symbols`,``],[`🆚`,`squared vs`,`symbols`,``],[`🇨🇩`,`regional indicator symbol letter c`,`flags`,``],[`🇬🇭`,`regional indicator symbol letter g`,`flags`,``],[`🇲🇳`,`regional indicator symbol letter m`,`flags`,``],[`🇷🇸`,`regional indicator symbol letter r`,`flags`,``],[`🈁`,`squared katakana koko`,`symbols`,``],[`🈂`,`squared katakana sa`,`symbols`,``],[`🈚`,`squared cjk unified ideograph-7121`,`symbols`,``],[`🈯`,`squared cjk unified ideograph-6307`,`symbols`,``],[`🈲`,`squared cjk unified ideograph-7981`,`symbols`,``],[`🈳`,`squared cjk unified ideograph-7a7a`,`symbols`,``],[`🈴`,`squared cjk unified ideograph-5408`,`symbols`,``],[`🈵`,`squared cjk unified ideograph-6e80`,`symbols`,``],[`🈶`,`squared cjk unified ideograph-6709`,`symbols`,``],[`🈷`,`squared cjk unified ideograph-6708`,`symbols`,``],[`🈸`,`squared cjk unified ideograph-7533`,`symbols`,``],[`🈹`,`squared cjk unified ideograph-5272`,`symbols`,``],[`🈺`,`squared cjk unified ideograph-55b6`,`symbols`,``],[`🉐`,`circled ideograph advantage`,`symbols`,``],[`🉑`,`circled ideograph accept`,`symbols`,``],[`🌀`,`cyclone`,`symbols`,`台风,龙卷风,旋风`],[`🌁`,`foggy`,`symbols`,`雾,雾霾,朦胧`],[`🌂`,`closed umbrella`,`symbols`,``],[`🌃`,`night with stars`,`symbols`,`夜晚,星空,城市`],[`🌄`,`sunrise over mountains`,`symbols`,`日出,山,早晨`],[`🌅`,`sunrise`,`symbols`,`日出,太阳,早晨`],[`🌆`,`cityscape at dusk`,`symbols`,`黄昏,傍晚,城市`],[`🌇`,`sunset over buildings`,`symbols`,`日落,黄昏`],[`🌈`,`rainbow`,`symbols`,`彩虹,雨后`],[`🌉`,`bridge at night`,`symbols`,`桥,大桥`],[`🌊`,`water wave`,`symbols`,`海浪,波浪,海`],[`🌋`,`volcano`,`symbols`,`火山,爆发`],[`🌌`,`milky way`,`symbols`,``],[`🌍`,`earth globe europe-africa`,`symbols`,``],[`🌎`,`earth globe americas`,`symbols`,`地球,美洲`],[`🌏`,`earth globe asia-australia`,`symbols`,`地球,亚洲`],[`🌐`,`globe with meridians`,`symbols`,``],[`🌑`,`new moon symbol`,`symbols`,``],[`🌒`,`waxing crescent moon symbol`,`symbols`,``],[`🌓`,`first quarter moon symbol`,`symbols`,``],[`🌔`,`waxing gibbous moon symbol`,`symbols`,``],[`🌕`,`full moon symbol`,`symbols`,``],[`🌖`,`waning gibbous moon symbol`,`symbols`,``],[`🌗`,`last quarter moon symbol`,`symbols`,``],[`🌘`,`waning crescent moon symbol`,`symbols`,``],[`🌙`,`crescent moon`,`symbols`,``],[`🌚`,`new moon with face`,`symbols`,``],[`🌛`,`first quarter moon with face`,`symbols`,``],[`🌜`,`last quarter moon with face`,`symbols`,``],[`🌝`,`full moon with face`,`symbols`,``],[`🌞`,`sun with face`,`symbols`,``],[`🌟`,`glowing star`,`symbols`,`星星,闪光,闪耀`],[`🌠`,`shooting star`,`symbols`,``],[`🌡`,`thermometer`,`symbols`,``],[`🌤`,`white sun with small cloud`,`symbols`,``],[`🌥`,`white sun behind cloud`,`symbols`,``],[`🌦`,`white sun behind cloud with rain`,`symbols`,``],[`🌧`,`cloud with rain`,`symbols`,``],[`🌨`,`cloud with snow`,`symbols`,``],[`🌩`,`cloud with lightning`,`symbols`,``],[`🌪`,`cloud with tornado`,`symbols`,``],[`🌫`,`fog`,`symbols`,``],[`🌬`,`wind blowing face`,`symbols`,``],[`🌭`,`hot dog`,`food`,`热狗`],[`🌮`,`taco`,`food`,`墨西哥卷饼`],[`🌯`,`burrito`,`food`,`墨西哥卷,卷饼`],[`🌰`,`chestnut`,`food`,`栗子,坚果`],[`🌱`,`seedling`,`food`,``],[`🌲`,`evergreen tree`,`food`,`松树,树`],[`🌳`,`deciduous tree`,`food`,`树,大树`],[`🌴`,`palm tree`,`food`,`棕榈树,热带,度假`],[`🌵`,`cactus`,`food`,`仙人掌,沙漠`],[`🌶`,`hot pepper`,`food`,``],[`🌷`,`tulip`,`food`,`郁金香,花`],[`🌸`,`cherry blossom`,`food`,`樱花,花,春天`],[`🌹`,`rose`,`food`,`玫瑰,花,爱情`],[`🌺`,`hibiscus`,`food`,`花,芙蓉`],[`🌻`,`sunflower`,`food`,`向日葵,花,太阳`],[`🌼`,`blossom`,`food`,`雏菊,花`],[`🌽`,`ear of maize`,`food`,`玉米`],[`🌾`,`ear of rice`,`food`,``],[`🌿`,`herb`,`food`,`草,植物,草药`],[`🍀`,`four leaf clover`,`food`,`四叶草,幸运,好运`],[`🍁`,`maple leaf`,`food`,`枫叶,秋天,红叶`],[`🍂`,`fallen leaf`,`food`,`落叶,秋天`],[`🍃`,`leaf fluttering in wind`,`food`,`树叶,风`],[`🍄`,`mushroom`,`food`,`蘑菇,菌`],[`🍅`,`tomato`,`food`,`番茄,西红柿`],[`🍆`,`aubergine`,`food`,`茄子`],[`🍇`,`grapes`,`food`,`葡萄`],[`🍈`,`melon`,`food`,`哈密瓜,甜瓜`],[`🍉`,`watermelon`,`food`,`西瓜`],[`🍊`,`tangerine`,`food`,`橙子,橘子`],[`🍋`,`lemon`,`food`,`柠檬`],[`🍌`,`banana`,`food`,`香蕉`],[`🍍`,`pineapple`,`food`,`菠萝`],[`🍎`,`red apple`,`food`,`苹果`],[`🍏`,`green apple`,`food`,``],[`🍐`,`pear`,`food`,`梨`],[`🍑`,`peach`,`food`,`桃子,蜜桃`],[`🍒`,`cherries`,`food`,`樱桃,车厘子`],[`🍓`,`strawberry`,`food`,`草莓`],[`🍔`,`hamburger`,`food`,`汉堡,汉堡包`],[`🍕`,`slice of pizza`,`food`,`披萨,比萨`],[`🍖`,`meat on bone`,`food`,`骨头,肉,排骨`],[`🍗`,`poultry leg`,`food`,`鸡腿,炸鸡`],[`🍘`,`rice cracker`,`food`,`米饼,仙贝`],[`🍙`,`rice ball`,`food`,`饭团`],[`🍚`,`cooked rice`,`food`,`米饭,饭`],[`🍛`,`curry and rice`,`food`,`咖喱,咖喱饭`],[`🍜`,`steaming bowl`,`food`,`面条,拉面,面`],[`🍝`,`spaghetti`,`food`,`意大利面,意面`],[`🍞`,`bread`,`food`,`面包`],[`🍟`,`french fries`,`food`,`薯条,炸薯条`],[`🍠`,`roasted sweet potato`,`food`,`红薯,地瓜`],[`🍡`,`dango`,`food`,`团子,丸子`],[`🍢`,`oden`,`food`,`关东煮,串`],[`🍣`,`sushi`,`food`,`寿司,三文鱼`],[`🍤`,`fried shrimp`,`food`,`炸虾,天妇罗`],[`🍥`,`fish cake with swirl design`,`food`,`鱼板,鸣门卷`],[`🍦`,`soft ice cream`,`food`,`冰淇淋,甜筒`],[`🍧`,`shaved ice`,`food`,`刨冰,冰沙`],[`🍨`,`ice cream`,`food`,`冰淇淋,圣代`],[`🍩`,`doughnut`,`food`,``],[`🍪`,`cookie`,`food`,``],[`🍫`,`chocolate bar`,`food`,`巧克力`],[`🍬`,`candy`,`food`,`糖果,糖`],[`🍭`,`lollipop`,`food`,`棒棒糖`],[`🍮`,`custard`,`food`,`布丁,焦糖`],[`🍯`,`honey pot`,`food`,`蜂蜜,蜜`],[`🍰`,`shortcake`,`food`,`蛋糕,奶油蛋糕`],[`🍱`,`bento box`,`food`,`便当,盒饭`],[`🍲`,`pot of food`,`food`,`火锅,汤锅,炖菜`],[`🍳`,`cooking`,`food`,`煎蛋,鸡蛋`],[`🍴`,`fork and knife`,`food`,`刀叉,餐具`],[`🍵`,`teacup without handle`,`food`,`绿茶,茶,抹茶`],[`🍶`,`sake bottle and cup`,`food`,`清酒,日本酒`],[`🍷`,`wine glass`,`food`,`红酒,葡萄酒,酒`],[`🍸`,`cocktail glass`,`food`,`鸡尾酒,马提尼`],[`🍹`,`tropical drink`,`food`,`果汁,鸡尾酒`],[`🍺`,`beer mug`,`food`,`啤酒,啤酒杯`],[`🍻`,`clinking beer mugs`,`food`,`干杯,碰杯,啤酒`],[`🍼`,`baby bottle`,`food`,`奶瓶,婴儿,奶粉`],[`🍽`,`fork and knife with plate`,`food`,``],[`🍾`,`bottle with popping cork`,`food`,`香槟,起泡酒,庆祝`],[`🍿`,`popcorn`,`food`,``],[`🎀`,`ribbon`,`activity`,`蝴蝶结,礼物,装饰`],[`🎁`,`wrapped present`,`activity`,`礼物,礼盒,生日`],[`🎂`,`birthday cake`,`activity`,`生日蛋糕,生日,蛋糕`],[`🎃`,`jack-o-lantern`,`activity`,``],[`🎄`,`christmas tree`,`activity`,``],[`🎅`,`father christmas`,`activity`,`圣诞老人,圣诞,圣诞节`],[`🎆`,`fireworks`,`activity`,``],[`🎇`,`firework sparkler`,`activity`,``],[`🎈`,`balloon`,`activity`,`气球,庆祝,派对`],[`🎉`,`party popper`,`activity`,`彩带,庆祝,派对,欢呼`],[`🎊`,`confetti ball`,`activity`,`庆祝`],[`🎋`,`tanabata tree`,`activity`,``],[`🎌`,`crossed flags`,`flags`,`旗,日本,交叉旗`],[`🎍`,`pine decoration`,`activity`,``],[`🎎`,`japanese dolls`,`activity`,`人偶,日本人偶`],[`🎏`,`carp streamer`,`activity`,`鲤鱼旗,日本,端午节`],[`🎐`,`wind chime`,`activity`,`风铃,夏天`],[`🎑`,`moon viewing ceremony`,`activity`,``],[`🎒`,`school satchel`,`activity`,`书包,背包`],[`🎓`,`graduation cap`,`activity`,`学士帽,毕业,学位`],[`🎖`,`military medal`,`activity`,``],[`🎗`,`reminder ribbon`,`activity`,``],[`🎙`,`studio microphone`,`activity`,``],[`🎚`,`level slider`,`activity`,``],[`🎛`,`control knobs`,`activity`,``],[`🎞`,`film frames`,`activity`,``],[`🎟`,`admission tickets`,`activity`,``],[`🎠`,`carousel horse`,`activity`,`旋转木马,游乐园`],[`🎡`,`ferris wheel`,`activity`,`摩天轮,游乐园`],[`🎢`,`roller coaster`,`activity`,`过山车,游乐园`],[`🎣`,`fishing pole and fish`,`activity`,`钓鱼`],[`🎤`,`microphone`,`activity`,`麦克风,唱歌,K歌`],[`🎥`,`movie camera`,`activity`,`摄影机,电影,拍摄`],[`🎦`,`cinema`,`activity`,``],[`🎧`,`headphone`,`activity`,`耳机,听歌,音乐,戴`],[`🎨`,`artist palette`,`activity`,`调色板,画画,美术,艺术`],[`🎩`,`top hat`,`activity`,`礼帽,魔术帽,帽子`],[`🎪`,`circus tent`,`activity`,`马戏团`],[`🎫`,`ticket`,`activity`,`门票,票,入场券`],[`🎬`,`clapper board`,`activity`,`场记板,电影,拍戏,导演`],[`🎭`,`performing arts`,`activity`,`面具,戏剧,表演,舞台`],[`🎮`,`video game`,`activity`,`游戏机,游戏,手柄,玩`],[`🎯`,`direct hit`,`activity`,`目标`],[`🎰`,`slot machine`,`activity`,``],[`🎱`,`billiards`,`activity`,`台球`],[`🎲`,`game die`,`activity`,`骰子,赌博,游戏`],[`🎳`,`bowling`,`activity`,`保龄球,球`],[`🎴`,`flower playing cards`,`activity`,`花牌,卡牌,纸牌`],[`🎵`,`musical note`,`activity`,`音符,音乐,歌`],[`🎶`,`multiple musical notes`,`activity`,`音符,音乐,唱歌`],[`🎷`,`saxophone`,`activity`,`萨克斯,爵士,乐器`],[`🎸`,`guitar`,`activity`,`吉他,弹吉他,摇滚`],[`🎹`,`musical keyboard`,`activity`,`钢琴,键盘,弹琴`],[`🎺`,`trumpet`,`activity`,`小号,喇叭,乐器`],[`🎻`,`violin`,`activity`,`小提琴,弦乐`],[`🎼`,`musical score`,`activity`,`乐谱,音乐,谱`],[`🎽`,`running shirt with sash`,`activity`,`背心`],[`🎾`,`tennis racquet and ball`,`activity`,`网球,球`],[`🎿`,`ski and ski boot`,`activity`,`滑雪`],[`🏀`,`basketball and hoop`,`activity`,`篮球,球`],[`🏁`,`chequered flag`,`flags`,`终点,旗帜,赛车,比赛`],[`🏂`,`snowboarder`,`activity`,``],[`🏃`,`runner`,`activity`,`跑步,跑,奔跑`],[`🏄`,`surfer`,`activity`,``],[`🏅`,`sports medal`,`activity`,`奖牌,奖章,荣誉`],[`🏆`,`trophy`,`activity`,``],[`🏇`,`horse racing`,`activity`,``],[`🏈`,`american football`,`activity`,`橄榄球,美式足球`],[`🏉`,`rugby football`,`activity`,`橄榄球,英式`],[`🏊`,`swimmer`,`activity`,``],[`🏋`,`weight lifter`,`activity`,``],[`🏌`,`golfer`,`activity`,``],[`🏍`,`racing motorcycle`,`activity`,``],[`🏎`,`racing car`,`activity`,``],[`🏏`,`cricket bat and ball`,`activity`,``],[`🏐`,`volleyball`,`activity`,`排球,球`],[`🏑`,`field hockey stick and ball`,`activity`,``],[`🏒`,`ice hockey stick and puck`,`activity`,``],[`🏓`,`table tennis paddle and ball`,`activity`,`乒乓球,乒乓,球`],[`🏔`,`snow capped mountain`,`activity`,``],[`🏕`,`camping`,`activity`,``],[`🏖`,`beach with umbrella`,`activity`,``],[`🏗`,`building construction`,`activity`,``],[`🏘`,`house buildings`,`activity`,``],[`🏙`,`cityscape`,`activity`,``],[`🏚`,`derelict house building`,`activity`,``],[`🏛`,`classical building`,`activity`,``],[`🏜`,`desert`,`activity`,``],[`🏝`,`desert island`,`activity`,``],[`🏞`,`national park`,`activity`,``],[`🏟`,`stadium`,`activity`,``],[`🏠`,`house building`,`travel`,`房子,家,住宅`],[`🏡`,`house with garden`,`travel`,`房子,家,花园`],[`🏢`,`office building`,`travel`,`办公楼,大楼,写字楼`],[`🏣`,`japanese post office`,`travel`,`邮局,邮政`],[`🏤`,`european post office`,`travel`,`邮局`],[`🏥`,`hospital`,`travel`,`医院,医疗`],[`🏦`,`bank`,`travel`,`银行,金融`],[`🏧`,`automated teller machine`,`travel`,``],[`🏨`,`hotel`,`travel`,`酒店,旅馆`],[`🏩`,`love hotel`,`travel`,`爱情旅馆,酒店`],[`🏪`,`convenience store`,`travel`,`便利店,商店`],[`🏫`,`school`,`travel`,`学校,校园`],[`🏬`,`department store`,`travel`,`商场,百货,购物`],[`🏭`,`factory`,`travel`,`工厂,工业`],[`🏮`,`izakaya lantern`,`travel`,``],[`🏯`,`japanese castle`,`objects`,`城堡,日本城堡`],[`🏰`,`european castle`,`travel`,`城堡,童话`],[`🏳`,`waving white flag`,`flags`,``],[`🏴`,`waving black flag`,`flags`,`黑旗`],[`🏵`,`rosette`,`objects`,``],[`🏷`,`label`,`objects`,``],[`🏸`,`badminton racquet and shuttlecock`,`activity`,`羽毛球,球`],[`🏹`,`bow and arrow`,`activity`,`射箭,弓箭,弓`],[`🏺`,`amphora`,`activity`,`陶罐,花瓶,双耳瓶`],[`🏻`,`emoji modifier fitzpatrick type-1-2`,`symbols`,``],[`🏼`,`emoji modifier fitzpatrick type-3`,`symbols`,``],[`🏽`,`emoji modifier fitzpatrick type-4`,`symbols`,``],[`🏾`,`emoji modifier fitzpatrick type-5`,`symbols`,``],[`🏿`,`emoji modifier fitzpatrick type-6`,`symbols`,``],[`🐀`,`rat`,`animals`,`老鼠,鼠`],[`🐁`,`mouse`,`animals`,`老鼠,鼠`],[`🐂`,`ox`,`animals`,`公牛,牛`],[`🐃`,`water buffalo`,`animals`,`水牛,牛`],[`🐄`,`cow`,`animals`,`奶牛,牛`],[`🐅`,`tiger`,`animals`,``],[`🐆`,`leopard`,`animals`,``],[`🐇`,`rabbit`,`animals`,`兔子,兔`],[`🐈`,`cat`,`animals`,`猫,猫咪`],[`🐉`,`dragon`,`animals`,`龙,中国龙`],[`🐊`,`crocodile`,`animals`,`鳄鱼,短吻鳄`],[`🐋`,`whale`,`animals`,`鲸鱼`],[`🐌`,`snail`,`animals`,``],[`🐍`,`snake`,`animals`,`蛇,爬行动物`],[`🐎`,`horse`,`animals`,``],[`🐏`,`ram`,`animals`,`羊,公羊`],[`🐐`,`goat`,`animals`,`山羊,羊`],[`🐑`,`sheep`,`animals`,`羊,绵羊`],[`🐒`,`monkey`,`animals`,``],[`🐓`,`rooster`,`animals`,`公鸡,鸡`],[`🐔`,`chicken`,`animals`,`鸡,母鸡`],[`🐕`,`dog`,`animals`,`狗,小狗`],[`🐖`,`pig`,`animals`,`猪`],[`🐗`,`boar`,`animals`,`野猪,猪`],[`🐘`,`elephant`,`animals`,`大象`],[`🐙`,`octopus`,`animals`,`章鱼,八爪鱼`],[`🐚`,`spiral shell`,`animals`,``],[`🐛`,`bug`,`animals`,``],[`🐜`,`ant`,`animals`,``],[`🐝`,`honeybee`,`animals`,``],[`🐞`,`lady beetle`,`animals`,``],[`🐟`,`fish`,`animals`,`鱼,鱼`],[`🐠`,`tropical fish`,`animals`,`热带鱼,鱼`],[`🐡`,`blowfish`,`animals`,`河豚,鱼`],[`🐢`,`turtle`,`animals`,`乌龟,慢`],[`🐣`,`hatching chick`,`animals`,`小鸡,破壳,孵化`],[`🐤`,`baby chick`,`animals`,`小鸡,黄,可爱`],[`🐥`,`front-facing baby chick`,`animals`,`小鸡,正面`],[`🐦`,`bird`,`animals`,`鸟`],[`🐧`,`penguin`,`animals`,`企鹅,南极`],[`🐨`,`koala`,`animals`,`考拉,无尾熊`],[`🐩`,`poodle`,`animals`,`贵宾犬,狗`],[`🐪`,`dromedary camel`,`animals`,`骆驼`],[`🐫`,`bactrian camel`,`animals`,`骆驼,双峰`],[`🐬`,`dolphin`,`animals`,`海豚,海洋`],[`🐭`,`mouse face`,`animals`,`老鼠,鼠`],[`🐮`,`cow face`,`animals`,`牛,奶牛`],[`🐯`,`tiger face`,`animals`,``],[`🐰`,`rabbit face`,`animals`,`兔子,兔,可爱`],[`🐱`,`cat face`,`animals`,``],[`🐲`,`dragon face`,`animals`,`龙,龙头`],[`🐳`,`spouting whale`,`animals`,`鲸鱼,喷水`],[`🐴`,`horse face`,`animals`,`马`],[`🐵`,`monkey face`,`animals`,``],[`🐶`,`dog face`,`animals`,``],[`🐷`,`pig face`,`animals`,`猪,猪头`],[`🐸`,`frog face`,`animals`,`青蛙,蛙`],[`🐹`,`hamster face`,`animals`,`仓鼠`],[`🐺`,`wolf face`,`animals`,``],[`🐻`,`bear face`,`animals`,`熊,泰迪熊`],[`🐼`,`panda face`,`animals`,``],[`🐽`,`pig nose`,`animals`,`猪鼻子,猪`],[`🐾`,`paw prints`,`animals`,`爪印,脚印`],[`🐿`,`chipmunk`,`animals`,``],[`👀`,`eyes`,`people`,``],[`👁`,`eye`,`people`,``],[`👂`,`ear`,`people`,`耳朵,听`],[`👃`,`nose`,`people`,`鼻子,闻`],[`👄`,`mouth`,`people`,`嘴巴,嘴唇,吻`],[`👅`,`tongue`,`people`,`舌头,舔`],[`👆`,`white up pointing backhand index`,`people`,`指,上面,向上`],[`👇`,`white down pointing backhand index`,`people`,`指,下面,向下`],[`👈`,`white left pointing backhand index`,`people`,`指,左边,指向`],[`👉`,`white right pointing backhand index`,`people`,`指,右边,指向`],[`👊`,`fisted hand sign`,`people`,`拳头,打,战斗`],[`👋`,`waving hand sign`,`people`,`挥手,再见,你好`],[`👌`,`ok hand sign`,`people`,`OK,好,可以`],[`👍`,`thumbs up sign`,`people`,`点赞,好,赞,棒`],[`👎`,`thumbs down sign`,`people`,`差评,不好,踩`],[`👏`,`clapping hands sign`,`people`,`鼓掌,拍手,掌声`],[`👐`,`open hands sign`,`people`,`张开,手,开放`],[`👑`,`crown`,`people`,`皇冠,王冠,国王,女王`],[`👒`,`womans hat`,`people`,`帽子,草帽,遮阳帽`],[`👓`,`eyeglasses`,`people`,`眼镜`],[`👔`,`necktie`,`people`,`领带,西装,工作`],[`👕`,`t-shirt`,`people`,`衣服,T恤`],[`👖`,`jeans`,`people`,`裤子,牛仔裤`],[`👗`,`dress`,`people`,`裙子,连衣裙`],[`👘`,`kimono`,`people`,`和服`],[`👙`,`bikini`,`people`,`比基尼,泳装`],[`👚`,`womans clothes`,`people`,`女装,衣服`],[`👛`,`purse`,`people`,`钱包,小包`],[`👜`,`handbag`,`people`,`手提包,包包`],[`👝`,`pouch`,`people`,`手拿包,包包`],[`👞`,`mans shoe`,`people`,`皮鞋,鞋`],[`👟`,`athletic shoe`,`people`,`运动鞋,跑鞋`],[`👠`,`high-heeled shoe`,`people`,`高跟鞋,鞋`],[`👡`,`womans sandal`,`people`,`凉鞋,鞋`],[`👢`,`womans boots`,`people`,`靴子,长靴`],[`👣`,`footprints`,`people`,`脚印,脚步,足迹`],[`👤`,`bust in silhouette`,`people`,`人,剪影,用户`],[`👥`,`busts in silhouette`,`people`,`人群,人,多个人`],[`👦`,`boy`,`people`,`男孩,小男孩`],[`👧`,`girl`,`people`,`女孩,小女孩`],[`👨`,`man`,`people`,`男人,男士`],[`👩`,`woman`,`people`,`女人,女士`],[`👪`,`family`,`people`,`家庭`],[`👫`,`woman and man holding hands`,`people`,``],[`👬`,`men holding hands`,`people`,``],[`👭`,`women holding hands`,`people`,``],[`👮`,`police officer`,`people`,`警察,警官`],[`👯`,`woman with bunny ears`,`people`,`兔子舞,蹦迪,派对`],[`👰`,`bride with veil`,`people`,`新娘,婚纱,结婚`],[`👱`,`person with blond hair`,`people`,``],[`👲`,`man with gua pi mao`,`people`,`中国人`],[`👳`,`man with turban`,`people`,`包头巾,印度,阿拉伯`],[`👴`,`older man`,`people`,`老人,老爷爷`],[`👵`,`older woman`,`people`,`老人,老奶奶`],[`👶`,`baby`,`people`,`婴儿,宝宝,小孩`],[`👷`,`construction worker`,`people`,`工人`],[`👸`,`princess`,`people`,`公主,女王`],[`👹`,`japanese ogre`,`people`,`妖怪,鬼,怪物`],[`👺`,`japanese goblin`,`people`,`天狗,怪物,鬼`],[`👻`,`ghost`,`people`,`幽灵,鬼,万圣节`],[`👼`,`baby angel`,`people`,`天使,婴儿,可爱`],[`👽`,`extraterrestrial alien`,`people`,`外星人,ET,飞碟`],[`👾`,`alien monster`,`people`,`外星人,怪兽,游戏`],[`👿`,`imp`,`people`,`恶魔,愤怒`],[`💀`,`skull`,`people`,`骷髅,死亡,骨头`],[`💁`,`information desk person`,`people`,``],[`💂`,`guardsman`,`people`,`卫兵,士兵`],[`💃`,`dancer`,`people`,`跳舞,舞女,跳舞`],[`💄`,`lipstick`,`people`,`口红,化妆`],[`💅`,`nail polish`,`people`,`美甲,指甲,涂`],[`💆`,`face massage`,`people`,`按摩,放松,头部`],[`💇`,`haircut`,`people`,`理发,剪发,发型`],[`💈`,`barber pole`,`people`,`理发店,理发`],[`💉`,`syringe`,`people`,`注射器,针,疫苗`],[`💊`,`pill`,`people`,`药丸,药,胶囊`],[`💋`,`kiss mark`,`people`,`吻,口红印,亲亲`],[`💌`,`love letter`,`people`,`情书,信,爱情`],[`💍`,`ring`,`people`,`戒指,钻戒,结婚`],[`💎`,`gem stone`,`people`,`钻石,宝石,珠宝`],[`💏`,`kiss`,`people`,``],[`💐`,`bouquet`,`smileys`,`花束,花,礼物`],[`💑`,`couple with heart`,`smileys`,``],[`💒`,`wedding`,`smileys`,`教堂,婚礼,教堂婚礼`],[`💓`,`beating heart`,`smileys`,`爱心,跳动,心跳`],[`💔`,`broken heart`,`smileys`,`心碎,伤心,破碎`],[`💕`,`two hearts`,`smileys`,`爱心,两个,喜欢`],[`💖`,`sparkling heart`,`smileys`,`爱心,闪光,喜欢`],[`💗`,`growing heart`,`smileys`,`爱心,跳动,喜欢`],[`💘`,`heart with arrow`,`smileys`,`爱心,箭,丘比特`],[`💙`,`blue heart`,`smileys`,``],[`💚`,`green heart`,`smileys`,``],[`💛`,`yellow heart`,`smileys`,``],[`💜`,`purple heart`,`smileys`,``],[`💝`,`heart with ribbon`,`smileys`,`爱心,礼物,蝴蝶结`],[`💞`,`revolving hearts`,`smileys`,`爱心,旋转,轮回`],[`💟`,`heart decoration`,`smileys`,`爱心,符号`],[`💠`,`diamond shape with a dot inside`,`objects`,``],[`💡`,`electric light bulb`,`objects`,``],[`💢`,`anger symbol`,`objects`,`生气,怒气`],[`💣`,`bomb`,`objects`,`炸弹,爆炸`],[`💤`,`sleeping symbol`,`objects`,`睡觉,打呼,困`],[`💥`,`collision symbol`,`objects`,``],[`💦`,`splashing sweat symbol`,`objects`,`汗,水,泪`],[`💧`,`droplet`,`objects`,`水滴,水,眼泪`],[`💨`,`dash symbol`,`objects`,`风,跑,快,烟雾`],[`💩`,`pile of poo`,`objects`,`大便,屎,狗屎`],[`💪`,`flexed biceps`,`people`,`肌肉,力量,加油,强壮`],[`💫`,`dizzy symbol`,`objects`,`星星,旋转`],[`💬`,`speech balloon`,`objects`,`对话,聊天`],[`💭`,`thought balloon`,`objects`,`想法,思考,气泡`],[`💮`,`white flower`,`objects`,``],[`💯`,`hundred points symbol`,`objects`,``],[`💰`,`money bag`,`objects`,`钱袋,钱,金钱`],[`💱`,`currency exchange`,`objects`,``],[`💲`,`heavy dollar sign`,`objects`,``],[`💳`,`credit card`,`objects`,`信用卡,银行卡,支付`],[`💴`,`banknote with yen sign`,`objects`,`日元,日圆,钱`],[`💵`,`banknote with dollar sign`,`objects`,`美元,美金,钱`],[`💶`,`banknote with euro sign`,`objects`,`欧元,钱`],[`💷`,`banknote with pound sign`,`objects`,`英镑,钱`],[`💸`,`money with wings`,`objects`,`钱,飞钱,花钱`],[`💹`,`chart with upwards trend and yen sign`,`objects`,`股票,上涨,图表,增长`],[`💺`,`seat`,`objects`,`座位,椅子,飞机座位`],[`💻`,`personal computer`,`objects`,`电脑,笔记本,笔记本电脑`],[`💼`,`briefcase`,`objects`,`公文包,工作,商务`],[`💽`,`minidisc`,`objects`,`光盘,磁盘`],[`💾`,`floppy disk`,`objects`,`软盘,保存`],[`💿`,`optical disc`,`objects`,`光盘,CD`],[`📀`,`dvd`,`objects`,`光盘,DVD`],[`📁`,`file folder`,`objects`,`文件夹`],[`📂`,`open file folder`,`objects`,`文件夹,打开`],[`📃`,`page with curl`,`objects`,`文件,文档`],[`📄`,`page facing up`,`objects`,`文件,文档,纸`],[`📅`,`calendar`,`objects`,`日历`],[`📆`,`tear-off calendar`,`objects`,`日历,日历页`],[`📇`,`card index`,`objects`,`名片,索引卡`],[`📈`,`chart with upwards trend`,`objects`,``],[`📉`,`chart with downwards trend`,`objects`,``],[`📊`,`bar chart`,`objects`,``],[`📋`,`clipboard`,`objects`,`剪贴板,清单,列表`],[`📌`,`pushpin`,`objects`,``],[`📍`,`round pushpin`,`objects`,``],[`📎`,`paperclip`,`objects`,``],[`📏`,`straight ruler`,`objects`,``],[`📐`,`triangular ruler`,`objects`,``],[`📑`,`bookmark tabs`,`objects`,`书签,标签,文件`],[`📒`,`ledger`,`objects`,``],[`📓`,`notebook`,`objects`,``],[`📔`,`notebook with decorative cover`,`objects`,``],[`📕`,`closed book`,`objects`,``],[`📖`,`open book`,`objects`,``],[`📗`,`green book`,`objects`,``],[`📘`,`blue book`,`objects`,``],[`📙`,`orange book`,`objects`,``],[`📚`,`books`,`objects`,``],[`📛`,`name badge`,`objects`,``],[`📜`,`scroll`,`objects`,``],[`📝`,`memo`,`objects`,`笔记,备忘录,写作,文档`],[`📞`,`telephone receiver`,`objects`,`电话`],[`📟`,`pager`,`objects`,`寻呼机,传呼机`],[`📠`,`fax machine`,`objects`,`传真机,传真`],[`📡`,`satellite antenna`,`objects`,`天线,卫星,信号`],[`📢`,`public address loudspeaker`,`objects`,``],[`📣`,`cheering megaphone`,`objects`,``],[`📤`,`outbox tray`,`objects`,`发送,输出,上传`],[`📥`,`inbox tray`,`objects`,`接收,下载,收件箱`],[`📦`,`package`,`objects`,`包裹,快递,箱子`],[`📧`,`e-mail symbol`,`objects`,`邮件,电子邮件`],[`📨`,`incoming envelope`,`objects`,`邮件,收到`],[`📩`,`envelope with downwards arrow above`,`objects`,`邮件,发送`],[`📪`,`closed mailbox with lowered flag`,`objects`,`邮箱,关闭`],[`📫`,`closed mailbox with raised flag`,`objects`,`邮箱,信箱,邮件`],[`📬`,`open mailbox with raised flag`,`objects`,`邮箱,有信`],[`📭`,`open mailbox with lowered flag`,`objects`,`邮箱,无信`],[`📮`,`postbox`,`objects`,`邮筒,邮政`],[`📯`,`postal horn`,`objects`,``],[`📰`,`newspaper`,`objects`,`报纸,新闻,报`],[`📱`,`mobile phone`,`objects`,`手机,智能手机,电话`],[`📲`,`mobile phone with rightwards arrow at left`,`objects`,`手机,接收,信号`],[`📳`,`vibration mode`,`objects`,``],[`📴`,`mobile phone off`,`objects`,``],[`📵`,`no mobile phones`,`objects`,``],[`📶`,`antenna with bars`,`objects`,``],[`📷`,`camera`,`objects`,`相机,拍照,照片`],[`📸`,`camera with flash`,`objects`,`相机,闪光灯,拍照`],[`📹`,`video camera`,`objects`,`摄像机,录像`],[`📺`,`television`,`objects`,``],[`📻`,`radio`,`objects`,`收音机,广播`],[`📼`,`videocassette`,`objects`,`录像带,磁带`],[`📽`,`film projector`,`objects`,``],[`📿`,`prayer beads`,`objects`,`念珠,佛珠,项链`],[`🔀`,`twisted rightwards arrows`,`objects`,``],[`🔁`,`clockwise rightwards and leftwards open circle arrows`,`objects`,``],[`🔂`,`clockwise rightwards and leftwards open circle arrows with circled one overlay`,`objects`,``],[`🔃`,`clockwise downwards and upwards open circle arrows`,`objects`,``],[`🔄`,`anticlockwise downwards and upwards open circle arrows`,`objects`,``],[`🔅`,`low brightness symbol`,`objects`,``],[`🔆`,`high brightness symbol`,`objects`,``],[`🔇`,`speaker with cancellation stroke`,`objects`,``],[`🔈`,`speaker`,`objects`,``],[`🔉`,`speaker with one sound wave`,`objects`,``],[`🔊`,`speaker with three sound waves`,`objects`,``],[`🔋`,`battery`,`objects`,``],[`🔌`,`electric plug`,`objects`,``],[`🔍`,`left-pointing magnifying glass`,`objects`,`搜索,放大镜,查找,查询`],[`🔎`,`right-pointing magnifying glass`,`objects`,`搜索,放大镜,查找`],[`🔏`,`lock with ink pen`,`objects`,`锁,保密,笔`],[`🔐`,`closed lock with key`,`objects`,`锁,安全,钥匙`],[`🔑`,`key`,`objects`,`钥匙,解锁`],[`🔒`,`lock`,`objects`,`锁,锁定,安全`],[`🔓`,`open lock`,`objects`,`解锁,打开`],[`🔔`,`bell`,`objects`,``],[`🔕`,`bell with cancellation stroke`,`objects`,``],[`🔖`,`bookmark`,`objects`,`书签,标记`],[`🔗`,`link symbol`,`objects`,``],[`🔘`,`radio button`,`objects`,``],[`🔙`,`back with leftwards arrow above`,`objects`,``],[`🔚`,`end with leftwards arrow above`,`objects`,``],[`🔛`,`on with exclamation mark with left right arrow above`,`objects`,``],[`🔜`,`soon with rightwards arrow above`,`objects`,``],[`🔝`,`top with upwards arrow above`,`objects`,``],[`🔞`,`no one under eighteen symbol`,`objects`,``],[`🔟`,`keycap 10`,`objects`,``],[`🔠`,`input symbol for latin capital letters`,`objects`,``],[`🔡`,`input symbol for latin small letters`,`objects`,``],[`🔢`,`input symbol for numbers`,`objects`,``],[`🔣`,`input symbol for symbols`,`objects`,``],[`🔤`,`input symbol for latin letters`,`objects`,``],[`🔥`,`fire`,`objects`,``],[`🔦`,`electric torch`,`objects`,``],[`🔧`,`wrench`,`objects`,`扳手,工具,维修`],[`🔨`,`hammer`,`objects`,`锤子,工具`],[`🔩`,`nut and bolt`,`objects`,`螺丝,螺母`],[`🔪`,`hocho`,`objects`,``],[`🔫`,`pistol`,`objects`,`枪`],[`🔬`,`microscope`,`objects`,`显微镜,科学,研究`],[`🔭`,`telescope`,`objects`,`望远镜,天文,观察`],[`🔮`,`crystal ball`,`objects`,``],[`🔯`,`six pointed star with middle dot`,`objects`,``],[`🔰`,`japanese symbol for beginner`,`objects`,``],[`🔱`,`trident emblem`,`objects`,``],[`🔲`,`black square button`,`objects`,``],[`🔳`,`white square button`,`objects`,``],[`🔴`,`large red circle`,`objects`,``],[`🔵`,`large blue circle`,`objects`,``],[`🔶`,`large orange diamond`,`objects`,``],[`🔷`,`large blue diamond`,`objects`,``],[`🔸`,`small orange diamond`,`objects`,``],[`🔹`,`small blue diamond`,`objects`,``],[`🔺`,`up-pointing red triangle`,`objects`,``],[`🔻`,`down-pointing red triangle`,`objects`,``],[`🔼`,`up-pointing small red triangle`,`objects`,``],[`🔽`,`down-pointing small red triangle`,`objects`,``],[`🕉`,`om symbol`,`objects`,``],[`🕊`,`dove of peace`,`objects`,``],[`🕋`,`kaaba`,`objects`,`天房,麦加,伊斯兰`],[`🕌`,`mosque`,`objects`,`清真寺,伊斯兰`],[`🕍`,`synagogue`,`objects`,`犹太教堂,犹太`],[`🕎`,`menorah with nine branches`,`objects`,``],[`🕐`,`clock face one oclock`,`objects`,`一点,时钟`],[`🕑`,`clock face two oclock`,`objects`,`两点,时钟`],[`🕒`,`clock face three oclock`,`objects`,`三点,时钟`],[`🕓`,`clock face four oclock`,`objects`,`四点,时钟`],[`🕔`,`clock face five oclock`,`objects`,`五点,时钟`],[`🕕`,`clock face six oclock`,`objects`,`六点,时钟`],[`🕖`,`clock face seven oclock`,`objects`,`七点,时钟`],[`🕗`,`clock face eight oclock`,`objects`,`八点,时钟`],[`🕘`,`clock face nine oclock`,`objects`,`九点,时钟`],[`🕙`,`clock face ten oclock`,`objects`,`十点,时钟`],[`🕚`,`clock face eleven oclock`,`objects`,`十一点,时钟`],[`🕛`,`clock face twelve oclock`,`objects`,`十二点,时钟,时间`],[`🕜`,`clock face one-thirty`,`objects`,``],[`🕝`,`clock face two-thirty`,`objects`,``],[`🕞`,`clock face three-thirty`,`objects`,``],[`🕟`,`clock face four-thirty`,`objects`,``],[`🕠`,`clock face five-thirty`,`objects`,``],[`🕡`,`clock face six-thirty`,`objects`,``],[`🕢`,`clock face seven-thirty`,`objects`,``],[`🕣`,`clock face eight-thirty`,`objects`,``],[`🕤`,`clock face nine-thirty`,`objects`,``],[`🕥`,`clock face ten-thirty`,`objects`,``],[`🕦`,`clock face eleven-thirty`,`objects`,``],[`🕧`,`clock face twelve-thirty`,`objects`,``],[`🕯`,`candle`,`objects`,``],[`🕰`,`mantelpiece clock`,`objects`,``],[`🕳`,`hole`,`objects`,``],[`🕴`,`man in business suit levitating`,`objects`,``],[`🕵`,`sleuth or spy`,`objects`,``],[`🕶`,`dark sunglasses`,`objects`,``],[`🕷`,`spider`,`objects`,``],[`🕸`,`spider web`,`objects`,``],[`🕹`,`joystick`,`objects`,``],[`🕺`,`man dancing`,`objects`,`跳舞,舞男`],[`🖇`,`linked paperclips`,`objects`,``],[`🖊`,`lower left ballpoint pen`,`objects`,``],[`🖋`,`lower left fountain pen`,`objects`,``],[`🖌`,`lower left paintbrush`,`objects`,``],[`🖍`,`lower left crayon`,`objects`,``],[`🖐`,`raised hand with fingers splayed`,`objects`,``],[`🖕`,`reversed hand with middle finger extended`,`objects`,`中指,骂人`],[`🖖`,`raised hand with part between middle and ring fingers`,`objects`,`瓦肯,举手,胜利`],[`🖤`,`black heart`,`objects`,``],[`🖥`,`desktop computer`,`objects`,``],[`🖨`,`printer`,`objects`,``],[`🖱`,`three button mouse`,`objects`,``],[`🖲`,`trackball`,`objects`,``],[`🖼`,`frame with picture`,`objects`,``],[`🗂`,`card index dividers`,`objects`,``],[`🗃`,`card file box`,`objects`,``],[`🗄`,`file cabinet`,`objects`,``],[`🗑`,`wastebasket`,`objects`,``],[`🗒`,`spiral note pad`,`objects`,``],[`🗓`,`spiral calendar pad`,`objects`,``],[`🗜`,`compression`,`objects`,``],[`🗝`,`old key`,`objects`,``],[`🗞`,`rolled-up newspaper`,`objects`,``],[`🗡`,`dagger knife`,`objects`,``],[`🗣`,`speaking head in silhouette`,`objects`,``],[`🗨`,`left speech bubble`,`objects`,``],[`🗯`,`right anger bubble`,`objects`,``],[`🗳`,`ballot box with ballot`,`objects`,``],[`🗺`,`world map`,`objects`,``],[`🗻`,`mount fuji`,`objects`,`富士山,山`],[`🗼`,`tokyo tower`,`objects`,`塔,东京塔`],[`🗽`,`statue of liberty`,`objects`,`自由女神像,纽约`],[`🗾`,`silhouette of japan`,`objects`,``],[`🗿`,`moyai`,`objects`,`雕像`],[`😀`,`grinning face`,`smileys`,`笑脸,开心,高兴`],[`😁`,`grinning face with smiling eyes`,`smileys`,`笑脸,开心`],[`😂`,`face with tears of joy`,`smileys`,`笑哭,大笑,笑`],[`😃`,`smiling face with open mouth`,`smileys`,`笑脸,开心`],[`😄`,`smiling face with open mouth and smiling eyes`,`smileys`,`笑脸,开心`],[`😅`,`smiling face with open mouth and cold sweat`,`smileys`,`笑脸,汗,尴尬`],[`😆`,`smiling face with open mouth and tightly-closed eyes`,`smileys`,`笑脸,大笑`],[`😇`,`smiling face with halo`,`smileys`,`天使,微笑,善良`],[`😈`,`smiling face with horns`,`smileys`,`恶魔,坏笑,邪恶`],[`😉`,`winking face`,`smileys`,`眨眼,调皮`],[`😊`,`smiling face with smiling eyes`,`smileys`,`微笑,开心,脸红`],[`😋`,`face savouring delicious food`,`smileys`,`好吃,美味,舔`],[`😌`,`relieved face`,`smileys`,`放松,安心`],[`😍`,`smiling face with heart-shaped eyes`,`smileys`,`爱,喜欢,花痴`],[`😎`,`smiling face with sunglasses`,`smileys`,`酷,墨镜,帅气`],[`😏`,`smirking face`,`smileys`,`得意,微笑,坏笑`],[`😐`,`neutral face`,`smileys`,`无语,面无表情`],[`😑`,`expressionless face`,`smileys`,`无语,面无表情`],[`😒`,`unamused face`,`smileys`,`不满,无语,翻白眼`],[`😓`,`face with cold sweat`,`smileys`,`冷汗,尴尬`],[`😔`,`pensive face`,`smileys`,`难过,低落`],[`😕`,`confused face`,`smileys`,`困惑,不解`],[`😖`,`confounded face`,`smileys`,`纠结,痛苦`],[`😗`,`kissing face`,`smileys`,`亲亲,吻`],[`😘`,`face throwing a kiss`,`smileys`,`飞吻,亲亲,爱`],[`😙`,`kissing face with smiling eyes`,`smileys`,``],[`😚`,`kissing face with closed eyes`,`smileys`,`亲亲,吻`],[`😛`,`face with stuck-out tongue`,`smileys`,`吐舌头,调皮`],[`😜`,`face with stuck-out tongue and winking eye`,`smileys`,`吐舌头,调皮,眨眼`],[`😝`,`face with stuck-out tongue and tightly-closed eyes`,`smileys`,`吐舌头,调皮`],[`😞`,`disappointed face`,`smileys`,`失望,难过`],[`😟`,`worried face`,`smileys`,`担心,忧虑`],[`😠`,`angry face`,`smileys`,`生气,愤怒`],[`😡`,`pouting face`,`smileys`,`生气,愤怒,红脸`],[`😢`,`crying face`,`smileys`,`哭,伤心,流泪`],[`😣`,`persevering face`,`smileys`,`挣扎,痛苦`],[`😤`,`face with look of triumph`,`smileys`,`生气,冒烟,气`],[`😥`,`disappointed but relieved face`,`smileys`,`难过,失望,松气`],[`😦`,`frowning face with open mouth`,`smileys`,`惊讶,张嘴`],[`😧`,`anguished face`,`smileys`,`震惊,痛苦`],[`😨`,`fearful face`,`smileys`,`害怕,恐惧`],[`😩`,`weary face`,`smileys`,`累,疲惫,哭`],[`😪`,`sleepy face`,`smileys`,`困,想睡`],[`😫`,`tired face`,`smileys`,`累,疲惫`],[`😬`,`grimacing face`,`smileys`,`尴尬,咧嘴`],[`😭`,`loudly crying face`,`smileys`,`大哭,伤心,哭`],[`😮`,`face with open mouth`,`smileys`,`惊讶,哇`],[`😯`,`hushed face`,`smileys`,`惊讶,安静`],[`😰`,`face with open mouth and cold sweat`,`smileys`,`担心,冷汗`],[`😱`,`face screaming in fear`,`smileys`,`尖叫,害怕,恐怖`],[`😲`,`astonished face`,`smileys`,`震惊,惊讶`],[`😳`,`flushed face`,`smileys`,`脸红,害羞,震惊`],[`😴`,`sleeping face`,`smileys`,`睡觉,睡觉`],[`😵`,`dizzy face`,`smileys`,`晕,头晕,死`],[`😶`,`face without mouth`,`smileys`,`沉默,无语`],[`😷`,`face with medical mask`,`smileys`,`生病,口罩,感冒`],[`😸`,`grinning cat face with smiling eyes`,`smileys`,`猫,笑脸`],[`😹`,`cat face with tears of joy`,`smileys`,`猫,笑哭`],[`😺`,`smiling cat face with open mouth`,`smileys`,`猫,笑脸,开心`],[`😻`,`smiling cat face with heart-shaped eyes`,`smileys`,`猫,爱,喜欢`],[`😼`,`cat face with wry smile`,`smileys`,`猫,坏笑`],[`😽`,`kissing cat face with closed eyes`,`smileys`,`猫,亲亲`],[`😾`,`pouting cat face`,`smileys`,`猫,生气`],[`😿`,`crying cat face`,`smileys`,`猫,哭,伤心`],[`🙀`,`weary cat face`,`smileys`,`猫,震惊,害怕`],[`🙁`,`slightly frowning face`,`smileys`,`难过,失望`],[`🙂`,`slightly smiling face`,`smileys`,`微笑,笑`],[`🙃`,`upside-down face`,`smileys`,`微笑,倒`],[`🙄`,`face with rolling eyes`,`smileys`,`翻白眼,无语`],[`🙅`,`face with no good gesture`,`smileys`,``],[`🙆`,`face with ok gesture`,`smileys`,``],[`🙇`,`person bowing deeply`,`smileys`,``],[`🙈`,`see-no-evil monkey`,`smileys`,``],[`🙉`,`hear-no-evil monkey`,`smileys`,``],[`🙊`,`speak-no-evil monkey`,`smileys`,``],[`🙋`,`happy person raising one hand`,`smileys`,``],[`🙌`,`person raising both hands in celebration`,`smileys`,`欢呼,举起,庆祝`],[`🙍`,`person frowning`,`smileys`,``],[`🙎`,`person with pouting face`,`smileys`,``],[`🙏`,`person with folded hands`,`smileys`,`祈祷,拜托,感谢,合十`],[`🚀`,`rocket`,`travel`,`火箭,发射,太空`],[`🚁`,`helicopter`,`travel`,`直升机`],[`🚂`,`steam locomotive`,`travel`,`火车,蒸汽火车`],[`🚃`,`railway car`,`travel`,`电车,火车`],[`🚄`,`high-speed train`,`travel`,`高铁,动车,火车`],[`🚅`,`high-speed train with bullet nose`,`travel`,``],[`🚆`,`train`,`travel`,`火车,铁路`],[`🚇`,`metro`,`travel`,`地铁,地铁站`],[`🚈`,`light rail`,`travel`,`轻轨,轨道交通`],[`🚉`,`station`,`travel`,`火车站,车站`],[`🚊`,`tram`,`travel`,`电车`],[`🚋`,`tram car`,`travel`,`电车,有轨电车`],[`🚌`,`bus`,`travel`,`公交车,巴士`],[`🚍`,`oncoming bus`,`travel`,`公交车`],[`🚎`,`trolleybus`,`travel`,`无轨电车,巴士`],[`🚏`,`bus stop`,`travel`,`公交站,车站`],[`🚐`,`minibus`,`travel`,`面包车,小巴`],[`🚑`,`ambulance`,`travel`,`救护车,急救`],[`🚒`,`fire engine`,`travel`,`消防车,救火`],[`🚓`,`police car`,`travel`,`警车,警察`],[`🚔`,`oncoming police car`,`travel`,`警车,巡逻`],[`🚕`,`taxi`,`travel`,`出租车,的士`],[`🚖`,`oncoming taxi`,`travel`,`出租车`],[`🚗`,`automobile`,`travel`,`汽车,轿车,车`],[`🚘`,`oncoming automobile`,`travel`,`汽车`],[`🚙`,`recreational vehicle`,`travel`,`SUV,越野车,汽车`],[`🚚`,`delivery truck`,`travel`,`卡车,货车`],[`🚛`,`articulated lorry`,`travel`,`卡车,货车`],[`🚜`,`tractor`,`travel`,`拖拉机,农用`],[`🚝`,`monorail`,`travel`,`单轨,单轨列车`],[`🚞`,`mountain railway`,`travel`,`火车,山区铁路`],[`🚟`,`suspension railway`,`travel`,`缆车,悬挂列车`],[`🚠`,`mountain cableway`,`travel`,`缆车,高山`],[`🚡`,`aerial tramway`,`travel`,`缆车,索道`],[`🚢`,`ship`,`travel`,`轮船,船,大海`],[`🚣`,`rowboat`,`travel`,``],[`🚤`,`speedboat`,`travel`,`快艇,汽艇`],[`🚥`,`horizontal traffic light`,`travel`,`红绿灯,交通信号灯`],[`🚦`,`vertical traffic light`,`travel`,`红绿灯,信号灯`],[`🚧`,`construction sign`,`travel`,`施工,施工中,路障`],[`🚨`,`police cars revolving light`,`travel`,`警车灯,警报,紧急`],[`🚩`,`triangular flag on post`,`travel`,`红旗,旗帜,标志`],[`🚪`,`door`,`travel`,`门,房门`],[`🚫`,`no entry sign`,`travel`,``],[`🚬`,`smoking symbol`,`travel`,`香烟,烟,吸烟`],[`🚭`,`no smoking symbol`,`travel`,``],[`🚮`,`put litter in its place symbol`,`travel`,`垃圾,清理`],[`🚯`,`do not litter symbol`,`travel`,``],[`🚰`,`potable water symbol`,`travel`,``],[`🚱`,`non-potable water symbol`,`travel`,``],[`🚲`,`bicycle`,`travel`,`自行车,单车,骑行`],[`🚳`,`no bicycles`,`travel`,``],[`🚴`,`bicyclist`,`travel`,``],[`🚵`,`mountain bicyclist`,`travel`,``],[`🚶`,`pedestrian`,`travel`,`走路,步行,散步`],[`🚷`,`no pedestrians`,`travel`,``],[`🚸`,`children crossing`,`travel`,``],[`🚹`,`mens symbol`,`travel`,``],[`🚺`,`womens symbol`,`travel`,``],[`🚻`,`restroom`,`travel`,``],[`🚼`,`baby symbol`,`travel`,``],[`🚽`,`toilet`,`travel`,`马桶,厕所,卫生间`],[`🚾`,`water closet`,`travel`,``],[`🚿`,`shower`,`travel`,`淋浴,洗澡`],[`🛀`,`bath`,`travel`,`泡澡`],[`🛁`,`bathtub`,`travel`,`浴缸,洗澡,泡澡`],[`🛂`,`passport control`,`travel`,``],[`🛃`,`customs`,`travel`,``],[`🛄`,`baggage claim`,`travel`,``],[`🛅`,`left luggage`,`travel`,``],[`🛋`,`couch and lamp`,`travel`,``],[`🛌`,`sleeping accommodation`,`travel`,`睡觉`],[`🛍`,`shopping bags`,`travel`,``],[`🛎`,`bellhop bell`,`travel`,``],[`🛏`,`bed`,`travel`,``],[`🛐`,`place of worship`,`travel`,``],[`🛑`,`octagonal sign`,`travel`,`停止,停车,红圈`],[`🛒`,`shopping trolley`,`travel`,`购物车,购物`],[`🛕`,`hindu temple`,`travel`,`印度教神庙`],[`🛖`,`hut`,`travel`,`草屋,小屋`],[`🛗`,`elevator`,`travel`,``],[`🛜`,`wireless`,`travel`,``],[`🛝`,`playground slide`,`travel`,``],[`🛞`,`wheel`,`travel`,`车轮,轮胎`],[`🛟`,`ring buoy`,`travel`,`救生圈,救生`],[`🛠`,`hammer and wrench`,`travel`,``],[`🛡`,`shield`,`travel`,``],[`🛢`,`oil drum`,`travel`,``],[`🛣`,`motorway`,`travel`,``],[`🛤`,`railway track`,`travel`,``],[`🛥`,`motor boat`,`travel`,``],[`🛩`,`small airplane`,`travel`,``],[`🛫`,`airplane departure`,`travel`,`起飞,飞机,出发`],[`🛬`,`airplane arriving`,`travel`,`降落,飞机,到达`],[`🛰`,`satellite`,`travel`,``],[`🛳`,`passenger ship`,`travel`,``],[`🛴`,`scooter`,`travel`,`滑板车,平衡车`],[`🛵`,`motor scooter`,`travel`,`摩托车,电动车,踏板车`],[`🛶`,`canoe`,`travel`,`独木舟,皮划艇`],[`🛷`,`sled`,`travel`,`雪橇,雪车`],[`🛸`,`flying saucer`,`travel`,`飞碟,UFO,外星人`],[`🛹`,`skateboard`,`travel`,`滑板`],[`🛺`,`auto rickshaw`,`travel`,`三轮车,突突车`],[`🛻`,`pickup truck`,`travel`,`皮卡,卡车`],[`🛼`,`roller skate`,`travel`,`轮滑`],[`🟠`,`large orange circle`,`symbols`,``],[`🟡`,`large yellow circle`,`symbols`,``],[`🟢`,`large green circle`,`symbols`,``],[`🟣`,`large purple circle`,`symbols`,``],[`🟤`,`large brown circle`,`symbols`,``],[`🟥`,`large red square`,`symbols`,``],[`🟦`,`large blue square`,`symbols`,``],[`🟧`,`large orange square`,`symbols`,``],[`🟨`,`large yellow square`,`symbols`,``],[`🟩`,`large green square`,`symbols`,``],[`🟪`,`large purple square`,`symbols`,``],[`🟫`,`large brown square`,`symbols`,``],[`🟰`,`heavy equals sign`,`symbols`,``],[`🤌`,`pinched fingers`,`symbols`,`手指,捏,意大利`],[`🤍`,`white heart`,`symbols`,`白心,白色,爱心`],[`🤎`,`brown heart`,`symbols`,`棕心,棕色,爱心`],[`🤏`,`pinching hand`,`symbols`,`捏,一点点,微小`],[`🤐`,`zipper-mouth face`,`smileys`,`闭嘴,不说`],[`🤑`,`money-mouth face`,`smileys`,`发财,金钱,贪婪`],[`🤒`,`face with thermometer`,`smileys`,`发烧,生病,温度计`],[`🤓`,`nerd face`,`smileys`,`书呆子,眼镜`],[`🤔`,`thinking face`,`smileys`,`思考,疑问,想`],[`🤕`,`face with head-bandage`,`smileys`,`受伤,包扎,头`],[`🤖`,`robot face`,`smileys`,`机器人,AI,机械`],[`🤗`,`hugging face`,`smileys`,`拥抱,欢迎`],[`🤘`,`sign of the horns`,`smileys`,`摇滚,手势,牛`],[`🤙`,`call me hand`,`smileys`,`打电话,挂,酷`],[`🤚`,`raised back of hand`,`smileys`,`手,举手,停`],[`🤛`,`left-facing fist`,`smileys`,`拳头,左边`],[`🤜`,`right-facing fist`,`smileys`,`拳头,右边`],[`🤝`,`handshake`,`smileys`,`握手,合作,协议`],[`🤞`,`hand with index and middle fingers crossed`,`smileys`,`祈祷,好运,手指交叉`],[`🤟`,`i love you hand sign`,`smileys`,`爱你,摇滚`],[`🤠`,`face with cowboy hat`,`smileys`,`牛仔,帽子`],[`🤡`,`clown face`,`smileys`,`小丑,马戏团`],[`🤢`,`nauseated face`,`smileys`,`恶心,呕吐`],[`🤣`,`rolling on the floor laughing`,`smileys`,`笑哭,大笑,笑`],[`🤤`,`drooling face`,`smileys`,`流口水,馋`],[`🤥`,`lying face`,`smileys`,`说谎,撒谎`],[`🤦`,`face palm`,`smileys`,`捂脸,无奈,扶额`],[`🤧`,`sneezing face`,`smileys`,`打喷嚏,感冒`],[`🤨`,`face with one eyebrow raised`,`symbols`,`怀疑,挑眉`],[`🤩`,`grinning face with star eyes`,`symbols`,`星星眼,兴奋,惊讶`],[`🤪`,`grinning face with one large and one small eye`,`symbols`,`疯狂,搞怪`],[`🤫`,`face with finger covering closed lips`,`symbols`,`嘘,安静`],[`🤬`,`serious face with symbols covering mouth`,`symbols`,`骂人,脏话,生气`],[`🤭`,`smiling face with smiling eyes and hand covering mouth`,`symbols`,`捂嘴,偷笑,惊讶`],[`🤮`,`face with open mouth vomiting`,`symbols`,`呕吐,恶心`],[`🤯`,`shocked face with exploding head`,`smileys`,`爆炸,震惊,头炸`],[`🤰`,`pregnant woman`,`people`,`孕妇,怀孕`],[`🤱`,`breast-feeding`,`people`,``],[`🤲`,`palms up together`,`people`,``],[`🤳`,`selfie`,`people`,`自拍,拍照`],[`🤴`,`prince`,`people`,`王子,国王`],[`🤵`,`man in tuxedo`,`people`,`新郎,西装,燕尾服`],[`🤶`,`mother christmas`,`people`,`圣诞奶奶,圣诞老人`],[`🤷`,`shrug`,`people`,`耸肩,无奈,不知道`],[`🤸`,`person doing cartwheel`,`people`,`翻跟头,体操,空翻`],[`🤹`,`juggling`,`people`,`杂耍`],[`🤺`,`fencer`,`people`,`击剑,剑术`],[`🤼`,`wrestlers`,`activity`,`摔跤,格斗`],[`🤽`,`water polo`,`activity`,``],[`🤾`,`handball`,`activity`,``],[`🤿`,`diving mask`,`activity`,`潜水面罩,潜水`],[`🥀`,`wilted flower`,`symbols`,``],[`🥁`,`drum with drumsticks`,`symbols`,`鼓,打鼓,乐器`],[`🥂`,`clinking glasses`,`symbols`,`干杯,香槟杯`],[`🥃`,`tumbler glass`,`symbols`,`威士忌,酒杯`],[`🥄`,`spoon`,`symbols`,`勺子,汤匙`],[`🥅`,`goal net`,`symbols`,`球门,网,进球`],[`🥇`,`first place medal`,`symbols`,`金牌,冠军,第一名,奖牌`],[`🥈`,`second place medal`,`symbols`,`银牌,第二名,奖牌`],[`🥉`,`third place medal`,`symbols`,`铜牌,第三名,奖牌`],[`🥊`,`boxing glove`,`symbols`,`拳击,拳击手套,打拳`],[`🥋`,`martial arts uniform`,`symbols`,`道服,武术,空手道`],[`🥌`,`curling stone`,`symbols`,`冰壶,冰壶`],[`🥍`,`lacrosse stick and ball`,`symbols`,``],[`🥎`,`softball`,`symbols`,`垒球,球`],[`🥏`,`flying disc`,`symbols`,`飞盘,飞碟`],[`🥐`,`croissant`,`food`,`牛角包,可颂`],[`🥑`,`avocado`,`food`,`牛油果,鳄梨`],[`🥒`,`cucumber`,`food`,`黄瓜`],[`🥓`,`bacon`,`food`,`培根,腊肉`],[`🥔`,`potato`,`food`,`土豆,马铃薯`],[`🥕`,`carrot`,`food`,`胡萝卜`],[`🥖`,`baguette bread`,`food`,`法棍,面包`],[`🥗`,`green salad`,`food`,`沙拉,蔬菜`],[`🥘`,`shallow pan of food`,`food`,`炖锅,海鲜饭`],[`🥙`,`stuffed flatbread`,`food`,`卷饼,肉夹馍`],[`🥚`,`egg`,`food`,`鸡蛋,蛋`],[`🥛`,`glass of milk`,`food`,`牛奶,奶`],[`🥜`,`peanuts`,`food`,``],[`🥝`,`kiwifruit`,`food`,`猕猴桃,奇异果`],[`🥞`,`pancakes`,`food`,`松饼,煎饼`],[`🥟`,`dumpling`,`food`,`饺子,锅贴`],[`🥠`,`fortune cookie`,`food`,`幸运饼干`],[`🥡`,`takeout box`,`food`,``],[`🥢`,`chopsticks`,`food`,`筷子`],[`🥣`,`bowl with spoon`,`food`,``],[`🥤`,`cup with straw`,`food`,`饮料,杯`],[`🥥`,`coconut`,`food`,`椰子`],[`🥦`,`broccoli`,`food`,`西兰花`],[`🥧`,`pie`,`food`,`派,馅饼`],[`🥨`,`pretzel`,`food`,`椒盐卷饼`],[`🥩`,`cut of meat`,`food`,`牛排,肉`],[`🥪`,`sandwich`,`food`,`三明治`],[`🥫`,`canned food`,`food`,`罐头,罐装`],[`🥬`,`leafy green`,`symbols`,`青菜,白菜,生菜`],[`🥭`,`mango`,`symbols`,`芒果`],[`🥮`,`moon cake`,`symbols`,``],[`🥯`,`bagel`,`symbols`,`贝果,面包圈`],[`🥰`,`smiling face with smiling eyes and three hearts`,`smileys`,`爱,微笑,爱心`],[`🥱`,`yawning face`,`smileys`,`打哈欠,困,无聊`],[`🥲`,`smiling face with tear`,`smileys`,``],[`🥳`,`face with party horn and party hat`,`smileys`,`庆祝,派对,欢呼`],[`🥴`,`face with uneven eyes and wavy mouth`,`smileys`,`晕,醉,头昏`],[`🥵`,`overheated face`,`smileys`,`热`],[`🥶`,`freezing face`,`smileys`,`冷`],[`🥷`,`ninja`,`people`,`忍者,忍者`],[`🥸`,`disguised face`,`symbols`,`伪装`],[`🥹`,`face holding back tears`,`symbols`,`感动,忍住,哭,泪目`],[`🥺`,`face with pleading eyes`,`smileys`,`可怜,委屈,求`],[`🥻`,`sari`,`symbols`,`纱丽,印度`],[`🥼`,`lab coat`,`symbols`,``],[`🥽`,`goggles`,`symbols`,``],[`🥾`,`hiking boot`,`symbols`,`靴子,登山鞋`],[`🥿`,`flat shoe`,`symbols`,`平底鞋,鞋`],[`🦀`,`crab`,`animals`,`螃蟹,海鲜`],[`🦁`,`lion face`,`animals`,``],[`🦂`,`scorpion`,`animals`,``],[`🦃`,`turkey`,`animals`,`火鸡,感恩节`],[`🦄`,`unicorn face`,`animals`,`独角兽,梦幻`],[`🦅`,`eagle`,`animals`,`老鹰,鹰`],[`🦆`,`duck`,`animals`,`鸭子,鸭`],[`🦇`,`bat`,`animals`,`蝙蝠`],[`🦈`,`shark`,`animals`,`鲨鱼,鱼`],[`🦉`,`owl`,`animals`,`猫头鹰,智慧`],[`🦊`,`fox face`,`animals`,``],[`🦋`,`butterfly`,`animals`,``],[`🦌`,`deer`,`animals`,`鹿,麋鹿`],[`🦍`,`gorilla`,`animals`,``],[`🦎`,`lizard`,`animals`,`蜥蜴,爬行动物`],[`🦏`,`rhinoceros`,`animals`,`犀牛`],[`🦐`,`shrimp`,`animals`,`虾,海鲜`],[`🦑`,`squid`,`animals`,`鱿鱼,海鲜`],[`🦒`,`giraffe face`,`animals`,`长颈鹿`],[`🦓`,`zebra face`,`animals`,`斑马`],[`🦔`,`hedgehog`,`animals`,`刺猬`],[`🦕`,`sauropod`,`animals`,`恐龙,雷龙`],[`🦖`,`t-rex`,`animals`,`恐龙,霸王龙`],[`🦗`,`cricket`,`animals`,``],[`🦘`,`kangaroo`,`animals`,`袋鼠`],[`🦙`,`llama`,`animals`,`羊驼,草泥马`],[`🦚`,`peacock`,`animals`,`孔雀,开屏`],[`🦛`,`hippopotamus`,`animals`,`河马`],[`🦜`,`parrot`,`animals`,`鹦鹉`],[`🦝`,`raccoon`,`animals`,`浣熊`],[`🦞`,`lobster`,`animals`,`龙虾,海鲜`],[`🦟`,`mosquito`,`animals`,``],[`🦠`,`microbe`,`animals`,``],[`🦡`,`badger`,`animals`,`獾`],[`🦢`,`swan`,`animals`,`天鹅,鹅`],[`🦣`,`mammoth`,`animals`,`猛犸象`],[`🦤`,`dodo`,`animals`,`渡渡鸟`],[`🦥`,`sloth`,`animals`,`树懒`],[`🦦`,`otter`,`animals`,`水獭`],[`🦧`,`orangutan`,`animals`,``],[`🦨`,`skunk`,`animals`,`臭鼬`],[`🦩`,`flamingo`,`animals`,`火烈鸟,红鹤`],[`🦪`,`oyster`,`animals`,`生蚝,牡蛎`],[`🦫`,`beaver`,`animals`,`河狸,海狸`],[`🦬`,`bison`,`animals`,`野牛,水牛`],[`🦭`,`seal`,`animals`,`海豹,海狮`],[`🦮`,`guide dog`,`animals`,`导盲犬,狗`],[`🦯`,`probing cane`,`symbols`,``],[`🦰`,`emoji component red hair`,`people`,`红发,头发,发色`],[`🦱`,`emoji component curly hair`,`people`,`卷发,头发`],[`🦲`,`emoji component bald`,`people`,`光头,秃头`],[`🦳`,`emoji component white hair`,`people`,`白发,头发`],[`🦴`,`bone`,`people`,``],[`🦵`,`leg`,`people`,`腿,大腿`],[`🦶`,`foot`,`people`,`脚,足`],[`🦷`,`tooth`,`people`,`牙齿,牙`],[`🦸`,`superhero`,`people`,`英雄`],[`🦹`,`supervillain`,`people`,`超级反派,坏人,反派`],[`🦺`,`safety vest`,`symbols`,``],[`🦻`,`ear with hearing aid`,`symbols`,`助听器,耳朵`],[`🦼`,`motorized wheelchair`,`people`,``],[`🦽`,`manual wheelchair`,`people`,``],[`🦾`,`mechanical arm`,`people`,`机械臂,机器人,义肢`],[`🦿`,`mechanical leg`,`people`,`机械腿,义肢`],[`🧀`,`cheese wedge`,`food`,`奶酪,芝士`],[`🧁`,`cupcake`,`food`,`纸杯蛋糕,杯子蛋糕`],[`🧂`,`salt shaker`,`food`,``],[`🧃`,`beverage box`,`food`,`果汁盒,饮料`],[`🧄`,`garlic`,`food`,`大蒜,蒜`],[`🧅`,`onion`,`food`,`洋葱`],[`🧆`,`falafel`,`food`,`鹰嘴豆丸子`],[`🧇`,`waffle`,`food`,`华夫饼`],[`🧈`,`butter`,`food`,`黄油,奶油`],[`🧉`,`mate drink`,`food`,`马黛茶`],[`🧊`,`ice cube`,`food`,`冰块,冰`],[`🧋`,`bubble tea`,`food`,`奶茶,珍珠奶茶`],[`🧌`,`troll`,`symbols`,`巨魔,妖怪`],[`🧍`,`standing person`,`symbols`,`站立,站着,人`],[`🧎`,`kneeling person`,`symbols`,`跪,跪下,祈祷`],[`🧏`,`deaf person`,`symbols`,``],[`🧐`,`face with monocle`,`people`,`检查,研究,眼镜`],[`🧑`,`adult`,`people`,`人`],[`🧒`,`child`,`people`,``],[`🧓`,`older adult`,`people`,`老人,奶奶,爷爷`],[`🧔`,`bearded person`,`people`,`胡子,胡须,大叔`],[`🧕`,`person with headscarf`,`people`,`头巾`],[`🧖`,`person in steamy room`,`people`,`桑拿,蒸汽,洗澡`],[`🧗`,`person climbing`,`people`,`攀岩`],[`🧘`,`person in lotus position`,`people`,`打坐`],[`🧙`,`mage`,`people`,`巫师,魔法师,法师`],[`🧚`,`fairy`,`people`,`仙女,精灵,小仙女`],[`🧛`,`vampire`,`people`,`吸血鬼,德古拉`],[`🧜`,`merperson`,`people`,`美人鱼,人鱼`],[`🧝`,`elf`,`people`,`精灵,耳朵`],[`🧞`,`genie`,`people`,`灯神,精灵,神灯`],[`🧟`,`zombie`,`people`,`僵尸,丧尸`],[`🧠`,`brain`,`people`,`大脑,思考,记忆,AI`],[`🧡`,`orange heart`,`people`,``],[`🧢`,`billed cap`,`people`,`棒球帽,帽子`],[`🧣`,`scarf`,`people`,`围巾,冬天`],[`🧤`,`gloves`,`people`,`手套,冬天`],[`🧥`,`coat`,`people`,`大衣,外套`],[`🧦`,`socks`,`people`,`袜子`],[`🧧`,`red gift envelope`,`objects`,`红包,利是,新年`],[`🧨`,`firecracker`,`objects`,``],[`🧩`,`jigsaw puzzle piece`,`objects`,`拼图,拼图游戏`],[`🧪`,`test tube`,`objects`,`试管,实验,化学,科学`],[`🧫`,`petri dish`,`objects`,`培养皿,实验,细菌`],[`🧬`,`dna double helix`,`objects`,`DNA,基因,生物`],[`🧭`,`compass`,`objects`,`指南针`],[`🧮`,`abacus`,`objects`,`算盘,计算`],[`🧯`,`fire extinguisher`,`objects`,`灭火器,消防`],[`🧰`,`toolbox`,`objects`,`工具箱,工具`],[`🧱`,`brick`,`objects`,`砖`],[`🧲`,`magnet`,`objects`,`磁铁,磁性`],[`🧳`,`luggage`,`objects`,`行李箱`],[`🧴`,`lotion bottle`,`objects`,`乳液,护肤,防晒`],[`🧵`,`spool of thread`,`objects`,`线,针线,缝纫`],[`🧶`,`ball of yarn`,`objects`,`毛线,织毛衣`],[`🧷`,`safety pin`,`objects`,`别针,安全别针`],[`🧸`,`teddy bear`,`objects`,`泰迪熊,玩具熊`],[`🧹`,`broom`,`objects`,`扫帚`],[`🧺`,`basket`,`objects`,`篮子`],[`🧻`,`roll of paper`,`objects`,`纸巾`],[`🧼`,`bar of soap`,`objects`,`肥皂,洗手,清洁`],[`🧽`,`sponge`,`objects`,`海绵,清洁`],[`🧾`,`receipt`,`objects`,`收据`],[`🧿`,`nazar amulet`,`objects`,`护身符`],[`🩰`,`ballet shoes`,`activity`,`芭蕾`],[`🩱`,`one-piece swimsuit`,`activity`,`泳衣`],[`🩲`,`briefs`,`activity`,`泳裤`],[`🩳`,`shorts`,`activity`,`短裤`],[`🩴`,`thong sandal`,`activity`,`凉拖`],[`🩵`,`light blue heart`,`activity`,`浅蓝`],[`🩶`,`grey heart`,`activity`,`灰心`],[`🩷`,`pink heart`,`activity`,`粉色`],[`🩸`,`drop of blood`,`activity`,`血`],[`🩹`,`adhesive bandage`,`activity`,`创可贴`],[`🩺`,`stethoscope`,`activity`,`听诊器`],[`🩻`,`x-ray`,`activity`,`X光`],[`🩼`,`crutch`,`activity`,`拐杖`],[`🪀`,`yo-yo`,`objects`,`玩具`],[`🪁`,`kite`,`objects`,`风筝`],[`🪂`,`parachute`,`objects`,`跳伞`],[`🪃`,`boomerang`,`objects`,``],[`🪄`,`magic wand`,`objects`,`魔杖,魔法,魔术`],[`🪅`,`pinata`,`objects`,`皮纳塔`],[`🪆`,`nesting dolls`,`objects`,``],[`🪇`,`maracas`,`objects`,`沙锤`],[`🪈`,`flute`,`objects`,`笛子`],[`🪐`,`ringed planet`,`objects`,``],[`🪑`,`chair`,`objects`,`椅子`],[`🪒`,`razor`,`objects`,`剃须刀,剃刀`],[`🪓`,`axe`,`objects`,`斧头,斧子`],[`🪔`,`diya lamp`,`objects`,`油灯`],[`🪕`,`banjo`,`objects`,`班卓琴`],[`🪖`,`military helmet`,`objects`,`军盔`],[`🪗`,`accordion`,`objects`,`手风琴`],[`🪘`,`long drum`,`objects`,`鼓`],[`🪙`,`coin`,`objects`,`金币`],[`🪚`,`carpentry saw`,`objects`,`锯子,锯`],[`🪛`,`screwdriver`,`objects`,`螺丝刀`],[`🪜`,`ladder`,`objects`,`梯子`],[`🪝`,`hook`,`objects`,`钩子,挂钩`],[`🪞`,`mirror`,`objects`,`镜子`],[`🪟`,`window`,`objects`,`窗户`],[`🪠`,`plunger`,`objects`,`皮搋子,通马桶`],[`🪡`,`sewing needle`,`objects`,`针,缝纫,刺绣`],[`🪢`,`knot`,`objects`,``],[`🪣`,`bucket`,`objects`,`水桶,桶`],[`🪤`,`mouse trap`,`objects`,`捕鼠器`],[`🪥`,`toothbrush`,`objects`,`牙刷,刷牙`],[`🪦`,`headstone`,`objects`,`墓碑`],[`🪧`,`placard`,`objects`,`告示牌`],[`🪨`,`rock`,`objects`,`石头,岩石`],[`🪩`,`mirror ball`,`objects`,`迪斯科球`],[`🪪`,`identification card`,`objects`,`身份证`],[`🪫`,`low battery`,`objects`,`电池,没电,低电量`],[`🪬`,`hamsa`,`objects`,`手掌印,护身符`],[`🪭`,`folding hand fan`,`objects`,``],[`🪮`,`hair pick`,`objects`,`梳子`],[`🪯`,`khanda`,`objects`,``],[`🪰`,`fly`,`objects`,`苍蝇,飞虫`],[`🪱`,`worm`,`objects`,``],[`🪲`,`beetle`,`objects`,`甲虫,昆虫`],[`🪳`,`cockroach`,`objects`,`蟑螂,虫子`],[`🪴`,`potted plant`,`objects`,`盆栽,植物,绿植`],[`🪵`,`wood`,`objects`,`木头,柴火,木`],[`🪶`,`feather`,`objects`,`羽毛,羽毛笔`],[`🪷`,`lotus`,`objects`,`莲花`],[`🪸`,`coral`,`objects`,`珊瑚`],[`🪹`,`empty nest`,`objects`,`鸟巢`],[`🪺`,`nest with eggs`,`objects`,`鸟巢`],[`🪻`,`hyacinth`,`objects`,`风信子`],[`🪼`,`jellyfish`,`objects`,`水母`],[`🪽`,`wing`,`objects`,`翅膀`],[`🪿`,`goose`,`objects`,`鹅`],[`🫀`,`anatomical heart`,`objects`,`心脏,心跳`],[`🫁`,`lungs`,`objects`,`肺,呼吸`],[`🫂`,`people hugging`,`objects`,`拥抱,人,朋友`],[`🫃`,`pregnant man`,`objects`,`孕妇,怀孕`],[`🫄`,`pregnant person`,`objects`,`孕妇,怀孕`],[`🫅`,`person with crown`,`objects`,`国王,王子,皇冠`],[`🫎`,`moose`,`objects`,`驼鹿,麋鹿`],[`🫏`,`donkey`,`objects`,`驴,动物`],[`🫐`,`blueberries`,`food`,`蓝莓`],[`🫑`,`bell pepper`,`food`,`甜椒,彩椒`],[`🫒`,`olive`,`food`,`橄榄`],[`🫓`,`flatbread`,`food`,`薄饼,饼`],[`🫔`,`tamale`,`food`,`玉米粉蒸肉`],[`🫕`,`fondue`,`food`,`奶酪火锅`],[`🫖`,`teapot`,`food`,`茶壶,茶`],[`🫗`,`pouring liquid`,`food`,`倒,倒水,水杯`],[`🫘`,`beans`,`food`,`豆子,红豆`],[`🫙`,`jar`,`food`,`罐子,玻璃罐`],[`🫚`,`ginger root`,`food`,`姜,生姜`],[`🫛`,`pea pod`,`food`,`豌豆荚,豆`],[`🫠`,`melting face`,`smileys`,`融化`],[`🫡`,`saluting face`,`smileys`,`敬礼`],[`🫢`,`face with open eyes and hand over mouth`,`smileys`,`捂眼`],[`🫣`,`face with peeking eye`,`smileys`,`偷看`],[`🫤`,`face with diagonal mouth`,`smileys`,`撇嘴`],[`🫥`,`dotted line face`,`smileys`,`隐形`],[`🫦`,`biting lip`,`smileys`,`咬唇,嘴唇`],[`🫧`,`bubbles`,`smileys`,`泡泡`],[`🫨`,`shaking face`,`smileys`,`摇晃,震动,抖`],[`🫰`,`hand with index finger and thumb crossed`,`people`,`比心,手指,捏`],[`🫱`,`rightwards hand`,`people`,`手,右边,推`],[`🫲`,`leftwards hand`,`people`,`手,左边,推`],[`🫳`,`palm down hand`,`people`,`手,向下,放`],[`🫴`,`palm up hand`,`people`,`手,向上,举`],[`🫵`,`index pointing at the viewer`,`people`,`指,你`],[`🫶`,`heart hands`,`people`,`比心,爱心,手势`],[`🫷`,`leftwards pushing hand`,`people`,`手,推,右边`],[`🫸`,`rightwards pushing hand`,`people`,`手,推,左边`],[`‼`,`double exclamation mark`,`symbols`,``],[`‼️`,`double exclamation mark`,`symbols`,``],[`⁉`,`exclamation question mark`,`symbols`,``],[`⁉️`,`exclamation question mark`,`symbols`,``],[`™`,`trade mark sign`,`symbols`,``],[`™️`,`trade mark sign`,`symbols`,``],[`ℹ`,`information source`,`symbols`,``],[`ℹ️`,`information source`,`symbols`,``],[`↔`,`left right arrow`,`symbols`,``],[`↔️`,`left right arrow`,`symbols`,``],[`↕`,`up down arrow`,`symbols`,``],[`↕️`,`up down arrow`,`symbols`,``],[`↖`,`north west arrow`,`symbols`,``],[`↖️`,`north west arrow`,`symbols`,``],[`↗`,`north east arrow`,`symbols`,``],[`↗️`,`north east arrow`,`symbols`,``],[`↘`,`south east arrow`,`symbols`,``],[`↘️`,`south east arrow`,`symbols`,``],[`↙`,`south west arrow`,`symbols`,``],[`↙️`,`south west arrow`,`symbols`,``],[`↩`,`leftwards arrow with hook`,`symbols`,``],[`↩️`,`leftwards arrow with hook`,`symbols`,``],[`↪`,`rightwards arrow with hook`,`symbols`,``],[`↪️`,`rightwards arrow with hook`,`symbols`,``],[`⌚`,`watch`,`objects`,`手表`],[`⌚️`,`watch`,`objects`,``],[`⌛`,`hourglass`,`objects`,`沙漏,时间,等待`],[`⌛️`,`hourglass`,`objects`,``],[`⌨`,`keyboard`,`symbols`,``],[`⌨️`,`keyboard`,`symbols`,`键盘,打字`],[`⏏`,`eject symbol`,`symbols`,``],[`⏏️`,`eject symbol`,`symbols`,``],[`⏩`,`black right-pointing double triangle`,`objects`,``],[`⏪`,`black left-pointing double triangle`,`objects`,``],[`⏫`,`black up-pointing double triangle`,`objects`,``],[`⏬`,`black down-pointing double triangle`,`objects`,``],[`⏭`,`black right-pointing double triangle with vertical bar`,`objects`,``],[`⏭️`,`black right-pointing double triangle with vertical bar`,`objects`,``],[`⏮`,`black left-pointing double triangle with vertical bar`,`objects`,``],[`⏮️`,`black left-pointing double triangle with vertical bar`,`objects`,``],[`⏯`,`black right-pointing triangle with double vertical bar`,`objects`,``],[`⏯️`,`black right-pointing triangle with double vertical bar`,`objects`,``],[`⏰`,`alarm clock`,`objects`,`闹钟,时间,起床`],[`⏱`,`stopwatch`,`objects`,``],[`⏱️`,`stopwatch`,`objects`,`秒表`],[`⏲`,`timer clock`,`objects`,``],[`⏲️`,`timer clock`,`objects`,`计时器`],[`⏳`,`hourglass with flowing sand`,`objects`,`沙漏`],[`⏸`,`double vertical bar`,`symbols`,``],[`⏸️`,`double vertical bar`,`symbols`,``],[`⏹`,`black square for stop`,`symbols`,``],[`⏹️`,`black square for stop`,`symbols`,``],[`⏺`,`black circle for record`,`symbols`,``],[`⏺️`,`black circle for record`,`symbols`,``],[`Ⓜ`,`circled latin capital letter m`,`symbols`,``],[`Ⓜ️`,`circled latin capital letter m`,`symbols`,``],[`▪`,`black small square`,`symbols`,``],[`▪️`,`black small square`,`symbols`,``],[`▫`,`white small square`,`symbols`,``],[`▫️`,`white small square`,`symbols`,``],[`▶`,`black right-pointing triangle`,`symbols`,``],[`▶️`,`black right-pointing triangle`,`symbols`,``],[`◀`,`black left-pointing triangle`,`symbols`,``],[`◀️`,`black left-pointing triangle`,`symbols`,``],[`◻`,`white medium square`,`symbols`,``],[`◻️`,`white medium square`,`symbols`,``],[`◼`,`black medium square`,`symbols`,``],[`◼️`,`black medium square`,`symbols`,``],[`◽`,`white medium small square`,`symbols`,``],[`◾`,`black medium small square`,`symbols`,``],[`◾️`,`black medium small square`,`symbols`,``],[`☀`,`black sun with rays`,`symbols`,``],[`☀️`,`black sun with rays`,`symbols`,`太阳,晴天,阳光`],[`☁`,`cloud`,`symbols`,``],[`☁️`,`cloud`,`symbols`,`云,多云,天气`],[`☂`,`umbrella`,`symbols`,``],[`☂️`,`umbrella`,`symbols`,``],[`☃`,`snowman`,`symbols`,``],[`☃️`,`snowman`,`symbols`,`雪人,冬天,雪`],[`☄`,`comet`,`symbols`,``],[`☄️`,`comet`,`symbols`,``],[`☎`,`black telephone`,`symbols`,``],[`☎️`,`black telephone`,`symbols`,`电话`],[`☑`,`ballot box with check`,`symbols`,``],[`☑️`,`ballot box with check`,`symbols`,``],[`☔`,`umbrella with rain drops`,`symbols`,``],[`☔️`,`umbrella with rain drops`,`symbols`,``],[`☕`,`hot beverage`,`food`,`咖啡,热饮`],[`☕️`,`hot beverage`,`food`,``],[`☘`,`shamrock`,`symbols`,``],[`☘️`,`shamrock`,`symbols`,``],[`☝`,`white up pointing index`,`symbols`,``],[`☝️`,`white up pointing index`,`symbols`,`指,上面,向上`],[`☠`,`skull and crossbones`,`symbols`,``],[`☠️`,`skull and crossbones`,`symbols`,`骷髅,死亡,危险`],[`☢`,`radioactive sign`,`symbols`,``],[`☢️`,`radioactive sign`,`symbols`,``],[`☣`,`biohazard sign`,`symbols`,``],[`☣️`,`biohazard sign`,`symbols`,``],[`☦`,`orthodox cross`,`symbols`,``],[`☦️`,`orthodox cross`,`symbols`,``],[`☪`,`star and crescent`,`symbols`,``],[`☪️`,`star and crescent`,`symbols`,``],[`☮`,`peace symbol`,`symbols`,``],[`☮️`,`peace symbol`,`symbols`,``],[`☯`,`yin yang`,`symbols`,``],[`☯️`,`yin yang`,`symbols`,``],[`☸`,`wheel of dharma`,`symbols`,``],[`☸️`,`wheel of dharma`,`symbols`,``],[`☹`,`white frowning face`,`smileys`,``],[`☹️`,`white frowning face`,`smileys`,``],[`☺`,`white smiling face`,`smileys`,``],[`☺️`,`white smiling face`,`smileys`,``],[`♀`,`female sign`,`symbols`,``],[`♀️`,`female sign`,`symbols`,``],[`♂`,`male sign`,`symbols`,``],[`♂️`,`male sign`,`symbols`,``],[`♈`,`aries`,`symbols`,``],[`♈️`,`aries`,`symbols`,``],[`♉`,`taurus`,`symbols`,``],[`♉️`,`taurus`,`symbols`,``],[`♊`,`gemini`,`symbols`,``],[`♊️`,`gemini`,`symbols`,``],[`♋`,`cancer`,`symbols`,``],[`♋️`,`cancer`,`symbols`,``],[`♌`,`leo`,`symbols`,``],[`♌️`,`leo`,`symbols`,``],[`♍`,`virgo`,`symbols`,``],[`♍️`,`virgo`,`symbols`,``],[`♎`,`libra`,`symbols`,``],[`♎️`,`libra`,`symbols`,``],[`♏`,`scorpius`,`symbols`,``],[`♏️`,`scorpius`,`symbols`,``],[`♐`,`sagittarius`,`symbols`,``],[`♐️`,`sagittarius`,`symbols`,``],[`♑`,`capricorn`,`symbols`,``],[`♑️`,`capricorn`,`symbols`,``],[`♒`,`aquarius`,`symbols`,``],[`♒️`,`aquarius`,`symbols`,``],[`♓`,`pisces`,`symbols`,``],[`♓️`,`pisces`,`symbols`,``],[`♟`,`black chess pawn`,`symbols`,``],[`♟️`,`black chess pawn`,`symbols`,`棋子,国际象棋,象棋`],[`♠`,`black spade suit`,`symbols`,``],[`♠️`,`black spade suit`,`symbols`,``],[`♣`,`black club suit`,`symbols`,``],[`♣️`,`black club suit`,`symbols`,``],[`♥`,`black heart suit`,`symbols`,``],[`♥️`,`black heart suit`,`symbols`,``],[`♦`,`black diamond suit`,`symbols`,``],[`♦️`,`black diamond suit`,`symbols`,``],[`♨`,`hot springs`,`symbols`,``],[`♨️`,`hot springs`,`symbols`,`温泉,热泉`],[`♻`,`black universal recycling symbol`,`symbols`,``],[`♻️`,`black universal recycling symbol`,`symbols`,``],[`♾`,`permanent paper sign`,`symbols`,``],[`♾️`,`permanent paper sign`,`symbols`,``],[`♿`,`wheelchair symbol`,`symbols`,``],[`♿️`,`wheelchair symbol`,`symbols`,``],[`⚒`,`hammer and pick`,`symbols`,``],[`⚒️`,`hammer and pick`,`symbols`,`锤子,工具`],[`⚓`,`anchor`,`symbols`,`锚,航海,停泊`],[`⚔`,`crossed swords`,`symbols`,``],[`⚔️`,`crossed swords`,`symbols`,`剑,交叉,战斗`],[`⚕`,`staff of aesculapius`,`symbols`,``],[`⚕️`,`staff of aesculapius`,`symbols`,``],[`⚖`,`scales`,`symbols`,``],[`⚖️`,`scales`,`symbols`,``],[`⚗`,`alembic`,`symbols`,``],[`⚗️`,`alembic`,`symbols`,``],[`⚙`,`gear`,`symbols`,``],[`⚙️`,`gear`,`symbols`,``],[`⚛`,`atom symbol`,`symbols`,``],[`⚛️`,`atom symbol`,`symbols`,``],[`⚜`,`fleur-de-lis`,`symbols`,``],[`⚜️`,`fleur-de-lis`,`symbols`,``],[`⚠`,`warning sign`,`symbols`,``],[`⚠️`,`warning sign`,`symbols`,``],[`⚡`,`high voltage sign`,`symbols`,``],[`⚧`,`male with stroke and male and female sign`,`symbols`,``],[`⚧️`,`male with stroke and male and female sign`,`symbols`,``],[`⚪`,`medium white circle`,`symbols`,``],[`⚪️`,`medium white circle`,`symbols`,``],[`⚫`,`medium black circle`,`symbols`,``],[`⚰`,`coffin`,`symbols`,``],[`⚰️`,`coffin`,`symbols`,`棺材,死亡`],[`⚱`,`funeral urn`,`symbols`,``],[`⚱️`,`funeral urn`,`symbols`,`骨灰盒,死亡`],[`⚽`,`soccer ball`,`activity`,`足球,球`],[`⚽️`,`soccer ball`,`activity`,``],[`⚾`,`baseball`,`activity`,`棒球,球`],[`⚾️`,`baseball`,`activity`,``],[`⛄`,`snowman without snow`,`symbols`,`雪人,冬天`],[`⛄️`,`snowman without snow`,`symbols`,``],[`⛅`,`sun behind cloud`,`symbols`,`太阳,云,多云`],[`⛈`,`thunder cloud and rain`,`symbols`,``],[`⛈️`,`thunder cloud and rain`,`symbols`,`雷雨,雷暴,天气`],[`⛎`,`ophiuchus`,`symbols`,``],[`⛏`,`pick`,`symbols`,``],[`⛏️`,`pick`,`symbols`,`镐,工具`],[`⛑`,`helmet with white cross`,`symbols`,``],[`⛑️`,`helmet with white cross`,`symbols`,`头盔,救援,安全`],[`⛓`,`chains`,`symbols`,``],[`⛓️`,`chains`,`symbols`,``],[`⛔`,`no entry`,`symbols`,``],[`⛩`,`shinto shrine`,`travel`,``],[`⛩️`,`shinto shrine`,`travel`,`鸟居,神社,日本`],[`⛪`,`church`,`travel`,`教堂`],[`⛰`,`mountain`,`travel`,``],[`⛰️`,`mountain`,`travel`,`山,山峰`],[`⛱`,`umbrella on ground`,`travel`,``],[`⛱️`,`umbrella on ground`,`travel`,``],[`⛲`,`fountain`,`travel`,`喷泉`],[`⛲️`,`fountain`,`travel`,``],[`⛳`,`flag in hole`,`activity`,`高尔夫,高尔夫球,球洞`],[`⛳️`,`flag in hole`,`activity`,``],[`⛴`,`ferry`,`travel`,``],[`⛴️`,`ferry`,`travel`,`渡轮,船`],[`⛵`,`sailboat`,`travel`,`帆船,船`],[`⛵️`,`sailboat`,`travel`,``],[`⛷`,`skier`,`activity`,``],[`⛷️`,`skier`,`activity`,``],[`⛸`,`ice skate`,`activity`,``],[`⛸️`,`ice skate`,`activity`,`溜冰,冰刀,滑冰`],[`⛹`,`person with ball`,`activity`,``],[`⛹️`,`person with ball`,`activity`,``],[`⛺`,`tent`,`travel`,`帐篷,露营`],[`⛺️`,`tent`,`travel`,``],[`⛽`,`fuel pump`,`travel`,`加油站,加油,汽油`],[`✂`,`black scissors`,`symbols`,``],[`✂️`,`black scissors`,`symbols`,``],[`✅`,`white heavy check mark`,`symbols`,``],[`✈`,`airplane`,`travel`,``],[`✈️`,`airplane`,`travel`,`飞机,航班,起飞`],[`✉`,`envelope`,`symbols`,``],[`✉️`,`envelope`,`symbols`,`信封,邮件,信`],[`✊`,`raised fist`,`people`,`拳头,加油,力量`],[`✋`,`raised hand`,`people`,`手,举手,停`],[`✌`,`victory hand`,`symbols`,``],[`✌️`,`victory hand`,`symbols`,`胜利,耶,剪刀手`],[`✍`,`writing hand`,`symbols`,``],[`✍️`,`writing hand`,`symbols`,`写字,写作,手`],[`✏`,`pencil`,`symbols`,``],[`✏️`,`pencil`,`symbols`,``],[`✒`,`black nib`,`symbols`,``],[`✒️`,`black nib`,`symbols`,``],[`✔`,`heavy check mark`,`symbols`,``],[`✔️`,`heavy check mark`,`symbols`,``],[`✖`,`heavy multiplication x`,`symbols`,``],[`✖️`,`heavy multiplication x`,`symbols`,``],[`✝`,`latin cross`,`symbols`,``],[`✝️`,`latin cross`,`symbols`,``],[`✡`,`star of david`,`symbols`,``],[`✡️`,`star of david`,`symbols`,``],[`✨`,`sparkles`,`symbols`,`星星,闪光,发光`],[`✳`,`eight spoked asterisk`,`symbols`,``],[`✳️`,`eight spoked asterisk`,`symbols`,``],[`✴`,`eight pointed black star`,`symbols`,``],[`✴️`,`eight pointed black star`,`symbols`,``],[`❄`,`snowflake`,`symbols`,``],[`❄️`,`snowflake`,`symbols`,`雪花,雪,冬天,冷`],[`❇`,`sparkle`,`symbols`,``],[`❇️`,`sparkle`,`symbols`,``],[`❌`,`cross mark`,`symbols`,``],[`❎`,`negative squared cross mark`,`symbols`,``],[`❓`,`black question mark ornament`,`symbols`,``],[`❔`,`white question mark ornament`,`symbols`,``],[`❕`,`white exclamation mark ornament`,`symbols`,``],[`❗`,`heavy exclamation mark symbol`,`symbols`,``],[`❗️`,`heavy exclamation mark symbol`,`symbols`,``],[`❣`,`heavy heart exclamation mark ornament`,`symbols`,``],[`❣️`,`heavy heart exclamation mark ornament`,`symbols`,`爱心,感叹号`],[`❤`,`heavy black heart`,`smileys`,``],[`❤️`,`heavy black heart`,`smileys`,`爱心,红心,爱`],[`➕`,`heavy plus sign`,`symbols`,``],[`➖`,`heavy minus sign`,`symbols`,``],[`➗`,`heavy division sign`,`symbols`,``],[`➡`,`black rightwards arrow`,`symbols`,``],[`➡️`,`black rightwards arrow`,`symbols`,``],[`➰`,`curly loop`,`symbols`,``],[`➿`,`double curly loop`,`symbols`,``],[`⬅`,`leftwards black arrow`,`symbols`,``],[`⬅️`,`leftwards black arrow`,`symbols`,``],[`⬆`,`upwards black arrow`,`symbols`,``],[`⬆️`,`upwards black arrow`,`symbols`,``],[`⬇`,`downwards black arrow`,`symbols`,``],[`⬇️`,`downwards black arrow`,`symbols`,``],[`⬛`,`black large square`,`symbols`,``],[`⬛️`,`black large square`,`symbols`,``],[`⬜`,`white large square`,`symbols`,``],[`⬜️`,`white large square`,`symbols`,``],[`⭐`,`white medium star`,`symbols`,`星星,五星,评分`],[`⭕`,`heavy large circle`,`symbols`,``],[`⭕️`,`heavy large circle`,`symbols`,``],[`⤴`,`arrow pointing rightwards then curving upwards`,`symbols`,``],[`⤴️`,`arrow pointing rightwards then curving upwards`,`symbols`,``],[`⤵`,`arrow pointing rightwards then curving downwards`,`symbols`,``],[`⤵️`,`arrow pointing rightwards then curving downwards`,`symbols`,``],[`〰`,`wavy dash`,`symbols`,``],[`〰️`,`wavy dash`,`symbols`,``],[`〽`,`part alternation mark`,`symbols`,``],[`〽️`,`part alternation mark`,`symbols`,``],[`㊗`,`circled ideograph congratulation`,`symbols`,``],[`㊗️`,`circled ideograph congratulation`,`symbols`,``],[`㊙`,`circled ideograph secret`,`symbols`,``],[`㊙️`,`circled ideograph secret`,`symbols`,``],[`©`,`copyright sign`,`symbols`,``],[`©️`,`copyright sign`,`symbols`,``],[`®`,`registered sign`,`symbols`,``],[`®️`,`registered sign`,`symbols`,``],[`👨💻`,`man technologist`,`people`,`程序员,开发者,工程师,码农`],[`👩💻`,`woman technologist`,`people`,`程序员,开发者,工程师`],[`🧑💻`,`technologist`,`people`,`程序员,开发者,工程师`],[`👨🔧`,`man mechanic`,`people`,``],[`👩🔧`,`woman mechanic`,`people`,``],[`👨🎨`,`man artist`,`people`,``],[`👩🎨`,`woman artist`,`people`,``],[`👨🚀`,`man astronaut`,`people`,``],[`👩🚀`,`woman astronaut`,`people`,``],[`👨⚕️`,`man health worker`,`people`,``],[`👩⚕️`,`woman health worker`,`people`,``],[`👨🏫`,`man teacher`,`people`,``],[`👩🏫`,`woman teacher`,`people`,``],[`👨🍳`,`man cook`,`people`,``],[`👩🍳`,`woman cook`,`people`,``],[`👨🌾`,`man farmer`,`people`,``],[`👩🌾`,`woman farmer`,`people`,``],[`👩🏭`,`woman factory worker`,`people`,``],[`👨🎓`,`man student`,`people`,``],[`👩🎓`,`woman student`,`people`,``],[`👨🚒`,`man firefighter`,`people`,``],[`👩🚒`,`woman firefighter`,`people`,``],[`👨⚖️`,`man judge`,`people`,``],[`👩⚖️`,`woman judge`,`people`,``],[`👨💼`,`man office worker`,`people`,``],[`👩💼`,`woman office worker`,`people`,``],[`👨🎤`,`man singer`,`people`,``],[`👩🎤`,`woman singer`,`people`,``],[`👨🦰`,`man red hair`,`people`,``],[`👩🦰`,`woman red hair`,`people`,``],[`👨🦱`,`man curly hair`,`people`,``],[`👩🦱`,`woman curly hair`,`people`,``],[`👩🦲`,`woman bald`,`people`,``],[`👨🦳`,`man white hair`,`people`,``],[`👩🦳`,`woman white hair`,`people`,``],[`👩❤️👨`,`couple with heart`,`people`,``],[`👨❤️👨`,`couple with heart`,`people`,``],[`👩❤️👩`,`couple with heart`,`people`,``],[`👨👩👧`,`family man woman girl`,`people`,``],[`👨👩👦`,`family man woman boy`,`people`,``],[`👨👩👧👦`,`family man woman girl boy`,`people`,``],[`👨👩👦👦`,`man`,`people`,``],[`👨👩👧👧`,`family man woman girl girl`,`people`,``],[`👩👩👧`,`family woman woman girl`,`people`,``],[`👨👨👧`,`family man man girl`,`people`,``],[`👨👦`,`family man boy`,`people`,``],[`👩👧`,`family woman girl`,`people`,``],[`👨👧👦`,`family man girl boy`,`people`,``],[`👩❤️💋👨`,`kiss woman man`,`people`,``],[`🧑🤝🧑`,`people holding hands`,`people`,``],[`❤️🔥`,`heart on fire`,`smileys`,``],[`🧑🚒`,`firefighter`,`people`,`消防员`],[`🧑🏭`,`factory worker`,`people`,``],[`🧑🎓`,`student`,`people`,`学生,毕业生,大学生`],[`🧑🏫`,`teacher`,`people`,`老师,教师,教授`],[`🧑🎤`,`singer`,`people`,`歌手,歌星`],[`🧑⚕️`,`health worker`,`people`,`医生,医疗`],[`🧑⚖️`,`judge`,`people`,`法官,审判`],[`🧑🍳`,`cook`,`people`,`厨师,大厨`],[`🧑🌾`,`farmer`,`people`,`农民,农夫`],[`🧑🎨`,`artist`,`people`,`画家,艺术家`],[`🧑🔬`,`scientist`,`people`,``],[`🧑🔧`,`mechanic`,`people`,`技工,维修工`],[`🧑💼`,`office worker`,`people`,`白领,上班族,职员`],[`🧑🚀`,`astronaut`,`people`,`宇航员,太空人`],[`🏃♂️`,`man running`,`activity`,``],[`🏃♀️`,`woman running`,`activity`,``],[`🚶♂️`,`man walking`,`travel`,``],[`🚶♀️`,`woman walking`,`travel`,``],[`🧎♂️`,`man kneeling`,`symbols`,``],[`🧎♀️`,`woman kneeling`,`symbols`,``],[`🏋️♂️`,`man lifting weights`,`activity`,``],[`🏋️♀️`,`woman lifting weights`,`activity`,``],[`🤸♂️`,`man cartwheeling`,`people`,``],[`🤸♀️`,`woman cartwheeling`,`people`,``],[`⛹️♂️`,`man bouncing ball`,`activity`,``],[`⛹️♀️`,`woman bouncing ball`,`activity`,``],[`🤾♂️`,`man playing handball`,`activity`,``],[`🤾♀️`,`woman playing handball`,`activity`,``],[`🧘♀️`,`woman in lotus position`,`people`,``],[`🏄♂️`,`man surfing`,`activity`,``],[`🏄♀️`,`woman surfing`,`activity`,``],[`🏊♂️`,`man swimming`,`activity`,``],[`🏊♀️`,`woman swimming`,`activity`,``],[`🚴♂️`,`man biking`,`travel`,``],[`🚴♀️`,`woman biking`,`travel`,``],[`🚵♂️`,`man mountain biking`,`travel`,``],[`🚵♀️`,`woman mountain biking`,`travel`,``],[`👯♂️`,`men with bunny ears`,`people`,``],[`👯♀️`,`women with bunny ears`,`people`,``],[`🧖♂️`,`man in steamy room`,`people`,``],[`🧖♀️`,`woman in steamy room`,`people`,``],[`🧗♂️`,`man climbing`,`people`,``],[`🧗♀️`,`woman climbing`,`people`,``],[`🤦♂️`,`man facepalming`,`smileys`,``],[`🤦♀️`,`woman facepalming`,`smileys`,``],[`🤷♂️`,`man shrugging`,`people`,``],[`🤷♀️`,`woman shrugging`,`people`,``],[`🙍♂️`,`person frowning`,`smileys`,``],[`🙍♀️`,`woman frowning`,`smileys`,``],[`🙎♂️`,`man pouting`,`smileys`,``],[`🙎♀️`,`woman pouting`,`smileys`,``],[`🙅♂️`,`man gesturing no`,`smileys`,``],[`🙅♀️`,`woman gesturing no`,`smileys`,``],[`🙆♂️`,`man gesturing ok`,`smileys`,``],[`🙆♀️`,`woman gesturing ok`,`smileys`,``],[`💁♂️`,`man tipping hand`,`people`,``],[`💁♀️`,`woman tipping hand`,`people`,``],[`🙋♂️`,`man raising hand`,`smileys`,``],[`🙋♀️`,`woman raising hand`,`smileys`,``],[`🙇♂️`,`man bowing`,`smileys`,``],[`🙇♀️`,`woman bowing`,`smileys`,``],[`💆♂️`,`man getting massage`,`people`,``],[`💆♀️`,`woman getting massage`,`people`,``],[`💇♂️`,`man getting haircut`,`people`,``],[`💇♀️`,`woman getting haircut`,`people`,``],[`🧞♂️`,`man genie`,`people`,``],[`🧞♀️`,`woman genie`,`people`,``],[`🧟♂️`,`man zombie`,`people`,``],[`🧟♀️`,`woman zombie`,`people`,``],[`🧜♂️`,`merman`,`people`,``],[`🧚♂️`,`man fairy`,`people`,``],[`🧚♀️`,`woman fairy`,`people`,``],[`🧛♂️`,`man vampire`,`people`,``],[`🧛♀️`,`woman vampire`,`people`,``],[`🧙♂️`,`man mage`,`people`,``],[`🧙♀️`,`mage`,`people`,``],[`🧝♂️`,`man elf`,`people`,``],[`🧝♀️`,`woman elf`,`people`,``],[`🦸♂️`,`man superhero`,`people`,``],[`🦸♀️`,`woman superhero`,`people`,``],[`🦹♂️`,`man supervillain`,`people`,``],[`🦹♀️`,`woman supervillain`,`people`,``],[`0️⃣`,`keycap 0`,`symbols`,``],[`1️⃣`,`keycap 1`,`symbols`,``],[`2️⃣`,`keycap 2`,`symbols`,``],[`3️⃣`,`keycap 3`,`symbols`,``],[`4️⃣`,`keycap 4`,`symbols`,``],[`5️⃣`,`keycap 5`,`symbols`,``],[`6️⃣`,`keycap 6`,`symbols`,``],[`7️⃣`,`keycap 7`,`symbols`,``],[`8️⃣`,`keycap 8`,`symbols`,``],[`9️⃣`,`keycap 9`,`symbols`,``],[`#️⃣`,`keycap #`,`symbols`,``],[`*️⃣`,`keycap *`,`symbols`,``],[`🇨🇳`,`flag china`,`flags`,`中国,国旗,五星红旗`],[`🇺🇸`,`flag united states`,`flags`,`美国,国旗,USA`],[`🇬🇧`,`flag united kingdom`,`flags`,`英国,国旗,UK`],[`🇯🇵`,`flag japan`,`flags`,`日本,国旗`],[`🇫🇷`,`flag france`,`flags`,`法国,国旗`],[`🇩🇪`,`flag germany`,`flags`,`德国,国旗`],[`🇮🇹`,`flag italy`,`flags`,`意大利,国旗`],[`🇪🇸`,`flag spain`,`flags`,`西班牙,国旗`],[`🇷🇺`,`flag russia`,`flags`,`俄罗斯,国旗`],[`🇮🇳`,`regional indicator symbol letter i`,`flags`,`印度,国旗`],[`🇧🇷`,`flag brazil`,`flags`,`巴西,国旗`],[`🇨🇦`,`flag canada`,`flags`,`加拿大,国旗`],[`🇦🇺`,`flag australia`,`flags`,`澳大利亚,国旗`],[`🇸🇬`,`flag singapore`,`flags`,`新加坡,国旗`],[`🇭🇰`,`flag hong kong`,`flags`,`香港,国旗,区旗`],[`🇹🇼`,`flag taiwan`,`flags`,`台湾,国旗`],[`🇲🇴`,`flag macau`,`flags`,`澳门,国旗`],[`🇻🇳`,`flag vietnam`,`flags`,`越南,国旗`],[`🇲🇾`,`regional indicator symbol letter m`,`flags`,`马来西亚,国旗`],[`🇮🇩`,`flag indonesia`,`flags`,`印尼,国旗`],[`🇵🇭`,`flag philippines`,`flags`,`菲律宾,国旗`],[`🇹🇷`,`flag turkey`,`flags`,`土耳其,国旗`],[`🇸🇦`,`flag saudi arabia`,`flags`,`沙特,国旗`],[`🇦🇪`,`flag united arab emirates`,`flags`,`阿联酋,国旗`],[`🇳🇱`,`flag netherlands`,`flags`,`荷兰,国旗`],[`🇸🇪`,`flag sweden`,`flags`,`瑞典,国旗`],[`🇨🇭`,`flag switzerland`,`flags`,`瑞士,国旗`],[`🇦🇹`,`flag austria`,`flags`,`奥地利,国旗`],[`🇧🇪`,`flag belgium`,`flags`,`比利时,国旗`],[`🇵🇹`,`flag portugal`,`flags`,`葡萄牙,国旗`],[`🇬🇷`,`flag greece`,`flags`,`希腊,国旗`],[`🇳🇴`,`flag norway`,`flags`,`挪威,国旗`],[`🇩🇰`,`flag denmark`,`flags`,`丹麦,国旗`],[`🇫🇮`,`flag finland`,`flags`,`芬兰,国旗`],[`🇵🇱`,`flag poland`,`flags`,`波兰,国旗`],[`🇺🇦`,`flag ukraine`,`flags`,`乌克兰,国旗`],[`🇮🇱`,`flag israel`,`flags`,`以色列,国旗`],[`🇪🇬`,`flag egypt`,`flags`,`埃及,国旗`],[`🇿🇦`,`flag south africa`,`flags`,`南非,国旗`],[`🇳🇬`,`flag nigeria`,`flags`,`尼日利亚,国旗`],[`🇲🇽`,`flag mexico`,`flags`,`墨西哥,国旗`],[`🇦🇷`,`flag argentina`,`flags`,``],[`🇨🇱`,`flag chile`,`flags`,`智利,国旗`],[`🇰🇿`,`flag kazakhstan`,`flags`,`哈萨克斯坦,国旗`],[`🇺🇿`,`flag uzbekistan`,`flags`,`乌兹别克斯坦,国旗`],[`🇳🇿`,`flag new zealand`,`flags`,`新西兰,国旗`],[`🇮🇪`,`flag ireland`,`flags`,`爱尔兰,国旗`],[`🇨🇿`,`flag czechia`,`flags`,`捷克,国旗`],[`👍🏻`,`thumbs up light skin`,`people`,``],[`👍🏽`,`thumbs up sign`,`people`,``],[`👍🏾`,`thumbs up medium dark skin`,`people`,``],[`👍🏿`,`thumbs up dark skin`,`people`,``],[`👏🏻`,`clapping hands light skin`,`people`,``],[`👏🏼`,`clapping hands medium light skin`,`people`,``],[`👏🏽`,`clapping hands medium skin`,`people`,``],[`👏🏾`,`clapping hands medium dark skin`,`people`,``],[`👏🏿`,`clapping hands dark skin`,`people`,``],[`🙏🏻`,`folded hands light skin`,`smileys`,``],[`🙏🏼`,`folded hands medium light skin`,`smileys`,``],[`🙏🏽`,`folded hands medium skin`,`smileys`,``],[`🙏🏾`,`folded hands medium dark skin`,`smileys`,``],[`🙏🏿`,`folded hands dark skin`,`smileys`,``],[`🏳️🌈`,`rainbow flag`,`flags`,``],[`🏴☠️`,`pirate flag`,`flags`,`海盗旗,海盗`]];n(`zh`,{agentMgr:{allTools:`全部`,defaultAgentName:`默认助手`,defaultAgentDesc:`全能 AI 助手,拥有所有工具能力`,switchedTo:`已切换到:{name}`,editAgent:`编辑助手`,templateLoaded:`已加载模板:{name}`,noSkillsHint:`暂无启用技能(请先确认 Agent 已连接且技能开关已开启)`,nameRequired:`请输入助手名称`,agentUpdated:`助手已更新`,agentCreated:`助手 "{name}" 已创建`,saveFailed:`保存失败:{message}`,confirmDeleteAgentMessage:`确定要删除助手 "{name}" 吗?
|
|
2051
2051
|
正在使用该助手的会话将恢复为默认助手。`,deleteAgentTitle:`删除助手`,agentDeleted:`助手已删除`,deleteFailed:`删除失败:{message}`,cannotDeleteDefault:`默认助手不支持删除`,emojiCatSmileys:`笑脸与表情`,emojiCatPeople:`人物与身体`,emojiCatAnimals:`动物与自然`,emojiCatFood:`食物与饮品`,emojiCatTravel:`旅行与交通`,emojiCatActivity:`活动与运动`,emojiCatObjects:`物品`,emojiCatSymbols:`符号`,emojiCatFlags:`旗帜`,emojiSearchPlaceholder:`搜索 Emoji(英文名 / 中文关键词)`,emojiSearchClear:`清空搜索`,emojiNoMatch:`未找到匹配的 Emoji`,confirm:`确认`},agentTemplates:{codeReviewName:`代码审查专家`,codeReviewDesc:`专注于代码审查和质量保证`,webAutomationName:`网页自动化助手`,webAutomationDesc:`专注于网页交互和自动化`,dataAnalystName:`数据分析师`,dataAnalystDesc:`专注于数据提取、分析和可视化`,documentationName:`文档助手`,documentationDesc:`专注于技术文档和内容整理`}}),n(`en`,{agentMgr:{allTools:`All`,defaultAgentName:`Default Assistant`,defaultAgentDesc:`All-purpose AI assistant with all tool capabilities`,switchedTo:`Switched to: {name}`,editAgent:`Edit assistant`,templateLoaded:`Template loaded: {name}`,noSkillsHint:`No enabled skills (please confirm Agent is connected and skill switch is on)`,nameRequired:`Please enter assistant name`,agentUpdated:`Assistant updated`,agentCreated:`Assistant "{name}" created`,saveFailed:`Save failed: {message}`,confirmDeleteAgentMessage:`Are you sure you want to delete assistant "{name}"?
|
|
2052
|
-
Sessions using this assistant will revert to the default assistant.`,deleteAgentTitle:`Delete assistant`,agentDeleted:`Assistant deleted`,deleteFailed:`Delete failed: {message}`,cannotDeleteDefault:`Default assistant cannot be deleted`,emojiCatSmileys:`Smileys & Emotion`,emojiCatPeople:`People & Body`,emojiCatAnimals:`Animals & Nature`,emojiCatFood:`Food & Drink`,emojiCatTravel:`Travel & Places`,emojiCatActivity:`Activities`,emojiCatObjects:`Objects`,emojiCatSymbols:`Symbols`,emojiCatFlags:`Flags`,emojiSearchPlaceholder:`Search emoji (name / keyword)`,emojiSearchClear:`Clear search`,emojiNoMatch:`No matching emoji`,confirm:`Confirm`},agentTemplates:{codeReviewName:`Code Review Expert`,codeReviewDesc:`Focused on code review and quality assurance`,webAutomationName:`Web Automation Assistant`,webAutomationDesc:`Focused on web interaction and automation`,dataAnalystName:`Data Analyst`,dataAnalystDesc:`Focused on data extraction, analysis, and visualization`,documentationName:`Documentation Assistant`,documentationDesc:`Focused on technical documentation and content organization`}});async function ST(){await CT(),await wT(),DT(),kT(),a.debug(`[AgentMgr] Agent managerinitialization complete, activeAgentId:`,N.activeAgentId)}async function CT(){let[e,t]=await Promise.all([
|
|
2052
|
+
Sessions using this assistant will revert to the default assistant.`,deleteAgentTitle:`Delete assistant`,agentDeleted:`Assistant deleted`,deleteFailed:`Delete failed: {message}`,cannotDeleteDefault:`Default assistant cannot be deleted`,emojiCatSmileys:`Smileys & Emotion`,emojiCatPeople:`People & Body`,emojiCatAnimals:`Animals & Nature`,emojiCatFood:`Food & Drink`,emojiCatTravel:`Travel & Places`,emojiCatActivity:`Activities`,emojiCatObjects:`Objects`,emojiCatSymbols:`Symbols`,emojiCatFlags:`Flags`,emojiSearchPlaceholder:`Search emoji (name / keyword)`,emojiSearchClear:`Clear search`,emojiNoMatch:`No matching emoji`,confirm:`Confirm`},agentTemplates:{codeReviewName:`Code Review Expert`,codeReviewDesc:`Focused on code review and quality assurance`,webAutomationName:`Web Automation Assistant`,webAutomationDesc:`Focused on web interaction and automation`,dataAnalystName:`Data Analyst`,dataAnalystDesc:`Focused on data extraction, analysis, and visualization`,documentationName:`Documentation Assistant`,documentationDesc:`Focused on technical documentation and content organization`}});async function ST(){await CT(),await wT(),DT(),kT(),a.debug(`[AgentMgr] Agent managerinitialization complete, activeAgentId:`,N.activeAgentId)}async function CT(){let[e,t]=await Promise.all([bt(),St()]);N.activeSessionId||(N.activeAgentId=e),N.customAgents=t.filter(e=>!e.isBuiltin);let n=N.activeAgentId||e,r=t.find(e=>e.id===n||!n&&e.id==="default");N.activeAgentToolIds=r?r.toolIds:null,a.debug(`[AgentMgr] Agent state loaded, activeAgentId:`,N.activeAgentId,`total:`,t.length,`toolIds:`,N.activeAgentToolIds)}async function wT(){let e=document.getElementById(`agentListItems`),t=document.getElementById(`agentDropdownFooter`);if(!e)return;let n=await St(),i=N.activeAgentId,a=``;for(let e of n){let t=e.id===i||!i&&e.id==="default",n=e.toolIds?e.toolIds.length:r(`agentMgr.allTools`),o=e.id==="default"?r(`agentMgr.defaultAgentName`):e.name,s=e.id==="default"?r(`agentMgr.defaultAgentDesc`):e.description||r(`agentConfig.toolCount`,{count:n});a+=`
|
|
2053
2053
|
<div class="agent-item ${t?`active`:``} ${e.isBuiltin?``:`is-editable`}" data-agent-id="${Y(e.id)}">
|
|
2054
2054
|
<span class="agent-item-icon">${dE(e.icon)}</span>
|
|
2055
2055
|
<div class="agent-item-info">
|
|
@@ -2065,7 +2065,7 @@ Sessions using this assistant will revert to the default assistant.`,deleteAgent
|
|
|
2065
2065
|
<div class="agent-item" id="agentAddBtn" style="color:var(--brand-500);">
|
|
2066
2066
|
<span class="agent-item-icon" style="color:var(--brand-500);">+</span>
|
|
2067
2067
|
<span class="agent-item-name">${r(`agentEditor.createNew`)}</span>
|
|
2068
|
-
</div>`),TT(n,i)}function TT(e,t){let n=document.getElementById(`agentSelectorBtn`),i=document.getElementById(`agentSelectorText`),a=document.getElementById(`agentSelectorEmoji`);if(!n||!i)return;let o=e.find(e=>e.id===t)||e.find(e=>e.id==="default");if(o){let e=o.id==="default"?r(`agentMgr.defaultAgentName`):o.name;i.textContent=`${o.icon} ${e}`,a&&(a.textContent=o.icon),n.title=`${r(`header.switchAgent`)}: ${o.icon} ${e}`}else i.textContent=r(`header.defaultAssistant`),a&&(a.textContent=`🤖`),n.title=r(`header.switchAgent`)}function ET(){let e=document.getElementById(`agentSelectorBtn`),t=document.getElementById(`agentSelectorDropdown`),n=document.getElementById(`agentSelectorWrapper`);if(!e||!t||!n)return;let r=n.getBoundingClientRect(),i=document.body.clientWidth;t.style.left=``,t.style.right=`auto`,t.style.maxWidth=Math.min(320,i-16)+`px`;let a=t.getBoundingClientRect().width,o=Math.min(a,i-16),s=e.getBoundingClientRect(),c=s.left+s.width/2,l=i-o-8,u=Math.max(8,Math.min(l,c-o/2));t.style.left=u-r.left+`px`}function DT(){let e=document.getElementById(`agentSelectorBtn`),t=document.getElementById(`agentSelectorDropdown`);!e||!t||(e.addEventListener(`click`,async e=>{if(e.stopPropagation(),t.style.display===`flex`)t.style.display=`none`;else{t.style.left=``,t.style.right=`auto`,t.style.maxWidth=Math.min(320,document.body.clientWidth-16)+`px`,t.style.display=`flex`,ET();try{await wT()}catch{}ET()}}),document.addEventListener(`click`,()=>{t.style.display=`none`}),t.addEventListener(`click`,async e=>{let n=e.target.closest(`.agent-item`);if(!n)return;let r=e.target.closest(`[data-action]`);if(r&&r.dataset.action===`edit`){e.stopPropagation();let t=r.dataset.agentId;HT(t);return}if(r&&r.dataset.action===`delete`){e.stopPropagation(),await cE(r.dataset.agentId);return}if(n.id===`agentAddBtn`){HT(null);return}let i=n.dataset.agentId;i&&(await OT(i),t.style.display=`none`)}))}async function OT(e){let t=e?await _t(e):null;if(N.activeAgentId=e,N.activeAgentToolIds=t?t.toolIds:null,N.activeAgentMcpExcludedServerIds=t?t.mcpExcludedServerIds??null:null,await Ct(e),Ii().catch(()=>{}),t&&!t.isBuiltin)t.model&&(N.currentModel=t.model),t.temperature!==null&&t.temperature!==void 0&&(N.temperature=t.temperature,N.topP=t.topP!==null&&t.topP!==void 0?t.topP:1),document.dispatchEvent(new CustomEvent(`agent-model-changed`));else if(!t||t.isBuiltin)try{let e=await chrome.storage.local.get([`modelName`,`temperature`,`topP`]);e.modelName&&(N.currentModel=e.modelName),e.temperature!==void 0&&(N.temperature=e.temperature),e.topP!==void 0&&(N.topP=e.topP),document.dispatchEvent(new CustomEvent(`agent-model-changed`))}catch{}await wT();let n=`agentMcpClosedServers_${e||`default`}`,i=await chrome.storage.local.get([n,`ragTools`,`ragToolsIntroduced`]),o=i.ragTools||[];N.mcpClosedServers=i[n]||[];let s=`agentEnabledTools_${e||`default`}`,c=await chrome.storage.local.get([s,`enabledTools`]),l=!!c[s],u=c[s]||c.enabledTools;if(l||u&&u.length>0){let e=Fa(o),t=u.filter(t=>e.has(t));if(l)N.enabledTools=t;else{let e=x.filter(e=>e.enabled&&!t.includes(e.id)).map(e=>e.id);N.enabledTools=[...t,...e]}let n=Pa(N.enabledTools,o,i.ragToolsIntroduced);N.enabledTools=n.tools,N.enabledTools.length!==u.length&&chrome.storage.local.set({[s]:N.enabledTools,...n.migrated?{ragToolsIntroduced:!0}:{}})}else{N.enabledTools=x.filter(e=>e.enabled).map(e=>e.id);let e=Pa(N.enabledTools,o,i.ragToolsIntroduced);N.enabledTools=e.tools,e.migrated&&chrome.storage.local.set({ragToolsIntroduced:!0,[s]:N.enabledTools})}let d=document.getElementById(`toolsPopupOverlay`);d&&d.classList.contains(`show`)&&(ba(),Oa(),ka()),Ma();let f=t&&t.id!=="default"?t.name:r(`agentMgr.defaultAgentName`);L(r(`agentMgr.switchedTo`,{name:f}),`info`,2e3),a.debug(`[AgentMgr] switched Agent:`,e,f)}function kT(){let e=document.getElementById(`agentEditModal`);if(!e)return;e.querySelector(`#agentModalCloseBtn`)?.addEventListener(`click`,UT),e.querySelector(`#agentSaveBtn`)?.addEventListener(`click`,oE),e.querySelector(`#agentDeleteBtn`)?.addEventListener(`click`,sE),e.querySelector(`#agentTemplateSelect`)?.addEventListener(`change`,GT),PT();let t=document.getElementById(`agentToolActions`);t&&t.addEventListener(`click`,e=>{let t=e.target.closest(`button`);if(!t)return;let n=t.dataset.action;n===`selectAll`?FT():n===`deselectAll`?IT():n===`toggleSelectedOnly`&&(KT.selectedOnly=!KT.selectedOnly,JT())});let n=document.getElementById(`agentToolSearchInput`);if(n){let e=null,t=document.getElementById(`agentToolSearchClear`),r=()=>{t&&(t.style.display=n.value?`block`:`none`)};n.addEventListener(`input`,()=>{r(),clearTimeout(e),e=setTimeout(()=>{KT.searchText=n.value,JT()},150)}),t&&t.addEventListener(`click`,()=>{clearTimeout(e),n.value=``,r(),KT.searchText=``,JT(),n.focus()}),r()}let r=document.getElementById(`agentSkillActions`);r&&r.addEventListener(`click`,e=>{let t=e.target.closest(`button`);if(!t)return;let n=t.dataset.action;n===`selectAllSkills`?LT():n===`deselectAllSkills`?RT():n===`toggleSelectedOnlySkills`&&(QT.selectedOnly=!QT.selectedOnly,eE())});let i=document.getElementById(`agentSkillSearchInput`);if(i){let e=null,t=document.getElementById(`agentSkillSearchClear`),n=()=>{t&&(t.style.display=i.value?`block`:`none`)};i.addEventListener(`input`,()=>{n(),clearTimeout(e),e=setTimeout(()=>{QT.searchText=i.value,eE()},150)}),t&&t.addEventListener(`click`,()=>{clearTimeout(e),i.value=``,n(),QT.searchText=``,eE(),i.focus()}),n()}let a=document.getElementById(`agentToolList`);a&&(a.addEventListener(`click`,e=>{let t=e.target.closest(`.agent-mcp-expand-btn`);if(t){e.preventDefault(),YT(t.dataset.serverId,t);return}let n=e.target.closest(`.agent-mcp-service-item`);if(n&&!e.target.closest(`input[type="checkbox"]`)){e.preventDefault(),YT(n.dataset.mcpServerId,n.querySelector(`.agent-mcp-expand-btn`));return}let r=e.target.closest(`.agent-tool-category-clickable`);r&&zT(r.dataset.category)}),a.addEventListener(`change`,e=>{if(!e.target.matches(`input[type="checkbox"]`))return;let t=KT,n=e.target.dataset.toolId,r=e.target.dataset.mcpServerId;t.inheritMode=!1,n?e.target.checked?t.selectedSet.add(n):t.selectedSet.delete(n):r&&(e.target.checked?t.excludedSet.delete(r):t.excludedSet.add(r)),t.selectedOnly?JT():BT()}));let o=document.getElementById(`agentSkillList`);o&&o.addEventListener(`change`,e=>{if(!e.target.matches(`input[type="checkbox"]`))return;let t=QT;t.inheritMode=!1,e.target.checked?t.selectedSet.add(e.target.value):t.selectedSet.delete(e.target.value),t.selectedOnly&&!e.target.checked?eE():VT()}),document.addEventListener(`click`,e=>{let t=document.getElementById(`emojiPicker`),n=document.getElementById(`agentEditIconBtn`);t&&n&&t.style.display===`block`&&!n.contains(e.target)&&!t.contains(e.target)&&(t.style.display=`none`)})}var AT=[[`smileys`,`emojiCatSmileys`],[`people`,`emojiCatPeople`],[`animals`,`emojiCatAnimals`],[`food`,`emojiCatFood`],[`travel`,`emojiCatTravel`],[`activity`,`emojiCatActivity`],[`objects`,`emojiCatObjects`],[`symbols`,`emojiCatSymbols`],[`flags`,`emojiCatFlags`]];function jT(e,t){return!!(e[1].includes(t)||e[3]&&e[3].includes(t))}function MT(e){let t=``;for(let[e,n]of AT){let i=xT.filter(t=>t[2]===e);if(i.length){t+=`<div class="emoji-category-label">${r(`agentMgr.`+n)}</div>`,t+=`<div class="emoji-picker-grid">`;for(let e of i)t+=`<button type="button" class="emoji-picker-item" data-emoji="${Y(e[0])}" title="${Y(e[1])}">${e[0]}</button>`;t+=`</div>`}}e.innerHTML=t}function NT(e,t){let n=xT.filter(e=>jT(e,t));if(!n.length){e.innerHTML=`<div class="emoji-picker-empty">${r(`agentMgr.emojiNoMatch`)}</div>`;return}let i=`<div class="emoji-picker-grid">`;for(let e of n)i+=`<button type="button" class="emoji-picker-item" data-emoji="${Y(e[0])}" title="${Y(e[1])}">${e[0]}</button>`;i+=`</div>`,e.innerHTML=i}function PT(){let e=document.getElementById(`emojiPicker`),t=document.getElementById(`agentEditIconBtn`),n=document.getElementById(`agentEditIcon`),r=document.getElementById(`emojiSearchInput`),i=document.getElementById(`emojiSearchClear`),a=document.getElementById(`emojiPickerBody`);if(!e||!t)return;let o=()=>{let e=r?r.value.trim().toLowerCase():``;e?NT(a,e):MT(a),i&&(i.style.display=e?`flex`:`none`)};t.addEventListener(`click`,n=>{if(n.stopPropagation(),e.style.display===`block`){e.style.display=`none`;return}r&&(r.value=``),o();let i=t.getBoundingClientRect();document.body.clientWidth-i.left>=330?(e.style.left=`0`,e.style.right=`auto`):(e.style.left=`auto`,e.style.right=`0`),e.style.display=`block`}),r&&r.addEventListener(`input`,o),i&&i.addEventListener(`click`,e=>{e.stopPropagation(),r&&(r.value=``),o(),r&&r.focus()}),e.addEventListener(`click`,r=>{let i=r.target.closest(`.emoji-picker-item`);if(!i)return;let a=i.dataset.emoji;t.textContent=a,n&&(n.value=a),e.style.display=`none`})}function FT(){let e=KT;e.inheritMode=!1,e.allTools.forEach(t=>e.selectedSet.add(t.id)),e.mcpServices.forEach(t=>e.excludedSet.delete(t.serverId)),JT()}function IT(){let e=KT;e.inheritMode=!1,e.allTools.forEach(t=>e.selectedSet.delete(t.id)),e.mcpServices.forEach(t=>e.excludedSet.add(t.serverId)),JT()}function LT(){let e=QT;e.inheritMode=!1,e.skills.forEach(t=>e.selectedSet.add(t.name)),eE()}function RT(){let e=QT;e.inheritMode=!1,e.selectedSet.clear(),eE()}function zT(e){let t=KT;if(e===`mcp`){if(t.mcpServices.length===0)return;t.inheritMode=!1;let e=t.mcpServices.every(e=>!t.excludedSet.has(e.serverId));t.mcpServices.forEach(n=>{e?t.excludedSet.add(n.serverId):t.excludedSet.delete(n.serverId)}),document.querySelectorAll(`#agentToolList .agent-mcp-service-item input[type="checkbox"]`).forEach(t=>{t.checked=!e})}else{let n=t.allTools.filter(t=>(t.category||`other`)===e);if(n.length===0)return;t.inheritMode=!1;let r=n.every(e=>t.selectedSet.has(e.id));n.forEach(e=>{r?t.selectedSet.delete(e.id):t.selectedSet.add(e.id)}),document.querySelectorAll(`#agentToolList .agent-tool-item[data-category="${e}"] input[type="checkbox"]`).forEach(e=>{e.checked=!r})}t.selectedOnly?JT():BT()}function BT(){let e=KT,t=document.getElementById(`agentToolList`);if(!t)return;let n=e.mcpServices.filter(t=>!e.excludedSet.has(t.serverId)).length;t.querySelectorAll(`.agent-tool-category-clickable`).forEach(t=>{let r=t.dataset.category,i=t.querySelector(`.agent-tool-cat-count`);if(i)if(r===`mcp`)i.textContent=`${n}/${e.mcpServices.length}`;else{let t=e.allTools.filter(e=>(e.category||`other`)===r);i.textContent=`${t.filter(t=>e.selectedSet.has(t.id)).length}/${t.length}`}});let i=document.getElementById(`agentToolCount`);if(i){let t=e.allTools.filter(t=>e.selectedSet.has(t.id)).length,a=e.allTools.length+e.mcpServices.length;i.textContent=r(`agentConfig.selectedTotalCount`,{selected:e.inheritMode?a:t+n,total:a})}}function VT(){let e=document.getElementById(`agentSkillCount`);if(!e)return;let t=QT,n=t.skills.length;e.textContent=r(`agentConfig.selectedTotalCount`,{selected:t.inheritMode?n:t.selectedSet.size,total:n})}async function HT(e){let t=document.getElementById(`agentEditModal`);if(!t)return;await nE(),rE(-1),t.querySelector(`#agentEditId`).value=``,t.querySelector(`#agentEditName`).value=``,t.querySelector(`#agentEditIcon`).value=`🤖`;let n=t.querySelector(`#agentEditIconBtn`);n&&(n.textContent=`🤖`),t.querySelector(`#agentEditDesc`).value=``,t.querySelector(`#agentEditPrompt`).value=``,t.querySelector(`#agentEditAllowSub`).checked=!1,t.querySelector(`#agentTemplateSelect`).value=``,t.querySelector(`#agentEditModel`).value=``;let i=t.querySelector(`#agentDeleteBtn`),a=t.querySelector(`#agentEditTitle`);if(e){let n=await _t(e);if(!n||n.isBuiltin)return;a.textContent=r(`agentMgr.editAgent`),t.querySelector(`#agentEditId`).value=n.id,t.querySelector(`#agentEditName`).value=n.name,t.querySelector(`#agentEditIcon`).value=n.icon||`🤖`;let o=t.querySelector(`#agentEditIconBtn`);o&&(o.textContent=n.icon||`🤖`),t.querySelector(`#agentEditDesc`).value=n.description||``,t.querySelector(`#agentEditPrompt`).value=n.systemPrompt||``,t.querySelector(`#agentEditAllowSub`).checked=n.allowSubDispatch||!1,t.querySelector(`#agentEditModel`).value=n.model||``,rE(aE(n.temperature,n.topP)),i.style.display=`block`,qT(n.toolIds,n.mcpExcludedServerIds??[]),$T(n.skillIds)}else a.textContent=r(`agentEditor.createNew`),i.style.display=`none`,qT(null,[]),$T(null);WT(),t.style.display=`flex`;let o=t.querySelector(`#agentEditModel`);if(o){let e=o.value,t=o.cloneNode(!0);o.parentNode.replaceChild(t,o),t.value=e,t.addEventListener(`mousedown`,()=>{let e=t.value;e&&(t.dataset._saved=e,t.value=``)}),t.addEventListener(`blur`,()=>{setTimeout(()=>{t.value||=t.dataset._saved||``},150)})}}function UT(){let e=document.getElementById(`agentEditModal`);e&&(e.style.display=`none`)}function WT(){let e=document.getElementById(`agentTemplateSelect`);if(!e)return;let t=[r(`agentTemplates.codeReviewName`),r(`agentTemplates.webAutomationName`),r(`agentTemplates.dataAnalystName`),r(`agentTemplates.documentationName`)],n=`<option value="">${r(`agentEditor.selectTemplate`)}</option>`;for(let e=0;e<oe.length;e++){let r=oe[e];n+=`<option value="${e}">${r.icon} ${t[e]}</option>`}e.innerHTML=n}function GT(e){let t=parseInt(e.target.value);if(isNaN(t)||t<0||t>=oe.length)return;let n=oe[t],i=document.getElementById(`agentEditModal`);if(!i)return;let a=[`agentTemplates.codeReviewName`,`agentTemplates.webAutomationName`,`agentTemplates.dataAnalystName`,`agentTemplates.documentationName`],o=[`agentTemplates.codeReviewDesc`,`agentTemplates.webAutomationDesc`,`agentTemplates.dataAnalystDesc`,`agentTemplates.documentationDesc`];i.querySelector(`#agentEditName`).value=r(a[t]),i.querySelector(`#agentEditIcon`).value=n.icon;let c=i.querySelector(`#agentEditIconBtn`);c&&(c.textContent=n.icon),i.querySelector(`#agentEditDesc`).value=r(o[t]),i.querySelector(`#agentEditPrompt`).value=s()===`en`?n.systemPrompt:n.systemPromptZh||n.systemPrompt,i.querySelector(`#agentEditAllowSub`).checked=n.allowSubDispatch||!1,i.querySelector(`#agentEditModel`).value=n.model||``,rE(aE(n.temperature,n.topP)),qT(n.toolIds,[]),$T(n.skillIds||null),L(r(`agentMgr.templateLoaded`,{name:n.name}),`info`,2e3)}var KT={allTools:[],mcpServices:[],selectedSet:new Set,excludedSet:new Set,searchText:``,selectedOnly:!1,inheritMode:!1};async function qT(e,t){if(!document.getElementById(`agentToolList`))return;let n=[];try{n=(await chrome.storage.local.get([`mcpTools`])).mcpTools||[]}catch{}let{mcpEnabled:r,skillsEnabled:i,ragTools:a}=await chrome.storage.local.get([`mcpEnabled`,`skillsEnabled`,`ragTools`]),o=N.agentPlatform?.connected===!0,s=[...x,...a||[]];o||(s=s.filter(e=>!e.id.startsWith(`agent_`)&&!e.id.startsWith(`knowledge_`))),i===!1&&(s=s.filter(e=>e.id!==`agent_skill`));let c=[];if(r===!0&&o){let e=new Map;for(let t of n){let n=t.serverId||`unknown`;e.has(n)||e.set(n,{serverId:n,serverName:t.serverName||n,tools:[]}),e.get(n).tools.push(t)}c=Array.from(e.values())}let l=new Set(Array.isArray(t)?t:[]),u=KT;u.allTools=s,u.mcpServices=c,u.selectedSet=new Set(e||[]),u.excludedSet=l,u.searchText=``,u.selectedOnly=!1,u.inheritMode=!e;let d=document.getElementById(`agentToolSearchInput`);d&&(d.value=``);let f=document.getElementById(`agentToolSearchClear`);f&&(f.style.display=`none`),JT()}function JT(){let e=document.getElementById(`agentToolList`);if(!e)return;let t=KT,n=za({tools:t.allTools,services:t.mcpServices,selectedSet:t.selectedSet,excludedSet:t.excludedSet,query:t.searchText,selectedOnly:t.selectedOnly,getDesc:ta}),i=t.mcpServices.filter(e=>!t.excludedSet.has(e.serverId)).length,a={};for(let e of n.tools){let t=e.category||`other`;a[t]||(a[t]=[]),a[t].push(e)}let o=``;for(let[e,n]of Object.entries(a)){let i=r(`toolCategory.${e}`)===`toolCategory.${e}`?e:r(`toolCategory.${e}`),a=t.allTools.filter(t=>(t.category||`other`)===e),s=a.filter(e=>t.selectedSet.has(e.id)).length;o+=`<div class="agent-tool-category agent-tool-category-clickable" data-category="${Y(e)}" title="${Y(r(`agentConfig.toggleCategoryAll`))}">${i} <span class="agent-tool-cat-count" style="font-weight:400;color:var(--text-tertiary);">${s}/${a.length}</span></div>`;for(let r of n){let n=t.selectedSet.has(r.id)?`checked`:``,i=ta(r),a=i.length>40?i.substring(0,40)+`...`:i;o+=`
|
|
2068
|
+
</div>`),TT(n,i)}function TT(e,t){let n=document.getElementById(`agentSelectorBtn`),i=document.getElementById(`agentSelectorText`),a=document.getElementById(`agentSelectorEmoji`);if(!n||!i)return;let o=e.find(e=>e.id===t)||e.find(e=>e.id==="default");if(o){let e=o.id==="default"?r(`agentMgr.defaultAgentName`):o.name;i.textContent=`${o.icon} ${e}`,a&&(a.textContent=o.icon),n.title=`${r(`header.switchAgent`)}: ${o.icon} ${e}`}else i.textContent=r(`header.defaultAssistant`),a&&(a.textContent=`🤖`),n.title=r(`header.switchAgent`)}function ET(){let e=document.getElementById(`agentSelectorBtn`),t=document.getElementById(`agentSelectorDropdown`),n=document.getElementById(`agentSelectorWrapper`);if(!e||!t||!n)return;let r=n.getBoundingClientRect(),i=document.body.clientWidth;t.style.left=``,t.style.right=`auto`,t.style.maxWidth=Math.min(320,i-16)+`px`;let a=t.getBoundingClientRect().width,o=Math.min(a,i-16),s=e.getBoundingClientRect(),c=s.left+s.width/2,l=i-o-8,u=Math.max(8,Math.min(l,c-o/2));t.style.left=u-r.left+`px`}function DT(){let e=document.getElementById(`agentSelectorBtn`),t=document.getElementById(`agentSelectorDropdown`);!e||!t||(e.addEventListener(`click`,async e=>{if(e.stopPropagation(),t.style.display===`flex`)t.style.display=`none`;else{t.style.left=``,t.style.right=`auto`,t.style.maxWidth=Math.min(320,document.body.clientWidth-16)+`px`,t.style.display=`flex`,ET();try{await wT()}catch{}ET()}}),document.addEventListener(`click`,()=>{t.style.display=`none`}),t.addEventListener(`click`,async e=>{let n=e.target.closest(`.agent-item`);if(!n)return;let r=e.target.closest(`[data-action]`);if(r&&r.dataset.action===`edit`){e.stopPropagation();let t=r.dataset.agentId;HT(t);return}if(r&&r.dataset.action===`delete`){e.stopPropagation(),await cE(r.dataset.agentId);return}if(n.id===`agentAddBtn`){HT(null);return}let i=n.dataset.agentId;i&&(await OT(i),t.style.display=`none`)}))}async function OT(e){let t=e?await vt(e):null;if(N.activeAgentId=e,N.activeAgentToolIds=t?t.toolIds:null,N.activeAgentMcpExcludedServerIds=t?t.mcpExcludedServerIds??null:null,await wt(e),Ii().catch(()=>{}),t&&!t.isBuiltin)t.model&&(N.currentModel=t.model),t.temperature!==null&&t.temperature!==void 0&&(N.temperature=t.temperature,N.topP=t.topP!==null&&t.topP!==void 0?t.topP:1),document.dispatchEvent(new CustomEvent(`agent-model-changed`));else if(!t||t.isBuiltin)try{let e=await chrome.storage.local.get([`modelName`,`temperature`,`topP`]);e.modelName&&(N.currentModel=e.modelName),e.temperature!==void 0&&(N.temperature=e.temperature),e.topP!==void 0&&(N.topP=e.topP),document.dispatchEvent(new CustomEvent(`agent-model-changed`))}catch{}await wT();let n=`agentMcpClosedServers_${e||`default`}`,i=await chrome.storage.local.get([n,`ragTools`,`ragToolsIntroduced`]),o=i.ragTools||[];N.mcpClosedServers=i[n]||[];let s=`agentEnabledTools_${e||`default`}`,c=await chrome.storage.local.get([s,`enabledTools`]),l=!!c[s],u=c[s]||c.enabledTools;if(l||u&&u.length>0){let e=Fa(o),t=u.filter(t=>e.has(t));if(l)N.enabledTools=t;else{let e=x.filter(e=>e.enabled&&!t.includes(e.id)).map(e=>e.id);N.enabledTools=[...t,...e]}let n=Pa(N.enabledTools,o,i.ragToolsIntroduced);N.enabledTools=n.tools,N.enabledTools.length!==u.length&&chrome.storage.local.set({[s]:N.enabledTools,...n.migrated?{ragToolsIntroduced:!0}:{}})}else{N.enabledTools=x.filter(e=>e.enabled).map(e=>e.id);let e=Pa(N.enabledTools,o,i.ragToolsIntroduced);N.enabledTools=e.tools,e.migrated&&chrome.storage.local.set({ragToolsIntroduced:!0,[s]:N.enabledTools})}let d=document.getElementById(`toolsPopupOverlay`);d&&d.classList.contains(`show`)&&(ba(),Oa(),ka()),Ma();let f=t&&t.id!=="default"?t.name:r(`agentMgr.defaultAgentName`);L(r(`agentMgr.switchedTo`,{name:f}),`info`,2e3),a.debug(`[AgentMgr] switched Agent:`,e,f)}function kT(){let e=document.getElementById(`agentEditModal`);if(!e)return;e.querySelector(`#agentModalCloseBtn`)?.addEventListener(`click`,UT),e.querySelector(`#agentSaveBtn`)?.addEventListener(`click`,oE),e.querySelector(`#agentDeleteBtn`)?.addEventListener(`click`,sE),e.querySelector(`#agentTemplateSelect`)?.addEventListener(`change`,GT),PT();let t=document.getElementById(`agentToolActions`);t&&t.addEventListener(`click`,e=>{let t=e.target.closest(`button`);if(!t)return;let n=t.dataset.action;n===`selectAll`?FT():n===`deselectAll`?IT():n===`toggleSelectedOnly`&&(KT.selectedOnly=!KT.selectedOnly,JT())});let n=document.getElementById(`agentToolSearchInput`);if(n){let e=null,t=document.getElementById(`agentToolSearchClear`),r=()=>{t&&(t.style.display=n.value?`block`:`none`)};n.addEventListener(`input`,()=>{r(),clearTimeout(e),e=setTimeout(()=>{KT.searchText=n.value,JT()},150)}),t&&t.addEventListener(`click`,()=>{clearTimeout(e),n.value=``,r(),KT.searchText=``,JT(),n.focus()}),r()}let r=document.getElementById(`agentSkillActions`);r&&r.addEventListener(`click`,e=>{let t=e.target.closest(`button`);if(!t)return;let n=t.dataset.action;n===`selectAllSkills`?LT():n===`deselectAllSkills`?RT():n===`toggleSelectedOnlySkills`&&(QT.selectedOnly=!QT.selectedOnly,eE())});let i=document.getElementById(`agentSkillSearchInput`);if(i){let e=null,t=document.getElementById(`agentSkillSearchClear`),n=()=>{t&&(t.style.display=i.value?`block`:`none`)};i.addEventListener(`input`,()=>{n(),clearTimeout(e),e=setTimeout(()=>{QT.searchText=i.value,eE()},150)}),t&&t.addEventListener(`click`,()=>{clearTimeout(e),i.value=``,n(),QT.searchText=``,eE(),i.focus()}),n()}let a=document.getElementById(`agentToolList`);a&&(a.addEventListener(`click`,e=>{let t=e.target.closest(`.agent-mcp-expand-btn`);if(t){e.preventDefault(),YT(t.dataset.serverId,t);return}let n=e.target.closest(`.agent-mcp-service-item`);if(n&&!e.target.closest(`input[type="checkbox"]`)){e.preventDefault(),YT(n.dataset.mcpServerId,n.querySelector(`.agent-mcp-expand-btn`));return}let r=e.target.closest(`.agent-tool-category-clickable`);r&&zT(r.dataset.category)}),a.addEventListener(`change`,e=>{if(!e.target.matches(`input[type="checkbox"]`))return;let t=KT,n=e.target.dataset.toolId,r=e.target.dataset.mcpServerId;t.inheritMode=!1,n?e.target.checked?t.selectedSet.add(n):t.selectedSet.delete(n):r&&(e.target.checked?t.excludedSet.delete(r):t.excludedSet.add(r)),t.selectedOnly?JT():BT()}));let o=document.getElementById(`agentSkillList`);o&&o.addEventListener(`change`,e=>{if(!e.target.matches(`input[type="checkbox"]`))return;let t=QT;t.inheritMode=!1,e.target.checked?t.selectedSet.add(e.target.value):t.selectedSet.delete(e.target.value),t.selectedOnly&&!e.target.checked?eE():VT()}),document.addEventListener(`click`,e=>{let t=document.getElementById(`emojiPicker`),n=document.getElementById(`agentEditIconBtn`);t&&n&&t.style.display===`block`&&!n.contains(e.target)&&!t.contains(e.target)&&(t.style.display=`none`)})}var AT=[[`smileys`,`emojiCatSmileys`],[`people`,`emojiCatPeople`],[`animals`,`emojiCatAnimals`],[`food`,`emojiCatFood`],[`travel`,`emojiCatTravel`],[`activity`,`emojiCatActivity`],[`objects`,`emojiCatObjects`],[`symbols`,`emojiCatSymbols`],[`flags`,`emojiCatFlags`]];function jT(e,t){return!!(e[1].includes(t)||e[3]&&e[3].includes(t))}function MT(e){let t=``;for(let[e,n]of AT){let i=xT.filter(t=>t[2]===e);if(i.length){t+=`<div class="emoji-category-label">${r(`agentMgr.`+n)}</div>`,t+=`<div class="emoji-picker-grid">`;for(let e of i)t+=`<button type="button" class="emoji-picker-item" data-emoji="${Y(e[0])}" title="${Y(e[1])}">${e[0]}</button>`;t+=`</div>`}}e.innerHTML=t}function NT(e,t){let n=xT.filter(e=>jT(e,t));if(!n.length){e.innerHTML=`<div class="emoji-picker-empty">${r(`agentMgr.emojiNoMatch`)}</div>`;return}let i=`<div class="emoji-picker-grid">`;for(let e of n)i+=`<button type="button" class="emoji-picker-item" data-emoji="${Y(e[0])}" title="${Y(e[1])}">${e[0]}</button>`;i+=`</div>`,e.innerHTML=i}function PT(){let e=document.getElementById(`emojiPicker`),t=document.getElementById(`agentEditIconBtn`),n=document.getElementById(`agentEditIcon`),r=document.getElementById(`emojiSearchInput`),i=document.getElementById(`emojiSearchClear`),a=document.getElementById(`emojiPickerBody`);if(!e||!t)return;let o=()=>{let e=r?r.value.trim().toLowerCase():``;e?NT(a,e):MT(a),i&&(i.style.display=e?`flex`:`none`)};t.addEventListener(`click`,n=>{if(n.stopPropagation(),e.style.display===`block`){e.style.display=`none`;return}r&&(r.value=``),o();let i=t.getBoundingClientRect();document.body.clientWidth-i.left>=330?(e.style.left=`0`,e.style.right=`auto`):(e.style.left=`auto`,e.style.right=`0`),e.style.display=`block`}),r&&r.addEventListener(`input`,o),i&&i.addEventListener(`click`,e=>{e.stopPropagation(),r&&(r.value=``),o(),r&&r.focus()}),e.addEventListener(`click`,r=>{let i=r.target.closest(`.emoji-picker-item`);if(!i)return;let a=i.dataset.emoji;t.textContent=a,n&&(n.value=a),e.style.display=`none`})}function FT(){let e=KT;e.inheritMode=!1,e.allTools.forEach(t=>e.selectedSet.add(t.id)),e.mcpServices.forEach(t=>e.excludedSet.delete(t.serverId)),JT()}function IT(){let e=KT;e.inheritMode=!1,e.allTools.forEach(t=>e.selectedSet.delete(t.id)),e.mcpServices.forEach(t=>e.excludedSet.add(t.serverId)),JT()}function LT(){let e=QT;e.inheritMode=!1,e.skills.forEach(t=>e.selectedSet.add(t.name)),eE()}function RT(){let e=QT;e.inheritMode=!1,e.selectedSet.clear(),eE()}function zT(e){let t=KT;if(e===`mcp`){if(t.mcpServices.length===0)return;t.inheritMode=!1;let e=t.mcpServices.every(e=>!t.excludedSet.has(e.serverId));t.mcpServices.forEach(n=>{e?t.excludedSet.add(n.serverId):t.excludedSet.delete(n.serverId)}),document.querySelectorAll(`#agentToolList .agent-mcp-service-item input[type="checkbox"]`).forEach(t=>{t.checked=!e})}else{let n=t.allTools.filter(t=>(t.category||`other`)===e);if(n.length===0)return;t.inheritMode=!1;let r=n.every(e=>t.selectedSet.has(e.id));n.forEach(e=>{r?t.selectedSet.delete(e.id):t.selectedSet.add(e.id)}),document.querySelectorAll(`#agentToolList .agent-tool-item[data-category="${e}"] input[type="checkbox"]`).forEach(e=>{e.checked=!r})}t.selectedOnly?JT():BT()}function BT(){let e=KT,t=document.getElementById(`agentToolList`);if(!t)return;let n=e.mcpServices.filter(t=>!e.excludedSet.has(t.serverId)).length;t.querySelectorAll(`.agent-tool-category-clickable`).forEach(t=>{let r=t.dataset.category,i=t.querySelector(`.agent-tool-cat-count`);if(i)if(r===`mcp`)i.textContent=`${n}/${e.mcpServices.length}`;else{let t=e.allTools.filter(e=>(e.category||`other`)===r);i.textContent=`${t.filter(t=>e.selectedSet.has(t.id)).length}/${t.length}`}});let i=document.getElementById(`agentToolCount`);if(i){let t=e.allTools.filter(t=>e.selectedSet.has(t.id)).length,a=e.allTools.length+e.mcpServices.length;i.textContent=r(`agentConfig.selectedTotalCount`,{selected:e.inheritMode?a:t+n,total:a})}}function VT(){let e=document.getElementById(`agentSkillCount`);if(!e)return;let t=QT,n=t.skills.length;e.textContent=r(`agentConfig.selectedTotalCount`,{selected:t.inheritMode?n:t.selectedSet.size,total:n})}async function HT(e){let t=document.getElementById(`agentEditModal`);if(!t)return;await nE(),rE(-1),t.querySelector(`#agentEditId`).value=``,t.querySelector(`#agentEditName`).value=``,t.querySelector(`#agentEditIcon`).value=`🤖`;let n=t.querySelector(`#agentEditIconBtn`);n&&(n.textContent=`🤖`),t.querySelector(`#agentEditDesc`).value=``,t.querySelector(`#agentEditPrompt`).value=``,t.querySelector(`#agentEditAllowSub`).checked=!1,t.querySelector(`#agentTemplateSelect`).value=``,t.querySelector(`#agentEditModel`).value=``;let i=t.querySelector(`#agentDeleteBtn`),a=t.querySelector(`#agentEditTitle`);if(e){let n=await vt(e);if(!n||n.isBuiltin)return;a.textContent=r(`agentMgr.editAgent`),t.querySelector(`#agentEditId`).value=n.id,t.querySelector(`#agentEditName`).value=n.name,t.querySelector(`#agentEditIcon`).value=n.icon||`🤖`;let o=t.querySelector(`#agentEditIconBtn`);o&&(o.textContent=n.icon||`🤖`),t.querySelector(`#agentEditDesc`).value=n.description||``,t.querySelector(`#agentEditPrompt`).value=n.systemPrompt||``,t.querySelector(`#agentEditAllowSub`).checked=n.allowSubDispatch||!1,t.querySelector(`#agentEditModel`).value=n.model||``,rE(aE(n.temperature,n.topP)),i.style.display=`block`,qT(n.toolIds,n.mcpExcludedServerIds??[]),$T(n.skillIds)}else a.textContent=r(`agentEditor.createNew`),i.style.display=`none`,qT(null,[]),$T(null);WT(),t.style.display=`flex`;let o=t.querySelector(`#agentEditModel`);if(o){let e=o.value,t=o.cloneNode(!0);o.parentNode.replaceChild(t,o),t.value=e,t.addEventListener(`mousedown`,()=>{let e=t.value;e&&(t.dataset._saved=e,t.value=``)}),t.addEventListener(`blur`,()=>{setTimeout(()=>{t.value||=t.dataset._saved||``},150)})}}function UT(){let e=document.getElementById(`agentEditModal`);e&&(e.style.display=`none`)}function WT(){let e=document.getElementById(`agentTemplateSelect`);if(!e)return;let t=[r(`agentTemplates.codeReviewName`),r(`agentTemplates.webAutomationName`),r(`agentTemplates.dataAnalystName`),r(`agentTemplates.documentationName`)],n=`<option value="">${r(`agentEditor.selectTemplate`)}</option>`;for(let e=0;e<oe.length;e++){let r=oe[e];n+=`<option value="${e}">${r.icon} ${t[e]}</option>`}e.innerHTML=n}function GT(e){let t=parseInt(e.target.value);if(isNaN(t)||t<0||t>=oe.length)return;let n=oe[t],i=document.getElementById(`agentEditModal`);if(!i)return;let a=[`agentTemplates.codeReviewName`,`agentTemplates.webAutomationName`,`agentTemplates.dataAnalystName`,`agentTemplates.documentationName`],o=[`agentTemplates.codeReviewDesc`,`agentTemplates.webAutomationDesc`,`agentTemplates.dataAnalystDesc`,`agentTemplates.documentationDesc`];i.querySelector(`#agentEditName`).value=r(a[t]),i.querySelector(`#agentEditIcon`).value=n.icon;let c=i.querySelector(`#agentEditIconBtn`);c&&(c.textContent=n.icon),i.querySelector(`#agentEditDesc`).value=r(o[t]),i.querySelector(`#agentEditPrompt`).value=s()===`en`?n.systemPrompt:n.systemPromptZh||n.systemPrompt,i.querySelector(`#agentEditAllowSub`).checked=n.allowSubDispatch||!1,i.querySelector(`#agentEditModel`).value=n.model||``,rE(aE(n.temperature,n.topP)),qT(n.toolIds,[]),$T(n.skillIds||null),L(r(`agentMgr.templateLoaded`,{name:n.name}),`info`,2e3)}var KT={allTools:[],mcpServices:[],selectedSet:new Set,excludedSet:new Set,searchText:``,selectedOnly:!1,inheritMode:!1};async function qT(e,t){if(!document.getElementById(`agentToolList`))return;let n=[];try{n=(await chrome.storage.local.get([`mcpTools`])).mcpTools||[]}catch{}let{mcpEnabled:r,skillsEnabled:i,ragTools:a}=await chrome.storage.local.get([`mcpEnabled`,`skillsEnabled`,`ragTools`]),o=N.agentPlatform?.connected===!0,s=[...x,...a||[]];o||(s=s.filter(e=>!e.id.startsWith(`agent_`)&&!e.id.startsWith(`knowledge_`))),i===!1&&(s=s.filter(e=>e.id!==`agent_skill`));let c=[];if(r===!0&&o){let e=new Map;for(let t of n){let n=t.serverId||`unknown`;e.has(n)||e.set(n,{serverId:n,serverName:t.serverName||n,tools:[]}),e.get(n).tools.push(t)}c=Array.from(e.values())}let l=new Set(Array.isArray(t)?t:[]),u=KT;u.allTools=s,u.mcpServices=c,u.selectedSet=new Set(e||[]),u.excludedSet=l,u.searchText=``,u.selectedOnly=!1,u.inheritMode=!e;let d=document.getElementById(`agentToolSearchInput`);d&&(d.value=``);let f=document.getElementById(`agentToolSearchClear`);f&&(f.style.display=`none`),JT()}function JT(){let e=document.getElementById(`agentToolList`);if(!e)return;let t=KT,n=za({tools:t.allTools,services:t.mcpServices,selectedSet:t.selectedSet,excludedSet:t.excludedSet,query:t.searchText,selectedOnly:t.selectedOnly,getDesc:ta}),i=t.mcpServices.filter(e=>!t.excludedSet.has(e.serverId)).length,a={};for(let e of n.tools){let t=e.category||`other`;a[t]||(a[t]=[]),a[t].push(e)}let o=``;for(let[e,n]of Object.entries(a)){let i=r(`toolCategory.${e}`)===`toolCategory.${e}`?e:r(`toolCategory.${e}`),a=t.allTools.filter(t=>(t.category||`other`)===e),s=a.filter(e=>t.selectedSet.has(e.id)).length;o+=`<div class="agent-tool-category agent-tool-category-clickable" data-category="${Y(e)}" title="${Y(r(`agentConfig.toggleCategoryAll`))}">${i} <span class="agent-tool-cat-count" style="font-weight:400;color:var(--text-tertiary);">${s}/${a.length}</span></div>`;for(let r of n){let n=t.selectedSet.has(r.id)?`checked`:``,i=ta(r),a=i.length>40?i.substring(0,40)+`...`:i;o+=`
|
|
2069
2069
|
<label class="agent-tool-item" data-category="${Y(e)}">
|
|
2070
2070
|
<input type="checkbox" value="${Y(r.id)}" ${n} data-tool-id="${Y(r.id)}">
|
|
2071
2071
|
<span class="agent-tool-name" title="${Y(r.name)}">${dE(r.name)}</span>
|
|
@@ -2083,7 +2083,7 @@ Sessions using this assistant will revert to the default assistant.`,deleteAgent
|
|
|
2083
2083
|
<input type="checkbox" value="${Y(e.name)}" ${n}>
|
|
2084
2084
|
<span class="agent-tool-name" title="${Y(e.name)}">${dE(e.name)}</span>
|
|
2085
2085
|
<span class="agent-tool-desc" title="${Y(r)}">${dE(r.substring(0,40))}${r.length>40?`...`:``}</span>
|
|
2086
|
-
</label>`}).join(``)}let n=document.getElementById(`agentSkillSelectedOnlyBtn`);n&&(n.classList.toggle(`active`,t.selectedOnly),n.textContent=r(t.selectedOnly?`agentEditor.showAllSkills`:`agentEditor.selectedOnlyFilter`),n.title=r(`agentToolFilter.selectedCountHint`,{count:t.selectedSet.size})),VT()}function tE(){let e=QT,t=e.skills.filter(t=>e.selectedSet.has(t.name)).map(e=>e.name),n=new Set(t),r=[...e.selectedSet].filter(e=>!n.has(e)),i=[...t,...r];return i.length>0?i:null}async function nE(){let e=document.getElementById(`agentModelList`);if(e)return new Promise(t=>{chrome.storage.local.get([`customModels`],n=>{let r=[];(n.customModels||[]).forEach(e=>{let t;typeof e==`string`?t=e:e&&e.name&&(t=e.name),t&&!r.includes(t)&&r.push(t)}),e.innerHTML=r.map(e=>`<option value="${Y(e)}">`).join(``),t()})})}function rE(e){let t=document.getElementById(`agentEditTempPreset`);if(t){for(;t.options.length>1;)t.remove(1);Rn.forEach((e,n)=>{let i=document.createElement(`option`);i.value=n,i.textContent=`${r(e.labelKey)}(${e.temp.toFixed(2)})`,t.appendChild(i)}),e!==void 0&&e>=0?t.value=e:t.value=``}}function iE(){let e=document.getElementById(`agentEditTempPreset`);if(!e||e.value===``)return{temperature:null,topP:null};let t=parseInt(e.value);if(isNaN(t)||t<0||t>=Rn.length)return{temperature:null,topP:null};let n=Rn[t];return{temperature:n.temp,topP:n.topP}}function aE(e,t){if(e==null)return-1;for(let n=0;n<Rn.length;n++){let r=Rn[n];if(Math.abs(r.temp-e)<.001&&Math.abs(r.topP-(t||1))<.001)return n}return-1}async function oE(){let e=document.getElementById(`agentEditModal`);if(!e)return;let t=e.querySelector(`#agentEditId`).value,n=e.querySelector(`#agentEditName`).value.trim(),i=e.querySelector(`#agentEditIcon`).value.trim()||`🤖`,o=e.querySelector(`#agentEditDesc`).value.trim(),s=e.querySelector(`#agentEditPrompt`).value.trim(),c=e.querySelector(`#agentEditAllowSub`).checked,l=XT(),u=ZT(),d=tE(),f=e.querySelector(`#agentEditModel`).value.trim()||null,{temperature:p,topP:m}=iE();if(!n){L(r(`agentMgr.nameRequired`),`warning`);return}let h={name:n,icon:i,description:o,systemPrompt:s,allowSubDispatch:c,toolIds:l,skillIds:d,model:f,temperature:p,topP:m};u!==void 0&&(h.mcpExcludedServerIds=u);try{t?(await vt(t,h),t===N.activeAgentId&&u!==void 0&&(N.activeAgentMcpExcludedServerIds=u),L(r(`agentMgr.agentUpdated`),`success`)):L(r(`agentMgr.agentCreated`,{name:(await bt(h)).name}),`success`),await CT(),await wT(),UT(),Ma()}catch(e){a.error(`[AgentMgr] save Agent failed:`,e),L(r(`agentMgr.saveFailed`,{message:e.message}),`error`)}}async function sE(){let e=document.getElementById(`agentEditModal`);if(!e)return;let t=e.querySelector(`#agentEditId`)?.value;if(!t)return;let n=await _t(t);if(await fE(r(`agentMgr.confirmDeleteAgentMessage`,{name:n?n.name:``}),r(`agentMgr.deleteAgentTitle`)))try{await St(t),L(r(`agentMgr.agentDeleted`),`success`),await CT(),await wT(),UT()}catch(e){a.error(`[AgentMgr] delete Agent failed:`,e),L(r(`agentMgr.deleteFailed`,{message:e.message}),`error`)}}async function cE(e){if(!e)return!1;let t=await _t(e);if(!t||t.isBuiltin)return L(r(`agentMgr.cannotDeleteDefault`),`warning`),!1;if(!await fE(r(`agentMgr.confirmDeleteAgentMessage`,{name:t.name}),r(`agentMgr.deleteAgentTitle`)))return!1;try{return await St(e),L(r(`agentMgr.agentDeleted`),`success`),await CT(),await wT(),!0}catch(e){return a.error(`[AgentMgr] delete Agent failed:`,e),L(r(`agentMgr.deleteFailed`,{message:e.message}),`error`),!1}}async function lE(e=N.activeAgentId){return e?await _t(e):null}function uE(e){return e?e.toolIds:null}function dE(e){if(!e)return``;let t=document.createElement(`div`);return t.textContent=e,t.innerHTML}function Y(e){return e?e.replace(/["&<>]/g,e=>({'"':`"`,"&":`&`,"<":`<`,">":`>`})[e]):``}async function fE(e,t){return typeof window.showCustomConfirm==`function`?window.showCustomConfirm(e,t):new Promise(n=>{let i=document.getElementById(`agentConfirmModal`);if(!i){n(confirm(e));return}i.querySelector(`#agentConfirmMessage`).textContent=e,i.querySelector(`#agentConfirmTitle`).textContent=t||r(`agentMgr.confirm`),i.style.display=`flex`;let a=()=>{i.style.display=`none`,i.querySelector(`#agentConfirmOk`).removeEventListener(`click`,o),i.querySelector(`#agentConfirmCancel`).removeEventListener(`click`,s),i.removeEventListener(`click`,c)},o=()=>{a(),n(!0)},s=()=>{a(),n(!1)},c=e=>{e.target===i&&(a(),n(!1))};i.querySelector(`#agentConfirmOk`).addEventListener(`click`,o),i.querySelector(`#agentConfirmCancel`).addEventListener(`click`,s),i.addEventListener(`click`,c)})}n(`zh`,{contextUsage:{indicatorTitle:`上下文占用 {percent}%({used} / {total} tokens)· 点击查看详情`,memoryOffToast:`记忆已关闭,无可压缩内容`,generatingToast:`正在生成回复,请稍后再试`,nothingToCompactToast:`没有新的消息可压缩`,confirmTitle:`压缩上下文`,confirmMessage:`将压缩 {count} 条历史消息(约 {tokens} tokens)为一份摘要{summaryHint}。原始消息仍保留在会话中,发送新消息前可撤销。`,confirmWithOldSummary:`(含已有摘要,将合并为新摘要)`,confirmOk:`开始压缩`,compactingTitle:`正在压缩上下文`,compactingHint:`正在调用模型生成摘要,请稍候…(通常需要几秒到十几秒)`,compactDone:`压缩完成,节约约 {saved} tokens`,compactErrConfig:`无法压缩:API 配置缺失`,compactErrFailed:`压缩失败,请稍后重试`,compactErrEmpty:`模型未返回摘要内容`,compactErrHttp:`接口错误 HTTP {status}`,compactErrTimeout:`请求超时`,autoCompactedToast:`上下文接近上限,已自动压缩(预计省 {saved} tokens)`,undoTitle:`撤销压缩`,undoMessage:`撤销后,发送将恢复携带完整历史。确定撤销吗?`,undoOk:`撤销`,undoDone:`已撤销压缩`,dividerText:`⬆ 上方 {count} 条消息已压缩为摘要`,dividerView:`查看`,dividerUndo:`撤销`,popupTitle:`上下文占用明细`,rowSystem:`系统提示词`,rowTools:`工具定义`,rowHistory:`历史消息`,rowInput:`当前输入`,historyMeta:`选中 {selected} 条 / 共 {total} 条`,historyTrimmed:`为控制预算裁剪了 {count} 条(以规则摘要替代)`,refInfo:`输出预留 {output} · 安全余量 {safety}(不计入上方占用)`,memoryLabel:`记忆设置`,memoryAll:`携带全部历史`,memoryLimited:`携带最近 {n} 条`,memoryOff:`不携带历史(仅当前消息)`,compactionActive:`已压缩 {count} 条历史 · 摘要约 {tokens} tokens`,compactionInvalidHint:`压缩点已失效(对应消息已被删除),本次发送未使用压缩`,removeInvalid:`移除失效的压缩记录`,btnCompact:`压缩上下文`,btnCompactAgain:`再次压缩`,btnUndoCompact:`撤销压缩`,undoExpiredToast:`已发送新消息,无法再撤销压缩(可再次压缩合并更新)`,summaryTitle:`上下文摘要(压缩 {count} 条历史)`,summaryTabPreview:`预览`,summaryTabSource:`源码`}}),n(`en`,{contextUsage:{indicatorTitle:`Context usage {percent}% ({used} / {total} tokens) · Click for details`,memoryOffToast:`Memory is off, nothing to compact`,generatingToast:`Generating a reply, please try again later`,nothingToCompactToast:`No new messages to compact`,confirmTitle:`Compact Context`,confirmMessage:`Compact {count} history messages (~{tokens} tokens) into a summary{summaryHint}. Original messages remain in the session; undo is available before sending new messages.`,confirmWithOldSummary:` (including the existing summary, which will be merged into a new one)`,confirmOk:`Start Compaction`,compactingTitle:`Compacting Context`,compactingHint:`Generating a summary with the model, please wait… (usually takes a few seconds)`,compactDone:`Compaction complete, saved ~{saved} tokens`,compactErrConfig:`Cannot compact: API configuration missing`,compactErrFailed:`Compaction failed, please try again later`,compactErrEmpty:`the model returned no summary`,compactErrHttp:`API error HTTP {status}`,compactErrTimeout:`request timed out`,autoCompactedToast:`Context is near its limit; auto-compacted (est. {saved} tokens saved)`,undoTitle:`Undo Compaction`,undoMessage:`After undo, sending will include the full history again. Undo?`,undoOk:`Undo`,undoDone:`Compaction undone`,dividerText:`⬆ {count} messages above compacted into a summary`,dividerView:`View`,dividerUndo:`Undo`,popupTitle:`Context Usage Details`,rowSystem:`System prompt`,rowTools:`Tool definitions`,rowHistory:`History messages`,rowInput:`Current input`,historyMeta:`Selected {selected} / {total} total`,historyTrimmed:`{count} messages trimmed for budget (replaced by rule summary)`,refInfo:`Output reserve {output} · Safety margin {safety} (not counted above)`,memoryLabel:`Memory setting`,memoryAll:`Carry all history`,memoryLimited:`Carry latest {n} messages`,memoryOff:`No history (current message only)`,compactionActive:`{count} messages compacted · summary ~{tokens} tokens`,compactionInvalidHint:`Compaction point is stale (its message was deleted); this send ignores the compaction`,removeInvalid:`Remove stale compaction record`,btnCompact:`Compact Context`,btnCompactAgain:`Compact Again`,btnUndoCompact:`Undo Compaction`,undoExpiredToast:`New messages have been sent; compaction can no longer be undone (you can compact again)`,summaryTitle:`Context Summary ({count} messages compacted)`,summaryTabPreview:`Preview`,summaryTabSource:`Source`}});var pE=300,mE=``,hE=0,gE=null;async function _E(){try{let{mcpTools:e}=await chrome.storage.local.get([`mcpTools`]),t=e||[],n=new Set(Array.isArray(N.mcpClosedServers)?N.mcpClosedServers:[]),r=new Set(Array.isArray(N.activeAgentMcpExcludedServerIds)?N.activeAgentMcpExcludedServerIds:[]);return t.filter(e=>{let t=e.serverId||`unknown`;return!n.has(t)&&!r.has(t)}).length}catch{return 0}}function vE(){let e=document.getElementById(`userInput`)?.value||``;return{usage:Gn({model:N.currentModel,customModelMap:N.customModelMap,systemPromptText:mE,toolCount:(N.useTools?N.enabledTools.length:0)+hE,history:N.messageHistory,inputText:e,maxMemoryMessages:N.chatConfig?.maxMemoryMessages??null,compaction:N.activeCompaction,isolateChat:N.isolateChat}),inputText:e}}function yE(e){let t=document.getElementById(`contextUsageIndicator`);if(!t)return;t._lastUsage=e,t.dataset.level=e.level;let n=Math.round(e.ratio*100),i=t.querySelector(`.context-usage-percent`);i&&(i.textContent=`${n}%`),t.style.setProperty(`--usage-ratio`,String(Math.min(Math.max(e.ratio,0),1))),t.title=r(`contextUsage.indicatorTitle`,{percent:n,used:F(e.usedTokens),total:F(e.contextWindow)})}function bE(){try{let{usage:e}=vE();return yE(e),ME(),e}catch(e){return a.warn(`[ContextIndicator] update failed:`,e?.message),null}}function xE(){clearTimeout(gE),gE=setTimeout(()=>bE(),pE)}async function SE(e=null){let t=e===null?N.activeSessionId:e;try{mE=await Gt(await lE(),{sessionId:t})}catch(e){a.warn(`[ContextIndicator] refresh system prompt failed:`,e?.message)}try{hE=await _E()}catch{hE=0}bE()}function CE(){let e=document.getElementById(`contextUsageIndicator`);e&&(e.addEventListener(`click`,()=>IE()),document.getElementById(`userInput`)?.addEventListener(`input`,xE),document.addEventListener(`generating-state-changed`,()=>{SE()}),document.addEventListener(`agent-model-changed`,()=>{SE()}),document.addEventListener(`session-switched`,()=>{SE()}),document.addEventListener(`session-workdir-changed`,()=>{SE()}),chrome.storage.onChanged.addListener((e,t)=>{t===`local`&&((e.chatMaxMemoryMessages||e.isolateChat)&&xE(),(e.modelName||e.customModels)&&xE(),(e.isolateChat||e.mcpTools||e.mcpEnabled||e.enabledTools||e.enableTools)&&SE())}),SE())}function wE({title:e,message:t,okText:n}){return new Promise(i=>{let a=document.createElement(`div`);a.className=`modal-overlay show`,a.style.zIndex=`10200`,a.innerHTML=`
|
|
2086
|
+
</label>`}).join(``)}let n=document.getElementById(`agentSkillSelectedOnlyBtn`);n&&(n.classList.toggle(`active`,t.selectedOnly),n.textContent=r(t.selectedOnly?`agentEditor.showAllSkills`:`agentEditor.selectedOnlyFilter`),n.title=r(`agentToolFilter.selectedCountHint`,{count:t.selectedSet.size})),VT()}function tE(){let e=QT,t=e.skills.filter(t=>e.selectedSet.has(t.name)).map(e=>e.name),n=new Set(t),r=[...e.selectedSet].filter(e=>!n.has(e)),i=[...t,...r];return i.length>0?i:null}async function nE(){let e=document.getElementById(`agentModelList`);if(e)return new Promise(t=>{chrome.storage.local.get([`customModels`],n=>{let r=[];(n.customModels||[]).forEach(e=>{let t;typeof e==`string`?t=e:e&&e.name&&(t=e.name),t&&!r.includes(t)&&r.push(t)}),e.innerHTML=r.map(e=>`<option value="${Y(e)}">`).join(``),t()})})}function rE(e){let t=document.getElementById(`agentEditTempPreset`);if(t){for(;t.options.length>1;)t.remove(1);Rn.forEach((e,n)=>{let i=document.createElement(`option`);i.value=n,i.textContent=`${r(e.labelKey)}(${e.temp.toFixed(2)})`,t.appendChild(i)}),e!==void 0&&e>=0?t.value=e:t.value=``}}function iE(){let e=document.getElementById(`agentEditTempPreset`);if(!e||e.value===``)return{temperature:null,topP:null};let t=parseInt(e.value);if(isNaN(t)||t<0||t>=Rn.length)return{temperature:null,topP:null};let n=Rn[t];return{temperature:n.temp,topP:n.topP}}function aE(e,t){if(e==null)return-1;for(let n=0;n<Rn.length;n++){let r=Rn[n];if(Math.abs(r.temp-e)<.001&&Math.abs(r.topP-(t||1))<.001)return n}return-1}async function oE(){let e=document.getElementById(`agentEditModal`);if(!e)return;let t=e.querySelector(`#agentEditId`).value,n=e.querySelector(`#agentEditName`).value.trim(),i=e.querySelector(`#agentEditIcon`).value.trim()||`🤖`,o=e.querySelector(`#agentEditDesc`).value.trim(),s=e.querySelector(`#agentEditPrompt`).value.trim(),c=e.querySelector(`#agentEditAllowSub`).checked,l=XT(),u=ZT(),d=tE(),f=e.querySelector(`#agentEditModel`).value.trim()||null,{temperature:p,topP:m}=iE();if(!n){L(r(`agentMgr.nameRequired`),`warning`);return}let h={name:n,icon:i,description:o,systemPrompt:s,allowSubDispatch:c,toolIds:l,skillIds:d,model:f,temperature:p,topP:m};u!==void 0&&(h.mcpExcludedServerIds=u);try{t?(await yt(t,h),t===N.activeAgentId&&u!==void 0&&(N.activeAgentMcpExcludedServerIds=u),L(r(`agentMgr.agentUpdated`),`success`)):L(r(`agentMgr.agentCreated`,{name:(await xt(h)).name}),`success`),await CT(),await wT(),UT(),Ma()}catch(e){a.error(`[AgentMgr] save Agent failed:`,e),L(r(`agentMgr.saveFailed`,{message:e.message}),`error`)}}async function sE(){let e=document.getElementById(`agentEditModal`);if(!e)return;let t=e.querySelector(`#agentEditId`)?.value;if(!t)return;let n=await vt(t);if(await fE(r(`agentMgr.confirmDeleteAgentMessage`,{name:n?n.name:``}),r(`agentMgr.deleteAgentTitle`)))try{await Ct(t),L(r(`agentMgr.agentDeleted`),`success`),await CT(),await wT(),UT()}catch(e){a.error(`[AgentMgr] delete Agent failed:`,e),L(r(`agentMgr.deleteFailed`,{message:e.message}),`error`)}}async function cE(e){if(!e)return!1;let t=await vt(e);if(!t||t.isBuiltin)return L(r(`agentMgr.cannotDeleteDefault`),`warning`),!1;if(!await fE(r(`agentMgr.confirmDeleteAgentMessage`,{name:t.name}),r(`agentMgr.deleteAgentTitle`)))return!1;try{return await Ct(e),L(r(`agentMgr.agentDeleted`),`success`),await CT(),await wT(),!0}catch(e){return a.error(`[AgentMgr] delete Agent failed:`,e),L(r(`agentMgr.deleteFailed`,{message:e.message}),`error`),!1}}async function lE(e=N.activeAgentId){return e?await vt(e):null}function uE(e){return e?e.toolIds:null}function dE(e){if(!e)return``;let t=document.createElement(`div`);return t.textContent=e,t.innerHTML}function Y(e){return e?e.replace(/["&<>]/g,e=>({'"':`"`,"&":`&`,"<":`<`,">":`>`})[e]):``}async function fE(e,t){return typeof window.showCustomConfirm==`function`?window.showCustomConfirm(e,t):new Promise(n=>{let i=document.getElementById(`agentConfirmModal`);if(!i){n(confirm(e));return}i.querySelector(`#agentConfirmMessage`).textContent=e,i.querySelector(`#agentConfirmTitle`).textContent=t||r(`agentMgr.confirm`),i.style.display=`flex`;let a=()=>{i.style.display=`none`,i.querySelector(`#agentConfirmOk`).removeEventListener(`click`,o),i.querySelector(`#agentConfirmCancel`).removeEventListener(`click`,s),i.removeEventListener(`click`,c)},o=()=>{a(),n(!0)},s=()=>{a(),n(!1)},c=e=>{e.target===i&&(a(),n(!1))};i.querySelector(`#agentConfirmOk`).addEventListener(`click`,o),i.querySelector(`#agentConfirmCancel`).addEventListener(`click`,s),i.addEventListener(`click`,c)})}n(`zh`,{contextUsage:{indicatorTitle:`上下文占用 {percent}%({used} / {total} tokens)· 点击查看详情`,memoryOffToast:`记忆已关闭,无可压缩内容`,generatingToast:`正在生成回复,请稍后再试`,nothingToCompactToast:`没有新的消息可压缩`,confirmTitle:`压缩上下文`,confirmMessage:`将压缩 {count} 条历史消息(约 {tokens} tokens)为一份摘要{summaryHint}。原始消息仍保留在会话中,发送新消息前可撤销。`,confirmWithOldSummary:`(含已有摘要,将合并为新摘要)`,confirmOk:`开始压缩`,compactingTitle:`正在压缩上下文`,compactingHint:`正在调用模型生成摘要,请稍候…(通常需要几秒到十几秒)`,compactDone:`压缩完成,节约约 {saved} tokens`,compactErrConfig:`无法压缩:API 配置缺失`,compactErrFailed:`压缩失败,请稍后重试`,compactErrEmpty:`模型未返回摘要内容`,compactErrHttp:`接口错误 HTTP {status}`,compactErrTimeout:`请求超时`,autoCompactedToast:`上下文接近上限,已自动压缩(预计省 {saved} tokens)`,undoTitle:`撤销压缩`,undoMessage:`撤销后,发送将恢复携带完整历史。确定撤销吗?`,undoOk:`撤销`,undoDone:`已撤销压缩`,dividerText:`⬆ 上方 {count} 条消息已压缩为摘要`,dividerView:`查看`,dividerUndo:`撤销`,popupTitle:`上下文占用明细`,rowSystem:`系统提示词`,rowTools:`工具定义`,rowHistory:`历史消息`,rowInput:`当前输入`,historyMeta:`选中 {selected} 条 / 共 {total} 条`,historyTrimmed:`为控制预算裁剪了 {count} 条(以规则摘要替代)`,refInfo:`输出预留 {output} · 安全余量 {safety}(不计入上方占用)`,memoryLabel:`记忆设置`,memoryAll:`携带全部历史`,memoryLimited:`携带最近 {n} 条`,memoryOff:`不携带历史(仅当前消息)`,compactionActive:`已压缩 {count} 条历史 · 摘要约 {tokens} tokens`,compactionInvalidHint:`压缩点已失效(对应消息已被删除),本次发送未使用压缩`,removeInvalid:`移除失效的压缩记录`,btnCompact:`压缩上下文`,btnCompactAgain:`再次压缩`,btnUndoCompact:`撤销压缩`,undoExpiredToast:`已发送新消息,无法再撤销压缩(可再次压缩合并更新)`,summaryTitle:`上下文摘要(压缩 {count} 条历史)`,summaryTabPreview:`预览`,summaryTabSource:`源码`}}),n(`en`,{contextUsage:{indicatorTitle:`Context usage {percent}% ({used} / {total} tokens) · Click for details`,memoryOffToast:`Memory is off, nothing to compact`,generatingToast:`Generating a reply, please try again later`,nothingToCompactToast:`No new messages to compact`,confirmTitle:`Compact Context`,confirmMessage:`Compact {count} history messages (~{tokens} tokens) into a summary{summaryHint}. Original messages remain in the session; undo is available before sending new messages.`,confirmWithOldSummary:` (including the existing summary, which will be merged into a new one)`,confirmOk:`Start Compaction`,compactingTitle:`Compacting Context`,compactingHint:`Generating a summary with the model, please wait… (usually takes a few seconds)`,compactDone:`Compaction complete, saved ~{saved} tokens`,compactErrConfig:`Cannot compact: API configuration missing`,compactErrFailed:`Compaction failed, please try again later`,compactErrEmpty:`the model returned no summary`,compactErrHttp:`API error HTTP {status}`,compactErrTimeout:`request timed out`,autoCompactedToast:`Context is near its limit; auto-compacted (est. {saved} tokens saved)`,undoTitle:`Undo Compaction`,undoMessage:`After undo, sending will include the full history again. Undo?`,undoOk:`Undo`,undoDone:`Compaction undone`,dividerText:`⬆ {count} messages above compacted into a summary`,dividerView:`View`,dividerUndo:`Undo`,popupTitle:`Context Usage Details`,rowSystem:`System prompt`,rowTools:`Tool definitions`,rowHistory:`History messages`,rowInput:`Current input`,historyMeta:`Selected {selected} / {total} total`,historyTrimmed:`{count} messages trimmed for budget (replaced by rule summary)`,refInfo:`Output reserve {output} · Safety margin {safety} (not counted above)`,memoryLabel:`Memory setting`,memoryAll:`Carry all history`,memoryLimited:`Carry latest {n} messages`,memoryOff:`No history (current message only)`,compactionActive:`{count} messages compacted · summary ~{tokens} tokens`,compactionInvalidHint:`Compaction point is stale (its message was deleted); this send ignores the compaction`,removeInvalid:`Remove stale compaction record`,btnCompact:`Compact Context`,btnCompactAgain:`Compact Again`,btnUndoCompact:`Undo Compaction`,undoExpiredToast:`New messages have been sent; compaction can no longer be undone (you can compact again)`,summaryTitle:`Context Summary ({count} messages compacted)`,summaryTabPreview:`Preview`,summaryTabSource:`Source`}});var pE=300,mE=``,hE=0,gE=null;async function _E(){try{let{mcpTools:e}=await chrome.storage.local.get([`mcpTools`]),t=e||[],n=new Set(Array.isArray(N.mcpClosedServers)?N.mcpClosedServers:[]),r=new Set(Array.isArray(N.activeAgentMcpExcludedServerIds)?N.activeAgentMcpExcludedServerIds:[]);return t.filter(e=>{let t=e.serverId||`unknown`;return!n.has(t)&&!r.has(t)}).length}catch{return 0}}function vE(){let e=document.getElementById(`userInput`)?.value||``;return{usage:Gn({model:N.currentModel,customModelMap:N.customModelMap,systemPromptText:mE,toolCount:(N.useTools?N.enabledTools.length:0)+hE,history:N.messageHistory,inputText:e,maxMemoryMessages:N.chatConfig?.maxMemoryMessages??null,compaction:N.activeCompaction,isolateChat:N.isolateChat}),inputText:e}}function yE(e){let t=document.getElementById(`contextUsageIndicator`);if(!t)return;t._lastUsage=e,t.dataset.level=e.level;let n=Math.round(e.ratio*100),i=t.querySelector(`.context-usage-percent`);i&&(i.textContent=`${n}%`),t.style.setProperty(`--usage-ratio`,String(Math.min(Math.max(e.ratio,0),1))),t.title=r(`contextUsage.indicatorTitle`,{percent:n,used:F(e.usedTokens),total:F(e.contextWindow)})}function bE(){try{let{usage:e}=vE();return yE(e),ME(),e}catch(e){return a.warn(`[ContextIndicator] update failed:`,e?.message),null}}function xE(){clearTimeout(gE),gE=setTimeout(()=>bE(),pE)}async function SE(e=null){let t=e===null?N.activeSessionId:e;try{mE=await Kt(await lE(),{sessionId:t})}catch(e){a.warn(`[ContextIndicator] refresh system prompt failed:`,e?.message)}try{hE=await _E()}catch{hE=0}bE()}function CE(){let e=document.getElementById(`contextUsageIndicator`);e&&(e.addEventListener(`click`,()=>IE()),document.getElementById(`userInput`)?.addEventListener(`input`,xE),document.addEventListener(`generating-state-changed`,()=>{SE()}),document.addEventListener(`agent-model-changed`,()=>{SE()}),document.addEventListener(`session-switched`,()=>{SE()}),document.addEventListener(`session-workdir-changed`,()=>{SE()}),chrome.storage.onChanged.addListener((e,t)=>{t===`local`&&((e.chatMaxMemoryMessages||e.isolateChat)&&xE(),(e.modelName||e.customModels)&&xE(),(e.isolateChat||e.mcpTools||e.mcpEnabled||e.enabledTools||e.enableTools)&&SE())}),SE())}function wE({title:e,message:t,okText:n}){return new Promise(i=>{let a=document.createElement(`div`);a.className=`modal-overlay show`,a.style.zIndex=`10200`,a.innerHTML=`
|
|
2087
2087
|
<div class="modal-container">
|
|
2088
2088
|
<div class="modal-title"></div>
|
|
2089
2089
|
<div class="modal-message"></div>
|
|
@@ -2120,18 +2120,18 @@ Sessions using this assistant will revert to the default assistant.`,deleteAgent
|
|
|
2120
2120
|
<div class="context-usage-popup-body">
|
|
2121
2121
|
<div class="context-usage-total">
|
|
2122
2122
|
<span class="context-usage-total-percent">${i}%</span>
|
|
2123
|
-
<span class="context-usage-total-detail">${
|
|
2123
|
+
<span class="context-usage-total-detail">${Ft(t.usedTokens)} / ${Ft(t.contextWindow)}</span>
|
|
2124
2124
|
</div>
|
|
2125
2125
|
<div class="context-usage-bar"><div class="context-usage-bar-fill" style="width:${Math.min(i,100)}%"></div></div>
|
|
2126
2126
|
<div class="context-usage-section">
|
|
2127
|
-
<div class="context-usage-row"><span>${r(`contextUsage.rowSystem`)}</span><span>${
|
|
2128
|
-
<div class="context-usage-row"><span>${r(`contextUsage.rowTools`)}</span><span>${
|
|
2129
|
-
<div class="context-usage-row"><span>${r(`contextUsage.rowHistory`)}</span><span>${
|
|
2127
|
+
<div class="context-usage-row"><span>${r(`contextUsage.rowSystem`)}</span><span>${Ft(n.system)}</span></div>
|
|
2128
|
+
<div class="context-usage-row"><span>${r(`contextUsage.rowTools`)}</span><span>${Ft(n.tools)}</span></div>
|
|
2129
|
+
<div class="context-usage-row"><span>${r(`contextUsage.rowHistory`)}</span><span>${Ft(n.history)}</span></div>
|
|
2130
2130
|
<div class="context-usage-dim">${c}</div>
|
|
2131
2131
|
${l}
|
|
2132
|
-
<div class="context-usage-row"><span>${r(`contextUsage.rowInput`)}</span><span>${
|
|
2132
|
+
<div class="context-usage-row"><span>${r(`contextUsage.rowInput`)}</span><span>${Ft(n.input)}</span></div>
|
|
2133
2133
|
</div>
|
|
2134
|
-
<div class="context-usage-section context-usage-dim">${r(`contextUsage.refInfo`,{output:
|
|
2134
|
+
<div class="context-usage-section context-usage-dim">${r(`contextUsage.refInfo`,{output:Ft(n.outputReserve),safety:Ft(n.safetyMargin)})}</div>
|
|
2135
2135
|
<div class="context-usage-section">
|
|
2136
2136
|
<div class="context-usage-row"><span>${r(`contextUsage.memoryLabel`)}</span><span>${a}</span></div>
|
|
2137
2137
|
</div>
|
|
@@ -2149,7 +2149,7 @@ Sessions using this assistant will revert to the default assistant.`,deleteAgent
|
|
|
2149
2149
|
<div class="context-usage-summary-body"></div>
|
|
2150
2150
|
</div>
|
|
2151
2151
|
`,document.body.appendChild(t);let n=t.querySelector(`.context-usage-summary-body`),i=t.querySelectorAll(`.context-usage-summary-tab`),a=t=>{i.forEach(e=>e.classList.toggle(`active`,e.dataset.mode===t)),t===`preview`?(n.classList.add(`markdown-body`),n.innerHTML=on(e.summary),sn()):(n.classList.remove(`markdown-body`),n.textContent=e.summary)};i.forEach(e=>e.addEventListener(`click`,()=>a(e.dataset.mode))),a(`preview`),t.querySelector(`.context-usage-summary-close`).addEventListener(`click`,()=>t.remove()),t.addEventListener(`click`,e=>{e.target===t&&t.remove()})}var RE=`panel-observer-`,zE=new Map;function BE(e){if(!e)return null;let t=zE.get(e);if(t)return t;let n;try{n=chrome.runtime.connect({name:`${RE}${e}`})}catch(e){return a.debug(`[PanelObserver] 建立观察端口失败(忽略):`,e?.message||e),null}zE.set(e,n);try{n.onDisconnect.addListener(()=>{zE.get(e)===n&&zE.delete(e)})}catch(e){a.debug(`[PanelObserver] 观察端口断开监听挂不上(忽略):`,e?.message||e)}return n}function VE(e){if(!e)return;let t=zE.get(e);if(t){zE.delete(e);try{t.disconnect()}catch(e){a.debug(`[PanelObserver] 关闭观察端口异常(忽略):`,e?.message||e)}}}function HE({sessionId:e,callId:t,renderer:n,persist:r,onFinished:i=()=>{},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(()=>r(e)).catch(e=>a.warn(`[ChatReattach] 终态落库失败(忽略):`,e?.message||e)).then(()=>{try{i()}catch{}})};return{sessionId:e,callId:t,get finished(){return l},dispose(){l=!0},restore(e){if(!u)return;u=!1;let r=!!e&&e.callId===t,i=r&&typeof e.accumulated==`string`?e.accumulated:``,a=r&&!!e.html;a&&n.restore?.({html:e.html}),c=i,i&&!a&&n.chunk?.(i);let o=p(d);d=[];for(let e of o)g(e)},handleMessage(e){return l||!f(e)?!1:u?e.type===`STREAM_CHUNK`?(d.push(e),!0):e.type===`API_COMPLETE`||e.type===`API_ERROR`?(m(),g(e)):(d.push(e),!0):g(e)}};function g(r){switch(r.type){case`STREAM_START`:return c=``,n.start?.(),!0;case`STREAM_CHUNK`:return c+=r.delta||``,n.chunk?.(c),!0;case`STREAM_TOOL_CALL`:return n.toolCalls?.(r.toolCalls||[]),!0;case`STREAM_TOOL_RESULT`:return r.result&&n.toolResult?.(r.result),!0;case`AGENT_STREAM`:return r.execId&&n.agentStream?.(r),!0;case`AGENT_STREAM_DONE`:return r.execId&&n.agentStreamDone?.(r),!0;case`API_RETRYING`:return n.retrying?.(r.attempt,r.maxRetries),!0;case`STREAM_PRESELECT`:return n.preselect?.(r.preselectLog||[]),!0;case`EXECUTION_STATUS_UPDATE`:return!0;case`API_COMPLETE`:{let i=r.content&&String(r.content).trim()?r.content:o||c,a=r.executionLog||[],s={reflectionScore:r.reflectionScore,reasoningContent:r.reasoningContent||null,wasRevised:r.wasRevised||!1,budgetEnded:r.budgetEnded===!0};return n.final?.(i,a,s),h({sessionId:e,callId:t,content:i,executionLog:a,...s}),!0}case`API_ERROR`:return n.error?.(r.error||``,r.executionLog||[]),h({sessionId:e,callId:t,error:r.error||``,executionLog:r.executionLog||[]}),!0;default:return!1}}}function UE({queryRunning:e,hasLocalListener:t,isAttached:n,attach:r}){return{async syncFromBackground(){try{let i=await e(),a=i&&i.activeCallIds?i.activeCallIds:{};for(let[e,i]of Object.entries(a))!e||!i||t(e)||n(e,i)||r(e,i)}catch(e){a.debug(`[ChatReattach] 查询后台运行状态失败(忽略):`,e?.message||e)}}}}var WE=!1,GE=new Map,KE=null,qE=!1,JE=null,YE=null,XE=null,ZE=250,QE=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 $E(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 eD(e,t){let n=new Map;return{start(){VS(e,``),YS(``),GS(Date.now()),nC(t),wS(t)},chunk(n){VS(e,n),oC(t,n)},restore({html:e}){eC(t,e)},toolCalls(e){sC(t,e)},toolResult(e){uC(e,t)},agentStream(e){let r=n.get(e.execId);r||(r={element:lC(e.toolCallId?t.querySelector(`.tool-call-item[data-tool-call-id="${e.toolCallId}"]`):null,t.querySelector(`.stream-content`)),stdout:``,stderr:``},n.set(e.execId,r),sn());let i=r.element.querySelector(`code`);i&&(e.streamType===`stderr`?r.stderr+=e.data||``:r.stdout+=e.data||``,i.textContent=r.stdout+(r.stderr?`
|
|
2152
|
-
`+r.stderr:``),i.parentElement.scrollTop=i.parentElement.scrollHeight)},agentStreamDone(e){let t=n.get(e.execId);t&&e.exitCode!==0&&t.element.classList.add(`agent-stream-error`)},retrying(e,n){tC(t,e,n)},preselect(e){let n=t.querySelector(`.message-content`);!n||!e.length||e.forEach(e=>n.insertBefore(dC(e),n.firstChild))},final(e,n,r={}){fC(t,e,n,r.reflectionScore,r.reasoningContent,r.wasRevised)},error(e,n){fC(t,e,n||[])}}}async function tD(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),N.activeSessionId===t){N.messageHistory.push(i);try{document.dispatchEvent(new CustomEvent(`session-cache-invalidate`,{detail:{sessionId:t}}))}catch{}}let{appendMessageToSession:a}=await M(async()=>{let{appendMessageToSession:e}=await Promise.resolve().then(()=>ki);return{appendMessageToSession:e}},void 0);await a(t,i)}function nD(){M(()=>Promise.resolve().then(()=>hC).then(e=>e.syncPendingSessionsToStorage()),void 0).catch(e=>a.debug(`[ChatReattach] 同步生成态失败(忽略):`,e?.message||e))}var rD=1e3;function iD(e){return Promise.race([pS(e),new Promise(e=>setTimeout(()=>e(null),rD))])}function aD(e,t){let n=RS(e);if(n())return!1;let i=QS(e);i.dataset.callId=t,n(i),VS(e,``),GS(Date.now()),qS(Date.now()),N.pendingCallApiSessionIds.add(e),N.generatingSessionIds.add(e),nD();try{document.dispatchEvent(new CustomEvent(`generating-state-changed`))}catch{}let o=HE({sessionId:e,callId:t,awaitSnapshot:!0,renderer:eD(e,i),persist:t=>tD(t,e,i),emptyFallback:r(`chatMsg.emptyModelReply`),onFinished:()=>{if(GE.get(e)===o){GE.delete(e),VE(e),N.pendingCallApiSessionIds.delete(e),nD(),zS(e);try{document.dispatchEvent(new CustomEvent(`session-cache-invalidate`,{detail:{sessionId:e}}))}catch{}jl(e)}}});return GE.set(e,o),BE(e),iD(e).then(t=>{o.finished||GE.get(e)!==o||o.restore(t)}).catch(()=>o.restore(null)),N.activeSessionId===e&&iC(e),a.info(`[ChatReattach] 已接管运行中的任务: sessionId=${e}, callId=${t}`),!0}function oD(e){let t=GE.get(e);if(!t)return;GE.delete(e),VE(e);try{t.dispose?.()}catch{}let n=RS(e),r=n();try{r?.remove()}catch{}n(null),zS(e),N.pendingCallApiSessionIds.delete(e),nD();try{document.dispatchEvent(new CustomEvent(`generating-state-changed`))}catch{}}function sD(){let e=KE;e&&Promise.resolve().then(()=>e.syncFromBackground()).catch(e=>a.debug(`[ChatReattach] 对齐后台状态失败(忽略):`,e?.message||e))}function cD(){!WE||!KE||XE||(XE=setTimeout(()=>{XE=null,sD()},ZE))}var lD=new Map,uD=3e3,dD=100,fD=new Set,pD=new Set([`API_COMPLETE`,`API_ERROR`]);function mD(e,t){let n=`${e}|${t.callId}`;fD.has(n)||(fD.add(n),fD.size>dD&&fD.delete(fD.values().next().value),oD(e),aD(e,t.callId)&&GE.get(e)?.handleMessage(t))}function hD(e,t,n){let r=lD.get(e);if(r){r.messages.push(n);return}r={callId:t,messages:[n]},lD.set(e,r),$E(uD).then(t=>gD(e,t&&t.activeCallIds&&t.activeCallIds[e]||null)).catch(()=>gD(e,null)).finally(()=>{lD.delete(e)})}function gD(e,t){let n=lD.get(e);if(!n)return;let{callId:r,messages:i}=n;if(t===r)oD(e),aD(e,r);else if(t===null){let t=i.find(e=>pD.has(e.type));if(!t)return;mD(e,t);return}else return;let a=GE.get(e);if(!(!a||a.callId!==r))for(let e of i){if(a.finished)break;a.handleMessage(e)}}function _D(){qE||(qE=!0,chrome.runtime.onMessage.addListener(e=>{if(!e)return!1;let t=e.sessionId?GE.get(e.sessionId):null;return t?e.callId&&e.callId!==t.callId?(hD(e.sessionId,e.callId,e),!1):(BE(e.sessionId),t.handleMessage(e),!1):(e.callId&&QE.has(e.type)&&cD(),!1)}),JE=e=>{let t=e?.detail?.sessionId;t&&GE.has(t)&&iC(t),cD()},document.addEventListener(`session-hydrated`,JE),YE=e=>{let t=e?.detail?.sessionId;t&&GE.has(t)&&iC(t)},document.addEventListener(`chat-history-rendered`,YE))}function vD(){return WE?{syncFromBackground:()=>KE.syncFromBackground()}:(WE=!0,_D(),KE=UE({queryRunning:$E,hasLocalListener:e=>N.pendingCancelApiMap.has(e),isAttached:(e,t)=>GE.get(e)?.callId===t?(BE(e),!0):!1,attach:(e,t)=>{aD(e,t)}}),KE.syncFromBackground(),{syncFromBackground:()=>KE.syncFromBackground()})}function yD(e){!WE||!KE||(e&&N.activeSessionId===e&&iC(e),KE.syncFromBackground())}n(`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:`未知会话`}}),n(`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 bD=`sessionDockDismissed`,xD=5e3,SD=250,CD=1200,wD=8,TD=wD-1,ED=9e4,DD={running:0,queued:1,done:2},OD=new Map,kD=new Map,AD=new Map,jD=new Map,MD=new Set,ND=new Set,PD=new Map,FD=new Map,ID=new Set,LD=new Set,RD=[],zD=new Set,BD=null,VD=null,HD=null,UD=[],WD=!1,GD=null,KD=null,qD=!1,JD=null,YD=null;function XD(e){return e?Array.isArray(e)?e:e instanceof Set?Array.from(e):[]:[]}function ZD(e){let t=new Set;for(let n of XD(e))n&&t.add(me(String(n))||String(n));return t}function QD({phase:e=``,sessionId:t=null,backendRunningIds:n=[],startedAt:r=0,lastUpdateAt:i=0,now:a=Date.now(),staleMs:o=ED}={}){if(e!==`running`||!t||XD(n).includes(t))return!1;let s=Math.max(Number(r)||0,Number(i)||0);return s?a-s>=o:!1}var $D=160;function eO(e){let t=String(e??``).replace(/\s+/g,` `).trim();if(!t)return``;let n=Array.from(t);return n.length<=$D?t:`${n.slice(0,$D).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 nO({phase:e=``,queuedText:t=``,questionText:n=``,title:r=``}={}){let i=e===`queued`?eO(t):``,a=i||eO(n),o=eO(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 rO(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=d(n.content);if(r&&String(r).trim())return{text:String(r),messageId:n.messageId?String(n.messageId):``}}return{text:``,messageId:``}}function iO({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:_=ED}={}){let v=XD(s),y=new Set([...XD(a),...XD(o),...v]),b=new Set(XD(c)),x=new Set(XD(d)),S=new Set(XD(u)),C=l||{},w=new Set([...y,...b,...Object.keys(C)]),T=[];for(let a of w){if(!a||a===e)continue;let o=Number(C[a])||0,s;if(y.has(a))s=`running`;else if(o>0)s=`queued`;else if(b.has(a))s=`done`;else continue;let c=QD({phase:s,sessionId:a,backendRunningIds:v,startedAt:p?.[a],lastUpdateAt:h?.[a],now:g,staleMs:_});if(x.has(a)&&(s===`done`||c))continue;let l=f?.[a]||{},u=nO({phase:s,queuedText:i?.[a]||``,questionText:n?.[a]||``,title:t?.[a]||``});T.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:S.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 T.sort((e,t)=>{let n=DD[e.phase]-DD[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}),T}function aO(e){return LD.has(e)||N.generatingSessionIds.has(e)||N.pendingCallApiSessionIds.has(e)}function oO(){let e={};try{let t=Xr();for(let n of t){let t=Kr(n);t>0&&(e[n]=t)}}catch(e){a.debug(`[SessionDock] read queue counts failed:`,e?.message||e)}return e}function sO(){let e={};for(let t of N.sessions||[])e[t.id]=t.title||``;for(let[t,n]of PD)e[t]||(e[t]=n);return e}function cO(){let e={},t={},n=new Map;for(let e of N.sessions||[])n.set(e.id,e);for(let r of new Set([...LD,...N.generatingSessionIds,...N.pendingCallApiSessionIds,...N.completedSessionIds])){let i=kD.get(r)||AD.get(r)||0,a=FD.get(r);if(i&&a&&a.stamp===i){a.text&&(e[r]=a.text,t[r]=a.messageId||``);continue}let o=rO(n.get(r));o.text&&(e[r]=o.text,t[r]=o.messageId)}return{questions:e,anchors:t}}function lO(){let e={};try{for(let t of Xr()){let n=qr(t);n?.text&&(e[t]=String(n.text))}}catch(e){a.debug(`[SessionDock] read queued texts failed:`,e?.message||e)}return e}function uO(e){for(let t of e||[]){let e=t.sessionId;if(!e)continue;let n=t.startedAt||t.doneAt||0,r=FD.get(e),i=!r||r.stamp!==n,o=!t.title;!i&&!o||ID.has(e)||(ID.add(e),je(e).then(t=>{if(t&&((o||!PD.has(e))&&PD.set(e,t.title||``),i)){let r=rO(t);FD.set(e,{text:r.text,messageId:r.messageId,stamp:n})}}).catch(e=>{a.debug(`[SessionDock] hydrate label failed:`,e?.message||e)}).finally(()=>{ID.delete(e),FO()}))}}function dO(e){if(!e)return``;let t=new Date(e);return`${String(t.getHours()).padStart(2,`0`)}:${String(t.getMinutes()).padStart(2,`0`)}`}function fO(e){if(e.phase===`running`){if(e.stale)return r(`dock.stale`);let t=e.nodeName?r(`dock.node`,{node:e.nodeName}):r(`dock.running`);return e.subtaskTotal>1?`${t} · ${r(`dock.subtask`,{index:e.subtaskIndex,total:e.subtaskTotal})}`:t}return e.phase===`queued`?r(`dock.queued`,{count:e.queuedCount}):e.doneAt?r(`dock.doneAt`,{time:dO(e.doneAt)}):r(`dock.done`)}function pO(){let e=N.completedSessionIds;for(let e of new Set([...LD,...N.generatingSessionIds,...N.pendingCallApiSessionIds]))kD.has(e)||kD.set(e,Date.now()),AD.delete(e);for(let e of LD)ND.delete(e);for(let t of e)!AD.has(t)&&!aO(t)&&AD.set(t,Date.now());let{questions:t,anchors:n}=cO(),r=iO({activeSessionId:N.activeSessionId,titles:sO(),questions:t,anchors:n,queuedTexts:lO(),generatingIds:N.generatingSessionIds,pendingIds:N.pendingCallApiSessionIds,runningIds:LD,completedIds:e,queuedCounts:oO(),scheduledIds:MD,dismissedIds:ND,nodeInfo:Object.fromEntries(OD),startedAt:Object.fromEntries(kD),doneAt:Object.fromEntries(AD),lastUpdateAt:Object.fromEntries(jD),now:Date.now()});return uO(r),r}function mO(e){let t=new Set(RD.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&&(zD=new Set(n),JD&&clearTimeout(JD),JD=setTimeout(()=>{JD=null,zD=new Set,FO()},CD))}function hO(){if(BD||typeof document>`u`)return BD;BD=document.createElement(`div`),BD.className=`session-dock`,BD.id=`sessionDock`,BD.setAttribute(`role`,`navigation`),document.body.appendChild(BD),VD=document.createElement(`div`),VD.className=`session-dock-tip`,document.body.appendChild(VD),gO();let e=document.getElementById(`chatContainer`);return e&&typeof ResizeObserver<`u`&&new ResizeObserver(gO).observe(e),window.addEventListener(`resize`,gO),BD}function gO(){if(!BD)return;let e=document.getElementById(`chatContainer`);if(!e)return;let t=e.getBoundingClientRect();BD.style.top=`${Math.max(0,Math.round(t.top+8))}px`}function _O(e){Ys(e.sessionId,{focusMessageId:e.anchorMessageId||null})}function vO(e){let t=document.createElement(`div`);t.className=`session-dock-item`,t.dataset.sessionId=e.sessionId,t.dataset.phase=e.phase,e.stale&&(t.dataset.stale=`true`),zD.has(e.sessionId)&&t.classList.add(`is-flash`);let n=e.title||r(`dock.unknownSession`),i=e.primary||n,a=fO(e),o=e.phase===`done`?`✓`:Array.from(n)[0]||`?`,s=document.createElement(`button`);if(s.type=`button`,s.className=`session-dock-chip`,s.setAttribute(`aria-label`,`${i} · ${a}`),s.title=``,s.textContent=o,s.addEventListener(`click`,()=>{_O(e)}),t.appendChild(s),e.queuedCount>0&&e.phase!==`done`){let n=document.createElement(`span`);n.className=`session-dock-badge`,n.textContent=String(e.queuedCount>99?`99+`:e.queuedCount),t.appendChild(n)}if(e.source===`scheduled`){let e=document.createElement(`span`);e.className=`session-dock-clock`,t.appendChild(e)}if(e.phase===`done`||e.stale){let n=document.createElement(`button`);n.type=`button`,n.className=`session-dock-dismiss`;let i=e.stale?r(`dock.dismissStale`):r(`dock.dismiss`);n.setAttribute(`aria-label`,i),n.title=i,n.textContent=`×`,n.addEventListener(`click`,t=>{t.stopPropagation(),jO(e.sessionId)}),t.appendChild(n)}return t.addEventListener(`mouseenter`,()=>yO(t,e,a)),t.addEventListener(`mouseleave`,bO),t.addEventListener(`focusin`,()=>yO(t,e,a)),t.addEventListener(`focusout`,bO),t}function yO(e,t,n){if(!VD)return;VD.innerHTML=``;let i=document.createElement(`div`);i.className=`session-dock-tip-title`,i.textContent=t.primary||t.title||r(`dock.unknownSession`);let a=document.createElement(`div`);if(a.className=`session-dock-tip-status`,a.textContent=n,VD.appendChild(i),t.sub){let e=document.createElement(`div`);e.className=`session-dock-tip-sub`,e.textContent=t.sub,VD.appendChild(e)}VD.appendChild(a);let o=e.getBoundingClientRect();VD.style.top=`${Math.round(o.top)}px`,VD.style.left=`${Math.round(o.right+8)}px`,VD.classList.add(`show`)}function bO(){VD&&VD.classList.remove(`show`)}function xO(){return HD||typeof document>`u`?HD:(HD=document.createElement(`div`),HD.className=`session-dock-overflow`,HD.setAttribute(`role`,`menu`),HD.addEventListener(`mouseenter`,SO),HD.addEventListener(`mouseleave`,CO),HD.addEventListener(`focusin`,SO),HD.addEventListener(`focusout`,CO),document.body.appendChild(HD),HD)}function SO(){YD&&=(clearTimeout(YD),null)}function CO(){WD||(SO(),YD=setTimeout(()=>{YD=null,OO()},220))}function wO(){let e=BD?BD.querySelector(`.session-dock-more`):null;e&&(e.setAttribute(`aria-expanded`,WD?`true`:`false`),e.classList.toggle(`is-open`,WD))}function TO(){let e=xO();if(!e)return;e.innerHTML=``;let t=document.createElement(`div`);t.className=`session-dock-overflow-header`,t.textContent=r(`dock.overflowTitle`),e.appendChild(t);let n=document.createElement(`div`);n.className=`session-dock-overflow-list`;for(let e of UD){let t=e.primary||e.title||r(`dock.unknownSession`),i=fO(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`,`${t} · ${i}`);let o=document.createElement(`span`);o.className=`session-dock-overflow-title`,o.textContent=t;let s=document.createElement(`span`);s.className=`session-dock-overflow-status`,s.textContent=i,a.appendChild(o),a.appendChild(s),a.addEventListener(`click`,()=>{OO(),_O(e)}),n.appendChild(a)}e.appendChild(n)}function EO(){if(!HD||!BD)return;let e=BD.querySelector(`.session-dock-item--more`);if(!e)return;let t=e.getBoundingClientRect();HD.style.left=`${Math.round(t.right+8)}px`;let n=HD.offsetHeight||0,r=Math.max(8,window.innerHeight-n-8);HD.style.top=`${Math.round(Math.min(Math.max(8,t.top),r))}px`}function DO(){UD.length!==0&&xO()&&(SO(),TO(),EO(),HD.classList.add(`show`),wO())}function OO(){SO(),WD=!1,HD&&HD.classList.remove(`show`),wO()}function kO(){if(HD&&HD.classList.contains(`show`)&&WD){OO();return}DO(),WD=!0,wO()}function AO(e){let t=document.createElement(`div`);t.className=`session-dock-item session-dock-item--more`,t.dataset.count=String(e.length);let n=document.createElement(`button`);return n.type=`button`,n.className=`session-dock-chip session-dock-more`,n.setAttribute(`aria-label`,r(`dock.moreAria`,{count:e.length})),n.setAttribute(`aria-expanded`,WD?`true`:`false`),n.textContent=`+${e.length>99?`99`:e.length}`,n.addEventListener(`click`,()=>kO()),t.appendChild(n),t.addEventListener(`mouseenter`,()=>DO()),t.addEventListener(`mouseleave`,CO),t.addEventListener(`focusin`,()=>DO()),t.addEventListener(`focusout`,CO),t}function jO(e){e&&(ND.add(e),MO(),FO())}function MO(){try{chrome.storage.local.set({[bD]:Array.from(ND)}).catch(()=>{})}catch{}}function NO(){try{chrome.storage.local.get([bD],e=>{let t=e?.[bD];if(Array.isArray(t)){for(let e of t)ND.add(e);FO()}})}catch{}}function PO(){if(!hO())return;let e=pO();if(mO(e),RD=e,OO(),UD=[],BD.innerHTML=``,e.length===0){BD.classList.remove(`show`),document.body.classList.remove(`has-session-dock`),bO();return}let t=e.length>wD?TD:wD;UD=e.slice(t);for(let n of e.slice(0,t))BD.appendChild(vO(n));UD.length>0&&BD.appendChild(AO(UD)),BD.classList.add(`show`),document.body.classList.add(`has-session-dock`)}function FO(){GD||=setTimeout(()=>{GD=null;try{PO()}catch(e){a.warn(`[SessionDock] render failed:`,e?.message||e)}},SD)}function IO(){return new Promise(e=>{try{chrome.runtime.sendMessage({type:`QUERY_SESSION_RUNNING`},t=>{if(chrome.runtime.lastError||!t){e();return}Array.isArray(t.activeSessionIds)&&(LD=ZD(t.activeSessionIds)),e()})}catch{e()}})}function LO(e){let t=e?.sessionId;if(!t)return;let n=OD.get(t)||{};OD.set(t,{nodeName:e.nodeName||n.nodeName||``,subtaskIndex:e.subtaskIndex||n.subtaskIndex||0,subtaskTotal:e.subtaskTotal||n.subtaskTotal||0}),jD.set(t,Date.now()),FO()}function RO(e){e&&(OD.delete(e),kD.delete(e),AD.delete(e),jD.delete(e),ND.delete(e),PD.delete(e),FD.delete(e),FO())}function zO(){if(!(qD||typeof document>`u`||!hO())){qD=!0,NO(),document.addEventListener(`generating-state-changed`,FO),document.addEventListener(`session-switched`,FO),document.addEventListener(`generation-ended`,e=>{let t=e?.detail?.sessionId;t&&!AD.has(t)&&AD.set(t,Date.now()),FO()}),document.addEventListener(`session-archived`,e=>RO(e?.detail?.sessionId)),document.addEventListener(`session-deleted`,e=>RO(e?.detail?.sessionId));try{Hr(FO)}catch(e){a.debug(`[SessionDock] subscribe queue failed:`,e?.message||e)}try{chrome.runtime.onMessage.addListener(e=>e?e.type===`EXECUTION_STATUS_UPDATE`?(LO(e),!1):e.type===`SCHEDULED_TASK_RUN_STATE`&&e.sessionId?(e.running?MD.add(e.sessionId):MD.delete(e.sessionId),FO(),!1):(e.type===`SCHEDULED_SESSION_UPDATED`&&FO(),!1):!1)}catch(e){a.debug(`[SessionDock] register runtime listener failed:`,e?.message||e)}document.addEventListener(`visibilitychange`,()=>{if(document.hidden){OO();return}IO().then(FO)}),document.addEventListener(`keydown`,e=>{e.key===`Escape`&&WD&&OO()}),KD||=setInterval(()=>{document.hidden||IO().then(FO)},xD),IO().then(()=>{for(let e of LD)kD.has(e)||kD.set(e,Date.now());PO()})}}function BO(){let e=document.getElementById(`chatNavUp`),t=document.getElementById(`chatNavDown`),n=document.getElementById(`chatNavHotzone`),i=document.getElementById(`chatNavButtons`),a=document.getElementById(`chatNavQuestionPanel`),o=[],s=!1,c=null,l=``,u=!1,d=!1;function f(){let e=document.getElementById(`chatContainer`);return e?e.getBoundingClientRect().top:0}function p(e,t){let n=document.getElementById(`chatContainer`);if(!n)return`noop`;let r=Bt(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=wt(r.length,It(r,i),e);return a===null?(m(e),`blocked`):(r[a].start.scrollIntoView({behavior:`smooth`,block:`start`}),`jumped`)}function m(n){let r=n===`prev`?e:t;r&&(r.classList.remove(`blocked`),r.offsetWidth,r.classList.add(`blocked`),r.addEventListener(`animationend`,()=>r.classList.remove(`blocked`),{once:!0}))}function h(e,t){let n=a.querySelectorAll(`.chat-nav-question-item`);n.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=r(`chat.navPosition`,{current:e>=0?e+1:t,total:t}));let o=Array.from(n).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=Bt(document.getElementById(`chatContainer`));let e=l?Bt(document.getElementById(`chatContainer`)).length:a.querySelectorAll(`.chat-nav-question-item`).length;if(o.length===0){a.innerHTML=``,a.classList.remove(`expanded`);return}if(!l&&e!==o.length){_();return}h(It(o,f()),o.length)}function _(){if(!a)return!1;if(o=Bt(document.getElementById(`chatContainer`)),o.length===0)return a.innerHTML=``,!1;let e=It(o,f()),t=document.activeElement===a.querySelector(`[data-role="nav-search"]`);a.innerHTML=Et(o,e,s,l),a.querySelector(`.chat-nav-pin`).addEventListener(`click`,e=>{e.stopPropagation(),w()});let n=a.querySelector(`[data-role="nav-search"]`);if(n){let e=()=>{l!==n.value&&(l=n.value,_())};n.addEventListener(`input`,t=>{t.isComposing||e()}),n.addEventListener(`compositionend`,e),t&&(n.focus(),n.setSelectionRange(n.value.length,n.value.length))}if(e>=0){let t=a.querySelector(`.chat-nav-question-item[data-group-index="${e}"]`);t&&t.scrollIntoView({block:`nearest`})}return!0}function v(){let e=document.activeElement;return e?[n,i,a].some(t=>t&&(t===e||t.contains(e))):!1}function y(){i.classList.remove(`expanded`),a&&a.classList.remove(`expanded`)}function b(){let e=v();y(),e&&n&&(u=!0,n.focus({preventScroll:!0}),u=!1)}function x(){if(clearTimeout(c),i.classList.add(`expanded`),a){if(a.classList.contains(`expanded`)){g();return}_()?a.classList.add(`expanded`):a.classList.remove(`expanded`)}}function S(e){clearTimeout(c),!s&&(v()||(e?y():c=setTimeout(y,300)))}function C(e){if(s=e,n&&(n.classList.toggle(`pinned`,e),n.setAttribute(`aria-pressed`,String(e))),a){a.classList.toggle(`pinned`,e);let t=a.querySelector(`.chat-nav-pin`);if(t){let n=r(e?`chat.navUnpinLabel`:`chat.navPinLabel`);t.textContent=n,t.title=n,t.setAttribute(`aria-pressed`,String(e)),t.classList.toggle(`on`,e)}}}function w(){C(!s)}e&&e.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),p(`prev`,e.ctrlKey||e.metaKey),g()}),t&&t.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),p(`next`,e.ctrlKey||e.metaKey),g()}),n&&i&&(n.addEventListener(`mouseenter`,x),n.addEventListener(`mouseleave`,()=>S(!1)),n.addEventListener(`click`,()=>w()),n.addEventListener(`focus`,()=>{u||x()}),n.addEventListener(`blur`,()=>S(!1)),n.addEventListener(`keydown`,e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),w())}),i.addEventListener(`mouseenter`,x),i.addEventListener(`mouseleave`,()=>S(!1)),i.addEventListener(`focusin`,x),a&&(a.addEventListener(`mouseenter`,()=>{d=!0,x()}),a.addEventListener(`mouseleave`,()=>{d=!1,S(!1)}),a.addEventListener(`focusin`,x),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():b()})));{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 T(){let e=a&&a.classList.contains(`expanded`);if(!s&&!e)return!1;if(a&&a.querySelector(`[data-role="nav-search"]`)&&l){l=``,_();let e=a.querySelector(`[data-role="nav-search"]`);return e&&e.focus(),!0}return C(!1),b(),!0}return{jumpToMessage:p,updateActiveQuestion:g,handleEscape:T,isPinned:()=>s}}n(`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:`消息已被删除`}}),n(`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 VO=!1,HO=!1,UO=[],WO=``;function GO(){N.searchInputHistory=[],N.searchInputHistoryIndex=-1;try{chrome.storage.local.get([`searchInputHistory`],e=>{e.searchInputHistory&&(N.searchInputHistory=e.searchInputHistory)})}catch{}let e=document.createElement(`div`);e.className=`search-panel-container`,e.id=`searchPanelContainer`,e.innerHTML=`
|
|
2152
|
+
`+r.stderr:``),i.parentElement.scrollTop=i.parentElement.scrollHeight)},agentStreamDone(e){let t=n.get(e.execId);t&&e.exitCode!==0&&t.element.classList.add(`agent-stream-error`)},retrying(e,n){tC(t,e,n)},preselect(e){let n=t.querySelector(`.message-content`);!n||!e.length||e.forEach(e=>n.insertBefore(dC(e),n.firstChild))},final(e,n,r={}){fC(t,e,n,r.reflectionScore,r.reasoningContent,r.wasRevised)},error(e,n){fC(t,e,n||[])}}}async function tD(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),N.activeSessionId===t){N.messageHistory.push(i);try{document.dispatchEvent(new CustomEvent(`session-cache-invalidate`,{detail:{sessionId:t}}))}catch{}}let{appendMessageToSession:a}=await M(async()=>{let{appendMessageToSession:e}=await Promise.resolve().then(()=>ki);return{appendMessageToSession:e}},void 0);await a(t,i)}function nD(){M(()=>Promise.resolve().then(()=>hC).then(e=>e.syncPendingSessionsToStorage()),void 0).catch(e=>a.debug(`[ChatReattach] 同步生成态失败(忽略):`,e?.message||e))}var rD=1e3;function iD(e){return Promise.race([pS(e),new Promise(e=>setTimeout(()=>e(null),rD))])}function aD(e,t){let n=RS(e);if(n())return!1;let i=QS(e);i.dataset.callId=t,n(i),VS(e,``),GS(Date.now()),qS(Date.now()),N.pendingCallApiSessionIds.add(e),N.generatingSessionIds.add(e),nD();try{document.dispatchEvent(new CustomEvent(`generating-state-changed`))}catch{}let o=HE({sessionId:e,callId:t,awaitSnapshot:!0,renderer:eD(e,i),persist:t=>tD(t,e,i),emptyFallback:r(`chatMsg.emptyModelReply`),onFinished:()=>{if(GE.get(e)===o){GE.delete(e),VE(e),N.pendingCallApiSessionIds.delete(e),nD(),zS(e);try{document.dispatchEvent(new CustomEvent(`session-cache-invalidate`,{detail:{sessionId:e}}))}catch{}jl(e)}}});return GE.set(e,o),BE(e),iD(e).then(t=>{o.finished||GE.get(e)!==o||o.restore(t)}).catch(()=>o.restore(null)),N.activeSessionId===e&&iC(e),a.info(`[ChatReattach] 已接管运行中的任务: sessionId=${e}, callId=${t}`),!0}function oD(e){let t=GE.get(e);if(!t)return;GE.delete(e),VE(e);try{t.dispose?.()}catch{}let n=RS(e),r=n();try{r?.remove()}catch{}n(null),zS(e),N.pendingCallApiSessionIds.delete(e),nD();try{document.dispatchEvent(new CustomEvent(`generating-state-changed`))}catch{}}function sD(){let e=KE;e&&Promise.resolve().then(()=>e.syncFromBackground()).catch(e=>a.debug(`[ChatReattach] 对齐后台状态失败(忽略):`,e?.message||e))}function cD(){!WE||!KE||XE||(XE=setTimeout(()=>{XE=null,sD()},ZE))}var lD=new Map,uD=3e3,dD=100,fD=new Set,pD=new Set([`API_COMPLETE`,`API_ERROR`]);function mD(e,t){let n=`${e}|${t.callId}`;fD.has(n)||(fD.add(n),fD.size>dD&&fD.delete(fD.values().next().value),oD(e),aD(e,t.callId)&&GE.get(e)?.handleMessage(t))}function hD(e,t,n){let r=lD.get(e);if(r){r.messages.push(n);return}r={callId:t,messages:[n]},lD.set(e,r),$E(uD).then(t=>gD(e,t&&t.activeCallIds&&t.activeCallIds[e]||null)).catch(()=>gD(e,null)).finally(()=>{lD.delete(e)})}function gD(e,t){let n=lD.get(e);if(!n)return;let{callId:r,messages:i}=n;if(t===r)oD(e),aD(e,r);else if(t===null){let t=i.find(e=>pD.has(e.type));if(!t)return;mD(e,t);return}else return;let a=GE.get(e);if(!(!a||a.callId!==r))for(let e of i){if(a.finished)break;a.handleMessage(e)}}function _D(){qE||(qE=!0,chrome.runtime.onMessage.addListener(e=>{if(!e)return!1;let t=e.sessionId?GE.get(e.sessionId):null;return t?e.callId&&e.callId!==t.callId?(hD(e.sessionId,e.callId,e),!1):(BE(e.sessionId),t.handleMessage(e),!1):(e.callId&&QE.has(e.type)&&cD(),!1)}),JE=e=>{let t=e?.detail?.sessionId;t&&GE.has(t)&&iC(t),cD()},document.addEventListener(`session-hydrated`,JE),YE=e=>{let t=e?.detail?.sessionId;t&&GE.has(t)&&iC(t)},document.addEventListener(`chat-history-rendered`,YE))}function vD(){return WE?{syncFromBackground:()=>KE.syncFromBackground()}:(WE=!0,_D(),KE=UE({queryRunning:$E,hasLocalListener:e=>N.pendingCancelApiMap.has(e),isAttached:(e,t)=>GE.get(e)?.callId===t?(BE(e),!0):!1,attach:(e,t)=>{aD(e,t)}}),KE.syncFromBackground(),{syncFromBackground:()=>KE.syncFromBackground()})}function yD(e){!WE||!KE||(e&&N.activeSessionId===e&&iC(e),KE.syncFromBackground())}n(`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:`未知会话`}}),n(`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 bD=`sessionDockDismissed`,xD=5e3,SD=250,CD=1200,wD=8,TD=wD-1,ED=9e4,DD={running:0,queued:1,done:2},OD=new Map,kD=new Map,AD=new Map,jD=new Map,MD=new Set,ND=new Set,PD=new Map,FD=new Map,ID=new Set,LD=new Set,RD=[],zD=new Set,BD=null,VD=null,HD=null,UD=[],WD=!1,GD=null,KD=null,qD=!1,JD=null,YD=null;function XD(e){return e?Array.isArray(e)?e:e instanceof Set?Array.from(e):[]:[]}function ZD(e){let t=new Set;for(let n of XD(e))n&&t.add(me(String(n))||String(n));return t}function QD({phase:e=``,sessionId:t=null,backendRunningIds:n=[],startedAt:r=0,lastUpdateAt:i=0,now:a=Date.now(),staleMs:o=ED}={}){if(e!==`running`||!t||XD(n).includes(t))return!1;let s=Math.max(Number(r)||0,Number(i)||0);return s?a-s>=o:!1}var $D=160;function eO(e){let t=String(e??``).replace(/\s+/g,` `).trim();if(!t)return``;let n=Array.from(t);return n.length<=$D?t:`${n.slice(0,$D).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 nO({phase:e=``,queuedText:t=``,questionText:n=``,title:r=``}={}){let i=e===`queued`?eO(t):``,a=i||eO(n),o=eO(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 rO(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=d(n.content);if(r&&String(r).trim())return{text:String(r),messageId:n.messageId?String(n.messageId):``}}return{text:``,messageId:``}}function iO({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:_=ED}={}){let v=XD(s),y=new Set([...XD(a),...XD(o),...v]),b=new Set(XD(c)),x=new Set(XD(d)),S=new Set(XD(u)),C=l||{},w=new Set([...y,...b,...Object.keys(C)]),T=[];for(let a of w){if(!a||a===e)continue;let o=Number(C[a])||0,s;if(y.has(a))s=`running`;else if(o>0)s=`queued`;else if(b.has(a))s=`done`;else continue;let c=QD({phase:s,sessionId:a,backendRunningIds:v,startedAt:p?.[a],lastUpdateAt:h?.[a],now:g,staleMs:_});if(x.has(a)&&(s===`done`||c))continue;let l=f?.[a]||{},u=nO({phase:s,queuedText:i?.[a]||``,questionText:n?.[a]||``,title:t?.[a]||``});T.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:S.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 T.sort((e,t)=>{let n=DD[e.phase]-DD[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}),T}function aO(e){return LD.has(e)||N.generatingSessionIds.has(e)||N.pendingCallApiSessionIds.has(e)}function oO(){let e={};try{let t=Xr();for(let n of t){let t=Kr(n);t>0&&(e[n]=t)}}catch(e){a.debug(`[SessionDock] read queue counts failed:`,e?.message||e)}return e}function sO(){let e={};for(let t of N.sessions||[])e[t.id]=t.title||``;for(let[t,n]of PD)e[t]||(e[t]=n);return e}function cO(){let e={},t={},n=new Map;for(let e of N.sessions||[])n.set(e.id,e);for(let r of new Set([...LD,...N.generatingSessionIds,...N.pendingCallApiSessionIds,...N.completedSessionIds])){let i=kD.get(r)||AD.get(r)||0,a=FD.get(r);if(i&&a&&a.stamp===i){a.text&&(e[r]=a.text,t[r]=a.messageId||``);continue}let o=rO(n.get(r));o.text&&(e[r]=o.text,t[r]=o.messageId)}return{questions:e,anchors:t}}function lO(){let e={};try{for(let t of Xr()){let n=qr(t);n?.text&&(e[t]=String(n.text))}}catch(e){a.debug(`[SessionDock] read queued texts failed:`,e?.message||e)}return e}function uO(e){for(let t of e||[]){let e=t.sessionId;if(!e)continue;let n=t.startedAt||t.doneAt||0,r=FD.get(e),i=!r||r.stamp!==n,o=!t.title;!i&&!o||ID.has(e)||(ID.add(e),je(e).then(t=>{if(t&&((o||!PD.has(e))&&PD.set(e,t.title||``),i)){let r=rO(t);FD.set(e,{text:r.text,messageId:r.messageId,stamp:n})}}).catch(e=>{a.debug(`[SessionDock] hydrate label failed:`,e?.message||e)}).finally(()=>{ID.delete(e),FO()}))}}function dO(e){if(!e)return``;let t=new Date(e);return`${String(t.getHours()).padStart(2,`0`)}:${String(t.getMinutes()).padStart(2,`0`)}`}function fO(e){if(e.phase===`running`){if(e.stale)return r(`dock.stale`);let t=e.nodeName?r(`dock.node`,{node:e.nodeName}):r(`dock.running`);return e.subtaskTotal>1?`${t} · ${r(`dock.subtask`,{index:e.subtaskIndex,total:e.subtaskTotal})}`:t}return e.phase===`queued`?r(`dock.queued`,{count:e.queuedCount}):e.doneAt?r(`dock.doneAt`,{time:dO(e.doneAt)}):r(`dock.done`)}function pO(){let e=N.completedSessionIds;for(let e of new Set([...LD,...N.generatingSessionIds,...N.pendingCallApiSessionIds]))kD.has(e)||kD.set(e,Date.now()),AD.delete(e);for(let e of LD)ND.delete(e);for(let t of e)!AD.has(t)&&!aO(t)&&AD.set(t,Date.now());let{questions:t,anchors:n}=cO(),r=iO({activeSessionId:N.activeSessionId,titles:sO(),questions:t,anchors:n,queuedTexts:lO(),generatingIds:N.generatingSessionIds,pendingIds:N.pendingCallApiSessionIds,runningIds:LD,completedIds:e,queuedCounts:oO(),scheduledIds:MD,dismissedIds:ND,nodeInfo:Object.fromEntries(OD),startedAt:Object.fromEntries(kD),doneAt:Object.fromEntries(AD),lastUpdateAt:Object.fromEntries(jD),now:Date.now()});return uO(r),r}function mO(e){let t=new Set(RD.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&&(zD=new Set(n),JD&&clearTimeout(JD),JD=setTimeout(()=>{JD=null,zD=new Set,FO()},CD))}function hO(){if(BD||typeof document>`u`)return BD;BD=document.createElement(`div`),BD.className=`session-dock`,BD.id=`sessionDock`,BD.setAttribute(`role`,`navigation`),document.body.appendChild(BD),VD=document.createElement(`div`),VD.className=`session-dock-tip`,document.body.appendChild(VD),gO();let e=document.getElementById(`chatContainer`);return e&&typeof ResizeObserver<`u`&&new ResizeObserver(gO).observe(e),window.addEventListener(`resize`,gO),BD}function gO(){if(!BD)return;let e=document.getElementById(`chatContainer`);if(!e)return;let t=e.getBoundingClientRect();BD.style.top=`${Math.max(0,Math.round(t.top+8))}px`}function _O(e){Ys(e.sessionId,{focusMessageId:e.anchorMessageId||null})}function vO(e){let t=document.createElement(`div`);t.className=`session-dock-item`,t.dataset.sessionId=e.sessionId,t.dataset.phase=e.phase,e.stale&&(t.dataset.stale=`true`),zD.has(e.sessionId)&&t.classList.add(`is-flash`);let n=e.title||r(`dock.unknownSession`),i=e.primary||n,a=fO(e),o=e.phase===`done`?`✓`:Array.from(n)[0]||`?`,s=document.createElement(`button`);if(s.type=`button`,s.className=`session-dock-chip`,s.setAttribute(`aria-label`,`${i} · ${a}`),s.title=``,s.textContent=o,s.addEventListener(`click`,()=>{_O(e)}),t.appendChild(s),e.queuedCount>0&&e.phase!==`done`){let n=document.createElement(`span`);n.className=`session-dock-badge`,n.textContent=String(e.queuedCount>99?`99+`:e.queuedCount),t.appendChild(n)}if(e.source===`scheduled`){let e=document.createElement(`span`);e.className=`session-dock-clock`,t.appendChild(e)}if(e.phase===`done`||e.stale){let n=document.createElement(`button`);n.type=`button`,n.className=`session-dock-dismiss`;let i=e.stale?r(`dock.dismissStale`):r(`dock.dismiss`);n.setAttribute(`aria-label`,i),n.title=i,n.textContent=`×`,n.addEventListener(`click`,t=>{t.stopPropagation(),jO(e.sessionId)}),t.appendChild(n)}return t.addEventListener(`mouseenter`,()=>yO(t,e,a)),t.addEventListener(`mouseleave`,bO),t.addEventListener(`focusin`,()=>yO(t,e,a)),t.addEventListener(`focusout`,bO),t}function yO(e,t,n){if(!VD)return;VD.innerHTML=``;let i=document.createElement(`div`);i.className=`session-dock-tip-title`,i.textContent=t.primary||t.title||r(`dock.unknownSession`);let a=document.createElement(`div`);if(a.className=`session-dock-tip-status`,a.textContent=n,VD.appendChild(i),t.sub){let e=document.createElement(`div`);e.className=`session-dock-tip-sub`,e.textContent=t.sub,VD.appendChild(e)}VD.appendChild(a);let o=e.getBoundingClientRect();VD.style.top=`${Math.round(o.top)}px`,VD.style.left=`${Math.round(o.right+8)}px`,VD.classList.add(`show`)}function bO(){VD&&VD.classList.remove(`show`)}function xO(){return HD||typeof document>`u`?HD:(HD=document.createElement(`div`),HD.className=`session-dock-overflow`,HD.setAttribute(`role`,`menu`),HD.addEventListener(`mouseenter`,SO),HD.addEventListener(`mouseleave`,CO),HD.addEventListener(`focusin`,SO),HD.addEventListener(`focusout`,CO),document.body.appendChild(HD),HD)}function SO(){YD&&=(clearTimeout(YD),null)}function CO(){WD||(SO(),YD=setTimeout(()=>{YD=null,OO()},220))}function wO(){let e=BD?BD.querySelector(`.session-dock-more`):null;e&&(e.setAttribute(`aria-expanded`,WD?`true`:`false`),e.classList.toggle(`is-open`,WD))}function TO(){let e=xO();if(!e)return;e.innerHTML=``;let t=document.createElement(`div`);t.className=`session-dock-overflow-header`,t.textContent=r(`dock.overflowTitle`),e.appendChild(t);let n=document.createElement(`div`);n.className=`session-dock-overflow-list`;for(let e of UD){let t=e.primary||e.title||r(`dock.unknownSession`),i=fO(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`,`${t} · ${i}`);let o=document.createElement(`span`);o.className=`session-dock-overflow-title`,o.textContent=t;let s=document.createElement(`span`);s.className=`session-dock-overflow-status`,s.textContent=i,a.appendChild(o),a.appendChild(s),a.addEventListener(`click`,()=>{OO(),_O(e)}),n.appendChild(a)}e.appendChild(n)}function EO(){if(!HD||!BD)return;let e=BD.querySelector(`.session-dock-item--more`);if(!e)return;let t=e.getBoundingClientRect();HD.style.left=`${Math.round(t.right+8)}px`;let n=HD.offsetHeight||0,r=Math.max(8,window.innerHeight-n-8);HD.style.top=`${Math.round(Math.min(Math.max(8,t.top),r))}px`}function DO(){UD.length!==0&&xO()&&(SO(),TO(),EO(),HD.classList.add(`show`),wO())}function OO(){SO(),WD=!1,HD&&HD.classList.remove(`show`),wO()}function kO(){if(HD&&HD.classList.contains(`show`)&&WD){OO();return}DO(),WD=!0,wO()}function AO(e){let t=document.createElement(`div`);t.className=`session-dock-item session-dock-item--more`,t.dataset.count=String(e.length);let n=document.createElement(`button`);return n.type=`button`,n.className=`session-dock-chip session-dock-more`,n.setAttribute(`aria-label`,r(`dock.moreAria`,{count:e.length})),n.setAttribute(`aria-expanded`,WD?`true`:`false`),n.textContent=`+${e.length>99?`99`:e.length}`,n.addEventListener(`click`,()=>kO()),t.appendChild(n),t.addEventListener(`mouseenter`,()=>DO()),t.addEventListener(`mouseleave`,CO),t.addEventListener(`focusin`,()=>DO()),t.addEventListener(`focusout`,CO),t}function jO(e){e&&(ND.add(e),MO(),FO())}function MO(){try{chrome.storage.local.set({[bD]:Array.from(ND)}).catch(()=>{})}catch{}}function NO(){try{chrome.storage.local.get([bD],e=>{let t=e?.[bD];if(Array.isArray(t)){for(let e of t)ND.add(e);FO()}})}catch{}}function PO(){if(!hO())return;let e=pO();if(mO(e),RD=e,OO(),UD=[],BD.innerHTML=``,e.length===0){BD.classList.remove(`show`),document.body.classList.remove(`has-session-dock`),bO();return}let t=e.length>wD?TD:wD;UD=e.slice(t);for(let n of e.slice(0,t))BD.appendChild(vO(n));UD.length>0&&BD.appendChild(AO(UD)),BD.classList.add(`show`),document.body.classList.add(`has-session-dock`)}function FO(){GD||=setTimeout(()=>{GD=null;try{PO()}catch(e){a.warn(`[SessionDock] render failed:`,e?.message||e)}},SD)}function IO(){return new Promise(e=>{try{chrome.runtime.sendMessage({type:`QUERY_SESSION_RUNNING`},t=>{if(chrome.runtime.lastError||!t){e();return}Array.isArray(t.activeSessionIds)&&(LD=ZD(t.activeSessionIds)),e()})}catch{e()}})}function LO(e){let t=e?.sessionId;if(!t)return;let n=OD.get(t)||{};OD.set(t,{nodeName:e.nodeName||n.nodeName||``,subtaskIndex:e.subtaskIndex||n.subtaskIndex||0,subtaskTotal:e.subtaskTotal||n.subtaskTotal||0}),jD.set(t,Date.now()),FO()}function RO(e){e&&(OD.delete(e),kD.delete(e),AD.delete(e),jD.delete(e),ND.delete(e),PD.delete(e),FD.delete(e),FO())}function zO(){if(!(qD||typeof document>`u`||!hO())){qD=!0,NO(),document.addEventListener(`generating-state-changed`,FO),document.addEventListener(`session-switched`,FO),document.addEventListener(`generation-ended`,e=>{let t=e?.detail?.sessionId;t&&!AD.has(t)&&AD.set(t,Date.now()),FO()}),document.addEventListener(`session-archived`,e=>RO(e?.detail?.sessionId)),document.addEventListener(`session-deleted`,e=>RO(e?.detail?.sessionId));try{Hr(FO)}catch(e){a.debug(`[SessionDock] subscribe queue failed:`,e?.message||e)}try{chrome.runtime.onMessage.addListener(e=>e?e.type===`EXECUTION_STATUS_UPDATE`?(LO(e),!1):e.type===`SCHEDULED_TASK_RUN_STATE`&&e.sessionId?(e.running?MD.add(e.sessionId):MD.delete(e.sessionId),FO(),!1):(e.type===`SCHEDULED_SESSION_UPDATED`&&FO(),!1):!1)}catch(e){a.debug(`[SessionDock] register runtime listener failed:`,e?.message||e)}document.addEventListener(`visibilitychange`,()=>{if(document.hidden){OO();return}IO().then(FO)}),document.addEventListener(`keydown`,e=>{e.key===`Escape`&&WD&&OO()}),KD||=setInterval(()=>{document.hidden||IO().then(FO)},xD),IO().then(()=>{for(let e of LD)kD.has(e)||kD.set(e,Date.now());PO()})}}function BO(){let e=document.getElementById(`chatNavUp`),t=document.getElementById(`chatNavDown`),n=document.getElementById(`chatNavHotzone`),i=document.getElementById(`chatNavButtons`),a=document.getElementById(`chatNavQuestionPanel`),o=[],s=!1,c=null,l=``,u=!1,d=!1;function f(){let e=document.getElementById(`chatContainer`);return e?e.getBoundingClientRect().top:0}function p(e,t){let n=document.getElementById(`chatContainer`);if(!n)return`noop`;let r=Vt(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=Tt(r.length,Lt(r,i),e);return a===null?(m(e),`blocked`):(r[a].start.scrollIntoView({behavior:`smooth`,block:`start`}),`jumped`)}function m(n){let r=n===`prev`?e:t;r&&(r.classList.remove(`blocked`),r.offsetWidth,r.classList.add(`blocked`),r.addEventListener(`animationend`,()=>r.classList.remove(`blocked`),{once:!0}))}function h(e,t){let n=a.querySelectorAll(`.chat-nav-question-item`);n.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=r(`chat.navPosition`,{current:e>=0?e+1:t,total:t}));let o=Array.from(n).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=Vt(document.getElementById(`chatContainer`));let e=l?Vt(document.getElementById(`chatContainer`)).length:a.querySelectorAll(`.chat-nav-question-item`).length;if(o.length===0){a.innerHTML=``,a.classList.remove(`expanded`);return}if(!l&&e!==o.length){_();return}h(Lt(o,f()),o.length)}function _(){if(!a)return!1;if(o=Vt(document.getElementById(`chatContainer`)),o.length===0)return a.innerHTML=``,!1;let e=Lt(o,f()),t=document.activeElement===a.querySelector(`[data-role="nav-search"]`);a.innerHTML=Dt(o,e,s,l),a.querySelector(`.chat-nav-pin`).addEventListener(`click`,e=>{e.stopPropagation(),w()});let n=a.querySelector(`[data-role="nav-search"]`);if(n){let e=()=>{l!==n.value&&(l=n.value,_())};n.addEventListener(`input`,t=>{t.isComposing||e()}),n.addEventListener(`compositionend`,e),t&&(n.focus(),n.setSelectionRange(n.value.length,n.value.length))}if(e>=0){let t=a.querySelector(`.chat-nav-question-item[data-group-index="${e}"]`);t&&t.scrollIntoView({block:`nearest`})}return!0}function v(){let e=document.activeElement;return e?[n,i,a].some(t=>t&&(t===e||t.contains(e))):!1}function y(){i.classList.remove(`expanded`),a&&a.classList.remove(`expanded`)}function b(){let e=v();y(),e&&n&&(u=!0,n.focus({preventScroll:!0}),u=!1)}function x(){if(clearTimeout(c),i.classList.add(`expanded`),a){if(a.classList.contains(`expanded`)){g();return}_()?a.classList.add(`expanded`):a.classList.remove(`expanded`)}}function S(e){clearTimeout(c),!s&&(v()||(e?y():c=setTimeout(y,300)))}function C(e){if(s=e,n&&(n.classList.toggle(`pinned`,e),n.setAttribute(`aria-pressed`,String(e))),a){a.classList.toggle(`pinned`,e);let t=a.querySelector(`.chat-nav-pin`);if(t){let n=r(e?`chat.navUnpinLabel`:`chat.navPinLabel`);t.textContent=n,t.title=n,t.setAttribute(`aria-pressed`,String(e)),t.classList.toggle(`on`,e)}}}function w(){C(!s)}e&&e.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),p(`prev`,e.ctrlKey||e.metaKey),g()}),t&&t.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),p(`next`,e.ctrlKey||e.metaKey),g()}),n&&i&&(n.addEventListener(`mouseenter`,x),n.addEventListener(`mouseleave`,()=>S(!1)),n.addEventListener(`click`,()=>w()),n.addEventListener(`focus`,()=>{u||x()}),n.addEventListener(`blur`,()=>S(!1)),n.addEventListener(`keydown`,e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),w())}),i.addEventListener(`mouseenter`,x),i.addEventListener(`mouseleave`,()=>S(!1)),i.addEventListener(`focusin`,x),a&&(a.addEventListener(`mouseenter`,()=>{d=!0,x()}),a.addEventListener(`mouseleave`,()=>{d=!1,S(!1)}),a.addEventListener(`focusin`,x),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():b()})));{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 T(){let e=a&&a.classList.contains(`expanded`);if(!s&&!e)return!1;if(a&&a.querySelector(`[data-role="nav-search"]`)&&l){l=``,_();let e=a.querySelector(`[data-role="nav-search"]`);return e&&e.focus(),!0}return C(!1),b(),!0}return{jumpToMessage:p,updateActiveQuestion:g,handleEscape:T,isPinned:()=>s}}function VO(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`))}n(`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:`消息已被删除`}}),n(`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 HO=!1,UO=!1,WO=[],GO=``;function KO(){N.searchInputHistory=[],N.searchInputHistoryIndex=-1;try{chrome.storage.local.get([`searchInputHistory`],e=>{e.searchInputHistory&&(N.searchInputHistory=e.searchInputHistory)})}catch{}let e=document.createElement(`div`);e.className=`search-panel-container`,e.id=`searchPanelContainer`,e.innerHTML=`
|
|
2153
2153
|
<button class="search-panel-toggle" id="searchPanelToggle" title="${r(`searchPanel.toggleTitle`)}">
|
|
2154
2154
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
2155
2155
|
<circle cx="11" cy="11" r="8"/>
|
|
@@ -2184,13 +2184,13 @@ Sessions using this assistant will revert to the default assistant.`,deleteAgent
|
|
|
2184
2184
|
<div class="search-panel-empty">${r(`searchPanel.startSearchHint`)}</div>
|
|
2185
2185
|
</div>
|
|
2186
2186
|
</div>
|
|
2187
|
-
`,er(`search`).appendChild(e),
|
|
2187
|
+
`,er(`search`).appendChild(e),qO(),a.debug(`[SearchPanel] search panelinitializing`)}function qO(){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`)?YO():JO()}),i.addEventListener(`click`,()=>{YO()}),r.addEventListener(`click`,()=>{n.value=``,r.style.display=`none`,XO(),n.focus()}),n.addEventListener(`input`,()=>{let e=n.value.trim();r.style.display=e?``:`none`,e||XO()}),n.addEventListener(`keydown`,e=>{if(e.key===`Enter`){e.stopPropagation();let t=n.value.trim();t&&(s(t),ZO(t))}else if(e.key===`Escape`)N.searchInputHistoryIndex>=0?(N.searchInputHistoryIndex=-1,n.value=``):(e.stopPropagation(),YO());else if(e.key===`ArrowUp`){e.preventDefault(),e.stopPropagation();let t=N.searchInputHistory;if(t.length===0)return;N.searchInputHistoryIndex===-1?N.searchInputHistoryIndex=t.length-1:N.searchInputHistoryIndex>0&&N.searchInputHistoryIndex--,n.value=t[N.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=N.searchInputHistory;N.searchInputHistoryIndex>=0&&N.searchInputHistoryIndex<t.length-1?(N.searchInputHistoryIndex++,n.value=t[N.searchInputHistoryIndex]||``,n.selectionStart=n.selectionEnd=n.value.length):(N.searchInputHistoryIndex=-1,n.value=``),r.style.display=n.value?``:`none`}});function s(e){if(!e||!e.trim())return;let t=e.trim(),n=N.searchInputHistory,r=n.indexOf(t);r!==-1&&n.splice(r,1),n.push(t),n.length>20&&n.shift(),N.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&&ZO(e)}),o.addEventListener(`click`,()=>{o.classList.contains(`active`)||(o.classList.add(`active`),a.classList.remove(`active`));let e=n.value.trim();e&&ZO(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 ak(n,r)})}function JO(){let e=document.getElementById(`searchPanel`),t=document.getElementById(`searchPanelInput`);e.classList.add(`expanded`),It(e),t.value.trim()&&WO.length===0&&ZO(t.value.trim()),setTimeout(()=>t.focus(),100)}function YO(){let e=document.getElementById(`searchPanel`);e.classList.remove(`expanded`),Gt(e),UO=!0,HO=!1}function XO(){UO=!0,HO=!1,WO=[],GO=``;let e=document.getElementById(`searchPanelContent`),t=document.getElementById(`searchPanelCount`);e&&(e.innerHTML=`<div class="search-panel-empty">${r(`searchPanel.startSearchHint`)}</div>`),t&&(t.textContent=``)}async function ZO(e){if(!e||!e.trim()||(e=e.trim().toLowerCase(),HO&&GO===e))return;UO=!0,await new Promise(e=>setTimeout(e,50)),HO=!0,UO=!1,WO=[],GO=e;let t=document.getElementById(`searchPanelContent`),n=document.getElementById(`searchPanelCount`);t.innerHTML=`<div class="search-panel-loading">${r(`searchPanel.searching`)}</div>`,n.textContent=``;let i=document.getElementById(`searchModeGlobal`).classList.contains(`active`);try{i?await $O(e,t,n):await QO(e,t,n)}catch(e){a.error(`[SearchPanel] search error:`,e),UO||(t.innerHTML=`<div class="search-panel-empty">${r(`searchPanel.searchError`)}</div>`)}UO||(HO=!1)}async function QO(e,t,n){let i=N.activeSessionId;if(!i){t.innerHTML=`<div class="search-panel-empty">${r(`searchPanel.noActiveSession`)}</div>`;return}let a=ek(N.messageHistory||[],e,i);if(!UO){if(WO=a,n.textContent=a.length>0?r(`searchPanel.countResult`,{count:a.length}):r(`searchPanel.noResult`),a.length===0){t.innerHTML=`<div class="search-panel-empty">${r(`searchPanel.noMatch`)}</div>`;return}nk(a,e,t)}}async function $O(e,t,n){let i=N.activeSessionId,o=await we(),s=(o||[]).filter(e=>!e.archivedAt);if(UO)return;if(!s||s.length===0){t.innerHTML=`<div class="search-panel-empty">${r(`searchPanel.noSessionData`)}</div>`;return}let c=[],l=[];if(i){let a=ek(N.messageHistory||[],e,i);if(UO)return;let s=o.find(e=>e.id===i)?.title||r(`searchPanel.currentSession`);for(let e of a)c.push({...e,sessionTitle:s});WO=[...c],n.textContent=r(`searchPanel.searchingWithCount`,{count:c.length}),nk(WO,e,t,!0)}let u=s.filter(e=>e.id!==i);for(let i of u){if(UO)return;try{let a=await je(i.id);if(!a||!a.messageHistory)continue;let o=ek(a.messageHistory||[],e,i.id);if(o.length>0){for(let e of o)l.push({...e,sessionTitle:i.title||r(`searchPanel.unknownSession`)});WO=[...c,...l];let a=c.length+l.length;n.textContent=a>0?r(`searchPanel.countResult`,{count:a}):r(`searchPanel.noResult`),nk(WO,e,t)}}catch(e){a.warn(`[SearchPanel] searchsession failed:`,i.id,e)}await new Promise(e=>setTimeout(e,10))}if(UO)return;let d=WO.length;if(n.textContent=d>0?r(`searchPanel.countResult`,{count:d}):r(`searchPanel.noResult`),d===0){t.innerHTML=`<div class="search-panel-empty">${r(`searchPanel.noMatch`)}</div>`;return}nk(WO,e,t)}function ek(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=tk(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 tk(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 nk(e,t,n,i){if(n||=document.getElementById(`searchPanelContent`),!n)return;if(e.length===0){n.innerHTML=`<div class="search-panel-empty">${r(`searchPanel.noMatch`)}</div>`;return}let a=N.activeSessionId,o=e.filter(e=>e.sessionId===a),s=e.filter(e=>e.sessionId!==a),c=``,l=i?r(`searchPanel.searchingSuffix`):``;o.length>0&&(c+=`<div class="search-section">
|
|
2188
2188
|
<div class="search-section-title">${r(`searchPanel.currentSessionResults`,{label:l,count:o.length})}</div>
|
|
2189
|
-
${
|
|
2189
|
+
${rk(o,t)}
|
|
2190
2190
|
</div>`),s.length>0&&(c+=`<div class="search-section">
|
|
2191
2191
|
<div class="search-section-title">${r(`searchPanel.otherSessionsResults`,{count:s.length})}</div>
|
|
2192
|
-
${
|
|
2193
|
-
</div>`),n.innerHTML=c}function
|
|
2192
|
+
${rk(s,t)}
|
|
2193
|
+
</div>`),n.innerHTML=c}function rk(e,t){return e.map((e,n)=>{let i=e.role===`user`?`👤`:`🤖`,a=e.role===`user`?r(`searchPanel.roleUser`):r(`searchPanel.roleAssistant`),o=e.sessionTitle||``,s=e.sessionId===N.activeSessionId,c=ik(P(e.matchPreview),t);return`
|
|
2194
2194
|
<div class="search-result-item" data-session-id="${e.sessionId}" data-message-id="${e.messageId}" title="${P(e.content)}">
|
|
2195
2195
|
<div class="search-result-header">
|
|
2196
2196
|
<span class="search-result-role">${i} ${a}</span>
|
|
@@ -2198,7 +2198,7 @@ Sessions using this assistant will revert to the default assistant.`,deleteAgent
|
|
|
2198
2198
|
</div>
|
|
2199
2199
|
<div class="search-result-preview">${c}</div>
|
|
2200
2200
|
</div>
|
|
2201
|
-
`}).join(``)}function
|
|
2201
|
+
`}).join(``)}function ik(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 ak(e,t){if(!(!e||!t)){if(N.activeSessionId!==e)try{let t=N.activeSessionId;if(await Bi(e)===!1||N.activeSessionId!==e){L(r(`searchPanel.sessionNotExist`),`warning`);return}document.dispatchEvent(new CustomEvent(`session-switched`,{detail:{sessionId:e,previousSessionId:t,skipScrollRestore:!0}}));try{let{renderSessionTabs:e}=await M(async()=>{let{renderSessionTabs:e}=await Promise.resolve().then(()=>Yo);return{renderSessionTabs:e}},void 0);e()}catch(e){a.warn(`[SearchPanel] refreshsessionTab failed:`,e)}}catch(e){a.error(`[SearchPanel] switchsession failed:`,e);return}setTimeout(async()=>{let n=document.getElementById(`chatContainer`);if(!n){a.warn(`[SearchPanel] chatContainer not found`);return}let i=n.querySelector(`.message[data-message-id="${t}"]`);if(i||=n.querySelector(`[data-message-id="${t}"]`),!i){let r=Array.from(n.querySelectorAll(`[data-message-id]`),e=>e.dataset.messageId);a.warn(`[SearchPanel] positionmessage failed`,{targetSessionId:e,activeSessionId:N.activeSessionId,targetMessageId:t,typeOfMessageId:typeof t,messageIdLength:t.length,domMessageIds:r,chatContainerHtmlLen:n.innerHTML.length})}if(i)i.scrollIntoView({behavior:`instant`,block:`nearest`}),i.classList.add(`bookmark-highlight`),setTimeout(()=>{i.classList.remove(`bookmark-highlight`)},2e3);else{L(r(`searchPanel.messageDeleted`),`warning`);try{if(await _e(e,t)){WO=WO.filter(n=>!(n.sessionId===e&&n.messageId===t));let n=document.getElementById(`searchPanelContent`),i=document.getElementById(`searchPanelCount`);n&&WO.length>0?(nk(WO,GO,n),i.textContent=r(`searchPanel.countResult`,{count:WO.length})):n&&WO.length===0&&(n.innerHTML=`<div class="search-panel-empty">${r(`searchPanel.noMatch`)}</div>`,i&&(i.textContent=r(`searchPanel.noResult`))),a.debug(`[SearchPanel] cleaned IndexedDB dirtydata:`,e,t)}}catch(e){a.warn(`[SearchPanel] cleanupdirtydata failed:`,e)}}},500)}}n(`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})`}}),n(`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})`}});function ok(e){return chrome.runtime.sendMessage(e)}function sk(e){return e?new Date(e).toLocaleString(void 0,{month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`}):`—`}function ck(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 lk(e){return e===`success`?r(`schedPanel.statusSuccess`):e===`failed`?r(`schedPanel.statusFailed`):e===`running`?r(`schedPanel.statusRunning`):``}function uk(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 dk(e){let t=e.schedule||{};return t.type===`once`?t.onceMode===`relative`?r(`schedPanel.scheduleTypeOnce`)+` · `+(t.value||``)+r(`schedPanel.minutesSuffix`):r(`schedPanel.scheduleTypeOnce`)+` · `+sk(new Date(t.value).getTime()):t.type===`interval`?r(`schedPanel.scheduleTypeInterval`)+` · `+(t.value||``):t.type===`cron`?r(`schedPanel.scheduleTypeCron`)+` · `+(t.value||``):``}function fk(e){return e.enabled?e.lastStatus===`running`?`<span class="sched-badge running">${r(`schedPanel.statusRunning`)}</span>`:e.lastStatus===`failed`?`<span class="sched-badge failed">${r(`schedPanel.statusFailed`)}</span>`:e.lastStatus===`success`?`<span class="sched-badge success">${r(`schedPanel.statusSuccess`)}</span>`:``:`<span class="sched-badge muted">${r(`schedPanel.statusDisabled`)}</span>`}function pk(){let e=document.getElementById(`chatContainer`);e&&(e.scrollTop=e.scrollHeight)}async function mk(e){if(e){if(N.activeSessionId!==e){let t=N.activeSessionId;try{if(await Bi(e)===!1||N.activeSessionId!==e)return}catch{return}document.dispatchEvent(new CustomEvent(`session-switched`,{detail:{sessionId:e,previousSessionId:t,skipScrollRestore:!0}}));try{let{renderSessionTabs:e}=await M(async()=>{let{renderSessionTabs:e}=await Promise.resolve().then(()=>Yo);return{renderSessionTabs:e}},void 0);e()}catch{}}setTimeout(pk,500)}}function hk(){let e=document.createElement(`div`);e.className=`schedule-panel-container`,e.id=`schedulePanelContainer`,e.innerHTML=`
|
|
2202
2202
|
<style>
|
|
2203
2203
|
.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; }
|
|
2204
2204
|
.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; }
|
|
@@ -2329,23 +2329,23 @@ Sessions using this assistant will revert to the default assistant.`,deleteAgent
|
|
|
2329
2329
|
<button class="primary" id="scheduleModalSave">${r(`schedPanel.save`)}</button>
|
|
2330
2330
|
</div>
|
|
2331
2331
|
</div>
|
|
2332
|
-
`,document.body.appendChild(t);let n=document.getElementById(`schedulePanelToggle`),i=document.getElementById(`schedulePanel`),a=new Set;function o(){let e=a.size>0;n.classList.toggle(`running`,e),n.title=e?`${r(`schedPanel.toggleTitle`)} · ${r(`schedPanel.toggleRunning`)}`:r(`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`),_=document.getElementById(`schedOnceModeWrap`),v=document.getElementById(`schedValueLabel`),y=document.getElementById(`schedEndWrap`),b=null;function x(){let e=m.value,t=g.value;_.style.display=e===`once`?``:`none`,y.style.display=e===`interval`?``:`none`,e===`once`?t===`relative`?(v.textContent=r(`schedPanel.onceModeRelative`),h.type=`text`,h.placeholder=r(`schedPanel.relativeValuePlaceholder`)):(v.textContent=r(`schedPanel.onceModeAbsolute`),h.type=`datetime-local`,h.placeholder=``):e===`interval`?(v.textContent=r(`schedPanel.valueLabelInterval`),h.type=`text`,h.placeholder=r(`schedPanel.intervalValuePlaceholder`)):(v.textContent=r(`schedPanel.valueLabelCron`),h.type=`text`,h.placeholder=r(`schedPanel.cronValuePlaceholder`))}function S(e){e?(i.classList.add(`open`),
|
|
2332
|
+
`,document.body.appendChild(t);let n=document.getElementById(`schedulePanelToggle`),i=document.getElementById(`schedulePanel`),a=new Set;function o(){let e=a.size>0;n.classList.toggle(`running`,e),n.title=e?`${r(`schedPanel.toggleTitle`)} · ${r(`schedPanel.toggleRunning`)}`:r(`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`),_=document.getElementById(`schedOnceModeWrap`),v=document.getElementById(`schedValueLabel`),y=document.getElementById(`schedEndWrap`),b=null;function x(){let e=m.value,t=g.value;_.style.display=e===`once`?``:`none`,y.style.display=e===`interval`?``:`none`,e===`once`?t===`relative`?(v.textContent=r(`schedPanel.onceModeRelative`),h.type=`text`,h.placeholder=r(`schedPanel.relativeValuePlaceholder`)):(v.textContent=r(`schedPanel.onceModeAbsolute`),h.type=`datetime-local`,h.placeholder=``):e===`interval`?(v.textContent=r(`schedPanel.valueLabelInterval`),h.type=`text`,h.placeholder=r(`schedPanel.intervalValuePlaceholder`)):(v.textContent=r(`schedPanel.valueLabelCron`),h.type=`text`,h.placeholder=r(`schedPanel.cronValuePlaceholder`))}function S(e){e?(i.classList.add(`open`),It(i),C()):(i.classList.remove(`open`),Gt(i))}n.addEventListener(`click`,()=>{S(!i.classList.contains(`open`))}),s.addEventListener(`click`,()=>S(!1)),m.addEventListener(`change`,x),g.addEventListener(`change`,x),document.getElementById(`scheduleModalCloseBtn`).addEventListener(`click`,O),f.addEventListener(`click`,O),p.addEventListener(`click`,k),c.addEventListener(`click`,()=>D(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 C(){try{let e=(await ok({type:`SCHEDULED_TASK_LIST`}))?.tasks||[],t=document.getElementById(`schedulePanelCount`);t&&(t.textContent=e.length>0?`(${e.length})`:``),T(e),a.clear(),e.forEach(e=>{e.lastStatus===`running`&&a.add(e.id)}),o()}catch(e){l.innerHTML=`<div class="sched-empty">${P(String(e?.message||e))}</div>`}}function w(e){return!e||!e.length?`<div class="sched-history"><div class="sched-run">${r(`schedPanel.runHistoryEmpty`)}</div></div>`:`<div class="sched-history">${e.slice().reverse().map(e=>`
|
|
2333
2333
|
<div class="sched-run">
|
|
2334
2334
|
<span class="dot ${P(e.status||``)}"></span>
|
|
2335
|
-
<span class="time">${P(
|
|
2336
|
-
<span>${P(
|
|
2337
|
-
<span class="dur">${P(
|
|
2335
|
+
<span class="time">${P(sk(e.startedAt))}</span>
|
|
2336
|
+
<span>${P(lk(e.status))}</span>
|
|
2337
|
+
<span class="dur">${P(ck(e.durationMs))}</span>
|
|
2338
2338
|
${e.error?`<span class="err" title="${P(e.error)}">${P(e.error)}</span>`:``}
|
|
2339
2339
|
</div>
|
|
2340
2340
|
`).join(``)}</div>`}function T(e){if(!e.length){l.innerHTML=`<div class="sched-empty">${r(`schedPanel.empty`)}</div>`;return}l.innerHTML=e.map(e=>{let t=e.runHistory?.length||0,n=t>0?`<button class="sched-history-btn" data-act="history">${r(`schedPanel.runCountLabel`,{count:t})}</button>`:``;return`
|
|
2341
2341
|
<div class="sched-item" data-id="${P(e.id)}">
|
|
2342
2342
|
<div class="row1">
|
|
2343
2343
|
<span class="name" title="${P(e.name)}">${P(e.name)}</span>
|
|
2344
|
-
${
|
|
2344
|
+
${fk(e)}
|
|
2345
2345
|
</div>
|
|
2346
2346
|
${e.description?`<div class="desc">${P(e.description)}</div>`:``}
|
|
2347
|
-
<div class="meta">${P(
|
|
2348
|
-
<div class="meta">${r(`schedPanel.nextRun`)}: ${P(
|
|
2347
|
+
<div class="meta">${P(dk(e))}</div>
|
|
2348
|
+
<div class="meta">${r(`schedPanel.nextRun`)}: ${P(sk(e.nextRunAt))}</div>
|
|
2349
2349
|
${n}
|
|
2350
2350
|
<div class="sched-history" data-history style="display:none;">${w(e.runHistory)}</div>
|
|
2351
2351
|
<div class="actions">
|
|
@@ -2355,16 +2355,16 @@ Sessions using this assistant will revert to the default assistant.`,deleteAgent
|
|
|
2355
2355
|
<button data-act="delete" class="danger">${r(`schedPanel.delete`)}</button>
|
|
2356
2356
|
</div>
|
|
2357
2357
|
</div>
|
|
2358
|
-
`}).join(``)}l.addEventListener(`click`,async e=>{let t=e.target.closest(`button[data-act]`);if(!t)return;let n=t.closest(`.sched-item`),i=n?.dataset.id;if(!i)return;let a=t.dataset.act;if(a===`toggle`){let e=(await E())[i];if(!e)return;await
|
|
2359
|
-
`)}function
|
|
2360
|
-
`)}function
|
|
2358
|
+
`}).join(``)}l.addEventListener(`click`,async e=>{let t=e.target.closest(`button[data-act]`);if(!t)return;let n=t.closest(`.sched-item`),i=n?.dataset.id;if(!i)return;let a=t.dataset.act;if(a===`toggle`){let e=(await E())[i];if(!e)return;await ok({type:`SCHEDULED_TASK_TOGGLE`,id:i,enabled:!e.enabled}),C()}else if(a===`run`){let e=await ok({type:`SCHEDULED_TASK_RUN_NOW`,id:i});e?.success?(L(r(`schedPanel.runNowToast`),`success`),mk(e.sessionId),setTimeout(C,1500)):L(e?.error||r(`schedPanel.createFailed`),`error`)}else if(a===`history`){let e=n.querySelector(`[data-history]`);e&&(e.style.display=e.style.display===`none`?``:`none`)}else if(a===`edit`)D((await E())[i]);else if(a===`delete`){let e=(await E())[i];await window.showCustomConfirm(r(`schedPanel.deleteConfirmMsg`,{name:e?.name||``}),r(`schedPanel.deleteConfirmTitle`))&&(await ok({type:`SCHEDULED_TASK_DELETE`,id:i}),L(r(`schedPanel.deleted`),`success`),C())}});async function E(){let e=await ok({type:`SCHEDULED_TASK_LIST`}),t={};return(e?.tasks||[]).forEach(e=>{t[e.id]=e}),t}async function D(e){b=e||null,d.textContent=r(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`,x(),h.value=e?.schedule?.value||``,document.getElementById(`schedFormContextMode`).value=e?.contextMode||`fetch`,document.getElementById(`schedFormMaxRuns`).value=e?.maxRuns??``,document.getElementById(`schedFormEndAt`).value=e?.endAt?uk(e.endAt):``;let t=document.getElementById(`schedFormSession`),n=`<option value="">${r(`schedPanel.sessionAuto`)}</option>`;try{let{list:t}=await ke(),r=[...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 r){let r=e?.sessionId===t.id?`selected`:``,i=P(t.title||t.id);n+=`<option value="${P(t.id)}" ${r}>${i}</option>`}}catch{}t.innerHTML=n,u.classList.add(`open`)}function O(){u.classList.remove(`open`),b=null}async function k(){let e=document.getElementById(`schedFormName`).value.trim(),t=document.getElementById(`schedFormPrompt`).value.trim(),n=m.value,i=h.value.trim();if(!e){L(r(`schedPanel.nameRequired`),`warning`);return}if(!t){L(r(`schedPanel.promptRequired`),`warning`);return}if(!i){L(r(`schedPanel.scheduleRequired`),`warning`);return}let a=n===`interval`&&parseInt(document.getElementById(`schedFormMaxRuns`).value,10)||null,o=n===`interval`?document.getElementById(`schedFormEndAt`).value:``,s=o?new Date(o).getTime():null,c={name:e,description:document.getElementById(`schedFormDesc`).value.trim(),prompt:t,schedule:n===`once`?{type:n,value:i,onceMode:g.value}:{type:n,value:i},contextUrl:document.getElementById(`schedFormUrl`).value.trim()||null,contextMode:document.getElementById(`schedFormContextMode`).value||`fetch`,sessionId:document.getElementById(`schedFormSession`).value||null,maxRuns:a,endAt:s,enabled:b?b.enabled:!0};try{let e=await ok({type:b?`SCHEDULED_TASK_UPDATE`:`SCHEDULED_TASK_CREATE`,task:b?{...c,id:b.id}:c});e?.success?(L(r(`schedPanel.saved`),`success`),O(),C()):L(e?.error||r(`schedPanel.createFailed`),`error`)}catch(e){L(e?.message||r(`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`)&&C().catch(()=>{}),e.sessionId&&e.sessionId===N.activeSessionId&&setTimeout(pk,600))}),x(),S(!1),C().catch(()=>{})}n(`zh`,{todoTime:{justNow:`刚刚`,minutesAgo:`{n} 分钟前`,hoursAgo:`{n} 小时前`,daysAgo:`{n} 天前`,today:`今天`,tomorrow:`明天`,yesterday:`昨天`,doneStamp:`{date} 完成`,overdueStamp:`已逾期 {date}`},todoDigest:{active:`待办`,done:`已完成`,note:`备注`,due:`截止`,highPriority:`高优先级`},todoExport:{title:`待办清单`,count:`共 {n} 条`,scopeAll:`全部`,scopeActive:`仅待办`,scopeDone:`仅已完成`}}),n(`en`,{todoTime:{justNow:`just now`,minutesAgo:`{n} min ago`,hoursAgo:`{n} h ago`,daysAgo:`{n} d ago`,today:`Today`,tomorrow:`Tomorrow`,yesterday:`Yesterday`,doneStamp:`done {date}`,overdueStamp:`overdue {date}`},todoDigest:{active:`To do`,done:`Done`,note:`Note`,due:`Due`,highPriority:`high priority`},todoExport:{title:`Todo list`,count:`{n} items`,scopeAll:`All`,scopeActive:`To do only`,scopeDone:`Done only`}});var X={PENDING:`pending`,DOING:`doing`,DONE:`done`},gk={HIGH:`high`,MEDIUM:`medium`,LOW:`low`},_k=[X.PENDING,X.DOING,X.DONE],vk=[gk.HIGH,gk.MEDIUM,gk.LOW],yk=[`http:`,`https:`],bk=60*1e3,xk=60*bk,Sk=24*xk,Ck=[`all`,`active`,`done`],wk=[`id`,`title`,`note`,`status`,`prevStatus`,`priority`,`link`,`order`,`dueAt`,`createdAt`,`updatedAt`,`completedAt`];function Tk(e){return _k[(_k.indexOf(e)+1)%_k.length]}function Ek(e){return _k.includes(e)}function Dk(e){return vk.includes(e)?e:null}function Ok(e){let t=Dk(e);if(!t)return vk[0];let n=vk.indexOf(t);return n===vk.length-1?null:vk[n+1]}function kk(e){let t=String(e??``).trim().replace(/^\/+/,``);if(!t)return{url:``,host:``,valid:!0};let n=/^[a-z][a-z0-9+.-]*:/i.test(t)?t:`https://${t}`,r=null;try{r=new URL(n)}catch{return{url:``,host:``,valid:!1}}return yk.includes(r.protocol)?{url:r.href,host:Ak(r.hostname),valid:!0}:{url:``,host:``,valid:!1}}function Ak(e,t=22){let n=String(e||``).toLowerCase().replace(/^www\./,``);return n.length>t?`${n.slice(0,t-1)}…`:n}function jk(e){let{url:t,host:n}=kk(e&&e.link);return t?n:``}function Mk(e){let{url:t,valid:n}=kk(e);return n&&!!t}function Nk(e){return(e&&e.prevStatus)===X.DOING?X.DOING:X.PENDING}function Pk(e){return`todo_`+e.toString(36)+`_`+Math.random().toString(36).substring(2,6)}function Fk(e,t={},n=Date.now()){return{id:Pk(n),title:String(e||``).trim(),note:String(t.note||``).trim(),status:X.PENDING,prevStatus:null,priority:Dk(t.priority),link:kk(t.link).url,order:0,dueAt:Number.isFinite(t.dueAt)?t.dueAt:null,createdAt:n,updatedAt:n,completedAt:null}}function Ik(e){let t=e&&typeof e==`object`?e:{},n=Number.isFinite(t.createdAt)?t.createdAt:Date.now(),r=Ek(t.status)?t.status:X.PENDING;return{id:String(t.id||``),title:String(t.title||``).trim(),note:String(t.note||``),status:r,prevStatus:r===X.DONE&&Ek(t.prevStatus)&&t.prevStatus!==X.DONE?t.prevStatus:null,priority:Dk(t.priority),link:kk(t.link).url,order:Number.isFinite(t.order)?t.order:2**53-1,dueAt:Number.isFinite(t.dueAt)?t.dueAt:null,createdAt:n,updatedAt:Number.isFinite(t.updatedAt)?t.updatedAt:n,completedAt:Number.isFinite(t.completedAt)?t.completedAt:null}}function Lk(e,t){return e.order===t.order?e.createdAt-t.createdAt:e.order-t.order}function Rk(e,t){return(t.completedAt||t.updatedAt||0)-(e.completedAt||e.updatedAt||0)}function zk(e){let t=Array.isArray(e)?e.map(Ik):[],n=[],r=[];for(let e of t)e.status===X.DONE?r.push(e):n.push(e);return n.sort(Lk),r.sort(Rk),{active:n,done:r,stats:{total:t.length,done:r.length,active:n.length,pending:n.filter(e=>e.status===X.PENDING).length,doing:n.filter(e=>e.status===X.DOING).length}}}function Bk(e,t,n){let r=Array.isArray(e)?e.slice():[];if(t<0||t>=r.length)return r;let[i]=r.splice(t,1),a=Math.max(0,Math.min(n,r.length));return r.splice(a,0,i),r}function Vk(e,t=Date.now()){return(Array.isArray(e)?e:[]).map((e,n)=>e.order===n?e:{...e,order:n,updatedAt:t})}function Hk(e){let{active:t}=zk(e);return t.reduce((e,t)=>Number.isFinite(t.order)&&t.order<2**53-1?Math.max(e,t.order):e,-1)+1}function Uk(e,t){return e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate()}function Wk(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime()}function Gk(e,t=Date.now()){let n=new Date(e),r=new Date(t);if(isNaN(n.getTime()))return``;if(s()===`en`){let e=n.toLocaleString(`en-US`,{month:`short`});return n.getFullYear()===r.getFullYear()?`${e} ${n.getDate()}`:`${e} ${n.getDate()}, ${n.getFullYear()}`}return n.getFullYear()===r.getFullYear()?`${n.getMonth()+1}月${n.getDate()}日`:`${n.getFullYear()}年${n.getMonth()+1}月${n.getDate()}日`}function Kk(e,t=Date.now()){if(!Number.isFinite(e))return``;let n=t-e;return n<bk?r(`todoTime.justNow`):n<xk?r(`todoTime.minutesAgo`,{n:Math.floor(n/bk)}):n<Sk?r(`todoTime.hoursAgo`,{n:Math.floor(n/xk)}):n<7*Sk?r(`todoTime.daysAgo`,{n:Math.floor(n/Sk)}):Gk(e,t)}function qk(e,t=Date.now()){if(!Number.isFinite(e))return``;let n=new Date(e),i=new Date(t);if(isNaN(n.getTime()))return``;if(Uk(n,i))return r(`todoTime.today`);let a=Math.round((Wk(n)-Wk(i))/Sk);return a===1?r(`todoTime.tomorrow`):a===-1?r(`todoTime.yesterday`):Gk(e,t)}function Jk(e,t=Date.now()){let n=e&&Number.isFinite(e.completedAt)?e.completedAt:e&&e.updatedAt;return Number.isFinite(n)?r(`todoTime.doneStamp`,{date:Gk(n,t)}):``}function Yk(e,t=Date.now()){if(!e||!Number.isFinite(e.dueAt)||e.status===X.DONE)return!1;let n=Wk(new Date(t));return Wk(new Date(e.dueAt))<n}function Xk(e){return String(e||``).replace(/\s*\n+\s*/g,` `).trim()}function Zk(e,t){let n=kk(e.link).url,i=n?` [${jk(e)}](${n})`:``;if(e.status===X.DONE){let n=Number.isFinite(e.completedAt)?`(${r(`todoTime.doneStamp`,{date:Gk(e.completedAt,t)})})`:``;return`- [x] ${Xk(e.title)}${n}${i}`}let a=e.status===X.DOING?`⏳ `:``,o=Number.isFinite(e.dueAt)?`(${r(`todoDigest.due`)} ${qk(e.dueAt,t)})`:``,s=e.priority===gk.HIGH?`(${r(`todoDigest.highPriority`)})`:``;return`- [ ] ${a}${Xk(e.title)}${s}${o}${i}`}function Qk(e){return!e.note||!e.note.trim()?``:` - ${r(`todoDigest.note`)}:${Xk(e.note)}`}function $k(e,t={}){let n=Ik(e);if(!n.title)return``;let r=[Zk(n,t.now||Date.now())],i=Qk(n);return i&&r.push(i),r.join(`
|
|
2359
|
+
`)}function eA(e){return Ck.includes(e)?e:`all`}function tA(e,t=`all`){let{active:n,done:r}=zk(e),i=eA(t);return i===`active`?n:i===`done`?r:[...n,...r]}function nA(e){let t=Ik(e),n={};for(let e of wk)n[e]=t[e];return n}function rA(e,t={}){let n=eA(t.scope);return{kind:`todos`,version:1,scope:n,exportedAt:t.now||Date.now(),todos:tA(e,n).map(nA)}}function iA(e,t={}){let n=eA(t.scope),i=t.now||Date.now(),a=tA(e,n),o=r(`todoExport.scope${n===`active`?`Active`:n===`done`?`Done`:`All`}`),s=[`# ${r(`todoExport.title`)}(${o} · ${r(`todoExport.count`,{n:a.length})})`,``];for(let e of a){s.push(Zk(e,i));let t=Qk(e);t&&s.push(t)}return s.join(`
|
|
2360
|
+
`)}function aA(e){let t=null;return Array.isArray(e)?t=e:e&&typeof e==`object`&&Array.isArray(e.todos)&&(t=e.todos),t?{ok:!0,todos:t.filter(e=>e&&typeof e==`object`&&!Array.isArray(e))}:{ok:!1,reason:`format`}}function oA(e,t,n=Date.now()){let r=(Array.isArray(e)?e:[]).map(Ik),i=new Set(r.map(e=>e.id).filter(Boolean)),a=r.reduce((e,t)=>Number.isFinite(t.order)&&t.order<2**53-1?Math.max(e,t.order):e,-1)+1,o=[],s=0;for(let e of Array.isArray(t)?t:[]){let t=String(e&&e.title||``).trim();if(!t){s+=1;continue}let r=String(e&&e.id||``).trim();if(r&&i.has(r)){s+=1;continue}r||=Pk(n),i.add(r),o.push({...Ik({...e,id:r,title:t}),order:a++})}return{todos:[...r,...o],addedItems:o,added:o.length,skipped:s}}var sA=`todoStatsLog`,cA=7;function lA(e){return String(e).padStart(2,`0`)}function uA(e=Date.now()){let t=new Date(e);return`${t.getFullYear()}-${lA(t.getMonth()+1)}-${lA(t.getDate())}`}function dA(e,t){let n=new Date(e);return n.setDate(n.getDate()+t),n.getTime()}function fA(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 pA(e,t=Date.now()){let n=uA(dA(t,-90)),r={};for(let[t,i]of Object.entries(e&&typeof e==`object`?e:{}))t>=n&&(r[t]=i);return r}function mA(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 hA(e,t){let n=mA(e,uA(t)).done>0?t:dA(t,-1),r=0;for(;r<=90&&!(mA(e,uA(n)).done<=0);)r+=1,n=dA(n,-1);return r}function gA(e,t,n=Date.now()){let r=Array.isArray(e)?e.map(Ik):[],{stats:i}=zk(r),a=t&&typeof t==`object`?t:{},o=[];for(let e=cA-1;e>=0;--e){let t=uA(dA(n,-e));o.push({date:t,...mA(a,t)})}return{total:i.total,done:i.done,doing:i.doing,pending:i.pending,overdue:r.filter(e=>Yk(e,n)).length,high:r.filter(e=>e.status!==X.DONE&&e.priority===gk.HIGH).length,doneRate:i.total?Math.round(i.done/i.total*100):0,today:mA(a,uA(n)),week:o,streak:hA(a,n)}}var _A=Promise.resolve();async function vA(){try{if(typeof chrome>`u`||!chrome.storage?.local?.get)return{};let e=await chrome.storage.local.get([sA]),t=e&&e.todoStatsLog;return t&&typeof t==`object`?t:{}}catch(e){return a.warn(`[Todo] load stats log failed:`,e),{}}}async function yA(e){typeof chrome>`u`||!chrome.storage?.local?.set||await chrome.storage.local.set({[sA]:e})}function bA(e,t,n=Date.now()){let r=_A.then(async()=>{let r=pA(fA(await vA(),uA(n),e,t));return await yA(r),r});return _A=r.then(()=>void 0,()=>void 0),r.catch(e=>(a.warn(`[Todo] record stat failed:`,e),null))}var xA=new Set,SA=Promise.resolve();function CA(e){let t=SA.then(e);return SA=t.then(()=>void 0,()=>void 0),t}function wA(e){return typeof e==`function`?(xA.add(e),()=>xA.delete(e)):()=>{}}function TA(){for(let e of xA)try{e()}catch(e){a.warn(`[Todo] listener failed:`,e)}}async function EA(){try{N.todos=(await Ce()||[]).map(Ik).filter(e=>e.id&&e.title),a.debug(`[Todo] loaded todos:`,N.todos.length)}catch(e){a.error(`[Todo] load todos failed:`,e),N.todos=[]}}function DA(){return zk(N.todos)}function OA(e){return N.todos.find(t=>t.id===e)||null}function kA(e){N.todos=N.todos.map(t=>t.id===e.id?e:t)}async function AA(e,t={}){let n=String(e||``).trim();if(!n)return null;let r=Fk(n,t);return r.order=Hk(N.todos),N.todos=[...N.todos,r],await CA(()=>De(r)).catch(e=>(a.error(`[Todo] add failed:`,e),!1))?(TA(),await bA(`added`,1,r.createdAt),r):(N.todos=N.todos.filter(e=>e.id!==r.id),TA(),null)}async function jA(e,t={}){let n=OA(e);if(!n)return!1;let r={...n,updatedAt:Date.now()};if(t.title!==void 0){let e=String(t.title).trim();if(!e)return!1;r.title=e}return t.note!==void 0&&(r.note=String(t.note||``).trim()),t.dueAt!==void 0&&(r.dueAt=Number.isFinite(t.dueAt)?t.dueAt:null),t.priority!==void 0&&(r.priority=Dk(t.priority)),t.link!==void 0&&(r.link=kk(t.link).url),kA(r),await CA(()=>De(r)).catch(e=>(a.error(`[Todo] update failed:`,e),!1))?(TA(),!0):(kA(n),TA(),!1)}async function MA(e,t){let n=OA(e);if(!n||!Ek(t))return!1;if(n.status===t)return!0;let r=Date.now(),i={...n,status:t,updatedAt:r};return t===X.DONE?(i.completedAt=r,n.status!==X.DONE&&(i.prevStatus=n.status)):n.status===X.DONE&&(i.completedAt=null,i.prevStatus=null),kA(i),await CA(()=>De(i)).catch(e=>(a.error(`[Todo] set status failed:`,e),!1))?(TA(),t===X.DONE&&n.status!==X.DONE?await bA(`done`,1,i.completedAt):n.status===X.DONE&&t!==X.DONE&&await bA(`done`,-1,n.completedAt),!0):(kA(n),TA(),!1)}function NA(e){let t=OA(e);return t?MA(e,Tk(t.status)):Promise.resolve(!1)}function PA(e){let t=OA(e);return!t||t.status!==X.DONE?Promise.resolve(!1):MA(e,Nk(t))}function FA(e,t){return jA(e,{priority:Dk(t)})}async function IA(e,t){if(!OA(e))return{ok:!1,reason:`missing`};let n=kk(t);if(!n.valid)return{ok:!1,reason:`invalid`};let r=await jA(e,{link:n.url});return{ok:r,reason:r?``:`save`}}async function LA(e){let t=OA(e);return t?(N.todos=N.todos.filter(t=>t.id!==e),await CA(()=>Se(e)).catch(e=>(a.error(`[Todo] delete failed:`,e),!1))?(TA(),!0):(N.todos=[...N.todos,t],TA(),!1)):!1}async function RA(e,t){let{active:n}=DA();if(e===t)return!0;if(e<0||e>=n.length)return!1;let r=Vk(Bk(n,e,t)),i=new Map(r.map(e=>[e.id,e])),o=N.todos;if(N.todos=N.todos.map(e=>i.get(e.id)||e),!await CA(()=>Ge(r)).catch(e=>(a.error(`[Todo] reorder failed:`,e),!1))){let e=new Map(o.map(e=>[e.id,e.order]));return N.todos=N.todos.map(t=>e.has(t.id)?{...t,order:e.get(t.id)}:t),TA(),!1}return TA(),!0}async function zA(){let{done:e}=DA();if(e.length===0)return!0;let t=e.map(e=>e.id),n=N.todos;if(N.todos=N.todos.filter(e=>!t.includes(e.id)),!await CA(()=>ce(t)).catch(e=>(a.error(`[Todo] clear completed failed:`,e),!1))){let e=new Set(N.todos.map(e=>e.id)),r=n.filter(n=>t.includes(n.id)&&!e.has(n.id));return N.todos=[...N.todos,...r],TA(),!1}return TA(),!0}async function BA(e,t=`merge`){if(t===`replace`)return VA(e);let n=oA(N.todos,e);if(n.addedItems.length===0)return{ok:!0,added:0,skipped:n.skipped};let r=N.todos;N.todos=n.todos;let i=new Set(n.addedItems.map(e=>e.id));return await CA(()=>Ge(n.addedItems)).catch(e=>(a.error(`[Todo] import merge failed:`,e),!1))?(TA(),{ok:!0,added:n.addedItems.length,skipped:n.skipped}):(N.todos=r.filter(e=>!i.has(e.id)),TA(),{ok:!1,added:0,skipped:n.skipped})}async function VA(e){let{addedItems:t,skipped:n}=oA([],e);if(t.length===0)return{ok:!1,added:0,skipped:n,reason:`empty`};let r=N.todos,i=r.map(e=>e.id);return N.todos=t,await CA(async()=>i.length>0&&!await ce(i).catch(e=>(a.error(`[Todo] replace delete failed:`,e),!1))?!1:await Ge(t).catch(e=>(a.error(`[Todo] replace write failed:`,e),!1))?!0:(i.length>0&&await Ge(r).catch(()=>!1),!1)).catch(e=>(a.error(`[Todo] replace failed:`,e),!1))?(TA(),{ok:!0,added:t.length,skipped:n}):(N.todos=r,TA(),{ok:!1,added:0,skipped:n})}var HA=[`all`,`active`,`done`],UA={json:{ext:`json`,type:`application/json;charset=utf-8`},md:{ext:`md`,type:`text/markdown;charset=utf-8`}};function WA(e){return e===`md`?`md`:`json`}function GA(e){return String(e).padStart(2,`0`)}function KA(e){let t=new Date(e);return`${t.getFullYear()}-${GA(t.getMonth()+1)}-${GA(t.getDate())}`}function qA(e,t,n=Date.now()){let r=HA.includes(e)?e:`all`;return`ai-helper-todos${r===`all`?``:`-${r}`}-${KA(n)}.${UA[WA(t)].ext}`}function JA(e,t={}){let n=HA.includes(t.scope)?t.scope:`all`,r=WA(t.format),i=t.now||Date.now(),a=r===`md`?iA(e,{scope:n,now:i}):JSON.stringify(rA(e,{scope:n,now:i}),null,2);return{filename:qA(n,r,i),blob:new Blob([a],{type:UA[r].type})}}function YA(e,t={}){let{filename:n,blob:r}=JA(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 XA(){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 ZA(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 aA(n)}var QA=`<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>`,$A=[`all`,`active`,`done`],ej=[`json`,`md`],tj=[`merge`,`replace`];n(`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:`取消`}}),n(`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 nj(e){return`<div class="todo-io-header">
|
|
2361
2361
|
<span class="todo-io-title">${P(e)}</span>
|
|
2362
2362
|
<button type="button" class="todo-io-close" data-io-action="cancel"
|
|
2363
|
-
title="${I(r(`todoIo.close`))}" aria-label="${I(r(`todoIo.close`))}">${
|
|
2364
|
-
</div>`}function
|
|
2363
|
+
title="${I(r(`todoIo.close`))}" aria-label="${I(r(`todoIo.close`))}">${QA}</button>
|
|
2364
|
+
</div>`}function rj(e,t){return`<div class="todo-io-actions">
|
|
2365
2365
|
<button type="button" class="todo-io-btn" data-io-action="cancel">${P(r(`todoIo.cancel`))}</button>
|
|
2366
2366
|
<button type="button" class="todo-io-btn primary" data-io-action="confirm"${t?` disabled`:``}>${P(e)}</button>
|
|
2367
|
-
</div>`}function
|
|
2367
|
+
</div>`}function ij({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`:``}">
|
|
2368
2368
|
<input type="radio" name="todoIo-${I(e)}" value="${I(t)}"
|
|
2369
2369
|
data-io-field="${I(e)}"${i?` checked`:``} />
|
|
2370
2370
|
<span class="todo-io-option-main">
|
|
@@ -2372,9 +2372,9 @@ Sessions using this assistant will revert to the default assistant.`,deleteAgent
|
|
|
2372
2372
|
${r?`<span class="todo-io-option-hint">${P(r)}</span>`:``}
|
|
2373
2373
|
</span>
|
|
2374
2374
|
${s}
|
|
2375
|
-
</label>`}function
|
|
2375
|
+
</label>`}function aj(e,t={}){let n=$A.includes(e?.scope)?e.scope:`all`,i=ej.includes(e?.format)?e.format:`json`,a=Number(t[n]||0)===0,o=[[`all`,r(`todoIo.scopeAll`)],[`active`,r(`todoIo.scopeActive`)],[`done`,r(`todoIo.scopeDone`)]].map(([e,r])=>ij({field:`scope`,value:e,label:r,checked:e===n,count:Number(t[e]||0)})).join(``),s=[[`json`,r(`todo.exportJson`)],[`md`,r(`todo.exportMd`)]].map(([e,t])=>ij({field:`format`,value:e,label:t,checked:e===i})).join(``);return`<div class="todo-io-card" role="dialog" aria-modal="true" tabindex="-1"
|
|
2376
2376
|
aria-label="${I(r(`todoIo.exportTitle`))}">
|
|
2377
|
-
${
|
|
2377
|
+
${nj(r(`todoIo.exportTitle`))}
|
|
2378
2378
|
<div class="todo-io-body">
|
|
2379
2379
|
<div class="todo-io-group">
|
|
2380
2380
|
<div class="todo-io-group-label">${P(r(`todoIo.rangeLabel`))}</div>
|
|
@@ -2386,10 +2386,10 @@ Sessions using this assistant will revert to the default assistant.`,deleteAgent
|
|
|
2386
2386
|
</div>
|
|
2387
2387
|
<p class="todo-io-hint${a?` show`:``}" data-io-hint>${P(r(`todoIo.emptyRange`))}</p>
|
|
2388
2388
|
</div>
|
|
2389
|
-
${
|
|
2390
|
-
</div>`}function
|
|
2389
|
+
${rj(r(`todoIo.exportAction`),a)}
|
|
2390
|
+
</div>`}function oj(e,t={}){let n=tj.includes(e?.mode)?e.mode:`merge`,i=Number(t.count||0),a=Number(t.existing||0),o=[[`merge`,r(`todoIo.modeMerge`),r(`todoIo.modeMergeHint`)],[`replace`,r(`todoIo.modeReplace`),r(`todoIo.modeReplaceHint`,{n:a})]].map(([e,t,r])=>ij({field:`mode`,value:e,label:t,hint:r,checked:e===n,danger:e===`replace`})).join(``);return`<div class="todo-io-card" role="dialog" aria-modal="true" tabindex="-1"
|
|
2391
2391
|
aria-label="${I(r(`todoIo.importTitle`))}">
|
|
2392
|
-
${
|
|
2392
|
+
${nj(r(`todoIo.importTitle`))}
|
|
2393
2393
|
<div class="todo-io-body">
|
|
2394
2394
|
<p class="todo-io-summary">${P(r(`todoIo.importSummary`,{count:i,existing:a}))}</p>
|
|
2395
2395
|
<div class="todo-io-group">
|
|
@@ -2398,14 +2398,14 @@ Sessions using this assistant will revert to the default assistant.`,deleteAgent
|
|
|
2398
2398
|
</div>
|
|
2399
2399
|
<p class="todo-io-warn${n===`replace`?` show`:``}" data-io-warn>${P(r(`todoIo.replaceWarn`,{count:i}))}</p>
|
|
2400
2400
|
</div>
|
|
2401
|
-
${
|
|
2402
|
-
</div>`}var
|
|
2401
|
+
${rj(r(`todoIo.importAction`),!1)}
|
|
2402
|
+
</div>`}var sj=null,Z=null,cj=null;function lj(){return sj||(sj=document.createElement(`div`),sj.className=`todo-io-overlay`,sj.id=`todoIoOverlay`,sj.addEventListener(`click`,e=>{if(e.target===sj){pj(null);return}let t=e.target.closest?.(`[data-io-action]`);t?.dataset.ioAction===`cancel`?pj(null):t?.dataset.ioAction===`confirm`&&fj()}),sj.addEventListener(`change`,e=>{if(!Z)return;let t=e.target.closest?.(`input[data-io-field]`);t&&(Z.state[t.dataset.ioField]=t.value,dj())}),document.body.appendChild(sj),sj)}function uj(){if(!Z)return;let e=lj();e.innerHTML=Z.kind===`export`?aj(Z.state,Z.counts):oj(Z.state,Z.info),dj()}function dj(){if(!(!Z||!sj)){if(Z.kind===`export`){let e=!Number(Z.counts[Z.state.scope]||0),t=sj.querySelector(`[data-io-action="confirm"]`);t&&(t.disabled=e),sj.querySelector(`[data-io-hint]`)?.classList.toggle(`show`,e);return}sj.querySelector(`[data-io-warn]`)?.classList.toggle(`show`,Z.state.mode===`replace`)}}function fj(){if(Z){if(Z.kind===`export`){if(!Number(Z.counts[Z.state.scope]||0))return;pj({scope:Z.state.scope,format:Z.state.format});return}pj(Z.state.mode)}}function pj(e){if(!Z)return;let{resolve:t}=Z;Z=null,sj?.classList.remove(`show`),hj(),t(e)}function mj(){cj||(cj=e=>{e.key===`Escape`&&(e.stopPropagation(),pj(null))},document.addEventListener(`keydown`,cj))}function hj(){cj&&=(document.removeEventListener(`keydown`,cj),null)}function gj(e,t,n){return Z&&pj(null),new Promise(r=>{Z={kind:e,state:t,...n,resolve:r},uj(),sj.classList.add(`show`),mj(),sj.querySelector(`.todo-io-card`)?.focus()})}function _j({counts:e={},scope:t=`all`,format:n=`json`}={}){return gj(`export`,{scope:$A.includes(t)?t:`all`,format:ej.includes(n)?n:`json`},{counts:e})}function vj({count:e=0,existing:t=0,mode:n=`merge`}={}){return gj(`import`,{mode:tj.includes(n)?n:`merge`},{info:{count:e,existing:t}})}c(()=>{Z&&(uj(),sj.querySelector(`.todo-io-card`)?.focus())}),n(`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:`还没有待办,加一条就能看到趋势`}}),n(`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 yj={zh:[`日`,`一`,`二`,`三`,`四`,`五`,`六`],en:[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`]},bj=6;function xj(e){let[t,n,r]=String(e||``).split(`-`).map(Number);return!t||!n||!r?null:new Date(t,n-1,r)}function Sj(e){let t=xj(e);return t?s()===`en`?`${t.toLocaleString(`en-US`,{month:`short`})} ${t.getDate()}`:`${t.getMonth()+1}月${t.getDate()}日`:String(e||``)}function Cj(e){let t=xj(e);return t?(yj[s()]||yj.zh)[t.getDay()]:``}function wj(e,t,n){return`<div class="todo-stats-tile${n?` ${n}`:``}">
|
|
2403
2403
|
<span class="todo-stats-tile-value">${e}</span>
|
|
2404
2404
|
<span class="todo-stats-tile-label">${t}</span>
|
|
2405
|
-
</div>`}function
|
|
2405
|
+
</div>`}function Tj(e){let t=e.reduce((e,t)=>Math.max(e,t.done||0),0);return`<div class="todo-stats-week">${e.map(e=>{let n=e.done||0,i=n===0?0:Math.max(bj,Math.round(n/t*100));return`<div class="todo-stats-bar-col" title="${r(`todoStats.dayTitle`,{date:Sj(e.date),done:n,added:e.added||0})}">
|
|
2406
2406
|
<span class="todo-stats-bar" style="height:${i}%"></span>
|
|
2407
|
-
<span class="todo-stats-bar-label">${
|
|
2408
|
-
</div>`}).join(``)}</div>`}function
|
|
2407
|
+
<span class="todo-stats-bar-label">${Cj(e.date)}</span>
|
|
2408
|
+
</div>`}).join(``)}</div>`}function Ej(e){let t=e&&typeof e==`object`?e:{},n=Number(t.total)||0;if(n===0)return`<div class="todo-stats-empty">${r(`todoStats.empty`)}</div>`;let i=Math.min(100,Math.max(0,Number(t.doneRate)||0)),a=t.today||{added:0,done:0},o=Array.isArray(t.week)?t.week:[];return`<div class="todo-stats-hero">
|
|
2409
2409
|
<div class="todo-stats-rate">
|
|
2410
2410
|
<span class="todo-stats-rate-value">${i}%</span>
|
|
2411
2411
|
<span class="todo-stats-rate-label">${r(`todoStats.rate`)}</span>
|
|
@@ -2414,29 +2414,29 @@ Sessions using this assistant will revert to the default assistant.`,deleteAgent
|
|
|
2414
2414
|
<div class="todo-stats-track"><i style="width:${i}%"></i></div>
|
|
2415
2415
|
</div>
|
|
2416
2416
|
<div class="todo-stats-tiles">
|
|
2417
|
-
${
|
|
2418
|
-
${
|
|
2419
|
-
${
|
|
2420
|
-
${
|
|
2417
|
+
${wj(t.pending||0,r(`todoStats.pending`))}
|
|
2418
|
+
${wj(t.doing||0,r(`todoStats.doing`),`doing`)}
|
|
2419
|
+
${wj(t.done||0,r(`todoStats.done`),`done`)}
|
|
2420
|
+
${wj(t.overdue||0,r(`todoStats.overdue`),t.overdue?`alert`:``)}
|
|
2421
2421
|
</div>
|
|
2422
2422
|
<div class="todo-stats-section">
|
|
2423
2423
|
<div class="todo-stats-section-title">${r(`todoStats.week`)}</div>
|
|
2424
|
-
${
|
|
2424
|
+
${Tj(o)}
|
|
2425
2425
|
</div>
|
|
2426
2426
|
<div class="todo-stats-facts">
|
|
2427
2427
|
<span>${r(`todoStats.todayAdded`,{n:a.added||0})}</span>
|
|
2428
2428
|
<span>${r(`todoStats.todayDone`,{n:a.done||0})}</span>
|
|
2429
2429
|
<span>${r(`todoStats.streak`,{n:t.streak||0})}</span>
|
|
2430
2430
|
<span>${r(`todoStats.highCount`,{n:t.high||0})}</span>
|
|
2431
|
-
</div>`}var
|
|
2431
|
+
</div>`}var Dj=`<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>`,Oj=null,kj=null;function Aj(){return Oj||(Oj=document.createElement(`div`),Oj.className=`todo-stats-overlay`,Oj.id=`todoStatsOverlay`,Oj.addEventListener(`click`,e=>{(e.target===Oj||e.target.closest?.(`[data-action="close-stats"]`))&&Pj()}),document.body.appendChild(Oj),Oj)}function jj(e){let t=Aj();t.innerHTML=`
|
|
2432
2432
|
<div class="todo-stats-card" role="dialog" aria-modal="true" aria-label="${I(r(`todoStats.title`))}">
|
|
2433
2433
|
<div class="todo-stats-header">
|
|
2434
2434
|
<span class="todo-stats-title">${r(`todoStats.title`)}</span>
|
|
2435
2435
|
<button type="button" class="todo-stats-close" data-action="close-stats"
|
|
2436
|
-
title="${I(r(`todoStats.close`))}" aria-label="${I(r(`todoStats.close`))}">${
|
|
2436
|
+
title="${I(r(`todoStats.close`))}" aria-label="${I(r(`todoStats.close`))}">${Dj}</button>
|
|
2437
2437
|
</div>
|
|
2438
|
-
<div class="todo-stats-body">${
|
|
2439
|
-
</div>`}async function
|
|
2438
|
+
<div class="todo-stats-body">${Ej(e)}</div>
|
|
2439
|
+
</div>`}async function Mj(){let e=await vA(),{active:t,done:n}=DA();jj(gA([...t,...n],e))}async function Nj(){await Mj();let e=Aj();e.classList.add(`show`),kj||(kj=e=>{e.key===`Escape`&&(e.stopPropagation(),Pj())},document.addEventListener(`keydown`,kj)),e.querySelector(`.todo-stats-close`)?.focus()}function Pj(){Oj&&(Oj.classList.remove(`show`),kj&&=(document.removeEventListener(`keydown`,kj),null))}c(()=>{Oj?.classList.contains(`show`)&&Mj()}),n(`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:`待办统计`}}),n(`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 Fj=`.input-container`,Ij=160,Lj=8,Rj=108,zj=220,Bj=6e3,Q={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>`},Vj=null,Hj=null,Uj=null,Wj=null,Gj=null,Kj=null,qj=null,Jj=null,Yj=null,Xj=null,Zj=null,Qj=`active`,$j=null,eM=null,tM=null,nM=null,rM=new Set,iM=null,aM=!1,oM=null,sM=null,cM=null,lM=null,uM=0,dM=new Map,fM=[`todo-edit-input`,`todo-note-input`,`todo-due-input`,`todo-link-input`],pM={"todo-edit-input":`title`,"todo-note-input":`note`,"todo-due-input":`due`,"todo-link-input":`link`};function mM(){aM||(aM=!0,Vj=document.createElement(`div`),Vj.className=`todo-panel-container`,Vj.id=`todoPanelContainer`,Vj.innerHTML=`
|
|
2440
2440
|
<button class="todo-panel-toggle" id="todoPanelToggle" data-i18n-title="todo.toggleTitle" data-i18n-aria-label="todo.toggleTitle">
|
|
2441
2441
|
<span class="todo-badge" id="todoBadge" style="display:none;"></span>
|
|
2442
2442
|
${Q.listCheck}
|
|
@@ -2468,17 +2468,17 @@ Sessions using this assistant will revert to the default assistant.`,deleteAgent
|
|
|
2468
2468
|
</div>
|
|
2469
2469
|
<div class="todo-body" id="todoBody"></div>
|
|
2470
2470
|
</div>
|
|
2471
|
-
`,er(`todo`).appendChild(
|
|
2472
|
-
<span class="todo-undo-text">${P(r(`todo.undoBar`,{title:
|
|
2473
|
-
<button class="todo-mini-btn" data-action="undo-complete" data-id="${I(
|
|
2474
|
-
</div>`),
|
|
2471
|
+
`,er(`todo`).appendChild(Vj),o(Vj),qj=Vj.querySelector(`#todoPanelToggle`),Hj=Vj.querySelector(`#todoPanel`),Uj=Vj.querySelector(`#todoBody`),Wj=Vj.querySelector(`#todoPanelCount`),Gj=Vj.querySelector(`#todoProgressBar`),Kj=Vj.querySelector(`#todoAddInput`),Jj=Vj.querySelector(`#todoBadge`),Xj=Vj.querySelector(`#todoTabActive`),Zj=Vj.querySelector(`#todoTabDone`),Wj.textContent=r(`todo.progressLabel`,{done:0,total:0}),qj.addEventListener(`click`,gM),Vj.addEventListener(`click`,qM),Vj.addEventListener(`change`,pN),Vj.addEventListener(`keydown`,eN),Uj.addEventListener(`dragstart`,RN),Uj.addEventListener(`dragover`,zN),Uj.addEventListener(`drop`,VN),Uj.addEventListener(`dragend`,HN),Uj.addEventListener(`focusout`,mN),Uj.addEventListener(`focusin`,e=>{let t=e.target.closest?.(`.todo-item`);t?.dataset.id&&(cM=t.dataset.id)}),Vj.addEventListener(`pointerdown`,e=>{let t=e.target?.closest?.(`[data-action="link-cancel"]`);t&&(e.preventDefault(),vN(t.dataset.id||nM))}),document.addEventListener(`keydown`,e=>{e.key===`Escape`&&Yj&&SN()}),document.addEventListener(`keydown`,rN),document.addEventListener(`click`,e=>{Yj&&(Yj.contains(e.target)||SN())},!0),wA(()=>OM()),c(()=>{o(Vj),OM()}),i().then(()=>{o(Vj),OM()}),OM())}function hM(){return!!Hj&&Hj.classList.contains(`expanded`)}function gM(){hM()?vM():_M()}function _M(){Qj=`active`,oM=null,uM=0,Hj.style.removeProperty(`height`),OM(),Hj.classList.add(`expanded`),qj.classList.add(`active`),MM(),jM(),setTimeout(()=>{hM()&&Kj.focus()},60)}function vM(){Hj.classList.remove(`expanded`),qj.classList.remove(`active`),NM(),Hj.style.removeProperty(`--fit-y`),Hj.style.removeProperty(`--todo-max-h`),Hj.style.removeProperty(`height`),uM=0,SN(),yN(),FM()}function yM(){fM.forEach(e=>{Uj.querySelectorAll(`.${e}`).forEach(t=>{let n=t.dataset.id;if(!n)return;let r=dM.get(n)||{};r[pM[e]]=t.value,dM.set(n,r)})})}function bM(e){if(dM.size===0)return;let t=new Set(e.map(e=>e.id));for(let e of[...dM.keys()])t.has(e)||dM.delete(e)}function xM(e){e?dM.delete(e):dM.clear()}function SM(e,t){let n=dM.get(e);return n&&n[t]!==void 0?n[t]:null}function CM(){let e=document.activeElement;if(!e||!Uj.contains(e))return null;let t=fM.find(t=>e.classList.contains(t));return!t||!e.dataset.id?null:{cls:t,id:e.dataset.id,caret:wM(e)}}function wM(e){try{return e.selectionStart}catch{return null}}function TM(e){return Uj.querySelector(`.${e.cls}[data-id="${I(e.id)}"]`)}function EM(e){let t=TM(e);if(t&&(t.focus(),e.caret!==null))try{t.selectionStart=t.selectionEnd=e.caret}catch{}}function DM(){if($j){UM();return}if(eM){let e=TM({cls:`todo-note-input`,id:eM});e&&e.focus();return}if(tM){let e=TM({cls:`todo-due-input`,id:tM});e&&e.focus();return}if(nM){let e=TM({cls:`todo-link-input`,id:nM});if(!e)return;e.focus(),e.selectionStart=e.selectionEnd=e.value.length}}function OM(){if(!Uj)return;yM();let e=CM(),t=document.activeElement?.closest?.(`.todo-item`)?.dataset.id||null,{active:n,done:i,stats:a}=DA();Wj.textContent=r(`todo.progressLabel`,{done:a.done,total:a.total})+(a.doing>0?r(`todo.progressDoing`,{doing:a.doing}):``),Gj.style.width=a.total?`${Math.round(a.done/a.total*100)}%`:`0%`,IM(n.length),kM(n.length,i.length);let o=Qj===`done`?i:n,s=[];if(bM([...n,...i]),oM&&s.push(`<div class="todo-undo">
|
|
2472
|
+
<span class="todo-undo-text">${P(r(`todo.undoBar`,{title:oM.title}))}</span>
|
|
2473
|
+
<button class="todo-mini-btn" data-action="undo-complete" data-id="${I(oM.id)}">${P(r(`todo.undoAction`))}</button>
|
|
2474
|
+
</div>`),Qj===`done`&&i.length>0&&s.push(`<button class="todo-clear-done" data-action="clear-completed-btn">
|
|
2475
2475
|
${Q.trash}<span>${P(r(`todo.clearCompleted`))} (${i.length})</span>
|
|
2476
|
-
</button>`),o.length===0){let e=
|
|
2476
|
+
</button>`),o.length===0){let e=Qj===`done`;s.push(`<div class="todo-empty">
|
|
2477
2477
|
<div class="todo-empty-title">${P(r(e?`todo.emptyDone`:`todo.empty`))}</div>
|
|
2478
2478
|
<div class="todo-empty-hint">${P(r(e?`todo.emptyDoneHint`:`todo.emptyHint`))}</div>
|
|
2479
|
-
</div>`)}else s.push(`<div class="todo-list" data-group="${
|
|
2480
|
-
title="${I(t)}" aria-label="${I(t)}">${n}</button>`}function
|
|
2481
|
-
title="${I(n)}" aria-label="${I(n)}">${Q.link}<span>${P(t)}</span></button>`}function
|
|
2479
|
+
</div>`)}else s.push(`<div class="todo-list" data-group="${Qj}">${o.map(e=>HM(e,Qj)).join(``)}</div>`);Uj.innerHTML=s.join(``),e?EM(e):t?sN(t):DM(),jM()}function kM(e,t){if(!Xj||!Zj)return;let n=Qj===`done`;Xj.classList.toggle(`active`,!n),Zj.classList.toggle(`active`,n),Xj.setAttribute(`aria-selected`,String(!n)),Zj.setAttribute(`aria-selected`,String(n)),Xj.querySelector(`.todo-tab-count`).textContent=String(e),Zj.querySelector(`.todo-tab-count`).textContent=String(t)}function AM(){let e=document.querySelector(Fj)?.getBoundingClientRect();return e&&e.height>0&&Number.isFinite(e.top)?e.top:window.innerHeight-Ij}function jM(){!Hj||!hM()||(Hj.style.removeProperty(`--fit-y`),requestAnimationFrame(()=>{if(!Hj||!hM())return;let e=AM()-Lj,t=Hj.getBoundingClientRect();if(!t.height)return;let n=Math.max(zj,Math.floor(e-Rj));Hj.style.setProperty(`--todo-max-h`,`${n}px`),uM&&(Hj.style.height=`auto`),uM=Math.min(n,Math.max(uM,Hj.offsetHeight)),Hj.style.height=`${uM}px`;let r=Math.floor(e-t.bottom);r&&Hj.style.setProperty(`--fit-y`,`${r}px`)}))}function MM(){NM(),window.addEventListener(`resize`,jM);let e=document.querySelector(Fj);e&&typeof ResizeObserver<`u`&&(lM=new ResizeObserver(()=>jM()),lM.observe(e))}function NM(){window.removeEventListener(`resize`,jM),lM?.disconnect(),lM=null}function PM(e){oM={id:e.id,title:e.title},clearTimeout(sM),sM=setTimeout(()=>{oM=null,OM()},Bj)}function FM(){clearTimeout(sM),sM=null,oM=null}function IM(e){Jj&&(e>0?(Jj.textContent=e>99?`99+`:String(e),Jj.style.display=``):Jj.style.display=`none`)}function LM(e){return e===X.DONE?r(`todo.statusDone`):e===X.DOING?r(`todo.statusDoing`):r(`todo.statusPending`)}function RM(e){let t=r(`todo.statusTip`,{status:LM(e.status),next:LM(Tk(e.status))}),n=e.status===X.DONE?Q.check:e.status===X.DOING?`<i></i>`:``;return`<button class="todo-status" data-action="cycle" data-id="${I(e.id)}"
|
|
2480
|
+
title="${I(t)}" aria-label="${I(t)}">${n}</button>`}function zM(e){let t=jk(e);if(!t)return``;let n=r(`todo.openLinkTitle`,{host:t});return`<button class="todo-link-chip" data-action="open-link" data-id="${I(e.id)}"
|
|
2481
|
+
title="${I(n)}" aria-label="${I(n)}">${Q.link}<span>${P(t)}</span></button>`}function BM(e){let t=zM(e);if(e.status===X.DONE)return`<div class="todo-meta">${t}<span>${P(Jk(e))}</span></div>`;let n=[];if(t&&n.push(t),Number.isFinite(e.dueAt)){let t=Yk(e),i=t?r(`todoTime.overdueStamp`,{date:qk(e.dueAt)}):qk(e.dueAt);n.push(`<span class="todo-due${t?` overdue`:``}">${Q.alert}${P(i)}</span>`)}let i=Kk(e.createdAt);return i&&n.push(`<span>${P(i)}</span>`),n.length===0?``:`<div class="todo-meta">${n.join(`<span class="todo-sep">·</span>`)}</div>`}function VM(e){let t=rM.has(e.id),n=eM===e.id,i=!!(e.note&&e.note.trim());if(n){let t=SM(e.id,`note`);return`<div class="todo-note-editor">
|
|
2482
2482
|
<textarea class="todo-note-input" data-id="${I(e.id)}" rows="2"
|
|
2483
2483
|
placeholder="${I(r(`todo.notePlaceholder`))}">${P(t===null?e.note||``:t)}</textarea>
|
|
2484
2484
|
<div class="todo-note-editor-actions">
|
|
@@ -2488,50 +2488,50 @@ Sessions using this assistant will revert to the default assistant.`,deleteAgent
|
|
|
2488
2488
|
</div>`}return i?`<button class="todo-note-toggle${t?` open`:``}" data-action="toggle-note" data-id="${I(e.id)}">
|
|
2489
2489
|
${Q.chevron}<span>${P(r(`todo.noteToggle`))}</span>
|
|
2490
2490
|
</button>
|
|
2491
|
-
${t?`<div class="todo-note">${P(e.note)}</div>`:``}`:``}function
|
|
2492
|
-
<input type="date" class="todo-due-input" data-id="${I(e.id)}" value="${I(c===null?
|
|
2491
|
+
${t?`<div class="todo-note">${P(e.note)}</div>`:``}`:``}function HM(e,t){let n=e.status===X.DONE,i=$j===e.id,a=[`todo-item`];e.status===X.DOING&&a.push(`doing`),n&&a.push(`done`),e.priority&&a.push(`prio-${e.priority}`),tM===e.id&&a.push(`editing-due`);let o=SM(e.id,`title`),s=i?`<input type="text" class="todo-edit-input" data-id="${I(e.id)}" value="${I(o===null?e.title:o)}" />`:`<div class="todo-name">${P(e.title)}</div>`,c=SM(e.id,`due`),l=tM===e.id?`<div class="todo-due-editor">
|
|
2492
|
+
<input type="date" class="todo-due-input" data-id="${I(e.id)}" value="${I(c===null?WM(e.dueAt):c)}" />
|
|
2493
2493
|
<button class="todo-mini-btn ghost" data-action="due-clear" data-id="${I(e.id)}">${P(r(`todo.clearDue`))}</button>
|
|
2494
|
-
</div>`:``,u=
|
|
2494
|
+
</div>`:``,u=SM(e.id,`link`),d=nM===e.id?`<div class="todo-link-editor">
|
|
2495
2495
|
<input type="text" class="todo-link-input" data-id="${I(e.id)}" autocomplete="off"
|
|
2496
2496
|
placeholder="${I(r(`todo.linkPlaceholder`))}" value="${I(u===null?e.link||``:u)}" />
|
|
2497
2497
|
<button class="todo-mini-btn ghost" data-action="link-cancel" data-id="${I(e.id)}">${P(r(`todo.noteCancel`))}</button>
|
|
2498
|
-
</div>`:``,f=t===`active`?` draggable="true"`:``,p
|
|
2498
|
+
</div>`:``,f=t===`active`?` draggable="true"`:``,p=$j===e.id||eM===e.id||tM===e.id||nM===e.id,m=`
|
|
2499
2499
|
<div class="todo-item-actions">
|
|
2500
|
-
${n?`<button class="todo-act" data-action="restore" data-id="${I(e.id)}" title="${I(r(`todo.restoreTo`,{status:
|
|
2500
|
+
${n?`<button class="todo-act" data-action="restore" data-id="${I(e.id)}" title="${I(r(`todo.restoreTo`,{status:LM(Nk(e))}))}" aria-label="${I(r(`todo.restoreTo`,{status:LM(Nk(e))}))}">${Q.undo}</button>`:``}
|
|
2501
2501
|
<button class="todo-act" data-action="edit-title" data-id="${I(e.id)}" title="${I(r(`todo.editItem`))}" aria-label="${I(r(`todo.editItem`))}">${Q.edit}</button>
|
|
2502
2502
|
<button class="todo-act" data-action="copy-item" data-id="${I(e.id)}" title="${I(r(`todo.copyItem`))}" aria-label="${I(r(`todo.copyItem`))}">${Q.copy}</button>
|
|
2503
2503
|
<button class="todo-act" data-action="fill-item" data-id="${I(e.id)}" title="${I(r(`todo.fillInput`))}" aria-label="${I(r(`todo.fillInput`))}">${Q.fill}</button>
|
|
2504
2504
|
<button class="todo-act" data-action="row-more" data-id="${I(e.id)}" title="${I(r(`todo.more`))}" aria-label="${I(r(`todo.more`))}">${Q.more}</button>
|
|
2505
2505
|
</div>`;return`<div class="${a.join(` `)}" data-id="${I(e.id)}" data-group="${t}"${f} tabindex="0" data-priority="${I(e.priority||``)}">
|
|
2506
|
-
${
|
|
2506
|
+
${RM(e)}
|
|
2507
2507
|
<div class="todo-main">
|
|
2508
2508
|
${s}
|
|
2509
|
-
${
|
|
2509
|
+
${VM(e)}
|
|
2510
2510
|
${l}
|
|
2511
2511
|
${d}
|
|
2512
|
-
${
|
|
2512
|
+
${BM(e)}
|
|
2513
2513
|
</div>
|
|
2514
2514
|
${p?``:m}
|
|
2515
|
-
</div>`}function
|
|
2515
|
+
</div>`}function UM(){let e=Uj.querySelector(`.todo-edit-input[data-id="${$j}"]`);e&&(e.focus(),e.selectionStart=e.selectionEnd=e.value.length)}function WM(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 GM(e,t){Promise.resolve(e).then(e=>{if(e===!0||e&&e.ok===!0){t&&L(t,`success`);return}L(r(e&&e.reason===`invalid`?`todo.linkInvalid`:`todo.saveFailed`),`error`)})}function KM(e){let t=e&&e.link;if(!t||!Mk(t)){L(r(`todo.linkInvalid`),`error`);return}try{chrome.tabs.create({url:t})}catch(e){a.warn(`[Todo] open link failed:`,e),L(r(`todo.copyFailed`),`error`)}}function qM(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(),vM();return;case`fill-item`:e.stopPropagation(),FN(r);return;case`copy-item`:e.stopPropagation(),IN(r);return;case`header-more`:e.stopPropagation(),ON(t);return;case`add`:e.stopPropagation(),hN();return;case`switch-tab`:YM(t.dataset.tab);return;case`undo-complete`:e.stopPropagation(),QM(r);return;case`restore`:e.stopPropagation(),ZM(r);return;case`open-link`:e.stopPropagation(),KM(JM(r));return;case`clear-completed-btn`:e.stopPropagation(),$M();return;case`cycle`:e.stopPropagation(),GM(NA(r));return;case`toggle-note`:e.stopPropagation(),rM.has(r)?rM.delete(r):rM.add(r),OM();return;case`edit-title`:e.stopPropagation(),yN(),$j=r,OM();return;case`row-more`:e.stopPropagation(),DN(t,r);return;case`note-save`:e.stopPropagation(),gN(r);return;case`note-cancel`:e.stopPropagation(),eM=null,xM(r),OM();return;case`due-clear`:e.stopPropagation(),tM=null,xM(r),GM(jA(r,{dueAt:null}));return;case`link-cancel`:e.stopPropagation(),vN(r);return;default:return}}function JM(e){let{active:t,done:n}=DA();return[...t,...n].find(t=>t.id===e)||null}function YM(e){let t=e===`done`?`done`:`active`;t!==Qj&&(Qj=t,yN(),OM())}function XM(e){let t=JM(e);t&&(PM(t),GM(MA(e,X.DONE)))}function ZM(e){let t=JM(e);if(!t)return;let n=Nk(t);FM(),GM(PA(e),r(`todo.restoredToast`,{status:LM(n)}))}function QM(e){ZM(e)}async function $M(){let{done:e}=DA();e.length!==0&&await bN(r(`todo.clearCompletedConfirmMsg`,{n:e.length}),r(`todo.clearCompletedConfirmTitle`))&&GM(zA(),r(`todo.clearedToast`))}function eN(e){if((e.key===`ArrowUp`||e.key===`ArrowDown`)&&!e.target.closest?.(`input, textarea, [contenteditable="true"]`)&&e.target.closest?.(`.todo-item`)){e.preventDefault(),oN(e.key===`ArrowDown`?1:-1);return}if(e.target===Kj){e.key===`Enter`?(e.preventDefault(),hN()):e.key===`Escape`&&(e.stopPropagation(),Kj.value=``,hM()&&vM());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($j=null,!n){xM(t),OM();return}xM(t),GM(jA(t,{title:n}))}else e.key===`Escape`&&(e.stopPropagation(),$j=null,xM(e.target.dataset.id),OM());return}if(e.target.classList?.contains(`todo-note-input`)){e.key===`Enter`&&(e.metaKey||e.ctrlKey)?(e.preventDefault(),e.stopPropagation(),gN(e.target.dataset.id)):e.key===`Escape`&&(e.stopPropagation(),eM=null,xM(e.target.dataset.id),OM());return}if(e.target.classList?.contains(`todo-link-input`)){let t=e.target.dataset.id;e.key===`Enter`?(e.preventDefault(),e.stopPropagation(),_N(t,e.target.value)):e.key===`Escape`&&(e.stopPropagation(),vN(t))}}var tN={KeyT:()=>gM(),KeyA:()=>cN(),KeyB:e=>lN(e),KeyL:e=>uN(e),KeyD:e=>dN(e),KeyP:e=>fN(e)},nN=new Set([`KeyT`,`KeyA`]);function rN(e){if(!e.altKey||e.shiftKey||e.ctrlKey||e.metaKey)return;let t=tN[e.code];if(!t)return;if(nN.has(e.code)){e.preventDefault(),t();return}let n=aN();n&&(e.preventDefault(),t(n))}function iN(){return Uj?Array.from(Uj.querySelectorAll(`.todo-item`)):[]}function aN(){if(!hM())return null;let e=document.activeElement?.closest?.(`.todo-item`);if(e?.dataset.id&&Uj.contains(e))return e.dataset.id;let t=iN();return cM&&t.some(e=>e.dataset.id===cM)?cM:t[0]?.dataset.id||null}function oN(e){let t=iN();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 sN(e){let t=iN().find(t=>t.dataset.id===e);t&&t.focus()}function cN(){if(hM()){Kj.focus();return}_M()}function lN(e){eM=e,rM.add(e),OM()}function uN(e){nM=e,OM()}function dN(e){let t=JM(e);t&&(t.status===X.DONE?ZM(e):XM(e))}function fN(e){let t=JM(e);t&&GM(FA(e,Ok(t.priority)))}function pN(e){if(e.target.classList?.contains(`todo-link-input`)){let t=e.target.dataset.id;if(!nM||nM!==t)return;_N(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(tM=null,xM(t),!n){GM(jA(t,{dueAt:null}));return}let r=new Date(n+`T00:00:00`);GM(jA(t,{dueAt:isNaN(r.getTime())?null:r.getTime()}))}function mN(e){if(e.target?.classList?.contains(`todo-link-input`)){let t=e.target.dataset.id;if(!nM||nM!==t)return;_N(t,e.target.value);return}if(!e.target?.classList?.contains(`todo-edit-input`))return;let t=e.target.dataset.id;if(!$j||$j!==t)return;let n=e.target.value.trim();if($j=null,!n){xM(t),OM();return}xM(t),jA(t,{title:n}).then(e=>{e?OM():L(r(`todo.saveFailed`),`error`)})}async function hN(){let e=Kj.value.trim();e&&(Kj.value=``,Qj===`done`&&(Qj=`active`),await AA(e)||L(r(`todo.saveFailed`),`error`),Kj.focus())}function gN(e){let t=Uj.querySelector(`.todo-note-input[data-id="${I(e)}"]`),n=t?t.value:``;eM=null,rM.delete(e),xM(e),GM(jA(e,{note:n}))}function _N(e,t){let n=!!JM(e)?.link;nM=null,xM(e);let i=String(t||``).trim();GM(IA(e,i),r(i?`todo.linkSavedToast`:n?`todo.linkRemovedToast`:`todo.linkSavedToast`))}function vN(e){nM=null,xM(e),OM()}function yN(){let e=$j||eM||tM||nM;$j=null,eM=null,tM=null,nM=null,xM(),e&&OM()}async function bN(e,t){return typeof window<`u`&&typeof window.showCustomConfirm==`function`?!!await window.showCustomConfirm(e,t):!1}function xN(){return Yj||(Yj=document.createElement(`div`),Yj.className=`todo-menu`,document.body.appendChild(Yj),Yj.addEventListener(`click`,e=>{let t=e.target.closest(`[data-priority-value]`);if(t){let e=t.dataset.menuId,n=t.dataset.priorityValue||null;SN(),GM(FA(e,n));return}let n=e.target.closest(`[data-menu-action]`);if(!n)return;let{menuAction:r,menuId:i}=n.dataset;SN(),NN(r,i)}),Yj)}function SN(){Yj&&=(Yj.remove(),null)}function CN(e){return e?`<kbd class="todo-menu-kbd">${P(e)}</kbd>`:``}function wN(e,t){if(e.swatches){let n=[[``,r(`todo.priorityNone`)],[gk.LOW,r(`todo.priorityLow`)],[gk.MEDIUM,r(`todo.priorityMedium`)],[gk.HIGH,r(`todo.priorityHigh`)]];return`<div class="todo-menu-row">
|
|
2516
2516
|
<span class="todo-menu-row-label">${P(e.label)}</span>
|
|
2517
2517
|
${n.map(([n,i])=>`
|
|
2518
2518
|
<button type="button" class="todo-swatch${n?` ${n}`:``}${e.current===n?` active`:``}"
|
|
2519
2519
|
data-priority-value="${I(n)}" data-menu-id="${I(t)}"
|
|
2520
2520
|
title="${I(r(`todo.priorityTitle`,{level:i}))}"
|
|
2521
2521
|
aria-label="${I(i)}"></button>`).join(``)}
|
|
2522
|
-
${
|
|
2522
|
+
${CN(e.shortcut)}
|
|
2523
2523
|
</div>`}return`${e.divider?`<div class="todo-menu-sep"></div>`:``}<button type="button" data-menu-action="${I(e.action)}" data-menu-id="${I(t||``)}"
|
|
2524
2524
|
class="todo-menu-item${e.danger?` danger`:``}">
|
|
2525
|
-
${e.icon||``}<span>${P(e.label)}</span>${
|
|
2526
|
-
</button>`}function wN(e,t,n){let r=bN();r.innerHTML=t.map((e,t)=>t===0&&e.divider?{...e,divider:!1}:e).map(e=>CN(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 TN(e){if(e.status===X.DONE){let t=Mk(e),n=[{action:`restore`,label:r(`todo.restoreTo`,{status:IM(t)}),icon:Q.undo,shortcut:`Alt+D`,divider:!0}];return t!==X.PENDING&&n.push({action:`set-pending`,label:r(`todo.backToPending`),icon:Q.circle}),n}return e.status===X.DOING?[{action:`set-done`,label:r(`todo.markDone`),icon:Q.check,shortcut:`Alt+D`,divider:!0},{action:`set-pending`,label:r(`todo.backToPending`),icon:Q.circle}]:[{action:`set-doing`,label:r(`todo.startDoing`),icon:Q.play,divider:!0},{action:`set-done`,label:r(`todo.markDone`),icon:Q.check,shortcut:`Alt+D`}]}function EN(e,t){let n=qM(t);n&&wN(e,[...TN(n),{swatches:!0,label:r(`todo.priority`),current:n.priority||``,shortcut:`Alt+P`,divider:!0},{action:`edit-title`,label:r(`todo.editTitleAction`),icon:Q.edit,divider:!0},{action:`edit-note`,label:n.note?r(`todo.editNote`):r(`todo.addNote`),icon:Q.note,shortcut:`Alt+B`},{action:`set-due`,label:r(`todo.setDue`),icon:Q.calendar},{action:`edit-link`,label:n.link?r(`todo.editLink`):r(`todo.addLink`),icon:Q.link,shortcut:`Alt+L`},{action:`delete`,label:r(`todo.delete`),icon:Q.trash,danger:!0,divider:!0}],t)}function DN(e){let t=ON();t.length!==0&&wN(e,t,``)}function ON(){return[{action:`stats`,label:r(`todo.statsEntry`),icon:Q.chart,divider:!0},{action:`export-options`,label:r(`todo.exportEntry`),icon:Q.download,divider:!0},{action:`import-options`,label:r(`todo.importEntry`),icon:Q.upload}]}async function kN(){let{active:e,done:t}=EA(),n=await gj({counts:{all:e.length+t.length,active:e.length,done:t.length}});n&&AN(n.scope,n.format)}function AN(e,t){let{active:n,done:i}=EA(),o=[...n,...i];if(eA(o,e).length===0){L(r(`todo.exportEmptyToast`),`info`);return}try{L(r(`todo.exportedToast`,{name:JA(o,{scope:e,format:t})}),`success`)}catch(e){a.error(`[Todo] export failed:`,e),L(r(`todo.exportFailedToast`),`error`)}}async function jN(){let e=await YA();if(!e)return;let t=await XA(e);if(!t.ok){L(r(t.reason===`json`?`todo.importJsonError`:`todo.importFormatError`),`error`);return}let{active:n,done:i}=EA(),a=await _j({count:t.todos.length,existing:n.length+i.length});if(!a)return;Zj=`active`,DM();let o=await zA(t.todos,a);if(!o.ok){L(r(o.reason===`empty`?`todo.importEmptyToast`:`todo.importFailedToast`),`error`);return}if(o.added===0){L(r(`todo.importNothingNewToast`,{skipped:o.skipped}),`info`);return}L(r(`todo.importedToast`,{added:o.added,skipped:o.skipped}),`success`)}async function MN(e,t){let n=qM(t);switch(e){case`set-doing`:WM(jA(t,X.DOING));return;case`set-pending`:WM(jA(t,X.PENDING));return;case`set-done`:YM(t);return;case`restore`:XM(t);return;case`edit-title`:Qj=t,DM();return;case`edit-note`:$j=t,nM.add(t),DM(),setTimeout(()=>{let e=Hj.querySelector(`.todo-note-input[data-id="${t}"]`);e&&(e.focus(),e.selectionStart=e.selectionEnd=e.value.length)},30);return;case`set-due`:eM=t,DM(),setTimeout(()=>{let e=Hj.querySelector(`.todo-due-input[data-id="${t}"]`);e&&e.focus()},30);return;case`edit-link`:lN(t);return;case`stats`:Mj();return;case`export-options`:kN();return;case`import-options`:jN();return;case`delete`:await yN(r(`todo.deleteConfirmMsg`,{title:n?.title||``}),r(`todo.deleteConfirmTitle`))&&WM(IA(t),r(`todo.deletedToast`));return;default:}}function NN(e,t={}){let{active:n,done:r}=EA(),i=[...n,...r].find(t=>t.id===e);return i?Qk(i,t):``}function PN(e){let t=NN(e);if(!t){L(r(`todo.emptyDigestToast`),`info`);return}let n=document.getElementById(`userInput`);if(!n){L(r(`todo.noInputToast`),`error`);return}let i=n.value.replace(/\s+$/,``);n.value=i?`${i}\n\n${t}`:t,n.dispatchEvent(new Event(`input`,{bubbles:!0})),n.focus(),n.selectionStart=n.selectionEnd=n.value.length,Vt(),_M(),L(r(`todo.filledToast`),`success`)}function FN(e){let t=NN(e);if(!t){L(r(`todo.emptyDigestToast`),`info`);return}IN(t,r(`todo.copiedToast`))}function IN(e,t){try{navigator.clipboard.writeText(e).then(()=>{L(t,`success`)}).catch(e=>{a.warn(`[Todo] copy failed:`,e),L(r(`todo.copyFailed`),`error`)})}catch(e){a.warn(`[Todo] clipboard unavailable:`,e),L(r(`todo.copyFailed`),`error`)}}function LN(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`));rM={id:t.dataset.id,from:r.indexOf(t),list:n},t.classList.add(`dragging`);let{active:i,done:a}=EA(),o=[...i,...a].find(e=>e.id===t.dataset.id);try{e.dataTransfer.effectAllowed=`copyMove`,e.dataTransfer.setData(`text/plain`,Qk(o)||t.dataset.id)}catch{}}function RN(e){if(!rM)return;e.preventDefault();let t=rM.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=zN();r>=n.length?t.appendChild(i):n[r].before(i)}function zN(){let e=Hj.querySelector(`.todo-insert`);return e||(e=document.createElement(`div`),e.className=`todo-insert`,e)}function BN(e){if(!rM)return;e.preventDefault();let t=rM.list,n=Hj.querySelector(`.todo-insert`),r=rM.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=rM.from;VN(),i!==r&&WM(LA(i,r))}function VN(){rM=null,Hj?.querySelectorAll(`.todo-item.dragging`).forEach(e=>e.classList.remove(`dragging`)),Hj?.querySelector(`.todo-insert`)?.remove()}var HN=`—`,UN=[{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 WN(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 GN(e){if(!e)return HN;let t=Date.parse(e);return Number.isNaN(t)?HN:new Date(t).toLocaleString()}function KN(e){let t=WN(ht),n=[{label:r(`versionInfo.version`),value:t.version?`v${t.version}`:HN},{label:r(`versionInfo.tag`),value:t.tag||HN},{label:r(`versionInfo.commit`),value:t.commitId?t.commitId.slice(0,8):HN,title:t.commitId,mono:!0},{label:r(`versionInfo.publishedAt`),value:GN(t.publishedAt)}];e.textContent=``;for(let t of n){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 qN(e){e.textContent=``;for(let t of UN){let n=document.createElement(`div`);n.className=`version-info-link`,n.title=t.url;let i=document.createElement(`span`);i.className=`version-info-link-icon`,i.innerHTML=t.icon;let a=document.createElement(`span`);a.className=`version-info-link-label`,a.textContent=r(t.labelKey);let o=document.createElement(`span`);o.className=`version-info-link-arrow`,o.textContent=`↗`,n.appendChild(i),n.appendChild(a),n.appendChild(o),n.addEventListener(`click`,()=>{chrome.tabs.create({url:t.url})}),e.appendChild(n)}}function JN(){let e=WN(ht);return[`AI Helper v${e.version||HN}`,`${r(`versionInfo.tag`)}: ${e.tag||HN}`,`${r(`versionInfo.commit`)}: ${e.commitId||HN}`,`${r(`versionInfo.publishedAt`)}: ${GN(e.publishedAt)}`].join(`
|
|
2527
|
-
`)}function
|
|
2525
|
+
${e.icon||``}<span>${P(e.label)}</span>${CN(e.shortcut)}
|
|
2526
|
+
</button>`}function TN(e,t,n){let r=xN();r.innerHTML=t.map((e,t)=>t===0&&e.divider?{...e,divider:!1}:e).map(e=>wN(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 EN(e){if(e.status===X.DONE){let t=Nk(e),n=[{action:`restore`,label:r(`todo.restoreTo`,{status:LM(t)}),icon:Q.undo,shortcut:`Alt+D`,divider:!0}];return t!==X.PENDING&&n.push({action:`set-pending`,label:r(`todo.backToPending`),icon:Q.circle}),n}return e.status===X.DOING?[{action:`set-done`,label:r(`todo.markDone`),icon:Q.check,shortcut:`Alt+D`,divider:!0},{action:`set-pending`,label:r(`todo.backToPending`),icon:Q.circle}]:[{action:`set-doing`,label:r(`todo.startDoing`),icon:Q.play,divider:!0},{action:`set-done`,label:r(`todo.markDone`),icon:Q.check,shortcut:`Alt+D`}]}function DN(e,t){let n=JM(t);n&&TN(e,[...EN(n),{swatches:!0,label:r(`todo.priority`),current:n.priority||``,shortcut:`Alt+P`,divider:!0},{action:`edit-title`,label:r(`todo.editTitleAction`),icon:Q.edit,divider:!0},{action:`edit-note`,label:n.note?r(`todo.editNote`):r(`todo.addNote`),icon:Q.note,shortcut:`Alt+B`},{action:`set-due`,label:r(`todo.setDue`),icon:Q.calendar},{action:`edit-link`,label:n.link?r(`todo.editLink`):r(`todo.addLink`),icon:Q.link,shortcut:`Alt+L`},{action:`delete`,label:r(`todo.delete`),icon:Q.trash,danger:!0,divider:!0}],t)}function ON(e){let t=kN();t.length!==0&&TN(e,t,``)}function kN(){return[{action:`stats`,label:r(`todo.statsEntry`),icon:Q.chart,divider:!0},{action:`export-options`,label:r(`todo.exportEntry`),icon:Q.download,divider:!0},{action:`import-options`,label:r(`todo.importEntry`),icon:Q.upload}]}async function AN(){let{active:e,done:t}=DA(),n=await _j({counts:{all:e.length+t.length,active:e.length,done:t.length}});n&&jN(n.scope,n.format)}function jN(e,t){let{active:n,done:i}=DA(),o=[...n,...i];if(tA(o,e).length===0){L(r(`todo.exportEmptyToast`),`info`);return}try{L(r(`todo.exportedToast`,{name:YA(o,{scope:e,format:t})}),`success`)}catch(e){a.error(`[Todo] export failed:`,e),L(r(`todo.exportFailedToast`),`error`)}}async function MN(){let e=await XA();if(!e)return;let t=await ZA(e);if(!t.ok){L(r(t.reason===`json`?`todo.importJsonError`:`todo.importFormatError`),`error`);return}let{active:n,done:i}=DA(),a=await vj({count:t.todos.length,existing:n.length+i.length});if(!a)return;Qj=`active`,OM();let o=await BA(t.todos,a);if(!o.ok){L(r(o.reason===`empty`?`todo.importEmptyToast`:`todo.importFailedToast`),`error`);return}if(o.added===0){L(r(`todo.importNothingNewToast`,{skipped:o.skipped}),`info`);return}L(r(`todo.importedToast`,{added:o.added,skipped:o.skipped}),`success`)}async function NN(e,t){let n=JM(t);switch(e){case`set-doing`:GM(MA(t,X.DOING));return;case`set-pending`:GM(MA(t,X.PENDING));return;case`set-done`:XM(t);return;case`restore`:ZM(t);return;case`edit-title`:$j=t,OM();return;case`edit-note`:eM=t,rM.add(t),OM(),setTimeout(()=>{let e=Uj.querySelector(`.todo-note-input[data-id="${t}"]`);e&&(e.focus(),e.selectionStart=e.selectionEnd=e.value.length)},30);return;case`set-due`:tM=t,OM(),setTimeout(()=>{let e=Uj.querySelector(`.todo-due-input[data-id="${t}"]`);e&&e.focus()},30);return;case`edit-link`:uN(t);return;case`stats`:Nj();return;case`export-options`:AN();return;case`import-options`:MN();return;case`delete`:await bN(r(`todo.deleteConfirmMsg`,{title:n?.title||``}),r(`todo.deleteConfirmTitle`))&&GM(LA(t),r(`todo.deletedToast`));return;default:}}function PN(e,t={}){let{active:n,done:r}=DA(),i=[...n,...r].find(t=>t.id===e);return i?$k(i,t):``}function FN(e){let t=PN(e);if(!t){L(r(`todo.emptyDigestToast`),`info`);return}let n=document.getElementById(`userInput`);if(!n){L(r(`todo.noInputToast`),`error`);return}let i=n.value.replace(/\s+$/,``);n.value=i?`${i}\n\n${t}`:t,n.dispatchEvent(new Event(`input`,{bubbles:!0})),n.focus(),n.selectionStart=n.selectionEnd=n.value.length,Ht(),vM(),L(r(`todo.filledToast`),`success`)}function IN(e){let t=PN(e);if(!t){L(r(`todo.emptyDigestToast`),`info`);return}LN(t,r(`todo.copiedToast`))}function LN(e,t){try{navigator.clipboard.writeText(e).then(()=>{L(t,`success`)}).catch(e=>{a.warn(`[Todo] copy failed:`,e),L(r(`todo.copyFailed`),`error`)})}catch(e){a.warn(`[Todo] clipboard unavailable:`,e),L(r(`todo.copyFailed`),`error`)}}function RN(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`));iM={id:t.dataset.id,from:r.indexOf(t),list:n},t.classList.add(`dragging`);let{active:i,done:a}=DA(),o=[...i,...a].find(e=>e.id===t.dataset.id);try{e.dataTransfer.effectAllowed=`copyMove`,e.dataTransfer.setData(`text/plain`,$k(o)||t.dataset.id)}catch{}}function zN(e){if(!iM)return;e.preventDefault();let t=iM.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=BN();r>=n.length?t.appendChild(i):n[r].before(i)}function BN(){let e=Uj.querySelector(`.todo-insert`);return e||(e=document.createElement(`div`),e.className=`todo-insert`,e)}function VN(e){if(!iM)return;e.preventDefault();let t=iM.list,n=Uj.querySelector(`.todo-insert`),r=iM.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=iM.from;HN(),i!==r&&GM(RA(i,r))}function HN(){iM=null,Uj?.querySelectorAll(`.todo-item.dragging`).forEach(e=>e.classList.remove(`dragging`)),Uj?.querySelector(`.todo-insert`)?.remove()}var UN=`—`,WN=[{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 GN(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 KN(e){if(!e)return UN;let t=Date.parse(e);return Number.isNaN(t)?UN:new Date(t).toLocaleString()}function qN(e){let t=GN(_t),n=[{label:r(`versionInfo.version`),value:t.version?`v${t.version}`:UN},{label:r(`versionInfo.tag`),value:t.tag||UN},{label:r(`versionInfo.commit`),value:t.commitId?t.commitId.slice(0,8):UN,title:t.commitId,mono:!0},{label:r(`versionInfo.publishedAt`),value:KN(t.publishedAt)}];e.textContent=``;for(let t of n){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 JN(e){e.textContent=``;for(let t of WN){let n=document.createElement(`div`);n.className=`version-info-link`,n.title=t.url;let i=document.createElement(`span`);i.className=`version-info-link-icon`,i.innerHTML=t.icon;let a=document.createElement(`span`);a.className=`version-info-link-label`,a.textContent=r(t.labelKey);let o=document.createElement(`span`);o.className=`version-info-link-arrow`,o.textContent=`↗`,n.appendChild(i),n.appendChild(a),n.appendChild(o),n.addEventListener(`click`,()=>{chrome.tabs.create({url:t.url})}),e.appendChild(n)}}function YN(){let e=GN(_t);return[`AI Helper v${e.version||UN}`,`${r(`versionInfo.tag`)}: ${e.tag||UN}`,`${r(`versionInfo.commit`)}: ${e.commitId||UN}`,`${r(`versionInfo.publishedAt`)}: ${KN(e.publishedAt)}`].join(`
|
|
2527
|
+
`)}function XN(){let e=document.getElementById(`versionInfoBtn`),t=document.getElementById(`versionInfoModal`),n=document.getElementById(`versionInfoCloseBtn`),i=document.getElementById(`versionInfoCopyBtn`),a=document.getElementById(`versionInfoList`),o=document.getElementById(`versionInfoLinks`);if(!e||!t||!a)return;let s=()=>{t.style.display=`none`};e.addEventListener(`click`,e=>{e.stopPropagation();let n=document.getElementById(`headerMoreDropdown`);n&&n.classList.remove(`show`),qN(a),o&&JN(o),t.style.display=`flex`}),n&&n.addEventListener(`click`,s),t.addEventListener(`click`,e=>{e.target===t&&s()}),document.addEventListener(`keydown`,e=>{e.key===`Escape`&&t.style.display===`flex`&&s()}),i&&i.addEventListener(`click`,async()=>{try{await navigator.clipboard.writeText(YN()),L(r(`common.copySuccess`),`success`)}catch{L(r(`common.copyFailed`),`error`)}})}var ZN=null;function QN(){if(!ZN)return;ZN.classList.remove(`open`);let e=ZN.parentElement?ZN.parentElement.querySelector(`.section-select-row`):null;e&&e.classList.remove(`open`),ZN=null}function $N(){return`<input type="search" class="section-select-search" placeholder="${r(`sectionSelect.searchPlaceholder`)}" data-i18n-placeholder="sectionSelect.searchPlaceholder" spellcheck="false">`}function eP(e,t){if(!e)return;let n=String(t||``).trim().toLowerCase(),i=Array.from(e.children).filter(e=>e.hasAttribute(`data-value`)),a=0;for(let e of i){let t=!n||e.textContent.toLowerCase().includes(n);e.style.display=t?``:`none`,t&&(a+=1)}let o=e.querySelector(`.section-select-empty`);n&&a===0?(o||(o=document.createElement(`div`),o.className=`section-select-empty`,e.appendChild(o)),o.textContent=r(`sectionSelect.noMatch`)):o&&o.remove()}function tP(e,t){QN(),e.classList.add(`open`),t.classList.add(`open`),ZN=e;let n=e.querySelector(`.section-select-search`);n&&(n.value=``,eP(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===ZN?QN():tP(e,t);return}ZN&&!ZN.parentElement.contains(e.target)&&QN()}),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&&eP(n,t.value)});var nP=!1;async function rP(){document.getElementById(`providerList`)&&(nP||(nP=!0,oP(),sP()),await iP())}async function iP(){let e=document.getElementById(`providerList`),t=document.getElementById(`providerSelectValue`),n=document.getElementById(`providerSelectHost`);if(!e)return;let r=await w(),i=r.profiles.find(e=>e.id===r.activeProfileId)||r.profiles[0];t&&(t.textContent=i?i.name:``),n&&(n.textContent=i?O(i.apiBase):``),e.innerHTML=$N();let a=[...r.profiles].sort((e,t)=>T(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=O(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(),QN(),aP(t.id)}),e.appendChild(r)}}async function aP(e){if(e===(await w()).activeProfileId)return;let t=await D(e);t&&(await iP(),a.debug(`[SidePanel] provider switched:`,t.name))}function oP(){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 sP(){chrome.storage.onChanged.addListener((e,t)=>{t===`local`&&(e.modelProfiles||e.activeProfileId)&&iP()})}var cP=0;function lP(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 uP(e){let t=[];return e.querySelectorAll(`*`).forEach(e=>{getComputedStyle(e).position===`absolute`&&e.getClientRects().length>0&&t.push(e)}),t}function dP(e){e.forEach(e=>{(e.getAnimations?.()||[]).forEach(e=>{e.playState!==`idle`&&e.finish?.()})})}function fP(){cP||=requestAnimationFrame(()=>{cP=0,hP()})}function pP(){let e=document.getElementById(`selectionToggleGroup`),t=document.getElementById(`inputAddMenuSwitches`);e&&t&&e.parentElement!==t&&t.appendChild(e)}function mP(){let e=document.getElementById(`selectionToggleGroup`),t=document.querySelector(`.input-bottom-left`);e&&t&&e.parentElement!==t&&t.appendChild(e)}function hP(){let e=document.querySelector(`.input-bottom-row`),t=e?.closest(`.input-container`)||null;if(!(!e||!t)){t.classList.add(`measuring`);try{gP(e,t)}finally{t.classList.remove(`measuring`)}}}function gP(e,t){t.classList.remove(`temp-collapsed`,`agent-collapsed`,`switches-icon`,`selection-in-menu`),mP();let n=uP(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]}),dP(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`),pP(),i()}function _P(){hP(),window.addEventListener(`resize`,fP);let e=document.querySelector(`.input-bottom-row`);e&&typeof MutationObserver<`u`&&new MutationObserver(t=>{let n=document.getElementById(`selectionToggleGroup`),r=e=>!!n&&[...e.addedNodes,...e.removedNodes].includes(n);t.some(t=>!lP(t.target,e)&&!r(t))&&fP()}).observe(e,{subtree:!0,childList:!0,characterData:!0})}n(`zh`,{fileSelector:{workspaceTitle:`工作目录`,switchHint:`方向键切换 · Enter添加到文件问答 · Esc取消`,searching:`搜索中...`,noMatch:`没有匹配的文件或目录`,noWorkspace:`暂无工作目录,请先连接 Agent`,loadFailed:`加载失败: {error}`,truncated:`仅显示前 {count} 条,请继续输入以缩小范围`}}),n(`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 vP=50,yP=200,bP=200,xP=0,SP=null,CP=[];function wP(e){return(e||``).replace(/\\/g,`/`).replace(/\/+/g,`/`)}function TP(e){let t=document.getElementById(`fileAtTitlePath`);if(!t)return;let n=e?wP(e):``;t.textContent=n,t.title=n}async function EP(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(),DP(),await Kh()})),Et(),t.style.display=`block`,n.classList.add(`show`),await OP(e)}function DP(){let e=document.getElementById(`fileAtSelector`),t=document.getElementById(`fileAtDropdown`);e&&(e.style.display=`none`),t&&t.classList.remove(`show`),N.selectedFileAtIndex=-1,SP&&=(clearTimeout(SP),null),xP++}function OP(e=``){let t=document.getElementById(`fileAtList`);if(!t)return;let n=++xP,i=e.trim();SP&&clearTimeout(SP);let o=async()=>{try{let e=await bn();if(n!==xP)return;if(TP(e),!e){t.innerHTML=`<div class="prompt-empty">${r(`fileSelector.noWorkspace`)}</div>`,N.selectedFileAtIndex=-1;return}let a;if(a=i?await Nn(e,i,yP):((await mn(e)).entries||[]).map(t=>({name:t.name,type:t.type||`file`,size:t.size,mtime:t.mtime,fullPath:wP(`${e}/${t.name}`)})),n!==xP)return;AP(a,i,t,e)}catch(e){if(n!==xP)return;a.warn(`[FileAtSelector] search failed:`,e.message),t.innerHTML=`<div class="prompt-empty">${r(`fileSelector.loadFailed`,{error:e.message})}</div>`,N.selectedFileAtIndex=-1}};i?(t.innerHTML=`<div class="prompt-empty">${r(`fileSelector.searching`)}</div>`,SP=setTimeout(o,bP)):SP=setTimeout(o,0)}function kP(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 AP(e,t,n,i){let a=kP(e,t),o=a.slice(0,vP),s=a.length>vP,c=wP(i);if(o.length===0){n.innerHTML=`<div class="prompt-empty">${r(`fileSelector.noMatch`)}</div>`,N.selectedFileAtIndex=-1;return}if(N.selectedFileAtIndex=0,CP=o,n.innerHTML=o.map((e,t)=>{let n=vn(e.name,e.type),r=wP(e.fullPath),i=r.startsWith(c)?r.substring(c.length).replace(/^\//,``):r;return`
|
|
2528
2528
|
<div class="prompt-item ${t===0?`selected`:``}" data-index="${t}" data-path="${P(r)}" title="${P(r)}">
|
|
2529
2529
|
<span class="prompt-item-index">${t+1}</span>
|
|
2530
2530
|
<span class="prompt-item-icon">${n}</span>
|
|
2531
2531
|
<span class="prompt-item-content">${P(e.name)}</span>
|
|
2532
2532
|
<span class="file-at-path">${P(i)}</span>
|
|
2533
2533
|
</div>
|
|
2534
|
-
`}).join(``),s){let e=document.createElement(`div`);e.className=`file-at-truncated`,e.textContent=r(`fileSelector.truncated`,{count:
|
|
2534
|
+
`}).join(``),s){let e=document.createElement(`div`);e.className=`file-at-truncated`,e.textContent=r(`fileSelector.truncated`,{count:vP}),n.appendChild(e)}n.querySelectorAll(`.prompt-item`).forEach(e=>{e.addEventListener(`click`,()=>{jP(CP.find(t=>t.fullPath===e.dataset.path)||e.dataset.path)})})}function jP(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),DP(),uy([e]),Ht()}function MP(e){let t=N.selectedFileAtIndex;e.forEach((e,n)=>{n===t?(e.classList.add(`selected`),e.scrollIntoView({block:`nearest`})):e.classList.remove(`selected`)})}n(`zh`,{input:{addMenuPanelSearchPlaceholder:`搜索…`,addMenuPanelClear:`清除`,addMenuPanelLoading:`加载中…`,addMenuPanelEmpty:`暂无可用内容`,addMenuPanelNoMatch:`没有匹配项`}}),n(`en`,{input:{addMenuPanelSearchPlaceholder:`Search…`,addMenuPanelClear:`Clear`,addMenuPanelLoading:`Loading…`,addMenuPanelEmpty:`No items available`,addMenuPanelNoMatch:`No matches`}});var NP=null,PP=null,FP=null,IP=null,LP=null,RP=null,zP=null,BP=[],VP=0,HP=()=>{},UP=[{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`}],WP=new Set([`screenshot`]),GP={prompts:{titleKey:`promptManager.title`,action:()=>Pw()},skills:{titleKey:`promptSelector.skillManageTitle`,action:()=>KP(`toolbox`)},mcp:{titleKey:`promptSelector.mcpManageTitle`,action:()=>KP(`toolbox`)},pages:{titleKey:`pageSelector.openNewTab`,action:()=>chrome.tabs.create({})},knowledge:{titleKey:`header.manageKnowledge`,action:()=>KP(`knowledge`)},agents:{titleKey:`header.addEditAssistant`,action:()=>HT(null)},proxies:{titleKey:`header.addEditAgent`,action:()=>KP(`agent`)},workspace:{titleKey:`workspace.openPanel`,action:()=>Kh()}};function KP(e){chrome.runtime.sendMessage({type:`OPEN_OPTIONS_PAGE`,hash:e})}function qP(){if(!LP)return;let e=zP?GP[zP]:null;if(!e){LP.style.display=`none`;return}let t=r(e.titleKey);LP.title=t,LP.setAttribute(`aria-label`,t),LP.style.display=`flex`}function JP(){IP&&(IP.style.display=WP.has(zP)?`none`:``)}function YP(e={}){if(HP=typeof e.onRequestClose==`function`?e.onRequestClose:()=>{},NP=document.getElementById(`inputAddPanel`),PP=document.getElementById(`inputAddPanelSearch`),FP=document.getElementById(`inputAddPanelSearchClear`),LP=document.getElementById(`inputAddPanelManage`),IP=document.getElementById(`inputAddPanelSearchWrap`),RP=document.getElementById(`inputAddPanelList`),!(!NP||!PP||!RP)){if(LP&&LP.addEventListener(`click`,()=>{let e=zP?GP[zP]:null;e&&(HP(),e.action())}),FP){let e=r(`input.addMenuPanelClear`);FP.title=e,FP.setAttribute(`aria-label`,e),FP.addEventListener(`click`,()=>{PP.value=``,aF(),XP(),PP.focus()})}PP.addEventListener(`input`,()=>{aF(),XP()})}}function XP(){FP&&PP&&(FP.style.display=PP.value?`flex`:`none`)}function ZP(){return!!zP}function QP(){return zP}function $P(){return!!PP&&document.activeElement===PP}async function eF(e){if(!NP||!e||zP===e&&NP.style.display!==`none`)return;zP=e,qP(),JP(),PP&&(PP.value=``,PP.placeholder=r(`input.addMenuPanelSearchPlaceholder`),XP()),NP.style.display=`flex`;let t=++VP;RP&&(RP.innerHTML=`<div class="prompt-empty">${r(`input.addMenuPanelLoading`)}</div>`);try{let n=await nF(e);if(t!==VP)return;BP=Array.isArray(n)?n:[],aF()}catch(e){if(t!==VP)return;a.warn(`[InputAddPanel] load failed:`,e&&e.message),BP=[],RP&&(RP.innerHTML=`<div class="prompt-empty">${r(`input.addMenuPanelEmpty`)}</div>`)}}function tF(){zP=null,qP(),JP(),BP=[],VP++,PP&&(PP.value=``,XP()),RP&&(RP.innerHTML=``),NP&&(NP.style.display=`none`)}function nF(e){switch(e){case`prompts`:return Promise.resolve(N.customPrompts||[]);case`skills`:return Zw(!0);case`mcp`:return dT();case`pages`:return qb();case`knowledge`:return Vb().then(e=>e.ok?e.collections:[]);case`agents`:return St();case`proxies`:return cb();case`workspace`:return rF();case`screenshot`:return Promise.resolve(UP);default:return Promise.resolve([])}}async function rF(){let e=await bn();if(!e)return[];let t=await mn(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 iF(e){if(!e)return BP;let t=e.toLowerCase();return BP.filter(e=>{switch(zP){case`prompts`:return String(e.code||``).toLowerCase().includes(t)||String(e.content||``).toLowerCase().includes(t);case`skills`:return String(e.name||``).toLowerCase().includes(t)||String(e.description||``).toLowerCase().includes(t);case`mcp`:return String(e.serverName||``).toLowerCase().includes(t)||String(e.serverId||``).toLowerCase().includes(t);case`pages`:return String(e.title||``).toLowerCase().includes(t)||String(e.url||``).toLowerCase().includes(t);case`knowledge`:return String(e.name||``).toLowerCase().includes(t)||String(e.description||``).toLowerCase().includes(t);case`agents`:return String(_b(e)||``).toLowerCase().includes(t)||String(vb(e)||``).toLowerCase().includes(t);case`proxies`:return String(e.name||``).toLowerCase().includes(t)||String(e.url||``).toLowerCase().includes(t);case`workspace`:return String(e.name||``).toLowerCase().includes(t);case`screenshot`:return r(e.nameKey).toLowerCase().includes(t)||r(e.descKey).toLowerCase().includes(t);default:return!0}})}function aF(){if(!RP)return;let e=PP?PP.value.trim():``,t=iF(e);if(t.length===0){RP.innerHTML=`<div class="prompt-empty">${r(e?`input.addMenuPanelNoMatch`:`input.addMenuPanelEmpty`)}</div>`;return}RP.innerHTML=t.map(e=>oF(e)).join(``),RP.querySelectorAll(`.input-add-panel-item`).forEach(e=>{e.addEventListener(`click`,t=>sF(t,e))}),RP.querySelectorAll(`img.favicon-img`).forEach(e=>{e.addEventListener(`error`,()=>{e.style.display=`none`})}),zP===`proxies`&&t.forEach(e=>Tb(e)),zP===`skills`&&iT(),zP===`mcp`&&vT(),zP===`knowledge`&&Nb()}function oF(e){switch(zP){case`prompts`:return`<div class="prompt-item input-add-panel-item input-add-panel-item-two-line" data-code="${P(e.code)}" title="${I(e.content||``)}">
|
|
2535
2535
|
<span class="input-add-panel-item-title"><span class="input-add-panel-item-inline-icon">${xw}</span>/${P(e.code)}</span>
|
|
2536
2536
|
<span class="input-add-panel-item-sub">${P(e.content||``)}</span>
|
|
2537
2537
|
</div>`;case`skills`:{let t=e.enabled===!1,n=t?`${e.name}\n${r(`skillSelector.disabledTooltip`)}`:e.name,i=e.description||``;return`<div class="skill-list-item input-add-panel-item input-add-panel-item-two-line${t?` skill-list-item-disabled`:``}" data-skill-name="${P(e.name)}" title="${I(n)}">
|
|
@@ -2563,9 +2563,9 @@ Sessions using this assistant will revert to the default assistant.`,deleteAgent
|
|
|
2563
2563
|
<span class="input-add-panel-item-title">${e.icon} ${P(r(e.nameKey))}</span>
|
|
2564
2564
|
<span class="input-add-panel-item-sub">${P(r(e.descKey))}</span>
|
|
2565
2565
|
<kbd class="input-add-panel-item-kbd">${P(e.kbd)}</kbd>
|
|
2566
|
-
</div>`;default:return``}}async function oF(e,t){let n=e.ctrlKey||e.metaKey;switch(RP){case`prompts`:{let e=t.dataset.code;n?Mw(e,{skipTriggerStrip:!0}):Nw(e),VP();break}case`skills`:tT(t.dataset.skillName,zP,{clearTrigger:!1}),n&&VP();break;case`mcp`:mT(t.dataset.serverId,t.dataset.serverName,zP,{clearTrigger:!1}),n&&VP();break;case`pages`:{let e=zP.find(e=>String(e.id)===t.dataset.tabId);if(e){Xb(e);let t=document.getElementById(`userInput`);t&&t.focus(),Vt()}VP();break}case`knowledge`:Pb({id:t.dataset.kbId,name:t.dataset.kbName,enabled:t.dataset.kbDisabled!==`1`},{clearTrigger:!1}),n&&VP();break;case`agents`:await jb(t.dataset.agentId,{clearTrigger:!1}),VP();break;case`proxies`:await Ub(t.dataset.proxyId,{clearTrigger:!1}),VP();break;case`workspace`:{let e=zP.find(e=>e.fullPath===t.dataset.path);if(e){let t=document.getElementById(`userInput`);t&&t.focus(),await uy([e]),Vt()}VP();break}case`screenshot`:VP(),await(t.dataset.shotAction===`region`?$m:Qm)();break;default:break}}var sF=0,cF=200,lF=150,uF={promptTriggerBtn:`prompts`,addMenuSkillBtn:`skills`,addMenuMcpBtn:`mcp`,addMenuPageBtn:`pages`,addMenuKnowledgeBtn:`knowledge`,addMenuAgentBtn:`agents`,addMenuProxyBtn:`proxies`,addMenuWorkspaceBtn:`workspace`,screenshotBtn:`screenshot`};async function dF(){let e=[{id:`addMenuSkillBtn`,available:()=>Yw()},{id:`addMenuMcpBtn`,available:()=>uT()},{id:`addMenuKnowledgeBtn`,available:async()=>(await Vb()).ok},{id:`addMenuProxyBtn`,available:async()=>(await cb()).length>0},{id:`addMenuWorkspaceBtn`,available:async()=>!!await bn()}],t=++sF;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===sF&&(r.style.display=i?``:`none`)}))}function fF(){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=XP()?ZP():null;t.querySelectorAll(`.input-add-item`).forEach(t=>{t.classList.toggle(`panel-active`,!!e&&uF[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?(eF(),s(),dF()):(i&&=(clearTimeout(i),null),a&&=(clearTimeout(a),null),eF(),s())},u=()=>t.style.display!==`none`;JP({onRequestClose:()=>l(!1)}),e.addEventListener(`click`,e=>{e.stopPropagation();let t=!u();t&&(Ew(),fb(),EP()),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,!QP()&&(eF(),s())},lF)};r&&r.addEventListener(`mouseover`,e=>{if(!u())return;let t=e.target.closest(`.input-add-item`),n=t?uF[t.id]:null;if(!n){d();return}a&&=(clearTimeout(a),null),!(XP()&&ZP()===n)&&(i&&clearTimeout(i),i=setTimeout(async()=>{i=null;let e=$P(n);c(t);try{await e}catch{}c(t),s()},cF))}),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`,()=>{XP()&&c()}),[{id:`promptTriggerBtn`,open:()=>Tw(``,`prompts`)},{id:`addMenuSkillBtn`,open:()=>Tw(``,`skills`)},{id:`addMenuMcpBtn`,open:()=>Tw(``,`mcp`)},{id:`addMenuPageBtn`,open:()=>ub(``,`pages`)},{id:`addMenuKnowledgeBtn`,open:()=>ub(``,`knowledge`)},{id:`addMenuAgentBtn`,open:()=>ub(``,`agents`)},{id:`addMenuProxyBtn`,open:()=>ub(``,`proxies`)},{id:`addMenuWorkspaceBtn`,open:()=>TP(``)}].forEach(({id:e,open:t})=>{let n=document.getElementById(e);n&&n.addEventListener(`click`,async e=>{e.stopPropagation(),n.blur(),Ew(),fb(),EP();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 pF=`usageTipsEnabled`,mF=8e3;n(`zh`,{usageTips:{dismiss:`不再显示`,dismissedHint:`已关闭使用技巧提示。想重新看到:设置 → 基础 → 打开「使用技巧提示」`}}),n(`en`,{usageTips:{dismiss:`Don't show again`,dismissedHint:`Tips hidden. To bring them back: Settings → Basic → enable "Usage tips".`}});var hF=[{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:`schedule`,scene:`plugin`,zh:`定时任务可以让 AI 在指定时间自动执行,适合日报、巡检这类重复工作。`,en:`Scheduled tasks let the AI run at set times — handy for daily reports and routine checks.`},{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.`}],gF=null,_F=null,vF=null,yF=null,bF=null,xF=!1,SF=null,CF=!0,wF=null;function TF(){return N.agentPlatform?.connected===!0}function EF(){let e=s();return hF.filter(e=>e.scene!==`agent`||TF()).map(t=>({id:t.id,text:e===`en`?t.en:t.zh}))}function DF(e){let t=e.findIndex(e=>e.id===SF);return t>=0?t:0}function OF(){if(!gF||!_F)return;let e=_F.scrollWidth>_F.clientWidth+1;gF.classList.toggle(`is-truncated`,e)}function kF(e,t){if(!_F||!e.length)return;let n=e[t%e.length];SF=n.id,_F.textContent=n.text,vF&&(vF.textContent=n.text),OF(),_F.classList.remove(`fade-in`),_F.offsetWidth,_F.classList.add(`fade-in`)}function AF(){if(!CF||!gF||gF.style.display===`none`)return;let e=EF();e.length&&kF(e,DF(e)+1)}function jF(){bF&&=(clearInterval(bF),null)}function MF(){jF(),!(!CF||xF)&&(bF=setInterval(AF,mF))}function NF(){if(!CF||!gF)return;let e=EF();if(!e.length){FF();return}e.some(e=>e.id===SF)?kF(e,DF(e)):(SF=null,kF(e,0))}function PF(){if(!gF)return;CF=!0,gF.style.display=``;let e=EF();if(!e.length){FF();return}kF(e,DF(e)),MF()}function FF(){gF&&(gF.style.display=`none`,jF())}function IF(){gF.addEventListener(`mouseenter`,()=>{xF=!0,jF()}),gF.addEventListener(`mouseleave`,()=>{xF=!1,MF()}),yF.addEventListener(`click`,e=>{e.stopPropagation(),LF(),L(r(`usageTips.dismissedHint`),`info`,5e3)}),chrome.storage.onChanged.addListener((e,t)=>{t!==`local`||!e[pF]||(e[pF].newValue===!1?(CF=!1,FF()):PF())}),document.addEventListener(`agent-connection-changed`,NF),c(NF),typeof ResizeObserver<`u`&&new ResizeObserver(OF).observe(gF)}function LF(){CF=!1,FF();try{chrome.storage.local.set({[pF]:!1})}catch{}}function RF(){if(gF=document.getElementById(`usageTipsBar`),_F=document.getElementById(`usageTipsText`),vF=document.getElementById(`usageTipsTooltip`),yF=document.getElementById(`usageTipsDismiss`),!(!gF||!_F||!vF||!yF)){IF(),wF=document.getElementById(`chatContainer`),wF&&(wF.appendChild(gF),typeof MutationObserver<`u`&&new MutationObserver(()=>{(gF.parentNode!==wF||gF.nextElementSibling)&&wF.appendChild(gF)}).observe(wF,{childList:!0}));try{chrome.storage.local.get([pF],e=>{CF=e?.[pF]!==!1,CF?PF():FF()})}catch{PF()}}}function zF({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(`
|
|
2566
|
+
</div>`;default:return``}}async function sF(e,t){let n=e.ctrlKey||e.metaKey;switch(zP){case`prompts`:{let e=t.dataset.code;n?Mw(e,{skipTriggerStrip:!0}):Nw(e),HP();break}case`skills`:tT(t.dataset.skillName,BP,{clearTrigger:!1}),n&&HP();break;case`mcp`:mT(t.dataset.serverId,t.dataset.serverName,BP,{clearTrigger:!1}),n&&HP();break;case`pages`:{let e=BP.find(e=>String(e.id)===t.dataset.tabId);if(e){Xb(e);let t=document.getElementById(`userInput`);t&&t.focus(),Ht()}HP();break}case`knowledge`:Pb({id:t.dataset.kbId,name:t.dataset.kbName,enabled:t.dataset.kbDisabled!==`1`},{clearTrigger:!1}),n&&HP();break;case`agents`:await jb(t.dataset.agentId,{clearTrigger:!1}),HP();break;case`proxies`:await Ub(t.dataset.proxyId,{clearTrigger:!1}),HP();break;case`workspace`:{let e=BP.find(e=>e.fullPath===t.dataset.path);if(e){let t=document.getElementById(`userInput`);t&&t.focus(),await uy([e]),Ht()}HP();break}case`screenshot`:HP(),await(t.dataset.shotAction===`region`?$m:Qm)();break;default:break}}var cF=0,lF=200,uF=150,dF={promptTriggerBtn:`prompts`,addMenuSkillBtn:`skills`,addMenuMcpBtn:`mcp`,addMenuPageBtn:`pages`,addMenuKnowledgeBtn:`knowledge`,addMenuAgentBtn:`agents`,addMenuProxyBtn:`proxies`,addMenuWorkspaceBtn:`workspace`,screenshotBtn:`screenshot`};async function fF(){let e=[{id:`addMenuSkillBtn`,available:()=>Yw()},{id:`addMenuMcpBtn`,available:()=>uT()},{id:`addMenuKnowledgeBtn`,available:async()=>(await Vb()).ok},{id:`addMenuProxyBtn`,available:async()=>(await cb()).length>0},{id:`addMenuWorkspaceBtn`,available:async()=>!!await bn()}],t=++cF;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===cF&&(r.style.display=i?``:`none`)}))}function pF(){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=ZP()?QP():null;t.querySelectorAll(`.input-add-item`).forEach(t=>{t.classList.toggle(`panel-active`,!!e&&dF[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?(tF(),s(),fF()):(i&&=(clearTimeout(i),null),a&&=(clearTimeout(a),null),tF(),s())},u=()=>t.style.display!==`none`;YP({onRequestClose:()=>l(!1)}),e.addEventListener(`click`,e=>{e.stopPropagation();let t=!u();t&&(Ew(),fb(),DP()),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,!$P()&&(tF(),s())},uF)};r&&r.addEventListener(`mouseover`,e=>{if(!u())return;let t=e.target.closest(`.input-add-item`),n=t?dF[t.id]:null;if(!n){d();return}a&&=(clearTimeout(a),null),!(ZP()&&QP()===n)&&(i&&clearTimeout(i),i=setTimeout(async()=>{i=null;let e=eF(n);c(t);try{await e}catch{}c(t),s()},lF))}),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`,()=>{ZP()&&c()}),[{id:`promptTriggerBtn`,open:()=>Tw(``,`prompts`)},{id:`addMenuSkillBtn`,open:()=>Tw(``,`skills`)},{id:`addMenuMcpBtn`,open:()=>Tw(``,`mcp`)},{id:`addMenuPageBtn`,open:()=>ub(``,`pages`)},{id:`addMenuKnowledgeBtn`,open:()=>ub(``,`knowledge`)},{id:`addMenuAgentBtn`,open:()=>ub(``,`agents`)},{id:`addMenuProxyBtn`,open:()=>ub(``,`proxies`)},{id:`addMenuWorkspaceBtn`,open:()=>EP(``)}].forEach(({id:e,open:t})=>{let n=document.getElementById(e);n&&n.addEventListener(`click`,async e=>{e.stopPropagation(),n.blur(),Ew(),fb(),DP();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`,hF=8e3;n(`zh`,{usageTips:{dismiss:`不再显示`,dismissedHint:`已关闭使用技巧提示。想重新看到:设置 → 基础 → 打开「使用技巧提示」`}}),n(`en`,{usageTips:{dismiss:`Don't show again`,dismissedHint:`Tips hidden. To bring them back: Settings → Basic → enable "Usage tips".`}});var gF=[{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:`schedule`,scene:`plugin`,zh:`定时任务可以让 AI 在指定时间自动执行,适合日报、巡检这类重复工作。`,en:`Scheduled tasks let the AI run at set times — handy for daily reports and routine checks.`},{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.`}],_F=null,vF=null,yF=null,bF=null,xF=null,SF=!1,CF=null,wF=!0,TF=null;function EF(){return N.agentPlatform?.connected===!0}function DF(){let e=s();return gF.filter(e=>e.scene!==`agent`||EF()).map(t=>({id:t.id,text:e===`en`?t.en:t.zh}))}function OF(e){let t=e.findIndex(e=>e.id===CF);return t>=0?t:0}function kF(){if(!_F||!vF)return;let e=vF.scrollWidth>vF.clientWidth+1;_F.classList.toggle(`is-truncated`,e)}function AF(e,t){if(!vF||!e.length)return;let n=e[t%e.length];CF=n.id,vF.textContent=n.text,yF&&(yF.textContent=n.text),kF(),vF.classList.remove(`fade-in`),vF.offsetWidth,vF.classList.add(`fade-in`)}function jF(){if(!wF||!_F||_F.style.display===`none`)return;let e=DF();e.length&&AF(e,OF(e)+1)}function MF(){xF&&=(clearInterval(xF),null)}function NF(){MF(),!(!wF||SF)&&(xF=setInterval(jF,hF))}function PF(){if(!wF||!_F)return;let e=DF();if(!e.length){IF();return}e.some(e=>e.id===CF)?AF(e,OF(e)):(CF=null,AF(e,0))}function FF(){if(!_F)return;wF=!0,_F.style.display=``;let e=DF();if(!e.length){IF();return}AF(e,OF(e)),NF()}function IF(){_F&&(_F.style.display=`none`,MF())}function LF(){_F.addEventListener(`mouseenter`,()=>{SF=!0,MF()}),_F.addEventListener(`mouseleave`,()=>{SF=!1,NF()}),bF.addEventListener(`click`,e=>{e.stopPropagation(),RF(),L(r(`usageTips.dismissedHint`),`info`,5e3)}),chrome.storage.onChanged.addListener((e,t)=>{t!==`local`||!e[mF]||(e[mF].newValue===!1?(wF=!1,IF()):FF())}),document.addEventListener(`agent-connection-changed`,PF),c(PF),typeof ResizeObserver<`u`&&new ResizeObserver(kF).observe(_F)}function RF(){wF=!1,IF();try{chrome.storage.local.set({[mF]:!1})}catch{}}function zF(){if(_F=document.getElementById(`usageTipsBar`),vF=document.getElementById(`usageTipsText`),yF=document.getElementById(`usageTipsTooltip`),bF=document.getElementById(`usageTipsDismiss`),!(!_F||!vF||!yF||!bF)){LF(),TF=document.getElementById(`chatContainer`),TF&&(TF.appendChild(_F),typeof MutationObserver<`u`&&new MutationObserver(()=>{(_F.parentNode!==TF||_F.nextElementSibling)&&TF.appendChild(_F)}).observe(TF,{childList:!0}));try{chrome.storage.local.get([mF],e=>{wF=e?.[mF]!==!1,wF?FF():IF()})}catch{FF()}}}function BF({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(`
|
|
2567
2567
|
`,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(`
|
|
2568
|
-
`,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
|
|
2568
|
+
`,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 VF(e,t){let n;return function(...r){clearTimeout(n),n=setTimeout(()=>{clearTimeout(n),e(...r)},t)}}var HF=null,UF=null,WF=null,GF=null,KF=null,qF=null,JF=null,YF=null,XF=null,ZF=null,QF=!1,$F=!1,eI=null,tI={[R.DISPATCHING]:`queue.statusDispatching`,[R.INJECTING]:`queue.statusInjecting`,[R.INJECTED]:`queue.statusInjected`,[R.DONE]:`queue.statusDone`,[R.FAILED]:`queue.statusFailed`};function nI(e){if(e.status===R.QUEUED)return e.interrupted?r(`queue.statusRecovered`):``;let t=tI[e.status];return t?r(t):``}function rI(){return N.activeSessionId}function iI(e){let t=e.attachmentSummary||e.contextSnapshot&&e.contextSnapshot.attachmentSummary||null,n=[];t&&(t.imageCount&&n.push(r(`queue.withImages`,{count:t.imageCount})),t.fileCount&&n.push(r(`queue.withFiles`,{count:t.fileCount})));let i=n.length?n.join(` · `):id(e.contextSnapshot)?r(`queue.withContext`):``;return i?`<span class="queue-chip-ctx" title="${P(t&&(t.fileNames||[]).length?t.fileNames.join(`、`):i)}">${P(i)}</span>`:``}function aI(e,t){let n=iI(e),i=e.status===R.DISPATCHING,a=nI(e),o=(a?`<span class="queue-chip-status${i?` running`:``}${e.interrupted?` warning`:``}"${i?` title="${P(r(`queue.statusRunningHint`))}"`:``}>${P(a)}</span>`:``)+n,s=N.isGenerating===!0;return`
|
|
2569
2569
|
<div class="queue-chip" draggable="true" data-id="${P(e.id)}" data-status="${P(e.status)}">
|
|
2570
2570
|
<span class="queue-chip-index">${t+1}</span>
|
|
2571
2571
|
<div class="queue-chip-main">
|
|
@@ -2577,16 +2577,16 @@ Sessions using this assistant will revert to the default assistant.`,deleteAgent
|
|
|
2577
2577
|
<button class="queue-chip-btn" type="button" data-act="edit" title="${P(r(`queue.editBack`))}">✎</button>
|
|
2578
2578
|
<button class="queue-chip-btn danger" type="button" data-act="remove" title="${P(r(`queue.delete`))}">✕</button>
|
|
2579
2579
|
</div>
|
|
2580
|
-
</div>`}function
|
|
2580
|
+
</div>`}function oI(e){return e.length?e.map(e=>`
|
|
2581
2581
|
<div class="queue-recent-item" data-id="${P(e.id)}">
|
|
2582
|
-
<span class="queue-recent-status">${P(
|
|
2582
|
+
<span class="queue-recent-status">${P(nI(e))}</span>
|
|
2583
2583
|
<span class="queue-recent-text" title="${P(e.text)}">${P(e.text)}</span>
|
|
2584
2584
|
<button class="queue-chip-btn" type="button" data-act="requeue" title="${P(r(`queue.requeue`))}">↺</button>
|
|
2585
2585
|
<button class="queue-chip-btn danger" type="button" data-act="forget" title="${P(r(`queue.forgetRecent`))}">✕</button>
|
|
2586
|
-
</div>`).join(``):`<div class="queue-recent-empty">${P(r(`queue.recentEmpty`))}</div>`}function
|
|
2586
|
+
</div>`).join(``):`<div class="queue-recent-empty">${P(r(`queue.recentEmpty`))}</div>`}function sI(e={}){if(!HF||eI)return;let t=rI();if(!t){HF.style.display=`none`;return}let n=Gr(t),i=n.items,a=i.length>0,o=n.recent.filter(e=>e.status===R.FAILED).length,s=o>0;if(!a&&!s&&(!$F||n.recent.length===0)){HF.style.display=`none`;return}if(HF.style.display=``,HF.classList.toggle(`empty`,!a),HF.classList.toggle(`expanded`,QF&&a),HF.classList.toggle(`paused`,n.paused),WF&&(a?(WF.textContent=r(`queue.summary`,{count:i.length}),WF.classList.remove(`failed`),WF.removeAttribute(`title`)):s?(WF.textContent=r(`queue.summaryFailed`,{count:o}),WF.classList.add(`failed`),WF.title=r(`queue.summaryFailedHint`)):(WF.textContent=r(`queue.summaryEmpty`),WF.classList.remove(`failed`),WF.removeAttribute(`title`))),GF&&(GF.style.display=n.paused?``:`none`,GF.title=n.pausedReason===`user_stopped`?r(`queue.pausedByStop`):r(`queue.pausedHint`)),KF){let e=n.paused&&i.length>0;KF.style.display=e?``:`none`,KF.textContent=r(`queue.resumeQueue`)}if(qF){let e=N.isGenerating===!0&&a&&!n.paused;qF.style.display=e?``:`none`}JF&&(JF.classList.toggle(`active`,$F),JF.title=r(`queue.recentTitle`)),XF&&(XF.style.display=a?``:`none`,XF.setAttribute(`aria-expanded`,QF?`true`:`false`),XF.textContent=QF?`▲`:`▼`),UF&&(UF.style.display=QF&&a?``:`none`,UF.innerHTML=a?i.map((e,t)=>aI(e,t)).join(``):``),YF&&(YF.style.display=$F?``:`none`,YF.innerHTML=$F?oI(n.recent):``),e.flash&&(HF.classList.remove(`queue-flash`),HF.offsetWidth,HF.classList.add(`queue-flash`))}async function cI(e,t={}){let n=rI();if(!n||!e)return!1;let i=Yr(n,e);if(!i)return!1;let a=document.getElementById(`userInput`);if(a&&a.value.trim()){let e=await md({autoDrain:!1});if(!e.ok)return L(e.error===`queue_full`?r(`queue.queueFull`,{limit:e.limit}):r(`queue.enqueueFailed`),`warning`),!1}else if(ad())return L(r(`queue.inputHasUnsavedContext`),`warning`,4e3),!1;let o=await fd(i);return a&&(a.value=i.text,a.style.height=`auto`,a.dispatchEvent(new Event(`input`)),a.focus()),await $r(n,e),await pd(e),o.wantsAttachments?L(o.attachments?r(`queue.editBackWithAttachments`):r(`queue.attachmentsMissing`),o.attachments?`success`:`warning`,2500):t.viaShortcut&&L(r(`queue.editTailHint`),`info`,2e3),!0}function lI(){let e=rI();if(!e)return!1;let t=Jr(e);return t?(cI(t.id,{viaShortcut:!0}),!0):!1}async function uI(e,t){let n=rI();if(!(!n||!t)&&!(Ur(n).findIndex(e=>e.id===t)<0))switch(e){case`edit`:await cI(t);break;case`inject`:await Md(t,n);break;case`remove`:await $r(n,t),await pd(t),L(r(`queue.deleted`),`info`,1500);break;default:break}}async function dI(e){let t=rI();t&&await ei(t,e)}async function fI(e,t){if(e.preventDefault(),!eI)return;let n=t?.dataset?.id;if(!n||n===eI)return;let r=rI();if(!r)return;let i=Ur(r).map(e=>e.id),a=i.indexOf(eI);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,eI),await dI(i)}function pI(){UF&&(UF.addEventListener(`dragstart`,e=>{let t=e.target.closest?.(`.queue-chip`);if(t){eI=t.dataset.id,t.classList.add(`dragging`);try{e.dataTransfer.effectAllowed=`move`,e.dataTransfer.setData(`text/plain`,eI)}catch{}}}),UF.addEventListener(`dragend`,e=>{let t=e.target.closest?.(`.queue-chip`);t&&t.classList.remove(`dragging`),eI=null,UF.querySelectorAll(`.drag-over-top, .drag-over-bottom`).forEach(e=>{e.classList.remove(`drag-over-top`,`drag-over-bottom`)}),sI()}),UF.addEventListener(`dragover`,e=>{let t=e.target.closest?.(`.queue-chip`);if(!t||!eI||t.dataset.id===eI)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)}),UF.addEventListener(`dragleave`,e=>{let t=e.target.closest?.(`.queue-chip`);t&&t.classList.remove(`drag-over-top`,`drag-over-bottom`)}),UF.addEventListener(`drop`,e=>{let t=e.target.closest?.(`.queue-chip`);fI(e,t)}))}function mI(){UF?.addEventListener(`click`,e=>{let t=e.target.closest?.(`.queue-chip-btn`);if(!t||t.disabled)return;let n=t.closest(`.queue-chip`);n&&uI(t.dataset.act,n.dataset.id)}),YF?.addEventListener(`click`,async e=>{let t=e.target.closest?.(`.queue-chip-btn`),n=t?.closest(`.queue-recent-item`),i=rI();if(!t||!n||!i)return;if(t.dataset.act===`forget`){await oi(i,n.dataset.id)&&L(r(`queue.forgotRecent`),`success`,1500);return}if(t.dataset.act!==`requeue`)return;let a=Wr(i).find(e=>e.id===n.dataset.id),o=!!(a&&a.attachmentSummary),s=await ai(i,n.dataset.id);if(!s.ok){L(s.error===`queue_full`?r(`queue.queueFull`,{limit:s.limit}):r(`queue.enqueueFailed`),`warning`);return}L(r(o?`queue.requeuedNoAttachments`:`queue.requeued`),o?`warning`:`success`,2500)}),XF?.addEventListener(`click`,()=>{QF=!QF,sI()}),ZF?.addEventListener(`click`,e=>{e.target.closest?.(`button`)||Ur(rI()||``).length&&(QF=!QF,sI())}),JF?.addEventListener(`click`,()=>{$F=!$F,$F&&(QF=!0),sI()}),KF?.addEventListener(`click`,async()=>{await Yd(),L(r(`queue.resumed`),`success`,1500)}),qF?.addEventListener(`click`,()=>{document.dispatchEvent(new CustomEvent(`queue-stop-and-send`))}),pI(),Hr(()=>sI()),document.addEventListener(`queue-enqueued`,()=>{QF=!0,sI({flash:!0})}),document.addEventListener(`session-switched`,()=>{sI()}),document.addEventListener(`generation-ended`,()=>sI()),document.addEventListener(`generating-state-changed`,()=>sI())}async function hI(){await Br(),sI()}async function gI(){if(await Br(),HF=document.getElementById(`queueStrip`),!HF){a.warn(`[QueuePanel] #queueStrip not found, queue UI disabled`);return}UF=document.getElementById(`queueList`),WF=document.getElementById(`queueSummary`),GF=document.getElementById(`queuePausedTag`),KF=document.getElementById(`queueResumeBtn`),qF=document.getElementById(`queueStopSendBtn`),JF=document.getElementById(`queueRecentBtn`),YF=document.getElementById(`queueRecent`),XF=document.getElementById(`queueToggleBtn`),ZF=HF.querySelector(`.queue-strip-head`),mI(),sI()}var _I=new Set,vI=new Set,yI=new Map,bI=30*1e3;function xI(e){let t=yI.get(e);return t?Date.now()-t<bI?!0:(yI.delete(e),!1):!1}async function SI(e){let t=me(e)||e;if(!t||_I.has(t)||vI.has(t)||xI(t))return null;vI.add(t);try{let e=await te();if(!e)return null;let n=null;try{let r=await be(`${e.url}/api/status/detail`,{headers:{Authorization:`Bearer ${e.token}`,"X-AIH-Session-Id":t}});if(!r.ok)return yI.set(t,Date.now()),null;n=await r.json()}catch(e){return a.debug(`[WorkdirReconcile] fetch detail failed:`,e?.message||e),yI.set(t,Date.now()),null}if(!n?.success||!n.sessionWorkdirSupported)return yI.set(t,Date.now()),null;let r=n.sessionWorkdir||null,i=n.defaultWorkdir||n.workdir||null;if(!r||r===i)return yI.set(t,Date.now()),null;let o=await fe(t);return o.scope===`session`?(yI.set(t,Date.now()),null):o.boundWorkdir?await ge(t)?(_I.add(t),a.debug(`[WorkdirReconcile] cleared stale agent binding:`,t,r),{cleaned:!0,workdir:r}):null:await Te(t,r,o.agentId||e.id||null)?(_I.add(t),a.debug(`[WorkdirReconcile] restored session workdir:`,t,r),{adopted:!0,workdir:r}):null}finally{vI.delete(t)}}n(`zh`,{sidePanel:{popupTitle:`浮层解答`,popupTooltip:`浮层解答(不进入对话)`,popupLoading:`思考中...`,popupCopy:`复制`,popupCopied:`已复制到剪贴板`,popupTransfer:`转入对话`,popupTransferred:`已转入对话`,popupRegenerate:`重新生成`,popupClose:`关闭`,popupLock:`锁定(不随点击外部关闭)`,popupUnlock:`解锁(可点击外部关闭)`,popupRequestFailed:`请求失败`,popupContextLabel:`上下文`,popupContextTruncated:`(已截断)`,popupSystemPrompt:`用户在阅读 AI 回答时选中了其中的片段,希望理解选中内容。请结合上下文,只针对选中片段回答,简洁清楚,不要展开与选中内容无关的长论述。`}}),n(`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 CI=1500,$=null,wI=null,TI=``,EI=null,DI=``,OI=``,kI=!1,AI=!1,jI=!1;function MI(e){return(e||``).replace(/[ \t\f\v]+/g,` `).replace(/ *\n */g,`
|
|
2587
2587
|
`).replace(/\n{3,}/g,`
|
|
2588
2588
|
|
|
2589
|
-
`).trim()}function
|
|
2589
|
+
`).trim()}function NI(e,t){if(!e)return{context:``,truncated:!1};let n=e.startContainer?.parentElement?.closest?.(`.message`);if(!n)return{context:``,truncated:!1};let r=MI(n.textContent);if(!r)return{context:``,truncated:!1};let i=f(r);if(i<=CI)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*CI/Math.max(i,1)),c=Math.max(0,Math.floor(o-s/2)),l=Math.min(r.length,c+s);if(a>=0){let e=a+t.length;a<c&&(c=Math.max(0,a-50)),e>l&&(l=Math.min(r.length,e+50))}let u=r.slice(c,l).trim();if(f(u)>CI){let e=CI/f(u);u=u.slice(0,Math.floor(u.length*e))}return{context:u,truncated:!0}}function PI(e,t,n,i){let a=r(`sidePanel.popupSystemPrompt`),o=``;return t&&(o+=`[${r(`sidePanel.popupContextLabel`)}${i?r(`sidePanel.popupContextTruncated`):``}]\n${t}\n\n`),o+=`[${r(`sidePanel.selectedContentLabel`)}]\n${e}\n\n`,o+=`[${r(`sidePanel.userQuestionLabel`)}]\n${n}`,[{role:`system`,content:a},{role:`user`,content:o}]}function FI(){return $&&document.body.contains($)?$:($=document.createElement(`div`),$.className=`selection-answer-popup`,$.id=`selectionAnswerPopup`,$.innerHTML=`
|
|
2590
2590
|
<div class="sap-header">
|
|
2591
2591
|
<span class="sap-title"></span>
|
|
2592
2592
|
<div class="sap-header-actions">
|
|
@@ -2600,7 +2600,7 @@ Sessions using this assistant will revert to the default assistant.`,deleteAgent
|
|
|
2600
2600
|
<button class="sap-btn sap-transfer"></button>
|
|
2601
2601
|
<button class="sap-btn sap-regen"></button>
|
|
2602
2602
|
</div>
|
|
2603
|
-
`,document.body.appendChild($),$.querySelector(`.sap-close`).addEventListener(`click`,UI),$.querySelector(`.sap-lock`).addEventListener(`click`,LI),$.querySelector(`.sap-copy`).addEventListener(`click`,qI),$.querySelector(`.sap-transfer`).addEventListener(`click`,JI),$.querySelector(`.sap-regen`).addEventListener(`click`,()=>{TI&&EI&&XI()}),KI($.querySelector(`.sap-header`)),$)}function FI(){if(!$)return;$.querySelector(`.sap-close`).title=r(`sidePanel.popupClose`);let e=$.querySelector(`.sap-copy`);e.textContent=r(`sidePanel.popupCopy`),e.title=r(`sidePanel.popupCopy`);let t=$.querySelector(`.sap-transfer`);t.textContent=r(`sidePanel.popupTransfer`),t.title=r(`sidePanel.popupTransfer`);let n=$.querySelector(`.sap-regen`);n.textContent=r(`sidePanel.popupRegenerate`),n.title=r(`sidePanel.popupRegenerate`),II()}function II(){if(!$)return;let e=$.querySelector(`.sap-lock`);e&&(e.classList.toggle(`locked`,AI),e.title=r(AI?`sidePanel.popupUnlock`:`sidePanel.popupLock`),e.innerHTML=AI?`<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 LI(){AI=!AI,II()}function RI(e,t){let n=PI(),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 zI(e){let t=PI();FI(),t.querySelector(`.sap-title`).textContent=e||r(`sidePanel.popupTitle`),t.querySelector(`.sap-body`).innerHTML=`<div class="sap-loading">${P(r(`sidePanel.popupLoading`))}</div>`,t.classList.add(`show`),$.style.display=`block`}function BI(){return!!$&&$.classList.contains(`show`)}function VI(e,t=!0){let n=$?.querySelector(`.sap-body`);n&&(n.innerHTML=`<div class="sap-content markdown-body">${e}</div>`,t&&(n.scrollTop=n.scrollHeight))}function HI(e){let t=$?.querySelector(`.sap-body`);t&&(t.innerHTML=`<div class="sap-error">${P(e)}</div>`)}function UI(){kI&&CI&&chrome.runtime.sendMessage({type:`CANCEL_REACT`,sessionId:CI}).catch(()=>{}),$&&($.classList.remove(`show`),$.style.display=`none`),CI=null,wI=``,kI=!1,AI=!1}function WI(e){if(!BI()||AI||$.contains(e.target))return;let t=document.getElementById(`selectionFloatingMenu`);t&&t.contains(e.target)||UI()}function GI(e){e.key===`Escape`&&(!BI()||AI||UI())}function KI(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=$.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;$.style.position=`fixed`,$.style.top=i+s+`px`,$.style.left=a+o+`px`}),document.addEventListener(`mouseup`,()=>{t=!1})}function qI(){wI&&navigator.clipboard.writeText(wI).then(()=>{L(r(`sidePanel.popupCopied`))}).catch(()=>{let e=document.createElement(`textarea`);e.value=wI,document.body.appendChild(e),e.select(),document.execCommand(`copy`),document.body.removeChild(e),L(r(`sidePanel.popupCopied`))})}function JI(){if(!wI||!TI)return;let e=wI,t=TI.content,n=`${DI?`[${r(`sidePanel.popupContextLabel`)}]\n${DI}\n\n`:``}[${r(`sidePanel.selectedContentLabel`)}]\n${EI}\n\n[${r(`sidePanel.userQuestionLabel`)}]\n${TI.content}`;M(async()=>{let{addMessage:e}=await Promise.resolve().then(()=>hC);return{addMessage:e}},void 0).then(({addMessage:i})=>{i(`user`,t,!0,[],null,!1,n),N.messageHistory.push({role:`user`,content:n,timestamp:new Date().toISOString()}),i(`assistant`,e,!0),N.messageHistory.push({role:`assistant`,content:e}),M(async()=>{let{saveCurrentSession:e}=await Promise.resolve().then(()=>ki);return{saveCurrentSession:e}},void 0).then(({saveCurrentSession:e})=>{e()}),Promise.all([M(()=>Promise.resolve().then(()=>hS),void 0),new Promise(e=>requestAnimationFrame(e))]).then(([{autoScrollToBottom:e}])=>{e(document.getElementById(`chatContainer`),{force:!0,smooth:!0}),L(r(`sidePanel.popupTransferred`))})}),UI()}function YI(e,t,n){let{context:r,truncated:i}=MI(n,t);TI=e,EI=t,DI=r,OI=i,XI()}function XI(){wI=``,kI=!0,zI(TI?.content);let e=NI(EI,DI,TI.content,OI);CI=`popup_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,chrome.runtime.sendMessage({type:`SIDEPANEL_POPUP_ASK`,sessionId:CI,messages:e}).catch(e=>{a.error(`[SelectionPopup] sendMessage failed:`,e),HI(r(`sidePanel.popupRequestFailed`)),kI=!1})}var ZI=!1;function QI(){ZI||(ZI=!0,chrome.runtime.onMessage.addListener(e=>{if(!(!e||!e.type)&&e.type.startsWith(`SIDEPANEL_POPUP_`)&&e.sessionId===CI){if(e.type===`SIDEPANEL_POPUP_STREAM_CHUNK`)e.delta&&(wI+=e.delta,VI(qt(wI)));else if(e.type===`SIDEPANEL_POPUP_STREAM_DONE`)kI=!1,e.finalContent&&(wI=e.finalContent),VI(qt(wI));else if(e.type===`SIDEPANEL_POPUP_STREAM_ERROR`){if(!kI)return;kI=!1,HI(e.error||r(`sidePanel.popupRequestFailed`))}}}))}function $I(){QI(),document.addEventListener(`mousedown`,WI),document.addEventListener(`keydown`,GI)}function eL(e,t,n,r,i){!t||!e||(QI(),RI(n,r),AI=!1,YI(e,t,i||N.currentSelectionRange))}n(`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 调用`}}),n(`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 tL(e,t){let n=document.getElementById(`tokenStatsOverlay`),i=document.getElementById(`tokenStatsClose`),o=document.getElementById(`tokenStatsRefreshBtn`),s=document.getElementById(`tokenStatsClearBtn`),c=document.getElementById(`tokenStatsTabNav`),l=document.getElementById(`tokenStatsTopCards`);if(!n)return;let u=`trend`,d=`month`;function f(){n.style.display=`flex`,h()}function p(){n.style.display=`none`}if(window.openTokenStats=f,i&&i.addEventListener(`click`,p),n&&n.addEventListener(`click`,e=>{e.target===n&&p()}),o&&o.addEventListener(`click`,h),s&&s.addEventListener(`click`,async()=>{await t(r(`tokenStats.clearConfirmMessage`),r(`toolStats.clearTitle`))&&(await ze(),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)`,w())})});async function h(){let t=e(),n=document.getElementById(`tokenStatsLoading`),i=document.getElementById(`tokenStatsEmpty`),o=document.getElementById(`tokenStatsContent`);n&&(n.style.display=``),i&&(i.style.display=`none`),o&&(o.style.display=`none`),c&&(c.style.display=`none`),l&&(l.style.display=`none`);try{let[e,r]=await Promise.all([qe(t),Ae()]);if(n&&(n.style.display=`none`),!(r&&r.totalApiCalls>0)){i&&(i.style.display=``);return}o&&(o.style.display=``),c&&(c.style.display=`flex`),l&&(l.style.display=``),g(e),_(e),E(e.records||[]),x(r),w()}catch(e){a.error(`[TokenStats] load stats failed:`,e),n&&(n.style.display=`none`),i&&(i.textContent=r(`tokenStats.loadFailed`),i.style.display=``)}}function g(e){if(!l)return;if(!e||e.apiCallCount===0){l.innerHTML=``;return}let t=e.maxContextUsageRate||0,n=O(t);l.innerHTML=`
|
|
2603
|
+
`,document.body.appendChild($),$.querySelector(`.sap-close`).addEventListener(`click`,WI),$.querySelector(`.sap-lock`).addEventListener(`click`,RI),$.querySelector(`.sap-copy`).addEventListener(`click`,JI),$.querySelector(`.sap-transfer`).addEventListener(`click`,YI),$.querySelector(`.sap-regen`).addEventListener(`click`,()=>{EI&&DI&&ZI()}),qI($.querySelector(`.sap-header`)),$)}function II(){if(!$)return;$.querySelector(`.sap-close`).title=r(`sidePanel.popupClose`);let e=$.querySelector(`.sap-copy`);e.textContent=r(`sidePanel.popupCopy`),e.title=r(`sidePanel.popupCopy`);let t=$.querySelector(`.sap-transfer`);t.textContent=r(`sidePanel.popupTransfer`),t.title=r(`sidePanel.popupTransfer`);let n=$.querySelector(`.sap-regen`);n.textContent=r(`sidePanel.popupRegenerate`),n.title=r(`sidePanel.popupRegenerate`),LI()}function LI(){if(!$)return;let e=$.querySelector(`.sap-lock`);e&&(e.classList.toggle(`locked`,jI),e.title=r(jI?`sidePanel.popupUnlock`:`sidePanel.popupLock`),e.innerHTML=jI?`<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 RI(){jI=!jI,LI()}function zI(e,t){let n=FI(),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 BI(e){let t=FI();II(),t.querySelector(`.sap-title`).textContent=e||r(`sidePanel.popupTitle`),t.querySelector(`.sap-body`).innerHTML=`<div class="sap-loading">${P(r(`sidePanel.popupLoading`))}</div>`,t.classList.add(`show`),$.style.display=`block`}function VI(){return!!$&&$.classList.contains(`show`)}function HI(e,t=!0){let n=$?.querySelector(`.sap-body`);n&&(n.innerHTML=`<div class="sap-content markdown-body">${e}</div>`,t&&(n.scrollTop=n.scrollHeight))}function UI(e){let t=$?.querySelector(`.sap-body`);t&&(t.innerHTML=`<div class="sap-error">${P(e)}</div>`)}function WI(){AI&&wI&&chrome.runtime.sendMessage({type:`CANCEL_REACT`,sessionId:wI}).catch(()=>{}),$&&($.classList.remove(`show`),$.style.display=`none`),wI=null,TI=``,AI=!1,jI=!1}function GI(e){if(!VI()||jI||$.contains(e.target))return;let t=document.getElementById(`selectionFloatingMenu`);t&&t.contains(e.target)||WI()}function KI(e){e.key===`Escape`&&(!VI()||jI||WI())}function qI(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=$.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;$.style.position=`fixed`,$.style.top=i+s+`px`,$.style.left=a+o+`px`}),document.addEventListener(`mouseup`,()=>{t=!1})}function JI(){TI&&navigator.clipboard.writeText(TI).then(()=>{L(r(`sidePanel.popupCopied`))}).catch(()=>{let e=document.createElement(`textarea`);e.value=TI,document.body.appendChild(e),e.select(),document.execCommand(`copy`),document.body.removeChild(e),L(r(`sidePanel.popupCopied`))})}function YI(){if(!TI||!EI)return;mx()&&bx();let e=TI,t=EI.content,n=`${OI?`[${r(`sidePanel.popupContextLabel`)}]\n${OI}\n\n`:``}[${r(`sidePanel.selectedContentLabel`)}]\n${DI}\n\n[${r(`sidePanel.userQuestionLabel`)}]\n${EI.content}`;M(async()=>{let{addMessage:e}=await Promise.resolve().then(()=>hC);return{addMessage:e}},void 0).then(({addMessage:i})=>{i(`user`,t,!0,[],null,!1,n),N.messageHistory.push({role:`user`,content:n,timestamp:new Date().toISOString()}),i(`assistant`,e,!0),N.messageHistory.push({role:`assistant`,content:e}),M(async()=>{let{saveCurrentSession:e}=await Promise.resolve().then(()=>ki);return{saveCurrentSession:e}},void 0).then(({saveCurrentSession:e})=>{e()}),Promise.all([M(()=>Promise.resolve().then(()=>hS),void 0),new Promise(e=>requestAnimationFrame(e))]).then(([{autoScrollToBottom:e}])=>{e(document.getElementById(`chatContainer`),{force:!0,smooth:!0}),L(r(`sidePanel.popupTransferred`))})}),WI()}function XI(e,t,n){let{context:r,truncated:i}=NI(n,t);EI=e,DI=t,OI=r,kI=i,ZI()}function ZI(){TI=``,AI=!0,BI(EI?.content);let e=PI(DI,OI,EI.content,kI);wI=`popup_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,chrome.runtime.sendMessage({type:`SIDEPANEL_POPUP_ASK`,sessionId:wI,messages:e}).catch(e=>{a.error(`[SelectionPopup] sendMessage failed:`,e),UI(r(`sidePanel.popupRequestFailed`)),AI=!1})}var QI=!1;function $I(){QI||(QI=!0,chrome.runtime.onMessage.addListener(e=>{if(!(!e||!e.type)&&e.type.startsWith(`SIDEPANEL_POPUP_`)&&e.sessionId===wI){if(e.type===`SIDEPANEL_POPUP_STREAM_CHUNK`)e.delta&&(TI+=e.delta,HI(Jt(TI)));else if(e.type===`SIDEPANEL_POPUP_STREAM_DONE`)AI=!1,e.finalContent&&(TI=e.finalContent),HI(Jt(TI));else if(e.type===`SIDEPANEL_POPUP_STREAM_ERROR`){if(!AI)return;AI=!1,UI(e.error||r(`sidePanel.popupRequestFailed`))}}}))}function eL(){$I(),document.addEventListener(`mousedown`,GI),document.addEventListener(`keydown`,KI)}function tL(e,t,n,r,i){!t||!e||($I(),zI(n,r),jI=!1,XI(e,t,i||N.currentSelectionRange))}n(`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 调用`}}),n(`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 nL(e,t){let n=document.getElementById(`tokenStatsOverlay`),i=document.getElementById(`tokenStatsClose`),o=document.getElementById(`tokenStatsRefreshBtn`),s=document.getElementById(`tokenStatsClearBtn`),c=document.getElementById(`tokenStatsTabNav`),l=document.getElementById(`tokenStatsTopCards`);if(!n)return;let u=`trend`,d=`month`;function f(){n.style.display=`flex`,h()}function p(){n.style.display=`none`}if(window.openTokenStats=f,i&&i.addEventListener(`click`,p),n&&n.addEventListener(`click`,e=>{e.target===n&&p()}),o&&o.addEventListener(`click`,h),s&&s.addEventListener(`click`,async()=>{await t(r(`tokenStats.clearConfirmMessage`),r(`toolStats.clearTitle`))&&(await ze(),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)`,w())})});async function h(){let t=e(),n=document.getElementById(`tokenStatsLoading`),i=document.getElementById(`tokenStatsEmpty`),o=document.getElementById(`tokenStatsContent`);n&&(n.style.display=``),i&&(i.style.display=`none`),o&&(o.style.display=`none`),c&&(c.style.display=`none`),l&&(l.style.display=`none`);try{let[e,r]=await Promise.all([qe(t),Ae()]);if(n&&(n.style.display=`none`),!(r&&r.totalApiCalls>0)){i&&(i.style.display=``);return}o&&(o.style.display=``),c&&(c.style.display=`flex`),l&&(l.style.display=``),g(e),_(e),E(e.records||[]),x(r),w()}catch(e){a.error(`[TokenStats] load stats failed:`,e),n&&(n.style.display=`none`),i&&(i.textContent=r(`tokenStats.loadFailed`),i.style.display=``)}}function g(e){if(!l)return;if(!e||e.apiCallCount===0){l.innerHTML=``;return}let t=e.maxContextUsageRate||0,n=O(t);l.innerHTML=`
|
|
2604
2604
|
<div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 8px;">
|
|
2605
2605
|
<div style="background: var(--brand-soft-bg); border-radius: 8px; padding: 10px; text-align: center;">
|
|
2606
2606
|
<div style="font-size: 10px; color: var(--text-tertiary); margin-bottom: 4px;">${r(`tokenStats.topCardSessionTokens`)}</div>
|
|
@@ -2711,7 +2711,7 @@ Sessions using this assistant will revert to the default assistant.`,deleteAgent
|
|
|
2711
2711
|
<span style="background:var(--bg-subtle);padding:1px 5px;border-radius:3px;font-size:9px;color:var(--text-secondary);">${P(i)}</span>
|
|
2712
2712
|
<span style="font-weight:500;color:var(--text-primary);margin-left:auto;">${D(e.totalTokens)}</span>
|
|
2713
2713
|
<span style="color:${o};font-size:9px;font-weight:500;width:35px;text-align:right;">${((e.contextUsageRate||0)*100).toFixed(1)}%</span>
|
|
2714
|
-
</div>`}).join(``)}function D(e){return e>=1e6?(e/1e6).toFixed(1)+`M`:e>=1e3?(e/1e3).toFixed(1)+`K`:String(e)}function O(e){return e>=.8?`#ef4444`:e>=.5?`#f59e0b`:`#10b981`}}function
|
|
2714
|
+
</div>`}).join(``)}function D(e){return e>=1e6?(e/1e6).toFixed(1)+`M`:e>=1e3?(e/1e3).toFixed(1)+`K`:String(e)}function O(e){return e>=.8?`#ef4444`:e>=.5?`#f59e0b`:`#10b981`}}function rL(e){return(e||[]).map(e=>e.token?{...e,token:S(e.token)}:e)}n(`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}
|
|
2715
2715
|
代理地址:{url}
|
|
2716
2716
|
|
|
2717
2717
|
确定要重启代理服务吗?重启期间服务将短暂不可用。`,restartAgentTitle:`重启代理`,agentRestarting:`代理服务正在重启...`,restartFailed:`重启失败: {error}`,restartRequestFailed:`重启请求失败: {error}`,updateAgentConfirm:`代理名称:{name}
|
|
@@ -2720,7 +2720,7 @@ Sessions using this assistant will revert to the default assistant.`,deleteAgent
|
|
|
2720
2720
|
确定要更新代理吗?将通过 npm 安装最新版本,然后重启服务。更新期间服务不可用。`,updateAgentTitle:`更新代理`,agentUpdating:`正在更新代理(可能需要几分钟)...`,agentUpdateRestarting:`代理正在更新并重启...`,updateFailed:`更新失败: {error}`,updateRequestFailed:`更新请求失败: {error}`,stopAgentConfirm:`代理名称:{name}
|
|
2721
2721
|
代理地址:{url}
|
|
2722
2722
|
|
|
2723
|
-
确定要停止代理服务吗?停止后将无法连接,需要手动重新启动。`,stopAgentTitle:`停止代理`,agentStopped:`代理服务已停止,代理已离线`,stopFailed:`停止失败: {error}`,stopRequestFailed:`停止请求失败: {error}`,agentStatusRefreshed:`代理状态已刷新`,deleteAgentTitle:`删除代理`,deleteAgentConfirm:`确定要删除代理"{name}"吗?此操作不可恢复。`,welcomeTitle:`开始对话`,welcomeSubtitle:`输入您的问题,AI 助手将为您解答`,sendBtnStop:`停止生成`,sendBtnSend:`发送`,imageNotEnabled:`未启用图片识别,图片已作为文件附件处理`,screenshotFailed:`截图失败,请重试`,auditCategoryAuth:`认证`,auditCategoryFs:`文件`,auditCategoryExec:`命令`,auditCategorySecurity:`安全`,auditCategorySystem:`系统`,auditDetailSeparator:`;`,auditQueryFailed:`查询失败: {error}`,auditLoadFailed:`加载失败: {error}`,auditNoMatch:`没有匹配的审计日志`,auditEmpty:`暂无审计日志`,clearStatsConfirm:`确定要清空所有工具使用统计吗?此操作不可撤销。`,clearStatsTitle:`清空统计`,toolStatsSummary:`已使用 {used} 个,未使用 {unused} 个`,toolStatsLoadFailed:`加载失败`,toolNameDescSeparator:`:`}}),n(`en`,{sidePanel:{confirmAction:`Confirm Action`,memoryLimitAll:`All`,memoryLimitTitle:`Click to set memory history limit`,configUpdated:`✅ Configuration updated`,selectedPrefix:`📌 Selected`,askBasedOnSelection:`Ask based on selection`,selectedContentLabel:`Selected content`,selectedContentSummary:`summary`,userQuestionLabel:`User question`,requestFailed:`❌ Request failed: `,unknownError:`Unknown error`,notConnected:`Not Connected`,noPairedAgents:`No paired agents`,agentDisabled:`Disabled`,agentConnected:`Connected`,agentChecking:`Checking...`,agentOnline:`Online`,agentOffline:`Offline`,enableAgent:`Enable`,disableAgent:`Disable`,disconnectAgent:`Disconnect`,connectAgent:`Connect`,deleteAgentBtn:`Delete`,workingDirectory:`Working directory: {path}`,agentAddressCopied:`Agent address copied`,unknownAgent:`Unknown`,restartAgentConfirm:`Agent name: {name}
|
|
2723
|
+
确定要停止代理服务吗?停止后将无法连接,需要手动重新启动。`,stopAgentTitle:`停止代理`,agentStopped:`代理服务已停止,代理已离线`,stopFailed:`停止失败: {error}`,stopRequestFailed:`停止请求失败: {error}`,agentStatusRefreshed:`代理状态已刷新`,deleteAgentTitle:`删除代理`,deleteAgentConfirm:`确定要删除代理"{name}"吗?此操作不可恢复。`,welcomeTitle:`开始对话`,welcomeSubtitle:`输入您的问题,AI 助手将为您解答`,sendBtnStop:`停止生成`,sendBtnSend:`发送`,imageNotEnabled:`未启用图片识别,图片已作为文件附件处理`,screenshotFailed:`截图失败,请重试`,auditCategoryAuth:`认证`,auditCategoryFs:`文件`,auditCategoryExec:`命令`,auditCategorySecurity:`安全`,auditCategorySystem:`系统`,auditDetailSeparator:`;`,auditQueryFailed:`查询失败: {error}`,auditLoadFailed:`加载失败: {error}`,auditNoMatch:`没有匹配的审计日志`,auditEmpty:`暂无审计日志`,clearStatsConfirm:`确定要清空所有工具使用统计吗?此操作不可撤销。`,clearStatsTitle:`清空统计`,toolStatsSummary:`已使用 {used} 个,未使用 {unused} 个`,toolStatsLoadFailed:`加载失败`,toolNameDescSeparator:`:`}}),n(`en`,{sidePanel:{confirmAction:`Confirm Action`,memoryLimitAll:`All`,memoryLimitTitle:`Click to set memory history limit`,configUpdated:`✅ Configuration updated`,selectedPrefix:`📌 Selected`,askBasedOnSelection:`Ask based on selection`,copySelectionTooltip:`Copy selection`,copySelectionDone:`Selection copied`,selectedContentLabel:`Selected content`,selectedContentSummary:`summary`,userQuestionLabel:`User question`,requestFailed:`❌ Request failed: `,unknownError:`Unknown error`,notConnected:`Not Connected`,noPairedAgents:`No paired agents`,agentDisabled:`Disabled`,agentConnected:`Connected`,agentChecking:`Checking...`,agentOnline:`Online`,agentOffline:`Offline`,enableAgent:`Enable`,disableAgent:`Disable`,disconnectAgent:`Disconnect`,connectAgent:`Connect`,deleteAgentBtn:`Delete`,workingDirectory:`Working directory: {path}`,agentAddressCopied:`Agent address copied`,unknownAgent:`Unknown`,restartAgentConfirm:`Agent name: {name}
|
|
2724
2724
|
Agent address: {url}
|
|
2725
2725
|
|
|
2726
2726
|
Are you sure you want to restart the agent service? The service will be briefly unavailable during restart.`,restartAgentTitle:`Restart Agent`,agentRestarting:`Agent service is restarting...`,restartFailed:`Restart failed: {error}`,restartRequestFailed:`Restart request failed: {error}`,updateAgentConfirm:`Agent name: {name}
|
|
@@ -2729,7 +2729,7 @@ Agent address: {url}
|
|
|
2729
2729
|
Are you sure you want to update the agent? It will install the latest version via npm, 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...`,updateFailed:`Update failed: {error}`,updateRequestFailed:`Update request failed: {error}`,stopAgentConfirm:`Agent name: {name}
|
|
2730
2730
|
Agent address: {url}
|
|
2731
2731
|
|
|
2732
|
-
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`,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,t=r(`sidePanel.confirmAction`)){return new Promise(n=>{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){n(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(),n(!0)},u=()=>{c(),n(!1)},d=e=>{e.target===r&&(c(),n(!1))},f=e=>{e.key===`Enter`?(e.preventDefault(),e.stopPropagation(),l()):e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),u())};i.textContent=t,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&&(N.chatConfig.autoCompaction=e.chatAutoCompaction.newValue===!0,iL(),a.debug(`[SidePanel] auto-compaction config updated:`,N.chatConfig.autoCompaction)),t===`local`&&e.chatPersistSummaryToMemory&&(N.chatConfig.persistSummaryToMemory=e.chatPersistSummaryToMemory.newValue!==!1,aL(),a.debug(`[SidePanel] persist-summary config updated:`,N.chatConfig.persistSummaryToMemory)),t===`local`&&e.chatMaxMemoryMessages&&(N.chatConfig.maxMemoryMessages=e.chatMaxMemoryMessages.newValue,rL(),a.debug(`[SidePanel] memory limitconfiguration updated:`,N.chatConfig.maxMemoryMessages)),t===`local`&&e.queueAutoCarry&&(N.chatConfig.queueAutoCarry=e.queueAutoCarry.newValue!==!1,a.debug(`[SidePanel] queue auto-carry updated:`,N.chatConfig.queueAutoCarry)),t===`local`&&e.queueAutoCarryEveryNIterations&&(N.chatConfig.queueAutoCarryEveryNIterations=e.queueAutoCarryEveryNIterations.newValue,a.debug(`[SidePanel] queue auto-carry interval updated:`,N.chatConfig.queueAutoCarryEveryNIterations))});function rL(){let e=document.getElementById(`memoryLimitLabel`);e&&(N.chatConfig.maxMemoryMessages!==null&&N.chatConfig.maxMemoryMessages!==void 0&&N.chatConfig.maxMemoryMessages>0?e.textContent=N.chatConfig.maxMemoryMessages:e.textContent=r(`sidePanel.memoryLimitAll`),e.title=r(`sidePanel.memoryLimitTitle`))}function iL(){let e=document.getElementById(`autoCompactBtn`);e&&(e.checked=N.chatConfig.autoCompaction===!0)}function aL(){let e=document.getElementById(`persistSummaryBtn`);e&&(e.checked=N.chatConfig.persistSummaryToMemory!==!1)}function oL(e){e.preventDefault(),e.stopPropagation();let t=document.getElementById(`memoryLimitDropdown`);if(t.classList.toggle(`show`),t.classList.contains(`show`)){let e=N.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 sL(){let e=document.getElementById(`memoryLimitDropdown`),t=document.getElementById(`memoryLimitLabel`),n=e?.querySelector(`#memoryLimitInput`);if(!e||!t)return;rL(),t.addEventListener(`click`,oL);let i=document.getElementById(`autoCompactBtn`);i&&(i.checked=N.chatConfig.autoCompaction===!0,i.addEventListener(`change`,()=>{let e=i.checked;chrome.storage.local.set({chatAutoCompaction:e},()=>{N.chatConfig.autoCompaction=e,L(r(`sidePanel.configUpdated`),`success`)})}));let a=document.getElementById(`persistSummaryBtn`);a&&(a.checked=N.chatConfig.persistSummaryToMemory!==!1,a.addEventListener(`change`,()=>{let e=a.checked;chrome.storage.local.set({chatPersistSummaryToMemory:e},()=>{N.chatConfig.persistSummaryToMemory=e,L(r(`sidePanel.configUpdated`),`success`)})}));let o=e.querySelectorAll(`.memory-limit-option`);o.forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation();let i=parseInt(e.dataset.value),a=i===0?null:i;o.forEach(e=>e.classList.remove(`selected`)),e.classList.add(`selected`),n&&(n.value=i===0?``:i),chrome.storage.local.set({chatMaxMemoryMessages:a},()=>{N.chatConfig.maxMemoryMessages=a,rL(),L(r(`sidePanel.configUpdated`),`success`)})})}),n&&(n.addEventListener(`click`,e=>e.stopPropagation()),n.addEventListener(`mousedown`,e=>e.stopPropagation()),n.addEventListener(`change`,e=>{e.stopPropagation();let t=e.target.value.trim(),n=t&&parseInt(t)>0?parseInt(t):null;o.forEach(e=>e.classList.remove(`selected`)),chrome.storage.local.set({chatMaxMemoryMessages:n},()=>{N.chatConfig.maxMemoryMessages=n,rL(),L(r(`sidePanel.configUpdated`),`success`)})})),document.getElementById(`memoryLimitConfigEntry`)?.addEventListener(`click`,()=>{chrome.runtime.sendMessage({type:`OPEN_OPTIONS_PAGE`,hash:`memory`})}),document.addEventListener(`click`,n=>{!e.contains(n.target)&&n.target!==t&&e.classList.remove(`show`)})}async function cL(e){if(N.activeAgentId&&N.activeAgentId!=="default")try{let{updateAgent:t}=await M(async()=>{let{updateAgent:e}=await import(`./agent-store-1fyaAv9T.js`).then(e=>e.t);return{updateAgent:e}},__vite__mapDeps([0,1,2,3,4]));await t(N.activeAgentId,{model:e})}catch{}else chrome.storage.local.set({modelName:e}),A(e)}async function lL(){try{let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),t=nL(e.pairedAgents),n=e.activeAgentId,r=t.find(e=>e.id===n&&!e.disabled);if(!r){N.agentPlatform={connected:!1},wL(N.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){N.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&&N.agentVersions.set(n,t.version),t.workdir&&N.agentWorkdirs.set(n,t.workdir),t.homeDir&&N.agentHomeDirs.set(n,t.homeDir);let e=OL(t.platformName||t.platform,t.arch);e&&N.agentSystemInfos.set(n,e)}else N.agentPlatform={connected:!1}}else N.agentPlatform={connected:!1}}catch{N.agentPlatform={connected:!1}}else N.agentPlatform={connected:!1};wL(N.agentPlatform),Xm()}catch{}}async function uL(e,t,n){if(N.activeAgentId&&N.activeAgentId!=="default")try{let{updateAgent:n}=await M(async()=>{let{updateAgent:e}=await import(`./agent-store-1fyaAv9T.js`).then(e=>e.t);return{updateAgent:e}},__vite__mapDeps([0,1,2,3,4]));await n(N.activeAgentId,{temperature:e,topP:t})}catch{}else chrome.storage.local.set({temperature:e,topP:t,selectedTempIndex:n})}function dL(){let e=document.getElementById(`currentModelTag`);if(!e)return;let t=N.currentModel||``;e.textContent=t,e.title=t,e.style.display=t?``:`none`}var fL=new Set,pL=0;function mL(){let e=document.getElementById(`workdirTag`);e&&(e.dataset.locked=qm(N.activeSessionId)?`true`:`false`)}async function hL(){let e=++pL,t=document.getElementById(`workdirTag`),n=document.getElementById(`workdirTagName`);if(!t||!n)return;let i=N.activeSessionId||null,o=Array.isArray(N.enabledTools)&&N.enabledTools.includes(`agent_exec`);if(N.agentPlatform?.connected!==!0||!o){t.style.display=`none`;return}let s=null;try{s=await fe(i)}catch(e){a.debug(`[WorkdirTag] resolve failed:`,e&&e.message)}if(e!==pL)return;let c=s&&s.workdir||``;if(!c){t.style.display=`none`;return}t.style.display=``,n.textContent=ae(c,{homeDir:N.agentPlatform?.homeDir||``}),mL();try{let{getWorkspaceRoot:e}=await M(async()=>{let{getWorkspaceRoot:e}=await import(`./workspace-manager-DfSFPqwp.js`).then(e=>e.D);return{getWorkspaceRoot:e}},__vite__mapDeps([15,1,2,3,4])),n=await e(i),r=!!(n&&n!==c);r&&s.scope==="default"?(t.dataset.invalid=`false`,xI(i).then(e=>{e&&hL()}).catch(e=>a.debug(`[WorkdirTag] reconcile failed:`,e&&e.message))):t.dataset.invalid=r?`true`:`false`}catch{t.dataset.invalid=`false`}if(e===pL&&(t.title=`${c}${s.scope===`session`?r(`workdirTag.sessionScope`):r(`workdirTag.defaultScope`)}${t.dataset.invalid===`true`?r(`workdirTag.pathMissing`):``}`,s.boundWorkdir&&s.scope==="default")){let e=`${i||``}::${s.agentId||``}`;fL.has(e)||(fL.add(e),L(r(`workdirTag.agentSwitched`),`warning`))}}function gL(){let e=document.getElementById(`workdirTag`);e&&(e.setAttribute(`aria-label`,r(`workdirTag.tagHint`)),e.addEventListener(`click`,async e=>{if(e.stopPropagation(),qm(N.activeSessionId)){mL(),L(r(`workdirTag.lockedHint`),`warning`);return}mL();let{showSwitchWorkdirDialog:t}=await M(async()=>{let{showSwitchWorkdirDialog:e}=await Promise.resolve().then(()=>nh);return{showSwitchWorkdirDialog:e}},void 0);await t({sessionId:N.activeSessionId||null})})),hL(),document.addEventListener(`session-switched`,()=>{hL()}),document.addEventListener(`session-workdir-changed`,()=>{hL()}),document.addEventListener(`agent-model-changed`,()=>{hL()}),document.addEventListener(`agent-tools-changed`,()=>{hL()}),document.addEventListener(`generating-state-changed`,()=>{mL()}),document.addEventListener(`generation-ended`,()=>{mL()}),Hr(()=>{mL()})}function _L(){let e=document.getElementById(`currentModelTag`);e&&e.addEventListener(`click`,e=>{e.stopPropagation(),document.getElementById(`tempDisplay`)?.click()}),dL()}function vL(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=E(t),r.style.display=``):r.style.display=`none`),dL()}function yL(e,t){let n=document.getElementById(`tempDropdown`);if(!n){typeof t==`function`&&t();return}let i=n.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=`
|
|
2732
|
+
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`,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,t=r(`sidePanel.confirmAction`)){return new Promise(n=>{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){n(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(),n(!0)},u=()=>{c(),n(!1)},d=e=>{e.target===r&&(c(),n(!1))},f=e=>{e.key===`Enter`?(e.preventDefault(),e.stopPropagation(),l()):e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),u())};i.textContent=t,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&&(N.chatConfig.autoCompaction=e.chatAutoCompaction.newValue===!0,aL(),a.debug(`[SidePanel] auto-compaction config updated:`,N.chatConfig.autoCompaction)),t===`local`&&e.chatPersistSummaryToMemory&&(N.chatConfig.persistSummaryToMemory=e.chatPersistSummaryToMemory.newValue!==!1,oL(),a.debug(`[SidePanel] persist-summary config updated:`,N.chatConfig.persistSummaryToMemory)),t===`local`&&e.chatMaxMemoryMessages&&(N.chatConfig.maxMemoryMessages=e.chatMaxMemoryMessages.newValue,iL(),a.debug(`[SidePanel] memory limitconfiguration updated:`,N.chatConfig.maxMemoryMessages)),t===`local`&&e.queueAutoCarry&&(N.chatConfig.queueAutoCarry=e.queueAutoCarry.newValue!==!1,a.debug(`[SidePanel] queue auto-carry updated:`,N.chatConfig.queueAutoCarry)),t===`local`&&e.queueAutoCarryEveryNIterations&&(N.chatConfig.queueAutoCarryEveryNIterations=e.queueAutoCarryEveryNIterations.newValue,a.debug(`[SidePanel] queue auto-carry interval updated:`,N.chatConfig.queueAutoCarryEveryNIterations))});function iL(){let e=document.getElementById(`memoryLimitLabel`);e&&(N.chatConfig.maxMemoryMessages!==null&&N.chatConfig.maxMemoryMessages!==void 0&&N.chatConfig.maxMemoryMessages>0?e.textContent=N.chatConfig.maxMemoryMessages:e.textContent=r(`sidePanel.memoryLimitAll`),e.title=r(`sidePanel.memoryLimitTitle`))}function aL(){let e=document.getElementById(`autoCompactBtn`);e&&(e.checked=N.chatConfig.autoCompaction===!0)}function oL(){let e=document.getElementById(`persistSummaryBtn`);e&&(e.checked=N.chatConfig.persistSummaryToMemory!==!1)}function sL(e){e.preventDefault(),e.stopPropagation();let t=document.getElementById(`memoryLimitDropdown`);if(t.classList.toggle(`show`),t.classList.contains(`show`)){let e=N.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 cL(){let e=document.getElementById(`memoryLimitDropdown`),t=document.getElementById(`memoryLimitLabel`),n=e?.querySelector(`#memoryLimitInput`);if(!e||!t)return;iL(),t.addEventListener(`click`,sL);let i=document.getElementById(`autoCompactBtn`);i&&(i.checked=N.chatConfig.autoCompaction===!0,i.addEventListener(`change`,()=>{let e=i.checked;chrome.storage.local.set({chatAutoCompaction:e},()=>{N.chatConfig.autoCompaction=e,L(r(`sidePanel.configUpdated`),`success`)})}));let a=document.getElementById(`persistSummaryBtn`);a&&(a.checked=N.chatConfig.persistSummaryToMemory!==!1,a.addEventListener(`change`,()=>{let e=a.checked;chrome.storage.local.set({chatPersistSummaryToMemory:e},()=>{N.chatConfig.persistSummaryToMemory=e,L(r(`sidePanel.configUpdated`),`success`)})}));let o=e.querySelectorAll(`.memory-limit-option`);o.forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation();let i=parseInt(e.dataset.value),a=i===0?null:i;o.forEach(e=>e.classList.remove(`selected`)),e.classList.add(`selected`),n&&(n.value=i===0?``:i),chrome.storage.local.set({chatMaxMemoryMessages:a},()=>{N.chatConfig.maxMemoryMessages=a,iL(),L(r(`sidePanel.configUpdated`),`success`)})})}),n&&(n.addEventListener(`click`,e=>e.stopPropagation()),n.addEventListener(`mousedown`,e=>e.stopPropagation()),n.addEventListener(`change`,e=>{e.stopPropagation();let t=e.target.value.trim(),n=t&&parseInt(t)>0?parseInt(t):null;o.forEach(e=>e.classList.remove(`selected`)),chrome.storage.local.set({chatMaxMemoryMessages:n},()=>{N.chatConfig.maxMemoryMessages=n,iL(),L(r(`sidePanel.configUpdated`),`success`)})})),document.getElementById(`memoryLimitConfigEntry`)?.addEventListener(`click`,()=>{chrome.runtime.sendMessage({type:`OPEN_OPTIONS_PAGE`,hash:`memory`})}),document.addEventListener(`click`,n=>{!e.contains(n.target)&&n.target!==t&&e.classList.remove(`show`)})}async function lL(e){if(N.activeAgentId&&N.activeAgentId!=="default")try{let{updateAgent:t}=await M(async()=>{let{updateAgent:e}=await import(`./agent-store-CXWql6bl.js`).then(e=>e.t);return{updateAgent:e}},__vite__mapDeps([0,1,2,3,4]));await t(N.activeAgentId,{model:e})}catch{}else chrome.storage.local.set({modelName:e}),A(e)}async function uL(){try{let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),t=rL(e.pairedAgents),n=e.activeAgentId,r=t.find(e=>e.id===n&&!e.disabled);if(!r){N.agentPlatform={connected:!1},OL(N.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){N.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&&N.agentVersions.set(n,t.version),t.workdir&&N.agentWorkdirs.set(n,t.workdir),t.homeDir&&N.agentHomeDirs.set(n,t.homeDir);let e=ML(t.platformName||t.platform,t.arch);e&&N.agentSystemInfos.set(n,e)}else N.agentPlatform={connected:!1}}else N.agentPlatform={connected:!1}}catch{N.agentPlatform={connected:!1}}else N.agentPlatform={connected:!1};OL(N.agentPlatform),Xm()}catch{}}async function dL(e,t,n){if(N.activeAgentId&&N.activeAgentId!=="default")try{let{updateAgent:n}=await M(async()=>{let{updateAgent:e}=await import(`./agent-store-CXWql6bl.js`).then(e=>e.t);return{updateAgent:e}},__vite__mapDeps([0,1,2,3,4]));await n(N.activeAgentId,{temperature:e,topP:t})}catch{}else chrome.storage.local.set({temperature:e,topP:t,selectedTempIndex:n})}function fL(){let e=document.getElementById(`currentModelTag`);if(!e)return;let t=N.currentModel||``;e.textContent=t,e.title=t,e.style.display=t?``:`none`}var pL=new Set,mL=0;function hL(){let e=document.getElementById(`workdirTag`);e&&(e.dataset.locked=qm(N.activeSessionId)?`true`:`false`)}async function gL(){let e=++mL,t=document.getElementById(`workdirTag`),n=document.getElementById(`workdirTagName`);if(!t||!n)return;let i=N.activeSessionId||null,o=Array.isArray(N.enabledTools)&&N.enabledTools.includes(`agent_exec`);if(N.agentPlatform?.connected!==!0||!o){t.style.display=`none`;return}let s=null;try{s=await fe(i)}catch(e){a.debug(`[WorkdirTag] resolve failed:`,e&&e.message)}if(e!==mL)return;let c=s&&s.workdir||``;if(!c){t.style.display=`none`;return}t.style.display=``,n.textContent=ae(c,{homeDir:N.agentPlatform?.homeDir||``}),hL();try{let{getWorkspaceRoot:e}=await M(async()=>{let{getWorkspaceRoot:e}=await import(`./workspace-manager-CZeD2gWf.js`).then(e=>e.D);return{getWorkspaceRoot:e}},__vite__mapDeps([15,1,2,3,4])),n=await e(i),r=!!(n&&n!==c);r&&s.scope==="default"?(t.dataset.invalid=`false`,SI(i).then(e=>{e&&gL()}).catch(e=>a.debug(`[WorkdirTag] reconcile failed:`,e&&e.message))):t.dataset.invalid=r?`true`:`false`}catch{t.dataset.invalid=`false`}if(e===mL&&(t.title=`${c}${s.scope===`session`?r(`workdirTag.sessionScope`):r(`workdirTag.defaultScope`)}${t.dataset.invalid===`true`?r(`workdirTag.pathMissing`):``}`,s.boundWorkdir&&s.scope==="default")){let e=`${i||``}::${s.agentId||``}`;pL.has(e)||(pL.add(e),L(r(`workdirTag.agentSwitched`),`warning`))}}function _L(){let e=document.getElementById(`workdirTag`);e&&(e.setAttribute(`aria-label`,r(`workdirTag.tagHint`)),e.addEventListener(`click`,async e=>{if(e.stopPropagation(),qm(N.activeSessionId)){hL(),L(r(`workdirTag.lockedHint`),`warning`);return}hL();let{showSwitchWorkdirDialog:t}=await M(async()=>{let{showSwitchWorkdirDialog:e}=await Promise.resolve().then(()=>nh);return{showSwitchWorkdirDialog:e}},void 0);await t({sessionId:N.activeSessionId||null})})),gL(),document.addEventListener(`session-switched`,()=>{gL()}),document.addEventListener(`session-workdir-changed`,()=>{gL()}),document.addEventListener(`agent-model-changed`,()=>{gL()}),document.addEventListener(`agent-tools-changed`,()=>{gL()}),document.addEventListener(`generating-state-changed`,()=>{hL()}),document.addEventListener(`generation-ended`,()=>{hL()}),Hr(()=>{hL()})}function vL(){let e=document.getElementById(`currentModelTag`);e&&e.addEventListener(`click`,e=>{e.stopPropagation(),document.getElementById(`tempDisplay`)?.click()}),fL()}function yL(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=E(t),r.style.display=``):r.style.display=`none`),fL()}function bL(e,t){let n=document.getElementById(`tempDropdown`);if(!n){typeof t==`function`&&t();return}let i=n.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=`
|
|
2733
2733
|
<div class="model-section-title" data-i18n="model.selectModel">${r(`model.selectModel`)}</div>
|
|
2734
2734
|
<div class="section-select" id="modelSelect">
|
|
2735
2735
|
<div class="section-select-row" id="modelSelectRow">
|
|
@@ -2738,10 +2738,17 @@ Are you sure you want to stop the agent service? You will not be able to connect
|
|
|
2738
2738
|
<span class="section-select-caret"></span>
|
|
2739
2739
|
</div>
|
|
2740
2740
|
<div class="section-select-list" id="modelSelectList"></div>
|
|
2741
|
-
</div>`;let e=i.querySelector(`#modelSelectList`);e.innerHTML
|
|
2742
|
-
|
|
2743
|
-
<
|
|
2744
|
-
|
|
2741
|
+
</div>`;let e=i.querySelector(`#modelSelectList`);e.innerHTML=$N();let t=[...a].sort((e,t)=>T(e.name,t.name));for(let n of t){let t=document.createElement(`div`);t.className=`model-option`,t.dataset.value=n.name,n.contextWindow&&n.contextWindow>0&&(t.dataset.contextWindow=n.contextWindow),t.innerHTML=`<span class="model-option-check"></span><span class="model-option-left">${P(n.name)}</span>`;let i=document.createElement(`span`);i.className=`model-option-right`;let a=document.createElement(`span`);a.className=`model-ctx-badge`;let o=n.contextWindow&&n.contextWindow>0;a.textContent=E(o?n.contextWindow:p(n.name)),o||(a.classList.add(`is-auto`),a.title=r(`settings.ctxBadgeAutoTip`)),i.appendChild(a),t.appendChild(i),t.addEventListener(`click`,e=>{e.stopPropagation(),QN(),N.currentModel=n.name,yL(n.name),lL(n.name),bE()}),e.appendChild(t)}}N.customModelMap=h(e),typeof t==`function`&&t()}function xL(e,t=r(`sidePanel.selectedPrefix`)){if(!N.enableSelectionQuery)return;N.quotedContextText=``,N.selectedContextText=e;let n=document.getElementById(`selectionIndicator`),i=document.getElementById(`selectionText`),a=document.getElementById(`userInput`);if(n&&i&&a){let r;r=e.length>100?e.substring(0,100)+`...`:e.length>50?e.substring(0,50)+`...`:e,i.textContent=`${t}: ${r}`,n.classList.add(`show`)}}var SL=null,CL=``;function wL(){if(SL&&SL.isConnected)return SL;SL=document.createElement(`div`),SL.className=`selection-floating-menu`,SL.id=`selectionFloatingMenu`,SL.innerHTML=`
|
|
2742
|
+
<div class="menu-header">
|
|
2743
|
+
<span class="menu-header-title"></span>
|
|
2744
|
+
<button class="menu-copy-btn" type="button">
|
|
2745
|
+
<svg viewBox="0 0 16 16" fill="currentColor">
|
|
2746
|
+
<path d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 0 1 0 1.5h-1.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-1.5a.75.75 0 0 1 1.5 0v1.5A1.75 1.75 0 0 1 9.25 16h-7.5A1.75 1.75 0 0 1 0 14.25zM5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0 1 14.25 11h-7.5A1.75 1.75 0 0 1 5 9.25zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25z"/>
|
|
2747
|
+
</svg>
|
|
2748
|
+
</button>
|
|
2749
|
+
</div>
|
|
2750
|
+
<div class="menu-items"></div>
|
|
2751
|
+
`;let e=SL.querySelector(`.menu-copy-btn`);return e?.addEventListener(`click`,t=>{t.stopPropagation(),CL&&(At(CL,e),L(r(`sidePanel.copySelectionDone`),`success`),window.getSelection()?.removeAllRanges(),window.hideFloatingMenu())}),document.body.appendChild(SL),SL}function TL(e,t,n=0,i=0){if(!N.enableSelectionQuery)return;let o=N.customPrompts.filter(e=>e.enabledInMenu===!0);if(o.length===0){a.debug(`[SidePanel] showFloatingMenu skipped: no prompts enabled in menu`);return}let s=wL();CL=t||``,s.querySelector(`.menu-header-title`).textContent=r(`sidePanel.askBasedOnSelection`);let c=s.querySelector(`.menu-copy-btn`);c&&(c.title=r(`sidePanel.copySelectionTooltip`));let l=s.querySelector(`.menu-items`);l.innerHTML=``,o.forEach(e=>{let a=e.content.length>10?e.content.substring(0,10)+`...`:e.content,o=document.createElement(`div`);o.className=`menu-item`,o.innerHTML=`
|
|
2745
2752
|
<span>${a}</span>
|
|
2746
2753
|
<span class="menu-item-actions">
|
|
2747
2754
|
<span class="menu-item-code">/${e.code}</span>
|
|
@@ -2753,9 +2760,9 @@ Are you sure you want to stop the agent service? You will not be able to connect
|
|
|
2753
2760
|
</svg>
|
|
2754
2761
|
</button>
|
|
2755
2762
|
</span>
|
|
2756
|
-
`,o.addEventListener(`click`,n=>{n.stopPropagation(),
|
|
2763
|
+
`,o.addEventListener(`click`,n=>{n.stopPropagation(),EL(e,t)}),o.querySelector(`.menu-item-popup-btn`).addEventListener(`click`,r=>{r.stopPropagation();let a=N.currentSelectionRange?N.currentSelectionRange.cloneRange():null;window.getSelection()?.removeAllRanges(),window.hideFloatingMenu(),tL(e,t,n,i,a)}),l.appendChild(o)});let u=window.innerWidth,d=window.innerHeight,f=40+o.length*36,p=i-f-30,m=n-20;p<8&&(p=i+30),m+180>u-8&&(m=n-180-30,m<8&&(m=n+20)),m<8&&(m=8),p+f>d-8&&(p=i-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(){SL&&SL.classList.remove(`show`),CL=``,N.lastSelectedText=``,N.currentSelectionRange=null};async function EL(e,t){if(!N.enableSelectionQuery)return;if(window.hideFloatingMenu(),N.isGenerating){a.debug(`[SidePanel] generating,please wait...`);return}mx()&&bx(),await Xc({state:N,getRatio:()=>vE().usage?.ratio??0,compact:DE}),N.selectedContextText=t,SC();let n=document.getElementById(`chatContainer`).querySelector(`.welcome-message`);n&&n.remove(),ew(`selected`,t,!1);let{compressed:i,wasCompressed:o}=k(t),s=`[${r(`sidePanel.selectedContentLabel`)}${o?r(`sidePanel.selectedContentSummary`):``}]\n${i}\n\n[${r(`sidePanel.userQuestionLabel`)}]\n${e.content}`,{messageId:c,timestamp:l}=iw(`user`,e.content,!0,[],null,!1,s);N.messageHistory.push({role:`user`,content:s,messageId:c,timestamp:l}),OC(),qn(e.content),N.isGenerating=!0;let u=uw(),d=N.activeSessionId,p=N.currentModel;try{await zt(),a.debug(`[SidePanel] sendmessagedebuginfo:`),a.debug(` - isolateChat:`,N.isolateChat),a.debug(` - chatConfig:`,N.chatConfig),a.debug(` - messageHistory.length:`,N.messageHistory.length);let t=[{role:`system`,content:await Kt(null,{sessionId:d})}];if(N.isolateChat){let e=f(t[0]?.content||``),n=g(p,0,N.customModelMap)-e-4096-2e3,r=Math.floor(n*.7),i=N.messageHistory[N.messageHistory.length-1],o=Hn(N.messageHistory.slice(0,-1),{isolateChat:!0,maxMemoryMessages:N.chatConfig.maxMemoryMessages,compaction:N.activeCompaction,historyBudget:r,currentMessage:i});Wn(t,o,N.activeCompaction,a),o.historySummaryText&&(t[0]={...t[0],content:t[0].content+`
|
|
2757
2764
|
|
|
2758
|
-
`+o.historySummaryText}),t=[...t,...o.messages];for(let e=0;e<t.length-1;e++)t[e]={...t[e],content:v(t[e].content)}}else t.push({role:`user`,content:s});let n=await
|
|
2765
|
+
`+o.historySummaryText}),t=[...t,...o.messages];for(let e=0;e<t.length-1;e++)t[e]={...t[e],content:v(t[e].content)}}else t.push({role:`user`,content:s});let n=await Pt(),i,o;try{let r=await yw(t,p,N.useTools,n);if(i=r.content,o=r.executionLog||[],dw(u),r.wasStreamed)r.streamingMsgId&&(N.messageHistory.push({role:`assistant`,content:i,executionLog:o,messageId:r.streamingMsgId}),OC());else{let{element:e,messageId:t}=iw(`assistant`,i,!0,o);await cn(e),N.messageHistory.push({role:`assistant`,content:i,executionLog:o,messageId:t}),OC()}Dl(d,e.content);return}catch(t){dw(u),i=r(`sidePanel.requestFailed`)+(t.message||r(`sidePanel.unknownError`)),o=t.executionLog||[];let{element:n,messageId:a}=iw(`assistant`,i,!0,o);throw N.messageHistory.push({role:`assistant`,content:i,executionLog:o,messageId:a}),OC(),t.message!==r(`chatMsg.errTaskStopped`)&&Ol(d,i,e.content),t}}catch{}finally{jl(d),document.getElementById(`userInput`).focus()}}var DL=null;async function OL(e,t=!1){let n=document.getElementById(`headerAgentDot`),i=document.getElementById(`headerAgentName`),a=document.getElementById(`headerAgentTrigger`);if(!n||!i)return;let o=null,s=[];try{let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]);s=rL(e.pairedAgents),o=s.find(t=>t.id===e.activeAgentId)}catch{}let c=e?.connected===!0;if(c!==DL){DL=c;try{document.dispatchEvent(new CustomEvent(`agent-connection-changed`,{detail:{connected:c}}))}catch{}}if(!c||!o?(n.className=`header-agent-dot disconnected`,i.textContent=o?o.name.length>12?o.name.substring(0,12)+`...`:o.name:r(`sidePanel.notConnected`),i.classList.toggle(`truncated`,!!o),a.title=o?o.name:``):(n.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),kL(o,s,c),!t){let e=document.getElementById(`headerAgentDropdown`);e&&e.style.display!==`none`&&FL()}Ev(c),gL()}function kL(e,t,n){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`,t.length===0){i.innerHTML=`<div class="agent-dd-empty">`+r(`sidePanel.noPairedAgents`)+`</div>`;let e=document.getElementById(`agentDdRestartBtn`),t=document.getElementById(`agentDdUpdateBtn`),n=document.getElementById(`agentDdStopBtn`);e&&(e.disabled=!0),t&&(t.disabled=!0),n&&(n.disabled=!0);return}i.innerHTML=t.map(t=>{let i=t.id===e?.id,a=!!t.disabled,o=N.agentVersions.get(t.id),s,c;a?(s=`disabled`,c=r(`sidePanel.agentDisabled`)):i?(s=n?`connected`:`disconnected`,c=r(n?`sidePanel.agentConnected`:`sidePanel.notConnected`)):(s=`checking`,c=r(`sidePanel.agentChecking`));let l=N.agentWorkdirs.get(t.id),u=jL(l,N.agentHomeDirs.get(t.id)),d=N.agentSystemInfos.get(t.id);return`
|
|
2759
2766
|
<div class="agent-dd-item${i?` active`:``}${a?` disabled`:``}" data-agent-id="${t.id}">
|
|
2760
2767
|
<span class="agent-dd-item-dot ${s}"></span>
|
|
2761
2768
|
<div class="agent-dd-item-info">
|
|
@@ -2772,7 +2779,7 @@ Are you sure you want to stop the agent service? You will not be able to connect
|
|
|
2772
2779
|
<button class="agent-dd-tool-btn delete" data-action="delete" data-id="${t.id}" title="${r(`sidePanel.deleteAgentBtn`)}">🗑</button>
|
|
2773
2780
|
</div>
|
|
2774
2781
|
</div>
|
|
2775
|
-
`}).join(``);let o=document.getElementById(`agentDdRestartBtn`),s=document.getElementById(`agentDdUpdateBtn`),c=document.getElementById(`agentDdStopBtn`),l=!!(e&&n);o&&(o.disabled=!l),s&&(s.disabled=!l),c&&(c.disabled=!l)}async function EL(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 DL(e,t){return e?t&&e.startsWith(t)?`~`+e.substring(t.length):e:``}function OL(e,t){return e||``}function kL(e,t){let n=document.querySelector(`.agent-dd-item[data-agent-id="${e}"]`);if(!n)return;let i=n.querySelector(`.agent-dd-item-dot`),a=n.querySelector(`.agent-dd-item-status`),o=n.classList.contains(`active`);i&&(i.classList.remove(`checking`,`connected`,`disconnected`,`online`,`offline`),i.classList.add(o?t?`connected`:`disconnected`:t?`online`:`offline`)),a&&(o?a.textContent=r(t?`sidePanel.agentConnected`:`sidePanel.notConnected`):a.textContent===r(`sidePanel.agentChecking`)&&(a.textContent=r(t?`sidePanel.agentOnline`:`sidePanel.agentOffline`)))}function AL(e,t){if(!t)return;let n=document.querySelector(`.agent-dd-item[data-agent-id="${e}"]`);if(!n)return;let i=n.querySelector(`.agent-dd-item-info`);if(!i)return;let a=DL(t,N.agentHomeDirs.get(e)),o=i.querySelector(`.agent-dd-item-workdir`);o?(o.textContent=a,o.title=r(`sidePanel.workingDirectory`,{path:t})):(o=document.createElement(`span`),o.className=`agent-dd-item-workdir`,o.title=r(`sidePanel.workingDirectory`,{path:t}),o.textContent=a,i.appendChild(o))}window.updateAgentItemWorkdir=AL;async function jL(){try{let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),t=nL(e.pairedAgents),n=e.activeAgentId;await Promise.all(t.filter(e=>!e.disabled).map(async e=>{let t=await EL(e.url,e.token),r=t.online;t.version&&N.agentVersions.set(e.id,t.version),t.workdir&&N.agentWorkdirs.set(e.id,t.workdir),t.homeDir&&N.agentHomeDirs.set(e.id,t.homeDir);let i=OL(t.platformName,t.arch);i&&N.agentSystemInfos.set(e.id,i),t.workdir&&AL(e.id,t.workdir),kL(e.id,r),e.id===n&&r!==(N.agentPlatform?.connected===!0)&&(N.agentPlatform={...N.agentPlatform,connected:r},wL(N.agentPlatform,!0),r&&ML(e))}))}catch{}}async function ML(e){try{let t=e;if(!t){let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),n=nL(e.pairedAgents),r=e.activeAgentId;t=n.find(e=>e.id===r&&!e.disabled)}if(!t||!t.url){N.agentPlatform={...N.agentPlatform,connected:!0},wL(N.agentPlatform),Xm();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){N.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&&N.agentVersions.set(t.id,e.version),e.workdir&&(N.agentWorkdirs.set(t.id,e.workdir),AL(t.id,e.workdir)),e.homeDir&&N.agentHomeDirs.set(t.id,e.homeDir);let n=OL(e.platformName||e.platform,e.arch);n&&N.agentSystemInfos.set(t.id,n),wL(N.agentPlatform),Xm();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();N.agentPlatform={platformName:e.platformName||e.platform||`Unknown`,platform:e.platform||`unknown`,arch:e.arch||`unknown`,connected:!0},wL(N.agentPlatform),Xm();return}}catch{}N.agentPlatform={...N.agentPlatform,connected:!0},wL(N.agentPlatform),Xm()}catch{N.agentPlatform={...N.agentPlatform,connected:!0},wL(N.agentPlatform),Xm()}}var NL=null;function PL(e,t=20){NL&&clearInterval(NL);let n=0;NL=setInterval(async()=>{if(n++,n>t||!e){clearInterval(NL),NL=null;return}try{let t=nL((await chrome.storage.local.get([`pairedAgents`])).pairedAgents).find(t=>t.id===e);if(!t){clearInterval(NL),NL=null;return}let n=await EL(t.url,t.token);if(n.online){clearInterval(NL),NL=null,n.version&&N.agentVersions.set(e,n.version),n.workdir&&N.agentWorkdirs.set(e,n.workdir),n.homeDir&&N.agentHomeDirs.set(e,n.homeDir);let r=OL(n.platformName,n.arch);r&&N.agentSystemInfos.set(e,r),n.workdir&&AL(e,n.workdir),await ML(t),kL(e,!0)}}catch{}},3e3)}function FL(){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 IL(){let e=document.getElementById(`headerAgentTrigger`),t=document.getElementById(`headerAgentDropdown`),n=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||!t)return;e.addEventListener(`click`,e=>{e.stopPropagation();let n=t.style.display!==`none`;t.style.display=n?`none`:``,n||(FL(),wL(N.agentPlatform||{}),jL())}),document.addEventListener(`click`,n=>{!t.contains(n.target)&&n.target!==e&&(t.style.display=`none`)}),n.addEventListener(`click`,async e=>{e.stopPropagation(),N.activeAgentId;let t=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),n=nL(t.pairedAgents).find(e=>e.id===t.activeAgentId);n?.url&&(await navigator.clipboard.writeText(n.url),L(r(`sidePanel.agentAddressCopied`),`success`))}),i.addEventListener(`click`,async()=>{t.style.display=`none`,await chrome.storage.local.set({optionsInitialTab:`agent`});let e=await chrome.tabs.query({}),n=chrome.runtime.getURL(`options/index.html`),r=e.find(e=>e.url&&e.url.startsWith(n));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()=>{t.style.display=`none`;let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),n=nL(e.pairedAgents).find(t=>t.id===e.activeAgentId),i=n?.name||r(`sidePanel.unknownAgent`),a=n?.url||r(`sidePanel.unknownAgent`);if(await window.showCustomConfirm(r(`sidePanel.restartAgentConfirm`,{name:i,url:a}),r(`sidePanel.restartAgentTitle`)))try{chrome.runtime.sendMessage({type:`AGENT_RESTART`},async e=>{e?.success?(L(r(`sidePanel.agentRestarting`),`success`),N.agentPlatform={...N.agentPlatform,connected:!1},await wL(N.agentPlatform,!0),n?.id&&kL(n.id,!1),PL(n?.id)):L(r(`sidePanel.restartFailed`,{error:e?.error||r(`sidePanel.unknownError`)}),`error`)})}catch(e){L(r(`sidePanel.restartRequestFailed`,{error:e.message}),`error`)}}),o.addEventListener(`click`,async()=>{t.style.display=`none`;let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),n=nL(e.pairedAgents).find(t=>t.id===e.activeAgentId),i=n?.name||r(`sidePanel.unknownAgent`),a=n?.url||r(`sidePanel.unknownAgent`);if(await window.showCustomConfirm(r(`sidePanel.updateAgentConfirm`,{name:i,url:a}),r(`sidePanel.updateAgentTitle`))){L(r(`sidePanel.agentUpdating`),`info`);try{chrome.runtime.sendMessage({type:`AGENT_UPDATE`},async e=>{e?.success?(L(r(`sidePanel.agentUpdateRestarting`),`success`),N.agentPlatform={...N.agentPlatform,connected:!1},await wL(N.agentPlatform,!0),n?.id&&kL(n.id,!1),PL(n?.id)):L(r(`sidePanel.updateFailed`,{error:e?.error||r(`sidePanel.unknownError`)}),`error`)})}catch(e){L(r(`sidePanel.updateRequestFailed`,{error:e.message}),`error`)}}}),s.addEventListener(`click`,async()=>{t.style.display=`none`;let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),n=nL(e.pairedAgents).find(t=>t.id===e.activeAgentId),i=n?.name||r(`sidePanel.unknownAgent`),a=n?.url||r(`sidePanel.unknownAgent`);if(await window.showCustomConfirm(r(`sidePanel.stopAgentConfirm`,{name:i,url:a}),r(`sidePanel.stopAgentTitle`)))try{chrome.runtime.sendMessage({type:`AGENT_STOP`},async e=>{e?.success?(L(r(`sidePanel.agentStopped`),`success`),N.agentPlatform={...N.agentPlatform,connected:!1},await wL(N.agentPlatform,!0),n?.id&&kL(n.id,!1)):L(r(`sidePanel.stopFailed`,{error:e?.error||r(`sidePanel.unknownError`)}),`error`)})}catch(e){L(r(`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=r(`sidePanel.agentChecking`)}),await jL(),L(r(`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,t){let n=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),i=nL(n.pairedAgents);switch(e){case`enable`:i=i.map(e=>e.id===t?{...e,disabled:!1}:e),await chrome.storage.local.set({pairedAgents:i});break;case`disable`:{i=i.map(e=>e.id===t?{...e,disabled:!0}:e);let e=n.activeAgentId;n.activeAgentId===t&&(e=i.find(e=>e.id!==t&&!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:t}),chrome.runtime.sendMessage({type:`AGENT_CONNECTION_CHANGED`,connected:!0,agentId:t});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===t);if(!await window.showCustomConfirm(r(`sidePanel.deleteAgentTitle`),r(`sidePanel.deleteAgentConfirm`,{name:e?.name||t})))return;i=i.filter(e=>e.id!==t);let a=n.activeAgentId===t?i.find(e=>!e.disabled)?.id||null:n.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 LL=new Map,RL=8;function zL(e,t){for(LL.has(e)&&LL.delete(e),LL.set(e,t);LL.size>RL;)LL.delete(LL.keys().next().value)}function BL(e){let t=LL.get(e);if(t!==void 0)return LL.delete(e),LL.set(e,t),t}function VL(e){LL.delete(e)}document.addEventListener(`DOMContentLoaded`,async()=>{await ut(),mt(()=>{Jt()}),el(),await Promise.allSettled([i().then(()=>{o(),Na(),c(()=>{o(),Na()})}),Ot(),vC(),ji()]),window.__tableBlocks=[],chrome.runtime.onMessage.addListener(e=>{if(e.type===`SCHEDULED_SESSION_UPDATED`){let t=e.sessionId;t===N.activeSessionId?EC().catch(()=>{}):t&&(Ni(t).catch(()=>{}),document.dispatchEvent(new CustomEvent(`session-cache-invalidate`,{detail:{sessionId:t}})));return}if(e.type===`CLOSE_SIDEPANEL`){a.debug(`[SidePanel] recei to CLOSE_SIDEPANEL,closesidebar`);try{window.close()}catch{}return}if(e.type===`SELECTION_AI_SEARCH`&&e.prompt&&(a.debug(`[SidePanel] received selectedtext AI search:`,e.selectedText?.substring(0,50)),e.selectedText&&bL(e.selectedText),ZC(e.prompt,e.selectedText),chrome.storage.session.remove(`pendingSelectionSearch`).catch(()=>{})),e.type===`FILL_SIDEPANEL_INPUT`&&e.text&&(a.debug(`[SidePanel] received follow-upfill:`,e.text?.substring(0,50)),QC(e.text),chrome.storage.session.remove(`pendingFillInput`).catch(()=>{})),e.type===`DIRECT_SEND`&&e.text&&(a.debug(`[SidePanel] received directsend:`,e.text?.substring(0,50)),e.selectedText&&bL(e.selectedText),$C(e.text,e.selectedText||``),chrome.storage.session.remove(`pendingDirectSend`).catch(()=>{})),e.type===`AGENT_STATUS_CHANGE`&&(a.debug(`[SidePanel] recei to Agent status change:`,e.connected,e.status),N.agentPlatform={...N.agentPlatform,connected:e.connected},wL(N.agentPlatform),Xm(),Ia(),e.connected&&ML()),e.type===`AGENT_CONNECTION_CHANGED`){if(a.debug(`[SidePanel] recei to Agent connection statuschanged:`,e.connected,e.agentId),!e.connected){N.agentPlatform={connected:!1},wL(N.agentPlatform),Xm(),Ia();return}e.agentId&&(async()=>{try{let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),t=nL(e.pairedAgents).find(t=>t.id===e.activeAgentId&&!t.disabled);if(!t){N.agentPlatform={connected:!1},wL(N.agentPlatform),Xm(),Ia(),Tv();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){N.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&&N.agentVersions.set(e.activeAgentId,t.version),t.workdir&&N.agentWorkdirs.set(e.activeAgentId,t.workdir),t.homeDir&&N.agentHomeDirs.set(e.activeAgentId,t.homeDir);let n=OL(t.platformName||t.platform,t.arch);n&&N.agentSystemInfos.set(e.activeAgentId,n)}else N.agentPlatform={connected:!1}}else N.agentPlatform={connected:!1}}catch{N.agentPlatform={connected:!1}}else try{let n=await fetch(`${t.url}/api/status`,{cache:`no-cache`});if(n.ok){let t=await n.json();N.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&&N.agentVersions.set(e.activeAgentId,t.version);let r=OL(t.platformName||t.platform,t.arch);r&&N.agentSystemInfos.set(e.activeAgentId,r)}else N.agentPlatform={connected:!1}}catch{N.agentPlatform={connected:!1}}}catch{N.agentPlatform={connected:!1}}wL(N.agentPlatform),Xm(),Ia(),Tv()})()}e.type===`SCREENSHOT_RESULT`&&e.dataUrl&&(a.debug(`[SidePanel] received pageshortcutscreenshotresult:`,e.mode),th(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(a.debug(`[SidePanel] Tab switch, new Tab ID:`,t.tabId),!await e(t.tabId)){a.debug(`[SidePanel] Tab 无侧边栏,保持 currentTabId:`,N.currentTabId);return}N.currentTabId=t.tabId}),chrome.tabs.onUpdated.addListener(async(e,t)=>{t.status===`complete`&&N.currentTabId===e&&a.debug(`[SidePanel] current Tab page update:`,t)}),typeof marked<`u`&&(marked.setOptions({breaks:!0,gfm:!0}),a.debug(`[SidePanel] Marked library loaded`));let t=document.getElementById(`userInput`),n=document.getElementById(`sendBtn`),s=document.getElementById(`clearChatBtn`),l=document.getElementById(`exportChatBtn`),u=document.getElementById(`chatContainer`),d=document.getElementById(`tempDisplay`),f=document.getElementById(`tempDropdown`),p=document.getElementById(`tempPresetList`),m=document.getElementById(`tempSlider`),h=document.getElementById(`tempNumberInput`);function g(){if(!t||N.isScrolling)return;t.style.height=`auto`;let e=t.scrollHeight;e<=50?t.style.height=``:t.style.height=Math.min(e,100)+`px`,Tt()}chrome.storage.local.get([`temperature`,`topP`,`selectedTempIndex`],e=>{(!N.activeAgentId||N.activeAgentId==="default")&&(e.temperature!==void 0&&(N.temperature=e.temperature),e.topP!==void 0&&(N.topP=e.topP),e.selectedTempIndex!==void 0&&(N.selectedTempIndex=e.selectedTempIndex)),_()});function _(){m&&(m.value=N.temperature),h&&(h.value=N.temperature.toFixed(2));let e=document.getElementById(`tempIconValue`);e&&(e.textContent=N.temperature.toFixed(2)),y()}function v(){let e=0,t=Math.abs(Rn[0].temp-N.temperature);for(let n=1;n<Rn.length;n++){let r=Math.abs(Rn[n].temp-N.temperature);r<t&&(t=r,e=n)}return e}function y(){let e=v();p.innerHTML=Rn.map((t,n)=>`
|
|
2782
|
+
`}).join(``);let o=document.getElementById(`agentDdRestartBtn`),s=document.getElementById(`agentDdUpdateBtn`),c=document.getElementById(`agentDdStopBtn`),l=!!(e&&n);o&&(o.disabled=!l),s&&(s.disabled=!l),c&&(c.disabled=!l)}async function AL(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 jL(e,t){return e?t&&e.startsWith(t)?`~`+e.substring(t.length):e:``}function ML(e,t){return e||``}function NL(e,t){let n=document.querySelector(`.agent-dd-item[data-agent-id="${e}"]`);if(!n)return;let i=n.querySelector(`.agent-dd-item-dot`),a=n.querySelector(`.agent-dd-item-status`),o=n.classList.contains(`active`);i&&(i.classList.remove(`checking`,`connected`,`disconnected`,`online`,`offline`),i.classList.add(o?t?`connected`:`disconnected`:t?`online`:`offline`)),a&&(o?a.textContent=r(t?`sidePanel.agentConnected`:`sidePanel.notConnected`):a.textContent===r(`sidePanel.agentChecking`)&&(a.textContent=r(t?`sidePanel.agentOnline`:`sidePanel.agentOffline`)))}function PL(e,t){if(!t)return;let n=document.querySelector(`.agent-dd-item[data-agent-id="${e}"]`);if(!n)return;let i=n.querySelector(`.agent-dd-item-info`);if(!i)return;let a=jL(t,N.agentHomeDirs.get(e)),o=i.querySelector(`.agent-dd-item-workdir`);o?(o.textContent=a,o.title=r(`sidePanel.workingDirectory`,{path:t})):(o=document.createElement(`span`),o.className=`agent-dd-item-workdir`,o.title=r(`sidePanel.workingDirectory`,{path:t}),o.textContent=a,i.appendChild(o))}window.updateAgentItemWorkdir=PL;async function FL(){try{let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),t=rL(e.pairedAgents),n=e.activeAgentId;await Promise.all(t.filter(e=>!e.disabled).map(async e=>{let t=await AL(e.url,e.token),r=t.online;t.version&&N.agentVersions.set(e.id,t.version),t.workdir&&N.agentWorkdirs.set(e.id,t.workdir),t.homeDir&&N.agentHomeDirs.set(e.id,t.homeDir);let i=ML(t.platformName,t.arch);i&&N.agentSystemInfos.set(e.id,i),t.workdir&&PL(e.id,t.workdir),NL(e.id,r),e.id===n&&r!==(N.agentPlatform?.connected===!0)&&(N.agentPlatform={...N.agentPlatform,connected:r},OL(N.agentPlatform,!0),r&&IL(e))}))}catch{}}async function IL(e){try{let t=e;if(!t){let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),n=rL(e.pairedAgents),r=e.activeAgentId;t=n.find(e=>e.id===r&&!e.disabled)}if(!t||!t.url){N.agentPlatform={...N.agentPlatform,connected:!0},OL(N.agentPlatform),Xm();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){N.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&&N.agentVersions.set(t.id,e.version),e.workdir&&(N.agentWorkdirs.set(t.id,e.workdir),PL(t.id,e.workdir)),e.homeDir&&N.agentHomeDirs.set(t.id,e.homeDir);let n=ML(e.platformName||e.platform,e.arch);n&&N.agentSystemInfos.set(t.id,n),OL(N.agentPlatform),Xm();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();N.agentPlatform={platformName:e.platformName||e.platform||`Unknown`,platform:e.platform||`unknown`,arch:e.arch||`unknown`,connected:!0},OL(N.agentPlatform),Xm();return}}catch{}N.agentPlatform={...N.agentPlatform,connected:!0},OL(N.agentPlatform),Xm()}catch{N.agentPlatform={...N.agentPlatform,connected:!0},OL(N.agentPlatform),Xm()}}var LL=null;function RL(e,t=20){LL&&clearInterval(LL);let n=0;LL=setInterval(async()=>{if(n++,n>t||!e){clearInterval(LL),LL=null;return}try{let t=rL((await chrome.storage.local.get([`pairedAgents`])).pairedAgents).find(t=>t.id===e);if(!t){clearInterval(LL),LL=null;return}let n=await AL(t.url,t.token);if(n.online){clearInterval(LL),LL=null,n.version&&N.agentVersions.set(e,n.version),n.workdir&&N.agentWorkdirs.set(e,n.workdir),n.homeDir&&N.agentHomeDirs.set(e,n.homeDir);let r=ML(n.platformName,n.arch);r&&N.agentSystemInfos.set(e,r),n.workdir&&PL(e,n.workdir),await IL(t),NL(e,!0)}}catch{}},3e3)}function zL(){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 BL(){let e=document.getElementById(`headerAgentTrigger`),t=document.getElementById(`headerAgentDropdown`),n=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||!t)return;e.addEventListener(`click`,e=>{e.stopPropagation();let n=t.style.display!==`none`;t.style.display=n?`none`:``,n||(zL(),OL(N.agentPlatform||{}),FL())}),document.addEventListener(`click`,n=>{!t.contains(n.target)&&n.target!==e&&(t.style.display=`none`)}),n.addEventListener(`click`,async e=>{e.stopPropagation(),N.activeAgentId;let t=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),n=rL(t.pairedAgents).find(e=>e.id===t.activeAgentId);n?.url&&(await navigator.clipboard.writeText(n.url),L(r(`sidePanel.agentAddressCopied`),`success`))}),i.addEventListener(`click`,async()=>{t.style.display=`none`,await chrome.storage.local.set({optionsInitialTab:`agent`});let e=await chrome.tabs.query({}),n=chrome.runtime.getURL(`options/index.html`),r=e.find(e=>e.url&&e.url.startsWith(n));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()=>{t.style.display=`none`;let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),n=rL(e.pairedAgents).find(t=>t.id===e.activeAgentId),i=n?.name||r(`sidePanel.unknownAgent`),a=n?.url||r(`sidePanel.unknownAgent`);if(await window.showCustomConfirm(r(`sidePanel.restartAgentConfirm`,{name:i,url:a}),r(`sidePanel.restartAgentTitle`)))try{chrome.runtime.sendMessage({type:`AGENT_RESTART`},async e=>{e?.success?(L(r(`sidePanel.agentRestarting`),`success`),N.agentPlatform={...N.agentPlatform,connected:!1},await OL(N.agentPlatform,!0),n?.id&&NL(n.id,!1),RL(n?.id)):L(r(`sidePanel.restartFailed`,{error:e?.error||r(`sidePanel.unknownError`)}),`error`)})}catch(e){L(r(`sidePanel.restartRequestFailed`,{error:e.message}),`error`)}}),o.addEventListener(`click`,async()=>{t.style.display=`none`;let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),n=rL(e.pairedAgents).find(t=>t.id===e.activeAgentId),i=n?.name||r(`sidePanel.unknownAgent`),a=n?.url||r(`sidePanel.unknownAgent`);if(await window.showCustomConfirm(r(`sidePanel.updateAgentConfirm`,{name:i,url:a}),r(`sidePanel.updateAgentTitle`))){L(r(`sidePanel.agentUpdating`),`info`);try{chrome.runtime.sendMessage({type:`AGENT_UPDATE`},async e=>{e?.success?(L(r(`sidePanel.agentUpdateRestarting`),`success`),N.agentPlatform={...N.agentPlatform,connected:!1},await OL(N.agentPlatform,!0),n?.id&&NL(n.id,!1),RL(n?.id)):L(r(`sidePanel.updateFailed`,{error:e?.error||r(`sidePanel.unknownError`)}),`error`)})}catch(e){L(r(`sidePanel.updateRequestFailed`,{error:e.message}),`error`)}}}),s.addEventListener(`click`,async()=>{t.style.display=`none`;let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),n=rL(e.pairedAgents).find(t=>t.id===e.activeAgentId),i=n?.name||r(`sidePanel.unknownAgent`),a=n?.url||r(`sidePanel.unknownAgent`);if(await window.showCustomConfirm(r(`sidePanel.stopAgentConfirm`,{name:i,url:a}),r(`sidePanel.stopAgentTitle`)))try{chrome.runtime.sendMessage({type:`AGENT_STOP`},async e=>{e?.success?(L(r(`sidePanel.agentStopped`),`success`),N.agentPlatform={...N.agentPlatform,connected:!1},await OL(N.agentPlatform,!0),n?.id&&NL(n.id,!1)):L(r(`sidePanel.stopFailed`,{error:e?.error||r(`sidePanel.unknownError`)}),`error`)})}catch(e){L(r(`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=r(`sidePanel.agentChecking`)}),await FL(),L(r(`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,t){let n=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),i=rL(n.pairedAgents);switch(e){case`enable`:i=i.map(e=>e.id===t?{...e,disabled:!1}:e),await chrome.storage.local.set({pairedAgents:i});break;case`disable`:{i=i.map(e=>e.id===t?{...e,disabled:!0}:e);let e=n.activeAgentId;n.activeAgentId===t&&(e=i.find(e=>e.id!==t&&!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:t}),chrome.runtime.sendMessage({type:`AGENT_CONNECTION_CHANGED`,connected:!0,agentId:t});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===t);if(!await window.showCustomConfirm(r(`sidePanel.deleteAgentTitle`),r(`sidePanel.deleteAgentConfirm`,{name:e?.name||t})))return;i=i.filter(e=>e.id!==t);let a=n.activeAgentId===t?i.find(e=>!e.disabled)?.id||null:n.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 VL=new Map,HL=8;function UL(e,t){for(VL.has(e)&&VL.delete(e),VL.set(e,t);VL.size>HL;)VL.delete(VL.keys().next().value)}function WL(e){let t=VL.get(e);if(t!==void 0)return VL.delete(e),VL.set(e,t),t}function GL(e){VL.delete(e)}document.addEventListener(`DOMContentLoaded`,async()=>{await dt(),mt(()=>{Yt()}),el(),await Promise.allSettled([i().then(()=>{o(),Na(),c(()=>{o(),Na()})}),kt(),vC(),ji()]),window.__tableBlocks=[],chrome.runtime.onMessage.addListener(e=>{if(e.type===`SCHEDULED_SESSION_UPDATED`){let t=e.sessionId;t===N.activeSessionId?EC().catch(()=>{}):t&&(Ni(t).catch(()=>{}),document.dispatchEvent(new CustomEvent(`session-cache-invalidate`,{detail:{sessionId:t}})));return}if(e.type===`CLOSE_SIDEPANEL`){a.debug(`[SidePanel] recei to CLOSE_SIDEPANEL,closesidebar`);try{window.close()}catch{}return}if(e.type===`SELECTION_AI_SEARCH`&&e.prompt&&(a.debug(`[SidePanel] received selectedtext AI search:`,e.selectedText?.substring(0,50)),e.selectedText&&xL(e.selectedText),ZC(e.prompt,e.selectedText),chrome.storage.session.remove(`pendingSelectionSearch`).catch(()=>{})),e.type===`FILL_SIDEPANEL_INPUT`&&e.text&&(a.debug(`[SidePanel] received follow-upfill:`,e.text?.substring(0,50)),QC(e.text),chrome.storage.session.remove(`pendingFillInput`).catch(()=>{})),e.type===`DIRECT_SEND`&&e.text&&(a.debug(`[SidePanel] received directsend:`,e.text?.substring(0,50)),e.selectedText&&xL(e.selectedText),$C(e.text,e.selectedText||``),chrome.storage.session.remove(`pendingDirectSend`).catch(()=>{})),e.type===`AGENT_STATUS_CHANGE`&&(a.debug(`[SidePanel] recei to Agent status change:`,e.connected,e.status),N.agentPlatform={...N.agentPlatform,connected:e.connected},OL(N.agentPlatform),Xm(),Ia(),e.connected&&IL()),e.type===`AGENT_CONNECTION_CHANGED`){if(a.debug(`[SidePanel] recei to Agent connection statuschanged:`,e.connected,e.agentId),!e.connected){N.agentPlatform={connected:!1},OL(N.agentPlatform),Xm(),Ia();return}e.agentId&&(async()=>{try{let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),t=rL(e.pairedAgents).find(t=>t.id===e.activeAgentId&&!t.disabled);if(!t){N.agentPlatform={connected:!1},OL(N.agentPlatform),Xm(),Ia(),Tv();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){N.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&&N.agentVersions.set(e.activeAgentId,t.version),t.workdir&&N.agentWorkdirs.set(e.activeAgentId,t.workdir),t.homeDir&&N.agentHomeDirs.set(e.activeAgentId,t.homeDir);let n=ML(t.platformName||t.platform,t.arch);n&&N.agentSystemInfos.set(e.activeAgentId,n)}else N.agentPlatform={connected:!1}}else N.agentPlatform={connected:!1}}catch{N.agentPlatform={connected:!1}}else try{let n=await fetch(`${t.url}/api/status`,{cache:`no-cache`});if(n.ok){let t=await n.json();N.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&&N.agentVersions.set(e.activeAgentId,t.version);let r=ML(t.platformName||t.platform,t.arch);r&&N.agentSystemInfos.set(e.activeAgentId,r)}else N.agentPlatform={connected:!1}}catch{N.agentPlatform={connected:!1}}}catch{N.agentPlatform={connected:!1}}OL(N.agentPlatform),Xm(),Ia(),Tv()})()}e.type===`SCREENSHOT_RESULT`&&e.dataUrl&&(a.debug(`[SidePanel] received pageshortcutscreenshotresult:`,e.mode),th(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(a.debug(`[SidePanel] Tab switch, new Tab ID:`,t.tabId),!await e(t.tabId)){a.debug(`[SidePanel] Tab 无侧边栏,保持 currentTabId:`,N.currentTabId);return}N.currentTabId=t.tabId}),chrome.tabs.onUpdated.addListener(async(e,t)=>{t.status===`complete`&&N.currentTabId===e&&a.debug(`[SidePanel] current Tab page update:`,t)}),typeof marked<`u`&&(marked.setOptions({breaks:!0,gfm:!0}),a.debug(`[SidePanel] Marked library loaded`));let t=document.getElementById(`userInput`),n=document.getElementById(`sendBtn`),s=document.getElementById(`clearChatBtn`),l=document.getElementById(`exportChatBtn`),u=document.getElementById(`chatContainer`),d=document.getElementById(`tempDisplay`),f=document.getElementById(`tempDropdown`),p=document.getElementById(`tempPresetList`),m=document.getElementById(`tempSlider`),h=document.getElementById(`tempNumberInput`);function g(){if(!t||N.isScrolling)return;t.style.height=`auto`;let e=t.scrollHeight;e<=50?t.style.height=``:t.style.height=Math.min(e,100)+`px`,Et()}chrome.storage.local.get([`temperature`,`topP`,`selectedTempIndex`],e=>{(!N.activeAgentId||N.activeAgentId==="default")&&(e.temperature!==void 0&&(N.temperature=e.temperature),e.topP!==void 0&&(N.topP=e.topP),e.selectedTempIndex!==void 0&&(N.selectedTempIndex=e.selectedTempIndex)),_()});function _(){m&&(m.value=N.temperature),h&&(h.value=N.temperature.toFixed(2));let e=document.getElementById(`tempIconValue`);e&&(e.textContent=N.temperature.toFixed(2)),y()}function v(){let e=0,t=Math.abs(Rn[0].temp-N.temperature);for(let n=1;n<Rn.length;n++){let r=Math.abs(Rn[n].temp-N.temperature);r<t&&(t=r,e=n)}return e}function y(){let e=v();p.innerHTML=Rn.map((t,n)=>`
|
|
2776
2783
|
<div class="temp-preset-item ${n===e?`selected`:``}" data-index="${n}">
|
|
2777
2784
|
<div class="temp-preset-radio"></div>
|
|
2778
2785
|
<div class="temp-preset-info">
|
|
@@ -2781,15 +2788,15 @@ Are you sure you want to stop the agent service? You will not be able to connect
|
|
|
2781
2788
|
</div>
|
|
2782
2789
|
<div class="temp-preset-value">${t.temp.toFixed(2)}</div>
|
|
2783
2790
|
</div>
|
|
2784
|
-
`).join(``),p.querySelectorAll(`.temp-preset-item`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),b(parseInt(e.dataset.index))})})}function b(e){let t=Rn[e];t&&(N.selectedTempIndex=e,N.temperature=t.temp,_(),
|
|
2791
|
+
`).join(``),p.querySelectorAll(`.temp-preset-item`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),b(parseInt(e.dataset.index))})})}function b(e){let t=Rn[e];t&&(N.selectedTempIndex=e,N.temperature=t.temp,_(),dL(N.temperature,N.topP,N.selectedTempIndex))}m.addEventListener(`input`,e=>{e.stopPropagation();let t=parseFloat(e.target.value);isNaN(t)&&(t=0),t=Math.max(0,Math.min(1,t)),N.temperature=t,h.value=t.toFixed(2);let n=document.getElementById(`tempIconValue`);n&&(n.textContent=t.toFixed(2)),y(),dL(N.temperature,N.topP,v())}),h.addEventListener(`change`,e=>{e.stopPropagation();let t=parseFloat(e.target.value);isNaN(t)&&(t=0),t=Math.max(0,Math.min(1,t)),N.temperature=t,m.value=t,h.value=t.toFixed(2);let n=document.getElementById(`tempIconValue`);n&&(n.textContent=t.toFixed(2)),y(),dL(N.temperature,N.topP,v())}),d&&f&&(d.addEventListener(`click`,e=>{e.stopPropagation(),f.classList.toggle(`show`)}),document.addEventListener(`click`,e=>{let t=document.querySelector(`.temp-selector`);t&&!t.contains(e.target)&&f.classList.remove(`show`)})),document.addEventListener(`mousedown`,e=>{VO(e.target)&&(N.lastMouseX=e.clientX,N.lastMouseY=e.clientY)}),document.addEventListener(`mouseup`,e=>{VO(e.target)&&(N.lastMouseX=e.clientX,N.lastMouseY=e.clientY,N.enableSelectionQuery&&setTimeout(()=>{let e=window.getSelection();if(e&&!e.isCollapsed&&e.toString().trim()){let t=e.toString().trim();VO(e.anchorNode)&&(N.lastSelectedText=t,N.currentSelectionRange=e.getRangeAt(0).cloneRange(),xL(t),TL(e,t,N.lastMouseX,N.lastMouseY))}else VO(e.anchorNode)||(N.lastSelectedText=``,N.currentSelectionRange=null,window.hideFloatingMenu())},50))});let w=``,T=null;async function E(){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!==w&&(w=n,xL(n.trim())):w=``}}catch{}}function D(){T&&=(clearInterval(T),null),N.enableSelectionQuery&&(T=setInterval(E,500))}D(),chrome.storage.onChanged.addListener((e,t)=>{if(t===`local`&&`enableSelectionQuery`in e){N.enableSelectionQuery=e.enableSelectionQuery.newValue;let t=document.getElementById(`enableSelectionQueryBtn`);t&&(t.checked=N.enableSelectionQuery),D()}}),await C(),rP(),chrome.storage.local.get([`modelName`,`customModels`,`customPrompts`,`systemPrompt`,`inputHistory`,`agentPlatform`,`enableImageInput`,`imageModelName`,`imageApiBase`,`imageApiKey`,`enableFileInput`],e=>{let t=e.modelName;t&&(N.currentModel=t),N.customPrompts=e.customPrompts||[],N.systemPrompt=e.systemPrompt||``,N.inputHistory=e.inputHistory||[],e.agentPlatform&&(N.agentPlatform=e.agentPlatform),OL(N.agentPlatform),chrome.runtime.sendMessage({type:`TRIGGER_AGENT_HEALTH_CHECK`}).catch(()=>{}),uL(),N.enableImageInput=e.enableImageInput||!1,N.imageModelName=e.imageModelName||``,N.imageApiBase=e.imageApiBase||``,N.imageApiKey=S(e.imageApiKey)||``,N.enableFileInput=!0,Jm(),Xm(),ww(),bL(e.customModels,()=>{t&&yL(t)})}),chrome.storage.onChanged.addListener((e,t)=>{if(t===`local`){if(e.customModels&&bL(e.customModels.newValue||[],()=>{yL(N.currentModel)}),e.modelName){let t=e.modelName.newValue;t&&(!N.activeAgentId||N.activeAgentId==="default")&&(N.currentModel=t,yL(t))}if(e.enableImageInput&&(N.enableImageInput=e.enableImageInput.newValue,Jm()),e.enableFileInput&&(N.enableFileInput=e.enableFileInput.newValue,Xm()),e.enableExecutionLog&&(N.chatConfig.enableExecutionLog=e.enableExecutionLog.newValue),e.showMessageTimestamp){let t=e.showMessageTimestamp.newValue!==!1;N.chatConfig.showMessageTimestamp=t,aw(t)}e.systemPrompt&&(N.systemPrompt=e.systemPrompt.newValue||``),e.imageModelName&&(N.imageModelName=e.imageModelName.newValue||``),e.imageApiBase&&(N.imageApiBase=e.imageApiBase.newValue||``),e.imageApiKey&&(N.imageApiKey=S(e.imageApiKey.newValue)||``)}}),await EC(),await hI();let O=await chrome.storage.session.get([`pendingSelectionSearch`,`pendingFillInput`,`pendingDirectSend`]),k=[];if(O.pendingSelectionSearch&&O.pendingSelectionSearch.selectedText){let{prompt:e,selectedText:t}=O.pendingSelectionSearch;a.debug(`[SidePanel] pending selected textsearch:`,t?.substring(0,50)),xL(t),setTimeout(()=>{ZC(e,t)},500),k.push(`pendingSelectionSearch`)}if(O.pendingFillInput&&O.pendingFillInput.text){let{text:e}=O.pendingFillInput;a.debug(`[SidePanel] pending fill trackasktext:`,e?.substring(0,50)),setTimeout(()=>{QC(e)},500),k.push(`pendingFillInput`)}if(O.pendingDirectSend&&O.pendingDirectSend.text){let{text:e,selectedText:t}=O.pendingDirectSend;a.debug(`[SidePanel] pending directsend text:`,e?.substring(0,50)),t&&xL(t),setTimeout(()=>{$C(e,t||``)},500),k.push(`pendingDirectSend`)}k.length>0&&await chrome.storage.session.remove(k);let A=document.getElementById(`userInput`);A&&A.focus(),document.addEventListener(`session-switched`,e=>{let{sessionId:t,previousSessionId:n}=e.detail||{},i=document.getElementById(`chatContainer`),o=document.getElementById(`userInput`);if(!i)return;let s=n&&N.messageHistory?.some(e=>e.resumable);if(n&&!N.pendingCallApiSessionIds.has(n)&&!s){let e=hx(i);e&&UL(n,e)}let c=document.getElementById(`imagePreviewBar`);N.attachedImages.length>0&&c&&c.style.display===`none`&&(N.attachedImages=[]),N.executionLogListener&&=(chrome.runtime.onMessage.removeListener(N.executionLogListener),null),te(),o&&o.focus();let l=N.pendingCallApiSessionIds.has(t)&&!!N.pendingCancelApi,u=WL(t),d=N.messageHistory&&N.messageHistory.length>0;if(u&&!l&&d){if(i.innerHTML=u,mw(i),$t(),sn(),!e.detail?.skipScrollRestore){let e=`scrollPosition_`+(t||`default`);chrome.storage.local.get([e],t=>{t[e]!==void 0&&setTimeout(()=>{let n=document.getElementById(`chatContainer`);n&&(n.scrollTop=t[e])},150)})}Qx();return}if(i.innerHTML=``,d){if(N.messageHistory.forEach(e=>{e.htmlContent?pw(e.htmlContent,e.messageId,e.resumable):iw(e.role,e.content,!1,e.executionLog||[],e.reflectionScore,e.wasRevised,null,e.messageId,[],e.resumable||!1,e.timestamp??null)}),sw(),lw(),$t(),sn(),!N.pendingCallApiSessionIds.has(t)){let e=hx(i);e&&UL(t,e)}Qx()}else{let e=document.createElement(`div`);e.className=`welcome-message`,e.innerHTML=`
|
|
2785
2792
|
<div class="icon-wrapper">
|
|
2786
2793
|
<div class="icon">💬</div>
|
|
2787
2794
|
</div>
|
|
2788
2795
|
<h2>${r(`sidePanel.welcomeTitle`)}</h2>
|
|
2789
2796
|
<p>${r(`sidePanel.welcomeSubtitle`)}</p>
|
|
2790
|
-
`,i.appendChild(e)}if(a.debug(`[SidePanel] session-switched: pendingTask?`,l,`pendingSessionIds:`,[...N.pendingCallApiSessionIds],`activeSessionId:`,t,`hasCancelApi:`,!!N.pendingCancelApi),l&&(a.debug(`[SidePanel] switch back tobackground task session,rebuildstreamingoutput element`),aC(t)),yD(t),!e.detail?.skipScrollRestore){let e=`scrollPosition_`+(t||`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 M(async()=>{let{updateScrollButtonState:e}=await Promise.resolve().then(()=>hS);return{updateScrollButtonState:e}},void 0);r()},150)})}}),document.addEventListener(`session-cache-invalidate`,e=>{let{sessionId:t}=e.detail||{};t&&VL(t)}),document.querySelectorAll(`.model-option`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation();let n=e.dataset.value;N.currentModel=n,vL(n),cL(n),bE()})}),document.addEventListener(`agent-model-changed`,()=>{vL(N.currentModel);let e=document.getElementById(`tempSlider`),t=document.getElementById(`tempNumberInput`),n=document.getElementById(`tempIconValue`);e&&(e.value=N.temperature),t&&(t.value=N.temperature.toFixed(2)),n&&(n.textContent=N.temperature.toFixed(2)),y()}),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`),Ew()),r&&!r.contains(e.target)&&fb();let a=document.getElementById(`fileAtSelector`);if(a&&!a.contains(e.target)&&EP(),i&&!i.contains(e.target)){let t=window.getSelection(),n=u.contains(e.target),r=t&&!t.isCollapsed&&u.contains(t.anchorNode);(!n||!r)&&window.hideFloatingMenu()}});let j=document.getElementById(`stopCompanionBtn`);function ee(){let e=!!(t&&t.value&&t.value.trim());return N.isGenerating&&e}function te(){t&&t.value&&t.value.trim();let e=N.isGenerating,i=ee();n.classList.toggle(`queue-mode`,i),n.classList.toggle(`stop-mode`,e&&!i),i?(n.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>`,n.title=r(`queue.enqueueBtn`)):e?(n.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>`,n.title=r(`sidePanel.sendBtnStop`)):(n.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>`,n.title=r(`sidePanel.sendBtnSend`)),n.disabled=!1,n.style.opacity=``,n.style.cursor=``,j&&(j.style.display=i?``:`none`,j.disabled=!1,j.style.opacity=``,j.style.cursor=``)}n.addEventListener(`click`,()=>{if(!N.isGenerating){XC();return}t&&t.value&&t.value.trim()?md():pC(n)}),j?.addEventListener(`click`,()=>pC(j));function ne(e){if(!N.isGenerating)return!1;let t=N.activeSessionId;return t?bd(t)?(yd(t),pC(j&&j.style.display!==`none`?j:e||n)?(L(r(`queue.stopAndSendStarted`),`success`,2500),!0):(xd(t),!0)):(L(r(`queue.stopAndSendEmpty`),`warning`,3e3),!1):!1}function re(e,{isPrimarySend:t=!1}={}){if(!e)return;let n=()=>t&&ee();e.addEventListener(`contextmenu`,t=>{n()||!N.isGenerating||!bd(N.activeSessionId)||(t.preventDefault(),ne(e))});let r=null,i=()=>{r&&=(clearTimeout(r),null)};e.addEventListener(`pointerdown`,t=>{t.pointerType===`mouse`&&t.button!==0||n()||!N.isGenerating||!bd(N.activeSessionId)||(i(),r=setTimeout(()=>{r=null,ne(e)},600))});for(let t of[`pointerup`,`pointerleave`,`pointercancel`])e.addEventListener(t,i)}re(n,{isPrimarySend:!0}),re(j),document.addEventListener(`queue-stop-and-send`,()=>{ne(j&&j.style.display!==`none`?j:n)}),document.addEventListener(`generating-state-changed`,te),t.addEventListener(`input`,te),document.addEventListener(`voice-draft-written`,te);let ie=document.getElementById(`shortcutsBtn`),ae=document.getElementById(`shortcutsModal`),oe=document.getElementById(`shortcutsCloseBtn`);function se(){ae&&(ae.style.display=`flex`)}function ce(){ae&&(ae.style.display=`none`)}ie&&ie.addEventListener(`click`,e=>{e.stopPropagation(),se();let t=document.getElementById(`headerMoreDropdown`);t&&t.classList.remove(`show`)}),oe&&oe.addEventListener(`click`,ce),ae&&ae.addEventListener(`click`,e=>{e.target===ae&&ce()});let le=BO();Nx(),qu({adjustInputHeight:g}).catch(e=>{a.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`?ya():va()}if(e.key===`Escape`&&Hu()){e.preventDefault();return}if(!(e.key===`Escape`&&le.handleEscape())){if(e.key===`Escape`&&ae&&ae.style.display!==`none`){ce();return}if(e.altKey&&e.code===`Slash`){e.preventDefault(),se();return}if(e.altKey&&!e.shiftKey&&e.code===`KeyS`&&!e.ctrlKey&&!e.metaKey){e.preventDefault(),Qm();return}if(e.altKey&&e.shiftKey&&e.code===`KeyS`&&!e.ctrlKey&&!e.metaKey){e.preventDefault(),$m();return}if(au(e)){e.preventDefault(),Bu();return}if(e.altKey&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&e.code===`KeyN`){e.preventDefault(),ns();return}if(e.altKey&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&e.code===`KeyW`){e.preventDefault(),ac();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){bw(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`;le.jumpToMessage(t,e.ctrlKey||e.metaKey),le.updateActiveQuestion();return}}}),t.addEventListener(`keydown`,e=>{let n=document.getElementById(`promptSelector`),r=document.getElementById(`promptDropdown`),i=document.getElementById(`agentAtSelector`),a=document.getElementById(`agentAtDropdown`);if(i.style.display!==`none`&&a.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(sb);for(let e=0;e<t.length;e++)if(r=(r+1)%t.length,n(t[r])){mb(t[r]);break}return}let r,i;n?(r=document.getElementById(`agentAtList`),i=N.selectedAgentAtIndex):sb===`pages`?(r=document.getElementById(`agentPageList`),i=N.selectedPageIndex):sb===`proxies`?(r=document.getElementById(`agentProxyList`),i=N.selectedProxyAtIndex):sb===`knowledge`?(r=document.getElementById(`agentKnowledgeList`),i=N.selectedKnowledgeAtIndex):(r=document.getElementById(`agentAtList`),i=N.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?(N.selectedAgentAtIndex=t,Ob(a)):sb===`proxies`?(N.selectedProxyAtIndex=t,Ob(a)):sb===`knowledge`?(N.selectedKnowledgeAtIndex=t,Ob(a)):sb===`pages`?(N.selectedPageIndex=t,Yb(a)):(N.selectedAgentAtIndex=t,Ob(a));return}else if(e.key===`ArrowUp`){e.preventDefault();let t=i<0||i===0?o-1:i-1;n?(N.selectedAgentAtIndex=t,Ob(a)):sb===`proxies`?(N.selectedProxyAtIndex=t,Ob(a)):sb===`knowledge`?(N.selectedKnowledgeAtIndex=t,Ob(a)):sb===`pages`?(N.selectedPageIndex=t,Yb(a)):(N.selectedAgentAtIndex=t,Ob(a));return}else if(e.key===`Enter`&&i>=0){e.preventDefault(),a[i].click(),(e.ctrlKey||e.metaKey)&&fb();return}else if(e.key===`Escape`){fb();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&&(N.selectedFileAtIndex=e.key===`ArrowDown`?N.selectedFileAtIndex<0?0:(N.selectedFileAtIndex+1)%r:N.selectedFileAtIndex<0||N.selectedFileAtIndex===0?r-1:N.selectedFileAtIndex-1,jP(n));return}if(e.key===`Enter`&&r>0&&N.selectedFileAtIndex>=0){e.preventDefault(),n[N.selectedFileAtIndex].click();return}if(e.key===`Escape`){e.preventDefault(),EP();return}}if(n.style.display!==`none`&&r.classList.contains(`show`)){if(N.showMergedList){let t=r.querySelectorAll(`#promptList .prompt-item`),n=t.length;if(e.key===`ArrowDown`){e.preventDefault(),N.selectedPromptIndex<0?N.selectedPromptIndex=0:N.selectedPromptIndex=(N.selectedPromptIndex+1)%n,jw(t);return}if(e.key===`ArrowUp`){e.preventDefault(),N.selectedPromptIndex<0||N.selectedPromptIndex===0?N.selectedPromptIndex=n-1:--N.selectedPromptIndex,jw(t);return}if(e.key===`Enter`&&N.selectedPromptIndex>=0){e.preventDefault();let n=t[N.selectedPromptIndex];n.dataset.type===`skill`||n.dataset.type===`mcp`?(n.click(),(e.ctrlKey||e.metaKey)&&Ew()):e.ctrlKey||e.metaKey?Mw(n.dataset.code):Nw(n.dataset.code);return}if(e.key===`Escape`){Ew();return}return}if(N.activeDropdownTab===`skills`){let t=r.querySelectorAll(`#skillList .skill-list-item`),n=t.length;if(e.key===`ArrowDown`){e.preventDefault(),N.selectedSkillIndex<0?N.selectedSkillIndex=0:N.selectedSkillIndex=(N.selectedSkillIndex+1)%n,$w(t);return}if(e.key===`ArrowUp`){e.preventDefault(),N.selectedSkillIndex<0||N.selectedSkillIndex===0?N.selectedSkillIndex=n-1:--N.selectedSkillIndex,$w(t);return}if(e.key===`Enter`&&N.selectedSkillIndex>=0){e.preventDefault(),t[N.selectedSkillIndex].click(),(e.ctrlKey||e.metaKey)&&Ew();return}if(e.key===`Escape`){Ew();return}if(e.key===`Tab`){e.preventDefault();let t=document.getElementById(`mcpTab`);t&&t.style.display!==`none`?oT(`mcp`):oT(`prompts`);return}return}if(N.activeDropdownTab===`mcp`){let t=r.querySelectorAll(`#mcpList .mcp-list-item`),n=t.length;if(e.key===`ArrowDown`){e.preventDefault(),N.selectedMcpServiceIndex<0?N.selectedMcpServiceIndex=0:N.selectedMcpServiceIndex=(N.selectedMcpServiceIndex+1)%n,pT(t);return}if(e.key===`ArrowUp`){e.preventDefault(),N.selectedMcpServiceIndex<0||N.selectedMcpServiceIndex===0?N.selectedMcpServiceIndex=n-1:--N.selectedMcpServiceIndex,pT(t);return}if(e.key===`Enter`&&N.selectedMcpServiceIndex>=0){e.preventDefault(),t[N.selectedMcpServiceIndex].click(),(e.ctrlKey||e.metaKey)&&Ew();return}if(e.key===`Escape`){Ew();return}if(e.key===`Tab`){e.preventDefault(),oT(`prompts`);return}return}let t=r.querySelectorAll(`#promptList .prompt-item`),n=t.length;if(e.key===`Tab`){let t=document.getElementById(`skillsTab`),n=document.getElementById(`mcpTab`);if(t&&t.style.display!==`none`){e.preventDefault(),oT(`skills`);return}if(n&&n.style.display!==`none`){e.preventDefault(),oT(`mcp`);return}}if(n!==0&&e.key===`ArrowDown`){e.preventDefault(),N.selectedPromptIndex<0?N.selectedPromptIndex=0:N.selectedPromptIndex=(N.selectedPromptIndex+1)%n,jw(t);return}if(e.key===`ArrowUp`){e.preventDefault(),N.selectedPromptIndex<0||N.selectedPromptIndex===0?N.selectedPromptIndex=n-1:--N.selectedPromptIndex,jw(t);return}if(e.key===`Enter`&&(e.ctrlKey||e.metaKey)&&N.selectedPromptIndex>=0){e.preventDefault();let n=t[N.selectedPromptIndex].dataset.code;Mw(n);return}if(e.key===`Enter`&&N.selectedPromptIndex>=0){e.preventDefault();let n=t[N.selectedPromptIndex].dataset.code;Nw(n);return}if(e.key===`Escape`){Ew();return}}if(e.key===`Escape`){N.inputHistoryIndex>=0&&(N.inputHistoryIndex=-1),t.value&&(t.value=``,t.style.height=`auto`,t.dispatchEvent(new Event(`input`))),e.preventDefault();return}let c=n.style.display!==`none`&&r.classList.contains(`show`),l=i.style.display!==`none`&&a.classList.contains(`show`),u=o.style.display!==`none`&&s.classList.contains(`show`);if(e.key===`ArrowUp`&&N.inputHistoryIndex===-1&&!t.value.trim()&&!ad()&&cI()){e.preventDefault();return}if(!c&&!l&&!u){let n=zF({key:e.key,value:t.value,caret:t.selectionStart,history:N.inputHistory,index:N.inputHistoryIndex});if(n.handled){e.preventDefault(),N.inputHistoryIndex=n.index,t.value=n.value,t.dispatchEvent(new Event(`input`)),t.setSelectionRange(n.value.length,n.value.length);return}}if(e.key===`Enter`&&!e.shiftKey){if(N.isComposing)return;if(e.preventDefault(),EP(),N.isGenerating){if(e.altKey){Pd(t.value);return}md();return}XC()}}),t.addEventListener(`compositionstart`,()=>{N.isComposing=!0}),t.addEventListener(`compositionend`,()=>{N.isComposing=!1}),t.addEventListener(`paste`,e=>{let t=e.clipboardData?.items;if(t)for(let n of t){if(n.type.startsWith(`image/`)&&N.enableImageInput){e.preventDefault();let t=n.getAsFile();t&&zp(t);break}if(n.kind===`file`&&N.enableFileInput){e.preventDefault();let t=n.getAsFile();t&&Em([t]);break}}});let ue=document.getElementById(`fileAttachBtn`),de=document.getElementById(`fileInput`);ue&&de&&(ue.addEventListener(`click`,()=>{de.click()}),de.addEventListener(`change`,async()=>{if(de.files.length>0){let e=Array.from(de.files),t=e.filter(e=>e.type.startsWith(`image/`)),n=e.filter(e=>!e.type.startsWith(`image/`));if(t.length>0)if(N.enableImageInput)for(let e of t)await zp(e);else L(r(`sidePanel.imageNotEnabled`)),Em(t);n.length>0&&Em(n),de.value=``}}));let fe=document.querySelector(`.input-wrapper`),pe=0;fe&&(fe.addEventListener(`dragenter`,e=>{e.preventDefault(),e.stopPropagation(),pe++,fe.classList.add(`drag-over`)}),fe.addEventListener(`dragleave`,e=>{e.preventDefault(),e.stopPropagation(),pe--,pe<=0&&(pe=0,fe.classList.remove(`drag-over`))}),fe.addEventListener(`dragover`,e=>{e.preventDefault(),e.stopPropagation()}),fe.addEventListener(`drop`,async e=>{e.preventDefault(),e.stopPropagation(),pe=0,fe.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){uy([e]);return}}catch(e){a.warn(`[SidePanel] parse workspace dragdata failed:`,e)}}let i=Array.from(e.dataTransfer.files);if(i.length>0){e.preventDefault();let t=i.filter(e=>e.type.startsWith(`image/`)),n=i.filter(e=>!e.type.startsWith(`image/`));if(t.length>0)if(N.enableImageInput)for(let e of t)await zp(e);else L(r(`sidePanel.imageNotEnabled`)),Em(t);n.length>0&&Em(n);return}let o=e.dataTransfer.getData(`text/plain`);if(o&&(e.preventDefault(),t)){t.focus();let e=t.selectionStart??t.value.length,n=t.selectionEnd??t.value.length;t.value=t.value.slice(0,e)+o+t.value.slice(n),t.selectionStart=t.selectionEnd=e+o.length,t.dispatchEvent(new Event(`input`))}}));let me=document.getElementById(`screenshotBtn`);me&&me.addEventListener(`click`,async()=>{if(N.enableImageInput)try{await Qm()}catch(e){a.error(`[SidePanel] screenshot failed:`,e),L(r(`sidePanel.screenshotFailed`))}}),Lp(),t.addEventListener(`wheel`,e=>{N.isScrolling=!0;let n=t.style.height||t.offsetHeight+`px`;t.style.height=n,t.scrollHeight<=t.clientHeight+10&&(e.preventDefault(),e.stopPropagation()),setTimeout(()=>{N.isScrolling=!1},100)},{passive:!1}),t.addEventListener(`input`,e=>{let n=t.value,r=document.getElementById(`promptSelector`),i=document.getElementById(`promptDropdown`);document.getElementById(`agentAtSelector`),document.getElementById(`agentAtDropdown`);let a=n.lastIndexOf(`/`),o=n.lastIndexOf(`@`),s=n.lastIndexOf(`$`),c=e=>{if(e===-1||e!==0&&n[e-1]!==`
|
|
2797
|
+
`,i.appendChild(e)}if(a.debug(`[SidePanel] session-switched: pendingTask?`,l,`pendingSessionIds:`,[...N.pendingCallApiSessionIds],`activeSessionId:`,t,`hasCancelApi:`,!!N.pendingCancelApi),l&&(a.debug(`[SidePanel] switch back tobackground task session,rebuildstreamingoutput element`),aC(t)),yD(t),!e.detail?.skipScrollRestore){let e=`scrollPosition_`+(t||`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 M(async()=>{let{updateScrollButtonState:e}=await Promise.resolve().then(()=>hS);return{updateScrollButtonState:e}},void 0);r()},150)})}}),document.addEventListener(`session-cache-invalidate`,e=>{let{sessionId:t}=e.detail||{};t&&GL(t)}),document.querySelectorAll(`.model-option`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation();let n=e.dataset.value;N.currentModel=n,yL(n),lL(n),bE()})}),document.addEventListener(`agent-model-changed`,()=>{yL(N.currentModel);let e=document.getElementById(`tempSlider`),t=document.getElementById(`tempNumberInput`),n=document.getElementById(`tempIconValue`);e&&(e.value=N.temperature),t&&(t.value=N.temperature.toFixed(2)),n&&(n.textContent=N.temperature.toFixed(2)),y()}),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`),Ew()),r&&!r.contains(e.target)&&fb();let a=document.getElementById(`fileAtSelector`);if(a&&!a.contains(e.target)&&DP(),i&&!i.contains(e.target)){let t=window.getSelection(),n=VO(e.target),r=t&&!t.isCollapsed&&VO(t.anchorNode);(!n||!r)&&window.hideFloatingMenu()}});let j=document.getElementById(`stopCompanionBtn`);function ee(){let e=!!(t&&t.value&&t.value.trim());return N.isGenerating&&e}function te(){t&&t.value&&t.value.trim();let e=N.isGenerating,i=ee();n.classList.toggle(`queue-mode`,i),n.classList.toggle(`stop-mode`,e&&!i),i?(n.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>`,n.title=r(`queue.enqueueBtn`)):e?(n.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>`,n.title=r(`sidePanel.sendBtnStop`)):(n.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>`,n.title=r(`sidePanel.sendBtnSend`)),n.disabled=!1,n.style.opacity=``,n.style.cursor=``,j&&(j.style.display=i?``:`none`,j.disabled=!1,j.style.opacity=``,j.style.cursor=``)}n.addEventListener(`click`,()=>{if(!N.isGenerating){XC();return}t&&t.value&&t.value.trim()?md():pC(n)}),j?.addEventListener(`click`,()=>pC(j));function ne(e){if(!N.isGenerating)return!1;let t=N.activeSessionId;return t?bd(t)?(yd(t),pC(j&&j.style.display!==`none`?j:e||n)?(L(r(`queue.stopAndSendStarted`),`success`,2500),!0):(xd(t),!0)):(L(r(`queue.stopAndSendEmpty`),`warning`,3e3),!1):!1}function re(e,{isPrimarySend:t=!1}={}){if(!e)return;let n=()=>t&&ee();e.addEventListener(`contextmenu`,t=>{n()||!N.isGenerating||!bd(N.activeSessionId)||(t.preventDefault(),ne(e))});let r=null,i=()=>{r&&=(clearTimeout(r),null)};e.addEventListener(`pointerdown`,t=>{t.pointerType===`mouse`&&t.button!==0||n()||!N.isGenerating||!bd(N.activeSessionId)||(i(),r=setTimeout(()=>{r=null,ne(e)},600))});for(let t of[`pointerup`,`pointerleave`,`pointercancel`])e.addEventListener(t,i)}re(n,{isPrimarySend:!0}),re(j),document.addEventListener(`queue-stop-and-send`,()=>{ne(j&&j.style.display!==`none`?j:n)}),document.addEventListener(`generating-state-changed`,te),t.addEventListener(`input`,te),document.addEventListener(`voice-draft-written`,te);let ie=document.getElementById(`shortcutsBtn`),ae=document.getElementById(`shortcutsModal`),oe=document.getElementById(`shortcutsCloseBtn`);function se(){ae&&(ae.style.display=`flex`)}function ce(){ae&&(ae.style.display=`none`)}ie&&ie.addEventListener(`click`,e=>{e.stopPropagation(),se();let t=document.getElementById(`headerMoreDropdown`);t&&t.classList.remove(`show`)}),oe&&oe.addEventListener(`click`,ce),ae&&ae.addEventListener(`click`,e=>{e.target===ae&&ce()});let le=BO();Nx(),qu({adjustInputHeight:g}).catch(e=>{a.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`?ya():va()}if(e.key===`Escape`&&Hu()){e.preventDefault();return}if(!(e.key===`Escape`&&le.handleEscape())){if(e.key===`Escape`&&ae&&ae.style.display!==`none`){ce();return}if(e.altKey&&e.code===`Slash`){e.preventDefault(),se();return}if(e.altKey&&!e.shiftKey&&e.code===`KeyS`&&!e.ctrlKey&&!e.metaKey){e.preventDefault(),Qm();return}if(e.altKey&&e.shiftKey&&e.code===`KeyS`&&!e.ctrlKey&&!e.metaKey){e.preventDefault(),$m();return}if(au(e)){e.preventDefault(),Bu();return}if(e.altKey&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&e.code===`KeyN`){e.preventDefault(),ns();return}if(e.altKey&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&e.code===`KeyW`){e.preventDefault(),ac();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){bw(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`;le.jumpToMessage(t,e.ctrlKey||e.metaKey),le.updateActiveQuestion();return}}}),t.addEventListener(`keydown`,e=>{let n=document.getElementById(`promptSelector`),r=document.getElementById(`promptDropdown`),i=document.getElementById(`agentAtSelector`),a=document.getElementById(`agentAtDropdown`);if(i.style.display!==`none`&&a.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(sb);for(let e=0;e<t.length;e++)if(r=(r+1)%t.length,n(t[r])){mb(t[r]);break}return}let r,i;n?(r=document.getElementById(`agentAtList`),i=N.selectedAgentAtIndex):sb===`pages`?(r=document.getElementById(`agentPageList`),i=N.selectedPageIndex):sb===`proxies`?(r=document.getElementById(`agentProxyList`),i=N.selectedProxyAtIndex):sb===`knowledge`?(r=document.getElementById(`agentKnowledgeList`),i=N.selectedKnowledgeAtIndex):(r=document.getElementById(`agentAtList`),i=N.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?(N.selectedAgentAtIndex=t,Ob(a)):sb===`proxies`?(N.selectedProxyAtIndex=t,Ob(a)):sb===`knowledge`?(N.selectedKnowledgeAtIndex=t,Ob(a)):sb===`pages`?(N.selectedPageIndex=t,Yb(a)):(N.selectedAgentAtIndex=t,Ob(a));return}else if(e.key===`ArrowUp`){e.preventDefault();let t=i<0||i===0?o-1:i-1;n?(N.selectedAgentAtIndex=t,Ob(a)):sb===`proxies`?(N.selectedProxyAtIndex=t,Ob(a)):sb===`knowledge`?(N.selectedKnowledgeAtIndex=t,Ob(a)):sb===`pages`?(N.selectedPageIndex=t,Yb(a)):(N.selectedAgentAtIndex=t,Ob(a));return}else if(e.key===`Enter`&&i>=0){e.preventDefault(),a[i].click(),(e.ctrlKey||e.metaKey)&&fb();return}else if(e.key===`Escape`){fb();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&&(N.selectedFileAtIndex=e.key===`ArrowDown`?N.selectedFileAtIndex<0?0:(N.selectedFileAtIndex+1)%r:N.selectedFileAtIndex<0||N.selectedFileAtIndex===0?r-1:N.selectedFileAtIndex-1,MP(n));return}if(e.key===`Enter`&&r>0&&N.selectedFileAtIndex>=0){e.preventDefault(),n[N.selectedFileAtIndex].click();return}if(e.key===`Escape`){e.preventDefault(),DP();return}}if(n.style.display!==`none`&&r.classList.contains(`show`)){if(N.showMergedList){let t=r.querySelectorAll(`#promptList .prompt-item`),n=t.length;if(e.key===`ArrowDown`){e.preventDefault(),N.selectedPromptIndex<0?N.selectedPromptIndex=0:N.selectedPromptIndex=(N.selectedPromptIndex+1)%n,jw(t);return}if(e.key===`ArrowUp`){e.preventDefault(),N.selectedPromptIndex<0||N.selectedPromptIndex===0?N.selectedPromptIndex=n-1:--N.selectedPromptIndex,jw(t);return}if(e.key===`Enter`&&N.selectedPromptIndex>=0){e.preventDefault();let n=t[N.selectedPromptIndex];n.dataset.type===`skill`||n.dataset.type===`mcp`?(n.click(),(e.ctrlKey||e.metaKey)&&Ew()):e.ctrlKey||e.metaKey?Mw(n.dataset.code):Nw(n.dataset.code);return}if(e.key===`Escape`){Ew();return}return}if(N.activeDropdownTab===`skills`){let t=r.querySelectorAll(`#skillList .skill-list-item`),n=t.length;if(e.key===`ArrowDown`){e.preventDefault(),N.selectedSkillIndex<0?N.selectedSkillIndex=0:N.selectedSkillIndex=(N.selectedSkillIndex+1)%n,$w(t);return}if(e.key===`ArrowUp`){e.preventDefault(),N.selectedSkillIndex<0||N.selectedSkillIndex===0?N.selectedSkillIndex=n-1:--N.selectedSkillIndex,$w(t);return}if(e.key===`Enter`&&N.selectedSkillIndex>=0){e.preventDefault(),t[N.selectedSkillIndex].click(),(e.ctrlKey||e.metaKey)&&Ew();return}if(e.key===`Escape`){Ew();return}if(e.key===`Tab`){e.preventDefault();let t=document.getElementById(`mcpTab`);t&&t.style.display!==`none`?oT(`mcp`):oT(`prompts`);return}return}if(N.activeDropdownTab===`mcp`){let t=r.querySelectorAll(`#mcpList .mcp-list-item`),n=t.length;if(e.key===`ArrowDown`){e.preventDefault(),N.selectedMcpServiceIndex<0?N.selectedMcpServiceIndex=0:N.selectedMcpServiceIndex=(N.selectedMcpServiceIndex+1)%n,pT(t);return}if(e.key===`ArrowUp`){e.preventDefault(),N.selectedMcpServiceIndex<0||N.selectedMcpServiceIndex===0?N.selectedMcpServiceIndex=n-1:--N.selectedMcpServiceIndex,pT(t);return}if(e.key===`Enter`&&N.selectedMcpServiceIndex>=0){e.preventDefault(),t[N.selectedMcpServiceIndex].click(),(e.ctrlKey||e.metaKey)&&Ew();return}if(e.key===`Escape`){Ew();return}if(e.key===`Tab`){e.preventDefault(),oT(`prompts`);return}return}let t=r.querySelectorAll(`#promptList .prompt-item`),n=t.length;if(e.key===`Tab`){let t=document.getElementById(`skillsTab`),n=document.getElementById(`mcpTab`);if(t&&t.style.display!==`none`){e.preventDefault(),oT(`skills`);return}if(n&&n.style.display!==`none`){e.preventDefault(),oT(`mcp`);return}}if(n!==0&&e.key===`ArrowDown`){e.preventDefault(),N.selectedPromptIndex<0?N.selectedPromptIndex=0:N.selectedPromptIndex=(N.selectedPromptIndex+1)%n,jw(t);return}if(e.key===`ArrowUp`){e.preventDefault(),N.selectedPromptIndex<0||N.selectedPromptIndex===0?N.selectedPromptIndex=n-1:--N.selectedPromptIndex,jw(t);return}if(e.key===`Enter`&&(e.ctrlKey||e.metaKey)&&N.selectedPromptIndex>=0){e.preventDefault();let n=t[N.selectedPromptIndex].dataset.code;Mw(n);return}if(e.key===`Enter`&&N.selectedPromptIndex>=0){e.preventDefault();let n=t[N.selectedPromptIndex].dataset.code;Nw(n);return}if(e.key===`Escape`){Ew();return}}if(e.key===`Escape`){N.inputHistoryIndex>=0&&(N.inputHistoryIndex=-1),t.value&&(t.value=``,t.style.height=`auto`,t.dispatchEvent(new Event(`input`))),e.preventDefault();return}let c=n.style.display!==`none`&&r.classList.contains(`show`),l=i.style.display!==`none`&&a.classList.contains(`show`),u=o.style.display!==`none`&&s.classList.contains(`show`);if(e.key===`ArrowUp`&&N.inputHistoryIndex===-1&&!t.value.trim()&&!ad()&&lI()){e.preventDefault();return}if(!c&&!l&&!u){let n=BF({key:e.key,value:t.value,caret:t.selectionStart,history:N.inputHistory,index:N.inputHistoryIndex});if(n.handled){e.preventDefault(),N.inputHistoryIndex=n.index,t.value=n.value,t.dispatchEvent(new Event(`input`)),t.setSelectionRange(n.value.length,n.value.length);return}}if(e.key===`Enter`&&!e.shiftKey){if(N.isComposing)return;if(e.preventDefault(),DP(),N.isGenerating){if(e.altKey){Pd(t.value);return}md();return}XC()}}),t.addEventListener(`compositionstart`,()=>{N.isComposing=!0}),t.addEventListener(`compositionend`,()=>{N.isComposing=!1}),t.addEventListener(`paste`,e=>{let t=e.clipboardData?.items;if(t)for(let n of t){if(n.type.startsWith(`image/`)&&N.enableImageInput){e.preventDefault();let t=n.getAsFile();t&&zp(t);break}if(n.kind===`file`&&N.enableFileInput){e.preventDefault();let t=n.getAsFile();t&&Em([t]);break}}});let ue=document.getElementById(`fileAttachBtn`),de=document.getElementById(`fileInput`);ue&&de&&(ue.addEventListener(`click`,()=>{de.click()}),de.addEventListener(`change`,async()=>{if(de.files.length>0){let e=Array.from(de.files),t=e.filter(e=>e.type.startsWith(`image/`)),n=e.filter(e=>!e.type.startsWith(`image/`));if(t.length>0)if(N.enableImageInput)for(let e of t)await zp(e);else L(r(`sidePanel.imageNotEnabled`)),Em(t);n.length>0&&Em(n),de.value=``}}));let fe=document.querySelector(`.input-wrapper`),pe=0;fe&&(fe.addEventListener(`dragenter`,e=>{e.preventDefault(),e.stopPropagation(),pe++,fe.classList.add(`drag-over`)}),fe.addEventListener(`dragleave`,e=>{e.preventDefault(),e.stopPropagation(),pe--,pe<=0&&(pe=0,fe.classList.remove(`drag-over`))}),fe.addEventListener(`dragover`,e=>{e.preventDefault(),e.stopPropagation()}),fe.addEventListener(`drop`,async e=>{e.preventDefault(),e.stopPropagation(),pe=0,fe.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){uy([e]);return}}catch(e){a.warn(`[SidePanel] parse workspace dragdata failed:`,e)}}let i=Array.from(e.dataTransfer.files);if(i.length>0){e.preventDefault();let t=i.filter(e=>e.type.startsWith(`image/`)),n=i.filter(e=>!e.type.startsWith(`image/`));if(t.length>0)if(N.enableImageInput)for(let e of t)await zp(e);else L(r(`sidePanel.imageNotEnabled`)),Em(t);n.length>0&&Em(n);return}let o=e.dataTransfer.getData(`text/plain`);if(o&&(e.preventDefault(),t)){t.focus();let e=t.selectionStart??t.value.length,n=t.selectionEnd??t.value.length;t.value=t.value.slice(0,e)+o+t.value.slice(n),t.selectionStart=t.selectionEnd=e+o.length,t.dispatchEvent(new Event(`input`))}}));let me=document.getElementById(`screenshotBtn`);me&&me.addEventListener(`click`,async()=>{if(N.enableImageInput)try{await Qm()}catch(e){a.error(`[SidePanel] screenshot failed:`,e),L(r(`sidePanel.screenshotFailed`))}}),Lp(),t.addEventListener(`wheel`,e=>{N.isScrolling=!0;let n=t.style.height||t.offsetHeight+`px`;t.style.height=n,t.scrollHeight<=t.clientHeight+10&&(e.preventDefault(),e.stopPropagation()),setTimeout(()=>{N.isScrolling=!1},100)},{passive:!1}),t.addEventListener(`input`,e=>{let n=t.value,r=document.getElementById(`promptSelector`),i=document.getElementById(`promptDropdown`);document.getElementById(`agentAtSelector`),document.getElementById(`agentAtDropdown`);let a=n.lastIndexOf(`/`),o=n.lastIndexOf(`@`),s=n.lastIndexOf(`$`),c=e=>{if(e===-1||e!==0&&n[e-1]!==`
|
|
2791
2798
|
`&&n[e-1]!==` `)return!1;let t=n.substring(e+1);return!(t.includes(` `)||t.includes(`
|
|
2792
|
-
`))},l=c(a),u=c(o),d=c(s),f=null;if(l&&(f={key:`slash`,index:a}),u&&(!f||o>f.index)&&(f={key:`at`,index:o}),d&&(!f||s>f.index)&&(f={key:`dollar`,index:s}),f&&f.key===`dollar`)Ew(),fb(),
|
|
2799
|
+
`))},l=c(a),u=c(o),d=c(s),f=null;if(l&&(f={key:`slash`,index:a}),u&&(!f||o>f.index)&&(f={key:`at`,index:o}),d&&(!f||s>f.index)&&(f={key:`dollar`,index:s}),f&&f.key===`dollar`)Ew(),fb(),EP(n.substring(s+1));else if(f&&f.key===`at`)Ew(),DP(),ub(n.substring(o+1));else if(f&&f.key===`slash`){fb(),DP();let e=n.substring(a+1);r.style.display!==`none`&&i.classList.contains(`show`)?Ow(e):Tw(e)}else Ew(),fb(),DP();g()});let he=VF((e,t)=>{chrome.storage.local.set({[e]:t})},200);u.addEventListener(`scroll`,()=>{he(`scrollPosition_`+(N.activeSessionId||`default`),u.scrollTop)}),window.addEventListener(`pagehide`,()=>{chrome.storage.local.set({[`scrollPosition_`+(N.activeSessionId||`default`)]:u.scrollTop})});let ge=document.getElementById(`headerMoreBtn`),_e=document.getElementById(`headerMoreDropdown`);ge&&_e&&(ge.addEventListener(`click`,e=>{e.stopPropagation(),_e.classList.toggle(`show`)}),document.addEventListener(`click`,e=>{!_e.contains(e.target)&&e.target!==ge&&Ce()}));let ve=document.getElementById(`themeToggleBtn`),ye=document.getElementById(`themeToggleLabel`),be=document.getElementById(`themeSubmenu`),xe=e=>r(e===`dark`?`settings.themeDark`:e===`system`?`settings.themeSystem`:`settings.themeLight`),Se=()=>{let e=ut();ye&&(ye.textContent=r(`header.themeToggle`,{theme:xe(e)})),be&&be.querySelectorAll(`.theme-submenu-item`).forEach(t=>{t.classList.toggle(`active`,t.dataset.themeValue===e)}),ve&&ve.setAttribute(`aria-expanded`,String(!!(be&&be.classList.contains(`show`))))};function Ce(){be&&be.classList.remove(`show`),_e&&_e.classList.remove(`show`),ve&&ve.setAttribute(`aria-expanded`,`false`)}ve&&be&&(ve.addEventListener(`click`,e=>{e.stopPropagation(),be.classList.toggle(`show`),Se()}),be.querySelectorAll(`.theme-submenu-item`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),gt(e.dataset.themeValue),Ce()})})),Se(),mt(Se),c(Se),s.addEventListener(`click`,e=>{e.stopPropagation(),Ce(),jC()}),l&&l.addEventListener(`click`,e=>{e.stopPropagation(),Ce(),Zf()});let we=document.getElementById(`importChatBtn`);we&&we.addEventListener(`click`,e=>{e.stopPropagation(),Ce(),np()});let Te=document.getElementById(`importSessionsFile`);Te&&Te.addEventListener(`change`,e=>{let t=e.target.files[0];t&&rp(t)});let Ee=document.getElementById(`settingsBtn`);Ee&&Ee.addEventListener(`click`,()=>{chrome.runtime.openOptionsPage()});let De=document.getElementById(`headerAgentIndicator`);De&&De.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 Oe=document.getElementById(`prototypeLibraryBtn`);Oe&&Oe.addEventListener(`click`,e=>{e.stopPropagation(),Ce(),Tc()});let ke=document.getElementById(`tokenStatsHeaderBtn`);ke&&ke.addEventListener(`click`,e=>{e.stopPropagation(),Ce(),window.openTokenStats&&window.openTokenStats()});let Ae=document.getElementById(`auditLogBtn`),je=document.getElementById(`auditLogOverlay`),Me=document.getElementById(`auditLogClose`),Ne=document.getElementById(`auditLogRefreshBtn`),Pe=document.getElementById(`auditLogCategoryFilter`),Fe=document.getElementById(`auditLogLimit`),Ie=document.getElementById(`auditLogSearch`),Le=document.getElementById(`auditLogSearchClear`),Re=document.getElementById(`auditLogLoading`),ze=document.getElementById(`auditLogEmpty`),Be=document.getElementById(`auditLogList`),Ve=[],He={auth:r(`sidePanel.auditCategoryAuth`),fs:r(`sidePanel.auditCategoryFs`),exec:r(`sidePanel.auditCategoryExec`),security:r(`sidePanel.auditCategorySecurity`),system:r(`sidePanel.auditCategorySystem`)},Ue={info:`INFO`,warn:`WARN`,error:`ERROR`},We={info:`audit-level-info`,warn:`audit-level-warn`,error:`audit-level-error`};function Ge(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 Ke(e){let t=new Set([`timestamp`,`level`,`category`,`action`]),n=[];for(let[r,i]of Object.entries(e)){if(t.has(r))continue;let e=typeof i==`string`?i:JSON.stringify(i),a=e.length>60?e.slice(0,60)+`...`:e;n.push(`${r}: ${a}`)}return n.join(r(`sidePanel.auditDetailSeparator`))}async function qe(){if(!Re||!ze||!Be)return;Re.style.display=`block`,ze.style.display=`none`,Be.style.display=`none`;let e=Pe?.value||null,t=parseInt(Fe?.value||`200`,10);try{let n=await new Promise((n,r)=>{chrome.runtime.sendMessage({type:`QUERY_AUDIT_LOGS`,category:e,limit:t},e=>{chrome.runtime.lastError?r(Error(chrome.runtime.lastError.message)):n(e)})});if(Re.style.display=`none`,!n||!n.success){ze.style.display=`block`,ze.textContent=r(`sidePanel.auditQueryFailed`,{error:n?.error||r(`sidePanel.unknownError`)});return}Ve=n.entries||[],Je()}catch(e){Re.style.display=`none`,ze.style.display=`block`,ze.textContent=r(`sidePanel.auditLoadFailed`,{error:e.message})}}function Je(){if(!Be)return;let e=(Ie?.value||``).trim().toLowerCase(),t=Ve;if(e&&(t=t.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))),Le&&(Le.style.display=e?`block`:`none`),Re.style.display=`none`,t.length===0){ze.style.display=`block`,ze.textContent=r(e?`sidePanel.auditNoMatch`:`sidePanel.auditEmpty`),Be.style.display=`none`;return}ze.style.display=`none`,Be.style.display=`block`,Be.innerHTML=t.map(e=>{let t=P(He[e.category]||e.category||`-`),n=P(Ue[e.level]||e.level?.toUpperCase()||`INFO`),r=We[e.level]||`audit-level-info`,i=Ge(e.timestamp),a=P(Ke(e));return`<div class="audit-entry">
|
|
2793
2800
|
<div class="audit-entry-header">
|
|
2794
2801
|
<span class="audit-time">${i}</span>
|
|
2795
2802
|
<span class="audit-level ${r}">${n}</span>
|
|
@@ -2797,7 +2804,7 @@ Are you sure you want to stop the agent service? You will not be able to connect
|
|
|
2797
2804
|
<span class="audit-action">${P(e.action||`-`)}</span>
|
|
2798
2805
|
</div>
|
|
2799
2806
|
${a?`<div class="audit-details">${a}</div>`:``}
|
|
2800
|
-
</div>`}).join(``)}function Ye(){je&&(je.style.display=`flex`,qe())}function Xe(){je&&(je.style.display=`none`)}Ae&&Ae.addEventListener(`click`,e=>{e.stopPropagation(),Ce(),Ye()}),Me&&Me.addEventListener(`click`,Xe),Ne&&Ne.addEventListener(`click`,qe),Pe&&Pe.addEventListener(`change`,qe),Fe&&Fe.addEventListener(`change`,qe),Ie&&Ie.addEventListener(`input`,()=>{Je()}),Le&&Le.addEventListener(`click`,()=>{Ie&&(Ie.value=``),Je()}),
|
|
2807
|
+
</div>`}).join(``)}function Ye(){je&&(je.style.display=`flex`,qe())}function Xe(){je&&(je.style.display=`none`)}Ae&&Ae.addEventListener(`click`,e=>{e.stopPropagation(),Ce(),Ye()}),Me&&Me.addEventListener(`click`,Xe),Ne&&Ne.addEventListener(`click`,qe),Pe&&Pe.addEventListener(`change`,qe),Fe&&Fe.addEventListener(`change`,qe),Ie&&Ie.addEventListener(`input`,()=>{Je()}),Le&&Le.addEventListener(`click`,()=>{Ie&&(Ie.value=``),Je()}),nL(()=>N.activeSessionId,window.showCustomConfirm);let Ze=document.getElementById(`isolateChatBtn`),Qe=document.getElementById(`enableToolsBtn`),$e=document.getElementById(`toolsConfigBtn`),et=`agentEnabledTools_${N.activeAgentId||`default`}`,tt=`agentMcpClosedServers_${N.activeAgentId||`default`}`;chrome.storage.local.get([et,`enabledTools`,`isolateChat`,`enableSelectionQuery`,`enableTools`,tt,`mcpTools`,`mcpEnabled`,`ragTools`,`ragToolsIntroduced`],e=>{e.isolateChat!==void 0&&(N.isolateChat=e.isolateChat),Ze.checked=N.isolateChat,e.enableSelectionQuery!==void 0&&(N.enableSelectionQuery=e.enableSelectionQuery);let t=document.getElementById(`enableSelectionQueryBtn`);t&&(t.checked=N.enableSelectionQuery),e.enableTools!==void 0&&(N.useTools=e.enableTools),N.activeAgentId&&M(async()=>{let{getAgent:e}=await import(`./agent-store-CXWql6bl.js`).then(e=>e.t);return{getAgent:e}},__vite__mapDeps([0,1,2,3,4])).then(({getAgent:e})=>e(N.activeAgentId)).then(e=>{N.activeAgentMcpExcludedServerIds=e?e.mcpExcludedServerIds??null:null,Ma()}).catch(()=>{}),N.mcpClosedServers=e[tt]||[];let n=e.ragTools||[],r=e[et],i=e.enabledTools;if(Array.isArray(r)){let t=Fa(n);N.enabledTools=r.filter(e=>t.has(e));let i=Pa(N.enabledTools,n,e.ragToolsIntroduced);N.enabledTools=i.tools,i.migrated?chrome.storage.local.set({ragToolsIntroduced:!0,[et]:N.enabledTools}):N.enabledTools.length!==r.length&&chrome.storage.local.set({[et]:N.enabledTools})}else if(i&&i.length>0){let t=Fa(n),r=i.filter(e=>t.has(e)),a=x.filter(e=>e.enabled&&!r.includes(e.id)).map(e=>e.id);N.enabledTools=[...r,...a];let o=Pa(N.enabledTools,n,e.ragToolsIntroduced);N.enabledTools=o.tools,chrome.storage.local.set({[et]:N.enabledTools,...o.migrated?{ragToolsIntroduced:!0}:{}})}else{N.enabledTools=x.filter(e=>e.enabled).map(e=>e.id);let t=Pa(N.enabledTools,n,e.ragToolsIntroduced);N.enabledTools=t.tools,t.migrated&&chrome.storage.local.set({ragToolsIntroduced:!0,[et]:N.enabledTools})}Qe&&(Qe.checked=N.useTools),Ma(),gL(),D()}),Ze.addEventListener(`change`,()=>{N.isolateChat=Ze.checked,chrome.storage.local.set({isolateChat:N.isolateChat}),a.debug(`[SidePanel] conv memory:`,N.isolateChat?`enabled`:`disabled`)});let nt=document.getElementById(`enableSelectionQueryBtn`);nt&&nt.addEventListener(`change`,()=>{N.enableSelectionQuery=nt.checked,chrome.storage.local.set({enableSelectionQuery:N.enableSelectionQuery}),a.debug(`[SidePanel] text Q&A:`,N.enableSelectionQuery?`enabled`:`disabled`),!N.enableSelectionQuery&&N.selectedContextText&&SC()}),Qe&&Qe.addEventListener(`change`,()=>{N.useTools=Qe.checked,chrome.storage.local.set({enableTools:N.useTools}),a.debug(`[SidePanel] tool master switch:`,N.useTools?`enabled`:`disabled`),Ma()}),$e&&$e.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),va()});let rt=document.getElementById(`toolsPopupOverlay`),it=document.getElementById(`toolsPopupClose`),at=rt?rt.querySelector(`.modal-container`):null;it&&it.addEventListener(`click`,ya),at&&at.addEventListener(`click`,e=>{e.stopPropagation()});let ot=document.getElementById(`toolsSearchInput`),st=document.getElementById(`toolsSearchClear`);ot&&ot.addEventListener(`input`,e=>{N.currentSearch=e.target.value.toLowerCase(),st&&(st.style.display=e.target.value?``:`none`),ba()}),st&&st.addEventListener(`click`,()=>{ot&&(ot.value=``,st.style.display=`none`,N.currentSearch=``,ba())});let ct=document.querySelectorAll(`.category-btn`);ct.forEach(e=>{e.addEventListener(`click`,()=>{ct.forEach(e=>{e.classList.remove(`active`),e.classList.contains(`category-all`)?(e.style.background=`var(--brand-violet-soft-bg)`,e.style.color=`var(--brand-500)`,e.style.borderColor=`var(--brand-violet-soft-border)`):(e.style.background=`var(--bg-surface)`,e.style.color=`var(--text-secondary)`,e.style.borderColor=`var(--border-subtle)`)}),e.classList.add(`active`),e.style.background=`linear-gradient(135deg, var(--brand-500) 0%, var(--brand-accent) 100%)`,e.style.color=`var(--text-on-brand)`,e.style.borderColor=`transparent`,N.currentCategory=e.dataset.category,ba()})});let lt=document.getElementById(`toolsCategories`);lt&<.addEventListener(`wheel`,e=>{e.preventDefault(),lt.scrollLeft+=e.deltaY*2},{passive:!1});let ft=document.getElementById(`toolsSelectAll`),pt=document.getElementById(`toolsSelectNone`);ft&&ft.addEventListener(`click`,()=>{Ea().forEach(e=>{let t=document.getElementById(`tool_`+e.id);t&&(t.checked=!0),N.enabledTools.includes(e.id)||N.enabledTools.push(e.id)}),ja(!0),Da(),Oa(),ka()}),pt&&pt.addEventListener(`click`,()=>{Ea().forEach(e=>{let t=document.getElementById(`tool_`+e.id);t&&(t.checked=!1);let n=N.enabledTools.indexOf(e.id);n>-1&&N.enabledTools.splice(n,1)}),ja(!1),Da(),Oa(),ka()});let ht=document.getElementById(`toolsPopupSave`);ht&&ht.addEventListener(`click`,()=>{Aa(),ka()});let _t=document.getElementById(`toolsPreselectToggle`);_t&&_t.addEventListener(`change`,()=>{chrome.storage.local.set({enableToolPreselect:_t.checked},()=>{a.debug(`[SidePanel] toolpre-filter toggle updated:`,_t.checked)})});let vt=document.getElementById(`toolConfirmToggle`);vt&&vt.addEventListener(`change`,()=>{chrome.storage.local.set({toolConfirmationEnabled:vt.checked},()=>{a.debug(`[SidePanel] sensitive-operation confirmation toggle updated:`,vt.checked)})});let yt=document.getElementById(`toolsPopupCancel`);yt&&yt.addEventListener(`click`,()=>{ya()});let bt=document.getElementById(`modalCancelBtn`),xt=document.getElementById(`modalConfirmBtn`),St=document.getElementById(`toolStatsOverlay`),Ct=document.getElementById(`toolStatsClose`),wt=document.getElementById(`toolStatsBtn`);function Tt(){St&&(St.style.display=`flex`,Mt())}function Dt(){St&&(St.style.display=`none`)}wt&&wt.addEventListener(`click`,e=>{e.stopPropagation(),Tt()}),Ct&&Ct.addEventListener(`click`,Dt),St&&St.addEventListener(`click`,e=>{e.target===St&&Dt()});let Ot=document.getElementById(`toolStatsRefreshBtn`);Ot&&Ot.addEventListener(`click`,Mt);let At=document.getElementById(`toolStatsClearBtn`);At&&At.addEventListener(`click`,async()=>{await window.showCustomConfirm(r(`sidePanel.clearStatsConfirm`),r(`sidePanel.clearStatsTitle`))&&(await chrome.storage.local.remove([`toolUsageStats`]),Mt())});let jt={column:`callCount`,asc:!1};async function Mt(){let e=document.getElementById(`toolStatsTable`),t=document.getElementById(`toolStatsTableBody`),n=document.getElementById(`toolStatsLoading`),i=document.getElementById(`toolStatsEmpty`),o=document.getElementById(`toolStatsSummary`),s=document.getElementById(`toolStatsUnusedSection`),c=document.getElementById(`toolStatsUnusedList`);if(!(!e||!t||!n||!i)){e.style.display=`none`,i.style.display=`none`,s&&(s.style.display=`none`),o&&(o.textContent=``),n.style.display=``;try{let t=(await chrome.storage.local.get([`toolUsageStats`])).toolUsageStats||{},a=Object.entries(t);if(a.length===0){n.style.display=`none`,i.style.display=``;return}let l={};x.forEach(e=>{l[e.id]=e.name?`${e.name}${r(`sidePanel.toolNameDescSeparator`)}${e.description||``}`:e.description||e.id}),Nt(a,l);let u=x.map(e=>e.id),d=new Set(a.map(([e])=>e)),f=u.filter(e=>!d.has(e)),p=a.length,m=f.length;o&&(o.textContent=r(`sidePanel.toolStatsSummary`,{used:p,unused:m})),s&&c&&m>0&&(c.innerHTML=f.sort((e,t)=>e.toLowerCase().localeCompare(t.toLowerCase())).map(e=>`<code title="${P(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=``),n.style.display=`none`,e.style.display=``}catch(e){a.error(`[SidePanel] loadstats failed:`,e),n.style.display=`none`,i.textContent=r(`sidePanel.toolStatsLoadFailed`),i.style.display=``}}}function Nt(e,t){let n=document.getElementById(`toolStatsTableBody`);if(!n)return;let{column:r,asc:i}=jt;n.innerHTML=[...e].sort((e,t)=>{let[n,a]=e,[o,s]=t,c=a.callCount>0?a.successCount/a.callCount*100:0,l=s.callCount>0?s.successCount/s.callCount*100:0,u=a.callCount>0?a.totalDuration/a.callCount:0,d=s.callCount>0?s.totalDuration/s.callCount:0,f=0;switch(r){case`name`:f=n.toLowerCase().localeCompare(o.toLowerCase());break;case`callCount`:f=a.callCount-s.callCount;break;case`successCount`:f=a.successCount-s.successCount;break;case`successRate`:f=c-l;break;case`duration`:f=u-d;break}return i?f:-f}).map(([e,n])=>{let r=n.callCount>0?n.successCount/n.callCount*100:0,i=n.callCount>0?n.totalDuration/n.callCount:0,a=t[e]||e,o=`#38a169`;r<60?o=`#e53e3e`:r<85&&(o=`#d69e2e`);let s=Bt(i);return`<tr>
|
|
2801
2808
|
<td style="padding: 6px 10px; border-bottom: 1px solid var(--border-subtle); color: var(--text-primary);"><code title="${P(a)}">${e}</code></td>
|
|
2802
2809
|
<td style="padding: 6px 10px; text-align: right; border-bottom: 1px solid var(--border-subtle); color: var(--text-secondary);">${n.callCount}</td>
|
|
2803
2810
|
<td style="padding: 6px 10px; text-align: right; border-bottom: 1px solid var(--border-subtle); color: var(--text-secondary);">${n.successCount}</td>
|
|
@@ -2808,4 +2815,4 @@ Are you sure you want to stop the agent service? You will not be able to connect
|
|
|
2808
2815
|
<span style="font-size: 12px; color: ${o}; font-weight: 500;">${r.toFixed(0)}%</span>
|
|
2809
2816
|
</td>
|
|
2810
2817
|
<td style="padding: 6px 10px; text-align: right; border-bottom: 1px solid var(--border-subtle); color: var(--text-tertiary); font-size: 12px;">${s}</td>
|
|
2811
|
-
</tr>`}).join(``),Pt()}function Pt(){let{column:e,asc:t}=jt,n=[`name`,`callCount`,`successCount`,`successRate`,`duration`],r={name:`sortByName`,callCount:`sortByCallCount`,successCount:`sortBySuccessCount`,successRate:`sortBySuccessRate`,duration:`sortByDuration`};n.forEach(n=>{let i=document.getElementById(r[n]);if(!i)return;let a=i.querySelector(`.sort-indicator`);a&&(n===e?(a.textContent=t?`▲`:`▼`,a.style.color=`var(--brand-500)`):(a.textContent=``,a.style.color=``))})}document.querySelectorAll(`#toolStatsTable th[data-sort]`).forEach(e=>{e.addEventListener(`click`,()=>{let t=e.dataset.sort;jt.column===t?jt.asc=!jt.asc:(jt.column=t,jt.asc=!1),Mt()})}),bt.addEventListener(`click`,()=>{MC()}),xt.addEventListener(`click`,()=>{MC(),AC()});let Ft=document.getElementById(`confirmModal`);Ft.addEventListener(`click`,e=>{e.target===Ft&&MC()});let It=document.getElementById(`selectionClose`);It&&It.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),a.debug(`[SidePanel] user clickcloseselected content by button`),SC(),window.hideFloatingMenu(),N.lastSelectedText=``,N.currentSelectionRange=null}),t.addEventListener(`input`,()=>{})}),
|
|
2818
|
+
</tr>`}).join(``),Pt()}function Pt(){let{column:e,asc:t}=jt,n=[`name`,`callCount`,`successCount`,`successRate`,`duration`],r={name:`sortByName`,callCount:`sortByCallCount`,successCount:`sortBySuccessCount`,successRate:`sortBySuccessRate`,duration:`sortByDuration`};n.forEach(n=>{let i=document.getElementById(r[n]);if(!i)return;let a=i.querySelector(`.sort-indicator`);a&&(n===e?(a.textContent=t?`▲`:`▼`,a.style.color=`var(--brand-500)`):(a.textContent=``,a.style.color=``))})}document.querySelectorAll(`#toolStatsTable th[data-sort]`).forEach(e=>{e.addEventListener(`click`,()=>{let t=e.dataset.sort;jt.column===t?jt.asc=!jt.asc:(jt.column=t,jt.asc=!1),Mt()})}),bt.addEventListener(`click`,()=>{MC()}),xt.addEventListener(`click`,()=>{MC(),AC()});let Ft=document.getElementById(`confirmModal`);Ft.addEventListener(`click`,e=>{e.target===Ft&&MC()});let It=document.getElementById(`selectionClose`);It&&It.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),a.debug(`[SidePanel] user clickcloseselected content by button`),SC(),window.hideFloatingMenu(),N.lastSelectedText=``,N.currentSelectionRange=null}),t.addEventListener(`input`,()=>{})}),jt().then(()=>{iL(),aw(N.chatConfig.showMessageTimestamp!==!1),aL(),oL()}),document.addEventListener(`DOMContentLoaded`,()=>{cL()}),document.addEventListener(`DOMContentLoaded`,lr),document.addEventListener(`DOMContentLoaded`,CE),document.addEventListener(`DOMContentLoaded`,vL),document.addEventListener(`DOMContentLoaded`,_L),document.addEventListener(`DOMContentLoaded`,_P),document.addEventListener(`DOMContentLoaded`,pF),document.addEventListener(`DOMContentLoaded`,zF),document.addEventListener(`DOMContentLoaded`,Ef),document.addEventListener(`DOMContentLoaded`,async()=>{$n(),vD(),await jm(),zm(),await EA(),mM(),KO(),eL(),hk(),BL(),Th(),XN();let{updateBookmarkButtons:e,updateBookmarkBadge:t}=await M(async()=>{let{updateBookmarkButtons:e,updateBookmarkBadge:t}=await Promise.resolve().then(()=>Rm);return{updateBookmarkButtons:e,updateBookmarkBadge:t}},void 0);e(),t()}),document.addEventListener(`DOMContentLoaded`,()=>{zO()}),document.addEventListener(`DOMContentLoaded`,async()=>{td(e=>XC(e)),await Jd(),await gI()});function KL(){SC(),nT(),hT(),Ib(),Zb(),Om();let e=document.getElementById(`imagePreviewBar`);e&&(e.innerHTML=``,e.style.display=`none`)}function qL(e){let t=e||{};t.quotedContextText&&bC(t.quotedContextText),t.selectedPage&&Xb(t.selectedPage),!t.quotedContextText&&N.selectedContextText&&xC(),rT(),_T(),Lb(),Zm(),km()}document.addEventListener(`queue-context-cleared`,KL),document.addEventListener(`queue-context-restored`,e=>{qL(e&&e.detail?e.detail.snapshot:null)}),document.addEventListener(`DOMContentLoaded`,Ww),document.addEventListener(`DOMContentLoaded`,aT),document.addEventListener(`DOMContentLoaded`,cT),document.addEventListener(`DOMContentLoaded`,yT),document.addEventListener(`DOMContentLoaded`,ex),document.addEventListener(`DOMContentLoaded`,ko),document.addEventListener(`DOMContentLoaded`,Jo),document.addEventListener(`DOMContentLoaded`,Hc),document.addEventListener(`DOMContentLoaded`,tp),document.addEventListener(`DOMContentLoaded`,()=>ST()),document.addEventListener(`DOMContentLoaded`,async()=>{let{refreshAgentNames:e,initScrollToBottomBtn:t}=await M(async()=>{let{refreshAgentNames:e,initScrollToBottomBtn:t}=await Promise.resolve().then(()=>hS);return{refreshAgentNames:e,initScrollToBottomBtn:t}},void 0);e(),t()}),document.addEventListener(`DOMContentLoaded`,()=>{let e=new URLSearchParams(window.location.search).has(`popup`),t=document.getElementById(`detachBtn`),n=document.getElementById(`attachBtn`),i=e?n:t;e?n&&(n.style.display=`flex`):t&&(t.style.display=`flex`);let o=()=>{if(!i)return;let t=N.pendingCallApiSessionIds&&N.pendingCallApiSessionIds.size>0;i.disabled=t,i.style.opacity=t?`0.35`:``,i.style.cursor=t?`not-allowed`:`pointer`,i.title=r(t?`detach.taskRunning`:e?`header.attachTitle`:`header.detachTitle`)};o(),document.addEventListener(`generating-state-changed`,o),t&&t.addEventListener(`click`,async()=>{if(N.pendingCallApiSessionIds&&N.pendingCallApiSessionIds.size>0){L(r(`detach.taskRunning`),`warning`);return}try{if((await chrome.runtime.sendMessage({type:`DETACH_SIDEPANEL`,width:window.innerWidth}))?.success)try{window.close()}catch{}}catch(e){a.warn(`[SidePanel] detach failed:`,e?.message)}}),n&&n.addEventListener(`click`,async()=>{if(N.pendingCallApiSessionIds&&N.pendingCallApiSessionIds.size>0){L(r(`detach.taskRunning`),`warning`);return}try{let e=(await chrome.windows.getCurrent()).id;await chrome.runtime.sendMessage({type:`ATTACH_SIDEPANEL`,windowId:e});try{window.close()}catch{}}catch(e){a.warn(`[SidePanel] attach failed:`,e?.message)}})});export{nh as t};
|