claude-simple 0.2.35 → 0.2.36
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 +0 -0
- package/client.js +1 -1
- package/dist/addon-fit.min.js +0 -0
- package/dist/{app.0.2.35.min.js → app.0.2.36.min.js} +147 -147
- package/dist/index.html +2 -2
- package/dist/{style.0.2.35.min.css → style.0.2.36.min.css} +23 -0
- package/dist/xterm.min.css +0 -0
- package/dist/xterm.min.js +0 -0
- package/gateway.js +0 -0
- package/package.json +1 -1
- package/public/addon-fit.min.js +0 -0
- package/public/agent-panel.js +0 -0
- package/public/api.js +0 -0
- package/public/app.js +2 -2
- package/public/base.css +0 -0
- package/public/cache.js +0 -0
- package/public/chat.js +0 -0
- package/public/download-status.js +25 -0
- package/public/files.js +71 -38
- package/public/git.js +0 -0
- package/public/icons/icon-180.png +0 -0
- package/public/icons/icon-192.png +0 -0
- package/public/icons/icon-512.png +0 -0
- package/public/icons/icon-maskable-512.png +0 -0
- package/public/index.html +2 -2
- package/public/lib.js +0 -0
- package/public/manifest.webmanifest +0 -0
- package/public/mobile.js +0 -0
- package/public/notifications.js +0 -0
- package/public/offline.html +0 -0
- package/public/pwa.js +1 -1
- package/public/router.js +0 -0
- package/public/settings.js +0 -0
- package/public/shell/boot.js +0 -0
- package/public/shell/dashboard.js +0 -0
- package/public/shell/hub.js +0 -0
- package/public/shell/layout.js +0 -0
- package/public/shell/notes.js +0 -0
- package/public/shell/session-context.js +0 -0
- package/public/shell/session-list.js +0 -0
- package/public/shell/session-nav.js +0 -0
- package/public/shell/templates.js +0 -0
- package/public/shell/util.js +0 -0
- package/public/shell.js +0 -0
- package/public/state.js +0 -0
- package/public/style.css +23 -0
- package/public/sw.js +3 -3
- package/public/terminal.js +0 -0
- package/public/wake-lock.js +0 -0
- package/public/xterm.min.css +0 -0
- package/public/xterm.min.js +0 -0
- package/src/agents/claude.js +0 -0
- package/src/agents/meta-agent.js +0 -0
- package/src/agents/models.js +0 -0
- package/src/agents/sessions.js +0 -0
- package/src/agents/stream-batch.js +0 -0
- package/src/app.js +0 -0
- package/src/auto-update.js +0 -0
- package/src/runtime/approvals.js +0 -0
- package/src/runtime/outbox.js +0 -0
- package/src/runtime/protocol.js +0 -0
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
var Ld=Object.defineProperty;var W=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(s){throw n=[s],s}};var ds=(e,t)=>{for(var n in t)Ld(e,n,{get:t[n],enumerable:!0})};function Id(){qo||(qo=!0,queueMicrotask(()=>{qo=!1,Oo()}))}function $i(e){for(let t of e)(t._isComputed?Cn:Mn).add(t);Bo>0||aa||(Ed==="microtask"?Id():Oo())}function Li(e,t,n,s){let a=new Set(n);for(let r of n)r._subs.delete(t);n.clear(),s?.forEach(r=>r?.()),s?.splice(0);let o=[Jt,fs,Po];[Jt,fs,Po]=[t,n,s];try{return e()}catch(r){for(let d of a)d._subs.add(t),n.add(d);throw r}finally{[Jt,fs,Po]=o}}var Jt,fs,Bo,Po,Cn,Mn,aa,us,Ho,Ed,qo,Oo,Si,I,Uo,je,xe,De,An,Td,p,b,Ei,i,Ro,Cd,ot,ps,Md,oa,Ad,Uf,ra,Ff,Wf,Ii,Ti=W(()=>{Jt=null,fs=null,Bo=0,Po=null,Cn=new Set,Mn=new Set,aa=!1,us=1e4,Ho={flushes:0,runs:0,lastFlushRuns:0},Ed="sync",qo=!1;Oo=()=>{if(aa)return;aa=!0;let e=0;Ho.flushes++;try{for(;Cn.size||Mn.size;){for(;Cn.size;){let t=Cn.values().next().value;if(Cn.delete(t),++e>us)throw new Error(`mini-react: reactive update loop exceeded ${us} runs`);t()}if(Mn.size){let t=Mn.values().next().value;if(Mn.delete(t),++e>us)throw new Error(`mini-react: reactive update loop exceeded ${us} runs`);t()}}}finally{Ho.runs+=e,Ho.lastFlushRuns=e,e>us&&(Cn.clear(),Mn.clear()),aa=!1}};Si=class{constructor(e,t){this._v=e,this._subs=new Set,this._eq=t??((n,s)=>n===s)}get value(){return Jt&&(this._subs.add(Jt),fs?.add(this)),this._v}set value(e){this._eq(e,this._v)||(this._v=e,$i(this._subs))}peek(){return this._v}},I=(e,{equals:t}={})=>new Si(e,t);Uo=e=>{let t=new Si(void 0),n=new Set,s=!0,a=!1,o=u=>{if(!s||a)return t._v;s=!1;try{let c=Li(e,r,n,null),f=c!==t._v;f&&(t._v=c),f&&u&&$i(t._subs)}catch(c){s=!0,console.error("[computed]",c)}return t._v},r=()=>{s||a||(s=!0,t._subs.size&&o(!0))};r._isComputed=!0;let d=()=>o(!1);return Object.defineProperty(t,"value",{get(){return Jt&&(t._subs.add(Jt),fs?.add(t)),d()},set(){throw new TypeError("Cannot assign to a computed signal")}}),t.dispose=()=>{if(!a){a=!0;for(let u of n)u._subs.delete(r);n.clear()}},t},je=e=>{let t=new Set,n=[],s=()=>{try{let a=Li(e,s,t,n);typeof a=="function"&&n.push(a)}catch(a){console.error("[effect]",a)}};return s(),()=>{for(let a of t)a._subs.delete(s);t.clear(),n.forEach(a=>a?.()),n.splice(0)}},xe=e=>{Bo++;try{e()}finally{--Bo===0&&Oo()}},De=(e,t)=>{let n=e.peek(),s=!1;return je(()=>{let a=e.value;s&&t(a,n),s=!0,n=a})},An=e=>je(()=>{let t=new AbortController;return Promise.resolve(e(t.signal)).catch(n=>{n?.name!=="AbortError"&&console.error("[asyncEffect]",n)}),()=>t.abort()}),Td={"&":"&","<":"<",">":">",'"':"""},p=e=>String(e??"").replace(/[&<>"]/g,t=>Td[t]),b=(()=>{let e=new Map,t=n=>{e.has(n)||(e.set(n,[]),document.addEventListener(n,s=>{xe(()=>{for(let[a,o]of e.get(n)){let r=s.target.closest(a);r&&o(s,r)}})},{capture:!0}))};return{on:(n,s,a)=>{t(n);let o=[s,a];return e.get(n).push(o),()=>e.set(n,e.get(n).filter(r=>r!==o))},off:(n,s)=>{e.has(n)&&e.set(n,e.get(n).filter(([a])=>a!==s))}}})(),Ei=(e,{keepAlive:t=!1}={})=>{let n=I(location.hash.slice(1)||"/"),s=!1,a=()=>{n.value=location.hash.slice(1)||"/"};window.addEventListener("hashchange",a);let o=t?new Map:null,r=(c,f)=>{if(!t)return f();if(o.has(c))return o.get(c);let m=f();return o.set(c,m),m},d=I(void 0),u=je(()=>{let c=n.value;for(let[f,m]of Object.entries(e)){if(f==="*")continue;let g=new RegExp("^"+f.replace(/:\w+/g,"([^/]+)")+"$"),w=c.match(g);if(w){let y=w.slice(1);d.value=typeof m=="function"?r(`${f}|${y.join("/")}`,()=>m(...y)):m;return}}if(e["*"]){let f=e["*"];d.value=typeof f=="function"?r("*",f):f;return}d.value=null});return{current:n,route:d,navigate:c=>{s||(location.hash=c)},match:c=>{let f=n.value.match(new RegExp("^"+c.replace(/:\w+/g,"([^/]+)")+"$"));return f?f.slice(1):null},invalidate:c=>{if(o){if(c===void 0){o.clear();return}for(let f of[...o.keys()])(f===c||f.startsWith(`${c}|`))&&o.delete(f)}},dispose:()=>{s||(s=!0,window.removeEventListener("hashchange",a),u(),o?.clear())}}},i=e=>document.getElementById(e),Ro=()=>typeof navigator>"u"||navigator.onLine!==!1,Cd=e=>new Promise(t=>setTimeout(t,e)),ot=e=>e===void 0?"undefined":e===null||typeof e!="object"?JSON.stringify(e):e instanceof Date?`Date(${e.toJSON()})`:Array.isArray(e)?`[${e.map(ot).join(",")}]`:`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${ot(e[t])}`).join(",")}}`,ps=(e,t)=>{if(!t)return!0;if(typeof t=="function")return t(e);if(t.queryKey){let n=ot(t.queryKey);if(t.exact?e.hash!==n:!e.hash.startsWith(n.slice(0,-1)))return!1}return!t.tags||t.tags.some(n=>e.tags.has(n))},Md=e=>{try{return JSON.stringify(e),!0}catch{return!1}},oa=(e,t)=>{if(Object.is(e,t))return e;if(!e||!t||typeof e!="object"||typeof t!="object")return t;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return t;let a=t.map((o,r)=>oa(e[r],o));return a.every((o,r)=>o===e[r])?e:a}if(Array.isArray(e)||Array.isArray(t)||Object.getPrototypeOf(e)!==Object.prototype||Object.getPrototypeOf(t)!==Object.prototype)return t;let n=Object.keys(t);if(n.length!==Object.keys(e).length)return t;let s={};for(let a of n){if(!(a in e))return t;s[a]=oa(e[a],t[a])}return n.every(a=>s[a]===e[a])?e:s},Ad=({staleTime:e=3e4,gcTime:t=3e5,retry:n=2,retryDelay:s=1e3,refetchOnWindowFocus:a=!1,refetchOnReconnect:o=!0}={})=>{let r=new Map,d=new Set,u=new Map,c=null,f=!1,m=h=>{for(let v of d)v(h)},g=h=>h.state,w=h=>!h.invalidated&&Date.now()-h.state.updatedAt.peek()<h.options.staleTime,y=h=>{h.invalidated=!0,h.state.isStale.value=!0},A=h=>{h.gcTimer&&clearTimeout(h.gcTimer),h.gcTimer=null},ae=h=>{A(h),!h.observers&&Number.isFinite(h.options.gcTime)&&(h.gcTimer=setTimeout(()=>{!h.observers&&!h.promise&&(r.delete(h.hash),m({type:"gc",key:h.key}))},h.options.gcTime))},O=h=>{h.pollTimer&&clearTimeout(h.pollTimer),h.pollTimer=null},pe=h=>{O(h);let v=typeof h.options.refetchInterval=="function"?h.options.refetchInterval(h):h.options.refetchInterval;h.observers&&Number.isFinite(v)&&v>0&&(h.pollTimer=setTimeout(async()=>{Ro()&&await he(h,{force:!0}).catch(()=>{}),pe(h)},v))},q=(h,v=ot(h.queryKey))=>{let k={staleTime:e,gcTime:t,retry:n,retryDelay:s,...h},S={hash:v,key:h.queryKey,queryFn:h.queryFn,options:k,tags:new Set(h.tags??[]),observers:0,invalidated:!0,promise:null,ctrl:null,version:0,gcTimer:null,pollTimer:null,state:{data:I(h.initialData),error:I(null),status:I(h.initialData===void 0?"idle":"success"),fetchStatus:I("idle"),updatedAt:I(h.initialData===void 0?0:Date.now()),isStale:I(!0)}};return r.set(v,S),S},Q=h=>{if(!h?.queryKey)throw new TypeError("query: queryKey is required");let v=ot(h.queryKey),k=r.get(v)??q(h,v);h.queryFn&&(k.queryFn=h.queryFn),k.options={...k.options,...h};for(let S of h.tags??[])k.tags.add(S);return k},he=(h,{force:v=!1}={})=>{if(!h.queryFn)return Promise.reject(new TypeError(`query ${h.hash} has no queryFn`));if(!v&&w(h))return Promise.resolve(h.state.data.peek());if(h.promise)return h.promise;if(!Ro())return h.state.fetchStatus.value="paused",Promise.reject(new Error("Query paused while offline"));A(h);let k=++h.version,S=new AbortController;h.ctrl=S,xe(()=>{h.state.data.peek()===void 0&&(h.state.status.value="pending"),h.state.fetchStatus.value="fetching",h.state.error.value=null}),m({type:"fetch",key:h.key});let U=async(j,V)=>{try{return await h.queryFn({queryKey:h.key,signal:S.signal,meta:h.options.meta})}catch(R){if(S.signal.aborted||R?.name==="AbortError"||j<=0||h.options.retry===!1)throw R;return await Cd(typeof V=="function"?V(j,R):V),U(j-1,typeof V=="number"?V*2:V)}},F=U(h.options.retry??n,h.options.retryDelay??s).then(j=>(h.version===k&&!S.signal.aborted&&xe(()=>{h.state.data.value=h.options.structuralSharing===!1?j:oa(h.state.data.peek(),j),h.state.status.value="success",h.state.fetchStatus.value="idle",h.state.updatedAt.value=Date.now(),h.state.isStale.value=!1,h.invalidated=!1}),m({type:"success",key:h.key}),j)).catch(j=>{throw h.version===k&&!S.signal.aborted&&xe(()=>{h.state.error.value=j,h.state.status.value=h.state.data.peek()===void 0?"error":"success",h.state.fetchStatus.value="idle"}),S.signal.aborted||m({type:"error",key:h.key,error:j}),j}).finally(()=>{h.promise===F&&(h.promise=null,h.ctrl=null,ae(h))});return h.promise=F,F},Ae=h=>Promise.all([...r.values()].filter(v=>ps(v,h)&&v.observers).map(v=>he(v,{force:!0}).catch(()=>{}))),L={query(h){let v=Q(h);v.observers++,A(v),pe(v),h.enabled!==!1&&(!w(v)||h.refetchOnMount)&&he(v).catch(()=>{});let k=()=>{v.observers=Math.max(0,v.observers-1),ae(v),pe(v)};return[g(v),{refetch:()=>he(v,{force:!0}),invalidate:()=>L.invalidateQueries({queryKey:v.key,exact:!0}),setData:S=>L.setQueryData(v.key,S),cancel:()=>L.cancelQueries({queryKey:v.key,exact:!0}),dispose:k}]},prefetchQuery(h){let v=Q(h);return he(v)},fetchQuery(h){let v=Q(h);return he(v)},getQueryData(h){return r.get(ot(h))?.state.data.peek()},getQueryState(h){let v=r.get(ot(h));return v&&g(v)},setQueryData(h,v,{tags:k}={}){let S=r.get(ot(h))??Q({queryKey:h,tags:k}),U=typeof v=="function"?v(S.state.data.peek()):v,F=S.options.structuralSharing===!1?U:oa(S.state.data.peek(),U);xe(()=>{S.state.data.value=F,S.state.status.value="success",S.state.error.value=null,S.state.updatedAt.value=Date.now(),S.state.isStale.value=!1}),S.invalidated=!1;for(let j of k??[])S.tags.add(j);return m({type:"set",key:S.key}),c&&c.postMessage({type:"invalidate",hash:S.hash}),F},invalidateQueries(h){for(let v of r.values())ps(v,h)&&y(v);return m({type:"invalidate",filter:h}),c&&c.postMessage({type:"invalidate",filter:h}),Ae(h)},cancelQueries(h){for(let v of r.values())ps(v,h)&&v.ctrl?.abort()},removeQueries(h){for(let v of[...r.values()])ps(v,h)&&(v.ctrl?.abort(),A(v),O(v),r.delete(v.hash))},mutate({mutationFn:h,variables:v,optimistic:k,invalidate:S,onMutate:U,onSuccess:F,onError:j,networkMode:V="online"}={}){if(typeof h!="function")return Promise.reject(new TypeError("mutate: mutationFn is required"));let R=[],ve=D=>(Array.isArray(D)?D:[D]).filter(Boolean).forEach(de=>{let zt=L.getQueryData(de.queryKey);R.push([de.queryKey,zt]),L.setQueryData(de.queryKey,Tn=>de.updater(Tn))}),Ke=async()=>{let D=await U?.(v,{client:L});k&&ve(typeof k=="function"?k(v):k);try{let de=await h(v);return await F?.(de,v,D),S&&await L.invalidateQueries(S),m({type:"mutation-success"}),de}catch(de){for(let[zt,Tn]of R)L.setQueryData(zt,Tn);throw await j?.(de,v,D),m({type:"mutation-error",error:de}),de}};return!Ro()&&V==="offlineFirst"?(ge.push(Ke),m({type:"mutation-queued"}),Promise.resolve({queued:!0})):Ke()},infiniteQuery({queryKey:h,queryFn:v,initialPageParam:k=0,getNextPageParam:S,...U}){let[F,j]=L.query({queryKey:h,...U,queryFn:async V=>({pages:[await v({...V,pageParam:k})],pageParams:[k]})});return[F,{...j,fetchNextPage:async()=>{let V=F.data.peek()??{pages:[],pageParams:[]},R=S?.(V.pages.at(-1),V.pages);if(R==null)return;let ve=await v({queryKey:h,pageParam:R,signal:new AbortController().signal});return L.setQueryData(h,{pages:[...V.pages,ve],pageParams:[...V.pageParams,R]}),ve}}]},dehydrate({shouldDehydrate:h=k=>k.state.status.peek()==="success",version:v=1}={}){return{version:v,timestamp:Date.now(),queries:[...r.values()].filter(h).filter(k=>Md(k.state.data.peek())).map(k=>({key:k.key,data:k.state.data.peek(),updatedAt:k.state.updatedAt.peek(),staleTime:k.options.staleTime,tags:[...k.tags]}))}},hydrate(h,{version:v=1}={}){if(!h||h.version!==v||!Array.isArray(h.queries))return!1;for(let k of h.queries){let S=r.get(ot(k.key))??Q({queryKey:k.key,staleTime:k.staleTime,tags:k.tags});xe(()=>{S.state.data.value=k.data,S.state.status.value="success",S.state.updatedAt.value=k.updatedAt,S.state.isStale.value=Date.now()-k.updatedAt>=S.options.staleTime}),S.invalidated=S.state.isStale.peek()}return m({type:"hydrate"}),!0},persist({storage:h=typeof localStorage>"u"?null:localStorage,key:v="mini-react-query",version:k=1}={}){if(!h)throw new Error("persist: a storage adapter is required");let S=!1,U=async()=>{let j=JSON.stringify(L.dehydrate({version:k}));return h.set?h.set(v,j):h.setItem(v,j)},F=L.subscribe(()=>{S||(S=!0,queueMicrotask(()=>{S=!1,U().catch(()=>{})}))});return{restore:async()=>{let j=await(h.get?h.get(v):h.getItem(v));return j?L.hydrate(JSON.parse(j),{version:k}):!1},save:U,dispose:F}},sync(h="mini-react-query"){return typeof BroadcastChannel>"u"?()=>{}:(c?.close(),c=new BroadcastChannel(h),c.onmessage=v=>{if(v.data?.type!=="invalidate")return;let k=v.data.hash?S=>S.hash===v.data.hash:v.data.filter;for(let S of r.values())ps(S,k)&&y(S);Ae(k)},()=>{c?.close(),c=null})},subscribe(h){return d.add(h),()=>d.delete(h)},getDebugSnapshot(){return[...r.values()].map(h=>({key:h.key,observers:h.observers,status:h.state.status.peek(),fetchStatus:h.state.fetchStatus.peek(),updatedAt:h.state.updatedAt.peek(),stale:h.state.isStale.peek(),tags:[...h.tags]}))},async fetchJSON(h,v={},{queryKey:k=["GET",h,v.body??null],...S}={}){let U=ot(k);return L.fetchQuery({queryKey:k,...S,queryFn:async({signal:F})=>{let j=new Headers(v.headers),V=u.get(U);V?.etag&&j.set("If-None-Match",V.etag);let R=await fetch(h,{...v,headers:j,signal:F});if(R.status===304&&V)return L.getQueryData(k);if(!R.ok)throw new Error(`HTTP ${R.status}`);let ve=R.headers.get("cache-control")?.match(/max-age=(\d+)/)?.[1];if(ve){let Ke=r.get(U);Ke&&(Ke.options.staleTime=Number(ve)*1e3)}return u.set(U,{etag:R.headers.get("etag")}),R.json()}})},destroy(){f=!0;for(let h of r.values())h.ctrl?.abort(),A(h),O(h);c?.close(),d.clear()}},ge=[],be=()=>{a&&Ae()},oe=()=>{for(o&&Ae();ge.length;)ge.shift()().catch(()=>{})};typeof window<"u"&&(window.addEventListener("focus",be),window.addEventListener("online",oe));let Kt=L.destroy;return L.destroy=()=>{f||(typeof window<"u"&&(window.removeEventListener("focus",be),window.removeEventListener("online",oe)),Kt())},L},Uf=Ad(),ra=({cache:e=!0,ttl:t=3e4,retry:n=2,retryDelay:s=1e3,store:a=null,dedupe:o=!0}={})=>{let r=new Map,d=new Map,u=new Map,c=(m,g)=>{if(a)return a.get(m);let w=r.get(m);return w&&Date.now()-w.ts<g?w.data:void 0},f=async(m,g,w)=>{if(a)return a.set(m,g,{ttl:w});r.set(m,{data:g,ts:Date.now()})};return{get:(m,g,w={})=>{let y=w.ttl??t,A=e&&w.cache!==!1&&y!==0,ae=w.dedupe??o;if(ae&&d.has(m))return d.get(m);let O=()=>{let q=u.get(m)??0,Q=(he,Ae)=>Promise.resolve(g()).then(async L=>(A&&(u.get(m)??0)===q&&await f(m,L,y),L)).catch(L=>{if(he>0&&L?.name!=="AbortError")return new Promise(ge=>setTimeout(ge,Ae)).then(()=>Q(he-1,Ae*2));throw L});return Q(w.retry??n,s)},pe=q=>(ae&&(d.set(m,q),q.finally(()=>{d.get(m)===q&&d.delete(m)}).catch(()=>{})),q);if(!A)return pe(O());if(!a){let q=c(m,y);return q!==void 0?Promise.resolve(q):pe(O())}return pe(Promise.resolve(c(m,y)).then(q=>q!==void 0?q:O()))},invalidate:m=>{if(m!==void 0)u.set(m,(u.get(m)??0)+1);else{for(let g of r.keys())u.set(g,(u.get(g)??0)+1);for(let g of d.keys())u.set(g,(u.get(g)??0)+1)}if(a)return m===void 0?a.clear():a.delete(m);m===void 0?r.clear():r.delete(m)}}},Ff=new TextEncoder,Wf=new TextDecoder,Ii=(e,t="kv")=>{let n=null,s=()=>n?Promise.resolve(n):new Promise((o,r)=>{let d=indexedDB.open(e,1);d.onupgradeneeded=u=>u.target.result.createObjectStore(t),d.onsuccess=u=>{n=u.target.result,o(n)},d.onerror=u=>r(u.target.error)}),a=async(o,r)=>{let d=await s();return new Promise((u,c)=>{let f=d.transaction(t,o),m=r(f.objectStore(t));m.onsuccess=()=>u(m.result),m.onerror=()=>c(m.error)})};return{async get(o){let r=await a("readonly",d=>d.get(o));if(r){if(r.expires&&Date.now()>r.expires){this.delete(o);return}return r.val}},async set(o,r,{ttl:d}={}){await a("readwrite",u=>u.put({val:r,expires:d?Date.now()+d:null},o))},delete:o=>a("readwrite",r=>r.delete(o)),clear:()=>a("readwrite",o=>o.clear()),keys:()=>a("readonly",o=>o.getAllKeys())}}});var K=W(()=>{Ti()});var Hi={};ds(Hi,{AGENT_DEFAULT_MODEL:()=>_i,AGENT_LABELS:()=>Z,AGENT_MODELS:()=>Fo,LOW_TURN_THRESHOLD:()=>Go,activityHits:()=>rt,activityLoading:()=>bt,addCustomModel:()=>Yt,agentFilter:()=>ye,agentFilters:()=>Vt,agentsMeta:()=>Qt,chatDensity:()=>_e,collapsedFolders:()=>Dn,ctx:()=>l,currentAgent:()=>$,currentEffort:()=>te,currentModel:()=>N,currentPermission:()=>ue,currentProject:()=>E,currentTab:()=>X,expandedFolders:()=>jn,favoritesOnly:()=>ze,filesPath:()=>Y,filesRoot:()=>ie,filteredSessions:()=>_t,getCustomModels:()=>la,getDefaultEffort:()=>Qe,getDefaultModel:()=>Oe,getEffortsForModel:()=>Xt,getModelsForAgent:()=>Be,getSavedModel:()=>Di,getSessionMeta:()=>_n,gitRoot:()=>Se,hubMachineReady:()=>it,hubMode:()=>M,isProcessing:()=>P,machinesList:()=>le,metaKey:()=>J,projectGroups:()=>Zt,removeCustomModel:()=>Jo,selectedMachineId:()=>_,sessionDisplayTitle:()=>vt,sessionFilter:()=>ke,sessionMetaMap:()=>T,sessionSearch:()=>$e,sessionSort:()=>Ci,sessionsData:()=>ne,setAgent:()=>Ne,setChatDensity:()=>Ko,setCurrentModel:()=>se,setSelectedMachine:()=>Le,showHiddenOnly:()=>Je,sidebarView:()=>gt,timeRange:()=>ia,viewingFile:()=>re,workspacesData:()=>fe,wsStatus:()=>me});function Ai(){try{let e=JSON.parse(localStorage.getItem(Mi)||"{}");return e&&typeof e=="object"?e:{}}catch{return{}}}function ji(e,t=l.sessionId,n=l.machineId){if(!t)return"";let s=(e||"claude").toLowerCase();return`${n||""}:${s}:${t}`}function Di(e,t=l.sessionId,n=l.machineId){let s=ji(e,t,n);if(!s)return null;let a=Ai()[s];return typeof a=="string"&&a.trim()?a:null}function se(e,t=$.peek(),n=l.sessionId,s=l.machineId){let a=String(e||"").trim();if(!a)return;let o=ji(t,n,s);if(o){let r=Ai();r[o]=a,localStorage.setItem(Mi,JSON.stringify(r))}N.value=a}function Le(e){let t=e||null;_.value=t,l.machineId=t,t?localStorage.setItem("machineId",t):localStorage.removeItem("machineId")}function J(e,t,n){let s=`${e||"claude"}:${t}`;return n||l?.machineId?`${n||l.machineId}:${s}`:s}function _n(e,t,n){return T.peek()?.[J(e,t,n)]||{favorite:!1,notes:"",title:"",hidden:!1,branch:null}}function vt(e,{preferSnippet:t=!1}={}){if(!e)return"Session";if(t&&e.snippet)return e.snippet;let s=(_n(e.agent,e.sessionId,e.machineId).title||"").trim();return s||e.display||e.sessionId?.slice(0,8)||"Session"}function Ko(e){let t=["clean","normal","full"].includes(e)?e:"normal";_e.value=t,localStorage.setItem("chatDensity",t),document.getElementById("messages")?.setAttribute("data-density",t)}function Dd(e){return e?typeof e=="string"?{value:e,label:e}:e.value?{value:String(e.value),label:e.label||e.value,...Array.isArray(e.efforts)&&e.efforts.length?{efforts:e.efforts.map(String)}:{},...e.defaultEffort?{defaultEffort:String(e.defaultEffort)}:{}}:null:null}function zo(){try{let e=localStorage.getItem(Ni);if(!e)return{};let t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function Pi(e){localStorage.setItem(Ni,JSON.stringify(e))}function la(e){let t=(e||"claude").toLowerCase(),n=zo()[t];return Array.isArray(n)?n.filter(Boolean).map(String):[]}function Yt(e,t){let n=(e||"claude").toLowerCase(),s=String(t||"").trim();if(!s)return!1;let a=zo(),o=Array.isArray(a[n])?[...a[n]]:[];return o.includes(s)||o.push(s),a[n]=o,Pi(a),!0}function Jo(e,t){let n=(e||"claude").toLowerCase(),s=String(t||"").trim(),a=zo(),o=Array.isArray(a[n])?a[n].filter(r=>r!==s):[];return a[n]=o,Pi(a),!0}function Be(e){let t=(e||"claude").toLowerCase(),n=Qt.peek()?.defaults?.[t],s=n?.models?.length?n.models.map(Dd).filter(Boolean):(Fo[t]||Fo.claude).map(r=>({...r})),a=la(t),o=new Set(s.map(r=>r.value));for(let r of a){if(o.has(r)){s=s.map(d=>{if(d.value!==r)return d;let u=String(d.label||d.value);return{...d,custom:!0,label:u.includes("\u2605")?u:`${u} \u2605`}});continue}o.add(r),s.push({value:r,label:`${r} \u2605`,custom:!0})}return s}function Oe(e){let t=(e||"claude").toLowerCase(),n=Qt.peek()?.defaults?.[t];return n?.model?String(n.model):_i[t]||Be(t)[0]?.value||"sonnet"}function Xt(e,t){let s=Be(e).find(o=>o.value===t);if(s?.efforts?.length)return s.efforts;let a=Qt.peek()?.defaults?.[(e||"claude").toLowerCase()];return a?.efforts?.length?a.efforts.map(String):["low","medium","high","xhigh","max"]}function Qe(e,t){let n=(e||"claude").toLowerCase(),s=Qt.peek()?.defaults?.[n];if(s?.effortDefault)return String(s.effortDefault);let o=Be(n).find(r=>r.value===t);return o?.defaultEffort?String(o.defaultEffort):n==="grok"?"low":n==="gemini"&&String(t||"").match(/-(low|medium|high)$/i)?.[1]?.toLowerCase()||""}function Ne(e){let t=(e||"claude").toLowerCase();$.value=t,localStorage.setItem("agent",t),ue.value="bypassPermissions";let n=typeof document>"u"?null:document.getElementById("sel-permission");n&&(n.value=ue.peek());let s=Di(t);s?N.value=s:se(Oe(t),t);let a=Qe(t,N.peek());a?te.value=a:t!=="grok"&&t!=="gemini"&&(te.value="")}function _d(e,t){return!t||t==="all"?!0:(e.agent||"claude")===t}function Nd(e,t){if(!t)return!0;let n=T.value?.[J(e.agent,e.sessionId,e.machineId)];return[e.display,e.cwd,e.projectName,e.agent,e.sessionId,e.snippet,e.machineId,n?.notes,n?.title].filter(Boolean).join(" ").toLowerCase().includes(t)}function Wo(e){return Array.isArray(e)?e:e&&Array.isArray(e.results)?e.results:e&&Array.isArray(e.sessions)?e.sessions:[]}var ne,fe,ke,$e,Ci,jn,Dn,Y,re,E,X,P,me,Mi,jd,$,N,te,ue,ie,Se,Qt,gt,ye,Vt,ia,rt,bt,T,ze,Je,Go,_e,M,le,_,it,l,Z,Fo,_i,Ni,_t,Zt,G=W(()=>{K();ne=I([]),fe=I([]),ke=I(null),$e=I(""),Ci=I("time"),jn=I(new Set),Dn=I(new Set),Y=I(""),re=I(null),E=I(null),X=I("chat"),P=I(!1),me=I("idle"),Mi="modelBySession",jd=localStorage.getItem("agent")||"claude";$=I(jd),N=I("sonnet"),te=I(""),ue=I("bypassPermissions"),ie=I(""),Se=I(""),Qt=I(null),gt=I(localStorage.getItem("sidebarView")||"projects"),ye=I(localStorage.getItem("agentFilter")||"all"),Vt=I((()=>{try{let e=JSON.parse(localStorage.getItem("agentFilters")||"[]");return Array.isArray(e)?e.filter(Boolean):[]}catch{return[]}})()),ia=I(localStorage.getItem("timeRange")||"14"),rt=I(null),bt=I(!1),T=I({}),ze=I(localStorage.getItem("favoritesOnly")==="1"),Je=I(localStorage.getItem("showHiddenOnly")==="1"),Go=2,_e=I(localStorage.getItem("chatDensity")||"normal"),M=I(!1),le=I([]),_=I(null),it=I(!1),l={token:localStorage.getItem("token"),sessionId:null,agent:null,machineId:null,ws:null,shellBubble:null,configDir:null,externalSessionReadOnly:!1,role:null,username:null,lock:{key:null,token:null,holder:null,held:!1,foreign:!1}};Z={claude:"Claude",codex:"Codex",grok:"Grok",gemini:"Gemini",cursor:"Cursor"},Fo={claude:[{value:"fable",label:"fable"},{value:"opus",label:"opus"},{value:"sonnet",label:"sonnet"},{value:"haiku",label:"haiku"}],codex:[{value:"gpt-5.4",label:"gpt-5.4"},{value:"gpt-5.3",label:"gpt-5.3"},{value:"gpt-5.2",label:"gpt-5.2"},{value:"o3",label:"o3"},{value:"o4-mini",label:"o4-mini"},{value:"codex-mini-latest",label:"codex-mini"}],grok:[{value:"grok-4.5",label:"grok-4.5"},{value:"grok-4",label:"grok-4"},{value:"grok-3",label:"grok-3"},{value:"grok-3-mini",label:"grok-3-mini"}],gemini:[{value:"gemini-3.7-flash-high",label:"Gemini 3.7 Flash (High)"},{value:"gemini-3.7-flash-medium",label:"Gemini 3.7 Flash (Medium)"},{value:"gemini-3.7-flash-low",label:"Gemini 3.7 Flash (Low)"},{value:"gemini-3.6-flash-high",label:"Gemini 3.6 Flash (High)"},{value:"gemini-3.6-flash-medium",label:"Gemini 3.6 Flash (Medium)"},{value:"gemini-3.6-flash-low",label:"Gemini 3.6 Flash (Low)"},{value:"gemini-3.5-flash-high",label:"Gemini 3.5 Flash (High)"},{value:"gemini-3.5-flash-medium",label:"Gemini 3.5 Flash (Medium)"},{value:"gemini-3.5-flash-low",label:"Gemini 3.5 Flash (Low)"},{value:"gemini-3.1-pro-high",label:"Gemini 3.1 Pro (High)"},{value:"gemini-3.1-pro-low",label:"Gemini 3.1 Pro (Low)"}],cursor:[{value:"auto",label:"Auto"},{value:"gpt-5.3-codex",label:"GPT-5.3 Codex"},{value:"composer-2.5",label:"Composer 2.5"}]},_i={claude:"sonnet",codex:"gpt-5.4",grok:"grok-4.5",gemini:"gemini-3.7-flash-high",cursor:"auto"};Ni="customModelsByAgent";_t=Uo(()=>{let e=$e.value.toLowerCase().trim(),t=Ci.value,n=ye.value,s=Vt.value,a=ze.value,o=Je.value,r=T.value,d=rt.value,u=d?.results?.length&&e?Wo(d.results):Wo(ne.value),c=_.value;return M.value&&c&&(u=u.filter(f=>f&&(!f.machineId||f.machineId===c))),u=u.filter(f=>f&&(s.length?s.includes(f.agent||"claude"):_d(f,n))),o?u=u.filter(f=>f&&r?.[J(f.agent,f.sessionId,f.machineId)]?.hidden):u=u.filter(f=>f&&!r?.[J(f.agent,f.sessionId,f.machineId)]?.hidden),a&&(u=u.filter(f=>f&&r?.[J(f.agent,f.sessionId,f.machineId)]?.favorite)),e&&!(d?.results&&d.q===e)&&(u=u.filter(f=>f&&Nd(f,e))),u=[...u].sort((f,m)=>{let g=r?.[J(f.agent,f.sessionId,f.machineId)]?.favorite?1:0,w=r?.[J(m.agent,m.sessionId,m.machineId)]?.favorite?1:0;return g!==w?w-g:t==="project"&&(f.cwd||"").localeCompare(m.cwd||"")||m.updatedAt-f.updatedAt}),!e&&!a?u.slice(0,120):u}),Zt=Uo(()=>{let e=Wo(_t.value),t=new Map;for(let n of e){if(!n)continue;let s=n.machineId?`${n.machineId}::${n.cwd||"(no path)"}`:n.cwd||"(no path)";t.has(s)||t.set(s,{cwd:n.cwd||null,machineId:n.machineId||null,projectName:n.projectName||(n.cwd?n.cwd.split("/").filter(Boolean).pop():"(no path)"),updatedAt:0,agents:{},sessions:[],latest:null});let a=t.get(s);a.sessions.push(n),a.agents[n.agent||"claude"]=(a.agents[n.agent||"claude"]||0)+1,(n.updatedAt||0)>a.updatedAt&&(a.updatedAt=n.updatedAt,a.latest=n)}return[...t.values()].sort((n,s)=>s.updatedAt-n.updatedAt)})});function ms(e={}){return e.machineId!==void 0?e.machineId:l.machineId||_.peek()||null}function qd(e){let t=e.split("?")[0];return t==="/api/hub"||t==="/api/machines"||t==="/api/notifications"||t==="/api/notifications/read"||t==="/api/notes"||t.startsWith("/api/notes/")||t==="/api/queue"||t.startsWith("/api/queue/")||t.startsWith("/api/ai/")||t.startsWith("/api/auth/")||t.startsWith("/api/collab/")}async function x(e,t,n,s,a={}){let o=a.hub?null:ms(a),r={"Content-Type":"application/json",...l.token?{Authorization:`Bearer ${l.token}`}:{}};!a.hub&&M.peek()&&o&&!qd(t)&&(r["X-Machine-Id"]=o),e.toUpperCase()!=="GET"&&e.toUpperCase()!=="HEAD"&&l.lock?.token&&l.lock?.key&&!String(t).startsWith("/api/collab/")&&(r["X-Lock-Token"]=l.lock.token,r["X-Lock-Key"]=l.lock.key);let u=a.etag===!0?`${l.token||""}:${o||""}:${t}`:a.etag||null;if(e.toUpperCase()==="GET"&&u){let m=Ri.get(u);m&&(r["If-None-Match"]=m)}let c=async()=>{let m=await fetch(t,{method:e,signal:s,headers:r,cache:a.cache||(e.toUpperCase()==="GET"?"no-store":"default"),...n!==void 0?{body:JSON.stringify(n)}:{}});if(m.status===304)return Hd;let g=await m.json().catch(()=>({}));if(!m.ok)throw new Error(g.error||`HTTP ${m.status}`);if(u){let w=m.headers.get("ETag");w&&Ri.set(u,w)}return g};if(e.toUpperCase()!=="GET"||s||a.dedupe===!1)return c();let f=`${l.token||""}:${o||""}:${t}`;return Pd.get(f,c)}function lt(e){return l.ws?.readyState===WebSocket.OPEN?(l.ws.send(JSON.stringify(e)),!0):(e?.type==="ping"||e?.type==="pong"||e?.type==="subscribe"||ca.push(e),!1)}function da(){for(;ca.length&&l.ws?.readyState===WebSocket.OPEN;)l.ws.send(JSON.stringify(ca.shift()))}function ua(){ca.length=0}function Qo(e={}){let t=new URLSearchParams(e);l.token&&t.set("token",l.token);let n=ms();return M.peek()&&n&&t.set("machine",n),t.toString()}function ct(e={},t={}){let n={...e};l.token&&(n.Authorization=`Bearer ${l.token}`);let s=ms();return!t.hub&&M.peek()&&s&&(n["X-Machine-Id"]=s),n}async function pa(){try{let e=await fetch("/api/hub");if(!e.ok)return M.value=!1,!1;let t=await e.json();if(t?.hub)return M.value=!0,t}catch{}return M.value=!1,!1}var Pd,Ri,Hd,ca,ce=W(()=>{G();K();Pd=ra({cache:!1,dedupe:!0,retry:0}),Ri=new Map,Hd=Symbol("not-modified");ca=[]});function en(e,t){e&&(t?e.setAttribute("inert",""):e.removeAttribute("inert"))}function Nn(e){return!e||e.classList.contains("hidden")?!0:e.style.display==="none"}function Ee(){let e=typeof window<"u"&&window.matchMedia("(max-width: 640px)").matches,t=document.getElementById("sidebar");if(t){let s=!e||t.classList.contains("open");en(t,!s)}en(document.getElementById("welcome"),Nn(document.getElementById("welcome"))),en(document.getElementById("auth-screen"),Nn(document.getElementById("auth-screen"))),en(document.getElementById("chat-opts"),Nn(document.getElementById("chat-opts"))),en(document.getElementById("machine-picker"),Nn(document.getElementById("machine-picker")));for(let s of["files","git","shell","memory"]){let a=document.getElementById(`tab-${s}`);en(a,Nn(a))}let n=document.getElementById("tab-chat");n&&en(n,Nn(n))}function hs(){let e=window.visualViewport,t=document.documentElement;if(!e)return;let n=e.height<window.innerHeight-80;t.classList.toggle("vv-keyboard",n),t.style.setProperty("--vvh",`${Math.round(e.height)}px`),t.style.setProperty("--vv-top",`${Math.round(e.offsetTop)}px`)}function Oi(){Ee(),hs();let e=window.visualViewport;e&&(e.addEventListener("resize",hs),e.addEventListener("scroll",hs)),window.addEventListener("resize",()=>{hs(),Ee()}),window.addEventListener("orientationchange",()=>{setTimeout(()=>{hs(),Ee()},250)})}var Pn=W(()=>{});function tn(){try{let e=localStorage.getItem(Ui);return e?JSON.parse(e):null}catch{return null}}function Vo(e){try{let n={...tn()||{},...e,updatedAt:Date.now()};localStorage.setItem(Ui,JSON.stringify(n))}catch{}}var Ui,ma=W(()=>{Ui="lastSessionContext"});function Rd(e){let t=String(e??"").trim();if(!t)return"";try{return decodeURIComponent(t)}catch{return t}}function Fi(e){return String(e||"").replace(/\\/g,"/")}function Bd(e){return e.replace(/:[0-9]+(?::[0-9]+)?$/,"")}function ha(e,t){let n=Rd(e);if(!n||/^(https?:|mailto:|tel:|javascript:|#)/i.test(n)||(n=Fi(n).split(/[?#]/)[0],n=n.replace(/^file:\/\//i,""),/^\/[A-Za-z]:\//.test(n)&&(n=n.slice(1)),!n||n==="."||n==="/")||/^\/(api|ws|session)\b/.test(n))return null;let s=n.endsWith("/"),a=Bd(n.replace(/\/+$/,"")),o=Fi(t).replace(/\/+$/,"");if((a.startsWith("/")||/^[A-Za-z]:\//.test(a))&&o){let d=a.toLowerCase(),u=o.toLowerCase();if(d===u)return{relative:"",isDir:!0,root:o};if(d.startsWith(`${u}/`))return{relative:a.slice(o.length+1),isDir:s,root:o};let c=a.split("/"),f=c.pop()||"",m=c.join("/")||(a.startsWith("/")?"/":"");return{relative:f,isDir:s,root:m}}if(a=a.replace(/^\.\//,""),a.startsWith("../")&&o){let d=o.split("/"),u=a.split("/");for(let f of u)f===".."?d.pop():f&&f!=="."&&d.push(f);let c=d.join("/")||"/";return ha(c,t)}return{relative:a,isDir:s,root:o||t}}var Yo=W(()=>{});function Ud(){let e=document.getElementById("mermaid-zoom-overlay");if(e)return e;e=document.createElement("div"),e.id="mermaid-zoom-overlay",e.className="mermaid-zoom-overlay hidden",e.setAttribute("role","dialog"),e.setAttribute("aria-modal","true"),e.setAttribute("aria-label","Mermaid diagram enlarged"),e.innerHTML='<button type="button" class="mermaid-zoom-close" aria-label="\u5173\u95ED\u653E\u5927\u56FE">\xD7</button><div class="mermaid-zoom-canvas"></div>',document.body.appendChild(e);let t=()=>e.classList.add("hidden");return e.addEventListener("click",n=>{(n.target===e||n.target.closest(".mermaid-zoom-close"))&&t()}),Gi||(Gi=!0,document.addEventListener("keydown",n=>{n.key==="Escape"&&t()})),e}function Ki(e){let t=e.querySelector("svg");if(!t)return;let n=Ud(),s=n.querySelector(".mermaid-zoom-canvas");s.innerHTML=t.outerHTML;let a=s.querySelector("svg");a?.removeAttribute("width"),a?.removeAttribute("height"),n.classList.remove("hidden")}function Fd(){let e=globalThis.mermaid;return!e||Wi||(e.initialize({startOnLoad:!1,securityLevel:"strict",theme:document.documentElement.dataset.theme==="dark"?"dark":"default",flowchart:{htmlLabels:!1}}),Wi=!0),e}function Wd(e){let t=String(e||"").replace(/\r\n?/g,`
|
|
2
|
-
`).trim();return t=t.replace(/^```(?:mermaid)?\s*/i,"").replace(/\s*```$/,"").trim(),t=t.replace(/^mermaid\s*\n/i,""),t=t.replace(/^graph\s+(TD|TB|BT|RL|LR)\b/i,"flowchart $1"),t}function xt(e){let t=
|
|
3
|
-
`}function
|
|
4
|
-
`+n,t+3);return s===-1?{end:e.length}:{end:s+1+n.length}}if(e[t]==="`"){let n=1;for(;e[t+n]==="`";)n++;let s=t+n;for(;s<e.length;){if(e[s]==="`"){let a=0;for(;e[s+a]==="`";)a++;if(a===n)return{end:s+a};s+=a;continue}s++}return{end:t+n}}return null}function
|
|
1
|
+
var _d=Object.defineProperty;var B=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(s){throw n=[s],s}};var us=(e,t)=>{for(var n in t)_d(e,n,{get:t[n],enumerable:!0})};function Pd(){Wo||(Wo=!0,queueMicrotask(()=>{Wo=!1,Ko()}))}function Ai(e){for(let t of e)(t._isComputed?Mn:An).add(t);zo>0||ia||(Nd==="microtask"?Pd():Ko())}function ji(e,t,n,s){let a=new Set(n);for(let r of n)r._subs.delete(t);n.clear(),s?.forEach(r=>r?.()),s?.splice(0);let o=[Qt,ms,Uo];[Qt,ms,Uo]=[t,n,s];try{return e()}catch(r){for(let c of a)c._subs.add(t),n.add(c);throw r}finally{[Qt,ms,Uo]=o}}var Qt,ms,zo,Uo,Mn,An,ia,ps,Fo,Nd,Wo,Ko,Di,I,Jo,De,xe,je,Dn,Hd,p,b,_i,i,Go,qd,ot,fs,Rd,la,Bd,Yf,ca,Xf,Zf,Ni,Pi=B(()=>{Qt=null,ms=null,zo=0,Uo=null,Mn=new Set,An=new Set,ia=!1,ps=1e4,Fo={flushes:0,runs:0,lastFlushRuns:0},Nd="sync",Wo=!1;Ko=()=>{if(ia)return;ia=!0;let e=0;Fo.flushes++;try{for(;Mn.size||An.size;){for(;Mn.size;){let t=Mn.values().next().value;if(Mn.delete(t),++e>ps)throw new Error(`mini-react: reactive update loop exceeded ${ps} runs`);t()}if(An.size){let t=An.values().next().value;if(An.delete(t),++e>ps)throw new Error(`mini-react: reactive update loop exceeded ${ps} runs`);t()}}}finally{Fo.runs+=e,Fo.lastFlushRuns=e,e>ps&&(Mn.clear(),An.clear()),ia=!1}};Di=class{constructor(e,t){this._v=e,this._subs=new Set,this._eq=t??((n,s)=>n===s)}get value(){return Qt&&(this._subs.add(Qt),ms?.add(this)),this._v}set value(e){this._eq(e,this._v)||(this._v=e,Ai(this._subs))}peek(){return this._v}},I=(e,{equals:t}={})=>new Di(e,t);Jo=e=>{let t=new Di(void 0),n=new Set,s=!0,a=!1,o=u=>{if(!s||a)return t._v;s=!1;try{let d=ji(e,r,n,null),f=d!==t._v;f&&(t._v=d),f&&u&&Ai(t._subs)}catch(d){s=!0,console.error("[computed]",d)}return t._v},r=()=>{s||a||(s=!0,t._subs.size&&o(!0))};r._isComputed=!0;let c=()=>o(!1);return Object.defineProperty(t,"value",{get(){return Qt&&(t._subs.add(Qt),ms?.add(t)),c()},set(){throw new TypeError("Cannot assign to a computed signal")}}),t.dispose=()=>{if(!a){a=!0;for(let u of n)u._subs.delete(r);n.clear()}},t},De=e=>{let t=new Set,n=[],s=()=>{try{let a=ji(e,s,t,n);typeof a=="function"&&n.push(a)}catch(a){console.error("[effect]",a)}};return s(),()=>{for(let a of t)a._subs.delete(s);t.clear(),n.forEach(a=>a?.()),n.splice(0)}},xe=e=>{zo++;try{e()}finally{--zo===0&&Ko()}},je=(e,t)=>{let n=e.peek(),s=!1;return De(()=>{let a=e.value;s&&t(a,n),s=!0,n=a})},Dn=e=>De(()=>{let t=new AbortController;return Promise.resolve(e(t.signal)).catch(n=>{n?.name!=="AbortError"&&console.error("[asyncEffect]",n)}),()=>t.abort()}),Hd={"&":"&","<":"<",">":">",'"':"""},p=e=>String(e??"").replace(/[&<>"]/g,t=>Hd[t]),b=(()=>{let e=new Map,t=n=>{e.has(n)||(e.set(n,[]),document.addEventListener(n,s=>{xe(()=>{for(let[a,o]of e.get(n)){let r=s.target.closest(a);r&&o(s,r)}})},{capture:!0}))};return{on:(n,s,a)=>{t(n);let o=[s,a];return e.get(n).push(o),()=>e.set(n,e.get(n).filter(r=>r!==o))},off:(n,s)=>{e.has(n)&&e.set(n,e.get(n).filter(([a])=>a!==s))}}})(),_i=(e,{keepAlive:t=!1}={})=>{let n=I(location.hash.slice(1)||"/"),s=!1,a=()=>{n.value=location.hash.slice(1)||"/"};window.addEventListener("hashchange",a);let o=t?new Map:null,r=(d,f)=>{if(!t)return f();if(o.has(d))return o.get(d);let m=f();return o.set(d,m),m},c=I(void 0),u=De(()=>{let d=n.value;for(let[f,m]of Object.entries(e)){if(f==="*")continue;let g=new RegExp("^"+f.replace(/:\w+/g,"([^/]+)")+"$"),w=d.match(g);if(w){let y=w.slice(1);c.value=typeof m=="function"?r(`${f}|${y.join("/")}`,()=>m(...y)):m;return}}if(e["*"]){let f=e["*"];c.value=typeof f=="function"?r("*",f):f;return}c.value=null});return{current:n,route:c,navigate:d=>{s||(location.hash=d)},match:d=>{let f=n.value.match(new RegExp("^"+d.replace(/:\w+/g,"([^/]+)")+"$"));return f?f.slice(1):null},invalidate:d=>{if(o){if(d===void 0){o.clear();return}for(let f of[...o.keys()])(f===d||f.startsWith(`${d}|`))&&o.delete(f)}},dispose:()=>{s||(s=!0,window.removeEventListener("hashchange",a),u(),o?.clear())}}},i=e=>document.getElementById(e),Go=()=>typeof navigator>"u"||navigator.onLine!==!1,qd=e=>new Promise(t=>setTimeout(t,e)),ot=e=>e===void 0?"undefined":e===null||typeof e!="object"?JSON.stringify(e):e instanceof Date?`Date(${e.toJSON()})`:Array.isArray(e)?`[${e.map(ot).join(",")}]`:`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${ot(e[t])}`).join(",")}}`,fs=(e,t)=>{if(!t)return!0;if(typeof t=="function")return t(e);if(t.queryKey){let n=ot(t.queryKey);if(t.exact?e.hash!==n:!e.hash.startsWith(n.slice(0,-1)))return!1}return!t.tags||t.tags.some(n=>e.tags.has(n))},Rd=e=>{try{return JSON.stringify(e),!0}catch{return!1}},la=(e,t)=>{if(Object.is(e,t))return e;if(!e||!t||typeof e!="object"||typeof t!="object")return t;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return t;let a=t.map((o,r)=>la(e[r],o));return a.every((o,r)=>o===e[r])?e:a}if(Array.isArray(e)||Array.isArray(t)||Object.getPrototypeOf(e)!==Object.prototype||Object.getPrototypeOf(t)!==Object.prototype)return t;let n=Object.keys(t);if(n.length!==Object.keys(e).length)return t;let s={};for(let a of n){if(!(a in e))return t;s[a]=la(e[a],t[a])}return n.every(a=>s[a]===e[a])?e:s},Bd=({staleTime:e=3e4,gcTime:t=3e5,retry:n=2,retryDelay:s=1e3,refetchOnWindowFocus:a=!1,refetchOnReconnect:o=!0}={})=>{let r=new Map,c=new Set,u=new Map,d=null,f=!1,m=h=>{for(let v of c)v(h)},g=h=>h.state,w=h=>!h.invalidated&&Date.now()-h.state.updatedAt.peek()<h.options.staleTime,y=h=>{h.invalidated=!0,h.state.isStale.value=!0},P=h=>{h.gcTimer&&clearTimeout(h.gcTimer),h.gcTimer=null},ae=h=>{P(h),!h.observers&&Number.isFinite(h.options.gcTime)&&(h.gcTimer=setTimeout(()=>{!h.observers&&!h.promise&&(r.delete(h.hash),m({type:"gc",key:h.key}))},h.options.gcTime))},K=h=>{h.pollTimer&&clearTimeout(h.pollTimer),h.pollTimer=null},pe=h=>{K(h);let v=typeof h.options.refetchInterval=="function"?h.options.refetchInterval(h):h.options.refetchInterval;h.observers&&Number.isFinite(v)&&v>0&&(h.pollTimer=setTimeout(async()=>{Go()&&await he(h,{force:!0}).catch(()=>{}),pe(h)},v))},q=(h,v=ot(h.queryKey))=>{let k={staleTime:e,gcTime:t,retry:n,retryDelay:s,...h},S={hash:v,key:h.queryKey,queryFn:h.queryFn,options:k,tags:new Set(h.tags??[]),observers:0,invalidated:!0,promise:null,ctrl:null,version:0,gcTimer:null,pollTimer:null,state:{data:I(h.initialData),error:I(null),status:I(h.initialData===void 0?"idle":"success"),fetchStatus:I("idle"),updatedAt:I(h.initialData===void 0?0:Date.now()),isStale:I(!0)}};return r.set(v,S),S},Q=h=>{if(!h?.queryKey)throw new TypeError("query: queryKey is required");let v=ot(h.queryKey),k=r.get(v)??q(h,v);h.queryFn&&(k.queryFn=h.queryFn),k.options={...k.options,...h};for(let S of h.tags??[])k.tags.add(S);return k},he=(h,{force:v=!1}={})=>{if(!h.queryFn)return Promise.reject(new TypeError(`query ${h.hash} has no queryFn`));if(!v&&w(h))return Promise.resolve(h.state.data.peek());if(h.promise)return h.promise;if(!Go())return h.state.fetchStatus.value="paused",Promise.reject(new Error("Query paused while offline"));P(h);let k=++h.version,S=new AbortController;h.ctrl=S,xe(()=>{h.state.data.peek()===void 0&&(h.state.status.value="pending"),h.state.fetchStatus.value="fetching",h.state.error.value=null}),m({type:"fetch",key:h.key});let U=async(A,V)=>{try{return await h.queryFn({queryKey:h.key,signal:S.signal,meta:h.options.meta})}catch(R){if(S.signal.aborted||R?.name==="AbortError"||A<=0||h.options.retry===!1)throw R;return await qd(typeof V=="function"?V(A,R):V),U(A-1,typeof V=="number"?V*2:V)}},F=U(h.options.retry??n,h.options.retryDelay??s).then(A=>(h.version===k&&!S.signal.aborted&&xe(()=>{h.state.data.value=h.options.structuralSharing===!1?A:la(h.state.data.peek(),A),h.state.status.value="success",h.state.fetchStatus.value="idle",h.state.updatedAt.value=Date.now(),h.state.isStale.value=!1,h.invalidated=!1}),m({type:"success",key:h.key}),A)).catch(A=>{throw h.version===k&&!S.signal.aborted&&xe(()=>{h.state.error.value=A,h.state.status.value=h.state.data.peek()===void 0?"error":"success",h.state.fetchStatus.value="idle"}),S.signal.aborted||m({type:"error",key:h.key,error:A}),A}).finally(()=>{h.promise===F&&(h.promise=null,h.ctrl=null,ae(h))});return h.promise=F,F},Ae=h=>Promise.all([...r.values()].filter(v=>fs(v,h)&&v.observers).map(v=>he(v,{force:!0}).catch(()=>{}))),L={query(h){let v=Q(h);v.observers++,P(v),pe(v),h.enabled!==!1&&(!w(v)||h.refetchOnMount)&&he(v).catch(()=>{});let k=()=>{v.observers=Math.max(0,v.observers-1),ae(v),pe(v)};return[g(v),{refetch:()=>he(v,{force:!0}),invalidate:()=>L.invalidateQueries({queryKey:v.key,exact:!0}),setData:S=>L.setQueryData(v.key,S),cancel:()=>L.cancelQueries({queryKey:v.key,exact:!0}),dispose:k}]},prefetchQuery(h){let v=Q(h);return he(v)},fetchQuery(h){let v=Q(h);return he(v)},getQueryData(h){return r.get(ot(h))?.state.data.peek()},getQueryState(h){let v=r.get(ot(h));return v&&g(v)},setQueryData(h,v,{tags:k}={}){let S=r.get(ot(h))??Q({queryKey:h,tags:k}),U=typeof v=="function"?v(S.state.data.peek()):v,F=S.options.structuralSharing===!1?U:la(S.state.data.peek(),U);xe(()=>{S.state.data.value=F,S.state.status.value="success",S.state.error.value=null,S.state.updatedAt.value=Date.now(),S.state.isStale.value=!1}),S.invalidated=!1;for(let A of k??[])S.tags.add(A);return m({type:"set",key:S.key}),d&&d.postMessage({type:"invalidate",hash:S.hash}),F},invalidateQueries(h){for(let v of r.values())fs(v,h)&&y(v);return m({type:"invalidate",filter:h}),d&&d.postMessage({type:"invalidate",filter:h}),Ae(h)},cancelQueries(h){for(let v of r.values())fs(v,h)&&v.ctrl?.abort()},removeQueries(h){for(let v of[...r.values()])fs(v,h)&&(v.ctrl?.abort(),P(v),K(v),r.delete(v.hash))},mutate({mutationFn:h,variables:v,optimistic:k,invalidate:S,onMutate:U,onSuccess:F,onError:A,networkMode:V="online"}={}){if(typeof h!="function")return Promise.reject(new TypeError("mutate: mutationFn is required"));let R=[],ve=D=>(Array.isArray(D)?D:[D]).filter(Boolean).forEach(de=>{let Jt=L.getQueryData(de.queryKey);R.push([de.queryKey,Jt]),L.setQueryData(de.queryKey,Cn=>de.updater(Cn))}),ze=async()=>{let D=await U?.(v,{client:L});k&&ve(typeof k=="function"?k(v):k);try{let de=await h(v);return await F?.(de,v,D),S&&await L.invalidateQueries(S),m({type:"mutation-success"}),de}catch(de){for(let[Jt,Cn]of R)L.setQueryData(Jt,Cn);throw await A?.(de,v,D),m({type:"mutation-error",error:de}),de}};return!Go()&&V==="offlineFirst"?(ge.push(ze),m({type:"mutation-queued"}),Promise.resolve({queued:!0})):ze()},infiniteQuery({queryKey:h,queryFn:v,initialPageParam:k=0,getNextPageParam:S,...U}){let[F,A]=L.query({queryKey:h,...U,queryFn:async V=>({pages:[await v({...V,pageParam:k})],pageParams:[k]})});return[F,{...A,fetchNextPage:async()=>{let V=F.data.peek()??{pages:[],pageParams:[]},R=S?.(V.pages.at(-1),V.pages);if(R==null)return;let ve=await v({queryKey:h,pageParam:R,signal:new AbortController().signal});return L.setQueryData(h,{pages:[...V.pages,ve],pageParams:[...V.pageParams,R]}),ve}}]},dehydrate({shouldDehydrate:h=k=>k.state.status.peek()==="success",version:v=1}={}){return{version:v,timestamp:Date.now(),queries:[...r.values()].filter(h).filter(k=>Rd(k.state.data.peek())).map(k=>({key:k.key,data:k.state.data.peek(),updatedAt:k.state.updatedAt.peek(),staleTime:k.options.staleTime,tags:[...k.tags]}))}},hydrate(h,{version:v=1}={}){if(!h||h.version!==v||!Array.isArray(h.queries))return!1;for(let k of h.queries){let S=r.get(ot(k.key))??Q({queryKey:k.key,staleTime:k.staleTime,tags:k.tags});xe(()=>{S.state.data.value=k.data,S.state.status.value="success",S.state.updatedAt.value=k.updatedAt,S.state.isStale.value=Date.now()-k.updatedAt>=S.options.staleTime}),S.invalidated=S.state.isStale.peek()}return m({type:"hydrate"}),!0},persist({storage:h=typeof localStorage>"u"?null:localStorage,key:v="mini-react-query",version:k=1}={}){if(!h)throw new Error("persist: a storage adapter is required");let S=!1,U=async()=>{let A=JSON.stringify(L.dehydrate({version:k}));return h.set?h.set(v,A):h.setItem(v,A)},F=L.subscribe(()=>{S||(S=!0,queueMicrotask(()=>{S=!1,U().catch(()=>{})}))});return{restore:async()=>{let A=await(h.get?h.get(v):h.getItem(v));return A?L.hydrate(JSON.parse(A),{version:k}):!1},save:U,dispose:F}},sync(h="mini-react-query"){return typeof BroadcastChannel>"u"?()=>{}:(d?.close(),d=new BroadcastChannel(h),d.onmessage=v=>{if(v.data?.type!=="invalidate")return;let k=v.data.hash?S=>S.hash===v.data.hash:v.data.filter;for(let S of r.values())fs(S,k)&&y(S);Ae(k)},()=>{d?.close(),d=null})},subscribe(h){return c.add(h),()=>c.delete(h)},getDebugSnapshot(){return[...r.values()].map(h=>({key:h.key,observers:h.observers,status:h.state.status.peek(),fetchStatus:h.state.fetchStatus.peek(),updatedAt:h.state.updatedAt.peek(),stale:h.state.isStale.peek(),tags:[...h.tags]}))},async fetchJSON(h,v={},{queryKey:k=["GET",h,v.body??null],...S}={}){let U=ot(k);return L.fetchQuery({queryKey:k,...S,queryFn:async({signal:F})=>{let A=new Headers(v.headers),V=u.get(U);V?.etag&&A.set("If-None-Match",V.etag);let R=await fetch(h,{...v,headers:A,signal:F});if(R.status===304&&V)return L.getQueryData(k);if(!R.ok)throw new Error(`HTTP ${R.status}`);let ve=R.headers.get("cache-control")?.match(/max-age=(\d+)/)?.[1];if(ve){let ze=r.get(U);ze&&(ze.options.staleTime=Number(ve)*1e3)}return u.set(U,{etag:R.headers.get("etag")}),R.json()}})},destroy(){f=!0;for(let h of r.values())h.ctrl?.abort(),P(h),K(h);d?.close(),c.clear()}},ge=[],be=()=>{a&&Ae()},oe=()=>{for(o&&Ae();ge.length;)ge.shift()().catch(()=>{})};typeof window<"u"&&(window.addEventListener("focus",be),window.addEventListener("online",oe));let Kt=L.destroy;return L.destroy=()=>{f||(typeof window<"u"&&(window.removeEventListener("focus",be),window.removeEventListener("online",oe)),Kt())},L},Yf=Bd(),ca=({cache:e=!0,ttl:t=3e4,retry:n=2,retryDelay:s=1e3,store:a=null,dedupe:o=!0}={})=>{let r=new Map,c=new Map,u=new Map,d=(m,g)=>{if(a)return a.get(m);let w=r.get(m);return w&&Date.now()-w.ts<g?w.data:void 0},f=async(m,g,w)=>{if(a)return a.set(m,g,{ttl:w});r.set(m,{data:g,ts:Date.now()})};return{get:(m,g,w={})=>{let y=w.ttl??t,P=e&&w.cache!==!1&&y!==0,ae=w.dedupe??o;if(ae&&c.has(m))return c.get(m);let K=()=>{let q=u.get(m)??0,Q=(he,Ae)=>Promise.resolve(g()).then(async L=>(P&&(u.get(m)??0)===q&&await f(m,L,y),L)).catch(L=>{if(he>0&&L?.name!=="AbortError")return new Promise(ge=>setTimeout(ge,Ae)).then(()=>Q(he-1,Ae*2));throw L});return Q(w.retry??n,s)},pe=q=>(ae&&(c.set(m,q),q.finally(()=>{c.get(m)===q&&c.delete(m)}).catch(()=>{})),q);if(!P)return pe(K());if(!a){let q=d(m,y);return q!==void 0?Promise.resolve(q):pe(K())}return pe(Promise.resolve(d(m,y)).then(q=>q!==void 0?q:K()))},invalidate:m=>{if(m!==void 0)u.set(m,(u.get(m)??0)+1);else{for(let g of r.keys())u.set(g,(u.get(g)??0)+1);for(let g of c.keys())u.set(g,(u.get(g)??0)+1)}if(a)return m===void 0?a.clear():a.delete(m);m===void 0?r.clear():r.delete(m)}}},Xf=new TextEncoder,Zf=new TextDecoder,Ni=(e,t="kv")=>{let n=null,s=()=>n?Promise.resolve(n):new Promise((o,r)=>{let c=indexedDB.open(e,1);c.onupgradeneeded=u=>u.target.result.createObjectStore(t),c.onsuccess=u=>{n=u.target.result,o(n)},c.onerror=u=>r(u.target.error)}),a=async(o,r)=>{let c=await s();return new Promise((u,d)=>{let f=c.transaction(t,o),m=r(f.objectStore(t));m.onsuccess=()=>u(m.result),m.onerror=()=>d(m.error)})};return{async get(o){let r=await a("readonly",c=>c.get(o));if(r){if(r.expires&&Date.now()>r.expires){this.delete(o);return}return r.val}},async set(o,r,{ttl:c}={}){await a("readwrite",u=>u.put({val:r,expires:c?Date.now()+c:null},o))},delete:o=>a("readwrite",r=>r.delete(o)),clear:()=>a("readwrite",o=>o.clear()),keys:()=>a("readonly",o=>o.getAllKeys())}}});var G=B(()=>{Pi()});var Gi={};us(Gi,{AGENT_DEFAULT_MODEL:()=>Ui,AGENT_LABELS:()=>Z,AGENT_MODELS:()=>Qo,LOW_TURN_THRESHOLD:()=>Yo,activityHits:()=>rt,activityLoading:()=>bt,addCustomModel:()=>Xt,agentFilter:()=>ye,agentFilters:()=>Yt,agentsMeta:()=>Vt,chatDensity:()=>_e,collapsedFolders:()=>_n,ctx:()=>l,currentAgent:()=>$,currentEffort:()=>te,currentModel:()=>_,currentPermission:()=>ue,currentProject:()=>E,currentTab:()=>X,expandedFolders:()=>jn,favoritesOnly:()=>Ke,filesPath:()=>Y,filesRoot:()=>ie,filteredSessions:()=>_t,getCustomModels:()=>ua,getDefaultEffort:()=>Qe,getDefaultModel:()=>Oe,getEffortsForModel:()=>Zt,getModelsForAgent:()=>Be,getSavedModel:()=>Oi,getSessionMeta:()=>Nn,gitRoot:()=>Se,hubMachineReady:()=>it,hubMode:()=>M,isProcessing:()=>N,machinesList:()=>le,metaKey:()=>J,projectGroups:()=>en,removeCustomModel:()=>er,selectedMachineId:()=>j,sessionDisplayTitle:()=>vt,sessionFilter:()=>ke,sessionMetaMap:()=>T,sessionSearch:()=>$e,sessionSort:()=>Hi,sessionsData:()=>ne,setAgent:()=>Ne,setChatDensity:()=>Xo,setCurrentModel:()=>se,setSelectedMachine:()=>Le,showHiddenOnly:()=>Je,sidebarView:()=>gt,timeRange:()=>da,viewingFile:()=>re,workspacesData:()=>fe,wsStatus:()=>me});function Ri(){try{let e=JSON.parse(localStorage.getItem(qi)||"{}");return e&&typeof e=="object"?e:{}}catch{return{}}}function Bi(e,t=l.sessionId,n=l.machineId){if(!t)return"";let s=(e||"claude").toLowerCase();return`${n||""}:${s}:${t}`}function Oi(e,t=l.sessionId,n=l.machineId){let s=Bi(e,t,n);if(!s)return null;let a=Ri()[s];return typeof a=="string"&&a.trim()?a:null}function se(e,t=$.peek(),n=l.sessionId,s=l.machineId){let a=String(e||"").trim();if(!a)return;let o=Bi(t,n,s);if(o){let r=Ri();r[o]=a,localStorage.setItem(qi,JSON.stringify(r))}_.value=a}function Le(e){let t=e||null;j.value=t,l.machineId=t,t?localStorage.setItem("machineId",t):localStorage.removeItem("machineId")}function J(e,t,n){let s=`${e||"claude"}:${t}`;return n||l?.machineId?`${n||l.machineId}:${s}`:s}function Nn(e,t,n){return T.peek()?.[J(e,t,n)]||{favorite:!1,notes:"",title:"",hidden:!1,branch:null}}function vt(e,{preferSnippet:t=!1}={}){if(!e)return"Session";if(t&&e.snippet)return e.snippet;let s=(Nn(e.agent,e.sessionId,e.machineId).title||"").trim();return s||e.display||e.sessionId?.slice(0,8)||"Session"}function Xo(e){let t=["clean","normal","full"].includes(e)?e:"normal";_e.value=t,localStorage.setItem("chatDensity",t),document.getElementById("messages")?.setAttribute("data-density",t)}function Ud(e){return e?typeof e=="string"?{value:e,label:e}:e.value?{value:String(e.value),label:e.label||e.value,...Array.isArray(e.efforts)&&e.efforts.length?{efforts:e.efforts.map(String)}:{},...e.defaultEffort?{defaultEffort:String(e.defaultEffort)}:{}}:null:null}function Zo(){try{let e=localStorage.getItem(Fi);if(!e)return{};let t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function Wi(e){localStorage.setItem(Fi,JSON.stringify(e))}function ua(e){let t=(e||"claude").toLowerCase(),n=Zo()[t];return Array.isArray(n)?n.filter(Boolean).map(String):[]}function Xt(e,t){let n=(e||"claude").toLowerCase(),s=String(t||"").trim();if(!s)return!1;let a=Zo(),o=Array.isArray(a[n])?[...a[n]]:[];return o.includes(s)||o.push(s),a[n]=o,Wi(a),!0}function er(e,t){let n=(e||"claude").toLowerCase(),s=String(t||"").trim(),a=Zo(),o=Array.isArray(a[n])?a[n].filter(r=>r!==s):[];return a[n]=o,Wi(a),!0}function Be(e){let t=(e||"claude").toLowerCase(),n=Vt.peek()?.defaults?.[t],s=n?.models?.length?n.models.map(Ud).filter(Boolean):(Qo[t]||Qo.claude).map(r=>({...r})),a=ua(t),o=new Set(s.map(r=>r.value));for(let r of a){if(o.has(r)){s=s.map(c=>{if(c.value!==r)return c;let u=String(c.label||c.value);return{...c,custom:!0,label:u.includes("\u2605")?u:`${u} \u2605`}});continue}o.add(r),s.push({value:r,label:`${r} \u2605`,custom:!0})}return s}function Oe(e){let t=(e||"claude").toLowerCase(),n=Vt.peek()?.defaults?.[t];return n?.model?String(n.model):Ui[t]||Be(t)[0]?.value||"sonnet"}function Zt(e,t){let s=Be(e).find(o=>o.value===t);if(s?.efforts?.length)return s.efforts;let a=Vt.peek()?.defaults?.[(e||"claude").toLowerCase()];return a?.efforts?.length?a.efforts.map(String):["low","medium","high","xhigh","max"]}function Qe(e,t){let n=(e||"claude").toLowerCase(),s=Vt.peek()?.defaults?.[n];if(s?.effortDefault)return String(s.effortDefault);let o=Be(n).find(r=>r.value===t);return o?.defaultEffort?String(o.defaultEffort):n==="grok"?"low":n==="gemini"&&String(t||"").match(/-(low|medium|high)$/i)?.[1]?.toLowerCase()||""}function Ne(e){let t=(e||"claude").toLowerCase();$.value=t,localStorage.setItem("agent",t),ue.value="bypassPermissions";let n=typeof document>"u"?null:document.getElementById("sel-permission");n&&(n.value=ue.peek());let s=Oi(t);s?_.value=s:se(Oe(t),t);let a=Qe(t,_.peek());a?te.value=a:t!=="grok"&&t!=="gemini"&&(te.value="")}function Fd(e,t){return!t||t==="all"?!0:(e.agent||"claude")===t}function Wd(e,t){if(!t)return!0;let n=T.value?.[J(e.agent,e.sessionId,e.machineId)];return[e.display,e.cwd,e.projectName,e.agent,e.sessionId,e.snippet,e.machineId,n?.notes,n?.title].filter(Boolean).join(" ").toLowerCase().includes(t)}function Vo(e){return Array.isArray(e)?e:e&&Array.isArray(e.results)?e.results:e&&Array.isArray(e.sessions)?e.sessions:[]}var ne,fe,ke,$e,Hi,jn,_n,Y,re,E,X,N,me,qi,Od,$,_,te,ue,ie,Se,Vt,gt,ye,Yt,da,rt,bt,T,Ke,Je,Yo,_e,M,le,j,it,l,Z,Qo,Ui,Fi,_t,en,W=B(()=>{G();ne=I([]),fe=I([]),ke=I(null),$e=I(""),Hi=I("time"),jn=I(new Set),_n=I(new Set),Y=I(""),re=I(null),E=I(null),X=I("chat"),N=I(!1),me=I("idle"),qi="modelBySession",Od=localStorage.getItem("agent")||"claude";$=I(Od),_=I("sonnet"),te=I(""),ue=I("bypassPermissions"),ie=I(""),Se=I(""),Vt=I(null),gt=I(localStorage.getItem("sidebarView")||"projects"),ye=I(localStorage.getItem("agentFilter")||"all"),Yt=I((()=>{try{let e=JSON.parse(localStorage.getItem("agentFilters")||"[]");return Array.isArray(e)?e.filter(Boolean):[]}catch{return[]}})()),da=I(localStorage.getItem("timeRange")||"14"),rt=I(null),bt=I(!1),T=I({}),Ke=I(localStorage.getItem("favoritesOnly")==="1"),Je=I(localStorage.getItem("showHiddenOnly")==="1"),Yo=2,_e=I(localStorage.getItem("chatDensity")||"normal"),M=I(!1),le=I([]),j=I(null),it=I(!1),l={token:localStorage.getItem("token"),sessionId:null,agent:null,machineId:null,ws:null,shellBubble:null,configDir:null,externalSessionReadOnly:!1,role:null,username:null,lock:{key:null,token:null,holder:null,held:!1,foreign:!1}};Z={claude:"Claude",codex:"Codex",grok:"Grok",gemini:"Gemini",cursor:"Cursor"},Qo={claude:[{value:"fable",label:"fable"},{value:"opus",label:"opus"},{value:"sonnet",label:"sonnet"},{value:"haiku",label:"haiku"}],codex:[{value:"gpt-5.4",label:"gpt-5.4"},{value:"gpt-5.3",label:"gpt-5.3"},{value:"gpt-5.2",label:"gpt-5.2"},{value:"o3",label:"o3"},{value:"o4-mini",label:"o4-mini"},{value:"codex-mini-latest",label:"codex-mini"}],grok:[{value:"grok-4.5",label:"grok-4.5"},{value:"grok-4",label:"grok-4"},{value:"grok-3",label:"grok-3"},{value:"grok-3-mini",label:"grok-3-mini"}],gemini:[{value:"gemini-3.7-flash-high",label:"Gemini 3.7 Flash (High)"},{value:"gemini-3.7-flash-medium",label:"Gemini 3.7 Flash (Medium)"},{value:"gemini-3.7-flash-low",label:"Gemini 3.7 Flash (Low)"},{value:"gemini-3.6-flash-high",label:"Gemini 3.6 Flash (High)"},{value:"gemini-3.6-flash-medium",label:"Gemini 3.6 Flash (Medium)"},{value:"gemini-3.6-flash-low",label:"Gemini 3.6 Flash (Low)"},{value:"gemini-3.5-flash-high",label:"Gemini 3.5 Flash (High)"},{value:"gemini-3.5-flash-medium",label:"Gemini 3.5 Flash (Medium)"},{value:"gemini-3.5-flash-low",label:"Gemini 3.5 Flash (Low)"},{value:"gemini-3.1-pro-high",label:"Gemini 3.1 Pro (High)"},{value:"gemini-3.1-pro-low",label:"Gemini 3.1 Pro (Low)"}],cursor:[{value:"auto",label:"Auto"},{value:"gpt-5.3-codex",label:"GPT-5.3 Codex"},{value:"composer-2.5",label:"Composer 2.5"}]},Ui={claude:"sonnet",codex:"gpt-5.4",grok:"grok-4.5",gemini:"gemini-3.7-flash-high",cursor:"auto"};Fi="customModelsByAgent";_t=Jo(()=>{let e=$e.value.toLowerCase().trim(),t=Hi.value,n=ye.value,s=Yt.value,a=Ke.value,o=Je.value,r=T.value,c=rt.value,u=c?.results?.length&&e?Vo(c.results):Vo(ne.value),d=j.value;return M.value&&d&&(u=u.filter(f=>f&&(!f.machineId||f.machineId===d))),u=u.filter(f=>f&&(s.length?s.includes(f.agent||"claude"):Fd(f,n))),o?u=u.filter(f=>f&&r?.[J(f.agent,f.sessionId,f.machineId)]?.hidden):u=u.filter(f=>f&&!r?.[J(f.agent,f.sessionId,f.machineId)]?.hidden),a&&(u=u.filter(f=>f&&r?.[J(f.agent,f.sessionId,f.machineId)]?.favorite)),e&&!(c?.results&&c.q===e)&&(u=u.filter(f=>f&&Wd(f,e))),u=[...u].sort((f,m)=>{let g=r?.[J(f.agent,f.sessionId,f.machineId)]?.favorite?1:0,w=r?.[J(m.agent,m.sessionId,m.machineId)]?.favorite?1:0;return g!==w?w-g:t==="project"&&(f.cwd||"").localeCompare(m.cwd||"")||m.updatedAt-f.updatedAt}),!e&&!a?u.slice(0,120):u}),en=Jo(()=>{let e=Vo(_t.value),t=new Map;for(let n of e){if(!n)continue;let s=n.machineId?`${n.machineId}::${n.cwd||"(no path)"}`:n.cwd||"(no path)";t.has(s)||t.set(s,{cwd:n.cwd||null,machineId:n.machineId||null,projectName:n.projectName||(n.cwd?n.cwd.split("/").filter(Boolean).pop():"(no path)"),updatedAt:0,agents:{},sessions:[],latest:null});let a=t.get(s);a.sessions.push(n),a.agents[n.agent||"claude"]=(a.agents[n.agent||"claude"]||0)+1,(n.updatedAt||0)>a.updatedAt&&(a.updatedAt=n.updatedAt,a.latest=n)}return[...t.values()].sort((n,s)=>s.updatedAt-n.updatedAt)})});function hs(e={}){return e.machineId!==void 0?e.machineId:l.machineId||j.peek()||null}function Kd(e){let t=e.split("?")[0];return t==="/api/hub"||t==="/api/machines"||t==="/api/notifications"||t==="/api/notifications/read"||t==="/api/notes"||t.startsWith("/api/notes/")||t==="/api/queue"||t.startsWith("/api/queue/")||t.startsWith("/api/ai/")||t.startsWith("/api/auth/")||t.startsWith("/api/collab/")}async function x(e,t,n,s,a={}){let o=a.hub?null:hs(a),r={"Content-Type":"application/json",...l.token?{Authorization:`Bearer ${l.token}`}:{}};!a.hub&&M.peek()&&o&&!Kd(t)&&(r["X-Machine-Id"]=o),e.toUpperCase()!=="GET"&&e.toUpperCase()!=="HEAD"&&l.lock?.token&&l.lock?.key&&!String(t).startsWith("/api/collab/")&&(r["X-Lock-Token"]=l.lock.token,r["X-Lock-Key"]=l.lock.key);let u=a.etag===!0?`${l.token||""}:${o||""}:${t}`:a.etag||null;if(e.toUpperCase()==="GET"&&u){let m=Ki.get(u);m&&(r["If-None-Match"]=m)}let d=async()=>{let m=await fetch(t,{method:e,signal:s,headers:r,cache:a.cache||(e.toUpperCase()==="GET"?"no-store":"default"),...n!==void 0?{body:JSON.stringify(n)}:{}});if(m.status===304)return zd;let g=await m.json().catch(()=>({}));if(!m.ok)throw new Error(g.error||`HTTP ${m.status}`);if(u){let w=m.headers.get("ETag");w&&Ki.set(u,w)}return g};if(e.toUpperCase()!=="GET"||s||a.dedupe===!1)return d();let f=`${l.token||""}:${o||""}:${t}`;return Gd.get(f,d)}function lt(e){return l.ws?.readyState===WebSocket.OPEN?(l.ws.send(JSON.stringify(e)),!0):(e?.type==="ping"||e?.type==="pong"||e?.type==="subscribe"||pa.push(e),!1)}function fa(){for(;pa.length&&l.ws?.readyState===WebSocket.OPEN;)l.ws.send(JSON.stringify(pa.shift()))}function ma(){pa.length=0}function gs(e={}){let t=new URLSearchParams(e);l.token&&t.set("token",l.token);let n=hs();return M.peek()&&n&&t.set("machine",n),t.toString()}function ct(e={},t={}){let n={...e};l.token&&(n.Authorization=`Bearer ${l.token}`);let s=hs();return!t.hub&&M.peek()&&s&&(n["X-Machine-Id"]=s),n}async function ha(){try{let e=await fetch("/api/hub");if(!e.ok)return M.value=!1,!1;let t=await e.json();if(t?.hub)return M.value=!0,t}catch{}return M.value=!1,!1}var Gd,Ki,zd,pa,ce=B(()=>{W();G();Gd=ca({cache:!1,dedupe:!0,retry:0}),Ki=new Map,zd=Symbol("not-modified");pa=[]});function tn(e,t){e&&(t?e.setAttribute("inert",""):e.removeAttribute("inert"))}function Pn(e){return!e||e.classList.contains("hidden")?!0:e.style.display==="none"}function Ee(){let e=typeof window<"u"&&window.matchMedia("(max-width: 640px)").matches,t=document.getElementById("sidebar");if(t){let s=!e||t.classList.contains("open");tn(t,!s)}tn(document.getElementById("welcome"),Pn(document.getElementById("welcome"))),tn(document.getElementById("auth-screen"),Pn(document.getElementById("auth-screen"))),tn(document.getElementById("chat-opts"),Pn(document.getElementById("chat-opts"))),tn(document.getElementById("machine-picker"),Pn(document.getElementById("machine-picker")));for(let s of["files","git","shell","memory"]){let a=document.getElementById(`tab-${s}`);tn(a,Pn(a))}let n=document.getElementById("tab-chat");n&&tn(n,Pn(n))}function bs(){let e=window.visualViewport,t=document.documentElement;if(!e)return;let n=e.height<window.innerHeight-80;t.classList.toggle("vv-keyboard",n),t.style.setProperty("--vvh",`${Math.round(e.height)}px`),t.style.setProperty("--vv-top",`${Math.round(e.offsetTop)}px`)}function Qi(){Ee(),bs();let e=window.visualViewport;e&&(e.addEventListener("resize",bs),e.addEventListener("scroll",bs)),window.addEventListener("resize",()=>{bs(),Ee()}),window.addEventListener("orientationchange",()=>{setTimeout(()=>{bs(),Ee()},250)})}var Hn=B(()=>{});function nn(){try{let e=localStorage.getItem(Vi);return e?JSON.parse(e):null}catch{return null}}function tr(e){try{let n={...nn()||{},...e,updatedAt:Date.now()};localStorage.setItem(Vi,JSON.stringify(n))}catch{}}var Vi,ba=B(()=>{Vi="lastSessionContext"});function Jd(e){let t=String(e??"").trim();if(!t)return"";try{return decodeURIComponent(t)}catch{return t}}function Yi(e){return String(e||"").replace(/\\/g,"/")}function Qd(e){return e.replace(/:[0-9]+(?::[0-9]+)?$/,"")}function va(e,t){let n=Jd(e);if(!n||/^(https?:|mailto:|tel:|javascript:|#)/i.test(n)||(n=Yi(n).split(/[?#]/)[0],n=n.replace(/^file:\/\//i,""),/^\/[A-Za-z]:\//.test(n)&&(n=n.slice(1)),!n||n==="."||n==="/")||/^\/(api|ws|session)\b/.test(n))return null;let s=n.endsWith("/"),a=Qd(n.replace(/\/+$/,"")),o=Yi(t).replace(/\/+$/,"");if((a.startsWith("/")||/^[A-Za-z]:\//.test(a))&&o){let c=a.toLowerCase(),u=o.toLowerCase();if(c===u)return{relative:"",isDir:!0,root:o};if(c.startsWith(`${u}/`))return{relative:a.slice(o.length+1),isDir:s,root:o};let d=a.split("/"),f=d.pop()||"",m=d.join("/")||(a.startsWith("/")?"/":"");return{relative:f,isDir:s,root:m}}if(a=a.replace(/^\.\//,""),a.startsWith("../")&&o){let c=o.split("/"),u=a.split("/");for(let f of u)f===".."?c.pop():f&&f!=="."&&c.push(f);let d=c.join("/")||"/";return va(d,t)}return{relative:a,isDir:s,root:o||t}}var nr=B(()=>{});function Yd(){let e=document.getElementById("mermaid-zoom-overlay");if(e)return e;e=document.createElement("div"),e.id="mermaid-zoom-overlay",e.className="mermaid-zoom-overlay hidden",e.setAttribute("role","dialog"),e.setAttribute("aria-modal","true"),e.setAttribute("aria-label","Mermaid diagram enlarged"),e.innerHTML='<button type="button" class="mermaid-zoom-close" aria-label="\u5173\u95ED\u653E\u5927\u56FE">\xD7</button><div class="mermaid-zoom-canvas"></div>',document.body.appendChild(e);let t=()=>e.classList.add("hidden");return e.addEventListener("click",n=>{(n.target===e||n.target.closest(".mermaid-zoom-close"))&&t()}),Zi||(Zi=!0,document.addEventListener("keydown",n=>{n.key==="Escape"&&t()})),e}function el(e){let t=e.querySelector("svg");if(!t)return;let n=Yd(),s=n.querySelector(".mermaid-zoom-canvas");s.innerHTML=t.outerHTML;let a=s.querySelector("svg");a?.removeAttribute("width"),a?.removeAttribute("height"),n.classList.remove("hidden")}function Xd(){let e=globalThis.mermaid;return!e||Xi||(e.initialize({startOnLoad:!1,securityLevel:"strict",theme:document.documentElement.dataset.theme==="dark"?"dark":"default",flowchart:{htmlLabels:!1}}),Xi=!0),e}function Zd(e){let t=String(e||"").replace(/\r\n?/g,`
|
|
2
|
+
`).trim();return t=t.replace(/^```(?:mermaid)?\s*/i,"").replace(/\s*```$/,"").trim(),t=t.replace(/^mermaid\s*\n/i,""),t=t.replace(/^graph\s+(TD|TB|BT|RL|LR)\b/i,"flowchart $1"),t}function xt(e){let t=Xd();!t||!e||e.querySelectorAll("pre code.language-mermaid, pre code.lang-mermaid").forEach(n=>{if(n.dataset.mermaidHandled)return;let s=n.closest("pre"),a=Zd(n.textContent);if(!s||!a)return;n.dataset.mermaidHandled="1";let o=document.createElement("div");o.className="mermaid-diagram",o.setAttribute("role","img"),o.setAttribute("aria-label","Mermaid diagram"),s.replaceWith(o);let r=`mermaid-diagram-${++Vd}`;Promise.resolve(t.parse(a)).then(()=>t.render(r,a)).then(({svg:c,bindFunctions:u})=>{o.innerHTML=c,u?.(o),o.tabIndex=0,o.title="\u70B9\u51FB\u653E\u5927\u56FE\u8868",o.addEventListener("click",d=>{d.target.closest("a")||el(o)}),o.addEventListener("keydown",d=>{(d.key==="Enter"||d.key===" ")&&(d.preventDefault(),el(o))})}).catch(c=>{o.replaceWith(s),delete n.dataset.mermaidHandled,s.classList.add("mermaid-error"),s.title=`Mermaid render failed: ${c?.message||"invalid diagram"}`})})}var Xi,Vd,Zi,qn=B(()=>{Xi=!1,Vd=0,Zi=!1});function ar(e){return eu.test(String(e||""))}function tu(e){return String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function tl(e,t){return t===0||e[t-1]===`
|
|
3
|
+
`}function nu(e,t){if(tl(e,t)&&(e.startsWith("```",t)||e.startsWith("~~~",t))){let n=e.startsWith("```",t)?"```":"~~~",s=e.indexOf(`
|
|
4
|
+
`+n,t+3);return s===-1?{end:e.length}:{end:s+1+n.length}}if(e[t]==="`"){let n=1;for(;e[t+n]==="`";)n++;let s=t+n;for(;s<e.length;){if(e[s]==="`"){let a=0;for(;e[s+a]==="`";)a++;if(a===n)return{end:s+a};s+=a;continue}s++}return{end:t+n}}return null}function su(e,t){let n=e.slice(t);if(n.startsWith("$$")){let s=n.indexOf("$$",2);if(s>=2){let a=n.slice(2,s);if(a.trim())return{body:a,display:!0,end:t+s+2}}}if(n.startsWith("\\[")){let s=n.indexOf("\\]",2);if(s>=2){let a=n.slice(2,s);if(a.trim())return{body:a,display:!0,end:t+s+2}}}if(n.startsWith("\\(")){let s=n.indexOf("\\)",2);if(s>=2){let a=n.slice(2,s);if(a.trim())return{body:a,display:!1,end:t+s+2}}}if(n[0]==="$"&&n[1]!=="$"){let s=n.match(/^\$([^$\n]|\\\$)+?(?<!\s)\$/);if(s&&s[0][1]!==" "){let a=s[0].slice(1,-1);if(a.trim())return{body:a,display:!1,end:t+s[0].length}}}if(tl(e,t)){let s=n.match(/^[ \t]*\[[ \t]*\n([\s\S]*?)\n[ \t]*\][ \t]*(?=\n|$)/);if(s&&ar(s[1]))return{body:s[1],display:!0,end:t+s[0].length};let a=n.match(/^[ \t]*\[([^\]\n]+)\](?!\()/);if(a&&ar(a[1]))return{body:a[1],display:!0,end:t+a[0].length}}return null}function nl(e){let t=[],n=String(e??""),s="",a=0;for(;a<n.length;){let o=nu(n,a);if(o){s+=n.slice(a,o.end),a=o.end;continue}let r=su(n,a);if(r){let c=t.length;t.push({body:r.body,display:r.display}),s+=`@@MATH${c}@@`,a=r.end;continue}s+=n[a],a++}return{text:s,slots:t}}function xa(e,t){return t?.length?String(e).replace(/@@MATH(\d+)@@/g,(n,s)=>{let a=t[Number(s)];if(!a)return n;let o=a.display?"\\[":"\\(",r=a.display?"\\]":"\\)";return tu(`${o}${a.body}${r}`)}):e}function au(e){return e.parentElement?.closest("pre, code, .mermaid-diagram, .katex, script, style")}function sr(e,t){let n=[{re:/\\\[([\s\S]+?)\\\]/g,display:!0},{re:/\$\$([\s\S]+?)\$\$/g,display:!0},{re:/\\\(([\s\S]+?)\\\)/g,display:!1},{re:/(?<!\\)\$([^$\n]|\\\$)+?(?<!\s)(?<!\\)\$/g,display:!1},{re:/(?:^|\n)[ \t]*\[[ \t]*\n([\s\S]*?)\n[ \t]*\][ \t]*(?=\n|$)/g,display:!0,latex:!0},{re:/(?:^|\n)[ \t]*\[([^\]\n]+\\[a-zA-Z{}_^][^\]\n]*)\](?!\()/g,display:!0,latex:!0}],s=null;for(let a of n){a.re.lastIndex=t;let o=a.re.exec(e);if(!o||s&&o.index>=s.match.index)continue;let r=o[0],c;o[1]!=null&&(a.latex||r.startsWith("\\[")||r.startsWith("\\(")||r.startsWith("$$")||r.startsWith("$"))?c=o[1]:c=r.startsWith("\\[")||r.startsWith("\\(")||r.startsWith("$$")?r.slice(2,-2):r.slice(1,-1),c.trim()&&(a.latex&&!ar(c)||(s={match:o,body:c,display:a.display}))}return s}function ou(e){let t=e.nodeValue||"",n=0,s=sr(t,n);if(!s||typeof globalThis.katex?.renderToString!="function")return;let a=document.createDocumentFragment();for(;s;){s.match.index>n&&a.append(document.createTextNode(t.slice(n,s.match.index)));let o;try{o=globalThis.katex.renderToString(s.body.trim(),{displayMode:s.display,throwOnError:!1,strict:"warn"})}catch{a.append(document.createTextNode(s.match[0])),n=s.match.index+s.match[0].length,s=sr(t,n);continue}let r=document.createElement(s.display?"div":"span");r.className=s.display?"math-display":"math-inline",r.innerHTML=o,a.append(r),n=s.match.index+s.match[0].length,s=sr(t,n)}n<t.length&&a.append(document.createTextNode(t.slice(n))),e.replaceWith(a)}function yt(e){if(!e||typeof globalThis.katex?.renderToString!="function")return;let t=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),n=[];for(;t.nextNode();)au(t.currentNode)||n.push(t.currentNode);n.forEach(ou)}var eu,sn=B(()=>{eu=/\\[a-zA-Z]+|[_^]\{|\\[,;!]|\\[{}()[\]]|\\leq\b|\\geq\b|\\neq\b|\\in\b|\\sum\b|\\int\b|\\frac\b|\\min\b|\\max\b|\\mathrm\b|\\text\b|\\left\b|\\right\b/});function iu(e){return String(e??"").replace(ru,(t,n)=>`
|
|
5
5
|
|
|
6
6
|
> \u26A0\uFE0F \u539F\u59CB\u8BB0\u5F55\u5DF2\u622A\u65AD\uFF08${n} bytes\uFF09
|
|
7
7
|
|
|
8
|
-
`)}function Ve(e,{fallback:t}={}){let{text:n,slots:s}=
|
|
8
|
+
`)}function Ve(e,{fallback:t}={}){let{text:n,slots:s}=nl(iu(e));if(typeof marked>"u"){let a=t?t(n):n;return xa(a,s)}try{return xa(marked.parse(n,{breaks:!0,gfm:!0}),s)}catch{let a=t?t(n):n;return xa(a,s)}}var ru,an=B(()=>{sn();ru=/(?:<|\[)\s*(?:…\s*)?truncated\s+([\d,]+)\s+bytes\s*(?:>|\])/gi});function ya(e){return e==null?"":e>1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:e>1024?`${(e/1024).toFixed(1)} KB`:`${e} B`}function wa(e,t,n){let s=e||"file";if(n>0&&t!=null){let a=Math.min(100,Math.round(t/n*100));return`\u6B63\u5728\u4E0B\u8F7D ${s}\uFF08${a}%\uFF09`}return t>0?`\u6B63\u5728\u4E0B\u8F7D ${s}\uFF08${ya(t)}\uFF09`:`\u6B63\u5728\u4E0B\u8F7D ${s}\u2026`}function or(e){return`\u5DF2\u4FDD\u5B58 ${e||"file"}\uFF0C\u8BF7\u67E5\u770B\u6D4F\u89C8\u5668\u4E0B\u8F7D\u680F`}function vs(e){return`\u5DF2\u4EA4\u7ED9\u6D4F\u89C8\u5668\u4E0B\u8F7D ${e||"file"}`}var rr=B(()=>{});function ir(e,t){let n=va(e,t||ie.peek()||E.peek()?.path||"");if(!n)return!1;if(n.root&&(ie.value=n.root),n.isDir)re.value=null,Y.value=n.relative;else{let s=n.relative.split("/").filter(Boolean);Y.value=s.slice(0,-1).join("/"),re.value=n.relative}return X.value="files",!0}var lr=B(()=>{G();W();ce();nr();qn();sn();an();rr()});function cu({sessionId:e=l.sessionId,agent:t=l.agent||$.peek()||"claude",machineId:n=l.machineId||j.peek()||"local"}={}){return e?`session:${n||"local"}:${t||"claude"}:${e}`:null}function on(){return!((l.role||"editor")==="viewer"||l.lock?.foreign)}function du(){document.dispatchEvent(new CustomEvent("session-lock-changed",{detail:l.lock}))}function Rn(e){l.lock={key:null,token:null,holder:null,held:!1,foreign:!1,...e||{}},du()}async function wt(e={}){let t=cu(e);return t?(l.role||"editor")==="viewer"?(Rn({key:t,held:!1,foreign:!0,holder:"viewer"}),{ok:!1,error:"viewers cannot take exclusive locks",code:403}):(l.lock?.key&&l.lock.key!==t&&await $a(),xs||(xs=(async()=>{try{let s={key:t,kind:"session",ttlSec:cr,exclusive:!0,...l.lock?.token&&l.lock?.key===t?{token:l.lock.token}:{}},a=await x("POST","/api/collab/locks",s,void 0,{hub:!0});return Rn({key:t,token:a.token,holder:a.holder,held:!0,foreign:!1,expiresAt:a.expiresAt,version:a.version}),pu(),{ok:!0,lock:a}}catch(s){let a=String(s.message||s);return/locked|HTTP 423|423/.test(a)?(Rn({key:t,held:!1,foreign:!0,holder:"another user"}),{ok:!1,code:423,error:a}):(Rn({key:t,held:!0,foreign:!1,unmanaged:!0}),{ok:!0,skipped:!0,error:a})}finally{xs=null}})(),xs)):(Rn({foreign:!1,held:!0,unmanaged:!0}),{ok:!0,skipped:!0})}async function uu(){let{key:e,token:t,held:n}=l.lock||{};if(!(!e||!t||!n))try{let s=await x("POST","/api/collab/lock-action",{key:e,action:"heartbeat",token:t,ttlSec:cr},void 0,{hub:!0});s?.token&&(l.lock.token=s.token),s?.expiresAt&&(l.lock.expiresAt=s.expiresAt)}catch(s){let a=String(s.message||s);/token mismatch|HTTP 409|409|no lock|HTTP 404|404/.test(a)&&((await wt()).ok||dr())}}function pu(){dr(),ka=setInterval(()=>{uu().catch(()=>{})},lu)}function dr(){ka&&(clearInterval(ka),ka=null)}async function $a(){dr();let{key:e,token:t}=l.lock||{};if(Rn({held:!1,foreign:!1}),!!e)try{await x("POST","/api/collab/lock-action",{key:e,action:"release",token:t,ttlSec:cr},void 0,{hub:!0})}catch{}}async function sl(){try{let e=await x("GET","/api/collab/me",void 0,void 0,{hub:!0});return l.role=e?.role||l.role||"editor",l.username=e?.username||l.username||null,e}catch{return l.role||(l.role="editor"),null}}var cr,lu,ka,xs,ys=B(()=>{W();ce();cr=60,lu=2e4,ka=null,xs=null});async function ur(){if(ws&&!(typeof navigator>"u"||!navigator.wakeLock?.request)&&document.visibilityState==="visible"&&!rn)try{rn=await navigator.wakeLock.request("screen"),rn.addEventListener("release",()=>{rn=null,ws&&document.visibilityState==="visible"&&setTimeout(()=>{ur().catch(()=>{})},500)})}catch{rn=null}}async function al(){let e=rn;if(rn=null,!!e)try{await e.release()}catch{}}function Sa(e){ws=!!e,ws?ur().catch(()=>{}):al().catch(()=>{})}function pr(){typeof document>"u"||document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&ws?ur().catch(()=>{}):document.visibilityState==="hidden"&&al().catch(()=>{})})}var rn,ws,fr=B(()=>{rn=null,ws=!1});function O(e){if(e==null||e==="")return null;if(typeof e=="number")return!Number.isFinite(e)||e<=0?null:e<1e12?Math.round(e*1e3):Math.round(e);if(typeof e=="string"){let t=e.trim();if(/^\d+(\.\d+)?$/.test(t))return O(Number(t));let n=Date.parse(t);return Number.isNaN(n)?null:n}return null}function Bn(e){let t=O(e);if(t==null)return"";let n=Date.now()-t;return n<0?new Date(t).toLocaleDateString():n<6e4?"just now":n<36e5?`${Math.floor(n/6e4)}m ago`:n<864e5?`${Math.floor(n/36e5)}h ago`:n<7*864e5?`${Math.floor(n/864e5)}d ago`:new Date(t).toLocaleDateString()}function On(e,t=!0){let n=e||"claude",a={claude:"bg-orange-500/15 text-orange-400",codex:"bg-emerald-500/15 text-emerald-400",grok:"bg-sky-500/15 text-sky-400",gemini:"bg-violet-500/15 text-violet-400",cursor:"bg-amber-500/15 text-amber-400"}[n]||"bg-base-300 text-base-content/50",o=t?n==="claude"?"CC":n==="codex"?"CX":n==="grok"?"GX":n==="gemini"?"GM":n==="cursor"?"CU":n.slice(0,2).toUpperCase():Z[n]||n;return`<span class="text-[9px] px-1 py-0.5 rounded font-mono font-semibold flex-shrink-0 ${a}" title="${p(Z[n]||n)}">${o}</span>`}function Un(e){if(!e)return"";let t="",n=e.split("/").filter(Boolean);return n.length<=3?e:"\u2026/"+n.slice(-2).join("/")}var Nt=B(()=>{G();W()});function fu(e){let t=O(e);if(t==null)return"";let n=new Date(t);return Number.isNaN(n.getTime())?"":n.toLocaleString()}function ol(){let e=i("notifications-badge");if(e){if(!ln){e.classList.add("hidden"),e.textContent="0";return}e.classList.remove("hidden"),e.textContent=ln>99?"99+":String(ln)}}function ll(){let e=i("notifications-menu"),t=i("btn-notifications"),n=i("topbar");if(!e||!t||!n)return;let s=t.getBoundingClientRect(),a=n.getBoundingClientRect(),o=Math.min(416,window.innerWidth-16),r=Math.max(8,Math.min(window.innerWidth-o-8,s.right-o));e.style.top=`${Math.round(a.bottom+8)}px`,e.style.left=`${Math.round(r)}px`,e.style.width=`${Math.round(o)}px`}function ks(){let e=i("notifications-menu-list"),t=i("notifications-menu-empty");if(!(!e||!t)){if(!Pe.length){e.innerHTML="",t.classList.remove("hidden"),ol();return}t.classList.add("hidden"),e.innerHTML=Pe.map(n=>`
|
|
9
9
|
<button type="button"
|
|
10
10
|
class="w-full text-left rounded-lg border px-3 py-2 transition-colors hover:bg-base-200/70 ${n.unread?"border-primary/35 bg-primary/5":"border-base-300 bg-base-100"}"
|
|
11
11
|
data-notification-id="${p(n.id)}"
|
|
@@ -24,47 +24,47 @@ var Ld=Object.defineProperty;var W=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(
|
|
|
24
24
|
<div class="flex items-center gap-2 mt-1 text-[10px] text-base-content/35">
|
|
25
25
|
${n.projectName?`<span class="font-mono truncate">${p(n.projectName)}</span>`:""}
|
|
26
26
|
${n.machineId?`<span class="px-1 py-0.5 rounded bg-base-300 text-base-content/55 font-mono">${p(n.machineId)}</span>`:""}
|
|
27
|
-
<span>${p(
|
|
27
|
+
<span>${p(fu(n.createdAt))}</span>
|
|
28
28
|
</div>
|
|
29
29
|
</div>
|
|
30
30
|
</div>
|
|
31
|
-
</button>`).join(""),
|
|
31
|
+
</button>`).join(""),ol()}}function cn(){i("notifications-menu")?.classList.add("hidden"),i("notifications-backdrop")?.classList.add("hidden"),i("btn-notifications")?.setAttribute("aria-expanded","false")}function mu(){ll(),i("notifications-menu")?.classList.remove("hidden"),i("notifications-backdrop")?.classList.remove("hidden"),i("btn-notifications")?.setAttribute("aria-expanded","true")}function cl(){let e=i("notifications-menu");e&&(e.classList.contains("hidden")?mu():cn())}function rl(e){let t=new Map;for(let n of e||[])n?.id&&t.set(String(n.id),n);Pe=[...t.values()].sort((n,s)=>(O(s.createdAt)||0)-(O(n.createdAt)||0)),ln=Pe.reduce((n,s)=>n+(s.unread?1:0),0),ks()}async function La(){try{let e=await x("GET","/api/notifications?limit=80");Pe=Array.isArray(e?.notifications)?e.notifications:[],ln=Number(e?.unreadCount)||Pe.reduce((t,n)=>t+(n.unread?1:0),0),ks()}catch{Pe=[],ln=0,ks()}}async function il(e=null){let t=await x("POST","/api/notifications/read",e?.length?{ids:e}:{});Pe=Array.isArray(t?.notifications)?t.notifications:Pe.map(n=>!e||e.includes(n.id)?{...n,unread:!1}:n),ln=Number(t?.unreadCount)||Pe.reduce((n,s)=>n+(s.unread?1:0),0),ks()}function hu(e){if(!(typeof Notification>"u")&&document.visibilityState!=="visible"&&Notification.permission==="granted")try{let t=new Notification(e.title||"Session done",{body:e.body||e.projectName||e.sessionId||"",tag:e.id});t.onclick=()=>{window.focus(),t.close()}}catch{}}function Ea(e){if(!e?.id)return;if(Pe.find(n=>n.id===e.id)){rl([e,...Pe.filter(n=>n.id!==e.id)]);return}rl([e,...Pe]),hu(e)}function dl(e={}){mr=typeof e.openSession=="function"?e.openSession:null,ks(),La(),typeof Notification<"u"&&Notification.permission==="default"&&document.addEventListener("click",()=>{try{Notification.requestPermission().catch(()=>{})}catch{}},{once:!0}),b.on("click","#notifications-backdrop",t=>{t.preventDefault(),t.stopPropagation(),cn()}),b.on("click","#btn-notifications-read-all",async t=>{t.preventDefault(),t.stopPropagation(),await il()}),b.on("click","[data-notification-id]",async(t,n)=>{let s=n.dataset.notificationId;s&&(await il([s]),cn(),!(!mr||!n.dataset.notificationSession)&&mr(n.dataset.notificationSession,n.dataset.notificationCwd||null,null,n.dataset.notificationAgent||"claude",n.dataset.notificationMachine||null))}),document.addEventListener("click",t=>{let n=i("notifications-menu"),s=i("btn-notifications"),a=t.target;!n||n.classList.contains("hidden")||n.contains(a)||s?.contains(a)||cn()}),window.addEventListener("resize",()=>{i("notifications-menu")&&!i("notifications-menu").classList.contains("hidden")&&ll()})}var Pe,ln,mr,Ia=B(()=>{G();ce();Nt();Pe=[],ln=0,mr=null});function $s(e,t=80){return e?e.scrollHeight-e.scrollTop-e.clientHeight<t:!0}function gu(e,t){return e<0?!1:t}function bu({force:e=!1,following:t=!0,userScrolling:n=!1}={}){return e?!0:n?!1:t}function Ta(e){let t=!0,n=!1,s=0,a=()=>{t=$s(e),n=!1},o=u=>{t=gu(u.deltaY,t),u.deltaY<0&&(n=!0)},r=u=>{s=u.touches?.[0]?.clientY||0},c=u=>{(u.touches?.[0]?.clientY||0)-s>8&&(t=!1,n=!0)};return e.addEventListener("scroll",a,{passive:!0}),e.addEventListener("wheel",o,{passive:!0}),e.addEventListener("touchstart",r,{passive:!0}),e.addEventListener("touchmove",c,{passive:!0}),{stick(u=!1){bu({force:u,following:t,userScrolling:n})&&(e.scrollTop=e.scrollHeight,t=!0)},setFollowing(u){t=!!u},isFollowing(){return t},destroy(){e.removeEventListener("scroll",a),e.removeEventListener("wheel",o),e.removeEventListener("touchstart",r),e.removeEventListener("touchmove",c)}}}var hr=B(()=>{});function vu(){return Z[$.peek()]||"Assistant"}function xu(e){let t=String(e||"").trim();return/remote compact task|error decoding response body/i.test(t)?"Codex \u4F1A\u8BDD\u538B\u7F29\u5931\u8D25\uFF08\u7F51\u7EDC\u4E2D\u65AD\uFF09\u3002\u518D\u53D1\u4E00\u6761\u6D88\u606F\u91CD\u8BD5\uFF0C\u6216\u5F00\u65B0\u4F1A\u8BDD\u3002":t||"\u53D1\u9001\u5931\u8D25"}function gl(e){return e?(dn&&dn.el===e||(dn?.destroy?.(),dn=Ta(e),dn.el=e),dn):null}function He(e,t){if(!e||e.dataset.historyPainting==="1")return;gl(e).stick(!!t)}function qa(){try{Fe.length?sessionStorage.setItem(xr,JSON.stringify(Fe.slice(-30))):sessionStorage.removeItem(xr)}catch{}}function wu(){let e=St(),t=Fe.filter(n=>n.key===e).length;t&&!fl.has(e)&&(fl.add(e),C(`\u231B Restored ${t} queued prompt${t===1?"":"s"} in this browser tab`))}function bl(e=l.sessionId,t=l.agent,n=l.machineId){return e?`${n||""}:${t||"claude"}:${e}`:""}function ku(e={}){let t=bl(e.sessionId,e.agent,e.machineId);if(!t)return 0;try{return Number(JSON.parse(localStorage.getItem(vr)||"{}")[t])||0}catch{return 0}}function $u(e){let t=Number(e?.hubSeq)||0;if(!t)return!0;let n=bl(e.sessionId||l.sessionId,e.agent||l.agent,l.machineId);if(!n)return!0;let s={};try{s=JSON.parse(localStorage.getItem(vr)||"{}")||{}}catch{}let a=Number(s[n])||0;if(t<=a)return!1;s[n]=t;let o=Object.keys(s);o.length>500&&o.sort((r,c)=>Number(s[c])-Number(s[r])).slice(500).forEach(r=>delete s[r]);try{localStorage.setItem(vr,JSON.stringify(s))}catch{}return!0}function St({sessionId:e=l.sessionId,agent:t=l.agent,machineId:n=l.machineId}={}){return e?`${n||""}:${t||"claude"}:${e}`:null}function Kn(e){let t=St(e),n=i("chat-input");!t||!n||(n.value?un.set(t,n.value):un.delete(t))}function Jn(e){let t=i("chat-input");t&&(t.value=un.get(St(e))||"",Cs(t),Ts(t.value))}function Qn(e){let t=St(e);if(!t)return;let n=Fe.filter(a=>a.key===t);if(!n.length)return;Fe=Fe.filter(a=>a.key!==t),qa();let s=un.get(t)||"";un.set(t,[s,...n.map(a=>a.text)].filter(Boolean).join(`
|
|
32
32
|
|
|
33
|
-
`))}function
|
|
33
|
+
`))}function Vn(){N.peek()&&(N.value=!1,pn())}function Su(){ul||(ul=!0,document.addEventListener("visibilitychange",()=>{if(document.visibilityState==="visible"&&(ut=400,Fn({probe:!0}),l.ws?.readyState===WebSocket.OPEN&&l.sessionId))try{l.ws.send(JSON.stringify({type:"subscribe",sessionId:l.sessionId,agent:l.agent}))}catch{}}),window.addEventListener("online",()=>{ut=400,Fn({force:!0})}),window.addEventListener("pageshow",e=>{e.persisted?Fn({force:!0}):Fn({probe:!0})}),window.addEventListener("focus",()=>Fn({probe:!0})),navigator.connection?.addEventListener?.("change",()=>{ut=400,Fn({probe:!0})}))}function Ma(){let e=i("conn-dot");if(!e)return;let t=me.peek();e.classList.remove("bg-success","bg-warning","bg-error","bg-base-content/30","animate-pulse"),t==="open"?(e.classList.add("bg-success"),e.title="\u5DF2\u8FDE\u63A5"):t==="connecting"||t==="reconnecting"?(e.classList.add("bg-warning","animate-pulse"),e.title=t==="connecting"?"\u8FDE\u63A5\u4E2D\u2026":"\u91CD\u8FDE\u4E2D\u2026"):t==="offline"?(e.classList.add("bg-error"),e.title="\u79BB\u7EBF"):(e.classList.add("bg-base-content/30"),e.title="\u672A\u8FDE\u63A5")}function Fn(e={}){let t=l.ws?.readyState;if(e.force){ut=400,Ht({quiet:!0});return}if(t===WebSocket.OPEN){if(e.probe&&$t&&Date.now()-$t>45e3)try{l.ws.close()}catch{}else if(e.probe&&l.ws.readyState===WebSocket.OPEN)try{l.ws.send(JSON.stringify({type:"ping"}))}catch{}return}t!==WebSocket.CONNECTING&&(ut=Math.min(ut,800),Ht({quiet:!0}))}function Lu(){Wn||(me.value=typeof navigator<"u"&&navigator.onLine===!1?"offline":"reconnecting",Ma(),Wn=setTimeout(()=>{Wn=null,Ht({quiet:!0})},ut),ut=Math.min(Math.round(ut*1.8),15e3))}function vl(){Ca&&(clearInterval(Ca),Ca=null)}function Eu(e,t){vl(),Ca=setInterval(()=>{if(!(t!==Ls||e.readyState!==WebSocket.OPEN)){if($t&&Date.now()-$t>7e4){try{e.close()}catch{}return}if(!(typeof document<"u"&&document.visibilityState==="hidden")&&$t&&Date.now()-$t>4e4)try{e.send(JSON.stringify({type:"ping"}))}catch{}}},3e4)}function pn(){let e=N.peek()||!!E.peek()&&me.peek()==="open";Sa(e)}function _a(){return(l.role||"editor")==="viewer"?"\u53EA\u8BFB\u8D26\u53F7\uFF0C\u65E0\u6CD5\u8F93\u5165":l.lock?.foreign?`\u4F1A\u8BDD\u7531 ${l.lock.holder&&l.lock.holder!=="viewer"?l.lock.holder:"\u5176\u4ED6\u7528\u6237"} \u5360\u7528\uFF08\u9501\uFF09`:"\u5F53\u524D\u65E0\u6CD5\u8F93\u5165"}function zn(){let e=on();l.externalSessionReadOnly=!e;let t=i("chat-input"),n=i("send-btn"),s=i("btn-attach"),a=i("session-lock-banner");if(t&&(t.disabled=!e,t.readOnly=!e,e?N.peek()?t.placeholder="\u56DE\u590D\u4E2D\u2026 \u53EF\u5148\u5199\u597D\u4E0B\u4E00\u6761\uFF0C\u7ED3\u675F\u540E\u81EA\u52A8\u53D1\u9001 \xB7 \u6216\u70B9 \u25A0 \u505C\u6B62":Ts(t.value||""):t.placeholder=_a()),n&&(n.disabled=!e),s&&(s.disabled=!e),a)if(!e)a.classList.remove("hidden"),a.textContent=_a();else{let o=l.nativeRunNotice?.sessionId===l.sessionId?l.nativeRunNotice.message:"";a.classList.toggle("hidden",!o),a.textContent=o}}function Ra(e){zn()}function Ht(e={}){Su(),Wn&&(clearTimeout(Wn),Wn=null),e.quiet&&(br=!0);let t=l.machineId||(typeof localStorage<"u"?localStorage.getItem("machineId"):null);pl!==t&&(ma(),pl=t);let n=++Ls;try{l.ws?.close()}catch{}me.value="connecting",Ma();let s=location.protocol==="https:"?"wss":"ws",a=new URLSearchParams;l.token&&a.set("token",l.token),t&&a.set("machine",t),l.sessionId&&a.set("sessionId",l.sessionId),l.agent&&a.set("agent",l.agent);let o=ku();o&&a.set("lastSeq",String(o));let r=new WebSocket(`${s}://${location.host}/ws/chat?${a}`);l.ws=r,r.addEventListener("open",()=>{if(n===Ls){if(ut=1e3,$t=Date.now(),me.value="open",Ma(),l.sessionId)try{r.send(JSON.stringify({type:"subscribe",sessionId:l.sessionId,agent:l.agent}))}catch{}fa(),wu(),Eu(r,n),pn(),gr&&!br&&C(t?`\u5DF2\u91CD\u8FDE \xB7 ${t}`:"\u5DF2\u91CD\u8FDE"),gr=!1,br=!1}}),r.addEventListener("message",c=>{if(n!==Ls)return;let u;try{u=JSON.parse(c.data)}catch{return}if($u(u)){if(u.type==="pong"){$t=Date.now();return}if(u.type==="ping"){if($t=Date.now(),r.readyState===WebSocket.OPEN)try{r.send(JSON.stringify({type:"pong"}))}catch{}return}if(u.type==="run-status"){if(u._hubReplay||u.sessionId&&u.sessionId!==l.sessionId)return;if(typeof u.running!="boolean"){l.nativeRunNotice={sessionId:l.sessionId,message:u.message||"\u7EC8\u7AEF\u4F1A\u8BDD\u672A\u786E\u8BA4\u7ED3\u675F"},zn();return}l.nativeRunNotice=null,zn(),u.running?N.value=!0:(N.peek()&&(N.value=!1),yr()),pn();return}yl(u)}}),r.addEventListener("close",()=>{n===Ls&&(vl(),gr=!0,me.value=typeof navigator<"u"&&navigator.onLine===!1?"offline":"reconnecting",Ma(),Lu())}),r.addEventListener("error",()=>{})}function yr(){if(!Fe.length||N.peek())return;let e=St(),t=Fe.findIndex(a=>a.key===e);if(t<0)return;let[n]=Fe.splice(t,1);qa();let s=i("chat-input");s&&(s.value=n.text,Cs(s)),setTimeout(()=>{if(n.key!==St()||N.peek()){un.set(n.key,n.text);return}Ms()},0)}function Es(){N.value=!1,pn(),yr()}function kr(){return xl}function yl(e){if(!(e?.sessionId&&l.sessionId&&e.sessionId!==l.sessionId)){if(e&&typeof e.type=="string"&&(e.type==="note.added"||e.type==="note.updated"||e.type==="note.removed"||e.type==="queue.item.added"||e.type==="queue.item.updated"||e.type==="queue.item.removed"||e.type==="queue.item.moved"||e.type==="queue.item.sending")){window.dispatchEvent(new CustomEvent("hub-ws-message",{detail:e}));let t={"note.added":"hub:note-added","note.updated":"hub:note-updated","note.removed":"hub:note-removed"}[e.type];t&&window.dispatchEvent(new CustomEvent(t,{detail:e}))}if(e._hubReplay===!0){document.dispatchEvent(new CustomEvent("external-session-updated",{detail:e}));return}if(e.type==="batch"&&Array.isArray(e.items)){for(let t of e.items)yl(t);return}if(["assistant","assistant_stream_start","assistant_delta","thought_delta","tool_use"].includes(e.type)&&xl++,e.type==="session-created"){let t=_.peek();l.sessionId=e.sessionId,e.agent&&e.agent!==$.peek()&&Ne(e.agent),se(t,e.agent||$.peek(),e.sessionId),document.dispatchEvent(new CustomEvent("sessions-changed"));return}if(e.type==="external-sessions-changed"){document.dispatchEvent(new CustomEvent("sessions-changed"));return}if(e.type==="external-session-updated"){document.dispatchEvent(new CustomEvent("sessions-changed")),document.dispatchEvent(new CustomEvent("external-session-updated",{detail:e}));return}if(e.type==="notification"&&e.notification){Ea(e.notification);return}if(e.type==="grok-queue-status"){Ru(e);return}if(e.type==="result"){Is(),Ss(),pt();let t=e.usage;if(t){let n={input_tokens:t.inputTokens??t.input_tokens,output_tokens:t.outputTokens??t.output_tokens,cache_read_input_tokens:t.cacheReadInputTokens??t.cache_read_input_tokens,cache_creation_input_tokens:t.cacheCreationInputTokens??t.cache_creation_input_tokens,total_tokens:t.totalTokens??t.total_tokens,reasoning_tokens:t.reasoningTokens??t.reasoning_tokens,costUSD:t.costUSD??t.cost_usd};l.lastUsage=n,l.sessionId&&(l.lastUsageSessionId=l.sessionId),Gn(n)}e.is_error||C("\u2713 Done"),Es();return}if(e.type==="complete"){Is(),Ss(),pt(),!e.aborted&&e.agent==="claude"?C("\u2713 Done"):!e.aborted&&e.agent&&e.agent!=="claude"&&!e.error||(!e.aborted&&!e.agent?C("\u2713 Done"):e.aborted&&C("\u5DF2\u505C\u6B62")),Es();return}if(e.type==="error"){Is(),Ss(),(e.code===423||/locked/i.test(String(e.message||"")))&&(l.lock={...l.lock||{},held:!1,foreign:!0,holder:e.lock?.holder||l.lock?.holder||"another user"},zn()),qt("error","Error",xu(e.message)),Es();return}if(e.type==="shell-start"){l.shellBubble=null;return}if(e.type==="shell-output"){l.shellBubble||(l.shellBubble=Ou(e.stream==="stderr"?"shell-err":"shell")),Uu(l.shellBubble,e.data);return}if(e.type==="shell-exit"){l.shellBubble=null,C(e.code===0?"\u2713 Exit 0":`\u2717 Exit ${e.code}${e.error?": "+e.error:""}`),Es();return}if(e.type==="assistant"){Ss();for(let t of e.message?.content||[])t.type==="text"&&t.text?(pt(),qt("assistant",vu(),t.text,{ts:e.ts||Date.now()})):t.type==="tool_use"&&Er(t,{ts:e.ts||Date.now()});return}if(e.type==="assistant_stream_start"){N.peek()||(N.value=!0,pn()),wl(e.ts);return}if(e.type==="assistant_delta"){N.peek()||(N.value=!0,pn()),Iu(e.data||"");return}if(e.type==="assistant_stream_end"){Ss();return}if(e.type==="thought_stream_start"){kl();return}if(e.type==="thought_delta"){Tu(e.data||"");return}if(e.type==="thought_stream_end"){Is();return}if(e.type==="status"){let t=i("stream-status");if(t)t.textContent=e.message||"";else{let n=i("messages");n&&e.message&&(n.insertAdjacentHTML("beforeend",`<div id="stream-status" class="text-center text-[10px] text-base-content/35 py-0.5">${p(e.message)}</div>`),He(n))}return}if(e.type==="permission_resolved"){let t=e.requestId||e.request_id;t&&i(`perm-${t}`)?.remove();return}(e.type==="permission_request"||e.request_id&&e.tool_name)&&Gu(e)}}function wl(e){let t=i("messages");if(!t||(pt(),Is(),Xe&&t.contains(Xe)))return;let n=Na(e||Date.now()),s=Pa(e||Date.now());t.insertAdjacentHTML("beforeend",`
|
|
34
34
|
<div class="msg-row assistant px-2 live-stream" data-ts="${p(s)}">
|
|
35
35
|
<div class="max-w-[88%] rounded-2xl rounded-tl-sm px-3 py-2 text-sm bg-base-200 break-words md">
|
|
36
36
|
<div class="msg-stream-body whitespace-pre-wrap"></div>
|
|
37
37
|
</div>
|
|
38
38
|
${n?`<div class="msg-ts" title="${p(s)}">${p(n)}</div>`:""}
|
|
39
|
-
</div>`),Xe=t.lastElementChild,Ue=Xe.querySelector(".msg-stream-body"),i("stream-status")?.remove(),He(t)}function
|
|
39
|
+
</div>`),Xe=t.lastElementChild,Ue=Xe.querySelector(".msg-stream-body"),i("stream-status")?.remove(),He(t)}function Iu(e){e&&(Ue||wl(Date.now()),Ue&&(Ue.textContent+=e,He(i("messages"))))}function Ss(){if(!Xe||!Ue){Xe=null,Ue=null;return}let e=Ue.textContent||"";e.trim()?(Ue.classList.remove("whitespace-pre-wrap"),Ue.classList.add("md"),Ue.innerHTML=Da(e),Cl(Xe),Il(Xe,e)):Xe.remove(),Xe=null,Ue=null,i("stream-status")?.remove()}function kl(){let e=i("messages");e&&(Pt&&e.contains(Pt)||(e.insertAdjacentHTML("beforeend",`
|
|
40
40
|
<div class="msg-row assistant px-2 thought-stream">
|
|
41
41
|
<div class="max-w-[88%] rounded-lg border border-base-300/60 bg-base-200/50 px-2.5 py-1.5 text-[11px] text-base-content/45">
|
|
42
42
|
<div class="font-medium text-base-content/35 mb-0.5">thinking\u2026</div>
|
|
43
43
|
<div class="thought-body font-mono whitespace-pre-wrap max-h-24 overflow-y-auto opacity-80"></div>
|
|
44
44
|
</div>
|
|
45
|
-
</div>`),Pt=e.lastElementChild,dt=Pt.querySelector(".thought-body"),He(e)))}function
|
|
46
|
-
<div class="text-[10px] text-base-content/30 px-1 select-none">\u{1F4AD} thought ${e?`(${e} chars)`:""}</div>`}Pt=null,dt=null}function
|
|
47
|
-
Available: ${u}`:""}`),!0}let a=
|
|
45
|
+
</div>`),Pt=e.lastElementChild,dt=Pt.querySelector(".thought-body"),He(e)))}function Tu(e){e&&(dt||kl(),dt&&(dt.textContent+=e,dt.scrollTop=dt.scrollHeight,He(i("messages"))))}function Is(){if(Pt&&dt){let e=(dt.textContent||"").length;Pt.innerHTML=`
|
|
46
|
+
<div class="text-[10px] text-base-content/30 px-1 select-none">\u{1F4AD} thought ${e?`(${e} chars)`:""}</div>`}Pt=null,dt=null}function Mu(e){let[t,...n]=e.slice(1).trim().split(/\s+/),s=n.join(" ");switch(t.toLowerCase()){case"agent":{if(!s)return C(`Current agent: ${$.peek()} \xB7 agents: claude | codex | grok | gemini | cursor`),!0;let a=s.toLowerCase();return["claude","codex","grok","gemini","cursor"].includes(a)?(a!==$.peek()?(l.sessionId=null,Ne(a),se(Oe(a)),document.dispatchEvent(new CustomEvent("agent-changed")),C(`Agent \u2192 ${Z[a]} \xB7 model ${_.peek()} \xB7 new session`)):C(`Agent already ${Z[a]}`),!0):(C(`Unknown agent "${s}" \xB7 valid: claude | codex | grok | gemini | cursor`),!0)}case"model":{if(!s){let c=$.peek(),u=Be(c).map(d=>d.value).join(" | ");return C(`Current model: ${_.peek()} (${c})${u?`
|
|
47
|
+
Available: ${u}`:""}`),!0}let a=Cu[s.toLowerCase()]||s,o=$.peek()||"claude",r=Be(o).some(c=>c.value===a);return r||Xt(o,a),se(a),C(`Model set to ${a}${r?"":" (saved as custom \u2605)"}`),document.dispatchEvent(new CustomEvent("agent-changed")),!0}case"effort":{let a=Zt($.peek(),_.peek());return s?a.includes(s.toLowerCase())?(te.value=s.toLowerCase(),C(`Effort set to ${s.toLowerCase()}`),!0):(C(`Unknown effort level "${s}" \xB7 valid: ${a.join(" | ")}`),!0):(C(`Current effort: ${te.peek()||"(default)"} \xB7 levels: ${a.join(" | ")}`),!0)}case"clear":return Xn(),l.sessionId=null,l.lastUsage=null,C("Cleared \xB7 new session"),!0;case"usage":return Au(),!0;case"help":return C(`Available slash commands:
|
|
48
48
|
/agent [claude|codex|grok|gemini|cursor]
|
|
49
49
|
/model [haiku|sonnet|opus|<model-id>]
|
|
50
50
|
/effort [low|medium|high|xhigh|max]
|
|
51
51
|
/usage
|
|
52
52
|
/clear
|
|
53
|
-
/help`),!0;default:return!1}}function Ie(e){if(e==null||Number.isNaN(Number(e)))return"\u2014";let t=Number(e);return t>=1e6?`${(t/1e6).toFixed(2)}M`:t>=1e3?`${(t/1e3).toFixed(1)}k`:String(Math.round(t))}async function
|
|
54
|
-
`))
|
|
55
|
-
`)),(r.tokensUsed!=null||r.windowTokens!=null)&&
|
|
53
|
+
/help`),!0;default:return!1}}function Ie(e){if(e==null||Number.isNaN(Number(e)))return"\u2014";let t=Number(e);return t>=1e6?`${(t/1e6).toFixed(2)}M`:t>=1e3?`${(t/1e3).toFixed(1)}k`:String(Math.round(t))}async function Au(){let e=$.peek()||"claude",t=_.peek()||"\u2014",n=l.sessionId,s=[`Agent: ${Z[e]||e}`,`Model: ${t}`,`Session: ${n?n.slice(0,8)+"\u2026":"(new \u2014 send a message first)"}`];if(l.lastUsage&&(!n||l.lastUsageSessionId===n)){let a=l.lastUsage;s.push(`Last turn: \u2191${Ie(a.input_tokens)} \u2193${Ie(a.output_tokens)}`+(a.cache_read_input_tokens?` \xB7 ${Ie(a.cache_read_input_tokens)} cached`:"")+(a.reasoning_tokens?` \xB7 ${Ie(a.reasoning_tokens)} reason`:"")+(a.total_tokens?` \xB7 \u03A3${Ie(a.total_tokens)}`:"")+(a.costUSD!=null?` \xB7 $${Number(a.costUSD).toFixed(4)}`:""))}if(!n){C(s.join(`
|
|
54
|
+
`)),$r("\u25C8 /usage \xB7 no session yet");return}C("Loading usage\u2026");try{let a=new URLSearchParams({sessionId:n,agent:e}),r=(await x("GET",`/api/usage?${a}`)).context||{};if(r.model&&(s[1]=`Model: ${r.model}`),r.title&&s.push(`Title: ${r.title}`),r.tokensUsed!=null||r.windowTokens!=null||r.usagePercent!=null){let u=r.tokensUsed!=null?Ie(r.tokensUsed):"\u2014",d=r.windowTokens!=null?Ie(r.windowTokens):"\u2014",f=r.usagePercent!=null?`${r.usagePercent}%`:"\u2014";s.push(`Context window: ${u} / ${d} (${f})`)}if(r.turnCount!=null&&s.push(`Turns: ${r.turnCount}`),r.toolCallCount!=null&&s.push(`Tools: ${r.toolCallCount}`),r.sessionDurationSeconds!=null){let u=Math.floor(r.sessionDurationSeconds/60),d=Math.round(r.sessionDurationSeconds%60);s.push(`Duration: ${u}m ${d}s`)}if(r.sessionTotals){let u=r.sessionTotals;s.push(`Session totals: \u2191${Ie(u.input_tokens)} \u2193${Ie(u.output_tokens)}`+(u.cache_read_input_tokens?` \xB7 ${Ie(u.cache_read_input_tokens)} cached`:"")+(u.total_tokens?` \xB7 \u03A3${Ie(u.total_tokens)}`:"")+(u.costUSD?` \xB7 $${Number(u.costUSD).toFixed(4)}`:""))}if(r.lastTurn&&!l.lastUsage){let u=r.lastTurn;s.push(`Last completed turn: \u2191${Ie(u.input_tokens)} \u2193${Ie(u.output_tokens)}`+(u.cache_read_input_tokens?` \xB7 ${Ie(u.cache_read_input_tokens)} cached`:"")+(u.costUSD!=null?` \xB7 $${Number(u.costUSD).toFixed(4)}`:""))}r.note&&s.push(r.note);let c=i("messages");if(c){let u=[...c.children];for(let d=u.length-1;d>=0;d--)if(u[d].textContent==="Loading usage\u2026"){u[d].remove();break}}C(s.join(`
|
|
55
|
+
`)),(r.tokensUsed!=null||r.windowTokens!=null)&&Sr({tokensUsed:r.tokensUsed,windowTokens:r.windowTokens,usagePercent:r.usagePercent,model:r.model||t,turnCount:r.turnCount,toolCallCount:r.toolCallCount}),r.sessionTotals?Gn(r.sessionTotals):r.lastTurn?Gn(r.lastTurn):l.lastUsage&&Gn(l.lastUsage)}catch(a){let o=i("messages");if(o){let r=[...o.children];for(let c=r.length-1;c>=0;c--)if(r[c].textContent==="Loading usage\u2026"){r[c].remove();break}}C(`${s.join(`
|
|
56
56
|
`)}
|
|
57
|
-
(usage fetch failed: ${a.message})`)}}function
|
|
57
|
+
(usage fetch failed: ${a.message})`)}}function Ms(){let e=i("chat-input"),t=e?.value.trim();if(!t||!E.peek())return;if(!on()){C(_a()),wt().then(()=>zn()).catch(()=>{});return}if(l.sessionId&&!l.lock?.held&&!l.lock?.unmanaged){wt().then(s=>{if(!s?.ok&&!s?.skipped){zn(),C(_a());return}Ms()}).catch(()=>Ms());return}if(N.peek()){if($.peek()==="grok"&&l.sessionId){let s="grok",a=te.peek()||Qe(s,_.peek())||"low",o=lt({type:"command",cmd:"turn.start",agent:s,command:t,sessionId:l.sessionId,lockToken:l.lock?.token||void 0,options:{agent:s,cwd:E.peek().path,sessionId:l.sessionId,configDir:l.configDir,model:_.peek(),lockToken:l.lock?.token||void 0,effort:a,...ue.peek()&&{permissionMode:ue.peek()},...ue.peek()==="bypassPermissions"&&{allowDangerouslySkipPermissions:!0}}});El(t),e.value="",Cs(e),Ts(""),Aa(),C(o?"\u5DF2\u52A0\u5165 Grok \u670D\u52A1\u7AEF\u961F\u5217\uFF0C\u5237\u65B0\u9875\u9762\u4ECD\u4F1A\u663E\u793A":"\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u6D88\u606F\u5C06\u5728\u91CD\u8FDE\u540E\u53D1\u9001");return}Fe.push({key:St(),text:t}),qa(),e.value="",Cs(e),Ts(""),Aa(),C(`\u5DF2\u6392\u961F\u4E0B\u4E00\u6761\uFF0C\u5F53\u524D\u56DE\u590D\u7ED3\u675F\u540E\u53D1\u9001\uFF1A${t.length>80?t.slice(0,80)+"\u2026":t}`);return}if(e.value="",un.delete(St()),Cs(e),Ts(""),Aa(),t.startsWith("/")&&Mu(t))return;N.value=!0,pn();let n=Date.now();if(Sl(t))qt("shell","$ Shell",t.slice(1).trim(),{ts:n}),lt({type:"command",cmd:"shell.exec",command:t.slice(1).trim(),cwd:E.peek().path})||C("\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u547D\u4EE4\u5DF2\u5165\u961F\uFF0C\u91CD\u8FDE\u540E\u53D1\u9001");else{pt(),qt("user","You",t,{ts:n,forceStick:!0});let s=$.peek()||"claude",a=te.peek()||Qe(s,_.peek())||(s==="grok"?"low":""),o=ue.peek();l.sessionId&&se(_.peek(),s,l.sessionId),lt({type:"command",cmd:"turn.start",agent:s,command:t,sessionId:l.sessionId,lockToken:l.lock?.token||void 0,options:{agent:s,cwd:E.peek().path,sessionId:l.sessionId,configDir:l.configDir,model:_.peek(),lockToken:l.lock?.token||void 0,...a&&{effort:a},...o&&{permissionMode:o},...o==="bypassPermissions"&&{allowDangerouslySkipPermissions:!0}}})||C("\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u6D88\u606F\u5DF2\u5165\u961F\uFF0C\u91CD\u8FDE\u540E\u53D1\u9001")}}function $l(){l.sessionId&<({type:"command",cmd:"turn.interrupt",sessionId:l.sessionId}),Fe=Fe.filter(e=>e.key!==St()),qa(),Bu(),Es()}function Ts(e){let t=Sl(e),n=i("chat-input"),s=i("send-btn");if(!n||!s)return;n.classList.toggle("textarea-warning",t),n.style.fontFamily=t?"monospace":"",s.classList.toggle("btn-warning",t),s.classList.toggle("btn-primary",!t),s.textContent=t?"Run":"Send";let a=Z[$.peek()]||"agent",o=typeof window<"u"&&window.matchMedia("(max-width: 640px)").matches;t?n.placeholder=o?"Shell \u547D\u4EE4\u2026":"Shell command (without !)\u2026":n.placeholder=o?`\u95EE ${a}\u2026`:`Ask ${a}\u2026 or !cmd for shell`}function Sl(e){let t=String(e||"").trimStart();return t.startsWith("!")&&!/^!\[[^\]]*\]\([^)]+\)/.test(t)}function Du(){return typeof window<"u"&&window.matchMedia("(max-width: 640px)").matches,72}function Cs(e){e.style.height="auto",e.style.height=Math.min(e.scrollHeight,Du())+"px"}function Na(e){let t=O(e);if(t==null)return"";let n=new Date(t);if(Number.isNaN(n.getTime()))return"";let s=new Date,a=n.toDateString()===s.toDateString(),o=n.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1});return a?o:`${n.toLocaleDateString(void 0,{month:"numeric",day:"numeric"})} ${o}`}function Pa(e){let t=O(e);return t==null?"":new Date(t).toISOString()}function Nu(e,t,n){if(e==="system")return t;let s=Na(n),a=Pa(n),o=s?`<div class="msg-ts" title="${p(a)}">${p(s)}</div>`:"";return`<div class="msg-row ${e==="user"?"user":e==="shell"||e==="shell-err"?"assistant":e} px-2" data-ts="${p(a)}">${t}${o}</div>`}function Pu(e,t,n){let s='<button class="msg-expand-btn text-[10px] text-primary/70 mt-1.5 block cursor-pointer hover:text-primary">\u25BC Show more</button>',a;switch(e){case"user":{let r=/!\[.*?\]\(.*?\)/.test(t)?Da(t):null,c=t.length>ju,u=c?`<div class="msg-body">${r??p(t.trimEnd())}</div>${s}`:r??p(t.trimEnd());a=`<div class="max-w-[80%] rounded-2xl rounded-tr-sm px-3 py-2 text-sm bg-primary/15 border border-primary/20 text-base-content break-words${c?" msg-card":""}${r?" md":""}"${r?"":' style="white-space:pre-wrap"'}>${u}</div>`;break}case"assistant":{let o=t.length>_u,r=o?`<div class="msg-body">${Da(t)}</div>${s}`:Da(t);a=`<div class="msg-assistant-content max-w-[min(92%,52rem)] rounded-2xl rounded-tl-sm px-3.5 py-2.5 text-sm bg-base-200 border border-base-300/40 break-words md leading-relaxed${o?" msg-card":""}">${r}</div>`;break}case"error":a=`<div class="max-w-[88%] rounded-2xl rounded-tl-sm px-3 py-2 text-sm bg-error/10 border border-error/20 text-error break-words" style="white-space:pre-wrap">${p(t)}</div>`;break;case"shell":case"shell-err":a=`<div class="w-full max-w-[96%] rounded-lg code-surface px-3 py-2 text-sm font-mono ${e==="shell-err"?"text-error":""} break-words" style="white-space:pre-wrap">${p(t)}</div>`;break;case"system":return`<div class="text-center text-[11px] text-base-content/30 py-0.5 select-none">${p(t)}</div>`;default:a=`<div class="rounded-lg px-3 py-2 text-sm bg-base-300 break-words" style="white-space:pre-wrap">${p(t)}</div>`}return Nu(e,a,n)}function qt(e,t,n,s={}){let a=i("messages");if(!a)return;let o=O(s.ts)??(e==="system"?null:Date.now());a.insertAdjacentHTML("beforeend",Pu(e,n,o)),Cl(a.lastElementChild),e==="assistant"&&Il(a.lastElementChild,n,s),He(a,!!s.forceStick)}function C(e){qt("system","",e)}function Aa(){for(let e of Ha)if(e.previewUrl)try{URL.revokeObjectURL(e.previewUrl)}catch{}Ha.length=0,Hu()}function Yn(){Aa()}function Hu(){let e=i("chat-attach-bar");if(e){if(!Ha.length){e.classList.add("hidden"),e.innerHTML="";return}e.classList.remove("hidden"),e.innerHTML=Ha.map((t,n)=>`
|
|
58
58
|
<div class="chat-thumb relative" title="${p(t.ref||t.path)}">
|
|
59
59
|
${t.previewUrl?`<img src="${t.previewUrl}" alt="${p(t.label||"img")}">`:`<span class="chat-thumb-path">${p(t.label||t.name||"file")}</span>`}
|
|
60
60
|
<span class="chat-thumb-label">${p(t.label||t.kind||"")}</span>
|
|
61
61
|
<button type="button" class="chat-thumb-x" data-rm-attach="${n}" aria-label="remove">\u2715</button>
|
|
62
|
-
</div>`).join("")}}function kt(e){return e>=1e3?`${(e/1e3).toFixed(1)}k`:String(e)}function
|
|
62
|
+
</div>`).join("")}}function kt(e){return e>=1e3?`${(e/1e3).toFixed(1)}k`:String(e)}function $r(e){let t=i("messages");t&&(t.insertAdjacentHTML("beforeend",`<div class="token-bar select-none">
|
|
63
63
|
<span class="token-bar-mark">\u25C8</span><span class="token-bar-text">${p(e)}</span>
|
|
64
|
-
</div>`),He(t))}function
|
|
65
|
-
${String(e||"")}`}function
|
|
64
|
+
</div>`),He(t))}function Gn(e){if(!e)return;let t=e.input_tokens??e.inputTokens??0,n=e.output_tokens??e.outputTokens??0,s=e.total_tokens??e.totalTokens??t+n,a=e.cache_read_input_tokens??e.cachedReadTokens?` \xB7 ${kt(e.cache_read_input_tokens??e.cachedReadTokens)} cached`:"",o=e.cache_creation_input_tokens??e.cacheCreationInputTokens?` \xB7 ${kt(e.cache_creation_input_tokens??e.cacheCreationInputTokens)} cache-write`:"",r=e.reasoning_tokens??e.reasoningTokens?` \xB7 ${kt(e.reasoning_tokens??e.reasoningTokens)} reason`:"",c=e.costUSD??e.cost_usd,u=c!=null?` \xB7 $${Number(c).toFixed(4)}`:"",d=s?` \xB7 \u03A3${kt(s)}`:"";$r(`\u2191${kt(t)} \u2193${kt(n)}${a}${o}${r}${d}${u}`)}function Sr(e){if(!e)return;let t=e.tokensUsed??e.contextTokensUsed,n=e.windowTokens??e.contextWindowTokens,s=e.usagePercent??e.contextWindowUsage;if(t==null&&n==null&&s==null)return;let a=[];t!=null&&n!=null?a.push(`context ${kt(t)} / ${kt(n)}`):t!=null&&a.push(`context ${kt(t)}`),s!=null&&a.push(`${s}%`),e.model&&a.push(e.model),e.turnCount!=null&&a.push(`${e.turnCount} turns`),e.toolCallCount!=null&&a.push(`${e.toolCallCount} tools`),$r(`\u25A3 ${a.join(" \xB7 ")}`)}function Ll(){let e=i("messages");e&&(e.dataset.historyPainting="1",e.innerHTML="",Ye=null,wr.clear())}function Lr(e=null){let t=i("messages");t&&(delete t.dataset.historyPainting,e==null?He(t,!0):(t.scrollTop=Math.max(0,e),gl(t).setFollowing($s(t))))}function Xn(){let e=i("messages"),t=i("permission-requests");e&&(e.innerHTML="",delete e.dataset.historyPainting),t&&(t.innerHTML=""),l.shellBubble=null,Ye=null,Xe=Ue=null,Pt=dt=null,wr.clear(),ja.clear()}function qu(e,t=l.sessionId){return`${t||""}
|
|
65
|
+
${String(e||"")}`}function El(e,t=l.sessionId){let n=qu(e,t);!e||ja.has(n)||(ja.add(n),qt("user","You",e,{ts:Date.now(),forceStick:!0}),i("messages")?.lastElementChild?.classList.add("queued-user-msg"))}function Ru(e){if((e.sessionId||l.sessionId)!==l.sessionId)return;let t=Array.isArray(e.items)?e.items.filter(n=>typeof n=="string"&&n.trim()):[];for(let n of t)El(n,e.sessionId||l.sessionId);t.length&&C(`\u231B Grok queue \xB7 ${t.length} prompt${t.length===1?"":"s"} waiting`)}function Bu(){let e=i("messages");e&&(e.querySelectorAll(".queued-user-msg").forEach(t=>{t.classList.remove("queued-user-msg"),t.classList.add("cancelled-queued-user-msg")}),ja.clear())}function Il(e,t,n={}){if(!e||!t||e.querySelector(".msg-actions"))return;let s=`a${++yu}`;wr.set(s,{text:t,historyIndex:Number.isInteger(n.historyIndex)?n.historyIndex:null,sessionId:l.sessionId,agent:l.agent||$.peek()||"claude",machineId:l.machineId||null});let a=!["gemini","cursor"].includes(l.agent||$.peek()||"claude"),o=document.createElement("div");o.className="msg-actions",o.innerHTML=`
|
|
66
66
|
<button type="button" class="msg-action-btn" data-copy-message="${p(s)}" title="Copy answer">Copy</button>
|
|
67
|
-
${a?`<button type="button" class="msg-action-btn" data-fork-message="${p(s)}" title="Start a branch from this answer">Fork</button>`:""}`;let r=e.querySelector(".msg-ts");e.insertBefore(o,r||null)}function
|
|
67
|
+
${a?`<button type="button" class="msg-action-btn" data-fork-message="${p(s)}" title="Start a branch from this answer">Fork</button>`:""}`;let r=e.querySelector(".msg-ts");e.insertBefore(o,r||null)}function Ou(e){let t=i("messages");if(!t)return null;let n=e==="shell-err"?" text-error":"";return t.insertAdjacentHTML("beforeend",`<div class="mx-2 rounded-lg code-surface px-3 py-2 text-sm font-mono${n} whitespace-pre-wrap break-words"></div>`),He(t),t.lastElementChild}function Uu(e,t){e&&(e.textContent+=t,He(e.closest("#messages")))}function Fu(e){let t=typeof e.input=="object"?JSON.stringify(e.input,null,2):String(e.input||""),s=((typeof e.input=="object"?Object.values(e.input).find(a=>typeof a=="string"&&a.trim()):t)||"").replace(/\n/g," ").slice(0,_e.peek()==="full"?120:80);return{inputStr:t,preview:s}}function ml(e,{inBatch:t=!1}={}){let{inputStr:n,preview:s}=Fu(e);return`<div class="tool-card${t?" tool-batch-item":""} cursor-pointer select-none px-2 py-1">
|
|
68
68
|
<div class="flex items-center gap-1.5 text-xs font-mono">
|
|
69
69
|
<span class="text-warning">\u26A1</span>
|
|
70
70
|
<span class="text-warning font-semibold">${p(e.name||"tool")}</span>
|
|
@@ -72,21 +72,21 @@ ${String(e||"")}`}function vl(e,t=l.sessionId){let n=Cu(e,t);!e||Ta.has(n)||(Ta.
|
|
|
72
72
|
<span class="tool-chevron text-[10px] text-base-content/40">\u25B6</span>
|
|
73
73
|
</div>
|
|
74
74
|
<div class="tool-detail">${p(n)}</div>
|
|
75
|
-
</div>`}function
|
|
75
|
+
</div>`}function Wu(e){let t=[...new Set(e.names)],n=t.slice(0,4).join(", ")+(t.length>4?"\u2026":""),s=e.el.querySelector(".tool-batch-summary");s&&(s.innerHTML=`<span class="text-warning">\u26A1</span>
|
|
76
76
|
<span class="font-semibold text-base-content/70">${e.count} tool${e.count===1?"":"s"}</span>
|
|
77
77
|
<span class="text-base-content/40 truncate flex-1">${p(n)}</span>
|
|
78
|
-
<span class="tool-chevron text-[10px] text-base-content/40">\u25B6</span>`)}function pt(){Ye=null}function
|
|
79
|
-
<div class="msg-row assistant px-2" data-ts="${p(
|
|
78
|
+
<span class="tool-chevron text-[10px] text-base-content/40">\u25B6</span>`)}function pt(){Ye=null}function Er(e,t={}){let n=i("messages");if(!n)return;let s=_e.peek()||"normal",a=O(t.ts);if(s==="clean"){if(!Ye||!n.contains(Ye.el)){let u=Na(a),d=Pa(a);n.insertAdjacentHTML("beforeend",`
|
|
79
|
+
<div class="msg-row assistant px-2" data-ts="${p(d)}">
|
|
80
80
|
<div class="tool-batch w-full max-w-[96%] px-2 py-1.5">
|
|
81
81
|
<div class="tool-batch-summary flex items-center gap-1.5 text-xs font-mono"></div>
|
|
82
82
|
<div class="tool-batch-list"></div>
|
|
83
83
|
</div>
|
|
84
|
-
${u?`<div class="msg-ts" title="${p(
|
|
85
|
-
</div>`),Ye={el:n.lastElementChild.querySelector(".tool-batch"),names:[],count:0}}Ye.names.push(e.name||"tool"),Ye.count++,Ye.el.querySelector(".tool-batch-list")?.insertAdjacentHTML("beforeend",
|
|
84
|
+
${u?`<div class="msg-ts" title="${p(d)}">${p(u)}</div>`:""}
|
|
85
|
+
</div>`),Ye={el:n.lastElementChild.querySelector(".tool-batch"),names:[],count:0}}Ye.names.push(e.name||"tool"),Ye.count++,Ye.el.querySelector(".tool-batch-list")?.insertAdjacentHTML("beforeend",ml(e,{inBatch:!0})),Wu(Ye),He(n);return}Ye=null;let o=Na(a),r=Pa(a);n.insertAdjacentHTML("beforeend",`
|
|
86
86
|
<div class="msg-row assistant px-2" data-ts="${p(r)}">
|
|
87
|
-
<div class="w-full max-w-[96%]">${
|
|
87
|
+
<div class="w-full max-w-[96%]">${ml(e)}</div>
|
|
88
88
|
${o?`<div class="msg-ts" title="${p(r)}">${p(o)}</div>`:""}
|
|
89
|
-
</div>`),He(n)}function
|
|
89
|
+
</div>`),He(n)}function Tl(){let e=i("messages");e&&e.setAttribute("data-density",_e.peek()||"normal")}function Gu(e){let t=e.request_id||e.requestId;if(!t||i(`perm-${t}`))return;let n=e.tool_input?JSON.stringify(e.tool_input).slice(0,200):"";i("permission-requests")?.insertAdjacentHTML("beforeend",`
|
|
90
90
|
<div id="perm-${t}" class="perm-banner mx-3 mb-2 rounded-lg border border-warning/25 bg-warning/8 p-3">
|
|
91
91
|
<div class="text-xs text-warning font-semibold mb-1">\u26A0\uFE0F Permission Required</div>
|
|
92
92
|
<div class="font-mono text-xs text-base-content/60 break-all mb-2">
|
|
@@ -96,13 +96,13 @@ ${String(e||"")}`}function vl(e,t=l.sessionId){let n=Cu(e,t);!e||Ta.has(n)||(Ta.
|
|
|
96
96
|
<button class="btn btn-success btn-xs" data-perm-id="${t}" data-perm-allow="1">Allow</button>
|
|
97
97
|
<button class="btn btn-error btn-xs" data-perm-id="${t}" data-perm-allow="0">Deny</button>
|
|
98
98
|
</div>
|
|
99
|
-
</div>`),He(i("messages"))}function
|
|
99
|
+
</div>`),He(i("messages"))}function zu(){if(hl||typeof marked>"u")return;let e=s=>String(s??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),t=(s,a)=>{let o=String(a||"").trim().split(/\s+/)[0]||"",r=o||"text",c=o?`language-${p(o)}`:"";return`<div class="code-block">
|
|
100
100
|
<div class="code-block-header">
|
|
101
101
|
<span class="code-block-lang">${p(r)}</span>
|
|
102
102
|
<button type="button" class="code-copy" data-copy="1" title="Copy code">Copy</button>
|
|
103
103
|
</div>
|
|
104
|
-
<pre><code class="hljs ${
|
|
105
|
-
</div>`},n={code(s,a){return s&&typeof s=="object"&&s.text!=null?t(s.text,s.lang||a):t(s,a)},table(s,a){return s&&typeof s=="object"&&!Array.isArray(s)&&s.header?!1:`<div class="table-wrap"><table><thead>${s}</thead><tbody>${a}</tbody></table></div>`},html(s){return e(s)}};try{if(typeof marked.use=="function")marked.use({gfm:!0,breaks:!0,renderer:n});else if(typeof marked.setOptions=="function"){let s=new marked.Renderer;s.code=n.code,s.table=n.table,marked.setOptions({gfm:!0,breaks:!0,renderer:s})}}catch(s){console.warn("[md] marked setup failed",s)}
|
|
104
|
+
<pre><code class="hljs ${c}">${e(s)}</code></pre>
|
|
105
|
+
</div>`},n={code(s,a){return s&&typeof s=="object"&&s.text!=null?t(s.text,s.lang||a):t(s,a)},table(s,a){return s&&typeof s=="object"&&!Array.isArray(s)&&s.header?!1:`<div class="table-wrap"><table><thead>${s}</thead><tbody>${a}</tbody></table></div>`},html(s){return e(s)}};try{if(typeof marked.use=="function")marked.use({gfm:!0,breaks:!0,renderer:n});else if(typeof marked.setOptions=="function"){let s=new marked.Renderer;s.code=n.code,s.table=n.table,marked.setOptions({gfm:!0,breaks:!0,renderer:s})}}catch(s){console.warn("[md] marked setup failed",s)}hl=!0}function Da(e){if(typeof marked>"u")return p(e);try{return zu(),Ve(e,{fallback:()=>p(e)})}catch{return p(e)}}function Ku(e){!e||typeof hljs>"u"||(e.querySelectorAll("pre code:not(.hljs)").forEach(t=>{try{hljs.highlightElement(t)}catch{}}),e.querySelectorAll("pre code.hljs").forEach(t=>{t.classList.add("hljs")}))}function Cl(e){Ku(e),yt(e),xt(e)}var dn,Ls,Wn,ut,$t,Ca,ul,gr,pl,br,vr,wr,yu,ja,xr,Fe,fl,un,xl,Xe,Ue,Pt,dt,Cu,ju,_u,Ha,Ye,hl,Ba=B(()=>{G();lr();W();ce();ys();fr();Ia();qn();sn();an();hr();Nt();Nt();dn=null;Ls=0,Wn=null,ut=1e3,$t=0,Ca=null,ul=!1,gr=!1,pl=null,br=!1,vr="hubStreamCursors",wr=new Map,yu=0,ja=new Set,xr="pendingUserTexts",Fe=(()=>{try{let e=JSON.parse(sessionStorage.getItem(xr)||"[]");return Array.isArray(e)?e.filter(t=>t?.key&&t?.text).slice(-30):[]}catch{return[]}})(),fl=new Set,un=new Map;xl=0;Xe=null,Ue=null,Pt=null,dt=null;Cu={haiku:"claude-haiku-4-5",sonnet:"claude-sonnet-4-6",opus:"claude-opus-4-5",sonnet4:"claude-sonnet-4-6",haiku4:"claude-haiku-4-5"};ju=200,_u=500;Ha=[];Ye=null;hl=!1});function Al(e,t){Ml=e,Ir=t,window.addEventListener("hashchange",()=>{if(Tr){Tr=!1;return}jl(location.hash.slice(1)||"/")}),je(X,n=>{l.sessionId&&As()})}function Cr(e){let[t,n=""]=String(e||"").split("?",2),s=t.match(/^\/session\/([^/]+)(?:\/([^/]+))?$/);if(!s)return null;let a=new URLSearchParams(n);try{return{id:decodeURIComponent(s[1]),tab:s[2]?decodeURIComponent(s[2]):null,machineId:a.get("machine")||null,agent:a.get("agent")||null}}catch{return null}}function Dl(){jl(location.hash.slice(1)||"/")}function jl(e){let t=String(e||"").split("?")[0];if(t==="/settings"){document.dispatchEvent(new CustomEvent("router:settings"));return}if(t==="/notes"){document.dispatchEvent(new CustomEvent("router:notes"));return}let n=Cr(e);if(!n){document.dispatchEvent(new CustomEvent("router:home"));return}let{id:s,tab:a,machineId:o,agent:r}=n;!Ml||!Ir||(s!==l.sessionId?document.dispatchEvent(new CustomEvent("router:session",{detail:{id:s,tab:a,machineId:o,agent:r}})):a&&a!==X.peek()&&Ir(a))}function Mr(e){Tr=!0,location.hash=e}function As(){if(!l.sessionId)return;let e=new URLSearchParams;l.machineId&&e.set("machine",l.machineId),l.agent&&e.set("agent",l.agent);let t=e.size?`?${e}`:"";Mr(`/session/${encodeURIComponent(l.sessionId)}/${encodeURIComponent(X.peek())}${t}`)}function _l(){if(!l.sessionId)return null;let e=new URL(location.href),t=new URLSearchParams;l.machineId&&t.set("machine",l.machineId),l.agent&&t.set("agent",l.agent);let n=t.size?`?${t}`:"";return e.hash=`/session/${encodeURIComponent(l.sessionId)}/${encodeURIComponent(X.peek())}${n}`,e.toString()}var rh,Ml,Ir,Tr,Oa=B(()=>{G();W();rh=_i({"/":()=>{},"/session/*":()=>{},"/session/*/*":()=>{},"*":()=>{}}),Ml=null,Ir=null,Tr=!1});async function Fa(){try{return await ft.get("sessions")??null}catch{return null}}async function Nl(e){try{await ft.set("sessions",e,{ttl:Ju})}catch{}}async function Pl(){try{return await ft.get("workspaces")??null}catch{return null}}async function Ds(e){try{await ft.set("workspaces",e,{ttl:3600*1e3})}catch{}}async function Hl(e){try{return js(await ft.get(`transcript:${e}`))}catch{return null}}function ql(e,t){let n=js(t);return Ar=Ar.catch(()=>{}).then(async()=>{await ft.set(`transcript:${e}`,n,{ttl:1440*60*1e3});let s=`transcript:${e}`,a=await ft.get("transcript-index-v2"),o=[{key:s,at:Date.now()},...(a||[]).filter(c=>c.key!==s)].filter(c=>c.at>=Date.now()-1440*60*1e3).slice(0,24),r=new Set(o.map(c=>c.key));for(let c of await ft.keys())String(c).startsWith("transcript:")&&!r.has(c)&&await ft.delete(c);await ft.set("transcript-index-v2",o)}),Ar.catch(()=>{})}function Ua(e,t=1024*1024){if(typeof e=="string")return e.length*3+2;if(!e||typeof e!="object")return 16;let n=2;for(let[s,a]of Object.entries(e))if(n+=s.length*3+Ua(a,t-n)+4,n>t)break;return n}function js(e){if(!e?.msgs)return e??null;let t=e.msgs.length,n=Ua(e.context),s=n>64*1024?null:e.context;for(n=Ua(s);t>0&&e.msgs.length-t<80;){let a=Ua(e.msgs[t-1]);if(n+a>1024*1024)break;n+=a,t--}return{...e,context:s,msgs:e.msgs.slice(t),meta:{...e.meta,oldestIndex:(e.meta?.oldestIndex||0)+t,truncated:t>0||!!e.meta?.truncated}}}var ft,Ju,Ar,_s=B(()=>{G();ft=Ni("claude-ui"),Ju=300*1e3;Ar=Promise.resolve()});var Rr={};us(Rr,{closeNotes:()=>zl,initNotes:()=>qr,openNotes:()=>za});function za(){Kl();let e=document.getElementById("notes-page");if(!e)return;e.hidden=!1,document.getElementById("welcome")?.classList.add("hidden");let t=document.getElementById("project-view");t&&(t.classList.add("hidden"),t.style.display="none"),document.documentElement.classList.remove("notes-open"),(location.hash||"")!=="#/notes"&&(location.hash="/notes"),hn({keepList:!0})}function zl({restore:e=!0}={}){let t=document.getElementById("notes-page");if(!t)return;t.hidden=!0,document.documentElement.classList.remove("notes-open"),Ze=null,Lt=!1;let n=document.getElementById("notes-add-form");if(n&&(n.hidden=!0),!!e)if(l.sessionId){let s=document.getElementById("project-view");s&&(s.classList.remove("hidden"),s.style.cssText="display:flex;flex-direction:column;flex:1;min-height:0;overflow:hidden")}else{let s=document.getElementById("welcome");s&&(s.classList.remove("hidden"),s.style.display="")}}function Kl(){if(Fl)return;Fl=!0,(document.getElementById("main")||document.getElementById("root")).insertAdjacentHTML("beforeend",ap()),document.addEventListener("router:notes",()=>za()),document.getElementById("notes-page").addEventListener("click",s=>{if(s.target.closest("[data-notes-close]")){zl(),(location.hash||"")==="#/notes"&&history.back();return}let o=s.target.closest("[data-notes-add]");if(o){s.preventDefault(),Lt=!Lt;let m=document.getElementById("notes-add-form");m&&(m.hidden=!Lt),o.textContent=Lt?"\u6536\u8D77":"+ \u65B0\u589E",Lt&&document.getElementById("notes-add-text")?.focus();return}if(s.target.closest("[data-notes-submit]")){s.preventDefault(),Wl();return}let c=s.target.closest("[data-notes-edit]");if(c){s.preventDefault(),op(c.dataset.notesEdit);return}if(s.target.closest("[data-notes-save]")){s.preventDefault(),ip();return}if(s.target.closest("[data-notes-cancel]")){if(s.preventDefault(),Ze)rp();else{Lt=!1;let m=document.getElementById("notes-add-form");m&&(m.hidden=!0);let g=document.querySelector("[data-notes-add]");g&&(g.textContent="+ \u65B0\u589E")}return}let f=s.target.closest("[data-notes-remove]");if(f){s.preventDefault();let m=f.dataset.notesRemove;confirm("\u5220\u9664\u8FD9\u6761\u8BB0\u5F55?")&&Jl(m)}});let n=document.getElementById("notes-add-text");n&&n.addEventListener("keydown",s=>{(s.metaKey||s.ctrlKey)&&s.key==="Enter"&&(s.preventDefault(),Wl())})}function ap(){return`
|
|
106
106
|
<section id="notes-page" class="notes-page" hidden>
|
|
107
107
|
<header class="notes-header">
|
|
108
108
|
<div>
|
|
@@ -124,21 +124,21 @@ ${String(e||"")}`}function vl(e,t=l.sessionId){let n=Cu(e,t);!e||Ta.has(n)||(Ta.
|
|
|
124
124
|
<ul id="notes-list" class="notes-list">
|
|
125
125
|
<li class="notes-empty">\u52A0\u8F7D\u4E2D\u2026</li>
|
|
126
126
|
</ul>
|
|
127
|
-
</section>`}async function
|
|
128
|
-
<textarea class="notes-edit-text" rows="4">${
|
|
127
|
+
</section>`}async function hn({keepList:e=!1}={}){let t=document.getElementById("notes-list");if(t){(!e||!mn)&&(t.innerHTML='<li class="notes-empty">\u52A0\u8F7D\u4E2D\u2026</li>');try{mn=(await x("GET","/api/notes?limit=200",void 0,void 0,{hub:!0}))?.items||[],Hr()}catch(n){t.innerHTML=`<li class="notes-empty notes-error">\u52A0\u8F7D\u5931\u8D25:${n?.message||n}</li>`}}}function Hr(){let e=document.getElementById("notes-list");if(!e)return;let t=document.getElementById("notes-count");t&&(t.textContent=mn?.length?`${mn.length} \u6761\u8BB0\u4E8B \xB7 \u591A\u7AEF\u5B9E\u65F6\u540C\u6B65`:"\u591A\u7AEF\u5B9E\u65F6\u540C\u6B65");let n=document.getElementById("notes-add-form");if(n&&(n.hidden=!Lt),!mn||mn.length===0){e.innerHTML='<li class="notes-empty">\u8FD8\u6CA1\u6709\u8BB0\u4E8B\u3002\u70B9\u4E0A\u9762\u7684\u300C\u65B0\u589E\u300D\uFF0C\u6216\u8005\u5728 Meta Agent \u91CC\u8F93\u5165\u300C\u8BB0: xxx\u300D</li>';return}e.innerHTML="";for(let s of mn){let a=document.createElement("li");a.className="notes-item",a.dataset.id=s.id,Ze===s.id?a.innerHTML=`
|
|
128
|
+
<textarea class="notes-edit-text" rows="4">${Gl(s.text)}</textarea>
|
|
129
129
|
<div class="notes-item-actions">
|
|
130
130
|
<button class="btn btn-sm btn-primary" data-notes-save>\u4FDD\u5B58</button>
|
|
131
131
|
<button class="btn btn-sm btn-ghost" data-notes-cancel>\u53D6\u6D88</button>
|
|
132
132
|
</div>`:a.innerHTML=`
|
|
133
|
-
<div class="notes-text">${
|
|
133
|
+
<div class="notes-text">${Gl(s.text)}</div>
|
|
134
134
|
<div class="notes-item-foot">
|
|
135
|
-
<span class="notes-meta">${
|
|
135
|
+
<span class="notes-meta">${lp(s.createdAt)}</span>
|
|
136
136
|
<div class="notes-item-actions">
|
|
137
137
|
<button class="btn btn-ghost btn-xs" data-notes-edit="${s.id}" title="\u7F16\u8F91">\u7F16\u8F91</button>
|
|
138
138
|
<button class="btn btn-ghost btn-xs text-error" data-notes-remove="${s.id}" title="\u5220\u9664">\u5220\u9664</button>
|
|
139
139
|
</div>
|
|
140
|
-
</div>`,e.appendChild(a)}}function
|
|
141
|
-
`);
|
|
140
|
+
</div>`,e.appendChild(a)}}function op(e){Ze=e,Hr()}function rp(){Ze=null,Hr()}async function ip(){let e=document.getElementById("notes-list");if(!e)return;let t=e.querySelector(`li[data-id="${cp(Ze)}"]`);if(!t)return;let n=t.querySelector(".notes-edit-text");if(!n)return;let s=(n.value||"").trim();if(!s){confirm("\u6587\u672C\u4E3A\u7A7A,\u5220\u9664\u8FD9\u6761\u8BB0\u5F55?")&&await Jl(Ze);return}try{await x("PATCH",`/api/notes/${Ze}`,{text:s},void 0,{hub:!0}),Ze=null,await hn({keepList:!0})}catch(a){alert("\u4FDD\u5B58\u5931\u8D25:"+(a?.message||a))}}async function Wl(){let e=document.getElementById("notes-add-text");if(!e)return;let t=(e.value||"").trim();if(!t){e.focus();return}try{await x("POST","/api/notes",{text:t},void 0,{hub:!0}),e.value="",Lt=!1;let n=document.getElementById("notes-add-form");n&&(n.hidden=!0);let s=document.querySelector("[data-notes-add]");s&&(s.textContent="+ \u65B0\u589E"),await hn({keepList:!0})}catch(n){alert("\u4FDD\u5B58\u5931\u8D25:"+(n?.message||n))}}async function Jl(e){try{await x("DELETE",`/api/notes/${e}`,void 0,void 0,{hub:!0}),Ze===e&&(Ze=null),await hn({keepList:!0})}catch(t){alert("\u5220\u9664\u5931\u8D25:"+(t?.message||t))}}function lp(e){if(!e)return"";let t=new Date(e),n=s=>String(s).padStart(2,"0");return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())} ${n(t.getHours())}:${n(t.getMinutes())}`}function cp(e){return typeof CSS<"u"&&CSS.escape?CSS.escape(e):String(e).replace(/[^a-zA-Z0-9_-]/g,t=>"\\"+t)}function Gl(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function qr(){Kl()}var mn,Ze,Fl,Lt,Ps=B(()=>{ce();W();mn=null,Ze=null,Fl=!1,Lt=!1;typeof window<"u"&&(window.addEventListener("hub:note-added",()=>{document.getElementById("notes-page")?.hidden||hn()}),window.addEventListener("hub:note-updated",()=>{document.getElementById("notes-page")?.hidden||hn()}),window.addEventListener("hub:note-removed",()=>{document.getElementById("notes-page")?.hidden||hn()}))});function ts(e){return Ve(e,{fallback:t=>p(t).replace(/\n/g,"<br>")})}function ns(e){e&&(typeof hljs<"u"&&e.querySelectorAll("pre code").forEach(t=>{try{hljs.highlightElement(t)}catch{}}),yt(e),xt(e))}async function Ur(e,t,n){let s=ct({"Content-Type":"application/json"},{hub:!0}),a=await fetch(e,{method:"POST",headers:s,body:JSON.stringify(t||{})});if(!a.ok){let d=await a.json().catch(()=>({}));throw new Error(d.error||`HTTP ${a.status}`)}let o=a.body.getReader(),r=new TextDecoder,c="",u="message";for(;;){let{done:d,value:f}=await o.read();if(d)break;c+=r.decode(f,{stream:!0});let m=c.split(`
|
|
141
|
+
`);c=m.pop()||"";for(let g of m)if(g.startsWith("event:"))u=g.slice(6).trim();else if(g.startsWith("data:")){let w=g.slice(5).trim();if(!w)continue;let y;try{y=JSON.parse(w)}catch{continue}n[u]?.(y),!n[u]&&n.tool&&(u==="tool_call"&&n.tool({name:y.name,args:y.args,id:y.callId,phase:"start"}),u==="tool_result"&&n.tool({id:y.callId,phase:y.ok===!1?"error":"done",result:y.ok===!1?y.error:y.result})),n.any?.(u,y),u="message"}else g.trim()===""&&(u="message")}}function dp(){return`
|
|
142
142
|
<div id="meta-agent-panel" class="meta-agent-panel hidden" aria-hidden="true">
|
|
143
143
|
<div class="meta-agent-backdrop" data-ma-close="1"></div>
|
|
144
144
|
<div class="meta-agent-sheet">
|
|
@@ -318,39 +318,39 @@ ${String(e||"")}`}function vl(e,t=l.sessionId){let n=Cu(e,t);!e||Ta.has(n)||(Ta.
|
|
|
318
318
|
</div>
|
|
319
319
|
</div>
|
|
320
320
|
</div>
|
|
321
|
-
</div>`}function Te(e){Rt=e;let t=i("ma-mode-chat"),n=i("ma-mode-history"),s=i("ma-mode-notes"),a=i("ma-mode-report"),o=i("ma-mode-config");for(let[
|
|
321
|
+
</div>`}function Te(e){Rt=e;let t=i("ma-mode-chat"),n=i("ma-mode-history"),s=i("ma-mode-notes"),a=i("ma-mode-report"),o=i("ma-mode-config");for(let[c,u]of[[t,"chat"],[n,"history"],[s,"notes"],[a,"report"],[o,"config"]]){if(!c)continue;let d=e===u;c.classList.toggle("hidden",!d),c.classList.toggle("flex",d)}let r=(c,u)=>{let d=i(c);d&&(d.classList.toggle("border-primary/40",u),d.classList.toggle("text-primary",u))};r("ma-btn-chat",e==="chat"),r("ma-btn-history",e==="history"),r("ma-btn-notes",e==="notes"),r("ma-btn-report",e==="report"),e==="history"&&xn(),e==="notes"&&bn()}function qs(){let e=i("ma-session-title"),t=i("ma-resume-bar"),n=i("ma-resume-text");if(!we){e&&(e.textContent="\u65B0\u5BF9\u8BDD"),t?.classList.add("hidden");return}let s=qe?.title||we.slice(0,8),a=Xa(qe?.updatedAt);if(e&&(e.textContent=a?`${s} \xB7 ${a}`:s),t&&n){t.classList.remove("hidden");let o=qe?.messageCount;n.textContent=o?`\u5DF2\u52A0\u8F7D\u5386\u53F2 \xB7 ${o} \u6761\u6D88\u606F \xB7 \u53D1\u9001\u5373\u53EF\u7EE7\u7EED`:"\u5DF2\u52A0\u8F7D\u5386\u53F2\u4F1A\u8BDD \xB7 \u53D1\u9001\u5373\u53EF\u7EE7\u7EED"}}function Fr(e="chat"){let t=i("meta-agent-panel");if(t){if(t.classList.remove("hidden"),t.setAttribute("aria-hidden","false"),Ya=!0,Te(e),e==="chat"){Et();let n=localStorage.getItem(Bt);!we&&n?It(n,{silent:!0}).catch(()=>{localStorage.removeItem(Bt)}):qs()}e==="history"&&Et().then(()=>xn()),e==="report"&&rc(),e==="config"&&ic(),setTimeout(()=>{Rt==="chat"&&i("ma-input")?.focus(),Rt==="history"&&i("ma-history-search")?.focus()},50)}}function nc(){let e=i("meta-agent-panel");e&&(e.classList.add("hidden"),e.setAttribute("aria-hidden","true"),Ya=!1)}function sc(){Ya?nc():Fr(Rt==="config"?"chat":Rt)}function ee(e,t,n={}){let s=i("ma-messages");if(!s)return null;let a=document.createElement("div");return a.className=`ma-msg ma-msg-${e}`,e==="user"?a.innerHTML=`<div class="ma-bubble user">${p(t)}</div>`:e==="assistant"?(a.innerHTML=`<div class="ma-bubble assistant md">${ts(t)}</div>`,ns(a)):e==="reasoning"?(a.innerHTML='<details class="ma-reasoning" open><summary>\u601D\u8003\u8FC7\u7A0B</summary><pre style="white-space:pre-wrap"></pre></details>',a.querySelector("pre").textContent=t):e==="error"?a.innerHTML=`<div class="ma-bubble error">${p(t)}</div>`:e==="system"?a.innerHTML=`<div class="ma-sys">${p(t)}</div>`:e==="tool"&&(a.innerHTML=`<details class="ma-tool" data-tool-id="${p(n.id||"")}">
|
|
322
322
|
<summary><span class="ma-tool-name">${p(n.name||"tool")}</span>
|
|
323
323
|
<span class="ma-tool-phase">${p(n.phase||"")}</span></summary>
|
|
324
324
|
<pre class="ma-tool-args" style="white-space:pre-wrap">${p(JSON.stringify(n.args||{},null,2))}</pre>
|
|
325
|
-
</details>`),s.appendChild(a),s.scrollTop=s.scrollHeight,a}function
|
|
325
|
+
</details>`),s.appendChild(a),s.scrollTop=s.scrollHeight,a}function Vl(e,t){let n=e?.querySelector(".ma-bubble");n&&(n.innerHTML=ts(t),ns(n),i("ma-messages").scrollTop=i("ma-messages").scrollHeight)}function Or(e,t,n){let s=i("ma-messages");if(!s)return;let a=s.querySelector(`[data-tool-id="${CSS.escape(e)}"]`);if(!a)return;a.classList.toggle("done",t==="done"),a.classList.toggle("error",t==="error");let o=a.querySelector(".ma-tool-phase");if(o&&(o.textContent=t),n!==void 0&&t!=="start"){let r=a.querySelector(".ma-tool-result");r||(r=document.createElement("pre"),r.className="ma-tool-result",r.style.whiteSpace="pre-wrap",a.appendChild(r)),r.textContent=JSON.stringify(n,null,2)}}function up(e){let t=i("ma-messages");if(!t)return;let n=document.createElement("div");n.className="ma-approval",n.dataset.approvalId=e.id;let s=e.args?.command??"";n.innerHTML=`
|
|
326
326
|
<div class="ma-approval-label">\u26A0 Agent \u60F3\u8981\u6267\u884C\u547D\u4EE4\uFF0C\u662F\u5426\u5141\u8BB8\uFF1F</div>
|
|
327
327
|
<pre class="ma-approval-cmd">${p(s)}</pre>
|
|
328
328
|
<div class="ma-approval-actions">
|
|
329
329
|
<button type="button" class="btn btn-xs btn-error" data-approve="0">\u62D2\u7EDD</button>
|
|
330
330
|
<button type="button" class="btn btn-xs btn-success" data-approve="1">\u5141\u8BB8\u6267\u884C</button>
|
|
331
|
-
</div>`,n.querySelectorAll("[data-approve]").forEach(a=>{a.addEventListener("click",async()=>{let o=a.dataset.approve==="1";n.querySelectorAll("button").forEach(r=>{r.disabled=!0}),n.querySelector(".ma-approval-label").textContent=o?"\u2713 \u5DF2\u5141\u8BB8\uFF0C\u6B63\u5728\u6267\u884C\u2026":"\u2717 \u5DF2\u62D2\u7EDD";try{await x("POST","/api/ai/approve",{id:e.id,approved:o})}catch(r){n.querySelector(".ma-approval-label").textContent=`\u786E\u8BA4\u5931\u8D25\uFF1A${r.message}`}})}),t.appendChild(n),t.scrollTop=t.scrollHeight}function
|
|
332
|
-
`)&&
|
|
331
|
+
</div>`,n.querySelectorAll("[data-approve]").forEach(a=>{a.addEventListener("click",async()=>{let o=a.dataset.approve==="1";n.querySelectorAll("button").forEach(r=>{r.disabled=!0}),n.querySelector(".ma-approval-label").textContent=o?"\u2713 \u5DF2\u5141\u8BB8\uFF0C\u6B63\u5728\u6267\u884C\u2026":"\u2717 \u5DF2\u62D2\u7EDD";try{await x("POST","/api/ai/approve",{id:e.id,approved:o})}catch(r){n.querySelector(".ma-approval-label").textContent=`\u786E\u8BA4\u5931\u8D25\uFF1A${r.message}`}})}),t.appendChild(n),t.scrollTop=t.scrollHeight}function pp(){return Ql+=1,`img${Ql}`}function fp(e,t){if(!e)return;let n=e.selectionStart??e.value.length,s=e.selectionEnd??e.value.length;e.value=e.value.slice(0,n)+t+e.value.slice(s),e.selectionStart=e.selectionEnd=n+t.length,e.dispatchEvent(new Event("input"))}async function Yl(e,t){let n=ct({"x-filename":t||`paste-${Date.now()}.png`},{hub:!0});delete n["Content-Type"];let s=await fetch("/api/upload-image",{method:"POST",headers:n,body:e});if(!s.ok){let d=await s.json().catch(()=>({}));throw new Error(d.error||`Upload failed: ${s.status}`)}let{path:a}=await s.json();if(!a)throw new Error("upload returned no path");let o=pp(),r=`[${o}](${a})`,c=i("ma-input");fp(c,(c?.value&&!c.value.endsWith(`
|
|
332
|
+
`)&&c.value.length?`
|
|
333
333
|
`:"")+r+`
|
|
334
|
-
`);let u="";try{u=URL.createObjectURL(e)}catch{}return
|
|
334
|
+
`);let u="";try{u=URL.createObjectURL(e)}catch{}return gn.push({path:a,previewUrl:u,label:o,ref:r}),Wr(),{path:a,ref:r,label:o}}function Wr(){let e=i("ma-attach-bar");if(e){if(!gn.length){e.classList.add("hidden"),e.innerHTML="";return}e.classList.remove("hidden"),e.innerHTML=gn.map((t,n)=>`
|
|
335
335
|
<div class="ma-thumb relative" title="${p(t.ref||t.path)}">
|
|
336
336
|
${t.previewUrl?`<img src="${t.previewUrl}" alt="${p(t.label||"img")}">`:`<span class="ma-thumb-path">${p(t.label||"img")}</span>`}
|
|
337
337
|
<span class="ma-thumb-label">${p(t.label||"")}</span>
|
|
338
338
|
<button type="button" class="ma-thumb-x" data-rm-img="${n}">\u2715</button>
|
|
339
|
-
</div>`).join(""),e.querySelectorAll("[data-rm-img]").forEach(t=>{t.addEventListener("click",()=>{let n=parseInt(t.dataset.rmImg,10),s=
|
|
339
|
+
</div>`).join(""),e.querySelectorAll("[data-rm-img]").forEach(t=>{t.addEventListener("click",()=>{let n=parseInt(t.dataset.rmImg,10),s=gn[n];if(s?.previewUrl)try{URL.revokeObjectURL(s.previewUrl)}catch{}let a=i("ma-input");a&&s?.ref&&(a.value=a.value.split(s.ref).join("").replace(/\n{3,}/g,`
|
|
340
340
|
|
|
341
|
-
`),a.dispatchEvent(new Event("input"))),
|
|
341
|
+
`),a.dispatchEvent(new Event("input"))),gn.splice(n,1),Wr()})})}}function Xa(e){if(!e)return"";let t=new Date(e);if(Number.isNaN(t.getTime()))return"";let n=String(t.getMonth()+1).padStart(2,"0"),s=String(t.getDate()).padStart(2,"0"),a=String(t.getHours()).padStart(2,"0"),o=String(t.getMinutes()).padStart(2,"0");return`${n}-${s} ${a}:${o}`}async function Et(){try{Qa=(await x("GET","/api/ai/sessions")).sessions||[]}catch{Qa=[]}return Qa}function ac(){let e=E.peek(),t=l.sessionId?`${l.agent||$.peek()||"claude"}:${l.sessionId.slice(0,8)}`:"";return{project:e?.path||"",sessionId:l.sessionId||"",agent:l.agent||$.peek()||"claude",summary:[e?.name?`\u9879\u76EE ${e.name}`:"",t?`\u4F1A\u8BDD ${t}`:""].filter(Boolean).join(" \xB7 ")}}function Hs(){vn=null,tc=null,i("ma-note-title").value="",i("ma-note-content").value="",i("ma-note-pin").checked=!1,i("ma-note-link-project").checked=!!E.peek()?.path,i("ma-note-link-session").checked=!!l.sessionId,i("ma-note-status").textContent="\u65B0\u8BB0\u4E8B",i("ma-note-delete").disabled=!0,i("ma-note-links").textContent=ac().summary||"\u672A\u5173\u8054\u4E0A\u4E0B\u6587"}function oc(e){vn=e?.id||null,tc=e||null,i("ma-note-title").value=e?.title||"",i("ma-note-content").value=e?.content||"",i("ma-note-pin").checked=!!e?.pinned,i("ma-note-link-project").checked=!!e?.cwd,i("ma-note-link-session").checked=!!e?.sessionId,i("ma-note-status").textContent=e?.updatedAt?`\u4E0A\u6B21\u66F4\u65B0 ${Xa(e.updatedAt)}`:"",i("ma-note-delete").disabled=!e?.id;let t=[];e?.cwd&&t.push(`\u9879\u76EE ${e.cwd.split("/").pop()}`),e?.sessionId&&t.push(`\u4F1A\u8BDD ${e.agent||"claude"}:${e.sessionId.slice(0,8)}`),i("ma-note-links").textContent=t.join(" \xB7 ")||"\u672A\u5173\u8054\u4E0A\u4E0B\u6587"}function mp(){let e=i("ma-note-title")?.value?.trim()||"",t=i("ma-note-content")?.value?.trim()||"";if(!e&&!t){i("ma-note-status").textContent="\u5148\u9009\u4E00\u6761\u8BB0\u4E8B\u6216\u8F93\u5165\u5185\u5BB9";return}let n=[];i("ma-note-link-project")?.checked&&E.peek()?.path&&n.push(`\u9879\u76EE\u8DEF\u5F84\uFF1A${E.peek().path}`),i("ma-note-link-session")?.checked&&l.sessionId&&n.push(`\u5173\u8054\u4F1A\u8BDD\uFF1A${l.agent||$.peek()||"claude"} / ${l.sessionId}`);let s=["\u57FA\u4E8E\u4E0B\u9762\u8FD9\u6761\u5DE5\u4F5C\u8BB0\u4E8B\u56DE\u7B54\uFF0C\u5E76\u7ED3\u5408\u76F8\u5173\u4F1A\u8BDD\u4E0E\u9879\u76EE\u4E0A\u4E0B\u6587\uFF1A",`\u6807\u9898\uFF1A${e||"\u672A\u547D\u540D"}`,t?`\u5185\u5BB9\uFF1A
|
|
342
342
|
${t}`:"",n.length?n.join(`
|
|
343
343
|
`):"","","\u8BF7\u5148\u603B\u7ED3\u8FD9\u6761\u8BB0\u4E8B\u7684\u6838\u5FC3\uFF0C\u518D\u7ED9\u51FA\u4E0B\u4E00\u6B65\u5EFA\u8BAE\u548C\u53EF\u80FD\u98CE\u9669\u3002"].filter(Boolean).join(`
|
|
344
|
-
`);Te("chat"),i("ma-input").value=s,i("ma-input").dispatchEvent(new Event("input")),i("ma-input").focus()}async function
|
|
344
|
+
`);Te("chat"),i("ma-input").value=s,i("ma-input").dispatchEvent(new Event("input")),i("ma-input").focus()}async function es(){let e=(ec||"").trim();return Va=(await x("GET",`/api/ai/notes?limit=80${e?`&q=${encodeURIComponent(e)}`:""}`)).notes||[],Va}function bn(){let e=i("ma-notes-list");if(e){if(!Va.length){e.innerHTML='<div class="text-center text-xs text-base-content/40 py-10">\u8FD8\u6CA1\u6709\u8BB0\u4E8B\u3002</div>';return}e.innerHTML=Va.map(t=>{let n=t.id===vn,s=[t.scope==="project"?"\u9879\u76EE":t.scope==="session"?"\u4F1A\u8BDD":"\u901A\u7528",t.pinned?"\u7F6E\u9876":""].filter(Boolean).join(" \xB7 ");return`
|
|
345
345
|
<button type="button" class="ma-note-item ${n?"active":""}" data-note-id="${p(t.id)}">
|
|
346
346
|
<div class="text-left">
|
|
347
347
|
<div class="font-medium text-xs truncate">${p(t.title||"\u672A\u547D\u540D")}</div>
|
|
348
348
|
<div class="text-[10px] text-base-content/45 mt-0.5 line-clamp-2">${p(t.content||"")}</div>
|
|
349
|
-
<div class="text-[10px] text-base-content/35 mt-1">${p(s)}${s?" \xB7 ":""}${p(
|
|
349
|
+
<div class="text-[10px] text-base-content/35 mt-1">${p(s)}${s?" \xB7 ":""}${p(Xa(t.updatedAt)||"")}</div>
|
|
350
350
|
</div>
|
|
351
|
-
</button>`}).join(""),e.querySelectorAll("[data-note-id]").forEach(t=>{t.addEventListener("click",async()=>{try{let n=await x("GET",`/api/ai/notes/${t.dataset.noteId}`);
|
|
351
|
+
</button>`}).join(""),e.querySelectorAll("[data-note-id]").forEach(t=>{t.addEventListener("click",async()=>{try{let n=await x("GET",`/api/ai/notes/${t.dataset.noteId}`);oc(n),bn()}catch(n){i("ma-note-status").textContent=n.message}})})}}async function hp(){let e=i("ma-note-title")?.value?.trim()||"",t=i("ma-note-content")?.value?.trim()||"";if(!e||!t){i("ma-note-status").textContent="\u6807\u9898\u548C\u5185\u5BB9\u90FD\u4E0D\u80FD\u4E3A\u7A7A";return}let n=ac(),s={id:vn||void 0,title:e,content:t,pinned:!!i("ma-note-pin")?.checked,cwd:i("ma-note-link-project")?.checked?n.project:"",sessionId:i("ma-note-link-session")?.checked?n.sessionId:"",agent:i("ma-note-link-session")?.checked?n.agent:""};i("ma-note-status").textContent="\u4FDD\u5B58\u4E2D\u2026";let a=await x("POST","/api/ai/notes",s);oc(a),await es(),bn()}async function gp(){if(!vn){Hs();return}confirm("\u5220\u9664\u8FD9\u6761\u8BB0\u4E8B\uFF1F\u4E0D\u53EF\u6062\u590D\u3002")&&(await x("DELETE",`/api/ai/notes/${vn}`),Hs(),await es(),bn())}function xn(){let e=i("ma-history-list");if(!e)return;let t=(Zl||"").trim().toLowerCase(),n=Qa;if(t&&(n=n.filter(s=>`${s.title||""} ${s.preview||""} ${s.id||""}`.toLowerCase().includes(t))),!n.length){e.innerHTML=`<div class="text-center text-xs text-base-content/40 py-10">
|
|
352
352
|
${t?"\u6CA1\u6709\u5339\u914D\u7684\u4F1A\u8BDD":"\u8FD8\u6CA1\u6709\u5386\u53F2\u5BF9\u8BDD\u3002\u53D1\u4E00\u6761\u6D88\u606F\u540E\u4F1A\u51FA\u73B0\u5728\u8FD9\u91CC\u3002"}
|
|
353
|
-
</div>`;return}e.innerHTML=n.map(s=>{let a=s.id===we,o=
|
|
353
|
+
</div>`;return}e.innerHTML=n.map(s=>{let a=s.id===we,o=Xa(s.updatedAt)||"",r=s.messageCount||0;return`
|
|
354
354
|
<div class="ma-hist-item ${a?"active":""}" data-hist-id="${p(s.id)}">
|
|
355
355
|
<div class="flex items-start gap-2">
|
|
356
356
|
<button type="button" class="ma-hist-open flex-1 min-w-0 text-left" data-hist-open="${p(s.id)}">
|
|
@@ -363,49 +363,49 @@ ${t}`:"",n.length?n.join(`
|
|
|
363
363
|
<button type="button" class="btn btn-ghost btn-xs px-1 text-error" data-hist-del="${p(s.id)}" title="\u5220\u9664">\u2715</button>
|
|
364
364
|
</div>
|
|
365
365
|
</div>
|
|
366
|
-
</div>`}).join(""),e.querySelectorAll("[data-hist-open]").forEach(s=>{s.addEventListener("click",async()=>{await It(s.dataset.histOpen),Te("chat"),i("ma-input")?.focus()})}),e.querySelectorAll("[data-hist-resume]").forEach(s=>{s.addEventListener("click",async a=>{a.stopPropagation(),await It(s.dataset.histResume),Te("chat"),i("ma-input")?.focus()})}),e.querySelectorAll("[data-hist-del]").forEach(s=>{s.addEventListener("click",async a=>{a.stopPropagation();let o=s.dataset.histDel;if(confirm("\u5220\u9664\u8BE5\u5386\u53F2\u4F1A\u8BDD\uFF1F\u4E0D\u53EF\u6062\u590D\u3002"))try{await x("DELETE",`/api/ai/sessions/${o}`),we===o&&(we=null,qe=null,localStorage.removeItem(Bt),It(null)),await Et(),
|
|
367
|
-
`)||"[\u2026]"}function
|
|
366
|
+
</div>`}).join(""),e.querySelectorAll("[data-hist-open]").forEach(s=>{s.addEventListener("click",async()=>{await It(s.dataset.histOpen),Te("chat"),i("ma-input")?.focus()})}),e.querySelectorAll("[data-hist-resume]").forEach(s=>{s.addEventListener("click",async a=>{a.stopPropagation(),await It(s.dataset.histResume),Te("chat"),i("ma-input")?.focus()})}),e.querySelectorAll("[data-hist-del]").forEach(s=>{s.addEventListener("click",async a=>{a.stopPropagation();let o=s.dataset.histDel;if(confirm("\u5220\u9664\u8BE5\u5386\u53F2\u4F1A\u8BDD\uFF1F\u4E0D\u53EF\u6062\u590D\u3002"))try{await x("DELETE",`/api/ai/sessions/${o}`),we===o&&(we=null,qe=null,localStorage.removeItem(Bt),It(null)),await Et(),xn()}catch(r){alert(r.message)}})})}function Xl(e){return typeof e=="string"?e:Array.isArray(e)&&e.map(t=>typeof t=="string"?t:t?.type==="text"?t.text||"":t?.type==="image_url"?"[\u56FE\u7247]":"").filter(Boolean).join(`
|
|
367
|
+
`)||"[\u2026]"}function bp(e){let t=i("ma-messages");if(t){if(t.innerHTML="",!e?.length){ee("system","\u6B64\u4F1A\u8BDD\u6682\u65E0\u6D88\u606F\u3002");return}for(let n of e){if(n.role==="user"){ee("user",Xl(n.content));continue}if(n.role==="assistant"){if(n.reasoning&&(ee("reasoning",n.reasoning).querySelector("details").open=!1),n.content&&ee("assistant",typeof n.content=="string"?n.content:Xl(n.content)),n.tool_calls?.length)for(let s of n.tool_calls){let a=s.function?.name||s.name||"tool",o={};try{o=JSON.parse(s.function?.arguments||s.arguments||"{}")}catch{}ee("tool","",{name:a,args:o,phase:"history",id:s.id||a})}continue}if(n.role==="tool"){let s=n.content;try{s=JSON.parse(n.content)}catch{}let a=n.tool_call_id||"";if(a)Or(a,typeof s=="string"&&s.startsWith("error:")?"error":"done",s);else{ee("tool","",{name:"tool_result",args:{},phase:"done",id:`tr_${Math.random().toString(36).slice(2,8)}`});let o=t.querySelectorAll(".ma-tool"),r=o[o.length-1];if(r){r.classList.add("done");let c=r.querySelector(".ma-tool-result");c||(c=document.createElement("pre"),c.className="ma-tool-result",c.style.whiteSpace="pre-wrap",r.appendChild(c)),c.textContent=typeof s=="string"?s.slice(0,500):JSON.stringify(s,null,2)}}}}t.scrollTop=t.scrollHeight}}async function vp(){if(!we){await It(null);return}if(confirm("\u5220\u9664\u5F53\u524D Meta Agent \u4F1A\u8BDD\uFF1F\u6B64\u64CD\u4F5C\u4E0D\u53EF\u6062\u590D\u3002"))try{await x("DELETE",`/api/ai/sessions/${we}`),we=null,qe=null,localStorage.removeItem(Bt),await Et(),await It(null),Rt==="history"&&xn()}catch(e){ee("error",e.message)}}async function It(e,t={}){if(!e){we=null,qe=null,localStorage.removeItem(Bt);let n=i("ma-messages");return n&&(n.innerHTML=""),ee("system","\u65B0\u5BF9\u8BDD \u2014 \u8D34\u56FE \u2192 [imgN](\u8DEF\u5F84)\uFF1B\u9700\u8981\u770B\u56FE\u65F6\u8C03\u7528 VLM\u3002\u5386\u53F2\u5728\u300C\u5386\u53F2\u300D\u9875\uFF0C\u53EF\u968F\u65F6 resume\u3002"),qs(),null}try{let n=await x("GET",`/api/ai/sessions/${e}`);return we=n.id,qe={id:n.id,title:n.title,updatedAt:n.updatedAt,messageCount:(n.messages||[]).length},localStorage.setItem(Bt,n.id),bp(n.messages||[]),t.silent||ee("system","\u2191 \u5386\u53F2\u5DF2\u52A0\u8F7D\u3002\u5728\u4E0B\u65B9\u7EE7\u7EED\u8F93\u5165\u5373\u53EF resume\uFF08\u670D\u52A1\u7AEF\u4FDD\u7559\u5B8C\u6574 tool / VLM \u4E0A\u4E0B\u6587\uFF09\u3002"),qs(),Rt==="history"&&xn(),n}catch(n){throw t.silent||ee("error",n.message),n}}async function Ja(){if(Zn)return;let e=i("ma-input"),t=(e?.value||"").trim();if(!t)return;Zn=!0,i("ma-send").disabled=!0,ee("user",t),e.value="",e.style.height="";for(let o of gn)if(o.previewUrl)try{URL.revokeObjectURL(o.previewUrl)}catch{}gn=[],Wr();let n=null,s="",a=null;try{await Ur("/api/ai/chat",{message:t,sessionId:we},{session:o=>{we=o.id,qe={...qe||{},id:o.id,title:o.title||qe?.title||t.slice(0,40),updatedAt:Date.now()},localStorage.setItem(Bt,o.id),qs()},round_start:()=>{n=null,a&&(a.querySelector("details").open=!1),a=null},reasoning:o=>{a||(a=ee("reasoning","")),a.querySelector("pre").textContent=o.content||""},tool_call:o=>{ee("tool","",{name:o.name,args:o.args,phase:"\u6267\u884C\u4E2D",id:o.callId})},tool_result:o=>Or(o.callId,o.ok===!1?"error":"done",o.ok===!1?o.error:o.result),content:o=>{s=o.content||"",n||(n=ee("assistant","")),Vl(n,s)},tool:o=>{o.phase==="start"?ee("tool","",{name:o.name,args:o.args,phase:"start",id:o.id}):Or(o.id,o.phase,o.result)},approval:o=>up(o),done:o=>{o.sessionId&&(we=o.sessionId,localStorage.setItem(Bt,o.sessionId)),(o.title||o.sessionId)&&(qe={id:we,title:o.title||qe?.title||"\u5BF9\u8BDD",updatedAt:Date.now(),messageCount:(qe?.messageCount||0)+2}),o.content&&(n||(n=ee("assistant","")),Vl(n,o.content)),a&&(a.querySelector("details").open=!1),qs(),Et()},error:o=>{ee("error",o.message||"error")}})}catch(o){ee("error",o.message)}finally{Zn=!1,i("ma-send").disabled=!1}}async function xp(){if(Zn)return;Zn=!0;let e=parseInt(i("ma-report-days")?.value||"1",10),t=i("ma-report-body");t.innerHTML=`<div class="text-sm text-base-content/50 py-6 text-center">\u6B63\u5728\u6C47\u603B\u8FD1 ${e} \u5929\u6D3B\u52A8\u2026</div>`,i("ma-gen-report").disabled=!0;let n="",s=document.createElement("div");s.className="ma-report-tools flex flex-col gap-1 mb-3";try{await Ur("/api/ai/report",{days:e},{content:a=>{n=a.content||"",t.innerHTML="",t.appendChild(s);let o=document.createElement("div");o.className="md ma-report-md",o.innerHTML=ts(n),ns(o),t.appendChild(o)},tool:a=>{if(a.phase==="start"){let o=document.createElement("div");o.className="ma-tool",o.dataset.toolId=a.id||a.name,o.innerHTML=`<span class="ma-tool-name">${p(a.name)}</span> <span class="ma-tool-phase">start</span>`,s.appendChild(o)}else{let o=s.querySelector(`[data-tool-id="${CSS.escape(a.id||a.name)}"]`);o&&(o.classList.add(a.phase==="error"?"error":"done"),o.querySelector(".ma-tool-phase").textContent=a.phase)}},done:a=>{if(a.content){t.innerHTML="",t.appendChild(s);let o=document.createElement("div");o.className="md ma-report-md",o.innerHTML=ts(a.content),ns(o),t.appendChild(o)}},error:a=>{t.innerHTML=`<div class="alert alert-error text-sm">${p(a.message)}</div>`}})}catch(a){t.innerHTML=`<div class="alert alert-error text-sm">${p(a.message)}</div>`}finally{Zn=!1,i("ma-gen-report").disabled=!1}}async function rc(){try{let e=new Date,t=`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,"0")}-${String(e.getDate()).padStart(2,"0")}`,n=await x("GET",`/api/ai/reports/${t}`);if(n?.markdown){let s=i("ma-report-body");s.innerHTML=`
|
|
368
368
|
<div class="text-[10px] text-base-content/40 mb-2">${p(n.title||t)} \xB7 ${p(n.generatedAt||"")}</div>
|
|
369
|
-
<div class="md ma-report-md">${
|
|
369
|
+
<div class="md ma-report-md">${ts(n.markdown)}</div>`,ns(s)}}catch{}}async function yp(){let e=i("ma-report-list");try{let t=await x("GET","/api/ai/reports");e.classList.remove("hidden");let n=t.reports||[];if(!n.length){e.innerHTML='<div class="text-xs text-base-content/40 px-2 py-1">\u6682\u65E0\u5386\u53F2\u62A5\u544A</div>';return}e.innerHTML=n.map(s=>`
|
|
370
370
|
<button type="button" class="ma-report-item w-full text-left px-2 py-1 rounded hover:bg-base-200 text-xs"
|
|
371
371
|
data-day="${p(s.day)}">
|
|
372
372
|
<span class="font-semibold">${p(s.day)}</span>
|
|
373
373
|
<span class="text-base-content/45 ml-1">${p(s.title||"")}</span>
|
|
374
374
|
</button>`).join(""),e.querySelectorAll("[data-day]").forEach(s=>{s.addEventListener("click",async()=>{try{let a=await x("GET",`/api/ai/reports/${s.dataset.day}`),o=i("ma-report-body");o.innerHTML=`
|
|
375
375
|
<div class="text-[10px] text-base-content/40 mb-2">${p(a.title||a.day)} \xB7 ${p(a.generatedAt||"")}</div>
|
|
376
|
-
<div class="md ma-report-md">${
|
|
377
|
-
<div class="aspect-square rounded-xl flex flex-col items-center justify-center p-2 relative transition-all min-h-[50px] md:min-h-[60px] ${
|
|
376
|
+
<div class="md ma-report-md">${ts(a.markdown)}</div>`,ns(o)}catch(a){i("ma-report-body").innerHTML=`<div class="alert alert-error text-sm">${p(a.message)}</div>`}})})}catch(t){e.classList.remove("hidden"),e.innerHTML=`<div class="text-xs text-error px-2">${p(t.message)}</div>`}}async function ic(){try{let e=await x("GET","/api/ai/config");i("ma-cfg-url").value=e.url||"",i("ma-cfg-model").value=e.model||"",i("ma-cfg-key").placeholder=e.hasKey?"\u5DF2\u914D\u7F6E \xB7 \u7559\u7A7A\u4E0D\u4FEE\u6539":"API Key",i("ma-cfg-key").value="",i("ma-cfg-vlm-url").value=e.vlm_url||"",i("ma-cfg-vlm-model").value=e.vlm_model||"",i("ma-cfg-vlm-key").value="",i("ma-cfg-vlm-key").placeholder=e.hasVlmKey?"\u5DF2\u914D\u7F6E \xB7 \u7559\u7A7A\u4E0D\u4FEE\u6539":"\u53EF\u9009",i("ma-cfg-system").value=e.system||"",i("ma-auto-report")&&(i("ma-auto-report").checked=!!e.auto_report),i("ma-auto-hour")&&(i("ma-auto-hour").value=String(e.auto_report_hour??18)),Rs(e)}catch(e){i("ma-cfg-status").textContent=e.message}}async function wp(){let e=i("ma-cfg-status");e.textContent="\u4FDD\u5B58\u4E2D\u2026";try{let t={url:i("ma-cfg-url").value.trim(),model:i("ma-cfg-model").value.trim(),vlm_url:i("ma-cfg-vlm-url").value.trim(),vlm_model:i("ma-cfg-vlm-model").value.trim(),system:i("ma-cfg-system").value,auto_report:!!i("ma-auto-report")?.checked,auto_report_hour:parseInt(i("ma-auto-hour")?.value||"18",10)},n=i("ma-cfg-key").value.trim(),s=i("ma-cfg-vlm-key").value.trim();n&&(t.key=n),s&&(t.vlm_key=s);let a=await x("PUT","/api/ai/config",t);e.textContent=a.hasKey?"\u5DF2\u4FDD\u5B58 \u2713":"\u5DF2\u4FDD\u5B58\uFF08\u672A\u8BBE\u7F6E Key\uFF09",i("ma-cfg-key").value="",i("ma-cfg-vlm-key").value="",Rs(a)}catch(t){e.textContent=t.message}}function Rs(e){if(Ka&&(clearInterval(Ka),Ka=null),!e?.auto_report)return;let t=e.auto_report_hour??18;Ka=setInterval(async()=>{if(!l.token)return;let n=new Date;if(n.getHours()!==t)return;let s=`${n.getFullYear()}-${String(n.getMonth()+1).padStart(2,"0")}-${String(n.getDate()).padStart(2,"0")}`;if(Br!==s&&!(n.getMinutes()>10))try{Br=s,localStorage.setItem("ai_last_auto_report",s),await Ur("/api/ai/report",{days:e.auto_report_days||1},{done:()=>{console.info("[meta-agent] auto report saved for",s)},error:a=>console.warn("[meta-agent] auto report",a.message)})}catch(a){console.warn("[meta-agent] auto report failed",a),Br="",localStorage.removeItem("ai_last_auto_report")}},60*1e3)}function lc(){i("meta-agent-panel")||(document.getElementById("root")?.insertAdjacentHTML("beforeend",dp()),document.querySelectorAll("[data-ma-close]").forEach(e=>{e.addEventListener("click",nc)}),i("ma-btn-chat")?.addEventListener("click",()=>Te("chat")),i("ma-btn-history")?.addEventListener("click",async()=>{await Et(),Te("history")}),i("ma-btn-notes")?.addEventListener("click",async()=>{await es(),vn||Hs(),Te("notes")}),i("ma-open-history")?.addEventListener("click",async()=>{await Et(),Te("history")}),i("ma-btn-report")?.addEventListener("click",()=>{Te("report"),rc()}),i("ma-btn-config")?.addEventListener("click",()=>{Te("config"),ic()}),i("ma-send")?.addEventListener("click",Ja),i("ma-input")?.addEventListener("keydown",e=>{(e.metaKey||e.ctrlKey)&&e.key==="Enter"&&(e.preventDefault(),Ja())}),i("ma-input")?.addEventListener("input",()=>{let e=i("ma-input");e.style.height="auto",e.style.height=Math.min(e.scrollHeight,120)+"px"}),i("ma-new-chat")?.addEventListener("click",()=>{It(null),Te("chat")}),i("ma-del-session")?.addEventListener("click",vp),i("ma-resume-focus")?.addEventListener("click",()=>{i("ma-input")?.focus()}),i("ma-history-refresh")?.addEventListener("click",async()=>{await Et(),xn()}),i("ma-history-new")?.addEventListener("click",()=>{It(null),Te("chat")}),i("ma-history-search")?.addEventListener("input",e=>{Zl=e.target.value||"",xn()}),i("ma-quick-today")?.addEventListener("click",()=>{Te("chat"),i("ma-input").value="\u6839\u636E\u6211\u6700\u8FD1\u7684\u4F1A\u8BDD\uFF0C\u603B\u7ED3\u4ECA\u5929\u6211\u505A\u4E86\u4EC0\u4E48\uFF1F\u6309\u9879\u76EE\u5217\u51FA\u4EAE\u70B9\u4E0E\u672A\u5B8C\u6210\u4E8B\u9879\u3002",Ja()}),i("ma-quick-projects")?.addEventListener("click",()=>{Te("chat"),i("ma-input").value="\u5217\u51FA\u6700\u8FD1 14 \u5929\u6D3B\u8DC3\u7684\u9879\u76EE\uFF0C\u6BCF\u4E2A\u9879\u76EE\u4E00\u53E5\u8BDD\u8BF4\u660E\u6700\u8FD1\u5728\u505A\u4EC0\u4E48\u3002",Ja()}),i("ma-gen-report")?.addEventListener("click",xp),i("ma-load-reports")?.addEventListener("click",yp),i("ma-notes-refresh")?.addEventListener("click",async()=>{await es(),bn()}),i("ma-notes-new")?.addEventListener("click",()=>{Hs(),bn(),i("ma-note-title")?.focus()}),i("ma-notes-search")?.addEventListener("input",async e=>{ec=e.target.value||"",await es(),bn()}),i("ma-note-save")?.addEventListener("click",async()=>{try{await hp()}catch(e){i("ma-note-status").textContent=e.message}}),i("ma-note-delete")?.addEventListener("click",async()=>{try{await gp()}catch(e){i("ma-note-status").textContent=e.message}}),i("ma-note-ask")?.addEventListener("click",mp),i("ma-cfg-save")?.addEventListener("click",wp),i("ma-auto-report")?.addEventListener("change",async()=>{try{let e=await x("PUT","/api/ai/config",{auto_report:!!i("ma-auto-report").checked,auto_report_hour:parseInt(i("ma-auto-hour")?.value||"18",10)});Rs(e)}catch{}}),i("ma-auto-hour")?.addEventListener("change",async()=>{try{let e=await x("PUT","/api/ai/config",{auto_report:!!i("ma-auto-report")?.checked,auto_report_hour:parseInt(i("ma-auto-hour").value||"18",10)});Rs(e)}catch{}}),i("ma-image-input")?.addEventListener("change",async e=>{let t=[...e.target.files||[]],n=i("ma-input");n&&(n.disabled=!0);try{for(let s of t)if(s.type.startsWith("image/")){if(s.size>12*1024*1024){ee("error",`${s.name} \u8FC7\u5927 (>12MB)`);continue}await Yl(s,s.name||`upload-${Date.now()}.png`)}}catch(s){ee("error",`\u56FE\u7247\u4E0A\u4F20\u5931\u8D25: ${s.message}`)}finally{e.target.value="",n&&(n.disabled=!1,n.focus())}}),document.addEventListener("paste",async e=>{if(!Ya||Rt!=="chat")return;let t=i("ma-input"),n=i("meta-agent-panel"),s=document.activeElement;if(!n||!s||!n.contains(s))return;let o=[...e.clipboardData?.items||[]].filter(r=>r.type.startsWith("image/"));if(o.length){e.preventDefault(),t&&(t.disabled=!0);try{for(let r of o){let c=r.getAsFile();if(!c)continue;let u=(r.type.split("/")[1]||"png").replace(/[^a-z0-9]/gi,"")||"png";await Yl(c,`paste-${Date.now()}.${u}`)}}catch(r){ee("error",`\u7C98\u8D34\u56FE\u7247\u5931\u8D25: ${r.message}`)}finally{t&&(t.disabled=!1,t.focus())}}}),It(null,{silent:!0}),Hs())}function Bs(){l.token&&(M.peek()&&!hs()||(Et(),es().catch(()=>{}),x("GET","/api/ai/config").then(Rs).catch(()=>{})))}var Ya,Rt,Zn,we,qe,gn,Ql,Ka,Br,Qa,Zl,Va,ec,vn,tc,Bt,Os=B(()=>{G();ce();W();qn();an();sn();Ya=!1,Rt="chat",Zn=!1,we=null,qe=null,gn=[],Ql=0,Ka=null,Br=localStorage.getItem("ai_last_auto_report")||"",Qa=[],Zl="",Va=[],ec="",vn=null,tc=null,Bt="ma_last_session_id"});function Gr(e){return Array.isArray(e)?e:e&&Array.isArray(e.results)?e.results:e&&Array.isArray(e.sessions)?e.sessions:[]}function wn(){let e=Gr(ne.peek()),t=j.peek();M.peek()&&t&&(e=e.filter(s=>s&&(!s.machineId||s.machineId===t)));let n=ye.peek();return n&&n!=="all"&&(e=e.filter(s=>s&&(s.agent||"claude")===n)),e}function uc(e){let t=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),s=String(e.getDate()).padStart(2,"0");return`${t}-${n}-${s}`}function kp(e,t){let n=[],a=new Date(e,t,1).getDay(),r=new Date(e,t+1,0).getDate(),c=new Date(e,t,0).getDate();for(let d=a-1;d>=0;d--)n.push({date:new Date(e,t-1,c-d),isCurrentMonth:!1});for(let d=1;d<=r;d++)n.push({date:new Date(e,t,d),isCurrentMonth:!0});let u=7-n.length%7;if(u<7)for(let d=1;d<=u;d++)n.push({date:new Date(e,t+1,d),isCurrentMonth:!1});return n}function pc(e,t){let n=new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime(),s=n+1440*60*1e3;return t.filter(a=>{let o=O(a.updatedAt);return o!=null&&o>=n&&o<s})}function fc(e){return e==null||isNaN(e)?"0":e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:String(e)}function kn(e){let t=i("calendar-grid");if(!t)return;e=Gr(e??wn());let n=i("calendar-month-year");if(n){let f=new Date(Za,yn,1);n.textContent=f.toLocaleDateString([],{month:"long",year:"numeric"})}let s=e.length,a=new Set(e.map(f=>f.cwd).filter(Boolean)).size,o=e.reduce((f,m)=>f+(Number(m.totalTokens)||0),0),r=i("stats-total-sessions"),c=i("stats-total-projects"),u=i("stats-total-tokens");r&&(r.textContent=String(s)),c&&(c.textContent=String(a)),u&&(u.textContent=fc(o));let d=kp(Za,yn);Us||(Us=uc(new Date)),t.innerHTML=d.map(f=>{let m=f.date,g=uc(m),y=pc(m,e).length,P=m.toDateString()===new Date().toDateString(),ae=g===Us,K="",pe="text-base-content/65",q="border border-transparent",Q="cursor-default",he=f.isCurrentMonth?"":"opacity-25";y>0?(Q="cursor-pointer",y<=2?(K="bg-primary/15",pe="text-primary font-bold",q="border border-primary/30"):y<=5?(K="bg-primary/30",pe="text-primary font-bold",q="border border-primary/50"):(K="bg-primary/60",pe="text-primary-content font-bold",q="border border-primary/80")):(K="bg-base-300/25",f.isCurrentMonth&&(Q="hover:bg-base-300/50")),P?q="border-2 border-primary":ae&&(q="border-2 border-accent");let Ae=m.getDate()===1?`<span class="absolute top-0.5 left-1 text-[8px] opacity-60 uppercase">${m.toLocaleDateString([],{month:"short"})}</span>`:"";return`
|
|
377
|
+
<div class="aspect-square rounded-xl flex flex-col items-center justify-center p-2 relative transition-all min-h-[50px] md:min-h-[60px] ${K} ${pe} ${q} ${Q} ${he}"
|
|
378
378
|
data-cal-date="${g}" title="${m.toDateString()}: ${y} session(s)">
|
|
379
379
|
${Ae}
|
|
380
380
|
<span class="text-sm font-semibold">${m.getDate()}</span>
|
|
381
381
|
${y>0?`<span class="text-[10px] mt-0.5 opacity-80 font-medium whitespace-nowrap">${y}s</span>`:""}
|
|
382
|
-
</div>`}).join("")
|
|
382
|
+
</div>`}).join(""),$p(e),Kr()}function $p(e){let t=i("selected-day-title"),n=i("selected-day-sessions");if(!t||!n)return;let[s,a,o]=Us.split("-").map(Number),r=new Date(s,a-1,o);t.textContent=`Activity on ${r.toLocaleDateString([],{weekday:"short",month:"short",day:"numeric",year:"numeric"})}`,e=Gr(e);let c=pc(r,e),u=c.reduce((f,m)=>f+(Number(m.totalTokens)||0),0),d=i("stats-selected-tokens");if(d&&(d.textContent=fc(u)),!c.length){n.innerHTML='<div class="text-center text-xs text-base-content/40 my-auto py-6">No sessions active on this day</div>';return}c.sort((f,m)=>(O(m.updatedAt)||0)-(O(f.updatedAt)||0)),n.innerHTML=c.map(f=>{let m=O(f.updatedAt),g=m!=null?new Date(m).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):"";return`
|
|
383
383
|
<div class="flex items-center gap-2.5 p-2.5 rounded-lg bg-base-300/40 hover:bg-base-300 border border-base-300/50 cursor-pointer text-left transition-all ${l.sessionId===f.sessionId?"border-primary bg-primary/5":""}"
|
|
384
384
|
data-session-id="${p(f.sessionId)}"
|
|
385
385
|
data-session-cwd="${p(f.cwd||"")}"
|
|
386
386
|
data-session-config-dir="${p(f.configDir||"")}"
|
|
387
387
|
data-session-agent="${p(f.agent||"claude")}"
|
|
388
388
|
data-session-machine="${p(f.machineId||"")}">
|
|
389
|
-
<div class="flex-shrink-0">${
|
|
389
|
+
<div class="flex-shrink-0">${On(f.agent)}</div>
|
|
390
390
|
<div class="flex-1 min-w-0">
|
|
391
391
|
<div class="text-xs font-semibold truncate text-base-content/90">${p(vt(f))}</div>
|
|
392
|
-
<div class="text-[10px] text-base-content/40 truncate mt-0.5">${p(f.projectName||
|
|
392
|
+
<div class="text-[10px] text-base-content/40 truncate mt-0.5">${p(f.projectName||Un(f.cwd)||"No workspace")}</div>
|
|
393
393
|
</div>
|
|
394
394
|
<div class="text-[9px] text-base-content/45 font-mono whitespace-nowrap bg-base-300 px-1.5 py-0.5 rounded">${g}</div>
|
|
395
|
-
</div>`}).join("")}function
|
|
395
|
+
</div>`}).join("")}function eo(e){return`${e.machineId||""}:${e.agent||"claude"}:${e.sessionId}`}function zr(){try{let e=JSON.parse(localStorage.getItem(hc)||"[]");return Array.isArray(e)?e.filter(t=>t&&t.sessionId):[]}catch{return[]}}function gc(e){try{localStorage.setItem(hc,JSON.stringify(e))}catch{}}function bc(e){if(!e?.sessionId)return;let t=eo(e),n={...e,lastOpenedAt:Date.now()},s=zr().filter(a=>eo(a)!==t);s.unshift(n),gc(s.slice(0,mc)),Kr(),Qr()}function vc(e){if(!e?.sessionId)return;let t=eo(e);gc(zr().filter(n=>eo(n)!==t)),Kr(),Qr()}function xc(e){return zr().sort((t,n)=>(O(n.lastOpenedAt)||0)-(O(t.lastOpenedAt)||0)).slice(0,e)}function Kr(){let e=i("recent-sessions-list");if(!e)return;let t=xc(6);if(!t.length){e.innerHTML='<div class="col-span-full text-center text-xs text-base-content/40 py-4">No recent sessions</div>';return}e.innerHTML=t.map(n=>{let s=Bn(n.updatedAt);return`
|
|
396
396
|
<div class="flex items-center gap-2.5 p-3 rounded-xl bg-base-200 hover:bg-base-300 border border-base-300/80 cursor-pointer text-left transition-all ${l.sessionId===n.sessionId?"border-primary bg-primary/5":""}"
|
|
397
397
|
data-session-id="${p(n.sessionId)}"
|
|
398
398
|
data-session-cwd="${p(n.cwd||"")}"
|
|
399
399
|
data-session-config-dir="${p(n.configDir||"")}"
|
|
400
400
|
data-session-agent="${p(n.agent||"claude")}"
|
|
401
401
|
data-session-machine="${p(n.machineId||"")}">
|
|
402
|
-
<div class="flex-shrink-0">${
|
|
402
|
+
<div class="flex-shrink-0">${On(n.agent)}</div>
|
|
403
403
|
<div class="flex-1 min-w-0">
|
|
404
404
|
<div class="text-xs font-bold truncate text-base-content/95">${p(vt(n))}</div>
|
|
405
|
-
<div class="text-[10px] text-base-content/40 truncate mt-1">${p(n.projectName||
|
|
405
|
+
<div class="text-[10px] text-base-content/40 truncate mt-1">${p(n.projectName||Un(n.cwd)||"No workspace")}</div>
|
|
406
406
|
</div>
|
|
407
407
|
<div class="text-[9px] text-base-content/40 whitespace-nowrap self-start mt-0.5">${s}</div>
|
|
408
|
-
</div>`}).join("")}function
|
|
408
|
+
</div>`}).join("")}function $n(){let e=i("recent-menu");e&&(e.classList.add("hidden"),e.classList.remove("recent-menu-open"),e.style.top="",e.style.left="",e.style.right="",e.style.width="",e.style.maxHeight=""),i("recent-menu-backdrop")?.classList.add("hidden")}function Jr(){let e=i("recent-menu"),t=i("topbar");if(!e||!t)return;let n=t.getBoundingClientRect(),a=Math.round(n.bottom+6),o=window.matchMedia("(max-width: 640px)").matches?8:null;if(e.style.top=`${a}px`,o!=null)e.style.left=`${o}px`,e.style.right=`${o}px`;else{let u=i("btn-recent-sessions")?.getBoundingClientRect();if(u){let d=Math.min(320,window.innerWidth-16),f=u.left;f+d>window.innerWidth-8&&(f=window.innerWidth-d-8),f<8&&(f=8),e.style.left=`${Math.round(f)}px`,e.style.right="auto",e.style.width=`${d}px`}}let r=Math.max(160,window.innerHeight-a-12);e.style.maxHeight=`${Math.min(r,Math.round(window.innerHeight*.7))}px`}function Sp(){let e=i("recent-menu");e&&(Qr(),e.classList.remove("hidden"),e.classList.add("recent-menu-open"),Jr(),i("recent-menu-backdrop")?.classList.remove("hidden"))}function yc(){let e=i("recent-menu");e&&(e.classList.contains("hidden")?Sp():$n())}function Qr(){let e=i("recent-menu-list"),t=i("recent-menu-empty"),n=i("recent-menu-count");if(!e)return;let s=xc(mc);if(n&&(n.textContent=s.length?`${s.length}`:""),!s.length){e.innerHTML="",t?.classList.remove("hidden");return}t?.classList.add("hidden"),e.innerHTML=s.map(a=>{let o=Bn(a.updatedAt),r=l.sessionId===a.sessionId&&(!a.machineId||!l.machineId||a.machineId===l.machineId),c=a.machineId?`<span class="text-[9px] font-mono text-base-content/35 truncate max-w-[4.5rem]" title="${p(a.machineId)}">@${p(a.machineId)}</span>`:"";return`
|
|
409
409
|
<div class="recent-menu-item w-full text-left px-2 py-1.5 rounded-md flex items-start gap-2
|
|
410
410
|
${r?"bg-primary/15 text-primary":"hover:bg-base-200"}">
|
|
411
411
|
<button type="button" class="flex min-w-0 flex-1 items-start gap-2 text-left" aria-label="\u6253\u5F00 ${p(vt(a))}"
|
|
@@ -414,14 +414,14 @@ ${t}`:"",n.length?n.join(`
|
|
|
414
414
|
data-session-config-dir="${p(a.configDir||"")}"
|
|
415
415
|
data-session-agent="${p(a.agent||"claude")}"
|
|
416
416
|
data-session-machine="${p(a.machineId||"")}">
|
|
417
|
-
<span class="flex-shrink-0 mt-0.5">${
|
|
417
|
+
<span class="flex-shrink-0 mt-0.5">${On(a.agent)}</span>
|
|
418
418
|
<span class="flex-1 min-w-0">
|
|
419
419
|
<span class="block text-xs font-semibold truncate leading-snug">${p(vt(a))}</span>
|
|
420
|
-
<span class="block text-[10px] text-base-content/40 truncate mt-0.5">${p(a.projectName||
|
|
420
|
+
<span class="block text-[10px] text-base-content/40 truncate mt-0.5">${p(a.projectName||Un(a.cwd)||"\u2014")}</span>
|
|
421
421
|
</span>
|
|
422
422
|
<span class="flex flex-col items-end gap-0.5 flex-shrink-0 self-start">
|
|
423
423
|
<span class="text-[9px] text-base-content/40 whitespace-nowrap">${p(o)}</span>
|
|
424
|
-
${
|
|
424
|
+
${c}
|
|
425
425
|
${r?'<span class="text-[9px] opacity-70">\u5F53\u524D</span>':""}
|
|
426
426
|
</span>
|
|
427
427
|
</button>
|
|
@@ -430,9 +430,9 @@ ${t}`:"",n.length?n.join(`
|
|
|
430
430
|
data-dismiss-recent-session="${p(a.sessionId)}"
|
|
431
431
|
data-dismiss-recent-agent="${p(a.agent||"claude")}"
|
|
432
432
|
data-dismiss-recent-machine="${p(a.machineId||"")}">\xD7</button>
|
|
433
|
-
</div>`}).join("")}function
|
|
434
|
-
(original: ${e.display||e.sessionId})`:e.display||"",
|
|
435
|
-
${n?"border-primary bg-primary/5":"border-transparent"} ${r?"session-fav":""} ${
|
|
433
|
+
</div>`}).join("")}function wc(e){Us=e}function Vr(e){yn+=e,yn<0?(yn=11,Za--):yn>11&&(yn=0,Za++)}var Za,yn,Us,mc,hc,Yr=B(()=>{G();W();Nt();Za=new Date().getFullYear(),yn=new Date().getMonth(),Us=null;mc=15,hc="recentSessionsV1"});var lo={};us(lo,{loadAgentsMeta:()=>as,loadAllSessions:()=>We,loadMemoryTab:()=>io,loadWorkspaces:()=>ss,markActiveSessionRow:()=>Lp,mdToHtml:()=>Cc,openMemoryFile:()=>ni,promptCustomModel:()=>ao,refreshEffortSelect:()=>so,refreshModelSelect:()=>et,renderProjectGroups:()=>Ic,renderSessionList:()=>ti,renderTimeline:()=>Tc,runActivitySearch:()=>oo,scheduleActivitySearch:()=>ro,sessionItemHtml:()=>ei,syncSidebarChrome:()=>Fs});function kc(e){return!Array.isArray(e)||!e.length?"":e.map(t=>`${t.sessionId}:${t.updatedAt||0}:${t.turnCount||0}:${t.agent||""}`).join("|")}function Lp(e,t){let n=t||"claude";document.querySelectorAll("#session-list .session-row").forEach(s=>{let a=s.dataset.sessionId===e&&(s.dataset.sessionAgent||"claude")===n;s.classList.toggle("border-primary",a),s.classList.toggle("bg-primary/5",a),s.classList.toggle("border-transparent",!a);let o=s.querySelector(".session-title-text");o&&(o.classList.toggle("text-primary",a),o.classList.toggle("font-medium",a),o.classList.toggle("text-base-content/85",!a))})}function $c(e){return Array.isArray(e)?e:e&&Array.isArray(e.results)?e.results:e&&Array.isArray(e.sessions)?e.sessions:[]}function Ep(e,t){return e?.parentSessionId?J(e.parentAgent||t.agent,e.parentSessionId,e.parentMachineId??t.machineId):""}function Ip(e){let t=Array.isArray(e)?e:[],n=new Map(t.map(u=>[J(u.agent,u.sessionId,u.machineId),u])),s=new Map,a=[];for(let u of t){let d=T.peek()?.[J(u.agent,u.sessionId,u.machineId)]?.branch,f=Ep(d,u);if(f&&n.has(f)&&f!==J(u.agent,u.sessionId,u.machineId)){let m=s.get(f)||[];m.push(u),s.set(f,m)}else a.push(u)}let o=(u,d)=>(d.updatedAt||0)-(u.updatedAt||0);a.sort(o);for(let u of s.values())u.sort(o);let r=[],c=(u,d,f=new Set)=>{let m=J(u.agent,u.sessionId,u.machineId);if(!f.has(m)){f.add(m),r.push(d?{...u,_branchDepth:d}:u);for(let g of s.get(m)||[])c(g,d+1,f)}};for(let u of a)c(u,0);return r}async function Tp(){if(!Xr){Xr=!0;try{no++,await We()}finally{Xr=!1}}}function Cp({hubIndex:e=!1,offset:t=0}={}){let n=new URLSearchParams;n.set("limit",String(to)),t&&n.set("offset",String(t)),(M.peek()||e)&&n.set("index","1");let s=n.toString();return s?`/api/sessions?${s}`:"/api/sessions"}async function We({waitFresh:e=!0,hubIndex:t=!1}={}){let n=j.peek()||null;n!==Sc&&(Sc=n,no=1);let s=++Lc,a=$c(await Fa()).slice(0,to*no);if(a.length){let r=j.peek();if(M.peek()&&r){let c=a.filter(u=>!u.machineId||u.machineId===r);ne.value=c.length?c:a}else ne.value=a}let o=async()=>{let r=[];for(let u=0;u<no;u++){let d=Cp({hubIndex:t,offset:u*to}),f=await x("GET",d,void 0,void 0,{machineId:n||void 0});if(s!==Lc)return ne.peek();let m=$c(f);if(r.push(...m),Zr=m.length===to,!Zr)break}let c=new Map(r.map(u=>[`${u.machineId||""}:${u.agent}:${u.sessionId}`,u]));return r.splice(0,r.length,...c.values()),kc(r)!==kc(ne.peek())&&(ne.value=r,Nl(r)),r};if(e||!a.length)try{await o()}catch(r){if(!a.length){let c=i("session-list");c&&(c.innerHTML=`<div class="px-3 py-3 text-xs text-error">${p(r.message)}</div>`)}}else o().catch(()=>{})}async function ss({waitFresh:e=!0}={}){let t=await Pl();t&&(fe.value=t);let n=async()=>{let s=await x("GET","/api/workspaces");fe.value=s,Ds(s)};if(e||!t)try{await n()}catch{}else n().catch(()=>{})}function ei(e,{showProject:t=!1}={}){let n=l.sessionId===e.sessionId&&(l.agent||$.peek())===(e.agent||"claude"),s=T.peek()?.[J(e.agent,e.sessionId,e.machineId)]||{},a=!!(s.title&&String(s.title).trim()),o=e.snippet&&$e.peek()?e.snippet:vt(e),r=!!s.favorite,c=!!s.hidden,u=!!(s.notes&&String(s.notes).trim()),d=s.branch?.parentSessionId?s.branch:null,f=Math.max(0,Math.min(4,Number(e._branchDepth)||0)),m=Number(e.turnCount)||0,g=m>0&&m<=Yo,w=t?`<div class="text-[10px] text-base-content/40 font-mono truncate" title="${p(e.cwd||"")}">${p(e.projectName||Un(e.cwd)||"\u2014")}</div>`:"",y=[g?`<span class="session-thin-badge" title="Only ${m} turn${m===1?"":"s"}">thin\xB7${m}</span>`:"",a?`<span class="session-renamed-badge" title="Custom name (original: ${p(e.display||"")})">renamed</span>`:"",c?'<span class="session-hidden-badge" title="Hidden">hidden</span>':"",u?`<span class="session-note-dot" title="${p(s.notes)}">\u{1F4DD}</span>`:"",d?`<span class="session-branch-badge" title="Forked from ${p(d.parentAgent||e.agent)}:${p(d.parentSessionId)}">\u2387 fork</span>`:""].filter(Boolean).join(""),P=e.machineId?`<span class="text-[9px] px-1 py-0.5 rounded bg-base-300 text-base-content/50 font-mono flex-shrink-0" title="Machine">${p(e.machineId)}</span>`:"",ae=a?`${o}
|
|
434
|
+
(original: ${e.display||e.sessionId})`:e.display||"",K=d?`<div class="session-branch-line" title="Forked from ${p(d.parentAgent||e.agent)} \xB7 ${p(d.parentSessionId)}">\u21B3 ${p(d.parentAgent||e.agent)} \xB7 ${p(d.parentSessionId.slice(0,8))}</div>`:"";return`<div class="session-row ${f?"session-branch":""} px-2.5 py-1.5 cursor-pointer hover:bg-base-300 border-l-2
|
|
435
|
+
${n?"border-primary bg-primary/5":"border-transparent"} ${r?"session-fav":""} ${c?"session-hidden-row":""} ${g?"session-thin":""}"
|
|
436
436
|
style="--branch-depth:${f}"
|
|
437
437
|
data-session-id="${p(e.sessionId)}"
|
|
438
438
|
data-session-cwd="${p(e.cwd||"")}"
|
|
@@ -447,7 +447,7 @@ ${t}`:"",n.length?n.join(`
|
|
|
447
447
|
data-fav-session-agent="${p(e.agent||"claude")}"
|
|
448
448
|
data-fav-session-machine="${p(e.machineId||"")}"
|
|
449
449
|
title="${r?"Unfavorite":"Favorite"}">${r?"\u2605":"\u2606"}</button>
|
|
450
|
-
${
|
|
450
|
+
${On(e.agent)}
|
|
451
451
|
<div class="min-w-0 flex-1">
|
|
452
452
|
<div class="session-title-wrap flex items-center gap-1 min-w-0"
|
|
453
453
|
data-rename-session-id="${p(e.sessionId)}"
|
|
@@ -459,39 +459,39 @@ ${t}`:"",n.length?n.join(`
|
|
|
459
459
|
<button type="button" class="session-rename-btn flex-shrink-0"
|
|
460
460
|
data-rename-session="1"
|
|
461
461
|
title="Rename session">\u270E</button>
|
|
462
|
-
<button type="button" class="session-hide-btn flex-shrink-0 ${
|
|
462
|
+
<button type="button" class="session-hide-btn flex-shrink-0 ${c?"is-hidden":""}"
|
|
463
463
|
data-hide-toggle="1"
|
|
464
464
|
data-hide-session-id="${p(e.sessionId)}"
|
|
465
465
|
data-hide-session-agent="${p(e.agent||"claude")}"
|
|
466
466
|
data-hide-session-machine="${p(e.machineId||"")}"
|
|
467
|
-
title="${
|
|
467
|
+
title="${c?"Unhide session":"Hide session"}">${c?"\u{1F441}":"\u{1F648}"}</button>
|
|
468
468
|
</div>
|
|
469
469
|
${w}
|
|
470
|
-
${
|
|
471
|
-
${y||
|
|
470
|
+
${K}
|
|
471
|
+
${y||P?`<div class="flex items-center gap-1 mt-0.5 flex-wrap">${P}${y}</div>`:""}
|
|
472
472
|
</div>
|
|
473
|
-
<span class="text-[9px] text-base-content/30 flex-shrink-0 mt-0.5">${
|
|
473
|
+
<span class="text-[9px] text-base-content/30 flex-shrink-0 mt-0.5">${Bn(e.updatedAt)}</span>
|
|
474
474
|
</div>
|
|
475
|
-
</div>`}async function
|
|
475
|
+
</div>`}async function as(){try{let e=await x("GET","/api/agents");return Vt.value=e,et(),e}catch(e){return console.warn("[agents] failed to load model list",e),null}}function so(){let e=i("sel-effort");if(!e)return;let t=$.peek()||"claude",n=_.peek(),s=Zt(t,n),a=te.peek()||"";if(!a){let r=Qe(t,n);r&&s.includes(r)&&(a=r,te.value=r)}let o=['<option value="">effort: off</option>'].concat(s.map(r=>`<option value="${p(r)}" ${r===a?"selected":""}>${p(r)}</option>`));if(e.innerHTML=o.join(""),a&&!s.includes(a)){let r=Qe(t,n);r&&s.includes(r)?(te.value=r,e.value=r):(te.value="",e.value="")}else e.value=a}function et(){let e=i("sel-model");if(!e)return;let t=$.peek()||"claude",n=Be(t),s=_.peek();if(s&&!n.some(o=>o.value===s)&&(n=[{value:s,label:`${s} \u2605`,custom:!0},...n]),e.innerHTML=n.map(o=>`<option value="${p(o.value)}" ${o.value===s?"selected":""}>${p(o.label)}</option>`).join(""),n.some(o=>o.value===s))e.value=s;else{let o=Oe(t)||n[0]?.value;se(o),e.value=o,s=o}let a=i("sel-agent");a&&(a.value=t),so()}function ao({editCurrent:e=!1}={}){let t=$.peek()||"claude",n=e&&_.peek()||"",s=e?`Edit model id for ${t}:`:`Add model id for ${t} (saved in this browser):`,a=window.prompt(s,n);if(a==null)return;let o=a.trim();o&&(e&&n&&n!==o&&ua(t).includes(n)&&er(t,n),Xt(t,o),se(o),et())}function Ic(e){if(!Array.isArray(e)||!e.length)return`<div class="px-3 py-6 text-center text-xs text-base-content/40">
|
|
476
476
|
No projects in this range.<br>
|
|
477
477
|
<span class="text-base-content/30">Try \u201CAll\u201D time or another agent.</span>
|
|
478
|
-
</div>`;let t=jn.value,n=
|
|
478
|
+
</div>`;let t=jn.value,n=_n.value,s=!!$e.value.trim(),a=e[0]?.cwd||"(no path)";return e.map(o=>{let r=o.cwd||"(no path)",c=!1;n.has(r)?c=!1:t.has(r)?c=!0:c=s||r===a||e.length<=3;let u=o.machineId?`<span class="text-[9px] font-mono text-base-content/40 flex-shrink-0">@${p(o.machineId)}</span>`:"",d=`
|
|
479
479
|
<div class="project-header px-2.5 py-2 cursor-pointer hover:bg-base-300/80 select-none border-b border-base-300/40"
|
|
480
480
|
data-folder="${p(r)}" data-project-cwd="${p(o.cwd||"")}" data-project-machine="${p(o.machineId||"")}">
|
|
481
481
|
<div class="flex items-center gap-1.5">
|
|
482
|
-
<span class="text-[10px] text-base-content/40 w-3 flex-shrink-0">${
|
|
482
|
+
<span class="text-[10px] text-base-content/40 w-3 flex-shrink-0">${c?"\u25BE":"\u25B8"}</span>
|
|
483
483
|
<span class="text-[12px] font-semibold truncate flex-1" title="${p(o.cwd||"")}">${p(o.projectName)}</span>
|
|
484
484
|
${u}
|
|
485
|
-
<span class="text-[9px] text-base-content/30 flex-shrink-0">${
|
|
485
|
+
<span class="text-[9px] text-base-content/30 flex-shrink-0">${Bn(o.updatedAt)}</span>
|
|
486
486
|
</div>
|
|
487
|
-
</div>`,m=
|
|
487
|
+
</div>`,m=Ip(o.sessions).slice(0,40),g=o.sessions.length>40?`<div class="px-3 py-1 text-[10px] text-base-content/30">+${o.sessions.length-40} more</div>`:"",w=c?`<div class="pb-1 border-b border-base-300/30">${m.map(y=>ei(y)).join("")}${g}</div>`:"";return d+w}).join("")}function Tc(e){if(!Array.isArray(e)||!e.length)return`<div class="px-3 py-6 text-center text-xs text-base-content/40">
|
|
488
488
|
No recent activity.<br>
|
|
489
489
|
<span class="text-base-content/30">Widen the time range or clear filters.</span>
|
|
490
490
|
</div>`;let t=new Map;for(let n of e){let a=(n.updatedAt?new Date(n.updatedAt):new Date).toLocaleDateString(void 0,{weekday:"short",month:"short",day:"numeric"});t.has(a)||t.set(a,[]),t.get(a).push(n)}return[...t.entries()].map(([n,s])=>`
|
|
491
491
|
<div class="px-2.5 pt-2.5 pb-1 text-[10px] uppercase tracking-wide text-base-content/35 font-medium sticky top-0 bg-base-200/95 backdrop-blur-sm z-[1]">${p(n)}</div>
|
|
492
|
-
${s.map(a=>
|
|
493
|
-
`).join("")}function
|
|
494
|
-
<div class="px-3 pb-4 flex flex-col gap-1">${a.map(o=>`<button type="button" class="memory-file text-left px-3 py-2 rounded-lg border border-base-300 hover:border-primary hover:bg-primary/5" data-memory-file="${p(o.id)}" data-memory-agent="${p(t)}"><span class="font-mono text-xs">${p(o.name)}</span><span class="ml-2 text-[10px] text-base-content/40">${p(o.scope||"")}</span></button>`).join("")}<div id="memory-file-content"></div></div>`}catch(t){e.innerHTML=`<div class="p-4 text-error text-xs">${p(t?.message??String(t))}</div>`}}}async function
|
|
492
|
+
${s.map(a=>ei(a,{showProject:!0})).join("")}
|
|
493
|
+
`).join("")}function ti(){let e=gt.value,t=Array.isArray(_t.value)?_t.value:[],n=Array.isArray(en.value)?en.value:[];return(e==="timeline"?Tc(t):Ic(n))+(Zr?'<button class="btn btn-sm btn-ghost w-full" data-load-more-sessions>\u52A0\u8F7D\u66F4\u591A\u4F1A\u8BDD</button>':"")}function Fs(){document.querySelectorAll("[data-view]").forEach(o=>{let r=o.dataset.view===gt.peek();o.classList.toggle("bg-primary/15",r),o.classList.toggle("text-primary",r),o.classList.toggle("font-medium",r),o.classList.toggle("text-base-content/50",!r)}),document.querySelectorAll("[data-agent-filter]").forEach(o=>{o.classList.toggle("active",o.dataset.agentFilter===ye.peek())});let e=i("time-range");e&&e.value!==da.peek()&&(e.value=da.peek());let t=i("search-status");if(!t)return;let n=rt.peek(),s=Array.isArray(n?.results)?n.results:null,a=($e.peek()||"").trim();if(bt.peek())t.classList.remove("hidden"),t.textContent="Searching content\u2026";else if(a&&s)t.classList.remove("hidden"),t.textContent=`${s.length} hit${s.length===1?"":"s"}${n.deep===!1?"":" (incl. content)"}`;else if(a)t.classList.remove("hidden"),t.textContent="Local filter only \u2014 type to deep-search";else{let o=_t.peek(),r=en.peek(),c=Array.isArray(o)?o.length:0,u=Array.isArray(r)?r.length:0;t.classList.remove("hidden"),t.textContent=gt.peek()==="projects"?`${u} project${u===1?"":"s"} \xB7 ${c} session${c===1?"":"s"}`:`${c} recent session${c===1?"":"s"}`}}async function oo(e){let t=(e||"").trim();if(!t){rt.value=null,bt.value=!1;return}bt.value=!0;try{let n=new URLSearchParams({q:t,days:"0",limit:"50",deep:"1"});ye.peek()&&ye.peek()!=="all"&&n.set("agent",ye.peek());let s=await x("GET",`/api/activity?${n}`);$e.peek().trim()===t&&(rt.value={q:t.toLowerCase(),results:s.results||[],deep:!0})}catch(n){$e.peek().trim()===t&&(rt.value={q:t.toLowerCase(),results:[],error:n.message})}finally{bt.value=!1}}function ro(e){clearTimeout(Ec);let t=(e||"").trim();if(!t){rt.value=null,bt.value=!1;return}Ec=setTimeout(()=>oo(t),350)}function Cc(e){if(!e)return"";if(typeof marked>"u")return`<pre class="whitespace-pre-wrap text-xs">${p(e)}</pre>`;try{return Ve(e,{fallback:t=>`<pre class="whitespace-pre-wrap text-xs">${p(t)}</pre>`})}catch{return`<pre class="whitespace-pre-wrap text-xs">${p(e)}</pre>`}}async function io(){let e=i("memory-area");if(e){if(!l.sessionId){e.innerHTML='<div class="p-4 text-xs text-base-content/40">Open or resume a session to view its memory.</div>';return}e.innerHTML='<div class="p-4 text-xs text-base-content/40">Loading\u2026</div>';try{let t=l.agent||$.peek()||"claude",n=new URLSearchParams({agent:t}),a=(await x("GET",`/api/sessions/${l.sessionId}/memory?${n}`)).files||[];if(!a.length){e.innerHTML='<div class="p-4 text-base-content/40 text-xs">No memory files available for this agent/session.</div>';return}e.innerHTML=`<div class="p-3 text-[11px] text-base-content/45">${p(t)} \xB7 ${a.length} memory file${a.length===1?"":"s"} \xB7 click to open</div>
|
|
494
|
+
<div class="px-3 pb-4 flex flex-col gap-1">${a.map(o=>`<button type="button" class="memory-file text-left px-3 py-2 rounded-lg border border-base-300 hover:border-primary hover:bg-primary/5" data-memory-file="${p(o.id)}" data-memory-agent="${p(t)}"><span class="font-mono text-xs">${p(o.name)}</span><span class="ml-2 text-[10px] text-base-content/40">${p(o.scope||"")}</span></button>`).join("")}<div id="memory-file-content"></div></div>`}catch(t){e.innerHTML=`<div class="p-4 text-error text-xs">${p(t?.message??String(t))}</div>`}}}async function ni(e,t){let n=i("memory-file-content");if(!(!n||!l.sessionId||!e)){n.innerHTML='<div class="p-3 text-xs text-base-content/40">Loading file\u2026</div>';try{let s=new URLSearchParams({agent:t||l.agent||$.peek()||"claude",file:e}),a=await x("GET",`/api/sessions/${l.sessionId}/memory/file?${s}`);n.innerHTML=`<div class="mt-2 border border-base-300 rounded-lg overflow-hidden"><div class="px-3 py-1.5 bg-base-300/50 text-xs font-mono">${p(a.name)}</div><div class="px-3 py-2 md">${Cc(a.content)}</div></div>`}catch(s){n.innerHTML=`<div class="mt-2 p-3 text-error text-xs">${p(s?.message??String(s))}</div>`}}}var to,no,Sc,Lc,Zr,Xr,Ec,Tt=B(()=>{G();W();ce();_s();Nt();an();to=200,no=1,Sc=null,Lc=0,Zr=!1,Xr=!1;document.addEventListener("click",e=>{e.target.closest?.("[data-load-more-sessions]")&&Tp().catch(console.warn)});Ec=null});function Mc(e,t){co=e||"",uo=t||""}async function Ac(e){let t=i("project-notes-bar");if(t)try{let n=await x("GET",`/api/projects/notes?root=${encodeURIComponent(e)}`);co=n.goal||"",uo=n.notes||"",os(),t.style.display="flex"}catch(n){console.error("Error fetching project notes:",n),t.style.display="none"}}function os(){let e=i("project-notes-bar");if(!e)return;let t=co||"No goal yet \u2014 click Edit",n=uo||"";e.innerHTML=`
|
|
495
495
|
<div class="flex items-start gap-2 w-full">
|
|
496
496
|
<div class="flex-1 min-w-0">
|
|
497
497
|
<div class="truncate">
|
|
@@ -502,31 +502,31 @@ ${t}`:"",n.length?n.join(`
|
|
|
502
502
|
</div>
|
|
503
503
|
<button id="btn-edit-project-notes" class="btn btn-ghost btn-xs px-1.5 hover:bg-base-300 flex-shrink-0">Edit</button>
|
|
504
504
|
</div>
|
|
505
|
-
`}function
|
|
505
|
+
`}function Dc(){let e=i("project-notes-bar");e&&(e.innerHTML=`
|
|
506
506
|
<div class="flex flex-col gap-1.5 w-full">
|
|
507
507
|
<div class="flex items-center gap-2">
|
|
508
508
|
<span class="text-[10px] font-bold text-base-content/40 uppercase w-12 flex-shrink-0">Goal</span>
|
|
509
509
|
<input id="project-goal-input" type="text" class="input input-xs input-bordered flex-1 text-xs"
|
|
510
|
-
placeholder="One-line project goal\u2026" value="${p(
|
|
510
|
+
placeholder="One-line project goal\u2026" value="${p(co)}">
|
|
511
511
|
</div>
|
|
512
512
|
<div class="flex items-start gap-2">
|
|
513
513
|
<span class="text-[10px] font-bold text-base-content/40 uppercase w-12 flex-shrink-0 mt-1">Notes</span>
|
|
514
514
|
<textarea id="project-notes-input" rows="2" class="textarea textarea-xs textarea-bordered flex-1 text-xs leading-snug"
|
|
515
|
-
placeholder="Longer project notes (stack, links, status\u2026)">${p(
|
|
515
|
+
placeholder="Longer project notes (stack, links, status\u2026)">${p(uo)}</textarea>
|
|
516
516
|
</div>
|
|
517
517
|
<div class="flex items-center gap-1 justify-end">
|
|
518
518
|
<button id="btn-save-project-notes" class="btn btn-primary btn-xs px-2">Save</button>
|
|
519
519
|
<button id="btn-cancel-project-notes" class="btn btn-ghost btn-xs px-2">Cancel</button>
|
|
520
520
|
</div>
|
|
521
521
|
</div>
|
|
522
|
-
`,i("project-goal-input")?.focus())}async function
|
|
522
|
+
`,i("project-goal-input")?.focus())}async function Ws(){try{let e=await x("GET","/api/sessions/meta");T.value=e||{}}catch(e){console.warn("session meta load failed",e)}}function tt(){let e=i("session-notes-bar");if(!e)return;let t=l.sessionId,n=l.agent||$.peek()||"claude";if(!t){e.style.display="none",e.innerHTML="";return}if(e.querySelector(".session-rename-input"))return;let s=Nn(n,t),a=(s.notes||"").trim(),o=!!s.favorite,r=!!s.hidden,c=s.branch?.parentSessionId?s.branch:null,d=(s.title||"").trim()||t.slice(0,8);e.style.display="flex",e.innerHTML=`
|
|
523
523
|
<div class="flex-1 min-w-0 flex items-center gap-2">
|
|
524
524
|
<button type="button" class="session-fav-btn ${o?"is-fav":""}" data-fav-toggle="1"
|
|
525
525
|
data-fav-session-id="${p(t)}" data-fav-session-agent="${p(n)}"
|
|
526
526
|
title="${o?"Unfavorite":"Favorite"}">${o?"\u2605":"\u2606"}</button>
|
|
527
527
|
<span id="session-title-display"
|
|
528
528
|
class="session-title-inline max-w-[40%] truncate font-semibold text-base-content/85"
|
|
529
|
-
title="${p(
|
|
529
|
+
title="${p(d)}">${p(d)}</span>
|
|
530
530
|
<button type="button" class="session-rename-btn flex-shrink-0 opacity-70 hover:opacity-100"
|
|
531
531
|
data-rename-bar="1" title="Rename session">\u270E</button>
|
|
532
532
|
<div class="session-title-actions flex items-center gap-0.5 flex-shrink-0">
|
|
@@ -542,15 +542,15 @@ ${t}`:"",n.length?n.join(`
|
|
|
542
542
|
<span class="font-bold text-base-content/40 uppercase flex-shrink-0">Note:</span>
|
|
543
543
|
<span class="truncate text-base-content/70 ${a?"":"italic text-base-content/40"}"
|
|
544
544
|
id="session-notes-text" title="${p(a||"Add a note for this session")}">${p(a||"No session note")}</span>
|
|
545
|
-
${
|
|
545
|
+
${c?`<span class="session-branch-current" title="Forked from ${p(c.parentAgent||n)} \xB7 ${p(c.parentSessionId)}">\u2387 from ${p(c.parentSessionId.slice(0,8))}</span>`:""}
|
|
546
546
|
</div>
|
|
547
547
|
<button id="btn-edit-session-notes" class="btn btn-ghost btn-xs px-1.5">Note</button>
|
|
548
|
-
`}function
|
|
548
|
+
`}function jc(){let e=i("session-notes-bar");if(!e||!l.sessionId)return;let t=l.agent||$.peek()||"claude",n=Nn(t,l.sessionId);e.innerHTML=`
|
|
549
549
|
<input id="session-notes-input" type="text" class="input input-xs input-bordered flex-1 text-xs"
|
|
550
550
|
placeholder="Note for this session\u2026" value="${p(n.notes||"")}">
|
|
551
551
|
<button id="btn-save-session-notes" class="btn btn-primary btn-xs px-2">Save</button>
|
|
552
552
|
<button id="btn-cancel-session-notes" class="btn btn-ghost btn-xs px-2">Cancel</button>
|
|
553
|
-
`;let s=i("session-notes-input");s?.focus(),s?.select()}function
|
|
553
|
+
`;let s=i("session-notes-input");s?.focus(),s?.select()}function po(){return{favorite:!1,notes:"",title:"",hidden:!1,branch:null}}function fo(e,t){return{favorite:t.favorite!==void 0?!!t.favorite:!!e.favorite,notes:t.notes!==void 0?String(t.notes||""):String(e.notes||""),title:t.title!==void 0?String(t.title||"").trim():String(e.title||"").trim(),hidden:t.hidden!==void 0?!!t.hidden:!!e.hidden,branch:t.branch!==void 0?t.branch||null:e.branch||null,updatedAt:Date.now()}}function _c(e){return!e?.favorite&&!e?.hidden&&!(e?.notes||"").trim()&&!(e?.title||"").trim()&&!e?.branch}async function Nc(e,t,{machineId:n}={}){let s=n||l.machineId||null,a=J(t,e,s),o=T.peek()?.[a]||po(),r=!o.favorite;T.value={...T.peek(),[a]:{...o,favorite:r,updatedAt:Date.now()}};try{let c=await x("PUT","/api/sessions/meta",{sessionId:e,agent:t,favorite:r,machineId:s||void 0},void 0,{machineId:s||void 0});T.value={...T.peek(),[a]:fo(o,{favorite:c.favorite??r,notes:c.notes,title:c.title,hidden:c.hidden})}}catch(c){T.value={...T.peek(),[a]:o},alert(`Favorite failed: ${c.message}`)}l.sessionId===e&&tt()}async function Pc(e,t,{machineId:n}={}){if(!e)return!1;let s=n||l.machineId||null,a=J(t,e,s),o=T.peek()?.[a]||po(),r=!o.hidden;T.value={...T.peek(),[a]:{...o,hidden:r,updatedAt:Date.now()}};try{let c=await x("PUT","/api/sessions/meta",{sessionId:e,agent:t,hidden:r,machineId:s||void 0},void 0,{machineId:s||void 0}),u=fo(o,{favorite:c.favorite,notes:c.notes,title:c.title,hidden:c.hidden??r});if(_c(u)){let d={...T.peek()};delete d[a],T.value=d}else T.value={...T.peek(),[a]:u}}catch(c){return T.value={...T.peek(),[a]:o},alert(`Hide failed: ${c.message}`),!1}return l.sessionId===e&&tt(),!0}async function si(e,t,n,{machineId:s}={}){let a=s||l.machineId||null,o=J(t,e,a),r=T.peek()?.[o]||po();try{let c=await x("PUT","/api/sessions/meta",{sessionId:e,agent:t,notes:n,machineId:a||void 0},void 0,{machineId:a||void 0});T.value={...T.peek(),[o]:fo(r,{favorite:c.favorite,notes:c.notes??n,title:c.title,hidden:c.hidden})}}catch(c){return alert(`Save note failed: ${c.message}`),!1}return!0}async function Mp(e,t,n,{machineId:s}={}){if(!e)return!1;let a=s||l.machineId||null,o=J(t,e,a),r=T.peek()?.[o]||po(),c=String(n||"").trim().slice(0,200);T.value={...T.peek(),[o]:{...r,title:c,updatedAt:Date.now()}};try{let u=await x("PUT","/api/sessions/meta",{sessionId:e,agent:t,title:c,machineId:a||void 0},void 0,{machineId:a||void 0}),d=fo(r,{favorite:u.favorite,notes:u.notes,title:u.title!==void 0?u.title:c,hidden:u.hidden});if(_c(d)){let f={...T.peek()};delete f[o],T.value=f}else T.value={...T.peek(),[o]:d}}catch(u){return T.value={...T.peek(),[o]:r},alert(`Rename failed: ${u.message}`),!1}return l.sessionId===e&&tt(),!0}function ai({sessionId:e,agent:t="claude",machineId:n=null,fallbackDisplay:s="",mountEl:a}={}){if(!e||!a)return;document.querySelectorAll(".session-rename-input").forEach(g=>{g.dispatchEvent(new CustomEvent("session-rename-cancel",{bubbles:!0}))});let r=(Nn(t,e,n).title||"").trim()||s||e.slice(0,8),c=a.innerHTML,u=a.className;a.classList.add("session-rename-active"),a.innerHTML=`<input type="text" class="session-rename-input input input-xs input-bordered w-full min-w-0 text-xs font-mono"
|
|
554
554
|
value="${p(r)}"
|
|
555
555
|
placeholder="Session name (empty = original)"
|
|
556
556
|
maxlength="200"
|
|
@@ -558,7 +558,7 @@ ${t}`:"",n.length?n.join(`
|
|
|
558
558
|
data-rename-session-id="${p(e)}"
|
|
559
559
|
data-rename-session-agent="${p(t)}"
|
|
560
560
|
data-rename-session-machine="${p(n||"")}"
|
|
561
|
-
autocomplete="off" spellcheck="false" />`;let
|
|
561
|
+
autocomplete="off" spellcheck="false" />`;let d=a.querySelector(".session-rename-input");if(!d)return;let f=!1,m=async g=>{if(f)return;f=!0;let w=g?d.value:r;if(a.className=u,!g){a.innerHTML=c;return}await Mp(e,t,w,{machineId:n}),document.querySelectorAll(".session-rename-input").forEach(y=>y.remove()),l.sessionId===e&&tt(),T.value={...T.peek()}};d.addEventListener("keydown",g=>{g.stopPropagation(),g.key==="Enter"?(g.preventDefault(),m(!0)):g.key==="Escape"&&(g.preventDefault(),m(!1))}),d.addEventListener("click",g=>g.stopPropagation()),d.addEventListener("mousedown",g=>g.stopPropagation()),d.addEventListener("session-rename-cancel",()=>m(!1)),d.addEventListener("blur",()=>{setTimeout(()=>m(!0),0)}),requestAnimationFrame(()=>{d.focus(),d.select()})}var co,uo,Gs=B(()=>{G();W();ce();co="",uo=""});var Rc={};us(Rc,{closeMachineMenu:()=>En,enterMachine:()=>ri,hideMachinePicker:()=>ho,refreshMachinesList:()=>Sn,renderMachineMenuList:()=>zs,renderMachinePickerList:()=>mo,showMachinePicker:()=>Ln,startMachinePolling:()=>oi,syncTopbarMachine:()=>Ot});async function Sn(){try{let e=await x("GET","/api/machines");le.value=Array.isArray(e)?e:[]}catch{try{let e=await ha();e?.machines&&(le.value=e.machines)}catch{}}return le.peek()||[]}function mo(){let e=i("machine-picker-list"),t=i("machine-picker-empty");if(!e)return;let n=le.peek()||[];if(!n.length){e.innerHTML="",t?.classList.remove("hidden");return}t?.classList.add("hidden"),e.innerHTML=n.map(s=>{let a=s.online!==!1,o=[s.hostname,s.platform].filter(Boolean).join(" \xB7 ");return`
|
|
562
562
|
<button type="button" class="machine-pick-card w-full text-left px-4 py-3 rounded-xl border border-base-300
|
|
563
563
|
hover:border-primary hover:bg-primary/5 transition-colors ${a?"":"opacity-50"}"
|
|
564
564
|
data-pick-machine="${p(s.id)}" ${a?"":"disabled"}>
|
|
@@ -567,7 +567,7 @@ ${t}`:"",n.length?n.join(`
|
|
|
567
567
|
<span class="font-semibold text-sm font-mono">${p(s.id)}</span>
|
|
568
568
|
</div>
|
|
569
569
|
${o?`<div class="text-xs text-base-content/45 mt-1 pl-4">${p(o)}</div>`:""}
|
|
570
|
-
</button>`}).join("")}function
|
|
570
|
+
</button>`}).join("")}function Ln(){let e=i("machine-picker");if(!e)return;e.classList.remove("hidden"),Ee(),it.value=!1,mo();let t=i("machine-picker-status");if(t){let n=(le.peek()||[]).filter(s=>s.online!==!1).length;t.textContent=`${n} online`}}function ho(){i("machine-picker")?.classList.add("hidden"),Ee(),it.value=!0}function En(){i("machine-menu")?.classList.add("hidden")}function zs(){let e=i("machine-menu-list"),t=i("machine-menu-empty");if(!e)return;let n=le.peek()||[],s=j.peek()||"";if(!n.length){e.innerHTML="",t?.classList.remove("hidden");return}t?.classList.add("hidden"),e.innerHTML=n.map(a=>{let o=a.online!==!1,r=a.id===s,c=[a.hostname,a.platform].filter(Boolean).join(" \xB7 "),u=a.connectedAt?new Date(a.connectedAt).toLocaleTimeString():"";return`
|
|
571
571
|
<button type="button"
|
|
572
572
|
class="machine-menu-item w-full text-left px-2 py-1.5 rounded-md text-xs
|
|
573
573
|
${r?"bg-primary/15 text-primary":"hover:bg-base-200"}
|
|
@@ -580,9 +580,9 @@ ${t}`:"",n.length?n.join(`
|
|
|
580
580
|
${r?'<span class="text-[9px] opacity-70">\u5F53\u524D</span>':""}
|
|
581
581
|
<span class="text-[9px] ${o?"text-success":"text-error"}">${o?"online":"offline"}</span>
|
|
582
582
|
</div>
|
|
583
|
-
${
|
|
584
|
-
</button>`}).join("")}function Ot(){let e=i("machine-menu-wrap"),t=i("topbar-machine-label"),n=i("topbar-machine-dot");if(!M.peek()){e?.classList.add("hidden");return}e?.classList.remove("hidden");let s=
|
|
585
|
-
`):String(D.content??"");
|
|
583
|
+
${c||u?`<div class="text-[10px] text-base-content/40 pl-3.5 mt-0.5 truncate">${p(c)}${u?" \xB7 "+p(u):""}</div>`:""}
|
|
584
|
+
</button>`}).join("")}function Ot(){let e=i("machine-menu-wrap"),t=i("topbar-machine-label"),n=i("topbar-machine-dot");if(!M.peek()){e?.classList.add("hidden");return}e?.classList.remove("hidden");let s=j.peek()||"",o=(le.peek()||[]).find(c=>c.id===s),r=o?o.online!==!1:!1;t&&(t.textContent=s||"\u9009\u62E9\u673A\u5668"),n&&(n.classList.toggle("bg-success",!!s&&r),n.classList.toggle("bg-warning",!!s&&!r),n.classList.toggle("bg-base-content/30",!s)),zs()}function oi(){Hc||(Hc=setInterval(async()=>{if(!M.peek()||!l.token)return;await Sn(),Ot();let e=j.peek();if(e){let t=(le.peek()||[]).find(n=>n.id===e);if(t&&t.online===!1){let n=i("topbar-machine-label");n&&(n.textContent=`${e} (offline)`)}}},15e3)),qc||(qc=setInterval(()=>{document.visibilityState!=="visible"||!M.peek()||!l.token||!j.peek()||We({waitFresh:!1,hubIndex:!0}).catch(()=>{})},2e3))}async function ri(e,{forceReload:t=!1}={}){if(!e)return;let n=j.peek(),s=n&&n!==e;if(Le(e),ho(),En(),Ot(),s||t){try{l.ws?.close()}catch{}l.ws=null,l.sessionId=null,xe(()=>{E.value=null,ke.value=null,re.value=null});try{let{filesRoot:o,gitRoot:r,filesPath:c}=await Promise.resolve().then(()=>(W(),Gi));o.value="",r.value="",c.value=""}catch{}if(s){let{goHome:o}=await Promise.resolve().then(()=>(rs(),ii));o()}}let a=i("topbar-project");a&&!E.peek()&&(a.textContent=`Machine \xB7 ${e}`),Bs(),await Promise.all([We(),ss(),Ws(),as().catch(()=>{})]),it.value=!0}var Hc,qc,Ks=B(()=>{G();W();ce();Tt();Gs();Os();Hn();Hc=null,qc=null});var ii={};us(ii,{goHome:()=>vo,openProject:()=>li,resumeSession:()=>nt,switchTab:()=>Ct});function bo(e){for(let t of["files-machine-hint","git-machine-hint"]){let n=i(t);n&&(e?(n.textContent=`@${e}`,n.classList.remove("hidden"),n.title=`Paths are on machine ${e}`):(n.textContent="",n.classList.add("hidden"),n.title=""))}}function li(e){Js=null,$a(),Ra(!1),Kn(),Qn(),Yn(),Vn();let t=e?.path||"";xe(()=>{E.value=e,ke.value=t,t&&(ie.value=t,Se.value=t,Y.value="",re.value=null)}),l.sessionId=null,i("topbar-project").textContent=t||"Project";let n=i("files-root-input");n&&t&&(n.value=t);let s=i("git-root-input");s&&t&&(s.value=t),bo(e?.machineId||j.peek()||l.machineId),i("welcome").classList.add("hidden");let a=i("project-view");a.classList.remove("hidden"),a.style.display="flex",Xn(),Jn({sessionId:null}),Ht(),Ct("chat")}function vo(){Js=null,$a(),Ra(!1),Kn(),Qn(),Yn(),Vn(),E.value=null,ke.value=null,ie.value="",Se.value="",Y.value="",re.value=null,l.sessionId=null,Jn({sessionId:null}),bo(null),document.documentElement.classList.remove("boot-restore");let e=i("topbar-project");e&&(e.textContent="Select a session"),Promise.resolve().then(()=>(Ps(),Rr)).then(({closeNotes:s})=>s({restore:!1})).catch(()=>{});let t=i("welcome");t&&(t.classList.remove("hidden"),t.style.display="",kn(wn()));let n=i("project-view");n&&(n.classList.add("hidden"),n.style.display="none"),Mr("/")}async function nt(e,t,n,s,a,o={}){let r=o.tab&&["chat","files","git","shell","memory"].includes(o.tab)?o.tab:"chat",c=o.skipHistory??(r!=="chat"&&r!=="memory"),u=ne.peek().find(L=>L.sessionId===e&&(!a||L.machineId===a||!L.machineId)),d=nn(),f=d?.sessionId===e?d:null,m=s||u?.agent||f?.agent||"claude",g=a||u?.machineId||f?.machineId||j.peek()||null,w=t||u?.cwd||f?.cwd||null,y=n||u?.configDir||f?.configDir||null;if(Promise.resolve().then(()=>(Ps(),Rr)).then(({closeNotes:L})=>L({restore:!1})).catch(()=>{}),Kn(),Qn(),Yn(),Vn(),g&&g!==l.machineId){Le(g);try{l.ws?.close()}catch{}l.ws=null,Promise.resolve().then(()=>(Ks(),Rc)).then(({syncTopbarMachine:L})=>L()).catch(()=>{}),Promise.resolve().then(()=>(Tt(),lo)).then(({loadAllSessions:L})=>L()).catch(()=>{})}l.sessionId=e,Ra(!1),wt({sessionId:e,agent:m,machineId:g}).catch(()=>{}),l.configDir=y,l.agent=m,Ne(m),et(),Jn({sessionId:e,agent:m,machineId:g});let P=w;Bc(P,g,e),P&&x("POST","/api/resolve-path",{path:P},void 0,{machineId:g||void 0}).then(L=>{l.sessionId!==e||!L?.path||L.path===P||(P=L.path,Bc(P,g,e),tr({sessionId:e,cwd:P}))}).catch(()=>{}),Xn(),Ht(),Ct(r),Promise.resolve().then(()=>(Tt(),lo)).then(({markActiveSessionRow:L})=>{L(e,m)}).catch(()=>{}),tr({sessionId:e,cwd:P||w,configDir:y,agent:m,machineId:g,tab:r}),bc({sessionId:e,cwd:P||w,configDir:y,agent:m,machineId:g,display:u?.display||f?.display||"",projectName:u?.projectName||f?.projectName||"",updatedAt:u?.updatedAt||f?.updatedAt||null});let ae=Z[m]||m,K=`${l.token||""}:${g||""}:${m}:${e}`,pe=0,q=0,Q=null,he=(L,ge,be={},oe=!1)=>{if(l.sessionId!==e||l.agent!==m||(l.machineId||null)!==g)return;let Kt=++pe,h=i("messages"),v=!!h.querySelector(".msg-row"),k=h.scrollTop,S=h.scrollHeight,U=!v||h.scrollHeight-h.scrollTop-h.clientHeight<80;if(Ll(),be.oldestIndex>0){let R=document.createElement("button");R.className="btn btn-sm btn-ghost",R.textContent="\u52A0\u8F7D\u66F4\u65E9\u7684\u6D88\u606F",R.onclick=async()=>{R.disabled=!0;try{let ve=new URLSearchParams({tail:"80",compact:"1",before:String(be.oldestIndex),agent:m});g&&ve.set("machine",g);let ze=await x("GET",`/api/sessions/${e}/messages?${ve}`,void 0,void 0,{machineId:g||void 0});if(Kt!==pe||l.sessionId!==e)return;let D=[...ze.messages,...L],de={...be,oldestIndex:ze.oldestIndex,truncated:ze.oldestIndex>0};Q={msgs:D,context:ge,meta:de},he(D,ge,de,!0)}catch(ve){R.disabled=!1,R.textContent=`\u52A0\u8F7D\u5931\u8D25\uFF0C\u70B9\u51FB\u91CD\u8BD5 (${ve.message})`}},i("messages").appendChild(R)}if(be.stale&&C("\u5F53\u524D\u663E\u793A\u79BB\u7EBF\u7F13\u5B58\uFF0C\u6B63\u5728\u7B49\u5F85\u673A\u5668\u6062\u590D\u8FDE\u63A5"),!L.length){C(`${ae} \xB7 ${e.slice(0,8)}\u2026 \u2014 no history`),Lr();return}pt();let F=40,A=0,V=()=>{if(l.sessionId!==e||Kt!==pe)return;let R=Math.min(A+F,L.length);for(;A<R;A++){let D=L[A],de=O(D.ts??D.timestamp),Jt=D.type||(D.role?"text":null);if(Jt==="text"||D.role&&D.content!=null&&!D.name){(D.role==="assistant"||D.role==="user")&&pt();let Cn=typeof D.content=="string"?D.content:Array.isArray(D.content)?D.content.map(jd=>jd?.text||"").filter(Boolean).join(`
|
|
585
|
+
`):String(D.content??"");Cn&&qt(D.role==="user"?"user":"assistant",D.role==="user"?"You":ae,Cn,{ts:de,historyIndex:(be.oldestIndex||0)+A})}else Jt==="tool_use"||D.name?Er({name:D.name||"tool",input:D.input??D.arguments??{}},{ts:de}):(Jt==="token_usage"||D.usage)&&(pt(),Gn(D.usage||D))}if(A<L.length){requestAnimationFrame(V);return}pt(),ge&&Sr(ge);let ve=L.filter(D=>D.type==="token_usage").length||L.filter(D=>D.role==="user").length,ze=be.truncated?` (showing last ${L.length} of ${be.total||"?"})`:"";C(`\u2500\u2500 ${ae} history \xB7 ${ve} turn${ve!==1?"s":""}${ze} \u2500\u2500`),Lr(oe?k+h.scrollHeight-S:U?null:k)};V()},Ae=async({preferCache:L=!0}={})=>{let ge=++q,be=Ut.get(K)||(L?await Hl(K):null);if(!(ge!==q||l.sessionId!==e)){if(L&&be&&be.msgs?.length){let oe=js(be);he(oe.msgs,oe.context,oe.meta)}be?.msgs?.length||C(`Loading ${ae} history\u2026`);try{let oe=g||j.peek()||l.machineId||null;if(M.peek()&&!oe)throw new Error("\u672A\u9009\u62E9\u673A\u5668\uFF0C\u65E0\u6CD5\u52A0\u8F7D\u5386\u53F2");oe&&l.machineId!==oe&&Le(oe);let Kt=async F=>{let A=new URLSearchParams({tail:"80",compact:"1"});return F&&A.set("agent",F),oe&&A.set("machine",oe),x("GET",`/api/sessions/${e}/messages?${A}`,void 0,void 0,{machineId:oe||void 0,dedupe:!1,cache:"no-store"})},h=kr(),v=await Kt(m);if(ge!==q||l.sessionId!==e)return;let k=Array.isArray(v)?v:v?.messages||[];!k.length&&m&&(v=await Kt(null),k=Array.isArray(v)?v:v?.messages||[]);let S=Array.isArray(v)?null:v?.context||null;if(ge!==q||l.sessionId!==e)return;let U=Array.isArray(v)?{}:{truncated:v?.truncated,total:v?.total,oldestIndex:v?.oldestIndex||0,stale:v?.stale};if(Q&&U.oldestIndex>Q.meta.oldestIndex&&Q.meta.oldestIndex>0){let F=U.oldestIndex-Q.meta.oldestIndex;F<=Q.msgs.length&&(k=[...Q.msgs.slice(0,F),...k],U.oldestIndex=Q.meta.oldestIndex)}if(Q={msgs:k,context:S,meta:U},k.length&&!U.stale){let F={msgs:k,context:S,meta:U,at:Date.now()};for(Ut.delete(K),Ut.set(K,js(F));Ut.size>24;)Ut.delete(Ut.keys().next().value);ql(K,F).catch(()=>{})}else Ut.delete(K);if(h!==kr()||i("messages")?.querySelector(".live-stream"))return;he(k,S,U)}catch(oe){if(l.sessionId!==e||ge!==q)return;Ut.delete(K),C(`${ae} \xB7 ${e.slice(0,8)}\u2026 (history unavailable: ${oe.message})`)}}};Js={sessionId:e,agent:m,refresh:()=>Ae({preferCache:!1}).catch(()=>{})},c?Ae().catch(()=>{}):(await new Promise(L=>requestAnimationFrame(L)),Ae().catch(()=>{})),As(),tt()}function Bc(e,t,n){if(e){let s=e.split("/").filter(Boolean).pop()||e;xe(()=>{E.value={id:s,name:s,path:e,machineId:t},ke.value=e,ie.value=e,Se.value=e,Y.value="",re.value=null}),i("topbar-project").textContent=t?`${e} @${t}`:e;let a=i("files-root-input");a&&(a.value=e);let o=i("git-root-input");o&&(o.value=e),bo(t),i("welcome")?.classList.add("hidden");let r=i("project-view");r&&(r.classList.remove("hidden"),r.style.display="flex",r.style.flexDirection="column",r.style.flex="1",r.style.minHeight="0",r.style.overflow="hidden")}else{i("welcome")?.classList.add("hidden");let s=i("project-view");s&&(s.classList.remove("hidden"),s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),bo(t)}}function Ct(e){X.value=e}var Js,go,Ut,rs=B(()=>{G();W();ce();_s();ba();Ba();ys();Oa();Tt();Gs();Yr();Js=null,go=null;document.addEventListener("external-session-updated",({detail:e})=>{let t=Js;!t||!e||e.sessionId!==t.sessionId||e.agent&&t.agent&&e.agent!==t.agent||(go&&clearTimeout(go),go=setTimeout(()=>{go=null,Js?.refresh()},140))});Ut=new Map});W();W();G();var im=ca({cache:!1,dedupe:!0,retry:0});async function zi(){try{let e=await fetch("/api/hub");if(!e.ok)return M.value=!1,!1;let t=await e.json();if(t?.hub)return M.value=!0,t}catch{}return M.value=!1,!1}G();W();ce();var ga=null;async function Ji(){if(!ga)return!1;ga.prompt();let e=await ga.userChoice.catch(()=>null);return ga=null,document.getElementById("btn-pwa-install")?.classList.add("hidden"),e?.outcome==="accepted"}Hn();ba();Ba();Oa();G();ce();W();_s();var _r=["ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_MODEL","ANTHROPIC_DEFAULT_OPUS_MODEL","ANTHROPIC_DEFAULT_SONNET_MODEL","ANTHROPIC_DEFAULT_HAIKU_MODEL","CLAUDE_CODE_SUBAGENT_MODEL","CLAUDE_CODE_EFFORT_LEVEL"],fn="claude";function Ol(){document.getElementById("root").insertAdjacentHTML("beforeend",Qu()),Vu()}function Qu(){return`
|
|
586
586
|
<div id="settings-page" class="set-page" hidden>
|
|
587
587
|
<header class="set-island">
|
|
588
588
|
<button type="button" id="set-back" class="btn btn-ghost btn-sm px-2" aria-label="\u8FD4\u56DE">\u2190</button>
|
|
@@ -612,7 +612,7 @@ ${t}`:"",n.length?n.join(`
|
|
|
612
612
|
<div class="label py-1"><span class="label-text text-xs uppercase tracking-wide">Profile</span></div>
|
|
613
613
|
<select id="ae-profile" class="select select-bordered select-sm"></select>
|
|
614
614
|
</label>
|
|
615
|
-
<div class="set-fields">${
|
|
615
|
+
<div class="set-fields">${_r.map(t=>`<label class="form-control"><div class="label py-1"><span class="label-text text-xs font-mono">${p(t)}</span></div><input id="ae-${t}" class="input input-bordered input-sm font-mono text-xs" autocomplete="off" spellcheck="false"></label>`).join("")}</div>
|
|
616
616
|
<p id="claude-env-error" class="text-error text-xs mt-2 hidden"></p>
|
|
617
617
|
<button type="button" id="claude-env-save" class="btn btn-primary btn-sm mt-4">Save profile</button>
|
|
618
618
|
</section>
|
|
@@ -682,20 +682,20 @@ ${t}`:"",n.length?n.join(`
|
|
|
682
682
|
</section>
|
|
683
683
|
</div>
|
|
684
684
|
</div>
|
|
685
|
-
</div>`}function
|
|
685
|
+
</div>`}function Vu(){i("quota-refresh")?.addEventListener("click",jr),i("quota-profile")?.addEventListener("change",jr),i("set-back")?.addEventListener("click",Bl),document.querySelectorAll("[data-set-sec]").forEach(e=>{e.addEventListener("click",()=>Wa(e.dataset.setSec))}),i("ws-add-btn")?.addEventListener("click",Dr),i("ws-new-name")?.addEventListener("keydown",e=>{e.key==="Enter"&&Dr()}),i("ws-new-dir")?.addEventListener("keydown",e=>{e.key==="Enter"&&Dr()}),i("mcp-token-generate")?.addEventListener("click",np),i("mcp-token-copy")?.addEventListener("click",sp),i("claude-env-save")?.addEventListener("click",Zu),i("ae-profile")?.addEventListener("change",()=>{Ns()}),i("user-add-btn")?.addEventListener("click",ep),i("pw-save")?.addEventListener("click",tp),document.addEventListener("router:settings",()=>Ga()),document.addEventListener("router:home",()=>{Yu()&&Bl()})}function Wa(e){fn=e||"claude",document.querySelectorAll("[data-set-sec]").forEach(t=>t.classList.toggle("is-on",t.dataset.setSec===fn)),document.querySelectorAll("[data-set-panel]").forEach(t=>{t.hidden=t.dataset.setPanel!==fn}),fn==="quota"&&jr()}var Rl=0;async function jr(){let e=++Rl,t=i("quota-list");if(!t)return;t.textContent="\u6B63\u5728\u8BFB\u53D6\u5F53\u524D\u673A\u5668\u7684\u989D\u5EA6\u2026";let n=j.peek(),s=i("quota-profile"),a=s?.value||"";if(s&&(s.innerHTML='<option value="">Claude \u9ED8\u8BA4\u8D26\u53F7</option>'+(fe.peek()||[]).map(r=>`<option value="${p(r.configDir)}">${p(r.name||r.configDir)}</option>`).join(""),s.value=a),M.peek()&&!n){t.textContent="\u8BF7\u5148\u9009\u62E9\u673A\u5668";return}let o=await Promise.all(["claude","grok","codex"].map(async r=>{let c=new URLSearchParams({agent:r});r==="claude"&&s?.value&&c.set("configDir",s.value);try{return await x("GET",`/api/agents/quota?${c}`,void 0,void 0,{machineId:n||void 0})}catch(u){return{agent:r,meters:[],message:u.message}}}));e!==Rl||n!==j.peek()||(t.innerHTML=o.map(r=>`<div class="border border-base-300 rounded-lg p-4 mb-3">
|
|
686
686
|
<h3 class="font-semibold">${p(r.agent)} ${p(r.plan||"")}</h3>
|
|
687
|
-
${(r.meters||[]).map(
|
|
688
|
-
<progress class="progress progress-primary w-full" max="100" value="${Number(
|
|
689
|
-
${
|
|
687
|
+
${(r.meters||[]).map(c=>`<div class="mt-3"><div class="text-sm">${p(c.label)} \xB7 \u5DF2\u7528 ${p(c.usedPercent)}% \xB7 \u5269\u4F59 ${p(c.remainingPercent)}%</div>
|
|
688
|
+
<progress class="progress progress-primary w-full" max="100" value="${Number(c.usedPercent)}"></progress>
|
|
689
|
+
${c.resetsAt?`<div class="text-xs opacity-60">\u91CD\u7F6E\uFF1A${p(new Date(c.resetsAt).toLocaleString())}</div>`:""}</div>`).join("")||`<p class="text-sm opacity-60 mt-2">${p(r.message||"\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u989D\u5EA6")}</p>`}
|
|
690
690
|
${r.fetchedAt?`<div class="text-xs opacity-50 mt-2">\u66F4\u65B0\u4E8E ${p(new Date(r.fetchedAt).toLocaleString())}</div>`:""}
|
|
691
|
-
</div>`).join(""))}function
|
|
691
|
+
</div>`).join(""))}function Ga(e){let t=i("settings-page");if(!t)return;t.hidden=!1,document.documentElement.classList.add("settings-open"),Wa(e||fn||"claude"),Nr(),Pr(),Ns(),Ul(),(i("mcp-token-settings")||document.querySelector('[data-set-panel="mcp"]'))&&!M.peek()&&document.querySelector('[data-set-sec="mcp"]')?.classList.add("hidden"),(location.hash||"")!=="#/settings"&&(location.hash="/settings")}function Bl(){let e=i("settings-page");e&&(e.hidden=!0),document.documentElement.classList.remove("settings-open"),(location.hash||"")==="#/settings"&&(location.hash="")}function Yu(){return!i("settings-page")?.hidden}function Nr(){let e=i("ws-list");if(!e)return;let t=fe.peek()||[];if(!t.length){e.innerHTML='<div class="text-xs text-base-content/40">\u8FD8\u6CA1\u6709 workspace</div>';return}e.innerHTML=t.map((n,s)=>`
|
|
692
692
|
<div class="set-row" style="--index:${s}">
|
|
693
693
|
<div class="set-row-body">
|
|
694
694
|
<div class="text-sm font-medium">${p(n.name)}</div>
|
|
695
695
|
<div class="text-xs font-mono text-base-content/50">${p(n.configDir)}</div>
|
|
696
696
|
</div>
|
|
697
697
|
${t.length>1?`<button type="button" class="btn btn-ghost btn-xs" data-ws-delete="${p(n.id)}">Remove</button>`:'<span class="text-xs text-base-content/40">default</span>'}
|
|
698
|
-
</div>`).join(""),e.querySelectorAll("[data-ws-delete]").forEach(n=>{n.addEventListener("click",()=>
|
|
698
|
+
</div>`).join(""),e.querySelectorAll("[data-ws-delete]").forEach(n=>{n.addEventListener("click",()=>Xu(n.dataset.wsDelete))})}function Pr(e){let t=i("ae-profile");if(!t)return;let n=e??t.value,s=fe.peek()||[],a=[...new Set(s.map(o=>o.name).filter(Boolean))];t.innerHTML='<option value="">Default</option>'+a.map(o=>`<option value="${p(o)}">${p(o)}</option>`).join(""),[...t.options].some(o=>o.value===n)?t.value=n:t.value=""}async function Dr(){let e=i("ws-new-name").value.trim(),t=i("ws-new-dir").value.trim(),n=i("ws-error");if(n.classList.add("hidden"),!e||!t){n.textContent="\u9700\u8981 name \u548C\u8DEF\u5F84",n.classList.remove("hidden");return}try{let s=await x("POST","/api/workspaces",{name:e,configDir:t}),a=[...(fe.peek()||[]).filter(o=>o.id!==s.id),s];fe.value=a,Ds(a),i("ws-new-name").value="",i("ws-new-dir").value="",Nr(),Pr(s.name),await Ns(),Wa("claude")}catch(s){n.textContent=s.message,n.classList.remove("hidden")}}async function Xu(e){try{await x("DELETE",`/api/workspaces/${e}`);let t=(fe.peek()||[]).filter(n=>n.id!==e);fe.value=t,Ds(t),Nr(),Pr(""),await Ns()}catch(t){let n=i("ws-error");n&&(n.textContent=t.message,n.classList.remove("hidden"))}}async function Ns(){try{let e=i("ae-profile")?.value||"",t=e?`?name=${encodeURIComponent(e)}`:"",n=await x("GET",`/api/agent-env${t}`),s=n.env||{},a=e?{}:n.process||{};for(let o of _r){let r=i(`ae-${o}`);if(!r)continue;let c=s[o]??a[o];c&&typeof c=="object"&&c.set?(r.placeholder=`saved ${c.preview||"\u2022\u2022\u2022\u2022"}`,r.value="",r.dataset.keep="1"):(r.value=typeof c=="string"?c:"",r.placeholder=o,r.dataset.keep="")}}catch{}}async function Zu(){let e=i("claude-env-error");e?.classList.add("hidden");let t={};for(let n of _r){let s=i(`ae-${n}`);if(!s)continue;let a=s.value.trim();a?t[n]=a:s.dataset.keep==="1"?t[n]={set:!0}:t[n]=""}try{let n=i("ae-profile")?.value||"";await x("PUT","/api/agent-env",{name:n,env:t}),await Ns()}catch(n){e&&(e.textContent=n.message,e.classList.remove("hidden"))}}async function Ul(){let e=i("set-nav-users"),t=document.querySelector('[data-set-panel="users"]');try{let n=await x("GET","/api/collab/me"),s=n.role==="admin"||n.role==="owner";if(e?.classList.toggle("hidden",!s),t&&(t.hidden=!s||fn!=="users"),!s){fn==="users"&&Wa("claude");return}let a=await x("GET","/api/collab/users"),o=i("users-list"),r=Array.isArray(a)?a:[];o.innerHTML=r.map(c=>`<div class="set-row"><div class="text-sm font-medium flex-1">${p(c.username)}</div><div class="text-xs text-base-content/50">${p(c.role||"")}</div></div>`).join("")||'<div class="text-xs text-base-content/40">\u8FD8\u6CA1\u6709\u5176\u4ED6\u7528\u6237</div>'}catch{e?.classList.add("hidden")}}async function ep(){let e=i("users-error");e?.classList.add("hidden");let t=i("user-new-name")?.value.trim(),n=i("user-new-pass")?.value||"",s=i("user-new-role")?.value||"editor";if(!t||!n){e&&(e.textContent="\u9700\u8981\u7528\u6237\u540D\u548C\u5BC6\u7801",e.classList.remove("hidden"));return}try{await x("POST","/api/collab/users",{username:t,password:n,role:s}),i("user-new-name").value="",i("user-new-pass").value="",await Ul()}catch(a){e&&(e.textContent=a.message,e.classList.remove("hidden"))}}async function tp(){let e=i("pw-error");e?.classList.add("hidden");let t=i("pw-current")?.value||"",n=i("pw-next")?.value||"",s=i("pw-next2")?.value||"";if(n!==s){e&&(e.textContent="\u4E24\u6B21\u65B0\u5BC6\u7801\u4E0D\u4E00\u81F4",e.classList.remove("hidden"));return}try{await x("POST","/api/auth/password",{current:t,next:n}),i("pw-current").value="",i("pw-next").value="",i("pw-next2").value=""}catch(a){e&&(e.textContent=a.message,e.classList.remove("hidden"))}}async function np(){let e=i("mcp-token-result"),t=i("mcp-token-error");e?.classList.add("hidden"),t?.classList.add("hidden");let n=j.peek();if(!n){t.textContent="\u8BF7\u5148\u5728\u4E3B\u754C\u9762\u9009\u4E00\u53F0\u5728\u7EBF\u673A\u5668\u3002",t.classList.remove("hidden");return}try{let s=Number(i("mcp-token-expiry").value),a=await x("POST",`/api/mcp/tokens?machine=${encodeURIComponent(n)}`,{expiresInSeconds:s});i("mcp-token-value").value=a.token||"";let o=i("mcp-token-url");o&&(o.textContent=`${location.origin}/mcp`),e.classList.remove("hidden")}catch(s){t.textContent=s.message,t.classList.remove("hidden")}}async function sp(){let e=i("mcp-token-value")?.value;if(e)try{await navigator.clipboard.writeText(e)}catch{i("mcp-token-value")?.select(),document.execCommand("copy")}}Ps();Os();Ia();W();var cc=()=>`
|
|
699
699
|
<div id="auth-screen" class="${l.token?"hidden":""} flex items-center justify-center h-full p-4" ${l.token?'style="display:none"':""}>
|
|
700
700
|
<div class="card bg-base-200 border border-base-300 w-full max-w-sm shadow-xl">
|
|
701
701
|
<div class="card-body gap-3 p-8">
|
|
@@ -716,7 +716,7 @@ ${t}`:"",n.length?n.join(`
|
|
|
716
716
|
<div id="auth-error" class="alert alert-error text-xs py-2 hidden"></div>
|
|
717
717
|
</div>
|
|
718
718
|
</div>
|
|
719
|
-
</div>`,
|
|
719
|
+
</div>`,dc=(e={})=>{let t=!!e.restoreSession,n=l.token?"":"hidden",s=l.token?"display:flex":"display:none";return`
|
|
720
720
|
<div id="sidebar-overlay" class="hidden fixed inset-0 bg-black/50 z-[9]" aria-hidden="true"></div>
|
|
721
721
|
<div id="app" class="${n} flex-col flex-1 overflow-hidden" style="${s}">
|
|
722
722
|
<div id="topbar" class="flex items-center gap-2 px-3 bg-base-200 border-b border-base-300 flex-shrink-0" style="height:44px">
|
|
@@ -1120,7 +1120,7 @@ ${t}`:"",n.length?n.join(`
|
|
|
1120
1120
|
</div>
|
|
1121
1121
|
</div>
|
|
1122
1122
|
<form method="dialog" class="modal-backdrop"><button>close</button></form>
|
|
1123
|
-
</dialog>`};
|
|
1123
|
+
</dialog>`};Yr();Tt();rs();G();W();ce();ys();_s();ba();Tt();Gs();Os();rs();Ks();Hn();async function xo(e={}){i("auth-screen").style.display="none";let t=i("app");t.classList.remove("hidden"),t.style.display="flex",queueMicrotask(Ee),sl().catch(()=>{});let n=e.hub;n===void 0?n=await ha():n?(M.value=!0,n.machines&&(le.value=n.machines)):M.value=!1;let s=e.deepLink||null,a=nn();if(!!(s?.id||(location.hash||"").startsWith("#/session/"))){let c=i("welcome");c&&(c.classList.add("hidden"),c.style.display="none");let u=i("project-view");u&&(u.classList.remove("hidden"),u.style.display="flex",u.style.flexDirection="column",u.style.flex="1",u.style.minHeight="0")}if(M.peek()){let c=localStorage.getItem("machineId")||a?.machineId||"";c&&(Le(c),ho(),it.value=!0,Bs());let u=Sn().then(m=>(Ot(),c&&!m.some(w=>w.id===c&&w.online!==!1)&&m.length&&(m.some(y=>y.id===c)||(Le(null),Ln())),m));oi(),Ot();let d=Promise.all([We({waitFresh:!1}),ss({waitFresh:!1}),Ws().catch(()=>{}),as().catch(()=>{})]);if(s?.id){let m=ne.peek().find(g=>g.sessionId===s.id)||(a?.sessionId===s.id?a:null);await nt(s.id,m?.cwd||null,m?.configDir||null,s.agent||m?.agent||null,s.machineId||m?.machineId||c||null,{tab:s.tab||"chat"}),u.catch(()=>{}),d.catch(()=>{});return}if(!c){if(await u,!(le.peek()||[]).length){Ln(),d.catch(()=>{});return}Ln(),d.catch(()=>{});return}await d;let f=i("topbar-project");f&&f.textContent==="Select a session"&&(f.textContent=`Machine \xB7 ${c}`);return}Bs();let r=Promise.all([We({waitFresh:!1}),ss({waitFresh:!1}),Ws().catch(()=>{}),as().catch(()=>{})]);if(s?.id){await Fa().then(u=>{Array.isArray(u)?ne.value=u:u&&Array.isArray(u.sessions)&&(ne.value=u.sessions)}).catch(()=>{});let c=ne.peek().find(u=>u.sessionId===s.id)||(a?.sessionId===s.id?a:null);await nt(s.id,c?.cwd||null,c?.configDir||null,s.agent||c?.agent||null,null,{tab:s.tab||"chat"}),r.catch(()=>{});return}await r}Gs();Ks();G();W();ce();Ba();Tt();rs();Ks();Hn();function Oc(){let e=i("sidebar");e&&(e.classList.add("open"),i("sidebar-overlay").classList.remove("hidden"),i("hamburger")?.setAttribute("aria-expanded","true"),Ee(),setTimeout(()=>i("session-search")?.focus({preventScroll:!0}),180))}function Qs(){let e=i("sidebar");e&&(e.classList.remove("open"),i("sidebar-overlay").classList.add("hidden"),i("hamburger")?.setAttribute("aria-expanded","false"),Ee(),i("hamburger")?.focus({preventScroll:!0}))}function Uc(){window.innerWidth<=640&&Qs()}function Fc(){let e=i("sidebar-toggle"),t=i("sidebar");if(!e||!t)return;let n=localStorage.getItem("sidebarCollapsed")==="1",s=localStorage.getItem("sidebarWidth")||t.style.width||"280px",a=()=>{t.classList.toggle("desktop-collapsed",n),n?(t.style.width="0",t.style.minWidth="0",t.style.overflow="hidden"):(t.style.width=s,t.style.minWidth="",t.style.overflow=""),e.textContent=n?"\u25B6":"\u25C0",e.title=n?"\u5C55\u5F00\u4FA7\u680F":"\u6536\u8D77\u4FA7\u680F",e.setAttribute("aria-label",e.title),e.setAttribute("aria-expanded",n?"false":"true")};a(),e.addEventListener("click",()=>{n=!n,n&&(s=t.style.width||s),localStorage.setItem("sidebarCollapsed",n?"1":"0"),a()})}function Wc(){let e=i("sidebar-resize"),t=i("sidebar"),n=!1;e.addEventListener("mousedown",s=>{n=!0,document.body.style.userSelect="none",document.body.style.cursor="col-resize",s.preventDefault()}),document.addEventListener("mousemove",s=>{if(!n)return;let a=Math.min(Math.max(s.clientX,160),520);t.style.width=a+"px",t.style.minWidth=""}),document.addEventListener("mouseup",()=>{if(!n)return;n=!1,document.body.style.userSelect="",document.body.style.cursor="";let s=Math.round(t.getBoundingClientRect().width);s>=160&&localStorage.setItem("sidebarWidth",`${s}px`)})}function ci(e){document.documentElement.setAttribute("data-theme",e),localStorage.setItem("theme",e);let t=i("btn-theme"),n=e==="dark"||e==="night"||e==="black"?"\u{1F319}":"\u2600\uFE0F";t&&(t.textContent=n),document.querySelectorAll('[data-sidebar-action="theme"]').forEach(a=>{a.textContent=n});let s=document.getElementById("hljs-theme");if(s||(s=document.querySelector('link[href*="highlight"][href*="styles"]'),s&&(s.id="hljs-theme")),s){let a=e==="dark"||e==="night"||e==="black";s.href="/vendor/highlight-dark.min.css"}}function di(){let e=document.documentElement.getAttribute("data-theme")||"dark";ci(e==="dark"?"light":"dark")}function ui(){let e=i("new-session-agent");e&&(e.value=$.peek()||"claude");let t=i("new-session-workspace");if(t){let a=fe.peek();t.innerHTML=a.map(o=>`<option value="${p(o.configDir)}">${p(o.name)} \u2014 ${p(o.configDir)}</option>`).join(""),l.configDir&&(t.value=l.configDir)}let n=i("new-session-machine-wrap"),s=i("new-session-machine");if(n&&s)if(M.peek()){n.style.display="";let a=le.peek()||[],o=j.peek()||"";s.innerHTML=a.length?a.map(r=>`<option value="${p(r.id)}">${p(r.id)}${r.hostname?" \u2014 "+p(r.hostname):""}</option>`).join(""):'<option value="">(no machines online)</option>',o&&(s.value=o),s.disabled=!0}else n.style.display="none",s&&(s.disabled=!1);pi(),i("new-session-path").value=E.peek()?.path||"",i("new-session-error").classList.add("hidden"),i("modal-new-session").showModal(),setTimeout(()=>i("new-session-path").focus(),50)}function pi(){let e=i("new-session-agent")?.value||"claude",t=i("new-session-ws-wrap");t&&(t.style.display=e==="claude"?"":"none")}async function fi(){let e=i("new-session-path").value.trim(),t=i("new-session-agent")?.value||"claude",n=t==="claude"?i("new-session-workspace").value:null,s=i("new-session-error");if(s.classList.add("hidden"),!e){s.textContent="Working directory is required",s.classList.remove("hidden");return}if(M.peek()){let a=j.peek()||i("new-session-machine")?.value||le.peek()?.[0]?.id;if(!a){s.textContent="\u8BF7\u5148\u9009\u62E9\u4E00\u53F0\u673A\u5668",s.classList.remove("hidden"),Ln();return}Le(a)}try{let a=await x("POST","/api/resolve-path",{path:e});if(!a.isDir)throw new Error("Path is not a directory");i("modal-new-session").close();let o=a.path.split("/").filter(Boolean).pop()||a.path;Kn(),Qn(),Yn(),Vn(),l.sessionId=null,l.configDir=n||null,l.agent=t,Ne(t),se(Oe(t)||_.peek()),et(),xe(()=>{E.value={id:o,name:o,path:a.path,machineId:j.peek()||l.machineId},ke.value=a.path,ie.value=a.path,Se.value=a.path,Y.value="",re.value=null}),i("topbar-project").textContent=a.path;let r=i("files-root-input");r&&(r.value=a.path);let c=i("git-root-input");c&&(c.value=a.path),i("welcome").classList.add("hidden");let u=i("project-view");u.classList.remove("hidden"),u.style.display="flex",Xn(),Jn({sessionId:null}),Ht(),Ct("chat"),C(`New ${Z[t]||t} session \xB7 ${a.path}`)}catch(a){s.textContent=a.message,s.classList.remove("hidden")}}function Ap(){let e=/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1,t=/Android/i.test(navigator.userAgent),n;e?n=`<ol class="list-decimal pl-4 space-y-2 text-sm text-base-content/80">
|
|
1124
1124
|
<li>\u70B9\u5E95\u90E8\u5206\u4EAB\u6309\u94AE <strong>\u5206\u4EAB</strong>\uFF08\u65B9\u6846+\u5411\u4E0A\u7BAD\u5934\uFF09</li>
|
|
1125
1125
|
<li>\u4E0B\u6ED1\u627E\u5230\u5E76\u70B9 <strong>\u6DFB\u52A0\u5230\u4E3B\u5C4F\u5E55</strong></li>
|
|
1126
1126
|
<li>\u786E\u8BA4\u540D\u79F0\u540E\u70B9 <strong>\u6DFB\u52A0</strong></li>
|
|
@@ -1140,48 +1140,48 @@ ${t}`:"",n.length?n.join(`
|
|
|
1140
1140
|
<form method="dialog"><button class="btn btn-sm">\u77E5\u9053\u4E86</button></form>
|
|
1141
1141
|
</div>
|
|
1142
1142
|
</div>
|
|
1143
|
-
<form method="dialog" class="modal-backdrop"><button>close</button></form>`,s.showModal()}async function
|
|
1143
|
+
<form method="dialog" class="modal-backdrop"><button>close</button></form>`,s.showModal()}async function hi(){let e=i("auth-screen");e&&(e.classList.remove("hidden"),e.style.display="flex");let t=i("app");t&&(t.classList.add("hidden"),t.style.display="none");let n=i("auth-btn"),s,a=new AbortController,o=setTimeout(()=>a.abort(),8e3);try{s=await x("GET","/api/auth/status",void 0,a.signal)}catch(r){console.warn("[auth status]",r);let c=i("auth-error");c&&(c.textContent="\u65E0\u6CD5\u8FDE\u63A5\u670D\u52A1\u5668\u3002\u8BF7\u68C0\u67E5\u7F51\u7EDC\u6216\u670D\u52A1\u5730\u5740\u540E\u91CD\u8BD5\u3002",c.classList.remove("hidden")),n&&(n.dataset.mode="login");return}finally{clearTimeout(o)}s.needsSetup?(i("auth-subtitle").textContent="Create your account to get started",n.textContent="Create Account",n.dataset.mode="register"):n.dataset.mode="login"}async function mi(){let e=i("auth-username").value.trim(),t=i("auth-password").value,n=i("auth-error");n.classList.add("hidden");try{let s=await x("POST",`/api/auth/${i("auth-btn").dataset.mode||"login"}`,{username:e,password:t});l.token=s.token,localStorage.setItem("token",s.token),xo()}catch(s){n.textContent=s.message,n.classList.remove("hidden")}}function gi(){return l.token?/^#\/session\//.test(location.hash||""):!1}function Gc(e={}){if(ci(localStorage.getItem("theme")||"dark"),!document.getElementById("xterm-css")){let d=document.createElement("link");d.id="xterm-css",d.rel="stylesheet",d.href="/xterm.min.css",document.head.appendChild(d)}if(!document.getElementById("xterm-js")){let d=document.createElement("script");d.id="xterm-js",d.src="/xterm.min.js",document.head.appendChild(d)}if(!document.getElementById("xterm-fit-js")){let d=document.createElement("script");d.id="xterm-fit-js",d.src="/addon-fit.min.js",document.head.appendChild(d)}let t=e.restoreSession??gi(),n=document.getElementById("root");if(n.style.cssText="display:flex;flex-direction:column;flex:1;height:100%",n.innerHTML=cc()+dc({restoreSession:t}),t){let d=i("session-list");d&&(d.innerHTML='<div class="px-3 py-3 text-[10px] text-base-content/35">Loading sessions\u2026</div>')}De(()=>{let d=fe.value,f=i("ws-tabs");if(!f)return;if(d.length<=1){f.innerHTML="";return}let m=ke.peek();f.innerHTML=[{id:null,name:"All"},...d].map(g=>`<button class="px-3 py-1.5 text-[11px] flex-shrink-0 border-b-2 whitespace-nowrap
|
|
1144
1144
|
${(g.id===null?!m:m===g.configDir)?"border-primary text-primary":"border-transparent text-base-content/50 hover:text-base-content"}"
|
|
1145
1145
|
data-ws-tab="${p(g.configDir||"")}">
|
|
1146
1146
|
${p(g.name)}
|
|
1147
|
-
</button>`).join("")}),je(()=>{_t.value,Zt.value,gt.value,rt.value,T.value;let c=i("session-list");if(!c||c.querySelector(".session-rename-input"))return;let f=Jr();if(c._lastHtml===f){Bs();return}let m=c.scrollTop;c.innerHTML=f,c._lastHtml=f,c.scrollTop=m,Bs()}),je(()=>{bt.value,Bs()}),je(()=>{ne.value,ye.value,_.value,M.value;let c=i("welcome");c&&(document.documentElement.classList.contains("boot-restore")||document.documentElement.classList.contains("boot-pending")||c.classList.contains("hidden")||c.style.display==="none"||wn())}),De(ke,c=>{let f=i("session-filter-badge");f&&(f.style.display=c?"inline":"none",f.title=c||"")}),je(()=>{let c=E.value;if(c&&c.path)$c(c.path);else{let f=i("project-notes-bar");f&&(f.style.display="none")}}),De(X,c=>{document.querySelectorAll("[data-tab]").forEach(m=>{let g=m.dataset.tab===c;m.classList.toggle("text-primary",g),m.classList.toggle("border-primary",g),m.classList.toggle("text-base-content/50",!g),m.classList.toggle("border-transparent",!g)});let f=i("project-view");f&&!f.classList.contains("hidden")&&(f.style.display="flex",f.style.flexDirection="column",f.style.minHeight="0",f.style.flex="1"),["chat","files","git","shell","memory"].forEach(m=>{let g=i(`tab-${m}`);if(!g)return;let w=m===c;g.classList.toggle("hidden",!w),w?(g.style.display="flex",g.style.flexDirection="column",g.style.flex="1 1 0",g.style.minHeight="0",g.style.overflow="hidden"):g.style.display="none"}),c==="memory"&&no(),c==="shell"&&requestAnimationFrame(()=>{document.dispatchEvent(new CustomEvent("shell-tab-shown"))}),Ee()}),Pc(),Nc(),nl({openSession:nt});let s=c=>{i("app")?.classList.toggle("chat-chrome-collapsed",c),i("btn-expand-chat-chrome")?.classList.toggle("hidden",!c),localStorage.setItem("chatChromeCollapsed",c?"1":"0")};s(localStorage.getItem("chatChromeCollapsed")==="1");let a=null;document.addEventListener("sessions-changed",()=>{a&&clearTimeout(a),a=setTimeout(()=>{a=null,We({waitFresh:!1})},1200)}),document.addEventListener("router:home",fo),document.addEventListener("router:session",async({detail:{id:c,tab:f,machineId:m,agent:g}})=>{let w=ne.peek().find(A=>A.sessionId===c),y=tn();await nt(c,w?.cwd||(y?.sessionId===c?y.cwd:null)||null,w?.configDir||(y?.sessionId===c?y.configDir:null)||null,g||w?.agent||(y?.sessionId===c?y.agent:null)||null,m||w?.machineId||(y?.sessionId===c?y.machineId:null)||null,{tab:f||"chat"})}),b.on("click","#btn-home",fo),b.on("click","#btn-share-session, #btn-share-session-current",async(c,f)=>{let m=El();if(m)try{await navigator.clipboard.writeText(m),f.classList.add("is-copied"),f.title="\u5DF2\u590D\u5236\u5206\u4EAB\u94FE\u63A5",setTimeout(()=>{f.classList.remove("is-copied"),f.title="\u590D\u5236\u5F53\u524D\u4F1A\u8BDD\u5206\u4EAB\u94FE\u63A5"},1400)}catch{window.prompt("\u590D\u5236\u4F1A\u8BDD\u94FE\u63A5\uFF1A",m)}}),b.on("click","#auth-btn",ii),b.on("submit","#auth-form",c=>{c.preventDefault(),ii()}),b.on("keydown","#auth-username, #auth-password",c=>{c.key==="Enter"&&ii()}),b.on("click","#hamburger",()=>i("sidebar").classList.contains("open")?Ks():Dc()),b.on("click","#sidebar-overlay",Ks),document.addEventListener("keydown",c=>{c.key==="Escape"&&window.innerWidth<=640&&i("sidebar")?.classList.contains("open")&&(c.preventDefault(),Ks())}),b.on("input","#session-search",(c,f)=>{$e.value=f.value,to(f.value)}),b.on("click","#sidebar-filter-toggle",()=>{let c=i("sidebar-filter-menu");if(!c)return;let f=c.classList.toggle("hidden");i("sidebar-filter-toggle")?.setAttribute("aria-expanded",String(!f))}),b.on("change","[data-agent-option]",(c,f)=>{let m=new Set(Vt.peek());f.checked?m.add(f.dataset.agentOption):m.delete(f.dataset.agentOption);let g=[...m];Vt.value=g,localStorage.setItem("agentFilters",JSON.stringify(g)),ye.value=g.length===1?g[0]:"all"}),b.on("change","#filter-favorites",(c,f)=>{ze.value=f.checked,localStorage.setItem("favoritesOnly",f.checked?"1":"0")}),b.on("change","#filter-hidden",(c,f)=>{Je.value=f.checked,localStorage.setItem("showHiddenOnly",f.checked?"1":"0")}),b.on("click","#filter-clear",()=>{Vt.value=[],ye.value="all",ze.value=!1,Je.value=!1,localStorage.setItem("agentFilters","[]"),localStorage.setItem("favoritesOnly","0"),localStorage.setItem("showHiddenOnly","0"),document.querySelectorAll("[data-agent-option]").forEach(c=>{c.checked=!1}),i("filter-favorites")&&(i("filter-favorites").checked=!1),i("filter-hidden")&&(i("filter-hidden").checked=!1)}),b.on("click","#session-filter-badge",()=>{ke.value=null}),b.on("click","[data-ws-tab]",(c,f)=>{ke.value=f.dataset.wsTab||null}),b.on("click","#sidebar-refresh",()=>{We(),$e.peek().trim()&&eo($e.peek())}),b.on("click","[data-view]",(c,f)=>{gt.value=f.dataset.view,localStorage.setItem("sidebarView",f.dataset.view)}),b.on("click","[data-agent-filter]",(c,f)=>{ye.value=f.dataset.agentFilter,localStorage.setItem("agentFilter",f.dataset.agentFilter),$e.peek().trim()&&to($e.peek())}),b.on("dblclick","[data-project-cwd]",(c,f)=>{let m=f.dataset.projectCwd;if(!m)return;let g=m.split("/").filter(Boolean).pop()||m;ti({id:g,name:g,path:m}),C(`Project \xB7 ${m}`)}),b.on("click","#btn-pwa-install",async()=>{await Bi()||kp()}),document.addEventListener("pwa-installable",()=>{document.getElementById("btn-pwa-install")?.classList.remove("hidden")}),b.on("click","#btn-settings",Ba),b.on("click","#btn-notes",()=>Oa()),b.on("click","#btn-collapse-chat-chrome",()=>s(!0)),b.on("click","#btn-expand-chat-chrome",()=>s(!1)),b.on("click","#btn-meta-agent",()=>Ql()),b.on("click","#btn-meta-agent-welcome",()=>Pr("chat")),b.on("click","#btn-theme",si),b.on("click","[data-sidebar-action]",(c,f)=>{let m=f.dataset.sidebarAction;m==="new"&&ai(),m==="theme"&&si(),m==="settings"&&Ba(),m==="logout"&&(l.token=null,localStorage.removeItem("token"),Le(null),it.value=!1,location.reload())}),b.on("click","#btn-cal-prev",()=>{Fr(-1),wn(yn())}),b.on("click","#btn-cal-next",()=>{Fr(1),wn(yn())}),b.on("click","[data-cal-date]",(c,f)=>{fc(f.dataset.calDate),wn(yn())}),b.on("click","[data-session-id]",(c,f)=>{c.target.closest("[data-fav-toggle]")||c.target.closest("[data-hide-toggle]")||c.target.closest("[data-rename-session]")||c.target.closest(".session-rename-input")||c.target.closest(".session-title-wrap.session-rename-active")||(nt(f.dataset.sessionId,f.dataset.sessionCwd||null,f.dataset.sessionConfigDir||null,f.dataset.sessionAgent||"claude",f.dataset.sessionMachine||null),_c())}),b.on("click","[data-rename-session]",(c,f)=>{c.preventDefault(),c.stopPropagation();let m=f.closest(".session-title-wrap")||f,g=m.dataset.renameSessionId||m.dataset.sessionId;g&&Yr({sessionId:g,agent:m.dataset.renameSessionAgent||"claude",machineId:m.dataset.renameSessionMachine||null,fallbackDisplay:m.dataset.renameSessionDisplay||"",mountEl:m})}),b.on("click","[data-rename-bar]",(c,f)=>{if(c.preventDefault(),c.stopPropagation(),!l.sessionId)return;let m=document.getElementById("session-title-display")||f;Yr({sessionId:l.sessionId,agent:l.agent||$.peek()||"claude",machineId:l.machineId||null,mountEl:m})}),b.on("click","[data-folder]",(c,f)=>{let m=f.dataset.folder,w=f.querySelector("span")?.textContent.trim()==="\u25BE",y=new Set(jn.peek()),A=new Set(Dn.peek());w?(y.delete(m),A.add(m)):(y.add(m),A.delete(m)),xe(()=>{jn.value=y,Dn.value=A})}),b.on("click","#memory-refresh",no),b.on("click","[data-memory-file]",c=>Qr(c.dataset.memoryFile,c.dataset.memoryAgent)),b.on("click","[data-tab]",(c,f)=>Ct(f.dataset.tab));let o=async(c,f)=>{let m=i(c),g=m?.value.trim();if(!g){f.value="";return}try{let w=await x("POST","/api/resolve-path",{path:g});if(w.isDir===!1)throw new Error("Path is not a directory on the target machine");f.value=w.path,m.value=w.path;let y=E.peek();y&&(E.value={...y,path:w.path})}catch(w){m.style.color="oklch(var(--er))",m.title=w.message,setTimeout(()=>{m.style.color="",m.title=""},2e3)}};b.on("click","#files-root-btn",()=>o("files-root-input",ie)),b.on("click","#git-root-btn",()=>o("git-root-input",Se)),b.on("keydown","#files-root-input",c=>{c.key==="Enter"&&o("files-root-input",ie)}),b.on("keydown","#git-root-input",c=>{c.key==="Enter"&&o("git-root-input",Se)}),b.on("click","#btn-opts",()=>{i("chat-opts").classList.toggle("hidden"),Ee()}),b.on("change","#sel-agent",(c,f)=>{let m=$.peek(),g=f.value;m!==g&&(l.sessionId=null,Ne(g),se(Oe(g)||N.peek()),i("sel-permission").value=ue.peek(),et(),C(`Agent \u2192 ${Z[g]||g} \xB7 model ${N.peek()} \xB7 new session`))}),b.on("change","#sel-convert-agent",async(c,f)=>{let m=f.value;if(!m)return;let g=l.sessionId;if(!g){alert("No active session to convert."),f.value="";return}let w=l.agent||$.peek()||"claude";if(w===m){alert("Cannot convert to the same agent."),f.value="";return}f.disabled=!0,C(`Converting session ${g.slice(0,8)} from ${w} to ${m}...`);try{let y=await x("POST",`/api/sessions/${g}/convert`,{targetAgent:m,sourceAgent:w});y&&y.success?(C(`\u2713 Converted successfully. New session: ${y.targetSessionId.slice(0,8)}`),await We(),await nt(y.targetSessionId,E.peek()?.path||null,null,y.targetAgent),Ts()):C("Failed to convert session.")}catch(y){C(`Error converting session: ${y.message}`),alert(`Error converting session: ${y.message}`)}finally{f.disabled=!1,f.value=""}}),b.on("change","#sel-model",(c,f)=>{se(f.value),Xa()}),b.on("click","#btn-model-add",()=>Za({editCurrent:!1})),b.on("click","#btn-model-edit",()=>Za({editCurrent:!0})),b.on("change","#sel-effort",(c,f)=>{te.value=f.value}),b.on("change","#sel-permission",(c,f)=>{ue.value=f.value}),b.on("change","#sel-density",(c,f)=>{Ko(f.value),C(`Density \u2192 ${f.value} (applies to new tool calls; reload session to re-group history)`)}),document.addEventListener("agent-changed",et),b.on("click","#btn-new-session, #btn-new-session-current, #btn-new-session-welcome",ai),b.on("click","#new-session-cancel",()=>i("modal-new-session").close()),b.on("click","#new-session-start",ri),b.on("change","#new-session-agent",oi),b.on("keydown","#new-session-path",c=>{c.key==="Enter"&&ri()}),b.on("click","#send-btn",Is),b.on("click","#stop-btn",hl),b.on("click","#btn-logout",()=>{l.token=null,localStorage.removeItem("token"),Le(null),it.value=!1,location.reload()}),b.on("click","[data-pick-machine]",async(c,f)=>{let m=f.dataset.pickMachine;if(!m||m===_.peek()){Ln();return}await Zr(m,{forceReload:!0}),ya()});let r=async()=>{let c=i("machine-picker-status");if(c&&(c.textContent="\u5237\u65B0\u4E2D\u2026"),await $n(),lo(),Fs(),Ot(),c){let f=(le.peek()||[]).filter(m=>m.online!==!1).length;c.textContent=`${f} online`}};b.on("click","#btn-refresh-machines",r),b.on("click","#btn-refresh-machines-menu",async c=>{c.stopPropagation(),await r()}),b.on("click","#btn-machine-menu",async c=>{c.stopPropagation(),kn(),ln();let f=i("machine-menu");f&&(f.classList.contains("hidden")?(await $n(),Fs(),f.classList.remove("hidden")):f.classList.add("hidden"))}),b.on("click","#btn-recent-sessions",c=>{c.preventDefault(),c.stopPropagation(),Ln(),ln(),pc();let f=!i("recent-menu")?.classList.contains("hidden"),m=i("btn-recent-sessions");m&&m.setAttribute("aria-expanded",f?"true":"false")}),b.on("click","#recent-menu-backdrop",c=>{c.preventDefault(),c.stopPropagation(),kn(),i("btn-recent-sessions")?.setAttribute("aria-expanded","false")}),document.addEventListener("click",c=>{let f=i("machine-menu-wrap");f&&!f.contains(c.target)&&Ln();let m=i("recent-menu"),g=i("btn-recent-sessions"),w=c.target;if(m&&!m.classList.contains("hidden")){if(m.contains(w)||g?.contains(w))return;kn(),g?.setAttribute("aria-expanded","false")}}),b.on("click","#btn-notifications",c=>{c.preventDefault(),c.stopPropagation(),Ln(),kn(),tl()}),window.addEventListener("resize",()=>{i("recent-menu")&&!i("recent-menu").classList.contains("hidden")&&Or()}),b.on("click","#recent-menu [data-session-id]",()=>{kn(),i("btn-recent-sessions")?.setAttribute("aria-expanded","false")}),b.on("click","[data-dismiss-recent-session]",(c,f)=>{c.preventDefault(),c.stopPropagation(),dc({sessionId:f.dataset.dismissRecentSession,agent:f.dataset.dismissRecentAgent||"claude",machineId:f.dataset.dismissRecentMachine||null})}),b.on("click","#btn-edit-project-notes, #project-goal-text, #project-notes-text",()=>{Sc()}),b.on("click","#btn-cancel-project-notes",()=>{as()});let d=async()=>{let c=i("project-goal-input")?.value?.trim()??"",f=i("project-notes-input")?.value?.trim()??"",m=E.peek();if(!(!m||!m.path))try{let g=await x("POST","/api/projects/notes",{root:m.path,goal:c,notes:f});kc(g.goal||"",g.notes||""),as()}catch(g){alert(`Error saving project notes: ${g.message}`)}};b.on("click","#btn-save-project-notes",d),b.on("keydown","#project-goal-input",c=>{c.key==="Enter"&&d(),c.key==="Escape"&&as()}),b.on("keydown","#project-notes-input",c=>{c.key==="Escape"&&as()}),b.on("click","[data-fav-toggle]",(c,f)=>{c.stopPropagation(),c.preventDefault();let m=f.dataset.favSessionMachine||l.machineId;m&&(l.machineId=m,localStorage.setItem("machineId",m)),Ic(f.dataset.favSessionId,f.dataset.favSessionAgent||"claude",{machineId:m||null})}),b.on("click","[data-hide-toggle]",(c,f)=>{c.stopPropagation(),c.preventDefault();let m=f.dataset.hideSessionMachine||l.machineId;m&&(l.machineId=m,localStorage.setItem("machineId",m)),Tc(f.dataset.hideSessionId,f.dataset.hideSessionAgent||"claude",{machineId:m||null})}),b.on("click","#btn-edit-session-notes, #session-notes-text",()=>{Lc()}),b.on("click","#btn-cancel-session-notes",()=>tt()),b.on("click","#btn-save-session-notes",async()=>{let c=i("session-notes-input")?.value?.trim()||"";if(!l.sessionId)return;let f=l.agent||$.peek()||"claude";await Vr(l.sessionId,f,c)&&tt()}),b.on("keydown","#session-notes-input",async c=>{if(c.key==="Escape"&&tt(),c.key==="Enter"){let f=c.target.value.trim();if(!l.sessionId)return;let m=l.agent||$.peek()||"claude";await Vr(l.sessionId,m,f)&&tt()}}),b.on("click","#btn-fav-filter",()=>{let c=!ze.peek();ze.value=c,localStorage.setItem("favoritesOnly",c?"1":"0"),i("btn-fav-filter")?.classList.toggle("active",c),c&&Je.peek()&&(Je.value=!1,localStorage.setItem("showHiddenOnly","0"),i("btn-hidden-filter")?.classList.remove("active"))}),b.on("click","#btn-hidden-filter",()=>{let c=!Je.peek();Je.value=c,localStorage.setItem("showHiddenOnly",c?"1":"0"),i("btn-hidden-filter")?.classList.toggle("active",c),c&&ze.peek()&&(ze.value=!1,localStorage.setItem("favoritesOnly","0"),i("btn-fav-filter")?.classList.remove("active"))}),et(),je(()=>{M.value,_.value,l.token&&ya()}),i("sel-permission").value=ue.peek(),yl();let u=i("sel-density");u&&(u.value=_e.peek()||"normal"),document.querySelectorAll("[data-agent-option]").forEach(c=>{c.checked=Vt.peek().includes(c.dataset.agentOption)}),i("filter-favorites")&&(i("filter-favorites").checked=ze.peek()),i("filter-hidden")&&(i("filter-hidden").checked=Je.peek()),document.querySelectorAll("[data-agent-filter]").forEach(c=>{c.classList.toggle("active",c.dataset.agentFilter===ye.peek())}),i("btn-fav-filter")?.classList.toggle("active",ze.peek()),i("btn-hidden-filter")?.classList.toggle("active",Je.peek()),document.querySelectorAll("[data-view]").forEach(c=>{let f=c.dataset.view===gt.peek();c.classList.toggle("bg-primary/15",f),c.classList.toggle("text-primary",f),c.classList.toggle("font-medium",f),c.classList.toggle("text-base-content/50",!f)})}K();tr();G();ce();bs();rr();ka();Hn();nn();sn();lr();Nt();Nt();function $p(){return Z[$.peek()]||"Assistant"}function Sp(e){let t=String(e||"").trim();return/remote compact task|error decoding response body/i.test(t)?"Codex \u4F1A\u8BDD\u538B\u7F29\u5931\u8D25\uFF08\u7F51\u7EDC\u4E2D\u65AD\uFF09\u3002\u518D\u53D1\u4E00\u6761\u6D88\u606F\u91CD\u8BD5\uFF0C\u6216\u5F00\u65B0\u4F1A\u8BDD\u3002":t||"\u53D1\u9001\u5931\u8D25"}var En=null;function Lp(e){return ys(e)}function Gc(e){return e?(En&&En.el===e||(En?.destroy?.(),En=$a(e),En.el=e),En):null}function Re(e,t){if(!e||e.dataset.historyPainting==="1")return;Gc(e).stick(!!t)}var Js=0,jt=null,at=1e3,At=0,bo=null,qc=!1,vo=!1,Rc=null,xo=!1,ui="hubStreamCursors",Io=new Map,Ep=0,pi=new Set,fi="pendingUserTexts",In=(()=>{try{let e=JSON.parse(sessionStorage.getItem(fi)||"[]");return Array.isArray(e)?e.filter(t=>t?.key&&t?.text).slice(-30):[]}catch{return[]}})(),Bc=new Set,Kc=new Map;function zc(){try{In.length?sessionStorage.setItem(fi,JSON.stringify(In.slice(-30))):sessionStorage.removeItem(fi)}catch{}}function Ip(){let e=Zs(),t=In.filter(n=>n.key===e).length;t&&!Bc.has(e)&&(Bc.add(e),H(`\u231B Restored ${t} queued prompt${t===1?"":"s"} in this browser tab`))}function Jc(e=l.sessionId,t=l.agent,n=l.machineId){return e?`${n||""}:${t||"claude"}:${e}`:""}function Tp(e={}){let t=Jc(e.sessionId,e.agent,e.machineId);if(!t)return 0;try{return Number(JSON.parse(localStorage.getItem(ui)||"{}")[t])||0}catch{return 0}}function Cp(e){let t=Number(e?.hubSeq)||0;if(!t)return!0;let n=Jc(e.sessionId||l.sessionId,e.agent||l.agent,l.machineId);if(!n)return!0;let s={};try{s=JSON.parse(localStorage.getItem(ui)||"{}")||{}}catch{}let a=Number(s[n])||0;if(t<=a)return!1;s[n]=t;let o=Object.keys(s);o.length>500&&o.sort((r,d)=>Number(s[d])-Number(s[r])).slice(500).forEach(r=>delete s[r]);try{localStorage.setItem(ui,JSON.stringify(s))}catch{}return!0}function Zs({sessionId:e=l.sessionId,agent:t=l.agent,machineId:n=l.machineId}={}){return e?`${n||""}:${t||"claude"}:${e}`:null}function Mp(){qc||(qc=!0,document.addEventListener("visibilitychange",()=>{if(document.visibilityState==="visible"&&(at=400,rs({probe:!0}),l.ws?.readyState===WebSocket.OPEN&&l.sessionId))try{l.ws.send(JSON.stringify({type:"subscribe",sessionId:l.sessionId,agent:l.agent}))}catch{}}),window.addEventListener("online",()=>{at=400,rs({force:!0})}),window.addEventListener("pageshow",e=>{e.persisted?rs({force:!0}):rs({probe:!0})}),window.addEventListener("focus",()=>rs({probe:!0})),navigator.connection?.addEventListener?.("change",()=>{at=400,rs({probe:!0})}))}function Vs(){let e=i("conn-dot");if(!e)return;let t=me.peek();e.classList.remove("bg-success","bg-warning","bg-error","bg-base-content/30","animate-pulse"),t==="open"?(e.classList.add("bg-success"),e.title="\u5DF2\u8FDE\u63A5"):t==="connecting"||t==="reconnecting"?(e.classList.add("bg-warning","animate-pulse"),e.title=t==="connecting"?"\u8FDE\u63A5\u4E2D\u2026":"\u91CD\u8FDE\u4E2D\u2026"):t==="offline"?(e.classList.add("bg-error"),e.title="\u79BB\u7EBF"):(e.classList.add("bg-base-content/30"),e.title="\u672A\u8FDE\u63A5")}function rs(e={}){let t=l.ws?.readyState;if(e.force){at=400,$o({quiet:!0});return}if(t===WebSocket.OPEN){if(e.probe&&At&&Date.now()-At>45e3)try{l.ws.close()}catch{}else if(e.probe&&l.ws.readyState===WebSocket.OPEN)try{l.ws.send(JSON.stringify({type:"ping"}))}catch{}return}t!==WebSocket.CONNECTING&&(at=Math.min(at,800),$o({quiet:!0}))}function Ap(){jt||(me.value=typeof navigator<"u"&&navigator.onLine===!1?"offline":"reconnecting",Vs(),jt=setTimeout(()=>{jt=null,$o({quiet:!0})},at),at=Math.min(Math.round(at*1.8),15e3))}function Qc(){bo&&(clearInterval(bo),bo=null)}function jp(e,t){Qc(),bo=setInterval(()=>{if(!(t!==Js||e.readyState!==WebSocket.OPEN)){if(At&&Date.now()-At>7e4){try{e.close()}catch{}return}if(!(typeof document<"u"&&document.visibilityState==="hidden")&&At&&Date.now()-At>4e4)try{e.send(JSON.stringify({type:"ping"}))}catch{}}},3e4)}function Dt(){let e=P.peek()||!!E.peek()&&me.peek()==="open";xa(e)}function ko(){return(l.role||"editor")==="viewer"?"\u53EA\u8BFB\u8D26\u53F7\uFF0C\u65E0\u6CD5\u8F93\u5165":l.lock?.foreign?`\u4F1A\u8BDD\u7531 ${l.lock.holder&&l.lock.holder!=="viewer"?l.lock.holder:"\u5176\u4ED6\u7528\u6237"} \u5360\u7528\uFF08\u9501\uFF09`:"\u5F53\u524D\u65E0\u6CD5\u8F93\u5165"}function Wt(){let e=an();l.externalSessionReadOnly=!e;let t=i("chat-input"),n=i("send-btn"),s=i("btn-attach"),a=i("session-lock-banner");if(t&&(t.disabled=!e,t.readOnly=!e,e?P.peek()?t.placeholder="\u56DE\u590D\u4E2D\u2026 \u53EF\u5148\u5199\u597D\u4E0B\u4E00\u6761\uFF0C\u7ED3\u675F\u540E\u81EA\u52A8\u53D1\u9001 \xB7 \u6216\u70B9 \u25A0 \u505C\u6B62":Ys(t.value||""):t.placeholder=ko()),n&&(n.disabled=!e),s&&(s.disabled=!e),a)if(!e)a.classList.remove("hidden"),a.textContent=ko();else{let o=l.nativeRunNotice?.sessionId===l.sessionId?l.nativeRunNotice.message:"";a.classList.toggle("hidden",!o),a.textContent=o}}function Dp(){at=400,jt&&(clearTimeout(jt),jt=null),xo=!1;let e=l.ws?.readyState;if(e===WebSocket.OPEN||e===WebSocket.CONNECTING)try{l.ws?.close()}catch{}$o({quiet:!1}),H("\u6B63\u5728\u91CD\u65B0\u8FDE\u63A5\u5E76\u540C\u6B65\u2026")}function $o(e={}){Mp(),jt&&(clearTimeout(jt),jt=null),e.quiet&&(xo=!0);let t=l.machineId||(typeof localStorage<"u"?localStorage.getItem("machineId"):null);Rc!==t&&(ua(),Rc=t);let n=++Js;try{l.ws?.close()}catch{}me.value="connecting",Vs();let s=location.protocol==="https:"?"wss":"ws",a=new URLSearchParams;l.token&&a.set("token",l.token),t&&a.set("machine",t),l.sessionId&&a.set("sessionId",l.sessionId),l.agent&&a.set("agent",l.agent);let o=Tp();o&&a.set("lastSeq",String(o));let r=new WebSocket(`${s}://${location.host}/ws/chat?${a}`);l.ws=r,r.addEventListener("open",()=>{if(n===Js){if(at=1e3,At=Date.now(),me.value="open",Vs(),l.sessionId)try{r.send(JSON.stringify({type:"subscribe",sessionId:l.sessionId,agent:l.agent}))}catch{}da(),Ip(),jp(r,n),Dt(),vo&&!xo&&H(t?`\u5DF2\u91CD\u8FDE \xB7 ${t}`:"\u5DF2\u91CD\u8FDE"),vo=!1,xo=!1}}),r.addEventListener("message",d=>{if(n!==Js)return;let u;try{u=JSON.parse(d.data)}catch{return}if(Cp(u)){if(u.type==="pong"){At=Date.now();return}if(u.type==="ping"){if(At=Date.now(),r.readyState===WebSocket.OPEN)try{r.send(JSON.stringify({type:"pong"}))}catch{}return}if(u.type==="run-status"){if(u._hubReplay||u.sessionId&&u.sessionId!==l.sessionId)return;if(typeof u.running!="boolean"){l.nativeRunNotice={sessionId:l.sessionId,message:u.message||"\u7EC8\u7AEF\u4F1A\u8BDD\u672A\u786E\u8BA4\u7ED3\u675F"},Wt();return}l.nativeRunNotice=null,Wt(),u.running?P.value=!0:(P.peek()&&(P.value=!1),mi()),Dt();return}Vc(u)}}),r.addEventListener("close",()=>{n===Js&&(Qc(),vo=!0,me.value=typeof navigator<"u"&&navigator.onLine===!1?"offline":"reconnecting",Vs(),Ap())}),r.addEventListener("error",()=>{})}function mi(){if(!In.length||P.peek())return;let e=Zs(),t=In.findIndex(a=>a.key===e);if(t<0)return;let[n]=In.splice(t,1);zc();let s=i("chat-input");s&&(s.value=n.text,Xs(s)),setTimeout(()=>{if(n.key!==Zs()||P.peek()){Kc.set(n.key,n.text);return}ea()},0)}function ho(){P.value=!1,Dt(),mi()}var _p=0;function Vc(e){if(!(e?.sessionId&&l.sessionId&&e.sessionId!==l.sessionId)){if(e&&typeof e.type=="string"&&(e.type==="note.added"||e.type==="note.updated"||e.type==="note.removed"||e.type==="queue.item.added"||e.type==="queue.item.updated"||e.type==="queue.item.removed"||e.type==="queue.item.moved"||e.type==="queue.item.sending")){window.dispatchEvent(new CustomEvent("hub-ws-message",{detail:e}));let t={"note.added":"hub:note-added","note.updated":"hub:note-updated","note.removed":"hub:note-removed"}[e.type];t&&window.dispatchEvent(new CustomEvent(t,{detail:e}))}if(e._hubReplay===!0){document.dispatchEvent(new CustomEvent("external-session-updated",{detail:e}));return}if(e.type==="batch"&&Array.isArray(e.items)){for(let t of e.items)Vc(t);return}if(["assistant","assistant_stream_start","assistant_delta","thought_delta","tool_use"].includes(e.type)&&_p++,e.type==="session-created"){let t=N.peek();l.sessionId=e.sessionId,e.agent&&e.agent!==$.peek()&&Ne(e.agent),se(t,e.agent||$.peek(),e.sessionId),document.dispatchEvent(new CustomEvent("sessions-changed"));return}if(e.type==="external-sessions-changed"){document.dispatchEvent(new CustomEvent("sessions-changed"));return}if(e.type==="external-session-updated"){document.dispatchEvent(new CustomEvent("sessions-changed")),document.dispatchEvent(new CustomEvent("external-session-updated",{detail:e}));return}if(e.type==="notification"&&e.notification){wa(e.notification);return}if(e.type==="grok-queue-status"){ef(e);return}if(e.type==="result"){Qs(),zs(),is();let t=e.usage;if(t){let n={input_tokens:t.inputTokens??t.input_tokens,output_tokens:t.outputTokens??t.output_tokens,cache_read_input_tokens:t.cacheReadInputTokens??t.cache_read_input_tokens,cache_creation_input_tokens:t.cacheCreationInputTokens??t.cache_creation_input_tokens,total_tokens:t.totalTokens??t.total_tokens,reasoning_tokens:t.reasoningTokens??t.reasoning_tokens,costUSD:t.costUSD??t.cost_usd};l.lastUsage=n,l.sessionId&&(l.lastUsageSessionId=l.sessionId),yo(n)}e.is_error||H("\u2713 Done"),ho();return}if(e.type==="complete"){Qs(),zs(),is(),!e.aborted&&e.agent==="claude"?H("\u2713 Done"):!e.aborted&&e.agent&&e.agent!=="claude"&&!e.error||(!e.aborted&&!e.agent?H("\u2713 Done"):e.aborted&&H("\u5DF2\u505C\u6B62")),ho();return}if(e.type==="error"){Qs(),zs(),(e.code===423||/locked/i.test(String(e.message||"")))&&(l.lock={...l.lock||{},held:!1,foreign:!0,holder:e.lock?.holder||l.lock?.holder||"another user"},Wt()),ls("error","Error",Sp(e.message)),ho();return}if(e.type==="shell-start"){l.shellBubble=null;return}if(e.type==="shell-output"){l.shellBubble||(l.shellBubble=sf(e.stream==="stderr"?"shell-err":"shell")),af(l.shellBubble,e.data);return}if(e.type==="shell-exit"){l.shellBubble=null,H(e.code===0?"\u2713 Exit 0":`\u2717 Exit ${e.code}${e.error?": "+e.error:""}`),ho();return}if(e.type==="assistant"){zs();for(let t of e.message?.content||[])t.type==="text"&&t.text?(is(),ls("assistant",$p(),t.text,{ts:e.ts||Date.now()})):t.type==="tool_use"&&lf(t,{ts:e.ts||Date.now()});return}if(e.type==="assistant_stream_start"){P.peek()||(P.value=!0,Dt()),Yc(e.ts);return}if(e.type==="assistant_delta"){P.peek()||(P.value=!0,Dt()),Np(e.data||"");return}if(e.type==="assistant_stream_end"){zs();return}if(e.type==="thought_stream_start"){Xc();return}if(e.type==="thought_delta"){Pp(e.data||"");return}if(e.type==="thought_stream_end"){Qs();return}if(e.type==="status"){let t=i("stream-status");if(t)t.textContent=e.message||"";else{let n=i("messages");n&&e.message&&(n.insertAdjacentHTML("beforeend",`<div id="stream-status" class="text-center text-[10px] text-base-content/35 py-0.5">${p(e.message)}</div>`),Re(n))}return}if(e.type==="permission_resolved"){let t=e.requestId||e.request_id;t&&i(`perm-${t}`)?.remove();return}(e.type==="permission_request"||e.request_id&&e.tool_name)&&cf(e)}}var st=null,Ge=null,Ft=null,ht=null;function Yc(e){let t=i("messages");if(!t||(is(),Qs(),st&&t.contains(st)))return;let n=So(e||Date.now()),s=Lo(e||Date.now());t.insertAdjacentHTML("beforeend",`
|
|
1147
|
+
</button>`).join("")}),De(()=>{_t.value,en.value,gt.value,rt.value,T.value;let d=i("session-list");if(!d||d.querySelector(".session-rename-input"))return;let f=ti();if(d._lastHtml===f){Fs();return}let m=d.scrollTop;d.innerHTML=f,d._lastHtml=f,d.scrollTop=m,Fs()}),De(()=>{bt.value,Fs()}),De(()=>{ne.value,ye.value,j.value,M.value;let d=i("welcome");d&&(document.documentElement.classList.contains("boot-restore")||document.documentElement.classList.contains("boot-pending")||d.classList.contains("hidden")||d.style.display==="none"||kn())}),je(ke,d=>{let f=i("session-filter-badge");f&&(f.style.display=d?"inline":"none",f.title=d||"")}),De(()=>{let d=E.value;if(d&&d.path)Ac(d.path);else{let f=i("project-notes-bar");f&&(f.style.display="none")}}),je(X,d=>{document.querySelectorAll("[data-tab]").forEach(m=>{let g=m.dataset.tab===d;m.classList.toggle("text-primary",g),m.classList.toggle("border-primary",g),m.classList.toggle("text-base-content/50",!g),m.classList.toggle("border-transparent",!g)});let f=i("project-view");f&&!f.classList.contains("hidden")&&(f.style.display="flex",f.style.flexDirection="column",f.style.minHeight="0",f.style.flex="1"),["chat","files","git","shell","memory"].forEach(m=>{let g=i(`tab-${m}`);if(!g)return;let w=m===d;g.classList.toggle("hidden",!w),w?(g.style.display="flex",g.style.flexDirection="column",g.style.flex="1 1 0",g.style.minHeight="0",g.style.overflow="hidden"):g.style.display="none"}),d==="memory"&&io(),d==="shell"&&requestAnimationFrame(()=>{document.dispatchEvent(new CustomEvent("shell-tab-shown"))}),Ee()}),Wc(),Fc(),dl({openSession:nt});let s=d=>{i("app")?.classList.toggle("chat-chrome-collapsed",d),i("btn-expand-chat-chrome")?.classList.toggle("hidden",!d),localStorage.setItem("chatChromeCollapsed",d?"1":"0")};s(localStorage.getItem("chatChromeCollapsed")==="1");let a=null;document.addEventListener("sessions-changed",()=>{a&&clearTimeout(a),a=setTimeout(()=>{a=null,We({waitFresh:!1})},1200)}),document.addEventListener("router:home",vo),document.addEventListener("router:session",async({detail:{id:d,tab:f,machineId:m,agent:g}})=>{let w=ne.peek().find(P=>P.sessionId===d),y=nn();await nt(d,w?.cwd||(y?.sessionId===d?y.cwd:null)||null,w?.configDir||(y?.sessionId===d?y.configDir:null)||null,g||w?.agent||(y?.sessionId===d?y.agent:null)||null,m||w?.machineId||(y?.sessionId===d?y.machineId:null)||null,{tab:f||"chat"})}),b.on("click","#btn-home",vo),b.on("click","#btn-share-session, #btn-share-session-current",async(d,f)=>{let m=_l();if(m)try{await navigator.clipboard.writeText(m),f.classList.add("is-copied"),f.title="\u5DF2\u590D\u5236\u5206\u4EAB\u94FE\u63A5",setTimeout(()=>{f.classList.remove("is-copied"),f.title="\u590D\u5236\u5F53\u524D\u4F1A\u8BDD\u5206\u4EAB\u94FE\u63A5"},1400)}catch{window.prompt("\u590D\u5236\u4F1A\u8BDD\u94FE\u63A5\uFF1A",m)}}),b.on("click","#auth-btn",mi),b.on("submit","#auth-form",d=>{d.preventDefault(),mi()}),b.on("keydown","#auth-username, #auth-password",d=>{d.key==="Enter"&&mi()}),b.on("click","#hamburger",()=>i("sidebar").classList.contains("open")?Qs():Oc()),b.on("click","#sidebar-overlay",Qs),document.addEventListener("keydown",d=>{d.key==="Escape"&&window.innerWidth<=640&&i("sidebar")?.classList.contains("open")&&(d.preventDefault(),Qs())}),b.on("input","#session-search",(d,f)=>{$e.value=f.value,ro(f.value)}),b.on("click","#sidebar-filter-toggle",()=>{let d=i("sidebar-filter-menu");if(!d)return;let f=d.classList.toggle("hidden");i("sidebar-filter-toggle")?.setAttribute("aria-expanded",String(!f))}),b.on("change","[data-agent-option]",(d,f)=>{let m=new Set(Yt.peek());f.checked?m.add(f.dataset.agentOption):m.delete(f.dataset.agentOption);let g=[...m];Yt.value=g,localStorage.setItem("agentFilters",JSON.stringify(g)),ye.value=g.length===1?g[0]:"all"}),b.on("change","#filter-favorites",(d,f)=>{Ke.value=f.checked,localStorage.setItem("favoritesOnly",f.checked?"1":"0")}),b.on("change","#filter-hidden",(d,f)=>{Je.value=f.checked,localStorage.setItem("showHiddenOnly",f.checked?"1":"0")}),b.on("click","#filter-clear",()=>{Yt.value=[],ye.value="all",Ke.value=!1,Je.value=!1,localStorage.setItem("agentFilters","[]"),localStorage.setItem("favoritesOnly","0"),localStorage.setItem("showHiddenOnly","0"),document.querySelectorAll("[data-agent-option]").forEach(d=>{d.checked=!1}),i("filter-favorites")&&(i("filter-favorites").checked=!1),i("filter-hidden")&&(i("filter-hidden").checked=!1)}),b.on("click","#session-filter-badge",()=>{ke.value=null}),b.on("click","[data-ws-tab]",(d,f)=>{ke.value=f.dataset.wsTab||null}),b.on("click","#sidebar-refresh",()=>{We(),$e.peek().trim()&&oo($e.peek())}),b.on("click","[data-view]",(d,f)=>{gt.value=f.dataset.view,localStorage.setItem("sidebarView",f.dataset.view)}),b.on("click","[data-agent-filter]",(d,f)=>{ye.value=f.dataset.agentFilter,localStorage.setItem("agentFilter",f.dataset.agentFilter),$e.peek().trim()&&ro($e.peek())}),b.on("dblclick","[data-project-cwd]",(d,f)=>{let m=f.dataset.projectCwd;if(!m)return;let g=m.split("/").filter(Boolean).pop()||m;li({id:g,name:g,path:m}),C(`Project \xB7 ${m}`)}),b.on("click","#btn-pwa-install",async()=>{await Ji()||Ap()}),document.addEventListener("pwa-installable",()=>{document.getElementById("btn-pwa-install")?.classList.remove("hidden")}),b.on("click","#btn-settings",Ga),b.on("click","#btn-notes",()=>za()),b.on("click","#btn-collapse-chat-chrome",()=>s(!0)),b.on("click","#btn-expand-chat-chrome",()=>s(!1)),b.on("click","#btn-meta-agent",()=>sc()),b.on("click","#btn-meta-agent-welcome",()=>Fr("chat")),b.on("click","#btn-theme",di),b.on("click","[data-sidebar-action]",(d,f)=>{let m=f.dataset.sidebarAction;m==="new"&&ui(),m==="theme"&&di(),m==="settings"&&Ga(),m==="logout"&&(l.token=null,localStorage.removeItem("token"),Le(null),it.value=!1,location.reload())}),b.on("click","#btn-cal-prev",()=>{Vr(-1),kn(wn())}),b.on("click","#btn-cal-next",()=>{Vr(1),kn(wn())}),b.on("click","[data-cal-date]",(d,f)=>{wc(f.dataset.calDate),kn(wn())}),b.on("click","[data-session-id]",(d,f)=>{d.target.closest("[data-fav-toggle]")||d.target.closest("[data-hide-toggle]")||d.target.closest("[data-rename-session]")||d.target.closest(".session-rename-input")||d.target.closest(".session-title-wrap.session-rename-active")||(nt(f.dataset.sessionId,f.dataset.sessionCwd||null,f.dataset.sessionConfigDir||null,f.dataset.sessionAgent||"claude",f.dataset.sessionMachine||null),Uc())}),b.on("click","[data-rename-session]",(d,f)=>{d.preventDefault(),d.stopPropagation();let m=f.closest(".session-title-wrap")||f,g=m.dataset.renameSessionId||m.dataset.sessionId;g&&ai({sessionId:g,agent:m.dataset.renameSessionAgent||"claude",machineId:m.dataset.renameSessionMachine||null,fallbackDisplay:m.dataset.renameSessionDisplay||"",mountEl:m})}),b.on("click","[data-rename-bar]",(d,f)=>{if(d.preventDefault(),d.stopPropagation(),!l.sessionId)return;let m=document.getElementById("session-title-display")||f;ai({sessionId:l.sessionId,agent:l.agent||$.peek()||"claude",machineId:l.machineId||null,mountEl:m})}),b.on("click","[data-folder]",(d,f)=>{let m=f.dataset.folder,w=f.querySelector("span")?.textContent.trim()==="\u25BE",y=new Set(jn.peek()),P=new Set(_n.peek());w?(y.delete(m),P.add(m)):(y.add(m),P.delete(m)),xe(()=>{jn.value=y,_n.value=P})}),b.on("click","#memory-refresh",io),b.on("click","[data-memory-file]",d=>ni(d.dataset.memoryFile,d.dataset.memoryAgent)),b.on("click","[data-tab]",(d,f)=>Ct(f.dataset.tab));let o=async(d,f)=>{let m=i(d),g=m?.value.trim();if(!g){f.value="";return}try{let w=await x("POST","/api/resolve-path",{path:g});if(w.isDir===!1)throw new Error("Path is not a directory on the target machine");f.value=w.path,m.value=w.path;let y=E.peek();y&&(E.value={...y,path:w.path})}catch(w){m.style.color="oklch(var(--er))",m.title=w.message,setTimeout(()=>{m.style.color="",m.title=""},2e3)}};b.on("click","#files-root-btn",()=>o("files-root-input",ie)),b.on("click","#git-root-btn",()=>o("git-root-input",Se)),b.on("keydown","#files-root-input",d=>{d.key==="Enter"&&o("files-root-input",ie)}),b.on("keydown","#git-root-input",d=>{d.key==="Enter"&&o("git-root-input",Se)}),b.on("click","#btn-opts",()=>{i("chat-opts").classList.toggle("hidden"),Ee()}),b.on("change","#sel-agent",(d,f)=>{let m=$.peek(),g=f.value;m!==g&&(l.sessionId=null,Ne(g),se(Oe(g)||_.peek()),i("sel-permission").value=ue.peek(),et(),C(`Agent \u2192 ${Z[g]||g} \xB7 model ${_.peek()} \xB7 new session`))}),b.on("change","#sel-convert-agent",async(d,f)=>{let m=f.value;if(!m)return;let g=l.sessionId;if(!g){alert("No active session to convert."),f.value="";return}let w=l.agent||$.peek()||"claude";if(w===m){alert("Cannot convert to the same agent."),f.value="";return}f.disabled=!0,C(`Converting session ${g.slice(0,8)} from ${w} to ${m}...`);try{let y=await x("POST",`/api/sessions/${g}/convert`,{targetAgent:m,sourceAgent:w});y&&y.success?(C(`\u2713 Converted successfully. New session: ${y.targetSessionId.slice(0,8)}`),await We(),await nt(y.targetSessionId,E.peek()?.path||null,null,y.targetAgent),As()):C("Failed to convert session.")}catch(y){C(`Error converting session: ${y.message}`),alert(`Error converting session: ${y.message}`)}finally{f.disabled=!1,f.value=""}}),b.on("change","#sel-model",(d,f)=>{se(f.value),so()}),b.on("click","#btn-model-add",()=>ao({editCurrent:!1})),b.on("click","#btn-model-edit",()=>ao({editCurrent:!0})),b.on("change","#sel-effort",(d,f)=>{te.value=f.value}),b.on("change","#sel-permission",(d,f)=>{ue.value=f.value}),b.on("change","#sel-density",(d,f)=>{Xo(f.value),C(`Density \u2192 ${f.value} (applies to new tool calls; reload session to re-group history)`)}),document.addEventListener("agent-changed",et),b.on("click","#btn-new-session, #btn-new-session-current, #btn-new-session-welcome",ui),b.on("click","#new-session-cancel",()=>i("modal-new-session").close()),b.on("click","#new-session-start",fi),b.on("change","#new-session-agent",pi),b.on("keydown","#new-session-path",d=>{d.key==="Enter"&&fi()}),b.on("click","#send-btn",Ms),b.on("click","#stop-btn",$l),b.on("click","#btn-logout",()=>{l.token=null,localStorage.removeItem("token"),Le(null),it.value=!1,location.reload()}),b.on("click","[data-pick-machine]",async(d,f)=>{let m=f.dataset.pickMachine;if(!m||m===j.peek()){En();return}await ri(m,{forceReload:!0}),La()});let r=async()=>{let d=i("machine-picker-status");if(d&&(d.textContent="\u5237\u65B0\u4E2D\u2026"),await Sn(),mo(),zs(),Ot(),d){let f=(le.peek()||[]).filter(m=>m.online!==!1).length;d.textContent=`${f} online`}};b.on("click","#btn-refresh-machines",r),b.on("click","#btn-refresh-machines-menu",async d=>{d.stopPropagation(),await r()}),b.on("click","#btn-machine-menu",async d=>{d.stopPropagation(),$n(),cn();let f=i("machine-menu");f&&(f.classList.contains("hidden")?(await Sn(),zs(),f.classList.remove("hidden")):f.classList.add("hidden"))}),b.on("click","#btn-recent-sessions",d=>{d.preventDefault(),d.stopPropagation(),En(),cn(),yc();let f=!i("recent-menu")?.classList.contains("hidden"),m=i("btn-recent-sessions");m&&m.setAttribute("aria-expanded",f?"true":"false")}),b.on("click","#recent-menu-backdrop",d=>{d.preventDefault(),d.stopPropagation(),$n(),i("btn-recent-sessions")?.setAttribute("aria-expanded","false")}),document.addEventListener("click",d=>{let f=i("machine-menu-wrap");f&&!f.contains(d.target)&&En();let m=i("recent-menu"),g=i("btn-recent-sessions"),w=d.target;if(m&&!m.classList.contains("hidden")){if(m.contains(w)||g?.contains(w))return;$n(),g?.setAttribute("aria-expanded","false")}}),b.on("click","#btn-notifications",d=>{d.preventDefault(),d.stopPropagation(),En(),$n(),cl()}),window.addEventListener("resize",()=>{i("recent-menu")&&!i("recent-menu").classList.contains("hidden")&&Jr()}),b.on("click","#recent-menu [data-session-id]",()=>{$n(),i("btn-recent-sessions")?.setAttribute("aria-expanded","false")}),b.on("click","[data-dismiss-recent-session]",(d,f)=>{d.preventDefault(),d.stopPropagation(),vc({sessionId:f.dataset.dismissRecentSession,agent:f.dataset.dismissRecentAgent||"claude",machineId:f.dataset.dismissRecentMachine||null})}),b.on("click","#btn-edit-project-notes, #project-goal-text, #project-notes-text",()=>{Dc()}),b.on("click","#btn-cancel-project-notes",()=>{os()});let c=async()=>{let d=i("project-goal-input")?.value?.trim()??"",f=i("project-notes-input")?.value?.trim()??"",m=E.peek();if(!(!m||!m.path))try{let g=await x("POST","/api/projects/notes",{root:m.path,goal:d,notes:f});Mc(g.goal||"",g.notes||""),os()}catch(g){alert(`Error saving project notes: ${g.message}`)}};b.on("click","#btn-save-project-notes",c),b.on("keydown","#project-goal-input",d=>{d.key==="Enter"&&c(),d.key==="Escape"&&os()}),b.on("keydown","#project-notes-input",d=>{d.key==="Escape"&&os()}),b.on("click","[data-fav-toggle]",(d,f)=>{d.stopPropagation(),d.preventDefault();let m=f.dataset.favSessionMachine||l.machineId;m&&(l.machineId=m,localStorage.setItem("machineId",m)),Nc(f.dataset.favSessionId,f.dataset.favSessionAgent||"claude",{machineId:m||null})}),b.on("click","[data-hide-toggle]",(d,f)=>{d.stopPropagation(),d.preventDefault();let m=f.dataset.hideSessionMachine||l.machineId;m&&(l.machineId=m,localStorage.setItem("machineId",m)),Pc(f.dataset.hideSessionId,f.dataset.hideSessionAgent||"claude",{machineId:m||null})}),b.on("click","#btn-edit-session-notes, #session-notes-text",()=>{jc()}),b.on("click","#btn-cancel-session-notes",()=>tt()),b.on("click","#btn-save-session-notes",async()=>{let d=i("session-notes-input")?.value?.trim()||"";if(!l.sessionId)return;let f=l.agent||$.peek()||"claude";await si(l.sessionId,f,d)&&tt()}),b.on("keydown","#session-notes-input",async d=>{if(d.key==="Escape"&&tt(),d.key==="Enter"){let f=d.target.value.trim();if(!l.sessionId)return;let m=l.agent||$.peek()||"claude";await si(l.sessionId,m,f)&&tt()}}),b.on("click","#btn-fav-filter",()=>{let d=!Ke.peek();Ke.value=d,localStorage.setItem("favoritesOnly",d?"1":"0"),i("btn-fav-filter")?.classList.toggle("active",d),d&&Je.peek()&&(Je.value=!1,localStorage.setItem("showHiddenOnly","0"),i("btn-hidden-filter")?.classList.remove("active"))}),b.on("click","#btn-hidden-filter",()=>{let d=!Je.peek();Je.value=d,localStorage.setItem("showHiddenOnly",d?"1":"0"),i("btn-hidden-filter")?.classList.toggle("active",d),d&&Ke.peek()&&(Ke.value=!1,localStorage.setItem("favoritesOnly","0"),i("btn-fav-filter")?.classList.remove("active"))}),et(),De(()=>{M.value,j.value,l.token&&La()}),i("sel-permission").value=ue.peek(),Tl();let u=i("sel-density");u&&(u.value=_e.peek()||"normal"),document.querySelectorAll("[data-agent-option]").forEach(d=>{d.checked=Yt.peek().includes(d.dataset.agentOption)}),i("filter-favorites")&&(i("filter-favorites").checked=Ke.peek()),i("filter-hidden")&&(i("filter-hidden").checked=Je.peek()),document.querySelectorAll("[data-agent-filter]").forEach(d=>{d.classList.toggle("active",d.dataset.agentFilter===ye.peek())}),i("btn-fav-filter")?.classList.toggle("active",Ke.peek()),i("btn-hidden-filter")?.classList.toggle("active",Je.peek()),document.querySelectorAll("[data-view]").forEach(d=>{let f=d.dataset.view===gt.peek();d.classList.toggle("bg-primary/15",f),d.classList.toggle("text-primary",f),d.classList.toggle("font-medium",f),d.classList.toggle("text-base-content/50",!f)})}G();lr();W();ce();ys();fr();Ia();qn();sn();an();hr();Nt();Nt();function Dp(){return Z[$.peek()]||"Assistant"}function jp(e){let t=String(e||"").trim();return/remote compact task|error decoding response body/i.test(t)?"Codex \u4F1A\u8BDD\u538B\u7F29\u5931\u8D25\uFF08\u7F51\u7EDC\u4E2D\u65AD\uFF09\u3002\u518D\u53D1\u4E00\u6761\u6D88\u606F\u91CD\u8BD5\uFF0C\u6216\u5F00\u65B0\u4F1A\u8BDD\u3002":t||"\u53D1\u9001\u5931\u8D25"}var In=null;function _p(e){return $s(e)}function Zc(e){return e?(In&&In.el===e||(In?.destroy?.(),In=Ta(e),In.el=e),In):null}function Re(e,t){if(!e||e.dataset.historyPainting==="1")return;Zc(e).stick(!!t)}var Ys=0,Dt=null,at=1e3,At=0,ko=null,zc=!1,$o=!1,Kc=null,So=!1,vi="hubStreamCursors",Do=new Map,Np=0,xi=new Set,yi="pendingUserTexts",Tn=(()=>{try{let e=JSON.parse(sessionStorage.getItem(yi)||"[]");return Array.isArray(e)?e.filter(t=>t?.key&&t?.text).slice(-30):[]}catch{return[]}})(),Jc=new Set,ed=new Map;function td(){try{Tn.length?sessionStorage.setItem(yi,JSON.stringify(Tn.slice(-30))):sessionStorage.removeItem(yi)}catch{}}function Pp(){let e=na(),t=Tn.filter(n=>n.key===e).length;t&&!Jc.has(e)&&(Jc.add(e),H(`\u231B Restored ${t} queued prompt${t===1?"":"s"} in this browser tab`))}function nd(e=l.sessionId,t=l.agent,n=l.machineId){return e?`${n||""}:${t||"claude"}:${e}`:""}function Hp(e={}){let t=nd(e.sessionId,e.agent,e.machineId);if(!t)return 0;try{return Number(JSON.parse(localStorage.getItem(vi)||"{}")[t])||0}catch{return 0}}function qp(e){let t=Number(e?.hubSeq)||0;if(!t)return!0;let n=nd(e.sessionId||l.sessionId,e.agent||l.agent,l.machineId);if(!n)return!0;let s={};try{s=JSON.parse(localStorage.getItem(vi)||"{}")||{}}catch{}let a=Number(s[n])||0;if(t<=a)return!1;s[n]=t;let o=Object.keys(s);o.length>500&&o.sort((r,c)=>Number(s[c])-Number(s[r])).slice(500).forEach(r=>delete s[r]);try{localStorage.setItem(vi,JSON.stringify(s))}catch{}return!0}function na({sessionId:e=l.sessionId,agent:t=l.agent,machineId:n=l.machineId}={}){return e?`${n||""}:${t||"claude"}:${e}`:null}function Rp(){zc||(zc=!0,document.addEventListener("visibilitychange",()=>{if(document.visibilityState==="visible"&&(at=400,is({probe:!0}),l.ws?.readyState===WebSocket.OPEN&&l.sessionId))try{l.ws.send(JSON.stringify({type:"subscribe",sessionId:l.sessionId,agent:l.agent}))}catch{}}),window.addEventListener("online",()=>{at=400,is({force:!0})}),window.addEventListener("pageshow",e=>{e.persisted?is({force:!0}):is({probe:!0})}),window.addEventListener("focus",()=>is({probe:!0})),navigator.connection?.addEventListener?.("change",()=>{at=400,is({probe:!0})}))}function Zs(){let e=i("conn-dot");if(!e)return;let t=me.peek();e.classList.remove("bg-success","bg-warning","bg-error","bg-base-content/30","animate-pulse"),t==="open"?(e.classList.add("bg-success"),e.title="\u5DF2\u8FDE\u63A5"):t==="connecting"||t==="reconnecting"?(e.classList.add("bg-warning","animate-pulse"),e.title=t==="connecting"?"\u8FDE\u63A5\u4E2D\u2026":"\u91CD\u8FDE\u4E2D\u2026"):t==="offline"?(e.classList.add("bg-error"),e.title="\u79BB\u7EBF"):(e.classList.add("bg-base-content/30"),e.title="\u672A\u8FDE\u63A5")}function is(e={}){let t=l.ws?.readyState;if(e.force){at=400,To({quiet:!0});return}if(t===WebSocket.OPEN){if(e.probe&&At&&Date.now()-At>45e3)try{l.ws.close()}catch{}else if(e.probe&&l.ws.readyState===WebSocket.OPEN)try{l.ws.send(JSON.stringify({type:"ping"}))}catch{}return}t!==WebSocket.CONNECTING&&(at=Math.min(at,800),To({quiet:!0}))}function Bp(){Dt||(me.value=typeof navigator<"u"&&navigator.onLine===!1?"offline":"reconnecting",Zs(),Dt=setTimeout(()=>{Dt=null,To({quiet:!0})},at),at=Math.min(Math.round(at*1.8),15e3))}function sd(){ko&&(clearInterval(ko),ko=null)}function Op(e,t){sd(),ko=setInterval(()=>{if(!(t!==Ys||e.readyState!==WebSocket.OPEN)){if(At&&Date.now()-At>7e4){try{e.close()}catch{}return}if(!(typeof document<"u"&&document.visibilityState==="hidden")&&At&&Date.now()-At>4e4)try{e.send(JSON.stringify({type:"ping"}))}catch{}}},3e4)}function jt(){let e=N.peek()||!!E.peek()&&me.peek()==="open";Sa(e)}function Io(){return(l.role||"editor")==="viewer"?"\u53EA\u8BFB\u8D26\u53F7\uFF0C\u65E0\u6CD5\u8F93\u5165":l.lock?.foreign?`\u4F1A\u8BDD\u7531 ${l.lock.holder&&l.lock.holder!=="viewer"?l.lock.holder:"\u5176\u4ED6\u7528\u6237"} \u5360\u7528\uFF08\u9501\uFF09`:"\u5F53\u524D\u65E0\u6CD5\u8F93\u5165"}function Wt(){let e=on();l.externalSessionReadOnly=!e;let t=i("chat-input"),n=i("send-btn"),s=i("btn-attach"),a=i("session-lock-banner");if(t&&(t.disabled=!e,t.readOnly=!e,e?N.peek()?t.placeholder="\u56DE\u590D\u4E2D\u2026 \u53EF\u5148\u5199\u597D\u4E0B\u4E00\u6761\uFF0C\u7ED3\u675F\u540E\u81EA\u52A8\u53D1\u9001 \xB7 \u6216\u70B9 \u25A0 \u505C\u6B62":ea(t.value||""):t.placeholder=Io()),n&&(n.disabled=!e),s&&(s.disabled=!e),a)if(!e)a.classList.remove("hidden"),a.textContent=Io();else{let o=l.nativeRunNotice?.sessionId===l.sessionId?l.nativeRunNotice.message:"";a.classList.toggle("hidden",!o),a.textContent=o}}function Up(){at=400,Dt&&(clearTimeout(Dt),Dt=null),So=!1;let e=l.ws?.readyState;if(e===WebSocket.OPEN||e===WebSocket.CONNECTING)try{l.ws?.close()}catch{}To({quiet:!1}),H("\u6B63\u5728\u91CD\u65B0\u8FDE\u63A5\u5E76\u540C\u6B65\u2026")}function To(e={}){Rp(),Dt&&(clearTimeout(Dt),Dt=null),e.quiet&&(So=!0);let t=l.machineId||(typeof localStorage<"u"?localStorage.getItem("machineId"):null);Kc!==t&&(ma(),Kc=t);let n=++Ys;try{l.ws?.close()}catch{}me.value="connecting",Zs();let s=location.protocol==="https:"?"wss":"ws",a=new URLSearchParams;l.token&&a.set("token",l.token),t&&a.set("machine",t),l.sessionId&&a.set("sessionId",l.sessionId),l.agent&&a.set("agent",l.agent);let o=Hp();o&&a.set("lastSeq",String(o));let r=new WebSocket(`${s}://${location.host}/ws/chat?${a}`);l.ws=r,r.addEventListener("open",()=>{if(n===Ys){if(at=1e3,At=Date.now(),me.value="open",Zs(),l.sessionId)try{r.send(JSON.stringify({type:"subscribe",sessionId:l.sessionId,agent:l.agent}))}catch{}fa(),Pp(),Op(r,n),jt(),$o&&!So&&H(t?`\u5DF2\u91CD\u8FDE \xB7 ${t}`:"\u5DF2\u91CD\u8FDE"),$o=!1,So=!1}}),r.addEventListener("message",c=>{if(n!==Ys)return;let u;try{u=JSON.parse(c.data)}catch{return}if(qp(u)){if(u.type==="pong"){At=Date.now();return}if(u.type==="ping"){if(At=Date.now(),r.readyState===WebSocket.OPEN)try{r.send(JSON.stringify({type:"pong"}))}catch{}return}if(u.type==="run-status"){if(u._hubReplay||u.sessionId&&u.sessionId!==l.sessionId)return;if(typeof u.running!="boolean"){l.nativeRunNotice={sessionId:l.sessionId,message:u.message||"\u7EC8\u7AEF\u4F1A\u8BDD\u672A\u786E\u8BA4\u7ED3\u675F"},Wt();return}l.nativeRunNotice=null,Wt(),u.running?N.value=!0:(N.peek()&&(N.value=!1),wi()),jt();return}ad(u)}}),r.addEventListener("close",()=>{n===Ys&&(sd(),$o=!0,me.value=typeof navigator<"u"&&navigator.onLine===!1?"offline":"reconnecting",Zs(),Bp())}),r.addEventListener("error",()=>{})}function wi(){if(!Tn.length||N.peek())return;let e=na(),t=Tn.findIndex(a=>a.key===e);if(t<0)return;let[n]=Tn.splice(t,1);td();let s=i("chat-input");s&&(s.value=n.text,ta(s)),setTimeout(()=>{if(n.key!==na()||N.peek()){ed.set(n.key,n.text);return}sa()},0)}function yo(){N.value=!1,jt(),wi()}var Fp=0;function ad(e){if(!(e?.sessionId&&l.sessionId&&e.sessionId!==l.sessionId)){if(e&&typeof e.type=="string"&&(e.type==="note.added"||e.type==="note.updated"||e.type==="note.removed"||e.type==="queue.item.added"||e.type==="queue.item.updated"||e.type==="queue.item.removed"||e.type==="queue.item.moved"||e.type==="queue.item.sending")){window.dispatchEvent(new CustomEvent("hub-ws-message",{detail:e}));let t={"note.added":"hub:note-added","note.updated":"hub:note-updated","note.removed":"hub:note-removed"}[e.type];t&&window.dispatchEvent(new CustomEvent(t,{detail:e}))}if(e._hubReplay===!0){document.dispatchEvent(new CustomEvent("external-session-updated",{detail:e}));return}if(e.type==="batch"&&Array.isArray(e.items)){for(let t of e.items)ad(t);return}if(["assistant","assistant_stream_start","assistant_delta","thought_delta","tool_use"].includes(e.type)&&Fp++,e.type==="session-created"){let t=_.peek();l.sessionId=e.sessionId,e.agent&&e.agent!==$.peek()&&Ne(e.agent),se(t,e.agent||$.peek(),e.sessionId),document.dispatchEvent(new CustomEvent("sessions-changed"));return}if(e.type==="external-sessions-changed"){document.dispatchEvent(new CustomEvent("sessions-changed"));return}if(e.type==="external-session-updated"){document.dispatchEvent(new CustomEvent("sessions-changed")),document.dispatchEvent(new CustomEvent("external-session-updated",{detail:e}));return}if(e.type==="notification"&&e.notification){Ea(e.notification);return}if(e.type==="grok-queue-status"){df(e);return}if(e.type==="result"){Xs(),Vs(),ls();let t=e.usage;if(t){let n={input_tokens:t.inputTokens??t.input_tokens,output_tokens:t.outputTokens??t.output_tokens,cache_read_input_tokens:t.cacheReadInputTokens??t.cache_read_input_tokens,cache_creation_input_tokens:t.cacheCreationInputTokens??t.cache_creation_input_tokens,total_tokens:t.totalTokens??t.total_tokens,reasoning_tokens:t.reasoningTokens??t.reasoning_tokens,costUSD:t.costUSD??t.cost_usd};l.lastUsage=n,l.sessionId&&(l.lastUsageSessionId=l.sessionId),Lo(n)}e.is_error||H("\u2713 Done"),yo();return}if(e.type==="complete"){Xs(),Vs(),ls(),!e.aborted&&e.agent==="claude"?H("\u2713 Done"):!e.aborted&&e.agent&&e.agent!=="claude"&&!e.error||(!e.aborted&&!e.agent?H("\u2713 Done"):e.aborted&&H("\u5DF2\u505C\u6B62")),yo();return}if(e.type==="error"){Xs(),Vs(),(e.code===423||/locked/i.test(String(e.message||"")))&&(l.lock={...l.lock||{},held:!1,foreign:!0,holder:e.lock?.holder||l.lock?.holder||"another user"},Wt()),cs("error","Error",jp(e.message)),yo();return}if(e.type==="shell-start"){l.shellBubble=null;return}if(e.type==="shell-output"){l.shellBubble||(l.shellBubble=ff(e.stream==="stderr"?"shell-err":"shell")),mf(l.shellBubble,e.data);return}if(e.type==="shell-exit"){l.shellBubble=null,H(e.code===0?"\u2713 Exit 0":`\u2717 Exit ${e.code}${e.error?": "+e.error:""}`),yo();return}if(e.type==="assistant"){Vs();for(let t of e.message?.content||[])t.type==="text"&&t.text?(ls(),cs("assistant",Dp(),t.text,{ts:e.ts||Date.now()})):t.type==="tool_use"&&bf(t,{ts:e.ts||Date.now()});return}if(e.type==="assistant_stream_start"){N.peek()||(N.value=!0,jt()),od(e.ts);return}if(e.type==="assistant_delta"){N.peek()||(N.value=!0,jt()),Wp(e.data||"");return}if(e.type==="assistant_stream_end"){Vs();return}if(e.type==="thought_stream_start"){rd();return}if(e.type==="thought_delta"){Gp(e.data||"");return}if(e.type==="thought_stream_end"){Xs();return}if(e.type==="status"){let t=i("stream-status");if(t)t.textContent=e.message||"";else{let n=i("messages");n&&e.message&&(n.insertAdjacentHTML("beforeend",`<div id="stream-status" class="text-center text-[10px] text-base-content/35 py-0.5">${p(e.message)}</div>`),Re(n))}return}if(e.type==="permission_resolved"){let t=e.requestId||e.request_id;t&&i(`perm-${t}`)?.remove();return}(e.type==="permission_request"||e.request_id&&e.tool_name)&&vf(e)}}var st=null,Ge=null,Ft=null,ht=null;function od(e){let t=i("messages");if(!t||(ls(),Xs(),st&&t.contains(st)))return;let n=Co(e||Date.now()),s=Mo(e||Date.now());t.insertAdjacentHTML("beforeend",`
|
|
1148
1148
|
<div class="msg-row assistant px-2 live-stream" data-ts="${p(s)}">
|
|
1149
1149
|
<div class="max-w-[88%] rounded-2xl rounded-tl-sm px-3 py-2 text-sm bg-base-200 break-words md">
|
|
1150
1150
|
<div class="msg-stream-body whitespace-pre-wrap"></div>
|
|
1151
1151
|
</div>
|
|
1152
1152
|
${n?`<div class="msg-ts" title="${p(s)}">${p(n)}</div>`:""}
|
|
1153
|
-
</div>`),st=t.lastElementChild,Ge=st.querySelector(".msg-stream-body"),i("stream-status")?.remove(),Re(t)}function
|
|
1153
|
+
</div>`),st=t.lastElementChild,Ge=st.querySelector(".msg-stream-body"),i("stream-status")?.remove(),Re(t)}function Wp(e){e&&(Ge||od(Date.now()),Ge&&(Ge.textContent+=e,Re(i("messages"))))}function Vs(){if(!st||!Ge){st=null,Ge=null;return}let e=Ge.textContent||"";e.trim()?(Ge.classList.remove("whitespace-pre-wrap"),Ge.classList.add("md"),Ge.innerHTML=Eo(e),pd(st),ud(st,e)):st.remove(),st=null,Ge=null,i("stream-status")?.remove()}function rd(){let e=i("messages");e&&(Ft&&e.contains(Ft)||(e.insertAdjacentHTML("beforeend",`
|
|
1154
1154
|
<div class="msg-row assistant px-2 thought-stream">
|
|
1155
1155
|
<div class="max-w-[88%] rounded-lg border border-base-300/60 bg-base-200/50 px-2.5 py-1.5 text-[11px] text-base-content/45">
|
|
1156
1156
|
<div class="font-medium text-base-content/35 mb-0.5">thinking\u2026</div>
|
|
1157
1157
|
<div class="thought-body font-mono whitespace-pre-wrap max-h-24 overflow-y-auto opacity-80"></div>
|
|
1158
1158
|
</div>
|
|
1159
|
-
</div>`),Ft=e.lastElementChild,ht=Ft.querySelector(".thought-body"),Re(e)))}function
|
|
1160
|
-
<div class="text-[10px] text-base-content/30 px-1 select-none">\u{1F4AD} thought ${e?`(${e} chars)`:""}</div>`}Ft=null,ht=null}var
|
|
1161
|
-
Available: ${u}`:""}`),!0}let a=
|
|
1159
|
+
</div>`),Ft=e.lastElementChild,ht=Ft.querySelector(".thought-body"),Re(e)))}function Gp(e){e&&(ht||rd(),ht&&(ht.textContent+=e,ht.scrollTop=ht.scrollHeight,Re(i("messages"))))}function Xs(){if(Ft&&ht){let e=(ht.textContent||"").length;Ft.innerHTML=`
|
|
1160
|
+
<div class="text-[10px] text-base-content/30 px-1 select-none">\u{1F4AD} thought ${e?`(${e} chars)`:""}</div>`}Ft=null,ht=null}var zp={haiku:"claude-haiku-4-5",sonnet:"claude-sonnet-4-6",opus:"claude-opus-4-5",sonnet4:"claude-sonnet-4-6",haiku4:"claude-haiku-4-5"};function Kp(e){let[t,...n]=e.slice(1).trim().split(/\s+/),s=n.join(" ");switch(t.toLowerCase()){case"agent":{if(!s)return H(`Current agent: ${$.peek()} \xB7 agents: claude | codex | grok | gemini | cursor`),!0;let a=s.toLowerCase();return["claude","codex","grok","gemini","cursor"].includes(a)?(a!==$.peek()?(l.sessionId=null,Ne(a),se(Oe(a)),document.dispatchEvent(new CustomEvent("agent-changed")),H(`Agent \u2192 ${Z[a]} \xB7 model ${_.peek()} \xB7 new session`)):H(`Agent already ${Z[a]}`),!0):(H(`Unknown agent "${s}" \xB7 valid: claude | codex | grok | gemini | cursor`),!0)}case"model":{if(!s){let c=$.peek(),u=Be(c).map(d=>d.value).join(" | ");return H(`Current model: ${_.peek()} (${c})${u?`
|
|
1161
|
+
Available: ${u}`:""}`),!0}let a=zp[s.toLowerCase()]||s,o=$.peek()||"claude",r=Be(o).some(c=>c.value===a);return r||Xt(o,a),se(a),H(`Model set to ${a}${r?"":" (saved as custom \u2605)"}`),document.dispatchEvent(new CustomEvent("agent-changed")),!0}case"effort":{let a=Zt($.peek(),_.peek());return s?a.includes(s.toLowerCase())?(te.value=s.toLowerCase(),H(`Effort set to ${s.toLowerCase()}`),!0):(H(`Unknown effort level "${s}" \xB7 valid: ${a.join(" | ")}`),!0):(H(`Current effort: ${te.peek()||"(default)"} \xB7 levels: ${a.join(" | ")}`),!0)}case"clear":return lf(),l.sessionId=null,l.lastUsage=null,H("Cleared \xB7 new session"),!0;case"usage":return Jp(),!0;case"help":return H(`Available slash commands:
|
|
1162
1162
|
/agent [claude|codex|grok|gemini|cursor]
|
|
1163
1163
|
/model [haiku|sonnet|opus|<model-id>]
|
|
1164
1164
|
/effort [low|medium|high|xhigh|max]
|
|
1165
1165
|
/usage
|
|
1166
1166
|
/clear
|
|
1167
|
-
/help`),!0;default:return!1}}function Ce(e){if(e==null||Number.isNaN(Number(e)))return"\u2014";let t=Number(e);return t>=1e6?`${(t/1e6).toFixed(2)}M`:t>=1e3?`${(t/1e3).toFixed(1)}k`:String(Math.round(t))}async function
|
|
1168
|
-
`)),
|
|
1169
|
-
`)),(r.tokensUsed!=null||r.windowTokens!=null)&&
|
|
1167
|
+
/help`),!0;default:return!1}}function Ce(e){if(e==null||Number.isNaN(Number(e)))return"\u2014";let t=Number(e);return t>=1e6?`${(t/1e6).toFixed(2)}M`:t>=1e3?`${(t/1e3).toFixed(1)}k`:String(Math.round(t))}async function Jp(){let e=$.peek()||"claude",t=_.peek()||"\u2014",n=l.sessionId,s=[`Agent: ${Z[e]||e}`,`Model: ${t}`,`Session: ${n?n.slice(0,8)+"\u2026":"(new \u2014 send a message first)"}`];if(l.lastUsage&&(!n||l.lastUsageSessionId===n)){let a=l.lastUsage;s.push(`Last turn: \u2191${Ce(a.input_tokens)} \u2193${Ce(a.output_tokens)}`+(a.cache_read_input_tokens?` \xB7 ${Ce(a.cache_read_input_tokens)} cached`:"")+(a.reasoning_tokens?` \xB7 ${Ce(a.reasoning_tokens)} reason`:"")+(a.total_tokens?` \xB7 \u03A3${Ce(a.total_tokens)}`:"")+(a.costUSD!=null?` \xB7 $${Number(a.costUSD).toFixed(4)}`:""))}if(!n){H(s.join(`
|
|
1168
|
+
`)),Si("\u25C8 /usage \xB7 no session yet");return}H("Loading usage\u2026");try{let a=new URLSearchParams({sessionId:n,agent:e}),r=(await x("GET",`/api/usage?${a}`)).context||{};if(r.model&&(s[1]=`Model: ${r.model}`),r.title&&s.push(`Title: ${r.title}`),r.tokensUsed!=null||r.windowTokens!=null||r.usagePercent!=null){let u=r.tokensUsed!=null?Ce(r.tokensUsed):"\u2014",d=r.windowTokens!=null?Ce(r.windowTokens):"\u2014",f=r.usagePercent!=null?`${r.usagePercent}%`:"\u2014";s.push(`Context window: ${u} / ${d} (${f})`)}if(r.turnCount!=null&&s.push(`Turns: ${r.turnCount}`),r.toolCallCount!=null&&s.push(`Tools: ${r.toolCallCount}`),r.sessionDurationSeconds!=null){let u=Math.floor(r.sessionDurationSeconds/60),d=Math.round(r.sessionDurationSeconds%60);s.push(`Duration: ${u}m ${d}s`)}if(r.sessionTotals){let u=r.sessionTotals;s.push(`Session totals: \u2191${Ce(u.input_tokens)} \u2193${Ce(u.output_tokens)}`+(u.cache_read_input_tokens?` \xB7 ${Ce(u.cache_read_input_tokens)} cached`:"")+(u.total_tokens?` \xB7 \u03A3${Ce(u.total_tokens)}`:"")+(u.costUSD?` \xB7 $${Number(u.costUSD).toFixed(4)}`:""))}if(r.lastTurn&&!l.lastUsage){let u=r.lastTurn;s.push(`Last completed turn: \u2191${Ce(u.input_tokens)} \u2193${Ce(u.output_tokens)}`+(u.cache_read_input_tokens?` \xB7 ${Ce(u.cache_read_input_tokens)} cached`:"")+(u.costUSD!=null?` \xB7 $${Number(u.costUSD).toFixed(4)}`:""))}r.note&&s.push(r.note);let c=i("messages");if(c){let u=[...c.children];for(let d=u.length-1;d>=0;d--)if(u[d].textContent==="Loading usage\u2026"){u[d].remove();break}}H(s.join(`
|
|
1169
|
+
`)),(r.tokensUsed!=null||r.windowTokens!=null)&&rf({tokensUsed:r.tokensUsed,windowTokens:r.windowTokens,usagePercent:r.usagePercent,model:r.model||t,turnCount:r.turnCount,toolCallCount:r.toolCallCount}),r.sessionTotals?Lo(r.sessionTotals):r.lastTurn?Lo(r.lastTurn):l.lastUsage&&Lo(l.lastUsage)}catch(a){let o=i("messages");if(o){let r=[...o.children];for(let c=r.length-1;c>=0;c--)if(r[c].textContent==="Loading usage\u2026"){r[c].remove();break}}H(`${s.join(`
|
|
1170
1170
|
`)}
|
|
1171
|
-
(usage fetch failed: ${a.message})`)}}function
|
|
1171
|
+
(usage fetch failed: ${a.message})`)}}function sa(){let e=i("chat-input"),t=e?.value.trim();if(!t||!E.peek())return;if(!on()){H(Io()),wt().then(()=>Wt()).catch(()=>{});return}if(l.sessionId&&!l.lock?.held&&!l.lock?.unmanaged){wt().then(s=>{if(!s?.ok&&!s?.skipped){Wt(),H(Io());return}sa()}).catch(()=>sa());return}if(N.peek()){if($.peek()==="grok"&&l.sessionId){let s="grok",a=te.peek()||Qe(s,_.peek())||"low",o=lt({type:"command",cmd:"turn.start",agent:s,command:t,sessionId:l.sessionId,lockToken:l.lock?.token||void 0,options:{agent:s,cwd:E.peek().path,sessionId:l.sessionId,configDir:l.configDir,model:_.peek(),lockToken:l.lock?.token||void 0,effort:a,...ue.peek()&&{permissionMode:ue.peek()},...ue.peek()==="bypassPermissions"&&{allowDangerouslySkipPermissions:!0}}});dd(t),e.value="",ta(e),ea(""),bi(),H(o?"\u5DF2\u52A0\u5165 Grok \u670D\u52A1\u7AEF\u961F\u5217\uFF0C\u5237\u65B0\u9875\u9762\u4ECD\u4F1A\u663E\u793A":"\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u6D88\u606F\u5C06\u5728\u91CD\u8FDE\u540E\u53D1\u9001");return}Tn.push({key:na(),text:t}),td(),e.value="",ta(e),ea(""),bi(),H(`\u5DF2\u6392\u961F\u4E0B\u4E00\u6761\uFF0C\u5F53\u524D\u56DE\u590D\u7ED3\u675F\u540E\u53D1\u9001\uFF1A${t.length>80?t.slice(0,80)+"\u2026":t}`);return}if(e.value="",ed.delete(na()),ta(e),ea(""),bi(),t.startsWith("/")&&Kp(t))return;N.value=!0,jt();let n=Date.now();if(id(t))cs("shell","$ Shell",t.slice(1).trim(),{ts:n}),lt({type:"command",cmd:"shell.exec",command:t.slice(1).trim(),cwd:E.peek().path})||H("\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u547D\u4EE4\u5DF2\u5165\u961F\uFF0C\u91CD\u8FDE\u540E\u53D1\u9001");else{ls(),cs("user","You",t,{ts:n,forceStick:!0});let s=$.peek()||"claude",a=te.peek()||Qe(s,_.peek())||(s==="grok"?"low":""),o=ue.peek();l.sessionId&&se(_.peek(),s,l.sessionId),lt({type:"command",cmd:"turn.start",agent:s,command:t,sessionId:l.sessionId,lockToken:l.lock?.token||void 0,options:{agent:s,cwd:E.peek().path,sessionId:l.sessionId,configDir:l.configDir,model:_.peek(),lockToken:l.lock?.token||void 0,...a&&{effort:a},...o&&{permissionMode:o},...o==="bypassPermissions"&&{allowDangerouslySkipPermissions:!0}}})||H("\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u6D88\u606F\u5DF2\u5165\u961F\uFF0C\u91CD\u8FDE\u540E\u53D1\u9001")}}function ea(e){let t=id(e),n=i("chat-input"),s=i("send-btn");if(!n||!s)return;n.classList.toggle("textarea-warning",t),n.style.fontFamily=t?"monospace":"",s.classList.toggle("btn-warning",t),s.classList.toggle("btn-primary",!t),s.textContent=t?"Run":"Send";let a=Z[$.peek()]||"agent",o=typeof window<"u"&&window.matchMedia("(max-width: 640px)").matches;t?n.placeholder=o?"Shell \u547D\u4EE4\u2026":"Shell command (without !)\u2026":n.placeholder=o?`\u95EE ${a}\u2026`:`Ask ${a}\u2026 or !cmd for shell`}function id(e){let t=String(e||"").trimStart();return t.startsWith("!")&&!/^!\[[^\]]*\]\([^)]+\)/.test(t)}function Qp(){return typeof window<"u"&&window.matchMedia("(max-width: 640px)").matches,72}function ta(e){e.style.height="auto",e.style.height=Math.min(e.scrollHeight,Qp())+"px"}var Vp=200,Yp=500;function Co(e){let t=O(e);if(t==null)return"";let n=new Date(t);if(Number.isNaN(n.getTime()))return"";let s=new Date,a=n.toDateString()===s.toDateString(),o=n.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1});return a?o:`${n.toLocaleDateString(void 0,{month:"numeric",day:"numeric"})} ${o}`}function Mo(e){let t=O(e);return t==null?"":new Date(t).toISOString()}function Xp(e,t,n){if(e==="system")return t;let s=Co(n),a=Mo(n),o=s?`<div class="msg-ts" title="${p(a)}">${p(s)}</div>`:"";return`<div class="msg-row ${e==="user"?"user":e==="shell"||e==="shell-err"?"assistant":e} px-2" data-ts="${p(a)}">${t}${o}</div>`}function Zp(e,t,n){let s='<button class="msg-expand-btn text-[10px] text-primary/70 mt-1.5 block cursor-pointer hover:text-primary">\u25BC Show more</button>',a;switch(e){case"user":{let r=/!\[.*?\]\(.*?\)/.test(t)?Eo(t):null,c=t.length>Vp,u=c?`<div class="msg-body">${r??p(t.trimEnd())}</div>${s}`:r??p(t.trimEnd());a=`<div class="max-w-[80%] rounded-2xl rounded-tr-sm px-3 py-2 text-sm bg-primary/15 border border-primary/20 text-base-content break-words${c?" msg-card":""}${r?" md":""}"${r?"":' style="white-space:pre-wrap"'}>${u}</div>`;break}case"assistant":{let o=t.length>Yp,r=o?`<div class="msg-body">${Eo(t)}</div>${s}`:Eo(t);a=`<div class="msg-assistant-content max-w-[min(92%,52rem)] rounded-2xl rounded-tl-sm px-3.5 py-2.5 text-sm bg-base-200 border border-base-300/40 break-words md leading-relaxed${o?" msg-card":""}">${r}</div>`;break}case"error":a=`<div class="max-w-[88%] rounded-2xl rounded-tl-sm px-3 py-2 text-sm bg-error/10 border border-error/20 text-error break-words" style="white-space:pre-wrap">${p(t)}</div>`;break;case"shell":case"shell-err":a=`<div class="w-full max-w-[96%] rounded-lg code-surface px-3 py-2 text-sm font-mono ${e==="shell-err"?"text-error":""} break-words" style="white-space:pre-wrap">${p(t)}</div>`;break;case"system":return`<div class="text-center text-[11px] text-base-content/30 py-0.5 select-none">${p(t)}</div>`;default:a=`<div class="rounded-lg px-3 py-2 text-sm bg-base-300 break-words" style="white-space:pre-wrap">${p(t)}</div>`}return Xp(e,a,n)}function cs(e,t,n,s={}){let a=i("messages");if(!a)return;let o=O(s.ts)??(e==="system"?null:Date.now());a.insertAdjacentHTML("beforeend",Zp(e,n,o)),pd(a.lastElementChild),e==="assistant"&&ud(a.lastElementChild,n,s),Re(a,!!s.forceStick)}function H(e){cs("system","",e)}var Gt=[],wo=0,Qc=!1;async function ef(e,t){let n=t||`upload-${Date.now()}`,s=await ld(e,n),a=ct({"x-filename":n});delete a["Content-Type"],s?.type&&!a["Content-Type"]&&!a["content-type"]&&(a["Content-Type"]=s.type);let o=await fetch("/api/upload-image",{method:"POST",headers:a,body:s});if(!o.ok){let c=await o.json().catch(()=>({}));throw new Error(c.error||`Upload failed: ${o.status}`)}let r=await o.json();if(!r?.path)throw new Error("upload returned no path");return r.path}function tf(e,t){return e.length>=8&&e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71?"image/png":e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255?"image/jpeg":e.length>=6&&String.fromCharCode(...e.slice(0,6))==="GIF87a"?"image/gif":e.length>=12&&String.fromCharCode(...e.slice(8,12))==="WEBP"?"image/webp":t||"image/png"}async function ld(e,t){if(!e||!ki({type:e.type,name:t}))return e;let n;try{n=(await e.slice(0,80).text()).trim()}catch{return e}if(!/^(?:data:image\/[a-z0-9.+-]+;base64,|iVBORw0KGgo|\/9j\/|R0lGOD|UklGR)/i.test(n))return e;let s;try{s=(await e.text()).trim()}catch{return e}let o=/^data:image\/[a-z0-9.+-]+;base64,([a-z0-9+/=\s]+)$/i.exec(s)?.[1]||s;if(!o||!/^[a-z0-9+/=\s]+$/i.test(o)||o.length%4===1)return e;try{let r=atob(o.replace(/\s/g,"")),c=Uint8Array.from(r,f=>f.charCodeAt(0)),u=tf(c,e.type);return u===(e.type||"image/png")&&!/^(image\/png|image\/jpeg|image\/gif|image\/webp)$/.test(u)?e:c.length>=3&&(c[0]===137&&c[1]===80&&c[2]===78||c[0]===255&&c[1]===216&&c[2]===255||String.fromCharCode(...c.slice(0,6))==="GIF87a"||String.fromCharCode(...c.slice(8,12))==="WEBP")?new Blob([c],{type:u}):e}catch{return e}}function nf(e,t){if(!e)return;let n=e.selectionStart??e.value.length,s=e.selectionEnd??e.value.length,o=(n>0&&e.value[n-1]!==`
|
|
1172
1172
|
`?`
|
|
1173
1173
|
`:"")+t+`
|
|
1174
|
-
`;e.value=e.value.slice(0,n)+o+e.value.slice(s),e.selectionStart=e.selectionEnd=n+o.length,e.dispatchEvent(new Event("input"))}function
|
|
1174
|
+
`;e.value=e.value.slice(0,n)+o+e.value.slice(s),e.selectionStart=e.selectionEnd=n+o.length,e.dispatchEvent(new Event("input"))}function ki(e){return e?e.type&&e.type.startsWith("image/")?!0:/\.(png|jpe?g|gif|webp|bmp|svg|heic|heif|avif)$/i.test(e.name||""):!1}function sf(e,t){let n=e?.name||t.split("/").pop()||"file";if(ki(e)){wo+=1;let a=`img${wo}`;return{ref:``,label:a,kind:"image"}}wo+=1;let s=`file${wo}`;return{ref:`[${s}](${t})`,label:s,kind:"file"}}function bi(){for(let e of Gt)if(e.previewUrl)try{URL.revokeObjectURL(e.previewUrl)}catch{}Gt.length=0,$i()}function $i(){let e=i("chat-attach-bar");if(e){if(!Gt.length){e.classList.add("hidden"),e.innerHTML="";return}e.classList.remove("hidden"),e.innerHTML=Gt.map((t,n)=>`
|
|
1175
1175
|
<div class="chat-thumb relative" title="${p(t.ref||t.path)}">
|
|
1176
1176
|
${t.previewUrl?`<img src="${t.previewUrl}" alt="${p(t.label||"img")}">`:`<span class="chat-thumb-path">${p(t.label||t.name||"file")}</span>`}
|
|
1177
1177
|
<span class="chat-thumb-label">${p(t.label||t.kind||"")}</span>
|
|
1178
1178
|
<button type="button" class="chat-thumb-x" data-rm-attach="${n}" aria-label="remove">\u2715</button>
|
|
1179
|
-
</div>`).join("")}}async function
|
|
1179
|
+
</div>`).join("")}}async function af(e){if(!e)return;let t=e.name||`upload-${Date.now()}`,n=await ld(e,t),s=await ef(n,t),{ref:a,label:o,kind:r}=sf(e,s),c="";if(r==="image")try{c=URL.createObjectURL(n)}catch{}return Gt.push({path:s,ref:a,label:o,kind:r,name:t,previewUrl:c}),$i(),nf(i("chat-input"),a),s}async function Ao(e){let t=[...e||[]].filter(Boolean);if(!t.length)return;let n=i("chat-input");n&&(n.disabled=!0);try{for(let s of t)try{await af(s)}catch(a){H(`\u4E0A\u4F20\u5931\u8D25 ${s.name||"file"}: ${a.message}`)}}finally{n&&(n.disabled=!1,n.focus())}}function of(){let e=i("chat-file-input");if(e){e.value="",e.click();return}let t=document.createElement("input");t.type="file",t.accept="image/*,*/*",t.multiple=!0,t.addEventListener("change",()=>Ao(t.files)),t.click()}function cd(){document.addEventListener("paste",async e=>{let t=i("chat-input");if(!t)return;let n=i("chat-composer");if(!(n&&(n.contains(document.activeElement)||document.activeElement===t))&&document.activeElement!==t)return;let a=[...e.clipboardData?.items||[]],o=[];for(let u of a)if(u.kind==="file"){let d=u.getAsFile();d&&o.push(d)}let r=o.filter(u=>ki(u)),c=r.length?r:o;c.length&&(e.preventDefault(),await Ao(c))}),!Qc&&(Qc=!0,document.addEventListener("dragover",e=>{let t=i("chat-composer");!t||!e.dataTransfer?.types?.includes("Files")||!t.contains(e.target)&&e.target!==t||(e.preventDefault(),t.classList.add("chat-drop-active"))}),document.addEventListener("dragleave",e=>{let t=i("chat-composer");t&&(e.target===t||t.contains(e.target))&&(t.contains(e.relatedTarget)||t.classList.remove("chat-drop-active"))}),document.addEventListener("drop",async e=>{let t=i("chat-composer");if(!t||(t.classList.remove("chat-drop-active"),!t.contains(e.target)&&e.target!==t))return;let n=[...e.dataTransfer?.files||[]];n.length&&(e.preventDefault(),await Ao(n))}))}function Mt(e){return e>=1e3?`${(e/1e3).toFixed(1)}k`:String(e)}function Si(e){let t=i("messages");t&&(t.insertAdjacentHTML("beforeend",`<div class="token-bar select-none">
|
|
1180
1180
|
<span class="token-bar-mark">\u25C8</span><span class="token-bar-text">${p(e)}</span>
|
|
1181
|
-
</div>`),Re(t))}function
|
|
1182
|
-
${String(e||"")}`}function
|
|
1181
|
+
</div>`),Re(t))}function Lo(e){if(!e)return;let t=e.input_tokens??e.inputTokens??0,n=e.output_tokens??e.outputTokens??0,s=e.total_tokens??e.totalTokens??t+n,a=e.cache_read_input_tokens??e.cachedReadTokens?` \xB7 ${Mt(e.cache_read_input_tokens??e.cachedReadTokens)} cached`:"",o=e.cache_creation_input_tokens??e.cacheCreationInputTokens?` \xB7 ${Mt(e.cache_creation_input_tokens??e.cacheCreationInputTokens)} cache-write`:"",r=e.reasoning_tokens??e.reasoningTokens?` \xB7 ${Mt(e.reasoning_tokens??e.reasoningTokens)} reason`:"",c=e.costUSD??e.cost_usd,u=c!=null?` \xB7 $${Number(c).toFixed(4)}`:"",d=s?` \xB7 \u03A3${Mt(s)}`:"";Si(`\u2191${Mt(t)} \u2193${Mt(n)}${a}${o}${r}${d}${u}`)}function rf(e){if(!e)return;let t=e.tokensUsed??e.contextTokensUsed,n=e.windowTokens??e.contextWindowTokens,s=e.usagePercent??e.contextWindowUsage;if(t==null&&n==null&&s==null)return;let a=[];t!=null&&n!=null?a.push(`context ${Mt(t)} / ${Mt(n)}`):t!=null&&a.push(`context ${Mt(t)}`),s!=null&&a.push(`${s}%`),e.model&&a.push(e.model),e.turnCount!=null&&a.push(`${e.turnCount} turns`),e.toolCallCount!=null&&a.push(`${e.toolCallCount} tools`),Si(`\u25A3 ${a.join(" \xB7 ")}`)}function lf(){let e=i("messages"),t=i("permission-requests");e&&(e.innerHTML="",delete e.dataset.historyPainting),t&&(t.innerHTML=""),l.shellBubble=null,mt=null,st=Ge=null,Ft=ht=null,Do.clear(),xi.clear()}function cf(e,t=l.sessionId){return`${t||""}
|
|
1182
|
+
${String(e||"")}`}function dd(e,t=l.sessionId){let n=cf(e,t);!e||xi.has(n)||(xi.add(n),cs("user","You",e,{ts:Date.now(),forceStick:!0}),i("messages")?.lastElementChild?.classList.add("queued-user-msg"))}function df(e){if((e.sessionId||l.sessionId)!==l.sessionId)return;let t=Array.isArray(e.items)?e.items.filter(n=>typeof n=="string"&&n.trim()):[];for(let n of t)dd(n,e.sessionId||l.sessionId);t.length&&H(`\u231B Grok queue \xB7 ${t.length} prompt${t.length===1?"":"s"} waiting`)}function ud(e,t,n={}){if(!e||!t||e.querySelector(".msg-actions"))return;let s=`a${++Np}`;Do.set(s,{text:t,historyIndex:Number.isInteger(n.historyIndex)?n.historyIndex:null,sessionId:l.sessionId,agent:l.agent||$.peek()||"claude",machineId:l.machineId||null});let a=!["gemini","cursor"].includes(l.agent||$.peek()||"claude"),o=document.createElement("div");o.className="msg-actions",o.innerHTML=`
|
|
1183
1183
|
<button type="button" class="msg-action-btn" data-copy-message="${p(s)}" title="Copy answer">Copy</button>
|
|
1184
|
-
${a?`<button type="button" class="msg-action-btn" data-fork-message="${p(s)}" title="Start a branch from this answer">Fork</button>`:""}`;let r=e.querySelector(".msg-ts");e.insertBefore(o,r||null)}async function
|
|
1184
|
+
${a?`<button type="button" class="msg-action-btn" data-fork-message="${p(s)}" title="Start a branch from this answer">Fork</button>`:""}`;let r=e.querySelector(".msg-ts");e.insertBefore(o,r||null)}async function uf(e){let t=Do.get(e.dataset.copyMessage||"");if(t){try{await navigator.clipboard.writeText(t.text),e.textContent="Copied"}catch{e.textContent="Failed"}setTimeout(()=>{e.textContent="Copy"},1300)}}async function pf(e){let t=Do.get(e.dataset.forkMessage||"");if(!(!t||!t.sessionId||t.sessionId!==l.sessionId)){e.disabled=!0,e.textContent="Forking\u2026";try{let n=await x("POST",`/api/sessions/${encodeURIComponent(t.sessionId)}/fork`,{sourceAgent:t.agent,...t.historyIndex!=null?{upTo:t.historyIndex}:{},assistantText:t.text},void 0,{machineId:t.machineId||void 0});if(!n?.success||!n.targetSessionId)throw new Error("Fork did not create a session");let s={parentSessionId:t.sessionId,parentAgent:t.agent,parentMachineId:t.machineId,forkMessageIndex:Number.isInteger(n.forkMessageIndex)?n.forkMessageIndex:t.historyIndex,forkedAt:Date.now()},a=await x("PUT","/api/sessions/meta",{sessionId:n.targetSessionId,agent:n.targetAgent||t.agent,branch:s,machineId:t.machineId||void 0},void 0,{machineId:t.machineId||void 0}),o=J(n.targetAgent||t.agent,n.targetSessionId,t.machineId);T.value={...T.peek(),[o]:{favorite:!!a?.favorite,notes:a?.notes||"",title:a?.title||"",hidden:!!a?.hidden,branch:a?.branch||s,updatedAt:a?.updatedAt||Date.now()}};let[{loadAllSessions:r},{resumeSession:c}]=await Promise.all([Promise.resolve().then(()=>(Tt(),lo)),Promise.resolve().then(()=>(rs(),ii))]);await r({waitFresh:!0}),await c(n.targetSessionId,E.peek()?.path||null,l.configDir||null,n.targetAgent||t.agent,t.machineId||null),H("Fork created \u2014 this branch can now continue independently.")}catch(n){e.textContent="Fork failed",H(`Fork failed: ${n.message}`),setTimeout(()=>{e.textContent="Fork"},1800)}finally{e.disabled=!1,e.textContent==="Forking\u2026"&&(e.textContent="Fork")}}}function ff(e){let t=i("messages");if(!t)return null;let n=e==="shell-err"?" text-error":"";return t.insertAdjacentHTML("beforeend",`<div class="mx-2 rounded-lg code-surface px-3 py-2 text-sm font-mono${n} whitespace-pre-wrap break-words"></div>`),Re(t),t.lastElementChild}function mf(e,t){e&&(e.textContent+=t,Re(e.closest("#messages")))}var mt=null;function hf(e){let t=typeof e.input=="object"?JSON.stringify(e.input,null,2):String(e.input||""),s=((typeof e.input=="object"?Object.values(e.input).find(a=>typeof a=="string"&&a.trim()):t)||"").replace(/\n/g," ").slice(0,_e.peek()==="full"?120:80);return{inputStr:t,preview:s}}function Vc(e,{inBatch:t=!1}={}){let{inputStr:n,preview:s}=hf(e);return`<div class="tool-card${t?" tool-batch-item":""} cursor-pointer select-none px-2 py-1">
|
|
1185
1185
|
<div class="flex items-center gap-1.5 text-xs font-mono">
|
|
1186
1186
|
<span class="text-warning">\u26A1</span>
|
|
1187
1187
|
<span class="text-warning font-semibold">${p(e.name||"tool")}</span>
|
|
@@ -1189,21 +1189,21 @@ ${String(e||"")}`}function nd(e,t=l.sessionId){let n=Zp(e,t);!e||pi.has(n)||(pi.
|
|
|
1189
1189
|
<span class="tool-chevron text-[10px] text-base-content/40">\u25B6</span>
|
|
1190
1190
|
</div>
|
|
1191
1191
|
<div class="tool-detail">${p(n)}</div>
|
|
1192
|
-
</div>`}function
|
|
1192
|
+
</div>`}function gf(e){let t=[...new Set(e.names)],n=t.slice(0,4).join(", ")+(t.length>4?"\u2026":""),s=e.el.querySelector(".tool-batch-summary");s&&(s.innerHTML=`<span class="text-warning">\u26A1</span>
|
|
1193
1193
|
<span class="font-semibold text-base-content/70">${e.count} tool${e.count===1?"":"s"}</span>
|
|
1194
1194
|
<span class="text-base-content/40 truncate flex-1">${p(n)}</span>
|
|
1195
|
-
<span class="tool-chevron text-[10px] text-base-content/40">\u25B6</span>`)}function
|
|
1196
|
-
<div class="msg-row assistant px-2" data-ts="${p(
|
|
1195
|
+
<span class="tool-chevron text-[10px] text-base-content/40">\u25B6</span>`)}function ls(){mt=null}function bf(e,t={}){let n=i("messages");if(!n)return;let s=_e.peek()||"normal",a=O(t.ts);if(s==="clean"){if(!mt||!n.contains(mt.el)){let u=Co(a),d=Mo(a);n.insertAdjacentHTML("beforeend",`
|
|
1196
|
+
<div class="msg-row assistant px-2" data-ts="${p(d)}">
|
|
1197
1197
|
<div class="tool-batch w-full max-w-[96%] px-2 py-1.5">
|
|
1198
1198
|
<div class="tool-batch-summary flex items-center gap-1.5 text-xs font-mono"></div>
|
|
1199
1199
|
<div class="tool-batch-list"></div>
|
|
1200
1200
|
</div>
|
|
1201
|
-
${u?`<div class="msg-ts" title="${p(
|
|
1202
|
-
</div>`),mt={el:n.lastElementChild.querySelector(".tool-batch"),names:[],count:0}}mt.names.push(e.name||"tool"),mt.count++,mt.el.querySelector(".tool-batch-list")?.insertAdjacentHTML("beforeend",
|
|
1201
|
+
${u?`<div class="msg-ts" title="${p(d)}">${p(u)}</div>`:""}
|
|
1202
|
+
</div>`),mt={el:n.lastElementChild.querySelector(".tool-batch"),names:[],count:0}}mt.names.push(e.name||"tool"),mt.count++,mt.el.querySelector(".tool-batch-list")?.insertAdjacentHTML("beforeend",Vc(e,{inBatch:!0})),gf(mt),Re(n);return}mt=null;let o=Co(a),r=Mo(a);n.insertAdjacentHTML("beforeend",`
|
|
1203
1203
|
<div class="msg-row assistant px-2" data-ts="${p(r)}">
|
|
1204
|
-
<div class="w-full max-w-[96%]">${
|
|
1204
|
+
<div class="w-full max-w-[96%]">${Vc(e)}</div>
|
|
1205
1205
|
${o?`<div class="msg-ts" title="${p(r)}">${p(o)}</div>`:""}
|
|
1206
|
-
</div>`),Re(n)}function
|
|
1206
|
+
</div>`),Re(n)}function Yc(){let e=i("messages");e&&e.setAttribute("data-density",_e.peek()||"normal")}function vf(e){let t=e.request_id||e.requestId;if(!t||i(`perm-${t}`))return;let n=e.tool_input?JSON.stringify(e.tool_input).slice(0,200):"";i("permission-requests")?.insertAdjacentHTML("beforeend",`
|
|
1207
1207
|
<div id="perm-${t}" class="perm-banner mx-3 mb-2 rounded-lg border border-warning/25 bg-warning/8 p-3">
|
|
1208
1208
|
<div class="text-xs text-warning font-semibold mb-1">\u26A0\uFE0F Permission Required</div>
|
|
1209
1209
|
<div class="font-mono text-xs text-base-content/60 break-all mb-2">
|
|
@@ -1213,61 +1213,61 @@ ${String(e||"")}`}function nd(e,t=l.sessionId){let n=Zp(e,t);!e||pi.has(n)||(pi.
|
|
|
1213
1213
|
<button class="btn btn-success btn-xs" data-perm-id="${t}" data-perm-allow="1">Allow</button>
|
|
1214
1214
|
<button class="btn btn-error btn-xs" data-perm-id="${t}" data-perm-allow="0">Deny</button>
|
|
1215
1215
|
</div>
|
|
1216
|
-
</div>`),Re(i("messages"))}var
|
|
1216
|
+
</div>`),Re(i("messages"))}var Xc=!1;function xf(){if(Xc||typeof marked>"u")return;let e=s=>String(s??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),t=(s,a)=>{let o=String(a||"").trim().split(/\s+/)[0]||"",r=o||"text",c=o?`language-${p(o)}`:"";return`<div class="code-block">
|
|
1217
1217
|
<div class="code-block-header">
|
|
1218
1218
|
<span class="code-block-lang">${p(r)}</span>
|
|
1219
1219
|
<button type="button" class="code-copy" data-copy="1" title="Copy code">Copy</button>
|
|
1220
1220
|
</div>
|
|
1221
|
-
<pre><code class="hljs ${
|
|
1222
|
-
</div>`},n={code(s,a){return s&&typeof s=="object"&&s.text!=null?t(s.text,s.lang||a):t(s,a)},table(s,a){return s&&typeof s=="object"&&!Array.isArray(s)&&s.header?!1:`<div class="table-wrap"><table><thead>${s}</thead><tbody>${a}</tbody></table></div>`},html(s){return e(s)}};try{if(typeof marked.use=="function")marked.use({gfm:!0,breaks:!0,renderer:n});else if(typeof marked.setOptions=="function"){let s=new marked.Renderer;s.code=n.code,s.table=n.table,marked.setOptions({gfm:!0,breaks:!0,renderer:s})}}catch(s){console.warn("[md] marked setup failed",s)}
|
|
1221
|
+
<pre><code class="hljs ${c}">${e(s)}</code></pre>
|
|
1222
|
+
</div>`},n={code(s,a){return s&&typeof s=="object"&&s.text!=null?t(s.text,s.lang||a):t(s,a)},table(s,a){return s&&typeof s=="object"&&!Array.isArray(s)&&s.header?!1:`<div class="table-wrap"><table><thead>${s}</thead><tbody>${a}</tbody></table></div>`},html(s){return e(s)}};try{if(typeof marked.use=="function")marked.use({gfm:!0,breaks:!0,renderer:n});else if(typeof marked.setOptions=="function"){let s=new marked.Renderer;s.code=n.code,s.table=n.table,marked.setOptions({gfm:!0,breaks:!0,renderer:s})}}catch(s){console.warn("[md] marked setup failed",s)}Xc=!0}function Eo(e){if(typeof marked>"u")return p(e);try{return xf(),Ve(e,{fallback:()=>p(e)})}catch{return p(e)}}function yf(e){!e||typeof hljs>"u"||(e.querySelectorAll("pre code:not(.hljs)").forEach(t=>{try{hljs.highlightElement(t)}catch{}}),e.querySelectorAll("pre code.hljs").forEach(t=>{t.classList.add("hljs")}))}function pd(e){yf(e),yt(e),xt(e)}function fd(){Yc(),pr(),je(me,s=>{Zs(),jt();let a=i("ws-banner"),o=i("ws-banner-text");if(!a)return;if(s==="open"||s==="idle"){a.classList.add("hidden"),o&&(o.textContent="");return}if(s==="connecting"&&!$o){a.classList.add("hidden");return}a.classList.remove("hidden");let r=s==="offline"?"\u7F51\u7EDC\u5DF2\u65AD\u5F00\uFF0C\u6062\u590D\u540E\u4F1A\u81EA\u52A8\u91CD\u8FDE":s==="connecting"?"\u6B63\u5728\u8FDE\u63A5\u2026":"\u8FDE\u63A5\u4E2D\u65AD\uFF0C\u6B63\u5728\u91CD\u8FDE\u2026\uFF08\u7184\u5C4F\u6216\u5207\u7F51\u65F6\u5E38\u89C1\uFF09";o?o.textContent=r:a.textContent=r}),je(E,()=>jt()),b.on("click","#messages a, #chat-log a, .md-body a",(s,a)=>{let o=a.getAttribute("href")||"",r=E.peek()?.path||"";ir(o,r)&&(s.preventDefault(),s.stopPropagation())}),b.on("click","#ws-banner-retry",s=>{s.preventDefault(),Up()}),je(N,s=>{i("send-btn")?.classList.toggle("hidden",s),i("stop-btn")?.classList.toggle("hidden",!s),Wt(),s||i("send-btn")?.toggleAttribute("disabled",!on());let a=i("messages");if(!a)return;let o=i("typing-indicator");s&&!o?(a.insertAdjacentHTML("beforeend",'<div id="typing-indicator" class="flex justify-start px-2"><div class="flex items-center gap-1.5 rounded-2xl rounded-tl-sm px-3 py-2 bg-base-200 text-xs text-base-content/40"><span class="dot"></span><span class="dot"></span><span class="dot"></span></div></div>'),Re(a)):s||(o?.remove(),ls()),jt()}),je(_e,()=>Yc()),document.addEventListener("session-lock-changed",()=>Wt()),Wt(),b.on("keydown","#chat-input",s=>{if(s.key!=="Enter")return;let a=s.metaKey||s.ctrlKey,o=window.matchMedia("(max-width: 640px)").matches&&!s.shiftKey&&!a;(a||o)&&(s.preventDefault(),sa())}),b.on("submit","#chat-form",s=>{s.preventDefault(),sa()}),b.on("input","#chat-input",(s,a)=>{ta(a),ea(a.value)}),b.on("click","#btn-attach",s=>{s.preventDefault(),of()}),b.on("change","#chat-file-input",(s,a)=>{let o=a?.files;o?.length&&Ao(o),a&&(a.value="")}),b.on("click","[data-rm-attach]",(s,a)=>{s.preventDefault(),s.stopPropagation();let o=parseInt(a.dataset.rmAttach,10);if(Number.isNaN(o)||o<0||o>=Gt.length)return;let r=Gt[o];if(r?.previewUrl)try{URL.revokeObjectURL(r.previewUrl)}catch{}let c=i("chat-input");c&&r?.ref&&(c.value=c.value.split(r.ref).join("").replace(/\n{3,}/g,`
|
|
1223
1223
|
|
|
1224
|
-
`),
|
|
1224
|
+
`),c.dispatchEvent(new Event("input"))),Gt.splice(o,1),$i()}),b.on("click","[data-perm-id]",(s,a)=>{lt({type:"command",cmd:"approval.respond",requestId:a.dataset.permId,allow:a.dataset.permAllow==="1",sessionId:l.sessionId}),a.closest(".perm-banner")?.remove()}),b.on("click",".tool-card",(s,a)=>{let o=a.closest(".tool-batch");if(o&&!o.classList.contains("open")&&!a.classList.contains("tool-batch-item"))return;s.stopPropagation();let r=i("messages"),c=a.getBoundingClientRect().top;if(a.classList.toggle("open"),r){let u=a.getBoundingClientRect().top;r.scrollTop+=u-c}}),b.on("click",".tool-batch",(s,a)=>{if(s.target.closest(".tool-card")&&a.classList.contains("open"))return;let o=i("messages"),r=a.getBoundingClientRect().top;if(a.classList.toggle("open"),o){let c=a.getBoundingClientRect().top;o.scrollTop+=c-r}});let e=i("messages"),t=i("scroll-top-btn"),n=i("scroll-bottom-btn");if(e&&t&&n){let s=()=>{let a=e.scrollHeight-e.clientHeight>200;t.classList.toggle("hidden",!a||e.scrollTop<200),n.classList.toggle("hidden",!a||_p(e))};e.addEventListener("scroll",s,{passive:!0}),new ResizeObserver(s).observe(e),new MutationObserver(s).observe(e,{childList:!0,subtree:!0}),t.addEventListener("click",()=>e.scrollTo({top:0,behavior:"smooth"})),n.addEventListener("click",()=>{Zc(e)?.setFollowing(!0),e.scrollTo({top:e.scrollHeight,behavior:"smooth"})}),s()}b.on("click",".msg-expand-btn",(s,a)=>{s.stopPropagation();let r=a.closest(".msg-card").classList.toggle("open");a.textContent=r?"\u25B2 Show less":"\u25BC Show more"}),b.on("click","[data-copy-message]",(s,a)=>{s.preventDefault(),s.stopPropagation(),uf(a)}),b.on("click","[data-fork-message]",(s,a)=>{s.preventDefault(),s.stopPropagation(),pf(a)}),b.on("click",".code-copy",async(s,a)=>{s.preventDefault(),s.stopPropagation();let c=a.closest(".code-block")?.querySelector("pre code")?.textContent??"";try{await navigator.clipboard.writeText(c),a.textContent="Copied",a.classList.add("copied"),setTimeout(()=>{a.textContent="Copy",a.classList.remove("copied")},1400)}catch{a.textContent="Failed",setTimeout(()=>{a.textContent="Copy"},1400)}})}G();W();ce();nr();qn();sn();an();rr();function wf(e){let t=e.split(".").pop()?.toLowerCase();return{js:"\u{1F4C4}",ts:"\u{1F4C4}",jsx:"\u{1F4C4}",tsx:"\u{1F4C4}",py:"\u{1F40D}",md:"\u{1F4DD}",json:"\u2699\uFE0F",html:"\u{1F310}",css:"\u{1F3A8}",sh:"\u26A1",env:"\u{1F511}",docx:"\u{1F4D8}",pptx:"\u{1F4D9}",xlsx:"\u{1F4D7}",pdf:"\u{1F4D5}"}[t]||"\u{1F4C4}"}function hd(e){let t=(e||"").split("/").pop()||"",n=t.lastIndexOf(".");return n>=0?t.slice(n+1).toLowerCase():""}function gd(e){let t=hd(e);return t==="docx"||t==="pptx"||t==="xlsx"||t==="pdf"?t:null}function bd(e){let t=hd(e);return t==="md"||t==="markdown"||t==="mdx"}function kf(e){let t=atob(e),n=new Uint8Array(t.length);for(let s=0;s<t.length;s++)n[s]=t.charCodeAt(s);return n.buffer}var Li=new Map;function _o(e){if(Li.has(e))return Li.get(e);let t=new Promise((n,s)=>{let a=document.querySelector(`script[data-src="${e}"]`);if(a){if(a.dataset.loaded==="1")return n();a.addEventListener("load",()=>n()),a.addEventListener("error",()=>s(new Error(`Failed to load ${e}`)));return}let o=document.createElement("script");o.src=e,o.async=!0,o.dataset.src=e,o.onload=()=>{o.dataset.loaded="1",n()},o.onerror=()=>s(new Error(`Failed to load ${e}`)),document.head.appendChild(o)});return Li.set(e,t),t}function $f(e){let n=((e||"").split("/").pop()||"").toLowerCase(),s={dockerfile:"dockerfile",makefile:"makefile",gemfile:"ruby",rakefile:"ruby",procfile:"yaml","cmakelists.txt":"cmake"};if(s[n])return s[n];let a=n.includes(".")?n.split(".").pop():"";return{js:"javascript",mjs:"javascript",cjs:"javascript",jsx:"javascript",ts:"typescript",tsx:"typescript",mts:"typescript",cts:"typescript",py:"python",pyw:"python",pyi:"python",rb:"ruby",go:"go",rs:"rust",java:"java",kt:"kotlin",kts:"kotlin",c:"c",h:"c",cpp:"cpp",cc:"cpp",cxx:"cpp",hpp:"cpp",hh:"cpp",cs:"csharp",swift:"swift",php:"php",scala:"scala",sh:"bash",bash:"bash",zsh:"bash",fish:"bash",ps1:"powershell",psm1:"powershell",html:"xml",htm:"xml",xhtml:"xml",xml:"xml",svg:"xml",css:"css",scss:"scss",less:"less",json:"json",jsonc:"json",json5:"json",yml:"yaml",yaml:"yaml",toml:"ini",ini:"ini",conf:"ini",env:"bash",md:"markdown",mdx:"markdown",markdown:"markdown",sql:"sql",graphql:"graphql",gql:"graphql",vue:"xml",svelte:"xml",r:"r",lua:"lua",pl:"perl",pm:"perl",dart:"dart",ex:"elixir",exs:"elixir",erl:"erlang",zig:"zig",nim:"nim",clj:"clojure",cljs:"clojure",diff:"diff",patch:"diff",dockerfile:"dockerfile"}[a]||""}function Sf(e){!e||typeof hljs>"u"||e.querySelectorAll("pre code.file-preview-code").forEach(t=>{try{delete t.dataset.highlighted,hljs.highlightElement(t)}catch{}})}function ds(e,t,n){let s=ya(t);return`
|
|
1225
1225
|
<div class="flex items-center gap-2 px-4 py-1.5 border-b border-base-300 flex-shrink-0 bg-base-200">
|
|
1226
1226
|
<span class="text-xs text-base-content/40 flex-1 truncate">${p(e)} \xB7 ${p(s)}${n?` \xB7 <span class="text-primary/70">${p(n)}</span>`:""}</span>
|
|
1227
1227
|
<button type="button" class="btn btn-ghost btn-xs" data-download-path="${p(e)}">\u2193 Download</button>
|
|
1228
|
-
</div>`}function
|
|
1228
|
+
</div>`}function Lf(e){return!Array.isArray(e)||!e.length?'<div class="p-4 text-xs text-base-content/40">Empty directory</div>':(e.sort((t,n)=>n.isDir-t.isDir||t.name.localeCompare(n.name)),e.map(t=>`
|
|
1229
1229
|
<div class="flex items-center gap-2 px-4 py-1.5 hover:bg-base-300 group"
|
|
1230
1230
|
${t.isDir?`data-dir-path="${p(t.path)}"`:`data-file-path="${p(t.path)}"`}>
|
|
1231
|
-
<span class="cursor-pointer flex-shrink-0">${t.isDir?"\u{1F4C1}":
|
|
1231
|
+
<span class="cursor-pointer flex-shrink-0">${t.isDir?"\u{1F4C1}":wf(t.name)}</span>
|
|
1232
1232
|
<span class="text-sm flex-1 truncate cursor-pointer ${t.isDir?"text-primary":""}">${p(t.name)}</span>
|
|
1233
1233
|
${t.isDir?"":`
|
|
1234
1234
|
<button type="button" class="file-row-action btn btn-ghost btn-xs px-1.5 text-base-content/50 hover:text-base-content"
|
|
1235
1235
|
data-download-path="${p(t.path)}" title="Download" aria-label="Download">\u2193</button>
|
|
1236
1236
|
<button type="button" class="file-row-action btn btn-ghost btn-xs px-1.5 text-error/60 hover:text-error"
|
|
1237
1237
|
data-delete-path="${p(t.path)}" title="Delete" aria-label="Delete">\u2715</button>`}
|
|
1238
|
-
</div>`).join(""))}function
|
|
1238
|
+
</div>`).join(""))}function Ef(e,t,n){let s=/[\x00-\x08\x0e-\x1f]/.test(t.slice(0,512));if(!s&&bd(e))return Tf(e,t,n);let a=$f(e),o=a?`language-${p(a)}`:"",r=s?`<div class="p-4 text-xs text-base-content/40">Binary file \u2014 <button class="text-primary hover:underline" data-download-path="${p(e)}">Download</button></div>`:`<pre class="file-preview p-4 font-mono text-xs leading-relaxed overflow-auto flex-1 m-0"><code class="hljs file-preview-code ${o}">${p(t)}</code></pre>`;return ds(e,n,s?"binary":a||"text")+r}function If(e){return Ve(e,{fallback:t=>p(t).replace(/\n/g,"<br>")})}function Tf(e,t,n){return ds(e,n,"Markdown")+`
|
|
1239
1239
|
<div class="file-markdown-toolbar" role="group" aria-label="Markdown view">
|
|
1240
1240
|
<button type="button" class="file-markdown-mode active" data-file-render-mode="preview">Preview</button>
|
|
1241
1241
|
<button type="button" class="file-markdown-mode" data-file-render-mode="code">Code</button>
|
|
1242
1242
|
</div>
|
|
1243
|
-
<div class="file-markdown-preview md p-4 overflow-auto flex-1">${
|
|
1244
|
-
<pre class="file-markdown-code file-preview p-4 font-mono text-xs leading-relaxed overflow-auto flex-1 m-0 hidden"><code class="file-preview-code language-markdown">${p(t)}</code></pre>`}function
|
|
1243
|
+
<div class="file-markdown-preview md p-4 overflow-auto flex-1">${If(t)}</div>
|
|
1244
|
+
<pre class="file-markdown-code file-preview p-4 font-mono text-xs leading-relaxed overflow-auto flex-1 m-0 hidden"><code class="file-preview-code language-markdown">${p(t)}</code></pre>`}function Cf(e){let t=e?.querySelector(".file-markdown-preview");t&&(typeof hljs<"u"&&t.querySelectorAll("pre code:not(.hljs)").forEach(n=>{try{hljs.highlightElement(n)}catch{}}),yt(t),xt(t))}async function Mf(e){if(await _o("/vendor/mammoth.browser.min.js"),typeof mammoth>"u")throw new Error("mammoth failed to load");let t=await mammoth.convertToHtml({arrayBuffer:e});return`<div class="office-preview office-docx overflow-auto flex-1 p-4 md">${t.messages?.length?`<div class="office-warn text-xs text-warning/80 px-3 py-1">${t.messages.length} conversion note(s)</div>`:""}<div class="office-docx-body">${t.value||'<p class="text-base-content/40">Empty document</p>'}</div></div>`}async function Af(e){if(await _o("/vendor/xlsx.full.min.js"),typeof XLSX>"u")throw new Error("SheetJS failed to load");let t=XLSX.read(new Uint8Array(e),{type:"array"}),n=t.SheetNames||[];if(!n.length)return'<div class="p-4 text-xs text-base-content/40">Empty workbook</div>';let s=n.map((o,r)=>`<button type="button" class="office-sheet-tab${r===0?" active":""}" data-sheet-idx="${r}">${p(o)}</button>`).join(""),a=n.map((o,r)=>{let c=t.Sheets[o],u;try{u=XLSX.utils.sheet_to_html(c,{id:`xlsx-sheet-${r}`,editable:!1})}catch{u='<p class="text-base-content/40 text-xs p-2">Unable to render this sheet</p>'}return`<div class="office-sheet-pane${r===0?"":" hidden"}" data-sheet-pane="${r}">${u}</div>`}).join("");return`
|
|
1245
1245
|
<div class="office-preview office-xlsx flex flex-col flex-1 min-h-0 overflow-hidden">
|
|
1246
1246
|
<div class="office-sheet-tabs flex gap-1 px-2 py-1.5 border-b border-base-300 overflow-x-auto flex-shrink-0 bg-base-200">${s}</div>
|
|
1247
1247
|
<div class="office-sheet-body flex-1 overflow-auto p-2">${a}</div>
|
|
1248
|
-
</div>`}function
|
|
1248
|
+
</div>`}function Df(e){let t=[],n=/<a:p[\s>][\s\S]*?<\/a:p>/g,s=/<a:t(?:\s[^>]*)?>([\s\S]*?)<\/a:t>/g,a,o=e.match(n)||[e];for(let r of o){let c=[];for(s.lastIndex=0;(a=s.exec(r))!==null;){let u=a[1].replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&").replace(/"/g,'"').replace(/'/g,"'");u&&c.push(u)}c.length&&t.push(c.join(""))}return t}async function jf(e){if(await _o("/vendor/jszip.min.js"),typeof JSZip>"u")throw new Error("JSZip failed to load");let t=await JSZip.loadAsync(e),n=Object.keys(t.files).filter(a=>/^ppt\/slides\/slide\d+\.xml$/i.test(a)).sort((a,o)=>{let r=parseInt(a.match(/slide(\d+)/i)?.[1]||"0",10),c=parseInt(o.match(/slide(\d+)/i)?.[1]||"0",10);return r-c});if(!n.length)return'<div class="p-4 text-xs text-base-content/40">No slides found in this presentation</div>';let s=[];for(let a=0;a<n.length;a++){let o=await t.files[n[a]].async("string"),r=Df(o),c=r.length?r.map(u=>`<p>${p(u)}</p>`).join(""):'<p class="text-base-content/40 italic">\uFF08\u6B64\u9875\u65E0\u53EF\u63D0\u53D6\u6587\u672C / \u53EF\u80FD\u4EE5\u56FE\u7247\u4E3A\u4E3B\uFF09</p>';s.push(`
|
|
1249
1249
|
<article class="office-slide-card">
|
|
1250
1250
|
<header class="office-slide-num">Slide ${a+1}</header>
|
|
1251
|
-
<div class="office-slide-body">${
|
|
1251
|
+
<div class="office-slide-body">${c}</div>
|
|
1252
1252
|
</article>`)}return`
|
|
1253
1253
|
<div class="office-preview office-pptx overflow-auto flex-1 p-3 space-y-3">
|
|
1254
1254
|
<p class="text-xs text-base-content/50 px-1">\u6587\u672C\u9884\u89C8\uFF08\u7248\u5F0F/\u56FE\u7247\u4E0D\u8FD8\u539F\uFF09\xB7 ${n.length} slide(s)</p>
|
|
1255
1255
|
${s.join("")}
|
|
1256
|
-
</div>`}async function
|
|
1256
|
+
</div>`}async function _f(){if(await _o("/vendor/pdf.min.js"),typeof pdfjsLib>"u")throw new Error("pdf.js failed to load");return pdfjsLib.GlobalWorkerOptions.workerSrc="/vendor/pdf.worker.min.js",pdfjsLib}async function Nf(e){let n=await(await _f()).getDocument({data:e}).promise,s=n.numPages,a=Math.min(s,40),o=[];for(let c=1;c<=a;c++){let u=await n.getPage(c),d=u.getViewport({scale:1}),f=Math.min(1.5,820/d.width),m=u.getViewport({scale:f}),g=document.createElement("canvas");g.width=Math.floor(m.width),g.height=Math.floor(m.height),g.className="office-pdf-page",g.dataset.page=String(c),await u.render({canvasContext:g.getContext("2d"),viewport:m}).promise,o.push(`
|
|
1257
1257
|
<figure class="office-pdf-figure">
|
|
1258
|
-
<figcaption class="office-pdf-cap">Page ${
|
|
1258
|
+
<figcaption class="office-pdf-cap">Page ${c} / ${s}</figcaption>
|
|
1259
1259
|
${g.outerHTML}
|
|
1260
1260
|
</figure>`)}let r=s>a?`<p class="text-xs text-base-content/50 px-2">Showing first ${a} of ${s} pages \u2014 download for full file.</p>`:"";return`
|
|
1261
1261
|
<div class="office-preview office-pdf overflow-auto flex-1 p-3 space-y-3">
|
|
1262
1262
|
<p class="text-xs text-base-content/50 px-1">PDF preview \xB7 ${s} page(s)</p>
|
|
1263
1263
|
${r}
|
|
1264
1264
|
${o.join("")}
|
|
1265
|
-
</div>`}async function
|
|
1266
|
-
${
|
|
1265
|
+
</div>`}async function Pf(e,t,n){let s=gd(e),a={docx:"Word",pptx:"PowerPoint",xlsx:"Excel",pdf:"PDF"},o=kf(t),r;if(s==="docx")r=await Mf(o);else if(s==="xlsx")r=await Af(o);else if(s==="pptx")r=await jf(o);else if(s==="pdf")r=await Nf(o);else throw new Error("Unsupported office type");return ds(e,n,a[s]||s)+r}function Hf(e,t){let n=e?e.split("/"):[],s=t?n.slice(0,-1):n,a='<span class="cursor-pointer text-primary hover:underline" data-dir-path="">root</span>',o="";for(let r of s)o=o?`${o}/${r}`:r,a+=` <span class="text-base-content/40">/</span> <span class="cursor-pointer text-primary hover:underline" data-dir-path="${p(o)}">${p(r)}</span>`;return t&&(a+=` <span class="text-base-content/40">/</span> <span>${p(n.at(-1))}</span>`),a}function qf(){let e=E.peek(),t=ie.peek()||e?.path;if(!t)return;let n=document.createElement("input");n.type="file",n.multiple=!0,n.addEventListener("change",async()=>{let s=Y.peek(),a="_",o=[...n.files],r=!1;for(let c of o){let u=s?`${s}/${c.name}`:c.name,d=`/api/projects/${a}/file?root=${encodeURIComponent(t)}&path=${encodeURIComponent(u)}`;try{let f=await fetch(d,{method:"POST",headers:ct(),body:c,duplex:"half"});if(!f.ok){let m=await f.json().catch(()=>({}));throw new Error(m.error||`HTTP ${f.status}`)}}catch(f){alert(`Upload failed (${c.name}): ${f.message}`),r=!0;break}}if(!r){let c=Y.peek();Y.value=c+"\0",Y.value=c}}),n.click()}var Ei=!1,md=0;function Rf(){let e=document.getElementById("file-download-toast");return e||(e=document.createElement("div"),e.id="file-download-toast",e.className="file-download-toast",e.setAttribute("role","status"),e.setAttribute("aria-live","polite"),e.hidden=!0,document.body.appendChild(e),e)}function zt(e,{sticky:t=!1}={}){let n=Rf();n.textContent=e,n.hidden=!1,n.classList.add("visible"),clearTimeout(md),t||(md=setTimeout(()=>{n.classList.remove("visible")},5e3))}function jo(e,t){let n=document.createElement("a");n.href=e,n.download=t,n.rel="noopener",n.style.display="none",document.body.appendChild(n),n.click(),n.remove()}async function Bf(e,t){let n=ie.peek()||e?.path||"";if(!n){alert("No path selected \u2014 set root first");return}if(Ei){zt("\u5DF2\u6709\u6587\u4EF6\u6B63\u5728\u4E0B\u8F7D");return}let s="_",a=(t||"").split("/").pop()||"download",o=new URLSearchParams({root:n,path:t,download:"true"}),r=`/api/projects/${s}/file?${o}`;Ei=!0,zt(wa(a),{sticky:!0});try{let c=await fetch(r,{headers:ct(),credentials:"same-origin"});if(!c.ok){let P=await c.json().catch(()=>({}));throw new Error(P.error||`HTTP ${c.status}`)}let u=16*1024*1024,d=Number(c.headers.get("content-length"))||0;if(d>u||!c.body){await c.body?.cancel(),jo(`/api/projects/${s}/file?${gs({root:n,path:t,download:"true"})}`,a),zt(vs(a));return}let f=c.body.getReader(),m=[],g=0;for(;;){let{done:P,value:ae}=await f.read();if(P)break;if(g+=ae.byteLength,g>u){await f.cancel(),jo(`/api/projects/${s}/file?${gs({root:n,path:t,download:"true"})}`,a),zt(vs(a));return}m.push(ae),zt(wa(a,g,d),{sticky:!0})}let w=new Blob(m,{type:c.headers.get("content-type")||"application/octet-stream"}),y=URL.createObjectURL(w);jo(y,a),setTimeout(()=>URL.revokeObjectURL(y),6e4),zt(or(a))}catch(c){if(c.name==="AbortError")return;try{jo(`/api/projects/${s}/file?${gs({root:n,path:t,download:"true"})}`,a),zt(vs(a))}catch{zt(`\u4E0B\u8F7D\u5931\u8D25\uFF1A${c.message}`),alert(`Download failed: ${c.message}`)}}finally{Ei=!1}}async function Of(e,t){if(!confirm(`Delete "${t.split("/").pop()}"?`))return;let n=ie.peek()||e?.path||"",s="_";try{await x("DELETE",`/api/projects/${s}/file?root=${encodeURIComponent(n)}&path=${encodeURIComponent(t)}`),Y.value=Y.peek()+" ",Y.value=Y.peek().trimEnd()}catch(a){alert(`Delete failed: ${a.message}`)}}async function Uf(e,t,n,s){let a=n.size??(typeof n.content=="string"?n.content.length:0),o=gd(t);if(o&&n.encoding==="base64"){e.innerHTML=ds(t,a,o)+`<div class="p-4 text-xs text-base-content/40">Parsing ${o.toUpperCase()}\u2026</div>`;try{let r=await Pf(t,n.content,a);if(s.aborted)return;e.innerHTML=r}catch(r){if(s.aborted)return;e.innerHTML=ds(t,a,o)+`<div class="p-4 text-xs text-error">Preview failed: ${p(r.message)} \u2014 <button class="text-primary hover:underline" data-download-path="${p(t)}">Download</button></div>`}return}if(n.encoding==="base64"){e.innerHTML=ds(t,a,"binary")+`<div class="p-4 text-xs text-base-content/40">Binary file \u2014 <button class="text-primary hover:underline" data-download-path="${p(t)}">Download</button></div>`;return}e.innerHTML=Ef(t,n.content||"",a),Sf(e),bd(t)&&Cf(e)}function vd(){De(()=>{let e=i("files-breadcrumb");if(!e)return;let t=re.value!==null;e.innerHTML=`
|
|
1266
|
+
${Hf(re.value??Y.value,t)}
|
|
1267
1267
|
<div class="flex-1"></div>
|
|
1268
|
-
${t?"":'<button id="btn-upload" class="btn btn-ghost btn-xs text-base-content/50 hover:text-base-content">\u2191 Upload</button>'}`}),
|
|
1268
|
+
${t?"":'<button id="btn-upload" class="btn btn-ghost btn-xs text-base-content/50 hover:text-base-content">\u2191 Upload</button>'}`}),Dn(async e=>{let t=X.value,n=E.value,s=(ie.value||n?.path||"").trim(),a=re.value,o=Y.value,r=i("files-area");if(!r||t!=="files")return;if(!s){r.innerHTML='<div class="p-4 text-xs text-base-content/40">No path yet \u2014 open a session (uses that machine's cwd) or type an absolute path and press Go.</div>';return}let c="_";r.innerHTML='<div class="p-4 text-xs text-base-content/40">Loading\u2026</div>';try{if(a!==null){let f=await x("GET",`/api/projects/${c}/file?root=${encodeURIComponent(s)}&path=${encodeURIComponent(a)}`,void 0,e);e.aborted||await Uf(r,a,f,e);return}let u=await x("GET",`/api/projects/${c}/files?root=${encodeURIComponent(s)}&path=${encodeURIComponent(o)}`,void 0,e);if(e.aborted)return;let d=Array.isArray(u)?u:Array.isArray(u?.files)?u.files:null;if(!d){r.innerHTML=`<div class="p-4 text-xs text-error">${p(u?.error||"Invalid directory listing")}</div>`;return}r.innerHTML=Lf(d)}catch(u){!e.aborted&&u?.name!=="AbortError"&&(r.innerHTML=`<div class="p-4 text-xs text-error">${p(u.message)}</div>`)}}),b.on("click","[data-dir-path]",(e,t)=>{re.value=null,Y.value=t.dataset.dirPath}),b.on("click","[data-file-path]",(e,t)=>{re.value=t.dataset.filePath}),b.on("click","#btn-upload",()=>qf()),b.on("click","[data-download-path]",(e,t)=>{e.preventDefault(),e.stopPropagation();let n=t.dataset.downloadPath;n&&Bf(E.peek(),n)}),b.on("click","[data-delete-path]",(e,t)=>{e.preventDefault(),e.stopPropagation();let n=t.dataset.deletePath;n&&Of(E.peek(),n)}),b.on("click","[data-file-render-mode]",(e,t)=>{let n=t.closest("#files-area");if(!n)return;let s=t.dataset.fileRenderMode==="code";n.querySelector(".file-markdown-preview")?.classList.toggle("hidden",s),n.querySelector(".file-markdown-code")?.classList.toggle("hidden",!s),n.querySelectorAll("[data-file-render-mode]").forEach(a=>{a.classList.toggle("active",a===t)})}),b.on("click",".office-sheet-tab",(e,t)=>{let n=t.closest(".office-xlsx");if(!n)return;let s=t.dataset.sheetIdx;n.querySelectorAll(".office-sheet-tab").forEach(a=>a.classList.toggle("active",a===t)),n.querySelectorAll(".office-sheet-pane").forEach(a=>{a.classList.toggle("hidden",a.dataset.sheetPane!==s)})})}G();W();ce();var xd=I(!1);function Ff(e){return e?e.split(`
|
|
1269
1269
|
`).map(t=>p(t).replace(/\b([0-9a-f]{7})\b/,'<span class="gh">$1</span>').replace(/\(([^)]*)\)/,'<span style="color:oklch(var(--wa))">($1)</span>')).join(`
|
|
1270
|
-
`):'<span class="text-base-content/40">No commits</span>'}function
|
|
1270
|
+
`):'<span class="text-base-content/40">No commits</span>'}function Wf(e){if(!e)return"";if(!e.isGit)return'<div class="p-4 text-sm text-base-content/50">Not a git repository</div>';let t={M:"text-warning",D:"text-error"};return`
|
|
1271
1271
|
<div class="px-4 py-2 text-xs text-base-content/50 border-b border-base-300">
|
|
1272
1272
|
Branch: <span class="text-success font-semibold">${p(e.branch)}</span>
|
|
1273
1273
|
</div>
|
|
@@ -1293,16 +1293,16 @@ ${String(e||"")}`}function nd(e,t=l.sessionId){let n=Zp(e,t);!e||pi.has(n)||(pi.
|
|
|
1293
1293
|
<span class="text-base-content/40">Loading\u2026</span>
|
|
1294
1294
|
</div>
|
|
1295
1295
|
</div>
|
|
1296
|
-
</div>`}function
|
|
1296
|
+
</div>`}function Gf(e){return e.split(`
|
|
1297
1297
|
`).map(t=>t.startsWith("+")&&!t.startsWith("+++")?`<span class="diff-add">${p(t)}</span>`:t.startsWith("-")&&!t.startsWith("---")?`<span class="diff-del">${p(t)}</span>`:t.startsWith("@@")?`<span class="diff-hunk">${p(t)}</span>`:/^(diff |index |---|[+]{3})/.test(t)?`<span class="diff-head">${p(t)}</span>`:`<span>${p(t)}</span>`).join(`
|
|
1298
|
-
`)}function
|
|
1299
|
-
`),
|
|
1298
|
+
`)}function yd(){Dn(async e=>{let t=X.value,n=E.value,s=Se.value||n?.path,a=i("git-area");if(!a||t!=="git")return;if(!s){a.innerHTML='<div class="p-4 text-sm text-base-content/50">Enter a project root above, or open a session with a working directory.</div>';return}let o="_";a.innerHTML='<div class="p-4 text-xs text-base-content/40">Loading\u2026</div>';try{let r=await x("GET",`/api/projects/${o}/git/status?root=${encodeURIComponent(s)}`,void 0,e);e.aborted||(a.innerHTML=Wf(r))}catch(r){!e.aborted&&r?.name!=="AbortError"&&(a.innerHTML=`<div class="p-4 text-xs text-error">${p(r?.message??String(r))}</div>`)}}),Dn(async e=>{let t=E.value,n=Se.value||t?.path,s=xd.value,a=i("diff-content");if(!a||!n)return;let o=t?.id||"_";try{let r=await x("GET",`/api/projects/${o}/git/diff?root=${encodeURIComponent(n)}${s?"&staged=true":""}`,void 0,e);e.aborted||(a.innerHTML=r?.diff?Gf(r.diff):'<span class="text-base-content/40">No changes</span>')}catch(r){!e.aborted&&r?.name!=="AbortError"&&(a.innerHTML=`<span class="text-error">${p(r?.message??String(r))}</span>`)}}),b.on("click","#diff-unstaged, #diff-staged",(e,t)=>{let n=t.id==="diff-staged";xd.value=n,i("diff-unstaged").className=`cursor-pointer ${n?"text-base-content/50":"text-primary"}`,i("diff-staged").className=`cursor-pointer ${n?"text-primary":"text-base-content/50"}`}),b.on("click","#git-graph-toggle",()=>{let e=i("git-graph-panel"),t=i("git-graph-chevron"),n=e.classList.toggle("hidden");t.textContent=n?"\u25B6":"\u25BC",n||zf()})}function zf(){let e=E.peek(),t=Se.peek()||e?.path,n=i("git-graph-content");if(!t||!n)return;let s="_";n.innerHTML='<span class="text-base-content/40">Loading\u2026</span>',x("GET",`/api/projects/${s}/git/log?root=${encodeURIComponent(t)}`).then(a=>{n.innerHTML=a.graph?Ff(a.graph):'<span class="text-base-content/40">No commits</span>'}).catch(a=>{n.innerHTML=`<span class="text-error">${p(a.message)}</span>`})}Ps();G();W();var Me=null,z=null,Po=null,ra=!1,Ho=null,Sd=null,aa=0,oa=null,Ii=!1,wd=!1,kd={"ctrl-c":"",escape:"\x1B",tab:" ",up:"\x1B[A",down:"\x1B[B",left:"\x1B[D",right:"\x1B[C"};function Ti(e){Me&&Me.readyState===WebSocket.OPEN&&Me.send(JSON.stringify({type:"input",data:e}))}function Kf(){return window.matchMedia("(max-width: 640px), (hover: none) and (pointer: coarse)").matches}function qo(){if(Kf()){document.getElementById("term-mobile-input")?.focus({preventScroll:!0});return}z?.focus();let e=document.querySelector("#terminal-container .xterm-helper-textarea");e&&(e.focus({preventScroll:!0}),requestAnimationFrame(()=>e.focus({preventScroll:!0})))}function Ld(){if(z)return;let e=i("terminal-container");if(!e)return;if(typeof Terminal>"u"){setTimeout(Ld,100);return}z=new Terminal({cursorBlink:!0,fontFamily:"Fira Code, Courier New, monospace",fontSize:12,theme:{background:"#0d1117",foreground:"#c9d1d9",cursor:"#58a6ff",black:"#0d1117",red:"#ff7b72",green:"#3fb950",yellow:"#d29922",blue:"#58a6ff",magenta:"#bc8cff",cyan:"#39c5cf",white:"#b1bac4",brightBlack:"#484f58",brightRed:"#ffa198",brightGreen:"#56d364",brightYellow:"#e3b341",brightBlue:"#79c0ff",brightMagenta:"#d8b9ff",brightCyan:"#56d4dd",brightWhite:"#ffffff"}}),typeof FitAddon<"u"&&(Po=new FitAddon.FitAddon,z.loadAddon(Po)),z.open(e),No(),z.onData(n=>{Ti(n)}),e.addEventListener("pointerdown",()=>qo(),{passive:!0}),e.addEventListener("touchend",()=>qo(),{passive:!0}),window.addEventListener("resize",()=>{No(),Ro()});let t=window.visualViewport;if(t){let n=0,s=()=>{n&&cancelAnimationFrame(n),n=requestAnimationFrame(()=>{n=0,X.peek()==="shell"&&(No(),Ro())})};t.addEventListener("resize",s),t.addEventListener("scroll",s)}}function No(){try{Po&&z&&Po.fit()}catch{}}function Ro(){Me&&Me.readyState===WebSocket.OPEN&&z&&Me.send(JSON.stringify({type:"resize",cols:z.cols,rows:z.rows}))}function Ed(){return l.machineId||j.peek()||null}function Bo(e){oa&&(clearTimeout(oa),oa=null),Ii=!0;let t=++aa;if(Me){try{Me.close()}catch{}Me=null}ra=!1;let n=location.protocol==="https:"?"wss":"ws",s=z?z.cols:80,a=z?z.rows:24,o=new URLSearchParams;l.token&&o.set("token",l.token),e&&o.set("cwd",e),o.set("cols",String(s)),o.set("rows",String(a));let r=Ed();M.peek()&&r&&o.set("machine",r),Ho=e||null,Sd=r,Me=new WebSocket(`${n}://${location.host}/ws/shell?${o}`),Me.addEventListener("open",()=>{t===aa&&(ra=!0,z?.write(`\x1B[32mConnected to interactive terminal\x1B[0m\r
|
|
1299
|
+
`),Ro())}),Me.addEventListener("message",c=>{if(t!==aa)return;let u;try{u=JSON.parse(c.data)}catch{return}u.type==="output"?z?.write(u.data):u.type==="exit"?z?.write(`\r
|
|
1300
1300
|
\x1B[33m[process exited: ${u.code}]\x1B[0m\r
|
|
1301
1301
|
`):u.type==="error"&&z?.write(`\r
|
|
1302
1302
|
\x1B[31m[error: ${u.data||u.message||""}]\x1B[0m\r
|
|
1303
|
-
`)}),Me.addEventListener("close",()=>{t===
|
|
1303
|
+
`)}),Me.addEventListener("close",()=>{t===aa&&(ra=!1,z?.write(`\r
|
|
1304
1304
|
\x1B[33m[disconnected]\x1B[0m\r
|
|
1305
|
-
`),!(!
|
|
1306
|
-
`),
|
|
1305
|
+
`),!(!Ii||X.peek()!=="shell")&&(z?.write(`\x1B[33m[reconnecting\u2026]\x1B[0m\r
|
|
1306
|
+
`),oa=setTimeout(()=>{oa=null,Bo(Ho)},1500)))}),Me.addEventListener("error",()=>{t===aa&&z?.write(`\r
|
|
1307
1307
|
\x1B[31m[WebSocket error]\x1B[0m\r
|
|
1308
|
-
`)})}function
|
|
1308
|
+
`)})}function $d(){let e=E.peek()?.path,t=i("term-cwd");t&&(t.textContent=e||"~"),z||Ld(),requestAnimationFrame(()=>{requestAnimationFrame(()=>{No();let n=Ed();!ra||Ho!==(e||null)||Sd!==n?(z?.clear(),Bo(e)):Ro()})})}function Id(){wd||(wd=!0,document.getElementById("term-keyboard")?.addEventListener("click",qo),document.getElementById("term-mobile-composer")?.addEventListener("submit",e=>{e.preventDefault();let t=document.getElementById("term-mobile-input");t&&(Ti(`${t.value}\r`),t.value="",t.focus({preventScroll:!0}))}),document.getElementById("term-mobile-keys")?.addEventListener("pointerdown",e=>{e.target.closest("[data-term-key]")&&e.preventDefault()}),document.getElementById("term-mobile-keys")?.addEventListener("click",e=>{let t=e.target.closest("[data-term-key]")?.dataset.termKey;!t||!kd[t]||(Ti(kd[t]),qo())})),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&(X.peek()!=="shell"||!Ii||ra||Bo(Ho))}),je(X,e=>{e==="shell"&&$d()}),document.addEventListener("shell-tab-shown",()=>{X.peek()==="shell"&&$d()}),document.getElementById("term-reconnect")?.addEventListener("click",()=>{z?.clear(),Bo(E.peek()?.path)})}Os();Oa();var Td=null;function Cd(){return window.matchMedia("(display-mode: standalone)").matches||window.navigator.standalone===!0||document.referrer.includes("android-app://")}function Jf(e){let t=String(e||"").replace(/^\[|\]$/g,"");return!!(/^\d{1,3}(\.\d{1,3}){3}$/.test(t)||t.includes(":")&&/^[0-9a-f:]+$/i.test(t))}function Qf(){if(!("serviceWorker"in navigator)||!window.isSecureContext)return!1;let e=location.hostname;return e==="localhost"||e==="127.0.0.1"||e==="::1"?!0:Jf(e)?!1:location.protocol==="https:"}function Md(){document.getElementById("btn-pwa-install")?.classList.remove("hidden")}function Ad(){Cd()&&document.documentElement.classList.add("pwa-standalone"),window.addEventListener("beforeinstallprompt",n=>{n.preventDefault(),Td=n,document.dispatchEvent(new CustomEvent("pwa-installable")),Md()}),window.addEventListener("appinstalled",()=>{Td=null,document.getElementById("btn-pwa-install")?.classList.add("hidden")});let e=/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1;if(!Cd()&&(e||/Android/i.test(navigator.userAgent))&&requestAnimationFrame(()=>Md()),!Qf()){"serviceWorker"in navigator&&navigator.serviceWorker.getRegistrations().then(n=>n.forEach(s=>s.unregister())).catch(()=>{});return}let t=()=>{navigator.serviceWorker.register("/sw.js?v=38",{scope:"/"}).then(n=>{n.addEventListener("updatefound",()=>{let s=n.installing;s&&s.addEventListener("statechange",()=>{s.state==="installed"&&navigator.serviceWorker.controller&&console.info("[pwa] New version ready \u2014 reload to apply")})})}).catch(()=>{navigator.serviceWorker.getRegistrations().then(n=>n.forEach(s=>s.unregister())).catch(()=>{})})};document.readyState==="complete"?setTimeout(t,0):window.addEventListener("load",()=>setTimeout(t,0))}Hn();function Ci(){let e=document.documentElement;e.classList.add("boot-ready"),e.classList.remove("boot-pending")}function Oo(){document.documentElement.classList.remove("boot-restore")}var Mi=Cr(location.hash.slice(1)||"/"),Dd=gi()||!!(l.token&&Mi?.id);Gc({restoreSession:Dd});Qi();fd();vd();yd();Ol();qr();Id();cd();lc();Al(nt,Ct);(async()=>{let e=zi();if(l.token)try{let t=document.getElementById("auth-screen"),n=document.getElementById("app");if(t&&(t.style.display="none",t.classList.add("hidden")),n&&(n.style.display="flex",n.classList.remove("hidden")),Dd){document.documentElement.classList.add("boot-restore");let a=document.getElementById("welcome"),o=document.getElementById("project-view");a&&(a.classList.add("hidden"),a.style.display="none"),o&&(o.classList.remove("hidden"),o.style.cssText="display:flex;flex-direction:column;flex:1;min-height:0;overflow:hidden")}let s=await e;await xo({hub:s,deepLink:Mi}),Mi?.id||(Dl(),(location.hash||"").startsWith("#/session/")||Oo()),requestAnimationFrame(()=>{requestAnimationFrame(Ci)})}catch(t){console.error("[boot]",t),l.token=null,localStorage.removeItem("token"),Oo(),await hi(),Ci()}else{Oo();try{await hi()}catch(t){console.error("[boot auth]",t)}finally{Ci()}}})();document.addEventListener("router:home",()=>{Oo()});Ad();
|