dsh-thoughtdag 0.4.11 → 0.4.12

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 (21) hide show
  1. package/README.md +7 -0
  2. package/dist-app/assets/{canonical-Cw94rYnE.js → canonical-DccXDqkX.js} +2 -2
  3. package/dist-app/assets/{canvas-record-BYGoWCSi.js → canvas-record-Dw4tjwhH.js} +1 -1
  4. package/dist-app/assets/{claude-code-session-D7_MMzYc.js → claude-code-session-ON4i33o-.js} +1 -1
  5. package/dist-app/assets/{codex-session-DVFc0JXs.js → codex-session-BWQTXLRK.js} +1 -1
  6. package/dist-app/assets/{dsh-session-BsZRbFip.js → dsh-session-DoRNUaQq.js} +1 -1
  7. package/dist-app/assets/{experiment-loop-C9Q1W_wR.js → experiment-loop-BuZFR0si.js} +1 -1
  8. package/dist-app/assets/{index-Dyq9QwYZ.js → index-CTQSx_k0.js} +3 -3
  9. package/dist-app/assets/{index-z0ZTt6U1.js → index-DD461-fW.js} +1 -1
  10. package/dist-app/assets/{index-BEqQ5wV9.js → index-DaODh24h.js} +1 -1
  11. package/dist-app/assets/{index-Y8weIZcr.js → index-DwwxoOcO.js} +12 -12
  12. package/dist-app/assets/{live-mirror-BlUlIINC.js → live-mirror-D3u92mbO.js} +2 -2
  13. package/dist-app/assets/{pi-session-wpL6N_gb.js → pi-session-IbIlOArr.js} +1 -1
  14. package/dist-app/assets/{sensitive-scan-Kz-yplyP.js → sensitive-scan-C6YN1rzZ.js} +1 -1
  15. package/dist-app/assets/{session-handoff-BLHyTTl7.js → session-handoff-Fpl3jes7.js} +2 -2
  16. package/dist-app/assets/{shared-BoxE2SdQ.js → shared-DCtLTsEN.js} +1 -1
  17. package/dist-app/assets/{turndown-plugin-gfm.cjs-2uYHu5V7.js → turndown-plugin-gfm.cjs-CqvfCrbV.js} +1 -1
  18. package/dist-app/assets/{update-check-B1wesdxM.js → update-check-B1kgBEyl.js} +1 -1
  19. package/dist-app/index.html +1 -1
  20. package/lib/index.js +26 -8
  21. 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 S of k){const w=S.trim();if(!w.startsWith("data: "))continue;const C=w.slice(6);if(C==="[DONE]")continue;let T;try{T=JSON.parse(C)}catch{continue}if(T.error){const M=typeof T.error=="string"?T.error:T.error.message;throw new Error(M||"Upstream stream error")}const N=T.choices?.[0];if(!N)continue;const D=N.delta;D?.content&&(p+=D.content,a(D.content));const O=D?.reasoning??D?.reasoning_content;O&&r(O);for(const M of D?.annotations??[]){const _=M.url_citation;_?.url&&!s.has(_.url)&&s.set(_.url,{title:_.title||_.url,url:_.url,media:"Web"})}N.finish_reason&&(x=N.finish_reason)}}return{text:p,finishReason:x}}async function SH(e,t,n,a,r,s,o,c){const d=JS(n,s),h=Kb(e.baseURL)&&c!==!1,m=new Map;let p="",x="";const b=k=>{p+=k,a(k,p)},y=k=>{x+=k,o?.onReasoning?.(k,x)};try{let k=await M5(e,h?`${t}:online`:t,d,b,y,m,r);if(h&&p.length===0&&(k=await M5(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&&o?.onSources?.([...m.values()]),p}catch(k){throw e7(k)}}async function TH(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:JS(n,a)})});if(!r.ok){const o=await r.json().catch(()=>null);throw new Error(o?.error?.message||`HTTP ${r.status}`)}return(await r.json()).choices?.[0]?.message?.content??""}catch(r){throw e7(r)}}const AH=`${$i}/api/claude`,t7=()=>{const e=li();return e.length>0?e:void 0},NH=`${$i}/api/stream`,CH=`${$i}/api/pdf-extract`,_H=`${$i}/api/approvals`;async function MH(e,t){const n=e.id,a=typeof t=="string"?{confirmed:t!=="rejected",...t==="allowed-session"?{scope:"session"}:{}}:t;if(e.channel?.runId&&window.desktopAgents)try{return await window.desktopAgents.answer(e.channel.runId,n,a)}catch{return!1}const r="confirmed"in a&&a.confirmed?"allowed-once":"rejected";try{return(await fetch(`${_H}/${encodeURIComponent(n)}`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"same-origin",body:JSON.stringify({outcome:r})})).ok}catch{return!1}}async function IH(e){const t=await fetch(CH,{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(kl(n,`HTTP ${t.status}`))}return t.json()}async function DH(e){try{const t=await fetch(`${$i}/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(kl(n,`HTTP ${t.status}`))}return t.json()}catch(t){throw Qb(t)}}function Qb(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 n7(e,t){if(!t?.length)return t;const n=await Us(),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 a7(e,t){if(!t?.length)return;const n=await Us(),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(De("error.textOnlyModelImages"))}async function Bo(e,t,n){const a=n||pe.getState().selectedModel||void 0;t=await n7(a,t);const r=Xb();if(r&&a)return await a7(a,t),TH(r,a,e,t);try{const s=await fetch(AH,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({messages:e,images:t?.length?t:void 0,model:n||pe.getState().selectedModel||void 0,providers:t7()})});if(!s.ok){const c=await s.json().catch(()=>({error:"Unknown error"}));throw new Error(kl(c,`HTTP ${s.status}`))}return(await s.json()).text}catch(s){throw Qb(s)}}async function r7(e,t,n,a,r,s,o,c){const d=o||pe.getState().selectedModel||void 0;if(d&&Fd(d)&&window.desktopAgents)return r?.onDispatch?.({messages:e,images:a??[],model:d,toolPrefs:s??{},lane:"proxy"}),RU(e,t,n,a,r,d,c?.cwd?{cwd:c.cwd,sessionPath:c.sessionPath,forkEntryId:c.forkEntryId,continue:c.continue}:void 0,c?.nodeId);a=await n7(d,a);let h=!1;const m={...r,onRerouted:(k,S)=>{h=!0,r?.onRerouted?.(k,S)}},p=async(k,S)=>{const w=Xb();return w&&d?(await a7(d,k),r?.onDispatch?.({messages:e,images:k??[],model:d,toolPrefs:s??{},lane:"direct"}),SH(w,d,e,S,n,k,m,s?.web)):(r?.onDispatch?.({messages:e,images:k??[],model:d??"",toolPrefs:s??{},lane:"proxy"}),y(k,S))},x=d?XB(d):void 0,b=!!d&&li().some(k=>k.models.some(S=>S.id===d));if(a?.length&&d&&b&&x!==!1){const k=d.split("/").pop()??d,S=(C,T)=>{QB(d,C)&&(s0(li()).then(Tl).catch(()=>{}),Ye("info",He(De(T),{m:k})))};let w=!1;try{const C=await p(a,(T,N)=>{w=!0,t(T,N)});return x===void 0&&!h&&C.trim()&&S(!0,"toast.visionLearnedTrue"),C}catch(C){if(C instanceof DOMException&&C.name==="AbortError"||w||h)throw C;if(x===!0){const N=C instanceof Error?C.message:String(C);throw new Error(`${N} ${De("error.visionDeclaredHint")}`)}const T=await p(void 0,t);return T.trim()&&S(!1,"toast.visionLearnedFalse"),T}}return p(a,t);async function y(k,S){try{const w=await fetch(NH,{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,...pe.getState().searchEnginePref!=="server"?{searchEngine:pe.getState().searchEnginePref}:{},...pe.getState().anysearchKey?{anysearchKey:pe.getState().anysearchKey}:{},model:o||pe.getState().selectedModel||void 0,providers:t7(),...c?{harness:c}:{}}),signal:n});if(!w.ok){const M=await w.json().catch(()=>({error:"Unknown error"}));throw new Error(kl(M,`HTTP ${w.status}`))}const C=w.body.getReader(),T=new TextDecoder;let N="",D="",O="";for(;;){const{done:M,value:_}=await C.read();if(M)break;N+=T.decode(_,{stream:!0});const R=N.split(`
47
47
  `);N=R.pop()||"";for(const G of R){const B=G.trim();if(!B||!B.startsWith("data: "))continue;const $=B.slice(6);if($!=="[DONE]")try{const Z=JSON.parse($);if(Z.error)throw new Error(kl(Z.error,"Upstream stream error"));Z.text&&(D+=Z.text,S(Z.text,D)),Z.reasoning&&(O+=Z.reasoning,m.onReasoning?.(Z.reasoning,O)),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&&(Ye("info",He(De("toast.visionRerouted"),{from:Z.rerouted.from,to:Z.rerouted.to}),7e3),m.onRerouted?.(Z.rerouted.from,Z.rerouted.to)),Z.imageFallback?.model&&(Ye("info",He(De("toast.imagesAsText"),{model:Z.imageFallback.model}),9e3),m.onImageFallback?.(Z.imageFallback.model))}catch(Z){if(Z instanceof Error&&Z.message!==$)throw Z}}}return D}catch(w){throw Qb(w)}}}const Bx="att-content:",i7=e=>`${Bx}${e}`,s7=e=>e.type==="application/pdf"&&!!e.content&&!e.contentInVault;async function Zb(e){return s7(e)?(await Ur(i7(e.id),e.content),{...e,content:"",contentInVault:!0}):e}async function Jb(e){return e.contentInVault?await El(i7(e.id))??"":e.content}async function e2(e){const t=[];for(const n of e){const a=n.data.attachments;if(!a?.some(s=>s.contentInVault)){t.push(n);continue}const r=[];for(const s of a){if(!s.contentInVault){r.push(s);continue}const o=await Jb(s),c={...s,content:o};delete c.contentInVault,r.push(c)}t.push({...n,data:{...n.data,attachments:r}})}return t}async function Sm(e){const t=[];for(const n of e){const a=n.data.attachments;if(!a?.some(s7)){t.push(n);continue}const r=[];for(const s of a)r.push(await Zb(s));t.push({...n,data:{...n.data,attachments:r}})}return t}async function o7(e){const t=await YS();let n=0;for(const a of t)typeof a!="string"||!a.startsWith(Bx)||e.has(a.slice(Bx.length))||(await qc(a),n++);return n}const OH=Object.freeze(Object.defineProperty({__proto__:null,gcVault:o7,inlineVaultedContent:e2,internAttachment:Zb,internNodes:Sm,loadAttachmentContent:Jb},Symbol.toStringTag,{value:"Module"}));function RH(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 LH=/\.(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,jH=/\.x?html?$/i,PH=/\.(pptx?|key|odp|doc|rtf|odt|xlsx?|numbers|ods)$/i,Bd="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 Ac(e){return`${e.name}|${e.size}|${e.content?.substring(0,100)}`}function zH(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"),o=e.type==="text/html"||jH.test(e.name),c=e.type.startsWith("text/")||LH.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 Tt(()=>import("./index-z0ZTt6U1.js").then(x=>x.i),[])).extractRawText({arrayBuffer:h});t({id:n,name:e.name,type:"text/plain",size:e.size,addedAt:a,content:p.value.trim()})}catch{t(null)}}):o?e.text().then(h=>{t({id:n,name:e.name,type:"text/html",size:e.size,addedAt:a,content:h})}):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 I5(e){const[t,n]=await Promise.all([Tt(()=>import("./pdf-gh-BrLFn.js"),[]),Tt(()=>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 BH=150;async function D5(e){const t=BH/72,n=[];for(let a=1;a<=e.numPages;a++){const r=document.createElement("canvas");try{const s=await e.getPage(a),o=s.getViewport({scale:t});r.width=Math.ceil(o.width),r.height=Math.ceil(o.height);const c=r.getContext("2d");if(!c)throw new Error("no 2d context");await s.render({canvasContext:c,viewport:o}).promise}catch{r.width=8,r.height=8}n.push(r.toDataURL("image/png").split(",")[1])}return n}async function o0(e,t){if(PH.test(e.name)){Ye("info",`${e.name}: ${De("content.officeExportHint")}`);return}const n=await zH(e);if(!n)return;if(n.type==="text/html"){t.add({...n,isExtracting:!0});try{const{extractHtmlMaterial:r}=await Tt(async()=>{const{extractHtmlMaterial:o}=await Promise.resolve().then(()=>d9);return{extractHtmlMaterial:o}},void 0),s=await r(n.content);t.update(n.id,{extractedText:s.markdown,numPages:s.numPages,isExtracting:!1})}catch{t.update(n.id,{extractedText:RH(n.content),isExtracting:!1})}return}if(n.type!=="application/pdf"){t.add(n);return}const a=await Zb(n);t.add({...a,isExtracting:!0});try{const r=await IH(n.content);if(!r.numPages&&!r.text?.trim())throw new Error("empty extraction result");const s=r.numPages||0;let o=r.images;if(!o?.length)try{const c=await I5(n.content);o=await D5(c),c.destroy()}catch{o=void 0}t.update(n.id,{extractedText:r.text,pageImages:o?.length?o:void 0,numPages:s,renderMode:s>p5?"text-only":"full",isExtracting:!1})}catch{try{const r=await I5(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 o;try{o=await D5(r)}catch{o=void 0}r.destroy(),t.update(n.id,{extractedText:s.join(`
49
+ `).trim()}const LH=/\.(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,jH=/\.x?html?$/i,PH=/\.(pptx?|key|odp|doc|rtf|odt|xlsx?|numbers|ods)$/i,Bd="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 Ac(e){return`${e.name}|${e.size}|${e.content?.substring(0,100)}`}function zH(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"),o=e.type==="text/html"||jH.test(e.name),c=e.type.startsWith("text/")||LH.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 Tt(()=>import("./index-DD461-fW.js").then(x=>x.i),[])).extractRawText({arrayBuffer:h});t({id:n,name:e.name,type:"text/plain",size:e.size,addedAt:a,content:p.value.trim()})}catch{t(null)}}):o?e.text().then(h=>{t({id:n,name:e.name,type:"text/html",size:e.size,addedAt:a,content:h})}):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 I5(e){const[t,n]=await Promise.all([Tt(()=>import("./pdf-gh-BrLFn.js"),[]),Tt(()=>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 BH=150;async function D5(e){const t=BH/72,n=[];for(let a=1;a<=e.numPages;a++){const r=document.createElement("canvas");try{const s=await e.getPage(a),o=s.getViewport({scale:t});r.width=Math.ceil(o.width),r.height=Math.ceil(o.height);const c=r.getContext("2d");if(!c)throw new Error("no 2d context");await s.render({canvasContext:c,viewport:o}).promise}catch{r.width=8,r.height=8}n.push(r.toDataURL("image/png").split(",")[1])}return n}async function o0(e,t){if(PH.test(e.name)){Ye("info",`${e.name}: ${De("content.officeExportHint")}`);return}const n=await zH(e);if(!n)return;if(n.type==="text/html"){t.add({...n,isExtracting:!0});try{const{extractHtmlMaterial:r}=await Tt(async()=>{const{extractHtmlMaterial:o}=await Promise.resolve().then(()=>d9);return{extractHtmlMaterial:o}},void 0),s=await r(n.content);t.update(n.id,{extractedText:s.markdown,numPages:s.numPages,isExtracting:!1})}catch{t.update(n.id,{extractedText:RH(n.content),isExtracting:!1})}return}if(n.type!=="application/pdf"){t.add(n);return}const a=await Zb(n);t.add({...a,isExtracting:!0});try{const r=await IH(n.content);if(!r.numPages&&!r.text?.trim())throw new Error("empty extraction result");const s=r.numPages||0;let o=r.images;if(!o?.length)try{const c=await I5(n.content);o=await D5(c),c.destroy()}catch{o=void 0}t.update(n.id,{extractedText:r.text,pageImages:o?.length?o:void 0,numPages:s,renderMode:s>p5?"text-only":"full",isExtracting:!1})}catch{try{const r=await I5(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 o;try{o=await D5(r)}catch{o=void 0}r.destroy(),t.update(n.id,{extractedText:s.join(`
50
50
 
51
51
  `).trim(),pageImages:o?.length?o:void 0,numPages:r.numPages,renderMode:r.numPages>p5?"text-only":"full",isExtracting:!1})}catch{t.update(n.id,{isExtracting:!1})}}}const Yu="[*_`~()#>\\[\\]|-]*",HH="\\s+(?:(?:\\d{1,3}[.)]|[-*+>|]|#{1,6}|[-:|]{3,})\\s+)*";function t2(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(`${Yu}${HH}${Yu}${s}`):n.push(`${Yu}${s}`),a=!1}try{return new RegExp(Yu+n.join("")+Yu,"g")}catch{return null}}function UH(e,t){const n=t2(t);return n?n.test(e):!1}function gf(e,t){const n=e??[],a=n.filter(r=>UH(t,r.text));return a.length===n.length?n:a}function O5(e){const t=e.data.question.replace(/\s+/g," ").trim();return t.length>60?`${t.slice(0,60)}…`:t}function l7(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,10 +58,10 @@ ${U}`:`[File: ${$.name} — HTML with no extractable text yet]`}),h.push(R($))}e
58
58
  ${$.content}`}),h.push(R($))}if(G.size>0&&B){const $=[...G.entries()].map(([U,q])=>`${U}: ${[...q].join(", ")}`),Z=M.data.agentSession?.cwd??M.data.importSource?.cwd;c.push({role:"user",content:`[Files this turn touched${Z?` in ${Z}`:""} — contents not included] ${$.join("; ")}`}),h.push(R(B))}};for(const M of k)if(!M.data.archived&&(D(M,"material"),M.data.question)){const _=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:_}),h.push({layer:"material",nodeId:M.id,part:"question"})}b("material");for(const M of S)M.source.data.archived||(c.push({role:"user",content:Hd(M)}),h.push({layer:"reference",refSourceId:M.source.id,part:"reference"}));b("reference");for(const M of w)if(!M.data.archived&&(D(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 _=l7(M);c.push({role:"assistant",content:y.has(M.id)?`${qH}
61
- ${_}`:_}),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 O=u7(w,t);return O&&(c.unshift({role:"system",content:O}),h.unshift({layer:"system",part:"role"})),{messages:c,images:d,layerTokens:p,sources:h,imageSources:m}}function L5(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 j5(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 Lr(){return pe.getState().condenseRun.status!=="building"?!1:(Ye("info",De("condense.editLocked")),!0)}const VH=(e,t)=>({history:[{nodes:[],edges:[]}],historyIndex:0,pushHistory:()=>{const{nodes:n,edges:a,history:r,historyIndex:s}=t(),o=r.slice(0,s+1);o.push({nodes:n,edges:a}),o.length>UB&&o.shift(),e({history:o,historyIndex:o.length-1})},undo:()=>{if(Lr())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(Lr())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 d7(e){if(e.data.isCollapsed)return FB;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 Ao(e){return Math.max(e.measured?.height??0,d7(e))}function GH(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),o=a.find(c=>c.source===r.id);if(a=a.filter(c=>c.target!==r.id),!!o)for(const c of s)a.some(d=>d.source===c.source&&d.target===o.target)||a.push({...c,target:o.target})}return a}function ir(e,t){if(e.length===0)return e;const n=new Set(e.filter(P=>["note","file","link","frame"].includes(P.data.stepKind??"")).map(P=>P.id)),a=e.filter(P=>!n.has(P.id)),r=t.filter(P=>!n.has(P.source)&&!n.has(P.target)),s=g5,o=x5,c=b5,d=24,h=r.filter(P=>!P.data?.isCrossLink),m=new Set(h.map(P=>P.target));for(const P of r)P.data?.isCrossLink&&!P.data?.isWatch&&!m.has(P.target)&&(h.push(P),m.add(P.target));const p=new Set(h.map(P=>P.target)),x=a.filter(P=>!p.has(P.id)),b=new Map;for(const P of h){const re=b.get(P.target)||[];re.push(P.source),b.set(P.target,re)}const y=new Map,k=new Map;for(const P of x){const re=t.filter(Te=>Te.target===P.id&&!Te.data?.isCrossLink&&n.has(Te.source)).map(Te=>e.find(ne=>ne.id===Te.source)).filter(Te=>!!Te);if(re.length===0)continue;const fe=re.reduce((Te,ne)=>Te.position.y+Ao(Te)>ne.position.y+Ao(ne)?Te:ne),ge=k.get(fe.id)??0;k.set(fe.id,ge+1),y.set(P.id,{x:fe.position.x-60+ge*(g5+x5),y:fe.position.y+Ao(fe)+b5})}const S=new Map;for(const P of h){const re=S.get(P.source)||[];re.push(P.target),S.set(P.source,re)}const w=(P,re)=>`${P}\0${re}`,C=new Set(r.filter(P=>P.data?.isBranchFromSelection).map(P=>w(P.source,P.target)));function T(P,re){const fe=(S.get(P)||[]).filter(ne=>(re.get(ne)??P)===P),ge=fe.filter(ne=>!C.has(w(P,ne))),Te=fe.filter(ne=>C.has(w(P,ne)));return{continuation:ge[0]??null,regenerates:ge.slice(1),explores:Te}}const N=1e5;function D(P){const re=new Map;let fe=0,ge=N;const Te=new Map,ne=Ae=>Te.get(Ae)??Ae*(s+o);function ke(Ae,Le){if(re.has(Ae))return;re.set(Ae,Le);const{continuation:qe,regenerates:je,explores:et}=T(Ae,P);qe&&ke(qe,Le);for(let Ke=0;Ke<je.length;Ke++){let kt;Le>=N?(kt=ge++,Te.set(kt,ne(Le)+(Ke+1)*(s+o))):(kt=Le+1+Ke,fe=Math.max(fe,kt+1)),ke(je[Ke],kt)}let dt=0;for(const Ke of et){let kt;Le>=N?(kt=ge++,Te.set(kt,ne(Le)+(je.length+1+dt)*(s+o)),dt++):(kt=fe,fe++),ke(Ke,kt)}}for(const Ae of x){const Le=y.get(Ae.id);if(Le){const qe=ge++;Te.set(qe,Le.x),ke(Ae.id,qe)}else{const qe=fe;fe++,ke(Ae.id,qe)}}for(let Ae=0;Ae<a.length;Ae++){let Le=!1;for(const qe of a){if(re.has(qe.id))continue;const je=(b.get(qe.id)||[]).map(et=>re.get(et)).filter(et=>et!==void 0).sort((et,dt)=>et-dt);je.length&&(ke(qe.id,je[Math.floor((je.length-1)/2)]),Le=!0)}if(!Le)break}return{nodeColumn:re,colX:ne}}const O=new Map;for(const[P,re]of b){if(re.length<2)continue;const fe=re.filter(Te=>!C.has(w(Te,P))),ge=fe.length?fe:re;O.set(P,ge[0])}const{nodeColumn:M,colX:_}=D(O),R=new Map;for(const P of a)R.set(P.id,Ao(P));const G=new Map,B=new Set,$=[...x.map(P=>P.id)];for(const P of $){const re=M.get(P)??0,fe=y.get(P);G.set(P,{x:_(re),y:fe?.y??0}),B.add(P)}for(;$.length>0;){const P=$.shift(),re=G.get(P),fe=R.get(P)||220,{continuation:ge,regenerates:Te,explores:ne}=T(P,O);if(ge&&!B.has(ge)){B.add(ge);const Ae=M.get(ge)??0;G.set(ge,{x:_(Ae),y:re.y+fe+c}),$.push(ge)}const ke=re.y+fe+c;for(const Ae of Te){if(B.has(Ae))continue;B.add(Ae);const Le=M.get(Ae)??0;G.set(Ae,{x:_(Le),y:ke}),$.push(Ae)}for(const Ae of ne){if(B.has(Ae))continue;B.add(Ae);const Le=M.get(Ae)??0;G.set(Ae,{x:_(Le),y:re.y+fe*.25}),$.push(Ae)}}for(let P=0;P<a.length;P++){let re=!1;for(const fe of a){if(G.has(fe.id))continue;const ge=(b.get(fe.id)||[]).filter(ne=>G.has(ne));if(!ge.length)continue;const Te=Math.max(...ge.map(ne=>G.get(ne).y+(R.get(ne)||220)));G.set(fe.id,{x:_(M.get(fe.id)??0),y:Te+c}),re=!0}if(!re)break}for(const P of a)G.has(P.id)||G.set(P.id,{x:0,y:0});for(let P=0;P<5;P++){let re=!1;for(const fe of a){const ge=G.get(fe.id);if(!ge)continue;const Te=(b.get(fe.id)||[]).filter(Le=>G.has(Le));if(Te.length<2)continue;const ne=Te.filter(Le=>!C.has(`${Le}\0${fe.id}`)),ke=Te.filter(Le=>C.has(`${Le}\0${fe.id}`));let Ae=-1/0;for(const Le of ne)Ae=Math.max(Ae,G.get(Le).y+(R.get(Le)||220)+c);for(const Le of ke)Ae=Math.max(Ae,G.get(Le).y);if(Ae>-1/0&&ge.y<Ae){const Le=Ae-ge.y;ge.y=Ae;for(const qe of new Set(Mo(fe.id,h))){const je=G.get(qe);je&&(je.y+=Le)}re=!0}}if(!re)break}const Z=new Map;for(const P of a){const re=M.get(P.id)??0,fe=Z.get(re)||[];fe.push(P.id),Z.set(re,fe)}for(let P=0;P<5;P++){let re=!1;for(const[,fe]of Z){fe.sort((ge,Te)=>G.get(ge).y-G.get(Te).y);for(let ge=1;ge<fe.length;ge++){const Te=fe[ge-1],ne=fe[ge],ke=G.get(Te),Ae=G.get(ne),Le=R.get(Te)||220,qe=ke.y+Le+d;if(Ae.y<qe){const je=qe-Ae.y;Ae.y=qe,re=!0;for(const et of new Set(Mo(ne,h))){const dt=G.get(et);dt&&(dt.y+=je)}}}}if(!re)break}const U=8e3,q=180,H=e.filter(P=>P.data.stepKind==="note"&&P.data.importSource),V=new Set(t.filter(P=>H.some(re=>re.id===P.source)).map(P=>P.target));for(const P of x){const re=[];let fe=P.id,ge=!0;for(;fe;){re.push(fe);const et=S.get(fe)||[];if(et.length>1){ge=!1;break}fe=et[0]}if(!ge||re.length<8)continue;const Te=new Set(re),ne=G.get(re[0]),ke=re[re.length-1];if(G.get(ke).y+(R.get(ke)||220)-ne.y<=U||a.some(et=>!Te.has(et.id)&&G.get(et.id).x>ne.x+s/2))continue;let qe=0,je=ne.y;for(const et of re){const dt=R.get(et)||220,Ke=je-ne.y,kt=Ke+dt>U,bt=V.has(et)&&Ke>U*.6;(kt||bt)&&je!==ne.y&&(qe++,je=ne.y);const at=G.get(et);at.x=ne.x+qe*(s+q),at.y=je,je+=dt+c}}const X=a.map(P=>{const re=G.get(P.id);return{x:re.x,y:re.y,w:s,h:R.get(P.id)||220}}),K=460,F=130,W=(P,re)=>X.some(fe=>P<fe.x+fe.w&&P+K>fe.x&&re<fe.y+fe.h&&re+F>fe.y),ee=new Map;for(const P of H){const re=t.find(ne=>ne.source===P.id)?.target,fe=re?G.get(re):void 0;if(!fe)continue;let ge=fe.x-520,Te=fe.y;if(W(ge,Te)&&(ge=fe.x,Te=fe.y-F-40),W(ge,Te)){const ne=Math.round(fe.x),ke=Math.min(...a.filter(Le=>Math.round(G.get(Le.id).x)===ne).map(Le=>G.get(Le.id).y)),Ae=ee.get(ne)??0;ee.set(ne,Ae+1),ge=fe.x,Te=ke-F-40-Ae*(F+30)}G.set(P.id,{x:ge,y:Te})}return e.map(P=>{const re=G.get(P.id);return re?{...P,position:re}:P})}const $H=(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(Lr())return;t().logEvent("delete",n,{n:1}),t().pushHistory();const{edges:a}=t(),r=Mo(n,a),s=new Set([n,...r]);e(o=>({nodes:o.nodes.filter(c=>!s.has(c.id)),edges:o.edges.filter(c=>!s.has(c.source)&&!s.has(c.target))})),t().pushHistory(),Tt(()=>import("./canonical-Cw94rYnE.js"),[]).then(o=>o.unsubscribeOrphanedSessions())},deleteEdges:n=>{if(Lr())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(Lr())return;t().logEvent("edit-response",n,{chars:a.length}),t().pushHistory();const r=$n(t().nodes.find(s=>s.id===n)?.data.question+a||a);e(s=>({nodes:s.nodes.map(o=>o.id===n?{...o,data:{...o.data,response:a,responses:o.data.responses.map((c,d)=>d===o.data.responseIndex?a:c),summaries:o.data.summaries?.map((c,d)=>d===o.data.responseIndex?void 0:c),summaryTypes:o.data.summaryTypes?.map((c,d)=>d===o.data.responseIndex?void 0:c),editedAts:o.data.responses.map((c,d)=>d===o.data.responseIndex?new Date().toISOString():o.data.editedAts?.[d]),highlights:gf(o.data.highlights,a),isEditingResponse:!1,tokenCount:r}}:o)})),t().pushHistory()},toggleCollapse:n=>{const a=t().nodes.find(h=>h.id===n);if(!a)return;const r=Ao(a),o=d7({...a,data:{...a.data,isCollapsed:!a.data.isCollapsed}})-r,c=Mo(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+o}}:m)}))},setEditing:(n,a)=>{a&&Lr()||e(r=>({nodes:r.nodes.map(s=>s.id===n?{...s,data:{...s.data,isEditing:a}}:s)}))},setEditingResponse:(n,a)=>{a&&Lr()||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()}))}},o=t().edges.find(m=>m.target===n),c=o?{...o,id:`edge-${o.source}-${r}`,target:r}:null,d=c?[...t().edges,c]:t().edges,h=ir([...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=kr(n,t().nodes,t().edges).messages.reduce((S,w)=>S+$n(w.content),0);Ye("success",He(De("edge.materialWiredFull"),{n:k.toLocaleString()}),8e3,{label:De("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}=Fr(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(Hd({source:d,depth:"quote",chain:b})),S=kr(n,s,r).messages.reduce((w,C)=>w+$n(C.content),0)+$n(d.data.question+d.data.response);Ye("info",He(De("edge.linkedQuote"),{n:y}),8e3,{label:He(De("edge.makeFull"),{m:S}),run:()=>t().setEdgeStructural(p.id,!0)})}}},staleIds:[],recomputeStaleness:()=>{const{nodes:n,edges:a}=t(),r=[];for(const o of n)!o.data.lastContextHash||!o.data.response||["note","file","link","frame"].includes(o.data.stepKind??"")||c7(o.id,n,a)!==o.data.lastContextHash&&r.push(o.id);const s=t().staleIds;s.length===r.length&&s.every((o,c)=>o===r[c])||e({staleIds:r})},setEdgeStructural:(n,a)=>{const{nodes:r,edges:s}=t(),o=s.find(c=>c.id===n);if(o){if(a){const c=s.filter(h=>!h.data?.isCrossLink),{ordered:d}=Fr(o.source,r,c);if(d.some(h=>h.id===o.target)){Ye("error",De("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:ir(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:o,responseIndex:c}=s.data;let d=a==="prev"?c-1:c+1;return d<0&&(d=o.length-1),d>=o.length&&(d=0),{...s,data:{...s.data,responseIndex:d,response:o[d],question:s.data.questions?.[d]??s.data.question,generationFailed:void 0,highlights:gf(s.data.highlights,o[d])}}})}))},deleteVersion:(n,a)=>{t().pushHistory(),e(r=>({nodes:r.nodes.map(s=>{if(s.id!==n)return s;const o=s.data.responses.filter((d,h)=>h!==a);if(o.length===0)return s;const c=Math.min(s.data.responseIndex,o.length-1);return{...s,data:{...s.data,responses:o,responseIndex:c,response:o[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:gf(s.data.highlights,o[c])}}})})),t().pushHistory()},relayout:()=>{Lr()||(t().pushHistory(),e(n=>{const a=GH(n.nodes,n.edges);return{nodes:ir(n.nodes,a),edges:a}}),t().pushHistory())},setArchived:(n,a)=>{const r=new Set(n);t().pushHistory(),t().logEvent(a?"archive":"unarchive",n[0],{n:n.length}),e(s=>({nodes:s.nodes.map(o=>r.has(o.id)?{...o,data:{...o.data,archived:a||void 0,archivedAt:a?new Date().toISOString():void 0}}:o)})),t().pushHistory()},setNodeModel:(n,a)=>{e(r=>({nodes:r.nodes.map(s=>s.id===n?{...s,data:{...s.data,model:a}}:s)}))},alignSelection:n=>{if(n.length<2)return;const a=new Set(n),{nodes:r,edges:s}=t(),o=new Map,c=s.filter(b=>!b.data?.isWatch),d=(b,y)=>{if(o.has(b))return o.get(b);if(y.has(b))return 0;y.add(b);const k=c.filter(w=>w.target===b&&a.has(w.source)),S=k.length===0?0:1+Math.max(...k.map(w=>d(w.source,y)));return o.set(b,S),S},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+=Ao(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(Lr())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(),Tt(()=>import("./canonical-Cw94rYnE.js"),[]).then(r=>r.unsubscribeOrphanedSessions())},duplicateSelection:n=>{const{nodes:a,edges:r}=t(),s=new Set(n),o=a.filter(M=>s.has(M.id));if(o.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??Ao(M)}),d=o.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,_)=>M.x<_.x+_.w&&M.x+M.w>_.x&&M.y<_.y+_.h&&M.y+M.h>_.y,S=b.find(M=>!d.some(_=>y.some(R=>k({..._,x:_.x+M.dx,y:_.y+M.dy},R))))??{dx:p,dy:x},w=new Map,C=new Map;for(const M of o){w.set(M.id,In());for(const _ of M.data.attachments??[])C.set(_.id,In())}const T=M=>(M??[]).map(_=>C.get(_)??_),N=o.map(M=>({...M,id:w.get(M.id),position:{x:M.position.x+S.dx,y:M.position.y+S.dy},selected:!0,data:{...M.data,attachments:(M.data.attachments??[]).map(_=>({..._,id:C.get(_.id)})),excludedAttachmentIds:T(M.data.excludedAttachmentIds),includedAttachmentIds:T(M.data.includedAttachmentIds),digestOf:M.data.digestOf?C.get(M.data.digestOf)??M.data.digestOf:void 0,highlights:(M.data.highlights??[]).map(_=>({..._,id:In()})),isEditing:!1,isEditingResponse:!1,isLoading:!1}})),D=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})),O=N.map(M=>M.id);e(M=>({nodes:[...M.nodes.map(_=>_.selected?{..._,selected:!1}:_),...N],edges:[...M.edges,...D],selectedNodeId:O.length===1?O[0]:null,selectedNodeIds:O})),t().pushHistory()}});function n2(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 Hf(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 YH(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:Ac(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 KH(e,t){return`sha256:${await Hf(n2(YH(e,t)))}`}function XH(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 aie(e,t,n,a){const r=kr(e,t,n,a.branchContext,void 0,void 0,a.staleIds),s=t.find(x=>x.id===e),o=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(S=>S.id===x),k=y?.data.attachments?.find(S=>S.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:Ac(k),model_projection:{mode:XH(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 KH(t,n),target_node_id:e},intent:{task:a.task??s?.data.question??"",language:a.language??null},context:{messages:o,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 Hf(n2(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 hc="dsh-sessions",v1="/session.jsonl.zstd",QH=1500,ZH=2500,JH=6e4,eU=6e4,tU=600*1e3;let Hx=null;function nU(e){if(window.desktopSessions)return;const t=e.replace(/\/+$/,""),n=async q=>{const H=await fetch(t+q,{credentials:"same-origin"});if(!H.ok)throw new Error(`${q}: ${H.status}`);return H.json()},a=async q=>{const H=await fetch(t+q,{credentials:"same-origin"});if(!H.ok)throw new Error(`${q}: ${H.status}`);return H.text()},r=new Map,s=q=>`${q}${v1}`,o=(q,H)=>{const V=q.indexOf(`
61
+ ${_}`:_}),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 O=u7(w,t);return O&&(c.unshift({role:"system",content:O}),h.unshift({layer:"system",part:"role"})),{messages:c,images:d,layerTokens:p,sources:h,imageSources:m}}function L5(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 j5(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 Lr(){return pe.getState().condenseRun.status!=="building"?!1:(Ye("info",De("condense.editLocked")),!0)}const VH=(e,t)=>({history:[{nodes:[],edges:[]}],historyIndex:0,pushHistory:()=>{const{nodes:n,edges:a,history:r,historyIndex:s}=t(),o=r.slice(0,s+1);o.push({nodes:n,edges:a}),o.length>UB&&o.shift(),e({history:o,historyIndex:o.length-1})},undo:()=>{if(Lr())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(Lr())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 d7(e){if(e.data.isCollapsed)return FB;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 Ao(e){return Math.max(e.measured?.height??0,d7(e))}function GH(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),o=a.find(c=>c.source===r.id);if(a=a.filter(c=>c.target!==r.id),!!o)for(const c of s)a.some(d=>d.source===c.source&&d.target===o.target)||a.push({...c,target:o.target})}return a}function ir(e,t){if(e.length===0)return e;const n=new Set(e.filter(P=>["note","file","link","frame"].includes(P.data.stepKind??"")).map(P=>P.id)),a=e.filter(P=>!n.has(P.id)),r=t.filter(P=>!n.has(P.source)&&!n.has(P.target)),s=g5,o=x5,c=b5,d=24,h=r.filter(P=>!P.data?.isCrossLink),m=new Set(h.map(P=>P.target));for(const P of r)P.data?.isCrossLink&&!P.data?.isWatch&&!m.has(P.target)&&(h.push(P),m.add(P.target));const p=new Set(h.map(P=>P.target)),x=a.filter(P=>!p.has(P.id)),b=new Map;for(const P of h){const re=b.get(P.target)||[];re.push(P.source),b.set(P.target,re)}const y=new Map,k=new Map;for(const P of x){const re=t.filter(Te=>Te.target===P.id&&!Te.data?.isCrossLink&&n.has(Te.source)).map(Te=>e.find(ne=>ne.id===Te.source)).filter(Te=>!!Te);if(re.length===0)continue;const fe=re.reduce((Te,ne)=>Te.position.y+Ao(Te)>ne.position.y+Ao(ne)?Te:ne),ge=k.get(fe.id)??0;k.set(fe.id,ge+1),y.set(P.id,{x:fe.position.x-60+ge*(g5+x5),y:fe.position.y+Ao(fe)+b5})}const S=new Map;for(const P of h){const re=S.get(P.source)||[];re.push(P.target),S.set(P.source,re)}const w=(P,re)=>`${P}\0${re}`,C=new Set(r.filter(P=>P.data?.isBranchFromSelection).map(P=>w(P.source,P.target)));function T(P,re){const fe=(S.get(P)||[]).filter(ne=>(re.get(ne)??P)===P),ge=fe.filter(ne=>!C.has(w(P,ne))),Te=fe.filter(ne=>C.has(w(P,ne)));return{continuation:ge[0]??null,regenerates:ge.slice(1),explores:Te}}const N=1e5;function D(P){const re=new Map;let fe=0,ge=N;const Te=new Map,ne=Ae=>Te.get(Ae)??Ae*(s+o);function ke(Ae,Le){if(re.has(Ae))return;re.set(Ae,Le);const{continuation:qe,regenerates:je,explores:et}=T(Ae,P);qe&&ke(qe,Le);for(let Ke=0;Ke<je.length;Ke++){let kt;Le>=N?(kt=ge++,Te.set(kt,ne(Le)+(Ke+1)*(s+o))):(kt=Le+1+Ke,fe=Math.max(fe,kt+1)),ke(je[Ke],kt)}let dt=0;for(const Ke of et){let kt;Le>=N?(kt=ge++,Te.set(kt,ne(Le)+(je.length+1+dt)*(s+o)),dt++):(kt=fe,fe++),ke(Ke,kt)}}for(const Ae of x){const Le=y.get(Ae.id);if(Le){const qe=ge++;Te.set(qe,Le.x),ke(Ae.id,qe)}else{const qe=fe;fe++,ke(Ae.id,qe)}}for(let Ae=0;Ae<a.length;Ae++){let Le=!1;for(const qe of a){if(re.has(qe.id))continue;const je=(b.get(qe.id)||[]).map(et=>re.get(et)).filter(et=>et!==void 0).sort((et,dt)=>et-dt);je.length&&(ke(qe.id,je[Math.floor((je.length-1)/2)]),Le=!0)}if(!Le)break}return{nodeColumn:re,colX:ne}}const O=new Map;for(const[P,re]of b){if(re.length<2)continue;const fe=re.filter(Te=>!C.has(w(Te,P))),ge=fe.length?fe:re;O.set(P,ge[0])}const{nodeColumn:M,colX:_}=D(O),R=new Map;for(const P of a)R.set(P.id,Ao(P));const G=new Map,B=new Set,$=[...x.map(P=>P.id)];for(const P of $){const re=M.get(P)??0,fe=y.get(P);G.set(P,{x:_(re),y:fe?.y??0}),B.add(P)}for(;$.length>0;){const P=$.shift(),re=G.get(P),fe=R.get(P)||220,{continuation:ge,regenerates:Te,explores:ne}=T(P,O);if(ge&&!B.has(ge)){B.add(ge);const Ae=M.get(ge)??0;G.set(ge,{x:_(Ae),y:re.y+fe+c}),$.push(ge)}const ke=re.y+fe+c;for(const Ae of Te){if(B.has(Ae))continue;B.add(Ae);const Le=M.get(Ae)??0;G.set(Ae,{x:_(Le),y:ke}),$.push(Ae)}for(const Ae of ne){if(B.has(Ae))continue;B.add(Ae);const Le=M.get(Ae)??0;G.set(Ae,{x:_(Le),y:re.y+fe*.25}),$.push(Ae)}}for(let P=0;P<a.length;P++){let re=!1;for(const fe of a){if(G.has(fe.id))continue;const ge=(b.get(fe.id)||[]).filter(ne=>G.has(ne));if(!ge.length)continue;const Te=Math.max(...ge.map(ne=>G.get(ne).y+(R.get(ne)||220)));G.set(fe.id,{x:_(M.get(fe.id)??0),y:Te+c}),re=!0}if(!re)break}for(const P of a)G.has(P.id)||G.set(P.id,{x:0,y:0});for(let P=0;P<5;P++){let re=!1;for(const fe of a){const ge=G.get(fe.id);if(!ge)continue;const Te=(b.get(fe.id)||[]).filter(Le=>G.has(Le));if(Te.length<2)continue;const ne=Te.filter(Le=>!C.has(`${Le}\0${fe.id}`)),ke=Te.filter(Le=>C.has(`${Le}\0${fe.id}`));let Ae=-1/0;for(const Le of ne)Ae=Math.max(Ae,G.get(Le).y+(R.get(Le)||220)+c);for(const Le of ke)Ae=Math.max(Ae,G.get(Le).y);if(Ae>-1/0&&ge.y<Ae){const Le=Ae-ge.y;ge.y=Ae;for(const qe of new Set(Mo(fe.id,h))){const je=G.get(qe);je&&(je.y+=Le)}re=!0}}if(!re)break}const Z=new Map;for(const P of a){const re=M.get(P.id)??0,fe=Z.get(re)||[];fe.push(P.id),Z.set(re,fe)}for(let P=0;P<5;P++){let re=!1;for(const[,fe]of Z){fe.sort((ge,Te)=>G.get(ge).y-G.get(Te).y);for(let ge=1;ge<fe.length;ge++){const Te=fe[ge-1],ne=fe[ge],ke=G.get(Te),Ae=G.get(ne),Le=R.get(Te)||220,qe=ke.y+Le+d;if(Ae.y<qe){const je=qe-Ae.y;Ae.y=qe,re=!0;for(const et of new Set(Mo(ne,h))){const dt=G.get(et);dt&&(dt.y+=je)}}}}if(!re)break}const U=8e3,q=180,H=e.filter(P=>P.data.stepKind==="note"&&P.data.importSource),V=new Set(t.filter(P=>H.some(re=>re.id===P.source)).map(P=>P.target));for(const P of x){const re=[];let fe=P.id,ge=!0;for(;fe;){re.push(fe);const et=S.get(fe)||[];if(et.length>1){ge=!1;break}fe=et[0]}if(!ge||re.length<8)continue;const Te=new Set(re),ne=G.get(re[0]),ke=re[re.length-1];if(G.get(ke).y+(R.get(ke)||220)-ne.y<=U||a.some(et=>!Te.has(et.id)&&G.get(et.id).x>ne.x+s/2))continue;let qe=0,je=ne.y;for(const et of re){const dt=R.get(et)||220,Ke=je-ne.y,kt=Ke+dt>U,bt=V.has(et)&&Ke>U*.6;(kt||bt)&&je!==ne.y&&(qe++,je=ne.y);const at=G.get(et);at.x=ne.x+qe*(s+q),at.y=je,je+=dt+c}}const X=a.map(P=>{const re=G.get(P.id);return{x:re.x,y:re.y,w:s,h:R.get(P.id)||220}}),K=460,F=130,W=(P,re)=>X.some(fe=>P<fe.x+fe.w&&P+K>fe.x&&re<fe.y+fe.h&&re+F>fe.y),ee=new Map;for(const P of H){const re=t.find(ne=>ne.source===P.id)?.target,fe=re?G.get(re):void 0;if(!fe)continue;let ge=fe.x-520,Te=fe.y;if(W(ge,Te)&&(ge=fe.x,Te=fe.y-F-40),W(ge,Te)){const ne=Math.round(fe.x),ke=Math.min(...a.filter(Le=>Math.round(G.get(Le.id).x)===ne).map(Le=>G.get(Le.id).y)),Ae=ee.get(ne)??0;ee.set(ne,Ae+1),ge=fe.x,Te=ke-F-40-Ae*(F+30)}G.set(P.id,{x:ge,y:Te})}return e.map(P=>{const re=G.get(P.id);return re?{...P,position:re}:P})}const $H=(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(Lr())return;t().logEvent("delete",n,{n:1}),t().pushHistory();const{edges:a}=t(),r=Mo(n,a),s=new Set([n,...r]);e(o=>({nodes:o.nodes.filter(c=>!s.has(c.id)),edges:o.edges.filter(c=>!s.has(c.source)&&!s.has(c.target))})),t().pushHistory(),Tt(()=>import("./canonical-DccXDqkX.js"),[]).then(o=>o.unsubscribeOrphanedSessions())},deleteEdges:n=>{if(Lr())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(Lr())return;t().logEvent("edit-response",n,{chars:a.length}),t().pushHistory();const r=$n(t().nodes.find(s=>s.id===n)?.data.question+a||a);e(s=>({nodes:s.nodes.map(o=>o.id===n?{...o,data:{...o.data,response:a,responses:o.data.responses.map((c,d)=>d===o.data.responseIndex?a:c),summaries:o.data.summaries?.map((c,d)=>d===o.data.responseIndex?void 0:c),summaryTypes:o.data.summaryTypes?.map((c,d)=>d===o.data.responseIndex?void 0:c),editedAts:o.data.responses.map((c,d)=>d===o.data.responseIndex?new Date().toISOString():o.data.editedAts?.[d]),highlights:gf(o.data.highlights,a),isEditingResponse:!1,tokenCount:r}}:o)})),t().pushHistory()},toggleCollapse:n=>{const a=t().nodes.find(h=>h.id===n);if(!a)return;const r=Ao(a),o=d7({...a,data:{...a.data,isCollapsed:!a.data.isCollapsed}})-r,c=Mo(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+o}}:m)}))},setEditing:(n,a)=>{a&&Lr()||e(r=>({nodes:r.nodes.map(s=>s.id===n?{...s,data:{...s.data,isEditing:a}}:s)}))},setEditingResponse:(n,a)=>{a&&Lr()||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()}))}},o=t().edges.find(m=>m.target===n),c=o?{...o,id:`edge-${o.source}-${r}`,target:r}:null,d=c?[...t().edges,c]:t().edges,h=ir([...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=kr(n,t().nodes,t().edges).messages.reduce((S,w)=>S+$n(w.content),0);Ye("success",He(De("edge.materialWiredFull"),{n:k.toLocaleString()}),8e3,{label:De("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}=Fr(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(Hd({source:d,depth:"quote",chain:b})),S=kr(n,s,r).messages.reduce((w,C)=>w+$n(C.content),0)+$n(d.data.question+d.data.response);Ye("info",He(De("edge.linkedQuote"),{n:y}),8e3,{label:He(De("edge.makeFull"),{m:S}),run:()=>t().setEdgeStructural(p.id,!0)})}}},staleIds:[],recomputeStaleness:()=>{const{nodes:n,edges:a}=t(),r=[];for(const o of n)!o.data.lastContextHash||!o.data.response||["note","file","link","frame"].includes(o.data.stepKind??"")||c7(o.id,n,a)!==o.data.lastContextHash&&r.push(o.id);const s=t().staleIds;s.length===r.length&&s.every((o,c)=>o===r[c])||e({staleIds:r})},setEdgeStructural:(n,a)=>{const{nodes:r,edges:s}=t(),o=s.find(c=>c.id===n);if(o){if(a){const c=s.filter(h=>!h.data?.isCrossLink),{ordered:d}=Fr(o.source,r,c);if(d.some(h=>h.id===o.target)){Ye("error",De("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:ir(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:o,responseIndex:c}=s.data;let d=a==="prev"?c-1:c+1;return d<0&&(d=o.length-1),d>=o.length&&(d=0),{...s,data:{...s.data,responseIndex:d,response:o[d],question:s.data.questions?.[d]??s.data.question,generationFailed:void 0,highlights:gf(s.data.highlights,o[d])}}})}))},deleteVersion:(n,a)=>{t().pushHistory(),e(r=>({nodes:r.nodes.map(s=>{if(s.id!==n)return s;const o=s.data.responses.filter((d,h)=>h!==a);if(o.length===0)return s;const c=Math.min(s.data.responseIndex,o.length-1);return{...s,data:{...s.data,responses:o,responseIndex:c,response:o[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:gf(s.data.highlights,o[c])}}})})),t().pushHistory()},relayout:()=>{Lr()||(t().pushHistory(),e(n=>{const a=GH(n.nodes,n.edges);return{nodes:ir(n.nodes,a),edges:a}}),t().pushHistory())},setArchived:(n,a)=>{const r=new Set(n);t().pushHistory(),t().logEvent(a?"archive":"unarchive",n[0],{n:n.length}),e(s=>({nodes:s.nodes.map(o=>r.has(o.id)?{...o,data:{...o.data,archived:a||void 0,archivedAt:a?new Date().toISOString():void 0}}:o)})),t().pushHistory()},setNodeModel:(n,a)=>{e(r=>({nodes:r.nodes.map(s=>s.id===n?{...s,data:{...s.data,model:a}}:s)}))},alignSelection:n=>{if(n.length<2)return;const a=new Set(n),{nodes:r,edges:s}=t(),o=new Map,c=s.filter(b=>!b.data?.isWatch),d=(b,y)=>{if(o.has(b))return o.get(b);if(y.has(b))return 0;y.add(b);const k=c.filter(w=>w.target===b&&a.has(w.source)),S=k.length===0?0:1+Math.max(...k.map(w=>d(w.source,y)));return o.set(b,S),S},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+=Ao(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(Lr())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(),Tt(()=>import("./canonical-DccXDqkX.js"),[]).then(r=>r.unsubscribeOrphanedSessions())},duplicateSelection:n=>{const{nodes:a,edges:r}=t(),s=new Set(n),o=a.filter(M=>s.has(M.id));if(o.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??Ao(M)}),d=o.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,_)=>M.x<_.x+_.w&&M.x+M.w>_.x&&M.y<_.y+_.h&&M.y+M.h>_.y,S=b.find(M=>!d.some(_=>y.some(R=>k({..._,x:_.x+M.dx,y:_.y+M.dy},R))))??{dx:p,dy:x},w=new Map,C=new Map;for(const M of o){w.set(M.id,In());for(const _ of M.data.attachments??[])C.set(_.id,In())}const T=M=>(M??[]).map(_=>C.get(_)??_),N=o.map(M=>({...M,id:w.get(M.id),position:{x:M.position.x+S.dx,y:M.position.y+S.dy},selected:!0,data:{...M.data,attachments:(M.data.attachments??[]).map(_=>({..._,id:C.get(_.id)})),excludedAttachmentIds:T(M.data.excludedAttachmentIds),includedAttachmentIds:T(M.data.includedAttachmentIds),digestOf:M.data.digestOf?C.get(M.data.digestOf)??M.data.digestOf:void 0,highlights:(M.data.highlights??[]).map(_=>({..._,id:In()})),isEditing:!1,isEditingResponse:!1,isLoading:!1}})),D=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})),O=N.map(M=>M.id);e(M=>({nodes:[...M.nodes.map(_=>_.selected?{..._,selected:!1}:_),...N],edges:[...M.edges,...D],selectedNodeId:O.length===1?O[0]:null,selectedNodeIds:O})),t().pushHistory()}});function n2(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 Hf(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 YH(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:Ac(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 KH(e,t){return`sha256:${await Hf(n2(YH(e,t)))}`}function XH(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 aie(e,t,n,a){const r=kr(e,t,n,a.branchContext,void 0,void 0,a.staleIds),s=t.find(x=>x.id===e),o=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(S=>S.id===x),k=y?.data.attachments?.find(S=>S.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:Ac(k),model_projection:{mode:XH(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 KH(t,n),target_node_id:e},intent:{task:a.task??s?.data.question??"",language:a.language??null},context:{messages:o,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 Hf(n2(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 hc="dsh-sessions",v1="/session.jsonl.zstd",QH=1500,ZH=2500,JH=6e4,eU=6e4,tU=600*1e3;let Hx=null;function nU(e){if(window.desktopSessions)return;const t=e.replace(/\/+$/,""),n=async q=>{const H=await fetch(t+q,{credentials:"same-origin"});if(!H.ok)throw new Error(`${q}: ${H.status}`);return H.json()},a=async q=>{const H=await fetch(t+q,{credentials:"same-origin"});if(!H.ok)throw new Error(`${q}: ${H.status}`);return H.text()},r=new Map,s=q=>`${q}${v1}`,o=(q,H)=>{const V=q.indexOf(`
62
62
  `),X=V<0?q:q.slice(0,V);try{const K=JSON.parse(X);if(K.type==="session"&&K.cwd===void 0)return K.cwd=H,JSON.stringify(K)+(V<0?"":q.slice(V))}catch{}return q},c=q=>q.endsWith(v1)?q.slice(0,-v1.length):null,d=async()=>{const[q,H]=await Promise.all([n("/disksessions").then(X=>X.sessions).catch(()=>[]),n("/sessions").then(X=>X.sessions).catch(()=>[])]),V=new Set;for(const X of q){V.add(X.id);const K=r.get(X.id);r.set(X.id,{id:X.id,live:!1,size:X.size,mtime:X.mtime,seq:K?.seq??null,cwd:X.cwd??K?.cwd??null})}for(const X of H)V.add(X.id),h(X);for(const X of[...r.keys()])V.has(X)||r.delete(X);return[...r.values()]},h=q=>{const H=r.get(q.id),V=typeof q.seq=="number"?q.seq:null,X=V!==null&&H?.seq!==null&&H?.seq!==void 0&&V>H.seq;r.set(q.id,{id:q.id,live:!0,size:H?.size??0,mtime:X||!H?Date.now():H.mtime,seq:V,cwd:H?.cwd??null})},m=async()=>{const q=await n("/sessions").then(H=>H.sessions).catch(()=>[]);for(const H of q)h(H);return[...r.values()]},p=new Map,x=async q=>{const H=r.get(q)??(await d(),r.get(q));if(!H)return"";const V=p.get(q);if(V&&Date.now()-V.at<QH&&V.seq===H.seq)return V.text;let X;if(H.live&&V&&V.seq!==null&&H.seq!==null&&H.seq>V.seq&&V.text){const K=await a(`/sessions/${encodeURIComponent(q)}/log?since=${V.seq}`).catch(()=>null);K===null?X=V.text:X=K?`${V.text}
63
63
  ${K}`:V.text}else X=await a(H.live?`/sessions/${encodeURIComponent(q)}/log`:`/disksessions/${encodeURIComponent(q)}/log`).catch(()=>""),H.live&&H.cwd&&(X=o(X,H.cwd));return p.set(q,{at:Date.now(),seq:H.seq,text:X}),X};let b=null;const y=async()=>b||(b=await n("/roots").then(q=>q.roots.filter(H=>H.exists)).catch(()=>[]),b),k=new Map,S=async q=>n(`/roots/${encodeURIComponent(q)}/list`).then(H=>H.files).catch(()=>[]),w=(q,H,V,X="")=>`/roots/${encodeURIComponent(q)}/${H}?rel=${encodeURIComponent(V)}${X}`,C=[];let T=!1;const N=new Map;let D=0;const O=(q,H)=>{const V=`${q}|${H.rel}`,X=k.get(V);if(k.set(V,H.mtime),Date.now()-H.mtime<tU?N.set(V,{rootKey:q,rel:H.rel,mtime:H.mtime}):N.delete(V),X!==void 0&&H.mtime>X)for(const K of C)K({rootKey:q,rel:H.rel})},M=async()=>{const q=Date.now()-D>=eU,H=new Map([...r].map(([X,K])=>[X,K.seq])),V=await(q?d():m()).catch(()=>[]);for(const X of V){if(!X.live)continue;const K=H.get(X.id);if(K===void 0||X.seq!==null&&K!==null&&X.seq>K)for(const F of C)F({rootKey:hc,rel:s(X.id)})}if(q){D=Date.now();for(const X of await y())for(const K of await S(X.key))O(X.key,K);return}for(const X of[...N.values()]){const K=await n(w(X.rootKey,"stat",X.rel)).catch(()=>null);if(!K){N.delete(`${X.rootKey}|${X.rel}`);continue}O(X.rootKey,{rel:X.rel,size:K.size,mtime:K.mtime})}};let _=!0,R=null;const G=()=>_&&document.visibilityState!=="hidden",B=()=>{R!==null&&window.clearTimeout(R),R=window.setTimeout(async()=>{await M().catch(()=>{}),B()},G()?ZH:JH)},$=()=>{!T||!G()||M().catch(()=>{}).then(B)};document.addEventListener("visibilitychange",$);const Z=q=>{window.parent.postMessage({source:"dsh-thoughtdag",type:"td:select-session",session:q},window.location.origin)},U={roots:async()=>[{key:hc,path:"~/.dsh/sessions",builtin:!0,exists:!0},...await y()],addRoot:async()=>null,removeRoot:async()=>{},list:async q=>{if(q!==hc){const H=await S(q);for(const V of H)k.set(`${q}|${V.rel}`,V.mtime);return H}return(await d()).map(H=>({rel:s(H.id),size:H.size,mtime:H.mtime}))},head:async(q,H,V)=>{if(q!==hc)return a(w(q,"head",H,`&bytes=${Math.max(1024,V|0)}`)).catch(()=>"");const X=c(H);return X?(await x(X)).slice(0,Math.min(Math.max(1024,V|0),524288)):""},read:async(q,H)=>{if(q!==hc)return a(w(q,"read",H)).catch(()=>"");const V=c(H);return V?x(V):""},readRange:async(q,H,V,X)=>{if(q!==hc)return n(w(q,"range",H,`&start=${V|0}&length=${X|0}`)).catch(()=>({text:"",nextStart:V|0,eof:!0}));const K=c(H),F=K?await x(K):"",W=Math.max(0,V|0),ee=Math.min(Math.max(65536,X|0),32*1024*1024),P=Math.min(ee,Math.max(0,F.length-W));if(P===0)return{text:"",nextStart:W,eof:!0};let re=F.slice(W,W+P);const fe=W+P>=F.length;if(!fe){const ge=re.lastIndexOf(`
64
- `);if(ge<0)return{text:"",nextStart:W+P,eof:!1};re=re.slice(0,ge+1)}return{text:re,nextStart:W+re.length,eof:fe}},openInCli:async(q,H,V)=>{if(q==="dsh")return Z(V),{opened:!0,via:"app",command:""};try{const X=await fetch(t+"/agents/open-in-cli",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"same-origin",body:JSON.stringify({runner:q,cwd:H,sessionId:V})});if(X.ok){const K=await X.json();return{opened:!!K.opened,via:"terminal",command:K.command??""}}}catch{}return{opened:!1,via:"app",command:""}},openTargets:async()=>({terminals:[],apps:[{runner:"dsh",name:"DeepSeek Harness"}],prefs:{terminal:""},canAddCustom:!1}),setOpenPrefs:async q=>q,addTerminal:async()=>null,watchStart:async()=>{if(!T){T=!0,await d().catch(()=>{}),D=Date.now();for(const q of await y())for(const H of await S(q.key))O(q.key,H);B()}return!0},onSessionsChanged:q=>{C.push(q)}};window.desktopSessions=U,window.addEventListener("message",q=>{const H=q.data;if(!(q.origin!==window.location.origin||H?.source!=="dsh-thoughtdag")&&(H.type==="td:current-session"&&(Hx=H.session??null,window.dispatchEvent(new CustomEvent("td:dsh-current",{detail:Hx}))),H.type==="td:view")){const V=_;_=H.shown!==!1,_&&!V?$():!_&&V&&B()}}),window.parent.postMessage({source:"dsh-thoughtdag",type:"td:request-current"},window.location.origin)}const P5="harness/agent",aU=e=>!!e&&(e===P5||e.startsWith(P5+"/"));async function rU(){try{const{useStore:e}=await Tt(async()=>{const{useStore:r}=await Promise.resolve().then(()=>Hs);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 iU(e,t){if(!window.desktopSessions||!aU(t))return;const n=await rU()??Hx?.cwd??void 0;try{const{useStore:a}=await Tt(async()=>{const{useStore:h}=await Promise.resolve().then(()=>Hs);return{useStore:h}},void 0),{useProjects:r}=await Tt(async()=>{const{useProjects:h}=await Promise.resolve().then(()=>qr);return{useProjects:h}},void 0),{projects:s,activeId:o}=r.getState(),d=s.find(h=>h.id===o)?.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 h7=(e,t,n,a,r,s)=>{const o=r?[r]:[];e(c=>({nodes:c.nodes.map(d=>d.id===t?{...d,data:{...d.data,importSource:{runner:"dsh",sessionId:n,itemIds:o,...a.cwd?{cwd:a.cwd}:{}},...s?{source:s}:{}}}:d)}))};async function f7(e,t){if(!e)return!1;const{useProjects:n,patchLedgerEntry:a}=await Tt(async()=>{const{useProjects:d,patchLedgerEntry:h}=await Promise.resolve().then(()=>qr);return{useProjects:d,patchLedgerEntry:h}},void 0),{projects:r,activeId:s}=n.getState();if(!s)return!1;const o=r.find(d=>d.id===s)?.sourceSession;if(!o)return!1;const c=o.sessionId===e?o:o.chapters?.find(d=>d.sessionId===e)??o.branches?.find(d=>d.sessionId===e);return c?(await a(s,e,{importedCount:c.importedCount+1,tailNodeId:t}),!0):!1}async function sU(e,t,n,a){return window.desktopSessions?(h7(e,t,n.session??a.session,n,a.userMessageId),f7(n.session,t)):!1}async function oU(e,t,n,a,r,s,o,c=!1){if(!window.desktopSessions)return;const d=r.session??o?.session??s;d&&(h7(e,n,d,r,o?.userMessageId??null,{question:a.question,response:a.response}),c||await f7(r.session,n))}const lU=45,cU=3,uU=/sk-[a-zA-Z0-9_-]{8,}|api[ _-]?key|password|token|secret/i,Ux=new Map;function dU(e){return e.category!=="project"?!0:(Date.now()-new Date(e.at).getTime())/864e5<=lU}function hU(){const{memoryEnabled:e,memories:t}=pe.getState();if(!e)return null;const n=t.filter(dU);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
+ `);if(ge<0)return{text:"",nextStart:W+P,eof:!1};re=re.slice(0,ge+1)}return{text:re,nextStart:W+re.length,eof:fe}},openInCli:async(q,H,V)=>{if(q==="dsh")return Z(V),{opened:!0,via:"app",command:""};try{const X=await fetch(t+"/agents/open-in-cli",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"same-origin",body:JSON.stringify({runner:q,cwd:H,sessionId:V})});if(X.ok){const K=await X.json();return{opened:!!K.opened,via:"terminal",command:K.command??""}}}catch{}return{opened:!1,via:"app",command:""}},openTargets:async()=>({terminals:[],apps:[{runner:"dsh",name:"DeepSeek Harness"}],prefs:{terminal:""},canAddCustom:!1}),setOpenPrefs:async q=>q,addTerminal:async()=>null,watchStart:async()=>{if(!T){T=!0,await d().catch(()=>{}),D=Date.now();for(const q of await y())for(const H of await S(q.key))O(q.key,H);B()}return!0},onSessionsChanged:q=>{C.push(q)}};window.desktopSessions=U,window.addEventListener("message",q=>{const H=q.data;if(!(q.origin!==window.location.origin||H?.source!=="dsh-thoughtdag")&&(H.type==="td:current-session"&&(Hx=H.session??null,window.dispatchEvent(new CustomEvent("td:dsh-current",{detail:Hx}))),H.type==="td:view")){const V=_;_=H.shown!==!1,_&&!V?$():!_&&V&&B()}}),window.parent.postMessage({source:"dsh-thoughtdag",type:"td:request-current"},window.location.origin)}const P5="harness/agent",aU=e=>!!e&&(e===P5||e.startsWith(P5+"/"));async function rU(){try{const{useStore:e}=await Tt(async()=>{const{useStore:r}=await Promise.resolve().then(()=>Hs);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 iU(e,t){if(!window.desktopSessions||!aU(t))return;const n=await rU()??Hx?.cwd??void 0;try{const{useStore:a}=await Tt(async()=>{const{useStore:p}=await Promise.resolve().then(()=>Hs);return{useStore:p}},void 0),{useProjects:r}=await Tt(async()=>{const{useProjects:p}=await Promise.resolve().then(()=>qr);return{useProjects:p}},void 0),{projects:s,activeId:o}=r.getState(),c=s.find(p=>p.id===o)?.sourceSession,{nodes:d,edges:h}=a.getState(),m=h.filter(p=>p.target===e);if(m.length===1){const p=m[0].source,b=(c?[c,...c.chapters??[],...c.branches??[]].filter(S=>S.runner==="dsh"&&S.sessionId):[]).find(S=>S.tailNodeId===p);if(b)return{...n?{cwd:n}:{},session:b.sessionId};const k=d.find(S=>S.id===p)?.data.importSource;if(k?.runner==="dsh"&&k.sessionId&&k.itemIds?.[0])return{...n?{cwd:n}:{},forkSession:k.sessionId,forkAnchor:k.itemIds[0]}}}catch{}return n?{cwd:n}:{}}const h7=(e,t,n,a,r,s)=>{const o=r?[r]:[];e(c=>({nodes:c.nodes.map(d=>d.id===t?{...d,data:{...d.data,importSource:{runner:"dsh",sessionId:n,itemIds:o,...a.cwd?{cwd:a.cwd}:{}},...s?{source:s}:{}}}:d)}))};async function f7(e,t){if(!e)return!1;const{useProjects:n,patchLedgerEntry:a}=await Tt(async()=>{const{useProjects:d,patchLedgerEntry:h}=await Promise.resolve().then(()=>qr);return{useProjects:d,patchLedgerEntry:h}},void 0),{projects:r,activeId:s}=n.getState();if(!s)return!1;const o=r.find(d=>d.id===s)?.sourceSession;if(!o)return!1;const c=o.sessionId===e?o:o.chapters?.find(d=>d.sessionId===e)??o.branches?.find(d=>d.sessionId===e);return c?(await a(s,e,{importedCount:c.importedCount+1,tailNodeId:t}),!0):!1}async function sU(e,t,n,a){return window.desktopSessions?(h7(e,t,n.session??a.session,n,a.userMessageId),f7(n.session,t)):!1}async function oU(e,t,n,a,r,s,o,c=!1){if(!window.desktopSessions)return;const d=r.session??o?.session??s;d&&(h7(e,n,d,r,o?.userMessageId??null,{question:a.question,response:a.response}),c||await f7(r.session,n))}const lU=45,cU=3,uU=/sk-[a-zA-Z0-9_-]{8,}|api[ _-]?key|password|token|secret/i,Ux=new Map;function dU(e){return e.category!=="project"?!0:(Date.now()-new Date(e.at).getTime())/864e5<=lU}function hU(){const{memoryEnabled:e,memories:t}=pe.getState();if(!e)return null;const n=t.filter(dU);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:
65
65
  ${n.map(r=>`- ${r.text}`).join(`
66
66
  `)}`}}const fU=`You maintain a user's long-term memory for an AI workspace. Above is the list of EXISTING memory entries (possibly empty), then ONE exchange from the current session. Decide whether the exchange reveals something DURABLE about the user, and CLASSIFY it: "preference" = how they like things done (language, style, format, tools, models); "identity" = who they are (role, field, expertise, long-term research agenda); "project" = what they are working on right now. Also report evidence: "stated" if the user said it about themselves in so many words, "inferred" if you are concluding it from behavior. NOT memories: content questions, one-off task details, general knowledge, facts about how this workspace itself works, verbatim text blocks, credentials. If a new observation covers the same topic as an existing entry, prefer update over add. Be conservative: most exchanges contain nothing. Reply with EXACTLY one line of JSON, nothing else: {"action":"none"} or {"action":"add","category":"preference|identity|project","evidence":"stated|inferred","text":"..."} or {"action":"update","id":"...","category":"...","evidence":"...","text":"..."} . The text must be ONE short sentence, in the same language the user writes in.`;function mU(e,t,n){const a=(e.text??"").trim();if(!a)return"empty";if(uU.test(a))return"credential-like";const r=e.category;if(!r||!["preference","identity","project"].includes(r))return"no-category";if(r==="identity"&&e.evidence!=="stated")return"identity-inferred";if(e.action==="add"){if(t.some(o=>o.text===a))return"duplicate";if((Ux.get("(none)")??0)>=cU)return"session-cap"}return e.action==="update"&&!t.some(s=>s.id===e.id)?"unknown-id":null}function pU(e,t,n){const{memoryEnabled:a,memories:r,setMemories:s}=pe.getState();!a||e.trim().length<8||(async()=>{try{const o=(await Us())?.default??void 0,c=r.slice(0,40).map(y=>`${y.id}: ${y.text}`).join(`
67
67
  `)||"(none)",h=(await Bo([{role:"user",content:`Existing memory entries:
@@ -145,7 +145,7 @@ ${c.content.trim()}`).join(`
145
145
 
146
146
  ---
147
147
 
148
- ${p}`:p,w=pe.getState().agentEffort||void 0,C=[...new Set(oe.getState().nodes.flatMap(_=>(_.data.approvals??[]).filter(R=>R.outcome==="allowed-session"&&typeof R.rule=="string"&&R.rule.startsWith(h.runtime==="claude-code"?"claude:":h.runtime+":")).map(R=>R.rule)))];DU();let T="",N="",D="";const M=await new Promise(_=>{d.run({runtime:h.runtime,cwd:m,prompt:S,...o?.sessionPath?{sessionPath:o.sessionPath}:{},...o?.forkEntryId?{forkEntryId:o.forkEntryId}:{},images:(a??[]).map(R=>({type:"image",data:R.data,mimeType:R.mimeType})),model:{provider:h.provider,id:h.id},...w?{effort:w}:{},...C.length?{allowRules:C}:{}}).then(R=>{const G=()=>{d.abort(R)};n?.aborted&&G(),n?.addEventListener("abort",G,{once:!0}),xf.set(R,B=>{switch(B.type){case"session":{const $=B.model?.resolved;$&&window.dispatchEvent(new CustomEvent("td:agent-model-resolved",{detail:{id:s,resolved:$}})),r?.onAgentSession?.({runtime:h.runtime,sessionId:B.sessionId??null,sessionFile:B.sessionFile??null,cwd:B.cwd??m,...typeof B.effort=="string"&&B.effort?{effort:B.effort}:{}});break}case"message_update":{const $=B.assistantMessageEvent;$?.type==="text_delta"&&$.delta?(T+=$.delta,t($.delta,T)):$?.type==="thinking_delta"&&$.delta&&(N+=$.delta,r?.onReasoning?.($.delta,N));break}case"tool_execution_start":{const $=String(B.toolName??"tool"),Z=OU($,B.args);r?.onAgentTool?.({id:String(B.toolCallId??""),name:$,query:Z,phase:"start"});break}case"tool_execution_end":r?.onAgentTool?.({id:String(B.toolCallId??""),name:String(B.toolName??"tool"),query:"",phase:"end",isError:!!B.isError});break;case"extension_ui_cancelled":{const $=`dialog-${Date.now()}`,Z=String(B.title??B.method??"dialog");r?.onAgentTool?.({id:$,name:"dialog",query:Z,phase:"start"}),r?.onAgentTool?.({id:$,name:"dialog",query:"",phase:"end",isError:!0});break}case"question_answered":r?.onApprovalDecided?.({...B.auto?{auto:!0,name:String(B.title??""),query:String(B.message??""),rule:typeof B.rule=="string"?B.rule:null}:{},id:String(B.id),outcome:B.outcome??"cancelled",value:typeof B.value=="string"?B.value:null});break;case"question":r?.onApproval?.({id:String(B.id),kind:B.kind??"confirm",toolName:h.runtime,callId:null,reason:null,name:String(B.title??""),query:String(B.message??""),arguments:null,options:Array.isArray(B.options)?B.options:[],placeholder:typeof B.placeholder=="string"?B.placeholder:null,prefill:typeof B.prefill=="string"?B.prefill:null,channel:{runId:R},paths:Array.isArray(B.paths)?B.paths:[],suggest:typeof B.suggest=="string"?B.suggest:null,rule:typeof B.rule=="string"?B.rule:null});break;case"fs_changes":r?.onAgentChanges?.({changed:B.changed??[],added:B.added??[],removed:B.removed??[],truncated:!!B.truncated});break;case"run_end":D=typeof B.text=="string"&&B.text?B.text:T,xf.delete(R),n?.removeEventListener("abort",G),_({how:String(B.how??"end")});break;case"run_error":xf.delete(R),n?.removeEventListener("abort",G),_({how:"error",error:String(B.message??"agent run failed")});break}})}).catch(R=>_({how:"error",error:R instanceof Error?R.message:String(R)}))});if(n?.aborted)throw new DOMException("The operation was aborted.","AbortError");if(M.how==="error")throw new Error(M.error??"agent run failed");return D||T}async function LU(e,t,n){const a=o=>(console.warn("[agent] turn not adopted:",o,t.runtime,t.sessionFile),!1),r=window.desktopSessions;if(!r||!t.sessionFile)return a(r?"no session file":"no sessions bridge");const s=Vc[t.runtime].rootKey;try{const c=(await r.roots()).find(U=>U.key===s);if(!c)return a("no root "+s);const d=c.path.replace(/\/$/,"")+"/";if(!t.sessionFile.startsWith(d))return a("file outside root "+d);const h=t.sessionFile.slice(d.length),{anyRunnerSessionConversation:m}=await Tt(async()=>{const{anyRunnerSessionConversation:U}=await import("./index-Dyq9QwYZ.js");return{anyRunnerSessionConversation:U}},[]),{useStore:p}=await Tt(async()=>{const{useStore:U}=await Promise.resolve().then(()=>Hs);return{useStore:U}},void 0),{useProjects:x,registerLedgerEntry:b,updateSourceSession:y,subscribedSessionIds:k}=await Tt(async()=>{const{useProjects:U,registerLedgerEntry:q,updateSourceSession:H,subscribedSessionIds:V}=await Promise.resolve().then(()=>qr);return{useProjects:U,registerLedgerEntry:q,updateSourceSession:H,subscribedSessionIds:V}},void 0),S=await r.read(s,h);if(!S)return a("empty file");const w=await m(S);if(!w?.sessionId)return a("no conversation recognized");const T=w.build().nodes.filter(U=>U.data.importSource),N=n.trim();let D=-1;for(let U=T.length-1;U>=0;U--){const q=T[U].data.question.trim();if(q===N||q.endsWith(N)||N.endsWith(q)){D=U;break}}if(D<0&&(D=T.length-1),D<0)return a("no turn in file yet");const O=T[D],M=O.data.attachments??[],_=PU(t,M),R=_?[...M,_]:M;p.setState(U=>({nodes:U.nodes.map(q=>q.id===e?{...q,data:{...q.data,attachments:[...(q.data.attachments??[]).filter(H=>!H.op),...R],excludedAttachmentIds:[...new Set([...q.data.excludedAttachmentIds??[],...R.map(H=>H.id)])],importSource:O.data.importSource,source:O.data.source??{question:O.data.question,response:O.data.response},agentTrace:void 0}}:q)}));const{projects:G,activeId:B}=x.getState(),$=B?G.find(U=>U.id===B):void 0;if(!$)return!0;const Z={sessionId:w.sessionId,runner:t.runtime,importedCount:D+1,tailNodeId:e};if(k($).includes(w.sessionId)){const{patchLedgerEntry:U}=await Tt(async()=>{const{patchLedgerEntry:q}=await Promise.resolve().then(()=>qr);return{patchLedgerEntry:q}},void 0);await U(B,w.sessionId,{importedCount:D+1,tailNodeId:e})}else $.sourceSession?await b(B,"chapter",Z):(await y(B,Z),x.getState().projects.find(U=>U.id===B)?.sourceSession||(x.setState(U=>({projects:U.projects.map(q=>q.id===B?{...q,sourceSession:Z}:q)})),await b(B,"chapter",Z).catch(()=>{}),x.setState(U=>({projects:U.projects.map(q=>q.id===B&&q.sourceSession?{...q,sourceSession:{...q.sourceSession,chapters:(q.sourceSession.chapters??[]).filter(H=>H.sessionId!==Z.sessionId)}}:q)}))));return!0}catch(o){return a("threw: "+(o instanceof Error?o.message:String(o)))}}async function jU(){try{const{useProjects:e}=await Tt(async()=>{const{useProjects:r}=await Promise.resolve().then(()=>qr);return{useProjects:r}},void 0),{projects:t,activeId:n}=e.getState(),a=t.find(r=>r.id===n)?.agentGuard;return{mode:a?.mode==="allow"?"allow":"ask",allow:a?.allow??[]}}catch{return{mode:"ask",allow:[]}}}async function i2(e){if(!window.desktopAgents)return;const t=e??(await r2())?.cwd;if(t)try{await window.desktopAgents.guardWrite(t,await jU())}catch{}}async function F5(e){const{useProjects:t,setProjectAgentGuard:n}=await Tt(async()=>{const{useProjects:o,setProjectAgentGuard:c}=await Promise.resolve().then(()=>qr);return{useProjects:o,setProjectAgentGuard:c}},void 0),{projects:a,activeId:r}=t.getState();if(!r)return;const s=a.find(o=>o.id===r)?.agentGuard;await n(r,{mode:e,allow:s?.allow??[]}),await i2()}async function g7(e,t=!1){const{useProjects:n,setProjectAgentGuard:a}=await Tt(async()=>{const{useProjects:d,setProjectAgentGuard:h}=await Promise.resolve().then(()=>qr);return{useProjects:d,setProjectAgentGuard:h}},void 0),{projects:r,activeId:s}=n.getState();if(!s)return;const o=r.find(d=>d.id===s)?.agentGuard,c=t?(o?.allow??[]).filter(d=>d!==e):[...new Set([...o?.allow??[],e])];await a(s,{mode:o?.mode??"ask",allow:c}),await i2()}function PU(e,t){const n=e.changes;if(!n)return null;const a=new Set;for(const d of t)for(const h of d.paths??[])a.add(h.startsWith("/")?h:`${e.cwd.replace(/\/$/,"")}/${h}`);const r=[...n.changed,...n.added].filter(d=>!a.has(d)),s=n.removed.filter(d=>!a.has(d));if(r.length===0&&s.length===0&&!n.truncated)return null;const o=d=>d.startsWith(e.cwd)?d.slice(e.cwd.length).replace(/^\//,""):d,c=[];return r.length&&c.push("Changed on disk during this turn (seen by the file system, not declared by a tool):",...r.map(d=>"- "+o(d))),s.length&&c.push("Removed:",...s.map(d=>"- "+o(d))),n.truncated&&c.push("(the directory was too large to scan completely)"),{id:`fs-${Date.now().toString(36)}`,name:"tool: fs-changes",type:"text/plain",size:0,content:c.join(`
148
+ ${p}`:p,w=pe.getState().agentEffort||void 0,C=[...new Set(oe.getState().nodes.flatMap(_=>(_.data.approvals??[]).filter(R=>R.outcome==="allowed-session"&&typeof R.rule=="string"&&R.rule.startsWith(h.runtime==="claude-code"?"claude:":h.runtime+":")).map(R=>R.rule)))];DU();let T="",N="",D="";const M=await new Promise(_=>{d.run({runtime:h.runtime,cwd:m,prompt:S,...o?.sessionPath?{sessionPath:o.sessionPath}:{},...o?.forkEntryId?{forkEntryId:o.forkEntryId}:{},images:(a??[]).map(R=>({type:"image",data:R.data,mimeType:R.mimeType})),model:{provider:h.provider,id:h.id},...w?{effort:w}:{},...C.length?{allowRules:C}:{}}).then(R=>{const G=()=>{d.abort(R)};n?.aborted&&G(),n?.addEventListener("abort",G,{once:!0}),xf.set(R,B=>{switch(B.type){case"session":{const $=B.model?.resolved;$&&window.dispatchEvent(new CustomEvent("td:agent-model-resolved",{detail:{id:s,resolved:$}})),r?.onAgentSession?.({runtime:h.runtime,sessionId:B.sessionId??null,sessionFile:B.sessionFile??null,cwd:B.cwd??m,...typeof B.effort=="string"&&B.effort?{effort:B.effort}:{}});break}case"message_update":{const $=B.assistantMessageEvent;$?.type==="text_delta"&&$.delta?(T+=$.delta,t($.delta,T)):$?.type==="thinking_delta"&&$.delta&&(N+=$.delta,r?.onReasoning?.($.delta,N));break}case"tool_execution_start":{const $=String(B.toolName??"tool"),Z=OU($,B.args);r?.onAgentTool?.({id:String(B.toolCallId??""),name:$,query:Z,phase:"start"});break}case"tool_execution_end":r?.onAgentTool?.({id:String(B.toolCallId??""),name:String(B.toolName??"tool"),query:"",phase:"end",isError:!!B.isError});break;case"extension_ui_cancelled":{const $=`dialog-${Date.now()}`,Z=String(B.title??B.method??"dialog");r?.onAgentTool?.({id:$,name:"dialog",query:Z,phase:"start"}),r?.onAgentTool?.({id:$,name:"dialog",query:"",phase:"end",isError:!0});break}case"question_answered":r?.onApprovalDecided?.({...B.auto?{auto:!0,name:String(B.title??""),query:String(B.message??""),rule:typeof B.rule=="string"?B.rule:null}:{},id:String(B.id),outcome:B.outcome??"cancelled",value:typeof B.value=="string"?B.value:null});break;case"question":r?.onApproval?.({id:String(B.id),kind:B.kind??"confirm",toolName:h.runtime,callId:null,reason:null,name:String(B.title??""),query:String(B.message??""),arguments:null,options:Array.isArray(B.options)?B.options:[],placeholder:typeof B.placeholder=="string"?B.placeholder:null,prefill:typeof B.prefill=="string"?B.prefill:null,channel:{runId:R},paths:Array.isArray(B.paths)?B.paths:[],suggest:typeof B.suggest=="string"?B.suggest:null,rule:typeof B.rule=="string"?B.rule:null});break;case"fs_changes":r?.onAgentChanges?.({changed:B.changed??[],added:B.added??[],removed:B.removed??[],truncated:!!B.truncated});break;case"run_end":D=typeof B.text=="string"&&B.text?B.text:T,xf.delete(R),n?.removeEventListener("abort",G),_({how:String(B.how??"end")});break;case"run_error":xf.delete(R),n?.removeEventListener("abort",G),_({how:"error",error:String(B.message??"agent run failed")});break}})}).catch(R=>_({how:"error",error:R instanceof Error?R.message:String(R)}))});if(n?.aborted)throw new DOMException("The operation was aborted.","AbortError");if(M.how==="error")throw new Error(M.error??"agent run failed");return D||T}async function LU(e,t,n){const a=o=>(console.warn("[agent] turn not adopted:",o,t.runtime,t.sessionFile),!1),r=window.desktopSessions;if(!r||!t.sessionFile)return a(r?"no session file":"no sessions bridge");const s=Vc[t.runtime].rootKey;try{const c=(await r.roots()).find(U=>U.key===s);if(!c)return a("no root "+s);const d=c.path.replace(/\/$/,"")+"/";if(!t.sessionFile.startsWith(d))return a("file outside root "+d);const h=t.sessionFile.slice(d.length),{anyRunnerSessionConversation:m}=await Tt(async()=>{const{anyRunnerSessionConversation:U}=await import("./index-CTQSx_k0.js");return{anyRunnerSessionConversation:U}},[]),{useStore:p}=await Tt(async()=>{const{useStore:U}=await Promise.resolve().then(()=>Hs);return{useStore:U}},void 0),{useProjects:x,registerLedgerEntry:b,updateSourceSession:y,subscribedSessionIds:k}=await Tt(async()=>{const{useProjects:U,registerLedgerEntry:q,updateSourceSession:H,subscribedSessionIds:V}=await Promise.resolve().then(()=>qr);return{useProjects:U,registerLedgerEntry:q,updateSourceSession:H,subscribedSessionIds:V}},void 0),S=await r.read(s,h);if(!S)return a("empty file");const w=await m(S);if(!w?.sessionId)return a("no conversation recognized");const T=w.build().nodes.filter(U=>U.data.importSource),N=n.trim();let D=-1;for(let U=T.length-1;U>=0;U--){const q=T[U].data.question.trim();if(q===N||q.endsWith(N)||N.endsWith(q)){D=U;break}}if(D<0&&(D=T.length-1),D<0)return a("no turn in file yet");const O=T[D],M=O.data.attachments??[],_=PU(t,M),R=_?[...M,_]:M;p.setState(U=>({nodes:U.nodes.map(q=>q.id===e?{...q,data:{...q.data,attachments:[...(q.data.attachments??[]).filter(H=>!H.op),...R],excludedAttachmentIds:[...new Set([...q.data.excludedAttachmentIds??[],...R.map(H=>H.id)])],importSource:O.data.importSource,source:O.data.source??{question:O.data.question,response:O.data.response},agentTrace:void 0}}:q)}));const{projects:G,activeId:B}=x.getState(),$=B?G.find(U=>U.id===B):void 0;if(!$)return!0;const Z={sessionId:w.sessionId,runner:t.runtime,importedCount:D+1,tailNodeId:e};if(k($).includes(w.sessionId)){const{patchLedgerEntry:U}=await Tt(async()=>{const{patchLedgerEntry:q}=await Promise.resolve().then(()=>qr);return{patchLedgerEntry:q}},void 0);await U(B,w.sessionId,{importedCount:D+1,tailNodeId:e})}else $.sourceSession?await b(B,"chapter",Z):(await y(B,Z),x.getState().projects.find(U=>U.id===B)?.sourceSession||(x.setState(U=>({projects:U.projects.map(q=>q.id===B?{...q,sourceSession:Z}:q)})),await b(B,"chapter",Z).catch(()=>{}),x.setState(U=>({projects:U.projects.map(q=>q.id===B&&q.sourceSession?{...q,sourceSession:{...q.sourceSession,chapters:(q.sourceSession.chapters??[]).filter(H=>H.sessionId!==Z.sessionId)}}:q)}))));return!0}catch(o){return a("threw: "+(o instanceof Error?o.message:String(o)))}}async function jU(){try{const{useProjects:e}=await Tt(async()=>{const{useProjects:r}=await Promise.resolve().then(()=>qr);return{useProjects:r}},void 0),{projects:t,activeId:n}=e.getState(),a=t.find(r=>r.id===n)?.agentGuard;return{mode:a?.mode==="allow"?"allow":"ask",allow:a?.allow??[]}}catch{return{mode:"ask",allow:[]}}}async function i2(e){if(!window.desktopAgents)return;const t=e??(await r2())?.cwd;if(t)try{await window.desktopAgents.guardWrite(t,await jU())}catch{}}async function F5(e){const{useProjects:t,setProjectAgentGuard:n}=await Tt(async()=>{const{useProjects:o,setProjectAgentGuard:c}=await Promise.resolve().then(()=>qr);return{useProjects:o,setProjectAgentGuard:c}},void 0),{projects:a,activeId:r}=t.getState();if(!r)return;const s=a.find(o=>o.id===r)?.agentGuard;await n(r,{mode:e,allow:s?.allow??[]}),await i2()}async function g7(e,t=!1){const{useProjects:n,setProjectAgentGuard:a}=await Tt(async()=>{const{useProjects:d,setProjectAgentGuard:h}=await Promise.resolve().then(()=>qr);return{useProjects:d,setProjectAgentGuard:h}},void 0),{projects:r,activeId:s}=n.getState();if(!s)return;const o=r.find(d=>d.id===s)?.agentGuard,c=t?(o?.allow??[]).filter(d=>d!==e):[...new Set([...o?.allow??[],e])];await a(s,{mode:o?.mode??"ask",allow:c}),await i2()}function PU(e,t){const n=e.changes;if(!n)return null;const a=new Set;for(const d of t)for(const h of d.paths??[])a.add(h.startsWith("/")?h:`${e.cwd.replace(/\/$/,"")}/${h}`);const r=[...n.changed,...n.added].filter(d=>!a.has(d)),s=n.removed.filter(d=>!a.has(d));if(r.length===0&&s.length===0&&!n.truncated)return null;const o=d=>d.startsWith(e.cwd)?d.slice(e.cwd.length).replace(/^\//,""):d,c=[];return r.length&&c.push("Changed on disk during this turn (seen by the file system, not declared by a tool):",...r.map(d=>"- "+o(d))),s.length&&c.push("Removed:",...s.map(d=>"- "+o(d))),n.truncated&&c.push("(the directory was too large to scan completely)"),{id:`fs-${Date.now().toString(36)}`,name:"tool: fs-changes",type:"text/plain",size:0,content:c.join(`
149
149
  `),op:"write",paths:[...r,...s]}}let Wa=null,Fx=null;const gd=new Set;function Us(){return Wa?Promise.resolve(Wa):(Fx??=(async()=>{const e=li();let t=null;if(e.length>0)try{t=await s0(e)}catch{}return t||(t=await fetch(`${$i}/api/models`).then(n=>n.json()).then(n=>({models:n.models??[],default:n.default??null,capabilities:n.capabilities})).catch(()=>null)),t?(Wa=y7(t),Wa):null})(),Fx)}function q5(e){return(e.split("/").pop()??e).toLowerCase()}function x7(e,t){if(t.some(r=>r.id===e))return e;const n=q5(e),a=t.find(r=>q5(r.id)===n);return a?a.id:null}const s2="thoughtdag.agentModels",b7="thoughtdag.agentModelNames",Tm=()=>typeof window<"u"&&!!window.desktopAgents;function o2(){try{const e=JSON.parse(localStorage.getItem(b7)??"{}");return e&&typeof e=="object"?e:{}}catch{return{}}}function l2(e){const t=o2();return e.map(n=>{const a=n.provider===Ya?t[n.id]:void 0;return!a||n.id.endsWith("/"+a)||n.name.includes(a)?n:{...n,name:`${n.name} · ${a}`}})}function Uf(e,t,n){if(!e)return"";const a=m7(e);if(!a)return e.split("/").pop()??e;let r=[];try{r=JSON.parse(localStorage.getItem(s2)??"[]")}catch{r=[]}const o=r.find(h=>h&&h.id===e)?.name??`${Vc[a.runtime].label} · ${a.id}`,c=n?.compact?void 0:o2()[e],d=c&&!o.includes(c)?`${o} · ${c}`:o;return t?`${d} · ${t}`:d}function y7(e){if(!Tm())return e;let t=[];try{t=JSON.parse(localStorage.getItem(s2)??"[]")}catch{t=[]}const n=e.models.filter(a=>a.provider!==Ya);return{...e,models:[...n,...l2(t.filter(a=>a&&a.provider===Ya))],agentsPending:!1}}let qx=!1,Ku=null;async function v7(){if(!(!Tm()||!Wa))return Ku||(Ku=(async()=>{const e=Wa;Tl({...e,agentsPending:!0});const t=await AU().catch(()=>[]);try{localStorage.setItem(s2,JSON.stringify(t))}catch{}const n=(Wa??e).models.filter(a=>a.provider!==Ya);Tl({...Wa??e,models:[...n,...l2(t)],agentsPending:!1})})().finally(()=>{Ku=null}),Ku)}function zU(){qx||!Tm()||(qx=!0,Us().then(()=>v7()))}function BU(e,t){if(!e||!t)return;const n=o2();if(n[e]===t)return;n[e]=t;try{localStorage.setItem(b7,JSON.stringify(n))}catch{}if(!Wa)return;const a=Wa.models.filter(s=>s.provider!==Ya),r=Wa.models.filter(s=>s.provider===Ya).map(s=>({...s,name:s.name.split(" · ").slice(0,2).join(" · ")}));Tl({...Wa,models:[...a,...l2(r)]})}typeof window<"u"&&window.addEventListener("td:agent-model-resolved",e=>{const t=e.detail;t?.id&&t?.resolved&&BU(t.id,t.resolved)});function Tl(e){Wa=e,Fx=Promise.resolve(e);for(const t of gd)t(e);if(e.agentsPending===void 0&&Tm()&&!e.models.some(t=>t.provider===Ya)){Wa=y7(e);for(const t of gd)t(Wa);qx&&v7()}}function _l(){const[e,t]=L.useState(Wa);return L.useEffect(()=>{const n=a=>t(a);return gd.add(n),Wa||Us().then(a=>{gd.has(n)&&a&&t(a)}),()=>{gd.delete(n)}},[]),e}const HU=[[/^(Read|NotebookRead)$/i,"📖"],[/^(Edit|Write|MultiEdit|NotebookEdit)$/i,"✏️"],[/^(Bash|BashOutput|Shell)$/i,"⌨️"],[/^(Grep|Glob|LS|Search|WebSearch)$/i,"🔍"],[/^(WebFetch|Fetch)$/i,"🌐"],[/^(Task|Agent)$/i,"🤖"]],w7=/^tool: (\S+?)( \(truncated\))?$/;function UU(e){const t=new Map;for(const n of e.attachments??[]){const a=n.name.match(w7);if(!a)continue;const r=a[1],s=HU.find(([c])=>c.test(r))?.[1]??"🔧",o=t.get(r);o?o.count+=1:t.set(r,{glyph:s,name:r,count:1})}return[...t.values()]}function FU(e){let t=0;for(const s of e.attachments??[])w7.test(s.name)&&(t+=$n(s.content));if(t===0)return null;const n=$n(e.question),a=$n(e.response),r=n+a+t;return{q:n,a,tool:t,total:r,toolShare:r>0?t/r:0}}function qU(e){const t=new Map;for(const n of e.attachments??[])if(!(!n.paths?.length||n.op!=="read"&&n.op!=="write"&&n.op!=="edit"))for(const a of n.paths){const r=t.get(a);r?r.op==="read"&&n.op!=="read"&&(r.op=n.op):t.set(a,{path:a,name:a.split("/").filter(Boolean).pop()??a,op:n.op})}return[...t.values()].sort((n,a)=>(n.op==="read"?1:0)-(a.op==="read"?1:0))}function WU(e,t=140){const n=e.replace(/```[\s\S]*?```/g,"").split(/\n\s*\n/).map(s=>s.replace(/!?\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/[#*`>|_~]/g,"").replace(/^\s*[-•\d.)]+\s*/gm,"").replace(/\s+/g," ").trim()).filter(s=>s.length>12&&!/[::]$/.test(s)&&!/^(sources?|references?|来源|参考)\b/i.test(s)),a=n.filter(s=>s.length>=30),r=a[a.length-1]??n[n.length-1]??e.replace(/[#*`>-]/g,"").replace(/\s+/g," ").trim();return r.length>t?`${r.slice(0,t)}…`:r}function l0(){const e=L.useRef("work");return un(t=>{const n=t.transform[2],a=e.current;return a==="work"?n<=.8&&(e.current=n<=.32?"glyph":"map"):a==="map"?n>=.9?e.current="work":n<=.32&&(e.current="glyph"):n>=.9?e.current="work":n>=.4&&(e.current="map"),e.current})}const W5={en:{name:"Rule-out / Rule-in",steps:[{id:"q",kind:"human",x:560,y:40,title:"Research question",instruction:"Type the question to differentiate: what phenomenon needs explaining?"},{id:"mechA",kind:"prompt",x:20,y:440,title:"Candidate: Mechanism A",instruction:`You advocate a low-level mechanistic account of the phenomenon. Be concrete and falsifiable.
150
150
  From this lens, give the single best candidate explanation for the question above: name the mechanism, its testable predictions, and what evidence would rule it in or out.`},{id:"mechB",kind:"prompt",x:500,y:440,title:"Candidate: Mechanism B",instruction:`You advocate a higher-level / systems account. Name the mechanism and its boundary conditions.
151
151
  From this lens, give the single best candidate explanation for the question above: name the mechanism, its testable predictions, and what evidence would rule it in or out.`},{id:"conf",kind:"prompt",x:980,y:440,title:"Candidate: Confound",instruction:`You argue the effect is an artifact or confound, not the phenomenon of interest.
@@ -156,13 +156,13 @@ For each candidate above, judge what evidence would rule it OUT and what would r
156
156
  严格从这个视角,为上面的问题给出唯一最佳的候选解释:说清机制、可检验的预测,以及什么证据能确认或排除它。`},{id:"conf",kind:"prompt",x:980,y:440,title:"候选:混杂",instruction:`你主张这个效应是假象或混杂因素,而非目标现象。
157
157
  严格从这个视角,为上面的问题给出唯一最佳的候选解释:说清疑似的混杂来源、可检验的预测,以及什么证据能确认或排除它。`},{id:"null",kind:"prompt",x:1460,y:440,title:"候选:零假设",instruction:`你主张这个效应可能不真实或被夸大,给出最强的收缩性论证。
158
158
  严格从这个视角回答上面的问题:什么会让效应消失,以及什么证据能确认或排除这一解释。`},{id:"rev",kind:"prompt",x:560,y:920,title:"鉴别评审",instruction:`你是一位严谨的方法学家,正在对相互竞争的解释做鉴别诊断。
159
- 对上面每个候选,判断什么证据能将它排除(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 VU(e){const{name:t,steps:n,edges:a}=W5[e]??W5.en,r=n.map(o=>({id:`p-${o.id}`,type:"thought",position:{x:o.x,y:o.y},dragHandle:".drag-handle",data:{question:o.title,instruction:o.instruction,stepKind:o.kind,response:"",responses:[],responseIndex:-1,isCollapsed:!1,isEditing:!1,isEditingResponse:!1,isLoading:!1,tokenCount:0,highlights:[],highlightMode:"tag",attachments:[],excludedAttachmentIds:[],includedAttachmentIds:[],roleMode:"inherit",isRoot:o.id==="q",isBranch:!1}})),s=a.map(([o,c])=>({id:`p-e-${o}-${c}`,source:`p-${o}`,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 Wx="thoughtdag:projects",V5="thoughtdag",oi=e=>`thoughtdag:project:${e}`;async function Ff(e,t){const{projects:n,activeId:a}=rn.getState();if(t&&e===a){const r=n.filter(s=>s.id!==e&&!s.archived).sort((s,o)=>o.updatedAt-s.updatedAt);r.length>0?await _s(r[0].id):await Am("My Canvas")}rn.setState(r=>({projects:r.projects.map(s=>s.id===e?{...s,archived:t}:s)})),await Sr()}async function GU(e,t){rn.setState(n=>({projects:n.projects.map(a=>a.id===e&&a.sourceSession?{...a,sourceSession:{...a.sourceSession,...t}}:a)})),await Sr()}async function $U(e,t,n){rn.setState(a=>({projects:a.projects.map(r=>{if(r.id!==e||!r.sourceSession)return r;const s=r.sourceSession;return s.sessionId===t?{...r,sourceSession:{...s,...n}}:{...r,sourceSession:{...s,chapters:s.chapters?.map(o=>o.sessionId===t?{...o,...n}:o),branches:s.branches?.map(o=>o.sessionId===t?{...o,...n}:o)}}})})),await Sr()}async function YU(e,t,n){rn.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 Sr()}async function KU(e,t){rn.setState(n=>({projects:n.projects.map(a=>{if(a.id!==e||!a.sourceSession)return a;const r=a.sourceSession,s=(r.chapters??[]).filter(d=>d.sessionId!==t),o=(r.branches??[]).filter(d=>d.sessionId!==t),c={...r,chapters:s.length?s:void 0,branches:o.length?o:void 0};return c.sessionId===t&&(c.sessionId="",c.runner="",c.importedCount=0,c.tailNodeId=""),!c.sessionId&&s.length===0&&o.length===0?{...a,sourceSession:void 0}:{...a,sourceSession:c}})})),await Sr()}function Vx(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 k7(e,t){rn.setState(n=>({projects:n.projects.map(a=>a.id===e?{...a,instantiatedFrom:{name:t,at:new Date().toISOString()}}:a)})),await Sr()}const rn=i0(()=>({projects:[],activeId:null,switching:!1}));async function Sr(){const{projects:e,activeId:t}=rn.getState();await Ur(Wx,{projects:e,activeId:t})}let G5=null;function E7(){return G5??=(async()=>{let e=await El(Wx);if(!e||e.projects.length===0){const t=await El(V5),n=crypto.randomUUID(),a=Date.now();t&&await Ur(oi(n),t),e={projects:[{id:n,name:"My Canvas",createdAt:a,updatedAt:a}],activeId:n},await Ur(Wx,e),t&&await qc(V5)}e.projects.some(t=>t.id===e.activeId)||(e.activeId=e.projects[0].id),rn.setState({projects:e.projects,activeId:e.activeId}),oe.persist.setOptions({name:oi(e.activeId)}),await oe.persist.rehydrate()})().catch(async e=>{console.error("[thoughtdag] project boot failed:",e),Ye("error",De("toast.projectsLoadFailed")),oe.persist.setOptions({name:oi("recovery")}),await oe.persist.rehydrate()}),G5}let Gx=!1;async function XU(){for(const t of Ns.values())t.abort();const e=Date.now()+1e3;for(;Ns.size>0&&Date.now()<e;)await new Promise(t=>setTimeout(t,30));await new Promise(t=>setTimeout(t,0))}const S7=[];async function _s(e){for(const r of S7)await r().catch(()=>{});const{activeId:t,switching:n,projects:a}=rn.getState();if(!(n||e===t||!a.some(r=>r.id===e))){rn.setState({switching:!0});try{await XU(),await mH(),Gx=!0,oe.persist.setOptions({name:oi(e)}),await oe.persist.rehydrate(),oe.setState({selectedNodeId:null,selectedNodeIds:[]}),rn.setState(r=>({activeId:e,projects:r.projects.map(s=>s.id===e&&s.archived?{...s,archived:!1}:s)})),await Sr()}finally{Gx=!1,rn.setState({switching:!1})}}}async function Am(e="Untitled",t="chat"){const n=crypto.randomUUID(),a=Date.now();return rn.setState(r=>({projects:[...r.projects,{id:n,name:e,createdAt:a,updatedAt:a,kind:t}]})),await Sr(),await _s(n),n}async function c2(e,t){rn.setState(n=>({projects:n.projects.map(a=>a.id===e?{...a,agentCwd:t}:a)})),await Sr()}async function QU(e,t){rn.setState(n=>({projects:n.projects.map(a=>a.id===e?{...a,agentGuard:t}:a)})),await Sr()}async function T7(e,t){rn.setState(n=>({projects:n.projects.map(a=>a.id===e?{...a,name:t}:a)})),await Sr()}async function A7(e){const{projects:t,activeId:n}=rn.getState();if(e===n){const a=t.filter(r=>r.id!==e);a.length>0?await _s(a[0].id):await Am("My Canvas")}await qc(oi(e)),rn.setState(a=>({projects:a.projects.filter(r=>r.id!==e)})),await Sr(),Tt(()=>import("./canvas-record-BYGoWCSi.js"),[]).then(a=>a.removeCanvasRecord(e)).catch(()=>{})}async function Gc(e,t,n="chat",a){const r=Date.now();rn.setState(s=>({projects:[...s.projects,{id:e,name:t,createdAt:r,updatedAt:r,kind:n,...a}]})),await Sr(),await _s(e)}async function ZU(e){const{name:t,nodes:n,edges:a}=VU(e),r=crypto.randomUUID();await Ur(oi(r),JSON.stringify({state:{nodes:n,edges:a},version:1})),await Gc(r,t,"paradigm")}let k1=null;oe.subscribe((e,t)=>{Gx||e.nodes===t.nodes&&e.edges===t.edges||(k1&&clearTimeout(k1),k1=setTimeout(()=>{const{activeId:n}=rn.getState();if(!n)return;const a=[...new Set(oe.getState().nodes.map(r=>r.data.importSource?.sessionId).filter(r=>!!r))];rn.setState(r=>({projects:r.projects.map(s=>s.id===n?{...s,updatedAt:Date.now(),provenanceSessions:a}:s)})),Sr()},1e3))});const qr=Object.freeze(Object.defineProperty({__proto__:null,adoptImportedProject:Gc,beforeSwitchHooks:S7,bootProjects:E7,createBuiltinParadigm:ZU,createProject:Am,deleteProject:A7,markInstantiatedFrom:k7,patchLedgerEntry:$U,projectStorageKey:oi,registerLedgerEntry:YU,removeLedgerEntry:KU,renameProject:T7,setProjectAgentCwd:c2,setProjectAgentGuard:QU,setProjectArchived:Ff,subscribedSessionIds:Vx,switchProject:_s,updateSourceSession:GU,useProjects:rn},Symbol.toStringTag,{value:"Module"}));function N7(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 C7(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 _7(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 M7(e){const t=e.message?.content?.parts;return Array.isArray(t)?t.filter(n=>typeof n=="string").join(`
159
+ 对上面每个候选,判断什么证据能将它排除(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 VU(e){const{name:t,steps:n,edges:a}=W5[e]??W5.en,r=n.map(o=>({id:`p-${o.id}`,type:"thought",position:{x:o.x,y:o.y},dragHandle:".drag-handle",data:{question:o.title,instruction:o.instruction,stepKind:o.kind,response:"",responses:[],responseIndex:-1,isCollapsed:!1,isEditing:!1,isEditingResponse:!1,isLoading:!1,tokenCount:0,highlights:[],highlightMode:"tag",attachments:[],excludedAttachmentIds:[],includedAttachmentIds:[],roleMode:"inherit",isRoot:o.id==="q",isBranch:!1}})),s=a.map(([o,c])=>({id:`p-e-${o}-${c}`,source:`p-${o}`,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 Wx="thoughtdag:projects",V5="thoughtdag",oi=e=>`thoughtdag:project:${e}`;async function Ff(e,t){const{projects:n,activeId:a}=rn.getState();if(t&&e===a){const r=n.filter(s=>s.id!==e&&!s.archived).sort((s,o)=>o.updatedAt-s.updatedAt);r.length>0?await _s(r[0].id):await Am("My Canvas")}rn.setState(r=>({projects:r.projects.map(s=>s.id===e?{...s,archived:t}:s)})),await Sr()}async function GU(e,t){rn.setState(n=>({projects:n.projects.map(a=>a.id===e&&a.sourceSession?{...a,sourceSession:{...a.sourceSession,...t}}:a)})),await Sr()}async function $U(e,t,n){rn.setState(a=>({projects:a.projects.map(r=>{if(r.id!==e||!r.sourceSession)return r;const s=r.sourceSession;return s.sessionId===t?{...r,sourceSession:{...s,...n}}:{...r,sourceSession:{...s,chapters:s.chapters?.map(o=>o.sessionId===t?{...o,...n}:o),branches:s.branches?.map(o=>o.sessionId===t?{...o,...n}:o)}}})})),await Sr()}async function YU(e,t,n){rn.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 Sr()}async function KU(e,t){rn.setState(n=>({projects:n.projects.map(a=>{if(a.id!==e||!a.sourceSession)return a;const r=a.sourceSession,s=(r.chapters??[]).filter(d=>d.sessionId!==t),o=(r.branches??[]).filter(d=>d.sessionId!==t),c={...r,chapters:s.length?s:void 0,branches:o.length?o:void 0};return c.sessionId===t&&(c.sessionId="",c.runner="",c.importedCount=0,c.tailNodeId=""),!c.sessionId&&s.length===0&&o.length===0?{...a,sourceSession:void 0}:{...a,sourceSession:c}})})),await Sr()}function Vx(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 k7(e,t){rn.setState(n=>({projects:n.projects.map(a=>a.id===e?{...a,instantiatedFrom:{name:t,at:new Date().toISOString()}}:a)})),await Sr()}const rn=i0(()=>({projects:[],activeId:null,switching:!1}));async function Sr(){const{projects:e,activeId:t}=rn.getState();await Ur(Wx,{projects:e,activeId:t})}let G5=null;function E7(){return G5??=(async()=>{let e=await El(Wx);if(!e||e.projects.length===0){const t=await El(V5),n=crypto.randomUUID(),a=Date.now();t&&await Ur(oi(n),t),e={projects:[{id:n,name:"My Canvas",createdAt:a,updatedAt:a}],activeId:n},await Ur(Wx,e),t&&await qc(V5)}e.projects.some(t=>t.id===e.activeId)||(e.activeId=e.projects[0].id),rn.setState({projects:e.projects,activeId:e.activeId}),oe.persist.setOptions({name:oi(e.activeId)}),await oe.persist.rehydrate()})().catch(async e=>{console.error("[thoughtdag] project boot failed:",e),Ye("error",De("toast.projectsLoadFailed")),oe.persist.setOptions({name:oi("recovery")}),await oe.persist.rehydrate()}),G5}let Gx=!1;async function XU(){for(const t of Ns.values())t.abort();const e=Date.now()+1e3;for(;Ns.size>0&&Date.now()<e;)await new Promise(t=>setTimeout(t,30));await new Promise(t=>setTimeout(t,0))}const S7=[];async function _s(e){for(const r of S7)await r().catch(()=>{});const{activeId:t,switching:n,projects:a}=rn.getState();if(!(n||e===t||!a.some(r=>r.id===e))){rn.setState({switching:!0});try{await XU(),await mH(),Gx=!0,oe.persist.setOptions({name:oi(e)}),await oe.persist.rehydrate(),oe.setState({selectedNodeId:null,selectedNodeIds:[]}),rn.setState(r=>({activeId:e,projects:r.projects.map(s=>s.id===e&&s.archived?{...s,archived:!1}:s)})),await Sr()}finally{Gx=!1,rn.setState({switching:!1})}}}async function Am(e="Untitled",t="chat"){const n=crypto.randomUUID(),a=Date.now();return rn.setState(r=>({projects:[...r.projects,{id:n,name:e,createdAt:a,updatedAt:a,kind:t}]})),await Sr(),await _s(n),n}async function c2(e,t){rn.setState(n=>({projects:n.projects.map(a=>a.id===e?{...a,agentCwd:t}:a)})),await Sr()}async function QU(e,t){rn.setState(n=>({projects:n.projects.map(a=>a.id===e?{...a,agentGuard:t}:a)})),await Sr()}async function T7(e,t){rn.setState(n=>({projects:n.projects.map(a=>a.id===e?{...a,name:t}:a)})),await Sr()}async function A7(e){const{projects:t,activeId:n}=rn.getState();if(e===n){const a=t.filter(r=>r.id!==e);a.length>0?await _s(a[0].id):await Am("My Canvas")}await qc(oi(e)),rn.setState(a=>({projects:a.projects.filter(r=>r.id!==e)})),await Sr(),Tt(()=>import("./canvas-record-Dw4tjwhH.js"),[]).then(a=>a.removeCanvasRecord(e)).catch(()=>{})}async function Gc(e,t,n="chat",a){const r=Date.now();rn.setState(s=>({projects:[...s.projects,{id:e,name:t,createdAt:r,updatedAt:r,kind:n,...a}]})),await Sr(),await _s(e)}async function ZU(e){const{name:t,nodes:n,edges:a}=VU(e),r=crypto.randomUUID();await Ur(oi(r),JSON.stringify({state:{nodes:n,edges:a},version:1})),await Gc(r,t,"paradigm")}let k1=null;oe.subscribe((e,t)=>{Gx||e.nodes===t.nodes&&e.edges===t.edges||(k1&&clearTimeout(k1),k1=setTimeout(()=>{const{activeId:n}=rn.getState();if(!n)return;const a=[...new Set(oe.getState().nodes.map(r=>r.data.importSource?.sessionId).filter(r=>!!r))];rn.setState(r=>({projects:r.projects.map(s=>s.id===n?{...s,updatedAt:Date.now(),provenanceSessions:a}:s)})),Sr()},1e3))});const qr=Object.freeze(Object.defineProperty({__proto__:null,adoptImportedProject:Gc,beforeSwitchHooks:S7,bootProjects:E7,createBuiltinParadigm:ZU,createProject:Am,deleteProject:A7,markInstantiatedFrom:k7,patchLedgerEntry:$U,projectStorageKey:oi,registerLedgerEntry:YU,removeLedgerEntry:KU,renameProject:T7,setProjectAgentCwd:c2,setProjectAgentGuard:QU,setProjectArchived:Ff,subscribedSessionIds:Vx,switchProject:_s,updateSourceSession:GU,useProjects:rn},Symbol.toStringTag,{value:"Module"}));function N7(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 C7(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 _7(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 M7(e){const t=e.message?.content?.parts;return Array.isArray(t)?t.filter(n=>typeof n=="string").join(`
160
160
  `).trim():""}function JU(e){const t=[],n=[],a=Object.values(e).filter(s=>!s.parent||!e[s.parent]),r=(s,o,c)=>{const d=e[s];if(!d)return;const h=d.message?.author?.role,m=M7(d);let p=o,x=c;if(h==="user"&&m)p=m;else if(h==="assistant"&&m){if(p!==null){const b=C7(p,m,c===null);t.push(b),c&&n.push(_7(c,b.id)),x=b.id,p=null}else if(x){const b=t.find(y=>y.id===x);b&&(b.data.response+=`
161
161
 
162
162
  `+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:ir(t,n),edges:n}}function I7(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(`
163
163
  `).trim():""}function eF(e){const t=[],n=[];let a=null,r=null;for(const s of e){const o=I7(s);if(o){if(s.sender==="human")a=o;else if(s.sender==="assistant"){if(a!==null){const c=C7(a,o,r===null);t.push(c),r&&n.push(_7(r,c.id)),r=c.id,a=null}else if(r){const c=t.find(d=>d.id===r);c&&(c.data.response+=`
164
164
 
165
- `+o,c.data.responses=[c.data.response])}}}}return{nodes:ir(t,n),edges:n}}function tF(e){const t=N7(e),n=[];if(t==="chatgpt")for(const a of e){const r=a.mapping??{},s=Object.values(r).filter(o=>["user","assistant"].includes(o.message?.author?.role??"")&&M7(o)).length;s!==0&&n.push({title:a.title||"Untitled",messageCount:s,source:"chatgpt",build:()=>JU(r)})}else if(t==="claude")for(const a of e){const r=a.chat_messages??[],s=r.filter(o=>I7(o)).length;s!==0&&n.push({title:a.name||"Untitled",messageCount:s,source:"claude",build:()=>eF(r)})}return n}function nF(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 aF(e){const t=e;return!!t&&typeof t=="object"&&t.kind==="thoughtdag-paradigm"&&Array.isArray(t.nodes)&&Array.isArray(t.edges)}const rF=()=>({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 iF(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={...rF(),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:{}}}),o=new Set(s.map(c=>c.target));for(const c of a)o.has(c.id)||(c.data.isRoot=!0);return{nodes:ir(a,s),edges:s}}const D7=1,u2=1;function Nm(e){return e.replace(/[\\/:*?"<>|]/g,"_").trim()||"canvas"}function c0(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 d2(e){await navigator.clipboard.writeText(e),Ye("success",De("toast.copied"))}function Ms(){const{projects:e,activeId:t}=rn.getState();return e.find(n=>n.id===t)?.name??"canvas"}async function bf(e){const{nodes:t}=oe.getState(),{confirmIfSensitive:n}=await Tt(async()=>{const{confirmIfSensitive:p}=await import("./sensitive-scan-Kz-yplyP.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(),o=await e2(a),{projects:c,activeId:d}=rn.getState(),h=Ms(),m=JSON.stringify({version:D7,name:h,projectId:d,exportedAt:new Date().toISOString(),instantiatedFrom:c.find(p=>p.id===d)?.instantiatedFrom,...e?.sharedReadonly?{sharedReadonly:!0}:{},nodes:Ro(o),edges:r,events:s});c0(`${Nm(h)}.thoughtdag.json`,m,"application/json"),Ye("success",He(De("toast.exported"),{name:h}))}function sF(){const{nodes:e,edges:t}=oe.getState(),n=Ms(),a=JSON.stringify({kind:"thoughtdag-paradigm",version:1,name:n,nodes:Ro(e),edges:t});c0(`${Nm(n)}.paradigm.json`,a,"application/json"),Ye("success",He(De("toast.exported"),{name:n}))}async function oF(e){const t=await e.text();let n;try{n=JSON.parse(t)}catch{const{anyRunnerSessionConversation:r}=await Tt(async()=>{const{anyRunnerSessionConversation:o}=await import("./index-Dyq9QwYZ.js");return{anyRunnerSessionConversation:o}},[]),s=await r(t);return s?{kind:"chat",conversations:[s]}:(Ye("error",De("toast.importFailedJson")),{kind:"error"})}if(aF(n)){const r=crypto.randomUUID(),s=await Sm(await O7(n.nodes));return await Ur(oi(r),JSON.stringify({state:{nodes:s,edges:n.edges},version:u2})),await Gc(r,n.name||"Paradigm","paradigm"),Ye("success",He(De("toast.imported"),{name:n.name,n:n.nodes.length})),{kind:"own",ok:!0}}if(n?.format==="thoughtdag-manifest")return Ye("error",De("toast.importManifest"),9e3),{kind:"error"};const a=N7(n);if(a==="chatgpt"||a==="claude"){const r=tF(n);return r.length===0?(Ye("error",De("toast.importNoConversations")),{kind:"error"}):{kind:"chat",conversations:r}}return{kind:"own",ok:await uF(e,n)}}function lF(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 cF(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 Tt(async()=>{const{useUiStore:d}=await Promise.resolve().then(()=>km);return{useUiStore:d}},void 0);c.getState().setArrivalFocusNodeId(r[r.length-1].id)}const o=crypto.randomUUID();await Ur(oi(o),JSON.stringify({state:{nodes:Ro(r),edges:s},version:u2})),await Gc(o,a.title.slice(0,60)),t??=o,n+=r.length}t&&Ye("success",He(De("toast.importedChats"),{n:e.length,m:n}))}async function O7(e){const t=await Us();if(!t||t.models.length===0)return e;const n=new Set,a=new Set,r=e.map(s=>{const o=s.data?.model;if(!o)return s;const c=x7(o,t.models);return c===o?s:c?(n.add(`${o} → ${c}`),{...s,data:{...s.data,model:c}}):(a.add(o),s)});return n.size&&Ye("info",He(De("import.modelsRemapped"),{list:[...n].join(",")}),9e3),a.size&&Ye("info",He(De("import.modelsMissing"),{list:[...a].join(",")}),1e4),r}async function uF(e,t){let n;try{n=t??JSON.parse(await e.text())}catch{return Ye("error",De("toast.importFailedJson")),!1}if(!Array.isArray(n.nodes)||!Array.isArray(n.edges))return Ye("error",De("toast.importFailedMissing")),!1;if(n.nodes.length>0&&!lF(n.nodes))return Ye("error",De("toast.importFailedShape"),9e3),!1;if(n.sharedReadonly&&!await Cs({title:De("import.readonlyTitle"),message:De("import.readonlyConfirm"),confirmLabel:De("common.confirm")}))return!1;if(n.sourceSession?.sessionId){const{useProjects:o,switchProject:c}=await Tt(async()=>{const{useProjects:h,switchProject:m}=await Promise.resolve().then(()=>qr);return{useProjects:h,switchProject:m}},void 0),d=o.getState().projects.find(h=>h.sourceSession?.sessionId===n.sourceSession.sessionId);if(d)return await c(d.id),Ye("info",He(De("toast.importAlreadySubscribed"),{name:d.name}),9e3),!0}const a=crypto.randomUUID(),r=await Sm(await O7(n.nodes));await Ur(oi(a),JSON.stringify({state:{nodes:Ro(r),edges:n.edges,...Array.isArray(n.events)?{events:n.events}:{}},version:u2}));const s=n.name?.trim()||e.name.replace(/\.thoughtdag\.json$|\.json$/i,"")||"Imported canvas";return await Gc(a,s,"chat",{instantiatedFrom:n.instantiatedFrom,sourceSession:n.sourceSession}),Ye("success",He(De("toast.imported"),{name:s,n:n.nodes.length})),!0}function dF(){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(`
165
+ `+o,c.data.responses=[c.data.response])}}}}return{nodes:ir(t,n),edges:n}}function tF(e){const t=N7(e),n=[];if(t==="chatgpt")for(const a of e){const r=a.mapping??{},s=Object.values(r).filter(o=>["user","assistant"].includes(o.message?.author?.role??"")&&M7(o)).length;s!==0&&n.push({title:a.title||"Untitled",messageCount:s,source:"chatgpt",build:()=>JU(r)})}else if(t==="claude")for(const a of e){const r=a.chat_messages??[],s=r.filter(o=>I7(o)).length;s!==0&&n.push({title:a.name||"Untitled",messageCount:s,source:"claude",build:()=>eF(r)})}return n}function nF(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 aF(e){const t=e;return!!t&&typeof t=="object"&&t.kind==="thoughtdag-paradigm"&&Array.isArray(t.nodes)&&Array.isArray(t.edges)}const rF=()=>({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 iF(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={...rF(),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:{}}}),o=new Set(s.map(c=>c.target));for(const c of a)o.has(c.id)||(c.data.isRoot=!0);return{nodes:ir(a,s),edges:s}}const D7=1,u2=1;function Nm(e){return e.replace(/[\\/:*?"<>|]/g,"_").trim()||"canvas"}function c0(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 d2(e){await navigator.clipboard.writeText(e),Ye("success",De("toast.copied"))}function Ms(){const{projects:e,activeId:t}=rn.getState();return e.find(n=>n.id===t)?.name??"canvas"}async function bf(e){const{nodes:t}=oe.getState(),{confirmIfSensitive:n}=await Tt(async()=>{const{confirmIfSensitive:p}=await import("./sensitive-scan-C6YN1rzZ.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(),o=await e2(a),{projects:c,activeId:d}=rn.getState(),h=Ms(),m=JSON.stringify({version:D7,name:h,projectId:d,exportedAt:new Date().toISOString(),instantiatedFrom:c.find(p=>p.id===d)?.instantiatedFrom,...e?.sharedReadonly?{sharedReadonly:!0}:{},nodes:Ro(o),edges:r,events:s});c0(`${Nm(h)}.thoughtdag.json`,m,"application/json"),Ye("success",He(De("toast.exported"),{name:h}))}function sF(){const{nodes:e,edges:t}=oe.getState(),n=Ms(),a=JSON.stringify({kind:"thoughtdag-paradigm",version:1,name:n,nodes:Ro(e),edges:t});c0(`${Nm(n)}.paradigm.json`,a,"application/json"),Ye("success",He(De("toast.exported"),{name:n}))}async function oF(e){const t=await e.text();let n;try{n=JSON.parse(t)}catch{const{anyRunnerSessionConversation:r}=await Tt(async()=>{const{anyRunnerSessionConversation:o}=await import("./index-CTQSx_k0.js");return{anyRunnerSessionConversation:o}},[]),s=await r(t);return s?{kind:"chat",conversations:[s]}:(Ye("error",De("toast.importFailedJson")),{kind:"error"})}if(aF(n)){const r=crypto.randomUUID(),s=await Sm(await O7(n.nodes));return await Ur(oi(r),JSON.stringify({state:{nodes:s,edges:n.edges},version:u2})),await Gc(r,n.name||"Paradigm","paradigm"),Ye("success",He(De("toast.imported"),{name:n.name,n:n.nodes.length})),{kind:"own",ok:!0}}if(n?.format==="thoughtdag-manifest")return Ye("error",De("toast.importManifest"),9e3),{kind:"error"};const a=N7(n);if(a==="chatgpt"||a==="claude"){const r=tF(n);return r.length===0?(Ye("error",De("toast.importNoConversations")),{kind:"error"}):{kind:"chat",conversations:r}}return{kind:"own",ok:await uF(e,n)}}function lF(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 cF(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 Tt(async()=>{const{useUiStore:d}=await Promise.resolve().then(()=>km);return{useUiStore:d}},void 0);c.getState().setArrivalFocusNodeId(r[r.length-1].id)}const o=crypto.randomUUID();await Ur(oi(o),JSON.stringify({state:{nodes:Ro(r),edges:s},version:u2})),await Gc(o,a.title.slice(0,60)),t??=o,n+=r.length}t&&Ye("success",He(De("toast.importedChats"),{n:e.length,m:n}))}async function O7(e){const t=await Us();if(!t||t.models.length===0)return e;const n=new Set,a=new Set,r=e.map(s=>{const o=s.data?.model;if(!o)return s;const c=x7(o,t.models);return c===o?s:c?(n.add(`${o} → ${c}`),{...s,data:{...s.data,model:c}}):(a.add(o),s)});return n.size&&Ye("info",He(De("import.modelsRemapped"),{list:[...n].join(",")}),9e3),a.size&&Ye("info",He(De("import.modelsMissing"),{list:[...a].join(",")}),1e4),r}async function uF(e,t){let n;try{n=t??JSON.parse(await e.text())}catch{return Ye("error",De("toast.importFailedJson")),!1}if(!Array.isArray(n.nodes)||!Array.isArray(n.edges))return Ye("error",De("toast.importFailedMissing")),!1;if(n.nodes.length>0&&!lF(n.nodes))return Ye("error",De("toast.importFailedShape"),9e3),!1;if(n.sharedReadonly&&!await Cs({title:De("import.readonlyTitle"),message:De("import.readonlyConfirm"),confirmLabel:De("common.confirm")}))return!1;if(n.sourceSession?.sessionId){const{useProjects:o,switchProject:c}=await Tt(async()=>{const{useProjects:h,switchProject:m}=await Promise.resolve().then(()=>qr);return{useProjects:h,switchProject:m}},void 0),d=o.getState().projects.find(h=>h.sourceSession?.sessionId===n.sourceSession.sessionId);if(d)return await c(d.id),Ye("info",He(De("toast.importAlreadySubscribed"),{name:d.name}),9e3),!0}const a=crypto.randomUUID(),r=await Sm(await O7(n.nodes));await Ur(oi(a),JSON.stringify({state:{nodes:Ro(r),edges:n.edges,...Array.isArray(n.events)?{events:n.events}:{}},version:u2}));const s=n.name?.trim()||e.name.replace(/\.thoughtdag\.json$|\.json$/i,"")||"Imported canvas";return await Gc(a,s,"chat",{instantiatedFrom:n.instantiatedFrom,sourceSession:n.sourceSession}),Ye("success",He(De("toast.imported"),{name:s,n:n.nodes.length})),!0}function dF(){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(`
166
166
  `);c0(`${Nm(Ms())}.events.csv`,a,"text/csv"),Ye("success",He(De("toast.exported"),{name:Ms()}))}function hF(e){const t=[`## Q: ${e.data.question}`,""],n=e.data.attachments||[];return n.length>0&&t.push(`> ${De("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(`
167
167
  `)}function R7(e,t){const n=e.reduce((a,r)=>a+$n(r.data.question+r.data.response),0);return[`# ${Ms()}`,"",`> ${t} · exported ${new Date().toISOString().slice(0,10)} · ${e.length} nodes · ~${n} tok`,"",e.map(hF).join(`
168
168
  ---
@@ -517,17 +517,17 @@ ${De("continue.genOpen")}
517
517
  ${c.join(`
518
518
  `)||"-"}`}]),h=ZS(new Date().toISOString()).slice(0,10),m=Xne(n.position);ti("note",m,{question:`**📌 ${h} · ${De("continue.recapTag")}**
519
519
 
520
- ${d.trim()}`}),o9.current?.setCenter((n.position.x+m.x)/2+260,(n.position.y+m.y)/2+140,{zoom:.75,duration:600}),Ye("success",De("continue.noteDropped"))}catch(a){Ye("error",a instanceof Error?a.message:String(a))}}}function Qne({x:e,y:t,nodeId:n,onClose:a}){const r=jt(),s=L.useRef(null),o=oe(C=>C.nodes.find(T=>T.id===n));if(L.useEffect(()=>{const C=N=>{s.current?.contains(N.target)||a()},T=N=>{N.key==="Escape"&&a()};return window.addEventListener("mousedown",C),window.addEventListener("keydown",T),()=>{window.removeEventListener("mousedown",C),window.removeEventListener("keydown",T)}},[a]),!o)return null;const c=o.data.stepKind,d=!!c,h=!d&&!!o.data.response&&!o.data.isLoading,m=d?c==="note"||c==="link"?o.data.question:"":o.data.response,p="w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5",x="text-ink-faint shrink-0",b=200,y=340,k=Math.min(e,window.innerWidth-b-8),S=Math.min(t,window.innerHeight-y-8),w=C=>()=>{a(),C()};return Za.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:S},children:[!d&&u.jsxs("button",{className:p,onClick:w(()=>{oe.getState().setSelectedNodeId(n),pe.getState().setPanelOpen(!0)}),children:[u.jsx(Io,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.openPanel")]}),h&&u.jsxs("button",{className:p,onClick:w(()=>pe.getState().setResponseViewerNodeId(n)),children:[u.jsx(RS,{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(lr,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.rerun")]}),h&&u.jsxs("button",{className:p,title:De("actions.regenBranchTitle"),onClick:w(()=>{oe.getState().regenerate(n)}),children:[u.jsx(MS,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.regenBranch")]}),h&&u.jsxs("button",{className:p,onClick:w(()=>{l9(n)}),children:[u.jsx(Vi,{size:14,strokeWidth:1.75,className:x})," ",r("continue.summarize")]}),m&&u.jsxs("button",{className:p,onClick:w(()=>{navigator.clipboard.writeText(m).then(()=>Ye("success",De("ctx.copied")))}),children:[u.jsx(Bs,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.copyContent")]}),!d&&u.jsxs("button",{className:p,title:De("exp.takeTitle"),onClick:w(()=>{Tt(()=>import("./experiment-loop-C9Q1W_wR.js"),[]).then(C=>C.takeToExperiment(n,"branch"))}),"data-take-to-experiment":!0,children:[u.jsx(rz,{size:14,strokeWidth:1.75,className:x})," ",r("exp.take")]}),!d&&u.jsxs("button",{className:p,title:De("exp.continueTitle"),onClick:w(()=>{Tt(()=>import("./experiment-loop-C9Q1W_wR.js"),[]).then(C=>C.takeToExperiment(n,"continue"))}),"data-take-to-continue":!0,children:[u.jsx(Io,{size:14,strokeWidth:1.75,className:x})," ",r("exp.continue")]}),u.jsxs("button",{className:p,onClick:w(()=>oe.getState().duplicateNode(n)),children:[u.jsx(nz,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.duplicate")]}),u.jsxs("button",{className:p,onClick:w(()=>oe.getState().setArchived([n],!o.data.archived)),children:[o.data.archived?u.jsx(TS,{size:14,strokeWidth:1.75,className:x}):u.jsx(zo,{size:14,strokeWidth:1.75,className:x}),o.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(()=>{Cs({title:De("confirm.deleteNodesTitle"),message:He(De("confirm.deleteNodes"),{n:1}),confirmLabel:De("common.delete"),danger:!0}).then(C=>{C&&oe.getState().deleteNode(n)})}),children:[u.jsx(Va,{size:14,strokeWidth:1.75,className:"shrink-0"})," ",r("common.delete")]})]}),document.body)}function Zne({onLocate:e}){const t=pe(N=>N.highlightsOverviewOpen),n=pe(N=>N.setHighlightsOverviewOpen),a=oe(N=>N.nodes),r=oe(N=>N.removeHighlight),s=oe(N=>N.weaveHighlights),o=jt(),[c,d]=L.useState("time"),[h,m]=L.useState(new Set),[p,x]=L.useState(""),b=L.useMemo(()=>{const N=[];for(const O of a){const M=O.data.question.replace(/\s+/g," ").trim().slice(0,60)||"—";for(const _ of O.data.highlights||[])N.push({hlId:_.id,text:_.text,at:_.at,nodeId:O.id,nodeTitle:M})}const D=c==="time"?[...N].sort((O,M)=>(M.at??"").localeCompare(O.at??"")):N;return D.map((O,M)=>({...O,showGroup:c==="node"&&(M===0||D[M-1].nodeTitle!==O.nodeTitle)}))},[a,c]);if(!t)return null;const y=N=>{const D=new Set(h);D.has(N)?D.delete(N):D.add(N),m(D)},k=()=>{n(!1),m(new Set),x("")},S=()=>{const N=[...h].filter(O=>b.some(M=>M.hlId===O));if(N.length===0)return;const D=[...new Set(b.filter(O=>N.includes(O.hlId)).map(O=>O.nodeId))];k(),s(D,p.trim()||void 0,N)},w=()=>{const N=b.map(D=>`- ${D.text}
520
+ ${d.trim()}`}),o9.current?.setCenter((n.position.x+m.x)/2+260,(n.position.y+m.y)/2+140,{zoom:.75,duration:600}),Ye("success",De("continue.noteDropped"))}catch(a){Ye("error",a instanceof Error?a.message:String(a))}}}function Qne({x:e,y:t,nodeId:n,onClose:a}){const r=jt(),s=L.useRef(null),o=oe(C=>C.nodes.find(T=>T.id===n));if(L.useEffect(()=>{const C=N=>{s.current?.contains(N.target)||a()},T=N=>{N.key==="Escape"&&a()};return window.addEventListener("mousedown",C),window.addEventListener("keydown",T),()=>{window.removeEventListener("mousedown",C),window.removeEventListener("keydown",T)}},[a]),!o)return null;const c=o.data.stepKind,d=!!c,h=!d&&!!o.data.response&&!o.data.isLoading,m=d?c==="note"||c==="link"?o.data.question:"":o.data.response,p="w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5",x="text-ink-faint shrink-0",b=200,y=340,k=Math.min(e,window.innerWidth-b-8),S=Math.min(t,window.innerHeight-y-8),w=C=>()=>{a(),C()};return Za.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:S},children:[!d&&u.jsxs("button",{className:p,onClick:w(()=>{oe.getState().setSelectedNodeId(n),pe.getState().setPanelOpen(!0)}),children:[u.jsx(Io,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.openPanel")]}),h&&u.jsxs("button",{className:p,onClick:w(()=>pe.getState().setResponseViewerNodeId(n)),children:[u.jsx(RS,{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(lr,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.rerun")]}),h&&u.jsxs("button",{className:p,title:De("actions.regenBranchTitle"),onClick:w(()=>{oe.getState().regenerate(n)}),children:[u.jsx(MS,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.regenBranch")]}),h&&u.jsxs("button",{className:p,onClick:w(()=>{l9(n)}),children:[u.jsx(Vi,{size:14,strokeWidth:1.75,className:x})," ",r("continue.summarize")]}),m&&u.jsxs("button",{className:p,onClick:w(()=>{navigator.clipboard.writeText(m).then(()=>Ye("success",De("ctx.copied")))}),children:[u.jsx(Bs,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.copyContent")]}),!d&&u.jsxs("button",{className:p,title:De("exp.takeTitle"),onClick:w(()=>{Tt(()=>import("./experiment-loop-BuZFR0si.js"),[]).then(C=>C.takeToExperiment(n,"branch"))}),"data-take-to-experiment":!0,children:[u.jsx(rz,{size:14,strokeWidth:1.75,className:x})," ",r("exp.take")]}),!d&&u.jsxs("button",{className:p,title:De("exp.continueTitle"),onClick:w(()=>{Tt(()=>import("./experiment-loop-BuZFR0si.js"),[]).then(C=>C.takeToExperiment(n,"continue"))}),"data-take-to-continue":!0,children:[u.jsx(Io,{size:14,strokeWidth:1.75,className:x})," ",r("exp.continue")]}),u.jsxs("button",{className:p,onClick:w(()=>oe.getState().duplicateNode(n)),children:[u.jsx(nz,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.duplicate")]}),u.jsxs("button",{className:p,onClick:w(()=>oe.getState().setArchived([n],!o.data.archived)),children:[o.data.archived?u.jsx(TS,{size:14,strokeWidth:1.75,className:x}):u.jsx(zo,{size:14,strokeWidth:1.75,className:x}),o.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(()=>{Cs({title:De("confirm.deleteNodesTitle"),message:He(De("confirm.deleteNodes"),{n:1}),confirmLabel:De("common.delete"),danger:!0}).then(C=>{C&&oe.getState().deleteNode(n)})}),children:[u.jsx(Va,{size:14,strokeWidth:1.75,className:"shrink-0"})," ",r("common.delete")]})]}),document.body)}function Zne({onLocate:e}){const t=pe(N=>N.highlightsOverviewOpen),n=pe(N=>N.setHighlightsOverviewOpen),a=oe(N=>N.nodes),r=oe(N=>N.removeHighlight),s=oe(N=>N.weaveHighlights),o=jt(),[c,d]=L.useState("time"),[h,m]=L.useState(new Set),[p,x]=L.useState(""),b=L.useMemo(()=>{const N=[];for(const O of a){const M=O.data.question.replace(/\s+/g," ").trim().slice(0,60)||"—";for(const _ of O.data.highlights||[])N.push({hlId:_.id,text:_.text,at:_.at,nodeId:O.id,nodeTitle:M})}const D=c==="time"?[...N].sort((O,M)=>(M.at??"").localeCompare(O.at??"")):N;return D.map((O,M)=>({...O,showGroup:c==="node"&&(M===0||D[M-1].nodeTitle!==O.nodeTitle)}))},[a,c]);if(!t)return null;const y=N=>{const D=new Set(h);D.has(N)?D.delete(N):D.add(N),m(D)},k=()=>{n(!1),m(new Set),x("")},S=()=>{const N=[...h].filter(O=>b.some(M=>M.hlId===O));if(N.length===0)return;const D=[...new Set(b.filter(O=>N.includes(O.hlId)).map(O=>O.nodeId))];k(),s(D,p.trim()||void 0,N)},w=()=>{const N=b.map(D=>`- ${D.text}
521
521
  — ${D.nodeTitle}${D.at?` · ${D.at.slice(0,10)}`:""}`);h2(`# ${o("hlov.title")}
522
522
 
523
523
  ${N.join(`
524
524
  `)}
525
525
  `)},C="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",T=(N,D)=>u.jsx("button",{onClick:()=>d(N),className:`text-2xs px-2.5 py-1 rounded-full transition-colors ${c===N?"bg-accent/10 text-accent":"text-ink-faint hover:bg-wash"}`,children:D});return Za.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:N=>N.stopPropagation(),children:[u.jsxs("div",{className:"flex items-center gap-2 px-5 py-3 border-b border-line shrink-0",children:[u.jsx(jd,{size:15,strokeWidth:1.75,className:"text-amber-500"}),u.jsx("span",{className:"text-sm font-semibold text-ink",children:o("hlov.title")}),u.jsx("span",{className:"text-2xs text-ink-faint",children:He(o("hlov.count"),{n:b.length})}),u.jsx("div",{className:"flex-1"}),T("time",o("hlov.byTime")),T("node",o("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(mn,{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:o("hlov.empty")}),b.map(N=>u.jsxs("div",{children:[N.showGroup&&u.jsx("div",{className:"text-2xs text-ink-faint font-medium mt-3 mb-1 first:mt-0 truncate",children:N.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(N.hlId),onChange:()=>y(N.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:N.text})}),c==="time"&&u.jsxs("button",{className:C,onClick:()=>{k(),e(N.nodeId)},title:o("hlov.locateTitle"),children:[N.nodeTitle.slice(0,14),N.nodeTitle.length>14?"…":""]}),c==="node"&&u.jsx("button",{className:C,onClick:()=>{k(),e(N.nodeId)},title:o("hlov.locateTitle"),children:"↦"}),N.at&&u.jsx("span",{className:"shrink-0 text-2xs text-ink-faint font-mono mt-0.5",children:N.at.slice(5,10)}),u.jsx("button",{onClick:()=>r(N.nodeId,N.hlId),title:o("common.delete"),className:"text-ink-faint hover:text-red-500 w-5 h-5 rounded-full flex items-center justify-center transition-colors shrink-0 opacity-0 group-hover:opacity-100",children:u.jsx(Va,{size:12,strokeWidth:1.75})})]})]},N.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:N=>x(N.target.value),onKeyDown:N=>{N.key==="Enter"&&!Qa(N)&&S()},placeholder:o("toolbar.intentPlaceholder"),className:"flex-1 text-xs border border-amber-500/30 rounded-lg px-3 py-2 focus:outline-none focus:ring-1 focus:ring-amber-500 bg-amber-500/5"}),u.jsx("button",{onClick:S,className:"text-xs bg-amber-500 hover:bg-amber-400 text-white px-3 py-2 rounded-lg transition-colors shrink-0",children:He(o("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?He(o("hlov.picked"),{n:h.size}):o("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:o("hlov.exportTitle"),children:[u.jsx(Tc,{size:12,strokeWidth:1.75})," ",o("hlov.export")]})]})]})]})}),document.body)}const Jne={pdf:vi,img:yz,txt:vi,note:Vi,link:Do};function eae({onLocate:e}){const t=pe(x=>x.materialsOverviewOpen),n=pe(x=>x.setMaterialsOverviewOpen),a=oe(x=>x.nodes),r=jt(),[s,o]=L.useState("time"),c=L.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(`
526
- `)[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 S=y.data.question.replace(/\s+/g," ").trim().slice(0,60)||(k==="file"?r("glyph.file"):"—");for(const w of y.data.attachments||[]){const C=w.type==="application/pdf"?"pdf":w.type.startsWith("image/")?"img":"txt";x.push({key:w.id,name:w.name,icon:C,sizeKB:w.size/1024,at:w.addedAt,nodeId:y.id,nodeTitle:S,canOpen:C==="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(),pe.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:()=>o(x),className:`text-2xs px-2.5 py-1 rounded-full transition-colors ${s===x?"bg-accent/10 text-accent":"text-ink-faint hover:bg-wash"}`,children:b});return Za.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(wi,{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:He(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(mn,{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=Jne[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(Io,{size:14,strokeWidth:1.75})})]})]},x.key)})]})]})}),document.body)}function tae(e){const t=e.data.stepKind;return t==="note"||t==="file"||t==="link"||t==="frame"?t:e.data.condensedFrom?.length?"distill":"qa"}function nae(e,t){let n=0,a=e.indexOf(t);for(;a!==-1;)n+=1,a=e.indexOf(t,a+t.length);return n}function aae(e,t,n){const r=Math.max(0,t-40),s=Math.min(e.length,t+n+60),o=r>0?"…":"",c=s<e.length?"…":"";return{snippet:o+e.slice(r,s)+c,matchStart:o.length+(t-r)}}function rae(e,t){const n=t.trim().toLowerCase();if(!n)return[];const a=[];for(const r of e){const s=r.data;if(s.stepKind==="fanout")continue;const o=[s.question??"",s.response??"",...(s.highlights??[]).map(p=>p.text),s.linkTitle??"",...(s.attachments??[]).map(p=>p.name),s.summaries?.[s.responseIndex]??s.summary??""];let c=0,d=null;for(const p of o){if(!p)continue;const x=p.toLowerCase(),b=x.indexOf(n);b!==-1&&(c+=nae(x,n),d||(d={text:p,at:b}))}if(!d)continue;const{snippet:h,matchStart:m}=aae(d.text,d.at,n.length);a.push({nodeId:r.id,kind:tae(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 iae={qa:LS,note:Vi,file:vi,link:Do,frame:Lx,distill:ym},sx=50;function sae({open:e,onClose:t,onLocate:n}){const a=jt(),r=oe(w=>w.nodes),s=pe(w=>w.setSearchHitIds),[o,c]=L.useState(""),[d,h]=L.useState(0),m=L.useRef(null),[p,x]=L.useState(e);p!==e&&(x(e),e&&(c(""),h(0))),L.useEffect(()=>{e&&setTimeout(()=>m.current?.focus(),50)},[e]);const[b,y]=L.useState("");L.useEffect(()=>{const w=setTimeout(()=>y(o),120);return()=>clearTimeout(w)},[o]);const k=L.useMemo(()=>e?rae(r,b):[],[e,r,b]);if(L.useEffect(()=>{if(!e||!b.trim()){s(null);return}s(new Set(k.map(w=>w.nodeId)))},[e,b,k,s]),L.useEffect(()=>()=>s(null),[s]),!e)return null;const S=w=>{n(w.nodeId);const C=b.trim().toLowerCase();setTimeout(()=>{const T=document.querySelector("[data-focus-panel]");if(!T||!C)return;const N=document.createTreeWalker(T,NodeFilter.SHOW_TEXT);let D;for(;D=N.nextNode();)if(D.textContent?.toLowerCase().includes(C)){const O=D.parentElement;O?.scrollIntoView({block:"center",behavior:"smooth"}),O?.animate([{backgroundColor:"rgba(107, 92, 231, 0.22)"},{backgroundColor:"transparent"}],{duration:1800,easing:"ease-out"});break}},500)};return 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(Pf,{size:15,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),u.jsx("input",{ref:m,type:"text",value:o,onChange:w=>{c(w.target.value),h(0)},onKeyDown:w=>{w.key==="Escape"&&(w.stopPropagation(),t()),w.key==="ArrowDown"&&(w.preventDefault(),h(C=>Math.min(C+1,k.length-1))),w.key==="ArrowUp"&&(w.preventDefault(),h(C=>Math.max(C-1,0))),w.key==="Enter"&&!Qa(w)&&k[d]&&(w.preventDefault(),S(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}),o&&u.jsx("span",{className:"text-2xs text-ink-faint shrink-0",children:He(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(mn,{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,sx).map((w,C)=>{const T=iae[w.kind],D=r.find(O=>O.id===w.nodeId)?.data.question||"—";return u.jsx("li",{children:u.jsxs("button",{onClick:()=>S(w),onMouseEnter:()=>h(C),className:`w-full text-left px-4 py-2 transition-colors ${C===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 ${C===d?"text-accent":"text-ink"}`,children:[u.jsx(T,{size:12,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),u.jsx("span",{className:"truncate flex-1 min-w-0",children:D}),w.archived&&u.jsx(zo,{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>sx&&u.jsx("li",{className:"px-4 py-2 text-2xs text-ink-faint",children:He(a("search.more"),{n:k.length-sx})})]})]})})}const dE=new Set(["note","file","link"]),Mi=e=>{const t=(e?.data.question??"").replace(/\s+/g," ").trim();return t.length>24?`${t.slice(0,24)}…`:t||"(空)"};function ox(e,t,n){const a=new Set([e]),r=[e];for(;r.length;){const s=r.shift();for(const o of n.get(s)??[]){if(o===t)return!0;a.has(o)||(a.add(o),r.push(o))}}return!1}function lx(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 hE(e,t){const n=[],a=new Map(e.map(_=>[_.id,_])),r=t.filter(_=>!_.data?.isCrossLink),s=t.filter(_=>_.data?.isCrossLink),o=lx(r),c=lx(t);for(const _ of r){const R=lx(r.filter(G=>G.id!==_.id));ox(_.source,_.target,R)&&n.push({tier:1,kind:"residual-edge",fixable:!0,params:{a:Mi(a.get(_.source)),b:Mi(a.get(_.target))},nodeIds:[_.target,_.source],edgeIds:[_.id]})}for(const _ of s)ox(_.source,_.target,o)&&n.push({tier:1,kind:"shadow-reference",fixable:!0,params:{a:Mi(a.get(_.source)),b:Mi(a.get(_.target))},nodeIds:[_.target,_.source],edgeIds:[_.id]});const d=new Map;for(const _ of r)d.has(_.source)||d.set(_.source,[]),d.get(_.source).push(_.target);const h=[];for(const _ of d.values()){const R=_.filter(B=>a.get(B)?.data.stepKind==="prompt"),G=_.filter(B=>a.get(B)?.data.isBranch);R.length>=2&&h.push(R),G.length>=2&&h.push(G)}for(const _ of h)for(const R of _)for(const G of _)if(R!==G&&ox(R,G,c)){const B=t.find($=>$.source===R&&$.target===G);n.push({tier:1,kind:"blind-pool-breach",fixable:!!B,params:{a:Mi(a.get(G)),b:Mi(a.get(R))},nodeIds:[G,R],edgeIds:B?[B.id]:[]})}for(const _ of h){const R=_.map(B=>new Set(t.filter($=>$.target===B).map($=>$.source))),G=new Set([...R[0]].filter(B=>R.every($=>$.has(B))));_.forEach((B,$)=>{const Z=[...R[$]].filter(U=>!G.has(U)&&!_.includes(U));Z.length>0&&n.push({tier:1,kind:"pool-asymmetry",fixable:!1,params:{a:Mi(a.get(B)),n:Z.length},nodeIds:[B,...Z],edgeIds:[]})})}const m=e.filter(_=>!dE.has(_.data.stepKind??"")&&_.data.stepKind!=="frame"),p=new Map,x=new Map,b=_=>$n(_.data.question+_.data.response),y=new Map;for(const _ of m)y.set(_.id,0);for(const _ of r)y.has(_.target)&&y.has(_.source)&&y.set(_.target,(y.get(_.target)??0)+1);const k=m.filter(_=>(y.get(_.id)??0)===0).map(_=>_.id),S=[],w=new Map(y);for(;k.length;){const _=k.shift();S.push(_);for(const R of o.get(_)??[])w.has(R)&&(w.set(R,w.get(R)-1),w.get(R)===0&&k.push(R))}for(const _ of S){const R=a.get(_),G=r.filter(Z=>Z.target===_&&p.has(Z.source)),B=G.length?Math.max(...G.map(Z=>p.get(Z.source)))+1:1,$=G.length?Math.max(...G.map(Z=>x.get(Z.source)))+b(R):b(R);p.set(_,B),x.set(_,$)}const C=m.filter(_=>!(o.get(_.id)??[]).length&&!_.data.archived),T=C.filter(_=>(p.get(_.id)??0)>=8||(x.get(_.id)??0)>=15e3).sort((_,R)=>(p.get(R.id)??0)-(p.get(_.id)??0)).slice(0,3);for(const _ of T)n.push({tier:2,kind:"long-chain",fixable:!1,params:{a:Mi(_),d:p.get(_.id)??0,tok:x.get(_.id)??0},nodeIds:[_.id],edgeIds:[]});const N=C.filter(_=>_.data.response);N.length>=4&&n.push({tier:2,kind:"open-branches",fixable:!1,params:{n:N.length},nodeIds:N.map(_=>_.id),edgeIds:[]});for(const _ of m){const R=r.filter(B=>B.target===_.id).length,G=(o.get(_.id)??[]).length;R>=2&&G>=1&&n.push({tier:2,kind:"collider-continuation",fixable:!1,params:{a:Mi(_),n:R},nodeIds:[_.id],edgeIds:[]})}const D=e.filter(_=>dE.has(_.data.stepKind??"")&&!t.some(R=>R.source===_.id));D.length>0&&n.push({tier:2,kind:"orphan-materials",fixable:!1,params:{n:D.length},nodeIds:D.map(_=>_.id),edgeIds:[]});const O=_=>{const R=new Set,G=[_];for(;G.length;)for(const B of o.get(G.shift())??[])R.has(B)||(R.add(B),G.push(B));return R.size},M=m.map(_=>({n:_,c:O(_.id)})).filter(({c:_})=>_>=5).sort((_,R)=>R.c-_.c).slice(0,3);for(const{n:_,c:R}of M)n.push({tier:2,kind:"load-bearing",fixable:!1,params:{a:Mi(_),n:R},nodeIds:[_.id],edgeIds:[]});return n.sort((_,R)=>_.tier-R.tier)}const oae={"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 lae({onLocate:e,openPing:t=0,showTrigger:n=!0}){const a=oe(w=>w.deleteEdges),r=jt(),[s,o]=L.useState(!1),[c,d]=L.useState([]),h=L.useRef(null),[m,p]=L.useState(t);L.useEffect(()=>{if(!s)return;const w=C=>{h.current?.contains(C.target)||o(!1)};return window.addEventListener("mousedown",w),()=>window.removeEventListener("mousedown",w)},[s]);const x=()=>{const{nodes:w,edges:C}=oe.getState();d(hE(w,C)),o(!0)};t!==m&&(p(t),x());const b=w=>{a(w.edgeIds);const{nodes:C,edges:T}=oe.getState();d(hE(C,T))},y=c.filter(w=>w.tier===1),k=c.filter(w=>w.tier===2),S=(w,C)=>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:He(r(oae[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(ld,{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(Va,{size:13,strokeWidth:1.75})})]})]},`${w.kind}-${C}`);return u.jsxs("div",{ref:h,className:"relative",children:[n&&u.jsx("button",{onClick:()=>s?o(!1):x(),className:`bg-card/90 backdrop-blur border rounded-lg w-8 h-8 flex items-center justify-center shadow-sm transition-colors ${s?"border-accent/40 text-accent":"border-line text-ink-faint hover:bg-wash"}`,title:r("toolbar.diagnose"),children:u.jsx(zS,{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?"":He(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(S)]}),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(S)]})]})]})}async function c9(e,t){const{default:n}=await Tt(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&&cae(r,t.baseUrl),r}function cae(e,t){const n=a=>{try{const r=new URL(a,t);return/^https?:$/.test(r.protocol)?r.href:null}catch{return null}};e.querySelectorAll("link").forEach(a=>{const r=a.getAttribute("href"),s=r?n(r):null;(a.getAttribute("rel")??"").toLowerCase()!=="stylesheet"||!s?a.remove():a.setAttribute("href",s)});for(const[a,r]of[["img","src"],["source","src"],["video","poster"],["a","href"]])e.querySelectorAll(`${a}[${r}]`).forEach(s=>{const o=s.getAttribute(r),c=o?n(o):null;c?s.setAttribute(r,c):s.removeAttribute(r)});e.querySelectorAll("img[srcset], source[srcset]").forEach(a=>a.removeAttribute("srcset"))}async function uae(){const[{default:e},t]=await Promise.all([Tt(()=>import("./turndown.browser.es-kLzRgxYD.js"),[]),Tt(()=>import("./turndown-plugin-gfm.cjs-2uYHu5V7.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 fE(e){return(e.textContent??"").trim().length>0||!!e.querySelector("img,svg,canvas,video")}function oy(e){const t=Array.from(e.querySelectorAll(".reveal .slides > section"));if(t.length>=2){const s=[];for(const o of t){const c=Array.from(o.children).filter(d=>d.tagName==="SECTION");c.length>0?s.push(...c):s.push(o)}return s}const n=new Map;for(const s of Array.from(e.body?.querySelectorAll("[class]")??[])){const o=s.getAttribute("class")??"";if(!/(?:^|[\s_-])(?:slide|page)(?:[\s_-]|$)/i.test(o)||!fE(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(fE);return r.length>=3?r:null}async function dae(e,t){const n=await c9(e,t),a=await uae(),r=oy(n);if(r)return{markdown:r.map((d,h)=>`<!-- tdag-page:${h+1} -->
526
+ `)[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 S=y.data.question.replace(/\s+/g," ").trim().slice(0,60)||(k==="file"?r("glyph.file"):"—");for(const w of y.data.attachments||[]){const C=w.type==="application/pdf"?"pdf":w.type.startsWith("image/")?"img":"txt";x.push({key:w.id,name:w.name,icon:C,sizeKB:w.size/1024,at:w.addedAt,nodeId:y.id,nodeTitle:S,canOpen:C==="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(),pe.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:()=>o(x),className:`text-2xs px-2.5 py-1 rounded-full transition-colors ${s===x?"bg-accent/10 text-accent":"text-ink-faint hover:bg-wash"}`,children:b});return Za.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(wi,{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:He(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(mn,{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=Jne[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(Io,{size:14,strokeWidth:1.75})})]})]},x.key)})]})]})}),document.body)}function tae(e){const t=e.data.stepKind;return t==="note"||t==="file"||t==="link"||t==="frame"?t:e.data.condensedFrom?.length?"distill":"qa"}function nae(e,t){let n=0,a=e.indexOf(t);for(;a!==-1;)n+=1,a=e.indexOf(t,a+t.length);return n}function aae(e,t,n){const r=Math.max(0,t-40),s=Math.min(e.length,t+n+60),o=r>0?"…":"",c=s<e.length?"…":"";return{snippet:o+e.slice(r,s)+c,matchStart:o.length+(t-r)}}function rae(e,t){const n=t.trim().toLowerCase();if(!n)return[];const a=[];for(const r of e){const s=r.data;if(s.stepKind==="fanout")continue;const o=[s.question??"",s.response??"",...(s.highlights??[]).map(p=>p.text),s.linkTitle??"",...(s.attachments??[]).map(p=>p.name),s.summaries?.[s.responseIndex]??s.summary??""];let c=0,d=null;for(const p of o){if(!p)continue;const x=p.toLowerCase(),b=x.indexOf(n);b!==-1&&(c+=nae(x,n),d||(d={text:p,at:b}))}if(!d)continue;const{snippet:h,matchStart:m}=aae(d.text,d.at,n.length);a.push({nodeId:r.id,kind:tae(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 iae={qa:LS,note:Vi,file:vi,link:Do,frame:Lx,distill:ym},sx=50;function sae({open:e,onClose:t,onLocate:n}){const a=jt(),r=oe(w=>w.nodes),s=pe(w=>w.setSearchHitIds),[o,c]=L.useState(""),[d,h]=L.useState(0),m=L.useRef(null),[p,x]=L.useState(e);p!==e&&(x(e),e&&(c(""),h(0))),L.useEffect(()=>{e&&setTimeout(()=>m.current?.focus(),50)},[e]);const[b,y]=L.useState("");L.useEffect(()=>{const w=setTimeout(()=>y(o),120);return()=>clearTimeout(w)},[o]);const k=L.useMemo(()=>e?rae(r,b):[],[e,r,b]);if(L.useEffect(()=>{if(!e||!b.trim()){s(null);return}s(new Set(k.map(w=>w.nodeId)))},[e,b,k,s]),L.useEffect(()=>()=>s(null),[s]),!e)return null;const S=w=>{n(w.nodeId);const C=b.trim().toLowerCase();setTimeout(()=>{const T=document.querySelector("[data-focus-panel]");if(!T||!C)return;const N=document.createTreeWalker(T,NodeFilter.SHOW_TEXT);let D;for(;D=N.nextNode();)if(D.textContent?.toLowerCase().includes(C)){const O=D.parentElement;O?.scrollIntoView({block:"center",behavior:"smooth"}),O?.animate([{backgroundColor:"rgba(107, 92, 231, 0.22)"},{backgroundColor:"transparent"}],{duration:1800,easing:"ease-out"});break}},500)};return 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(Pf,{size:15,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),u.jsx("input",{ref:m,type:"text",value:o,onChange:w=>{c(w.target.value),h(0)},onKeyDown:w=>{w.key==="Escape"&&(w.stopPropagation(),t()),w.key==="ArrowDown"&&(w.preventDefault(),h(C=>Math.min(C+1,k.length-1))),w.key==="ArrowUp"&&(w.preventDefault(),h(C=>Math.max(C-1,0))),w.key==="Enter"&&!Qa(w)&&k[d]&&(w.preventDefault(),S(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}),o&&u.jsx("span",{className:"text-2xs text-ink-faint shrink-0",children:He(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(mn,{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,sx).map((w,C)=>{const T=iae[w.kind],D=r.find(O=>O.id===w.nodeId)?.data.question||"—";return u.jsx("li",{children:u.jsxs("button",{onClick:()=>S(w),onMouseEnter:()=>h(C),className:`w-full text-left px-4 py-2 transition-colors ${C===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 ${C===d?"text-accent":"text-ink"}`,children:[u.jsx(T,{size:12,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),u.jsx("span",{className:"truncate flex-1 min-w-0",children:D}),w.archived&&u.jsx(zo,{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>sx&&u.jsx("li",{className:"px-4 py-2 text-2xs text-ink-faint",children:He(a("search.more"),{n:k.length-sx})})]})]})})}const dE=new Set(["note","file","link"]),Mi=e=>{const t=(e?.data.question??"").replace(/\s+/g," ").trim();return t.length>24?`${t.slice(0,24)}…`:t||"(空)"};function ox(e,t,n){const a=new Set([e]),r=[e];for(;r.length;){const s=r.shift();for(const o of n.get(s)??[]){if(o===t)return!0;a.has(o)||(a.add(o),r.push(o))}}return!1}function lx(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 hE(e,t){const n=[],a=new Map(e.map(_=>[_.id,_])),r=t.filter(_=>!_.data?.isCrossLink),s=t.filter(_=>_.data?.isCrossLink),o=lx(r),c=lx(t);for(const _ of r){const R=lx(r.filter(G=>G.id!==_.id));ox(_.source,_.target,R)&&n.push({tier:1,kind:"residual-edge",fixable:!0,params:{a:Mi(a.get(_.source)),b:Mi(a.get(_.target))},nodeIds:[_.target,_.source],edgeIds:[_.id]})}for(const _ of s)ox(_.source,_.target,o)&&n.push({tier:1,kind:"shadow-reference",fixable:!0,params:{a:Mi(a.get(_.source)),b:Mi(a.get(_.target))},nodeIds:[_.target,_.source],edgeIds:[_.id]});const d=new Map;for(const _ of r)d.has(_.source)||d.set(_.source,[]),d.get(_.source).push(_.target);const h=[];for(const _ of d.values()){const R=_.filter(B=>a.get(B)?.data.stepKind==="prompt"),G=_.filter(B=>a.get(B)?.data.isBranch);R.length>=2&&h.push(R),G.length>=2&&h.push(G)}for(const _ of h)for(const R of _)for(const G of _)if(R!==G&&ox(R,G,c)){const B=t.find($=>$.source===R&&$.target===G);n.push({tier:1,kind:"blind-pool-breach",fixable:!!B,params:{a:Mi(a.get(G)),b:Mi(a.get(R))},nodeIds:[G,R],edgeIds:B?[B.id]:[]})}for(const _ of h){const R=_.map(B=>new Set(t.filter($=>$.target===B).map($=>$.source))),G=new Set([...R[0]].filter(B=>R.every($=>$.has(B))));_.forEach((B,$)=>{const Z=[...R[$]].filter(U=>!G.has(U)&&!_.includes(U));Z.length>0&&n.push({tier:1,kind:"pool-asymmetry",fixable:!1,params:{a:Mi(a.get(B)),n:Z.length},nodeIds:[B,...Z],edgeIds:[]})})}const m=e.filter(_=>!dE.has(_.data.stepKind??"")&&_.data.stepKind!=="frame"),p=new Map,x=new Map,b=_=>$n(_.data.question+_.data.response),y=new Map;for(const _ of m)y.set(_.id,0);for(const _ of r)y.has(_.target)&&y.has(_.source)&&y.set(_.target,(y.get(_.target)??0)+1);const k=m.filter(_=>(y.get(_.id)??0)===0).map(_=>_.id),S=[],w=new Map(y);for(;k.length;){const _=k.shift();S.push(_);for(const R of o.get(_)??[])w.has(R)&&(w.set(R,w.get(R)-1),w.get(R)===0&&k.push(R))}for(const _ of S){const R=a.get(_),G=r.filter(Z=>Z.target===_&&p.has(Z.source)),B=G.length?Math.max(...G.map(Z=>p.get(Z.source)))+1:1,$=G.length?Math.max(...G.map(Z=>x.get(Z.source)))+b(R):b(R);p.set(_,B),x.set(_,$)}const C=m.filter(_=>!(o.get(_.id)??[]).length&&!_.data.archived),T=C.filter(_=>(p.get(_.id)??0)>=8||(x.get(_.id)??0)>=15e3).sort((_,R)=>(p.get(R.id)??0)-(p.get(_.id)??0)).slice(0,3);for(const _ of T)n.push({tier:2,kind:"long-chain",fixable:!1,params:{a:Mi(_),d:p.get(_.id)??0,tok:x.get(_.id)??0},nodeIds:[_.id],edgeIds:[]});const N=C.filter(_=>_.data.response);N.length>=4&&n.push({tier:2,kind:"open-branches",fixable:!1,params:{n:N.length},nodeIds:N.map(_=>_.id),edgeIds:[]});for(const _ of m){const R=r.filter(B=>B.target===_.id).length,G=(o.get(_.id)??[]).length;R>=2&&G>=1&&n.push({tier:2,kind:"collider-continuation",fixable:!1,params:{a:Mi(_),n:R},nodeIds:[_.id],edgeIds:[]})}const D=e.filter(_=>dE.has(_.data.stepKind??"")&&!t.some(R=>R.source===_.id));D.length>0&&n.push({tier:2,kind:"orphan-materials",fixable:!1,params:{n:D.length},nodeIds:D.map(_=>_.id),edgeIds:[]});const O=_=>{const R=new Set,G=[_];for(;G.length;)for(const B of o.get(G.shift())??[])R.has(B)||(R.add(B),G.push(B));return R.size},M=m.map(_=>({n:_,c:O(_.id)})).filter(({c:_})=>_>=5).sort((_,R)=>R.c-_.c).slice(0,3);for(const{n:_,c:R}of M)n.push({tier:2,kind:"load-bearing",fixable:!1,params:{a:Mi(_),n:R},nodeIds:[_.id],edgeIds:[]});return n.sort((_,R)=>_.tier-R.tier)}const oae={"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 lae({onLocate:e,openPing:t=0,showTrigger:n=!0}){const a=oe(w=>w.deleteEdges),r=jt(),[s,o]=L.useState(!1),[c,d]=L.useState([]),h=L.useRef(null),[m,p]=L.useState(t);L.useEffect(()=>{if(!s)return;const w=C=>{h.current?.contains(C.target)||o(!1)};return window.addEventListener("mousedown",w),()=>window.removeEventListener("mousedown",w)},[s]);const x=()=>{const{nodes:w,edges:C}=oe.getState();d(hE(w,C)),o(!0)};t!==m&&(p(t),x());const b=w=>{a(w.edgeIds);const{nodes:C,edges:T}=oe.getState();d(hE(C,T))},y=c.filter(w=>w.tier===1),k=c.filter(w=>w.tier===2),S=(w,C)=>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:He(r(oae[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(ld,{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(Va,{size:13,strokeWidth:1.75})})]})]},`${w.kind}-${C}`);return u.jsxs("div",{ref:h,className:"relative",children:[n&&u.jsx("button",{onClick:()=>s?o(!1):x(),className:`bg-card/90 backdrop-blur border rounded-lg w-8 h-8 flex items-center justify-center shadow-sm transition-colors ${s?"border-accent/40 text-accent":"border-line text-ink-faint hover:bg-wash"}`,title:r("toolbar.diagnose"),children:u.jsx(zS,{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?"":He(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(S)]}),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(S)]})]})]})}async function c9(e,t){const{default:n}=await Tt(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&&cae(r,t.baseUrl),r}function cae(e,t){const n=a=>{try{const r=new URL(a,t);return/^https?:$/.test(r.protocol)?r.href:null}catch{return null}};e.querySelectorAll("link").forEach(a=>{const r=a.getAttribute("href"),s=r?n(r):null;(a.getAttribute("rel")??"").toLowerCase()!=="stylesheet"||!s?a.remove():a.setAttribute("href",s)});for(const[a,r]of[["img","src"],["source","src"],["video","poster"],["a","href"]])e.querySelectorAll(`${a}[${r}]`).forEach(s=>{const o=s.getAttribute(r),c=o?n(o):null;c?s.setAttribute(r,c):s.removeAttribute(r)});e.querySelectorAll("img[srcset], source[srcset]").forEach(a=>a.removeAttribute("srcset"))}async function uae(){const[{default:e},t]=await Promise.all([Tt(()=>import("./turndown.browser.es-kLzRgxYD.js"),[]),Tt(()=>import("./turndown-plugin-gfm.cjs-CqvfCrbV.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 fE(e){return(e.textContent??"").trim().length>0||!!e.querySelector("img,svg,canvas,video")}function oy(e){const t=Array.from(e.querySelectorAll(".reveal .slides > section"));if(t.length>=2){const s=[];for(const o of t){const c=Array.from(o.children).filter(d=>d.tagName==="SECTION");c.length>0?s.push(...c):s.push(o)}return s}const n=new Map;for(const s of Array.from(e.body?.querySelectorAll("[class]")??[])){const o=s.getAttribute("class")??"";if(!/(?:^|[\s_-])(?:slide|page)(?:[\s_-]|$)/i.test(o)||!fE(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(fE);return r.length>=3?r:null}async function dae(e,t){const n=await c9(e,t),a=await uae(),r=oy(n);if(r)return{markdown:r.map((d,h)=>`<!-- tdag-page:${h+1} -->
527
527
 
528
528
  ${a.turndown(d.cloneNode(!0).outerHTML).trim()}`).join(`
529
529
 
530
- `).trim(),numPages:r.length,title:n.title||void 0};let s=n.title||void 0,o=null;try{const{default:c}=await Tt(async()=>{const{default:h}=await import("./index-BEqQ5wV9.js").then(m=>m.i);return{default:h}},[]),d=new c(n.cloneNode(!0)).parse();d?.content&&d.content.replace(/<[^>]+>/g," ").trim().length>40&&(o=d.content,d.title&&(s=d.title))}catch{}if(o==null&&n.body){const c=n.body.cloneNode(!0);c.querySelectorAll("script,style,noscript,nav,header,footer,aside").forEach(d=>d.remove()),o=c.innerHTML}return{markdown:o?a.turndown(o).trim():"",title:s}}const hae=[":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(`
530
+ `).trim(),numPages:r.length,title:n.title||void 0};let s=n.title||void 0,o=null;try{const{default:c}=await Tt(async()=>{const{default:h}=await import("./index-DaODh24h.js").then(m=>m.i);return{default:h}},[]),d=new c(n.cloneNode(!0)).parse();d?.content&&d.content.replace(/<[^>]+>/g," ").trim().length>40&&(o=d.content,d.title&&(s=d.title))}catch{}if(o==null&&n.body){const c=n.body.cloneNode(!0);c.querySelectorAll("script,style,noscript,nav,header,footer,aside").forEach(d=>d.remove()),o=c.innerHTML}return{markdown:o?a.turndown(o).trim():"",title:s}}const hae=[":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(`
531
531
  `);function yb(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;")}function fae(e,t){const n=e.tagName.toLowerCase(),a=["class","id","style"].map(r=>{const s=e.getAttribute(r);return s?` ${r}="${yb(s)}"`:""}).join("");return`<${n}${a} data-tdag-shell>${t}</${n}>`}function mE(e,t,n,a){const r=n?` class="${yb(n)}"`:"",s=a?` style="${yb(a)}"`:"";return`<!doctype html><html><head><meta charset="utf-8">${e}<style>${hae}</style></head><body${r}${s}>${t}</body></html>`}async function u9(e,t){const n=await c9(e,t),a=Array.from(n.querySelectorAll('style, link[rel="stylesheet" i]')).map(c=>c.outerHTML).join(`
532
532
  `),r=n.body?.getAttribute("class"),s=n.body?.getAttribute("style"),o=oy(n);return o?o.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=fae(p,m);return{page:d+1,srcdoc:mE(a,m,r,s)}}):[{page:null,srcdoc:mE(a,n.body?.innerHTML??"",r,s)}]}const d9=Object.freeze(Object.defineProperty({__proto__:null,buildReaderPages:u9,detectSlides:oy,extractHtmlMaterial:dae},Symbol.toStringTag,{value:"Module"}));function pE({att:e,onSelect:t,clipMode:n,onClipped:a,baseUrl:r}){const s=jt(),[o,c]=L.useState(null),[d,h]=L.useState(!1);return L.useEffect(()=>{let m=!1;return u9(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")}):o?u.jsx("div",{className:"flex flex-col items-center py-6 px-4",children:o.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(mae,{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(Un,{size:16,strokeWidth:1.75,className:"animate-spin text-accent"})," ",s("reader.loading")]})}function mae({srcdoc:e,page:t,onSelect:n,clipMode:a,onClipped:r,clipFailedText:s}){const o=L.useRef(null),c=L.useRef(null),[d,h]=L.useState(120),[m,p]=L.useState(null),[x,b]=L.useState(!1),y=()=>{const w=c.current,C=w?.contentDocument;if(!w||!C?.body)return;const T=C.body.scrollWidth||C.documentElement.scrollWidth,N=w.clientWidth;T>N+2&&(C.body.style.zoom=String(N/T)),h(Math.max(40,C.documentElement.scrollHeight+2)),C.addEventListener("mouseup",()=>{const D=w.contentWindow?.getSelection();if(!D||D.isCollapsed){n(null);return}const O=D.toString().replace(/\s+/g," ").trim();if(O.length<2)return;const M=D.getRangeAt(0).getBoundingClientRect(),_=w.getBoundingClientRect();n({text:O,page:t,x:_.left+M.left+M.width/2,y:_.top+M.bottom})})},k=w=>{const C=o.current.getBoundingClientRect();return{x:Math.min(1,Math.max(0,(w.clientX-C.left)/C.width)),y:Math.min(1,Math.max(0,(w.clientY-C.top)/C.height))}},S=()=>{if(!m||x){p(null);return}const w=Math.min(m.x0,m.x1),C=Math.min(m.y0,m.y1),T=Math.abs(m.x1-m.x0),N=Math.abs(m.y1-m.y0);if(p(null),T<.02||N<.01)return;const D=c.current?.contentDocument;!D?.documentElement||!r||(b(!0),(async()=>{const{toCanvas:O}=await Tt(async()=>{const{toCanvas:q}=await import("./index-BeoRn2gJ.js");return{toCanvas:q}},[]),M=await O(D.documentElement,{pixelRatio:2}),_=Math.floor(w*M.width),R=Math.floor(C*M.height),G=Math.max(1,Math.floor(T*M.width)),B=Math.max(1,Math.floor(N*M.height)),$=document.createElement("canvas");$.width=G,$.height=B,$.getContext("2d").drawImage(M,_,R,G,B,0,0,G,B);const Z=o.current.getBoundingClientRect(),U={left:Z.left+w*Z.width,top:Z.top+C*Z.height,width:T*Z.width,height:N*Z.height};r(t??1,[w,C,T,N],$.toDataURL("image/png"),U)})().catch(()=>Ye("error",s)).finally(()=>b(!1)))};return u.jsxs("div",{ref:o,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 C=k(w);p({x0:C.x,y0:C.y,x1:C.x,y1:C.y})},onMouseMove:w=>{if(m){const C=k(w);p({...m,x1:C.x,y1:C.y})}},onMouseUp:S,onMouseLeave:()=>{m&&S()},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(Un,{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 cx=null;function pae(){return cx||(cx=Promise.all([Tt(()=>import("./pdf-gh-BrLFn.js"),[]),Tt(()=>import("./pdf.worker.min-C_APr3k7.js"),[])]).then(([e,t])=>(e.GlobalWorkerOptions.workerSrc=t.default,e))),cx}function gae(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 xae=/<!--\s*tdag-page:(\d+)\s*-->/;function bae(e){const t=e.split(xae),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 ux=60,gE=new Map;function yae({onLocate:e}){const t=pe(a=>a.readerNodeId),n=oe(a=>t?a.nodes.find(r=>r.id===t):void 0);return L.useEffect(()=>{t&&!n&&pe.getState().setReaderNodeId(null)},[t,n]),n?u.jsx(vae,{node:n,onLocate:e},n.id):null}function vae({node:e,onLocate:t}){const n=jt(),a=e.data,r=a.stepKind==="file"||!a.stepKind&&(a.attachments??[]).some(xe=>xe.type==="application/pdf")?"file":a.stepKind==="link"?"link":"note",s=L.useMemo(()=>a.attachments??[],[a.attachments]),o=s.find(xe=>xe.type==="application/pdf"),c=s.find(xe=>xe.type==="text/html"),d=r==="link"?a.linkSnapshotHtml:void 0,h=L.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=L.useMemo(()=>s.filter(xe=>xe.type.startsWith("image/")),[s]),p=()=>pe.getState().setReaderNodeId(null),x=L.useMemo(()=>{if(o)return o.extractedText??"";if(r==="file"){const xe=s.filter(Nt=>!Nt.type.startsWith("image/")&&Nt.type!=="application/pdf"),Xe=xe.map(Nt=>{const Ct=Nt.type==="text/html"?Nt.extractedText??"":Nt.content;return xe.length>1?`### ${Nt.name}
533
533
 
@@ -544,7 +544,7 @@ ${Nt.extractedText}`:Nt.extractedText);return Xe.join(`
544
544
  `))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(`
545
545
  `)[0].slice(0,80)}catch{}return null}function Tae(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(`
546
546
  `).trim();if(a&&!a.startsWith("<"))return a.split(`
547
- `)[0].slice(0,80)}return null}const h9="thoughtdag.atlas.disabledRoots",ly=()=>{try{return new Set(JSON.parse(localStorage.getItem(h9)??"[]"))}catch{return new Set}};function Aae(e,t){const n=ly();t?n.add(e):n.delete(e),localStorage.setItem(h9,JSON.stringify([...n]))}const rm=new Set;async function Nae(){const e=window.desktopSessions;if(!e)return[];const t=ly(),n=(await e.roots().catch(()=>[])).filter(r=>r.exists&&!t.has(r.key)).map(r=>r.key),a=[];for(const r of n){const o=[...await e.list(r).catch(()=>[])].sort((d,h)=>h.mtime-d.mtime),c=12;for(let d=0;d<o.length;d+=c){const h=await Promise.all(o.slice(d,d+c).map(async m=>{const p=m.rel.endsWith(".zstd")?xE:Sae,x=await e.head(r,m.rel,p).catch(()=>"");if(!x)return null;const b=bE(r,m.rel,x,m.mtime,m.size);if(b)return b;const y=await e.head(r,m.rel,xE).catch(()=>"");return y.length>x.length?bE(r,m.rel,y,m.mtime,m.size):null}));for(const m of h)m&&a.push(m)}}rm.clear();for(const r of a)rm.add(r.sessionId);return a.sort((r,s)=>s.mtime-r.mtime)}function Cae(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 f9="thoughtdag.atlas.watermark",To=e=>`${e.rootKey}:${e.rel}`;function cy(){try{return JSON.parse(localStorage.getItem(f9)??"{}")}catch{return{}}}function im(e){localStorage.setItem(f9,JSON.stringify(e))}function _ae(e){const t=cy(),n=new Map;if(Object.keys(t).length===0)return im(Object.fromEntries(e.map(s=>[To(s),{mtime:s.mtime,size:s.size}]))),n;const a=new Set(e.map(To));let r=!1;for(const s of Object.keys(t))a.has(s)||(delete t[s],r=!0);for(const s of e){const o=t[To(s)];o?(s.size>o.size||s.mtime>o.mtime+1e3)&&n.set(To(s),{kind:"updated",deltaSize:Math.max(0,s.size-o.size)}):n.set(To(s),{kind:"new",deltaSize:s.size})}return r&&im(t),n}function Mae(e){const t=cy();t[To(e)]={mtime:e.mtime,size:e.size},im(t)}function Iae(e){const t=cy();for(const n of e)t[To(n)]={mtime:n.mtime,size:n.size};im(t)}const gc=To,hx=e=>new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),yE=e=>e>1e6?`${(e/1e6).toFixed(1)} MB`:`${Math.max(1,Math.round(e/1024))} KB`,Dae={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 Oae({roots:e,counts:t,onChanged:n,onClose:a}){const r=jt(),s=ly(),o={"claude-projects":"Claude Code","codex-sessions":"Codex","dsh-sessions":"DeepSeek Harness","pi-sessions":"Pi"},[c,d]=L.useState(null),h=()=>{window.desktopSessions?.commandsStatus?.().then(d).catch(()=>{})};L.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=>{Aae(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:o[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(Va,{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 Tt(async()=>{const{confirmDialog:w}=await Promise.resolve().then(()=>km);return{confirmDialog:w}},void 0);if(!await y({title:De("atlas.handoffEnableTitle"),message:He(De("confirm.installCommand"),{path:b.dest}),confirmLabel:De(b.state==="outdated"?"atlas.handoffUpdate":"atlas.handoffEnable")}))return;const S=await window.desktopSessions.commandsInstall(x);S.ok?Ye("success",He(De("atlas.handoffInstalled"),{cmd:b.invoke}),8e3):Ye("error",S.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(Va,{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(lr,{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(jS,{size:13,strokeWidth:1.75})," ",r("atlas.addDir")]})]})]})})}function m9({onClose:e,onSwitched:t,focusSessionId:n}){const a=jt(),r=rn(se=>se.projects),s=rn(se=>se.projects.find(Be=>Be.id===se.activeId)?.sourceSession?.sessionId),o=!!window.desktopSessions,[c,d]=L.useState(null),[h,m]=L.useState([]),[p,x]=L.useState(!1),[b,y]=L.useState(window.desktopSessions?null:"canvases"),[k,S]=L.useState(null),[w,C]=L.useState(!1),[T,N]=L.useState(null),[D,O]=L.useState(new Map),[M,_]=L.useState(new Map),[R,G]=L.useState(new Map),[B,$]=L.useState(!1),Z=se=>`${se.rootKey}|${se.rel}`,U=se=>G(Be=>{const ve=new Map(Be),We=Z(se);return ve.has(We)?ve.delete(We):ve.set(We,se),ve}),q=se=>r.find(Be=>Vx(Be).includes(se)),[H,V]=L.useState(""),[X,K]=L.useState(new Set),[F,W]=L.useState("time"),[ee,P]=L.useState(!1),[re,fe]=L.useState(!1),[ge,Te]=L.useState(new Map),[ne,ke]=L.useState(null);L.useEffect(()=>{window.desktopSessions?.openTargets().then(ke).catch(()=>{})},[]);const Ae=L.useMemo(()=>new Map((ne?.apps??[]).map(se=>[se.runner,se.name])),[ne]),Le=async()=>{x(!0);try{m(await window.desktopSessions?.roots().catch(()=>[])??[]);const se=await Nae();if(d(se),Te(_ae(se)),window.desktopSessions?.codexThreads?.().then(Be=>{Be&&(O(new Map(Be.filter(ve=>ve.name&&ve.sessionId).map(ve=>[ve.sessionId,ve.name]))),_(new Map(Be.filter(ve=>ve.forkedFromId&&ve.sessionId).map(ve=>[ve.sessionId,ve.forkedFromId]))))}).catch(()=>{}),n){const Be=se.find(ve=>ve.sessionId===n);Be&&y(Be.cwd??"")}}finally{x(!1)}};L.useEffect(()=>{Le()},[]),L.useEffect(()=>{let se=!1;const Be=()=>{se||p||(se=!0,setTimeout(()=>{se=!1,Le()},2e3))};return window.addEventListener("td:sessions-changed",Be),()=>window.removeEventListener("td:sessions-changed",Be)},[p]);const qe=L.useCallback(se=>D.get(se.sessionId)??se.title,[D]),je=L.useMemo(()=>(c??[]).filter(se=>!X.has(se.runner)&&(re||!se.subagent)&&(!ee||ge.has(gc(se)))&&(!H.trim()||qe(se).toLowerCase().includes(H.trim().toLowerCase()))),[c,X,H,ee,ge,re,qe]),et=L.useMemo(()=>Cae(je),[je]),dt=L.useMemo(()=>[...new Set((c??[]).map(se=>se.runner))].sort(),[c]),Ke=L.useMemo(()=>{const se=new Map;for(const Be of c??[])se.set(Be.rootKey,(se.get(Be.rootKey)??0)+1);return se},[c]),kt=b==="canvases"?null:et.find(se=>(se.cwd??"")===(b??et[0]?.cwd??""))??et[0]??null,bt=L.useMemo(()=>{if(!kt)return[];const se=F==="name"?(Be,ve)=>qe(Be).localeCompare(qe(ve)):Dae[F];return[...kt.cards].sort(se)},[kt,F,qe]),at=se=>{Mae(se),Te(Be=>{const ve=new Map(Be);return ve.delete(gc(se)),ve})},Et=async se=>{if(!k){S(se.rel),at(se);try{const{streamRunnerConversation:Be}=await Tt(async()=>{const{streamRunnerConversation:At}=await import("./index-Dyq9QwYZ.js");return{streamRunnerConversation:At}},[]),{importOrAppendConversation:ve,shellSessionReader:We}=await Tt(async()=>{const{importOrAppendConversation:At,shellSessionReader:qt}=await import("./canonical-Cw94rYnE.js");return{importOrAppendConversation:At,shellSessionReader:qt}},[]),ut=await Be(We(se.rootKey,se.rel)),gt=await ve(ut);if(!gt)throw new Error(De("handoff.notASession"));gt.kind==="appended"?Ye("success",He(De("atlas.appended"),{n:gt.turns}),9e3):gt.kind==="mounted"?Ye("success",He(De(gt.mode==="continue"?"atlas.mountedChapter":"atlas.mountedBranch"),{n:gt.turns}),9e3):gt.kind==="opened"?Ye("info",De("atlas.upToDate"),6e3):Ye("success",He(De("toast.importedChats"),{n:1,m:gt.nodeCount}),9e3),e(),t()}catch(Be){Ye("error",He(De("atlas.parseFailed"),{msg:Be instanceof Error?Be.message:String(Be)}))}finally{S(null)}}},Bt=async se=>{if(!(k||R.size<2)){S("__merge__");try{const{streamRunnerConversation:Be}=await Tt(async()=>{const{streamRunnerConversation:At}=await import("./index-Dyq9QwYZ.js");return{streamRunnerConversation:At}},[]),{mergeSessionsIntoProject:ve,shellSessionReader:We}=await Tt(async()=>{const{mergeSessionsIntoProject:At,shellSessionReader:qt}=await import("./canonical-Cw94rYnE.js");return{mergeSessionsIntoProject:At,shellSessionReader:qt}},[]),ut=[];for(const At of R.values())ut.push(await Be(We(At.rootKey,At.rel))),at(At);const gt=await ve(ut,se);if(!gt)throw new Error(De("handoff.notASession"));Ye("success",He(De("atlas.merged"),{n:gt.mounted}),1e4),gt.skipped>0&&Ye("info",He(De("atlas.mergeSkippedInfo"),{n:gt.skipped}),8e3),G(new Map),e(),t()}catch(Be){Ye("error",He(De("atlas.parseFailed"),{msg:Be instanceof Error?Be.message:String(Be)}))}finally{S(null)}}},Ve=async se=>{const Be=rn.getState().projects.find(ut=>ut.sourceSession?.sessionId===se.sessionId);if(!Be||k)return;const{confirmDialog:ve}=await Tt(async()=>{const{confirmDialog:ut}=await Promise.resolve().then(()=>km);return{confirmDialog:ut}},void 0);if(await ve({title:De("confirm.recastTitle"),message:He(De("confirm.recast"),{name:Be.name}),confirmLabel:De("confirm.recastTitle"),danger:!0})){S(se.rel);try{const{streamRunnerConversation:ut}=await Tt(async()=>{const{streamRunnerConversation:Kt}=await import("./index-Dyq9QwYZ.js");return{streamRunnerConversation:Kt}},[]),{importOrAppendConversation:gt,shellSessionReader:At}=await Tt(async()=>{const{importOrAppendConversation:Kt,shellSessionReader:kn}=await import("./canonical-Cw94rYnE.js");return{importOrAppendConversation:Kt,shellSessionReader:kn}},[]),qt=await ut(At(se.rootKey,se.rel));if(!qt)throw new Error(De("handoff.notASession"));const{deleteProject:hn}=await Tt(async()=>{const{deleteProject:Kt}=await Promise.resolve().then(()=>qr);return{deleteProject:Kt}},void 0);if(await hn(Be.id),!await gt(qt))throw new Error(De("handoff.notASession"));Ye("success",De("atlas.recastDone"),8e3),e(),t()}catch(ut){Ye("error",He(De("atlas.parseFailed"),{msg:ut instanceof Error?ut.message:String(ut)}))}finally{S(null)}}},Ht=async(se,Be)=>{const ve=await window.desktopSessions.openInCli(se.runner,se.cwd,se.sessionId,Be).catch(()=>({opened:!1,via:"",command:""}));ve.opened&&ve.via==="app"?(await navigator.clipboard.writeText(se.sessionId).catch(()=>{}),Ye("success",De("atlas.appOpened"),9e3)):ve.opened?Ye("success",De("atlas.opened")):ve.command&&(await navigator.clipboard.writeText(ve.command).catch(()=>{}),Ye("info",De("atlas.cmdCopied"),9e3))};return Za.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")}),ge.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:He(a("atlas.changesSummary"),{n:[...ge.values()].filter(se=>se.kind==="new").length,m:[...ge.values()].filter(se=>se.kind==="updated").length})}),u.jsx("button",{className:"text-ink-faint hover:text-ink underline decoration-dotted transition-colors",onClick:()=>{Iae(c??[]),Te(new Map)},"data-atlas-mark-all":!0,children:a("atlas.markAllSeen")})]})]}),o&&ne&&ne.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(Oo,{size:14,strokeWidth:1.75}),u.jsxs("select",{value:ne.prefs.terminal,onChange:se=>{const Be=se.target.value;if(Be==="__add__"){window.desktopSessions?.addTerminal().then(()=>window.desktopSessions?.openTargets().then(ke));return}window.desktopSessions?.setOpenPrefs({terminal:Be}).then(ve=>ke(We=>We&&{...We,prefs:ve}))},className:"bg-transparent focus:outline-none text-sm text-ink cursor-pointer","data-atlas-terminal-select":!0,children:[ne.terminals.map(se=>u.jsx("option",{value:se.id,children:se.name},se.id)),ne.canAddCustom&&u.jsx("option",{value:"__add__",children:a("atlas.otherTerminal")})]})]}),o&&u.jsxs("button",{onClick:()=>C(!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(jS,{size:14,strokeWidth:1.75})," ",a("atlas.sources")]}),o&&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(Un,{size:14,className:"animate-spin"}):u.jsx(lr,{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(mn,{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(se=>!se.archived).sort((se,Be)=>Be.updatedAt-se.updatedAt).slice(0,6).map(se=>u.jsxs("button",{onClick:()=>{e(),_s(se.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":se.id,children:[se.sourceSession?.sessionId?u.jsx("span",{className:"text-2xs font-mono border border-line rounded px-1 py-px shrink-0 text-ink-faint",children:se.sourceSession.runner}):u.jsx(h5,{size:13,strokeWidth:1.75,className:"shrink-0 text-ink-faint"}),u.jsx("span",{className:"flex-1 truncate text-sm",children:se.name})]},se.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")}),!o&&u.jsx("div",{className:"px-4 py-2 text-xs text-ink-faint",children:a("atlas.webNoScan")}),o&&c===null&&u.jsxs("div",{className:"px-4 py-2 text-sm text-ink-faint flex items-center gap-2",children:[u.jsx(Un,{size:14,className:"animate-spin"})," ",a("atlas.scanning")]}),o&&c!==null&&et.length===0&&u.jsx("div",{className:"px-4 py-2 text-xs text-ink-faint",children:a("atlas.empty")}),et.map(se=>{const Be=se.cwd??"",ve=b!=="canvases"&&kt===se;return u.jsxs("button",{onClick:()=>y(Be),className:`w-full text-left px-4 py-2 flex items-center gap-2 transition-colors ${ve?"bg-accent/5 text-accent":"text-ink hover:bg-wash"}`,"data-atlas-folder":se.name||"unfiled",children:[ve?u.jsx(Pc,{size:15,strokeWidth:1.75,className:"shrink-0"}):u.jsx(lz,{size:15,strokeWidth:1.75,className:"shrink-0 text-ink-faint"}),u.jsx("span",{className:"flex-1 truncate text-sm",children:se.name||a("atlas.unfiled")}),(()=>{const We=se.cards.filter(ut=>ge.has(gc(ut))).length;return We>0?u.jsxs("span",{className:"text-2xs text-accent shrink-0","data-atlas-folder-changes":!0,children:["+",We]}):null})(),u.jsx("span",{className:"text-2xs text-ink-faint shrink-0",children:se.cards.length})]},Be)}),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(h5,{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(se=>!se.archived).sort((se,Be)=>Be.updatedAt-se.updatedAt).map(se=>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(),_s(se.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:se.name}),u.jsxs("div",{className:"text-2xs text-ink-faint mt-0.5 flex items-center gap-1.5",children:[u.jsx("span",{children:hx(se.updatedAt)}),!!se.sourceSession?.sessionId&&u.jsx("span",{className:"font-mono border border-line rounded px-1 py-px",children:se.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:Be=>{Be.stopPropagation(),Ff(se.id,!0)},"data-atlas-archive":!0,children:u.jsx(zo,{size:15,strokeWidth:1.75})}),!!se.sourceSession&&Vx(se).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:[se.sourceSession.sessionId&&u.jsxs("span",{children:["◉ ",se.sourceSession.runner," ",se.sourceSession.sessionId.slice(0,8)," · ",He(a("atlas.turnsN"),{n:se.sourceSession.importedCount})]}),(se.sourceSession.chapters??[]).map(Be=>u.jsxs("span",{children:["↳ ",Be.runner," ",Be.sessionId.slice(0,8)," · ",He(a("atlas.turnsN"),{n:Be.importedCount})]},Be.sessionId)),(se.sourceSession.branches??[]).map(Be=>u.jsxs("span",{children:["⑂ ",Be.runner," ",Be.sessionId.slice(0,8)," · ",He(a("atlas.turnsN"),{n:Be.importedCount})]},Be.sessionId))]})]},se.id)),r.some(se=>se.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:He(a("atlas.archivedGroup"),{n:r.filter(se=>se.archived).length})}),u.jsx("div",{className:"space-y-1.5 mt-1.5",children:r.filter(se=>se.archived).sort((se,Be)=>Be.updatedAt-se.updatedAt).map(se=>u.jsxs("button",{title:a("atlas.restoreOpen"),onClick:()=>{Ff(se.id,!1).then(()=>{e(),_s(se.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:se.name}),!!se.sourceSession?.sessionId&&u.jsx("span",{className:"text-2xs font-mono border border-line rounded px-1 py-px shrink-0 text-ink-faint",children:se.sourceSession.runner})]}),u.jsx("div",{className:"text-2xs text-ink-faint mt-0.5",children:hx(se.updatedAt)})]},se.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(Pf,{size:13,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),u.jsx("input",{value:H,onChange:se=>V(se.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})]}),dt.map(se=>u.jsx("button",{onClick:()=>K(Be=>{const ve=new Set(Be);return ve.has(se)?ve.delete(se):ve.add(se),ve}),className:`text-2xs font-mono border rounded-lg px-2 py-1 transition-colors ${X.has(se)?"border-line text-ink-faint line-through":"border-accent/40 text-accent bg-accent/5"}`,"data-atlas-runner-toggle":se,children:se},se)),ge.size>0&&u.jsx("button",{onClick:()=>P(se=>!se),className:`text-2xs border rounded-lg px-2 py-1 transition-colors ${ee?"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(se=>se.subagent)&&u.jsx("button",{onClick:()=>fe(se=>!se),className:`text-2xs border rounded-lg px-2 py-1 transition-colors ${re?"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:()=>W(se=>({time:"name",name:"size",size:"runner",runner:"time"})[se]),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(sP,{size:12,strokeWidth:1.75}),a(`atlas.sort${F[0].toUpperCase()}${F.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," · ",He(a("atlas.sessions"),{n:kt.cards.length})]}),u.jsx("div",{className:"space-y-1.5",children:bt.map(se=>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(se))?"border-accent/60 bg-accent/5":"border-line"}`,onClick:()=>{Et(se)},"data-atlas-session":se.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:qe(se)}),M.has(se.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(se.sessionId)}`,"data-atlas-fork":!0,children:"⑂"}),ge.get(gc(se))?.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")}),ge.get(gc(se))?.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:["+",yE(ge.get(gc(se)).deltaSize)]}),se.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 Be=q(se.sessionId);return Be?u.jsx("span",{className:"text-2xs text-ink-faint border border-line rounded px-1 py-px shrink-0",title:Be.name,"data-atlas-badge":"canvas",children: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:se.runner}),u.jsx("span",{children:hx(se.mtime)}),u.jsx("span",{children:yE(se.size)})]})]}),k===se.rel?u.jsx(Un,{size:16,className:"animate-spin text-accent shrink-0"}):u.jsxs("div",{className:`${R.has(Z(se))?"":"opacity-0 group-hover:opacity-100"} transition-opacity flex items-center gap-1 shrink-0`,children:[!q(se.sessionId)&&!!se.sessionId&&u.jsx("button",{title:a("atlas.pickForMerge"),className:`p-1.5 rounded transition-colors ${R.has(Z(se))?"text-accent":"text-ink-faint hover:text-accent"}`,onClick:Be=>{Be.stopPropagation(),U(se)},"data-atlas-pick":R.has(Z(se))?"on":"off",children:R.has(Z(se))?u.jsx(bB,{size:16,strokeWidth:1.75}):u.jsx(Gb,{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(wz,{size:16,strokeWidth:1.75})}),r.some(Be=>Be.sourceSession?.sessionId===se.sessionId)&&u.jsx("button",{title:a("atlas.recast"),className:"text-ink-faint hover:text-red-500 p-1.5 rounded transition-colors",onClick:Be=>{Be.stopPropagation(),Ve(se)},"data-atlas-recast":!0,children:u.jsx(eB,{size:16,strokeWidth:1.75})}),!q(se.sessionId)&&u.jsx("button",{title:a("atlas.mountTo"),className:"text-ink-faint hover:text-accent p-1.5 rounded transition-colors",onClick:Be=>{Be.stopPropagation(),N(se)},"data-atlas-mount":!0,children:u.jsx(Do,{size:16,strokeWidth:1.75})}),Ae.has(se.runner)&&u.jsx("button",{title:He(a("atlas.openApp"),{name:Ae.get(se.runner)}),className:"text-ink-faint hover:text-accent p-1.5 rounded transition-colors",onClick:Be=>{Be.stopPropagation(),Ht(se,"app")},"data-atlas-open-app":!0,children:u.jsx(nP,{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:Be=>{Be.stopPropagation(),Ht(se,"terminal")},"data-atlas-open-cli":!0,children:u.jsx(Oo,{size:16,strokeWidth:1.75})})]})]},se.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&&!B&&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:He(a("atlas.mergeSelected"),{n:R.size})}),k==="__merge__"?u.jsx(Un,{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:()=>{Bt()},"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:()=>$(!0),"data-atlas-merge-into":!0,children:a("atlas.mergeInto")})]}),u.jsx("button",{className:"text-ink-faint hover:text-ink p-1",onClick:()=>G(new Map),title:a("common.cancel"),children:u.jsx(mn,{size:14,strokeWidth:1.75})})]}),(T||B)&&u.jsx("div",{className:"absolute inset-0 z-10 bg-ink/20 flex items-center justify-center",onClick:()=>{N(null),$(!1)},children:u.jsxs("div",{className:"bg-surface border border-line rounded-2xl shadow-xl w-[400px] max-h-[70%] overflow-y-auto",onClick:se=>se.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(B?"atlas.mergeInto":"atlas.mountTo")}),u.jsx("div",{className:"text-2xs text-ink-muted mt-0.5",children:a(B?"atlas.mergeSelected":"atlas.mountHint").replace("{n}",String(R.size))})]}),r.filter(se=>!se.archived&&se.kind!=="paradigm").sort((se,Be)=>Be.updatedAt-se.updatedAt).map(se=>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(B){$(!1),Bt(se.id);return}const Be=T;N(null),(async()=>{S(Be.rel);try{const{streamRunnerConversation:ve}=await Tt(async()=>{const{streamRunnerConversation:qt}=await import("./index-Dyq9QwYZ.js");return{streamRunnerConversation:qt}},[]),{mountConversationToProject:We,shellSessionReader:ut}=await Tt(async()=>{const{mountConversationToProject:qt,shellSessionReader:hn}=await import("./canonical-Cw94rYnE.js");return{mountConversationToProject:qt,shellSessionReader:hn}},[]),gt=await ve(ut(Be.rootKey,Be.rel)),At=await We(gt,se.id);if(!At)throw new Error(De("handoff.notASession"));Ye("success",He(De("atlas.mountedChapter"),{n:At.kind==="mounted"||At.kind==="appended"?At.turns:0}),9e3),e(),t()}catch(ve){Ye("error",He(De("atlas.parseFailed"),{msg:ve instanceof Error?ve.message:String(ve)}))}finally{S(null)}})()},children:se.name},se.id))]})}),w&&u.jsx(Oae,{roots:h,counts:Ke,onChanged:()=>{Le()},onClose:()=>C(!1)})]})}),document.body)}function Rae({conversations:e,onClose:t,onDone:n}){const a=jt(),[r,s]=L.useState(new Set),[o,c]=L.useState(!1),d=p=>{s(x=>{const b=new Set(x);return b.has(p)?b.delete(p):b.add(p),b})},h=r.size===e.length,m=async()=>{r.size===0||o||(c(!0),await cF([...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(mn,{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(LS,{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:He(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||o,className:"text-xs bg-accent hover:bg-accent-strong text-white px-5 py-2 rounded-lg transition-colors disabled:opacity-30",children:o?"…":He(a("import.confirm"),{n:r.size})})]})]})})}function Lae(e){const t=Date.now()-e,n=Math.floor(t/6e4);if(n<1)return De("switcher.justNow");if(n<60)return He(De("switcher.minAgo"),{n});const a=Math.floor(n/60);if(a<24)return He(De("switcher.hourAgo"),{n:a});const r=Math.floor(a/24);return r<30?He(De("switcher.dayAgo"),{n:r}):new Date(e).toLocaleDateString(Ra.getState().lang==="zh"?"zh-CN":"en-US")}function jae({onSwitched:e}){const t=jt(),n=rn(_=>_.projects),a=rn(_=>_.activeId),r=rn(_=>_.switching),s=n.find(_=>_.id===a)?.kind==="paradigm",[o,c]=L.useState(!1),[d,h]=L.useState(null),[m,p]=L.useState(!1),[x,b]=L.useState(void 0),[y,k]=L.useState(null),[S,w]=L.useState(""),C=L.useRef(null),T=L.useRef(null),N=n.find(_=>_.id===a),D=n.filter(_=>!_.archived).sort((_,R)=>R.updatedAt-_.updatedAt).slice(0,7),O=async _=>{const{canvasUniqueness:R}=await Tt(async()=>{const{canvasUniqueness:Z}=await import("./canonical-Cw94rYnE.js");return{canvasUniqueness:Z}},[]),G=await R(_.id),B=G==="native"?"confirm.deleteNative":G==="diverged-mirror"?"confirm.deleteDiverged":"confirm.deletePristine";await Cs({title:De("confirm.deleteCanvasTitle"),message:He(De(B),{name:_.name}),confirmLabel:De("common.delete"),danger:G!=="pristine-mirror"})&&A7(_.id).then(e)};L.useEffect(()=>{if(!o)return;const _=R=>{T.current?.contains(R.target)||c(!1)};return window.addEventListener("mousedown",_),()=>window.removeEventListener("mousedown",_)},[o]);const M=async _=>{c(!1),await _s(_),e(),Tt(()=>import("./canonical-Cw94rYnE.js"),[]).then(R=>R.unsubscribeOrphanedSessions()),Tt(()=>import("./live-mirror-BlUlIINC.js"),[]).then(R=>R.sweepRecentSessions())};return u.jsxs("div",{ref:T,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(!o),disabled:r,className:"bg-card/90 backdrop-blur border border-line rounded-xl px-3.5 py-2 shadow-sm hover:bg-wash transition-colors flex items-center gap-2 text-sm text-ink max-w-[240px] disabled:opacity-60",children:[r?u.jsx(Un,{size:16,strokeWidth:1.75,className:"animate-spin shrink-0 text-accent"}):s?u.jsx(WP,{size:16,strokeWidth:1.75,className:"shrink-0 text-accent"}):u.jsx(Pc,{size:16,strokeWidth:1.75,className:"shrink-0 text-ink-muted"}),u.jsx("span",{className:"truncate font-medium",children:N?.name??"…"}),u.jsx(Cl,{size:14,strokeWidth:1.75,className:"shrink-0 text-ink-faint"})]}),!!N?.sourceSession?.sessionId&&(()=>{const _=rm.size>0&&!rm.has(N.sourceSession.sessionId);return u.jsxs("button",{title:_?De("switcher.mirrorBadgeGone"):He(De("switcher.mirrorBadge"),{runner:N.sourceSession.runner}),onClick:()=>{b(N.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 ${_?"text-ink-faint/50 line-through decoration-1":"text-ink-faint hover:text-accent"}`,"data-twin-badge":_?"unreachable":"live",children:["⇄ ",N.sourceSession.runner]})})()]}),o&&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:D.map(_=>u.jsx("div",{className:`group flex items-center gap-1 px-3 py-2 hover:bg-wash cursor-pointer transition-colors ${_.id===a?"bg-accent/5":""}`,onClick:()=>{y!==_.id&&_.id!==a&&M(_.id)},children:y===_.id?u.jsx("input",{autoFocus:!0,value:S,onChange:R=>w(R.target.value),onClick:R=>R.stopPropagation(),onKeyDown:R=>{R.key==="Enter"&&!Qa(R)&&S.trim()&&(T7(_.id,S.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 ${_.id===a?"text-accent font-medium":"text-ink"}`,children:_.name}),u.jsxs("div",{className:"text-2xs text-ink-faint flex items-center gap-1.5",children:[u.jsx("span",{children:Lae(_.updatedAt)}),!!_.sourceSession?.sessionId&&u.jsx("span",{className:"font-mono border border-line rounded px-1 py-px","data-mirror-mark":!0,children:_.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(_.id),w(_.name)},children:u.jsx(Fc,{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(),O(_)},children:u.jsx(Va,{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(),Ff(_.id,!0).then(e)},"data-archive-canvas":!0,children:u.jsx(zo,{size:14,strokeWidth:1.75})})]})},_.id))}),u.jsxs("div",{className:"border-t border-line mt-1 pt-1",children:[u.jsxs("button",{onClick:()=>{c(!1),Am().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(vm,{size:15,strokeWidth:1.75})," ",t("switcher.newCanvas")]}),u.jsxs("button",{onClick:()=>C.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(MB,{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(Oz,{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(lr,{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:C,type:"file",accept:".json,.jsonl,application/json",className:"hidden",onChange:_=>{const R=_.target.files?.[0];R&&oF(R).then(G=>{G.kind==="own"&&G.ok?(c(!1),e()):G.kind==="chat"&&(c(!1),h(G.conversations))}).catch(G=>{Ye("error",He(De("toast.importFailedGeneric"),{msg:G instanceof Error?G.message:String(G)}))}),_.target.value=""}})]})]}),d&&u.jsx(Rae,{conversations:d,onClose:()=>h(null),onDone:()=>{h(null),e()}}),m&&u.jsx(m9,{onClose:()=>{p(!1),b(void 0)},onSwitched:e,focusSessionId:x})]})}const Pae="JVBERi0xLjQKMSAwIG9iago8PCAvVHlwZSAvQ2F0YWxvZyAvUGFnZXMgMiAwIFIgPj4KZW5kb2JqCjIgMCBvYmoKPDwgL1R5cGUgL1BhZ2VzIC9LaWRzIFszIDAgUiA0IDAgUl0gL0NvdW50IDIgPj4KZW5kb2JqCjMgMCBvYmoKPDwgL1R5cGUgL1BhZ2UgL1BhcmVudCAyIDAgUiAvTWVkaWFCb3ggWzAgMCA1OTUgODQyXSAvQ29udGVudHMgNSAwIFIgL1Jlc291cmNlcyA8PCAvRm9udCA8PCAvRjEgNyAwIFIgL0YyIDggMCBSID4+ID4+ID4+CmVuZG9iago0IDAgb2JqCjw8IC9UeXBlIC9QYWdlIC9QYXJlbnQgMiAwIFIgL01lZGlhQm94IFswIDAgNTk1IDg0Ml0gL0NvbnRlbnRzIDYgMCBSIC9SZXNvdXJjZXMgPDwgL0ZvbnQgPDwgL0YxIDcgMCBSIC9GMiA4IDAgUiA+PiA+PiA+PgplbmRvYmoKNSAwIG9iago8PCAvTGVuZ3RoIDExMTIgPj4Kc3RyZWFtCkJUCi9GMiAxOSBUZiAxIDAgMCAxIDY0IDcyNS4wIFRtIChXaHkgU2F2ZWQgQXJ0aWNsZXMgU3RheSBVbnJlYWQpIFRqCi9GMSAxMSBUZiAxIDAgMCAxIDY0IDcwOC4wIFRtIChBIHNob3J0IGJyaWVmIG9uIGRpZ2l0YWwgaG9hcmRpbmcgYW5kIHRoZSBjb2xsZWN0b3IncyBmYWxsYWN5KSBUagovRjIgMTMgVGYgMSAwIDAgMSA2NCA2NjkuMCBUbSAoMS4gVGhlIHBoZW5vbWVub24pIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNjUxLjUgVG0gKFJlYWQtaXQtbGF0ZXIgc2VydmljZXMgcmVwb3J0IHRoYXQgbW9zdCBzYXZlZCBpdGVtcyBhcmUgbmV2ZXIpIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNjM0LjAgVG0gKHJlb3BlbmVkLiBBY3Jvc3MgcHVibGlzaGVkIHVzYWdlIHN0dWRpZXMsIHRoZSBzaGFyZSBvZiBzYXZlZCkgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA2MTYuNSBUbSAoYXJ0aWNsZXMgdGhhdCBnZXQgYSBzZWNvbmQgdmlzaXQgaXMgc21hbGwsIGFuZCBjb21wbGV0aW9uIHJhdGVzKSBUagovRjEgMTEuNSBUZiAxIDAgMCAxIDY0IDU5OS4wIFRtIChhcmUgc21hbGxlciBzdGlsbC4gVGhlIGFyY2hpdmUgZ3Jvd3M7IHRoZSByZWFkaW5nIGRvZXMgbm90LikgVGoKL0YyIDEzIFRmIDEgMCAwIDEgNjQgNTYwLjAgVG0gKDIuIFRoZSBjb2xsZWN0b3IncyBmYWxsYWN5KSBUagovRjEgMTEuNSBUZiAxIDAgMCAxIDY0IDU0Mi41IFRtIChDb2xsZWN0aW5nIHByb2R1Y2VzIGFuIGltbWVkaWF0ZSBzZW5zZSBvZiBwcm9ncmVzcyB3aGlsZSB0aGUpIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNTI1LjAgVG0gKHVuZGVyc3RhbmRpbmcgaXQgcHJvbWlzZXMgaXMgZGVmZXJyZWQuIFNhdmluZyBhIHRleHQgZmVlbHMgbGlrZSkgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA1MDcuNSBUbSAoYSBmaXJzdCBzdGVwIG9mIHJlYWRpbmcgaXQsIGJ1dCBubyBwYXJ0IG9mIHRoZSByZWFkaW5nIGhhcykgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA0OTAuMCBUbSAoaGFwcGVuZWQuKSBUagovRjIgMTEuNSBUZiAxIDAgMCAxIDY0IDQ3Mi41IFRtIChUaGUgYWN0IG9mIHNhdmluZyBpcyBtaXN0YWtlbiBmb3IgdGhlIGFjdCBvZiBsZWFybmluZy4pIFRqCkVUCmVuZHN0cmVhbQplbmRvYmoKNiAwIG9iago8PCAvTGVuZ3RoIDkwOCA+PgpzdHJlYW0KQlQKL0YyIDEzIFRmIDEgMCAwIDEgNjQgNzI1LjAgVG0gKDMuIFdoeSBpdCBwZXJzaXN0cykgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA3MDcuNSBUbSAoVGhlIGNvc3RzIGFyZSBhc3ltbWV0cmljOiBzYXZpbmcgdGFrZXMgb25lIHNlY29uZCBhbmQgcGF5cyBvdXQpIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNjkwLjAgVG0gKGEgc21hbGwgcmV3YXJkIG5vdzsgcmVhZGluZyB0YWtlcyBhbiBob3VyIGFuZCBwYXlzIG91dCBsYXRlci4pIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNjcyLjUgVG0gKEhhYml0cyBmb2xsb3cgdGhlIGNoZWFwZXIgbG9vcCwgc28gbGlicmFyaWVzIGluZmxhdGUgYnkgZGVmYXVsdC4pIFRqCi9GMiAxMyBUZiAxIDAgMCAxIDY0IDYzMy41IFRtICg0LiBXaGF0IGhlbHBzKSBUagovRjEgMTEuNSBUZiAxIDAgMCAxIDY0IDYxNi4wIFRtIChJbnRlcnZlbnRpb25zIHRoYXQgd29yayBtb3ZlIHByb2Nlc3NpbmcgdG8gdGhlIG1vbWVudCBvZiBjYXB0dXJlOikgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA1OTguNSBUbSAod3JpdGUgb25lIGxpbmUgaW4geW91ciBvd24gd29yZHMgYWJvdXQgd2h5IHRoZSBpdGVtIG1hdHRlcnMsIGFuZCkgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA1ODEuMCBUbSAoc2NoZWR1bGUgYSByZXZpZXcgcGFzcyBpbnN0ZWFkIG9mIHRydXN0aW5nIHRoZSBhcmNoaXZlIHRvKSBUagovRjEgMTEuNSBUZiAxIDAgMCAxIDY0IDU2My41IFRtIChyZXN1cmZhY2UgaXQuKSBUagovRjEgMTEuNSBUZiAxIDAgMCAxIDY0IDUzMi4wIFRtIChBIHNtYWxsZXIgbGlicmFyeSB0aGF0IGdldHMgcHJvY2Vzc2VkIGJlYXRzIGEgY29tcGxldGUgb25lIHRoYXQpIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNTE0LjUgVG0gKGRvZXMgbm90LikgVGoKRVQKZW5kc3RyZWFtCmVuZG9iago3IDAgb2JqCjw8IC9UeXBlIC9Gb250IC9TdWJ0eXBlIC9UeXBlMSAvQmFzZUZvbnQgL0hlbHZldGljYSA+PgplbmRvYmoKOCAwIG9iago8PCAvVHlwZSAvRm9udCAvU3VidHlwZSAvVHlwZTEgL0Jhc2VGb250IC9IZWx2ZXRpY2EtQm9sZCA+PgplbmRvYmoKeHJlZgowIDkKMDAwMDAwMDAwMCA2NTUzNSBmIAowMDAwMDAwMDA5IDAwMDAwIG4gCjAwMDAwMDAwNTggMDAwMDAgbiAKMDAwMDAwMDEyMSAwMDAwMCBuIAowMDAwMDAwMjU3IDAwMDAwIG4gCjAwMDAwMDAzOTMgMDAwMDAgbiAKMDAwMDAwMTU1NyAwMDAwMCBuIAowMDAwMDAyNTE2IDAwMDAwIG4gCjAwMDAwMDI1ODYgMDAwMDAgbiAKdHJhaWxlcgo8PCAvU2l6ZSA5IC9Sb290IDEgMCBSID4+CnN0YXJ0eHJlZgoyNjYxCiUlRU9G",zae=`<!-- tdag-page:1 -->
547
+ `)[0].slice(0,80)}return null}const h9="thoughtdag.atlas.disabledRoots",ly=()=>{try{return new Set(JSON.parse(localStorage.getItem(h9)??"[]"))}catch{return new Set}};function Aae(e,t){const n=ly();t?n.add(e):n.delete(e),localStorage.setItem(h9,JSON.stringify([...n]))}const rm=new Set;async function Nae(){const e=window.desktopSessions;if(!e)return[];const t=ly(),n=(await e.roots().catch(()=>[])).filter(r=>r.exists&&!t.has(r.key)).map(r=>r.key),a=[];for(const r of n){const o=[...await e.list(r).catch(()=>[])].sort((d,h)=>h.mtime-d.mtime),c=12;for(let d=0;d<o.length;d+=c){const h=await Promise.all(o.slice(d,d+c).map(async m=>{const p=m.rel.endsWith(".zstd")?xE:Sae,x=await e.head(r,m.rel,p).catch(()=>"");if(!x)return null;const b=bE(r,m.rel,x,m.mtime,m.size);if(b)return b;const y=await e.head(r,m.rel,xE).catch(()=>"");return y.length>x.length?bE(r,m.rel,y,m.mtime,m.size):null}));for(const m of h)m&&a.push(m)}}rm.clear();for(const r of a)rm.add(r.sessionId);return a.sort((r,s)=>s.mtime-r.mtime)}function Cae(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 f9="thoughtdag.atlas.watermark",To=e=>`${e.rootKey}:${e.rel}`;function cy(){try{return JSON.parse(localStorage.getItem(f9)??"{}")}catch{return{}}}function im(e){localStorage.setItem(f9,JSON.stringify(e))}function _ae(e){const t=cy(),n=new Map;if(Object.keys(t).length===0)return im(Object.fromEntries(e.map(s=>[To(s),{mtime:s.mtime,size:s.size}]))),n;const a=new Set(e.map(To));let r=!1;for(const s of Object.keys(t))a.has(s)||(delete t[s],r=!0);for(const s of e){const o=t[To(s)];o?(s.size>o.size||s.mtime>o.mtime+1e3)&&n.set(To(s),{kind:"updated",deltaSize:Math.max(0,s.size-o.size)}):n.set(To(s),{kind:"new",deltaSize:s.size})}return r&&im(t),n}function Mae(e){const t=cy();t[To(e)]={mtime:e.mtime,size:e.size},im(t)}function Iae(e){const t=cy();for(const n of e)t[To(n)]={mtime:n.mtime,size:n.size};im(t)}const gc=To,hx=e=>new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),yE=e=>e>1e6?`${(e/1e6).toFixed(1)} MB`:`${Math.max(1,Math.round(e/1024))} KB`,Dae={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 Oae({roots:e,counts:t,onChanged:n,onClose:a}){const r=jt(),s=ly(),o={"claude-projects":"Claude Code","codex-sessions":"Codex","dsh-sessions":"DeepSeek Harness","pi-sessions":"Pi"},[c,d]=L.useState(null),h=()=>{window.desktopSessions?.commandsStatus?.().then(d).catch(()=>{})};L.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=>{Aae(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:o[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(Va,{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 Tt(async()=>{const{confirmDialog:w}=await Promise.resolve().then(()=>km);return{confirmDialog:w}},void 0);if(!await y({title:De("atlas.handoffEnableTitle"),message:He(De("confirm.installCommand"),{path:b.dest}),confirmLabel:De(b.state==="outdated"?"atlas.handoffUpdate":"atlas.handoffEnable")}))return;const S=await window.desktopSessions.commandsInstall(x);S.ok?Ye("success",He(De("atlas.handoffInstalled"),{cmd:b.invoke}),8e3):Ye("error",S.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(Va,{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(lr,{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(jS,{size:13,strokeWidth:1.75})," ",r("atlas.addDir")]})]})]})})}function m9({onClose:e,onSwitched:t,focusSessionId:n}){const a=jt(),r=rn(se=>se.projects),s=rn(se=>se.projects.find(Be=>Be.id===se.activeId)?.sourceSession?.sessionId),o=!!window.desktopSessions,[c,d]=L.useState(null),[h,m]=L.useState([]),[p,x]=L.useState(!1),[b,y]=L.useState(window.desktopSessions?null:"canvases"),[k,S]=L.useState(null),[w,C]=L.useState(!1),[T,N]=L.useState(null),[D,O]=L.useState(new Map),[M,_]=L.useState(new Map),[R,G]=L.useState(new Map),[B,$]=L.useState(!1),Z=se=>`${se.rootKey}|${se.rel}`,U=se=>G(Be=>{const ve=new Map(Be),We=Z(se);return ve.has(We)?ve.delete(We):ve.set(We,se),ve}),q=se=>r.find(Be=>Vx(Be).includes(se)),[H,V]=L.useState(""),[X,K]=L.useState(new Set),[F,W]=L.useState("time"),[ee,P]=L.useState(!1),[re,fe]=L.useState(!1),[ge,Te]=L.useState(new Map),[ne,ke]=L.useState(null);L.useEffect(()=>{window.desktopSessions?.openTargets().then(ke).catch(()=>{})},[]);const Ae=L.useMemo(()=>new Map((ne?.apps??[]).map(se=>[se.runner,se.name])),[ne]),Le=async()=>{x(!0);try{m(await window.desktopSessions?.roots().catch(()=>[])??[]);const se=await Nae();if(d(se),Te(_ae(se)),window.desktopSessions?.codexThreads?.().then(Be=>{Be&&(O(new Map(Be.filter(ve=>ve.name&&ve.sessionId).map(ve=>[ve.sessionId,ve.name]))),_(new Map(Be.filter(ve=>ve.forkedFromId&&ve.sessionId).map(ve=>[ve.sessionId,ve.forkedFromId]))))}).catch(()=>{}),n){const Be=se.find(ve=>ve.sessionId===n);Be&&y(Be.cwd??"")}}finally{x(!1)}};L.useEffect(()=>{Le()},[]),L.useEffect(()=>{let se=!1;const Be=()=>{se||p||(se=!0,setTimeout(()=>{se=!1,Le()},2e3))};return window.addEventListener("td:sessions-changed",Be),()=>window.removeEventListener("td:sessions-changed",Be)},[p]);const qe=L.useCallback(se=>D.get(se.sessionId)??se.title,[D]),je=L.useMemo(()=>(c??[]).filter(se=>!X.has(se.runner)&&(re||!se.subagent)&&(!ee||ge.has(gc(se)))&&(!H.trim()||qe(se).toLowerCase().includes(H.trim().toLowerCase()))),[c,X,H,ee,ge,re,qe]),et=L.useMemo(()=>Cae(je),[je]),dt=L.useMemo(()=>[...new Set((c??[]).map(se=>se.runner))].sort(),[c]),Ke=L.useMemo(()=>{const se=new Map;for(const Be of c??[])se.set(Be.rootKey,(se.get(Be.rootKey)??0)+1);return se},[c]),kt=b==="canvases"?null:et.find(se=>(se.cwd??"")===(b??et[0]?.cwd??""))??et[0]??null,bt=L.useMemo(()=>{if(!kt)return[];const se=F==="name"?(Be,ve)=>qe(Be).localeCompare(qe(ve)):Dae[F];return[...kt.cards].sort(se)},[kt,F,qe]),at=se=>{Mae(se),Te(Be=>{const ve=new Map(Be);return ve.delete(gc(se)),ve})},Et=async se=>{if(!k){S(se.rel),at(se);try{const{streamRunnerConversation:Be}=await Tt(async()=>{const{streamRunnerConversation:At}=await import("./index-CTQSx_k0.js");return{streamRunnerConversation:At}},[]),{importOrAppendConversation:ve,shellSessionReader:We}=await Tt(async()=>{const{importOrAppendConversation:At,shellSessionReader:qt}=await import("./canonical-DccXDqkX.js");return{importOrAppendConversation:At,shellSessionReader:qt}},[]),ut=await Be(We(se.rootKey,se.rel)),gt=await ve(ut);if(!gt)throw new Error(De("handoff.notASession"));gt.kind==="appended"?Ye("success",He(De("atlas.appended"),{n:gt.turns}),9e3):gt.kind==="mounted"?Ye("success",He(De(gt.mode==="continue"?"atlas.mountedChapter":"atlas.mountedBranch"),{n:gt.turns}),9e3):gt.kind==="opened"?Ye("info",De("atlas.upToDate"),6e3):Ye("success",He(De("toast.importedChats"),{n:1,m:gt.nodeCount}),9e3),e(),t()}catch(Be){Ye("error",He(De("atlas.parseFailed"),{msg:Be instanceof Error?Be.message:String(Be)}))}finally{S(null)}}},Bt=async se=>{if(!(k||R.size<2)){S("__merge__");try{const{streamRunnerConversation:Be}=await Tt(async()=>{const{streamRunnerConversation:At}=await import("./index-CTQSx_k0.js");return{streamRunnerConversation:At}},[]),{mergeSessionsIntoProject:ve,shellSessionReader:We}=await Tt(async()=>{const{mergeSessionsIntoProject:At,shellSessionReader:qt}=await import("./canonical-DccXDqkX.js");return{mergeSessionsIntoProject:At,shellSessionReader:qt}},[]),ut=[];for(const At of R.values())ut.push(await Be(We(At.rootKey,At.rel))),at(At);const gt=await ve(ut,se);if(!gt)throw new Error(De("handoff.notASession"));Ye("success",He(De("atlas.merged"),{n:gt.mounted}),1e4),gt.skipped>0&&Ye("info",He(De("atlas.mergeSkippedInfo"),{n:gt.skipped}),8e3),G(new Map),e(),t()}catch(Be){Ye("error",He(De("atlas.parseFailed"),{msg:Be instanceof Error?Be.message:String(Be)}))}finally{S(null)}}},Ve=async se=>{const Be=rn.getState().projects.find(ut=>ut.sourceSession?.sessionId===se.sessionId);if(!Be||k)return;const{confirmDialog:ve}=await Tt(async()=>{const{confirmDialog:ut}=await Promise.resolve().then(()=>km);return{confirmDialog:ut}},void 0);if(await ve({title:De("confirm.recastTitle"),message:He(De("confirm.recast"),{name:Be.name}),confirmLabel:De("confirm.recastTitle"),danger:!0})){S(se.rel);try{const{streamRunnerConversation:ut}=await Tt(async()=>{const{streamRunnerConversation:Kt}=await import("./index-CTQSx_k0.js");return{streamRunnerConversation:Kt}},[]),{importOrAppendConversation:gt,shellSessionReader:At}=await Tt(async()=>{const{importOrAppendConversation:Kt,shellSessionReader:kn}=await import("./canonical-DccXDqkX.js");return{importOrAppendConversation:Kt,shellSessionReader:kn}},[]),qt=await ut(At(se.rootKey,se.rel));if(!qt)throw new Error(De("handoff.notASession"));const{deleteProject:hn}=await Tt(async()=>{const{deleteProject:Kt}=await Promise.resolve().then(()=>qr);return{deleteProject:Kt}},void 0);if(await hn(Be.id),!await gt(qt))throw new Error(De("handoff.notASession"));Ye("success",De("atlas.recastDone"),8e3),e(),t()}catch(ut){Ye("error",He(De("atlas.parseFailed"),{msg:ut instanceof Error?ut.message:String(ut)}))}finally{S(null)}}},Ht=async(se,Be)=>{const ve=await window.desktopSessions.openInCli(se.runner,se.cwd,se.sessionId,Be).catch(()=>({opened:!1,via:"",command:""}));ve.opened&&ve.via==="app"?(await navigator.clipboard.writeText(se.sessionId).catch(()=>{}),Ye("success",De("atlas.appOpened"),9e3)):ve.opened?Ye("success",De("atlas.opened")):ve.command&&(await navigator.clipboard.writeText(ve.command).catch(()=>{}),Ye("info",De("atlas.cmdCopied"),9e3))};return Za.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")}),ge.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:He(a("atlas.changesSummary"),{n:[...ge.values()].filter(se=>se.kind==="new").length,m:[...ge.values()].filter(se=>se.kind==="updated").length})}),u.jsx("button",{className:"text-ink-faint hover:text-ink underline decoration-dotted transition-colors",onClick:()=>{Iae(c??[]),Te(new Map)},"data-atlas-mark-all":!0,children:a("atlas.markAllSeen")})]})]}),o&&ne&&ne.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(Oo,{size:14,strokeWidth:1.75}),u.jsxs("select",{value:ne.prefs.terminal,onChange:se=>{const Be=se.target.value;if(Be==="__add__"){window.desktopSessions?.addTerminal().then(()=>window.desktopSessions?.openTargets().then(ke));return}window.desktopSessions?.setOpenPrefs({terminal:Be}).then(ve=>ke(We=>We&&{...We,prefs:ve}))},className:"bg-transparent focus:outline-none text-sm text-ink cursor-pointer","data-atlas-terminal-select":!0,children:[ne.terminals.map(se=>u.jsx("option",{value:se.id,children:se.name},se.id)),ne.canAddCustom&&u.jsx("option",{value:"__add__",children:a("atlas.otherTerminal")})]})]}),o&&u.jsxs("button",{onClick:()=>C(!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(jS,{size:14,strokeWidth:1.75})," ",a("atlas.sources")]}),o&&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(Un,{size:14,className:"animate-spin"}):u.jsx(lr,{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(mn,{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(se=>!se.archived).sort((se,Be)=>Be.updatedAt-se.updatedAt).slice(0,6).map(se=>u.jsxs("button",{onClick:()=>{e(),_s(se.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":se.id,children:[se.sourceSession?.sessionId?u.jsx("span",{className:"text-2xs font-mono border border-line rounded px-1 py-px shrink-0 text-ink-faint",children:se.sourceSession.runner}):u.jsx(h5,{size:13,strokeWidth:1.75,className:"shrink-0 text-ink-faint"}),u.jsx("span",{className:"flex-1 truncate text-sm",children:se.name})]},se.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")}),!o&&u.jsx("div",{className:"px-4 py-2 text-xs text-ink-faint",children:a("atlas.webNoScan")}),o&&c===null&&u.jsxs("div",{className:"px-4 py-2 text-sm text-ink-faint flex items-center gap-2",children:[u.jsx(Un,{size:14,className:"animate-spin"})," ",a("atlas.scanning")]}),o&&c!==null&&et.length===0&&u.jsx("div",{className:"px-4 py-2 text-xs text-ink-faint",children:a("atlas.empty")}),et.map(se=>{const Be=se.cwd??"",ve=b!=="canvases"&&kt===se;return u.jsxs("button",{onClick:()=>y(Be),className:`w-full text-left px-4 py-2 flex items-center gap-2 transition-colors ${ve?"bg-accent/5 text-accent":"text-ink hover:bg-wash"}`,"data-atlas-folder":se.name||"unfiled",children:[ve?u.jsx(Pc,{size:15,strokeWidth:1.75,className:"shrink-0"}):u.jsx(lz,{size:15,strokeWidth:1.75,className:"shrink-0 text-ink-faint"}),u.jsx("span",{className:"flex-1 truncate text-sm",children:se.name||a("atlas.unfiled")}),(()=>{const We=se.cards.filter(ut=>ge.has(gc(ut))).length;return We>0?u.jsxs("span",{className:"text-2xs text-accent shrink-0","data-atlas-folder-changes":!0,children:["+",We]}):null})(),u.jsx("span",{className:"text-2xs text-ink-faint shrink-0",children:se.cards.length})]},Be)}),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(h5,{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(se=>!se.archived).sort((se,Be)=>Be.updatedAt-se.updatedAt).map(se=>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(),_s(se.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:se.name}),u.jsxs("div",{className:"text-2xs text-ink-faint mt-0.5 flex items-center gap-1.5",children:[u.jsx("span",{children:hx(se.updatedAt)}),!!se.sourceSession?.sessionId&&u.jsx("span",{className:"font-mono border border-line rounded px-1 py-px",children:se.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:Be=>{Be.stopPropagation(),Ff(se.id,!0)},"data-atlas-archive":!0,children:u.jsx(zo,{size:15,strokeWidth:1.75})}),!!se.sourceSession&&Vx(se).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:[se.sourceSession.sessionId&&u.jsxs("span",{children:["◉ ",se.sourceSession.runner," ",se.sourceSession.sessionId.slice(0,8)," · ",He(a("atlas.turnsN"),{n:se.sourceSession.importedCount})]}),(se.sourceSession.chapters??[]).map(Be=>u.jsxs("span",{children:["↳ ",Be.runner," ",Be.sessionId.slice(0,8)," · ",He(a("atlas.turnsN"),{n:Be.importedCount})]},Be.sessionId)),(se.sourceSession.branches??[]).map(Be=>u.jsxs("span",{children:["⑂ ",Be.runner," ",Be.sessionId.slice(0,8)," · ",He(a("atlas.turnsN"),{n:Be.importedCount})]},Be.sessionId))]})]},se.id)),r.some(se=>se.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:He(a("atlas.archivedGroup"),{n:r.filter(se=>se.archived).length})}),u.jsx("div",{className:"space-y-1.5 mt-1.5",children:r.filter(se=>se.archived).sort((se,Be)=>Be.updatedAt-se.updatedAt).map(se=>u.jsxs("button",{title:a("atlas.restoreOpen"),onClick:()=>{Ff(se.id,!1).then(()=>{e(),_s(se.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:se.name}),!!se.sourceSession?.sessionId&&u.jsx("span",{className:"text-2xs font-mono border border-line rounded px-1 py-px shrink-0 text-ink-faint",children:se.sourceSession.runner})]}),u.jsx("div",{className:"text-2xs text-ink-faint mt-0.5",children:hx(se.updatedAt)})]},se.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(Pf,{size:13,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),u.jsx("input",{value:H,onChange:se=>V(se.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})]}),dt.map(se=>u.jsx("button",{onClick:()=>K(Be=>{const ve=new Set(Be);return ve.has(se)?ve.delete(se):ve.add(se),ve}),className:`text-2xs font-mono border rounded-lg px-2 py-1 transition-colors ${X.has(se)?"border-line text-ink-faint line-through":"border-accent/40 text-accent bg-accent/5"}`,"data-atlas-runner-toggle":se,children:se},se)),ge.size>0&&u.jsx("button",{onClick:()=>P(se=>!se),className:`text-2xs border rounded-lg px-2 py-1 transition-colors ${ee?"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(se=>se.subagent)&&u.jsx("button",{onClick:()=>fe(se=>!se),className:`text-2xs border rounded-lg px-2 py-1 transition-colors ${re?"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:()=>W(se=>({time:"name",name:"size",size:"runner",runner:"time"})[se]),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(sP,{size:12,strokeWidth:1.75}),a(`atlas.sort${F[0].toUpperCase()}${F.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," · ",He(a("atlas.sessions"),{n:kt.cards.length})]}),u.jsx("div",{className:"space-y-1.5",children:bt.map(se=>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(se))?"border-accent/60 bg-accent/5":"border-line"}`,onClick:()=>{Et(se)},"data-atlas-session":se.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:qe(se)}),M.has(se.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(se.sessionId)}`,"data-atlas-fork":!0,children:"⑂"}),ge.get(gc(se))?.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")}),ge.get(gc(se))?.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:["+",yE(ge.get(gc(se)).deltaSize)]}),se.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 Be=q(se.sessionId);return Be?u.jsx("span",{className:"text-2xs text-ink-faint border border-line rounded px-1 py-px shrink-0",title:Be.name,"data-atlas-badge":"canvas",children: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:se.runner}),u.jsx("span",{children:hx(se.mtime)}),u.jsx("span",{children:yE(se.size)})]})]}),k===se.rel?u.jsx(Un,{size:16,className:"animate-spin text-accent shrink-0"}):u.jsxs("div",{className:`${R.has(Z(se))?"":"opacity-0 group-hover:opacity-100"} transition-opacity flex items-center gap-1 shrink-0`,children:[!q(se.sessionId)&&!!se.sessionId&&u.jsx("button",{title:a("atlas.pickForMerge"),className:`p-1.5 rounded transition-colors ${R.has(Z(se))?"text-accent":"text-ink-faint hover:text-accent"}`,onClick:Be=>{Be.stopPropagation(),U(se)},"data-atlas-pick":R.has(Z(se))?"on":"off",children:R.has(Z(se))?u.jsx(bB,{size:16,strokeWidth:1.75}):u.jsx(Gb,{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(wz,{size:16,strokeWidth:1.75})}),r.some(Be=>Be.sourceSession?.sessionId===se.sessionId)&&u.jsx("button",{title:a("atlas.recast"),className:"text-ink-faint hover:text-red-500 p-1.5 rounded transition-colors",onClick:Be=>{Be.stopPropagation(),Ve(se)},"data-atlas-recast":!0,children:u.jsx(eB,{size:16,strokeWidth:1.75})}),!q(se.sessionId)&&u.jsx("button",{title:a("atlas.mountTo"),className:"text-ink-faint hover:text-accent p-1.5 rounded transition-colors",onClick:Be=>{Be.stopPropagation(),N(se)},"data-atlas-mount":!0,children:u.jsx(Do,{size:16,strokeWidth:1.75})}),Ae.has(se.runner)&&u.jsx("button",{title:He(a("atlas.openApp"),{name:Ae.get(se.runner)}),className:"text-ink-faint hover:text-accent p-1.5 rounded transition-colors",onClick:Be=>{Be.stopPropagation(),Ht(se,"app")},"data-atlas-open-app":!0,children:u.jsx(nP,{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:Be=>{Be.stopPropagation(),Ht(se,"terminal")},"data-atlas-open-cli":!0,children:u.jsx(Oo,{size:16,strokeWidth:1.75})})]})]},se.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&&!B&&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:He(a("atlas.mergeSelected"),{n:R.size})}),k==="__merge__"?u.jsx(Un,{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:()=>{Bt()},"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:()=>$(!0),"data-atlas-merge-into":!0,children:a("atlas.mergeInto")})]}),u.jsx("button",{className:"text-ink-faint hover:text-ink p-1",onClick:()=>G(new Map),title:a("common.cancel"),children:u.jsx(mn,{size:14,strokeWidth:1.75})})]}),(T||B)&&u.jsx("div",{className:"absolute inset-0 z-10 bg-ink/20 flex items-center justify-center",onClick:()=>{N(null),$(!1)},children:u.jsxs("div",{className:"bg-surface border border-line rounded-2xl shadow-xl w-[400px] max-h-[70%] overflow-y-auto",onClick:se=>se.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(B?"atlas.mergeInto":"atlas.mountTo")}),u.jsx("div",{className:"text-2xs text-ink-muted mt-0.5",children:a(B?"atlas.mergeSelected":"atlas.mountHint").replace("{n}",String(R.size))})]}),r.filter(se=>!se.archived&&se.kind!=="paradigm").sort((se,Be)=>Be.updatedAt-se.updatedAt).map(se=>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(B){$(!1),Bt(se.id);return}const Be=T;N(null),(async()=>{S(Be.rel);try{const{streamRunnerConversation:ve}=await Tt(async()=>{const{streamRunnerConversation:qt}=await import("./index-CTQSx_k0.js");return{streamRunnerConversation:qt}},[]),{mountConversationToProject:We,shellSessionReader:ut}=await Tt(async()=>{const{mountConversationToProject:qt,shellSessionReader:hn}=await import("./canonical-DccXDqkX.js");return{mountConversationToProject:qt,shellSessionReader:hn}},[]),gt=await ve(ut(Be.rootKey,Be.rel)),At=await We(gt,se.id);if(!At)throw new Error(De("handoff.notASession"));Ye("success",He(De("atlas.mountedChapter"),{n:At.kind==="mounted"||At.kind==="appended"?At.turns:0}),9e3),e(),t()}catch(ve){Ye("error",He(De("atlas.parseFailed"),{msg:ve instanceof Error?ve.message:String(ve)}))}finally{S(null)}})()},children:se.name},se.id))]})}),w&&u.jsx(Oae,{roots:h,counts:Ke,onChanged:()=>{Le()},onClose:()=>C(!1)})]})}),document.body)}function Rae({conversations:e,onClose:t,onDone:n}){const a=jt(),[r,s]=L.useState(new Set),[o,c]=L.useState(!1),d=p=>{s(x=>{const b=new Set(x);return b.has(p)?b.delete(p):b.add(p),b})},h=r.size===e.length,m=async()=>{r.size===0||o||(c(!0),await cF([...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(mn,{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(LS,{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:He(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||o,className:"text-xs bg-accent hover:bg-accent-strong text-white px-5 py-2 rounded-lg transition-colors disabled:opacity-30",children:o?"…":He(a("import.confirm"),{n:r.size})})]})]})})}function Lae(e){const t=Date.now()-e,n=Math.floor(t/6e4);if(n<1)return De("switcher.justNow");if(n<60)return He(De("switcher.minAgo"),{n});const a=Math.floor(n/60);if(a<24)return He(De("switcher.hourAgo"),{n:a});const r=Math.floor(a/24);return r<30?He(De("switcher.dayAgo"),{n:r}):new Date(e).toLocaleDateString(Ra.getState().lang==="zh"?"zh-CN":"en-US")}function jae({onSwitched:e}){const t=jt(),n=rn(_=>_.projects),a=rn(_=>_.activeId),r=rn(_=>_.switching),s=n.find(_=>_.id===a)?.kind==="paradigm",[o,c]=L.useState(!1),[d,h]=L.useState(null),[m,p]=L.useState(!1),[x,b]=L.useState(void 0),[y,k]=L.useState(null),[S,w]=L.useState(""),C=L.useRef(null),T=L.useRef(null),N=n.find(_=>_.id===a),D=n.filter(_=>!_.archived).sort((_,R)=>R.updatedAt-_.updatedAt).slice(0,7),O=async _=>{const{canvasUniqueness:R}=await Tt(async()=>{const{canvasUniqueness:Z}=await import("./canonical-DccXDqkX.js");return{canvasUniqueness:Z}},[]),G=await R(_.id),B=G==="native"?"confirm.deleteNative":G==="diverged-mirror"?"confirm.deleteDiverged":"confirm.deletePristine";await Cs({title:De("confirm.deleteCanvasTitle"),message:He(De(B),{name:_.name}),confirmLabel:De("common.delete"),danger:G!=="pristine-mirror"})&&A7(_.id).then(e)};L.useEffect(()=>{if(!o)return;const _=R=>{T.current?.contains(R.target)||c(!1)};return window.addEventListener("mousedown",_),()=>window.removeEventListener("mousedown",_)},[o]);const M=async _=>{c(!1),await _s(_),e(),Tt(()=>import("./canonical-DccXDqkX.js"),[]).then(R=>R.unsubscribeOrphanedSessions()),Tt(()=>import("./live-mirror-D3u92mbO.js"),[]).then(R=>R.sweepRecentSessions())};return u.jsxs("div",{ref:T,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(!o),disabled:r,className:"bg-card/90 backdrop-blur border border-line rounded-xl px-3.5 py-2 shadow-sm hover:bg-wash transition-colors flex items-center gap-2 text-sm text-ink max-w-[240px] disabled:opacity-60",children:[r?u.jsx(Un,{size:16,strokeWidth:1.75,className:"animate-spin shrink-0 text-accent"}):s?u.jsx(WP,{size:16,strokeWidth:1.75,className:"shrink-0 text-accent"}):u.jsx(Pc,{size:16,strokeWidth:1.75,className:"shrink-0 text-ink-muted"}),u.jsx("span",{className:"truncate font-medium",children:N?.name??"…"}),u.jsx(Cl,{size:14,strokeWidth:1.75,className:"shrink-0 text-ink-faint"})]}),!!N?.sourceSession?.sessionId&&(()=>{const _=rm.size>0&&!rm.has(N.sourceSession.sessionId);return u.jsxs("button",{title:_?De("switcher.mirrorBadgeGone"):He(De("switcher.mirrorBadge"),{runner:N.sourceSession.runner}),onClick:()=>{b(N.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 ${_?"text-ink-faint/50 line-through decoration-1":"text-ink-faint hover:text-accent"}`,"data-twin-badge":_?"unreachable":"live",children:["⇄ ",N.sourceSession.runner]})})()]}),o&&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:D.map(_=>u.jsx("div",{className:`group flex items-center gap-1 px-3 py-2 hover:bg-wash cursor-pointer transition-colors ${_.id===a?"bg-accent/5":""}`,onClick:()=>{y!==_.id&&_.id!==a&&M(_.id)},children:y===_.id?u.jsx("input",{autoFocus:!0,value:S,onChange:R=>w(R.target.value),onClick:R=>R.stopPropagation(),onKeyDown:R=>{R.key==="Enter"&&!Qa(R)&&S.trim()&&(T7(_.id,S.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 ${_.id===a?"text-accent font-medium":"text-ink"}`,children:_.name}),u.jsxs("div",{className:"text-2xs text-ink-faint flex items-center gap-1.5",children:[u.jsx("span",{children:Lae(_.updatedAt)}),!!_.sourceSession?.sessionId&&u.jsx("span",{className:"font-mono border border-line rounded px-1 py-px","data-mirror-mark":!0,children:_.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(_.id),w(_.name)},children:u.jsx(Fc,{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(),O(_)},children:u.jsx(Va,{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(),Ff(_.id,!0).then(e)},"data-archive-canvas":!0,children:u.jsx(zo,{size:14,strokeWidth:1.75})})]})},_.id))}),u.jsxs("div",{className:"border-t border-line mt-1 pt-1",children:[u.jsxs("button",{onClick:()=>{c(!1),Am().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(vm,{size:15,strokeWidth:1.75})," ",t("switcher.newCanvas")]}),u.jsxs("button",{onClick:()=>C.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(MB,{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(Oz,{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(lr,{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:C,type:"file",accept:".json,.jsonl,application/json",className:"hidden",onChange:_=>{const R=_.target.files?.[0];R&&oF(R).then(G=>{G.kind==="own"&&G.ok?(c(!1),e()):G.kind==="chat"&&(c(!1),h(G.conversations))}).catch(G=>{Ye("error",He(De("toast.importFailedGeneric"),{msg:G instanceof Error?G.message:String(G)}))}),_.target.value=""}})]})]}),d&&u.jsx(Rae,{conversations:d,onClose:()=>h(null),onDone:()=>{h(null),e()}}),m&&u.jsx(m9,{onClose:()=>{p(!1),b(void 0)},onSwitched:e,focusSessionId:x})]})}const Pae="JVBERi0xLjQKMSAwIG9iago8PCAvVHlwZSAvQ2F0YWxvZyAvUGFnZXMgMiAwIFIgPj4KZW5kb2JqCjIgMCBvYmoKPDwgL1R5cGUgL1BhZ2VzIC9LaWRzIFszIDAgUiA0IDAgUl0gL0NvdW50IDIgPj4KZW5kb2JqCjMgMCBvYmoKPDwgL1R5cGUgL1BhZ2UgL1BhcmVudCAyIDAgUiAvTWVkaWFCb3ggWzAgMCA1OTUgODQyXSAvQ29udGVudHMgNSAwIFIgL1Jlc291cmNlcyA8PCAvRm9udCA8PCAvRjEgNyAwIFIgL0YyIDggMCBSID4+ID4+ID4+CmVuZG9iago0IDAgb2JqCjw8IC9UeXBlIC9QYWdlIC9QYXJlbnQgMiAwIFIgL01lZGlhQm94IFswIDAgNTk1IDg0Ml0gL0NvbnRlbnRzIDYgMCBSIC9SZXNvdXJjZXMgPDwgL0ZvbnQgPDwgL0YxIDcgMCBSIC9GMiA4IDAgUiA+PiA+PiA+PgplbmRvYmoKNSAwIG9iago8PCAvTGVuZ3RoIDExMTIgPj4Kc3RyZWFtCkJUCi9GMiAxOSBUZiAxIDAgMCAxIDY0IDcyNS4wIFRtIChXaHkgU2F2ZWQgQXJ0aWNsZXMgU3RheSBVbnJlYWQpIFRqCi9GMSAxMSBUZiAxIDAgMCAxIDY0IDcwOC4wIFRtIChBIHNob3J0IGJyaWVmIG9uIGRpZ2l0YWwgaG9hcmRpbmcgYW5kIHRoZSBjb2xsZWN0b3IncyBmYWxsYWN5KSBUagovRjIgMTMgVGYgMSAwIDAgMSA2NCA2NjkuMCBUbSAoMS4gVGhlIHBoZW5vbWVub24pIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNjUxLjUgVG0gKFJlYWQtaXQtbGF0ZXIgc2VydmljZXMgcmVwb3J0IHRoYXQgbW9zdCBzYXZlZCBpdGVtcyBhcmUgbmV2ZXIpIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNjM0LjAgVG0gKHJlb3BlbmVkLiBBY3Jvc3MgcHVibGlzaGVkIHVzYWdlIHN0dWRpZXMsIHRoZSBzaGFyZSBvZiBzYXZlZCkgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA2MTYuNSBUbSAoYXJ0aWNsZXMgdGhhdCBnZXQgYSBzZWNvbmQgdmlzaXQgaXMgc21hbGwsIGFuZCBjb21wbGV0aW9uIHJhdGVzKSBUagovRjEgMTEuNSBUZiAxIDAgMCAxIDY0IDU5OS4wIFRtIChhcmUgc21hbGxlciBzdGlsbC4gVGhlIGFyY2hpdmUgZ3Jvd3M7IHRoZSByZWFkaW5nIGRvZXMgbm90LikgVGoKL0YyIDEzIFRmIDEgMCAwIDEgNjQgNTYwLjAgVG0gKDIuIFRoZSBjb2xsZWN0b3IncyBmYWxsYWN5KSBUagovRjEgMTEuNSBUZiAxIDAgMCAxIDY0IDU0Mi41IFRtIChDb2xsZWN0aW5nIHByb2R1Y2VzIGFuIGltbWVkaWF0ZSBzZW5zZSBvZiBwcm9ncmVzcyB3aGlsZSB0aGUpIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNTI1LjAgVG0gKHVuZGVyc3RhbmRpbmcgaXQgcHJvbWlzZXMgaXMgZGVmZXJyZWQuIFNhdmluZyBhIHRleHQgZmVlbHMgbGlrZSkgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA1MDcuNSBUbSAoYSBmaXJzdCBzdGVwIG9mIHJlYWRpbmcgaXQsIGJ1dCBubyBwYXJ0IG9mIHRoZSByZWFkaW5nIGhhcykgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA0OTAuMCBUbSAoaGFwcGVuZWQuKSBUagovRjIgMTEuNSBUZiAxIDAgMCAxIDY0IDQ3Mi41IFRtIChUaGUgYWN0IG9mIHNhdmluZyBpcyBtaXN0YWtlbiBmb3IgdGhlIGFjdCBvZiBsZWFybmluZy4pIFRqCkVUCmVuZHN0cmVhbQplbmRvYmoKNiAwIG9iago8PCAvTGVuZ3RoIDkwOCA+PgpzdHJlYW0KQlQKL0YyIDEzIFRmIDEgMCAwIDEgNjQgNzI1LjAgVG0gKDMuIFdoeSBpdCBwZXJzaXN0cykgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA3MDcuNSBUbSAoVGhlIGNvc3RzIGFyZSBhc3ltbWV0cmljOiBzYXZpbmcgdGFrZXMgb25lIHNlY29uZCBhbmQgcGF5cyBvdXQpIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNjkwLjAgVG0gKGEgc21hbGwgcmV3YXJkIG5vdzsgcmVhZGluZyB0YWtlcyBhbiBob3VyIGFuZCBwYXlzIG91dCBsYXRlci4pIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNjcyLjUgVG0gKEhhYml0cyBmb2xsb3cgdGhlIGNoZWFwZXIgbG9vcCwgc28gbGlicmFyaWVzIGluZmxhdGUgYnkgZGVmYXVsdC4pIFRqCi9GMiAxMyBUZiAxIDAgMCAxIDY0IDYzMy41IFRtICg0LiBXaGF0IGhlbHBzKSBUagovRjEgMTEuNSBUZiAxIDAgMCAxIDY0IDYxNi4wIFRtIChJbnRlcnZlbnRpb25zIHRoYXQgd29yayBtb3ZlIHByb2Nlc3NpbmcgdG8gdGhlIG1vbWVudCBvZiBjYXB0dXJlOikgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA1OTguNSBUbSAod3JpdGUgb25lIGxpbmUgaW4geW91ciBvd24gd29yZHMgYWJvdXQgd2h5IHRoZSBpdGVtIG1hdHRlcnMsIGFuZCkgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA1ODEuMCBUbSAoc2NoZWR1bGUgYSByZXZpZXcgcGFzcyBpbnN0ZWFkIG9mIHRydXN0aW5nIHRoZSBhcmNoaXZlIHRvKSBUagovRjEgMTEuNSBUZiAxIDAgMCAxIDY0IDU2My41IFRtIChyZXN1cmZhY2UgaXQuKSBUagovRjEgMTEuNSBUZiAxIDAgMCAxIDY0IDUzMi4wIFRtIChBIHNtYWxsZXIgbGlicmFyeSB0aGF0IGdldHMgcHJvY2Vzc2VkIGJlYXRzIGEgY29tcGxldGUgb25lIHRoYXQpIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNTE0LjUgVG0gKGRvZXMgbm90LikgVGoKRVQKZW5kc3RyZWFtCmVuZG9iago3IDAgb2JqCjw8IC9UeXBlIC9Gb250IC9TdWJ0eXBlIC9UeXBlMSAvQmFzZUZvbnQgL0hlbHZldGljYSA+PgplbmRvYmoKOCAwIG9iago8PCAvVHlwZSAvRm9udCAvU3VidHlwZSAvVHlwZTEgL0Jhc2VGb250IC9IZWx2ZXRpY2EtQm9sZCA+PgplbmRvYmoKeHJlZgowIDkKMDAwMDAwMDAwMCA2NTUzNSBmIAowMDAwMDAwMDA5IDAwMDAwIG4gCjAwMDAwMDAwNTggMDAwMDAgbiAKMDAwMDAwMDEyMSAwMDAwMCBuIAowMDAwMDAwMjU3IDAwMDAwIG4gCjAwMDAwMDAzOTMgMDAwMDAgbiAKMDAwMDAwMTU1NyAwMDAwMCBuIAowMDAwMDAyNTE2IDAwMDAwIG4gCjAwMDAwMDI1ODYgMDAwMDAgbiAKdHJhaWxlcgo8PCAvU2l6ZSA5IC9Sb290IDEgMCBSID4+CnN0YXJ0eHJlZgoyNjYxCiUlRU9G",zae=`<!-- tdag-page:1 -->
548
548
 
549
549
  # Why Saved Articles Stay Unread
550
550
 
@@ -778,11 +778,11 @@ ${n==="zh"?"**高光(原文保真)**":"**Highlights (verbatim)**"}
778
778
  ${T.map(_=>`> ${_.text}`).join(`
779
779
  `)}`:"",D=In();x.push(D);const O=`${n==="zh"?"凝练":"Condensed"}: ${w.data.question.replace(/\s+/g," ").slice(0,60)} → ${C.data.question.replace(/\s+/g," ").slice(0,60)}`,M=`${t[S]||""}${N}`;p.push({id:D,type:"thought",position:{x:w.position.x+h,y:w.position.y},dragHandle:".drag-handle",data:{question:O,response:M,responses:[M],responseIndex:0,condensedFrom:k.nodeIds,createdAt:new Date().toISOString(),isCollapsed:!1,isEditing:!1,isEditingResponse:!1,isLoading:!1,tokenCount:$n(`${O}
780
780
  ${M}`),highlights:[],highlightMode:"tag",attachments:[],excludedAttachmentIds:[],includedAttachmentIds:[],roleMode:"inherit",isRoot:!1,isBranch:!1}}),k.nodeIds.forEach(_=>m.set(_,D))});for(const k of r){if(c.has(k.id))continue;const S=In();m.set(k.id,S);const w=k.data;p.push({...k,id:S,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 S=m.get(k.source),w=m.get(k.target);if(!S||!w||S===w)continue;const C=`${S}→${w}`;y.has(C)||(y.add(C),b.push({...k,id:`e-${In()}`,source:S,target:w,selected:!1}))}return a.pushHistory(),oe.setState(k=>{const S=[...k.nodes,...p],w=[...k.edges,...b];return{nodes:ir(S,w),edges:w}}),{copiedNodes:p.length,collapsedRuns:e.length,distillIds:x}}let ul=0;function Are(){ul++,pe.getState().setCondenseRun({status:"idle",current:0,total:0,streaming:""})}async function Nre(e,t,n){if(e.length===0)return;const a=++ul,r=pe.getState(),s=oe.getState().nodes.map(o=>o.id);r.setCondenseRun({status:"building",current:0,total:e.length,streaming:"",error:void 0,originalIds:s,distillIds:[]});try{const o=[];let c="";for(let h=0;h<e.length;h++){if(ul!==a)return;pe.getState().setCondenseRun({current:h+1,streaming:""});const m=await Ere(e[h],t,n,p=>{ul===a&&pe.getState().setCondenseRun({streaming:p})},c||void 0);if(ul!==a)return;o.push(m),c=`${c}
781
- ${m}`.slice(-1500)}const d=Tre(e,o,t);if(ul!==a)return;pe.getState().setCondenseRun({status:"done",streaming:"",distillIds:d.distillIds}),Ye("success",De("condense.copyReady"),8e3,{label:De("tmap.export"),run:()=>pe.getState().setThoughtMapOpen(!0)})}catch(o){if(ul!==a)return;pe.getState().setCondenseRun({status:"error",error:o instanceof Error?o.message:String(o)})}}function Cre({onFocusSegment:e}){const t=pe(B=>B.condenseDialogOpen),n=pe(B=>B.condenseRun),a=jt(),r=Ra(B=>B.lang),s=oe(B=>B.nodes),o=oe(B=>B.edges),[c,d]=L.useState(0),h=L.useMemo(()=>t&&n.status==="idle"?wre(s,o):[],[t,n.status,s,o,c]),m=pe(B=>B.selectedModel),p=_l()?.models??[],[x,b]=L.useState(""),[y,k]=L.useState(new Set),[S,w]=L.useState(null),C=L.useRef(null),T=B=>{const $=C.current?.getBoundingClientRect();if(!$)return;const Z=B.clientX-$.left,U=B.clientY-$.top,q=V=>w({x:Math.min(window.innerWidth-120,Math.max(0,V.clientX-Z)),y:Math.min(window.innerHeight-80,Math.max(0,V.clientY-U))}),H=()=>{window.removeEventListener("mousemove",q),window.removeEventListener("mouseup",H)};window.addEventListener("mousemove",q),window.addEventListener("mouseup",H)},N=B=>B.nodeIds.join(","),D=h.filter(B=>!y.has(N(B))),O=D.reduce((B,$)=>B+$.saving,0),M=()=>{pe.getState().setCondenseDialogOpen(!1),pe.getState().setCondenseHighlightIds([])};if(L.useEffect(()=>{if(!t)return;const B=$=>{$.key==="Escape"&&M()};return window.addEventListener("keydown",B),()=>window.removeEventListener("keydown",B)},[t]),!t)return null;const _=()=>{D.length!==0&&Nre(D,r,x||m||void 0)},R=()=>{oe.getState().setArchived(n.originalIds,!0),Ye("success",a("condense.originalArchived")),pe.getState().setCondenseRun({status:"idle",current:0,total:0,streaming:"",originalIds:[],distillIds:[]}),M()},G=()=>{const $=oe.getState().nodes.filter(Z=>n.distillIds.includes(Z.id));$.length&&e?.($.map(Z=>Z.id))};return Za.createPortal(u.jsxs("div",{ref:C,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:S?{left:S.x,top:S.y}:{left:80,bottom:16},"data-condense-dialog":!0,onClick:B=>B.stopPropagation(),children:[u.jsxs("div",{className:"flex items-start justify-between mb-1 cursor-grab active:cursor-grabbing select-none",onMouseDown:T,children:[u.jsxs("div",{className:"text-sm font-semibold text-ink flex items-center gap-2",children:[u.jsx(ym,{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(mn,{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(B=>B+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:He(a("condense.scanLine"),{turns:String(s.filter(B=>B.data.response&&!B.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:B=>b(B.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:He(a("condense.modelGlobal"),{model:m||"auto"})}),p.map(B=>u.jsx("option",{value:B.id,children:B.id},B.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(B=>{const $=N(B),Z=!y.has($);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:()=>{pe.getState().setCondenseHighlightIds(B.nodeIds),e?.(B.nodeIds)},children:[u.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[u.jsx("input",{type:"checkbox",checked:Z,onClick:U=>U.stopPropagation(),onChange:()=>k(U=>{const q=new Set(U);return q.has($)?q.delete($):q.add($),q}),className:"accent-[var(--color-accent)]","data-condense-check":!0}),u.jsx("span",{className:"text-2xs text-ink-faint font-mono",children:He(a("condense.segMeta"),{n:String(B.nodeIds.length),tok:String(B.saving)})})]}),u.jsx("p",{className:"text-xs text-ink mt-1 leading-snug line-clamp-2",children:B.headQuestion})]},$)})}),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:_,disabled:D.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(Bs,{size:13,strokeWidth:1.75}),He(a("condense.buildCopy"),{n:String(D.length),tok:String(O)})]})]})]}),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(Un,{size:15,className:"animate-spin text-accent"}),He(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:()=>Are(),"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:()=>pe.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(ii,{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:G,className:"text-xs bg-accent/10 text-accent hover:bg-accent/20 px-3 py-2 rounded-lg transition-colors",children:a("condense.viewCopy")}),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(zo,{size:13,strokeWidth:1.75})," ",a("condense.archiveOriginal")]})]}),u.jsx("button",{onClick:()=>{pe.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 IE(){const e=Ra(n=>n.lang),t=Ra(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 _re={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"})]})},DE={4:"prune",5:"map",6:"reading",7:"ref"};function Mre(){const e=pe(h=>h.tutorialOpen),t=pe(h=>h.setTutorialOpen);L.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=jt(),a=Ra(h=>h.lang),[r,s]=L.useState(0),o=[{label:n("tutorial.pg1"),steps:[1,2,3]},{label:n("tutorial.pg2"),steps:[4,5]},{label:n("tutorial.pg3"),steps:[6,7]},{label:n("tutorial.pg4"),steps:[8,9,10]}],c=r===o.length-1;if(L.useEffect(()=>{if(!e)return;s(0);const h=m=>{m.key==="ArrowRight"&&s(p=>Math.min(p+1,o.length-1)),m.key==="ArrowLeft"&&s(p=>Math.max(p-1,0))};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[e]),!e)return null;const d=o[r];return 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(mn,{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:DE[h]?u.jsx("img",{src:`/tutorial/${DE[h]}-${a}.gif`,loading:"lazy",alt:"",className:"w-full h-full object-cover"}):_re[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(Lf,{size:16,strokeWidth:1.75})}),u.jsx("div",{className:"flex items-center gap-2",children:o.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}/${o.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(Fi,{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 Ire=new URLSearchParams(window.location.search),Pi=Ire.get("dv"),uf="https://chenxiachan.github.io/thoughtdag/docs",E9=[{version:"0.4.11",date:"2026-09-08",announce:!1,lead:{zh:"性能优化:启动更快,后台更省,多个工具调用并行时更稳;300 节点以上的画布实测流畅。ThoughtDAG 现在可以用 Claude Code、Codex、Pi 作为节点的 Agent 运行时,处于测试阶段。",en:"Performance: faster launch, lighter in the background, steadier when several tool calls run in parallel; canvases past 300 nodes measured smooth. ThoughtDAG can now run a node through Claude Code, Codex or Pi as its agent runtime, in testing."},items:[]},{version:"0.4.10",date:"2026-09-07",announce:!1,lead:{zh:"Agent 执行预览继续:Codex 加入,和 Pi 一样在画布里带工具作答;这条通道现在在桌面版、本地网页版和 DeepSeek Harness 插件里都可用;插件里的 Harness Agent 按模型平铺;插件有新版本时画布会提示。",en:"Agent runs, preview continued: Codex joins Pi, answering with tools right from the canvas; the lane now works in the desktop app, the local web app and the DeepSeek Harness plugin alike; inside the plugin the Harness agent lists one entry per model; the canvas tells you when a newer plugin is out."},items:[]},{version:"0.4.9",date:"2026-09-07",announce:!1,lead:{zh:"Agent 执行预览:桌面版的模型选择器多了「Agent 执行」组,装了 Pi 的话可以直接在画布里让它带工具作答,轨迹、足迹、审批和提问都落在节点上,工作目录在顶栏可见可改。正式版会连同 Claude Code 与 Codex 一起发布。DeepSeek Harness 插件里的审批卡片同步更新。",en:'Agent runs, preview: the desktop picker gains an "Agent runs" group; with Pi installed, a question runs through it with tools right from the canvas, and the trace, footprints, approvals and questions land on the node, with the working directory visible on the toolbar. The full release will arrive together with Claude Code and Codex. The approval card inside the DeepSeek Harness plugin is updated alike.'},items:[]},{version:"0.4.8",date:"2026-09-07",announce:!1,lead:{zh:"DeepSeek Harness 插件在 Windows 上能打开了:静态资源和会话目录的路径守卫此前只认正斜杠,Windows 用户看到的是一片 403。感谢 GitHub 上的报告(#23)。桌面版本次只同步版本号。",en:"The DeepSeek Harness plugin now opens on Windows: the path guards for static assets and session directories only accepted forward slashes, so Windows users saw nothing but 403s. Thanks to the report on GitHub (#23). The desktop app only moves its version number this time."},items:[]},{version:"0.4.7",date:"2026-09-07",announce:!1,lead:{zh:"DeepSeek Harness 插件里,Agent 需要你批准的操作现在直接出现在节点上:工具、命令、理由,允许一次或拒绝,决定留在节点记录里。桌面版本次只同步版本号。",en:"Inside the DeepSeek Harness plugin, an action the agent needs approved now appears on the node itself: tool, command, reason, allow once or reject, and the decision stays in the node's record. The desktop app only moves its version number this time."},items:[]},{version:"0.4.6",date:"2026-09-06",announce:!0,lead:{zh:"🎉 Pi 的会话进了对话地图,「⋯」菜单里多了更新历史,随时能回看每一版改了什么。",en:"🎉 Pi sessions join the Session Atlas, and the ⋯ menu gains a release history, so what every version changed is one click away."},items:[{title:{zh:"Pi 的会话也在地图上了",en:"Pi sessions are on the map"},body:{zh:"本地 Pi 会话按项目聚在一起,打开就是一张图。Pi 里的每次分叉在图上就是一条支线,不再压成一条直线。命令行 why 和 MCP 也同步认识 Pi 留下的文件足迹。",en:"Local Pi sessions group by project and open as a graph. Every fork you made in Pi shows up as a branch instead of being flattened into one line. The why command and MCP index Pi's file footprints too."},link:{label:{zh:"怎么用",en:"How it works"},href:`${uf}/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:`${uf}/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:`${uf}/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:`${uf}/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 Eb(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 bx(e,t){return E9.filter(n=>n.announce&&Eb(n.version,t)<=0&&(e===null||Eb(n.version,e)>0))}const Sb="thoughtdag.whatsNewSeen",Dre=new URLSearchParams(window.location.search);function Ore(){if(!Pi)return[];if(Dre.get("wn")==="1")return bx(null,Pi);let t=null;try{t=localStorage.getItem(Sb)}catch{}if(t===null){let n=!1;try{n=!!(localStorage.getItem("thoughtdag.tutorialDone")||localStorage.getItem("thoughtdag.lastBackupAt"))}catch{}if(!n){try{localStorage.setItem(Sb,Pi)}catch{}return[]}return bx(null,Pi)}return t===Pi?[]:bx(t,Pi)}function S9({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 Rre(){const[e,t]=L.useState(()=>Ore()),n=e.length>0,a=Ra(c=>c.lang),r=jt(),s=L.useRef(null),o=()=>{if(Pi)try{localStorage.setItem(Sb,Pi)}catch{}t([])};return L.useEffect(()=>{if(!n)return;s.current?.focus({preventScroll:!0});const c=d=>{d.stopPropagation(),(d.key==="Escape"||d.key==="Enter")&&o()};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:o,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:He(r("whatsNew.title"),{v:Pi??""})}),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(S9,{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:()=>{o(),pe.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:o,className:"text-xs text-white px-4 py-2 rounded-lg bg-accent hover:bg-accent-strong transition-colors",children:r("whatsNew.ok")})]})]})}):null}function Lre(){const e=pe(r=>r.releaseNotesOpen),t=pe(r=>r.setReleaseNotesOpen),n=Ra(r=>r.lang),a=jt();return L.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:E9.map(r=>{const s=Pi===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(S9,{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 yx=e=>e.split("/").filter(Boolean).slice(-1)[0]??e;function jre(){const e=jt(),t=pe(D=>D.selectedModel),n=rn(D=>D.activeId),a=rn(D=>D.projects),r=oe(D=>D.nodes.length),[s,o]=L.useState(null),[c,d]=L.useState(null),[h,m]=L.useState(!1),[p,x]=L.useState(""),b=L.useRef(null),y=!!window.desktopAgents&&Fd(t);if(L.useEffect(()=>{if(!y)return;let D=!0;return r2().then(O=>{D&&o(O)}),NU().then(O=>{D&&d(O)}),()=>{D=!1}},[y,n,a,r]),L.useEffect(()=>{if(!h)return;const D=M=>{b.current&&!b.current.contains(M.target)&&m(!1)},O=M=>{M.key==="Escape"&&m(!1)};return document.addEventListener("mousedown",D),document.addEventListener("keydown",O),()=>{document.removeEventListener("mousedown",D),document.removeEventListener("keydown",O)}},[h]),!y||!s)return null;const k=a.find(D=>D.id===n),S=[...new Set(a.map(D=>D.agentCwd).filter(D=>!!D))].filter(D=>D!==k?.agentCwd).slice(0,5),w=async D=>{n&&(await c2(n,D),m(!1))},C=window.desktopAgents?.capabilities?.nativePicker!==!1,T=async()=>{const D=await window.desktopAgents.pickCwd();D&&await w(D)},N=async()=>{const D=p.trim();D.startsWith("/")&&await w(D)};return u.jsxs("div",{ref:b,className:"relative",children:[u.jsxs("button",{onClick:D=>{D.stopPropagation(),m(O=>!O)},className:"bg-card/90 backdrop-blur border border-line rounded-lg h-8 px-2.5 flex items-center gap-1.5 shadow-sm hover:bg-wash transition-colors text-xs text-ink max-w-[220px]",title:`${e("agent.cwd")} · ${s.cwd}`,"data-agent-cwd":s.kind,children:[u.jsx(Pc,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),u.jsx("span",{className:"truncate",children:s.kind==="workspace"?e("agent.cwdWorkspace"):yx(s.cwd)}),u.jsx(Cl,{size:12,strokeWidth:1.75,className:"text-ink-faint shrink-0"})]}),h&&u.jsxs("div",{className:"absolute right-0 top-full mt-1.5 w-[320px] bg-card border border-line rounded-xl shadow-lg py-1.5 z-50 animate-fade-in",onClick:D=>D.stopPropagation(),children:[u.jsx("p",{className:"text-2xs text-ink-faint uppercase tracking-wider font-medium px-3 pt-1 pb-1",children:e("agent.cwd")}),u.jsxs("button",{onClick:()=>{w(void 0)},className:"w-full text-left px-3 py-2 text-xs hover:bg-wash flex items-center gap-2",children:[u.jsxs("span",{className:"flex-1 min-w-0",children:[u.jsx("span",{className:"block text-ink",children:e(c?"agent.cwdMirrored":"agent.cwdWorkspace")}),u.jsx("span",{className:"block text-2xs text-ink-faint truncate",children:c??e("agent.cwdWorkspaceHint")})]}),!k?.agentCwd&&u.jsx(ii,{size:13,strokeWidth:2,className:"shrink-0 text-accent"})]}),k?.agentCwd&&u.jsxs("button",{onClick:()=>{w(k.agentCwd)},className:"w-full text-left px-3 py-2 text-xs hover:bg-wash flex items-center gap-2",children:[u.jsxs("span",{className:"flex-1 min-w-0",children:[u.jsx("span",{className:"block text-ink",children:yx(k.agentCwd)}),u.jsx("span",{className:"block text-2xs text-ink-faint truncate",children:k.agentCwd})]}),u.jsx(ii,{size:13,strokeWidth:2,className:"shrink-0 text-accent"})]}),S.length>0&&u.jsx("p",{className:"text-2xs text-ink-faint uppercase tracking-wider font-medium px-3 pt-2 pb-1",children:e("agent.cwdRecent")}),S.map(D=>u.jsx("button",{onClick:()=>{w(D)},className:"w-full text-left px-3 py-1.5 text-xs hover:bg-wash flex items-center gap-2",children:u.jsxs("span",{className:"flex-1 min-w-0",children:[u.jsx("span",{className:"block text-ink",children:yx(D)}),u.jsx("span",{className:"block text-2xs text-ink-faint truncate",children:D})]})},D)),u.jsx("div",{className:"border-t border-line/60 my-1"}),C?u.jsxs("button",{onClick:()=>{T()},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash flex items-center gap-2","data-agent-cwd-pick":!0,children:[u.jsx(Pc,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",e("agent.cwdPick")]}):u.jsxs("div",{className:"px-3 py-2 flex items-center gap-2",children:[u.jsx("input",{value:p,onChange:D=>x(D.target.value),onKeyDown:D=>{D.stopPropagation(),D.key==="Enter"&&N()},placeholder:e("agent.cwdType"),className:"flex-1 min-w-0 text-xs font-mono bg-wash border border-line rounded-md px-2 py-1 focus:outline-none focus:border-accent/60","data-agent-cwd-input":!0}),u.jsx("button",{onClick:()=>{N()},className:"text-xs text-accent hover:underline shrink-0",children:e("agent.cwdUse")})]}),u.jsx("div",{className:"border-t border-line/60 my-1"}),u.jsx("p",{className:"text-2xs text-ink-faint uppercase tracking-wider font-medium px-3 pt-1 pb-1",children:e("agent.guard")}),u.jsxs("button",{onClick:()=>{F5("ask"),m(!1)},className:"w-full text-left px-3 py-1.5 text-xs hover:bg-wash flex items-center gap-2","data-agent-guard":"ask",children:[u.jsx(uB,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),u.jsxs("span",{className:"flex-1 min-w-0",children:[u.jsx("span",{className:"block text-ink",children:e("agent.guardAsk")}),u.jsx("span",{className:"block text-2xs text-ink-faint",children:e("agent.guardAskHint")})]}),(k?.agentGuard?.mode??"ask")==="ask"&&u.jsx(ii,{size:13,strokeWidth:2,className:"shrink-0 text-accent"})]}),u.jsxs("button",{onClick:()=>{F5("allow"),m(!1)},className:"w-full text-left px-3 py-1.5 text-xs hover:bg-wash flex items-center gap-2","data-agent-guard":"allow",children:[u.jsx(hB,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),u.jsxs("span",{className:"flex-1 min-w-0",children:[u.jsx("span",{className:"block text-ink",children:e("agent.guardAllow")}),u.jsx("span",{className:"block text-2xs text-ink-faint",children:e("agent.guardAllowHint")})]}),k?.agentGuard?.mode==="allow"&&u.jsx(ii,{size:13,strokeWidth:2,className:"shrink-0 text-accent"})]}),(k?.agentGuard?.allow?.length??0)>0&&u.jsxs(u.Fragment,{children:[u.jsx("p",{className:"text-2xs text-ink-faint px-3 pt-2 pb-1",children:e("agent.guardAllowed")}),k.agentGuard.allow.map(D=>u.jsxs("div",{className:"px-3 py-1 text-xs flex items-center gap-2 min-w-0","data-agent-guard-allowed":D,children:[u.jsx("span",{className:"flex-1 min-w-0 truncate text-ink-muted font-mono",title:D,children:D}),u.jsx("button",{onClick:()=>{g7(D,!0)},className:"text-ink-faint hover:text-red-500 shrink-0",title:e("agent.guardRemove"),children:u.jsx(mn,{size:12,strokeWidth:2})})]},D))]})]})]})}const OE="thoughtdag.pluginUpdateNotified",Tb="dsh plugin --profile web update dsh-thoughtdag";async function Pre(e){try{const t=await fetch(e.replace(/\/+$/,"")+"/version",{credentials:"same-origin"});if(!t.ok)return;const n=await t.json();if(!n.version||!n.latest||Eb(n.latest,n.version)<=0)return;pe.getState().setPluginUpdate({current:n.version,latest:n.latest});let a=null;try{a=localStorage.getItem(OE)}catch{}if(a!==n.latest){try{localStorage.setItem(OE,n.latest)}catch{}Ye("info",He(De("plugin.updateAvailable"),{v:n.latest}),9e3)}}catch{}}const zre=Object.freeze(Object.defineProperty({__proto__:null,PLUGIN_UPDATE_COMMAND:Tb,bootPluginUpdateCheck:Pre},Symbol.toStringTag,{value:"Module"})),Bre={ruleout:"#ef4444",decision:"#6B5CE7",pivot:"#e8890c",open:"#d97706",insight:"#0284c7"},RE=e=>{if(e){for(let t=e.length-1;t>=0;t--)if(e[t])return e[t]}};function Hre(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(`
781
+ ${m}`.slice(-1500)}const d=Tre(e,o,t);if(ul!==a)return;pe.getState().setCondenseRun({status:"done",streaming:"",distillIds:d.distillIds}),Ye("success",De("condense.copyReady"),8e3,{label:De("tmap.export"),run:()=>pe.getState().setThoughtMapOpen(!0)})}catch(o){if(ul!==a)return;pe.getState().setCondenseRun({status:"error",error:o instanceof Error?o.message:String(o)})}}function Cre({onFocusSegment:e}){const t=pe(B=>B.condenseDialogOpen),n=pe(B=>B.condenseRun),a=jt(),r=Ra(B=>B.lang),s=oe(B=>B.nodes),o=oe(B=>B.edges),[c,d]=L.useState(0),h=L.useMemo(()=>t&&n.status==="idle"?wre(s,o):[],[t,n.status,s,o,c]),m=pe(B=>B.selectedModel),p=_l()?.models??[],[x,b]=L.useState(""),[y,k]=L.useState(new Set),[S,w]=L.useState(null),C=L.useRef(null),T=B=>{const $=C.current?.getBoundingClientRect();if(!$)return;const Z=B.clientX-$.left,U=B.clientY-$.top,q=V=>w({x:Math.min(window.innerWidth-120,Math.max(0,V.clientX-Z)),y:Math.min(window.innerHeight-80,Math.max(0,V.clientY-U))}),H=()=>{window.removeEventListener("mousemove",q),window.removeEventListener("mouseup",H)};window.addEventListener("mousemove",q),window.addEventListener("mouseup",H)},N=B=>B.nodeIds.join(","),D=h.filter(B=>!y.has(N(B))),O=D.reduce((B,$)=>B+$.saving,0),M=()=>{pe.getState().setCondenseDialogOpen(!1),pe.getState().setCondenseHighlightIds([])};if(L.useEffect(()=>{if(!t)return;const B=$=>{$.key==="Escape"&&M()};return window.addEventListener("keydown",B),()=>window.removeEventListener("keydown",B)},[t]),!t)return null;const _=()=>{D.length!==0&&Nre(D,r,x||m||void 0)},R=()=>{oe.getState().setArchived(n.originalIds,!0),Ye("success",a("condense.originalArchived")),pe.getState().setCondenseRun({status:"idle",current:0,total:0,streaming:"",originalIds:[],distillIds:[]}),M()},G=()=>{const $=oe.getState().nodes.filter(Z=>n.distillIds.includes(Z.id));$.length&&e?.($.map(Z=>Z.id))};return Za.createPortal(u.jsxs("div",{ref:C,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:S?{left:S.x,top:S.y}:{left:80,bottom:16},"data-condense-dialog":!0,onClick:B=>B.stopPropagation(),children:[u.jsxs("div",{className:"flex items-start justify-between mb-1 cursor-grab active:cursor-grabbing select-none",onMouseDown:T,children:[u.jsxs("div",{className:"text-sm font-semibold text-ink flex items-center gap-2",children:[u.jsx(ym,{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(mn,{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(B=>B+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:He(a("condense.scanLine"),{turns:String(s.filter(B=>B.data.response&&!B.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:B=>b(B.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:He(a("condense.modelGlobal"),{model:m||"auto"})}),p.map(B=>u.jsx("option",{value:B.id,children:B.id},B.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(B=>{const $=N(B),Z=!y.has($);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:()=>{pe.getState().setCondenseHighlightIds(B.nodeIds),e?.(B.nodeIds)},children:[u.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[u.jsx("input",{type:"checkbox",checked:Z,onClick:U=>U.stopPropagation(),onChange:()=>k(U=>{const q=new Set(U);return q.has($)?q.delete($):q.add($),q}),className:"accent-[var(--color-accent)]","data-condense-check":!0}),u.jsx("span",{className:"text-2xs text-ink-faint font-mono",children:He(a("condense.segMeta"),{n:String(B.nodeIds.length),tok:String(B.saving)})})]}),u.jsx("p",{className:"text-xs text-ink mt-1 leading-snug line-clamp-2",children:B.headQuestion})]},$)})}),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:_,disabled:D.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(Bs,{size:13,strokeWidth:1.75}),He(a("condense.buildCopy"),{n:String(D.length),tok:String(O)})]})]})]}),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(Un,{size:15,className:"animate-spin text-accent"}),He(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:()=>Are(),"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:()=>pe.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(ii,{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:G,className:"text-xs bg-accent/10 text-accent hover:bg-accent/20 px-3 py-2 rounded-lg transition-colors",children:a("condense.viewCopy")}),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(zo,{size:13,strokeWidth:1.75})," ",a("condense.archiveOriginal")]})]}),u.jsx("button",{onClick:()=>{pe.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 IE(){const e=Ra(n=>n.lang),t=Ra(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 _re={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"})]})},DE={4:"prune",5:"map",6:"reading",7:"ref"};function Mre(){const e=pe(h=>h.tutorialOpen),t=pe(h=>h.setTutorialOpen);L.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=jt(),a=Ra(h=>h.lang),[r,s]=L.useState(0),o=[{label:n("tutorial.pg1"),steps:[1,2,3]},{label:n("tutorial.pg2"),steps:[4,5]},{label:n("tutorial.pg3"),steps:[6,7]},{label:n("tutorial.pg4"),steps:[8,9,10]}],c=r===o.length-1;if(L.useEffect(()=>{if(!e)return;s(0);const h=m=>{m.key==="ArrowRight"&&s(p=>Math.min(p+1,o.length-1)),m.key==="ArrowLeft"&&s(p=>Math.max(p-1,0))};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[e]),!e)return null;const d=o[r];return 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(mn,{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:DE[h]?u.jsx("img",{src:`/tutorial/${DE[h]}-${a}.gif`,loading:"lazy",alt:"",className:"w-full h-full object-cover"}):_re[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(Lf,{size:16,strokeWidth:1.75})}),u.jsx("div",{className:"flex items-center gap-2",children:o.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}/${o.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(Fi,{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 Ire=new URLSearchParams(window.location.search),Pi=Ire.get("dv"),uf="https://chenxiachan.github.io/thoughtdag/docs",E9=[{version:"0.4.12",date:"2026-09-10",announce:!1,lead:{zh:"DeepSeek Harness 插件里,Agent 子节点现在续接父节点的会话;同一父节点下的第二个分支从父节点那一轮分叉出自己的会话,preset 的会话状态不再在每个子节点重头开始(#28、#29)。插件的构建脚本在 Windows 上也能跑了(#24、#26)。桌面版本次只同步版本号。",en:"Inside the DeepSeek Harness plugin, an agent child node now continues its parent's session, and a second branch off the same parent forks its own session at that parent's turn, so a preset's session state no longer restarts at every child (#28, #29). The plugin's build script runs on Windows too (#24, #26). The desktop app only moves its version number."},items:[]},{version:"0.4.11",date:"2026-09-08",announce:!1,lead:{zh:"性能优化:启动更快,后台更省,多个工具调用并行时更稳;300 节点以上的画布实测流畅。ThoughtDAG 现在可以用 Claude Code、Codex、Pi 作为节点的 Agent 运行时,处于测试阶段。",en:"Performance: faster launch, lighter in the background, steadier when several tool calls run in parallel; canvases past 300 nodes measured smooth. ThoughtDAG can now run a node through Claude Code, Codex or Pi as its agent runtime, in testing."},items:[]},{version:"0.4.10",date:"2026-09-07",announce:!1,lead:{zh:"Agent 执行预览继续:Codex 加入,和 Pi 一样在画布里带工具作答;这条通道现在在桌面版、本地网页版和 DeepSeek Harness 插件里都可用;插件里的 Harness Agent 按模型平铺;插件有新版本时画布会提示。",en:"Agent runs, preview continued: Codex joins Pi, answering with tools right from the canvas; the lane now works in the desktop app, the local web app and the DeepSeek Harness plugin alike; inside the plugin the Harness agent lists one entry per model; the canvas tells you when a newer plugin is out."},items:[]},{version:"0.4.9",date:"2026-09-07",announce:!1,lead:{zh:"Agent 执行预览:桌面版的模型选择器多了「Agent 执行」组,装了 Pi 的话可以直接在画布里让它带工具作答,轨迹、足迹、审批和提问都落在节点上,工作目录在顶栏可见可改。正式版会连同 Claude Code 与 Codex 一起发布。DeepSeek Harness 插件里的审批卡片同步更新。",en:'Agent runs, preview: the desktop picker gains an "Agent runs" group; with Pi installed, a question runs through it with tools right from the canvas, and the trace, footprints, approvals and questions land on the node, with the working directory visible on the toolbar. The full release will arrive together with Claude Code and Codex. The approval card inside the DeepSeek Harness plugin is updated alike.'},items:[]},{version:"0.4.8",date:"2026-09-07",announce:!1,lead:{zh:"DeepSeek Harness 插件在 Windows 上能打开了:静态资源和会话目录的路径守卫此前只认正斜杠,Windows 用户看到的是一片 403。感谢 GitHub 上的报告(#23)。桌面版本次只同步版本号。",en:"The DeepSeek Harness plugin now opens on Windows: the path guards for static assets and session directories only accepted forward slashes, so Windows users saw nothing but 403s. Thanks to the report on GitHub (#23). The desktop app only moves its version number this time."},items:[]},{version:"0.4.7",date:"2026-09-07",announce:!1,lead:{zh:"DeepSeek Harness 插件里,Agent 需要你批准的操作现在直接出现在节点上:工具、命令、理由,允许一次或拒绝,决定留在节点记录里。桌面版本次只同步版本号。",en:"Inside the DeepSeek Harness plugin, an action the agent needs approved now appears on the node itself: tool, command, reason, allow once or reject, and the decision stays in the node's record. The desktop app only moves its version number this time."},items:[]},{version:"0.4.6",date:"2026-09-06",announce:!0,lead:{zh:"🎉 Pi 的会话进了对话地图,「⋯」菜单里多了更新历史,随时能回看每一版改了什么。",en:"🎉 Pi sessions join the Session Atlas, and the ⋯ menu gains a release history, so what every version changed is one click away."},items:[{title:{zh:"Pi 的会话也在地图上了",en:"Pi sessions are on the map"},body:{zh:"本地 Pi 会话按项目聚在一起,打开就是一张图。Pi 里的每次分叉在图上就是一条支线,不再压成一条直线。命令行 why 和 MCP 也同步认识 Pi 留下的文件足迹。",en:"Local Pi sessions group by project and open as a graph. Every fork you made in Pi shows up as a branch instead of being flattened into one line. The why command and MCP index Pi's file footprints too."},link:{label:{zh:"怎么用",en:"How it works"},href:`${uf}/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:`${uf}/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:`${uf}/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:`${uf}/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 Eb(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 bx(e,t){return E9.filter(n=>n.announce&&Eb(n.version,t)<=0&&(e===null||Eb(n.version,e)>0))}const Sb="thoughtdag.whatsNewSeen",Dre=new URLSearchParams(window.location.search);function Ore(){if(!Pi)return[];if(Dre.get("wn")==="1")return bx(null,Pi);let t=null;try{t=localStorage.getItem(Sb)}catch{}if(t===null){let n=!1;try{n=!!(localStorage.getItem("thoughtdag.tutorialDone")||localStorage.getItem("thoughtdag.lastBackupAt"))}catch{}if(!n){try{localStorage.setItem(Sb,Pi)}catch{}return[]}return bx(null,Pi)}return t===Pi?[]:bx(t,Pi)}function S9({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 Rre(){const[e,t]=L.useState(()=>Ore()),n=e.length>0,a=Ra(c=>c.lang),r=jt(),s=L.useRef(null),o=()=>{if(Pi)try{localStorage.setItem(Sb,Pi)}catch{}t([])};return L.useEffect(()=>{if(!n)return;s.current?.focus({preventScroll:!0});const c=d=>{d.stopPropagation(),(d.key==="Escape"||d.key==="Enter")&&o()};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:o,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:He(r("whatsNew.title"),{v:Pi??""})}),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(S9,{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:()=>{o(),pe.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:o,className:"text-xs text-white px-4 py-2 rounded-lg bg-accent hover:bg-accent-strong transition-colors",children:r("whatsNew.ok")})]})]})}):null}function Lre(){const e=pe(r=>r.releaseNotesOpen),t=pe(r=>r.setReleaseNotesOpen),n=Ra(r=>r.lang),a=jt();return L.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:E9.map(r=>{const s=Pi===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(S9,{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 yx=e=>e.split("/").filter(Boolean).slice(-1)[0]??e;function jre(){const e=jt(),t=pe(D=>D.selectedModel),n=rn(D=>D.activeId),a=rn(D=>D.projects),r=oe(D=>D.nodes.length),[s,o]=L.useState(null),[c,d]=L.useState(null),[h,m]=L.useState(!1),[p,x]=L.useState(""),b=L.useRef(null),y=!!window.desktopAgents&&Fd(t);if(L.useEffect(()=>{if(!y)return;let D=!0;return r2().then(O=>{D&&o(O)}),NU().then(O=>{D&&d(O)}),()=>{D=!1}},[y,n,a,r]),L.useEffect(()=>{if(!h)return;const D=M=>{b.current&&!b.current.contains(M.target)&&m(!1)},O=M=>{M.key==="Escape"&&m(!1)};return document.addEventListener("mousedown",D),document.addEventListener("keydown",O),()=>{document.removeEventListener("mousedown",D),document.removeEventListener("keydown",O)}},[h]),!y||!s)return null;const k=a.find(D=>D.id===n),S=[...new Set(a.map(D=>D.agentCwd).filter(D=>!!D))].filter(D=>D!==k?.agentCwd).slice(0,5),w=async D=>{n&&(await c2(n,D),m(!1))},C=window.desktopAgents?.capabilities?.nativePicker!==!1,T=async()=>{const D=await window.desktopAgents.pickCwd();D&&await w(D)},N=async()=>{const D=p.trim();D.startsWith("/")&&await w(D)};return u.jsxs("div",{ref:b,className:"relative",children:[u.jsxs("button",{onClick:D=>{D.stopPropagation(),m(O=>!O)},className:"bg-card/90 backdrop-blur border border-line rounded-lg h-8 px-2.5 flex items-center gap-1.5 shadow-sm hover:bg-wash transition-colors text-xs text-ink max-w-[220px]",title:`${e("agent.cwd")} · ${s.cwd}`,"data-agent-cwd":s.kind,children:[u.jsx(Pc,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),u.jsx("span",{className:"truncate",children:s.kind==="workspace"?e("agent.cwdWorkspace"):yx(s.cwd)}),u.jsx(Cl,{size:12,strokeWidth:1.75,className:"text-ink-faint shrink-0"})]}),h&&u.jsxs("div",{className:"absolute right-0 top-full mt-1.5 w-[320px] bg-card border border-line rounded-xl shadow-lg py-1.5 z-50 animate-fade-in",onClick:D=>D.stopPropagation(),children:[u.jsx("p",{className:"text-2xs text-ink-faint uppercase tracking-wider font-medium px-3 pt-1 pb-1",children:e("agent.cwd")}),u.jsxs("button",{onClick:()=>{w(void 0)},className:"w-full text-left px-3 py-2 text-xs hover:bg-wash flex items-center gap-2",children:[u.jsxs("span",{className:"flex-1 min-w-0",children:[u.jsx("span",{className:"block text-ink",children:e(c?"agent.cwdMirrored":"agent.cwdWorkspace")}),u.jsx("span",{className:"block text-2xs text-ink-faint truncate",children:c??e("agent.cwdWorkspaceHint")})]}),!k?.agentCwd&&u.jsx(ii,{size:13,strokeWidth:2,className:"shrink-0 text-accent"})]}),k?.agentCwd&&u.jsxs("button",{onClick:()=>{w(k.agentCwd)},className:"w-full text-left px-3 py-2 text-xs hover:bg-wash flex items-center gap-2",children:[u.jsxs("span",{className:"flex-1 min-w-0",children:[u.jsx("span",{className:"block text-ink",children:yx(k.agentCwd)}),u.jsx("span",{className:"block text-2xs text-ink-faint truncate",children:k.agentCwd})]}),u.jsx(ii,{size:13,strokeWidth:2,className:"shrink-0 text-accent"})]}),S.length>0&&u.jsx("p",{className:"text-2xs text-ink-faint uppercase tracking-wider font-medium px-3 pt-2 pb-1",children:e("agent.cwdRecent")}),S.map(D=>u.jsx("button",{onClick:()=>{w(D)},className:"w-full text-left px-3 py-1.5 text-xs hover:bg-wash flex items-center gap-2",children:u.jsxs("span",{className:"flex-1 min-w-0",children:[u.jsx("span",{className:"block text-ink",children:yx(D)}),u.jsx("span",{className:"block text-2xs text-ink-faint truncate",children:D})]})},D)),u.jsx("div",{className:"border-t border-line/60 my-1"}),C?u.jsxs("button",{onClick:()=>{T()},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash flex items-center gap-2","data-agent-cwd-pick":!0,children:[u.jsx(Pc,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",e("agent.cwdPick")]}):u.jsxs("div",{className:"px-3 py-2 flex items-center gap-2",children:[u.jsx("input",{value:p,onChange:D=>x(D.target.value),onKeyDown:D=>{D.stopPropagation(),D.key==="Enter"&&N()},placeholder:e("agent.cwdType"),className:"flex-1 min-w-0 text-xs font-mono bg-wash border border-line rounded-md px-2 py-1 focus:outline-none focus:border-accent/60","data-agent-cwd-input":!0}),u.jsx("button",{onClick:()=>{N()},className:"text-xs text-accent hover:underline shrink-0",children:e("agent.cwdUse")})]}),u.jsx("div",{className:"border-t border-line/60 my-1"}),u.jsx("p",{className:"text-2xs text-ink-faint uppercase tracking-wider font-medium px-3 pt-1 pb-1",children:e("agent.guard")}),u.jsxs("button",{onClick:()=>{F5("ask"),m(!1)},className:"w-full text-left px-3 py-1.5 text-xs hover:bg-wash flex items-center gap-2","data-agent-guard":"ask",children:[u.jsx(uB,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),u.jsxs("span",{className:"flex-1 min-w-0",children:[u.jsx("span",{className:"block text-ink",children:e("agent.guardAsk")}),u.jsx("span",{className:"block text-2xs text-ink-faint",children:e("agent.guardAskHint")})]}),(k?.agentGuard?.mode??"ask")==="ask"&&u.jsx(ii,{size:13,strokeWidth:2,className:"shrink-0 text-accent"})]}),u.jsxs("button",{onClick:()=>{F5("allow"),m(!1)},className:"w-full text-left px-3 py-1.5 text-xs hover:bg-wash flex items-center gap-2","data-agent-guard":"allow",children:[u.jsx(hB,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),u.jsxs("span",{className:"flex-1 min-w-0",children:[u.jsx("span",{className:"block text-ink",children:e("agent.guardAllow")}),u.jsx("span",{className:"block text-2xs text-ink-faint",children:e("agent.guardAllowHint")})]}),k?.agentGuard?.mode==="allow"&&u.jsx(ii,{size:13,strokeWidth:2,className:"shrink-0 text-accent"})]}),(k?.agentGuard?.allow?.length??0)>0&&u.jsxs(u.Fragment,{children:[u.jsx("p",{className:"text-2xs text-ink-faint px-3 pt-2 pb-1",children:e("agent.guardAllowed")}),k.agentGuard.allow.map(D=>u.jsxs("div",{className:"px-3 py-1 text-xs flex items-center gap-2 min-w-0","data-agent-guard-allowed":D,children:[u.jsx("span",{className:"flex-1 min-w-0 truncate text-ink-muted font-mono",title:D,children:D}),u.jsx("button",{onClick:()=>{g7(D,!0)},className:"text-ink-faint hover:text-red-500 shrink-0",title:e("agent.guardRemove"),children:u.jsx(mn,{size:12,strokeWidth:2})})]},D))]})]})]})}const OE="thoughtdag.pluginUpdateNotified",Tb="dsh plugin --profile web update dsh-thoughtdag";async function Pre(e){try{const t=await fetch(e.replace(/\/+$/,"")+"/version",{credentials:"same-origin"});if(!t.ok)return;const n=await t.json();if(!n.version||!n.latest||Eb(n.latest,n.version)<=0)return;pe.getState().setPluginUpdate({current:n.version,latest:n.latest});let a=null;try{a=localStorage.getItem(OE)}catch{}if(a!==n.latest){try{localStorage.setItem(OE,n.latest)}catch{}Ye("info",He(De("plugin.updateAvailable"),{v:n.latest}),9e3)}}catch{}}const zre=Object.freeze(Object.defineProperty({__proto__:null,PLUGIN_UPDATE_COMMAND:Tb,bootPluginUpdateCheck:Pre},Symbol.toStringTag,{value:"Module"})),Bre={ruleout:"#ef4444",decision:"#6B5CE7",pivot:"#e8890c",open:"#d97706",insight:"#0284c7"},RE=e=>{if(e){for(let t=e.length-1;t>=0;t--)if(e[t])return e[t]}};function Hre(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(`
782
782
  `)[0].replace(/^#+\s*/,"")||void 0}function dy(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,o=[r.askedAt,RE(r.generatedAts),RE(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=o?Date.parse(o):NaN;return{entry:{id:n.id,label:(d||Hre(r)||r.question||"").slice(0,120),topic:h,badged:!!c&&c!=="insight",type:c??void 0,createdAt:s,modifiedAt:o,color:c&&Bre[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 Ure=e=>e?24:16,Fre=(e,t,n)=>{const a=Ure(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 qre(){const e=l0(),t=oe(N=>N.nodes),n=oe(N=>N.setSelectedNodeId),a=pe(N=>N.setTimelineOverviewOpen),r=Nl(),s=jt(),o=FS(),[c,d]=L.useState(null),[h,m]=L.useState(()=>Date.now());L.useEffect(()=>{const N=setInterval(()=>m(Date.now()),6e4);return()=>clearInterval(N)},[]);const p=un(N=>N.transform),x=un(N=>N.width),b=un(N=>N.height),y=L.useMemo(()=>dy(t,h),[t,h]),k=L.useMemo(()=>{const[N,D,O]=p,M=-N/O,_=-D/O,R=(x-N)/O,G=(b-D)/O,B=new Set;for(const $ of y)$.x+520>M&&$.x<R&&$.y+220>_&&$.y<G&&B.add($.id);return B},[y,p,x,b]);if(e==="work"||y.length<2)return null;const S=N=>N?N.slice(0,10):"",w=N=>N.slice(5).replace("-","/"),C=N=>N?new Date(N).toLocaleString(o):"",T=c?y.find(N=>N.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:[T&&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:[T.topic&&u.jsxs("span",{className:"text-accent",children:[T.topic," · "]}),T.label||"…"]}),T.createdAt&&u.jsxs("div",{className:"text-ink-faint mt-0.5",children:[s("timeline.created")," ",C(T.createdAt)]}),T.modifiedAt&&T.modifiedAt!==T.createdAt&&u.jsxs("div",{className:"text-ink-faint",children:[s("timeline.modified")," ",C(T.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(Wb,{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((N,D)=>{const O=D>0?S(y[D-1].createdAt):"",M=S(N.createdAt),_=M!==""&&M!==O;return u.jsxs("button",{"data-timeline-dot":N.id,onMouseEnter:R=>d({id:N.id,idx:D,y:R.currentTarget.getBoundingClientRect().top}),onMouseLeave:()=>d(R=>R?.id===N.id?null:R),onClick:()=>{n(N.id);const R=r.getViewport().zoom;r.setCenter(N.x+260+sm(N.id)/(2*R),N.y+110,{zoom:R,duration:300})},onDoubleClick:()=>{n(N.id),r.setCenter(N.x+260+sm(N.id)/2,N.y+110,{zoom:1,duration:350})},className:"relative flex items-center w-full h-[14px] shrink-0 pl-[29px] cursor-pointer","aria-label":N.label,children:[u.jsx("span",{className:`rounded-full ${N.recentlyEdited?"tdag-timeline-pulse":""}`,style:{width:Fre(D,c?.idx??null,N.badged),height:4,background:N.color,opacity:N.archived?.3:k.has(N.id)?1:.45,transition:"width .18s ease, opacity .3s ease"}}),_&&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)})]},N.id)})})})]})}function T9(e){const t=e.filter(a=>!a.data.archived).map(a=>`${a.id}:${Wc(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 Ab=new Map,Wre=(e,t)=>Ab.get(`${t}:${e}`),LE={ruleout:"RULEOUT",decision:"DECISION",pivot:"PIVOT",open:"OPEN",insight:"INSIGHT"};async function Vre(e,t,n){const a=T9(e),r=Ab.get(`${n}:${a}`);if(r)return r;const s=e.find(b=>b.data.isRoot),o=dy(e.filter(b=>!b.data.archived),0),d=o.length>60?o.filter((b,y)=>b.badged||y<10||y>=o.length-10):o,h=o.length-d.length,m=d.map(b=>{const y=e.find(C=>C.id===b.id);if(!y)return null;const k=y.data,S=Wc(k);if(!S)return null;const w=k.summaryTypes?.[k.responseIndex]??void 0;return`- ${w&&LE[w]?`${LE[w]}: `:""}${b.topic?`[${b.topic}] `:""}${S}`}).filter(b=>!!b);h>0&&m.push(`(${h} plain steps omitted from this list)`);const x={text:(await Bo([{role:"user",content:`Opening question of a thinking map: ${s?.data.question?.slice(0,300)??"(untitled)"}
783
783
 
784
784
  The takeaway of every step, in the order they were thought (tags: RULEOUT = killed an option, DECISION = chose, PIVOT = reframed, OPEN = still unresolved):
785
785
  ${m.join(`
786
786
  `)}
787
787
 
788
- 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 Ab.set(`${n}:${a}`,x),x}function Gre({onLocate:e}){const t=pe(D=>D.timelineOverviewOpen),n=pe(D=>D.setTimelineOverviewOpen),a=oe(D=>D.nodes),r=jt(),s=FS(),o=Ra(D=>D.lang),c=L.useMemo(()=>dy(a,0),[a]),d=L.useMemo(()=>T9(a),[a]),[h,m]=L.useState(null),[p,x]=L.useState(!1),[b,y]=L.useState(!1),k=Wre(d,o)??h,S=!!k&&(k.fp!==d||k.lang!==o),w=()=>{x(!0),y(!1);const{nodes:D,edges:O}=oe.getState();Vre(D,O,o).then(m).catch(()=>y(!0)).finally(()=>x(!1))};if(!t)return null;const C=()=>n(!1),T=D=>D?D.slice(0,10):"",N=D=>D?new Date(D).toLocaleTimeString(s,{hour:"2-digit",minute:"2-digit"}):"—";return Za.createPortal(u.jsx("div",{className:"fixed inset-0 z-[60] bg-ink/30 backdrop-blur-sm flex items-center justify-center p-6",onClick:C,children:u.jsxs("div",{className:"bg-card rounded-2xl shadow-2xl border border-line w-[640px] max-h-[80vh] flex flex-col",onClick:D=>D.stopPropagation(),children:[u.jsxs("div",{className:"flex items-center gap-2 px-5 py-3 border-b border-line shrink-0",children:[u.jsx(Wb,{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:He(r("tlov.count"),{n:c.length})}),u.jsx("div",{className:"flex-1"}),u.jsxs("button",{onClick:()=>{C(),pe.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(Vb,{size:13,strokeWidth:1.75}),r("tmap.export")]}),u.jsx("button",{onClick:C,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(mn,{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(zf,{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 ${S?"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:S?r("tlov.gedankenStale"):new Date(k.at).toLocaleString(s)}),S&&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((D,O)=>{const M=O>0?T(c[O-1].createdAt):void 0,_=T(D.createdAt),R=O===0||_!==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:_||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:D.color,opacity:D.archived?.35:1}}),u.jsx("span",{className:"text-2xs font-mono text-ink-faint shrink-0 w-11",children:N(D.createdAt)}),u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsxs("p",{className:`text-sm truncate ${D.archived?"text-ink-faint line-through":D.badged?"text-ink":"text-ink-muted"}`,children:[D.topic&&u.jsxs("span",{className:"font-medium text-accent",children:[D.topic," · "]}),D.label||"…"]}),D.modifiedAt&&D.modifiedAt!==D.createdAt&&u.jsxs("p",{className:"text-2xs text-ink-faint",children:[r("timeline.modified")," ",new Date(D.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:()=>{C(),e(D.id)},title:r("hlov.locateTitle"),children:r("tlov.locate")})]})]},D.id)})]})]})}),document.body)}const $re=L.memo(function(t){const n=rn(a=>a.projects.find(r=>r.id===a.activeId)?.kind==="paradigm");return t.data?.stepKind==="frame"?u.jsx(Cne,{...t}):am(t.data?.stepKind)?u.jsx(Nne,{...t}):n?u.jsx(bne,{...t}):u.jsx(pne,{...t})}),Yre={thought:$re},Kre={smoothstep:L.memo(Ine)};function Xre(){const[e,t]=L.useState(yt||oe.persist.hasHydrated());return L.useEffect(()=>oe.persist.onFinishHydration(()=>t(!0)),[]),L.useEffect(()=>{if(!e||yt)return;let n;const a=()=>{clearTimeout(n),n=setTimeout(()=>{Uae()},800)},r=oe.subscribe((s,o)=>{s.nodes!==o.nodes&&a()});return a(),()=>{r(),clearTimeout(n)}},[e]),L.useEffect(()=>{pe.getState().condenseRun.status==="building"&&pe.getState().setCondenseRun({status:"idle",current:0,total:0,streaming:""})},[]),L.useEffect(()=>{if(yt)return;const n=setTimeout(()=>{Fae()},6e3);return()=>clearTimeout(n)},[]),L.useEffect(()=>{if(!e||yt||localStorage.getItem("thoughtdag.tutorialDone")||oe.getState().nodes.length>0)return;const n=setTimeout(()=>pe.getState().setTutorialOpen(!0),900);return()=>clearTimeout(n)},[e]),L.useEffect(()=>{$ae()},[]),L.useEffect(()=>{yt||(Tt(()=>import("./session-handoff-BLHyTTl7.js"),[]).then(n=>n.consumeSessionHandoff()),Tt(()=>import("./live-mirror-BlUlIINC.js"),[]).then(n=>n.startLiveMirror()),Tt(()=>import("./canvas-record-BYGoWCSi.js"),[]).then(n=>n.startCanvasRecord()),Tt(()=>import("./canonical-Cw94rYnE.js"),[]).then(n=>n.unsubscribeOrphanedSessions()))},[]),L.useEffect(()=>{yt||Gae().then(n=>{n&&(n.status==="minted"?(Ye("success",De("provider.oauthMinted")),x9(n.key)):Ye("error",He(De("provider.oauthFailed"),{error:n.error})))})},[]),u.jsxs(u.Fragment,{children:[e&&u.jsx(Qre,{}),u.jsx(Qae,{}),u.jsx(Jae,{}),u.jsx(nre,{}),u.jsx(are,{}),u.jsx(rre,{}),u.jsx(ire,{}),u.jsx(sre,{}),u.jsx(hre,{}),u.jsx(bre,{}),u.jsx(Yae,{}),u.jsx(Mre,{}),u.jsx(Rre,{}),u.jsx(Lre,{})]})}function Qre(){const{nodes:e,edges:t,setNodes:n,setEdges:a,addQuestion:r,undo:s,redo:o,addCrossLink:c,setSelectedNodeId:d,setSelectedNodeIds:h,history:m,historyIndex:p,relayout:x}=oe(),b=jt(),y=pe(ae=>ae.setTutorialOpen),k=pe(ae=>ae.annotationsHidden),S=pe(ae=>ae.setAnnotationsHidden),[w,C]=L.useState(""),[T,N]=L.useState(!1),[D,O]=L.useState(""),[M,_]=L.useState(!1),[R,G]=L.useState(!1),[B,$]=L.useState([]),[Z,U]=L.useState(!1),q=L.useRef(null),H=L.useRef(null),V=e.length>0,X=oe(ae=>ae.events.length>0),K=oe(ae=>ae.nodes.reduce((be,Ce)=>be+(Ce.data.highlights?.length??0),0)),F=oe(ae=>ae.nodes.reduce((be,Ce)=>be+(Ce.data.attachments?.length??0)+(["note","link"].includes(Ce.data.stepKind??"")?1:0),0)),W=L.useRef(null),ee=pe(ae=>ae.arrivalFocusNodeId);L.useEffect(()=>{if(!ee)return;const ae=oe.getState().nodes.find(be=>be.id===ee);ae&&(pe.getState().setArrivalFocusNodeId(null),window.setTimeout(()=>{W.current?.setCenter(ae.position.x+260,ae.position.y+140,{zoom:.9,duration:400})},150))},[ee]);const P=Ts(ae=>ae.paper),re=Ts(ae=>ae.lighting),fe=Ts(ae=>ae.resolved),ge=L.useMemo(()=>wne(),[fe]),Te=L.useMemo(()=>{const ae=getComputedStyle(document.documentElement),be=(ae.getPropertyValue("--color-surface").trim()||"#FAF9F7").replace("#",""),[Ce,ye,Ue]=[0,2,4].map(tt=>parseInt(be.slice(tt,tt+2),16));return{mask:`rgba(${Ce},${ye},${Ue},0.7)`,archived:ae.getPropertyValue("--color-wash").trim()||"#EFEDE9",ordinary:fe==="dark"?"#6E6759":"#B9B3AB"}},[fe]),ne=L.useRef(e.length),ke=L.useCallback((ae,be={})=>{const Ce=W.current;if(!Ce)return;const ye=be.zoom??Ce.getZoom();Ce.setCenter(ae.position.x+(be.offX??260)+sm(ae.id)/(2*ye),ae.position.y+110,{zoom:ye,duration:be.duration??350})},[]),Ae=Ra(ae=>ae.lang),Le=pe(ae=>ae.condenseRun),qe=Le.status==="building",je=rn(ae=>ae.projects.find(be=>be.id===ae.activeId)?.kind==="paradigm"),et=_l();L.useEffect(()=>{if(yt||!V||oe.getState().nodes.length<10)return;const ae=Number(localStorage.getItem("thoughtdag.lastBackupAt")??0);if(ae===0){localStorage.setItem("thoughtdag.lastBackupAt",String(Date.now()));return}Date.now()-ae<168*3600*1e3||sessionStorage.getItem("thoughtdag.backupNudged")||(sessionStorage.setItem("thoughtdag.backupNudged","yes"),Ye("info",De("backup.nudge"),0,{label:De("backup.nudgeBtn"),run:()=>bf()}))},[V]);const dt=L.useCallback(()=>{const{nodes:ae,edges:be}=Hae(Ae),Ce=oe.getState();Ce.setNodes([...Ce.nodes,...ae.filter(ye=>!Ce.nodes.some(Ue=>Ue.id===ye.id))]),Ce.setEdges([...Ce.edges,...be.filter(ye=>!Ce.edges.some(Ue=>Ue.id===ye.id))]),Ce.pushHistory(),setTimeout(()=>{const ye=W.current;ye&&(ye.fitView({duration:500,padding:.1}),setTimeout(()=>{if(ye.getViewport().zoom<.34){const Ue=[...oe.getState().nodes].sort((tt,rt)=>(tt.data.createdAt??"").localeCompare(rt.data.createdAt??""))[0];Ue&&ye.setCenter(Ue.position.x+300,Ue.position.y+240,{zoom:.6,duration:550})}},680))},100),localStorage.getItem("thoughtdag.tutorialDone")||y(!0)},[Ae,y]),Ke=L.useCallback(ae=>{const be=oe.getState(),Ce=be.nodes[be.nodes.length-1],ye=Ce?{x:Ce.position.x,y:Ce.position.y+340}:{x:120,y:80},Ue=In();be.setNodes([...be.nodes,{id:Ue,type:"thought",position:ye,dragHandle:".drag-handle",data:{question:"",instruction:"",stepKind:ae,response:"",responses:[],responseIndex:-1,isCollapsed:!1,isEditing:!1,isEditingResponse:!1,isLoading:!1,tokenCount:0,highlights:[],highlightMode:"tag",attachments:[],excludedAttachmentIds:[],includedAttachmentIds:[],roleMode:"inherit",isRoot:be.nodes.length===0,isBranch:!1}}]),be.pushHistory()},[]),kt=L.useCallback(()=>{ne.current=oe.getState().nodes.length,setTimeout(()=>W.current?.fitView({duration:300,padding:.2}),50)},[]),bt=L.useRef(null),at=L.useCallback(ae=>{const be=oe.getState(),Ce=In();be.setNodes([...be.nodes,{id:Ce,type:"thought",position:ae,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}}]),be.pushHistory()},[]),Et=L.useCallback(ae=>{const be=[];for(const Ce of Array.from(ae)){const ye=Ce.name.split(".").pop()?.toLowerCase()??"";Ce.type.startsWith("image/")||Ce.type==="application/pdf"||Ce.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(ye)?be.push(Ce):Ye("info",He(De("toast.unsupportedFile"),{name:Ce.name}))}return be},[]),Bt=L.useCallback(ae=>{const be=oe.getState(),Ce=In();return be.setNodes([...be.nodes,{id:Ce,type:"thought",position:ae,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:pe.getState().webSearchEnabled,scholarSearch:pe.getState().scholarSearchEnabled}}]),be.pushHistory(),Ce},[]),Ve=L.useCallback(ae=>{const be=Et(ae);if(be.length===0)return;let Ce=null;be.forEach((ye,Ue)=>{const tt=ti("file",{x:120+Ue%3*480,y:120+Math.floor(Ue/3)*620});Ad(tt,[ye]),!Ce&&!ye.type.startsWith("image/")&&(Ce=tt)}),Ce&&pe.getState().setReaderNodeId(Ce),setTimeout(()=>W.current?.fitView({duration:400,padding:.2}),120)},[Et]),Ht=L.useCallback((ae,be)=>{const Ce=ae.clientX,ye=ae.clientY,Ue=ae.currentTarget;let tt=null;const rt=Ut=>{!tt&&Math.hypot(Ut.clientX-Ce,Ut.clientY-ye)>6&&(tt=document.createElement("div"),tt.innerHTML=Ue.innerHTML,tt.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(tt)),tt&&(tt.style.left=`${Ut.clientX-18}px`,tt.style.top=`${Ut.clientY-18}px`)},vt=Ut=>{window.removeEventListener("pointermove",rt),window.removeEventListener("pointerup",vt);const Wt=!!tt;tt?.remove(),be(Wt?{x:Ut.clientX,y:Ut.clientY}:null)};window.addEventListener("pointermove",rt),window.addEventListener("pointerup",vt)},[]),se=L.useCallback(ae=>{const be=W.current?.screenToFlowPosition(ae??{x:window.innerWidth/2,y:window.innerHeight/2})??{x:140,y:140};return{x:be.x-200,y:be.y-60}},[]);L.useEffect(()=>{const ae=Ce=>{bt.current={x:Ce.clientX,y:Ce.clientY}},be=Ce=>{if(yt)return;const ye=Ce.target;if(ye&&(ye.tagName==="INPUT"||ye.tagName==="TEXTAREA"||ye.isContentEditable))return;const Ue=rn.getState(),tt=Ue.projects.find(Qt=>Qt.id===Ue.activeId)?.kind==="paradigm";if(oe.getState().nodes.length===0&&!tt)return;const rt=Ce.clipboardData;if(!rt)return;const vt=se(bt.current),Ut=rt.getData("text/plain").trim(),Wt=Array.from(rt.files),ia=Wt.some(Qt=>!Qt.type.startsWith("image/"));if(Wt.length>0&&(ia||!Ut)){Ce.preventDefault();const Qt=ti("file",vt);Ad(Qt,Wt);return}if(Ut)if(Ce.preventDefault(),/^https?:\/\/\S+$/.test(Ut)){const Qt=ti("link",vt,{linkUrl:Ut});r9(Qt,Ut)}else ti("note",vt,{question:Ene(Ut)})};return window.addEventListener("mousemove",ae),window.addEventListener("paste",be),()=>{window.removeEventListener("mousemove",ae),window.removeEventListener("paste",be)}},[se]);const Be=L.useCallback(async()=>{const ae=oe.getState();if(ae.nodes.length===0)return;const{nodes:be,edges:Ce}=iF(ae.nodes,ae.edges),ye=rn.getState(),Ue=ye.projects.find(rt=>rt.id===ye.activeId)?.name??"Paradigm",tt=crypto.randomUUID();await Ur(oi(tt),JSON.stringify({state:{nodes:be,edges:Ce},version:1})),await Gc(tt,`▶ ${Ue}`,"chat"),await k7(tt,Ue),ne.current=oe.getState().nodes.length,setTimeout(()=>W.current?.fitView({duration:400,padding:.15}),150)},[]);L.useEffect(()=>{e.length===0&&!je&&!localStorage.getItem("thoughtdag.seeded")&&localStorage.setItem("thoughtdag.seeded","yes")},[]),L.useEffect(()=>{if(e.length>ne.current&&W.current){const ae=e[e.length-1];ae&&setTimeout(()=>ke(ae,{zoom:1,duration:400,offX:220}),100)}ne.current=e.length},[e,ke]);const ve=L.useCallback(ae=>{const be=oe.getState().nodes;n(Y8(ae,be))},[n]),We=L.useCallback(ae=>a(K8(ae,oe.getState().edges)),[a]),ut=L.useRef(null),gt=L.useCallback((ae,be)=>{if(be.data.stepKind!=="frame"||be.data.frameCarry===!1)return;const Ce=oe.getState(),ye=Ce.nodes.find(vt=>vt.id===be.id);if(!ye)return;const Ue=ye.measured?.width??ye.width??0,tt=ye.measured?.height??ye.height??0,rt=Ce.nodes.filter(vt=>{if(vt.id===ye.id||vt.data.stepKind==="frame"||vt.selected)return!1;const Ut=vt.position.x+(vt.measured?.width??520)/2,Wt=vt.position.y+(vt.measured?.height??120)/2;return Ut>=ye.position.x&&Ut<=ye.position.x+Ue&&Wt>=ye.position.y&&Wt<=ye.position.y+tt}).map(vt=>({id:vt.id,start:vt.position}));rt.length!==0&&(ut.current={frameId:ye.id,start:ye.position,members:rt})},[]),At=L.useCallback((ae,be)=>{const Ce=ut.current;if(!Ce||be.id!==Ce.frameId)return;const ye=be.position.x-Ce.start.x,Ue=be.position.y-Ce.start.y,tt=new Map(Ce.members.map(rt=>[rt.id,{x:rt.start.x+ye,y:rt.start.y+Ue}]));oe.setState(rt=>({nodes:rt.nodes.map(vt=>{const Ut=tt.get(vt.id);return Ut?{...vt,position:Ut}:vt})}))},[]),qt=L.useCallback(()=>{ut.current=null},[]),[hn,wn]=L.useState(null),[Kt,kn]=L.useState(null),sn=L.useCallback((ae,be)=>{yt||window.getSelection()?.toString()||(ae.preventDefault(),kn({x:ae.clientX,y:ae.clientY,nodeId:be.id}))},[]),ka=L.useCallback((ae,be)=>{ae.preventDefault(),wn({x:ae.clientX,y:ae.clientY,edgeId:be.id})},[]);L.useEffect(()=>{if(!hn)return;const ae=()=>wn(null);return window.addEventListener("click",ae),()=>window.removeEventListener("click",ae)},[hn]);const Fn=oe(ae=>ae.deleteEdges),dr=L.useCallback(ae=>{Fn([ae]),wn(null)},[Fn]),tr=L.useCallback(ae=>{ae.source&&ae.target&&c(ae.source,ae.target)},[c]),Qn=L.useCallback(()=>{window.getSelection()?.removeAllRanges(),document.body.classList.add("tdag-connecting")},[]),Ba=L.useCallback((ae,be)=>{if(document.body.classList.remove("tdag-connecting"),je||be.isValid||be.fromHandle?.type!=="source"||!be.fromNode)return;const Ce=be.fromNode.id,ye=ae.target?.closest?.(".react-flow__node");if(ye){const Wt=ye.getAttribute("data-id");if(Wt&&Wt!==Ce){const ia=oe.getState().nodes.find(Da=>Da.id===Wt),Qt=ia?.data.stepKind??"";ia&&!["note","file","link","frame"].includes(Qt)&&oe.getState().addCrossLink(Ce,Wt)}return}const{clientX:Ue,clientY:tt}="changedTouches"in ae?ae.changedTouches[0]:ae,rt=se({x:Ue,y:tt}),vt=oe.getState();if(vt.nodes.find(Wt=>Wt.id===Ce)?.data.stepKind==="frame")return;const Ut=Bt(rt);vt.setEdges([...oe.getState().edges,{id:`edge-${Ce}-${Ut}`,source:Ce,target:Ut,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()},[je,se,Bt]),Jt=oe(ae=>ae.selectedNodeId),ce=oe(ae=>ae.selectedNodeIds),ze=pe(ae=>ae.panelOpen),ht=pe(ae=>ae.viewerLoadError),It=oe(ae=>ae.staleIds.length),En=pe(ae=>ae.panelWidth),on=e.find(ae=>ae.id===Jt)?.data.stepKind,xt=am(on)||on==="frame",ft=ze&&!!Jt&&!je&&!xt,Rt=ce.length>1,On=oe(ae=>ae.batchDelete);L.useEffect(()=>{const ae=be=>{if(!pe.getState().confirmRequest&&!(yt&&!((be.metaKey||be.ctrlKey)&&be.key==="f"))){if((be.metaKey||be.ctrlKey)&&be.key==="z"&&(be.shiftKey?(be.preventDefault(),o()):(be.preventDefault(),s())),(be.metaKey||be.ctrlKey)&&be.key==="f"){be.preventDefault(),N(!0);return}{const Ce=be.target;if(!(Ce.tagName==="INPUT"||Ce.tagName==="TEXTAREA"||Ce.isContentEditable)&&Jt&&!je&&!be.metaKey&&!be.ctrlKey&&!be.altKey){const{nodes:Ue,edges:tt}=oe.getState();if(be.key===" "){be.preventDefault(),oe.getState().toggleCollapse(Jt);return}if(be.key==="r"||be.key==="R"){be.preventDefault(),oe.getState().rerunNode(Jt,{});return}if(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(be.key)){const rt=tt.filter(Ut=>!Ut.data?.isCrossLink);let vt;if(be.key==="ArrowUp")vt=rt.find(Ut=>Ut.target===Jt)?.source;else if(be.key==="ArrowDown")vt=rt.find(Ut=>Ut.source===Jt)?.target;else{const Ut=rt.find(Qt=>Qt.target===Jt),Wt=Ut?rt.filter(Qt=>Qt.source===Ut.source).map(Qt=>Qt.target):Ue.filter(Qt=>!rt.some(Da=>Da.target===Qt.id)).map(Qt=>Qt.id),ia=Wt.indexOf(Jt);ia!==-1&&Wt.length>1&&(vt=Wt[(ia+(be.key==="ArrowRight"?1:Wt.length-1))%Wt.length])}if(vt){be.preventDefault(),d(vt);const Ut=Ue.find(Wt=>Wt.id===vt);Ut&&ke(Ut,{zoom:1,duration:300})}return}}}if(be.key==="Escape"){const Ce=be.target;if(Ce.tagName==="INPUT"||Ce.tagName==="TEXTAREA"||Ce.isContentEditable)return;ce.length>1?h([]):Jt&&d(null);return}if(be.key==="Delete"||be.key==="Backspace"){const Ce=be.target;if(Ce.tagName==="INPUT"||Ce.tagName==="TEXTAREA"||Ce.isContentEditable)return;if(ce.length>1)be.preventDefault(),Cs({title:De("confirm.deleteNodesTitle"),message:He(De("confirm.deleteNodes"),{n:ce.length}),confirmLabel:De("common.delete"),danger:!0}).then(ye=>{ye&&On(ce)});else{const ye=t.filter(Ue=>Ue.selected).map(Ue=>Ue.id);ye.length>0&&(be.preventDefault(),Fn(ye))}}}};return window.addEventListener("keydown",ae),()=>window.removeEventListener("keydown",ae)},[s,o,Jt,ce,d,h,On,t,Fn,je,ke]);const Mn=()=>{w.trim()&&(r(w.trim(),{rolePrompt:D.trim()||void 0,initialAttachments:B.length>0?B:void 0}),C(""),O(""),_(!1),$([]))},xe=async ae=>{for(const be of Array.from(ae))await o0(be,{add:Ce=>$(ye=>[...ye,Ce]),update:(Ce,ye)=>$(Ue=>Ue.map(tt=>tt.id===Ce?{...tt,...ye}:tt))})},Xe=ae=>{ae.key==="Enter"&&!ae.shiftKey&&!Qa(ae)&&(ae.preventDefault(),Mn())},Nt=L.useCallback(({nodes:ae})=>{const be=ae.map(Ce=>Ce.id);be.length>1?h(be):be.length===1&&d(be[0])},[d,h]),Ct=L.useMemo(()=>e.filter(ae=>ae.data.stepKind==="frame"),[e]),[ot,Lt]=L.useState(!1),en=L.useRef(null);L.useEffect(()=>{if(!ot)return;const ae=be=>{en.current?.contains(be.target)||Lt(!1)};return window.addEventListener("mousedown",ae),()=>window.removeEventListener("mousedown",ae)},[ot]);const[Xt,xn]=L.useState(!1),de=pe(ae=>ae.pluginUpdate),[Pt,fn]=L.useState(0),Cn=pe(ae=>ae.searchHitIds!==null),Sn=L.useRef(null);L.useEffect(()=>{if(!Xt)return;const ae=be=>{Sn.current?.contains(be.target)||xn(!1)};return window.addEventListener("mousedown",ae),()=>window.removeEventListener("mousedown",ae)},[Xt]);const ea=pe(ae=>ae.searchHitIds),xa=L.useMemo(()=>{if(!Jt||ce.length>1||!e.some(rt=>rt.id===Jt))return null;const ae=Em(Jt,e,t),be=new Set;for(const rt of ae.mainline)rt.id!==Jt&&be.add(rt.id);for(const rt of ae.materials)be.add(rt.id);for(const rt of ae.references)be.add(rt.source.id);const Ce=t.filter(rt=>!rt.data?.isCrossLink),ye=Fr(Jt,e,Ce).visitedEdgeIds,Ue=new Set(ae.references.map(rt=>rt.edge.id)),tt=Ce.filter(rt=>rt.source===Jt);return{ctx:be,down:new Set(tt.map(rt=>rt.target)),pathEdgeIds:ye,refEdgeIds:Ue,downEdgeIds:new Set(tt.map(rt=>rt.id))}},[Jt,ce,e,t]),Vr=L.useMemo(()=>{let ae=e;return k&&(ae=ae.map(be=>{const Ce=be.data.stepKind,ye=am(Ce)&&!t.some(Ue=>Ue.source===be.id||Ue.target===be.id);return Ce==="frame"||ye?{...be,hidden:!0}:be})),ea!==null&&(ae=ae.map(be=>ea.has(be.id)||be.data.stepKind==="frame"?{...be,className:"search-hit"}:be.className==="search-hit"?{...be,className:void 0}:be)),xa&&(ae=ae.map(be=>{const Ce=be.id===Jt?"target":xa.ctx.has(be.id)?"ctx":xa.down.has(be.id)?"down":be.data.stepKind==="frame"?void 0:"dim";return Ce?{...be,className:[be.className,`focus-${Ce}`].filter(Boolean).join(" "),...Ce!=="dim"?{data:{...be.data,focusRole:Ce}}:{}}:be})),ae},[e,t,k,ea,xa,Jt]),ra=L.useMemo(()=>{const ae=t.map(ye=>{const Ue=ye.data?.isBranchFromSelection?{...ye,animated:!1,style:{...ye.style,strokeDasharray:void 0}}:ye,tt=typeof Ue.style?.stroke=="string"?sE[Ue.style.stroke.toUpperCase()]:void 0,rt=Ue.markerEnd&&typeof Ue.markerEnd=="object"?Ue.markerEnd:void 0,vt=typeof rt?.color=="string"?sE[rt.color.toUpperCase()]:void 0;return!tt&&!vt?Ue:{...Ue,...tt?{style:{...Ue.style,stroke:ge[tt]}}:{},...vt&&rt?{markerEnd:{...rt,color:ge[vt]}}:{}}});if(xa)return ae.map(ye=>xa.pathEdgeIds.has(ye.id)?{...ye,className:"focus-e-path",style:{...ye.style,stroke:ge.accent,strokeWidth:3.5,opacity:1},markerEnd:{type:"arrowclosed",...ye.markerEnd&&typeof ye.markerEnd=="object"?ye.markerEnd:{},color:ge.accent},zIndex:10,data:{...ye.data,focusRole:"path"}}:xa.refEdgeIds.has(ye.id)?{...ye,style:{...ye.style,opacity:.9},zIndex:5,data:{...ye.data,focusRole:"ref"}}:xa.downEdgeIds.has(ye.id)?{...ye,className:"focus-e-down",style:{...ye.style,strokeWidth:2.5,opacity:.85},markerEnd:{type:"arrowclosed",...ye.markerEnd&&typeof ye.markerEnd=="object"?ye.markerEnd:{}},zIndex:5,data:{...ye.data,focusRole:"down"}}:{...ye,style:{...ye.style,strokeWidth:1.5,opacity:.2},zIndex:0});const be=ce.length>1?ce:[];if(be.length===0)return ae;const{visitedEdgeIds:Ce}=Fr(be,e,t);return ae.map(ye=>Ce.has(ye.id)?{...ye,style:{...ye.style,stroke:ge.trace,strokeWidth:3.5,opacity:1},markerEnd:{type:"arrowclosed",...ye.markerEnd&&typeof ye.markerEnd=="object"?ye.markerEnd:{},color:ge.trace},zIndex:10}:{...ye,style:{...ye.style,strokeWidth:1.5,opacity:.2},zIndex:0})},[e,t,ce,ge,xa]);return L.useEffect(()=>{if(!ft||!Jt)return;const ae=setTimeout(()=>{const be=W.current;if(!be)return;const Ce=oe.getState().nodes.find(vt=>vt.id===Jt);if(!Ce)return;const ye=be.getViewport(),Ue=Ce.measured?.width??Ce.width??480,tt=(Ce.position.x+Ue)*ye.zoom+ye.x,rt=window.innerWidth-pe.getState().panelWidth-pd-24;if(tt>rt){const vt=(Ce.position.x+Ue/2)*ye.zoom+ye.x;be.setViewport({...ye,x:ye.x-(vt-rt/2)},{duration:300})}},60);return()=>clearTimeout(ae)},[ft,Jt]),u.jsxs("div",{className:"relative w-full h-full","data-searching":Cn||void 0,children:[u.jsxs("div",{className:"relative h-full w-full",onDoubleClick:ae=>{ae.target.classList.contains("react-flow__pane")&&!je&&Bt(se({x:ae.clientX,y:ae.clientY}))},onDragOver:ae=>{(ae.dataTransfer.types.includes("application/thoughtdag-content")||ae.dataTransfer.types.includes("Files"))&&(ae.preventDefault(),ae.dataTransfer.dropEffect="copy",!V&&!je&&U(!0))},onDrop:ae=>{if(yt)return;const be=ae.target;if(!V&&!je&&ae.dataTransfer.files.length>0){ae.preventDefault(),U(!1),Ve(ae.dataTransfer.files);return}const Ce=be.closest?.(".react-flow__node"),ye=Ce&&oe.getState().nodes.find(rt=>rt.id===Ce.getAttribute("data-id"))?.data.stepKind==="frame";if(!be.classList?.contains("react-flow__pane")&&!ye)return;const Ue=se({x:ae.clientX,y:ae.clientY}),tt=ae.dataTransfer.getData("application/thoughtdag-content");if(tt==="ask"){ae.preventDefault(),Bt(Ue);return}if(tt==="frame"){ae.preventDefault(),at(Ue);return}if(tt==="note"||tt==="file"){ae.preventDefault(),ti(tt,Ue);return}if(ae.dataTransfer.files.length>0){ae.preventDefault();const rt=Et(ae.dataTransfer.files);if(rt.length===0)return;const vt=ti("file",Ue);Ad(vt,rt)}},children:[u.jsxs(xj,{onInit:ae=>{W.current=ae,o9.current=ae;const be=pe.getState().arrivalFocusNodeId;if(be){pe.getState().setArrivalFocusNodeId(null);const Ce=oe.getState().nodes.find(ye=>ye.id===be);Ce&&window.setTimeout(()=>{ae.setCenter(Ce.position.x+260,Ce.position.y+140,{zoom:.9,duration:400})},150)}},nodes:Vr,edges:ra,onNodesChange:ve,onEdgesChange:We,onNodeDragStart:gt,onNodeDrag:At,onNodeDragStop:qt,onConnect:tr,onConnectStart:Qn,onConnectEnd:Ba,onEdgeContextMenu:ka,onNodeContextMenu:sn,nodeTypes:Yre,edgeTypes:Kre,deleteKeyCode:null,fitView:!0,onlyRenderVisibleElements:!0,minZoom:.04,maxZoom:2,defaultEdgeOptions:{type:"smoothstep",animated:!1,style:{stroke:ge.accent,strokeWidth:2},markerEnd:{type:"arrowclosed",color:ge.accent,width:18,height:18}},snapToGrid:P==="grid",snapGrid:[22,22],proOptions:{hideAttribution:!0},nodeDragThreshold:5,connectionRadius:40,selectionMode:Oc.Partial,selectionOnDrag:!yt,nodesDraggable:!yt,nodesConnectable:!yt,panOnDrag:yt?!0:[1,2],zoomOnDoubleClick:!1,connectionLineStyle:{stroke:ge.accent,strokeDasharray:"8 4",strokeWidth:2},onSelectionChange:Nt,onPaneClick:()=>{d(null),h([]),kn(null)},children:[P==="grid"?u.jsxs(u.Fragment,{children:[u.jsx(d1,{id:"grid-fine",variant:yi.Lines,gap:22,color:"var(--canvas-grid-fine)"}),u.jsx(d1,{id:"grid-major",variant:yi.Lines,gap:110,color:"var(--canvas-grid-major)"})]}):u.jsx(d1,{variant:yi.Dots,gap:24,size:1,color:"var(--canvas-dot)"}),u.jsx(Jre,{}),u.jsx(Zre,{panelShiftWidth:ft?En:0}),u.jsx(qre,{}),u.jsx(_j,{position:"bottom-left"}),e.length>0&&u.jsx(Fj,{nodeColor:ae=>{const be=ae.data;if(be.archived)return Te.archived;const Ce=be.stepKind;return Ce==="note"?"#D97706":Ce==="file"||Ce==="link"?"#64748B":Array.isArray(be.condensedFrom)&&be.condensedFrom.length?"#8B7CF0":be.isRoot?ge.accent:be.isBranch?ge.warm:Te.ordinary},maskColor:Te.mask,style:{width:200,height:140},pannable:!0,zoomable:!0,position:"bottom-right"})]}),!V&&je&&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:()=>Ke("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(fd,{size:15,strokeWidth:1.75})," ",b("paradigm.addHuman")]}),u.jsxs("button",{onClick:()=>Ke("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(Oo,{size:15,strokeWidth:1.75})," ",b("paradigm.addPrompt")]})]})]})}),yt&&!V&&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:ht?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(Un,{size:16,strokeWidth:1.75,className:"animate-spin text-accent"})," ",b("viewer.loading")]})})}),!V&&!je&&!yt&&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:ae=>C(ae.target.value),onKeyDown:Xe,onPaste:ae=>{if(ae.clipboardData.getData("text/plain").trim())return;const be=Array.from(ae.clipboardData.items).filter(Ce=>Ce.kind==="file").map(Ce=>Ce.getAsFile()).filter(Boolean);be.length&&xe(be)},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}),B.length>0&&u.jsx("div",{className:"flex flex-wrap gap-2 mt-2 pb-1",children:B.map(ae=>u.jsxs("div",{className:"flex items-center gap-1.5 bg-wash rounded-lg px-2.5 py-1.5 group",children:[ae.thumbnailUrl?u.jsx("img",{src:ae.thumbnailUrl,className:"w-6 h-6 rounded object-cover",alt:ae.name}):u.jsx("span",{className:"text-xs",children:u.jsx(vi,{size:16,strokeWidth:1.75})}),u.jsx("span",{className:"text-xs text-ink-muted max-w-[100px] truncate",children:ae.name}),ae.isExtracting&&u.jsx("span",{className:"text-2xs text-accent",children:u.jsx(Un,{className:"animate-spin",size:12,strokeWidth:1.75})}),ae.numPages!=null&&u.jsxs("span",{className:"text-2xs text-ink-faint",children:[ae.numPages,"p"]}),u.jsx("button",{onClick:()=>$(be=>be.filter(Ce=>Ce.id!==ae.id)),className:"text-ink-faint hover:text-red-500 text-xs opacity-0 group-hover:opacity-100 transition-opacity",children:u.jsx(mn,{size:14,strokeWidth:1.75})})]},ae.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:()=>{_(!1),O("")},className:"text-xs text-ink-faint hover:text-ink-muted",children:u.jsx(mn,{size:14,strokeWidth:1.75})})]}),u.jsx("textarea",{value:D,onChange:ae=>O(ae.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(i9,{onPick:O})]}),u.jsxs("div",{className:"flex items-center justify-end mt-2 gap-2",children:[u.jsx(f2,{}),u.jsx("button",{onClick:()=>_(!M),title:b("landing.roleTrayTitle"),className:`rounded-full w-8 h-8 flex items-center justify-center transition-colors shrink-0 ${M||D?"text-accent bg-accent/10 hover:bg-accent/20":"text-ink-faint hover:text-ink-muted hover:bg-line"}`,children:u.jsx($P,{size:16,strokeWidth:1.75})}),u.jsx("button",{onClick:()=>q.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(wi,{size:16,strokeWidth:1.75})}),u.jsx("input",{ref:q,type:"file",multiple:!0,accept:Bd,className:"hidden",onChange:ae=>{xe(ae.target.files||[]),ae.target.value=""}}),u.jsx("button",{onClick:Mn,disabled:!w.trim()||B.some(ae=>ae.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:B.some(ae=>ae.isExtracting)?b("landing.extracting"):b("landing.send")})]})]}),u.jsxs("div",{onClick:()=>H.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(Io,{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:()=>G(!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(bP,{size:15,strokeWidth:1.75,className:"text-accent shrink-0"}),u.jsx("span",{children:b("landing.atlasStart")}),u.jsx(hP,{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:H,type:"file",multiple:!0,accept:Bd,className:"hidden",onChange:ae=>{Ve(ae.target.files||[]),ae.target.value=""}}),R&&u.jsx(m9,{onClose:()=>G(!1),onSwitched:()=>{G(!1),kt()}}),(!et||(et.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(Pd,{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:[Ae==="zh"&&u.jsx("button",{onClick:()=>{pe.getState().setApiKeyPresetHint("zhipu"),pe.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:()=>{g9()},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:()=>pe.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:()=>pe.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:qi,title:"landing.feature1.title",desc:"landing.feature1.desc"},{icon:m5,title:"landing.feature2.title",desc:"landing.feature2.desc"},{icon:PS,title:"landing.feature3.title",desc:"landing.feature3.desc"}].map(({icon:ae,title:be,desc:Ce})=>u.jsxs("div",{className:"bg-card/60 backdrop-blur border border-line rounded-xl px-4 py-3.5",children:[u.jsx(ae,{size:16,strokeWidth:1.75,className:"text-accent mb-2"}),u.jsx("h3",{className:"text-xs font-semibold text-ink mb-1",children:b(be)}),u.jsx("p",{className:"text-2xs text-ink-faint leading-relaxed",children:b(Ce)})]},be))}),u.jsxs("div",{className:"text-center mt-6 flex items-center justify-center gap-5",children:[u.jsxs("button",{onClick:dt,className:"text-xs text-accent hover:text-accent-strong font-medium transition-colors inline-flex items-center gap-1.5",children:[u.jsx(m5,{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(c5,{size:14,strokeWidth:1.75})," ",b("landing.howItWorks")]})]})]})]}),!yt&&u.jsx(jae,{onSwitched:kt}),(V||je)&&!yt&&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:[!je&&u.jsx("button",{onClick:()=>Bt(se(null)),draggable:!0,onDragStart:ae=>{ae.dataTransfer.setData("application/thoughtdag-content","ask"),ae.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(fd,{size:17,strokeWidth:1.75})}),u.jsx("button",{onPointerDown:ae=>Ht(ae,be=>ti("note",se(be))),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(Vi,{size:17,strokeWidth:1.75})}),u.jsx("button",{onPointerDown:ae=>Ht(ae,be=>ti("file",se(be))),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(wi,{size:17,strokeWidth:1.75})}),u.jsx("button",{onPointerDown:ae=>Ht(ae,be=>at(se(be))),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(Lx,{size:17,strokeWidth:1.75})})]}),yt&&u.jsxs("div",{className:"absolute top-4 z-10 flex gap-1.5 items-center transition-[right] duration-200",style:{right:ft?En+pd+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(Ld,{size:14,strokeWidth:1.75})," ",b("viewer.badge")]}),u.jsx("button",{onClick:()=>N(!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(Pf,{size:15,strokeWidth:1.75})}),u.jsx(IE,{}),u.jsx("button",{onClick:()=>bf(),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(Tc,{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")})]}),!yt&&u.jsxs("div",{className:"absolute top-4 z-10 flex gap-1.5 items-center transition-[right] duration-200",style:{right:ft?En+pd+12:16},children:[je&&u.jsxs(u.Fragment,{children:[u.jsxs("button",{onClick:()=>Ke("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(fd,{size:14,strokeWidth:1.75})," ",b("paradigm.addHuman")]}),u.jsxs("button",{onClick:()=>Ke("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(Oo,{size:14,strokeWidth:1.75})," ",b("paradigm.addPrompt")]}),u.jsxs("button",{onClick:()=>{Be()},title:b("paradigm.instantiateTitle"),className:"bg-ink text-white rounded-lg h-8 px-3 flex items-center gap-1.5 shadow-sm hover:bg-ink/85 transition-colors text-xs font-medium",children:["▶ ",b("paradigm.instantiate")]})]}),!je&&u.jsx(jre,{}),!je&&u.jsx(s9,{}),!V&&u.jsx("button",{onClick:()=>pe.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(Pd,{size:15,strokeWidth:1.75})}),It>0&&!je&&u.jsxs("button",{onClick:()=>{const{nodes:ae,edges:be,staleIds:Ce}=oe.getState(),ye=Ce.reduce((Ue,tt)=>{const rt=ae.map(Wt=>Wt.id===tt?{...Wt,data:{...Wt.data,question:"",response:""}}:Wt),{layerTokens:vt}=kr(tt,rt,be),Ut=ae.find(Wt=>Wt.id===tt)?.data.question??"";return Ue+vt.material+vt.reference+vt.chain+$n(Ut)},0);Cs({title:b("replay.confirmTitle"),message:He(b("replay.confirmMsg"),{n:It,tok:ye.toLocaleString()}),confirmLabel:b("replay.confirmBtn")}).then(Ue=>{Ue&&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(Mz,{size:14,strokeWidth:1.75})," ",It]}),V&&Ct.length>0&&u.jsxs("div",{ref:en,className:"relative",children:[u.jsx("button",{onClick:()=>Lt(ae=>!ae),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(Lx,{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:Ct.map(ae=>u.jsxs("button",{onClick:()=>{Lt(!1),W.current?.fitBounds({x:ae.position.x,y:ae.position.y,width:ae.width??640,height:ae.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 ${(md[ae.data.frameColor??"gray"]??md.gray).dot}`}),u.jsx("span",{className:"truncate",children:ae.data.question||b("frame.untitled")})]},ae.id))})]}),V&&u.jsx("button",{onClick:()=>N(!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(Pf,{size:15,strokeWidth:1.75})}),u.jsx(IE,{}),V&&!je&&u.jsx(lae,{showTrigger:!1,openPing:Pt,onLocate:ae=>{const be=oe.getState().nodes.find(Ce=>Ce.id===ae);be&&(d(ae),ke(be,{zoom:1}))}}),qe&&!yt&&u.jsxs("button",{onClick:()=>pe.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:He(b("condense.entryBuilding"),{i:String(Le.current),n:String(Le.total)}),"data-condense-entry":!0,children:[u.jsx(Un,{size:14,strokeWidth:1.75,className:"animate-spin"}),u.jsxs("span",{className:"text-2xs font-mono",children:[Le.current,"/",Le.total]})]}),Vm&&u.jsx("button",{onClick:()=>pe.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(_S,{size:15,strokeWidth:1.75})}),u.jsxs("div",{ref:Sn,className:"relative",children:[u.jsx("button",{onClick:()=>xn(ae=>!ae),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(AS,{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:[V&&u.jsxs("button",{onClick:()=>{xn(!1),S(!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(Vi,{size:14,strokeWidth:1.75,className:`shrink-0 ${k?"text-accent":"text-ink-faint"}`})," ",b(k?"toolbar.menuAnnotationsShow":"toolbar.menuAnnotationsHide")]}),V&&u.jsxs("button",{onClick:()=>{xn(!1),Cs({title:b("confirm.relayoutTitle"),message:b("confirm.relayoutMsg"),confirmLabel:b("toolbar.relayout")}).then(ae=>{ae&&(x(),setTimeout(()=>W.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(Az,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("toolbar.relayout")]}),K>0&&u.jsxs("button",{onClick:()=>{xn(!1),pe.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(jd,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",He(b("hlov.entry"),{n:K})]}),F>0&&u.jsxs("button",{onClick:()=>{xn(!1),pe.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(wi,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",He(b("matov.entry"),{n:F})]}),V&&u.jsx("div",{className:"border-t border-line/60 my-1"}),V&&!je&&!yt&&u.jsxs("button",{onClick:()=>{xn(!1),pe.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(ym,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("condense.title"),"…"]}),V&&!je&&u.jsxs("button",{onClick:()=>{xn(!1),fn(ae=>ae+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(zS,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("toolbar.menuDiagnose")]}),V&&!je&&u.jsxs("button",{onClick:()=>{xn(!1),(async()=>{const{nodes:ae,edges:be}=oe.getState(),{confirmIfSensitive:Ce}=await Tt(async()=>{const{confirmIfSensitive:Ue}=await import("./sensitive-scan-Kz-yplyP.js");return{confirmIfSensitive:Ue}},[]);if(!await Ce(ae))return;const ye=await gH(ae,be);await navigator.clipboard.writeText(ye).catch(()=>{}),pe.getState().setShareDialogUrl(ye)})()},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(sB,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("toolbar.menuShare")]}),V&&u.jsxs("button",{onClick:()=>{xn(!1),je?sF():bf()},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(Tc,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b(je?"paradigm.exportParadigm":"switcher.exportBackup")]}),X&&u.jsxs("button",{onClick:()=>{xn(!1),dF()},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(vi,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("toolbar.exportEvents")]}),V&&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(([ae,be],Ce)=>u.jsx("button",{onClick:()=>Ts.getState().setLighting(ae),className:`flex-1 px-1 py-1.5 transition-colors ${Ce>0?"border-l border-line":""} ${re===ae?"bg-accent/10 text-accent font-medium":"text-ink-muted hover:bg-wash"}`,children:be},ae))})]}),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(([ae,be],Ce)=>u.jsx("button",{onClick:()=>Ts.getState().setPaper(ae),className:`flex-1 px-1 py-1.5 transition-colors ${Ce>0?"border-l border-line":""} ${P===ae?"bg-accent/10 text-accent font-medium":"text-ink-muted hover:bg-wash"}`,children:be},ae))})]}),u.jsx("div",{className:"border-t border-line/60 my-1"}),u.jsxs("button",{onClick:()=>{xn(!1),pe.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(vP,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("memory.managerTitle")]}),u.jsxs("button",{onClick:()=>{xn(!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(c5,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("landing.howItWorks")]}),de&&u.jsxs("button",{onClick:()=>{xn(!1),navigator.clipboard.writeText(Tb).then(()=>Ye("success",b("plugin.updateCopied"),6e3)).catch(()=>{})},className:"w-full text-left px-3 py-2 text-xs text-accent hover:bg-wash transition-colors flex items-center gap-2.5",title:He(b("plugin.updateHint"),{cmd:Tb}),"data-plugin-update":!0,children:[u.jsx(Tc,{size:14,strokeWidth:1.75,className:"shrink-0"})," ",He(b("plugin.updateAvailable"),{v:de.latest})]}),u.jsxs("button",{onClick:()=>{xn(!1),pe.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(Wb,{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(HS,{size:16,strokeWidth:1.75})}),u.jsx("button",{onClick:o,disabled:p>=m.length-1,className:"bg-card/90 backdrop-blur border border-line rounded-lg w-8 h-8 flex items-center justify-center shadow-sm hover:bg-wash transition-colors disabled:opacity-20 disabled:cursor-not-allowed",title:b("canvas.redo"),children:u.jsx(Kz,{size:16,strokeWidth:1.75})})]}),Rt&&!yt&&u.jsx(Kne,{}),u.jsx(sae,{open:T,onClose:()=>N(!1),onLocate:ae=>{const be=oe.getState().nodes.find(Ce=>Ce.id===ae);be&&(d(ae),ke(be,{zoom:1}))}}),Kt&&u.jsx(Qne,{x:Kt.x,y:Kt.y,nodeId:Kt.nodeId,onClose:()=>kn(null)}),u.jsx(eae,{onLocate:ae=>{const be=oe.getState().nodes.find(Ce=>Ce.id===ae);be&&(d(ae),ke(be,{zoom:1}))}}),u.jsx(Gre,{onLocate:ae=>{const be=oe.getState().nodes.find(Ce=>Ce.id===ae);be&&(d(ae),ke(be,{zoom:1}))}}),u.jsx(Zne,{onLocate:ae=>{const be=oe.getState().nodes.find(Ce=>Ce.id===ae);be&&(d(ae),ke(be,{zoom:1}))}}),hn&&u.jsx("div",{className:"fixed z-50 bg-card border border-line rounded-xl shadow-lg py-1 min-w-[120px]",style:{left:hn.x,top:hn.y},children:u.jsxs("button",{onClick:()=>dr(hn.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(Va,{size:14,strokeWidth:1.75}),b("canvas.deleteEdge")]})})]}),u.jsx(Cre,{onFocusSegment:ae=>{const be=W.current,Ce=oe.getState().nodes.filter(Wt=>ae.includes(Wt.id));if(!be||Ce.length===0)return;const ye=Ce.map(Wt=>Wt.position.x),Ue=Ce.map(Wt=>Wt.position.y),tt=Math.min(...ye),rt=Math.min(...Ue),vt=Math.max(...ye)+520-tt,Ut=Math.max(...Ue)+240-rt;be.fitBounds({x:tt,y:rt,width:vt+700,height:Ut},{duration:350,padding:.15})}}),ft&&u.jsx(Yne,{onFocusNode:ae=>{const be=e.find(Ce=>Ce.id===ae);be&&ke(be,{duration:300})}}),u.jsx(yae,{onLocate:ae=>{const be=oe.getState().nodes.find(Ce=>Ce.id===ae);be&&(d(ae),ke(be,{zoom:1}))}})]})}function Zre({panelShiftWidth:e}){const t=l0(),n=jt(),a=Nl(),r=oe(d=>d.nodes.length),s=oe(d=>d.nodes),o=L.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(yt||t==="work"||r<2)return null;const c=()=>{if(!o)return;pe.getState().setBeaconNodeId(null);const{node:d}=o;a.setCenter(d.position.x+260,d.position.y+110,{zoom:1,duration:1100}),window.setTimeout(()=>{oe.getState().setSelectedNodeId(d.id),pe.getState().setPanelOpen(!0),window.setTimeout(()=>{a.setCenter(d.position.x+260+sm(d.id)/2,d.position.y+110,{zoom:1,duration:300})},60)},1150),window.setTimeout(()=>{Ye("success",n("continue.arrived"),12e3,{label:n("continue.summarize"),run:()=>{l9(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:()=>pe.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(Vb,{size:16,strokeWidth:1.75})," ",n("tmap.export")]}),o&&u.jsxs("button",{onClick:c,onMouseEnter:()=>pe.getState().setBeaconNodeId(o.node.id),onMouseLeave:()=>pe.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(Zz,{size:16,strokeWidth:1.75})," ",n("continue.button")]})]})}function Jre(){const e=l0(),t=un(n=>n.transform[2]);return L.useEffect(()=>{document.querySelector(".react-flow")?.setAttribute("data-zoom-tier",e)},[e]),L.useEffect(()=>{document.querySelector(".react-flow")?.style.setProperty("--tdag-zoom",String(t))},[t]),null}vne();const hy="/thoughtdag/api";window.desktopSessions||nU(hy);Tt(()=>Promise.resolve().then(()=>zre),void 0).then(e=>e.bootPluginUpdateCheck(hy));if(!window.desktopAgents){const e=hy;Tt(()=>import("./http-bridge-mmwHcDuo.js"),[]).then(async t=>{await t.installAgentsHttpBridge(e)&&window.dispatchEvent(new CustomEvent("td:agents-ready"))})}yt?bH():(E7(),navigator.storage?.persist&&navigator.storage.persist(),Tt(()=>Promise.resolve().then(()=>xre),void 0).then(e=>e.bootAutoBackup()));Tt(()=>import("./update-check-B1wesdxM.js"),[]).then(e=>e.bootUpdateCheck());window.addEventListener("hashchange",()=>{window.location.hash.startsWith("#view=")!==yt&&window.location.reload()});z_.createRoot(document.getElementById("root")).render(u.jsx(L.StrictMode,{children:u.jsx(Xre,{})}));export{Xd as A,ir as B,WU as C,km as D,D7 as E,nie as F,Hs as G,qr as H,Tt as _,De as a,oe as b,rn as c,Ms as d,yt as e,He as f,S7 as g,_s as h,sie as i,Ur as j,Gc as k,Am as l,Vx as m,KU as n,In as o,oi as p,$U as q,YU as r,Ro as s,Ye as t,pe as u,C7 as v,Cs as w,aie as x,tie as y,eie as z};
788
+ 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 Ab.set(`${n}:${a}`,x),x}function Gre({onLocate:e}){const t=pe(D=>D.timelineOverviewOpen),n=pe(D=>D.setTimelineOverviewOpen),a=oe(D=>D.nodes),r=jt(),s=FS(),o=Ra(D=>D.lang),c=L.useMemo(()=>dy(a,0),[a]),d=L.useMemo(()=>T9(a),[a]),[h,m]=L.useState(null),[p,x]=L.useState(!1),[b,y]=L.useState(!1),k=Wre(d,o)??h,S=!!k&&(k.fp!==d||k.lang!==o),w=()=>{x(!0),y(!1);const{nodes:D,edges:O}=oe.getState();Vre(D,O,o).then(m).catch(()=>y(!0)).finally(()=>x(!1))};if(!t)return null;const C=()=>n(!1),T=D=>D?D.slice(0,10):"",N=D=>D?new Date(D).toLocaleTimeString(s,{hour:"2-digit",minute:"2-digit"}):"—";return Za.createPortal(u.jsx("div",{className:"fixed inset-0 z-[60] bg-ink/30 backdrop-blur-sm flex items-center justify-center p-6",onClick:C,children:u.jsxs("div",{className:"bg-card rounded-2xl shadow-2xl border border-line w-[640px] max-h-[80vh] flex flex-col",onClick:D=>D.stopPropagation(),children:[u.jsxs("div",{className:"flex items-center gap-2 px-5 py-3 border-b border-line shrink-0",children:[u.jsx(Wb,{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:He(r("tlov.count"),{n:c.length})}),u.jsx("div",{className:"flex-1"}),u.jsxs("button",{onClick:()=>{C(),pe.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(Vb,{size:13,strokeWidth:1.75}),r("tmap.export")]}),u.jsx("button",{onClick:C,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(mn,{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(zf,{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 ${S?"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:S?r("tlov.gedankenStale"):new Date(k.at).toLocaleString(s)}),S&&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((D,O)=>{const M=O>0?T(c[O-1].createdAt):void 0,_=T(D.createdAt),R=O===0||_!==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:_||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:D.color,opacity:D.archived?.35:1}}),u.jsx("span",{className:"text-2xs font-mono text-ink-faint shrink-0 w-11",children:N(D.createdAt)}),u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsxs("p",{className:`text-sm truncate ${D.archived?"text-ink-faint line-through":D.badged?"text-ink":"text-ink-muted"}`,children:[D.topic&&u.jsxs("span",{className:"font-medium text-accent",children:[D.topic," · "]}),D.label||"…"]}),D.modifiedAt&&D.modifiedAt!==D.createdAt&&u.jsxs("p",{className:"text-2xs text-ink-faint",children:[r("timeline.modified")," ",new Date(D.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:()=>{C(),e(D.id)},title:r("hlov.locateTitle"),children:r("tlov.locate")})]})]},D.id)})]})]})}),document.body)}const $re=L.memo(function(t){const n=rn(a=>a.projects.find(r=>r.id===a.activeId)?.kind==="paradigm");return t.data?.stepKind==="frame"?u.jsx(Cne,{...t}):am(t.data?.stepKind)?u.jsx(Nne,{...t}):n?u.jsx(bne,{...t}):u.jsx(pne,{...t})}),Yre={thought:$re},Kre={smoothstep:L.memo(Ine)};function Xre(){const[e,t]=L.useState(yt||oe.persist.hasHydrated());return L.useEffect(()=>oe.persist.onFinishHydration(()=>t(!0)),[]),L.useEffect(()=>{if(!e||yt)return;let n;const a=()=>{clearTimeout(n),n=setTimeout(()=>{Uae()},800)},r=oe.subscribe((s,o)=>{s.nodes!==o.nodes&&a()});return a(),()=>{r(),clearTimeout(n)}},[e]),L.useEffect(()=>{pe.getState().condenseRun.status==="building"&&pe.getState().setCondenseRun({status:"idle",current:0,total:0,streaming:""})},[]),L.useEffect(()=>{if(yt)return;const n=setTimeout(()=>{Fae()},6e3);return()=>clearTimeout(n)},[]),L.useEffect(()=>{if(!e||yt||localStorage.getItem("thoughtdag.tutorialDone")||oe.getState().nodes.length>0)return;const n=setTimeout(()=>pe.getState().setTutorialOpen(!0),900);return()=>clearTimeout(n)},[e]),L.useEffect(()=>{$ae()},[]),L.useEffect(()=>{yt||(Tt(()=>import("./session-handoff-Fpl3jes7.js"),[]).then(n=>n.consumeSessionHandoff()),Tt(()=>import("./live-mirror-D3u92mbO.js"),[]).then(n=>n.startLiveMirror()),Tt(()=>import("./canvas-record-Dw4tjwhH.js"),[]).then(n=>n.startCanvasRecord()),Tt(()=>import("./canonical-DccXDqkX.js"),[]).then(n=>n.unsubscribeOrphanedSessions()))},[]),L.useEffect(()=>{yt||Gae().then(n=>{n&&(n.status==="minted"?(Ye("success",De("provider.oauthMinted")),x9(n.key)):Ye("error",He(De("provider.oauthFailed"),{error:n.error})))})},[]),u.jsxs(u.Fragment,{children:[e&&u.jsx(Qre,{}),u.jsx(Qae,{}),u.jsx(Jae,{}),u.jsx(nre,{}),u.jsx(are,{}),u.jsx(rre,{}),u.jsx(ire,{}),u.jsx(sre,{}),u.jsx(hre,{}),u.jsx(bre,{}),u.jsx(Yae,{}),u.jsx(Mre,{}),u.jsx(Rre,{}),u.jsx(Lre,{})]})}function Qre(){const{nodes:e,edges:t,setNodes:n,setEdges:a,addQuestion:r,undo:s,redo:o,addCrossLink:c,setSelectedNodeId:d,setSelectedNodeIds:h,history:m,historyIndex:p,relayout:x}=oe(),b=jt(),y=pe(ae=>ae.setTutorialOpen),k=pe(ae=>ae.annotationsHidden),S=pe(ae=>ae.setAnnotationsHidden),[w,C]=L.useState(""),[T,N]=L.useState(!1),[D,O]=L.useState(""),[M,_]=L.useState(!1),[R,G]=L.useState(!1),[B,$]=L.useState([]),[Z,U]=L.useState(!1),q=L.useRef(null),H=L.useRef(null),V=e.length>0,X=oe(ae=>ae.events.length>0),K=oe(ae=>ae.nodes.reduce((be,Ce)=>be+(Ce.data.highlights?.length??0),0)),F=oe(ae=>ae.nodes.reduce((be,Ce)=>be+(Ce.data.attachments?.length??0)+(["note","link"].includes(Ce.data.stepKind??"")?1:0),0)),W=L.useRef(null),ee=pe(ae=>ae.arrivalFocusNodeId);L.useEffect(()=>{if(!ee)return;const ae=oe.getState().nodes.find(be=>be.id===ee);ae&&(pe.getState().setArrivalFocusNodeId(null),window.setTimeout(()=>{W.current?.setCenter(ae.position.x+260,ae.position.y+140,{zoom:.9,duration:400})},150))},[ee]);const P=Ts(ae=>ae.paper),re=Ts(ae=>ae.lighting),fe=Ts(ae=>ae.resolved),ge=L.useMemo(()=>wne(),[fe]),Te=L.useMemo(()=>{const ae=getComputedStyle(document.documentElement),be=(ae.getPropertyValue("--color-surface").trim()||"#FAF9F7").replace("#",""),[Ce,ye,Ue]=[0,2,4].map(tt=>parseInt(be.slice(tt,tt+2),16));return{mask:`rgba(${Ce},${ye},${Ue},0.7)`,archived:ae.getPropertyValue("--color-wash").trim()||"#EFEDE9",ordinary:fe==="dark"?"#6E6759":"#B9B3AB"}},[fe]),ne=L.useRef(e.length),ke=L.useCallback((ae,be={})=>{const Ce=W.current;if(!Ce)return;const ye=be.zoom??Ce.getZoom();Ce.setCenter(ae.position.x+(be.offX??260)+sm(ae.id)/(2*ye),ae.position.y+110,{zoom:ye,duration:be.duration??350})},[]),Ae=Ra(ae=>ae.lang),Le=pe(ae=>ae.condenseRun),qe=Le.status==="building",je=rn(ae=>ae.projects.find(be=>be.id===ae.activeId)?.kind==="paradigm"),et=_l();L.useEffect(()=>{if(yt||!V||oe.getState().nodes.length<10)return;const ae=Number(localStorage.getItem("thoughtdag.lastBackupAt")??0);if(ae===0){localStorage.setItem("thoughtdag.lastBackupAt",String(Date.now()));return}Date.now()-ae<168*3600*1e3||sessionStorage.getItem("thoughtdag.backupNudged")||(sessionStorage.setItem("thoughtdag.backupNudged","yes"),Ye("info",De("backup.nudge"),0,{label:De("backup.nudgeBtn"),run:()=>bf()}))},[V]);const dt=L.useCallback(()=>{const{nodes:ae,edges:be}=Hae(Ae),Ce=oe.getState();Ce.setNodes([...Ce.nodes,...ae.filter(ye=>!Ce.nodes.some(Ue=>Ue.id===ye.id))]),Ce.setEdges([...Ce.edges,...be.filter(ye=>!Ce.edges.some(Ue=>Ue.id===ye.id))]),Ce.pushHistory(),setTimeout(()=>{const ye=W.current;ye&&(ye.fitView({duration:500,padding:.1}),setTimeout(()=>{if(ye.getViewport().zoom<.34){const Ue=[...oe.getState().nodes].sort((tt,rt)=>(tt.data.createdAt??"").localeCompare(rt.data.createdAt??""))[0];Ue&&ye.setCenter(Ue.position.x+300,Ue.position.y+240,{zoom:.6,duration:550})}},680))},100),localStorage.getItem("thoughtdag.tutorialDone")||y(!0)},[Ae,y]),Ke=L.useCallback(ae=>{const be=oe.getState(),Ce=be.nodes[be.nodes.length-1],ye=Ce?{x:Ce.position.x,y:Ce.position.y+340}:{x:120,y:80},Ue=In();be.setNodes([...be.nodes,{id:Ue,type:"thought",position:ye,dragHandle:".drag-handle",data:{question:"",instruction:"",stepKind:ae,response:"",responses:[],responseIndex:-1,isCollapsed:!1,isEditing:!1,isEditingResponse:!1,isLoading:!1,tokenCount:0,highlights:[],highlightMode:"tag",attachments:[],excludedAttachmentIds:[],includedAttachmentIds:[],roleMode:"inherit",isRoot:be.nodes.length===0,isBranch:!1}}]),be.pushHistory()},[]),kt=L.useCallback(()=>{ne.current=oe.getState().nodes.length,setTimeout(()=>W.current?.fitView({duration:300,padding:.2}),50)},[]),bt=L.useRef(null),at=L.useCallback(ae=>{const be=oe.getState(),Ce=In();be.setNodes([...be.nodes,{id:Ce,type:"thought",position:ae,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}}]),be.pushHistory()},[]),Et=L.useCallback(ae=>{const be=[];for(const Ce of Array.from(ae)){const ye=Ce.name.split(".").pop()?.toLowerCase()??"";Ce.type.startsWith("image/")||Ce.type==="application/pdf"||Ce.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(ye)?be.push(Ce):Ye("info",He(De("toast.unsupportedFile"),{name:Ce.name}))}return be},[]),Bt=L.useCallback(ae=>{const be=oe.getState(),Ce=In();return be.setNodes([...be.nodes,{id:Ce,type:"thought",position:ae,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:pe.getState().webSearchEnabled,scholarSearch:pe.getState().scholarSearchEnabled}}]),be.pushHistory(),Ce},[]),Ve=L.useCallback(ae=>{const be=Et(ae);if(be.length===0)return;let Ce=null;be.forEach((ye,Ue)=>{const tt=ti("file",{x:120+Ue%3*480,y:120+Math.floor(Ue/3)*620});Ad(tt,[ye]),!Ce&&!ye.type.startsWith("image/")&&(Ce=tt)}),Ce&&pe.getState().setReaderNodeId(Ce),setTimeout(()=>W.current?.fitView({duration:400,padding:.2}),120)},[Et]),Ht=L.useCallback((ae,be)=>{const Ce=ae.clientX,ye=ae.clientY,Ue=ae.currentTarget;let tt=null;const rt=Ut=>{!tt&&Math.hypot(Ut.clientX-Ce,Ut.clientY-ye)>6&&(tt=document.createElement("div"),tt.innerHTML=Ue.innerHTML,tt.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(tt)),tt&&(tt.style.left=`${Ut.clientX-18}px`,tt.style.top=`${Ut.clientY-18}px`)},vt=Ut=>{window.removeEventListener("pointermove",rt),window.removeEventListener("pointerup",vt);const Wt=!!tt;tt?.remove(),be(Wt?{x:Ut.clientX,y:Ut.clientY}:null)};window.addEventListener("pointermove",rt),window.addEventListener("pointerup",vt)},[]),se=L.useCallback(ae=>{const be=W.current?.screenToFlowPosition(ae??{x:window.innerWidth/2,y:window.innerHeight/2})??{x:140,y:140};return{x:be.x-200,y:be.y-60}},[]);L.useEffect(()=>{const ae=Ce=>{bt.current={x:Ce.clientX,y:Ce.clientY}},be=Ce=>{if(yt)return;const ye=Ce.target;if(ye&&(ye.tagName==="INPUT"||ye.tagName==="TEXTAREA"||ye.isContentEditable))return;const Ue=rn.getState(),tt=Ue.projects.find(Qt=>Qt.id===Ue.activeId)?.kind==="paradigm";if(oe.getState().nodes.length===0&&!tt)return;const rt=Ce.clipboardData;if(!rt)return;const vt=se(bt.current),Ut=rt.getData("text/plain").trim(),Wt=Array.from(rt.files),ia=Wt.some(Qt=>!Qt.type.startsWith("image/"));if(Wt.length>0&&(ia||!Ut)){Ce.preventDefault();const Qt=ti("file",vt);Ad(Qt,Wt);return}if(Ut)if(Ce.preventDefault(),/^https?:\/\/\S+$/.test(Ut)){const Qt=ti("link",vt,{linkUrl:Ut});r9(Qt,Ut)}else ti("note",vt,{question:Ene(Ut)})};return window.addEventListener("mousemove",ae),window.addEventListener("paste",be),()=>{window.removeEventListener("mousemove",ae),window.removeEventListener("paste",be)}},[se]);const Be=L.useCallback(async()=>{const ae=oe.getState();if(ae.nodes.length===0)return;const{nodes:be,edges:Ce}=iF(ae.nodes,ae.edges),ye=rn.getState(),Ue=ye.projects.find(rt=>rt.id===ye.activeId)?.name??"Paradigm",tt=crypto.randomUUID();await Ur(oi(tt),JSON.stringify({state:{nodes:be,edges:Ce},version:1})),await Gc(tt,`▶ ${Ue}`,"chat"),await k7(tt,Ue),ne.current=oe.getState().nodes.length,setTimeout(()=>W.current?.fitView({duration:400,padding:.15}),150)},[]);L.useEffect(()=>{e.length===0&&!je&&!localStorage.getItem("thoughtdag.seeded")&&localStorage.setItem("thoughtdag.seeded","yes")},[]),L.useEffect(()=>{if(e.length>ne.current&&W.current){const ae=e[e.length-1];ae&&setTimeout(()=>ke(ae,{zoom:1,duration:400,offX:220}),100)}ne.current=e.length},[e,ke]);const ve=L.useCallback(ae=>{const be=oe.getState().nodes;n(Y8(ae,be))},[n]),We=L.useCallback(ae=>a(K8(ae,oe.getState().edges)),[a]),ut=L.useRef(null),gt=L.useCallback((ae,be)=>{if(be.data.stepKind!=="frame"||be.data.frameCarry===!1)return;const Ce=oe.getState(),ye=Ce.nodes.find(vt=>vt.id===be.id);if(!ye)return;const Ue=ye.measured?.width??ye.width??0,tt=ye.measured?.height??ye.height??0,rt=Ce.nodes.filter(vt=>{if(vt.id===ye.id||vt.data.stepKind==="frame"||vt.selected)return!1;const Ut=vt.position.x+(vt.measured?.width??520)/2,Wt=vt.position.y+(vt.measured?.height??120)/2;return Ut>=ye.position.x&&Ut<=ye.position.x+Ue&&Wt>=ye.position.y&&Wt<=ye.position.y+tt}).map(vt=>({id:vt.id,start:vt.position}));rt.length!==0&&(ut.current={frameId:ye.id,start:ye.position,members:rt})},[]),At=L.useCallback((ae,be)=>{const Ce=ut.current;if(!Ce||be.id!==Ce.frameId)return;const ye=be.position.x-Ce.start.x,Ue=be.position.y-Ce.start.y,tt=new Map(Ce.members.map(rt=>[rt.id,{x:rt.start.x+ye,y:rt.start.y+Ue}]));oe.setState(rt=>({nodes:rt.nodes.map(vt=>{const Ut=tt.get(vt.id);return Ut?{...vt,position:Ut}:vt})}))},[]),qt=L.useCallback(()=>{ut.current=null},[]),[hn,wn]=L.useState(null),[Kt,kn]=L.useState(null),sn=L.useCallback((ae,be)=>{yt||window.getSelection()?.toString()||(ae.preventDefault(),kn({x:ae.clientX,y:ae.clientY,nodeId:be.id}))},[]),ka=L.useCallback((ae,be)=>{ae.preventDefault(),wn({x:ae.clientX,y:ae.clientY,edgeId:be.id})},[]);L.useEffect(()=>{if(!hn)return;const ae=()=>wn(null);return window.addEventListener("click",ae),()=>window.removeEventListener("click",ae)},[hn]);const Fn=oe(ae=>ae.deleteEdges),dr=L.useCallback(ae=>{Fn([ae]),wn(null)},[Fn]),tr=L.useCallback(ae=>{ae.source&&ae.target&&c(ae.source,ae.target)},[c]),Qn=L.useCallback(()=>{window.getSelection()?.removeAllRanges(),document.body.classList.add("tdag-connecting")},[]),Ba=L.useCallback((ae,be)=>{if(document.body.classList.remove("tdag-connecting"),je||be.isValid||be.fromHandle?.type!=="source"||!be.fromNode)return;const Ce=be.fromNode.id,ye=ae.target?.closest?.(".react-flow__node");if(ye){const Wt=ye.getAttribute("data-id");if(Wt&&Wt!==Ce){const ia=oe.getState().nodes.find(Da=>Da.id===Wt),Qt=ia?.data.stepKind??"";ia&&!["note","file","link","frame"].includes(Qt)&&oe.getState().addCrossLink(Ce,Wt)}return}const{clientX:Ue,clientY:tt}="changedTouches"in ae?ae.changedTouches[0]:ae,rt=se({x:Ue,y:tt}),vt=oe.getState();if(vt.nodes.find(Wt=>Wt.id===Ce)?.data.stepKind==="frame")return;const Ut=Bt(rt);vt.setEdges([...oe.getState().edges,{id:`edge-${Ce}-${Ut}`,source:Ce,target:Ut,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()},[je,se,Bt]),Jt=oe(ae=>ae.selectedNodeId),ce=oe(ae=>ae.selectedNodeIds),ze=pe(ae=>ae.panelOpen),ht=pe(ae=>ae.viewerLoadError),It=oe(ae=>ae.staleIds.length),En=pe(ae=>ae.panelWidth),on=e.find(ae=>ae.id===Jt)?.data.stepKind,xt=am(on)||on==="frame",ft=ze&&!!Jt&&!je&&!xt,Rt=ce.length>1,On=oe(ae=>ae.batchDelete);L.useEffect(()=>{const ae=be=>{if(!pe.getState().confirmRequest&&!(yt&&!((be.metaKey||be.ctrlKey)&&be.key==="f"))){if((be.metaKey||be.ctrlKey)&&be.key==="z"&&(be.shiftKey?(be.preventDefault(),o()):(be.preventDefault(),s())),(be.metaKey||be.ctrlKey)&&be.key==="f"){be.preventDefault(),N(!0);return}{const Ce=be.target;if(!(Ce.tagName==="INPUT"||Ce.tagName==="TEXTAREA"||Ce.isContentEditable)&&Jt&&!je&&!be.metaKey&&!be.ctrlKey&&!be.altKey){const{nodes:Ue,edges:tt}=oe.getState();if(be.key===" "){be.preventDefault(),oe.getState().toggleCollapse(Jt);return}if(be.key==="r"||be.key==="R"){be.preventDefault(),oe.getState().rerunNode(Jt,{});return}if(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(be.key)){const rt=tt.filter(Ut=>!Ut.data?.isCrossLink);let vt;if(be.key==="ArrowUp")vt=rt.find(Ut=>Ut.target===Jt)?.source;else if(be.key==="ArrowDown")vt=rt.find(Ut=>Ut.source===Jt)?.target;else{const Ut=rt.find(Qt=>Qt.target===Jt),Wt=Ut?rt.filter(Qt=>Qt.source===Ut.source).map(Qt=>Qt.target):Ue.filter(Qt=>!rt.some(Da=>Da.target===Qt.id)).map(Qt=>Qt.id),ia=Wt.indexOf(Jt);ia!==-1&&Wt.length>1&&(vt=Wt[(ia+(be.key==="ArrowRight"?1:Wt.length-1))%Wt.length])}if(vt){be.preventDefault(),d(vt);const Ut=Ue.find(Wt=>Wt.id===vt);Ut&&ke(Ut,{zoom:1,duration:300})}return}}}if(be.key==="Escape"){const Ce=be.target;if(Ce.tagName==="INPUT"||Ce.tagName==="TEXTAREA"||Ce.isContentEditable)return;ce.length>1?h([]):Jt&&d(null);return}if(be.key==="Delete"||be.key==="Backspace"){const Ce=be.target;if(Ce.tagName==="INPUT"||Ce.tagName==="TEXTAREA"||Ce.isContentEditable)return;if(ce.length>1)be.preventDefault(),Cs({title:De("confirm.deleteNodesTitle"),message:He(De("confirm.deleteNodes"),{n:ce.length}),confirmLabel:De("common.delete"),danger:!0}).then(ye=>{ye&&On(ce)});else{const ye=t.filter(Ue=>Ue.selected).map(Ue=>Ue.id);ye.length>0&&(be.preventDefault(),Fn(ye))}}}};return window.addEventListener("keydown",ae),()=>window.removeEventListener("keydown",ae)},[s,o,Jt,ce,d,h,On,t,Fn,je,ke]);const Mn=()=>{w.trim()&&(r(w.trim(),{rolePrompt:D.trim()||void 0,initialAttachments:B.length>0?B:void 0}),C(""),O(""),_(!1),$([]))},xe=async ae=>{for(const be of Array.from(ae))await o0(be,{add:Ce=>$(ye=>[...ye,Ce]),update:(Ce,ye)=>$(Ue=>Ue.map(tt=>tt.id===Ce?{...tt,...ye}:tt))})},Xe=ae=>{ae.key==="Enter"&&!ae.shiftKey&&!Qa(ae)&&(ae.preventDefault(),Mn())},Nt=L.useCallback(({nodes:ae})=>{const be=ae.map(Ce=>Ce.id);be.length>1?h(be):be.length===1&&d(be[0])},[d,h]),Ct=L.useMemo(()=>e.filter(ae=>ae.data.stepKind==="frame"),[e]),[ot,Lt]=L.useState(!1),en=L.useRef(null);L.useEffect(()=>{if(!ot)return;const ae=be=>{en.current?.contains(be.target)||Lt(!1)};return window.addEventListener("mousedown",ae),()=>window.removeEventListener("mousedown",ae)},[ot]);const[Xt,xn]=L.useState(!1),de=pe(ae=>ae.pluginUpdate),[Pt,fn]=L.useState(0),Cn=pe(ae=>ae.searchHitIds!==null),Sn=L.useRef(null);L.useEffect(()=>{if(!Xt)return;const ae=be=>{Sn.current?.contains(be.target)||xn(!1)};return window.addEventListener("mousedown",ae),()=>window.removeEventListener("mousedown",ae)},[Xt]);const ea=pe(ae=>ae.searchHitIds),xa=L.useMemo(()=>{if(!Jt||ce.length>1||!e.some(rt=>rt.id===Jt))return null;const ae=Em(Jt,e,t),be=new Set;for(const rt of ae.mainline)rt.id!==Jt&&be.add(rt.id);for(const rt of ae.materials)be.add(rt.id);for(const rt of ae.references)be.add(rt.source.id);const Ce=t.filter(rt=>!rt.data?.isCrossLink),ye=Fr(Jt,e,Ce).visitedEdgeIds,Ue=new Set(ae.references.map(rt=>rt.edge.id)),tt=Ce.filter(rt=>rt.source===Jt);return{ctx:be,down:new Set(tt.map(rt=>rt.target)),pathEdgeIds:ye,refEdgeIds:Ue,downEdgeIds:new Set(tt.map(rt=>rt.id))}},[Jt,ce,e,t]),Vr=L.useMemo(()=>{let ae=e;return k&&(ae=ae.map(be=>{const Ce=be.data.stepKind,ye=am(Ce)&&!t.some(Ue=>Ue.source===be.id||Ue.target===be.id);return Ce==="frame"||ye?{...be,hidden:!0}:be})),ea!==null&&(ae=ae.map(be=>ea.has(be.id)||be.data.stepKind==="frame"?{...be,className:"search-hit"}:be.className==="search-hit"?{...be,className:void 0}:be)),xa&&(ae=ae.map(be=>{const Ce=be.id===Jt?"target":xa.ctx.has(be.id)?"ctx":xa.down.has(be.id)?"down":be.data.stepKind==="frame"?void 0:"dim";return Ce?{...be,className:[be.className,`focus-${Ce}`].filter(Boolean).join(" "),...Ce!=="dim"?{data:{...be.data,focusRole:Ce}}:{}}:be})),ae},[e,t,k,ea,xa,Jt]),ra=L.useMemo(()=>{const ae=t.map(ye=>{const Ue=ye.data?.isBranchFromSelection?{...ye,animated:!1,style:{...ye.style,strokeDasharray:void 0}}:ye,tt=typeof Ue.style?.stroke=="string"?sE[Ue.style.stroke.toUpperCase()]:void 0,rt=Ue.markerEnd&&typeof Ue.markerEnd=="object"?Ue.markerEnd:void 0,vt=typeof rt?.color=="string"?sE[rt.color.toUpperCase()]:void 0;return!tt&&!vt?Ue:{...Ue,...tt?{style:{...Ue.style,stroke:ge[tt]}}:{},...vt&&rt?{markerEnd:{...rt,color:ge[vt]}}:{}}});if(xa)return ae.map(ye=>xa.pathEdgeIds.has(ye.id)?{...ye,className:"focus-e-path",style:{...ye.style,stroke:ge.accent,strokeWidth:3.5,opacity:1},markerEnd:{type:"arrowclosed",...ye.markerEnd&&typeof ye.markerEnd=="object"?ye.markerEnd:{},color:ge.accent},zIndex:10,data:{...ye.data,focusRole:"path"}}:xa.refEdgeIds.has(ye.id)?{...ye,style:{...ye.style,opacity:.9},zIndex:5,data:{...ye.data,focusRole:"ref"}}:xa.downEdgeIds.has(ye.id)?{...ye,className:"focus-e-down",style:{...ye.style,strokeWidth:2.5,opacity:.85},markerEnd:{type:"arrowclosed",...ye.markerEnd&&typeof ye.markerEnd=="object"?ye.markerEnd:{}},zIndex:5,data:{...ye.data,focusRole:"down"}}:{...ye,style:{...ye.style,strokeWidth:1.5,opacity:.2},zIndex:0});const be=ce.length>1?ce:[];if(be.length===0)return ae;const{visitedEdgeIds:Ce}=Fr(be,e,t);return ae.map(ye=>Ce.has(ye.id)?{...ye,style:{...ye.style,stroke:ge.trace,strokeWidth:3.5,opacity:1},markerEnd:{type:"arrowclosed",...ye.markerEnd&&typeof ye.markerEnd=="object"?ye.markerEnd:{},color:ge.trace},zIndex:10}:{...ye,style:{...ye.style,strokeWidth:1.5,opacity:.2},zIndex:0})},[e,t,ce,ge,xa]);return L.useEffect(()=>{if(!ft||!Jt)return;const ae=setTimeout(()=>{const be=W.current;if(!be)return;const Ce=oe.getState().nodes.find(vt=>vt.id===Jt);if(!Ce)return;const ye=be.getViewport(),Ue=Ce.measured?.width??Ce.width??480,tt=(Ce.position.x+Ue)*ye.zoom+ye.x,rt=window.innerWidth-pe.getState().panelWidth-pd-24;if(tt>rt){const vt=(Ce.position.x+Ue/2)*ye.zoom+ye.x;be.setViewport({...ye,x:ye.x-(vt-rt/2)},{duration:300})}},60);return()=>clearTimeout(ae)},[ft,Jt]),u.jsxs("div",{className:"relative w-full h-full","data-searching":Cn||void 0,children:[u.jsxs("div",{className:"relative h-full w-full",onDoubleClick:ae=>{ae.target.classList.contains("react-flow__pane")&&!je&&Bt(se({x:ae.clientX,y:ae.clientY}))},onDragOver:ae=>{(ae.dataTransfer.types.includes("application/thoughtdag-content")||ae.dataTransfer.types.includes("Files"))&&(ae.preventDefault(),ae.dataTransfer.dropEffect="copy",!V&&!je&&U(!0))},onDrop:ae=>{if(yt)return;const be=ae.target;if(!V&&!je&&ae.dataTransfer.files.length>0){ae.preventDefault(),U(!1),Ve(ae.dataTransfer.files);return}const Ce=be.closest?.(".react-flow__node"),ye=Ce&&oe.getState().nodes.find(rt=>rt.id===Ce.getAttribute("data-id"))?.data.stepKind==="frame";if(!be.classList?.contains("react-flow__pane")&&!ye)return;const Ue=se({x:ae.clientX,y:ae.clientY}),tt=ae.dataTransfer.getData("application/thoughtdag-content");if(tt==="ask"){ae.preventDefault(),Bt(Ue);return}if(tt==="frame"){ae.preventDefault(),at(Ue);return}if(tt==="note"||tt==="file"){ae.preventDefault(),ti(tt,Ue);return}if(ae.dataTransfer.files.length>0){ae.preventDefault();const rt=Et(ae.dataTransfer.files);if(rt.length===0)return;const vt=ti("file",Ue);Ad(vt,rt)}},children:[u.jsxs(xj,{onInit:ae=>{W.current=ae,o9.current=ae;const be=pe.getState().arrivalFocusNodeId;if(be){pe.getState().setArrivalFocusNodeId(null);const Ce=oe.getState().nodes.find(ye=>ye.id===be);Ce&&window.setTimeout(()=>{ae.setCenter(Ce.position.x+260,Ce.position.y+140,{zoom:.9,duration:400})},150)}},nodes:Vr,edges:ra,onNodesChange:ve,onEdgesChange:We,onNodeDragStart:gt,onNodeDrag:At,onNodeDragStop:qt,onConnect:tr,onConnectStart:Qn,onConnectEnd:Ba,onEdgeContextMenu:ka,onNodeContextMenu:sn,nodeTypes:Yre,edgeTypes:Kre,deleteKeyCode:null,fitView:!0,onlyRenderVisibleElements:!0,minZoom:.04,maxZoom:2,defaultEdgeOptions:{type:"smoothstep",animated:!1,style:{stroke:ge.accent,strokeWidth:2},markerEnd:{type:"arrowclosed",color:ge.accent,width:18,height:18}},snapToGrid:P==="grid",snapGrid:[22,22],proOptions:{hideAttribution:!0},nodeDragThreshold:5,connectionRadius:40,selectionMode:Oc.Partial,selectionOnDrag:!yt,nodesDraggable:!yt,nodesConnectable:!yt,panOnDrag:yt?!0:[1,2],zoomOnDoubleClick:!1,connectionLineStyle:{stroke:ge.accent,strokeDasharray:"8 4",strokeWidth:2},onSelectionChange:Nt,onPaneClick:()=>{d(null),h([]),kn(null)},children:[P==="grid"?u.jsxs(u.Fragment,{children:[u.jsx(d1,{id:"grid-fine",variant:yi.Lines,gap:22,color:"var(--canvas-grid-fine)"}),u.jsx(d1,{id:"grid-major",variant:yi.Lines,gap:110,color:"var(--canvas-grid-major)"})]}):u.jsx(d1,{variant:yi.Dots,gap:24,size:1,color:"var(--canvas-dot)"}),u.jsx(Jre,{}),u.jsx(Zre,{panelShiftWidth:ft?En:0}),u.jsx(qre,{}),u.jsx(_j,{position:"bottom-left"}),e.length>0&&u.jsx(Fj,{nodeColor:ae=>{const be=ae.data;if(be.archived)return Te.archived;const Ce=be.stepKind;return Ce==="note"?"#D97706":Ce==="file"||Ce==="link"?"#64748B":Array.isArray(be.condensedFrom)&&be.condensedFrom.length?"#8B7CF0":be.isRoot?ge.accent:be.isBranch?ge.warm:Te.ordinary},maskColor:Te.mask,style:{width:200,height:140},pannable:!0,zoomable:!0,position:"bottom-right"})]}),!V&&je&&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:()=>Ke("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(fd,{size:15,strokeWidth:1.75})," ",b("paradigm.addHuman")]}),u.jsxs("button",{onClick:()=>Ke("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(Oo,{size:15,strokeWidth:1.75})," ",b("paradigm.addPrompt")]})]})]})}),yt&&!V&&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:ht?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(Un,{size:16,strokeWidth:1.75,className:"animate-spin text-accent"})," ",b("viewer.loading")]})})}),!V&&!je&&!yt&&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:ae=>C(ae.target.value),onKeyDown:Xe,onPaste:ae=>{if(ae.clipboardData.getData("text/plain").trim())return;const be=Array.from(ae.clipboardData.items).filter(Ce=>Ce.kind==="file").map(Ce=>Ce.getAsFile()).filter(Boolean);be.length&&xe(be)},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}),B.length>0&&u.jsx("div",{className:"flex flex-wrap gap-2 mt-2 pb-1",children:B.map(ae=>u.jsxs("div",{className:"flex items-center gap-1.5 bg-wash rounded-lg px-2.5 py-1.5 group",children:[ae.thumbnailUrl?u.jsx("img",{src:ae.thumbnailUrl,className:"w-6 h-6 rounded object-cover",alt:ae.name}):u.jsx("span",{className:"text-xs",children:u.jsx(vi,{size:16,strokeWidth:1.75})}),u.jsx("span",{className:"text-xs text-ink-muted max-w-[100px] truncate",children:ae.name}),ae.isExtracting&&u.jsx("span",{className:"text-2xs text-accent",children:u.jsx(Un,{className:"animate-spin",size:12,strokeWidth:1.75})}),ae.numPages!=null&&u.jsxs("span",{className:"text-2xs text-ink-faint",children:[ae.numPages,"p"]}),u.jsx("button",{onClick:()=>$(be=>be.filter(Ce=>Ce.id!==ae.id)),className:"text-ink-faint hover:text-red-500 text-xs opacity-0 group-hover:opacity-100 transition-opacity",children:u.jsx(mn,{size:14,strokeWidth:1.75})})]},ae.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:()=>{_(!1),O("")},className:"text-xs text-ink-faint hover:text-ink-muted",children:u.jsx(mn,{size:14,strokeWidth:1.75})})]}),u.jsx("textarea",{value:D,onChange:ae=>O(ae.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(i9,{onPick:O})]}),u.jsxs("div",{className:"flex items-center justify-end mt-2 gap-2",children:[u.jsx(f2,{}),u.jsx("button",{onClick:()=>_(!M),title:b("landing.roleTrayTitle"),className:`rounded-full w-8 h-8 flex items-center justify-center transition-colors shrink-0 ${M||D?"text-accent bg-accent/10 hover:bg-accent/20":"text-ink-faint hover:text-ink-muted hover:bg-line"}`,children:u.jsx($P,{size:16,strokeWidth:1.75})}),u.jsx("button",{onClick:()=>q.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(wi,{size:16,strokeWidth:1.75})}),u.jsx("input",{ref:q,type:"file",multiple:!0,accept:Bd,className:"hidden",onChange:ae=>{xe(ae.target.files||[]),ae.target.value=""}}),u.jsx("button",{onClick:Mn,disabled:!w.trim()||B.some(ae=>ae.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:B.some(ae=>ae.isExtracting)?b("landing.extracting"):b("landing.send")})]})]}),u.jsxs("div",{onClick:()=>H.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(Io,{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:()=>G(!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(bP,{size:15,strokeWidth:1.75,className:"text-accent shrink-0"}),u.jsx("span",{children:b("landing.atlasStart")}),u.jsx(hP,{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:H,type:"file",multiple:!0,accept:Bd,className:"hidden",onChange:ae=>{Ve(ae.target.files||[]),ae.target.value=""}}),R&&u.jsx(m9,{onClose:()=>G(!1),onSwitched:()=>{G(!1),kt()}}),(!et||(et.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(Pd,{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:[Ae==="zh"&&u.jsx("button",{onClick:()=>{pe.getState().setApiKeyPresetHint("zhipu"),pe.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:()=>{g9()},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:()=>pe.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:()=>pe.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:qi,title:"landing.feature1.title",desc:"landing.feature1.desc"},{icon:m5,title:"landing.feature2.title",desc:"landing.feature2.desc"},{icon:PS,title:"landing.feature3.title",desc:"landing.feature3.desc"}].map(({icon:ae,title:be,desc:Ce})=>u.jsxs("div",{className:"bg-card/60 backdrop-blur border border-line rounded-xl px-4 py-3.5",children:[u.jsx(ae,{size:16,strokeWidth:1.75,className:"text-accent mb-2"}),u.jsx("h3",{className:"text-xs font-semibold text-ink mb-1",children:b(be)}),u.jsx("p",{className:"text-2xs text-ink-faint leading-relaxed",children:b(Ce)})]},be))}),u.jsxs("div",{className:"text-center mt-6 flex items-center justify-center gap-5",children:[u.jsxs("button",{onClick:dt,className:"text-xs text-accent hover:text-accent-strong font-medium transition-colors inline-flex items-center gap-1.5",children:[u.jsx(m5,{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(c5,{size:14,strokeWidth:1.75})," ",b("landing.howItWorks")]})]})]})]}),!yt&&u.jsx(jae,{onSwitched:kt}),(V||je)&&!yt&&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:[!je&&u.jsx("button",{onClick:()=>Bt(se(null)),draggable:!0,onDragStart:ae=>{ae.dataTransfer.setData("application/thoughtdag-content","ask"),ae.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(fd,{size:17,strokeWidth:1.75})}),u.jsx("button",{onPointerDown:ae=>Ht(ae,be=>ti("note",se(be))),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(Vi,{size:17,strokeWidth:1.75})}),u.jsx("button",{onPointerDown:ae=>Ht(ae,be=>ti("file",se(be))),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(wi,{size:17,strokeWidth:1.75})}),u.jsx("button",{onPointerDown:ae=>Ht(ae,be=>at(se(be))),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(Lx,{size:17,strokeWidth:1.75})})]}),yt&&u.jsxs("div",{className:"absolute top-4 z-10 flex gap-1.5 items-center transition-[right] duration-200",style:{right:ft?En+pd+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(Ld,{size:14,strokeWidth:1.75})," ",b("viewer.badge")]}),u.jsx("button",{onClick:()=>N(!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(Pf,{size:15,strokeWidth:1.75})}),u.jsx(IE,{}),u.jsx("button",{onClick:()=>bf(),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(Tc,{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")})]}),!yt&&u.jsxs("div",{className:"absolute top-4 z-10 flex gap-1.5 items-center transition-[right] duration-200",style:{right:ft?En+pd+12:16},children:[je&&u.jsxs(u.Fragment,{children:[u.jsxs("button",{onClick:()=>Ke("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(fd,{size:14,strokeWidth:1.75})," ",b("paradigm.addHuman")]}),u.jsxs("button",{onClick:()=>Ke("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(Oo,{size:14,strokeWidth:1.75})," ",b("paradigm.addPrompt")]}),u.jsxs("button",{onClick:()=>{Be()},title:b("paradigm.instantiateTitle"),className:"bg-ink text-white rounded-lg h-8 px-3 flex items-center gap-1.5 shadow-sm hover:bg-ink/85 transition-colors text-xs font-medium",children:["▶ ",b("paradigm.instantiate")]})]}),!je&&u.jsx(jre,{}),!je&&u.jsx(s9,{}),!V&&u.jsx("button",{onClick:()=>pe.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(Pd,{size:15,strokeWidth:1.75})}),It>0&&!je&&u.jsxs("button",{onClick:()=>{const{nodes:ae,edges:be,staleIds:Ce}=oe.getState(),ye=Ce.reduce((Ue,tt)=>{const rt=ae.map(Wt=>Wt.id===tt?{...Wt,data:{...Wt.data,question:"",response:""}}:Wt),{layerTokens:vt}=kr(tt,rt,be),Ut=ae.find(Wt=>Wt.id===tt)?.data.question??"";return Ue+vt.material+vt.reference+vt.chain+$n(Ut)},0);Cs({title:b("replay.confirmTitle"),message:He(b("replay.confirmMsg"),{n:It,tok:ye.toLocaleString()}),confirmLabel:b("replay.confirmBtn")}).then(Ue=>{Ue&&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(Mz,{size:14,strokeWidth:1.75})," ",It]}),V&&Ct.length>0&&u.jsxs("div",{ref:en,className:"relative",children:[u.jsx("button",{onClick:()=>Lt(ae=>!ae),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(Lx,{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:Ct.map(ae=>u.jsxs("button",{onClick:()=>{Lt(!1),W.current?.fitBounds({x:ae.position.x,y:ae.position.y,width:ae.width??640,height:ae.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 ${(md[ae.data.frameColor??"gray"]??md.gray).dot}`}),u.jsx("span",{className:"truncate",children:ae.data.question||b("frame.untitled")})]},ae.id))})]}),V&&u.jsx("button",{onClick:()=>N(!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(Pf,{size:15,strokeWidth:1.75})}),u.jsx(IE,{}),V&&!je&&u.jsx(lae,{showTrigger:!1,openPing:Pt,onLocate:ae=>{const be=oe.getState().nodes.find(Ce=>Ce.id===ae);be&&(d(ae),ke(be,{zoom:1}))}}),qe&&!yt&&u.jsxs("button",{onClick:()=>pe.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:He(b("condense.entryBuilding"),{i:String(Le.current),n:String(Le.total)}),"data-condense-entry":!0,children:[u.jsx(Un,{size:14,strokeWidth:1.75,className:"animate-spin"}),u.jsxs("span",{className:"text-2xs font-mono",children:[Le.current,"/",Le.total]})]}),Vm&&u.jsx("button",{onClick:()=>pe.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(_S,{size:15,strokeWidth:1.75})}),u.jsxs("div",{ref:Sn,className:"relative",children:[u.jsx("button",{onClick:()=>xn(ae=>!ae),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(AS,{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:[V&&u.jsxs("button",{onClick:()=>{xn(!1),S(!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(Vi,{size:14,strokeWidth:1.75,className:`shrink-0 ${k?"text-accent":"text-ink-faint"}`})," ",b(k?"toolbar.menuAnnotationsShow":"toolbar.menuAnnotationsHide")]}),V&&u.jsxs("button",{onClick:()=>{xn(!1),Cs({title:b("confirm.relayoutTitle"),message:b("confirm.relayoutMsg"),confirmLabel:b("toolbar.relayout")}).then(ae=>{ae&&(x(),setTimeout(()=>W.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(Az,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("toolbar.relayout")]}),K>0&&u.jsxs("button",{onClick:()=>{xn(!1),pe.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(jd,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",He(b("hlov.entry"),{n:K})]}),F>0&&u.jsxs("button",{onClick:()=>{xn(!1),pe.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(wi,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",He(b("matov.entry"),{n:F})]}),V&&u.jsx("div",{className:"border-t border-line/60 my-1"}),V&&!je&&!yt&&u.jsxs("button",{onClick:()=>{xn(!1),pe.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(ym,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("condense.title"),"…"]}),V&&!je&&u.jsxs("button",{onClick:()=>{xn(!1),fn(ae=>ae+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(zS,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("toolbar.menuDiagnose")]}),V&&!je&&u.jsxs("button",{onClick:()=>{xn(!1),(async()=>{const{nodes:ae,edges:be}=oe.getState(),{confirmIfSensitive:Ce}=await Tt(async()=>{const{confirmIfSensitive:Ue}=await import("./sensitive-scan-C6YN1rzZ.js");return{confirmIfSensitive:Ue}},[]);if(!await Ce(ae))return;const ye=await gH(ae,be);await navigator.clipboard.writeText(ye).catch(()=>{}),pe.getState().setShareDialogUrl(ye)})()},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(sB,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("toolbar.menuShare")]}),V&&u.jsxs("button",{onClick:()=>{xn(!1),je?sF():bf()},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(Tc,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b(je?"paradigm.exportParadigm":"switcher.exportBackup")]}),X&&u.jsxs("button",{onClick:()=>{xn(!1),dF()},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(vi,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("toolbar.exportEvents")]}),V&&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(([ae,be],Ce)=>u.jsx("button",{onClick:()=>Ts.getState().setLighting(ae),className:`flex-1 px-1 py-1.5 transition-colors ${Ce>0?"border-l border-line":""} ${re===ae?"bg-accent/10 text-accent font-medium":"text-ink-muted hover:bg-wash"}`,children:be},ae))})]}),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(([ae,be],Ce)=>u.jsx("button",{onClick:()=>Ts.getState().setPaper(ae),className:`flex-1 px-1 py-1.5 transition-colors ${Ce>0?"border-l border-line":""} ${P===ae?"bg-accent/10 text-accent font-medium":"text-ink-muted hover:bg-wash"}`,children:be},ae))})]}),u.jsx("div",{className:"border-t border-line/60 my-1"}),u.jsxs("button",{onClick:()=>{xn(!1),pe.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(vP,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("memory.managerTitle")]}),u.jsxs("button",{onClick:()=>{xn(!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(c5,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("landing.howItWorks")]}),de&&u.jsxs("button",{onClick:()=>{xn(!1),navigator.clipboard.writeText(Tb).then(()=>Ye("success",b("plugin.updateCopied"),6e3)).catch(()=>{})},className:"w-full text-left px-3 py-2 text-xs text-accent hover:bg-wash transition-colors flex items-center gap-2.5",title:He(b("plugin.updateHint"),{cmd:Tb}),"data-plugin-update":!0,children:[u.jsx(Tc,{size:14,strokeWidth:1.75,className:"shrink-0"})," ",He(b("plugin.updateAvailable"),{v:de.latest})]}),u.jsxs("button",{onClick:()=>{xn(!1),pe.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(Wb,{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(HS,{size:16,strokeWidth:1.75})}),u.jsx("button",{onClick:o,disabled:p>=m.length-1,className:"bg-card/90 backdrop-blur border border-line rounded-lg w-8 h-8 flex items-center justify-center shadow-sm hover:bg-wash transition-colors disabled:opacity-20 disabled:cursor-not-allowed",title:b("canvas.redo"),children:u.jsx(Kz,{size:16,strokeWidth:1.75})})]}),Rt&&!yt&&u.jsx(Kne,{}),u.jsx(sae,{open:T,onClose:()=>N(!1),onLocate:ae=>{const be=oe.getState().nodes.find(Ce=>Ce.id===ae);be&&(d(ae),ke(be,{zoom:1}))}}),Kt&&u.jsx(Qne,{x:Kt.x,y:Kt.y,nodeId:Kt.nodeId,onClose:()=>kn(null)}),u.jsx(eae,{onLocate:ae=>{const be=oe.getState().nodes.find(Ce=>Ce.id===ae);be&&(d(ae),ke(be,{zoom:1}))}}),u.jsx(Gre,{onLocate:ae=>{const be=oe.getState().nodes.find(Ce=>Ce.id===ae);be&&(d(ae),ke(be,{zoom:1}))}}),u.jsx(Zne,{onLocate:ae=>{const be=oe.getState().nodes.find(Ce=>Ce.id===ae);be&&(d(ae),ke(be,{zoom:1}))}}),hn&&u.jsx("div",{className:"fixed z-50 bg-card border border-line rounded-xl shadow-lg py-1 min-w-[120px]",style:{left:hn.x,top:hn.y},children:u.jsxs("button",{onClick:()=>dr(hn.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(Va,{size:14,strokeWidth:1.75}),b("canvas.deleteEdge")]})})]}),u.jsx(Cre,{onFocusSegment:ae=>{const be=W.current,Ce=oe.getState().nodes.filter(Wt=>ae.includes(Wt.id));if(!be||Ce.length===0)return;const ye=Ce.map(Wt=>Wt.position.x),Ue=Ce.map(Wt=>Wt.position.y),tt=Math.min(...ye),rt=Math.min(...Ue),vt=Math.max(...ye)+520-tt,Ut=Math.max(...Ue)+240-rt;be.fitBounds({x:tt,y:rt,width:vt+700,height:Ut},{duration:350,padding:.15})}}),ft&&u.jsx(Yne,{onFocusNode:ae=>{const be=e.find(Ce=>Ce.id===ae);be&&ke(be,{duration:300})}}),u.jsx(yae,{onLocate:ae=>{const be=oe.getState().nodes.find(Ce=>Ce.id===ae);be&&(d(ae),ke(be,{zoom:1}))}})]})}function Zre({panelShiftWidth:e}){const t=l0(),n=jt(),a=Nl(),r=oe(d=>d.nodes.length),s=oe(d=>d.nodes),o=L.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(yt||t==="work"||r<2)return null;const c=()=>{if(!o)return;pe.getState().setBeaconNodeId(null);const{node:d}=o;a.setCenter(d.position.x+260,d.position.y+110,{zoom:1,duration:1100}),window.setTimeout(()=>{oe.getState().setSelectedNodeId(d.id),pe.getState().setPanelOpen(!0),window.setTimeout(()=>{a.setCenter(d.position.x+260+sm(d.id)/2,d.position.y+110,{zoom:1,duration:300})},60)},1150),window.setTimeout(()=>{Ye("success",n("continue.arrived"),12e3,{label:n("continue.summarize"),run:()=>{l9(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:()=>pe.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(Vb,{size:16,strokeWidth:1.75})," ",n("tmap.export")]}),o&&u.jsxs("button",{onClick:c,onMouseEnter:()=>pe.getState().setBeaconNodeId(o.node.id),onMouseLeave:()=>pe.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(Zz,{size:16,strokeWidth:1.75})," ",n("continue.button")]})]})}function Jre(){const e=l0(),t=un(n=>n.transform[2]);return L.useEffect(()=>{document.querySelector(".react-flow")?.setAttribute("data-zoom-tier",e)},[e]),L.useEffect(()=>{document.querySelector(".react-flow")?.style.setProperty("--tdag-zoom",String(t))},[t]),null}vne();const hy="/thoughtdag/api";window.desktopSessions||nU(hy);Tt(()=>Promise.resolve().then(()=>zre),void 0).then(e=>e.bootPluginUpdateCheck(hy));if(!window.desktopAgents){const e=hy;Tt(()=>import("./http-bridge-mmwHcDuo.js"),[]).then(async t=>{await t.installAgentsHttpBridge(e)&&window.dispatchEvent(new CustomEvent("td:agents-ready"))})}yt?bH():(E7(),navigator.storage?.persist&&navigator.storage.persist(),Tt(()=>Promise.resolve().then(()=>xre),void 0).then(e=>e.bootAutoBackup()));Tt(()=>import("./update-check-B1kgBEyl.js"),[]).then(e=>e.bootUpdateCheck());window.addEventListener("hashchange",()=>{window.location.hash.startsWith("#view=")!==yt&&window.location.reload()});z_.createRoot(document.getElementById("root")).render(u.jsx(L.StrictMode,{children:u.jsx(Xre,{})}));export{Xd as A,ir as B,WU as C,km as D,D7 as E,nie as F,Hs as G,qr as H,Tt as _,De as a,oe as b,rn as c,Ms as d,yt as e,He as f,S7 as g,_s as h,sie as i,Ur as j,Gc as k,Am as l,Vx as m,KU as n,In as o,oi as p,$U as q,YU as r,Ro as s,Ye as t,pe as u,C7 as v,Cs as w,aie as x,tie as y,eie as z};