dsh-thoughtdag 0.4.7 → 0.4.8

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 (20) hide show
  1. package/dist-app/assets/{canonical-D2XBb2dX.js → canonical-HRd1ZNsL.js} +2 -2
  2. package/dist-app/assets/{canvas-record-GBNDUaVp.js → canvas-record-sMlQAe86.js} +1 -1
  3. package/dist-app/assets/{claude-code-session-KqpMLSSi.js → claude-code-session-CNy9Vlyr.js} +1 -1
  4. package/dist-app/assets/{codex-session-Dcy2uWFk.js → codex-session-IGOBB6wr.js} +1 -1
  5. package/dist-app/assets/{dsh-session-DtUFFQiI.js → dsh-session-C33CwagF.js} +1 -1
  6. package/dist-app/assets/{experiment-loop-DmwbMQzX.js → experiment-loop-LWCgLcKh.js} +1 -1
  7. package/dist-app/assets/{index-XXbBaf-t.js → index-BlhS4j5g.js} +1 -1
  8. package/dist-app/assets/{index-NvCD8Rvo.js → index-CrxLUdb9.js} +3 -3
  9. package/dist-app/assets/{index-zDvcuppH.js → index-CxfScRHS.js} +10 -10
  10. package/dist-app/assets/{index-DalA8OYo.js → index-D_9Fas4A.js} +1 -1
  11. package/dist-app/assets/{live-mirror-DHhvAkDw.js → live-mirror-DrVBjNxd.js} +2 -2
  12. package/dist-app/assets/{pi-session-BQNKkZYe.js → pi-session-64OkE2In.js} +1 -1
  13. package/dist-app/assets/{sensitive-scan-BVopW_mj.js → sensitive-scan-BjlPCfxy.js} +1 -1
  14. package/dist-app/assets/{session-handoff-CdTJCZJl.js → session-handoff-TXfFS7pB.js} +2 -2
  15. package/dist-app/assets/{shared-DWUtbV9j.js → shared-Bad_vakP.js} +1 -1
  16. package/dist-app/assets/{turndown-plugin-gfm.cjs-DmDDHBxg.js → turndown-plugin-gfm.cjs-DXKuEPQs.js} +1 -1
  17. package/dist-app/assets/{update-check-DFw8Y8PB.js → update-check-BCL5Q3Vc.js} +1 -1
  18. package/dist-app/index.html +1 -1
  19. package/lib/index.js +5 -3
  20. package/package.json +1 -1
@@ -46,7 +46,7 @@ Economist: You analyze through incentives and trade-offs...`,"fanout.confirm":"F
46
46
  `);m=k.pop()||"";for(const T of k){const w=T.trim();if(!w.startsWith("data: "))continue;const _=w.slice(6);if(_==="[DONE]")continue;let A;try{A=JSON.parse(_)}catch{continue}if(A.error){const M=typeof A.error=="string"?A.error:A.error.message;throw new Error(M||"Upstream stream error")}const C=A.choices?.[0];if(!C)continue;const O=C.delta;O?.content&&(p+=O.content,a(O.content));const D=O?.reasoning??O?.reasoning_content;D&&r(D);for(const M of O?.annotations??[]){const N=M.url_citation;N?.url&&!s.has(N.url)&&s.set(N.url,{title:N.title||N.url,url:N.url,media:"Web"})}C.finish_reason&&(x=C.finish_reason)}}return{text:p,finishReason:x}}async function GB(e,t,n,a,r,s,l,c){const d=N7(n,s),h=Rb(e.baseURL)&&c!==!1,m=new Map;let p="",x="";const b=k=>{p+=k,a(k,p)},y=k=>{x+=k,l?.onReasoning?.(k,x)};try{let k=await o5(e,h?`${t}:online`:t,d,b,y,m,r);if(h&&p.length===0&&(k=await o5(e,t,d,b,y,m,r)),p.length===0)throw new Error(`Model produced no text (finish: ${k.finishReason}, model: ${t}${h?" via :online":""})`);return m.size>0&&l?.onSources?.([...m.values()]),p}catch(k){throw C7(k)}}async function YB(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:N7(n,a)})});if(!r.ok){const l=await r.json().catch(()=>null);throw new Error(l?.error?.message||`HTTP ${r.status}`)}return(await r.json()).choices?.[0]?.message?.content??""}catch(r){throw C7(r)}}const $B=`${Fi}/api/claude`,_7=()=>{const e=ai();return e.length>0?e:void 0},KB=`${Fi}/api/stream`,XB=`${Fi}/api/pdf-extract`,QB=`${Fi}/api/approvals`;async function ZB(e,t){try{return(await fetch(`${QB}/${encodeURIComponent(e)}`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"same-origin",body:JSON.stringify({outcome:t})})).ok}catch{return!1}}async function JB(e){const t=await fetch(XB,{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(yl(n,`HTTP ${t.status}`))}return t.json()}async function eH(e){try{const t=await fetch(`${Fi}/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(yl(n,`HTTP ${t.status}`))}return t.json()}catch(t){throw jb(t)}}function jb(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 M7(e,t){if(!t?.length)return t;const n=await Do(),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 I7(e,t){if(!t?.length)return;const n=await Do(),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(Ie("error.textOnlyModelImages"))}async function Oo(e,t,n){const a=n||xe.getState().selectedModel||void 0;t=await M7(a,t);const r=Lb();if(r&&a)return await I7(a,t),YB(r,a,e,t);try{const s=await fetch($B,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({messages:e,images:t?.length?t:void 0,model:n||xe.getState().selectedModel||void 0,providers:_7()})});if(!s.ok){const c=await s.json().catch(()=>({error:"Unknown error"}));throw new Error(yl(c,`HTTP ${s.status}`))}return(await s.json()).text}catch(s){throw jb(s)}}async function D7(e,t,n,a,r,s,l,c){const d=l||xe.getState().selectedModel||void 0;a=await M7(d,a);let h=!1;const m={...r,onRerouted:(k,T)=>{h=!0,r?.onRerouted?.(k,T)}},p=async(k,T)=>{const w=Lb();return w&&d?(await I7(d,k),r?.onDispatch?.({messages:e,images:k??[],model:d,toolPrefs:s??{},lane:"direct"}),GB(w,d,e,T,n,k,m,s?.web)):(r?.onDispatch?.({messages:e,images:k??[],model:d??"",toolPrefs:s??{},lane:"proxy"}),y(k,T))},x=d?zB(d):void 0,b=!!d&&ai().some(k=>k.models.some(T=>T.id===d));if(a?.length&&d&&b&&x!==!1){const k=d.split("/").pop()??d,T=(_,A)=>{BB(d,_)&&(Xd(ai()).then(mm).catch(()=>{}),Ke("info",Ue(Ie(A),{m:k})))};let w=!1;try{const _=await p(a,(A,C)=>{w=!0,t(A,C)});return x===void 0&&!h&&_.trim()&&T(!0,"toast.visionLearnedTrue"),_}catch(_){if(_ instanceof DOMException&&_.name==="AbortError"||w||h)throw _;if(x===!0){const C=_ instanceof Error?_.message:String(_);throw new Error(`${C} ${Ie("error.visionDeclaredHint")}`)}const A=await p(void 0,t);return A.trim()&&T(!1,"toast.visionLearnedFalse"),A}}return p(a,t);async function y(k,T){try{const w=await fetch(KB,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({messages:e,images:k?.length?k:void 0,webSearch:s?.web,scholarSearch:s?.scholar,mcpTools:s?.mcp,...xe.getState().searchEnginePref!=="server"?{searchEngine:xe.getState().searchEnginePref}:{},...xe.getState().anysearchKey?{anysearchKey:xe.getState().anysearchKey}:{},model:l||xe.getState().selectedModel||void 0,providers:_7(),...c?{harness:c}:{}}),signal:n});if(!w.ok){const M=await w.json().catch(()=>({error:"Unknown error"}));throw new Error(yl(M,`HTTP ${w.status}`))}const _=w.body.getReader(),A=new TextDecoder;let C="",O="",D="";for(;;){const{done:M,value:N}=await _.read();if(M)break;C+=A.decode(N,{stream:!0});const R=C.split(`
47
47
  `);C=R.pop()||"";for(const B of R){const U=B.trim();if(!U||!U.startsWith("data: "))continue;const Y=U.slice(6);if(Y!=="[DONE]")try{const Z=JSON.parse(Y);if(Z.error)throw new Error(yl(Z.error,"Upstream stream error"));Z.text&&(O+=Z.text,T(Z.text,O)),Z.reasoning&&(D+=Z.reasoning,m.onReasoning?.(Z.reasoning,D)),Z.tool?.query&&m.onToolCall?.(Z.tool.name,Z.tool.query),Z.gatewaySearch&&m.onGatewaySearch?.(),typeof Z.harnessSession=="string"&&m.onHarnessSession?.(Z.harnessSession,!!Z.continued),Z.harnessTurn?.session&&m.onHarnessTurn?.(Z.harnessTurn),Z.approval?.id&&m.onApproval?.(Z.approval),Z.approvalDecided?.id&&m.onApprovalDecided?.(Z.approvalDecided),Array.isArray(Z.sources)&&m.onSources?.(Z.sources),Z.rerouted?.to&&(Ke("info",Ue(Ie("toast.visionRerouted"),{from:Z.rerouted.from,to:Z.rerouted.to}),7e3),m.onRerouted?.(Z.rerouted.from,Z.rerouted.to)),Z.imageFallback?.model&&(Ke("info",Ue(Ie("toast.imagesAsText"),{model:Z.imageFallback.model}),9e3),m.onImageFallback?.(Z.imageFallback.model))}catch(Z){if(Z instanceof Error&&Z.message!==Y)throw Z}}}return O}catch(w){throw jb(w)}}}const Cx="att-content:",O7=e=>`${Cx}${e}`,R7=e=>e.type==="application/pdf"&&!!e.content&&!e.contentInVault;async function L7(e){return R7(e)?(await zr(O7(e.id),e.content),{...e,content:"",contentInVault:!0}):e}async function j7(e){return e.contentInVault?await bl(O7(e.id))??"":e.content}async function P7(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 l=await j7(s),c={...s,content:l};delete c.contentInVault,r.push(c)}t.push({...n,data:{...n.data,attachments:r}})}return t}async function Pb(e){const t=[];for(const n of e){const a=n.data.attachments;if(!a?.some(R7)){t.push(n);continue}const r=[];for(const s of a)r.push(await L7(s));t.push({...n,data:{...n.data,attachments:r}})}return t}async function tH(e){const t=await x7();let n=0;for(const a of t)typeof a!="string"||!a.startsWith(Cx)||e.has(a.slice(Cx.length))||(await jc(a),n++);return n}function nH(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,`
48
48
 
49
- `).trim()}const aH=/\.(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,rH=/\.x?html?$/i,iH=/\.(pptx?|key|odp|doc|rtf|odt|xlsx?|numbers|ods)$/i,_d="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 yc(e){return`${e.name}|${e.size}|${e.content?.substring(0,100)}`}function sH(e){return new Promise(t=>{const n=In(),a=new Date().toISOString(),r=e.type.startsWith("image/"),s=e.type==="application/pdf"||e.name.endsWith(".pdf"),l=e.type==="text/html"||rH.test(e.name),c=e.type.startsWith("text/")||aH.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 Kt(()=>import("./index-XXbBaf-t.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)}}):l?e.text().then(h=>{t({id:n,name:e.name,type:"text/html",size:e.size,addedAt:a,content:h})}):c?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 l5(e){const[t,n]=await Promise.all([Kt(()=>import("./pdf-gh-BrLFn.js"),[]),Kt(()=>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 oH=150;async function c5(e){const t=oH/72,n=[];for(let a=1;a<=e.numPages;a++){const r=document.createElement("canvas");try{const s=await e.getPage(a),l=s.getViewport({scale:t});r.width=Math.ceil(l.width),r.height=Math.ceil(l.height);const c=r.getContext("2d");if(!c)throw new Error("no 2d context");await s.render({canvasContext:c,viewport:l}).promise}catch{r.width=8,r.height=8}n.push(r.toDataURL("image/png").split(",")[1])}return n}async function Qd(e,t){if(iH.test(e.name)){Ke("info",`${e.name}: ${Ie("content.officeExportHint")}`);return}const n=await sH(e);if(!n)return;if(n.type==="text/html"){t.add({...n,isExtracting:!0});try{const{extractHtmlMaterial:r}=await Kt(async()=>{const{extractHtmlMaterial:l}=await Promise.resolve().then(()=>ON);return{extractHtmlMaterial:l}},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:nH(n.content),isExtracting:!1})}return}if(n.type!=="application/pdf"){t.add(n);return}const a=await L7(n);t.add({...a,isExtracting:!0});try{const r=await JB(n.content);if(!r.numPages&&!r.text?.trim())throw new Error("empty extraction result");const s=r.numPages||0;let l=r.images;if(!l?.length)try{const c=await l5(n.content);l=await c5(c),c.destroy()}catch{l=void 0}t.update(n.id,{extractedText:r.text,pageImages:l?.length?l:void 0,numPages:s,renderMode:s>Yw?"text-only":"full",isExtracting:!1})}catch{try{const r=await l5(n.content),s=[];for(let c=1;c<=r.numPages;c++)try{const h=await(await r.getPage(c)).getTextContent();s.push(h.items.map(m=>"str"in m?m.str:"").join(" "))}catch{s.push("")}let l;try{l=await c5(r)}catch{l=void 0}r.destroy(),t.update(n.id,{extractedText:s.join(`
49
+ `).trim()}const aH=/\.(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,rH=/\.x?html?$/i,iH=/\.(pptx?|key|odp|doc|rtf|odt|xlsx?|numbers|ods)$/i,_d="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 yc(e){return`${e.name}|${e.size}|${e.content?.substring(0,100)}`}function sH(e){return new Promise(t=>{const n=In(),a=new Date().toISOString(),r=e.type.startsWith("image/"),s=e.type==="application/pdf"||e.name.endsWith(".pdf"),l=e.type==="text/html"||rH.test(e.name),c=e.type.startsWith("text/")||aH.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 Kt(()=>import("./index-BlhS4j5g.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)}}):l?e.text().then(h=>{t({id:n,name:e.name,type:"text/html",size:e.size,addedAt:a,content:h})}):c?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 l5(e){const[t,n]=await Promise.all([Kt(()=>import("./pdf-gh-BrLFn.js"),[]),Kt(()=>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 oH=150;async function c5(e){const t=oH/72,n=[];for(let a=1;a<=e.numPages;a++){const r=document.createElement("canvas");try{const s=await e.getPage(a),l=s.getViewport({scale:t});r.width=Math.ceil(l.width),r.height=Math.ceil(l.height);const c=r.getContext("2d");if(!c)throw new Error("no 2d context");await s.render({canvasContext:c,viewport:l}).promise}catch{r.width=8,r.height=8}n.push(r.toDataURL("image/png").split(",")[1])}return n}async function Qd(e,t){if(iH.test(e.name)){Ke("info",`${e.name}: ${Ie("content.officeExportHint")}`);return}const n=await sH(e);if(!n)return;if(n.type==="text/html"){t.add({...n,isExtracting:!0});try{const{extractHtmlMaterial:r}=await Kt(async()=>{const{extractHtmlMaterial:l}=await Promise.resolve().then(()=>ON);return{extractHtmlMaterial:l}},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:nH(n.content),isExtracting:!1})}return}if(n.type!=="application/pdf"){t.add(n);return}const a=await L7(n);t.add({...a,isExtracting:!0});try{const r=await JB(n.content);if(!r.numPages&&!r.text?.trim())throw new Error("empty extraction result");const s=r.numPages||0;let l=r.images;if(!l?.length)try{const c=await l5(n.content);l=await c5(c),c.destroy()}catch{l=void 0}t.update(n.id,{extractedText:r.text,pageImages:l?.length?l:void 0,numPages:s,renderMode:s>Yw?"text-only":"full",isExtracting:!1})}catch{try{const r=await l5(n.content),s=[];for(let c=1;c<=r.numPages;c++)try{const h=await(await r.getPage(c)).getTextContent();s.push(h.items.map(m=>"str"in m?m.str:"").join(" "))}catch{s.push("")}let l;try{l=await c5(r)}catch{l=void 0}r.destroy(),t.update(n.id,{extractedText:s.join(`
50
50
 
51
51
  `).trim(),pageImages:l?.length?l:void 0,numPages:r.numPages,renderMode:r.numPages>Yw?"text-only":"full",isExtracting:!1})}catch{t.update(n.id,{isExtracting:!1})}}}const Bu="[*_`~()#>\\[\\]|-]*",lH="\\s+(?:(?:\\d{1,3}[.)]|[-*+>|]|#{1,6}|[-:|]{3,})\\s+)*";function zb(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(`${Bu}${lH}${Bu}${s}`):n.push(`${Bu}${s}`),a=!1}try{return new RegExp(Bu+n.join("")+Bu,"g")}catch{return null}}function cH(e,t){const n=zb(t);return n?n.test(e):!1}function lf(e,t){const n=e??[],a=n.filter(r=>cH(t,r.text));return a.length===n.length?n:a}function u5(e){const t=e.data.question.replace(/\s+/g," ").trim();return t.length>60?`${t.slice(0,60)}…`:t}function z7(e){const t=e.data.highlightMode||"off",n=e.data.highlights||[];if(t==="filter"&&n.length>0)return n.map(a=>a.text).join(`
52
52
 
@@ -58,7 +58,7 @@ ${Y}`:`[File: ${B.name} — HTML with no extractable text yet]`}),h.push(R(B))}e
58
58
  ${B.content}`}),h.push(R(B))}};for(const M of k)if(!M.data.archived&&(O(M,"material"),M.data.question)){const N=M.data.stepKind==="note"?`[Note]
59
59
  ${M.data.question}`:M.data.stepKind==="link"?`[Link snapshot: ${M.data.linkUrl??""} @ ${(M.data.linkFetchedAt??"").slice(0,10)}]
60
60
  ${M.data.question}`:M.data.question;c.push({role:"user",content:N}),h.push({layer:"material",nodeId:M.id,part:"question"})}b("material");for(const M of T)M.source.data.archived||(c.push({role:"user",content:Md(M)}),h.push({layer:"reference",refSourceId:M.source.id,part:"reference"}));b("reference");for(const M of w)if(!M.data.archived&&(O(M,"chain"),M.data.question&&(c.push({role:"user",content:M.data.question}),h.push({layer:"chain",nodeId:M.id,part:"question"})),M.data.response)){const N=z7(M);c.push({role:"assistant",content:y.has(M.id)?`${dH}
61
- ${N}`:N}),h.push({layer:"chain",nodeId:M.id,part:"response"})}a&&(c.push({role:"user",content:`[Regarding this passage: "${a}"]`}),h.push({layer:"branch",nodeId:e,part:"passage"})),b("chain");const D=H7(w,t);return D&&(c.unshift({role:"system",content:D}),h.unshift({layer:"system",part:"role"})),{messages:c,images:d,layerTokens:p,sources:h,imageSources:m}}function h5(e,t,n){if(e?.roleMode==="reset"&&e.rolePrompt||e?.rolePrompt&&e.roleMode==="inherit"&&!n)return e.rolePrompt;if(t?.roleMode==="set-next"&&t.rolePrompt)return t.rolePrompt}function f5(e,t){if(!t)return;const n=e.filter(a=>a.role!=="system");n.unshift({role:"system",content:t}),e.length=0,e.push(...n)}function Dr(){return xe.getState().condenseRun.status!=="building"?!1:(Ke("info",Ie("condense.editLocked")),!0)}const fH=(e,t)=>({history:[{nodes:[],edges:[]}],historyIndex:0,pushHistory:()=>{const{nodes:n,edges:a,history:r,historyIndex:s}=t(),l=r.slice(0,s+1);l.push({nodes:n,edges:a}),l.length>IB&&l.shift(),e({history:l,historyIndex:l.length-1})},undo:()=>{if(Dr())return;const{history:n,historyIndex:a}=t();if(a<=0)return;const r=n[a-1];e({nodes:r.nodes,edges:r.edges,historyIndex:a-1}),t().logEvent("undo")},redo:()=>{if(Dr())return;const{history:n,historyIndex:a}=t();if(a>=n.length-1)return;const r=n[a+1];e({nodes:r.nodes,edges:r.edges,historyIndex:a+1}),t().logEvent("redo")}});function U7(e){if(e.data.isCollapsed)return DB;const t=Math.min(180,40+(e.data.question||"").length/1.2),n=Math.min(400,(e.data.response||"").length/1.05),a=(e.data.highlights?.length??0)*26,r=(e.data.attachments?.length??0)>0?30:0,s=215+t+n+a+r;return Math.max(260,Math.min(930,s))}function vo(e){return Math.max(e.measured?.height??0,U7(e))}function mH(e,t){const n=e.filter(r=>r.data.stepKind==="note"&&r.data.importSource&&t.some(s=>s.target===r.id));if(n.length===0)return t;let a=[...t];for(const r of n){const s=a.filter(c=>c.target===r.id),l=a.find(c=>c.source===r.id);if(a=a.filter(c=>c.target!==r.id),!!l)for(const c of s)a.some(d=>d.source===c.source&&d.target===l.target)||a.push({...c,target:l.target})}return a}function nr(e,t){if(e.length===0)return e;const n=new Set(e.filter(H=>["note","file","link","frame"].includes(H.data.stepKind??"")).map(H=>H.id)),a=e.filter(H=>!n.has(H.id)),r=t.filter(H=>!n.has(H.source)&&!n.has(H.target)),s=$w,l=Kw,c=Xw,d=24,h=r.filter(H=>!H.data?.isCrossLink),m=new Set(h.map(H=>H.target));for(const H of r)H.data?.isCrossLink&&!H.data?.isWatch&&!m.has(H.target)&&(h.push(H),m.add(H.target));const p=new Set(h.map(H=>H.target)),x=a.filter(H=>!p.has(H.id)),b=new Map;for(const H of h){const se=b.get(H.target)||[];se.push(H.source),b.set(H.target,se)}const y=new Map,k=new Map;for(const H of x){const se=t.filter(ke=>ke.target===H.id&&!ke.data?.isCrossLink&&n.has(ke.source)).map(ke=>e.find(ae=>ae.id===ke.source)).filter(ke=>!!ke);if(se.length===0)continue;const ye=se.reduce((ke,ae)=>ke.position.y+vo(ke)>ae.position.y+vo(ae)?ke:ae),be=k.get(ye.id)??0;k.set(ye.id,be+1),y.set(H.id,{x:ye.position.x-60+be*($w+Kw),y:ye.position.y+vo(ye)+Xw})}const T=new Map;for(const H of h){const se=T.get(H.source)||[];se.push(H.target),T.set(H.source,se)}const w=(H,se)=>`${H}\0${se}`,_=new Set(r.filter(H=>H.data?.isBranchFromSelection).map(H=>w(H.source,H.target)));function A(H,se){const ye=(T.get(H)||[]).filter(ae=>(se.get(ae)??H)===H),be=ye.filter(ae=>!_.has(w(H,ae))),ke=ye.filter(ae=>_.has(w(H,ae)));return{continuation:be[0]??null,regenerates:be.slice(1),explores:ke}}const C=1e5;function O(H){const se=new Map;let ye=0,be=C;const ke=new Map,ae=Oe=>ke.get(Oe)??Oe*(s+l);function Te(Oe,Le){if(se.has(Oe))return;se.set(Oe,Le);const{continuation:We,regenerates:Be,explores:rt}=A(Oe,H);We&&Te(We,Le);for(let Xe=0;Xe<Be.length;Xe++){let kt;Le>=C?(kt=be++,ke.set(kt,ae(Le)+(Xe+1)*(s+l))):(kt=Le+1+Xe,ye=Math.max(ye,kt+1)),Te(Be[Xe],kt)}let ht=0;for(const Xe of rt){let kt;Le>=C?(kt=be++,ke.set(kt,ae(Le)+(Be.length+1+ht)*(s+l)),ht++):(kt=ye,ye++),Te(Xe,kt)}}for(const Oe of x){const Le=y.get(Oe.id);if(Le){const We=be++;ke.set(We,Le.x),Te(Oe.id,We)}else{const We=ye;ye++,Te(Oe.id,We)}}for(let Oe=0;Oe<a.length;Oe++){let Le=!1;for(const We of a){if(se.has(We.id))continue;const Be=(b.get(We.id)||[]).map(rt=>se.get(rt)).filter(rt=>rt!==void 0).sort((rt,ht)=>rt-ht);Be.length&&(Te(We.id,Be[Math.floor((Be.length-1)/2)]),Le=!0)}if(!Le)break}return{nodeColumn:se,colX:ae}}const D=new Map;for(const[H,se]of b){if(se.length<2)continue;const ye=se.filter(ke=>!_.has(w(ke,H))),be=ye.length?ye:se;D.set(H,be[0])}const{nodeColumn:M,colX:N}=O(D),R=new Map;for(const H of a)R.set(H.id,vo(H));const B=new Map,U=new Set,Y=[...x.map(H=>H.id)];for(const H of Y){const se=M.get(H)??0,ye=y.get(H);B.set(H,{x:N(se),y:ye?.y??0}),U.add(H)}for(;Y.length>0;){const H=Y.shift(),se=B.get(H),ye=R.get(H)||220,{continuation:be,regenerates:ke,explores:ae}=A(H,D);if(be&&!U.has(be)){U.add(be);const Oe=M.get(be)??0;B.set(be,{x:N(Oe),y:se.y+ye+c}),Y.push(be)}const Te=se.y+ye+c;for(const Oe of ke){if(U.has(Oe))continue;U.add(Oe);const Le=M.get(Oe)??0;B.set(Oe,{x:N(Le),y:Te}),Y.push(Oe)}for(const Oe of ae){if(U.has(Oe))continue;U.add(Oe);const Le=M.get(Oe)??0;B.set(Oe,{x:N(Le),y:se.y+ye*.25}),Y.push(Oe)}}for(let H=0;H<a.length;H++){let se=!1;for(const ye of a){if(B.has(ye.id))continue;const be=(b.get(ye.id)||[]).filter(ae=>B.has(ae));if(!be.length)continue;const ke=Math.max(...be.map(ae=>B.get(ae).y+(R.get(ae)||220)));B.set(ye.id,{x:N(M.get(ye.id)??0),y:ke+c}),se=!0}if(!se)break}for(const H of a)B.has(H.id)||B.set(H.id,{x:0,y:0});for(let H=0;H<5;H++){let se=!1;for(const ye of a){const be=B.get(ye.id);if(!be)continue;const ke=(b.get(ye.id)||[]).filter(Le=>B.has(Le));if(ke.length<2)continue;const ae=ke.filter(Le=>!_.has(`${Le}\0${ye.id}`)),Te=ke.filter(Le=>_.has(`${Le}\0${ye.id}`));let Oe=-1/0;for(const Le of ae)Oe=Math.max(Oe,B.get(Le).y+(R.get(Le)||220)+c);for(const Le of Te)Oe=Math.max(Oe,B.get(Le).y);if(Oe>-1/0&&be.y<Oe){const Le=Oe-be.y;be.y=Oe;for(const We of new Set(To(ye.id,h))){const Be=B.get(We);Be&&(Be.y+=Le)}se=!0}}if(!se)break}const Z=new Map;for(const H of a){const se=M.get(H.id)??0,ye=Z.get(se)||[];ye.push(H.id),Z.set(se,ye)}for(let H=0;H<5;H++){let se=!1;for(const[,ye]of Z){ye.sort((be,ke)=>B.get(be).y-B.get(ke).y);for(let be=1;be<ye.length;be++){const ke=ye[be-1],ae=ye[be],Te=B.get(ke),Oe=B.get(ae),Le=R.get(ke)||220,We=Te.y+Le+d;if(Oe.y<We){const Be=We-Oe.y;Oe.y=We,se=!0;for(const rt of new Set(To(ae,h))){const ht=B.get(rt);ht&&(ht.y+=Be)}}}}if(!se)break}const W=8e3,K=180,F=e.filter(H=>H.data.stepKind==="note"&&H.data.importSource),G=new Set(t.filter(H=>F.some(se=>se.id===H.source)).map(H=>H.target));for(const H of x){const se=[];let ye=H.id,be=!0;for(;ye;){se.push(ye);const rt=T.get(ye)||[];if(rt.length>1){be=!1;break}ye=rt[0]}if(!be||se.length<8)continue;const ke=new Set(se),ae=B.get(se[0]),Te=se[se.length-1];if(B.get(Te).y+(R.get(Te)||220)-ae.y<=W||a.some(rt=>!ke.has(rt.id)&&B.get(rt.id).x>ae.x+s/2))continue;let We=0,Be=ae.y;for(const rt of se){const ht=R.get(rt)||220,Xe=Be-ae.y,kt=Xe+ht>W,yt=G.has(rt)&&Xe>W*.6;(kt||yt)&&Be!==ae.y&&(We++,Be=ae.y);const at=B.get(rt);at.x=ae.x+We*(s+K),at.y=Be,Be+=ht+c}}const ne=a.map(H=>{const se=B.get(H.id);return{x:se.x,y:se.y,w:s,h:R.get(H.id)||220}}),X=460,P=130,q=(H,se)=>ne.some(ye=>H<ye.x+ye.w&&H+X>ye.x&&se<ye.y+ye.h&&se+P>ye.y),J=new Map;for(const H of F){const se=t.find(ae=>ae.source===H.id)?.target,ye=se?B.get(se):void 0;if(!ye)continue;let be=ye.x-520,ke=ye.y;if(q(be,ke)&&(be=ye.x,ke=ye.y-P-40),q(be,ke)){const ae=Math.round(ye.x),Te=Math.min(...a.filter(Le=>Math.round(B.get(Le.id).x)===ae).map(Le=>B.get(Le.id).y)),Oe=J.get(ae)??0;J.set(ae,Oe+1),be=ye.x,ke=Te-P-40-Oe*(P+30)}B.set(H.id,{x:be,y:ke})}return e.map(H=>{const se=B.get(H.id);return se?{...H,position:se}:H})}const pH=(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(Dr())return;t().logEvent("delete",n,{n:1}),t().pushHistory();const{edges:a}=t(),r=To(n,a),s=new Set([n,...r]);e(l=>({nodes:l.nodes.filter(c=>!s.has(c.id)),edges:l.edges.filter(c=>!s.has(c.source)&&!s.has(c.target))})),t().pushHistory(),Kt(()=>import("./canonical-D2XBb2dX.js"),[]).then(l=>l.unsubscribeOrphanedSessions())},deleteEdges:n=>{if(Dr())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(Dr())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(l=>l.id===n?{...l,data:{...l.data,response:a,responses:l.data.responses.map((c,d)=>d===l.data.responseIndex?a:c),summaries:l.data.summaries?.map((c,d)=>d===l.data.responseIndex?void 0:c),summaryTypes:l.data.summaryTypes?.map((c,d)=>d===l.data.responseIndex?void 0:c),editedAts:l.data.responses.map((c,d)=>d===l.data.responseIndex?new Date().toISOString():l.data.editedAts?.[d]),highlights:lf(l.data.highlights,a),isEditingResponse:!1,tokenCount:r}}:l)})),t().pushHistory()},toggleCollapse:n=>{const a=t().nodes.find(h=>h.id===n);if(!a)return;const r=vo(a),l=U7({...a,data:{...a.data,isCollapsed:!a.data.isCollapsed}})-r,c=To(n,t().edges),d=new Set(c);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+l}}:m)}))},setEditing:(n,a)=>{a&&Dr()||e(r=>({nodes:r.nodes.map(s=>s.id===n?{...s,data:{...s.data,isEditing:a}}:s)}))},setEditingResponse:(n,a)=>{a&&Dr()||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=In(),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:In()}))}},l=t().edges.find(m=>m.target===n),c=l?{...l,id:`edge-${l.source}-${r}`,target:r}:null,d=c?[...t().edges,c]:t().edges,h=nr([...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 c=s.find(x=>x.id===n);if(c&&["note","file","link"].includes(c.data.stepKind??"")){t().pushHistory();const x={id:`edge-${n}-${a}`,source:n,sourceHandle:"continue",target:a,targetHandle:"top",type:"smoothstep",style:{stroke:nt.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 k=yr(n,t().nodes,t().edges).messages.reduce((T,w)=>T+$n(w.content),0);Ke("success",Ue(Ie("edge.materialWiredFull"),{n:k.toLocaleString()}),8e3,{label:Ie("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:nt.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}=Br(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(Md({source:d,depth:"quote",chain:b})),T=yr(n,s,r).messages.reduce((w,_)=>w+$n(_.content),0)+$n(d.data.question+d.data.response);Ke("info",Ue(Ie("edge.linkedQuote"),{n:y}),8e3,{label:Ue(Ie("edge.makeFull"),{m:T}),run:()=>t().setEdgeStructural(p.id,!0)})}}},staleIds:[],recomputeStaleness:()=>{const{nodes:n,edges:a}=t(),r=[];for(const l of n)!l.data.lastContextHash||!l.data.response||["note","file","link","frame"].includes(l.data.stepKind??"")||B7(l.id,n,a)!==l.data.lastContextHash&&r.push(l.id);const s=t().staleIds;s.length===r.length&&s.every((l,c)=>l===r[c])||e({staleIds:r})},setEdgeStructural:(n,a)=>{const{nodes:r,edges:s}=t(),l=s.find(c=>c.id===n);if(l){if(a){const c=s.filter(h=>!h.data?.isCrossLink),{ordered:d}=Br(l.source,r,c);if(d.some(h=>h.id===l.target)){Ke("error",Ie("edge.cycleBlocked"));return}}t().pushHistory(),t().logEvent(a?"connect":"disconnect",n,{convert:!0}),e(c=>({edges:c.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:nt.accent,strokeWidth:2},markerEnd:{type:"arrowclosed",color:nt.accent,width:18,height:18},data:h}}return{...d,animated:!0,style:{stroke:nt.accent,strokeDasharray:"8 4",strokeWidth:2},markerEnd:{type:"arrowclosed",color:nt.accent,width:18,height:18},data:{...d.data??{},isCrossLink:!0,contextDepth:void 0}}})})),e(c=>({nodes:nr(c.nodes,c.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:l,responseIndex:c}=s.data;let d=a==="prev"?c-1:c+1;return d<0&&(d=l.length-1),d>=l.length&&(d=0),{...s,data:{...s.data,responseIndex:d,response:l[d],question:s.data.questions?.[d]??s.data.question,generationFailed:void 0,highlights:lf(s.data.highlights,l[d])}}})}))},deleteVersion:(n,a)=>{t().pushHistory(),e(r=>({nodes:r.nodes.map(s=>{if(s.id!==n)return s;const l=s.data.responses.filter((d,h)=>h!==a);if(l.length===0)return s;const c=Math.min(s.data.responseIndex,l.length-1);return{...s,data:{...s.data,responses:l,responseIndex:c,response:l[c],questions:s.data.questions?.filter((d,h)=>h!==a),question:s.data.questions?.filter((d,h)=>h!==a)[c]??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:lf(s.data.highlights,l[c])}}})})),t().pushHistory()},relayout:()=>{Dr()||(t().pushHistory(),e(n=>{const a=mH(n.nodes,n.edges);return{nodes:nr(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(l=>r.has(l.id)?{...l,data:{...l.data,archived:a||void 0,archivedAt:a?new Date().toISOString():void 0}}:l)})),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(),l=new Map,c=s.filter(b=>!b.data?.isWatch),d=(b,y)=>{if(l.has(b))return l.get(b);if(y.has(b))return 0;y.add(b);const k=c.filter(w=>w.target===b&&a.has(w.source)),T=k.length===0?0:1+Math.max(...k.map(w=>d(w.source,y)));return l.set(b,T),T},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+=vo(b)+40;e(b=>({nodes:b.nodes.map(y=>{const k=x.get(y.id);return k?{...y,position:k}:y})})),t().pushHistory()},batchDelete:n=>{if(Dr())return;t().logEvent("delete",n[0],{n:n.length}),t().pushHistory();const a=new Set(n);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(),Kt(()=>import("./canonical-D2XBb2dX.js"),[]).then(r=>r.unsubscribeOrphanedSessions())},duplicateSelection:n=>{const{nodes:a,edges:r}=t(),s=new Set(n),l=a.filter(M=>s.has(M.id));if(l.length===0)return;t().pushHistory();const c=M=>({x:M.position.x,y:M.position.y,w:M.measured?.width??M.width??520,h:M.measured?.height??M.height??vo(M)}),d=l.map(c),h={x:Math.min(...d.map(M=>M.x)),y:Math.min(...d.map(M=>M.y)),right:Math.max(...d.map(M=>M.x+M.w)),bottom:Math.max(...d.map(M=>M.y+M.h))},m=80,p=h.right-h.x+m,x=h.bottom-h.y+m,b=[];for(let M=1;M<=6;M++)b.push({dx:M*p,dy:0},{dx:0,dy:M*x},{dx:M*p,dy:M*x});const y=a.filter(M=>M.data.stepKind!=="frame").map(c),k=(M,N)=>M.x<N.x+N.w&&M.x+M.w>N.x&&M.y<N.y+N.h&&M.y+M.h>N.y,T=b.find(M=>!d.some(N=>y.some(R=>k({...N,x:N.x+M.dx,y:N.y+M.dy},R))))??{dx:p,dy:x},w=new Map,_=new Map;for(const M of l){w.set(M.id,In());for(const N of M.data.attachments??[])_.set(N.id,In())}const A=M=>(M??[]).map(N=>_.get(N)??N),C=l.map(M=>({...M,id:w.get(M.id),position:{x:M.position.x+T.dx,y:M.position.y+T.dy},selected:!0,data:{...M.data,attachments:(M.data.attachments??[]).map(N=>({...N,id:_.get(N.id)})),excludedAttachmentIds:A(M.data.excludedAttachmentIds),includedAttachmentIds:A(M.data.includedAttachmentIds),digestOf:M.data.digestOf?_.get(M.data.digestOf)??M.data.digestOf:void 0,highlights:(M.data.highlights??[]).map(N=>({...N,id:In()})),isEditing:!1,isEditingResponse:!1,isLoading:!1}})),O=r.filter(M=>s.has(M.source)&&s.has(M.target)).map(M=>({...M,id:`edge-${w.get(M.source)}-${w.get(M.target)}`,source:w.get(M.source),target:w.get(M.target),data:M.data?{...M.data}:M.data})),D=C.map(M=>M.id);e(M=>({nodes:[...M.nodes.map(N=>N.selected?{...N,selected:!1}:N),...C],edges:[...M.edges,...O],selectedNodeId:D.length===1?D[0]:null,selectedNodeIds:D})),t().pushHistory()}});function Bb(e){const t=n=>{if(Array.isArray(n))return n.map(t);if(n&&typeof n=="object"){const a={};for(const r of Object.keys(n).sort()){const s=n[r];s!==void 0&&(a[r]=t(s))}return a}return n};return JSON.stringify(t(e))}async function If(e){const t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return[...new Uint8Array(t)].map(n=>n.toString(16).padStart(2,"0")).join("")}function gH(e,t){const n=[...e].sort((r,s)=>r.id<s.id?-1:1).map(r=>({id:r.id,stepKind:r.data.stepKind,question:r.data.question,response:r.data.response,archived:r.data.archived||void 0,branchContext:r.data.branchContext||void 0,highlightMode:r.data.highlightMode!=="off"?r.data.highlightMode:void 0,highlights:(r.data.highlights??[]).length>0?r.data.highlights.map(s=>s.text):void 0,linkUrl:r.data.linkUrl,linkFetchedAt:r.data.linkFetchedAt,rolePrompt:r.data.rolePrompt,roleMode:r.data.roleMode,excludedAttachmentIds:r.data.excludedAttachmentIds?.length?r.data.excludedAttachmentIds:void 0,attachments:(r.data.attachments??[]).map(s=>({id:s.id,name:s.name,type:s.type,fingerprint:yc(s),extractedText:s.extractedText,renderMode:s.renderMode}))})),a=[...t].sort((r,s)=>r.id<s.id?-1:1).map(r=>({source:r.source,target:r.target,isCrossLink:r.data?.isCrossLink||void 0,isWatch:r.data?.isWatch||void 0,contextDepth:r.data?.contextDepth}));return{nodes:n,edges:a}}async function xH(e,t){return`sha256:${await If(Bb(gH(e,t)))}`}function bH(e){if(e.type.startsWith("image/")){const t=e.renderMode!=="text-only",n=!!e.extractedText?.trim();return t&&n?"extracted_text+pixels":t?"pixels":n?"extracted_text":"placeholder"}return e.extractedText?.trim()||e.type.startsWith("text/")?"extracted_text":"placeholder"}async function Kae(e,t,n,a){const r=yr(e,t,n,a.branchContext,void 0,void 0,a.staleIds),s=t.find(x=>x.id===e),l=r.messages.map((x,b)=>{const y=r.sources[b]??{layer:"chain"};return{id:`item_${String(b+1).padStart(3,"0")}`,kind:"message",role:x.role,content:[{type:"text",text:x.content}],source:{layer:y.layer,part:y.part,node_id:y.nodeId??y.refSourceId,attachment_id:y.attachmentId},selection:{mode:"full",reason:`structural-${y.layer}`}}}),c=new Map,d=(x,b)=>{if(!x||!b||c.has(b))return;const y=t.find(T=>T.id===x),k=y?.data.attachments?.find(T=>T.id===b);!y||!k||c.set(b,{id:b,kind:k.type.startsWith("image/")?"image":"document",name:k.name,mime_type:k.type,size:k.size,fingerprint:yc(k),model_projection:{mode:bH(k)},source:{node_id:y.id}})};r.sources.forEach(x=>d(x.nodeId,x.attachmentId)),r.imageSources.forEach(x=>d(x.nodeId,x.attachmentId));const h=r.sources.filter(x=>x.layer==="reference"&&x.refSourceId).map(x=>({source_node_id:x.refSourceId})),m={format:"thoughtdag.context-bundle",version:0,graph:{project_id:a.projectId??null,snapshot_hash:await xH(t,n),target_node_id:e},intent:{task:a.task??s?.data.question??"",language:a.language??null},context:{messages:l,materials:[...c.values()],references:h},execution_hints:{preferred_model:a.preferredModel??s?.data.model??null,required_tools:[],required_mcp_servers:[]},budget:{estimated_tokens:r.messages.reduce((x,b)=>x+$n(b.content),0),limit:null,truncation:"none"}},p=await If(Bb(m));return{...m,id:`cb_${p.slice(0,16)}`,created_at:a.now,provenance:{source_runs:[],compiler:{name:"thoughtdag",adapter_id:null}},integrity:{content_hash:`sha256:${p}`}}}const sc="dsh-sessions",c1="/session.jsonl.zstd",yH=1500,vH=2500;let _x=null;function wH(e){if(window.desktopSessions)return;const t=e.replace(/\/+$/,""),n=async O=>{const D=await fetch(t+O,{credentials:"same-origin"});if(!D.ok)throw new Error(`${O}: ${D.status}`);return D.json()},a=async O=>{const D=await fetch(t+O,{credentials:"same-origin"});if(!D.ok)throw new Error(`${O}: ${D.status}`);return D.text()},r=new Map,s=O=>`${O}${c1}`,l=(O,D)=>{const M=O.indexOf(`
61
+ ${N}`:N}),h.push({layer:"chain",nodeId:M.id,part:"response"})}a&&(c.push({role:"user",content:`[Regarding this passage: "${a}"]`}),h.push({layer:"branch",nodeId:e,part:"passage"})),b("chain");const D=H7(w,t);return D&&(c.unshift({role:"system",content:D}),h.unshift({layer:"system",part:"role"})),{messages:c,images:d,layerTokens:p,sources:h,imageSources:m}}function h5(e,t,n){if(e?.roleMode==="reset"&&e.rolePrompt||e?.rolePrompt&&e.roleMode==="inherit"&&!n)return e.rolePrompt;if(t?.roleMode==="set-next"&&t.rolePrompt)return t.rolePrompt}function f5(e,t){if(!t)return;const n=e.filter(a=>a.role!=="system");n.unshift({role:"system",content:t}),e.length=0,e.push(...n)}function Dr(){return xe.getState().condenseRun.status!=="building"?!1:(Ke("info",Ie("condense.editLocked")),!0)}const fH=(e,t)=>({history:[{nodes:[],edges:[]}],historyIndex:0,pushHistory:()=>{const{nodes:n,edges:a,history:r,historyIndex:s}=t(),l=r.slice(0,s+1);l.push({nodes:n,edges:a}),l.length>IB&&l.shift(),e({history:l,historyIndex:l.length-1})},undo:()=>{if(Dr())return;const{history:n,historyIndex:a}=t();if(a<=0)return;const r=n[a-1];e({nodes:r.nodes,edges:r.edges,historyIndex:a-1}),t().logEvent("undo")},redo:()=>{if(Dr())return;const{history:n,historyIndex:a}=t();if(a>=n.length-1)return;const r=n[a+1];e({nodes:r.nodes,edges:r.edges,historyIndex:a+1}),t().logEvent("redo")}});function U7(e){if(e.data.isCollapsed)return DB;const t=Math.min(180,40+(e.data.question||"").length/1.2),n=Math.min(400,(e.data.response||"").length/1.05),a=(e.data.highlights?.length??0)*26,r=(e.data.attachments?.length??0)>0?30:0,s=215+t+n+a+r;return Math.max(260,Math.min(930,s))}function vo(e){return Math.max(e.measured?.height??0,U7(e))}function mH(e,t){const n=e.filter(r=>r.data.stepKind==="note"&&r.data.importSource&&t.some(s=>s.target===r.id));if(n.length===0)return t;let a=[...t];for(const r of n){const s=a.filter(c=>c.target===r.id),l=a.find(c=>c.source===r.id);if(a=a.filter(c=>c.target!==r.id),!!l)for(const c of s)a.some(d=>d.source===c.source&&d.target===l.target)||a.push({...c,target:l.target})}return a}function nr(e,t){if(e.length===0)return e;const n=new Set(e.filter(H=>["note","file","link","frame"].includes(H.data.stepKind??"")).map(H=>H.id)),a=e.filter(H=>!n.has(H.id)),r=t.filter(H=>!n.has(H.source)&&!n.has(H.target)),s=$w,l=Kw,c=Xw,d=24,h=r.filter(H=>!H.data?.isCrossLink),m=new Set(h.map(H=>H.target));for(const H of r)H.data?.isCrossLink&&!H.data?.isWatch&&!m.has(H.target)&&(h.push(H),m.add(H.target));const p=new Set(h.map(H=>H.target)),x=a.filter(H=>!p.has(H.id)),b=new Map;for(const H of h){const se=b.get(H.target)||[];se.push(H.source),b.set(H.target,se)}const y=new Map,k=new Map;for(const H of x){const se=t.filter(ke=>ke.target===H.id&&!ke.data?.isCrossLink&&n.has(ke.source)).map(ke=>e.find(ae=>ae.id===ke.source)).filter(ke=>!!ke);if(se.length===0)continue;const ye=se.reduce((ke,ae)=>ke.position.y+vo(ke)>ae.position.y+vo(ae)?ke:ae),be=k.get(ye.id)??0;k.set(ye.id,be+1),y.set(H.id,{x:ye.position.x-60+be*($w+Kw),y:ye.position.y+vo(ye)+Xw})}const T=new Map;for(const H of h){const se=T.get(H.source)||[];se.push(H.target),T.set(H.source,se)}const w=(H,se)=>`${H}\0${se}`,_=new Set(r.filter(H=>H.data?.isBranchFromSelection).map(H=>w(H.source,H.target)));function A(H,se){const ye=(T.get(H)||[]).filter(ae=>(se.get(ae)??H)===H),be=ye.filter(ae=>!_.has(w(H,ae))),ke=ye.filter(ae=>_.has(w(H,ae)));return{continuation:be[0]??null,regenerates:be.slice(1),explores:ke}}const C=1e5;function O(H){const se=new Map;let ye=0,be=C;const ke=new Map,ae=Oe=>ke.get(Oe)??Oe*(s+l);function Te(Oe,Le){if(se.has(Oe))return;se.set(Oe,Le);const{continuation:We,regenerates:Be,explores:rt}=A(Oe,H);We&&Te(We,Le);for(let Xe=0;Xe<Be.length;Xe++){let kt;Le>=C?(kt=be++,ke.set(kt,ae(Le)+(Xe+1)*(s+l))):(kt=Le+1+Xe,ye=Math.max(ye,kt+1)),Te(Be[Xe],kt)}let ht=0;for(const Xe of rt){let kt;Le>=C?(kt=be++,ke.set(kt,ae(Le)+(Be.length+1+ht)*(s+l)),ht++):(kt=ye,ye++),Te(Xe,kt)}}for(const Oe of x){const Le=y.get(Oe.id);if(Le){const We=be++;ke.set(We,Le.x),Te(Oe.id,We)}else{const We=ye;ye++,Te(Oe.id,We)}}for(let Oe=0;Oe<a.length;Oe++){let Le=!1;for(const We of a){if(se.has(We.id))continue;const Be=(b.get(We.id)||[]).map(rt=>se.get(rt)).filter(rt=>rt!==void 0).sort((rt,ht)=>rt-ht);Be.length&&(Te(We.id,Be[Math.floor((Be.length-1)/2)]),Le=!0)}if(!Le)break}return{nodeColumn:se,colX:ae}}const D=new Map;for(const[H,se]of b){if(se.length<2)continue;const ye=se.filter(ke=>!_.has(w(ke,H))),be=ye.length?ye:se;D.set(H,be[0])}const{nodeColumn:M,colX:N}=O(D),R=new Map;for(const H of a)R.set(H.id,vo(H));const B=new Map,U=new Set,Y=[...x.map(H=>H.id)];for(const H of Y){const se=M.get(H)??0,ye=y.get(H);B.set(H,{x:N(se),y:ye?.y??0}),U.add(H)}for(;Y.length>0;){const H=Y.shift(),se=B.get(H),ye=R.get(H)||220,{continuation:be,regenerates:ke,explores:ae}=A(H,D);if(be&&!U.has(be)){U.add(be);const Oe=M.get(be)??0;B.set(be,{x:N(Oe),y:se.y+ye+c}),Y.push(be)}const Te=se.y+ye+c;for(const Oe of ke){if(U.has(Oe))continue;U.add(Oe);const Le=M.get(Oe)??0;B.set(Oe,{x:N(Le),y:Te}),Y.push(Oe)}for(const Oe of ae){if(U.has(Oe))continue;U.add(Oe);const Le=M.get(Oe)??0;B.set(Oe,{x:N(Le),y:se.y+ye*.25}),Y.push(Oe)}}for(let H=0;H<a.length;H++){let se=!1;for(const ye of a){if(B.has(ye.id))continue;const be=(b.get(ye.id)||[]).filter(ae=>B.has(ae));if(!be.length)continue;const ke=Math.max(...be.map(ae=>B.get(ae).y+(R.get(ae)||220)));B.set(ye.id,{x:N(M.get(ye.id)??0),y:ke+c}),se=!0}if(!se)break}for(const H of a)B.has(H.id)||B.set(H.id,{x:0,y:0});for(let H=0;H<5;H++){let se=!1;for(const ye of a){const be=B.get(ye.id);if(!be)continue;const ke=(b.get(ye.id)||[]).filter(Le=>B.has(Le));if(ke.length<2)continue;const ae=ke.filter(Le=>!_.has(`${Le}\0${ye.id}`)),Te=ke.filter(Le=>_.has(`${Le}\0${ye.id}`));let Oe=-1/0;for(const Le of ae)Oe=Math.max(Oe,B.get(Le).y+(R.get(Le)||220)+c);for(const Le of Te)Oe=Math.max(Oe,B.get(Le).y);if(Oe>-1/0&&be.y<Oe){const Le=Oe-be.y;be.y=Oe;for(const We of new Set(To(ye.id,h))){const Be=B.get(We);Be&&(Be.y+=Le)}se=!0}}if(!se)break}const Z=new Map;for(const H of a){const se=M.get(H.id)??0,ye=Z.get(se)||[];ye.push(H.id),Z.set(se,ye)}for(let H=0;H<5;H++){let se=!1;for(const[,ye]of Z){ye.sort((be,ke)=>B.get(be).y-B.get(ke).y);for(let be=1;be<ye.length;be++){const ke=ye[be-1],ae=ye[be],Te=B.get(ke),Oe=B.get(ae),Le=R.get(ke)||220,We=Te.y+Le+d;if(Oe.y<We){const Be=We-Oe.y;Oe.y=We,se=!0;for(const rt of new Set(To(ae,h))){const ht=B.get(rt);ht&&(ht.y+=Be)}}}}if(!se)break}const W=8e3,K=180,F=e.filter(H=>H.data.stepKind==="note"&&H.data.importSource),G=new Set(t.filter(H=>F.some(se=>se.id===H.source)).map(H=>H.target));for(const H of x){const se=[];let ye=H.id,be=!0;for(;ye;){se.push(ye);const rt=T.get(ye)||[];if(rt.length>1){be=!1;break}ye=rt[0]}if(!be||se.length<8)continue;const ke=new Set(se),ae=B.get(se[0]),Te=se[se.length-1];if(B.get(Te).y+(R.get(Te)||220)-ae.y<=W||a.some(rt=>!ke.has(rt.id)&&B.get(rt.id).x>ae.x+s/2))continue;let We=0,Be=ae.y;for(const rt of se){const ht=R.get(rt)||220,Xe=Be-ae.y,kt=Xe+ht>W,yt=G.has(rt)&&Xe>W*.6;(kt||yt)&&Be!==ae.y&&(We++,Be=ae.y);const at=B.get(rt);at.x=ae.x+We*(s+K),at.y=Be,Be+=ht+c}}const ne=a.map(H=>{const se=B.get(H.id);return{x:se.x,y:se.y,w:s,h:R.get(H.id)||220}}),X=460,P=130,q=(H,se)=>ne.some(ye=>H<ye.x+ye.w&&H+X>ye.x&&se<ye.y+ye.h&&se+P>ye.y),J=new Map;for(const H of F){const se=t.find(ae=>ae.source===H.id)?.target,ye=se?B.get(se):void 0;if(!ye)continue;let be=ye.x-520,ke=ye.y;if(q(be,ke)&&(be=ye.x,ke=ye.y-P-40),q(be,ke)){const ae=Math.round(ye.x),Te=Math.min(...a.filter(Le=>Math.round(B.get(Le.id).x)===ae).map(Le=>B.get(Le.id).y)),Oe=J.get(ae)??0;J.set(ae,Oe+1),be=ye.x,ke=Te-P-40-Oe*(P+30)}B.set(H.id,{x:be,y:ke})}return e.map(H=>{const se=B.get(H.id);return se?{...H,position:se}:H})}const pH=(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(Dr())return;t().logEvent("delete",n,{n:1}),t().pushHistory();const{edges:a}=t(),r=To(n,a),s=new Set([n,...r]);e(l=>({nodes:l.nodes.filter(c=>!s.has(c.id)),edges:l.edges.filter(c=>!s.has(c.source)&&!s.has(c.target))})),t().pushHistory(),Kt(()=>import("./canonical-HRd1ZNsL.js"),[]).then(l=>l.unsubscribeOrphanedSessions())},deleteEdges:n=>{if(Dr())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(Dr())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(l=>l.id===n?{...l,data:{...l.data,response:a,responses:l.data.responses.map((c,d)=>d===l.data.responseIndex?a:c),summaries:l.data.summaries?.map((c,d)=>d===l.data.responseIndex?void 0:c),summaryTypes:l.data.summaryTypes?.map((c,d)=>d===l.data.responseIndex?void 0:c),editedAts:l.data.responses.map((c,d)=>d===l.data.responseIndex?new Date().toISOString():l.data.editedAts?.[d]),highlights:lf(l.data.highlights,a),isEditingResponse:!1,tokenCount:r}}:l)})),t().pushHistory()},toggleCollapse:n=>{const a=t().nodes.find(h=>h.id===n);if(!a)return;const r=vo(a),l=U7({...a,data:{...a.data,isCollapsed:!a.data.isCollapsed}})-r,c=To(n,t().edges),d=new Set(c);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+l}}:m)}))},setEditing:(n,a)=>{a&&Dr()||e(r=>({nodes:r.nodes.map(s=>s.id===n?{...s,data:{...s.data,isEditing:a}}:s)}))},setEditingResponse:(n,a)=>{a&&Dr()||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=In(),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:In()}))}},l=t().edges.find(m=>m.target===n),c=l?{...l,id:`edge-${l.source}-${r}`,target:r}:null,d=c?[...t().edges,c]:t().edges,h=nr([...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 c=s.find(x=>x.id===n);if(c&&["note","file","link"].includes(c.data.stepKind??"")){t().pushHistory();const x={id:`edge-${n}-${a}`,source:n,sourceHandle:"continue",target:a,targetHandle:"top",type:"smoothstep",style:{stroke:nt.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 k=yr(n,t().nodes,t().edges).messages.reduce((T,w)=>T+$n(w.content),0);Ke("success",Ue(Ie("edge.materialWiredFull"),{n:k.toLocaleString()}),8e3,{label:Ie("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:nt.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}=Br(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(Md({source:d,depth:"quote",chain:b})),T=yr(n,s,r).messages.reduce((w,_)=>w+$n(_.content),0)+$n(d.data.question+d.data.response);Ke("info",Ue(Ie("edge.linkedQuote"),{n:y}),8e3,{label:Ue(Ie("edge.makeFull"),{m:T}),run:()=>t().setEdgeStructural(p.id,!0)})}}},staleIds:[],recomputeStaleness:()=>{const{nodes:n,edges:a}=t(),r=[];for(const l of n)!l.data.lastContextHash||!l.data.response||["note","file","link","frame"].includes(l.data.stepKind??"")||B7(l.id,n,a)!==l.data.lastContextHash&&r.push(l.id);const s=t().staleIds;s.length===r.length&&s.every((l,c)=>l===r[c])||e({staleIds:r})},setEdgeStructural:(n,a)=>{const{nodes:r,edges:s}=t(),l=s.find(c=>c.id===n);if(l){if(a){const c=s.filter(h=>!h.data?.isCrossLink),{ordered:d}=Br(l.source,r,c);if(d.some(h=>h.id===l.target)){Ke("error",Ie("edge.cycleBlocked"));return}}t().pushHistory(),t().logEvent(a?"connect":"disconnect",n,{convert:!0}),e(c=>({edges:c.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:nt.accent,strokeWidth:2},markerEnd:{type:"arrowclosed",color:nt.accent,width:18,height:18},data:h}}return{...d,animated:!0,style:{stroke:nt.accent,strokeDasharray:"8 4",strokeWidth:2},markerEnd:{type:"arrowclosed",color:nt.accent,width:18,height:18},data:{...d.data??{},isCrossLink:!0,contextDepth:void 0}}})})),e(c=>({nodes:nr(c.nodes,c.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:l,responseIndex:c}=s.data;let d=a==="prev"?c-1:c+1;return d<0&&(d=l.length-1),d>=l.length&&(d=0),{...s,data:{...s.data,responseIndex:d,response:l[d],question:s.data.questions?.[d]??s.data.question,generationFailed:void 0,highlights:lf(s.data.highlights,l[d])}}})}))},deleteVersion:(n,a)=>{t().pushHistory(),e(r=>({nodes:r.nodes.map(s=>{if(s.id!==n)return s;const l=s.data.responses.filter((d,h)=>h!==a);if(l.length===0)return s;const c=Math.min(s.data.responseIndex,l.length-1);return{...s,data:{...s.data,responses:l,responseIndex:c,response:l[c],questions:s.data.questions?.filter((d,h)=>h!==a),question:s.data.questions?.filter((d,h)=>h!==a)[c]??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:lf(s.data.highlights,l[c])}}})})),t().pushHistory()},relayout:()=>{Dr()||(t().pushHistory(),e(n=>{const a=mH(n.nodes,n.edges);return{nodes:nr(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(l=>r.has(l.id)?{...l,data:{...l.data,archived:a||void 0,archivedAt:a?new Date().toISOString():void 0}}:l)})),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(),l=new Map,c=s.filter(b=>!b.data?.isWatch),d=(b,y)=>{if(l.has(b))return l.get(b);if(y.has(b))return 0;y.add(b);const k=c.filter(w=>w.target===b&&a.has(w.source)),T=k.length===0?0:1+Math.max(...k.map(w=>d(w.source,y)));return l.set(b,T),T},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+=vo(b)+40;e(b=>({nodes:b.nodes.map(y=>{const k=x.get(y.id);return k?{...y,position:k}:y})})),t().pushHistory()},batchDelete:n=>{if(Dr())return;t().logEvent("delete",n[0],{n:n.length}),t().pushHistory();const a=new Set(n);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(),Kt(()=>import("./canonical-HRd1ZNsL.js"),[]).then(r=>r.unsubscribeOrphanedSessions())},duplicateSelection:n=>{const{nodes:a,edges:r}=t(),s=new Set(n),l=a.filter(M=>s.has(M.id));if(l.length===0)return;t().pushHistory();const c=M=>({x:M.position.x,y:M.position.y,w:M.measured?.width??M.width??520,h:M.measured?.height??M.height??vo(M)}),d=l.map(c),h={x:Math.min(...d.map(M=>M.x)),y:Math.min(...d.map(M=>M.y)),right:Math.max(...d.map(M=>M.x+M.w)),bottom:Math.max(...d.map(M=>M.y+M.h))},m=80,p=h.right-h.x+m,x=h.bottom-h.y+m,b=[];for(let M=1;M<=6;M++)b.push({dx:M*p,dy:0},{dx:0,dy:M*x},{dx:M*p,dy:M*x});const y=a.filter(M=>M.data.stepKind!=="frame").map(c),k=(M,N)=>M.x<N.x+N.w&&M.x+M.w>N.x&&M.y<N.y+N.h&&M.y+M.h>N.y,T=b.find(M=>!d.some(N=>y.some(R=>k({...N,x:N.x+M.dx,y:N.y+M.dy},R))))??{dx:p,dy:x},w=new Map,_=new Map;for(const M of l){w.set(M.id,In());for(const N of M.data.attachments??[])_.set(N.id,In())}const A=M=>(M??[]).map(N=>_.get(N)??N),C=l.map(M=>({...M,id:w.get(M.id),position:{x:M.position.x+T.dx,y:M.position.y+T.dy},selected:!0,data:{...M.data,attachments:(M.data.attachments??[]).map(N=>({...N,id:_.get(N.id)})),excludedAttachmentIds:A(M.data.excludedAttachmentIds),includedAttachmentIds:A(M.data.includedAttachmentIds),digestOf:M.data.digestOf?_.get(M.data.digestOf)??M.data.digestOf:void 0,highlights:(M.data.highlights??[]).map(N=>({...N,id:In()})),isEditing:!1,isEditingResponse:!1,isLoading:!1}})),O=r.filter(M=>s.has(M.source)&&s.has(M.target)).map(M=>({...M,id:`edge-${w.get(M.source)}-${w.get(M.target)}`,source:w.get(M.source),target:w.get(M.target),data:M.data?{...M.data}:M.data})),D=C.map(M=>M.id);e(M=>({nodes:[...M.nodes.map(N=>N.selected?{...N,selected:!1}:N),...C],edges:[...M.edges,...O],selectedNodeId:D.length===1?D[0]:null,selectedNodeIds:D})),t().pushHistory()}});function Bb(e){const t=n=>{if(Array.isArray(n))return n.map(t);if(n&&typeof n=="object"){const a={};for(const r of Object.keys(n).sort()){const s=n[r];s!==void 0&&(a[r]=t(s))}return a}return n};return JSON.stringify(t(e))}async function If(e){const t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return[...new Uint8Array(t)].map(n=>n.toString(16).padStart(2,"0")).join("")}function gH(e,t){const n=[...e].sort((r,s)=>r.id<s.id?-1:1).map(r=>({id:r.id,stepKind:r.data.stepKind,question:r.data.question,response:r.data.response,archived:r.data.archived||void 0,branchContext:r.data.branchContext||void 0,highlightMode:r.data.highlightMode!=="off"?r.data.highlightMode:void 0,highlights:(r.data.highlights??[]).length>0?r.data.highlights.map(s=>s.text):void 0,linkUrl:r.data.linkUrl,linkFetchedAt:r.data.linkFetchedAt,rolePrompt:r.data.rolePrompt,roleMode:r.data.roleMode,excludedAttachmentIds:r.data.excludedAttachmentIds?.length?r.data.excludedAttachmentIds:void 0,attachments:(r.data.attachments??[]).map(s=>({id:s.id,name:s.name,type:s.type,fingerprint:yc(s),extractedText:s.extractedText,renderMode:s.renderMode}))})),a=[...t].sort((r,s)=>r.id<s.id?-1:1).map(r=>({source:r.source,target:r.target,isCrossLink:r.data?.isCrossLink||void 0,isWatch:r.data?.isWatch||void 0,contextDepth:r.data?.contextDepth}));return{nodes:n,edges:a}}async function xH(e,t){return`sha256:${await If(Bb(gH(e,t)))}`}function bH(e){if(e.type.startsWith("image/")){const t=e.renderMode!=="text-only",n=!!e.extractedText?.trim();return t&&n?"extracted_text+pixels":t?"pixels":n?"extracted_text":"placeholder"}return e.extractedText?.trim()||e.type.startsWith("text/")?"extracted_text":"placeholder"}async function Kae(e,t,n,a){const r=yr(e,t,n,a.branchContext,void 0,void 0,a.staleIds),s=t.find(x=>x.id===e),l=r.messages.map((x,b)=>{const y=r.sources[b]??{layer:"chain"};return{id:`item_${String(b+1).padStart(3,"0")}`,kind:"message",role:x.role,content:[{type:"text",text:x.content}],source:{layer:y.layer,part:y.part,node_id:y.nodeId??y.refSourceId,attachment_id:y.attachmentId},selection:{mode:"full",reason:`structural-${y.layer}`}}}),c=new Map,d=(x,b)=>{if(!x||!b||c.has(b))return;const y=t.find(T=>T.id===x),k=y?.data.attachments?.find(T=>T.id===b);!y||!k||c.set(b,{id:b,kind:k.type.startsWith("image/")?"image":"document",name:k.name,mime_type:k.type,size:k.size,fingerprint:yc(k),model_projection:{mode:bH(k)},source:{node_id:y.id}})};r.sources.forEach(x=>d(x.nodeId,x.attachmentId)),r.imageSources.forEach(x=>d(x.nodeId,x.attachmentId));const h=r.sources.filter(x=>x.layer==="reference"&&x.refSourceId).map(x=>({source_node_id:x.refSourceId})),m={format:"thoughtdag.context-bundle",version:0,graph:{project_id:a.projectId??null,snapshot_hash:await xH(t,n),target_node_id:e},intent:{task:a.task??s?.data.question??"",language:a.language??null},context:{messages:l,materials:[...c.values()],references:h},execution_hints:{preferred_model:a.preferredModel??s?.data.model??null,required_tools:[],required_mcp_servers:[]},budget:{estimated_tokens:r.messages.reduce((x,b)=>x+$n(b.content),0),limit:null,truncation:"none"}},p=await If(Bb(m));return{...m,id:`cb_${p.slice(0,16)}`,created_at:a.now,provenance:{source_runs:[],compiler:{name:"thoughtdag",adapter_id:null}},integrity:{content_hash:`sha256:${p}`}}}const sc="dsh-sessions",c1="/session.jsonl.zstd",yH=1500,vH=2500;let _x=null;function wH(e){if(window.desktopSessions)return;const t=e.replace(/\/+$/,""),n=async O=>{const D=await fetch(t+O,{credentials:"same-origin"});if(!D.ok)throw new Error(`${O}: ${D.status}`);return D.json()},a=async O=>{const D=await fetch(t+O,{credentials:"same-origin"});if(!D.ok)throw new Error(`${O}: ${D.status}`);return D.text()},r=new Map,s=O=>`${O}${c1}`,l=(O,D)=>{const M=O.indexOf(`
62
62
  `),N=M<0?O:O.slice(0,M);try{const R=JSON.parse(N);if(R.type==="session"&&R.cwd===void 0)return R.cwd=D,JSON.stringify(R)+(M<0?"":O.slice(M))}catch{}return O},c=O=>O.endsWith(c1)?O.slice(0,-c1.length):null,d=async()=>{const[O,D]=await Promise.all([n("/disksessions").then(N=>N.sessions).catch(()=>[]),n("/sessions").then(N=>N.sessions).catch(()=>[])]),M=new Set;for(const N of O){M.add(N.id);const R=r.get(N.id);r.set(N.id,{id:N.id,live:!1,size:N.size,mtime:N.mtime,seq:R?.seq??null,cwd:N.cwd??R?.cwd??null})}for(const N of D){M.add(N.id);const R=r.get(N.id),B=typeof N.seq=="number"?N.seq:null,U=B!==null&&R?.seq!==null&&R?.seq!==void 0&&B>R.seq;r.set(N.id,{id:N.id,live:!0,size:R?.size??0,mtime:U||!R?Date.now():R.mtime,seq:B,cwd:R?.cwd??null})}for(const N of[...r.keys()])M.has(N)||r.delete(N);return[...r.values()]},h=new Map,m=async O=>{const D=r.get(O)??(await d(),r.get(O));if(!D)return"";const M=h.get(O);if(M&&Date.now()-M.at<yH&&M.seq===D.seq)return M.text;let N=await a(D.live?`/sessions/${encodeURIComponent(O)}/log`:`/disksessions/${encodeURIComponent(O)}/log`).catch(()=>"");return D.live&&D.cwd&&(N=l(N,D.cwd)),h.set(O,{at:Date.now(),seq:D.seq,text:N}),N};let p=null;const x=async()=>p||(p=await n("/roots").then(O=>O.roots.filter(D=>D.exists)).catch(()=>[]),p),b=new Map,y=async O=>n(`/roots/${encodeURIComponent(O)}/list`).then(D=>D.files).catch(()=>[]),k=(O,D,M,N="")=>`/roots/${encodeURIComponent(O)}/${D}?rel=${encodeURIComponent(M)}${N}`,T=[];let w=!1;const _=async()=>{const O=new Map([...r].map(([M,N])=>[M,N.seq])),D=await d().catch(()=>[]);for(const M of D){if(!M.live)continue;const N=O.get(M.id);if(N===void 0||M.seq!==null&&N!==null&&M.seq>N){h.delete(M.id);for(const R of T)R({rootKey:sc,rel:s(M.id)})}}for(const M of await x())for(const N of await y(M.key)){const R=`${M.key}|${N.rel}`,B=b.get(R);if(b.set(R,N.mtime),B!==void 0&&N.mtime>B)for(const U of T)U({rootKey:M.key,rel:N.rel})}},A=O=>{window.parent.postMessage({source:"dsh-thoughtdag",type:"td:select-session",session:O},window.location.origin)},C={roots:async()=>[{key:sc,path:"~/.dsh/sessions",builtin:!0,exists:!0},...await x()],addRoot:async()=>null,removeRoot:async()=>{},list:async O=>{if(O!==sc){const D=await y(O);for(const M of D)b.set(`${O}|${M.rel}`,M.mtime);return D}return(await d()).map(D=>({rel:s(D.id),size:D.size,mtime:D.mtime}))},head:async(O,D,M)=>{if(O!==sc)return a(k(O,"head",D,`&bytes=${Math.max(1024,M|0)}`)).catch(()=>"");const N=c(D);return N?(await m(N)).slice(0,Math.min(Math.max(1024,M|0),524288)):""},read:async(O,D)=>{if(O!==sc)return a(k(O,"read",D)).catch(()=>"");const M=c(D);return M?m(M):""},readRange:async(O,D,M,N)=>{if(O!==sc)return n(k(O,"range",D,`&start=${M|0}&length=${N|0}`)).catch(()=>({text:"",nextStart:M|0,eof:!0}));const R=c(D),B=R?await m(R):"",U=Math.max(0,M|0),Y=Math.min(Math.max(65536,N|0),32*1024*1024),Z=Math.min(Y,Math.max(0,B.length-U));if(Z===0)return{text:"",nextStart:U,eof:!0};let W=B.slice(U,U+Z);const K=U+Z>=B.length;if(!K){const F=W.lastIndexOf(`
63
63
  `);if(F<0)return{text:"",nextStart:U+Z,eof:!1};W=W.slice(0,F+1)}return{text:W,nextStart:U+W.length,eof:K}},openInCli:async(O,D,M)=>O!=="dsh"?{opened:!1,via:"app",command:""}:(A(M),{opened:!0,via:"app",command:""}),openTargets:async()=>({terminals:[],apps:[{runner:"dsh",name:"DeepSeek Harness"}],prefs:{terminal:""},canAddCustom:!1}),setOpenPrefs:async O=>O,addTerminal:async()=>null,watchStart:async()=>(w||(w=!0,await d().catch(()=>{}),window.setInterval(()=>{_()},vH)),!0),onSessionsChanged:O=>{T.push(O)}};window.desktopSessions=C,window.addEventListener("message",O=>{const D=O.data;O.origin!==window.location.origin||D?.source!=="dsh-thoughtdag"||D.type==="td:current-session"&&(_x=D.session??null,window.dispatchEvent(new CustomEvent("td:dsh-current",{detail:_x})))}),window.parent.postMessage({source:"dsh-thoughtdag",type:"td:request-current"},window.location.origin)}const kH="harness/agent";async function EH(){try{const{useStore:e}=await Kt(async()=>{const{useStore:r}=await Promise.resolve().then(()=>Hb);return{useStore:r}},void 0),t=new Map;for(const r of e.getState().nodes){const s=r.data.importSource?.cwd;s&&t.set(s,(t.get(s)??0)+1)}let n=null,a=0;for(const[r,s]of t)s>a&&(n=r,a=s);return n}catch{return null}}async function TH(e,t){if(!window.desktopSessions||t!==kH)return;const n=await EH()??_x?.cwd??void 0;try{const{useStore:a}=await Kt(async()=>{const{useStore:h}=await Promise.resolve().then(()=>Hb);return{useStore:h}},void 0),{useProjects:r}=await Kt(async()=>{const{useProjects:h}=await Promise.resolve().then(()=>gm);return{useProjects:h}},void 0),{projects:s,activeId:l}=r.getState(),d=s.find(h=>h.id===l)?.sourceSession;if(d&&d.runner==="dsh"){const h=a.getState().edges.filter(m=>m.target===e);if(h.length===1&&h[0].source===d.tailNodeId)return{...n?{cwd:n}:{},session:d.sessionId}}}catch{}return n?{cwd:n}:{}}const F7=(e,t,n,a,r,s)=>{const l=r?[r]:[];e(c=>({nodes:c.nodes.map(d=>d.id===t?{...d,data:{...d.data,importSource:{runner:"dsh",sessionId:n,itemIds:l,...a.cwd?{cwd:a.cwd}:{}},...s?{source:s}:{}}}:d)}))};async function q7(e,t){if(!e)return!1;const{useProjects:n,patchLedgerEntry:a}=await Kt(async()=>{const{useProjects:d,patchLedgerEntry:h}=await Promise.resolve().then(()=>gm);return{useProjects:d,patchLedgerEntry:h}},void 0),{projects:r,activeId:s}=n.getState();if(!s)return!1;const l=r.find(d=>d.id===s)?.sourceSession;if(!l)return!1;const c=l.sessionId===e?l:l.chapters?.find(d=>d.sessionId===e)??l.branches?.find(d=>d.sessionId===e);return c?(await a(s,e,{importedCount:c.importedCount+1,tailNodeId:t}),!0):!1}async function SH(e,t,n,a){return window.desktopSessions?(F7(e,t,n.session??a.session,n,a.userMessageId),q7(n.session,t)):!1}async function AH(e,t,n,a,r,s,l,c=!1){if(!window.desktopSessions)return;const d=r.session??l?.session??s;d&&(F7(e,n,d,r,l?.userMessageId??null,{question:a.question,response:a.response}),c||await q7(r.session,n))}const NH=45,CH=3,_H=/sk-[a-zA-Z0-9_-]{8,}|api[ _-]?key|password|token|secret/i,Mx=new Map;function MH(e){return e.category!=="project"?!0:(Date.now()-new Date(e.at).getTime())/864e5<=NH}function IH(){const{memoryEnabled:e,memories:t}=xe.getState();if(!e)return null;const n=t.filter(MH);return n.length===0?null:{role:"user",content:`[Memory] Durable notes about this user, recorded across earlier sessions. Use them ONLY where relevant; never recite them, never treat them as part of the current question:
64
64
  ${n.map(r=>`- ${r.text}`).join(`
@@ -131,13 +131,13 @@ For each candidate above, judge what evidence would rule it OUT and what would r
131
131
  严格从这个视角,为上面的问题给出唯一最佳的候选解释:说清机制、可检验的预测,以及什么证据能确认或排除它。`},{id:"conf",kind:"prompt",x:980,y:440,title:"候选:混杂",instruction:`你主张这个效应是假象或混杂因素,而非目标现象。
132
132
  严格从这个视角,为上面的问题给出唯一最佳的候选解释:说清疑似的混杂来源、可检验的预测,以及什么证据能确认或排除它。`},{id:"null",kind:"prompt",x:1460,y:440,title:"候选:零假设",instruction:`你主张这个效应可能不真实或被夸大,给出最强的收缩性论证。
133
133
  严格从这个视角回答上面的问题:什么会让效应消失,以及什么证据能确认或排除这一解释。`},{id:"rev",kind:"prompt",x:560,y:920,title:"鉴别评审",instruction:`你是一位严谨的方法学家,正在对相互竞争的解释做鉴别诊断。
134
- 对上面每个候选,判断什么证据能将它排除(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 VH(e){const{name:t,steps:n,edges:a}=g5[e]??g5.en,r=n.map(l=>({id:`p-${l.id}`,type:"thought",position:{x:l.x,y:l.y},dragHandle:".drag-handle",data:{question:l.title,instruction:l.instruction,stepKind:l.kind,response:"",responses:[],responseIndex:-1,isCollapsed:!1,isEditing:!1,isEditingResponse:!1,isLoading:!1,tokenCount:0,highlights:[],highlightMode:"tag",attachments:[],excludedAttachmentIds:[],includedAttachmentIds:[],roleMode:"inherit",isRoot:l.id==="q",isBranch:!1}})),s=a.map(([l,c])=>({id:`p-e-${l}-${c}`,source:`p-${l}`,target:`p-${c}`,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 Ix="thoughtdag:projects",x5="thoughtdag",ni=e=>`thoughtdag:project:${e}`;async function Df(e,t){const{projects:n,activeId:a}=Cn.getState();if(t&&e===a){const r=n.filter(s=>s.id!==e&&!s.archived).sort((s,l)=>l.updatedAt-s.updatedAt);r.length>0?await Ss(r[0].id):await pm("My Canvas")}Cn.setState(r=>({projects:r.projects.map(s=>s.id===e?{...s,archived:t}:s)})),await si()}async function GH(e,t){Cn.setState(n=>({projects:n.projects.map(a=>a.id===e&&a.sourceSession?{...a,sourceSession:{...a.sourceSession,...t}}:a)})),await si()}async function YH(e,t,n){Cn.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(l=>l.sessionId===t?{...l,...n}:l),branches:s.branches?.map(l=>l.sessionId===t?{...l,...n}:l)}}})})),await si()}async function $H(e,t,n){Cn.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 si()}async function KH(e,t){Cn.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),l=(r.branches??[]).filter(d=>d.sessionId!==t),c={...r,chapters:s.length?s:void 0,branches:l.length?l:void 0};return c.sessionId===t&&(c.sessionId="",c.runner="",c.importedCount=0,c.tailNodeId=""),!c.sessionId&&s.length===0&&l.length===0?{...a,sourceSession:void 0}:{...a,sourceSession:c}})})),await si()}function Dx(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 W7(e,t){Cn.setState(n=>({projects:n.projects.map(a=>a.id===e?{...a,instantiatedFrom:{name:t,at:new Date().toISOString()}}:a)})),await si()}const Cn=Kd(()=>({projects:[],activeId:null,switching:!1}));async function si(){const{projects:e,activeId:t}=Cn.getState();await zr(Ix,{projects:e,activeId:t})}let b5=null;function V7(){return b5??=(async()=>{let e=await bl(Ix);if(!e||e.projects.length===0){const t=await bl(x5),n=crypto.randomUUID(),a=Date.now();t&&await zr(ni(n),t),e={projects:[{id:n,name:"My Canvas",createdAt:a,updatedAt:a}],activeId:n},await zr(Ix,e),t&&await jc(x5)}e.projects.some(t=>t.id===e.activeId)||(e.activeId=e.projects[0].id),Cn.setState({projects:e.projects,activeId:e.activeId}),oe.persist.setOptions({name:ni(e.activeId)}),await oe.persist.rehydrate()})().catch(async e=>{console.error("[thoughtdag] project boot failed:",e),Ke("error",Ie("toast.projectsLoadFailed")),oe.persist.setOptions({name:ni("recovery")}),await oe.persist.rehydrate()}),b5}let Ox=!1;async function XH(){for(const t of ks.values())t.abort();const e=Date.now()+1e3;for(;ks.size>0&&Date.now()<e;)await new Promise(t=>setTimeout(t,30));await new Promise(t=>setTimeout(t,0))}const G7=[];async function Ss(e){for(const r of G7)await r().catch(()=>{});const{activeId:t,switching:n,projects:a}=Cn.getState();if(!(n||e===t||!a.some(r=>r.id===e))){Cn.setState({switching:!0});try{await XH(),await SB(),Ox=!0,oe.persist.setOptions({name:ni(e)}),await oe.persist.rehydrate(),oe.setState({selectedNodeId:null,selectedNodeIds:[]}),Cn.setState(r=>({activeId:e,projects:r.projects.map(s=>s.id===e&&s.archived?{...s,archived:!1}:s)})),await si()}finally{Ox=!1,Cn.setState({switching:!1})}}}async function pm(e="Untitled",t="chat"){const n=crypto.randomUUID(),a=Date.now();return Cn.setState(r=>({projects:[...r.projects,{id:n,name:e,createdAt:a,updatedAt:a,kind:t}]})),await si(),await Ss(n),n}async function Y7(e,t){Cn.setState(n=>({projects:n.projects.map(a=>a.id===e?{...a,name:t}:a)})),await si()}async function $7(e){const{projects:t,activeId:n}=Cn.getState();if(e===n){const a=t.filter(r=>r.id!==e);a.length>0?await Ss(a[0].id):await pm("My Canvas")}await jc(ni(e)),Cn.setState(a=>({projects:a.projects.filter(r=>r.id!==e)})),await si(),Kt(()=>import("./canvas-record-GBNDUaVp.js"),[]).then(a=>a.removeCanvasRecord(e)).catch(()=>{})}async function Pc(e,t,n="chat",a){const r=Date.now();Cn.setState(s=>({projects:[...s.projects,{id:e,name:t,createdAt:r,updatedAt:r,kind:n,...a}]})),await si(),await Ss(e)}async function QH(e){const{name:t,nodes:n,edges:a}=VH(e),r=crypto.randomUUID();await zr(ni(r),JSON.stringify({state:{nodes:n,edges:a},version:1})),await Pc(r,t,"paradigm")}let d1=null;oe.subscribe((e,t)=>{Ox||e.nodes===t.nodes&&e.edges===t.edges||(d1&&clearTimeout(d1),d1=setTimeout(()=>{const{activeId:n}=Cn.getState();if(!n)return;const a=[...new Set(oe.getState().nodes.map(r=>r.data.importSource?.sessionId).filter(r=>!!r))];Cn.setState(r=>({projects:r.projects.map(s=>s.id===n?{...s,updatedAt:Date.now(),provenanceSessions:a}:s)})),si()},1e3))});const gm=Object.freeze(Object.defineProperty({__proto__:null,adoptImportedProject:Pc,beforeSwitchHooks:G7,bootProjects:V7,createBuiltinParadigm:QH,createProject:pm,deleteProject:$7,markInstantiatedFrom:W7,patchLedgerEntry:YH,projectStorageKey:ni,registerLedgerEntry:$H,removeLedgerEntry:KH,renameProject:Y7,setProjectArchived:Df,subscribedSessionIds:Dx,switchProject:Ss,updateSourceSession:GH,useProjects:Cn},Symbol.toStringTag,{value:"Module"}));function K7(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 X7(e,t,n){return{id:In(),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 Q7(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 Z7(e){const t=e.message?.content?.parts;return Array.isArray(t)?t.filter(n=>typeof n=="string").join(`
134
+ 对上面每个候选,判断什么证据能将它排除(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 VH(e){const{name:t,steps:n,edges:a}=g5[e]??g5.en,r=n.map(l=>({id:`p-${l.id}`,type:"thought",position:{x:l.x,y:l.y},dragHandle:".drag-handle",data:{question:l.title,instruction:l.instruction,stepKind:l.kind,response:"",responses:[],responseIndex:-1,isCollapsed:!1,isEditing:!1,isEditingResponse:!1,isLoading:!1,tokenCount:0,highlights:[],highlightMode:"tag",attachments:[],excludedAttachmentIds:[],includedAttachmentIds:[],roleMode:"inherit",isRoot:l.id==="q",isBranch:!1}})),s=a.map(([l,c])=>({id:`p-e-${l}-${c}`,source:`p-${l}`,target:`p-${c}`,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 Ix="thoughtdag:projects",x5="thoughtdag",ni=e=>`thoughtdag:project:${e}`;async function Df(e,t){const{projects:n,activeId:a}=Cn.getState();if(t&&e===a){const r=n.filter(s=>s.id!==e&&!s.archived).sort((s,l)=>l.updatedAt-s.updatedAt);r.length>0?await Ss(r[0].id):await pm("My Canvas")}Cn.setState(r=>({projects:r.projects.map(s=>s.id===e?{...s,archived:t}:s)})),await si()}async function GH(e,t){Cn.setState(n=>({projects:n.projects.map(a=>a.id===e&&a.sourceSession?{...a,sourceSession:{...a.sourceSession,...t}}:a)})),await si()}async function YH(e,t,n){Cn.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(l=>l.sessionId===t?{...l,...n}:l),branches:s.branches?.map(l=>l.sessionId===t?{...l,...n}:l)}}})})),await si()}async function $H(e,t,n){Cn.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 si()}async function KH(e,t){Cn.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),l=(r.branches??[]).filter(d=>d.sessionId!==t),c={...r,chapters:s.length?s:void 0,branches:l.length?l:void 0};return c.sessionId===t&&(c.sessionId="",c.runner="",c.importedCount=0,c.tailNodeId=""),!c.sessionId&&s.length===0&&l.length===0?{...a,sourceSession:void 0}:{...a,sourceSession:c}})})),await si()}function Dx(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 W7(e,t){Cn.setState(n=>({projects:n.projects.map(a=>a.id===e?{...a,instantiatedFrom:{name:t,at:new Date().toISOString()}}:a)})),await si()}const Cn=Kd(()=>({projects:[],activeId:null,switching:!1}));async function si(){const{projects:e,activeId:t}=Cn.getState();await zr(Ix,{projects:e,activeId:t})}let b5=null;function V7(){return b5??=(async()=>{let e=await bl(Ix);if(!e||e.projects.length===0){const t=await bl(x5),n=crypto.randomUUID(),a=Date.now();t&&await zr(ni(n),t),e={projects:[{id:n,name:"My Canvas",createdAt:a,updatedAt:a}],activeId:n},await zr(Ix,e),t&&await jc(x5)}e.projects.some(t=>t.id===e.activeId)||(e.activeId=e.projects[0].id),Cn.setState({projects:e.projects,activeId:e.activeId}),oe.persist.setOptions({name:ni(e.activeId)}),await oe.persist.rehydrate()})().catch(async e=>{console.error("[thoughtdag] project boot failed:",e),Ke("error",Ie("toast.projectsLoadFailed")),oe.persist.setOptions({name:ni("recovery")}),await oe.persist.rehydrate()}),b5}let Ox=!1;async function XH(){for(const t of ks.values())t.abort();const e=Date.now()+1e3;for(;ks.size>0&&Date.now()<e;)await new Promise(t=>setTimeout(t,30));await new Promise(t=>setTimeout(t,0))}const G7=[];async function Ss(e){for(const r of G7)await r().catch(()=>{});const{activeId:t,switching:n,projects:a}=Cn.getState();if(!(n||e===t||!a.some(r=>r.id===e))){Cn.setState({switching:!0});try{await XH(),await SB(),Ox=!0,oe.persist.setOptions({name:ni(e)}),await oe.persist.rehydrate(),oe.setState({selectedNodeId:null,selectedNodeIds:[]}),Cn.setState(r=>({activeId:e,projects:r.projects.map(s=>s.id===e&&s.archived?{...s,archived:!1}:s)})),await si()}finally{Ox=!1,Cn.setState({switching:!1})}}}async function pm(e="Untitled",t="chat"){const n=crypto.randomUUID(),a=Date.now();return Cn.setState(r=>({projects:[...r.projects,{id:n,name:e,createdAt:a,updatedAt:a,kind:t}]})),await si(),await Ss(n),n}async function Y7(e,t){Cn.setState(n=>({projects:n.projects.map(a=>a.id===e?{...a,name:t}:a)})),await si()}async function $7(e){const{projects:t,activeId:n}=Cn.getState();if(e===n){const a=t.filter(r=>r.id!==e);a.length>0?await Ss(a[0].id):await pm("My Canvas")}await jc(ni(e)),Cn.setState(a=>({projects:a.projects.filter(r=>r.id!==e)})),await si(),Kt(()=>import("./canvas-record-sMlQAe86.js"),[]).then(a=>a.removeCanvasRecord(e)).catch(()=>{})}async function Pc(e,t,n="chat",a){const r=Date.now();Cn.setState(s=>({projects:[...s.projects,{id:e,name:t,createdAt:r,updatedAt:r,kind:n,...a}]})),await si(),await Ss(e)}async function QH(e){const{name:t,nodes:n,edges:a}=VH(e),r=crypto.randomUUID();await zr(ni(r),JSON.stringify({state:{nodes:n,edges:a},version:1})),await Pc(r,t,"paradigm")}let d1=null;oe.subscribe((e,t)=>{Ox||e.nodes===t.nodes&&e.edges===t.edges||(d1&&clearTimeout(d1),d1=setTimeout(()=>{const{activeId:n}=Cn.getState();if(!n)return;const a=[...new Set(oe.getState().nodes.map(r=>r.data.importSource?.sessionId).filter(r=>!!r))];Cn.setState(r=>({projects:r.projects.map(s=>s.id===n?{...s,updatedAt:Date.now(),provenanceSessions:a}:s)})),si()},1e3))});const gm=Object.freeze(Object.defineProperty({__proto__:null,adoptImportedProject:Pc,beforeSwitchHooks:G7,bootProjects:V7,createBuiltinParadigm:QH,createProject:pm,deleteProject:$7,markInstantiatedFrom:W7,patchLedgerEntry:YH,projectStorageKey:ni,registerLedgerEntry:$H,removeLedgerEntry:KH,renameProject:Y7,setProjectArchived:Df,subscribedSessionIds:Dx,switchProject:Ss,updateSourceSession:GH,useProjects:Cn},Symbol.toStringTag,{value:"Module"}));function K7(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 X7(e,t,n){return{id:In(),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 Q7(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 Z7(e){const t=e.message?.content?.parts;return Array.isArray(t)?t.filter(n=>typeof n=="string").join(`
135
135
  `).trim():""}function ZH(e){const t=[],n=[],a=Object.values(e).filter(s=>!s.parent||!e[s.parent]),r=(s,l,c)=>{const d=e[s];if(!d)return;const h=d.message?.author?.role,m=Z7(d);let p=l,x=c;if(h==="user"&&m)p=m;else if(h==="assistant"&&m){if(p!==null){const b=X7(p,m,c===null);t.push(b),c&&n.push(Q7(c,b.id)),x=b.id,p=null}else if(x){const b=t.find(y=>y.id===x);b&&(b.data.response+=`
136
136
 
137
137
  `+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:nr(t,n),edges:n}}function J7(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(`
138
138
  `).trim():""}function JH(e){const t=[],n=[];let a=null,r=null;for(const s of e){const l=J7(s);if(l){if(s.sender==="human")a=l;else if(s.sender==="assistant"){if(a!==null){const c=X7(a,l,r===null);t.push(c),r&&n.push(Q7(r,c.id)),r=c.id,a=null}else if(r){const c=t.find(d=>d.id===r);c&&(c.data.response+=`
139
139
 
140
- `+l,c.data.responses=[c.data.response])}}}}return{nodes:nr(t,n),edges:n}}function eU(e){const t=K7(e),n=[];if(t==="chatgpt")for(const a of e){const r=a.mapping??{},s=Object.values(r).filter(l=>["user","assistant"].includes(l.message?.author?.role??"")&&Z7(l)).length;s!==0&&n.push({title:a.title||"Untitled",messageCount:s,source:"chatgpt",build:()=>ZH(r)})}else if(t==="claude")for(const a of e){const r=a.chat_messages??[],s=r.filter(l=>J7(l)).length;s!==0&&n.push({title:a.name||"Untitled",messageCount:s,source:"claude",build:()=>JH(r)})}return n}function tU(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 nU(e){const t=e;return!!t&&typeof t=="object"&&t.kind==="thoughtdag-paradigm"&&Array.isArray(t.nodes)&&Array.isArray(t.edges)}const aU=()=>({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 rU(e,t){const n=new Map,a=e.map(c=>{const d=In();n.set(c.id,d);const h=c.data.stepKind??"prompt",m=(c.data.instruction?.trim()||c.data.question||"").trim(),p={...aU(),question:m,rolePrompt:c.data.rolePrompt||void 0,roleMode:c.data.rolePrompt?"reset":"inherit"};return h==="human"&&(p.stepKind="human",p.question="",p.instruction=c.data.instruction?.trim()||void 0,p.rolePrompt=void 0,p.roleMode="inherit"),h==="prompt"&&(p.stepKind="prompt",p.webSearch=c.data.webSearch,p.scholarSearch=c.data.scholarSearch,p.autoRerun=c.data.autoRerun,p.autoRerunRounds=c.data.autoRerunRounds),(h==="note"||h==="file"||h==="link"||h==="frame")&&(p.stepKind=h,p.question=c.data.question||"",p.attachments=c.data.attachments??[],p.tokenCount=c.data.tokenCount??0,p.linkUrl=c.data.linkUrl,p.linkTitle=c.data.linkTitle,p.linkFetchedAt=c.data.linkFetchedAt,p.frameColor=c.data.frameColor),h==="review"&&(p.isEvaluator=!0,p.autoRerun=!0,p.autoRerunRounds=c.data.autoRerunRounds,p.rolePrompt||(p.roleMode="inherit")),h==="fanout"&&(p.stepKind="fanout",p.fanoutRoles=c.data.fanoutRoles),{id:d,type:"thought",position:{...c.position},width:c.width,height:c.height,zIndex:c.zIndex,dragHandle:".drag-handle",data:p}}),r=new Set(e.filter(c=>(c.data.stepKind??"step")==="review").map(c=>n.get(c.id))),s=t.filter(c=>n.has(c.source)&&n.has(c.target)).map(c=>{const d=n.get(c.source),h=n.get(c.target);return r.has(h)?{id:`watch-${d}-${h}`,source:d,target:h,sourceHandle:"branch",targetHandle:"left",type:"smoothstep",style:{stroke:nt.watch,strokeWidth:2,strokeDasharray:"4 4"},animated:!0,markerEnd:{type:"arrowclosed",color:nt.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:nt.accent,strokeWidth:2},animated:!1,markerEnd:{type:"arrowclosed",color:nt.accent,width:18,height:18},data:{}}}),l=new Set(s.map(c=>c.target));for(const c of a)l.has(c.id)||(c.data.isRoot=!0);return{nodes:nr(a,s),edges:s}}const eT=1,Ub=1;function xm(e){return e.replace(/[\\/:*?"<>|]/g,"_").trim()||"canvas"}function Jd(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 Fb(e){await navigator.clipboard.writeText(e),Ke("success",Ie("toast.copied"))}function As(){const{projects:e,activeId:t}=Cn.getState();return e.find(n=>n.id===t)?.name??"canvas"}async function cf(e){const{nodes:t}=oe.getState(),{confirmIfSensitive:n}=await Kt(async()=>{const{confirmIfSensitive:p}=await import("./sensitive-scan-BVopW_mj.js");return{confirmIfSensitive:p}},[]);if(!await n(t))return;localStorage.setItem("thoughtdag.lastBackupAt",String(Date.now()));const{nodes:a,edges:r,events:s}=oe.getState(),l=await P7(a),{projects:c,activeId:d}=Cn.getState(),h=As(),m=JSON.stringify({version:eT,name:h,projectId:d,exportedAt:new Date().toISOString(),instantiatedFrom:c.find(p=>p.id===d)?.instantiatedFrom,...e?.sharedReadonly?{sharedReadonly:!0}:{},nodes:No(l),edges:r,events:s});Jd(`${xm(h)}.thoughtdag.json`,m,"application/json"),Ke("success",Ue(Ie("toast.exported"),{name:h}))}function iU(){const{nodes:e,edges:t}=oe.getState(),n=As(),a=JSON.stringify({kind:"thoughtdag-paradigm",version:1,name:n,nodes:No(e),edges:t});Jd(`${xm(n)}.paradigm.json`,a,"application/json"),Ke("success",Ue(Ie("toast.exported"),{name:n}))}async function sU(e){const t=await e.text();let n;try{n=JSON.parse(t)}catch{const{anyRunnerSessionConversation:r}=await Kt(async()=>{const{anyRunnerSessionConversation:l}=await import("./index-NvCD8Rvo.js");return{anyRunnerSessionConversation:l}},[]),s=await r(t);return s?{kind:"chat",conversations:[s]}:(Ke("error",Ie("toast.importFailedJson")),{kind:"error"})}if(nU(n)){const r=crypto.randomUUID(),s=await Pb(await tT(n.nodes));return await zr(ni(r),JSON.stringify({state:{nodes:s,edges:n.edges},version:Ub})),await Pc(r,n.name||"Paradigm","paradigm"),Ke("success",Ue(Ie("toast.imported"),{name:n.name,n:n.nodes.length})),{kind:"own",ok:!0}}if(n?.format==="thoughtdag-manifest")return Ke("error",Ie("toast.importManifest"),9e3),{kind:"error"};const a=K7(n);if(a==="chatgpt"||a==="claude"){const r=eU(n);return r.length===0?(Ke("error",Ie("toast.importNoConversations")),{kind:"error"}):{kind:"chat",conversations:r}}return{kind:"own",ok:await cU(e,n)}}function oU(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 lU(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:c}=await Kt(async()=>{const{useUiStore:d}=await Promise.resolve().then(()=>hm);return{useUiStore:d}},void 0);c.getState().setArrivalFocusNodeId(r[r.length-1].id)}const l=crypto.randomUUID();await zr(ni(l),JSON.stringify({state:{nodes:No(r),edges:s},version:Ub})),await Pc(l,a.title.slice(0,60)),t??=l,n+=r.length}t&&Ke("success",Ue(Ie("toast.importedChats"),{n:e.length,m:n}))}async function tT(e){const t=await Do();if(!t||t.models.length===0)return e;const n=new Set,a=new Set,r=e.map(s=>{const l=s.data?.model;if(!l)return s;const c=A7(l,t.models);return c===l?s:c?(n.add(`${l} → ${c}`),{...s,data:{...s.data,model:c}}):(a.add(l),s)});return n.size&&Ke("info",Ue(Ie("import.modelsRemapped"),{list:[...n].join(",")}),9e3),a.size&&Ke("info",Ue(Ie("import.modelsMissing"),{list:[...a].join(",")}),1e4),r}async function cU(e,t){let n;try{n=t??JSON.parse(await e.text())}catch{return Ke("error",Ie("toast.importFailedJson")),!1}if(!Array.isArray(n.nodes)||!Array.isArray(n.edges))return Ke("error",Ie("toast.importFailedMissing")),!1;if(n.nodes.length>0&&!oU(n.nodes))return Ke("error",Ie("toast.importFailedShape"),9e3),!1;if(n.sharedReadonly&&!await Ts({title:Ie("import.readonlyTitle"),message:Ie("import.readonlyConfirm"),confirmLabel:Ie("common.confirm")}))return!1;if(n.sourceSession?.sessionId){const{useProjects:l,switchProject:c}=await Kt(async()=>{const{useProjects:h,switchProject:m}=await Promise.resolve().then(()=>gm);return{useProjects:h,switchProject:m}},void 0),d=l.getState().projects.find(h=>h.sourceSession?.sessionId===n.sourceSession.sessionId);if(d)return await c(d.id),Ke("info",Ue(Ie("toast.importAlreadySubscribed"),{name:d.name}),9e3),!0}const a=crypto.randomUUID(),r=await Pb(await tT(n.nodes));await zr(ni(a),JSON.stringify({state:{nodes:No(r),edges:n.edges,...Array.isArray(n.events)?{events:n.events}:{}},version:Ub}));const s=n.name?.trim()||e.name.replace(/\.thoughtdag\.json$|\.json$/i,"")||"Imported canvas";return await Pc(a,s,"chat",{instantiatedFrom:n.instantiatedFrom,sourceSession:n.sourceSession}),Ke("success",Ue(Ie("toast.imported"),{name:s,n:n.nodes.length})),!0}function uU(){const{events:e}=oe.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(`
140
+ `+l,c.data.responses=[c.data.response])}}}}return{nodes:nr(t,n),edges:n}}function eU(e){const t=K7(e),n=[];if(t==="chatgpt")for(const a of e){const r=a.mapping??{},s=Object.values(r).filter(l=>["user","assistant"].includes(l.message?.author?.role??"")&&Z7(l)).length;s!==0&&n.push({title:a.title||"Untitled",messageCount:s,source:"chatgpt",build:()=>ZH(r)})}else if(t==="claude")for(const a of e){const r=a.chat_messages??[],s=r.filter(l=>J7(l)).length;s!==0&&n.push({title:a.name||"Untitled",messageCount:s,source:"claude",build:()=>JH(r)})}return n}function tU(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 nU(e){const t=e;return!!t&&typeof t=="object"&&t.kind==="thoughtdag-paradigm"&&Array.isArray(t.nodes)&&Array.isArray(t.edges)}const aU=()=>({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 rU(e,t){const n=new Map,a=e.map(c=>{const d=In();n.set(c.id,d);const h=c.data.stepKind??"prompt",m=(c.data.instruction?.trim()||c.data.question||"").trim(),p={...aU(),question:m,rolePrompt:c.data.rolePrompt||void 0,roleMode:c.data.rolePrompt?"reset":"inherit"};return h==="human"&&(p.stepKind="human",p.question="",p.instruction=c.data.instruction?.trim()||void 0,p.rolePrompt=void 0,p.roleMode="inherit"),h==="prompt"&&(p.stepKind="prompt",p.webSearch=c.data.webSearch,p.scholarSearch=c.data.scholarSearch,p.autoRerun=c.data.autoRerun,p.autoRerunRounds=c.data.autoRerunRounds),(h==="note"||h==="file"||h==="link"||h==="frame")&&(p.stepKind=h,p.question=c.data.question||"",p.attachments=c.data.attachments??[],p.tokenCount=c.data.tokenCount??0,p.linkUrl=c.data.linkUrl,p.linkTitle=c.data.linkTitle,p.linkFetchedAt=c.data.linkFetchedAt,p.frameColor=c.data.frameColor),h==="review"&&(p.isEvaluator=!0,p.autoRerun=!0,p.autoRerunRounds=c.data.autoRerunRounds,p.rolePrompt||(p.roleMode="inherit")),h==="fanout"&&(p.stepKind="fanout",p.fanoutRoles=c.data.fanoutRoles),{id:d,type:"thought",position:{...c.position},width:c.width,height:c.height,zIndex:c.zIndex,dragHandle:".drag-handle",data:p}}),r=new Set(e.filter(c=>(c.data.stepKind??"step")==="review").map(c=>n.get(c.id))),s=t.filter(c=>n.has(c.source)&&n.has(c.target)).map(c=>{const d=n.get(c.source),h=n.get(c.target);return r.has(h)?{id:`watch-${d}-${h}`,source:d,target:h,sourceHandle:"branch",targetHandle:"left",type:"smoothstep",style:{stroke:nt.watch,strokeWidth:2,strokeDasharray:"4 4"},animated:!0,markerEnd:{type:"arrowclosed",color:nt.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:nt.accent,strokeWidth:2},animated:!1,markerEnd:{type:"arrowclosed",color:nt.accent,width:18,height:18},data:{}}}),l=new Set(s.map(c=>c.target));for(const c of a)l.has(c.id)||(c.data.isRoot=!0);return{nodes:nr(a,s),edges:s}}const eT=1,Ub=1;function xm(e){return e.replace(/[\\/:*?"<>|]/g,"_").trim()||"canvas"}function Jd(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 Fb(e){await navigator.clipboard.writeText(e),Ke("success",Ie("toast.copied"))}function As(){const{projects:e,activeId:t}=Cn.getState();return e.find(n=>n.id===t)?.name??"canvas"}async function cf(e){const{nodes:t}=oe.getState(),{confirmIfSensitive:n}=await Kt(async()=>{const{confirmIfSensitive:p}=await import("./sensitive-scan-BjlPCfxy.js");return{confirmIfSensitive:p}},[]);if(!await n(t))return;localStorage.setItem("thoughtdag.lastBackupAt",String(Date.now()));const{nodes:a,edges:r,events:s}=oe.getState(),l=await P7(a),{projects:c,activeId:d}=Cn.getState(),h=As(),m=JSON.stringify({version:eT,name:h,projectId:d,exportedAt:new Date().toISOString(),instantiatedFrom:c.find(p=>p.id===d)?.instantiatedFrom,...e?.sharedReadonly?{sharedReadonly:!0}:{},nodes:No(l),edges:r,events:s});Jd(`${xm(h)}.thoughtdag.json`,m,"application/json"),Ke("success",Ue(Ie("toast.exported"),{name:h}))}function iU(){const{nodes:e,edges:t}=oe.getState(),n=As(),a=JSON.stringify({kind:"thoughtdag-paradigm",version:1,name:n,nodes:No(e),edges:t});Jd(`${xm(n)}.paradigm.json`,a,"application/json"),Ke("success",Ue(Ie("toast.exported"),{name:n}))}async function sU(e){const t=await e.text();let n;try{n=JSON.parse(t)}catch{const{anyRunnerSessionConversation:r}=await Kt(async()=>{const{anyRunnerSessionConversation:l}=await import("./index-CrxLUdb9.js");return{anyRunnerSessionConversation:l}},[]),s=await r(t);return s?{kind:"chat",conversations:[s]}:(Ke("error",Ie("toast.importFailedJson")),{kind:"error"})}if(nU(n)){const r=crypto.randomUUID(),s=await Pb(await tT(n.nodes));return await zr(ni(r),JSON.stringify({state:{nodes:s,edges:n.edges},version:Ub})),await Pc(r,n.name||"Paradigm","paradigm"),Ke("success",Ue(Ie("toast.imported"),{name:n.name,n:n.nodes.length})),{kind:"own",ok:!0}}if(n?.format==="thoughtdag-manifest")return Ke("error",Ie("toast.importManifest"),9e3),{kind:"error"};const a=K7(n);if(a==="chatgpt"||a==="claude"){const r=eU(n);return r.length===0?(Ke("error",Ie("toast.importNoConversations")),{kind:"error"}):{kind:"chat",conversations:r}}return{kind:"own",ok:await cU(e,n)}}function oU(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 lU(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:c}=await Kt(async()=>{const{useUiStore:d}=await Promise.resolve().then(()=>hm);return{useUiStore:d}},void 0);c.getState().setArrivalFocusNodeId(r[r.length-1].id)}const l=crypto.randomUUID();await zr(ni(l),JSON.stringify({state:{nodes:No(r),edges:s},version:Ub})),await Pc(l,a.title.slice(0,60)),t??=l,n+=r.length}t&&Ke("success",Ue(Ie("toast.importedChats"),{n:e.length,m:n}))}async function tT(e){const t=await Do();if(!t||t.models.length===0)return e;const n=new Set,a=new Set,r=e.map(s=>{const l=s.data?.model;if(!l)return s;const c=A7(l,t.models);return c===l?s:c?(n.add(`${l} → ${c}`),{...s,data:{...s.data,model:c}}):(a.add(l),s)});return n.size&&Ke("info",Ue(Ie("import.modelsRemapped"),{list:[...n].join(",")}),9e3),a.size&&Ke("info",Ue(Ie("import.modelsMissing"),{list:[...a].join(",")}),1e4),r}async function cU(e,t){let n;try{n=t??JSON.parse(await e.text())}catch{return Ke("error",Ie("toast.importFailedJson")),!1}if(!Array.isArray(n.nodes)||!Array.isArray(n.edges))return Ke("error",Ie("toast.importFailedMissing")),!1;if(n.nodes.length>0&&!oU(n.nodes))return Ke("error",Ie("toast.importFailedShape"),9e3),!1;if(n.sharedReadonly&&!await Ts({title:Ie("import.readonlyTitle"),message:Ie("import.readonlyConfirm"),confirmLabel:Ie("common.confirm")}))return!1;if(n.sourceSession?.sessionId){const{useProjects:l,switchProject:c}=await Kt(async()=>{const{useProjects:h,switchProject:m}=await Promise.resolve().then(()=>gm);return{useProjects:h,switchProject:m}},void 0),d=l.getState().projects.find(h=>h.sourceSession?.sessionId===n.sourceSession.sessionId);if(d)return await c(d.id),Ke("info",Ue(Ie("toast.importAlreadySubscribed"),{name:d.name}),9e3),!0}const a=crypto.randomUUID(),r=await Pb(await tT(n.nodes));await zr(ni(a),JSON.stringify({state:{nodes:No(r),edges:n.edges,...Array.isArray(n.events)?{events:n.events}:{}},version:Ub}));const s=n.name?.trim()||e.name.replace(/\.thoughtdag\.json$|\.json$/i,"")||"Imported canvas";return await Pc(a,s,"chat",{instantiatedFrom:n.instantiatedFrom,sourceSession:n.sourceSession}),Ke("success",Ue(Ie("toast.imported"),{name:s,n:n.nodes.length})),!0}function uU(){const{events:e}=oe.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(`
141
141
  `);Jd(`${xm(As())}.events.csv`,a,"text/csv"),Ke("success",Ue(Ie("toast.exported"),{name:As()}))}function dU(e){const t=[`## Q: ${e.data.question}`,""],n=e.data.attachments||[];return n.length>0&&t.push(`> ${Ie("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(`
142
142
  `)}function nT(e,t){const n=e.reduce((a,r)=>a+$n(r.data.question+r.data.response),0);return[`# ${As()}`,"",`> ${t} · exported ${new Date().toISOString().slice(0,10)} · ${e.length} nodes · ~${n} tok`,"",e.map(dU).join(`
143
143
  ---
@@ -492,17 +492,17 @@ ${Ie("continue.genOpen")}
492
492
  ${c.join(`
493
493
  `)||"-"}`}]),h=m7(new Date().toISOString()).slice(0,10),m=Wte(n.position);Qr("note",m,{question:`**📌 ${h} · ${Ie("continue.recapTag")}**
494
494
 
495
- ${d.trim()}`}),_N.current?.setCenter((n.position.x+m.x)/2+260,(n.position.y+m.y)/2+140,{zoom:.75,duration:600}),Ke("success",Ie("continue.noteDropped"))}catch(a){Ke("error",a instanceof Error?a.message:String(a))}}}function Vte({x:e,y:t,nodeId:n,onClose:a}){const r=Ft(),s=j.useRef(null),l=oe(_=>_.nodes.find(A=>A.id===n));if(j.useEffect(()=>{const _=C=>{s.current?.contains(C.target)||a()},A=C=>{C.key==="Escape"&&a()};return window.addEventListener("mousedown",_),window.addEventListener("keydown",A),()=>{window.removeEventListener("mousedown",_),window.removeEventListener("keydown",A)}},[a]),!l)return null;const c=l.data.stepKind,d=!!c,h=!d&&!!l.data.response&&!l.data.isLoading,m=d?c==="note"||c==="link"?l.data.question:"":l.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=340,k=Math.min(e,window.innerWidth-b-8),T=Math.min(t,window.innerHeight-y-8),w=_=>()=>{a(),_()};return $a.createPortal(u.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:k,top:T},children:[!d&&u.jsxs("button",{className:p,onClick:w(()=>{oe.getState().setSelectedNodeId(n),xe.getState().setPanelOpen(!0)}),children:[u.jsx(So,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.openPanel")]}),h&&u.jsxs("button",{className:p,onClick:w(()=>xe.getState().setResponseViewerNodeId(n)),children:[u.jsx(s7,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.readingView")]}),h&&u.jsxs("button",{className:p,onClick:w(()=>{oe.getState().rerunNode(n)}),children:[u.jsx(ir,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.rerun")]}),h&&u.jsxs("button",{className:p,title:Ie("actions.regenBranchTitle"),onClick:w(()=>{oe.getState().regenerate(n)}),children:[u.jsx(a7,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.regenBranch")]}),h&&u.jsxs("button",{className:p,onClick:w(()=>{MN(n)}),children:[u.jsx(Hi,{size:14,strokeWidth:1.75,className:x})," ",r("continue.summarize")]}),m&&u.jsxs("button",{className:p,onClick:w(()=>{navigator.clipboard.writeText(m).then(()=>Ke("success",Ie("ctx.copied")))}),children:[u.jsx(Ls,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.copyContent")]}),!d&&u.jsxs("button",{className:p,title:Ie("exp.takeTitle"),onClick:w(()=>{Kt(()=>import("./experiment-loop-DmwbMQzX.js"),[]).then(_=>_.takeToExperiment(n,"branch"))}),"data-take-to-experiment":!0,children:[u.jsx(AP,{size:14,strokeWidth:1.75,className:x})," ",r("exp.take")]}),!d&&u.jsxs("button",{className:p,title:Ie("exp.continueTitle"),onClick:w(()=>{Kt(()=>import("./experiment-loop-DmwbMQzX.js"),[]).then(_=>_.takeToExperiment(n,"continue"))}),"data-take-to-continue":!0,children:[u.jsx(So,{size:14,strokeWidth:1.75,className:x})," ",r("exp.continue")]}),u.jsxs("button",{className:p,onClick:w(()=>oe.getState().duplicateNode(n)),children:[u.jsx(TP,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.duplicate")]}),u.jsxs("button",{className:p,onClick:w(()=>oe.getState().setArchived([n],!l.data.archived)),children:[l.data.archived?u.jsx(Q8,{size:14,strokeWidth:1.75,className:x}):u.jsx(Io,{size:14,strokeWidth:1.75,className:x}),l.data.archived?r("ctx.unarchive"):r("archive.label")]}),u.jsx("div",{className:"h-px bg-line my-1"}),u.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:w(()=>{Ts({title:Ie("confirm.deleteNodesTitle"),message:Ue(Ie("confirm.deleteNodes"),{n:1}),confirmLabel:Ie("common.delete"),danger:!0}).then(_=>{_&&oe.getState().deleteNode(n)})}),children:[u.jsx(Fa,{size:14,strokeWidth:1.75,className:"shrink-0"})," ",r("common.delete")]})]}),document.body)}function Gte({onLocate:e}){const t=xe(C=>C.highlightsOverviewOpen),n=xe(C=>C.setHighlightsOverviewOpen),a=oe(C=>C.nodes),r=oe(C=>C.removeHighlight),s=oe(C=>C.weaveHighlights),l=Ft(),[c,d]=j.useState("time"),[h,m]=j.useState(new Set),[p,x]=j.useState(""),b=j.useMemo(()=>{const C=[];for(const D of a){const M=D.data.question.replace(/\s+/g," ").trim().slice(0,60)||"—";for(const N of D.data.highlights||[])C.push({hlId:N.id,text:N.text,at:N.at,nodeId:D.id,nodeTitle:M})}const O=c==="time"?[...C].sort((D,M)=>(M.at??"").localeCompare(D.at??"")):C;return O.map((D,M)=>({...D,showGroup:c==="node"&&(M===0||O[M-1].nodeTitle!==D.nodeTitle)}))},[a,c]);if(!t)return null;const y=C=>{const O=new Set(h);O.has(C)?O.delete(C):O.add(C),m(O)},k=()=>{n(!1),m(new Set),x("")},T=()=>{const C=[...h].filter(D=>b.some(M=>M.hlId===D));if(C.length===0)return;const O=[...new Set(b.filter(D=>C.includes(D.hlId)).map(D=>D.nodeId))];k(),s(O,p.trim()||void 0,C)},w=()=>{const C=b.map(O=>`- ${O.text}
495
+ ${d.trim()}`}),_N.current?.setCenter((n.position.x+m.x)/2+260,(n.position.y+m.y)/2+140,{zoom:.75,duration:600}),Ke("success",Ie("continue.noteDropped"))}catch(a){Ke("error",a instanceof Error?a.message:String(a))}}}function Vte({x:e,y:t,nodeId:n,onClose:a}){const r=Ft(),s=j.useRef(null),l=oe(_=>_.nodes.find(A=>A.id===n));if(j.useEffect(()=>{const _=C=>{s.current?.contains(C.target)||a()},A=C=>{C.key==="Escape"&&a()};return window.addEventListener("mousedown",_),window.addEventListener("keydown",A),()=>{window.removeEventListener("mousedown",_),window.removeEventListener("keydown",A)}},[a]),!l)return null;const c=l.data.stepKind,d=!!c,h=!d&&!!l.data.response&&!l.data.isLoading,m=d?c==="note"||c==="link"?l.data.question:"":l.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=340,k=Math.min(e,window.innerWidth-b-8),T=Math.min(t,window.innerHeight-y-8),w=_=>()=>{a(),_()};return $a.createPortal(u.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:k,top:T},children:[!d&&u.jsxs("button",{className:p,onClick:w(()=>{oe.getState().setSelectedNodeId(n),xe.getState().setPanelOpen(!0)}),children:[u.jsx(So,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.openPanel")]}),h&&u.jsxs("button",{className:p,onClick:w(()=>xe.getState().setResponseViewerNodeId(n)),children:[u.jsx(s7,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.readingView")]}),h&&u.jsxs("button",{className:p,onClick:w(()=>{oe.getState().rerunNode(n)}),children:[u.jsx(ir,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.rerun")]}),h&&u.jsxs("button",{className:p,title:Ie("actions.regenBranchTitle"),onClick:w(()=>{oe.getState().regenerate(n)}),children:[u.jsx(a7,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.regenBranch")]}),h&&u.jsxs("button",{className:p,onClick:w(()=>{MN(n)}),children:[u.jsx(Hi,{size:14,strokeWidth:1.75,className:x})," ",r("continue.summarize")]}),m&&u.jsxs("button",{className:p,onClick:w(()=>{navigator.clipboard.writeText(m).then(()=>Ke("success",Ie("ctx.copied")))}),children:[u.jsx(Ls,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.copyContent")]}),!d&&u.jsxs("button",{className:p,title:Ie("exp.takeTitle"),onClick:w(()=>{Kt(()=>import("./experiment-loop-LWCgLcKh.js"),[]).then(_=>_.takeToExperiment(n,"branch"))}),"data-take-to-experiment":!0,children:[u.jsx(AP,{size:14,strokeWidth:1.75,className:x})," ",r("exp.take")]}),!d&&u.jsxs("button",{className:p,title:Ie("exp.continueTitle"),onClick:w(()=>{Kt(()=>import("./experiment-loop-LWCgLcKh.js"),[]).then(_=>_.takeToExperiment(n,"continue"))}),"data-take-to-continue":!0,children:[u.jsx(So,{size:14,strokeWidth:1.75,className:x})," ",r("exp.continue")]}),u.jsxs("button",{className:p,onClick:w(()=>oe.getState().duplicateNode(n)),children:[u.jsx(TP,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.duplicate")]}),u.jsxs("button",{className:p,onClick:w(()=>oe.getState().setArchived([n],!l.data.archived)),children:[l.data.archived?u.jsx(Q8,{size:14,strokeWidth:1.75,className:x}):u.jsx(Io,{size:14,strokeWidth:1.75,className:x}),l.data.archived?r("ctx.unarchive"):r("archive.label")]}),u.jsx("div",{className:"h-px bg-line my-1"}),u.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:w(()=>{Ts({title:Ie("confirm.deleteNodesTitle"),message:Ue(Ie("confirm.deleteNodes"),{n:1}),confirmLabel:Ie("common.delete"),danger:!0}).then(_=>{_&&oe.getState().deleteNode(n)})}),children:[u.jsx(Fa,{size:14,strokeWidth:1.75,className:"shrink-0"})," ",r("common.delete")]})]}),document.body)}function Gte({onLocate:e}){const t=xe(C=>C.highlightsOverviewOpen),n=xe(C=>C.setHighlightsOverviewOpen),a=oe(C=>C.nodes),r=oe(C=>C.removeHighlight),s=oe(C=>C.weaveHighlights),l=Ft(),[c,d]=j.useState("time"),[h,m]=j.useState(new Set),[p,x]=j.useState(""),b=j.useMemo(()=>{const C=[];for(const D of a){const M=D.data.question.replace(/\s+/g," ").trim().slice(0,60)||"—";for(const N of D.data.highlights||[])C.push({hlId:N.id,text:N.text,at:N.at,nodeId:D.id,nodeTitle:M})}const O=c==="time"?[...C].sort((D,M)=>(M.at??"").localeCompare(D.at??"")):C;return O.map((D,M)=>({...D,showGroup:c==="node"&&(M===0||O[M-1].nodeTitle!==D.nodeTitle)}))},[a,c]);if(!t)return null;const y=C=>{const O=new Set(h);O.has(C)?O.delete(C):O.add(C),m(O)},k=()=>{n(!1),m(new Set),x("")},T=()=>{const C=[...h].filter(D=>b.some(M=>M.hlId===D));if(C.length===0)return;const O=[...new Set(b.filter(D=>C.includes(D.hlId)).map(D=>D.nodeId))];k(),s(O,p.trim()||void 0,C)},w=()=>{const C=b.map(O=>`- ${O.text}
496
496
  — ${O.nodeTitle}${O.at?` · ${O.at.slice(0,10)}`:""}`);qb(`# ${l("hlov.title")}
497
497
 
498
498
  ${C.join(`
499
499
  `)}
500
500
  `)},_="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",A=(C,O)=>u.jsx("button",{onClick:()=>d(C),className:`text-2xs px-2.5 py-1 rounded-full transition-colors ${c===C?"bg-accent/10 text-accent":"text-ink-faint hover:bg-wash"}`,children:O});return $a.createPortal(u.jsx("div",{className:"fixed inset-0 z-[60] bg-ink/30 backdrop-blur-sm flex items-center justify-center p-6",onClick:k,children:u.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:[u.jsxs("div",{className:"flex items-center gap-2 px-5 py-3 border-b border-line shrink-0",children:[u.jsx(Sd,{size:15,strokeWidth:1.75,className:"text-amber-500"}),u.jsx("span",{className:"text-sm font-semibold text-ink",children:l("hlov.title")}),u.jsx("span",{className:"text-2xs text-ink-faint",children:Ue(l("hlov.count"),{n:b.length})}),u.jsx("div",{className:"flex-1"}),A("time",l("hlov.byTime")),A("node",l("hlov.byNode")),u.jsx("button",{onClick:k,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:u.jsx(bn,{size:15,strokeWidth:1.75})})]}),u.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-5 py-3",children:[b.length===0&&u.jsx("p",{className:"text-xs text-ink-faint italic py-2",children:l("hlov.empty")}),b.map(C=>u.jsxs("div",{children:[C.showGroup&&u.jsx("div",{className:"text-2xs text-ink-faint font-medium mt-3 mb-1 first:mt-0 truncate",children:C.nodeTitle}),u.jsxs("div",{className:"group flex items-start gap-2.5 py-1.5 border-b border-line/50 last:border-0",children:[u.jsx("input",{type:"checkbox",checked:h.has(C.hlId),onChange:()=>y(C.hlId),className:"mt-1 accent-amber-500 shrink-0"}),u.jsx("span",{className:"flex-1 text-sm text-ink leading-relaxed min-w-0",children:u.jsx("mark",{className:"bg-amber-100 text-amber-800 px-0.5 rounded",children:C.text})}),c==="time"&&u.jsxs("button",{className:_,onClick:()=>{k(),e(C.nodeId)},title:l("hlov.locateTitle"),children:[C.nodeTitle.slice(0,14),C.nodeTitle.length>14?"…":""]}),c==="node"&&u.jsx("button",{className:_,onClick:()=>{k(),e(C.nodeId)},title:l("hlov.locateTitle"),children:"↦"}),C.at&&u.jsx("span",{className:"shrink-0 text-2xs text-ink-faint font-mono mt-0.5",children:C.at.slice(5,10)}),u.jsx("button",{onClick:()=>r(C.nodeId,C.hlId),title:l("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:u.jsx(Fa,{size:12,strokeWidth:1.75})})]})]},C.hlId))]}),u.jsxs("div",{className:"px-5 py-3 border-t border-line shrink-0 space-y-2",children:[h.size>0&&u.jsxs("div",{className:"flex gap-1.5",children:[u.jsx("input",{type:"text",value:p,onChange:C=>x(C.target.value),onKeyDown:C=>{C.key==="Enter"&&!Ya(C)&&T()},placeholder:l("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"}),u.jsx("button",{onClick:T,className:"text-xs bg-amber-500 hover:bg-amber-400 text-white px-3 py-2 rounded-lg transition-colors shrink-0",children:Ue(l("hlov.weavePicked"),{n:h.size})})]}),u.jsxs("div",{className:"flex items-center",children:[u.jsx("span",{className:"text-2xs text-ink-faint",children:h.size>0?Ue(l("hlov.picked"),{n:h.size}):l("hlov.pickHint")}),u.jsx("div",{className:"flex-1"}),b.length>0&&u.jsxs("button",{onClick:w,className:"flex items-center gap-1.5 text-2xs text-ink-faint hover:text-ink-muted transition-colors",title:l("hlov.exportTitle"),children:[u.jsx(Ed,{size:12,strokeWidth:1.75})," ",l("hlov.export")]})]})]})]})}),document.body)}const Yte={pdf:gi,img:UP,txt:gi,note:Hi,link:Ao};function $te({onLocate:e}){const t=xe(x=>x.materialsOverviewOpen),n=xe(x=>x.setMaterialsOverviewOpen),a=oe(x=>x.nodes),r=Ft(),[s,l]=j.useState("time"),c=j.useMemo(()=>{const x=[];for(const y of a){const k=y.data.stepKind;if(k==="note"||k==="link"){const w=k==="link"?y.data.linkTitle||y.data.linkUrl||"—":y.data.question.split(`
501
- `)[0].replace(/^#+\s*/,"").slice(0,60)||"—";x.push({key:y.id,name:w,icon:k,at:y.data.createdAt,nodeId:y.id,nodeTitle:w,canOpen:!0});continue}const T=y.data.question.replace(/\s+/g," ").trim().slice(0,60)||(k==="file"?r("glyph.file"):"—");for(const w of y.data.attachments||[]){const _=w.type==="application/pdf"?"pdf":w.type.startsWith("image/")?"img":"txt";x.push({key:w.id,name:w.name,icon:_,sizeKB:w.size/1024,at:w.addedAt,nodeId:y.id,nodeTitle:T,canOpen:_==="pdf"})}}const b=s==="time"?[...x].sort((y,k)=>(k.at??"").localeCompare(y.at??"")):x;return b.map((y,k)=>({...y,showGroup:s==="node"&&(k===0||b[k-1].nodeTitle!==y.nodeTitle)}))},[a,s,r]);if(!t)return null;const d=()=>n(!1),h=x=>{d(),xe.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)=>u.jsx("button",{onClick:()=>l(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 $a.createPortal(u.jsx("div",{className:"fixed inset-0 z-[60] bg-ink/30 backdrop-blur-sm flex items-center justify-center p-6",onClick:d,children:u.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:[u.jsxs("div",{className:"flex items-center gap-2 px-5 py-3 border-b border-line shrink-0",children:[u.jsx(xi,{size:15,strokeWidth:1.75,className:"text-warm"}),u.jsx("span",{className:"text-sm font-semibold text-ink",children:r("matov.title")}),u.jsx("span",{className:"text-2xs text-ink-faint",children:Ue(r("matov.count"),{n:c.length})}),u.jsx("div",{className:"flex-1"}),p("time",r("hlov.byTime")),p("node",r("hlov.byNode")),u.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:u.jsx(bn,{size:15,strokeWidth:1.75})})]}),u.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-5 py-3",children:[c.length===0&&u.jsx("p",{className:"text-xs text-ink-faint italic py-2",children:r("matov.empty")}),c.map(x=>{const b=Yte[x.icon];return u.jsxs("div",{children:[x.showGroup&&u.jsx("div",{className:"text-2xs text-ink-faint font-medium mt-3 mb-1 first:mt-0 truncate",children:x.nodeTitle}),u.jsxs("div",{className:"group flex items-center gap-2.5 py-1.5 border-b border-line/50 last:border-0",children:[u.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:u.jsx(b,{size:14,strokeWidth:1.75})}),u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsx("p",{className:"text-sm text-ink truncate",children:x.name}),u.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"&&u.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"&&u.jsx("button",{className:m,onClick:()=>{d(),e(x.nodeId)},title:r("hlov.locateTitle"),children:"↦"}),x.canOpen&&u.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:u.jsx(So,{size:14,strokeWidth:1.75})})]})]},x.key)})]})]})}),document.body)}function Kte(e){const t=e.data.stepKind;return t==="note"||t==="file"||t==="link"||t==="frame"?t:e.data.condensedFrom?.length?"distill":"qa"}function Xte(e,t){let n=0,a=e.indexOf(t);for(;a!==-1;)n+=1,a=e.indexOf(t,a+t.length);return n}function Qte(e,t,n){const r=Math.max(0,t-40),s=Math.min(e.length,t+n+60),l=r>0?"…":"",c=s<e.length?"…":"";return{snippet:l+e.slice(r,s)+c,matchStart:l.length+(t-r)}}function Zte(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 l=[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 c=0,d=null;for(const p of l){if(!p)continue;const x=p.toLowerCase(),b=x.indexOf(n);b!==-1&&(c+=Xte(x,n),d||(d={text:p,at:b}))}if(!d)continue;const{snippet:h,matchStart:m}=Qte(d.text,d.at,n.length);a.push({nodeId:r.id,kind:Kte(r),archived:!!s.archived,count:c,snippet:h,matchStart:m,matchLen:n.length})}return a.sort((r,s)=>Number(r.archived)-Number(s.archived)||s.count-r.count),a}const Jte={qa:o7,note:Hi,file:gi,link:Ao,frame:Ex,distill:cm},K1=50;function ene({open:e,onClose:t,onLocate:n}){const a=Ft(),r=oe(w=>w.nodes),s=xe(w=>w.setSearchHitIds),[l,c]=j.useState(""),[d,h]=j.useState(0),m=j.useRef(null),[p,x]=j.useState(e);p!==e&&(x(e),e&&(c(""),h(0))),j.useEffect(()=>{e&&setTimeout(()=>m.current?.focus(),50)},[e]);const[b,y]=j.useState("");j.useEffect(()=>{const w=setTimeout(()=>y(l),120);return()=>clearTimeout(w)},[l]);const k=j.useMemo(()=>e?Zte(r,b):[],[e,r,b]);if(j.useEffect(()=>{if(!e||!b.trim()){s(null);return}s(new Set(k.map(w=>w.nodeId)))},[e,b,k,s]),j.useEffect(()=>()=>s(null),[s]),!e)return null;const T=w=>{n(w.nodeId);const _=b.trim().toLowerCase();setTimeout(()=>{const A=document.querySelector("[data-focus-panel]");if(!A||!_)return;const C=document.createTreeWalker(A,NodeFilter.SHOW_TEXT);let O;for(;O=C.nextNode();)if(O.textContent?.toLowerCase().includes(_)){const D=O.parentElement;D?.scrollIntoView({block:"center",behavior:"smooth"}),D?.animate([{backgroundColor:"rgba(107, 92, 231, 0.22)"},{backgroundColor:"transparent"}],{duration:1800,easing:"ease-out"});break}},500)};return u.jsx("div",{className:"absolute top-4 left-1/2 -translate-x-1/2 z-20 w-[460px]","data-canvas-search":!0,children:u.jsxs("div",{className:"bg-card border border-line rounded-xl shadow-xl overflow-hidden",children:[u.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:[u.jsx(Cf,{size:15,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),u.jsx("input",{ref:m,type:"text",value:l,onChange:w=>{c(w.target.value),h(0)},onKeyDown:w=>{w.key==="Escape"&&(w.stopPropagation(),t()),w.key==="ArrowDown"&&(w.preventDefault(),h(_=>Math.min(_+1,k.length-1))),w.key==="ArrowUp"&&(w.preventDefault(),h(_=>Math.max(_-1,0))),w.key==="Enter"&&!Ya(w)&&k[d]&&(w.preventDefault(),T(k[d]))},placeholder:a("search.placeholder"),className:"flex-1 bg-transparent text-sm text-ink placeholder-ink-faint focus:outline-none","data-search-input":!0}),l&&u.jsx("span",{className:"text-2xs text-ink-faint shrink-0",children:Ue(a("search.count"),{n:k.length})}),u.jsx("button",{onClick:t,className:"text-ink-faint hover:text-ink transition-colors shrink-0",children:u.jsx(bn,{size:14,strokeWidth:1.75})})]}),k.length>0&&u.jsxs("ul",{className:"border-t border-line/60 max-h-72 overflow-y-auto py-1",children:[k.slice(0,K1).map((w,_)=>{const A=Jte[w.kind],O=r.find(D=>D.id===w.nodeId)?.data.question||"—";return u.jsx("li",{children:u.jsxs("button",{onClick:()=>T(w),onMouseEnter:()=>h(_),className:`w-full text-left px-4 py-2 transition-colors ${_===d?"bg-accent/8":""} ${w.archived?"opacity-55":""}`,"data-search-hit-row":!0,children:[u.jsxs("p",{className:`text-xs font-medium truncate flex items-center gap-1.5 ${_===d?"text-accent":"text-ink"}`,children:[u.jsx(A,{size:12,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),u.jsx("span",{className:"truncate flex-1 min-w-0",children:O}),w.archived&&u.jsx(Io,{size:11,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),w.count>1&&u.jsxs("span",{className:"text-2xs text-ink-faint font-normal shrink-0",children:["×",w.count]})]}),u.jsxs("p",{className:"text-2xs text-ink-faint mt-0.5 break-all leading-relaxed",children:[w.snippet.slice(0,w.matchStart),u.jsx("mark",{className:"bg-accent/20 text-accent rounded-sm px-px",children:w.snippet.slice(w.matchStart,w.matchStart+w.matchLen)}),w.snippet.slice(w.matchStart+w.matchLen)]})]})},w.nodeId)}),k.length>K1&&u.jsx("li",{className:"px-4 py-2 text-2xs text-ink-faint",children:Ue(a("search.more"),{n:k.length-K1})})]})]})})}const Pk=new Set(["note","file","link"]),Ai=e=>{const t=(e?.data.question??"").replace(/\s+/g," ").trim();return t.length>24?`${t.slice(0,24)}…`:t||"(空)"};function X1(e,t,n){const a=new Set([e]),r=[e];for(;r.length;){const s=r.shift();for(const l of n.get(s)??[]){if(l===t)return!0;a.has(l)||(a.add(l),r.push(l))}}return!1}function Q1(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 zk(e,t){const n=[],a=new Map(e.map(N=>[N.id,N])),r=t.filter(N=>!N.data?.isCrossLink),s=t.filter(N=>N.data?.isCrossLink),l=Q1(r),c=Q1(t);for(const N of r){const R=Q1(r.filter(B=>B.id!==N.id));X1(N.source,N.target,R)&&n.push({tier:1,kind:"residual-edge",fixable:!0,params:{a:Ai(a.get(N.source)),b:Ai(a.get(N.target))},nodeIds:[N.target,N.source],edgeIds:[N.id]})}for(const N of s)X1(N.source,N.target,l)&&n.push({tier:1,kind:"shadow-reference",fixable:!0,params:{a:Ai(a.get(N.source)),b:Ai(a.get(N.target))},nodeIds:[N.target,N.source],edgeIds:[N.id]});const d=new Map;for(const N of r)d.has(N.source)||d.set(N.source,[]),d.get(N.source).push(N.target);const h=[];for(const N of d.values()){const R=N.filter(U=>a.get(U)?.data.stepKind==="prompt"),B=N.filter(U=>a.get(U)?.data.isBranch);R.length>=2&&h.push(R),B.length>=2&&h.push(B)}for(const N of h)for(const R of N)for(const B of N)if(R!==B&&X1(R,B,c)){const U=t.find(Y=>Y.source===R&&Y.target===B);n.push({tier:1,kind:"blind-pool-breach",fixable:!!U,params:{a:Ai(a.get(B)),b:Ai(a.get(R))},nodeIds:[B,R],edgeIds:U?[U.id]:[]})}for(const N of h){const R=N.map(U=>new Set(t.filter(Y=>Y.target===U).map(Y=>Y.source))),B=new Set([...R[0]].filter(U=>R.every(Y=>Y.has(U))));N.forEach((U,Y)=>{const Z=[...R[Y]].filter(W=>!B.has(W)&&!N.includes(W));Z.length>0&&n.push({tier:1,kind:"pool-asymmetry",fixable:!1,params:{a:Ai(a.get(U)),n:Z.length},nodeIds:[U,...Z],edgeIds:[]})})}const m=e.filter(N=>!Pk.has(N.data.stepKind??"")&&N.data.stepKind!=="frame"),p=new Map,x=new Map,b=N=>$n(N.data.question+N.data.response),y=new Map;for(const N of m)y.set(N.id,0);for(const N of r)y.has(N.target)&&y.has(N.source)&&y.set(N.target,(y.get(N.target)??0)+1);const k=m.filter(N=>(y.get(N.id)??0)===0).map(N=>N.id),T=[],w=new Map(y);for(;k.length;){const N=k.shift();T.push(N);for(const R of l.get(N)??[])w.has(R)&&(w.set(R,w.get(R)-1),w.get(R)===0&&k.push(R))}for(const N of T){const R=a.get(N),B=r.filter(Z=>Z.target===N&&p.has(Z.source)),U=B.length?Math.max(...B.map(Z=>p.get(Z.source)))+1:1,Y=B.length?Math.max(...B.map(Z=>x.get(Z.source)))+b(R):b(R);p.set(N,U),x.set(N,Y)}const _=m.filter(N=>!(l.get(N.id)??[]).length&&!N.data.archived),A=_.filter(N=>(p.get(N.id)??0)>=8||(x.get(N.id)??0)>=15e3).sort((N,R)=>(p.get(R.id)??0)-(p.get(N.id)??0)).slice(0,3);for(const N of A)n.push({tier:2,kind:"long-chain",fixable:!1,params:{a:Ai(N),d:p.get(N.id)??0,tok:x.get(N.id)??0},nodeIds:[N.id],edgeIds:[]});const C=_.filter(N=>N.data.response);C.length>=4&&n.push({tier:2,kind:"open-branches",fixable:!1,params:{n:C.length},nodeIds:C.map(N=>N.id),edgeIds:[]});for(const N of m){const R=r.filter(U=>U.target===N.id).length,B=(l.get(N.id)??[]).length;R>=2&&B>=1&&n.push({tier:2,kind:"collider-continuation",fixable:!1,params:{a:Ai(N),n:R},nodeIds:[N.id],edgeIds:[]})}const O=e.filter(N=>Pk.has(N.data.stepKind??"")&&!t.some(R=>R.source===N.id));O.length>0&&n.push({tier:2,kind:"orphan-materials",fixable:!1,params:{n:O.length},nodeIds:O.map(N=>N.id),edgeIds:[]});const D=N=>{const R=new Set,B=[N];for(;B.length;)for(const U of l.get(B.shift())??[])R.has(U)||(R.add(U),B.push(U));return R.size},M=m.map(N=>({n:N,c:D(N.id)})).filter(({c:N})=>N>=5).sort((N,R)=>R.c-N.c).slice(0,3);for(const{n:N,c:R}of M)n.push({tier:2,kind:"load-bearing",fixable:!1,params:{a:Ai(N),n:R},nodeIds:[N.id],edgeIds:[]});return n.sort((N,R)=>N.tier-R.tier)}const tne={"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 nne({onLocate:e,openPing:t=0,showTrigger:n=!0}){const a=oe(w=>w.deleteEdges),r=Ft(),[s,l]=j.useState(!1),[c,d]=j.useState([]),h=j.useRef(null),[m,p]=j.useState(t);j.useEffect(()=>{if(!s)return;const w=_=>{h.current?.contains(_.target)||l(!1)};return window.addEventListener("mousedown",w),()=>window.removeEventListener("mousedown",w)},[s]);const x=()=>{const{nodes:w,edges:_}=oe.getState();d(zk(w,_)),l(!0)};t!==m&&(p(t),x());const b=w=>{a(w.edgeIds);const{nodes:_,edges:A}=oe.getState();d(zk(_,A))},y=c.filter(w=>w.tier===1),k=c.filter(w=>w.tier===2),T=(w,_)=>u.jsxs("div",{className:"px-3 py-2 border-b border-line/50 last:border-0 flex items-start gap-2",children:[u.jsx("span",{className:`w-1.5 h-1.5 rounded-full mt-1.5 shrink-0 ${w.tier===1?"bg-red-400":"bg-amber-400"}`}),u.jsx("span",{className:"text-xs text-ink-muted leading-relaxed flex-1 min-w-0",children:Ue(r(tne[w.kind]),w.params)}),u.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[w.nodeIds.length>0&&u.jsx("button",{onClick:()=>e(w.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:u.jsx(Zu,{size:13,strokeWidth:1.75})}),w.fixable&&u.jsx("button",{onClick:()=>b(w),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:u.jsx(Fa,{size:13,strokeWidth:1.75})})]})]},`${w.kind}-${_}`);return u.jsxs("div",{ref:h,className:"relative",children:[n&&u.jsx("button",{onClick:()=>s?l(!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:u.jsx(u7,{size:15,strokeWidth:1.75})}),s&&u.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:[u.jsxs("div",{className:"px-3 py-1.5 text-2xs font-semibold text-ink-muted border-b border-line",children:[r("diag.title"),u.jsx("span",{className:"text-ink-faint font-normal ml-2",children:c.length===0?"":Ue(r("diag.summary"),{a:y.length,b:k.length})})]}),c.length===0&&u.jsx("p",{className:"px-3 py-3 text-xs text-ink-faint italic",children:r("diag.clean")}),y.length>0&&u.jsxs(u.Fragment,{children:[u.jsx("p",{className:"px-3 pt-2 pb-1 text-2xs font-semibold text-red-500",children:r("diag.tier1")}),y.map(T)]}),k.length>0&&u.jsxs(u.Fragment,{children:[u.jsx("p",{className:"px-3 pt-2 pb-1 text-2xs font-semibold text-amber-600",children:r("diag.tier2")}),k.map(T)]})]})]})}async function IN(e,t){const{default:n}=await Kt(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&&ane(r,t.baseUrl),r}function ane(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 l=s.getAttribute(r),c=l?n(l):null;c?s.setAttribute(r,c):s.removeAttribute(r)});e.querySelectorAll("img[srcset], source[srcset]").forEach(a=>a.removeAttribute("srcset"))}async function rne(){const[{default:e},t]=await Promise.all([Kt(()=>import("./turndown.browser.es-kLzRgxYD.js"),[]),Kt(()=>import("./turndown-plugin-gfm.cjs-DmDDHBxg.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 Bk(e){return(e.textContent??"").trim().length>0||!!e.querySelector("img,svg,canvas,video")}function z2(e){const t=Array.from(e.querySelectorAll(".reveal .slides > section"));if(t.length>=2){const s=[];for(const l of t){const c=Array.from(l.children).filter(d=>d.tagName==="SECTION");c.length>0?s.push(...c):s.push(l)}return s}const n=new Map;for(const s of Array.from(e.body?.querySelectorAll("[class]")??[])){const l=s.getAttribute("class")??"";if(!/(?:^|[\s_-])(?:slide|page)(?:[\s_-]|$)/i.test(l)||!Bk(s))continue;const c=s.parentElement;if(!c)continue;const d=n.get(c)??[];d.push(s),n.set(c,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(Bk);return r.length>=3?r:null}async function ine(e,t){const n=await IN(e,t),a=await rne(),r=z2(n);if(r)return{markdown:r.map((d,h)=>`<!-- tdag-page:${h+1} -->
501
+ `)[0].replace(/^#+\s*/,"").slice(0,60)||"—";x.push({key:y.id,name:w,icon:k,at:y.data.createdAt,nodeId:y.id,nodeTitle:w,canOpen:!0});continue}const T=y.data.question.replace(/\s+/g," ").trim().slice(0,60)||(k==="file"?r("glyph.file"):"—");for(const w of y.data.attachments||[]){const _=w.type==="application/pdf"?"pdf":w.type.startsWith("image/")?"img":"txt";x.push({key:w.id,name:w.name,icon:_,sizeKB:w.size/1024,at:w.addedAt,nodeId:y.id,nodeTitle:T,canOpen:_==="pdf"})}}const b=s==="time"?[...x].sort((y,k)=>(k.at??"").localeCompare(y.at??"")):x;return b.map((y,k)=>({...y,showGroup:s==="node"&&(k===0||b[k-1].nodeTitle!==y.nodeTitle)}))},[a,s,r]);if(!t)return null;const d=()=>n(!1),h=x=>{d(),xe.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)=>u.jsx("button",{onClick:()=>l(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 $a.createPortal(u.jsx("div",{className:"fixed inset-0 z-[60] bg-ink/30 backdrop-blur-sm flex items-center justify-center p-6",onClick:d,children:u.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:[u.jsxs("div",{className:"flex items-center gap-2 px-5 py-3 border-b border-line shrink-0",children:[u.jsx(xi,{size:15,strokeWidth:1.75,className:"text-warm"}),u.jsx("span",{className:"text-sm font-semibold text-ink",children:r("matov.title")}),u.jsx("span",{className:"text-2xs text-ink-faint",children:Ue(r("matov.count"),{n:c.length})}),u.jsx("div",{className:"flex-1"}),p("time",r("hlov.byTime")),p("node",r("hlov.byNode")),u.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:u.jsx(bn,{size:15,strokeWidth:1.75})})]}),u.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-5 py-3",children:[c.length===0&&u.jsx("p",{className:"text-xs text-ink-faint italic py-2",children:r("matov.empty")}),c.map(x=>{const b=Yte[x.icon];return u.jsxs("div",{children:[x.showGroup&&u.jsx("div",{className:"text-2xs text-ink-faint font-medium mt-3 mb-1 first:mt-0 truncate",children:x.nodeTitle}),u.jsxs("div",{className:"group flex items-center gap-2.5 py-1.5 border-b border-line/50 last:border-0",children:[u.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:u.jsx(b,{size:14,strokeWidth:1.75})}),u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsx("p",{className:"text-sm text-ink truncate",children:x.name}),u.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"&&u.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"&&u.jsx("button",{className:m,onClick:()=>{d(),e(x.nodeId)},title:r("hlov.locateTitle"),children:"↦"}),x.canOpen&&u.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:u.jsx(So,{size:14,strokeWidth:1.75})})]})]},x.key)})]})]})}),document.body)}function Kte(e){const t=e.data.stepKind;return t==="note"||t==="file"||t==="link"||t==="frame"?t:e.data.condensedFrom?.length?"distill":"qa"}function Xte(e,t){let n=0,a=e.indexOf(t);for(;a!==-1;)n+=1,a=e.indexOf(t,a+t.length);return n}function Qte(e,t,n){const r=Math.max(0,t-40),s=Math.min(e.length,t+n+60),l=r>0?"…":"",c=s<e.length?"…":"";return{snippet:l+e.slice(r,s)+c,matchStart:l.length+(t-r)}}function Zte(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 l=[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 c=0,d=null;for(const p of l){if(!p)continue;const x=p.toLowerCase(),b=x.indexOf(n);b!==-1&&(c+=Xte(x,n),d||(d={text:p,at:b}))}if(!d)continue;const{snippet:h,matchStart:m}=Qte(d.text,d.at,n.length);a.push({nodeId:r.id,kind:Kte(r),archived:!!s.archived,count:c,snippet:h,matchStart:m,matchLen:n.length})}return a.sort((r,s)=>Number(r.archived)-Number(s.archived)||s.count-r.count),a}const Jte={qa:o7,note:Hi,file:gi,link:Ao,frame:Ex,distill:cm},K1=50;function ene({open:e,onClose:t,onLocate:n}){const a=Ft(),r=oe(w=>w.nodes),s=xe(w=>w.setSearchHitIds),[l,c]=j.useState(""),[d,h]=j.useState(0),m=j.useRef(null),[p,x]=j.useState(e);p!==e&&(x(e),e&&(c(""),h(0))),j.useEffect(()=>{e&&setTimeout(()=>m.current?.focus(),50)},[e]);const[b,y]=j.useState("");j.useEffect(()=>{const w=setTimeout(()=>y(l),120);return()=>clearTimeout(w)},[l]);const k=j.useMemo(()=>e?Zte(r,b):[],[e,r,b]);if(j.useEffect(()=>{if(!e||!b.trim()){s(null);return}s(new Set(k.map(w=>w.nodeId)))},[e,b,k,s]),j.useEffect(()=>()=>s(null),[s]),!e)return null;const T=w=>{n(w.nodeId);const _=b.trim().toLowerCase();setTimeout(()=>{const A=document.querySelector("[data-focus-panel]");if(!A||!_)return;const C=document.createTreeWalker(A,NodeFilter.SHOW_TEXT);let O;for(;O=C.nextNode();)if(O.textContent?.toLowerCase().includes(_)){const D=O.parentElement;D?.scrollIntoView({block:"center",behavior:"smooth"}),D?.animate([{backgroundColor:"rgba(107, 92, 231, 0.22)"},{backgroundColor:"transparent"}],{duration:1800,easing:"ease-out"});break}},500)};return u.jsx("div",{className:"absolute top-4 left-1/2 -translate-x-1/2 z-20 w-[460px]","data-canvas-search":!0,children:u.jsxs("div",{className:"bg-card border border-line rounded-xl shadow-xl overflow-hidden",children:[u.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:[u.jsx(Cf,{size:15,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),u.jsx("input",{ref:m,type:"text",value:l,onChange:w=>{c(w.target.value),h(0)},onKeyDown:w=>{w.key==="Escape"&&(w.stopPropagation(),t()),w.key==="ArrowDown"&&(w.preventDefault(),h(_=>Math.min(_+1,k.length-1))),w.key==="ArrowUp"&&(w.preventDefault(),h(_=>Math.max(_-1,0))),w.key==="Enter"&&!Ya(w)&&k[d]&&(w.preventDefault(),T(k[d]))},placeholder:a("search.placeholder"),className:"flex-1 bg-transparent text-sm text-ink placeholder-ink-faint focus:outline-none","data-search-input":!0}),l&&u.jsx("span",{className:"text-2xs text-ink-faint shrink-0",children:Ue(a("search.count"),{n:k.length})}),u.jsx("button",{onClick:t,className:"text-ink-faint hover:text-ink transition-colors shrink-0",children:u.jsx(bn,{size:14,strokeWidth:1.75})})]}),k.length>0&&u.jsxs("ul",{className:"border-t border-line/60 max-h-72 overflow-y-auto py-1",children:[k.slice(0,K1).map((w,_)=>{const A=Jte[w.kind],O=r.find(D=>D.id===w.nodeId)?.data.question||"—";return u.jsx("li",{children:u.jsxs("button",{onClick:()=>T(w),onMouseEnter:()=>h(_),className:`w-full text-left px-4 py-2 transition-colors ${_===d?"bg-accent/8":""} ${w.archived?"opacity-55":""}`,"data-search-hit-row":!0,children:[u.jsxs("p",{className:`text-xs font-medium truncate flex items-center gap-1.5 ${_===d?"text-accent":"text-ink"}`,children:[u.jsx(A,{size:12,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),u.jsx("span",{className:"truncate flex-1 min-w-0",children:O}),w.archived&&u.jsx(Io,{size:11,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),w.count>1&&u.jsxs("span",{className:"text-2xs text-ink-faint font-normal shrink-0",children:["×",w.count]})]}),u.jsxs("p",{className:"text-2xs text-ink-faint mt-0.5 break-all leading-relaxed",children:[w.snippet.slice(0,w.matchStart),u.jsx("mark",{className:"bg-accent/20 text-accent rounded-sm px-px",children:w.snippet.slice(w.matchStart,w.matchStart+w.matchLen)}),w.snippet.slice(w.matchStart+w.matchLen)]})]})},w.nodeId)}),k.length>K1&&u.jsx("li",{className:"px-4 py-2 text-2xs text-ink-faint",children:Ue(a("search.more"),{n:k.length-K1})})]})]})})}const Pk=new Set(["note","file","link"]),Ai=e=>{const t=(e?.data.question??"").replace(/\s+/g," ").trim();return t.length>24?`${t.slice(0,24)}…`:t||"(空)"};function X1(e,t,n){const a=new Set([e]),r=[e];for(;r.length;){const s=r.shift();for(const l of n.get(s)??[]){if(l===t)return!0;a.has(l)||(a.add(l),r.push(l))}}return!1}function Q1(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 zk(e,t){const n=[],a=new Map(e.map(N=>[N.id,N])),r=t.filter(N=>!N.data?.isCrossLink),s=t.filter(N=>N.data?.isCrossLink),l=Q1(r),c=Q1(t);for(const N of r){const R=Q1(r.filter(B=>B.id!==N.id));X1(N.source,N.target,R)&&n.push({tier:1,kind:"residual-edge",fixable:!0,params:{a:Ai(a.get(N.source)),b:Ai(a.get(N.target))},nodeIds:[N.target,N.source],edgeIds:[N.id]})}for(const N of s)X1(N.source,N.target,l)&&n.push({tier:1,kind:"shadow-reference",fixable:!0,params:{a:Ai(a.get(N.source)),b:Ai(a.get(N.target))},nodeIds:[N.target,N.source],edgeIds:[N.id]});const d=new Map;for(const N of r)d.has(N.source)||d.set(N.source,[]),d.get(N.source).push(N.target);const h=[];for(const N of d.values()){const R=N.filter(U=>a.get(U)?.data.stepKind==="prompt"),B=N.filter(U=>a.get(U)?.data.isBranch);R.length>=2&&h.push(R),B.length>=2&&h.push(B)}for(const N of h)for(const R of N)for(const B of N)if(R!==B&&X1(R,B,c)){const U=t.find(Y=>Y.source===R&&Y.target===B);n.push({tier:1,kind:"blind-pool-breach",fixable:!!U,params:{a:Ai(a.get(B)),b:Ai(a.get(R))},nodeIds:[B,R],edgeIds:U?[U.id]:[]})}for(const N of h){const R=N.map(U=>new Set(t.filter(Y=>Y.target===U).map(Y=>Y.source))),B=new Set([...R[0]].filter(U=>R.every(Y=>Y.has(U))));N.forEach((U,Y)=>{const Z=[...R[Y]].filter(W=>!B.has(W)&&!N.includes(W));Z.length>0&&n.push({tier:1,kind:"pool-asymmetry",fixable:!1,params:{a:Ai(a.get(U)),n:Z.length},nodeIds:[U,...Z],edgeIds:[]})})}const m=e.filter(N=>!Pk.has(N.data.stepKind??"")&&N.data.stepKind!=="frame"),p=new Map,x=new Map,b=N=>$n(N.data.question+N.data.response),y=new Map;for(const N of m)y.set(N.id,0);for(const N of r)y.has(N.target)&&y.has(N.source)&&y.set(N.target,(y.get(N.target)??0)+1);const k=m.filter(N=>(y.get(N.id)??0)===0).map(N=>N.id),T=[],w=new Map(y);for(;k.length;){const N=k.shift();T.push(N);for(const R of l.get(N)??[])w.has(R)&&(w.set(R,w.get(R)-1),w.get(R)===0&&k.push(R))}for(const N of T){const R=a.get(N),B=r.filter(Z=>Z.target===N&&p.has(Z.source)),U=B.length?Math.max(...B.map(Z=>p.get(Z.source)))+1:1,Y=B.length?Math.max(...B.map(Z=>x.get(Z.source)))+b(R):b(R);p.set(N,U),x.set(N,Y)}const _=m.filter(N=>!(l.get(N.id)??[]).length&&!N.data.archived),A=_.filter(N=>(p.get(N.id)??0)>=8||(x.get(N.id)??0)>=15e3).sort((N,R)=>(p.get(R.id)??0)-(p.get(N.id)??0)).slice(0,3);for(const N of A)n.push({tier:2,kind:"long-chain",fixable:!1,params:{a:Ai(N),d:p.get(N.id)??0,tok:x.get(N.id)??0},nodeIds:[N.id],edgeIds:[]});const C=_.filter(N=>N.data.response);C.length>=4&&n.push({tier:2,kind:"open-branches",fixable:!1,params:{n:C.length},nodeIds:C.map(N=>N.id),edgeIds:[]});for(const N of m){const R=r.filter(U=>U.target===N.id).length,B=(l.get(N.id)??[]).length;R>=2&&B>=1&&n.push({tier:2,kind:"collider-continuation",fixable:!1,params:{a:Ai(N),n:R},nodeIds:[N.id],edgeIds:[]})}const O=e.filter(N=>Pk.has(N.data.stepKind??"")&&!t.some(R=>R.source===N.id));O.length>0&&n.push({tier:2,kind:"orphan-materials",fixable:!1,params:{n:O.length},nodeIds:O.map(N=>N.id),edgeIds:[]});const D=N=>{const R=new Set,B=[N];for(;B.length;)for(const U of l.get(B.shift())??[])R.has(U)||(R.add(U),B.push(U));return R.size},M=m.map(N=>({n:N,c:D(N.id)})).filter(({c:N})=>N>=5).sort((N,R)=>R.c-N.c).slice(0,3);for(const{n:N,c:R}of M)n.push({tier:2,kind:"load-bearing",fixable:!1,params:{a:Ai(N),n:R},nodeIds:[N.id],edgeIds:[]});return n.sort((N,R)=>N.tier-R.tier)}const tne={"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 nne({onLocate:e,openPing:t=0,showTrigger:n=!0}){const a=oe(w=>w.deleteEdges),r=Ft(),[s,l]=j.useState(!1),[c,d]=j.useState([]),h=j.useRef(null),[m,p]=j.useState(t);j.useEffect(()=>{if(!s)return;const w=_=>{h.current?.contains(_.target)||l(!1)};return window.addEventListener("mousedown",w),()=>window.removeEventListener("mousedown",w)},[s]);const x=()=>{const{nodes:w,edges:_}=oe.getState();d(zk(w,_)),l(!0)};t!==m&&(p(t),x());const b=w=>{a(w.edgeIds);const{nodes:_,edges:A}=oe.getState();d(zk(_,A))},y=c.filter(w=>w.tier===1),k=c.filter(w=>w.tier===2),T=(w,_)=>u.jsxs("div",{className:"px-3 py-2 border-b border-line/50 last:border-0 flex items-start gap-2",children:[u.jsx("span",{className:`w-1.5 h-1.5 rounded-full mt-1.5 shrink-0 ${w.tier===1?"bg-red-400":"bg-amber-400"}`}),u.jsx("span",{className:"text-xs text-ink-muted leading-relaxed flex-1 min-w-0",children:Ue(r(tne[w.kind]),w.params)}),u.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[w.nodeIds.length>0&&u.jsx("button",{onClick:()=>e(w.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:u.jsx(Zu,{size:13,strokeWidth:1.75})}),w.fixable&&u.jsx("button",{onClick:()=>b(w),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:u.jsx(Fa,{size:13,strokeWidth:1.75})})]})]},`${w.kind}-${_}`);return u.jsxs("div",{ref:h,className:"relative",children:[n&&u.jsx("button",{onClick:()=>s?l(!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:u.jsx(u7,{size:15,strokeWidth:1.75})}),s&&u.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:[u.jsxs("div",{className:"px-3 py-1.5 text-2xs font-semibold text-ink-muted border-b border-line",children:[r("diag.title"),u.jsx("span",{className:"text-ink-faint font-normal ml-2",children:c.length===0?"":Ue(r("diag.summary"),{a:y.length,b:k.length})})]}),c.length===0&&u.jsx("p",{className:"px-3 py-3 text-xs text-ink-faint italic",children:r("diag.clean")}),y.length>0&&u.jsxs(u.Fragment,{children:[u.jsx("p",{className:"px-3 pt-2 pb-1 text-2xs font-semibold text-red-500",children:r("diag.tier1")}),y.map(T)]}),k.length>0&&u.jsxs(u.Fragment,{children:[u.jsx("p",{className:"px-3 pt-2 pb-1 text-2xs font-semibold text-amber-600",children:r("diag.tier2")}),k.map(T)]})]})]})}async function IN(e,t){const{default:n}=await Kt(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&&ane(r,t.baseUrl),r}function ane(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 l=s.getAttribute(r),c=l?n(l):null;c?s.setAttribute(r,c):s.removeAttribute(r)});e.querySelectorAll("img[srcset], source[srcset]").forEach(a=>a.removeAttribute("srcset"))}async function rne(){const[{default:e},t]=await Promise.all([Kt(()=>import("./turndown.browser.es-kLzRgxYD.js"),[]),Kt(()=>import("./turndown-plugin-gfm.cjs-DXKuEPQs.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 Bk(e){return(e.textContent??"").trim().length>0||!!e.querySelector("img,svg,canvas,video")}function z2(e){const t=Array.from(e.querySelectorAll(".reveal .slides > section"));if(t.length>=2){const s=[];for(const l of t){const c=Array.from(l.children).filter(d=>d.tagName==="SECTION");c.length>0?s.push(...c):s.push(l)}return s}const n=new Map;for(const s of Array.from(e.body?.querySelectorAll("[class]")??[])){const l=s.getAttribute("class")??"";if(!/(?:^|[\s_-])(?:slide|page)(?:[\s_-]|$)/i.test(l)||!Bk(s))continue;const c=s.parentElement;if(!c)continue;const d=n.get(c)??[];d.push(s),n.set(c,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(Bk);return r.length>=3?r:null}async function ine(e,t){const n=await IN(e,t),a=await rne(),r=z2(n);if(r)return{markdown:r.map((d,h)=>`<!-- tdag-page:${h+1} -->
502
502
 
503
503
  ${a.turndown(d.cloneNode(!0).outerHTML).trim()}`).join(`
504
504
 
505
- `).trim(),numPages:r.length,title:n.title||void 0};let s=n.title||void 0,l=null;try{const{default:c}=await Kt(async()=>{const{default:h}=await import("./index-DalA8OYo.js").then(m=>m.i);return{default:h}},[]),d=new c(n.cloneNode(!0)).parse();d?.content&&d.content.replace(/<[^>]+>/g," ").trim().length>40&&(l=d.content,d.title&&(s=d.title))}catch{}if(l==null&&n.body){const c=n.body.cloneNode(!0);c.querySelectorAll("script,style,noscript,nav,header,footer,aside").forEach(d=>d.remove()),l=c.innerHTML}return{markdown:l?a.turndown(l).trim():"",title:s}}const sne=[":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(`
505
+ `).trim(),numPages:r.length,title:n.title||void 0};let s=n.title||void 0,l=null;try{const{default:c}=await Kt(async()=>{const{default:h}=await import("./index-D_9Fas4A.js").then(m=>m.i);return{default:h}},[]),d=new c(n.cloneNode(!0)).parse();d?.content&&d.content.replace(/<[^>]+>/g," ").trim().length>40&&(l=d.content,d.title&&(s=d.title))}catch{}if(l==null&&n.body){const c=n.body.cloneNode(!0);c.querySelectorAll("script,style,noscript,nav,header,footer,aside").forEach(d=>d.remove()),l=c.innerHTML}return{markdown:l?a.turndown(l).trim():"",title:s}}const sne=[":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(`
506
506
  `);function sb(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;")}function one(e,t){const n=e.tagName.toLowerCase(),a=["class","id","style"].map(r=>{const s=e.getAttribute(r);return s?` ${r}="${sb(s)}"`:""}).join("");return`<${n}${a} data-tdag-shell>${t}</${n}>`}function Hk(e,t,n,a){const r=n?` class="${sb(n)}"`:"",s=a?` style="${sb(a)}"`:"";return`<!doctype html><html><head><meta charset="utf-8">${e}<style>${sne}</style></head><body${r}${s}>${t}</body></html>`}async function DN(e,t){const n=await IN(e,t),a=Array.from(n.querySelectorAll('style, link[rel="stylesheet" i]')).map(c=>c.outerHTML).join(`
507
507
  `),r=n.body?.getAttribute("class"),s=n.body?.getAttribute("style"),l=z2(n);return l?l.map((c,d)=>{const h=c.cloneNode(!0);h.setAttribute("data-tdag-slide","");let m=h.outerHTML;for(let p=c.parentElement;p&&p!==n.body&&p.tagName!=="HTML";p=p.parentElement)m=one(p,m);return{page:d+1,srcdoc:Hk(a,m,r,s)}}):[{page:null,srcdoc:Hk(a,n.body?.innerHTML??"",r,s)}]}const ON=Object.freeze(Object.defineProperty({__proto__:null,buildReaderPages:DN,detectSlides:z2,extractHtmlMaterial:ine},Symbol.toStringTag,{value:"Module"}));function Uk({att:e,onSelect:t,clipMode:n,onClipped:a,baseUrl:r}){const s=Ft(),[l,c]=j.useState(null),[d,h]=j.useState(!1);return j.useEffect(()=>{let m=!1;return DN(e.content,r?{baseUrl:r}:void 0).then(p=>{m||c(p)}).catch(()=>{m||h(!0)}),()=>{m=!0}},[]),d?u.jsx("p",{className:"text-sm text-ink-faint italic py-10 text-center",children:s("reader.htmlNoText")}):l?u.jsx("div",{className:"flex flex-col items-center py-6 px-4",children:l.map(m=>u.jsxs("div",{"data-page":m.page??void 0,className:"w-full max-w-[860px]",children:[m.page!=null&&u.jsxs("div",{className:"text-2xs text-ink-faint font-mono text-center select-none pt-4 pb-2",children:["— p.",m.page," —"]}),u.jsx(lne,{srcdoc:m.srcdoc,page:m.page,onSelect:t,clipMode:n,onClipped:a,clipFailedText:s("reader.clipFailed")})]},m.page??0))}):u.jsxs("div",{className:"flex items-center justify-center gap-2 h-full min-h-[200px] text-sm text-ink-muted",children:[u.jsx(Xn,{size:16,strokeWidth:1.75,className:"animate-spin text-accent"})," ",s("reader.loading")]})}function lne({srcdoc:e,page:t,onSelect:n,clipMode:a,onClipped:r,clipFailedText:s}){const l=j.useRef(null),c=j.useRef(null),[d,h]=j.useState(120),[m,p]=j.useState(null),[x,b]=j.useState(!1),y=()=>{const w=c.current,_=w?.contentDocument;if(!w||!_?.body)return;const A=_.body.scrollWidth||_.documentElement.scrollWidth,C=w.clientWidth;A>C+2&&(_.body.style.zoom=String(C/A)),h(Math.max(40,_.documentElement.scrollHeight+2)),_.addEventListener("mouseup",()=>{const O=w.contentWindow?.getSelection();if(!O||O.isCollapsed){n(null);return}const D=O.toString().replace(/\s+/g," ").trim();if(D.length<2)return;const M=O.getRangeAt(0).getBoundingClientRect(),N=w.getBoundingClientRect();n({text:D,page:t,x:N.left+M.left+M.width/2,y:N.top+M.bottom})})},k=w=>{const _=l.current.getBoundingClientRect();return{x:Math.min(1,Math.max(0,(w.clientX-_.left)/_.width)),y:Math.min(1,Math.max(0,(w.clientY-_.top)/_.height))}},T=()=>{if(!m||x){p(null);return}const w=Math.min(m.x0,m.x1),_=Math.min(m.y0,m.y1),A=Math.abs(m.x1-m.x0),C=Math.abs(m.y1-m.y0);if(p(null),A<.02||C<.01)return;const O=c.current?.contentDocument;!O?.documentElement||!r||(b(!0),(async()=>{const{toCanvas:D}=await Kt(async()=>{const{toCanvas:K}=await import("./index-BeoRn2gJ.js");return{toCanvas:K}},[]),M=await D(O.documentElement,{pixelRatio:2}),N=Math.floor(w*M.width),R=Math.floor(_*M.height),B=Math.max(1,Math.floor(A*M.width)),U=Math.max(1,Math.floor(C*M.height)),Y=document.createElement("canvas");Y.width=B,Y.height=U,Y.getContext("2d").drawImage(M,N,R,B,U,0,0,B,U);const Z=l.current.getBoundingClientRect(),W={left:Z.left+w*Z.width,top:Z.top+_*Z.height,width:A*Z.width,height:C*Z.height};r(t??1,[w,_,A,C],Y.toDataURL("image/png"),W)})().catch(()=>Ke("error",s)).finally(()=>b(!1)))};return u.jsxs("div",{ref:l,className:"relative",children:[u.jsx("iframe",{ref:c,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&&u.jsxs("div",{className:"absolute inset-0 cursor-crosshair",style:{zIndex:6},"data-clip-overlay":t??1,onMouseDown:w=>{w.preventDefault();const _=k(w);p({x0:_.x,y0:_.y,x1:_.x,y1:_.y})},onMouseMove:w=>{if(m){const _=k(w);p({...m,x1:_.x,y1:_.y})}},onMouseUp:T,onMouseLeave:()=>{m&&T()},children:[x&&u.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:u.jsx(Xn,{size:11,strokeWidth:1.75,className:"animate-spin"})}),m&&u.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 Z1=null;function cne(){return Z1||(Z1=Promise.all([Kt(()=>import("./pdf-gh-BrLFn.js"),[]),Kt(()=>import("./pdf.worker.min-C_APr3k7.js"),[])]).then(([e,t])=>(e.GlobalWorkerOptions.workerSrc=t.default,e))),Z1}function une(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 dne=/<!--\s*tdag-page:(\d+)\s*-->/;function hne(e){const t=e.split(dne),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 J1=60,Fk=new Map;function fne({onLocate:e}){const t=xe(a=>a.readerNodeId),n=oe(a=>t?a.nodes.find(r=>r.id===t):void 0);return j.useEffect(()=>{t&&!n&&xe.getState().setReaderNodeId(null)},[t,n]),n?u.jsx(mne,{node:n,onLocate:e},n.id):null}function mne({node:e,onLocate:t}){const n=Ft(),a=e.data,r=a.stepKind==="file"||!a.stepKind&&(a.attachments??[]).some(me=>me.type==="application/pdf")?"file":a.stepKind==="link"?"link":"note",s=j.useMemo(()=>a.attachments??[],[a.attachments]),l=s.find(me=>me.type==="application/pdf"),c=s.find(me=>me.type==="text/html"),d=r==="link"?a.linkSnapshotHtml:void 0,h=j.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=j.useMemo(()=>s.filter(me=>me.type.startsWith("image/")),[s]),p=()=>xe.getState().setReaderNodeId(null),x=j.useMemo(()=>{if(l)return l.extractedText??"";if(r==="file"){const me=s.filter(At=>!At.type.startsWith("image/")&&At.type!=="application/pdf"),Qe=me.map(At=>{const Nt=At.type==="text/html"?At.extractedText??"":At.content;return me.length>1?`### ${At.name}
508
508
 
@@ -519,7 +519,7 @@ ${At.extractedText}`:At.extractedText);return Qe.join(`
519
519
  `))if(t.includes('"user"'))try{const n=JSON.parse(t);let a=null;if(n.type==="user"&&typeof n.message?.content=="string"?a=n.message.content:n.type==="response_item"&&n.payload?.type==="message"&&n.payload.role==="user"&&(a=(n.payload.content??[]).find(r=>r.type==="input_text"&&r.text)?.text??null),a&&a.trim()&&!a.startsWith("<")&&!a.startsWith("# AGENTS.md instructions for "))return a.trim().split(`
520
520
  `)[0].slice(0,80)}catch{}return null}function yne(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(`
521
521
  `).trim();if(a&&!a.startsWith("<"))return a.split(`
522
- `)[0].slice(0,80)}return null}const RN="thoughtdag.atlas.disabledRoots",B2=()=>{try{return new Set(JSON.parse(localStorage.getItem(RN)??"[]"))}catch{return new Set}};function vne(e,t){const n=B2();t?n.add(e):n.delete(e),localStorage.setItem(RN,JSON.stringify([...n]))}const $f=new Set;async function wne(){const e=window.desktopSessions;if(!e)return[];const t=B2(),n=(await e.roots().catch(()=>[])).filter(r=>r.exists&&!t.has(r.key)).map(r=>r.key),a=[];for(const r of n){const l=[...await e.list(r).catch(()=>[])].sort((d,h)=>h.mtime-d.mtime),c=12;for(let d=0;d<l.length;d+=c){const h=await Promise.all(l.slice(d,d+c).map(async m=>{const p=m.rel.endsWith(".zstd")?qk:bne,x=await e.head(r,m.rel,p).catch(()=>"");if(!x)return null;const b=Wk(r,m.rel,x,m.mtime,m.size);if(b)return b;const y=await e.head(r,m.rel,qk).catch(()=>"");return y.length>x.length?Wk(r,m.rel,y,m.mtime,m.size):null}));for(const m of h)m&&a.push(m)}}$f.clear();for(const r of a)$f.add(r.sessionId);return a.sort((r,s)=>s.mtime-r.mtime)}function kne(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)}const LN="thoughtdag.atlas.watermark",yo=e=>`${e.rootKey}:${e.rel}`;function H2(){try{return JSON.parse(localStorage.getItem(LN)??"{}")}catch{return{}}}function Kf(e){localStorage.setItem(LN,JSON.stringify(e))}function Ene(e){const t=H2(),n=new Map;if(Object.keys(t).length===0)return Kf(Object.fromEntries(e.map(s=>[yo(s),{mtime:s.mtime,size:s.size}]))),n;const a=new Set(e.map(yo));let r=!1;for(const s of Object.keys(t))a.has(s)||(delete t[s],r=!0);for(const s of e){const l=t[yo(s)];l?(s.size>l.size||s.mtime>l.mtime+1e3)&&n.set(yo(s),{kind:"updated",deltaSize:Math.max(0,s.size-l.size)}):n.set(yo(s),{kind:"new",deltaSize:s.size})}return r&&Kf(t),n}function Tne(e){const t=H2();t[yo(e)]={mtime:e.mtime,size:e.size},Kf(t)}function Sne(e){const t=H2();for(const n of e)t[yo(n)]={mtime:n.mtime,size:n.size};Kf(t)}const uc=yo,tx=e=>new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),Vk=e=>e>1e6?`${(e/1e6).toFixed(1)} MB`:`${Math.max(1,Math.round(e/1024))} KB`,Ane={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 Nne({roots:e,counts:t,onChanged:n,onClose:a}){const r=Ft(),s=B2(),l={"claude-projects":"Claude Code","codex-sessions":"Codex","dsh-sessions":"DeepSeek Harness","pi-sessions":"Pi"},[c,d]=j.useState(null),h=()=>{window.desktopSessions?.commandsStatus?.().then(d).catch(()=>{})};j.useEffect(h,[]);const m={"claude-code":"Claude Code",codex:"Codex",dsh:"DeepSeek Harness",pi:"Pi"},p=x=>u.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:[u.jsx("input",{type:"checkbox",checked:!s.has(x.key),disabled:!x.exists,onChange:b=>{vne(x.key,!b.target.checked),n()},className:"shrink-0"}),u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsx("div",{className:"text-sm text-ink",children:l[x.key]??x.path.split("/").filter(Boolean).pop()}),u.jsx("div",{className:"text-2xs text-ink-faint truncate",children:x.path})]}),u.jsx("span",{className:"text-2xs text-ink-faint shrink-0",children:x.exists?t.get(x.key)??0:r("atlas.rootMissing")}),!x.builtin&&u.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:u.jsx(Fa,{size:14,strokeWidth:1.75})})]},x.key);return u.jsx("div",{className:"absolute inset-0 z-10 bg-ink/20 flex items-center justify-center",onClick:a,children:u.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:[u.jsxs("div",{className:"px-4 pt-3.5 pb-2.5 border-b border-line",children:[u.jsx("div",{className:"text-sm font-semibold text-ink",children:r("atlas.sourcesTitle")}),u.jsx("div",{className:"text-2xs text-ink-muted mt-0.5",children:r("atlas.sourcesHint")})]}),e.filter(x=>x.builtin).map(p),c&&Object.values(c).some(x=>x.state!=="unavailable")&&u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"px-4 pt-3 pb-1.5 text-2xs uppercase tracking-wide text-ink-faint",children:r("atlas.handoffTitle")}),Object.entries(c).filter(([,x])=>x.state!=="unavailable").map(([x,b])=>u.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:[u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsxs("div",{className:"text-sm text-ink flex items-center gap-2",children:[m[x]??x,u.jsx("code",{className:"text-2xs bg-wash border border-line rounded px-1.5 py-px font-mono",children:b.invoke})]}),u.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"&&u.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 Kt(async()=>{const{confirmDialog:w}=await Promise.resolve().then(()=>hm);return{confirmDialog:w}},void 0);if(!await y({title:Ie("atlas.handoffEnableTitle"),message:Ue(Ie("confirm.installCommand"),{path:b.dest}),confirmLabel:Ie(b.state==="outdated"?"atlas.handoffUpdate":"atlas.handoffEnable")}))return;const T=await window.desktopSessions.commandsInstall(x);T.ok?Ke("success",Ue(Ie("atlas.handoffInstalled"),{cmd:b.invoke}),8e3):Ke("error",T.error??"install failed"),h()})()},children:r(b.state==="outdated"?"atlas.handoffUpdate":"atlas.handoffEnable")}),(b.state==="installed"||b.state==="outdated")&&u.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:u.jsx(Fa,{size:14,strokeWidth:1.75})})]},x))]}),e.filter(x=>!x.builtin).map(p),u.jsxs("div",{className:"flex items-center gap-2 px-4 py-3",children:[u.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:[u.jsx(ir,{size:13,strokeWidth:1.75})," ",r("atlas.autoDetect")]}),u.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:[u.jsx(l7,{size:13,strokeWidth:1.75})," ",r("atlas.addDir")]})]})]})})}function jN({onClose:e,onSwitched:t,focusSessionId:n}){const a=Ft(),r=Cn(ie=>ie.projects),s=Cn(ie=>ie.projects.find(ze=>ze.id===ie.activeId)?.sourceSession?.sessionId),l=!!window.desktopSessions,[c,d]=j.useState(null),[h,m]=j.useState([]),[p,x]=j.useState(!1),[b,y]=j.useState(window.desktopSessions?null:"canvases"),[k,T]=j.useState(null),[w,_]=j.useState(!1),[A,C]=j.useState(null),[O,D]=j.useState(new Map),[M,N]=j.useState(new Map),[R,B]=j.useState(new Map),[U,Y]=j.useState(!1),Z=ie=>`${ie.rootKey}|${ie.rel}`,W=ie=>B(ze=>{const pe=new Map(ze),qe=Z(ie);return pe.has(qe)?pe.delete(qe):pe.set(qe,ie),pe}),K=ie=>r.find(ze=>Dx(ze).includes(ie)),[F,G]=j.useState(""),[ne,X]=j.useState(new Set),[P,q]=j.useState("time"),[J,H]=j.useState(!1),[se,ye]=j.useState(!1),[be,ke]=j.useState(new Map),[ae,Te]=j.useState(null);j.useEffect(()=>{window.desktopSessions?.openTargets().then(Te).catch(()=>{})},[]);const Oe=j.useMemo(()=>new Map((ae?.apps??[]).map(ie=>[ie.runner,ie.name])),[ae]),Le=async()=>{x(!0);try{m(await window.desktopSessions?.roots().catch(()=>[])??[]);const ie=await wne();if(d(ie),ke(Ene(ie)),window.desktopSessions?.codexThreads?.().then(ze=>{ze&&(D(new Map(ze.filter(pe=>pe.name&&pe.sessionId).map(pe=>[pe.sessionId,pe.name]))),N(new Map(ze.filter(pe=>pe.forkedFromId&&pe.sessionId).map(pe=>[pe.sessionId,pe.forkedFromId]))))}).catch(()=>{}),n){const ze=ie.find(pe=>pe.sessionId===n);ze&&y(ze.cwd??"")}}finally{x(!1)}};j.useEffect(()=>{Le()},[]),j.useEffect(()=>{let ie=!1;const ze=()=>{ie||p||(ie=!0,setTimeout(()=>{ie=!1,Le()},2e3))};return window.addEventListener("td:sessions-changed",ze),()=>window.removeEventListener("td:sessions-changed",ze)},[p]);const We=j.useCallback(ie=>O.get(ie.sessionId)??ie.title,[O]),Be=j.useMemo(()=>(c??[]).filter(ie=>!ne.has(ie.runner)&&(se||!ie.subagent)&&(!J||be.has(uc(ie)))&&(!F.trim()||We(ie).toLowerCase().includes(F.trim().toLowerCase()))),[c,ne,F,J,be,se,We]),rt=j.useMemo(()=>kne(Be),[Be]),ht=j.useMemo(()=>[...new Set((c??[]).map(ie=>ie.runner))].sort(),[c]),Xe=j.useMemo(()=>{const ie=new Map;for(const ze of c??[])ie.set(ze.rootKey,(ie.get(ze.rootKey)??0)+1);return ie},[c]),kt=b==="canvases"?null:rt.find(ie=>(ie.cwd??"")===(b??rt[0]?.cwd??""))??rt[0]??null,yt=j.useMemo(()=>{if(!kt)return[];const ie=P==="name"?(ze,pe)=>We(ze).localeCompare(We(pe)):Ane[P];return[...kt.cards].sort(ie)},[kt,P,We]),at=ie=>{Tne(ie),ke(ze=>{const pe=new Map(ze);return pe.delete(uc(ie)),pe})},Et=async ie=>{if(!k){T(ie.rel),at(ie);try{const{streamRunnerConversation:ze}=await Kt(async()=>{const{streamRunnerConversation:St}=await import("./index-NvCD8Rvo.js");return{streamRunnerConversation:St}},[]),{importOrAppendConversation:pe,shellSessionReader:qe}=await Kt(async()=>{const{importOrAppendConversation:St,shellSessionReader:qt}=await import("./canonical-D2XBb2dX.js");return{importOrAppendConversation:St,shellSessionReader:qt}},[]),ut=await ze(qe(ie.rootKey,ie.rel)),gt=await pe(ut);if(!gt)throw new Error(Ie("handoff.notASession"));gt.kind==="appended"?Ke("success",Ue(Ie("atlas.appended"),{n:gt.turns}),9e3):gt.kind==="mounted"?Ke("success",Ue(Ie(gt.mode==="continue"?"atlas.mountedChapter":"atlas.mountedBranch"),{n:gt.turns}),9e3):gt.kind==="opened"?Ke("info",Ie("atlas.upToDate"),6e3):Ke("success",Ue(Ie("toast.importedChats"),{n:1,m:gt.nodeCount}),9e3),e(),t()}catch(ze){Ke("error",Ue(Ie("atlas.parseFailed"),{msg:ze instanceof Error?ze.message:String(ze)}))}finally{T(null)}}},zt=async ie=>{if(!(k||R.size<2)){T("__merge__");try{const{streamRunnerConversation:ze}=await Kt(async()=>{const{streamRunnerConversation:St}=await import("./index-NvCD8Rvo.js");return{streamRunnerConversation:St}},[]),{mergeSessionsIntoProject:pe,shellSessionReader:qe}=await Kt(async()=>{const{mergeSessionsIntoProject:St,shellSessionReader:qt}=await import("./canonical-D2XBb2dX.js");return{mergeSessionsIntoProject:St,shellSessionReader:qt}},[]),ut=[];for(const St of R.values())ut.push(await ze(qe(St.rootKey,St.rel))),at(St);const gt=await pe(ut,ie);if(!gt)throw new Error(Ie("handoff.notASession"));Ke("success",Ue(Ie("atlas.merged"),{n:gt.mounted}),1e4),gt.skipped>0&&Ke("info",Ue(Ie("atlas.mergeSkippedInfo"),{n:gt.skipped}),8e3),B(new Map),e(),t()}catch(ze){Ke("error",Ue(Ie("atlas.parseFailed"),{msg:ze instanceof Error?ze.message:String(ze)}))}finally{T(null)}}},Ve=async ie=>{const ze=Cn.getState().projects.find(ut=>ut.sourceSession?.sessionId===ie.sessionId);if(!ze||k)return;const{confirmDialog:pe}=await Kt(async()=>{const{confirmDialog:ut}=await Promise.resolve().then(()=>hm);return{confirmDialog:ut}},void 0);if(await pe({title:Ie("confirm.recastTitle"),message:Ue(Ie("confirm.recast"),{name:ze.name}),confirmLabel:Ie("confirm.recastTitle"),danger:!0})){T(ie.rel);try{const{streamRunnerConversation:ut}=await Kt(async()=>{const{streamRunnerConversation:$t}=await import("./index-NvCD8Rvo.js");return{streamRunnerConversation:$t}},[]),{importOrAppendConversation:gt,shellSessionReader:St}=await Kt(async()=>{const{importOrAppendConversation:$t,shellSessionReader:vn}=await import("./canonical-D2XBb2dX.js");return{importOrAppendConversation:$t,shellSessionReader:vn}},[]),qt=await ut(St(ie.rootKey,ie.rel));if(!qt)throw new Error(Ie("handoff.notASession"));const{deleteProject:un}=await Kt(async()=>{const{deleteProject:$t}=await Promise.resolve().then(()=>gm);return{deleteProject:$t}},void 0);if(await un(ze.id),!await gt(qt))throw new Error(Ie("handoff.notASession"));Ke("success",Ie("atlas.recastDone"),8e3),e(),t()}catch(ut){Ke("error",Ue(Ie("atlas.parseFailed"),{msg:ut instanceof Error?ut.message:String(ut)}))}finally{T(null)}}},Bt=async(ie,ze)=>{const pe=await window.desktopSessions.openInCli(ie.runner,ie.cwd,ie.sessionId,ze).catch(()=>({opened:!1,via:"",command:""}));pe.opened&&pe.via==="app"?(await navigator.clipboard.writeText(ie.sessionId).catch(()=>{}),Ke("success",Ie("atlas.appOpened"),9e3)):pe.opened?Ke("success",Ie("atlas.opened")):pe.command&&(await navigator.clipboard.writeText(pe.command).catch(()=>{}),Ke("info",Ie("atlas.cmdCopied"),9e3))};return $a.createPortal(u.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:u.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:[u.jsxs("div",{className:"flex items-start gap-3 px-5 pt-4 pb-3 border-b border-line",children:[u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsx("div",{className:"text-base font-semibold text-ink",children:a("atlas.title")}),u.jsx("div",{className:"text-xs text-ink-muted mt-0.5",children:a("atlas.subtitle")}),be.size>0&&u.jsxs("div",{className:"text-xs mt-1 flex items-center gap-2","data-atlas-changes":!0,children:[u.jsx("span",{className:"text-accent",children:Ue(a("atlas.changesSummary"),{n:[...be.values()].filter(ie=>ie.kind==="new").length,m:[...be.values()].filter(ie=>ie.kind==="updated").length})}),u.jsx("button",{className:"text-ink-faint hover:text-ink underline decoration-dotted transition-colors",onClick:()=>{Sne(c??[]),ke(new Map)},"data-atlas-mark-all":!0,children:a("atlas.markAllSeen")})]})]}),l&&ae&&ae.terminals.length>0&&u.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:a("atlas.terminalChoice"),children:[u.jsx(Nd,{size:14,strokeWidth:1.75}),u.jsxs("select",{value:ae.prefs.terminal,onChange:ie=>{const ze=ie.target.value;if(ze==="__add__"){window.desktopSessions?.addTerminal().then(()=>window.desktopSessions?.openTargets().then(Te));return}window.desktopSessions?.setOpenPrefs({terminal:ze}).then(pe=>Te(qe=>qe&&{...qe,prefs:pe}))},className:"bg-transparent focus:outline-none text-sm text-ink cursor-pointer","data-atlas-terminal-select":!0,children:[ae.terminals.map(ie=>u.jsx("option",{value:ie.id,children:ie.name},ie.id)),ae.canAddCustom&&u.jsx("option",{value:"__add__",children:a("atlas.otherTerminal")})]})]}),l&&u.jsxs("button",{onClick:()=>_(!0),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:[u.jsx(l7,{size:14,strokeWidth:1.75})," ",a("atlas.sources")]}),l&&u.jsxs("button",{onClick:()=>{Le()},disabled:p,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:[p?u.jsx(Xn,{size:14,className:"animate-spin"}):u.jsx(ir,{size:14,strokeWidth:1.75}),a(p?"atlas.scanning":"atlas.refresh")]}),u.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:u.jsx(bn,{size:18,strokeWidth:1.75})})]}),u.jsxs("div",{className:"flex-1 flex min-h-0",children:[u.jsxs("div",{className:"w-[260px] border-r border-line overflow-y-auto py-2 shrink-0",children:[u.jsx("div",{className:"px-4 py-1 text-2xs uppercase tracking-wide text-ink-faint",children:a("atlas.recent")}),r.filter(ie=>!ie.archived).sort((ie,ze)=>ze.updatedAt-ie.updatedAt).slice(0,6).map(ie=>u.jsxs("button",{onClick:()=>{e(),Ss(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?u.jsx("span",{className:"text-2xs font-mono border border-line rounded px-1 py-px shrink-0 text-ink-faint",children:ie.sourceSession.runner}):u.jsx(Fw,{size:13,strokeWidth:1.75,className:"shrink-0 text-ink-faint"}),u.jsx("span",{className:"flex-1 truncate text-sm",children:ie.name})]},ie.id)),u.jsx("div",{className:"border-t border-line mt-2 pt-2 px-4 py-1 text-2xs uppercase tracking-wide text-ink-faint",children:a("atlas.folders")}),!l&&u.jsx("div",{className:"px-4 py-2 text-xs text-ink-faint",children:a("atlas.webNoScan")}),l&&c===null&&u.jsxs("div",{className:"px-4 py-2 text-sm text-ink-faint flex items-center gap-2",children:[u.jsx(Xn,{size:14,className:"animate-spin"})," ",a("atlas.scanning")]}),l&&c!==null&&rt.length===0&&u.jsx("div",{className:"px-4 py-2 text-xs text-ink-faint",children:a("atlas.empty")}),rt.map(ie=>{const ze=ie.cwd??"",pe=b!=="canvases"&&kt===ie;return u.jsxs("button",{onClick:()=>y(ze),className:`w-full text-left px-4 py-2 flex items-center gap-2 transition-colors ${pe?"bg-accent/5 text-accent":"text-ink hover:bg-wash"}`,"data-atlas-folder":ie.name||"unfiled",children:[pe?u.jsx(t7,{size:15,strokeWidth:1.75,className:"shrink-0"}):u.jsx(MP,{size:15,strokeWidth:1.75,className:"shrink-0 text-ink-faint"}),u.jsx("span",{className:"flex-1 truncate text-sm",children:ie.name||a("atlas.unfiled")}),(()=>{const qe=ie.cards.filter(ut=>be.has(uc(ut))).length;return qe>0?u.jsxs("span",{className:"text-2xs text-accent shrink-0","data-atlas-folder-changes":!0,children:["+",qe]}):null})(),u.jsx("span",{className:"text-2xs text-ink-faint shrink-0",children:ie.cards.length})]},ze)}),u.jsx("div",{className:"border-t border-line mt-2 pt-2",children:u.jsxs("button",{onClick:()=>y("canvases"),className:`w-full text-left px-4 py-2 flex items-center gap-2 transition-colors ${b==="canvases"?"bg-accent/5 text-accent":"text-ink hover:bg-wash"}`,"data-atlas-canvases":!0,children:[u.jsx(Fw,{size:15,strokeWidth:1.75,className:"shrink-0"}),u.jsx("span",{className:"flex-1 truncate text-sm",children:a("atlas.myCanvases")}),u.jsx("span",{className:"text-2xs text-ink-faint shrink-0",children:r.length})]})})]}),u.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:b==="canvases"?u.jsxs("div",{className:"space-y-1.5",children:[r.filter(ie=>!ie.archived).sort((ie,ze)=>ze.updatedAt-ie.updatedAt).map(ie=>u.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(),Ss(ie.id).then(t)},children:[u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsx("div",{className:"text-sm text-ink font-medium truncate",children:ie.name}),u.jsxs("div",{className:"text-2xs text-ink-faint mt-0.5 flex items-center gap-1.5",children:[u.jsx("span",{children:tx(ie.updatedAt)}),!!ie.sourceSession?.sessionId&&u.jsx("span",{className:"font-mono border border-line rounded px-1 py-px",children:ie.sourceSession.runner})]})]}),u.jsx("button",{title:a("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:ze=>{ze.stopPropagation(),Df(ie.id,!0)},"data-atlas-archive":!0,children:u.jsx(Io,{size:15,strokeWidth:1.75})}),!!ie.sourceSession&&Dx(ie).length>0&&u.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&&u.jsxs("span",{children:["◉ ",ie.sourceSession.runner," ",ie.sourceSession.sessionId.slice(0,8)," · ",Ue(a("atlas.turnsN"),{n:ie.sourceSession.importedCount})]}),(ie.sourceSession.chapters??[]).map(ze=>u.jsxs("span",{children:["↳ ",ze.runner," ",ze.sessionId.slice(0,8)," · ",Ue(a("atlas.turnsN"),{n:ze.importedCount})]},ze.sessionId)),(ie.sourceSession.branches??[]).map(ze=>u.jsxs("span",{children:["⑂ ",ze.runner," ",ze.sessionId.slice(0,8)," · ",Ue(a("atlas.turnsN"),{n:ze.importedCount})]},ze.sessionId))]})]},ie.id)),r.some(ie=>ie.archived)&&u.jsxs("details",{className:"pt-2","data-atlas-archived-group":!0,children:[u.jsx("summary",{className:"text-2xs uppercase tracking-wide text-ink-faint cursor-pointer px-1 py-1",children:Ue(a("atlas.archivedGroup"),{n:r.filter(ie=>ie.archived).length})}),u.jsx("div",{className:"space-y-1.5 mt-1.5",children:r.filter(ie=>ie.archived).sort((ie,ze)=>ze.updatedAt-ie.updatedAt).map(ie=>u.jsxs("button",{title:a("atlas.restoreOpen"),onClick:()=>{Df(ie.id,!1).then(()=>{e(),Ss(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:[u.jsxs("div",{className:"text-sm text-ink truncate flex items-center gap-1.5",children:[u.jsx("span",{className:"truncate",children:ie.name}),!!ie.sourceSession?.sessionId&&u.jsx("span",{className:"text-2xs font-mono border border-line rounded px-1 py-px shrink-0 text-ink-faint",children:ie.sourceSession.runner})]}),u.jsx("div",{className:"text-2xs text-ink-faint mt-0.5",children:tx(ie.updatedAt)})]},ie.id))})]})]}):u.jsxs(u.Fragment,{children:[(c?.length??0)>0&&u.jsxs("div",{className:"flex items-center gap-2 mb-3 flex-wrap",children:[u.jsxs("div",{className:"flex items-center gap-1.5 border border-line rounded-lg px-2 py-1 bg-card",children:[u.jsx(Cf,{size:13,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),u.jsx("input",{value:F,onChange:ie=>G(ie.target.value),placeholder:a("atlas.filterTitle"),className:"text-sm bg-transparent focus:outline-none w-[150px] text-ink placeholder:text-ink-faint","data-atlas-filter":!0})]}),ht.map(ie=>u.jsx("button",{onClick:()=>X(ze=>{const pe=new Set(ze);return pe.has(ie)?pe.delete(ie):pe.add(ie),pe}),className:`text-2xs font-mono border rounded-lg px-2 py-1 transition-colors ${ne.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)),be.size>0&&u.jsx("button",{onClick:()=>H(ie=>!ie),className:`text-2xs border rounded-lg px-2 py-1 transition-colors ${J?"border-accent text-white bg-accent":"border-line text-ink-muted hover:text-ink"}`,"data-atlas-only-changed":!0,children:a("atlas.onlyChanged")}),(c??[]).some(ie=>ie.subagent)&&u.jsx("button",{onClick:()=>ye(ie=>!ie),className:`text-2xs border rounded-lg px-2 py-1 transition-colors ${se?"border-accent text-accent bg-accent/5":"border-line text-ink-faint hover:text-ink"}`,"data-atlas-show-sub":!0,children:a("atlas.showSub")}),u.jsxs("button",{onClick:()=>q(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:[u.jsx(Cj,{size:12,strokeWidth:1.75}),a(`atlas.sort${P[0].toUpperCase()}${P.slice(1)}`)]})]}),kt?u.jsxs(u.Fragment,{children:[kt.cwd&&u.jsxs("div",{className:"text-2xs text-ink-faint mb-3 truncate",children:[kt.cwd," · ",Ue(a("atlas.sessions"),{n:kt.cards.length})]}),u.jsx("div",{className:"space-y-1.5",children:yt.map(ie=>u.jsxs("div",{className:`group border rounded-xl px-4 py-3 hover:bg-wash transition-colors cursor-pointer flex items-center gap-3 ${R.has(Z(ie))?"border-accent/60 bg-accent/5":"border-line"}`,onClick:()=>{Et(ie)},"data-atlas-session":ie.sessionId,children:[u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsxs("div",{className:"text-sm text-ink truncate flex items-center gap-1.5",children:[u.jsx("span",{className:"truncate",children:We(ie)}),M.has(ie.sessionId)&&u.jsx("span",{className:"text-2xs text-ink-faint border border-line rounded px-1 py-px shrink-0 font-mono",title:`⑂ ${M.get(ie.sessionId)}`,"data-atlas-fork":!0,children:"⑂"}),be.get(uc(ie))?.kind==="new"&&u.jsx("span",{className:"text-2xs text-white bg-accent rounded px-1 py-px shrink-0","data-atlas-badge":"new",children:a("atlas.badgeNew")}),be.get(uc(ie))?.kind==="updated"&&u.jsxs("span",{className:"text-2xs text-accent border border-accent/40 rounded px-1 py-px shrink-0","data-atlas-badge":"updated",children:["+",Vk(be.get(uc(ie)).deltaSize)]}),ie.sessionId===s?u.jsx("span",{className:"text-2xs text-white bg-ink rounded px-1 py-px shrink-0","data-atlas-badge":"current",children:a("atlas.currentOpen")}):(()=>{const ze=K(ie.sessionId);return ze?u.jsx("span",{className:"text-2xs text-ink-faint border border-line rounded px-1 py-px shrink-0",title:ze.name,"data-atlas-badge":"canvas",children:a("atlas.onCanvas")}):null})()]}),u.jsxs("div",{className:"text-2xs text-ink-faint mt-0.5 flex items-center gap-2",children:[u.jsx("span",{className:"border border-line rounded px-1 py-px font-mono",children:ie.runner}),u.jsx("span",{children:tx(ie.mtime)}),u.jsx("span",{children:Vk(ie.size)})]})]}),k===ie.rel?u.jsx(Xn,{size:16,className:"animate-spin text-accent shrink-0"}):u.jsxs("div",{className:`${R.has(Z(ie))?"":"opacity-0 group-hover:opacity-100"} transition-opacity flex items-center gap-1 shrink-0`,children:[!K(ie.sessionId)&&!!ie.sessionId&&u.jsx("button",{title:a("atlas.pickForMerge"),className:`p-1.5 rounded transition-colors ${R.has(Z(ie))?"text-accent":"text-ink-faint hover:text-accent"}`,onClick:ze=>{ze.stopPropagation(),W(ie)},"data-atlas-pick":R.has(Z(ie))?"on":"off",children:R.has(Z(ie))?u.jsx(Lz,{size:16,strokeWidth:1.75}):u.jsx(Ib,{size:16,strokeWidth:1.75})}),u.jsx("span",{title:a("atlas.import"),className:"text-ink-faint hover:text-accent p-1.5",children:u.jsx(qP,{size:16,strokeWidth:1.75})}),r.some(ze=>ze.sourceSession?.sessionId===ie.sessionId)&&u.jsx("button",{title:a("atlas.recast"),className:"text-ink-faint hover:text-red-500 p-1.5 rounded transition-colors",onClick:ze=>{ze.stopPropagation(),Ve(ie)},"data-atlas-recast":!0,children:u.jsx(wz,{size:16,strokeWidth:1.75})}),!K(ie.sessionId)&&u.jsx("button",{title:a("atlas.mountTo"),className:"text-ink-faint hover:text-accent p-1.5 rounded transition-colors",onClick:ze=>{ze.stopPropagation(),C(ie)},"data-atlas-mount":!0,children:u.jsx(Ao,{size:16,strokeWidth:1.75})}),Oe.has(ie.runner)&&u.jsx("button",{title:Ue(a("atlas.openApp"),{name:Oe.get(ie.runner)}),className:"text-ink-faint hover:text-accent p-1.5 rounded transition-colors",onClick:ze=>{ze.stopPropagation(),Bt(ie,"app")},"data-atlas-open-app":!0,children:u.jsx(Tj,{size:16,strokeWidth:1.75})}),u.jsx("button",{title:a("atlas.openTerminal"),className:"text-ink-faint hover:text-accent p-1.5 rounded transition-colors",onClick:ze=>{ze.stopPropagation(),Bt(ie,"terminal")},"data-atlas-open-cli":!0,children:u.jsx(Nd,{size:16,strokeWidth:1.75})})]})]},ie.rel))})]}):u.jsx("div",{className:"py-16 text-center text-sm text-ink-faint",children:c===null?a("atlas.scanning"):c.length>0?a("atlas.filteredOut"):a("atlas.empty")})]})})]}),R.size>=2&&!U&&u.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:[u.jsx("span",{className:"text-xs text-ink-muted whitespace-nowrap",children:Ue(a("atlas.mergeSelected"),{n:R.size})}),k==="__merge__"?u.jsx(Xn,{size:15,className:"animate-spin text-accent"}):u.jsxs(u.Fragment,{children:[u.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:()=>{zt()},"data-atlas-merge-new":!0,children:a("atlas.mergeNew")}),u.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:()=>Y(!0),"data-atlas-merge-into":!0,children:a("atlas.mergeInto")})]}),u.jsx("button",{className:"text-ink-faint hover:text-ink p-1",onClick:()=>B(new Map),title:a("common.cancel"),children:u.jsx(bn,{size:14,strokeWidth:1.75})})]}),(A||U)&&u.jsx("div",{className:"absolute inset-0 z-10 bg-ink/20 flex items-center justify-center",onClick:()=>{C(null),Y(!1)},children:u.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:[u.jsxs("div",{className:"px-4 pt-3.5 pb-2.5 border-b border-line",children:[u.jsx("div",{className:"text-sm font-semibold text-ink",children:a(U?"atlas.mergeInto":"atlas.mountTo")}),u.jsx("div",{className:"text-2xs text-ink-muted mt-0.5",children:a(U?"atlas.mergeSelected":"atlas.mountHint").replace("{n}",String(R.size))})]}),r.filter(ie=>!ie.archived&&ie.kind!=="paradigm").sort((ie,ze)=>ze.updatedAt-ie.updatedAt).map(ie=>u.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(U){Y(!1),zt(ie.id);return}const ze=A;C(null),(async()=>{T(ze.rel);try{const{streamRunnerConversation:pe}=await Kt(async()=>{const{streamRunnerConversation:qt}=await import("./index-NvCD8Rvo.js");return{streamRunnerConversation:qt}},[]),{mountConversationToProject:qe,shellSessionReader:ut}=await Kt(async()=>{const{mountConversationToProject:qt,shellSessionReader:un}=await import("./canonical-D2XBb2dX.js");return{mountConversationToProject:qt,shellSessionReader:un}},[]),gt=await pe(ut(ze.rootKey,ze.rel)),St=await qe(gt,ie.id);if(!St)throw new Error(Ie("handoff.notASession"));Ke("success",Ue(Ie("atlas.mountedChapter"),{n:St.kind==="mounted"||St.kind==="appended"?St.turns:0}),9e3),e(),t()}catch(pe){Ke("error",Ue(Ie("atlas.parseFailed"),{msg:pe instanceof Error?pe.message:String(pe)}))}finally{T(null)}})()},children:ie.name},ie.id))]})}),w&&u.jsx(Nne,{roots:h,counts:Xe,onChanged:()=>{Le()},onClose:()=>_(!1)})]})}),document.body)}function Cne({conversations:e,onClose:t,onDone:n}){const a=Ft(),[r,s]=j.useState(new Set),[l,c]=j.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||l||(c(!0),await lU([...r].sort((p,x)=>p-x).map(p=>e[p])),c(!1),n())};return u.jsx("div",{className:"fixed inset-0 z-50 bg-ink/30 backdrop-blur-sm flex items-center justify-center p-6",onClick:t,children:u.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:[u.jsxs("div",{className:"px-6 py-4 border-b border-line flex items-start justify-between gap-4",children:[u.jsxs("div",{children:[u.jsx("h2",{className:"text-base font-semibold text-ink",children:a("import.title")}),u.jsx("p",{className:"text-xs text-ink-muted mt-1 leading-relaxed",children:a("import.subtitle")})]}),u.jsx("button",{onClick:t,className:"text-ink-faint hover:text-ink transition-colors shrink-0 mt-0.5",children:u.jsx(bn,{size:16,strokeWidth:1.75})})]}),u.jsx("div",{className:"px-6 py-2 border-b border-line/60",children:u.jsxs("label",{className:"flex items-center gap-2 text-xs text-ink-muted cursor-pointer select-none py-1",children:[u.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"),u.jsx("span",{className:"ml-auto text-2xs text-ink-faint uppercase tracking-wider",children:e[0]?.source})]})}),u.jsx("ul",{className:"flex-1 overflow-y-auto py-1",children:e.map((p,x)=>u.jsx("li",{children:u.jsxs("label",{className:"flex items-center gap-3 px-6 py-2 hover:bg-wash transition-colors cursor-pointer select-none",children:[u.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"}),u.jsx(o7,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),u.jsx("span",{className:"text-sm text-ink truncate flex-1",children:p.title}),u.jsx("span",{className:"text-2xs text-ink-faint shrink-0",children:Ue(a("import.messages"),{n:p.messageCount})})]})},x))}),u.jsxs("div",{className:"px-6 py-4 border-t border-line flex justify-end gap-2",children:[u.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")}),u.jsx("button",{onClick:()=>{m()},disabled:r.size===0||l,className:"text-xs bg-accent hover:bg-accent-strong text-white px-5 py-2 rounded-lg transition-colors disabled:opacity-30",children:l?"…":Ue(a("import.confirm"),{n:r.size})})]})]})})}function _ne(e){const t=Date.now()-e,n=Math.floor(t/6e4);if(n<1)return Ie("switcher.justNow");if(n<60)return Ue(Ie("switcher.minAgo"),{n});const a=Math.floor(n/60);if(a<24)return Ue(Ie("switcher.hourAgo"),{n:a});const r=Math.floor(a/24);return r<30?Ue(Ie("switcher.dayAgo"),{n:r}):new Date(e).toLocaleDateString(Da.getState().lang==="zh"?"zh-CN":"en-US")}function Mne({onSwitched:e}){const t=Ft(),n=Cn(N=>N.projects),a=Cn(N=>N.activeId),r=Cn(N=>N.switching),s=n.find(N=>N.id===a)?.kind==="paradigm",[l,c]=j.useState(!1),[d,h]=j.useState(null),[m,p]=j.useState(!1),[x,b]=j.useState(void 0),[y,k]=j.useState(null),[T,w]=j.useState(""),_=j.useRef(null),A=j.useRef(null),C=n.find(N=>N.id===a),O=n.filter(N=>!N.archived).sort((N,R)=>R.updatedAt-N.updatedAt).slice(0,7),D=async N=>{const{canvasUniqueness:R}=await Kt(async()=>{const{canvasUniqueness:Z}=await import("./canonical-D2XBb2dX.js");return{canvasUniqueness:Z}},[]),B=await R(N.id),U=B==="native"?"confirm.deleteNative":B==="diverged-mirror"?"confirm.deleteDiverged":"confirm.deletePristine";await Ts({title:Ie("confirm.deleteCanvasTitle"),message:Ue(Ie(U),{name:N.name}),confirmLabel:Ie("common.delete"),danger:B!=="pristine-mirror"})&&$7(N.id).then(e)};j.useEffect(()=>{if(!l)return;const N=R=>{A.current?.contains(R.target)||c(!1)};return window.addEventListener("mousedown",N),()=>window.removeEventListener("mousedown",N)},[l]);const M=async N=>{c(!1),await Ss(N),e(),Kt(()=>import("./canonical-D2XBb2dX.js"),[]).then(R=>R.unsubscribeOrphanedSessions()),Kt(()=>import("./live-mirror-DHhvAkDw.js"),[]).then(R=>R.sweepRecentSessions())};return u.jsxs("div",{ref:A,className:"absolute top-4 left-4 z-20",children:[u.jsxs("div",{className:"flex items-center gap-1.5",children:[u.jsxs("button",{onClick:()=>c(!l),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?u.jsx(Xn,{size:16,strokeWidth:1.75,className:"animate-spin shrink-0 text-accent"}):s?u.jsx(hP,{size:16,strokeWidth:1.75,className:"shrink-0 text-accent"}):u.jsx(t7,{size:16,strokeWidth:1.75,className:"shrink-0 text-ink-muted"}),u.jsx("span",{className:"truncate font-medium",children:C?.name??"…"}),u.jsx($d,{size:14,strokeWidth:1.75,className:"shrink-0 text-ink-faint"})]}),!!C?.sourceSession?.sessionId&&(()=>{const N=$f.size>0&&!$f.has(C.sourceSession.sessionId);return u.jsxs("button",{title:N?Ie("switcher.mirrorBadgeGone"):Ue(Ie("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 ${N?"text-ink-faint/50 line-through decoration-1":"text-ink-faint hover:text-accent"}`,"data-twin-badge":N?"unreachable":"live",children:["⇄ ",C.sourceSession.runner]})})()]}),l&&u.jsxs("div",{className:"mt-1.5 bg-card border border-line rounded-xl shadow-lg py-1.5 w-[320px] animate-fade-in",children:[u.jsx("div",{className:"max-h-[320px] overflow-y-auto",children:O.map(N=>u.jsx("div",{className:`group flex items-center gap-1 px-3 py-2 hover:bg-wash cursor-pointer transition-colors ${N.id===a?"bg-accent/5":""}`,onClick:()=>{y!==N.id&&N.id!==a&&M(N.id)},children:y===N.id?u.jsx("input",{autoFocus:!0,value:T,onChange:R=>w(R.target.value),onClick:R=>R.stopPropagation(),onKeyDown:R=>{R.key==="Enter"&&!Ya(R)&&T.trim()&&(Y7(N.id,T.trim()),k(null)),R.key==="Escape"&&k(null)},onBlur:()=>k(null),className:"flex-1 text-sm text-ink border border-accent/40 rounded-lg px-2 py-1 bg-surface focus:outline-none"}):u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsx("div",{className:`text-sm truncate ${N.id===a?"text-accent font-medium":"text-ink"}`,children:N.name}),u.jsxs("div",{className:"text-2xs text-ink-faint flex items-center gap-1.5",children:[u.jsx("span",{children:_ne(N.updatedAt)}),!!N.sourceSession?.sessionId&&u.jsx("span",{className:"font-mono border border-line rounded px-1 py-px","data-mirror-mark":!0,children:N.sourceSession.runner})]})]}),u.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:R=>{R.stopPropagation(),k(N.id),w(N.name)},children:u.jsx(Rc,{size:14,strokeWidth:1.75})}),u.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:R=>{R.stopPropagation(),D(N)},children:u.jsx(Fa,{size:14,strokeWidth:1.75})}),u.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:R=>{R.stopPropagation(),Df(N.id,!0).then(e)},"data-archive-canvas":!0,children:u.jsx(Io,{size:14,strokeWidth:1.75})})]})},N.id))}),u.jsxs("div",{className:"border-t border-line mt-1 pt-1",children:[u.jsxs("button",{onClick:()=>{c(!1),pm().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:[u.jsx(um,{size:15,strokeWidth:1.75})," ",t("switcher.newCanvas")]}),u.jsxs("button",{onClick:()=>_.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:[u.jsx(Yz,{size:15,strokeWidth:1.75})," ",t("switcher.importBackup")]}),u.jsxs("button",{onClick:()=>{c(!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:[u.jsx(nz,{size:15,strokeWidth:1.75})," ",t("switcher.allCanvases")]}),window.desktop&&u.jsxs("button",{onClick:()=>{c(!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:[u.jsx(ir,{size:15,strokeWidth:1.75})," ",t("update.checkMenu"),u.jsxs("span",{className:"ml-auto text-2xs text-ink-faint",children:["v",new URLSearchParams(window.location.search).get("dv")]})]}),u.jsx("input",{ref:_,type:"file",accept:".json,.jsonl,application/json",className:"hidden",onChange:N=>{const R=N.target.files?.[0];R&&sU(R).then(B=>{B.kind==="own"&&B.ok?(c(!1),e()):B.kind==="chat"&&(c(!1),h(B.conversations))}).catch(B=>{Ke("error",Ue(Ie("toast.importFailedGeneric"),{msg:B instanceof Error?B.message:String(B)}))}),N.target.value=""}})]})]}),d&&u.jsx(Cne,{conversations:d,onClose:()=>h(null),onDone:()=>{h(null),e()}}),m&&u.jsx(jN,{onClose:()=>{p(!1),b(void 0)},onSwitched:e,focusSessionId:x})]})}const Ine="JVBERi0xLjQKMSAwIG9iago8PCAvVHlwZSAvQ2F0YWxvZyAvUGFnZXMgMiAwIFIgPj4KZW5kb2JqCjIgMCBvYmoKPDwgL1R5cGUgL1BhZ2VzIC9LaWRzIFszIDAgUiA0IDAgUl0gL0NvdW50IDIgPj4KZW5kb2JqCjMgMCBvYmoKPDwgL1R5cGUgL1BhZ2UgL1BhcmVudCAyIDAgUiAvTWVkaWFCb3ggWzAgMCA1OTUgODQyXSAvQ29udGVudHMgNSAwIFIgL1Jlc291cmNlcyA8PCAvRm9udCA8PCAvRjEgNyAwIFIgL0YyIDggMCBSID4+ID4+ID4+CmVuZG9iago0IDAgb2JqCjw8IC9UeXBlIC9QYWdlIC9QYXJlbnQgMiAwIFIgL01lZGlhQm94IFswIDAgNTk1IDg0Ml0gL0NvbnRlbnRzIDYgMCBSIC9SZXNvdXJjZXMgPDwgL0ZvbnQgPDwgL0YxIDcgMCBSIC9GMiA4IDAgUiA+PiA+PiA+PgplbmRvYmoKNSAwIG9iago8PCAvTGVuZ3RoIDExMTIgPj4Kc3RyZWFtCkJUCi9GMiAxOSBUZiAxIDAgMCAxIDY0IDcyNS4wIFRtIChXaHkgU2F2ZWQgQXJ0aWNsZXMgU3RheSBVbnJlYWQpIFRqCi9GMSAxMSBUZiAxIDAgMCAxIDY0IDcwOC4wIFRtIChBIHNob3J0IGJyaWVmIG9uIGRpZ2l0YWwgaG9hcmRpbmcgYW5kIHRoZSBjb2xsZWN0b3IncyBmYWxsYWN5KSBUagovRjIgMTMgVGYgMSAwIDAgMSA2NCA2NjkuMCBUbSAoMS4gVGhlIHBoZW5vbWVub24pIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNjUxLjUgVG0gKFJlYWQtaXQtbGF0ZXIgc2VydmljZXMgcmVwb3J0IHRoYXQgbW9zdCBzYXZlZCBpdGVtcyBhcmUgbmV2ZXIpIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNjM0LjAgVG0gKHJlb3BlbmVkLiBBY3Jvc3MgcHVibGlzaGVkIHVzYWdlIHN0dWRpZXMsIHRoZSBzaGFyZSBvZiBzYXZlZCkgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA2MTYuNSBUbSAoYXJ0aWNsZXMgdGhhdCBnZXQgYSBzZWNvbmQgdmlzaXQgaXMgc21hbGwsIGFuZCBjb21wbGV0aW9uIHJhdGVzKSBUagovRjEgMTEuNSBUZiAxIDAgMCAxIDY0IDU5OS4wIFRtIChhcmUgc21hbGxlciBzdGlsbC4gVGhlIGFyY2hpdmUgZ3Jvd3M7IHRoZSByZWFkaW5nIGRvZXMgbm90LikgVGoKL0YyIDEzIFRmIDEgMCAwIDEgNjQgNTYwLjAgVG0gKDIuIFRoZSBjb2xsZWN0b3IncyBmYWxsYWN5KSBUagovRjEgMTEuNSBUZiAxIDAgMCAxIDY0IDU0Mi41IFRtIChDb2xsZWN0aW5nIHByb2R1Y2VzIGFuIGltbWVkaWF0ZSBzZW5zZSBvZiBwcm9ncmVzcyB3aGlsZSB0aGUpIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNTI1LjAgVG0gKHVuZGVyc3RhbmRpbmcgaXQgcHJvbWlzZXMgaXMgZGVmZXJyZWQuIFNhdmluZyBhIHRleHQgZmVlbHMgbGlrZSkgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA1MDcuNSBUbSAoYSBmaXJzdCBzdGVwIG9mIHJlYWRpbmcgaXQsIGJ1dCBubyBwYXJ0IG9mIHRoZSByZWFkaW5nIGhhcykgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA0OTAuMCBUbSAoaGFwcGVuZWQuKSBUagovRjIgMTEuNSBUZiAxIDAgMCAxIDY0IDQ3Mi41IFRtIChUaGUgYWN0IG9mIHNhdmluZyBpcyBtaXN0YWtlbiBmb3IgdGhlIGFjdCBvZiBsZWFybmluZy4pIFRqCkVUCmVuZHN0cmVhbQplbmRvYmoKNiAwIG9iago8PCAvTGVuZ3RoIDkwOCA+PgpzdHJlYW0KQlQKL0YyIDEzIFRmIDEgMCAwIDEgNjQgNzI1LjAgVG0gKDMuIFdoeSBpdCBwZXJzaXN0cykgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA3MDcuNSBUbSAoVGhlIGNvc3RzIGFyZSBhc3ltbWV0cmljOiBzYXZpbmcgdGFrZXMgb25lIHNlY29uZCBhbmQgcGF5cyBvdXQpIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNjkwLjAgVG0gKGEgc21hbGwgcmV3YXJkIG5vdzsgcmVhZGluZyB0YWtlcyBhbiBob3VyIGFuZCBwYXlzIG91dCBsYXRlci4pIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNjcyLjUgVG0gKEhhYml0cyBmb2xsb3cgdGhlIGNoZWFwZXIgbG9vcCwgc28gbGlicmFyaWVzIGluZmxhdGUgYnkgZGVmYXVsdC4pIFRqCi9GMiAxMyBUZiAxIDAgMCAxIDY0IDYzMy41IFRtICg0LiBXaGF0IGhlbHBzKSBUagovRjEgMTEuNSBUZiAxIDAgMCAxIDY0IDYxNi4wIFRtIChJbnRlcnZlbnRpb25zIHRoYXQgd29yayBtb3ZlIHByb2Nlc3NpbmcgdG8gdGhlIG1vbWVudCBvZiBjYXB0dXJlOikgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA1OTguNSBUbSAod3JpdGUgb25lIGxpbmUgaW4geW91ciBvd24gd29yZHMgYWJvdXQgd2h5IHRoZSBpdGVtIG1hdHRlcnMsIGFuZCkgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA1ODEuMCBUbSAoc2NoZWR1bGUgYSByZXZpZXcgcGFzcyBpbnN0ZWFkIG9mIHRydXN0aW5nIHRoZSBhcmNoaXZlIHRvKSBUagovRjEgMTEuNSBUZiAxIDAgMCAxIDY0IDU2My41IFRtIChyZXN1cmZhY2UgaXQuKSBUagovRjEgMTEuNSBUZiAxIDAgMCAxIDY0IDUzMi4wIFRtIChBIHNtYWxsZXIgbGlicmFyeSB0aGF0IGdldHMgcHJvY2Vzc2VkIGJlYXRzIGEgY29tcGxldGUgb25lIHRoYXQpIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNTE0LjUgVG0gKGRvZXMgbm90LikgVGoKRVQKZW5kc3RyZWFtCmVuZG9iago3IDAgb2JqCjw8IC9UeXBlIC9Gb250IC9TdWJ0eXBlIC9UeXBlMSAvQmFzZUZvbnQgL0hlbHZldGljYSA+PgplbmRvYmoKOCAwIG9iago8PCAvVHlwZSAvRm9udCAvU3VidHlwZSAvVHlwZTEgL0Jhc2VGb250IC9IZWx2ZXRpY2EtQm9sZCA+PgplbmRvYmoKeHJlZgowIDkKMDAwMDAwMDAwMCA2NTUzNSBmIAowMDAwMDAwMDA5IDAwMDAwIG4gCjAwMDAwMDAwNTggMDAwMDAgbiAKMDAwMDAwMDEyMSAwMDAwMCBuIAowMDAwMDAwMjU3IDAwMDAwIG4gCjAwMDAwMDAzOTMgMDAwMDAgbiAKMDAwMDAwMTU1NyAwMDAwMCBuIAowMDAwMDAyNTE2IDAwMDAwIG4gCjAwMDAwMDI1ODYgMDAwMDAgbiAKdHJhaWxlcgo8PCAvU2l6ZSA5IC9Sb290IDEgMCBSID4+CnN0YXJ0eHJlZgoyNjYxCiUlRU9G",Dne=`<!-- tdag-page:1 -->
522
+ `)[0].slice(0,80)}return null}const RN="thoughtdag.atlas.disabledRoots",B2=()=>{try{return new Set(JSON.parse(localStorage.getItem(RN)??"[]"))}catch{return new Set}};function vne(e,t){const n=B2();t?n.add(e):n.delete(e),localStorage.setItem(RN,JSON.stringify([...n]))}const $f=new Set;async function wne(){const e=window.desktopSessions;if(!e)return[];const t=B2(),n=(await e.roots().catch(()=>[])).filter(r=>r.exists&&!t.has(r.key)).map(r=>r.key),a=[];for(const r of n){const l=[...await e.list(r).catch(()=>[])].sort((d,h)=>h.mtime-d.mtime),c=12;for(let d=0;d<l.length;d+=c){const h=await Promise.all(l.slice(d,d+c).map(async m=>{const p=m.rel.endsWith(".zstd")?qk:bne,x=await e.head(r,m.rel,p).catch(()=>"");if(!x)return null;const b=Wk(r,m.rel,x,m.mtime,m.size);if(b)return b;const y=await e.head(r,m.rel,qk).catch(()=>"");return y.length>x.length?Wk(r,m.rel,y,m.mtime,m.size):null}));for(const m of h)m&&a.push(m)}}$f.clear();for(const r of a)$f.add(r.sessionId);return a.sort((r,s)=>s.mtime-r.mtime)}function kne(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)}const LN="thoughtdag.atlas.watermark",yo=e=>`${e.rootKey}:${e.rel}`;function H2(){try{return JSON.parse(localStorage.getItem(LN)??"{}")}catch{return{}}}function Kf(e){localStorage.setItem(LN,JSON.stringify(e))}function Ene(e){const t=H2(),n=new Map;if(Object.keys(t).length===0)return Kf(Object.fromEntries(e.map(s=>[yo(s),{mtime:s.mtime,size:s.size}]))),n;const a=new Set(e.map(yo));let r=!1;for(const s of Object.keys(t))a.has(s)||(delete t[s],r=!0);for(const s of e){const l=t[yo(s)];l?(s.size>l.size||s.mtime>l.mtime+1e3)&&n.set(yo(s),{kind:"updated",deltaSize:Math.max(0,s.size-l.size)}):n.set(yo(s),{kind:"new",deltaSize:s.size})}return r&&Kf(t),n}function Tne(e){const t=H2();t[yo(e)]={mtime:e.mtime,size:e.size},Kf(t)}function Sne(e){const t=H2();for(const n of e)t[yo(n)]={mtime:n.mtime,size:n.size};Kf(t)}const uc=yo,tx=e=>new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),Vk=e=>e>1e6?`${(e/1e6).toFixed(1)} MB`:`${Math.max(1,Math.round(e/1024))} KB`,Ane={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 Nne({roots:e,counts:t,onChanged:n,onClose:a}){const r=Ft(),s=B2(),l={"claude-projects":"Claude Code","codex-sessions":"Codex","dsh-sessions":"DeepSeek Harness","pi-sessions":"Pi"},[c,d]=j.useState(null),h=()=>{window.desktopSessions?.commandsStatus?.().then(d).catch(()=>{})};j.useEffect(h,[]);const m={"claude-code":"Claude Code",codex:"Codex",dsh:"DeepSeek Harness",pi:"Pi"},p=x=>u.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:[u.jsx("input",{type:"checkbox",checked:!s.has(x.key),disabled:!x.exists,onChange:b=>{vne(x.key,!b.target.checked),n()},className:"shrink-0"}),u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsx("div",{className:"text-sm text-ink",children:l[x.key]??x.path.split("/").filter(Boolean).pop()}),u.jsx("div",{className:"text-2xs text-ink-faint truncate",children:x.path})]}),u.jsx("span",{className:"text-2xs text-ink-faint shrink-0",children:x.exists?t.get(x.key)??0:r("atlas.rootMissing")}),!x.builtin&&u.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:u.jsx(Fa,{size:14,strokeWidth:1.75})})]},x.key);return u.jsx("div",{className:"absolute inset-0 z-10 bg-ink/20 flex items-center justify-center",onClick:a,children:u.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:[u.jsxs("div",{className:"px-4 pt-3.5 pb-2.5 border-b border-line",children:[u.jsx("div",{className:"text-sm font-semibold text-ink",children:r("atlas.sourcesTitle")}),u.jsx("div",{className:"text-2xs text-ink-muted mt-0.5",children:r("atlas.sourcesHint")})]}),e.filter(x=>x.builtin).map(p),c&&Object.values(c).some(x=>x.state!=="unavailable")&&u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"px-4 pt-3 pb-1.5 text-2xs uppercase tracking-wide text-ink-faint",children:r("atlas.handoffTitle")}),Object.entries(c).filter(([,x])=>x.state!=="unavailable").map(([x,b])=>u.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:[u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsxs("div",{className:"text-sm text-ink flex items-center gap-2",children:[m[x]??x,u.jsx("code",{className:"text-2xs bg-wash border border-line rounded px-1.5 py-px font-mono",children:b.invoke})]}),u.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"&&u.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 Kt(async()=>{const{confirmDialog:w}=await Promise.resolve().then(()=>hm);return{confirmDialog:w}},void 0);if(!await y({title:Ie("atlas.handoffEnableTitle"),message:Ue(Ie("confirm.installCommand"),{path:b.dest}),confirmLabel:Ie(b.state==="outdated"?"atlas.handoffUpdate":"atlas.handoffEnable")}))return;const T=await window.desktopSessions.commandsInstall(x);T.ok?Ke("success",Ue(Ie("atlas.handoffInstalled"),{cmd:b.invoke}),8e3):Ke("error",T.error??"install failed"),h()})()},children:r(b.state==="outdated"?"atlas.handoffUpdate":"atlas.handoffEnable")}),(b.state==="installed"||b.state==="outdated")&&u.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:u.jsx(Fa,{size:14,strokeWidth:1.75})})]},x))]}),e.filter(x=>!x.builtin).map(p),u.jsxs("div",{className:"flex items-center gap-2 px-4 py-3",children:[u.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:[u.jsx(ir,{size:13,strokeWidth:1.75})," ",r("atlas.autoDetect")]}),u.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:[u.jsx(l7,{size:13,strokeWidth:1.75})," ",r("atlas.addDir")]})]})]})})}function jN({onClose:e,onSwitched:t,focusSessionId:n}){const a=Ft(),r=Cn(ie=>ie.projects),s=Cn(ie=>ie.projects.find(ze=>ze.id===ie.activeId)?.sourceSession?.sessionId),l=!!window.desktopSessions,[c,d]=j.useState(null),[h,m]=j.useState([]),[p,x]=j.useState(!1),[b,y]=j.useState(window.desktopSessions?null:"canvases"),[k,T]=j.useState(null),[w,_]=j.useState(!1),[A,C]=j.useState(null),[O,D]=j.useState(new Map),[M,N]=j.useState(new Map),[R,B]=j.useState(new Map),[U,Y]=j.useState(!1),Z=ie=>`${ie.rootKey}|${ie.rel}`,W=ie=>B(ze=>{const pe=new Map(ze),qe=Z(ie);return pe.has(qe)?pe.delete(qe):pe.set(qe,ie),pe}),K=ie=>r.find(ze=>Dx(ze).includes(ie)),[F,G]=j.useState(""),[ne,X]=j.useState(new Set),[P,q]=j.useState("time"),[J,H]=j.useState(!1),[se,ye]=j.useState(!1),[be,ke]=j.useState(new Map),[ae,Te]=j.useState(null);j.useEffect(()=>{window.desktopSessions?.openTargets().then(Te).catch(()=>{})},[]);const Oe=j.useMemo(()=>new Map((ae?.apps??[]).map(ie=>[ie.runner,ie.name])),[ae]),Le=async()=>{x(!0);try{m(await window.desktopSessions?.roots().catch(()=>[])??[]);const ie=await wne();if(d(ie),ke(Ene(ie)),window.desktopSessions?.codexThreads?.().then(ze=>{ze&&(D(new Map(ze.filter(pe=>pe.name&&pe.sessionId).map(pe=>[pe.sessionId,pe.name]))),N(new Map(ze.filter(pe=>pe.forkedFromId&&pe.sessionId).map(pe=>[pe.sessionId,pe.forkedFromId]))))}).catch(()=>{}),n){const ze=ie.find(pe=>pe.sessionId===n);ze&&y(ze.cwd??"")}}finally{x(!1)}};j.useEffect(()=>{Le()},[]),j.useEffect(()=>{let ie=!1;const ze=()=>{ie||p||(ie=!0,setTimeout(()=>{ie=!1,Le()},2e3))};return window.addEventListener("td:sessions-changed",ze),()=>window.removeEventListener("td:sessions-changed",ze)},[p]);const We=j.useCallback(ie=>O.get(ie.sessionId)??ie.title,[O]),Be=j.useMemo(()=>(c??[]).filter(ie=>!ne.has(ie.runner)&&(se||!ie.subagent)&&(!J||be.has(uc(ie)))&&(!F.trim()||We(ie).toLowerCase().includes(F.trim().toLowerCase()))),[c,ne,F,J,be,se,We]),rt=j.useMemo(()=>kne(Be),[Be]),ht=j.useMemo(()=>[...new Set((c??[]).map(ie=>ie.runner))].sort(),[c]),Xe=j.useMemo(()=>{const ie=new Map;for(const ze of c??[])ie.set(ze.rootKey,(ie.get(ze.rootKey)??0)+1);return ie},[c]),kt=b==="canvases"?null:rt.find(ie=>(ie.cwd??"")===(b??rt[0]?.cwd??""))??rt[0]??null,yt=j.useMemo(()=>{if(!kt)return[];const ie=P==="name"?(ze,pe)=>We(ze).localeCompare(We(pe)):Ane[P];return[...kt.cards].sort(ie)},[kt,P,We]),at=ie=>{Tne(ie),ke(ze=>{const pe=new Map(ze);return pe.delete(uc(ie)),pe})},Et=async ie=>{if(!k){T(ie.rel),at(ie);try{const{streamRunnerConversation:ze}=await Kt(async()=>{const{streamRunnerConversation:St}=await import("./index-CrxLUdb9.js");return{streamRunnerConversation:St}},[]),{importOrAppendConversation:pe,shellSessionReader:qe}=await Kt(async()=>{const{importOrAppendConversation:St,shellSessionReader:qt}=await import("./canonical-HRd1ZNsL.js");return{importOrAppendConversation:St,shellSessionReader:qt}},[]),ut=await ze(qe(ie.rootKey,ie.rel)),gt=await pe(ut);if(!gt)throw new Error(Ie("handoff.notASession"));gt.kind==="appended"?Ke("success",Ue(Ie("atlas.appended"),{n:gt.turns}),9e3):gt.kind==="mounted"?Ke("success",Ue(Ie(gt.mode==="continue"?"atlas.mountedChapter":"atlas.mountedBranch"),{n:gt.turns}),9e3):gt.kind==="opened"?Ke("info",Ie("atlas.upToDate"),6e3):Ke("success",Ue(Ie("toast.importedChats"),{n:1,m:gt.nodeCount}),9e3),e(),t()}catch(ze){Ke("error",Ue(Ie("atlas.parseFailed"),{msg:ze instanceof Error?ze.message:String(ze)}))}finally{T(null)}}},zt=async ie=>{if(!(k||R.size<2)){T("__merge__");try{const{streamRunnerConversation:ze}=await Kt(async()=>{const{streamRunnerConversation:St}=await import("./index-CrxLUdb9.js");return{streamRunnerConversation:St}},[]),{mergeSessionsIntoProject:pe,shellSessionReader:qe}=await Kt(async()=>{const{mergeSessionsIntoProject:St,shellSessionReader:qt}=await import("./canonical-HRd1ZNsL.js");return{mergeSessionsIntoProject:St,shellSessionReader:qt}},[]),ut=[];for(const St of R.values())ut.push(await ze(qe(St.rootKey,St.rel))),at(St);const gt=await pe(ut,ie);if(!gt)throw new Error(Ie("handoff.notASession"));Ke("success",Ue(Ie("atlas.merged"),{n:gt.mounted}),1e4),gt.skipped>0&&Ke("info",Ue(Ie("atlas.mergeSkippedInfo"),{n:gt.skipped}),8e3),B(new Map),e(),t()}catch(ze){Ke("error",Ue(Ie("atlas.parseFailed"),{msg:ze instanceof Error?ze.message:String(ze)}))}finally{T(null)}}},Ve=async ie=>{const ze=Cn.getState().projects.find(ut=>ut.sourceSession?.sessionId===ie.sessionId);if(!ze||k)return;const{confirmDialog:pe}=await Kt(async()=>{const{confirmDialog:ut}=await Promise.resolve().then(()=>hm);return{confirmDialog:ut}},void 0);if(await pe({title:Ie("confirm.recastTitle"),message:Ue(Ie("confirm.recast"),{name:ze.name}),confirmLabel:Ie("confirm.recastTitle"),danger:!0})){T(ie.rel);try{const{streamRunnerConversation:ut}=await Kt(async()=>{const{streamRunnerConversation:$t}=await import("./index-CrxLUdb9.js");return{streamRunnerConversation:$t}},[]),{importOrAppendConversation:gt,shellSessionReader:St}=await Kt(async()=>{const{importOrAppendConversation:$t,shellSessionReader:vn}=await import("./canonical-HRd1ZNsL.js");return{importOrAppendConversation:$t,shellSessionReader:vn}},[]),qt=await ut(St(ie.rootKey,ie.rel));if(!qt)throw new Error(Ie("handoff.notASession"));const{deleteProject:un}=await Kt(async()=>{const{deleteProject:$t}=await Promise.resolve().then(()=>gm);return{deleteProject:$t}},void 0);if(await un(ze.id),!await gt(qt))throw new Error(Ie("handoff.notASession"));Ke("success",Ie("atlas.recastDone"),8e3),e(),t()}catch(ut){Ke("error",Ue(Ie("atlas.parseFailed"),{msg:ut instanceof Error?ut.message:String(ut)}))}finally{T(null)}}},Bt=async(ie,ze)=>{const pe=await window.desktopSessions.openInCli(ie.runner,ie.cwd,ie.sessionId,ze).catch(()=>({opened:!1,via:"",command:""}));pe.opened&&pe.via==="app"?(await navigator.clipboard.writeText(ie.sessionId).catch(()=>{}),Ke("success",Ie("atlas.appOpened"),9e3)):pe.opened?Ke("success",Ie("atlas.opened")):pe.command&&(await navigator.clipboard.writeText(pe.command).catch(()=>{}),Ke("info",Ie("atlas.cmdCopied"),9e3))};return $a.createPortal(u.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:u.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:[u.jsxs("div",{className:"flex items-start gap-3 px-5 pt-4 pb-3 border-b border-line",children:[u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsx("div",{className:"text-base font-semibold text-ink",children:a("atlas.title")}),u.jsx("div",{className:"text-xs text-ink-muted mt-0.5",children:a("atlas.subtitle")}),be.size>0&&u.jsxs("div",{className:"text-xs mt-1 flex items-center gap-2","data-atlas-changes":!0,children:[u.jsx("span",{className:"text-accent",children:Ue(a("atlas.changesSummary"),{n:[...be.values()].filter(ie=>ie.kind==="new").length,m:[...be.values()].filter(ie=>ie.kind==="updated").length})}),u.jsx("button",{className:"text-ink-faint hover:text-ink underline decoration-dotted transition-colors",onClick:()=>{Sne(c??[]),ke(new Map)},"data-atlas-mark-all":!0,children:a("atlas.markAllSeen")})]})]}),l&&ae&&ae.terminals.length>0&&u.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:a("atlas.terminalChoice"),children:[u.jsx(Nd,{size:14,strokeWidth:1.75}),u.jsxs("select",{value:ae.prefs.terminal,onChange:ie=>{const ze=ie.target.value;if(ze==="__add__"){window.desktopSessions?.addTerminal().then(()=>window.desktopSessions?.openTargets().then(Te));return}window.desktopSessions?.setOpenPrefs({terminal:ze}).then(pe=>Te(qe=>qe&&{...qe,prefs:pe}))},className:"bg-transparent focus:outline-none text-sm text-ink cursor-pointer","data-atlas-terminal-select":!0,children:[ae.terminals.map(ie=>u.jsx("option",{value:ie.id,children:ie.name},ie.id)),ae.canAddCustom&&u.jsx("option",{value:"__add__",children:a("atlas.otherTerminal")})]})]}),l&&u.jsxs("button",{onClick:()=>_(!0),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:[u.jsx(l7,{size:14,strokeWidth:1.75})," ",a("atlas.sources")]}),l&&u.jsxs("button",{onClick:()=>{Le()},disabled:p,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:[p?u.jsx(Xn,{size:14,className:"animate-spin"}):u.jsx(ir,{size:14,strokeWidth:1.75}),a(p?"atlas.scanning":"atlas.refresh")]}),u.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:u.jsx(bn,{size:18,strokeWidth:1.75})})]}),u.jsxs("div",{className:"flex-1 flex min-h-0",children:[u.jsxs("div",{className:"w-[260px] border-r border-line overflow-y-auto py-2 shrink-0",children:[u.jsx("div",{className:"px-4 py-1 text-2xs uppercase tracking-wide text-ink-faint",children:a("atlas.recent")}),r.filter(ie=>!ie.archived).sort((ie,ze)=>ze.updatedAt-ie.updatedAt).slice(0,6).map(ie=>u.jsxs("button",{onClick:()=>{e(),Ss(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?u.jsx("span",{className:"text-2xs font-mono border border-line rounded px-1 py-px shrink-0 text-ink-faint",children:ie.sourceSession.runner}):u.jsx(Fw,{size:13,strokeWidth:1.75,className:"shrink-0 text-ink-faint"}),u.jsx("span",{className:"flex-1 truncate text-sm",children:ie.name})]},ie.id)),u.jsx("div",{className:"border-t border-line mt-2 pt-2 px-4 py-1 text-2xs uppercase tracking-wide text-ink-faint",children:a("atlas.folders")}),!l&&u.jsx("div",{className:"px-4 py-2 text-xs text-ink-faint",children:a("atlas.webNoScan")}),l&&c===null&&u.jsxs("div",{className:"px-4 py-2 text-sm text-ink-faint flex items-center gap-2",children:[u.jsx(Xn,{size:14,className:"animate-spin"})," ",a("atlas.scanning")]}),l&&c!==null&&rt.length===0&&u.jsx("div",{className:"px-4 py-2 text-xs text-ink-faint",children:a("atlas.empty")}),rt.map(ie=>{const ze=ie.cwd??"",pe=b!=="canvases"&&kt===ie;return u.jsxs("button",{onClick:()=>y(ze),className:`w-full text-left px-4 py-2 flex items-center gap-2 transition-colors ${pe?"bg-accent/5 text-accent":"text-ink hover:bg-wash"}`,"data-atlas-folder":ie.name||"unfiled",children:[pe?u.jsx(t7,{size:15,strokeWidth:1.75,className:"shrink-0"}):u.jsx(MP,{size:15,strokeWidth:1.75,className:"shrink-0 text-ink-faint"}),u.jsx("span",{className:"flex-1 truncate text-sm",children:ie.name||a("atlas.unfiled")}),(()=>{const qe=ie.cards.filter(ut=>be.has(uc(ut))).length;return qe>0?u.jsxs("span",{className:"text-2xs text-accent shrink-0","data-atlas-folder-changes":!0,children:["+",qe]}):null})(),u.jsx("span",{className:"text-2xs text-ink-faint shrink-0",children:ie.cards.length})]},ze)}),u.jsx("div",{className:"border-t border-line mt-2 pt-2",children:u.jsxs("button",{onClick:()=>y("canvases"),className:`w-full text-left px-4 py-2 flex items-center gap-2 transition-colors ${b==="canvases"?"bg-accent/5 text-accent":"text-ink hover:bg-wash"}`,"data-atlas-canvases":!0,children:[u.jsx(Fw,{size:15,strokeWidth:1.75,className:"shrink-0"}),u.jsx("span",{className:"flex-1 truncate text-sm",children:a("atlas.myCanvases")}),u.jsx("span",{className:"text-2xs text-ink-faint shrink-0",children:r.length})]})})]}),u.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:b==="canvases"?u.jsxs("div",{className:"space-y-1.5",children:[r.filter(ie=>!ie.archived).sort((ie,ze)=>ze.updatedAt-ie.updatedAt).map(ie=>u.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(),Ss(ie.id).then(t)},children:[u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsx("div",{className:"text-sm text-ink font-medium truncate",children:ie.name}),u.jsxs("div",{className:"text-2xs text-ink-faint mt-0.5 flex items-center gap-1.5",children:[u.jsx("span",{children:tx(ie.updatedAt)}),!!ie.sourceSession?.sessionId&&u.jsx("span",{className:"font-mono border border-line rounded px-1 py-px",children:ie.sourceSession.runner})]})]}),u.jsx("button",{title:a("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:ze=>{ze.stopPropagation(),Df(ie.id,!0)},"data-atlas-archive":!0,children:u.jsx(Io,{size:15,strokeWidth:1.75})}),!!ie.sourceSession&&Dx(ie).length>0&&u.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&&u.jsxs("span",{children:["◉ ",ie.sourceSession.runner," ",ie.sourceSession.sessionId.slice(0,8)," · ",Ue(a("atlas.turnsN"),{n:ie.sourceSession.importedCount})]}),(ie.sourceSession.chapters??[]).map(ze=>u.jsxs("span",{children:["↳ ",ze.runner," ",ze.sessionId.slice(0,8)," · ",Ue(a("atlas.turnsN"),{n:ze.importedCount})]},ze.sessionId)),(ie.sourceSession.branches??[]).map(ze=>u.jsxs("span",{children:["⑂ ",ze.runner," ",ze.sessionId.slice(0,8)," · ",Ue(a("atlas.turnsN"),{n:ze.importedCount})]},ze.sessionId))]})]},ie.id)),r.some(ie=>ie.archived)&&u.jsxs("details",{className:"pt-2","data-atlas-archived-group":!0,children:[u.jsx("summary",{className:"text-2xs uppercase tracking-wide text-ink-faint cursor-pointer px-1 py-1",children:Ue(a("atlas.archivedGroup"),{n:r.filter(ie=>ie.archived).length})}),u.jsx("div",{className:"space-y-1.5 mt-1.5",children:r.filter(ie=>ie.archived).sort((ie,ze)=>ze.updatedAt-ie.updatedAt).map(ie=>u.jsxs("button",{title:a("atlas.restoreOpen"),onClick:()=>{Df(ie.id,!1).then(()=>{e(),Ss(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:[u.jsxs("div",{className:"text-sm text-ink truncate flex items-center gap-1.5",children:[u.jsx("span",{className:"truncate",children:ie.name}),!!ie.sourceSession?.sessionId&&u.jsx("span",{className:"text-2xs font-mono border border-line rounded px-1 py-px shrink-0 text-ink-faint",children:ie.sourceSession.runner})]}),u.jsx("div",{className:"text-2xs text-ink-faint mt-0.5",children:tx(ie.updatedAt)})]},ie.id))})]})]}):u.jsxs(u.Fragment,{children:[(c?.length??0)>0&&u.jsxs("div",{className:"flex items-center gap-2 mb-3 flex-wrap",children:[u.jsxs("div",{className:"flex items-center gap-1.5 border border-line rounded-lg px-2 py-1 bg-card",children:[u.jsx(Cf,{size:13,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),u.jsx("input",{value:F,onChange:ie=>G(ie.target.value),placeholder:a("atlas.filterTitle"),className:"text-sm bg-transparent focus:outline-none w-[150px] text-ink placeholder:text-ink-faint","data-atlas-filter":!0})]}),ht.map(ie=>u.jsx("button",{onClick:()=>X(ze=>{const pe=new Set(ze);return pe.has(ie)?pe.delete(ie):pe.add(ie),pe}),className:`text-2xs font-mono border rounded-lg px-2 py-1 transition-colors ${ne.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)),be.size>0&&u.jsx("button",{onClick:()=>H(ie=>!ie),className:`text-2xs border rounded-lg px-2 py-1 transition-colors ${J?"border-accent text-white bg-accent":"border-line text-ink-muted hover:text-ink"}`,"data-atlas-only-changed":!0,children:a("atlas.onlyChanged")}),(c??[]).some(ie=>ie.subagent)&&u.jsx("button",{onClick:()=>ye(ie=>!ie),className:`text-2xs border rounded-lg px-2 py-1 transition-colors ${se?"border-accent text-accent bg-accent/5":"border-line text-ink-faint hover:text-ink"}`,"data-atlas-show-sub":!0,children:a("atlas.showSub")}),u.jsxs("button",{onClick:()=>q(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:[u.jsx(Cj,{size:12,strokeWidth:1.75}),a(`atlas.sort${P[0].toUpperCase()}${P.slice(1)}`)]})]}),kt?u.jsxs(u.Fragment,{children:[kt.cwd&&u.jsxs("div",{className:"text-2xs text-ink-faint mb-3 truncate",children:[kt.cwd," · ",Ue(a("atlas.sessions"),{n:kt.cards.length})]}),u.jsx("div",{className:"space-y-1.5",children:yt.map(ie=>u.jsxs("div",{className:`group border rounded-xl px-4 py-3 hover:bg-wash transition-colors cursor-pointer flex items-center gap-3 ${R.has(Z(ie))?"border-accent/60 bg-accent/5":"border-line"}`,onClick:()=>{Et(ie)},"data-atlas-session":ie.sessionId,children:[u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsxs("div",{className:"text-sm text-ink truncate flex items-center gap-1.5",children:[u.jsx("span",{className:"truncate",children:We(ie)}),M.has(ie.sessionId)&&u.jsx("span",{className:"text-2xs text-ink-faint border border-line rounded px-1 py-px shrink-0 font-mono",title:`⑂ ${M.get(ie.sessionId)}`,"data-atlas-fork":!0,children:"⑂"}),be.get(uc(ie))?.kind==="new"&&u.jsx("span",{className:"text-2xs text-white bg-accent rounded px-1 py-px shrink-0","data-atlas-badge":"new",children:a("atlas.badgeNew")}),be.get(uc(ie))?.kind==="updated"&&u.jsxs("span",{className:"text-2xs text-accent border border-accent/40 rounded px-1 py-px shrink-0","data-atlas-badge":"updated",children:["+",Vk(be.get(uc(ie)).deltaSize)]}),ie.sessionId===s?u.jsx("span",{className:"text-2xs text-white bg-ink rounded px-1 py-px shrink-0","data-atlas-badge":"current",children:a("atlas.currentOpen")}):(()=>{const ze=K(ie.sessionId);return ze?u.jsx("span",{className:"text-2xs text-ink-faint border border-line rounded px-1 py-px shrink-0",title:ze.name,"data-atlas-badge":"canvas",children:a("atlas.onCanvas")}):null})()]}),u.jsxs("div",{className:"text-2xs text-ink-faint mt-0.5 flex items-center gap-2",children:[u.jsx("span",{className:"border border-line rounded px-1 py-px font-mono",children:ie.runner}),u.jsx("span",{children:tx(ie.mtime)}),u.jsx("span",{children:Vk(ie.size)})]})]}),k===ie.rel?u.jsx(Xn,{size:16,className:"animate-spin text-accent shrink-0"}):u.jsxs("div",{className:`${R.has(Z(ie))?"":"opacity-0 group-hover:opacity-100"} transition-opacity flex items-center gap-1 shrink-0`,children:[!K(ie.sessionId)&&!!ie.sessionId&&u.jsx("button",{title:a("atlas.pickForMerge"),className:`p-1.5 rounded transition-colors ${R.has(Z(ie))?"text-accent":"text-ink-faint hover:text-accent"}`,onClick:ze=>{ze.stopPropagation(),W(ie)},"data-atlas-pick":R.has(Z(ie))?"on":"off",children:R.has(Z(ie))?u.jsx(Lz,{size:16,strokeWidth:1.75}):u.jsx(Ib,{size:16,strokeWidth:1.75})}),u.jsx("span",{title:a("atlas.import"),className:"text-ink-faint hover:text-accent p-1.5",children:u.jsx(qP,{size:16,strokeWidth:1.75})}),r.some(ze=>ze.sourceSession?.sessionId===ie.sessionId)&&u.jsx("button",{title:a("atlas.recast"),className:"text-ink-faint hover:text-red-500 p-1.5 rounded transition-colors",onClick:ze=>{ze.stopPropagation(),Ve(ie)},"data-atlas-recast":!0,children:u.jsx(wz,{size:16,strokeWidth:1.75})}),!K(ie.sessionId)&&u.jsx("button",{title:a("atlas.mountTo"),className:"text-ink-faint hover:text-accent p-1.5 rounded transition-colors",onClick:ze=>{ze.stopPropagation(),C(ie)},"data-atlas-mount":!0,children:u.jsx(Ao,{size:16,strokeWidth:1.75})}),Oe.has(ie.runner)&&u.jsx("button",{title:Ue(a("atlas.openApp"),{name:Oe.get(ie.runner)}),className:"text-ink-faint hover:text-accent p-1.5 rounded transition-colors",onClick:ze=>{ze.stopPropagation(),Bt(ie,"app")},"data-atlas-open-app":!0,children:u.jsx(Tj,{size:16,strokeWidth:1.75})}),u.jsx("button",{title:a("atlas.openTerminal"),className:"text-ink-faint hover:text-accent p-1.5 rounded transition-colors",onClick:ze=>{ze.stopPropagation(),Bt(ie,"terminal")},"data-atlas-open-cli":!0,children:u.jsx(Nd,{size:16,strokeWidth:1.75})})]})]},ie.rel))})]}):u.jsx("div",{className:"py-16 text-center text-sm text-ink-faint",children:c===null?a("atlas.scanning"):c.length>0?a("atlas.filteredOut"):a("atlas.empty")})]})})]}),R.size>=2&&!U&&u.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:[u.jsx("span",{className:"text-xs text-ink-muted whitespace-nowrap",children:Ue(a("atlas.mergeSelected"),{n:R.size})}),k==="__merge__"?u.jsx(Xn,{size:15,className:"animate-spin text-accent"}):u.jsxs(u.Fragment,{children:[u.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:()=>{zt()},"data-atlas-merge-new":!0,children:a("atlas.mergeNew")}),u.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:()=>Y(!0),"data-atlas-merge-into":!0,children:a("atlas.mergeInto")})]}),u.jsx("button",{className:"text-ink-faint hover:text-ink p-1",onClick:()=>B(new Map),title:a("common.cancel"),children:u.jsx(bn,{size:14,strokeWidth:1.75})})]}),(A||U)&&u.jsx("div",{className:"absolute inset-0 z-10 bg-ink/20 flex items-center justify-center",onClick:()=>{C(null),Y(!1)},children:u.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:[u.jsxs("div",{className:"px-4 pt-3.5 pb-2.5 border-b border-line",children:[u.jsx("div",{className:"text-sm font-semibold text-ink",children:a(U?"atlas.mergeInto":"atlas.mountTo")}),u.jsx("div",{className:"text-2xs text-ink-muted mt-0.5",children:a(U?"atlas.mergeSelected":"atlas.mountHint").replace("{n}",String(R.size))})]}),r.filter(ie=>!ie.archived&&ie.kind!=="paradigm").sort((ie,ze)=>ze.updatedAt-ie.updatedAt).map(ie=>u.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(U){Y(!1),zt(ie.id);return}const ze=A;C(null),(async()=>{T(ze.rel);try{const{streamRunnerConversation:pe}=await Kt(async()=>{const{streamRunnerConversation:qt}=await import("./index-CrxLUdb9.js");return{streamRunnerConversation:qt}},[]),{mountConversationToProject:qe,shellSessionReader:ut}=await Kt(async()=>{const{mountConversationToProject:qt,shellSessionReader:un}=await import("./canonical-HRd1ZNsL.js");return{mountConversationToProject:qt,shellSessionReader:un}},[]),gt=await pe(ut(ze.rootKey,ze.rel)),St=await qe(gt,ie.id);if(!St)throw new Error(Ie("handoff.notASession"));Ke("success",Ue(Ie("atlas.mountedChapter"),{n:St.kind==="mounted"||St.kind==="appended"?St.turns:0}),9e3),e(),t()}catch(pe){Ke("error",Ue(Ie("atlas.parseFailed"),{msg:pe instanceof Error?pe.message:String(pe)}))}finally{T(null)}})()},children:ie.name},ie.id))]})}),w&&u.jsx(Nne,{roots:h,counts:Xe,onChanged:()=>{Le()},onClose:()=>_(!1)})]})}),document.body)}function Cne({conversations:e,onClose:t,onDone:n}){const a=Ft(),[r,s]=j.useState(new Set),[l,c]=j.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||l||(c(!0),await lU([...r].sort((p,x)=>p-x).map(p=>e[p])),c(!1),n())};return u.jsx("div",{className:"fixed inset-0 z-50 bg-ink/30 backdrop-blur-sm flex items-center justify-center p-6",onClick:t,children:u.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:[u.jsxs("div",{className:"px-6 py-4 border-b border-line flex items-start justify-between gap-4",children:[u.jsxs("div",{children:[u.jsx("h2",{className:"text-base font-semibold text-ink",children:a("import.title")}),u.jsx("p",{className:"text-xs text-ink-muted mt-1 leading-relaxed",children:a("import.subtitle")})]}),u.jsx("button",{onClick:t,className:"text-ink-faint hover:text-ink transition-colors shrink-0 mt-0.5",children:u.jsx(bn,{size:16,strokeWidth:1.75})})]}),u.jsx("div",{className:"px-6 py-2 border-b border-line/60",children:u.jsxs("label",{className:"flex items-center gap-2 text-xs text-ink-muted cursor-pointer select-none py-1",children:[u.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"),u.jsx("span",{className:"ml-auto text-2xs text-ink-faint uppercase tracking-wider",children:e[0]?.source})]})}),u.jsx("ul",{className:"flex-1 overflow-y-auto py-1",children:e.map((p,x)=>u.jsx("li",{children:u.jsxs("label",{className:"flex items-center gap-3 px-6 py-2 hover:bg-wash transition-colors cursor-pointer select-none",children:[u.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"}),u.jsx(o7,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),u.jsx("span",{className:"text-sm text-ink truncate flex-1",children:p.title}),u.jsx("span",{className:"text-2xs text-ink-faint shrink-0",children:Ue(a("import.messages"),{n:p.messageCount})})]})},x))}),u.jsxs("div",{className:"px-6 py-4 border-t border-line flex justify-end gap-2",children:[u.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")}),u.jsx("button",{onClick:()=>{m()},disabled:r.size===0||l,className:"text-xs bg-accent hover:bg-accent-strong text-white px-5 py-2 rounded-lg transition-colors disabled:opacity-30",children:l?"…":Ue(a("import.confirm"),{n:r.size})})]})]})})}function _ne(e){const t=Date.now()-e,n=Math.floor(t/6e4);if(n<1)return Ie("switcher.justNow");if(n<60)return Ue(Ie("switcher.minAgo"),{n});const a=Math.floor(n/60);if(a<24)return Ue(Ie("switcher.hourAgo"),{n:a});const r=Math.floor(a/24);return r<30?Ue(Ie("switcher.dayAgo"),{n:r}):new Date(e).toLocaleDateString(Da.getState().lang==="zh"?"zh-CN":"en-US")}function Mne({onSwitched:e}){const t=Ft(),n=Cn(N=>N.projects),a=Cn(N=>N.activeId),r=Cn(N=>N.switching),s=n.find(N=>N.id===a)?.kind==="paradigm",[l,c]=j.useState(!1),[d,h]=j.useState(null),[m,p]=j.useState(!1),[x,b]=j.useState(void 0),[y,k]=j.useState(null),[T,w]=j.useState(""),_=j.useRef(null),A=j.useRef(null),C=n.find(N=>N.id===a),O=n.filter(N=>!N.archived).sort((N,R)=>R.updatedAt-N.updatedAt).slice(0,7),D=async N=>{const{canvasUniqueness:R}=await Kt(async()=>{const{canvasUniqueness:Z}=await import("./canonical-HRd1ZNsL.js");return{canvasUniqueness:Z}},[]),B=await R(N.id),U=B==="native"?"confirm.deleteNative":B==="diverged-mirror"?"confirm.deleteDiverged":"confirm.deletePristine";await Ts({title:Ie("confirm.deleteCanvasTitle"),message:Ue(Ie(U),{name:N.name}),confirmLabel:Ie("common.delete"),danger:B!=="pristine-mirror"})&&$7(N.id).then(e)};j.useEffect(()=>{if(!l)return;const N=R=>{A.current?.contains(R.target)||c(!1)};return window.addEventListener("mousedown",N),()=>window.removeEventListener("mousedown",N)},[l]);const M=async N=>{c(!1),await Ss(N),e(),Kt(()=>import("./canonical-HRd1ZNsL.js"),[]).then(R=>R.unsubscribeOrphanedSessions()),Kt(()=>import("./live-mirror-DrVBjNxd.js"),[]).then(R=>R.sweepRecentSessions())};return u.jsxs("div",{ref:A,className:"absolute top-4 left-4 z-20",children:[u.jsxs("div",{className:"flex items-center gap-1.5",children:[u.jsxs("button",{onClick:()=>c(!l),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?u.jsx(Xn,{size:16,strokeWidth:1.75,className:"animate-spin shrink-0 text-accent"}):s?u.jsx(hP,{size:16,strokeWidth:1.75,className:"shrink-0 text-accent"}):u.jsx(t7,{size:16,strokeWidth:1.75,className:"shrink-0 text-ink-muted"}),u.jsx("span",{className:"truncate font-medium",children:C?.name??"…"}),u.jsx($d,{size:14,strokeWidth:1.75,className:"shrink-0 text-ink-faint"})]}),!!C?.sourceSession?.sessionId&&(()=>{const N=$f.size>0&&!$f.has(C.sourceSession.sessionId);return u.jsxs("button",{title:N?Ie("switcher.mirrorBadgeGone"):Ue(Ie("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 ${N?"text-ink-faint/50 line-through decoration-1":"text-ink-faint hover:text-accent"}`,"data-twin-badge":N?"unreachable":"live",children:["⇄ ",C.sourceSession.runner]})})()]}),l&&u.jsxs("div",{className:"mt-1.5 bg-card border border-line rounded-xl shadow-lg py-1.5 w-[320px] animate-fade-in",children:[u.jsx("div",{className:"max-h-[320px] overflow-y-auto",children:O.map(N=>u.jsx("div",{className:`group flex items-center gap-1 px-3 py-2 hover:bg-wash cursor-pointer transition-colors ${N.id===a?"bg-accent/5":""}`,onClick:()=>{y!==N.id&&N.id!==a&&M(N.id)},children:y===N.id?u.jsx("input",{autoFocus:!0,value:T,onChange:R=>w(R.target.value),onClick:R=>R.stopPropagation(),onKeyDown:R=>{R.key==="Enter"&&!Ya(R)&&T.trim()&&(Y7(N.id,T.trim()),k(null)),R.key==="Escape"&&k(null)},onBlur:()=>k(null),className:"flex-1 text-sm text-ink border border-accent/40 rounded-lg px-2 py-1 bg-surface focus:outline-none"}):u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsx("div",{className:`text-sm truncate ${N.id===a?"text-accent font-medium":"text-ink"}`,children:N.name}),u.jsxs("div",{className:"text-2xs text-ink-faint flex items-center gap-1.5",children:[u.jsx("span",{children:_ne(N.updatedAt)}),!!N.sourceSession?.sessionId&&u.jsx("span",{className:"font-mono border border-line rounded px-1 py-px","data-mirror-mark":!0,children:N.sourceSession.runner})]})]}),u.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:R=>{R.stopPropagation(),k(N.id),w(N.name)},children:u.jsx(Rc,{size:14,strokeWidth:1.75})}),u.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:R=>{R.stopPropagation(),D(N)},children:u.jsx(Fa,{size:14,strokeWidth:1.75})}),u.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:R=>{R.stopPropagation(),Df(N.id,!0).then(e)},"data-archive-canvas":!0,children:u.jsx(Io,{size:14,strokeWidth:1.75})})]})},N.id))}),u.jsxs("div",{className:"border-t border-line mt-1 pt-1",children:[u.jsxs("button",{onClick:()=>{c(!1),pm().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:[u.jsx(um,{size:15,strokeWidth:1.75})," ",t("switcher.newCanvas")]}),u.jsxs("button",{onClick:()=>_.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:[u.jsx(Yz,{size:15,strokeWidth:1.75})," ",t("switcher.importBackup")]}),u.jsxs("button",{onClick:()=>{c(!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:[u.jsx(nz,{size:15,strokeWidth:1.75})," ",t("switcher.allCanvases")]}),window.desktop&&u.jsxs("button",{onClick:()=>{c(!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:[u.jsx(ir,{size:15,strokeWidth:1.75})," ",t("update.checkMenu"),u.jsxs("span",{className:"ml-auto text-2xs text-ink-faint",children:["v",new URLSearchParams(window.location.search).get("dv")]})]}),u.jsx("input",{ref:_,type:"file",accept:".json,.jsonl,application/json",className:"hidden",onChange:N=>{const R=N.target.files?.[0];R&&sU(R).then(B=>{B.kind==="own"&&B.ok?(c(!1),e()):B.kind==="chat"&&(c(!1),h(B.conversations))}).catch(B=>{Ke("error",Ue(Ie("toast.importFailedGeneric"),{msg:B instanceof Error?B.message:String(B)}))}),N.target.value=""}})]})]}),d&&u.jsx(Cne,{conversations:d,onClose:()=>h(null),onDone:()=>{h(null),e()}}),m&&u.jsx(jN,{onClose:()=>{p(!1),b(void 0)},onSwitched:e,focusSessionId:x})]})}const Ine="JVBERi0xLjQKMSAwIG9iago8PCAvVHlwZSAvQ2F0YWxvZyAvUGFnZXMgMiAwIFIgPj4KZW5kb2JqCjIgMCBvYmoKPDwgL1R5cGUgL1BhZ2VzIC9LaWRzIFszIDAgUiA0IDAgUl0gL0NvdW50IDIgPj4KZW5kb2JqCjMgMCBvYmoKPDwgL1R5cGUgL1BhZ2UgL1BhcmVudCAyIDAgUiAvTWVkaWFCb3ggWzAgMCA1OTUgODQyXSAvQ29udGVudHMgNSAwIFIgL1Jlc291cmNlcyA8PCAvRm9udCA8PCAvRjEgNyAwIFIgL0YyIDggMCBSID4+ID4+ID4+CmVuZG9iago0IDAgb2JqCjw8IC9UeXBlIC9QYWdlIC9QYXJlbnQgMiAwIFIgL01lZGlhQm94IFswIDAgNTk1IDg0Ml0gL0NvbnRlbnRzIDYgMCBSIC9SZXNvdXJjZXMgPDwgL0ZvbnQgPDwgL0YxIDcgMCBSIC9GMiA4IDAgUiA+PiA+PiA+PgplbmRvYmoKNSAwIG9iago8PCAvTGVuZ3RoIDExMTIgPj4Kc3RyZWFtCkJUCi9GMiAxOSBUZiAxIDAgMCAxIDY0IDcyNS4wIFRtIChXaHkgU2F2ZWQgQXJ0aWNsZXMgU3RheSBVbnJlYWQpIFRqCi9GMSAxMSBUZiAxIDAgMCAxIDY0IDcwOC4wIFRtIChBIHNob3J0IGJyaWVmIG9uIGRpZ2l0YWwgaG9hcmRpbmcgYW5kIHRoZSBjb2xsZWN0b3IncyBmYWxsYWN5KSBUagovRjIgMTMgVGYgMSAwIDAgMSA2NCA2NjkuMCBUbSAoMS4gVGhlIHBoZW5vbWVub24pIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNjUxLjUgVG0gKFJlYWQtaXQtbGF0ZXIgc2VydmljZXMgcmVwb3J0IHRoYXQgbW9zdCBzYXZlZCBpdGVtcyBhcmUgbmV2ZXIpIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNjM0LjAgVG0gKHJlb3BlbmVkLiBBY3Jvc3MgcHVibGlzaGVkIHVzYWdlIHN0dWRpZXMsIHRoZSBzaGFyZSBvZiBzYXZlZCkgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA2MTYuNSBUbSAoYXJ0aWNsZXMgdGhhdCBnZXQgYSBzZWNvbmQgdmlzaXQgaXMgc21hbGwsIGFuZCBjb21wbGV0aW9uIHJhdGVzKSBUagovRjEgMTEuNSBUZiAxIDAgMCAxIDY0IDU5OS4wIFRtIChhcmUgc21hbGxlciBzdGlsbC4gVGhlIGFyY2hpdmUgZ3Jvd3M7IHRoZSByZWFkaW5nIGRvZXMgbm90LikgVGoKL0YyIDEzIFRmIDEgMCAwIDEgNjQgNTYwLjAgVG0gKDIuIFRoZSBjb2xsZWN0b3IncyBmYWxsYWN5KSBUagovRjEgMTEuNSBUZiAxIDAgMCAxIDY0IDU0Mi41IFRtIChDb2xsZWN0aW5nIHByb2R1Y2VzIGFuIGltbWVkaWF0ZSBzZW5zZSBvZiBwcm9ncmVzcyB3aGlsZSB0aGUpIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNTI1LjAgVG0gKHVuZGVyc3RhbmRpbmcgaXQgcHJvbWlzZXMgaXMgZGVmZXJyZWQuIFNhdmluZyBhIHRleHQgZmVlbHMgbGlrZSkgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA1MDcuNSBUbSAoYSBmaXJzdCBzdGVwIG9mIHJlYWRpbmcgaXQsIGJ1dCBubyBwYXJ0IG9mIHRoZSByZWFkaW5nIGhhcykgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA0OTAuMCBUbSAoaGFwcGVuZWQuKSBUagovRjIgMTEuNSBUZiAxIDAgMCAxIDY0IDQ3Mi41IFRtIChUaGUgYWN0IG9mIHNhdmluZyBpcyBtaXN0YWtlbiBmb3IgdGhlIGFjdCBvZiBsZWFybmluZy4pIFRqCkVUCmVuZHN0cmVhbQplbmRvYmoKNiAwIG9iago8PCAvTGVuZ3RoIDkwOCA+PgpzdHJlYW0KQlQKL0YyIDEzIFRmIDEgMCAwIDEgNjQgNzI1LjAgVG0gKDMuIFdoeSBpdCBwZXJzaXN0cykgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA3MDcuNSBUbSAoVGhlIGNvc3RzIGFyZSBhc3ltbWV0cmljOiBzYXZpbmcgdGFrZXMgb25lIHNlY29uZCBhbmQgcGF5cyBvdXQpIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNjkwLjAgVG0gKGEgc21hbGwgcmV3YXJkIG5vdzsgcmVhZGluZyB0YWtlcyBhbiBob3VyIGFuZCBwYXlzIG91dCBsYXRlci4pIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNjcyLjUgVG0gKEhhYml0cyBmb2xsb3cgdGhlIGNoZWFwZXIgbG9vcCwgc28gbGlicmFyaWVzIGluZmxhdGUgYnkgZGVmYXVsdC4pIFRqCi9GMiAxMyBUZiAxIDAgMCAxIDY0IDYzMy41IFRtICg0LiBXaGF0IGhlbHBzKSBUagovRjEgMTEuNSBUZiAxIDAgMCAxIDY0IDYxNi4wIFRtIChJbnRlcnZlbnRpb25zIHRoYXQgd29yayBtb3ZlIHByb2Nlc3NpbmcgdG8gdGhlIG1vbWVudCBvZiBjYXB0dXJlOikgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA1OTguNSBUbSAod3JpdGUgb25lIGxpbmUgaW4geW91ciBvd24gd29yZHMgYWJvdXQgd2h5IHRoZSBpdGVtIG1hdHRlcnMsIGFuZCkgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA1ODEuMCBUbSAoc2NoZWR1bGUgYSByZXZpZXcgcGFzcyBpbnN0ZWFkIG9mIHRydXN0aW5nIHRoZSBhcmNoaXZlIHRvKSBUagovRjEgMTEuNSBUZiAxIDAgMCAxIDY0IDU2My41IFRtIChyZXN1cmZhY2UgaXQuKSBUagovRjEgMTEuNSBUZiAxIDAgMCAxIDY0IDUzMi4wIFRtIChBIHNtYWxsZXIgbGlicmFyeSB0aGF0IGdldHMgcHJvY2Vzc2VkIGJlYXRzIGEgY29tcGxldGUgb25lIHRoYXQpIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNTE0LjUgVG0gKGRvZXMgbm90LikgVGoKRVQKZW5kc3RyZWFtCmVuZG9iago3IDAgb2JqCjw8IC9UeXBlIC9Gb250IC9TdWJ0eXBlIC9UeXBlMSAvQmFzZUZvbnQgL0hlbHZldGljYSA+PgplbmRvYmoKOCAwIG9iago8PCAvVHlwZSAvRm9udCAvU3VidHlwZSAvVHlwZTEgL0Jhc2VGb250IC9IZWx2ZXRpY2EtQm9sZCA+PgplbmRvYmoKeHJlZgowIDkKMDAwMDAwMDAwMCA2NTUzNSBmIAowMDAwMDAwMDA5IDAwMDAwIG4gCjAwMDAwMDAwNTggMDAwMDAgbiAKMDAwMDAwMDEyMSAwMDAwMCBuIAowMDAwMDAwMjU3IDAwMDAwIG4gCjAwMDAwMDAzOTMgMDAwMDAgbiAKMDAwMDAwMTU1NyAwMDAwMCBuIAowMDAwMDAyNTE2IDAwMDAwIG4gCjAwMDAwMDI1ODYgMDAwMDAgbiAKdHJhaWxlcgo8PCAvU2l6ZSA5IC9Sb290IDEgMCBSID4+CnN0YXJ0eHJlZgoyNjYxCiUlRU9G",Dne=`<!-- tdag-page:1 -->
523
523
 
524
524
  # Why Saved Articles Stay Unread
525
525
 
@@ -753,11 +753,11 @@ ${n==="zh"?"**高光(原文保真)**":"**Highlights (verbatim)**"}
753
753
  ${A.map(N=>`> ${N.text}`).join(`
754
754
  `)}`:"",O=In();x.push(O);const D=`${n==="zh"?"凝练":"Condensed"}: ${w.data.question.replace(/\s+/g," ").slice(0,60)} → ${_.data.question.replace(/\s+/g," ").slice(0,60)}`,M=`${t[T]||""}${C}`;p.push({id:O,type:"thought",position:{x:w.position.x+h,y:w.position.y},dragHandle:".drag-handle",data:{question:D,response:M,responses:[M],responseIndex:0,condensedFrom:k.nodeIds,createdAt:new Date().toISOString(),isCollapsed:!1,isEditing:!1,isEditingResponse:!1,isLoading:!1,tokenCount:$n(`${D}
755
755
  ${M}`),highlights:[],highlightMode:"tag",attachments:[],excludedAttachmentIds:[],includedAttachmentIds:[],roleMode:"inherit",isRoot:!1,isBranch:!1}}),k.nodeIds.forEach(N=>m.set(N,O))});for(const k of r){if(c.has(k.id))continue;const T=In();m.set(k.id,T);const w=k.data;p.push({...k,id:T,position:{x:k.position.x+h,y:k.position.y},selected:!1,data:{...w,isEditing:!1,isEditingResponse:!1,isLoading:!1}})}const b=[],y=new Set;for(const k of s){const T=m.get(k.source),w=m.get(k.target);if(!T||!w||T===w)continue;const _=`${T}→${w}`;y.has(_)||(y.add(_),b.push({...k,id:`e-${In()}`,source:T,target:w,selected:!1}))}return a.pushHistory(),oe.setState(k=>{const T=[...k.nodes,...p],w=[...k.edges,...b];return{nodes:nr(T,w),edges:w}}),{copiedNodes:p.length,collapsedRuns:e.length,distillIds:x}}let rl=0;function vae(){rl++,xe.getState().setCondenseRun({status:"idle",current:0,total:0,streaming:""})}async function wae(e,t,n){if(e.length===0)return;const a=++rl,r=xe.getState(),s=oe.getState().nodes.map(l=>l.id);r.setCondenseRun({status:"building",current:0,total:e.length,streaming:"",error:void 0,originalIds:s,distillIds:[]});try{const l=[];let c="";for(let h=0;h<e.length;h++){if(rl!==a)return;xe.getState().setCondenseRun({current:h+1,streaming:""});const m=await xae(e[h],t,n,p=>{rl===a&&xe.getState().setCondenseRun({streaming:p})},c||void 0);if(rl!==a)return;l.push(m),c=`${c}
756
- ${m}`.slice(-1500)}const d=yae(e,l,t);if(rl!==a)return;xe.getState().setCondenseRun({status:"done",streaming:"",distillIds:d.distillIds}),Ke("success",Ie("condense.copyReady"),8e3,{label:Ie("tmap.export"),run:()=>xe.getState().setThoughtMapOpen(!0)})}catch(l){if(rl!==a)return;xe.getState().setCondenseRun({status:"error",error:l instanceof Error?l.message:String(l)})}}function kae({onFocusSegment:e}){const t=xe(U=>U.condenseDialogOpen),n=xe(U=>U.condenseRun),a=Ft(),r=Da(U=>U.lang),s=oe(U=>U.nodes),l=oe(U=>U.edges),[c,d]=j.useState(0),h=j.useMemo(()=>t&&n.status==="idle"?pae(s,l):[],[t,n.status,s,l,c]),m=xe(U=>U.selectedModel),p=El()?.models??[],[x,b]=j.useState(""),[y,k]=j.useState(new Set),[T,w]=j.useState(null),_=j.useRef(null),A=U=>{const Y=_.current?.getBoundingClientRect();if(!Y)return;const Z=U.clientX-Y.left,W=U.clientY-Y.top,K=G=>w({x:Math.min(window.innerWidth-120,Math.max(0,G.clientX-Z)),y:Math.min(window.innerHeight-80,Math.max(0,G.clientY-W))}),F=()=>{window.removeEventListener("mousemove",K),window.removeEventListener("mouseup",F)};window.addEventListener("mousemove",K),window.addEventListener("mouseup",F)},C=U=>U.nodeIds.join(","),O=h.filter(U=>!y.has(C(U))),D=O.reduce((U,Y)=>U+Y.saving,0),M=()=>{xe.getState().setCondenseDialogOpen(!1),xe.getState().setCondenseHighlightIds([])};if(j.useEffect(()=>{if(!t)return;const U=Y=>{Y.key==="Escape"&&M()};return window.addEventListener("keydown",U),()=>window.removeEventListener("keydown",U)},[t]),!t)return null;const N=()=>{O.length!==0&&wae(O,r,x||m||void 0)},R=()=>{oe.getState().setArchived(n.originalIds,!0),Ke("success",a("condense.originalArchived")),xe.getState().setCondenseRun({status:"idle",current:0,total:0,streaming:"",originalIds:[],distillIds:[]}),M()},B=()=>{const Y=oe.getState().nodes.filter(Z=>n.distillIds.includes(Z.id));Y.length&&e?.(Y.map(Z=>Z.id))};return $a.createPortal(u.jsxs("div",{ref:_,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:T?{left:T.x,top:T.y}:{left:80,bottom:16},"data-condense-dialog":!0,onClick:U=>U.stopPropagation(),children:[u.jsxs("div",{className:"flex items-start justify-between mb-1 cursor-grab active:cursor-grabbing select-none",onMouseDown:A,children:[u.jsxs("div",{className:"text-sm font-semibold text-ink flex items-center gap-2",children:[u.jsx(cm,{size:15,strokeWidth:1.75,className:"text-accent"})," ",a("condense.title")]}),u.jsx("button",{onClick:M,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:u.jsx(bn,{size:15})})]}),n.status==="idle"&&u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"flex items-center justify-between gap-2 mb-2",children:[u.jsx("p",{className:"text-2xs text-ink-faint leading-snug",title:a("condense.copyIntroFull"),children:a("condense.copyIntroShort")}),u.jsxs("button",{onClick:()=>d(U=>U+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")]})]}),u.jsx("p",{className:"text-2xs text-ink-faint mb-2","data-condense-scanline":!0,children:Ue(a("condense.scanLine"),{turns:String(s.filter(U=>U.data.response&&!U.data.stepKind).length),n:String(h.length)})}),u.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[u.jsx("label",{className:"text-2xs text-ink-muted shrink-0",children:a("condense.modelLabel")}),u.jsxs("select",{value:x,onChange:U=>b(U.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:[u.jsx("option",{value:"",children:Ue(a("condense.modelGlobal"),{model:m||"auto"})}),p.map(U=>u.jsx("option",{value:U.id,children:U.id},U.id))]})]}),h.length===0?u.jsx("p",{className:"text-xs text-ink-muted py-4",children:a("condense.segNothing")}):u.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto space-y-2 pr-1",children:h.map(U=>{const Y=C(U),Z=!y.has(Y);return u.jsxs("div",{"data-condense-item":!0,className:`border rounded-xl p-3 transition-colors cursor-pointer ${Z?"border-accent/60 bg-accent/5":"border-line opacity-60"}`,onClick:()=>{xe.getState().setCondenseHighlightIds(U.nodeIds),e?.(U.nodeIds)},children:[u.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[u.jsx("input",{type:"checkbox",checked:Z,onClick:W=>W.stopPropagation(),onChange:()=>k(W=>{const K=new Set(W);return K.has(Y)?K.delete(Y):K.add(Y),K}),className:"accent-[var(--color-accent)]","data-condense-check":!0}),u.jsx("span",{className:"text-2xs text-ink-faint font-mono",children:Ue(a("condense.segMeta"),{n:String(U.nodeIds.length),tok:String(U.saving)})})]}),u.jsx("p",{className:"text-xs text-ink mt-1 leading-snug line-clamp-2",children:U.headQuestion})]},Y)})}),h.length>0&&u.jsxs("div",{className:"flex items-center justify-between gap-2 pt-3 mt-2 border-t border-line",children:[u.jsx("span",{className:"text-2xs text-ink-faint",children:a("condense.copyFootnote")}),u.jsxs("button",{onClick:N,disabled:O.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:[u.jsx(Ls,{size:13,strokeWidth:1.75}),Ue(a("condense.buildCopy"),{n:String(O.length),tok:String(D)})]})]})]}),n.status==="building"&&u.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",children:[u.jsxs("div",{className:"flex items-center gap-2 text-sm text-ink-muted mb-1.5",children:[u.jsx(Xn,{size:15,className:"animate-spin text-accent"}),Ue(a("condense.buildingRun"),{i:String(n.current),n:String(n.total)})]}),u.jsx("p",{className:"text-2xs text-ink-faint mb-2",children:a("condense.runningBg")}),n.streaming&&u.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}),u.jsx("button",{onClick:()=>vae(),"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"&&u.jsxs("div",{className:"flex flex-col gap-2 py-3",children:[u.jsx("p",{className:"text-2xs text-red-600",children:n.error}),u.jsx("button",{onClick:()=>xe.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"&&u.jsxs("div",{className:"flex flex-col gap-3 py-3",children:[u.jsxs("div",{className:"flex items-center gap-2 text-sm text-green-700",children:[u.jsx(xl,{size:16})," ",a("condense.copyReady")]}),u.jsx("p",{className:"text-2xs text-ink-faint leading-relaxed",children:a("condense.copyCompareHint")}),u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx("button",{onClick:B,className:"text-xs bg-accent/10 text-accent hover:bg-accent/20 px-3 py-2 rounded-lg transition-colors",children:a("condense.viewCopy")}),u.jsxs("button",{onClick:R,"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:[u.jsx(Io,{size:13,strokeWidth:1.75})," ",a("condense.archiveOriginal")]})]}),u.jsx("button",{onClick:()=>{xe.getState().setCondenseRun({status:"idle"}),M()},className:"self-start text-xs text-ink-faint hover:text-ink transition-colors",children:a("common.close")})]})]}),document.body)}function aE(){const e=Da(n=>n.lang),t=Da(n=>n.setLang);return u.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=>u.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 da({x:e,y:t,w:n=34,h:a=20,tone:r="plain"}){return u.jsxs("g",{children:[u.jsx("rect",{x:e,y:t,width:n,height:a,rx:4,fill:"white",stroke:nt.line,strokeWidth:1}),r!=="plain"&&u.jsx("rect",{x:e,y:t,width:2.5,height:a,rx:1.25,fill:r==="accent"?nt.accent:nt.warm})]})}const Eae={1:u.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[u.jsx(da,{x:43,y:32,tone:"accent"}),u.jsx("circle",{cx:60,cy:28,r:2.5,fill:nt.accent})]}),2:u.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[u.jsx(da,{x:43,y:12,tone:"accent"}),u.jsx("line",{x1:60,y1:32,x2:60,y2:50,stroke:nt.accent,strokeWidth:1.75}),u.jsx("path",{d:"M 57 47 L 60 52 L 63 47 Z",fill:nt.accent}),u.jsx(da,{x:43,y:52})]}),3:u.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[u.jsx(da,{x:20,y:12,tone:"accent"}),u.jsx("line",{x1:37,y1:32,x2:37,y2:50,stroke:nt.accent,strokeWidth:1.75}),u.jsx("path",{d:"M 34 47 L 37 52 L 40 47 Z",fill:nt.accent}),u.jsx(da,{x:20,y:52}),u.jsx("rect",{x:26,y:58,width:14,height:3,rx:1.5,fill:nt.trace,opacity:.6}),u.jsx("path",{d:"M 54 62 C 64 62, 62 40, 72 38",stroke:nt.warm,strokeWidth:1.75,fill:"none",strokeDasharray:"4 3"}),u.jsx("path",{d:"M 69 35.5 L 74 38 L 70 41 Z",fill:nt.warm}),u.jsx(da,{x:74,y:28,tone:"warm"})]}),4:u.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[u.jsx(da,{x:43,y:10,tone:"accent"}),u.jsx("line",{x1:60,y1:30,x2:60,y2:52,stroke:nt.line,strokeWidth:1.75,strokeDasharray:"3 3"}),u.jsx("circle",{cx:60,cy:41,r:7,fill:"white",stroke:"#FCA5A5",strokeWidth:1}),u.jsx("line",{x1:57,y1:38,x2:63,y2:44,stroke:"#EF4444",strokeWidth:1.5,strokeLinecap:"round"}),u.jsx("line",{x1:63,y1:38,x2:57,y2:44,stroke:"#EF4444",strokeWidth:1.5,strokeLinecap:"round"}),u.jsx(da,{x:43,y:54})]}),5:u.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[u.jsx(da,{x:12,y:14,w:40,h:15}),u.jsx("circle",{cx:14,cy:16,r:4.5,fill:"#D64533"}),u.jsx("text",{x:14,y:18.4,textAnchor:"middle",fontSize:6,fontWeight:700,fill:"white",children:"✕"}),u.jsx(da,{x:12,y:35,w:40,h:15}),u.jsx("circle",{cx:14,cy:37,r:4.5,fill:nt.accent}),u.jsx("text",{x:14,y:39.4,textAnchor:"middle",fontSize:6,fontWeight:700,fill:"white",children:"⚖"}),u.jsx(da,{x:12,y:56,w:40,h:15}),u.jsx("circle",{cx:14,cy:58,r:4.5,fill:"#C9A227"}),u.jsx("text",{x:14,y:60.4,textAnchor:"middle",fontSize:6,fontWeight:700,fill:"white",children:"?"}),u.jsx("path",{d:"M 62 42 L 74 42",stroke:nt.inkMuted,strokeWidth:1.2}),u.jsx("path",{d:"M 71.5 39.5 L 76 42 L 71.5 44.5 Z",fill:nt.inkMuted}),u.jsx("rect",{x:86,y:14,width:13,height:13,rx:4.5,fill:"#D64533"}),u.jsx("line",{x1:92.5,y1:27,x2:92.5,y2:35,stroke:nt.accent,strokeWidth:1.4}),u.jsx("rect",{x:86,y:35,width:13,height:13,rx:4.5,fill:nt.accent}),u.jsx("line",{x1:92.5,y1:48,x2:92.5,y2:56,stroke:nt.accent,strokeWidth:1.4}),u.jsx("rect",{x:86,y:56,width:13,height:13,rx:4.5,fill:"#C9A227"})]}),7:u.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[u.jsx("rect",{x:14,y:12,width:30,height:22,rx:3,fill:"#FEF3C7",stroke:"#F59E0B",strokeWidth:.8}),u.jsx("line",{x1:29,y1:34,x2:29,y2:50,stroke:nt.accent,strokeWidth:1.75}),u.jsx("path",{d:"M 26 47 L 29 52 L 32 47 Z",fill:nt.accent}),u.jsx(da,{x:12,y:52,tone:"accent"}),u.jsx("path",{d:"M 100 22 C 80 22, 70 55, 50 60",stroke:nt.accent,strokeWidth:1.75,fill:"none",strokeDasharray:"5 3"}),u.jsx("path",{d:"M 52 57 L 47 61 L 52 64 Z",fill:nt.accent}),u.jsx(da,{x:82,y:12})]}),9:u.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[u.jsx(da,{x:43,y:10,tone:"accent"}),u.jsx("line",{x1:60,y1:30,x2:60,y2:48,stroke:nt.accent,strokeWidth:1.75}),u.jsx("path",{d:"M 57 45 L 60 50 L 63 45 Z",fill:nt.accent}),u.jsx(da,{x:43,y:50}),u.jsx("circle",{cx:75,cy:53,r:4,fill:"#F59E0B"}),u.jsx("path",{d:"M 73.5 53 a 1.5 1.5 0 1 1 3 0",stroke:"white",strokeWidth:.9,fill:"none"}),u.jsx("text",{x:60,y:80,textAnchor:"middle",fontSize:7,fill:nt.inkMuted,fontFamily:"JetBrains Mono Variable, monospace",children:"v2/2 · replay"})]}),6:u.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[u.jsx("rect",{x:8,y:18,width:14,height:48,rx:4,fill:"white",stroke:nt.line,strokeWidth:1}),u.jsx("circle",{cx:15,cy:27,r:3,fill:nt.accent,opacity:.7}),u.jsx("rect",{x:12,y:37,width:6,height:6,rx:1,fill:"#F59E0B",opacity:.8}),u.jsx("rect",{x:12,y:49,width:6,height:6,rx:1,fill:nt.inkMuted,opacity:.5}),u.jsx("rect",{x:38,y:14,width:32,height:24,rx:3,fill:"#FEF3C7",stroke:"#F59E0B",strokeWidth:.8}),u.jsx("rect",{x:80,y:14,width:32,height:24,rx:3,fill:"white",stroke:nt.line,strokeWidth:1}),u.jsx("circle",{cx:88,cy:22,r:3,fill:nt.line}),u.jsx("path",{d:"M 82 34 L 92 26 L 100 32 L 108 24",stroke:nt.inkMuted,strokeWidth:1.2,fill:"none"}),u.jsx("text",{x:72,y:62,textAnchor:"middle",fontSize:7,fill:nt.inkMuted,fontFamily:"JetBrains Mono Variable, monospace",children:"⌘V paste anything"})]}),8:u.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[u.jsx("rect",{x:8,y:8,width:70,height:52,rx:3,fill:nt.accent,opacity:.06,stroke:nt.accent,strokeWidth:.8,strokeDasharray:"3 2"}),u.jsx(da,{x:14,y:14,w:26,h:16}),u.jsx(da,{x:46,y:14,w:26,h:16}),u.jsx(da,{x:30,y:38,w:26,h:16}),u.jsx("path",{d:"M 40 46 C 60 50, 70 50, 84 48",stroke:nt.accent,strokeWidth:1.4,fill:"none"}),u.jsx("path",{d:"M 59 30 C 70 36, 76 42, 84 46",stroke:nt.accent,strokeWidth:1.4,fill:"none"}),u.jsx("path",{d:"M 43 22 C 66 24, 76 38, 84 44",stroke:nt.accent,strokeWidth:1.4,fill:"none"}),u.jsx(da,{x:84,y:40,w:28,h:18,tone:"accent"})]}),10:u.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[u.jsx(da,{x:10,y:18,w:30,h:17,tone:"accent"}),u.jsx("line",{x1:25,y1:35,x2:25,y2:48,stroke:nt.accent,strokeWidth:1.5}),u.jsx("path",{d:"M 22.5 45.5 L 25 50 L 27.5 45.5 Z",fill:nt.accent}),u.jsx(da,{x:10,y:50,w:30,h:17}),u.jsx("path",{d:"M 46 42 L 60 42",stroke:nt.inkMuted,strokeWidth:1.2}),u.jsx("path",{d:"M 57.5 39.5 L 62 42 L 57.5 44.5 Z",fill:nt.inkMuted}),u.jsx("rect",{x:68,y:20,width:44,height:44,rx:5,fill:"white",stroke:nt.line,strokeWidth:1}),u.jsx(da,{x:74,y:30,w:20,h:11,tone:"accent"}),u.jsx(da,{x:88,y:46,w:20,h:11}),u.jsx("rect",{x:76,y:14,width:28,height:11,rx:5.5,fill:"#2B2A28"}),u.jsx("circle",{cx:84,cy:19.5,r:2.6,fill:"none",stroke:"white",strokeWidth:1}),u.jsx("circle",{cx:84,cy:19.5,r:.9,fill:"white"}),u.jsx("text",{x:90,y:22,fontSize:6,fill:"white",fontFamily:"JetBrains Mono Variable, monospace",children:"view"}),u.jsx("text",{x:60,y:78,textAnchor:"middle",fontSize:7,fill:nt.inkMuted,fontFamily:"JetBrains Mono Variable, monospace",children:"#view= · read-only"})]})},rE={4:"prune",5:"map",6:"reading",7:"ref"};function Tae(){const e=xe(h=>h.tutorialOpen),t=xe(h=>h.setTutorialOpen);j.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=Ft(),a=Da(h=>h.lang),[r,s]=j.useState(0),l=[{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]}],c=r===l.length-1;if(j.useEffect(()=>{if(!e)return;s(0);const h=m=>{m.key==="ArrowRight"&&s(p=>Math.min(p+1,l.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=l[r];return u.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:u.jsxs("div",{className:"bg-card border border-line rounded-2xl shadow-2xl w-[min(980px,94vw)] flex flex-col",onClick:h=>h.stopPropagation(),children:[u.jsxs("div",{className:"flex items-start justify-between px-7 pt-5 pb-1 shrink-0",children:[u.jsxs("div",{className:"flex items-baseline gap-3 min-w-0",children:[u.jsx("h2",{className:"text-lg font-semibold text-ink tracking-tight shrink-0",children:n("tutorial.title")}),u.jsx("p",{className:"text-xs text-ink-faint truncate",children:n("tutorial.subtitle")})]}),u.jsx("button",{onClick:()=>t(!1),className:"text-ink-faint hover:text-ink transition-colors mt-1",children:u.jsx(bn,{size:18,strokeWidth:1.75})})]}),u.jsxs("div",{className:"px-7 pt-3 pb-1 min-h-[380px]",children:[u.jsx("p",{className:"text-2xs font-semibold text-accent mb-3 uppercase tracking-wider",children:d.label}),u.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=>u.jsxs("div",{className:"bg-surface border border-line/70 rounded-xl p-4 flex flex-col animate-fade-in",children:[u.jsx("div",{className:"w-full aspect-[120/72] bg-card rounded-lg border border-line/60 mb-3 overflow-hidden",children:rE[h]?u.jsx("img",{src:`/tutorial/${rE[h]}-${a}.gif`,loading:"lazy",alt:"",className:"w-full h-full object-cover"}):Eae[h]}),u.jsx("h3",{className:"text-[13px] font-semibold text-ink leading-snug",children:n(`tutorial.step${h}.title`)}),u.jsx("p",{className:"text-xs text-ink-muted leading-relaxed mt-1.5",children:n(`tutorial.step${h}.desc`)})]},h))})]}),u.jsxs("div",{className:"px-7 py-4 shrink-0 flex items-center justify-between",children:[u.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:u.jsx(Af,{size:16,strokeWidth:1.75})}),u.jsx("div",{className:"flex items-center gap-2",children:l.map((h,m)=>u.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}/${l.length}`},m))}),c?u.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")}):u.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:u.jsx(Es,{size:16,strokeWidth:1.75})})]}),u.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:[u.jsxs("span",{children:[n("shortcut.panKeys")," ",n("shortcut.pan")]}),u.jsxs("span",{children:[n("shortcut.marqueeKeys")," ",n("shortcut.marquee")]}),u.jsxs("span",{children:["⌘","F ",n("shortcut.search")]}),u.jsxs("span",{children:["Space ",n("shortcut.collapse")]}),u.jsxs("span",{children:["R ",n("shortcut.regenerate")]}),u.jsxs("span",{children:["↑↓←→"," ",n("shortcut.navigate")]}),u.jsxs("span",{children:["⌘","Z/","⇧","⌘","Z ",n("shortcut.undo")]}),u.jsxs("span",{children:["Del ",n("shortcut.delete")]}),u.jsxs("span",{children:["Esc ",n("shortcut.escape")]})]})]})})}const Sae=new URLSearchParams(window.location.search),Oi=Sae.get("dv"),Jh="https://chenxiachan.github.io/thoughtdag/docs",VN=[{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:`${Jh}/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:`${Jh}/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:`${Jh}/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:`${Jh}/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 iE(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 ox(e,t){return VN.filter(n=>n.announce&&iE(n.version,t)<=0&&(e===null||iE(n.version,e)>0))}const ub="thoughtdag.whatsNewSeen",Aae=new URLSearchParams(window.location.search);function Nae(){if(!Oi)return[];if(Aae.get("wn")==="1")return ox(null,Oi);let t=null;try{t=localStorage.getItem(ub)}catch{}if(t===null){let n=!1;try{n=!!(localStorage.getItem("thoughtdag.tutorialDone")||localStorage.getItem("thoughtdag.lastBackupAt"))}catch{}if(!n){try{localStorage.setItem(ub,Oi)}catch{}return[]}return ox(null,Oi)}return t===Oi?[]:ox(t,Oi)}function GN({items:e,lang:t}){return e.length===0?null:u.jsx("ol",{className:"divide-y divide-line",children:e.map((n,a)=>u.jsxs("li",{className:"py-3 flex gap-3.5",children:[u.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}),u.jsxs("div",{className:"min-w-0",children:[u.jsx("div",{className:"text-sm font-medium text-ink",children:n.title[t]}),u.jsx("p",{className:"text-sm text-ink-muted leading-relaxed mt-1 [overflow-wrap:anywhere]",children:n.body[t]}),n.link&&u.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 Cae(){const[e,t]=j.useState(()=>Nae()),n=e.length>0,a=Da(c=>c.lang),r=Ft(),s=j.useRef(null),l=()=>{if(Oi)try{localStorage.setItem(ub,Oi)}catch{}t([])};return j.useEffect(()=>{if(!n)return;s.current?.focus({preventScroll:!0});const c=d=>{d.stopPropagation(),(d.key==="Escape"||d.key==="Enter")&&l()};return window.addEventListener("keydown",c,!0),()=>window.removeEventListener("keydown",c,!0)},[n]),n?u.jsx("div",{className:"fixed inset-0 z-[100] bg-black/25 flex items-center justify-center animate-fade-in p-6",onClick:l,children:u.jsxs("div",{className:"bg-card border border-line rounded-2xl shadow-xl w-[680px] max-w-full max-h-[85vh] overflow-y-auto",onClick:c=>c.stopPropagation(),role:"dialog","aria-labelledby":"whats-new-title","data-whats-new":!0,children:[u.jsxs("div",{className:"px-6 pt-5 pb-4 border-b border-line",children:[u.jsx("div",{className:"text-2xs uppercase tracking-wide text-ink-faint",children:"ThoughtDAG"}),u.jsx("h2",{id:"whats-new-title",className:"text-base font-semibold text-ink mt-0.5",children:Ue(r("whatsNew.title"),{v:Oi??""})}),e.length>1&&u.jsx("p",{className:"text-xs text-ink-faint mt-1",children:r("whatsNew.multi")})]}),u.jsx("ol",{className:"px-6 divide-y divide-line",children:e.map(c=>u.jsxs("li",{className:"py-4","data-release":c.version,children:[e.length>1&&u.jsxs("div",{className:"flex items-baseline gap-2.5 mb-1.5",children:[u.jsxs("span",{className:"text-sm font-semibold text-ink tabular-nums",children:["v",c.version]}),u.jsx("span",{className:"text-xs text-ink-faint tabular-nums",children:c.date})]}),u.jsx("p",{className:"text-sm text-ink-muted leading-relaxed [overflow-wrap:anywhere]",children:c.lead[a]}),u.jsx(GN,{items:c.items,lang:a})]},c.version))}),u.jsxs("div",{className:"sticky bottom-0 bg-card px-6 py-4 border-t border-line flex items-center justify-between gap-4",children:[u.jsx("button",{onClick:()=>{l(),xe.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")}),u.jsx("button",{ref:s,onClick:l,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 _ae(){const e=xe(r=>r.releaseNotesOpen),t=xe(r=>r.setReleaseNotesOpen),n=Da(r=>r.lang),a=Ft();return j.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?u.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:u.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:[u.jsxs("div",{className:"px-6 pt-5 pb-4 border-b border-line",children:[u.jsx("div",{className:"text-2xs uppercase tracking-wide text-ink-faint",children:"ThoughtDAG"}),u.jsx("h2",{id:"release-notes-title",className:"text-base font-semibold text-ink mt-0.5",children:a("releaseNotes.title")})]}),u.jsx("ol",{className:"px-6 divide-y divide-line",children:VN.map(r=>{const s=Oi===r.version;return u.jsxs("li",{className:"py-4","data-release":r.version,children:[u.jsxs("div",{className:"flex items-baseline gap-2.5 flex-wrap",children:[u.jsxs("span",{className:"text-sm font-semibold text-ink tabular-nums",children:["v",r.version]}),u.jsx("span",{className:"text-xs text-ink-faint tabular-nums",children:r.date}),s&&u.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")})]}),u.jsx("p",{className:"text-sm text-ink-muted leading-relaxed mt-1.5 [overflow-wrap:anywhere]",children:r.lead[n]}),u.jsx(GN,{items:r.items,lang:n})]},r.version)})}),u.jsx("div",{className:"sticky bottom-0 bg-card px-6 py-4 border-t border-line flex justify-end",children:u.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 Mae={ruleout:"#ef4444",decision:"#6B5CE7",pivot:"#e8890c",open:"#d97706",insight:"#0284c7"},sE=e=>{if(e){for(let t=e.length-1;t>=0;t--)if(e[t])return e[t]}};function Iae(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(`
756
+ ${m}`.slice(-1500)}const d=yae(e,l,t);if(rl!==a)return;xe.getState().setCondenseRun({status:"done",streaming:"",distillIds:d.distillIds}),Ke("success",Ie("condense.copyReady"),8e3,{label:Ie("tmap.export"),run:()=>xe.getState().setThoughtMapOpen(!0)})}catch(l){if(rl!==a)return;xe.getState().setCondenseRun({status:"error",error:l instanceof Error?l.message:String(l)})}}function kae({onFocusSegment:e}){const t=xe(U=>U.condenseDialogOpen),n=xe(U=>U.condenseRun),a=Ft(),r=Da(U=>U.lang),s=oe(U=>U.nodes),l=oe(U=>U.edges),[c,d]=j.useState(0),h=j.useMemo(()=>t&&n.status==="idle"?pae(s,l):[],[t,n.status,s,l,c]),m=xe(U=>U.selectedModel),p=El()?.models??[],[x,b]=j.useState(""),[y,k]=j.useState(new Set),[T,w]=j.useState(null),_=j.useRef(null),A=U=>{const Y=_.current?.getBoundingClientRect();if(!Y)return;const Z=U.clientX-Y.left,W=U.clientY-Y.top,K=G=>w({x:Math.min(window.innerWidth-120,Math.max(0,G.clientX-Z)),y:Math.min(window.innerHeight-80,Math.max(0,G.clientY-W))}),F=()=>{window.removeEventListener("mousemove",K),window.removeEventListener("mouseup",F)};window.addEventListener("mousemove",K),window.addEventListener("mouseup",F)},C=U=>U.nodeIds.join(","),O=h.filter(U=>!y.has(C(U))),D=O.reduce((U,Y)=>U+Y.saving,0),M=()=>{xe.getState().setCondenseDialogOpen(!1),xe.getState().setCondenseHighlightIds([])};if(j.useEffect(()=>{if(!t)return;const U=Y=>{Y.key==="Escape"&&M()};return window.addEventListener("keydown",U),()=>window.removeEventListener("keydown",U)},[t]),!t)return null;const N=()=>{O.length!==0&&wae(O,r,x||m||void 0)},R=()=>{oe.getState().setArchived(n.originalIds,!0),Ke("success",a("condense.originalArchived")),xe.getState().setCondenseRun({status:"idle",current:0,total:0,streaming:"",originalIds:[],distillIds:[]}),M()},B=()=>{const Y=oe.getState().nodes.filter(Z=>n.distillIds.includes(Z.id));Y.length&&e?.(Y.map(Z=>Z.id))};return $a.createPortal(u.jsxs("div",{ref:_,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:T?{left:T.x,top:T.y}:{left:80,bottom:16},"data-condense-dialog":!0,onClick:U=>U.stopPropagation(),children:[u.jsxs("div",{className:"flex items-start justify-between mb-1 cursor-grab active:cursor-grabbing select-none",onMouseDown:A,children:[u.jsxs("div",{className:"text-sm font-semibold text-ink flex items-center gap-2",children:[u.jsx(cm,{size:15,strokeWidth:1.75,className:"text-accent"})," ",a("condense.title")]}),u.jsx("button",{onClick:M,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:u.jsx(bn,{size:15})})]}),n.status==="idle"&&u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"flex items-center justify-between gap-2 mb-2",children:[u.jsx("p",{className:"text-2xs text-ink-faint leading-snug",title:a("condense.copyIntroFull"),children:a("condense.copyIntroShort")}),u.jsxs("button",{onClick:()=>d(U=>U+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")]})]}),u.jsx("p",{className:"text-2xs text-ink-faint mb-2","data-condense-scanline":!0,children:Ue(a("condense.scanLine"),{turns:String(s.filter(U=>U.data.response&&!U.data.stepKind).length),n:String(h.length)})}),u.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[u.jsx("label",{className:"text-2xs text-ink-muted shrink-0",children:a("condense.modelLabel")}),u.jsxs("select",{value:x,onChange:U=>b(U.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:[u.jsx("option",{value:"",children:Ue(a("condense.modelGlobal"),{model:m||"auto"})}),p.map(U=>u.jsx("option",{value:U.id,children:U.id},U.id))]})]}),h.length===0?u.jsx("p",{className:"text-xs text-ink-muted py-4",children:a("condense.segNothing")}):u.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto space-y-2 pr-1",children:h.map(U=>{const Y=C(U),Z=!y.has(Y);return u.jsxs("div",{"data-condense-item":!0,className:`border rounded-xl p-3 transition-colors cursor-pointer ${Z?"border-accent/60 bg-accent/5":"border-line opacity-60"}`,onClick:()=>{xe.getState().setCondenseHighlightIds(U.nodeIds),e?.(U.nodeIds)},children:[u.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[u.jsx("input",{type:"checkbox",checked:Z,onClick:W=>W.stopPropagation(),onChange:()=>k(W=>{const K=new Set(W);return K.has(Y)?K.delete(Y):K.add(Y),K}),className:"accent-[var(--color-accent)]","data-condense-check":!0}),u.jsx("span",{className:"text-2xs text-ink-faint font-mono",children:Ue(a("condense.segMeta"),{n:String(U.nodeIds.length),tok:String(U.saving)})})]}),u.jsx("p",{className:"text-xs text-ink mt-1 leading-snug line-clamp-2",children:U.headQuestion})]},Y)})}),h.length>0&&u.jsxs("div",{className:"flex items-center justify-between gap-2 pt-3 mt-2 border-t border-line",children:[u.jsx("span",{className:"text-2xs text-ink-faint",children:a("condense.copyFootnote")}),u.jsxs("button",{onClick:N,disabled:O.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:[u.jsx(Ls,{size:13,strokeWidth:1.75}),Ue(a("condense.buildCopy"),{n:String(O.length),tok:String(D)})]})]})]}),n.status==="building"&&u.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",children:[u.jsxs("div",{className:"flex items-center gap-2 text-sm text-ink-muted mb-1.5",children:[u.jsx(Xn,{size:15,className:"animate-spin text-accent"}),Ue(a("condense.buildingRun"),{i:String(n.current),n:String(n.total)})]}),u.jsx("p",{className:"text-2xs text-ink-faint mb-2",children:a("condense.runningBg")}),n.streaming&&u.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}),u.jsx("button",{onClick:()=>vae(),"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"&&u.jsxs("div",{className:"flex flex-col gap-2 py-3",children:[u.jsx("p",{className:"text-2xs text-red-600",children:n.error}),u.jsx("button",{onClick:()=>xe.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"&&u.jsxs("div",{className:"flex flex-col gap-3 py-3",children:[u.jsxs("div",{className:"flex items-center gap-2 text-sm text-green-700",children:[u.jsx(xl,{size:16})," ",a("condense.copyReady")]}),u.jsx("p",{className:"text-2xs text-ink-faint leading-relaxed",children:a("condense.copyCompareHint")}),u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx("button",{onClick:B,className:"text-xs bg-accent/10 text-accent hover:bg-accent/20 px-3 py-2 rounded-lg transition-colors",children:a("condense.viewCopy")}),u.jsxs("button",{onClick:R,"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:[u.jsx(Io,{size:13,strokeWidth:1.75})," ",a("condense.archiveOriginal")]})]}),u.jsx("button",{onClick:()=>{xe.getState().setCondenseRun({status:"idle"}),M()},className:"self-start text-xs text-ink-faint hover:text-ink transition-colors",children:a("common.close")})]})]}),document.body)}function aE(){const e=Da(n=>n.lang),t=Da(n=>n.setLang);return u.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=>u.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 da({x:e,y:t,w:n=34,h:a=20,tone:r="plain"}){return u.jsxs("g",{children:[u.jsx("rect",{x:e,y:t,width:n,height:a,rx:4,fill:"white",stroke:nt.line,strokeWidth:1}),r!=="plain"&&u.jsx("rect",{x:e,y:t,width:2.5,height:a,rx:1.25,fill:r==="accent"?nt.accent:nt.warm})]})}const Eae={1:u.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[u.jsx(da,{x:43,y:32,tone:"accent"}),u.jsx("circle",{cx:60,cy:28,r:2.5,fill:nt.accent})]}),2:u.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[u.jsx(da,{x:43,y:12,tone:"accent"}),u.jsx("line",{x1:60,y1:32,x2:60,y2:50,stroke:nt.accent,strokeWidth:1.75}),u.jsx("path",{d:"M 57 47 L 60 52 L 63 47 Z",fill:nt.accent}),u.jsx(da,{x:43,y:52})]}),3:u.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[u.jsx(da,{x:20,y:12,tone:"accent"}),u.jsx("line",{x1:37,y1:32,x2:37,y2:50,stroke:nt.accent,strokeWidth:1.75}),u.jsx("path",{d:"M 34 47 L 37 52 L 40 47 Z",fill:nt.accent}),u.jsx(da,{x:20,y:52}),u.jsx("rect",{x:26,y:58,width:14,height:3,rx:1.5,fill:nt.trace,opacity:.6}),u.jsx("path",{d:"M 54 62 C 64 62, 62 40, 72 38",stroke:nt.warm,strokeWidth:1.75,fill:"none",strokeDasharray:"4 3"}),u.jsx("path",{d:"M 69 35.5 L 74 38 L 70 41 Z",fill:nt.warm}),u.jsx(da,{x:74,y:28,tone:"warm"})]}),4:u.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[u.jsx(da,{x:43,y:10,tone:"accent"}),u.jsx("line",{x1:60,y1:30,x2:60,y2:52,stroke:nt.line,strokeWidth:1.75,strokeDasharray:"3 3"}),u.jsx("circle",{cx:60,cy:41,r:7,fill:"white",stroke:"#FCA5A5",strokeWidth:1}),u.jsx("line",{x1:57,y1:38,x2:63,y2:44,stroke:"#EF4444",strokeWidth:1.5,strokeLinecap:"round"}),u.jsx("line",{x1:63,y1:38,x2:57,y2:44,stroke:"#EF4444",strokeWidth:1.5,strokeLinecap:"round"}),u.jsx(da,{x:43,y:54})]}),5:u.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[u.jsx(da,{x:12,y:14,w:40,h:15}),u.jsx("circle",{cx:14,cy:16,r:4.5,fill:"#D64533"}),u.jsx("text",{x:14,y:18.4,textAnchor:"middle",fontSize:6,fontWeight:700,fill:"white",children:"✕"}),u.jsx(da,{x:12,y:35,w:40,h:15}),u.jsx("circle",{cx:14,cy:37,r:4.5,fill:nt.accent}),u.jsx("text",{x:14,y:39.4,textAnchor:"middle",fontSize:6,fontWeight:700,fill:"white",children:"⚖"}),u.jsx(da,{x:12,y:56,w:40,h:15}),u.jsx("circle",{cx:14,cy:58,r:4.5,fill:"#C9A227"}),u.jsx("text",{x:14,y:60.4,textAnchor:"middle",fontSize:6,fontWeight:700,fill:"white",children:"?"}),u.jsx("path",{d:"M 62 42 L 74 42",stroke:nt.inkMuted,strokeWidth:1.2}),u.jsx("path",{d:"M 71.5 39.5 L 76 42 L 71.5 44.5 Z",fill:nt.inkMuted}),u.jsx("rect",{x:86,y:14,width:13,height:13,rx:4.5,fill:"#D64533"}),u.jsx("line",{x1:92.5,y1:27,x2:92.5,y2:35,stroke:nt.accent,strokeWidth:1.4}),u.jsx("rect",{x:86,y:35,width:13,height:13,rx:4.5,fill:nt.accent}),u.jsx("line",{x1:92.5,y1:48,x2:92.5,y2:56,stroke:nt.accent,strokeWidth:1.4}),u.jsx("rect",{x:86,y:56,width:13,height:13,rx:4.5,fill:"#C9A227"})]}),7:u.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[u.jsx("rect",{x:14,y:12,width:30,height:22,rx:3,fill:"#FEF3C7",stroke:"#F59E0B",strokeWidth:.8}),u.jsx("line",{x1:29,y1:34,x2:29,y2:50,stroke:nt.accent,strokeWidth:1.75}),u.jsx("path",{d:"M 26 47 L 29 52 L 32 47 Z",fill:nt.accent}),u.jsx(da,{x:12,y:52,tone:"accent"}),u.jsx("path",{d:"M 100 22 C 80 22, 70 55, 50 60",stroke:nt.accent,strokeWidth:1.75,fill:"none",strokeDasharray:"5 3"}),u.jsx("path",{d:"M 52 57 L 47 61 L 52 64 Z",fill:nt.accent}),u.jsx(da,{x:82,y:12})]}),9:u.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[u.jsx(da,{x:43,y:10,tone:"accent"}),u.jsx("line",{x1:60,y1:30,x2:60,y2:48,stroke:nt.accent,strokeWidth:1.75}),u.jsx("path",{d:"M 57 45 L 60 50 L 63 45 Z",fill:nt.accent}),u.jsx(da,{x:43,y:50}),u.jsx("circle",{cx:75,cy:53,r:4,fill:"#F59E0B"}),u.jsx("path",{d:"M 73.5 53 a 1.5 1.5 0 1 1 3 0",stroke:"white",strokeWidth:.9,fill:"none"}),u.jsx("text",{x:60,y:80,textAnchor:"middle",fontSize:7,fill:nt.inkMuted,fontFamily:"JetBrains Mono Variable, monospace",children:"v2/2 · replay"})]}),6:u.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[u.jsx("rect",{x:8,y:18,width:14,height:48,rx:4,fill:"white",stroke:nt.line,strokeWidth:1}),u.jsx("circle",{cx:15,cy:27,r:3,fill:nt.accent,opacity:.7}),u.jsx("rect",{x:12,y:37,width:6,height:6,rx:1,fill:"#F59E0B",opacity:.8}),u.jsx("rect",{x:12,y:49,width:6,height:6,rx:1,fill:nt.inkMuted,opacity:.5}),u.jsx("rect",{x:38,y:14,width:32,height:24,rx:3,fill:"#FEF3C7",stroke:"#F59E0B",strokeWidth:.8}),u.jsx("rect",{x:80,y:14,width:32,height:24,rx:3,fill:"white",stroke:nt.line,strokeWidth:1}),u.jsx("circle",{cx:88,cy:22,r:3,fill:nt.line}),u.jsx("path",{d:"M 82 34 L 92 26 L 100 32 L 108 24",stroke:nt.inkMuted,strokeWidth:1.2,fill:"none"}),u.jsx("text",{x:72,y:62,textAnchor:"middle",fontSize:7,fill:nt.inkMuted,fontFamily:"JetBrains Mono Variable, monospace",children:"⌘V paste anything"})]}),8:u.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[u.jsx("rect",{x:8,y:8,width:70,height:52,rx:3,fill:nt.accent,opacity:.06,stroke:nt.accent,strokeWidth:.8,strokeDasharray:"3 2"}),u.jsx(da,{x:14,y:14,w:26,h:16}),u.jsx(da,{x:46,y:14,w:26,h:16}),u.jsx(da,{x:30,y:38,w:26,h:16}),u.jsx("path",{d:"M 40 46 C 60 50, 70 50, 84 48",stroke:nt.accent,strokeWidth:1.4,fill:"none"}),u.jsx("path",{d:"M 59 30 C 70 36, 76 42, 84 46",stroke:nt.accent,strokeWidth:1.4,fill:"none"}),u.jsx("path",{d:"M 43 22 C 66 24, 76 38, 84 44",stroke:nt.accent,strokeWidth:1.4,fill:"none"}),u.jsx(da,{x:84,y:40,w:28,h:18,tone:"accent"})]}),10:u.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[u.jsx(da,{x:10,y:18,w:30,h:17,tone:"accent"}),u.jsx("line",{x1:25,y1:35,x2:25,y2:48,stroke:nt.accent,strokeWidth:1.5}),u.jsx("path",{d:"M 22.5 45.5 L 25 50 L 27.5 45.5 Z",fill:nt.accent}),u.jsx(da,{x:10,y:50,w:30,h:17}),u.jsx("path",{d:"M 46 42 L 60 42",stroke:nt.inkMuted,strokeWidth:1.2}),u.jsx("path",{d:"M 57.5 39.5 L 62 42 L 57.5 44.5 Z",fill:nt.inkMuted}),u.jsx("rect",{x:68,y:20,width:44,height:44,rx:5,fill:"white",stroke:nt.line,strokeWidth:1}),u.jsx(da,{x:74,y:30,w:20,h:11,tone:"accent"}),u.jsx(da,{x:88,y:46,w:20,h:11}),u.jsx("rect",{x:76,y:14,width:28,height:11,rx:5.5,fill:"#2B2A28"}),u.jsx("circle",{cx:84,cy:19.5,r:2.6,fill:"none",stroke:"white",strokeWidth:1}),u.jsx("circle",{cx:84,cy:19.5,r:.9,fill:"white"}),u.jsx("text",{x:90,y:22,fontSize:6,fill:"white",fontFamily:"JetBrains Mono Variable, monospace",children:"view"}),u.jsx("text",{x:60,y:78,textAnchor:"middle",fontSize:7,fill:nt.inkMuted,fontFamily:"JetBrains Mono Variable, monospace",children:"#view= · read-only"})]})},rE={4:"prune",5:"map",6:"reading",7:"ref"};function Tae(){const e=xe(h=>h.tutorialOpen),t=xe(h=>h.setTutorialOpen);j.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=Ft(),a=Da(h=>h.lang),[r,s]=j.useState(0),l=[{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]}],c=r===l.length-1;if(j.useEffect(()=>{if(!e)return;s(0);const h=m=>{m.key==="ArrowRight"&&s(p=>Math.min(p+1,l.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=l[r];return u.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:u.jsxs("div",{className:"bg-card border border-line rounded-2xl shadow-2xl w-[min(980px,94vw)] flex flex-col",onClick:h=>h.stopPropagation(),children:[u.jsxs("div",{className:"flex items-start justify-between px-7 pt-5 pb-1 shrink-0",children:[u.jsxs("div",{className:"flex items-baseline gap-3 min-w-0",children:[u.jsx("h2",{className:"text-lg font-semibold text-ink tracking-tight shrink-0",children:n("tutorial.title")}),u.jsx("p",{className:"text-xs text-ink-faint truncate",children:n("tutorial.subtitle")})]}),u.jsx("button",{onClick:()=>t(!1),className:"text-ink-faint hover:text-ink transition-colors mt-1",children:u.jsx(bn,{size:18,strokeWidth:1.75})})]}),u.jsxs("div",{className:"px-7 pt-3 pb-1 min-h-[380px]",children:[u.jsx("p",{className:"text-2xs font-semibold text-accent mb-3 uppercase tracking-wider",children:d.label}),u.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=>u.jsxs("div",{className:"bg-surface border border-line/70 rounded-xl p-4 flex flex-col animate-fade-in",children:[u.jsx("div",{className:"w-full aspect-[120/72] bg-card rounded-lg border border-line/60 mb-3 overflow-hidden",children:rE[h]?u.jsx("img",{src:`/tutorial/${rE[h]}-${a}.gif`,loading:"lazy",alt:"",className:"w-full h-full object-cover"}):Eae[h]}),u.jsx("h3",{className:"text-[13px] font-semibold text-ink leading-snug",children:n(`tutorial.step${h}.title`)}),u.jsx("p",{className:"text-xs text-ink-muted leading-relaxed mt-1.5",children:n(`tutorial.step${h}.desc`)})]},h))})]}),u.jsxs("div",{className:"px-7 py-4 shrink-0 flex items-center justify-between",children:[u.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:u.jsx(Af,{size:16,strokeWidth:1.75})}),u.jsx("div",{className:"flex items-center gap-2",children:l.map((h,m)=>u.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}/${l.length}`},m))}),c?u.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")}):u.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:u.jsx(Es,{size:16,strokeWidth:1.75})})]}),u.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:[u.jsxs("span",{children:[n("shortcut.panKeys")," ",n("shortcut.pan")]}),u.jsxs("span",{children:[n("shortcut.marqueeKeys")," ",n("shortcut.marquee")]}),u.jsxs("span",{children:["⌘","F ",n("shortcut.search")]}),u.jsxs("span",{children:["Space ",n("shortcut.collapse")]}),u.jsxs("span",{children:["R ",n("shortcut.regenerate")]}),u.jsxs("span",{children:["↑↓←→"," ",n("shortcut.navigate")]}),u.jsxs("span",{children:["⌘","Z/","⇧","⌘","Z ",n("shortcut.undo")]}),u.jsxs("span",{children:["Del ",n("shortcut.delete")]}),u.jsxs("span",{children:["Esc ",n("shortcut.escape")]})]})]})})}const Sae=new URLSearchParams(window.location.search),Oi=Sae.get("dv"),Jh="https://chenxiachan.github.io/thoughtdag/docs",VN=[{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:`${Jh}/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:`${Jh}/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:`${Jh}/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:`${Jh}/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 iE(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 ox(e,t){return VN.filter(n=>n.announce&&iE(n.version,t)<=0&&(e===null||iE(n.version,e)>0))}const ub="thoughtdag.whatsNewSeen",Aae=new URLSearchParams(window.location.search);function Nae(){if(!Oi)return[];if(Aae.get("wn")==="1")return ox(null,Oi);let t=null;try{t=localStorage.getItem(ub)}catch{}if(t===null){let n=!1;try{n=!!(localStorage.getItem("thoughtdag.tutorialDone")||localStorage.getItem("thoughtdag.lastBackupAt"))}catch{}if(!n){try{localStorage.setItem(ub,Oi)}catch{}return[]}return ox(null,Oi)}return t===Oi?[]:ox(t,Oi)}function GN({items:e,lang:t}){return e.length===0?null:u.jsx("ol",{className:"divide-y divide-line",children:e.map((n,a)=>u.jsxs("li",{className:"py-3 flex gap-3.5",children:[u.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}),u.jsxs("div",{className:"min-w-0",children:[u.jsx("div",{className:"text-sm font-medium text-ink",children:n.title[t]}),u.jsx("p",{className:"text-sm text-ink-muted leading-relaxed mt-1 [overflow-wrap:anywhere]",children:n.body[t]}),n.link&&u.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 Cae(){const[e,t]=j.useState(()=>Nae()),n=e.length>0,a=Da(c=>c.lang),r=Ft(),s=j.useRef(null),l=()=>{if(Oi)try{localStorage.setItem(ub,Oi)}catch{}t([])};return j.useEffect(()=>{if(!n)return;s.current?.focus({preventScroll:!0});const c=d=>{d.stopPropagation(),(d.key==="Escape"||d.key==="Enter")&&l()};return window.addEventListener("keydown",c,!0),()=>window.removeEventListener("keydown",c,!0)},[n]),n?u.jsx("div",{className:"fixed inset-0 z-[100] bg-black/25 flex items-center justify-center animate-fade-in p-6",onClick:l,children:u.jsxs("div",{className:"bg-card border border-line rounded-2xl shadow-xl w-[680px] max-w-full max-h-[85vh] overflow-y-auto",onClick:c=>c.stopPropagation(),role:"dialog","aria-labelledby":"whats-new-title","data-whats-new":!0,children:[u.jsxs("div",{className:"px-6 pt-5 pb-4 border-b border-line",children:[u.jsx("div",{className:"text-2xs uppercase tracking-wide text-ink-faint",children:"ThoughtDAG"}),u.jsx("h2",{id:"whats-new-title",className:"text-base font-semibold text-ink mt-0.5",children:Ue(r("whatsNew.title"),{v:Oi??""})}),e.length>1&&u.jsx("p",{className:"text-xs text-ink-faint mt-1",children:r("whatsNew.multi")})]}),u.jsx("ol",{className:"px-6 divide-y divide-line",children:e.map(c=>u.jsxs("li",{className:"py-4","data-release":c.version,children:[e.length>1&&u.jsxs("div",{className:"flex items-baseline gap-2.5 mb-1.5",children:[u.jsxs("span",{className:"text-sm font-semibold text-ink tabular-nums",children:["v",c.version]}),u.jsx("span",{className:"text-xs text-ink-faint tabular-nums",children:c.date})]}),u.jsx("p",{className:"text-sm text-ink-muted leading-relaxed [overflow-wrap:anywhere]",children:c.lead[a]}),u.jsx(GN,{items:c.items,lang:a})]},c.version))}),u.jsxs("div",{className:"sticky bottom-0 bg-card px-6 py-4 border-t border-line flex items-center justify-between gap-4",children:[u.jsx("button",{onClick:()=>{l(),xe.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")}),u.jsx("button",{ref:s,onClick:l,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 _ae(){const e=xe(r=>r.releaseNotesOpen),t=xe(r=>r.setReleaseNotesOpen),n=Da(r=>r.lang),a=Ft();return j.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?u.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:u.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:[u.jsxs("div",{className:"px-6 pt-5 pb-4 border-b border-line",children:[u.jsx("div",{className:"text-2xs uppercase tracking-wide text-ink-faint",children:"ThoughtDAG"}),u.jsx("h2",{id:"release-notes-title",className:"text-base font-semibold text-ink mt-0.5",children:a("releaseNotes.title")})]}),u.jsx("ol",{className:"px-6 divide-y divide-line",children:VN.map(r=>{const s=Oi===r.version;return u.jsxs("li",{className:"py-4","data-release":r.version,children:[u.jsxs("div",{className:"flex items-baseline gap-2.5 flex-wrap",children:[u.jsxs("span",{className:"text-sm font-semibold text-ink tabular-nums",children:["v",r.version]}),u.jsx("span",{className:"text-xs text-ink-faint tabular-nums",children:r.date}),s&&u.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")})]}),u.jsx("p",{className:"text-sm text-ink-muted leading-relaxed mt-1.5 [overflow-wrap:anywhere]",children:r.lead[n]}),u.jsx(GN,{items:r.items,lang:n})]},r.version)})}),u.jsx("div",{className:"sticky bottom-0 bg-card px-6 py-4 border-t border-line flex justify-end",children:u.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 Mae={ruleout:"#ef4444",decision:"#6B5CE7",pivot:"#e8890c",open:"#d97706",insight:"#0284c7"},sE=e=>{if(e){for(let t=e.length-1;t>=0;t--)if(e[t])return e[t]}};function Iae(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(`
757
757
  `)[0].replace(/^#+\s*/,"")||void 0}function F2(e,t){return e.filter(n=>n.data.stepKind!=="frame").map((n,a)=>{const r=n.data,s=r.createdAt??r.askedAt??r.generatedAts?.[0]??r.lastGeneratedAt,l=[r.askedAt,sE(r.generatedAts),sE(r.editedAts)].filter(Boolean).sort().pop(),c=r.summaryTypes?.[r.responseIndex??0]??void 0,d=r.summaries?.[r.responseIndex??0],h=r.summaryTopics?.[r.responseIndex??0]??void 0,m=s?Date.parse(s):NaN,p=l?Date.parse(l):NaN;return{entry:{id:n.id,label:(d||Iae(r)||r.question||"").slice(0,120),topic:h,badged:!!c&&c!=="insight",type:c??void 0,createdAt:s,modifiedAt:l,color:c&&Mae[c]||"#b8b3c7",archived:!!r.archived,recentlyEdited:!isNaN(m)&&!isNaN(p)&&p-m>6e4&&t-p<30*6e4,x:n.position.x,y:n.position.y},i:a}}).sort((n,a)=>{const r=n.entry.createdAt??"",s=a.entry.createdAt??"";return r<s?-1:r>s?1:n.i-a.i}).map(({entry:n})=>n)}const Dae=e=>e?24:16,Oae=(e,t,n)=>{const a=Dae(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 Rae(){const e=Zd(),t=oe(C=>C.nodes),n=oe(C=>C.setSelectedNodeId),a=xe(C=>C.setTimelineOverviewOpen),r=kl(),s=Ft(),l=k7(),[c,d]=j.useState(null),[h,m]=j.useState(()=>Date.now());j.useEffect(()=>{const C=setInterval(()=>m(Date.now()),6e4);return()=>clearInterval(C)},[]);const p=ln(C=>C.transform),x=ln(C=>C.width),b=ln(C=>C.height),y=j.useMemo(()=>F2(t,h),[t,h]),k=j.useMemo(()=>{const[C,O,D]=p,M=-C/D,N=-O/D,R=(x-C)/D,B=(b-O)/D,U=new Set;for(const Y of y)Y.x+520>M&&Y.x<R&&Y.y+220>N&&Y.y<B&&U.add(Y.id);return U},[y,p,x,b]);if(e==="work"||y.length<2)return null;const T=C=>C?C.slice(0,10):"",w=C=>C.slice(5).replace("-","/"),_=C=>C?new Date(C).toLocaleString(l):"",A=c?y.find(C=>C.id===c.id):null;return u.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:[A&&c&&u.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:c.y-14},children:[u.jsxs("div",{className:"font-medium text-ink truncate",children:[A.topic&&u.jsxs("span",{className:"text-accent",children:[A.topic," · "]}),A.label||"…"]}),A.createdAt&&u.jsxs("div",{className:"text-ink-faint mt-0.5",children:[s("timeline.created")," ",_(A.createdAt)]}),A.modifiedAt&&A.modifiedAt!==A.createdAt&&u.jsxs("div",{className:"text-ink-faint",children:[s("timeline.modified")," ",_(A.modifiedAt)]}),u.jsx("div",{className:"text-[10px] text-ink-faint/80 mt-1",children:s("timeline.clickHint")})]}),u.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:u.jsx(_b,{size:14,strokeWidth:1.75})}),u.jsx("div",{className:"pointer-events-auto overflow-y-auto tdag-noscrollbar max-h-[170px] mt-0.5",children:u.jsx("div",{className:"flex flex-col py-1",children:y.map((C,O)=>{const D=O>0?T(y[O-1].createdAt):"",M=T(C.createdAt),N=M!==""&&M!==D;return u.jsxs("button",{"data-timeline-dot":C.id,onMouseEnter:R=>d({id:C.id,idx:O,y:R.currentTarget.getBoundingClientRect().top}),onMouseLeave:()=>d(R=>R?.id===C.id?null:R),onClick:()=>{n(C.id);const R=r.getViewport().zoom;r.setCenter(C.x+260+Xf(C.id)/(2*R),C.y+110,{zoom:R,duration:300})},onDoubleClick:()=>{n(C.id),r.setCenter(C.x+260+Xf(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:[u.jsx("span",{className:`rounded-full ${C.recentlyEdited?"tdag-timeline-pulse":""}`,style:{width:Oae(O,c?.idx??null,C.badged),height:4,background:C.color,opacity:C.archived?.3:k.has(C.id)?1:.45,transition:"width .18s ease, opacity .3s ease"}}),N&&u.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:w(M)})]},C.id)})})})]})}function YN(e){const t=e.filter(a=>!a.data.archived).map(a=>`${a.id}:${Lc(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 db=new Map,Lae=(e,t)=>db.get(`${t}:${e}`),oE={ruleout:"RULEOUT",decision:"DECISION",pivot:"PIVOT",open:"OPEN",insight:"INSIGHT"};async function jae(e,t,n){const a=YN(e),r=db.get(`${n}:${a}`);if(r)return r;const s=e.find(b=>b.data.isRoot),l=F2(e.filter(b=>!b.data.archived),0),d=l.length>60?l.filter((b,y)=>b.badged||y<10||y>=l.length-10):l,h=l.length-d.length,m=d.map(b=>{const y=e.find(_=>_.id===b.id);if(!y)return null;const k=y.data,T=Lc(k);if(!T)return null;const w=k.summaryTypes?.[k.responseIndex]??void 0;return`- ${w&&oE[w]?`${oE[w]}: `:""}${b.topic?`[${b.topic}] `:""}${T}`}).filter(b=>!!b);h>0&&m.push(`(${h} plain steps omitted from this list)`);const x={text:(await Oo([{role:"user",content:`Opening question of a thinking map: ${s?.data.question?.slice(0,300)??"(untitled)"}
758
758
 
759
759
  The takeaway of every step, in the order they were thought (tags: RULEOUT = killed an option, DECISION = chose, PIVOT = reframed, OPEN = still unresolved):
760
760
  ${m.join(`
761
761
  `)}
762
762
 
763
- 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 db.set(`${n}:${a}`,x),x}function Pae({onLocate:e}){const t=xe(O=>O.timelineOverviewOpen),n=xe(O=>O.setTimelineOverviewOpen),a=oe(O=>O.nodes),r=Ft(),s=k7(),l=Da(O=>O.lang),c=j.useMemo(()=>F2(a,0),[a]),d=j.useMemo(()=>YN(a),[a]),[h,m]=j.useState(null),[p,x]=j.useState(!1),[b,y]=j.useState(!1),k=Lae(d,l)??h,T=!!k&&(k.fp!==d||k.lang!==l),w=()=>{x(!0),y(!1);const{nodes:O,edges:D}=oe.getState();jae(O,D,l).then(m).catch(()=>y(!0)).finally(()=>x(!1))};if(!t)return null;const _=()=>n(!1),A=O=>O?O.slice(0,10):"",C=O=>O?new Date(O).toLocaleTimeString(s,{hour:"2-digit",minute:"2-digit"}):"—";return $a.createPortal(u.jsx("div",{className:"fixed inset-0 z-[60] bg-ink/30 backdrop-blur-sm flex items-center justify-center p-6",onClick:_,children:u.jsxs("div",{className:"bg-card rounded-2xl shadow-2xl border border-line w-[640px] max-h-[80vh] flex flex-col",onClick:O=>O.stopPropagation(),children:[u.jsxs("div",{className:"flex items-center gap-2 px-5 py-3 border-b border-line shrink-0",children:[u.jsx(_b,{size:15,strokeWidth:1.75,className:"text-accent"}),u.jsx("span",{className:"text-sm font-semibold text-ink",children:r("tlov.title")}),u.jsx("span",{className:"text-2xs text-ink-faint",children:Ue(r("tlov.count"),{n:c.length})}),u.jsx("div",{className:"flex-1"}),u.jsxs("button",{onClick:()=>{_(),xe.getState().setThoughtMapOpen(!0)},disabled:c.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:[u.jsx(Mb,{size:13,strokeWidth:1.75}),r("tmap.export")]}),u.jsx("button",{onClick:_,className:"text-ink-faint hover:text-ink w-7 h-7 rounded-lg hover:bg-wash flex items-center justify-center transition-colors",children:u.jsx(bn,{size:15,strokeWidth:1.75})})]}),u.jsxs("div",{className:"px-5 pt-3 shrink-0","data-gedankengang":!0,children:[!k&&!p&&u.jsxs("button",{onClick:w,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:[u.jsx(_f,{size:12,strokeWidth:1.75}),r("tlov.gedankenGenerate")]}),p&&u.jsx("p",{className:"text-2xs text-ink-faint italic py-1.5",children:r("tlov.gedankenLoading")}),b&&!p&&u.jsx("p",{className:"text-2xs text-red-500 py-1",children:r("tlov.gedankenFailed")}),k&&!p&&u.jsxs("div",{className:`rounded-xl bg-wash px-4 py-3 ${T?"opacity-60":""}`,children:[u.jsx("p",{className:"text-sm text-ink leading-relaxed",children:k.text}),u.jsxs("div",{className:"flex items-center gap-2 mt-1.5",children:[u.jsx("span",{className:"text-2xs text-ink-faint",children:T?r("tlov.gedankenStale"):new Date(k.at).toLocaleString(s)}),T&&u.jsx("button",{onClick:w,className:"text-2xs text-accent hover:underline",children:r("tlov.gedankenRedo")})]})]})]}),u.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-5 py-3","data-timeline-overview":!0,children:[c.length===0&&u.jsx("p",{className:"text-xs text-ink-faint italic py-2",children:r("tlov.empty")}),c.map((O,D)=>{const M=D>0?A(c[D-1].createdAt):void 0,N=A(O.createdAt),R=D===0||N!==M;return u.jsxs("div",{children:[R&&u.jsx("div",{className:"sticky top-0 bg-card text-2xs text-ink-faint font-medium pt-3 pb-1 first:pt-0",children:N||r("tlov.undated")}),u.jsxs("div",{className:"group flex items-center gap-2.5 py-1.5 border-b border-line/50 last:border-0",children:[u.jsx("span",{className:"w-2 h-2 rounded-full shrink-0",style:{background:O.color,opacity:O.archived?.35:1}}),u.jsx("span",{className:"text-2xs font-mono text-ink-faint shrink-0 w-11",children:C(O.createdAt)}),u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsxs("p",{className:`text-sm truncate ${O.archived?"text-ink-faint line-through":O.badged?"text-ink":"text-ink-muted"}`,children:[O.topic&&u.jsxs("span",{className:"font-medium text-accent",children:[O.topic," · "]}),O.label||"…"]}),O.modifiedAt&&O.modifiedAt!==O.createdAt&&u.jsxs("p",{className:"text-2xs text-ink-faint",children:[r("timeline.modified")," ",new Date(O.modifiedAt).toLocaleString(s)]})]}),u.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:()=>{_(),e(O.id)},title:r("hlov.locateTitle"),children:r("tlov.locate")})]})]},O.id)})]})]})}),document.body)}const zae=j.memo(function(t){const n=Cn(a=>a.projects.find(r=>r.id===a.activeId)?.kind==="paradigm");return t.data?.stepKind==="frame"?u.jsx(Ste,{...t}):Yf(t.data?.stepKind)?u.jsx(Tte,{...t}):n?u.jsx(pte,{...t}):u.jsx(hte,{...t})}),Bae={thought:zae},Hae={smoothstep:j.memo(Cte)};function Uae(){const[e,t]=j.useState(vt||oe.persist.hasHydrated());return j.useEffect(()=>oe.persist.onFinishHydration(()=>t(!0)),[]),j.useEffect(()=>{if(!e||vt)return;let n;const a=()=>{clearTimeout(n),n=setTimeout(()=>{Lne()},800)},r=oe.subscribe((s,l)=>{s.nodes!==l.nodes&&a()});return a(),()=>{r(),clearTimeout(n)}},[e]),j.useEffect(()=>{xe.getState().condenseRun.status==="building"&&xe.getState().setCondenseRun({status:"idle",current:0,total:0,streaming:""})},[]),j.useEffect(()=>{if(vt)return;const n=setTimeout(()=>{jne()},6e3);return()=>clearTimeout(n)},[]),j.useEffect(()=>{if(!e||vt||localStorage.getItem("thoughtdag.tutorialDone")||oe.getState().nodes.length>0)return;const n=setTimeout(()=>xe.getState().setTutorialOpen(!0),900);return()=>clearTimeout(n)},[e]),j.useEffect(()=>{Une()},[]),j.useEffect(()=>{vt||(Kt(()=>import("./session-handoff-CdTJCZJl.js"),[]).then(n=>n.consumeSessionHandoff()),Kt(()=>import("./live-mirror-DHhvAkDw.js"),[]).then(n=>n.startLiveMirror()),Kt(()=>import("./canvas-record-GBNDUaVp.js"),[]).then(n=>n.startCanvasRecord()),Kt(()=>import("./canonical-D2XBb2dX.js"),[]).then(n=>n.unsubscribeOrphanedSessions()))},[]),j.useEffect(()=>{vt||Hne().then(n=>{n&&(n.status==="minted"?(Ke("success",Ie("provider.oauthMinted")),BN(n.key)):Ke("error",Ue(Ie("provider.oauthFailed"),{error:n.error})))})},[]),u.jsxs(u.Fragment,{children:[e&&u.jsx(Fae,{}),u.jsx(Vne,{}),u.jsx(Yne,{}),u.jsx(Xne,{}),u.jsx(Qne,{}),u.jsx(Zne,{}),u.jsx(Jne,{}),u.jsx(eae,{}),u.jsx(sae,{}),u.jsx(hae,{}),u.jsx(Fne,{}),u.jsx(Tae,{}),u.jsx(Cae,{}),u.jsx(_ae,{})]})}function Fae(){const{nodes:e,edges:t,setNodes:n,setEdges:a,addQuestion:r,undo:s,redo:l,addCrossLink:c,setSelectedNodeId:d,setSelectedNodeIds:h,history:m,historyIndex:p,relayout:x}=oe(),b=Ft(),y=xe(ee=>ee.setTutorialOpen),k=xe(ee=>ee.annotationsHidden),T=xe(ee=>ee.setAnnotationsHidden),[w,_]=j.useState(""),[A,C]=j.useState(!1),[O,D]=j.useState(""),[M,N]=j.useState(!1),[R,B]=j.useState(!1),[U,Y]=j.useState([]),[Z,W]=j.useState(!1),K=j.useRef(null),F=j.useRef(null),G=e.length>0,ne=oe(ee=>ee.events.length>0),X=oe(ee=>ee.nodes.reduce((ge,_e)=>ge+(_e.data.highlights?.length??0),0)),P=oe(ee=>ee.nodes.reduce((ge,_e)=>ge+(_e.data.attachments?.length??0)+(["note","link"].includes(_e.data.stepKind??"")?1:0),0)),q=j.useRef(null),J=xe(ee=>ee.arrivalFocusNodeId);j.useEffect(()=>{if(!J)return;const ee=oe.getState().nodes.find(ge=>ge.id===J);ee&&(xe.getState().setArrivalFocusNodeId(null),window.setTimeout(()=>{q.current?.setCenter(ee.position.x+260,ee.position.y+140,{zoom:.9,duration:400})},150))},[J]);const H=vs(ee=>ee.paper),se=vs(ee=>ee.lighting),ye=vs(ee=>ee.resolved),be=j.useMemo(()=>bte(),[ye]),ke=j.useMemo(()=>{const ee=getComputedStyle(document.documentElement),ge=(ee.getPropertyValue("--color-surface").trim()||"#FAF9F7").replace("#",""),[_e,He,Se]=[0,2,4].map(Ye=>parseInt(ge.slice(Ye,Ye+2),16));return{mask:`rgba(${_e},${He},${Se},0.7)`,archived:ee.getPropertyValue("--color-wash").trim()||"#EFEDE9",ordinary:ye==="dark"?"#6E6759":"#B9B3AB"}},[ye]),ae=j.useRef(e.length),Te=j.useCallback((ee,ge={})=>{const _e=q.current;if(!_e)return;const He=ge.zoom??_e.getZoom();_e.setCenter(ee.position.x+(ge.offX??260)+Xf(ee.id)/(2*He),ee.position.y+110,{zoom:He,duration:ge.duration??350})},[]),Oe=Da(ee=>ee.lang),Le=xe(ee=>ee.condenseRun),We=Le.status==="building",Be=Cn(ee=>ee.projects.find(ge=>ge.id===ee.activeId)?.kind==="paradigm"),rt=El();j.useEffect(()=>{if(vt||!G||oe.getState().nodes.length<10)return;const ee=Number(localStorage.getItem("thoughtdag.lastBackupAt")??0);if(ee===0){localStorage.setItem("thoughtdag.lastBackupAt",String(Date.now()));return}Date.now()-ee<168*3600*1e3||sessionStorage.getItem("thoughtdag.backupNudged")||(sessionStorage.setItem("thoughtdag.backupNudged","yes"),Ke("info",Ie("backup.nudge"),0,{label:Ie("backup.nudgeBtn"),run:()=>cf()}))},[G]);const ht=j.useCallback(()=>{const{nodes:ee,edges:ge}=Rne(Oe),_e=oe.getState();_e.setNodes([..._e.nodes,...ee.filter(He=>!_e.nodes.some(Se=>Se.id===He.id))]),_e.setEdges([..._e.edges,...ge.filter(He=>!_e.edges.some(Se=>Se.id===He.id))]),_e.pushHistory(),setTimeout(()=>{const He=q.current;He&&(He.fitView({duration:500,padding:.1}),setTimeout(()=>{if(He.getViewport().zoom<.34){const Se=[...oe.getState().nodes].sort((Ye,Ze)=>(Ye.data.createdAt??"").localeCompare(Ze.data.createdAt??""))[0];Se&&He.setCenter(Se.position.x+300,Se.position.y+240,{zoom:.6,duration:550})}},680))},100),localStorage.getItem("thoughtdag.tutorialDone")||y(!0)},[Oe,y]),Xe=j.useCallback(ee=>{const ge=oe.getState(),_e=ge.nodes[ge.nodes.length-1],He=_e?{x:_e.position.x,y:_e.position.y+340}:{x:120,y:80},Se=In();ge.setNodes([...ge.nodes,{id:Se,type:"thought",position:He,dragHandle:".drag-handle",data:{question:"",instruction:"",stepKind:ee,response:"",responses:[],responseIndex:-1,isCollapsed:!1,isEditing:!1,isEditingResponse:!1,isLoading:!1,tokenCount:0,highlights:[],highlightMode:"tag",attachments:[],excludedAttachmentIds:[],includedAttachmentIds:[],roleMode:"inherit",isRoot:ge.nodes.length===0,isBranch:!1}}]),ge.pushHistory()},[]),kt=j.useCallback(()=>{ae.current=oe.getState().nodes.length,setTimeout(()=>q.current?.fitView({duration:300,padding:.2}),50)},[]),yt=j.useRef(null),at=j.useCallback(ee=>{const ge=oe.getState(),_e=In();ge.setNodes([...ge.nodes,{id:_e,type:"thought",position:ee,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}}]),ge.pushHistory()},[]),Et=j.useCallback(ee=>{const ge=[];for(const _e of Array.from(ee)){const He=_e.name.split(".").pop()?.toLowerCase()??"";_e.type.startsWith("image/")||_e.type==="application/pdf"||_e.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(He)?ge.push(_e):Ke("info",Ue(Ie("toast.unsupportedFile"),{name:_e.name}))}return ge},[]),zt=j.useCallback(ee=>{const ge=oe.getState(),_e=In();return ge.setNodes([...ge.nodes,{id:_e,type:"thought",position:ee,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,webSearch:xe.getState().webSearchEnabled,scholarSearch:xe.getState().scholarSearchEnabled}}]),ge.pushHistory(),_e},[]),Ve=j.useCallback(ee=>{const ge=Et(ee);if(ge.length===0)return;let _e=null;ge.forEach((He,Se)=>{const Ye=Qr("file",{x:120+Se%3*480,y:120+Math.floor(Se/3)*620});md(Ye,[He]),!_e&&!He.type.startsWith("image/")&&(_e=Ye)}),_e&&xe.getState().setReaderNodeId(_e),setTimeout(()=>q.current?.fitView({duration:400,padding:.2}),120)},[Et]),Bt=j.useCallback((ee,ge)=>{const _e=ee.clientX,He=ee.clientY,Se=ee.currentTarget;let Ye=null;const Ze=Mt=>{!Ye&&Math.hypot(Mt.clientX-_e,Mt.clientY-He)>6&&(Ye=document.createElement("div"),Ye.innerHTML=Se.innerHTML,Ye.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(Ye)),Ye&&(Ye.style.left=`${Mt.clientX-18}px`,Ye.style.top=`${Mt.clientY-18}px`)},xt=Mt=>{window.removeEventListener("pointermove",Ze),window.removeEventListener("pointerup",xt);const Ht=!!Ye;Ye?.remove(),ge(Ht?{x:Mt.clientX,y:Mt.clientY}:null)};window.addEventListener("pointermove",Ze),window.addEventListener("pointerup",xt)},[]),ie=j.useCallback(ee=>{const ge=q.current?.screenToFlowPosition(ee??{x:window.innerWidth/2,y:window.innerHeight/2})??{x:140,y:140};return{x:ge.x-200,y:ge.y-60}},[]);j.useEffect(()=>{const ee=_e=>{yt.current={x:_e.clientX,y:_e.clientY}},ge=_e=>{if(vt)return;const He=_e.target;if(He&&(He.tagName==="INPUT"||He.tagName==="TEXTAREA"||He.isContentEditable))return;const Se=Cn.getState(),Ye=Se.projects.find(Tn=>Tn.id===Se.activeId)?.kind==="paradigm";if(oe.getState().nodes.length===0&&!Ye)return;const Ze=_e.clipboardData;if(!Ze)return;const xt=ie(yt.current),Mt=Ze.getData("text/plain").trim(),Ht=Array.from(Ze.files),ca=Ht.some(Tn=>!Tn.type.startsWith("image/"));if(Ht.length>0&&(ca||!Mt)){_e.preventDefault();const Tn=Qr("file",xt);md(Tn,Ht);return}if(Mt)if(_e.preventDefault(),/^https?:\/\/\S+$/.test(Mt)){const Tn=Qr("link",xt,{linkUrl:Mt});AN(Tn,Mt)}else Qr("note",xt,{question:vte(Mt)})};return window.addEventListener("mousemove",ee),window.addEventListener("paste",ge),()=>{window.removeEventListener("mousemove",ee),window.removeEventListener("paste",ge)}},[ie]);const ze=j.useCallback(async()=>{const ee=oe.getState();if(ee.nodes.length===0)return;const{nodes:ge,edges:_e}=rU(ee.nodes,ee.edges),He=Cn.getState(),Se=He.projects.find(Ze=>Ze.id===He.activeId)?.name??"Paradigm",Ye=crypto.randomUUID();await zr(ni(Ye),JSON.stringify({state:{nodes:ge,edges:_e},version:1})),await Pc(Ye,`▶ ${Se}`,"chat"),await W7(Ye,Se),ae.current=oe.getState().nodes.length,setTimeout(()=>q.current?.fitView({duration:400,padding:.15}),150)},[]);j.useEffect(()=>{e.length===0&&!Be&&!localStorage.getItem("thoughtdag.seeded")&&localStorage.setItem("thoughtdag.seeded","yes")},[]),j.useEffect(()=>{if(e.length>ae.current&&q.current){const ee=e[e.length-1];ee&&setTimeout(()=>Te(ee,{zoom:1,duration:400,offX:220}),100)}ae.current=e.length},[e,Te]);const pe=j.useCallback(ee=>{const ge=oe.getState().nodes;n(v8(ee,ge))},[n]),qe=j.useCallback(ee=>a(w8(ee,oe.getState().edges)),[a]),ut=j.useRef(null),gt=j.useCallback((ee,ge)=>{if(ge.data.stepKind!=="frame"||ge.data.frameCarry===!1)return;const _e=oe.getState(),He=_e.nodes.find(xt=>xt.id===ge.id);if(!He)return;const Se=He.measured?.width??He.width??0,Ye=He.measured?.height??He.height??0,Ze=_e.nodes.filter(xt=>{if(xt.id===He.id||xt.data.stepKind==="frame"||xt.selected)return!1;const Mt=xt.position.x+(xt.measured?.width??520)/2,Ht=xt.position.y+(xt.measured?.height??120)/2;return Mt>=He.position.x&&Mt<=He.position.x+Se&&Ht>=He.position.y&&Ht<=He.position.y+Ye}).map(xt=>({id:xt.id,start:xt.position}));Ze.length!==0&&(ut.current={frameId:He.id,start:He.position,members:Ze})},[]),St=j.useCallback((ee,ge)=>{const _e=ut.current;if(!_e||ge.id!==_e.frameId)return;const He=ge.position.x-_e.start.x,Se=ge.position.y-_e.start.y,Ye=new Map(_e.members.map(Ze=>[Ze.id,{x:Ze.start.x+He,y:Ze.start.y+Se}]));oe.setState(Ze=>({nodes:Ze.nodes.map(xt=>{const Mt=Ye.get(xt.id);return Mt?{...xt,position:Mt}:xt})}))},[]),qt=j.useCallback(()=>{ut.current=null},[]),[un,yn]=j.useState(null),[$t,vn]=j.useState(null),an=j.useCallback((ee,ge)=>{vt||window.getSelection()?.toString()||(ee.preventDefault(),vn({x:ee.clientX,y:ee.clientY,nodeId:ge.id}))},[]),wa=j.useCallback((ee,ge)=>{ee.preventDefault(),yn({x:ee.clientX,y:ee.clientY,edgeId:ge.id})},[]);j.useEffect(()=>{if(!un)return;const ee=()=>yn(null);return window.addEventListener("click",ee),()=>window.removeEventListener("click",ee)},[un]);const qn=oe(ee=>ee.deleteEdges),lr=j.useCallback(ee=>{qn([ee]),yn(null)},[qn]),Qa=j.useCallback(ee=>{ee.source&&ee.target&&c(ee.source,ee.target)},[c]),Jn=j.useCallback(()=>{window.getSelection()?.removeAllRanges(),document.body.classList.add("tdag-connecting")},[]),Pa=j.useCallback((ee,ge)=>{if(document.body.classList.remove("tdag-connecting"),Be||ge.isValid||ge.fromHandle?.type!=="source"||!ge.fromNode)return;const _e=ge.fromNode.id,He=ee.target?.closest?.(".react-flow__node");if(He){const Ht=He.getAttribute("data-id");if(Ht&&Ht!==_e){const ca=oe.getState().nodes.find(Rn=>Rn.id===Ht),Tn=ca?.data.stepKind??"";ca&&!["note","file","link","frame"].includes(Tn)&&oe.getState().addCrossLink(_e,Ht)}return}const{clientX:Se,clientY:Ye}="changedTouches"in ee?ee.changedTouches[0]:ee,Ze=ie({x:Se,y:Ye}),xt=oe.getState();if(xt.nodes.find(Ht=>Ht.id===_e)?.data.stepKind==="frame")return;const Mt=zt(Ze);xt.setEdges([...oe.getState().edges,{id:`edge-${_e}-${Mt}`,source:_e,target:Mt,sourceHandle:"continue",targetHandle:"top",type:"smoothstep",style:{stroke:nt.accent,strokeWidth:2},animated:!1,markerEnd:{type:"arrowclosed",color:nt.accent,width:18,height:18},data:{}}]),oe.getState().pushHistory()},[Be,ie,zt]),Zt=oe(ee=>ee.selectedNodeId),ce=oe(ee=>ee.selectedNodeIds),Pe=xe(ee=>ee.panelOpen),dt=xe(ee=>ee.viewerLoadError),It=oe(ee=>ee.staleIds.length),wn=xe(ee=>ee.panelWidth),rn=e.find(ee=>ee.id===Zt)?.data.stepKind,bt=Yf(rn)||rn==="frame",ft=Pe&&!!Zt&&!Be&&!bt,Rt=ce.length>1,On=oe(ee=>ee.batchDelete);j.useEffect(()=>{const ee=ge=>{if(!xe.getState().confirmRequest&&!(vt&&!((ge.metaKey||ge.ctrlKey)&&ge.key==="f"))){if((ge.metaKey||ge.ctrlKey)&&ge.key==="z"&&(ge.shiftKey?(ge.preventDefault(),l()):(ge.preventDefault(),s())),(ge.metaKey||ge.ctrlKey)&&ge.key==="f"){ge.preventDefault(),C(!0);return}{const _e=ge.target;if(!(_e.tagName==="INPUT"||_e.tagName==="TEXTAREA"||_e.isContentEditable)&&Zt&&!Be&&!ge.metaKey&&!ge.ctrlKey&&!ge.altKey){const{nodes:Se,edges:Ye}=oe.getState();if(ge.key===" "){ge.preventDefault(),oe.getState().toggleCollapse(Zt);return}if(ge.key==="r"||ge.key==="R"){ge.preventDefault(),oe.getState().rerunNode(Zt,{});return}if(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(ge.key)){const Ze=Ye.filter(Mt=>!Mt.data?.isCrossLink);let xt;if(ge.key==="ArrowUp")xt=Ze.find(Mt=>Mt.target===Zt)?.source;else if(ge.key==="ArrowDown")xt=Ze.find(Mt=>Mt.source===Zt)?.target;else{const Mt=Ze.find(Tn=>Tn.target===Zt),Ht=Mt?Ze.filter(Tn=>Tn.source===Mt.source).map(Tn=>Tn.target):Se.filter(Tn=>!Ze.some(Rn=>Rn.target===Tn.id)).map(Tn=>Tn.id),ca=Ht.indexOf(Zt);ca!==-1&&Ht.length>1&&(xt=Ht[(ca+(ge.key==="ArrowRight"?1:Ht.length-1))%Ht.length])}if(xt){ge.preventDefault(),d(xt);const Mt=Se.find(Ht=>Ht.id===xt);Mt&&Te(Mt,{zoom:1,duration:300})}return}}}if(ge.key==="Escape"){const _e=ge.target;if(_e.tagName==="INPUT"||_e.tagName==="TEXTAREA"||_e.isContentEditable)return;ce.length>1?h([]):Zt&&d(null);return}if(ge.key==="Delete"||ge.key==="Backspace"){const _e=ge.target;if(_e.tagName==="INPUT"||_e.tagName==="TEXTAREA"||_e.isContentEditable)return;if(ce.length>1)ge.preventDefault(),Ts({title:Ie("confirm.deleteNodesTitle"),message:Ue(Ie("confirm.deleteNodes"),{n:ce.length}),confirmLabel:Ie("common.delete"),danger:!0}).then(He=>{He&&On(ce)});else{const He=t.filter(Se=>Se.selected).map(Se=>Se.id);He.length>0&&(ge.preventDefault(),qn(He))}}}};return window.addEventListener("keydown",ee),()=>window.removeEventListener("keydown",ee)},[s,l,Zt,ce,d,h,On,t,qn,Be,Te]);const Mn=()=>{w.trim()&&(r(w.trim(),{rolePrompt:O.trim()||void 0,initialAttachments:U.length>0?U:void 0}),_(""),D(""),N(!1),Y([]))},me=async ee=>{for(const ge of Array.from(ee))await Qd(ge,{add:_e=>Y(He=>[...He,_e]),update:(_e,He)=>Y(Se=>Se.map(Ye=>Ye.id===_e?{...Ye,...He}:Ye))})},Qe=ee=>{ee.key==="Enter"&&!ee.shiftKey&&!Ya(ee)&&(ee.preventDefault(),Mn())},At=j.useCallback(({nodes:ee})=>{const ge=ee.map(_e=>_e.id);ge.length>1?h(ge):ge.length===1&&d(ge[0])},[d,h]),Nt=j.useMemo(()=>e.filter(ee=>ee.data.stepKind==="frame"),[e]),[ot,Lt]=j.useState(!1),Jt=j.useRef(null);j.useEffect(()=>{if(!ot)return;const ee=ge=>{Jt.current?.contains(ge.target)||Lt(!1)};return window.addEventListener("mousedown",ee),()=>window.removeEventListener("mousedown",ee)},[ot]);const[Xt,kn]=j.useState(!1),[he,jt]=j.useState(0),dn=xe(ee=>ee.searchHitIds!==null),En=j.useRef(null);j.useEffect(()=>{if(!Xt)return;const ee=ge=>{En.current?.contains(ge.target)||kn(!1)};return window.addEventListener("mousedown",ee),()=>window.removeEventListener("mousedown",ee)},[Xt]);const mn=xe(ee=>ee.searchHitIds),zn=j.useMemo(()=>{if(!Zt||ce.length>1||!e.some(Ze=>Ze.id===Zt))return null;const ee=dm(Zt,e,t),ge=new Set;for(const Ze of ee.mainline)Ze.id!==Zt&&ge.add(Ze.id);for(const Ze of ee.materials)ge.add(Ze.id);for(const Ze of ee.references)ge.add(Ze.source.id);const _e=t.filter(Ze=>!Ze.data?.isCrossLink),He=Br(Zt,e,_e).visitedEdgeIds,Se=new Set(ee.references.map(Ze=>Ze.edge.id)),Ye=_e.filter(Ze=>Ze.source===Zt);return{ctx:ge,down:new Set(Ye.map(Ze=>Ze.target)),pathEdgeIds:He,refEdgeIds:Se,downEdgeIds:new Set(Ye.map(Ze=>Ze.id))}},[Zt,ce,e,t]),Er=j.useMemo(()=>{let ee=e;return k&&(ee=ee.map(ge=>{const _e=ge.data.stepKind,He=Yf(_e)&&!t.some(Se=>Se.source===ge.id||Se.target===ge.id);return _e==="frame"||He?{...ge,hidden:!0}:ge})),mn!==null&&(ee=ee.map(ge=>mn.has(ge.id)||ge.data.stepKind==="frame"?{...ge,className:"search-hit"}:ge.className==="search-hit"?{...ge,className:void 0}:ge)),zn&&(ee=ee.map(ge=>{const _e=ge.id===Zt?"target":zn.ctx.has(ge.id)?"ctx":zn.down.has(ge.id)?"down":ge.data.stepKind==="frame"?void 0:"dim";return _e?{...ge,className:[ge.className,`focus-${_e}`].filter(Boolean).join(" "),..._e!=="dim"?{data:{...ge.data,focusRole:_e}}:{}}:ge})),ee},[e,t,k,mn,zn,Zt]),Ur=j.useMemo(()=>{const ee=t.map(He=>{const Se=He.data?.isBranchFromSelection?{...He,animated:!1,style:{...He.style,strokeDasharray:void 0}}:He,Ye=typeof Se.style?.stroke=="string"?Dk[Se.style.stroke.toUpperCase()]:void 0,Ze=Se.markerEnd&&typeof Se.markerEnd=="object"?Se.markerEnd:void 0,xt=typeof Ze?.color=="string"?Dk[Ze.color.toUpperCase()]:void 0;return!Ye&&!xt?Se:{...Se,...Ye?{style:{...Se.style,stroke:be[Ye]}}:{},...xt&&Ze?{markerEnd:{...Ze,color:be[xt]}}:{}}});if(zn)return ee.map(He=>zn.pathEdgeIds.has(He.id)?{...He,className:"focus-e-path",style:{...He.style,stroke:be.accent,strokeWidth:3.5,opacity:1},markerEnd:{type:"arrowclosed",...He.markerEnd&&typeof He.markerEnd=="object"?He.markerEnd:{},color:be.accent},zIndex:10,data:{...He.data,focusRole:"path"}}:zn.refEdgeIds.has(He.id)?{...He,style:{...He.style,opacity:.9},zIndex:5,data:{...He.data,focusRole:"ref"}}:zn.downEdgeIds.has(He.id)?{...He,className:"focus-e-down",style:{...He.style,strokeWidth:2.5,opacity:.85},markerEnd:{type:"arrowclosed",...He.markerEnd&&typeof He.markerEnd=="object"?He.markerEnd:{}},zIndex:5,data:{...He.data,focusRole:"down"}}:{...He,style:{...He.style,strokeWidth:1.5,opacity:.2},zIndex:0});const ge=ce.length>1?ce:[];if(ge.length===0)return ee;const{visitedEdgeIds:_e}=Br(ge,e,t);return ee.map(He=>_e.has(He.id)?{...He,style:{...He.style,stroke:be.trace,strokeWidth:3.5,opacity:1},markerEnd:{type:"arrowclosed",...He.markerEnd&&typeof He.markerEnd=="object"?He.markerEnd:{},color:be.trace},zIndex:10}:{...He,style:{...He.style,strokeWidth:1.5,opacity:.2},zIndex:0})},[e,t,ce,be,zn]);return j.useEffect(()=>{if(!ft||!Zt)return;const ee=setTimeout(()=>{const ge=q.current;if(!ge)return;const _e=oe.getState().nodes.find(xt=>xt.id===Zt);if(!_e)return;const He=ge.getViewport(),Se=_e.measured?.width??_e.width??480,Ye=(_e.position.x+Se)*He.zoom+He.x,Ze=window.innerWidth-xe.getState().panelWidth-rd-24;if(Ye>Ze){const xt=(_e.position.x+Se/2)*He.zoom+He.x;ge.setViewport({...He,x:He.x-(xt-Ze/2)},{duration:300})}},60);return()=>clearTimeout(ee)},[ft,Zt]),u.jsxs("div",{className:"relative w-full h-full","data-searching":dn||void 0,children:[u.jsxs("div",{className:"relative h-full w-full",onDoubleClick:ee=>{ee.target.classList.contains("react-flow__pane")&&!Be&&zt(ie({x:ee.clientX,y:ee.clientY}))},onDragOver:ee=>{(ee.dataTransfer.types.includes("application/thoughtdag-content")||ee.dataTransfer.types.includes("Files"))&&(ee.preventDefault(),ee.dataTransfer.dropEffect="copy",!G&&!Be&&W(!0))},onDrop:ee=>{if(vt)return;const ge=ee.target;if(!G&&!Be&&ee.dataTransfer.files.length>0){ee.preventDefault(),W(!1),Ve(ee.dataTransfer.files);return}const _e=ge.closest?.(".react-flow__node"),He=_e&&oe.getState().nodes.find(Ze=>Ze.id===_e.getAttribute("data-id"))?.data.stepKind==="frame";if(!ge.classList?.contains("react-flow__pane")&&!He)return;const Se=ie({x:ee.clientX,y:ee.clientY}),Ye=ee.dataTransfer.getData("application/thoughtdag-content");if(Ye==="ask"){ee.preventDefault(),zt(Se);return}if(Ye==="frame"){ee.preventDefault(),at(Se);return}if(Ye==="note"||Ye==="file"){ee.preventDefault(),Qr(Ye,Se);return}if(ee.dataTransfer.files.length>0){ee.preventDefault();const Ze=Et(ee.dataTransfer.files);if(Ze.length===0)return;const xt=Qr("file",Se);md(xt,Ze)}},children:[u.jsxs(BL,{onInit:ee=>{q.current=ee,_N.current=ee;const ge=xe.getState().arrivalFocusNodeId;if(ge){xe.getState().setArrivalFocusNodeId(null);const _e=oe.getState().nodes.find(He=>He.id===ge);_e&&window.setTimeout(()=>{ee.setCenter(_e.position.x+260,_e.position.y+140,{zoom:.9,duration:400})},150)}},nodes:Er,edges:Ur,onNodesChange:pe,onEdgesChange:qe,onNodeDragStart:gt,onNodeDrag:St,onNodeDragStop:qt,onConnect:Qa,onConnectStart:Jn,onConnectEnd:Pa,onEdgeContextMenu:wa,onNodeContextMenu:an,nodeTypes:Bae,edgeTypes:Hae,deleteKeyCode:null,fitView:!0,onlyRenderVisibleElements:!0,minZoom:.04,maxZoom:2,defaultEdgeOptions:{type:"smoothstep",animated:!1,style:{stroke:be.accent,strokeWidth:2},markerEnd:{type:"arrowclosed",color:be.accent,width:18,height:18}},snapToGrid:H==="grid",snapGrid:[22,22],proOptions:{hideAttribution:!0},nodeDragThreshold:5,connectionRadius:40,selectionMode:Ac.Partial,selectionOnDrag:!vt,nodesDraggable:!vt,nodesConnectable:!vt,panOnDrag:vt?!0:[1,2],zoomOnDoubleClick:!1,connectionLineStyle:{stroke:be.accent,strokeDasharray:"8 4",strokeWidth:2},onSelectionChange:At,onPaneClick:()=>{d(null),h([]),vn(null)},children:[H==="grid"?u.jsxs(u.Fragment,{children:[u.jsx(t1,{id:"grid-fine",variant:pi.Lines,gap:22,color:"var(--canvas-grid-fine)"}),u.jsx(t1,{id:"grid-major",variant:pi.Lines,gap:110,color:"var(--canvas-grid-major)"})]}):u.jsx(t1,{variant:pi.Dots,gap:24,size:1,color:"var(--canvas-dot)"}),u.jsx(Wae,{}),u.jsx(qae,{panelShiftWidth:ft?wn:0}),u.jsx(Rae,{}),u.jsx(QL,{position:"bottom-left"}),e.length>0&&u.jsx(uj,{nodeColor:ee=>{const ge=ee.data;if(ge.archived)return ke.archived;const _e=ge.stepKind;return _e==="note"?"#D97706":_e==="file"||_e==="link"?"#64748B":Array.isArray(ge.condensedFrom)&&ge.condensedFrom.length?"#8B7CF0":ge.isRoot?be.accent:ge.isBranch?be.warm:ke.ordinary},maskColor:ke.mask,style:{width:200,height:140},pannable:!0,zoomable:!0,position:"bottom-right"})]}),!G&&Be&&u.jsx("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:u.jsxs("div",{className:"text-center pointer-events-auto",children:[u.jsx("p",{className:"text-sm text-ink-muted mb-1 font-medium",children:b("paradigm.emptyTitle")}),u.jsx("p",{className:"text-xs text-ink-faint mb-4 max-w-sm leading-relaxed",children:b("paradigm.emptyHint")}),u.jsxs("div",{className:"flex items-center justify-center gap-2",children:[u.jsxs("button",{onClick:()=>Xe("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:[u.jsx(sf,{size:15,strokeWidth:1.75})," ",b("paradigm.addHuman")]}),u.jsxs("button",{onClick:()=>Xe("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:[u.jsx(Nd,{size:15,strokeWidth:1.75})," ",b("paradigm.addPrompt")]})]})]})}),vt&&!G&&u.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:u.jsx("div",{className:"text-center max-w-[420px] px-6",children:dt?u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"text-3xl mb-3",children:"🔗"}),u.jsx("div",{className:"text-sm font-semibold text-ink mb-1.5",children:b("viewer.loadError")}),u.jsx("p",{className:"text-xs text-ink-muted leading-relaxed",children:b("viewer.loadErrorHint")})]}):u.jsxs("div",{className:"flex items-center gap-2 text-sm text-ink-muted justify-center",children:[u.jsx(Xn,{size:16,strokeWidth:1.75,className:"animate-spin text-accent"})," ",b("viewer.loading")]})})}),!G&&!Be&&!vt&&u.jsxs("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none overflow-hidden",children:[u.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:[u.jsx("path",{d:"M80 40 C80 90 80 90 80 130 M80 170 C80 210 80 210 80 250",stroke:nt.line,strokeWidth:"2",fill:"none"}),u.jsx("path",{d:"M95 150 C150 150 150 90 205 88",stroke:nt.line,strokeWidth:"2",strokeDasharray:"6 5",fill:"none"}),u.jsx("circle",{cx:"80",cy:"30",r:"7",fill:nt.line}),u.jsx("circle",{cx:"80",cy:"150",r:"7",fill:"none",stroke:nt.line,strokeWidth:"2.5"}),u.jsx("circle",{cx:"80",cy:"262",r:"7",fill:nt.line}),u.jsx("circle",{cx:"218",cy:"88",r:"7",fill:nt.line})]}),u.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:[u.jsx("path",{d:"M240 30 C240 80 240 80 240 120 M240 160 C240 200 240 200 240 240",stroke:nt.line,strokeWidth:"2",fill:"none"}),u.jsx("path",{d:"M225 140 C170 140 170 210 115 212",stroke:nt.line,strokeWidth:"2",strokeDasharray:"6 5",fill:"none"}),u.jsx("circle",{cx:"240",cy:"20",r:"7",fill:nt.line}),u.jsx("circle",{cx:"240",cy:"140",r:"7",fill:"none",stroke:nt.line,strokeWidth:"2.5"}),u.jsx("circle",{cx:"240",cy:"252",r:"7",fill:nt.line}),u.jsx("circle",{cx:"102",cy:"212",r:"7",fill:nt.line})]}),u.jsxs("div",{className:"pointer-events-auto w-[560px] animate-fade-in relative",children:[u.jsxs("div",{className:"text-center mb-8",children:[u.jsxs("svg",{width:"52",height:"52",viewBox:"0 0 44 44",className:"mx-auto mb-4","aria-hidden":!0,children:[u.jsx("circle",{className:"dag-pop",style:{animationDelay:"0.05s"},cx:"22",cy:"7",r:"3.5",fill:nt.accent}),u.jsx("line",{className:"dag-pop",style:{animationDelay:"0.2s"},x1:"22",y1:"11",x2:"22",y2:"19",stroke:nt.accent,strokeWidth:"2",strokeLinecap:"round"}),u.jsx("circle",{className:"dag-pop",style:{animationDelay:"0.35s"},cx:"22",cy:"22",r:"3.5",fill:"none",stroke:nt.accent,strokeWidth:"2.5"}),u.jsx("line",{className:"dag-pop",style:{animationDelay:"0.5s"},x1:"22",y1:"25",x2:"22",y2:"33",stroke:nt.accent,strokeWidth:"2",strokeLinecap:"round"}),u.jsx("circle",{className:"dag-pop",style:{animationDelay:"0.65s"},cx:"22",cy:"37",r:"3.5",fill:nt.accent,opacity:"0.35"}),u.jsx("line",{className:"dag-pop",style:{animationDelay:"0.8s"},x1:"25.5",y1:"23.5",x2:"33",y2:"28.5",stroke:nt.warm,strokeWidth:"2",strokeLinecap:"round",strokeDasharray:"3 3"}),u.jsx("circle",{className:"dag-pop",style:{animationDelay:"0.95s"},cx:"36",cy:"30",r:"3.5",fill:nt.warm})]}),u.jsx("h1",{className:"text-4xl font-semibold tracking-tight text-ink mb-2.5",children:"ThoughtDAG"}),u.jsx("p",{className:"text-sm text-ink-muted",children:b("landing.tagline")}),u.jsx("p",{className:"text-xs text-ink-muted mt-1.5 font-medium",children:b("landing.mechanism")})]}),u.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:[u.jsx("textarea",{value:w,onChange:ee=>_(ee.target.value),onKeyDown:Qe,onPaste:ee=>{if(ee.clipboardData.getData("text/plain").trim())return;const ge=Array.from(ee.clipboardData.items).filter(_e=>_e.kind==="file").map(_e=>_e.getAsFile()).filter(Boolean);ge.length&&me(ge)},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}),U.length>0&&u.jsx("div",{className:"flex flex-wrap gap-2 mt-2 pb-1",children:U.map(ee=>u.jsxs("div",{className:"flex items-center gap-1.5 bg-wash rounded-lg px-2.5 py-1.5 group",children:[ee.thumbnailUrl?u.jsx("img",{src:ee.thumbnailUrl,className:"w-6 h-6 rounded object-cover",alt:ee.name}):u.jsx("span",{className:"text-xs",children:u.jsx(gi,{size:16,strokeWidth:1.75})}),u.jsx("span",{className:"text-xs text-ink-muted max-w-[100px] truncate",children:ee.name}),ee.isExtracting&&u.jsx("span",{className:"text-2xs text-accent",children:u.jsx(Xn,{className:"animate-spin",size:12,strokeWidth:1.75})}),ee.numPages!=null&&u.jsxs("span",{className:"text-2xs text-ink-faint",children:[ee.numPages,"p"]}),u.jsx("button",{onClick:()=>Y(ge=>ge.filter(_e=>_e.id!==ee.id)),className:"text-ink-faint hover:text-red-500 text-xs opacity-0 group-hover:opacity-100 transition-opacity",children:u.jsx(bn,{size:14,strokeWidth:1.75})})]},ee.id))}),M&&u.jsxs("div",{className:"space-y-1 mt-2",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx("span",{className:"text-xs text-ink-muted font-medium",children:b("landing.roleLabel")}),u.jsx("button",{onClick:()=>{N(!1),D("")},className:"text-xs text-ink-faint hover:text-ink-muted",children:u.jsx(bn,{size:14,strokeWidth:1.75})})]}),u.jsx("textarea",{value:O,onChange:ee=>D(ee.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}),u.jsx(NN,{onPick:D})]}),u.jsxs("div",{className:"flex items-center justify-end mt-2 gap-2",children:[u.jsx(Wb,{}),u.jsx("button",{onClick:()=>N(!M),title:b("landing.roleTrayTitle"),className:`rounded-full w-8 h-8 flex items-center justify-center transition-colors shrink-0 ${M||O?"text-accent bg-accent/10 hover:bg-accent/20":"text-ink-faint hover:text-ink-muted hover:bg-line"}`,children:u.jsx(pP,{size:16,strokeWidth:1.75})}),u.jsx("button",{onClick:()=>K.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:u.jsx(xi,{size:16,strokeWidth:1.75})}),u.jsx("input",{ref:K,type:"file",multiple:!0,accept:_d,className:"hidden",onChange:ee=>{me(ee.target.files||[]),ee.target.value=""}}),u.jsx("button",{onClick:Mn,disabled:!w.trim()||U.some(ee=>ee.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:U.some(ee=>ee.isExtracting)?b("landing.extracting"):b("landing.send")})]})]}),u.jsxs("div",{onClick:()=>F.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 ${Z?"border-accent bg-accent/5 ring-2 ring-accent/20":"border-line hover:border-accent/40 hover:bg-accent/5"}`,children:[u.jsxs("div",{className:"flex items-center justify-center gap-2 text-sm text-ink-muted font-medium",children:[u.jsx(So,{size:15,strokeWidth:1.75,className:"text-accent"})," ",b("landing.docStart")]}),u.jsx("p",{className:"text-2xs text-ink-faint mt-1.5",children:b("landing.docFormats")}),u.jsx("p",{className:"text-2xs text-ink-faint mt-0.5",children:b("landing.docPrivacy")})]}),!!window.desktopSessions&&u.jsxs("button",{onClick:()=>B(!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:[u.jsxs("div",{className:"flex items-center justify-center gap-2 text-sm text-ink-muted font-medium",children:[u.jsx(Hj,{size:15,strokeWidth:1.75,className:"text-accent shrink-0"}),u.jsx("span",{children:b("landing.atlasStart")}),u.jsx(Rj,{size:13,strokeWidth:1.75,className:"text-accent shrink-0"})]}),u.jsx("p",{className:"text-2xs text-ink-faint mt-1.5",children:b("landing.atlasDesc")})]}),u.jsx("input",{ref:F,type:"file",multiple:!0,accept:_d,className:"hidden",onChange:ee=>{Ve(ee.target.files||[]),ee.target.value=""}}),R&&u.jsx(jN,{onClose:()=>B(!1),onSwitched:()=>{B(!1),kt()}}),(!rt||(rt.models?.length??0)===0)&&u.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:[u.jsxs("div",{className:"flex items-center justify-center gap-2 text-sm text-ink-muted font-medium",children:[u.jsx(Ad,{size:15,strokeWidth:1.75,className:"text-accent shrink-0"})," ",b("landing.quickTitle")]}),u.jsx("p",{className:"text-2xs text-ink-faint mt-1.5",children:b("landing.quickDesc")}),u.jsxs("div",{className:"mt-2.5 flex items-center justify-center flex-wrap gap-2",children:[Oe==="zh"&&u.jsx("button",{onClick:()=>{xe.getState().setApiKeyPresetHint("zhipu"),xe.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")}),u.jsx("button",{onClick:()=>{zN()},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")}),u.jsx("button",{onClick:()=>xe.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")})]}),u.jsx("button",{onClick:()=>xe.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")})]}),u.jsx("div",{className:"grid grid-cols-3 gap-3 mt-6",children:[{icon:zi,title:"landing.feature1.title",desc:"landing.feature1.desc"},{icon:Ww,title:"landing.feature2.title",desc:"landing.feature2.desc"},{icon:c7,title:"landing.feature3.title",desc:"landing.feature3.desc"}].map(({icon:ee,title:ge,desc:_e})=>u.jsxs("div",{className:"bg-card/60 backdrop-blur border border-line rounded-xl px-4 py-3.5",children:[u.jsx(ee,{size:16,strokeWidth:1.75,className:"text-accent mb-2"}),u.jsx("h3",{className:"text-xs font-semibold text-ink mb-1",children:b(ge)}),u.jsx("p",{className:"text-2xs text-ink-faint leading-relaxed",children:b(_e)})]},ge))}),u.jsxs("div",{className:"text-center mt-6 flex items-center justify-center gap-5",children:[u.jsxs("button",{onClick:ht,className:"text-xs text-accent hover:text-accent-strong font-medium transition-colors inline-flex items-center gap-1.5",children:[u.jsx(Ww,{size:14,strokeWidth:1.75})," ",b("landing.loadExample")]}),u.jsxs("button",{onClick:()=>y(!0),className:"text-xs text-ink-muted hover:text-accent transition-colors inline-flex items-center gap-1.5",children:[u.jsx(Bw,{size:14,strokeWidth:1.75})," ",b("landing.howItWorks")]})]})]})]}),!vt&&u.jsx(Mne,{onSwitched:kt}),(G||Be)&&!vt&&u.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:[!Be&&u.jsx("button",{onClick:()=>zt(ie(null)),draggable:!0,onDragStart:ee=>{ee.dataTransfer.setData("application/thoughtdag-content","ask"),ee.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:u.jsx(sf,{size:17,strokeWidth:1.75})}),u.jsx("button",{onPointerDown:ee=>Bt(ee,ge=>Qr("note",ie(ge))),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:u.jsx(Hi,{size:17,strokeWidth:1.75})}),u.jsx("button",{onPointerDown:ee=>Bt(ee,ge=>Qr("file",ie(ge))),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:u.jsx(xi,{size:17,strokeWidth:1.75})}),u.jsx("button",{onPointerDown:ee=>Bt(ee,ge=>at(ie(ge))),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:u.jsx(Ex,{size:17,strokeWidth:1.75})})]}),vt&&u.jsxs("div",{className:"absolute top-4 z-10 flex gap-1.5 items-center transition-[right] duration-200",style:{right:ft?wn+rd+12:16},children:[u.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:[u.jsx(Td,{size:14,strokeWidth:1.75})," ",b("viewer.badge")]}),u.jsx("button",{onClick:()=>C(!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:u.jsx(Cf,{size:15,strokeWidth:1.75})}),u.jsx(aE,{}),u.jsx("button",{onClick:()=>cf(),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:u.jsx(Ed,{size:15,strokeWidth:1.75})}),u.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")})]}),!vt&&u.jsxs("div",{className:"absolute top-4 z-10 flex gap-1.5 items-center transition-[right] duration-200",style:{right:ft?wn+rd+12:16},children:[Be&&u.jsxs(u.Fragment,{children:[u.jsxs("button",{onClick:()=>Xe("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:[u.jsx(sf,{size:14,strokeWidth:1.75})," ",b("paradigm.addHuman")]}),u.jsxs("button",{onClick:()=>Xe("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:[u.jsx(Nd,{size:14,strokeWidth:1.75})," ",b("paradigm.addPrompt")]}),u.jsxs("button",{onClick:()=>{ze()},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")]})]}),!Be&&u.jsx(CN,{}),!G&&u.jsx("button",{onClick:()=>xe.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:u.jsx(Ad,{size:15,strokeWidth:1.75})}),It>0&&!Be&&u.jsxs("button",{onClick:()=>{const{nodes:ee,edges:ge,staleIds:_e}=oe.getState(),He=_e.reduce((Se,Ye)=>{const Ze=ee.map(Ht=>Ht.id===Ye?{...Ht,data:{...Ht.data,question:"",response:""}}:Ht),{layerTokens:xt}=yr(Ye,Ze,ge),Mt=ee.find(Ht=>Ht.id===Ye)?.data.question??"";return Se+xt.material+xt.reference+xt.chain+$n(Mt)},0);Ts({title:b("replay.confirmTitle"),message:Ue(b("replay.confirmMsg"),{n:It,tok:He.toLocaleString()}),confirmLabel:b("replay.confirmBtn")}).then(Se=>{Se&&oe.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:[u.jsx(JP,{size:14,strokeWidth:1.75})," ",It]}),G&&Nt.length>0&&u.jsxs("div",{ref:Jt,className:"relative",children:[u.jsx("button",{onClick:()=>Lt(ee=>!ee),className:`bg-card/90 backdrop-blur border rounded-lg w-8 h-8 flex items-center justify-center shadow-sm transition-colors ${ot?"border-accent/40 text-accent":"border-line text-ink-faint hover:bg-wash"}`,title:b("toolbar.frames"),children:u.jsx(Ex,{size:15,strokeWidth:1.75})}),ot&&u.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:Nt.map(ee=>u.jsxs("button",{onClick:()=>{Lt(!1),q.current?.fitBounds({x:ee.position.x,y:ee.position.y,width:ee.width??640,height:ee.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:[u.jsx("span",{className:`w-2.5 h-2.5 rounded-sm shrink-0 ${(ad[ee.data.frameColor??"gray"]??ad.gray).dot}`}),u.jsx("span",{className:"truncate",children:ee.data.question||b("frame.untitled")})]},ee.id))})]}),G&&u.jsx("button",{onClick:()=>C(!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:u.jsx(Cf,{size:15,strokeWidth:1.75})}),u.jsx(aE,{}),G&&!Be&&u.jsx(nne,{showTrigger:!1,openPing:he,onLocate:ee=>{const ge=oe.getState().nodes.find(_e=>_e.id===ee);ge&&(d(ee),Te(ge,{zoom:1}))}}),We&&!vt&&u.jsxs("button",{onClick:()=>xe.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:Ue(b("condense.entryBuilding"),{i:String(Le.current),n:String(Le.total)}),"data-condense-entry":!0,children:[u.jsx(Xn,{size:14,strokeWidth:1.75,className:"animate-spin"}),u.jsxs("span",{className:"text-2xs font-mono",children:[Le.current,"/",Le.total]})]}),Lm&&u.jsx("button",{onClick:()=>xe.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:u.jsx(n7,{size:15,strokeWidth:1.75})}),u.jsxs("div",{ref:En,className:"relative",children:[u.jsx("button",{onClick:()=>kn(ee=>!ee),className:`bg-card/90 backdrop-blur border rounded-lg w-8 h-8 flex items-center justify-center shadow-sm transition-colors ${Xt?"border-accent/40 text-accent":"border-line text-ink-faint hover:bg-wash"}`,title:b("toolbar.more"),"data-toolbar-more":!0,children:u.jsx(Z8,{size:15,strokeWidth:1.75})}),Xt&&u.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:[G&&u.jsxs("button",{onClick:()=>{kn(!1),T(!k)},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(k?"toolbar.showAnnotations":"toolbar.hideAnnotations"),children:[u.jsx(Hi,{size:14,strokeWidth:1.75,className:`shrink-0 ${k?"text-accent":"text-ink-faint"}`})," ",b(k?"toolbar.menuAnnotationsShow":"toolbar.menuAnnotationsHide")]}),G&&u.jsxs("button",{onClick:()=>{kn(!1),Ts({title:b("confirm.relayoutTitle"),message:b("confirm.relayoutMsg"),confirmLabel:b("toolbar.relayout")}).then(ee=>{ee&&(x(),setTimeout(()=>q.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:[u.jsx(KP,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("toolbar.relayout")]}),X>0&&u.jsxs("button",{onClick:()=>{kn(!1),xe.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:[u.jsx(Sd,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",Ue(b("hlov.entry"),{n:X})]}),P>0&&u.jsxs("button",{onClick:()=>{kn(!1),xe.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:[u.jsx(xi,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",Ue(b("matov.entry"),{n:P})]}),G&&u.jsx("div",{className:"border-t border-line/60 my-1"}),G&&!Be&&!vt&&u.jsxs("button",{onClick:()=>{kn(!1),xe.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:[u.jsx(cm,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("condense.title"),"…"]}),G&&!Be&&u.jsxs("button",{onClick:()=>{kn(!1),jt(ee=>ee+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:[u.jsx(u7,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("toolbar.menuDiagnose")]}),G&&!Be&&u.jsxs("button",{onClick:()=>{kn(!1),(async()=>{const{nodes:ee,edges:ge}=oe.getState(),{confirmIfSensitive:_e}=await Kt(async()=>{const{confirmIfSensitive:Se}=await import("./sensitive-scan-BVopW_mj.js");return{confirmIfSensitive:Se}},[]);if(!await _e(ee))return;const He=await NB(ee,ge);await navigator.clipboard.writeText(He).catch(()=>{}),xe.getState().setShareDialogUrl(He)})()},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:[u.jsx(Nz,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("toolbar.menuShare")]}),G&&u.jsxs("button",{onClick:()=>{kn(!1),Be?iU():cf()},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:[u.jsx(Ed,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b(Be?"paradigm.exportParadigm":"switcher.exportBackup")]}),ne&&u.jsxs("button",{onClick:()=>{kn(!1),uU()},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:[u.jsx(gi,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("toolbar.exportEvents")]}),G&&u.jsx("div",{className:"border-t border-line/60 my-1"}),u.jsxs("div",{className:"px-3 pt-2 pb-1","data-appearance-lighting":!0,children:[u.jsx("div",{className:"text-2xs text-ink-faint mb-1.5",children:b("appearance.lighting")}),u.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(([ee,ge],_e)=>u.jsx("button",{onClick:()=>vs.getState().setLighting(ee),className:`flex-1 px-1 py-1.5 transition-colors ${_e>0?"border-l border-line":""} ${se===ee?"bg-accent/10 text-accent font-medium":"text-ink-muted hover:bg-wash"}`,children:ge},ee))})]}),u.jsxs("div",{className:"px-3 pt-1 pb-2","data-appearance-paper":!0,children:[u.jsx("div",{className:"text-2xs text-ink-faint mb-1.5",children:b("appearance.paper")}),u.jsx("div",{className:"flex rounded-lg border border-line overflow-hidden text-2xs",children:[["plain",b("appearance.plain")],["grid",b("appearance.grid")]].map(([ee,ge],_e)=>u.jsx("button",{onClick:()=>vs.getState().setPaper(ee),className:`flex-1 px-1 py-1.5 transition-colors ${_e>0?"border-l border-line":""} ${H===ee?"bg-accent/10 text-accent font-medium":"text-ink-muted hover:bg-wash"}`,children:ge},ee))})]}),u.jsx("div",{className:"border-t border-line/60 my-1"}),u.jsxs("button",{onClick:()=>{kn(!1),xe.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:[u.jsx(Fj,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("memory.managerTitle")]}),u.jsxs("button",{onClick:()=>{kn(!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:[u.jsx(Bw,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("landing.howItWorks")]}),u.jsxs("button",{onClick:()=>{kn(!1),xe.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:[u.jsx(_b,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("releaseNotes.entry")]})]})]}),u.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:u.jsx(h7,{size:16,strokeWidth:1.75})}),u.jsx("button",{onClick:l,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:u.jsx(gz,{size:16,strokeWidth:1.75})})]}),Rt&&!vt&&u.jsx(qte,{}),u.jsx(ene,{open:A,onClose:()=>C(!1),onLocate:ee=>{const ge=oe.getState().nodes.find(_e=>_e.id===ee);ge&&(d(ee),Te(ge,{zoom:1}))}}),$t&&u.jsx(Vte,{x:$t.x,y:$t.y,nodeId:$t.nodeId,onClose:()=>vn(null)}),u.jsx($te,{onLocate:ee=>{const ge=oe.getState().nodes.find(_e=>_e.id===ee);ge&&(d(ee),Te(ge,{zoom:1}))}}),u.jsx(Pae,{onLocate:ee=>{const ge=oe.getState().nodes.find(_e=>_e.id===ee);ge&&(d(ee),Te(ge,{zoom:1}))}}),u.jsx(Gte,{onLocate:ee=>{const ge=oe.getState().nodes.find(_e=>_e.id===ee);ge&&(d(ee),Te(ge,{zoom:1}))}}),un&&u.jsx("div",{className:"fixed z-50 bg-card border border-line rounded-xl shadow-lg py-1 min-w-[120px]",style:{left:un.x,top:un.y},children:u.jsxs("button",{onClick:()=>lr(un.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:[u.jsx(Fa,{size:14,strokeWidth:1.75}),b("canvas.deleteEdge")]})})]}),u.jsx(kae,{onFocusSegment:ee=>{const ge=q.current,_e=oe.getState().nodes.filter(Ht=>ee.includes(Ht.id));if(!ge||_e.length===0)return;const He=_e.map(Ht=>Ht.position.x),Se=_e.map(Ht=>Ht.position.y),Ye=Math.min(...He),Ze=Math.min(...Se),xt=Math.max(...He)+520-Ye,Mt=Math.max(...Se)+240-Ze;ge.fitBounds({x:Ye,y:Ze,width:xt+700,height:Mt},{duration:350,padding:.15})}}),ft&&u.jsx(Fte,{onFocusNode:ee=>{const ge=e.find(_e=>_e.id===ee);ge&&Te(ge,{duration:300})}}),u.jsx(fne,{onLocate:ee=>{const ge=oe.getState().nodes.find(_e=>_e.id===ee);ge&&(d(ee),Te(ge,{zoom:1}))}})]})}function qae({panelShiftWidth:e}){const t=Zd(),n=Ft(),a=kl(),r=oe(d=>d.nodes.length),s=oe(d=>d.nodes),l=j.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(vt||t==="work"||r<2)return null;const c=()=>{if(!l)return;xe.getState().setBeaconNodeId(null);const{node:d}=l;a.setCenter(d.position.x+260,d.position.y+110,{zoom:1,duration:1100}),window.setTimeout(()=>{oe.getState().setSelectedNodeId(d.id),xe.getState().setPanelOpen(!0),window.setTimeout(()=>{a.setCenter(d.position.x+260+Xf(d.id)/2,d.position.y+110,{zoom:1,duration:300})},60)},1150),window.setTimeout(()=>{Ke("success",n("continue.arrived"),12e3,{label:n("continue.summarize"),run:()=>{MN(d.id)}})},1550)};return u.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:[u.jsxs("button",{onClick:()=>xe.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:[u.jsx(Mb,{size:16,strokeWidth:1.75})," ",n("tmap.export")]}),l&&u.jsxs("button",{onClick:c,onMouseEnter:()=>xe.getState().setBeaconNodeId(l.node.id),onMouseLeave:()=>xe.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:[u.jsx(yz,{size:16,strokeWidth:1.75})," ",n("continue.button")]})]})}function Wae(){const e=Zd(),t=ln(n=>n.transform[2]);return j.useEffect(()=>{document.querySelector(".react-flow")?.setAttribute("data-zoom-tier",e)},[e]),j.useEffect(()=>{document.querySelector(".react-flow")?.style.setProperty("--tdag-zoom",String(t))},[t]),null}xte();const Vae="/thoughtdag/api";window.desktopSessions||wH(Vae);vt?_B():(V7(),navigator.storage?.persist&&navigator.storage.persist(),Kt(()=>Promise.resolve().then(()=>dae),void 0).then(e=>e.bootAutoBackup()));Kt(()=>import("./update-check-DFw8Y8PB.js"),[]).then(e=>e.bootUpdateCheck());window.addEventListener("hashchange",()=>{window.location.hash.startsWith("#view=")!==vt&&window.location.reload()});s_.createRoot(document.getElementById("root")).render(u.jsx(j.StrictMode,{children:u.jsx(Uae,{})}));export{Bd as A,nr as B,uB as C,$ae as D,eT as E,hm as F,Hb as G,gm as H,Kt as _,Ie as a,oe as b,Cn as c,As as d,vt as e,Ue as f,G7 as g,Ss as h,Zae as i,zr as j,Pc as k,pm as l,Dx as m,KH as n,In as o,ni as p,YH as q,$H as r,No as s,Ke as t,xe as u,X7 as v,Ts as w,Kae as x,Yae as y,Gae as z};
763
+ 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 db.set(`${n}:${a}`,x),x}function Pae({onLocate:e}){const t=xe(O=>O.timelineOverviewOpen),n=xe(O=>O.setTimelineOverviewOpen),a=oe(O=>O.nodes),r=Ft(),s=k7(),l=Da(O=>O.lang),c=j.useMemo(()=>F2(a,0),[a]),d=j.useMemo(()=>YN(a),[a]),[h,m]=j.useState(null),[p,x]=j.useState(!1),[b,y]=j.useState(!1),k=Lae(d,l)??h,T=!!k&&(k.fp!==d||k.lang!==l),w=()=>{x(!0),y(!1);const{nodes:O,edges:D}=oe.getState();jae(O,D,l).then(m).catch(()=>y(!0)).finally(()=>x(!1))};if(!t)return null;const _=()=>n(!1),A=O=>O?O.slice(0,10):"",C=O=>O?new Date(O).toLocaleTimeString(s,{hour:"2-digit",minute:"2-digit"}):"—";return $a.createPortal(u.jsx("div",{className:"fixed inset-0 z-[60] bg-ink/30 backdrop-blur-sm flex items-center justify-center p-6",onClick:_,children:u.jsxs("div",{className:"bg-card rounded-2xl shadow-2xl border border-line w-[640px] max-h-[80vh] flex flex-col",onClick:O=>O.stopPropagation(),children:[u.jsxs("div",{className:"flex items-center gap-2 px-5 py-3 border-b border-line shrink-0",children:[u.jsx(_b,{size:15,strokeWidth:1.75,className:"text-accent"}),u.jsx("span",{className:"text-sm font-semibold text-ink",children:r("tlov.title")}),u.jsx("span",{className:"text-2xs text-ink-faint",children:Ue(r("tlov.count"),{n:c.length})}),u.jsx("div",{className:"flex-1"}),u.jsxs("button",{onClick:()=>{_(),xe.getState().setThoughtMapOpen(!0)},disabled:c.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:[u.jsx(Mb,{size:13,strokeWidth:1.75}),r("tmap.export")]}),u.jsx("button",{onClick:_,className:"text-ink-faint hover:text-ink w-7 h-7 rounded-lg hover:bg-wash flex items-center justify-center transition-colors",children:u.jsx(bn,{size:15,strokeWidth:1.75})})]}),u.jsxs("div",{className:"px-5 pt-3 shrink-0","data-gedankengang":!0,children:[!k&&!p&&u.jsxs("button",{onClick:w,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:[u.jsx(_f,{size:12,strokeWidth:1.75}),r("tlov.gedankenGenerate")]}),p&&u.jsx("p",{className:"text-2xs text-ink-faint italic py-1.5",children:r("tlov.gedankenLoading")}),b&&!p&&u.jsx("p",{className:"text-2xs text-red-500 py-1",children:r("tlov.gedankenFailed")}),k&&!p&&u.jsxs("div",{className:`rounded-xl bg-wash px-4 py-3 ${T?"opacity-60":""}`,children:[u.jsx("p",{className:"text-sm text-ink leading-relaxed",children:k.text}),u.jsxs("div",{className:"flex items-center gap-2 mt-1.5",children:[u.jsx("span",{className:"text-2xs text-ink-faint",children:T?r("tlov.gedankenStale"):new Date(k.at).toLocaleString(s)}),T&&u.jsx("button",{onClick:w,className:"text-2xs text-accent hover:underline",children:r("tlov.gedankenRedo")})]})]})]}),u.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-5 py-3","data-timeline-overview":!0,children:[c.length===0&&u.jsx("p",{className:"text-xs text-ink-faint italic py-2",children:r("tlov.empty")}),c.map((O,D)=>{const M=D>0?A(c[D-1].createdAt):void 0,N=A(O.createdAt),R=D===0||N!==M;return u.jsxs("div",{children:[R&&u.jsx("div",{className:"sticky top-0 bg-card text-2xs text-ink-faint font-medium pt-3 pb-1 first:pt-0",children:N||r("tlov.undated")}),u.jsxs("div",{className:"group flex items-center gap-2.5 py-1.5 border-b border-line/50 last:border-0",children:[u.jsx("span",{className:"w-2 h-2 rounded-full shrink-0",style:{background:O.color,opacity:O.archived?.35:1}}),u.jsx("span",{className:"text-2xs font-mono text-ink-faint shrink-0 w-11",children:C(O.createdAt)}),u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsxs("p",{className:`text-sm truncate ${O.archived?"text-ink-faint line-through":O.badged?"text-ink":"text-ink-muted"}`,children:[O.topic&&u.jsxs("span",{className:"font-medium text-accent",children:[O.topic," · "]}),O.label||"…"]}),O.modifiedAt&&O.modifiedAt!==O.createdAt&&u.jsxs("p",{className:"text-2xs text-ink-faint",children:[r("timeline.modified")," ",new Date(O.modifiedAt).toLocaleString(s)]})]}),u.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:()=>{_(),e(O.id)},title:r("hlov.locateTitle"),children:r("tlov.locate")})]})]},O.id)})]})]})}),document.body)}const zae=j.memo(function(t){const n=Cn(a=>a.projects.find(r=>r.id===a.activeId)?.kind==="paradigm");return t.data?.stepKind==="frame"?u.jsx(Ste,{...t}):Yf(t.data?.stepKind)?u.jsx(Tte,{...t}):n?u.jsx(pte,{...t}):u.jsx(hte,{...t})}),Bae={thought:zae},Hae={smoothstep:j.memo(Cte)};function Uae(){const[e,t]=j.useState(vt||oe.persist.hasHydrated());return j.useEffect(()=>oe.persist.onFinishHydration(()=>t(!0)),[]),j.useEffect(()=>{if(!e||vt)return;let n;const a=()=>{clearTimeout(n),n=setTimeout(()=>{Lne()},800)},r=oe.subscribe((s,l)=>{s.nodes!==l.nodes&&a()});return a(),()=>{r(),clearTimeout(n)}},[e]),j.useEffect(()=>{xe.getState().condenseRun.status==="building"&&xe.getState().setCondenseRun({status:"idle",current:0,total:0,streaming:""})},[]),j.useEffect(()=>{if(vt)return;const n=setTimeout(()=>{jne()},6e3);return()=>clearTimeout(n)},[]),j.useEffect(()=>{if(!e||vt||localStorage.getItem("thoughtdag.tutorialDone")||oe.getState().nodes.length>0)return;const n=setTimeout(()=>xe.getState().setTutorialOpen(!0),900);return()=>clearTimeout(n)},[e]),j.useEffect(()=>{Une()},[]),j.useEffect(()=>{vt||(Kt(()=>import("./session-handoff-TXfFS7pB.js"),[]).then(n=>n.consumeSessionHandoff()),Kt(()=>import("./live-mirror-DrVBjNxd.js"),[]).then(n=>n.startLiveMirror()),Kt(()=>import("./canvas-record-sMlQAe86.js"),[]).then(n=>n.startCanvasRecord()),Kt(()=>import("./canonical-HRd1ZNsL.js"),[]).then(n=>n.unsubscribeOrphanedSessions()))},[]),j.useEffect(()=>{vt||Hne().then(n=>{n&&(n.status==="minted"?(Ke("success",Ie("provider.oauthMinted")),BN(n.key)):Ke("error",Ue(Ie("provider.oauthFailed"),{error:n.error})))})},[]),u.jsxs(u.Fragment,{children:[e&&u.jsx(Fae,{}),u.jsx(Vne,{}),u.jsx(Yne,{}),u.jsx(Xne,{}),u.jsx(Qne,{}),u.jsx(Zne,{}),u.jsx(Jne,{}),u.jsx(eae,{}),u.jsx(sae,{}),u.jsx(hae,{}),u.jsx(Fne,{}),u.jsx(Tae,{}),u.jsx(Cae,{}),u.jsx(_ae,{})]})}function Fae(){const{nodes:e,edges:t,setNodes:n,setEdges:a,addQuestion:r,undo:s,redo:l,addCrossLink:c,setSelectedNodeId:d,setSelectedNodeIds:h,history:m,historyIndex:p,relayout:x}=oe(),b=Ft(),y=xe(ee=>ee.setTutorialOpen),k=xe(ee=>ee.annotationsHidden),T=xe(ee=>ee.setAnnotationsHidden),[w,_]=j.useState(""),[A,C]=j.useState(!1),[O,D]=j.useState(""),[M,N]=j.useState(!1),[R,B]=j.useState(!1),[U,Y]=j.useState([]),[Z,W]=j.useState(!1),K=j.useRef(null),F=j.useRef(null),G=e.length>0,ne=oe(ee=>ee.events.length>0),X=oe(ee=>ee.nodes.reduce((ge,_e)=>ge+(_e.data.highlights?.length??0),0)),P=oe(ee=>ee.nodes.reduce((ge,_e)=>ge+(_e.data.attachments?.length??0)+(["note","link"].includes(_e.data.stepKind??"")?1:0),0)),q=j.useRef(null),J=xe(ee=>ee.arrivalFocusNodeId);j.useEffect(()=>{if(!J)return;const ee=oe.getState().nodes.find(ge=>ge.id===J);ee&&(xe.getState().setArrivalFocusNodeId(null),window.setTimeout(()=>{q.current?.setCenter(ee.position.x+260,ee.position.y+140,{zoom:.9,duration:400})},150))},[J]);const H=vs(ee=>ee.paper),se=vs(ee=>ee.lighting),ye=vs(ee=>ee.resolved),be=j.useMemo(()=>bte(),[ye]),ke=j.useMemo(()=>{const ee=getComputedStyle(document.documentElement),ge=(ee.getPropertyValue("--color-surface").trim()||"#FAF9F7").replace("#",""),[_e,He,Se]=[0,2,4].map(Ye=>parseInt(ge.slice(Ye,Ye+2),16));return{mask:`rgba(${_e},${He},${Se},0.7)`,archived:ee.getPropertyValue("--color-wash").trim()||"#EFEDE9",ordinary:ye==="dark"?"#6E6759":"#B9B3AB"}},[ye]),ae=j.useRef(e.length),Te=j.useCallback((ee,ge={})=>{const _e=q.current;if(!_e)return;const He=ge.zoom??_e.getZoom();_e.setCenter(ee.position.x+(ge.offX??260)+Xf(ee.id)/(2*He),ee.position.y+110,{zoom:He,duration:ge.duration??350})},[]),Oe=Da(ee=>ee.lang),Le=xe(ee=>ee.condenseRun),We=Le.status==="building",Be=Cn(ee=>ee.projects.find(ge=>ge.id===ee.activeId)?.kind==="paradigm"),rt=El();j.useEffect(()=>{if(vt||!G||oe.getState().nodes.length<10)return;const ee=Number(localStorage.getItem("thoughtdag.lastBackupAt")??0);if(ee===0){localStorage.setItem("thoughtdag.lastBackupAt",String(Date.now()));return}Date.now()-ee<168*3600*1e3||sessionStorage.getItem("thoughtdag.backupNudged")||(sessionStorage.setItem("thoughtdag.backupNudged","yes"),Ke("info",Ie("backup.nudge"),0,{label:Ie("backup.nudgeBtn"),run:()=>cf()}))},[G]);const ht=j.useCallback(()=>{const{nodes:ee,edges:ge}=Rne(Oe),_e=oe.getState();_e.setNodes([..._e.nodes,...ee.filter(He=>!_e.nodes.some(Se=>Se.id===He.id))]),_e.setEdges([..._e.edges,...ge.filter(He=>!_e.edges.some(Se=>Se.id===He.id))]),_e.pushHistory(),setTimeout(()=>{const He=q.current;He&&(He.fitView({duration:500,padding:.1}),setTimeout(()=>{if(He.getViewport().zoom<.34){const Se=[...oe.getState().nodes].sort((Ye,Ze)=>(Ye.data.createdAt??"").localeCompare(Ze.data.createdAt??""))[0];Se&&He.setCenter(Se.position.x+300,Se.position.y+240,{zoom:.6,duration:550})}},680))},100),localStorage.getItem("thoughtdag.tutorialDone")||y(!0)},[Oe,y]),Xe=j.useCallback(ee=>{const ge=oe.getState(),_e=ge.nodes[ge.nodes.length-1],He=_e?{x:_e.position.x,y:_e.position.y+340}:{x:120,y:80},Se=In();ge.setNodes([...ge.nodes,{id:Se,type:"thought",position:He,dragHandle:".drag-handle",data:{question:"",instruction:"",stepKind:ee,response:"",responses:[],responseIndex:-1,isCollapsed:!1,isEditing:!1,isEditingResponse:!1,isLoading:!1,tokenCount:0,highlights:[],highlightMode:"tag",attachments:[],excludedAttachmentIds:[],includedAttachmentIds:[],roleMode:"inherit",isRoot:ge.nodes.length===0,isBranch:!1}}]),ge.pushHistory()},[]),kt=j.useCallback(()=>{ae.current=oe.getState().nodes.length,setTimeout(()=>q.current?.fitView({duration:300,padding:.2}),50)},[]),yt=j.useRef(null),at=j.useCallback(ee=>{const ge=oe.getState(),_e=In();ge.setNodes([...ge.nodes,{id:_e,type:"thought",position:ee,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}}]),ge.pushHistory()},[]),Et=j.useCallback(ee=>{const ge=[];for(const _e of Array.from(ee)){const He=_e.name.split(".").pop()?.toLowerCase()??"";_e.type.startsWith("image/")||_e.type==="application/pdf"||_e.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(He)?ge.push(_e):Ke("info",Ue(Ie("toast.unsupportedFile"),{name:_e.name}))}return ge},[]),zt=j.useCallback(ee=>{const ge=oe.getState(),_e=In();return ge.setNodes([...ge.nodes,{id:_e,type:"thought",position:ee,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,webSearch:xe.getState().webSearchEnabled,scholarSearch:xe.getState().scholarSearchEnabled}}]),ge.pushHistory(),_e},[]),Ve=j.useCallback(ee=>{const ge=Et(ee);if(ge.length===0)return;let _e=null;ge.forEach((He,Se)=>{const Ye=Qr("file",{x:120+Se%3*480,y:120+Math.floor(Se/3)*620});md(Ye,[He]),!_e&&!He.type.startsWith("image/")&&(_e=Ye)}),_e&&xe.getState().setReaderNodeId(_e),setTimeout(()=>q.current?.fitView({duration:400,padding:.2}),120)},[Et]),Bt=j.useCallback((ee,ge)=>{const _e=ee.clientX,He=ee.clientY,Se=ee.currentTarget;let Ye=null;const Ze=Mt=>{!Ye&&Math.hypot(Mt.clientX-_e,Mt.clientY-He)>6&&(Ye=document.createElement("div"),Ye.innerHTML=Se.innerHTML,Ye.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(Ye)),Ye&&(Ye.style.left=`${Mt.clientX-18}px`,Ye.style.top=`${Mt.clientY-18}px`)},xt=Mt=>{window.removeEventListener("pointermove",Ze),window.removeEventListener("pointerup",xt);const Ht=!!Ye;Ye?.remove(),ge(Ht?{x:Mt.clientX,y:Mt.clientY}:null)};window.addEventListener("pointermove",Ze),window.addEventListener("pointerup",xt)},[]),ie=j.useCallback(ee=>{const ge=q.current?.screenToFlowPosition(ee??{x:window.innerWidth/2,y:window.innerHeight/2})??{x:140,y:140};return{x:ge.x-200,y:ge.y-60}},[]);j.useEffect(()=>{const ee=_e=>{yt.current={x:_e.clientX,y:_e.clientY}},ge=_e=>{if(vt)return;const He=_e.target;if(He&&(He.tagName==="INPUT"||He.tagName==="TEXTAREA"||He.isContentEditable))return;const Se=Cn.getState(),Ye=Se.projects.find(Tn=>Tn.id===Se.activeId)?.kind==="paradigm";if(oe.getState().nodes.length===0&&!Ye)return;const Ze=_e.clipboardData;if(!Ze)return;const xt=ie(yt.current),Mt=Ze.getData("text/plain").trim(),Ht=Array.from(Ze.files),ca=Ht.some(Tn=>!Tn.type.startsWith("image/"));if(Ht.length>0&&(ca||!Mt)){_e.preventDefault();const Tn=Qr("file",xt);md(Tn,Ht);return}if(Mt)if(_e.preventDefault(),/^https?:\/\/\S+$/.test(Mt)){const Tn=Qr("link",xt,{linkUrl:Mt});AN(Tn,Mt)}else Qr("note",xt,{question:vte(Mt)})};return window.addEventListener("mousemove",ee),window.addEventListener("paste",ge),()=>{window.removeEventListener("mousemove",ee),window.removeEventListener("paste",ge)}},[ie]);const ze=j.useCallback(async()=>{const ee=oe.getState();if(ee.nodes.length===0)return;const{nodes:ge,edges:_e}=rU(ee.nodes,ee.edges),He=Cn.getState(),Se=He.projects.find(Ze=>Ze.id===He.activeId)?.name??"Paradigm",Ye=crypto.randomUUID();await zr(ni(Ye),JSON.stringify({state:{nodes:ge,edges:_e},version:1})),await Pc(Ye,`▶ ${Se}`,"chat"),await W7(Ye,Se),ae.current=oe.getState().nodes.length,setTimeout(()=>q.current?.fitView({duration:400,padding:.15}),150)},[]);j.useEffect(()=>{e.length===0&&!Be&&!localStorage.getItem("thoughtdag.seeded")&&localStorage.setItem("thoughtdag.seeded","yes")},[]),j.useEffect(()=>{if(e.length>ae.current&&q.current){const ee=e[e.length-1];ee&&setTimeout(()=>Te(ee,{zoom:1,duration:400,offX:220}),100)}ae.current=e.length},[e,Te]);const pe=j.useCallback(ee=>{const ge=oe.getState().nodes;n(v8(ee,ge))},[n]),qe=j.useCallback(ee=>a(w8(ee,oe.getState().edges)),[a]),ut=j.useRef(null),gt=j.useCallback((ee,ge)=>{if(ge.data.stepKind!=="frame"||ge.data.frameCarry===!1)return;const _e=oe.getState(),He=_e.nodes.find(xt=>xt.id===ge.id);if(!He)return;const Se=He.measured?.width??He.width??0,Ye=He.measured?.height??He.height??0,Ze=_e.nodes.filter(xt=>{if(xt.id===He.id||xt.data.stepKind==="frame"||xt.selected)return!1;const Mt=xt.position.x+(xt.measured?.width??520)/2,Ht=xt.position.y+(xt.measured?.height??120)/2;return Mt>=He.position.x&&Mt<=He.position.x+Se&&Ht>=He.position.y&&Ht<=He.position.y+Ye}).map(xt=>({id:xt.id,start:xt.position}));Ze.length!==0&&(ut.current={frameId:He.id,start:He.position,members:Ze})},[]),St=j.useCallback((ee,ge)=>{const _e=ut.current;if(!_e||ge.id!==_e.frameId)return;const He=ge.position.x-_e.start.x,Se=ge.position.y-_e.start.y,Ye=new Map(_e.members.map(Ze=>[Ze.id,{x:Ze.start.x+He,y:Ze.start.y+Se}]));oe.setState(Ze=>({nodes:Ze.nodes.map(xt=>{const Mt=Ye.get(xt.id);return Mt?{...xt,position:Mt}:xt})}))},[]),qt=j.useCallback(()=>{ut.current=null},[]),[un,yn]=j.useState(null),[$t,vn]=j.useState(null),an=j.useCallback((ee,ge)=>{vt||window.getSelection()?.toString()||(ee.preventDefault(),vn({x:ee.clientX,y:ee.clientY,nodeId:ge.id}))},[]),wa=j.useCallback((ee,ge)=>{ee.preventDefault(),yn({x:ee.clientX,y:ee.clientY,edgeId:ge.id})},[]);j.useEffect(()=>{if(!un)return;const ee=()=>yn(null);return window.addEventListener("click",ee),()=>window.removeEventListener("click",ee)},[un]);const qn=oe(ee=>ee.deleteEdges),lr=j.useCallback(ee=>{qn([ee]),yn(null)},[qn]),Qa=j.useCallback(ee=>{ee.source&&ee.target&&c(ee.source,ee.target)},[c]),Jn=j.useCallback(()=>{window.getSelection()?.removeAllRanges(),document.body.classList.add("tdag-connecting")},[]),Pa=j.useCallback((ee,ge)=>{if(document.body.classList.remove("tdag-connecting"),Be||ge.isValid||ge.fromHandle?.type!=="source"||!ge.fromNode)return;const _e=ge.fromNode.id,He=ee.target?.closest?.(".react-flow__node");if(He){const Ht=He.getAttribute("data-id");if(Ht&&Ht!==_e){const ca=oe.getState().nodes.find(Rn=>Rn.id===Ht),Tn=ca?.data.stepKind??"";ca&&!["note","file","link","frame"].includes(Tn)&&oe.getState().addCrossLink(_e,Ht)}return}const{clientX:Se,clientY:Ye}="changedTouches"in ee?ee.changedTouches[0]:ee,Ze=ie({x:Se,y:Ye}),xt=oe.getState();if(xt.nodes.find(Ht=>Ht.id===_e)?.data.stepKind==="frame")return;const Mt=zt(Ze);xt.setEdges([...oe.getState().edges,{id:`edge-${_e}-${Mt}`,source:_e,target:Mt,sourceHandle:"continue",targetHandle:"top",type:"smoothstep",style:{stroke:nt.accent,strokeWidth:2},animated:!1,markerEnd:{type:"arrowclosed",color:nt.accent,width:18,height:18},data:{}}]),oe.getState().pushHistory()},[Be,ie,zt]),Zt=oe(ee=>ee.selectedNodeId),ce=oe(ee=>ee.selectedNodeIds),Pe=xe(ee=>ee.panelOpen),dt=xe(ee=>ee.viewerLoadError),It=oe(ee=>ee.staleIds.length),wn=xe(ee=>ee.panelWidth),rn=e.find(ee=>ee.id===Zt)?.data.stepKind,bt=Yf(rn)||rn==="frame",ft=Pe&&!!Zt&&!Be&&!bt,Rt=ce.length>1,On=oe(ee=>ee.batchDelete);j.useEffect(()=>{const ee=ge=>{if(!xe.getState().confirmRequest&&!(vt&&!((ge.metaKey||ge.ctrlKey)&&ge.key==="f"))){if((ge.metaKey||ge.ctrlKey)&&ge.key==="z"&&(ge.shiftKey?(ge.preventDefault(),l()):(ge.preventDefault(),s())),(ge.metaKey||ge.ctrlKey)&&ge.key==="f"){ge.preventDefault(),C(!0);return}{const _e=ge.target;if(!(_e.tagName==="INPUT"||_e.tagName==="TEXTAREA"||_e.isContentEditable)&&Zt&&!Be&&!ge.metaKey&&!ge.ctrlKey&&!ge.altKey){const{nodes:Se,edges:Ye}=oe.getState();if(ge.key===" "){ge.preventDefault(),oe.getState().toggleCollapse(Zt);return}if(ge.key==="r"||ge.key==="R"){ge.preventDefault(),oe.getState().rerunNode(Zt,{});return}if(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(ge.key)){const Ze=Ye.filter(Mt=>!Mt.data?.isCrossLink);let xt;if(ge.key==="ArrowUp")xt=Ze.find(Mt=>Mt.target===Zt)?.source;else if(ge.key==="ArrowDown")xt=Ze.find(Mt=>Mt.source===Zt)?.target;else{const Mt=Ze.find(Tn=>Tn.target===Zt),Ht=Mt?Ze.filter(Tn=>Tn.source===Mt.source).map(Tn=>Tn.target):Se.filter(Tn=>!Ze.some(Rn=>Rn.target===Tn.id)).map(Tn=>Tn.id),ca=Ht.indexOf(Zt);ca!==-1&&Ht.length>1&&(xt=Ht[(ca+(ge.key==="ArrowRight"?1:Ht.length-1))%Ht.length])}if(xt){ge.preventDefault(),d(xt);const Mt=Se.find(Ht=>Ht.id===xt);Mt&&Te(Mt,{zoom:1,duration:300})}return}}}if(ge.key==="Escape"){const _e=ge.target;if(_e.tagName==="INPUT"||_e.tagName==="TEXTAREA"||_e.isContentEditable)return;ce.length>1?h([]):Zt&&d(null);return}if(ge.key==="Delete"||ge.key==="Backspace"){const _e=ge.target;if(_e.tagName==="INPUT"||_e.tagName==="TEXTAREA"||_e.isContentEditable)return;if(ce.length>1)ge.preventDefault(),Ts({title:Ie("confirm.deleteNodesTitle"),message:Ue(Ie("confirm.deleteNodes"),{n:ce.length}),confirmLabel:Ie("common.delete"),danger:!0}).then(He=>{He&&On(ce)});else{const He=t.filter(Se=>Se.selected).map(Se=>Se.id);He.length>0&&(ge.preventDefault(),qn(He))}}}};return window.addEventListener("keydown",ee),()=>window.removeEventListener("keydown",ee)},[s,l,Zt,ce,d,h,On,t,qn,Be,Te]);const Mn=()=>{w.trim()&&(r(w.trim(),{rolePrompt:O.trim()||void 0,initialAttachments:U.length>0?U:void 0}),_(""),D(""),N(!1),Y([]))},me=async ee=>{for(const ge of Array.from(ee))await Qd(ge,{add:_e=>Y(He=>[...He,_e]),update:(_e,He)=>Y(Se=>Se.map(Ye=>Ye.id===_e?{...Ye,...He}:Ye))})},Qe=ee=>{ee.key==="Enter"&&!ee.shiftKey&&!Ya(ee)&&(ee.preventDefault(),Mn())},At=j.useCallback(({nodes:ee})=>{const ge=ee.map(_e=>_e.id);ge.length>1?h(ge):ge.length===1&&d(ge[0])},[d,h]),Nt=j.useMemo(()=>e.filter(ee=>ee.data.stepKind==="frame"),[e]),[ot,Lt]=j.useState(!1),Jt=j.useRef(null);j.useEffect(()=>{if(!ot)return;const ee=ge=>{Jt.current?.contains(ge.target)||Lt(!1)};return window.addEventListener("mousedown",ee),()=>window.removeEventListener("mousedown",ee)},[ot]);const[Xt,kn]=j.useState(!1),[he,jt]=j.useState(0),dn=xe(ee=>ee.searchHitIds!==null),En=j.useRef(null);j.useEffect(()=>{if(!Xt)return;const ee=ge=>{En.current?.contains(ge.target)||kn(!1)};return window.addEventListener("mousedown",ee),()=>window.removeEventListener("mousedown",ee)},[Xt]);const mn=xe(ee=>ee.searchHitIds),zn=j.useMemo(()=>{if(!Zt||ce.length>1||!e.some(Ze=>Ze.id===Zt))return null;const ee=dm(Zt,e,t),ge=new Set;for(const Ze of ee.mainline)Ze.id!==Zt&&ge.add(Ze.id);for(const Ze of ee.materials)ge.add(Ze.id);for(const Ze of ee.references)ge.add(Ze.source.id);const _e=t.filter(Ze=>!Ze.data?.isCrossLink),He=Br(Zt,e,_e).visitedEdgeIds,Se=new Set(ee.references.map(Ze=>Ze.edge.id)),Ye=_e.filter(Ze=>Ze.source===Zt);return{ctx:ge,down:new Set(Ye.map(Ze=>Ze.target)),pathEdgeIds:He,refEdgeIds:Se,downEdgeIds:new Set(Ye.map(Ze=>Ze.id))}},[Zt,ce,e,t]),Er=j.useMemo(()=>{let ee=e;return k&&(ee=ee.map(ge=>{const _e=ge.data.stepKind,He=Yf(_e)&&!t.some(Se=>Se.source===ge.id||Se.target===ge.id);return _e==="frame"||He?{...ge,hidden:!0}:ge})),mn!==null&&(ee=ee.map(ge=>mn.has(ge.id)||ge.data.stepKind==="frame"?{...ge,className:"search-hit"}:ge.className==="search-hit"?{...ge,className:void 0}:ge)),zn&&(ee=ee.map(ge=>{const _e=ge.id===Zt?"target":zn.ctx.has(ge.id)?"ctx":zn.down.has(ge.id)?"down":ge.data.stepKind==="frame"?void 0:"dim";return _e?{...ge,className:[ge.className,`focus-${_e}`].filter(Boolean).join(" "),..._e!=="dim"?{data:{...ge.data,focusRole:_e}}:{}}:ge})),ee},[e,t,k,mn,zn,Zt]),Ur=j.useMemo(()=>{const ee=t.map(He=>{const Se=He.data?.isBranchFromSelection?{...He,animated:!1,style:{...He.style,strokeDasharray:void 0}}:He,Ye=typeof Se.style?.stroke=="string"?Dk[Se.style.stroke.toUpperCase()]:void 0,Ze=Se.markerEnd&&typeof Se.markerEnd=="object"?Se.markerEnd:void 0,xt=typeof Ze?.color=="string"?Dk[Ze.color.toUpperCase()]:void 0;return!Ye&&!xt?Se:{...Se,...Ye?{style:{...Se.style,stroke:be[Ye]}}:{},...xt&&Ze?{markerEnd:{...Ze,color:be[xt]}}:{}}});if(zn)return ee.map(He=>zn.pathEdgeIds.has(He.id)?{...He,className:"focus-e-path",style:{...He.style,stroke:be.accent,strokeWidth:3.5,opacity:1},markerEnd:{type:"arrowclosed",...He.markerEnd&&typeof He.markerEnd=="object"?He.markerEnd:{},color:be.accent},zIndex:10,data:{...He.data,focusRole:"path"}}:zn.refEdgeIds.has(He.id)?{...He,style:{...He.style,opacity:.9},zIndex:5,data:{...He.data,focusRole:"ref"}}:zn.downEdgeIds.has(He.id)?{...He,className:"focus-e-down",style:{...He.style,strokeWidth:2.5,opacity:.85},markerEnd:{type:"arrowclosed",...He.markerEnd&&typeof He.markerEnd=="object"?He.markerEnd:{}},zIndex:5,data:{...He.data,focusRole:"down"}}:{...He,style:{...He.style,strokeWidth:1.5,opacity:.2},zIndex:0});const ge=ce.length>1?ce:[];if(ge.length===0)return ee;const{visitedEdgeIds:_e}=Br(ge,e,t);return ee.map(He=>_e.has(He.id)?{...He,style:{...He.style,stroke:be.trace,strokeWidth:3.5,opacity:1},markerEnd:{type:"arrowclosed",...He.markerEnd&&typeof He.markerEnd=="object"?He.markerEnd:{},color:be.trace},zIndex:10}:{...He,style:{...He.style,strokeWidth:1.5,opacity:.2},zIndex:0})},[e,t,ce,be,zn]);return j.useEffect(()=>{if(!ft||!Zt)return;const ee=setTimeout(()=>{const ge=q.current;if(!ge)return;const _e=oe.getState().nodes.find(xt=>xt.id===Zt);if(!_e)return;const He=ge.getViewport(),Se=_e.measured?.width??_e.width??480,Ye=(_e.position.x+Se)*He.zoom+He.x,Ze=window.innerWidth-xe.getState().panelWidth-rd-24;if(Ye>Ze){const xt=(_e.position.x+Se/2)*He.zoom+He.x;ge.setViewport({...He,x:He.x-(xt-Ze/2)},{duration:300})}},60);return()=>clearTimeout(ee)},[ft,Zt]),u.jsxs("div",{className:"relative w-full h-full","data-searching":dn||void 0,children:[u.jsxs("div",{className:"relative h-full w-full",onDoubleClick:ee=>{ee.target.classList.contains("react-flow__pane")&&!Be&&zt(ie({x:ee.clientX,y:ee.clientY}))},onDragOver:ee=>{(ee.dataTransfer.types.includes("application/thoughtdag-content")||ee.dataTransfer.types.includes("Files"))&&(ee.preventDefault(),ee.dataTransfer.dropEffect="copy",!G&&!Be&&W(!0))},onDrop:ee=>{if(vt)return;const ge=ee.target;if(!G&&!Be&&ee.dataTransfer.files.length>0){ee.preventDefault(),W(!1),Ve(ee.dataTransfer.files);return}const _e=ge.closest?.(".react-flow__node"),He=_e&&oe.getState().nodes.find(Ze=>Ze.id===_e.getAttribute("data-id"))?.data.stepKind==="frame";if(!ge.classList?.contains("react-flow__pane")&&!He)return;const Se=ie({x:ee.clientX,y:ee.clientY}),Ye=ee.dataTransfer.getData("application/thoughtdag-content");if(Ye==="ask"){ee.preventDefault(),zt(Se);return}if(Ye==="frame"){ee.preventDefault(),at(Se);return}if(Ye==="note"||Ye==="file"){ee.preventDefault(),Qr(Ye,Se);return}if(ee.dataTransfer.files.length>0){ee.preventDefault();const Ze=Et(ee.dataTransfer.files);if(Ze.length===0)return;const xt=Qr("file",Se);md(xt,Ze)}},children:[u.jsxs(BL,{onInit:ee=>{q.current=ee,_N.current=ee;const ge=xe.getState().arrivalFocusNodeId;if(ge){xe.getState().setArrivalFocusNodeId(null);const _e=oe.getState().nodes.find(He=>He.id===ge);_e&&window.setTimeout(()=>{ee.setCenter(_e.position.x+260,_e.position.y+140,{zoom:.9,duration:400})},150)}},nodes:Er,edges:Ur,onNodesChange:pe,onEdgesChange:qe,onNodeDragStart:gt,onNodeDrag:St,onNodeDragStop:qt,onConnect:Qa,onConnectStart:Jn,onConnectEnd:Pa,onEdgeContextMenu:wa,onNodeContextMenu:an,nodeTypes:Bae,edgeTypes:Hae,deleteKeyCode:null,fitView:!0,onlyRenderVisibleElements:!0,minZoom:.04,maxZoom:2,defaultEdgeOptions:{type:"smoothstep",animated:!1,style:{stroke:be.accent,strokeWidth:2},markerEnd:{type:"arrowclosed",color:be.accent,width:18,height:18}},snapToGrid:H==="grid",snapGrid:[22,22],proOptions:{hideAttribution:!0},nodeDragThreshold:5,connectionRadius:40,selectionMode:Ac.Partial,selectionOnDrag:!vt,nodesDraggable:!vt,nodesConnectable:!vt,panOnDrag:vt?!0:[1,2],zoomOnDoubleClick:!1,connectionLineStyle:{stroke:be.accent,strokeDasharray:"8 4",strokeWidth:2},onSelectionChange:At,onPaneClick:()=>{d(null),h([]),vn(null)},children:[H==="grid"?u.jsxs(u.Fragment,{children:[u.jsx(t1,{id:"grid-fine",variant:pi.Lines,gap:22,color:"var(--canvas-grid-fine)"}),u.jsx(t1,{id:"grid-major",variant:pi.Lines,gap:110,color:"var(--canvas-grid-major)"})]}):u.jsx(t1,{variant:pi.Dots,gap:24,size:1,color:"var(--canvas-dot)"}),u.jsx(Wae,{}),u.jsx(qae,{panelShiftWidth:ft?wn:0}),u.jsx(Rae,{}),u.jsx(QL,{position:"bottom-left"}),e.length>0&&u.jsx(uj,{nodeColor:ee=>{const ge=ee.data;if(ge.archived)return ke.archived;const _e=ge.stepKind;return _e==="note"?"#D97706":_e==="file"||_e==="link"?"#64748B":Array.isArray(ge.condensedFrom)&&ge.condensedFrom.length?"#8B7CF0":ge.isRoot?be.accent:ge.isBranch?be.warm:ke.ordinary},maskColor:ke.mask,style:{width:200,height:140},pannable:!0,zoomable:!0,position:"bottom-right"})]}),!G&&Be&&u.jsx("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:u.jsxs("div",{className:"text-center pointer-events-auto",children:[u.jsx("p",{className:"text-sm text-ink-muted mb-1 font-medium",children:b("paradigm.emptyTitle")}),u.jsx("p",{className:"text-xs text-ink-faint mb-4 max-w-sm leading-relaxed",children:b("paradigm.emptyHint")}),u.jsxs("div",{className:"flex items-center justify-center gap-2",children:[u.jsxs("button",{onClick:()=>Xe("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:[u.jsx(sf,{size:15,strokeWidth:1.75})," ",b("paradigm.addHuman")]}),u.jsxs("button",{onClick:()=>Xe("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:[u.jsx(Nd,{size:15,strokeWidth:1.75})," ",b("paradigm.addPrompt")]})]})]})}),vt&&!G&&u.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:u.jsx("div",{className:"text-center max-w-[420px] px-6",children:dt?u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"text-3xl mb-3",children:"🔗"}),u.jsx("div",{className:"text-sm font-semibold text-ink mb-1.5",children:b("viewer.loadError")}),u.jsx("p",{className:"text-xs text-ink-muted leading-relaxed",children:b("viewer.loadErrorHint")})]}):u.jsxs("div",{className:"flex items-center gap-2 text-sm text-ink-muted justify-center",children:[u.jsx(Xn,{size:16,strokeWidth:1.75,className:"animate-spin text-accent"})," ",b("viewer.loading")]})})}),!G&&!Be&&!vt&&u.jsxs("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none overflow-hidden",children:[u.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:[u.jsx("path",{d:"M80 40 C80 90 80 90 80 130 M80 170 C80 210 80 210 80 250",stroke:nt.line,strokeWidth:"2",fill:"none"}),u.jsx("path",{d:"M95 150 C150 150 150 90 205 88",stroke:nt.line,strokeWidth:"2",strokeDasharray:"6 5",fill:"none"}),u.jsx("circle",{cx:"80",cy:"30",r:"7",fill:nt.line}),u.jsx("circle",{cx:"80",cy:"150",r:"7",fill:"none",stroke:nt.line,strokeWidth:"2.5"}),u.jsx("circle",{cx:"80",cy:"262",r:"7",fill:nt.line}),u.jsx("circle",{cx:"218",cy:"88",r:"7",fill:nt.line})]}),u.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:[u.jsx("path",{d:"M240 30 C240 80 240 80 240 120 M240 160 C240 200 240 200 240 240",stroke:nt.line,strokeWidth:"2",fill:"none"}),u.jsx("path",{d:"M225 140 C170 140 170 210 115 212",stroke:nt.line,strokeWidth:"2",strokeDasharray:"6 5",fill:"none"}),u.jsx("circle",{cx:"240",cy:"20",r:"7",fill:nt.line}),u.jsx("circle",{cx:"240",cy:"140",r:"7",fill:"none",stroke:nt.line,strokeWidth:"2.5"}),u.jsx("circle",{cx:"240",cy:"252",r:"7",fill:nt.line}),u.jsx("circle",{cx:"102",cy:"212",r:"7",fill:nt.line})]}),u.jsxs("div",{className:"pointer-events-auto w-[560px] animate-fade-in relative",children:[u.jsxs("div",{className:"text-center mb-8",children:[u.jsxs("svg",{width:"52",height:"52",viewBox:"0 0 44 44",className:"mx-auto mb-4","aria-hidden":!0,children:[u.jsx("circle",{className:"dag-pop",style:{animationDelay:"0.05s"},cx:"22",cy:"7",r:"3.5",fill:nt.accent}),u.jsx("line",{className:"dag-pop",style:{animationDelay:"0.2s"},x1:"22",y1:"11",x2:"22",y2:"19",stroke:nt.accent,strokeWidth:"2",strokeLinecap:"round"}),u.jsx("circle",{className:"dag-pop",style:{animationDelay:"0.35s"},cx:"22",cy:"22",r:"3.5",fill:"none",stroke:nt.accent,strokeWidth:"2.5"}),u.jsx("line",{className:"dag-pop",style:{animationDelay:"0.5s"},x1:"22",y1:"25",x2:"22",y2:"33",stroke:nt.accent,strokeWidth:"2",strokeLinecap:"round"}),u.jsx("circle",{className:"dag-pop",style:{animationDelay:"0.65s"},cx:"22",cy:"37",r:"3.5",fill:nt.accent,opacity:"0.35"}),u.jsx("line",{className:"dag-pop",style:{animationDelay:"0.8s"},x1:"25.5",y1:"23.5",x2:"33",y2:"28.5",stroke:nt.warm,strokeWidth:"2",strokeLinecap:"round",strokeDasharray:"3 3"}),u.jsx("circle",{className:"dag-pop",style:{animationDelay:"0.95s"},cx:"36",cy:"30",r:"3.5",fill:nt.warm})]}),u.jsx("h1",{className:"text-4xl font-semibold tracking-tight text-ink mb-2.5",children:"ThoughtDAG"}),u.jsx("p",{className:"text-sm text-ink-muted",children:b("landing.tagline")}),u.jsx("p",{className:"text-xs text-ink-muted mt-1.5 font-medium",children:b("landing.mechanism")})]}),u.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:[u.jsx("textarea",{value:w,onChange:ee=>_(ee.target.value),onKeyDown:Qe,onPaste:ee=>{if(ee.clipboardData.getData("text/plain").trim())return;const ge=Array.from(ee.clipboardData.items).filter(_e=>_e.kind==="file").map(_e=>_e.getAsFile()).filter(Boolean);ge.length&&me(ge)},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}),U.length>0&&u.jsx("div",{className:"flex flex-wrap gap-2 mt-2 pb-1",children:U.map(ee=>u.jsxs("div",{className:"flex items-center gap-1.5 bg-wash rounded-lg px-2.5 py-1.5 group",children:[ee.thumbnailUrl?u.jsx("img",{src:ee.thumbnailUrl,className:"w-6 h-6 rounded object-cover",alt:ee.name}):u.jsx("span",{className:"text-xs",children:u.jsx(gi,{size:16,strokeWidth:1.75})}),u.jsx("span",{className:"text-xs text-ink-muted max-w-[100px] truncate",children:ee.name}),ee.isExtracting&&u.jsx("span",{className:"text-2xs text-accent",children:u.jsx(Xn,{className:"animate-spin",size:12,strokeWidth:1.75})}),ee.numPages!=null&&u.jsxs("span",{className:"text-2xs text-ink-faint",children:[ee.numPages,"p"]}),u.jsx("button",{onClick:()=>Y(ge=>ge.filter(_e=>_e.id!==ee.id)),className:"text-ink-faint hover:text-red-500 text-xs opacity-0 group-hover:opacity-100 transition-opacity",children:u.jsx(bn,{size:14,strokeWidth:1.75})})]},ee.id))}),M&&u.jsxs("div",{className:"space-y-1 mt-2",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx("span",{className:"text-xs text-ink-muted font-medium",children:b("landing.roleLabel")}),u.jsx("button",{onClick:()=>{N(!1),D("")},className:"text-xs text-ink-faint hover:text-ink-muted",children:u.jsx(bn,{size:14,strokeWidth:1.75})})]}),u.jsx("textarea",{value:O,onChange:ee=>D(ee.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}),u.jsx(NN,{onPick:D})]}),u.jsxs("div",{className:"flex items-center justify-end mt-2 gap-2",children:[u.jsx(Wb,{}),u.jsx("button",{onClick:()=>N(!M),title:b("landing.roleTrayTitle"),className:`rounded-full w-8 h-8 flex items-center justify-center transition-colors shrink-0 ${M||O?"text-accent bg-accent/10 hover:bg-accent/20":"text-ink-faint hover:text-ink-muted hover:bg-line"}`,children:u.jsx(pP,{size:16,strokeWidth:1.75})}),u.jsx("button",{onClick:()=>K.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:u.jsx(xi,{size:16,strokeWidth:1.75})}),u.jsx("input",{ref:K,type:"file",multiple:!0,accept:_d,className:"hidden",onChange:ee=>{me(ee.target.files||[]),ee.target.value=""}}),u.jsx("button",{onClick:Mn,disabled:!w.trim()||U.some(ee=>ee.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:U.some(ee=>ee.isExtracting)?b("landing.extracting"):b("landing.send")})]})]}),u.jsxs("div",{onClick:()=>F.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 ${Z?"border-accent bg-accent/5 ring-2 ring-accent/20":"border-line hover:border-accent/40 hover:bg-accent/5"}`,children:[u.jsxs("div",{className:"flex items-center justify-center gap-2 text-sm text-ink-muted font-medium",children:[u.jsx(So,{size:15,strokeWidth:1.75,className:"text-accent"})," ",b("landing.docStart")]}),u.jsx("p",{className:"text-2xs text-ink-faint mt-1.5",children:b("landing.docFormats")}),u.jsx("p",{className:"text-2xs text-ink-faint mt-0.5",children:b("landing.docPrivacy")})]}),!!window.desktopSessions&&u.jsxs("button",{onClick:()=>B(!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:[u.jsxs("div",{className:"flex items-center justify-center gap-2 text-sm text-ink-muted font-medium",children:[u.jsx(Hj,{size:15,strokeWidth:1.75,className:"text-accent shrink-0"}),u.jsx("span",{children:b("landing.atlasStart")}),u.jsx(Rj,{size:13,strokeWidth:1.75,className:"text-accent shrink-0"})]}),u.jsx("p",{className:"text-2xs text-ink-faint mt-1.5",children:b("landing.atlasDesc")})]}),u.jsx("input",{ref:F,type:"file",multiple:!0,accept:_d,className:"hidden",onChange:ee=>{Ve(ee.target.files||[]),ee.target.value=""}}),R&&u.jsx(jN,{onClose:()=>B(!1),onSwitched:()=>{B(!1),kt()}}),(!rt||(rt.models?.length??0)===0)&&u.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:[u.jsxs("div",{className:"flex items-center justify-center gap-2 text-sm text-ink-muted font-medium",children:[u.jsx(Ad,{size:15,strokeWidth:1.75,className:"text-accent shrink-0"})," ",b("landing.quickTitle")]}),u.jsx("p",{className:"text-2xs text-ink-faint mt-1.5",children:b("landing.quickDesc")}),u.jsxs("div",{className:"mt-2.5 flex items-center justify-center flex-wrap gap-2",children:[Oe==="zh"&&u.jsx("button",{onClick:()=>{xe.getState().setApiKeyPresetHint("zhipu"),xe.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")}),u.jsx("button",{onClick:()=>{zN()},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")}),u.jsx("button",{onClick:()=>xe.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")})]}),u.jsx("button",{onClick:()=>xe.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")})]}),u.jsx("div",{className:"grid grid-cols-3 gap-3 mt-6",children:[{icon:zi,title:"landing.feature1.title",desc:"landing.feature1.desc"},{icon:Ww,title:"landing.feature2.title",desc:"landing.feature2.desc"},{icon:c7,title:"landing.feature3.title",desc:"landing.feature3.desc"}].map(({icon:ee,title:ge,desc:_e})=>u.jsxs("div",{className:"bg-card/60 backdrop-blur border border-line rounded-xl px-4 py-3.5",children:[u.jsx(ee,{size:16,strokeWidth:1.75,className:"text-accent mb-2"}),u.jsx("h3",{className:"text-xs font-semibold text-ink mb-1",children:b(ge)}),u.jsx("p",{className:"text-2xs text-ink-faint leading-relaxed",children:b(_e)})]},ge))}),u.jsxs("div",{className:"text-center mt-6 flex items-center justify-center gap-5",children:[u.jsxs("button",{onClick:ht,className:"text-xs text-accent hover:text-accent-strong font-medium transition-colors inline-flex items-center gap-1.5",children:[u.jsx(Ww,{size:14,strokeWidth:1.75})," ",b("landing.loadExample")]}),u.jsxs("button",{onClick:()=>y(!0),className:"text-xs text-ink-muted hover:text-accent transition-colors inline-flex items-center gap-1.5",children:[u.jsx(Bw,{size:14,strokeWidth:1.75})," ",b("landing.howItWorks")]})]})]})]}),!vt&&u.jsx(Mne,{onSwitched:kt}),(G||Be)&&!vt&&u.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:[!Be&&u.jsx("button",{onClick:()=>zt(ie(null)),draggable:!0,onDragStart:ee=>{ee.dataTransfer.setData("application/thoughtdag-content","ask"),ee.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:u.jsx(sf,{size:17,strokeWidth:1.75})}),u.jsx("button",{onPointerDown:ee=>Bt(ee,ge=>Qr("note",ie(ge))),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:u.jsx(Hi,{size:17,strokeWidth:1.75})}),u.jsx("button",{onPointerDown:ee=>Bt(ee,ge=>Qr("file",ie(ge))),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:u.jsx(xi,{size:17,strokeWidth:1.75})}),u.jsx("button",{onPointerDown:ee=>Bt(ee,ge=>at(ie(ge))),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:u.jsx(Ex,{size:17,strokeWidth:1.75})})]}),vt&&u.jsxs("div",{className:"absolute top-4 z-10 flex gap-1.5 items-center transition-[right] duration-200",style:{right:ft?wn+rd+12:16},children:[u.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:[u.jsx(Td,{size:14,strokeWidth:1.75})," ",b("viewer.badge")]}),u.jsx("button",{onClick:()=>C(!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:u.jsx(Cf,{size:15,strokeWidth:1.75})}),u.jsx(aE,{}),u.jsx("button",{onClick:()=>cf(),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:u.jsx(Ed,{size:15,strokeWidth:1.75})}),u.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")})]}),!vt&&u.jsxs("div",{className:"absolute top-4 z-10 flex gap-1.5 items-center transition-[right] duration-200",style:{right:ft?wn+rd+12:16},children:[Be&&u.jsxs(u.Fragment,{children:[u.jsxs("button",{onClick:()=>Xe("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:[u.jsx(sf,{size:14,strokeWidth:1.75})," ",b("paradigm.addHuman")]}),u.jsxs("button",{onClick:()=>Xe("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:[u.jsx(Nd,{size:14,strokeWidth:1.75})," ",b("paradigm.addPrompt")]}),u.jsxs("button",{onClick:()=>{ze()},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")]})]}),!Be&&u.jsx(CN,{}),!G&&u.jsx("button",{onClick:()=>xe.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:u.jsx(Ad,{size:15,strokeWidth:1.75})}),It>0&&!Be&&u.jsxs("button",{onClick:()=>{const{nodes:ee,edges:ge,staleIds:_e}=oe.getState(),He=_e.reduce((Se,Ye)=>{const Ze=ee.map(Ht=>Ht.id===Ye?{...Ht,data:{...Ht.data,question:"",response:""}}:Ht),{layerTokens:xt}=yr(Ye,Ze,ge),Mt=ee.find(Ht=>Ht.id===Ye)?.data.question??"";return Se+xt.material+xt.reference+xt.chain+$n(Mt)},0);Ts({title:b("replay.confirmTitle"),message:Ue(b("replay.confirmMsg"),{n:It,tok:He.toLocaleString()}),confirmLabel:b("replay.confirmBtn")}).then(Se=>{Se&&oe.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:[u.jsx(JP,{size:14,strokeWidth:1.75})," ",It]}),G&&Nt.length>0&&u.jsxs("div",{ref:Jt,className:"relative",children:[u.jsx("button",{onClick:()=>Lt(ee=>!ee),className:`bg-card/90 backdrop-blur border rounded-lg w-8 h-8 flex items-center justify-center shadow-sm transition-colors ${ot?"border-accent/40 text-accent":"border-line text-ink-faint hover:bg-wash"}`,title:b("toolbar.frames"),children:u.jsx(Ex,{size:15,strokeWidth:1.75})}),ot&&u.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:Nt.map(ee=>u.jsxs("button",{onClick:()=>{Lt(!1),q.current?.fitBounds({x:ee.position.x,y:ee.position.y,width:ee.width??640,height:ee.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:[u.jsx("span",{className:`w-2.5 h-2.5 rounded-sm shrink-0 ${(ad[ee.data.frameColor??"gray"]??ad.gray).dot}`}),u.jsx("span",{className:"truncate",children:ee.data.question||b("frame.untitled")})]},ee.id))})]}),G&&u.jsx("button",{onClick:()=>C(!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:u.jsx(Cf,{size:15,strokeWidth:1.75})}),u.jsx(aE,{}),G&&!Be&&u.jsx(nne,{showTrigger:!1,openPing:he,onLocate:ee=>{const ge=oe.getState().nodes.find(_e=>_e.id===ee);ge&&(d(ee),Te(ge,{zoom:1}))}}),We&&!vt&&u.jsxs("button",{onClick:()=>xe.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:Ue(b("condense.entryBuilding"),{i:String(Le.current),n:String(Le.total)}),"data-condense-entry":!0,children:[u.jsx(Xn,{size:14,strokeWidth:1.75,className:"animate-spin"}),u.jsxs("span",{className:"text-2xs font-mono",children:[Le.current,"/",Le.total]})]}),Lm&&u.jsx("button",{onClick:()=>xe.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:u.jsx(n7,{size:15,strokeWidth:1.75})}),u.jsxs("div",{ref:En,className:"relative",children:[u.jsx("button",{onClick:()=>kn(ee=>!ee),className:`bg-card/90 backdrop-blur border rounded-lg w-8 h-8 flex items-center justify-center shadow-sm transition-colors ${Xt?"border-accent/40 text-accent":"border-line text-ink-faint hover:bg-wash"}`,title:b("toolbar.more"),"data-toolbar-more":!0,children:u.jsx(Z8,{size:15,strokeWidth:1.75})}),Xt&&u.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:[G&&u.jsxs("button",{onClick:()=>{kn(!1),T(!k)},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(k?"toolbar.showAnnotations":"toolbar.hideAnnotations"),children:[u.jsx(Hi,{size:14,strokeWidth:1.75,className:`shrink-0 ${k?"text-accent":"text-ink-faint"}`})," ",b(k?"toolbar.menuAnnotationsShow":"toolbar.menuAnnotationsHide")]}),G&&u.jsxs("button",{onClick:()=>{kn(!1),Ts({title:b("confirm.relayoutTitle"),message:b("confirm.relayoutMsg"),confirmLabel:b("toolbar.relayout")}).then(ee=>{ee&&(x(),setTimeout(()=>q.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:[u.jsx(KP,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("toolbar.relayout")]}),X>0&&u.jsxs("button",{onClick:()=>{kn(!1),xe.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:[u.jsx(Sd,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",Ue(b("hlov.entry"),{n:X})]}),P>0&&u.jsxs("button",{onClick:()=>{kn(!1),xe.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:[u.jsx(xi,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",Ue(b("matov.entry"),{n:P})]}),G&&u.jsx("div",{className:"border-t border-line/60 my-1"}),G&&!Be&&!vt&&u.jsxs("button",{onClick:()=>{kn(!1),xe.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:[u.jsx(cm,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("condense.title"),"…"]}),G&&!Be&&u.jsxs("button",{onClick:()=>{kn(!1),jt(ee=>ee+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:[u.jsx(u7,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("toolbar.menuDiagnose")]}),G&&!Be&&u.jsxs("button",{onClick:()=>{kn(!1),(async()=>{const{nodes:ee,edges:ge}=oe.getState(),{confirmIfSensitive:_e}=await Kt(async()=>{const{confirmIfSensitive:Se}=await import("./sensitive-scan-BjlPCfxy.js");return{confirmIfSensitive:Se}},[]);if(!await _e(ee))return;const He=await NB(ee,ge);await navigator.clipboard.writeText(He).catch(()=>{}),xe.getState().setShareDialogUrl(He)})()},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:[u.jsx(Nz,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("toolbar.menuShare")]}),G&&u.jsxs("button",{onClick:()=>{kn(!1),Be?iU():cf()},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:[u.jsx(Ed,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b(Be?"paradigm.exportParadigm":"switcher.exportBackup")]}),ne&&u.jsxs("button",{onClick:()=>{kn(!1),uU()},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:[u.jsx(gi,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("toolbar.exportEvents")]}),G&&u.jsx("div",{className:"border-t border-line/60 my-1"}),u.jsxs("div",{className:"px-3 pt-2 pb-1","data-appearance-lighting":!0,children:[u.jsx("div",{className:"text-2xs text-ink-faint mb-1.5",children:b("appearance.lighting")}),u.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(([ee,ge],_e)=>u.jsx("button",{onClick:()=>vs.getState().setLighting(ee),className:`flex-1 px-1 py-1.5 transition-colors ${_e>0?"border-l border-line":""} ${se===ee?"bg-accent/10 text-accent font-medium":"text-ink-muted hover:bg-wash"}`,children:ge},ee))})]}),u.jsxs("div",{className:"px-3 pt-1 pb-2","data-appearance-paper":!0,children:[u.jsx("div",{className:"text-2xs text-ink-faint mb-1.5",children:b("appearance.paper")}),u.jsx("div",{className:"flex rounded-lg border border-line overflow-hidden text-2xs",children:[["plain",b("appearance.plain")],["grid",b("appearance.grid")]].map(([ee,ge],_e)=>u.jsx("button",{onClick:()=>vs.getState().setPaper(ee),className:`flex-1 px-1 py-1.5 transition-colors ${_e>0?"border-l border-line":""} ${H===ee?"bg-accent/10 text-accent font-medium":"text-ink-muted hover:bg-wash"}`,children:ge},ee))})]}),u.jsx("div",{className:"border-t border-line/60 my-1"}),u.jsxs("button",{onClick:()=>{kn(!1),xe.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:[u.jsx(Fj,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("memory.managerTitle")]}),u.jsxs("button",{onClick:()=>{kn(!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:[u.jsx(Bw,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("landing.howItWorks")]}),u.jsxs("button",{onClick:()=>{kn(!1),xe.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:[u.jsx(_b,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("releaseNotes.entry")]})]})]}),u.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:u.jsx(h7,{size:16,strokeWidth:1.75})}),u.jsx("button",{onClick:l,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:u.jsx(gz,{size:16,strokeWidth:1.75})})]}),Rt&&!vt&&u.jsx(qte,{}),u.jsx(ene,{open:A,onClose:()=>C(!1),onLocate:ee=>{const ge=oe.getState().nodes.find(_e=>_e.id===ee);ge&&(d(ee),Te(ge,{zoom:1}))}}),$t&&u.jsx(Vte,{x:$t.x,y:$t.y,nodeId:$t.nodeId,onClose:()=>vn(null)}),u.jsx($te,{onLocate:ee=>{const ge=oe.getState().nodes.find(_e=>_e.id===ee);ge&&(d(ee),Te(ge,{zoom:1}))}}),u.jsx(Pae,{onLocate:ee=>{const ge=oe.getState().nodes.find(_e=>_e.id===ee);ge&&(d(ee),Te(ge,{zoom:1}))}}),u.jsx(Gte,{onLocate:ee=>{const ge=oe.getState().nodes.find(_e=>_e.id===ee);ge&&(d(ee),Te(ge,{zoom:1}))}}),un&&u.jsx("div",{className:"fixed z-50 bg-card border border-line rounded-xl shadow-lg py-1 min-w-[120px]",style:{left:un.x,top:un.y},children:u.jsxs("button",{onClick:()=>lr(un.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:[u.jsx(Fa,{size:14,strokeWidth:1.75}),b("canvas.deleteEdge")]})})]}),u.jsx(kae,{onFocusSegment:ee=>{const ge=q.current,_e=oe.getState().nodes.filter(Ht=>ee.includes(Ht.id));if(!ge||_e.length===0)return;const He=_e.map(Ht=>Ht.position.x),Se=_e.map(Ht=>Ht.position.y),Ye=Math.min(...He),Ze=Math.min(...Se),xt=Math.max(...He)+520-Ye,Mt=Math.max(...Se)+240-Ze;ge.fitBounds({x:Ye,y:Ze,width:xt+700,height:Mt},{duration:350,padding:.15})}}),ft&&u.jsx(Fte,{onFocusNode:ee=>{const ge=e.find(_e=>_e.id===ee);ge&&Te(ge,{duration:300})}}),u.jsx(fne,{onLocate:ee=>{const ge=oe.getState().nodes.find(_e=>_e.id===ee);ge&&(d(ee),Te(ge,{zoom:1}))}})]})}function qae({panelShiftWidth:e}){const t=Zd(),n=Ft(),a=kl(),r=oe(d=>d.nodes.length),s=oe(d=>d.nodes),l=j.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(vt||t==="work"||r<2)return null;const c=()=>{if(!l)return;xe.getState().setBeaconNodeId(null);const{node:d}=l;a.setCenter(d.position.x+260,d.position.y+110,{zoom:1,duration:1100}),window.setTimeout(()=>{oe.getState().setSelectedNodeId(d.id),xe.getState().setPanelOpen(!0),window.setTimeout(()=>{a.setCenter(d.position.x+260+Xf(d.id)/2,d.position.y+110,{zoom:1,duration:300})},60)},1150),window.setTimeout(()=>{Ke("success",n("continue.arrived"),12e3,{label:n("continue.summarize"),run:()=>{MN(d.id)}})},1550)};return u.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:[u.jsxs("button",{onClick:()=>xe.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:[u.jsx(Mb,{size:16,strokeWidth:1.75})," ",n("tmap.export")]}),l&&u.jsxs("button",{onClick:c,onMouseEnter:()=>xe.getState().setBeaconNodeId(l.node.id),onMouseLeave:()=>xe.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:[u.jsx(yz,{size:16,strokeWidth:1.75})," ",n("continue.button")]})]})}function Wae(){const e=Zd(),t=ln(n=>n.transform[2]);return j.useEffect(()=>{document.querySelector(".react-flow")?.setAttribute("data-zoom-tier",e)},[e]),j.useEffect(()=>{document.querySelector(".react-flow")?.style.setProperty("--tdag-zoom",String(t))},[t]),null}xte();const Vae="/thoughtdag/api";window.desktopSessions||wH(Vae);vt?_B():(V7(),navigator.storage?.persist&&navigator.storage.persist(),Kt(()=>Promise.resolve().then(()=>dae),void 0).then(e=>e.bootAutoBackup()));Kt(()=>import("./update-check-BCL5Q3Vc.js"),[]).then(e=>e.bootUpdateCheck());window.addEventListener("hashchange",()=>{window.location.hash.startsWith("#view=")!==vt&&window.location.reload()});s_.createRoot(document.getElementById("root")).render(u.jsx(j.StrictMode,{children:u.jsx(Uae,{})}));export{Bd as A,nr as B,uB as C,$ae as D,eT as E,hm as F,Hb as G,gm as H,Kt as _,Ie as a,oe as b,Cn as c,As as d,vt as e,Ue as f,G7 as g,Ss as h,Zae as i,zr as j,Pc as k,pm as l,Dx as m,KH as n,In as o,ni as p,YH as q,$H as r,No as s,Ke as t,xe as u,X7 as v,Ts as w,Kae as x,Yae as y,Gae as z};