dsh-thoughtdag 0.5.12 → 0.5.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (19) hide show
  1. package/dist-app/assets/{canonical-46lAq3XC.js → canonical-Bkq2Xinv.js} +2 -2
  2. package/dist-app/assets/{canvas-record-PNNfw7b3.js → canvas-record-BD0b1tl8.js} +1 -1
  3. package/dist-app/assets/{claude-code-session-DtdYqKTH.js → claude-code-session-CmZZMVmM.js} +1 -1
  4. package/dist-app/assets/{codex-session-C1JXlxO_.js → codex-session-CcVN_Kn7.js} +1 -1
  5. package/dist-app/assets/{dsh-session-D606GO4A.js → dsh-session-eUU9cqVs.js} +1 -1
  6. package/dist-app/assets/{experiment-loop-PGHklznL.js → experiment-loop-D5X-o2kG.js} +1 -1
  7. package/dist-app/assets/{http-bridge-k3v0JK5X.js → http-bridge-BnB37T8x.js} +1 -1
  8. package/dist-app/assets/{index-BF3yHokv.js → index--sniMyQq.js} +1 -1
  9. package/dist-app/assets/{index-CjJoJV4P.js → index-C4lWKzPK.js} +3 -3
  10. package/dist-app/assets/{index-CPB-aTvu.js → index-D-nwx3XX.js} +1 -1
  11. package/dist-app/assets/{index-Cr0pf9Wu.js → index-LCj6YsSC.js} +15 -15
  12. package/dist-app/assets/{pi-session-DKMmMqPQ.js → pi-session-CvsiY9hT.js} +1 -1
  13. package/dist-app/assets/{sensitive-scan-DBS7362r.js → sensitive-scan-ULbRwlLo.js} +1 -1
  14. package/dist-app/assets/{session-handoff-DwZJMHEU.js → session-handoff-9h2VEmwX.js} +2 -2
  15. package/dist-app/assets/{shared-CFMn8_Ds.js → shared-Df03vMLX.js} +1 -1
  16. package/dist-app/assets/{turndown-plugin-gfm.cjs-D0S5uwh5.js → turndown-plugin-gfm.cjs-DtPIPA4T.js} +1 -1
  17. package/dist-app/assets/{update-check-CRxOAqxm.js → update-check-DwksTqSo.js} +1 -1
  18. package/dist-app/index.html +1 -1
  19. package/package.json +1 -1
@@ -1,4 +1,4 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/claude-code-session-DtdYqKTH.js","assets/shared-CFMn8_Ds.js","assets/codex-session-C1JXlxO_.js"])))=>i.map(i=>d[i]);
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/claude-code-session-CmZZMVmM.js","assets/shared-Df03vMLX.js","assets/codex-session-CcVN_Kn7.js"])))=>i.map(i=>d[i]);
2
2
  (function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))a(r);new MutationObserver(r=>{for(const s of r)if(s.type==="childList")for(const o of s.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&a(o)}).observe(document,{childList:!0,subtree:!0});function n(r){const s={};return r.integrity&&(s.integrity=r.integrity),r.referrerPolicy&&(s.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?s.credentials="include":r.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function a(r){if(r.ep)return;r.ep=!0;const s=n(r);fetch(r.href,s)}})();const aD="modulepreload",rD=function(e){return"/thoughtdag/"+e},Ik={},pt=function(t,n,a){let r=Promise.resolve();if(n&&n.length>0){let d=function(h){return Promise.all(h.map(m=>Promise.resolve(m).then(p=>({status:"fulfilled",value:p}),p=>({status:"rejected",reason:p}))))};document.getElementsByTagName("link");const o=document.querySelector("meta[property=csp-nonce]"),u=o?.nonce||o?.getAttribute("nonce");r=d(n.map(h=>{if(h=rD(h),h in Ik)return;Ik[h]=!0;const m=h.endsWith(".css"),p=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${h}"]${p}`))return;const x=document.createElement("link");if(x.rel=m?"stylesheet":aD,m||(x.as="script"),x.crossOrigin="",x.href=h,u&&x.setAttribute("nonce",u),document.head.appendChild(x),m)return new Promise((b,y)=>{x.addEventListener("load",b),x.addEventListener("error",()=>y(new Error(`Unable to preload CSS for ${h}`)))})}))}function s(o){const u=new Event("vite:preloadError",{cancelable:!0});if(u.payload=o,window.dispatchEvent(u),!u.defaultPrevented)throw o}return r.then(o=>{for(const u of o||[])u.status==="rejected"&&s(u.reason);return t().catch(s)})};var Que=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function L0(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Zue(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if(typeof t=="function"){var n=function a(){var r=!1;try{r=this instanceof a}catch{}return r?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach(function(a){var r=Object.getOwnPropertyDescriptor(e,a);Object.defineProperty(n,a,r.get?r:{enumerable:!0,get:function(){return e[a]}})}),n}var Z1={exports:{}},Ed={};var Ok;function sD(){if(Ok)return Ed;Ok=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function n(a,r,s){var o=null;if(s!==void 0&&(o=""+s),r.key!==void 0&&(o=""+r.key),"key"in r){s={};for(var u in r)u!=="key"&&(s[u]=r[u])}else s=r;return r=s.ref,{$$typeof:e,type:a,key:o,ref:r!==void 0?r:null,props:s}}return Ed.Fragment=t,Ed.jsx=n,Ed.jsxs=n,Ed}var Dk;function iD(){return Dk||(Dk=1,Z1.exports=sD()),Z1.exports}var l=iD(),J1={exports:{}},rn={};var Rk;function oD(){if(Rk)return rn;Rk=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),a=Symbol.for("react.strict_mode"),r=Symbol.for("react.profiler"),s=Symbol.for("react.consumer"),o=Symbol.for("react.context"),u=Symbol.for("react.forward_ref"),d=Symbol.for("react.suspense"),h=Symbol.for("react.memo"),m=Symbol.for("react.lazy"),p=Symbol.for("react.activity"),x=Symbol.iterator;function b($){return $===null||typeof $!="object"?null:($=x&&$[x]||$["@@iterator"],typeof $=="function"?$:null)}var y={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},w=Object.assign,E={};function v($,Z,K){this.props=$,this.context=Z,this.refs=E,this.updater=K||y}v.prototype.isReactComponent={},v.prototype.setState=function($,Z){if(typeof $!="object"&&typeof $!="function"&&$!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,$,Z,"setState")},v.prototype.forceUpdate=function($){this.updater.enqueueForceUpdate(this,$,"forceUpdate")};function N(){}N.prototype=v.prototype;function S($,Z,K){this.props=$,this.context=Z,this.refs=E,this.updater=K||y}var C=S.prototype=new N;C.constructor=S,w(C,v.prototype),C.isPureReactComponent=!0;var I=Array.isArray;function O(){}var _={H:null,A:null,T:null,S:null},A=Object.prototype.hasOwnProperty;function H($,Z,K){var J=K.ref;return{$$typeof:e,type:$,key:Z,ref:J!==void 0?J:null,props:K}}function G($,Z){return H($.type,Z,$.props)}function D($){return typeof $=="object"&&$!==null&&$.$$typeof===e}function P($){var Z={"=":"=0",":":"=2"};return"$"+$.replace(/[=:]/g,function(K){return Z[K]})}var Y=/\/+/g;function U($,Z){return typeof $=="object"&&$!==null&&$.key!=null?P(""+$.key):Z.toString(36)}function z($){switch($.status){case"fulfilled":return $.value;case"rejected":throw $.reason;default:switch(typeof $.status=="string"?$.then(O,O):($.status="pending",$.then(function(Z){$.status==="pending"&&($.status="fulfilled",$.value=Z)},function(Z){$.status==="pending"&&($.status="rejected",$.reason=Z)})),$.status){case"fulfilled":return $.value;case"rejected":throw $.reason}}throw $}function L($,Z,K,J,oe){var me=typeof $;(me==="undefined"||me==="boolean")&&($=null);var ye=!1;if($===null)ye=!0;else switch(me){case"bigint":case"string":case"number":ye=!0;break;case"object":switch($.$$typeof){case e:case t:ye=!0;break;case m:return ye=$._init,L(ye($._payload),Z,K,J,oe)}}if(ye)return oe=oe($),ye=J===""?"."+U($,0):J,I(oe)?(K="",ye!=null&&(K=ye.replace(Y,"$&/")+"/"),L(oe,Z,K,"",function(Te){return Te})):oe!=null&&(D(oe)&&(oe=G(oe,K+(oe.key==null||$&&$.key===oe.key?"":(""+oe.key).replace(Y,"$&/")+"/")+ye)),Z.push(oe)),1;ye=0;var ae=J===""?".":J+":";if(I($))for(var ge=0;ge<$.length;ge++)J=$[ge],me=ae+U(J,ge),ye+=L(J,Z,K,me,oe);else if(ge=b($),typeof ge=="function")for($=ge.call($),ge=0;!(J=$.next()).done;)J=J.value,me=ae+U(J,ge++),ye+=L(J,Z,K,me,oe);else if(me==="object"){if(typeof $.then=="function")return L(z($),Z,K,J,oe);throw Z=String($),Error("Objects are not valid as a React child (found: "+(Z==="[object Object]"?"object with keys {"+Object.keys($).join(", ")+"}":Z)+"). If you meant to render a collection of children, use an array instead.")}return ye}function q($,Z,K){if($==null)return $;var J=[],oe=0;return L($,J,"","",function(me){return Z.call(K,me,oe++)}),J}function W($){if($._status===-1){var Z=$._result;Z=Z(),Z.then(function(K){($._status===0||$._status===-1)&&($._status=1,$._result=K)},function(K){($._status===0||$._status===-1)&&($._status=2,$._result=K)}),$._status===-1&&($._status=0,$._result=Z)}if($._status===1)return $._result.default;throw $._result}var X=typeof reportError=="function"?reportError:function($){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var Z=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof $=="object"&&$!==null&&typeof $.message=="string"?String($.message):String($),error:$});if(!window.dispatchEvent(Z))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",$);return}console.error($)},B={map:q,forEach:function($,Z,K){q($,function(){Z.apply(this,arguments)},K)},count:function($){var Z=0;return q($,function(){Z++}),Z},toArray:function($){return q($,function(Z){return Z})||[]},only:function($){if(!D($))throw Error("React.Children.only expected to receive a single React element child.");return $}};return rn.Activity=p,rn.Children=B,rn.Component=v,rn.Fragment=n,rn.Profiler=r,rn.PureComponent=S,rn.StrictMode=a,rn.Suspense=d,rn.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=_,rn.__COMPILER_RUNTIME={__proto__:null,c:function($){return _.H.useMemoCache($)}},rn.cache=function($){return function(){return $.apply(null,arguments)}},rn.cacheSignal=function(){return null},rn.cloneElement=function($,Z,K){if($==null)throw Error("The argument must be a React element, but you passed "+$+".");var J=w({},$.props),oe=$.key;if(Z!=null)for(me in Z.key!==void 0&&(oe=""+Z.key),Z)!A.call(Z,me)||me==="key"||me==="__self"||me==="__source"||me==="ref"&&Z.ref===void 0||(J[me]=Z[me]);var me=arguments.length-2;if(me===1)J.children=K;else if(1<me){for(var ye=Array(me),ae=0;ae<me;ae++)ye[ae]=arguments[ae+2];J.children=ye}return H($.type,oe,J)},rn.createContext=function($){return $={$$typeof:o,_currentValue:$,_currentValue2:$,_threadCount:0,Provider:null,Consumer:null},$.Provider=$,$.Consumer={$$typeof:s,_context:$},$},rn.createElement=function($,Z,K){var J,oe={},me=null;if(Z!=null)for(J in Z.key!==void 0&&(me=""+Z.key),Z)A.call(Z,J)&&J!=="key"&&J!=="__self"&&J!=="__source"&&(oe[J]=Z[J]);var ye=arguments.length-2;if(ye===1)oe.children=K;else if(1<ye){for(var ae=Array(ye),ge=0;ge<ye;ge++)ae[ge]=arguments[ge+2];oe.children=ae}if($&&$.defaultProps)for(J in ye=$.defaultProps,ye)oe[J]===void 0&&(oe[J]=ye[J]);return H($,me,oe)},rn.createRef=function(){return{current:null}},rn.forwardRef=function($){return{$$typeof:u,render:$}},rn.isValidElement=D,rn.lazy=function($){return{$$typeof:m,_payload:{_status:-1,_result:$},_init:W}},rn.memo=function($,Z){return{$$typeof:h,type:$,compare:Z===void 0?null:Z}},rn.startTransition=function($){var Z=_.T,K={};_.T=K;try{var J=$(),oe=_.S;oe!==null&&oe(K,J),typeof J=="object"&&J!==null&&typeof J.then=="function"&&J.then(O,X)}catch(me){X(me)}finally{Z!==null&&K.types!==null&&(Z.types=K.types),_.T=Z}},rn.unstable_useCacheRefresh=function(){return _.H.useCacheRefresh()},rn.use=function($){return _.H.use($)},rn.useActionState=function($,Z,K){return _.H.useActionState($,Z,K)},rn.useCallback=function($,Z){return _.H.useCallback($,Z)},rn.useContext=function($){return _.H.useContext($)},rn.useDebugValue=function(){},rn.useDeferredValue=function($,Z){return _.H.useDeferredValue($,Z)},rn.useEffect=function($,Z){return _.H.useEffect($,Z)},rn.useEffectEvent=function($){return _.H.useEffectEvent($)},rn.useId=function(){return _.H.useId()},rn.useImperativeHandle=function($,Z,K){return _.H.useImperativeHandle($,Z,K)},rn.useInsertionEffect=function($,Z){return _.H.useInsertionEffect($,Z)},rn.useLayoutEffect=function($,Z){return _.H.useLayoutEffect($,Z)},rn.useMemo=function($,Z){return _.H.useMemo($,Z)},rn.useOptimistic=function($,Z){return _.H.useOptimistic($,Z)},rn.useReducer=function($,Z,K){return _.H.useReducer($,Z,K)},rn.useRef=function($){return _.H.useRef($)},rn.useState=function($){return _.H.useState($)},rn.useSyncExternalStore=function($,Z,K){return _.H.useSyncExternalStore($,Z,K)},rn.useTransition=function(){return _.H.useTransition()},rn.version="19.2.4",rn}var jk;function P0(){return jk||(jk=1,J1.exports=oD()),J1.exports}var R=P0();const Bd=L0(R);var ex={exports:{}},Sd={},tx={exports:{}},nx={};var Lk;function lD(){return Lk||(Lk=1,(function(e){function t(L,q){var W=L.length;L.push(q);e:for(;0<W;){var X=W-1>>>1,B=L[X];if(0<r(B,q))L[X]=q,L[W]=B,W=X;else break e}}function n(L){return L.length===0?null:L[0]}function a(L){if(L.length===0)return null;var q=L[0],W=L.pop();if(W!==q){L[0]=W;e:for(var X=0,B=L.length,$=B>>>1;X<$;){var Z=2*(X+1)-1,K=L[Z],J=Z+1,oe=L[J];if(0>r(K,W))J<B&&0>r(oe,K)?(L[X]=oe,L[J]=W,X=J):(L[X]=K,L[Z]=W,X=Z);else if(J<B&&0>r(oe,W))L[X]=oe,L[J]=W,X=J;else break e}}return q}function r(L,q){var W=L.sortIndex-q.sortIndex;return W!==0?W:L.id-q.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var s=performance;e.unstable_now=function(){return s.now()}}else{var o=Date,u=o.now();e.unstable_now=function(){return o.now()-u}}var d=[],h=[],m=1,p=null,x=3,b=!1,y=!1,w=!1,E=!1,v=typeof setTimeout=="function"?setTimeout:null,N=typeof clearTimeout=="function"?clearTimeout:null,S=typeof setImmediate<"u"?setImmediate:null;function C(L){for(var q=n(h);q!==null;){if(q.callback===null)a(h);else if(q.startTime<=L)a(h),q.sortIndex=q.expirationTime,t(d,q);else break;q=n(h)}}function I(L){if(w=!1,C(L),!y)if(n(d)!==null)y=!0,O||(O=!0,P());else{var q=n(h);q!==null&&z(I,q.startTime-L)}}var O=!1,_=-1,A=5,H=-1;function G(){return E?!0:!(e.unstable_now()-H<A)}function D(){if(E=!1,O){var L=e.unstable_now();H=L;var q=!0;try{e:{y=!1,w&&(w=!1,N(_),_=-1),b=!0;var W=x;try{t:{for(C(L),p=n(d);p!==null&&!(p.expirationTime>L&&G());){var X=p.callback;if(typeof X=="function"){p.callback=null,x=p.priorityLevel;var B=X(p.expirationTime<=L);if(L=e.unstable_now(),typeof B=="function"){p.callback=B,C(L),q=!0;break t}p===n(d)&&a(d),C(L)}else a(d);p=n(d)}if(p!==null)q=!0;else{var $=n(h);$!==null&&z(I,$.startTime-L),q=!1}}break e}finally{p=null,x=W,b=!1}q=void 0}}finally{q?P():O=!1}}}var P;if(typeof S=="function")P=function(){S(D)};else if(typeof MessageChannel<"u"){var Y=new MessageChannel,U=Y.port2;Y.port1.onmessage=D,P=function(){U.postMessage(null)}}else P=function(){v(D,0)};function z(L,q){_=v(function(){L(e.unstable_now())},q)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(L){L.callback=null},e.unstable_forceFrameRate=function(L){0>L||125<L?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):A=0<L?Math.floor(1e3/L):5},e.unstable_getCurrentPriorityLevel=function(){return x},e.unstable_next=function(L){switch(x){case 1:case 2:case 3:var q=3;break;default:q=x}var W=x;x=q;try{return L()}finally{x=W}},e.unstable_requestPaint=function(){E=!0},e.unstable_runWithPriority=function(L,q){switch(L){case 1:case 2:case 3:case 4:case 5:break;default:L=3}var W=x;x=L;try{return q()}finally{x=W}},e.unstable_scheduleCallback=function(L,q,W){var X=e.unstable_now();switch(typeof W=="object"&&W!==null?(W=W.delay,W=typeof W=="number"&&0<W?X+W:X):W=X,L){case 1:var B=-1;break;case 2:B=250;break;case 5:B=1073741823;break;case 4:B=1e4;break;default:B=5e3}return B=W+B,L={id:m++,callback:q,priorityLevel:L,startTime:W,expirationTime:B,sortIndex:-1},W>X?(L.sortIndex=W,t(h,L),n(d)===null&&L===n(h)&&(w?(N(_),_=-1):w=!0,z(I,W-X))):(L.sortIndex=B,t(d,L),y||b||(y=!0,O||(O=!0,P()))),L},e.unstable_shouldYield=G,e.unstable_wrapCallback=function(L){var q=x;return function(){var W=x;x=q;try{return L.apply(this,arguments)}finally{x=W}}}})(nx)),nx}var Pk;function cD(){return Pk||(Pk=1,tx.exports=lD()),tx.exports}var ax={exports:{}},ir={};var zk;function uD(){if(zk)return ir;zk=1;var e=P0();function t(d){var h="https://react.dev/errors/"+d;if(1<arguments.length){h+="?args[]="+encodeURIComponent(arguments[1]);for(var m=2;m<arguments.length;m++)h+="&args[]="+encodeURIComponent(arguments[m])}return"Minified React error #"+d+"; visit "+h+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function n(){}var a={d:{f:n,r:function(){throw Error(t(522))},D:n,C:n,L:n,m:n,X:n,S:n,M:n},p:0,findDOMNode:null},r=Symbol.for("react.portal");function s(d,h,m){var p=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:r,key:p==null?null:""+p,children:d,containerInfo:h,implementation:m}}var o=e.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function u(d,h){if(d==="font")return"";if(typeof h=="string")return h==="use-credentials"?h:""}return ir.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=a,ir.createPortal=function(d,h){var m=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!h||h.nodeType!==1&&h.nodeType!==9&&h.nodeType!==11)throw Error(t(299));return s(d,h,null,m)},ir.flushSync=function(d){var h=o.T,m=a.p;try{if(o.T=null,a.p=2,d)return d()}finally{o.T=h,a.p=m,a.d.f()}},ir.preconnect=function(d,h){typeof d=="string"&&(h?(h=h.crossOrigin,h=typeof h=="string"?h==="use-credentials"?h:"":void 0):h=null,a.d.C(d,h))},ir.prefetchDNS=function(d){typeof d=="string"&&a.d.D(d)},ir.preinit=function(d,h){if(typeof d=="string"&&h&&typeof h.as=="string"){var m=h.as,p=u(m,h.crossOrigin),x=typeof h.integrity=="string"?h.integrity:void 0,b=typeof h.fetchPriority=="string"?h.fetchPriority:void 0;m==="style"?a.d.S(d,typeof h.precedence=="string"?h.precedence:void 0,{crossOrigin:p,integrity:x,fetchPriority:b}):m==="script"&&a.d.X(d,{crossOrigin:p,integrity:x,fetchPriority:b,nonce:typeof h.nonce=="string"?h.nonce:void 0})}},ir.preinitModule=function(d,h){if(typeof d=="string")if(typeof h=="object"&&h!==null){if(h.as==null||h.as==="script"){var m=u(h.as,h.crossOrigin);a.d.M(d,{crossOrigin:m,integrity:typeof h.integrity=="string"?h.integrity:void 0,nonce:typeof h.nonce=="string"?h.nonce:void 0})}}else h==null&&a.d.M(d)},ir.preload=function(d,h){if(typeof d=="string"&&typeof h=="object"&&h!==null&&typeof h.as=="string"){var m=h.as,p=u(m,h.crossOrigin);a.d.L(d,m,{crossOrigin:p,integrity:typeof h.integrity=="string"?h.integrity:void 0,nonce:typeof h.nonce=="string"?h.nonce:void 0,type:typeof h.type=="string"?h.type:void 0,fetchPriority:typeof h.fetchPriority=="string"?h.fetchPriority:void 0,referrerPolicy:typeof h.referrerPolicy=="string"?h.referrerPolicy:void 0,imageSrcSet:typeof h.imageSrcSet=="string"?h.imageSrcSet:void 0,imageSizes:typeof h.imageSizes=="string"?h.imageSizes:void 0,media:typeof h.media=="string"?h.media:void 0})}},ir.preloadModule=function(d,h){if(typeof d=="string")if(h){var m=u(h.as,h.crossOrigin);a.d.m(d,{as:typeof h.as=="string"&&h.as!=="script"?h.as:void 0,crossOrigin:m,integrity:typeof h.integrity=="string"?h.integrity:void 0})}else a.d.m(d)},ir.requestFormReset=function(d){a.d.r(d)},ir.unstable_batchedUpdates=function(d,h){return d(h)},ir.useFormState=function(d,h,m){return o.H.useFormState(d,h,m)},ir.useFormStatus=function(){return o.H.useHostTransitionStatus()},ir.version="19.2.4",ir}var Bk;function JN(){if(Bk)return ax.exports;Bk=1;function e(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),ax.exports=uD(),ax.exports}var Hk;function dD(){if(Hk)return Sd;Hk=1;var e=cD(),t=P0(),n=JN();function a(i){var c="https://react.dev/errors/"+i;if(1<arguments.length){c+="?args[]="+encodeURIComponent(arguments[1]);for(var f=2;f<arguments.length;f++)c+="&args[]="+encodeURIComponent(arguments[f])}return"Minified React error #"+i+"; visit "+c+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function r(i){return!(!i||i.nodeType!==1&&i.nodeType!==9&&i.nodeType!==11)}function s(i){var c=i,f=i;if(i.alternate)for(;c.return;)c=c.return;else{i=c;do c=i,(c.flags&4098)!==0&&(f=c.return),i=c.return;while(i)}return c.tag===3?f:null}function o(i){if(i.tag===13){var c=i.memoizedState;if(c===null&&(i=i.alternate,i!==null&&(c=i.memoizedState)),c!==null)return c.dehydrated}return null}function u(i){if(i.tag===31){var c=i.memoizedState;if(c===null&&(i=i.alternate,i!==null&&(c=i.memoizedState)),c!==null)return c.dehydrated}return null}function d(i){if(s(i)!==i)throw Error(a(188))}function h(i){var c=i.alternate;if(!c){if(c=s(i),c===null)throw Error(a(188));return c!==i?null:i}for(var f=i,g=c;;){var k=f.return;if(k===null)break;var T=k.alternate;if(T===null){if(g=k.return,g!==null){f=g;continue}break}if(k.child===T.child){for(T=k.child;T;){if(T===f)return d(k),i;if(T===g)return d(k),c;T=T.sibling}throw Error(a(188))}if(f.return!==g.return)f=k,g=T;else{for(var V=!1,ee=k.child;ee;){if(ee===f){V=!0,f=k,g=T;break}if(ee===g){V=!0,g=k,f=T;break}ee=ee.sibling}if(!V){for(ee=T.child;ee;){if(ee===f){V=!0,f=T,g=k;break}if(ee===g){V=!0,g=T,f=k;break}ee=ee.sibling}if(!V)throw Error(a(189))}}if(f.alternate!==g)throw Error(a(190))}if(f.tag!==3)throw Error(a(188));return f.stateNode.current===f?i:c}function m(i){var c=i.tag;if(c===5||c===26||c===27||c===6)return i;for(i=i.child;i!==null;){if(c=m(i),c!==null)return c;i=i.sibling}return null}var p=Object.assign,x=Symbol.for("react.element"),b=Symbol.for("react.transitional.element"),y=Symbol.for("react.portal"),w=Symbol.for("react.fragment"),E=Symbol.for("react.strict_mode"),v=Symbol.for("react.profiler"),N=Symbol.for("react.consumer"),S=Symbol.for("react.context"),C=Symbol.for("react.forward_ref"),I=Symbol.for("react.suspense"),O=Symbol.for("react.suspense_list"),_=Symbol.for("react.memo"),A=Symbol.for("react.lazy"),H=Symbol.for("react.activity"),G=Symbol.for("react.memo_cache_sentinel"),D=Symbol.iterator;function P(i){return i===null||typeof i!="object"?null:(i=D&&i[D]||i["@@iterator"],typeof i=="function"?i:null)}var Y=Symbol.for("react.client.reference");function U(i){if(i==null)return null;if(typeof i=="function")return i.$$typeof===Y?null:i.displayName||i.name||null;if(typeof i=="string")return i;switch(i){case w:return"Fragment";case v:return"Profiler";case E:return"StrictMode";case I:return"Suspense";case O:return"SuspenseList";case H:return"Activity"}if(typeof i=="object")switch(i.$$typeof){case y:return"Portal";case S:return i.displayName||"Context";case N:return(i._context.displayName||"Context")+".Consumer";case C:var c=i.render;return i=i.displayName,i||(i=c.displayName||c.name||"",i=i!==""?"ForwardRef("+i+")":"ForwardRef"),i;case _:return c=i.displayName||null,c!==null?c:U(i.type)||"Memo";case A:c=i._payload,i=i._init;try{return U(i(c))}catch{}}return null}var z=Array.isArray,L=t.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,q=n.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,W={pending:!1,data:null,method:null,action:null},X=[],B=-1;function $(i){return{current:i}}function Z(i){0>B||(i.current=X[B],X[B]=null,B--)}function K(i,c){B++,X[B]=i.current,i.current=c}var J=$(null),oe=$(null),me=$(null),ye=$(null);function ae(i,c){switch(K(me,c),K(oe,i),K(J,null),c.nodeType){case 9:case 11:i=(i=c.documentElement)&&(i=i.namespaceURI)?ek(i):0;break;default:if(i=c.tagName,c=c.namespaceURI)c=ek(c),i=tk(c,i);else switch(i){case"svg":i=1;break;case"math":i=2;break;default:i=0}}Z(J),K(J,i)}function ge(){Z(J),Z(oe),Z(me)}function Te(i){i.memoizedState!==null&&K(ye,i);var c=J.current,f=tk(c,i.type);c!==f&&(K(oe,i),K(J,f))}function Fe(i){oe.current===i&&(Z(J),Z(oe)),ye.current===i&&(Z(ye),yd._currentValue=W)}var Me,Le;function Ee(i){if(Me===void 0)try{throw Error()}catch(f){var c=f.stack.trim().match(/\n( *(at )?)/);Me=c&&c[1]||"",Le=-1<f.stack.indexOf(`
3
3
  at`)?" (<anonymous>)":-1<f.stack.indexOf("@")?"@unknown:0:0":""}return`
4
4
  `+Me+i+Le}var ze=!1;function De(i,c){if(!i||ze)return"";ze=!0;var f=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var g={DetermineComponentFrameRoot:function(){try{if(c){var Xe=function(){throw Error()};if(Object.defineProperty(Xe.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(Xe,[])}catch(qe){var He=qe}Reflect.construct(i,[],Xe)}else{try{Xe.call()}catch(qe){He=qe}i.call(Xe.prototype)}}else{try{throw Error()}catch(qe){He=qe}(Xe=i())&&typeof Xe.catch=="function"&&Xe.catch(function(){})}}catch(qe){if(qe&&He&&typeof qe.stack=="string")return[qe.stack,He.stack]}return[null,null]}};g.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var k=Object.getOwnPropertyDescriptor(g.DetermineComponentFrameRoot,"name");k&&k.configurable&&Object.defineProperty(g.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var T=g.DetermineComponentFrameRoot(),V=T[0],ee=T[1];if(V&&ee){var be=V.split(`
@@ -63,7 +63,7 @@ Economist: You analyze through incentives and trade-offs...`,"fanout.confirm":"F
63
63
  `);m=w.pop()||"";for(const E of w){const v=E.trim();if(!v.startsWith("data: "))continue;const N=v.slice(6);if(N==="[DONE]")continue;let S;try{S=JSON.parse(N)}catch{continue}if(S.error){const _=typeof S.error=="string"?S.error:S.error.message;throw new Error(_||"Upstream stream error")}const C=S.choices?.[0];if(!C)continue;const I=C.delta;I?.content&&(p+=I.content,a(I.content));const O=I?.reasoning??I?.reasoning_content;O&&r(O);for(const _ of I?.annotations??[]){const A=_.url_citation;A?.url&&!s.has(A.url)&&s.set(A.url,{title:A.title||A.url,url:A.url,media:"Web"})}C.finish_reason&&(x=C.finish_reason)}}return{text:p,finishReason:x}}async function Zq(e,t,n,a,r,s,o,u){const d=y8(n,s),h=w2(e.baseURL)&&u!==!1,m=new Map;let p="",x="";const b=w=>{p+=w,a(w,p)},y=w=>{x+=w,o?.onReasoning?.(w,x)};try{let w=await yE(e,h?`${t}:online`:t,d,b,y,m,r);if(h&&p.length===0&&(w=await yE(e,t,d,b,y,m,r)),p.length===0)throw new Error(`Model produced no text (finish: ${w.finishReason}, model: ${t}${h?" via :online":""})`);return m.size>0&&o?.onSources?.([...m.values()]),p}catch(w){throw v8(w)}}async function Jq(e,t,n,a){try{const r=await fetch(`${e.baseURL.replace(/\/$/,"")}/chat/completions`,{method:"POST",headers:{Authorization:`Bearer ${e.apiKey}`,"Content-Type":"application/json","X-Title":"ThoughtDAG"},body:JSON.stringify({model:t,messages:y8(n,a)})});if(!r.ok){const o=await r.json().catch(()=>null);throw new Error(o?.error?.message||`HTTP ${r.status}`)}return(await r.json()).choices?.[0]?.message?.content??""}catch(r){throw v8(r)}}const e$=`${hi}/api/claude`,w8=()=>{const e=rs();return e.length>0?e:void 0},t$=`${hi}/api/stream`,n$=`${hi}/api/pdf-extract`,a$=`${hi}/api/approvals`;async function r$(e,t){const n=e.id,a=typeof t=="string"?{confirmed:t!=="rejected",...t==="allowed-session"?{scope:"session"}:{}}:t;if(e.channel?.runId&&window.desktopAgents)try{return await window.desktopAgents.answer(e.channel.runId,n,a)}catch{return!1}const r="confirmed"in a&&a.confirmed?"allowed-once":"rejected";try{return(await fetch(`${a$}/${encodeURIComponent(n)}`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"same-origin",body:JSON.stringify({outcome:r})})).ok}catch{return!1}}async function s$(e){const t=await fetch(n$,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({base64:e})});if(!t.ok){const n=await t.json().catch(()=>({error:`HTTP ${t.status}`}));throw new Error(Gl(n,`HTTP ${t.status}`))}return t.json()}async function i$(e){try{const t=await fetch(`${hi}/api/fetch-url`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:e})});if(!t.ok){const n=await t.json().catch(()=>({error:t.status===404?"Proxy has no /api/fetch-url — restart it (npm run server)":`HTTP ${t.status}`}));throw new Error(Gl(n,`HTTP ${t.status}`))}return t.json()}catch(t){throw E2(t)}}function E2(e){if(e instanceof DOMException&&e.name==="AbortError")return e;const t=e instanceof Error?e.message:"Unknown error";return new Error(/fetch|network|Failed to fetch/i.test(t)?`${t} — is the proxy running? (npm run server)`:t)}async function k8(e,t){if(!t?.length)return t;const n=await hr(),a=e??n?.default??void 0,r=a?n?.models.find(s=>s.id===a):void 0;if(!(r&&r.vision===!1&&t.every(s=>s.hasCompanion)))return t}async function E8(e,t){if(!t?.length)return;const n=await hr(),a=e??n?.default??void 0,r=a?n?.models.find(s=>s.id===a):void 0;if(r&&r.vision===!1)throw new Error(Ne("error.textOnlyModelImages"))}async function Ka(e,t,n,a){const r=n||ce.getState().selectedModel||void 0;t=await k8(r,t);const s=k2();if(s&&r)return await E8(r,t),Jq(s,r,e,t);try{const o=await fetch(e$,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({messages:e,images:t?.length?t:void 0,model:n||ce.getState().selectedModel||void 0,...a?.fast?{fast:!0}:{},providers:w8()})});if(!o.ok){const d=await o.json().catch(()=>({error:"Unknown error"}));throw new Error(Gl(d,`HTTP ${o.status}`))}return(await o.json()).text}catch(o){throw E2(o)}}async function S8(e,t,n,a,r,s,o,u){const d=o||ce.getState().selectedModel||void 0;if(d&&li(d)&&window.desktopAgents)return r?.onDispatch?.({messages:e,images:a??[],model:d,toolPrefs:s??{},lane:"proxy"}),KV(e,t,n,a,r,d,u?.cwd?{cwd:u.cwd,sessionPath:u.sessionPath,forkEntryId:u.forkEntryId,continue:u.continue}:void 0,u?.nodeId);a=await k8(d,a);let h=!1;const m={...r,onRerouted:(w,E)=>{h=!0,r?.onRerouted?.(w,E)}},p=async(w,E)=>{const v=k2();return v&&d?(await E8(d,w),r?.onDispatch?.({messages:e,images:w??[],model:d,toolPrefs:s??{},lane:"direct"}),Zq(v,d,e,E,n,w,m,s?.web)):(r?.onDispatch?.({messages:e,images:w??[],model:d??"",toolPrefs:s??{},lane:"proxy"}),y(w,E))},x=d?Tq(d):void 0,b=!!d&&rs().some(w=>w.models.some(E=>E.id===d));if(a?.length&&d&&b&&x!==!1){const w=d.split("/").pop()??d,E=(N,S)=>{Aq(d,N)&&(Y0(rs()).then(Kl).catch(()=>{}),We("info",ve(Ne(S),{m:w})))};let v=!1;try{const N=await p(a,(S,C)=>{v=!0,t(S,C)});return x===void 0&&!h&&N.trim()&&E(!0,"toast.visionLearnedTrue"),N}catch(N){if(N instanceof DOMException&&N.name==="AbortError"||v||h)throw N;if(x===!0){const C=N instanceof Error?N.message:String(N);throw new Error(`${C} ${Ne("error.visionDeclaredHint")}`)}const S=await p(void 0,t);return S.trim()&&E(!1,"toast.visionLearnedFalse"),S}}return p(a,t);async function y(w,E){try{const v=await fetch(t$,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({messages:e,images:w?.length?w:void 0,webSearch:s?.web,scholarSearch:s?.scholar,mcpTools:s?.mcp,...ce.getState().searchEnginePref!=="server"?{searchEngine:ce.getState().searchEnginePref}:{},...ce.getState().anysearchKey?{anysearchKey:ce.getState().anysearchKey}:{},model:o||ce.getState().selectedModel||void 0,providers:w8(),...u?{harness:u}:{}}),signal:n});if(!v.ok){const _=await v.json().catch(()=>({error:"Unknown error"}));throw new Error(Gl(_,`HTTP ${v.status}`))}const N=v.body.getReader(),S=new TextDecoder;let C="",I="",O="";for(;;){const{done:_,value:A}=await N.read();if(_)break;C+=S.decode(A,{stream:!0});const H=C.split(`
64
64
  `);C=H.pop()||"";for(const G of H){const D=G.trim();if(!D||!D.startsWith("data: "))continue;const P=D.slice(6);if(P!=="[DONE]")try{const Y=JSON.parse(P);if(Y.error)throw new Error(Gl(Y.error,"Upstream stream error"));Y.text&&(I+=Y.text,E(Y.text,I)),Y.reasoning&&(O+=Y.reasoning,m.onReasoning?.(Y.reasoning,O)),Y.tool?.query&&m.onToolCall?.(Y.tool.name,Y.tool.query),Y.gatewaySearch&&m.onGatewaySearch?.(),typeof Y.harnessSession=="string"&&m.onHarnessSession?.(Y.harnessSession,!!Y.continued),Y.harnessTurn?.session&&m.onHarnessTurn?.(Y.harnessTurn),Y.approval?.id&&m.onApproval?.(Y.approval),Y.approvalDecided?.id&&m.onApprovalDecided?.(Y.approvalDecided),Array.isArray(Y.sources)&&m.onSources?.(Y.sources),Y.rerouted?.to&&(We("info",ve(Ne("toast.visionRerouted"),{from:Y.rerouted.from,to:Y.rerouted.to}),7e3),m.onRerouted?.(Y.rerouted.from,Y.rerouted.to)),Y.imageFallback?.model&&(We("info",ve(Ne("toast.imagesAsText"),{model:Y.imageFallback.model}),9e3),m.onImageFallback?.(Y.imageFallback.model))}catch(Y){if(Y instanceof Error&&Y.message!==P)throw Y}}}return I}catch(v){throw E2(v)}}}const Jb="att-content:",N8=e=>`${Jb}${e}`,T8=e=>e.type==="application/pdf"&&!!e.content&&!e.contentInVault;async function S2(e){return T8(e)?(await Pr(N8(e.id),e.content),{...e,content:"",contentInVault:!0}):e}async function N2(e){return e.contentInVault?await Zo(N8(e.id))??"":e.content}async function T2(e){const t=[];for(const n of e){const a=n.data.attachments;if(!a?.some(s=>s.contentInVault)){t.push(n);continue}const r=[];for(const s of a){if(!s.contentInVault){r.push(s);continue}const o=await N2(s),u={...s,content:o};delete u.contentInVault,r.push(u)}t.push({...n,data:{...n.data,attachments:r}})}return t}async function Tp(e){const t=[];for(const n of e){const a=n.data.attachments;if(!a?.some(T8)){t.push(n);continue}const r=[];for(const s of a)r.push(await S2(s));t.push({...n,data:{...n.data,attachments:r}})}return t}async function A8(e){const t=await m8();let n=0;for(const a of t)typeof a!="string"||!a.startsWith(Jb)||e.has(a.slice(Jb.length))||(await Su(a),n++);return n}const o$=Object.freeze(Object.defineProperty({__proto__:null,gcVault:A8,inlineVaultedContent:T2,internAttachment:S2,internNodes:Tp,loadAttachmentContent:N2},Symbol.toStringTag,{value:"Module"}));function l$(e){return e.replace(/<script[\s\S]*?<\/script>/gi," ").replace(/<style[\s\S]*?<\/style>/gi," ").replace(/<[^>]+>/g," ").replace(/&nbsp;/g," ").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/[ \t]+/g," ").replace(/\s*\n\s*(\s*\n\s*)+/g,`
65
65
 
66
- `).trim()}const c$=/\.(md|txt|js|ts|tsx|jsx|py|json|csv|yaml|yml|toml|sh|bash|zsh|c|cpp|h|hpp|java|rs|go|rb|swift|kt|css|xml|sql|r|m|lua)$/i,u$=/\.x?html?$/i,d$=/\.(pptx?|key|odp|doc|rtf|odt|xlsx?|numbers|ods)$/i,w0="image/*,.pdf,.txt,.md,.js,.ts,.tsx,.jsx,.py,.json,.csv,.yaml,.yml,.toml,.sh,.c,.cpp,.h,.java,.rs,.go,.rb,.swift,.css,.html,.htm,.xml,.sql";function nu(e){return`${e.name}|${e.size}|${e.content?.substring(0,100)}`}function h$(e){return new Promise(t=>{const n=En(),a=new Date().toISOString(),r=e.type.startsWith("image/"),s=e.type==="application/pdf"||e.name.endsWith(".pdf"),o=e.type==="text/html"||u$.test(e.name),u=e.type.startsWith("text/")||c$.test(e.name),d=e.name.toLowerCase().endsWith(".docx");if(r){const h=new FileReader;h.onload=()=>{const m=h.result.split(",")[1];t({id:n,name:e.name,type:e.type,size:e.size,addedAt:a,content:m,thumbnailUrl:h.result})},h.readAsDataURL(e)}else if(s){const h=new FileReader;h.onload=()=>{const m=h.result.split(",")[1];t({id:n,name:e.name,type:"application/pdf",size:e.size,addedAt:a,content:m})},h.readAsDataURL(e)}else d?e.arrayBuffer().then(async h=>{try{const p=await(await pt(()=>import("./index-CPB-aTvu.js").then(x=>x.i),[])).extractRawText({arrayBuffer:h});t({id:n,name:e.name,type:"text/plain",size:e.size,addedAt:a,content:p.value.trim()})}catch{t(null)}}):o?e.text().then(h=>{t({id:n,name:e.name,type:"text/html",size:e.size,addedAt:a,content:h})}):u?e.text().then(h=>{t({id:n,name:e.name,type:e.type||"text/plain",size:e.size,addedAt:a,content:h})}):t(null)})}async function vE(e){const[t,n]=await Promise.all([pt(()=>import("./pdf-gh-BrLFn.js"),[]),pt(()=>import("./pdf.worker.min-C_APr3k7.js"),[])]);t.GlobalWorkerOptions.workerSrc=n.default;const a=Uint8Array.from(atob(e),r=>r.charCodeAt(0));return t.getDocument({data:a,verbosity:0}).promise}const f$=150;async function wE(e){const t=f$/72,n=[];for(let a=1;a<=e.numPages;a++){const r=document.createElement("canvas");try{const s=await e.getPage(a),o=s.getViewport({scale:t});r.width=Math.ceil(o.width),r.height=Math.ceil(o.height);const u=r.getContext("2d");if(!u)throw new Error("no 2d context");await s.render({canvasContext:u,viewport:o}).promise}catch{r.width=8,r.height=8}n.push(r.toDataURL("image/png").split(",")[1])}return n}async function X0(e,t){if(d$.test(e.name)){We("info",`${e.name}: ${Ne("content.officeExportHint")}`);return}const n=await h$(e);if(!n)return;if(n.type==="text/html"){t.add({...n,isExtracting:!0});try{const{extractHtmlMaterial:r}=await pt(async()=>{const{extractHtmlMaterial:o}=await Promise.resolve().then(()=>FM);return{extractHtmlMaterial:o}},void 0),s=await r(n.content);t.update(n.id,{extractedText:s.markdown,numPages:s.numPages,isExtracting:!1})}catch{t.update(n.id,{extractedText:l$(n.content),isExtracting:!1})}return}if(n.type!=="application/pdf"){t.add(n);return}const a=await S2(n);t.add({...a,isExtracting:!0});try{const r=await s$(n.content);if(!r.numPages&&!r.text?.trim())throw new Error("empty extraction result");const s=r.numPages||0;let o=r.images;if(!o?.length)try{const u=await vE(n.content);o=await wE(u),u.destroy()}catch{o=void 0}t.update(n.id,{extractedText:r.text,pageImages:o?.length?o:void 0,numPages:s,renderMode:s>aE?"text-only":"full",isExtracting:!1})}catch{try{const r=await vE(n.content),s=[];for(let u=1;u<=r.numPages;u++)try{const h=await(await r.getPage(u)).getTextContent();s.push(h.items.map(m=>"str"in m?m.str:"").join(" "))}catch{s.push("")}let o;try{o=await wE(r)}catch{o=void 0}r.destroy(),t.update(n.id,{extractedText:s.join(`
66
+ `).trim()}const c$=/\.(md|txt|js|ts|tsx|jsx|py|json|csv|yaml|yml|toml|sh|bash|zsh|c|cpp|h|hpp|java|rs|go|rb|swift|kt|css|xml|sql|r|m|lua)$/i,u$=/\.x?html?$/i,d$=/\.(pptx?|key|odp|doc|rtf|odt|xlsx?|numbers|ods)$/i,w0="image/*,.pdf,.txt,.md,.js,.ts,.tsx,.jsx,.py,.json,.csv,.yaml,.yml,.toml,.sh,.c,.cpp,.h,.java,.rs,.go,.rb,.swift,.css,.html,.htm,.xml,.sql";function nu(e){return`${e.name}|${e.size}|${e.content?.substring(0,100)}`}function h$(e){return new Promise(t=>{const n=En(),a=new Date().toISOString(),r=e.type.startsWith("image/"),s=e.type==="application/pdf"||e.name.endsWith(".pdf"),o=e.type==="text/html"||u$.test(e.name),u=e.type.startsWith("text/")||c$.test(e.name),d=e.name.toLowerCase().endsWith(".docx");if(r){const h=new FileReader;h.onload=()=>{const m=h.result.split(",")[1];t({id:n,name:e.name,type:e.type,size:e.size,addedAt:a,content:m,thumbnailUrl:h.result})},h.readAsDataURL(e)}else if(s){const h=new FileReader;h.onload=()=>{const m=h.result.split(",")[1];t({id:n,name:e.name,type:"application/pdf",size:e.size,addedAt:a,content:m})},h.readAsDataURL(e)}else d?e.arrayBuffer().then(async h=>{try{const p=await(await pt(()=>import("./index-D-nwx3XX.js").then(x=>x.i),[])).extractRawText({arrayBuffer:h});t({id:n,name:e.name,type:"text/plain",size:e.size,addedAt:a,content:p.value.trim()})}catch{t(null)}}):o?e.text().then(h=>{t({id:n,name:e.name,type:"text/html",size:e.size,addedAt:a,content:h})}):u?e.text().then(h=>{t({id:n,name:e.name,type:e.type||"text/plain",size:e.size,addedAt:a,content:h})}):t(null)})}async function vE(e){const[t,n]=await Promise.all([pt(()=>import("./pdf-gh-BrLFn.js"),[]),pt(()=>import("./pdf.worker.min-C_APr3k7.js"),[])]);t.GlobalWorkerOptions.workerSrc=n.default;const a=Uint8Array.from(atob(e),r=>r.charCodeAt(0));return t.getDocument({data:a,verbosity:0}).promise}const f$=150;async function wE(e){const t=f$/72,n=[];for(let a=1;a<=e.numPages;a++){const r=document.createElement("canvas");try{const s=await e.getPage(a),o=s.getViewport({scale:t});r.width=Math.ceil(o.width),r.height=Math.ceil(o.height);const u=r.getContext("2d");if(!u)throw new Error("no 2d context");await s.render({canvasContext:u,viewport:o}).promise}catch{r.width=8,r.height=8}n.push(r.toDataURL("image/png").split(",")[1])}return n}async function X0(e,t){if(d$.test(e.name)){We("info",`${e.name}: ${Ne("content.officeExportHint")}`);return}const n=await h$(e);if(!n)return;if(n.type==="text/html"){t.add({...n,isExtracting:!0});try{const{extractHtmlMaterial:r}=await pt(async()=>{const{extractHtmlMaterial:o}=await Promise.resolve().then(()=>FM);return{extractHtmlMaterial:o}},void 0),s=await r(n.content);t.update(n.id,{extractedText:s.markdown,numPages:s.numPages,isExtracting:!1})}catch{t.update(n.id,{extractedText:l$(n.content),isExtracting:!1})}return}if(n.type!=="application/pdf"){t.add(n);return}const a=await S2(n);t.add({...a,isExtracting:!0});try{const r=await s$(n.content);if(!r.numPages&&!r.text?.trim())throw new Error("empty extraction result");const s=r.numPages||0;let o=r.images;if(!o?.length)try{const u=await vE(n.content);o=await wE(u),u.destroy()}catch{o=void 0}t.update(n.id,{extractedText:r.text,pageImages:o?.length?o:void 0,numPages:s,renderMode:s>aE?"text-only":"full",isExtracting:!1})}catch{try{const r=await vE(n.content),s=[];for(let u=1;u<=r.numPages;u++)try{const h=await(await r.getPage(u)).getTextContent();s.push(h.items.map(m=>"str"in m?m.str:"").join(" "))}catch{s.push("")}let o;try{o=await wE(r)}catch{o=void 0}r.destroy(),t.update(n.id,{extractedText:s.join(`
67
67
 
68
68
  `).trim(),pageImages:o?.length?o:void 0,numPages:r.numPages,renderMode:r.numPages>aE?"text-only":"full",isExtracting:!1})}catch{t.update(n.id,{isExtracting:!1})}}}const Ad="[*_`~()#>\\[\\]|-]*",m$="\\s+(?:(?:\\d{1,3}[.)]|[-*+>|]|#{1,6}|[-:|]{3,})\\s+)*";function A2(e){const t=[...e.trim()];if(t.length===0)return null;const n=[];let a=!1;for(const r of t){if(/\s/.test(r)){a=!0;continue}const s=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");n.length===0?n.push(s):a?n.push(`${Ad}${m$}${Ad}${s}`):n.push(`${Ad}${s}`),a=!1}try{return new RegExp(Ad+n.join("")+Ad,"g")}catch{return null}}function p$(e,t){const n=A2(t);return n?n.test(e):!1}function dm(e,t){const n=e??[],a=n.filter(r=>p$(t,r.text));return a.length===n.length?n:a}function kE(e){const t=e.data.question.replace(/\s+/g," ").trim();return t.length>60?`${t.slice(0,60)}…`:t}function C8(e){const t=e.data.highlightMode||"off",n=e.data.highlights||[];if(t==="filter"&&n.length>0)return n.map(a=>a.text).join(`
69
69
 
@@ -153,7 +153,7 @@ ${y??`*${ve(Ne("reader.pageFail"),{n:p+1})}*`}`),n(p+1,d.length)}if(!a()){if(!m)
153
153
  `)[0].slice(0,80)}catch{}return null}function MW(e){for(const t of e){if(t.type!=="user/message")continue;const n=t.data;if(!n||n.source?.kind&&n.source.kind!=="user")continue;const a=(n.content??[]).filter(r=>r.type==="text"&&r.text).map(r=>r.text).join(`
154
154
  `).trim();if(a&&!a.startsWith("<"))return a.split(`
155
155
  `)[0].slice(0,80)}return null}const e7="thoughtdag.atlas.disabledRoots",L2=()=>{try{return new Set(JSON.parse(localStorage.getItem(e7)??"[]"))}catch{return new Set}};function IW(e,t){const n=L2();t?n.add(e):n.delete(e),localStorage.setItem(e7,JSON.stringify([...n]))}const Hm=new Set;async function OW(){const e=window.desktopSessions;if(!e)return[];const t=L2(),n=(await e.roots().catch(()=>[])).filter(r=>r.exists&&!t.has(r.key)).map(r=>r.key),a=[];for(const r of n){const o=[...await e.list(r).catch(()=>[])].sort((d,h)=>h.mtime-d.mtime),u=12;for(let d=0;d<o.length;d+=u){const h=await Promise.all(o.slice(d,d+u).map(async m=>{const p=m.rel.endsWith(".zstd")?IE:_W,x=await e.head(r,m.rel,p).catch(()=>"");if(!x)return null;const b=OE(r,m.rel,x,m.mtime,m.size);if(b)return b;const y=await e.head(r,m.rel,IE).catch(()=>"");return y.length>x.length?OE(r,m.rel,y,m.mtime,m.size):null}));for(const m of h)m&&a.push(m)}}Hm.clear();for(const r of a)Hm.add(r.sessionId);return a.sort((r,s)=>s.mtime-r.mtime)}function DW(e){const t=new Map;for(const n of e){const a=n.cwd??"";let r=t.get(a);r||(r={cwd:n.cwd,name:n.cwd?n.cwd.split("/").filter(Boolean).pop()??n.cwd:"",cards:[]},t.set(a,r)),r.cards.push(n)}return[...t.values()].sort((n,a)=>!n.cwd!=!a.cwd?n.cwd?-1:1:a.cards[0].mtime-n.cards[0].mtime)}async function DE(e,t){let n="";for(;;){const a=await t();if(a===null)break;const r=(n+a).split(`
156
- `);n=r.pop()??"";for(const s of r)e.feedLine(s)}return n&&e.feedLine(n),e.toSubagentSession()}async function Kc(e,t,n,a){if(!e?.adopt||!e.sessionId||!window.desktopSessions)return e;const r=[];try{const{shellSessionReader:s}=await pt(async()=>{const{shellSessionReader:o}=await import("./canonical-46lAq3XC.js");return{shellSessionReader:o}},[]);if(e.source==="claude-code"){const o=`${n.replace(/\.jsonl$/,"")}/subagents/`,u=(await window.desktopSessions.list(t)).map(d=>d.rel).filter(d=>d.startsWith(o)&&d.endsWith(".jsonl"));if(u.length){const{ClaudeSessionCollector:d}=await pt(async()=>{const{ClaudeSessionCollector:h}=await import("./claude-code-session-DtdYqKTH.js");return{ClaudeSessionCollector:h}},__vite__mapDeps([0,1]));for(const h of u){const m=await DE(new d,s(t,h)).catch(()=>null);m&&r.push(m)}}}else if(e.source==="codex"&&a){const o=a.filter(u=>u.runner==="codex"&&u.subagent&&u.parentSessionId===e.sessionId);if(o.length){const{CodexSessionCollector:u}=await pt(async()=>{const{CodexSessionCollector:d}=await import("./codex-session-C1JXlxO_.js");return{CodexSessionCollector:d}},__vite__mapDeps([2,1]));for(const d of o){const h=await DE(new u,s(d.rootKey,d.rel)).catch(()=>null);h&&r.push(h)}}}}catch{}return r.length&&e.adopt(r),e}function t7(e,t){return e.find(n=>(n.rel.split("/").pop()??n.rel).includes(t))}let RE=!1,ry=null;function RW(){ry?.()}let sy=null;async function P2(e){return sy?(await sy(e),!0):!1}function jW(){const e=window.desktopSessions;if(!e||RE)return;RE=!0,e.watchStart();let t=!1,n=null;const a=async d=>{if(t){n=d;return}t=!0;try{window.dispatchEvent(new CustomEvent("td:sessions-changed"));const{useProjects:h,subscribedSessionIds:m}=await pt(async()=>{const{useProjects:_,subscribedSessionIds:A}=await Promise.resolve().then(()=>Na);return{useProjects:_,subscribedSessionIds:A}},void 0),{activeId:p,projects:x}=h.getState(),b=x.find(_=>_.id===p),y=await e.head(d.rootKey,d.rel,262144).catch(()=>"");if(!y)return;const w=ME(y);if(!w)return;const E=!!b&&m(b).includes(w);let v=null;if(!E){if(x.some(G=>m(G).includes(w)))return;const{useStore:A}=await pt(async()=>{const{useStore:G}=await Promise.resolve().then(()=>ws);return{useStore:G}},void 0);if(!A.getState().nodes.some(G=>G.data.importSource?.sessionId===w)){const{parseAnchor:G}=await pt(async()=>{const{parseAnchor:P}=await import("./experiment-loop-PGHklznL.js");return{parseAnchor:P}},[]),D=G(y);if(!D||!x.some(P=>P.id===D.project))return;if(v=D.project,v!==p){We("info",Ne("atlas.mountPending"),9e3);return}}}const{streamRunnerConversation:N}=await pt(async()=>{const{streamRunnerConversation:_}=await import("./index-CjJoJV4P.js");return{streamRunnerConversation:_}},[]),{importOrAppendConversation:S,shellSessionReader:C}=await pt(async()=>{const{importOrAppendConversation:_,shellSessionReader:A}=await import("./canonical-46lAq3XC.js");return{importOrAppendConversation:_,shellSessionReader:A}},[]),I=await Kc(await N(C(d.rootKey,d.rel)).catch(()=>null),d.rootKey,d.rel),O=await S(I,{focusOnRefresh:!1});O?.kind==="appended"?We("success",ve(Ne("atlas.liveAppended"),{n:O.turns}),8e3):O?.kind==="mounted"&&We("success",ve(Ne(O.mode==="continue"?"atlas.mountedChapter":"atlas.mountedBranch"),{n:O.turns}),9e3)}finally{if(t=!1,n){const h=n;n=null,a(h)}}};e.onSessionsChanged(d=>{a(d)});const r=async d=>{if(!d)return;const{useStore:h}=await pt(async()=>{const{useStore:x}=await Promise.resolve().then(()=>ws);return{useStore:x}},void 0),{useUiStore:m}=await pt(async()=>{const{useUiStore:x}=await Promise.resolve().then(()=>gu);return{useUiStore:x}},void 0),p=h.getState().nodes.find(x=>x.data.importSource?.itemIds?.includes(d));p&&m.getState().setArrivalFocusNodeId(p.id)},s=async(d,h)=>{const{useProjects:m,switchProject:p}=await pt(async()=>{const{useProjects:w,switchProject:E}=await Promise.resolve().then(()=>Na);return{useProjects:w,switchProject:E}},void 0),x=m.getState().projects,b=x.filter(w=>w.name===d),y=x.find(w=>w.id===d)??(b.length===1?b[0]:void 0);if(!y){We("error",Ne("handoff.deeplinkMiss"));return}if(await p(y.id),h){const{useStore:w}=await pt(async()=>{const{useStore:v}=await Promise.resolve().then(()=>ws);return{useStore:v}},void 0),{useUiStore:E}=await pt(async()=>{const{useUiStore:v}=await Promise.resolve().then(()=>gu);return{useUiStore:v}},void 0);w.getState().nodes.some(v=>v.id===h)&&E.getState().setArrivalFocusNodeId(h)}},o=async d=>{let h="",m="";try{const N=new URL(d),S=N.searchParams.get("canvas");if(S){await s(S,N.searchParams.get("node")??"");return}h=N.searchParams.get("session")??"",m=N.searchParams.get("turn")??""}catch{return}if(!/^[A-Za-z0-9_-]{8,}$/.test(h))return;/^[A-Za-z0-9_-]*$/.test(m)||(m="");const p=await e.roots().catch(()=>[]);let x=null;for(const N of p){const S=await e.list(N.key).catch(()=>[]),C=t7(S,h);if(C){x={rootKey:N.key,rel:C.rel};break}}if(!x){const N=[];for(const S of p)for(const C of await e.list(S.key).catch(()=>[]))N.push({rootKey:S.key,rel:C.rel,mtime:C.mtime});N.sort((S,C)=>C.mtime-S.mtime);for(const S of N.slice(0,40)){const C=await e.head(S.rootKey,S.rel,262144).catch(()=>"");if(C&&ME(C)===h){x=S;break}}}if(!x){We("error",Ne("handoff.deeplinkMiss"));return}const{streamRunnerConversation:b}=await pt(async()=>{const{streamRunnerConversation:N}=await import("./index-CjJoJV4P.js");return{streamRunnerConversation:N}},[]),{importOrAppendConversation:y,shellSessionReader:w}=await pt(async()=>{const{importOrAppendConversation:N,shellSessionReader:S}=await import("./canonical-46lAq3XC.js");return{importOrAppendConversation:N,shellSessionReader:S}},[]),E=await Kc(await b(w(x.rootKey,x.rel)).catch(()=>null),x.rootKey,x.rel),v=await y(E);v?v.kind==="appended"?We("success",ve(Ne("atlas.liveAppended"),{n:v.turns}),8e3):v.kind==="mounted"?We("success",ve(Ne(v.mode==="continue"?"atlas.mountedChapter":"atlas.mountedBranch"),{n:v.turns}),9e3):v.kind==="imported"&&We("success",ve(Ne("toast.importedChats"),{n:1,m:v.nodeCount}),8e3):We("error",Ne("handoff.notASession")),v&&m&&await r(m)};sy=o,e.onDeepLink?.(d=>{o(d)}),(async()=>{const{bootProjects:d}=await pt(async()=>{const{bootProjects:m}=await Promise.resolve().then(()=>Na);return{bootProjects:m}},void 0);await d();const h=await e.pendingDeepLink?.().catch(()=>null);h&&o(h)})();const u="thoughtdag.atlas.sweepmark";ry=async()=>{const{bootProjects:d}=await pt(async()=>{const{bootProjects:y}=await Promise.resolve().then(()=>Na);return{bootProjects:y}},void 0);await d();const h=await e.roots().catch(()=>[]),m=[];for(const y of h){const w=await e.list(y.key).catch(()=>[]);for(const E of w)m.push({rootKey:y.key,rel:E.rel,mtime:E.mtime,size:E.size})}let p={};try{p=JSON.parse(localStorage.getItem(u)??"{}")}catch{}const x=Object.keys(p).length===0;m.sort((y,w)=>w.mtime-y.mtime);const b=m.filter((y,w)=>{const E=`${y.mtime}|${y.size}`;return p[`${y.rootKey}|${y.rel}`]===E?!1:x?w<30:!0});for(const y of b)await a({rootKey:y.rootKey,rel:y.rel});for(const y of m)p[`${y.rootKey}|${y.rel}`]=`${y.mtime}|${y.size}`;localStorage.setItem(u,JSON.stringify(p))},ry()}const n7=Object.freeze(Object.defineProperty({__proto__:null,openWhyLink:P2,pickSessionFile:t7,startLiveMirror:jW,sweepRecentSessions:RW},Symbol.toStringTag,{value:"Module"})),a7=(e,t)=>`td:card:${e}#${t}`,LW=420;let Cx=0;const PW=4;async function r7(e,t){try{const n=await Zo(a7(e,t));return typeof n=="string"&&n?n:void 0}catch{return}}async function s7(e,t,n){const a=(await hr())?.default??void 0,r=`Condense the past exchange below into a card of at most 60 words (or 120 Chinese characters), in the exchange's own language: what was asked, what was concluded or decided, the names, numbers and file names that matter. No preamble, no markdown. Output only the card.
156
+ `);n=r.pop()??"";for(const s of r)e.feedLine(s)}return n&&e.feedLine(n),e.toSubagentSession()}async function Kc(e,t,n,a){if(!e?.adopt||!e.sessionId||!window.desktopSessions)return e;const r=[];try{const{shellSessionReader:s}=await pt(async()=>{const{shellSessionReader:o}=await import("./canonical-Bkq2Xinv.js");return{shellSessionReader:o}},[]);if(e.source==="claude-code"){const o=`${n.replace(/\.jsonl$/,"")}/subagents/`,u=(await window.desktopSessions.list(t)).map(d=>d.rel).filter(d=>d.startsWith(o)&&d.endsWith(".jsonl"));if(u.length){const{ClaudeSessionCollector:d}=await pt(async()=>{const{ClaudeSessionCollector:h}=await import("./claude-code-session-CmZZMVmM.js");return{ClaudeSessionCollector:h}},__vite__mapDeps([0,1]));for(const h of u){const m=await DE(new d,s(t,h)).catch(()=>null);m&&r.push(m)}}}else if(e.source==="codex"&&a){const o=a.filter(u=>u.runner==="codex"&&u.subagent&&u.parentSessionId===e.sessionId);if(o.length){const{CodexSessionCollector:u}=await pt(async()=>{const{CodexSessionCollector:d}=await import("./codex-session-CcVN_Kn7.js");return{CodexSessionCollector:d}},__vite__mapDeps([2,1]));for(const d of o){const h=await DE(new u,s(d.rootKey,d.rel)).catch(()=>null);h&&r.push(h)}}}}catch{}return r.length&&e.adopt(r),e}function t7(e,t){return e.find(n=>(n.rel.split("/").pop()??n.rel).includes(t))}let RE=!1,ry=null;function RW(){ry?.()}let sy=null;async function P2(e){return sy?(await sy(e),!0):!1}function jW(){const e=window.desktopSessions;if(!e||RE)return;RE=!0,e.watchStart();let t=!1,n=null;const a=async d=>{if(t){n=d;return}t=!0;try{window.dispatchEvent(new CustomEvent("td:sessions-changed"));const{useProjects:h,subscribedSessionIds:m}=await pt(async()=>{const{useProjects:_,subscribedSessionIds:A}=await Promise.resolve().then(()=>Na);return{useProjects:_,subscribedSessionIds:A}},void 0),{activeId:p,projects:x}=h.getState(),b=x.find(_=>_.id===p),y=await e.head(d.rootKey,d.rel,262144).catch(()=>"");if(!y)return;const w=ME(y);if(!w)return;const E=!!b&&m(b).includes(w);let v=null;if(!E){if(x.some(G=>m(G).includes(w)))return;const{useStore:A}=await pt(async()=>{const{useStore:G}=await Promise.resolve().then(()=>ws);return{useStore:G}},void 0);if(!A.getState().nodes.some(G=>G.data.importSource?.sessionId===w)){const{parseAnchor:G}=await pt(async()=>{const{parseAnchor:P}=await import("./experiment-loop-D5X-o2kG.js");return{parseAnchor:P}},[]),D=G(y);if(!D||!x.some(P=>P.id===D.project))return;if(v=D.project,v!==p){We("info",Ne("atlas.mountPending"),9e3);return}}}const{streamRunnerConversation:N}=await pt(async()=>{const{streamRunnerConversation:_}=await import("./index-C4lWKzPK.js");return{streamRunnerConversation:_}},[]),{importOrAppendConversation:S,shellSessionReader:C}=await pt(async()=>{const{importOrAppendConversation:_,shellSessionReader:A}=await import("./canonical-Bkq2Xinv.js");return{importOrAppendConversation:_,shellSessionReader:A}},[]),I=await Kc(await N(C(d.rootKey,d.rel)).catch(()=>null),d.rootKey,d.rel),O=await S(I,{focusOnRefresh:!1});O?.kind==="appended"?We("success",ve(Ne("atlas.liveAppended"),{n:O.turns}),8e3):O?.kind==="mounted"&&We("success",ve(Ne(O.mode==="continue"?"atlas.mountedChapter":"atlas.mountedBranch"),{n:O.turns}),9e3)}finally{if(t=!1,n){const h=n;n=null,a(h)}}};e.onSessionsChanged(d=>{a(d)});const r=async d=>{if(!d)return;const{useStore:h}=await pt(async()=>{const{useStore:x}=await Promise.resolve().then(()=>ws);return{useStore:x}},void 0),{useUiStore:m}=await pt(async()=>{const{useUiStore:x}=await Promise.resolve().then(()=>gu);return{useUiStore:x}},void 0),p=h.getState().nodes.find(x=>x.data.importSource?.itemIds?.includes(d));p&&m.getState().setArrivalFocusNodeId(p.id)},s=async(d,h)=>{const{useProjects:m,switchProject:p}=await pt(async()=>{const{useProjects:w,switchProject:E}=await Promise.resolve().then(()=>Na);return{useProjects:w,switchProject:E}},void 0),x=m.getState().projects,b=x.filter(w=>w.name===d),y=x.find(w=>w.id===d)??(b.length===1?b[0]:void 0);if(!y){We("error",Ne("handoff.deeplinkMiss"));return}if(await p(y.id),h){const{useStore:w}=await pt(async()=>{const{useStore:v}=await Promise.resolve().then(()=>ws);return{useStore:v}},void 0),{useUiStore:E}=await pt(async()=>{const{useUiStore:v}=await Promise.resolve().then(()=>gu);return{useUiStore:v}},void 0);w.getState().nodes.some(v=>v.id===h)&&E.getState().setArrivalFocusNodeId(h)}},o=async d=>{let h="",m="";try{const N=new URL(d),S=N.searchParams.get("canvas");if(S){await s(S,N.searchParams.get("node")??"");return}h=N.searchParams.get("session")??"",m=N.searchParams.get("turn")??""}catch{return}if(!/^[A-Za-z0-9_-]{8,}$/.test(h))return;/^[A-Za-z0-9_-]*$/.test(m)||(m="");const p=await e.roots().catch(()=>[]);let x=null;for(const N of p){const S=await e.list(N.key).catch(()=>[]),C=t7(S,h);if(C){x={rootKey:N.key,rel:C.rel};break}}if(!x){const N=[];for(const S of p)for(const C of await e.list(S.key).catch(()=>[]))N.push({rootKey:S.key,rel:C.rel,mtime:C.mtime});N.sort((S,C)=>C.mtime-S.mtime);for(const S of N.slice(0,40)){const C=await e.head(S.rootKey,S.rel,262144).catch(()=>"");if(C&&ME(C)===h){x=S;break}}}if(!x){We("error",Ne("handoff.deeplinkMiss"));return}const{streamRunnerConversation:b}=await pt(async()=>{const{streamRunnerConversation:N}=await import("./index-C4lWKzPK.js");return{streamRunnerConversation:N}},[]),{importOrAppendConversation:y,shellSessionReader:w}=await pt(async()=>{const{importOrAppendConversation:N,shellSessionReader:S}=await import("./canonical-Bkq2Xinv.js");return{importOrAppendConversation:N,shellSessionReader:S}},[]),E=await Kc(await b(w(x.rootKey,x.rel)).catch(()=>null),x.rootKey,x.rel),v=await y(E);v?v.kind==="appended"?We("success",ve(Ne("atlas.liveAppended"),{n:v.turns}),8e3):v.kind==="mounted"?We("success",ve(Ne(v.mode==="continue"?"atlas.mountedChapter":"atlas.mountedBranch"),{n:v.turns}),9e3):v.kind==="imported"&&We("success",ve(Ne("toast.importedChats"),{n:1,m:v.nodeCount}),8e3):We("error",Ne("handoff.notASession")),v&&m&&await r(m)};sy=o,e.onDeepLink?.(d=>{o(d)}),(async()=>{const{bootProjects:d}=await pt(async()=>{const{bootProjects:m}=await Promise.resolve().then(()=>Na);return{bootProjects:m}},void 0);await d();const h=await e.pendingDeepLink?.().catch(()=>null);h&&o(h)})();const u="thoughtdag.atlas.sweepmark";ry=async()=>{const{bootProjects:d}=await pt(async()=>{const{bootProjects:y}=await Promise.resolve().then(()=>Na);return{bootProjects:y}},void 0);await d();const h=await e.roots().catch(()=>[]),m=[];for(const y of h){const w=await e.list(y.key).catch(()=>[]);for(const E of w)m.push({rootKey:y.key,rel:E.rel,mtime:E.mtime,size:E.size})}let p={};try{p=JSON.parse(localStorage.getItem(u)??"{}")}catch{}const x=Object.keys(p).length===0;m.sort((y,w)=>w.mtime-y.mtime);const b=m.filter((y,w)=>{const E=`${y.mtime}|${y.size}`;return p[`${y.rootKey}|${y.rel}`]===E?!1:x?w<30:!0});for(const y of b)await a({rootKey:y.rootKey,rel:y.rel});for(const y of m)p[`${y.rootKey}|${y.rel}`]=`${y.mtime}|${y.size}`;localStorage.setItem(u,JSON.stringify(p))},ry()}const n7=Object.freeze(Object.defineProperty({__proto__:null,openWhyLink:P2,pickSessionFile:t7,startLiveMirror:jW,sweepRecentSessions:RW},Symbol.toStringTag,{value:"Module"})),a7=(e,t)=>`td:card:${e}#${t}`,LW=420;let Cx=0;const PW=4;async function r7(e,t){try{const n=await Zo(a7(e,t));return typeof n=="string"&&n?n:void 0}catch{return}}async function s7(e,t,n){const a=(await hr())?.default??void 0,r=`Condense the past exchange below into a card of at most 60 words (or 120 Chinese characters), in the exchange's own language: what was asked, what was concluded or decided, the names, numbers and file names that matter. No preamble, no markdown. Output only the card.
157
157
 
158
158
  ${n.slice(0,6e3)}`,o=(await Ka([{role:"user",content:r}],void 0,a)).trim().replace(/^["“「]|["”」]$/g,"").slice(0,LW);if(!(o.length<20)){try{await Pr(a7(e,t),o)}catch{}return o}}function z2(e,t){const n=t.filter(a=>!a.card);n.length&&(async()=>{for(const a of n){for(;Cx>=PW;)await new Promise(r=>setTimeout(r,200));Cx++,s7(a.session,a.turn,a.text).then(r=>{r&&se.setState(s=>({nodes:s.nodes.map(o=>o.id===e&&o.data.recallItems?.some(u=>u.id===a.id)?{...o,data:{...o.data,recallItems:o.data.recallItems.map(u=>u.id===a.id?{...u,card:r,cardTokens:_n(r)}:u)}}:o)}))}).catch(()=>{}).finally(()=>{Cx--})}})()}const E0=["what","decisions","now","open"],Fm={what:"dossier.secWhat",decisions:"dossier.secDecisions",now:"dossier.secNow",open:"dossier.secOpen"},zW=100,BW=60,HW=6,FW=3200,UW=e=>e?e.slice(5,10).replace("-","-"):"",qW=(e,t)=>{const n=e.sources[t];return n?`${n.runner} ${UW(n.at)}`:""};function $W(e,t,n={}){const a=n.cap??FW,r=n.sources??!0,s=[`## ${ve(Ne("dossier.title"),{name:t})}${e.updatedAt?` (${Ne("dossier.updated")} ${e.updatedAt.slice(0,10)})`:""}`];for(const u of E0){const d=e.sections[u];if(d.length){s.push(`### ${Ne(Fm[u])}`);for(const h of d){const m=r?h.src.map(p=>qW(e,p)).filter(Boolean).slice(0,2):[];s.push(`- ${h.text}${m.length?` (${m.join("; ")})`:""}`)}}}const o=s.join(`
159
159
  `);return o.length>a?o.slice(0,a).trimEnd()+`
@@ -229,7 +229,7 @@ takeaway: the conclusion, stated first and plainly, as one clause. Hard limit: 1
229
229
 
230
230
  Both in the same language as the question. Never use dash characters (—, –, -) inside topic or takeaway; use commas or colons instead. Output only that one line.`}],void 0,p,{fast:!0}).then(x=>{const b=x.trim().split(`
231
231
  `)[0].trim(),y=b.match(/^(INSIGHT|RULEOUT|DECISION|PIVOT|OPEN)\s*[||::]\s*([^||]+?)\s*[||]\s*(.+)$/is),w=y?null:b.match(/^(INSIGHT|RULEOUT|DECISION|PIVOT|OPEN)[::||]\s*(.+)$/is),E=(y?.[1]??w?.[1])?.toLowerCase()??"insight",v=y?y[2].trim():void 0,N=y?y[3].trim():w?w[2].trim():b;return d(N,v,E)});if(!s){o.then(m).catch(()=>{});return}$m.add(e),o.then(async p=>{if(!p)return;const x=await C7(t,n,p,{context:s.context,thread:s.thread,parentAnswer:s.parentAnswer}).catch(()=>null);s.set(e,n,x),x?await d(Jo(x,1),Jo(x,0),x.move??"insight"):await m(p)}).catch(()=>{}).finally(()=>$m.delete(e))}function MV(e,t,n){const{ordered:a}=zr(e,t,n),r={ruleout:"RULEOUT",decision:"DECISION",pivot:"PIVOT",open:"OPEN"},s=a.filter(u=>u.id!==e).map(u=>{const d=Qi(u.data);if(!d)return null;const h=u.data.summaryTypes?.[u.data.responseIndex];return`- ${h&&r[h]?`${r[h]}: `:""}${d}`}).filter(u=>!!u).slice(-8),o=a.find(u=>u.data.isRoot&&u.id!==e);return o?.data.question&&s.unshift(`Opening question of the map: ${o.data.question.slice(0,200)}`),s}const Ls=new Map,Ix=new Map,T0=new Map;async function Bi(e,t,n,a){if(Nt)return;const{question:r,images:s,onSuccess:o,versionMode:u="replace"}=a;let{messages:d}=a;a.autoChain||T0.clear(),Ls.get(n)?.abort();const h=(Ix.get(n)??0)+1;Ix.set(n,h);const m=()=>Ix.get(n)===h,p=new AbortController;Ls.set(n,p),e(Y=>({nodes:Y.nodes.map(U=>U.id===n?{...U,data:{...U.data,generationFailed:void 0,reasoning:void 0,restreaming:U.data.response?!0:void 0}}:U)}));let x;const b=t().nodes.find(Y=>Y.id===n)?.data.model;let y=b;const w=await hr(),E=w?.default??null;if(b&&w&&w.models.length>0){const Y=B7(b,w.models);Y!==b&&(y=Y??void 0,We("info",ve(Ne(Y?"node.pinnedModelRemapped":"node.pinnedModelUnavailable"),Y?{m:b,r:Y}:{m:b}),7e3))}let v,N=!1;const S=y??ce.getState().selectedModel??E??void 0,C=await L8(n,S),I=C?void 0:await P7(S,n);let O,_=null,A=null;const H=(Y,U=!1)=>{if(!m())return;const z=_n(r+Y),L=v??S;t().logEvent("generate",n,{chars:Y.length,...L?{model:L}:{},...U?{failed:!0}:{}});const q=_8(n,t().nodes,t().edges),W=b$(M8(n,t().nodes,t().edges));e(X=>({nodes:X.nodes.map(B=>{if(B.id!==n)return B;const $=new Set([Ne("node.failedPlaceholder"),Ne("node.emptyResponse")]),Z=u==="append"||U?B.data.responses.map((Me,Le)=>({r:Me,q:B.data.questions?.[Le],by:B.data.generatedBy?.[Le],rs:B.data.reasonings?.[Le],at:B.data.generatedAts?.[Le],ed:B.data.editedAts?.[Le],gw:B.data.gatewaySearches?.[Le],ef:B.data.generatedEfforts?.[Le]})).filter(({r:Me})=>Me&&!(U&&$.has(Me))):[],K=new Date().toISOString(),J=[...Z.map(({r:Me})=>Me),Y],oe=[...Z.map(({q:Me})=>Me??B.data.question),B.data.question],me=[...Z.map(({by:Me})=>Me),L],ye=[...Z.map(({gw:Me})=>Me),N||void 0],ae=[...Z.map(({ef:Me})=>Me),li(L)&&B.data.agentSession?.effort||void 0],ge=[...Z.map(({rs:Me})=>Me),B.data.reasoning||void 0],Te=[...Z.map(({at:Me})=>Me),K],Fe=[...Z.map(({ed:Me})=>Me),void 0];return{...B,data:{...B.data,response:Y,responses:J,questions:oe,generatedBy:me,gatewaySearches:ye,generatedEfforts:ae,reasonings:ge,generatedAts:Te,editedAts:Fe,reasoning:void 0,restreaming:void 0,pendingApprovals:void 0,agentTrace:void 0,responseIndex:J.length-1,isLoading:!1,tokenCount:z,generationFailed:U||void 0,references:x,highlights:dm(B.data.highlights,Y),lastContextHash:q,lastContextParts:W,lastGeneratedAt:K}}})}))},G=t().nodes.find(Y=>Y.id===n)?.data,D=!G?.stepKind&&!G?.digestOf?bW():null;if(D){let Y=d.length-1;for(let U=d.length-1;U>=0;U--)if(d[U].role==="assistant"){Y=U+1;break}d=[...d.slice(0,Y),D,...d.slice(Y)]}if(!G?.stepKind&&!G?.digestOf&&(G?.recall??ce.getState().recallEnabled)&&m()){let Y=G?.recallItems;if(!Y){const{useProjects:z}=await pt(async()=>{const{useProjects:W}=await Promise.resolve().then(()=>Na);return{useProjects:W}},void 0),L=(W,X)=>{m()&&e(B=>({nodes:B.nodes.map($=>$.id===n?{...$,data:{...$.data,recallProgress:{done:W,total:X}}}:$)}))},q=await k7(r,{excludeSession:z.getState().activeId,model:S,onProgress:L,reach:G?.recallReach,scale:G?.recallScale});if(Y=q.items,!m())return;e(W=>({nodes:W.nodes.map(X=>X.id===n?{...X,data:{...X.data,recallItems:q.items,recallMeta:q.meta,recallProgress:null}}:X)})),z2(n,q.items)}const U=cV(Y);if(U){let z=d.length-1;for(let L=d.length-1;L>=0;L--)if(d[L].role==="assistant"){z=L+1;break}d=[...d.slice(0,z),U,...d.slice(z)]}}try{const Y=S,U=Y?d8(Y):void 0;if(U){const J=_n(d.map(oe=>oe.content).join(`
232
- `));if(J>=U)throw new Error(ve(Ne("toast.contextOverWindow"),{est:J.toLocaleString(),model:Y,limit:U.toLocaleString()}))}let z=null,L=null;const q=()=>{if(!z||!m()){z=null;return}const J=z;z=null,e(oe=>({nodes:oe.nodes.map(me=>me.id===n?{...me,data:{...me.data,...J.response!==void 0?{response:J.response,restreaming:void 0}:{},...J.reasoning!==void 0?{reasoning:J.reasoning}:{}}}:me)}))},W=J=>{z={...z??{},...J},L==null&&(q(),L=window.setTimeout(()=>{L=null,q()},100))},X=()=>{L!=null&&(clearTimeout(L),L=null),q()},B=[...new Set((a.sources??[]).map(J=>J.nodeId).filter(J=>!!J))],$=async J=>{const oe=await Promise.all(J.images.map(async ae=>({type:ae.mimeType,sha:await jm(ae.data)}))),me=await jm(_2({messages:J.messages,images:oe,model:J.model,tools:{web:!!J.toolPrefs.web,scholar:!!J.toolPrefs.scholar,mcp:!!J.toolPrefs.mcp}})),ye=B.slice(0,200);t().logEvent("commit",n,{kind:"request",sha:`sha256:${me}`,n:J.messages.length,images:J.images.length,lane:J.lane,...J.model?{model:J.model}:{},...ye.length?{m:ye.join(",")}:{},...B.length>ye.length?{more:!0}:{}})};let Z=!1;const K=await S8(d,(J,oe)=>{if(W({response:oe}),C&&!Z){Z=!0;const me=new Date().toISOString();e(ye=>({nodes:ye.nodes.map(ae=>ae.id===n&&ae.data.agentTrace?.some(ge=>ge.status==="running")?{...ae,data:{...ae.data,agentTrace:ae.data.agentTrace.map(ge=>ge.status==="running"?{...ge,status:"ok",endedAt:me}:ge)}}:ae)}))}},p.signal,s,{onDispatch:J=>{$(J).catch(()=>{})},onToolCall:(J,oe)=>{if(!m())return;if(C){const ye=new Date().toISOString();e(ae=>({nodes:ae.nodes.map(ge=>{if(ge.id!==n)return ge;const Te=(ge.data.agentTrace??[]).map(Fe=>Fe.status==="running"?{...Fe,status:"ok",endedAt:ye}:Fe);return Te.push({id:`${ye}-${Te.length}`,name:J,query:oe,status:"running",startedAt:ye}),{...ge,data:{...ge.data,agentTrace:Te}}})}));return}const me=J==="arxiv_search"?"📚":J==="semantic_scholar"?"🎓":J.startsWith("mcp:")?"🔧":"🔍";e(ye=>({nodes:ye.nodes.map(ae=>ae.id===n&&!ae.data.response?{...ae,data:{...ae.data,response:`${me} ${oe}…`}}:ae)}))},onGatewaySearch:()=>{m()&&(N=!0,e(J=>({nodes:J.nodes.map(oe=>oe.id===n&&!oe.data.response?{...oe,data:{...oe.data,response:`🌐 ${Ne("node.gatewaySearching")}`}}:oe)})))},onSources:J=>{x=J},onHarnessSession:J=>{O=J},onAgentTool:J=>{if(!m())return;const oe=new Date().toISOString();e(me=>({nodes:me.nodes.map(ye=>{if(ye.id!==n)return ye;const ae=[...ye.data.agentTrace??[]];if(J.phase==="start")ae.push({id:J.id||`${ae.length}`,name:J.name,query:J.query,status:"running",startedAt:oe});else{const ge=ae.findIndex(Te=>Te.id===J.id&&Te.status==="running");ge>=0&&(ae[ge]={...ae[ge],status:J.isError?"error":"ok",endedAt:oe})}return{...ye,data:{...ye.data,agentTrace:ae}}})}))},onAgentSession:J=>{if(!m())return;const oe=!!I?.continue;e(me=>({nodes:me.nodes.map(ye=>ye.id===n?{...ye,data:{...ye.data,agentSession:{...ye.data.agentSession,...J,continued:oe}}}:ye)})),oe&&J.sessionId&&$V(J.runtime,n,J.sessionId,J.cwd)},onAgentChanges:J=>{m()&&e(oe=>({nodes:oe.nodes.map(me=>me.id===n&&me.data.agentSession?{...me,data:{...me.data,agentSession:{...me.data.agentSession,changes:J}}}:me)}))},onHarnessTurn:J=>{_=J,C&&!A&&(A=B8(e,n,C,J).catch(()=>!1))},onApproval:J=>{if(!m())return;const oe=new Date().toISOString();e(me=>({nodes:me.nodes.map(ye=>{if(ye.id!==n)return ye;const ae=ye.data.pendingApprovals??[];return ae.some(ge=>ge.id===J.id)?ye:{...ye,data:{...ye.data,pendingApprovals:[...ae,{...J,askedAt:oe}]}}})})),We("info",Ne("approval.toast"),8e3)},onApprovalDecided:({id:J,outcome:oe,value:me,auto:ye,name:ae,query:ge,rule:Te})=>{if(!m())return;const Fe=new Date().toISOString();e(Me=>({nodes:Me.nodes.map(Le=>{if(Le.id!==n)return Le;const Ee=Le.data.pendingApprovals??[],ze=Ee.find(Ke=>Ke.id===J),De=Ee.filter(Ke=>Ke.id!==J),tt=De.length?De:void 0;if(!ze&&ye)return{...Le,data:{...Le.data,pendingApprovals:tt,approvals:[...Le.data.approvals??[],{id:J,kind:"confirm",toolName:Le.data.agentSession?.runtime??"agent",callId:null,reason:null,name:ae??"",query:ge??"",arguments:null,askedAt:Fe,decidedAt:Fe,outcome:oe,auto:!0,...Te?{rule:Te}:{}}]}};if(!ze)return{...Le,data:{...Le.data,pendingApprovals:tt}};const xt={...ze};return delete xt.answered,{...Le,data:{...Le.data,pendingApprovals:tt,approvals:[...Le.data.approvals??[],{...xt,outcome:oe,decidedAt:Fe,...me?{value:me}:{}}]}}})}))},onRerouted:(J,oe)=>{v=oe},onImageFallback:J=>{v=J},onReasoning:(J,oe)=>{W({reasoning:oe})}},(()=>{const J=t().nodes.find(oe=>oe.id===n)?.data;return{web:J?.webSearch??ce.getState().webSearchEnabled,scholar:J?.scholarSearch??ce.getState().scholarSearchEnabled,mcp:ce.getState().mcpEnabled}})(),y,C??(I?{...I,nodeId:n}:void 0));if(X(),!m())return;if(Ls.delete(n),!K.trim()){H(Ne("node.emptyResponse"),!0);return}if(I){const J=t().nodes.find(oe=>oe.id===n)?.data.agentSession;J&&await XV(n,J,r).catch(()=>!1)}if(H(K),C){const J=A?await A:!1;await H8(e,t,n,{question:r,response:K},C,O,_,J)}o?.(K),t().pushHistory(),_V(n,r,K,t().setSummary,MV(n,t().nodes,t().edges),{model:C||I?void 0:S,set:t().setLadder,...O7(n,t().nodes,t().edges)}),!G?.stepKind&&!G?.digestOf&&pt(async()=>{const{useProjects:J}=await Promise.resolve().then(()=>Na);return{useProjects:J}},void 0).then(({useProjects:J})=>{const{projects:oe,activeId:me}=J.getState(),ye=oe.find(ae=>ae.id===me);SW(r,K,ye?{id:ye.id,name:ye.name}:void 0)}),IV(e,t,n),Yl(t,n)}catch(Y){if(!m())return;Ls.delete(n);const U=t().nodes.find(L=>L.id===n)?.data.response||"";if(Y instanceof DOMException&&Y.name==="AbortError")H(U||Ne("node.stoppedPlaceholder"));else{const L=Y instanceof Error?Y.message:Ne("toast.unknownError");/no model configured/i.test(L)?(We("info",Ne("toast.noModelYet")),ce.getState().setApiKeyModalOpen(!0)):/429|too many requests|rate.?limit|quota/i.test(L)?We("info",Ne("toast.rateLimited")):We("error",ve(Ne("toast.generationFailed"),{message:L})),H(U||Ne("node.failedPlaceholder"),!0)}t().pushHistory()}}function Yl(e,t){if(ce.getState().autoRefreshPaused)return;const{nodes:n,edges:a}=e(),r=new Map(n.map(o=>[o.id,o])),s=o=>{const u=r.get(o);return!u||u.data.isLoading?!1:u.data.stepKind==="human"||u.data.stepKind==="note"||u.data.stepKind==="link"?!!u.data.question.trim():u.data.stepKind==="file"?(u.data.attachments?.length??0)>0:!!u.data.response&&!u.data.generationFailed};for(const o of a){if(o.source!==t||o.data?.isCrossLink)continue;const u=r.get(o.target);!u||u.data.stepKind!=="prompt"||u.data.response||u.data.isLoading||u.data.generationFailed||!a.filter(h=>h.target===u.id&&!h.data?.isCrossLink).map(h=>h.source).every(s)||e().rerunNode(u.id,{auto:!0})}}function IV(e,t,n){if(ce.getState().autoRefreshPaused)return;const a=new Set([n]),r=[n];for(;r.length>0;){const d=r.shift();for(const h of t().edges)h.target===d&&!h.data?.isCrossLink&&!a.has(h.source)&&(a.add(h.source),r.push(h.source))}t().edges.some(d=>d.data?.followsTip&&d.source!==n&&a.has(d.source))&&e(d=>({edges:d.edges.map(h=>h.data?.followsTip&&h.source!==n&&a.has(h.source)?{...h,id:`watch-${n}-${h.target}`,source:n}:h)}));const{nodes:o,edges:u}=t();for(const d of o){if(!(d.data.autoRerun??d.data.evaluatorTrigger==="auto")||d.id===n||d.data.isLoading||Ls.has(d.id))continue;const m=T0.get(d.id)??0;if(m>=(d.data.autoRerunRounds??1))continue;const{ordered:p}=zr(d.id,o,u);p.some(x=>x.id===n)&&(T0.set(d.id,m+1),t().rerunNode(d.id,{auto:!0}))}}const $E=e=>{for(const t of e){const n=Ls.get(t);n&&(n.abort(),Ls.delete(t))}},OV=(e,t)=>({nodes:[],edges:[],selectedNodeId:null,selectedNodeIds:[],setNodes:n=>e({nodes:n}),setEdges:n=>e({edges:n}),setSelectedNodeId:n=>e({selectedNodeId:n,selectedNodeIds:n?[n]:[]}),setSelectedNodeIds:n=>e({selectedNodeIds:n,selectedNodeId:n.length===1?n[0]:null}),deleteNode:n=>{if(Xr())return;t().logEvent("delete",n,{n:1}),t().pushHistory();const{edges:a}=t(),r=Xo(n,a),s=new Set([n,...r]);$E(s),e(o=>({nodes:o.nodes.filter(u=>!s.has(u.id)),edges:o.edges.filter(u=>!s.has(u.source)&&!s.has(u.target))})),t().pushHistory(),pt(()=>import("./canonical-46lAq3XC.js"),[]).then(o=>o.unsubscribeOrphanedSessions())},deleteEdges:n=>{if(Xr())return;t().logEvent("disconnect",n[0],{n:n.length});const a=new Set(n);t().edges.some(r=>a.has(r.id))&&(t().pushHistory(),e(r=>({edges:r.edges.filter(s=>!a.has(s.id))})),t().pushHistory())},editResponse:(n,a)=>{if(Xr())return;t().logEvent("edit-response",n,{chars:a.length}),t().pushHistory();const r=_n(t().nodes.find(s=>s.id===n)?.data.question+a||a);e(s=>({nodes:s.nodes.map(o=>o.id===n?{...o,data:{...o.data,response:a,responses:o.data.responses.map((u,d)=>d===o.data.responseIndex?a:u),summaries:o.data.summaries?.map((u,d)=>d===o.data.responseIndex?void 0:u),summaryTypes:o.data.summaryTypes?.map((u,d)=>d===o.data.responseIndex?void 0:u),summaryTopics:o.data.summaryTopics?.map((u,d)=>d===o.data.responseIndex?void 0:u),summaryLadders:o.data.summaryLadders?.map((u,d)=>d===o.data.responseIndex?void 0:u),editedAts:o.data.responses.map((u,d)=>d===o.data.responseIndex?new Date().toISOString():o.data.editedAts?.[d]),highlights:dm(o.data.highlights,a),isEditingResponse:!1,tokenCount:r}}:o)})),t().pushHistory()},toggleCollapse:n=>{const a=t().nodes.find(h=>h.id===n);if(!a)return;const r=Fi(a),o=C2({...a,data:{...a.data,isCollapsed:!a.data.isCollapsed}})-r,u=Xo(n,t().edges),d=new Set(u);e(h=>({nodes:h.nodes.map(m=>m.id===n?{...m,data:{...m.data,isCollapsed:!m.data.isCollapsed}}:d.has(m.id)?{...m,position:{...m.position,y:m.position.y+o}}:m)}))},setEditing:(n,a)=>{a&&Xr()||e(r=>({nodes:r.nodes.map(s=>s.id===n?{...s,data:{...s.data,isEditing:a}}:s)}))},setEditingResponse:(n,a)=>{a&&Xr()||e(r=>({nodes:r.nodes.map(s=>s.id===n?{...s,data:{...s.data,isEditingResponse:a}}:s)}))},duplicateNode:n=>{const a=t().nodes.find(m=>m.id===n);if(!a)return;t().pushHistory();const r=En(),s={id:r,type:"thought",position:{x:0,y:0},dragHandle:".drag-handle",data:{...a.data,isCollapsed:!0,isEditing:!1,isEditingResponse:!1,isLoading:!1,highlights:a.data.highlights.map(m=>({...m,id:En()}))}},o=t().edges.find(m=>m.target===n),u=o?{...o,id:`edge-${o.source}-${r}`,target:r}:null,d=u?[...t().edges,u]:t().edges,h=yr([...t().nodes,s],d);e({nodes:h,edges:d,selectedNodeId:r}),t().pushHistory()},addCrossLink:(n,a)=>{const{edges:r,nodes:s}=t();if(r.some(x=>x.source===n&&x.target===a))return;const u=s.find(x=>x.id===n);if(u&&["note","file","link"].includes(u.data.stepKind??"")){t().pushHistory();const x={id:`edge-${n}-${a}`,source:n,sourceHandle:"continue",target:a,targetHandle:"top",type:"smoothstep",style:{stroke:at.accent,strokeDasharray:"8 4",strokeWidth:2},animated:!0,data:{isCrossLink:!0,createdAt:new Date().toISOString()}};e(y=>({edges:[...y.edges,x]})),t().logEvent("connect",x.id),t().setEdgeStructural(x.id,!0);const b=t().edges.find(y=>y.id===x.id);if(b&&!b.data?.isCrossLink){const w=vr(n,t().nodes,t().edges).messages.reduce((E,v)=>E+_n(v.content),0);We("success",ve(Ne("edge.materialWiredFull"),{n:w.toLocaleString()}),8e3,{label:Ne("edge.materialMakeQuote"),run:()=>t().setEdgeStructural(x.id,!1)})}return}t().pushHistory();const d=s.find(x=>x.id===n),h=s.find(x=>x.id===a),m=!!d&&!!h&&h.position.y>d.position.y+60&&Math.abs(h.position.x-d.position.x)<320,p={id:`crosslink-${n}-${a}`,source:n,sourceHandle:m?"continue":"branch",target:a,targetHandle:m?"top":"left",type:"smoothstep",style:{stroke:at.accent,strokeDasharray:"8 4",strokeWidth:2},animated:!0,data:{isCrossLink:!0,createdAt:new Date().toISOString()}};if(e(x=>({edges:[...x.edges,p]})),t().logEvent("connect",p.id),t().pushHistory(),d&&!["note","file","link"].includes(d.data.stepKind??"")){const{ordered:x}=zr(n,s,r.filter(y=>!y.data?.isCrossLink)),b=x.filter(y=>y.id!==n&&!["note","file","link"].includes(y.data.stepKind??""));if(b.length>0){const y=_n(k0({source:d,depth:"quote",chain:b})),E=vr(n,s,r).messages.reduce((v,N)=>v+_n(N.content),0)+_n(d.data.question+d.data.response);We("info",ve(Ne("edge.linkedQuote"),{n:y}),8e3,{label:ve(Ne("edge.makeFull"),{m:E}),run:()=>t().setEdgeStructural(p.id,!0)})}}},staleIds:[],staleFps:{},staleVerdicts:{},setStaleVerdicts:n=>e(a=>({staleVerdicts:{...a.staleVerdicts,...n}})),recomputeStaleness:()=>{const{nodes:n,edges:a}=t(),r=[],s={};for(const d of n){if(!d.data.lastContextHash||!d.data.response||["note","file","link","frame"].includes(d.data.stepKind??""))continue;const h=_8(d.id,n,a);h!==d.data.lastContextHash&&(r.push(d.id),s[d.id]=h)}const o=t().staleFps,u=t().staleIds;u.length===r.length&&u.every((d,h)=>d===r[h]&&o[d]===s[d])||(e({staleIds:r,staleFps:s}),r.length&&pt(()=>Promise.resolve().then(()=>RV),void 0).then(d=>d.judgeStaleness()).catch(()=>{}))},setEdgeStructural:(n,a)=>{const{nodes:r,edges:s}=t(),o=s.find(u=>u.id===n);if(o){if(a){const u=s.filter(h=>!h.data?.isCrossLink),{ordered:d}=zr(o.source,r,u);if(d.some(h=>h.id===o.target)){We("error",Ne("edge.cycleBlocked"));return}}t().pushHistory(),t().logEvent(a?"connect":"disconnect",n,{convert:!0}),e(u=>({edges:u.edges.map(d=>{if(d.id!==n)return d;if(a){const h={...d.data??{}};return delete h.isCrossLink,delete h.contextDepth,delete h.isWatch,{...d,sourceHandle:"continue",targetHandle:"top",animated:!1,style:{stroke:at.accent,strokeWidth:2},markerEnd:{type:"arrowclosed",color:at.accent,width:18,height:18},data:h}}return{...d,animated:!0,style:{stroke:at.accent,strokeDasharray:"8 4",strokeWidth:2},markerEnd:{type:"arrowclosed",color:at.accent,width:18,height:18},data:{...d.data??{},isCrossLink:!0,contextDepth:void 0}}})})),e(u=>({nodes:yr(u.nodes,u.edges)})),t().pushHistory()}},setCrossLinkDepth:(n,a)=>{t().pushHistory(),e(r=>({edges:r.edges.map(s=>s.id!==n||!s.data?.isCrossLink?s:{...s,style:{...s.style,strokeDasharray:a==="full"?"12 3":"8 4",strokeWidth:a==="full"?3:2},data:{...s.data,contextDepth:a==="full"?"full":void 0}})})),t().pushHistory()},navigateVersion:(n,a)=>{e(r=>({nodes:r.nodes.map(s=>{if(s.id!==n)return s;const{responses:o,responseIndex:u}=s.data;let d=a==="prev"?u-1:u+1;return d<0&&(d=o.length-1),d>=o.length&&(d=0),{...s,data:{...s.data,responseIndex:d,response:o[d],question:s.data.questions?.[d]??s.data.question,generationFailed:void 0,highlights:dm(s.data.highlights,o[d])}}})}))},deleteVersion:(n,a)=>{t().pushHistory(),e(r=>({nodes:r.nodes.map(s=>{if(s.id!==n)return s;const o=s.data.responses.filter((d,h)=>h!==a);if(o.length===0)return s;const u=Math.min(s.data.responseIndex,o.length-1);return{...s,data:{...s.data,responses:o,responseIndex:u,response:o[u],questions:s.data.questions?.filter((d,h)=>h!==a),question:s.data.questions?.filter((d,h)=>h!==a)[u]??s.data.question,summaries:s.data.summaries?.filter((d,h)=>h!==a),generatedBy:s.data.generatedBy?.filter((d,h)=>h!==a),summaryTypes:s.data.summaryTypes?.filter((d,h)=>h!==a),reasonings:s.data.reasonings?.filter((d,h)=>h!==a),generatedAts:s.data.generatedAts?.filter((d,h)=>h!==a),editedAts:s.data.editedAts?.filter((d,h)=>h!==a),highlights:dm(s.data.highlights,o[u])}}})})),t().pushHistory()},relayout:()=>{Xr()||(t().pushHistory(),e(n=>{const a=E$(n.nodes,n.edges);return{nodes:yr(n.nodes,a),edges:a}}),t().pushHistory())},setArchived:(n,a)=>{const r=new Set(n);t().pushHistory(),t().logEvent(a?"archive":"unarchive",n[0],{n:n.length}),e(s=>({nodes:s.nodes.map(o=>r.has(o.id)?{...o,data:{...o.data,archived:a||void 0,archivedAt:a?new Date().toISOString():void 0}}:o)})),t().pushHistory()},setNodeModel:(n,a)=>{e(r=>({nodes:r.nodes.map(s=>s.id===n?{...s,data:{...s.data,model:a}}:s)}))},alignSelection:n=>{if(n.length<2)return;const a=new Set(n),{nodes:r,edges:s}=t(),o=new Map,u=s.filter(b=>!b.data?.isWatch),d=(b,y)=>{if(o.has(b))return o.get(b);if(y.has(b))return 0;y.add(b);const w=u.filter(v=>v.target===b&&a.has(v.source)),E=w.length===0?0:1+Math.max(...w.map(v=>d(v.source,y)));return o.set(b,E),E},h=n.map(b=>r.find(y=>y.id===b)).filter(b=>!!b).sort((b,y)=>d(b.id,new Set)-d(y.id,new Set)||b.position.y-y.position.y);t().pushHistory();const m=h[0].position;let p=m.y;const x=new Map;for(const b of h)x.set(b.id,{x:m.x,y:p}),p+=Fi(b)+40;e(b=>({nodes:b.nodes.map(y=>{const w=x.get(y.id);return w?{...y,position:w}:y})})),t().pushHistory()},batchDelete:n=>{if(Xr())return;t().logEvent("delete",n[0],{n:n.length}),t().pushHistory();const a=new Set(n);$E(a),e(r=>({nodes:r.nodes.filter(s=>!a.has(s.id)),edges:r.edges.filter(s=>!a.has(s.source)&&!a.has(s.target)),selectedNodeId:null,selectedNodeIds:[]})),t().pushHistory(),pt(()=>import("./canonical-46lAq3XC.js"),[]).then(r=>r.unsubscribeOrphanedSessions())},duplicateSelection:n=>{const{nodes:a,edges:r}=t(),s=new Set(n),o=a.filter(_=>s.has(_.id));if(o.length===0)return;t().pushHistory();const u=_=>({x:_.position.x,y:_.position.y,w:_.measured?.width??_.width??520,h:_.measured?.height??_.height??Fi(_)}),d=o.map(u),h={x:Math.min(...d.map(_=>_.x)),y:Math.min(...d.map(_=>_.y)),right:Math.max(...d.map(_=>_.x+_.w)),bottom:Math.max(...d.map(_=>_.y+_.h))},m=80,p=h.right-h.x+m,x=h.bottom-h.y+m,b=[];for(let _=1;_<=6;_++)b.push({dx:_*p,dy:0},{dx:0,dy:_*x},{dx:_*p,dy:_*x});const y=a.filter(_=>_.data.stepKind!=="frame").map(u),w=(_,A)=>_.x<A.x+A.w&&_.x+_.w>A.x&&_.y<A.y+A.h&&_.y+_.h>A.y,E=b.find(_=>!d.some(A=>y.some(H=>w({...A,x:A.x+_.dx,y:A.y+_.dy},H))))??{dx:p,dy:x},v=new Map,N=new Map;for(const _ of o){v.set(_.id,En());for(const A of _.data.attachments??[])N.set(A.id,En())}const S=_=>(_??[]).map(A=>N.get(A)??A),C=o.map(_=>({..._,id:v.get(_.id),position:{x:_.position.x+E.dx,y:_.position.y+E.dy},selected:!0,data:{..._.data,attachments:(_.data.attachments??[]).map(A=>({...A,id:N.get(A.id)})),excludedAttachmentIds:S(_.data.excludedAttachmentIds),includedAttachmentIds:S(_.data.includedAttachmentIds),digestOf:_.data.digestOf?N.get(_.data.digestOf)??_.data.digestOf:void 0,highlights:(_.data.highlights??[]).map(A=>({...A,id:En()})),isEditing:!1,isEditingResponse:!1,isLoading:!1}})),I=r.filter(_=>s.has(_.source)&&s.has(_.target)).map(_=>({..._,id:`edge-${v.get(_.source)}-${v.get(_.target)}`,source:v.get(_.source),target:v.get(_.target),data:_.data?{..._.data}:_.data})),O=C.map(_=>_.id);e(_=>({nodes:[..._.nodes.map(A=>A.selected?{...A,selected:!1}:A),...C],edges:[..._.edges,...I],selectedNodeId:O.length===1?O[0]:null,selectedNodeIds:O})),t().pushHistory()}}),$2=(e,t)=>{const n=e.staleVerdicts[t];return!!n&&n.fp===e.staleFps[t]&&n.p<Z$},Qr=e=>e.staleIds.filter(t=>!$2(e,t)),R7=(e,t)=>{const n=e.staleVerdicts[t];return n&&n.fp===e.staleFps[t]?n:void 0},DV=8;let Ox=!1;const Dx=new Set;async function j7(){if(Ox||!jr())return;const e=se.getState(),t=e.staleIds.filter(a=>e.staleVerdicts[a]?.fp!==e.staleFps[a]&&!Dx.has(`${a}:${e.staleFps[a]}`));if(!t.length)return;Ox=!0;try{const{nodes:a,edges:r}=e,s=[];for(const o of t.slice(0,DV)){Dx.add(`${o}:${e.staleFps[o]}`);const u=a.find(p=>p.id===o),d=u?.data.lastContextParts;if(!u||!d)continue;const h=M8(o,a,r),m=[];for(const[p,x]of Object.entries(h)){const b=d[p];(!b||b.h!==x.h)&&m.push({node:p,before:b?.head??"",after:x.text})}for(const p of Object.keys(d))h[p]||m.push({node:p,before:d[p].head,after:""});m.length&&s.push({id:o,question:u.data.question,answer:u.data.response,changes:m})}if(s.length){const o=await J$(s),u={};for(const d of s)u[d.id]={fp:e.staleFps[d.id],p:o[d.id],changed:d.changes.map(h=>h.node)};se.getState().setStaleVerdicts(u)}}catch{}finally{Ox=!1}const n=se.getState();n.staleIds.some(a=>n.staleVerdicts[a]?.fp!==n.staleFps[a]&&!Dx.has(`${a}:${n.staleFps[a]}`))&&j7()}const RV=Object.freeze(Object.defineProperty({__proto__:null,currentStaleVerdict:R7,judgeStaleness:j7,shownStaleIds:Qr,staleHiddenByJudge:$2},Symbol.toStringTag,{value:"Module"})),jV=(e,t)=>({addQuestion:async(n,a={})=>{if(Xr())return;const{parentId:r,branchContext:s,branchYRatio:o,inheritRole:u,rolePrompt:d,initialAttachments:h,excludeAllInheritedAttachments:m,mentions:p}=a,x=En();t().logEvent("ask",x,{chars:n.length,...r?{}:{root:!0},...s?{branch:!0}:{}});const b=!r,y=r?t().nodes.find(Y=>Y.id===r)?.data.model:void 0,w={id:x,type:"thought",position:{x:0,y:0},dragHandle:".drag-handle",data:{question:n,createdAt:new Date().toISOString(),askedAt:new Date().toISOString(),model:y,response:"",responses:[],responseIndex:-1,isCollapsed:!1,isEditing:!1,isEditingResponse:!1,isLoading:!0,tokenCount:0,branchContext:s,highlights:[],highlightMode:"tag",attachments:h||[],excludedAttachmentIds:m&&r?t().getInheritedAttachments(r).map(({attachment:Y})=>Y.id).concat((t().nodes.find(Y=>Y.id===r)?.data.attachments||[]).map(Y=>Y.id)):[],includedAttachmentIds:[],roleMode:u===!1?"reset":"inherit",rolePrompt:d||void 0,isRoot:b,isBranch:!!s,webSearch:ce.getState().webSearchEnabled,scholarSearch:ce.getState().scholarSearchEnabled,...qc()}},E=!!s,v=r?{id:`edge-${r}-${x}`,source:r,target:x,sourceHandle:E?"branch":"continue",targetHandle:E?"left":"top",type:"smoothstep",...E?{style:{stroke:at.warm,strokeWidth:2},animated:!1,markerEnd:{type:"arrowclosed",color:at.warm,width:18,height:18},data:{isBranchFromSelection:!0,branchYRatio:o??.5}}:{style:{stroke:at.accent,strokeWidth:2},animated:!1,markerEnd:{type:"arrowclosed",color:at.accent,width:18,height:18},data:{}}}:null;let N=v?[...t().edges,v]:t().edges;const S=(p??[]).filter(Y=>Y!==x&&Y!==r&&t().nodes.some(U=>U.id===Y));if(S.length>0){const Y=N.filter(q=>!q.data?.isCrossLink),U=r?new Set(zr(r,t().nodes,Y).ordered.map(q=>q.id)):new Set,z=new Set(N.filter(q=>q.data?.isCrossLink&&q.target===x).map(q=>q.source));let L=0;for(const q of S)U.has(q)||z.has(q)||(N=[...N,{id:`crosslink-${q}-${x}`,source:q,target:x,sourceHandle:"branch",targetHandle:"left",type:"smoothstep",style:{stroke:at.accent,strokeDasharray:"8 4",strokeWidth:2},animated:!0,data:{isCrossLink:!0,createdAt:new Date().toISOString()}}],L++);L>0&&We("info",ve(Ne("mention.wired"),{n:L}),6e3)}const C=r?t().nodes.map(Y=>Y.id===r?{...Y,data:{...Y.data,isCollapsed:!0}}:Y):t().nodes,I=yr([...C,w],N);e({nodes:I,edges:N,selectedNodeId:x});const O=t().nodes.find(Y=>Y.id===x),_=r?vr(r,t().nodes,t().edges,s,O?.data.excludedAttachmentIds,O?.data.includedAttachmentIds,Qr(t())):{messages:[],images:[],sources:[]},A=_.messages,H=_.images,G=r?t().nodes.find(Y=>Y.id===r):null;NE(A,SE(O?.data,G?.data,!!r));const D=O?.data.attachments||[];for(const Y of D)A.some(z=>z.content.includes(`[PDF: ${Y.name}]`)||z.content.includes(`[File: ${Y.name}]`))||(Y.type.startsWith("image/")?H.push({data:Y.content,mimeType:Y.type}):Y.type==="application/pdf"?Y.extractedText&&A.push({role:"user",content:`[PDF: ${Y.name}]
232
+ `));if(J>=U)throw new Error(ve(Ne("toast.contextOverWindow"),{est:J.toLocaleString(),model:Y,limit:U.toLocaleString()}))}let z=null,L=null;const q=()=>{if(!z||!m()){z=null;return}const J=z;z=null,e(oe=>({nodes:oe.nodes.map(me=>me.id===n?{...me,data:{...me.data,...J.response!==void 0?{response:J.response,restreaming:void 0}:{},...J.reasoning!==void 0?{reasoning:J.reasoning}:{}}}:me)}))},W=J=>{z={...z??{},...J},L==null&&(q(),L=window.setTimeout(()=>{L=null,q()},100))},X=()=>{L!=null&&(clearTimeout(L),L=null),q()},B=[...new Set((a.sources??[]).map(J=>J.nodeId).filter(J=>!!J))],$=async J=>{const oe=await Promise.all(J.images.map(async ae=>({type:ae.mimeType,sha:await jm(ae.data)}))),me=await jm(_2({messages:J.messages,images:oe,model:J.model,tools:{web:!!J.toolPrefs.web,scholar:!!J.toolPrefs.scholar,mcp:!!J.toolPrefs.mcp}})),ye=B.slice(0,200);t().logEvent("commit",n,{kind:"request",sha:`sha256:${me}`,n:J.messages.length,images:J.images.length,lane:J.lane,...J.model?{model:J.model}:{},...ye.length?{m:ye.join(",")}:{},...B.length>ye.length?{more:!0}:{}})};let Z=!1;const K=await S8(d,(J,oe)=>{if(W({response:oe}),C&&!Z){Z=!0;const me=new Date().toISOString();e(ye=>({nodes:ye.nodes.map(ae=>ae.id===n&&ae.data.agentTrace?.some(ge=>ge.status==="running")?{...ae,data:{...ae.data,agentTrace:ae.data.agentTrace.map(ge=>ge.status==="running"?{...ge,status:"ok",endedAt:me}:ge)}}:ae)}))}},p.signal,s,{onDispatch:J=>{$(J).catch(()=>{})},onToolCall:(J,oe)=>{if(!m())return;if(C){const ye=new Date().toISOString();e(ae=>({nodes:ae.nodes.map(ge=>{if(ge.id!==n)return ge;const Te=(ge.data.agentTrace??[]).map(Fe=>Fe.status==="running"?{...Fe,status:"ok",endedAt:ye}:Fe);return Te.push({id:`${ye}-${Te.length}`,name:J,query:oe,status:"running",startedAt:ye}),{...ge,data:{...ge.data,agentTrace:Te}}})}));return}const me=J==="arxiv_search"?"📚":J==="semantic_scholar"?"🎓":J.startsWith("mcp:")?"🔧":"🔍";e(ye=>({nodes:ye.nodes.map(ae=>ae.id===n&&!ae.data.response?{...ae,data:{...ae.data,response:`${me} ${oe}…`}}:ae)}))},onGatewaySearch:()=>{m()&&(N=!0,e(J=>({nodes:J.nodes.map(oe=>oe.id===n&&!oe.data.response?{...oe,data:{...oe.data,response:`🌐 ${Ne("node.gatewaySearching")}`}}:oe)})))},onSources:J=>{x=J},onHarnessSession:J=>{O=J},onAgentTool:J=>{if(!m())return;const oe=new Date().toISOString();e(me=>({nodes:me.nodes.map(ye=>{if(ye.id!==n)return ye;const ae=[...ye.data.agentTrace??[]];if(J.phase==="start")ae.push({id:J.id||`${ae.length}`,name:J.name,query:J.query,status:"running",startedAt:oe});else{const ge=ae.findIndex(Te=>Te.id===J.id&&Te.status==="running");ge>=0&&(ae[ge]={...ae[ge],status:J.isError?"error":"ok",endedAt:oe})}return{...ye,data:{...ye.data,agentTrace:ae}}})}))},onAgentSession:J=>{if(!m())return;const oe=!!I?.continue;e(me=>({nodes:me.nodes.map(ye=>ye.id===n?{...ye,data:{...ye.data,agentSession:{...ye.data.agentSession,...J,continued:oe}}}:ye)})),oe&&J.sessionId&&$V(J.runtime,n,J.sessionId,J.cwd)},onAgentChanges:J=>{m()&&e(oe=>({nodes:oe.nodes.map(me=>me.id===n&&me.data.agentSession?{...me,data:{...me.data,agentSession:{...me.data.agentSession,changes:J}}}:me)}))},onHarnessTurn:J=>{_=J,C&&!A&&(A=B8(e,n,C,J).catch(()=>!1))},onApproval:J=>{if(!m())return;const oe=new Date().toISOString();e(me=>({nodes:me.nodes.map(ye=>{if(ye.id!==n)return ye;const ae=ye.data.pendingApprovals??[];return ae.some(ge=>ge.id===J.id)?ye:{...ye,data:{...ye.data,pendingApprovals:[...ae,{...J,askedAt:oe}]}}})})),We("info",Ne("approval.toast"),8e3)},onApprovalDecided:({id:J,outcome:oe,value:me,auto:ye,name:ae,query:ge,rule:Te})=>{if(!m())return;const Fe=new Date().toISOString();e(Me=>({nodes:Me.nodes.map(Le=>{if(Le.id!==n)return Le;const Ee=Le.data.pendingApprovals??[],ze=Ee.find(Ke=>Ke.id===J),De=Ee.filter(Ke=>Ke.id!==J),tt=De.length?De:void 0;if(!ze&&ye)return{...Le,data:{...Le.data,pendingApprovals:tt,approvals:[...Le.data.approvals??[],{id:J,kind:"confirm",toolName:Le.data.agentSession?.runtime??"agent",callId:null,reason:null,name:ae??"",query:ge??"",arguments:null,askedAt:Fe,decidedAt:Fe,outcome:oe,auto:!0,...Te?{rule:Te}:{}}]}};if(!ze)return{...Le,data:{...Le.data,pendingApprovals:tt}};const xt={...ze};return delete xt.answered,{...Le,data:{...Le.data,pendingApprovals:tt,approvals:[...Le.data.approvals??[],{...xt,outcome:oe,decidedAt:Fe,...me?{value:me}:{}}]}}})}))},onRerouted:(J,oe)=>{v=oe},onImageFallback:J=>{v=J},onReasoning:(J,oe)=>{W({reasoning:oe})}},(()=>{const J=t().nodes.find(oe=>oe.id===n)?.data;return{web:J?.webSearch??ce.getState().webSearchEnabled,scholar:J?.scholarSearch??ce.getState().scholarSearchEnabled,mcp:ce.getState().mcpEnabled}})(),y,C??(I?{...I,nodeId:n}:void 0));if(X(),!m())return;if(Ls.delete(n),!K.trim()){H(Ne("node.emptyResponse"),!0);return}if(I){const J=t().nodes.find(oe=>oe.id===n)?.data.agentSession;J&&await XV(n,J,r).catch(()=>!1)}if(H(K),C){const J=A?await A:!1;await H8(e,t,n,{question:r,response:K},C,O,_,J)}o?.(K),t().pushHistory(),_V(n,r,K,t().setSummary,MV(n,t().nodes,t().edges),{model:C||I?void 0:S,set:t().setLadder,...O7(n,t().nodes,t().edges)}),!G?.stepKind&&!G?.digestOf&&pt(async()=>{const{useProjects:J}=await Promise.resolve().then(()=>Na);return{useProjects:J}},void 0).then(({useProjects:J})=>{const{projects:oe,activeId:me}=J.getState(),ye=oe.find(ae=>ae.id===me);SW(r,K,ye?{id:ye.id,name:ye.name}:void 0)}),IV(e,t,n),Yl(t,n)}catch(Y){if(!m())return;Ls.delete(n);const U=t().nodes.find(L=>L.id===n)?.data.response||"";if(Y instanceof DOMException&&Y.name==="AbortError")H(U||Ne("node.stoppedPlaceholder"));else{const L=Y instanceof Error?Y.message:Ne("toast.unknownError");/no model configured/i.test(L)?(We("info",Ne("toast.noModelYet")),ce.getState().setApiKeyModalOpen(!0)):/429|too many requests|rate.?limit|quota/i.test(L)?We("info",Ne("toast.rateLimited")):We("error",ve(Ne("toast.generationFailed"),{message:L})),H(U||Ne("node.failedPlaceholder"),!0)}t().pushHistory()}}function Yl(e,t){if(ce.getState().autoRefreshPaused)return;const{nodes:n,edges:a}=e(),r=new Map(n.map(o=>[o.id,o])),s=o=>{const u=r.get(o);return!u||u.data.isLoading?!1:u.data.stepKind==="human"||u.data.stepKind==="note"||u.data.stepKind==="link"?!!u.data.question.trim():u.data.stepKind==="file"?(u.data.attachments?.length??0)>0:!!u.data.response&&!u.data.generationFailed};for(const o of a){if(o.source!==t||o.data?.isCrossLink)continue;const u=r.get(o.target);!u||u.data.stepKind!=="prompt"||u.data.response||u.data.isLoading||u.data.generationFailed||!a.filter(h=>h.target===u.id&&!h.data?.isCrossLink).map(h=>h.source).every(s)||e().rerunNode(u.id,{auto:!0})}}function IV(e,t,n){if(ce.getState().autoRefreshPaused)return;const a=new Set([n]),r=[n];for(;r.length>0;){const d=r.shift();for(const h of t().edges)h.target===d&&!h.data?.isCrossLink&&!a.has(h.source)&&(a.add(h.source),r.push(h.source))}t().edges.some(d=>d.data?.followsTip&&d.source!==n&&a.has(d.source))&&e(d=>({edges:d.edges.map(h=>h.data?.followsTip&&h.source!==n&&a.has(h.source)?{...h,id:`watch-${n}-${h.target}`,source:n}:h)}));const{nodes:o,edges:u}=t();for(const d of o){if(!(d.data.autoRerun??d.data.evaluatorTrigger==="auto")||d.id===n||d.data.isLoading||Ls.has(d.id))continue;const m=T0.get(d.id)??0;if(m>=(d.data.autoRerunRounds??1))continue;const{ordered:p}=zr(d.id,o,u);p.some(x=>x.id===n)&&(T0.set(d.id,m+1),t().rerunNode(d.id,{auto:!0}))}}const $E=e=>{for(const t of e){const n=Ls.get(t);n&&(n.abort(),Ls.delete(t))}},OV=(e,t)=>({nodes:[],edges:[],selectedNodeId:null,selectedNodeIds:[],setNodes:n=>e({nodes:n}),setEdges:n=>e({edges:n}),setSelectedNodeId:n=>e({selectedNodeId:n,selectedNodeIds:n?[n]:[]}),setSelectedNodeIds:n=>e({selectedNodeIds:n,selectedNodeId:n.length===1?n[0]:null}),deleteNode:n=>{if(Xr())return;t().logEvent("delete",n,{n:1}),t().pushHistory();const{edges:a}=t(),r=Xo(n,a),s=new Set([n,...r]);$E(s),e(o=>({nodes:o.nodes.filter(u=>!s.has(u.id)),edges:o.edges.filter(u=>!s.has(u.source)&&!s.has(u.target))})),t().pushHistory(),pt(()=>import("./canonical-Bkq2Xinv.js"),[]).then(o=>o.unsubscribeOrphanedSessions())},deleteEdges:n=>{if(Xr())return;t().logEvent("disconnect",n[0],{n:n.length});const a=new Set(n);t().edges.some(r=>a.has(r.id))&&(t().pushHistory(),e(r=>({edges:r.edges.filter(s=>!a.has(s.id))})),t().pushHistory())},editResponse:(n,a)=>{if(Xr())return;t().logEvent("edit-response",n,{chars:a.length}),t().pushHistory();const r=_n(t().nodes.find(s=>s.id===n)?.data.question+a||a);e(s=>({nodes:s.nodes.map(o=>o.id===n?{...o,data:{...o.data,response:a,responses:o.data.responses.map((u,d)=>d===o.data.responseIndex?a:u),summaries:o.data.summaries?.map((u,d)=>d===o.data.responseIndex?void 0:u),summaryTypes:o.data.summaryTypes?.map((u,d)=>d===o.data.responseIndex?void 0:u),summaryTopics:o.data.summaryTopics?.map((u,d)=>d===o.data.responseIndex?void 0:u),summaryLadders:o.data.summaryLadders?.map((u,d)=>d===o.data.responseIndex?void 0:u),editedAts:o.data.responses.map((u,d)=>d===o.data.responseIndex?new Date().toISOString():o.data.editedAts?.[d]),highlights:dm(o.data.highlights,a),isEditingResponse:!1,tokenCount:r}}:o)})),t().pushHistory()},toggleCollapse:n=>{const a=t().nodes.find(h=>h.id===n);if(!a)return;const r=Fi(a),o=C2({...a,data:{...a.data,isCollapsed:!a.data.isCollapsed}})-r,u=Xo(n,t().edges),d=new Set(u);e(h=>({nodes:h.nodes.map(m=>m.id===n?{...m,data:{...m.data,isCollapsed:!m.data.isCollapsed}}:d.has(m.id)?{...m,position:{...m.position,y:m.position.y+o}}:m)}))},setEditing:(n,a)=>{a&&Xr()||e(r=>({nodes:r.nodes.map(s=>s.id===n?{...s,data:{...s.data,isEditing:a}}:s)}))},setEditingResponse:(n,a)=>{a&&Xr()||e(r=>({nodes:r.nodes.map(s=>s.id===n?{...s,data:{...s.data,isEditingResponse:a}}:s)}))},duplicateNode:n=>{const a=t().nodes.find(m=>m.id===n);if(!a)return;t().pushHistory();const r=En(),s={id:r,type:"thought",position:{x:0,y:0},dragHandle:".drag-handle",data:{...a.data,isCollapsed:!0,isEditing:!1,isEditingResponse:!1,isLoading:!1,highlights:a.data.highlights.map(m=>({...m,id:En()}))}},o=t().edges.find(m=>m.target===n),u=o?{...o,id:`edge-${o.source}-${r}`,target:r}:null,d=u?[...t().edges,u]:t().edges,h=yr([...t().nodes,s],d);e({nodes:h,edges:d,selectedNodeId:r}),t().pushHistory()},addCrossLink:(n,a)=>{const{edges:r,nodes:s}=t();if(r.some(x=>x.source===n&&x.target===a))return;const u=s.find(x=>x.id===n);if(u&&["note","file","link"].includes(u.data.stepKind??"")){t().pushHistory();const x={id:`edge-${n}-${a}`,source:n,sourceHandle:"continue",target:a,targetHandle:"top",type:"smoothstep",style:{stroke:at.accent,strokeDasharray:"8 4",strokeWidth:2},animated:!0,data:{isCrossLink:!0,createdAt:new Date().toISOString()}};e(y=>({edges:[...y.edges,x]})),t().logEvent("connect",x.id),t().setEdgeStructural(x.id,!0);const b=t().edges.find(y=>y.id===x.id);if(b&&!b.data?.isCrossLink){const w=vr(n,t().nodes,t().edges).messages.reduce((E,v)=>E+_n(v.content),0);We("success",ve(Ne("edge.materialWiredFull"),{n:w.toLocaleString()}),8e3,{label:Ne("edge.materialMakeQuote"),run:()=>t().setEdgeStructural(x.id,!1)})}return}t().pushHistory();const d=s.find(x=>x.id===n),h=s.find(x=>x.id===a),m=!!d&&!!h&&h.position.y>d.position.y+60&&Math.abs(h.position.x-d.position.x)<320,p={id:`crosslink-${n}-${a}`,source:n,sourceHandle:m?"continue":"branch",target:a,targetHandle:m?"top":"left",type:"smoothstep",style:{stroke:at.accent,strokeDasharray:"8 4",strokeWidth:2},animated:!0,data:{isCrossLink:!0,createdAt:new Date().toISOString()}};if(e(x=>({edges:[...x.edges,p]})),t().logEvent("connect",p.id),t().pushHistory(),d&&!["note","file","link"].includes(d.data.stepKind??"")){const{ordered:x}=zr(n,s,r.filter(y=>!y.data?.isCrossLink)),b=x.filter(y=>y.id!==n&&!["note","file","link"].includes(y.data.stepKind??""));if(b.length>0){const y=_n(k0({source:d,depth:"quote",chain:b})),E=vr(n,s,r).messages.reduce((v,N)=>v+_n(N.content),0)+_n(d.data.question+d.data.response);We("info",ve(Ne("edge.linkedQuote"),{n:y}),8e3,{label:ve(Ne("edge.makeFull"),{m:E}),run:()=>t().setEdgeStructural(p.id,!0)})}}},staleIds:[],staleFps:{},staleVerdicts:{},setStaleVerdicts:n=>e(a=>({staleVerdicts:{...a.staleVerdicts,...n}})),recomputeStaleness:()=>{const{nodes:n,edges:a}=t(),r=[],s={};for(const d of n){if(!d.data.lastContextHash||!d.data.response||["note","file","link","frame"].includes(d.data.stepKind??""))continue;const h=_8(d.id,n,a);h!==d.data.lastContextHash&&(r.push(d.id),s[d.id]=h)}const o=t().staleFps,u=t().staleIds;u.length===r.length&&u.every((d,h)=>d===r[h]&&o[d]===s[d])||(e({staleIds:r,staleFps:s}),r.length&&pt(()=>Promise.resolve().then(()=>RV),void 0).then(d=>d.judgeStaleness()).catch(()=>{}))},setEdgeStructural:(n,a)=>{const{nodes:r,edges:s}=t(),o=s.find(u=>u.id===n);if(o){if(a){const u=s.filter(h=>!h.data?.isCrossLink),{ordered:d}=zr(o.source,r,u);if(d.some(h=>h.id===o.target)){We("error",Ne("edge.cycleBlocked"));return}}t().pushHistory(),t().logEvent(a?"connect":"disconnect",n,{convert:!0}),e(u=>({edges:u.edges.map(d=>{if(d.id!==n)return d;if(a){const h={...d.data??{}};return delete h.isCrossLink,delete h.contextDepth,delete h.isWatch,{...d,sourceHandle:"continue",targetHandle:"top",animated:!1,style:{stroke:at.accent,strokeWidth:2},markerEnd:{type:"arrowclosed",color:at.accent,width:18,height:18},data:h}}return{...d,animated:!0,style:{stroke:at.accent,strokeDasharray:"8 4",strokeWidth:2},markerEnd:{type:"arrowclosed",color:at.accent,width:18,height:18},data:{...d.data??{},isCrossLink:!0,contextDepth:void 0}}})})),e(u=>({nodes:yr(u.nodes,u.edges)})),t().pushHistory()}},setCrossLinkDepth:(n,a)=>{t().pushHistory(),e(r=>({edges:r.edges.map(s=>s.id!==n||!s.data?.isCrossLink?s:{...s,style:{...s.style,strokeDasharray:a==="full"?"12 3":"8 4",strokeWidth:a==="full"?3:2},data:{...s.data,contextDepth:a==="full"?"full":void 0}})})),t().pushHistory()},navigateVersion:(n,a)=>{e(r=>({nodes:r.nodes.map(s=>{if(s.id!==n)return s;const{responses:o,responseIndex:u}=s.data;let d=a==="prev"?u-1:u+1;return d<0&&(d=o.length-1),d>=o.length&&(d=0),{...s,data:{...s.data,responseIndex:d,response:o[d],question:s.data.questions?.[d]??s.data.question,generationFailed:void 0,highlights:dm(s.data.highlights,o[d])}}})}))},deleteVersion:(n,a)=>{t().pushHistory(),e(r=>({nodes:r.nodes.map(s=>{if(s.id!==n)return s;const o=s.data.responses.filter((d,h)=>h!==a);if(o.length===0)return s;const u=Math.min(s.data.responseIndex,o.length-1);return{...s,data:{...s.data,responses:o,responseIndex:u,response:o[u],questions:s.data.questions?.filter((d,h)=>h!==a),question:s.data.questions?.filter((d,h)=>h!==a)[u]??s.data.question,summaries:s.data.summaries?.filter((d,h)=>h!==a),generatedBy:s.data.generatedBy?.filter((d,h)=>h!==a),summaryTypes:s.data.summaryTypes?.filter((d,h)=>h!==a),reasonings:s.data.reasonings?.filter((d,h)=>h!==a),generatedAts:s.data.generatedAts?.filter((d,h)=>h!==a),editedAts:s.data.editedAts?.filter((d,h)=>h!==a),highlights:dm(s.data.highlights,o[u])}}})})),t().pushHistory()},relayout:()=>{Xr()||(t().pushHistory(),e(n=>{const a=E$(n.nodes,n.edges);return{nodes:yr(n.nodes,a),edges:a}}),t().pushHistory())},setArchived:(n,a)=>{const r=new Set(n);t().pushHistory(),t().logEvent(a?"archive":"unarchive",n[0],{n:n.length}),e(s=>({nodes:s.nodes.map(o=>r.has(o.id)?{...o,data:{...o.data,archived:a||void 0,archivedAt:a?new Date().toISOString():void 0}}:o)})),t().pushHistory()},setNodeModel:(n,a)=>{e(r=>({nodes:r.nodes.map(s=>s.id===n?{...s,data:{...s.data,model:a}}:s)}))},alignSelection:n=>{if(n.length<2)return;const a=new Set(n),{nodes:r,edges:s}=t(),o=new Map,u=s.filter(b=>!b.data?.isWatch),d=(b,y)=>{if(o.has(b))return o.get(b);if(y.has(b))return 0;y.add(b);const w=u.filter(v=>v.target===b&&a.has(v.source)),E=w.length===0?0:1+Math.max(...w.map(v=>d(v.source,y)));return o.set(b,E),E},h=n.map(b=>r.find(y=>y.id===b)).filter(b=>!!b).sort((b,y)=>d(b.id,new Set)-d(y.id,new Set)||b.position.y-y.position.y);t().pushHistory();const m=h[0].position;let p=m.y;const x=new Map;for(const b of h)x.set(b.id,{x:m.x,y:p}),p+=Fi(b)+40;e(b=>({nodes:b.nodes.map(y=>{const w=x.get(y.id);return w?{...y,position:w}:y})})),t().pushHistory()},batchDelete:n=>{if(Xr())return;t().logEvent("delete",n[0],{n:n.length}),t().pushHistory();const a=new Set(n);$E(a),e(r=>({nodes:r.nodes.filter(s=>!a.has(s.id)),edges:r.edges.filter(s=>!a.has(s.source)&&!a.has(s.target)),selectedNodeId:null,selectedNodeIds:[]})),t().pushHistory(),pt(()=>import("./canonical-Bkq2Xinv.js"),[]).then(r=>r.unsubscribeOrphanedSessions())},duplicateSelection:n=>{const{nodes:a,edges:r}=t(),s=new Set(n),o=a.filter(_=>s.has(_.id));if(o.length===0)return;t().pushHistory();const u=_=>({x:_.position.x,y:_.position.y,w:_.measured?.width??_.width??520,h:_.measured?.height??_.height??Fi(_)}),d=o.map(u),h={x:Math.min(...d.map(_=>_.x)),y:Math.min(...d.map(_=>_.y)),right:Math.max(...d.map(_=>_.x+_.w)),bottom:Math.max(...d.map(_=>_.y+_.h))},m=80,p=h.right-h.x+m,x=h.bottom-h.y+m,b=[];for(let _=1;_<=6;_++)b.push({dx:_*p,dy:0},{dx:0,dy:_*x},{dx:_*p,dy:_*x});const y=a.filter(_=>_.data.stepKind!=="frame").map(u),w=(_,A)=>_.x<A.x+A.w&&_.x+_.w>A.x&&_.y<A.y+A.h&&_.y+_.h>A.y,E=b.find(_=>!d.some(A=>y.some(H=>w({...A,x:A.x+_.dx,y:A.y+_.dy},H))))??{dx:p,dy:x},v=new Map,N=new Map;for(const _ of o){v.set(_.id,En());for(const A of _.data.attachments??[])N.set(A.id,En())}const S=_=>(_??[]).map(A=>N.get(A)??A),C=o.map(_=>({..._,id:v.get(_.id),position:{x:_.position.x+E.dx,y:_.position.y+E.dy},selected:!0,data:{..._.data,attachments:(_.data.attachments??[]).map(A=>({...A,id:N.get(A.id)})),excludedAttachmentIds:S(_.data.excludedAttachmentIds),includedAttachmentIds:S(_.data.includedAttachmentIds),digestOf:_.data.digestOf?N.get(_.data.digestOf)??_.data.digestOf:void 0,highlights:(_.data.highlights??[]).map(A=>({...A,id:En()})),isEditing:!1,isEditingResponse:!1,isLoading:!1}})),I=r.filter(_=>s.has(_.source)&&s.has(_.target)).map(_=>({..._,id:`edge-${v.get(_.source)}-${v.get(_.target)}`,source:v.get(_.source),target:v.get(_.target),data:_.data?{..._.data}:_.data})),O=C.map(_=>_.id);e(_=>({nodes:[..._.nodes.map(A=>A.selected?{...A,selected:!1}:A),...C],edges:[..._.edges,...I],selectedNodeId:O.length===1?O[0]:null,selectedNodeIds:O})),t().pushHistory()}}),$2=(e,t)=>{const n=e.staleVerdicts[t];return!!n&&n.fp===e.staleFps[t]&&n.p<Z$},Qr=e=>e.staleIds.filter(t=>!$2(e,t)),R7=(e,t)=>{const n=e.staleVerdicts[t];return n&&n.fp===e.staleFps[t]?n:void 0},DV=8;let Ox=!1;const Dx=new Set;async function j7(){if(Ox||!jr())return;const e=se.getState(),t=e.staleIds.filter(a=>e.staleVerdicts[a]?.fp!==e.staleFps[a]&&!Dx.has(`${a}:${e.staleFps[a]}`));if(!t.length)return;Ox=!0;try{const{nodes:a,edges:r}=e,s=[];for(const o of t.slice(0,DV)){Dx.add(`${o}:${e.staleFps[o]}`);const u=a.find(p=>p.id===o),d=u?.data.lastContextParts;if(!u||!d)continue;const h=M8(o,a,r),m=[];for(const[p,x]of Object.entries(h)){const b=d[p];(!b||b.h!==x.h)&&m.push({node:p,before:b?.head??"",after:x.text})}for(const p of Object.keys(d))h[p]||m.push({node:p,before:d[p].head,after:""});m.length&&s.push({id:o,question:u.data.question,answer:u.data.response,changes:m})}if(s.length){const o=await J$(s),u={};for(const d of s)u[d.id]={fp:e.staleFps[d.id],p:o[d.id],changed:d.changes.map(h=>h.node)};se.getState().setStaleVerdicts(u)}}catch{}finally{Ox=!1}const n=se.getState();n.staleIds.some(a=>n.staleVerdicts[a]?.fp!==n.staleFps[a]&&!Dx.has(`${a}:${n.staleFps[a]}`))&&j7()}const RV=Object.freeze(Object.defineProperty({__proto__:null,currentStaleVerdict:R7,judgeStaleness:j7,shownStaleIds:Qr,staleHiddenByJudge:$2},Symbol.toStringTag,{value:"Module"})),jV=(e,t)=>({addQuestion:async(n,a={})=>{if(Xr())return;const{parentId:r,branchContext:s,branchYRatio:o,inheritRole:u,rolePrompt:d,initialAttachments:h,excludeAllInheritedAttachments:m,mentions:p}=a,x=En();t().logEvent("ask",x,{chars:n.length,...r?{}:{root:!0},...s?{branch:!0}:{}});const b=!r,y=r?t().nodes.find(Y=>Y.id===r)?.data.model:void 0,w={id:x,type:"thought",position:{x:0,y:0},dragHandle:".drag-handle",data:{question:n,createdAt:new Date().toISOString(),askedAt:new Date().toISOString(),model:y,response:"",responses:[],responseIndex:-1,isCollapsed:!1,isEditing:!1,isEditingResponse:!1,isLoading:!0,tokenCount:0,branchContext:s,highlights:[],highlightMode:"tag",attachments:h||[],excludedAttachmentIds:m&&r?t().getInheritedAttachments(r).map(({attachment:Y})=>Y.id).concat((t().nodes.find(Y=>Y.id===r)?.data.attachments||[]).map(Y=>Y.id)):[],includedAttachmentIds:[],roleMode:u===!1?"reset":"inherit",rolePrompt:d||void 0,isRoot:b,isBranch:!!s,webSearch:ce.getState().webSearchEnabled,scholarSearch:ce.getState().scholarSearchEnabled,...qc()}},E=!!s,v=r?{id:`edge-${r}-${x}`,source:r,target:x,sourceHandle:E?"branch":"continue",targetHandle:E?"left":"top",type:"smoothstep",...E?{style:{stroke:at.warm,strokeWidth:2},animated:!1,markerEnd:{type:"arrowclosed",color:at.warm,width:18,height:18},data:{isBranchFromSelection:!0,branchYRatio:o??.5}}:{style:{stroke:at.accent,strokeWidth:2},animated:!1,markerEnd:{type:"arrowclosed",color:at.accent,width:18,height:18},data:{}}}:null;let N=v?[...t().edges,v]:t().edges;const S=(p??[]).filter(Y=>Y!==x&&Y!==r&&t().nodes.some(U=>U.id===Y));if(S.length>0){const Y=N.filter(q=>!q.data?.isCrossLink),U=r?new Set(zr(r,t().nodes,Y).ordered.map(q=>q.id)):new Set,z=new Set(N.filter(q=>q.data?.isCrossLink&&q.target===x).map(q=>q.source));let L=0;for(const q of S)U.has(q)||z.has(q)||(N=[...N,{id:`crosslink-${q}-${x}`,source:q,target:x,sourceHandle:"branch",targetHandle:"left",type:"smoothstep",style:{stroke:at.accent,strokeDasharray:"8 4",strokeWidth:2},animated:!0,data:{isCrossLink:!0,createdAt:new Date().toISOString()}}],L++);L>0&&We("info",ve(Ne("mention.wired"),{n:L}),6e3)}const C=r?t().nodes.map(Y=>Y.id===r?{...Y,data:{...Y.data,isCollapsed:!0}}:Y):t().nodes,I=yr([...C,w],N);e({nodes:I,edges:N,selectedNodeId:x});const O=t().nodes.find(Y=>Y.id===x),_=r?vr(r,t().nodes,t().edges,s,O?.data.excludedAttachmentIds,O?.data.includedAttachmentIds,Qr(t())):{messages:[],images:[],sources:[]},A=_.messages,H=_.images,G=r?t().nodes.find(Y=>Y.id===r):null;NE(A,SE(O?.data,G?.data,!!r));const D=O?.data.attachments||[];for(const Y of D)A.some(z=>z.content.includes(`[PDF: ${Y.name}]`)||z.content.includes(`[File: ${Y.name}]`))||(Y.type.startsWith("image/")?H.push({data:Y.content,mimeType:Y.type}):Y.type==="application/pdf"?Y.extractedText&&A.push({role:"user",content:`[PDF: ${Y.name}]
233
233
  ${Y.extractedText}`}):Y.type==="text/html"?Y.extractedText?.trim()&&A.push({role:"user",content:`[File: ${Y.name}]
234
234
  ${Y.extractedText}`}):Y.content&&A.push({role:"user",content:`[File: ${Y.name}]
235
235
  ${Y.content}`}));const P=A.find(Y=>Y.role==="system")?.content||void 0;A.push({role:"user",content:n}),e(Y=>({nodes:Y.nodes.map(U=>U.id===x?{...U,data:{...U.data,appliedRole:P}}:U)})),await Bi(e,t,x,{question:n,messages:A,images:H,sources:_.sources})},fanOut:async(n,a,r,s={})=>{t().logEvent("fanout",n,{roles:r.length,chars:a.length});const o=t().nodes.find(S=>S.id===n);if(!o||r.length===0)return;const u=!!s.follow,d=u&&s.rounds&&s.rounds>1?Math.min(s.rounds,5):void 0;t().pushHistory();const h=[],m=[],p=[];r.forEach((S,C)=>{const I=En(),O=`${S.prompt}
@@ -287,7 +287,7 @@ ${u.content.trim()}`).join(`
287
287
 
288
288
  ---
289
289
 
290
- ${p}`:p,v=ce.getState().agentEffort||void 0,N=[...new Set(se.getState().nodes.flatMap(A=>(A.data.approvals??[]).filter(H=>H.outcome==="allowed-session"&&typeof H.rule=="string"&&H.rule.startsWith(h.runtime==="claude-code"?"claude:":h.runtime+":")).map(H=>H.rule)))];GV();let S="",C="",I="";const _=await new Promise(A=>{d.run({runtime:h.runtime,cwd:m,prompt:E,...o?.sessionPath?{sessionPath:o.sessionPath}:{},...o?.forkEntryId?{forkEntryId:o.forkEntryId}:{},images:(a??[]).map(H=>({type:"image",data:H.data,mimeType:H.mimeType})),model:{provider:h.provider,id:h.id},...v?{effort:v}:{},...N.length?{allowRules:N}:{}}).then(H=>{const G=()=>{d.abort(H)};n?.aborted&&G(),n?.addEventListener("abort",G,{once:!0}),hm.set(H,D=>{switch(D.type){case"session":{const P=D.model?.resolved;P&&window.dispatchEvent(new CustomEvent("td:agent-model-resolved",{detail:{id:s,resolved:P}})),r?.onAgentSession?.({runtime:h.runtime,sessionId:D.sessionId??null,sessionFile:D.sessionFile??null,cwd:D.cwd??m,...typeof D.effort=="string"&&D.effort?{effort:D.effort}:{}});break}case"message_update":{const P=D.assistantMessageEvent;P?.type==="text_delta"&&P.delta?(S+=P.delta,t(P.delta,S)):P?.type==="thinking_delta"&&P.delta&&(C+=P.delta,r?.onReasoning?.(P.delta,C));break}case"tool_execution_start":{const P=String(D.toolName??"tool"),Y=YV(P,D.args);r?.onAgentTool?.({id:String(D.toolCallId??""),name:P,query:Y,phase:"start"});break}case"tool_execution_end":r?.onAgentTool?.({id:String(D.toolCallId??""),name:String(D.toolName??"tool"),query:"",phase:"end",isError:!!D.isError});break;case"extension_ui_cancelled":{const P=`dialog-${Date.now()}`,Y=String(D.title??D.method??"dialog");r?.onAgentTool?.({id:P,name:"dialog",query:Y,phase:"start"}),r?.onAgentTool?.({id:P,name:"dialog",query:"",phase:"end",isError:!0});break}case"question_answered":r?.onApprovalDecided?.({...D.auto?{auto:!0,name:String(D.title??""),query:String(D.message??""),rule:typeof D.rule=="string"?D.rule:null}:{},id:String(D.id),outcome:D.outcome??"cancelled",value:typeof D.value=="string"?D.value:null});break;case"question":r?.onApproval?.({id:String(D.id),kind:D.kind??"confirm",toolName:h.runtime,callId:null,reason:null,name:String(D.title??""),query:String(D.message??""),arguments:null,options:Array.isArray(D.options)?D.options:[],placeholder:typeof D.placeholder=="string"?D.placeholder:null,prefill:typeof D.prefill=="string"?D.prefill:null,channel:{runId:H},paths:Array.isArray(D.paths)?D.paths:[],suggest:typeof D.suggest=="string"?D.suggest:null,rule:typeof D.rule=="string"?D.rule:null});break;case"fs_changes":r?.onAgentChanges?.({changed:D.changed??[],added:D.added??[],removed:D.removed??[],truncated:!!D.truncated});break;case"run_end":I=typeof D.text=="string"&&D.text?D.text:S,hm.delete(H),n?.removeEventListener("abort",G),A({how:String(D.how??"end")});break;case"run_error":hm.delete(H),n?.removeEventListener("abort",G),A({how:"error",error:String(D.message??"agent run failed")});break}})}).catch(H=>A({how:"error",error:H instanceof Error?H.message:String(H)}))});if(n?.aborted)throw new DOMException("The operation was aborted.","AbortError");if(_.how==="error")throw new Error(_.error??"agent run failed");return I||S}async function XV(e,t,n){const a=o=>(console.warn("[agent] turn not adopted:",o,t.runtime,t.sessionFile),!1),r=window.desktopSessions;if(!r||!t.sessionFile)return a(r?"no session file":"no sessions bridge");const s=Ji[t.runtime].rootKey;try{const u=(await r.roots()).find(U=>U.key===s);if(!u)return a("no root "+s);const d=u.path.replace(/\/$/,"")+"/";if(!t.sessionFile.startsWith(d))return a("file outside root "+d);const h=t.sessionFile.slice(d.length),{anyRunnerSessionConversation:m}=await pt(async()=>{const{anyRunnerSessionConversation:U}=await import("./index-CjJoJV4P.js");return{anyRunnerSessionConversation:U}},[]),{useStore:p}=await pt(async()=>{const{useStore:U}=await Promise.resolve().then(()=>ws);return{useStore:U}},void 0),{useProjects:x,registerLedgerEntry:b,updateSourceSession:y,subscribedSessionIds:w}=await pt(async()=>{const{useProjects:U,registerLedgerEntry:z,updateSourceSession:L,subscribedSessionIds:q}=await Promise.resolve().then(()=>Na);return{useProjects:U,registerLedgerEntry:z,updateSourceSession:L,subscribedSessionIds:q}},void 0),E=await r.read(s,h);if(!E)return a("empty file");const v=await m(E);if(!v?.sessionId)return a("no conversation recognized");const S=v.build().nodes.filter(U=>U.data.importSource),C=n.trim();let I=-1;for(let U=S.length-1;U>=0;U--){const z=S[U].data.question.trim();if(z===C||z.endsWith(C)||C.endsWith(z)){I=U;break}}if(I<0&&(I=S.length-1),I<0)return a("no turn in file yet");const O=S[I],_=O.data.attachments??[],A=ZV(t,_),H=A?[..._,A]:_;p.setState(U=>({nodes:U.nodes.map(z=>z.id===e?{...z,data:{...z.data,attachments:[...(z.data.attachments??[]).filter(L=>!L.op),...H],excludedAttachmentIds:[...new Set([...z.data.excludedAttachmentIds??[],...H.map(L=>L.id)])],importSource:O.data.importSource,source:O.data.source??{question:O.data.question,response:O.data.response},agentTrace:void 0}}:z)}));const{projects:G,activeId:D}=x.getState(),P=D?G.find(U=>U.id===D):void 0;if(!P)return!0;const Y={sessionId:v.sessionId,runner:t.runtime,importedCount:I+1,tailNodeId:e};if(w(P).includes(v.sessionId)){const{patchLedgerEntry:U}=await pt(async()=>{const{patchLedgerEntry:z}=await Promise.resolve().then(()=>Na);return{patchLedgerEntry:z}},void 0);await U(D,v.sessionId,{importedCount:I+1,tailNodeId:e})}else P.sourceSession?await b(D,"chapter",Y):(await y(D,Y),x.getState().projects.find(U=>U.id===D)?.sourceSession||(x.setState(U=>({projects:U.projects.map(z=>z.id===D?{...z,sourceSession:Y}:z)})),await b(D,"chapter",Y).catch(()=>{}),x.setState(U=>({projects:U.projects.map(z=>z.id===D&&z.sourceSession?{...z,sourceSession:{...z.sourceSession,chapters:(z.sourceSession.chapters??[]).filter(L=>L.sessionId!==Y.sessionId)}}:z)}))));return!0}catch(o){return a("threw: "+(o instanceof Error?o.message:String(o)))}}async function QV(){try{const{useProjects:e}=await pt(async()=>{const{useProjects:r}=await Promise.resolve().then(()=>Na);return{useProjects:r}},void 0),{projects:t,activeId:n}=e.getState(),a=t.find(r=>r.id===n)?.agentGuard;return{mode:a?.mode==="allow"?"allow":"ask",allow:a?.allow??[]}}catch{return{mode:"ask",allow:[]}}}async function V2(e){if(!window.desktopAgents)return;const t=e??(await W2())?.cwd;if(t)try{await window.desktopAgents.guardWrite(t,await QV())}catch{}}async function YE(e){const{useProjects:t,setProjectAgentGuard:n}=await pt(async()=>{const{useProjects:o,setProjectAgentGuard:u}=await Promise.resolve().then(()=>Na);return{useProjects:o,setProjectAgentGuard:u}},void 0),{projects:a,activeId:r}=t.getState();if(!r)return;const s=a.find(o=>o.id===r)?.agentGuard;await n(r,{mode:e,allow:s?.allow??[]}),await V2()}async function z7(e,t=!1){const{useProjects:n,setProjectAgentGuard:a}=await pt(async()=>{const{useProjects:d,setProjectAgentGuard:h}=await Promise.resolve().then(()=>Na);return{useProjects:d,setProjectAgentGuard:h}},void 0),{projects:r,activeId:s}=n.getState();if(!s)return;const o=r.find(d=>d.id===s)?.agentGuard,u=t?(o?.allow??[]).filter(d=>d!==e):[...new Set([...o?.allow??[],e])];await a(s,{mode:o?.mode??"ask",allow:u}),await V2()}function ZV(e,t){const n=e.changes;if(!n)return null;const a=new Set;for(const d of t)for(const h of d.paths??[])a.add(h.startsWith("/")?h:`${e.cwd.replace(/\/$/,"")}/${h}`);const r=[...n.changed,...n.added].filter(d=>!a.has(d)),s=n.removed.filter(d=>!a.has(d));if(r.length===0&&s.length===0&&!n.truncated)return null;const o=d=>d.startsWith(e.cwd)?d.slice(e.cwd.length).replace(/^\//,""):d,u=[];return r.length&&u.push("Changed on disk during this turn (seen by the file system, not declared by a tool):",...r.map(d=>"- "+o(d))),s.length&&u.push("Removed:",...s.map(d=>"- "+o(d))),n.truncated&&u.push("(the directory was too large to scan completely)"),{id:`fs-${Date.now().toString(36)}`,name:"tool: fs-changes",type:"text/plain",size:0,content:u.join(`
290
+ ${p}`:p,v=ce.getState().agentEffort||void 0,N=[...new Set(se.getState().nodes.flatMap(A=>(A.data.approvals??[]).filter(H=>H.outcome==="allowed-session"&&typeof H.rule=="string"&&H.rule.startsWith(h.runtime==="claude-code"?"claude:":h.runtime+":")).map(H=>H.rule)))];GV();let S="",C="",I="";const _=await new Promise(A=>{d.run({runtime:h.runtime,cwd:m,prompt:E,...o?.sessionPath?{sessionPath:o.sessionPath}:{},...o?.forkEntryId?{forkEntryId:o.forkEntryId}:{},images:(a??[]).map(H=>({type:"image",data:H.data,mimeType:H.mimeType})),model:{provider:h.provider,id:h.id},...v?{effort:v}:{},...N.length?{allowRules:N}:{}}).then(H=>{const G=()=>{d.abort(H)};n?.aborted&&G(),n?.addEventListener("abort",G,{once:!0}),hm.set(H,D=>{switch(D.type){case"session":{const P=D.model?.resolved;P&&window.dispatchEvent(new CustomEvent("td:agent-model-resolved",{detail:{id:s,resolved:P}})),r?.onAgentSession?.({runtime:h.runtime,sessionId:D.sessionId??null,sessionFile:D.sessionFile??null,cwd:D.cwd??m,...typeof D.effort=="string"&&D.effort?{effort:D.effort}:{}});break}case"message_update":{const P=D.assistantMessageEvent;P?.type==="text_delta"&&P.delta?(S+=P.delta,t(P.delta,S)):P?.type==="thinking_delta"&&P.delta&&(C+=P.delta,r?.onReasoning?.(P.delta,C));break}case"tool_execution_start":{const P=String(D.toolName??"tool"),Y=YV(P,D.args);r?.onAgentTool?.({id:String(D.toolCallId??""),name:P,query:Y,phase:"start"});break}case"tool_execution_end":r?.onAgentTool?.({id:String(D.toolCallId??""),name:String(D.toolName??"tool"),query:"",phase:"end",isError:!!D.isError});break;case"extension_ui_cancelled":{const P=`dialog-${Date.now()}`,Y=String(D.title??D.method??"dialog");r?.onAgentTool?.({id:P,name:"dialog",query:Y,phase:"start"}),r?.onAgentTool?.({id:P,name:"dialog",query:"",phase:"end",isError:!0});break}case"question_answered":r?.onApprovalDecided?.({...D.auto?{auto:!0,name:String(D.title??""),query:String(D.message??""),rule:typeof D.rule=="string"?D.rule:null}:{},id:String(D.id),outcome:D.outcome??"cancelled",value:typeof D.value=="string"?D.value:null});break;case"question":r?.onApproval?.({id:String(D.id),kind:D.kind??"confirm",toolName:h.runtime,callId:null,reason:null,name:String(D.title??""),query:String(D.message??""),arguments:null,options:Array.isArray(D.options)?D.options:[],placeholder:typeof D.placeholder=="string"?D.placeholder:null,prefill:typeof D.prefill=="string"?D.prefill:null,channel:{runId:H},paths:Array.isArray(D.paths)?D.paths:[],suggest:typeof D.suggest=="string"?D.suggest:null,rule:typeof D.rule=="string"?D.rule:null});break;case"fs_changes":r?.onAgentChanges?.({changed:D.changed??[],added:D.added??[],removed:D.removed??[],truncated:!!D.truncated});break;case"run_end":I=typeof D.text=="string"&&D.text?D.text:S,hm.delete(H),n?.removeEventListener("abort",G),A({how:String(D.how??"end")});break;case"run_error":hm.delete(H),n?.removeEventListener("abort",G),A({how:"error",error:String(D.message??"agent run failed")});break}})}).catch(H=>A({how:"error",error:H instanceof Error?H.message:String(H)}))});if(n?.aborted)throw new DOMException("The operation was aborted.","AbortError");if(_.how==="error")throw new Error(_.error??"agent run failed");return I||S}async function XV(e,t,n){const a=o=>(console.warn("[agent] turn not adopted:",o,t.runtime,t.sessionFile),!1),r=window.desktopSessions;if(!r||!t.sessionFile)return a(r?"no session file":"no sessions bridge");const s=Ji[t.runtime].rootKey;try{const u=(await r.roots()).find(U=>U.key===s);if(!u)return a("no root "+s);const d=u.path.replace(/\/$/,"")+"/";if(!t.sessionFile.startsWith(d))return a("file outside root "+d);const h=t.sessionFile.slice(d.length),{anyRunnerSessionConversation:m}=await pt(async()=>{const{anyRunnerSessionConversation:U}=await import("./index-C4lWKzPK.js");return{anyRunnerSessionConversation:U}},[]),{useStore:p}=await pt(async()=>{const{useStore:U}=await Promise.resolve().then(()=>ws);return{useStore:U}},void 0),{useProjects:x,registerLedgerEntry:b,updateSourceSession:y,subscribedSessionIds:w}=await pt(async()=>{const{useProjects:U,registerLedgerEntry:z,updateSourceSession:L,subscribedSessionIds:q}=await Promise.resolve().then(()=>Na);return{useProjects:U,registerLedgerEntry:z,updateSourceSession:L,subscribedSessionIds:q}},void 0),E=await r.read(s,h);if(!E)return a("empty file");const v=await m(E);if(!v?.sessionId)return a("no conversation recognized");const S=v.build().nodes.filter(U=>U.data.importSource),C=n.trim();let I=-1;for(let U=S.length-1;U>=0;U--){const z=S[U].data.question.trim();if(z===C||z.endsWith(C)||C.endsWith(z)){I=U;break}}if(I<0&&(I=S.length-1),I<0)return a("no turn in file yet");const O=S[I],_=O.data.attachments??[],A=ZV(t,_),H=A?[..._,A]:_;p.setState(U=>({nodes:U.nodes.map(z=>z.id===e?{...z,data:{...z.data,attachments:[...(z.data.attachments??[]).filter(L=>!L.op),...H],excludedAttachmentIds:[...new Set([...z.data.excludedAttachmentIds??[],...H.map(L=>L.id)])],importSource:O.data.importSource,source:O.data.source??{question:O.data.question,response:O.data.response},agentTrace:void 0}}:z)}));const{projects:G,activeId:D}=x.getState(),P=D?G.find(U=>U.id===D):void 0;if(!P)return!0;const Y={sessionId:v.sessionId,runner:t.runtime,importedCount:I+1,tailNodeId:e};if(w(P).includes(v.sessionId)){const{patchLedgerEntry:U}=await pt(async()=>{const{patchLedgerEntry:z}=await Promise.resolve().then(()=>Na);return{patchLedgerEntry:z}},void 0);await U(D,v.sessionId,{importedCount:I+1,tailNodeId:e})}else P.sourceSession?await b(D,"chapter",Y):(await y(D,Y),x.getState().projects.find(U=>U.id===D)?.sourceSession||(x.setState(U=>({projects:U.projects.map(z=>z.id===D?{...z,sourceSession:Y}:z)})),await b(D,"chapter",Y).catch(()=>{}),x.setState(U=>({projects:U.projects.map(z=>z.id===D&&z.sourceSession?{...z,sourceSession:{...z.sourceSession,chapters:(z.sourceSession.chapters??[]).filter(L=>L.sessionId!==Y.sessionId)}}:z)}))));return!0}catch(o){return a("threw: "+(o instanceof Error?o.message:String(o)))}}async function QV(){try{const{useProjects:e}=await pt(async()=>{const{useProjects:r}=await Promise.resolve().then(()=>Na);return{useProjects:r}},void 0),{projects:t,activeId:n}=e.getState(),a=t.find(r=>r.id===n)?.agentGuard;return{mode:a?.mode==="allow"?"allow":"ask",allow:a?.allow??[]}}catch{return{mode:"ask",allow:[]}}}async function V2(e){if(!window.desktopAgents)return;const t=e??(await W2())?.cwd;if(t)try{await window.desktopAgents.guardWrite(t,await QV())}catch{}}async function YE(e){const{useProjects:t,setProjectAgentGuard:n}=await pt(async()=>{const{useProjects:o,setProjectAgentGuard:u}=await Promise.resolve().then(()=>Na);return{useProjects:o,setProjectAgentGuard:u}},void 0),{projects:a,activeId:r}=t.getState();if(!r)return;const s=a.find(o=>o.id===r)?.agentGuard;await n(r,{mode:e,allow:s?.allow??[]}),await V2()}async function z7(e,t=!1){const{useProjects:n,setProjectAgentGuard:a}=await pt(async()=>{const{useProjects:d,setProjectAgentGuard:h}=await Promise.resolve().then(()=>Na);return{useProjects:d,setProjectAgentGuard:h}},void 0),{projects:r,activeId:s}=n.getState();if(!s)return;const o=r.find(d=>d.id===s)?.agentGuard,u=t?(o?.allow??[]).filter(d=>d!==e):[...new Set([...o?.allow??[],e])];await a(s,{mode:o?.mode??"ask",allow:u}),await V2()}function ZV(e,t){const n=e.changes;if(!n)return null;const a=new Set;for(const d of t)for(const h of d.paths??[])a.add(h.startsWith("/")?h:`${e.cwd.replace(/\/$/,"")}/${h}`);const r=[...n.changed,...n.added].filter(d=>!a.has(d)),s=n.removed.filter(d=>!a.has(d));if(r.length===0&&s.length===0&&!n.truncated)return null;const o=d=>d.startsWith(e.cwd)?d.slice(e.cwd.length).replace(/^\//,""):d,u=[];return r.length&&u.push("Changed on disk during this turn (seen by the file system, not declared by a tool):",...r.map(d=>"- "+o(d))),s.length&&u.push("Removed:",...s.map(d=>"- "+o(d))),n.truncated&&u.push("(the directory was too large to scan completely)"),{id:`fs-${Date.now().toString(36)}`,name:"tool: fs-changes",type:"text/plain",size:0,content:u.join(`
291
291
  `),op:"write",paths:[...r,...s]}}let nr=null,hy=null;const Qd=new Set;function hr(){return nr?Promise.resolve(nr):(hy??=(async()=>{const e=rs();let t=null;if(e.length>0)try{t=await Y0(e)}catch{}return t||(t=await fetch(`${hi}/api/models`).then(n=>n.json()).then(n=>({models:n.models??[],default:n.default??null,capabilities:n.capabilities})).catch(()=>null)),t?(nr=F7(t),nr):null})(),hy)}function KE(e){return(e.split("/").pop()??e).toLowerCase()}function B7(e,t){if(t.some(r=>r.id===e))return e;const n=KE(e),a=t.find(r=>KE(r.id)===n);return a?a.id:null}const G2="thoughtdag.agentModels",H7="thoughtdag.agentModelNames",Mp=()=>typeof window<"u"&&!!window.desktopAgents,vu=e=>e.provider===or&&li(e.id);function Y2(){try{const e=JSON.parse(localStorage.getItem(H7)??"{}");return e&&typeof e=="object"?e:{}}catch{return{}}}function K2(e){const t=Y2();return e.map(n=>{const a=n.provider===or?t[n.id]:void 0;return!a||n.id.endsWith("/"+a)||n.name.includes(a)?n:{...n,name:`${n.name} · ${ve(Ne("models.resolvedLast"),{r:a})}`}})}function A0(e,t,n){if(!e)return"";const a=L7(e);if(!a)return e.split("/").pop()??e;let r=[];try{r=JSON.parse(localStorage.getItem(G2)??"[]")}catch{r=[]}const o=r.find(h=>h&&h.id===e)?.name??`${Ji[a.runtime].label} · ${a.id}`,u=n?.compact?void 0:Y2()[e],d=u&&!o.includes(u)?`${o} · ${u}`:o;return t?`${d} · ${t}`:d}function F7(e){if(!Mp())return e;let t=[];try{t=JSON.parse(localStorage.getItem(G2)??"[]")}catch{t=[]}const n=e.models.filter(a=>!vu(a));return{...e,models:[...n,...K2(t.filter(a=>a&&vu(a)))],agentsPending:!1}}let Wm=!1,_d=null;async function X2(){if(!(!Mp()||!nr))return _d||(_d=(async()=>{const e=nr;Kl({...e,agentsPending:!0});const t=await FV().catch(()=>({models:[],runtimes:{}})),n=t.models;try{localStorage.setItem(G2,JSON.stringify(n))}catch{}const a=(nr??e).models.filter(r=>!vu(r));Kl({...nr??e,models:[...a,...K2(n)],agentsPending:!1,runtimes:t.runtimes})})().finally(()=>{_d=null}),_d)}function JV(){return Wm=!0,hr().then(()=>X2())}function XE(){Wm||!Mp()||(Wm=!0,hr().then(()=>X2()))}function eG(e,t){if(!e||!t)return;const n=Y2();if(n[e]===t)return;n[e]=t;try{localStorage.setItem(H7,JSON.stringify(n))}catch{}if(!nr)return;const a=nr.models.filter(s=>!vu(s)),r=nr.models.filter(vu).map(s=>({...s,name:s.name.split(" · ").slice(0,2).join(" · ")}));Kl({...nr,models:[...a,...K2(r)]})}typeof window<"u"&&window.addEventListener("td:agent-model-resolved",e=>{const t=e.detail;t?.id&&t?.resolved&&eG(t.id,t.resolved)});function Kl(e){nr=e,hy=Promise.resolve(e);for(const t of Qd)t(e);if(e.agentsPending===void 0&&Mp()&&!e.models.some(vu)){nr=F7(e);for(const t of Qd)t(nr);Wm&&X2()}}function ec(){const[e,t]=R.useState(nr);return R.useEffect(()=>{const n=a=>t(a);return Qd.add(n),nr||hr().then(a=>{Qd.has(n)&&a&&t(a)}),()=>{Qd.delete(n)}},[]),e}const tG=[[/^(Read|NotebookRead)$/i,"📖"],[/^(Edit|Write|MultiEdit|NotebookEdit)$/i,"✏️"],[/^(Bash|BashOutput|Shell)$/i,"⌨️"],[/^(Grep|Glob|LS|Search|WebSearch)$/i,"🔍"],[/^(WebFetch|Fetch)$/i,"🌐"],[/^(Task|Agent)$/i,"🤖"]],U7=/^tool: (\S+?)( \(truncated\))?$/;function nG(e){const t=new Map;for(const n of e.attachments??[]){const a=n.name.match(U7);if(!a)continue;const r=a[1],s=tG.find(([u])=>u.test(r))?.[1]??"🔧",o=t.get(r);o?o.count+=1:t.set(r,{glyph:s,name:r,count:1})}return[...t.values()]}function aG(e){let t=0;for(const s of e.attachments??[])U7.test(s.name)&&(t+=_n(s.content));if(t===0)return null;const n=_n(e.question),a=_n(e.response),r=n+a+t;return{q:n,a,tool:t,total:r,toolShare:r>0?t/r:0}}function rG(e){const t=new Map;for(const n of e.attachments??[])if(!(!n.paths?.length||n.op!=="read"&&n.op!=="write"&&n.op!=="edit"))for(const a of n.paths){const r=t.get(a);r?r.op==="read"&&n.op!=="read"&&(r.op=n.op):t.set(a,{path:a,name:a.split("/").filter(Boolean).pop()??a,op:n.op})}return[...t.values()].sort((n,a)=>(n.op==="read"?1:0)-(a.op==="read"?1:0))}function sG(e,t=140){const n=e.replace(/```[\s\S]*?```/g,"").split(/\n\s*\n/).map(s=>s.replace(/!?\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/[#*`>|_~]/g,"").replace(/^\s*[-•\d.)]+\s*/gm,"").replace(/\s+/g," ").trim()).filter(s=>s.length>12&&!/[::]$/.test(s)&&!/^(sources?|references?|来源|参考)\b/i.test(s)),a=n.filter(s=>s.length>=30),r=a[a.length-1]??n[n.length-1]??e.replace(/[#*`>-]/g,"").replace(/\s+/g," ").trim();return r.length>t?`${r.slice(0,t)}…`:r}function Z0(){const e=R.useRef("work");return fn(t=>{const n=t.transform[2],a=e.current;return a==="work"?n<=.8&&(e.current=n<=.32?"glyph":"map"):a==="map"?n>=.9?e.current="work":n<=.32&&(e.current="glyph"):n>=.9?e.current="work":n>=.4&&(e.current="map"),e.current})}const QE={en:{name:"Rule-out / Rule-in",steps:[{id:"q",kind:"human",x:560,y:40,title:"Research question",instruction:"Type the question to differentiate: what phenomenon needs explaining?"},{id:"mechA",kind:"prompt",x:20,y:440,title:"Candidate: Mechanism A",instruction:`You advocate a low-level mechanistic account of the phenomenon. Be concrete and falsifiable.
292
292
  From this lens, give the single best candidate explanation for the question above: name the mechanism, its testable predictions, and what evidence would rule it in or out.`},{id:"mechB",kind:"prompt",x:500,y:440,title:"Candidate: Mechanism B",instruction:`You advocate a higher-level / systems account. Name the mechanism and its boundary conditions.
293
293
  From this lens, give the single best candidate explanation for the question above: name the mechanism, its testable predictions, and what evidence would rule it in or out.`},{id:"conf",kind:"prompt",x:980,y:440,title:"Candidate: Confound",instruction:`You argue the effect is an artifact or confound, not the phenomenon of interest.
@@ -298,13 +298,13 @@ For each candidate above, judge what evidence would rule it OUT and what would r
298
298
  严格从这个视角,为上面的问题给出唯一最佳的候选解释:说清机制、可检验的预测,以及什么证据能确认或排除它。`},{id:"conf",kind:"prompt",x:980,y:440,title:"候选:混杂",instruction:`你主张这个效应是假象或混杂因素,而非目标现象。
299
299
  严格从这个视角,为上面的问题给出唯一最佳的候选解释:说清疑似的混杂来源、可检验的预测,以及什么证据能确认或排除它。`},{id:"null",kind:"prompt",x:1460,y:440,title:"候选:零假设",instruction:`你主张这个效应可能不真实或被夸大,给出最强的收缩性论证。
300
300
  严格从这个视角回答上面的问题:什么会让效应消失,以及什么证据能确认或排除这一解释。`},{id:"rev",kind:"prompt",x:560,y:920,title:"鉴别评审",instruction:`你是一位严谨的方法学家,正在对相互竞争的解释做鉴别诊断。
301
- 对上面每个候选,判断什么证据能将它排除(rule out)、什么能将它确认(rule in)。按可区分度排序:哪个检验最能把它们分开?`},{id:"syn",kind:"prompt",x:560,y:1360,title:"收敛",instruction:"综合上面的候选与区分性检验:先确认哪个解释、排除哪个,以及信息量最大的下一个实验是什么。"}],edges:[["q","mechA"],["q","mechB"],["q","conf"],["q","null"],["mechA","rev"],["mechB","rev"],["conf","rev"],["null","rev"],["rev","syn"]]}};function iG(e){const{name:t,steps:n,edges:a}=QE[e]??QE.en,r=n.map(o=>({id:`p-${o.id}`,type:"thought",position:{x:o.x,y:o.y},dragHandle:".drag-handle",data:{question:o.title,instruction:o.instruction,stepKind:o.kind,response:"",responses:[],responseIndex:-1,isCollapsed:!1,isEditing:!1,isEditingResponse:!1,isLoading:!1,tokenCount:0,highlights:[],highlightMode:"tag",attachments:[],excludedAttachmentIds:[],includedAttachmentIds:[],roleMode:"inherit",isRoot:o.id==="q",isBranch:!1}})),s=a.map(([o,u])=>({id:`p-e-${o}-${u}`,source:`p-${o}`,target:`p-${u}`,type:"smoothstep",sourceHandle:"continue",targetHandle:"top",style:{stroke:"#6B5CE7",strokeWidth:2},markerEnd:{type:"arrowclosed",color:"#6B5CE7",width:18,height:18},data:{}}));return{name:t,nodes:r,edges:s}}const fy="thoughtdag:projects",ZE="thoughtdag",ks=e=>`thoughtdag:project:${e}`;async function Vm(e,t){const{projects:n,activeId:a}=sn.getState();if(t&&e===a){const r=n.filter(s=>s.id!==e&&!s.archived).sort((s,o)=>o.updatedAt-s.updatedAt);r.length>0?await Wi(r[0].id):await Ip("My Canvas")}sn.setState(r=>({projects:r.projects.map(s=>s.id===e?{...s,archived:t}:s)})),await Br()}async function oG(e,t){sn.setState(n=>({projects:n.projects.map(a=>a.id===e&&a.sourceSession?{...a,sourceSession:{...a.sourceSession,...t}}:a)})),await Br()}async function lG(e,t,n){sn.setState(a=>({projects:a.projects.map(r=>{if(r.id!==e||!r.sourceSession)return r;const s=r.sourceSession;return s.sessionId===t?{...r,sourceSession:{...s,...n}}:{...r,sourceSession:{...s,chapters:s.chapters?.map(o=>o.sessionId===t?{...o,...n}:o),branches:s.branches?.map(o=>o.sessionId===t?{...o,...n}:o)}}})})),await Br()}async function cG(e,t,n){sn.setState(a=>({projects:a.projects.map(r=>{if(r.id!==e)return r;const s=r.sourceSession??{sessionId:"",runner:"",importedCount:0,tailNodeId:""};return t==="chapter"?{...r,sourceSession:{...s,chapters:[...s.chapters??[],{sessionId:n.sessionId,runner:n.runner,importedCount:n.importedCount,tailNodeId:n.tailNodeId}]}}:{...r,sourceSession:{...s,branches:[...s.branches??[],{...n,anchorNodeId:n.anchorNodeId??""}]}}})})),await Br()}async function uG(e,t){sn.setState(n=>({projects:n.projects.map(a=>{if(a.id!==e||!a.sourceSession)return a;const r=a.sourceSession,s=(r.chapters??[]).filter(d=>d.sessionId!==t),o=(r.branches??[]).filter(d=>d.sessionId!==t),u={...r,chapters:s.length?s:void 0,branches:o.length?o:void 0};return u.sessionId===t&&(u.sessionId="",u.runner="",u.importedCount=0,u.tailNodeId=""),!u.sessionId&&s.length===0&&o.length===0?{...a,sourceSession:void 0}:{...a,sourceSession:u}})})),await Br()}function my(e){const t=e.sourceSession;return t?[t.sessionId,...(t.chapters??[]).map(n=>n.sessionId),...(t.branches??[]).map(n=>n.sessionId)].filter(Boolean):[]}async function q7(e,t){sn.setState(n=>({projects:n.projects.map(a=>a.id===e?{...a,instantiatedFrom:{name:t,at:new Date().toISOString()}}:a)})),await Br()}const sn=G0(()=>({projects:[],activeId:null,switching:!1}));async function Br(){const{projects:e,activeId:t}=sn.getState();await Pr(fy,{projects:e,activeId:t})}let JE=null;function $7(){return JE??=(async()=>{let e=await Zo(fy);if(!e||e.projects.length===0){const t=await Zo(ZE),n=crypto.randomUUID(),a=Date.now();t&&await Pr(ks(n),t),e={projects:[{id:n,name:"My Canvas",createdAt:a,updatedAt:a}],activeId:n},await Pr(fy,e),t&&await Su(ZE)}e.projects.some(t=>t.id===e.activeId)||(e.activeId=e.projects[0].id),sn.setState({projects:e.projects,activeId:e.activeId}),se.persist.setOptions({name:ks(e.activeId)}),await se.persist.rehydrate()})().catch(async e=>{console.error("[thoughtdag] project boot failed:",e),We("error",Ne("toast.projectsLoadFailed")),se.persist.setOptions({name:ks("recovery")}),await se.persist.rehydrate()}),JE}let py=!1;async function dG(){for(const t of Ls.values())t.abort();const e=Date.now()+1e3;for(;Ls.size>0&&Date.now()<e;)await new Promise(t=>setTimeout(t,30));await new Promise(t=>setTimeout(t,0))}const W7=[];async function Wi(e){for(const r of W7)await r().catch(()=>{});const{activeId:t,switching:n,projects:a}=sn.getState();if(!(n||e===t||!a.some(r=>r.id===e))){sn.setState({switching:!0});try{await dG(),await qq(),xW(),py=!0,se.persist.setOptions({name:ks(e)}),await se.persist.rehydrate(),se.setState({selectedNodeId:null,selectedNodeIds:[]}),sn.setState(r=>({activeId:e,projects:r.projects.map(s=>s.id===e&&s.archived?{...s,archived:!1}:s)})),await Br()}finally{py=!1,sn.setState({switching:!1})}}}async function Ip(e="Untitled",t="chat"){const n=crypto.randomUUID(),a=Date.now();return sn.setState(r=>({projects:[...r.projects,{id:n,name:e,createdAt:a,updatedAt:a,kind:t}]})),await Br(),await Wi(n),n}async function Q2(e,t){sn.setState(n=>({projects:n.projects.map(a=>a.id===e?{...a,agentCwd:t}:a)})),await Br()}async function hG(e,t){sn.setState(n=>({projects:n.projects.map(a=>a.id===e?{...a,agentGuard:t}:a)})),await Br()}async function V7(e,t){sn.setState(n=>({projects:n.projects.map(a=>a.id===e?{...a,name:t}:a)})),await Br()}async function G7(e){const{projects:t,activeId:n}=sn.getState();if(e===n){const a=t.filter(r=>r.id!==e);a.length>0?await Wi(a[0].id):await Ip("My Canvas")}await Su(ks(e)),sn.setState(a=>({projects:a.projects.filter(r=>r.id!==e)})),await Br(),pt(()=>import("./canvas-record-PNNfw7b3.js"),[]).then(a=>a.removeCanvasRecord(e)).catch(()=>{})}async function Tu(e,t,n="chat",a){const r=Date.now();sn.setState(s=>({projects:[...s.projects,{id:e,name:t,createdAt:r,updatedAt:r,kind:n,...a}]})),await Br(),await Wi(e)}async function fG(e){const{name:t,nodes:n,edges:a}=iG(e),r=crypto.randomUUID();await Pr(ks(r),JSON.stringify({state:{nodes:n,edges:a},version:1})),await Tu(r,t,"paradigm")}let Rx=null;se.subscribe((e,t)=>{py||e.nodes===t.nodes&&e.edges===t.edges||(Rx&&clearTimeout(Rx),Rx=setTimeout(()=>{const{activeId:n}=sn.getState();if(!n)return;const a=[...new Set(se.getState().nodes.map(r=>r.data.importSource?.sessionId).filter(r=>!!r))];sn.setState(r=>({projects:r.projects.map(s=>s.id===n?{...s,updatedAt:Date.now(),provenanceSessions:a}:s)})),Br()},1e3))});const Na=Object.freeze(Object.defineProperty({__proto__:null,adoptImportedProject:Tu,beforeSwitchHooks:W7,bootProjects:$7,createBuiltinParadigm:fG,createProject:Ip,deleteProject:G7,markInstantiatedFrom:q7,patchLedgerEntry:lG,projectStorageKey:ks,registerLedgerEntry:cG,removeLedgerEntry:uG,renameProject:V7,setProjectAgentCwd:Q2,setProjectAgentGuard:hG,setProjectArchived:Vm,subscribedSessionIds:my,switchProject:Wi,updateSourceSession:oG,useProjects:sn},Symbol.toStringTag,{value:"Module"}));function Y7(e){if(Array.isArray(e)&&e.length>0){const n=e[0];if(n&&typeof n=="object"&&"mapping"in n)return"chatgpt";if(n&&typeof n=="object"&&"chat_messages"in n)return"claude"}const t=e;return t&&typeof t=="object"&&Array.isArray(t.nodes)&&Array.isArray(t.edges)?"thoughtdag":"unknown"}function Z2(e,t,n){return{id:En(),type:"thought",position:{x:0,y:0},dragHandle:".drag-handle",data:{question:e,response:t,responses:[t],responseIndex:0,isCollapsed:!0,isEditing:!1,isEditingResponse:!1,isLoading:!1,tokenCount:Math.ceil((e+t).length/4),highlights:[],highlightMode:"tag",attachments:[],excludedAttachmentIds:[],includedAttachmentIds:[],roleMode:"inherit",isRoot:n,isBranch:!1}}}function K7(e,t){return{id:`edge-${e}-${t}`,source:e,target:t,type:"smoothstep",sourceHandle:"continue",targetHandle:"top",style:{stroke:"#6B5CE7",strokeWidth:2},markerEnd:{type:"arrowclosed",color:"#6B5CE7",width:18,height:18},data:{}}}function X7(e){const t=e.message?.content?.parts;return Array.isArray(t)?t.filter(n=>typeof n=="string").join(`
301
+ 对上面每个候选,判断什么证据能将它排除(rule out)、什么能将它确认(rule in)。按可区分度排序:哪个检验最能把它们分开?`},{id:"syn",kind:"prompt",x:560,y:1360,title:"收敛",instruction:"综合上面的候选与区分性检验:先确认哪个解释、排除哪个,以及信息量最大的下一个实验是什么。"}],edges:[["q","mechA"],["q","mechB"],["q","conf"],["q","null"],["mechA","rev"],["mechB","rev"],["conf","rev"],["null","rev"],["rev","syn"]]}};function iG(e){const{name:t,steps:n,edges:a}=QE[e]??QE.en,r=n.map(o=>({id:`p-${o.id}`,type:"thought",position:{x:o.x,y:o.y},dragHandle:".drag-handle",data:{question:o.title,instruction:o.instruction,stepKind:o.kind,response:"",responses:[],responseIndex:-1,isCollapsed:!1,isEditing:!1,isEditingResponse:!1,isLoading:!1,tokenCount:0,highlights:[],highlightMode:"tag",attachments:[],excludedAttachmentIds:[],includedAttachmentIds:[],roleMode:"inherit",isRoot:o.id==="q",isBranch:!1}})),s=a.map(([o,u])=>({id:`p-e-${o}-${u}`,source:`p-${o}`,target:`p-${u}`,type:"smoothstep",sourceHandle:"continue",targetHandle:"top",style:{stroke:"#6B5CE7",strokeWidth:2},markerEnd:{type:"arrowclosed",color:"#6B5CE7",width:18,height:18},data:{}}));return{name:t,nodes:r,edges:s}}const fy="thoughtdag:projects",ZE="thoughtdag",ks=e=>`thoughtdag:project:${e}`;async function Vm(e,t){const{projects:n,activeId:a}=sn.getState();if(t&&e===a){const r=n.filter(s=>s.id!==e&&!s.archived).sort((s,o)=>o.updatedAt-s.updatedAt);r.length>0?await Wi(r[0].id):await Ip("My Canvas")}sn.setState(r=>({projects:r.projects.map(s=>s.id===e?{...s,archived:t}:s)})),await Br()}async function oG(e,t){sn.setState(n=>({projects:n.projects.map(a=>a.id===e&&a.sourceSession?{...a,sourceSession:{...a.sourceSession,...t}}:a)})),await Br()}async function lG(e,t,n){sn.setState(a=>({projects:a.projects.map(r=>{if(r.id!==e||!r.sourceSession)return r;const s=r.sourceSession;return s.sessionId===t?{...r,sourceSession:{...s,...n}}:{...r,sourceSession:{...s,chapters:s.chapters?.map(o=>o.sessionId===t?{...o,...n}:o),branches:s.branches?.map(o=>o.sessionId===t?{...o,...n}:o)}}})})),await Br()}async function cG(e,t,n){sn.setState(a=>({projects:a.projects.map(r=>{if(r.id!==e)return r;const s=r.sourceSession??{sessionId:"",runner:"",importedCount:0,tailNodeId:""};return t==="chapter"?{...r,sourceSession:{...s,chapters:[...s.chapters??[],{sessionId:n.sessionId,runner:n.runner,importedCount:n.importedCount,tailNodeId:n.tailNodeId}]}}:{...r,sourceSession:{...s,branches:[...s.branches??[],{...n,anchorNodeId:n.anchorNodeId??""}]}}})})),await Br()}async function uG(e,t){sn.setState(n=>({projects:n.projects.map(a=>{if(a.id!==e||!a.sourceSession)return a;const r=a.sourceSession,s=(r.chapters??[]).filter(d=>d.sessionId!==t),o=(r.branches??[]).filter(d=>d.sessionId!==t),u={...r,chapters:s.length?s:void 0,branches:o.length?o:void 0};return u.sessionId===t&&(u.sessionId="",u.runner="",u.importedCount=0,u.tailNodeId=""),!u.sessionId&&s.length===0&&o.length===0?{...a,sourceSession:void 0}:{...a,sourceSession:u}})})),await Br()}function my(e){const t=e.sourceSession;return t?[t.sessionId,...(t.chapters??[]).map(n=>n.sessionId),...(t.branches??[]).map(n=>n.sessionId)].filter(Boolean):[]}async function q7(e,t){sn.setState(n=>({projects:n.projects.map(a=>a.id===e?{...a,instantiatedFrom:{name:t,at:new Date().toISOString()}}:a)})),await Br()}const sn=G0(()=>({projects:[],activeId:null,switching:!1}));async function Br(){const{projects:e,activeId:t}=sn.getState();await Pr(fy,{projects:e,activeId:t})}let JE=null;function $7(){return JE??=(async()=>{let e=await Zo(fy);if(!e||e.projects.length===0){const t=await Zo(ZE),n=crypto.randomUUID(),a=Date.now();t&&await Pr(ks(n),t),e={projects:[{id:n,name:"My Canvas",createdAt:a,updatedAt:a}],activeId:n},await Pr(fy,e),t&&await Su(ZE)}e.projects.some(t=>t.id===e.activeId)||(e.activeId=e.projects[0].id),sn.setState({projects:e.projects,activeId:e.activeId}),se.persist.setOptions({name:ks(e.activeId)}),await se.persist.rehydrate()})().catch(async e=>{console.error("[thoughtdag] project boot failed:",e),We("error",Ne("toast.projectsLoadFailed")),se.persist.setOptions({name:ks("recovery")}),await se.persist.rehydrate()}),JE}let py=!1;async function dG(){for(const t of Ls.values())t.abort();const e=Date.now()+1e3;for(;Ls.size>0&&Date.now()<e;)await new Promise(t=>setTimeout(t,30));await new Promise(t=>setTimeout(t,0))}const W7=[];async function Wi(e){for(const r of W7)await r().catch(()=>{});const{activeId:t,switching:n,projects:a}=sn.getState();if(!(n||e===t||!a.some(r=>r.id===e))){sn.setState({switching:!0});try{await dG(),await qq(),xW(),py=!0,se.persist.setOptions({name:ks(e)}),await se.persist.rehydrate(),se.setState({selectedNodeId:null,selectedNodeIds:[]}),sn.setState(r=>({activeId:e,projects:r.projects.map(s=>s.id===e&&s.archived?{...s,archived:!1}:s)})),await Br()}finally{py=!1,sn.setState({switching:!1})}}}async function Ip(e="Untitled",t="chat"){const n=crypto.randomUUID(),a=Date.now();return sn.setState(r=>({projects:[...r.projects,{id:n,name:e,createdAt:a,updatedAt:a,kind:t}]})),await Br(),await Wi(n),n}async function Q2(e,t){sn.setState(n=>({projects:n.projects.map(a=>a.id===e?{...a,agentCwd:t}:a)})),await Br()}async function hG(e,t){sn.setState(n=>({projects:n.projects.map(a=>a.id===e?{...a,agentGuard:t}:a)})),await Br()}async function V7(e,t){sn.setState(n=>({projects:n.projects.map(a=>a.id===e?{...a,name:t}:a)})),await Br()}async function G7(e){const{projects:t,activeId:n}=sn.getState();if(e===n){const a=t.filter(r=>r.id!==e);a.length>0?await Wi(a[0].id):await Ip("My Canvas")}await Su(ks(e)),sn.setState(a=>({projects:a.projects.filter(r=>r.id!==e)})),await Br(),pt(()=>import("./canvas-record-BD0b1tl8.js"),[]).then(a=>a.removeCanvasRecord(e)).catch(()=>{})}async function Tu(e,t,n="chat",a){const r=Date.now();sn.setState(s=>({projects:[...s.projects,{id:e,name:t,createdAt:r,updatedAt:r,kind:n,...a}]})),await Br(),await Wi(e)}async function fG(e){const{name:t,nodes:n,edges:a}=iG(e),r=crypto.randomUUID();await Pr(ks(r),JSON.stringify({state:{nodes:n,edges:a},version:1})),await Tu(r,t,"paradigm")}let Rx=null;se.subscribe((e,t)=>{py||e.nodes===t.nodes&&e.edges===t.edges||(Rx&&clearTimeout(Rx),Rx=setTimeout(()=>{const{activeId:n}=sn.getState();if(!n)return;const a=[...new Set(se.getState().nodes.map(r=>r.data.importSource?.sessionId).filter(r=>!!r))];sn.setState(r=>({projects:r.projects.map(s=>s.id===n?{...s,updatedAt:Date.now(),provenanceSessions:a}:s)})),Br()},1e3))});const Na=Object.freeze(Object.defineProperty({__proto__:null,adoptImportedProject:Tu,beforeSwitchHooks:W7,bootProjects:$7,createBuiltinParadigm:fG,createProject:Ip,deleteProject:G7,markInstantiatedFrom:q7,patchLedgerEntry:lG,projectStorageKey:ks,registerLedgerEntry:cG,removeLedgerEntry:uG,renameProject:V7,setProjectAgentCwd:Q2,setProjectAgentGuard:hG,setProjectArchived:Vm,subscribedSessionIds:my,switchProject:Wi,updateSourceSession:oG,useProjects:sn},Symbol.toStringTag,{value:"Module"}));function Y7(e){if(Array.isArray(e)&&e.length>0){const n=e[0];if(n&&typeof n=="object"&&"mapping"in n)return"chatgpt";if(n&&typeof n=="object"&&"chat_messages"in n)return"claude"}const t=e;return t&&typeof t=="object"&&Array.isArray(t.nodes)&&Array.isArray(t.edges)?"thoughtdag":"unknown"}function Z2(e,t,n){return{id:En(),type:"thought",position:{x:0,y:0},dragHandle:".drag-handle",data:{question:e,response:t,responses:[t],responseIndex:0,isCollapsed:!0,isEditing:!1,isEditingResponse:!1,isLoading:!1,tokenCount:Math.ceil((e+t).length/4),highlights:[],highlightMode:"tag",attachments:[],excludedAttachmentIds:[],includedAttachmentIds:[],roleMode:"inherit",isRoot:n,isBranch:!1}}}function K7(e,t){return{id:`edge-${e}-${t}`,source:e,target:t,type:"smoothstep",sourceHandle:"continue",targetHandle:"top",style:{stroke:"#6B5CE7",strokeWidth:2},markerEnd:{type:"arrowclosed",color:"#6B5CE7",width:18,height:18},data:{}}}function X7(e){const t=e.message?.content?.parts;return Array.isArray(t)?t.filter(n=>typeof n=="string").join(`
302
302
  `).trim():""}function mG(e){const t=[],n=[],a=Object.values(e).filter(s=>!s.parent||!e[s.parent]),r=(s,o,u)=>{const d=e[s];if(!d)return;const h=d.message?.author?.role,m=X7(d);let p=o,x=u;if(h==="user"&&m)p=m;else if(h==="assistant"&&m){if(p!==null){const b=Z2(p,m,u===null);t.push(b),u&&n.push(K7(u,b.id)),x=b.id,p=null}else if(x){const b=t.find(y=>y.id===x);b&&(b.data.response+=`
303
303
 
304
304
  `+m,b.data.responses=[b.data.response])}}for(const b of d.children??[])r(b,p,x)};for(const s of a)r(s.id,null,null);return{nodes:yr(t,n),edges:n}}function Q7(e){return typeof e.text=="string"&&e.text.trim()?e.text.trim():Array.isArray(e.content)?e.content.filter(t=>t?.type==="text"&&typeof t.text=="string").map(t=>t.text).join(`
305
305
  `).trim():""}function pG(e){const t=[],n=[];let a=null,r=null;for(const s of e){const o=Q7(s);if(o){if(s.sender==="human")a=o;else if(s.sender==="assistant"){if(a!==null){const u=Z2(a,o,r===null);t.push(u),r&&n.push(K7(r,u.id)),r=u.id,a=null}else if(r){const u=t.find(d=>d.id===r);u&&(u.data.response+=`
306
306
 
307
- `+o,u.data.responses=[u.data.response])}}}}return{nodes:yr(t,n),edges:n}}function gG(e){const t=Y7(e),n=[];if(t==="chatgpt")for(const a of e){const r=a.mapping??{},s=Object.values(r).filter(o=>["user","assistant"].includes(o.message?.author?.role??"")&&X7(o)).length;s!==0&&n.push({title:a.title||"Untitled",messageCount:s,source:"chatgpt",build:()=>mG(r)})}else if(t==="claude")for(const a of e){const r=a.chat_messages??[],s=r.filter(o=>Q7(o)).length;s!==0&&n.push({title:a.name||"Untitled",messageCount:s,source:"claude",build:()=>pG(r)})}return n}function xG(e){return e.some(t=>t.data.stepKind==="human"&&!t.data.question||t.data.stepKind==="prompt"&&(t.data.isLoading||!t.data.response&&!t.data.generationFailed))}function bG(e){const t=e;return!!t&&typeof t=="object"&&t.kind==="thoughtdag-paradigm"&&Array.isArray(t.nodes)&&Array.isArray(t.edges)}const yG=()=>({question:"",response:"",responses:[],responseIndex:-1,isCollapsed:!1,isEditing:!1,isEditingResponse:!1,isLoading:!1,tokenCount:0,highlights:[],highlightMode:"tag",attachments:[],excludedAttachmentIds:[],includedAttachmentIds:[],roleMode:"inherit",isRoot:!1,isBranch:!1});function vG(e,t){const n=new Map,a=e.map(u=>{const d=En();n.set(u.id,d);const h=u.data.stepKind??"prompt",m=(u.data.instruction?.trim()||u.data.question||"").trim(),p={...yG(),question:m,rolePrompt:u.data.rolePrompt||void 0,roleMode:u.data.rolePrompt?"reset":"inherit"};return h==="human"&&(p.stepKind="human",p.question="",p.instruction=u.data.instruction?.trim()||void 0,p.rolePrompt=void 0,p.roleMode="inherit"),h==="prompt"&&(p.stepKind="prompt",p.webSearch=u.data.webSearch,p.scholarSearch=u.data.scholarSearch,p.autoRerun=u.data.autoRerun,p.autoRerunRounds=u.data.autoRerunRounds),(h==="note"||h==="file"||h==="link"||h==="frame")&&(p.stepKind=h,p.question=u.data.question||"",p.attachments=u.data.attachments??[],p.tokenCount=u.data.tokenCount??0,p.linkUrl=u.data.linkUrl,p.linkTitle=u.data.linkTitle,p.linkFetchedAt=u.data.linkFetchedAt,p.frameColor=u.data.frameColor),h==="review"&&(p.isEvaluator=!0,p.autoRerun=!0,p.autoRerunRounds=u.data.autoRerunRounds,p.rolePrompt||(p.roleMode="inherit")),h==="fanout"&&(p.stepKind="fanout",p.fanoutRoles=u.data.fanoutRoles),{id:d,type:"thought",position:{...u.position},width:u.width,height:u.height,zIndex:u.zIndex,dragHandle:".drag-handle",data:p}}),r=new Set(e.filter(u=>(u.data.stepKind??"step")==="review").map(u=>n.get(u.id))),s=t.filter(u=>n.has(u.source)&&n.has(u.target)).map(u=>{const d=n.get(u.source),h=n.get(u.target);return r.has(h)?{id:`watch-${d}-${h}`,source:d,target:h,sourceHandle:"branch",targetHandle:"left",type:"smoothstep",style:{stroke:at.watch,strokeWidth:2,strokeDasharray:"4 4"},animated:!0,markerEnd:{type:"arrowclosed",color:at.watch,width:18,height:18},data:{isCrossLink:!0,isWatch:!0,followsTip:!0}}:{id:`edge-${d}-${h}`,source:d,target:h,sourceHandle:"continue",targetHandle:"top",type:"smoothstep",style:{stroke:at.accent,strokeWidth:2},animated:!1,markerEnd:{type:"arrowclosed",color:at.accent,width:18,height:18},data:{}}}),o=new Set(s.map(u=>u.target));for(const u of a)o.has(u.id)||(u.data.isRoot=!0);return{nodes:yr(a,s),edges:s}}const Z7=1,J2=1;function Op(e){return e.replace(/[\\/:*?"<>|]/g,"_").trim()||"canvas"}function J0(e,t,n){const a=URL.createObjectURL(new Blob([t],{type:n}));Object.assign(document.createElement("a"),{href:a,download:e}).click(),URL.revokeObjectURL(a)}async function ev(e){await navigator.clipboard.writeText(e),We("success",Ne("toast.copied"))}function Vi(){const{projects:e,activeId:t}=sn.getState();return e.find(n=>n.id===t)?.name??"canvas"}async function gy(e){const{nodes:t}=se.getState(),{confirmIfSensitive:n}=await pt(async()=>{const{confirmIfSensitive:p}=await import("./sensitive-scan-DBS7362r.js");return{confirmIfSensitive:p}},[]);if(!await n(t))return;localStorage.setItem("thoughtdag.lastBackupAt",String(Date.now()));const{nodes:a,edges:r,events:s}=se.getState(),o=await T2(a),{projects:u,activeId:d}=sn.getState(),h=Vi(),m=JSON.stringify({version:Z7,name:h,projectId:d,exportedAt:new Date().toISOString(),instantiatedFrom:u.find(p=>p.id===d)?.instantiatedFrom,...e?.sharedReadonly?{sharedReadonly:!0}:{},nodes:el(o),edges:r,events:s});J0(`${Op(h)}.thoughtdag.json`,m,"application/json"),We("success",ve(Ne("toast.exported"),{name:h}))}function wG(){const{nodes:e,edges:t}=se.getState(),n=Vi(),a=JSON.stringify({kind:"thoughtdag-paradigm",version:1,name:n,nodes:el(e),edges:t});J0(`${Op(n)}.paradigm.json`,a,"application/json"),We("success",ve(Ne("toast.exported"),{name:n}))}async function kG(e){const t=await e.text();let n;try{n=JSON.parse(t)}catch{const{anyRunnerSessionConversation:r}=await pt(async()=>{const{anyRunnerSessionConversation:o}=await import("./index-CjJoJV4P.js");return{anyRunnerSessionConversation:o}},[]),s=await r(t);return s?{kind:"chat",conversations:[s]}:(We("error",Ne("toast.importFailedJson")),{kind:"error"})}if(bG(n)){const r=crypto.randomUUID(),s=await Tp(await J7(n.nodes));return await Pr(ks(r),JSON.stringify({state:{nodes:s,edges:n.edges},version:J2})),await Tu(r,n.name||"Paradigm","paradigm"),We("success",ve(Ne("toast.imported"),{name:n.name,n:n.nodes.length})),{kind:"own",ok:!0}}if(n?.format==="thoughtdag-manifest")return We("error",Ne("toast.importManifest"),9e3),{kind:"error"};const a=Y7(n);if(a==="chatgpt"||a==="claude"){const r=gG(n);return r.length===0?(We("error",Ne("toast.importNoConversations")),{kind:"error"}):{kind:"chat",conversations:r}}return{kind:"own",ok:await NG(e,n)}}function EG(e){return e.every(t=>{const n=t;return!!n&&typeof n.id=="string"&&!!n.position&&typeof n.position.x=="number"&&typeof n.position.y=="number"&&!!n.data&&typeof n.data=="object"})}async function SG(e){let t=null,n=0;for(const a of e){const{nodes:r,edges:s}=a.build();if(r.length===0)continue;if(t===null){const{useUiStore:u}=await pt(async()=>{const{useUiStore:d}=await Promise.resolve().then(()=>gu);return{useUiStore:d}},void 0);u.getState().setArrivalFocusNodeId(r[r.length-1].id)}const o=crypto.randomUUID();await Pr(ks(o),JSON.stringify({state:{nodes:el(r),edges:s},version:J2})),await Tu(o,a.title.slice(0,60)),t??=o,n+=r.length}t&&We("success",ve(Ne("toast.importedChats"),{n:e.length,m:n}))}async function J7(e){const t=await hr();if(!t||t.models.length===0)return e;const n=new Set,a=new Set,r=e.map(s=>{const o=s.data?.model;if(!o)return s;const u=B7(o,t.models);return u===o?s:u?(n.add(`${o} → ${u}`),{...s,data:{...s.data,model:u}}):(a.add(o),s)});return n.size&&We("info",ve(Ne("import.modelsRemapped"),{list:[...n].join(",")}),9e3),a.size&&We("info",ve(Ne("import.modelsMissing"),{list:[...a].join(",")}),1e4),r}async function NG(e,t){let n;try{n=t??JSON.parse(await e.text())}catch{return We("error",Ne("toast.importFailedJson")),!1}if(!Array.isArray(n.nodes)||!Array.isArray(n.edges))return We("error",Ne("toast.importFailedMissing")),!1;if(n.nodes.length>0&&!EG(n.nodes))return We("error",Ne("toast.importFailedShape"),9e3),!1;if(n.sharedReadonly&&!await oi({title:Ne("import.readonlyTitle"),message:Ne("import.readonlyConfirm"),confirmLabel:Ne("common.confirm")}))return!1;if(n.sourceSession?.sessionId){const{useProjects:o,switchProject:u}=await pt(async()=>{const{useProjects:h,switchProject:m}=await Promise.resolve().then(()=>Na);return{useProjects:h,switchProject:m}},void 0),d=o.getState().projects.find(h=>h.sourceSession?.sessionId===n.sourceSession.sessionId);if(d)return await u(d.id),We("info",ve(Ne("toast.importAlreadySubscribed"),{name:d.name}),9e3),!0}const a=crypto.randomUUID(),r=await Tp(await J7(n.nodes));await Pr(ks(a),JSON.stringify({state:{nodes:el(r),edges:n.edges,...Array.isArray(n.events)?{events:n.events}:{}},version:J2}));const s=n.name?.trim()||e.name.replace(/\.thoughtdag\.json$|\.json$/i,"")||"Imported canvas";return await Tu(a,s,"chat",{instantiatedFrom:n.instantiatedFrom,sourceSession:n.sourceSession}),We("success",ve(Ne("toast.imported"),{name:s,n:n.nodes.length})),!0}function TG(){const{events:e}=se.getState();if(e.length===0)return;const t=r=>`"${r.replace(/"/g,'""')}"`,a=["t,op,id,detail",...e.map(r=>[r.t,r.op,r.id??"",r.d?t(JSON.stringify(r.d)):""].join(","))].join(`
307
+ `+o,u.data.responses=[u.data.response])}}}}return{nodes:yr(t,n),edges:n}}function gG(e){const t=Y7(e),n=[];if(t==="chatgpt")for(const a of e){const r=a.mapping??{},s=Object.values(r).filter(o=>["user","assistant"].includes(o.message?.author?.role??"")&&X7(o)).length;s!==0&&n.push({title:a.title||"Untitled",messageCount:s,source:"chatgpt",build:()=>mG(r)})}else if(t==="claude")for(const a of e){const r=a.chat_messages??[],s=r.filter(o=>Q7(o)).length;s!==0&&n.push({title:a.name||"Untitled",messageCount:s,source:"claude",build:()=>pG(r)})}return n}function xG(e){return e.some(t=>t.data.stepKind==="human"&&!t.data.question||t.data.stepKind==="prompt"&&(t.data.isLoading||!t.data.response&&!t.data.generationFailed))}function bG(e){const t=e;return!!t&&typeof t=="object"&&t.kind==="thoughtdag-paradigm"&&Array.isArray(t.nodes)&&Array.isArray(t.edges)}const yG=()=>({question:"",response:"",responses:[],responseIndex:-1,isCollapsed:!1,isEditing:!1,isEditingResponse:!1,isLoading:!1,tokenCount:0,highlights:[],highlightMode:"tag",attachments:[],excludedAttachmentIds:[],includedAttachmentIds:[],roleMode:"inherit",isRoot:!1,isBranch:!1});function vG(e,t){const n=new Map,a=e.map(u=>{const d=En();n.set(u.id,d);const h=u.data.stepKind??"prompt",m=(u.data.instruction?.trim()||u.data.question||"").trim(),p={...yG(),question:m,rolePrompt:u.data.rolePrompt||void 0,roleMode:u.data.rolePrompt?"reset":"inherit"};return h==="human"&&(p.stepKind="human",p.question="",p.instruction=u.data.instruction?.trim()||void 0,p.rolePrompt=void 0,p.roleMode="inherit"),h==="prompt"&&(p.stepKind="prompt",p.webSearch=u.data.webSearch,p.scholarSearch=u.data.scholarSearch,p.autoRerun=u.data.autoRerun,p.autoRerunRounds=u.data.autoRerunRounds),(h==="note"||h==="file"||h==="link"||h==="frame")&&(p.stepKind=h,p.question=u.data.question||"",p.attachments=u.data.attachments??[],p.tokenCount=u.data.tokenCount??0,p.linkUrl=u.data.linkUrl,p.linkTitle=u.data.linkTitle,p.linkFetchedAt=u.data.linkFetchedAt,p.frameColor=u.data.frameColor),h==="review"&&(p.isEvaluator=!0,p.autoRerun=!0,p.autoRerunRounds=u.data.autoRerunRounds,p.rolePrompt||(p.roleMode="inherit")),h==="fanout"&&(p.stepKind="fanout",p.fanoutRoles=u.data.fanoutRoles),{id:d,type:"thought",position:{...u.position},width:u.width,height:u.height,zIndex:u.zIndex,dragHandle:".drag-handle",data:p}}),r=new Set(e.filter(u=>(u.data.stepKind??"step")==="review").map(u=>n.get(u.id))),s=t.filter(u=>n.has(u.source)&&n.has(u.target)).map(u=>{const d=n.get(u.source),h=n.get(u.target);return r.has(h)?{id:`watch-${d}-${h}`,source:d,target:h,sourceHandle:"branch",targetHandle:"left",type:"smoothstep",style:{stroke:at.watch,strokeWidth:2,strokeDasharray:"4 4"},animated:!0,markerEnd:{type:"arrowclosed",color:at.watch,width:18,height:18},data:{isCrossLink:!0,isWatch:!0,followsTip:!0}}:{id:`edge-${d}-${h}`,source:d,target:h,sourceHandle:"continue",targetHandle:"top",type:"smoothstep",style:{stroke:at.accent,strokeWidth:2},animated:!1,markerEnd:{type:"arrowclosed",color:at.accent,width:18,height:18},data:{}}}),o=new Set(s.map(u=>u.target));for(const u of a)o.has(u.id)||(u.data.isRoot=!0);return{nodes:yr(a,s),edges:s}}const Z7=1,J2=1;function Op(e){return e.replace(/[\\/:*?"<>|]/g,"_").trim()||"canvas"}function J0(e,t,n){const a=URL.createObjectURL(new Blob([t],{type:n}));Object.assign(document.createElement("a"),{href:a,download:e}).click(),URL.revokeObjectURL(a)}async function ev(e){await navigator.clipboard.writeText(e),We("success",Ne("toast.copied"))}function Vi(){const{projects:e,activeId:t}=sn.getState();return e.find(n=>n.id===t)?.name??"canvas"}async function gy(e){const{nodes:t}=se.getState(),{confirmIfSensitive:n}=await pt(async()=>{const{confirmIfSensitive:p}=await import("./sensitive-scan-ULbRwlLo.js");return{confirmIfSensitive:p}},[]);if(!await n(t))return;localStorage.setItem("thoughtdag.lastBackupAt",String(Date.now()));const{nodes:a,edges:r,events:s}=se.getState(),o=await T2(a),{projects:u,activeId:d}=sn.getState(),h=Vi(),m=JSON.stringify({version:Z7,name:h,projectId:d,exportedAt:new Date().toISOString(),instantiatedFrom:u.find(p=>p.id===d)?.instantiatedFrom,...e?.sharedReadonly?{sharedReadonly:!0}:{},nodes:el(o),edges:r,events:s});J0(`${Op(h)}.thoughtdag.json`,m,"application/json"),We("success",ve(Ne("toast.exported"),{name:h}))}function wG(){const{nodes:e,edges:t}=se.getState(),n=Vi(),a=JSON.stringify({kind:"thoughtdag-paradigm",version:1,name:n,nodes:el(e),edges:t});J0(`${Op(n)}.paradigm.json`,a,"application/json"),We("success",ve(Ne("toast.exported"),{name:n}))}async function kG(e){const t=await e.text();let n;try{n=JSON.parse(t)}catch{const{anyRunnerSessionConversation:r}=await pt(async()=>{const{anyRunnerSessionConversation:o}=await import("./index-C4lWKzPK.js");return{anyRunnerSessionConversation:o}},[]),s=await r(t);return s?{kind:"chat",conversations:[s]}:(We("error",Ne("toast.importFailedJson")),{kind:"error"})}if(bG(n)){const r=crypto.randomUUID(),s=await Tp(await J7(n.nodes));return await Pr(ks(r),JSON.stringify({state:{nodes:s,edges:n.edges},version:J2})),await Tu(r,n.name||"Paradigm","paradigm"),We("success",ve(Ne("toast.imported"),{name:n.name,n:n.nodes.length})),{kind:"own",ok:!0}}if(n?.format==="thoughtdag-manifest")return We("error",Ne("toast.importManifest"),9e3),{kind:"error"};const a=Y7(n);if(a==="chatgpt"||a==="claude"){const r=gG(n);return r.length===0?(We("error",Ne("toast.importNoConversations")),{kind:"error"}):{kind:"chat",conversations:r}}return{kind:"own",ok:await NG(e,n)}}function EG(e){return e.every(t=>{const n=t;return!!n&&typeof n.id=="string"&&!!n.position&&typeof n.position.x=="number"&&typeof n.position.y=="number"&&!!n.data&&typeof n.data=="object"})}async function SG(e){let t=null,n=0;for(const a of e){const{nodes:r,edges:s}=a.build();if(r.length===0)continue;if(t===null){const{useUiStore:u}=await pt(async()=>{const{useUiStore:d}=await Promise.resolve().then(()=>gu);return{useUiStore:d}},void 0);u.getState().setArrivalFocusNodeId(r[r.length-1].id)}const o=crypto.randomUUID();await Pr(ks(o),JSON.stringify({state:{nodes:el(r),edges:s},version:J2})),await Tu(o,a.title.slice(0,60)),t??=o,n+=r.length}t&&We("success",ve(Ne("toast.importedChats"),{n:e.length,m:n}))}async function J7(e){const t=await hr();if(!t||t.models.length===0)return e;const n=new Set,a=new Set,r=e.map(s=>{const o=s.data?.model;if(!o)return s;const u=B7(o,t.models);return u===o?s:u?(n.add(`${o} → ${u}`),{...s,data:{...s.data,model:u}}):(a.add(o),s)});return n.size&&We("info",ve(Ne("import.modelsRemapped"),{list:[...n].join(",")}),9e3),a.size&&We("info",ve(Ne("import.modelsMissing"),{list:[...a].join(",")}),1e4),r}async function NG(e,t){let n;try{n=t??JSON.parse(await e.text())}catch{return We("error",Ne("toast.importFailedJson")),!1}if(!Array.isArray(n.nodes)||!Array.isArray(n.edges))return We("error",Ne("toast.importFailedMissing")),!1;if(n.nodes.length>0&&!EG(n.nodes))return We("error",Ne("toast.importFailedShape"),9e3),!1;if(n.sharedReadonly&&!await oi({title:Ne("import.readonlyTitle"),message:Ne("import.readonlyConfirm"),confirmLabel:Ne("common.confirm")}))return!1;if(n.sourceSession?.sessionId){const{useProjects:o,switchProject:u}=await pt(async()=>{const{useProjects:h,switchProject:m}=await Promise.resolve().then(()=>Na);return{useProjects:h,switchProject:m}},void 0),d=o.getState().projects.find(h=>h.sourceSession?.sessionId===n.sourceSession.sessionId);if(d)return await u(d.id),We("info",ve(Ne("toast.importAlreadySubscribed"),{name:d.name}),9e3),!0}const a=crypto.randomUUID(),r=await Tp(await J7(n.nodes));await Pr(ks(a),JSON.stringify({state:{nodes:el(r),edges:n.edges,...Array.isArray(n.events)?{events:n.events}:{}},version:J2}));const s=n.name?.trim()||e.name.replace(/\.thoughtdag\.json$|\.json$/i,"")||"Imported canvas";return await Tu(a,s,"chat",{instantiatedFrom:n.instantiatedFrom,sourceSession:n.sourceSession}),We("success",ve(Ne("toast.imported"),{name:s,n:n.nodes.length})),!0}function TG(){const{events:e}=se.getState();if(e.length===0)return;const t=r=>`"${r.replace(/"/g,'""')}"`,a=["t,op,id,detail",...e.map(r=>[r.t,r.op,r.id??"",r.d?t(JSON.stringify(r.d)):""].join(","))].join(`
308
308
  `);J0(`${Op(Vi())}.events.csv`,a,"text/csv"),We("success",ve(Ne("toast.exported"),{name:Vi()}))}function AG(e){const t=[`## Q: ${e.data.question}`,""],n=e.data.attachments||[];return n.length>0&&t.push(`> ${Ne("export.attachmentsLabel")} ${n.map(a=>a.name).join(", ")}`,""),e.data.branchContext&&t.push(`> Exploring from: "${e.data.branchContext.slice(0,120)}"`,""),t.push(e.data.response||"_(no response)_",""),t.join(`
309
309
  `)}function eC(e,t){const n=e.reduce((a,r)=>a+_n(r.data.question+r.data.response),0);return[`# ${Vi()}`,"",`> ${t} · exported ${new Date().toISOString().slice(0,10)} · ${e.length} nodes · ~${n} tok`,"",e.map(AG).join(`
310
310
  ---
@@ -645,13 +645,13 @@ ${Ne("continue.genOpen")}
645
645
  ${u.join(`
646
646
  `)||"-"}`}]),h=b8(new Date().toISOString()).slice(0,10),m=Lle(n.position);gs("note",m,{question:`**📌 ${h} · ${Ne("continue.recapTag")}**
647
647
 
648
- ${d.trim()}`}),RM.current?.setCenter((n.position.x+m.x)/2+260,(n.position.y+m.y)/2+140,{zoom:.75,duration:600}),We("success",Ne("continue.noteDropped"))}catch(a){We("error",a instanceof Error?a.message:String(a))}}}function Ple({x:e,y:t,nodeId:n,onClose:a}){const r=Tt(),s=R.useRef(null),o=se(N=>N.nodes.find(S=>S.id===n));if(R.useEffect(()=>{const N=C=>{s.current?.contains(C.target)||a()},S=C=>{C.key==="Escape"&&a()};return window.addEventListener("mousedown",N),window.addEventListener("keydown",S),()=>{window.removeEventListener("mousedown",N),window.removeEventListener("keydown",S)}},[a]),!o)return null;const u=o.data.stepKind,d=!!u,h=!d&&!!o.data.response&&!o.data.isLoading,m=d?u==="note"||u==="link"?o.data.question:"":o.data.response,p="w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5",x="text-ink-faint shrink-0",b=200,y=380,w=Math.min(e,window.innerWidth-b-8),E=Math.min(t,window.innerHeight-y-8),v=N=>()=>{a(),N()};return dr.createPortal(l.jsxs("div",{ref:s,className:"fixed z-[70] bg-card border border-line rounded-xl shadow-lg py-1 w-[200px] animate-fade-in",style:{left:w,top:E},children:[!d&&l.jsxs("button",{className:p,onClick:v(()=>{se.getState().setSelectedNodeId(n),ce.getState().setPanelOpen(!0)}),children:[l.jsx(Wl,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.openPanel")]}),h&&l.jsxs("button",{className:p,onClick:v(()=>ce.getState().setResponseViewerNodeId(n)),children:[l.jsx(KA,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.readingView")]}),h&&l.jsxs("button",{className:p,onClick:v(()=>{se.getState().rerunNode(n)}),children:[l.jsx(cr,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.rerun")]}),h&&l.jsxs("button",{className:p,title:Ne("actions.regenBranchTitle"),onClick:v(()=>{se.getState().regenerate(n)}),children:[l.jsx(VA,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.regenBranch")]}),h&&(o.data.response?.length??0)>=400&&l.jsxs("button",{className:p,onClick:v(()=>{DM([n])}),"data-reselect-ladder":!0,children:[l.jsx(g2,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.reselectLadder")]}),h&&l.jsxs("button",{className:p,onClick:v(()=>{jM(n)}),children:[l.jsx(ui,{size:14,strokeWidth:1.75,className:x})," ",r("continue.summarize")]}),m&&l.jsxs("button",{className:p,onClick:v(()=>{navigator.clipboard.writeText(m).then(()=>We("success",Ne("ctx.copied")))}),children:[l.jsx(ro,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.copyContent")]}),l.jsxs("button",{className:p,onClick:v(()=>se.getState().duplicateNode(n)),children:[l.jsx(IF,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.duplicate")]}),l.jsxs("button",{className:p,onClick:v(()=>se.getState().setArchived([n],!o.data.archived)),children:[o.data.archived?l.jsx(UA,{size:14,strokeWidth:1.75,className:x}):l.jsx(rl,{size:14,strokeWidth:1.75,className:x}),o.data.archived?r("ctx.unarchive"):r("archive.label")]}),!d&&l.jsxs("button",{className:p,title:Ne("exp.copyForCliTitle"),onClick:v(()=>{pt(()=>import("./experiment-loop-PGHklznL.js"),[]).then(N=>N.takeToExperiment(n,"branch"))}),"data-take-to-experiment":!0,children:[l.jsx(DF,{size:14,strokeWidth:1.75,className:x})," ",r("exp.copyForCli")]}),l.jsx("div",{className:"h-px bg-line my-1"}),l.jsxs("button",{className:"w-full text-left px-3 py-2 text-xs text-red-600 hover:bg-red-50 transition-colors flex items-center gap-2.5",onClick:v(()=>{oi({title:Ne("confirm.deleteNodesTitle"),message:ve(Ne("confirm.deleteNodes"),{n:1}),confirmLabel:Ne("common.delete"),danger:!0}).then(N=>{N&&se.getState().deleteNode(n)})}),children:[l.jsx(rr,{size:14,strokeWidth:1.75,className:"shrink-0"})," ",r("common.delete")]})]}),document.body)}function zle({onLocate:e}){const t=ce(C=>C.highlightsOverviewOpen),n=ce(C=>C.setHighlightsOverviewOpen),a=se(C=>C.nodes),r=se(C=>C.removeHighlight),s=se(C=>C.weaveHighlights),o=Tt(),[u,d]=R.useState("time"),[h,m]=R.useState(new Set),[p,x]=R.useState(""),b=R.useMemo(()=>{const C=[];for(const O of a){const _=O.data.question.replace(/\s+/g," ").trim().slice(0,60)||"—";for(const A of O.data.highlights||[])C.push({hlId:A.id,text:A.text,at:A.at,nodeId:O.id,nodeTitle:_})}const I=u==="time"?[...C].sort((O,_)=>(_.at??"").localeCompare(O.at??"")):C;return I.map((O,_)=>({...O,showGroup:u==="node"&&(_===0||I[_-1].nodeTitle!==O.nodeTitle)}))},[a,u]);if(!t)return null;const y=C=>{const I=new Set(h);I.has(C)?I.delete(C):I.add(C),m(I)},w=()=>{n(!1),m(new Set),x("")},E=()=>{const C=[...h].filter(O=>b.some(_=>_.hlId===O));if(C.length===0)return;const I=[...new Set(b.filter(O=>C.includes(O.hlId)).map(O=>O.nodeId))];w(),s(I,p.trim()||void 0,C)},v=()=>{const C=b.map(I=>`- ${I.text}
648
+ ${d.trim()}`}),RM.current?.setCenter((n.position.x+m.x)/2+260,(n.position.y+m.y)/2+140,{zoom:.75,duration:600}),We("success",Ne("continue.noteDropped"))}catch(a){We("error",a instanceof Error?a.message:String(a))}}}function Ple({x:e,y:t,nodeId:n,onClose:a}){const r=Tt(),s=R.useRef(null),o=se(N=>N.nodes.find(S=>S.id===n));if(R.useEffect(()=>{const N=C=>{s.current?.contains(C.target)||a()},S=C=>{C.key==="Escape"&&a()};return window.addEventListener("mousedown",N),window.addEventListener("keydown",S),()=>{window.removeEventListener("mousedown",N),window.removeEventListener("keydown",S)}},[a]),!o)return null;const u=o.data.stepKind,d=!!u,h=!d&&!!o.data.response&&!o.data.isLoading,m=d?u==="note"||u==="link"?o.data.question:"":o.data.response,p="w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5",x="text-ink-faint shrink-0",b=200,y=380,w=Math.min(e,window.innerWidth-b-8),E=Math.min(t,window.innerHeight-y-8),v=N=>()=>{a(),N()};return dr.createPortal(l.jsxs("div",{ref:s,className:"fixed z-[70] bg-card border border-line rounded-xl shadow-lg py-1 w-[200px] animate-fade-in",style:{left:w,top:E},children:[!d&&l.jsxs("button",{className:p,onClick:v(()=>{se.getState().setSelectedNodeId(n),ce.getState().setPanelOpen(!0)}),children:[l.jsx(Wl,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.openPanel")]}),h&&l.jsxs("button",{className:p,onClick:v(()=>ce.getState().setResponseViewerNodeId(n)),children:[l.jsx(KA,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.readingView")]}),h&&l.jsxs("button",{className:p,onClick:v(()=>{se.getState().rerunNode(n)}),children:[l.jsx(cr,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.rerun")]}),h&&l.jsxs("button",{className:p,title:Ne("actions.regenBranchTitle"),onClick:v(()=>{se.getState().regenerate(n)}),children:[l.jsx(VA,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.regenBranch")]}),h&&(o.data.response?.length??0)>=400&&l.jsxs("button",{className:p,onClick:v(()=>{DM([n])}),"data-reselect-ladder":!0,children:[l.jsx(g2,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.reselectLadder")]}),h&&l.jsxs("button",{className:p,onClick:v(()=>{jM(n)}),children:[l.jsx(ui,{size:14,strokeWidth:1.75,className:x})," ",r("continue.summarize")]}),m&&l.jsxs("button",{className:p,onClick:v(()=>{navigator.clipboard.writeText(m).then(()=>We("success",Ne("ctx.copied")))}),children:[l.jsx(ro,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.copyContent")]}),l.jsxs("button",{className:p,onClick:v(()=>se.getState().duplicateNode(n)),children:[l.jsx(IF,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.duplicate")]}),l.jsxs("button",{className:p,onClick:v(()=>se.getState().setArchived([n],!o.data.archived)),children:[o.data.archived?l.jsx(UA,{size:14,strokeWidth:1.75,className:x}):l.jsx(rl,{size:14,strokeWidth:1.75,className:x}),o.data.archived?r("ctx.unarchive"):r("archive.label")]}),!d&&l.jsxs("button",{className:p,title:Ne("exp.copyForCliTitle"),onClick:v(()=>{pt(()=>import("./experiment-loop-D5X-o2kG.js"),[]).then(N=>N.takeToExperiment(n,"branch"))}),"data-take-to-experiment":!0,children:[l.jsx(DF,{size:14,strokeWidth:1.75,className:x})," ",r("exp.copyForCli")]}),l.jsx("div",{className:"h-px bg-line my-1"}),l.jsxs("button",{className:"w-full text-left px-3 py-2 text-xs text-red-600 hover:bg-red-50 transition-colors flex items-center gap-2.5",onClick:v(()=>{oi({title:Ne("confirm.deleteNodesTitle"),message:ve(Ne("confirm.deleteNodes"),{n:1}),confirmLabel:Ne("common.delete"),danger:!0}).then(N=>{N&&se.getState().deleteNode(n)})}),children:[l.jsx(rr,{size:14,strokeWidth:1.75,className:"shrink-0"})," ",r("common.delete")]})]}),document.body)}function zle({onLocate:e}){const t=ce(C=>C.highlightsOverviewOpen),n=ce(C=>C.setHighlightsOverviewOpen),a=se(C=>C.nodes),r=se(C=>C.removeHighlight),s=se(C=>C.weaveHighlights),o=Tt(),[u,d]=R.useState("time"),[h,m]=R.useState(new Set),[p,x]=R.useState(""),b=R.useMemo(()=>{if(!t)return[];const C=[];for(const O of a){const _=O.data.question.slice(0,200).replace(/\s+/g," ").trim().slice(0,60)||"—";for(const A of O.data.highlights||[])C.push({hlId:A.id,text:A.text,at:A.at,nodeId:O.id,nodeTitle:_})}const I=u==="time"?[...C].sort((O,_)=>(_.at??"").localeCompare(O.at??"")):C;return I.map((O,_)=>({...O,showGroup:u==="node"&&(_===0||I[_-1].nodeTitle!==O.nodeTitle)}))},[t,a,u]);if(!t)return null;const y=C=>{const I=new Set(h);I.has(C)?I.delete(C):I.add(C),m(I)},w=()=>{n(!1),m(new Set),x("")},E=()=>{const C=[...h].filter(O=>b.some(_=>_.hlId===O));if(C.length===0)return;const I=[...new Set(b.filter(O=>C.includes(O.hlId)).map(O=>O.nodeId))];w(),s(I,p.trim()||void 0,C)},v=()=>{const C=b.map(I=>`- ${I.text}
649
649
  — ${I.nodeTitle}${I.at?` · ${I.at.slice(0,10)}`:""}`);tv(`# ${o("hlov.title")}
650
650
 
651
651
  ${C.join(`
652
652
  `)}
653
- `)},N="shrink-0 text-2xs font-mono text-accent bg-accent/10 hover:bg-accent/20 rounded-full px-1.5 py-0.5 transition-colors",S=(C,I)=>l.jsx("button",{onClick:()=>d(C),className:`text-2xs px-2.5 py-1 rounded-full transition-colors ${u===C?"bg-accent/10 text-accent":"text-ink-faint hover:bg-wash"}`,children:I});return dr.createPortal(l.jsx("div",{className:"fixed inset-0 z-[60] bg-ink/30 backdrop-blur-sm flex items-center justify-center p-6",onClick:w,children:l.jsxs("div",{className:"bg-card rounded-2xl shadow-2xl border border-line w-[640px] max-h-[80vh] flex flex-col",onClick:C=>C.stopPropagation(),children:[l.jsxs("div",{className:"flex items-center gap-2 px-5 py-3 border-b border-line shrink-0",children:[l.jsx(x0,{size:15,strokeWidth:1.75,className:"text-amber-500"}),l.jsx("span",{className:"text-sm font-semibold text-ink",children:o("hlov.title")}),l.jsx("span",{className:"text-2xs text-ink-faint",children:ve(o("hlov.count"),{n:b.length})}),l.jsx("div",{className:"flex-1"}),S("time",o("hlov.byTime")),S("node",o("hlov.byNode")),l.jsx("button",{onClick:w,className:"text-ink-faint hover:text-ink w-7 h-7 rounded-lg hover:bg-wash flex items-center justify-center transition-colors ml-1",children:l.jsx(on,{size:15,strokeWidth:1.75})})]}),l.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-5 py-3",children:[b.length===0&&l.jsx("p",{className:"text-xs text-ink-faint italic py-2",children:o("hlov.empty")}),b.map(C=>l.jsxs("div",{children:[C.showGroup&&l.jsx("div",{className:"text-2xs text-ink-faint font-medium mt-3 mb-1 first:mt-0 truncate",children:C.nodeTitle}),l.jsxs("div",{className:"group flex items-start gap-2.5 py-1.5 border-b border-line/50 last:border-0",children:[l.jsx("input",{type:"checkbox",checked:h.has(C.hlId),onChange:()=>y(C.hlId),className:"mt-1 accent-amber-500 shrink-0"}),l.jsx("span",{className:"flex-1 text-sm text-ink leading-relaxed min-w-0",children:l.jsx("mark",{className:"bg-amber-100 text-amber-800 px-0.5 rounded",children:C.text})}),u==="time"&&l.jsxs("button",{className:N,onClick:()=>{w(),e(C.nodeId)},title:o("hlov.locateTitle"),children:[C.nodeTitle.slice(0,14),C.nodeTitle.length>14?"…":""]}),u==="node"&&l.jsx("button",{className:N,onClick:()=>{w(),e(C.nodeId)},title:o("hlov.locateTitle"),children:"↦"}),C.at&&l.jsx("span",{className:"shrink-0 text-2xs text-ink-faint font-mono mt-0.5",children:C.at.slice(5,10)}),l.jsx("button",{onClick:()=>r(C.nodeId,C.hlId),title:o("common.delete"),className:"text-ink-faint hover:text-red-500 w-5 h-5 rounded-full flex items-center justify-center transition-colors shrink-0 opacity-0 group-hover:opacity-100",children:l.jsx(rr,{size:12,strokeWidth:1.75})})]})]},C.hlId))]}),l.jsxs("div",{className:"px-5 py-3 border-t border-line shrink-0 space-y-2",children:[h.size>0&&l.jsxs("div",{className:"flex gap-1.5",children:[l.jsx("input",{type:"text",value:p,onChange:C=>x(C.target.value),onKeyDown:C=>{C.key==="Enter"&&!ar(C)&&E()},placeholder:o("toolbar.intentPlaceholder"),className:"flex-1 text-xs border border-amber-500/30 rounded-lg px-3 py-2 focus:outline-none focus:ring-1 focus:ring-amber-500 bg-amber-500/5"}),l.jsx("button",{onClick:E,className:"text-xs bg-amber-500 hover:bg-amber-400 text-white px-3 py-2 rounded-lg transition-colors shrink-0",children:ve(o("hlov.weavePicked"),{n:h.size})})]}),l.jsxs("div",{className:"flex items-center",children:[l.jsx("span",{className:"text-2xs text-ink-faint",children:h.size>0?ve(o("hlov.picked"),{n:h.size}):o("hlov.pickHint")}),l.jsx("div",{className:"flex-1"}),b.length>0&&l.jsxs("button",{onClick:v,className:"flex items-center gap-1.5 text-2xs text-ink-faint hover:text-ink-muted transition-colors",title:o("hlov.exportTitle"),children:[l.jsx(Ll,{size:12,strokeWidth:1.75})," ",o("hlov.export")]})]})]})]})}),document.body)}const Ble={pdf:zs,img:XF,txt:zs,note:ui,link:Xi};function Hle({onLocate:e}){const t=ce(x=>x.materialsOverviewOpen),n=ce(x=>x.setMaterialsOverviewOpen),a=se(x=>x.nodes),r=Tt(),[s,o]=R.useState("time"),u=R.useMemo(()=>{const x=[];for(const y of a){const w=y.data.stepKind;if(w==="note"||w==="link"){const v=w==="link"?y.data.linkTitle||y.data.linkUrl||"—":y.data.question.split(`
654
- `)[0].replace(/^#+\s*/,"").slice(0,60)||"—";x.push({key:y.id,name:v,icon:w,at:y.data.createdAt,nodeId:y.id,nodeTitle:v,canOpen:!0});continue}const E=y.data.question.replace(/\s+/g," ").trim().slice(0,60)||(w==="file"?r("glyph.file"):"—");for(const v of y.data.attachments||[]){const N=v.type==="application/pdf"?"pdf":v.type.startsWith("image/")?"img":"txt";x.push({key:v.id,name:v.name,icon:N,sizeKB:v.size/1024,at:v.addedAt,nodeId:y.id,nodeTitle:E,canOpen:N==="pdf"})}}const b=s==="time"?[...x].sort((y,w)=>(w.at??"").localeCompare(y.at??"")):x;return b.map((y,w)=>({...y,showGroup:s==="node"&&(w===0||b[w-1].nodeTitle!==y.nodeTitle)}))},[a,s,r]);if(!t)return null;const d=()=>n(!1),h=x=>{d(),ce.getState().setReaderNodeId(x)},m="shrink-0 text-2xs font-mono text-accent bg-accent/10 hover:bg-accent/20 rounded-full px-1.5 py-0.5 transition-colors",p=(x,b)=>l.jsx("button",{onClick:()=>o(x),className:`text-2xs px-2.5 py-1 rounded-full transition-colors ${s===x?"bg-accent/10 text-accent":"text-ink-faint hover:bg-wash"}`,children:b});return dr.createPortal(l.jsx("div",{className:"fixed inset-0 z-[60] bg-ink/30 backdrop-blur-sm flex items-center justify-center p-6",onClick:d,children:l.jsxs("div",{className:"bg-card rounded-2xl shadow-2xl border border-line w-[640px] max-h-[80vh] flex flex-col",onClick:x=>x.stopPropagation(),children:[l.jsxs("div",{className:"flex items-center gap-2 px-5 py-3 border-b border-line shrink-0",children:[l.jsx(Bs,{size:15,strokeWidth:1.75,className:"text-warm"}),l.jsx("span",{className:"text-sm font-semibold text-ink",children:r("matov.title")}),l.jsx("span",{className:"text-2xs text-ink-faint",children:ve(r("matov.count"),{n:u.length})}),l.jsx("div",{className:"flex-1"}),p("time",r("hlov.byTime")),p("node",r("hlov.byNode")),l.jsx("button",{onClick:d,className:"text-ink-faint hover:text-ink w-7 h-7 rounded-lg hover:bg-wash flex items-center justify-center transition-colors ml-1",children:l.jsx(on,{size:15,strokeWidth:1.75})})]}),l.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-5 py-3",children:[u.length===0&&l.jsx("p",{className:"text-xs text-ink-faint italic py-2",children:r("matov.empty")}),u.map(x=>{const b=Ble[x.icon];return l.jsxs("div",{children:[x.showGroup&&l.jsx("div",{className:"text-2xs text-ink-faint font-medium mt-3 mb-1 first:mt-0 truncate",children:x.nodeTitle}),l.jsxs("div",{className:"group flex items-center gap-2.5 py-1.5 border-b border-line/50 last:border-0",children:[l.jsx("span",{className:`w-7 h-7 rounded-lg flex items-center justify-center shrink-0 ${x.icon==="note"?"bg-amber-100 text-amber-600":x.icon==="link"?"bg-cyan-100 text-cyan-700":"bg-wash text-ink-muted"}`,children:l.jsx(b,{size:14,strokeWidth:1.75})}),l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsx("p",{className:"text-sm text-ink truncate",children:x.name}),l.jsxs("p",{className:"text-2xs text-ink-faint",children:[x.sizeKB!=null?`${x.sizeKB.toFixed(1)} KB`:r(`matov.kind.${x.icon}`),x.at?` · ${x.at.slice(0,10)}`:""]})]}),s==="time"&&l.jsxs("button",{className:m,onClick:()=>{d(),e(x.nodeId)},title:r("hlov.locateTitle"),children:[x.nodeTitle.slice(0,14),x.nodeTitle.length>14?"…":""]}),s==="node"&&l.jsx("button",{className:m,onClick:()=>{d(),e(x.nodeId)},title:r("hlov.locateTitle"),children:"↦"}),x.canOpen&&l.jsx("button",{onClick:()=>h(x.nodeId),title:r("attach.openReader"),className:"w-7 h-7 rounded-lg text-ink-faint hover:text-accent hover:bg-wash flex items-center justify-center transition-colors shrink-0",children:l.jsx(Wl,{size:14,strokeWidth:1.75})})]})]},x.key)})]})]})}),document.body)}function Fle(e){const t=e.data.stepKind;return t==="note"||t==="file"||t==="link"||t==="frame"?t:e.data.condensedFrom?.length?"distill":"qa"}function Ule(e,t){let n=0,a=e.indexOf(t);for(;a!==-1;)n+=1,a=e.indexOf(t,a+t.length);return n}function qle(e,t,n){const r=Math.max(0,t-40),s=Math.min(e.length,t+n+60),o=r>0?"…":"",u=s<e.length?"…":"";return{snippet:o+e.slice(r,s)+u,matchStart:o.length+(t-r)}}function $le(e,t){const n=t.trim().toLowerCase();if(!n)return[];const a=[];for(const r of e){const s=r.data;if(s.stepKind==="fanout")continue;const o=[s.question??"",s.response??"",...(s.highlights??[]).map(p=>p.text),s.linkTitle??"",...(s.attachments??[]).map(p=>p.name),s.summaries?.[s.responseIndex]??s.summary??""];let u=0,d=null;for(const p of o){if(!p)continue;const x=p.toLowerCase(),b=x.indexOf(n);b!==-1&&(u+=Ule(x,n),d||(d={text:p,at:b}))}if(!d)continue;const{snippet:h,matchStart:m}=qle(d.text,d.at,n.length);a.push({nodeId:r.id,kind:Fle(r),archived:!!s.archived,count:u,snippet:h,matchStart:m,matchLen:n.length})}return a.sort((r,s)=>Number(r.archived)-Number(s.archived)||s.count-r.count),a}const Wle={qa:XA,note:ui,file:zs,link:Xi,frame:Yb,distill:Sp},vb=50;function Vle({open:e,onClose:t,onLocate:n}){const a=Tt(),r=se(v=>v.nodes),s=ce(v=>v.setSearchHitIds),[o,u]=R.useState(""),[d,h]=R.useState(0),m=R.useRef(null),[p,x]=R.useState(e);p!==e&&(x(e),e&&(u(""),h(0))),R.useEffect(()=>{e&&setTimeout(()=>m.current?.focus(),50)},[e]);const[b,y]=R.useState("");R.useEffect(()=>{const v=setTimeout(()=>y(o),120);return()=>clearTimeout(v)},[o]);const w=R.useMemo(()=>e?$le(r,b):[],[e,r,b]);if(R.useEffect(()=>{if(!e||!b.trim()){s(null);return}s(new Set(w.map(v=>v.nodeId)))},[e,b,w,s]),R.useEffect(()=>()=>s(null),[s]),!e)return null;const E=v=>{n(v.nodeId);const N=b.trim().toLowerCase();setTimeout(()=>{const S=document.querySelector("[data-focus-panel]");if(!S||!N)return;const C=document.createTreeWalker(S,NodeFilter.SHOW_TEXT);let I;for(;I=C.nextNode();)if(I.textContent?.toLowerCase().includes(N)){const O=I.parentElement;O?.scrollIntoView({block:"center",behavior:"smooth"}),O?.animate([{backgroundColor:"rgba(107, 92, 231, 0.22)"},{backgroundColor:"transparent"}],{duration:1800,easing:"ease-out"});break}},500)};return l.jsx("div",{className:"absolute top-4 left-1/2 -translate-x-1/2 z-20 w-[460px]","data-canvas-search":!0,children:l.jsxs("div",{className:"bg-card border border-line rounded-xl shadow-xl overflow-hidden",children:[l.jsxs("div",{className:"flex items-center gap-2 px-4 py-2.5 transition-shadow focus-within:ring-1 focus-within:ring-accent/40",children:[l.jsx(y0,{size:15,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),l.jsx("input",{ref:m,type:"text",value:o,onChange:v=>{u(v.target.value),h(0)},onKeyDown:v=>{v.key==="Escape"&&(v.stopPropagation(),t()),v.key==="ArrowDown"&&(v.preventDefault(),h(N=>Math.min(N+1,w.length-1))),v.key==="ArrowUp"&&(v.preventDefault(),h(N=>Math.max(N-1,0))),v.key==="Enter"&&!ar(v)&&w[d]&&(v.preventDefault(),E(w[d]))},placeholder:a("search.placeholder"),className:"flex-1 bg-transparent text-sm text-ink placeholder-ink-faint focus:outline-none","data-search-input":!0}),o&&l.jsx("span",{className:"text-2xs text-ink-faint shrink-0",children:ve(a("search.count"),{n:w.length})}),l.jsx("button",{onClick:t,className:"text-ink-faint hover:text-ink transition-colors shrink-0",children:l.jsx(on,{size:14,strokeWidth:1.75})})]}),w.length>0&&l.jsxs("ul",{className:"border-t border-line/60 max-h-72 overflow-y-auto py-1",children:[w.slice(0,vb).map((v,N)=>{const S=Wle[v.kind],I=r.find(O=>O.id===v.nodeId)?.data.question||"—";return l.jsx("li",{children:l.jsxs("button",{onClick:()=>E(v),onMouseEnter:()=>h(N),className:`w-full text-left px-4 py-2 transition-colors ${N===d?"bg-accent/8":""} ${v.archived?"opacity-55":""}`,"data-search-hit-row":!0,children:[l.jsxs("p",{className:`text-xs font-medium truncate flex items-center gap-1.5 ${N===d?"text-accent":"text-ink"}`,children:[l.jsx(S,{size:12,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),l.jsx("span",{className:"truncate flex-1 min-w-0",children:I}),v.archived&&l.jsx(rl,{size:11,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),v.count>1&&l.jsxs("span",{className:"text-2xs text-ink-faint font-normal shrink-0",children:["×",v.count]})]}),l.jsxs("p",{className:"text-2xs text-ink-faint mt-0.5 break-all leading-relaxed",children:[v.snippet.slice(0,v.matchStart),l.jsx("mark",{className:"bg-accent/20 text-accent rounded-sm px-px",children:v.snippet.slice(v.matchStart,v.matchStart+v.matchLen)}),v.snippet.slice(v.matchStart+v.matchLen)]})]})},v.nodeId)}),w.length>vb&&l.jsx("li",{className:"px-4 py-2 text-2xs text-ink-faint",children:ve(a("search.more"),{n:w.length-vb})})]})]})})}const _l=e=>e.replace(/\s+/g," ").trim(),Is=(e,t)=>{const n=e.trim();if(n.length<=t)return n;const a=Math.round(t*.72);return`${n.slice(0,a)}
653
+ `)},N="shrink-0 text-2xs font-mono text-accent bg-accent/10 hover:bg-accent/20 rounded-full px-1.5 py-0.5 transition-colors",S=(C,I)=>l.jsx("button",{onClick:()=>d(C),className:`text-2xs px-2.5 py-1 rounded-full transition-colors ${u===C?"bg-accent/10 text-accent":"text-ink-faint hover:bg-wash"}`,children:I});return dr.createPortal(l.jsx("div",{className:"fixed inset-0 z-[60] bg-ink/30 backdrop-blur-sm flex items-center justify-center p-6",onClick:w,children:l.jsxs("div",{className:"bg-card rounded-2xl shadow-2xl border border-line w-[640px] max-h-[80vh] flex flex-col",onClick:C=>C.stopPropagation(),children:[l.jsxs("div",{className:"flex items-center gap-2 px-5 py-3 border-b border-line shrink-0",children:[l.jsx(x0,{size:15,strokeWidth:1.75,className:"text-amber-500"}),l.jsx("span",{className:"text-sm font-semibold text-ink",children:o("hlov.title")}),l.jsx("span",{className:"text-2xs text-ink-faint",children:ve(o("hlov.count"),{n:b.length})}),l.jsx("div",{className:"flex-1"}),S("time",o("hlov.byTime")),S("node",o("hlov.byNode")),l.jsx("button",{onClick:w,className:"text-ink-faint hover:text-ink w-7 h-7 rounded-lg hover:bg-wash flex items-center justify-center transition-colors ml-1",children:l.jsx(on,{size:15,strokeWidth:1.75})})]}),l.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-5 py-3",children:[b.length===0&&l.jsx("p",{className:"text-xs text-ink-faint italic py-2",children:o("hlov.empty")}),b.map(C=>l.jsxs("div",{children:[C.showGroup&&l.jsx("div",{className:"text-2xs text-ink-faint font-medium mt-3 mb-1 first:mt-0 truncate",children:C.nodeTitle}),l.jsxs("div",{className:"group flex items-start gap-2.5 py-1.5 border-b border-line/50 last:border-0",children:[l.jsx("input",{type:"checkbox",checked:h.has(C.hlId),onChange:()=>y(C.hlId),className:"mt-1 accent-amber-500 shrink-0"}),l.jsx("span",{className:"flex-1 text-sm text-ink leading-relaxed min-w-0",children:l.jsx("mark",{className:"bg-amber-100 text-amber-800 px-0.5 rounded",children:C.text})}),u==="time"&&l.jsxs("button",{className:N,onClick:()=>{w(),e(C.nodeId)},title:o("hlov.locateTitle"),children:[C.nodeTitle.slice(0,14),C.nodeTitle.length>14?"…":""]}),u==="node"&&l.jsx("button",{className:N,onClick:()=>{w(),e(C.nodeId)},title:o("hlov.locateTitle"),children:"↦"}),C.at&&l.jsx("span",{className:"shrink-0 text-2xs text-ink-faint font-mono mt-0.5",children:C.at.slice(5,10)}),l.jsx("button",{onClick:()=>r(C.nodeId,C.hlId),title:o("common.delete"),className:"text-ink-faint hover:text-red-500 w-5 h-5 rounded-full flex items-center justify-center transition-colors shrink-0 opacity-0 group-hover:opacity-100",children:l.jsx(rr,{size:12,strokeWidth:1.75})})]})]},C.hlId))]}),l.jsxs("div",{className:"px-5 py-3 border-t border-line shrink-0 space-y-2",children:[h.size>0&&l.jsxs("div",{className:"flex gap-1.5",children:[l.jsx("input",{type:"text",value:p,onChange:C=>x(C.target.value),onKeyDown:C=>{C.key==="Enter"&&!ar(C)&&E()},placeholder:o("toolbar.intentPlaceholder"),className:"flex-1 text-xs border border-amber-500/30 rounded-lg px-3 py-2 focus:outline-none focus:ring-1 focus:ring-amber-500 bg-amber-500/5"}),l.jsx("button",{onClick:E,className:"text-xs bg-amber-500 hover:bg-amber-400 text-white px-3 py-2 rounded-lg transition-colors shrink-0",children:ve(o("hlov.weavePicked"),{n:h.size})})]}),l.jsxs("div",{className:"flex items-center",children:[l.jsx("span",{className:"text-2xs text-ink-faint",children:h.size>0?ve(o("hlov.picked"),{n:h.size}):o("hlov.pickHint")}),l.jsx("div",{className:"flex-1"}),b.length>0&&l.jsxs("button",{onClick:v,className:"flex items-center gap-1.5 text-2xs text-ink-faint hover:text-ink-muted transition-colors",title:o("hlov.exportTitle"),children:[l.jsx(Ll,{size:12,strokeWidth:1.75})," ",o("hlov.export")]})]})]})]})}),document.body)}const Ble={pdf:zs,img:XF,txt:zs,note:ui,link:Xi};function Hle({onLocate:e}){const t=ce(x=>x.materialsOverviewOpen),n=ce(x=>x.setMaterialsOverviewOpen),a=se(x=>x.nodes),r=Tt(),[s,o]=R.useState("time"),u=R.useMemo(()=>{if(!t)return[];const x=[];for(const y of a){const w=y.data.stepKind;if(w==="note"||w==="link"){const v=w==="link"?y.data.linkTitle||y.data.linkUrl||"—":y.data.question.split(`
654
+ `)[0].replace(/^#+\s*/,"").slice(0,60)||"—";x.push({key:y.id,name:v,icon:w,at:y.data.createdAt,nodeId:y.id,nodeTitle:v,canOpen:!0});continue}const E=y.data.question.slice(0,200).replace(/\s+/g," ").trim().slice(0,60)||(w==="file"?r("glyph.file"):"—");for(const v of y.data.attachments||[]){const N=v.type==="application/pdf"?"pdf":v.type.startsWith("image/")?"img":"txt";x.push({key:v.id,name:v.name,icon:N,sizeKB:v.size/1024,at:v.addedAt,nodeId:y.id,nodeTitle:E,canOpen:N==="pdf"})}}const b=s==="time"?[...x].sort((y,w)=>(w.at??"").localeCompare(y.at??"")):x;return b.map((y,w)=>({...y,showGroup:s==="node"&&(w===0||b[w-1].nodeTitle!==y.nodeTitle)}))},[t,a,s,r]);if(!t)return null;const d=()=>n(!1),h=x=>{d(),ce.getState().setReaderNodeId(x)},m="shrink-0 text-2xs font-mono text-accent bg-accent/10 hover:bg-accent/20 rounded-full px-1.5 py-0.5 transition-colors",p=(x,b)=>l.jsx("button",{onClick:()=>o(x),className:`text-2xs px-2.5 py-1 rounded-full transition-colors ${s===x?"bg-accent/10 text-accent":"text-ink-faint hover:bg-wash"}`,children:b});return dr.createPortal(l.jsx("div",{className:"fixed inset-0 z-[60] bg-ink/30 backdrop-blur-sm flex items-center justify-center p-6",onClick:d,children:l.jsxs("div",{className:"bg-card rounded-2xl shadow-2xl border border-line w-[640px] max-h-[80vh] flex flex-col",onClick:x=>x.stopPropagation(),children:[l.jsxs("div",{className:"flex items-center gap-2 px-5 py-3 border-b border-line shrink-0",children:[l.jsx(Bs,{size:15,strokeWidth:1.75,className:"text-warm"}),l.jsx("span",{className:"text-sm font-semibold text-ink",children:r("matov.title")}),l.jsx("span",{className:"text-2xs text-ink-faint",children:ve(r("matov.count"),{n:u.length})}),l.jsx("div",{className:"flex-1"}),p("time",r("hlov.byTime")),p("node",r("hlov.byNode")),l.jsx("button",{onClick:d,className:"text-ink-faint hover:text-ink w-7 h-7 rounded-lg hover:bg-wash flex items-center justify-center transition-colors ml-1",children:l.jsx(on,{size:15,strokeWidth:1.75})})]}),l.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-5 py-3",children:[u.length===0&&l.jsx("p",{className:"text-xs text-ink-faint italic py-2",children:r("matov.empty")}),u.map(x=>{const b=Ble[x.icon];return l.jsxs("div",{children:[x.showGroup&&l.jsx("div",{className:"text-2xs text-ink-faint font-medium mt-3 mb-1 first:mt-0 truncate",children:x.nodeTitle}),l.jsxs("div",{className:"group flex items-center gap-2.5 py-1.5 border-b border-line/50 last:border-0",children:[l.jsx("span",{className:`w-7 h-7 rounded-lg flex items-center justify-center shrink-0 ${x.icon==="note"?"bg-amber-100 text-amber-600":x.icon==="link"?"bg-cyan-100 text-cyan-700":"bg-wash text-ink-muted"}`,children:l.jsx(b,{size:14,strokeWidth:1.75})}),l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsx("p",{className:"text-sm text-ink truncate",children:x.name}),l.jsxs("p",{className:"text-2xs text-ink-faint",children:[x.sizeKB!=null?`${x.sizeKB.toFixed(1)} KB`:r(`matov.kind.${x.icon}`),x.at?` · ${x.at.slice(0,10)}`:""]})]}),s==="time"&&l.jsxs("button",{className:m,onClick:()=>{d(),e(x.nodeId)},title:r("hlov.locateTitle"),children:[x.nodeTitle.slice(0,14),x.nodeTitle.length>14?"…":""]}),s==="node"&&l.jsx("button",{className:m,onClick:()=>{d(),e(x.nodeId)},title:r("hlov.locateTitle"),children:"↦"}),x.canOpen&&l.jsx("button",{onClick:()=>h(x.nodeId),title:r("attach.openReader"),className:"w-7 h-7 rounded-lg text-ink-faint hover:text-accent hover:bg-wash flex items-center justify-center transition-colors shrink-0",children:l.jsx(Wl,{size:14,strokeWidth:1.75})})]})]},x.key)})]})]})}),document.body)}function Fle(e){const t=e.data.stepKind;return t==="note"||t==="file"||t==="link"||t==="frame"?t:e.data.condensedFrom?.length?"distill":"qa"}function Ule(e,t){let n=0,a=e.indexOf(t);for(;a!==-1;)n+=1,a=e.indexOf(t,a+t.length);return n}function qle(e,t,n){const r=Math.max(0,t-40),s=Math.min(e.length,t+n+60),o=r>0?"…":"",u=s<e.length?"…":"";return{snippet:o+e.slice(r,s)+u,matchStart:o.length+(t-r)}}function $le(e,t){const n=t.trim().toLowerCase();if(!n)return[];const a=[];for(const r of e){const s=r.data;if(s.stepKind==="fanout")continue;const o=[s.question??"",s.response??"",...(s.highlights??[]).map(p=>p.text),s.linkTitle??"",...(s.attachments??[]).map(p=>p.name),s.summaries?.[s.responseIndex]??s.summary??""];let u=0,d=null;for(const p of o){if(!p)continue;const x=p.toLowerCase(),b=x.indexOf(n);b!==-1&&(u+=Ule(x,n),d||(d={text:p,at:b}))}if(!d)continue;const{snippet:h,matchStart:m}=qle(d.text,d.at,n.length);a.push({nodeId:r.id,kind:Fle(r),archived:!!s.archived,count:u,snippet:h,matchStart:m,matchLen:n.length})}return a.sort((r,s)=>Number(r.archived)-Number(s.archived)||s.count-r.count),a}const Wle={qa:XA,note:ui,file:zs,link:Xi,frame:Yb,distill:Sp},vb=50;function Vle({open:e,onClose:t,onLocate:n}){const a=Tt(),r=se(v=>v.nodes),s=ce(v=>v.setSearchHitIds),[o,u]=R.useState(""),[d,h]=R.useState(0),m=R.useRef(null),[p,x]=R.useState(e);p!==e&&(x(e),e&&(u(""),h(0))),R.useEffect(()=>{e&&setTimeout(()=>m.current?.focus(),50)},[e]);const[b,y]=R.useState("");R.useEffect(()=>{const v=setTimeout(()=>y(o),120);return()=>clearTimeout(v)},[o]);const w=R.useMemo(()=>e?$le(r,b):[],[e,r,b]);if(R.useEffect(()=>{if(!e||!b.trim()){s(null);return}s(new Set(w.map(v=>v.nodeId)))},[e,b,w,s]),R.useEffect(()=>()=>s(null),[s]),!e)return null;const E=v=>{n(v.nodeId);const N=b.trim().toLowerCase();setTimeout(()=>{const S=document.querySelector("[data-focus-panel]");if(!S||!N)return;const C=document.createTreeWalker(S,NodeFilter.SHOW_TEXT);let I;for(;I=C.nextNode();)if(I.textContent?.toLowerCase().includes(N)){const O=I.parentElement;O?.scrollIntoView({block:"center",behavior:"smooth"}),O?.animate([{backgroundColor:"rgba(107, 92, 231, 0.22)"},{backgroundColor:"transparent"}],{duration:1800,easing:"ease-out"});break}},500)};return l.jsx("div",{className:"absolute top-4 left-1/2 -translate-x-1/2 z-20 w-[460px]","data-canvas-search":!0,children:l.jsxs("div",{className:"bg-card border border-line rounded-xl shadow-xl overflow-hidden",children:[l.jsxs("div",{className:"flex items-center gap-2 px-4 py-2.5 transition-shadow focus-within:ring-1 focus-within:ring-accent/40",children:[l.jsx(y0,{size:15,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),l.jsx("input",{ref:m,type:"text",value:o,onChange:v=>{u(v.target.value),h(0)},onKeyDown:v=>{v.key==="Escape"&&(v.stopPropagation(),t()),v.key==="ArrowDown"&&(v.preventDefault(),h(N=>Math.min(N+1,w.length-1))),v.key==="ArrowUp"&&(v.preventDefault(),h(N=>Math.max(N-1,0))),v.key==="Enter"&&!ar(v)&&w[d]&&(v.preventDefault(),E(w[d]))},placeholder:a("search.placeholder"),className:"flex-1 bg-transparent text-sm text-ink placeholder-ink-faint focus:outline-none","data-search-input":!0}),o&&l.jsx("span",{className:"text-2xs text-ink-faint shrink-0",children:ve(a("search.count"),{n:w.length})}),l.jsx("button",{onClick:t,className:"text-ink-faint hover:text-ink transition-colors shrink-0",children:l.jsx(on,{size:14,strokeWidth:1.75})})]}),w.length>0&&l.jsxs("ul",{className:"border-t border-line/60 max-h-72 overflow-y-auto py-1",children:[w.slice(0,vb).map((v,N)=>{const S=Wle[v.kind],I=r.find(O=>O.id===v.nodeId)?.data.question||"—";return l.jsx("li",{children:l.jsxs("button",{onClick:()=>E(v),onMouseEnter:()=>h(N),className:`w-full text-left px-4 py-2 transition-colors ${N===d?"bg-accent/8":""} ${v.archived?"opacity-55":""}`,"data-search-hit-row":!0,children:[l.jsxs("p",{className:`text-xs font-medium truncate flex items-center gap-1.5 ${N===d?"text-accent":"text-ink"}`,children:[l.jsx(S,{size:12,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),l.jsx("span",{className:"truncate flex-1 min-w-0",children:I}),v.archived&&l.jsx(rl,{size:11,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),v.count>1&&l.jsxs("span",{className:"text-2xs text-ink-faint font-normal shrink-0",children:["×",v.count]})]}),l.jsxs("p",{className:"text-2xs text-ink-faint mt-0.5 break-all leading-relaxed",children:[v.snippet.slice(0,v.matchStart),l.jsx("mark",{className:"bg-accent/20 text-accent rounded-sm px-px",children:v.snippet.slice(v.matchStart,v.matchStart+v.matchLen)}),v.snippet.slice(v.matchStart+v.matchLen)]})]})},v.nodeId)}),w.length>vb&&l.jsx("li",{className:"px-4 py-2 text-2xs text-ink-faint",children:ve(a("search.more"),{n:w.length-vb})})]})]})})}const _l=e=>e.replace(/\s+/g," ").trim(),Is=(e,t)=>{const n=e.trim();if(n.length<=t)return n;const a=Math.round(t*.72);return`${n.slice(0,a)}
655
655
  …
656
656
  ${n.slice(n.length-(t-a))}`};function LM(e){const t=e.filter(r=>!r.data.archived&&r.data.stepKind!=="frame"),n=new Map,a=new Map;return t.forEach((r,s)=>{const o=`n${s+1}`;n.set(r.id,o),a.set(o,r.id)}),{live:t,byId:n,byAlias:a}}function j0(e,t){if(e.stepKind==="note")return`${t==="zh"?"便签":"note"}:${_l(Is(e.question??"",120))}`;if(e.stepKind==="file"||e.stepKind==="link"){const s=(e.attachments??[]).filter(o=>!o.name.startsWith("tool: ")).map(o=>o.name).join(", ");return`${t==="zh"?"材料":"material"}:${_l(s||e.linkUrl||e.question||"")}`}const n=e.summaryLadders?.[e.responseIndex??0]??void 0;if(n){const s=_l(Jo(n,0)),o=_l(Jo(n,1));if(s&&o&&o!==s)return`${s}:${o}`;if(s||o)return s||o}const a=Rm(e)||_l(Is(e.question??"",60)),r=Qi(e)||qm(e.response??"")[0]||"";return r?`${a}:${_l(Is(r,140))}`:a}function Gle(e,t,n,a){const r=e.filter(u=>a.has(u.id)),s=new Map;for(const u of t){const d=a.get(u.source),h=a.get(u.target);!d||!h||(s.has(u.target)||s.set(u.target,[]),s.get(u.target).push({alias:d,ref:!!u.data?.isCrossLink}))}const o=[];for(const u of r){const d=s.get(u.id)??[],h=d.length?`(${n==="zh"?"上游":"from"} ${d.map(m=>m.ref?`${m.alias}${n==="zh"?"·引用":"·ref"}`:m.alias).join(", ")})`:"";o.push(`[[${a.get(u.id)}]]${h} ${j0(u.data,n)}`)}return o.join(`
657
657
  `)}const Yle=`你在帮作者读懂一张 ThoughtDAG 画布。画布是一张有向图:节点是一轮问答、一张便签或一份材料,连线是上下文的流向(上游的内容进入下游的提问)。只根据下面给出的内容回答:画布大纲、当前关注的节点和它的脉络、相关材料。
@@ -681,11 +681,11 @@ ${I}`),x+=I.length)}}const y=[{role:"system",content:`${s==="zh"?Yle:Kle}
681
681
 
682
682
  ${m.join(`
683
683
 
684
- `)}`}];for(const w of r.filter(E=>!E.error).slice(-8))y.push({role:w.role,content:w.text});return y.push({role:"user",content:a}),{messages:y,context:h,byAlias:d,byId:u}}function PM(e,t){const n=[],a=/\[\[\s*(n\d+)\s*\]\]|\[\[\s*([^\]\n]{1,40})\s*\]\]/g;let r=0,s;for(;s=a.exec(e);){s.index>r&&n.push({kind:"text",text:e.slice(r,s.index)});const o=(s[1]??s[2]).trim(),u=t.get(o);n.push(u?{kind:"node",alias:o,id:u}:{kind:"unknown",alias:o}),r=s.index+s[0].length}return r<e.length&&n.push({kind:"text",text:e.slice(r)}),n}async function Qle(e,t,n,a,r,s,o){const{messages:u,context:d,byAlias:h}=Xle(e,t,n,a,r,s),m=new Date().toISOString();try{const p=await Ka(u,void 0,o),x=[...new Set(PM(p,h).flatMap(b=>b.kind==="node"?[b.id]:[]))];return{turn:{id:`${Date.now()}-a`,role:"assistant",text:p,at:m,focus:n,model:o,context:d,cites:x},byAlias:h}}catch(p){return{turn:{id:`${Date.now()}-a`,role:"assistant",text:"",at:m,focus:n,model:o,context:d,error:p instanceof Error?p.message:String(p)},byAlias:h}}}function EN(e,t,n,a,r="title"){const s=o=>o.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;");return PM(e,t).map(o=>{if(o.kind==="text")return o.text;if(o.kind==="unknown")return`<mark class="explore-mark" data-explore-target="" title="?">${s(o.alias)}?</mark>`;const u=n.find(m=>m.id===o.id),d=u?j0(u.data,a):o.alias,h=r==="alias"?o.alias:_l(Is(d.split(":")[0],40));return`<mark class="explore-mark" data-explore-target="${s(o.id)}" title="${s(r==="alias"?d:o.alias)}">${s(h)}</mark>`}).join("")}const zM=e=>`thoughtdag.canvasChat.${e}`,Zle=40,SN=e=>{try{const t=JSON.parse(localStorage.getItem(zM(e))??"[]");return Array.isArray(t)?t:[]}catch{return[]}},wb=(e,t)=>{try{localStorage.setItem(zM(e),JSON.stringify(t.slice(-Zle)))}catch{}};function Jle({open:e,onClose:t,onLocate:n}){const a=Tt(),r=Aa(W=>W.lang),s=sn(W=>W.activeId)??"default",o=se(W=>W.nodes),u=se(W=>W.edges),d=se(W=>W.selectedNodeId),h=ce(W=>W.selectedModel),[m,p]=R.useState(()=>SN(s)),[x,b]=R.useState(""),[y,w]=R.useState(!1),[E,v]=R.useState(!1),N=R.useRef(null);R.useEffect(()=>{p(SN(s))},[s]),R.useEffect(()=>{e&&N.current?.scrollTo({top:N.current.scrollHeight})},[e,m.length,y]),R.useEffect(()=>{e||ce.getState().setBeaconNodeId(null)},[e]),R.useEffect(()=>{v(!1)},[d]);const S=!E&&d&&o.some(W=>W.id===d&&!W.data.archived)?d:null,C=S?o.find(W=>W.id===S):void 0,{byAlias:I,byId:O}=R.useMemo(()=>LM(o),[o]),_=async()=>{const W=x.trim();if(!W||y)return;const X={id:En(),role:"user",text:W,at:new Date().toISOString(),focus:S},B=[...m,X];p(B),wb(s,B),b(""),w(!0);try{const{turn:$}=await Qle(o,u,S,W,m,r,h??void 0),Z=[...B,$];p(Z),wb(s,Z)}finally{w(!1)}},A=(W,X)=>{const B=se.getState(),$=(W.cites??[]).filter(ae=>B.nodes.some(ge=>ge.id===ae)),Z=W.focus&&B.nodes.find(ae=>ae.id===W.focus)||($.length?B.nodes.find(ae=>ae.id===$[$.length-1]):void 0),K=Z?B.nodes.filter(ae=>Math.abs(ae.position.x-Z.position.x)<400&&ae.position.y>Z.position.y):[],J=Z?{x:Z.position.x+(W.focus?0:560),y:W.focus?Math.max(Z.position.y+420,...K.map(ae=>ae.position.y+420)):Z.position.y}:{x:Math.max(0,...B.nodes.map(ae=>ae.position.x+560)),y:0},oe=Z2(X,EN(W.text,I,B.nodes,r),!W.focus);oe.position=J,oe.data={...oe.data,isCollapsed:!1,createdAt:W.at,lastGeneratedAt:W.at,generatedBy:[W.model??null],isBranch:!!W.focus},B.pushHistory();const me=[];W.focus&&B.nodes.some(ae=>ae.id===W.focus)&&me.push({id:`edge-${W.focus}-${oe.id}`,source:W.focus,target:oe.id,type:"smoothstep",sourceHandle:"continue",targetHandle:"top",style:{stroke:at.accent,strokeWidth:2},markerEnd:{type:"arrowclosed",color:at.accent,width:18,height:18},data:{}});const ye=new Date().toISOString();for(const ae of $){if(ae===W.focus)continue;const ge=B.nodes.find(Fe=>Fe.id===ae),Te=J.y>ge.position.y+60&&Math.abs(J.x-ge.position.x)<320;me.push({id:`crosslink-${ae}-${oe.id}`,source:ae,sourceHandle:Te?"continue":"branch",target:oe.id,targetHandle:Te?"top":"left",type:"smoothstep",style:{stroke:at.accent,strokeDasharray:"8 4",strokeWidth:2},animated:!0,data:{isCrossLink:!0,createdAt:ye}})}B.setNodes([...B.nodes,oe]),B.setEdges([...se.getState().edges,...me]);for(const ae of me)se.getState().logEvent("connect",ae.id);se.getState().logEvent("ask",oe.id,{chars:X.length}),We("success",ve(a("chat.dropped"),{n:$.length}),6e3),n(oe.id)};if(!e)return null;const H=W=>{for(let X=W-1;X>=0;X--)if(m[X].role==="user")return m[X].text;return""},G=(W,X,B)=>{const $=o.find(Z=>Z.id===W);return l.jsx("button",{type:"button",className:"cite-chip",title:$?j0($.data,r):X,onClick:()=>n(W),onMouseEnter:()=>Y(W),onMouseLeave:()=>Y(null),"data-cite":W,children:X},B)},D=W=>W.target.closest?.("mark[data-explore-target]")?.getAttribute("data-explore-target")||null,P=W=>{const X=D(W);X&&(W.stopPropagation(),n(X))},Y=W=>ce.getState().setBeaconNodeId(W),U=W=>Y(D(W)),z=()=>Y(null),L=W=>{b(W),window.setTimeout(()=>{const X=document.querySelector("[data-chat-input]");X?.focus(),X?.setSelectionRange(W.length,W.length)},0)},q=[{k:"Overview"},{k:"Locate"},{k:"Grounds"},{k:"Compare"},{k:"Progress"}];return l.jsxs("div",{className:"fixed bottom-4 right-4 z-[85] w-[440px] max-w-[calc(100vw-32px)] max-h-[72vh] flex flex-col rounded-2xl border border-line bg-card shadow-2xl","data-canvas-chat":!0,children:[l.jsxs("div",{className:"flex items-center gap-2 px-4 py-2.5 border-b border-line shrink-0",children:[l.jsx(Ol,{size:15,strokeWidth:1.75,className:"text-accent"}),l.jsx("span",{className:"text-sm font-semibold text-ink flex-1",children:a("chat.title")}),l.jsx("button",{type:"button",onClick:()=>{p([]),wb(s,[])},disabled:!m.length||y,className:"text-2xs text-ink-faint hover:text-ink disabled:opacity-40","data-chat-clear":!0,children:a("chat.clear")}),l.jsx("button",{type:"button",onClick:t,className:"text-ink-faint hover:text-ink w-7 h-7 rounded-full flex items-center justify-center hover:bg-wash",title:a("common.close"),children:l.jsx(on,{size:15,strokeWidth:1.75})})]}),l.jsxs("div",{ref:N,className:"flex-1 overflow-y-auto px-4 py-3 space-y-3 text-sm","data-chat-turns":!0,children:[!m.length&&l.jsxs("div",{className:"text-xs text-ink-muted leading-relaxed space-y-2","data-chat-empty":!0,children:[l.jsx("p",{children:a("chat.empty")}),l.jsxs("div",{className:"flex items-center gap-1 flex-wrap text-2xs",children:[l.jsx("span",{className:"text-ink-faint mr-0.5",children:a("chat.sug")}),q.map(({k:W})=>l.jsx("button",{type:"button",onClick:()=>L(a(`chat.sug${W}Q`)),title:a(`chat.sug${W}Q`),className:"px-2 py-0.5 rounded-full bg-wash text-ink-muted hover:text-accent hover:bg-accent/10 transition-colors","data-chat-suggest":W.toLowerCase(),children:a(`chat.sug${W}`)},W))]})]}),m.map((W,X)=>W.role==="user"?l.jsxs("div",{className:"flex flex-col items-end gap-1","data-chat-turn":"user",children:[l.jsx("div",{className:"max-w-[88%] bg-accent/10 text-ink rounded-2xl rounded-br-md px-3 py-2 whitespace-pre-wrap break-words",children:W.text}),W.focus&&O.has(W.focus)&&l.jsxs("span",{className:"text-2xs text-ink-faint",children:[a("chat.focus")," ",G(W.focus,O.get(W.focus),`${W.id}-f`)]})]},W.id):l.jsxs("div",{className:"flex flex-col items-start gap-1","data-chat-turn":"assistant",children:[W.error?l.jsx("div",{className:"max-w-[92%] text-xs text-red-500 bg-red-50 rounded-2xl rounded-bl-md px-3 py-2 break-words",children:W.error}):l.jsx("div",{className:"max-w-[92%] bg-wash text-ink rounded-2xl rounded-bl-md px-3 py-2 markdown-body text-sm leading-relaxed break-words",onClick:P,onMouseOver:U,onMouseOut:z,"data-chat-answer":!0,children:l.jsx(Ns,{children:EN(W.text,I,o,r,"alias")})}),!W.error&&l.jsxs("div",{className:"flex items-center gap-2 text-2xs text-ink-faint pl-1",children:[W.model&&l.jsx("span",{className:"font-mono",children:W.model.split("/").pop()}),l.jsx("button",{type:"button",onClick:()=>A(W,H(X)),className:"text-accent hover:underline","data-chat-drop":!0,children:a("chat.drop")})]})]},W.id)),y&&l.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-ink-faint",children:[l.jsx(tn,{size:12,className:"animate-spin"})," ",a("chat.thinking")]})]}),l.jsxs("div",{className:"border-t border-line px-3 py-2 shrink-0 space-y-1.5",children:[m.length>0&&l.jsx("div",{className:"flex items-center gap-1 flex-wrap text-2xs","data-chat-suggestions":!0,children:q.map(({k:W})=>l.jsx("button",{type:"button",onClick:()=>L(a(`chat.sug${W}Q`)),title:a(`chat.sug${W}Q`),className:"px-2 py-0.5 rounded-full bg-wash text-ink-muted hover:text-accent hover:bg-accent/10 transition-colors","data-chat-suggest":W.toLowerCase(),children:a(`chat.sug${W}`)},W))}),l.jsx("div",{className:"flex items-center gap-1.5 text-2xs text-ink-faint min-w-0","data-chat-focus":!0,children:C?l.jsxs(l.Fragment,{children:[l.jsx("span",{className:"shrink-0",children:a("chat.focus")}),l.jsx("button",{type:"button",onClick:()=>n(C.id),className:"text-accent truncate min-w-0 hover:underline",children:j0(C.data,r).split(":")[0]}),l.jsx("button",{type:"button",onClick:()=>v(!0),className:"shrink-0 w-5 h-5 rounded-full hover:bg-wash flex items-center justify-center",title:a("chat.focusAll"),children:l.jsx(on,{size:11})})]}):l.jsxs("span",{className:"truncate min-w-0",children:[l.jsx("span",{className:"text-ink-muted",children:a("chat.focusAll")})," · ",a("chat.focusAllHint")]})}),l.jsxs("div",{className:"flex items-end gap-1.5",children:[l.jsx("textarea",{value:x,onChange:W=>b(W.target.value),onKeyDown:W=>{W.key==="Enter"&&!W.shiftKey&&!ar(W)&&(W.preventDefault(),_()),W.key==="Escape"&&t()},placeholder:a("chat.placeholder"),rows:1,className:"flex-1 bg-wash text-sm text-ink rounded-lg px-3 py-1.5 focus:outline-none focus:ring-1 focus:ring-accent/40 resize-none placeholder-ink-faint max-h-[120px]",onInput:W=>{const X=W.currentTarget;X.style.height="auto",X.style.height=`${Math.min(120,X.scrollHeight)}px`},"data-chat-input":!0}),l.jsx("button",{type:"button",onClick:()=>{_()},disabled:!x.trim()||y,className:"w-8 h-8 rounded-lg bg-accent text-white flex items-center justify-center disabled:opacity-30 shrink-0",title:a("chat.send"),"data-chat-send":!0,children:l.jsx(Yo,{size:14,strokeWidth:1.75})})]})]})]})}const NN=new Set(["note","file","link"]),Ys=e=>{const t=(e?.data.question??"").replace(/\s+/g," ").trim();return t.length>24?`${t.slice(0,24)}…`:t||"(空)"};function kb(e,t,n){const a=new Set([e]),r=[e];for(;r.length;){const s=r.shift();for(const o of n.get(s)??[]){if(o===t)return!0;a.has(o)||(a.add(o),r.push(o))}}return!1}function Eb(e){const t=new Map;for(const n of e)t.has(n.source)||t.set(n.source,[]),t.get(n.source).push(n.target);return t}function TN(e,t){const n=[],a=new Map(e.map(A=>[A.id,A])),r=t.filter(A=>!A.data?.isCrossLink),s=t.filter(A=>A.data?.isCrossLink),o=Eb(r),u=Eb(t);for(const A of r){const H=Eb(r.filter(G=>G.id!==A.id));kb(A.source,A.target,H)&&n.push({tier:1,kind:"residual-edge",fixable:!0,params:{a:Ys(a.get(A.source)),b:Ys(a.get(A.target))},nodeIds:[A.target,A.source],edgeIds:[A.id]})}for(const A of s)kb(A.source,A.target,o)&&n.push({tier:1,kind:"shadow-reference",fixable:!0,params:{a:Ys(a.get(A.source)),b:Ys(a.get(A.target))},nodeIds:[A.target,A.source],edgeIds:[A.id]});const d=new Map;for(const A of r)d.has(A.source)||d.set(A.source,[]),d.get(A.source).push(A.target);const h=[];for(const A of d.values()){const H=A.filter(D=>a.get(D)?.data.stepKind==="prompt"),G=A.filter(D=>a.get(D)?.data.isBranch);H.length>=2&&h.push(H),G.length>=2&&h.push(G)}for(const A of h)for(const H of A)for(const G of A)if(H!==G&&kb(H,G,u)){const D=t.find(P=>P.source===H&&P.target===G);n.push({tier:1,kind:"blind-pool-breach",fixable:!!D,params:{a:Ys(a.get(G)),b:Ys(a.get(H))},nodeIds:[G,H],edgeIds:D?[D.id]:[]})}for(const A of h){const H=A.map(D=>new Set(t.filter(P=>P.target===D).map(P=>P.source))),G=new Set([...H[0]].filter(D=>H.every(P=>P.has(D))));A.forEach((D,P)=>{const Y=[...H[P]].filter(U=>!G.has(U)&&!A.includes(U));Y.length>0&&n.push({tier:1,kind:"pool-asymmetry",fixable:!1,params:{a:Ys(a.get(D)),n:Y.length},nodeIds:[D,...Y],edgeIds:[]})})}const m=e.filter(A=>!NN.has(A.data.stepKind??"")&&A.data.stepKind!=="frame"),p=new Map,x=new Map,b=A=>_n(A.data.question+A.data.response),y=new Map;for(const A of m)y.set(A.id,0);for(const A of r)y.has(A.target)&&y.has(A.source)&&y.set(A.target,(y.get(A.target)??0)+1);const w=m.filter(A=>(y.get(A.id)??0)===0).map(A=>A.id),E=[],v=new Map(y);for(;w.length;){const A=w.shift();E.push(A);for(const H of o.get(A)??[])v.has(H)&&(v.set(H,v.get(H)-1),v.get(H)===0&&w.push(H))}for(const A of E){const H=a.get(A),G=r.filter(Y=>Y.target===A&&p.has(Y.source)),D=G.length?Math.max(...G.map(Y=>p.get(Y.source)))+1:1,P=G.length?Math.max(...G.map(Y=>x.get(Y.source)))+b(H):b(H);p.set(A,D),x.set(A,P)}const N=m.filter(A=>!(o.get(A.id)??[]).length&&!A.data.archived),S=N.filter(A=>(p.get(A.id)??0)>=8||(x.get(A.id)??0)>=15e3).sort((A,H)=>(p.get(H.id)??0)-(p.get(A.id)??0)).slice(0,3);for(const A of S)n.push({tier:2,kind:"long-chain",fixable:!1,params:{a:Ys(A),d:p.get(A.id)??0,tok:x.get(A.id)??0},nodeIds:[A.id],edgeIds:[]});const C=N.filter(A=>A.data.response);C.length>=4&&n.push({tier:2,kind:"open-branches",fixable:!1,params:{n:C.length},nodeIds:C.map(A=>A.id),edgeIds:[]});for(const A of m){const H=r.filter(D=>D.target===A.id).length,G=(o.get(A.id)??[]).length;H>=2&&G>=1&&n.push({tier:2,kind:"collider-continuation",fixable:!1,params:{a:Ys(A),n:H},nodeIds:[A.id],edgeIds:[]})}const I=e.filter(A=>NN.has(A.data.stepKind??"")&&!t.some(H=>H.source===A.id));I.length>0&&n.push({tier:2,kind:"orphan-materials",fixable:!1,params:{n:I.length},nodeIds:I.map(A=>A.id),edgeIds:[]});const O=A=>{const H=new Set,G=[A];for(;G.length;)for(const D of o.get(G.shift())??[])H.has(D)||(H.add(D),G.push(D));return H.size},_=m.map(A=>({n:A,c:O(A.id)})).filter(({c:A})=>A>=5).sort((A,H)=>H.c-A.c).slice(0,3);for(const{n:A,c:H}of _)n.push({tier:2,kind:"load-bearing",fixable:!1,params:{a:Ys(A),n:H},nodeIds:[A.id],edgeIds:[]});return n.sort((A,H)=>A.tier-H.tier)}const ece={"residual-edge":"diag.residual","shadow-reference":"diag.shadow","blind-pool-breach":"diag.breach","pool-asymmetry":"diag.asym","long-chain":"diag.longChain","open-branches":"diag.openBranches","collider-continuation":"diag.collider","orphan-materials":"diag.orphans","load-bearing":"diag.loadBearing"};function tce({onLocate:e,openPing:t=0,showTrigger:n=!0}){const a=se(v=>v.deleteEdges),r=Tt(),[s,o]=R.useState(!1),[u,d]=R.useState([]),h=R.useRef(null),[m,p]=R.useState(t);R.useEffect(()=>{if(!s)return;const v=N=>{h.current?.contains(N.target)||o(!1)};return window.addEventListener("mousedown",v),()=>window.removeEventListener("mousedown",v)},[s]);const x=()=>{const{nodes:v,edges:N}=se.getState();d(TN(v,N)),o(!0)};t!==m&&(p(t),x());const b=v=>{a(v.edgeIds);const{nodes:N,edges:S}=se.getState();d(TN(N,S))},y=u.filter(v=>v.tier===1),w=u.filter(v=>v.tier===2),E=(v,N)=>l.jsxs("div",{className:"px-3 py-2 border-b border-line/50 last:border-0 flex items-start gap-2",children:[l.jsx("span",{className:`w-1.5 h-1.5 rounded-full mt-1.5 shrink-0 ${v.tier===1?"bg-red-400":"bg-amber-400"}`}),l.jsx("span",{className:"text-xs text-ink-muted leading-relaxed flex-1 min-w-0",children:ve(r(ece[v.kind]),v.params)}),l.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[v.nodeIds.length>0&&l.jsx("button",{onClick:()=>e(v.nodeIds[0]),title:r("diag.locate"),className:"w-6 h-6 rounded-md text-ink-faint hover:text-accent hover:bg-wash flex items-center justify-center transition-colors",children:l.jsx(Ud,{size:13,strokeWidth:1.75})}),v.fixable&&l.jsx("button",{onClick:()=>b(v),title:r("diag.fix"),className:"w-6 h-6 rounded-md text-ink-faint hover:text-red-500 hover:bg-red-50 flex items-center justify-center transition-colors",children:l.jsx(rr,{size:13,strokeWidth:1.75})})]})]},`${v.kind}-${N}`);return l.jsxs("div",{ref:h,className:"relative",children:[n&&l.jsx("button",{onClick:()=>s?o(!1):x(),className:`bg-card/90 backdrop-blur border rounded-lg w-8 h-8 flex items-center justify-center shadow-sm transition-colors ${s?"border-accent/40 text-accent":"border-line text-ink-faint hover:bg-wash"}`,title:r("toolbar.diagnose"),children:l.jsx(e8,{size:15,strokeWidth:1.75})}),s&&l.jsxs("div",{className:"absolute right-0 top-full mt-1.5 bg-card border border-line rounded-xl shadow-lg py-1 w-[340px] max-h-[420px] overflow-y-auto z-30 animate-fade-in",children:[l.jsxs("div",{className:"px-3 py-1.5 text-2xs font-semibold text-ink-muted border-b border-line",children:[r("diag.title"),l.jsx("span",{className:"text-ink-faint font-normal ml-2",children:u.length===0?"":ve(r("diag.summary"),{a:y.length,b:w.length})})]}),u.length===0&&l.jsx("p",{className:"px-3 py-3 text-xs text-ink-faint italic",children:r("diag.clean")}),y.length>0&&l.jsxs(l.Fragment,{children:[l.jsx("p",{className:"px-3 pt-2 pb-1 text-2xs font-semibold text-red-500",children:r("diag.tier1")}),y.map(E)]}),w.length>0&&l.jsxs(l.Fragment,{children:[l.jsx("p",{className:"px-3 pt-2 pb-1 text-2xs font-semibold text-amber-600",children:r("diag.tier2")}),w.map(E)]})]})]})}async function BM(e,t){const{default:n}=await pt(async()=>{const{default:s}=await import("./purify.es-Cz4mVeUR.js");return{default:s}},[]),a=n.sanitize(e,{WHOLE_DOCUMENT:!0,ADD_TAGS:["style"],FORBID_TAGS:["script","iframe","object","embed","form","base","meta",...t?.baseUrl?[]:["link"]]}),r=new DOMParser().parseFromString(a,"text/html");return t?.baseUrl&&nce(r,t.baseUrl),r}function nce(e,t){const n=a=>{try{const r=new URL(a,t);return/^https?:$/.test(r.protocol)?r.href:null}catch{return null}};e.querySelectorAll("link").forEach(a=>{const r=a.getAttribute("href"),s=r?n(r):null;(a.getAttribute("rel")??"").toLowerCase()!=="stylesheet"||!s?a.remove():a.setAttribute("href",s)});for(const[a,r]of[["img","src"],["source","src"],["video","poster"],["a","href"]])e.querySelectorAll(`${a}[${r}]`).forEach(s=>{const o=s.getAttribute(r),u=o?n(o):null;u?s.setAttribute(r,u):s.removeAttribute(r)});e.querySelectorAll("img[srcset], source[srcset]").forEach(a=>a.removeAttribute("srcset"))}async function ace(){const[{default:e},t]=await Promise.all([pt(()=>import("./turndown.browser.es-kLzRgxYD.js"),[]),pt(()=>import("./turndown-plugin-gfm.cjs-D0S5uwh5.js").then(a=>a.t),[])]),n=new e({headingStyle:"atx",codeBlockStyle:"fenced",hr:"---"});return n.use(t.gfm),n.remove(["style","script","noscript","title"]),n}function AN(e){return(e.textContent??"").trim().length>0||!!e.querySelector("img,svg,canvas,video")}function Kv(e){const t=Array.from(e.querySelectorAll(".reveal .slides > section"));if(t.length>=2){const s=[];for(const o of t){const u=Array.from(o.children).filter(d=>d.tagName==="SECTION");u.length>0?s.push(...u):s.push(o)}return s}const n=new Map;for(const s of Array.from(e.body?.querySelectorAll("[class]")??[])){const o=s.getAttribute("class")??"";if(!/(?:^|[\s_-])(?:slide|page)(?:[\s_-]|$)/i.test(o)||!AN(s))continue;const u=s.parentElement;if(!u)continue;const d=n.get(u)??[];d.push(s),n.set(u,d)}let a=null;for(const s of n.values())s.length>=2&&(!a||s.length>a.length)&&(a=s);if(a)return a;const r=Array.from(e.querySelectorAll("body > section")).filter(AN);return r.length>=3?r:null}async function rce(e,t){const n=await BM(e,t),a=await ace(),r=Kv(n);if(r)return{markdown:r.map((d,h)=>`<!-- tdag-page:${h+1} -->
684
+ `)}`}];for(const w of r.filter(E=>!E.error).slice(-8))y.push({role:w.role,content:w.text});return y.push({role:"user",content:a}),{messages:y,context:h,byAlias:d,byId:u}}function PM(e,t){const n=[],a=/\[\[\s*(n\d+)\s*\]\]|\[\[\s*([^\]\n]{1,40})\s*\]\]/g;let r=0,s;for(;s=a.exec(e);){s.index>r&&n.push({kind:"text",text:e.slice(r,s.index)});const o=(s[1]??s[2]).trim(),u=t.get(o);n.push(u?{kind:"node",alias:o,id:u}:{kind:"unknown",alias:o}),r=s.index+s[0].length}return r<e.length&&n.push({kind:"text",text:e.slice(r)}),n}async function Qle(e,t,n,a,r,s,o){const{messages:u,context:d,byAlias:h}=Xle(e,t,n,a,r,s),m=new Date().toISOString();try{const p=await Ka(u,void 0,o),x=[...new Set(PM(p,h).flatMap(b=>b.kind==="node"?[b.id]:[]))];return{turn:{id:`${Date.now()}-a`,role:"assistant",text:p,at:m,focus:n,model:o,context:d,cites:x},byAlias:h}}catch(p){return{turn:{id:`${Date.now()}-a`,role:"assistant",text:"",at:m,focus:n,model:o,context:d,error:p instanceof Error?p.message:String(p)},byAlias:h}}}function EN(e,t,n,a,r="title"){const s=o=>o.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;");return PM(e,t).map(o=>{if(o.kind==="text")return o.text;if(o.kind==="unknown")return`<mark class="explore-mark" data-explore-target="" title="?">${s(o.alias)}?</mark>`;const u=n.find(m=>m.id===o.id),d=u?j0(u.data,a):o.alias,h=r==="alias"?o.alias:_l(Is(d.split(":")[0],40));return`<mark class="explore-mark" data-explore-target="${s(o.id)}" title="${s(r==="alias"?d:o.alias)}">${s(h)}</mark>`}).join("")}const zM=e=>`thoughtdag.canvasChat.${e}`,Zle=40,SN=e=>{try{const t=JSON.parse(localStorage.getItem(zM(e))??"[]");return Array.isArray(t)?t:[]}catch{return[]}},wb=(e,t)=>{try{localStorage.setItem(zM(e),JSON.stringify(t.slice(-Zle)))}catch{}};function Jle({open:e,onClose:t,onLocate:n}){const a=Tt(),r=Aa(W=>W.lang),s=sn(W=>W.activeId)??"default",o=se(W=>W.nodes),u=se(W=>W.edges),d=se(W=>W.selectedNodeId),h=ce(W=>W.selectedModel),[m,p]=R.useState(()=>SN(s)),[x,b]=R.useState(""),[y,w]=R.useState(!1),[E,v]=R.useState(!1),N=R.useRef(null);R.useEffect(()=>{p(SN(s))},[s]),R.useEffect(()=>{e&&N.current?.scrollTo({top:N.current.scrollHeight})},[e,m.length,y]),R.useEffect(()=>{e||ce.getState().setBeaconNodeId(null)},[e]),R.useEffect(()=>{v(!1)},[d]);const S=!E&&d&&o.some(W=>W.id===d&&!W.data.archived)?d:null,C=S?o.find(W=>W.id===S):void 0,{byAlias:I,byId:O}=R.useMemo(()=>LM(o),[o]),_=async()=>{const W=x.trim();if(!W||y)return;const X={id:En(),role:"user",text:W,at:new Date().toISOString(),focus:S},B=[...m,X];p(B),wb(s,B),b(""),w(!0);try{const{turn:$}=await Qle(o,u,S,W,m,r,h??void 0),Z=[...B,$];p(Z),wb(s,Z)}finally{w(!1)}},A=(W,X)=>{const B=se.getState(),$=(W.cites??[]).filter(ae=>B.nodes.some(ge=>ge.id===ae)),Z=W.focus&&B.nodes.find(ae=>ae.id===W.focus)||($.length?B.nodes.find(ae=>ae.id===$[$.length-1]):void 0),K=Z?B.nodes.filter(ae=>Math.abs(ae.position.x-Z.position.x)<400&&ae.position.y>Z.position.y):[],J=Z?{x:Z.position.x+(W.focus?0:560),y:W.focus?Math.max(Z.position.y+420,...K.map(ae=>ae.position.y+420)):Z.position.y}:{x:Math.max(0,...B.nodes.map(ae=>ae.position.x+560)),y:0},oe=Z2(X,EN(W.text,I,B.nodes,r),!W.focus);oe.position=J,oe.data={...oe.data,isCollapsed:!1,createdAt:W.at,lastGeneratedAt:W.at,generatedBy:[W.model??null],isBranch:!!W.focus},B.pushHistory();const me=[];W.focus&&B.nodes.some(ae=>ae.id===W.focus)&&me.push({id:`edge-${W.focus}-${oe.id}`,source:W.focus,target:oe.id,type:"smoothstep",sourceHandle:"continue",targetHandle:"top",style:{stroke:at.accent,strokeWidth:2},markerEnd:{type:"arrowclosed",color:at.accent,width:18,height:18},data:{}});const ye=new Date().toISOString();for(const ae of $){if(ae===W.focus)continue;const ge=B.nodes.find(Fe=>Fe.id===ae),Te=J.y>ge.position.y+60&&Math.abs(J.x-ge.position.x)<320;me.push({id:`crosslink-${ae}-${oe.id}`,source:ae,sourceHandle:Te?"continue":"branch",target:oe.id,targetHandle:Te?"top":"left",type:"smoothstep",style:{stroke:at.accent,strokeDasharray:"8 4",strokeWidth:2},animated:!0,data:{isCrossLink:!0,createdAt:ye}})}B.setNodes([...B.nodes,oe]),B.setEdges([...se.getState().edges,...me]);for(const ae of me)se.getState().logEvent("connect",ae.id);se.getState().logEvent("ask",oe.id,{chars:X.length}),We("success",ve(a("chat.dropped"),{n:$.length}),6e3),n(oe.id)};if(!e)return null;const H=W=>{for(let X=W-1;X>=0;X--)if(m[X].role==="user")return m[X].text;return""},G=(W,X,B)=>{const $=o.find(Z=>Z.id===W);return l.jsx("button",{type:"button",className:"cite-chip",title:$?j0($.data,r):X,onClick:()=>n(W),onMouseEnter:()=>Y(W),onMouseLeave:()=>Y(null),"data-cite":W,children:X},B)},D=W=>W.target.closest?.("mark[data-explore-target]")?.getAttribute("data-explore-target")||null,P=W=>{const X=D(W);X&&(W.stopPropagation(),n(X))},Y=W=>ce.getState().setBeaconNodeId(W),U=W=>Y(D(W)),z=()=>Y(null),L=W=>{b(W),window.setTimeout(()=>{const X=document.querySelector("[data-chat-input]");X?.focus(),X?.setSelectionRange(W.length,W.length)},0)},q=[{k:"Overview"},{k:"Locate"},{k:"Grounds"},{k:"Compare"},{k:"Progress"}];return l.jsxs("div",{className:"fixed bottom-4 right-4 z-[85] w-[440px] max-w-[calc(100vw-32px)] max-h-[72vh] flex flex-col rounded-2xl border border-line bg-card shadow-2xl","data-canvas-chat":!0,children:[l.jsxs("div",{className:"flex items-center gap-2 px-4 py-2.5 border-b border-line shrink-0",children:[l.jsx(Ol,{size:15,strokeWidth:1.75,className:"text-accent"}),l.jsx("span",{className:"text-sm font-semibold text-ink flex-1",children:a("chat.title")}),l.jsx("button",{type:"button",onClick:()=>{p([]),wb(s,[])},disabled:!m.length||y,className:"text-2xs text-ink-faint hover:text-ink disabled:opacity-40","data-chat-clear":!0,children:a("chat.clear")}),l.jsx("button",{type:"button",onClick:t,className:"text-ink-faint hover:text-ink w-7 h-7 rounded-full flex items-center justify-center hover:bg-wash",title:a("common.close"),children:l.jsx(on,{size:15,strokeWidth:1.75})})]}),l.jsxs("div",{ref:N,className:"flex-1 overflow-y-auto px-4 py-3 space-y-3 text-sm","data-chat-turns":!0,children:[!m.length&&l.jsxs("div",{className:"text-xs text-ink-muted leading-relaxed space-y-2","data-chat-empty":!0,children:[l.jsx("p",{children:a("chat.empty")}),l.jsxs("div",{className:"flex items-center gap-1 flex-wrap text-2xs",children:[l.jsx("span",{className:"text-ink-faint mr-0.5",children:a("chat.sug")}),q.map(({k:W})=>l.jsx("button",{type:"button",onClick:()=>L(a(`chat.sug${W}Q`)),title:a(`chat.sug${W}Q`),className:"px-2 py-0.5 rounded-full bg-wash text-ink-muted hover:text-accent hover:bg-accent/10 transition-colors","data-chat-suggest":W.toLowerCase(),children:a(`chat.sug${W}`)},W))]})]}),m.map((W,X)=>W.role==="user"?l.jsxs("div",{className:"flex flex-col items-end gap-1","data-chat-turn":"user",children:[l.jsx("div",{className:"max-w-[88%] bg-accent/10 text-ink rounded-2xl rounded-br-md px-3 py-2 whitespace-pre-wrap break-words",children:W.text}),W.focus&&O.has(W.focus)&&l.jsxs("span",{className:"text-2xs text-ink-faint",children:[a("chat.focus")," ",G(W.focus,O.get(W.focus),`${W.id}-f`)]})]},W.id):l.jsxs("div",{className:"flex flex-col items-start gap-1","data-chat-turn":"assistant",children:[W.error?l.jsx("div",{className:"max-w-[92%] text-xs text-red-500 bg-red-50 rounded-2xl rounded-bl-md px-3 py-2 break-words",children:W.error}):l.jsx("div",{className:"max-w-[92%] bg-wash text-ink rounded-2xl rounded-bl-md px-3 py-2 markdown-body text-sm leading-relaxed break-words",onClick:P,onMouseOver:U,onMouseOut:z,"data-chat-answer":!0,children:l.jsx(Ns,{children:EN(W.text,I,o,r,"alias")})}),!W.error&&l.jsxs("div",{className:"flex items-center gap-2 text-2xs text-ink-faint pl-1",children:[W.model&&l.jsx("span",{className:"font-mono",children:W.model.split("/").pop()}),l.jsx("button",{type:"button",onClick:()=>A(W,H(X)),className:"text-accent hover:underline","data-chat-drop":!0,children:a("chat.drop")})]})]},W.id)),y&&l.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-ink-faint",children:[l.jsx(tn,{size:12,className:"animate-spin"})," ",a("chat.thinking")]})]}),l.jsxs("div",{className:"border-t border-line px-3 py-2 shrink-0 space-y-1.5",children:[m.length>0&&l.jsx("div",{className:"flex items-center gap-1 flex-wrap text-2xs","data-chat-suggestions":!0,children:q.map(({k:W})=>l.jsx("button",{type:"button",onClick:()=>L(a(`chat.sug${W}Q`)),title:a(`chat.sug${W}Q`),className:"px-2 py-0.5 rounded-full bg-wash text-ink-muted hover:text-accent hover:bg-accent/10 transition-colors","data-chat-suggest":W.toLowerCase(),children:a(`chat.sug${W}`)},W))}),l.jsx("div",{className:"flex items-center gap-1.5 text-2xs text-ink-faint min-w-0","data-chat-focus":!0,children:C?l.jsxs(l.Fragment,{children:[l.jsx("span",{className:"shrink-0",children:a("chat.focus")}),l.jsx("button",{type:"button",onClick:()=>n(C.id),className:"text-accent truncate min-w-0 hover:underline",children:j0(C.data,r).split(":")[0]}),l.jsx("button",{type:"button",onClick:()=>v(!0),className:"shrink-0 w-5 h-5 rounded-full hover:bg-wash flex items-center justify-center",title:a("chat.focusAll"),children:l.jsx(on,{size:11})})]}):l.jsxs("span",{className:"truncate min-w-0",children:[l.jsx("span",{className:"text-ink-muted",children:a("chat.focusAll")})," · ",a("chat.focusAllHint")]})}),l.jsxs("div",{className:"flex items-end gap-1.5",children:[l.jsx("textarea",{value:x,onChange:W=>b(W.target.value),onKeyDown:W=>{W.key==="Enter"&&!W.shiftKey&&!ar(W)&&(W.preventDefault(),_()),W.key==="Escape"&&t()},placeholder:a("chat.placeholder"),rows:1,className:"flex-1 bg-wash text-sm text-ink rounded-lg px-3 py-1.5 focus:outline-none focus:ring-1 focus:ring-accent/40 resize-none placeholder-ink-faint max-h-[120px]",onInput:W=>{const X=W.currentTarget;X.style.height="auto",X.style.height=`${Math.min(120,X.scrollHeight)}px`},"data-chat-input":!0}),l.jsx("button",{type:"button",onClick:()=>{_()},disabled:!x.trim()||y,className:"w-8 h-8 rounded-lg bg-accent text-white flex items-center justify-center disabled:opacity-30 shrink-0",title:a("chat.send"),"data-chat-send":!0,children:l.jsx(Yo,{size:14,strokeWidth:1.75})})]})]})]})}const NN=new Set(["note","file","link"]),Ys=e=>{const t=(e?.data.question??"").replace(/\s+/g," ").trim();return t.length>24?`${t.slice(0,24)}…`:t||"(空)"};function kb(e,t,n){const a=new Set([e]),r=[e];for(;r.length;){const s=r.shift();for(const o of n.get(s)??[]){if(o===t)return!0;a.has(o)||(a.add(o),r.push(o))}}return!1}function Eb(e){const t=new Map;for(const n of e)t.has(n.source)||t.set(n.source,[]),t.get(n.source).push(n.target);return t}function TN(e,t){const n=[],a=new Map(e.map(A=>[A.id,A])),r=t.filter(A=>!A.data?.isCrossLink),s=t.filter(A=>A.data?.isCrossLink),o=Eb(r),u=Eb(t);for(const A of r){const H=Eb(r.filter(G=>G.id!==A.id));kb(A.source,A.target,H)&&n.push({tier:1,kind:"residual-edge",fixable:!0,params:{a:Ys(a.get(A.source)),b:Ys(a.get(A.target))},nodeIds:[A.target,A.source],edgeIds:[A.id]})}for(const A of s)kb(A.source,A.target,o)&&n.push({tier:1,kind:"shadow-reference",fixable:!0,params:{a:Ys(a.get(A.source)),b:Ys(a.get(A.target))},nodeIds:[A.target,A.source],edgeIds:[A.id]});const d=new Map;for(const A of r)d.has(A.source)||d.set(A.source,[]),d.get(A.source).push(A.target);const h=[];for(const A of d.values()){const H=A.filter(D=>a.get(D)?.data.stepKind==="prompt"),G=A.filter(D=>a.get(D)?.data.isBranch);H.length>=2&&h.push(H),G.length>=2&&h.push(G)}for(const A of h)for(const H of A)for(const G of A)if(H!==G&&kb(H,G,u)){const D=t.find(P=>P.source===H&&P.target===G);n.push({tier:1,kind:"blind-pool-breach",fixable:!!D,params:{a:Ys(a.get(G)),b:Ys(a.get(H))},nodeIds:[G,H],edgeIds:D?[D.id]:[]})}for(const A of h){const H=A.map(D=>new Set(t.filter(P=>P.target===D).map(P=>P.source))),G=new Set([...H[0]].filter(D=>H.every(P=>P.has(D))));A.forEach((D,P)=>{const Y=[...H[P]].filter(U=>!G.has(U)&&!A.includes(U));Y.length>0&&n.push({tier:1,kind:"pool-asymmetry",fixable:!1,params:{a:Ys(a.get(D)),n:Y.length},nodeIds:[D,...Y],edgeIds:[]})})}const m=e.filter(A=>!NN.has(A.data.stepKind??"")&&A.data.stepKind!=="frame"),p=new Map,x=new Map,b=A=>_n(A.data.question+A.data.response),y=new Map;for(const A of m)y.set(A.id,0);for(const A of r)y.has(A.target)&&y.has(A.source)&&y.set(A.target,(y.get(A.target)??0)+1);const w=m.filter(A=>(y.get(A.id)??0)===0).map(A=>A.id),E=[],v=new Map(y);for(;w.length;){const A=w.shift();E.push(A);for(const H of o.get(A)??[])v.has(H)&&(v.set(H,v.get(H)-1),v.get(H)===0&&w.push(H))}for(const A of E){const H=a.get(A),G=r.filter(Y=>Y.target===A&&p.has(Y.source)),D=G.length?Math.max(...G.map(Y=>p.get(Y.source)))+1:1,P=G.length?Math.max(...G.map(Y=>x.get(Y.source)))+b(H):b(H);p.set(A,D),x.set(A,P)}const N=m.filter(A=>!(o.get(A.id)??[]).length&&!A.data.archived),S=N.filter(A=>(p.get(A.id)??0)>=8||(x.get(A.id)??0)>=15e3).sort((A,H)=>(p.get(H.id)??0)-(p.get(A.id)??0)).slice(0,3);for(const A of S)n.push({tier:2,kind:"long-chain",fixable:!1,params:{a:Ys(A),d:p.get(A.id)??0,tok:x.get(A.id)??0},nodeIds:[A.id],edgeIds:[]});const C=N.filter(A=>A.data.response);C.length>=4&&n.push({tier:2,kind:"open-branches",fixable:!1,params:{n:C.length},nodeIds:C.map(A=>A.id),edgeIds:[]});for(const A of m){const H=r.filter(D=>D.target===A.id).length,G=(o.get(A.id)??[]).length;H>=2&&G>=1&&n.push({tier:2,kind:"collider-continuation",fixable:!1,params:{a:Ys(A),n:H},nodeIds:[A.id],edgeIds:[]})}const I=e.filter(A=>NN.has(A.data.stepKind??"")&&!t.some(H=>H.source===A.id));I.length>0&&n.push({tier:2,kind:"orphan-materials",fixable:!1,params:{n:I.length},nodeIds:I.map(A=>A.id),edgeIds:[]});const O=A=>{const H=new Set,G=[A];for(;G.length;)for(const D of o.get(G.shift())??[])H.has(D)||(H.add(D),G.push(D));return H.size},_=m.map(A=>({n:A,c:O(A.id)})).filter(({c:A})=>A>=5).sort((A,H)=>H.c-A.c).slice(0,3);for(const{n:A,c:H}of _)n.push({tier:2,kind:"load-bearing",fixable:!1,params:{a:Ys(A),n:H},nodeIds:[A.id],edgeIds:[]});return n.sort((A,H)=>A.tier-H.tier)}const ece={"residual-edge":"diag.residual","shadow-reference":"diag.shadow","blind-pool-breach":"diag.breach","pool-asymmetry":"diag.asym","long-chain":"diag.longChain","open-branches":"diag.openBranches","collider-continuation":"diag.collider","orphan-materials":"diag.orphans","load-bearing":"diag.loadBearing"};function tce({onLocate:e,openPing:t=0,showTrigger:n=!0}){const a=se(v=>v.deleteEdges),r=Tt(),[s,o]=R.useState(!1),[u,d]=R.useState([]),h=R.useRef(null),[m,p]=R.useState(t);R.useEffect(()=>{if(!s)return;const v=N=>{h.current?.contains(N.target)||o(!1)};return window.addEventListener("mousedown",v),()=>window.removeEventListener("mousedown",v)},[s]);const x=()=>{const{nodes:v,edges:N}=se.getState();d(TN(v,N)),o(!0)};t!==m&&(p(t),x());const b=v=>{a(v.edgeIds);const{nodes:N,edges:S}=se.getState();d(TN(N,S))},y=u.filter(v=>v.tier===1),w=u.filter(v=>v.tier===2),E=(v,N)=>l.jsxs("div",{className:"px-3 py-2 border-b border-line/50 last:border-0 flex items-start gap-2",children:[l.jsx("span",{className:`w-1.5 h-1.5 rounded-full mt-1.5 shrink-0 ${v.tier===1?"bg-red-400":"bg-amber-400"}`}),l.jsx("span",{className:"text-xs text-ink-muted leading-relaxed flex-1 min-w-0",children:ve(r(ece[v.kind]),v.params)}),l.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[v.nodeIds.length>0&&l.jsx("button",{onClick:()=>e(v.nodeIds[0]),title:r("diag.locate"),className:"w-6 h-6 rounded-md text-ink-faint hover:text-accent hover:bg-wash flex items-center justify-center transition-colors",children:l.jsx(Ud,{size:13,strokeWidth:1.75})}),v.fixable&&l.jsx("button",{onClick:()=>b(v),title:r("diag.fix"),className:"w-6 h-6 rounded-md text-ink-faint hover:text-red-500 hover:bg-red-50 flex items-center justify-center transition-colors",children:l.jsx(rr,{size:13,strokeWidth:1.75})})]})]},`${v.kind}-${N}`);return l.jsxs("div",{ref:h,className:"relative",children:[n&&l.jsx("button",{onClick:()=>s?o(!1):x(),className:`bg-card/90 backdrop-blur border rounded-lg w-8 h-8 flex items-center justify-center shadow-sm transition-colors ${s?"border-accent/40 text-accent":"border-line text-ink-faint hover:bg-wash"}`,title:r("toolbar.diagnose"),children:l.jsx(e8,{size:15,strokeWidth:1.75})}),s&&l.jsxs("div",{className:"absolute right-0 top-full mt-1.5 bg-card border border-line rounded-xl shadow-lg py-1 w-[340px] max-h-[420px] overflow-y-auto z-30 animate-fade-in",children:[l.jsxs("div",{className:"px-3 py-1.5 text-2xs font-semibold text-ink-muted border-b border-line",children:[r("diag.title"),l.jsx("span",{className:"text-ink-faint font-normal ml-2",children:u.length===0?"":ve(r("diag.summary"),{a:y.length,b:w.length})})]}),u.length===0&&l.jsx("p",{className:"px-3 py-3 text-xs text-ink-faint italic",children:r("diag.clean")}),y.length>0&&l.jsxs(l.Fragment,{children:[l.jsx("p",{className:"px-3 pt-2 pb-1 text-2xs font-semibold text-red-500",children:r("diag.tier1")}),y.map(E)]}),w.length>0&&l.jsxs(l.Fragment,{children:[l.jsx("p",{className:"px-3 pt-2 pb-1 text-2xs font-semibold text-amber-600",children:r("diag.tier2")}),w.map(E)]})]})]})}async function BM(e,t){const{default:n}=await pt(async()=>{const{default:s}=await import("./purify.es-Cz4mVeUR.js");return{default:s}},[]),a=n.sanitize(e,{WHOLE_DOCUMENT:!0,ADD_TAGS:["style"],FORBID_TAGS:["script","iframe","object","embed","form","base","meta",...t?.baseUrl?[]:["link"]]}),r=new DOMParser().parseFromString(a,"text/html");return t?.baseUrl&&nce(r,t.baseUrl),r}function nce(e,t){const n=a=>{try{const r=new URL(a,t);return/^https?:$/.test(r.protocol)?r.href:null}catch{return null}};e.querySelectorAll("link").forEach(a=>{const r=a.getAttribute("href"),s=r?n(r):null;(a.getAttribute("rel")??"").toLowerCase()!=="stylesheet"||!s?a.remove():a.setAttribute("href",s)});for(const[a,r]of[["img","src"],["source","src"],["video","poster"],["a","href"]])e.querySelectorAll(`${a}[${r}]`).forEach(s=>{const o=s.getAttribute(r),u=o?n(o):null;u?s.setAttribute(r,u):s.removeAttribute(r)});e.querySelectorAll("img[srcset], source[srcset]").forEach(a=>a.removeAttribute("srcset"))}async function ace(){const[{default:e},t]=await Promise.all([pt(()=>import("./turndown.browser.es-kLzRgxYD.js"),[]),pt(()=>import("./turndown-plugin-gfm.cjs-DtPIPA4T.js").then(a=>a.t),[])]),n=new e({headingStyle:"atx",codeBlockStyle:"fenced",hr:"---"});return n.use(t.gfm),n.remove(["style","script","noscript","title"]),n}function AN(e){return(e.textContent??"").trim().length>0||!!e.querySelector("img,svg,canvas,video")}function Kv(e){const t=Array.from(e.querySelectorAll(".reveal .slides > section"));if(t.length>=2){const s=[];for(const o of t){const u=Array.from(o.children).filter(d=>d.tagName==="SECTION");u.length>0?s.push(...u):s.push(o)}return s}const n=new Map;for(const s of Array.from(e.body?.querySelectorAll("[class]")??[])){const o=s.getAttribute("class")??"";if(!/(?:^|[\s_-])(?:slide|page)(?:[\s_-]|$)/i.test(o)||!AN(s))continue;const u=s.parentElement;if(!u)continue;const d=n.get(u)??[];d.push(s),n.set(u,d)}let a=null;for(const s of n.values())s.length>=2&&(!a||s.length>a.length)&&(a=s);if(a)return a;const r=Array.from(e.querySelectorAll("body > section")).filter(AN);return r.length>=3?r:null}async function rce(e,t){const n=await BM(e,t),a=await ace(),r=Kv(n);if(r)return{markdown:r.map((d,h)=>`<!-- tdag-page:${h+1} -->
685
685
 
686
686
  ${a.turndown(d.cloneNode(!0).outerHTML).trim()}`).join(`
687
687
 
688
- `).trim(),numPages:r.length,title:n.title||void 0};let s=n.title||void 0,o=null;try{const{default:u}=await pt(async()=>{const{default:h}=await import("./index-BF3yHokv.js").then(m=>m.i);return{default:h}},[]),d=new u(n.cloneNode(!0)).parse();d?.content&&d.content.replace(/<[^>]+>/g," ").trim().length>40&&(o=d.content,d.title&&(s=d.title))}catch{}if(o==null&&n.body){const u=n.body.cloneNode(!0);u.querySelectorAll("script,style,noscript,nav,header,footer,aside").forEach(d=>d.remove()),o=u.innerHTML}return{markdown:o?a.turndown(o).trim():"",title:s}}const sce=[":root{color-scheme:light}","html,body{margin:0;padding:0;overflow-x:hidden}","[data-tdag-shell]{position:static !important;transform:none !important;width:auto !important;height:auto !important;min-height:0 !important;max-height:none !important;overflow:visible !important;display:block !important;margin:0 !important;padding:0 !important}","[data-tdag-slide]{display:block !important;visibility:visible !important;opacity:1 !important;position:relative !important;inset:auto !important;transform:none !important;margin:0 auto !important}"].join(`
688
+ `).trim(),numPages:r.length,title:n.title||void 0};let s=n.title||void 0,o=null;try{const{default:u}=await pt(async()=>{const{default:h}=await import("./index--sniMyQq.js").then(m=>m.i);return{default:h}},[]),d=new u(n.cloneNode(!0)).parse();d?.content&&d.content.replace(/<[^>]+>/g," ").trim().length>40&&(o=d.content,d.title&&(s=d.title))}catch{}if(o==null&&n.body){const u=n.body.cloneNode(!0);u.querySelectorAll("script,style,noscript,nav,header,footer,aside").forEach(d=>d.remove()),o=u.innerHTML}return{markdown:o?a.turndown(o).trim():"",title:s}}const sce=[":root{color-scheme:light}","html,body{margin:0;padding:0;overflow-x:hidden}","[data-tdag-shell]{position:static !important;transform:none !important;width:auto !important;height:auto !important;min-height:0 !important;max-height:none !important;overflow:visible !important;display:block !important;margin:0 !important;padding:0 !important}","[data-tdag-slide]{display:block !important;visibility:visible !important;opacity:1 !important;position:relative !important;inset:auto !important;transform:none !important;margin:0 auto !important}"].join(`
689
689
  `);function $y(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;")}function ice(e,t){const n=e.tagName.toLowerCase(),a=["class","id","style"].map(r=>{const s=e.getAttribute(r);return s?` ${r}="${$y(s)}"`:""}).join("");return`<${n}${a} data-tdag-shell>${t}</${n}>`}function CN(e,t,n,a){const r=n?` class="${$y(n)}"`:"",s=a?` style="${$y(a)}"`:"";return`<!doctype html><html><head><meta charset="utf-8">${e}<style>${sce}</style></head><body${r}${s}>${t}</body></html>`}async function HM(e,t){const n=await BM(e,t),a=Array.from(n.querySelectorAll('style, link[rel="stylesheet" i]')).map(u=>u.outerHTML).join(`
690
690
  `),r=n.body?.getAttribute("class"),s=n.body?.getAttribute("style"),o=Kv(n);return o?o.map((u,d)=>{const h=u.cloneNode(!0);h.setAttribute("data-tdag-slide","");let m=h.outerHTML;for(let p=u.parentElement;p&&p!==n.body&&p.tagName!=="HTML";p=p.parentElement)m=ice(p,m);return{page:d+1,srcdoc:CN(a,m,r,s)}}):[{page:null,srcdoc:CN(a,n.body?.innerHTML??"",r,s)}]}const FM=Object.freeze(Object.defineProperty({__proto__:null,buildReaderPages:HM,detectSlides:Kv,extractHtmlMaterial:rce},Symbol.toStringTag,{value:"Module"}));function _N({att:e,onSelect:t,clipMode:n,onClipped:a,baseUrl:r}){const s=Tt(),[o,u]=R.useState(null),[d,h]=R.useState(!1);return R.useEffect(()=>{let m=!1;return HM(e.content,r?{baseUrl:r}:void 0).then(p=>{m||u(p)}).catch(()=>{m||h(!0)}),()=>{m=!0}},[]),d?l.jsx("p",{className:"text-sm text-ink-faint italic py-10 text-center",children:s("reader.htmlNoText")}):o?l.jsx("div",{className:"flex flex-col items-center py-6 px-4",children:o.map(m=>l.jsxs("div",{"data-page":m.page??void 0,className:"w-full max-w-[860px]",children:[m.page!=null&&l.jsxs("div",{className:"text-2xs text-ink-faint font-mono text-center select-none pt-4 pb-2",children:["— p.",m.page," —"]}),l.jsx(oce,{srcdoc:m.srcdoc,page:m.page,onSelect:t,clipMode:n,onClipped:a,clipFailedText:s("reader.clipFailed")})]},m.page??0))}):l.jsxs("div",{className:"flex items-center justify-center gap-2 h-full min-h-[200px] text-sm text-ink-muted",children:[l.jsx(tn,{size:16,strokeWidth:1.75,className:"animate-spin text-accent"})," ",s("reader.loading")]})}function oce({srcdoc:e,page:t,onSelect:n,clipMode:a,onClipped:r,clipFailedText:s}){const o=R.useRef(null),u=R.useRef(null),[d,h]=R.useState(120),[m,p]=R.useState(null),[x,b]=R.useState(!1),y=()=>{const v=u.current,N=v?.contentDocument;if(!v||!N?.body)return;const S=N.body.scrollWidth||N.documentElement.scrollWidth,C=v.clientWidth;S>C+2&&(N.body.style.zoom=String(C/S)),h(Math.max(40,N.documentElement.scrollHeight+2)),N.addEventListener("mouseup",()=>{const I=v.contentWindow?.getSelection();if(!I||I.isCollapsed){n(null);return}const O=I.toString().replace(/\s+/g," ").trim();if(O.length<2)return;const _=I.getRangeAt(0).getBoundingClientRect(),A=v.getBoundingClientRect();n({text:O,page:t,x:A.left+_.left+_.width/2,y:A.top+_.bottom})})},w=v=>{const N=o.current.getBoundingClientRect();return{x:Math.min(1,Math.max(0,(v.clientX-N.left)/N.width)),y:Math.min(1,Math.max(0,(v.clientY-N.top)/N.height))}},E=()=>{if(!m||x){p(null);return}const v=Math.min(m.x0,m.x1),N=Math.min(m.y0,m.y1),S=Math.abs(m.x1-m.x0),C=Math.abs(m.y1-m.y0);if(p(null),S<.02||C<.01)return;const I=u.current?.contentDocument;!I?.documentElement||!r||(b(!0),(async()=>{const{toCanvas:O}=await pt(async()=>{const{toCanvas:z}=await import("./index-BeoRn2gJ.js");return{toCanvas:z}},[]),_=await O(I.documentElement,{pixelRatio:2}),A=Math.floor(v*_.width),H=Math.floor(N*_.height),G=Math.max(1,Math.floor(S*_.width)),D=Math.max(1,Math.floor(C*_.height)),P=document.createElement("canvas");P.width=G,P.height=D,P.getContext("2d").drawImage(_,A,H,G,D,0,0,G,D);const Y=o.current.getBoundingClientRect(),U={left:Y.left+v*Y.width,top:Y.top+N*Y.height,width:S*Y.width,height:C*Y.height};r(t??1,[v,N,S,C],P.toDataURL("image/png"),U)})().catch(()=>We("error",s)).finally(()=>b(!1)))};return l.jsxs("div",{ref:o,className:"relative",children:[l.jsx("iframe",{ref:u,sandbox:"allow-same-origin",srcDoc:e,onLoad:y,style:{height:d},className:"w-full border-0 bg-white shadow-md rounded-sm","aria-label":t!=null?`p.${t}`:"document"}),a&&l.jsxs("div",{className:"absolute inset-0 cursor-crosshair",style:{zIndex:6},"data-clip-overlay":t??1,onMouseDown:v=>{v.preventDefault();const N=w(v);p({x0:N.x,y0:N.y,x1:N.x,y1:N.y})},onMouseMove:v=>{if(m){const N=w(v);p({...m,x1:N.x,y1:N.y})}},onMouseUp:E,onMouseLeave:()=>{m&&E()},children:[x&&l.jsx("div",{className:"absolute top-2 right-2 flex items-center gap-1.5 text-2xs text-warm bg-card/95 border border-line rounded-lg px-2 py-1 shadow-sm",children:l.jsx(tn,{size:11,strokeWidth:1.75,className:"animate-spin"})}),m&&l.jsx("div",{className:"absolute border-2 border-warm bg-warm/10 rounded-sm pointer-events-none",style:{left:`${Math.min(m.x0,m.x1)*100}%`,top:`${Math.min(m.y0,m.y1)*100}%`,width:`${Math.abs(m.x1-m.x0)*100}%`,height:`${Math.abs(m.y1-m.y0)*100}%`}})]})]})}let Sb=null;function lce(){return Sb||(Sb=Promise.all([pt(()=>import("./pdf-gh-BrLFn.js"),[]),pt(()=>import("./pdf.worker.min-C_APr3k7.js"),[])]).then(([e,t])=>(e.GlobalWorkerOptions.workerSrc=t.default,e))),Sb}function cce(e){const t=atob(e),n=new Uint8Array(t.length);for(let a=0;a<t.length;a++)n[a]=t.charCodeAt(a);return n}const uce=/<!--\s*tdag-page:(\d+)\s*-->/;function dce(e){const t=e.split(uce),n=[];t[0].trim()&&n.push({page:null,md:t[0]});for(let a=1;a<t.length;a+=2)n.push({page:Number(t[a]),md:t[a+1]??""});return n.length>0?n:[{page:null,md:e}]}const Nb=60,MN=new Map;function hce({onLocate:e}){const t=ce(a=>a.readerNodeId),n=se(a=>t?a.nodes.find(r=>r.id===t):void 0);return R.useEffect(()=>{t&&!n&&ce.getState().setReaderNodeId(null)},[t,n]),n?l.jsx(fce,{node:n,onLocate:e},n.id):null}function fce({node:e,onLocate:t}){const n=Tt(),a=e.data,r=a.stepKind==="file"||!a.stepKind&&(a.attachments??[]).some(we=>we.type==="application/pdf")?"file":a.stepKind==="link"?"link":"note",s=R.useMemo(()=>a.attachments??[],[a.attachments]),o=s.find(we=>we.type==="application/pdf"),u=s.find(we=>we.type==="text/html"),d=r==="link"?a.linkSnapshotHtml:void 0,h=R.useMemo(()=>d?{id:`link-snapshot-${e.id}`,name:a.linkTitle||a.linkUrl||"snapshot",type:"text/html",size:d.length,content:d}:null,[d,e.id,a.linkTitle,a.linkUrl]),m=R.useMemo(()=>s.filter(we=>we.type.startsWith("image/")),[s]),p=()=>ce.getState().setReaderNodeId(null),x=R.useMemo(()=>{if(o)return o.extractedText??"";if(r==="file"){const we=s.filter(St=>!St.type.startsWith("image/")&&St.type!=="application/pdf"),et=we.map(St=>{const Lt=St.type==="text/html"?St.extractedText??"":St.content;return we.length>1?`### ${St.name}
691
691
 
@@ -701,7 +701,7 @@ ${_}`:O.question.trim();a([...n,{id:En(),text:A,at:new Date().toISOString(),from
701
701
  `).length+1),className:"w-full bg-wash border border-accent rounded-lg p-3 text-sm text-ink resize-y focus:outline-none","data-mp-profile-text":!0}),l.jsx("p",{className:"text-2xs text-ink-faint mt-1",children:n("mp.docHint")}),l.jsxs("div",{className:"flex justify-end gap-2 mt-2",children:[l.jsx("button",{onClick:()=>u(!1),className:"text-xs px-3 py-1 rounded-lg text-ink-muted hover:bg-wash",children:n("common.cancel")}),l.jsx("button",{onClick:()=>{fW(e,r,n("mp.editedNote")),u(!1)},className:"text-xs px-3 py-1 rounded-lg bg-accent text-white","data-mp-profile-save":!0,children:n("mp.save")})]})]}):d.length===0?l.jsx("p",{className:"text-xs text-ink-faint italic",children:n("mp.docEmpty")}):l.jsx("ul",{className:"text-sm text-ink leading-relaxed list-disc pl-5 max-w-[68ch]","data-mp-profile-lines":!0,children:d.map((h,m)=>{const p=Y8(a,h);return l.jsxs("li",{children:[l.jsx("span",{children:h}),p&&l.jsx("span",{className:"ml-1.5 align-baseline inline-flex font-mono text-2xs text-ink-faint border border-line rounded px-1 whitespace-nowrap",title:p.was?ve(n("mp.lineWas"),{t:p.was}):void 0,"data-mp-line-note":p.evidence,children:[p.from,ri(p.at),n(yce[p.evidence])].filter(Boolean).join(" · ")})]},m)})}),a.changelog.length>0&&l.jsxs("div",{className:"mt-3 pt-2 border-t border-dashed border-line-strong text-2xs text-ink-muted space-y-0.5",children:[l.jsx("div",{className:"text-ink-faint",children:n("mp.changelog")}),a.changelog.slice(-6).reverse().map((h,m)=>l.jsxs("div",{children:[l.jsx("span",{className:"font-mono text-ink mr-2",children:ri(h.at)}),h.note]},m))]})]})}function jN({topicId:e,name:t,onClose:n,onChanged:a,onOpened:r}){const s=Tt(),[o,u]=R.useState(void 0),[d,h]=R.useState(null),[m,p]=R.useState(null),[x,b]=R.useState(null),[y,w]=R.useState(""),[E,v]=R.useState(null),N=R.useCallback(async()=>{const _=Rn();if(_)try{const[A,H]=await Promise.all([_.dossier(e),_.dossiers()]);u(A),v(H.find(G=>G.topicId===e)??null)}catch(A){p(bm(A))}},[e]);R.useEffect(()=>{N()},[N]);const S=async _=>{h(_),p(null);try{const A=_==="build"?await H2(e):_==="update"?await u7(e):await WW(e);u(A),await N(),a()}catch(A){p(bm(A))}finally{h(null)}},C=async()=>{if(x)try{const _=await VW(e,x,y.split(`
702
702
  `));u(_),b(null),a()}catch(_){p(bm(_))}},I=async _=>{const A=o?.sources[_];!A||A.kind!=="turn"||await P2(A.open)&&r?.()},O=!!o?.builtAt&&!B2(o);return l.jsxs("div",{className:"border border-line rounded-xl bg-surface px-4 py-3 mt-3","data-mp-dossier":e,children:[l.jsxs("div",{className:"flex items-baseline gap-3 flex-wrap mb-2",children:[l.jsx("span",{className:"text-sm font-semibold text-ink",children:t}),l.jsx("span",{className:"text-2xs text-ink-faint",children:O?`${ve(s("mp.fromTurns"),{n:o.covered.length})} · ${ve(s("mp.updatedAt"),{d:ri(o.updatedAt)})}`:s("mp.notBuilt")}),l.jsx("span",{className:"flex-1"}),d?l.jsxs("span",{className:"text-xs text-accent flex items-center gap-1",children:[l.jsx(tn,{size:12,className:"animate-spin"})," ",s("mp.building")]}):l.jsxs(l.Fragment,{children:[O?l.jsxs("button",{onClick:()=>{S("update")},disabled:!E||E.newTurns===0&&E.pending===0,className:"text-xs px-2.5 py-1 rounded-lg bg-accent text-white disabled:opacity-40 flex items-center gap-1","data-mp-dossier-update":!0,children:[l.jsx(cr,{size:12,strokeWidth:1.75})," ",E?.newTurns?ve(s("mp.updateN"),{n:E.newTurns}):s("mp.update")]}):l.jsxs("button",{onClick:()=>{S("build")},className:"text-xs px-2.5 py-1 rounded-lg bg-accent text-white flex items-center gap-1","data-mp-dossier-build":!0,children:[l.jsx(Vl,{size:12,strokeWidth:1.75})," ",s("mp.build")]}),O&&l.jsx("button",{onClick:()=>{S("rebuild")},className:"text-xs px-2.5 py-1 rounded-lg text-ink-muted hover:bg-wash",children:s("mp.rebuild")})]}),l.jsx("button",{onClick:n,className:"text-xs px-2 py-1 rounded-lg text-ink-muted hover:bg-wash",children:s("common.close")})]}),m&&l.jsx("p",{className:"text-2xs text-red-500 mb-2","data-mp-dossier-error":!0,children:m}),o===void 0?l.jsx(tn,{size:14,className:"animate-spin text-ink-faint"}):l.jsxs("div",{className:"grid gap-3 max-w-[72ch]",children:[E0.map(_=>{const A=o?.sections[_]??[];return!A.length&&O&&x!==_?l.jsxs("div",{className:"group",children:[l.jsxs("div",{className:"text-2xs font-semibold text-ink-faint tracking-wide flex items-center gap-2",children:[s(Fm[_]),l.jsx("button",{onClick:()=>{b(_),w("")},className:"opacity-0 group-hover:opacity-100 text-accent font-normal",children:s("mp.edit")})]}),l.jsx("p",{className:"text-xs text-ink-faint italic",children:"—"})]},_):!A.length&&!O?null:l.jsxs("div",{className:"group","data-mp-dossier-section":_,children:[l.jsxs("div",{className:"text-2xs font-semibold text-ink-faint tracking-wide flex items-center gap-2",children:[s(Fm[_]),x!==_&&l.jsx("button",{onClick:()=>{b(_),w(A.map(H=>H.text).join(`
703
703
  `))},className:"opacity-0 group-hover:opacity-100 text-accent font-normal",children:s("mp.edit")})]}),x===_?l.jsxs("div",{children:[l.jsx("textarea",{value:y,onChange:H=>w(H.target.value),rows:Math.max(3,y.split(`
704
- `).length+1),className:"w-full bg-wash border border-accent rounded-lg p-2 text-sm text-ink resize-y focus:outline-none"}),l.jsxs("div",{className:"flex justify-end gap-2 mt-1",children:[l.jsx("button",{onClick:()=>b(null),className:"text-xs px-3 py-1 rounded-lg text-ink-muted hover:bg-wash",children:s("common.cancel")}),l.jsx("button",{onClick:()=>{C()},className:"text-xs px-3 py-1 rounded-lg bg-accent text-white",children:s("mp.save")})]})]}):l.jsx("ul",{className:"text-sm text-ink leading-relaxed space-y-0.5",children:A.map((H,G)=>l.jsxs("li",{className:"flex flex-wrap items-baseline gap-x-1.5",children:[l.jsx("span",{children:H.text}),H.src.map(D=>{const P=o.sources[D];return P?l.jsxs("button",{onClick:()=>{I(D)},title:`${P.title} · ${s("mp.sourceOpen")}`,className:"inline-flex items-center gap-0.5 font-mono text-2xs text-ink-faint border border-line rounded px-1 hover:text-accent hover:border-accent/40","data-mp-source":!0,children:[P.runner," · ",ri(P.at),P.kind==="turn"&&l.jsx(kp,{size:9})]},D):D.startsWith("filed:")?l.jsx("span",{className:"font-mono text-2xs text-ink-faint border border-line rounded px-1",children:s("mp.filedTag")},D):null})]},G))})]},_)}),!O&&!d&&l.jsx("p",{className:"text-xs text-ink-faint italic",children:E?.labeled?ve(s("mp.buildHint"),{n:E.labeled}):s("dossier.nothingToRead")}),!!o?.pending.length&&l.jsxs("div",{className:"text-2xs text-ink-muted border-t border-dashed border-line-strong pt-2","data-mp-dossier-pending":!0,children:[l.jsxs("div",{className:"text-ink-faint mb-0.5",children:[s("mp.pendingList")," · ",o.pending.length]}),o.pending.map(_=>l.jsxs("div",{children:[l.jsx("span",{className:"font-mono text-ink mr-2",children:ri(_.at)}),_.text]},_.id))]}),!!o?.changelog.length&&l.jsxs("div",{className:"text-2xs text-ink-muted border-t border-dashed border-line-strong pt-2",children:[l.jsx("div",{className:"text-ink-faint mb-0.5",children:s("mp.changelog")}),o.changelog.slice(-6).reverse().map((_,A)=>l.jsxs("div",{children:[l.jsx("span",{className:"font-mono text-ink mr-2",children:ri(_.at)}),_.note]},A))]})]})]})}function wce({query:e,onOpened:t}){const n=Tt(),a=ce(L=>L.recallEnabled),r=ce(L=>L.setRecallEnabled),s=ce(L=>L.memoryEnabled),o=ce(L=>L.setMemoryEnabled),u=ce(L=>L.profile),d=ce(L=>L.memoryInbox),[h,m]=R.useState(null),[p,x]=R.useState(null),[b,y]=R.useState(null),[w,E]=R.useState(null),[v,N]=R.useState(!1),[S,C]=R.useState(!1),[I,O]=R.useState(!1),[_,A]=R.useState(null),H=Ap();R.useEffect(()=>{R2()},[]);const[G,D]=R.useState(0),P=R.useCallback(()=>D(L=>L+1),[]);R.useEffect(()=>{const L=Rn();if(!L)return;let q=!0;return(async()=>{try{const[W,X]=await Promise.all([L.dossiers(),L.topics()]);if(!q)return;x(W),y(X);for(const B of W)B.built&&B.pending>=HW&&!ON.has(B.topicId)&&(ON.add(B.topicId),u7(B.topicId).then(()=>D($=>$+1)).catch(()=>{}))}catch{q&&x([])}})(),()=>{q=!1}},[G]),R.useEffect(()=>{!I||_!==null||Rn()?.memories().then(L=>A(L.length)).catch(()=>A(0))},[I,_]);const Y=R.useMemo(()=>({preferences:ss(u.preferences),identity:ss(u.identity)}),[u]),U=async(L,q)=>{const W=Rn(),X=d.find(B=>B.id===L);if(!(!W||!X))try{await W.dossierPending(q,{text:X.text,...X.from?{from:X.from}:{}}),CE(L),We("success",ve(n("mp.filed"),{name:b?.topics.find(B=>B.id===q)?.name??""})),P()}catch(B){We("error",bm(B))}},z=e.trim().length>=2;return l.jsxs("div",{"data-memory-page":!0,children:[z&&l.jsx(_M,{phrase:e,onOpened:t,dossiers:p??[],onOpenDossier:L=>E(L)}),z&&w&&l.jsx(jN,{topicId:w,name:p?.find(L=>L.topicId===w)?.name??"",onClose:()=>E(null),onChanged:P,onOpened:t}),!z&&l.jsxs("div",{className:"max-w-[860px]",children:[l.jsxs("section",{className:"mb-6","data-mp-section":"settings",children:[l.jsx("h4",{className:"text-2xs font-semibold uppercase tracking-wide text-ink-faint mb-1",children:n("mp.settings")}),l.jsxs("div",{className:"border-t border-line",children:[l.jsxs("div",{className:"flex items-center gap-4 py-2.5 border-b border-line",children:[l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsx("div",{className:"text-sm text-ink font-medium",children:n("mp.recallOn")}),l.jsx("div",{className:"text-2xs text-ink-faint",children:n("mp.recallOnHint")})]}),l.jsx(DN,{on:a,onChange:r,testId:"recall"})]}),l.jsxs("div",{className:"flex items-center gap-4 py-2.5 border-b border-line",children:[l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsx("div",{className:"text-sm text-ink font-medium",children:n("mp.memoryOn")}),l.jsx("div",{className:"text-2xs text-ink-faint",children:n("mp.memoryOnHint")})]}),l.jsx(DN,{on:s,onChange:o,testId:"memory"})]}),l.jsxs("div",{className:"flex items-center gap-4 py-2.5 border-b border-line",children:[l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsx("div",{className:"text-sm text-ink font-medium",children:n("mp.judgeRow")}),l.jsx("div",{className:"text-2xs text-ink-faint",children:n("mp.judgeRowHint")})]}),l.jsx("button",{onClick:()=>ce.getState().setApiKeyModalOpen(!0,"judge"),className:"text-xs text-accent hover:underline","data-judge-configure":!0,children:n("mp.open")})]})]})]}),l.jsxs("section",{className:"mb-6","data-mp-section":"you",children:[l.jsx("h4",{className:"text-2xs font-semibold uppercase tracking-wide text-ink-faint mb-1",children:n("mp.you")}),l.jsx("div",{className:"border-t border-line",children:["preferences","identity"].map(L=>l.jsxs("button",{onClick:()=>m(h===L?null:L),className:`w-full grid grid-cols-[110px_minmax(0,1fr)_auto] gap-3 items-center py-2.5 border-b border-line text-left hover:bg-wash -mx-2 px-2 ${h===L?"bg-wash":""}`,"data-mp-doc":L,children:[l.jsx("span",{className:"text-sm text-ink font-medium",children:n(L==="preferences"?"mp.preferences":"mp.identity")}),l.jsx("span",{className:"text-xs text-ink-muted truncate",children:Y[L].length?Y[L].join(" · "):n("mp.docEmpty")}),l.jsx("span",{className:"text-2xs text-ink-faint whitespace-nowrap",children:u[L].updatedAt?ve(n("mp.updatedAt"),{d:ri(u[L].updatedAt)}):""})]},L))}),h&&l.jsx(vce,{kind:h,onClose:()=>m(null)})]}),l.jsxs("section",{className:"mb-6","data-mp-section":"projects",children:[l.jsxs("div",{className:"flex items-center gap-3 mb-1",children:[l.jsx("h4",{className:"text-2xs font-semibold uppercase tracking-wide text-ink-faint",children:n("mp.projects")}),l.jsx("span",{className:"flex-1"}),H&&b&&b.topics.length>0&&l.jsxs("span",{className:"text-2xs text-ink-faint","data-mp-label-state":!0,children:[ve(n("mp.labelState"),{n:b.labeled,m:b.turns}),b.status.running?` · ${ve(n("topics.running"),{a:b.status.done,b:b.status.total})}`:""]}),H&&l.jsxs("button",{onClick:()=>N(L=>!L),className:"text-xs text-ink-muted hover:text-ink flex items-center gap-1 px-2 py-1 rounded-lg hover:bg-wash","data-mp-edit-topics":!0,children:[l.jsx(t8,{size:12,strokeWidth:1.75})," ",n("mp.editTopics")]})]}),H?l.jsxs(l.Fragment,{children:[v&&l.jsx("div",{className:"border border-line rounded-xl px-4 pb-3 mb-3 bg-surface",children:l.jsx(bce,{onOpened:t,onChanged:P})}),l.jsx("div",{className:"border-t border-line",children:p===null?l.jsx("div",{className:"py-3",children:l.jsx(tn,{size:14,className:"animate-spin text-ink-faint"})}):p.length===0?l.jsx("p",{className:"text-xs text-ink-faint italic py-2","data-mp-no-topics":!0,children:n("mp.noTopics")}):p.map(L=>l.jsxs("button",{onClick:()=>E(w===L.topicId?null:L.topicId),className:`w-full grid grid-cols-[150px_minmax(0,1fr)_auto] gap-3 items-center py-2.5 border-b border-line text-left hover:bg-wash -mx-2 px-2 ${w===L.topicId?"bg-wash":""}`,"data-mp-project":L.topicId,children:[l.jsx("span",{className:"text-sm text-ink font-medium truncate",children:L.name}),l.jsx("span",{className:"text-xs text-ink-muted truncate",children:L.built?L.lead:l.jsxs("span",{className:"text-ink-faint italic",children:[n("mp.notBuilt"),L.labeled?` · ${ve(n("mp.labeledTurns"),{n:L.labeled})}`:""]})}),l.jsxs("span",{className:"text-2xs text-ink-faint whitespace-nowrap flex items-center gap-1.5",children:[L.built&&L.newTurns>0&&l.jsx("span",{className:"px-1.5 py-px rounded-full border border-warm/60 text-warm bg-warm/10",children:ve(n("mp.newTurns"),{n:L.newTurns})}),L.pending>0&&l.jsx("span",{className:"px-1.5 py-px rounded-full border border-accent/40 text-accent bg-accent/10",children:ve(n("mp.pending"),{n:L.pending})}),L.built&&ve(n("mp.updatedAt"),{d:ri(L.updatedAt)})]})]},L.topicId))}),w&&!z&&l.jsx(jN,{topicId:w,name:p?.find(L=>L.topicId===w)?.name??"",onClose:()=>E(null),onChanged:P,onOpened:t})]}):l.jsx("p",{className:"text-xs text-ink-faint italic border-t border-line pt-2",children:n("mp.needIndex")}),d.length>0&&l.jsx(RN,{label:ve(n("mp.inbox"),{n:d.length}),open:S,onToggle:()=>C(L=>!L),testId:"inbox",children:l.jsx("div",{className:"space-y-1.5",children:d.map(L=>l.jsxs("div",{className:"flex items-center gap-2 text-xs","data-mp-inbox-item":!0,children:[l.jsx("span",{className:"flex-1 min-w-0 text-ink truncate",children:L.text}),l.jsxs("span",{className:"text-2xs text-ink-faint whitespace-nowrap",children:[L.from?`${L.from} · `:"",ri(L.at)]}),H&&!!b?.topics.length&&l.jsxs("select",{defaultValue:"",onChange:q=>{q.target.value&&U(L.id,q.target.value)},className:"text-2xs bg-wash border border-line rounded-md px-1.5 py-0.5","data-mp-inbox-file":!0,children:[l.jsx("option",{value:"",children:n("mp.fileTo")}),b.topics.map(q=>l.jsx("option",{value:q.id,children:q.name},q.id))]}),l.jsx("button",{onClick:()=>CE(L.id),className:"text-2xs text-ink-faint hover:text-red-500 px-1.5 py-0.5 rounded",children:n("mp.discard")})]},L.id))})})]}),H&&l.jsxs("section",{className:"mb-4","data-mp-section":"sources",children:[l.jsx("h4",{className:"text-2xs font-semibold uppercase tracking-wide text-ink-faint mb-1",children:n("mp.sources")}),l.jsxs(RN,{label:ve(n("mp.sourcesN"),{n:1+(_??0)}),open:I,onToggle:()=>O(L=>!L),testId:"sources",children:[l.jsxs("div",{className:"text-xs text-ink-muted mb-3 flex items-center gap-3",children:[l.jsx("span",{className:"text-ink font-medium",children:n("mp.index")}),l.jsx("span",{children:b?ve(n("mp.indexLine"),{n:b.turns}):"…"})]}),l.jsx(xce,{})]})]})]})]})}const UM="thoughtdag.atlas.watermark",Wo=e=>`${e.rootKey}:${e.rel}`;function Xv(){try{return JSON.parse(localStorage.getItem(UM)??"{}")}catch{return{}}}function lp(e){localStorage.setItem(UM,JSON.stringify(e))}function kce(e){const t=Xv(),n=new Map;if(Object.keys(t).length===0)return lp(Object.fromEntries(e.map(s=>[Wo(s),{mtime:s.mtime,size:s.size}]))),n;const a=new Set(e.map(Wo));let r=!1;for(const s of Object.keys(t))a.has(s)||(delete t[s],r=!0);for(const s of e){const o=t[Wo(s)];o?(s.size>o.size||s.mtime>o.mtime+1e3)&&n.set(Wo(s),{kind:"updated",deltaSize:Math.max(0,s.size-o.size)}):n.set(Wo(s),{kind:"new",deltaSize:s.size})}return r&&lp(t),n}function Ece(e){const t=Xv();t[Wo(e)]={mtime:e.mtime,size:e.size},lp(t)}function Sce(e){const t=Xv();for(const n of e)t[Wo(n)]={mtime:n.mtime,size:n.size};lp(t)}const Fc=Wo,Tb=e=>new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),LN=e=>e>1e6?`${(e/1e6).toFixed(1)} MB`:`${Math.max(1,Math.round(e/1024))} KB`,Nce={time:(e,t)=>t.mtime-e.mtime,name:(e,t)=>e.title.localeCompare(t.title),size:(e,t)=>t.size-e.size,runner:(e,t)=>e.runner.localeCompare(t.runner)||t.mtime-e.mtime};function Tce({roots:e,counts:t,onChanged:n,onClose:a}){const r=Tt(),s=L2(),o={"claude-projects":"Claude Code","codex-sessions":"Codex","dsh-sessions":"DeepSeek Harness","pi-sessions":"Pi"},[u,d]=R.useState(null),h=()=>{window.desktopSessions?.commandsStatus?.().then(d).catch(()=>{})};R.useEffect(h,[]);const m={"claude-code":"Claude Code",codex:"Codex",dsh:"DeepSeek Harness",pi:"Pi"},p=x=>l.jsxs("div",{className:"flex items-center gap-3 px-4 py-2.5 border-b border-line last:border-b-0","data-atlas-source":x.key,children:[l.jsx("input",{type:"checkbox",checked:!s.has(x.key),disabled:!x.exists,onChange:b=>{IW(x.key,!b.target.checked),n()},className:"shrink-0"}),l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsx("div",{className:"text-sm text-ink",children:o[x.key]??x.path.split("/").filter(Boolean).pop()}),l.jsx("div",{className:"text-2xs text-ink-faint truncate",children:x.path})]}),l.jsx("span",{className:"text-2xs text-ink-faint shrink-0",children:x.exists?t.get(x.key)??0:r("atlas.rootMissing")}),!x.builtin&&l.jsx("button",{className:"text-ink-faint hover:text-red-500 p-1 rounded transition-colors shrink-0",onClick:()=>{window.desktopSessions.removeRoot(x.key).then(n)},children:l.jsx(rr,{size:14,strokeWidth:1.75})})]},x.key);return l.jsx("div",{className:"absolute inset-0 z-10 bg-ink/20 flex items-center justify-center",onClick:a,children:l.jsxs("div",{className:"bg-surface border border-line rounded-2xl shadow-xl w-[440px] max-h-[80%] overflow-y-auto",onClick:x=>x.stopPropagation(),"data-atlas-sources-dialog":!0,children:[l.jsxs("div",{className:"px-4 pt-3.5 pb-2.5 border-b border-line",children:[l.jsx("div",{className:"text-sm font-semibold text-ink",children:r("atlas.sourcesTitle")}),l.jsx("div",{className:"text-2xs text-ink-muted mt-0.5",children:r("atlas.sourcesHint")})]}),e.filter(x=>x.builtin).map(p),u&&Object.values(u).some(x=>x.state!=="unavailable")&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"px-4 pt-3 pb-1.5 text-2xs uppercase tracking-wide text-ink-faint",children:r("atlas.handoffTitle")}),Object.entries(u).filter(([,x])=>x.state!=="unavailable").map(([x,b])=>l.jsxs("div",{className:"flex items-center gap-3 px-4 py-2.5 border-b border-line","data-atlas-handoff":x,"data-handoff-state":b.state,children:[l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsxs("div",{className:"text-sm text-ink flex items-center gap-2",children:[m[x]??x,l.jsx("code",{className:"text-2xs bg-wash border border-line rounded px-1.5 py-px font-mono",children:b.invoke})]}),l.jsx("div",{className:"text-2xs text-ink-faint truncate",children:r(b.state==="installed"?"atlas.handoffOn":b.state==="outdated"?"atlas.handoffOutdated":"atlas.handoffOff")})]}),b.state!=="installed"&&l.jsx("button",{className:"text-2xs bg-accent/10 text-accent hover:bg-accent/20 font-medium px-2.5 py-1 rounded-lg transition-colors shrink-0","data-handoff-install":!0,onClick:()=>{(async()=>{const{confirmDialog:y}=await pt(async()=>{const{confirmDialog:v}=await Promise.resolve().then(()=>gu);return{confirmDialog:v}},void 0);if(!await y({title:Ne("atlas.handoffEnableTitle"),message:ve(Ne("confirm.installCommand"),{path:b.dest}),confirmLabel:Ne(b.state==="outdated"?"atlas.handoffUpdate":"atlas.handoffEnable")}))return;const E=await window.desktopSessions.commandsInstall(x);E.ok?We("success",ve(Ne("atlas.handoffInstalled"),{cmd:b.invoke}),8e3):We("error",E.error??"install failed"),h()})()},children:r(b.state==="outdated"?"atlas.handoffUpdate":"atlas.handoffEnable")}),(b.state==="installed"||b.state==="outdated")&&l.jsx("button",{className:"text-ink-faint hover:text-red-500 p-1 rounded transition-colors shrink-0",title:r("atlas.handoffRemove"),"data-handoff-remove":!0,onClick:()=>{window.desktopSessions.commandsRemove(x).then(h)},children:l.jsx(rr,{size:14,strokeWidth:1.75})})]},x))]}),e.filter(x=>!x.builtin).map(p),l.jsxs("div",{className:"flex items-center gap-2 px-4 py-3",children:[l.jsxs("button",{onClick:n,className:"flex items-center gap-1.5 text-sm text-ink-muted hover:text-ink border border-line rounded-lg px-2.5 py-1.5 hover:bg-wash transition-colors",children:[l.jsx(cr,{size:13,strokeWidth:1.75})," ",r("atlas.autoDetect")]}),l.jsxs("button",{onClick:()=>{window.desktopSessions.addRoot().then(x=>{x&&n()})},className:"flex items-center gap-1.5 text-sm text-accent border border-line rounded-lg px-2.5 py-1.5 hover:bg-wash transition-colors","data-atlas-add-dir":!0,children:[l.jsx(QA,{size:13,strokeWidth:1.75})," ",r("atlas.addDir")]})]})]})})}function Qv({onClose:e,onSwitched:t,focusSessionId:n,initialTab:a}){const r=Tt(),[s,o]=R.useState(a??"sessions"),u=!!Rn(),d=sn(ie=>ie.projects),h=sn(ie=>ie.projects.find(Be=>Be.id===ie.activeId)?.sourceSession?.sessionId),m=!!window.desktopSessions,[p,x]=R.useState(null),[b,y]=R.useState([]),[w,E]=R.useState(!1),[v,N]=R.useState(window.desktopSessions?null:"canvases"),[S,C]=R.useState(null),[I,O]=R.useState(!1),[_,A]=R.useState(null),[H,G]=R.useState(new Map),[D,P]=R.useState(new Map),[Y,U]=R.useState(new Map),[z,L]=R.useState(!1),q=ie=>`${ie.rootKey}|${ie.rel}`,W=ie=>U(Be=>{const ot=new Map(Be),Ht=q(ie);return ot.has(Ht)?ot.delete(Ht):ot.set(Ht,ie),ot}),X=ie=>d.find(Be=>my(Be).includes(ie)),[B,$]=R.useState(""),[Z,K]=R.useState(new Set),[J,oe]=R.useState("time"),[me,ye]=R.useState(!1),[ae,ge]=R.useState(!1),[Te,Fe]=R.useState(new Map),[Me,Le]=R.useState(null);R.useEffect(()=>{window.desktopSessions?.openTargets().then(Le).catch(()=>{})},[]);const Ee=R.useMemo(()=>new Map((Me?.apps??[]).map(ie=>[ie.runner,ie.name])),[Me]),ze=async()=>{E(!0);try{y(await window.desktopSessions?.roots().catch(()=>[])??[]);const ie=await OW();if(x(ie),Fe(kce(ie)),window.desktopSessions?.codexThreads?.().then(Be=>{Be&&(G(new Map(Be.filter(ot=>ot.name&&ot.sessionId).map(ot=>[ot.sessionId,ot.name]))),P(new Map(Be.filter(ot=>ot.forkedFromId&&ot.sessionId).map(ot=>[ot.sessionId,ot.forkedFromId]))))}).catch(()=>{}),n){const Be=ie.find(ot=>ot.sessionId===n);Be&&N(Be.cwd??"")}}finally{E(!1)}};R.useEffect(()=>{ze()},[]),R.useEffect(()=>{let ie=!1;const Be=()=>{ie||w||(ie=!0,setTimeout(()=>{ie=!1,ze()},2e3))};return window.addEventListener("td:sessions-changed",Be),()=>window.removeEventListener("td:sessions-changed",Be)},[w]);const De=R.useCallback(ie=>H.get(ie.sessionId)??ie.title,[H]),tt=R.useMemo(()=>(p??[]).filter(ie=>!Z.has(ie.runner)&&(ae||!ie.subagent)&&(!me||Te.has(Fc(ie)))&&(!B.trim()||De(ie).toLowerCase().includes(B.trim().toLowerCase()))),[p,Z,B,me,Te,ae,De]),xt=R.useMemo(()=>DW(tt),[tt]),Ke=R.useMemo(()=>[...new Set((p??[]).map(ie=>ie.runner))].sort(),[p]),nt=R.useMemo(()=>{const ie=new Map;for(const Be of p??[])ie.set(Be.rootKey,(ie.get(Be.rootKey)??0)+1);return ie},[p]),st=v==="canvases"?null:xt.find(ie=>(ie.cwd??"")===(v??xt[0]?.cwd??""))??xt[0]??null,Ue=R.useMemo(()=>{if(!st)return[];const ie=J==="name"?(Be,ot)=>De(Be).localeCompare(De(ot)):Nce[J];return[...st.cards].sort(ie)},[st,J,De]),Rt=ie=>{Ece(ie),Fe(Be=>{const ot=new Map(Be);return ot.delete(Fc(ie)),ot})},lt=async ie=>{if(!S){C(ie.rel),Rt(ie);try{const{streamRunnerConversation:Be}=await pt(async()=>{const{streamRunnerConversation:Ft}=await import("./index-CjJoJV4P.js");return{streamRunnerConversation:Ft}},[]),{importOrAppendConversation:ot,shellSessionReader:Ht}=await pt(async()=>{const{importOrAppendConversation:Ft,shellSessionReader:ln}=await import("./canonical-46lAq3XC.js");return{importOrAppendConversation:Ft,shellSessionReader:ln}},[]),Wt=await Kc(await Be(Ht(ie.rootKey,ie.rel)),ie.rootKey,ie.rel,p),Vt=await ot(Wt);if(!Vt)throw new Error(Ne("handoff.notASession"));Vt.kind==="appended"?We("success",ve(Ne("atlas.appended"),{n:Vt.turns}),9e3):Vt.kind==="mounted"?We("success",ve(Ne(Vt.mode==="continue"?"atlas.mountedChapter":"atlas.mountedBranch"),{n:Vt.turns}),9e3):Vt.kind==="opened"?We("info",Ne("atlas.upToDate"),6e3):We("success",ve(Ne("toast.importedChats"),{n:1,m:Vt.nodeCount}),9e3),e(),t()}catch(Be){We("error",ve(Ne("atlas.parseFailed"),{msg:Be instanceof Error?Be.message:String(Be)}))}finally{C(null)}}},Dt=async ie=>{if(!(S||Y.size<2)){C("__merge__");try{const{streamRunnerConversation:Be}=await pt(async()=>{const{streamRunnerConversation:Ft}=await import("./index-CjJoJV4P.js");return{streamRunnerConversation:Ft}},[]),{mergeSessionsIntoProject:ot,shellSessionReader:Ht}=await pt(async()=>{const{mergeSessionsIntoProject:Ft,shellSessionReader:ln}=await import("./canonical-46lAq3XC.js");return{mergeSessionsIntoProject:Ft,shellSessionReader:ln}},[]),Wt=[];for(const Ft of Y.values())Wt.push(await Kc(await Be(Ht(Ft.rootKey,Ft.rel)),Ft.rootKey,Ft.rel,p)),Rt(Ft);const Vt=await ot(Wt,ie);if(!Vt)throw new Error(Ne("handoff.notASession"));We("success",ve(Ne("atlas.merged"),{n:Vt.mounted}),1e4),Vt.skipped>0&&We("info",ve(Ne("atlas.mergeSkippedInfo"),{n:Vt.skipped}),8e3),U(new Map),e(),t()}catch(Be){We("error",ve(Ne("atlas.parseFailed"),{msg:Be instanceof Error?Be.message:String(Be)}))}finally{C(null)}}},_e=async ie=>{const Be=sn.getState().projects.find(Wt=>Wt.sourceSession?.sessionId===ie.sessionId);if(!Be||S)return;const{confirmDialog:ot}=await pt(async()=>{const{confirmDialog:Wt}=await Promise.resolve().then(()=>gu);return{confirmDialog:Wt}},void 0);if(await ot({title:Ne("confirm.recastTitle"),message:ve(Ne("confirm.recast"),{name:Be.name}),confirmLabel:Ne("confirm.recastTitle"),danger:!0})){C(ie.rel);try{const{streamRunnerConversation:Wt}=await pt(async()=>{const{streamRunnerConversation:Dn}=await import("./index-CjJoJV4P.js");return{streamRunnerConversation:Dn}},[]),{importOrAppendConversation:Vt,shellSessionReader:Ft}=await pt(async()=>{const{importOrAppendConversation:Dn,shellSessionReader:qa}=await import("./canonical-46lAq3XC.js");return{importOrAppendConversation:Dn,shellSessionReader:qa}},[]),ln=await Kc(await Wt(Ft(ie.rootKey,ie.rel)),ie.rootKey,ie.rel,p);if(!ln)throw new Error(Ne("handoff.notASession"));const{deleteProject:$t}=await pt(async()=>{const{deleteProject:Dn}=await Promise.resolve().then(()=>Na);return{deleteProject:Dn}},void 0);if(await $t(Be.id),!await Vt(ln))throw new Error(Ne("handoff.notASession"));We("success",Ne("atlas.recastDone"),8e3),e(),t()}catch(Wt){We("error",ve(Ne("atlas.parseFailed"),{msg:Wt instanceof Error?Wt.message:String(Wt)}))}finally{C(null)}}},Qe=async(ie,Be)=>{const ot=await window.desktopSessions.openInCli(ie.runner,ie.cwd,ie.sessionId,Be).catch(()=>({opened:!1,via:"",command:""}));ot.opened&&ot.via==="app"?(await navigator.clipboard.writeText(ie.sessionId).catch(()=>{}),We("success",Ne("atlas.appOpened"),9e3)):ot.opened?We("success",Ne("atlas.opened")):ot.command&&(await navigator.clipboard.writeText(ot.command).catch(()=>{}),We("info",Ne("atlas.cmdCopied"),9e3))};return dr.createPortal(l.jsx("div",{className:"fixed inset-0 z-50 bg-ink/30 backdrop-blur-sm flex items-center justify-center p-6","data-session-atlas":!0,children:l.jsxs("div",{className:"bg-surface border border-line rounded-2xl shadow-2xl w-full max-w-[980px] h-[min(680px,90vh)] flex flex-col overflow-hidden",children:[l.jsxs("div",{className:"flex items-start gap-3 px-5 pt-4 pb-3 border-b border-line",children:[l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsx("div",{className:"text-base font-semibold text-ink",children:r(s==="memory"?"memory.managerTitle":"atlas.title")}),l.jsx("div",{className:"text-xs text-ink-muted mt-0.5",children:r(s==="memory"?"mp.subtitle":"atlas.subtitle")}),Te.size>0&&l.jsxs("div",{className:"text-xs mt-1 flex items-center gap-2","data-atlas-changes":!0,children:[l.jsx("span",{className:"text-accent",children:ve(r("atlas.changesSummary"),{n:[...Te.values()].filter(ie=>ie.kind==="new").length,m:[...Te.values()].filter(ie=>ie.kind==="updated").length})}),l.jsx("button",{className:"text-ink-faint hover:text-ink underline decoration-dotted transition-colors",onClick:()=>{Sce(p??[]),Fe(new Map)},"data-atlas-mark-all":!0,children:r("atlas.markAllSeen")})]})]}),m&&Me&&Me.terminals.length>0&&l.jsxs("label",{className:"flex items-center gap-1.5 text-sm text-ink-muted border border-line rounded-lg px-2.5 py-1.5 cursor-pointer",title:r("atlas.terminalChoice"),children:[l.jsx(Qo,{size:14,strokeWidth:1.75}),l.jsxs("select",{value:Me.prefs.terminal,onChange:ie=>{const Be=ie.target.value;if(Be==="__add__"){window.desktopSessions?.addTerminal().then(()=>window.desktopSessions?.openTargets().then(Le));return}window.desktopSessions?.setOpenPrefs({terminal:Be}).then(ot=>Le(Ht=>Ht&&{...Ht,prefs:ot}))},className:"bg-transparent focus:outline-none text-sm text-ink cursor-pointer","data-atlas-terminal-select":!0,children:[Me.terminals.map(ie=>l.jsx("option",{value:ie.id,children:ie.name},ie.id)),Me.canAddCustom&&l.jsx("option",{value:"__add__",children:r("atlas.otherTerminal")})]})]}),m&&l.jsxs("button",{onClick:()=>O(!0),hidden:s==="memory",className:"flex items-center gap-1.5 text-sm text-ink-muted hover:text-ink border border-line rounded-lg px-2.5 py-1.5 hover:bg-wash transition-colors","data-atlas-sources":!0,children:[l.jsx(QA,{size:14,strokeWidth:1.75})," ",r("atlas.sources")]}),m&&s!=="memory"&&l.jsxs("button",{onClick:()=>{ze()},disabled:w,className:"flex items-center gap-1.5 text-sm text-ink-muted hover:text-ink border border-line rounded-lg px-2.5 py-1.5 hover:bg-wash transition-colors disabled:opacity-60","data-atlas-refresh":!0,children:[w?l.jsx(tn,{size:14,className:"animate-spin"}):l.jsx(cr,{size:14,strokeWidth:1.75}),r(w?"atlas.scanning":"atlas.refresh")]}),l.jsx("button",{onClick:e,className:"text-ink-faint hover:text-ink p-1.5 rounded-lg hover:bg-wash transition-colors","data-atlas-close":!0,children:l.jsx(on,{size:18,strokeWidth:1.75})})]}),l.jsxs("div",{className:"flex items-center gap-3 px-5 py-2 border-b border-line shrink-0","data-atlas-tabs":!0,children:[l.jsx("div",{className:"flex items-center bg-wash rounded-lg p-0.5 shrink-0",children:["sessions","memory"].map(ie=>l.jsx("button",{onClick:()=>o(ie),className:`text-xs px-3 py-1 rounded-md transition-colors ${s===ie?"bg-card text-ink shadow-sm font-medium":"text-ink-muted hover:text-ink"}`,"data-atlas-tab":ie,"aria-pressed":s===ie,children:r(ie==="sessions"?"atlas.tabSessions":"atlas.tabMemory")},ie))}),u&&l.jsxs("div",{className:"flex items-center gap-1.5 border border-line rounded-lg px-2.5 py-1 bg-card flex-1 max-w-[520px]",children:[l.jsx(y0,{size:13,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),l.jsx("input",{value:B,onChange:ie=>$(ie.target.value),placeholder:r("atlas.searchPlaceholder"),className:"text-sm bg-transparent focus:outline-none w-full text-ink placeholder:text-ink-faint","data-atlas-search":!0})]})]}),s==="memory"?l.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-5 py-4","data-atlas-memory":!0,children:l.jsx(wce,{query:u?B:"",onOpened:()=>{e(),t()}})}):l.jsxs("div",{className:"flex-1 flex min-h-0",children:[l.jsxs("div",{className:"w-[260px] border-r border-line overflow-y-auto py-2 shrink-0",children:[l.jsx("div",{className:"px-4 py-1 text-2xs uppercase tracking-wide text-ink-faint",children:r("atlas.recent")}),d.filter(ie=>!ie.archived).sort((ie,Be)=>Be.updatedAt-ie.updatedAt).slice(0,6).map(ie=>l.jsxs("button",{onClick:()=>{e(),Wi(ie.id).then(t)},className:"w-full text-left px-4 py-1.5 flex items-center gap-2 text-ink hover:bg-wash transition-colors","data-atlas-recent":ie.id,children:[ie.sourceSession?.sessionId?l.jsx("span",{className:"text-2xs font-mono border border-line rounded px-1 py-px shrink-0 text-ink-faint",children:ie.sourceSession.runner}):l.jsx(eE,{size:13,strokeWidth:1.75,className:"shrink-0 text-ink-faint"}),l.jsx("span",{className:"flex-1 truncate text-sm",children:ie.name})]},ie.id)),l.jsx("div",{className:"border-t border-line mt-2 pt-2 px-4 py-1 text-2xs uppercase tracking-wide text-ink-faint",children:r("atlas.folders")}),!m&&l.jsx("div",{className:"px-4 py-2 text-xs text-ink-faint",children:r("atlas.webNoScan")}),m&&p===null&&l.jsxs("div",{className:"px-4 py-2 text-sm text-ink-faint flex items-center gap-2",children:[l.jsx(tn,{size:14,className:"animate-spin"})," ",r("atlas.scanning")]}),m&&p!==null&&xt.length===0&&l.jsx("div",{className:"px-4 py-2 text-xs text-ink-faint",children:r("atlas.empty")}),xt.map(ie=>{const Be=ie.cwd??"",ot=v!=="canvases"&&st===ie;return l.jsxs("button",{onClick:()=>N(Be),className:`w-full text-left px-4 py-2 flex items-center gap-2 transition-colors ${ot?"bg-accent/5 text-accent":"text-ink hover:bg-wash"}`,"data-atlas-folder":ie.name||"unfiled",children:[ot?l.jsx(pu,{size:15,strokeWidth:1.75,className:"shrink-0"}):l.jsx(PF,{size:15,strokeWidth:1.75,className:"shrink-0 text-ink-faint"}),l.jsx("span",{className:"flex-1 truncate text-sm",children:ie.name||r("atlas.unfiled")}),(()=>{const Ht=ie.cards.filter(Wt=>Te.has(Fc(Wt))).length;return Ht>0?l.jsxs("span",{className:"text-2xs text-accent shrink-0","data-atlas-folder-changes":!0,children:["+",Ht]}):null})(),l.jsx("span",{className:"text-2xs text-ink-faint shrink-0",children:ie.cards.length})]},Be)}),l.jsx("div",{className:"border-t border-line mt-2 pt-2",children:l.jsxs("button",{onClick:()=>N("canvases"),className:`w-full text-left px-4 py-2 flex items-center gap-2 transition-colors ${v==="canvases"?"bg-accent/5 text-accent":"text-ink hover:bg-wash"}`,"data-atlas-canvases":!0,children:[l.jsx(eE,{size:15,strokeWidth:1.75,className:"shrink-0"}),l.jsx("span",{className:"flex-1 truncate text-sm",children:r("atlas.myCanvases")}),l.jsx("span",{className:"text-2xs text-ink-faint shrink-0",children:d.length})]})})]}),l.jsxs("div",{className:"flex-1 overflow-y-auto p-4",children:[u&&B.trim().length>=2&&l.jsx(_M,{phrase:B,onOpened:()=>{e(),t()}}),v==="canvases"?l.jsxs("div",{className:"space-y-1.5",children:[d.filter(ie=>!ie.archived).sort((ie,Be)=>Be.updatedAt-ie.updatedAt).map(ie=>l.jsxs("div",{className:"group flex items-center flex-wrap gap-2 border border-line rounded-xl px-4 py-3 hover:bg-wash transition-colors cursor-pointer",onClick:()=>{e(),Wi(ie.id).then(t)},children:[l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsx("div",{className:"text-sm text-ink font-medium truncate",children:ie.name}),l.jsxs("div",{className:"text-2xs text-ink-faint mt-0.5 flex items-center gap-1.5",children:[l.jsx("span",{children:Tb(ie.updatedAt)}),!!ie.sourceSession?.sessionId&&l.jsx("span",{className:"font-mono border border-line rounded px-1 py-px",children:ie.sourceSession.runner})]})]}),l.jsx("button",{title:r("switcher.archive"),className:"opacity-0 group-hover:opacity-100 text-ink-faint hover:text-amber-600 p-1.5 rounded transition-all shrink-0",onClick:Be=>{Be.stopPropagation(),Vm(ie.id,!0)},"data-atlas-archive":!0,children:l.jsx(rl,{size:15,strokeWidth:1.75})}),!!ie.sourceSession&&my(ie).length>0&&l.jsxs("div",{className:"w-full basis-full text-2xs text-ink-faint font-mono flex flex-wrap gap-x-3 gap-y-0.5 pt-1","data-atlas-cluster":!0,children:[ie.sourceSession.sessionId&&l.jsxs("span",{children:["◉ ",ie.sourceSession.runner," ",ie.sourceSession.sessionId.slice(0,8)," · ",ve(r("atlas.turnsN"),{n:ie.sourceSession.importedCount})]}),(ie.sourceSession.chapters??[]).map(Be=>l.jsxs("span",{children:["↳ ",Be.runner," ",Be.sessionId.slice(0,8)," · ",ve(r("atlas.turnsN"),{n:Be.importedCount})]},Be.sessionId)),(ie.sourceSession.branches??[]).map(Be=>l.jsxs("span",{children:["⑂ ",Be.runner," ",Be.sessionId.slice(0,8)," · ",ve(r("atlas.turnsN"),{n:Be.importedCount})]},Be.sessionId))]})]},ie.id)),d.some(ie=>ie.archived)&&l.jsxs("details",{className:"pt-2","data-atlas-archived-group":!0,children:[l.jsx("summary",{className:"text-2xs uppercase tracking-wide text-ink-faint cursor-pointer px-1 py-1",children:ve(r("atlas.archivedGroup"),{n:d.filter(ie=>ie.archived).length})}),l.jsx("div",{className:"space-y-1.5 mt-1.5",children:d.filter(ie=>ie.archived).sort((ie,Be)=>Be.updatedAt-ie.updatedAt).map(ie=>l.jsxs("button",{title:r("atlas.restoreOpen"),onClick:()=>{Vm(ie.id,!1).then(()=>{e(),Wi(ie.id).then(t)})},className:"w-full text-left border border-dashed border-line rounded-xl px-4 py-2.5 hover:bg-wash transition-colors opacity-70 hover:opacity-100","data-atlas-archived-item":!0,children:[l.jsxs("div",{className:"text-sm text-ink truncate flex items-center gap-1.5",children:[l.jsx("span",{className:"truncate",children:ie.name}),!!ie.sourceSession?.sessionId&&l.jsx("span",{className:"text-2xs font-mono border border-line rounded px-1 py-px shrink-0 text-ink-faint",children:ie.sourceSession.runner})]}),l.jsx("div",{className:"text-2xs text-ink-faint mt-0.5",children:Tb(ie.updatedAt)})]},ie.id))})]})]}):l.jsxs(l.Fragment,{children:[(p?.length??0)>0&&l.jsxs("div",{className:"flex items-center gap-2 mb-3 flex-wrap",children:[!u&&l.jsxs("div",{className:"flex items-center gap-1.5 border border-line rounded-lg px-2 py-1 bg-card",children:[l.jsx(y0,{size:13,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),l.jsx("input",{value:B,onChange:ie=>$(ie.target.value),placeholder:r("atlas.filterTitle"),className:"text-sm bg-transparent focus:outline-none w-[150px] text-ink placeholder:text-ink-faint","data-atlas-filter":!0})]}),Ke.map(ie=>l.jsx("button",{onClick:()=>K(Be=>{const ot=new Set(Be);return ot.has(ie)?ot.delete(ie):ot.add(ie),ot}),className:`text-2xs font-mono border rounded-lg px-2 py-1 transition-colors ${Z.has(ie)?"border-line text-ink-faint line-through":"border-accent/40 text-accent bg-accent/5"}`,"data-atlas-runner-toggle":ie,children:ie},ie)),Te.size>0&&l.jsx("button",{onClick:()=>ye(ie=>!ie),className:`text-2xs border rounded-lg px-2 py-1 transition-colors ${me?"border-accent text-white bg-accent":"border-line text-ink-muted hover:text-ink"}`,"data-atlas-only-changed":!0,children:r("atlas.onlyChanged")}),(p??[]).some(ie=>ie.subagent)&&l.jsx("button",{onClick:()=>ge(ie=>!ie),className:`text-2xs border rounded-lg px-2 py-1 transition-colors ${ae?"border-accent text-accent bg-accent/5":"border-line text-ink-faint hover:text-ink"}`,"data-atlas-show-sub":!0,children:r("atlas.showSub")}),l.jsxs("button",{onClick:()=>oe(ie=>({time:"name",name:"size",size:"runner",runner:"time"})[ie]),className:"ml-auto flex items-center gap-1.5 text-2xs text-ink-muted hover:text-ink border border-line rounded-lg px-2 py-1 hover:bg-wash transition-colors","data-atlas-sort":!0,children:[l.jsx(jH,{size:12,strokeWidth:1.75}),r(`atlas.sort${J[0].toUpperCase()}${J.slice(1)}`)]})]}),st?l.jsxs(l.Fragment,{children:[st.cwd&&l.jsxs("div",{className:"text-2xs text-ink-faint mb-3 truncate",children:[st.cwd," · ",ve(r("atlas.sessions"),{n:st.cards.length})]}),l.jsx("div",{className:"space-y-1.5",children:Ue.map(ie=>l.jsxs("div",{className:`group border rounded-xl px-4 py-3 hover:bg-wash transition-colors cursor-pointer flex items-center gap-3 ${Y.has(q(ie))?"border-accent/60 bg-accent/5":"border-line"}`,onClick:()=>{lt(ie)},"data-atlas-session":ie.sessionId,children:[l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsxs("div",{className:"text-sm text-ink truncate flex items-center gap-1.5",children:[l.jsx("span",{className:"truncate",children:De(ie)}),D.has(ie.sessionId)&&l.jsx("span",{className:"text-2xs text-ink-faint border border-line rounded px-1 py-px shrink-0 font-mono",title:`⑂ ${D.get(ie.sessionId)}`,"data-atlas-fork":!0,children:"⑂"}),Te.get(Fc(ie))?.kind==="new"&&l.jsx("span",{className:"text-2xs text-white bg-accent rounded px-1 py-px shrink-0","data-atlas-badge":"new",children:r("atlas.badgeNew")}),Te.get(Fc(ie))?.kind==="updated"&&l.jsxs("span",{className:"text-2xs text-accent border border-accent/40 rounded px-1 py-px shrink-0","data-atlas-badge":"updated",children:["+",LN(Te.get(Fc(ie)).deltaSize)]}),ie.sessionId===h?l.jsx("span",{className:"text-2xs text-white bg-ink rounded px-1 py-px shrink-0","data-atlas-badge":"current",children:r("atlas.currentOpen")}):(()=>{const Be=X(ie.sessionId);return Be?l.jsx("span",{className:"text-2xs text-ink-faint border border-line rounded px-1 py-px shrink-0",title:Be.name,"data-atlas-badge":"canvas",children:r("atlas.onCanvas")}):null})()]}),l.jsxs("div",{className:"text-2xs text-ink-faint mt-0.5 flex items-center gap-2",children:[l.jsx("span",{className:"border border-line rounded px-1 py-px font-mono",children:ie.runner}),l.jsx("span",{children:Tb(ie.mtime)}),l.jsx("span",{children:LN(ie.size)})]})]}),S===ie.rel?l.jsx(tn,{size:16,className:"animate-spin text-accent shrink-0"}):l.jsxs("div",{className:`${Y.has(q(ie))?"":"opacity-0 group-hover:opacity-100"} transition-opacity flex items-center gap-1 shrink-0`,children:[!X(ie.sessionId)&&!!ie.sessionId&&l.jsx("button",{title:r("atlas.pickForMerge"),className:`p-1.5 rounded transition-colors ${Y.has(q(ie))?"text-accent":"text-ink-faint hover:text-accent"}`,onClick:Be=>{Be.stopPropagation(),W(ie)},"data-atlas-pick":Y.has(q(ie))?"on":"off",children:Y.has(q(ie))?l.jsx(KU,{size:16,strokeWidth:1.75}):l.jsx(V0,{size:16,strokeWidth:1.75})}),l.jsx("span",{title:r("atlas.import"),className:"text-ink-faint hover:text-accent p-1.5",children:l.jsx(ZF,{size:16,strokeWidth:1.75})}),d.some(Be=>Be.sourceSession?.sessionId===ie.sessionId)&&l.jsx("button",{title:r("atlas.recast"),className:"text-ink-faint hover:text-red-500 p-1.5 rounded transition-colors",onClick:Be=>{Be.stopPropagation(),_e(ie)},"data-atlas-recast":!0,children:l.jsx(ZA,{size:16,strokeWidth:1.75})}),!X(ie.sessionId)&&l.jsx("button",{title:r("atlas.mountTo"),className:"text-ink-faint hover:text-accent p-1.5 rounded transition-colors",onClick:Be=>{Be.stopPropagation(),A(ie)},"data-atlas-mount":!0,children:l.jsx(Xi,{size:16,strokeWidth:1.75})}),Ee.has(ie.runner)&&l.jsx("button",{title:ve(r("atlas.openApp"),{name:Ee.get(ie.runner)}),className:"text-ink-faint hover:text-accent p-1.5 rounded transition-colors",onClick:Be=>{Be.stopPropagation(),Qe(ie,"app")},"data-atlas-open-app":!0,children:l.jsx(IH,{size:16,strokeWidth:1.75})}),l.jsx("button",{title:r("atlas.openTerminal"),className:"text-ink-faint hover:text-accent p-1.5 rounded transition-colors",onClick:Be=>{Be.stopPropagation(),Qe(ie,"terminal")},"data-atlas-open-cli":!0,children:l.jsx(Qo,{size:16,strokeWidth:1.75})})]})]},ie.rel))})]}):l.jsx("div",{className:"py-16 text-center text-sm text-ink-faint",children:p===null?r("atlas.scanning"):p.length>0?r("atlas.filteredOut"):r("atlas.empty")})]})]})]}),Y.size>=2&&!z&&l.jsxs("div",{className:"absolute bottom-5 left-1/2 -translate-x-1/2 z-10 bg-surface border border-line rounded-xl shadow-lg px-4 py-2.5 flex items-center gap-3","data-atlas-merge-bar":!0,children:[l.jsx("span",{className:"text-xs text-ink-muted whitespace-nowrap",children:ve(r("atlas.mergeSelected"),{n:Y.size})}),S==="__merge__"?l.jsx(tn,{size:15,className:"animate-spin text-accent"}):l.jsxs(l.Fragment,{children:[l.jsx("button",{className:"text-xs bg-accent hover:bg-accent-strong text-white font-medium px-3 py-1.5 rounded-lg transition-colors whitespace-nowrap",onClick:()=>{Dt()},"data-atlas-merge-new":!0,children:r("atlas.mergeNew")}),l.jsx("button",{className:"text-xs text-ink-muted hover:text-ink hover:bg-wash font-medium px-3 py-1.5 rounded-lg transition-colors whitespace-nowrap",onClick:()=>L(!0),"data-atlas-merge-into":!0,children:r("atlas.mergeInto")})]}),l.jsx("button",{className:"text-ink-faint hover:text-ink p-1",onClick:()=>U(new Map),title:r("common.cancel"),children:l.jsx(on,{size:14,strokeWidth:1.75})})]}),(_||z)&&l.jsx("div",{className:"absolute inset-0 z-10 bg-ink/20 flex items-center justify-center",onClick:()=>{A(null),L(!1)},children:l.jsxs("div",{className:"bg-surface border border-line rounded-2xl shadow-xl w-[400px] max-h-[70%] overflow-y-auto",onClick:ie=>ie.stopPropagation(),"data-atlas-mount-picker":!0,children:[l.jsxs("div",{className:"px-4 pt-3.5 pb-2.5 border-b border-line",children:[l.jsx("div",{className:"text-sm font-semibold text-ink",children:r(z?"atlas.mergeInto":"atlas.mountTo")}),l.jsx("div",{className:"text-2xs text-ink-muted mt-0.5",children:r(z?"atlas.mergeSelected":"atlas.mountHint").replace("{n}",String(Y.size))})]}),d.filter(ie=>!ie.archived&&ie.kind!=="paradigm").sort((ie,Be)=>Be.updatedAt-ie.updatedAt).map(ie=>l.jsx("button",{className:"w-full text-left px-4 py-2.5 text-sm text-ink hover:bg-wash transition-colors border-b border-line last:border-b-0",onClick:()=>{if(z){L(!1),Dt(ie.id);return}const Be=_;A(null),(async()=>{C(Be.rel);try{const{streamRunnerConversation:ot}=await pt(async()=>{const{streamRunnerConversation:ln}=await import("./index-CjJoJV4P.js");return{streamRunnerConversation:ln}},[]),{mountConversationToProject:Ht,shellSessionReader:Wt}=await pt(async()=>{const{mountConversationToProject:ln,shellSessionReader:$t}=await import("./canonical-46lAq3XC.js");return{mountConversationToProject:ln,shellSessionReader:$t}},[]),Vt=await Kc(await ot(Wt(Be.rootKey,Be.rel)),Be.rootKey,Be.rel,p),Ft=await Ht(Vt,ie.id);if(!Ft)throw new Error(Ne("handoff.notASession"));We("success",ve(Ne("atlas.mountedChapter"),{n:Ft.kind==="mounted"||Ft.kind==="appended"?Ft.turns:0}),9e3),e(),t()}catch(ot){We("error",ve(Ne("atlas.parseFailed"),{msg:ot instanceof Error?ot.message:String(ot)}))}finally{C(null)}})()},children:ie.name},ie.id))]})}),I&&l.jsx(Tce,{roots:b,counts:nt,onChanged:()=>{ze()},onClose:()=>O(!1)})]})}),document.body)}function Ace(){const e=Tt(),t=ce(a=>!!a.harnessHost?.bar);if(!q$||t)return null;const n=()=>window.parent.postMessage({source:"dsh-thoughtdag",type:"td:close"},window.location.origin);return l.jsxs("div",{className:"bg-card/90 backdrop-blur border border-line rounded-xl p-0.5 shadow-sm flex items-center",role:"group","aria-label":"view switch","data-harness-view-switch":!0,children:[l.jsx("button",{type:"button",onClick:n,className:"h-8 px-3 rounded-[10px] text-xs font-semibold text-ink-muted hover:bg-wash hover:text-ink transition-colors whitespace-nowrap","data-view":"dialog","aria-pressed":!1,children:e("harness.viewChat")}),l.jsx("button",{type:"button",className:"h-8 px-3 rounded-[10px] text-xs font-semibold bg-ink text-card whitespace-nowrap cursor-default","data-view":"map","aria-pressed":!0,children:e("harness.viewMap")})]})}function Cce({conversations:e,onClose:t,onDone:n}){const a=Tt(),[r,s]=R.useState(new Set),[o,u]=R.useState(!1),d=p=>{s(x=>{const b=new Set(x);return b.has(p)?b.delete(p):b.add(p),b})},h=r.size===e.length,m=async()=>{r.size===0||o||(u(!0),await SG([...r].sort((p,x)=>p-x).map(p=>e[p])),u(!1),n())};return l.jsx("div",{className:"fixed inset-0 z-50 bg-ink/30 backdrop-blur-sm flex items-center justify-center p-6",onClick:t,children:l.jsxs("div",{className:"bg-card border border-line rounded-2xl shadow-2xl w-full max-w-lg max-h-[80vh] flex flex-col",onClick:p=>p.stopPropagation(),children:[l.jsxs("div",{className:"px-6 py-4 border-b border-line flex items-start justify-between gap-4",children:[l.jsxs("div",{children:[l.jsx("h2",{className:"text-base font-semibold text-ink",children:a("import.title")}),l.jsx("p",{className:"text-xs text-ink-muted mt-1 leading-relaxed",children:a("import.subtitle")})]}),l.jsx("button",{onClick:t,className:"text-ink-faint hover:text-ink transition-colors shrink-0 mt-0.5",children:l.jsx(on,{size:16,strokeWidth:1.75})})]}),l.jsx("div",{className:"px-6 py-2 border-b border-line/60",children:l.jsxs("label",{className:"flex items-center gap-2 text-xs text-ink-muted cursor-pointer select-none py-1",children:[l.jsx("input",{type:"checkbox",checked:h,onChange:()=>s(h?new Set:new Set(e.map((p,x)=>x))),className:"rounded border-line text-accent focus:ring-accent w-3.5 h-3.5"}),a("import.selectAll"),l.jsx("span",{className:"ml-auto text-2xs text-ink-faint uppercase tracking-wider",children:e[0]?.source})]})}),l.jsx("ul",{className:"flex-1 overflow-y-auto py-1",children:e.map((p,x)=>l.jsx("li",{children:l.jsxs("label",{className:"flex items-center gap-3 px-6 py-2 hover:bg-wash transition-colors cursor-pointer select-none",children:[l.jsx("input",{type:"checkbox",checked:r.has(x),onChange:()=>d(x),className:"rounded border-line text-accent focus:ring-accent w-3.5 h-3.5 shrink-0"}),l.jsx(XA,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),l.jsx("span",{className:"text-sm text-ink truncate flex-1",children:p.title}),l.jsx("span",{className:"text-2xs text-ink-faint shrink-0",children:ve(a("import.messages"),{n:p.messageCount})})]})},x))}),l.jsxs("div",{className:"px-6 py-4 border-t border-line flex justify-end gap-2",children:[l.jsx("button",{onClick:t,className:"text-xs text-ink-muted hover:text-ink px-4 py-2 rounded-lg hover:bg-wash transition-colors",children:a("common.cancel")}),l.jsx("button",{onClick:()=>{m()},disabled:r.size===0||o,className:"text-xs bg-accent hover:bg-accent-strong text-white px-5 py-2 rounded-lg transition-colors disabled:opacity-30",children:o?"…":ve(a("import.confirm"),{n:r.size})})]})]})})}function _ce(e){const t=Date.now()-e,n=Math.floor(t/6e4);if(n<1)return Ne("switcher.justNow");if(n<60)return ve(Ne("switcher.minAgo"),{n});const a=Math.floor(n/60);if(a<24)return ve(Ne("switcher.hourAgo"),{n:a});const r=Math.floor(a/24);return r<30?ve(Ne("switcher.dayAgo"),{n:r}):new Date(e).toLocaleDateString(Aa.getState().lang==="zh"?"zh-CN":"en-US")}function Mce({onSwitched:e}){const t=Tt(),n=sn(A=>A.projects),a=sn(A=>A.activeId),r=sn(A=>A.switching),s=n.find(A=>A.id===a)?.kind==="paradigm",[o,u]=R.useState(!1),[d,h]=R.useState(null),[m,p]=R.useState(!1),[x,b]=R.useState(void 0),[y,w]=R.useState(null),[E,v]=R.useState(""),N=R.useRef(null),S=R.useRef(null),C=n.find(A=>A.id===a),I=n.filter(A=>!A.archived).sort((A,H)=>H.updatedAt-A.updatedAt).slice(0,7),O=async A=>{const{canvasUniqueness:H}=await pt(async()=>{const{canvasUniqueness:Y}=await import("./canonical-46lAq3XC.js");return{canvasUniqueness:Y}},[]),G=await H(A.id),D=G==="native"?"confirm.deleteNative":G==="diverged-mirror"?"confirm.deleteDiverged":"confirm.deletePristine";await oi({title:Ne("confirm.deleteCanvasTitle"),message:ve(Ne(D),{name:A.name}),confirmLabel:Ne("common.delete"),danger:G!=="pristine-mirror"})&&G7(A.id).then(e)};R.useEffect(()=>{if(!o)return;const A=H=>{S.current?.contains(H.target)||u(!1)};return window.addEventListener("mousedown",A),()=>window.removeEventListener("mousedown",A)},[o]);const _=async A=>{u(!1),await Wi(A),e(),pt(()=>import("./canonical-46lAq3XC.js"),[]).then(H=>H.unsubscribeOrphanedSessions()),pt(()=>Promise.resolve().then(()=>n7),void 0).then(H=>H.sweepRecentSessions())};return l.jsxs("div",{ref:S,className:"absolute top-4 left-4 z-20",children:[l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsxs("button",{onClick:()=>u(!o),disabled:r,className:"bg-card/90 backdrop-blur border border-line rounded-xl px-3.5 py-2 shadow-sm hover:bg-wash transition-colors flex items-center gap-2 text-sm text-ink max-w-[240px] disabled:opacity-60",children:[r?l.jsx(tn,{size:16,strokeWidth:1.75,className:"animate-spin shrink-0 text-accent"}):s?l.jsx(yF,{size:16,strokeWidth:1.75,className:"shrink-0 text-accent"}):l.jsx(pu,{size:16,strokeWidth:1.75,className:"shrink-0 text-ink-muted"}),l.jsx("span",{className:"truncate font-medium",children:C?.name??"…"}),l.jsx(ur,{size:14,strokeWidth:1.75,className:"shrink-0 text-ink-faint"})]}),l.jsx(Ace,{}),!!C?.sourceSession?.sessionId&&(()=>{const A=Hm.size>0&&!Hm.has(C.sourceSession.sessionId);return l.jsxs("button",{title:A?Ne("switcher.mirrorBadgeGone"):ve(Ne("switcher.mirrorBadge"),{runner:C.sourceSession.runner}),onClick:()=>{b(C.sourceSession.sessionId),p(!0)},className:`bg-card/90 backdrop-blur border border-line rounded-xl px-2 py-2 shadow-sm hover:bg-wash transition-colors text-2xs font-mono flex items-center gap-1 ${A?"text-ink-faint/50 line-through decoration-1":"text-ink-faint hover:text-accent"}`,"data-twin-badge":A?"unreachable":"live",children:["⇄ ",C.sourceSession.runner]})})()]}),o&&l.jsxs("div",{className:"mt-1.5 bg-card border border-line rounded-xl shadow-lg py-1.5 w-[320px] animate-fade-in",children:[l.jsx("div",{className:"max-h-[320px] overflow-y-auto",children:I.map(A=>l.jsx("div",{className:`group flex items-center gap-1 px-3 py-2 hover:bg-wash cursor-pointer transition-colors ${A.id===a?"bg-accent/5":""}`,onClick:()=>{y!==A.id&&A.id!==a&&_(A.id)},children:y===A.id?l.jsx("input",{autoFocus:!0,value:E,onChange:H=>v(H.target.value),onClick:H=>H.stopPropagation(),onKeyDown:H=>{H.key==="Enter"&&!ar(H)&&E.trim()&&(V7(A.id,E.trim()),w(null)),H.key==="Escape"&&w(null)},onBlur:()=>w(null),className:"flex-1 text-sm text-ink border border-accent/40 rounded-lg px-2 py-1 bg-surface focus:outline-none"}):l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsx("div",{className:`text-sm truncate ${A.id===a?"text-accent font-medium":"text-ink"}`,children:A.name}),l.jsxs("div",{className:"text-2xs text-ink-faint flex items-center gap-1.5",children:[l.jsx("span",{children:_ce(A.updatedAt)}),!!A.sourceSession?.sessionId&&l.jsx("span",{className:"font-mono border border-line rounded px-1 py-px","data-mirror-mark":!0,children:A.sourceSession.runner})]})]}),l.jsx("button",{title:t("switcher.rename"),className:"opacity-0 group-hover:opacity-100 text-ink-faint hover:text-ink p-1 rounded transition-all shrink-0",onClick:H=>{H.stopPropagation(),w(A.id),v(A.name)},children:l.jsx(Jl,{size:14,strokeWidth:1.75})}),l.jsx("button",{title:t("common.delete"),className:"opacity-0 group-hover:opacity-100 text-ink-faint hover:text-red-500 p-1 rounded transition-all shrink-0",onClick:H=>{H.stopPropagation(),O(A)},children:l.jsx(rr,{size:14,strokeWidth:1.75})}),l.jsx("button",{title:t("switcher.archive"),className:"opacity-0 group-hover:opacity-100 text-ink-faint hover:text-amber-600 p-1 rounded transition-all shrink-0",onClick:H=>{H.stopPropagation(),Vm(A.id,!0).then(e)},"data-archive-canvas":!0,children:l.jsx(rl,{size:14,strokeWidth:1.75})})]})},A.id))}),l.jsxs("div",{className:"border-t border-line mt-1 pt-1",children:[l.jsxs("button",{onClick:()=>{u(!1),Ip().then(e)},className:"w-full text-left px-3 py-2 text-sm text-accent hover:bg-wash transition-colors flex items-center gap-2",children:[l.jsx(W0,{size:15,strokeWidth:1.75})," ",t("switcher.newCanvas")]}),l.jsxs("button",{onClick:()=>N.current?.click(),className:"w-full text-left px-3 py-2 text-sm text-ink-muted hover:bg-wash transition-colors flex items-center gap-2",children:[l.jsx(lq,{size:15,strokeWidth:1.75})," ",t("switcher.importBackup")]}),l.jsxs("button",{onClick:()=>{u(!1),p(!0)},className:"w-full text-left px-3 py-2 text-sm text-ink-muted hover:bg-wash transition-colors flex items-center gap-2","data-open-atlas":!0,children:[l.jsx(dU,{size:15,strokeWidth:1.75})," ",t("switcher.allCanvases")]}),window.desktop&&l.jsxs("button",{onClick:()=>{u(!1),window.desktop.checkForUpdates()},className:"w-full text-left px-3 py-2 text-sm text-ink-muted hover:bg-wash transition-colors flex items-center gap-2","data-check-updates":!0,children:[l.jsx(cr,{size:15,strokeWidth:1.75})," ",t("update.checkMenu"),l.jsxs("span",{className:"ml-auto text-2xs text-ink-faint",children:["v",new URLSearchParams(window.location.search).get("dv")]})]}),l.jsx("input",{ref:N,type:"file",accept:".json,.jsonl,application/json",className:"hidden",onChange:A=>{const H=A.target.files?.[0];H&&kG(H).then(G=>{G.kind==="own"&&G.ok?(u(!1),e()):G.kind==="chat"&&(u(!1),h(G.conversations))}).catch(G=>{We("error",ve(Ne("toast.importFailedGeneric"),{msg:G instanceof Error?G.message:String(G)}))}),A.target.value=""}})]})]}),d&&l.jsx(Cce,{conversations:d,onClose:()=>h(null),onDone:()=>{h(null),e()}}),m&&l.jsx(Qv,{onClose:()=>{p(!1),b(void 0)},onSwitched:e,focusSessionId:x})]})}const Ice="JVBERi0xLjQKMSAwIG9iago8PCAvVHlwZSAvQ2F0YWxvZyAvUGFnZXMgMiAwIFIgPj4KZW5kb2JqCjIgMCBvYmoKPDwgL1R5cGUgL1BhZ2VzIC9LaWRzIFszIDAgUiA0IDAgUl0gL0NvdW50IDIgPj4KZW5kb2JqCjMgMCBvYmoKPDwgL1R5cGUgL1BhZ2UgL1BhcmVudCAyIDAgUiAvTWVkaWFCb3ggWzAgMCA1OTUgODQyXSAvQ29udGVudHMgNSAwIFIgL1Jlc291cmNlcyA8PCAvRm9udCA8PCAvRjEgNyAwIFIgL0YyIDggMCBSID4+ID4+ID4+CmVuZG9iago0IDAgb2JqCjw8IC9UeXBlIC9QYWdlIC9QYXJlbnQgMiAwIFIgL01lZGlhQm94IFswIDAgNTk1IDg0Ml0gL0NvbnRlbnRzIDYgMCBSIC9SZXNvdXJjZXMgPDwgL0ZvbnQgPDwgL0YxIDcgMCBSIC9GMiA4IDAgUiA+PiA+PiA+PgplbmRvYmoKNSAwIG9iago8PCAvTGVuZ3RoIDExMTIgPj4Kc3RyZWFtCkJUCi9GMiAxOSBUZiAxIDAgMCAxIDY0IDcyNS4wIFRtIChXaHkgU2F2ZWQgQXJ0aWNsZXMgU3RheSBVbnJlYWQpIFRqCi9GMSAxMSBUZiAxIDAgMCAxIDY0IDcwOC4wIFRtIChBIHNob3J0IGJyaWVmIG9uIGRpZ2l0YWwgaG9hcmRpbmcgYW5kIHRoZSBjb2xsZWN0b3IncyBmYWxsYWN5KSBUagovRjIgMTMgVGYgMSAwIDAgMSA2NCA2NjkuMCBUbSAoMS4gVGhlIHBoZW5vbWVub24pIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNjUxLjUgVG0gKFJlYWQtaXQtbGF0ZXIgc2VydmljZXMgcmVwb3J0IHRoYXQgbW9zdCBzYXZlZCBpdGVtcyBhcmUgbmV2ZXIpIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNjM0LjAgVG0gKHJlb3BlbmVkLiBBY3Jvc3MgcHVibGlzaGVkIHVzYWdlIHN0dWRpZXMsIHRoZSBzaGFyZSBvZiBzYXZlZCkgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA2MTYuNSBUbSAoYXJ0aWNsZXMgdGhhdCBnZXQgYSBzZWNvbmQgdmlzaXQgaXMgc21hbGwsIGFuZCBjb21wbGV0aW9uIHJhdGVzKSBUagovRjEgMTEuNSBUZiAxIDAgMCAxIDY0IDU5OS4wIFRtIChhcmUgc21hbGxlciBzdGlsbC4gVGhlIGFyY2hpdmUgZ3Jvd3M7IHRoZSByZWFkaW5nIGRvZXMgbm90LikgVGoKL0YyIDEzIFRmIDEgMCAwIDEgNjQgNTYwLjAgVG0gKDIuIFRoZSBjb2xsZWN0b3IncyBmYWxsYWN5KSBUagovRjEgMTEuNSBUZiAxIDAgMCAxIDY0IDU0Mi41IFRtIChDb2xsZWN0aW5nIHByb2R1Y2VzIGFuIGltbWVkaWF0ZSBzZW5zZSBvZiBwcm9ncmVzcyB3aGlsZSB0aGUpIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNTI1LjAgVG0gKHVuZGVyc3RhbmRpbmcgaXQgcHJvbWlzZXMgaXMgZGVmZXJyZWQuIFNhdmluZyBhIHRleHQgZmVlbHMgbGlrZSkgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA1MDcuNSBUbSAoYSBmaXJzdCBzdGVwIG9mIHJlYWRpbmcgaXQsIGJ1dCBubyBwYXJ0IG9mIHRoZSByZWFkaW5nIGhhcykgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA0OTAuMCBUbSAoaGFwcGVuZWQuKSBUagovRjIgMTEuNSBUZiAxIDAgMCAxIDY0IDQ3Mi41IFRtIChUaGUgYWN0IG9mIHNhdmluZyBpcyBtaXN0YWtlbiBmb3IgdGhlIGFjdCBvZiBsZWFybmluZy4pIFRqCkVUCmVuZHN0cmVhbQplbmRvYmoKNiAwIG9iago8PCAvTGVuZ3RoIDkwOCA+PgpzdHJlYW0KQlQKL0YyIDEzIFRmIDEgMCAwIDEgNjQgNzI1LjAgVG0gKDMuIFdoeSBpdCBwZXJzaXN0cykgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA3MDcuNSBUbSAoVGhlIGNvc3RzIGFyZSBhc3ltbWV0cmljOiBzYXZpbmcgdGFrZXMgb25lIHNlY29uZCBhbmQgcGF5cyBvdXQpIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNjkwLjAgVG0gKGEgc21hbGwgcmV3YXJkIG5vdzsgcmVhZGluZyB0YWtlcyBhbiBob3VyIGFuZCBwYXlzIG91dCBsYXRlci4pIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNjcyLjUgVG0gKEhhYml0cyBmb2xsb3cgdGhlIGNoZWFwZXIgbG9vcCwgc28gbGlicmFyaWVzIGluZmxhdGUgYnkgZGVmYXVsdC4pIFRqCi9GMiAxMyBUZiAxIDAgMCAxIDY0IDYzMy41IFRtICg0LiBXaGF0IGhlbHBzKSBUagovRjEgMTEuNSBUZiAxIDAgMCAxIDY0IDYxNi4wIFRtIChJbnRlcnZlbnRpb25zIHRoYXQgd29yayBtb3ZlIHByb2Nlc3NpbmcgdG8gdGhlIG1vbWVudCBvZiBjYXB0dXJlOikgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA1OTguNSBUbSAod3JpdGUgb25lIGxpbmUgaW4geW91ciBvd24gd29yZHMgYWJvdXQgd2h5IHRoZSBpdGVtIG1hdHRlcnMsIGFuZCkgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA1ODEuMCBUbSAoc2NoZWR1bGUgYSByZXZpZXcgcGFzcyBpbnN0ZWFkIG9mIHRydXN0aW5nIHRoZSBhcmNoaXZlIHRvKSBUagovRjEgMTEuNSBUZiAxIDAgMCAxIDY0IDU2My41IFRtIChyZXN1cmZhY2UgaXQuKSBUagovRjEgMTEuNSBUZiAxIDAgMCAxIDY0IDUzMi4wIFRtIChBIHNtYWxsZXIgbGlicmFyeSB0aGF0IGdldHMgcHJvY2Vzc2VkIGJlYXRzIGEgY29tcGxldGUgb25lIHRoYXQpIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNTE0LjUgVG0gKGRvZXMgbm90LikgVGoKRVQKZW5kc3RyZWFtCmVuZG9iago3IDAgb2JqCjw8IC9UeXBlIC9Gb250IC9TdWJ0eXBlIC9UeXBlMSAvQmFzZUZvbnQgL0hlbHZldGljYSA+PgplbmRvYmoKOCAwIG9iago8PCAvVHlwZSAvRm9udCAvU3VidHlwZSAvVHlwZTEgL0Jhc2VGb250IC9IZWx2ZXRpY2EtQm9sZCA+PgplbmRvYmoKeHJlZgowIDkKMDAwMDAwMDAwMCA2NTUzNSBmIAowMDAwMDAwMDA5IDAwMDAwIG4gCjAwMDAwMDAwNTggMDAwMDAgbiAKMDAwMDAwMDEyMSAwMDAwMCBuIAowMDAwMDAwMjU3IDAwMDAwIG4gCjAwMDAwMDAzOTMgMDAwMDAgbiAKMDAwMDAwMTU1NyAwMDAwMCBuIAowMDAwMDAyNTE2IDAwMDAwIG4gCjAwMDAwMDI1ODYgMDAwMDAgbiAKdHJhaWxlcgo8PCAvU2l6ZSA5IC9Sb290IDEgMCBSID4+CnN0YXJ0eHJlZgoyNjYxCiUlRU9G",Oce=`<!-- tdag-page:1 -->
704
+ `).length+1),className:"w-full bg-wash border border-accent rounded-lg p-2 text-sm text-ink resize-y focus:outline-none"}),l.jsxs("div",{className:"flex justify-end gap-2 mt-1",children:[l.jsx("button",{onClick:()=>b(null),className:"text-xs px-3 py-1 rounded-lg text-ink-muted hover:bg-wash",children:s("common.cancel")}),l.jsx("button",{onClick:()=>{C()},className:"text-xs px-3 py-1 rounded-lg bg-accent text-white",children:s("mp.save")})]})]}):l.jsx("ul",{className:"text-sm text-ink leading-relaxed space-y-0.5",children:A.map((H,G)=>l.jsxs("li",{className:"flex flex-wrap items-baseline gap-x-1.5",children:[l.jsx("span",{children:H.text}),H.src.map(D=>{const P=o.sources[D];return P?l.jsxs("button",{onClick:()=>{I(D)},title:`${P.title} · ${s("mp.sourceOpen")}`,className:"inline-flex items-center gap-0.5 font-mono text-2xs text-ink-faint border border-line rounded px-1 hover:text-accent hover:border-accent/40","data-mp-source":!0,children:[P.runner," · ",ri(P.at),P.kind==="turn"&&l.jsx(kp,{size:9})]},D):D.startsWith("filed:")?l.jsx("span",{className:"font-mono text-2xs text-ink-faint border border-line rounded px-1",children:s("mp.filedTag")},D):null})]},G))})]},_)}),!O&&!d&&l.jsx("p",{className:"text-xs text-ink-faint italic",children:E?.labeled?ve(s("mp.buildHint"),{n:E.labeled}):s("dossier.nothingToRead")}),!!o?.pending.length&&l.jsxs("div",{className:"text-2xs text-ink-muted border-t border-dashed border-line-strong pt-2","data-mp-dossier-pending":!0,children:[l.jsxs("div",{className:"text-ink-faint mb-0.5",children:[s("mp.pendingList")," · ",o.pending.length]}),o.pending.map(_=>l.jsxs("div",{children:[l.jsx("span",{className:"font-mono text-ink mr-2",children:ri(_.at)}),_.text]},_.id))]}),!!o?.changelog.length&&l.jsxs("div",{className:"text-2xs text-ink-muted border-t border-dashed border-line-strong pt-2",children:[l.jsx("div",{className:"text-ink-faint mb-0.5",children:s("mp.changelog")}),o.changelog.slice(-6).reverse().map((_,A)=>l.jsxs("div",{children:[l.jsx("span",{className:"font-mono text-ink mr-2",children:ri(_.at)}),_.note]},A))]})]})]})}function wce({query:e,onOpened:t}){const n=Tt(),a=ce(L=>L.recallEnabled),r=ce(L=>L.setRecallEnabled),s=ce(L=>L.memoryEnabled),o=ce(L=>L.setMemoryEnabled),u=ce(L=>L.profile),d=ce(L=>L.memoryInbox),[h,m]=R.useState(null),[p,x]=R.useState(null),[b,y]=R.useState(null),[w,E]=R.useState(null),[v,N]=R.useState(!1),[S,C]=R.useState(!1),[I,O]=R.useState(!1),[_,A]=R.useState(null),H=Ap();R.useEffect(()=>{R2()},[]);const[G,D]=R.useState(0),P=R.useCallback(()=>D(L=>L+1),[]);R.useEffect(()=>{const L=Rn();if(!L)return;let q=!0;return(async()=>{try{const[W,X]=await Promise.all([L.dossiers(),L.topics()]);if(!q)return;x(W),y(X);for(const B of W)B.built&&B.pending>=HW&&!ON.has(B.topicId)&&(ON.add(B.topicId),u7(B.topicId).then(()=>D($=>$+1)).catch(()=>{}))}catch{q&&x([])}})(),()=>{q=!1}},[G]),R.useEffect(()=>{!I||_!==null||Rn()?.memories().then(L=>A(L.length)).catch(()=>A(0))},[I,_]);const Y=R.useMemo(()=>({preferences:ss(u.preferences),identity:ss(u.identity)}),[u]),U=async(L,q)=>{const W=Rn(),X=d.find(B=>B.id===L);if(!(!W||!X))try{await W.dossierPending(q,{text:X.text,...X.from?{from:X.from}:{}}),CE(L),We("success",ve(n("mp.filed"),{name:b?.topics.find(B=>B.id===q)?.name??""})),P()}catch(B){We("error",bm(B))}},z=e.trim().length>=2;return l.jsxs("div",{"data-memory-page":!0,children:[z&&l.jsx(_M,{phrase:e,onOpened:t,dossiers:p??[],onOpenDossier:L=>E(L)}),z&&w&&l.jsx(jN,{topicId:w,name:p?.find(L=>L.topicId===w)?.name??"",onClose:()=>E(null),onChanged:P,onOpened:t}),!z&&l.jsxs("div",{className:"max-w-[860px]",children:[l.jsxs("section",{className:"mb-6","data-mp-section":"settings",children:[l.jsx("h4",{className:"text-2xs font-semibold uppercase tracking-wide text-ink-faint mb-1",children:n("mp.settings")}),l.jsxs("div",{className:"border-t border-line",children:[l.jsxs("div",{className:"flex items-center gap-4 py-2.5 border-b border-line",children:[l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsx("div",{className:"text-sm text-ink font-medium",children:n("mp.recallOn")}),l.jsx("div",{className:"text-2xs text-ink-faint",children:n("mp.recallOnHint")})]}),l.jsx(DN,{on:a,onChange:r,testId:"recall"})]}),l.jsxs("div",{className:"flex items-center gap-4 py-2.5 border-b border-line",children:[l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsx("div",{className:"text-sm text-ink font-medium",children:n("mp.memoryOn")}),l.jsx("div",{className:"text-2xs text-ink-faint",children:n("mp.memoryOnHint")})]}),l.jsx(DN,{on:s,onChange:o,testId:"memory"})]}),l.jsxs("div",{className:"flex items-center gap-4 py-2.5 border-b border-line",children:[l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsx("div",{className:"text-sm text-ink font-medium",children:n("mp.judgeRow")}),l.jsx("div",{className:"text-2xs text-ink-faint",children:n("mp.judgeRowHint")})]}),l.jsx("button",{onClick:()=>ce.getState().setApiKeyModalOpen(!0,"judge"),className:"text-xs text-accent hover:underline","data-judge-configure":!0,children:n("mp.open")})]})]})]}),l.jsxs("section",{className:"mb-6","data-mp-section":"you",children:[l.jsx("h4",{className:"text-2xs font-semibold uppercase tracking-wide text-ink-faint mb-1",children:n("mp.you")}),l.jsx("div",{className:"border-t border-line",children:["preferences","identity"].map(L=>l.jsxs("button",{onClick:()=>m(h===L?null:L),className:`w-full grid grid-cols-[110px_minmax(0,1fr)_auto] gap-3 items-center py-2.5 border-b border-line text-left hover:bg-wash -mx-2 px-2 ${h===L?"bg-wash":""}`,"data-mp-doc":L,children:[l.jsx("span",{className:"text-sm text-ink font-medium",children:n(L==="preferences"?"mp.preferences":"mp.identity")}),l.jsx("span",{className:"text-xs text-ink-muted truncate",children:Y[L].length?Y[L].join(" · "):n("mp.docEmpty")}),l.jsx("span",{className:"text-2xs text-ink-faint whitespace-nowrap",children:u[L].updatedAt?ve(n("mp.updatedAt"),{d:ri(u[L].updatedAt)}):""})]},L))}),h&&l.jsx(vce,{kind:h,onClose:()=>m(null)})]}),l.jsxs("section",{className:"mb-6","data-mp-section":"projects",children:[l.jsxs("div",{className:"flex items-center gap-3 mb-1",children:[l.jsx("h4",{className:"text-2xs font-semibold uppercase tracking-wide text-ink-faint",children:n("mp.projects")}),l.jsx("span",{className:"flex-1"}),H&&b&&b.topics.length>0&&l.jsxs("span",{className:"text-2xs text-ink-faint","data-mp-label-state":!0,children:[ve(n("mp.labelState"),{n:b.labeled,m:b.turns}),b.status.running?` · ${ve(n("topics.running"),{a:b.status.done,b:b.status.total})}`:""]}),H&&l.jsxs("button",{onClick:()=>N(L=>!L),className:"text-xs text-ink-muted hover:text-ink flex items-center gap-1 px-2 py-1 rounded-lg hover:bg-wash","data-mp-edit-topics":!0,children:[l.jsx(t8,{size:12,strokeWidth:1.75})," ",n("mp.editTopics")]})]}),H?l.jsxs(l.Fragment,{children:[v&&l.jsx("div",{className:"border border-line rounded-xl px-4 pb-3 mb-3 bg-surface",children:l.jsx(bce,{onOpened:t,onChanged:P})}),l.jsx("div",{className:"border-t border-line",children:p===null?l.jsx("div",{className:"py-3",children:l.jsx(tn,{size:14,className:"animate-spin text-ink-faint"})}):p.length===0?l.jsx("p",{className:"text-xs text-ink-faint italic py-2","data-mp-no-topics":!0,children:n("mp.noTopics")}):p.map(L=>l.jsxs("button",{onClick:()=>E(w===L.topicId?null:L.topicId),className:`w-full grid grid-cols-[150px_minmax(0,1fr)_auto] gap-3 items-center py-2.5 border-b border-line text-left hover:bg-wash -mx-2 px-2 ${w===L.topicId?"bg-wash":""}`,"data-mp-project":L.topicId,children:[l.jsx("span",{className:"text-sm text-ink font-medium truncate",children:L.name}),l.jsx("span",{className:"text-xs text-ink-muted truncate",children:L.built?L.lead:l.jsxs("span",{className:"text-ink-faint italic",children:[n("mp.notBuilt"),L.labeled?` · ${ve(n("mp.labeledTurns"),{n:L.labeled})}`:""]})}),l.jsxs("span",{className:"text-2xs text-ink-faint whitespace-nowrap flex items-center gap-1.5",children:[L.built&&L.newTurns>0&&l.jsx("span",{className:"px-1.5 py-px rounded-full border border-warm/60 text-warm bg-warm/10",children:ve(n("mp.newTurns"),{n:L.newTurns})}),L.pending>0&&l.jsx("span",{className:"px-1.5 py-px rounded-full border border-accent/40 text-accent bg-accent/10",children:ve(n("mp.pending"),{n:L.pending})}),L.built&&ve(n("mp.updatedAt"),{d:ri(L.updatedAt)})]})]},L.topicId))}),w&&!z&&l.jsx(jN,{topicId:w,name:p?.find(L=>L.topicId===w)?.name??"",onClose:()=>E(null),onChanged:P,onOpened:t})]}):l.jsx("p",{className:"text-xs text-ink-faint italic border-t border-line pt-2",children:n("mp.needIndex")}),d.length>0&&l.jsx(RN,{label:ve(n("mp.inbox"),{n:d.length}),open:S,onToggle:()=>C(L=>!L),testId:"inbox",children:l.jsx("div",{className:"space-y-1.5",children:d.map(L=>l.jsxs("div",{className:"flex items-center gap-2 text-xs","data-mp-inbox-item":!0,children:[l.jsx("span",{className:"flex-1 min-w-0 text-ink truncate",children:L.text}),l.jsxs("span",{className:"text-2xs text-ink-faint whitespace-nowrap",children:[L.from?`${L.from} · `:"",ri(L.at)]}),H&&!!b?.topics.length&&l.jsxs("select",{defaultValue:"",onChange:q=>{q.target.value&&U(L.id,q.target.value)},className:"text-2xs bg-wash border border-line rounded-md px-1.5 py-0.5","data-mp-inbox-file":!0,children:[l.jsx("option",{value:"",children:n("mp.fileTo")}),b.topics.map(q=>l.jsx("option",{value:q.id,children:q.name},q.id))]}),l.jsx("button",{onClick:()=>CE(L.id),className:"text-2xs text-ink-faint hover:text-red-500 px-1.5 py-0.5 rounded",children:n("mp.discard")})]},L.id))})})]}),H&&l.jsxs("section",{className:"mb-4","data-mp-section":"sources",children:[l.jsx("h4",{className:"text-2xs font-semibold uppercase tracking-wide text-ink-faint mb-1",children:n("mp.sources")}),l.jsxs(RN,{label:ve(n("mp.sourcesN"),{n:1+(_??0)}),open:I,onToggle:()=>O(L=>!L),testId:"sources",children:[l.jsxs("div",{className:"text-xs text-ink-muted mb-3 flex items-center gap-3",children:[l.jsx("span",{className:"text-ink font-medium",children:n("mp.index")}),l.jsx("span",{children:b?ve(n("mp.indexLine"),{n:b.turns}):"…"})]}),l.jsx(xce,{})]})]})]})]})}const UM="thoughtdag.atlas.watermark",Wo=e=>`${e.rootKey}:${e.rel}`;function Xv(){try{return JSON.parse(localStorage.getItem(UM)??"{}")}catch{return{}}}function lp(e){localStorage.setItem(UM,JSON.stringify(e))}function kce(e){const t=Xv(),n=new Map;if(Object.keys(t).length===0)return lp(Object.fromEntries(e.map(s=>[Wo(s),{mtime:s.mtime,size:s.size}]))),n;const a=new Set(e.map(Wo));let r=!1;for(const s of Object.keys(t))a.has(s)||(delete t[s],r=!0);for(const s of e){const o=t[Wo(s)];o?(s.size>o.size||s.mtime>o.mtime+1e3)&&n.set(Wo(s),{kind:"updated",deltaSize:Math.max(0,s.size-o.size)}):n.set(Wo(s),{kind:"new",deltaSize:s.size})}return r&&lp(t),n}function Ece(e){const t=Xv();t[Wo(e)]={mtime:e.mtime,size:e.size},lp(t)}function Sce(e){const t=Xv();for(const n of e)t[Wo(n)]={mtime:n.mtime,size:n.size};lp(t)}const Fc=Wo,Tb=e=>new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),LN=e=>e>1e6?`${(e/1e6).toFixed(1)} MB`:`${Math.max(1,Math.round(e/1024))} KB`,Nce={time:(e,t)=>t.mtime-e.mtime,name:(e,t)=>e.title.localeCompare(t.title),size:(e,t)=>t.size-e.size,runner:(e,t)=>e.runner.localeCompare(t.runner)||t.mtime-e.mtime};function Tce({roots:e,counts:t,onChanged:n,onClose:a}){const r=Tt(),s=L2(),o={"claude-projects":"Claude Code","codex-sessions":"Codex","dsh-sessions":"DeepSeek Harness","pi-sessions":"Pi"},[u,d]=R.useState(null),h=()=>{window.desktopSessions?.commandsStatus?.().then(d).catch(()=>{})};R.useEffect(h,[]);const m={"claude-code":"Claude Code",codex:"Codex",dsh:"DeepSeek Harness",pi:"Pi"},p=x=>l.jsxs("div",{className:"flex items-center gap-3 px-4 py-2.5 border-b border-line last:border-b-0","data-atlas-source":x.key,children:[l.jsx("input",{type:"checkbox",checked:!s.has(x.key),disabled:!x.exists,onChange:b=>{IW(x.key,!b.target.checked),n()},className:"shrink-0"}),l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsx("div",{className:"text-sm text-ink",children:o[x.key]??x.path.split("/").filter(Boolean).pop()}),l.jsx("div",{className:"text-2xs text-ink-faint truncate",children:x.path})]}),l.jsx("span",{className:"text-2xs text-ink-faint shrink-0",children:x.exists?t.get(x.key)??0:r("atlas.rootMissing")}),!x.builtin&&l.jsx("button",{className:"text-ink-faint hover:text-red-500 p-1 rounded transition-colors shrink-0",onClick:()=>{window.desktopSessions.removeRoot(x.key).then(n)},children:l.jsx(rr,{size:14,strokeWidth:1.75})})]},x.key);return l.jsx("div",{className:"absolute inset-0 z-10 bg-ink/20 flex items-center justify-center",onClick:a,children:l.jsxs("div",{className:"bg-surface border border-line rounded-2xl shadow-xl w-[440px] max-h-[80%] overflow-y-auto",onClick:x=>x.stopPropagation(),"data-atlas-sources-dialog":!0,children:[l.jsxs("div",{className:"px-4 pt-3.5 pb-2.5 border-b border-line",children:[l.jsx("div",{className:"text-sm font-semibold text-ink",children:r("atlas.sourcesTitle")}),l.jsx("div",{className:"text-2xs text-ink-muted mt-0.5",children:r("atlas.sourcesHint")})]}),e.filter(x=>x.builtin).map(p),u&&Object.values(u).some(x=>x.state!=="unavailable")&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"px-4 pt-3 pb-1.5 text-2xs uppercase tracking-wide text-ink-faint",children:r("atlas.handoffTitle")}),Object.entries(u).filter(([,x])=>x.state!=="unavailable").map(([x,b])=>l.jsxs("div",{className:"flex items-center gap-3 px-4 py-2.5 border-b border-line","data-atlas-handoff":x,"data-handoff-state":b.state,children:[l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsxs("div",{className:"text-sm text-ink flex items-center gap-2",children:[m[x]??x,l.jsx("code",{className:"text-2xs bg-wash border border-line rounded px-1.5 py-px font-mono",children:b.invoke})]}),l.jsx("div",{className:"text-2xs text-ink-faint truncate",children:r(b.state==="installed"?"atlas.handoffOn":b.state==="outdated"?"atlas.handoffOutdated":"atlas.handoffOff")})]}),b.state!=="installed"&&l.jsx("button",{className:"text-2xs bg-accent/10 text-accent hover:bg-accent/20 font-medium px-2.5 py-1 rounded-lg transition-colors shrink-0","data-handoff-install":!0,onClick:()=>{(async()=>{const{confirmDialog:y}=await pt(async()=>{const{confirmDialog:v}=await Promise.resolve().then(()=>gu);return{confirmDialog:v}},void 0);if(!await y({title:Ne("atlas.handoffEnableTitle"),message:ve(Ne("confirm.installCommand"),{path:b.dest}),confirmLabel:Ne(b.state==="outdated"?"atlas.handoffUpdate":"atlas.handoffEnable")}))return;const E=await window.desktopSessions.commandsInstall(x);E.ok?We("success",ve(Ne("atlas.handoffInstalled"),{cmd:b.invoke}),8e3):We("error",E.error??"install failed"),h()})()},children:r(b.state==="outdated"?"atlas.handoffUpdate":"atlas.handoffEnable")}),(b.state==="installed"||b.state==="outdated")&&l.jsx("button",{className:"text-ink-faint hover:text-red-500 p-1 rounded transition-colors shrink-0",title:r("atlas.handoffRemove"),"data-handoff-remove":!0,onClick:()=>{window.desktopSessions.commandsRemove(x).then(h)},children:l.jsx(rr,{size:14,strokeWidth:1.75})})]},x))]}),e.filter(x=>!x.builtin).map(p),l.jsxs("div",{className:"flex items-center gap-2 px-4 py-3",children:[l.jsxs("button",{onClick:n,className:"flex items-center gap-1.5 text-sm text-ink-muted hover:text-ink border border-line rounded-lg px-2.5 py-1.5 hover:bg-wash transition-colors",children:[l.jsx(cr,{size:13,strokeWidth:1.75})," ",r("atlas.autoDetect")]}),l.jsxs("button",{onClick:()=>{window.desktopSessions.addRoot().then(x=>{x&&n()})},className:"flex items-center gap-1.5 text-sm text-accent border border-line rounded-lg px-2.5 py-1.5 hover:bg-wash transition-colors","data-atlas-add-dir":!0,children:[l.jsx(QA,{size:13,strokeWidth:1.75})," ",r("atlas.addDir")]})]})]})})}function Qv({onClose:e,onSwitched:t,focusSessionId:n,initialTab:a}){const r=Tt(),[s,o]=R.useState(a??"sessions"),u=!!Rn(),d=sn(ie=>ie.projects),h=sn(ie=>ie.projects.find(Be=>Be.id===ie.activeId)?.sourceSession?.sessionId),m=!!window.desktopSessions,[p,x]=R.useState(null),[b,y]=R.useState([]),[w,E]=R.useState(!1),[v,N]=R.useState(window.desktopSessions?null:"canvases"),[S,C]=R.useState(null),[I,O]=R.useState(!1),[_,A]=R.useState(null),[H,G]=R.useState(new Map),[D,P]=R.useState(new Map),[Y,U]=R.useState(new Map),[z,L]=R.useState(!1),q=ie=>`${ie.rootKey}|${ie.rel}`,W=ie=>U(Be=>{const ot=new Map(Be),Ht=q(ie);return ot.has(Ht)?ot.delete(Ht):ot.set(Ht,ie),ot}),X=ie=>d.find(Be=>my(Be).includes(ie)),[B,$]=R.useState(""),[Z,K]=R.useState(new Set),[J,oe]=R.useState("time"),[me,ye]=R.useState(!1),[ae,ge]=R.useState(!1),[Te,Fe]=R.useState(new Map),[Me,Le]=R.useState(null);R.useEffect(()=>{window.desktopSessions?.openTargets().then(Le).catch(()=>{})},[]);const Ee=R.useMemo(()=>new Map((Me?.apps??[]).map(ie=>[ie.runner,ie.name])),[Me]),ze=async()=>{E(!0);try{y(await window.desktopSessions?.roots().catch(()=>[])??[]);const ie=await OW();if(x(ie),Fe(kce(ie)),window.desktopSessions?.codexThreads?.().then(Be=>{Be&&(G(new Map(Be.filter(ot=>ot.name&&ot.sessionId).map(ot=>[ot.sessionId,ot.name]))),P(new Map(Be.filter(ot=>ot.forkedFromId&&ot.sessionId).map(ot=>[ot.sessionId,ot.forkedFromId]))))}).catch(()=>{}),n){const Be=ie.find(ot=>ot.sessionId===n);Be&&N(Be.cwd??"")}}finally{E(!1)}};R.useEffect(()=>{ze()},[]),R.useEffect(()=>{let ie=!1;const Be=()=>{ie||w||(ie=!0,setTimeout(()=>{ie=!1,ze()},2e3))};return window.addEventListener("td:sessions-changed",Be),()=>window.removeEventListener("td:sessions-changed",Be)},[w]);const De=R.useCallback(ie=>H.get(ie.sessionId)??ie.title,[H]),tt=R.useMemo(()=>(p??[]).filter(ie=>!Z.has(ie.runner)&&(ae||!ie.subagent)&&(!me||Te.has(Fc(ie)))&&(!B.trim()||De(ie).toLowerCase().includes(B.trim().toLowerCase()))),[p,Z,B,me,Te,ae,De]),xt=R.useMemo(()=>DW(tt),[tt]),Ke=R.useMemo(()=>[...new Set((p??[]).map(ie=>ie.runner))].sort(),[p]),nt=R.useMemo(()=>{const ie=new Map;for(const Be of p??[])ie.set(Be.rootKey,(ie.get(Be.rootKey)??0)+1);return ie},[p]),st=v==="canvases"?null:xt.find(ie=>(ie.cwd??"")===(v??xt[0]?.cwd??""))??xt[0]??null,Ue=R.useMemo(()=>{if(!st)return[];const ie=J==="name"?(Be,ot)=>De(Be).localeCompare(De(ot)):Nce[J];return[...st.cards].sort(ie)},[st,J,De]),Rt=ie=>{Ece(ie),Fe(Be=>{const ot=new Map(Be);return ot.delete(Fc(ie)),ot})},lt=async ie=>{if(!S){C(ie.rel),Rt(ie);try{const{streamRunnerConversation:Be}=await pt(async()=>{const{streamRunnerConversation:Ft}=await import("./index-C4lWKzPK.js");return{streamRunnerConversation:Ft}},[]),{importOrAppendConversation:ot,shellSessionReader:Ht}=await pt(async()=>{const{importOrAppendConversation:Ft,shellSessionReader:ln}=await import("./canonical-Bkq2Xinv.js");return{importOrAppendConversation:Ft,shellSessionReader:ln}},[]),Wt=await Kc(await Be(Ht(ie.rootKey,ie.rel)),ie.rootKey,ie.rel,p),Vt=await ot(Wt);if(!Vt)throw new Error(Ne("handoff.notASession"));Vt.kind==="appended"?We("success",ve(Ne("atlas.appended"),{n:Vt.turns}),9e3):Vt.kind==="mounted"?We("success",ve(Ne(Vt.mode==="continue"?"atlas.mountedChapter":"atlas.mountedBranch"),{n:Vt.turns}),9e3):Vt.kind==="opened"?We("info",Ne("atlas.upToDate"),6e3):We("success",ve(Ne("toast.importedChats"),{n:1,m:Vt.nodeCount}),9e3),e(),t()}catch(Be){We("error",ve(Ne("atlas.parseFailed"),{msg:Be instanceof Error?Be.message:String(Be)}))}finally{C(null)}}},Dt=async ie=>{if(!(S||Y.size<2)){C("__merge__");try{const{streamRunnerConversation:Be}=await pt(async()=>{const{streamRunnerConversation:Ft}=await import("./index-C4lWKzPK.js");return{streamRunnerConversation:Ft}},[]),{mergeSessionsIntoProject:ot,shellSessionReader:Ht}=await pt(async()=>{const{mergeSessionsIntoProject:Ft,shellSessionReader:ln}=await import("./canonical-Bkq2Xinv.js");return{mergeSessionsIntoProject:Ft,shellSessionReader:ln}},[]),Wt=[];for(const Ft of Y.values())Wt.push(await Kc(await Be(Ht(Ft.rootKey,Ft.rel)),Ft.rootKey,Ft.rel,p)),Rt(Ft);const Vt=await ot(Wt,ie);if(!Vt)throw new Error(Ne("handoff.notASession"));We("success",ve(Ne("atlas.merged"),{n:Vt.mounted}),1e4),Vt.skipped>0&&We("info",ve(Ne("atlas.mergeSkippedInfo"),{n:Vt.skipped}),8e3),U(new Map),e(),t()}catch(Be){We("error",ve(Ne("atlas.parseFailed"),{msg:Be instanceof Error?Be.message:String(Be)}))}finally{C(null)}}},_e=async ie=>{const Be=sn.getState().projects.find(Wt=>Wt.sourceSession?.sessionId===ie.sessionId);if(!Be||S)return;const{confirmDialog:ot}=await pt(async()=>{const{confirmDialog:Wt}=await Promise.resolve().then(()=>gu);return{confirmDialog:Wt}},void 0);if(await ot({title:Ne("confirm.recastTitle"),message:ve(Ne("confirm.recast"),{name:Be.name}),confirmLabel:Ne("confirm.recastTitle"),danger:!0})){C(ie.rel);try{const{streamRunnerConversation:Wt}=await pt(async()=>{const{streamRunnerConversation:Dn}=await import("./index-C4lWKzPK.js");return{streamRunnerConversation:Dn}},[]),{importOrAppendConversation:Vt,shellSessionReader:Ft}=await pt(async()=>{const{importOrAppendConversation:Dn,shellSessionReader:qa}=await import("./canonical-Bkq2Xinv.js");return{importOrAppendConversation:Dn,shellSessionReader:qa}},[]),ln=await Kc(await Wt(Ft(ie.rootKey,ie.rel)),ie.rootKey,ie.rel,p);if(!ln)throw new Error(Ne("handoff.notASession"));const{deleteProject:$t}=await pt(async()=>{const{deleteProject:Dn}=await Promise.resolve().then(()=>Na);return{deleteProject:Dn}},void 0);if(await $t(Be.id),!await Vt(ln))throw new Error(Ne("handoff.notASession"));We("success",Ne("atlas.recastDone"),8e3),e(),t()}catch(Wt){We("error",ve(Ne("atlas.parseFailed"),{msg:Wt instanceof Error?Wt.message:String(Wt)}))}finally{C(null)}}},Qe=async(ie,Be)=>{const ot=await window.desktopSessions.openInCli(ie.runner,ie.cwd,ie.sessionId,Be).catch(()=>({opened:!1,via:"",command:""}));ot.opened&&ot.via==="app"?(await navigator.clipboard.writeText(ie.sessionId).catch(()=>{}),We("success",Ne("atlas.appOpened"),9e3)):ot.opened?We("success",Ne("atlas.opened")):ot.command&&(await navigator.clipboard.writeText(ot.command).catch(()=>{}),We("info",Ne("atlas.cmdCopied"),9e3))};return dr.createPortal(l.jsx("div",{className:"fixed inset-0 z-50 bg-ink/30 backdrop-blur-sm flex items-center justify-center p-6","data-session-atlas":!0,children:l.jsxs("div",{className:"bg-surface border border-line rounded-2xl shadow-2xl w-full max-w-[980px] h-[min(680px,90vh)] flex flex-col overflow-hidden",children:[l.jsxs("div",{className:"flex items-start gap-3 px-5 pt-4 pb-3 border-b border-line",children:[l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsx("div",{className:"text-base font-semibold text-ink",children:r(s==="memory"?"memory.managerTitle":"atlas.title")}),l.jsx("div",{className:"text-xs text-ink-muted mt-0.5",children:r(s==="memory"?"mp.subtitle":"atlas.subtitle")}),Te.size>0&&l.jsxs("div",{className:"text-xs mt-1 flex items-center gap-2","data-atlas-changes":!0,children:[l.jsx("span",{className:"text-accent",children:ve(r("atlas.changesSummary"),{n:[...Te.values()].filter(ie=>ie.kind==="new").length,m:[...Te.values()].filter(ie=>ie.kind==="updated").length})}),l.jsx("button",{className:"text-ink-faint hover:text-ink underline decoration-dotted transition-colors",onClick:()=>{Sce(p??[]),Fe(new Map)},"data-atlas-mark-all":!0,children:r("atlas.markAllSeen")})]})]}),m&&Me&&Me.terminals.length>0&&l.jsxs("label",{className:"flex items-center gap-1.5 text-sm text-ink-muted border border-line rounded-lg px-2.5 py-1.5 cursor-pointer",title:r("atlas.terminalChoice"),children:[l.jsx(Qo,{size:14,strokeWidth:1.75}),l.jsxs("select",{value:Me.prefs.terminal,onChange:ie=>{const Be=ie.target.value;if(Be==="__add__"){window.desktopSessions?.addTerminal().then(()=>window.desktopSessions?.openTargets().then(Le));return}window.desktopSessions?.setOpenPrefs({terminal:Be}).then(ot=>Le(Ht=>Ht&&{...Ht,prefs:ot}))},className:"bg-transparent focus:outline-none text-sm text-ink cursor-pointer","data-atlas-terminal-select":!0,children:[Me.terminals.map(ie=>l.jsx("option",{value:ie.id,children:ie.name},ie.id)),Me.canAddCustom&&l.jsx("option",{value:"__add__",children:r("atlas.otherTerminal")})]})]}),m&&l.jsxs("button",{onClick:()=>O(!0),hidden:s==="memory",className:"flex items-center gap-1.5 text-sm text-ink-muted hover:text-ink border border-line rounded-lg px-2.5 py-1.5 hover:bg-wash transition-colors","data-atlas-sources":!0,children:[l.jsx(QA,{size:14,strokeWidth:1.75})," ",r("atlas.sources")]}),m&&s!=="memory"&&l.jsxs("button",{onClick:()=>{ze()},disabled:w,className:"flex items-center gap-1.5 text-sm text-ink-muted hover:text-ink border border-line rounded-lg px-2.5 py-1.5 hover:bg-wash transition-colors disabled:opacity-60","data-atlas-refresh":!0,children:[w?l.jsx(tn,{size:14,className:"animate-spin"}):l.jsx(cr,{size:14,strokeWidth:1.75}),r(w?"atlas.scanning":"atlas.refresh")]}),l.jsx("button",{onClick:e,className:"text-ink-faint hover:text-ink p-1.5 rounded-lg hover:bg-wash transition-colors","data-atlas-close":!0,children:l.jsx(on,{size:18,strokeWidth:1.75})})]}),l.jsxs("div",{className:"flex items-center gap-3 px-5 py-2 border-b border-line shrink-0","data-atlas-tabs":!0,children:[l.jsx("div",{className:"flex items-center bg-wash rounded-lg p-0.5 shrink-0",children:["sessions","memory"].map(ie=>l.jsx("button",{onClick:()=>o(ie),className:`text-xs px-3 py-1 rounded-md transition-colors ${s===ie?"bg-card text-ink shadow-sm font-medium":"text-ink-muted hover:text-ink"}`,"data-atlas-tab":ie,"aria-pressed":s===ie,children:r(ie==="sessions"?"atlas.tabSessions":"atlas.tabMemory")},ie))}),u&&l.jsxs("div",{className:"flex items-center gap-1.5 border border-line rounded-lg px-2.5 py-1 bg-card flex-1 max-w-[520px]",children:[l.jsx(y0,{size:13,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),l.jsx("input",{value:B,onChange:ie=>$(ie.target.value),placeholder:r("atlas.searchPlaceholder"),className:"text-sm bg-transparent focus:outline-none w-full text-ink placeholder:text-ink-faint","data-atlas-search":!0})]})]}),s==="memory"?l.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-5 py-4","data-atlas-memory":!0,children:l.jsx(wce,{query:u?B:"",onOpened:()=>{e(),t()}})}):l.jsxs("div",{className:"flex-1 flex min-h-0",children:[l.jsxs("div",{className:"w-[260px] border-r border-line overflow-y-auto py-2 shrink-0",children:[l.jsx("div",{className:"px-4 py-1 text-2xs uppercase tracking-wide text-ink-faint",children:r("atlas.recent")}),d.filter(ie=>!ie.archived).sort((ie,Be)=>Be.updatedAt-ie.updatedAt).slice(0,6).map(ie=>l.jsxs("button",{onClick:()=>{e(),Wi(ie.id).then(t)},className:"w-full text-left px-4 py-1.5 flex items-center gap-2 text-ink hover:bg-wash transition-colors","data-atlas-recent":ie.id,children:[ie.sourceSession?.sessionId?l.jsx("span",{className:"text-2xs font-mono border border-line rounded px-1 py-px shrink-0 text-ink-faint",children:ie.sourceSession.runner}):l.jsx(eE,{size:13,strokeWidth:1.75,className:"shrink-0 text-ink-faint"}),l.jsx("span",{className:"flex-1 truncate text-sm",children:ie.name})]},ie.id)),l.jsx("div",{className:"border-t border-line mt-2 pt-2 px-4 py-1 text-2xs uppercase tracking-wide text-ink-faint",children:r("atlas.folders")}),!m&&l.jsx("div",{className:"px-4 py-2 text-xs text-ink-faint",children:r("atlas.webNoScan")}),m&&p===null&&l.jsxs("div",{className:"px-4 py-2 text-sm text-ink-faint flex items-center gap-2",children:[l.jsx(tn,{size:14,className:"animate-spin"})," ",r("atlas.scanning")]}),m&&p!==null&&xt.length===0&&l.jsx("div",{className:"px-4 py-2 text-xs text-ink-faint",children:r("atlas.empty")}),xt.map(ie=>{const Be=ie.cwd??"",ot=v!=="canvases"&&st===ie;return l.jsxs("button",{onClick:()=>N(Be),className:`w-full text-left px-4 py-2 flex items-center gap-2 transition-colors ${ot?"bg-accent/5 text-accent":"text-ink hover:bg-wash"}`,"data-atlas-folder":ie.name||"unfiled",children:[ot?l.jsx(pu,{size:15,strokeWidth:1.75,className:"shrink-0"}):l.jsx(PF,{size:15,strokeWidth:1.75,className:"shrink-0 text-ink-faint"}),l.jsx("span",{className:"flex-1 truncate text-sm",children:ie.name||r("atlas.unfiled")}),(()=>{const Ht=ie.cards.filter(Wt=>Te.has(Fc(Wt))).length;return Ht>0?l.jsxs("span",{className:"text-2xs text-accent shrink-0","data-atlas-folder-changes":!0,children:["+",Ht]}):null})(),l.jsx("span",{className:"text-2xs text-ink-faint shrink-0",children:ie.cards.length})]},Be)}),l.jsx("div",{className:"border-t border-line mt-2 pt-2",children:l.jsxs("button",{onClick:()=>N("canvases"),className:`w-full text-left px-4 py-2 flex items-center gap-2 transition-colors ${v==="canvases"?"bg-accent/5 text-accent":"text-ink hover:bg-wash"}`,"data-atlas-canvases":!0,children:[l.jsx(eE,{size:15,strokeWidth:1.75,className:"shrink-0"}),l.jsx("span",{className:"flex-1 truncate text-sm",children:r("atlas.myCanvases")}),l.jsx("span",{className:"text-2xs text-ink-faint shrink-0",children:d.length})]})})]}),l.jsxs("div",{className:"flex-1 overflow-y-auto p-4",children:[u&&B.trim().length>=2&&l.jsx(_M,{phrase:B,onOpened:()=>{e(),t()}}),v==="canvases"?l.jsxs("div",{className:"space-y-1.5",children:[d.filter(ie=>!ie.archived).sort((ie,Be)=>Be.updatedAt-ie.updatedAt).map(ie=>l.jsxs("div",{className:"group flex items-center flex-wrap gap-2 border border-line rounded-xl px-4 py-3 hover:bg-wash transition-colors cursor-pointer",onClick:()=>{e(),Wi(ie.id).then(t)},children:[l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsx("div",{className:"text-sm text-ink font-medium truncate",children:ie.name}),l.jsxs("div",{className:"text-2xs text-ink-faint mt-0.5 flex items-center gap-1.5",children:[l.jsx("span",{children:Tb(ie.updatedAt)}),!!ie.sourceSession?.sessionId&&l.jsx("span",{className:"font-mono border border-line rounded px-1 py-px",children:ie.sourceSession.runner})]})]}),l.jsx("button",{title:r("switcher.archive"),className:"opacity-0 group-hover:opacity-100 text-ink-faint hover:text-amber-600 p-1.5 rounded transition-all shrink-0",onClick:Be=>{Be.stopPropagation(),Vm(ie.id,!0)},"data-atlas-archive":!0,children:l.jsx(rl,{size:15,strokeWidth:1.75})}),!!ie.sourceSession&&my(ie).length>0&&l.jsxs("div",{className:"w-full basis-full text-2xs text-ink-faint font-mono flex flex-wrap gap-x-3 gap-y-0.5 pt-1","data-atlas-cluster":!0,children:[ie.sourceSession.sessionId&&l.jsxs("span",{children:["◉ ",ie.sourceSession.runner," ",ie.sourceSession.sessionId.slice(0,8)," · ",ve(r("atlas.turnsN"),{n:ie.sourceSession.importedCount})]}),(ie.sourceSession.chapters??[]).map(Be=>l.jsxs("span",{children:["↳ ",Be.runner," ",Be.sessionId.slice(0,8)," · ",ve(r("atlas.turnsN"),{n:Be.importedCount})]},Be.sessionId)),(ie.sourceSession.branches??[]).map(Be=>l.jsxs("span",{children:["⑂ ",Be.runner," ",Be.sessionId.slice(0,8)," · ",ve(r("atlas.turnsN"),{n:Be.importedCount})]},Be.sessionId))]})]},ie.id)),d.some(ie=>ie.archived)&&l.jsxs("details",{className:"pt-2","data-atlas-archived-group":!0,children:[l.jsx("summary",{className:"text-2xs uppercase tracking-wide text-ink-faint cursor-pointer px-1 py-1",children:ve(r("atlas.archivedGroup"),{n:d.filter(ie=>ie.archived).length})}),l.jsx("div",{className:"space-y-1.5 mt-1.5",children:d.filter(ie=>ie.archived).sort((ie,Be)=>Be.updatedAt-ie.updatedAt).map(ie=>l.jsxs("button",{title:r("atlas.restoreOpen"),onClick:()=>{Vm(ie.id,!1).then(()=>{e(),Wi(ie.id).then(t)})},className:"w-full text-left border border-dashed border-line rounded-xl px-4 py-2.5 hover:bg-wash transition-colors opacity-70 hover:opacity-100","data-atlas-archived-item":!0,children:[l.jsxs("div",{className:"text-sm text-ink truncate flex items-center gap-1.5",children:[l.jsx("span",{className:"truncate",children:ie.name}),!!ie.sourceSession?.sessionId&&l.jsx("span",{className:"text-2xs font-mono border border-line rounded px-1 py-px shrink-0 text-ink-faint",children:ie.sourceSession.runner})]}),l.jsx("div",{className:"text-2xs text-ink-faint mt-0.5",children:Tb(ie.updatedAt)})]},ie.id))})]})]}):l.jsxs(l.Fragment,{children:[(p?.length??0)>0&&l.jsxs("div",{className:"flex items-center gap-2 mb-3 flex-wrap",children:[!u&&l.jsxs("div",{className:"flex items-center gap-1.5 border border-line rounded-lg px-2 py-1 bg-card",children:[l.jsx(y0,{size:13,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),l.jsx("input",{value:B,onChange:ie=>$(ie.target.value),placeholder:r("atlas.filterTitle"),className:"text-sm bg-transparent focus:outline-none w-[150px] text-ink placeholder:text-ink-faint","data-atlas-filter":!0})]}),Ke.map(ie=>l.jsx("button",{onClick:()=>K(Be=>{const ot=new Set(Be);return ot.has(ie)?ot.delete(ie):ot.add(ie),ot}),className:`text-2xs font-mono border rounded-lg px-2 py-1 transition-colors ${Z.has(ie)?"border-line text-ink-faint line-through":"border-accent/40 text-accent bg-accent/5"}`,"data-atlas-runner-toggle":ie,children:ie},ie)),Te.size>0&&l.jsx("button",{onClick:()=>ye(ie=>!ie),className:`text-2xs border rounded-lg px-2 py-1 transition-colors ${me?"border-accent text-white bg-accent":"border-line text-ink-muted hover:text-ink"}`,"data-atlas-only-changed":!0,children:r("atlas.onlyChanged")}),(p??[]).some(ie=>ie.subagent)&&l.jsx("button",{onClick:()=>ge(ie=>!ie),className:`text-2xs border rounded-lg px-2 py-1 transition-colors ${ae?"border-accent text-accent bg-accent/5":"border-line text-ink-faint hover:text-ink"}`,"data-atlas-show-sub":!0,children:r("atlas.showSub")}),l.jsxs("button",{onClick:()=>oe(ie=>({time:"name",name:"size",size:"runner",runner:"time"})[ie]),className:"ml-auto flex items-center gap-1.5 text-2xs text-ink-muted hover:text-ink border border-line rounded-lg px-2 py-1 hover:bg-wash transition-colors","data-atlas-sort":!0,children:[l.jsx(jH,{size:12,strokeWidth:1.75}),r(`atlas.sort${J[0].toUpperCase()}${J.slice(1)}`)]})]}),st?l.jsxs(l.Fragment,{children:[st.cwd&&l.jsxs("div",{className:"text-2xs text-ink-faint mb-3 truncate",children:[st.cwd," · ",ve(r("atlas.sessions"),{n:st.cards.length})]}),l.jsx("div",{className:"space-y-1.5",children:Ue.map(ie=>l.jsxs("div",{className:`group border rounded-xl px-4 py-3 hover:bg-wash transition-colors cursor-pointer flex items-center gap-3 ${Y.has(q(ie))?"border-accent/60 bg-accent/5":"border-line"}`,onClick:()=>{lt(ie)},"data-atlas-session":ie.sessionId,children:[l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsxs("div",{className:"text-sm text-ink truncate flex items-center gap-1.5",children:[l.jsx("span",{className:"truncate",children:De(ie)}),D.has(ie.sessionId)&&l.jsx("span",{className:"text-2xs text-ink-faint border border-line rounded px-1 py-px shrink-0 font-mono",title:`⑂ ${D.get(ie.sessionId)}`,"data-atlas-fork":!0,children:"⑂"}),Te.get(Fc(ie))?.kind==="new"&&l.jsx("span",{className:"text-2xs text-white bg-accent rounded px-1 py-px shrink-0","data-atlas-badge":"new",children:r("atlas.badgeNew")}),Te.get(Fc(ie))?.kind==="updated"&&l.jsxs("span",{className:"text-2xs text-accent border border-accent/40 rounded px-1 py-px shrink-0","data-atlas-badge":"updated",children:["+",LN(Te.get(Fc(ie)).deltaSize)]}),ie.sessionId===h?l.jsx("span",{className:"text-2xs text-white bg-ink rounded px-1 py-px shrink-0","data-atlas-badge":"current",children:r("atlas.currentOpen")}):(()=>{const Be=X(ie.sessionId);return Be?l.jsx("span",{className:"text-2xs text-ink-faint border border-line rounded px-1 py-px shrink-0",title:Be.name,"data-atlas-badge":"canvas",children:r("atlas.onCanvas")}):null})()]}),l.jsxs("div",{className:"text-2xs text-ink-faint mt-0.5 flex items-center gap-2",children:[l.jsx("span",{className:"border border-line rounded px-1 py-px font-mono",children:ie.runner}),l.jsx("span",{children:Tb(ie.mtime)}),l.jsx("span",{children:LN(ie.size)})]})]}),S===ie.rel?l.jsx(tn,{size:16,className:"animate-spin text-accent shrink-0"}):l.jsxs("div",{className:`${Y.has(q(ie))?"":"opacity-0 group-hover:opacity-100"} transition-opacity flex items-center gap-1 shrink-0`,children:[!X(ie.sessionId)&&!!ie.sessionId&&l.jsx("button",{title:r("atlas.pickForMerge"),className:`p-1.5 rounded transition-colors ${Y.has(q(ie))?"text-accent":"text-ink-faint hover:text-accent"}`,onClick:Be=>{Be.stopPropagation(),W(ie)},"data-atlas-pick":Y.has(q(ie))?"on":"off",children:Y.has(q(ie))?l.jsx(KU,{size:16,strokeWidth:1.75}):l.jsx(V0,{size:16,strokeWidth:1.75})}),l.jsx("span",{title:r("atlas.import"),className:"text-ink-faint hover:text-accent p-1.5",children:l.jsx(ZF,{size:16,strokeWidth:1.75})}),d.some(Be=>Be.sourceSession?.sessionId===ie.sessionId)&&l.jsx("button",{title:r("atlas.recast"),className:"text-ink-faint hover:text-red-500 p-1.5 rounded transition-colors",onClick:Be=>{Be.stopPropagation(),_e(ie)},"data-atlas-recast":!0,children:l.jsx(ZA,{size:16,strokeWidth:1.75})}),!X(ie.sessionId)&&l.jsx("button",{title:r("atlas.mountTo"),className:"text-ink-faint hover:text-accent p-1.5 rounded transition-colors",onClick:Be=>{Be.stopPropagation(),A(ie)},"data-atlas-mount":!0,children:l.jsx(Xi,{size:16,strokeWidth:1.75})}),Ee.has(ie.runner)&&l.jsx("button",{title:ve(r("atlas.openApp"),{name:Ee.get(ie.runner)}),className:"text-ink-faint hover:text-accent p-1.5 rounded transition-colors",onClick:Be=>{Be.stopPropagation(),Qe(ie,"app")},"data-atlas-open-app":!0,children:l.jsx(IH,{size:16,strokeWidth:1.75})}),l.jsx("button",{title:r("atlas.openTerminal"),className:"text-ink-faint hover:text-accent p-1.5 rounded transition-colors",onClick:Be=>{Be.stopPropagation(),Qe(ie,"terminal")},"data-atlas-open-cli":!0,children:l.jsx(Qo,{size:16,strokeWidth:1.75})})]})]},ie.rel))})]}):l.jsx("div",{className:"py-16 text-center text-sm text-ink-faint",children:p===null?r("atlas.scanning"):p.length>0?r("atlas.filteredOut"):r("atlas.empty")})]})]})]}),Y.size>=2&&!z&&l.jsxs("div",{className:"absolute bottom-5 left-1/2 -translate-x-1/2 z-10 bg-surface border border-line rounded-xl shadow-lg px-4 py-2.5 flex items-center gap-3","data-atlas-merge-bar":!0,children:[l.jsx("span",{className:"text-xs text-ink-muted whitespace-nowrap",children:ve(r("atlas.mergeSelected"),{n:Y.size})}),S==="__merge__"?l.jsx(tn,{size:15,className:"animate-spin text-accent"}):l.jsxs(l.Fragment,{children:[l.jsx("button",{className:"text-xs bg-accent hover:bg-accent-strong text-white font-medium px-3 py-1.5 rounded-lg transition-colors whitespace-nowrap",onClick:()=>{Dt()},"data-atlas-merge-new":!0,children:r("atlas.mergeNew")}),l.jsx("button",{className:"text-xs text-ink-muted hover:text-ink hover:bg-wash font-medium px-3 py-1.5 rounded-lg transition-colors whitespace-nowrap",onClick:()=>L(!0),"data-atlas-merge-into":!0,children:r("atlas.mergeInto")})]}),l.jsx("button",{className:"text-ink-faint hover:text-ink p-1",onClick:()=>U(new Map),title:r("common.cancel"),children:l.jsx(on,{size:14,strokeWidth:1.75})})]}),(_||z)&&l.jsx("div",{className:"absolute inset-0 z-10 bg-ink/20 flex items-center justify-center",onClick:()=>{A(null),L(!1)},children:l.jsxs("div",{className:"bg-surface border border-line rounded-2xl shadow-xl w-[400px] max-h-[70%] overflow-y-auto",onClick:ie=>ie.stopPropagation(),"data-atlas-mount-picker":!0,children:[l.jsxs("div",{className:"px-4 pt-3.5 pb-2.5 border-b border-line",children:[l.jsx("div",{className:"text-sm font-semibold text-ink",children:r(z?"atlas.mergeInto":"atlas.mountTo")}),l.jsx("div",{className:"text-2xs text-ink-muted mt-0.5",children:r(z?"atlas.mergeSelected":"atlas.mountHint").replace("{n}",String(Y.size))})]}),d.filter(ie=>!ie.archived&&ie.kind!=="paradigm").sort((ie,Be)=>Be.updatedAt-ie.updatedAt).map(ie=>l.jsx("button",{className:"w-full text-left px-4 py-2.5 text-sm text-ink hover:bg-wash transition-colors border-b border-line last:border-b-0",onClick:()=>{if(z){L(!1),Dt(ie.id);return}const Be=_;A(null),(async()=>{C(Be.rel);try{const{streamRunnerConversation:ot}=await pt(async()=>{const{streamRunnerConversation:ln}=await import("./index-C4lWKzPK.js");return{streamRunnerConversation:ln}},[]),{mountConversationToProject:Ht,shellSessionReader:Wt}=await pt(async()=>{const{mountConversationToProject:ln,shellSessionReader:$t}=await import("./canonical-Bkq2Xinv.js");return{mountConversationToProject:ln,shellSessionReader:$t}},[]),Vt=await Kc(await ot(Wt(Be.rootKey,Be.rel)),Be.rootKey,Be.rel,p),Ft=await Ht(Vt,ie.id);if(!Ft)throw new Error(Ne("handoff.notASession"));We("success",ve(Ne("atlas.mountedChapter"),{n:Ft.kind==="mounted"||Ft.kind==="appended"?Ft.turns:0}),9e3),e(),t()}catch(ot){We("error",ve(Ne("atlas.parseFailed"),{msg:ot instanceof Error?ot.message:String(ot)}))}finally{C(null)}})()},children:ie.name},ie.id))]})}),I&&l.jsx(Tce,{roots:b,counts:nt,onChanged:()=>{ze()},onClose:()=>O(!1)})]})}),document.body)}function Ace(){const e=Tt(),t=ce(a=>!!a.harnessHost?.bar);if(!q$||t)return null;const n=()=>window.parent.postMessage({source:"dsh-thoughtdag",type:"td:close"},window.location.origin);return l.jsxs("div",{className:"bg-card/90 backdrop-blur border border-line rounded-xl p-0.5 shadow-sm flex items-center",role:"group","aria-label":"view switch","data-harness-view-switch":!0,children:[l.jsx("button",{type:"button",onClick:n,className:"h-8 px-3 rounded-[10px] text-xs font-semibold text-ink-muted hover:bg-wash hover:text-ink transition-colors whitespace-nowrap","data-view":"dialog","aria-pressed":!1,children:e("harness.viewChat")}),l.jsx("button",{type:"button",className:"h-8 px-3 rounded-[10px] text-xs font-semibold bg-ink text-card whitespace-nowrap cursor-default","data-view":"map","aria-pressed":!0,children:e("harness.viewMap")})]})}function Cce({conversations:e,onClose:t,onDone:n}){const a=Tt(),[r,s]=R.useState(new Set),[o,u]=R.useState(!1),d=p=>{s(x=>{const b=new Set(x);return b.has(p)?b.delete(p):b.add(p),b})},h=r.size===e.length,m=async()=>{r.size===0||o||(u(!0),await SG([...r].sort((p,x)=>p-x).map(p=>e[p])),u(!1),n())};return l.jsx("div",{className:"fixed inset-0 z-50 bg-ink/30 backdrop-blur-sm flex items-center justify-center p-6",onClick:t,children:l.jsxs("div",{className:"bg-card border border-line rounded-2xl shadow-2xl w-full max-w-lg max-h-[80vh] flex flex-col",onClick:p=>p.stopPropagation(),children:[l.jsxs("div",{className:"px-6 py-4 border-b border-line flex items-start justify-between gap-4",children:[l.jsxs("div",{children:[l.jsx("h2",{className:"text-base font-semibold text-ink",children:a("import.title")}),l.jsx("p",{className:"text-xs text-ink-muted mt-1 leading-relaxed",children:a("import.subtitle")})]}),l.jsx("button",{onClick:t,className:"text-ink-faint hover:text-ink transition-colors shrink-0 mt-0.5",children:l.jsx(on,{size:16,strokeWidth:1.75})})]}),l.jsx("div",{className:"px-6 py-2 border-b border-line/60",children:l.jsxs("label",{className:"flex items-center gap-2 text-xs text-ink-muted cursor-pointer select-none py-1",children:[l.jsx("input",{type:"checkbox",checked:h,onChange:()=>s(h?new Set:new Set(e.map((p,x)=>x))),className:"rounded border-line text-accent focus:ring-accent w-3.5 h-3.5"}),a("import.selectAll"),l.jsx("span",{className:"ml-auto text-2xs text-ink-faint uppercase tracking-wider",children:e[0]?.source})]})}),l.jsx("ul",{className:"flex-1 overflow-y-auto py-1",children:e.map((p,x)=>l.jsx("li",{children:l.jsxs("label",{className:"flex items-center gap-3 px-6 py-2 hover:bg-wash transition-colors cursor-pointer select-none",children:[l.jsx("input",{type:"checkbox",checked:r.has(x),onChange:()=>d(x),className:"rounded border-line text-accent focus:ring-accent w-3.5 h-3.5 shrink-0"}),l.jsx(XA,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),l.jsx("span",{className:"text-sm text-ink truncate flex-1",children:p.title}),l.jsx("span",{className:"text-2xs text-ink-faint shrink-0",children:ve(a("import.messages"),{n:p.messageCount})})]})},x))}),l.jsxs("div",{className:"px-6 py-4 border-t border-line flex justify-end gap-2",children:[l.jsx("button",{onClick:t,className:"text-xs text-ink-muted hover:text-ink px-4 py-2 rounded-lg hover:bg-wash transition-colors",children:a("common.cancel")}),l.jsx("button",{onClick:()=>{m()},disabled:r.size===0||o,className:"text-xs bg-accent hover:bg-accent-strong text-white px-5 py-2 rounded-lg transition-colors disabled:opacity-30",children:o?"…":ve(a("import.confirm"),{n:r.size})})]})]})})}function _ce(e){const t=Date.now()-e,n=Math.floor(t/6e4);if(n<1)return Ne("switcher.justNow");if(n<60)return ve(Ne("switcher.minAgo"),{n});const a=Math.floor(n/60);if(a<24)return ve(Ne("switcher.hourAgo"),{n:a});const r=Math.floor(a/24);return r<30?ve(Ne("switcher.dayAgo"),{n:r}):new Date(e).toLocaleDateString(Aa.getState().lang==="zh"?"zh-CN":"en-US")}function Mce({onSwitched:e}){const t=Tt(),n=sn(A=>A.projects),a=sn(A=>A.activeId),r=sn(A=>A.switching),s=n.find(A=>A.id===a)?.kind==="paradigm",[o,u]=R.useState(!1),[d,h]=R.useState(null),[m,p]=R.useState(!1),[x,b]=R.useState(void 0),[y,w]=R.useState(null),[E,v]=R.useState(""),N=R.useRef(null),S=R.useRef(null),C=n.find(A=>A.id===a),I=n.filter(A=>!A.archived).sort((A,H)=>H.updatedAt-A.updatedAt).slice(0,7),O=async A=>{const{canvasUniqueness:H}=await pt(async()=>{const{canvasUniqueness:Y}=await import("./canonical-Bkq2Xinv.js");return{canvasUniqueness:Y}},[]),G=await H(A.id),D=G==="native"?"confirm.deleteNative":G==="diverged-mirror"?"confirm.deleteDiverged":"confirm.deletePristine";await oi({title:Ne("confirm.deleteCanvasTitle"),message:ve(Ne(D),{name:A.name}),confirmLabel:Ne("common.delete"),danger:G!=="pristine-mirror"})&&G7(A.id).then(e)};R.useEffect(()=>{if(!o)return;const A=H=>{S.current?.contains(H.target)||u(!1)};return window.addEventListener("mousedown",A),()=>window.removeEventListener("mousedown",A)},[o]);const _=async A=>{u(!1),await Wi(A),e(),pt(()=>import("./canonical-Bkq2Xinv.js"),[]).then(H=>H.unsubscribeOrphanedSessions()),pt(()=>Promise.resolve().then(()=>n7),void 0).then(H=>H.sweepRecentSessions())};return l.jsxs("div",{ref:S,className:"absolute top-4 left-4 z-20",children:[l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsxs("button",{onClick:()=>u(!o),disabled:r,className:"bg-card/90 backdrop-blur border border-line rounded-xl px-3.5 py-2 shadow-sm hover:bg-wash transition-colors flex items-center gap-2 text-sm text-ink max-w-[240px] disabled:opacity-60",children:[r?l.jsx(tn,{size:16,strokeWidth:1.75,className:"animate-spin shrink-0 text-accent"}):s?l.jsx(yF,{size:16,strokeWidth:1.75,className:"shrink-0 text-accent"}):l.jsx(pu,{size:16,strokeWidth:1.75,className:"shrink-0 text-ink-muted"}),l.jsx("span",{className:"truncate font-medium",children:C?.name??"…"}),l.jsx(ur,{size:14,strokeWidth:1.75,className:"shrink-0 text-ink-faint"})]}),l.jsx(Ace,{}),!!C?.sourceSession?.sessionId&&(()=>{const A=Hm.size>0&&!Hm.has(C.sourceSession.sessionId);return l.jsxs("button",{title:A?Ne("switcher.mirrorBadgeGone"):ve(Ne("switcher.mirrorBadge"),{runner:C.sourceSession.runner}),onClick:()=>{b(C.sourceSession.sessionId),p(!0)},className:`bg-card/90 backdrop-blur border border-line rounded-xl px-2 py-2 shadow-sm hover:bg-wash transition-colors text-2xs font-mono flex items-center gap-1 ${A?"text-ink-faint/50 line-through decoration-1":"text-ink-faint hover:text-accent"}`,"data-twin-badge":A?"unreachable":"live",children:["⇄ ",C.sourceSession.runner]})})()]}),o&&l.jsxs("div",{className:"mt-1.5 bg-card border border-line rounded-xl shadow-lg py-1.5 w-[320px] animate-fade-in",children:[l.jsx("div",{className:"max-h-[320px] overflow-y-auto",children:I.map(A=>l.jsx("div",{className:`group flex items-center gap-1 px-3 py-2 hover:bg-wash cursor-pointer transition-colors ${A.id===a?"bg-accent/5":""}`,onClick:()=>{y!==A.id&&A.id!==a&&_(A.id)},children:y===A.id?l.jsx("input",{autoFocus:!0,value:E,onChange:H=>v(H.target.value),onClick:H=>H.stopPropagation(),onKeyDown:H=>{H.key==="Enter"&&!ar(H)&&E.trim()&&(V7(A.id,E.trim()),w(null)),H.key==="Escape"&&w(null)},onBlur:()=>w(null),className:"flex-1 text-sm text-ink border border-accent/40 rounded-lg px-2 py-1 bg-surface focus:outline-none"}):l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsx("div",{className:`text-sm truncate ${A.id===a?"text-accent font-medium":"text-ink"}`,children:A.name}),l.jsxs("div",{className:"text-2xs text-ink-faint flex items-center gap-1.5",children:[l.jsx("span",{children:_ce(A.updatedAt)}),!!A.sourceSession?.sessionId&&l.jsx("span",{className:"font-mono border border-line rounded px-1 py-px","data-mirror-mark":!0,children:A.sourceSession.runner})]})]}),l.jsx("button",{title:t("switcher.rename"),className:"opacity-0 group-hover:opacity-100 text-ink-faint hover:text-ink p-1 rounded transition-all shrink-0",onClick:H=>{H.stopPropagation(),w(A.id),v(A.name)},children:l.jsx(Jl,{size:14,strokeWidth:1.75})}),l.jsx("button",{title:t("common.delete"),className:"opacity-0 group-hover:opacity-100 text-ink-faint hover:text-red-500 p-1 rounded transition-all shrink-0",onClick:H=>{H.stopPropagation(),O(A)},children:l.jsx(rr,{size:14,strokeWidth:1.75})}),l.jsx("button",{title:t("switcher.archive"),className:"opacity-0 group-hover:opacity-100 text-ink-faint hover:text-amber-600 p-1 rounded transition-all shrink-0",onClick:H=>{H.stopPropagation(),Vm(A.id,!0).then(e)},"data-archive-canvas":!0,children:l.jsx(rl,{size:14,strokeWidth:1.75})})]})},A.id))}),l.jsxs("div",{className:"border-t border-line mt-1 pt-1",children:[l.jsxs("button",{onClick:()=>{u(!1),Ip().then(e)},className:"w-full text-left px-3 py-2 text-sm text-accent hover:bg-wash transition-colors flex items-center gap-2",children:[l.jsx(W0,{size:15,strokeWidth:1.75})," ",t("switcher.newCanvas")]}),l.jsxs("button",{onClick:()=>N.current?.click(),className:"w-full text-left px-3 py-2 text-sm text-ink-muted hover:bg-wash transition-colors flex items-center gap-2",children:[l.jsx(lq,{size:15,strokeWidth:1.75})," ",t("switcher.importBackup")]}),l.jsxs("button",{onClick:()=>{u(!1),p(!0)},className:"w-full text-left px-3 py-2 text-sm text-ink-muted hover:bg-wash transition-colors flex items-center gap-2","data-open-atlas":!0,children:[l.jsx(dU,{size:15,strokeWidth:1.75})," ",t("switcher.allCanvases")]}),window.desktop&&l.jsxs("button",{onClick:()=>{u(!1),window.desktop.checkForUpdates()},className:"w-full text-left px-3 py-2 text-sm text-ink-muted hover:bg-wash transition-colors flex items-center gap-2","data-check-updates":!0,children:[l.jsx(cr,{size:15,strokeWidth:1.75})," ",t("update.checkMenu"),l.jsxs("span",{className:"ml-auto text-2xs text-ink-faint",children:["v",new URLSearchParams(window.location.search).get("dv")]})]}),l.jsx("input",{ref:N,type:"file",accept:".json,.jsonl,application/json",className:"hidden",onChange:A=>{const H=A.target.files?.[0];H&&kG(H).then(G=>{G.kind==="own"&&G.ok?(u(!1),e()):G.kind==="chat"&&(u(!1),h(G.conversations))}).catch(G=>{We("error",ve(Ne("toast.importFailedGeneric"),{msg:G instanceof Error?G.message:String(G)}))}),A.target.value=""}})]})]}),d&&l.jsx(Cce,{conversations:d,onClose:()=>h(null),onDone:()=>{h(null),e()}}),m&&l.jsx(Qv,{onClose:()=>{p(!1),b(void 0)},onSwitched:e,focusSessionId:x})]})}const Ice="JVBERi0xLjQKMSAwIG9iago8PCAvVHlwZSAvQ2F0YWxvZyAvUGFnZXMgMiAwIFIgPj4KZW5kb2JqCjIgMCBvYmoKPDwgL1R5cGUgL1BhZ2VzIC9LaWRzIFszIDAgUiA0IDAgUl0gL0NvdW50IDIgPj4KZW5kb2JqCjMgMCBvYmoKPDwgL1R5cGUgL1BhZ2UgL1BhcmVudCAyIDAgUiAvTWVkaWFCb3ggWzAgMCA1OTUgODQyXSAvQ29udGVudHMgNSAwIFIgL1Jlc291cmNlcyA8PCAvRm9udCA8PCAvRjEgNyAwIFIgL0YyIDggMCBSID4+ID4+ID4+CmVuZG9iago0IDAgb2JqCjw8IC9UeXBlIC9QYWdlIC9QYXJlbnQgMiAwIFIgL01lZGlhQm94IFswIDAgNTk1IDg0Ml0gL0NvbnRlbnRzIDYgMCBSIC9SZXNvdXJjZXMgPDwgL0ZvbnQgPDwgL0YxIDcgMCBSIC9GMiA4IDAgUiA+PiA+PiA+PgplbmRvYmoKNSAwIG9iago8PCAvTGVuZ3RoIDExMTIgPj4Kc3RyZWFtCkJUCi9GMiAxOSBUZiAxIDAgMCAxIDY0IDcyNS4wIFRtIChXaHkgU2F2ZWQgQXJ0aWNsZXMgU3RheSBVbnJlYWQpIFRqCi9GMSAxMSBUZiAxIDAgMCAxIDY0IDcwOC4wIFRtIChBIHNob3J0IGJyaWVmIG9uIGRpZ2l0YWwgaG9hcmRpbmcgYW5kIHRoZSBjb2xsZWN0b3IncyBmYWxsYWN5KSBUagovRjIgMTMgVGYgMSAwIDAgMSA2NCA2NjkuMCBUbSAoMS4gVGhlIHBoZW5vbWVub24pIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNjUxLjUgVG0gKFJlYWQtaXQtbGF0ZXIgc2VydmljZXMgcmVwb3J0IHRoYXQgbW9zdCBzYXZlZCBpdGVtcyBhcmUgbmV2ZXIpIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNjM0LjAgVG0gKHJlb3BlbmVkLiBBY3Jvc3MgcHVibGlzaGVkIHVzYWdlIHN0dWRpZXMsIHRoZSBzaGFyZSBvZiBzYXZlZCkgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA2MTYuNSBUbSAoYXJ0aWNsZXMgdGhhdCBnZXQgYSBzZWNvbmQgdmlzaXQgaXMgc21hbGwsIGFuZCBjb21wbGV0aW9uIHJhdGVzKSBUagovRjEgMTEuNSBUZiAxIDAgMCAxIDY0IDU5OS4wIFRtIChhcmUgc21hbGxlciBzdGlsbC4gVGhlIGFyY2hpdmUgZ3Jvd3M7IHRoZSByZWFkaW5nIGRvZXMgbm90LikgVGoKL0YyIDEzIFRmIDEgMCAwIDEgNjQgNTYwLjAgVG0gKDIuIFRoZSBjb2xsZWN0b3IncyBmYWxsYWN5KSBUagovRjEgMTEuNSBUZiAxIDAgMCAxIDY0IDU0Mi41IFRtIChDb2xsZWN0aW5nIHByb2R1Y2VzIGFuIGltbWVkaWF0ZSBzZW5zZSBvZiBwcm9ncmVzcyB3aGlsZSB0aGUpIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNTI1LjAgVG0gKHVuZGVyc3RhbmRpbmcgaXQgcHJvbWlzZXMgaXMgZGVmZXJyZWQuIFNhdmluZyBhIHRleHQgZmVlbHMgbGlrZSkgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA1MDcuNSBUbSAoYSBmaXJzdCBzdGVwIG9mIHJlYWRpbmcgaXQsIGJ1dCBubyBwYXJ0IG9mIHRoZSByZWFkaW5nIGhhcykgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA0OTAuMCBUbSAoaGFwcGVuZWQuKSBUagovRjIgMTEuNSBUZiAxIDAgMCAxIDY0IDQ3Mi41IFRtIChUaGUgYWN0IG9mIHNhdmluZyBpcyBtaXN0YWtlbiBmb3IgdGhlIGFjdCBvZiBsZWFybmluZy4pIFRqCkVUCmVuZHN0cmVhbQplbmRvYmoKNiAwIG9iago8PCAvTGVuZ3RoIDkwOCA+PgpzdHJlYW0KQlQKL0YyIDEzIFRmIDEgMCAwIDEgNjQgNzI1LjAgVG0gKDMuIFdoeSBpdCBwZXJzaXN0cykgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA3MDcuNSBUbSAoVGhlIGNvc3RzIGFyZSBhc3ltbWV0cmljOiBzYXZpbmcgdGFrZXMgb25lIHNlY29uZCBhbmQgcGF5cyBvdXQpIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNjkwLjAgVG0gKGEgc21hbGwgcmV3YXJkIG5vdzsgcmVhZGluZyB0YWtlcyBhbiBob3VyIGFuZCBwYXlzIG91dCBsYXRlci4pIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNjcyLjUgVG0gKEhhYml0cyBmb2xsb3cgdGhlIGNoZWFwZXIgbG9vcCwgc28gbGlicmFyaWVzIGluZmxhdGUgYnkgZGVmYXVsdC4pIFRqCi9GMiAxMyBUZiAxIDAgMCAxIDY0IDYzMy41IFRtICg0LiBXaGF0IGhlbHBzKSBUagovRjEgMTEuNSBUZiAxIDAgMCAxIDY0IDYxNi4wIFRtIChJbnRlcnZlbnRpb25zIHRoYXQgd29yayBtb3ZlIHByb2Nlc3NpbmcgdG8gdGhlIG1vbWVudCBvZiBjYXB0dXJlOikgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA1OTguNSBUbSAod3JpdGUgb25lIGxpbmUgaW4geW91ciBvd24gd29yZHMgYWJvdXQgd2h5IHRoZSBpdGVtIG1hdHRlcnMsIGFuZCkgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA1ODEuMCBUbSAoc2NoZWR1bGUgYSByZXZpZXcgcGFzcyBpbnN0ZWFkIG9mIHRydXN0aW5nIHRoZSBhcmNoaXZlIHRvKSBUagovRjEgMTEuNSBUZiAxIDAgMCAxIDY0IDU2My41IFRtIChyZXN1cmZhY2UgaXQuKSBUagovRjEgMTEuNSBUZiAxIDAgMCAxIDY0IDUzMi4wIFRtIChBIHNtYWxsZXIgbGlicmFyeSB0aGF0IGdldHMgcHJvY2Vzc2VkIGJlYXRzIGEgY29tcGxldGUgb25lIHRoYXQpIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNTE0LjUgVG0gKGRvZXMgbm90LikgVGoKRVQKZW5kc3RyZWFtCmVuZG9iago3IDAgb2JqCjw8IC9UeXBlIC9Gb250IC9TdWJ0eXBlIC9UeXBlMSAvQmFzZUZvbnQgL0hlbHZldGljYSA+PgplbmRvYmoKOCAwIG9iago8PCAvVHlwZSAvRm9udCAvU3VidHlwZSAvVHlwZTEgL0Jhc2VGb250IC9IZWx2ZXRpY2EtQm9sZCA+PgplbmRvYmoKeHJlZgowIDkKMDAwMDAwMDAwMCA2NTUzNSBmIAowMDAwMDAwMDA5IDAwMDAwIG4gCjAwMDAwMDAwNTggMDAwMDAgbiAKMDAwMDAwMDEyMSAwMDAwMCBuIAowMDAwMDAwMjU3IDAwMDAwIG4gCjAwMDAwMDAzOTMgMDAwMDAgbiAKMDAwMDAwMTU1NyAwMDAwMCBuIAowMDAwMDAyNTE2IDAwMDAwIG4gCjAwMDAwMDI1ODYgMDAwMDAgbiAKdHJhaWxlcgo8PCAvU2l6ZSA5IC9Sb290IDEgMCBSID4+CnN0YXJ0eHJlZgoyNjYxCiUlRU9G",Oce=`<!-- tdag-page:1 -->
705
705
 
706
706
  # Why Saved Articles Stay Unread
707
707
 
@@ -934,11 +934,11 @@ ${n==="zh"?"**高光(原文保真)**":"**Highlights (verbatim)**"}
934
934
  ${S.map(A=>`> ${A.text}`).join(`
935
935
  `)}`:"",I=En();x.push(I);const O=`${n==="zh"?"凝练":"Condensed"}: ${v.data.question.replace(/\s+/g," ").slice(0,60)} → ${N.data.question.replace(/\s+/g," ").slice(0,60)}`,_=`${t[E]||""}${C}`;p.push({id:I,type:"thought",position:{x:v.position.x+h,y:v.position.y},dragHandle:".drag-handle",data:{question:O,response:_,responses:[_],responseIndex:0,condensedFrom:w.nodeIds,createdAt:new Date().toISOString(),isCollapsed:!1,isEditing:!1,isEditingResponse:!1,isLoading:!1,tokenCount:_n(`${O}
936
936
  ${_}`),highlights:[],highlightMode:"tag",attachments:[],excludedAttachmentIds:[],includedAttachmentIds:[],roleMode:"inherit",isRoot:!1,isBranch:!1}}),w.nodeIds.forEach(A=>m.set(A,I))});for(const w of r){if(u.has(w.id))continue;const E=En();m.set(w.id,E);const v=w.data;p.push({...w,id:E,position:{x:w.position.x+h,y:w.position.y},selected:!1,data:{...v,isEditing:!1,isEditingResponse:!1,isLoading:!1}})}const b=[],y=new Set;for(const w of s){const E=m.get(w.source),v=m.get(w.target);if(!E||!v||E===v)continue;const N=`${E}→${v}`;y.has(N)||(y.add(N),b.push({...w,id:`e-${En()}`,source:E,target:v,selected:!1}))}return a.pushHistory(),se.setState(w=>{const E=[...w.nodes,...p],v=[...w.edges,...b];return{nodes:yr(E,v),edges:v}}),{copiedNodes:p.length,collapsedRuns:e.length,distillIds:x}}let Ml=0;function kue(){Ml++,ce.getState().setCondenseRun({status:"idle",current:0,total:0,streaming:""})}async function Eue(e,t,n){if(e.length===0)return;const a=++Ml,r=ce.getState(),s=se.getState().nodes.map(o=>o.id);r.setCondenseRun({status:"building",current:0,total:e.length,streaming:"",error:void 0,originalIds:s,distillIds:[]});try{const o=[];let u="";for(let h=0;h<e.length;h++){if(Ml!==a)return;ce.getState().setCondenseRun({current:h+1,streaming:""});const m=await yue(e[h],t,n,p=>{Ml===a&&ce.getState().setCondenseRun({streaming:p})},u||void 0);if(Ml!==a)return;o.push(m),u=`${u}
937
- ${m}`.slice(-1500)}const d=wue(e,o,t);if(Ml!==a)return;ce.getState().setCondenseRun({status:"done",streaming:"",distillIds:d.distillIds}),We("success",Ne("condense.copyReady"),8e3,{label:Ne("tmap.export"),run:()=>ce.getState().setThoughtMapOpen(!0)})}catch(o){if(Ml!==a)return;ce.getState().setCondenseRun({status:"error",error:o instanceof Error?o.message:String(o)})}}function Sue({onFocusSegment:e}){const t=ce(D=>D.condenseDialogOpen),n=ce(D=>D.condenseRun),a=Tt(),r=Aa(D=>D.lang),s=se(D=>D.nodes),o=se(D=>D.edges),[u,d]=R.useState(0),h=R.useMemo(()=>t&&n.status==="idle"?xue(s,o):[],[t,n.status,s,o,u]),m=ce(D=>D.selectedModel),p=ec()?.models??[],[x,b]=R.useState(""),[y,w]=R.useState(new Set),[E,v]=R.useState(null),N=R.useRef(null),S=D=>{const P=N.current?.getBoundingClientRect();if(!P)return;const Y=D.clientX-P.left,U=D.clientY-P.top,z=q=>v({x:Math.min(window.innerWidth-120,Math.max(0,q.clientX-Y)),y:Math.min(window.innerHeight-80,Math.max(0,q.clientY-U))}),L=()=>{window.removeEventListener("mousemove",z),window.removeEventListener("mouseup",L)};window.addEventListener("mousemove",z),window.addEventListener("mouseup",L)},C=D=>D.nodeIds.join(","),I=h.filter(D=>!y.has(C(D))),O=I.reduce((D,P)=>D+P.saving,0),_=()=>{ce.getState().setCondenseDialogOpen(!1),ce.getState().setCondenseHighlightIds([])};if(R.useEffect(()=>{if(!t)return;const D=P=>{P.key==="Escape"&&_()};return window.addEventListener("keydown",D),()=>window.removeEventListener("keydown",D)},[t]),!t)return null;const A=()=>{I.length!==0&&Eue(I,r,x||m||void 0)},H=()=>{se.getState().setArchived(n.originalIds,!0),We("success",a("condense.originalArchived")),ce.getState().setCondenseRun({status:"idle",current:0,total:0,streaming:"",originalIds:[],distillIds:[]}),_()},G=()=>{const P=se.getState().nodes.filter(Y=>n.distillIds.includes(Y.id));P.length&&e?.(P.map(Y=>Y.id))};return dr.createPortal(l.jsxs("div",{ref:N,className:"fixed z-[70] bg-surface border border-line rounded-2xl shadow-2xl w-[400px] max-h-[72vh] flex flex-col p-4 animate-fade-in",style:E?{left:E.x,top:E.y}:{left:80,bottom:16},"data-condense-dialog":!0,onClick:D=>D.stopPropagation(),children:[l.jsxs("div",{className:"flex items-start justify-between mb-1 cursor-grab active:cursor-grabbing select-none",onMouseDown:S,children:[l.jsxs("div",{className:"text-sm font-semibold text-ink flex items-center gap-2",children:[l.jsx(Sp,{size:15,strokeWidth:1.75,className:"text-accent"})," ",a("condense.title")]}),l.jsx("button",{onClick:_,title:n.status==="building"?a("condense.runningBg"):void 0,className:"text-ink-faint hover:text-ink rounded-lg w-7 h-7 flex items-center justify-center hover:bg-wash transition-colors",children:l.jsx(on,{size:15})})]}),n.status==="idle"&&l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"flex items-center justify-between gap-2 mb-2",children:[l.jsx("p",{className:"text-2xs text-ink-faint leading-snug",title:a("condense.copyIntroFull"),children:a("condense.copyIntroShort")}),l.jsxs("button",{onClick:()=>d(D=>D+1),title:a("condense.rescanTitle"),"data-condense-rescan":!0,className:"text-2xs text-ink-muted hover:text-accent px-2 py-1 rounded-lg hover:bg-wash transition-colors shrink-0",children:["⟳ ",a("condense.rescan")]})]}),l.jsx("p",{className:"text-2xs text-ink-faint mb-2","data-condense-scanline":!0,children:ve(a("condense.scanLine"),{turns:String(s.filter(D=>D.data.response&&!D.data.stepKind).length),n:String(h.length)})}),l.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[l.jsx("label",{className:"text-2xs text-ink-muted shrink-0",children:a("condense.modelLabel")}),l.jsxs("select",{value:x,onChange:D=>b(D.target.value),"data-condense-model":!0,className:"text-xs bg-wash text-ink rounded-lg px-2 py-1.5 focus:outline-none focus:ring-1 focus:ring-accent/40 max-w-[220px] truncate",children:[l.jsx("option",{value:"",children:ve(a("condense.modelGlobal"),{model:m||"auto"})}),p.map(D=>l.jsx("option",{value:D.id,children:D.id},D.id))]})]}),h.length===0?l.jsx("p",{className:"text-xs text-ink-muted py-4",children:a("condense.segNothing")}):l.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto space-y-2 pr-1",children:h.map(D=>{const P=C(D),Y=!y.has(P);return l.jsxs("div",{"data-condense-item":!0,className:`border rounded-xl p-3 transition-colors cursor-pointer ${Y?"border-accent/60 bg-accent/5":"border-line opacity-60"}`,onClick:()=>{ce.getState().setCondenseHighlightIds(D.nodeIds),e?.(D.nodeIds)},children:[l.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[l.jsx("input",{type:"checkbox",checked:Y,onClick:U=>U.stopPropagation(),onChange:()=>w(U=>{const z=new Set(U);return z.has(P)?z.delete(P):z.add(P),z}),className:"accent-[var(--color-accent)]","data-condense-check":!0}),l.jsx("span",{className:"text-2xs text-ink-faint font-mono",children:ve(a("condense.segMeta"),{n:String(D.nodeIds.length),tok:String(D.saving)})})]}),l.jsx("p",{className:"text-xs text-ink mt-1 leading-snug line-clamp-2",children:D.headQuestion})]},P)})}),h.length>0&&l.jsxs("div",{className:"flex items-center justify-between gap-2 pt-3 mt-2 border-t border-line",children:[l.jsx("span",{className:"text-2xs text-ink-faint",children:a("condense.copyFootnote")}),l.jsxs("button",{onClick:A,disabled:I.length===0,"data-condense-build":!0,className:"text-xs bg-accent text-white px-3.5 py-2 rounded-lg disabled:opacity-40 transition-colors flex items-center gap-1.5 shrink-0",children:[l.jsx(ro,{size:13,strokeWidth:1.75}),ve(a("condense.buildCopy"),{n:String(I.length),tok:String(O)})]})]})]}),n.status==="building"&&l.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",children:[l.jsxs("div",{className:"flex items-center gap-2 text-sm text-ink-muted mb-1.5",children:[l.jsx(tn,{size:15,className:"animate-spin text-accent"}),ve(a("condense.buildingRun"),{i:String(n.current),n:String(n.total)})]}),l.jsx("p",{className:"text-2xs text-ink-faint mb-2",children:a("condense.runningBg")}),n.streaming&&l.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto text-2xs text-ink-muted bg-wash rounded-lg p-2.5 whitespace-pre-wrap leading-relaxed","data-condense-streaming":!0,children:n.streaming}),l.jsx("button",{onClick:()=>kue(),"data-condense-cancel":!0,className:"self-start mt-3 text-xs text-ink-muted hover:text-red-600 px-3 py-1.5 rounded-lg hover:bg-wash transition-colors",children:a("common.cancel")})]}),n.status==="error"&&l.jsxs("div",{className:"flex flex-col gap-2 py-3",children:[l.jsx("p",{className:"text-2xs text-red-600",children:n.error}),l.jsx("button",{onClick:()=>ce.getState().setCondenseRun({status:"idle",error:void 0}),className:"self-start text-xs text-ink-muted hover:text-ink px-3 py-1.5 rounded-lg hover:bg-wash transition-colors",children:a("common.cancel")})]}),n.status==="done"&&l.jsxs("div",{className:"flex flex-col gap-3 py-3",children:[l.jsxs("div",{className:"flex items-center gap-2 text-sm text-green-700",children:[l.jsx(es,{size:16})," ",a("condense.copyReady")]}),l.jsx("p",{className:"text-2xs text-ink-faint leading-relaxed",children:a("condense.copyCompareHint")}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("button",{onClick:G,className:"text-xs bg-accent/10 text-accent hover:bg-accent/20 px-3 py-2 rounded-lg transition-colors",children:a("condense.viewCopy")}),l.jsxs("button",{onClick:H,"data-condense-archive-original":!0,className:"text-xs border border-line text-ink-muted hover:text-ink hover:bg-wash px-3 py-2 rounded-lg transition-colors flex items-center gap-1.5",children:[l.jsx(rl,{size:13,strokeWidth:1.75})," ",a("condense.archiveOriginal")]})]}),l.jsx("button",{onClick:()=>{ce.getState().setCondenseRun({status:"idle"}),_()},className:"self-start text-xs text-ink-faint hover:text-ink transition-colors",children:a("common.close")})]})]}),document.body)}function YN(){const e=Aa(n=>n.lang),t=Aa(n=>n.setLang);return l.jsx("div",{className:"flex items-center bg-card/90 backdrop-blur border border-line rounded-lg shadow-sm overflow-hidden",children:["en","zh"].map(n=>l.jsx("button",{onClick:()=>t(n),className:`px-2 h-8 text-2xs font-medium transition-colors ${e===n?"bg-accent text-white":"text-ink-muted hover:bg-wash"}`,children:n==="en"?"EN":"中"},n))})}function ma({x:e,y:t,w:n=34,h:a=20,tone:r="plain"}){return l.jsxs("g",{children:[l.jsx("rect",{x:e,y:t,width:n,height:a,rx:4,fill:"white",stroke:at.line,strokeWidth:1}),r!=="plain"&&l.jsx("rect",{x:e,y:t,width:2.5,height:a,rx:1.25,fill:r==="accent"?at.accent:at.warm})]})}const Nue={1:l.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[l.jsx(ma,{x:43,y:32,tone:"accent"}),l.jsx("circle",{cx:60,cy:28,r:2.5,fill:at.accent})]}),2:l.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[l.jsx(ma,{x:43,y:12,tone:"accent"}),l.jsx("line",{x1:60,y1:32,x2:60,y2:50,stroke:at.accent,strokeWidth:1.75}),l.jsx("path",{d:"M 57 47 L 60 52 L 63 47 Z",fill:at.accent}),l.jsx(ma,{x:43,y:52})]}),3:l.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[l.jsx(ma,{x:20,y:12,tone:"accent"}),l.jsx("line",{x1:37,y1:32,x2:37,y2:50,stroke:at.accent,strokeWidth:1.75}),l.jsx("path",{d:"M 34 47 L 37 52 L 40 47 Z",fill:at.accent}),l.jsx(ma,{x:20,y:52}),l.jsx("rect",{x:26,y:58,width:14,height:3,rx:1.5,fill:at.trace,opacity:.6}),l.jsx("path",{d:"M 54 62 C 64 62, 62 40, 72 38",stroke:at.warm,strokeWidth:1.75,fill:"none",strokeDasharray:"4 3"}),l.jsx("path",{d:"M 69 35.5 L 74 38 L 70 41 Z",fill:at.warm}),l.jsx(ma,{x:74,y:28,tone:"warm"})]}),4:l.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[l.jsx(ma,{x:43,y:10,tone:"accent"}),l.jsx("line",{x1:60,y1:30,x2:60,y2:52,stroke:at.line,strokeWidth:1.75,strokeDasharray:"3 3"}),l.jsx("circle",{cx:60,cy:41,r:7,fill:"white",stroke:"#FCA5A5",strokeWidth:1}),l.jsx("line",{x1:57,y1:38,x2:63,y2:44,stroke:"#EF4444",strokeWidth:1.5,strokeLinecap:"round"}),l.jsx("line",{x1:63,y1:38,x2:57,y2:44,stroke:"#EF4444",strokeWidth:1.5,strokeLinecap:"round"}),l.jsx(ma,{x:43,y:54})]}),5:l.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[l.jsx(ma,{x:12,y:14,w:40,h:15}),l.jsx("circle",{cx:14,cy:16,r:4.5,fill:"#D64533"}),l.jsx("text",{x:14,y:18.4,textAnchor:"middle",fontSize:6,fontWeight:700,fill:"white",children:"✕"}),l.jsx(ma,{x:12,y:35,w:40,h:15}),l.jsx("circle",{cx:14,cy:37,r:4.5,fill:at.accent}),l.jsx("text",{x:14,y:39.4,textAnchor:"middle",fontSize:6,fontWeight:700,fill:"white",children:"⚖"}),l.jsx(ma,{x:12,y:56,w:40,h:15}),l.jsx("circle",{cx:14,cy:58,r:4.5,fill:"#C9A227"}),l.jsx("text",{x:14,y:60.4,textAnchor:"middle",fontSize:6,fontWeight:700,fill:"white",children:"?"}),l.jsx("path",{d:"M 62 42 L 74 42",stroke:at.inkMuted,strokeWidth:1.2}),l.jsx("path",{d:"M 71.5 39.5 L 76 42 L 71.5 44.5 Z",fill:at.inkMuted}),l.jsx("rect",{x:86,y:14,width:13,height:13,rx:4.5,fill:"#D64533"}),l.jsx("line",{x1:92.5,y1:27,x2:92.5,y2:35,stroke:at.accent,strokeWidth:1.4}),l.jsx("rect",{x:86,y:35,width:13,height:13,rx:4.5,fill:at.accent}),l.jsx("line",{x1:92.5,y1:48,x2:92.5,y2:56,stroke:at.accent,strokeWidth:1.4}),l.jsx("rect",{x:86,y:56,width:13,height:13,rx:4.5,fill:"#C9A227"})]}),7:l.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[l.jsx("rect",{x:14,y:12,width:30,height:22,rx:3,fill:"#FEF3C7",stroke:"#F59E0B",strokeWidth:.8}),l.jsx("line",{x1:29,y1:34,x2:29,y2:50,stroke:at.accent,strokeWidth:1.75}),l.jsx("path",{d:"M 26 47 L 29 52 L 32 47 Z",fill:at.accent}),l.jsx(ma,{x:12,y:52,tone:"accent"}),l.jsx("path",{d:"M 100 22 C 80 22, 70 55, 50 60",stroke:at.accent,strokeWidth:1.75,fill:"none",strokeDasharray:"5 3"}),l.jsx("path",{d:"M 52 57 L 47 61 L 52 64 Z",fill:at.accent}),l.jsx(ma,{x:82,y:12})]}),9:l.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[l.jsx(ma,{x:43,y:10,tone:"accent"}),l.jsx("line",{x1:60,y1:30,x2:60,y2:48,stroke:at.accent,strokeWidth:1.75}),l.jsx("path",{d:"M 57 45 L 60 50 L 63 45 Z",fill:at.accent}),l.jsx(ma,{x:43,y:50}),l.jsx("circle",{cx:75,cy:53,r:4,fill:"#F59E0B"}),l.jsx("path",{d:"M 73.5 53 a 1.5 1.5 0 1 1 3 0",stroke:"white",strokeWidth:.9,fill:"none"}),l.jsx("text",{x:60,y:80,textAnchor:"middle",fontSize:7,fill:at.inkMuted,fontFamily:"JetBrains Mono Variable, monospace",children:"v2/2 · replay"})]}),6:l.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[l.jsx("rect",{x:8,y:18,width:14,height:48,rx:4,fill:"white",stroke:at.line,strokeWidth:1}),l.jsx("circle",{cx:15,cy:27,r:3,fill:at.accent,opacity:.7}),l.jsx("rect",{x:12,y:37,width:6,height:6,rx:1,fill:"#F59E0B",opacity:.8}),l.jsx("rect",{x:12,y:49,width:6,height:6,rx:1,fill:at.inkMuted,opacity:.5}),l.jsx("rect",{x:38,y:14,width:32,height:24,rx:3,fill:"#FEF3C7",stroke:"#F59E0B",strokeWidth:.8}),l.jsx("rect",{x:80,y:14,width:32,height:24,rx:3,fill:"white",stroke:at.line,strokeWidth:1}),l.jsx("circle",{cx:88,cy:22,r:3,fill:at.line}),l.jsx("path",{d:"M 82 34 L 92 26 L 100 32 L 108 24",stroke:at.inkMuted,strokeWidth:1.2,fill:"none"}),l.jsx("text",{x:72,y:62,textAnchor:"middle",fontSize:7,fill:at.inkMuted,fontFamily:"JetBrains Mono Variable, monospace",children:"⌘V paste anything"})]}),8:l.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[l.jsx("rect",{x:8,y:8,width:70,height:52,rx:3,fill:at.accent,opacity:.06,stroke:at.accent,strokeWidth:.8,strokeDasharray:"3 2"}),l.jsx(ma,{x:14,y:14,w:26,h:16}),l.jsx(ma,{x:46,y:14,w:26,h:16}),l.jsx(ma,{x:30,y:38,w:26,h:16}),l.jsx("path",{d:"M 40 46 C 60 50, 70 50, 84 48",stroke:at.accent,strokeWidth:1.4,fill:"none"}),l.jsx("path",{d:"M 59 30 C 70 36, 76 42, 84 46",stroke:at.accent,strokeWidth:1.4,fill:"none"}),l.jsx("path",{d:"M 43 22 C 66 24, 76 38, 84 44",stroke:at.accent,strokeWidth:1.4,fill:"none"}),l.jsx(ma,{x:84,y:40,w:28,h:18,tone:"accent"})]}),10:l.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[l.jsx(ma,{x:10,y:18,w:30,h:17,tone:"accent"}),l.jsx("line",{x1:25,y1:35,x2:25,y2:48,stroke:at.accent,strokeWidth:1.5}),l.jsx("path",{d:"M 22.5 45.5 L 25 50 L 27.5 45.5 Z",fill:at.accent}),l.jsx(ma,{x:10,y:50,w:30,h:17}),l.jsx("path",{d:"M 46 42 L 60 42",stroke:at.inkMuted,strokeWidth:1.2}),l.jsx("path",{d:"M 57.5 39.5 L 62 42 L 57.5 44.5 Z",fill:at.inkMuted}),l.jsx("rect",{x:68,y:20,width:44,height:44,rx:5,fill:"white",stroke:at.line,strokeWidth:1}),l.jsx(ma,{x:74,y:30,w:20,h:11,tone:"accent"}),l.jsx(ma,{x:88,y:46,w:20,h:11}),l.jsx("rect",{x:76,y:14,width:28,height:11,rx:5.5,fill:"#2B2A28"}),l.jsx("circle",{cx:84,cy:19.5,r:2.6,fill:"none",stroke:"white",strokeWidth:1}),l.jsx("circle",{cx:84,cy:19.5,r:.9,fill:"white"}),l.jsx("text",{x:90,y:22,fontSize:6,fill:"white",fontFamily:"JetBrains Mono Variable, monospace",children:"view"}),l.jsx("text",{x:60,y:78,textAnchor:"middle",fontSize:7,fill:at.inkMuted,fontFamily:"JetBrains Mono Variable, monospace",children:"#view= · read-only"})]})},KN={4:"prune",5:"map",6:"reading",7:"ref"};function Tue(){const e=ce(h=>h.tutorialOpen),t=ce(h=>h.setTutorialOpen);R.useEffect(()=>{if(!e)return;const h=m=>{m.key==="Escape"&&t(!1)};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[e,t]);const n=Tt(),a=Aa(h=>h.lang),[r,s]=R.useState(0),o=[{label:n("tutorial.pg1"),steps:[1,2,3]},{label:n("tutorial.pg2"),steps:[4,5]},{label:n("tutorial.pg3"),steps:[6,7]},{label:n("tutorial.pg4"),steps:[8,9,10]}],u=r===o.length-1;if(R.useEffect(()=>{if(!e)return;s(0);const h=m=>{m.key==="ArrowRight"&&s(p=>Math.min(p+1,o.length-1)),m.key==="ArrowLeft"&&s(p=>Math.max(p-1,0))};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[e]),!e)return null;const d=o[r];return l.jsx("div",{className:"fixed inset-0 z-[95] bg-black/25 flex items-center justify-center animate-fade-in p-6",onClick:()=>t(!1),children:l.jsxs("div",{className:"bg-card border border-line rounded-2xl shadow-2xl w-[min(980px,94vw)] flex flex-col",onClick:h=>h.stopPropagation(),children:[l.jsxs("div",{className:"flex items-start justify-between px-7 pt-5 pb-1 shrink-0",children:[l.jsxs("div",{className:"flex items-baseline gap-3 min-w-0",children:[l.jsx("h2",{className:"text-lg font-semibold text-ink tracking-tight shrink-0",children:n("tutorial.title")}),l.jsx("p",{className:"text-xs text-ink-faint truncate",children:n("tutorial.subtitle")})]}),l.jsx("button",{onClick:()=>t(!1),className:"text-ink-faint hover:text-ink transition-colors mt-1",children:l.jsx(on,{size:18,strokeWidth:1.75})})]}),l.jsxs("div",{className:"px-7 pt-3 pb-1 min-h-[380px]",children:[l.jsx("p",{className:"text-2xs font-semibold text-accent mb-3 uppercase tracking-wider",children:d.label}),l.jsx("div",{className:`grid gap-4 ${d.steps.length===3?"grid-cols-1 sm:grid-cols-3":"grid-cols-1 sm:grid-cols-2"}`,children:d.steps.map(h=>l.jsxs("div",{className:"bg-surface border border-line/70 rounded-xl p-4 flex flex-col animate-fade-in",children:[l.jsx("div",{className:"w-full aspect-[120/72] bg-card rounded-lg border border-line/60 mb-3 overflow-hidden",children:KN[h]?l.jsx("img",{src:`/thoughtdag/tutorial/${KN[h]}-${a}.gif`,loading:"lazy",alt:"",className:"w-full h-full object-cover"}):Nue[h]}),l.jsx("h3",{className:"text-[13px] font-semibold text-ink leading-snug",children:n(`tutorial.step${h}.title`)}),l.jsx("p",{className:"text-xs text-ink-muted leading-relaxed mt-1.5",children:n(`tutorial.step${h}.desc`)})]},h))})]}),l.jsxs("div",{className:"px-7 py-4 shrink-0 flex items-center justify-between",children:[l.jsx("button",{onClick:()=>s(h=>Math.max(h-1,0)),disabled:r===0,className:"w-8 h-8 rounded-lg border border-line text-ink-muted hover:bg-wash transition-colors flex items-center justify-center disabled:opacity-25 disabled:cursor-not-allowed",children:l.jsx(Mm,{size:16,strokeWidth:1.75})}),l.jsx("div",{className:"flex items-center gap-2",children:o.map((h,m)=>l.jsx("button",{onClick:()=>s(m),className:`h-2 rounded-full transition-all ${m===r?"w-6 bg-accent":"w-2 bg-line hover:bg-line-strong"}`,"aria-label":`${m+1}/${o.length}`},m))}),u?l.jsx("button",{onClick:()=>t(!1),className:"text-xs bg-accent hover:bg-accent-strong text-white px-5 py-2 rounded-lg transition-colors",children:n("tutorial.close")}):l.jsx("button",{onClick:()=>s(h=>h+1),className:"w-8 h-8 rounded-lg border border-line text-ink-muted hover:bg-wash transition-colors flex items-center justify-center",children:l.jsx(Fa,{size:16,strokeWidth:1.75})})]}),l.jsxs("div",{className:"px-7 py-2.5 border-t border-line/60 shrink-0 flex flex-wrap gap-x-4 gap-y-1 text-2xs text-ink-faint font-mono",children:[l.jsxs("span",{children:[n("shortcut.panKeys")," ",n("shortcut.pan")]}),l.jsxs("span",{children:[n("shortcut.marqueeKeys")," ",n("shortcut.marquee")]}),l.jsxs("span",{children:["⌘","F ",n("shortcut.search")]}),l.jsxs("span",{children:["Space ",n("shortcut.collapse")]}),l.jsxs("span",{children:["R ",n("shortcut.regenerate")]}),l.jsxs("span",{children:["↑↓←→"," ",n("shortcut.navigate")]}),l.jsxs("span",{children:["⌘","Z/","⇧","⌘","Z ",n("shortcut.undo")]}),l.jsxs("span",{children:["Del ",n("shortcut.delete")]}),l.jsxs("span",{children:["Esc ",n("shortcut.escape")]})]})]})})}const Aue=new URLSearchParams(window.location.search),Os=Aue.get("dv"),Uc="https://chenxiachan.github.io/thoughtdag/docs",QM=[{version:"0.5.12",date:"2026-10-01",announce:!0,lead:{zh:"💬 新增「问画布」:让模型读整张画布,回答里的每个编号都能点回节点。",en:"💬 New: Ask the canvas. The model reads the whole canvas, and every number in its answer points back at a node."},items:[{title:{zh:"💬 问画布",en:"💬 Ask the canvas"},body:{zh:"工具栏 ⌘F 旁的问号气泡。它读画布的大纲(每个节点一行:编号、主题、结论、上游),选中节点时再读它的脉络和材料。回答用编号引用:悬停点亮节点,点击定位,画布上没有的编号标红。「落到画布」把这轮问答变成节点,引用线连到它提到的每个节点。空白时给了五个起手问题:总览、定位、溯源、比对、进展。只看画布,不联网,不进上下文。",en:`The question bubble next to ⌘F on the toolbar. It reads an outline of the canvas (one line a node: number, topic, takeaway, upstream) and, with a node selected, that node's chain and materials. Answers cite by number: hover lights the node, click locates it, a number the canvas lacks shows red. "Drop onto the canvas" turns the exchange into a node wired by reference to every node it cited. Five opening questions wait in the empty state: overview, locate, grounds, compare, progress. It reads only the canvas: no web, nothing enters your context.`}},{title:{zh:"。 标点不再孤立",en:"。 Punctuation stays with its word"},body:{zh:"缩小后牌子上的句号、逗号不再掉到下一行开头。",en:"On zoomed-out plaques a full stop or comma no longer opens a line by itself."}},{title:{zh:"🔧 两处修复",en:"🔧 Two fixes"},body:{zh:"侧栏里点到已不存在的探索标记,面板不再空白(#56)。索引升级后第一次选「全量」回忆,不再卡住整个应用:索引在后台刷新,菜单里提示一句(#57)。",en:'Clicking a stale explore mark in the panel no longer blanks it (#56). The first "full" recall after an index upgrade no longer stalls the app: the index refreshes in the background and the menu says so (#57).'}}]},{version:"0.5.11",date:"2026-10-01",announce:!1,lead:{zh:"一批围绕提问的收口。空节点里选的全量回忆现在真的会跑,之前发送时被丢掉了;问题编辑器(卡片和侧栏)里多了这个节点自己的联网、学术、回忆开关,改的只是这个节点;任何节点都能设自己的角色,编辑器改成侧栏头部下方的整宽条;问题也按 Markdown 渲染;全量回忆的确认框按实测重算,只说要多等一会儿和费用;模型选择器把别名解析到的型号标为上次运行;Harness 插件对话页的浮动开关挪到标题行下方,Windows 上不再被拖拽区吞掉点击。",en:"A batch around asking. A full recall chosen on an empty card now runs (the choice was dropped on send); the question editors (card and panel) carry the node's own web, scholar and recall switches, and edit only that node; any node can set its own role, in a full-width editor under the panel header; questions render as Markdown; the full-recall dialog is re-measured and names the wait and the cost; the model picker marks an alias's resolved model as the last run's; the harness plugin's floating switch sits below the title row, so the Windows drag region no longer swallows its clicks."},items:[]},{version:"0.5.10",date:"2026-10-01",announce:!1,lead:{zh:"修复 0.5.9 带出的一处:索引升级后、第一次搜索之前,「全量」回忆的确认框把索引读成 0 条、0 秒、0 美元。现在计数会先把索引更新到位;索引真的空着或还在重建时,只提示一句,不弹确认框。",en:"Fixes one thing 0.5.9 brought: after the index upgrade and before the first search, the confirm dialog for a full recall read the index as 0 turns, 0 seconds, $0.00. The count now brings the index up to date first; an index that is empty or still rebuilding gets a notice instead of a dialog."},items:[]},{version:"0.5.9",date:"2026-10-01",announce:!1,lead:{zh:"回忆与记忆的四处收口,都出自 #51 的复审:归档的节点退出回忆索引(这次启动会把索引重建一遍);画像文档的每一行记着来自哪个画布、哪天、是本人说的还是推断的,模型改写后不再丢;新拉出的空节点和阅读器底栏有了和追问框一样的联网、学术、回忆开关;基准的 repair 用例多了一格带陈旧标记的条件。",en:"Four follow-ups from the #51 review, all on recall and memory: archived nodes leave the recall index (the index rebuilds once on this start); every line of the profile documents keeps which canvas it came from, when, and whether you said it or it was inferred, through the model's rewrites; a fresh node and the reader's footer carry the same web, scholar and recall switches as a follow-up; the benchmark's repair cases gain a condition that carries the stale mark."},items:[]},{version:"0.5.8",date:"2026-09-30",announce:!1,lead:{zh:"修复 0.5.7 的一处遗漏:回答里的消毒把画布自己加的标记也剥掉了,从回答文字跳到分支的入口失效,用户高亮和探索标记都退化成默认黄底。现在两种标记保留各自的类和目标,跳转、点状下划线、高亮填色都回来了。",en:"Fixes an oversight in 0.5.7: the answer sanitizer also stripped the marks the canvas adds itself, so the jump from an answer to the branch it bore stopped working and highlights and explore marks fell back to the browser's plain yellow. Both marks keep their class and target again; the jump, the dotted underline and the highlight fill are back."},items:[]},{version:"0.5.7",date:"2026-09-30",announce:!1,lead:{zh:"安全修补:回答里的原始 HTML 先经过消毒再渲染,折叠块、上下标、键帽、高亮、表格、换行照旧,能执行脚本或嵌入外部页面的标签(iframe、object、script、style、form 等)被去掉;此前分享链接、导入的画布或模型引用的网页都能借 srcdoc 的 iframe 在本页面的源里执行代码。托管代理的模型探测只接受公网 https 地址,两处网页快照抓取共用一套地址检查并逐跳核对重定向。另外两处小修:「重跑上游已变」只跑确认框里数到的那些,牌子摘要不再参考已归档的步骤。",en:"Security: raw HTML in an answer is sanitized before rendering; folds, sub/sup, kbd, highlights, tables and line breaks stay, while tags that run scripts or embed pages (iframe, object, script, style, form and the like) are stripped. Until now a shared link, an imported canvas or a page the model quoted could run code in this origin through a srcdoc iframe. The hosted proxy's model probe takes public https endpoints only, and both page-snapshot fetchers share one address guard and check every redirect hop. Two small fixes: replay reruns exactly the stale nodes the dialog counts, and plaque summaries no longer read archived steps."},items:[]},{version:"0.5.6",date:"2026-09-30",announce:!1,lead:{zh:"回忆改成安静的小标签,默认关:输入框旁一个「回忆」,点开是开关、搜索范围(轻量 40 条 / 深挖 2,000 条 / 全量)和带入上下文,改的只对这一次提问生效,「设为默认」写回全局;深挖和全量由判断模型分批看候选,全量先告诉你条数、秒数和费用。判断模型页的开关并进供应商下拉(最后一项「关闭,按规则」);联网和学术搜索也默认关。每个节点都有可缩放的摘要:一句话的回答、笔记、文件都上梯子。双击卡片上的问题,侧栏编辑框带着原文打开。Harness 插件:思维图顶上是自己的标题带(不再压住红绿灯);自己的模型接口回来了,添加、拉模型列表、调用都走插件;不再提示桌面版新版本,插件更新提示直接说在插件页重新添加哪个包;桌面版 0.2 写的 v4 会话文件进得了对话地图。",en:`Recall is a quiet chip, off by default: a "Recall" beside the composer opens the switch, the search reach (light 40 / deep 2,000 / full) and the context brought in; a change there holds for the next ask only, "set as default" writes it back. Deep and full have the decision model read candidates in batches; full first says how many turns, seconds and dollars. The decision model page folds its switch into the provider dropdown (last entry: off, rules decide); web and scholar search start off too. Every node zooms: one-line answers, notes and files get a ladder. Double-clicking a card's question opens the side panel editor with the text in place. Harness plugin: the map wears its own title band (clear of the traffic lights); its own model interfaces are back, added, listed and called through the plugin; no more desktop-app update nudge, and the plugin's own notice names the package to re-add on the Plugins page; the 0.2 desktop's v4 session files reach the atlas.`},items:[]},{version:"0.5.5",date:"2026-09-29",announce:!1,lead:{zh:"换档不再互相盖住:缩小到地图层时,节点的牌子不会超出布局留给它的位置,写不下的摘要在底部渐隐,再放大一档就能看全;折叠卡显示和牌子同一段摘要,放大缩小之间只是字号在变。节点间距略微拉开,已有画布的位置不动,按「一键排版」才换成新间距。另外:从 Finder 启动时也能找到本机的 Pi、Codex、Claude Code 命令行,找不到会说明查过哪些地方,可重新检测;子 Agent 的运行展开在父画布上,作为那一轮旁边的分支;模型接口分成「慢思考 · 回答模型」和「快思考 · 判断模型」两页,只用 Agent 的人也能单独接判断模型;新装机没有模型时会先问一次本机的 Agent。",en:"Zoom tiers no longer cover each other: at map zoom a node's plaque stays inside the room the layout keeps for it, an abstract that runs past it fades out at the bottom and shows in full one step in; the folded card carries the same abstract as the plaque, so zooming only changes the type size. Node gaps open slightly; existing canvases keep their positions until you choose Tidy layout. Also: the Pi, Codex and Claude Code CLIs are found under a Finder launch, and a missing one says where it looked, with a recheck; a subagent's run unfolds on the parent canvas as a branch beside its turn; the model dialog has two pages, slow thinking for answering models and fast thinking for the decision model, which agent-only users can connect on its own; a fresh install with no model asks the local agents first."},items:[]},{version:"0.5.4",date:"2026-09-29",announce:!1,lead:{zh:"鼠标滚轮恢复缩放画布,和 0.5.2 一样。0.5.3 起滚轮改成了平移,这对触控板顺手,却让鼠标用户没法用滚轮缩放。触控板用户可以在画布 ⋯ 菜单打开「滚轮平移画布」:双指滑动即平移,捏合或按住 ⌘/Ctrl 滚动来缩放。",en:"The mouse wheel zooms the canvas again, as in 0.5.2. Since 0.5.3 it panned, which suits a trackpad but left mouse users without wheel zoom. On a trackpad, turn on ⋯ → Wheel pans the canvas: a two-finger scroll pans, pinch or hold ⌘/Ctrl while scrolling to zoom."},items:[]},{version:"0.5.3",date:"2026-09-27",announce:!1,lead:{zh:"圈选多个节点后,工具栏多了「更新节点摘要」:用当前选中的模型为它们一次更新四层摘要,文件、便签和短回答自动跳过。进度在右下角,随时可停。旧画布想整体升级到新摘要,圈一下就行。右键单个节点也是同一个入口。",en:'With several nodes selected, the toolbar gains "Update node summaries": the picked model updates their four summary levels in one go, files, notes and short answers skipped. Progress shows bottom right and can be stopped any time. An older canvas upgrades to the new summaries with one lasso; the right-click item on a single node is the same door.'},items:[{title:{zh:"🧭 摘要写的是这一步新增了什么",en:"🧭 Summaries say what the step adds"},body:{zh:"结论与短述改为由模型撰写。写之前它先读这条思路里前面各步的牌匾,只写本步新增的结论、决定或转向,不重复前面已经说过的;概要仍是原答里的原文摘句,作为证据。旧节点用「更新节点摘要」换新即可。",en:'The takeaway and brief are now written by the model. It first reads the plaques of the earlier steps in the thread, then writes only what this step adds, a conclusion, a decision or a turn, without repeating what came before; the abstract stays verbatim sentences of the answer, as evidence. Older nodes switch over with "Update node summaries".'}},{title:{zh:"🖐️ 触控板双指滑动即平移",en:"🖐️ Two-finger scroll pans"},body:{zh:"在触控板上双指滑动就能移动画布,不用再按住按键拖。捏合缩放不变。鼠标滚轮现在同样是平移,缩放请按住 ⌘(Windows 上是 Ctrl)再滚。感谢 @Pireirik 的贡献。",en:"On a trackpad, a two-finger scroll moves the canvas; no button to hold. Pinch still zooms. A mouse wheel now pans too; hold ⌘ (Ctrl on Windows) to zoom with it. Contributed by @Pireirik."}}]},{version:"0.5.2",date:"2026-09-27",announce:!0,lead:{zh:"🔍 上下文管理重大更新!现在,无论画布缩放至何种比例,节点内容始终保持极佳的阅读体验。",en:"🔍 A major update to context management! Whatever the zoom, every node on the canvas now stays a pleasure to read."},media:{src:{zh:"whats-new/zoom-ladder-zh.mp4",en:"whats-new/zoom-ladder-en.mp4"},alt:{zh:"缩小画布时,牌匾上的结论逐词长成短述再长成摘要",en:"Zooming out, a plaque's takeaway grows word by word into a brief, then an abstract"},width:960,height:600},items:[{title:{zh:"🪜 智能四层摘要",en:"🪜 Four smart summary levels"},body:{zh:"每个回答自动构建「主题、结论、短述、完整概要」四个递进层级,随缩放比例自动无缝切换。",en:"Every answer builds four progressive levels, topic, takeaway, brief and full abstract, and switches between them seamlessly as you zoom."}},{title:{zh:"✨ 丝滑的视觉过渡",en:"✨ Silky visual transitions"},body:{zh:"缩放时,文字会逐词自然展开或收起。保留的关键词会平滑移动,新文本自然淡入,核心重点始终高亮加深。视线聚焦零中断,数十个节点的全局脉络一眼即达。",en:"As you zoom, text unfolds or folds word by word. The words that stay glide into place, new text fades in, and the key points stay highlighted in full ink. Your focus is never broken, and the shape of dozens of nodes reads at a glance."}},{title:{zh:"🔁 新旧节点全面兼容",en:"🔁 New and old nodes alike"},body:{zh:"新回答自动生效该特性;旧节点会在浏览时实时生成摘要层级,若需更精准的 AI 总结,只需右键一键生成。",en:"New answers get it automatically; older nodes build their levels live as you browse, and for a sharper AI-selected summary, one right-click does it."}},{title:{zh:"🎚️ 时间线详略随手调",en:"🎚️ Timeline detail at your fingertips"},body:{zh:"时间线弹窗新增详略滑块,从主题一路拉到完整概要,字号与行距随手指流动,每一步文字完整呈现,告别省略号。",en:"The timeline overview gains a detail slider: glide from topic to full abstract, type and spacing flowing with your drag, every step shown whole, no ellipsis anywhere."},media:{src:{zh:"whats-new/timeline-detail-zh.mp4",en:"whats-new/timeline-detail-en.mp4"},alt:{zh:"拖动时间线弹窗的详略滑块,每一步的文字逐词展开",en:"Dragging the timeline overview's detail slider, each step's text unfolds word by word"},width:720,height:760}},{title:{zh:"🛡️ 所见即所发",en:"🛡️ What you see is what is sent"},body:{zh:"判断模型认定上游改动与答案无关时,「上游已变」标记现在同时从预览和请求中退场,两者始终一致。感谢 Agent Memory Atlas 的审阅指出这一点。",en:'When the decision model rules an upstream change irrelevant, the "upstream changed" mark now leaves the preview and the request together, always in step. Thanks to the Agent Memory Atlas review for catching it.'}},{title:{zh:"🧹 右键菜单焕新",en:"🧹 A refreshed right-click menu"},body:{zh:"「重新生成」更简洁,CLI 相关操作合并为一项,新增「用模型重选摘要」。手动修改过的回答会自动重做摘要。",en:'"Regenerate" is simpler, the CLI actions merge into one, and "Update node summary" joins the menu. Hand-edited answers get their summaries redone automatically.'}}]},{version:"0.5.1",date:"2026-09-26",announce:!1,lead:{zh:"0.5 之后的一批修正。删除正在生成的节点时,那一轮生成随之中止,不再在后台跑完。记忆的自动写入上限按画布分开计,切换画布后重新计;之前是全局三条写满就静默。档案更新只带走模型读过的那几条待归档事实,更新期间新归档的保留下来;档案文件的写入排队进行,不再互相覆盖。why 层不再把执行失败的文件操作算作改动足迹,更新后索引会重建一次。判断模型直接沿用模型接入里保存的 OpenRouter key,不再显示为空、测试不可点。",en:"A round of fixes after 0.5. Deleting a node that is still generating stops that generation instead of letting it run on in the background. The memory judge's automatic-write cap counts per canvas and starts over on a canvas switch; it used to be one global count of three, after which memory went quiet. A dossier update takes only the filed facts the model read and keeps anything filed while it was writing; dossier writes queue instead of overwriting one another. The why layer no longer counts a file operation the harness answered with an error as a change, and the index rebuilds once. The decision model uses the OpenRouter key saved with your model providers, instead of showing an empty field with a disabled test."},items:[]},{version:"0.5.0",date:"2026-09-26",announce:!0,lead:{zh:"🎉 ThoughtDAG 0.5:记忆上线。你在 Pi、Codex、Claude Code、DeepSeek Harness 里聊过的一切,现在接成一个可以回忆的整体。散在几百个会话里的碎片,按主题整理成档案;提问时相关的档案和对话自动带进上下文,跨 Agent、跨时间。背后是快思考与慢思考的分工:慢思考模型回答,快思考模型判断。所有信息都在你自己的机器上。",en:"🎉 ThoughtDAG 0.5: memory. Everything you discussed in Pi, Codex, Claude Code and DeepSeek Harness now forms one whole you can recall. Fragments scattered across hundreds of sessions are organised into dossiers by topic; when you ask, the relevant dossiers and conversations ride into the context, across agents and across time. Behind it, a division of labour: a slow-thinking model answers, a fast-thinking model decides. Everything stays on your machine."},items:[{title:{zh:"碎片串成一条线",en:"Fragments become a thread"},body:{zh:"昨天在 Codex 里定的阈值,上周在 Claude Code 里排除的方案,今天在画布上问起时都在。每个主题一份档案:是什么、定过什么、到哪一步、还没解决什么,每句都能点回原来的那轮对话。「你」是两份文档:偏好与身份,记到新东西时改写而不是堆砌。原来的记忆条目已并入。",en:"The threshold you settled in Codex yesterday and the approach you ruled out in Claude Code last week are there when you ask on the canvas today. Every topic keeps a dossier: what it is, what was decided, where it stands, what is still open, each line pointing back to its turn. Your profile is two documents, preferences and identity, rewritten rather than piled up. Earlier memory entries were folded in."},link:{label:{zh:"记忆指南",en:"The memory guide"},href:`${Uc}/zh/guides/memory`}},{title:{zh:"提问时自动回忆",en:"Recall as you ask"},media:{src:{zh:"whats-new/jev-recall.mp4",en:"whats-new/jev-recall.mp4"},alt:{zh:"回忆流程里,判断模型半秒内从候选片段中选出相关的几条",en:"In the recall flow the decision model picks the relevant excerpts from the candidates in under a second"},width:1200,height:720},body:{zh:"开着「回忆」提问,先判断问题涉及哪些主题,把档案整份带进去;问的是细节时再补几条原话。带了什么、花了多少,面板上一条一条看得见,不想要的划掉就不带。带入量三档:省、标准、多带。",en:"With recall on, a question is first matched to its topics and their dossiers ride in whole; a question about a detail brings a few verbatim excerpts too. What came in and what it cost is listed item by item; strike one and it stays out. Three amounts: lean, standard, generous."}},{title:{zh:"快思考,慢思考",en:"Fast thinking, slow thinking"},body:{zh:"回答你的是慢思考模型。判断「这条相关吗」「这句是决定吗」「这处改动影响吗」的是快思考模型:半秒一次,返回校准过的概率,让回忆、地图徽章和「上游已变」都有依据。模型选择器里一行开关,默认开;关掉全部退回规则,功能不变。",en:"The slow-thinking model answers you. The fast-thinking model decides — is this relevant, is this line a decision, does this change matter — in half a second, with calibrated probabilities, so recall, map badges and “upstream changed” rest on evidence. One switch in the model picker, on by default; off, every decision falls back to a rule and nothing stops working."}},{title:{zh:"接入一个快思考模型",en:"Connect a fast-thinking model"},body:{zh:"Jev 类判断模型可以经你已保存的聚合商接入直接使用,也支持官方接口和自建服务;没有接入时会提示,一切照常。",en:"A Jev-class decision model runs through the aggregator access you already saved, through the official endpoint, or from a self-hosted server; without one you are told, and everything still works."},link:{label:{zh:"怎么接入",en:"How to connect one"},href:`${Uc}/zh/setup#decision-model`}},{title:{zh:"一切都在本地",en:"All of it stays local"},body:{zh:"索引、主题标签、档案存在本机 .thoughtdag 目录,画像文档存在应用本地。判断时发出去的只有问题和候选片段,发给你自己选的接入。",en:"The index, topic labels and dossiers live in your machine's .thoughtdag folder; your profile lives in the app's own storage. A decision sends only the question and the candidate excerpts, to the access you chose."}}]},{version:"0.4.20",date:"2026-09-23",announce:!1,lead:{zh:"DeepSeek Harness 插件一轮实测后的整理。「对话 | 思维图」开关:对话页顶部仍是浮动的,切到思维图后它移到画布顶栏「画布名」右侧,不再压住画布工具栏。工作目录改用 Harness 自己的目录选择器:本机运行时弹的就是系统的文件夹对话框,远程访问时回落为输入路径;0.4.19 里自带的目录浏览器撤掉。Harness Agent 也能选工作目录,新会话按所选目录运行。插件里去掉配置模型 API 的入口。实时镜像刷新会话时不再把镜头拉回节点。节点记录的是发起请求时的模型,执行中切换选择器不再改写徽章。Harness 执行中的每个工具调用都列为一条步骤,思考尾巴显示在下方。备份提醒去掉。",en:"DeepSeek Harness plugin, after a round of hands-on testing. The 对话 | 思维图 switch still floats over the chat; on the canvas it sits in the canvas's own top bar next to the canvas chip, so it never covers the toolbar. The working directory is chosen in the harness's own picker: the system folder dialog when the harness runs on this machine, a typed path when reached remotely; the folder browser 0.4.19 carried is withdrawn. The Harness Agent gets the folder chip too, and a fresh session runs where it says. The API-key door is gone inside the plugin. The live mirror no longer drags the camera back to a node while its session refreshes. A node records the model it was asked with; switching the picker mid-run no longer relabels it. Every tool call of a harness run is listed as a step, the thinking beneath. The backup reminder is removed."},items:[]},{version:"0.4.19",date:"2026-09-23",announce:!1,lead:{zh:"DeepSeek Harness 插件:Harness Agent 节点的回答不再「闪一下就没了」。新版 Harness(0.1.5-rc.3)不再把逐字流写进会话日志,一步只落一条 assistant/message;画布续读实时日志时按会话列表报的序号少读了一条,恰好是带答案的那条,节点随后被镜像成空回答。现在按实际持有的最后一条事件续读,且镜像永不把已有回答改写为空。思考过程重新同步显示:宿主订阅 Harness 新的流事件(agent/assistant-stream),正文和思考逐字到达节点,没有流的运行时从每步的 reasoning 块补发。「对话 | 思维图」开关回到浮动位置,空态也能切换(0.4.18 的标题栏开关撤回)。Agent 的工作目录改为浏览宿主机的文件夹来选,也仍可直接输入路径。",en:"DeepSeek Harness plugin: a Harness Agent node no longer shows its answer for a moment and then loses it. Newer Harness builds (0.1.5-rc.3) stop writing the token stream into the session log; a step lands as one assistant/message. When the canvas read the live log incrementally it asked from the seq the session list reported and skipped exactly one event, the one carrying the answer, and the node was then mirrored as an empty reply. It now continues from the last event it actually holds, and a mirror never rewrites an existing answer to nothing. Reasoning shows live again: the host subscribes to the Harness's new stream event (agent/assistant-stream), so text and reasoning reach the node as they are produced; a runtime without that stream gets each step's reasoning block instead. The 对话 | 思维图 switch floats again and works on the empty page (the 0.4.18 header switch is withdrawn). An agent's working directory is chosen by browsing the host's folders, with a path field still there for typing."},items:[]},{version:"0.4.18",date:"2026-09-23",announce:!1,lead:{zh:"DeepSeek Harness 插件:历史会话列表在新版 Harness 上不再为空。dsh 从 0.1.5-rc.2 起把会话格式版本写进日志文件名(session.v3.jsonl.zstd),插件现在按已知文件名探测,新旧两种都认(#44,感谢 @LHN-xiao-hai-tun)。模型选择器加宽,条目悬停显示完整名称,Agent 执行组的长名字改为换行而不是截断,flash 与 flash-vision 一眼可辨(#43)。",en:"DeepSeek Harness plugin: the list of past sessions is no longer empty on newer Harness builds. From 0.1.5-rc.2 dsh writes the session format version into the log file name (session.v3.jsonl.zstd); the plugin now probes the known names and reads both (#44, thanks @LHN-xiao-hai-tun). The model picker is wider, every entry shows its full name on hover, and long names in the agent group wrap instead of being cut, so flash and flash-vision tell apart at a glance (#43)."},items:[]},{version:"0.4.17",date:"2026-09-21",announce:!1,lead:{zh:"DeepSeek Harness 插件:从画布向 Harness 提问时,节点只接自己那一轮。此前如果你同时在聊天框里发消息,画布节点会拿到你那轮的回答、在你那轮结束时提前收尾,并把镜像标记挂到错误的轮次上,产生重复节点;工具审批也可能被画布抢走。现在 Host 用 dsh 记在消息上的请求 id 精确认出自己的那一轮,文本、工具调用、审批、结束全部按这一轮过滤(#42,感谢 @nanami-0713)。桌面版本次只同步版本号。",en:"DeepSeek Harness plugin: a question asked from the canvas now receives only its own turn. Before, if you were also typing in the chat, the canvas node could receive your turn's answer, finish early when your turn ended, and stamp its mirror mark on the wrong turn, leaving duplicate nodes; tool approvals could be captured by the canvas as well. The host now recognises its own turn by the request id dsh records on the message, and filters text, tool calls, approvals and the end of turn to that turn alone (#42, thanks @nanami-0713). The desktop app only moves its version number."},items:[]},{version:"0.4.16",date:"2026-09-17",announce:!1,lead:{zh:"分区框:两个只是部分重叠的框不再互相收编。拖动大框时,重叠的小框和它自己的节点留在原地;拖动和一键排版现在用同一条成员规则,普通节点按中心点归属,框只有完整落在另一个框里才算它的成员(#40,感谢 @nanami-0713)。DeepSeek Harness 插件:「插件有新版本」提示复制的命令带上具体版本号,发版当天也能立刻装到新版。",en:"Frames: two frames that merely overlap no longer own each other. Dragging the larger one leaves the overlapping smaller frame and its own nodes in place; dragging and auto layout now share one membership rule, nodes by centre and a frame only when it lies fully inside another (#40, thanks @nanami-0713). DeepSeek Harness plugin: the update hint now copies a command naming the exact version, so a release installs on its first day too."},items:[]},{version:"0.4.15",date:"2026-09-15",announce:!1,lead:{zh:"分区框三件事:一键排版后,框跟着框内的节点重新包好(#32);拖动外框会带动嵌套在里面的框;重叠时小框叠在大框上面,标题栏不再被盖住。三项均来自 @hexu321。DeepSeek Harness 插件:「对话 | 思维图」切换器移进会话标题栏,不再遮挡标题;返回按钮居中,画布右上的工具栏保持可见;从画布切回会话的跳转修好了(#30,来自 @nanami-0713)。插件重新在 npm 上发布,安装命令恢复为包名。",en:"Frames, three fixes: after auto layout a frame re-wraps the nodes it held (#32); dragging an outer frame carries the frames nested inside it; where frames overlap, the smaller one stacks on top so its title bar stays reachable. All three by @hexu321. DeepSeek Harness plugin: the 对话 | 思维图 switch moves into the session header and no longer covers the title; the back button sits top centre, clear of the canvas toolbar; jumping from the canvas back to a session works again (#30, by @nanami-0713). The plugin is back on npm and the install command is the package name again."},items:[]},{version:"0.4.14",date:"2026-09-11",announce:!1,lead:{zh:"插件的「有新版本」提示现在复制 dsh plugin --profile web add dsh-thoughtdag@latest,这条命令对从 npm 装和从 Release 文件装的用户都有效(update 对文件安装无效)。其余同 0.4.13。",en:"The plugin's update hint now copies dsh plugin --profile web add dsh-thoughtdag@latest, which works for installs from npm and from a release file alike (update does nothing for a file install). Otherwise the same as 0.4.13."},items:[]},{version:"0.4.13",date:"2026-09-11",announce:!1,lead:{zh:"修复:DeepSeek Harness 插件里,模型选择器丢失了「Harness · 模型」这一组 Agent 条目(0.4.11 起,机器上没装 Pi、Codex 等命令行时整组消失)。原因是思维图把 Harness 给的条目当成本机命令行的探测结果替换掉了,现在只替换命令行报来的那几种。插件里「如何使用」的教程动图也能显示了(#35,感谢 @Moya-Doc)。",en:`Fix: inside the DeepSeek Harness plugin, the model picker lost the "Harness · model" agent entries (since 0.4.11; with no Pi or Codex CLI on the machine the whole group vanished). The canvas had been replacing the harness's entries with the local CLI probe; now only the entries the CLIs report get replaced. The tutorial gifs inside the plugin load again (#35, thanks @Moya-Doc).`},items:[]},{version:"0.4.12",date:"2026-09-10",announce:!1,lead:{zh:"DeepSeek Harness 插件里,Agent 子节点现在续接父节点的会话;同一父节点下的第二个分支从父节点那一轮分叉出自己的会话,preset 的会话状态不再在每个子节点重头开始(#28、#29)。插件的构建脚本在 Windows 上也能跑了(#24、#26)。桌面版本次只同步版本号。",en:"Inside the DeepSeek Harness plugin, an agent child node now continues its parent's session, and a second branch off the same parent forks its own session at that parent's turn, so a preset's session state no longer restarts at every child (#28, #29). The plugin's build script runs on Windows too (#24, #26). The desktop app only moves its version number."},items:[]},{version:"0.4.11",date:"2026-09-08",announce:!1,lead:{zh:"性能优化:启动更快,后台更省,多个工具调用并行时更稳;300 节点以上的画布实测流畅。ThoughtDAG 现在可以用 Claude Code、Codex、Pi 作为节点的 Agent 运行时,处于测试阶段。",en:"Performance: faster launch, lighter in the background, steadier when several tool calls run in parallel; canvases past 300 nodes measured smooth. ThoughtDAG can now run a node through Claude Code, Codex or Pi as its agent runtime, in testing."},items:[]},{version:"0.4.10",date:"2026-09-07",announce:!1,lead:{zh:"Agent 执行预览继续:Codex 加入,和 Pi 一样在画布里带工具作答;这条通道现在在桌面版、本地网页版和 DeepSeek Harness 插件里都可用;插件里的 Harness Agent 按模型平铺;插件有新版本时画布会提示。",en:"Agent runs, preview continued: Codex joins Pi, answering with tools right from the canvas; the lane now works in the desktop app, the local web app and the DeepSeek Harness plugin alike; inside the plugin the Harness agent lists one entry per model; the canvas tells you when a newer plugin is out."},items:[]},{version:"0.4.9",date:"2026-09-07",announce:!1,lead:{zh:"Agent 执行预览:桌面版的模型选择器多了「Agent 执行」组,装了 Pi 的话可以直接在画布里让它带工具作答,轨迹、足迹、审批和提问都落在节点上,工作目录在顶栏可见可改。正式版会连同 Claude Code 与 Codex 一起发布。DeepSeek Harness 插件里的审批卡片同步更新。",en:'Agent runs, preview: the desktop picker gains an "Agent runs" group; with Pi installed, a question runs through it with tools right from the canvas, and the trace, footprints, approvals and questions land on the node, with the working directory visible on the toolbar. The full release will arrive together with Claude Code and Codex. The approval card inside the DeepSeek Harness plugin is updated alike.'},items:[]},{version:"0.4.8",date:"2026-09-07",announce:!1,lead:{zh:"DeepSeek Harness 插件在 Windows 上能打开了:静态资源和会话目录的路径守卫此前只认正斜杠,Windows 用户看到的是一片 403。感谢 GitHub 上的报告(#23)。桌面版本次只同步版本号。",en:"The DeepSeek Harness plugin now opens on Windows: the path guards for static assets and session directories only accepted forward slashes, so Windows users saw nothing but 403s. Thanks to the report on GitHub (#23). The desktop app only moves its version number this time."},items:[]},{version:"0.4.7",date:"2026-09-07",announce:!1,lead:{zh:"DeepSeek Harness 插件里,Agent 需要你批准的操作现在直接出现在节点上:工具、命令、理由,允许一次或拒绝,决定留在节点记录里。桌面版本次只同步版本号。",en:"Inside the DeepSeek Harness plugin, an action the agent needs approved now appears on the node itself: tool, command, reason, allow once or reject, and the decision stays in the node's record. The desktop app only moves its version number this time."},items:[]},{version:"0.4.6",date:"2026-09-06",announce:!0,lead:{zh:"🎉 Pi 的会话进了对话地图,「⋯」菜单里多了更新历史,随时能回看每一版改了什么。",en:"🎉 Pi sessions join the Session Atlas, and the ⋯ menu gains a release history, so what every version changed is one click away."},items:[{title:{zh:"Pi 的会话也在地图上了",en:"Pi sessions are on the map"},body:{zh:"本地 Pi 会话按项目聚在一起,打开就是一张图。Pi 里的每次分叉在图上就是一条支线,不再压成一条直线。命令行 why 和 MCP 也同步认识 Pi 留下的文件足迹。",en:"Local Pi sessions group by project and open as a graph. Every fork you made in Pi shows up as a branch instead of being flattened into one line. The why command and MCP index Pi's file footprints too."},link:{label:{zh:"怎么用",en:"How it works"},href:`${Uc}/zh/guides/session-atlas`}},{title:{zh:"更新历史,随时补看",en:"Release history, whenever you like"},body:{zh:"右上「⋯」菜单,「如何使用」下面。每个版本改了什么都在这里,从新到旧,当前版本有标记。",en:"In the ⋯ menu, under How it works: what each release changed, newest first, with the version you are running marked."}}]},{version:"0.4.5",date:"2026-09-06",announce:!0,lead:{zh:"🎉 这是 ThoughtDAG 到目前为止最大的一次升级:散在各个 Agent 里的对话接成了一张地图,能从画布里查,还能直接在 DeepSeek Harness 里用。四件新东西,都值得试一试。",en:"🎉 The biggest ThoughtDAG release so far: the conversations scattered across your agents become one map, you can query them, and it all runs inside DeepSeek Harness. Four new things, each worth a try."},items:[{title:{zh:"跨 Agent 的对话地图,终于连成一张",en:"Session Atlas: all your agents, one map"},body:{zh:"Claude Code、Codex 和 DeepSeek Harness 的本地会话按项目文件夹聚在一起,点开就是一张图,随对话实时生长。",en:"Local Claude Code, Codex and DeepSeek Harness sessions, grouped by project; open one as a graph and it follows the conversation live."},link:{label:{zh:"怎么用",en:"How it works"},href:`${Uc}/zh/guides/session-atlas`}},{title:{zh:"命令行 why:一条命令找回塑造文件的那些对话",en:"thoughtdag why: one command finds the conversations that shaped a file"},body:{zh:"npx thoughtdag why <文件> 列出哪些轮次读过、改过它,当时问了什么、改了什么;find 按原话搜,MCP 让 Agent 自己来查。",en:"npx thoughtdag why <file> lists the turns that read or changed it, what was asked and what changed; find searches verbatim; MCP lets your agent ask."},link:{label:{zh:"命令与 MCP",en:"CLI and MCP"},href:`${Uc}/zh/guides/why-layer`}},{title:{zh:"DeepSeek Harness 插件上线",en:"DeepSeek Harness plugin is live"},body:{zh:'dsh plugin --profile web add dsh-thoughtdag,Harness 的网页里多一个"思维图"视图:在画布上提问、让 Harness 的 Agent 带工具作答,why 也成了它的原生工具。',en:"dsh plugin --profile web add dsh-thoughtdag adds a canvas view to the Harness web UI: ask from the canvas, let its agent answer with tools, and why becomes a native tool there."},link:{label:{zh:"插件说明",en:"Plugin README"},href:"https://github.com/chenxiachan/thoughtdag/tree/main/dsh#readme"}},{title:{zh:"文档站上线",en:"The docs site is live"},body:{zh:"概念、任务指南、命令字典和隐私说明各有一页,中英文对照。感谢一路同行,欢迎来 Discussions 说说你怎么用它。",en:"Concepts, task guides, the command dictionary and the privacy notes, each on its own page, in both languages. Thank you for coming this far with us; tell us how you use it in Discussions."},link:{label:{zh:"打开文档",en:"Open the docs"},href:`${Uc}/zh/`}}]},{version:"0.4.4",date:"2026-09-04",announce:!1,lead:{zh:"DeepSeek Harness 成为对话地图的内置来源:它的 zstd 日志由桌面壳逐帧解码,每条消息一个节点,工具调用与结果配对成附件。",en:"DeepSeek Harness becomes a built-in Atlas source: the shell decodes its zstd logs frame by frame, one node per message, tool calls paired with their results as attachments."},items:[]},{version:"0.4.3",date:"2026-09-03",announce:!1,lead:{zh:"深链接可以直达某一轮,画布可以按稳定 id 打开;子 Agent 的会话文件不再打扰实时监听。",en:"A deep link can land on a turn and a canvas opens by its stable id; subagent session files no longer disturb the live watcher."},items:[]},{version:"0.4.2",date:"2026-09-02",announce:!1,lead:{zh:"镜像节点列出那一轮碰过的文件(✏️ 改过、📖 读过),预览用结论而不是开头;子 Agent 的会话作为子线程识别,报告折回发起它的那一轮。",en:"A mirrored node lists the files its turn touched (✏️ edited, 📖 read) and previews the conclusion rather than the opening line; subagent files are recognized as sub-threads and their reports fold into the launching turn."},items:[]},{version:"0.4.1",date:"2026-09-01",announce:!1,lead:{zh:"Agent 对话地图首发:本地 Claude Code 与 Codex 的会话按项目文件夹聚成一张图,一键接入,随对话实时生长。",en:"Session Atlas debuts: local Claude Code and Codex sessions group by project folder into one map, connect in one click, and grow with the conversation."},items:[]}];function Yy(e,t){const n=e.split(".").map(r=>parseInt(r,10)||0),a=t.split(".").map(r=>parseInt(r,10)||0);for(let r=0;r<Math.max(n.length,a.length);r++){const s=(n[r]??0)-(a[r]??0);if(s!==0)return s}return 0}function sm(e,t){return QM.filter(n=>n.announce&&Yy(n.version,t)<=0&&(e===null||Yy(n.version,e)>0))}const Ky="thoughtdag.whatsNewSeen",Cue=new URLSearchParams(window.location.search);function _ue(){if(!Os)return[];const e=Cue.get("wn");if(e==="1")return sm(null,Os);if(e)return sm(e,Os);let t=null;try{t=localStorage.getItem(Ky)}catch{}if(t===null){let n=!1;try{n=!!(localStorage.getItem("thoughtdag.tutorialDone")||localStorage.getItem("thoughtdag.lastBackupAt"))}catch{}if(!n){try{localStorage.setItem(Ky,Os)}catch{}return[]}return sm(null,Os)}return t===Os?[]:sm(t,Os)}function ZM({media:e,lang:t}){const n=e.src[t],a=/\.(mp4|webm)$/i.test(n);return l.jsx("div",{className:"mt-3 rounded-xl border border-line overflow-hidden bg-wash",style:{aspectRatio:`${e.width} / ${e.height}`},"data-whats-new-media":!0,children:a?l.jsx("video",{src:`/thoughtdag/${n}`,autoPlay:!0,loop:!0,muted:!0,playsInline:!0,className:"w-full h-full object-cover","aria-label":e.alt[t]}):l.jsx("img",{src:`/thoughtdag/${n}`,alt:e.alt[t],className:"w-full h-full object-cover"})})}function JM({items:e,lang:t}){return e.length===0?null:l.jsx("ol",{className:"divide-y divide-line",children:e.map((n,a)=>l.jsxs("li",{className:"py-3 flex gap-3.5",children:[l.jsx("span",{className:"shrink-0 w-6 h-6 rounded-full bg-accent/10 text-accent text-xs font-semibold flex items-center justify-center mt-0.5",children:a+1}),l.jsxs("div",{className:"min-w-0",children:[l.jsx("div",{className:"text-sm font-medium text-ink",children:n.title[t]}),l.jsx("p",{className:"text-sm text-ink-muted leading-relaxed mt-1 [overflow-wrap:anywhere]",children:n.body[t]}),n.media&&l.jsx(ZM,{media:n.media,lang:t}),n.link&&l.jsxs("a",{href:n.link.href,target:"_blank",rel:"noreferrer",className:"inline-block mt-1.5 text-xs font-medium text-accent hover:underline",children:[n.link.label[t]," →"]})]})]},a))})}function Mue(){const[e,t]=R.useState(()=>_ue()),n=e.length>0,a=Aa(u=>u.lang),r=Tt(),s=R.useRef(null),o=()=>{if(Os)try{localStorage.setItem(Ky,Os)}catch{}t([])};return R.useEffect(()=>{if(!n)return;s.current?.focus({preventScroll:!0});const u=d=>{d.stopPropagation(),(d.key==="Escape"||d.key==="Enter")&&o()};return window.addEventListener("keydown",u,!0),()=>window.removeEventListener("keydown",u,!0)},[n]),n?l.jsx("div",{className:"fixed inset-0 z-[100] bg-black/25 flex items-center justify-center animate-fade-in p-6",onClick:o,children:l.jsxs("div",{className:"bg-card border border-line rounded-2xl shadow-xl w-[680px] max-w-full max-h-[85vh] overflow-y-auto",onClick:u=>u.stopPropagation(),role:"dialog","aria-labelledby":"whats-new-title","data-whats-new":!0,children:[l.jsxs("div",{className:"px-6 pt-5 pb-4 border-b border-line",children:[l.jsx("div",{className:"text-2xs uppercase tracking-wide text-ink-faint",children:"ThoughtDAG"}),l.jsx("h2",{id:"whats-new-title",className:"text-base font-semibold text-ink mt-0.5",children:ve(r("whatsNew.title"),{v:Os??""})}),e.length>1&&l.jsx("p",{className:"text-xs text-ink-faint mt-1",children:r("whatsNew.multi")})]}),l.jsx("ol",{className:"px-6 divide-y divide-line",children:e.map(u=>l.jsxs("li",{className:"py-4","data-release":u.version,children:[e.length>1&&l.jsxs("div",{className:"flex items-baseline gap-2.5 mb-1.5",children:[l.jsxs("span",{className:"text-sm font-semibold text-ink tabular-nums",children:["v",u.version]}),l.jsx("span",{className:"text-xs text-ink-faint tabular-nums",children:u.date})]}),l.jsx("p",{className:"text-sm text-ink-muted leading-relaxed [overflow-wrap:anywhere]",children:u.lead[a]}),u.media&&l.jsx(ZM,{media:u.media,lang:a}),l.jsx(JM,{items:u.items,lang:a})]},u.version))}),l.jsxs("div",{className:"sticky bottom-0 bg-card px-6 py-4 border-t border-line flex items-center justify-between gap-4",children:[l.jsx("button",{onClick:()=>{o(),ce.getState().setReleaseNotesOpen(!0)},className:"text-xs text-ink-muted hover:text-ink hover:underline transition-colors","data-whats-new-all":!0,children:r("whatsNew.seeAll")}),l.jsx("button",{ref:s,onClick:o,className:"text-xs text-white px-4 py-2 rounded-lg bg-accent hover:bg-accent-strong transition-colors",children:r("whatsNew.ok")})]})]})}):null}function Iue(){const e=Tt(),t=ce(a=>a.ladderJob);if(R.useEffect(()=>{if(!t||t.running)return;const a=setTimeout(kN,8e3);return()=>clearTimeout(a)},[t]),!t)return null;const n=t.total?Math.min(1,(t.done+t.failed)/t.total):1;return l.jsxs("div",{className:"fixed bottom-4 right-4 z-[85] w-[300px] bg-card border border-line rounded-xl shadow-lg px-4 py-3 animate-fade-in","data-ladder-job":!0,"data-ladder-job-running":t.running?"yes":"no",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(g2,{size:14,strokeWidth:1.75,className:"text-accent shrink-0"}),l.jsx("span",{className:"text-xs font-medium text-ink flex-1",children:e("ladder.jobTitle")}),t.running?l.jsxs("button",{onClick:Rle,disabled:t.cancelled,className:"flex items-center gap-1 text-2xs text-ink-muted hover:text-red-600 disabled:opacity-50","data-ladder-job-stop":!0,children:[l.jsx(V0,{size:10,strokeWidth:1.75,fill:"currentColor"})," ",t.cancelled?e("ladder.jobStopping"):e("ladder.jobStop")]}):l.jsx("button",{onClick:kN,className:"text-ink-faint hover:text-ink",title:e("ladder.jobClose"),"data-ladder-job-close":!0,children:l.jsx(on,{size:13,strokeWidth:1.75})})]}),l.jsx("div",{className:"mt-2 h-1 rounded-full bg-wash overflow-hidden",children:l.jsx("div",{className:"h-full bg-accent transition-[width] duration-300",style:{width:`${Math.round(n*100)}%`}})}),l.jsx("p",{className:"mt-1.5 text-2xs text-ink-muted tabular-nums","data-ladder-job-line":!0,children:t.running?ve(e("ladder.jobProgress"),{n:t.done+t.failed,m:t.total,model:t.model}):(t.cancelled?ve(e("ladder.jobStopped"),{n:t.done}):ve(e("ladder.jobDone"),{n:t.done,k:t.skipped}))+(t.failed?ve(e("ladder.jobFailed"),{f:t.failed}):"")}),!t.running&&t.failed>0&&t.lastError&&l.jsx("p",{className:"mt-1 text-2xs text-red-500 break-words","data-ladder-job-error":!0,children:t.lastError})]})}function Oue(){const e=ce(r=>r.releaseNotesOpen),t=ce(r=>r.setReleaseNotesOpen),n=Aa(r=>r.lang),a=Tt();return R.useEffect(()=>{if(!e)return;const r=s=>{s.key==="Escape"&&(s.stopPropagation(),t(!1))};return window.addEventListener("keydown",r,!0),()=>window.removeEventListener("keydown",r,!0)},[e,t]),e?l.jsx("div",{className:"fixed inset-0 z-[100] bg-black/25 flex items-center justify-center animate-fade-in p-6",onClick:()=>t(!1),children:l.jsxs("div",{className:"bg-card border border-line rounded-2xl shadow-xl w-[680px] max-w-full max-h-[85vh] overflow-y-auto",onClick:r=>r.stopPropagation(),role:"dialog","aria-labelledby":"release-notes-title","data-release-notes":!0,children:[l.jsxs("div",{className:"px-6 pt-5 pb-4 border-b border-line",children:[l.jsx("div",{className:"text-2xs uppercase tracking-wide text-ink-faint",children:"ThoughtDAG"}),l.jsx("h2",{id:"release-notes-title",className:"text-base font-semibold text-ink mt-0.5",children:a("releaseNotes.title")})]}),l.jsx("ol",{className:"px-6 divide-y divide-line",children:QM.map(r=>{const s=Os===r.version;return l.jsxs("li",{className:"py-4","data-release":r.version,children:[l.jsxs("div",{className:"flex items-baseline gap-2.5 flex-wrap",children:[l.jsxs("span",{className:"text-sm font-semibold text-ink tabular-nums",children:["v",r.version]}),l.jsx("span",{className:"text-xs text-ink-faint tabular-nums",children:r.date}),s&&l.jsx("span",{className:"text-2xs font-medium uppercase tracking-wide text-accent bg-accent/10 rounded-full px-2 py-0.5",children:a("releaseNotes.current")})]}),l.jsx("p",{className:"text-sm text-ink-muted leading-relaxed mt-1.5 [overflow-wrap:anywhere]",children:r.lead[n]}),l.jsx(JM,{items:r.items,lang:n})]},r.version)})}),l.jsx("div",{className:"sticky bottom-0 bg-card px-6 py-4 border-t border-line flex justify-end",children:l.jsx("button",{onClick:()=>t(!1),className:"text-xs text-ink px-4 py-2 rounded-lg border border-line hover:bg-wash transition-colors",children:a("common.close")})})]})}):null}const Ob=e=>e.split("/").filter(Boolean).slice(-1)[0]??e;function Due(){const e=Tt(),t=ce(_=>_.selectedModel),n=sn(_=>_.activeId),a=sn(_=>_.projects),r=se(_=>_.nodes.length),[s,o]=R.useState(null),[u,d]=R.useState(null),[h,m]=R.useState(!1),[p,x]=R.useState(""),[,b]=R.useState(0),y=R.useRef(null),w=!!window.desktopSessions&&M2(t),E=!!window.desktopAgents&&(li(t)||w);if(R.useEffect(()=>{if(!E)return;let _=!0;return W2(w).then(A=>{_&&o(A)}),UV().then(A=>{_&&d(A)}),()=>{_=!1}},[E,w,n,a,r]),R.useEffect(()=>{if(!h)return;const _=H=>{y.current&&!y.current.contains(H.target)&&m(!1)},A=H=>{H.key==="Escape"&&m(!1)};return document.addEventListener("mousedown",_),document.addEventListener("keydown",A),()=>{document.removeEventListener("mousedown",_),document.removeEventListener("keydown",A)}},[h]),!E||!s)return null;const v=a.find(_=>_.id===n),N=[...new Set(a.map(_=>_.agentCwd).filter(_=>!!_))].filter(_=>_!==v?.agentCwd).slice(0,5),S=async _=>{n&&(await Q2(n,_),m(!1))},C=window.desktopAgents?.capabilities?.nativePicker!==!1,I=async()=>{const _=await window.desktopAgents.pickCwd();_?await S(_):window.desktopAgents?.capabilities?.nativePicker===!1&&b(A=>A+1)},O=async()=>{const _=p.trim();_.startsWith("/")&&await S(_)};return l.jsxs("div",{ref:y,className:"relative",children:[l.jsxs("button",{onClick:_=>{_.stopPropagation(),m(A=>!A)},className:"bg-card/90 backdrop-blur border border-line rounded-lg h-8 px-2.5 flex items-center gap-1.5 shadow-sm hover:bg-wash transition-colors text-xs text-ink max-w-[220px]",title:`${e("agent.cwd")} · ${s.cwd}`,"data-agent-cwd":s.kind,children:[l.jsx(pu,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),l.jsx("span",{className:"truncate",children:s.kind==="workspace"?e("agent.cwdWorkspace"):Ob(s.cwd)}),l.jsx(ur,{size:12,strokeWidth:1.75,className:"text-ink-faint shrink-0"})]}),h&&l.jsxs("div",{className:"absolute right-0 top-full mt-1.5 w-[320px] bg-card border border-line rounded-xl shadow-lg py-1.5 z-50 animate-fade-in",onClick:_=>_.stopPropagation(),children:[l.jsx("p",{className:"text-2xs text-ink-faint uppercase tracking-wider font-medium px-3 pt-1 pb-1",children:e("agent.cwd")}),l.jsxs("button",{onClick:()=>{S(void 0)},className:"w-full text-left px-3 py-2 text-xs hover:bg-wash flex items-center gap-2",children:[l.jsxs("span",{className:"flex-1 min-w-0",children:[l.jsx("span",{className:"block text-ink",children:u?e("agent.cwdMirrored"):s.kind==="session"?e("agent.cwdSession"):e("agent.cwdWorkspace")}),l.jsx("span",{className:"block text-2xs text-ink-faint truncate",children:u??(s.kind==="session"?s.cwd:e("agent.cwdWorkspaceHint"))})]}),!v?.agentCwd&&l.jsx(es,{size:13,strokeWidth:2,className:"shrink-0 text-accent"})]}),v?.agentCwd&&l.jsxs("button",{onClick:()=>{S(v.agentCwd)},className:"w-full text-left px-3 py-2 text-xs hover:bg-wash flex items-center gap-2",children:[l.jsxs("span",{className:"flex-1 min-w-0",children:[l.jsx("span",{className:"block text-ink",children:Ob(v.agentCwd)}),l.jsx("span",{className:"block text-2xs text-ink-faint truncate",children:v.agentCwd})]}),l.jsx(es,{size:13,strokeWidth:2,className:"shrink-0 text-accent"})]}),N.length>0&&l.jsx("p",{className:"text-2xs text-ink-faint uppercase tracking-wider font-medium px-3 pt-2 pb-1",children:e("agent.cwdRecent")}),N.map(_=>l.jsx("button",{onClick:()=>{S(_)},className:"w-full text-left px-3 py-1.5 text-xs hover:bg-wash flex items-center gap-2",children:l.jsxs("span",{className:"flex-1 min-w-0",children:[l.jsx("span",{className:"block text-ink",children:Ob(_)}),l.jsx("span",{className:"block text-2xs text-ink-faint truncate",children:_})]})},_)),l.jsx("div",{className:"border-t border-line/60 my-1"}),C?l.jsxs("button",{onClick:()=>{I()},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash flex items-center gap-2","data-agent-cwd-pick":!0,children:[l.jsx(pu,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",e("agent.cwdPick")]}):l.jsxs("div",{className:"px-3 py-2 flex items-center gap-2",children:[l.jsx("input",{value:p,onChange:_=>x(_.target.value),onKeyDown:_=>{_.stopPropagation(),_.key==="Enter"&&O()},placeholder:e("agent.cwdType"),className:"flex-1 min-w-0 text-xs font-mono bg-wash border border-line rounded-md px-2 py-1 focus:outline-none focus:border-accent/60","data-agent-cwd-input":!0}),l.jsx("button",{onClick:()=>{O()},className:"text-xs text-accent hover:underline shrink-0",children:e("agent.cwdUse")})]}),l.jsx("div",{className:"border-t border-line/60 my-1"}),l.jsx("p",{className:"text-2xs text-ink-faint uppercase tracking-wider font-medium px-3 pt-1 pb-1",children:e("agent.guard")}),l.jsxs("button",{onClick:()=>{YE("ask"),m(!1)},className:"w-full text-left px-3 py-1.5 text-xs hover:bg-wash flex items-center gap-2","data-agent-guard":"ask",children:[l.jsx(FU,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),l.jsxs("span",{className:"flex-1 min-w-0",children:[l.jsx("span",{className:"block text-ink",children:e("agent.guardAsk")}),l.jsx("span",{className:"block text-2xs text-ink-faint",children:e("agent.guardAskHint")})]}),(v?.agentGuard?.mode??"ask")==="ask"&&l.jsx(es,{size:13,strokeWidth:2,className:"shrink-0 text-accent"})]}),l.jsxs("button",{onClick:()=>{YE("allow"),m(!1)},className:"w-full text-left px-3 py-1.5 text-xs hover:bg-wash flex items-center gap-2","data-agent-guard":"allow",children:[l.jsx(qU,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),l.jsxs("span",{className:"flex-1 min-w-0",children:[l.jsx("span",{className:"block text-ink",children:e("agent.guardAllow")}),l.jsx("span",{className:"block text-2xs text-ink-faint",children:e("agent.guardAllowHint")})]}),v?.agentGuard?.mode==="allow"&&l.jsx(es,{size:13,strokeWidth:2,className:"shrink-0 text-accent"})]}),(v?.agentGuard?.allow?.length??0)>0&&l.jsxs(l.Fragment,{children:[l.jsx("p",{className:"text-2xs text-ink-faint px-3 pt-2 pb-1",children:e("agent.guardAllowed")}),v.agentGuard.allow.map(_=>l.jsxs("div",{className:"px-3 py-1 text-xs flex items-center gap-2 min-w-0","data-agent-guard-allowed":_,children:[l.jsx("span",{className:"flex-1 min-w-0 truncate text-ink-muted font-mono",title:_,children:_}),l.jsx("button",{onClick:()=>{z7(_,!0)},className:"text-ink-faint hover:text-red-500 shrink-0",title:e("agent.guardRemove"),children:l.jsx(on,{size:12,strokeWidth:2})})]},_))]})]})]})}const XN="thoughtdag.pluginUpdateNotified";function Xy(e){return`dsh plugin --profile web add dsh-thoughtdag@${e||"latest"}`}async function Rue(e){try{const t=await fetch(e.replace(/\/+$/,"")+"/version",{credentials:"same-origin"});if(!t.ok)return;const n=await t.json();if(!n.version||!n.latest||Yy(n.latest,n.version)<=0)return;ce.getState().setPluginUpdate({current:n.version,latest:n.latest});let a=null;try{a=localStorage.getItem(XN)}catch{}if(a!==n.latest){try{localStorage.setItem(XN,n.latest)}catch{}const r=ce.getState().harnessHost?.desktop??(()=>{try{const s=window.parent?.document?.documentElement;return!!s&&(s.dataset.platform!==void 0||s.hasAttribute("data-windows-titlebar"))}catch{return!1}})();We("info",ve(Ne("plugin.updateAvailable"),{v:n.latest})+(r?" "+ve(Ne("plugin.updateHintDesktop"),{pkg:`dsh-thoughtdag@${n.latest}`}):""),12e3)}}catch{}}const jue=Object.freeze(Object.defineProperty({__proto__:null,bootPluginUpdateCheck:Rue,pluginUpdateCommand:Xy},Symbol.toStringTag,{value:"Module"})),Lue={ruleout:"#ef4444",decision:"#6B5CE7",pivot:"#e8890c",open:"#d97706",insight:"#0284c7"},QN=e=>{if(e){for(let t=e.length-1;t>=0;t--)if(e[t])return e[t]}};function Pue(e){if(e.stepKind==="file")return e.attachments?.[0]?.name;if(e.stepKind==="link")return e.linkTitle||e.linkUrl;if(e.stepKind==="note")return e.question?.split(`
937
+ ${m}`.slice(-1500)}const d=wue(e,o,t);if(Ml!==a)return;ce.getState().setCondenseRun({status:"done",streaming:"",distillIds:d.distillIds}),We("success",Ne("condense.copyReady"),8e3,{label:Ne("tmap.export"),run:()=>ce.getState().setThoughtMapOpen(!0)})}catch(o){if(Ml!==a)return;ce.getState().setCondenseRun({status:"error",error:o instanceof Error?o.message:String(o)})}}function Sue({onFocusSegment:e}){const t=ce(D=>D.condenseDialogOpen),n=ce(D=>D.condenseRun),a=Tt(),r=Aa(D=>D.lang),s=se(D=>D.nodes),o=se(D=>D.edges),[u,d]=R.useState(0),h=R.useMemo(()=>t&&n.status==="idle"?xue(s,o):[],[t,n.status,s,o,u]),m=ce(D=>D.selectedModel),p=ec()?.models??[],[x,b]=R.useState(""),[y,w]=R.useState(new Set),[E,v]=R.useState(null),N=R.useRef(null),S=D=>{const P=N.current?.getBoundingClientRect();if(!P)return;const Y=D.clientX-P.left,U=D.clientY-P.top,z=q=>v({x:Math.min(window.innerWidth-120,Math.max(0,q.clientX-Y)),y:Math.min(window.innerHeight-80,Math.max(0,q.clientY-U))}),L=()=>{window.removeEventListener("mousemove",z),window.removeEventListener("mouseup",L)};window.addEventListener("mousemove",z),window.addEventListener("mouseup",L)},C=D=>D.nodeIds.join(","),I=h.filter(D=>!y.has(C(D))),O=I.reduce((D,P)=>D+P.saving,0),_=()=>{ce.getState().setCondenseDialogOpen(!1),ce.getState().setCondenseHighlightIds([])};if(R.useEffect(()=>{if(!t)return;const D=P=>{P.key==="Escape"&&_()};return window.addEventListener("keydown",D),()=>window.removeEventListener("keydown",D)},[t]),!t)return null;const A=()=>{I.length!==0&&Eue(I,r,x||m||void 0)},H=()=>{se.getState().setArchived(n.originalIds,!0),We("success",a("condense.originalArchived")),ce.getState().setCondenseRun({status:"idle",current:0,total:0,streaming:"",originalIds:[],distillIds:[]}),_()},G=()=>{const P=se.getState().nodes.filter(Y=>n.distillIds.includes(Y.id));P.length&&e?.(P.map(Y=>Y.id))};return dr.createPortal(l.jsxs("div",{ref:N,className:"fixed z-[70] bg-surface border border-line rounded-2xl shadow-2xl w-[400px] max-h-[72vh] flex flex-col p-4 animate-fade-in",style:E?{left:E.x,top:E.y}:{left:80,bottom:16},"data-condense-dialog":!0,onClick:D=>D.stopPropagation(),children:[l.jsxs("div",{className:"flex items-start justify-between mb-1 cursor-grab active:cursor-grabbing select-none",onMouseDown:S,children:[l.jsxs("div",{className:"text-sm font-semibold text-ink flex items-center gap-2",children:[l.jsx(Sp,{size:15,strokeWidth:1.75,className:"text-accent"})," ",a("condense.title")]}),l.jsx("button",{onClick:_,title:n.status==="building"?a("condense.runningBg"):void 0,className:"text-ink-faint hover:text-ink rounded-lg w-7 h-7 flex items-center justify-center hover:bg-wash transition-colors",children:l.jsx(on,{size:15})})]}),n.status==="idle"&&l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"flex items-center justify-between gap-2 mb-2",children:[l.jsx("p",{className:"text-2xs text-ink-faint leading-snug",title:a("condense.copyIntroFull"),children:a("condense.copyIntroShort")}),l.jsxs("button",{onClick:()=>d(D=>D+1),title:a("condense.rescanTitle"),"data-condense-rescan":!0,className:"text-2xs text-ink-muted hover:text-accent px-2 py-1 rounded-lg hover:bg-wash transition-colors shrink-0",children:["⟳ ",a("condense.rescan")]})]}),l.jsx("p",{className:"text-2xs text-ink-faint mb-2","data-condense-scanline":!0,children:ve(a("condense.scanLine"),{turns:String(s.filter(D=>D.data.response&&!D.data.stepKind).length),n:String(h.length)})}),l.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[l.jsx("label",{className:"text-2xs text-ink-muted shrink-0",children:a("condense.modelLabel")}),l.jsxs("select",{value:x,onChange:D=>b(D.target.value),"data-condense-model":!0,className:"text-xs bg-wash text-ink rounded-lg px-2 py-1.5 focus:outline-none focus:ring-1 focus:ring-accent/40 max-w-[220px] truncate",children:[l.jsx("option",{value:"",children:ve(a("condense.modelGlobal"),{model:m||"auto"})}),p.map(D=>l.jsx("option",{value:D.id,children:D.id},D.id))]})]}),h.length===0?l.jsx("p",{className:"text-xs text-ink-muted py-4",children:a("condense.segNothing")}):l.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto space-y-2 pr-1",children:h.map(D=>{const P=C(D),Y=!y.has(P);return l.jsxs("div",{"data-condense-item":!0,className:`border rounded-xl p-3 transition-colors cursor-pointer ${Y?"border-accent/60 bg-accent/5":"border-line opacity-60"}`,onClick:()=>{ce.getState().setCondenseHighlightIds(D.nodeIds),e?.(D.nodeIds)},children:[l.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[l.jsx("input",{type:"checkbox",checked:Y,onClick:U=>U.stopPropagation(),onChange:()=>w(U=>{const z=new Set(U);return z.has(P)?z.delete(P):z.add(P),z}),className:"accent-[var(--color-accent)]","data-condense-check":!0}),l.jsx("span",{className:"text-2xs text-ink-faint font-mono",children:ve(a("condense.segMeta"),{n:String(D.nodeIds.length),tok:String(D.saving)})})]}),l.jsx("p",{className:"text-xs text-ink mt-1 leading-snug line-clamp-2",children:D.headQuestion})]},P)})}),h.length>0&&l.jsxs("div",{className:"flex items-center justify-between gap-2 pt-3 mt-2 border-t border-line",children:[l.jsx("span",{className:"text-2xs text-ink-faint",children:a("condense.copyFootnote")}),l.jsxs("button",{onClick:A,disabled:I.length===0,"data-condense-build":!0,className:"text-xs bg-accent text-white px-3.5 py-2 rounded-lg disabled:opacity-40 transition-colors flex items-center gap-1.5 shrink-0",children:[l.jsx(ro,{size:13,strokeWidth:1.75}),ve(a("condense.buildCopy"),{n:String(I.length),tok:String(O)})]})]})]}),n.status==="building"&&l.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",children:[l.jsxs("div",{className:"flex items-center gap-2 text-sm text-ink-muted mb-1.5",children:[l.jsx(tn,{size:15,className:"animate-spin text-accent"}),ve(a("condense.buildingRun"),{i:String(n.current),n:String(n.total)})]}),l.jsx("p",{className:"text-2xs text-ink-faint mb-2",children:a("condense.runningBg")}),n.streaming&&l.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto text-2xs text-ink-muted bg-wash rounded-lg p-2.5 whitespace-pre-wrap leading-relaxed","data-condense-streaming":!0,children:n.streaming}),l.jsx("button",{onClick:()=>kue(),"data-condense-cancel":!0,className:"self-start mt-3 text-xs text-ink-muted hover:text-red-600 px-3 py-1.5 rounded-lg hover:bg-wash transition-colors",children:a("common.cancel")})]}),n.status==="error"&&l.jsxs("div",{className:"flex flex-col gap-2 py-3",children:[l.jsx("p",{className:"text-2xs text-red-600",children:n.error}),l.jsx("button",{onClick:()=>ce.getState().setCondenseRun({status:"idle",error:void 0}),className:"self-start text-xs text-ink-muted hover:text-ink px-3 py-1.5 rounded-lg hover:bg-wash transition-colors",children:a("common.cancel")})]}),n.status==="done"&&l.jsxs("div",{className:"flex flex-col gap-3 py-3",children:[l.jsxs("div",{className:"flex items-center gap-2 text-sm text-green-700",children:[l.jsx(es,{size:16})," ",a("condense.copyReady")]}),l.jsx("p",{className:"text-2xs text-ink-faint leading-relaxed",children:a("condense.copyCompareHint")}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("button",{onClick:G,className:"text-xs bg-accent/10 text-accent hover:bg-accent/20 px-3 py-2 rounded-lg transition-colors",children:a("condense.viewCopy")}),l.jsxs("button",{onClick:H,"data-condense-archive-original":!0,className:"text-xs border border-line text-ink-muted hover:text-ink hover:bg-wash px-3 py-2 rounded-lg transition-colors flex items-center gap-1.5",children:[l.jsx(rl,{size:13,strokeWidth:1.75})," ",a("condense.archiveOriginal")]})]}),l.jsx("button",{onClick:()=>{ce.getState().setCondenseRun({status:"idle"}),_()},className:"self-start text-xs text-ink-faint hover:text-ink transition-colors",children:a("common.close")})]})]}),document.body)}function YN(){const e=Aa(n=>n.lang),t=Aa(n=>n.setLang);return l.jsx("div",{className:"flex items-center bg-card/90 backdrop-blur border border-line rounded-lg shadow-sm overflow-hidden",children:["en","zh"].map(n=>l.jsx("button",{onClick:()=>t(n),className:`px-2 h-8 text-2xs font-medium transition-colors ${e===n?"bg-accent text-white":"text-ink-muted hover:bg-wash"}`,children:n==="en"?"EN":"中"},n))})}function ma({x:e,y:t,w:n=34,h:a=20,tone:r="plain"}){return l.jsxs("g",{children:[l.jsx("rect",{x:e,y:t,width:n,height:a,rx:4,fill:"white",stroke:at.line,strokeWidth:1}),r!=="plain"&&l.jsx("rect",{x:e,y:t,width:2.5,height:a,rx:1.25,fill:r==="accent"?at.accent:at.warm})]})}const Nue={1:l.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[l.jsx(ma,{x:43,y:32,tone:"accent"}),l.jsx("circle",{cx:60,cy:28,r:2.5,fill:at.accent})]}),2:l.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[l.jsx(ma,{x:43,y:12,tone:"accent"}),l.jsx("line",{x1:60,y1:32,x2:60,y2:50,stroke:at.accent,strokeWidth:1.75}),l.jsx("path",{d:"M 57 47 L 60 52 L 63 47 Z",fill:at.accent}),l.jsx(ma,{x:43,y:52})]}),3:l.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[l.jsx(ma,{x:20,y:12,tone:"accent"}),l.jsx("line",{x1:37,y1:32,x2:37,y2:50,stroke:at.accent,strokeWidth:1.75}),l.jsx("path",{d:"M 34 47 L 37 52 L 40 47 Z",fill:at.accent}),l.jsx(ma,{x:20,y:52}),l.jsx("rect",{x:26,y:58,width:14,height:3,rx:1.5,fill:at.trace,opacity:.6}),l.jsx("path",{d:"M 54 62 C 64 62, 62 40, 72 38",stroke:at.warm,strokeWidth:1.75,fill:"none",strokeDasharray:"4 3"}),l.jsx("path",{d:"M 69 35.5 L 74 38 L 70 41 Z",fill:at.warm}),l.jsx(ma,{x:74,y:28,tone:"warm"})]}),4:l.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[l.jsx(ma,{x:43,y:10,tone:"accent"}),l.jsx("line",{x1:60,y1:30,x2:60,y2:52,stroke:at.line,strokeWidth:1.75,strokeDasharray:"3 3"}),l.jsx("circle",{cx:60,cy:41,r:7,fill:"white",stroke:"#FCA5A5",strokeWidth:1}),l.jsx("line",{x1:57,y1:38,x2:63,y2:44,stroke:"#EF4444",strokeWidth:1.5,strokeLinecap:"round"}),l.jsx("line",{x1:63,y1:38,x2:57,y2:44,stroke:"#EF4444",strokeWidth:1.5,strokeLinecap:"round"}),l.jsx(ma,{x:43,y:54})]}),5:l.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[l.jsx(ma,{x:12,y:14,w:40,h:15}),l.jsx("circle",{cx:14,cy:16,r:4.5,fill:"#D64533"}),l.jsx("text",{x:14,y:18.4,textAnchor:"middle",fontSize:6,fontWeight:700,fill:"white",children:"✕"}),l.jsx(ma,{x:12,y:35,w:40,h:15}),l.jsx("circle",{cx:14,cy:37,r:4.5,fill:at.accent}),l.jsx("text",{x:14,y:39.4,textAnchor:"middle",fontSize:6,fontWeight:700,fill:"white",children:"⚖"}),l.jsx(ma,{x:12,y:56,w:40,h:15}),l.jsx("circle",{cx:14,cy:58,r:4.5,fill:"#C9A227"}),l.jsx("text",{x:14,y:60.4,textAnchor:"middle",fontSize:6,fontWeight:700,fill:"white",children:"?"}),l.jsx("path",{d:"M 62 42 L 74 42",stroke:at.inkMuted,strokeWidth:1.2}),l.jsx("path",{d:"M 71.5 39.5 L 76 42 L 71.5 44.5 Z",fill:at.inkMuted}),l.jsx("rect",{x:86,y:14,width:13,height:13,rx:4.5,fill:"#D64533"}),l.jsx("line",{x1:92.5,y1:27,x2:92.5,y2:35,stroke:at.accent,strokeWidth:1.4}),l.jsx("rect",{x:86,y:35,width:13,height:13,rx:4.5,fill:at.accent}),l.jsx("line",{x1:92.5,y1:48,x2:92.5,y2:56,stroke:at.accent,strokeWidth:1.4}),l.jsx("rect",{x:86,y:56,width:13,height:13,rx:4.5,fill:"#C9A227"})]}),7:l.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[l.jsx("rect",{x:14,y:12,width:30,height:22,rx:3,fill:"#FEF3C7",stroke:"#F59E0B",strokeWidth:.8}),l.jsx("line",{x1:29,y1:34,x2:29,y2:50,stroke:at.accent,strokeWidth:1.75}),l.jsx("path",{d:"M 26 47 L 29 52 L 32 47 Z",fill:at.accent}),l.jsx(ma,{x:12,y:52,tone:"accent"}),l.jsx("path",{d:"M 100 22 C 80 22, 70 55, 50 60",stroke:at.accent,strokeWidth:1.75,fill:"none",strokeDasharray:"5 3"}),l.jsx("path",{d:"M 52 57 L 47 61 L 52 64 Z",fill:at.accent}),l.jsx(ma,{x:82,y:12})]}),9:l.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[l.jsx(ma,{x:43,y:10,tone:"accent"}),l.jsx("line",{x1:60,y1:30,x2:60,y2:48,stroke:at.accent,strokeWidth:1.75}),l.jsx("path",{d:"M 57 45 L 60 50 L 63 45 Z",fill:at.accent}),l.jsx(ma,{x:43,y:50}),l.jsx("circle",{cx:75,cy:53,r:4,fill:"#F59E0B"}),l.jsx("path",{d:"M 73.5 53 a 1.5 1.5 0 1 1 3 0",stroke:"white",strokeWidth:.9,fill:"none"}),l.jsx("text",{x:60,y:80,textAnchor:"middle",fontSize:7,fill:at.inkMuted,fontFamily:"JetBrains Mono Variable, monospace",children:"v2/2 · replay"})]}),6:l.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[l.jsx("rect",{x:8,y:18,width:14,height:48,rx:4,fill:"white",stroke:at.line,strokeWidth:1}),l.jsx("circle",{cx:15,cy:27,r:3,fill:at.accent,opacity:.7}),l.jsx("rect",{x:12,y:37,width:6,height:6,rx:1,fill:"#F59E0B",opacity:.8}),l.jsx("rect",{x:12,y:49,width:6,height:6,rx:1,fill:at.inkMuted,opacity:.5}),l.jsx("rect",{x:38,y:14,width:32,height:24,rx:3,fill:"#FEF3C7",stroke:"#F59E0B",strokeWidth:.8}),l.jsx("rect",{x:80,y:14,width:32,height:24,rx:3,fill:"white",stroke:at.line,strokeWidth:1}),l.jsx("circle",{cx:88,cy:22,r:3,fill:at.line}),l.jsx("path",{d:"M 82 34 L 92 26 L 100 32 L 108 24",stroke:at.inkMuted,strokeWidth:1.2,fill:"none"}),l.jsx("text",{x:72,y:62,textAnchor:"middle",fontSize:7,fill:at.inkMuted,fontFamily:"JetBrains Mono Variable, monospace",children:"⌘V paste anything"})]}),8:l.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[l.jsx("rect",{x:8,y:8,width:70,height:52,rx:3,fill:at.accent,opacity:.06,stroke:at.accent,strokeWidth:.8,strokeDasharray:"3 2"}),l.jsx(ma,{x:14,y:14,w:26,h:16}),l.jsx(ma,{x:46,y:14,w:26,h:16}),l.jsx(ma,{x:30,y:38,w:26,h:16}),l.jsx("path",{d:"M 40 46 C 60 50, 70 50, 84 48",stroke:at.accent,strokeWidth:1.4,fill:"none"}),l.jsx("path",{d:"M 59 30 C 70 36, 76 42, 84 46",stroke:at.accent,strokeWidth:1.4,fill:"none"}),l.jsx("path",{d:"M 43 22 C 66 24, 76 38, 84 44",stroke:at.accent,strokeWidth:1.4,fill:"none"}),l.jsx(ma,{x:84,y:40,w:28,h:18,tone:"accent"})]}),10:l.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[l.jsx(ma,{x:10,y:18,w:30,h:17,tone:"accent"}),l.jsx("line",{x1:25,y1:35,x2:25,y2:48,stroke:at.accent,strokeWidth:1.5}),l.jsx("path",{d:"M 22.5 45.5 L 25 50 L 27.5 45.5 Z",fill:at.accent}),l.jsx(ma,{x:10,y:50,w:30,h:17}),l.jsx("path",{d:"M 46 42 L 60 42",stroke:at.inkMuted,strokeWidth:1.2}),l.jsx("path",{d:"M 57.5 39.5 L 62 42 L 57.5 44.5 Z",fill:at.inkMuted}),l.jsx("rect",{x:68,y:20,width:44,height:44,rx:5,fill:"white",stroke:at.line,strokeWidth:1}),l.jsx(ma,{x:74,y:30,w:20,h:11,tone:"accent"}),l.jsx(ma,{x:88,y:46,w:20,h:11}),l.jsx("rect",{x:76,y:14,width:28,height:11,rx:5.5,fill:"#2B2A28"}),l.jsx("circle",{cx:84,cy:19.5,r:2.6,fill:"none",stroke:"white",strokeWidth:1}),l.jsx("circle",{cx:84,cy:19.5,r:.9,fill:"white"}),l.jsx("text",{x:90,y:22,fontSize:6,fill:"white",fontFamily:"JetBrains Mono Variable, monospace",children:"view"}),l.jsx("text",{x:60,y:78,textAnchor:"middle",fontSize:7,fill:at.inkMuted,fontFamily:"JetBrains Mono Variable, monospace",children:"#view= · read-only"})]})},KN={4:"prune",5:"map",6:"reading",7:"ref"};function Tue(){const e=ce(h=>h.tutorialOpen),t=ce(h=>h.setTutorialOpen);R.useEffect(()=>{if(!e)return;const h=m=>{m.key==="Escape"&&t(!1)};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[e,t]);const n=Tt(),a=Aa(h=>h.lang),[r,s]=R.useState(0),o=[{label:n("tutorial.pg1"),steps:[1,2,3]},{label:n("tutorial.pg2"),steps:[4,5]},{label:n("tutorial.pg3"),steps:[6,7]},{label:n("tutorial.pg4"),steps:[8,9,10]}],u=r===o.length-1;if(R.useEffect(()=>{if(!e)return;s(0);const h=m=>{m.key==="ArrowRight"&&s(p=>Math.min(p+1,o.length-1)),m.key==="ArrowLeft"&&s(p=>Math.max(p-1,0))};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[e]),!e)return null;const d=o[r];return l.jsx("div",{className:"fixed inset-0 z-[95] bg-black/25 flex items-center justify-center animate-fade-in p-6",onClick:()=>t(!1),children:l.jsxs("div",{className:"bg-card border border-line rounded-2xl shadow-2xl w-[min(980px,94vw)] flex flex-col",onClick:h=>h.stopPropagation(),children:[l.jsxs("div",{className:"flex items-start justify-between px-7 pt-5 pb-1 shrink-0",children:[l.jsxs("div",{className:"flex items-baseline gap-3 min-w-0",children:[l.jsx("h2",{className:"text-lg font-semibold text-ink tracking-tight shrink-0",children:n("tutorial.title")}),l.jsx("p",{className:"text-xs text-ink-faint truncate",children:n("tutorial.subtitle")})]}),l.jsx("button",{onClick:()=>t(!1),className:"text-ink-faint hover:text-ink transition-colors mt-1",children:l.jsx(on,{size:18,strokeWidth:1.75})})]}),l.jsxs("div",{className:"px-7 pt-3 pb-1 min-h-[380px]",children:[l.jsx("p",{className:"text-2xs font-semibold text-accent mb-3 uppercase tracking-wider",children:d.label}),l.jsx("div",{className:`grid gap-4 ${d.steps.length===3?"grid-cols-1 sm:grid-cols-3":"grid-cols-1 sm:grid-cols-2"}`,children:d.steps.map(h=>l.jsxs("div",{className:"bg-surface border border-line/70 rounded-xl p-4 flex flex-col animate-fade-in",children:[l.jsx("div",{className:"w-full aspect-[120/72] bg-card rounded-lg border border-line/60 mb-3 overflow-hidden",children:KN[h]?l.jsx("img",{src:`/thoughtdag/tutorial/${KN[h]}-${a}.gif`,loading:"lazy",alt:"",className:"w-full h-full object-cover"}):Nue[h]}),l.jsx("h3",{className:"text-[13px] font-semibold text-ink leading-snug",children:n(`tutorial.step${h}.title`)}),l.jsx("p",{className:"text-xs text-ink-muted leading-relaxed mt-1.5",children:n(`tutorial.step${h}.desc`)})]},h))})]}),l.jsxs("div",{className:"px-7 py-4 shrink-0 flex items-center justify-between",children:[l.jsx("button",{onClick:()=>s(h=>Math.max(h-1,0)),disabled:r===0,className:"w-8 h-8 rounded-lg border border-line text-ink-muted hover:bg-wash transition-colors flex items-center justify-center disabled:opacity-25 disabled:cursor-not-allowed",children:l.jsx(Mm,{size:16,strokeWidth:1.75})}),l.jsx("div",{className:"flex items-center gap-2",children:o.map((h,m)=>l.jsx("button",{onClick:()=>s(m),className:`h-2 rounded-full transition-all ${m===r?"w-6 bg-accent":"w-2 bg-line hover:bg-line-strong"}`,"aria-label":`${m+1}/${o.length}`},m))}),u?l.jsx("button",{onClick:()=>t(!1),className:"text-xs bg-accent hover:bg-accent-strong text-white px-5 py-2 rounded-lg transition-colors",children:n("tutorial.close")}):l.jsx("button",{onClick:()=>s(h=>h+1),className:"w-8 h-8 rounded-lg border border-line text-ink-muted hover:bg-wash transition-colors flex items-center justify-center",children:l.jsx(Fa,{size:16,strokeWidth:1.75})})]}),l.jsxs("div",{className:"px-7 py-2.5 border-t border-line/60 shrink-0 flex flex-wrap gap-x-4 gap-y-1 text-2xs text-ink-faint font-mono",children:[l.jsxs("span",{children:[n("shortcut.panKeys")," ",n("shortcut.pan")]}),l.jsxs("span",{children:[n("shortcut.marqueeKeys")," ",n("shortcut.marquee")]}),l.jsxs("span",{children:["⌘","F ",n("shortcut.search")]}),l.jsxs("span",{children:["Space ",n("shortcut.collapse")]}),l.jsxs("span",{children:["R ",n("shortcut.regenerate")]}),l.jsxs("span",{children:["↑↓←→"," ",n("shortcut.navigate")]}),l.jsxs("span",{children:["⌘","Z/","⇧","⌘","Z ",n("shortcut.undo")]}),l.jsxs("span",{children:["Del ",n("shortcut.delete")]}),l.jsxs("span",{children:["Esc ",n("shortcut.escape")]})]})]})})}const Aue=new URLSearchParams(window.location.search),Os=Aue.get("dv"),Uc="https://chenxiachan.github.io/thoughtdag/docs",QM=[{version:"0.5.13",date:"2026-10-02",announce:!1,lead:{zh:"打开大会话时页面不再卡住:材料、高光、时间轴三个总览在关闭时不再每次节点更新都遍历整张画布(@suhyungJang 的 PR #58,时间轴照同样方式补上)。",en:"Opening a large session no longer freezes the page: the materials, highlights and timeline overviews stop walking the whole canvas on every node update while closed (@suhyungJang's PR #58; the timeline follows the same way)."},items:[]},{version:"0.5.12",date:"2026-10-01",announce:!0,lead:{zh:"💬 新增「问画布」:让模型读整张画布,回答里的每个编号都能点回节点。",en:"💬 New: Ask the canvas. The model reads the whole canvas, and every number in its answer points back at a node."},items:[{title:{zh:"💬 问画布",en:"💬 Ask the canvas"},body:{zh:"工具栏 ⌘F 旁的问号气泡。它读画布的大纲(每个节点一行:编号、主题、结论、上游),选中节点时再读它的脉络和材料。回答用编号引用:悬停点亮节点,点击定位,画布上没有的编号标红。「落到画布」把这轮问答变成节点,引用线连到它提到的每个节点。空白时给了五个起手问题:总览、定位、溯源、比对、进展。只看画布,不联网,不进上下文。",en:`The question bubble next to ⌘F on the toolbar. It reads an outline of the canvas (one line a node: number, topic, takeaway, upstream) and, with a node selected, that node's chain and materials. Answers cite by number: hover lights the node, click locates it, a number the canvas lacks shows red. "Drop onto the canvas" turns the exchange into a node wired by reference to every node it cited. Five opening questions wait in the empty state: overview, locate, grounds, compare, progress. It reads only the canvas: no web, nothing enters your context.`}},{title:{zh:"。 标点不再孤立",en:"。 Punctuation stays with its word"},body:{zh:"缩小后牌子上的句号、逗号不再掉到下一行开头。",en:"On zoomed-out plaques a full stop or comma no longer opens a line by itself."}},{title:{zh:"🔧 两处修复",en:"🔧 Two fixes"},body:{zh:"侧栏里点到已不存在的探索标记,面板不再空白(#56)。索引升级后第一次选「全量」回忆,不再卡住整个应用:索引在后台刷新,菜单里提示一句(#57)。",en:'Clicking a stale explore mark in the panel no longer blanks it (#56). The first "full" recall after an index upgrade no longer stalls the app: the index refreshes in the background and the menu says so (#57).'}}]},{version:"0.5.11",date:"2026-10-01",announce:!1,lead:{zh:"一批围绕提问的收口。空节点里选的全量回忆现在真的会跑,之前发送时被丢掉了;问题编辑器(卡片和侧栏)里多了这个节点自己的联网、学术、回忆开关,改的只是这个节点;任何节点都能设自己的角色,编辑器改成侧栏头部下方的整宽条;问题也按 Markdown 渲染;全量回忆的确认框按实测重算,只说要多等一会儿和费用;模型选择器把别名解析到的型号标为上次运行;Harness 插件对话页的浮动开关挪到标题行下方,Windows 上不再被拖拽区吞掉点击。",en:"A batch around asking. A full recall chosen on an empty card now runs (the choice was dropped on send); the question editors (card and panel) carry the node's own web, scholar and recall switches, and edit only that node; any node can set its own role, in a full-width editor under the panel header; questions render as Markdown; the full-recall dialog is re-measured and names the wait and the cost; the model picker marks an alias's resolved model as the last run's; the harness plugin's floating switch sits below the title row, so the Windows drag region no longer swallows its clicks."},items:[]},{version:"0.5.10",date:"2026-10-01",announce:!1,lead:{zh:"修复 0.5.9 带出的一处:索引升级后、第一次搜索之前,「全量」回忆的确认框把索引读成 0 条、0 秒、0 美元。现在计数会先把索引更新到位;索引真的空着或还在重建时,只提示一句,不弹确认框。",en:"Fixes one thing 0.5.9 brought: after the index upgrade and before the first search, the confirm dialog for a full recall read the index as 0 turns, 0 seconds, $0.00. The count now brings the index up to date first; an index that is empty or still rebuilding gets a notice instead of a dialog."},items:[]},{version:"0.5.9",date:"2026-10-01",announce:!1,lead:{zh:"回忆与记忆的四处收口,都出自 #51 的复审:归档的节点退出回忆索引(这次启动会把索引重建一遍);画像文档的每一行记着来自哪个画布、哪天、是本人说的还是推断的,模型改写后不再丢;新拉出的空节点和阅读器底栏有了和追问框一样的联网、学术、回忆开关;基准的 repair 用例多了一格带陈旧标记的条件。",en:"Four follow-ups from the #51 review, all on recall and memory: archived nodes leave the recall index (the index rebuilds once on this start); every line of the profile documents keeps which canvas it came from, when, and whether you said it or it was inferred, through the model's rewrites; a fresh node and the reader's footer carry the same web, scholar and recall switches as a follow-up; the benchmark's repair cases gain a condition that carries the stale mark."},items:[]},{version:"0.5.8",date:"2026-09-30",announce:!1,lead:{zh:"修复 0.5.7 的一处遗漏:回答里的消毒把画布自己加的标记也剥掉了,从回答文字跳到分支的入口失效,用户高亮和探索标记都退化成默认黄底。现在两种标记保留各自的类和目标,跳转、点状下划线、高亮填色都回来了。",en:"Fixes an oversight in 0.5.7: the answer sanitizer also stripped the marks the canvas adds itself, so the jump from an answer to the branch it bore stopped working and highlights and explore marks fell back to the browser's plain yellow. Both marks keep their class and target again; the jump, the dotted underline and the highlight fill are back."},items:[]},{version:"0.5.7",date:"2026-09-30",announce:!1,lead:{zh:"安全修补:回答里的原始 HTML 先经过消毒再渲染,折叠块、上下标、键帽、高亮、表格、换行照旧,能执行脚本或嵌入外部页面的标签(iframe、object、script、style、form 等)被去掉;此前分享链接、导入的画布或模型引用的网页都能借 srcdoc 的 iframe 在本页面的源里执行代码。托管代理的模型探测只接受公网 https 地址,两处网页快照抓取共用一套地址检查并逐跳核对重定向。另外两处小修:「重跑上游已变」只跑确认框里数到的那些,牌子摘要不再参考已归档的步骤。",en:"Security: raw HTML in an answer is sanitized before rendering; folds, sub/sup, kbd, highlights, tables and line breaks stay, while tags that run scripts or embed pages (iframe, object, script, style, form and the like) are stripped. Until now a shared link, an imported canvas or a page the model quoted could run code in this origin through a srcdoc iframe. The hosted proxy's model probe takes public https endpoints only, and both page-snapshot fetchers share one address guard and check every redirect hop. Two small fixes: replay reruns exactly the stale nodes the dialog counts, and plaque summaries no longer read archived steps."},items:[]},{version:"0.5.6",date:"2026-09-30",announce:!1,lead:{zh:"回忆改成安静的小标签,默认关:输入框旁一个「回忆」,点开是开关、搜索范围(轻量 40 条 / 深挖 2,000 条 / 全量)和带入上下文,改的只对这一次提问生效,「设为默认」写回全局;深挖和全量由判断模型分批看候选,全量先告诉你条数、秒数和费用。判断模型页的开关并进供应商下拉(最后一项「关闭,按规则」);联网和学术搜索也默认关。每个节点都有可缩放的摘要:一句话的回答、笔记、文件都上梯子。双击卡片上的问题,侧栏编辑框带着原文打开。Harness 插件:思维图顶上是自己的标题带(不再压住红绿灯);自己的模型接口回来了,添加、拉模型列表、调用都走插件;不再提示桌面版新版本,插件更新提示直接说在插件页重新添加哪个包;桌面版 0.2 写的 v4 会话文件进得了对话地图。",en:`Recall is a quiet chip, off by default: a "Recall" beside the composer opens the switch, the search reach (light 40 / deep 2,000 / full) and the context brought in; a change there holds for the next ask only, "set as default" writes it back. Deep and full have the decision model read candidates in batches; full first says how many turns, seconds and dollars. The decision model page folds its switch into the provider dropdown (last entry: off, rules decide); web and scholar search start off too. Every node zooms: one-line answers, notes and files get a ladder. Double-clicking a card's question opens the side panel editor with the text in place. Harness plugin: the map wears its own title band (clear of the traffic lights); its own model interfaces are back, added, listed and called through the plugin; no more desktop-app update nudge, and the plugin's own notice names the package to re-add on the Plugins page; the 0.2 desktop's v4 session files reach the atlas.`},items:[]},{version:"0.5.5",date:"2026-09-29",announce:!1,lead:{zh:"换档不再互相盖住:缩小到地图层时,节点的牌子不会超出布局留给它的位置,写不下的摘要在底部渐隐,再放大一档就能看全;折叠卡显示和牌子同一段摘要,放大缩小之间只是字号在变。节点间距略微拉开,已有画布的位置不动,按「一键排版」才换成新间距。另外:从 Finder 启动时也能找到本机的 Pi、Codex、Claude Code 命令行,找不到会说明查过哪些地方,可重新检测;子 Agent 的运行展开在父画布上,作为那一轮旁边的分支;模型接口分成「慢思考 · 回答模型」和「快思考 · 判断模型」两页,只用 Agent 的人也能单独接判断模型;新装机没有模型时会先问一次本机的 Agent。",en:"Zoom tiers no longer cover each other: at map zoom a node's plaque stays inside the room the layout keeps for it, an abstract that runs past it fades out at the bottom and shows in full one step in; the folded card carries the same abstract as the plaque, so zooming only changes the type size. Node gaps open slightly; existing canvases keep their positions until you choose Tidy layout. Also: the Pi, Codex and Claude Code CLIs are found under a Finder launch, and a missing one says where it looked, with a recheck; a subagent's run unfolds on the parent canvas as a branch beside its turn; the model dialog has two pages, slow thinking for answering models and fast thinking for the decision model, which agent-only users can connect on its own; a fresh install with no model asks the local agents first."},items:[]},{version:"0.5.4",date:"2026-09-29",announce:!1,lead:{zh:"鼠标滚轮恢复缩放画布,和 0.5.2 一样。0.5.3 起滚轮改成了平移,这对触控板顺手,却让鼠标用户没法用滚轮缩放。触控板用户可以在画布 ⋯ 菜单打开「滚轮平移画布」:双指滑动即平移,捏合或按住 ⌘/Ctrl 滚动来缩放。",en:"The mouse wheel zooms the canvas again, as in 0.5.2. Since 0.5.3 it panned, which suits a trackpad but left mouse users without wheel zoom. On a trackpad, turn on ⋯ → Wheel pans the canvas: a two-finger scroll pans, pinch or hold ⌘/Ctrl while scrolling to zoom."},items:[]},{version:"0.5.3",date:"2026-09-27",announce:!1,lead:{zh:"圈选多个节点后,工具栏多了「更新节点摘要」:用当前选中的模型为它们一次更新四层摘要,文件、便签和短回答自动跳过。进度在右下角,随时可停。旧画布想整体升级到新摘要,圈一下就行。右键单个节点也是同一个入口。",en:'With several nodes selected, the toolbar gains "Update node summaries": the picked model updates their four summary levels in one go, files, notes and short answers skipped. Progress shows bottom right and can be stopped any time. An older canvas upgrades to the new summaries with one lasso; the right-click item on a single node is the same door.'},items:[{title:{zh:"🧭 摘要写的是这一步新增了什么",en:"🧭 Summaries say what the step adds"},body:{zh:"结论与短述改为由模型撰写。写之前它先读这条思路里前面各步的牌匾,只写本步新增的结论、决定或转向,不重复前面已经说过的;概要仍是原答里的原文摘句,作为证据。旧节点用「更新节点摘要」换新即可。",en:'The takeaway and brief are now written by the model. It first reads the plaques of the earlier steps in the thread, then writes only what this step adds, a conclusion, a decision or a turn, without repeating what came before; the abstract stays verbatim sentences of the answer, as evidence. Older nodes switch over with "Update node summaries".'}},{title:{zh:"🖐️ 触控板双指滑动即平移",en:"🖐️ Two-finger scroll pans"},body:{zh:"在触控板上双指滑动就能移动画布,不用再按住按键拖。捏合缩放不变。鼠标滚轮现在同样是平移,缩放请按住 ⌘(Windows 上是 Ctrl)再滚。感谢 @Pireirik 的贡献。",en:"On a trackpad, a two-finger scroll moves the canvas; no button to hold. Pinch still zooms. A mouse wheel now pans too; hold ⌘ (Ctrl on Windows) to zoom with it. Contributed by @Pireirik."}}]},{version:"0.5.2",date:"2026-09-27",announce:!0,lead:{zh:"🔍 上下文管理重大更新!现在,无论画布缩放至何种比例,节点内容始终保持极佳的阅读体验。",en:"🔍 A major update to context management! Whatever the zoom, every node on the canvas now stays a pleasure to read."},media:{src:{zh:"whats-new/zoom-ladder-zh.mp4",en:"whats-new/zoom-ladder-en.mp4"},alt:{zh:"缩小画布时,牌匾上的结论逐词长成短述再长成摘要",en:"Zooming out, a plaque's takeaway grows word by word into a brief, then an abstract"},width:960,height:600},items:[{title:{zh:"🪜 智能四层摘要",en:"🪜 Four smart summary levels"},body:{zh:"每个回答自动构建「主题、结论、短述、完整概要」四个递进层级,随缩放比例自动无缝切换。",en:"Every answer builds four progressive levels, topic, takeaway, brief and full abstract, and switches between them seamlessly as you zoom."}},{title:{zh:"✨ 丝滑的视觉过渡",en:"✨ Silky visual transitions"},body:{zh:"缩放时,文字会逐词自然展开或收起。保留的关键词会平滑移动,新文本自然淡入,核心重点始终高亮加深。视线聚焦零中断,数十个节点的全局脉络一眼即达。",en:"As you zoom, text unfolds or folds word by word. The words that stay glide into place, new text fades in, and the key points stay highlighted in full ink. Your focus is never broken, and the shape of dozens of nodes reads at a glance."}},{title:{zh:"🔁 新旧节点全面兼容",en:"🔁 New and old nodes alike"},body:{zh:"新回答自动生效该特性;旧节点会在浏览时实时生成摘要层级,若需更精准的 AI 总结,只需右键一键生成。",en:"New answers get it automatically; older nodes build their levels live as you browse, and for a sharper AI-selected summary, one right-click does it."}},{title:{zh:"🎚️ 时间线详略随手调",en:"🎚️ Timeline detail at your fingertips"},body:{zh:"时间线弹窗新增详略滑块,从主题一路拉到完整概要,字号与行距随手指流动,每一步文字完整呈现,告别省略号。",en:"The timeline overview gains a detail slider: glide from topic to full abstract, type and spacing flowing with your drag, every step shown whole, no ellipsis anywhere."},media:{src:{zh:"whats-new/timeline-detail-zh.mp4",en:"whats-new/timeline-detail-en.mp4"},alt:{zh:"拖动时间线弹窗的详略滑块,每一步的文字逐词展开",en:"Dragging the timeline overview's detail slider, each step's text unfolds word by word"},width:720,height:760}},{title:{zh:"🛡️ 所见即所发",en:"🛡️ What you see is what is sent"},body:{zh:"判断模型认定上游改动与答案无关时,「上游已变」标记现在同时从预览和请求中退场,两者始终一致。感谢 Agent Memory Atlas 的审阅指出这一点。",en:'When the decision model rules an upstream change irrelevant, the "upstream changed" mark now leaves the preview and the request together, always in step. Thanks to the Agent Memory Atlas review for catching it.'}},{title:{zh:"🧹 右键菜单焕新",en:"🧹 A refreshed right-click menu"},body:{zh:"「重新生成」更简洁,CLI 相关操作合并为一项,新增「用模型重选摘要」。手动修改过的回答会自动重做摘要。",en:'"Regenerate" is simpler, the CLI actions merge into one, and "Update node summary" joins the menu. Hand-edited answers get their summaries redone automatically.'}}]},{version:"0.5.1",date:"2026-09-26",announce:!1,lead:{zh:"0.5 之后的一批修正。删除正在生成的节点时,那一轮生成随之中止,不再在后台跑完。记忆的自动写入上限按画布分开计,切换画布后重新计;之前是全局三条写满就静默。档案更新只带走模型读过的那几条待归档事实,更新期间新归档的保留下来;档案文件的写入排队进行,不再互相覆盖。why 层不再把执行失败的文件操作算作改动足迹,更新后索引会重建一次。判断模型直接沿用模型接入里保存的 OpenRouter key,不再显示为空、测试不可点。",en:"A round of fixes after 0.5. Deleting a node that is still generating stops that generation instead of letting it run on in the background. The memory judge's automatic-write cap counts per canvas and starts over on a canvas switch; it used to be one global count of three, after which memory went quiet. A dossier update takes only the filed facts the model read and keeps anything filed while it was writing; dossier writes queue instead of overwriting one another. The why layer no longer counts a file operation the harness answered with an error as a change, and the index rebuilds once. The decision model uses the OpenRouter key saved with your model providers, instead of showing an empty field with a disabled test."},items:[]},{version:"0.5.0",date:"2026-09-26",announce:!0,lead:{zh:"🎉 ThoughtDAG 0.5:记忆上线。你在 Pi、Codex、Claude Code、DeepSeek Harness 里聊过的一切,现在接成一个可以回忆的整体。散在几百个会话里的碎片,按主题整理成档案;提问时相关的档案和对话自动带进上下文,跨 Agent、跨时间。背后是快思考与慢思考的分工:慢思考模型回答,快思考模型判断。所有信息都在你自己的机器上。",en:"🎉 ThoughtDAG 0.5: memory. Everything you discussed in Pi, Codex, Claude Code and DeepSeek Harness now forms one whole you can recall. Fragments scattered across hundreds of sessions are organised into dossiers by topic; when you ask, the relevant dossiers and conversations ride into the context, across agents and across time. Behind it, a division of labour: a slow-thinking model answers, a fast-thinking model decides. Everything stays on your machine."},items:[{title:{zh:"碎片串成一条线",en:"Fragments become a thread"},body:{zh:"昨天在 Codex 里定的阈值,上周在 Claude Code 里排除的方案,今天在画布上问起时都在。每个主题一份档案:是什么、定过什么、到哪一步、还没解决什么,每句都能点回原来的那轮对话。「你」是两份文档:偏好与身份,记到新东西时改写而不是堆砌。原来的记忆条目已并入。",en:"The threshold you settled in Codex yesterday and the approach you ruled out in Claude Code last week are there when you ask on the canvas today. Every topic keeps a dossier: what it is, what was decided, where it stands, what is still open, each line pointing back to its turn. Your profile is two documents, preferences and identity, rewritten rather than piled up. Earlier memory entries were folded in."},link:{label:{zh:"记忆指南",en:"The memory guide"},href:`${Uc}/zh/guides/memory`}},{title:{zh:"提问时自动回忆",en:"Recall as you ask"},media:{src:{zh:"whats-new/jev-recall.mp4",en:"whats-new/jev-recall.mp4"},alt:{zh:"回忆流程里,判断模型半秒内从候选片段中选出相关的几条",en:"In the recall flow the decision model picks the relevant excerpts from the candidates in under a second"},width:1200,height:720},body:{zh:"开着「回忆」提问,先判断问题涉及哪些主题,把档案整份带进去;问的是细节时再补几条原话。带了什么、花了多少,面板上一条一条看得见,不想要的划掉就不带。带入量三档:省、标准、多带。",en:"With recall on, a question is first matched to its topics and their dossiers ride in whole; a question about a detail brings a few verbatim excerpts too. What came in and what it cost is listed item by item; strike one and it stays out. Three amounts: lean, standard, generous."}},{title:{zh:"快思考,慢思考",en:"Fast thinking, slow thinking"},body:{zh:"回答你的是慢思考模型。判断「这条相关吗」「这句是决定吗」「这处改动影响吗」的是快思考模型:半秒一次,返回校准过的概率,让回忆、地图徽章和「上游已变」都有依据。模型选择器里一行开关,默认开;关掉全部退回规则,功能不变。",en:"The slow-thinking model answers you. The fast-thinking model decides — is this relevant, is this line a decision, does this change matter — in half a second, with calibrated probabilities, so recall, map badges and “upstream changed” rest on evidence. One switch in the model picker, on by default; off, every decision falls back to a rule and nothing stops working."}},{title:{zh:"接入一个快思考模型",en:"Connect a fast-thinking model"},body:{zh:"Jev 类判断模型可以经你已保存的聚合商接入直接使用,也支持官方接口和自建服务;没有接入时会提示,一切照常。",en:"A Jev-class decision model runs through the aggregator access you already saved, through the official endpoint, or from a self-hosted server; without one you are told, and everything still works."},link:{label:{zh:"怎么接入",en:"How to connect one"},href:`${Uc}/zh/setup#decision-model`}},{title:{zh:"一切都在本地",en:"All of it stays local"},body:{zh:"索引、主题标签、档案存在本机 .thoughtdag 目录,画像文档存在应用本地。判断时发出去的只有问题和候选片段,发给你自己选的接入。",en:"The index, topic labels and dossiers live in your machine's .thoughtdag folder; your profile lives in the app's own storage. A decision sends only the question and the candidate excerpts, to the access you chose."}}]},{version:"0.4.20",date:"2026-09-23",announce:!1,lead:{zh:"DeepSeek Harness 插件一轮实测后的整理。「对话 | 思维图」开关:对话页顶部仍是浮动的,切到思维图后它移到画布顶栏「画布名」右侧,不再压住画布工具栏。工作目录改用 Harness 自己的目录选择器:本机运行时弹的就是系统的文件夹对话框,远程访问时回落为输入路径;0.4.19 里自带的目录浏览器撤掉。Harness Agent 也能选工作目录,新会话按所选目录运行。插件里去掉配置模型 API 的入口。实时镜像刷新会话时不再把镜头拉回节点。节点记录的是发起请求时的模型,执行中切换选择器不再改写徽章。Harness 执行中的每个工具调用都列为一条步骤,思考尾巴显示在下方。备份提醒去掉。",en:"DeepSeek Harness plugin, after a round of hands-on testing. The 对话 | 思维图 switch still floats over the chat; on the canvas it sits in the canvas's own top bar next to the canvas chip, so it never covers the toolbar. The working directory is chosen in the harness's own picker: the system folder dialog when the harness runs on this machine, a typed path when reached remotely; the folder browser 0.4.19 carried is withdrawn. The Harness Agent gets the folder chip too, and a fresh session runs where it says. The API-key door is gone inside the plugin. The live mirror no longer drags the camera back to a node while its session refreshes. A node records the model it was asked with; switching the picker mid-run no longer relabels it. Every tool call of a harness run is listed as a step, the thinking beneath. The backup reminder is removed."},items:[]},{version:"0.4.19",date:"2026-09-23",announce:!1,lead:{zh:"DeepSeek Harness 插件:Harness Agent 节点的回答不再「闪一下就没了」。新版 Harness(0.1.5-rc.3)不再把逐字流写进会话日志,一步只落一条 assistant/message;画布续读实时日志时按会话列表报的序号少读了一条,恰好是带答案的那条,节点随后被镜像成空回答。现在按实际持有的最后一条事件续读,且镜像永不把已有回答改写为空。思考过程重新同步显示:宿主订阅 Harness 新的流事件(agent/assistant-stream),正文和思考逐字到达节点,没有流的运行时从每步的 reasoning 块补发。「对话 | 思维图」开关回到浮动位置,空态也能切换(0.4.18 的标题栏开关撤回)。Agent 的工作目录改为浏览宿主机的文件夹来选,也仍可直接输入路径。",en:"DeepSeek Harness plugin: a Harness Agent node no longer shows its answer for a moment and then loses it. Newer Harness builds (0.1.5-rc.3) stop writing the token stream into the session log; a step lands as one assistant/message. When the canvas read the live log incrementally it asked from the seq the session list reported and skipped exactly one event, the one carrying the answer, and the node was then mirrored as an empty reply. It now continues from the last event it actually holds, and a mirror never rewrites an existing answer to nothing. Reasoning shows live again: the host subscribes to the Harness's new stream event (agent/assistant-stream), so text and reasoning reach the node as they are produced; a runtime without that stream gets each step's reasoning block instead. The 对话 | 思维图 switch floats again and works on the empty page (the 0.4.18 header switch is withdrawn). An agent's working directory is chosen by browsing the host's folders, with a path field still there for typing."},items:[]},{version:"0.4.18",date:"2026-09-23",announce:!1,lead:{zh:"DeepSeek Harness 插件:历史会话列表在新版 Harness 上不再为空。dsh 从 0.1.5-rc.2 起把会话格式版本写进日志文件名(session.v3.jsonl.zstd),插件现在按已知文件名探测,新旧两种都认(#44,感谢 @LHN-xiao-hai-tun)。模型选择器加宽,条目悬停显示完整名称,Agent 执行组的长名字改为换行而不是截断,flash 与 flash-vision 一眼可辨(#43)。",en:"DeepSeek Harness plugin: the list of past sessions is no longer empty on newer Harness builds. From 0.1.5-rc.2 dsh writes the session format version into the log file name (session.v3.jsonl.zstd); the plugin now probes the known names and reads both (#44, thanks @LHN-xiao-hai-tun). The model picker is wider, every entry shows its full name on hover, and long names in the agent group wrap instead of being cut, so flash and flash-vision tell apart at a glance (#43)."},items:[]},{version:"0.4.17",date:"2026-09-21",announce:!1,lead:{zh:"DeepSeek Harness 插件:从画布向 Harness 提问时,节点只接自己那一轮。此前如果你同时在聊天框里发消息,画布节点会拿到你那轮的回答、在你那轮结束时提前收尾,并把镜像标记挂到错误的轮次上,产生重复节点;工具审批也可能被画布抢走。现在 Host 用 dsh 记在消息上的请求 id 精确认出自己的那一轮,文本、工具调用、审批、结束全部按这一轮过滤(#42,感谢 @nanami-0713)。桌面版本次只同步版本号。",en:"DeepSeek Harness plugin: a question asked from the canvas now receives only its own turn. Before, if you were also typing in the chat, the canvas node could receive your turn's answer, finish early when your turn ended, and stamp its mirror mark on the wrong turn, leaving duplicate nodes; tool approvals could be captured by the canvas as well. The host now recognises its own turn by the request id dsh records on the message, and filters text, tool calls, approvals and the end of turn to that turn alone (#42, thanks @nanami-0713). The desktop app only moves its version number."},items:[]},{version:"0.4.16",date:"2026-09-17",announce:!1,lead:{zh:"分区框:两个只是部分重叠的框不再互相收编。拖动大框时,重叠的小框和它自己的节点留在原地;拖动和一键排版现在用同一条成员规则,普通节点按中心点归属,框只有完整落在另一个框里才算它的成员(#40,感谢 @nanami-0713)。DeepSeek Harness 插件:「插件有新版本」提示复制的命令带上具体版本号,发版当天也能立刻装到新版。",en:"Frames: two frames that merely overlap no longer own each other. Dragging the larger one leaves the overlapping smaller frame and its own nodes in place; dragging and auto layout now share one membership rule, nodes by centre and a frame only when it lies fully inside another (#40, thanks @nanami-0713). DeepSeek Harness plugin: the update hint now copies a command naming the exact version, so a release installs on its first day too."},items:[]},{version:"0.4.15",date:"2026-09-15",announce:!1,lead:{zh:"分区框三件事:一键排版后,框跟着框内的节点重新包好(#32);拖动外框会带动嵌套在里面的框;重叠时小框叠在大框上面,标题栏不再被盖住。三项均来自 @hexu321。DeepSeek Harness 插件:「对话 | 思维图」切换器移进会话标题栏,不再遮挡标题;返回按钮居中,画布右上的工具栏保持可见;从画布切回会话的跳转修好了(#30,来自 @nanami-0713)。插件重新在 npm 上发布,安装命令恢复为包名。",en:"Frames, three fixes: after auto layout a frame re-wraps the nodes it held (#32); dragging an outer frame carries the frames nested inside it; where frames overlap, the smaller one stacks on top so its title bar stays reachable. All three by @hexu321. DeepSeek Harness plugin: the 对话 | 思维图 switch moves into the session header and no longer covers the title; the back button sits top centre, clear of the canvas toolbar; jumping from the canvas back to a session works again (#30, by @nanami-0713). The plugin is back on npm and the install command is the package name again."},items:[]},{version:"0.4.14",date:"2026-09-11",announce:!1,lead:{zh:"插件的「有新版本」提示现在复制 dsh plugin --profile web add dsh-thoughtdag@latest,这条命令对从 npm 装和从 Release 文件装的用户都有效(update 对文件安装无效)。其余同 0.4.13。",en:"The plugin's update hint now copies dsh plugin --profile web add dsh-thoughtdag@latest, which works for installs from npm and from a release file alike (update does nothing for a file install). Otherwise the same as 0.4.13."},items:[]},{version:"0.4.13",date:"2026-09-11",announce:!1,lead:{zh:"修复:DeepSeek Harness 插件里,模型选择器丢失了「Harness · 模型」这一组 Agent 条目(0.4.11 起,机器上没装 Pi、Codex 等命令行时整组消失)。原因是思维图把 Harness 给的条目当成本机命令行的探测结果替换掉了,现在只替换命令行报来的那几种。插件里「如何使用」的教程动图也能显示了(#35,感谢 @Moya-Doc)。",en:`Fix: inside the DeepSeek Harness plugin, the model picker lost the "Harness · model" agent entries (since 0.4.11; with no Pi or Codex CLI on the machine the whole group vanished). The canvas had been replacing the harness's entries with the local CLI probe; now only the entries the CLIs report get replaced. The tutorial gifs inside the plugin load again (#35, thanks @Moya-Doc).`},items:[]},{version:"0.4.12",date:"2026-09-10",announce:!1,lead:{zh:"DeepSeek Harness 插件里,Agent 子节点现在续接父节点的会话;同一父节点下的第二个分支从父节点那一轮分叉出自己的会话,preset 的会话状态不再在每个子节点重头开始(#28、#29)。插件的构建脚本在 Windows 上也能跑了(#24、#26)。桌面版本次只同步版本号。",en:"Inside the DeepSeek Harness plugin, an agent child node now continues its parent's session, and a second branch off the same parent forks its own session at that parent's turn, so a preset's session state no longer restarts at every child (#28, #29). The plugin's build script runs on Windows too (#24, #26). The desktop app only moves its version number."},items:[]},{version:"0.4.11",date:"2026-09-08",announce:!1,lead:{zh:"性能优化:启动更快,后台更省,多个工具调用并行时更稳;300 节点以上的画布实测流畅。ThoughtDAG 现在可以用 Claude Code、Codex、Pi 作为节点的 Agent 运行时,处于测试阶段。",en:"Performance: faster launch, lighter in the background, steadier when several tool calls run in parallel; canvases past 300 nodes measured smooth. ThoughtDAG can now run a node through Claude Code, Codex or Pi as its agent runtime, in testing."},items:[]},{version:"0.4.10",date:"2026-09-07",announce:!1,lead:{zh:"Agent 执行预览继续:Codex 加入,和 Pi 一样在画布里带工具作答;这条通道现在在桌面版、本地网页版和 DeepSeek Harness 插件里都可用;插件里的 Harness Agent 按模型平铺;插件有新版本时画布会提示。",en:"Agent runs, preview continued: Codex joins Pi, answering with tools right from the canvas; the lane now works in the desktop app, the local web app and the DeepSeek Harness plugin alike; inside the plugin the Harness agent lists one entry per model; the canvas tells you when a newer plugin is out."},items:[]},{version:"0.4.9",date:"2026-09-07",announce:!1,lead:{zh:"Agent 执行预览:桌面版的模型选择器多了「Agent 执行」组,装了 Pi 的话可以直接在画布里让它带工具作答,轨迹、足迹、审批和提问都落在节点上,工作目录在顶栏可见可改。正式版会连同 Claude Code 与 Codex 一起发布。DeepSeek Harness 插件里的审批卡片同步更新。",en:'Agent runs, preview: the desktop picker gains an "Agent runs" group; with Pi installed, a question runs through it with tools right from the canvas, and the trace, footprints, approvals and questions land on the node, with the working directory visible on the toolbar. The full release will arrive together with Claude Code and Codex. The approval card inside the DeepSeek Harness plugin is updated alike.'},items:[]},{version:"0.4.8",date:"2026-09-07",announce:!1,lead:{zh:"DeepSeek Harness 插件在 Windows 上能打开了:静态资源和会话目录的路径守卫此前只认正斜杠,Windows 用户看到的是一片 403。感谢 GitHub 上的报告(#23)。桌面版本次只同步版本号。",en:"The DeepSeek Harness plugin now opens on Windows: the path guards for static assets and session directories only accepted forward slashes, so Windows users saw nothing but 403s. Thanks to the report on GitHub (#23). The desktop app only moves its version number this time."},items:[]},{version:"0.4.7",date:"2026-09-07",announce:!1,lead:{zh:"DeepSeek Harness 插件里,Agent 需要你批准的操作现在直接出现在节点上:工具、命令、理由,允许一次或拒绝,决定留在节点记录里。桌面版本次只同步版本号。",en:"Inside the DeepSeek Harness plugin, an action the agent needs approved now appears on the node itself: tool, command, reason, allow once or reject, and the decision stays in the node's record. The desktop app only moves its version number this time."},items:[]},{version:"0.4.6",date:"2026-09-06",announce:!0,lead:{zh:"🎉 Pi 的会话进了对话地图,「⋯」菜单里多了更新历史,随时能回看每一版改了什么。",en:"🎉 Pi sessions join the Session Atlas, and the ⋯ menu gains a release history, so what every version changed is one click away."},items:[{title:{zh:"Pi 的会话也在地图上了",en:"Pi sessions are on the map"},body:{zh:"本地 Pi 会话按项目聚在一起,打开就是一张图。Pi 里的每次分叉在图上就是一条支线,不再压成一条直线。命令行 why 和 MCP 也同步认识 Pi 留下的文件足迹。",en:"Local Pi sessions group by project and open as a graph. Every fork you made in Pi shows up as a branch instead of being flattened into one line. The why command and MCP index Pi's file footprints too."},link:{label:{zh:"怎么用",en:"How it works"},href:`${Uc}/zh/guides/session-atlas`}},{title:{zh:"更新历史,随时补看",en:"Release history, whenever you like"},body:{zh:"右上「⋯」菜单,「如何使用」下面。每个版本改了什么都在这里,从新到旧,当前版本有标记。",en:"In the ⋯ menu, under How it works: what each release changed, newest first, with the version you are running marked."}}]},{version:"0.4.5",date:"2026-09-06",announce:!0,lead:{zh:"🎉 这是 ThoughtDAG 到目前为止最大的一次升级:散在各个 Agent 里的对话接成了一张地图,能从画布里查,还能直接在 DeepSeek Harness 里用。四件新东西,都值得试一试。",en:"🎉 The biggest ThoughtDAG release so far: the conversations scattered across your agents become one map, you can query them, and it all runs inside DeepSeek Harness. Four new things, each worth a try."},items:[{title:{zh:"跨 Agent 的对话地图,终于连成一张",en:"Session Atlas: all your agents, one map"},body:{zh:"Claude Code、Codex 和 DeepSeek Harness 的本地会话按项目文件夹聚在一起,点开就是一张图,随对话实时生长。",en:"Local Claude Code, Codex and DeepSeek Harness sessions, grouped by project; open one as a graph and it follows the conversation live."},link:{label:{zh:"怎么用",en:"How it works"},href:`${Uc}/zh/guides/session-atlas`}},{title:{zh:"命令行 why:一条命令找回塑造文件的那些对话",en:"thoughtdag why: one command finds the conversations that shaped a file"},body:{zh:"npx thoughtdag why <文件> 列出哪些轮次读过、改过它,当时问了什么、改了什么;find 按原话搜,MCP 让 Agent 自己来查。",en:"npx thoughtdag why <file> lists the turns that read or changed it, what was asked and what changed; find searches verbatim; MCP lets your agent ask."},link:{label:{zh:"命令与 MCP",en:"CLI and MCP"},href:`${Uc}/zh/guides/why-layer`}},{title:{zh:"DeepSeek Harness 插件上线",en:"DeepSeek Harness plugin is live"},body:{zh:'dsh plugin --profile web add dsh-thoughtdag,Harness 的网页里多一个"思维图"视图:在画布上提问、让 Harness 的 Agent 带工具作答,why 也成了它的原生工具。',en:"dsh plugin --profile web add dsh-thoughtdag adds a canvas view to the Harness web UI: ask from the canvas, let its agent answer with tools, and why becomes a native tool there."},link:{label:{zh:"插件说明",en:"Plugin README"},href:"https://github.com/chenxiachan/thoughtdag/tree/main/dsh#readme"}},{title:{zh:"文档站上线",en:"The docs site is live"},body:{zh:"概念、任务指南、命令字典和隐私说明各有一页,中英文对照。感谢一路同行,欢迎来 Discussions 说说你怎么用它。",en:"Concepts, task guides, the command dictionary and the privacy notes, each on its own page, in both languages. Thank you for coming this far with us; tell us how you use it in Discussions."},link:{label:{zh:"打开文档",en:"Open the docs"},href:`${Uc}/zh/`}}]},{version:"0.4.4",date:"2026-09-04",announce:!1,lead:{zh:"DeepSeek Harness 成为对话地图的内置来源:它的 zstd 日志由桌面壳逐帧解码,每条消息一个节点,工具调用与结果配对成附件。",en:"DeepSeek Harness becomes a built-in Atlas source: the shell decodes its zstd logs frame by frame, one node per message, tool calls paired with their results as attachments."},items:[]},{version:"0.4.3",date:"2026-09-03",announce:!1,lead:{zh:"深链接可以直达某一轮,画布可以按稳定 id 打开;子 Agent 的会话文件不再打扰实时监听。",en:"A deep link can land on a turn and a canvas opens by its stable id; subagent session files no longer disturb the live watcher."},items:[]},{version:"0.4.2",date:"2026-09-02",announce:!1,lead:{zh:"镜像节点列出那一轮碰过的文件(✏️ 改过、📖 读过),预览用结论而不是开头;子 Agent 的会话作为子线程识别,报告折回发起它的那一轮。",en:"A mirrored node lists the files its turn touched (✏️ edited, 📖 read) and previews the conclusion rather than the opening line; subagent files are recognized as sub-threads and their reports fold into the launching turn."},items:[]},{version:"0.4.1",date:"2026-09-01",announce:!1,lead:{zh:"Agent 对话地图首发:本地 Claude Code 与 Codex 的会话按项目文件夹聚成一张图,一键接入,随对话实时生长。",en:"Session Atlas debuts: local Claude Code and Codex sessions group by project folder into one map, connect in one click, and grow with the conversation."},items:[]}];function Yy(e,t){const n=e.split(".").map(r=>parseInt(r,10)||0),a=t.split(".").map(r=>parseInt(r,10)||0);for(let r=0;r<Math.max(n.length,a.length);r++){const s=(n[r]??0)-(a[r]??0);if(s!==0)return s}return 0}function sm(e,t){return QM.filter(n=>n.announce&&Yy(n.version,t)<=0&&(e===null||Yy(n.version,e)>0))}const Ky="thoughtdag.whatsNewSeen",Cue=new URLSearchParams(window.location.search);function _ue(){if(!Os)return[];const e=Cue.get("wn");if(e==="1")return sm(null,Os);if(e)return sm(e,Os);let t=null;try{t=localStorage.getItem(Ky)}catch{}if(t===null){let n=!1;try{n=!!(localStorage.getItem("thoughtdag.tutorialDone")||localStorage.getItem("thoughtdag.lastBackupAt"))}catch{}if(!n){try{localStorage.setItem(Ky,Os)}catch{}return[]}return sm(null,Os)}return t===Os?[]:sm(t,Os)}function ZM({media:e,lang:t}){const n=e.src[t],a=/\.(mp4|webm)$/i.test(n);return l.jsx("div",{className:"mt-3 rounded-xl border border-line overflow-hidden bg-wash",style:{aspectRatio:`${e.width} / ${e.height}`},"data-whats-new-media":!0,children:a?l.jsx("video",{src:`/thoughtdag/${n}`,autoPlay:!0,loop:!0,muted:!0,playsInline:!0,className:"w-full h-full object-cover","aria-label":e.alt[t]}):l.jsx("img",{src:`/thoughtdag/${n}`,alt:e.alt[t],className:"w-full h-full object-cover"})})}function JM({items:e,lang:t}){return e.length===0?null:l.jsx("ol",{className:"divide-y divide-line",children:e.map((n,a)=>l.jsxs("li",{className:"py-3 flex gap-3.5",children:[l.jsx("span",{className:"shrink-0 w-6 h-6 rounded-full bg-accent/10 text-accent text-xs font-semibold flex items-center justify-center mt-0.5",children:a+1}),l.jsxs("div",{className:"min-w-0",children:[l.jsx("div",{className:"text-sm font-medium text-ink",children:n.title[t]}),l.jsx("p",{className:"text-sm text-ink-muted leading-relaxed mt-1 [overflow-wrap:anywhere]",children:n.body[t]}),n.media&&l.jsx(ZM,{media:n.media,lang:t}),n.link&&l.jsxs("a",{href:n.link.href,target:"_blank",rel:"noreferrer",className:"inline-block mt-1.5 text-xs font-medium text-accent hover:underline",children:[n.link.label[t]," →"]})]})]},a))})}function Mue(){const[e,t]=R.useState(()=>_ue()),n=e.length>0,a=Aa(u=>u.lang),r=Tt(),s=R.useRef(null),o=()=>{if(Os)try{localStorage.setItem(Ky,Os)}catch{}t([])};return R.useEffect(()=>{if(!n)return;s.current?.focus({preventScroll:!0});const u=d=>{d.stopPropagation(),(d.key==="Escape"||d.key==="Enter")&&o()};return window.addEventListener("keydown",u,!0),()=>window.removeEventListener("keydown",u,!0)},[n]),n?l.jsx("div",{className:"fixed inset-0 z-[100] bg-black/25 flex items-center justify-center animate-fade-in p-6",onClick:o,children:l.jsxs("div",{className:"bg-card border border-line rounded-2xl shadow-xl w-[680px] max-w-full max-h-[85vh] overflow-y-auto",onClick:u=>u.stopPropagation(),role:"dialog","aria-labelledby":"whats-new-title","data-whats-new":!0,children:[l.jsxs("div",{className:"px-6 pt-5 pb-4 border-b border-line",children:[l.jsx("div",{className:"text-2xs uppercase tracking-wide text-ink-faint",children:"ThoughtDAG"}),l.jsx("h2",{id:"whats-new-title",className:"text-base font-semibold text-ink mt-0.5",children:ve(r("whatsNew.title"),{v:Os??""})}),e.length>1&&l.jsx("p",{className:"text-xs text-ink-faint mt-1",children:r("whatsNew.multi")})]}),l.jsx("ol",{className:"px-6 divide-y divide-line",children:e.map(u=>l.jsxs("li",{className:"py-4","data-release":u.version,children:[e.length>1&&l.jsxs("div",{className:"flex items-baseline gap-2.5 mb-1.5",children:[l.jsxs("span",{className:"text-sm font-semibold text-ink tabular-nums",children:["v",u.version]}),l.jsx("span",{className:"text-xs text-ink-faint tabular-nums",children:u.date})]}),l.jsx("p",{className:"text-sm text-ink-muted leading-relaxed [overflow-wrap:anywhere]",children:u.lead[a]}),u.media&&l.jsx(ZM,{media:u.media,lang:a}),l.jsx(JM,{items:u.items,lang:a})]},u.version))}),l.jsxs("div",{className:"sticky bottom-0 bg-card px-6 py-4 border-t border-line flex items-center justify-between gap-4",children:[l.jsx("button",{onClick:()=>{o(),ce.getState().setReleaseNotesOpen(!0)},className:"text-xs text-ink-muted hover:text-ink hover:underline transition-colors","data-whats-new-all":!0,children:r("whatsNew.seeAll")}),l.jsx("button",{ref:s,onClick:o,className:"text-xs text-white px-4 py-2 rounded-lg bg-accent hover:bg-accent-strong transition-colors",children:r("whatsNew.ok")})]})]})}):null}function Iue(){const e=Tt(),t=ce(a=>a.ladderJob);if(R.useEffect(()=>{if(!t||t.running)return;const a=setTimeout(kN,8e3);return()=>clearTimeout(a)},[t]),!t)return null;const n=t.total?Math.min(1,(t.done+t.failed)/t.total):1;return l.jsxs("div",{className:"fixed bottom-4 right-4 z-[85] w-[300px] bg-card border border-line rounded-xl shadow-lg px-4 py-3 animate-fade-in","data-ladder-job":!0,"data-ladder-job-running":t.running?"yes":"no",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(g2,{size:14,strokeWidth:1.75,className:"text-accent shrink-0"}),l.jsx("span",{className:"text-xs font-medium text-ink flex-1",children:e("ladder.jobTitle")}),t.running?l.jsxs("button",{onClick:Rle,disabled:t.cancelled,className:"flex items-center gap-1 text-2xs text-ink-muted hover:text-red-600 disabled:opacity-50","data-ladder-job-stop":!0,children:[l.jsx(V0,{size:10,strokeWidth:1.75,fill:"currentColor"})," ",t.cancelled?e("ladder.jobStopping"):e("ladder.jobStop")]}):l.jsx("button",{onClick:kN,className:"text-ink-faint hover:text-ink",title:e("ladder.jobClose"),"data-ladder-job-close":!0,children:l.jsx(on,{size:13,strokeWidth:1.75})})]}),l.jsx("div",{className:"mt-2 h-1 rounded-full bg-wash overflow-hidden",children:l.jsx("div",{className:"h-full bg-accent transition-[width] duration-300",style:{width:`${Math.round(n*100)}%`}})}),l.jsx("p",{className:"mt-1.5 text-2xs text-ink-muted tabular-nums","data-ladder-job-line":!0,children:t.running?ve(e("ladder.jobProgress"),{n:t.done+t.failed,m:t.total,model:t.model}):(t.cancelled?ve(e("ladder.jobStopped"),{n:t.done}):ve(e("ladder.jobDone"),{n:t.done,k:t.skipped}))+(t.failed?ve(e("ladder.jobFailed"),{f:t.failed}):"")}),!t.running&&t.failed>0&&t.lastError&&l.jsx("p",{className:"mt-1 text-2xs text-red-500 break-words","data-ladder-job-error":!0,children:t.lastError})]})}function Oue(){const e=ce(r=>r.releaseNotesOpen),t=ce(r=>r.setReleaseNotesOpen),n=Aa(r=>r.lang),a=Tt();return R.useEffect(()=>{if(!e)return;const r=s=>{s.key==="Escape"&&(s.stopPropagation(),t(!1))};return window.addEventListener("keydown",r,!0),()=>window.removeEventListener("keydown",r,!0)},[e,t]),e?l.jsx("div",{className:"fixed inset-0 z-[100] bg-black/25 flex items-center justify-center animate-fade-in p-6",onClick:()=>t(!1),children:l.jsxs("div",{className:"bg-card border border-line rounded-2xl shadow-xl w-[680px] max-w-full max-h-[85vh] overflow-y-auto",onClick:r=>r.stopPropagation(),role:"dialog","aria-labelledby":"release-notes-title","data-release-notes":!0,children:[l.jsxs("div",{className:"px-6 pt-5 pb-4 border-b border-line",children:[l.jsx("div",{className:"text-2xs uppercase tracking-wide text-ink-faint",children:"ThoughtDAG"}),l.jsx("h2",{id:"release-notes-title",className:"text-base font-semibold text-ink mt-0.5",children:a("releaseNotes.title")})]}),l.jsx("ol",{className:"px-6 divide-y divide-line",children:QM.map(r=>{const s=Os===r.version;return l.jsxs("li",{className:"py-4","data-release":r.version,children:[l.jsxs("div",{className:"flex items-baseline gap-2.5 flex-wrap",children:[l.jsxs("span",{className:"text-sm font-semibold text-ink tabular-nums",children:["v",r.version]}),l.jsx("span",{className:"text-xs text-ink-faint tabular-nums",children:r.date}),s&&l.jsx("span",{className:"text-2xs font-medium uppercase tracking-wide text-accent bg-accent/10 rounded-full px-2 py-0.5",children:a("releaseNotes.current")})]}),l.jsx("p",{className:"text-sm text-ink-muted leading-relaxed mt-1.5 [overflow-wrap:anywhere]",children:r.lead[n]}),l.jsx(JM,{items:r.items,lang:n})]},r.version)})}),l.jsx("div",{className:"sticky bottom-0 bg-card px-6 py-4 border-t border-line flex justify-end",children:l.jsx("button",{onClick:()=>t(!1),className:"text-xs text-ink px-4 py-2 rounded-lg border border-line hover:bg-wash transition-colors",children:a("common.close")})})]})}):null}const Ob=e=>e.split("/").filter(Boolean).slice(-1)[0]??e;function Due(){const e=Tt(),t=ce(_=>_.selectedModel),n=sn(_=>_.activeId),a=sn(_=>_.projects),r=se(_=>_.nodes.length),[s,o]=R.useState(null),[u,d]=R.useState(null),[h,m]=R.useState(!1),[p,x]=R.useState(""),[,b]=R.useState(0),y=R.useRef(null),w=!!window.desktopSessions&&M2(t),E=!!window.desktopAgents&&(li(t)||w);if(R.useEffect(()=>{if(!E)return;let _=!0;return W2(w).then(A=>{_&&o(A)}),UV().then(A=>{_&&d(A)}),()=>{_=!1}},[E,w,n,a,r]),R.useEffect(()=>{if(!h)return;const _=H=>{y.current&&!y.current.contains(H.target)&&m(!1)},A=H=>{H.key==="Escape"&&m(!1)};return document.addEventListener("mousedown",_),document.addEventListener("keydown",A),()=>{document.removeEventListener("mousedown",_),document.removeEventListener("keydown",A)}},[h]),!E||!s)return null;const v=a.find(_=>_.id===n),N=[...new Set(a.map(_=>_.agentCwd).filter(_=>!!_))].filter(_=>_!==v?.agentCwd).slice(0,5),S=async _=>{n&&(await Q2(n,_),m(!1))},C=window.desktopAgents?.capabilities?.nativePicker!==!1,I=async()=>{const _=await window.desktopAgents.pickCwd();_?await S(_):window.desktopAgents?.capabilities?.nativePicker===!1&&b(A=>A+1)},O=async()=>{const _=p.trim();_.startsWith("/")&&await S(_)};return l.jsxs("div",{ref:y,className:"relative",children:[l.jsxs("button",{onClick:_=>{_.stopPropagation(),m(A=>!A)},className:"bg-card/90 backdrop-blur border border-line rounded-lg h-8 px-2.5 flex items-center gap-1.5 shadow-sm hover:bg-wash transition-colors text-xs text-ink max-w-[220px]",title:`${e("agent.cwd")} · ${s.cwd}`,"data-agent-cwd":s.kind,children:[l.jsx(pu,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),l.jsx("span",{className:"truncate",children:s.kind==="workspace"?e("agent.cwdWorkspace"):Ob(s.cwd)}),l.jsx(ur,{size:12,strokeWidth:1.75,className:"text-ink-faint shrink-0"})]}),h&&l.jsxs("div",{className:"absolute right-0 top-full mt-1.5 w-[320px] bg-card border border-line rounded-xl shadow-lg py-1.5 z-50 animate-fade-in",onClick:_=>_.stopPropagation(),children:[l.jsx("p",{className:"text-2xs text-ink-faint uppercase tracking-wider font-medium px-3 pt-1 pb-1",children:e("agent.cwd")}),l.jsxs("button",{onClick:()=>{S(void 0)},className:"w-full text-left px-3 py-2 text-xs hover:bg-wash flex items-center gap-2",children:[l.jsxs("span",{className:"flex-1 min-w-0",children:[l.jsx("span",{className:"block text-ink",children:u?e("agent.cwdMirrored"):s.kind==="session"?e("agent.cwdSession"):e("agent.cwdWorkspace")}),l.jsx("span",{className:"block text-2xs text-ink-faint truncate",children:u??(s.kind==="session"?s.cwd:e("agent.cwdWorkspaceHint"))})]}),!v?.agentCwd&&l.jsx(es,{size:13,strokeWidth:2,className:"shrink-0 text-accent"})]}),v?.agentCwd&&l.jsxs("button",{onClick:()=>{S(v.agentCwd)},className:"w-full text-left px-3 py-2 text-xs hover:bg-wash flex items-center gap-2",children:[l.jsxs("span",{className:"flex-1 min-w-0",children:[l.jsx("span",{className:"block text-ink",children:Ob(v.agentCwd)}),l.jsx("span",{className:"block text-2xs text-ink-faint truncate",children:v.agentCwd})]}),l.jsx(es,{size:13,strokeWidth:2,className:"shrink-0 text-accent"})]}),N.length>0&&l.jsx("p",{className:"text-2xs text-ink-faint uppercase tracking-wider font-medium px-3 pt-2 pb-1",children:e("agent.cwdRecent")}),N.map(_=>l.jsx("button",{onClick:()=>{S(_)},className:"w-full text-left px-3 py-1.5 text-xs hover:bg-wash flex items-center gap-2",children:l.jsxs("span",{className:"flex-1 min-w-0",children:[l.jsx("span",{className:"block text-ink",children:Ob(_)}),l.jsx("span",{className:"block text-2xs text-ink-faint truncate",children:_})]})},_)),l.jsx("div",{className:"border-t border-line/60 my-1"}),C?l.jsxs("button",{onClick:()=>{I()},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash flex items-center gap-2","data-agent-cwd-pick":!0,children:[l.jsx(pu,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",e("agent.cwdPick")]}):l.jsxs("div",{className:"px-3 py-2 flex items-center gap-2",children:[l.jsx("input",{value:p,onChange:_=>x(_.target.value),onKeyDown:_=>{_.stopPropagation(),_.key==="Enter"&&O()},placeholder:e("agent.cwdType"),className:"flex-1 min-w-0 text-xs font-mono bg-wash border border-line rounded-md px-2 py-1 focus:outline-none focus:border-accent/60","data-agent-cwd-input":!0}),l.jsx("button",{onClick:()=>{O()},className:"text-xs text-accent hover:underline shrink-0",children:e("agent.cwdUse")})]}),l.jsx("div",{className:"border-t border-line/60 my-1"}),l.jsx("p",{className:"text-2xs text-ink-faint uppercase tracking-wider font-medium px-3 pt-1 pb-1",children:e("agent.guard")}),l.jsxs("button",{onClick:()=>{YE("ask"),m(!1)},className:"w-full text-left px-3 py-1.5 text-xs hover:bg-wash flex items-center gap-2","data-agent-guard":"ask",children:[l.jsx(FU,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),l.jsxs("span",{className:"flex-1 min-w-0",children:[l.jsx("span",{className:"block text-ink",children:e("agent.guardAsk")}),l.jsx("span",{className:"block text-2xs text-ink-faint",children:e("agent.guardAskHint")})]}),(v?.agentGuard?.mode??"ask")==="ask"&&l.jsx(es,{size:13,strokeWidth:2,className:"shrink-0 text-accent"})]}),l.jsxs("button",{onClick:()=>{YE("allow"),m(!1)},className:"w-full text-left px-3 py-1.5 text-xs hover:bg-wash flex items-center gap-2","data-agent-guard":"allow",children:[l.jsx(qU,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),l.jsxs("span",{className:"flex-1 min-w-0",children:[l.jsx("span",{className:"block text-ink",children:e("agent.guardAllow")}),l.jsx("span",{className:"block text-2xs text-ink-faint",children:e("agent.guardAllowHint")})]}),v?.agentGuard?.mode==="allow"&&l.jsx(es,{size:13,strokeWidth:2,className:"shrink-0 text-accent"})]}),(v?.agentGuard?.allow?.length??0)>0&&l.jsxs(l.Fragment,{children:[l.jsx("p",{className:"text-2xs text-ink-faint px-3 pt-2 pb-1",children:e("agent.guardAllowed")}),v.agentGuard.allow.map(_=>l.jsxs("div",{className:"px-3 py-1 text-xs flex items-center gap-2 min-w-0","data-agent-guard-allowed":_,children:[l.jsx("span",{className:"flex-1 min-w-0 truncate text-ink-muted font-mono",title:_,children:_}),l.jsx("button",{onClick:()=>{z7(_,!0)},className:"text-ink-faint hover:text-red-500 shrink-0",title:e("agent.guardRemove"),children:l.jsx(on,{size:12,strokeWidth:2})})]},_))]})]})]})}const XN="thoughtdag.pluginUpdateNotified";function Xy(e){return`dsh plugin --profile web add dsh-thoughtdag@${e||"latest"}`}async function Rue(e){try{const t=await fetch(e.replace(/\/+$/,"")+"/version",{credentials:"same-origin"});if(!t.ok)return;const n=await t.json();if(!n.version||!n.latest||Yy(n.latest,n.version)<=0)return;ce.getState().setPluginUpdate({current:n.version,latest:n.latest});let a=null;try{a=localStorage.getItem(XN)}catch{}if(a!==n.latest){try{localStorage.setItem(XN,n.latest)}catch{}const r=ce.getState().harnessHost?.desktop??(()=>{try{const s=window.parent?.document?.documentElement;return!!s&&(s.dataset.platform!==void 0||s.hasAttribute("data-windows-titlebar"))}catch{return!1}})();We("info",ve(Ne("plugin.updateAvailable"),{v:n.latest})+(r?" "+ve(Ne("plugin.updateHintDesktop"),{pkg:`dsh-thoughtdag@${n.latest}`}):""),12e3)}}catch{}}const jue=Object.freeze(Object.defineProperty({__proto__:null,bootPluginUpdateCheck:Rue,pluginUpdateCommand:Xy},Symbol.toStringTag,{value:"Module"})),Lue={ruleout:"#ef4444",decision:"#6B5CE7",pivot:"#e8890c",open:"#d97706",insight:"#0284c7"},QN=e=>{if(e){for(let t=e.length-1;t>=0;t--)if(e[t])return e[t]}};function Pue(e){if(e.stepKind==="file")return e.attachments?.[0]?.name;if(e.stepKind==="link")return e.linkTitle||e.linkUrl;if(e.stepKind==="note")return e.question?.split(`
938
938
  `)[0].replace(/^#+\s*/,"")||void 0}function Jv(e,t,n={}){return e.filter(a=>a.data.stepKind!=="frame").map((a,r)=>{const s=a.data,o=s.createdAt??s.askedAt??s.generatedAts?.[0]??s.lastGeneratedAt,u=[s.askedAt,QN(s.generatedAts),QN(s.editedAts)].filter(Boolean).sort().pop(),d=s.summaryTypes?.[s.responseIndex??0]??void 0,h=s.summaries?.[s.responseIndex??0],m=s.summaryTopics?.[s.responseIndex??0]??void 0,p=n.ladders?s.summaryLadders?.[s.responseIndex??0]??q2(a.id,s.question,s.response,h,m):null,x=o?Date.parse(o):NaN,b=u?Date.parse(u):NaN;return{entry:{id:a.id,label:(h||Pue(s)||s.question||"").slice(0,120),topic:m,...p?{ladder:p}:{},badged:!!d&&d!=="insight",type:d??void 0,createdAt:o,modifiedAt:u,color:d&&Lue[d]||"#b8b3c7",archived:!!s.archived,recentlyEdited:!isNaN(x)&&!isNaN(b)&&b-x>6e4&&t-b<30*6e4,x:a.position.x,y:a.position.y},i:r}}).sort((a,r)=>{const s=a.entry.createdAt??"",o=r.entry.createdAt??"";return s<o?-1:s>o?1:a.i-r.i}).map(({entry:a})=>a)}const zue=e=>e?24:16,Bue=(e,t,n)=>{const a=zue(n);if(t==null)return a;const r=Math.abs(e-t);return r===0?a+14:r===1?a+7:r===2?a+3:a};function Hue(){const e=Z0(),t=se(C=>C.nodes),n=se(C=>C.setSelectedNodeId),a=ce(C=>C.setTimelineOverviewOpen),r=Zl(),s=Tt(),o=o8(),[u,d]=R.useState(null),[h,m]=R.useState(()=>Date.now());R.useEffect(()=>{const C=setInterval(()=>m(Date.now()),6e4);return()=>clearInterval(C)},[]);const p=fn(C=>C.transform),x=fn(C=>C.width),b=fn(C=>C.height),y=R.useMemo(()=>Jv(t,h),[t,h]),w=R.useMemo(()=>{const[C,I,O]=p,_=-C/O,A=-I/O,H=(x-C)/O,G=(b-I)/O,D=new Set;for(const P of y)P.x+520>_&&P.x<H&&P.y+220>A&&P.y<G&&D.add(P.id);return D},[y,p,x,b]);if(e==="work"||y.length<2)return null;const E=C=>C?C.slice(0,10):"",v=C=>C.slice(5).replace("-","/"),N=C=>C?new Date(C).toLocaleString(o):"",S=u?y.find(C=>C.id===u.id):null;return l.jsxs("div",{className:"absolute left-[2px] top-[calc(38%+116px)] w-[100px] z-10 tdag-timeline pointer-events-none flex flex-col items-stretch","data-timeline-bar":!0,role:"navigation","aria-label":s("timeline.label"),children:[S&&u&&l.jsxs("div",{className:"fixed left-[108px] max-w-[320px] bg-card border border-line rounded-lg shadow-md px-3 py-2 text-xs pointer-events-none z-20",style:{top:u.y-14},children:[l.jsxs("div",{className:"font-medium text-ink truncate",children:[S.topic&&l.jsxs("span",{className:"text-accent",children:[S.topic," · "]}),S.label||"…"]}),S.createdAt&&l.jsxs("div",{className:"text-ink-faint mt-0.5",children:[s("timeline.created")," ",N(S.createdAt)]}),S.modifiedAt&&S.modifiedAt!==S.createdAt&&l.jsxs("div",{className:"text-ink-faint",children:[s("timeline.modified")," ",N(S.modifiedAt)]}),l.jsx("div",{className:"text-[10px] text-ink-faint/80 mt-1",children:s("timeline.clickHint")})]}),l.jsx("button",{onClick:()=>a(!0),title:s("timeline.openOverview"),"data-timeline-overview-btn":!0,className:"pointer-events-auto self-start ml-[25px] w-7 h-7 rounded-lg flex items-center justify-center text-ink-faint/70 hover:text-accent hover:bg-accent/10 transition-colors",children:l.jsx(Ep,{size:14,strokeWidth:1.75})}),l.jsx("div",{className:"pointer-events-auto overflow-y-auto tdag-noscrollbar max-h-[170px] mt-0.5",children:l.jsx("div",{className:"flex flex-col py-1",children:y.map((C,I)=>{const O=I>0?E(y[I-1].createdAt):"",_=E(C.createdAt),A=_!==""&&_!==O;return l.jsxs("button",{"data-timeline-dot":C.id,onMouseEnter:H=>d({id:C.id,idx:I,y:H.currentTarget.getBoundingClientRect().top}),onMouseLeave:()=>d(H=>H?.id===C.id?null:H),onClick:()=>{n(C.id);const H=r.getViewport().zoom;r.setCenter(C.x+260+cp(C.id)/(2*H),C.y+110,{zoom:H,duration:300})},onDoubleClick:()=>{n(C.id),r.setCenter(C.x+260+cp(C.id)/2,C.y+110,{zoom:1,duration:350})},className:"relative flex items-center w-full h-[14px] shrink-0 pl-[29px] cursor-pointer","aria-label":C.label,children:[l.jsx("span",{className:`rounded-full ${C.recentlyEdited?"tdag-timeline-pulse":""}`,style:{width:Bue(I,u?.idx??null,C.badged),height:4,background:C.color,opacity:C.archived?.3:w.has(C.id)?1:.45,transition:"width .18s ease, opacity .3s ease"}}),A&&l.jsx("span",{className:"absolute left-[67px] top-1/2 -translate-y-1/2 text-[10px] leading-none text-ink-faint select-none whitespace-nowrap",children:v(_)})]},C.id)})})})]})}function eI(e){const t=e.filter(a=>!a.data.archived).map(a=>`${a.id}:${Qi(a.data)??""}:${a.data.summaryTypes?.[a.data.responseIndex]??""}`).sort();let n=5381;for(const a of t)for(let r=0;r<a.length;r++)n=(n<<5)+n+a.charCodeAt(r)|0;return String(n>>>0)}const Qy=new Map,Fue=(e,t)=>Qy.get(`${t}:${e}`),ZN={ruleout:"RULEOUT",decision:"DECISION",pivot:"PIVOT",open:"OPEN",insight:"INSIGHT"};async function Uue(e,t,n){const a=eI(e),r=Qy.get(`${n}:${a}`);if(r)return r;const s=e.find(b=>b.data.isRoot),o=Jv(e.filter(b=>!b.data.archived),0),d=o.length>60?o.filter((b,y)=>b.badged||y<10||y>=o.length-10):o,h=o.length-d.length,m=d.map(b=>{const y=e.find(N=>N.id===b.id);if(!y)return null;const w=y.data,E=Qi(w);if(!E)return null;const v=w.summaryTypes?.[w.responseIndex]??void 0;return`- ${v&&ZN[v]?`${ZN[v]}: `:""}${b.topic?`[${b.topic}] `:""}${E}`}).filter(b=>!!b);h>0&&m.push(`(${h} plain steps omitted from this list)`);const x={text:(await Ka([{role:"user",content:`Opening question of a thinking map: ${s?.data.question?.slice(0,300)??"(untitled)"}
939
939
 
940
940
  The takeaway of every step, in the order they were thought (tags: RULEOUT = killed an option, DECISION = chose, PIVOT = reframed, OPEN = still unresolved):
941
941
  ${m.join(`
942
942
  `)}
943
943
 
944
- Write the JOURNEY of this thinking as one flowing paragraph a reader absorbs in twenty seconds: where it started, what got ruled out, where it turned, where it landed, what remains open. Only the turns that mattered — do not enumerate every step. Hard limit: 250 characters for CJK languages, 500 characters otherwise. Write in ${n==="zh"?"Chinese":"English"} (the reader's interface language), even if the takeaway lines mix languages. Never use dash characters (—, –, -); use commas, colons or full stops. Output only the paragraph.`}])).trim(),fp:a,at:new Date().toISOString(),lang:n};return Qy.set(`${n}:${a}`,x),x}function que({onLocate:e}){const t=ce(z=>z.timelineOverviewOpen),n=ce(z=>z.setTimelineOverviewOpen),a=se(z=>z.nodes),r=Tt(),s=o8(),o=Aa(z=>z.lang),u=AV(),d=R.useMemo(()=>Jv(a,0,{ladders:!0}),[a,u]),[h,m]=R.useState(1),p=Math.round(h),x={paddingTop:4+h*5,paddingBottom:4+h*5},b=R.useRef(null),y=R.useRef(null),w=R.useRef(null),E=z=>{const L=b.current;if(L){const q=L.getBoundingClientRect().top,W=[...L.querySelectorAll("[data-entry]")];let X=y.current?W.find(B=>B.dataset.entry===y.current)??null:null;if(!X){const B=q+L.clientHeight/2;X=W.reduce(($,Z)=>{const K=Z.getBoundingClientRect(),J=Math.abs((K.top+K.bottom)/2-B);return!$||J<Math.abs(($.getBoundingClientRect().top+$.getBoundingClientRect().bottom)/2-B)?Z:$},null)}w.current=X?{id:X.dataset.entry,y:X.getBoundingClientRect().top-q}:null}m(z)};R.useLayoutEffect(()=>{const z=b.current,L=w.current;if(!z||!L)return;const q=z.querySelector(`[data-entry="${L.id}"]`);if(!q)return;const W=q.getBoundingClientRect().top-z.getBoundingClientRect().top;z.scrollTop+=W-L.y},[h]);const v=13+h*.9,N=R.useMemo(()=>eI(a),[a]),[S,C]=R.useState(null),[I,O]=R.useState(!1),[_,A]=R.useState(!1),H=Fue(N,o)??S,G=!!H&&(H.fp!==N||H.lang!==o),D=()=>{O(!0),A(!1);const{nodes:z,edges:L}=se.getState();Uue(z,L,o).then(C).catch(()=>A(!0)).finally(()=>O(!1))};if(!t)return null;const P=()=>n(!1),Y=z=>z?z.slice(0,10):"",U=z=>z?new Date(z).toLocaleTimeString(s,{hour:"2-digit",minute:"2-digit"}):"—";return dr.createPortal(l.jsx("div",{className:"fixed inset-0 z-[60] bg-ink/30 backdrop-blur-sm flex items-center justify-center p-6",onClick:P,children:l.jsxs("div",{className:"bg-card rounded-2xl shadow-2xl border border-line w-[640px] h-[80vh] flex flex-col",onClick:z=>z.stopPropagation(),children:[l.jsxs("div",{className:"flex items-center gap-2 px-5 py-3 border-b border-line shrink-0",children:[l.jsx(Ep,{size:15,strokeWidth:1.75,className:"text-accent"}),l.jsx("span",{className:"text-sm font-semibold text-ink",children:r("tlov.title")}),l.jsx("span",{className:"text-2xs text-ink-faint",children:ve(r("tlov.count"),{n:d.length})}),l.jsxs("label",{className:"flex items-center gap-2 ml-3 text-2xs text-ink-faint",title:r("tlov.detailTitle"),children:[l.jsx("span",{children:r("tlov.detail")}),l.jsx("input",{type:"range",min:0,max:3,step:.01,value:h,onChange:z=>E(Number(z.target.value)),className:"w-28 accent-accent","data-tlov-detail":!0}),l.jsx("span",{className:"text-ink-muted w-8",children:r(`ladder.level${p}`)})]}),l.jsx("div",{className:"flex-1"}),l.jsxs("button",{onClick:()=>{P(),ce.getState().setThoughtMapOpen(!0)},disabled:d.length===0,"data-tmap-from-timeline":!0,className:"flex items-center gap-1.5 text-2xs text-ink-muted hover:text-accent hover:bg-accent/10 rounded-full px-2.5 py-1 transition-colors disabled:opacity-50",children:[l.jsx(p2,{size:13,strokeWidth:1.75}),r("tmap.export")]}),l.jsx("button",{onClick:P,className:"text-ink-faint hover:text-ink w-7 h-7 rounded-lg hover:bg-wash flex items-center justify-center transition-colors",children:l.jsx(on,{size:15,strokeWidth:1.75})})]}),l.jsxs("div",{className:"px-5 pt-3 shrink-0","data-gedankengang":!0,children:[!H&&!I&&l.jsxs("button",{onClick:D,className:"flex items-center gap-1.5 text-2xs text-accent bg-accent/10 hover:bg-accent/20 rounded-full px-3 py-1.5 transition-colors",children:[l.jsx(Vl,{size:12,strokeWidth:1.75}),r("tlov.gedankenGenerate")]}),I&&l.jsx("p",{className:"text-2xs text-ink-faint italic py-1.5",children:r("tlov.gedankenLoading")}),_&&!I&&l.jsx("p",{className:"text-2xs text-red-500 py-1",children:r("tlov.gedankenFailed")}),H&&!I&&l.jsxs("div",{className:`rounded-xl bg-wash px-4 py-3 ${G?"opacity-60":""}`,children:[l.jsx("p",{className:"text-sm text-ink leading-relaxed",children:H.text}),l.jsxs("div",{className:"flex items-center gap-2 mt-1.5",children:[l.jsx("span",{className:"text-2xs text-ink-faint",children:G?r("tlov.gedankenStale"):new Date(H.at).toLocaleString(s)}),G&&l.jsx("button",{onClick:D,className:"text-2xs text-accent hover:underline",children:r("tlov.gedankenRedo")})]})]})]}),l.jsxs("div",{ref:b,className:"flex-1 min-h-0 overflow-y-auto px-5 py-3","data-timeline-overview":!0,children:[d.length===0&&l.jsx("p",{className:"text-xs text-ink-faint italic py-2",children:r("tlov.empty")}),d.map((z,L)=>{const q=L>0?Y(d[L-1].createdAt):void 0,W=Y(z.createdAt),X=L===0||W!==q;return l.jsxs("div",{children:[X&&l.jsx("div",{className:"sticky top-0 bg-card text-2xs text-ink-faint font-medium pt-3 pb-1 first:pt-0",children:W||r("tlov.undated")}),l.jsxs("div",{className:"group flex items-start gap-2.5 border-b border-line/50 last:border-0",style:x,"data-entry":z.id,onMouseEnter:()=>{y.current=z.id},onMouseLeave:()=>{y.current===z.id&&(y.current=null)},children:[l.jsx("span",{className:"w-2 h-2 rounded-full shrink-0",style:{background:z.color,opacity:z.archived?.35:1}}),l.jsx("span",{className:"text-2xs font-mono text-ink-faint shrink-0 w-11",children:U(z.createdAt)}),l.jsxs("div",{className:"flex-1 min-w-0",children:[z.ladder?l.jsx("div",{className:z.archived?"opacity-50 line-through":"",children:l.jsx(yM,{ladder:z.ladder,level:p,fontSize:v,weight:z.badged?"font-semibold":"font-medium",className:"whitespace-pre-wrap break-words"})}):l.jsx("p",{className:`leading-snug whitespace-pre-wrap break-words ${z.archived?"text-ink-faint line-through":z.badged?"text-ink":"text-ink-muted"}`,style:{fontSize:v,transition:"font-size 160ms ease-out"},children:p===0?z.topic||z.label||"…":l.jsxs(l.Fragment,{children:[z.topic&&l.jsxs("span",{className:"font-medium text-accent",children:[z.topic," · "]}),z.label||"…"]})}),z.modifiedAt&&z.modifiedAt!==z.createdAt&&l.jsxs("p",{className:"text-2xs text-ink-faint",children:[r("timeline.modified")," ",new Date(z.modifiedAt).toLocaleString(s)]})]}),l.jsx("button",{className:"shrink-0 text-2xs font-mono text-accent bg-accent/10 hover:bg-accent/20 rounded-full px-1.5 py-0.5 transition-colors opacity-0 group-hover:opacity-100",onClick:()=>{P(),e(z.id)},title:r("hlov.locateTitle"),children:r("tlov.locate")})]})]},z.id)})]})]})}),document.body)}const $ue=R.memo(function(t){const n=sn(a=>a.projects.find(r=>r.id===a.activeId)?.kind==="paradigm");return t.data?.stepKind==="frame"?l.jsx(ele,{...t}):Bm(t.data?.stepKind)?l.jsx(Joe,{...t}):n?l.jsx(Koe,{...t}):l.jsx(Voe,{...t})}),Wue={thought:$ue},Vue={smoothstep:R.memo(ale)};function Gue(){const[e,t]=R.useState(Nt||se.persist.hasHydrated());return R.useEffect(()=>se.persist.onFinishHydration(()=>t(!0)),[]),R.useEffect(()=>{if(!e||Nt)return;let n;const a=()=>{clearTimeout(n),n=setTimeout(()=>{jce()},800)},r=se.subscribe((s,o)=>{s.nodes!==o.nodes&&a()});return a(),()=>{r(),clearTimeout(n)}},[e]),R.useEffect(()=>{ce.getState().condenseRun.status==="building"&&ce.getState().setCondenseRun({status:"idle",current:0,total:0,streaming:""})},[]),R.useEffect(()=>{if(Nt)return;const n=setTimeout(()=>{Lce()},6e3);return()=>clearTimeout(n)},[]),R.useEffect(()=>{if(!e||Nt||localStorage.getItem("thoughtdag.tutorialDone")||se.getState().nodes.length>0)return;const n=setTimeout(()=>ce.getState().setTutorialOpen(!0),900);return()=>clearTimeout(n)},[e]),R.useEffect(()=>{Fce()},[]),R.useEffect(()=>{Nt||(pt(()=>import("./session-handoff-DwZJMHEU.js"),[]).then(n=>n.consumeSessionHandoff()),pt(()=>Promise.resolve().then(()=>n7),void 0).then(n=>n.startLiveMirror()),pt(()=>import("./canvas-record-PNNfw7b3.js"),[]).then(n=>n.startCanvasRecord()),pt(()=>import("./canonical-46lAq3XC.js"),[]).then(n=>n.unsubscribeOrphanedSessions()))},[]),R.useEffect(()=>{Nt||Hce().then(n=>{n&&(n.status==="minted"?(We("success",Ne("provider.oauthMinted")),WM(n.key)):We("error",ve(Ne("provider.oauthFailed"),{error:n.error})))})},[]),l.jsxs(l.Fragment,{children:[e&&l.jsx(Yue,{}),l.jsx(Wce,{}),l.jsx(Iue,{}),l.jsx(Gce,{}),l.jsx(Xce,{}),l.jsx(Qce,{}),l.jsx(eue,{}),l.jsx(tue,{}),l.jsx(nue,{}),l.jsx(lue,{}),l.jsx(mue,{}),l.jsx(Uce,{}),l.jsx(Tue,{}),l.jsx(Mue,{}),l.jsx(Oue,{})]})}function Yue(){const{nodes:e,edges:t,setNodes:n,setEdges:a,addQuestion:r,undo:s,redo:o,addCrossLink:u,setSelectedNodeId:d,setSelectedNodeIds:h,history:m,historyIndex:p,relayout:x}=se(),b=Tt(),y=ce(te=>te.setTutorialOpen),w=ce(te=>te.annotationsHidden),E=ce(te=>te.setAnnotationsHidden),v=ce(te=>te.wheelPans),N=ce(te=>te.setWheelPans),[S,C]=R.useState(""),[I,O]=R.useState(!1),[_,A]=R.useState(!1),[H,G]=R.useState(""),[D,P]=R.useState(!1),[Y,U]=R.useState(!1),[z,L]=R.useState([]),[q,W]=R.useState(!1),X=R.useRef(null),B=R.useRef(null),$=e.length>0,Z=se(te=>te.events.length>0),K=se(te=>te.nodes.reduce((pe,Ae)=>pe+(Ae.data.highlights?.length??0),0)),J=se(te=>te.nodes.reduce((pe,Ae)=>pe+(Ae.data.attachments?.length??0)+(["note","link"].includes(Ae.data.stepKind??"")?1:0),0)),oe=R.useRef(null),me=ce(te=>te.arrivalFocusNodeId);R.useEffect(()=>{if(!me)return;const te=se.getState().nodes.find(pe=>pe.id===me);te&&(ce.getState().setArrivalFocusNodeId(null),window.setTimeout(()=>{oe.current?.setCenter(te.position.x+260,te.position.y+140,{zoom:.9,duration:400})},150))},[me]);const ye=qi(te=>te.paper),ae=qi(te=>te.lighting),ge=qi(te=>te.resolved),Te=R.useMemo(()=>Zoe(),[ge]),Fe=R.useMemo(()=>{const te=getComputedStyle(document.documentElement),pe=(te.getPropertyValue("--color-surface").trim()||"#FAF9F7").replace("#",""),[Ae,Oe,ct]=[0,2,4].map(ht=>parseInt(pe.slice(ht,ht+2),16));return{mask:`rgba(${Ae},${Oe},${ct},0.7)`,archived:te.getPropertyValue("--color-wash").trim()||"#EFEDE9",ordinary:ge==="dark"?"#6E6759":"#B9B3AB"}},[ge]),Me=R.useRef(e.length),Le=R.useCallback((te,pe={})=>{const Ae=oe.current;if(!Ae)return;const Oe=pe.zoom??Ae.getZoom();Ae.setCenter(te.position.x+(pe.offX??260)+cp(te.id)/(2*Oe),te.position.y+110,{zoom:Oe,duration:pe.duration??350})},[]),Ee=Aa(te=>te.lang),ze=ce(te=>te.condenseRun),De=ze.status==="building",tt=sn(te=>te.projects.find(pe=>pe.id===te.activeId)?.kind==="paradigm"),xt=ec(),Ke=R.useCallback(()=>{const{nodes:te,edges:pe}=Rce(Ee),Ae=se.getState();Ae.setNodes([...Ae.nodes,...te.filter(Oe=>!Ae.nodes.some(ct=>ct.id===Oe.id))]),Ae.setEdges([...Ae.edges,...pe.filter(Oe=>!Ae.edges.some(ct=>ct.id===Oe.id))]),Ae.pushHistory(),setTimeout(()=>{const Oe=oe.current;Oe&&(Oe.fitView({duration:500,padding:.1}),setTimeout(()=>{if(Oe.getViewport().zoom<.34){const ct=[...se.getState().nodes].sort((ht,Et)=>(ht.data.createdAt??"").localeCompare(Et.data.createdAt??""))[0];ct&&Oe.setCenter(ct.position.x+300,ct.position.y+240,{zoom:.6,duration:550})}},680))},100),localStorage.getItem("thoughtdag.tutorialDone")||y(!0)},[Ee,y]),nt=R.useCallback(te=>{const pe=se.getState(),Ae=pe.nodes[pe.nodes.length-1],Oe=Ae?{x:Ae.position.x,y:Ae.position.y+340}:{x:120,y:80},ct=En();pe.setNodes([...pe.nodes,{id:ct,type:"thought",position:Oe,dragHandle:".drag-handle",data:{question:"",instruction:"",stepKind:te,response:"",responses:[],responseIndex:-1,isCollapsed:!1,isEditing:!1,isEditingResponse:!1,isLoading:!1,tokenCount:0,highlights:[],highlightMode:"tag",attachments:[],excludedAttachmentIds:[],includedAttachmentIds:[],roleMode:"inherit",isRoot:pe.nodes.length===0,isBranch:!1}}]),pe.pushHistory()},[]),st=R.useCallback(()=>{Me.current=se.getState().nodes.length,setTimeout(()=>oe.current?.fitView({duration:300,padding:.2}),50)},[]);R.useEffect(()=>{const te=()=>st();return window.addEventListener("td:project-switched",te),()=>window.removeEventListener("td:project-switched",te)},[st]);const Ue=R.useRef(null),Rt=R.useCallback(te=>{const pe=se.getState(),Ae=En();pe.setNodes([...pe.nodes,{id:Ae,type:"thought",position:te,width:640,height:420,zIndex:-1,dragHandle:".drag-handle",data:{question:"",stepKind:"frame",frameCarry:!1,response:"",responses:[],responseIndex:-1,isCollapsed:!1,isEditing:!1,isEditingResponse:!1,isLoading:!1,tokenCount:0,highlights:[],highlightMode:"tag",attachments:[],excludedAttachmentIds:[],includedAttachmentIds:[],roleMode:"inherit",isRoot:!1,isBranch:!1}}]),pe.pushHistory()},[]),lt=R.useCallback(te=>{const pe=[];for(const Ae of Array.from(te)){const Oe=Ae.name.split(".").pop()?.toLowerCase()??"";Ae.type.startsWith("image/")||Ae.type==="application/pdf"||Ae.type.startsWith("text/")||["pdf","docx","txt","md","csv","json","yaml","yml","toml","js","ts","tsx","jsx","py","sh","c","cpp","h","java","rs","go","rb","swift","css","html","xml","sql","tex","bib"].includes(Oe)?pe.push(Ae):We("info",ve(Ne("toast.unsupportedFile"),{name:Ae.name}))}return pe},[]),Dt=R.useCallback(te=>{const pe=se.getState(),Ae=En();return pe.setNodes([...pe.nodes,{id:Ae,type:"thought",position:te,dragHandle:".drag-handle",data:{question:"",response:"",responses:[],responseIndex:-1,isCollapsed:!1,isEditing:!1,isEditingResponse:!1,isLoading:!1,tokenCount:0,highlights:[],highlightMode:"tag",attachments:[],excludedAttachmentIds:[],includedAttachmentIds:[],roleMode:"inherit",isRoot:!1,isBranch:!1}}]),pe.pushHistory(),Ae},[]),_e=R.useCallback(te=>{const pe=lt(te);if(pe.length===0)return;let Ae=null;pe.forEach((Oe,ct)=>{const ht=gs("file",{x:120+ct%3*480,y:120+Math.floor(ct/3)*620});Xd(ht,[Oe]),!Ae&&!Oe.type.startsWith("image/")&&(Ae=ht)}),Ae&&ce.getState().setReaderNodeId(Ae),setTimeout(()=>oe.current?.fitView({duration:400,padding:.2}),120)},[lt]),Qe=R.useCallback((te,pe)=>{const Ae=te.clientX,Oe=te.clientY,ct=te.currentTarget;let ht=null;const Et=en=>{!ht&&Math.hypot(en.clientX-Ae,en.clientY-Oe)>6&&(ht=document.createElement("div"),ht.innerHTML=ct.innerHTML,ht.style.cssText="position:fixed;z-index:300;pointer-events:none;width:36px;height:36px;display:flex;align-items:center;justify-content:center;background:var(--color-card);border:1px solid var(--color-accent);border-radius:10px;box-shadow:0 4px 14px rgba(0,0,0,.18);opacity:.92;",document.body.appendChild(ht)),ht&&(ht.style.left=`${en.clientX-18}px`,ht.style.top=`${en.clientY-18}px`)},un=en=>{window.removeEventListener("pointermove",Et),window.removeEventListener("pointerup",un);const mn=!!ht;ht?.remove(),pe(mn?{x:en.clientX,y:en.clientY}:null)};window.addEventListener("pointermove",Et),window.addEventListener("pointerup",un)},[]),ie=R.useCallback(te=>{const pe=oe.current?.screenToFlowPosition(te??{x:window.innerWidth/2,y:window.innerHeight/2})??{x:140,y:140};return{x:pe.x-200,y:pe.y-60}},[]);R.useEffect(()=>{const te=Ae=>{Ue.current={x:Ae.clientX,y:Ae.clientY}},pe=Ae=>{if(Nt)return;const Oe=Ae.target;if(Oe&&(Oe.tagName==="INPUT"||Oe.tagName==="TEXTAREA"||Oe.isContentEditable))return;const ct=sn.getState(),ht=ct.projects.find(aa=>aa.id===ct.activeId)?.kind==="paradigm";if(se.getState().nodes.length===0&&!ht)return;const Et=Ae.clipboardData;if(!Et)return;const un=ie(Ue.current),en=Et.getData("text/plain").trim(),mn=Array.from(Et.files),Qa=mn.some(aa=>!aa.type.startsWith("image/"));if(mn.length>0&&(Qa||!en)){Ae.preventDefault();const aa=gs("file",un);Xd(aa,mn);return}if(en)if(Ae.preventDefault(),/^https?:\/\/\S+$/.test(en)){const aa=gs("link",un,{linkUrl:en});J8(aa,en)}else gs("note",un,{question:NW(en)})};return window.addEventListener("mousemove",te),window.addEventListener("paste",pe),()=>{window.removeEventListener("mousemove",te),window.removeEventListener("paste",pe)}},[ie]);const Be=R.useCallback(async()=>{const te=se.getState();if(te.nodes.length===0)return;const{nodes:pe,edges:Ae}=vG(te.nodes,te.edges),Oe=sn.getState(),ct=Oe.projects.find(Et=>Et.id===Oe.activeId)?.name??"Paradigm",ht=crypto.randomUUID();await Pr(ks(ht),JSON.stringify({state:{nodes:pe,edges:Ae},version:1})),await Tu(ht,`▶ ${ct}`,"chat"),await q7(ht,ct),Me.current=se.getState().nodes.length,setTimeout(()=>oe.current?.fitView({duration:400,padding:.15}),150)},[]);R.useEffect(()=>{e.length===0&&!tt&&!localStorage.getItem("thoughtdag.seeded")&&localStorage.setItem("thoughtdag.seeded","yes")},[]),R.useEffect(()=>{if(e.length>Me.current&&oe.current){const te=e[e.length-1];te&&setTimeout(()=>Le(te,{zoom:1,duration:400,offX:220}),100)}Me.current=e.length},[e,Le]);const ot=R.useCallback(te=>{const pe=se.getState().nodes;n(dA(te,pe))},[n]),Ht=R.useCallback(te=>a(hA(te,se.getState().edges)),[a]),Wt=R.useRef(null),Vt=R.useCallback((te,pe)=>{if(pe.data.stepKind!=="frame"||pe.data.frameCarry===!1)return;const Ae=se.getState(),Oe=Ae.nodes.find(ht=>ht.id===pe.id);if(!Oe)return;const ct=R8(Oe,Ae.nodes).filter(ht=>!ht.selected).map(ht=>({id:ht.id,start:ht.position}));ct.length!==0&&(Wt.current={frameId:Oe.id,start:Oe.position,members:ct})},[]),Ft=R.useCallback((te,pe)=>{const Ae=Wt.current;if(!Ae||pe.id!==Ae.frameId)return;const Oe=pe.position.x-Ae.start.x,ct=pe.position.y-Ae.start.y,ht=new Map(Ae.members.map(Et=>[Et.id,{x:Et.start.x+Oe,y:Et.start.y+ct}]));se.setState(Et=>({nodes:Et.nodes.map(un=>{const en=ht.get(un.id);return en?{...un,position:en}:un})}))},[]),ln=R.useCallback(()=>{Wt.current=null},[]),[$t,ha]=R.useState(null),[Dn,qa]=R.useState(null),sr=R.useCallback((te,pe)=>{Nt||window.getSelection()?.toString()||(te.preventDefault(),qa({x:te.clientX,y:te.clientY,nodeId:pe.id}))},[]),na=R.useCallback((te,pe)=>{te.preventDefault(),ha({x:te.clientX,y:te.clientY,edgeId:pe.id})},[]);R.useEffect(()=>{if(!$t)return;const te=()=>ha(null);return window.addEventListener("click",te),()=>window.removeEventListener("click",te)},[$t]);const Ca=se(te=>te.deleteEdges),oa=R.useCallback(te=>{Ca([te]),ha(null)},[Ca]),xe=R.useCallback(te=>{te.source&&te.target&&u(te.source,te.target)},[u]),Ve=R.useCallback(()=>{window.getSelection()?.removeAllRanges(),document.body.classList.add("tdag-connecting")},[]),gt=R.useCallback((te,pe)=>{if(document.body.classList.remove("tdag-connecting"),tt||pe.isValid||pe.fromHandle?.type!=="source"||!pe.fromNode)return;const Ae=pe.fromNode.id,Oe=te.target?.closest?.(".react-flow__node");if(Oe){const mn=Oe.getAttribute("data-id");if(mn&&mn!==Ae){const Qa=se.getState().nodes.find(Ma=>Ma.id===mn),aa=Qa?.data.stepKind??"";Qa&&!["note","file","link","frame"].includes(aa)&&se.getState().addCrossLink(Ae,mn)}return}const{clientX:ct,clientY:ht}="changedTouches"in te?te.changedTouches[0]:te,Et=ie({x:ct,y:ht}),un=se.getState();if(un.nodes.find(mn=>mn.id===Ae)?.data.stepKind==="frame")return;const en=Dt(Et);un.setEdges([...se.getState().edges,{id:`edge-${Ae}-${en}`,source:Ae,target:en,sourceHandle:"continue",targetHandle:"top",type:"smoothstep",style:{stroke:at.accent,strokeWidth:2},animated:!1,markerEnd:{type:"arrowclosed",color:at.accent,width:18,height:18},data:{}}]),se.getState().pushHistory()},[tt,ie,Dt]),wt=se(te=>te.selectedNodeId),cn=se(te=>te.selectedNodeIds),vn=ce(te=>te.panelOpen),_t=ce(te=>te.viewerLoadError),bt=se(te=>Qr(te).length),It=ce(te=>te.panelWidth),Nn=e.find(te=>te.id===wt),Mn=Nn?.data.stepKind,we=Bm(Mn)||Mn==="frame",et=vn&&!!Nn&&!tt&&!we;R.useEffect(()=>{wt&&!Nn&&se.getState().setSelectedNodeId(null)},[wt,Nn]);const St=cn.length>1,Lt=se(te=>te.batchDelete);R.useEffect(()=>{const te=pe=>{if(!ce.getState().confirmRequest&&!(Nt&&!((pe.metaKey||pe.ctrlKey)&&pe.key==="f"))){if((pe.metaKey||pe.ctrlKey)&&pe.key==="z"&&(pe.shiftKey?(pe.preventDefault(),o()):(pe.preventDefault(),s())),(pe.metaKey||pe.ctrlKey)&&pe.key==="f"){pe.preventDefault(),O(!0);return}{const Ae=pe.target;if(!(Ae.tagName==="INPUT"||Ae.tagName==="TEXTAREA"||Ae.isContentEditable)&&wt&&!tt&&!pe.metaKey&&!pe.ctrlKey&&!pe.altKey){const{nodes:ct,edges:ht}=se.getState();if(pe.key===" "){pe.preventDefault(),se.getState().toggleCollapse(wt);return}if(pe.key==="r"||pe.key==="R"){pe.preventDefault(),se.getState().rerunNode(wt,{});return}if(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(pe.key)){const Et=ht.filter(en=>!en.data?.isCrossLink);let un;if(pe.key==="ArrowUp")un=Et.find(en=>en.target===wt)?.source;else if(pe.key==="ArrowDown")un=Et.find(en=>en.source===wt)?.target;else{const en=Et.find(aa=>aa.target===wt),mn=en?Et.filter(aa=>aa.source===en.source).map(aa=>aa.target):ct.filter(aa=>!Et.some(Ma=>Ma.target===aa.id)).map(aa=>aa.id),Qa=mn.indexOf(wt);Qa!==-1&&mn.length>1&&(un=mn[(Qa+(pe.key==="ArrowRight"?1:mn.length-1))%mn.length])}if(un){pe.preventDefault(),d(un);const en=ct.find(mn=>mn.id===un);en&&Le(en,{zoom:1,duration:300})}return}}}if(pe.key==="Escape"){const Ae=pe.target;if(Ae.tagName==="INPUT"||Ae.tagName==="TEXTAREA"||Ae.isContentEditable)return;cn.length>1?h([]):wt&&d(null);return}if(pe.key==="Delete"||pe.key==="Backspace"){const Ae=pe.target;if(Ae.tagName==="INPUT"||Ae.tagName==="TEXTAREA"||Ae.isContentEditable)return;if(cn.length>1)pe.preventDefault(),oi({title:Ne("confirm.deleteNodesTitle"),message:ve(Ne("confirm.deleteNodes"),{n:cn.length}),confirmLabel:Ne("common.delete"),danger:!0}).then(Oe=>{Oe&&Lt(cn)});else{const Oe=t.filter(ct=>ct.selected).map(ct=>ct.id);Oe.length>0&&(pe.preventDefault(),Ca(Oe))}}}};return window.addEventListener("keydown",te),()=>window.removeEventListener("keydown",te)},[s,o,wt,cn,d,h,Lt,t,Ca,tt,Le]);const kt=()=>{S.trim()&&(r(S.trim(),{rolePrompt:H.trim()||void 0,initialAttachments:z.length>0?z:void 0}),C(""),G(""),P(!1),L([]))},qt=async te=>{for(const pe of Array.from(te))await X0(pe,{add:Ae=>L(Oe=>[...Oe,Ae]),update:(Ae,Oe)=>L(ct=>ct.map(ht=>ht.id===Ae?{...ht,...Oe}:ht))})},Qt=te=>{te.key==="Enter"&&!te.shiftKey&&!ar(te)&&(te.preventDefault(),kt())},nn=R.useCallback(({nodes:te})=>{const pe=te.map(Ae=>Ae.id);pe.length>1?h(pe):pe.length===1&&d(pe[0])},[d,h]),Jn=R.useMemo(()=>e.filter(te=>te.data.stepKind==="frame"),[e]),[Jt,In]=R.useState(!1),va=R.useRef(null);R.useEffect(()=>{if(!Jt)return;const te=pe=>{va.current?.contains(pe.target)||In(!1)};return window.addEventListener("mousedown",te),()=>window.removeEventListener("mousedown",te)},[Jt]);const[_a,an]=R.useState(!1),Bn=ce(te=>te.pluginUpdate),wa=ce(te=>!!te.harnessHost?.desktop),[Fn,Wn]=R.useState(0),pr=ce(te=>te.searchHitIds!==null),Xa=R.useRef(null);R.useEffect(()=>{if(!_a)return;const te=pe=>{Xa.current?.contains(pe.target)||an(!1)};return window.addEventListener("mousedown",te),()=>window.removeEventListener("mousedown",te)},[_a]);const $a=ce(te=>te.searchHitIds),Je=R.useMemo(()=>{if(!wt||cn.length>1||!e.some(Et=>Et.id===wt))return null;const te=K0(wt,e,t),pe=new Set;for(const Et of te.mainline)Et.id!==wt&&pe.add(Et.id);for(const Et of te.materials)pe.add(Et.id);for(const Et of te.references)pe.add(Et.source.id);const Ae=t.filter(Et=>!Et.data?.isCrossLink),Oe=zr(wt,e,Ae).visitedEdgeIds,ct=new Set(te.references.map(Et=>Et.edge.id)),ht=Ae.filter(Et=>Et.source===wt);return{ctx:pe,down:new Set(ht.map(Et=>Et.target)),pathEdgeIds:Oe,refEdgeIds:ct,downEdgeIds:new Set(ht.map(Et=>Et.id))}},[wt,cn,e,t]),le=R.useMemo(()=>{const te=e.filter(Oe=>Oe.data.stepKind==="frame").map((Oe,ct)=>({id:Oe.id,order:ct,area:(Oe.measured?.width??Oe.width??640)*(Oe.measured?.height??Oe.height??420)})).sort((Oe,ct)=>ct.area-Oe.area||Oe.order-ct.order),pe=new Map(te.map((Oe,ct)=>[Oe.id,ct-te.length]));let Ae=e.map(Oe=>Oe.data.stepKind==="frame"?{...Oe,zIndex:pe.get(Oe.id)??-1}:Oe);return w&&(Ae=Ae.map(Oe=>{const ct=Oe.data.stepKind,ht=Bm(ct)&&!t.some(Et=>Et.source===Oe.id||Et.target===Oe.id);return ct==="frame"||ht?{...Oe,hidden:!0}:Oe})),$a!==null&&(Ae=Ae.map(Oe=>$a.has(Oe.id)||Oe.data.stepKind==="frame"?{...Oe,className:"search-hit"}:Oe.className==="search-hit"?{...Oe,className:void 0}:Oe)),Je&&(Ae=Ae.map(Oe=>{const ct=Oe.id===wt?"target":Je.ctx.has(Oe.id)?"ctx":Je.down.has(Oe.id)?"down":Oe.data.stepKind==="frame"?void 0:"dim";return ct?{...Oe,className:[Oe.className,`focus-${ct}`].filter(Boolean).join(" "),...ct!=="dim"?{data:{...Oe.data,focusRole:ct}}:{}}:Oe})),Ae},[e,t,w,$a,Je,wt]),Ct=R.useMemo(()=>{const te=t.map(Oe=>{const ct=Oe.data?.isBranchFromSelection?{...Oe,animated:!1,style:{...Oe.style,strokeDasharray:void 0}}:Oe,ht=typeof ct.style?.stroke=="string"?pN[ct.style.stroke.toUpperCase()]:void 0,Et=ct.markerEnd&&typeof ct.markerEnd=="object"?ct.markerEnd:void 0,un=typeof Et?.color=="string"?pN[Et.color.toUpperCase()]:void 0;return!ht&&!un?ct:{...ct,...ht?{style:{...ct.style,stroke:Te[ht]}}:{},...un&&Et?{markerEnd:{...Et,color:Te[un]}}:{}}});if(Je)return te.map(Oe=>Je.pathEdgeIds.has(Oe.id)?{...Oe,className:"focus-e-path",style:{...Oe.style,stroke:Te.accent,strokeWidth:3.5,opacity:1},markerEnd:{type:"arrowclosed",...Oe.markerEnd&&typeof Oe.markerEnd=="object"?Oe.markerEnd:{},color:Te.accent},zIndex:10,data:{...Oe.data,focusRole:"path"}}:Je.refEdgeIds.has(Oe.id)?{...Oe,style:{...Oe.style,opacity:.9},zIndex:5,data:{...Oe.data,focusRole:"ref"}}:Je.downEdgeIds.has(Oe.id)?{...Oe,className:"focus-e-down",style:{...Oe.style,strokeWidth:2.5,opacity:.85},markerEnd:{type:"arrowclosed",...Oe.markerEnd&&typeof Oe.markerEnd=="object"?Oe.markerEnd:{}},zIndex:5,data:{...Oe.data,focusRole:"down"}}:{...Oe,style:{...Oe.style,strokeWidth:1.5,opacity:.2},zIndex:0});const pe=cn.length>1?cn:[];if(pe.length===0)return te;const{visitedEdgeIds:Ae}=zr(pe,e,t);return te.map(Oe=>Ae.has(Oe.id)?{...Oe,style:{...Oe.style,stroke:Te.trace,strokeWidth:3.5,opacity:1},markerEnd:{type:"arrowclosed",...Oe.markerEnd&&typeof Oe.markerEnd=="object"?Oe.markerEnd:{},color:Te.trace},zIndex:10}:{...Oe,style:{...Oe.style,strokeWidth:1.5,opacity:.2},zIndex:0})},[e,t,cn,Te,Je]);return R.useEffect(()=>{if(!et||!wt)return;const te=setTimeout(()=>{const pe=oe.current;if(!pe)return;const Ae=se.getState().nodes.find(un=>un.id===wt);if(!Ae)return;const Oe=pe.getViewport(),ct=Ae.measured?.width??Ae.width??480,ht=(Ae.position.x+ct)*Oe.zoom+Oe.x,Et=window.innerWidth-ce.getState().panelWidth-Yd-24;if(ht>Et){const un=(Ae.position.x+ct/2)*Oe.zoom+Oe.x;pe.setViewport({...Oe,x:Oe.x-(un-Et/2)},{duration:300})}},60);return()=>clearTimeout(te)},[et,wt]),l.jsxs("div",{className:"relative w-full h-full","data-searching":pr||void 0,children:[l.jsxs("div",{className:"relative h-full w-full",onDoubleClick:te=>{te.target.classList.contains("react-flow__pane")&&!tt&&Dt(ie({x:te.clientX,y:te.clientY}))},onDragOver:te=>{(te.dataTransfer.types.includes("application/thoughtdag-content")||te.dataTransfer.types.includes("Files"))&&(te.preventDefault(),te.dataTransfer.dropEffect="copy",!$&&!tt&&W(!0))},onDrop:te=>{if(Nt)return;const pe=te.target;if(!$&&!tt&&te.dataTransfer.files.length>0){te.preventDefault(),W(!1),_e(te.dataTransfer.files);return}const Ae=pe.closest?.(".react-flow__node"),Oe=Ae&&se.getState().nodes.find(Et=>Et.id===Ae.getAttribute("data-id"))?.data.stepKind==="frame";if(!pe.classList?.contains("react-flow__pane")&&!Oe)return;const ct=ie({x:te.clientX,y:te.clientY}),ht=te.dataTransfer.getData("application/thoughtdag-content");if(ht==="ask"){te.preventDefault(),Dt(ct);return}if(ht==="frame"){te.preventDefault(),Rt(ct);return}if(ht==="note"||ht==="file"){te.preventDefault(),gs(ht,ct);return}if(te.dataTransfer.files.length>0){te.preventDefault();const Et=lt(te.dataTransfer.files);if(Et.length===0)return;const un=gs("file",ct);Xd(un,Et)}},children:[l.jsxs(VB,{onInit:te=>{oe.current=te,RM.current=te;const pe=ce.getState().arrivalFocusNodeId;if(pe){ce.getState().setArrivalFocusNodeId(null);const Ae=se.getState().nodes.find(Oe=>Oe.id===pe);Ae&&window.setTimeout(()=>{te.setCenter(Ae.position.x+260,Ae.position.y+140,{zoom:.9,duration:400})},150)}},nodes:le,edges:Ct,onNodesChange:ot,onEdgesChange:Ht,onNodeDragStart:Vt,onNodeDrag:Ft,onNodeDragStop:ln,onConnect:xe,onConnectStart:Ve,onConnectEnd:gt,onEdgeContextMenu:na,onNodeContextMenu:sr,nodeTypes:Wue,edgeTypes:Vue,deleteKeyCode:null,fitView:!0,onlyRenderVisibleElements:!0,minZoom:.04,maxZoom:2,defaultEdgeOptions:{type:"smoothstep",animated:!1,style:{stroke:Te.accent,strokeWidth:2},markerEnd:{type:"arrowclosed",color:Te.accent,width:18,height:18}},snapToGrid:ye==="grid",snapGrid:[22,22],proOptions:{hideAttribution:!0},nodeDragThreshold:5,connectionRadius:40,selectionMode:du.Partial,selectionOnDrag:!Nt,nodesDraggable:!Nt,nodesConnectable:!Nt,panOnDrag:Nt?!0:[1,2],panOnScroll:v,zoomOnScroll:!v,zoomOnPinch:!0,zoomOnDoubleClick:!1,connectionLineStyle:{stroke:Te.accent,strokeDasharray:"8 4",strokeWidth:2},onSelectionChange:nn,onPaneClick:()=>{d(null),h([]),qa(null)},children:[ye==="grid"?l.jsxs(l.Fragment,{children:[l.jsx(gx,{id:"grid-fine",variant:Ps.Lines,gap:22,color:"var(--canvas-grid-fine)"}),l.jsx(gx,{id:"grid-major",variant:Ps.Lines,gap:110,color:"var(--canvas-grid-major)"})]}):l.jsx(gx,{variant:Ps.Dots,gap:24,size:1,color:"var(--canvas-dot)"}),l.jsx(Xue,{}),l.jsx(Kue,{panelShiftWidth:et?It:0}),l.jsx(Hue,{}),l.jsx(rH,{position:"bottom-left"}),e.length>0&&l.jsx(xH,{nodeColor:te=>{const pe=te.data;if(pe.archived)return Fe.archived;const Ae=pe.stepKind;return Ae==="note"?"#D97706":Ae==="file"||Ae==="link"?"#64748B":Array.isArray(pe.condensedFrom)&&pe.condensedFrom.length?"#8B7CF0":pe.isRoot?Te.accent:pe.isBranch?Te.warm:Fe.ordinary},maskColor:Fe.mask,style:{width:200,height:140},pannable:!0,zoomable:!0,position:"bottom-right"})]}),!$&&tt&&l.jsx("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:l.jsxs("div",{className:"text-center pointer-events-auto",children:[l.jsx("p",{className:"text-sm text-ink-muted mb-1 font-medium",children:b("paradigm.emptyTitle")}),l.jsx("p",{className:"text-xs text-ink-faint mb-4 max-w-sm leading-relaxed",children:b("paradigm.emptyHint")}),l.jsxs("div",{className:"flex items-center justify-center gap-2",children:[l.jsxs("button",{onClick:()=>nt("human"),className:"text-sm border-2 border-dashed border-warm/60 text-warm hover:bg-warm/10 px-4 py-2.5 rounded-xl transition-colors flex items-center gap-1.5",children:[l.jsx(Ol,{size:15,strokeWidth:1.75})," ",b("paradigm.addHuman")]}),l.jsxs("button",{onClick:()=>nt("prompt"),className:"text-sm border-2 border-dashed border-accent/50 text-accent hover:bg-accent/10 px-4 py-2.5 rounded-xl transition-colors flex items-center gap-1.5",children:[l.jsx(Qo,{size:15,strokeWidth:1.75})," ",b("paradigm.addPrompt")]})]})]})}),Nt&&!$&&l.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:l.jsx("div",{className:"text-center max-w-[420px] px-6",children:_t?l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"text-3xl mb-3",children:"🔗"}),l.jsx("div",{className:"text-sm font-semibold text-ink mb-1.5",children:b("viewer.loadError")}),l.jsx("p",{className:"text-xs text-ink-muted leading-relaxed",children:b("viewer.loadErrorHint")})]}):l.jsxs("div",{className:"flex items-center gap-2 text-sm text-ink-muted justify-center",children:[l.jsx(tn,{size:16,strokeWidth:1.75,className:"animate-spin text-accent"})," ",b("viewer.loading")]})})}),!$&&!tt&&!Nt&&l.jsxs("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none overflow-hidden",children:[l.jsxs("svg",{className:"absolute -left-10 top-[8%] w-[360px] h-[300px] opacity-[0.35] pointer-events-none",viewBox:"0 0 360 300","aria-hidden":!0,children:[l.jsx("path",{d:"M80 40 C80 90 80 90 80 130 M80 170 C80 210 80 210 80 250",stroke:at.line,strokeWidth:"2",fill:"none"}),l.jsx("path",{d:"M95 150 C150 150 150 90 205 88",stroke:at.line,strokeWidth:"2",strokeDasharray:"6 5",fill:"none"}),l.jsx("circle",{cx:"80",cy:"30",r:"7",fill:at.line}),l.jsx("circle",{cx:"80",cy:"150",r:"7",fill:"none",stroke:at.line,strokeWidth:"2.5"}),l.jsx("circle",{cx:"80",cy:"262",r:"7",fill:at.line}),l.jsx("circle",{cx:"218",cy:"88",r:"7",fill:at.line})]}),l.jsxs("svg",{className:"absolute right-[-30px] bottom-[10%] w-[320px] h-[280px] opacity-[0.35] pointer-events-none",viewBox:"0 0 320 280","aria-hidden":!0,children:[l.jsx("path",{d:"M240 30 C240 80 240 80 240 120 M240 160 C240 200 240 200 240 240",stroke:at.line,strokeWidth:"2",fill:"none"}),l.jsx("path",{d:"M225 140 C170 140 170 210 115 212",stroke:at.line,strokeWidth:"2",strokeDasharray:"6 5",fill:"none"}),l.jsx("circle",{cx:"240",cy:"20",r:"7",fill:at.line}),l.jsx("circle",{cx:"240",cy:"140",r:"7",fill:"none",stroke:at.line,strokeWidth:"2.5"}),l.jsx("circle",{cx:"240",cy:"252",r:"7",fill:at.line}),l.jsx("circle",{cx:"102",cy:"212",r:"7",fill:at.line})]}),l.jsxs("div",{className:"pointer-events-auto w-[560px] animate-fade-in relative",children:[l.jsxs("div",{className:"text-center mb-8",children:[l.jsxs("svg",{width:"52",height:"52",viewBox:"0 0 44 44",className:"mx-auto mb-4","aria-hidden":!0,children:[l.jsx("circle",{className:"dag-pop",style:{animationDelay:"0.05s"},cx:"22",cy:"7",r:"3.5",fill:at.accent}),l.jsx("line",{className:"dag-pop",style:{animationDelay:"0.2s"},x1:"22",y1:"11",x2:"22",y2:"19",stroke:at.accent,strokeWidth:"2",strokeLinecap:"round"}),l.jsx("circle",{className:"dag-pop",style:{animationDelay:"0.35s"},cx:"22",cy:"22",r:"3.5",fill:"none",stroke:at.accent,strokeWidth:"2.5"}),l.jsx("line",{className:"dag-pop",style:{animationDelay:"0.5s"},x1:"22",y1:"25",x2:"22",y2:"33",stroke:at.accent,strokeWidth:"2",strokeLinecap:"round"}),l.jsx("circle",{className:"dag-pop",style:{animationDelay:"0.65s"},cx:"22",cy:"37",r:"3.5",fill:at.accent,opacity:"0.35"}),l.jsx("line",{className:"dag-pop",style:{animationDelay:"0.8s"},x1:"25.5",y1:"23.5",x2:"33",y2:"28.5",stroke:at.warm,strokeWidth:"2",strokeLinecap:"round",strokeDasharray:"3 3"}),l.jsx("circle",{className:"dag-pop",style:{animationDelay:"0.95s"},cx:"36",cy:"30",r:"3.5",fill:at.warm})]}),l.jsx("h1",{className:"text-4xl font-semibold tracking-tight text-ink mb-2.5",children:"ThoughtDAG"}),l.jsx("p",{className:"text-sm text-ink-muted",children:b("landing.tagline")}),l.jsx("p",{className:"text-xs text-ink-muted mt-1.5 font-medium",children:b("landing.mechanism")})]}),l.jsxs("div",{className:"bg-card border border-line rounded-xl px-5 py-4 shadow-lg transition-all focus-within:border-accent/50 focus-within:shadow-xl",children:[l.jsx("textarea",{value:S,onChange:te=>C(te.target.value),onKeyDown:Qt,onPaste:te=>{if(te.clipboardData.getData("text/plain").trim())return;const pe=Array.from(te.clipboardData.items).filter(Ae=>Ae.kind==="file").map(Ae=>Ae.getAsFile()).filter(Boolean);pe.length&&qt(pe)},placeholder:b("landing.placeholder"),className:"w-full bg-transparent text-ink text-sm leading-relaxed resize-none focus:outline-none placeholder-ink-faint",rows:3,autoFocus:!0}),z.length>0&&l.jsx("div",{className:"flex flex-wrap gap-2 mt-2 pb-1",children:z.map(te=>l.jsxs("div",{className:"flex items-center gap-1.5 bg-wash rounded-lg px-2.5 py-1.5 group",children:[te.thumbnailUrl?l.jsx("img",{src:te.thumbnailUrl,className:"w-6 h-6 rounded object-cover",alt:te.name}):l.jsx("span",{className:"text-xs",children:l.jsx(zs,{size:16,strokeWidth:1.75})}),l.jsx("span",{className:"text-xs text-ink-muted max-w-[100px] truncate",children:te.name}),te.isExtracting&&l.jsx("span",{className:"text-2xs text-accent",children:l.jsx(tn,{className:"animate-spin",size:12,strokeWidth:1.75})}),te.numPages!=null&&l.jsxs("span",{className:"text-2xs text-ink-faint",children:[te.numPages,"p"]}),l.jsx("button",{onClick:()=>L(pe=>pe.filter(Ae=>Ae.id!==te.id)),className:"text-ink-faint hover:text-red-500 text-xs opacity-0 group-hover:opacity-100 transition-opacity",children:l.jsx(on,{size:14,strokeWidth:1.75})})]},te.id))}),D&&l.jsxs("div",{className:"space-y-1 mt-2",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsx("span",{className:"text-xs text-ink-muted font-medium",children:b("landing.roleLabel")}),l.jsx("button",{onClick:()=>{P(!1),G("")},className:"text-xs text-ink-faint hover:text-ink-muted",children:l.jsx(on,{size:14,strokeWidth:1.75})})]}),l.jsx("textarea",{value:H,onChange:te=>G(te.target.value),placeholder:b("landing.rolePlaceholder"),className:"w-full text-xs border border-line rounded-lg px-3 py-2 focus:outline-none focus:ring-1 focus:ring-accent bg-surface resize-none leading-relaxed",rows:2,autoFocus:!0}),l.jsx(AM,{onPick:G})]}),l.jsxs("div",{className:"flex items-center justify-end mt-2 gap-2",children:[l.jsx(Pl,{}),l.jsx("button",{onClick:()=>P(!D),title:b("landing.roleTrayTitle"),className:`rounded-full w-8 h-8 flex items-center justify-center transition-colors shrink-0 ${D||H?"text-accent bg-accent/10 hover:bg-accent/20":"text-ink-faint hover:text-ink-muted hover:bg-line"}`,children:l.jsx(kF,{size:16,strokeWidth:1.75})}),l.jsx("button",{onClick:()=>X.current?.click(),className:"text-ink-faint hover:text-accent hover:bg-wash rounded-xl px-3 py-2 transition-colors text-sm",title:b("landing.attach"),children:l.jsx(Bs,{size:16,strokeWidth:1.75})}),l.jsx("input",{ref:X,type:"file",multiple:!0,accept:w0,className:"hidden",onChange:te=>{qt(te.target.files||[]),te.target.value=""}}),l.jsx("button",{onClick:kt,disabled:!S.trim()||z.some(te=>te.isExtracting),className:"bg-accent hover:bg-accent-strong disabled:opacity-30 disabled:cursor-not-allowed text-white text-sm px-5 py-2 rounded-xl transition-all",children:z.some(te=>te.isExtracting)?b("landing.extracting"):b("landing.send")})]})]}),l.jsxs("div",{onClick:()=>B.current?.click(),className:`mt-3 border-2 border-dashed rounded-xl px-5 py-3.5 cursor-pointer transition-all text-center bg-card/60 backdrop-blur ${q?"border-accent bg-accent/5 ring-2 ring-accent/20":"border-line hover:border-accent/40 hover:bg-accent/5"}`,children:[l.jsxs("div",{className:"flex items-center justify-center gap-2 text-sm text-ink-muted font-medium",children:[l.jsx(Wl,{size:15,strokeWidth:1.75,className:"text-accent"})," ",b("landing.docStart")]}),l.jsx("p",{className:"text-2xs text-ink-faint mt-1.5",children:b("landing.docFormats")}),l.jsx("p",{className:"text-2xs text-ink-faint mt-0.5",children:b("landing.docPrivacy")})]}),!!window.desktopSessions&&l.jsxs("button",{onClick:()=>U(!0),className:"w-full mt-3 bg-card/60 backdrop-blur border border-line rounded-xl px-5 py-3.5 hover:border-accent/40 hover:bg-accent/5 transition-all text-center","data-landing-atlas":!0,children:[l.jsxs("div",{className:"flex items-center justify-center gap-2 text-sm text-ink-muted font-medium",children:[l.jsx(GH,{size:15,strokeWidth:1.75,className:"text-accent shrink-0"}),l.jsx("span",{children:b("landing.atlasStart")}),l.jsx(FH,{size:13,strokeWidth:1.75,className:"text-accent shrink-0"})]}),l.jsx("p",{className:"text-2xs text-ink-faint mt-1.5",children:b("landing.atlasDesc")})]}),l.jsx("input",{ref:B,type:"file",multiple:!0,accept:w0,className:"hidden",onChange:te=>{_e(te.target.files||[]),te.target.value=""}}),Y&&l.jsx(Qv,{onClose:()=>U(!1),onSwitched:()=>{U(!1),st()}}),(!xt||(xt.models?.length??0)===0)&&l.jsxs("div",{className:"mt-3 bg-card/60 backdrop-blur border border-line rounded-xl px-5 py-3.5 text-center","data-quick-connect":!0,children:[l.jsxs("div",{className:"flex items-center justify-center gap-2 text-sm text-ink-muted font-medium",children:[l.jsx(b0,{size:15,strokeWidth:1.75,className:"text-accent shrink-0"})," ",b("landing.quickTitle")]}),l.jsx("p",{className:"text-2xs text-ink-faint mt-1.5",children:b("landing.quickDesc")}),l.jsxs("div",{className:"mt-2.5 flex items-center justify-center flex-wrap gap-2",children:[Ee==="zh"&&l.jsx("button",{onClick:()=>{ce.getState().setApiKeyPresetHint("zhipu"),ce.getState().setApiKeyModalOpen(!0)},className:"text-2xs bg-accent/10 text-accent hover:bg-accent/20 font-medium px-3 py-1.5 rounded-lg transition-colors shrink-0","data-quick-zhipu":!0,children:b("landing.quickZhipu")}),l.jsx("button",{onClick:()=>{$M()},className:"text-2xs bg-accent/10 text-accent hover:bg-accent/20 font-medium px-3 py-1.5 rounded-lg transition-colors shrink-0","data-quick-primary":!0,children:b("landing.quickOpenRouter")}),l.jsx("button",{onClick:()=>ce.getState().setApiKeyModalOpen(!0),className:"text-2xs text-ink-muted hover:text-ink hover:bg-wash font-medium px-3 py-1.5 rounded-lg transition-colors shrink-0",children:b("landing.quickOther")})]}),l.jsx("button",{onClick:()=>ce.getState().setApiKeyModalOpen(!0),className:"mt-2 mx-auto text-2xs text-ink-faint hover:text-accent transition-colors block","data-quick-subs":!0,children:b("landing.quickSubs")})]}),l.jsx("div",{className:"grid grid-cols-3 gap-3 mt-6",children:[{icon:ii,title:"landing.feature1.title",desc:"landing.feature1.desc"},{icon:nE,title:"landing.feature2.title",desc:"landing.feature2.desc"},{icon:JA,title:"landing.feature3.title",desc:"landing.feature3.desc"}].map(({icon:te,title:pe,desc:Ae})=>l.jsxs("div",{className:"bg-card/60 backdrop-blur border border-line rounded-xl px-4 py-3.5",children:[l.jsx(te,{size:16,strokeWidth:1.75,className:"text-accent mb-2"}),l.jsx("h3",{className:"text-xs font-semibold text-ink mb-1",children:b(pe)}),l.jsx("p",{className:"text-2xs text-ink-faint leading-relaxed",children:b(Ae)})]},pe))}),l.jsxs("div",{className:"text-center mt-6 flex items-center justify-center gap-5",children:[l.jsxs("button",{onClick:Ke,className:"text-xs text-accent hover:text-accent-strong font-medium transition-colors inline-flex items-center gap-1.5",children:[l.jsx(nE,{size:14,strokeWidth:1.75})," ",b("landing.loadExample")]}),l.jsxs("button",{onClick:()=>y(!0),className:"text-xs text-ink-muted hover:text-accent transition-colors inline-flex items-center gap-1.5",children:[l.jsx(Q5,{size:14,strokeWidth:1.75})," ",b("landing.howItWorks")]})]})]})]}),!Nt&&l.jsx(Mce,{onSwitched:st}),($||tt)&&!Nt&&l.jsxs("div",{className:"absolute top-[38%] -translate-y-1/2 left-4 z-10 flex flex-col gap-1.5 bg-card/90 backdrop-blur border border-line rounded-xl p-1.5 shadow-sm",children:[!tt&&l.jsx("button",{onClick:()=>Dt(ie(null)),draggable:!0,onDragStart:te=>{te.dataTransfer.setData("application/thoughtdag-content","ask"),te.dataTransfer.effectAllowed="copy"},title:b("palette.askTitle"),className:"w-9 h-9 rounded-lg flex items-center justify-center text-accent hover:bg-accent/10 transition-colors cursor-grab",children:l.jsx(Ol,{size:17,strokeWidth:1.75})}),l.jsx("button",{onPointerDown:te=>Qe(te,pe=>gs("note",ie(pe))),title:b("palette.noteTitle"),className:"w-9 h-9 rounded-lg flex items-center justify-center text-amber-600 hover:bg-amber-500/10 transition-colors",children:l.jsx(ui,{size:17,strokeWidth:1.75})}),l.jsx("button",{onPointerDown:te=>Qe(te,pe=>gs("file",ie(pe))),title:b("palette.fileTitle"),className:"w-9 h-9 rounded-lg flex items-center justify-center text-ink-muted hover:bg-wash transition-colors",children:l.jsx(Bs,{size:17,strokeWidth:1.75})}),l.jsx("button",{onPointerDown:te=>Qe(te,pe=>Rt(ie(pe))),title:b("palette.frameTitle"),className:"w-9 h-9 rounded-lg flex items-center justify-center text-ink-muted hover:bg-wash transition-colors",children:l.jsx(Yb,{size:17,strokeWidth:1.75})})]}),Nt&&l.jsxs("div",{className:"absolute top-4 z-10 flex gap-1.5 items-center transition-[right] duration-200",style:{right:et?It+Yd+12:16},"data-top-toolbar":!0,children:[l.jsxs("span",{className:"bg-card/90 backdrop-blur border border-line rounded-lg h-8 px-3 flex items-center gap-1.5 shadow-sm text-ink-muted text-xs font-medium","data-viewer-badge":!0,children:[l.jsx(g0,{size:14,strokeWidth:1.75})," ",b("viewer.badge")]}),l.jsx("button",{onClick:()=>O(!0),className:"bg-card/90 backdrop-blur border border-line rounded-lg w-8 h-8 flex items-center justify-center shadow-sm hover:bg-wash transition-colors text-ink-muted hover:text-accent",title:b("search.entryTitle"),"data-search-entry":!0,children:l.jsx(y0,{size:15,strokeWidth:1.75})}),l.jsx(YN,{}),l.jsx("button",{onClick:()=>gy(),className:"bg-card/90 backdrop-blur border border-line rounded-lg w-8 h-8 flex items-center justify-center shadow-sm hover:bg-wash transition-colors text-ink-muted hover:text-accent",title:b("viewer.downloadJson"),children:l.jsx(Ll,{size:15,strokeWidth:1.75})}),l.jsx("a",{href:"https://github.com/chenxiachan/thoughtdag",target:"_blank",rel:"noreferrer",className:"bg-ink text-white rounded-lg h-8 px-3 flex items-center gap-1.5 shadow-sm hover:bg-ink/85 transition-colors text-xs font-medium",children:b("viewer.openApp")})]}),!Nt&&l.jsxs("div",{className:"absolute top-4 z-10 flex gap-1.5 items-center transition-[right] duration-200",style:{right:et?It+Yd+12:16},"data-top-toolbar":!0,children:[tt&&l.jsxs(l.Fragment,{children:[l.jsxs("button",{onClick:()=>nt("human"),className:"bg-card/90 backdrop-blur border border-warm/40 rounded-lg h-8 px-3 flex items-center gap-1.5 shadow-sm hover:bg-warm/10 transition-colors text-warm text-xs font-medium",children:[l.jsx(Ol,{size:14,strokeWidth:1.75})," ",b("paradigm.addHuman")]}),l.jsxs("button",{onClick:()=>nt("prompt"),className:"bg-card/90 backdrop-blur border border-accent/40 rounded-lg h-8 px-3 flex items-center gap-1.5 shadow-sm hover:bg-accent/10 transition-colors text-accent text-xs font-medium",children:[l.jsx(Qo,{size:14,strokeWidth:1.75})," ",b("paradigm.addPrompt")]}),l.jsxs("button",{onClick:()=>{Be()},title:b("paradigm.instantiateTitle"),className:"bg-ink text-white rounded-lg h-8 px-3 flex items-center gap-1.5 shadow-sm hover:bg-ink/85 transition-colors text-xs font-medium",children:["▶ ",b("paradigm.instantiate")]})]}),!tt&&l.jsx(Due,{}),!tt&&l.jsx(IM,{}),!$&&l.jsx("button",{onClick:()=>ce.getState().setApiKeyModalOpen(!0),className:"bg-card/90 backdrop-blur border border-line rounded-lg w-8 h-8 flex items-center justify-center shadow-sm hover:bg-wash transition-colors text-ink-faint hover:text-accent",title:b("apikey.entryTitle"),"data-apikey-entry":!0,children:l.jsx(b0,{size:15,strokeWidth:1.75})}),bt>0&&!tt&&l.jsxs("button",{onClick:()=>{const{nodes:te,edges:pe}=se.getState(),Oe=Qr(se.getState()).reduce((ct,ht)=>{const Et=te.map(mn=>mn.id===ht?{...mn,data:{...mn.data,question:"",response:""}}:mn),{layerTokens:un}=vr(ht,Et,pe),en=te.find(mn=>mn.id===ht)?.data.question??"";return ct+un.material+un.reference+un.chain+_n(en)},0);oi({title:b("replay.confirmTitle"),message:ve(b("replay.confirmMsg"),{n:bt,tok:Oe.toLocaleString()}),confirmLabel:b("replay.confirmBtn")}).then(ct=>{ct&&se.getState().replayStale()})},className:"bg-amber-500/10 backdrop-blur border border-amber-500/40 rounded-lg h-8 px-3 flex items-center gap-1.5 shadow-sm hover:bg-amber-500/20 transition-colors text-amber-600 text-xs font-medium",title:b("replay.chipTitle"),children:[l.jsx(lU,{size:14,strokeWidth:1.75})," ",bt]}),$&&Jn.length>0&&l.jsxs("div",{ref:va,className:"relative",children:[l.jsx("button",{onClick:()=>In(te=>!te),className:`bg-card/90 backdrop-blur border rounded-lg w-8 h-8 flex items-center justify-center shadow-sm transition-colors ${Jt?"border-accent/40 text-accent":"border-line text-ink-faint hover:bg-wash"}`,title:b("toolbar.frames"),children:l.jsx(Yb,{size:15,strokeWidth:1.75})}),Jt&&l.jsx("div",{className:"absolute right-0 top-full mt-1.5 bg-card border border-line rounded-xl shadow-lg py-1 w-[230px] max-h-[320px] overflow-y-auto z-30 animate-fade-in",children:Jn.map(te=>l.jsxs("button",{onClick:()=>{In(!1),oe.current?.fitBounds({x:te.position.x,y:te.position.y,width:te.width??640,height:te.height??420},{duration:400,padding:.15})},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2",children:[l.jsx("span",{className:`w-2.5 h-2.5 rounded-sm shrink-0 ${(Gd[te.data.frameColor??"gray"]??Gd.gray).dot}`}),l.jsx("span",{className:"truncate",children:te.data.question||b("frame.untitled")})]},te.id))})]}),$&&l.jsx("button",{onClick:()=>A(te=>!te),className:`bg-card/90 backdrop-blur border border-line rounded-lg w-8 h-8 flex items-center justify-center shadow-sm hover:bg-wash transition-colors ${_?"text-accent":"text-ink-faint hover:text-accent"}`,title:b("chat.entryTitle"),"data-chat-entry":!0,children:l.jsx(Ol,{size:15,strokeWidth:1.75})}),$&&l.jsx("button",{onClick:()=>O(!0),className:"bg-card/90 backdrop-blur border border-line rounded-lg w-8 h-8 flex items-center justify-center shadow-sm hover:bg-wash transition-colors text-ink-faint hover:text-accent",title:b("search.entryTitle"),"data-search-entry":!0,children:l.jsx(y0,{size:15,strokeWidth:1.75})}),l.jsx(YN,{}),$&&!tt&&l.jsx(tce,{showTrigger:!1,openPing:Fn,onLocate:te=>{const pe=se.getState().nodes.find(Ae=>Ae.id===te);pe&&(d(te),Le(pe,{zoom:1}))}}),De&&!Nt&&l.jsxs("button",{onClick:()=>ce.getState().setCondenseDialogOpen(!0),className:"bg-card/90 backdrop-blur border border-accent/50 rounded-lg h-8 px-2 flex items-center justify-center gap-1.5 shadow-sm hover:bg-wash transition-colors text-accent",title:ve(b("condense.entryBuilding"),{i:String(ze.current),n:String(ze.total)}),"data-condense-entry":!0,children:[l.jsx(tn,{size:14,strokeWidth:1.75,className:"animate-spin"}),l.jsxs("span",{className:"text-2xs font-mono",children:[ze.current,"/",ze.total]})]}),Xp&&l.jsx("button",{onClick:()=>ce.getState().setBackupDialogOpen(!0),className:"bg-card/90 backdrop-blur border border-line rounded-lg w-8 h-8 flex items-center justify-center shadow-sm hover:bg-wash transition-colors text-ink-muted hover:text-accent",title:b("backup.dialogTitle"),"data-backup-entry":!0,children:l.jsx(WA,{size:15,strokeWidth:1.75})}),l.jsxs("div",{ref:Xa,className:"relative",children:[l.jsx("button",{onClick:()=>an(te=>!te),className:`bg-card/90 backdrop-blur border rounded-lg w-8 h-8 flex items-center justify-center shadow-sm transition-colors ${_a?"border-accent/40 text-accent":"border-line text-ink-faint hover:bg-wash"}`,title:b("toolbar.more"),"data-toolbar-more":!0,children:l.jsx(qA,{size:15,strokeWidth:1.75})}),_a&&l.jsxs("div",{className:"absolute right-0 top-full mt-1.5 bg-card border border-line rounded-xl shadow-lg py-1 w-[220px] z-30 animate-fade-in",children:[$&&l.jsxs("button",{onClick:()=>{an(!1),E(!w)},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5",title:b(w?"toolbar.showAnnotations":"toolbar.hideAnnotations"),children:[l.jsx(ui,{size:14,strokeWidth:1.75,className:`shrink-0 ${w?"text-accent":"text-ink-faint"}`})," ",b(w?"toolbar.menuAnnotationsShow":"toolbar.menuAnnotationsHide")]}),l.jsxs("button",{onClick:()=>{an(!1),N(!v)},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5",title:b("toolbar.wheelPansTitle"),"aria-pressed":v,"data-wheel-pans":!0,children:[l.jsx($F,{size:14,strokeWidth:1.75,className:`shrink-0 ${v?"text-accent":"text-ink-faint"}`})," ",l.jsx("span",{className:"flex-1",children:b("toolbar.menuWheelPans")}),v&&l.jsx("span",{className:"text-accent",children:"✓"})]}),$&&l.jsxs("button",{onClick:()=>{an(!1),oi({title:b("confirm.relayoutTitle"),message:b("confirm.relayoutMsg"),confirmLabel:b("toolbar.relayout")}).then(te=>{te&&(x(),setTimeout(()=>oe.current?.fitView({duration:400,padding:.15}),50))})},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5",children:[l.jsx(rU,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("toolbar.relayout")]}),K>0&&l.jsxs("button",{onClick:()=>{an(!1),ce.getState().setHighlightsOverviewOpen(!0)},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5",title:b("hlov.entryTitle"),"data-hlov-entry":!0,children:[l.jsx(x0,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",ve(b("hlov.entry"),{n:K})]}),J>0&&l.jsxs("button",{onClick:()=>{an(!1),ce.getState().setMaterialsOverviewOpen(!0)},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5",title:b("matov.entryTitle"),"data-matov-entry":!0,children:[l.jsx(Bs,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",ve(b("matov.entry"),{n:J})]}),$&&l.jsx("div",{className:"border-t border-line/60 my-1"}),$&&!tt&&!Nt&&l.jsxs("button",{onClick:()=>{an(!1),ce.getState().setCondenseDialogOpen(!0)},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5",title:b("condense.entryTitle"),children:[l.jsx(Sp,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("condense.title"),"…"]}),$&&!tt&&l.jsxs("button",{onClick:()=>{an(!1),Wn(te=>te+1)},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5",title:b("toolbar.diagnose"),"data-menu-diagnose":!0,children:[l.jsx(e8,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("toolbar.menuDiagnose")]}),$&&!tt&&l.jsxs("button",{onClick:()=>{an(!1),(async()=>{const{nodes:te,edges:pe}=se.getState(),{confirmIfSensitive:Ae}=await pt(async()=>{const{confirmIfSensitive:ct}=await import("./sensitive-scan-DBS7362r.js");return{confirmIfSensitive:ct}},[]);if(!await Ae(te))return;const Oe=await Wq(te,pe);await navigator.clipboard.writeText(Oe).catch(()=>{}),ce.getState().setShareDialogUrl(Oe)})()},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5","data-share-link":!0,title:b("viewer.shareTitle"),children:[l.jsx(PU,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("toolbar.menuShare")]}),$&&l.jsxs("button",{onClick:()=>{an(!1),tt?wG():gy()},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5","data-menu-export":!0,children:[l.jsx(Ll,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b(tt?"paradigm.exportParadigm":"switcher.exportBackup")]}),Z&&l.jsxs("button",{onClick:()=>{an(!1),TG()},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5",title:b("toolbar.exportEventsTitle"),children:[l.jsx(zs,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("toolbar.exportEvents")]}),$&&l.jsx("div",{className:"border-t border-line/60 my-1"}),l.jsxs("div",{className:"px-3 pt-2 pb-1","data-appearance-lighting":!0,children:[l.jsx("div",{className:"text-2xs text-ink-faint mb-1.5",children:b("appearance.lighting")}),l.jsx("div",{className:"flex rounded-lg border border-line overflow-hidden text-2xs",children:[["light",b("appearance.light")],["dark",b("appearance.dark")],["system",b("appearance.system")]].map(([te,pe],Ae)=>l.jsx("button",{onClick:()=>qi.getState().setLighting(te),className:`flex-1 px-1 py-1.5 transition-colors ${Ae>0?"border-l border-line":""} ${ae===te?"bg-accent/10 text-accent font-medium":"text-ink-muted hover:bg-wash"}`,children:pe},te))})]}),l.jsxs("div",{className:"px-3 pt-1 pb-2","data-appearance-paper":!0,children:[l.jsx("div",{className:"text-2xs text-ink-faint mb-1.5",children:b("appearance.paper")}),l.jsx("div",{className:"flex rounded-lg border border-line overflow-hidden text-2xs",children:[["plain",b("appearance.plain")],["grid",b("appearance.grid")]].map(([te,pe],Ae)=>l.jsx("button",{onClick:()=>qi.getState().setPaper(te),className:`flex-1 px-1 py-1.5 transition-colors ${Ae>0?"border-l border-line":""} ${ye===te?"bg-accent/10 text-accent font-medium":"text-ink-muted hover:bg-wash"}`,children:pe},te))})]}),l.jsx("div",{className:"border-t border-line/60 my-1"}),l.jsxs("button",{onClick:()=>{an(!1),ce.getState().setMemoryManagerOpen(!0)},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5",title:b("memory.entryTitle"),children:[l.jsx(KH,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("memory.managerTitle")]}),l.jsxs("button",{onClick:()=>{an(!1),y(!0)},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5",children:[l.jsx(Q5,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("landing.howItWorks")]}),Bn&&l.jsxs("button",{onClick:()=>{an(!1);const te=wa?`dsh-thoughtdag@${Bn.latest}`:Xy(Bn.latest);navigator.clipboard.writeText(te).then(()=>We("success",b(wa?"plugin.updateCopiedDesktop":"plugin.updateCopied")))},className:"w-full text-left px-3 py-2 text-xs text-accent hover:bg-wash transition-colors flex items-center gap-2.5",title:wa?ve(b("plugin.updateHintDesktop"),{pkg:`dsh-thoughtdag@${Bn.latest}`}):ve(b("plugin.updateHint"),{cmd:Xy(Bn.latest)}),"data-plugin-update":!0,children:[l.jsx(Ll,{size:14,strokeWidth:1.75,className:"shrink-0"})," ",ve(b("plugin.updateAvailable"),{v:Bn.latest})]}),l.jsxs("button",{onClick:()=>{an(!1),ce.getState().setReleaseNotesOpen(!0)},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5","data-open-release-notes":!0,children:[l.jsx(Ep,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("releaseNotes.entry")]})]})]}),l.jsx("button",{onClick:s,disabled:p<=0,className:"bg-card/90 backdrop-blur border border-line rounded-lg w-8 h-8 flex items-center justify-center shadow-sm hover:bg-wash transition-colors disabled:opacity-20 disabled:cursor-not-allowed",title:b("canvas.undo"),children:l.jsx(a8,{size:16,strokeWidth:1.75})}),l.jsx("button",{onClick:o,disabled:p>=m.length-1,className:"bg-card/90 backdrop-blur border border-line rounded-lg w-8 h-8 flex items-center justify-center shadow-sm hover:bg-wash transition-colors disabled:opacity-20 disabled:cursor-not-allowed",title:b("canvas.redo"),children:l.jsx(TU,{size:16,strokeWidth:1.75})})]}),St&&!Nt&&l.jsx(jle,{}),!Nt&&l.jsx(Jle,{open:_,onClose:()=>A(!1),onLocate:te=>{const pe=se.getState().nodes.find(Ae=>Ae.id===te);pe&&(d(te),Le(pe,{zoom:1}))}}),l.jsx(Vle,{open:I,onClose:()=>O(!1),onLocate:te=>{const pe=se.getState().nodes.find(Ae=>Ae.id===te);pe&&(d(te),Le(pe,{zoom:1}))}}),Dn&&l.jsx(Ple,{x:Dn.x,y:Dn.y,nodeId:Dn.nodeId,onClose:()=>qa(null)}),l.jsx(Hle,{onLocate:te=>{const pe=se.getState().nodes.find(Ae=>Ae.id===te);pe&&(d(te),Le(pe,{zoom:1}))}}),l.jsx(que,{onLocate:te=>{const pe=se.getState().nodes.find(Ae=>Ae.id===te);pe&&(d(te),Le(pe,{zoom:1}))}}),l.jsx(zle,{onLocate:te=>{const pe=se.getState().nodes.find(Ae=>Ae.id===te);pe&&(d(te),Le(pe,{zoom:1}))}}),$t&&l.jsx("div",{className:"fixed z-50 bg-card border border-line rounded-xl shadow-lg py-1 min-w-[120px]",style:{left:$t.x,top:$t.y},children:l.jsxs("button",{onClick:()=>oa($t.edgeId),className:"w-full text-left px-4 py-2 text-sm text-red-600 hover:bg-red-50 transition-colors flex items-center gap-1.5",children:[l.jsx(rr,{size:14,strokeWidth:1.75}),b("canvas.deleteEdge")]})})]}),l.jsx(Sue,{onFocusSegment:te=>{const pe=oe.current,Ae=se.getState().nodes.filter(mn=>te.includes(mn.id));if(!pe||Ae.length===0)return;const Oe=Ae.map(mn=>mn.position.x),ct=Ae.map(mn=>mn.position.y),ht=Math.min(...Oe),Et=Math.min(...ct),un=Math.max(...Oe)+520-ht,en=Math.max(...ct)+240-Et;pe.fitBounds({x:ht,y:Et,width:un+700,height:en},{duration:350,padding:.15})}}),et&&l.jsx(Ile,{onFocusNode:te=>{const pe=e.find(Ae=>Ae.id===te);pe&&Le(pe,{duration:300})}}),l.jsx(hce,{onLocate:te=>{const pe=se.getState().nodes.find(Ae=>Ae.id===te);pe&&(d(te),Le(pe,{zoom:1}))}})]})}function Kue({panelShiftWidth:e}){const t=Z0(),n=Tt(),a=Zl(),r=se(d=>d.nodes.length),s=se(d=>d.nodes),o=R.useMemo(()=>{let d=null,h="";for(const m of s){if(m.data.stepKind&&m.data.stepKind!=="human"&&m.data.stepKind!=="prompt")continue;const p=[m.data.lastGeneratedAt,m.data.askedAt,m.data.createdAt,...m.data.editedAts??[]].filter(Boolean).sort().pop();p&&p>h&&(h=p,d=m)}return d?{node:d,at:h}:null},[s]);if(Nt||t==="work"||r<2)return null;const u=()=>{if(!o)return;ce.getState().setBeaconNodeId(null);const{node:d}=o;a.setCenter(d.position.x+260,d.position.y+110,{zoom:1,duration:1100}),window.setTimeout(()=>{se.getState().setSelectedNodeId(d.id),ce.getState().setPanelOpen(!0),window.setTimeout(()=>{a.setCenter(d.position.x+260+cp(d.id)/2,d.position.y+110,{zoom:1,duration:300})},60)},1150),window.setTimeout(()=>{We("success",n("continue.arrived"),12e3,{label:n("continue.summarize"),run:()=>{jM(d.id)}})},1550)};return l.jsxs("div",{className:"absolute bottom-6 z-10 flex items-center gap-2 -translate-x-1/2 transition-[left] duration-300",style:{left:`calc((100% - ${e}px) / 2)`},"data-map-dock":!0,children:[l.jsxs("button",{onClick:()=>ce.getState().setThoughtMapOpen(!0),"data-tmap-pill":!0,className:"flex items-center gap-2 bg-card/95 backdrop-blur border border-line-strong rounded-full px-5 py-2.5 text-sm text-ink shadow-lg hover:border-accent/40 hover:text-accent transition-colors",children:[l.jsx(p2,{size:16,strokeWidth:1.75})," ",n("tmap.export")]}),o&&l.jsxs("button",{onClick:u,onMouseEnter:()=>ce.getState().setBeaconNodeId(o.node.id),onMouseLeave:()=>ce.getState().setBeaconNodeId(null),title:n("continue.buttonTitle"),"data-continue-pill":!0,className:"flex items-center gap-2 bg-accent text-white rounded-full px-5 py-2.5 text-sm shadow-lg hover:bg-accent-strong transition-colors",children:[l.jsx(_U,{size:16,strokeWidth:1.75})," ",n("continue.button")]})]})}function Xue(){const e=Z0(),t=fn(n=>n.transform[2]);return R.useEffect(()=>{document.querySelector(".react-flow")?.setAttribute("data-zoom-tier",e)},[e]),R.useEffect(()=>{document.querySelector(".react-flow")?.style.setProperty("--tdag-zoom",String(t))},[t]),null}Qoe();const ew="/thoughtdag/api";window.desktopSessions||j8(ew);pt(()=>Promise.resolve().then(()=>jue),void 0).then(e=>e.bootPluginUpdateCheck(ew));if(!window.desktopAgents){const e=ew;pt(()=>import("./http-bridge-k3v0JK5X.js"),[]).then(async t=>{await t.installAgentsHttpBridge(e)&&window.dispatchEvent(new CustomEvent("td:agents-ready"))})}Nt?Gq():($7(),navigator.storage?.persist&&navigator.storage.persist(),pt(()=>Promise.resolve().then(()=>fue),void 0).then(e=>e.bootAutoBackup()));pt(()=>import("./update-check-CRxOAqxm.js"),[]).then(e=>e.bootUpdateCheck());window.addEventListener("hashchange",()=>{window.location.hash.startsWith("#view=")!==Nt&&window.location.reload()});fD.createRoot(document.getElementById("root")).render(l.jsx(R.StrictMode,{children:l.jsx(Gue,{})}));export{L0 as A,yr as B,sG as C,Jue as D,Z7 as E,Na as F,q$ as I,pt as _,Ne as a,se as b,sn as c,Vi as d,W7 as e,ve as f,Wi as g,Pr as h,Nt as i,Tu as j,Ip as k,my as l,uG as m,En as n,lG as o,ks as p,Z2 as q,cG as r,el as s,We as t,ce as u,oi as v,ede as w,Qr as x,Zue as y,Que as z};
944
+ Write the JOURNEY of this thinking as one flowing paragraph a reader absorbs in twenty seconds: where it started, what got ruled out, where it turned, where it landed, what remains open. Only the turns that mattered — do not enumerate every step. Hard limit: 250 characters for CJK languages, 500 characters otherwise. Write in ${n==="zh"?"Chinese":"English"} (the reader's interface language), even if the takeaway lines mix languages. Never use dash characters (—, –, -); use commas, colons or full stops. Output only the paragraph.`}])).trim(),fp:a,at:new Date().toISOString(),lang:n};return Qy.set(`${n}:${a}`,x),x}function que({onLocate:e}){const t=ce(z=>z.timelineOverviewOpen),n=ce(z=>z.setTimelineOverviewOpen),a=se(z=>z.nodes),r=Tt(),s=o8(),o=Aa(z=>z.lang),u=AV(),d=R.useMemo(()=>t?Jv(a,0,{ladders:!0}):[],[t,a,u]),[h,m]=R.useState(1),p=Math.round(h),x={paddingTop:4+h*5,paddingBottom:4+h*5},b=R.useRef(null),y=R.useRef(null),w=R.useRef(null),E=z=>{const L=b.current;if(L){const q=L.getBoundingClientRect().top,W=[...L.querySelectorAll("[data-entry]")];let X=y.current?W.find(B=>B.dataset.entry===y.current)??null:null;if(!X){const B=q+L.clientHeight/2;X=W.reduce(($,Z)=>{const K=Z.getBoundingClientRect(),J=Math.abs((K.top+K.bottom)/2-B);return!$||J<Math.abs(($.getBoundingClientRect().top+$.getBoundingClientRect().bottom)/2-B)?Z:$},null)}w.current=X?{id:X.dataset.entry,y:X.getBoundingClientRect().top-q}:null}m(z)};R.useLayoutEffect(()=>{const z=b.current,L=w.current;if(!z||!L)return;const q=z.querySelector(`[data-entry="${L.id}"]`);if(!q)return;const W=q.getBoundingClientRect().top-z.getBoundingClientRect().top;z.scrollTop+=W-L.y},[h]);const v=13+h*.9,N=R.useMemo(()=>t?eI(a):"",[t,a]),[S,C]=R.useState(null),[I,O]=R.useState(!1),[_,A]=R.useState(!1),H=Fue(N,o)??S,G=!!H&&(H.fp!==N||H.lang!==o),D=()=>{O(!0),A(!1);const{nodes:z,edges:L}=se.getState();Uue(z,L,o).then(C).catch(()=>A(!0)).finally(()=>O(!1))};if(!t)return null;const P=()=>n(!1),Y=z=>z?z.slice(0,10):"",U=z=>z?new Date(z).toLocaleTimeString(s,{hour:"2-digit",minute:"2-digit"}):"—";return dr.createPortal(l.jsx("div",{className:"fixed inset-0 z-[60] bg-ink/30 backdrop-blur-sm flex items-center justify-center p-6",onClick:P,children:l.jsxs("div",{className:"bg-card rounded-2xl shadow-2xl border border-line w-[640px] h-[80vh] flex flex-col",onClick:z=>z.stopPropagation(),children:[l.jsxs("div",{className:"flex items-center gap-2 px-5 py-3 border-b border-line shrink-0",children:[l.jsx(Ep,{size:15,strokeWidth:1.75,className:"text-accent"}),l.jsx("span",{className:"text-sm font-semibold text-ink",children:r("tlov.title")}),l.jsx("span",{className:"text-2xs text-ink-faint",children:ve(r("tlov.count"),{n:d.length})}),l.jsxs("label",{className:"flex items-center gap-2 ml-3 text-2xs text-ink-faint",title:r("tlov.detailTitle"),children:[l.jsx("span",{children:r("tlov.detail")}),l.jsx("input",{type:"range",min:0,max:3,step:.01,value:h,onChange:z=>E(Number(z.target.value)),className:"w-28 accent-accent","data-tlov-detail":!0}),l.jsx("span",{className:"text-ink-muted w-8",children:r(`ladder.level${p}`)})]}),l.jsx("div",{className:"flex-1"}),l.jsxs("button",{onClick:()=>{P(),ce.getState().setThoughtMapOpen(!0)},disabled:d.length===0,"data-tmap-from-timeline":!0,className:"flex items-center gap-1.5 text-2xs text-ink-muted hover:text-accent hover:bg-accent/10 rounded-full px-2.5 py-1 transition-colors disabled:opacity-50",children:[l.jsx(p2,{size:13,strokeWidth:1.75}),r("tmap.export")]}),l.jsx("button",{onClick:P,className:"text-ink-faint hover:text-ink w-7 h-7 rounded-lg hover:bg-wash flex items-center justify-center transition-colors",children:l.jsx(on,{size:15,strokeWidth:1.75})})]}),l.jsxs("div",{className:"px-5 pt-3 shrink-0","data-gedankengang":!0,children:[!H&&!I&&l.jsxs("button",{onClick:D,className:"flex items-center gap-1.5 text-2xs text-accent bg-accent/10 hover:bg-accent/20 rounded-full px-3 py-1.5 transition-colors",children:[l.jsx(Vl,{size:12,strokeWidth:1.75}),r("tlov.gedankenGenerate")]}),I&&l.jsx("p",{className:"text-2xs text-ink-faint italic py-1.5",children:r("tlov.gedankenLoading")}),_&&!I&&l.jsx("p",{className:"text-2xs text-red-500 py-1",children:r("tlov.gedankenFailed")}),H&&!I&&l.jsxs("div",{className:`rounded-xl bg-wash px-4 py-3 ${G?"opacity-60":""}`,children:[l.jsx("p",{className:"text-sm text-ink leading-relaxed",children:H.text}),l.jsxs("div",{className:"flex items-center gap-2 mt-1.5",children:[l.jsx("span",{className:"text-2xs text-ink-faint",children:G?r("tlov.gedankenStale"):new Date(H.at).toLocaleString(s)}),G&&l.jsx("button",{onClick:D,className:"text-2xs text-accent hover:underline",children:r("tlov.gedankenRedo")})]})]})]}),l.jsxs("div",{ref:b,className:"flex-1 min-h-0 overflow-y-auto px-5 py-3","data-timeline-overview":!0,children:[d.length===0&&l.jsx("p",{className:"text-xs text-ink-faint italic py-2",children:r("tlov.empty")}),d.map((z,L)=>{const q=L>0?Y(d[L-1].createdAt):void 0,W=Y(z.createdAt),X=L===0||W!==q;return l.jsxs("div",{children:[X&&l.jsx("div",{className:"sticky top-0 bg-card text-2xs text-ink-faint font-medium pt-3 pb-1 first:pt-0",children:W||r("tlov.undated")}),l.jsxs("div",{className:"group flex items-start gap-2.5 border-b border-line/50 last:border-0",style:x,"data-entry":z.id,onMouseEnter:()=>{y.current=z.id},onMouseLeave:()=>{y.current===z.id&&(y.current=null)},children:[l.jsx("span",{className:"w-2 h-2 rounded-full shrink-0",style:{background:z.color,opacity:z.archived?.35:1}}),l.jsx("span",{className:"text-2xs font-mono text-ink-faint shrink-0 w-11",children:U(z.createdAt)}),l.jsxs("div",{className:"flex-1 min-w-0",children:[z.ladder?l.jsx("div",{className:z.archived?"opacity-50 line-through":"",children:l.jsx(yM,{ladder:z.ladder,level:p,fontSize:v,weight:z.badged?"font-semibold":"font-medium",className:"whitespace-pre-wrap break-words"})}):l.jsx("p",{className:`leading-snug whitespace-pre-wrap break-words ${z.archived?"text-ink-faint line-through":z.badged?"text-ink":"text-ink-muted"}`,style:{fontSize:v,transition:"font-size 160ms ease-out"},children:p===0?z.topic||z.label||"…":l.jsxs(l.Fragment,{children:[z.topic&&l.jsxs("span",{className:"font-medium text-accent",children:[z.topic," · "]}),z.label||"…"]})}),z.modifiedAt&&z.modifiedAt!==z.createdAt&&l.jsxs("p",{className:"text-2xs text-ink-faint",children:[r("timeline.modified")," ",new Date(z.modifiedAt).toLocaleString(s)]})]}),l.jsx("button",{className:"shrink-0 text-2xs font-mono text-accent bg-accent/10 hover:bg-accent/20 rounded-full px-1.5 py-0.5 transition-colors opacity-0 group-hover:opacity-100",onClick:()=>{P(),e(z.id)},title:r("hlov.locateTitle"),children:r("tlov.locate")})]})]},z.id)})]})]})}),document.body)}const $ue=R.memo(function(t){const n=sn(a=>a.projects.find(r=>r.id===a.activeId)?.kind==="paradigm");return t.data?.stepKind==="frame"?l.jsx(ele,{...t}):Bm(t.data?.stepKind)?l.jsx(Joe,{...t}):n?l.jsx(Koe,{...t}):l.jsx(Voe,{...t})}),Wue={thought:$ue},Vue={smoothstep:R.memo(ale)};function Gue(){const[e,t]=R.useState(Nt||se.persist.hasHydrated());return R.useEffect(()=>se.persist.onFinishHydration(()=>t(!0)),[]),R.useEffect(()=>{if(!e||Nt)return;let n;const a=()=>{clearTimeout(n),n=setTimeout(()=>{jce()},800)},r=se.subscribe((s,o)=>{s.nodes!==o.nodes&&a()});return a(),()=>{r(),clearTimeout(n)}},[e]),R.useEffect(()=>{ce.getState().condenseRun.status==="building"&&ce.getState().setCondenseRun({status:"idle",current:0,total:0,streaming:""})},[]),R.useEffect(()=>{if(Nt)return;const n=setTimeout(()=>{Lce()},6e3);return()=>clearTimeout(n)},[]),R.useEffect(()=>{if(!e||Nt||localStorage.getItem("thoughtdag.tutorialDone")||se.getState().nodes.length>0)return;const n=setTimeout(()=>ce.getState().setTutorialOpen(!0),900);return()=>clearTimeout(n)},[e]),R.useEffect(()=>{Fce()},[]),R.useEffect(()=>{Nt||(pt(()=>import("./session-handoff-9h2VEmwX.js"),[]).then(n=>n.consumeSessionHandoff()),pt(()=>Promise.resolve().then(()=>n7),void 0).then(n=>n.startLiveMirror()),pt(()=>import("./canvas-record-BD0b1tl8.js"),[]).then(n=>n.startCanvasRecord()),pt(()=>import("./canonical-Bkq2Xinv.js"),[]).then(n=>n.unsubscribeOrphanedSessions()))},[]),R.useEffect(()=>{Nt||Hce().then(n=>{n&&(n.status==="minted"?(We("success",Ne("provider.oauthMinted")),WM(n.key)):We("error",ve(Ne("provider.oauthFailed"),{error:n.error})))})},[]),l.jsxs(l.Fragment,{children:[e&&l.jsx(Yue,{}),l.jsx(Wce,{}),l.jsx(Iue,{}),l.jsx(Gce,{}),l.jsx(Xce,{}),l.jsx(Qce,{}),l.jsx(eue,{}),l.jsx(tue,{}),l.jsx(nue,{}),l.jsx(lue,{}),l.jsx(mue,{}),l.jsx(Uce,{}),l.jsx(Tue,{}),l.jsx(Mue,{}),l.jsx(Oue,{})]})}function Yue(){const{nodes:e,edges:t,setNodes:n,setEdges:a,addQuestion:r,undo:s,redo:o,addCrossLink:u,setSelectedNodeId:d,setSelectedNodeIds:h,history:m,historyIndex:p,relayout:x}=se(),b=Tt(),y=ce(te=>te.setTutorialOpen),w=ce(te=>te.annotationsHidden),E=ce(te=>te.setAnnotationsHidden),v=ce(te=>te.wheelPans),N=ce(te=>te.setWheelPans),[S,C]=R.useState(""),[I,O]=R.useState(!1),[_,A]=R.useState(!1),[H,G]=R.useState(""),[D,P]=R.useState(!1),[Y,U]=R.useState(!1),[z,L]=R.useState([]),[q,W]=R.useState(!1),X=R.useRef(null),B=R.useRef(null),$=e.length>0,Z=se(te=>te.events.length>0),K=se(te=>te.nodes.reduce((pe,Ae)=>pe+(Ae.data.highlights?.length??0),0)),J=se(te=>te.nodes.reduce((pe,Ae)=>pe+(Ae.data.attachments?.length??0)+(["note","link"].includes(Ae.data.stepKind??"")?1:0),0)),oe=R.useRef(null),me=ce(te=>te.arrivalFocusNodeId);R.useEffect(()=>{if(!me)return;const te=se.getState().nodes.find(pe=>pe.id===me);te&&(ce.getState().setArrivalFocusNodeId(null),window.setTimeout(()=>{oe.current?.setCenter(te.position.x+260,te.position.y+140,{zoom:.9,duration:400})},150))},[me]);const ye=qi(te=>te.paper),ae=qi(te=>te.lighting),ge=qi(te=>te.resolved),Te=R.useMemo(()=>Zoe(),[ge]),Fe=R.useMemo(()=>{const te=getComputedStyle(document.documentElement),pe=(te.getPropertyValue("--color-surface").trim()||"#FAF9F7").replace("#",""),[Ae,Oe,ct]=[0,2,4].map(ht=>parseInt(pe.slice(ht,ht+2),16));return{mask:`rgba(${Ae},${Oe},${ct},0.7)`,archived:te.getPropertyValue("--color-wash").trim()||"#EFEDE9",ordinary:ge==="dark"?"#6E6759":"#B9B3AB"}},[ge]),Me=R.useRef(e.length),Le=R.useCallback((te,pe={})=>{const Ae=oe.current;if(!Ae)return;const Oe=pe.zoom??Ae.getZoom();Ae.setCenter(te.position.x+(pe.offX??260)+cp(te.id)/(2*Oe),te.position.y+110,{zoom:Oe,duration:pe.duration??350})},[]),Ee=Aa(te=>te.lang),ze=ce(te=>te.condenseRun),De=ze.status==="building",tt=sn(te=>te.projects.find(pe=>pe.id===te.activeId)?.kind==="paradigm"),xt=ec(),Ke=R.useCallback(()=>{const{nodes:te,edges:pe}=Rce(Ee),Ae=se.getState();Ae.setNodes([...Ae.nodes,...te.filter(Oe=>!Ae.nodes.some(ct=>ct.id===Oe.id))]),Ae.setEdges([...Ae.edges,...pe.filter(Oe=>!Ae.edges.some(ct=>ct.id===Oe.id))]),Ae.pushHistory(),setTimeout(()=>{const Oe=oe.current;Oe&&(Oe.fitView({duration:500,padding:.1}),setTimeout(()=>{if(Oe.getViewport().zoom<.34){const ct=[...se.getState().nodes].sort((ht,Et)=>(ht.data.createdAt??"").localeCompare(Et.data.createdAt??""))[0];ct&&Oe.setCenter(ct.position.x+300,ct.position.y+240,{zoom:.6,duration:550})}},680))},100),localStorage.getItem("thoughtdag.tutorialDone")||y(!0)},[Ee,y]),nt=R.useCallback(te=>{const pe=se.getState(),Ae=pe.nodes[pe.nodes.length-1],Oe=Ae?{x:Ae.position.x,y:Ae.position.y+340}:{x:120,y:80},ct=En();pe.setNodes([...pe.nodes,{id:ct,type:"thought",position:Oe,dragHandle:".drag-handle",data:{question:"",instruction:"",stepKind:te,response:"",responses:[],responseIndex:-1,isCollapsed:!1,isEditing:!1,isEditingResponse:!1,isLoading:!1,tokenCount:0,highlights:[],highlightMode:"tag",attachments:[],excludedAttachmentIds:[],includedAttachmentIds:[],roleMode:"inherit",isRoot:pe.nodes.length===0,isBranch:!1}}]),pe.pushHistory()},[]),st=R.useCallback(()=>{Me.current=se.getState().nodes.length,setTimeout(()=>oe.current?.fitView({duration:300,padding:.2}),50)},[]);R.useEffect(()=>{const te=()=>st();return window.addEventListener("td:project-switched",te),()=>window.removeEventListener("td:project-switched",te)},[st]);const Ue=R.useRef(null),Rt=R.useCallback(te=>{const pe=se.getState(),Ae=En();pe.setNodes([...pe.nodes,{id:Ae,type:"thought",position:te,width:640,height:420,zIndex:-1,dragHandle:".drag-handle",data:{question:"",stepKind:"frame",frameCarry:!1,response:"",responses:[],responseIndex:-1,isCollapsed:!1,isEditing:!1,isEditingResponse:!1,isLoading:!1,tokenCount:0,highlights:[],highlightMode:"tag",attachments:[],excludedAttachmentIds:[],includedAttachmentIds:[],roleMode:"inherit",isRoot:!1,isBranch:!1}}]),pe.pushHistory()},[]),lt=R.useCallback(te=>{const pe=[];for(const Ae of Array.from(te)){const Oe=Ae.name.split(".").pop()?.toLowerCase()??"";Ae.type.startsWith("image/")||Ae.type==="application/pdf"||Ae.type.startsWith("text/")||["pdf","docx","txt","md","csv","json","yaml","yml","toml","js","ts","tsx","jsx","py","sh","c","cpp","h","java","rs","go","rb","swift","css","html","xml","sql","tex","bib"].includes(Oe)?pe.push(Ae):We("info",ve(Ne("toast.unsupportedFile"),{name:Ae.name}))}return pe},[]),Dt=R.useCallback(te=>{const pe=se.getState(),Ae=En();return pe.setNodes([...pe.nodes,{id:Ae,type:"thought",position:te,dragHandle:".drag-handle",data:{question:"",response:"",responses:[],responseIndex:-1,isCollapsed:!1,isEditing:!1,isEditingResponse:!1,isLoading:!1,tokenCount:0,highlights:[],highlightMode:"tag",attachments:[],excludedAttachmentIds:[],includedAttachmentIds:[],roleMode:"inherit",isRoot:!1,isBranch:!1}}]),pe.pushHistory(),Ae},[]),_e=R.useCallback(te=>{const pe=lt(te);if(pe.length===0)return;let Ae=null;pe.forEach((Oe,ct)=>{const ht=gs("file",{x:120+ct%3*480,y:120+Math.floor(ct/3)*620});Xd(ht,[Oe]),!Ae&&!Oe.type.startsWith("image/")&&(Ae=ht)}),Ae&&ce.getState().setReaderNodeId(Ae),setTimeout(()=>oe.current?.fitView({duration:400,padding:.2}),120)},[lt]),Qe=R.useCallback((te,pe)=>{const Ae=te.clientX,Oe=te.clientY,ct=te.currentTarget;let ht=null;const Et=en=>{!ht&&Math.hypot(en.clientX-Ae,en.clientY-Oe)>6&&(ht=document.createElement("div"),ht.innerHTML=ct.innerHTML,ht.style.cssText="position:fixed;z-index:300;pointer-events:none;width:36px;height:36px;display:flex;align-items:center;justify-content:center;background:var(--color-card);border:1px solid var(--color-accent);border-radius:10px;box-shadow:0 4px 14px rgba(0,0,0,.18);opacity:.92;",document.body.appendChild(ht)),ht&&(ht.style.left=`${en.clientX-18}px`,ht.style.top=`${en.clientY-18}px`)},un=en=>{window.removeEventListener("pointermove",Et),window.removeEventListener("pointerup",un);const mn=!!ht;ht?.remove(),pe(mn?{x:en.clientX,y:en.clientY}:null)};window.addEventListener("pointermove",Et),window.addEventListener("pointerup",un)},[]),ie=R.useCallback(te=>{const pe=oe.current?.screenToFlowPosition(te??{x:window.innerWidth/2,y:window.innerHeight/2})??{x:140,y:140};return{x:pe.x-200,y:pe.y-60}},[]);R.useEffect(()=>{const te=Ae=>{Ue.current={x:Ae.clientX,y:Ae.clientY}},pe=Ae=>{if(Nt)return;const Oe=Ae.target;if(Oe&&(Oe.tagName==="INPUT"||Oe.tagName==="TEXTAREA"||Oe.isContentEditable))return;const ct=sn.getState(),ht=ct.projects.find(aa=>aa.id===ct.activeId)?.kind==="paradigm";if(se.getState().nodes.length===0&&!ht)return;const Et=Ae.clipboardData;if(!Et)return;const un=ie(Ue.current),en=Et.getData("text/plain").trim(),mn=Array.from(Et.files),Qa=mn.some(aa=>!aa.type.startsWith("image/"));if(mn.length>0&&(Qa||!en)){Ae.preventDefault();const aa=gs("file",un);Xd(aa,mn);return}if(en)if(Ae.preventDefault(),/^https?:\/\/\S+$/.test(en)){const aa=gs("link",un,{linkUrl:en});J8(aa,en)}else gs("note",un,{question:NW(en)})};return window.addEventListener("mousemove",te),window.addEventListener("paste",pe),()=>{window.removeEventListener("mousemove",te),window.removeEventListener("paste",pe)}},[ie]);const Be=R.useCallback(async()=>{const te=se.getState();if(te.nodes.length===0)return;const{nodes:pe,edges:Ae}=vG(te.nodes,te.edges),Oe=sn.getState(),ct=Oe.projects.find(Et=>Et.id===Oe.activeId)?.name??"Paradigm",ht=crypto.randomUUID();await Pr(ks(ht),JSON.stringify({state:{nodes:pe,edges:Ae},version:1})),await Tu(ht,`▶ ${ct}`,"chat"),await q7(ht,ct),Me.current=se.getState().nodes.length,setTimeout(()=>oe.current?.fitView({duration:400,padding:.15}),150)},[]);R.useEffect(()=>{e.length===0&&!tt&&!localStorage.getItem("thoughtdag.seeded")&&localStorage.setItem("thoughtdag.seeded","yes")},[]),R.useEffect(()=>{if(e.length>Me.current&&oe.current){const te=e[e.length-1];te&&setTimeout(()=>Le(te,{zoom:1,duration:400,offX:220}),100)}Me.current=e.length},[e,Le]);const ot=R.useCallback(te=>{const pe=se.getState().nodes;n(dA(te,pe))},[n]),Ht=R.useCallback(te=>a(hA(te,se.getState().edges)),[a]),Wt=R.useRef(null),Vt=R.useCallback((te,pe)=>{if(pe.data.stepKind!=="frame"||pe.data.frameCarry===!1)return;const Ae=se.getState(),Oe=Ae.nodes.find(ht=>ht.id===pe.id);if(!Oe)return;const ct=R8(Oe,Ae.nodes).filter(ht=>!ht.selected).map(ht=>({id:ht.id,start:ht.position}));ct.length!==0&&(Wt.current={frameId:Oe.id,start:Oe.position,members:ct})},[]),Ft=R.useCallback((te,pe)=>{const Ae=Wt.current;if(!Ae||pe.id!==Ae.frameId)return;const Oe=pe.position.x-Ae.start.x,ct=pe.position.y-Ae.start.y,ht=new Map(Ae.members.map(Et=>[Et.id,{x:Et.start.x+Oe,y:Et.start.y+ct}]));se.setState(Et=>({nodes:Et.nodes.map(un=>{const en=ht.get(un.id);return en?{...un,position:en}:un})}))},[]),ln=R.useCallback(()=>{Wt.current=null},[]),[$t,ha]=R.useState(null),[Dn,qa]=R.useState(null),sr=R.useCallback((te,pe)=>{Nt||window.getSelection()?.toString()||(te.preventDefault(),qa({x:te.clientX,y:te.clientY,nodeId:pe.id}))},[]),na=R.useCallback((te,pe)=>{te.preventDefault(),ha({x:te.clientX,y:te.clientY,edgeId:pe.id})},[]);R.useEffect(()=>{if(!$t)return;const te=()=>ha(null);return window.addEventListener("click",te),()=>window.removeEventListener("click",te)},[$t]);const Ca=se(te=>te.deleteEdges),oa=R.useCallback(te=>{Ca([te]),ha(null)},[Ca]),xe=R.useCallback(te=>{te.source&&te.target&&u(te.source,te.target)},[u]),Ve=R.useCallback(()=>{window.getSelection()?.removeAllRanges(),document.body.classList.add("tdag-connecting")},[]),gt=R.useCallback((te,pe)=>{if(document.body.classList.remove("tdag-connecting"),tt||pe.isValid||pe.fromHandle?.type!=="source"||!pe.fromNode)return;const Ae=pe.fromNode.id,Oe=te.target?.closest?.(".react-flow__node");if(Oe){const mn=Oe.getAttribute("data-id");if(mn&&mn!==Ae){const Qa=se.getState().nodes.find(Ma=>Ma.id===mn),aa=Qa?.data.stepKind??"";Qa&&!["note","file","link","frame"].includes(aa)&&se.getState().addCrossLink(Ae,mn)}return}const{clientX:ct,clientY:ht}="changedTouches"in te?te.changedTouches[0]:te,Et=ie({x:ct,y:ht}),un=se.getState();if(un.nodes.find(mn=>mn.id===Ae)?.data.stepKind==="frame")return;const en=Dt(Et);un.setEdges([...se.getState().edges,{id:`edge-${Ae}-${en}`,source:Ae,target:en,sourceHandle:"continue",targetHandle:"top",type:"smoothstep",style:{stroke:at.accent,strokeWidth:2},animated:!1,markerEnd:{type:"arrowclosed",color:at.accent,width:18,height:18},data:{}}]),se.getState().pushHistory()},[tt,ie,Dt]),wt=se(te=>te.selectedNodeId),cn=se(te=>te.selectedNodeIds),vn=ce(te=>te.panelOpen),_t=ce(te=>te.viewerLoadError),bt=se(te=>Qr(te).length),It=ce(te=>te.panelWidth),Nn=e.find(te=>te.id===wt),Mn=Nn?.data.stepKind,we=Bm(Mn)||Mn==="frame",et=vn&&!!Nn&&!tt&&!we;R.useEffect(()=>{wt&&!Nn&&se.getState().setSelectedNodeId(null)},[wt,Nn]);const St=cn.length>1,Lt=se(te=>te.batchDelete);R.useEffect(()=>{const te=pe=>{if(!ce.getState().confirmRequest&&!(Nt&&!((pe.metaKey||pe.ctrlKey)&&pe.key==="f"))){if((pe.metaKey||pe.ctrlKey)&&pe.key==="z"&&(pe.shiftKey?(pe.preventDefault(),o()):(pe.preventDefault(),s())),(pe.metaKey||pe.ctrlKey)&&pe.key==="f"){pe.preventDefault(),O(!0);return}{const Ae=pe.target;if(!(Ae.tagName==="INPUT"||Ae.tagName==="TEXTAREA"||Ae.isContentEditable)&&wt&&!tt&&!pe.metaKey&&!pe.ctrlKey&&!pe.altKey){const{nodes:ct,edges:ht}=se.getState();if(pe.key===" "){pe.preventDefault(),se.getState().toggleCollapse(wt);return}if(pe.key==="r"||pe.key==="R"){pe.preventDefault(),se.getState().rerunNode(wt,{});return}if(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(pe.key)){const Et=ht.filter(en=>!en.data?.isCrossLink);let un;if(pe.key==="ArrowUp")un=Et.find(en=>en.target===wt)?.source;else if(pe.key==="ArrowDown")un=Et.find(en=>en.source===wt)?.target;else{const en=Et.find(aa=>aa.target===wt),mn=en?Et.filter(aa=>aa.source===en.source).map(aa=>aa.target):ct.filter(aa=>!Et.some(Ma=>Ma.target===aa.id)).map(aa=>aa.id),Qa=mn.indexOf(wt);Qa!==-1&&mn.length>1&&(un=mn[(Qa+(pe.key==="ArrowRight"?1:mn.length-1))%mn.length])}if(un){pe.preventDefault(),d(un);const en=ct.find(mn=>mn.id===un);en&&Le(en,{zoom:1,duration:300})}return}}}if(pe.key==="Escape"){const Ae=pe.target;if(Ae.tagName==="INPUT"||Ae.tagName==="TEXTAREA"||Ae.isContentEditable)return;cn.length>1?h([]):wt&&d(null);return}if(pe.key==="Delete"||pe.key==="Backspace"){const Ae=pe.target;if(Ae.tagName==="INPUT"||Ae.tagName==="TEXTAREA"||Ae.isContentEditable)return;if(cn.length>1)pe.preventDefault(),oi({title:Ne("confirm.deleteNodesTitle"),message:ve(Ne("confirm.deleteNodes"),{n:cn.length}),confirmLabel:Ne("common.delete"),danger:!0}).then(Oe=>{Oe&&Lt(cn)});else{const Oe=t.filter(ct=>ct.selected).map(ct=>ct.id);Oe.length>0&&(pe.preventDefault(),Ca(Oe))}}}};return window.addEventListener("keydown",te),()=>window.removeEventListener("keydown",te)},[s,o,wt,cn,d,h,Lt,t,Ca,tt,Le]);const kt=()=>{S.trim()&&(r(S.trim(),{rolePrompt:H.trim()||void 0,initialAttachments:z.length>0?z:void 0}),C(""),G(""),P(!1),L([]))},qt=async te=>{for(const pe of Array.from(te))await X0(pe,{add:Ae=>L(Oe=>[...Oe,Ae]),update:(Ae,Oe)=>L(ct=>ct.map(ht=>ht.id===Ae?{...ht,...Oe}:ht))})},Qt=te=>{te.key==="Enter"&&!te.shiftKey&&!ar(te)&&(te.preventDefault(),kt())},nn=R.useCallback(({nodes:te})=>{const pe=te.map(Ae=>Ae.id);pe.length>1?h(pe):pe.length===1&&d(pe[0])},[d,h]),Jn=R.useMemo(()=>e.filter(te=>te.data.stepKind==="frame"),[e]),[Jt,In]=R.useState(!1),va=R.useRef(null);R.useEffect(()=>{if(!Jt)return;const te=pe=>{va.current?.contains(pe.target)||In(!1)};return window.addEventListener("mousedown",te),()=>window.removeEventListener("mousedown",te)},[Jt]);const[_a,an]=R.useState(!1),Bn=ce(te=>te.pluginUpdate),wa=ce(te=>!!te.harnessHost?.desktop),[Fn,Wn]=R.useState(0),pr=ce(te=>te.searchHitIds!==null),Xa=R.useRef(null);R.useEffect(()=>{if(!_a)return;const te=pe=>{Xa.current?.contains(pe.target)||an(!1)};return window.addEventListener("mousedown",te),()=>window.removeEventListener("mousedown",te)},[_a]);const $a=ce(te=>te.searchHitIds),Je=R.useMemo(()=>{if(!wt||cn.length>1||!e.some(Et=>Et.id===wt))return null;const te=K0(wt,e,t),pe=new Set;for(const Et of te.mainline)Et.id!==wt&&pe.add(Et.id);for(const Et of te.materials)pe.add(Et.id);for(const Et of te.references)pe.add(Et.source.id);const Ae=t.filter(Et=>!Et.data?.isCrossLink),Oe=zr(wt,e,Ae).visitedEdgeIds,ct=new Set(te.references.map(Et=>Et.edge.id)),ht=Ae.filter(Et=>Et.source===wt);return{ctx:pe,down:new Set(ht.map(Et=>Et.target)),pathEdgeIds:Oe,refEdgeIds:ct,downEdgeIds:new Set(ht.map(Et=>Et.id))}},[wt,cn,e,t]),le=R.useMemo(()=>{const te=e.filter(Oe=>Oe.data.stepKind==="frame").map((Oe,ct)=>({id:Oe.id,order:ct,area:(Oe.measured?.width??Oe.width??640)*(Oe.measured?.height??Oe.height??420)})).sort((Oe,ct)=>ct.area-Oe.area||Oe.order-ct.order),pe=new Map(te.map((Oe,ct)=>[Oe.id,ct-te.length]));let Ae=e.map(Oe=>Oe.data.stepKind==="frame"?{...Oe,zIndex:pe.get(Oe.id)??-1}:Oe);return w&&(Ae=Ae.map(Oe=>{const ct=Oe.data.stepKind,ht=Bm(ct)&&!t.some(Et=>Et.source===Oe.id||Et.target===Oe.id);return ct==="frame"||ht?{...Oe,hidden:!0}:Oe})),$a!==null&&(Ae=Ae.map(Oe=>$a.has(Oe.id)||Oe.data.stepKind==="frame"?{...Oe,className:"search-hit"}:Oe.className==="search-hit"?{...Oe,className:void 0}:Oe)),Je&&(Ae=Ae.map(Oe=>{const ct=Oe.id===wt?"target":Je.ctx.has(Oe.id)?"ctx":Je.down.has(Oe.id)?"down":Oe.data.stepKind==="frame"?void 0:"dim";return ct?{...Oe,className:[Oe.className,`focus-${ct}`].filter(Boolean).join(" "),...ct!=="dim"?{data:{...Oe.data,focusRole:ct}}:{}}:Oe})),Ae},[e,t,w,$a,Je,wt]),Ct=R.useMemo(()=>{const te=t.map(Oe=>{const ct=Oe.data?.isBranchFromSelection?{...Oe,animated:!1,style:{...Oe.style,strokeDasharray:void 0}}:Oe,ht=typeof ct.style?.stroke=="string"?pN[ct.style.stroke.toUpperCase()]:void 0,Et=ct.markerEnd&&typeof ct.markerEnd=="object"?ct.markerEnd:void 0,un=typeof Et?.color=="string"?pN[Et.color.toUpperCase()]:void 0;return!ht&&!un?ct:{...ct,...ht?{style:{...ct.style,stroke:Te[ht]}}:{},...un&&Et?{markerEnd:{...Et,color:Te[un]}}:{}}});if(Je)return te.map(Oe=>Je.pathEdgeIds.has(Oe.id)?{...Oe,className:"focus-e-path",style:{...Oe.style,stroke:Te.accent,strokeWidth:3.5,opacity:1},markerEnd:{type:"arrowclosed",...Oe.markerEnd&&typeof Oe.markerEnd=="object"?Oe.markerEnd:{},color:Te.accent},zIndex:10,data:{...Oe.data,focusRole:"path"}}:Je.refEdgeIds.has(Oe.id)?{...Oe,style:{...Oe.style,opacity:.9},zIndex:5,data:{...Oe.data,focusRole:"ref"}}:Je.downEdgeIds.has(Oe.id)?{...Oe,className:"focus-e-down",style:{...Oe.style,strokeWidth:2.5,opacity:.85},markerEnd:{type:"arrowclosed",...Oe.markerEnd&&typeof Oe.markerEnd=="object"?Oe.markerEnd:{}},zIndex:5,data:{...Oe.data,focusRole:"down"}}:{...Oe,style:{...Oe.style,strokeWidth:1.5,opacity:.2},zIndex:0});const pe=cn.length>1?cn:[];if(pe.length===0)return te;const{visitedEdgeIds:Ae}=zr(pe,e,t);return te.map(Oe=>Ae.has(Oe.id)?{...Oe,style:{...Oe.style,stroke:Te.trace,strokeWidth:3.5,opacity:1},markerEnd:{type:"arrowclosed",...Oe.markerEnd&&typeof Oe.markerEnd=="object"?Oe.markerEnd:{},color:Te.trace},zIndex:10}:{...Oe,style:{...Oe.style,strokeWidth:1.5,opacity:.2},zIndex:0})},[e,t,cn,Te,Je]);return R.useEffect(()=>{if(!et||!wt)return;const te=setTimeout(()=>{const pe=oe.current;if(!pe)return;const Ae=se.getState().nodes.find(un=>un.id===wt);if(!Ae)return;const Oe=pe.getViewport(),ct=Ae.measured?.width??Ae.width??480,ht=(Ae.position.x+ct)*Oe.zoom+Oe.x,Et=window.innerWidth-ce.getState().panelWidth-Yd-24;if(ht>Et){const un=(Ae.position.x+ct/2)*Oe.zoom+Oe.x;pe.setViewport({...Oe,x:Oe.x-(un-Et/2)},{duration:300})}},60);return()=>clearTimeout(te)},[et,wt]),l.jsxs("div",{className:"relative w-full h-full","data-searching":pr||void 0,children:[l.jsxs("div",{className:"relative h-full w-full",onDoubleClick:te=>{te.target.classList.contains("react-flow__pane")&&!tt&&Dt(ie({x:te.clientX,y:te.clientY}))},onDragOver:te=>{(te.dataTransfer.types.includes("application/thoughtdag-content")||te.dataTransfer.types.includes("Files"))&&(te.preventDefault(),te.dataTransfer.dropEffect="copy",!$&&!tt&&W(!0))},onDrop:te=>{if(Nt)return;const pe=te.target;if(!$&&!tt&&te.dataTransfer.files.length>0){te.preventDefault(),W(!1),_e(te.dataTransfer.files);return}const Ae=pe.closest?.(".react-flow__node"),Oe=Ae&&se.getState().nodes.find(Et=>Et.id===Ae.getAttribute("data-id"))?.data.stepKind==="frame";if(!pe.classList?.contains("react-flow__pane")&&!Oe)return;const ct=ie({x:te.clientX,y:te.clientY}),ht=te.dataTransfer.getData("application/thoughtdag-content");if(ht==="ask"){te.preventDefault(),Dt(ct);return}if(ht==="frame"){te.preventDefault(),Rt(ct);return}if(ht==="note"||ht==="file"){te.preventDefault(),gs(ht,ct);return}if(te.dataTransfer.files.length>0){te.preventDefault();const Et=lt(te.dataTransfer.files);if(Et.length===0)return;const un=gs("file",ct);Xd(un,Et)}},children:[l.jsxs(VB,{onInit:te=>{oe.current=te,RM.current=te;const pe=ce.getState().arrivalFocusNodeId;if(pe){ce.getState().setArrivalFocusNodeId(null);const Ae=se.getState().nodes.find(Oe=>Oe.id===pe);Ae&&window.setTimeout(()=>{te.setCenter(Ae.position.x+260,Ae.position.y+140,{zoom:.9,duration:400})},150)}},nodes:le,edges:Ct,onNodesChange:ot,onEdgesChange:Ht,onNodeDragStart:Vt,onNodeDrag:Ft,onNodeDragStop:ln,onConnect:xe,onConnectStart:Ve,onConnectEnd:gt,onEdgeContextMenu:na,onNodeContextMenu:sr,nodeTypes:Wue,edgeTypes:Vue,deleteKeyCode:null,fitView:!0,onlyRenderVisibleElements:!0,minZoom:.04,maxZoom:2,defaultEdgeOptions:{type:"smoothstep",animated:!1,style:{stroke:Te.accent,strokeWidth:2},markerEnd:{type:"arrowclosed",color:Te.accent,width:18,height:18}},snapToGrid:ye==="grid",snapGrid:[22,22],proOptions:{hideAttribution:!0},nodeDragThreshold:5,connectionRadius:40,selectionMode:du.Partial,selectionOnDrag:!Nt,nodesDraggable:!Nt,nodesConnectable:!Nt,panOnDrag:Nt?!0:[1,2],panOnScroll:v,zoomOnScroll:!v,zoomOnPinch:!0,zoomOnDoubleClick:!1,connectionLineStyle:{stroke:Te.accent,strokeDasharray:"8 4",strokeWidth:2},onSelectionChange:nn,onPaneClick:()=>{d(null),h([]),qa(null)},children:[ye==="grid"?l.jsxs(l.Fragment,{children:[l.jsx(gx,{id:"grid-fine",variant:Ps.Lines,gap:22,color:"var(--canvas-grid-fine)"}),l.jsx(gx,{id:"grid-major",variant:Ps.Lines,gap:110,color:"var(--canvas-grid-major)"})]}):l.jsx(gx,{variant:Ps.Dots,gap:24,size:1,color:"var(--canvas-dot)"}),l.jsx(Xue,{}),l.jsx(Kue,{panelShiftWidth:et?It:0}),l.jsx(Hue,{}),l.jsx(rH,{position:"bottom-left"}),e.length>0&&l.jsx(xH,{nodeColor:te=>{const pe=te.data;if(pe.archived)return Fe.archived;const Ae=pe.stepKind;return Ae==="note"?"#D97706":Ae==="file"||Ae==="link"?"#64748B":Array.isArray(pe.condensedFrom)&&pe.condensedFrom.length?"#8B7CF0":pe.isRoot?Te.accent:pe.isBranch?Te.warm:Fe.ordinary},maskColor:Fe.mask,style:{width:200,height:140},pannable:!0,zoomable:!0,position:"bottom-right"})]}),!$&&tt&&l.jsx("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:l.jsxs("div",{className:"text-center pointer-events-auto",children:[l.jsx("p",{className:"text-sm text-ink-muted mb-1 font-medium",children:b("paradigm.emptyTitle")}),l.jsx("p",{className:"text-xs text-ink-faint mb-4 max-w-sm leading-relaxed",children:b("paradigm.emptyHint")}),l.jsxs("div",{className:"flex items-center justify-center gap-2",children:[l.jsxs("button",{onClick:()=>nt("human"),className:"text-sm border-2 border-dashed border-warm/60 text-warm hover:bg-warm/10 px-4 py-2.5 rounded-xl transition-colors flex items-center gap-1.5",children:[l.jsx(Ol,{size:15,strokeWidth:1.75})," ",b("paradigm.addHuman")]}),l.jsxs("button",{onClick:()=>nt("prompt"),className:"text-sm border-2 border-dashed border-accent/50 text-accent hover:bg-accent/10 px-4 py-2.5 rounded-xl transition-colors flex items-center gap-1.5",children:[l.jsx(Qo,{size:15,strokeWidth:1.75})," ",b("paradigm.addPrompt")]})]})]})}),Nt&&!$&&l.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:l.jsx("div",{className:"text-center max-w-[420px] px-6",children:_t?l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"text-3xl mb-3",children:"🔗"}),l.jsx("div",{className:"text-sm font-semibold text-ink mb-1.5",children:b("viewer.loadError")}),l.jsx("p",{className:"text-xs text-ink-muted leading-relaxed",children:b("viewer.loadErrorHint")})]}):l.jsxs("div",{className:"flex items-center gap-2 text-sm text-ink-muted justify-center",children:[l.jsx(tn,{size:16,strokeWidth:1.75,className:"animate-spin text-accent"})," ",b("viewer.loading")]})})}),!$&&!tt&&!Nt&&l.jsxs("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none overflow-hidden",children:[l.jsxs("svg",{className:"absolute -left-10 top-[8%] w-[360px] h-[300px] opacity-[0.35] pointer-events-none",viewBox:"0 0 360 300","aria-hidden":!0,children:[l.jsx("path",{d:"M80 40 C80 90 80 90 80 130 M80 170 C80 210 80 210 80 250",stroke:at.line,strokeWidth:"2",fill:"none"}),l.jsx("path",{d:"M95 150 C150 150 150 90 205 88",stroke:at.line,strokeWidth:"2",strokeDasharray:"6 5",fill:"none"}),l.jsx("circle",{cx:"80",cy:"30",r:"7",fill:at.line}),l.jsx("circle",{cx:"80",cy:"150",r:"7",fill:"none",stroke:at.line,strokeWidth:"2.5"}),l.jsx("circle",{cx:"80",cy:"262",r:"7",fill:at.line}),l.jsx("circle",{cx:"218",cy:"88",r:"7",fill:at.line})]}),l.jsxs("svg",{className:"absolute right-[-30px] bottom-[10%] w-[320px] h-[280px] opacity-[0.35] pointer-events-none",viewBox:"0 0 320 280","aria-hidden":!0,children:[l.jsx("path",{d:"M240 30 C240 80 240 80 240 120 M240 160 C240 200 240 200 240 240",stroke:at.line,strokeWidth:"2",fill:"none"}),l.jsx("path",{d:"M225 140 C170 140 170 210 115 212",stroke:at.line,strokeWidth:"2",strokeDasharray:"6 5",fill:"none"}),l.jsx("circle",{cx:"240",cy:"20",r:"7",fill:at.line}),l.jsx("circle",{cx:"240",cy:"140",r:"7",fill:"none",stroke:at.line,strokeWidth:"2.5"}),l.jsx("circle",{cx:"240",cy:"252",r:"7",fill:at.line}),l.jsx("circle",{cx:"102",cy:"212",r:"7",fill:at.line})]}),l.jsxs("div",{className:"pointer-events-auto w-[560px] animate-fade-in relative",children:[l.jsxs("div",{className:"text-center mb-8",children:[l.jsxs("svg",{width:"52",height:"52",viewBox:"0 0 44 44",className:"mx-auto mb-4","aria-hidden":!0,children:[l.jsx("circle",{className:"dag-pop",style:{animationDelay:"0.05s"},cx:"22",cy:"7",r:"3.5",fill:at.accent}),l.jsx("line",{className:"dag-pop",style:{animationDelay:"0.2s"},x1:"22",y1:"11",x2:"22",y2:"19",stroke:at.accent,strokeWidth:"2",strokeLinecap:"round"}),l.jsx("circle",{className:"dag-pop",style:{animationDelay:"0.35s"},cx:"22",cy:"22",r:"3.5",fill:"none",stroke:at.accent,strokeWidth:"2.5"}),l.jsx("line",{className:"dag-pop",style:{animationDelay:"0.5s"},x1:"22",y1:"25",x2:"22",y2:"33",stroke:at.accent,strokeWidth:"2",strokeLinecap:"round"}),l.jsx("circle",{className:"dag-pop",style:{animationDelay:"0.65s"},cx:"22",cy:"37",r:"3.5",fill:at.accent,opacity:"0.35"}),l.jsx("line",{className:"dag-pop",style:{animationDelay:"0.8s"},x1:"25.5",y1:"23.5",x2:"33",y2:"28.5",stroke:at.warm,strokeWidth:"2",strokeLinecap:"round",strokeDasharray:"3 3"}),l.jsx("circle",{className:"dag-pop",style:{animationDelay:"0.95s"},cx:"36",cy:"30",r:"3.5",fill:at.warm})]}),l.jsx("h1",{className:"text-4xl font-semibold tracking-tight text-ink mb-2.5",children:"ThoughtDAG"}),l.jsx("p",{className:"text-sm text-ink-muted",children:b("landing.tagline")}),l.jsx("p",{className:"text-xs text-ink-muted mt-1.5 font-medium",children:b("landing.mechanism")})]}),l.jsxs("div",{className:"bg-card border border-line rounded-xl px-5 py-4 shadow-lg transition-all focus-within:border-accent/50 focus-within:shadow-xl",children:[l.jsx("textarea",{value:S,onChange:te=>C(te.target.value),onKeyDown:Qt,onPaste:te=>{if(te.clipboardData.getData("text/plain").trim())return;const pe=Array.from(te.clipboardData.items).filter(Ae=>Ae.kind==="file").map(Ae=>Ae.getAsFile()).filter(Boolean);pe.length&&qt(pe)},placeholder:b("landing.placeholder"),className:"w-full bg-transparent text-ink text-sm leading-relaxed resize-none focus:outline-none placeholder-ink-faint",rows:3,autoFocus:!0}),z.length>0&&l.jsx("div",{className:"flex flex-wrap gap-2 mt-2 pb-1",children:z.map(te=>l.jsxs("div",{className:"flex items-center gap-1.5 bg-wash rounded-lg px-2.5 py-1.5 group",children:[te.thumbnailUrl?l.jsx("img",{src:te.thumbnailUrl,className:"w-6 h-6 rounded object-cover",alt:te.name}):l.jsx("span",{className:"text-xs",children:l.jsx(zs,{size:16,strokeWidth:1.75})}),l.jsx("span",{className:"text-xs text-ink-muted max-w-[100px] truncate",children:te.name}),te.isExtracting&&l.jsx("span",{className:"text-2xs text-accent",children:l.jsx(tn,{className:"animate-spin",size:12,strokeWidth:1.75})}),te.numPages!=null&&l.jsxs("span",{className:"text-2xs text-ink-faint",children:[te.numPages,"p"]}),l.jsx("button",{onClick:()=>L(pe=>pe.filter(Ae=>Ae.id!==te.id)),className:"text-ink-faint hover:text-red-500 text-xs opacity-0 group-hover:opacity-100 transition-opacity",children:l.jsx(on,{size:14,strokeWidth:1.75})})]},te.id))}),D&&l.jsxs("div",{className:"space-y-1 mt-2",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsx("span",{className:"text-xs text-ink-muted font-medium",children:b("landing.roleLabel")}),l.jsx("button",{onClick:()=>{P(!1),G("")},className:"text-xs text-ink-faint hover:text-ink-muted",children:l.jsx(on,{size:14,strokeWidth:1.75})})]}),l.jsx("textarea",{value:H,onChange:te=>G(te.target.value),placeholder:b("landing.rolePlaceholder"),className:"w-full text-xs border border-line rounded-lg px-3 py-2 focus:outline-none focus:ring-1 focus:ring-accent bg-surface resize-none leading-relaxed",rows:2,autoFocus:!0}),l.jsx(AM,{onPick:G})]}),l.jsxs("div",{className:"flex items-center justify-end mt-2 gap-2",children:[l.jsx(Pl,{}),l.jsx("button",{onClick:()=>P(!D),title:b("landing.roleTrayTitle"),className:`rounded-full w-8 h-8 flex items-center justify-center transition-colors shrink-0 ${D||H?"text-accent bg-accent/10 hover:bg-accent/20":"text-ink-faint hover:text-ink-muted hover:bg-line"}`,children:l.jsx(kF,{size:16,strokeWidth:1.75})}),l.jsx("button",{onClick:()=>X.current?.click(),className:"text-ink-faint hover:text-accent hover:bg-wash rounded-xl px-3 py-2 transition-colors text-sm",title:b("landing.attach"),children:l.jsx(Bs,{size:16,strokeWidth:1.75})}),l.jsx("input",{ref:X,type:"file",multiple:!0,accept:w0,className:"hidden",onChange:te=>{qt(te.target.files||[]),te.target.value=""}}),l.jsx("button",{onClick:kt,disabled:!S.trim()||z.some(te=>te.isExtracting),className:"bg-accent hover:bg-accent-strong disabled:opacity-30 disabled:cursor-not-allowed text-white text-sm px-5 py-2 rounded-xl transition-all",children:z.some(te=>te.isExtracting)?b("landing.extracting"):b("landing.send")})]})]}),l.jsxs("div",{onClick:()=>B.current?.click(),className:`mt-3 border-2 border-dashed rounded-xl px-5 py-3.5 cursor-pointer transition-all text-center bg-card/60 backdrop-blur ${q?"border-accent bg-accent/5 ring-2 ring-accent/20":"border-line hover:border-accent/40 hover:bg-accent/5"}`,children:[l.jsxs("div",{className:"flex items-center justify-center gap-2 text-sm text-ink-muted font-medium",children:[l.jsx(Wl,{size:15,strokeWidth:1.75,className:"text-accent"})," ",b("landing.docStart")]}),l.jsx("p",{className:"text-2xs text-ink-faint mt-1.5",children:b("landing.docFormats")}),l.jsx("p",{className:"text-2xs text-ink-faint mt-0.5",children:b("landing.docPrivacy")})]}),!!window.desktopSessions&&l.jsxs("button",{onClick:()=>U(!0),className:"w-full mt-3 bg-card/60 backdrop-blur border border-line rounded-xl px-5 py-3.5 hover:border-accent/40 hover:bg-accent/5 transition-all text-center","data-landing-atlas":!0,children:[l.jsxs("div",{className:"flex items-center justify-center gap-2 text-sm text-ink-muted font-medium",children:[l.jsx(GH,{size:15,strokeWidth:1.75,className:"text-accent shrink-0"}),l.jsx("span",{children:b("landing.atlasStart")}),l.jsx(FH,{size:13,strokeWidth:1.75,className:"text-accent shrink-0"})]}),l.jsx("p",{className:"text-2xs text-ink-faint mt-1.5",children:b("landing.atlasDesc")})]}),l.jsx("input",{ref:B,type:"file",multiple:!0,accept:w0,className:"hidden",onChange:te=>{_e(te.target.files||[]),te.target.value=""}}),Y&&l.jsx(Qv,{onClose:()=>U(!1),onSwitched:()=>{U(!1),st()}}),(!xt||(xt.models?.length??0)===0)&&l.jsxs("div",{className:"mt-3 bg-card/60 backdrop-blur border border-line rounded-xl px-5 py-3.5 text-center","data-quick-connect":!0,children:[l.jsxs("div",{className:"flex items-center justify-center gap-2 text-sm text-ink-muted font-medium",children:[l.jsx(b0,{size:15,strokeWidth:1.75,className:"text-accent shrink-0"})," ",b("landing.quickTitle")]}),l.jsx("p",{className:"text-2xs text-ink-faint mt-1.5",children:b("landing.quickDesc")}),l.jsxs("div",{className:"mt-2.5 flex items-center justify-center flex-wrap gap-2",children:[Ee==="zh"&&l.jsx("button",{onClick:()=>{ce.getState().setApiKeyPresetHint("zhipu"),ce.getState().setApiKeyModalOpen(!0)},className:"text-2xs bg-accent/10 text-accent hover:bg-accent/20 font-medium px-3 py-1.5 rounded-lg transition-colors shrink-0","data-quick-zhipu":!0,children:b("landing.quickZhipu")}),l.jsx("button",{onClick:()=>{$M()},className:"text-2xs bg-accent/10 text-accent hover:bg-accent/20 font-medium px-3 py-1.5 rounded-lg transition-colors shrink-0","data-quick-primary":!0,children:b("landing.quickOpenRouter")}),l.jsx("button",{onClick:()=>ce.getState().setApiKeyModalOpen(!0),className:"text-2xs text-ink-muted hover:text-ink hover:bg-wash font-medium px-3 py-1.5 rounded-lg transition-colors shrink-0",children:b("landing.quickOther")})]}),l.jsx("button",{onClick:()=>ce.getState().setApiKeyModalOpen(!0),className:"mt-2 mx-auto text-2xs text-ink-faint hover:text-accent transition-colors block","data-quick-subs":!0,children:b("landing.quickSubs")})]}),l.jsx("div",{className:"grid grid-cols-3 gap-3 mt-6",children:[{icon:ii,title:"landing.feature1.title",desc:"landing.feature1.desc"},{icon:nE,title:"landing.feature2.title",desc:"landing.feature2.desc"},{icon:JA,title:"landing.feature3.title",desc:"landing.feature3.desc"}].map(({icon:te,title:pe,desc:Ae})=>l.jsxs("div",{className:"bg-card/60 backdrop-blur border border-line rounded-xl px-4 py-3.5",children:[l.jsx(te,{size:16,strokeWidth:1.75,className:"text-accent mb-2"}),l.jsx("h3",{className:"text-xs font-semibold text-ink mb-1",children:b(pe)}),l.jsx("p",{className:"text-2xs text-ink-faint leading-relaxed",children:b(Ae)})]},pe))}),l.jsxs("div",{className:"text-center mt-6 flex items-center justify-center gap-5",children:[l.jsxs("button",{onClick:Ke,className:"text-xs text-accent hover:text-accent-strong font-medium transition-colors inline-flex items-center gap-1.5",children:[l.jsx(nE,{size:14,strokeWidth:1.75})," ",b("landing.loadExample")]}),l.jsxs("button",{onClick:()=>y(!0),className:"text-xs text-ink-muted hover:text-accent transition-colors inline-flex items-center gap-1.5",children:[l.jsx(Q5,{size:14,strokeWidth:1.75})," ",b("landing.howItWorks")]})]})]})]}),!Nt&&l.jsx(Mce,{onSwitched:st}),($||tt)&&!Nt&&l.jsxs("div",{className:"absolute top-[38%] -translate-y-1/2 left-4 z-10 flex flex-col gap-1.5 bg-card/90 backdrop-blur border border-line rounded-xl p-1.5 shadow-sm",children:[!tt&&l.jsx("button",{onClick:()=>Dt(ie(null)),draggable:!0,onDragStart:te=>{te.dataTransfer.setData("application/thoughtdag-content","ask"),te.dataTransfer.effectAllowed="copy"},title:b("palette.askTitle"),className:"w-9 h-9 rounded-lg flex items-center justify-center text-accent hover:bg-accent/10 transition-colors cursor-grab",children:l.jsx(Ol,{size:17,strokeWidth:1.75})}),l.jsx("button",{onPointerDown:te=>Qe(te,pe=>gs("note",ie(pe))),title:b("palette.noteTitle"),className:"w-9 h-9 rounded-lg flex items-center justify-center text-amber-600 hover:bg-amber-500/10 transition-colors",children:l.jsx(ui,{size:17,strokeWidth:1.75})}),l.jsx("button",{onPointerDown:te=>Qe(te,pe=>gs("file",ie(pe))),title:b("palette.fileTitle"),className:"w-9 h-9 rounded-lg flex items-center justify-center text-ink-muted hover:bg-wash transition-colors",children:l.jsx(Bs,{size:17,strokeWidth:1.75})}),l.jsx("button",{onPointerDown:te=>Qe(te,pe=>Rt(ie(pe))),title:b("palette.frameTitle"),className:"w-9 h-9 rounded-lg flex items-center justify-center text-ink-muted hover:bg-wash transition-colors",children:l.jsx(Yb,{size:17,strokeWidth:1.75})})]}),Nt&&l.jsxs("div",{className:"absolute top-4 z-10 flex gap-1.5 items-center transition-[right] duration-200",style:{right:et?It+Yd+12:16},"data-top-toolbar":!0,children:[l.jsxs("span",{className:"bg-card/90 backdrop-blur border border-line rounded-lg h-8 px-3 flex items-center gap-1.5 shadow-sm text-ink-muted text-xs font-medium","data-viewer-badge":!0,children:[l.jsx(g0,{size:14,strokeWidth:1.75})," ",b("viewer.badge")]}),l.jsx("button",{onClick:()=>O(!0),className:"bg-card/90 backdrop-blur border border-line rounded-lg w-8 h-8 flex items-center justify-center shadow-sm hover:bg-wash transition-colors text-ink-muted hover:text-accent",title:b("search.entryTitle"),"data-search-entry":!0,children:l.jsx(y0,{size:15,strokeWidth:1.75})}),l.jsx(YN,{}),l.jsx("button",{onClick:()=>gy(),className:"bg-card/90 backdrop-blur border border-line rounded-lg w-8 h-8 flex items-center justify-center shadow-sm hover:bg-wash transition-colors text-ink-muted hover:text-accent",title:b("viewer.downloadJson"),children:l.jsx(Ll,{size:15,strokeWidth:1.75})}),l.jsx("a",{href:"https://github.com/chenxiachan/thoughtdag",target:"_blank",rel:"noreferrer",className:"bg-ink text-white rounded-lg h-8 px-3 flex items-center gap-1.5 shadow-sm hover:bg-ink/85 transition-colors text-xs font-medium",children:b("viewer.openApp")})]}),!Nt&&l.jsxs("div",{className:"absolute top-4 z-10 flex gap-1.5 items-center transition-[right] duration-200",style:{right:et?It+Yd+12:16},"data-top-toolbar":!0,children:[tt&&l.jsxs(l.Fragment,{children:[l.jsxs("button",{onClick:()=>nt("human"),className:"bg-card/90 backdrop-blur border border-warm/40 rounded-lg h-8 px-3 flex items-center gap-1.5 shadow-sm hover:bg-warm/10 transition-colors text-warm text-xs font-medium",children:[l.jsx(Ol,{size:14,strokeWidth:1.75})," ",b("paradigm.addHuman")]}),l.jsxs("button",{onClick:()=>nt("prompt"),className:"bg-card/90 backdrop-blur border border-accent/40 rounded-lg h-8 px-3 flex items-center gap-1.5 shadow-sm hover:bg-accent/10 transition-colors text-accent text-xs font-medium",children:[l.jsx(Qo,{size:14,strokeWidth:1.75})," ",b("paradigm.addPrompt")]}),l.jsxs("button",{onClick:()=>{Be()},title:b("paradigm.instantiateTitle"),className:"bg-ink text-white rounded-lg h-8 px-3 flex items-center gap-1.5 shadow-sm hover:bg-ink/85 transition-colors text-xs font-medium",children:["▶ ",b("paradigm.instantiate")]})]}),!tt&&l.jsx(Due,{}),!tt&&l.jsx(IM,{}),!$&&l.jsx("button",{onClick:()=>ce.getState().setApiKeyModalOpen(!0),className:"bg-card/90 backdrop-blur border border-line rounded-lg w-8 h-8 flex items-center justify-center shadow-sm hover:bg-wash transition-colors text-ink-faint hover:text-accent",title:b("apikey.entryTitle"),"data-apikey-entry":!0,children:l.jsx(b0,{size:15,strokeWidth:1.75})}),bt>0&&!tt&&l.jsxs("button",{onClick:()=>{const{nodes:te,edges:pe}=se.getState(),Oe=Qr(se.getState()).reduce((ct,ht)=>{const Et=te.map(mn=>mn.id===ht?{...mn,data:{...mn.data,question:"",response:""}}:mn),{layerTokens:un}=vr(ht,Et,pe),en=te.find(mn=>mn.id===ht)?.data.question??"";return ct+un.material+un.reference+un.chain+_n(en)},0);oi({title:b("replay.confirmTitle"),message:ve(b("replay.confirmMsg"),{n:bt,tok:Oe.toLocaleString()}),confirmLabel:b("replay.confirmBtn")}).then(ct=>{ct&&se.getState().replayStale()})},className:"bg-amber-500/10 backdrop-blur border border-amber-500/40 rounded-lg h-8 px-3 flex items-center gap-1.5 shadow-sm hover:bg-amber-500/20 transition-colors text-amber-600 text-xs font-medium",title:b("replay.chipTitle"),children:[l.jsx(lU,{size:14,strokeWidth:1.75})," ",bt]}),$&&Jn.length>0&&l.jsxs("div",{ref:va,className:"relative",children:[l.jsx("button",{onClick:()=>In(te=>!te),className:`bg-card/90 backdrop-blur border rounded-lg w-8 h-8 flex items-center justify-center shadow-sm transition-colors ${Jt?"border-accent/40 text-accent":"border-line text-ink-faint hover:bg-wash"}`,title:b("toolbar.frames"),children:l.jsx(Yb,{size:15,strokeWidth:1.75})}),Jt&&l.jsx("div",{className:"absolute right-0 top-full mt-1.5 bg-card border border-line rounded-xl shadow-lg py-1 w-[230px] max-h-[320px] overflow-y-auto z-30 animate-fade-in",children:Jn.map(te=>l.jsxs("button",{onClick:()=>{In(!1),oe.current?.fitBounds({x:te.position.x,y:te.position.y,width:te.width??640,height:te.height??420},{duration:400,padding:.15})},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2",children:[l.jsx("span",{className:`w-2.5 h-2.5 rounded-sm shrink-0 ${(Gd[te.data.frameColor??"gray"]??Gd.gray).dot}`}),l.jsx("span",{className:"truncate",children:te.data.question||b("frame.untitled")})]},te.id))})]}),$&&l.jsx("button",{onClick:()=>A(te=>!te),className:`bg-card/90 backdrop-blur border border-line rounded-lg w-8 h-8 flex items-center justify-center shadow-sm hover:bg-wash transition-colors ${_?"text-accent":"text-ink-faint hover:text-accent"}`,title:b("chat.entryTitle"),"data-chat-entry":!0,children:l.jsx(Ol,{size:15,strokeWidth:1.75})}),$&&l.jsx("button",{onClick:()=>O(!0),className:"bg-card/90 backdrop-blur border border-line rounded-lg w-8 h-8 flex items-center justify-center shadow-sm hover:bg-wash transition-colors text-ink-faint hover:text-accent",title:b("search.entryTitle"),"data-search-entry":!0,children:l.jsx(y0,{size:15,strokeWidth:1.75})}),l.jsx(YN,{}),$&&!tt&&l.jsx(tce,{showTrigger:!1,openPing:Fn,onLocate:te=>{const pe=se.getState().nodes.find(Ae=>Ae.id===te);pe&&(d(te),Le(pe,{zoom:1}))}}),De&&!Nt&&l.jsxs("button",{onClick:()=>ce.getState().setCondenseDialogOpen(!0),className:"bg-card/90 backdrop-blur border border-accent/50 rounded-lg h-8 px-2 flex items-center justify-center gap-1.5 shadow-sm hover:bg-wash transition-colors text-accent",title:ve(b("condense.entryBuilding"),{i:String(ze.current),n:String(ze.total)}),"data-condense-entry":!0,children:[l.jsx(tn,{size:14,strokeWidth:1.75,className:"animate-spin"}),l.jsxs("span",{className:"text-2xs font-mono",children:[ze.current,"/",ze.total]})]}),Xp&&l.jsx("button",{onClick:()=>ce.getState().setBackupDialogOpen(!0),className:"bg-card/90 backdrop-blur border border-line rounded-lg w-8 h-8 flex items-center justify-center shadow-sm hover:bg-wash transition-colors text-ink-muted hover:text-accent",title:b("backup.dialogTitle"),"data-backup-entry":!0,children:l.jsx(WA,{size:15,strokeWidth:1.75})}),l.jsxs("div",{ref:Xa,className:"relative",children:[l.jsx("button",{onClick:()=>an(te=>!te),className:`bg-card/90 backdrop-blur border rounded-lg w-8 h-8 flex items-center justify-center shadow-sm transition-colors ${_a?"border-accent/40 text-accent":"border-line text-ink-faint hover:bg-wash"}`,title:b("toolbar.more"),"data-toolbar-more":!0,children:l.jsx(qA,{size:15,strokeWidth:1.75})}),_a&&l.jsxs("div",{className:"absolute right-0 top-full mt-1.5 bg-card border border-line rounded-xl shadow-lg py-1 w-[220px] z-30 animate-fade-in",children:[$&&l.jsxs("button",{onClick:()=>{an(!1),E(!w)},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5",title:b(w?"toolbar.showAnnotations":"toolbar.hideAnnotations"),children:[l.jsx(ui,{size:14,strokeWidth:1.75,className:`shrink-0 ${w?"text-accent":"text-ink-faint"}`})," ",b(w?"toolbar.menuAnnotationsShow":"toolbar.menuAnnotationsHide")]}),l.jsxs("button",{onClick:()=>{an(!1),N(!v)},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5",title:b("toolbar.wheelPansTitle"),"aria-pressed":v,"data-wheel-pans":!0,children:[l.jsx($F,{size:14,strokeWidth:1.75,className:`shrink-0 ${v?"text-accent":"text-ink-faint"}`})," ",l.jsx("span",{className:"flex-1",children:b("toolbar.menuWheelPans")}),v&&l.jsx("span",{className:"text-accent",children:"✓"})]}),$&&l.jsxs("button",{onClick:()=>{an(!1),oi({title:b("confirm.relayoutTitle"),message:b("confirm.relayoutMsg"),confirmLabel:b("toolbar.relayout")}).then(te=>{te&&(x(),setTimeout(()=>oe.current?.fitView({duration:400,padding:.15}),50))})},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5",children:[l.jsx(rU,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("toolbar.relayout")]}),K>0&&l.jsxs("button",{onClick:()=>{an(!1),ce.getState().setHighlightsOverviewOpen(!0)},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5",title:b("hlov.entryTitle"),"data-hlov-entry":!0,children:[l.jsx(x0,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",ve(b("hlov.entry"),{n:K})]}),J>0&&l.jsxs("button",{onClick:()=>{an(!1),ce.getState().setMaterialsOverviewOpen(!0)},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5",title:b("matov.entryTitle"),"data-matov-entry":!0,children:[l.jsx(Bs,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",ve(b("matov.entry"),{n:J})]}),$&&l.jsx("div",{className:"border-t border-line/60 my-1"}),$&&!tt&&!Nt&&l.jsxs("button",{onClick:()=>{an(!1),ce.getState().setCondenseDialogOpen(!0)},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5",title:b("condense.entryTitle"),children:[l.jsx(Sp,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("condense.title"),"…"]}),$&&!tt&&l.jsxs("button",{onClick:()=>{an(!1),Wn(te=>te+1)},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5",title:b("toolbar.diagnose"),"data-menu-diagnose":!0,children:[l.jsx(e8,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("toolbar.menuDiagnose")]}),$&&!tt&&l.jsxs("button",{onClick:()=>{an(!1),(async()=>{const{nodes:te,edges:pe}=se.getState(),{confirmIfSensitive:Ae}=await pt(async()=>{const{confirmIfSensitive:ct}=await import("./sensitive-scan-ULbRwlLo.js");return{confirmIfSensitive:ct}},[]);if(!await Ae(te))return;const Oe=await Wq(te,pe);await navigator.clipboard.writeText(Oe).catch(()=>{}),ce.getState().setShareDialogUrl(Oe)})()},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5","data-share-link":!0,title:b("viewer.shareTitle"),children:[l.jsx(PU,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("toolbar.menuShare")]}),$&&l.jsxs("button",{onClick:()=>{an(!1),tt?wG():gy()},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5","data-menu-export":!0,children:[l.jsx(Ll,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b(tt?"paradigm.exportParadigm":"switcher.exportBackup")]}),Z&&l.jsxs("button",{onClick:()=>{an(!1),TG()},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5",title:b("toolbar.exportEventsTitle"),children:[l.jsx(zs,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("toolbar.exportEvents")]}),$&&l.jsx("div",{className:"border-t border-line/60 my-1"}),l.jsxs("div",{className:"px-3 pt-2 pb-1","data-appearance-lighting":!0,children:[l.jsx("div",{className:"text-2xs text-ink-faint mb-1.5",children:b("appearance.lighting")}),l.jsx("div",{className:"flex rounded-lg border border-line overflow-hidden text-2xs",children:[["light",b("appearance.light")],["dark",b("appearance.dark")],["system",b("appearance.system")]].map(([te,pe],Ae)=>l.jsx("button",{onClick:()=>qi.getState().setLighting(te),className:`flex-1 px-1 py-1.5 transition-colors ${Ae>0?"border-l border-line":""} ${ae===te?"bg-accent/10 text-accent font-medium":"text-ink-muted hover:bg-wash"}`,children:pe},te))})]}),l.jsxs("div",{className:"px-3 pt-1 pb-2","data-appearance-paper":!0,children:[l.jsx("div",{className:"text-2xs text-ink-faint mb-1.5",children:b("appearance.paper")}),l.jsx("div",{className:"flex rounded-lg border border-line overflow-hidden text-2xs",children:[["plain",b("appearance.plain")],["grid",b("appearance.grid")]].map(([te,pe],Ae)=>l.jsx("button",{onClick:()=>qi.getState().setPaper(te),className:`flex-1 px-1 py-1.5 transition-colors ${Ae>0?"border-l border-line":""} ${ye===te?"bg-accent/10 text-accent font-medium":"text-ink-muted hover:bg-wash"}`,children:pe},te))})]}),l.jsx("div",{className:"border-t border-line/60 my-1"}),l.jsxs("button",{onClick:()=>{an(!1),ce.getState().setMemoryManagerOpen(!0)},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5",title:b("memory.entryTitle"),children:[l.jsx(KH,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("memory.managerTitle")]}),l.jsxs("button",{onClick:()=>{an(!1),y(!0)},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5",children:[l.jsx(Q5,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("landing.howItWorks")]}),Bn&&l.jsxs("button",{onClick:()=>{an(!1);const te=wa?`dsh-thoughtdag@${Bn.latest}`:Xy(Bn.latest);navigator.clipboard.writeText(te).then(()=>We("success",b(wa?"plugin.updateCopiedDesktop":"plugin.updateCopied")))},className:"w-full text-left px-3 py-2 text-xs text-accent hover:bg-wash transition-colors flex items-center gap-2.5",title:wa?ve(b("plugin.updateHintDesktop"),{pkg:`dsh-thoughtdag@${Bn.latest}`}):ve(b("plugin.updateHint"),{cmd:Xy(Bn.latest)}),"data-plugin-update":!0,children:[l.jsx(Ll,{size:14,strokeWidth:1.75,className:"shrink-0"})," ",ve(b("plugin.updateAvailable"),{v:Bn.latest})]}),l.jsxs("button",{onClick:()=>{an(!1),ce.getState().setReleaseNotesOpen(!0)},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5","data-open-release-notes":!0,children:[l.jsx(Ep,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("releaseNotes.entry")]})]})]}),l.jsx("button",{onClick:s,disabled:p<=0,className:"bg-card/90 backdrop-blur border border-line rounded-lg w-8 h-8 flex items-center justify-center shadow-sm hover:bg-wash transition-colors disabled:opacity-20 disabled:cursor-not-allowed",title:b("canvas.undo"),children:l.jsx(a8,{size:16,strokeWidth:1.75})}),l.jsx("button",{onClick:o,disabled:p>=m.length-1,className:"bg-card/90 backdrop-blur border border-line rounded-lg w-8 h-8 flex items-center justify-center shadow-sm hover:bg-wash transition-colors disabled:opacity-20 disabled:cursor-not-allowed",title:b("canvas.redo"),children:l.jsx(TU,{size:16,strokeWidth:1.75})})]}),St&&!Nt&&l.jsx(jle,{}),!Nt&&l.jsx(Jle,{open:_,onClose:()=>A(!1),onLocate:te=>{const pe=se.getState().nodes.find(Ae=>Ae.id===te);pe&&(d(te),Le(pe,{zoom:1}))}}),l.jsx(Vle,{open:I,onClose:()=>O(!1),onLocate:te=>{const pe=se.getState().nodes.find(Ae=>Ae.id===te);pe&&(d(te),Le(pe,{zoom:1}))}}),Dn&&l.jsx(Ple,{x:Dn.x,y:Dn.y,nodeId:Dn.nodeId,onClose:()=>qa(null)}),l.jsx(Hle,{onLocate:te=>{const pe=se.getState().nodes.find(Ae=>Ae.id===te);pe&&(d(te),Le(pe,{zoom:1}))}}),l.jsx(que,{onLocate:te=>{const pe=se.getState().nodes.find(Ae=>Ae.id===te);pe&&(d(te),Le(pe,{zoom:1}))}}),l.jsx(zle,{onLocate:te=>{const pe=se.getState().nodes.find(Ae=>Ae.id===te);pe&&(d(te),Le(pe,{zoom:1}))}}),$t&&l.jsx("div",{className:"fixed z-50 bg-card border border-line rounded-xl shadow-lg py-1 min-w-[120px]",style:{left:$t.x,top:$t.y},children:l.jsxs("button",{onClick:()=>oa($t.edgeId),className:"w-full text-left px-4 py-2 text-sm text-red-600 hover:bg-red-50 transition-colors flex items-center gap-1.5",children:[l.jsx(rr,{size:14,strokeWidth:1.75}),b("canvas.deleteEdge")]})})]}),l.jsx(Sue,{onFocusSegment:te=>{const pe=oe.current,Ae=se.getState().nodes.filter(mn=>te.includes(mn.id));if(!pe||Ae.length===0)return;const Oe=Ae.map(mn=>mn.position.x),ct=Ae.map(mn=>mn.position.y),ht=Math.min(...Oe),Et=Math.min(...ct),un=Math.max(...Oe)+520-ht,en=Math.max(...ct)+240-Et;pe.fitBounds({x:ht,y:Et,width:un+700,height:en},{duration:350,padding:.15})}}),et&&l.jsx(Ile,{onFocusNode:te=>{const pe=e.find(Ae=>Ae.id===te);pe&&Le(pe,{duration:300})}}),l.jsx(hce,{onLocate:te=>{const pe=se.getState().nodes.find(Ae=>Ae.id===te);pe&&(d(te),Le(pe,{zoom:1}))}})]})}function Kue({panelShiftWidth:e}){const t=Z0(),n=Tt(),a=Zl(),r=se(d=>d.nodes.length),s=se(d=>d.nodes),o=R.useMemo(()=>{let d=null,h="";for(const m of s){if(m.data.stepKind&&m.data.stepKind!=="human"&&m.data.stepKind!=="prompt")continue;const p=[m.data.lastGeneratedAt,m.data.askedAt,m.data.createdAt,...m.data.editedAts??[]].filter(Boolean).sort().pop();p&&p>h&&(h=p,d=m)}return d?{node:d,at:h}:null},[s]);if(Nt||t==="work"||r<2)return null;const u=()=>{if(!o)return;ce.getState().setBeaconNodeId(null);const{node:d}=o;a.setCenter(d.position.x+260,d.position.y+110,{zoom:1,duration:1100}),window.setTimeout(()=>{se.getState().setSelectedNodeId(d.id),ce.getState().setPanelOpen(!0),window.setTimeout(()=>{a.setCenter(d.position.x+260+cp(d.id)/2,d.position.y+110,{zoom:1,duration:300})},60)},1150),window.setTimeout(()=>{We("success",n("continue.arrived"),12e3,{label:n("continue.summarize"),run:()=>{jM(d.id)}})},1550)};return l.jsxs("div",{className:"absolute bottom-6 z-10 flex items-center gap-2 -translate-x-1/2 transition-[left] duration-300",style:{left:`calc((100% - ${e}px) / 2)`},"data-map-dock":!0,children:[l.jsxs("button",{onClick:()=>ce.getState().setThoughtMapOpen(!0),"data-tmap-pill":!0,className:"flex items-center gap-2 bg-card/95 backdrop-blur border border-line-strong rounded-full px-5 py-2.5 text-sm text-ink shadow-lg hover:border-accent/40 hover:text-accent transition-colors",children:[l.jsx(p2,{size:16,strokeWidth:1.75})," ",n("tmap.export")]}),o&&l.jsxs("button",{onClick:u,onMouseEnter:()=>ce.getState().setBeaconNodeId(o.node.id),onMouseLeave:()=>ce.getState().setBeaconNodeId(null),title:n("continue.buttonTitle"),"data-continue-pill":!0,className:"flex items-center gap-2 bg-accent text-white rounded-full px-5 py-2.5 text-sm shadow-lg hover:bg-accent-strong transition-colors",children:[l.jsx(_U,{size:16,strokeWidth:1.75})," ",n("continue.button")]})]})}function Xue(){const e=Z0(),t=fn(n=>n.transform[2]);return R.useEffect(()=>{document.querySelector(".react-flow")?.setAttribute("data-zoom-tier",e)},[e]),R.useEffect(()=>{document.querySelector(".react-flow")?.style.setProperty("--tdag-zoom",String(t))},[t]),null}Qoe();const ew="/thoughtdag/api";window.desktopSessions||j8(ew);pt(()=>Promise.resolve().then(()=>jue),void 0).then(e=>e.bootPluginUpdateCheck(ew));if(!window.desktopAgents){const e=ew;pt(()=>import("./http-bridge-BnB37T8x.js"),[]).then(async t=>{await t.installAgentsHttpBridge(e)&&window.dispatchEvent(new CustomEvent("td:agents-ready"))})}Nt?Gq():($7(),navigator.storage?.persist&&navigator.storage.persist(),pt(()=>Promise.resolve().then(()=>fue),void 0).then(e=>e.bootAutoBackup()));pt(()=>import("./update-check-DwksTqSo.js"),[]).then(e=>e.bootUpdateCheck());window.addEventListener("hashchange",()=>{window.location.hash.startsWith("#view=")!==Nt&&window.location.reload()});fD.createRoot(document.getElementById("root")).render(l.jsx(R.StrictMode,{children:l.jsx(Gue,{})}));export{L0 as A,yr as B,sG as C,Jue as D,Z7 as E,Na as F,q$ as I,pt as _,Ne as a,se as b,sn as c,Vi as d,W7 as e,ve as f,Wi as g,Pr as h,Nt as i,Tu as j,Ip as k,my as l,uG as m,En as n,lG as o,ks as p,Z2 as q,cG as r,el as s,We as t,ce as u,oi as v,ede as w,Qr as x,Zue as y,Que as z};