dsh-thoughtdag 0.4.4 → 0.4.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +22 -6
- package/cordis.patch.yml +5 -0
- package/dist-app/assets/{canonical-DbPqsMYz.js → canonical-DDfsxGbh.js} +2 -2
- package/dist-app/assets/{canvas-record-C1A8ExlM.js → canvas-record-vunI4XSG.js} +1 -1
- package/dist-app/assets/{claude-code-session-DQRgWy00.js → claude-code-session-w7XeYCbv.js} +1 -1
- package/dist-app/assets/{codex-session--KVj3_vb.js → codex-session-BteJdhnJ.js} +1 -1
- package/dist-app/assets/{dsh-session-6OCSm4h5.js → dsh-session-DtVkAUjy.js} +1 -1
- package/dist-app/assets/{experiment-loop-BfxITu2e.js → experiment-loop-cKs-OaUA.js} +1 -1
- package/dist-app/assets/{index-6m02Pb4Q.js → index-BgFLKHxw.js} +10 -10
- package/dist-app/assets/{index-BH-U0zVI.js → index-CZgf0TxH.js} +1 -1
- package/dist-app/assets/{index-D-BTv0n0.js → index-DbmziCje.js} +3 -3
- package/dist-app/assets/{index-BL39OXsY.js → index-ZY9zV6mj.js} +1 -1
- package/dist-app/assets/{live-mirror-BElcCk_a.js → live-mirror-Cil__utB.js} +2 -2
- package/dist-app/assets/{sensitive-scan-L0rFzufE.js → sensitive-scan-NBqP2Srd.js} +1 -1
- package/dist-app/assets/{session-handoff-CGrowwZp.js → session-handoff-C_88Qy1y.js} +2 -2
- package/dist-app/assets/{shared-CURSZnXt.js → shared-0Cyt1YSM.js} +1 -1
- package/dist-app/assets/{turndown-plugin-gfm.cjs-p3SpZgsj.js → turndown-plugin-gfm.cjs-BkQZDlXD.js} +1 -1
- package/dist-app/assets/{update-check-D5daO3Cz.js → update-check-Ca6SiYKC.js} +1 -1
- package/dist-app/index.html +1 -1
- package/lib/index.js +95 -2
- package/lib/why.mjs +2588 -0
- package/package.json +1 -1
|
@@ -46,7 +46,7 @@ Economist: You analyze through incentives and trade-offs...`,"fanout.confirm":"F
|
|
|
46
46
|
`);m=E.pop()||"";for(const T of E){const w=T.trim();if(!w.startsWith("data: "))continue;const _=w.slice(6);if(_==="[DONE]")continue;let A;try{A=JSON.parse(_)}catch{continue}if(A.error){const M=typeof A.error=="string"?A.error:A.error.message;throw new Error(M||"Upstream stream error")}const C=A.choices?.[0];if(!C)continue;const O=C.delta;O?.content&&(p+=O.content,a(O.content));const D=O?.reasoning??O?.reasoning_content;D&&r(D);for(const M of O?.annotations??[]){const N=M.url_citation;N?.url&&!s.has(N.url)&&s.set(N.url,{title:N.title||N.url,url:N.url,media:"Web"})}C.finish_reason&&(x=C.finish_reason)}}return{text:p,finishReason:x}}async function LB(e,t,n,a,r,s,l,c){const d=E7(n,s),h=_b(e.baseURL)&&c!==!1,m=new Map;let p="",x="";const b=E=>{p+=E,a(E,p)},y=E=>{x+=E,l?.onReasoning?.(E,x)};try{let E=await nw(e,h?`${t}:online`:t,d,b,y,m,r);if(h&&p.length===0&&(E=await nw(e,t,d,b,y,m,r)),p.length===0)throw new Error(`Model produced no text (finish: ${E.finishReason}, model: ${t}${h?" via :online":""})`);return m.size>0&&l?.onSources?.([...m.values()]),p}catch(E){throw k7(E)}}async function jB(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:E7(n,a)})});if(!r.ok){const l=await r.json().catch(()=>null);throw new Error(l?.error?.message||`HTTP ${r.status}`)}return(await r.json()).choices?.[0]?.message?.content??""}catch(r){throw k7(r)}}const PB=`${Rs}/api/claude`,T7=()=>{const e=ai();return e.length>0?e:void 0},zB=`${Rs}/api/stream`,BB=`${Rs}/api/pdf-extract`;async function HB(e){const t=await fetch(BB,{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(bl(n,`HTTP ${t.status}`))}return t.json()}async function UB(e){try{const t=await fetch(`${Rs}/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(bl(n,`HTTP ${t.status}`))}return t.json()}catch(t){throw Ib(t)}}function Ib(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 S7(e,t){if(!t?.length)return t;const n=await Io(),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 Io(),a=e??n?.default??void 0,r=a?n?.models.find(s=>s.id===a):void 0;if(r&&r.vision===!1)throw new Error(Ie("error.textOnlyModelImages"))}async function Do(e,t,n){const a=n||ye.getState().selectedModel||void 0;t=await S7(a,t);const r=Mb();if(r&&a)return await A7(a,t),jB(r,a,e,t);try{const s=await fetch(PB,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({messages:e,images:t?.length?t:void 0,model:n||ye.getState().selectedModel||void 0,providers:T7()})});if(!s.ok){const c=await s.json().catch(()=>({error:"Unknown error"}));throw new Error(bl(c,`HTTP ${s.status}`))}return(await s.json()).text}catch(s){throw Ib(s)}}async function N7(e,t,n,a,r,s,l,c){const d=l||ye.getState().selectedModel||void 0;a=await S7(d,a);let h=!1;const m={...r,onRerouted:(E,T)=>{h=!0,r?.onRerouted?.(E,T)}},p=async(E,T)=>{const w=Mb();return w&&d?(await A7(d,E),r?.onDispatch?.({messages:e,images:E??[],model:d,toolPrefs:s??{},lane:"direct"}),LB(w,d,e,T,n,E,m,s?.web)):(r?.onDispatch?.({messages:e,images:E??[],model:d??"",toolPrefs:s??{},lane:"proxy"}),y(E,T))},x=d?NB(d):void 0,b=!!d&&ai().some(E=>E.models.some(T=>T.id===d));if(a?.length&&d&&b&&x!==!1){const E=d.split("/").pop()??d,T=(_,A)=>{CB(d,_)&&(Kd(ai()).then(hm).catch(()=>{}),Ke("info",qe(Ie(A),{m:E})))};let w=!1;try{const _=await p(a,(A,C)=>{w=!0,t(A,C)});return x===void 0&&!h&&_.trim()&&T(!0,"toast.visionLearnedTrue"),_}catch(_){if(_ instanceof DOMException&&_.name==="AbortError"||w||h)throw _;if(x===!0){const C=_ instanceof Error?_.message:String(_);throw new Error(`${C} ${Ie("error.visionDeclaredHint")}`)}const A=await p(void 0,t);return A.trim()&&T(!1,"toast.visionLearnedFalse"),A}}return p(a,t);async function y(E,T){try{const w=await fetch(zB,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({messages:e,images:E?.length?E:void 0,webSearch:s?.web,scholarSearch:s?.scholar,mcpTools:s?.mcp,...ye.getState().searchEnginePref!=="server"?{searchEngine:ye.getState().searchEnginePref}:{},...ye.getState().anysearchKey?{anysearchKey:ye.getState().anysearchKey}:{},model:l||ye.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(bl(M,`HTTP ${w.status}`))}const _=w.body.getReader(),A=new TextDecoder;let C="",O="",D="";for(;;){const{done:M,value:N}=await _.read();if(M)break;C+=A.decode(N,{stream:!0});const R=C.split(`
|
|
47
47
|
`);C=R.pop()||"";for(const B of R){const H=B.trim();if(!H||!H.startsWith("data: "))continue;const Y=H.slice(6);if(Y!=="[DONE]")try{const Z=JSON.parse(Y);if(Z.error)throw new Error(bl(Z.error,"Upstream stream error"));Z.text&&(O+=Z.text,T(Z.text,O)),Z.reasoning&&(D+=Z.reasoning,m.onReasoning?.(Z.reasoning,D)),Z.tool?.query&&m.onToolCall?.(Z.tool.name,Z.tool.query),Z.gatewaySearch&&m.onGatewaySearch?.(),typeof Z.harnessSession=="string"&&m.onHarnessSession?.(Z.harnessSession,!!Z.continued),Z.harnessTurn?.session&&m.onHarnessTurn?.(Z.harnessTurn),Array.isArray(Z.sources)&&m.onSources?.(Z.sources),Z.rerouted?.to&&(Ke("info",qe(Ie("toast.visionRerouted"),{from:Z.rerouted.from,to:Z.rerouted.to}),7e3),m.onRerouted?.(Z.rerouted.from,Z.rerouted.to)),Z.imageFallback?.model&&(Ke("info",qe(Ie("toast.imagesAsText"),{model:Z.imageFallback.model}),9e3),m.onImageFallback?.(Z.imageFallback.model))}catch(Z){if(Z instanceof Error&&Z.message!==Y)throw Z}}}return O}catch(w){throw Ib(w)}}}const Sx="att-content:",C7=e=>`${Sx}${e}`,_7=e=>e.type==="application/pdf"&&!!e.content&&!e.contentInVault;async function M7(e){return _7(e)?(await zr(C7(e.id),e.content),{...e,content:"",contentInVault:!0}):e}async function I7(e){return e.contentInVault?await xl(C7(e.id))??"":e.content}async function D7(e){const t=[];for(const n of e){const a=n.data.attachments;if(!a?.some(s=>s.contentInVault)){t.push(n);continue}const r=[];for(const s of a){if(!s.contentInVault){r.push(s);continue}const l=await I7(s),c={...s,content:l};delete c.contentInVault,r.push(c)}t.push({...n,data:{...n.data,attachments:r}})}return t}async function Db(e){const t=[];for(const n of e){const a=n.data.attachments;if(!a?.some(_7)){t.push(n);continue}const r=[];for(const s of a)r.push(await M7(s));t.push({...n,data:{...n.data,attachments:r}})}return t}async function FB(e){const t=await h7();let n=0;for(const a of t)typeof a!="string"||!a.startsWith(Sx)||e.has(a.slice(Sx.length))||(await Lc(a),n++);return n}function qB(e){return e.replace(/<script[\s\S]*?<\/script>/gi," ").replace(/<style[\s\S]*?<\/style>/gi," ").replace(/<[^>]+>/g," ").replace(/ /g," ").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/[ \t]+/g," ").replace(/\s*\n\s*(\s*\n\s*)+/g,`
|
|
48
48
|
|
|
49
|
-
`).trim()}const VB=/\.(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,WB=/\.x?html?$/i,GB=/\.(pptx?|key|odp|doc|rtf|odt|xlsx?|numbers|ods)$/i,Cd="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 bc(e){return`${e.name}|${e.size}|${e.content?.substring(0,100)}`}function YB(e){return new Promise(t=>{const n=In(),a=new Date().toISOString(),r=e.type.startsWith("image/"),s=e.type==="application/pdf"||e.name.endsWith(".pdf"),l=e.type==="text/html"||WB.test(e.name),c=e.type.startsWith("text/")||VB.test(e.name),d=e.name.toLowerCase().endsWith(".docx");if(r){const h=new FileReader;h.onload=()=>{const m=h.result.split(",")[1];t({id:n,name:e.name,type:e.type,size:e.size,addedAt:a,content:m,thumbnailUrl:h.result})},h.readAsDataURL(e)}else if(s){const h=new FileReader;h.onload=()=>{const m=h.result.split(",")[1];t({id:n,name:e.name,type:"application/pdf",size:e.size,addedAt:a,content:m})},h.readAsDataURL(e)}else d?e.arrayBuffer().then(async h=>{try{const p=await(await Kt(()=>import("./index-
|
|
49
|
+
`).trim()}const VB=/\.(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,WB=/\.x?html?$/i,GB=/\.(pptx?|key|odp|doc|rtf|odt|xlsx?|numbers|ods)$/i,Cd="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 bc(e){return`${e.name}|${e.size}|${e.content?.substring(0,100)}`}function YB(e){return new Promise(t=>{const n=In(),a=new Date().toISOString(),r=e.type.startsWith("image/"),s=e.type==="application/pdf"||e.name.endsWith(".pdf"),l=e.type==="text/html"||WB.test(e.name),c=e.type.startsWith("text/")||VB.test(e.name),d=e.name.toLowerCase().endsWith(".docx");if(r){const h=new FileReader;h.onload=()=>{const m=h.result.split(",")[1];t({id:n,name:e.name,type:e.type,size:e.size,addedAt:a,content:m,thumbnailUrl:h.result})},h.readAsDataURL(e)}else if(s){const h=new FileReader;h.onload=()=>{const m=h.result.split(",")[1];t({id:n,name:e.name,type:"application/pdf",size:e.size,addedAt:a,content:m})},h.readAsDataURL(e)}else d?e.arrayBuffer().then(async h=>{try{const p=await(await Kt(()=>import("./index-ZY9zV6mj.js").then(x=>x.i),[])).extractRawText({arrayBuffer:h});t({id:n,name:e.name,type:"text/plain",size:e.size,addedAt:a,content:p.value.trim()})}catch{t(null)}}):l?e.text().then(h=>{t({id:n,name:e.name,type:"text/html",size:e.size,addedAt:a,content:h})}):c?e.text().then(h=>{t({id:n,name:e.name,type:e.type||"text/plain",size:e.size,addedAt:a,content:h})}):t(null)})}async function aw(e){const[t,n]=await Promise.all([Kt(()=>import("./pdf-gh-BrLFn.js"),[]),Kt(()=>import("./pdf.worker.min-C_APr3k7.js"),[])]);t.GlobalWorkerOptions.workerSrc=n.default;const a=Uint8Array.from(atob(e),r=>r.charCodeAt(0));return t.getDocument({data:a,verbosity:0}).promise}const $B=150;async function rw(e){const t=$B/72,n=[];for(let a=1;a<=e.numPages;a++){const r=document.createElement("canvas");try{const s=await e.getPage(a),l=s.getViewport({scale:t});r.width=Math.ceil(l.width),r.height=Math.ceil(l.height);const c=r.getContext("2d");if(!c)throw new Error("no 2d context");await s.render({canvasContext:c,viewport:l}).promise}catch{r.width=8,r.height=8}n.push(r.toDataURL("image/png").split(",")[1])}return n}async function Xd(e,t){if(GB.test(e.name)){Ke("info",`${e.name}: ${Ie("content.officeExportHint")}`);return}const n=await YB(e);if(!n)return;if(n.type==="text/html"){t.add({...n,isExtracting:!0});try{const{extractHtmlMaterial:r}=await Kt(async()=>{const{extractHtmlMaterial:l}=await Promise.resolve().then(()=>AN);return{extractHtmlMaterial:l}},void 0),s=await r(n.content);t.update(n.id,{extractedText:s.markdown,numPages:s.numPages,isExtracting:!1})}catch{t.update(n.id,{extractedText:qB(n.content),isExtracting:!1})}return}if(n.type!=="application/pdf"){t.add(n);return}const a=await M7(n);t.add({...a,isExtracting:!0});try{const r=await HB(n.content);if(!r.numPages&&!r.text?.trim())throw new Error("empty extraction result");const s=r.numPages||0;let l=r.images;if(!l?.length)try{const c=await aw(n.content);l=await rw(c),c.destroy()}catch{l=void 0}t.update(n.id,{extractedText:r.text,pageImages:l?.length?l:void 0,numPages:s,renderMode:s>F5?"text-only":"full",isExtracting:!1})}catch{try{const r=await aw(n.content),s=[];for(let c=1;c<=r.numPages;c++)try{const h=await(await r.getPage(c)).getTextContent();s.push(h.items.map(m=>"str"in m?m.str:"").join(" "))}catch{s.push("")}let l;try{l=await rw(r)}catch{l=void 0}r.destroy(),t.update(n.id,{extractedText:s.join(`
|
|
50
50
|
|
|
51
51
|
`).trim(),pageImages:l?.length?l:void 0,numPages:r.numPages,renderMode:r.numPages>F5?"text-only":"full",isExtracting:!1})}catch{t.update(n.id,{isExtracting:!1})}}}const zu="[*_`~()#>\\[\\]|-]*",KB="\\s+(?:(?:\\d{1,3}[.)]|[-*+>|]|#{1,6}|[-:|]{3,})\\s+)*";function Ob(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(`${zu}${KB}${zu}${s}`):n.push(`${zu}${s}`),a=!1}try{return new RegExp(zu+n.join("")+zu,"g")}catch{return null}}function XB(e,t){const n=Ob(t);return n?n.test(e):!1}function sf(e,t){const n=e??[],a=n.filter(r=>XB(t,r.text));return a.length===n.length?n:a}function iw(e){const t=e.data.question.replace(/\s+/g," ").trim();return t.length>60?`${t.slice(0,60)}…`:t}function O7(e){const t=e.data.highlightMode||"off",n=e.data.highlights||[];if(t==="filter"&&n.length>0)return n.map(a=>a.text).join(`
|
|
52
52
|
|
|
@@ -58,7 +58,7 @@ ${Y}`:`[File: ${B.name} — HTML with no extractable text yet]`}),h.push(R(B))}e
|
|
|
58
58
|
${B.content}`}),h.push(R(B))}};for(const M of E)if(!M.data.archived&&(O(M,"material"),M.data.question)){const N=M.data.stepKind==="note"?`[Note]
|
|
59
59
|
${M.data.question}`:M.data.stepKind==="link"?`[Link snapshot: ${M.data.linkUrl??""} @ ${(M.data.linkFetchedAt??"").slice(0,10)}]
|
|
60
60
|
${M.data.question}`:M.data.question;c.push({role:"user",content:N}),h.push({layer:"material",nodeId:M.id,part:"question"})}b("material");for(const M of T)M.source.data.archived||(c.push({role:"user",content:_d(M)}),h.push({layer:"reference",refSourceId:M.source.id,part:"reference"}));b("reference");for(const M of w)if(!M.data.archived&&(O(M,"chain"),M.data.question&&(c.push({role:"user",content:M.data.question}),h.push({layer:"chain",nodeId:M.id,part:"question"})),M.data.response)){const N=O7(M);c.push({role:"assistant",content:y.has(M.id)?`${ZB}
|
|
61
|
-
${N}`:N}),h.push({layer:"chain",nodeId:M.id,part:"response"})}a&&(c.push({role:"user",content:`[Regarding this passage: "${a}"]`}),h.push({layer:"branch",nodeId:e,part:"passage"})),b("chain");const D=L7(w,t);return D&&(c.unshift({role:"system",content:D}),h.unshift({layer:"system",part:"role"})),{messages:c,images:d,layerTokens:p,sources:h,imageSources:m}}function ow(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 lw(e,t){if(!t)return;const n=e.filter(a=>a.role!=="system");n.unshift({role:"system",content:t}),e.length=0,e.push(...n)}function Dr(){return ye.getState().condenseRun.status!=="building"?!1:(Ke("info",Ie("condense.editLocked")),!0)}const eH=(e,t)=>({history:[{nodes:[],edges:[]}],historyIndex:0,pushHistory:()=>{const{nodes:n,edges:a,history:r,historyIndex:s}=t(),l=r.slice(0,s+1);l.push({nodes:n,edges:a}),l.length>vB&&l.shift(),e({history:l,historyIndex:l.length-1})},undo:()=>{if(Dr())return;const{history:n,historyIndex:a}=t();if(a<=0)return;const r=n[a-1];e({nodes:r.nodes,edges:r.edges,historyIndex:a-1}),t().logEvent("undo")},redo:()=>{if(Dr())return;const{history:n,historyIndex:a}=t();if(a>=n.length-1)return;const r=n[a+1];e({nodes:r.nodes,edges:r.edges,historyIndex:a+1}),t().logEvent("redo")}});function j7(e){if(e.data.isCollapsed)return wB;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 yo(e){return Math.max(e.measured?.height??0,j7(e))}function tH(e,t){const n=e.filter(r=>r.data.stepKind==="note"&&r.data.importSource&&t.some(s=>s.target===r.id));if(n.length===0)return t;let a=[...t];for(const r of n){const s=a.filter(c=>c.target===r.id),l=a.find(c=>c.source===r.id);if(a=a.filter(c=>c.target!==r.id),!!l)for(const c of s)a.some(d=>d.source===c.source&&d.target===l.target)||a.push({...c,target:l.target})}return a}function nr(e,t){if(e.length===0)return e;const n=new Set(e.filter(ae=>["note","file","link","frame"].includes(ae.data.stepKind??"")).map(ae=>ae.id)),a=e.filter(ae=>!n.has(ae.id)),r=t.filter(ae=>!n.has(ae.source)&&!n.has(ae.target)),s=q5,l=V5,c=W5,d=24,h=r.filter(ae=>!ae.data?.isCrossLink),m=new Set(h.map(ae=>ae.target));for(const ae of r)ae.data?.isCrossLink&&!ae.data?.isWatch&&!m.has(ae.target)&&(h.push(ae),m.add(ae.target));const p=new Set(h.map(ae=>ae.target)),x=a.filter(ae=>!p.has(ae.id)),b=new Map;for(const ae of h){const ve=b.get(ae.target)||[];ve.push(ae.source),b.set(ae.target,ve)}const y=new Map,E=new Map;for(const ae of x){const ve=t.filter(be=>be.target===ae.id&&!be.data?.isCrossLink&&n.has(be.source)).map(be=>e.find(Le=>Le.id===be.source)).filter(be=>!!be);if(ve.length===0)continue;const me=ve.reduce((be,Le)=>be.position.y+yo(be)>Le.position.y+yo(Le)?be:Le),ke=ve.reduce((be,Le)=>be+Le.position.x,0)/ve.length,re=E.get(me.id)??0;E.set(me.id,re+1),y.set(ae.id,{x:ke-60+re*(q5+V5),y:me.position.y+yo(me)+W5})}const T=new Map;for(const ae of h){const ve=T.get(ae.source)||[];ve.push(ae.target),T.set(ae.source,ve)}const w=(ae,ve)=>`${ae}\0${ve}`,_=new Set(r.filter(ae=>ae.data?.isBranchFromSelection).map(ae=>w(ae.source,ae.target)));function A(ae,ve){const me=(T.get(ae)||[]).filter(be=>(ve.get(be)??ae)===ae),ke=me.filter(be=>!_.has(w(ae,be))),re=me.filter(be=>_.has(w(ae,be)));return{continuation:ke[0]??null,regenerates:ke.slice(1),explores:re}}const C=1e5;function O(ae){const ve=new Map;let me=0,ke=C;const re=new Map,be=Oe=>re.get(Oe)??Oe*(s+l);function Le(Oe,je){if(ve.has(Oe))return;ve.set(Oe,je);const{continuation:ze,regenerates:rt,explores:ot}=A(Oe,ae);ze&&Le(ze,je);for(let kt=0;kt<rt.length;kt++){let ht;je>=C?(ht=ke++,re.set(ht,be(je)+(kt+1)*(s+l))):(ht=je+1+kt,me=Math.max(me,ht+1)),Le(rt[kt],ht)}let Xe=0;for(const kt of ot){let ht;je>=C?(ht=ke++,re.set(ht,be(je)+(rt.length+1+Xe)*(s+l)),Xe++):(ht=me,me++),Le(kt,ht)}}for(const Oe of x){const je=y.get(Oe.id);if(je){const ze=ke++;re.set(ze,je.x),Le(Oe.id,ze)}else{const ze=me;me++,Le(Oe.id,ze)}}for(let Oe=0;Oe<a.length;Oe++){let je=!1;for(const ze of a){if(ve.has(ze.id))continue;const rt=(b.get(ze.id)||[]).map(ot=>ve.get(ot)).filter(ot=>ot!==void 0).sort((ot,Xe)=>ot-Xe);rt.length&&(Le(ze.id,rt[Math.floor((rt.length-1)/2)]),je=!0)}if(!je)break}return{nodeColumn:ve,colX:be}}const D=O(new Map),M=new Map;for(const[ae,ve]of b){if(ve.length<2)continue;const me=ve.filter(Le=>D.nodeColumn.has(Le)),ke=me.filter(Le=>!_.has(w(Le,ae))),re=ke.length?ke:me;if(!re.length)continue;const be=[...re].sort((Le,Oe)=>D.colX(D.nodeColumn.get(Le))-D.colX(D.nodeColumn.get(Oe))||(Le<Oe?-1:Le>Oe?1:0));M.set(ae,be[Math.floor((be.length-1)/2)])}const{nodeColumn:N,colX:R}=O(M),B=new Map;for(const ae of a)B.set(ae.id,yo(ae));const H=new Map,Y=new Set,Z=[...x.map(ae=>ae.id)];for(const ae of Z){const ve=N.get(ae)??0,me=y.get(ae);H.set(ae,{x:R(ve),y:me?.y??0}),Y.add(ae)}for(;Z.length>0;){const ae=Z.shift(),ve=H.get(ae),me=B.get(ae)||220,{continuation:ke,regenerates:re,explores:be}=A(ae,M);if(ke&&!Y.has(ke)){Y.add(ke);const Oe=N.get(ke)??0;H.set(ke,{x:R(Oe),y:ve.y+me+c}),Z.push(ke)}const Le=ve.y+me+c;for(const Oe of re){if(Y.has(Oe))continue;Y.add(Oe);const je=N.get(Oe)??0;H.set(Oe,{x:R(je),y:Le}),Z.push(Oe)}for(const Oe of be){if(Y.has(Oe))continue;Y.add(Oe);const je=N.get(Oe)??0;H.set(Oe,{x:R(je),y:ve.y+me*.25}),Z.push(Oe)}}for(let ae=0;ae<a.length;ae++){let ve=!1;for(const me of a){if(H.has(me.id))continue;const ke=(b.get(me.id)||[]).filter(be=>H.has(be));if(!ke.length)continue;const re=Math.max(...ke.map(be=>H.get(be).y+(B.get(be)||220)));H.set(me.id,{x:R(N.get(me.id)??0),y:re+c}),ve=!0}if(!ve)break}for(const ae of a)H.has(ae.id)||H.set(ae.id,{x:0,y:0});for(let ae=0;ae<5;ae++){let ve=!1;for(const me of a){const ke=H.get(me.id);if(!ke)continue;const re=(b.get(me.id)||[]).filter(je=>H.has(je));if(re.length<2)continue;const be=re.filter(je=>!_.has(`${je}\0${me.id}`)),Le=re.filter(je=>_.has(`${je}\0${me.id}`));let Oe=-1/0;for(const je of be)Oe=Math.max(Oe,H.get(je).y+(B.get(je)||220)+c);for(const je of Le)Oe=Math.max(Oe,H.get(je).y);if(Oe>-1/0&&ke.y<Oe){const je=Oe-ke.y;ke.y=Oe;for(const ze of new Set(ko(me.id,h))){const rt=H.get(ze);rt&&(rt.y+=je)}ve=!0}}if(!ve)break}const q=new Map;for(const ae of a){const ve=N.get(ae.id)??0,me=q.get(ve)||[];me.push(ae.id),q.set(ve,me)}for(let ae=0;ae<5;ae++){let ve=!1;for(const[,me]of q){me.sort((ke,re)=>H.get(ke).y-H.get(re).y);for(let ke=1;ke<me.length;ke++){const re=me[ke-1],be=me[ke],Le=H.get(re),Oe=H.get(be),je=B.get(re)||220,ze=Le.y+je+d;if(Oe.y<ze){const rt=ze-Oe.y;Oe.y=ze,ve=!0;for(const ot of new Set(ko(be,h))){const Xe=H.get(ot);Xe&&(Xe.y+=rt)}}}}if(!ve)break}const K=8e3,U=180,G=e.filter(ae=>ae.data.stepKind==="note"&&ae.data.importSource),ne=new Set(t.filter(ae=>G.some(ve=>ve.id===ae.source)).map(ae=>ae.target));for(const ae of x){const ve=[];let me=ae.id,ke=!0;for(;me;){ve.push(me);const ot=T.get(me)||[];if(ot.length>1){ke=!1;break}me=ot[0]}if(!ke||ve.length<8)continue;const re=new Set(ve),be=H.get(ve[0]),Le=ve[ve.length-1];if(H.get(Le).y+(B.get(Le)||220)-be.y<=K||a.some(ot=>!re.has(ot.id)&&H.get(ot.id).x>be.x+s/2))continue;let ze=0,rt=be.y;for(const ot of ve){const Xe=B.get(ot)||220,kt=rt-be.y,ht=kt+Xe>K,at=ne.has(ot)&&kt>K*.6;(ht||at)&&rt!==be.y&&(ze++,rt=be.y);const wt=H.get(ot);wt.x=be.x+ze*(s+U),wt.y=rt,rt+=Xe+c}}const X=a.map(ae=>{const ve=H.get(ae.id);return{x:ve.x,y:ve.y,w:s,h:B.get(ae.id)||220}}),P=460,F=130,J=(ae,ve)=>X.some(me=>ae<me.x+me.w&&ae+P>me.x&&ve<me.y+me.h&&ve+F>me.y),W=new Map;for(const ae of G){const ve=t.find(be=>be.source===ae.id)?.target,me=ve?H.get(ve):void 0;if(!me)continue;let ke=me.x-520,re=me.y;if(J(ke,re)&&(ke=me.x,re=me.y-F-40),J(ke,re)){const be=Math.round(me.x),Le=Math.min(...a.filter(je=>Math.round(H.get(je.id).x)===be).map(je=>H.get(je.id).y)),Oe=W.get(be)??0;W.set(be,Oe+1),ke=me.x,re=Le-F-40-Oe*(F+30)}H.set(ae.id,{x:ke,y:re})}return e.map(ae=>{const ve=H.get(ae.id);return ve?{...ae,position:ve}:ae})}const nH=(e,t)=>({nodes:[],edges:[],selectedNodeId:null,selectedNodeIds:[],setNodes:n=>e({nodes:n}),setEdges:n=>e({edges:n}),setSelectedNodeId:n=>e({selectedNodeId:n,selectedNodeIds:n?[n]:[]}),setSelectedNodeIds:n=>e({selectedNodeIds:n,selectedNodeId:n.length===1?n[0]:null}),deleteNode:n=>{if(Dr())return;t().logEvent("delete",n,{n:1}),t().pushHistory();const{edges:a}=t(),r=ko(n,a),s=new Set([n,...r]);e(l=>({nodes:l.nodes.filter(c=>!s.has(c.id)),edges:l.edges.filter(c=>!s.has(c.source)&&!s.has(c.target))})),t().pushHistory(),Kt(()=>import("./canonical-DbPqsMYz.js"),[]).then(l=>l.unsubscribeOrphanedSessions())},deleteEdges:n=>{if(Dr())return;t().logEvent("disconnect",n[0],{n:n.length});const a=new Set(n);t().edges.some(r=>a.has(r.id))&&(t().pushHistory(),e(r=>({edges:r.edges.filter(s=>!a.has(s.id))})),t().pushHistory())},editResponse:(n,a)=>{if(Dr())return;t().logEvent("edit-response",n,{chars:a.length}),t().pushHistory();const r=$n(t().nodes.find(s=>s.id===n)?.data.question+a||a);e(s=>({nodes:s.nodes.map(l=>l.id===n?{...l,data:{...l.data,response:a,responses:l.data.responses.map((c,d)=>d===l.data.responseIndex?a:c),summaries:l.data.summaries?.map((c,d)=>d===l.data.responseIndex?void 0:c),summaryTypes:l.data.summaryTypes?.map((c,d)=>d===l.data.responseIndex?void 0:c),editedAts:l.data.responses.map((c,d)=>d===l.data.responseIndex?new Date().toISOString():l.data.editedAts?.[d]),highlights:sf(l.data.highlights,a),isEditingResponse:!1,tokenCount:r}}:l)})),t().pushHistory()},toggleCollapse:n=>{const a=t().nodes.find(h=>h.id===n);if(!a)return;const r=yo(a),l=j7({...a,data:{...a.data,isCollapsed:!a.data.isCollapsed}})-r,c=ko(n,t().edges),d=new Set(c);e(h=>({nodes:h.nodes.map(m=>m.id===n?{...m,data:{...m.data,isCollapsed:!m.data.isCollapsed}}:d.has(m.id)?{...m,position:{...m.position,y:m.position.y+l}}:m)}))},setEditing:(n,a)=>{a&&Dr()||e(r=>({nodes:r.nodes.map(s=>s.id===n?{...s,data:{...s.data,isEditing:a}}:s)}))},setEditingResponse:(n,a)=>{a&&Dr()||e(r=>({nodes:r.nodes.map(s=>s.id===n?{...s,data:{...s.data,isEditingResponse:a}}:s)}))},duplicateNode:n=>{const a=t().nodes.find(m=>m.id===n);if(!a)return;t().pushHistory();const r=In(),s={id:r,type:"thought",position:{x:0,y:0},dragHandle:".drag-handle",data:{...a.data,isCollapsed:!0,isEditing:!1,isEditingResponse:!1,isLoading:!1,highlights:a.data.highlights.map(m=>({...m,id:In()}))}},l=t().edges.find(m=>m.target===n),c=l?{...l,id:`edge-${l.source}-${r}`,target:r}:null,d=c?[...t().edges,c]:t().edges,h=nr([...t().nodes,s],d);e({nodes:h,edges:d,selectedNodeId:r}),t().pushHistory()},addCrossLink:(n,a)=>{const{edges:r,nodes:s}=t();if(r.some(x=>x.source===n&&x.target===a))return;const c=s.find(x=>x.id===n);if(c&&["note","file","link"].includes(c.data.stepKind??"")){t().pushHistory();const x={id:`edge-${n}-${a}`,source:n,sourceHandle:"continue",target:a,targetHandle:"top",type:"smoothstep",style:{stroke:nt.accent,strokeDasharray:"8 4",strokeWidth:2},animated:!0,data:{isCrossLink:!0,createdAt:new Date().toISOString()}};e(y=>({edges:[...y.edges,x]})),t().logEvent("connect",x.id),t().setEdgeStructural(x.id,!0);const b=t().edges.find(y=>y.id===x.id);if(b&&!b.data?.isCrossLink){const E=yr(n,t().nodes,t().edges).messages.reduce((T,w)=>T+$n(w.content),0);Ke("success",qe(Ie("edge.materialWiredFull"),{n:E.toLocaleString()}),8e3,{label:Ie("edge.materialMakeQuote"),run:()=>t().setEdgeStructural(x.id,!1)})}return}t().pushHistory();const d=s.find(x=>x.id===n),h=s.find(x=>x.id===a),m=!!d&&!!h&&h.position.y>d.position.y+60&&Math.abs(h.position.x-d.position.x)<320,p={id:`crosslink-${n}-${a}`,source:n,sourceHandle:m?"continue":"branch",target:a,targetHandle:m?"top":"left",type:"smoothstep",style:{stroke:nt.accent,strokeDasharray:"8 4",strokeWidth:2},animated:!0,data:{isCrossLink:!0,createdAt:new Date().toISOString()}};if(e(x=>({edges:[...x.edges,p]})),t().logEvent("connect",p.id),t().pushHistory(),d&&!["note","file","link"].includes(d.data.stepKind??"")){const{ordered:x}=Br(n,s,r.filter(y=>!y.data?.isCrossLink)),b=x.filter(y=>y.id!==n&&!["note","file","link"].includes(y.data.stepKind??""));if(b.length>0){const y=$n(_d({source:d,depth:"quote",chain:b})),T=yr(n,s,r).messages.reduce((w,_)=>w+$n(_.content),0)+$n(d.data.question+d.data.response);Ke("info",qe(Ie("edge.linkedQuote"),{n:y}),8e3,{label:qe(Ie("edge.makeFull"),{m:T}),run:()=>t().setEdgeStructural(p.id,!0)})}}},staleIds:[],recomputeStaleness:()=>{const{nodes:n,edges:a}=t(),r=[];for(const l of n)!l.data.lastContextHash||!l.data.response||["note","file","link","frame"].includes(l.data.stepKind??"")||R7(l.id,n,a)!==l.data.lastContextHash&&r.push(l.id);const s=t().staleIds;s.length===r.length&&s.every((l,c)=>l===r[c])||e({staleIds:r})},setEdgeStructural:(n,a)=>{const{nodes:r,edges:s}=t(),l=s.find(c=>c.id===n);if(l){if(a){const c=s.filter(h=>!h.data?.isCrossLink),{ordered:d}=Br(l.source,r,c);if(d.some(h=>h.id===l.target)){Ke("error",Ie("edge.cycleBlocked"));return}}t().pushHistory(),t().logEvent(a?"connect":"disconnect",n,{convert:!0}),e(c=>({edges:c.edges.map(d=>{if(d.id!==n)return d;if(a){const h={...d.data??{}};return delete h.isCrossLink,delete h.contextDepth,delete h.isWatch,{...d,sourceHandle:"continue",targetHandle:"top",animated:!1,style:{stroke:nt.accent,strokeWidth:2},markerEnd:{type:"arrowclosed",color:nt.accent,width:18,height:18},data:h}}return{...d,animated:!0,style:{stroke:nt.accent,strokeDasharray:"8 4",strokeWidth:2},markerEnd:{type:"arrowclosed",color:nt.accent,width:18,height:18},data:{...d.data??{},isCrossLink:!0,contextDepth:void 0}}})})),e(c=>({nodes:nr(c.nodes,c.edges)})),t().pushHistory()}},setCrossLinkDepth:(n,a)=>{t().pushHistory(),e(r=>({edges:r.edges.map(s=>s.id!==n||!s.data?.isCrossLink?s:{...s,style:{...s.style,strokeDasharray:a==="full"?"12 3":"8 4",strokeWidth:a==="full"?3:2},data:{...s.data,contextDepth:a==="full"?"full":void 0}})})),t().pushHistory()},navigateVersion:(n,a)=>{e(r=>({nodes:r.nodes.map(s=>{if(s.id!==n)return s;const{responses:l,responseIndex:c}=s.data;let d=a==="prev"?c-1:c+1;return d<0&&(d=l.length-1),d>=l.length&&(d=0),{...s,data:{...s.data,responseIndex:d,response:l[d],question:s.data.questions?.[d]??s.data.question,generationFailed:void 0,highlights:sf(s.data.highlights,l[d])}}})}))},deleteVersion:(n,a)=>{t().pushHistory(),e(r=>({nodes:r.nodes.map(s=>{if(s.id!==n)return s;const l=s.data.responses.filter((d,h)=>h!==a);if(l.length===0)return s;const c=Math.min(s.data.responseIndex,l.length-1);return{...s,data:{...s.data,responses:l,responseIndex:c,response:l[c],questions:s.data.questions?.filter((d,h)=>h!==a),question:s.data.questions?.filter((d,h)=>h!==a)[c]??s.data.question,summaries:s.data.summaries?.filter((d,h)=>h!==a),generatedBy:s.data.generatedBy?.filter((d,h)=>h!==a),summaryTypes:s.data.summaryTypes?.filter((d,h)=>h!==a),reasonings:s.data.reasonings?.filter((d,h)=>h!==a),generatedAts:s.data.generatedAts?.filter((d,h)=>h!==a),editedAts:s.data.editedAts?.filter((d,h)=>h!==a),highlights:sf(s.data.highlights,l[c])}}})})),t().pushHistory()},relayout:()=>{Dr()||(t().pushHistory(),e(n=>{const a=tH(n.nodes,n.edges);return{nodes:nr(n.nodes,a),edges:a}}),t().pushHistory())},setArchived:(n,a)=>{const r=new Set(n);t().pushHistory(),t().logEvent(a?"archive":"unarchive",n[0],{n:n.length}),e(s=>({nodes:s.nodes.map(l=>r.has(l.id)?{...l,data:{...l.data,archived:a||void 0,archivedAt:a?new Date().toISOString():void 0}}:l)})),t().pushHistory()},setNodeModel:(n,a)=>{e(r=>({nodes:r.nodes.map(s=>s.id===n?{...s,data:{...s.data,model:a}}:s)}))},alignSelection:n=>{if(n.length<2)return;const a=new Set(n),{nodes:r,edges:s}=t(),l=new Map,c=s.filter(b=>!b.data?.isWatch),d=(b,y)=>{if(l.has(b))return l.get(b);if(y.has(b))return 0;y.add(b);const E=c.filter(w=>w.target===b&&a.has(w.source)),T=E.length===0?0:1+Math.max(...E.map(w=>d(w.source,y)));return l.set(b,T),T},h=n.map(b=>r.find(y=>y.id===b)).filter(b=>!!b).sort((b,y)=>d(b.id,new Set)-d(y.id,new Set)||b.position.y-y.position.y);t().pushHistory();const m=h[0].position;let p=m.y;const x=new Map;for(const b of h)x.set(b.id,{x:m.x,y:p}),p+=yo(b)+40;e(b=>({nodes:b.nodes.map(y=>{const E=x.get(y.id);return E?{...y,position:E}:y})})),t().pushHistory()},batchDelete:n=>{if(Dr())return;t().logEvent("delete",n[0],{n:n.length}),t().pushHistory();const a=new Set(n);e(r=>({nodes:r.nodes.filter(s=>!a.has(s.id)),edges:r.edges.filter(s=>!a.has(s.source)&&!a.has(s.target)),selectedNodeId:null,selectedNodeIds:[]})),t().pushHistory(),Kt(()=>import("./canonical-DbPqsMYz.js"),[]).then(r=>r.unsubscribeOrphanedSessions())},duplicateSelection:n=>{const{nodes:a,edges:r}=t(),s=new Set(n),l=a.filter(M=>s.has(M.id));if(l.length===0)return;t().pushHistory();const c=M=>({x:M.position.x,y:M.position.y,w:M.measured?.width??M.width??520,h:M.measured?.height??M.height??yo(M)}),d=l.map(c),h={x:Math.min(...d.map(M=>M.x)),y:Math.min(...d.map(M=>M.y)),right:Math.max(...d.map(M=>M.x+M.w)),bottom:Math.max(...d.map(M=>M.y+M.h))},m=80,p=h.right-h.x+m,x=h.bottom-h.y+m,b=[];for(let M=1;M<=6;M++)b.push({dx:M*p,dy:0},{dx:0,dy:M*x},{dx:M*p,dy:M*x});const y=a.filter(M=>M.data.stepKind!=="frame").map(c),E=(M,N)=>M.x<N.x+N.w&&M.x+M.w>N.x&&M.y<N.y+N.h&&M.y+M.h>N.y,T=b.find(M=>!d.some(N=>y.some(R=>E({...N,x:N.x+M.dx,y:N.y+M.dy},R))))??{dx:p,dy:x},w=new Map,_=new Map;for(const M of l){w.set(M.id,In());for(const N of M.data.attachments??[])_.set(N.id,In())}const A=M=>(M??[]).map(N=>_.get(N)??N),C=l.map(M=>({...M,id:w.get(M.id),position:{x:M.position.x+T.dx,y:M.position.y+T.dy},selected:!0,data:{...M.data,attachments:(M.data.attachments??[]).map(N=>({...N,id:_.get(N.id)})),excludedAttachmentIds:A(M.data.excludedAttachmentIds),includedAttachmentIds:A(M.data.includedAttachmentIds),digestOf:M.data.digestOf?_.get(M.data.digestOf)??M.data.digestOf:void 0,highlights:(M.data.highlights??[]).map(N=>({...N,id:In()})),isEditing:!1,isEditingResponse:!1,isLoading:!1}})),O=r.filter(M=>s.has(M.source)&&s.has(M.target)).map(M=>({...M,id:`edge-${w.get(M.source)}-${w.get(M.target)}`,source:w.get(M.source),target:w.get(M.target),data:M.data?{...M.data}:M.data})),D=C.map(M=>M.id);e(M=>({nodes:[...M.nodes.map(N=>N.selected?{...N,selected:!1}:N),...C],edges:[...M.edges,...O],selectedNodeId:D.length===1?D[0]:null,selectedNodeIds:D})),t().pushHistory()}});function Rb(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 _f(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 aH(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:bc(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 rH(e,t){return`sha256:${await _f(Rb(aH(e,t)))}`}function iH(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 Iae(e,t,n,a){const r=yr(e,t,n,a.branchContext,void 0,void 0,a.staleIds),s=t.find(x=>x.id===e),l=r.messages.map((x,b)=>{const y=r.sources[b]??{layer:"chain"};return{id:`item_${String(b+1).padStart(3,"0")}`,kind:"message",role:x.role,content:[{type:"text",text:x.content}],source:{layer:y.layer,part:y.part,node_id:y.nodeId??y.refSourceId,attachment_id:y.attachmentId},selection:{mode:"full",reason:`structural-${y.layer}`}}}),c=new Map,d=(x,b)=>{if(!x||!b||c.has(b))return;const y=t.find(T=>T.id===x),E=y?.data.attachments?.find(T=>T.id===b);!y||!E||c.set(b,{id:b,kind:E.type.startsWith("image/")?"image":"document",name:E.name,mime_type:E.type,size:E.size,fingerprint:bc(E),model_projection:{mode:iH(E)},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 rH(t,n),target_node_id:e},intent:{task:a.task??s?.data.question??"",language:a.language??null},context:{messages:l,materials:[...c.values()],references:h},execution_hints:{preferred_model:a.preferredModel??s?.data.model??null,required_tools:[],required_mcp_servers:[]},budget:{estimated_tokens:r.messages.reduce((x,b)=>x+$n(b.content),0),limit:null,truncation:"none"}},p=await _f(Rb(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 ic="dsh-sessions",o1="/session.jsonl.zstd",sH=1500,oH=2500;let Ax=null;function lH(e){if(window.desktopSessions)return;const t=e.replace(/\/+$/,""),n=async O=>{const D=await fetch(t+O,{credentials:"same-origin"});if(!D.ok)throw new Error(`${O}: ${D.status}`);return D.json()},a=async O=>{const D=await fetch(t+O,{credentials:"same-origin"});if(!D.ok)throw new Error(`${O}: ${D.status}`);return D.text()},r=new Map,s=O=>`${O}${o1}`,l=(O,D)=>{const M=O.indexOf(`
|
|
61
|
+
${N}`:N}),h.push({layer:"chain",nodeId:M.id,part:"response"})}a&&(c.push({role:"user",content:`[Regarding this passage: "${a}"]`}),h.push({layer:"branch",nodeId:e,part:"passage"})),b("chain");const D=L7(w,t);return D&&(c.unshift({role:"system",content:D}),h.unshift({layer:"system",part:"role"})),{messages:c,images:d,layerTokens:p,sources:h,imageSources:m}}function ow(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 lw(e,t){if(!t)return;const n=e.filter(a=>a.role!=="system");n.unshift({role:"system",content:t}),e.length=0,e.push(...n)}function Dr(){return ye.getState().condenseRun.status!=="building"?!1:(Ke("info",Ie("condense.editLocked")),!0)}const eH=(e,t)=>({history:[{nodes:[],edges:[]}],historyIndex:0,pushHistory:()=>{const{nodes:n,edges:a,history:r,historyIndex:s}=t(),l=r.slice(0,s+1);l.push({nodes:n,edges:a}),l.length>vB&&l.shift(),e({history:l,historyIndex:l.length-1})},undo:()=>{if(Dr())return;const{history:n,historyIndex:a}=t();if(a<=0)return;const r=n[a-1];e({nodes:r.nodes,edges:r.edges,historyIndex:a-1}),t().logEvent("undo")},redo:()=>{if(Dr())return;const{history:n,historyIndex:a}=t();if(a>=n.length-1)return;const r=n[a+1];e({nodes:r.nodes,edges:r.edges,historyIndex:a+1}),t().logEvent("redo")}});function j7(e){if(e.data.isCollapsed)return wB;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 yo(e){return Math.max(e.measured?.height??0,j7(e))}function tH(e,t){const n=e.filter(r=>r.data.stepKind==="note"&&r.data.importSource&&t.some(s=>s.target===r.id));if(n.length===0)return t;let a=[...t];for(const r of n){const s=a.filter(c=>c.target===r.id),l=a.find(c=>c.source===r.id);if(a=a.filter(c=>c.target!==r.id),!!l)for(const c of s)a.some(d=>d.source===c.source&&d.target===l.target)||a.push({...c,target:l.target})}return a}function nr(e,t){if(e.length===0)return e;const n=new Set(e.filter(ae=>["note","file","link","frame"].includes(ae.data.stepKind??"")).map(ae=>ae.id)),a=e.filter(ae=>!n.has(ae.id)),r=t.filter(ae=>!n.has(ae.source)&&!n.has(ae.target)),s=q5,l=V5,c=W5,d=24,h=r.filter(ae=>!ae.data?.isCrossLink),m=new Set(h.map(ae=>ae.target));for(const ae of r)ae.data?.isCrossLink&&!ae.data?.isWatch&&!m.has(ae.target)&&(h.push(ae),m.add(ae.target));const p=new Set(h.map(ae=>ae.target)),x=a.filter(ae=>!p.has(ae.id)),b=new Map;for(const ae of h){const ve=b.get(ae.target)||[];ve.push(ae.source),b.set(ae.target,ve)}const y=new Map,E=new Map;for(const ae of x){const ve=t.filter(be=>be.target===ae.id&&!be.data?.isCrossLink&&n.has(be.source)).map(be=>e.find(Le=>Le.id===be.source)).filter(be=>!!be);if(ve.length===0)continue;const me=ve.reduce((be,Le)=>be.position.y+yo(be)>Le.position.y+yo(Le)?be:Le),ke=ve.reduce((be,Le)=>be+Le.position.x,0)/ve.length,re=E.get(me.id)??0;E.set(me.id,re+1),y.set(ae.id,{x:ke-60+re*(q5+V5),y:me.position.y+yo(me)+W5})}const T=new Map;for(const ae of h){const ve=T.get(ae.source)||[];ve.push(ae.target),T.set(ae.source,ve)}const w=(ae,ve)=>`${ae}\0${ve}`,_=new Set(r.filter(ae=>ae.data?.isBranchFromSelection).map(ae=>w(ae.source,ae.target)));function A(ae,ve){const me=(T.get(ae)||[]).filter(be=>(ve.get(be)??ae)===ae),ke=me.filter(be=>!_.has(w(ae,be))),re=me.filter(be=>_.has(w(ae,be)));return{continuation:ke[0]??null,regenerates:ke.slice(1),explores:re}}const C=1e5;function O(ae){const ve=new Map;let me=0,ke=C;const re=new Map,be=Oe=>re.get(Oe)??Oe*(s+l);function Le(Oe,je){if(ve.has(Oe))return;ve.set(Oe,je);const{continuation:ze,regenerates:rt,explores:ot}=A(Oe,ae);ze&&Le(ze,je);for(let kt=0;kt<rt.length;kt++){let ht;je>=C?(ht=ke++,re.set(ht,be(je)+(kt+1)*(s+l))):(ht=je+1+kt,me=Math.max(me,ht+1)),Le(rt[kt],ht)}let Xe=0;for(const kt of ot){let ht;je>=C?(ht=ke++,re.set(ht,be(je)+(rt.length+1+Xe)*(s+l)),Xe++):(ht=me,me++),Le(kt,ht)}}for(const Oe of x){const je=y.get(Oe.id);if(je){const ze=ke++;re.set(ze,je.x),Le(Oe.id,ze)}else{const ze=me;me++,Le(Oe.id,ze)}}for(let Oe=0;Oe<a.length;Oe++){let je=!1;for(const ze of a){if(ve.has(ze.id))continue;const rt=(b.get(ze.id)||[]).map(ot=>ve.get(ot)).filter(ot=>ot!==void 0).sort((ot,Xe)=>ot-Xe);rt.length&&(Le(ze.id,rt[Math.floor((rt.length-1)/2)]),je=!0)}if(!je)break}return{nodeColumn:ve,colX:be}}const D=O(new Map),M=new Map;for(const[ae,ve]of b){if(ve.length<2)continue;const me=ve.filter(Le=>D.nodeColumn.has(Le)),ke=me.filter(Le=>!_.has(w(Le,ae))),re=ke.length?ke:me;if(!re.length)continue;const be=[...re].sort((Le,Oe)=>D.colX(D.nodeColumn.get(Le))-D.colX(D.nodeColumn.get(Oe))||(Le<Oe?-1:Le>Oe?1:0));M.set(ae,be[Math.floor((be.length-1)/2)])}const{nodeColumn:N,colX:R}=O(M),B=new Map;for(const ae of a)B.set(ae.id,yo(ae));const H=new Map,Y=new Set,Z=[...x.map(ae=>ae.id)];for(const ae of Z){const ve=N.get(ae)??0,me=y.get(ae);H.set(ae,{x:R(ve),y:me?.y??0}),Y.add(ae)}for(;Z.length>0;){const ae=Z.shift(),ve=H.get(ae),me=B.get(ae)||220,{continuation:ke,regenerates:re,explores:be}=A(ae,M);if(ke&&!Y.has(ke)){Y.add(ke);const Oe=N.get(ke)??0;H.set(ke,{x:R(Oe),y:ve.y+me+c}),Z.push(ke)}const Le=ve.y+me+c;for(const Oe of re){if(Y.has(Oe))continue;Y.add(Oe);const je=N.get(Oe)??0;H.set(Oe,{x:R(je),y:Le}),Z.push(Oe)}for(const Oe of be){if(Y.has(Oe))continue;Y.add(Oe);const je=N.get(Oe)??0;H.set(Oe,{x:R(je),y:ve.y+me*.25}),Z.push(Oe)}}for(let ae=0;ae<a.length;ae++){let ve=!1;for(const me of a){if(H.has(me.id))continue;const ke=(b.get(me.id)||[]).filter(be=>H.has(be));if(!ke.length)continue;const re=Math.max(...ke.map(be=>H.get(be).y+(B.get(be)||220)));H.set(me.id,{x:R(N.get(me.id)??0),y:re+c}),ve=!0}if(!ve)break}for(const ae of a)H.has(ae.id)||H.set(ae.id,{x:0,y:0});for(let ae=0;ae<5;ae++){let ve=!1;for(const me of a){const ke=H.get(me.id);if(!ke)continue;const re=(b.get(me.id)||[]).filter(je=>H.has(je));if(re.length<2)continue;const be=re.filter(je=>!_.has(`${je}\0${me.id}`)),Le=re.filter(je=>_.has(`${je}\0${me.id}`));let Oe=-1/0;for(const je of be)Oe=Math.max(Oe,H.get(je).y+(B.get(je)||220)+c);for(const je of Le)Oe=Math.max(Oe,H.get(je).y);if(Oe>-1/0&&ke.y<Oe){const je=Oe-ke.y;ke.y=Oe;for(const ze of new Set(ko(me.id,h))){const rt=H.get(ze);rt&&(rt.y+=je)}ve=!0}}if(!ve)break}const q=new Map;for(const ae of a){const ve=N.get(ae.id)??0,me=q.get(ve)||[];me.push(ae.id),q.set(ve,me)}for(let ae=0;ae<5;ae++){let ve=!1;for(const[,me]of q){me.sort((ke,re)=>H.get(ke).y-H.get(re).y);for(let ke=1;ke<me.length;ke++){const re=me[ke-1],be=me[ke],Le=H.get(re),Oe=H.get(be),je=B.get(re)||220,ze=Le.y+je+d;if(Oe.y<ze){const rt=ze-Oe.y;Oe.y=ze,ve=!0;for(const ot of new Set(ko(be,h))){const Xe=H.get(ot);Xe&&(Xe.y+=rt)}}}}if(!ve)break}const K=8e3,U=180,G=e.filter(ae=>ae.data.stepKind==="note"&&ae.data.importSource),ne=new Set(t.filter(ae=>G.some(ve=>ve.id===ae.source)).map(ae=>ae.target));for(const ae of x){const ve=[];let me=ae.id,ke=!0;for(;me;){ve.push(me);const ot=T.get(me)||[];if(ot.length>1){ke=!1;break}me=ot[0]}if(!ke||ve.length<8)continue;const re=new Set(ve),be=H.get(ve[0]),Le=ve[ve.length-1];if(H.get(Le).y+(B.get(Le)||220)-be.y<=K||a.some(ot=>!re.has(ot.id)&&H.get(ot.id).x>be.x+s/2))continue;let ze=0,rt=be.y;for(const ot of ve){const Xe=B.get(ot)||220,kt=rt-be.y,ht=kt+Xe>K,at=ne.has(ot)&&kt>K*.6;(ht||at)&&rt!==be.y&&(ze++,rt=be.y);const wt=H.get(ot);wt.x=be.x+ze*(s+U),wt.y=rt,rt+=Xe+c}}const X=a.map(ae=>{const ve=H.get(ae.id);return{x:ve.x,y:ve.y,w:s,h:B.get(ae.id)||220}}),P=460,F=130,J=(ae,ve)=>X.some(me=>ae<me.x+me.w&&ae+P>me.x&&ve<me.y+me.h&&ve+F>me.y),W=new Map;for(const ae of G){const ve=t.find(be=>be.source===ae.id)?.target,me=ve?H.get(ve):void 0;if(!me)continue;let ke=me.x-520,re=me.y;if(J(ke,re)&&(ke=me.x,re=me.y-F-40),J(ke,re)){const be=Math.round(me.x),Le=Math.min(...a.filter(je=>Math.round(H.get(je.id).x)===be).map(je=>H.get(je.id).y)),Oe=W.get(be)??0;W.set(be,Oe+1),ke=me.x,re=Le-F-40-Oe*(F+30)}H.set(ae.id,{x:ke,y:re})}return e.map(ae=>{const ve=H.get(ae.id);return ve?{...ae,position:ve}:ae})}const nH=(e,t)=>({nodes:[],edges:[],selectedNodeId:null,selectedNodeIds:[],setNodes:n=>e({nodes:n}),setEdges:n=>e({edges:n}),setSelectedNodeId:n=>e({selectedNodeId:n,selectedNodeIds:n?[n]:[]}),setSelectedNodeIds:n=>e({selectedNodeIds:n,selectedNodeId:n.length===1?n[0]:null}),deleteNode:n=>{if(Dr())return;t().logEvent("delete",n,{n:1}),t().pushHistory();const{edges:a}=t(),r=ko(n,a),s=new Set([n,...r]);e(l=>({nodes:l.nodes.filter(c=>!s.has(c.id)),edges:l.edges.filter(c=>!s.has(c.source)&&!s.has(c.target))})),t().pushHistory(),Kt(()=>import("./canonical-DDfsxGbh.js"),[]).then(l=>l.unsubscribeOrphanedSessions())},deleteEdges:n=>{if(Dr())return;t().logEvent("disconnect",n[0],{n:n.length});const a=new Set(n);t().edges.some(r=>a.has(r.id))&&(t().pushHistory(),e(r=>({edges:r.edges.filter(s=>!a.has(s.id))})),t().pushHistory())},editResponse:(n,a)=>{if(Dr())return;t().logEvent("edit-response",n,{chars:a.length}),t().pushHistory();const r=$n(t().nodes.find(s=>s.id===n)?.data.question+a||a);e(s=>({nodes:s.nodes.map(l=>l.id===n?{...l,data:{...l.data,response:a,responses:l.data.responses.map((c,d)=>d===l.data.responseIndex?a:c),summaries:l.data.summaries?.map((c,d)=>d===l.data.responseIndex?void 0:c),summaryTypes:l.data.summaryTypes?.map((c,d)=>d===l.data.responseIndex?void 0:c),editedAts:l.data.responses.map((c,d)=>d===l.data.responseIndex?new Date().toISOString():l.data.editedAts?.[d]),highlights:sf(l.data.highlights,a),isEditingResponse:!1,tokenCount:r}}:l)})),t().pushHistory()},toggleCollapse:n=>{const a=t().nodes.find(h=>h.id===n);if(!a)return;const r=yo(a),l=j7({...a,data:{...a.data,isCollapsed:!a.data.isCollapsed}})-r,c=ko(n,t().edges),d=new Set(c);e(h=>({nodes:h.nodes.map(m=>m.id===n?{...m,data:{...m.data,isCollapsed:!m.data.isCollapsed}}:d.has(m.id)?{...m,position:{...m.position,y:m.position.y+l}}:m)}))},setEditing:(n,a)=>{a&&Dr()||e(r=>({nodes:r.nodes.map(s=>s.id===n?{...s,data:{...s.data,isEditing:a}}:s)}))},setEditingResponse:(n,a)=>{a&&Dr()||e(r=>({nodes:r.nodes.map(s=>s.id===n?{...s,data:{...s.data,isEditingResponse:a}}:s)}))},duplicateNode:n=>{const a=t().nodes.find(m=>m.id===n);if(!a)return;t().pushHistory();const r=In(),s={id:r,type:"thought",position:{x:0,y:0},dragHandle:".drag-handle",data:{...a.data,isCollapsed:!0,isEditing:!1,isEditingResponse:!1,isLoading:!1,highlights:a.data.highlights.map(m=>({...m,id:In()}))}},l=t().edges.find(m=>m.target===n),c=l?{...l,id:`edge-${l.source}-${r}`,target:r}:null,d=c?[...t().edges,c]:t().edges,h=nr([...t().nodes,s],d);e({nodes:h,edges:d,selectedNodeId:r}),t().pushHistory()},addCrossLink:(n,a)=>{const{edges:r,nodes:s}=t();if(r.some(x=>x.source===n&&x.target===a))return;const c=s.find(x=>x.id===n);if(c&&["note","file","link"].includes(c.data.stepKind??"")){t().pushHistory();const x={id:`edge-${n}-${a}`,source:n,sourceHandle:"continue",target:a,targetHandle:"top",type:"smoothstep",style:{stroke:nt.accent,strokeDasharray:"8 4",strokeWidth:2},animated:!0,data:{isCrossLink:!0,createdAt:new Date().toISOString()}};e(y=>({edges:[...y.edges,x]})),t().logEvent("connect",x.id),t().setEdgeStructural(x.id,!0);const b=t().edges.find(y=>y.id===x.id);if(b&&!b.data?.isCrossLink){const E=yr(n,t().nodes,t().edges).messages.reduce((T,w)=>T+$n(w.content),0);Ke("success",qe(Ie("edge.materialWiredFull"),{n:E.toLocaleString()}),8e3,{label:Ie("edge.materialMakeQuote"),run:()=>t().setEdgeStructural(x.id,!1)})}return}t().pushHistory();const d=s.find(x=>x.id===n),h=s.find(x=>x.id===a),m=!!d&&!!h&&h.position.y>d.position.y+60&&Math.abs(h.position.x-d.position.x)<320,p={id:`crosslink-${n}-${a}`,source:n,sourceHandle:m?"continue":"branch",target:a,targetHandle:m?"top":"left",type:"smoothstep",style:{stroke:nt.accent,strokeDasharray:"8 4",strokeWidth:2},animated:!0,data:{isCrossLink:!0,createdAt:new Date().toISOString()}};if(e(x=>({edges:[...x.edges,p]})),t().logEvent("connect",p.id),t().pushHistory(),d&&!["note","file","link"].includes(d.data.stepKind??"")){const{ordered:x}=Br(n,s,r.filter(y=>!y.data?.isCrossLink)),b=x.filter(y=>y.id!==n&&!["note","file","link"].includes(y.data.stepKind??""));if(b.length>0){const y=$n(_d({source:d,depth:"quote",chain:b})),T=yr(n,s,r).messages.reduce((w,_)=>w+$n(_.content),0)+$n(d.data.question+d.data.response);Ke("info",qe(Ie("edge.linkedQuote"),{n:y}),8e3,{label:qe(Ie("edge.makeFull"),{m:T}),run:()=>t().setEdgeStructural(p.id,!0)})}}},staleIds:[],recomputeStaleness:()=>{const{nodes:n,edges:a}=t(),r=[];for(const l of n)!l.data.lastContextHash||!l.data.response||["note","file","link","frame"].includes(l.data.stepKind??"")||R7(l.id,n,a)!==l.data.lastContextHash&&r.push(l.id);const s=t().staleIds;s.length===r.length&&s.every((l,c)=>l===r[c])||e({staleIds:r})},setEdgeStructural:(n,a)=>{const{nodes:r,edges:s}=t(),l=s.find(c=>c.id===n);if(l){if(a){const c=s.filter(h=>!h.data?.isCrossLink),{ordered:d}=Br(l.source,r,c);if(d.some(h=>h.id===l.target)){Ke("error",Ie("edge.cycleBlocked"));return}}t().pushHistory(),t().logEvent(a?"connect":"disconnect",n,{convert:!0}),e(c=>({edges:c.edges.map(d=>{if(d.id!==n)return d;if(a){const h={...d.data??{}};return delete h.isCrossLink,delete h.contextDepth,delete h.isWatch,{...d,sourceHandle:"continue",targetHandle:"top",animated:!1,style:{stroke:nt.accent,strokeWidth:2},markerEnd:{type:"arrowclosed",color:nt.accent,width:18,height:18},data:h}}return{...d,animated:!0,style:{stroke:nt.accent,strokeDasharray:"8 4",strokeWidth:2},markerEnd:{type:"arrowclosed",color:nt.accent,width:18,height:18},data:{...d.data??{},isCrossLink:!0,contextDepth:void 0}}})})),e(c=>({nodes:nr(c.nodes,c.edges)})),t().pushHistory()}},setCrossLinkDepth:(n,a)=>{t().pushHistory(),e(r=>({edges:r.edges.map(s=>s.id!==n||!s.data?.isCrossLink?s:{...s,style:{...s.style,strokeDasharray:a==="full"?"12 3":"8 4",strokeWidth:a==="full"?3:2},data:{...s.data,contextDepth:a==="full"?"full":void 0}})})),t().pushHistory()},navigateVersion:(n,a)=>{e(r=>({nodes:r.nodes.map(s=>{if(s.id!==n)return s;const{responses:l,responseIndex:c}=s.data;let d=a==="prev"?c-1:c+1;return d<0&&(d=l.length-1),d>=l.length&&(d=0),{...s,data:{...s.data,responseIndex:d,response:l[d],question:s.data.questions?.[d]??s.data.question,generationFailed:void 0,highlights:sf(s.data.highlights,l[d])}}})}))},deleteVersion:(n,a)=>{t().pushHistory(),e(r=>({nodes:r.nodes.map(s=>{if(s.id!==n)return s;const l=s.data.responses.filter((d,h)=>h!==a);if(l.length===0)return s;const c=Math.min(s.data.responseIndex,l.length-1);return{...s,data:{...s.data,responses:l,responseIndex:c,response:l[c],questions:s.data.questions?.filter((d,h)=>h!==a),question:s.data.questions?.filter((d,h)=>h!==a)[c]??s.data.question,summaries:s.data.summaries?.filter((d,h)=>h!==a),generatedBy:s.data.generatedBy?.filter((d,h)=>h!==a),summaryTypes:s.data.summaryTypes?.filter((d,h)=>h!==a),reasonings:s.data.reasonings?.filter((d,h)=>h!==a),generatedAts:s.data.generatedAts?.filter((d,h)=>h!==a),editedAts:s.data.editedAts?.filter((d,h)=>h!==a),highlights:sf(s.data.highlights,l[c])}}})})),t().pushHistory()},relayout:()=>{Dr()||(t().pushHistory(),e(n=>{const a=tH(n.nodes,n.edges);return{nodes:nr(n.nodes,a),edges:a}}),t().pushHistory())},setArchived:(n,a)=>{const r=new Set(n);t().pushHistory(),t().logEvent(a?"archive":"unarchive",n[0],{n:n.length}),e(s=>({nodes:s.nodes.map(l=>r.has(l.id)?{...l,data:{...l.data,archived:a||void 0,archivedAt:a?new Date().toISOString():void 0}}:l)})),t().pushHistory()},setNodeModel:(n,a)=>{e(r=>({nodes:r.nodes.map(s=>s.id===n?{...s,data:{...s.data,model:a}}:s)}))},alignSelection:n=>{if(n.length<2)return;const a=new Set(n),{nodes:r,edges:s}=t(),l=new Map,c=s.filter(b=>!b.data?.isWatch),d=(b,y)=>{if(l.has(b))return l.get(b);if(y.has(b))return 0;y.add(b);const E=c.filter(w=>w.target===b&&a.has(w.source)),T=E.length===0?0:1+Math.max(...E.map(w=>d(w.source,y)));return l.set(b,T),T},h=n.map(b=>r.find(y=>y.id===b)).filter(b=>!!b).sort((b,y)=>d(b.id,new Set)-d(y.id,new Set)||b.position.y-y.position.y);t().pushHistory();const m=h[0].position;let p=m.y;const x=new Map;for(const b of h)x.set(b.id,{x:m.x,y:p}),p+=yo(b)+40;e(b=>({nodes:b.nodes.map(y=>{const E=x.get(y.id);return E?{...y,position:E}:y})})),t().pushHistory()},batchDelete:n=>{if(Dr())return;t().logEvent("delete",n[0],{n:n.length}),t().pushHistory();const a=new Set(n);e(r=>({nodes:r.nodes.filter(s=>!a.has(s.id)),edges:r.edges.filter(s=>!a.has(s.source)&&!a.has(s.target)),selectedNodeId:null,selectedNodeIds:[]})),t().pushHistory(),Kt(()=>import("./canonical-DDfsxGbh.js"),[]).then(r=>r.unsubscribeOrphanedSessions())},duplicateSelection:n=>{const{nodes:a,edges:r}=t(),s=new Set(n),l=a.filter(M=>s.has(M.id));if(l.length===0)return;t().pushHistory();const c=M=>({x:M.position.x,y:M.position.y,w:M.measured?.width??M.width??520,h:M.measured?.height??M.height??yo(M)}),d=l.map(c),h={x:Math.min(...d.map(M=>M.x)),y:Math.min(...d.map(M=>M.y)),right:Math.max(...d.map(M=>M.x+M.w)),bottom:Math.max(...d.map(M=>M.y+M.h))},m=80,p=h.right-h.x+m,x=h.bottom-h.y+m,b=[];for(let M=1;M<=6;M++)b.push({dx:M*p,dy:0},{dx:0,dy:M*x},{dx:M*p,dy:M*x});const y=a.filter(M=>M.data.stepKind!=="frame").map(c),E=(M,N)=>M.x<N.x+N.w&&M.x+M.w>N.x&&M.y<N.y+N.h&&M.y+M.h>N.y,T=b.find(M=>!d.some(N=>y.some(R=>E({...N,x:N.x+M.dx,y:N.y+M.dy},R))))??{dx:p,dy:x},w=new Map,_=new Map;for(const M of l){w.set(M.id,In());for(const N of M.data.attachments??[])_.set(N.id,In())}const A=M=>(M??[]).map(N=>_.get(N)??N),C=l.map(M=>({...M,id:w.get(M.id),position:{x:M.position.x+T.dx,y:M.position.y+T.dy},selected:!0,data:{...M.data,attachments:(M.data.attachments??[]).map(N=>({...N,id:_.get(N.id)})),excludedAttachmentIds:A(M.data.excludedAttachmentIds),includedAttachmentIds:A(M.data.includedAttachmentIds),digestOf:M.data.digestOf?_.get(M.data.digestOf)??M.data.digestOf:void 0,highlights:(M.data.highlights??[]).map(N=>({...N,id:In()})),isEditing:!1,isEditingResponse:!1,isLoading:!1}})),O=r.filter(M=>s.has(M.source)&&s.has(M.target)).map(M=>({...M,id:`edge-${w.get(M.source)}-${w.get(M.target)}`,source:w.get(M.source),target:w.get(M.target),data:M.data?{...M.data}:M.data})),D=C.map(M=>M.id);e(M=>({nodes:[...M.nodes.map(N=>N.selected?{...N,selected:!1}:N),...C],edges:[...M.edges,...O],selectedNodeId:D.length===1?D[0]:null,selectedNodeIds:D})),t().pushHistory()}});function Rb(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 _f(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 aH(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:bc(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 rH(e,t){return`sha256:${await _f(Rb(aH(e,t)))}`}function iH(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 Iae(e,t,n,a){const r=yr(e,t,n,a.branchContext,void 0,void 0,a.staleIds),s=t.find(x=>x.id===e),l=r.messages.map((x,b)=>{const y=r.sources[b]??{layer:"chain"};return{id:`item_${String(b+1).padStart(3,"0")}`,kind:"message",role:x.role,content:[{type:"text",text:x.content}],source:{layer:y.layer,part:y.part,node_id:y.nodeId??y.refSourceId,attachment_id:y.attachmentId},selection:{mode:"full",reason:`structural-${y.layer}`}}}),c=new Map,d=(x,b)=>{if(!x||!b||c.has(b))return;const y=t.find(T=>T.id===x),E=y?.data.attachments?.find(T=>T.id===b);!y||!E||c.set(b,{id:b,kind:E.type.startsWith("image/")?"image":"document",name:E.name,mime_type:E.type,size:E.size,fingerprint:bc(E),model_projection:{mode:iH(E)},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 rH(t,n),target_node_id:e},intent:{task:a.task??s?.data.question??"",language:a.language??null},context:{messages:l,materials:[...c.values()],references:h},execution_hints:{preferred_model:a.preferredModel??s?.data.model??null,required_tools:[],required_mcp_servers:[]},budget:{estimated_tokens:r.messages.reduce((x,b)=>x+$n(b.content),0),limit:null,truncation:"none"}},p=await _f(Rb(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 ic="dsh-sessions",o1="/session.jsonl.zstd",sH=1500,oH=2500;let Ax=null;function lH(e){if(window.desktopSessions)return;const t=e.replace(/\/+$/,""),n=async O=>{const D=await fetch(t+O,{credentials:"same-origin"});if(!D.ok)throw new Error(`${O}: ${D.status}`);return D.json()},a=async O=>{const D=await fetch(t+O,{credentials:"same-origin"});if(!D.ok)throw new Error(`${O}: ${D.status}`);return D.text()},r=new Map,s=O=>`${O}${o1}`,l=(O,D)=>{const M=O.indexOf(`
|
|
62
62
|
`),N=M<0?O:O.slice(0,M);try{const R=JSON.parse(N);if(R.type==="session"&&R.cwd===void 0)return R.cwd=D,JSON.stringify(R)+(M<0?"":O.slice(M))}catch{}return O},c=O=>O.endsWith(o1)?O.slice(0,-o1.length):null,d=async()=>{const[O,D]=await Promise.all([n("/disksessions").then(N=>N.sessions).catch(()=>[]),n("/sessions").then(N=>N.sessions).catch(()=>[])]),M=new Set;for(const N of O){M.add(N.id);const R=r.get(N.id);r.set(N.id,{id:N.id,live:!1,size:N.size,mtime:N.mtime,seq:R?.seq??null,cwd:N.cwd??R?.cwd??null})}for(const N of D){M.add(N.id);const R=r.get(N.id),B=typeof N.seq=="number"?N.seq:null,H=B!==null&&R?.seq!==null&&R?.seq!==void 0&&B>R.seq;r.set(N.id,{id:N.id,live:!0,size:R?.size??0,mtime:H||!R?Date.now():R.mtime,seq:B,cwd:R?.cwd??null})}for(const N of[...r.keys()])M.has(N)||r.delete(N);return[...r.values()]},h=new Map,m=async O=>{const D=r.get(O)??(await d(),r.get(O));if(!D)return"";const M=h.get(O);if(M&&Date.now()-M.at<sH&&M.seq===D.seq)return M.text;let N=await a(D.live?`/sessions/${encodeURIComponent(O)}/log`:`/disksessions/${encodeURIComponent(O)}/log`).catch(()=>"");return D.live&&D.cwd&&(N=l(N,D.cwd)),h.set(O,{at:Date.now(),seq:D.seq,text:N}),N};let p=null;const x=async()=>p||(p=await n("/roots").then(O=>O.roots.filter(D=>D.exists)).catch(()=>[]),p),b=new Map,y=async O=>n(`/roots/${encodeURIComponent(O)}/list`).then(D=>D.files).catch(()=>[]),E=(O,D,M,N="")=>`/roots/${encodeURIComponent(O)}/${D}?rel=${encodeURIComponent(M)}${N}`,T=[];let w=!1;const _=async()=>{const O=new Map([...r].map(([M,N])=>[M,N.seq])),D=await d().catch(()=>[]);for(const M of D){if(!M.live)continue;const N=O.get(M.id);if(N===void 0||M.seq!==null&&N!==null&&M.seq>N){h.delete(M.id);for(const R of T)R({rootKey:ic,rel:s(M.id)})}}for(const M of await x())for(const N of await y(M.key)){const R=`${M.key}|${N.rel}`,B=b.get(R);if(b.set(R,N.mtime),B!==void 0&&N.mtime>B)for(const H of T)H({rootKey:M.key,rel:N.rel})}},A=O=>{window.parent.postMessage({source:"dsh-thoughtdag",type:"td:select-session",session:O},window.location.origin)},C={roots:async()=>[{key:ic,path:"~/.dsh/sessions",builtin:!0,exists:!0},...await x()],addRoot:async()=>null,removeRoot:async()=>{},list:async O=>{if(O!==ic){const D=await y(O);for(const M of D)b.set(`${O}|${M.rel}`,M.mtime);return D}return(await d()).map(D=>({rel:s(D.id),size:D.size,mtime:D.mtime}))},head:async(O,D,M)=>{if(O!==ic)return a(E(O,"head",D,`&bytes=${Math.max(1024,M|0)}`)).catch(()=>"");const N=c(D);return N?(await m(N)).slice(0,Math.min(Math.max(1024,M|0),524288)):""},read:async(O,D)=>{if(O!==ic)return a(E(O,"read",D)).catch(()=>"");const M=c(D);return M?m(M):""},readRange:async(O,D,M,N)=>{if(O!==ic)return n(E(O,"range",D,`&start=${M|0}&length=${N|0}`)).catch(()=>({text:"",nextStart:M|0,eof:!0}));const R=c(D),B=R?await m(R):"",H=Math.max(0,M|0),Y=Math.min(Math.max(65536,N|0),32*1024*1024),Z=Math.min(Y,Math.max(0,B.length-H));if(Z===0)return{text:"",nextStart:H,eof:!0};let q=B.slice(H,H+Z);const K=H+Z>=B.length;if(!K){const U=q.lastIndexOf(`
|
|
63
63
|
`);if(U<0)return{text:"",nextStart:H+Z,eof:!1};q=q.slice(0,U+1)}return{text:q,nextStart:H+q.length,eof:K}},openInCli:async(O,D,M)=>O!=="dsh"?{opened:!1,via:"app",command:""}:(A(M),{opened:!0,via:"app",command:""}),openTargets:async()=>({terminals:[],apps:[{runner:"dsh",name:"DeepSeek Harness"}],prefs:{terminal:""},canAddCustom:!1}),setOpenPrefs:async O=>O,addTerminal:async()=>null,watchStart:async()=>(w||(w=!0,await d().catch(()=>{}),window.setInterval(()=>{_()},oH)),!0),onSessionsChanged:O=>{T.push(O)}};window.desktopSessions=C,window.addEventListener("message",O=>{const D=O.data;O.origin!==window.location.origin||D?.source!=="dsh-thoughtdag"||D.type==="td:current-session"&&(Ax=D.session??null,window.dispatchEvent(new CustomEvent("td:dsh-current",{detail:Ax})))}),window.parent.postMessage({source:"dsh-thoughtdag",type:"td:request-current"},window.location.origin)}const cH="harness/agent";async function uH(){try{const{useStore:e}=await Kt(async()=>{const{useStore:r}=await Promise.resolve().then(()=>Lb);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 dH(e,t){if(!window.desktopSessions||t!==cH)return;const n=await uH()??Ax?.cwd??void 0;try{const{useStore:a}=await Kt(async()=>{const{useStore:h}=await Promise.resolve().then(()=>Lb);return{useStore:h}},void 0),{useProjects:r}=await Kt(async()=>{const{useProjects:h}=await Promise.resolve().then(()=>mm);return{useProjects:h}},void 0),{projects:s,activeId:l}=r.getState(),d=s.find(h=>h.id===l)?.sourceSession;if(d&&d.runner==="dsh"){const h=a.getState().edges.filter(m=>m.target===e);if(h.length===1&&h[0].source===d.tailNodeId)return{...n?{cwd:n}:{},session:d.sessionId}}}catch{}return n?{cwd:n}:{}}const P7=(e,t,n,a,r,s)=>{const l=r?[r]:[];e(c=>({nodes:c.nodes.map(d=>d.id===t?{...d,data:{...d.data,importSource:{runner:"dsh",sessionId:n,itemIds:l,...a.cwd?{cwd:a.cwd}:{}},...s?{source:s}:{}}}:d)}))};async function z7(e,t){if(!e)return!1;const{useProjects:n,patchLedgerEntry:a}=await Kt(async()=>{const{useProjects:d,patchLedgerEntry:h}=await Promise.resolve().then(()=>mm);return{useProjects:d,patchLedgerEntry:h}},void 0),{projects:r,activeId:s}=n.getState();if(!s)return!1;const l=r.find(d=>d.id===s)?.sourceSession;if(!l)return!1;const c=l.sessionId===e?l:l.chapters?.find(d=>d.sessionId===e)??l.branches?.find(d=>d.sessionId===e);return c?(await a(s,e,{importedCount:c.importedCount+1,tailNodeId:t}),!0):!1}async function hH(e,t,n,a){return window.desktopSessions?(P7(e,t,n.session??a.session,n,a.userMessageId),z7(n.session,t)):!1}async function fH(e,t,n,a,r,s,l,c=!1){if(!window.desktopSessions)return;const d=r.session??l?.session??s;d&&(P7(e,n,d,r,l?.userMessageId??null,{question:a.question,response:a.response}),c||await z7(r.session,n))}const mH=45,pH=3,gH=/sk-[a-zA-Z0-9_-]{8,}|api[ _-]?key|password|token|secret/i,Nx=new Map;function xH(e){return e.category!=="project"?!0:(Date.now()-new Date(e.at).getTime())/864e5<=mH}function bH(){const{memoryEnabled:e,memories:t}=ye.getState();if(!e)return null;const n=t.filter(xH);return n.length===0?null:{role:"user",content:`[Memory] Durable notes about this user, recorded across earlier sessions. Use them ONLY where relevant; never recite them, never treat them as part of the current question:
|
|
64
64
|
${n.map(r=>`- ${r.text}`).join(`
|
|
@@ -131,13 +131,13 @@ For each candidate above, judge what evidence would rule it OUT and what would r
|
|
|
131
131
|
严格从这个视角,为上面的问题给出唯一最佳的候选解释:说清机制、可检验的预测,以及什么证据能确认或排除它。`},{id:"conf",kind:"prompt",x:980,y:440,title:"候选:混杂",instruction:`你主张这个效应是假象或混杂因素,而非目标现象。
|
|
132
132
|
严格从这个视角,为上面的问题给出唯一最佳的候选解释:说清疑似的混杂来源、可检验的预测,以及什么证据能确认或排除它。`},{id:"null",kind:"prompt",x:1460,y:440,title:"候选:零假设",instruction:`你主张这个效应可能不真实或被夸大,给出最强的收缩性论证。
|
|
133
133
|
严格从这个视角回答上面的问题:什么会让效应消失,以及什么证据能确认或排除这一解释。`},{id:"rev",kind:"prompt",x:560,y:920,title:"鉴别评审",instruction:`你是一位严谨的方法学家,正在对相互竞争的解释做鉴别诊断。
|
|
134
|
-
对上面每个候选,判断什么证据能将它排除(rule out)、什么能将它确认(rule in)。按可区分度排序:哪个检验最能把它们分开?`},{id:"syn",kind:"prompt",x:560,y:1360,title:"收敛",instruction:"综合上面的候选与区分性检验:先确认哪个解释、排除哪个,以及信息量最大的下一个实验是什么。"}],edges:[["q","mechA"],["q","mechB"],["q","conf"],["q","null"],["mechA","rev"],["mechB","rev"],["conf","rev"],["null","rev"],["rev","syn"]]}};function DH(e){const{name:t,steps:n,edges:a}=dw[e]??dw.en,r=n.map(l=>({id:`p-${l.id}`,type:"thought",position:{x:l.x,y:l.y},dragHandle:".drag-handle",data:{question:l.title,instruction:l.instruction,stepKind:l.kind,response:"",responses:[],responseIndex:-1,isCollapsed:!1,isEditing:!1,isEditingResponse:!1,isLoading:!1,tokenCount:0,highlights:[],highlightMode:"tag",attachments:[],excludedAttachmentIds:[],includedAttachmentIds:[],roleMode:"inherit",isRoot:l.id==="q",isBranch:!1}})),s=a.map(([l,c])=>({id:`p-e-${l}-${c}`,source:`p-${l}`,target:`p-${c}`,type:"smoothstep",sourceHandle:"continue",targetHandle:"top",style:{stroke:"#6B5CE7",strokeWidth:2},markerEnd:{type:"arrowclosed",color:"#6B5CE7",width:18,height:18},data:{}}));return{name:t,nodes:r,edges:s}}const Cx="thoughtdag:projects",hw="thoughtdag",ni=e=>`thoughtdag:project:${e}`;async function Mf(e,t){const{projects:n,activeId:a}=Nn.getState();if(t&&e===a){const r=n.filter(s=>s.id!==e&&!s.archived).sort((s,l)=>l.updatedAt-s.updatedAt);r.length>0?await ks(r[0].id):await fm("My Canvas")}Nn.setState(r=>({projects:r.projects.map(s=>s.id===e?{...s,archived:t}:s)})),await si()}async function OH(e,t){Nn.setState(n=>({projects:n.projects.map(a=>a.id===e&&a.sourceSession?{...a,sourceSession:{...a.sourceSession,...t}}:a)})),await si()}async function RH(e,t,n){Nn.setState(a=>({projects:a.projects.map(r=>{if(r.id!==e||!r.sourceSession)return r;const s=r.sourceSession;return s.sessionId===t?{...r,sourceSession:{...s,...n}}:{...r,sourceSession:{...s,chapters:s.chapters?.map(l=>l.sessionId===t?{...l,...n}:l),branches:s.branches?.map(l=>l.sessionId===t?{...l,...n}:l)}}})})),await si()}async function LH(e,t,n){Nn.setState(a=>({projects:a.projects.map(r=>{if(r.id!==e)return r;const s=r.sourceSession??{sessionId:"",runner:"",importedCount:0,tailNodeId:""};return t==="chapter"?{...r,sourceSession:{...s,chapters:[...s.chapters??[],{sessionId:n.sessionId,runner:n.runner,importedCount:n.importedCount,tailNodeId:n.tailNodeId}]}}:{...r,sourceSession:{...s,branches:[...s.branches??[],{...n,anchorNodeId:n.anchorNodeId??""}]}}})})),await si()}async function jH(e,t){Nn.setState(n=>({projects:n.projects.map(a=>{if(a.id!==e||!a.sourceSession)return a;const r=a.sourceSession,s=(r.chapters??[]).filter(d=>d.sessionId!==t),l=(r.branches??[]).filter(d=>d.sessionId!==t),c={...r,chapters:s.length?s:void 0,branches:l.length?l:void 0};return c.sessionId===t&&(c.sessionId="",c.runner="",c.importedCount=0,c.tailNodeId=""),!c.sessionId&&s.length===0&&l.length===0?{...a,sourceSession:void 0}:{...a,sourceSession:c}})})),await si()}function _x(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 B7(e,t){Nn.setState(n=>({projects:n.projects.map(a=>a.id===e?{...a,instantiatedFrom:{name:t,at:new Date().toISOString()}}:a)})),await si()}const Nn=$d(()=>({projects:[],activeId:null,switching:!1}));async function si(){const{projects:e,activeId:t}=Nn.getState();await zr(Cx,{projects:e,activeId:t})}let fw=null;function H7(){return fw??=(async()=>{let e=await xl(Cx);if(!e||e.projects.length===0){const t=await xl(hw),n=crypto.randomUUID(),a=Date.now();t&&await zr(ni(n),t),e={projects:[{id:n,name:"My Canvas",createdAt:a,updatedAt:a}],activeId:n},await zr(Cx,e),t&&await Lc(hw)}e.projects.some(t=>t.id===e.activeId)||(e.activeId=e.projects[0].id),Nn.setState({projects:e.projects,activeId:e.activeId}),oe.persist.setOptions({name:ni(e.activeId)}),await oe.persist.rehydrate()})().catch(async e=>{console.error("[thoughtdag] project boot failed:",e),Ke("error",Ie("toast.projectsLoadFailed")),oe.persist.setOptions({name:ni("recovery")}),await oe.persist.rehydrate()}),fw}let Mx=!1;async function PH(){for(const t of vs.values())t.abort();const e=Date.now()+1e3;for(;vs.size>0&&Date.now()<e;)await new Promise(t=>setTimeout(t,30));await new Promise(t=>setTimeout(t,0))}const U7=[];async function ks(e){for(const r of U7)await r().catch(()=>{});const{activeId:t,switching:n,projects:a}=Nn.getState();if(!(n||e===t||!a.some(r=>r.id===e))){Nn.setState({switching:!0});try{await PH(),await mB(),Mx=!0,oe.persist.setOptions({name:ni(e)}),await oe.persist.rehydrate(),oe.setState({selectedNodeId:null,selectedNodeIds:[]}),Nn.setState(r=>({activeId:e,projects:r.projects.map(s=>s.id===e&&s.archived?{...s,archived:!1}:s)})),await si()}finally{Mx=!1,Nn.setState({switching:!1})}}}async function fm(e="Untitled",t="chat"){const n=crypto.randomUUID(),a=Date.now();return Nn.setState(r=>({projects:[...r.projects,{id:n,name:e,createdAt:a,updatedAt:a,kind:t}]})),await si(),await ks(n),n}async function F7(e,t){Nn.setState(n=>({projects:n.projects.map(a=>a.id===e?{...a,name:t}:a)})),await si()}async function q7(e){const{projects:t,activeId:n}=Nn.getState();if(e===n){const a=t.filter(r=>r.id!==e);a.length>0?await ks(a[0].id):await fm("My Canvas")}await Lc(ni(e)),Nn.setState(a=>({projects:a.projects.filter(r=>r.id!==e)})),await si(),Kt(()=>import("./canvas-record-
|
|
134
|
+
对上面每个候选,判断什么证据能将它排除(rule out)、什么能将它确认(rule in)。按可区分度排序:哪个检验最能把它们分开?`},{id:"syn",kind:"prompt",x:560,y:1360,title:"收敛",instruction:"综合上面的候选与区分性检验:先确认哪个解释、排除哪个,以及信息量最大的下一个实验是什么。"}],edges:[["q","mechA"],["q","mechB"],["q","conf"],["q","null"],["mechA","rev"],["mechB","rev"],["conf","rev"],["null","rev"],["rev","syn"]]}};function DH(e){const{name:t,steps:n,edges:a}=dw[e]??dw.en,r=n.map(l=>({id:`p-${l.id}`,type:"thought",position:{x:l.x,y:l.y},dragHandle:".drag-handle",data:{question:l.title,instruction:l.instruction,stepKind:l.kind,response:"",responses:[],responseIndex:-1,isCollapsed:!1,isEditing:!1,isEditingResponse:!1,isLoading:!1,tokenCount:0,highlights:[],highlightMode:"tag",attachments:[],excludedAttachmentIds:[],includedAttachmentIds:[],roleMode:"inherit",isRoot:l.id==="q",isBranch:!1}})),s=a.map(([l,c])=>({id:`p-e-${l}-${c}`,source:`p-${l}`,target:`p-${c}`,type:"smoothstep",sourceHandle:"continue",targetHandle:"top",style:{stroke:"#6B5CE7",strokeWidth:2},markerEnd:{type:"arrowclosed",color:"#6B5CE7",width:18,height:18},data:{}}));return{name:t,nodes:r,edges:s}}const Cx="thoughtdag:projects",hw="thoughtdag",ni=e=>`thoughtdag:project:${e}`;async function Mf(e,t){const{projects:n,activeId:a}=Nn.getState();if(t&&e===a){const r=n.filter(s=>s.id!==e&&!s.archived).sort((s,l)=>l.updatedAt-s.updatedAt);r.length>0?await ks(r[0].id):await fm("My Canvas")}Nn.setState(r=>({projects:r.projects.map(s=>s.id===e?{...s,archived:t}:s)})),await si()}async function OH(e,t){Nn.setState(n=>({projects:n.projects.map(a=>a.id===e&&a.sourceSession?{...a,sourceSession:{...a.sourceSession,...t}}:a)})),await si()}async function RH(e,t,n){Nn.setState(a=>({projects:a.projects.map(r=>{if(r.id!==e||!r.sourceSession)return r;const s=r.sourceSession;return s.sessionId===t?{...r,sourceSession:{...s,...n}}:{...r,sourceSession:{...s,chapters:s.chapters?.map(l=>l.sessionId===t?{...l,...n}:l),branches:s.branches?.map(l=>l.sessionId===t?{...l,...n}:l)}}})})),await si()}async function LH(e,t,n){Nn.setState(a=>({projects:a.projects.map(r=>{if(r.id!==e)return r;const s=r.sourceSession??{sessionId:"",runner:"",importedCount:0,tailNodeId:""};return t==="chapter"?{...r,sourceSession:{...s,chapters:[...s.chapters??[],{sessionId:n.sessionId,runner:n.runner,importedCount:n.importedCount,tailNodeId:n.tailNodeId}]}}:{...r,sourceSession:{...s,branches:[...s.branches??[],{...n,anchorNodeId:n.anchorNodeId??""}]}}})})),await si()}async function jH(e,t){Nn.setState(n=>({projects:n.projects.map(a=>{if(a.id!==e||!a.sourceSession)return a;const r=a.sourceSession,s=(r.chapters??[]).filter(d=>d.sessionId!==t),l=(r.branches??[]).filter(d=>d.sessionId!==t),c={...r,chapters:s.length?s:void 0,branches:l.length?l:void 0};return c.sessionId===t&&(c.sessionId="",c.runner="",c.importedCount=0,c.tailNodeId=""),!c.sessionId&&s.length===0&&l.length===0?{...a,sourceSession:void 0}:{...a,sourceSession:c}})})),await si()}function _x(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 B7(e,t){Nn.setState(n=>({projects:n.projects.map(a=>a.id===e?{...a,instantiatedFrom:{name:t,at:new Date().toISOString()}}:a)})),await si()}const Nn=$d(()=>({projects:[],activeId:null,switching:!1}));async function si(){const{projects:e,activeId:t}=Nn.getState();await zr(Cx,{projects:e,activeId:t})}let fw=null;function H7(){return fw??=(async()=>{let e=await xl(Cx);if(!e||e.projects.length===0){const t=await xl(hw),n=crypto.randomUUID(),a=Date.now();t&&await zr(ni(n),t),e={projects:[{id:n,name:"My Canvas",createdAt:a,updatedAt:a}],activeId:n},await zr(Cx,e),t&&await Lc(hw)}e.projects.some(t=>t.id===e.activeId)||(e.activeId=e.projects[0].id),Nn.setState({projects:e.projects,activeId:e.activeId}),oe.persist.setOptions({name:ni(e.activeId)}),await oe.persist.rehydrate()})().catch(async e=>{console.error("[thoughtdag] project boot failed:",e),Ke("error",Ie("toast.projectsLoadFailed")),oe.persist.setOptions({name:ni("recovery")}),await oe.persist.rehydrate()}),fw}let Mx=!1;async function PH(){for(const t of vs.values())t.abort();const e=Date.now()+1e3;for(;vs.size>0&&Date.now()<e;)await new Promise(t=>setTimeout(t,30));await new Promise(t=>setTimeout(t,0))}const U7=[];async function ks(e){for(const r of U7)await r().catch(()=>{});const{activeId:t,switching:n,projects:a}=Nn.getState();if(!(n||e===t||!a.some(r=>r.id===e))){Nn.setState({switching:!0});try{await PH(),await mB(),Mx=!0,oe.persist.setOptions({name:ni(e)}),await oe.persist.rehydrate(),oe.setState({selectedNodeId:null,selectedNodeIds:[]}),Nn.setState(r=>({activeId:e,projects:r.projects.map(s=>s.id===e&&s.archived?{...s,archived:!1}:s)})),await si()}finally{Mx=!1,Nn.setState({switching:!1})}}}async function fm(e="Untitled",t="chat"){const n=crypto.randomUUID(),a=Date.now();return Nn.setState(r=>({projects:[...r.projects,{id:n,name:e,createdAt:a,updatedAt:a,kind:t}]})),await si(),await ks(n),n}async function F7(e,t){Nn.setState(n=>({projects:n.projects.map(a=>a.id===e?{...a,name:t}:a)})),await si()}async function q7(e){const{projects:t,activeId:n}=Nn.getState();if(e===n){const a=t.filter(r=>r.id!==e);a.length>0?await ks(a[0].id):await fm("My Canvas")}await Lc(ni(e)),Nn.setState(a=>({projects:a.projects.filter(r=>r.id!==e)})),await si(),Kt(()=>import("./canvas-record-vunI4XSG.js"),[]).then(a=>a.removeCanvasRecord(e)).catch(()=>{})}async function jc(e,t,n="chat",a){const r=Date.now();Nn.setState(s=>({projects:[...s.projects,{id:e,name:t,createdAt:r,updatedAt:r,kind:n,...a}]})),await si(),await ks(e)}async function zH(e){const{name:t,nodes:n,edges:a}=DH(e),r=crypto.randomUUID();await zr(ni(r),JSON.stringify({state:{nodes:n,edges:a},version:1})),await jc(r,t,"paradigm")}let c1=null;oe.subscribe((e,t)=>{Mx||e.nodes===t.nodes&&e.edges===t.edges||(c1&&clearTimeout(c1),c1=setTimeout(()=>{const{activeId:n}=Nn.getState();if(!n)return;const a=[...new Set(oe.getState().nodes.map(r=>r.data.importSource?.sessionId).filter(r=>!!r))];Nn.setState(r=>({projects:r.projects.map(s=>s.id===n?{...s,updatedAt:Date.now(),provenanceSessions:a}:s)})),si()},1e3))});const mm=Object.freeze(Object.defineProperty({__proto__:null,adoptImportedProject:jc,beforeSwitchHooks:U7,bootProjects:H7,createBuiltinParadigm:zH,createProject:fm,deleteProject:q7,markInstantiatedFrom:B7,patchLedgerEntry:RH,projectStorageKey:ni,registerLedgerEntry:LH,removeLedgerEntry:jH,renameProject:F7,setProjectArchived:Mf,subscribedSessionIds:_x,switchProject:ks,updateSourceSession:OH,useProjects:Nn},Symbol.toStringTag,{value:"Module"}));function V7(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 W7(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 G7(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 Y7(e){const t=e.message?.content?.parts;return Array.isArray(t)?t.filter(n=>typeof n=="string").join(`
|
|
135
135
|
`).trim():""}function BH(e){const t=[],n=[],a=Object.values(e).filter(s=>!s.parent||!e[s.parent]),r=(s,l,c)=>{const d=e[s];if(!d)return;const h=d.message?.author?.role,m=Y7(d);let p=l,x=c;if(h==="user"&&m)p=m;else if(h==="assistant"&&m){if(p!==null){const b=W7(p,m,c===null);t.push(b),c&&n.push(G7(c,b.id)),x=b.id,p=null}else if(x){const b=t.find(y=>y.id===x);b&&(b.data.response+=`
|
|
136
136
|
|
|
137
137
|
`+m,b.data.responses=[b.data.response])}}for(const b of d.children??[])r(b,p,x)};for(const s of a)r(s.id,null,null);return{nodes:nr(t,n),edges:n}}function $7(e){return typeof e.text=="string"&&e.text.trim()?e.text.trim():Array.isArray(e.content)?e.content.filter(t=>t?.type==="text"&&typeof t.text=="string").map(t=>t.text).join(`
|
|
138
138
|
`).trim():""}function HH(e){const t=[],n=[];let a=null,r=null;for(const s of e){const l=$7(s);if(l){if(s.sender==="human")a=l;else if(s.sender==="assistant"){if(a!==null){const c=W7(a,l,r===null);t.push(c),r&&n.push(G7(r,c.id)),r=c.id,a=null}else if(r){const c=t.find(d=>d.id===r);c&&(c.data.response+=`
|
|
139
139
|
|
|
140
|
-
`+l,c.data.responses=[c.data.response])}}}}return{nodes:nr(t,n),edges:n}}function UH(e){const t=V7(e),n=[];if(t==="chatgpt")for(const a of e){const r=a.mapping??{},s=Object.values(r).filter(l=>["user","assistant"].includes(l.message?.author?.role??"")&&Y7(l)).length;s!==0&&n.push({title:a.title||"Untitled",messageCount:s,source:"chatgpt",build:()=>BH(r)})}else if(t==="claude")for(const a of e){const r=a.chat_messages??[],s=r.filter(l=>$7(l)).length;s!==0&&n.push({title:a.name||"Untitled",messageCount:s,source:"claude",build:()=>HH(r)})}return n}function FH(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 qH(e){const t=e;return!!t&&typeof t=="object"&&t.kind==="thoughtdag-paradigm"&&Array.isArray(t.nodes)&&Array.isArray(t.edges)}const VH=()=>({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 WH(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={...VH(),question:m,rolePrompt:c.data.rolePrompt||void 0,roleMode:c.data.rolePrompt?"reset":"inherit"};return h==="human"&&(p.stepKind="human",p.question="",p.instruction=c.data.instruction?.trim()||void 0,p.rolePrompt=void 0,p.roleMode="inherit"),h==="prompt"&&(p.stepKind="prompt",p.webSearch=c.data.webSearch,p.scholarSearch=c.data.scholarSearch,p.autoRerun=c.data.autoRerun,p.autoRerunRounds=c.data.autoRerunRounds),(h==="note"||h==="file"||h==="link"||h==="frame")&&(p.stepKind=h,p.question=c.data.question||"",p.attachments=c.data.attachments??[],p.tokenCount=c.data.tokenCount??0,p.linkUrl=c.data.linkUrl,p.linkTitle=c.data.linkTitle,p.linkFetchedAt=c.data.linkFetchedAt,p.frameColor=c.data.frameColor),h==="review"&&(p.isEvaluator=!0,p.autoRerun=!0,p.autoRerunRounds=c.data.autoRerunRounds,p.rolePrompt||(p.roleMode="inherit")),h==="fanout"&&(p.stepKind="fanout",p.fanoutRoles=c.data.fanoutRoles),{id:d,type:"thought",position:{...c.position},width:c.width,height:c.height,zIndex:c.zIndex,dragHandle:".drag-handle",data:p}}),r=new Set(e.filter(c=>(c.data.stepKind??"step")==="review").map(c=>n.get(c.id))),s=t.filter(c=>n.has(c.source)&&n.has(c.target)).map(c=>{const d=n.get(c.source),h=n.get(c.target);return r.has(h)?{id:`watch-${d}-${h}`,source:d,target:h,sourceHandle:"branch",targetHandle:"left",type:"smoothstep",style:{stroke:nt.watch,strokeWidth:2,strokeDasharray:"4 4"},animated:!0,markerEnd:{type:"arrowclosed",color:nt.watch,width:18,height:18},data:{isCrossLink:!0,isWatch:!0,followsTip:!0}}:{id:`edge-${d}-${h}`,source:d,target:h,sourceHandle:"continue",targetHandle:"top",type:"smoothstep",style:{stroke:nt.accent,strokeWidth:2},animated:!1,markerEnd:{type:"arrowclosed",color:nt.accent,width:18,height:18},data:{}}}),l=new Set(s.map(c=>c.target));for(const c of a)l.has(c.id)||(c.data.isRoot=!0);return{nodes:nr(a,s),edges:s}}const K7=1,jb=1;function pm(e){return e.replace(/[\\/:*?"<>|]/g,"_").trim()||"canvas"}function Zd(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 Pb(e){await navigator.clipboard.writeText(e),Ke("success",Ie("toast.copied"))}function Ts(){const{projects:e,activeId:t}=Nn.getState();return e.find(n=>n.id===t)?.name??"canvas"}async function of(e){const{nodes:t}=oe.getState(),{confirmIfSensitive:n}=await Kt(async()=>{const{confirmIfSensitive:p}=await import("./sensitive-scan-
|
|
140
|
+
`+l,c.data.responses=[c.data.response])}}}}return{nodes:nr(t,n),edges:n}}function UH(e){const t=V7(e),n=[];if(t==="chatgpt")for(const a of e){const r=a.mapping??{},s=Object.values(r).filter(l=>["user","assistant"].includes(l.message?.author?.role??"")&&Y7(l)).length;s!==0&&n.push({title:a.title||"Untitled",messageCount:s,source:"chatgpt",build:()=>BH(r)})}else if(t==="claude")for(const a of e){const r=a.chat_messages??[],s=r.filter(l=>$7(l)).length;s!==0&&n.push({title:a.name||"Untitled",messageCount:s,source:"claude",build:()=>HH(r)})}return n}function FH(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 qH(e){const t=e;return!!t&&typeof t=="object"&&t.kind==="thoughtdag-paradigm"&&Array.isArray(t.nodes)&&Array.isArray(t.edges)}const VH=()=>({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 WH(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={...VH(),question:m,rolePrompt:c.data.rolePrompt||void 0,roleMode:c.data.rolePrompt?"reset":"inherit"};return h==="human"&&(p.stepKind="human",p.question="",p.instruction=c.data.instruction?.trim()||void 0,p.rolePrompt=void 0,p.roleMode="inherit"),h==="prompt"&&(p.stepKind="prompt",p.webSearch=c.data.webSearch,p.scholarSearch=c.data.scholarSearch,p.autoRerun=c.data.autoRerun,p.autoRerunRounds=c.data.autoRerunRounds),(h==="note"||h==="file"||h==="link"||h==="frame")&&(p.stepKind=h,p.question=c.data.question||"",p.attachments=c.data.attachments??[],p.tokenCount=c.data.tokenCount??0,p.linkUrl=c.data.linkUrl,p.linkTitle=c.data.linkTitle,p.linkFetchedAt=c.data.linkFetchedAt,p.frameColor=c.data.frameColor),h==="review"&&(p.isEvaluator=!0,p.autoRerun=!0,p.autoRerunRounds=c.data.autoRerunRounds,p.rolePrompt||(p.roleMode="inherit")),h==="fanout"&&(p.stepKind="fanout",p.fanoutRoles=c.data.fanoutRoles),{id:d,type:"thought",position:{...c.position},width:c.width,height:c.height,zIndex:c.zIndex,dragHandle:".drag-handle",data:p}}),r=new Set(e.filter(c=>(c.data.stepKind??"step")==="review").map(c=>n.get(c.id))),s=t.filter(c=>n.has(c.source)&&n.has(c.target)).map(c=>{const d=n.get(c.source),h=n.get(c.target);return r.has(h)?{id:`watch-${d}-${h}`,source:d,target:h,sourceHandle:"branch",targetHandle:"left",type:"smoothstep",style:{stroke:nt.watch,strokeWidth:2,strokeDasharray:"4 4"},animated:!0,markerEnd:{type:"arrowclosed",color:nt.watch,width:18,height:18},data:{isCrossLink:!0,isWatch:!0,followsTip:!0}}:{id:`edge-${d}-${h}`,source:d,target:h,sourceHandle:"continue",targetHandle:"top",type:"smoothstep",style:{stroke:nt.accent,strokeWidth:2},animated:!1,markerEnd:{type:"arrowclosed",color:nt.accent,width:18,height:18},data:{}}}),l=new Set(s.map(c=>c.target));for(const c of a)l.has(c.id)||(c.data.isRoot=!0);return{nodes:nr(a,s),edges:s}}const K7=1,jb=1;function pm(e){return e.replace(/[\\/:*?"<>|]/g,"_").trim()||"canvas"}function Zd(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 Pb(e){await navigator.clipboard.writeText(e),Ke("success",Ie("toast.copied"))}function Ts(){const{projects:e,activeId:t}=Nn.getState();return e.find(n=>n.id===t)?.name??"canvas"}async function of(e){const{nodes:t}=oe.getState(),{confirmIfSensitive:n}=await Kt(async()=>{const{confirmIfSensitive:p}=await import("./sensitive-scan-NBqP2Srd.js");return{confirmIfSensitive:p}},[]);if(!await n(t))return;localStorage.setItem("thoughtdag.lastBackupAt",String(Date.now()));const{nodes:a,edges:r,events:s}=oe.getState(),l=await D7(a),{projects:c,activeId:d}=Nn.getState(),h=Ts(),m=JSON.stringify({version:K7,name:h,projectId:d,exportedAt:new Date().toISOString(),instantiatedFrom:c.find(p=>p.id===d)?.instantiatedFrom,...e?.sharedReadonly?{sharedReadonly:!0}:{},nodes:Ao(l),edges:r,events:s});Zd(`${pm(h)}.thoughtdag.json`,m,"application/json"),Ke("success",qe(Ie("toast.exported"),{name:h}))}function GH(){const{nodes:e,edges:t}=oe.getState(),n=Ts(),a=JSON.stringify({kind:"thoughtdag-paradigm",version:1,name:n,nodes:Ao(e),edges:t});Zd(`${pm(n)}.paradigm.json`,a,"application/json"),Ke("success",qe(Ie("toast.exported"),{name:n}))}async function YH(e){const t=await e.text();let n;try{n=JSON.parse(t)}catch{const{anyRunnerSessionConversation:r}=await Kt(async()=>{const{anyRunnerSessionConversation:l}=await import("./index-DbmziCje.js");return{anyRunnerSessionConversation:l}},[]),s=await r(t);return s?{kind:"chat",conversations:[s]}:(Ke("error",Ie("toast.importFailedJson")),{kind:"error"})}if(qH(n)){const r=crypto.randomUUID(),s=await Db(await X7(n.nodes));return await zr(ni(r),JSON.stringify({state:{nodes:s,edges:n.edges},version:jb})),await jc(r,n.name||"Paradigm","paradigm"),Ke("success",qe(Ie("toast.imported"),{name:n.name,n:n.nodes.length})),{kind:"own",ok:!0}}if(n?.format==="thoughtdag-manifest")return Ke("error",Ie("toast.importManifest"),9e3),{kind:"error"};const a=V7(n);if(a==="chatgpt"||a==="claude"){const r=UH(n);return r.length===0?(Ke("error",Ie("toast.importNoConversations")),{kind:"error"}):{kind:"chat",conversations:r}}return{kind:"own",ok:await XH(e,n)}}function $H(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 KH(e){let t=null,n=0;for(const a of e){const{nodes:r,edges:s}=a.build();if(r.length===0)continue;if(t===null){const{useUiStore:c}=await Kt(async()=>{const{useUiStore:d}=await Promise.resolve().then(()=>um);return{useUiStore:d}},void 0);c.getState().setArrivalFocusNodeId(r[r.length-1].id)}const l=crypto.randomUUID();await zr(ni(l),JSON.stringify({state:{nodes:Ao(r),edges:s},version:jb})),await jc(l,a.title.slice(0,60)),t??=l,n+=r.length}t&&Ke("success",qe(Ie("toast.importedChats"),{n:e.length,m:n}))}async function X7(e){const t=await Io();if(!t||t.models.length===0)return e;const n=new Set,a=new Set,r=e.map(s=>{const l=s.data?.model;if(!l)return s;const c=w7(l,t.models);return c===l?s:c?(n.add(`${l} → ${c}`),{...s,data:{...s.data,model:c}}):(a.add(l),s)});return n.size&&Ke("info",qe(Ie("import.modelsRemapped"),{list:[...n].join(",")}),9e3),a.size&&Ke("info",qe(Ie("import.modelsMissing"),{list:[...a].join(",")}),1e4),r}async function XH(e,t){let n;try{n=t??JSON.parse(await e.text())}catch{return Ke("error",Ie("toast.importFailedJson")),!1}if(!Array.isArray(n.nodes)||!Array.isArray(n.edges))return Ke("error",Ie("toast.importFailedMissing")),!1;if(n.nodes.length>0&&!$H(n.nodes))return Ke("error",Ie("toast.importFailedShape"),9e3),!1;if(n.sharedReadonly&&!await Es({title:Ie("import.readonlyTitle"),message:Ie("import.readonlyConfirm"),confirmLabel:Ie("common.confirm")}))return!1;if(n.sourceSession?.sessionId){const{useProjects:l,switchProject:c}=await Kt(async()=>{const{useProjects:h,switchProject:m}=await Promise.resolve().then(()=>mm);return{useProjects:h,switchProject:m}},void 0),d=l.getState().projects.find(h=>h.sourceSession?.sessionId===n.sourceSession.sessionId);if(d)return await c(d.id),Ke("info",qe(Ie("toast.importAlreadySubscribed"),{name:d.name}),9e3),!0}const a=crypto.randomUUID(),r=await Db(await X7(n.nodes));await zr(ni(a),JSON.stringify({state:{nodes:Ao(r),edges:n.edges,...Array.isArray(n.events)?{events:n.events}:{}},version:jb}));const s=n.name?.trim()||e.name.replace(/\.thoughtdag\.json$|\.json$/i,"")||"Imported canvas";return await jc(a,s,"chat",{instantiatedFrom:n.instantiatedFrom,sourceSession:n.sourceSession}),Ke("success",qe(Ie("toast.imported"),{name:s,n:n.nodes.length})),!0}function QH(){const{events:e}=oe.getState();if(e.length===0)return;const t=r=>`"${r.replace(/"/g,'""')}"`,a=["t,op,id,detail",...e.map(r=>[r.t,r.op,r.id??"",r.d?t(JSON.stringify(r.d)):""].join(","))].join(`
|
|
141
141
|
`);Zd(`${pm(Ts())}.events.csv`,a,"text/csv"),Ke("success",qe(Ie("toast.exported"),{name:Ts()}))}function ZH(e){const t=[`## Q: ${e.data.question}`,""],n=e.data.attachments||[];return n.length>0&&t.push(`> ${Ie("export.attachmentsLabel")} ${n.map(a=>a.name).join(", ")}`,""),e.data.branchContext&&t.push(`> Exploring from: "${e.data.branchContext.slice(0,120)}"`,""),t.push(e.data.response||"_(no response)_",""),t.join(`
|
|
142
142
|
`)}function Q7(e,t){const n=e.reduce((a,r)=>a+$n(r.data.question+r.data.response),0);return[`# ${Ts()}`,"",`> ${t} · exported ${new Date().toISOString().slice(0,10)} · ${e.length} nodes · ~${n} tok`,"",e.map(ZH).join(`
|
|
143
143
|
---
|
|
@@ -492,17 +492,17 @@ ${Ie("continue.genOpen")}
|
|
|
492
492
|
${c.join(`
|
|
493
493
|
`)||"-"}`}]),h=c7(new Date().toISOString()).slice(0,10),m=Ite(n.position);Qr("note",m,{question:`**📌 ${h} · ${Ie("continue.recapTag")}**
|
|
494
494
|
|
|
495
|
-
${d.trim()}`}),EN.current?.setCenter((n.position.x+m.x)/2+260,(n.position.y+m.y)/2+140,{zoom:.75,duration:600}),Ke("success",Ie("continue.noteDropped"))}catch(a){Ke("error",a instanceof Error?a.message:String(a))}}}function Dte({x:e,y:t,nodeId:n,onClose:a}){const r=Gt(),s=j.useRef(null),l=oe(_=>_.nodes.find(A=>A.id===n));if(j.useEffect(()=>{const _=C=>{s.current?.contains(C.target)||a()},A=C=>{C.key==="Escape"&&a()};return window.addEventListener("mousedown",_),window.addEventListener("keydown",A),()=>{window.removeEventListener("mousedown",_),window.removeEventListener("keydown",A)}},[a]),!l)return null;const c=l.data.stepKind,d=!!c,h=!d&&!!l.data.response&&!l.data.isLoading,m=d?c==="note"||c==="link"?l.data.question:"":l.data.response,p="w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5",x="text-ink-faint shrink-0",b=200,y=340,E=Math.min(e,window.innerWidth-b-8),T=Math.min(t,window.innerHeight-y-8),w=_=>()=>{a(),_()};return $a.createPortal(u.jsxs("div",{ref:s,className:"fixed z-[70] bg-card border border-line rounded-xl shadow-lg py-1 w-[200px] animate-fade-in",style:{left:E,top:T},children:[!d&&u.jsxs("button",{className:p,onClick:w(()=>{oe.getState().setSelectedNodeId(n),ye.getState().setPanelOpen(!0)}),children:[u.jsx(To,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.openPanel")]}),h&&u.jsxs("button",{className:p,onClick:w(()=>ye.getState().setResponseViewerNodeId(n)),children:[u.jsx(t7,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.readingView")]}),h&&u.jsxs("button",{className:p,onClick:w(()=>{oe.getState().rerunNode(n)}),children:[u.jsx(ir,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.rerun")]}),h&&u.jsxs("button",{className:p,title:Ie("actions.regenBranchTitle"),onClick:w(()=>{oe.getState().regenerate(n)}),children:[u.jsx(Q8,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.regenBranch")]}),h&&u.jsxs("button",{className:p,onClick:w(()=>{kN(n)}),children:[u.jsx(Bi,{size:14,strokeWidth:1.75,className:x})," ",r("continue.summarize")]}),m&&u.jsxs("button",{className:p,onClick:w(()=>{navigator.clipboard.writeText(m).then(()=>Ke("success",Ie("ctx.copied")))}),children:[u.jsx(Os,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.copyContent")]}),!d&&u.jsxs("button",{className:p,title:Ie("exp.takeTitle"),onClick:w(()=>{Kt(()=>import("./experiment-loop-
|
|
495
|
+
${d.trim()}`}),EN.current?.setCenter((n.position.x+m.x)/2+260,(n.position.y+m.y)/2+140,{zoom:.75,duration:600}),Ke("success",Ie("continue.noteDropped"))}catch(a){Ke("error",a instanceof Error?a.message:String(a))}}}function Dte({x:e,y:t,nodeId:n,onClose:a}){const r=Gt(),s=j.useRef(null),l=oe(_=>_.nodes.find(A=>A.id===n));if(j.useEffect(()=>{const _=C=>{s.current?.contains(C.target)||a()},A=C=>{C.key==="Escape"&&a()};return window.addEventListener("mousedown",_),window.addEventListener("keydown",A),()=>{window.removeEventListener("mousedown",_),window.removeEventListener("keydown",A)}},[a]),!l)return null;const c=l.data.stepKind,d=!!c,h=!d&&!!l.data.response&&!l.data.isLoading,m=d?c==="note"||c==="link"?l.data.question:"":l.data.response,p="w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5",x="text-ink-faint shrink-0",b=200,y=340,E=Math.min(e,window.innerWidth-b-8),T=Math.min(t,window.innerHeight-y-8),w=_=>()=>{a(),_()};return $a.createPortal(u.jsxs("div",{ref:s,className:"fixed z-[70] bg-card border border-line rounded-xl shadow-lg py-1 w-[200px] animate-fade-in",style:{left:E,top:T},children:[!d&&u.jsxs("button",{className:p,onClick:w(()=>{oe.getState().setSelectedNodeId(n),ye.getState().setPanelOpen(!0)}),children:[u.jsx(To,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.openPanel")]}),h&&u.jsxs("button",{className:p,onClick:w(()=>ye.getState().setResponseViewerNodeId(n)),children:[u.jsx(t7,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.readingView")]}),h&&u.jsxs("button",{className:p,onClick:w(()=>{oe.getState().rerunNode(n)}),children:[u.jsx(ir,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.rerun")]}),h&&u.jsxs("button",{className:p,title:Ie("actions.regenBranchTitle"),onClick:w(()=>{oe.getState().regenerate(n)}),children:[u.jsx(Q8,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.regenBranch")]}),h&&u.jsxs("button",{className:p,onClick:w(()=>{kN(n)}),children:[u.jsx(Bi,{size:14,strokeWidth:1.75,className:x})," ",r("continue.summarize")]}),m&&u.jsxs("button",{className:p,onClick:w(()=>{navigator.clipboard.writeText(m).then(()=>Ke("success",Ie("ctx.copied")))}),children:[u.jsx(Os,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.copyContent")]}),!d&&u.jsxs("button",{className:p,title:Ie("exp.takeTitle"),onClick:w(()=>{Kt(()=>import("./experiment-loop-cKs-OaUA.js"),[]).then(_=>_.takeToExperiment(n,"branch"))}),"data-take-to-experiment":!0,children:[u.jsx(xP,{size:14,strokeWidth:1.75,className:x})," ",r("exp.take")]}),!d&&u.jsxs("button",{className:p,title:Ie("exp.continueTitle"),onClick:w(()=>{Kt(()=>import("./experiment-loop-cKs-OaUA.js"),[]).then(_=>_.takeToExperiment(n,"continue"))}),"data-take-to-continue":!0,children:[u.jsx(To,{size:14,strokeWidth:1.75,className:x})," ",r("exp.continue")]}),u.jsxs("button",{className:p,onClick:w(()=>oe.getState().duplicateNode(n)),children:[u.jsx(pP,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.duplicate")]}),u.jsxs("button",{className:p,onClick:w(()=>oe.getState().setArchived([n],!l.data.archived)),children:[l.data.archived?u.jsx(W8,{size:14,strokeWidth:1.75,className:x}):u.jsx(Mo,{size:14,strokeWidth:1.75,className:x}),l.data.archived?r("ctx.unarchive"):r("archive.label")]}),u.jsx("div",{className:"h-px bg-line my-1"}),u.jsxs("button",{className:"w-full text-left px-3 py-2 text-xs text-red-600 hover:bg-red-50 transition-colors flex items-center gap-2.5",onClick:w(()=>{Es({title:Ie("confirm.deleteNodesTitle"),message:qe(Ie("confirm.deleteNodes"),{n:1}),confirmLabel:Ie("common.delete"),danger:!0}).then(_=>{_&&oe.getState().deleteNode(n)})}),children:[u.jsx(Ua,{size:14,strokeWidth:1.75,className:"shrink-0"})," ",r("common.delete")]})]}),document.body)}function Ote({onLocate:e}){const t=ye(C=>C.highlightsOverviewOpen),n=ye(C=>C.setHighlightsOverviewOpen),a=oe(C=>C.nodes),r=oe(C=>C.removeHighlight),s=oe(C=>C.weaveHighlights),l=Gt(),[c,d]=j.useState("time"),[h,m]=j.useState(new Set),[p,x]=j.useState(""),b=j.useMemo(()=>{const C=[];for(const D of a){const M=D.data.question.replace(/\s+/g," ").trim().slice(0,60)||"—";for(const N of D.data.highlights||[])C.push({hlId:N.id,text:N.text,at:N.at,nodeId:D.id,nodeTitle:M})}const O=c==="time"?[...C].sort((D,M)=>(M.at??"").localeCompare(D.at??"")):C;return O.map((D,M)=>({...D,showGroup:c==="node"&&(M===0||O[M-1].nodeTitle!==D.nodeTitle)}))},[a,c]);if(!t)return null;const y=C=>{const O=new Set(h);O.has(C)?O.delete(C):O.add(C),m(O)},E=()=>{n(!1),m(new Set),x("")},T=()=>{const C=[...h].filter(D=>b.some(M=>M.hlId===D));if(C.length===0)return;const O=[...new Set(b.filter(D=>C.includes(D.hlId)).map(D=>D.nodeId))];E(),s(O,p.trim()||void 0,C)},w=()=>{const C=b.map(O=>`- ${O.text}
|
|
496
496
|
— ${O.nodeTitle}${O.at?` · ${O.at.slice(0,10)}`:""}`);zb(`# ${l("hlov.title")}
|
|
497
497
|
|
|
498
498
|
${C.join(`
|
|
499
499
|
`)}
|
|
500
500
|
`)},_="shrink-0 text-2xs font-mono text-accent bg-accent/10 hover:bg-accent/20 rounded-full px-1.5 py-0.5 transition-colors",A=(C,O)=>u.jsx("button",{onClick:()=>d(C),className:`text-2xs px-2.5 py-1 rounded-full transition-colors ${c===C?"bg-accent/10 text-accent":"text-ink-faint hover:bg-wash"}`,children:O});return $a.createPortal(u.jsx("div",{className:"fixed inset-0 z-[60] bg-ink/30 backdrop-blur-sm flex items-center justify-center p-6",onClick:E,children:u.jsxs("div",{className:"bg-card rounded-2xl shadow-2xl border border-line w-[640px] max-h-[80vh] flex flex-col",onClick:C=>C.stopPropagation(),children:[u.jsxs("div",{className:"flex items-center gap-2 px-5 py-3 border-b border-line shrink-0",children:[u.jsx(Td,{size:15,strokeWidth:1.75,className:"text-amber-500"}),u.jsx("span",{className:"text-sm font-semibold text-ink",children:l("hlov.title")}),u.jsx("span",{className:"text-2xs text-ink-faint",children:qe(l("hlov.count"),{n:b.length})}),u.jsx("div",{className:"flex-1"}),A("time",l("hlov.byTime")),A("node",l("hlov.byNode")),u.jsx("button",{onClick:E,className:"text-ink-faint hover:text-ink w-7 h-7 rounded-lg hover:bg-wash flex items-center justify-center transition-colors ml-1",children:u.jsx(bn,{size:15,strokeWidth:1.75})})]}),u.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-5 py-3",children:[b.length===0&&u.jsx("p",{className:"text-xs text-ink-faint italic py-2",children:l("hlov.empty")}),b.map(C=>u.jsxs("div",{children:[C.showGroup&&u.jsx("div",{className:"text-2xs text-ink-faint font-medium mt-3 mb-1 first:mt-0 truncate",children:C.nodeTitle}),u.jsxs("div",{className:"group flex items-start gap-2.5 py-1.5 border-b border-line/50 last:border-0",children:[u.jsx("input",{type:"checkbox",checked:h.has(C.hlId),onChange:()=>y(C.hlId),className:"mt-1 accent-amber-500 shrink-0"}),u.jsx("span",{className:"flex-1 text-sm text-ink leading-relaxed min-w-0",children:u.jsx("mark",{className:"bg-amber-100 text-amber-800 px-0.5 rounded",children:C.text})}),c==="time"&&u.jsxs("button",{className:_,onClick:()=>{E(),e(C.nodeId)},title:l("hlov.locateTitle"),children:[C.nodeTitle.slice(0,14),C.nodeTitle.length>14?"…":""]}),c==="node"&&u.jsx("button",{className:_,onClick:()=>{E(),e(C.nodeId)},title:l("hlov.locateTitle"),children:"↦"}),C.at&&u.jsx("span",{className:"shrink-0 text-2xs text-ink-faint font-mono mt-0.5",children:C.at.slice(5,10)}),u.jsx("button",{onClick:()=>r(C.nodeId,C.hlId),title:l("common.delete"),className:"text-ink-faint hover:text-red-500 w-5 h-5 rounded-full flex items-center justify-center transition-colors shrink-0 opacity-0 group-hover:opacity-100",children:u.jsx(Ua,{size:12,strokeWidth:1.75})})]})]},C.hlId))]}),u.jsxs("div",{className:"px-5 py-3 border-t border-line shrink-0 space-y-2",children:[h.size>0&&u.jsxs("div",{className:"flex gap-1.5",children:[u.jsx("input",{type:"text",value:p,onChange:C=>x(C.target.value),onKeyDown:C=>{C.key==="Enter"&&!Ya(C)&&T()},placeholder:l("toolbar.intentPlaceholder"),className:"flex-1 text-xs border border-amber-500/30 rounded-lg px-3 py-2 focus:outline-none focus:ring-1 focus:ring-amber-500 bg-amber-500/5"}),u.jsx("button",{onClick:T,className:"text-xs bg-amber-500 hover:bg-amber-400 text-white px-3 py-2 rounded-lg transition-colors shrink-0",children:qe(l("hlov.weavePicked"),{n:h.size})})]}),u.jsxs("div",{className:"flex items-center",children:[u.jsx("span",{className:"text-2xs text-ink-faint",children:h.size>0?qe(l("hlov.picked"),{n:h.size}):l("hlov.pickHint")}),u.jsx("div",{className:"flex-1"}),b.length>0&&u.jsxs("button",{onClick:w,className:"flex items-center gap-1.5 text-2xs text-ink-faint hover:text-ink-muted transition-colors",title:l("hlov.exportTitle"),children:[u.jsx(Ed,{size:12,strokeWidth:1.75})," ",l("hlov.export")]})]})]})]})}),document.body)}const Rte={pdf:gi,img:DP,txt:gi,note:Bi,link:So};function Lte({onLocate:e}){const t=ye(x=>x.materialsOverviewOpen),n=ye(x=>x.setMaterialsOverviewOpen),a=oe(x=>x.nodes),r=Gt(),[s,l]=j.useState("time"),c=j.useMemo(()=>{const x=[];for(const y of a){const E=y.data.stepKind;if(E==="note"||E==="link"){const w=E==="link"?y.data.linkTitle||y.data.linkUrl||"—":y.data.question.split(`
|
|
501
|
-
`)[0].replace(/^#+\s*/,"").slice(0,60)||"—";x.push({key:y.id,name:w,icon:E,at:y.data.createdAt,nodeId:y.id,nodeTitle:w,canOpen:!0});continue}const T=y.data.question.replace(/\s+/g," ").trim().slice(0,60)||(E==="file"?r("glyph.file"):"—");for(const w of y.data.attachments||[]){const _=w.type==="application/pdf"?"pdf":w.type.startsWith("image/")?"img":"txt";x.push({key:w.id,name:w.name,icon:_,sizeKB:w.size/1024,at:w.addedAt,nodeId:y.id,nodeTitle:T,canOpen:_==="pdf"})}}const b=s==="time"?[...x].sort((y,E)=>(E.at??"").localeCompare(y.at??"")):x;return b.map((y,E)=>({...y,showGroup:s==="node"&&(E===0||b[E-1].nodeTitle!==y.nodeTitle)}))},[a,s,r]);if(!t)return null;const d=()=>n(!1),h=x=>{d(),ye.getState().setReaderNodeId(x)},m="shrink-0 text-2xs font-mono text-accent bg-accent/10 hover:bg-accent/20 rounded-full px-1.5 py-0.5 transition-colors",p=(x,b)=>u.jsx("button",{onClick:()=>l(x),className:`text-2xs px-2.5 py-1 rounded-full transition-colors ${s===x?"bg-accent/10 text-accent":"text-ink-faint hover:bg-wash"}`,children:b});return $a.createPortal(u.jsx("div",{className:"fixed inset-0 z-[60] bg-ink/30 backdrop-blur-sm flex items-center justify-center p-6",onClick:d,children:u.jsxs("div",{className:"bg-card rounded-2xl shadow-2xl border border-line w-[640px] max-h-[80vh] flex flex-col",onClick:x=>x.stopPropagation(),children:[u.jsxs("div",{className:"flex items-center gap-2 px-5 py-3 border-b border-line shrink-0",children:[u.jsx(xi,{size:15,strokeWidth:1.75,className:"text-warm"}),u.jsx("span",{className:"text-sm font-semibold text-ink",children:r("matov.title")}),u.jsx("span",{className:"text-2xs text-ink-faint",children:qe(r("matov.count"),{n:c.length})}),u.jsx("div",{className:"flex-1"}),p("time",r("hlov.byTime")),p("node",r("hlov.byNode")),u.jsx("button",{onClick:d,className:"text-ink-faint hover:text-ink w-7 h-7 rounded-lg hover:bg-wash flex items-center justify-center transition-colors ml-1",children:u.jsx(bn,{size:15,strokeWidth:1.75})})]}),u.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-5 py-3",children:[c.length===0&&u.jsx("p",{className:"text-xs text-ink-faint italic py-2",children:r("matov.empty")}),c.map(x=>{const b=Rte[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(To,{size:14,strokeWidth:1.75})})]})]},x.key)})]})]})}),document.body)}function jte(e){const t=e.data.stepKind;return t==="note"||t==="file"||t==="link"||t==="frame"?t:e.data.condensedFrom?.length?"distill":"qa"}function Pte(e,t){let n=0,a=e.indexOf(t);for(;a!==-1;)n+=1,a=e.indexOf(t,a+t.length);return n}function zte(e,t,n){const r=Math.max(0,t-40),s=Math.min(e.length,t+n+60),l=r>0?"…":"",c=s<e.length?"…":"";return{snippet:l+e.slice(r,s)+c,matchStart:l.length+(t-r)}}function Bte(e,t){const n=t.trim().toLowerCase();if(!n)return[];const a=[];for(const r of e){const s=r.data;if(s.stepKind==="fanout")continue;const l=[s.question??"",s.response??"",...(s.highlights??[]).map(p=>p.text),s.linkTitle??"",...(s.attachments??[]).map(p=>p.name),s.summaries?.[s.responseIndex]??s.summary??""];let c=0,d=null;for(const p of l){if(!p)continue;const x=p.toLowerCase(),b=x.indexOf(n);b!==-1&&(c+=Pte(x,n),d||(d={text:p,at:b}))}if(!d)continue;const{snippet:h,matchStart:m}=zte(d.text,d.at,n.length);a.push({nodeId:r.id,kind:jte(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 Hte={qa:n7,note:Bi,file:gi,link:So,frame:vx,distill:om},Y1=50;function Ute({open:e,onClose:t,onLocate:n}){const a=Gt(),r=oe(w=>w.nodes),s=ye(w=>w.setSearchHitIds),[l,c]=j.useState(""),[d,h]=j.useState(0),m=j.useRef(null),[p,x]=j.useState(e);p!==e&&(x(e),e&&(c(""),h(0))),j.useEffect(()=>{e&&setTimeout(()=>m.current?.focus(),50)},[e]);const[b,y]=j.useState("");j.useEffect(()=>{const w=setTimeout(()=>y(l),120);return()=>clearTimeout(w)},[l]);const E=j.useMemo(()=>e?Bte(r,b):[],[e,r,b]);if(j.useEffect(()=>{if(!e||!b.trim()){s(null);return}s(new Set(E.map(w=>w.nodeId)))},[e,b,E,s]),j.useEffect(()=>()=>s(null),[s]),!e)return null;const T=w=>{n(w.nodeId);const _=b.trim().toLowerCase();setTimeout(()=>{const A=document.querySelector("[data-focus-panel]");if(!A||!_)return;const C=document.createTreeWalker(A,NodeFilter.SHOW_TEXT);let O;for(;O=C.nextNode();)if(O.textContent?.toLowerCase().includes(_)){const D=O.parentElement;D?.scrollIntoView({block:"center",behavior:"smooth"}),D?.animate([{backgroundColor:"rgba(107, 92, 231, 0.22)"},{backgroundColor:"transparent"}],{duration:1800,easing:"ease-out"});break}},500)};return u.jsx("div",{className:"absolute top-4 left-1/2 -translate-x-1/2 z-20 w-[460px]","data-canvas-search":!0,children:u.jsxs("div",{className:"bg-card border border-line rounded-xl shadow-xl overflow-hidden",children:[u.jsxs("div",{className:"flex items-center gap-2 px-4 py-2.5 transition-shadow focus-within:ring-1 focus-within:ring-accent/40",children:[u.jsx(Af,{size:15,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),u.jsx("input",{ref:m,type:"text",value:l,onChange:w=>{c(w.target.value),h(0)},onKeyDown:w=>{w.key==="Escape"&&(w.stopPropagation(),t()),w.key==="ArrowDown"&&(w.preventDefault(),h(_=>Math.min(_+1,E.length-1))),w.key==="ArrowUp"&&(w.preventDefault(),h(_=>Math.max(_-1,0))),w.key==="Enter"&&!Ya(w)&&E[d]&&(w.preventDefault(),T(E[d]))},placeholder:a("search.placeholder"),className:"flex-1 bg-transparent text-sm text-ink placeholder-ink-faint focus:outline-none","data-search-input":!0}),l&&u.jsx("span",{className:"text-2xs text-ink-faint shrink-0",children:qe(a("search.count"),{n:E.length})}),u.jsx("button",{onClick:t,className:"text-ink-faint hover:text-ink transition-colors shrink-0",children:u.jsx(bn,{size:14,strokeWidth:1.75})})]}),E.length>0&&u.jsxs("ul",{className:"border-t border-line/60 max-h-72 overflow-y-auto py-1",children:[E.slice(0,Y1).map((w,_)=>{const A=Hte[w.kind],O=r.find(D=>D.id===w.nodeId)?.data.question||"—";return u.jsx("li",{children:u.jsxs("button",{onClick:()=>T(w),onMouseEnter:()=>h(_),className:`w-full text-left px-4 py-2 transition-colors ${_===d?"bg-accent/8":""} ${w.archived?"opacity-55":""}`,"data-search-hit-row":!0,children:[u.jsxs("p",{className:`text-xs font-medium truncate flex items-center gap-1.5 ${_===d?"text-accent":"text-ink"}`,children:[u.jsx(A,{size:12,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),u.jsx("span",{className:"truncate flex-1 min-w-0",children:O}),w.archived&&u.jsx(Mo,{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)}),E.length>Y1&&u.jsx("li",{className:"px-4 py-2 text-2xs text-ink-faint",children:qe(a("search.more"),{n:E.length-Y1})})]})]})})}const DE=new Set(["note","file","link"]),Ai=e=>{const t=(e?.data.question??"").replace(/\s+/g," ").trim();return t.length>24?`${t.slice(0,24)}…`:t||"(空)"};function $1(e,t,n){const a=new Set([e]),r=[e];for(;r.length;){const s=r.shift();for(const l of n.get(s)??[]){if(l===t)return!0;a.has(l)||(a.add(l),r.push(l))}}return!1}function K1(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 OE(e,t){const n=[],a=new Map(e.map(N=>[N.id,N])),r=t.filter(N=>!N.data?.isCrossLink),s=t.filter(N=>N.data?.isCrossLink),l=K1(r),c=K1(t);for(const N of r){const R=K1(r.filter(B=>B.id!==N.id));$1(N.source,N.target,R)&&n.push({tier:1,kind:"residual-edge",fixable:!0,params:{a:Ai(a.get(N.source)),b:Ai(a.get(N.target))},nodeIds:[N.target,N.source],edgeIds:[N.id]})}for(const N of s)$1(N.source,N.target,l)&&n.push({tier:1,kind:"shadow-reference",fixable:!0,params:{a:Ai(a.get(N.source)),b:Ai(a.get(N.target))},nodeIds:[N.target,N.source],edgeIds:[N.id]});const d=new Map;for(const N of r)d.has(N.source)||d.set(N.source,[]),d.get(N.source).push(N.target);const h=[];for(const N of d.values()){const R=N.filter(H=>a.get(H)?.data.stepKind==="prompt"),B=N.filter(H=>a.get(H)?.data.isBranch);R.length>=2&&h.push(R),B.length>=2&&h.push(B)}for(const N of h)for(const R of N)for(const B of N)if(R!==B&&$1(R,B,c)){const H=t.find(Y=>Y.source===R&&Y.target===B);n.push({tier:1,kind:"blind-pool-breach",fixable:!!H,params:{a:Ai(a.get(B)),b:Ai(a.get(R))},nodeIds:[B,R],edgeIds:H?[H.id]:[]})}for(const N of h){const R=N.map(H=>new Set(t.filter(Y=>Y.target===H).map(Y=>Y.source))),B=new Set([...R[0]].filter(H=>R.every(Y=>Y.has(H))));N.forEach((H,Y)=>{const Z=[...R[Y]].filter(q=>!B.has(q)&&!N.includes(q));Z.length>0&&n.push({tier:1,kind:"pool-asymmetry",fixable:!1,params:{a:Ai(a.get(H)),n:Z.length},nodeIds:[H,...Z],edgeIds:[]})})}const m=e.filter(N=>!DE.has(N.data.stepKind??"")&&N.data.stepKind!=="frame"),p=new Map,x=new Map,b=N=>$n(N.data.question+N.data.response),y=new Map;for(const N of m)y.set(N.id,0);for(const N of r)y.has(N.target)&&y.has(N.source)&&y.set(N.target,(y.get(N.target)??0)+1);const E=m.filter(N=>(y.get(N.id)??0)===0).map(N=>N.id),T=[],w=new Map(y);for(;E.length;){const N=E.shift();T.push(N);for(const R of l.get(N)??[])w.has(R)&&(w.set(R,w.get(R)-1),w.get(R)===0&&E.push(R))}for(const N of T){const R=a.get(N),B=r.filter(Z=>Z.target===N&&p.has(Z.source)),H=B.length?Math.max(...B.map(Z=>p.get(Z.source)))+1:1,Y=B.length?Math.max(...B.map(Z=>x.get(Z.source)))+b(R):b(R);p.set(N,H),x.set(N,Y)}const _=m.filter(N=>!(l.get(N.id)??[]).length&&!N.data.archived),A=_.filter(N=>(p.get(N.id)??0)>=8||(x.get(N.id)??0)>=15e3).sort((N,R)=>(p.get(R.id)??0)-(p.get(N.id)??0)).slice(0,3);for(const N of A)n.push({tier:2,kind:"long-chain",fixable:!1,params:{a:Ai(N),d:p.get(N.id)??0,tok:x.get(N.id)??0},nodeIds:[N.id],edgeIds:[]});const C=_.filter(N=>N.data.response);C.length>=4&&n.push({tier:2,kind:"open-branches",fixable:!1,params:{n:C.length},nodeIds:C.map(N=>N.id),edgeIds:[]});for(const N of m){const R=r.filter(H=>H.target===N.id).length,B=(l.get(N.id)??[]).length;R>=2&&B>=1&&n.push({tier:2,kind:"collider-continuation",fixable:!1,params:{a:Ai(N),n:R},nodeIds:[N.id],edgeIds:[]})}const O=e.filter(N=>DE.has(N.data.stepKind??"")&&!t.some(R=>R.source===N.id));O.length>0&&n.push({tier:2,kind:"orphan-materials",fixable:!1,params:{n:O.length},nodeIds:O.map(N=>N.id),edgeIds:[]});const D=N=>{const R=new Set,B=[N];for(;B.length;)for(const H of l.get(B.shift())??[])R.has(H)||(R.add(H),B.push(H));return R.size},M=m.map(N=>({n:N,c:D(N.id)})).filter(({c:N})=>N>=5).sort((N,R)=>R.c-N.c).slice(0,3);for(const{n:N,c:R}of M)n.push({tier:2,kind:"load-bearing",fixable:!1,params:{a:Ai(N),n:R},nodeIds:[N.id],edgeIds:[]});return n.sort((N,R)=>N.tier-R.tier)}const Fte={"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 qte({onLocate:e,openPing:t=0,showTrigger:n=!0}){const a=oe(w=>w.deleteEdges),r=Gt(),[s,l]=j.useState(!1),[c,d]=j.useState([]),h=j.useRef(null),[m,p]=j.useState(t);j.useEffect(()=>{if(!s)return;const w=_=>{h.current?.contains(_.target)||l(!1)};return window.addEventListener("mousedown",w),()=>window.removeEventListener("mousedown",w)},[s]);const x=()=>{const{nodes:w,edges:_}=oe.getState();d(OE(w,_)),l(!0)};t!==m&&(p(t),x());const b=w=>{a(w.edgeIds);const{nodes:_,edges:A}=oe.getState();d(OE(_,A))},y=c.filter(w=>w.tier===1),E=c.filter(w=>w.tier===2),T=(w,_)=>u.jsxs("div",{className:"px-3 py-2 border-b border-line/50 last:border-0 flex items-start gap-2",children:[u.jsx("span",{className:`w-1.5 h-1.5 rounded-full mt-1.5 shrink-0 ${w.tier===1?"bg-red-400":"bg-amber-400"}`}),u.jsx("span",{className:"text-xs text-ink-muted leading-relaxed flex-1 min-w-0",children:qe(r(Fte[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(Qu,{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(Ua,{size:13,strokeWidth:1.75})})]})]},`${w.kind}-${_}`);return u.jsxs("div",{ref:h,className:"relative",children:[n&&u.jsx("button",{onClick:()=>s?l(!1):x(),className:`bg-card/90 backdrop-blur border rounded-lg w-8 h-8 flex items-center justify-center shadow-sm transition-colors ${s?"border-accent/40 text-accent":"border-line text-ink-faint hover:bg-wash"}`,title:r("toolbar.diagnose"),children:u.jsx(i7,{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?"":qe(r("diag.summary"),{a:y.length,b:E.length})})]}),c.length===0&&u.jsx("p",{className:"px-3 py-3 text-xs text-ink-faint italic",children:r("diag.clean")}),y.length>0&&u.jsxs(u.Fragment,{children:[u.jsx("p",{className:"px-3 pt-2 pb-1 text-2xs font-semibold text-red-500",children:r("diag.tier1")}),y.map(T)]}),E.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")}),E.map(T)]})]})]})}async function TN(e,t){const{default:n}=await Kt(async()=>{const{default:s}=await import("./purify.es-Cz4mVeUR.js");return{default:s}},[]),a=n.sanitize(e,{WHOLE_DOCUMENT:!0,ADD_TAGS:["style"],FORBID_TAGS:["script","iframe","object","embed","form","base","meta",...t?.baseUrl?[]:["link"]]}),r=new DOMParser().parseFromString(a,"text/html");return t?.baseUrl&&Vte(r,t.baseUrl),r}function Vte(e,t){const n=a=>{try{const r=new URL(a,t);return/^https?:$/.test(r.protocol)?r.href:null}catch{return null}};e.querySelectorAll("link").forEach(a=>{const r=a.getAttribute("href"),s=r?n(r):null;(a.getAttribute("rel")??"").toLowerCase()!=="stylesheet"||!s?a.remove():a.setAttribute("href",s)});for(const[a,r]of[["img","src"],["source","src"],["video","poster"],["a","href"]])e.querySelectorAll(`${a}[${r}]`).forEach(s=>{const l=s.getAttribute(r),c=l?n(l):null;c?s.setAttribute(r,c):s.removeAttribute(r)});e.querySelectorAll("img[srcset], source[srcset]").forEach(a=>a.removeAttribute("srcset"))}async function Wte(){const[{default:e},t]=await Promise.all([Kt(()=>import("./turndown.browser.es-kLzRgxYD.js"),[]),Kt(()=>import("./turndown-plugin-gfm.cjs-p3SpZgsj.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 RE(e){return(e.textContent??"").trim().length>0||!!e.querySelector("img,svg,canvas,video")}function O2(e){const t=Array.from(e.querySelectorAll(".reveal .slides > section"));if(t.length>=2){const s=[];for(const l of t){const c=Array.from(l.children).filter(d=>d.tagName==="SECTION");c.length>0?s.push(...c):s.push(l)}return s}const n=new Map;for(const s of Array.from(e.body?.querySelectorAll("[class]")??[])){const l=s.getAttribute("class")??"";if(!/(?:^|[\s_-])(?:slide|page)(?:[\s_-]|$)/i.test(l)||!RE(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(RE);return r.length>=3?r:null}async function Gte(e,t){const n=await TN(e,t),a=await Wte(),r=O2(n);if(r)return{markdown:r.map((d,h)=>`<!-- tdag-page:${h+1} -->
|
|
501
|
+
`)[0].replace(/^#+\s*/,"").slice(0,60)||"—";x.push({key:y.id,name:w,icon:E,at:y.data.createdAt,nodeId:y.id,nodeTitle:w,canOpen:!0});continue}const T=y.data.question.replace(/\s+/g," ").trim().slice(0,60)||(E==="file"?r("glyph.file"):"—");for(const w of y.data.attachments||[]){const _=w.type==="application/pdf"?"pdf":w.type.startsWith("image/")?"img":"txt";x.push({key:w.id,name:w.name,icon:_,sizeKB:w.size/1024,at:w.addedAt,nodeId:y.id,nodeTitle:T,canOpen:_==="pdf"})}}const b=s==="time"?[...x].sort((y,E)=>(E.at??"").localeCompare(y.at??"")):x;return b.map((y,E)=>({...y,showGroup:s==="node"&&(E===0||b[E-1].nodeTitle!==y.nodeTitle)}))},[a,s,r]);if(!t)return null;const d=()=>n(!1),h=x=>{d(),ye.getState().setReaderNodeId(x)},m="shrink-0 text-2xs font-mono text-accent bg-accent/10 hover:bg-accent/20 rounded-full px-1.5 py-0.5 transition-colors",p=(x,b)=>u.jsx("button",{onClick:()=>l(x),className:`text-2xs px-2.5 py-1 rounded-full transition-colors ${s===x?"bg-accent/10 text-accent":"text-ink-faint hover:bg-wash"}`,children:b});return $a.createPortal(u.jsx("div",{className:"fixed inset-0 z-[60] bg-ink/30 backdrop-blur-sm flex items-center justify-center p-6",onClick:d,children:u.jsxs("div",{className:"bg-card rounded-2xl shadow-2xl border border-line w-[640px] max-h-[80vh] flex flex-col",onClick:x=>x.stopPropagation(),children:[u.jsxs("div",{className:"flex items-center gap-2 px-5 py-3 border-b border-line shrink-0",children:[u.jsx(xi,{size:15,strokeWidth:1.75,className:"text-warm"}),u.jsx("span",{className:"text-sm font-semibold text-ink",children:r("matov.title")}),u.jsx("span",{className:"text-2xs text-ink-faint",children:qe(r("matov.count"),{n:c.length})}),u.jsx("div",{className:"flex-1"}),p("time",r("hlov.byTime")),p("node",r("hlov.byNode")),u.jsx("button",{onClick:d,className:"text-ink-faint hover:text-ink w-7 h-7 rounded-lg hover:bg-wash flex items-center justify-center transition-colors ml-1",children:u.jsx(bn,{size:15,strokeWidth:1.75})})]}),u.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-5 py-3",children:[c.length===0&&u.jsx("p",{className:"text-xs text-ink-faint italic py-2",children:r("matov.empty")}),c.map(x=>{const b=Rte[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(To,{size:14,strokeWidth:1.75})})]})]},x.key)})]})]})}),document.body)}function jte(e){const t=e.data.stepKind;return t==="note"||t==="file"||t==="link"||t==="frame"?t:e.data.condensedFrom?.length?"distill":"qa"}function Pte(e,t){let n=0,a=e.indexOf(t);for(;a!==-1;)n+=1,a=e.indexOf(t,a+t.length);return n}function zte(e,t,n){const r=Math.max(0,t-40),s=Math.min(e.length,t+n+60),l=r>0?"…":"",c=s<e.length?"…":"";return{snippet:l+e.slice(r,s)+c,matchStart:l.length+(t-r)}}function Bte(e,t){const n=t.trim().toLowerCase();if(!n)return[];const a=[];for(const r of e){const s=r.data;if(s.stepKind==="fanout")continue;const l=[s.question??"",s.response??"",...(s.highlights??[]).map(p=>p.text),s.linkTitle??"",...(s.attachments??[]).map(p=>p.name),s.summaries?.[s.responseIndex]??s.summary??""];let c=0,d=null;for(const p of l){if(!p)continue;const x=p.toLowerCase(),b=x.indexOf(n);b!==-1&&(c+=Pte(x,n),d||(d={text:p,at:b}))}if(!d)continue;const{snippet:h,matchStart:m}=zte(d.text,d.at,n.length);a.push({nodeId:r.id,kind:jte(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 Hte={qa:n7,note:Bi,file:gi,link:So,frame:vx,distill:om},Y1=50;function Ute({open:e,onClose:t,onLocate:n}){const a=Gt(),r=oe(w=>w.nodes),s=ye(w=>w.setSearchHitIds),[l,c]=j.useState(""),[d,h]=j.useState(0),m=j.useRef(null),[p,x]=j.useState(e);p!==e&&(x(e),e&&(c(""),h(0))),j.useEffect(()=>{e&&setTimeout(()=>m.current?.focus(),50)},[e]);const[b,y]=j.useState("");j.useEffect(()=>{const w=setTimeout(()=>y(l),120);return()=>clearTimeout(w)},[l]);const E=j.useMemo(()=>e?Bte(r,b):[],[e,r,b]);if(j.useEffect(()=>{if(!e||!b.trim()){s(null);return}s(new Set(E.map(w=>w.nodeId)))},[e,b,E,s]),j.useEffect(()=>()=>s(null),[s]),!e)return null;const T=w=>{n(w.nodeId);const _=b.trim().toLowerCase();setTimeout(()=>{const A=document.querySelector("[data-focus-panel]");if(!A||!_)return;const C=document.createTreeWalker(A,NodeFilter.SHOW_TEXT);let O;for(;O=C.nextNode();)if(O.textContent?.toLowerCase().includes(_)){const D=O.parentElement;D?.scrollIntoView({block:"center",behavior:"smooth"}),D?.animate([{backgroundColor:"rgba(107, 92, 231, 0.22)"},{backgroundColor:"transparent"}],{duration:1800,easing:"ease-out"});break}},500)};return u.jsx("div",{className:"absolute top-4 left-1/2 -translate-x-1/2 z-20 w-[460px]","data-canvas-search":!0,children:u.jsxs("div",{className:"bg-card border border-line rounded-xl shadow-xl overflow-hidden",children:[u.jsxs("div",{className:"flex items-center gap-2 px-4 py-2.5 transition-shadow focus-within:ring-1 focus-within:ring-accent/40",children:[u.jsx(Af,{size:15,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),u.jsx("input",{ref:m,type:"text",value:l,onChange:w=>{c(w.target.value),h(0)},onKeyDown:w=>{w.key==="Escape"&&(w.stopPropagation(),t()),w.key==="ArrowDown"&&(w.preventDefault(),h(_=>Math.min(_+1,E.length-1))),w.key==="ArrowUp"&&(w.preventDefault(),h(_=>Math.max(_-1,0))),w.key==="Enter"&&!Ya(w)&&E[d]&&(w.preventDefault(),T(E[d]))},placeholder:a("search.placeholder"),className:"flex-1 bg-transparent text-sm text-ink placeholder-ink-faint focus:outline-none","data-search-input":!0}),l&&u.jsx("span",{className:"text-2xs text-ink-faint shrink-0",children:qe(a("search.count"),{n:E.length})}),u.jsx("button",{onClick:t,className:"text-ink-faint hover:text-ink transition-colors shrink-0",children:u.jsx(bn,{size:14,strokeWidth:1.75})})]}),E.length>0&&u.jsxs("ul",{className:"border-t border-line/60 max-h-72 overflow-y-auto py-1",children:[E.slice(0,Y1).map((w,_)=>{const A=Hte[w.kind],O=r.find(D=>D.id===w.nodeId)?.data.question||"—";return u.jsx("li",{children:u.jsxs("button",{onClick:()=>T(w),onMouseEnter:()=>h(_),className:`w-full text-left px-4 py-2 transition-colors ${_===d?"bg-accent/8":""} ${w.archived?"opacity-55":""}`,"data-search-hit-row":!0,children:[u.jsxs("p",{className:`text-xs font-medium truncate flex items-center gap-1.5 ${_===d?"text-accent":"text-ink"}`,children:[u.jsx(A,{size:12,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),u.jsx("span",{className:"truncate flex-1 min-w-0",children:O}),w.archived&&u.jsx(Mo,{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)}),E.length>Y1&&u.jsx("li",{className:"px-4 py-2 text-2xs text-ink-faint",children:qe(a("search.more"),{n:E.length-Y1})})]})]})})}const DE=new Set(["note","file","link"]),Ai=e=>{const t=(e?.data.question??"").replace(/\s+/g," ").trim();return t.length>24?`${t.slice(0,24)}…`:t||"(空)"};function $1(e,t,n){const a=new Set([e]),r=[e];for(;r.length;){const s=r.shift();for(const l of n.get(s)??[]){if(l===t)return!0;a.has(l)||(a.add(l),r.push(l))}}return!1}function K1(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 OE(e,t){const n=[],a=new Map(e.map(N=>[N.id,N])),r=t.filter(N=>!N.data?.isCrossLink),s=t.filter(N=>N.data?.isCrossLink),l=K1(r),c=K1(t);for(const N of r){const R=K1(r.filter(B=>B.id!==N.id));$1(N.source,N.target,R)&&n.push({tier:1,kind:"residual-edge",fixable:!0,params:{a:Ai(a.get(N.source)),b:Ai(a.get(N.target))},nodeIds:[N.target,N.source],edgeIds:[N.id]})}for(const N of s)$1(N.source,N.target,l)&&n.push({tier:1,kind:"shadow-reference",fixable:!0,params:{a:Ai(a.get(N.source)),b:Ai(a.get(N.target))},nodeIds:[N.target,N.source],edgeIds:[N.id]});const d=new Map;for(const N of r)d.has(N.source)||d.set(N.source,[]),d.get(N.source).push(N.target);const h=[];for(const N of d.values()){const R=N.filter(H=>a.get(H)?.data.stepKind==="prompt"),B=N.filter(H=>a.get(H)?.data.isBranch);R.length>=2&&h.push(R),B.length>=2&&h.push(B)}for(const N of h)for(const R of N)for(const B of N)if(R!==B&&$1(R,B,c)){const H=t.find(Y=>Y.source===R&&Y.target===B);n.push({tier:1,kind:"blind-pool-breach",fixable:!!H,params:{a:Ai(a.get(B)),b:Ai(a.get(R))},nodeIds:[B,R],edgeIds:H?[H.id]:[]})}for(const N of h){const R=N.map(H=>new Set(t.filter(Y=>Y.target===H).map(Y=>Y.source))),B=new Set([...R[0]].filter(H=>R.every(Y=>Y.has(H))));N.forEach((H,Y)=>{const Z=[...R[Y]].filter(q=>!B.has(q)&&!N.includes(q));Z.length>0&&n.push({tier:1,kind:"pool-asymmetry",fixable:!1,params:{a:Ai(a.get(H)),n:Z.length},nodeIds:[H,...Z],edgeIds:[]})})}const m=e.filter(N=>!DE.has(N.data.stepKind??"")&&N.data.stepKind!=="frame"),p=new Map,x=new Map,b=N=>$n(N.data.question+N.data.response),y=new Map;for(const N of m)y.set(N.id,0);for(const N of r)y.has(N.target)&&y.has(N.source)&&y.set(N.target,(y.get(N.target)??0)+1);const E=m.filter(N=>(y.get(N.id)??0)===0).map(N=>N.id),T=[],w=new Map(y);for(;E.length;){const N=E.shift();T.push(N);for(const R of l.get(N)??[])w.has(R)&&(w.set(R,w.get(R)-1),w.get(R)===0&&E.push(R))}for(const N of T){const R=a.get(N),B=r.filter(Z=>Z.target===N&&p.has(Z.source)),H=B.length?Math.max(...B.map(Z=>p.get(Z.source)))+1:1,Y=B.length?Math.max(...B.map(Z=>x.get(Z.source)))+b(R):b(R);p.set(N,H),x.set(N,Y)}const _=m.filter(N=>!(l.get(N.id)??[]).length&&!N.data.archived),A=_.filter(N=>(p.get(N.id)??0)>=8||(x.get(N.id)??0)>=15e3).sort((N,R)=>(p.get(R.id)??0)-(p.get(N.id)??0)).slice(0,3);for(const N of A)n.push({tier:2,kind:"long-chain",fixable:!1,params:{a:Ai(N),d:p.get(N.id)??0,tok:x.get(N.id)??0},nodeIds:[N.id],edgeIds:[]});const C=_.filter(N=>N.data.response);C.length>=4&&n.push({tier:2,kind:"open-branches",fixable:!1,params:{n:C.length},nodeIds:C.map(N=>N.id),edgeIds:[]});for(const N of m){const R=r.filter(H=>H.target===N.id).length,B=(l.get(N.id)??[]).length;R>=2&&B>=1&&n.push({tier:2,kind:"collider-continuation",fixable:!1,params:{a:Ai(N),n:R},nodeIds:[N.id],edgeIds:[]})}const O=e.filter(N=>DE.has(N.data.stepKind??"")&&!t.some(R=>R.source===N.id));O.length>0&&n.push({tier:2,kind:"orphan-materials",fixable:!1,params:{n:O.length},nodeIds:O.map(N=>N.id),edgeIds:[]});const D=N=>{const R=new Set,B=[N];for(;B.length;)for(const H of l.get(B.shift())??[])R.has(H)||(R.add(H),B.push(H));return R.size},M=m.map(N=>({n:N,c:D(N.id)})).filter(({c:N})=>N>=5).sort((N,R)=>R.c-N.c).slice(0,3);for(const{n:N,c:R}of M)n.push({tier:2,kind:"load-bearing",fixable:!1,params:{a:Ai(N),n:R},nodeIds:[N.id],edgeIds:[]});return n.sort((N,R)=>N.tier-R.tier)}const Fte={"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 qte({onLocate:e,openPing:t=0,showTrigger:n=!0}){const a=oe(w=>w.deleteEdges),r=Gt(),[s,l]=j.useState(!1),[c,d]=j.useState([]),h=j.useRef(null),[m,p]=j.useState(t);j.useEffect(()=>{if(!s)return;const w=_=>{h.current?.contains(_.target)||l(!1)};return window.addEventListener("mousedown",w),()=>window.removeEventListener("mousedown",w)},[s]);const x=()=>{const{nodes:w,edges:_}=oe.getState();d(OE(w,_)),l(!0)};t!==m&&(p(t),x());const b=w=>{a(w.edgeIds);const{nodes:_,edges:A}=oe.getState();d(OE(_,A))},y=c.filter(w=>w.tier===1),E=c.filter(w=>w.tier===2),T=(w,_)=>u.jsxs("div",{className:"px-3 py-2 border-b border-line/50 last:border-0 flex items-start gap-2",children:[u.jsx("span",{className:`w-1.5 h-1.5 rounded-full mt-1.5 shrink-0 ${w.tier===1?"bg-red-400":"bg-amber-400"}`}),u.jsx("span",{className:"text-xs text-ink-muted leading-relaxed flex-1 min-w-0",children:qe(r(Fte[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(Qu,{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(Ua,{size:13,strokeWidth:1.75})})]})]},`${w.kind}-${_}`);return u.jsxs("div",{ref:h,className:"relative",children:[n&&u.jsx("button",{onClick:()=>s?l(!1):x(),className:`bg-card/90 backdrop-blur border rounded-lg w-8 h-8 flex items-center justify-center shadow-sm transition-colors ${s?"border-accent/40 text-accent":"border-line text-ink-faint hover:bg-wash"}`,title:r("toolbar.diagnose"),children:u.jsx(i7,{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?"":qe(r("diag.summary"),{a:y.length,b:E.length})})]}),c.length===0&&u.jsx("p",{className:"px-3 py-3 text-xs text-ink-faint italic",children:r("diag.clean")}),y.length>0&&u.jsxs(u.Fragment,{children:[u.jsx("p",{className:"px-3 pt-2 pb-1 text-2xs font-semibold text-red-500",children:r("diag.tier1")}),y.map(T)]}),E.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")}),E.map(T)]})]})]})}async function TN(e,t){const{default:n}=await Kt(async()=>{const{default:s}=await import("./purify.es-Cz4mVeUR.js");return{default:s}},[]),a=n.sanitize(e,{WHOLE_DOCUMENT:!0,ADD_TAGS:["style"],FORBID_TAGS:["script","iframe","object","embed","form","base","meta",...t?.baseUrl?[]:["link"]]}),r=new DOMParser().parseFromString(a,"text/html");return t?.baseUrl&&Vte(r,t.baseUrl),r}function Vte(e,t){const n=a=>{try{const r=new URL(a,t);return/^https?:$/.test(r.protocol)?r.href:null}catch{return null}};e.querySelectorAll("link").forEach(a=>{const r=a.getAttribute("href"),s=r?n(r):null;(a.getAttribute("rel")??"").toLowerCase()!=="stylesheet"||!s?a.remove():a.setAttribute("href",s)});for(const[a,r]of[["img","src"],["source","src"],["video","poster"],["a","href"]])e.querySelectorAll(`${a}[${r}]`).forEach(s=>{const l=s.getAttribute(r),c=l?n(l):null;c?s.setAttribute(r,c):s.removeAttribute(r)});e.querySelectorAll("img[srcset], source[srcset]").forEach(a=>a.removeAttribute("srcset"))}async function Wte(){const[{default:e},t]=await Promise.all([Kt(()=>import("./turndown.browser.es-kLzRgxYD.js"),[]),Kt(()=>import("./turndown-plugin-gfm.cjs-BkQZDlXD.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 RE(e){return(e.textContent??"").trim().length>0||!!e.querySelector("img,svg,canvas,video")}function O2(e){const t=Array.from(e.querySelectorAll(".reveal .slides > section"));if(t.length>=2){const s=[];for(const l of t){const c=Array.from(l.children).filter(d=>d.tagName==="SECTION");c.length>0?s.push(...c):s.push(l)}return s}const n=new Map;for(const s of Array.from(e.body?.querySelectorAll("[class]")??[])){const l=s.getAttribute("class")??"";if(!/(?:^|[\s_-])(?:slide|page)(?:[\s_-]|$)/i.test(l)||!RE(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(RE);return r.length>=3?r:null}async function Gte(e,t){const n=await TN(e,t),a=await Wte(),r=O2(n);if(r)return{markdown:r.map((d,h)=>`<!-- tdag-page:${h+1} -->
|
|
502
502
|
|
|
503
503
|
${a.turndown(d.cloneNode(!0).outerHTML).trim()}`).join(`
|
|
504
504
|
|
|
505
|
-
`).trim(),numPages:r.length,title:n.title||void 0};let s=n.title||void 0,l=null;try{const{default:c}=await Kt(async()=>{const{default:h}=await import("./index-
|
|
505
|
+
`).trim(),numPages:r.length,title:n.title||void 0};let s=n.title||void 0,l=null;try{const{default:c}=await Kt(async()=>{const{default:h}=await import("./index-CZgf0TxH.js").then(m=>m.i);return{default:h}},[]),d=new c(n.cloneNode(!0)).parse();d?.content&&d.content.replace(/<[^>]+>/g," ").trim().length>40&&(l=d.content,d.title&&(s=d.title))}catch{}if(l==null&&n.body){const c=n.body.cloneNode(!0);c.querySelectorAll("script,style,noscript,nav,header,footer,aside").forEach(d=>d.remove()),l=c.innerHTML}return{markdown:l?a.turndown(l).trim():"",title:s}}const Yte=[":root{color-scheme:light}","html,body{margin:0;padding:0;overflow-x:hidden}","[data-tdag-shell]{position:static !important;transform:none !important;width:auto !important;height:auto !important;min-height:0 !important;max-height:none !important;overflow:visible !important;display:block !important;margin:0 !important;padding:0 !important}","[data-tdag-slide]{display:block !important;visibility:visible !important;opacity:1 !important;position:relative !important;inset:auto !important;transform:none !important;margin:0 auto !important}"].join(`
|
|
506
506
|
`);function ab(e){return e.replace(/&/g,"&").replace(/"/g,""")}function $te(e,t){const n=e.tagName.toLowerCase(),a=["class","id","style"].map(r=>{const s=e.getAttribute(r);return s?` ${r}="${ab(s)}"`:""}).join("");return`<${n}${a} data-tdag-shell>${t}</${n}>`}function LE(e,t,n,a){const r=n?` class="${ab(n)}"`:"",s=a?` style="${ab(a)}"`:"";return`<!doctype html><html><head><meta charset="utf-8">${e}<style>${Yte}</style></head><body${r}${s}>${t}</body></html>`}async function SN(e,t){const n=await TN(e,t),a=Array.from(n.querySelectorAll('style, link[rel="stylesheet" i]')).map(c=>c.outerHTML).join(`
|
|
507
507
|
`),r=n.body?.getAttribute("class"),s=n.body?.getAttribute("style"),l=O2(n);return l?l.map((c,d)=>{const h=c.cloneNode(!0);h.setAttribute("data-tdag-slide","");let m=h.outerHTML;for(let p=c.parentElement;p&&p!==n.body&&p.tagName!=="HTML";p=p.parentElement)m=$te(p,m);return{page:d+1,srcdoc:LE(a,m,r,s)}}):[{page:null,srcdoc:LE(a,n.body?.innerHTML??"",r,s)}]}const AN=Object.freeze(Object.defineProperty({__proto__:null,buildReaderPages:SN,detectSlides:O2,extractHtmlMaterial:Gte},Symbol.toStringTag,{value:"Module"}));function jE({att:e,onSelect:t,clipMode:n,onClipped:a,baseUrl:r}){const s=Gt(),[l,c]=j.useState(null),[d,h]=j.useState(!1);return j.useEffect(()=>{let m=!1;return SN(e.content,r?{baseUrl:r}:void 0).then(p=>{m||c(p)}).catch(()=>{m||h(!0)}),()=>{m=!0}},[]),d?u.jsx("p",{className:"text-sm text-ink-faint italic py-10 text-center",children:s("reader.htmlNoText")}):l?u.jsx("div",{className:"flex flex-col items-center py-6 px-4",children:l.map(m=>u.jsxs("div",{"data-page":m.page??void 0,className:"w-full max-w-[860px]",children:[m.page!=null&&u.jsxs("div",{className:"text-2xs text-ink-faint font-mono text-center select-none pt-4 pb-2",children:["— p.",m.page," —"]}),u.jsx(Kte,{srcdoc:m.srcdoc,page:m.page,onSelect:t,clipMode:n,onClipped:a,clipFailedText:s("reader.clipFailed")})]},m.page??0))}):u.jsxs("div",{className:"flex items-center justify-center gap-2 h-full min-h-[200px] text-sm text-ink-muted",children:[u.jsx(Xn,{size:16,strokeWidth:1.75,className:"animate-spin text-accent"})," ",s("reader.loading")]})}function Kte({srcdoc:e,page:t,onSelect:n,clipMode:a,onClipped:r,clipFailedText:s}){const l=j.useRef(null),c=j.useRef(null),[d,h]=j.useState(120),[m,p]=j.useState(null),[x,b]=j.useState(!1),y=()=>{const w=c.current,_=w?.contentDocument;if(!w||!_?.body)return;const A=_.body.scrollWidth||_.documentElement.scrollWidth,C=w.clientWidth;A>C+2&&(_.body.style.zoom=String(C/A)),h(Math.max(40,_.documentElement.scrollHeight+2)),_.addEventListener("mouseup",()=>{const O=w.contentWindow?.getSelection();if(!O||O.isCollapsed){n(null);return}const D=O.toString().replace(/\s+/g," ").trim();if(D.length<2)return;const M=O.getRangeAt(0).getBoundingClientRect(),N=w.getBoundingClientRect();n({text:D,page:t,x:N.left+M.left+M.width/2,y:N.top+M.bottom})})},E=w=>{const _=l.current.getBoundingClientRect();return{x:Math.min(1,Math.max(0,(w.clientX-_.left)/_.width)),y:Math.min(1,Math.max(0,(w.clientY-_.top)/_.height))}},T=()=>{if(!m||x){p(null);return}const w=Math.min(m.x0,m.x1),_=Math.min(m.y0,m.y1),A=Math.abs(m.x1-m.x0),C=Math.abs(m.y1-m.y0);if(p(null),A<.02||C<.01)return;const O=c.current?.contentDocument;!O?.documentElement||!r||(b(!0),(async()=>{const{toCanvas:D}=await Kt(async()=>{const{toCanvas:K}=await import("./index-BeoRn2gJ.js");return{toCanvas:K}},[]),M=await D(O.documentElement,{pixelRatio:2}),N=Math.floor(w*M.width),R=Math.floor(_*M.height),B=Math.max(1,Math.floor(A*M.width)),H=Math.max(1,Math.floor(C*M.height)),Y=document.createElement("canvas");Y.width=B,Y.height=H,Y.getContext("2d").drawImage(M,N,R,B,H,0,0,B,H);const Z=l.current.getBoundingClientRect(),q={left:Z.left+w*Z.width,top:Z.top+_*Z.height,width:A*Z.width,height:C*Z.height};r(t??1,[w,_,A,C],Y.toDataURL("image/png"),q)})().catch(()=>Ke("error",s)).finally(()=>b(!1)))};return u.jsxs("div",{ref:l,className:"relative",children:[u.jsx("iframe",{ref:c,sandbox:"allow-same-origin",srcDoc:e,onLoad:y,style:{height:d},className:"w-full border-0 bg-white shadow-md rounded-sm","aria-label":t!=null?`p.${t}`:"document"}),a&&u.jsxs("div",{className:"absolute inset-0 cursor-crosshair",style:{zIndex:6},"data-clip-overlay":t??1,onMouseDown:w=>{w.preventDefault();const _=E(w);p({x0:_.x,y0:_.y,x1:_.x,y1:_.y})},onMouseMove:w=>{if(m){const _=E(w);p({...m,x1:_.x,y1:_.y})}},onMouseUp:T,onMouseLeave:()=>{m&&T()},children:[x&&u.jsx("div",{className:"absolute top-2 right-2 flex items-center gap-1.5 text-2xs text-warm bg-card/95 border border-line rounded-lg px-2 py-1 shadow-sm",children:u.jsx(Xn,{size:11,strokeWidth:1.75,className:"animate-spin"})}),m&&u.jsx("div",{className:"absolute border-2 border-warm bg-warm/10 rounded-sm pointer-events-none",style:{left:`${Math.min(m.x0,m.x1)*100}%`,top:`${Math.min(m.y0,m.y1)*100}%`,width:`${Math.abs(m.x1-m.x0)*100}%`,height:`${Math.abs(m.y1-m.y0)*100}%`}})]})]})}let X1=null;function Xte(){return X1||(X1=Promise.all([Kt(()=>import("./pdf-gh-BrLFn.js"),[]),Kt(()=>import("./pdf.worker.min-C_APr3k7.js"),[])]).then(([e,t])=>(e.GlobalWorkerOptions.workerSrc=t.default,e))),X1}function Qte(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 Zte=/<!--\s*tdag-page:(\d+)\s*-->/;function Jte(e){const t=e.split(Zte),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 Q1=60,PE=new Map;function ene({onLocate:e}){const t=ye(a=>a.readerNodeId),n=oe(a=>t?a.nodes.find(r=>r.id===t):void 0);return j.useEffect(()=>{t&&!n&&ye.getState().setReaderNodeId(null)},[t,n]),n?u.jsx(tne,{node:n,onLocate:e},n.id):null}function tne({node:e,onLocate:t}){const n=Gt(),a=e.data,r=a.stepKind==="file"||!a.stepKind&&(a.attachments??[]).some(pe=>pe.type==="application/pdf")?"file":a.stepKind==="link"?"link":"note",s=j.useMemo(()=>a.attachments??[],[a.attachments]),l=s.find(pe=>pe.type==="application/pdf"),c=s.find(pe=>pe.type==="text/html"),d=r==="link"?a.linkSnapshotHtml:void 0,h=j.useMemo(()=>d?{id:`link-snapshot-${e.id}`,name:a.linkTitle||a.linkUrl||"snapshot",type:"text/html",size:d.length,content:d}:null,[d,e.id,a.linkTitle,a.linkUrl]),m=j.useMemo(()=>s.filter(pe=>pe.type.startsWith("image/")),[s]),p=()=>ye.getState().setReaderNodeId(null),x=j.useMemo(()=>{if(l)return l.extractedText??"";if(r==="file"){const pe=s.filter(At=>!At.type.startsWith("image/")&&At.type!=="application/pdf"),Qe=pe.map(At=>{const Nt=At.type==="text/html"?At.extractedText??"":At.content;return pe.length>1?`### ${At.name}
|
|
508
508
|
|
|
@@ -517,7 +517,7 @@ ${At.extractedText}`:At.extractedText);return Qe.join(`
|
|
|
517
517
|
`))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(`
|
|
518
518
|
`)[0].slice(0,80)}catch{}return null}function sne(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(`
|
|
519
519
|
`).trim();if(a&&!a.startsWith("<"))return a.split(`
|
|
520
|
-
`)[0].slice(0,80)}return null}const NN="thoughtdag.atlas.disabledRoots",R2=()=>{try{return new Set(JSON.parse(localStorage.getItem(NN)??"[]"))}catch{return new Set}};function one(e,t){const n=R2();t?n.add(e):n.delete(e),localStorage.setItem(NN,JSON.stringify([...n]))}const Gf=new Set;async function lne(){const e=window.desktopSessions;if(!e)return[];const t=R2(),n=(await e.roots().catch(()=>[])).filter(r=>r.exists&&!t.has(r.key)).map(r=>r.key),a=[];for(const r of n){const l=[...await e.list(r).catch(()=>[])].sort((d,h)=>h.mtime-d.mtime),c=12;for(let d=0;d<l.length;d+=c){const h=await Promise.all(l.slice(d,d+c).map(async m=>{const p=m.rel.endsWith(".zstd")?zE:ine,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,zE).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)}}Gf.clear();for(const r of a)Gf.add(r.sessionId);return a.sort((r,s)=>s.mtime-r.mtime)}function cne(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 CN="thoughtdag.atlas.watermark",bo=e=>`${e.rootKey}:${e.rel}`;function L2(){try{return JSON.parse(localStorage.getItem(CN)??"{}")}catch{return{}}}function Yf(e){localStorage.setItem(CN,JSON.stringify(e))}function une(e){const t=L2(),n=new Map;if(Object.keys(t).length===0)return Yf(Object.fromEntries(e.map(s=>[bo(s),{mtime:s.mtime,size:s.size}]))),n;const a=new Set(e.map(bo));let r=!1;for(const s of Object.keys(t))a.has(s)||(delete t[s],r=!0);for(const s of e){const l=t[bo(s)];l?(s.size>l.size||s.mtime>l.mtime+1e3)&&n.set(bo(s),{kind:"updated",deltaSize:Math.max(0,s.size-l.size)}):n.set(bo(s),{kind:"new",deltaSize:s.size})}return r&&Yf(t),n}function dne(e){const t=L2();t[bo(e)]={mtime:e.mtime,size:e.size},Yf(t)}function hne(e){const t=L2();for(const n of e)t[bo(n)]={mtime:n.mtime,size:n.size};Yf(t)}const cc=bo,J1=e=>new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),HE=e=>e>1e6?`${(e/1e6).toFixed(1)} MB`:`${Math.max(1,Math.round(e/1024))} KB`,fne={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 mne({roots:e,counts:t,onChanged:n,onClose:a}){const r=Gt(),s=R2(),l={"claude-projects":"Claude Code","codex-sessions":"Codex","dsh-sessions":"DeepSeek Harness"},[c,d]=j.useState(null),h=()=>{window.desktopSessions?.commandsStatus?.().then(d).catch(()=>{})};j.useEffect(h,[]);const m={"claude-code":"Claude Code",codex:"Codex",dsh:"DeepSeek Harness"},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=>{one(x.key,!b.target.checked),n()},className:"shrink-0"}),u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsx("div",{className:"text-sm text-ink",children:l[x.key]??x.path.split("/").filter(Boolean).pop()}),u.jsx("div",{className:"text-2xs text-ink-faint truncate",children:x.path})]}),u.jsx("span",{className:"text-2xs text-ink-faint shrink-0",children:x.exists?t.get(x.key)??0:r("atlas.rootMissing")}),!x.builtin&&u.jsx("button",{className:"text-ink-faint hover:text-red-500 p-1 rounded transition-colors shrink-0",onClick:()=>{window.desktopSessions.removeRoot(x.key).then(n)},children:u.jsx(Ua,{size:14,strokeWidth:1.75})})]},x.key);return u.jsx("div",{className:"absolute inset-0 z-10 bg-ink/20 flex items-center justify-center",onClick:a,children:u.jsxs("div",{className:"bg-surface border border-line rounded-2xl shadow-xl w-[440px] max-h-[80%] overflow-y-auto",onClick:x=>x.stopPropagation(),"data-atlas-sources-dialog":!0,children:[u.jsxs("div",{className:"px-4 pt-3.5 pb-2.5 border-b border-line",children:[u.jsx("div",{className:"text-sm font-semibold text-ink",children:r("atlas.sourcesTitle")}),u.jsx("div",{className:"text-2xs text-ink-muted mt-0.5",children:r("atlas.sourcesHint")})]}),e.filter(x=>x.builtin).map(p),c&&Object.values(c).some(x=>x.state!=="unavailable")&&u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"px-4 pt-3 pb-1.5 text-2xs uppercase tracking-wide text-ink-faint",children:r("atlas.handoffTitle")}),Object.entries(c).filter(([,x])=>x.state!=="unavailable").map(([x,b])=>u.jsxs("div",{className:"flex items-center gap-3 px-4 py-2.5 border-b border-line","data-atlas-handoff":x,"data-handoff-state":b.state,children:[u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsxs("div",{className:"text-sm text-ink flex items-center gap-2",children:[m[x]??x,u.jsx("code",{className:"text-2xs bg-wash border border-line rounded px-1.5 py-px font-mono",children:b.invoke})]}),u.jsx("div",{className:"text-2xs text-ink-faint truncate",children:r(b.state==="installed"?"atlas.handoffOn":b.state==="outdated"?"atlas.handoffOutdated":"atlas.handoffOff")})]}),b.state!=="installed"&&u.jsx("button",{className:"text-2xs bg-accent/10 text-accent hover:bg-accent/20 font-medium px-2.5 py-1 rounded-lg transition-colors shrink-0","data-handoff-install":!0,onClick:()=>{(async()=>{const{confirmDialog:y}=await Kt(async()=>{const{confirmDialog:w}=await Promise.resolve().then(()=>um);return{confirmDialog:w}},void 0);if(!await y({title:Ie("atlas.handoffEnableTitle"),message:qe(Ie("confirm.installCommand"),{path:b.dest}),confirmLabel:Ie(b.state==="outdated"?"atlas.handoffUpdate":"atlas.handoffEnable")}))return;const T=await window.desktopSessions.commandsInstall(x);T.ok?Ke("success",qe(Ie("atlas.handoffInstalled"),{cmd:b.invoke}),8e3):Ke("error",T.error??"install failed"),h()})()},children:r(b.state==="outdated"?"atlas.handoffUpdate":"atlas.handoffEnable")}),(b.state==="installed"||b.state==="outdated")&&u.jsx("button",{className:"text-ink-faint hover:text-red-500 p-1 rounded transition-colors shrink-0",title:r("atlas.handoffRemove"),"data-handoff-remove":!0,onClick:()=>{window.desktopSessions.commandsRemove(x).then(h)},children:u.jsx(Ua,{size:14,strokeWidth:1.75})})]},x))]}),["Pi"].map(x=>u.jsxs("div",{className:"flex items-center gap-3 px-4 py-2.5 border-b border-line opacity-50",children:[u.jsx("input",{type:"checkbox",disabled:!0,className:"shrink-0"}),u.jsx("div",{className:"flex-1 text-sm text-ink",children:x}),u.jsx("span",{className:"text-2xs text-ink-faint",children:r("atlas.parserSoon")})]},x)),e.filter(x=>!x.builtin).map(p),u.jsxs("div",{className:"flex items-center gap-2 px-4 py-3",children:[u.jsxs("button",{onClick:n,className:"flex items-center gap-1.5 text-sm text-ink-muted hover:text-ink border border-line rounded-lg px-2.5 py-1.5 hover:bg-wash transition-colors",children:[u.jsx(ir,{size:13,strokeWidth:1.75})," ",r("atlas.autoDetect")]}),u.jsxs("button",{onClick:()=>{window.desktopSessions.addRoot().then(x=>{x&&n()})},className:"flex items-center gap-1.5 text-sm text-accent border border-line rounded-lg px-2.5 py-1.5 hover:bg-wash transition-colors","data-atlas-add-dir":!0,children:[u.jsx(a7,{size:13,strokeWidth:1.75})," ",r("atlas.addDir")]})]})]})})}function _N({onClose:e,onSwitched:t,focusSessionId:n}){const a=Gt(),r=Nn(se=>se.projects),s=Nn(se=>se.projects.find(He=>He.id===se.activeId)?.sourceSession?.sessionId),l=!!window.desktopSessions,[c,d]=j.useState(null),[h,m]=j.useState([]),[p,x]=j.useState(!1),[b,y]=j.useState(window.desktopSessions?null:"canvases"),[E,T]=j.useState(null),[w,_]=j.useState(!1),[A,C]=j.useState(null),[O,D]=j.useState(new Map),[M,N]=j.useState(new Map),[R,B]=j.useState(new Map),[H,Y]=j.useState(!1),Z=se=>`${se.rootKey}|${se.rel}`,q=se=>B(He=>{const ge=new Map(He),Ve=Z(se);return ge.has(Ve)?ge.delete(Ve):ge.set(Ve,se),ge}),K=se=>r.find(He=>_x(He).includes(se)),[U,G]=j.useState(""),[ne,X]=j.useState(new Set),[P,F]=j.useState("time"),[J,W]=j.useState(!1),[ae,ve]=j.useState(!1),[me,ke]=j.useState(new Map),[re,be]=j.useState(null);j.useEffect(()=>{window.desktopSessions?.openTargets().then(be).catch(()=>{})},[]);const Le=j.useMemo(()=>new Map((re?.apps??[]).map(se=>[se.runner,se.name])),[re]),Oe=async()=>{x(!0);try{m(await window.desktopSessions?.roots().catch(()=>[])??[]);const se=await lne();if(d(se),ke(une(se)),window.desktopSessions?.codexThreads?.().then(He=>{He&&(D(new Map(He.filter(ge=>ge.name&&ge.sessionId).map(ge=>[ge.sessionId,ge.name]))),N(new Map(He.filter(ge=>ge.forkedFromId&&ge.sessionId).map(ge=>[ge.sessionId,ge.forkedFromId]))))}).catch(()=>{}),n){const He=se.find(ge=>ge.sessionId===n);He&&y(He.cwd??"")}}finally{x(!1)}};j.useEffect(()=>{Oe()},[]),j.useEffect(()=>{let se=!1;const He=()=>{se||p||(se=!0,setTimeout(()=>{se=!1,Oe()},2e3))};return window.addEventListener("td:sessions-changed",He),()=>window.removeEventListener("td:sessions-changed",He)},[p]);const je=se=>O.get(se.sessionId)??se.title,ze=j.useMemo(()=>(c??[]).filter(se=>!ne.has(se.runner)&&(ae||!se.subagent)&&(!J||me.has(cc(se)))&&(!U.trim()||je(se).toLowerCase().includes(U.trim().toLowerCase()))),[c,ne,U,J,me,ae,O]),rt=j.useMemo(()=>cne(ze),[ze]),ot=j.useMemo(()=>[...new Set((c??[]).map(se=>se.runner))].sort(),[c]),Xe=j.useMemo(()=>{const se=new Map;for(const He of c??[])se.set(He.rootKey,(se.get(He.rootKey)??0)+1);return se},[c]),kt=b==="canvases"?null:rt.find(se=>(se.cwd??"")===(b??rt[0]?.cwd??""))??rt[0]??null,ht=j.useMemo(()=>{if(!kt)return[];const se=P==="name"?(He,ge)=>je(He).localeCompare(je(ge)):fne[P];return[...kt.cards].sort(se)},[kt,P,O]),at=se=>{dne(se),ke(He=>{const ge=new Map(He);return ge.delete(cc(se)),ge})},wt=async se=>{if(!E){T(se.rel),at(se);try{const{streamRunnerConversation:He}=await Kt(async()=>{const{streamRunnerConversation:St}=await import("./index-D-BTv0n0.js");return{streamRunnerConversation:St}},[]),{importOrAppendConversation:ge,shellSessionReader:Ve}=await Kt(async()=>{const{importOrAppendConversation:St,shellSessionReader:Ft}=await import("./canonical-DbPqsMYz.js");return{importOrAppendConversation:St,shellSessionReader:Ft}},[]),dt=await He(Ve(se.rootKey,se.rel)),xt=await ge(dt);if(!xt)throw new Error(Ie("handoff.notASession"));xt.kind==="appended"?Ke("success",qe(Ie("atlas.appended"),{n:xt.turns}),9e3):xt.kind==="mounted"?Ke("success",qe(Ie(xt.mode==="continue"?"atlas.mountedChapter":"atlas.mountedBranch"),{n:xt.turns}),9e3):xt.kind==="opened"?Ke("info",Ie("atlas.upToDate"),6e3):Ke("success",qe(Ie("toast.importedChats"),{n:1,m:xt.nodeCount}),9e3),e(),t()}catch(He){Ke("error",qe(Ie("atlas.parseFailed"),{msg:He instanceof Error?He.message:String(He)}))}finally{T(null)}}},zt=async se=>{if(!(E||R.size<2)){T("__merge__");try{const{streamRunnerConversation:He}=await Kt(async()=>{const{streamRunnerConversation:St}=await import("./index-D-BTv0n0.js");return{streamRunnerConversation:St}},[]),{mergeSessionsIntoProject:ge,shellSessionReader:Ve}=await Kt(async()=>{const{mergeSessionsIntoProject:St,shellSessionReader:Ft}=await import("./canonical-DbPqsMYz.js");return{mergeSessionsIntoProject:St,shellSessionReader:Ft}},[]),dt=[];for(const St of R.values())dt.push(await He(Ve(St.rootKey,St.rel))),at(St);const xt=await ge(dt,se);if(!xt)throw new Error(Ie("handoff.notASession"));Ke("success",qe(Ie("atlas.merged"),{n:xt.mounted}),1e4),xt.skipped>0&&Ke("info",qe(Ie("atlas.mergeSkippedInfo"),{n:xt.skipped}),8e3),B(new Map),e(),t()}catch(He){Ke("error",qe(Ie("atlas.parseFailed"),{msg:He instanceof Error?He.message:String(He)}))}finally{T(null)}}},We=async se=>{const He=Nn.getState().projects.find(dt=>dt.sourceSession?.sessionId===se.sessionId);if(!He||E)return;const{confirmDialog:ge}=await Kt(async()=>{const{confirmDialog:dt}=await Promise.resolve().then(()=>um);return{confirmDialog:dt}},void 0);if(await ge({title:Ie("confirm.recastTitle"),message:qe(Ie("confirm.recast"),{name:He.name}),confirmLabel:Ie("confirm.recastTitle"),danger:!0})){T(se.rel);try{const{streamRunnerConversation:dt}=await Kt(async()=>{const{streamRunnerConversation:$t}=await import("./index-D-BTv0n0.js");return{streamRunnerConversation:$t}},[]),{importOrAppendConversation:xt,shellSessionReader:St}=await Kt(async()=>{const{importOrAppendConversation:$t,shellSessionReader:vn}=await import("./canonical-DbPqsMYz.js");return{importOrAppendConversation:$t,shellSessionReader:vn}},[]),Ft=await dt(St(se.rootKey,se.rel));if(!Ft)throw new Error(Ie("handoff.notASession"));const{deleteProject:un}=await Kt(async()=>{const{deleteProject:$t}=await Promise.resolve().then(()=>mm);return{deleteProject:$t}},void 0);if(await un(He.id),!await xt(Ft))throw new Error(Ie("handoff.notASession"));Ke("success",Ie("atlas.recastDone"),8e3),e(),t()}catch(dt){Ke("error",qe(Ie("atlas.parseFailed"),{msg:dt instanceof Error?dt.message:String(dt)}))}finally{T(null)}}},Bt=async(se,He)=>{const ge=await window.desktopSessions.openInCli(se.runner,se.cwd,se.sessionId,He).catch(()=>({opened:!1,via:"",command:""}));ge.opened&&ge.via==="app"?(await navigator.clipboard.writeText(se.sessionId).catch(()=>{}),Ke("success",Ie("atlas.appOpened"),9e3)):ge.opened?Ke("success",Ie("atlas.opened")):ge.command&&(await navigator.clipboard.writeText(ge.command).catch(()=>{}),Ke("info",Ie("atlas.cmdCopied"),9e3))};return $a.createPortal(u.jsx("div",{className:"fixed inset-0 z-50 bg-ink/30 backdrop-blur-sm flex items-center justify-center p-6","data-session-atlas":!0,children:u.jsxs("div",{className:"bg-surface border border-line rounded-2xl shadow-2xl w-full max-w-[980px] h-[min(680px,90vh)] flex flex-col overflow-hidden",children:[u.jsxs("div",{className:"flex items-start gap-3 px-5 pt-4 pb-3 border-b border-line",children:[u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsx("div",{className:"text-base font-semibold text-ink",children:a("atlas.title")}),u.jsx("div",{className:"text-xs text-ink-muted mt-0.5",children:a("atlas.subtitle")}),me.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:qe(a("atlas.changesSummary"),{n:[...me.values()].filter(se=>se.kind==="new").length,m:[...me.values()].filter(se=>se.kind==="updated").length})}),u.jsx("button",{className:"text-ink-faint hover:text-ink underline decoration-dotted transition-colors",onClick:()=>{hne(c??[]),ke(new Map)},"data-atlas-mark-all":!0,children:a("atlas.markAllSeen")})]})]}),l&&re&&re.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(Ad,{size:14,strokeWidth:1.75}),u.jsxs("select",{value:re.prefs.terminal,onChange:se=>{const He=se.target.value;if(He==="__add__"){window.desktopSessions?.addTerminal().then(()=>window.desktopSessions?.openTargets().then(be));return}window.desktopSessions?.setOpenPrefs({terminal:He}).then(ge=>be(Ve=>Ve&&{...Ve,prefs:ge}))},className:"bg-transparent focus:outline-none text-sm text-ink cursor-pointer","data-atlas-terminal-select":!0,children:[re.terminals.map(se=>u.jsx("option",{value:se.id,children:se.name},se.id)),re.canAddCustom&&u.jsx("option",{value:"__add__",children:a("atlas.otherTerminal")})]})]}),l&&u.jsxs("button",{onClick:()=>_(!0),className:"flex items-center gap-1.5 text-sm text-ink-muted hover:text-ink border border-line rounded-lg px-2.5 py-1.5 hover:bg-wash transition-colors","data-atlas-sources":!0,children:[u.jsx(a7,{size:14,strokeWidth:1.75})," ",a("atlas.sources")]}),l&&u.jsxs("button",{onClick:()=>{Oe()},disabled:p,className:"flex items-center gap-1.5 text-sm text-ink-muted hover:text-ink border border-line rounded-lg px-2.5 py-1.5 hover:bg-wash transition-colors disabled:opacity-60","data-atlas-refresh":!0,children:[p?u.jsx(Xn,{size:14,className:"animate-spin"}):u.jsx(ir,{size:14,strokeWidth:1.75}),a(p?"atlas.scanning":"atlas.refresh")]}),u.jsx("button",{onClick:e,className:"text-ink-faint hover:text-ink p-1.5 rounded-lg hover:bg-wash transition-colors","data-atlas-close":!0,children:u.jsx(bn,{size:18,strokeWidth:1.75})})]}),u.jsxs("div",{className:"flex-1 flex min-h-0",children:[u.jsxs("div",{className:"w-[260px] border-r border-line overflow-y-auto py-2 shrink-0",children:[u.jsx("div",{className:"px-4 py-1 text-2xs uppercase tracking-wide text-ink-faint",children:a("atlas.recent")}),r.filter(se=>!se.archived).sort((se,He)=>He.updatedAt-se.updatedAt).slice(0,6).map(se=>u.jsxs("button",{onClick:()=>{e(),ks(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(P5,{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")}),!l&&u.jsx("div",{className:"px-4 py-2 text-xs text-ink-faint",children:a("atlas.webNoScan")}),l&&c===null&&u.jsxs("div",{className:"px-4 py-2 text-sm text-ink-faint flex items-center gap-2",children:[u.jsx(Xn,{size:14,className:"animate-spin"})," ",a("atlas.scanning")]}),l&&c!==null&&rt.length===0&&u.jsx("div",{className:"px-4 py-2 text-xs text-ink-faint",children:a("atlas.empty")}),rt.map(se=>{const He=se.cwd??"",ge=b!=="canvases"&&kt===se;return u.jsxs("button",{onClick:()=>y(He),className:`w-full text-left px-4 py-2 flex items-center gap-2 transition-colors ${ge?"bg-accent/5 text-accent":"text-ink hover:bg-wash"}`,"data-atlas-folder":se.name||"unfiled",children:[ge?u.jsx(K8,{size:15,strokeWidth:1.75,className:"shrink-0"}):u.jsx(wP,{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 Ve=se.cards.filter(dt=>me.has(cc(dt))).length;return Ve>0?u.jsxs("span",{className:"text-2xs text-accent shrink-0","data-atlas-folder-changes":!0,children:["+",Ve]}):null})(),u.jsx("span",{className:"text-2xs text-ink-faint shrink-0",children:se.cards.length})]},He)}),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(P5,{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,He)=>He.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(),ks(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:J1(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:He=>{He.stopPropagation(),Mf(se.id,!0)},"data-atlas-archive":!0,children:u.jsx(Mo,{size:15,strokeWidth:1.75})}),!!se.sourceSession&&_x(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)," · ",qe(a("atlas.turnsN"),{n:se.sourceSession.importedCount})]}),(se.sourceSession.chapters??[]).map(He=>u.jsxs("span",{children:["↳ ",He.runner," ",He.sessionId.slice(0,8)," · ",qe(a("atlas.turnsN"),{n:He.importedCount})]},He.sessionId)),(se.sourceSession.branches??[]).map(He=>u.jsxs("span",{children:["⑂ ",He.runner," ",He.sessionId.slice(0,8)," · ",qe(a("atlas.turnsN"),{n:He.importedCount})]},He.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:qe(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,He)=>He.updatedAt-se.updatedAt).map(se=>u.jsxs("button",{title:a("atlas.restoreOpen"),onClick:()=>{Mf(se.id,!1).then(()=>{e(),ks(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:J1(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(Af,{size:13,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),u.jsx("input",{value:U,onChange:se=>G(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})]}),ot.map(se=>u.jsx("button",{onClick:()=>X(He=>{const ge=new Set(He);return ge.has(se)?ge.delete(se):ge.add(se),ge}),className:`text-2xs font-mono border rounded-lg px-2 py-1 transition-colors ${ne.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)),me.size>0&&u.jsx("button",{onClick:()=>W(se=>!se),className:`text-2xs border rounded-lg px-2 py-1 transition-colors ${J?"border-accent text-white bg-accent":"border-line text-ink-muted hover:text-ink"}`,"data-atlas-only-changed":!0,children:a("atlas.onlyChanged")}),(c??[]).some(se=>se.subagent)&&u.jsx("button",{onClick:()=>ve(se=>!se),className:`text-2xs border rounded-lg px-2 py-1 transition-colors ${ae?"border-accent text-accent bg-accent/5":"border-line text-ink-faint hover:text-ink"}`,"data-atlas-show-sub":!0,children:a("atlas.showSub")}),u.jsxs("button",{onClick:()=>F(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(yj,{size:12,strokeWidth:1.75}),a(`atlas.sort${P[0].toUpperCase()}${P.slice(1)}`)]})]}),kt?u.jsxs(u.Fragment,{children:[kt.cwd&&u.jsxs("div",{className:"text-2xs text-ink-faint mb-3 truncate",children:[kt.cwd," · ",qe(a("atlas.sessions"),{n:kt.cards.length})]}),u.jsx("div",{className:"space-y-1.5",children:ht.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:()=>{wt(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:je(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:"⑂"}),me.get(cc(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")}),me.get(cc(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:["+",HE(me.get(cc(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 He=K(se.sessionId);return He?u.jsx("span",{className:"text-2xs text-ink-faint border border-line rounded px-1 py-px shrink-0",title:He.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:J1(se.mtime)}),u.jsx("span",{children:HE(se.size)})]})]}),E===se.rel?u.jsx(Xn,{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:[!K(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:He=>{He.stopPropagation(),q(se)},"data-atlas-pick":R.has(Z(se))?"on":"off",children:R.has(Z(se))?u.jsx(Tz,{size:16,strokeWidth:1.75}):u.jsx(Ab,{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(RP,{size:16,strokeWidth:1.75})}),r.some(He=>He.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:He=>{He.stopPropagation(),We(se)},"data-atlas-recast":!0,children:u.jsx(hz,{size:16,strokeWidth:1.75})}),!K(se.sessionId)&&u.jsx("button",{title:a("atlas.mountTo"),className:"text-ink-faint hover:text-accent p-1.5 rounded transition-colors",onClick:He=>{He.stopPropagation(),C(se)},"data-atlas-mount":!0,children:u.jsx(So,{size:16,strokeWidth:1.75})}),Le.has(se.runner)&&u.jsx("button",{title:qe(a("atlas.openApp"),{name:Le.get(se.runner)}),className:"text-ink-faint hover:text-accent p-1.5 rounded transition-colors",onClick:He=>{He.stopPropagation(),Bt(se,"app")},"data-atlas-open-app":!0,children:u.jsx(pj,{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:He=>{He.stopPropagation(),Bt(se,"terminal")},"data-atlas-open-cli":!0,children:u.jsx(Ad,{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&&!H&&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:qe(a("atlas.mergeSelected"),{n:R.size})}),E==="__merge__"?u.jsx(Xn,{size:15,className:"animate-spin text-accent"}):u.jsxs(u.Fragment,{children:[u.jsx("button",{className:"text-xs bg-accent hover:bg-accent-strong text-white font-medium px-3 py-1.5 rounded-lg transition-colors whitespace-nowrap",onClick:()=>{zt()},"data-atlas-merge-new":!0,children:a("atlas.mergeNew")}),u.jsx("button",{className:"text-xs text-ink-muted hover:text-ink hover:bg-wash font-medium px-3 py-1.5 rounded-lg transition-colors whitespace-nowrap",onClick:()=>Y(!0),"data-atlas-merge-into":!0,children:a("atlas.mergeInto")})]}),u.jsx("button",{className:"text-ink-faint hover:text-ink p-1",onClick:()=>B(new Map),title:a("common.cancel"),children:u.jsx(bn,{size:14,strokeWidth:1.75})})]}),(A||H)&&u.jsx("div",{className:"absolute inset-0 z-10 bg-ink/20 flex items-center justify-center",onClick:()=>{C(null),Y(!1)},children:u.jsxs("div",{className:"bg-surface border border-line rounded-2xl shadow-xl w-[400px] max-h-[70%] overflow-y-auto",onClick: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(H?"atlas.mergeInto":"atlas.mountTo")}),u.jsx("div",{className:"text-2xs text-ink-muted mt-0.5",children:a(H?"atlas.mergeSelected":"atlas.mountHint").replace("{n}",String(R.size))})]}),r.filter(se=>!se.archived&&se.kind!=="paradigm").sort((se,He)=>He.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(H){Y(!1),zt(se.id);return}const He=A;C(null),(async()=>{T(He.rel);try{const{streamRunnerConversation:ge}=await Kt(async()=>{const{streamRunnerConversation:Ft}=await import("./index-D-BTv0n0.js");return{streamRunnerConversation:Ft}},[]),{mountConversationToProject:Ve,shellSessionReader:dt}=await Kt(async()=>{const{mountConversationToProject:Ft,shellSessionReader:un}=await import("./canonical-DbPqsMYz.js");return{mountConversationToProject:Ft,shellSessionReader:un}},[]),xt=await ge(dt(He.rootKey,He.rel)),St=await Ve(xt,se.id);if(!St)throw new Error(Ie("handoff.notASession"));Ke("success",qe(Ie("atlas.mountedChapter"),{n:St.kind==="mounted"||St.kind==="appended"?St.turns:0}),9e3),e(),t()}catch(ge){Ke("error",qe(Ie("atlas.parseFailed"),{msg:ge instanceof Error?ge.message:String(ge)}))}finally{T(null)}})()},children:se.name},se.id))]})}),w&&u.jsx(mne,{roots:h,counts:Xe,onChanged:()=>{Oe()},onClose:()=>_(!1)})]})}),document.body)}function pne({conversations:e,onClose:t,onDone:n}){const a=Gt(),[r,s]=j.useState(new Set),[l,c]=j.useState(!1),d=p=>{s(x=>{const b=new Set(x);return b.has(p)?b.delete(p):b.add(p),b})},h=r.size===e.length,m=async()=>{r.size===0||l||(c(!0),await KH([...r].sort((p,x)=>p-x).map(p=>e[p])),c(!1),n())};return u.jsx("div",{className:"fixed inset-0 z-50 bg-ink/30 backdrop-blur-sm flex items-center justify-center p-6",onClick:t,children:u.jsxs("div",{className:"bg-card border border-line rounded-2xl shadow-2xl w-full max-w-lg max-h-[80vh] flex flex-col",onClick:p=>p.stopPropagation(),children:[u.jsxs("div",{className:"px-6 py-4 border-b border-line flex items-start justify-between gap-4",children:[u.jsxs("div",{children:[u.jsx("h2",{className:"text-base font-semibold text-ink",children:a("import.title")}),u.jsx("p",{className:"text-xs text-ink-muted mt-1 leading-relaxed",children:a("import.subtitle")})]}),u.jsx("button",{onClick:t,className:"text-ink-faint hover:text-ink transition-colors shrink-0 mt-0.5",children:u.jsx(bn,{size:16,strokeWidth:1.75})})]}),u.jsx("div",{className:"px-6 py-2 border-b border-line/60",children:u.jsxs("label",{className:"flex items-center gap-2 text-xs text-ink-muted cursor-pointer select-none py-1",children:[u.jsx("input",{type:"checkbox",checked:h,onChange:()=>s(h?new Set:new Set(e.map((p,x)=>x))),className:"rounded border-line text-accent focus:ring-accent w-3.5 h-3.5"}),a("import.selectAll"),u.jsx("span",{className:"ml-auto text-2xs text-ink-faint uppercase tracking-wider",children:e[0]?.source})]})}),u.jsx("ul",{className:"flex-1 overflow-y-auto py-1",children:e.map((p,x)=>u.jsx("li",{children:u.jsxs("label",{className:"flex items-center gap-3 px-6 py-2 hover:bg-wash transition-colors cursor-pointer select-none",children:[u.jsx("input",{type:"checkbox",checked:r.has(x),onChange:()=>d(x),className:"rounded border-line text-accent focus:ring-accent w-3.5 h-3.5 shrink-0"}),u.jsx(n7,{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:qe(a("import.messages"),{n:p.messageCount})})]})},x))}),u.jsxs("div",{className:"px-6 py-4 border-t border-line flex justify-end gap-2",children:[u.jsx("button",{onClick:t,className:"text-xs text-ink-muted hover:text-ink px-4 py-2 rounded-lg hover:bg-wash transition-colors",children:a("common.cancel")}),u.jsx("button",{onClick:()=>{m()},disabled:r.size===0||l,className:"text-xs bg-accent hover:bg-accent-strong text-white px-5 py-2 rounded-lg transition-colors disabled:opacity-30",children:l?"…":qe(a("import.confirm"),{n:r.size})})]})]})})}function gne(e){const t=Date.now()-e,n=Math.floor(t/6e4);if(n<1)return Ie("switcher.justNow");if(n<60)return qe(Ie("switcher.minAgo"),{n});const a=Math.floor(n/60);if(a<24)return qe(Ie("switcher.hourAgo"),{n:a});const r=Math.floor(a/24);return r<30?qe(Ie("switcher.dayAgo"),{n:r}):new Date(e).toLocaleDateString(Fa.getState().lang==="zh"?"zh-CN":"en-US")}function xne({onSwitched:e}){const t=Gt(),n=Nn(N=>N.projects),a=Nn(N=>N.activeId),r=Nn(N=>N.switching),s=n.find(N=>N.id===a)?.kind==="paradigm",[l,c]=j.useState(!1),[d,h]=j.useState(null),[m,p]=j.useState(!1),[x,b]=j.useState(void 0),[y,E]=j.useState(null),[T,w]=j.useState(""),_=j.useRef(null),A=j.useRef(null),C=n.find(N=>N.id===a),O=n.filter(N=>!N.archived).sort((N,R)=>R.updatedAt-N.updatedAt).slice(0,7),D=async N=>{const{canvasUniqueness:R}=await Kt(async()=>{const{canvasUniqueness:Z}=await import("./canonical-DbPqsMYz.js");return{canvasUniqueness:Z}},[]),B=await R(N.id),H=B==="native"?"confirm.deleteNative":B==="diverged-mirror"?"confirm.deleteDiverged":"confirm.deletePristine";await Es({title:Ie("confirm.deleteCanvasTitle"),message:qe(Ie(H),{name:N.name}),confirmLabel:Ie("common.delete"),danger:B!=="pristine-mirror"})&&q7(N.id).then(e)};j.useEffect(()=>{if(!l)return;const N=R=>{A.current?.contains(R.target)||c(!1)};return window.addEventListener("mousedown",N),()=>window.removeEventListener("mousedown",N)},[l]);const M=async N=>{c(!1),await ks(N),e(),Kt(()=>import("./canonical-DbPqsMYz.js"),[]).then(R=>R.unsubscribeOrphanedSessions()),Kt(()=>import("./live-mirror-BElcCk_a.js"),[]).then(R=>R.sweepRecentSessions())};return u.jsxs("div",{ref:A,className:"absolute top-4 left-4 z-20",children:[u.jsxs("div",{className:"flex items-center gap-1.5",children:[u.jsxs("button",{onClick:()=>c(!l),disabled:r,className:"bg-card/90 backdrop-blur border border-line rounded-xl px-3.5 py-2 shadow-sm hover:bg-wash transition-colors flex items-center gap-2 text-sm text-ink max-w-[240px] disabled:opacity-60",children:[r?u.jsx(Xn,{size:16,strokeWidth:1.75,className:"animate-spin shrink-0 text-accent"}):s?u.jsx(aP,{size:16,strokeWidth:1.75,className:"shrink-0 text-accent"}):u.jsx(K8,{size:16,strokeWidth:1.75,className:"shrink-0 text-ink-muted"}),u.jsx("span",{className:"truncate font-medium",children:C?.name??"…"}),u.jsx(Yd,{size:14,strokeWidth:1.75,className:"shrink-0 text-ink-faint"})]}),!!C?.sourceSession?.sessionId&&(()=>{const N=Gf.size>0&&!Gf.has(C.sourceSession.sessionId);return u.jsxs("button",{title:N?Ie("switcher.mirrorBadgeGone"):qe(Ie("switcher.mirrorBadge"),{runner:C.sourceSession.runner}),onClick:()=>{b(C.sourceSession.sessionId),p(!0)},className:`bg-card/90 backdrop-blur border border-line rounded-xl px-2 py-2 shadow-sm hover:bg-wash transition-colors text-2xs font-mono flex items-center gap-1 ${N?"text-ink-faint/50 line-through decoration-1":"text-ink-faint hover:text-accent"}`,"data-twin-badge":N?"unreachable":"live",children:["⇄ ",C.sourceSession.runner]})})()]}),l&&u.jsxs("div",{className:"mt-1.5 bg-card border border-line rounded-xl shadow-lg py-1.5 w-[320px] animate-fade-in",children:[u.jsx("div",{className:"max-h-[320px] overflow-y-auto",children:O.map(N=>u.jsx("div",{className:`group flex items-center gap-1 px-3 py-2 hover:bg-wash cursor-pointer transition-colors ${N.id===a?"bg-accent/5":""}`,onClick:()=>{y!==N.id&&N.id!==a&&M(N.id)},children:y===N.id?u.jsx("input",{autoFocus:!0,value:T,onChange:R=>w(R.target.value),onClick:R=>R.stopPropagation(),onKeyDown:R=>{R.key==="Enter"&&!Ya(R)&&T.trim()&&(F7(N.id,T.trim()),E(null)),R.key==="Escape"&&E(null)},onBlur:()=>E(null),className:"flex-1 text-sm text-ink border border-accent/40 rounded-lg px-2 py-1 bg-surface focus:outline-none"}):u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsx("div",{className:`text-sm truncate ${N.id===a?"text-accent font-medium":"text-ink"}`,children:N.name}),u.jsxs("div",{className:"text-2xs text-ink-faint flex items-center gap-1.5",children:[u.jsx("span",{children:gne(N.updatedAt)}),!!N.sourceSession?.sessionId&&u.jsx("span",{className:"font-mono border border-line rounded px-1 py-px","data-mirror-mark":!0,children:N.sourceSession.runner})]})]}),u.jsx("button",{title:t("switcher.rename"),className:"opacity-0 group-hover:opacity-100 text-ink-faint hover:text-ink p-1 rounded transition-all shrink-0",onClick:R=>{R.stopPropagation(),E(N.id),w(N.name)},children:u.jsx(Oc,{size:14,strokeWidth:1.75})}),u.jsx("button",{title:t("common.delete"),className:"opacity-0 group-hover:opacity-100 text-ink-faint hover:text-red-500 p-1 rounded transition-all shrink-0",onClick:R=>{R.stopPropagation(),D(N)},children:u.jsx(Ua,{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(),Mf(N.id,!0).then(e)},"data-archive-canvas":!0,children:u.jsx(Mo,{size:14,strokeWidth:1.75})})]})},N.id))}),u.jsxs("div",{className:"border-t border-line mt-1 pt-1",children:[u.jsxs("button",{onClick:()=>{c(!1),fm().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(lm,{size:15,strokeWidth:1.75})," ",t("switcher.newCanvas")]}),u.jsxs("button",{onClick:()=>_.current?.click(),className:"w-full text-left px-3 py-2 text-sm text-ink-muted hover:bg-wash transition-colors flex items-center gap-2",children:[u.jsx(jz,{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(YP,{size:15,strokeWidth:1.75})," ",t("switcher.allCanvases")]}),window.desktop&&u.jsxs("button",{onClick:()=>{c(!1),window.desktop.checkForUpdates()},className:"w-full text-left px-3 py-2 text-sm text-ink-muted hover:bg-wash transition-colors flex items-center gap-2","data-check-updates":!0,children:[u.jsx(ir,{size:15,strokeWidth:1.75})," ",t("update.checkMenu"),u.jsxs("span",{className:"ml-auto text-2xs text-ink-faint",children:["v",new URLSearchParams(window.location.search).get("dv")]})]}),u.jsx("input",{ref:_,type:"file",accept:".json,.jsonl,application/json",className:"hidden",onChange:N=>{const R=N.target.files?.[0];R&&YH(R).then(B=>{B.kind==="own"&&B.ok?(c(!1),e()):B.kind==="chat"&&(c(!1),h(B.conversations))}).catch(B=>{Ke("error",qe(Ie("toast.importFailedGeneric"),{msg:B instanceof Error?B.message:String(B)}))}),N.target.value=""}})]})]}),d&&u.jsx(pne,{conversations:d,onClose:()=>h(null),onDone:()=>{h(null),e()}}),m&&u.jsx(_N,{onClose:()=>{p(!1),b(void 0)},onSwitched:e,focusSessionId:x})]})}const bne="JVBERi0xLjQKMSAwIG9iago8PCAvVHlwZSAvQ2F0YWxvZyAvUGFnZXMgMiAwIFIgPj4KZW5kb2JqCjIgMCBvYmoKPDwgL1R5cGUgL1BhZ2VzIC9LaWRzIFszIDAgUiA0IDAgUl0gL0NvdW50IDIgPj4KZW5kb2JqCjMgMCBvYmoKPDwgL1R5cGUgL1BhZ2UgL1BhcmVudCAyIDAgUiAvTWVkaWFCb3ggWzAgMCA1OTUgODQyXSAvQ29udGVudHMgNSAwIFIgL1Jlc291cmNlcyA8PCAvRm9udCA8PCAvRjEgNyAwIFIgL0YyIDggMCBSID4+ID4+ID4+CmVuZG9iago0IDAgb2JqCjw8IC9UeXBlIC9QYWdlIC9QYXJlbnQgMiAwIFIgL01lZGlhQm94IFswIDAgNTk1IDg0Ml0gL0NvbnRlbnRzIDYgMCBSIC9SZXNvdXJjZXMgPDwgL0ZvbnQgPDwgL0YxIDcgMCBSIC9GMiA4IDAgUiA+PiA+PiA+PgplbmRvYmoKNSAwIG9iago8PCAvTGVuZ3RoIDExMTIgPj4Kc3RyZWFtCkJUCi9GMiAxOSBUZiAxIDAgMCAxIDY0IDcyNS4wIFRtIChXaHkgU2F2ZWQgQXJ0aWNsZXMgU3RheSBVbnJlYWQpIFRqCi9GMSAxMSBUZiAxIDAgMCAxIDY0IDcwOC4wIFRtIChBIHNob3J0IGJyaWVmIG9uIGRpZ2l0YWwgaG9hcmRpbmcgYW5kIHRoZSBjb2xsZWN0b3IncyBmYWxsYWN5KSBUagovRjIgMTMgVGYgMSAwIDAgMSA2NCA2NjkuMCBUbSAoMS4gVGhlIHBoZW5vbWVub24pIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNjUxLjUgVG0gKFJlYWQtaXQtbGF0ZXIgc2VydmljZXMgcmVwb3J0IHRoYXQgbW9zdCBzYXZlZCBpdGVtcyBhcmUgbmV2ZXIpIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNjM0LjAgVG0gKHJlb3BlbmVkLiBBY3Jvc3MgcHVibGlzaGVkIHVzYWdlIHN0dWRpZXMsIHRoZSBzaGFyZSBvZiBzYXZlZCkgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA2MTYuNSBUbSAoYXJ0aWNsZXMgdGhhdCBnZXQgYSBzZWNvbmQgdmlzaXQgaXMgc21hbGwsIGFuZCBjb21wbGV0aW9uIHJhdGVzKSBUagovRjEgMTEuNSBUZiAxIDAgMCAxIDY0IDU5OS4wIFRtIChhcmUgc21hbGxlciBzdGlsbC4gVGhlIGFyY2hpdmUgZ3Jvd3M7IHRoZSByZWFkaW5nIGRvZXMgbm90LikgVGoKL0YyIDEzIFRmIDEgMCAwIDEgNjQgNTYwLjAgVG0gKDIuIFRoZSBjb2xsZWN0b3IncyBmYWxsYWN5KSBUagovRjEgMTEuNSBUZiAxIDAgMCAxIDY0IDU0Mi41IFRtIChDb2xsZWN0aW5nIHByb2R1Y2VzIGFuIGltbWVkaWF0ZSBzZW5zZSBvZiBwcm9ncmVzcyB3aGlsZSB0aGUpIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNTI1LjAgVG0gKHVuZGVyc3RhbmRpbmcgaXQgcHJvbWlzZXMgaXMgZGVmZXJyZWQuIFNhdmluZyBhIHRleHQgZmVlbHMgbGlrZSkgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA1MDcuNSBUbSAoYSBmaXJzdCBzdGVwIG9mIHJlYWRpbmcgaXQsIGJ1dCBubyBwYXJ0IG9mIHRoZSByZWFkaW5nIGhhcykgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA0OTAuMCBUbSAoaGFwcGVuZWQuKSBUagovRjIgMTEuNSBUZiAxIDAgMCAxIDY0IDQ3Mi41IFRtIChUaGUgYWN0IG9mIHNhdmluZyBpcyBtaXN0YWtlbiBmb3IgdGhlIGFjdCBvZiBsZWFybmluZy4pIFRqCkVUCmVuZHN0cmVhbQplbmRvYmoKNiAwIG9iago8PCAvTGVuZ3RoIDkwOCA+PgpzdHJlYW0KQlQKL0YyIDEzIFRmIDEgMCAwIDEgNjQgNzI1LjAgVG0gKDMuIFdoeSBpdCBwZXJzaXN0cykgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA3MDcuNSBUbSAoVGhlIGNvc3RzIGFyZSBhc3ltbWV0cmljOiBzYXZpbmcgdGFrZXMgb25lIHNlY29uZCBhbmQgcGF5cyBvdXQpIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNjkwLjAgVG0gKGEgc21hbGwgcmV3YXJkIG5vdzsgcmVhZGluZyB0YWtlcyBhbiBob3VyIGFuZCBwYXlzIG91dCBsYXRlci4pIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNjcyLjUgVG0gKEhhYml0cyBmb2xsb3cgdGhlIGNoZWFwZXIgbG9vcCwgc28gbGlicmFyaWVzIGluZmxhdGUgYnkgZGVmYXVsdC4pIFRqCi9GMiAxMyBUZiAxIDAgMCAxIDY0IDYzMy41IFRtICg0LiBXaGF0IGhlbHBzKSBUagovRjEgMTEuNSBUZiAxIDAgMCAxIDY0IDYxNi4wIFRtIChJbnRlcnZlbnRpb25zIHRoYXQgd29yayBtb3ZlIHByb2Nlc3NpbmcgdG8gdGhlIG1vbWVudCBvZiBjYXB0dXJlOikgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA1OTguNSBUbSAod3JpdGUgb25lIGxpbmUgaW4geW91ciBvd24gd29yZHMgYWJvdXQgd2h5IHRoZSBpdGVtIG1hdHRlcnMsIGFuZCkgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA1ODEuMCBUbSAoc2NoZWR1bGUgYSByZXZpZXcgcGFzcyBpbnN0ZWFkIG9mIHRydXN0aW5nIHRoZSBhcmNoaXZlIHRvKSBUagovRjEgMTEuNSBUZiAxIDAgMCAxIDY0IDU2My41IFRtIChyZXN1cmZhY2UgaXQuKSBUagovRjEgMTEuNSBUZiAxIDAgMCAxIDY0IDUzMi4wIFRtIChBIHNtYWxsZXIgbGlicmFyeSB0aGF0IGdldHMgcHJvY2Vzc2VkIGJlYXRzIGEgY29tcGxldGUgb25lIHRoYXQpIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNTE0LjUgVG0gKGRvZXMgbm90LikgVGoKRVQKZW5kc3RyZWFtCmVuZG9iago3IDAgb2JqCjw8IC9UeXBlIC9Gb250IC9TdWJ0eXBlIC9UeXBlMSAvQmFzZUZvbnQgL0hlbHZldGljYSA+PgplbmRvYmoKOCAwIG9iago8PCAvVHlwZSAvRm9udCAvU3VidHlwZSAvVHlwZTEgL0Jhc2VGb250IC9IZWx2ZXRpY2EtQm9sZCA+PgplbmRvYmoKeHJlZgowIDkKMDAwMDAwMDAwMCA2NTUzNSBmIAowMDAwMDAwMDA5IDAwMDAwIG4gCjAwMDAwMDAwNTggMDAwMDAgbiAKMDAwMDAwMDEyMSAwMDAwMCBuIAowMDAwMDAwMjU3IDAwMDAwIG4gCjAwMDAwMDAzOTMgMDAwMDAgbiAKMDAwMDAwMTU1NyAwMDAwMCBuIAowMDAwMDAyNTE2IDAwMDAwIG4gCjAwMDAwMDI1ODYgMDAwMDAgbiAKdHJhaWxlcgo8PCAvU2l6ZSA5IC9Sb290IDEgMCBSID4+CnN0YXJ0eHJlZgoyNjYxCiUlRU9G",yne=`<!-- tdag-page:1 -->
|
|
520
|
+
`)[0].slice(0,80)}return null}const NN="thoughtdag.atlas.disabledRoots",R2=()=>{try{return new Set(JSON.parse(localStorage.getItem(NN)??"[]"))}catch{return new Set}};function one(e,t){const n=R2();t?n.add(e):n.delete(e),localStorage.setItem(NN,JSON.stringify([...n]))}const Gf=new Set;async function lne(){const e=window.desktopSessions;if(!e)return[];const t=R2(),n=(await e.roots().catch(()=>[])).filter(r=>r.exists&&!t.has(r.key)).map(r=>r.key),a=[];for(const r of n){const l=[...await e.list(r).catch(()=>[])].sort((d,h)=>h.mtime-d.mtime),c=12;for(let d=0;d<l.length;d+=c){const h=await Promise.all(l.slice(d,d+c).map(async m=>{const p=m.rel.endsWith(".zstd")?zE:ine,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,zE).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)}}Gf.clear();for(const r of a)Gf.add(r.sessionId);return a.sort((r,s)=>s.mtime-r.mtime)}function cne(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 CN="thoughtdag.atlas.watermark",bo=e=>`${e.rootKey}:${e.rel}`;function L2(){try{return JSON.parse(localStorage.getItem(CN)??"{}")}catch{return{}}}function Yf(e){localStorage.setItem(CN,JSON.stringify(e))}function une(e){const t=L2(),n=new Map;if(Object.keys(t).length===0)return Yf(Object.fromEntries(e.map(s=>[bo(s),{mtime:s.mtime,size:s.size}]))),n;const a=new Set(e.map(bo));let r=!1;for(const s of Object.keys(t))a.has(s)||(delete t[s],r=!0);for(const s of e){const l=t[bo(s)];l?(s.size>l.size||s.mtime>l.mtime+1e3)&&n.set(bo(s),{kind:"updated",deltaSize:Math.max(0,s.size-l.size)}):n.set(bo(s),{kind:"new",deltaSize:s.size})}return r&&Yf(t),n}function dne(e){const t=L2();t[bo(e)]={mtime:e.mtime,size:e.size},Yf(t)}function hne(e){const t=L2();for(const n of e)t[bo(n)]={mtime:n.mtime,size:n.size};Yf(t)}const cc=bo,J1=e=>new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),HE=e=>e>1e6?`${(e/1e6).toFixed(1)} MB`:`${Math.max(1,Math.round(e/1024))} KB`,fne={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 mne({roots:e,counts:t,onChanged:n,onClose:a}){const r=Gt(),s=R2(),l={"claude-projects":"Claude Code","codex-sessions":"Codex","dsh-sessions":"DeepSeek Harness"},[c,d]=j.useState(null),h=()=>{window.desktopSessions?.commandsStatus?.().then(d).catch(()=>{})};j.useEffect(h,[]);const m={"claude-code":"Claude Code",codex:"Codex",dsh:"DeepSeek Harness"},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=>{one(x.key,!b.target.checked),n()},className:"shrink-0"}),u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsx("div",{className:"text-sm text-ink",children:l[x.key]??x.path.split("/").filter(Boolean).pop()}),u.jsx("div",{className:"text-2xs text-ink-faint truncate",children:x.path})]}),u.jsx("span",{className:"text-2xs text-ink-faint shrink-0",children:x.exists?t.get(x.key)??0:r("atlas.rootMissing")}),!x.builtin&&u.jsx("button",{className:"text-ink-faint hover:text-red-500 p-1 rounded transition-colors shrink-0",onClick:()=>{window.desktopSessions.removeRoot(x.key).then(n)},children:u.jsx(Ua,{size:14,strokeWidth:1.75})})]},x.key);return u.jsx("div",{className:"absolute inset-0 z-10 bg-ink/20 flex items-center justify-center",onClick:a,children:u.jsxs("div",{className:"bg-surface border border-line rounded-2xl shadow-xl w-[440px] max-h-[80%] overflow-y-auto",onClick:x=>x.stopPropagation(),"data-atlas-sources-dialog":!0,children:[u.jsxs("div",{className:"px-4 pt-3.5 pb-2.5 border-b border-line",children:[u.jsx("div",{className:"text-sm font-semibold text-ink",children:r("atlas.sourcesTitle")}),u.jsx("div",{className:"text-2xs text-ink-muted mt-0.5",children:r("atlas.sourcesHint")})]}),e.filter(x=>x.builtin).map(p),c&&Object.values(c).some(x=>x.state!=="unavailable")&&u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"px-4 pt-3 pb-1.5 text-2xs uppercase tracking-wide text-ink-faint",children:r("atlas.handoffTitle")}),Object.entries(c).filter(([,x])=>x.state!=="unavailable").map(([x,b])=>u.jsxs("div",{className:"flex items-center gap-3 px-4 py-2.5 border-b border-line","data-atlas-handoff":x,"data-handoff-state":b.state,children:[u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsxs("div",{className:"text-sm text-ink flex items-center gap-2",children:[m[x]??x,u.jsx("code",{className:"text-2xs bg-wash border border-line rounded px-1.5 py-px font-mono",children:b.invoke})]}),u.jsx("div",{className:"text-2xs text-ink-faint truncate",children:r(b.state==="installed"?"atlas.handoffOn":b.state==="outdated"?"atlas.handoffOutdated":"atlas.handoffOff")})]}),b.state!=="installed"&&u.jsx("button",{className:"text-2xs bg-accent/10 text-accent hover:bg-accent/20 font-medium px-2.5 py-1 rounded-lg transition-colors shrink-0","data-handoff-install":!0,onClick:()=>{(async()=>{const{confirmDialog:y}=await Kt(async()=>{const{confirmDialog:w}=await Promise.resolve().then(()=>um);return{confirmDialog:w}},void 0);if(!await y({title:Ie("atlas.handoffEnableTitle"),message:qe(Ie("confirm.installCommand"),{path:b.dest}),confirmLabel:Ie(b.state==="outdated"?"atlas.handoffUpdate":"atlas.handoffEnable")}))return;const T=await window.desktopSessions.commandsInstall(x);T.ok?Ke("success",qe(Ie("atlas.handoffInstalled"),{cmd:b.invoke}),8e3):Ke("error",T.error??"install failed"),h()})()},children:r(b.state==="outdated"?"atlas.handoffUpdate":"atlas.handoffEnable")}),(b.state==="installed"||b.state==="outdated")&&u.jsx("button",{className:"text-ink-faint hover:text-red-500 p-1 rounded transition-colors shrink-0",title:r("atlas.handoffRemove"),"data-handoff-remove":!0,onClick:()=>{window.desktopSessions.commandsRemove(x).then(h)},children:u.jsx(Ua,{size:14,strokeWidth:1.75})})]},x))]}),["Pi"].map(x=>u.jsxs("div",{className:"flex items-center gap-3 px-4 py-2.5 border-b border-line opacity-50",children:[u.jsx("input",{type:"checkbox",disabled:!0,className:"shrink-0"}),u.jsx("div",{className:"flex-1 text-sm text-ink",children:x}),u.jsx("span",{className:"text-2xs text-ink-faint",children:r("atlas.parserSoon")})]},x)),e.filter(x=>!x.builtin).map(p),u.jsxs("div",{className:"flex items-center gap-2 px-4 py-3",children:[u.jsxs("button",{onClick:n,className:"flex items-center gap-1.5 text-sm text-ink-muted hover:text-ink border border-line rounded-lg px-2.5 py-1.5 hover:bg-wash transition-colors",children:[u.jsx(ir,{size:13,strokeWidth:1.75})," ",r("atlas.autoDetect")]}),u.jsxs("button",{onClick:()=>{window.desktopSessions.addRoot().then(x=>{x&&n()})},className:"flex items-center gap-1.5 text-sm text-accent border border-line rounded-lg px-2.5 py-1.5 hover:bg-wash transition-colors","data-atlas-add-dir":!0,children:[u.jsx(a7,{size:13,strokeWidth:1.75})," ",r("atlas.addDir")]})]})]})})}function _N({onClose:e,onSwitched:t,focusSessionId:n}){const a=Gt(),r=Nn(se=>se.projects),s=Nn(se=>se.projects.find(He=>He.id===se.activeId)?.sourceSession?.sessionId),l=!!window.desktopSessions,[c,d]=j.useState(null),[h,m]=j.useState([]),[p,x]=j.useState(!1),[b,y]=j.useState(window.desktopSessions?null:"canvases"),[E,T]=j.useState(null),[w,_]=j.useState(!1),[A,C]=j.useState(null),[O,D]=j.useState(new Map),[M,N]=j.useState(new Map),[R,B]=j.useState(new Map),[H,Y]=j.useState(!1),Z=se=>`${se.rootKey}|${se.rel}`,q=se=>B(He=>{const ge=new Map(He),Ve=Z(se);return ge.has(Ve)?ge.delete(Ve):ge.set(Ve,se),ge}),K=se=>r.find(He=>_x(He).includes(se)),[U,G]=j.useState(""),[ne,X]=j.useState(new Set),[P,F]=j.useState("time"),[J,W]=j.useState(!1),[ae,ve]=j.useState(!1),[me,ke]=j.useState(new Map),[re,be]=j.useState(null);j.useEffect(()=>{window.desktopSessions?.openTargets().then(be).catch(()=>{})},[]);const Le=j.useMemo(()=>new Map((re?.apps??[]).map(se=>[se.runner,se.name])),[re]),Oe=async()=>{x(!0);try{m(await window.desktopSessions?.roots().catch(()=>[])??[]);const se=await lne();if(d(se),ke(une(se)),window.desktopSessions?.codexThreads?.().then(He=>{He&&(D(new Map(He.filter(ge=>ge.name&&ge.sessionId).map(ge=>[ge.sessionId,ge.name]))),N(new Map(He.filter(ge=>ge.forkedFromId&&ge.sessionId).map(ge=>[ge.sessionId,ge.forkedFromId]))))}).catch(()=>{}),n){const He=se.find(ge=>ge.sessionId===n);He&&y(He.cwd??"")}}finally{x(!1)}};j.useEffect(()=>{Oe()},[]),j.useEffect(()=>{let se=!1;const He=()=>{se||p||(se=!0,setTimeout(()=>{se=!1,Oe()},2e3))};return window.addEventListener("td:sessions-changed",He),()=>window.removeEventListener("td:sessions-changed",He)},[p]);const je=j.useCallback(se=>O.get(se.sessionId)??se.title,[O]),ze=j.useMemo(()=>(c??[]).filter(se=>!ne.has(se.runner)&&(ae||!se.subagent)&&(!J||me.has(cc(se)))&&(!U.trim()||je(se).toLowerCase().includes(U.trim().toLowerCase()))),[c,ne,U,J,me,ae,je]),rt=j.useMemo(()=>cne(ze),[ze]),ot=j.useMemo(()=>[...new Set((c??[]).map(se=>se.runner))].sort(),[c]),Xe=j.useMemo(()=>{const se=new Map;for(const He of c??[])se.set(He.rootKey,(se.get(He.rootKey)??0)+1);return se},[c]),kt=b==="canvases"?null:rt.find(se=>(se.cwd??"")===(b??rt[0]?.cwd??""))??rt[0]??null,ht=j.useMemo(()=>{if(!kt)return[];const se=P==="name"?(He,ge)=>je(He).localeCompare(je(ge)):fne[P];return[...kt.cards].sort(se)},[kt,P,je]),at=se=>{dne(se),ke(He=>{const ge=new Map(He);return ge.delete(cc(se)),ge})},wt=async se=>{if(!E){T(se.rel),at(se);try{const{streamRunnerConversation:He}=await Kt(async()=>{const{streamRunnerConversation:St}=await import("./index-DbmziCje.js");return{streamRunnerConversation:St}},[]),{importOrAppendConversation:ge,shellSessionReader:Ve}=await Kt(async()=>{const{importOrAppendConversation:St,shellSessionReader:Ft}=await import("./canonical-DDfsxGbh.js");return{importOrAppendConversation:St,shellSessionReader:Ft}},[]),dt=await He(Ve(se.rootKey,se.rel)),xt=await ge(dt);if(!xt)throw new Error(Ie("handoff.notASession"));xt.kind==="appended"?Ke("success",qe(Ie("atlas.appended"),{n:xt.turns}),9e3):xt.kind==="mounted"?Ke("success",qe(Ie(xt.mode==="continue"?"atlas.mountedChapter":"atlas.mountedBranch"),{n:xt.turns}),9e3):xt.kind==="opened"?Ke("info",Ie("atlas.upToDate"),6e3):Ke("success",qe(Ie("toast.importedChats"),{n:1,m:xt.nodeCount}),9e3),e(),t()}catch(He){Ke("error",qe(Ie("atlas.parseFailed"),{msg:He instanceof Error?He.message:String(He)}))}finally{T(null)}}},zt=async se=>{if(!(E||R.size<2)){T("__merge__");try{const{streamRunnerConversation:He}=await Kt(async()=>{const{streamRunnerConversation:St}=await import("./index-DbmziCje.js");return{streamRunnerConversation:St}},[]),{mergeSessionsIntoProject:ge,shellSessionReader:Ve}=await Kt(async()=>{const{mergeSessionsIntoProject:St,shellSessionReader:Ft}=await import("./canonical-DDfsxGbh.js");return{mergeSessionsIntoProject:St,shellSessionReader:Ft}},[]),dt=[];for(const St of R.values())dt.push(await He(Ve(St.rootKey,St.rel))),at(St);const xt=await ge(dt,se);if(!xt)throw new Error(Ie("handoff.notASession"));Ke("success",qe(Ie("atlas.merged"),{n:xt.mounted}),1e4),xt.skipped>0&&Ke("info",qe(Ie("atlas.mergeSkippedInfo"),{n:xt.skipped}),8e3),B(new Map),e(),t()}catch(He){Ke("error",qe(Ie("atlas.parseFailed"),{msg:He instanceof Error?He.message:String(He)}))}finally{T(null)}}},We=async se=>{const He=Nn.getState().projects.find(dt=>dt.sourceSession?.sessionId===se.sessionId);if(!He||E)return;const{confirmDialog:ge}=await Kt(async()=>{const{confirmDialog:dt}=await Promise.resolve().then(()=>um);return{confirmDialog:dt}},void 0);if(await ge({title:Ie("confirm.recastTitle"),message:qe(Ie("confirm.recast"),{name:He.name}),confirmLabel:Ie("confirm.recastTitle"),danger:!0})){T(se.rel);try{const{streamRunnerConversation:dt}=await Kt(async()=>{const{streamRunnerConversation:$t}=await import("./index-DbmziCje.js");return{streamRunnerConversation:$t}},[]),{importOrAppendConversation:xt,shellSessionReader:St}=await Kt(async()=>{const{importOrAppendConversation:$t,shellSessionReader:vn}=await import("./canonical-DDfsxGbh.js");return{importOrAppendConversation:$t,shellSessionReader:vn}},[]),Ft=await dt(St(se.rootKey,se.rel));if(!Ft)throw new Error(Ie("handoff.notASession"));const{deleteProject:un}=await Kt(async()=>{const{deleteProject:$t}=await Promise.resolve().then(()=>mm);return{deleteProject:$t}},void 0);if(await un(He.id),!await xt(Ft))throw new Error(Ie("handoff.notASession"));Ke("success",Ie("atlas.recastDone"),8e3),e(),t()}catch(dt){Ke("error",qe(Ie("atlas.parseFailed"),{msg:dt instanceof Error?dt.message:String(dt)}))}finally{T(null)}}},Bt=async(se,He)=>{const ge=await window.desktopSessions.openInCli(se.runner,se.cwd,se.sessionId,He).catch(()=>({opened:!1,via:"",command:""}));ge.opened&&ge.via==="app"?(await navigator.clipboard.writeText(se.sessionId).catch(()=>{}),Ke("success",Ie("atlas.appOpened"),9e3)):ge.opened?Ke("success",Ie("atlas.opened")):ge.command&&(await navigator.clipboard.writeText(ge.command).catch(()=>{}),Ke("info",Ie("atlas.cmdCopied"),9e3))};return $a.createPortal(u.jsx("div",{className:"fixed inset-0 z-50 bg-ink/30 backdrop-blur-sm flex items-center justify-center p-6","data-session-atlas":!0,children:u.jsxs("div",{className:"bg-surface border border-line rounded-2xl shadow-2xl w-full max-w-[980px] h-[min(680px,90vh)] flex flex-col overflow-hidden",children:[u.jsxs("div",{className:"flex items-start gap-3 px-5 pt-4 pb-3 border-b border-line",children:[u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsx("div",{className:"text-base font-semibold text-ink",children:a("atlas.title")}),u.jsx("div",{className:"text-xs text-ink-muted mt-0.5",children:a("atlas.subtitle")}),me.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:qe(a("atlas.changesSummary"),{n:[...me.values()].filter(se=>se.kind==="new").length,m:[...me.values()].filter(se=>se.kind==="updated").length})}),u.jsx("button",{className:"text-ink-faint hover:text-ink underline decoration-dotted transition-colors",onClick:()=>{hne(c??[]),ke(new Map)},"data-atlas-mark-all":!0,children:a("atlas.markAllSeen")})]})]}),l&&re&&re.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(Ad,{size:14,strokeWidth:1.75}),u.jsxs("select",{value:re.prefs.terminal,onChange:se=>{const He=se.target.value;if(He==="__add__"){window.desktopSessions?.addTerminal().then(()=>window.desktopSessions?.openTargets().then(be));return}window.desktopSessions?.setOpenPrefs({terminal:He}).then(ge=>be(Ve=>Ve&&{...Ve,prefs:ge}))},className:"bg-transparent focus:outline-none text-sm text-ink cursor-pointer","data-atlas-terminal-select":!0,children:[re.terminals.map(se=>u.jsx("option",{value:se.id,children:se.name},se.id)),re.canAddCustom&&u.jsx("option",{value:"__add__",children:a("atlas.otherTerminal")})]})]}),l&&u.jsxs("button",{onClick:()=>_(!0),className:"flex items-center gap-1.5 text-sm text-ink-muted hover:text-ink border border-line rounded-lg px-2.5 py-1.5 hover:bg-wash transition-colors","data-atlas-sources":!0,children:[u.jsx(a7,{size:14,strokeWidth:1.75})," ",a("atlas.sources")]}),l&&u.jsxs("button",{onClick:()=>{Oe()},disabled:p,className:"flex items-center gap-1.5 text-sm text-ink-muted hover:text-ink border border-line rounded-lg px-2.5 py-1.5 hover:bg-wash transition-colors disabled:opacity-60","data-atlas-refresh":!0,children:[p?u.jsx(Xn,{size:14,className:"animate-spin"}):u.jsx(ir,{size:14,strokeWidth:1.75}),a(p?"atlas.scanning":"atlas.refresh")]}),u.jsx("button",{onClick:e,className:"text-ink-faint hover:text-ink p-1.5 rounded-lg hover:bg-wash transition-colors","data-atlas-close":!0,children:u.jsx(bn,{size:18,strokeWidth:1.75})})]}),u.jsxs("div",{className:"flex-1 flex min-h-0",children:[u.jsxs("div",{className:"w-[260px] border-r border-line overflow-y-auto py-2 shrink-0",children:[u.jsx("div",{className:"px-4 py-1 text-2xs uppercase tracking-wide text-ink-faint",children:a("atlas.recent")}),r.filter(se=>!se.archived).sort((se,He)=>He.updatedAt-se.updatedAt).slice(0,6).map(se=>u.jsxs("button",{onClick:()=>{e(),ks(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(P5,{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")}),!l&&u.jsx("div",{className:"px-4 py-2 text-xs text-ink-faint",children:a("atlas.webNoScan")}),l&&c===null&&u.jsxs("div",{className:"px-4 py-2 text-sm text-ink-faint flex items-center gap-2",children:[u.jsx(Xn,{size:14,className:"animate-spin"})," ",a("atlas.scanning")]}),l&&c!==null&&rt.length===0&&u.jsx("div",{className:"px-4 py-2 text-xs text-ink-faint",children:a("atlas.empty")}),rt.map(se=>{const He=se.cwd??"",ge=b!=="canvases"&&kt===se;return u.jsxs("button",{onClick:()=>y(He),className:`w-full text-left px-4 py-2 flex items-center gap-2 transition-colors ${ge?"bg-accent/5 text-accent":"text-ink hover:bg-wash"}`,"data-atlas-folder":se.name||"unfiled",children:[ge?u.jsx(K8,{size:15,strokeWidth:1.75,className:"shrink-0"}):u.jsx(wP,{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 Ve=se.cards.filter(dt=>me.has(cc(dt))).length;return Ve>0?u.jsxs("span",{className:"text-2xs text-accent shrink-0","data-atlas-folder-changes":!0,children:["+",Ve]}):null})(),u.jsx("span",{className:"text-2xs text-ink-faint shrink-0",children:se.cards.length})]},He)}),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(P5,{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,He)=>He.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(),ks(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:J1(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:He=>{He.stopPropagation(),Mf(se.id,!0)},"data-atlas-archive":!0,children:u.jsx(Mo,{size:15,strokeWidth:1.75})}),!!se.sourceSession&&_x(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)," · ",qe(a("atlas.turnsN"),{n:se.sourceSession.importedCount})]}),(se.sourceSession.chapters??[]).map(He=>u.jsxs("span",{children:["↳ ",He.runner," ",He.sessionId.slice(0,8)," · ",qe(a("atlas.turnsN"),{n:He.importedCount})]},He.sessionId)),(se.sourceSession.branches??[]).map(He=>u.jsxs("span",{children:["⑂ ",He.runner," ",He.sessionId.slice(0,8)," · ",qe(a("atlas.turnsN"),{n:He.importedCount})]},He.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:qe(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,He)=>He.updatedAt-se.updatedAt).map(se=>u.jsxs("button",{title:a("atlas.restoreOpen"),onClick:()=>{Mf(se.id,!1).then(()=>{e(),ks(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:J1(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(Af,{size:13,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),u.jsx("input",{value:U,onChange:se=>G(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})]}),ot.map(se=>u.jsx("button",{onClick:()=>X(He=>{const ge=new Set(He);return ge.has(se)?ge.delete(se):ge.add(se),ge}),className:`text-2xs font-mono border rounded-lg px-2 py-1 transition-colors ${ne.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)),me.size>0&&u.jsx("button",{onClick:()=>W(se=>!se),className:`text-2xs border rounded-lg px-2 py-1 transition-colors ${J?"border-accent text-white bg-accent":"border-line text-ink-muted hover:text-ink"}`,"data-atlas-only-changed":!0,children:a("atlas.onlyChanged")}),(c??[]).some(se=>se.subagent)&&u.jsx("button",{onClick:()=>ve(se=>!se),className:`text-2xs border rounded-lg px-2 py-1 transition-colors ${ae?"border-accent text-accent bg-accent/5":"border-line text-ink-faint hover:text-ink"}`,"data-atlas-show-sub":!0,children:a("atlas.showSub")}),u.jsxs("button",{onClick:()=>F(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(yj,{size:12,strokeWidth:1.75}),a(`atlas.sort${P[0].toUpperCase()}${P.slice(1)}`)]})]}),kt?u.jsxs(u.Fragment,{children:[kt.cwd&&u.jsxs("div",{className:"text-2xs text-ink-faint mb-3 truncate",children:[kt.cwd," · ",qe(a("atlas.sessions"),{n:kt.cards.length})]}),u.jsx("div",{className:"space-y-1.5",children:ht.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:()=>{wt(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:je(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:"⑂"}),me.get(cc(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")}),me.get(cc(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:["+",HE(me.get(cc(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 He=K(se.sessionId);return He?u.jsx("span",{className:"text-2xs text-ink-faint border border-line rounded px-1 py-px shrink-0",title:He.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:J1(se.mtime)}),u.jsx("span",{children:HE(se.size)})]})]}),E===se.rel?u.jsx(Xn,{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:[!K(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:He=>{He.stopPropagation(),q(se)},"data-atlas-pick":R.has(Z(se))?"on":"off",children:R.has(Z(se))?u.jsx(Tz,{size:16,strokeWidth:1.75}):u.jsx(Ab,{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(RP,{size:16,strokeWidth:1.75})}),r.some(He=>He.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:He=>{He.stopPropagation(),We(se)},"data-atlas-recast":!0,children:u.jsx(hz,{size:16,strokeWidth:1.75})}),!K(se.sessionId)&&u.jsx("button",{title:a("atlas.mountTo"),className:"text-ink-faint hover:text-accent p-1.5 rounded transition-colors",onClick:He=>{He.stopPropagation(),C(se)},"data-atlas-mount":!0,children:u.jsx(So,{size:16,strokeWidth:1.75})}),Le.has(se.runner)&&u.jsx("button",{title:qe(a("atlas.openApp"),{name:Le.get(se.runner)}),className:"text-ink-faint hover:text-accent p-1.5 rounded transition-colors",onClick:He=>{He.stopPropagation(),Bt(se,"app")},"data-atlas-open-app":!0,children:u.jsx(pj,{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:He=>{He.stopPropagation(),Bt(se,"terminal")},"data-atlas-open-cli":!0,children:u.jsx(Ad,{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&&!H&&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:qe(a("atlas.mergeSelected"),{n:R.size})}),E==="__merge__"?u.jsx(Xn,{size:15,className:"animate-spin text-accent"}):u.jsxs(u.Fragment,{children:[u.jsx("button",{className:"text-xs bg-accent hover:bg-accent-strong text-white font-medium px-3 py-1.5 rounded-lg transition-colors whitespace-nowrap",onClick:()=>{zt()},"data-atlas-merge-new":!0,children:a("atlas.mergeNew")}),u.jsx("button",{className:"text-xs text-ink-muted hover:text-ink hover:bg-wash font-medium px-3 py-1.5 rounded-lg transition-colors whitespace-nowrap",onClick:()=>Y(!0),"data-atlas-merge-into":!0,children:a("atlas.mergeInto")})]}),u.jsx("button",{className:"text-ink-faint hover:text-ink p-1",onClick:()=>B(new Map),title:a("common.cancel"),children:u.jsx(bn,{size:14,strokeWidth:1.75})})]}),(A||H)&&u.jsx("div",{className:"absolute inset-0 z-10 bg-ink/20 flex items-center justify-center",onClick:()=>{C(null),Y(!1)},children:u.jsxs("div",{className:"bg-surface border border-line rounded-2xl shadow-xl w-[400px] max-h-[70%] overflow-y-auto",onClick: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(H?"atlas.mergeInto":"atlas.mountTo")}),u.jsx("div",{className:"text-2xs text-ink-muted mt-0.5",children:a(H?"atlas.mergeSelected":"atlas.mountHint").replace("{n}",String(R.size))})]}),r.filter(se=>!se.archived&&se.kind!=="paradigm").sort((se,He)=>He.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(H){Y(!1),zt(se.id);return}const He=A;C(null),(async()=>{T(He.rel);try{const{streamRunnerConversation:ge}=await Kt(async()=>{const{streamRunnerConversation:Ft}=await import("./index-DbmziCje.js");return{streamRunnerConversation:Ft}},[]),{mountConversationToProject:Ve,shellSessionReader:dt}=await Kt(async()=>{const{mountConversationToProject:Ft,shellSessionReader:un}=await import("./canonical-DDfsxGbh.js");return{mountConversationToProject:Ft,shellSessionReader:un}},[]),xt=await ge(dt(He.rootKey,He.rel)),St=await Ve(xt,se.id);if(!St)throw new Error(Ie("handoff.notASession"));Ke("success",qe(Ie("atlas.mountedChapter"),{n:St.kind==="mounted"||St.kind==="appended"?St.turns:0}),9e3),e(),t()}catch(ge){Ke("error",qe(Ie("atlas.parseFailed"),{msg:ge instanceof Error?ge.message:String(ge)}))}finally{T(null)}})()},children:se.name},se.id))]})}),w&&u.jsx(mne,{roots:h,counts:Xe,onChanged:()=>{Oe()},onClose:()=>_(!1)})]})}),document.body)}function pne({conversations:e,onClose:t,onDone:n}){const a=Gt(),[r,s]=j.useState(new Set),[l,c]=j.useState(!1),d=p=>{s(x=>{const b=new Set(x);return b.has(p)?b.delete(p):b.add(p),b})},h=r.size===e.length,m=async()=>{r.size===0||l||(c(!0),await KH([...r].sort((p,x)=>p-x).map(p=>e[p])),c(!1),n())};return u.jsx("div",{className:"fixed inset-0 z-50 bg-ink/30 backdrop-blur-sm flex items-center justify-center p-6",onClick:t,children:u.jsxs("div",{className:"bg-card border border-line rounded-2xl shadow-2xl w-full max-w-lg max-h-[80vh] flex flex-col",onClick:p=>p.stopPropagation(),children:[u.jsxs("div",{className:"px-6 py-4 border-b border-line flex items-start justify-between gap-4",children:[u.jsxs("div",{children:[u.jsx("h2",{className:"text-base font-semibold text-ink",children:a("import.title")}),u.jsx("p",{className:"text-xs text-ink-muted mt-1 leading-relaxed",children:a("import.subtitle")})]}),u.jsx("button",{onClick:t,className:"text-ink-faint hover:text-ink transition-colors shrink-0 mt-0.5",children:u.jsx(bn,{size:16,strokeWidth:1.75})})]}),u.jsx("div",{className:"px-6 py-2 border-b border-line/60",children:u.jsxs("label",{className:"flex items-center gap-2 text-xs text-ink-muted cursor-pointer select-none py-1",children:[u.jsx("input",{type:"checkbox",checked:h,onChange:()=>s(h?new Set:new Set(e.map((p,x)=>x))),className:"rounded border-line text-accent focus:ring-accent w-3.5 h-3.5"}),a("import.selectAll"),u.jsx("span",{className:"ml-auto text-2xs text-ink-faint uppercase tracking-wider",children:e[0]?.source})]})}),u.jsx("ul",{className:"flex-1 overflow-y-auto py-1",children:e.map((p,x)=>u.jsx("li",{children:u.jsxs("label",{className:"flex items-center gap-3 px-6 py-2 hover:bg-wash transition-colors cursor-pointer select-none",children:[u.jsx("input",{type:"checkbox",checked:r.has(x),onChange:()=>d(x),className:"rounded border-line text-accent focus:ring-accent w-3.5 h-3.5 shrink-0"}),u.jsx(n7,{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:qe(a("import.messages"),{n:p.messageCount})})]})},x))}),u.jsxs("div",{className:"px-6 py-4 border-t border-line flex justify-end gap-2",children:[u.jsx("button",{onClick:t,className:"text-xs text-ink-muted hover:text-ink px-4 py-2 rounded-lg hover:bg-wash transition-colors",children:a("common.cancel")}),u.jsx("button",{onClick:()=>{m()},disabled:r.size===0||l,className:"text-xs bg-accent hover:bg-accent-strong text-white px-5 py-2 rounded-lg transition-colors disabled:opacity-30",children:l?"…":qe(a("import.confirm"),{n:r.size})})]})]})})}function gne(e){const t=Date.now()-e,n=Math.floor(t/6e4);if(n<1)return Ie("switcher.justNow");if(n<60)return qe(Ie("switcher.minAgo"),{n});const a=Math.floor(n/60);if(a<24)return qe(Ie("switcher.hourAgo"),{n:a});const r=Math.floor(a/24);return r<30?qe(Ie("switcher.dayAgo"),{n:r}):new Date(e).toLocaleDateString(Fa.getState().lang==="zh"?"zh-CN":"en-US")}function xne({onSwitched:e}){const t=Gt(),n=Nn(N=>N.projects),a=Nn(N=>N.activeId),r=Nn(N=>N.switching),s=n.find(N=>N.id===a)?.kind==="paradigm",[l,c]=j.useState(!1),[d,h]=j.useState(null),[m,p]=j.useState(!1),[x,b]=j.useState(void 0),[y,E]=j.useState(null),[T,w]=j.useState(""),_=j.useRef(null),A=j.useRef(null),C=n.find(N=>N.id===a),O=n.filter(N=>!N.archived).sort((N,R)=>R.updatedAt-N.updatedAt).slice(0,7),D=async N=>{const{canvasUniqueness:R}=await Kt(async()=>{const{canvasUniqueness:Z}=await import("./canonical-DDfsxGbh.js");return{canvasUniqueness:Z}},[]),B=await R(N.id),H=B==="native"?"confirm.deleteNative":B==="diverged-mirror"?"confirm.deleteDiverged":"confirm.deletePristine";await Es({title:Ie("confirm.deleteCanvasTitle"),message:qe(Ie(H),{name:N.name}),confirmLabel:Ie("common.delete"),danger:B!=="pristine-mirror"})&&q7(N.id).then(e)};j.useEffect(()=>{if(!l)return;const N=R=>{A.current?.contains(R.target)||c(!1)};return window.addEventListener("mousedown",N),()=>window.removeEventListener("mousedown",N)},[l]);const M=async N=>{c(!1),await ks(N),e(),Kt(()=>import("./canonical-DDfsxGbh.js"),[]).then(R=>R.unsubscribeOrphanedSessions()),Kt(()=>import("./live-mirror-Cil__utB.js"),[]).then(R=>R.sweepRecentSessions())};return u.jsxs("div",{ref:A,className:"absolute top-4 left-4 z-20",children:[u.jsxs("div",{className:"flex items-center gap-1.5",children:[u.jsxs("button",{onClick:()=>c(!l),disabled:r,className:"bg-card/90 backdrop-blur border border-line rounded-xl px-3.5 py-2 shadow-sm hover:bg-wash transition-colors flex items-center gap-2 text-sm text-ink max-w-[240px] disabled:opacity-60",children:[r?u.jsx(Xn,{size:16,strokeWidth:1.75,className:"animate-spin shrink-0 text-accent"}):s?u.jsx(aP,{size:16,strokeWidth:1.75,className:"shrink-0 text-accent"}):u.jsx(K8,{size:16,strokeWidth:1.75,className:"shrink-0 text-ink-muted"}),u.jsx("span",{className:"truncate font-medium",children:C?.name??"…"}),u.jsx(Yd,{size:14,strokeWidth:1.75,className:"shrink-0 text-ink-faint"})]}),!!C?.sourceSession?.sessionId&&(()=>{const N=Gf.size>0&&!Gf.has(C.sourceSession.sessionId);return u.jsxs("button",{title:N?Ie("switcher.mirrorBadgeGone"):qe(Ie("switcher.mirrorBadge"),{runner:C.sourceSession.runner}),onClick:()=>{b(C.sourceSession.sessionId),p(!0)},className:`bg-card/90 backdrop-blur border border-line rounded-xl px-2 py-2 shadow-sm hover:bg-wash transition-colors text-2xs font-mono flex items-center gap-1 ${N?"text-ink-faint/50 line-through decoration-1":"text-ink-faint hover:text-accent"}`,"data-twin-badge":N?"unreachable":"live",children:["⇄ ",C.sourceSession.runner]})})()]}),l&&u.jsxs("div",{className:"mt-1.5 bg-card border border-line rounded-xl shadow-lg py-1.5 w-[320px] animate-fade-in",children:[u.jsx("div",{className:"max-h-[320px] overflow-y-auto",children:O.map(N=>u.jsx("div",{className:`group flex items-center gap-1 px-3 py-2 hover:bg-wash cursor-pointer transition-colors ${N.id===a?"bg-accent/5":""}`,onClick:()=>{y!==N.id&&N.id!==a&&M(N.id)},children:y===N.id?u.jsx("input",{autoFocus:!0,value:T,onChange:R=>w(R.target.value),onClick:R=>R.stopPropagation(),onKeyDown:R=>{R.key==="Enter"&&!Ya(R)&&T.trim()&&(F7(N.id,T.trim()),E(null)),R.key==="Escape"&&E(null)},onBlur:()=>E(null),className:"flex-1 text-sm text-ink border border-accent/40 rounded-lg px-2 py-1 bg-surface focus:outline-none"}):u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsx("div",{className:`text-sm truncate ${N.id===a?"text-accent font-medium":"text-ink"}`,children:N.name}),u.jsxs("div",{className:"text-2xs text-ink-faint flex items-center gap-1.5",children:[u.jsx("span",{children:gne(N.updatedAt)}),!!N.sourceSession?.sessionId&&u.jsx("span",{className:"font-mono border border-line rounded px-1 py-px","data-mirror-mark":!0,children:N.sourceSession.runner})]})]}),u.jsx("button",{title:t("switcher.rename"),className:"opacity-0 group-hover:opacity-100 text-ink-faint hover:text-ink p-1 rounded transition-all shrink-0",onClick:R=>{R.stopPropagation(),E(N.id),w(N.name)},children:u.jsx(Oc,{size:14,strokeWidth:1.75})}),u.jsx("button",{title:t("common.delete"),className:"opacity-0 group-hover:opacity-100 text-ink-faint hover:text-red-500 p-1 rounded transition-all shrink-0",onClick:R=>{R.stopPropagation(),D(N)},children:u.jsx(Ua,{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(),Mf(N.id,!0).then(e)},"data-archive-canvas":!0,children:u.jsx(Mo,{size:14,strokeWidth:1.75})})]})},N.id))}),u.jsxs("div",{className:"border-t border-line mt-1 pt-1",children:[u.jsxs("button",{onClick:()=>{c(!1),fm().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(lm,{size:15,strokeWidth:1.75})," ",t("switcher.newCanvas")]}),u.jsxs("button",{onClick:()=>_.current?.click(),className:"w-full text-left px-3 py-2 text-sm text-ink-muted hover:bg-wash transition-colors flex items-center gap-2",children:[u.jsx(jz,{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(YP,{size:15,strokeWidth:1.75})," ",t("switcher.allCanvases")]}),window.desktop&&u.jsxs("button",{onClick:()=>{c(!1),window.desktop.checkForUpdates()},className:"w-full text-left px-3 py-2 text-sm text-ink-muted hover:bg-wash transition-colors flex items-center gap-2","data-check-updates":!0,children:[u.jsx(ir,{size:15,strokeWidth:1.75})," ",t("update.checkMenu"),u.jsxs("span",{className:"ml-auto text-2xs text-ink-faint",children:["v",new URLSearchParams(window.location.search).get("dv")]})]}),u.jsx("input",{ref:_,type:"file",accept:".json,.jsonl,application/json",className:"hidden",onChange:N=>{const R=N.target.files?.[0];R&&YH(R).then(B=>{B.kind==="own"&&B.ok?(c(!1),e()):B.kind==="chat"&&(c(!1),h(B.conversations))}).catch(B=>{Ke("error",qe(Ie("toast.importFailedGeneric"),{msg:B instanceof Error?B.message:String(B)}))}),N.target.value=""}})]})]}),d&&u.jsx(pne,{conversations:d,onClose:()=>h(null),onDone:()=>{h(null),e()}}),m&&u.jsx(_N,{onClose:()=>{p(!1),b(void 0)},onSwitched:e,focusSessionId:x})]})}const bne="JVBERi0xLjQKMSAwIG9iago8PCAvVHlwZSAvQ2F0YWxvZyAvUGFnZXMgMiAwIFIgPj4KZW5kb2JqCjIgMCBvYmoKPDwgL1R5cGUgL1BhZ2VzIC9LaWRzIFszIDAgUiA0IDAgUl0gL0NvdW50IDIgPj4KZW5kb2JqCjMgMCBvYmoKPDwgL1R5cGUgL1BhZ2UgL1BhcmVudCAyIDAgUiAvTWVkaWFCb3ggWzAgMCA1OTUgODQyXSAvQ29udGVudHMgNSAwIFIgL1Jlc291cmNlcyA8PCAvRm9udCA8PCAvRjEgNyAwIFIgL0YyIDggMCBSID4+ID4+ID4+CmVuZG9iago0IDAgb2JqCjw8IC9UeXBlIC9QYWdlIC9QYXJlbnQgMiAwIFIgL01lZGlhQm94IFswIDAgNTk1IDg0Ml0gL0NvbnRlbnRzIDYgMCBSIC9SZXNvdXJjZXMgPDwgL0ZvbnQgPDwgL0YxIDcgMCBSIC9GMiA4IDAgUiA+PiA+PiA+PgplbmRvYmoKNSAwIG9iago8PCAvTGVuZ3RoIDExMTIgPj4Kc3RyZWFtCkJUCi9GMiAxOSBUZiAxIDAgMCAxIDY0IDcyNS4wIFRtIChXaHkgU2F2ZWQgQXJ0aWNsZXMgU3RheSBVbnJlYWQpIFRqCi9GMSAxMSBUZiAxIDAgMCAxIDY0IDcwOC4wIFRtIChBIHNob3J0IGJyaWVmIG9uIGRpZ2l0YWwgaG9hcmRpbmcgYW5kIHRoZSBjb2xsZWN0b3IncyBmYWxsYWN5KSBUagovRjIgMTMgVGYgMSAwIDAgMSA2NCA2NjkuMCBUbSAoMS4gVGhlIHBoZW5vbWVub24pIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNjUxLjUgVG0gKFJlYWQtaXQtbGF0ZXIgc2VydmljZXMgcmVwb3J0IHRoYXQgbW9zdCBzYXZlZCBpdGVtcyBhcmUgbmV2ZXIpIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNjM0LjAgVG0gKHJlb3BlbmVkLiBBY3Jvc3MgcHVibGlzaGVkIHVzYWdlIHN0dWRpZXMsIHRoZSBzaGFyZSBvZiBzYXZlZCkgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA2MTYuNSBUbSAoYXJ0aWNsZXMgdGhhdCBnZXQgYSBzZWNvbmQgdmlzaXQgaXMgc21hbGwsIGFuZCBjb21wbGV0aW9uIHJhdGVzKSBUagovRjEgMTEuNSBUZiAxIDAgMCAxIDY0IDU5OS4wIFRtIChhcmUgc21hbGxlciBzdGlsbC4gVGhlIGFyY2hpdmUgZ3Jvd3M7IHRoZSByZWFkaW5nIGRvZXMgbm90LikgVGoKL0YyIDEzIFRmIDEgMCAwIDEgNjQgNTYwLjAgVG0gKDIuIFRoZSBjb2xsZWN0b3IncyBmYWxsYWN5KSBUagovRjEgMTEuNSBUZiAxIDAgMCAxIDY0IDU0Mi41IFRtIChDb2xsZWN0aW5nIHByb2R1Y2VzIGFuIGltbWVkaWF0ZSBzZW5zZSBvZiBwcm9ncmVzcyB3aGlsZSB0aGUpIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNTI1LjAgVG0gKHVuZGVyc3RhbmRpbmcgaXQgcHJvbWlzZXMgaXMgZGVmZXJyZWQuIFNhdmluZyBhIHRleHQgZmVlbHMgbGlrZSkgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA1MDcuNSBUbSAoYSBmaXJzdCBzdGVwIG9mIHJlYWRpbmcgaXQsIGJ1dCBubyBwYXJ0IG9mIHRoZSByZWFkaW5nIGhhcykgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA0OTAuMCBUbSAoaGFwcGVuZWQuKSBUagovRjIgMTEuNSBUZiAxIDAgMCAxIDY0IDQ3Mi41IFRtIChUaGUgYWN0IG9mIHNhdmluZyBpcyBtaXN0YWtlbiBmb3IgdGhlIGFjdCBvZiBsZWFybmluZy4pIFRqCkVUCmVuZHN0cmVhbQplbmRvYmoKNiAwIG9iago8PCAvTGVuZ3RoIDkwOCA+PgpzdHJlYW0KQlQKL0YyIDEzIFRmIDEgMCAwIDEgNjQgNzI1LjAgVG0gKDMuIFdoeSBpdCBwZXJzaXN0cykgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA3MDcuNSBUbSAoVGhlIGNvc3RzIGFyZSBhc3ltbWV0cmljOiBzYXZpbmcgdGFrZXMgb25lIHNlY29uZCBhbmQgcGF5cyBvdXQpIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNjkwLjAgVG0gKGEgc21hbGwgcmV3YXJkIG5vdzsgcmVhZGluZyB0YWtlcyBhbiBob3VyIGFuZCBwYXlzIG91dCBsYXRlci4pIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNjcyLjUgVG0gKEhhYml0cyBmb2xsb3cgdGhlIGNoZWFwZXIgbG9vcCwgc28gbGlicmFyaWVzIGluZmxhdGUgYnkgZGVmYXVsdC4pIFRqCi9GMiAxMyBUZiAxIDAgMCAxIDY0IDYzMy41IFRtICg0LiBXaGF0IGhlbHBzKSBUagovRjEgMTEuNSBUZiAxIDAgMCAxIDY0IDYxNi4wIFRtIChJbnRlcnZlbnRpb25zIHRoYXQgd29yayBtb3ZlIHByb2Nlc3NpbmcgdG8gdGhlIG1vbWVudCBvZiBjYXB0dXJlOikgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA1OTguNSBUbSAod3JpdGUgb25lIGxpbmUgaW4geW91ciBvd24gd29yZHMgYWJvdXQgd2h5IHRoZSBpdGVtIG1hdHRlcnMsIGFuZCkgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA1ODEuMCBUbSAoc2NoZWR1bGUgYSByZXZpZXcgcGFzcyBpbnN0ZWFkIG9mIHRydXN0aW5nIHRoZSBhcmNoaXZlIHRvKSBUagovRjEgMTEuNSBUZiAxIDAgMCAxIDY0IDU2My41IFRtIChyZXN1cmZhY2UgaXQuKSBUagovRjEgMTEuNSBUZiAxIDAgMCAxIDY0IDUzMi4wIFRtIChBIHNtYWxsZXIgbGlicmFyeSB0aGF0IGdldHMgcHJvY2Vzc2VkIGJlYXRzIGEgY29tcGxldGUgb25lIHRoYXQpIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNTE0LjUgVG0gKGRvZXMgbm90LikgVGoKRVQKZW5kc3RyZWFtCmVuZG9iago3IDAgb2JqCjw8IC9UeXBlIC9Gb250IC9TdWJ0eXBlIC9UeXBlMSAvQmFzZUZvbnQgL0hlbHZldGljYSA+PgplbmRvYmoKOCAwIG9iago8PCAvVHlwZSAvRm9udCAvU3VidHlwZSAvVHlwZTEgL0Jhc2VGb250IC9IZWx2ZXRpY2EtQm9sZCA+PgplbmRvYmoKeHJlZgowIDkKMDAwMDAwMDAwMCA2NTUzNSBmIAowMDAwMDAwMDA5IDAwMDAwIG4gCjAwMDAwMDAwNTggMDAwMDAgbiAKMDAwMDAwMDEyMSAwMDAwMCBuIAowMDAwMDAwMjU3IDAwMDAwIG4gCjAwMDAwMDAzOTMgMDAwMDAgbiAKMDAwMDAwMTU1NyAwMDAwMCBuIAowMDAwMDAyNTE2IDAwMDAwIG4gCjAwMDAwMDI1ODYgMDAwMDAgbiAKdHJhaWxlcgo8PCAvU2l6ZSA5IC9Sb290IDEgMCBSID4+CnN0YXJ0eHJlZgoyNjYxCiUlRU9G",yne=`<!-- tdag-page:1 -->
|
|
521
521
|
|
|
522
522
|
# Why Saved Articles Stay Unread
|
|
523
523
|
|
|
@@ -717,7 +717,7 @@ Move processing to the moment of capture: one line in your own words on why it m
|
|
|
717
717
|
|
|
718
718
|
把「处理」前置到收藏那一刻:当场用自己的话写一句为什么重要,并安排定期回访,而不是指望收藏夹自己浮现 (p.2)。被处理的小书库,胜过完整的死书库。
|
|
719
719
|
|
|
720
|
-
*(我是一个导读节点:在阅读器里点「生成导读」长出来的。阅读器顶部的「导读」标签页就是我的阅读视图,(p.N) 在那里是可点击的跳页按钮。把我连向下游,后续问题就以这份压缩为上下文,而不是整份原文。)*`,x:2980,y:690,extra:{digestOf:"ex-att-brief",summaries:["导读完成:存≠学,处理才算数;要点均带页码"]}},{id:"frame-chain",q:"① 对话:主链 · 分支 · 评审",a:"",x:0,y:240,w:1290,h:1460,extra:{stepKind:"frame",frameColor:"violet"}},{id:"frame-material",q:"② 材料与引用",a:"",x:1400,y:0,w:640,h:1560,extra:{stepKind:"frame",frameColor:"amber"}},{id:"frame-prune",q:"③ ⚖️ 修剪上下文",a:"",x:2160,y:0,w:640,h:1240,extra:{stepKind:"frame",frameColor:"sky"}},{id:"frame-read",q:"④ 阅读闭环:文献长成对话",a:"",x:2920,y:0,w:1270,h:1240,extra:{stepKind:"frame",frameColor:"green"}}]}};function wne(e){const{nodes:t}=VE[e]??VE.en,n=t.map(({id:c,q:d,a:h,x:m,y:p,w:x,h:b,extra:y})=>({id:`ex-${c}`,type:"thought",position:{x:m,y:p},...x?{width:x}:{},...b?{height:b}:{},...y?.stepKind==="frame"?{zIndex:-1}:{},dragHandle:".drag-handle",data:{question:d,response:h,responses:h?[h]:[],responseIndex:h?0:-1,isCollapsed:!1,isEditing:!1,isEditingResponse:!1,isLoading:!1,tokenCount:Math.ceil((d+h).length/4),highlights:[],highlightMode:"tag",attachments:[],excludedAttachmentIds:[],includedAttachmentIds:[],roleMode:"inherit",isRoot:!1,isBranch:!1,...y}})),a=(c,d,h={})=>({id:`ex-e-${c}-${d}`,source:`ex-${c}`,target:`ex-${d}`,type:"smoothstep",sourceHandle:h.branch||h.ref?"branch":"continue",targetHandle:h.branch||h.watch||h.ref?"left":"top",animated:!!(h.branch||h.watch||h.ref),style:h.watch?{stroke:nt.watch,strokeWidth:2,strokeDasharray:"4 4"}:h.branch?{stroke:nt.warm,strokeWidth:2}:h.ref?{stroke:nt.accent,strokeWidth:2,strokeDasharray:"8 4"}:{stroke:nt.accent,strokeWidth:2},markerEnd:{type:"arrowclosed",color:h.watch?nt.watch:h.branch?nt.warm:nt.accent,width:18,height:18},data:h.watch?{isCrossLink:!0,isWatch:!0}:h.ref?{isCrossLink:!0}:h.branch?{isBranchFromSelection:!0}:{}}),r=[a("root","chain1"),a("root","ruleout",{branch:!0}),a("chain1","branch1",{branch:!0}),a("branch1","evaluator",{watch:!0}),a("note","ask"),a("branch1","ask",{ref:!0}),a("ask","stale-demo"),a("noise","cmp-full"),a("stale-demo","cmp-full",{branch:!0}),a("stale-demo","cmp-pruned",{branch:!0}),a("brief","brief-ask",{branch:!0}),a("brief","brief-digest")],s=[0,45,30,70,40,55,900,35,50,45,60,40,980,30,55,40,65,45,50,35];let l=Date.now()-72*3600*1e3;return n.forEach((c,d)=>{l+=(s[d%s.length]||45)*60*1e3,c.data.createdAt=new Date(l).toISOString()}),{nodes:n,edges:r}}function $f(e){const t=ye.getState();if(!t.panelOpen)return 0;const n=oe.getState().nodes.find(a=>a.id===e)?.data?.stepKind;return n==="note"||n==="file"||n==="link"||n==="frame"?0:t.panelWidth+ad+12}async function Ene(){const{nodes:e}=oe.getState();if(!e.some(n=>n.data.attachments?.some(a=>a.type==="application/pdf"&&a.content&&!a.contentInVault)))return;const t=await Db(e);oe.getState().nodes===e&&oe.setState({nodes:t})}async function kne(){try{const e=new Set;for(const n of oe.getState().nodes)for(const a of n.data.attachments??[])e.add(a.id);for(const n of Nn.getState().projects){const a=await xl(ni(n.id)).catch(()=>null),s=(typeof a=="string"?JSON.parse(a):a)?.state?.nodes??[];for(const l of s)for(const c of l.data.attachments??[])e.add(c.id)}const t=await FB(e);t>0&&console.info(`[thoughtdag] vault GC: swept ${t} orphaned payload(s)`)}catch(e){console.warn("[thoughtdag] vault GC failed:",e)}}const rb="thoughtdag.orVerifier",WE="https://openrouter.ai/auth",Tne="https://openrouter.ai/api/v1/auth/keys",MN=e=>btoa(String.fromCharCode(...e)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");async function Sne(e){const t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return MN(new Uint8Array(t))}async function IN(){const e=MN(crypto.getRandomValues(new Uint8Array(48))),t=await Sne(e);if(window.desktop){const a=`${location.origin}/oauth/openrouter`;window.open(`${WE}?callback_url=${encodeURIComponent(a)}&code_challenge=${t}&code_challenge_method=S256`),Ke("info",Ie("provider.oauthBrowserWait"));const r=await Ane();if(!r){Ke("error",qe(Ie("provider.oauthFailed"),{error:Ie("provider.oauthTimeout")}));return}const s=await ON(r,e);s.status==="minted"?(Ke("success",Ie("provider.oauthMinted")),DN(s.key)):Ke("error",qe(Ie("provider.oauthFailed"),{error:s.error}));return}sessionStorage.setItem(rb,e);const n=`${location.origin}${location.pathname}`;location.href=`${WE}?callback_url=${encodeURIComponent(n)}&code_challenge=${t}&code_challenge_method=S256`}async function Ane(){for(let e=0;e<100;e++){await new Promise(t=>setTimeout(t,3e3));try{const t=await fetch(`${Rs}/oauth/openrouter/code`),{code:n}=await t.json();if(n)return n}catch{}}return null}function DN(e){ye.getState().setOauthMintedKey(e),ye.getState().setApiKeyModalOpen(!0)}async function Nne(){const e=new URLSearchParams(location.search),t=e.get("code"),n=sessionStorage.getItem(rb);if(!t||!n)return null;sessionStorage.removeItem(rb),e.delete("code");const a=e.toString();return history.replaceState(null,"",`${location.pathname}${a?`?${a}`:""}${location.hash}`),ON(t,n)}async function ON(e,t){try{const n=await fetch(Tne,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e,code_verifier:t,code_challenge_method:"S256"})});if(!n.ok)throw new Error(`HTTP ${n.status}`);const{key:a}=await n.json();if(!a)throw new Error("no key in exchange response");return{status:"minted",key:a}}catch(n){return{status:"failed",error:n instanceof Error?n.message:String(n)}}}function Cne(){const e=window.desktop;e?.onUpdateEvent&&e.onUpdateEvent(t=>{switch(t.kind){case"available":Ke("info",qe(Ie("update.found"),{v:t.version??""}),0,{label:Ie("update.downloadAction"),run:()=>{e.downloadUpdate?.()}});break;case"downloading":Ke("info",qe(Ie("update.downloading"),{p:String(t.percent??0)}));break;case"ready":Ke("success",qe(Ie("update.ready"),{v:t.version??""}),0,{label:Ie("update.restartAction"),run:()=>{e.installUpdate?.()}});break;case"latest":Ke("success",qe(Ie("update.latest"),{v:t.version??""}));break;case"check-failed":Ke("error",Ie("update.checkFailed"));break;case"download-failed":Ke("error",Ie("update.downloadFailed"));break;case"dev":Ke("info","Dev build: no update channel.");break}})}function _ne(){const e=ye(a=>a.confirmRequest),t=ye(a=>a.resolveConfirm),n=Gt();return j.useEffect(()=>{if(!e)return;const a=r=>{r.stopPropagation(),r.key==="Escape"&&t(!1),r.key==="Enter"&&t(!0)};return window.addEventListener("keydown",a,!0),()=>window.removeEventListener("keydown",a,!0)},[e,t]),e?u.jsx("div",{className:"fixed inset-0 z-[100] bg-black/25 flex items-center justify-center animate-fade-in",onClick:()=>t(!1),children:u.jsxs("div",{className:"bg-card border border-line rounded-xl shadow-xl w-[380px] p-5",onClick:a=>a.stopPropagation(),children:[e.title&&u.jsx("h3",{className:"text-sm font-semibold text-ink mb-1.5",children:e.title}),u.jsx("p",{className:"text-sm text-ink-muted leading-relaxed whitespace-pre-line [overflow-wrap:anywhere]",children:e.message}),u.jsxs("div",{className:"flex justify-end gap-2 mt-5",children:[u.jsx("button",{onClick:()=>t(!1),className:"text-xs text-ink-muted hover:text-ink px-4 py-2 rounded-lg hover:bg-wash transition-colors",children:n("common.cancel")}),u.jsx("button",{onClick:()=>t(!0),autoFocus:!0,className:`text-xs text-white px-4 py-2 rounded-lg transition-colors ${e.danger?"bg-red-500 hover:bg-red-600":"bg-accent hover:bg-accent-strong"}`,children:e.confirmLabel??n("common.confirm")})]})]})}):null}const Mne={error:"border-red-200 bg-red-50 text-red-700",success:"border-green-200 bg-green-50 text-green-700",info:"border-line bg-card text-ink-muted"},Ine={error:qj,success:Wj,info:PP};function Dne(){const e=ye(n=>n.toasts),t=ye(n=>n.dismissToast);return e.length===0?null:u.jsx("div",{className:"fixed bottom-4 right-4 z-[90] flex flex-col gap-2 max-w-[380px]",children:e.map(n=>{const a=Ine[n.kind];return u.jsxs("div",{className:`flex items-start gap-2.5 border rounded-xl shadow-lg px-4 py-3 animate-fade-in ${Mne[n.kind]}`,children:[u.jsx(a,{size:16,strokeWidth:1.75,className:"shrink-0 mt-0.5"}),u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsx("p",{className:"text-xs leading-relaxed break-words",children:n.message}),n.action&&u.jsx("button",{onClick:()=>{n.action.run(),t(n.id)},className:"mt-2 text-2xs font-medium bg-accent/10 text-accent hover:bg-accent/20 px-2.5 py-1 rounded-lg transition-colors",children:n.action.label})]}),u.jsx("button",{onClick:()=>t(n.id),className:"shrink-0 opacity-50 hover:opacity-100 transition-opacity",children:u.jsx(bn,{size:14,strokeWidth:1.75})})]},n.id)})})}const One=350;function Rne(){const[e,t]=j.useState(null);return j.useEffect(()=>{let n=0,a=null;const r=()=>{a?.dataset.tipStash!==void 0&&(a.setAttribute("title",a.dataset.tipStash),delete a.dataset.tipStash)},s=()=>{window.clearTimeout(n),r(),a=null,t(null)},l=h=>{const m=h.target?.closest?.("[title], [data-tip-stash]");if(!m||m===a)return;s();const p=m.getAttribute("title")??m.dataset.tipStash??"";p.trim()&&(a=m,m.dataset.tipStash=p,m.removeAttribute("title"),n=window.setTimeout(()=>{if(a!==m||!m.isConnected)return;m.removeAttribute("title");const x=m.getBoundingClientRect(),b=x.bottom>window.innerHeight-96;t({text:p,x:Math.max(12,Math.min(x.left+x.width/2,window.innerWidth-12)),top:x.top,bottom:x.bottom,above:b})},One))},c=h=>{if(!a)return;const m=h.relatedTarget;m instanceof Node&&a.contains(m)||h.target instanceof Node&&(a===h.target||a.contains(h.target))&&s()},d=()=>s();return document.addEventListener("mouseover",l),document.addEventListener("mouseout",c),document.addEventListener("mousedown",d,!0),document.addEventListener("scroll",d,!0),window.addEventListener("blur",d),()=>{s(),document.removeEventListener("mouseover",l),document.removeEventListener("mouseout",c),document.removeEventListener("mousedown",d,!0),document.removeEventListener("scroll",d,!0),window.removeEventListener("blur",d)}},[]),e?u.jsx(Lne,{tip:e}):null}function Lne({tip:e}){const t=j.useRef(null),[n,a]=j.useState(e.x);return j.useLayoutEffect(()=>{const s=(t.current?.offsetWidth??0)/2;a(Math.max(12+s,Math.min(e.x,window.innerWidth-12-s)))},[e]),$a.createPortal(u.jsx("div",{ref:t,className:"tdag-tooltip",style:{left:n,top:e.above?e.top-8:e.bottom+8,transform:`translate(-50%, ${e.above?"-100%":"0"})`},children:e.text}),document.body)}function jne({role:e,onCommit:t,onRemove:n}){const a=Gt(),[r,s]=j.useState(e.name),[l,c]=j.useState(e.prompt),d=()=>t(e,r.trim(),l.trim());return u.jsxs("div",{className:"border border-line rounded-xl px-3 py-2.5 space-y-1.5 bg-surface",children:[u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx("input",{value:r,onChange:h=>s(h.target.value),onBlur:d,placeholder:a("roles.namePlaceholder"),className:"flex-1 text-sm font-medium text-ink bg-transparent focus:outline-none placeholder-ink-faint"}),e.builtin&&u.jsx("span",{className:"text-2xs text-ink-faint bg-wash px-1.5 py-0.5 rounded-full shrink-0",children:a("roles.builtin")}),u.jsx("button",{onClick:()=>n(e),title:a("common.delete"),className:"text-ink-faint hover:text-red-500 w-6 h-6 rounded-full flex items-center justify-center transition-colors shrink-0",children:u.jsx(Ua,{size:13,strokeWidth:1.75})})]}),u.jsx("textarea",{value:l,onChange:h=>c(h.target.value),onBlur:d,placeholder:a("roles.promptPlaceholder"),rows:2,className:"w-full text-xs text-ink-muted bg-transparent focus:outline-none resize-y leading-relaxed placeholder-ink-faint"})]})}function Pne(){const e=ye(m=>m.roleManagerOpen),t=ye(m=>m.setRoleManagerOpen),n=ye(m=>m.roleLib),a=ye(m=>m.setRoleLib),r=Fa(m=>m.lang),s=Gt();if(!e)return null;const l=Dm(r,n),c=(m,p,x)=>{p===m.name&&x===m.prompt||!p&&!x||(m.builtin?a({hidden:[...n.hidden,m.id],custom:[...n.custom,{id:In(),name:p||m.name,prompt:x||m.prompt}]}):a({...n,custom:n.custom.map(b=>b.id===m.id?{...b,name:p,prompt:x}:b)}))},d=m=>{m.builtin?a({...n,hidden:[...n.hidden,m.id]}):a({...n,custom:n.custom.filter(p=>p.id!==m.id)})},h=()=>a({...n,custom:[...n.custom,{id:In(),name:"",prompt:""}]});return $a.createPortal(u.jsx("div",{className:"fixed inset-0 z-[60] bg-ink/30 backdrop-blur-sm flex items-center justify-center p-6",onClick:()=>t(!1),children:u.jsxs("div",{className:"bg-card rounded-2xl shadow-2xl border border-line w-[560px] max-h-[80vh] flex flex-col",onClick:m=>m.stopPropagation(),children:[u.jsxs("div",{className:"flex items-center gap-2 px-5 py-3 border-b border-line shrink-0",children:[u.jsx("span",{className:"text-sm font-semibold text-ink",children:s("roles.managerTitle")}),u.jsx("span",{className:"text-2xs text-ink-faint flex-1",children:s("roles.hint")}),u.jsx("button",{onClick:()=>t(!1),className:"text-ink-faint hover:text-ink w-7 h-7 rounded-lg hover:bg-wash flex items-center justify-center transition-colors shrink-0",children:u.jsx(bn,{size:15,strokeWidth:1.75})})]}),u.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-5 py-3 space-y-2",children:[l.map(m=>u.jsx(jne,{role:m,onCommit:c,onRemove:d},m.id)),l.length===0&&u.jsx("p",{className:"text-xs text-ink-faint italic py-2",children:s("roles.empty")})]}),u.jsxs("div",{className:"flex items-center gap-2 px-5 py-3 border-t border-line shrink-0",children:[u.jsxs("button",{onClick:h,className:"flex items-center gap-1.5 text-xs text-accent hover:bg-accent/10 px-3 py-1.5 rounded-lg transition-colors",children:[u.jsx(lm,{size:14,strokeWidth:1.75})," ",s("roles.add")]}),u.jsx("div",{className:"flex-1"}),n.hidden.length>0&&u.jsx("button",{onClick:()=>a({...n,hidden:[]}),className:"text-2xs text-ink-faint hover:text-ink-muted underline decoration-dotted transition-colors",children:s("roles.restore")})]})]})}),document.body)}function zne(){const e=Gt(),t=ye(w=>w.memoryManagerOpen),n=ye(w=>w.setMemoryManagerOpen),a=ye(w=>w.memories),r=ye(w=>w.setMemories),s=ye(w=>w.memoryEnabled),l=ye(w=>w.setMemoryEnabled),[c,d]=j.useState(!1),[h,m]=j.useState("");if(!t)return null;const p=w=>e(w==="auto"?"memory.kindAuto":w==="imported"?"memory.kindImported":"memory.kindManual"),x=w=>w==="preference"?{label:e("memory.catPreference"),cls:"bg-sky-500/10 text-sky-600"}:w==="identity"?{label:e("memory.catIdentity"),cls:"bg-violet-500/10 text-violet-600"}:w==="project"?{label:e("memory.catProject"),cls:"bg-amber-500/10 text-amber-600"}:null,b=()=>r([...a,{id:In(),text:"",kind:"manual",at:new Date().toISOString()}]),y=(w,_)=>{const A=_.trim();if(!A){r(a.filter(C=>C.id!==w));return}r(a.map(C=>C.id===w?{...C,text:A}:C))},E=()=>{const w=h.split(`
|
|
720
|
+
*(我是一个导读节点:在阅读器里点「生成导读」长出来的。阅读器顶部的「导读」标签页就是我的阅读视图,(p.N) 在那里是可点击的跳页按钮。把我连向下游,后续问题就以这份压缩为上下文,而不是整份原文。)*`,x:2980,y:690,extra:{digestOf:"ex-att-brief",summaries:["导读完成:存≠学,处理才算数;要点均带页码"]}},{id:"frame-chain",q:"① 对话:主链 · 分支 · 评审",a:"",x:0,y:240,w:1290,h:1460,extra:{stepKind:"frame",frameColor:"violet"}},{id:"frame-material",q:"② 材料与引用",a:"",x:1400,y:0,w:640,h:1560,extra:{stepKind:"frame",frameColor:"amber"}},{id:"frame-prune",q:"③ ⚖️ 修剪上下文",a:"",x:2160,y:0,w:640,h:1240,extra:{stepKind:"frame",frameColor:"sky"}},{id:"frame-read",q:"④ 阅读闭环:文献长成对话",a:"",x:2920,y:0,w:1270,h:1240,extra:{stepKind:"frame",frameColor:"green"}}]}};function wne(e){const{nodes:t}=VE[e]??VE.en,n=t.map(({id:c,q:d,a:h,x:m,y:p,w:x,h:b,extra:y})=>({id:`ex-${c}`,type:"thought",position:{x:m,y:p},...x?{width:x}:{},...b?{height:b}:{},...y?.stepKind==="frame"?{zIndex:-1}:{},dragHandle:".drag-handle",data:{question:d,response:h,responses:h?[h]:[],responseIndex:h?0:-1,isCollapsed:!1,isEditing:!1,isEditingResponse:!1,isLoading:!1,tokenCount:Math.ceil((d+h).length/4),highlights:[],highlightMode:"tag",attachments:[],excludedAttachmentIds:[],includedAttachmentIds:[],roleMode:"inherit",isRoot:!1,isBranch:!1,...y}})),a=(c,d,h={})=>({id:`ex-e-${c}-${d}`,source:`ex-${c}`,target:`ex-${d}`,type:"smoothstep",sourceHandle:h.branch||h.ref?"branch":"continue",targetHandle:h.branch||h.watch||h.ref?"left":"top",animated:!!(h.branch||h.watch||h.ref),style:h.watch?{stroke:nt.watch,strokeWidth:2,strokeDasharray:"4 4"}:h.branch?{stroke:nt.warm,strokeWidth:2}:h.ref?{stroke:nt.accent,strokeWidth:2,strokeDasharray:"8 4"}:{stroke:nt.accent,strokeWidth:2},markerEnd:{type:"arrowclosed",color:h.watch?nt.watch:h.branch?nt.warm:nt.accent,width:18,height:18},data:h.watch?{isCrossLink:!0,isWatch:!0}:h.ref?{isCrossLink:!0}:h.branch?{isBranchFromSelection:!0}:{}}),r=[a("root","chain1"),a("root","ruleout",{branch:!0}),a("chain1","branch1",{branch:!0}),a("branch1","evaluator",{watch:!0}),a("note","ask"),a("branch1","ask",{ref:!0}),a("ask","stale-demo"),a("noise","cmp-full"),a("stale-demo","cmp-full",{branch:!0}),a("stale-demo","cmp-pruned",{branch:!0}),a("brief","brief-ask",{branch:!0}),a("brief","brief-digest")],s=[0,45,30,70,40,55,900,35,50,45,60,40,980,30,55,40,65,45,50,35];let l=Date.now()-72*3600*1e3;return n.forEach((c,d)=>{l+=(s[d%s.length]||45)*60*1e3,c.data.createdAt=new Date(l).toISOString()}),{nodes:n,edges:r}}function $f(e){const t=ye.getState();if(!t.panelOpen)return 0;const n=oe.getState().nodes.find(a=>a.id===e)?.data?.stepKind;return n==="note"||n==="file"||n==="link"||n==="frame"?0:t.panelWidth+ad+12}async function Ene(){const{nodes:e}=oe.getState();if(!e.some(n=>n.data.attachments?.some(a=>a.type==="application/pdf"&&a.content&&!a.contentInVault)))return;const t=await Db(e);oe.getState().nodes===e&&oe.setState({nodes:t})}async function kne(){try{const e=new Set;for(const n of oe.getState().nodes)for(const a of n.data.attachments??[])e.add(a.id);for(const n of Nn.getState().projects){const a=await xl(ni(n.id)).catch(()=>null),s=(typeof a=="string"?JSON.parse(a):a)?.state?.nodes??[];for(const l of s)for(const c of l.data.attachments??[])e.add(c.id)}const t=await FB(e);t>0&&console.info(`[thoughtdag] vault GC: swept ${t} orphaned payload(s)`)}catch(e){console.warn("[thoughtdag] vault GC failed:",e)}}const rb="thoughtdag.orVerifier",WE="https://openrouter.ai/auth",Tne="https://openrouter.ai/api/v1/auth/keys",MN=e=>btoa(String.fromCharCode(...e)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");async function Sne(e){const t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return MN(new Uint8Array(t))}async function IN(){const e=MN(crypto.getRandomValues(new Uint8Array(48))),t=await Sne(e);if(window.desktop){const a=`${location.origin}/oauth/openrouter`;window.open(`${WE}?callback_url=${encodeURIComponent(a)}&code_challenge=${t}&code_challenge_method=S256`),Ke("info",Ie("provider.oauthBrowserWait"));const r=await Ane();if(!r){Ke("error",qe(Ie("provider.oauthFailed"),{error:Ie("provider.oauthTimeout")}));return}const s=await ON(r,e);s.status==="minted"?(Ke("success",Ie("provider.oauthMinted")),DN(s.key)):Ke("error",qe(Ie("provider.oauthFailed"),{error:s.error}));return}sessionStorage.setItem(rb,e);const n=`${location.origin}${location.pathname}`;location.href=`${WE}?callback_url=${encodeURIComponent(n)}&code_challenge=${t}&code_challenge_method=S256`}async function Ane(){for(let e=0;e<100;e++){await new Promise(t=>setTimeout(t,3e3));try{const t=await fetch(`${Rs}/oauth/openrouter/code`),{code:n}=await t.json();if(n)return n}catch{}}return null}function DN(e){ye.getState().setOauthMintedKey(e),ye.getState().setApiKeyModalOpen(!0)}async function Nne(){const e=new URLSearchParams(location.search),t=e.get("code"),n=sessionStorage.getItem(rb);if(!t||!n)return null;sessionStorage.removeItem(rb),e.delete("code");const a=e.toString();return history.replaceState(null,"",`${location.pathname}${a?`?${a}`:""}${location.hash}`),ON(t,n)}async function ON(e,t){try{const n=await fetch(Tne,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e,code_verifier:t,code_challenge_method:"S256"})});if(!n.ok)throw new Error(`HTTP ${n.status}`);const{key:a}=await n.json();if(!a)throw new Error("no key in exchange response");return{status:"minted",key:a}}catch(n){return{status:"failed",error:n instanceof Error?n.message:String(n)}}}function Cne(){const e=window.desktop;e?.onUpdateEvent&&e.onUpdateEvent(t=>{switch(t.kind){case"available":Ke("info",qe(Ie("update.found"),{v:t.version??""}),0,{label:Ie("update.downloadAction"),run:()=>{e.downloadUpdate?.()}});break;case"downloading":Ke("info",qe(Ie("update.downloading"),{p:String(t.percent??0)}));break;case"ready":Ke("success",qe(Ie("update.ready"),{v:t.version??""}),0,{label:Ie("update.restartAction"),run:()=>{e.installUpdate?.()}});break;case"latest":Ke("success",qe(Ie("update.latest"),{v:t.version??""}));break;case"check-failed":Ke("error",Ie("update.checkFailed"));break;case"download-failed":Ke("error",Ie("update.downloadFailed"));break;case"dev":Ke("info","Dev build: no update channel.");break}})}function _ne(){const e=ye(a=>a.confirmRequest),t=ye(a=>a.resolveConfirm),n=Gt();return j.useEffect(()=>{if(!e)return;const a=r=>{r.stopPropagation(),r.key==="Escape"&&t(!1),r.key==="Enter"&&t(!0)};return window.addEventListener("keydown",a,!0),()=>window.removeEventListener("keydown",a,!0)},[e,t]),e?u.jsx("div",{className:"fixed inset-0 z-[100] bg-black/25 flex items-center justify-center animate-fade-in",onClick:()=>t(!1),children:u.jsxs("div",{className:"bg-card border border-line rounded-xl shadow-xl w-[380px] p-5",onClick:a=>a.stopPropagation(),children:[e.title&&u.jsx("h3",{className:"text-sm font-semibold text-ink mb-1.5",children:e.title}),u.jsx("p",{className:"text-sm text-ink-muted leading-relaxed whitespace-pre-line [overflow-wrap:anywhere]",children:e.message}),u.jsxs("div",{className:"flex justify-end gap-2 mt-5",children:[u.jsx("button",{onClick:()=>t(!1),className:"text-xs text-ink-muted hover:text-ink px-4 py-2 rounded-lg hover:bg-wash transition-colors",children:n("common.cancel")}),u.jsx("button",{onClick:()=>t(!0),autoFocus:!0,className:`text-xs text-white px-4 py-2 rounded-lg transition-colors ${e.danger?"bg-red-500 hover:bg-red-600":"bg-accent hover:bg-accent-strong"}`,children:e.confirmLabel??n("common.confirm")})]})]})}):null}const Mne={error:"border-red-200 bg-red-50 text-red-700",success:"border-green-200 bg-green-50 text-green-700",info:"border-line bg-card text-ink-muted"},Ine={error:qj,success:Wj,info:PP};function Dne(){const e=ye(n=>n.toasts),t=ye(n=>n.dismissToast);return e.length===0?null:u.jsx("div",{className:"fixed bottom-4 right-4 z-[90] flex flex-col gap-2 max-w-[380px]",children:e.map(n=>{const a=Ine[n.kind];return u.jsxs("div",{className:`flex items-start gap-2.5 border rounded-xl shadow-lg px-4 py-3 animate-fade-in ${Mne[n.kind]}`,children:[u.jsx(a,{size:16,strokeWidth:1.75,className:"shrink-0 mt-0.5"}),u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsx("p",{className:"text-xs leading-relaxed break-words",children:n.message}),n.action&&u.jsx("button",{onClick:()=>{n.action.run(),t(n.id)},className:"mt-2 text-2xs font-medium bg-accent/10 text-accent hover:bg-accent/20 px-2.5 py-1 rounded-lg transition-colors",children:n.action.label})]}),u.jsx("button",{onClick:()=>t(n.id),className:"shrink-0 opacity-50 hover:opacity-100 transition-opacity",children:u.jsx(bn,{size:14,strokeWidth:1.75})})]},n.id)})})}const One=350;function Rne(){const[e,t]=j.useState(null);return j.useEffect(()=>{let n=0,a=null;const r=()=>{a?.dataset.tipStash!==void 0&&(a.setAttribute("title",a.dataset.tipStash),delete a.dataset.tipStash)},s=()=>{window.clearTimeout(n),r(),a=null,t(null)},l=h=>{const m=h.target?.closest?.("[title], [data-tip-stash]");if(!m||m===a)return;s();const p=m.getAttribute("title")??m.dataset.tipStash??"";p.trim()&&(a=m,m.dataset.tipStash=p,m.removeAttribute("title"),n=window.setTimeout(()=>{if(a!==m||!m.isConnected)return;m.removeAttribute("title");const x=m.getBoundingClientRect(),b=x.bottom>window.innerHeight-96;t({text:p,x:Math.max(12,Math.min(x.left+x.width/2,window.innerWidth-12)),top:x.top,bottom:x.bottom,above:b})},One))},c=h=>{if(!a)return;const m=h.relatedTarget;m instanceof Node&&a.contains(m)||h.target instanceof Node&&(a===h.target||a.contains(h.target))&&s()},d=()=>s();return document.addEventListener("mouseover",l),document.addEventListener("mouseout",c),document.addEventListener("mousedown",d,!0),document.addEventListener("scroll",d,!0),window.addEventListener("blur",d),()=>{s(),document.removeEventListener("mouseover",l),document.removeEventListener("mouseout",c),document.removeEventListener("mousedown",d,!0),document.removeEventListener("scroll",d,!0),window.removeEventListener("blur",d)}},[]),e?u.jsx(Lne,{tip:e}):null}function Lne({tip:e}){const t=j.useRef(null);return j.useLayoutEffect(()=>{const n=t.current;if(!n)return;const a=n.offsetWidth/2;n.style.left=`${Math.max(12+a,Math.min(e.x,window.innerWidth-12-a))}px`},[e]),$a.createPortal(u.jsx("div",{ref:t,className:"tdag-tooltip",style:{left:e.x,top:e.above?e.top-8:e.bottom+8,transform:`translate(-50%, ${e.above?"-100%":"0"})`},children:e.text}),document.body)}function jne({role:e,onCommit:t,onRemove:n}){const a=Gt(),[r,s]=j.useState(e.name),[l,c]=j.useState(e.prompt),d=()=>t(e,r.trim(),l.trim());return u.jsxs("div",{className:"border border-line rounded-xl px-3 py-2.5 space-y-1.5 bg-surface",children:[u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx("input",{value:r,onChange:h=>s(h.target.value),onBlur:d,placeholder:a("roles.namePlaceholder"),className:"flex-1 text-sm font-medium text-ink bg-transparent focus:outline-none placeholder-ink-faint"}),e.builtin&&u.jsx("span",{className:"text-2xs text-ink-faint bg-wash px-1.5 py-0.5 rounded-full shrink-0",children:a("roles.builtin")}),u.jsx("button",{onClick:()=>n(e),title:a("common.delete"),className:"text-ink-faint hover:text-red-500 w-6 h-6 rounded-full flex items-center justify-center transition-colors shrink-0",children:u.jsx(Ua,{size:13,strokeWidth:1.75})})]}),u.jsx("textarea",{value:l,onChange:h=>c(h.target.value),onBlur:d,placeholder:a("roles.promptPlaceholder"),rows:2,className:"w-full text-xs text-ink-muted bg-transparent focus:outline-none resize-y leading-relaxed placeholder-ink-faint"})]})}function Pne(){const e=ye(m=>m.roleManagerOpen),t=ye(m=>m.setRoleManagerOpen),n=ye(m=>m.roleLib),a=ye(m=>m.setRoleLib),r=Fa(m=>m.lang),s=Gt();if(!e)return null;const l=Dm(r,n),c=(m,p,x)=>{p===m.name&&x===m.prompt||!p&&!x||(m.builtin?a({hidden:[...n.hidden,m.id],custom:[...n.custom,{id:In(),name:p||m.name,prompt:x||m.prompt}]}):a({...n,custom:n.custom.map(b=>b.id===m.id?{...b,name:p,prompt:x}:b)}))},d=m=>{m.builtin?a({...n,hidden:[...n.hidden,m.id]}):a({...n,custom:n.custom.filter(p=>p.id!==m.id)})},h=()=>a({...n,custom:[...n.custom,{id:In(),name:"",prompt:""}]});return $a.createPortal(u.jsx("div",{className:"fixed inset-0 z-[60] bg-ink/30 backdrop-blur-sm flex items-center justify-center p-6",onClick:()=>t(!1),children:u.jsxs("div",{className:"bg-card rounded-2xl shadow-2xl border border-line w-[560px] max-h-[80vh] flex flex-col",onClick:m=>m.stopPropagation(),children:[u.jsxs("div",{className:"flex items-center gap-2 px-5 py-3 border-b border-line shrink-0",children:[u.jsx("span",{className:"text-sm font-semibold text-ink",children:s("roles.managerTitle")}),u.jsx("span",{className:"text-2xs text-ink-faint flex-1",children:s("roles.hint")}),u.jsx("button",{onClick:()=>t(!1),className:"text-ink-faint hover:text-ink w-7 h-7 rounded-lg hover:bg-wash flex items-center justify-center transition-colors shrink-0",children:u.jsx(bn,{size:15,strokeWidth:1.75})})]}),u.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-5 py-3 space-y-2",children:[l.map(m=>u.jsx(jne,{role:m,onCommit:c,onRemove:d},m.id)),l.length===0&&u.jsx("p",{className:"text-xs text-ink-faint italic py-2",children:s("roles.empty")})]}),u.jsxs("div",{className:"flex items-center gap-2 px-5 py-3 border-t border-line shrink-0",children:[u.jsxs("button",{onClick:h,className:"flex items-center gap-1.5 text-xs text-accent hover:bg-accent/10 px-3 py-1.5 rounded-lg transition-colors",children:[u.jsx(lm,{size:14,strokeWidth:1.75})," ",s("roles.add")]}),u.jsx("div",{className:"flex-1"}),n.hidden.length>0&&u.jsx("button",{onClick:()=>a({...n,hidden:[]}),className:"text-2xs text-ink-faint hover:text-ink-muted underline decoration-dotted transition-colors",children:s("roles.restore")})]})]})}),document.body)}function zne(){const e=Gt(),t=ye(w=>w.memoryManagerOpen),n=ye(w=>w.setMemoryManagerOpen),a=ye(w=>w.memories),r=ye(w=>w.setMemories),s=ye(w=>w.memoryEnabled),l=ye(w=>w.setMemoryEnabled),[c,d]=j.useState(!1),[h,m]=j.useState("");if(!t)return null;const p=w=>e(w==="auto"?"memory.kindAuto":w==="imported"?"memory.kindImported":"memory.kindManual"),x=w=>w==="preference"?{label:e("memory.catPreference"),cls:"bg-sky-500/10 text-sky-600"}:w==="identity"?{label:e("memory.catIdentity"),cls:"bg-violet-500/10 text-violet-600"}:w==="project"?{label:e("memory.catProject"),cls:"bg-amber-500/10 text-amber-600"}:null,b=()=>r([...a,{id:In(),text:"",kind:"manual",at:new Date().toISOString()}]),y=(w,_)=>{const A=_.trim();if(!A){r(a.filter(C=>C.id!==w));return}r(a.map(C=>C.id===w?{...C,text:A}:C))},E=()=>{const w=h.split(`
|
|
721
721
|
`).map(A=>A.replace(/^[-•\s]+/,"").trim()).filter(A=>A.length>1);if(w.length===0){d(!1);return}const _=new Date().toISOString();r([...a,...w.map(A=>({id:In(),text:A,kind:"imported",at:_}))]),m(""),d(!1)},T=()=>Zd("thoughtdag-memory.json",JSON.stringify(a,null,2),"application/json");return $a.createPortal(u.jsx("div",{className:"fixed inset-0 z-[60] bg-ink/30 backdrop-blur-sm flex items-center justify-center p-6",onClick:()=>n(!1),children:u.jsxs("div",{className:"bg-card rounded-2xl shadow-2xl border border-line w-[600px] max-h-[80vh] flex flex-col",onClick:w=>w.stopPropagation(),children:[u.jsxs("div",{className:"flex items-center gap-2 px-5 py-3 border-b border-line shrink-0",children:[u.jsx("span",{className:"text-sm font-semibold text-ink",children:e("memory.managerTitle")}),u.jsx("span",{className:"text-2xs text-ink-faint flex-1",children:qe(e("memory.hint"),{n:a.length})}),u.jsx("button",{onClick:()=>l(!s),title:e("caps.memoryTitle"),className:`text-2xs px-2.5 py-1 rounded-full transition-colors shrink-0 ${s?"bg-accent/10 text-accent":"bg-wash text-ink-faint"}`,children:e(s?"caps.on":"caps.off")}),u.jsx("button",{onClick:()=>n(!1),className:"text-ink-faint hover:text-ink w-7 h-7 rounded-lg hover:bg-wash flex items-center justify-center transition-colors shrink-0",children:u.jsx(bn,{size:15,strokeWidth:1.75})})]}),u.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-5 py-3 space-y-2",children:[a.length===0&&!c&&u.jsx("p",{className:"text-xs text-ink-faint italic py-2",children:e("memory.empty")}),a.map(w=>u.jsxs("div",{className:"border border-line rounded-xl px-3 py-2 bg-surface group",children:[u.jsxs("div",{className:"flex items-start gap-2",children:[u.jsx("textarea",{defaultValue:w.text,onBlur:_=>y(w.id,_.target.value),rows:1,className:"flex-1 text-sm text-ink bg-transparent focus:outline-none resize-y leading-relaxed"}),u.jsx("button",{onClick:()=>r(a.filter(_=>_.id!==w.id)),title:e("common.delete"),className:"text-ink-faint hover:text-red-500 w-6 h-6 rounded-full flex items-center justify-center transition-colors shrink-0 opacity-0 group-hover:opacity-100",children:u.jsx(Ua,{size:13,strokeWidth:1.75})})]}),u.jsxs("p",{className:"text-2xs text-ink-faint mt-1 font-mono flex items-center gap-1.5 flex-wrap",children:[(()=>{const _=x(w.category);return _?u.jsx("span",{className:`px-1.5 py-px rounded-full font-sans ${_.cls}`,children:_.label}):null})(),u.jsxs("span",{children:[p(w.kind),w.project?` · ${w.project}`:""," · ",w.at.slice(0,10)]})]})]},w.id)),c&&u.jsxs("div",{className:"border border-accent/40 rounded-xl px-3 py-2 bg-surface space-y-2",children:[u.jsx("textarea",{value:h,onChange:w=>m(w.target.value),placeholder:e("memory.importPlaceholder"),rows:5,autoFocus:!0,className:"w-full text-xs text-ink bg-transparent focus:outline-none resize-y leading-relaxed placeholder-ink-faint"}),u.jsxs("div",{className:"flex justify-end gap-2",children:[u.jsx("button",{onClick:()=>d(!1),className:"text-xs text-ink-muted hover:text-ink px-3 py-1 rounded-lg hover:bg-wash transition-colors",children:e("common.cancel")}),u.jsx("button",{onClick:E,className:"text-xs bg-accent text-white px-3 py-1 rounded-lg",children:e("memory.importConfirm")})]})]})]}),u.jsxs("div",{className:"flex items-center gap-2 px-5 py-3 border-t border-line shrink-0",children:[u.jsxs("button",{onClick:b,className:"flex items-center gap-1.5 text-xs text-accent hover:bg-accent/10 px-3 py-1.5 rounded-lg transition-colors",children:[u.jsx(lm,{size:14,strokeWidth:1.75})," ",e("memory.add")]}),u.jsx("button",{onClick:()=>d(!0),className:"text-xs text-ink-muted hover:text-ink hover:bg-wash px-3 py-1.5 rounded-lg transition-colors",children:e("memory.import")}),u.jsx("div",{className:"flex-1"}),a.length>0&&u.jsxs("button",{onClick:T,className:"flex items-center gap-1.5 text-2xs text-ink-faint hover:text-ink-muted transition-colors",title:e("memory.exportTitle"),children:[u.jsx(Ed,{size:12,strokeWidth:1.75})," ",e("memory.export")]})]})]})}),document.body)}function Bne(){const e=Gt(),t=ye(re=>re.apiKeyModalOpen),n=ye(re=>re.setApiKeyModalOpen),a=El(),[r,s]=j.useState(()=>ai());j.useEffect(()=>{t&&s(ai())},[t]);const[l,c]=j.useState(!1),d=ye(re=>re.apiKeyPresetHint);j.useEffect(()=>{if(!t||!d)return;const re=_i.find(be=>be.id===d);re&&(c(!0),w(re),B(null),Y(new Map)),ye.getState().setApiKeyPresetHint(null)},[t,d]);const h=ye(re=>re.oauthMintedKey);j.useEffect(()=>{if(!t||!h)return;ye.getState().setOauthMintedKey(null);const re=_i.find(be=>be.id==="openrouter");c(!0),w(re),C(h),ae(re.baseURL,h,void 0,!0)},[t,h]);const[m,p]=j.useState(!1),[x,b]=j.useState(""),y=Fa(re=>re.lang),E=_i.filter(re=>!re.region||re.region===y),[T,w]=j.useState(E[0]),_=Rs==="",[A,C]=j.useState(""),[O,D]=j.useState(""),[M,N]=j.useState(""),[R,B]=j.useState(null),[H,Y]=j.useState(new Map),[Z,q]=j.useState(""),[K,U]=j.useState("time"),[G,ne]=j.useState(new Set),X=j.useMemo(()=>(a?.models??[]).filter(re=>!r.some(be=>be.models.some(Le=>Le.id===re.id))),[a,r]),P=(a?.models??[]).filter(re=>re.vision).length;if(!t)return null;const F=()=>{c(!1),B(null),Y(new Map),C(""),D(""),N(""),q(""),b("")},J=async re=>{p(!0),b("");try{const be=await Kd(re);return dm(re),s(re),hm(be),!0}catch(be){return b(be instanceof Error?be.message:String(be)),!1}finally{p(!1)}},W=async re=>{const be=_i.find(Le=>Le.baseURL===re.baseURL&&(!Le.region||Le.region===y))??_i.find(Le=>Le.baseURL===re.baseURL);w(be??_i.find(Le=>Le.id==="custom")),be||(D(re.baseURL),N(re.name)),C(re.apiKey),c(!0),await ae(re.baseURL,re.apiKey,re.models)},ae=async(re,be,Le,Oe)=>{p(!0),b(""),B(null);try{const je=re??(T.id==="custom"?O.trim():T.baseURL),ze=_i.find(ht=>ht.baseURL===je),rt=ze?.fixedModels,ot=rt?rt.map(ht=>({id:ht})):await v7(je,(be??A).trim());if(ot.length===0)throw new Error(e("provider.probeEmpty"));if(!rt)for(const ht of ze?.recommend??[])ot.some(at=>at.id===ht)||ot.push({id:ht,..._B(ht)?{vision:!0}:{}});for(const ht of Le??[])ot.some(at=>at.id===ht.id)||ot.push({...ht});const Xe=new Map,kt=Oe?ot.filter(ht=>new Set(T.recommend??[]).has(ht.id)):[];if(Le){const ht=new Set(ot.map(at=>at.id));for(const at of Le)ht.has(at.id)&&Xe.set(at.id,ot.find(wt=>wt.id===at.id)?.vision??!!at.vision)}else if(kt.length>0)kt.forEach(ht=>Xe.set(ht.id,!!ht.vision));else if(ot.some(ht=>ht.created))[...ot].sort((ht,at)=>(at.created??0)-(ht.created??0)).slice(0,8).forEach(ht=>Xe.set(ht.id,!!ht.vision));else{const ht=new Set(T.recommend??[]);for(const at of ot)(ht.size>0?ht.has(at.id):ot.length<=12)&&Xe.set(at.id,!!at.vision)}Y(Xe),ne(new Set(Xe.keys())),B(ot)}catch(je){b(je instanceof Error?je.message:String(je))}finally{p(!1)}},ve=async()=>{if(T.id!=="custom"&&!T.noKey&&!A.trim()){b(e("provider.keyMissing"));return}const re=T.id==="custom"?O.trim():T.baseURL,be=T.id==="custom"?M.trim()||e("provider.customName"):T.name,Le=new Map((R??[]).map(ze=>[ze.id,ze])),Oe=[...H.entries()].map(([ze,rt])=>{const ot=Le.get(ze)?.contextLength;return{id:ze,...rt?{vision:rt}:{},...ot?{contextLength:ot}:{}}});if(!re||Oe.length===0)return;const je=[...r.filter(ze=>ze.baseURL!==re),{preset:T.id,name:be,baseURL:re,apiKey:A.trim(),models:Oe}];await J(je)&&(Ke("success",qe(e("provider.added"),{n:Oe.length,name:be})),F())},me=async re=>{await J(r.filter(be=>be.baseURL!==re))},ke=(R?.filter(re=>!Z||re.id.toLowerCase().includes(Z.toLowerCase()))??[]).sort((re,be)=>Number(G.has(be.id))-Number(G.has(re.id))||(K==="time"?(be.created??0)-(re.created??0):re.id.localeCompare(be.id)));return $a.createPortal(u.jsx("div",{className:"fixed inset-0 z-[60] bg-ink/30 backdrop-blur-sm flex items-center justify-center p-6",onClick:()=>{n(!1),F()},children:u.jsxs("div",{className:"bg-card rounded-2xl shadow-2xl border border-line w-[560px] max-h-[86vh] flex flex-col",onClick:re=>re.stopPropagation(),children:[u.jsxs("div",{className:"flex items-center gap-2 px-5 py-3 border-b border-line shrink-0",children:[u.jsx(Sd,{size:15,strokeWidth:1.75,className:"text-accent shrink-0"}),u.jsx("span",{className:"text-sm font-semibold text-ink flex-1",children:e("provider.title")}),u.jsx("button",{onClick:()=>{n(!1),F()},className:"text-ink-faint hover:text-ink w-7 h-7 rounded-lg hover:bg-wash flex items-center justify-center transition-colors shrink-0",children:u.jsx(bn,{size:15,strokeWidth:1.75})})]}),u.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-5 py-4 space-y-3",children:[!l&&u.jsxs(u.Fragment,{children:[(a?.models.length??0)===0&&u.jsx("p",{className:"text-xs text-ink-muted leading-relaxed",children:e("provider.introEmpty")}),X.length>0&&u.jsx("div",{className:"border border-line rounded-xl px-3 py-2.5 bg-wash/50 text-xs text-ink-muted",children:qe(e("provider.serverRow"),{n:X.length})}),r.map(re=>u.jsxs("div",{className:"border border-line rounded-xl px-3 py-2.5 bg-surface flex items-start gap-2",children:[u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsx("div",{className:"text-sm text-ink font-medium",children:re.name}),u.jsx("div",{className:"text-2xs text-ink-faint mt-0.5 font-mono truncate",children:re.baseURL}),u.jsxs("div",{className:"text-2xs text-ink-muted mt-1",children:[qe(e("provider.modelCount"),{n:re.models.length}),re.models.some(be=>be.vision)&&u.jsxs("span",{children:[" · 📷 ",re.models.filter(be=>be.vision).length]})]})]}),u.jsx("button",{onClick:()=>{W(re)},disabled:m,title:e("provider.refreshTitle"),className:"text-ink-faint hover:text-accent w-6 h-6 rounded-full flex items-center justify-center transition-colors shrink-0","data-provider-refresh":!0,children:u.jsx(Oc,{size:13,strokeWidth:1.75})}),u.jsx("button",{onClick:()=>{me(re.baseURL)},disabled:m,title:e("common.delete"),className:"text-ink-faint hover:text-red-500 w-6 h-6 rounded-full flex items-center justify-center transition-colors shrink-0",children:u.jsx(Ua,{size:13,strokeWidth:1.75})})]},re.baseURL)),(a?.models.length??0)>0&&u.jsxs("p",{className:"text-2xs text-ink-faint leading-relaxed",children:[qe(e("provider.capabilityLine"),{n:a.models.length,v:P}),!a?.capabilities?.webSearch&&` ${e("provider.noSearchNote")}`]}),u.jsxs("button",{onClick:()=>c(!0),className:"flex items-center gap-1.5 text-xs text-accent hover:bg-accent/10 px-3 py-1.5 rounded-lg transition-colors","data-provider-add":!0,children:[u.jsx(lm,{size:14,strokeWidth:1.75})," ",e("provider.add")]})]}),l&&u.jsxs(u.Fragment,{children:[u.jsxs("div",{children:[u.jsx("label",{className:"text-2xs font-medium text-ink-muted block mb-1.5",children:e("provider.pickSource")}),u.jsx("div",{className:"flex flex-wrap gap-1.5",children:E.map(re=>u.jsx("button",{onClick:()=>{const be=r.find(Le=>Le.baseURL===re.baseURL);if(be){W(be);return}w(re),B(null),Y(new Map),b("")},className:`text-xs px-3 py-1.5 rounded-full border transition-colors ${T.id===re.id?"border-accent bg-accent/10 text-accent font-medium":"border-line text-ink-muted hover:bg-wash"}`,"data-preset":re.id,children:re.id==="custom"?e("provider.customName"):re.noKey?`${re.name} · ${e("provider.local")}`:re.name},re.id))})]}),T.id==="custom"&&u.jsxs(u.Fragment,{children:[u.jsxs("div",{children:[u.jsx("label",{className:"text-2xs font-medium text-ink-muted block mb-1.5",children:e("provider.baseURL")}),u.jsx("input",{value:O,onChange:re=>D(re.target.value),placeholder:"https://…/v1",className:"w-full bg-wash text-sm text-ink font-mono rounded-lg px-3 py-2 focus:outline-none focus:ring-1 focus:ring-accent/40 placeholder-ink-faint","data-provider-url":!0}),u.jsx("p",{className:"text-2xs text-ink-faint mt-1",children:e("provider.baseURLHint")})]}),u.jsxs("div",{children:[u.jsx("label",{className:"text-2xs font-medium text-ink-muted block mb-1.5",children:e("provider.displayName")}),u.jsx("input",{value:M,onChange:re=>N(re.target.value),placeholder:e("provider.customName"),className:"w-full bg-wash text-sm text-ink rounded-lg px-3 py-2 focus:outline-none focus:ring-1 focus:ring-accent/40 placeholder-ink-faint"})]})]}),T.id==="openrouter"&&!R&&u.jsxs("div",{className:"border border-accent/30 bg-accent/5 rounded-xl px-3 py-2.5 flex items-center gap-2.5","data-provider-oauth-row":!0,children:[u.jsx("p",{className:"text-2xs text-ink-muted leading-relaxed flex-1 min-w-0",children:e("provider.oauthHint")}),u.jsxs("button",{onClick:()=>{IN()},"data-provider-oauth":!0,className:"text-xs bg-accent text-white px-3 py-1.5 rounded-lg shrink-0 flex items-center gap-1.5",children:[u.jsx(Y8,{size:12,strokeWidth:1.75})," ",e("provider.oauthButton")]})]}),!T.noKey&&u.jsxs("div",{children:[u.jsx("label",{className:"text-2xs font-medium text-ink-muted block mb-1.5",children:"API key"}),u.jsx("input",{type:"password",value:A,onChange:re=>C(re.target.value),placeholder:"sk-…",autoFocus:!0,className:"w-full bg-wash text-sm text-ink font-mono rounded-lg px-3 py-2 focus:outline-none focus:ring-1 focus:ring-accent/40 placeholder-ink-faint","data-provider-key":!0}),T.keyUrl&&u.jsxs("p",{className:"text-2xs text-ink-faint mt-1.5",children:[e("provider.keyHint")," ",u.jsx("a",{href:T.keyUrl,target:"_blank",rel:"noreferrer",className:"text-accent hover:underline",children:T.keyUrl.replace("https://","")})]})]}),T.noKey&&u.jsx("p",{className:"text-2xs text-ink-faint leading-relaxed",children:e(T.hintKey??"provider.localHint")}),_,!R&&u.jsxs("button",{onClick:()=>{ae()},disabled:m||_||(T.id==="custom"?!O.trim():!T.noKey&&!A.trim()),className:"text-xs bg-accent text-white px-4 py-1.5 rounded-lg disabled:opacity-40 flex items-center gap-1.5","data-provider-probe":!0,children:[m&&u.jsx(Xn,{size:12,className:"animate-spin"}),e(m?"provider.probing":"provider.probe")]}),R&&u.jsx(u.Fragment,{children:u.jsxs("div",{children:[u.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[u.jsx("label",{className:"text-2xs font-medium text-ink-muted flex-1",children:qe(e("provider.pickModels"),{n:R.length})}),R.length>15&&u.jsx("input",{value:Z,onChange:re=>q(re.target.value),placeholder:e("provider.filter"),className:"bg-wash text-2xs text-ink rounded-md px-2 py-1 w-36 focus:outline-none focus:ring-1 focus:ring-accent/40 placeholder-ink-faint"}),R.some(re=>re.created)&&u.jsx("button",{onClick:()=>U(re=>re==="time"?"name":"time"),className:"text-2xs px-2.5 py-1.5 rounded-lg border border-line text-ink-muted hover:bg-wash transition-colors shrink-0","data-sort-toggle":!0,children:e(K==="time"?"provider.sortTime":"provider.sortName")})]}),u.jsx("div",{className:"border border-line rounded-xl max-h-[220px] overflow-y-auto divide-y divide-line/60","data-provider-models":!0,children:ke.slice(0,200).map(re=>u.jsxs("label",{className:"flex items-center gap-2 px-3 py-1.5 text-xs text-ink hover:bg-wash cursor-pointer",children:[u.jsx("input",{type:"checkbox",checked:H.has(re.id),onChange:be=>{const Le=new Map(H);be.target.checked?Le.set(re.id,!!re.vision):Le.delete(re.id),Y(Le)}}),u.jsx("span",{className:"font-mono flex-1 truncate",children:re.id}),re.contextLength?u.jsx("span",{className:"text-2xs text-ink-faint font-mono shrink-0",title:re.contextLength.toLocaleString(),"data-model-window":!0,children:re.contextLength>=1024*1024?`${Math.round(re.contextLength/(1024*1024))}M`:`${Math.round(re.contextLength/1024)}k`}):null,re.vision!=null?re.vision&&u.jsx("span",{title:e("provider.visionYes"),children:"📷"}):H.has(re.id)&&u.jsx("button",{onClick:be=>{be.preventDefault();const Le=new Map(H);Le.set(re.id,!Le.get(re.id)),Y(Le)},title:e("provider.visionToggle"),className:`flex items-center gap-0.5 text-2xs px-1.5 py-0.5 rounded-full transition-colors ${H.get(re.id)?"bg-accent/10 text-accent":"bg-wash text-ink-faint"}`,children:u.jsx(Lj,{size:11,strokeWidth:1.75})})]},re.id))}),u.jsx("p",{className:"text-2xs text-ink-faint mt-1",children:qe(e("provider.pickedCount"),{n:H.size})})]})}),u.jsx("p",{className:"text-2xs text-ink-faint leading-relaxed bg-wash rounded-lg px-3 py-2",children:e("provider.privacy")}),x&&u.jsx("p",{className:"text-xs text-red-600 leading-relaxed",children:x})]}),!l&&x&&u.jsx("p",{className:"text-xs text-red-600 leading-relaxed",children:x})]}),u.jsxs("div",{className:"flex items-center gap-2 px-5 py-3 border-t border-line shrink-0",children:[u.jsx("div",{className:"flex-1"}),l?u.jsxs(u.Fragment,{children:[u.jsx("button",{onClick:F,className:"text-xs text-ink-muted hover:text-ink px-3 py-1.5 rounded-lg hover:bg-wash transition-colors",children:e("common.cancel")}),u.jsxs("button",{onClick:()=>{ve()},disabled:m||H.size===0,className:"text-xs bg-accent text-white px-4 py-1.5 rounded-lg disabled:opacity-40 flex items-center gap-1.5","data-provider-save":!0,children:[m&&u.jsx(Xn,{size:12,className:"animate-spin"}),e("provider.save")]})]}):u.jsx("button",{onClick:()=>{n(!1),F()},className:"text-xs text-ink-muted hover:text-ink px-3 py-1.5 rounded-lg hover:bg-wash transition-colors",children:e("common.close")})]})]})}),document.body)}function Hne(){const e=ye(N=>N.responseViewerNodeId),t=oe(N=>e?N.nodes.find(R=>R.id===e):void 0),n=Gt(),a=()=>ye.getState().setResponseViewerNodeId(null),r=j.useRef(null),s=j.useRef(null),l=j.useRef(null),[c,d]=j.useState(""),[h,m]=j.useState(null),[p,x]=j.useState(""),[b,y]=j.useState("");j.useEffect(()=>{if(!e)return;const N=R=>{R.key==="Escape"&&(R.stopPropagation(),a())};return window.addEventListener("keydown",N,!0),()=>window.removeEventListener("keydown",N,!0)},[e]);const E=j.useCallback(()=>{const N=window.getSelection();if(N&&N.toString().trim().length>0&&r.current?.contains(N.anchorNode)){const R=N.toString().trim();d(R);const B=N.getRangeAt(0).getBoundingClientRect(),H=s.current?.getBoundingClientRect();H&&m({x:Math.max(70,Math.min(B.left+B.width/2-H.left,H.width-70)),y:Math.max(8,B.top-H.top-46)})}else d(""),m(null)},[]);j.useEffect(()=>{if(!(!e||vt))return document.addEventListener("mouseup",E),()=>document.removeEventListener("mouseup",E)},[e,E]);const[T,w]=j.useState(e);if(T!==e&&(w(e),x(""),y(""),d(""),m(null)),!e||!t)return null;const _=t.data,A=_.reasonings?.[_.responseIndex],C=!vt&&!_.stepKind,O=()=>{c&&(oe.getState().addHighlight(e,{id:In(),text:c}),d(""),m(null),window.getSelection()?.removeAllRanges())},D=()=>{x(c),d(""),m(null),window.getSelection()?.removeAllRanges(),setTimeout(()=>l.current?.focus(),60)},M=()=>{const N=b.trim();if(!N||_.isLoading)return;oe.getState().addQuestion(N,{parentId:e,branchContext:p||void 0});const R=oe.getState().nodes,B=R[R.length-1]?.id;B&&B!==e&&ye.getState().setResponseViewerNodeId(B),y(""),x("")};return $a.createPortal(u.jsx("div",{className:"fixed inset-0 z-[75] bg-ink/25 backdrop-blur-[2px] flex items-center justify-center animate-fade-in",onClick:a,"data-response-viewer":!0,children:u.jsxs("div",{ref:s,className:"relative bg-surface rounded-2xl shadow-2xl border border-line w-[min(920px,92vw)] h-[92vh] flex flex-col overflow-hidden",onClick:N=>N.stopPropagation(),children:[u.jsxs("div",{className:"flex items-start gap-3 px-6 py-4 border-b border-line bg-card shrink-0",children:[u.jsx("div",{className:"flex-1 min-w-0 text-sm font-semibold text-ink leading-snug line-clamp-2",children:_.question}),u.jsx("button",{onClick:a,title:n("panel.close"),className:"w-7 h-7 rounded-lg text-ink-faint hover:bg-wash hover:text-ink flex items-center justify-center transition-colors shrink-0",children:u.jsx(bn,{size:16,strokeWidth:1.75})})]}),u.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-8 py-6",children:u.jsxs("div",{className:"max-w-[760px] mx-auto",ref:r,children:[A&&u.jsx(I2,{text:A}),_.isLoading&&(!_.response||_.restreaming)?_.reasoning?u.jsxs("div",{children:[u.jsxs("div",{className:"text-2xs text-ink-faint mb-1",children:["💭 ",n("node.reasoningLive")]}),u.jsx("div",{className:"text-xs text-ink-faint italic leading-relaxed whitespace-pre-wrap break-words",children:_.reasoning})]}):u.jsxs("div",{className:"flex items-center gap-2 text-sm text-ink-muted py-10 justify-center",children:[u.jsx(Xn,{size:16,strokeWidth:1.75,className:"animate-spin text-accent"})," ",n("common.thinking")]}):u.jsxs("div",{className:"markdown-body text-[15px] text-ink leading-relaxed cursor-text",children:[_.highlights.length>0&&!_.isLoading?u.jsx(Pd,{content:_.response,highlights:new Set(_.highlights.map(N=>N.text))}):u.jsx(Is,{base:_.importSource?.cwd,children:_.response}),_.isLoading&&u.jsx("span",{className:"inline-block w-2 h-4 bg-accent animate-pulse rounded-sm ml-0.5"})]})]})}),C&&c&&h&&u.jsxs("div",{className:"absolute z-10 flex gap-1 bg-card border border-line rounded-xl shadow-lg p-1 animate-fade-in",style:{left:h.x,top:h.y,transform:"translateX(-50%)"},onMouseDown:N=>N.preventDefault(),children:[u.jsxs("button",{onMouseDown:N=>{N.preventDefault(),N.stopPropagation(),D()},className:"bg-accent hover:bg-accent-strong text-white text-xs px-3 py-1.5 rounded-lg transition-all whitespace-nowrap cursor-pointer",children:[u.jsx(Pi,{size:14,strokeWidth:1.75,className:"inline"})," ",n("common.explore")]}),u.jsxs("button",{onMouseDown:N=>{N.preventDefault(),N.stopPropagation(),O()},className:"bg-amber-500 hover:bg-amber-400 text-white text-xs px-3 py-1.5 rounded-lg transition-all whitespace-nowrap cursor-pointer",children:[u.jsx(Nd,{size:14,strokeWidth:1.75,className:"inline"})," ",n("common.highlight")]})]}),C&&u.jsx("div",{className:"border-t border-line bg-card px-6 py-3 shrink-0",children:u.jsxs("div",{className:"max-w-[760px] mx-auto",children:[p&&u.jsxs("div",{className:"mb-2 text-xs pl-3 py-1.5 pr-2 border-l-2 border-warm bg-warm/10 rounded-r text-ink-muted flex items-start gap-1.5",children:[u.jsx(Pi,{size:13,strokeWidth:1.75,className:"text-warm shrink-0 mt-0.5"}),u.jsxs("span",{className:"italic leading-relaxed min-w-0 flex-1",children:["“",p.slice(0,160),p.length>160?"…":"","”"]}),u.jsx("button",{onClick:()=>x(""),className:"text-ink-faint hover:text-ink shrink-0",title:n("common.cancel"),children:u.jsx(bn,{size:13,strokeWidth:1.75})})]}),u.jsxs("div",{className:"flex items-end gap-2",children:[u.jsx("textarea",{ref:l,value:b,onChange:N=>y(N.target.value),onKeyDown:N=>{N.key==="Enter"&&!N.shiftKey&&!Ya(N)&&(N.preventDefault(),M())},placeholder:n(p?"viewerqa.placeholderBranch":"viewerqa.placeholder"),rows:1,className:"flex-1 text-sm bg-wash border border-line rounded-xl px-3.5 py-2.5 resize-none focus:outline-none focus:ring-1 focus:ring-accent leading-relaxed"}),u.jsx("button",{onClick:M,disabled:!b.trim()||_.isLoading,title:n("viewerqa.askTitle"),className:"w-9 h-9 rounded-xl bg-accent text-white flex items-center justify-center hover:bg-accent-strong transition-colors disabled:opacity-30 shrink-0",children:u.jsx(ll,{size:15,strokeWidth:1.75})})]})]})})]})}),document.body)}function Une(){const e=ye(d=>d.shareDialogUrl),t=Gt(),[n,a]=j.useState(!1),[r,s]=j.useState(!0),l=()=>{a(!1),ye.getState().setShareDialogUrl(null)};if(j.useEffect(()=>{if(!e)return;const d=h=>{h.key==="Escape"&&(h.stopPropagation(),l())};return window.addEventListener("keydown",d,!0),()=>window.removeEventListener("keydown",d,!0)},[e]),!e)return null;const c=async()=>{await navigator.clipboard.writeText(e),a(!0),setTimeout(()=>a(!1),1600)};return $a.createPortal(u.jsx("div",{className:"fixed inset-0 z-[80] bg-ink/25 backdrop-blur-[2px] flex items-center justify-center animate-fade-in",onClick:l,"data-share-dialog":!0,children:u.jsxs("div",{className:"bg-surface rounded-2xl shadow-2xl border border-line w-[min(480px,92vw)] p-5",onClick:d=>d.stopPropagation(),children:[u.jsxs("div",{className:"flex items-start justify-between mb-3",children:[u.jsxs("div",{className:"text-sm font-semibold text-ink flex items-center gap-2",children:[u.jsx(kd,{size:15,strokeWidth:1.75,className:"text-accent"})," ",t("viewer.shareDialogTitle")]}),u.jsx("button",{onClick:l,className:"w-7 h-7 rounded-lg text-ink-faint hover:bg-wash hover:text-ink flex items-center justify-center transition-colors",children:u.jsx(bn,{size:15,strokeWidth:1.75})})]}),u.jsx("div",{className:"text-2xs font-semibold text-accent mb-1",children:t("share.directLane")}),u.jsx("p",{className:"text-xs text-ink-muted mb-2",children:t("share.directNote")}),u.jsxs("div",{className:"flex gap-1.5 mb-4",children:[u.jsx("input",{readOnly:!0,value:e,onFocus:d=>d.target.select(),className:"flex-1 min-w-0 text-xs font-mono text-ink-muted bg-wash border border-line rounded-lg px-3 py-2 focus:outline-none focus:ring-1 focus:ring-accent/40 truncate"}),u.jsxs("button",{onClick:()=>{c()},className:`shrink-0 text-xs px-3 py-2 rounded-lg flex items-center gap-1.5 transition-colors ${n?"bg-green-600 text-white":"bg-accent text-white hover:bg-accent-strong"}`,"data-share-copy":!0,children:[n?u.jsx(gl,{size:13,strokeWidth:2}):u.jsx(Os,{size:13,strokeWidth:1.75}),t(n?"viewer.copied":"viewer.copyLink")]})]}),e.length>3e4&&u.jsx("p",{className:"text-2xs text-amber-700 bg-amber-50 border border-amber-200 rounded-lg px-3 py-2 leading-relaxed mb-3","data-share-toolong":!0,children:t("share.linkTooLong")}),u.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[u.jsxs("button",{onClick:()=>{of({sharedReadonly:r})},"data-share-fullfile":!0,className:"text-xs px-3 py-1.5 rounded-lg border border-line text-ink-muted hover:bg-wash hover:text-ink transition-colors flex items-center gap-1.5",children:[u.jsx(dP,{size:13,strokeWidth:1.75}),t("share.fullFile")]}),u.jsxs("label",{className:"flex items-center gap-1.5 text-2xs text-ink-muted cursor-pointer select-none",children:[u.jsx("input",{type:"checkbox",checked:r,onChange:d=>s(d.target.checked),className:"accent-[color:var(--color-accent)]"}),t("share.readonlyMark")]})]}),u.jsx("div",{className:"border-t border-line pt-3",children:u.jsx("div",{className:"flex items-center gap-2",children:u.jsxs("button",{onClick:()=>{l(),ye.getState().setThoughtMapOpen(!0)},"data-share-thought-map":!0,className:"text-xs px-3 py-1.5 rounded-lg bg-accent/10 text-accent hover:bg-accent/20 transition-colors flex items-center gap-1.5 font-medium",children:[u.jsx(Sb,{size:13,strokeWidth:1.75}),t("tmap.export")]})})})]})}),document.body)}const RN=new Set(["file","note","link"]);function Fne(e,t){return{nodes:e.map(n=>{const a=n.data.summaryTypes,r=Array.isArray(a)?a[n.data.responseIndex]??a[0]:void 0,s=n.id.match(/-(\d{13})-/);return{id:n.id,x:n.position.x,y:n.position.y,material:RN.has(n.data.stepKind??""),root:!!n.data.isRoot,marked:r==="decision"||r==="pivot"||r==="ruleout",ts:s?Number(s[1]):void 0}}),edges:t.map(n=>({s:n.source,t:n.target,dashed:!!n.style?.strokeDasharray||!!n.data?.isWatch}))}}function qne(e){let t=0,n=0,a=0,r=0,s=0;for(const l of e){if(RN.has(l.data.stepKind??"")){n++;continue}t++;const c=l.data.summaryTypes,d=Array.isArray(c)?c[l.data.responseIndex]??c[0]:void 0;d==="decision"?a++:d==="pivot"?r++:d==="ruleout"&&s++}return{steps:t,materials:n,decisions:a,pivots:r,ruleouts:s}}function Vne(e){const t={};e.nodes.forEach(d=>{t[d.id]=d});const n={},a=new Set;e.edges.filter(d=>!d.dashed).forEach(d=>{(n[d.s]=n[d.s]||[]).push(d.t),t[d.s]&&!t[d.s].material&&a.add(d.t)});const r={};let s=0;const l=(d,h,m)=>{if(r[d])return;r[d]=[h,m],(n[d]||[]).filter(x=>t[x]&&!t[x].material&&!r[x]).forEach((x,b)=>l(x,b===0?h:++s,m+1))};e.nodes.filter(d=>!d.material&&!a.has(d.id)).forEach(d=>{l(d.id,s,0),s++});const c={};return e.nodes.filter(d=>d.material).forEach(d=>{const h=e.edges.find(m=>m.s===d.id&&r[m.t]);if(h){const[m,p]=r[h.t],x=c[h.t]=(c[h.t]||0)+1;r[d.id]=[m-.62,p-.55-(x-1)*.55]}else r[d.id]=[s++,0]}),e.nodes.forEach(d=>{r[d.id]||(r[d.id]=[s++,0])}),Object.fromEntries(Object.entries(r).map(([d,[h,m]])=>[d,[h*92,m*64]]))}function Wne(e){return Object.fromEntries(e.nodes.map(t=>[t.id,[t.x,t.y]]))}const LN="https://chenxiachan.github.io/thoughtdag/";function Kf(e,t){const n=t==="zh",a=[[e.steps,n?"步思考":e.steps===1?"step":"steps","dot"]];return e.materials&&a.push([e.materials,n?"份材料":e.materials===1?"source":"sources","dia"]),e.decisions&&a.push([e.decisions,n?"项决策":e.decisions===1?"decision":"decisions","red"]),e.pivots&&a.push([e.pivots,n?"次转向":e.pivots===1?"pivot":"pivots","red"]),e.ruleouts&&a.push([e.ruleouts,n?"次排除":e.ruleouts===1?"rule-out":"rule-outs","red"]),a}function GE(e,t,n){const a=Kf(n,e);return e==="zh"?`${t}。${a.map(([r,s])=>`${r} ${s}`).join("、")}。这是我思考时留下的形状。`:`${t}. ${a.map(([r,s])=>`${r} ${s}`).join(", ")}.
|
|
722
722
|
|
|
723
723
|
Mapped as I thought.`}function Gu(e){let t=0;for(const n of e)t+=/[\u2E80-\u9FFF\uF900-\uFAFF\uFF00-\uFF60\u3000-\u303F]/.test(n)?2:1;return t}function Qh(e,t){let n=0,a="";for(const r of e){if(n+=/[\u2E80-\u9FFF\uF900-\uFAFF\uFF00-\uFF60\u3000-\u303F]/.test(r)?2:1,n>t)break;a+=r}return a}function ex(){return`Made with ThoughtDAG (${LN})`}const Gne='<svg xmlns="http://www.w3.org/2000/svg" viewBox="14.5 2.5 22 39"><line x1="19" y1="10" x2="19" y2="18" stroke="#6B5CE7" stroke-width="2.5" stroke-linecap="round"/><line x1="19" y1="25" x2="19" y2="33" stroke="#6B5CE7" stroke-width="2.5" stroke-linecap="round"/><line x1="22.5" y1="23.5" x2="30" y2="28.5" stroke="#E08A3C" stroke-width="2.5" stroke-linecap="round" stroke-dasharray="3 3"/><circle cx="19" cy="7" r="3.8" fill="#6B5CE7"/><circle cx="19" cy="21.5" r="3.8" fill="none" stroke="#6B5CE7" stroke-width="2.6"/><circle cx="19" cy="36.5" r="3.8" fill="#6B5CE7"/><circle cx="32.5" cy="30" r="3.4" fill="#E08A3C"/></svg>',YE={zh:"一张思路地图",en:"A THOUGHT MAP"};function $E({kind:e}){return u.jsx("svg",{className:"tmap-sg",viewBox:"0 0 10 10","aria-hidden":!0,children:e==="dia"?u.jsx("rect",{x:"2.4",y:"2.4",width:"5.2",height:"5.2",transform:"rotate(45 5 5)",className:"tmap-sg-dia"}):u.jsx("circle",{cx:"5",cy:"5",r:"3.6",className:e==="red"?"tmap-sg-red":"tmap-sg-ink"})})}const Yu=40,tx=56;function nx({structure:e,positions:t,stats:n,title:a,subtitle:r,mapLang:s,paper:l,rot:c,tst:d,tss:h,tsx:m,showStats:p,timeInk:x,dateText:b,sig:y,sigPos:E,artRef:T}){const w=j.useRef(null),_=j.useRef(null),A=j.useMemo(()=>{const M=Object.values(t).map(R=>R[0]),N=Object.values(t).map(R=>R[1]);return{w:Math.max(...M)-Math.min(...M)+1,h:Math.max(...N)-Math.min(...N)+1}},[t]),C=(c?A.w/A.h:A.h/A.w)>=1.35?"scroll":"cover",O=Kf(n,s);j.useEffect(()=>{const M=w.current,N=T?.current??_.current;if(!M||!N)return;M.innerHTML="";const R=M.clientWidth,B=M.clientHeight;if(!R||!B)return;const H="http://www.w3.org/2000/svg",Y=(at,wt)=>{const zt=document.createElementNS(H,at);for(const We in wt)zt.setAttribute(We,String(wt[We]));return zt},Z=Y("svg",{width:"100%",height:"100%",viewBox:`0 0 ${R} ${B}`});M.appendChild(Z);const q={};Object.entries(t).forEach(([at,[wt,zt]])=>{q[at]=c?[zt,-wt]:[wt,zt]});const K=Object.values(q).map(at=>at[0]),U=Object.values(q).map(at=>at[1]),G=Math.min(...K),ne=Math.min(...U),X=C==="scroll"?{l:212,r:28,t:28,b:28}:{l:28,r:28,t:28+(a?124:0)+(r?36:0)+(y&&E==="byline"?26:0),b:p?72:48},P=Math.max(...K)-G+1,F=Math.max(...U)-ne+1,J=Math.min((R-X.l-X.r)/P,(B-X.t-X.b)/F),W=X.l+(R-X.l-X.r-P*J)/2,ae=X.t+(B-X.t-X.b-F*J)/2,ve={};Object.entries(q).forEach(([at,[wt,zt]])=>{ve[at]=[(wt-G)*J+W,(zt-ne)*J+ae]});const me=getComputedStyle(N),ke=me.getPropertyValue("--tm-ink").trim(),re=me.getPropertyValue("--tm-ink-min").trim(),be=me.getPropertyValue("--tm-red").trim(),Le=me.getPropertyValue("--tm-edge").trim(),Oe=at=>{const wt=at.replace("#","");return[0,2,4].map(zt=>parseInt(wt.slice(zt,zt+2),16))},je=(at,wt,zt)=>{const We=Oe(at),Bt=Oe(wt);return"#"+We.map((se,He)=>Math.round(se+(Bt[He]-se)*zt).toString(16).padStart(2,"0")).join("")},ze=e.nodes.filter(at=>!at.material&&at.ts!=null).sort((at,wt)=>at.ts-wt.ts),rt={};ze.forEach((at,wt)=>{rt[at.id]=ze.length>1?wt/(ze.length-1):1});const ot=ze.length?ze[ze.length-1].id:[...e.nodes].reverse().find(at=>!at.material)?.id??null,Xe=e.nodes.length,kt=Math.max(1.7,Math.min(5.2,5.6*Math.sqrt(60/Xe))),ht=Math.max(.5,Math.min(1.1,kt*.26));e.edges.forEach(at=>{const wt=ve[at.s],zt=ve[at.t];!wt||!zt||Z.appendChild(Y("line",{x1:wt[0],y1:wt[1],x2:zt[0],y2:zt[1],stroke:Le,"stroke-width":ht,...at.dashed?{"stroke-dasharray":"3 3"}:{}}))}),e.nodes.forEach(at=>{const wt=ve[at.id];if(!wt)return;const zt=at.root?kt+2.6:kt;if(at.material){const We=zt+.8;Z.appendChild(Y("rect",{x:wt[0]-We/1.45,y:wt[1]-We/1.45,width:We*1.38,height:We*1.38,fill:"none",stroke:ke,"stroke-width":Math.max(.8,ht+.2),transform:`rotate(45 ${wt[0]} ${wt[1]})`}))}else{const We=x?je(re,ke,rt[at.id]??1):ke;Z.appendChild(Y("circle",{cx:wt[0],cy:wt[1],r:zt,fill:at.marked?be:We})),at.id===ot&&Z.appendChild(Y("circle",{cx:wt[0],cy:wt[1],r:zt+2.8,fill:"none",stroke:ke,"stroke-width":Math.max(.9,ht+.15)}))}})},[e,t,A,l,c,d,h,m,C,a,r,p,x,y,E,T]);const D=u.jsxs("div",{className:"tmap-brand",children:[u.jsx("span",{dangerouslySetInnerHTML:{__html:Gne},style:{display:"contents"}}),u.jsx("div",{className:"tmap-bt",children:u.jsx("b",{children:"ThoughtDAG"})})]});return u.jsx("div",{ref:T??_,className:`tmap-art tmap-${l} tmap-${C}`,style:{"--tmt":d,"--tms":h,"--tmx":m},"data-tmap-art":!0,children:C==="scroll"?u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"tmap-head",children:[u.jsx("div",{className:"tmap-k",children:YE[s]}),b&&u.jsx("div",{className:"tmap-date",children:b}),a&&u.jsx("h4",{className:"tmap-t",children:a}),r&&u.jsx("div",{className:"tmap-s",children:r}),y&&E==="byline"&&u.jsx("div",{className:"tmap-sig-byline",children:y}),p&&u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"tmap-rule"}),u.jsx("div",{className:"tmap-stats",children:O.map(([M,N,R],B)=>u.jsxs("span",{children:[u.jsx($E,{kind:R}),u.jsx("b",{children:M})," ",N,u.jsx("br",{})]},B))})]}),u.jsx("div",{className:"tmap-spacer"}),D]}),u.jsx("div",{className:"tmap-graph",ref:w}),y&&E==="corner"&&u.jsx("div",{className:"tmap-sig-corner",children:y})]}):u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"tmap-head",children:[u.jsx("div",{className:"tmap-k",children:YE[s]}),b&&u.jsx("div",{className:"tmap-date",children:b}),a&&u.jsx("h4",{className:"tmap-t",children:a}),r&&u.jsx("div",{className:"tmap-s",children:r}),y&&E==="byline"&&u.jsx("div",{className:"tmap-sig-byline",children:y})]}),D,u.jsx("div",{className:"tmap-graph",ref:w}),y&&E==="corner"&&u.jsx("div",{className:"tmap-sig-corner",children:y}),u.jsx("div",{className:"tmap-footrow",children:p?u.jsx("div",{className:"tmap-statline",children:O.map(([M,N,R],B)=>u.jsxs("span",{children:[B>0&&" · ",u.jsxs("span",{className:"tmap-si",children:[u.jsx($E,{kind:R}),u.jsx("b",{children:M})," ",N]})]},B))}):u.jsx("div",{})})]})})}function Yne(){const e=ye(We=>We.thoughtMapOpen),t=Gt(),n=Fa(We=>We.lang),a=oe(We=>We.nodes),r=oe(We=>We.edges),s=Nn(We=>We.projects.find(Bt=>Bt.id===We.activeId)?.name??""),[l,c]=j.useState("image"),[d,h]=j.useState("tidy"),[m,p]=j.useState(!1),[x,b]=j.useState("light"),[y,E]=j.useState("zh"),[T,w]=j.useState("zh"),[_,A]=j.useState(1.15),[C,O]=j.useState(1),[D,M]=j.useState(1),[N,R]=j.useState(""),[B,H]=j.useState("byline"),[Y,Z]=j.useState(!0),[q,K]=j.useState(!1),[U,G]=j.useState(!0),[ne,X]=j.useState("span"),[P,F]=j.useState(""),[J,W]=j.useState(""),[ae,ve]=j.useState(""),[me,ke]=j.useState(!1),[re,be]=j.useState(!1),Le=j.useRef(null),Oe=j.useMemo(()=>Fne(a,r),[a,r]),je=j.useMemo(()=>qne(a),[a]),ze=j.useMemo(()=>d==="tidy"?Vne(Oe):Wne(Oe),[Oe,d]),rt=j.useMemo(()=>{if(!U)return"";const We=ge=>`${String(ge.getFullYear()%100).padStart(2,"0")}.${String(ge.getMonth()+1).padStart(2,"0")}.${String(ge.getDate()).padStart(2,"0")}`;if(ne==="today")return We(new Date);const Bt=Oe.nodes.map(ge=>ge.ts).filter(ge=>ge!=null);if(!Bt.length)return We(new Date);const se=new Date(Math.min(...Bt)),He=new Date(Math.max(...Bt));return We(se)===We(He)?We(se):`${We(se)}-${We(He)}`},[Oe,U,ne]);j.useEffect(()=>{e&&(c("image"),E(n),w(n),R(localStorage.getItem("thoughtdag.tmapSignature")??""),H(localStorage.getItem("thoughtdag.tmapSigPos")||"byline"),F(Qh(s,Yu)),W(""),ve(`${GE(n,s||"ThoughtDAG",je)}
|
|
@@ -758,4 +758,4 @@ The takeaway of every step, in the order they were thought (tags: RULEOUT = kill
|
|
|
758
758
|
${m.join(`
|
|
759
759
|
`)}
|
|
760
760
|
|
|
761
|
-
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 ob.set(`${n}:${a}`,x),x}function yae({onLocate:e}){const t=ye(O=>O.timelineOverviewOpen),n=ye(O=>O.setTimelineOverviewOpen),a=oe(O=>O.nodes),r=Gt(),s=x7(),l=Fa(O=>O.lang),c=j.useMemo(()=>P2(a,0),[a]),d=j.useMemo(()=>zN(a),[a]),[h,m]=j.useState(null),[p,x]=j.useState(!1),[b,y]=j.useState(!1),E=xae(d,l)??h,T=!!E&&(E.fp!==d||E.lang!==l),w=()=>{x(!0),y(!1);const{nodes:O,edges:D}=oe.getState();bae(O,D,l).then(m).catch(()=>y(!0)).finally(()=>x(!1))};if(!t)return null;const _=()=>n(!1),A=O=>O?O.slice(0,10):"",C=O=>O?new Date(O).toLocaleTimeString(s,{hour:"2-digit",minute:"2-digit"}):"—";return $a.createPortal(u.jsx("div",{className:"fixed inset-0 z-[60] bg-ink/30 backdrop-blur-sm flex items-center justify-center p-6",onClick:_,children:u.jsxs("div",{className:"bg-card rounded-2xl shadow-2xl border border-line w-[640px] max-h-[80vh] flex flex-col",onClick:O=>O.stopPropagation(),children:[u.jsxs("div",{className:"flex items-center gap-2 px-5 py-3 border-b border-line shrink-0",children:[u.jsx(J8,{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:qe(r("tlov.count"),{n:c.length})}),u.jsx("div",{className:"flex-1"}),u.jsxs("button",{onClick:()=>{_(),ye.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(Sb,{size:13,strokeWidth:1.75}),r("tmap.export")]}),u.jsx("button",{onClick:_,className:"text-ink-faint hover:text-ink w-7 h-7 rounded-lg hover:bg-wash flex items-center justify-center transition-colors",children:u.jsx(bn,{size:15,strokeWidth:1.75})})]}),u.jsxs("div",{className:"px-5 pt-3 shrink-0","data-gedankengang":!0,children:[!E&&!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(Nf,{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")}),E&&!p&&u.jsxs("div",{className:`rounded-xl bg-wash px-4 py-3 ${T?"opacity-60":""}`,children:[u.jsx("p",{className:"text-sm text-ink leading-relaxed",children:E.text}),u.jsxs("div",{className:"flex items-center gap-2 mt-1.5",children:[u.jsx("span",{className:"text-2xs text-ink-faint",children:T?r("tlov.gedankenStale"):new Date(E.at).toLocaleString(s)}),T&&u.jsx("button",{onClick:w,className:"text-2xs text-accent hover:underline",children:r("tlov.gedankenRedo")})]})]})]}),u.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-5 py-3","data-timeline-overview":!0,children:[c.length===0&&u.jsx("p",{className:"text-xs text-ink-faint italic py-2",children:r("tlov.empty")}),c.map((O,D)=>{const M=D>0?A(c[D-1].createdAt):void 0,N=A(O.createdAt),R=D===0||N!==M;return u.jsxs("div",{children:[R&&u.jsx("div",{className:"sticky top-0 bg-card text-2xs text-ink-faint font-medium pt-3 pb-1 first:pt-0",children:N||r("tlov.undated")}),u.jsxs("div",{className:"group flex items-center gap-2.5 py-1.5 border-b border-line/50 last:border-0",children:[u.jsx("span",{className:"w-2 h-2 rounded-full shrink-0",style:{background:O.color,opacity:O.archived?.35:1}}),u.jsx("span",{className:"text-2xs font-mono text-ink-faint shrink-0 w-11",children:C(O.createdAt)}),u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsxs("p",{className:`text-sm truncate ${O.archived?"text-ink-faint line-through":O.badged?"text-ink":"text-ink-muted"}`,children:[O.topic&&u.jsxs("span",{className:"font-medium text-accent",children:[O.topic," · "]}),O.label||"…"]}),O.modifiedAt&&O.modifiedAt!==O.createdAt&&u.jsxs("p",{className:"text-2xs text-ink-faint",children:[r("timeline.modified")," ",new Date(O.modifiedAt).toLocaleString(s)]})]}),u.jsx("button",{className:"shrink-0 text-2xs font-mono text-accent bg-accent/10 hover:bg-accent/20 rounded-full px-1.5 py-0.5 transition-colors opacity-0 group-hover:opacity-100",onClick:()=>{_(),e(O.id)},title:r("hlov.locateTitle"),children:r("tlov.locate")})]})]},O.id)})]})]})}),document.body)}const vae=j.memo(function(t){const n=Nn(a=>a.projects.find(r=>r.id===a.activeId)?.kind==="paradigm");return t.data?.stepKind==="frame"?u.jsx(hte,{...t}):Wf(t.data?.stepKind)?u.jsx(dte,{...t}):n?u.jsx(nte,{...t}):u.jsx(Jee,{...t})}),wae={thought:vae},Eae={smoothstep:j.memo(pte)};function kae(){const[e,t]=j.useState(vt||oe.persist.hasHydrated());return j.useEffect(()=>oe.persist.onFinishHydration(()=>t(!0)),[]),j.useEffect(()=>{if(!e||vt)return;let n;const a=()=>{clearTimeout(n),n=setTimeout(()=>{Ene()},800)},r=oe.subscribe((s,l)=>{s.nodes!==l.nodes&&a()});return a(),()=>{r(),clearTimeout(n)}},[e]),j.useEffect(()=>{ye.getState().condenseRun.status==="building"&&ye.getState().setCondenseRun({status:"idle",current:0,total:0,streaming:""})},[]),j.useEffect(()=>{if(vt)return;const n=setTimeout(()=>{kne()},6e3);return()=>clearTimeout(n)},[]),j.useEffect(()=>{if(!e||vt||localStorage.getItem("thoughtdag.tutorialDone")||oe.getState().nodes.length>0)return;const n=setTimeout(()=>ye.getState().setTutorialOpen(!0),900);return()=>clearTimeout(n)},[e]),j.useEffect(()=>{Cne()},[]),j.useEffect(()=>{vt||(Kt(()=>import("./session-handoff-CGrowwZp.js"),[]).then(n=>n.consumeSessionHandoff()),Kt(()=>import("./live-mirror-BElcCk_a.js"),[]).then(n=>n.startLiveMirror()),Kt(()=>import("./canvas-record-C1A8ExlM.js"),[]).then(n=>n.startCanvasRecord()),Kt(()=>import("./canonical-DbPqsMYz.js"),[]).then(n=>n.unsubscribeOrphanedSessions()))},[]),j.useEffect(()=>{vt||Nne().then(n=>{n&&(n.status==="minted"?(Ke("success",Ie("provider.oauthMinted")),DN(n.key)):Ke("error",qe(Ie("provider.oauthFailed"),{error:n.error})))})},[]),u.jsxs(u.Fragment,{children:[e&&u.jsx(Tae,{}),u.jsx(Dne,{}),u.jsx(Rne,{}),u.jsx(Pne,{}),u.jsx(zne,{}),u.jsx(Bne,{}),u.jsx(Hne,{}),u.jsx(Une,{}),u.jsx(Yne,{}),u.jsx(Jne,{}),u.jsx(_ne,{}),u.jsx(dae,{})]})}function Tae(){const{nodes:e,edges:t,setNodes:n,setEdges:a,addQuestion:r,undo:s,redo:l,addCrossLink:c,setSelectedNodeId:d,setSelectedNodeIds:h,history:m,historyIndex:p,relayout:x}=oe(),b=Gt(),y=ye(ee=>ee.setTutorialOpen),E=ye(ee=>ee.annotationsHidden),T=ye(ee=>ee.setAnnotationsHidden),[w,_]=j.useState(""),[A,C]=j.useState(!1),[O,D]=j.useState(""),[M,N]=j.useState(!1),[R,B]=j.useState(!1),[H,Y]=j.useState([]),[Z,q]=j.useState(!1),K=j.useRef(null),U=j.useRef(null),G=e.length>0,ne=oe(ee=>ee.events.length>0),X=oe(ee=>ee.nodes.reduce((xe,_e)=>xe+(_e.data.highlights?.length??0),0)),P=oe(ee=>ee.nodes.reduce((xe,_e)=>xe+(_e.data.attachments?.length??0)+(["note","link"].includes(_e.data.stepKind??"")?1:0),0)),F=j.useRef(null),J=ye(ee=>ee.arrivalFocusNodeId);j.useEffect(()=>{if(!J)return;const ee=oe.getState().nodes.find(xe=>xe.id===J);ee&&(ye.getState().setArrivalFocusNodeId(null),window.setTimeout(()=>{F.current?.setCenter(ee.position.x+260,ee.position.y+140,{zoom:.9,duration:400})},150))},[J]);const W=bs(ee=>ee.paper),ae=bs(ee=>ee.lighting),ve=bs(ee=>ee.resolved),me=j.useMemo(()=>ite(),[ve]),ke=j.useMemo(()=>{const ee=getComputedStyle(document.documentElement),xe=(ee.getPropertyValue("--color-surface").trim()||"#FAF9F7").replace("#",""),[_e,Ue,Se]=[0,2,4].map(Ye=>parseInt(xe.slice(Ye,Ye+2),16));return{mask:`rgba(${_e},${Ue},${Se},0.7)`,archived:ee.getPropertyValue("--color-wash").trim()||"#EFEDE9",ordinary:ve==="dark"?"#6E6759":"#B9B3AB"}},[ve]),re=j.useRef(e.length),be=j.useCallback((ee,xe={})=>{const _e=F.current;if(!_e)return;const Ue=xe.zoom??_e.getZoom();_e.setCenter(ee.position.x+(xe.offX??260)+$f(ee.id)/(2*Ue),ee.position.y+110,{zoom:Ue,duration:xe.duration??350})},[]),Le=Fa(ee=>ee.lang),Oe=ye(ee=>ee.condenseRun),je=Oe.status==="building",ze=Nn(ee=>ee.projects.find(xe=>xe.id===ee.activeId)?.kind==="paradigm"),rt=El();j.useEffect(()=>{if(vt||!G||oe.getState().nodes.length<10)return;const ee=Number(localStorage.getItem("thoughtdag.lastBackupAt")??0);if(ee===0){localStorage.setItem("thoughtdag.lastBackupAt",String(Date.now()));return}Date.now()-ee<168*3600*1e3||sessionStorage.getItem("thoughtdag.backupNudged")||(sessionStorage.setItem("thoughtdag.backupNudged","yes"),Ke("info",Ie("backup.nudge"),0,{label:Ie("backup.nudgeBtn"),run:()=>of()}))},[G]);const ot=j.useCallback(()=>{const{nodes:ee,edges:xe}=wne(Le),_e=oe.getState();_e.setNodes([..._e.nodes,...ee.filter(Ue=>!_e.nodes.some(Se=>Se.id===Ue.id))]),_e.setEdges([..._e.edges,...xe.filter(Ue=>!_e.edges.some(Se=>Se.id===Ue.id))]),_e.pushHistory(),setTimeout(()=>{const Ue=F.current;Ue&&(Ue.fitView({duration:500,padding:.1}),setTimeout(()=>{if(Ue.getViewport().zoom<.34){const Se=[...oe.getState().nodes].sort((Ye,Ze)=>(Ye.data.createdAt??"").localeCompare(Ze.data.createdAt??""))[0];Se&&Ue.setCenter(Se.position.x+300,Se.position.y+240,{zoom:.6,duration:550})}},680))},100),localStorage.getItem("thoughtdag.tutorialDone")||y(!0)},[Le,y]),Xe=j.useCallback(ee=>{const xe=oe.getState(),_e=xe.nodes[xe.nodes.length-1],Ue=_e?{x:_e.position.x,y:_e.position.y+340}:{x:120,y:80},Se=In();xe.setNodes([...xe.nodes,{id:Se,type:"thought",position:Ue,dragHandle:".drag-handle",data:{question:"",instruction:"",stepKind:ee,response:"",responses:[],responseIndex:-1,isCollapsed:!1,isEditing:!1,isEditingResponse:!1,isLoading:!1,tokenCount:0,highlights:[],highlightMode:"tag",attachments:[],excludedAttachmentIds:[],includedAttachmentIds:[],roleMode:"inherit",isRoot:xe.nodes.length===0,isBranch:!1}}]),xe.pushHistory()},[]),kt=j.useCallback(()=>{re.current=oe.getState().nodes.length,setTimeout(()=>F.current?.fitView({duration:300,padding:.2}),50)},[]),ht=j.useRef(null),at=j.useCallback(ee=>{const xe=oe.getState(),_e=In();xe.setNodes([...xe.nodes,{id:_e,type:"thought",position:ee,width:640,height:420,zIndex:-1,dragHandle:".drag-handle",data:{question:"",stepKind:"frame",frameCarry:!1,response:"",responses:[],responseIndex:-1,isCollapsed:!1,isEditing:!1,isEditingResponse:!1,isLoading:!1,tokenCount:0,highlights:[],highlightMode:"tag",attachments:[],excludedAttachmentIds:[],includedAttachmentIds:[],roleMode:"inherit",isRoot:!1,isBranch:!1}}]),xe.pushHistory()},[]),wt=j.useCallback(ee=>{const xe=[];for(const _e of Array.from(ee)){const Ue=_e.name.split(".").pop()?.toLowerCase()??"";_e.type.startsWith("image/")||_e.type==="application/pdf"||_e.type.startsWith("text/")||["pdf","docx","txt","md","csv","json","yaml","yml","toml","js","ts","tsx","jsx","py","sh","c","cpp","h","java","rs","go","rb","swift","css","html","xml","sql","tex","bib"].includes(Ue)?xe.push(_e):Ke("info",qe(Ie("toast.unsupportedFile"),{name:_e.name}))}return xe},[]),zt=j.useCallback(ee=>{const xe=oe.getState(),_e=In();return xe.setNodes([...xe.nodes,{id:_e,type:"thought",position:ee,dragHandle:".drag-handle",data:{question:"",response:"",responses:[],responseIndex:-1,isCollapsed:!1,isEditing:!1,isEditingResponse:!1,isLoading:!1,tokenCount:0,highlights:[],highlightMode:"tag",attachments:[],excludedAttachmentIds:[],includedAttachmentIds:[],roleMode:"inherit",isRoot:!1,isBranch:!1,webSearch:ye.getState().webSearchEnabled,scholarSearch:ye.getState().scholarSearchEnabled}}]),xe.pushHistory(),_e},[]),We=j.useCallback(ee=>{const xe=wt(ee);if(xe.length===0)return;let _e=null;xe.forEach((Ue,Se)=>{const Ye=Qr("file",{x:120+Se%3*480,y:120+Math.floor(Se/3)*620});fd(Ye,[Ue]),!_e&&!Ue.type.startsWith("image/")&&(_e=Ye)}),_e&&ye.getState().setReaderNodeId(_e),setTimeout(()=>F.current?.fitView({duration:400,padding:.2}),120)},[wt]),Bt=j.useCallback((ee,xe)=>{const _e=ee.clientX,Ue=ee.clientY,Se=ee.currentTarget;let Ye=null;const Ze=Mt=>{!Ye&&Math.hypot(Mt.clientX-_e,Mt.clientY-Ue)>6&&(Ye=document.createElement("div"),Ye.innerHTML=Se.innerHTML,Ye.style.cssText="position:fixed;z-index:300;pointer-events:none;width:36px;height:36px;display:flex;align-items:center;justify-content:center;background:var(--color-card);border:1px solid var(--color-accent);border-radius:10px;box-shadow:0 4px 14px rgba(0,0,0,.18);opacity:.92;",document.body.appendChild(Ye)),Ye&&(Ye.style.left=`${Mt.clientX-18}px`,Ye.style.top=`${Mt.clientY-18}px`)},bt=Mt=>{window.removeEventListener("pointermove",Ze),window.removeEventListener("pointerup",bt);const Ht=!!Ye;Ye?.remove(),xe(Ht?{x:Mt.clientX,y:Mt.clientY}:null)};window.addEventListener("pointermove",Ze),window.addEventListener("pointerup",bt)},[]),se=j.useCallback(ee=>{const xe=F.current?.screenToFlowPosition(ee??{x:window.innerWidth/2,y:window.innerHeight/2})??{x:140,y:140};return{x:xe.x-200,y:xe.y-60}},[]);j.useEffect(()=>{const ee=_e=>{ht.current={x:_e.clientX,y:_e.clientY}},xe=_e=>{if(vt)return;const Ue=_e.target;if(Ue&&(Ue.tagName==="INPUT"||Ue.tagName==="TEXTAREA"||Ue.isContentEditable))return;const Se=Nn.getState(),Ye=Se.projects.find(kn=>kn.id===Se.activeId)?.kind==="paradigm";if(oe.getState().nodes.length===0&&!Ye)return;const Ze=_e.clipboardData;if(!Ze)return;const bt=se(ht.current),Mt=Ze.getData("text/plain").trim(),Ht=Array.from(Ze.files),ca=Ht.some(kn=>!kn.type.startsWith("image/"));if(Ht.length>0&&(ca||!Mt)){_e.preventDefault();const kn=Qr("file",bt);fd(kn,Ht);return}if(Mt)if(_e.preventDefault(),/^https?:\/\/\S+$/.test(Mt)){const kn=Qr("link",bt,{linkUrl:Mt});yN(kn,Mt)}else Qr("note",bt,{question:ote(Mt)})};return window.addEventListener("mousemove",ee),window.addEventListener("paste",xe),()=>{window.removeEventListener("mousemove",ee),window.removeEventListener("paste",xe)}},[se]);const He=j.useCallback(async()=>{const ee=oe.getState();if(ee.nodes.length===0)return;const{nodes:xe,edges:_e}=WH(ee.nodes,ee.edges),Ue=Nn.getState(),Se=Ue.projects.find(Ze=>Ze.id===Ue.activeId)?.name??"Paradigm",Ye=crypto.randomUUID();await zr(ni(Ye),JSON.stringify({state:{nodes:xe,edges:_e},version:1})),await jc(Ye,`▶ ${Se}`,"chat"),await B7(Ye,Se),re.current=oe.getState().nodes.length,setTimeout(()=>F.current?.fitView({duration:400,padding:.15}),150)},[]);j.useEffect(()=>{e.length===0&&!ze&&!localStorage.getItem("thoughtdag.seeded")&&localStorage.setItem("thoughtdag.seeded","yes")},[]),j.useEffect(()=>{if(e.length>re.current&&F.current){const ee=e[e.length-1];ee&&setTimeout(()=>be(ee,{zoom:1,duration:400,offX:220}),100)}re.current=e.length},[e,be]);const ge=j.useCallback(ee=>{const xe=oe.getState().nodes;n(m8(ee,xe))},[n]),Ve=j.useCallback(ee=>a(p8(ee,oe.getState().edges)),[a]),dt=j.useRef(null),xt=j.useCallback((ee,xe)=>{if(xe.data.stepKind!=="frame"||xe.data.frameCarry===!1)return;const _e=oe.getState(),Ue=_e.nodes.find(bt=>bt.id===xe.id);if(!Ue)return;const Se=Ue.measured?.width??Ue.width??0,Ye=Ue.measured?.height??Ue.height??0,Ze=_e.nodes.filter(bt=>{if(bt.id===Ue.id||bt.data.stepKind==="frame"||bt.selected)return!1;const Mt=bt.position.x+(bt.measured?.width??520)/2,Ht=bt.position.y+(bt.measured?.height??120)/2;return Mt>=Ue.position.x&&Mt<=Ue.position.x+Se&&Ht>=Ue.position.y&&Ht<=Ue.position.y+Ye}).map(bt=>({id:bt.id,start:bt.position}));Ze.length!==0&&(dt.current={frameId:Ue.id,start:Ue.position,members:Ze})},[]),St=j.useCallback((ee,xe)=>{const _e=dt.current;if(!_e||xe.id!==_e.frameId)return;const Ue=xe.position.x-_e.start.x,Se=xe.position.y-_e.start.y,Ye=new Map(_e.members.map(Ze=>[Ze.id,{x:Ze.start.x+Ue,y:Ze.start.y+Se}]));oe.setState(Ze=>({nodes:Ze.nodes.map(bt=>{const Mt=Ye.get(bt.id);return Mt?{...bt,position:Mt}:bt})}))},[]),Ft=j.useCallback(()=>{dt.current=null},[]),[un,yn]=j.useState(null),[$t,vn]=j.useState(null),an=j.useCallback((ee,xe)=>{vt||window.getSelection()?.toString()||(ee.preventDefault(),vn({x:ee.clientX,y:ee.clientY,nodeId:xe.id}))},[]),wa=j.useCallback((ee,xe)=>{ee.preventDefault(),yn({x:ee.clientX,y:ee.clientY,edgeId:xe.id})},[]);j.useEffect(()=>{if(!un)return;const ee=()=>yn(null);return window.addEventListener("click",ee),()=>window.removeEventListener("click",ee)},[un]);const qn=oe(ee=>ee.deleteEdges),lr=j.useCallback(ee=>{qn([ee]),yn(null)},[qn]),Qa=j.useCallback(ee=>{ee.source&&ee.target&&c(ee.source,ee.target)},[c]),Jn=j.useCallback(()=>{window.getSelection()?.removeAllRanges(),document.body.classList.add("tdag-connecting")},[]),ja=j.useCallback((ee,xe)=>{if(document.body.classList.remove("tdag-connecting"),ze||xe.isValid||xe.fromHandle?.type!=="source"||!xe.fromNode)return;const _e=xe.fromNode.id,Ue=ee.target?.closest?.(".react-flow__node");if(Ue){const Ht=Ue.getAttribute("data-id");if(Ht&&Ht!==_e){const ca=oe.getState().nodes.find(Rn=>Rn.id===Ht),kn=ca?.data.stepKind??"";ca&&!["note","file","link","frame"].includes(kn)&&oe.getState().addCrossLink(_e,Ht)}return}const{clientX:Se,clientY:Ye}="changedTouches"in ee?ee.changedTouches[0]:ee,Ze=se({x:Se,y:Ye}),bt=oe.getState();if(bt.nodes.find(Ht=>Ht.id===_e)?.data.stepKind==="frame")return;const Mt=zt(Ze);bt.setEdges([...oe.getState().edges,{id:`edge-${_e}-${Mt}`,source:_e,target:Mt,sourceHandle:"continue",targetHandle:"top",type:"smoothstep",style:{stroke:nt.accent,strokeWidth:2},animated:!1,markerEnd:{type:"arrowclosed",color:nt.accent,width:18,height:18},data:{}}]),oe.getState().pushHistory()},[ze,se,zt]),Zt=oe(ee=>ee.selectedNodeId),ce=oe(ee=>ee.selectedNodeIds),Be=ye(ee=>ee.panelOpen),ft=ye(ee=>ee.viewerLoadError),It=oe(ee=>ee.staleIds.length),wn=ye(ee=>ee.panelWidth),rn=e.find(ee=>ee.id===Zt)?.data.stepKind,yt=Wf(rn)||rn==="frame",mt=Be&&!!Zt&&!ze&&!yt,Rt=ce.length>1,On=oe(ee=>ee.batchDelete);j.useEffect(()=>{const ee=xe=>{if(!ye.getState().confirmRequest&&!(vt&&!((xe.metaKey||xe.ctrlKey)&&xe.key==="f"))){if((xe.metaKey||xe.ctrlKey)&&xe.key==="z"&&(xe.shiftKey?(xe.preventDefault(),l()):(xe.preventDefault(),s())),(xe.metaKey||xe.ctrlKey)&&xe.key==="f"){xe.preventDefault(),C(!0);return}{const _e=xe.target;if(!(_e.tagName==="INPUT"||_e.tagName==="TEXTAREA"||_e.isContentEditable)&&Zt&&!ze&&!xe.metaKey&&!xe.ctrlKey&&!xe.altKey){const{nodes:Se,edges:Ye}=oe.getState();if(xe.key===" "){xe.preventDefault(),oe.getState().toggleCollapse(Zt);return}if(xe.key==="r"||xe.key==="R"){xe.preventDefault(),oe.getState().rerunNode(Zt,{});return}if(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(xe.key)){const Ze=Ye.filter(Mt=>!Mt.data?.isCrossLink);let bt;if(xe.key==="ArrowUp")bt=Ze.find(Mt=>Mt.target===Zt)?.source;else if(xe.key==="ArrowDown")bt=Ze.find(Mt=>Mt.source===Zt)?.target;else{const Mt=Ze.find(kn=>kn.target===Zt),Ht=Mt?Ze.filter(kn=>kn.source===Mt.source).map(kn=>kn.target):Se.filter(kn=>!Ze.some(Rn=>Rn.target===kn.id)).map(kn=>kn.id),ca=Ht.indexOf(Zt);ca!==-1&&Ht.length>1&&(bt=Ht[(ca+(xe.key==="ArrowRight"?1:Ht.length-1))%Ht.length])}if(bt){xe.preventDefault(),d(bt);const Mt=Se.find(Ht=>Ht.id===bt);Mt&&be(Mt,{zoom:1,duration:300})}return}}}if(xe.key==="Escape"){const _e=xe.target;if(_e.tagName==="INPUT"||_e.tagName==="TEXTAREA"||_e.isContentEditable)return;ce.length>1?h([]):Zt&&d(null);return}if(xe.key==="Delete"||xe.key==="Backspace"){const _e=xe.target;if(_e.tagName==="INPUT"||_e.tagName==="TEXTAREA"||_e.isContentEditable)return;if(ce.length>1)xe.preventDefault(),Es({title:Ie("confirm.deleteNodesTitle"),message:qe(Ie("confirm.deleteNodes"),{n:ce.length}),confirmLabel:Ie("common.delete"),danger:!0}).then(Ue=>{Ue&&On(ce)});else{const Ue=t.filter(Se=>Se.selected).map(Se=>Se.id);Ue.length>0&&(xe.preventDefault(),qn(Ue))}}}};return window.addEventListener("keydown",ee),()=>window.removeEventListener("keydown",ee)},[s,l,Zt,ce,d,h,On,t,qn,ze,be]);const Mn=()=>{w.trim()&&(r(w.trim(),{rolePrompt:O.trim()||void 0,initialAttachments:H.length>0?H:void 0}),_(""),D(""),N(!1),Y([]))},pe=async ee=>{for(const xe of Array.from(ee))await Xd(xe,{add:_e=>Y(Ue=>[...Ue,_e]),update:(_e,Ue)=>Y(Se=>Se.map(Ye=>Ye.id===_e?{...Ye,...Ue}:Ye))})},Qe=ee=>{ee.key==="Enter"&&!ee.shiftKey&&!Ya(ee)&&(ee.preventDefault(),Mn())},At=j.useCallback(({nodes:ee})=>{const xe=ee.map(_e=>_e.id);xe.length>1?h(xe):xe.length===1&&d(xe[0])},[d,h]),Nt=j.useMemo(()=>e.filter(ee=>ee.data.stepKind==="frame"),[e]),[lt,Lt]=j.useState(!1),Jt=j.useRef(null);j.useEffect(()=>{if(!lt)return;const ee=xe=>{Jt.current?.contains(xe.target)||Lt(!1)};return window.addEventListener("mousedown",ee),()=>window.removeEventListener("mousedown",ee)},[lt]);const[Xt,Cn]=j.useState(!1),[he,jt]=j.useState(0),dn=ye(ee=>ee.searchHitIds!==null),En=j.useRef(null);j.useEffect(()=>{if(!Xt)return;const ee=xe=>{En.current?.contains(xe.target)||Cn(!1)};return window.addEventListener("mousedown",ee),()=>window.removeEventListener("mousedown",ee)},[Xt]);const mn=ye(ee=>ee.searchHitIds),zn=j.useMemo(()=>{if(!Zt||ce.length>1||!e.some(Ze=>Ze.id===Zt))return null;const ee=cm(Zt,e,t),xe=new Set;for(const Ze of ee.mainline)Ze.id!==Zt&&xe.add(Ze.id);for(const Ze of ee.materials)xe.add(Ze.id);for(const Ze of ee.references)xe.add(Ze.source.id);const _e=t.filter(Ze=>!Ze.data?.isCrossLink),Ue=Br(Zt,e,_e).visitedEdgeIds,Se=new Set(ee.references.map(Ze=>Ze.edge.id)),Ye=_e.filter(Ze=>Ze.source===Zt);return{ctx:xe,down:new Set(Ye.map(Ze=>Ze.target)),pathEdgeIds:Ue,refEdgeIds:Se,downEdgeIds:new Set(Ye.map(Ze=>Ze.id))}},[Zt,ce,e,t]),kr=j.useMemo(()=>{let ee=e;return E&&(ee=ee.map(xe=>{const _e=xe.data.stepKind,Ue=Wf(_e)&&!t.some(Se=>Se.source===xe.id||Se.target===xe.id);return _e==="frame"||Ue?{...xe,hidden:!0}:xe})),mn!==null&&(ee=ee.map(xe=>mn.has(xe.id)||xe.data.stepKind==="frame"?{...xe,className:"search-hit"}:xe.className==="search-hit"?{...xe,className:void 0}:xe)),zn&&(ee=ee.map(xe=>{const _e=xe.id===Zt?"target":zn.ctx.has(xe.id)?"ctx":zn.down.has(xe.id)?"down":xe.data.stepKind==="frame"?void 0:"dim";return _e?{...xe,className:[xe.className,`focus-${_e}`].filter(Boolean).join(" "),..._e!=="dim"?{data:{...xe.data,focusRole:_e}}:{}}:xe})),ee},[e,t,E,mn,zn,Zt]),Ur=j.useMemo(()=>{const ee=t.map(Ue=>{const Se=Ue.data?.isBranchFromSelection?{...Ue,animated:!1,style:{...Ue.style,strokeDasharray:void 0}}:Ue,Ye=typeof Se.style?.stroke=="string"?NE[Se.style.stroke.toUpperCase()]:void 0,Ze=Se.markerEnd&&typeof Se.markerEnd=="object"?Se.markerEnd:void 0,bt=typeof Ze?.color=="string"?NE[Ze.color.toUpperCase()]:void 0;return!Ye&&!bt?Se:{...Se,...Ye?{style:{...Se.style,stroke:me[Ye]}}:{},...bt&&Ze?{markerEnd:{...Ze,color:me[bt]}}:{}}});if(zn)return ee.map(Ue=>zn.pathEdgeIds.has(Ue.id)?{...Ue,className:"focus-e-path",style:{...Ue.style,stroke:me.accent,strokeWidth:3.5,opacity:1},markerEnd:{type:"arrowclosed",...Ue.markerEnd&&typeof Ue.markerEnd=="object"?Ue.markerEnd:{},color:me.accent},zIndex:10,data:{...Ue.data,focusRole:"path"}}:zn.refEdgeIds.has(Ue.id)?{...Ue,style:{...Ue.style,opacity:.9},zIndex:5,data:{...Ue.data,focusRole:"ref"}}:zn.downEdgeIds.has(Ue.id)?{...Ue,className:"focus-e-down",style:{...Ue.style,strokeWidth:2.5,opacity:.85},markerEnd:{type:"arrowclosed",...Ue.markerEnd&&typeof Ue.markerEnd=="object"?Ue.markerEnd:{}},zIndex:5,data:{...Ue.data,focusRole:"down"}}:{...Ue,style:{...Ue.style,strokeWidth:1.5,opacity:.2},zIndex:0});const xe=ce.length>1?ce:[];if(xe.length===0)return ee;const{visitedEdgeIds:_e}=Br(xe,e,t);return ee.map(Ue=>_e.has(Ue.id)?{...Ue,style:{...Ue.style,stroke:me.trace,strokeWidth:3.5,opacity:1},markerEnd:{type:"arrowclosed",...Ue.markerEnd&&typeof Ue.markerEnd=="object"?Ue.markerEnd:{},color:me.trace},zIndex:10}:{...Ue,style:{...Ue.style,strokeWidth:1.5,opacity:.2},zIndex:0})},[e,t,ce,me,zn]);return j.useEffect(()=>{if(!mt||!Zt)return;const ee=setTimeout(()=>{const xe=F.current;if(!xe)return;const _e=oe.getState().nodes.find(bt=>bt.id===Zt);if(!_e)return;const Ue=xe.getViewport(),Se=_e.measured?.width??_e.width??480,Ye=(_e.position.x+Se)*Ue.zoom+Ue.x,Ze=window.innerWidth-ye.getState().panelWidth-ad-24;if(Ye>Ze){const bt=(_e.position.x+Se/2)*Ue.zoom+Ue.x;xe.setViewport({...Ue,x:Ue.x-(bt-Ze/2)},{duration:300})}},60);return()=>clearTimeout(ee)},[mt,Zt]),u.jsxs("div",{className:"relative w-full h-full","data-searching":dn||void 0,children:[u.jsxs("div",{className:"relative h-full w-full",onDoubleClick:ee=>{ee.target.classList.contains("react-flow__pane")&&!ze&&zt(se({x:ee.clientX,y:ee.clientY}))},onDragOver:ee=>{(ee.dataTransfer.types.includes("application/thoughtdag-content")||ee.dataTransfer.types.includes("Files"))&&(ee.preventDefault(),ee.dataTransfer.dropEffect="copy",!G&&!ze&&q(!0))},onDrop:ee=>{if(vt)return;const xe=ee.target;if(!G&&!ze&&ee.dataTransfer.files.length>0){ee.preventDefault(),q(!1),We(ee.dataTransfer.files);return}const _e=xe.closest?.(".react-flow__node"),Ue=_e&&oe.getState().nodes.find(Ze=>Ze.id===_e.getAttribute("data-id"))?.data.stepKind==="frame";if(!xe.classList?.contains("react-flow__pane")&&!Ue)return;const Se=se({x:ee.clientX,y:ee.clientY}),Ye=ee.dataTransfer.getData("application/thoughtdag-content");if(Ye==="ask"){ee.preventDefault(),zt(Se);return}if(Ye==="frame"){ee.preventDefault(),at(Se);return}if(Ye==="note"||Ye==="file"){ee.preventDefault(),Qr(Ye,Se);return}if(ee.dataTransfer.files.length>0){ee.preventDefault();const Ze=wt(ee.dataTransfer.files);if(Ze.length===0)return;const bt=Qr("file",Se);fd(bt,Ze)}},children:[u.jsxs(ML,{onInit:ee=>{F.current=ee,EN.current=ee;const xe=ye.getState().arrivalFocusNodeId;if(xe){ye.getState().setArrivalFocusNodeId(null);const _e=oe.getState().nodes.find(Ue=>Ue.id===xe);_e&&window.setTimeout(()=>{ee.setCenter(_e.position.x+260,_e.position.y+140,{zoom:.9,duration:400})},150)}},nodes:kr,edges:Ur,onNodesChange:ge,onEdgesChange:Ve,onNodeDragStart:xt,onNodeDrag:St,onNodeDragStop:Ft,onConnect:Qa,onConnectStart:Jn,onConnectEnd:ja,onEdgeContextMenu:wa,onNodeContextMenu:an,nodeTypes:wae,edgeTypes:Eae,deleteKeyCode:null,fitView:!0,onlyRenderVisibleElements:!0,minZoom:.04,maxZoom:2,defaultEdgeOptions:{type:"smoothstep",animated:!1,style:{stroke:me.accent,strokeWidth:2},markerEnd:{type:"arrowclosed",color:me.accent,width:18,height:18}},snapToGrid:W==="grid",snapGrid:[22,22],proOptions:{hideAttribution:!0},nodeDragThreshold:5,connectionRadius:40,selectionMode:Sc.Partial,selectionOnDrag:!vt,nodesDraggable:!vt,nodesConnectable:!vt,panOnDrag:vt?!0:[1,2],zoomOnDoubleClick:!1,connectionLineStyle:{stroke:me.accent,strokeDasharray:"8 4",strokeWidth:2},onSelectionChange:At,onPaneClick:()=>{d(null),h([]),vn(null)},children:[W==="grid"?u.jsxs(u.Fragment,{children:[u.jsx(Jg,{id:"grid-fine",variant:pi.Lines,gap:22,color:"var(--canvas-grid-fine)"}),u.jsx(Jg,{id:"grid-major",variant:pi.Lines,gap:110,color:"var(--canvas-grid-major)"})]}):u.jsx(Jg,{variant:pi.Dots,gap:24,size:1,color:"var(--canvas-dot)"}),u.jsx(Aae,{}),u.jsx(Sae,{panelShiftWidth:mt?wn:0}),u.jsx(gae,{}),u.jsx(FL,{position:"bottom-left"}),e.length>0&&u.jsx(tj,{nodeColor:ee=>{const xe=ee.data;if(xe.archived)return ke.archived;const _e=xe.stepKind;return _e==="note"?"#D97706":_e==="file"||_e==="link"?"#64748B":Array.isArray(xe.condensedFrom)&&xe.condensedFrom.length?"#8B7CF0":xe.isRoot?me.accent:xe.isBranch?me.warm:ke.ordinary},maskColor:ke.mask,style:{width:200,height:140},pannable:!0,zoomable:!0,position:"bottom-right"})]}),!G&&ze&&u.jsx("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:u.jsxs("div",{className:"text-center pointer-events-auto",children:[u.jsx("p",{className:"text-sm text-ink-muted mb-1 font-medium",children:b("paradigm.emptyTitle")}),u.jsx("p",{className:"text-xs text-ink-faint mb-4 max-w-sm leading-relaxed",children:b("paradigm.emptyHint")}),u.jsxs("div",{className:"flex items-center justify-center gap-2",children:[u.jsxs("button",{onClick:()=>Xe("human"),className:"text-sm border-2 border-dashed border-warm/60 text-warm hover:bg-warm/10 px-4 py-2.5 rounded-xl transition-colors flex items-center gap-1.5",children:[u.jsx(af,{size:15,strokeWidth:1.75})," ",b("paradigm.addHuman")]}),u.jsxs("button",{onClick:()=>Xe("prompt"),className:"text-sm border-2 border-dashed border-accent/50 text-accent hover:bg-accent/10 px-4 py-2.5 rounded-xl transition-colors flex items-center gap-1.5",children:[u.jsx(Ad,{size:15,strokeWidth:1.75})," ",b("paradigm.addPrompt")]})]})]})}),vt&&!G&&u.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:u.jsx("div",{className:"text-center max-w-[420px] px-6",children:ft?u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"text-3xl mb-3",children:"🔗"}),u.jsx("div",{className:"text-sm font-semibold text-ink mb-1.5",children:b("viewer.loadError")}),u.jsx("p",{className:"text-xs text-ink-muted leading-relaxed",children:b("viewer.loadErrorHint")})]}):u.jsxs("div",{className:"flex items-center gap-2 text-sm text-ink-muted justify-center",children:[u.jsx(Xn,{size:16,strokeWidth:1.75,className:"animate-spin text-accent"})," ",b("viewer.loading")]})})}),!G&&!ze&&!vt&&u.jsxs("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none overflow-hidden",children:[u.jsxs("svg",{className:"absolute -left-10 top-[8%] w-[360px] h-[300px] opacity-[0.35] pointer-events-none",viewBox:"0 0 360 300","aria-hidden":!0,children:[u.jsx("path",{d:"M80 40 C80 90 80 90 80 130 M80 170 C80 210 80 210 80 250",stroke:nt.line,strokeWidth:"2",fill:"none"}),u.jsx("path",{d:"M95 150 C150 150 150 90 205 88",stroke:nt.line,strokeWidth:"2",strokeDasharray:"6 5",fill:"none"}),u.jsx("circle",{cx:"80",cy:"30",r:"7",fill:nt.line}),u.jsx("circle",{cx:"80",cy:"150",r:"7",fill:"none",stroke:nt.line,strokeWidth:"2.5"}),u.jsx("circle",{cx:"80",cy:"262",r:"7",fill:nt.line}),u.jsx("circle",{cx:"218",cy:"88",r:"7",fill:nt.line})]}),u.jsxs("svg",{className:"absolute right-[-30px] bottom-[10%] w-[320px] h-[280px] opacity-[0.35] pointer-events-none",viewBox:"0 0 320 280","aria-hidden":!0,children:[u.jsx("path",{d:"M240 30 C240 80 240 80 240 120 M240 160 C240 200 240 200 240 240",stroke:nt.line,strokeWidth:"2",fill:"none"}),u.jsx("path",{d:"M225 140 C170 140 170 210 115 212",stroke:nt.line,strokeWidth:"2",strokeDasharray:"6 5",fill:"none"}),u.jsx("circle",{cx:"240",cy:"20",r:"7",fill:nt.line}),u.jsx("circle",{cx:"240",cy:"140",r:"7",fill:"none",stroke:nt.line,strokeWidth:"2.5"}),u.jsx("circle",{cx:"240",cy:"252",r:"7",fill:nt.line}),u.jsx("circle",{cx:"102",cy:"212",r:"7",fill:nt.line})]}),u.jsxs("div",{className:"pointer-events-auto w-[560px] animate-fade-in relative",children:[u.jsxs("div",{className:"text-center mb-8",children:[u.jsxs("svg",{width:"52",height:"52",viewBox:"0 0 44 44",className:"mx-auto mb-4","aria-hidden":!0,children:[u.jsx("circle",{className:"dag-pop",style:{animationDelay:"0.05s"},cx:"22",cy:"7",r:"3.5",fill:nt.accent}),u.jsx("line",{className:"dag-pop",style:{animationDelay:"0.2s"},x1:"22",y1:"11",x2:"22",y2:"19",stroke:nt.accent,strokeWidth:"2",strokeLinecap:"round"}),u.jsx("circle",{className:"dag-pop",style:{animationDelay:"0.35s"},cx:"22",cy:"22",r:"3.5",fill:"none",stroke:nt.accent,strokeWidth:"2.5"}),u.jsx("line",{className:"dag-pop",style:{animationDelay:"0.5s"},x1:"22",y1:"25",x2:"22",y2:"33",stroke:nt.accent,strokeWidth:"2",strokeLinecap:"round"}),u.jsx("circle",{className:"dag-pop",style:{animationDelay:"0.65s"},cx:"22",cy:"37",r:"3.5",fill:nt.accent,opacity:"0.35"}),u.jsx("line",{className:"dag-pop",style:{animationDelay:"0.8s"},x1:"25.5",y1:"23.5",x2:"33",y2:"28.5",stroke:nt.warm,strokeWidth:"2",strokeLinecap:"round",strokeDasharray:"3 3"}),u.jsx("circle",{className:"dag-pop",style:{animationDelay:"0.95s"},cx:"36",cy:"30",r:"3.5",fill:nt.warm})]}),u.jsx("h1",{className:"text-4xl font-semibold tracking-tight text-ink mb-2.5",children:"ThoughtDAG"}),u.jsx("p",{className:"text-sm text-ink-muted",children:b("landing.tagline")}),u.jsx("p",{className:"text-xs text-ink-muted mt-1.5 font-medium",children:b("landing.mechanism")})]}),u.jsxs("div",{className:"bg-card border border-line rounded-xl px-5 py-4 shadow-lg transition-all focus-within:border-accent/50 focus-within:shadow-xl",children:[u.jsx("textarea",{value:w,onChange:ee=>_(ee.target.value),onKeyDown:Qe,onPaste:ee=>{if(ee.clipboardData.getData("text/plain").trim())return;const xe=Array.from(ee.clipboardData.items).filter(_e=>_e.kind==="file").map(_e=>_e.getAsFile()).filter(Boolean);xe.length&&pe(xe)},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}),H.length>0&&u.jsx("div",{className:"flex flex-wrap gap-2 mt-2 pb-1",children:H.map(ee=>u.jsxs("div",{className:"flex items-center gap-1.5 bg-wash rounded-lg px-2.5 py-1.5 group",children:[ee.thumbnailUrl?u.jsx("img",{src:ee.thumbnailUrl,className:"w-6 h-6 rounded object-cover",alt:ee.name}):u.jsx("span",{className:"text-xs",children:u.jsx(gi,{size:16,strokeWidth:1.75})}),u.jsx("span",{className:"text-xs text-ink-muted max-w-[100px] truncate",children:ee.name}),ee.isExtracting&&u.jsx("span",{className:"text-2xs text-accent",children:u.jsx(Xn,{className:"animate-spin",size:12,strokeWidth:1.75})}),ee.numPages!=null&&u.jsxs("span",{className:"text-2xs text-ink-faint",children:[ee.numPages,"p"]}),u.jsx("button",{onClick:()=>Y(xe=>xe.filter(_e=>_e.id!==ee.id)),className:"text-ink-faint hover:text-red-500 text-xs opacity-0 group-hover:opacity-100 transition-opacity",children:u.jsx(bn,{size:14,strokeWidth:1.75})})]},ee.id))}),M&&u.jsxs("div",{className:"space-y-1 mt-2",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx("span",{className:"text-xs text-ink-muted font-medium",children:b("landing.roleLabel")}),u.jsx("button",{onClick:()=>{N(!1),D("")},className:"text-xs text-ink-faint hover:text-ink-muted",children:u.jsx(bn,{size:14,strokeWidth:1.75})})]}),u.jsx("textarea",{value:O,onChange:ee=>D(ee.target.value),placeholder:b("landing.rolePlaceholder"),className:"w-full text-xs border border-line rounded-lg px-3 py-2 focus:outline-none focus:ring-1 focus:ring-accent bg-surface resize-none leading-relaxed",rows:2,autoFocus:!0}),u.jsx(vN,{onPick:D})]}),u.jsxs("div",{className:"flex items-center justify-end mt-2 gap-2",children:[u.jsx(Bb,{}),u.jsx("button",{onClick:()=>N(!M),title:b("landing.roleTrayTitle"),className:`rounded-full w-8 h-8 flex items-center justify-center transition-colors shrink-0 ${M||O?"text-accent bg-accent/10 hover:bg-accent/20":"text-ink-faint hover:text-ink-muted hover:bg-line"}`,children:u.jsx(sP,{size:16,strokeWidth:1.75})}),u.jsx("button",{onClick:()=>K.current?.click(),className:"text-ink-faint hover:text-accent hover:bg-wash rounded-xl px-3 py-2 transition-colors text-sm",title:b("landing.attach"),children:u.jsx(xi,{size:16,strokeWidth:1.75})}),u.jsx("input",{ref:K,type:"file",multiple:!0,accept:Cd,className:"hidden",onChange:ee=>{pe(ee.target.files||[]),ee.target.value=""}}),u.jsx("button",{onClick:Mn,disabled:!w.trim()||H.some(ee=>ee.isExtracting),className:"bg-accent hover:bg-accent-strong disabled:opacity-30 disabled:cursor-not-allowed text-white text-sm px-5 py-2 rounded-xl transition-all",children:H.some(ee=>ee.isExtracting)?b("landing.extracting"):b("landing.send")})]})]}),u.jsxs("div",{onClick:()=>U.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(To,{size:15,strokeWidth:1.75,className:"text-accent"})," ",b("landing.docStart")]}),u.jsx("p",{className:"text-2xs text-ink-faint mt-1.5",children:b("landing.docFormats")}),u.jsx("p",{className:"text-2xs text-ink-faint mt-0.5",children:b("landing.docPrivacy")})]}),!!window.desktopSessions&&u.jsxs("button",{onClick:()=>B(!0),className:"w-full mt-3 bg-card/60 backdrop-blur border border-line rounded-xl px-5 py-3.5 hover:border-accent/40 hover:bg-accent/5 transition-all text-center","data-landing-atlas":!0,children:[u.jsxs("div",{className:"flex items-center justify-center gap-2 text-sm text-ink-muted font-medium",children:[u.jsx(Ij,{size:15,strokeWidth:1.75,className:"text-accent shrink-0"}),u.jsx("span",{children:b("landing.atlasStart")}),u.jsx(Sj,{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:U,type:"file",multiple:!0,accept:Cd,className:"hidden",onChange:ee=>{We(ee.target.files||[]),ee.target.value=""}}),R&&u.jsx(_N,{onClose:()=>B(!1),onSwitched:()=>{B(!1),kt()}}),(!rt||(rt.models?.length??0)===0)&&u.jsxs("div",{className:"mt-3 bg-card/60 backdrop-blur border border-line rounded-xl px-5 py-3.5 text-center","data-quick-connect":!0,children:[u.jsxs("div",{className:"flex items-center justify-center gap-2 text-sm text-ink-muted font-medium",children:[u.jsx(Sd,{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:[Le==="zh"&&u.jsx("button",{onClick:()=>{ye.getState().setApiKeyPresetHint("zhipu"),ye.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:()=>{IN()},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:()=>ye.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:()=>ye.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:Pi,title:"landing.feature1.title",desc:"landing.feature1.desc"},{icon:B5,title:"landing.feature2.title",desc:"landing.feature2.desc"},{icon:r7,title:"landing.feature3.title",desc:"landing.feature3.desc"}].map(({icon:ee,title:xe,desc:_e})=>u.jsxs("div",{className:"bg-card/60 backdrop-blur border border-line rounded-xl px-4 py-3.5",children:[u.jsx(ee,{size:16,strokeWidth:1.75,className:"text-accent mb-2"}),u.jsx("h3",{className:"text-xs font-semibold text-ink mb-1",children:b(xe)}),u.jsx("p",{className:"text-2xs text-ink-faint leading-relaxed",children:b(_e)})]},xe))}),u.jsxs("div",{className:"text-center mt-6 flex items-center justify-center gap-5",children:[u.jsxs("button",{onClick:ot,className:"text-xs text-accent hover:text-accent-strong font-medium transition-colors inline-flex items-center gap-1.5",children:[u.jsx(B5,{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(R5,{size:14,strokeWidth:1.75})," ",b("landing.howItWorks")]})]})]})]}),!vt&&u.jsx(xne,{onSwitched:kt}),(G||ze)&&!vt&&u.jsxs("div",{className:"absolute top-[38%] -translate-y-1/2 left-4 z-10 flex flex-col gap-1.5 bg-card/90 backdrop-blur border border-line rounded-xl p-1.5 shadow-sm",children:[!ze&&u.jsx("button",{onClick:()=>zt(se(null)),draggable:!0,onDragStart:ee=>{ee.dataTransfer.setData("application/thoughtdag-content","ask"),ee.dataTransfer.effectAllowed="copy"},title:b("palette.askTitle"),className:"w-9 h-9 rounded-lg flex items-center justify-center text-accent hover:bg-accent/10 transition-colors cursor-grab",children:u.jsx(af,{size:17,strokeWidth:1.75})}),u.jsx("button",{onPointerDown:ee=>Bt(ee,xe=>Qr("note",se(xe))),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(Bi,{size:17,strokeWidth:1.75})}),u.jsx("button",{onPointerDown:ee=>Bt(ee,xe=>Qr("file",se(xe))),title:b("palette.fileTitle"),className:"w-9 h-9 rounded-lg flex items-center justify-center text-ink-muted hover:bg-wash transition-colors",children:u.jsx(xi,{size:17,strokeWidth:1.75})}),u.jsx("button",{onPointerDown:ee=>Bt(ee,xe=>at(se(xe))),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(vx,{size:17,strokeWidth:1.75})})]}),vt&&u.jsxs("div",{className:"absolute top-4 z-10 flex gap-1.5 items-center transition-[right] duration-200",style:{right:mt?wn+ad+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(kd,{size:14,strokeWidth:1.75})," ",b("viewer.badge")]}),u.jsx("button",{onClick:()=>C(!0),className:"bg-card/90 backdrop-blur border border-line rounded-lg w-8 h-8 flex items-center justify-center shadow-sm hover:bg-wash transition-colors text-ink-muted hover:text-accent",title:b("search.entryTitle"),"data-search-entry":!0,children:u.jsx(Af,{size:15,strokeWidth:1.75})}),u.jsx(ZE,{}),u.jsx("button",{onClick:()=>of(),className:"bg-card/90 backdrop-blur border border-line rounded-lg w-8 h-8 flex items-center justify-center shadow-sm hover:bg-wash transition-colors text-ink-muted hover:text-accent",title:b("viewer.downloadJson"),children:u.jsx(Ed,{size:15,strokeWidth:1.75})}),u.jsx("a",{href:"https://github.com/chenxiachan/thoughtdag",target:"_blank",rel:"noreferrer",className:"bg-ink text-white rounded-lg h-8 px-3 flex items-center gap-1.5 shadow-sm hover:bg-ink/85 transition-colors text-xs font-medium",children:b("viewer.openApp")})]}),!vt&&u.jsxs("div",{className:"absolute top-4 z-10 flex gap-1.5 items-center transition-[right] duration-200",style:{right:mt?wn+ad+12:16},children:[ze&&u.jsxs(u.Fragment,{children:[u.jsxs("button",{onClick:()=>Xe("human"),className:"bg-card/90 backdrop-blur border border-warm/40 rounded-lg h-8 px-3 flex items-center gap-1.5 shadow-sm hover:bg-warm/10 transition-colors text-warm text-xs font-medium",children:[u.jsx(af,{size:14,strokeWidth:1.75})," ",b("paradigm.addHuman")]}),u.jsxs("button",{onClick:()=>Xe("prompt"),className:"bg-card/90 backdrop-blur border border-accent/40 rounded-lg h-8 px-3 flex items-center gap-1.5 shadow-sm hover:bg-accent/10 transition-colors text-accent text-xs font-medium",children:[u.jsx(Ad,{size:14,strokeWidth:1.75})," ",b("paradigm.addPrompt")]}),u.jsxs("button",{onClick:()=>{He()},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")]})]}),!ze&&u.jsx(wN,{}),!G&&u.jsx("button",{onClick:()=>ye.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(Sd,{size:15,strokeWidth:1.75})}),It>0&&!ze&&u.jsxs("button",{onClick:()=>{const{nodes:ee,edges:xe,staleIds:_e}=oe.getState(),Ue=_e.reduce((Se,Ye)=>{const Ze=ee.map(Ht=>Ht.id===Ye?{...Ht,data:{...Ht.data,question:"",response:""}}:Ht),{layerTokens:bt}=yr(Ye,Ze,xe),Mt=ee.find(Ht=>Ht.id===Ye)?.data.question??"";return Se+bt.material+bt.reference+bt.chain+$n(Mt)},0);Es({title:b("replay.confirmTitle"),message:qe(b("replay.confirmMsg"),{n:It,tok:Ue.toLocaleString()}),confirmLabel:b("replay.confirmBtn")}).then(Se=>{Se&&oe.getState().replayStale()})},className:"bg-amber-500/10 backdrop-blur border border-amber-500/40 rounded-lg h-8 px-3 flex items-center gap-1.5 shadow-sm hover:bg-amber-500/20 transition-colors text-amber-600 text-xs font-medium",title:b("replay.chipTitle"),children:[u.jsx(VP,{size:14,strokeWidth:1.75})," ",It]}),G&&Nt.length>0&&u.jsxs("div",{ref:Jt,className:"relative",children:[u.jsx("button",{onClick:()=>Lt(ee=>!ee),className:`bg-card/90 backdrop-blur border rounded-lg w-8 h-8 flex items-center justify-center shadow-sm transition-colors ${lt?"border-accent/40 text-accent":"border-line text-ink-faint hover:bg-wash"}`,title:b("toolbar.frames"),children:u.jsx(vx,{size:15,strokeWidth:1.75})}),lt&&u.jsx("div",{className:"absolute right-0 top-full mt-1.5 bg-card border border-line rounded-xl shadow-lg py-1 w-[230px] max-h-[320px] overflow-y-auto z-30 animate-fade-in",children:Nt.map(ee=>u.jsxs("button",{onClick:()=>{Lt(!1),F.current?.fitBounds({x:ee.position.x,y:ee.position.y,width:ee.width??640,height:ee.height??420},{duration:400,padding:.15})},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2",children:[u.jsx("span",{className:`w-2.5 h-2.5 rounded-sm shrink-0 ${(nd[ee.data.frameColor??"gray"]??nd.gray).dot}`}),u.jsx("span",{className:"truncate",children:ee.data.question||b("frame.untitled")})]},ee.id))})]}),G&&u.jsx("button",{onClick:()=>C(!0),className:"bg-card/90 backdrop-blur border border-line rounded-lg w-8 h-8 flex items-center justify-center shadow-sm hover:bg-wash transition-colors text-ink-faint hover:text-accent",title:b("search.entryTitle"),"data-search-entry":!0,children:u.jsx(Af,{size:15,strokeWidth:1.75})}),u.jsx(ZE,{}),G&&!ze&&u.jsx(qte,{showTrigger:!1,openPing:he,onLocate:ee=>{const xe=oe.getState().nodes.find(_e=>_e.id===ee);xe&&(d(ee),be(xe,{zoom:1}))}}),je&&!vt&&u.jsxs("button",{onClick:()=>ye.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:qe(b("condense.entryBuilding"),{i:String(Oe.current),n:String(Oe.total)}),"data-condense-entry":!0,children:[u.jsx(Xn,{size:14,strokeWidth:1.75,className:"animate-spin"}),u.jsxs("span",{className:"text-2xs font-mono",children:[Oe.current,"/",Oe.total]})]}),Om&&u.jsx("button",{onClick:()=>ye.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(X8,{size:15,strokeWidth:1.75})}),u.jsxs("div",{ref:En,className:"relative",children:[u.jsx("button",{onClick:()=>Cn(ee=>!ee),className:`bg-card/90 backdrop-blur border rounded-lg w-8 h-8 flex items-center justify-center shadow-sm transition-colors ${Xt?"border-accent/40 text-accent":"border-line text-ink-faint hover:bg-wash"}`,title:b("toolbar.more"),"data-toolbar-more":!0,children:u.jsx(G8,{size:15,strokeWidth:1.75})}),Xt&&u.jsxs("div",{className:"absolute right-0 top-full mt-1.5 bg-card border border-line rounded-xl shadow-lg py-1 w-[220px] z-30 animate-fade-in",children:[G&&u.jsxs("button",{onClick:()=>{Cn(!1),T(!E)},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(E?"toolbar.showAnnotations":"toolbar.hideAnnotations"),children:[u.jsx(Bi,{size:14,strokeWidth:1.75,className:`shrink-0 ${E?"text-accent":"text-ink-faint"}`})," ",b(E?"toolbar.menuAnnotationsShow":"toolbar.menuAnnotationsHide")]}),G&&u.jsxs("button",{onClick:()=>{Cn(!1),Es({title:b("confirm.relayoutTitle"),message:b("confirm.relayoutMsg"),confirmLabel:b("toolbar.relayout")}).then(ee=>{ee&&(x(),setTimeout(()=>F.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(HP,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("toolbar.relayout")]}),X>0&&u.jsxs("button",{onClick:()=>{Cn(!1),ye.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(Td,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",qe(b("hlov.entry"),{n:X})]}),P>0&&u.jsxs("button",{onClick:()=>{Cn(!1),ye.getState().setMaterialsOverviewOpen(!0)},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5",title:b("matov.entryTitle"),"data-matov-entry":!0,children:[u.jsx(xi,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",qe(b("matov.entry"),{n:P})]}),G&&u.jsx("div",{className:"border-t border-line/60 my-1"}),G&&!ze&&!vt&&u.jsxs("button",{onClick:()=>{Cn(!1),ye.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(om,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("condense.title"),"…"]}),G&&!ze&&u.jsxs("button",{onClick:()=>{Cn(!1),jt(ee=>ee+1)},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5",title:b("toolbar.diagnose"),"data-menu-diagnose":!0,children:[u.jsx(i7,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("toolbar.menuDiagnose")]}),G&&!ze&&u.jsxs("button",{onClick:()=>{Cn(!1),(async()=>{const{nodes:ee,edges:xe}=oe.getState(),{confirmIfSensitive:_e}=await Kt(async()=>{const{confirmIfSensitive:Se}=await import("./sensitive-scan-L0rFzufE.js");return{confirmIfSensitive:Se}},[]);if(!await _e(ee))return;const Ue=await gB(ee,xe);await navigator.clipboard.writeText(Ue).catch(()=>{}),ye.getState().setShareDialogUrl(Ue)})()},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(bz,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("toolbar.menuShare")]}),G&&u.jsxs("button",{onClick:()=>{Cn(!1),ze?GH():of()},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5","data-menu-export":!0,children:[u.jsx(Ed,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b(ze?"paradigm.exportParadigm":"switcher.exportBackup")]}),ne&&u.jsxs("button",{onClick:()=>{Cn(!1),QH()},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5",title:b("toolbar.exportEventsTitle"),children:[u.jsx(gi,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("toolbar.exportEvents")]}),G&&u.jsx("div",{className:"border-t border-line/60 my-1"}),u.jsxs("div",{className:"px-3 pt-2 pb-1","data-appearance-lighting":!0,children:[u.jsx("div",{className:"text-2xs text-ink-faint mb-1.5",children:b("appearance.lighting")}),u.jsx("div",{className:"flex rounded-lg border border-line overflow-hidden text-2xs",children:[["light",b("appearance.light")],["dark",b("appearance.dark")],["system",b("appearance.system")]].map(([ee,xe],_e)=>u.jsx("button",{onClick:()=>bs.getState().setLighting(ee),className:`flex-1 px-1 py-1.5 transition-colors ${_e>0?"border-l border-line":""} ${ae===ee?"bg-accent/10 text-accent font-medium":"text-ink-muted hover:bg-wash"}`,children:xe},ee))})]}),u.jsxs("div",{className:"px-3 pt-1 pb-2","data-appearance-paper":!0,children:[u.jsx("div",{className:"text-2xs text-ink-faint mb-1.5",children:b("appearance.paper")}),u.jsx("div",{className:"flex rounded-lg border border-line overflow-hidden text-2xs",children:[["plain",b("appearance.plain")],["grid",b("appearance.grid")]].map(([ee,xe],_e)=>u.jsx("button",{onClick:()=>bs.getState().setPaper(ee),className:`flex-1 px-1 py-1.5 transition-colors ${_e>0?"border-l border-line":""} ${W===ee?"bg-accent/10 text-accent font-medium":"text-ink-muted hover:bg-wash"}`,children:xe},ee))})]}),u.jsx("div",{className:"border-t border-line/60 my-1"}),u.jsxs("button",{onClick:()=>{Cn(!1),ye.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(Oj,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("memory.managerTitle")]}),u.jsxs("button",{onClick:()=>{Cn(!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(R5,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("landing.howItWorks")]})]})]}),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(o7,{size:16,strokeWidth:1.75})}),u.jsx("button",{onClick:l,disabled:p>=m.length-1,className:"bg-card/90 backdrop-blur border border-line rounded-lg w-8 h-8 flex items-center justify-center shadow-sm hover:bg-wash transition-colors disabled:opacity-20 disabled:cursor-not-allowed",title:b("canvas.redo"),children:u.jsx(oz,{size:16,strokeWidth:1.75})})]}),Rt&&!vt&&u.jsx(Mte,{}),u.jsx(Ute,{open:A,onClose:()=>C(!1),onLocate:ee=>{const xe=oe.getState().nodes.find(_e=>_e.id===ee);xe&&(d(ee),be(xe,{zoom:1}))}}),$t&&u.jsx(Dte,{x:$t.x,y:$t.y,nodeId:$t.nodeId,onClose:()=>vn(null)}),u.jsx(Lte,{onLocate:ee=>{const xe=oe.getState().nodes.find(_e=>_e.id===ee);xe&&(d(ee),be(xe,{zoom:1}))}}),u.jsx(yae,{onLocate:ee=>{const xe=oe.getState().nodes.find(_e=>_e.id===ee);xe&&(d(ee),be(xe,{zoom:1}))}}),u.jsx(Ote,{onLocate:ee=>{const xe=oe.getState().nodes.find(_e=>_e.id===ee);xe&&(d(ee),be(xe,{zoom:1}))}}),un&&u.jsx("div",{className:"fixed z-50 bg-card border border-line rounded-xl shadow-lg py-1 min-w-[120px]",style:{left:un.x,top:un.y},children:u.jsxs("button",{onClick:()=>lr(un.edgeId),className:"w-full text-left px-4 py-2 text-sm text-red-600 hover:bg-red-50 transition-colors flex items-center gap-1.5",children:[u.jsx(Ua,{size:14,strokeWidth:1.75}),b("canvas.deleteEdge")]})})]}),u.jsx(cae,{onFocusSegment:ee=>{const xe=F.current,_e=oe.getState().nodes.filter(Ht=>ee.includes(Ht.id));if(!xe||_e.length===0)return;const Ue=_e.map(Ht=>Ht.position.x),Se=_e.map(Ht=>Ht.position.y),Ye=Math.min(...Ue),Ze=Math.min(...Se),bt=Math.max(...Ue)+520-Ye,Mt=Math.max(...Se)+240-Ze;xe.fitBounds({x:Ye,y:Ze,width:bt+700,height:Mt},{duration:350,padding:.15})}}),mt&&u.jsx(_te,{onFocusNode:ee=>{const xe=e.find(_e=>_e.id===ee);xe&&be(xe,{duration:300})}}),u.jsx(ene,{onLocate:ee=>{const xe=oe.getState().nodes.find(_e=>_e.id===ee);xe&&(d(ee),be(xe,{zoom:1}))}})]})}function Sae({panelShiftWidth:e}){const t=Qd(),n=Gt(),a=wl(),r=oe(d=>d.nodes.length),s=oe(d=>d.nodes),l=j.useMemo(()=>{let d=null,h="";for(const m of s){if(m.data.stepKind&&m.data.stepKind!=="human"&&m.data.stepKind!=="prompt")continue;const p=[m.data.lastGeneratedAt,m.data.askedAt,m.data.createdAt,...m.data.editedAts??[]].filter(Boolean).sort().pop();p&&p>h&&(h=p,d=m)}return d?{node:d,at:h}:null},[s]);if(vt||t==="work"||r<2)return null;const c=()=>{if(!l)return;ye.getState().setBeaconNodeId(null);const{node:d}=l;a.setCenter(d.position.x+260,d.position.y+110,{zoom:1,duration:1100}),window.setTimeout(()=>{oe.getState().setSelectedNodeId(d.id),ye.getState().setPanelOpen(!0),window.setTimeout(()=>{a.setCenter(d.position.x+260+$f(d.id)/2,d.position.y+110,{zoom:1,duration:300})},60)},1150),window.setTimeout(()=>{Ke("success",n("continue.arrived"),12e3,{label:n("continue.summarize"),run:()=>{kN(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:()=>ye.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(Sb,{size:16,strokeWidth:1.75})," ",n("tmap.export")]}),l&&u.jsxs("button",{onClick:c,onMouseEnter:()=>ye.getState().setBeaconNodeId(l.node.id),onMouseLeave:()=>ye.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(uz,{size:16,strokeWidth:1.75})," ",n("continue.button")]})]})}function Aae(){const e=Qd(),t=ln(n=>n.transform[2]);return j.useEffect(()=>{document.querySelector(".react-flow")?.setAttribute("data-zoom-tier",e)},[e]),j.useEffect(()=>{document.querySelector(".react-flow")?.style.setProperty("--tdag-zoom",String(t))},[t]),null}rte();const Nae="/thoughtdag/api";window.desktopSessions||lH(Nae);vt?bB():(H7(),navigator.storage?.persist&&navigator.storage.persist(),Kt(()=>Promise.resolve().then(()=>Zne),void 0).then(e=>e.bootAutoBackup()));Kt(()=>import("./update-check-D5daO3Cz.js"),[]).then(e=>e.bootUpdateCheck());window.addEventListener("hashchange",()=>{window.location.hash.startsWith("#view=")!==vt&&window.location.reload()});QC.createRoot(document.getElementById("root")).render(u.jsx(j.StrictMode,{children:u.jsx(kae,{})}));export{zd as A,nr as B,Jz as C,Mae as D,K7 as E,um as F,Lb as G,mm as H,Kt as _,Ie as a,oe as b,Nn as c,Ts as d,vt as e,qe as f,U7 as g,ks as h,Rae as i,zr as j,jc as k,fm as l,_x as m,jH as n,In as o,ni as p,RH as q,LH as r,Ao as s,Ke as t,ye as u,W7 as v,Es as w,Iae as x,_ae as y,Cae as z};
|
|
761
|
+
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 ob.set(`${n}:${a}`,x),x}function yae({onLocate:e}){const t=ye(O=>O.timelineOverviewOpen),n=ye(O=>O.setTimelineOverviewOpen),a=oe(O=>O.nodes),r=Gt(),s=x7(),l=Fa(O=>O.lang),c=j.useMemo(()=>P2(a,0),[a]),d=j.useMemo(()=>zN(a),[a]),[h,m]=j.useState(null),[p,x]=j.useState(!1),[b,y]=j.useState(!1),E=xae(d,l)??h,T=!!E&&(E.fp!==d||E.lang!==l),w=()=>{x(!0),y(!1);const{nodes:O,edges:D}=oe.getState();bae(O,D,l).then(m).catch(()=>y(!0)).finally(()=>x(!1))};if(!t)return null;const _=()=>n(!1),A=O=>O?O.slice(0,10):"",C=O=>O?new Date(O).toLocaleTimeString(s,{hour:"2-digit",minute:"2-digit"}):"—";return $a.createPortal(u.jsx("div",{className:"fixed inset-0 z-[60] bg-ink/30 backdrop-blur-sm flex items-center justify-center p-6",onClick:_,children:u.jsxs("div",{className:"bg-card rounded-2xl shadow-2xl border border-line w-[640px] max-h-[80vh] flex flex-col",onClick:O=>O.stopPropagation(),children:[u.jsxs("div",{className:"flex items-center gap-2 px-5 py-3 border-b border-line shrink-0",children:[u.jsx(J8,{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:qe(r("tlov.count"),{n:c.length})}),u.jsx("div",{className:"flex-1"}),u.jsxs("button",{onClick:()=>{_(),ye.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(Sb,{size:13,strokeWidth:1.75}),r("tmap.export")]}),u.jsx("button",{onClick:_,className:"text-ink-faint hover:text-ink w-7 h-7 rounded-lg hover:bg-wash flex items-center justify-center transition-colors",children:u.jsx(bn,{size:15,strokeWidth:1.75})})]}),u.jsxs("div",{className:"px-5 pt-3 shrink-0","data-gedankengang":!0,children:[!E&&!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(Nf,{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")}),E&&!p&&u.jsxs("div",{className:`rounded-xl bg-wash px-4 py-3 ${T?"opacity-60":""}`,children:[u.jsx("p",{className:"text-sm text-ink leading-relaxed",children:E.text}),u.jsxs("div",{className:"flex items-center gap-2 mt-1.5",children:[u.jsx("span",{className:"text-2xs text-ink-faint",children:T?r("tlov.gedankenStale"):new Date(E.at).toLocaleString(s)}),T&&u.jsx("button",{onClick:w,className:"text-2xs text-accent hover:underline",children:r("tlov.gedankenRedo")})]})]})]}),u.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-5 py-3","data-timeline-overview":!0,children:[c.length===0&&u.jsx("p",{className:"text-xs text-ink-faint italic py-2",children:r("tlov.empty")}),c.map((O,D)=>{const M=D>0?A(c[D-1].createdAt):void 0,N=A(O.createdAt),R=D===0||N!==M;return u.jsxs("div",{children:[R&&u.jsx("div",{className:"sticky top-0 bg-card text-2xs text-ink-faint font-medium pt-3 pb-1 first:pt-0",children:N||r("tlov.undated")}),u.jsxs("div",{className:"group flex items-center gap-2.5 py-1.5 border-b border-line/50 last:border-0",children:[u.jsx("span",{className:"w-2 h-2 rounded-full shrink-0",style:{background:O.color,opacity:O.archived?.35:1}}),u.jsx("span",{className:"text-2xs font-mono text-ink-faint shrink-0 w-11",children:C(O.createdAt)}),u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsxs("p",{className:`text-sm truncate ${O.archived?"text-ink-faint line-through":O.badged?"text-ink":"text-ink-muted"}`,children:[O.topic&&u.jsxs("span",{className:"font-medium text-accent",children:[O.topic," · "]}),O.label||"…"]}),O.modifiedAt&&O.modifiedAt!==O.createdAt&&u.jsxs("p",{className:"text-2xs text-ink-faint",children:[r("timeline.modified")," ",new Date(O.modifiedAt).toLocaleString(s)]})]}),u.jsx("button",{className:"shrink-0 text-2xs font-mono text-accent bg-accent/10 hover:bg-accent/20 rounded-full px-1.5 py-0.5 transition-colors opacity-0 group-hover:opacity-100",onClick:()=>{_(),e(O.id)},title:r("hlov.locateTitle"),children:r("tlov.locate")})]})]},O.id)})]})]})}),document.body)}const vae=j.memo(function(t){const n=Nn(a=>a.projects.find(r=>r.id===a.activeId)?.kind==="paradigm");return t.data?.stepKind==="frame"?u.jsx(hte,{...t}):Wf(t.data?.stepKind)?u.jsx(dte,{...t}):n?u.jsx(nte,{...t}):u.jsx(Jee,{...t})}),wae={thought:vae},Eae={smoothstep:j.memo(pte)};function kae(){const[e,t]=j.useState(vt||oe.persist.hasHydrated());return j.useEffect(()=>oe.persist.onFinishHydration(()=>t(!0)),[]),j.useEffect(()=>{if(!e||vt)return;let n;const a=()=>{clearTimeout(n),n=setTimeout(()=>{Ene()},800)},r=oe.subscribe((s,l)=>{s.nodes!==l.nodes&&a()});return a(),()=>{r(),clearTimeout(n)}},[e]),j.useEffect(()=>{ye.getState().condenseRun.status==="building"&&ye.getState().setCondenseRun({status:"idle",current:0,total:0,streaming:""})},[]),j.useEffect(()=>{if(vt)return;const n=setTimeout(()=>{kne()},6e3);return()=>clearTimeout(n)},[]),j.useEffect(()=>{if(!e||vt||localStorage.getItem("thoughtdag.tutorialDone")||oe.getState().nodes.length>0)return;const n=setTimeout(()=>ye.getState().setTutorialOpen(!0),900);return()=>clearTimeout(n)},[e]),j.useEffect(()=>{Cne()},[]),j.useEffect(()=>{vt||(Kt(()=>import("./session-handoff-C_88Qy1y.js"),[]).then(n=>n.consumeSessionHandoff()),Kt(()=>import("./live-mirror-Cil__utB.js"),[]).then(n=>n.startLiveMirror()),Kt(()=>import("./canvas-record-vunI4XSG.js"),[]).then(n=>n.startCanvasRecord()),Kt(()=>import("./canonical-DDfsxGbh.js"),[]).then(n=>n.unsubscribeOrphanedSessions()))},[]),j.useEffect(()=>{vt||Nne().then(n=>{n&&(n.status==="minted"?(Ke("success",Ie("provider.oauthMinted")),DN(n.key)):Ke("error",qe(Ie("provider.oauthFailed"),{error:n.error})))})},[]),u.jsxs(u.Fragment,{children:[e&&u.jsx(Tae,{}),u.jsx(Dne,{}),u.jsx(Rne,{}),u.jsx(Pne,{}),u.jsx(zne,{}),u.jsx(Bne,{}),u.jsx(Hne,{}),u.jsx(Une,{}),u.jsx(Yne,{}),u.jsx(Jne,{}),u.jsx(_ne,{}),u.jsx(dae,{})]})}function Tae(){const{nodes:e,edges:t,setNodes:n,setEdges:a,addQuestion:r,undo:s,redo:l,addCrossLink:c,setSelectedNodeId:d,setSelectedNodeIds:h,history:m,historyIndex:p,relayout:x}=oe(),b=Gt(),y=ye(ee=>ee.setTutorialOpen),E=ye(ee=>ee.annotationsHidden),T=ye(ee=>ee.setAnnotationsHidden),[w,_]=j.useState(""),[A,C]=j.useState(!1),[O,D]=j.useState(""),[M,N]=j.useState(!1),[R,B]=j.useState(!1),[H,Y]=j.useState([]),[Z,q]=j.useState(!1),K=j.useRef(null),U=j.useRef(null),G=e.length>0,ne=oe(ee=>ee.events.length>0),X=oe(ee=>ee.nodes.reduce((xe,_e)=>xe+(_e.data.highlights?.length??0),0)),P=oe(ee=>ee.nodes.reduce((xe,_e)=>xe+(_e.data.attachments?.length??0)+(["note","link"].includes(_e.data.stepKind??"")?1:0),0)),F=j.useRef(null),J=ye(ee=>ee.arrivalFocusNodeId);j.useEffect(()=>{if(!J)return;const ee=oe.getState().nodes.find(xe=>xe.id===J);ee&&(ye.getState().setArrivalFocusNodeId(null),window.setTimeout(()=>{F.current?.setCenter(ee.position.x+260,ee.position.y+140,{zoom:.9,duration:400})},150))},[J]);const W=bs(ee=>ee.paper),ae=bs(ee=>ee.lighting),ve=bs(ee=>ee.resolved),me=j.useMemo(()=>ite(),[ve]),ke=j.useMemo(()=>{const ee=getComputedStyle(document.documentElement),xe=(ee.getPropertyValue("--color-surface").trim()||"#FAF9F7").replace("#",""),[_e,Ue,Se]=[0,2,4].map(Ye=>parseInt(xe.slice(Ye,Ye+2),16));return{mask:`rgba(${_e},${Ue},${Se},0.7)`,archived:ee.getPropertyValue("--color-wash").trim()||"#EFEDE9",ordinary:ve==="dark"?"#6E6759":"#B9B3AB"}},[ve]),re=j.useRef(e.length),be=j.useCallback((ee,xe={})=>{const _e=F.current;if(!_e)return;const Ue=xe.zoom??_e.getZoom();_e.setCenter(ee.position.x+(xe.offX??260)+$f(ee.id)/(2*Ue),ee.position.y+110,{zoom:Ue,duration:xe.duration??350})},[]),Le=Fa(ee=>ee.lang),Oe=ye(ee=>ee.condenseRun),je=Oe.status==="building",ze=Nn(ee=>ee.projects.find(xe=>xe.id===ee.activeId)?.kind==="paradigm"),rt=El();j.useEffect(()=>{if(vt||!G||oe.getState().nodes.length<10)return;const ee=Number(localStorage.getItem("thoughtdag.lastBackupAt")??0);if(ee===0){localStorage.setItem("thoughtdag.lastBackupAt",String(Date.now()));return}Date.now()-ee<168*3600*1e3||sessionStorage.getItem("thoughtdag.backupNudged")||(sessionStorage.setItem("thoughtdag.backupNudged","yes"),Ke("info",Ie("backup.nudge"),0,{label:Ie("backup.nudgeBtn"),run:()=>of()}))},[G]);const ot=j.useCallback(()=>{const{nodes:ee,edges:xe}=wne(Le),_e=oe.getState();_e.setNodes([..._e.nodes,...ee.filter(Ue=>!_e.nodes.some(Se=>Se.id===Ue.id))]),_e.setEdges([..._e.edges,...xe.filter(Ue=>!_e.edges.some(Se=>Se.id===Ue.id))]),_e.pushHistory(),setTimeout(()=>{const Ue=F.current;Ue&&(Ue.fitView({duration:500,padding:.1}),setTimeout(()=>{if(Ue.getViewport().zoom<.34){const Se=[...oe.getState().nodes].sort((Ye,Ze)=>(Ye.data.createdAt??"").localeCompare(Ze.data.createdAt??""))[0];Se&&Ue.setCenter(Se.position.x+300,Se.position.y+240,{zoom:.6,duration:550})}},680))},100),localStorage.getItem("thoughtdag.tutorialDone")||y(!0)},[Le,y]),Xe=j.useCallback(ee=>{const xe=oe.getState(),_e=xe.nodes[xe.nodes.length-1],Ue=_e?{x:_e.position.x,y:_e.position.y+340}:{x:120,y:80},Se=In();xe.setNodes([...xe.nodes,{id:Se,type:"thought",position:Ue,dragHandle:".drag-handle",data:{question:"",instruction:"",stepKind:ee,response:"",responses:[],responseIndex:-1,isCollapsed:!1,isEditing:!1,isEditingResponse:!1,isLoading:!1,tokenCount:0,highlights:[],highlightMode:"tag",attachments:[],excludedAttachmentIds:[],includedAttachmentIds:[],roleMode:"inherit",isRoot:xe.nodes.length===0,isBranch:!1}}]),xe.pushHistory()},[]),kt=j.useCallback(()=>{re.current=oe.getState().nodes.length,setTimeout(()=>F.current?.fitView({duration:300,padding:.2}),50)},[]),ht=j.useRef(null),at=j.useCallback(ee=>{const xe=oe.getState(),_e=In();xe.setNodes([...xe.nodes,{id:_e,type:"thought",position:ee,width:640,height:420,zIndex:-1,dragHandle:".drag-handle",data:{question:"",stepKind:"frame",frameCarry:!1,response:"",responses:[],responseIndex:-1,isCollapsed:!1,isEditing:!1,isEditingResponse:!1,isLoading:!1,tokenCount:0,highlights:[],highlightMode:"tag",attachments:[],excludedAttachmentIds:[],includedAttachmentIds:[],roleMode:"inherit",isRoot:!1,isBranch:!1}}]),xe.pushHistory()},[]),wt=j.useCallback(ee=>{const xe=[];for(const _e of Array.from(ee)){const Ue=_e.name.split(".").pop()?.toLowerCase()??"";_e.type.startsWith("image/")||_e.type==="application/pdf"||_e.type.startsWith("text/")||["pdf","docx","txt","md","csv","json","yaml","yml","toml","js","ts","tsx","jsx","py","sh","c","cpp","h","java","rs","go","rb","swift","css","html","xml","sql","tex","bib"].includes(Ue)?xe.push(_e):Ke("info",qe(Ie("toast.unsupportedFile"),{name:_e.name}))}return xe},[]),zt=j.useCallback(ee=>{const xe=oe.getState(),_e=In();return xe.setNodes([...xe.nodes,{id:_e,type:"thought",position:ee,dragHandle:".drag-handle",data:{question:"",response:"",responses:[],responseIndex:-1,isCollapsed:!1,isEditing:!1,isEditingResponse:!1,isLoading:!1,tokenCount:0,highlights:[],highlightMode:"tag",attachments:[],excludedAttachmentIds:[],includedAttachmentIds:[],roleMode:"inherit",isRoot:!1,isBranch:!1,webSearch:ye.getState().webSearchEnabled,scholarSearch:ye.getState().scholarSearchEnabled}}]),xe.pushHistory(),_e},[]),We=j.useCallback(ee=>{const xe=wt(ee);if(xe.length===0)return;let _e=null;xe.forEach((Ue,Se)=>{const Ye=Qr("file",{x:120+Se%3*480,y:120+Math.floor(Se/3)*620});fd(Ye,[Ue]),!_e&&!Ue.type.startsWith("image/")&&(_e=Ye)}),_e&&ye.getState().setReaderNodeId(_e),setTimeout(()=>F.current?.fitView({duration:400,padding:.2}),120)},[wt]),Bt=j.useCallback((ee,xe)=>{const _e=ee.clientX,Ue=ee.clientY,Se=ee.currentTarget;let Ye=null;const Ze=Mt=>{!Ye&&Math.hypot(Mt.clientX-_e,Mt.clientY-Ue)>6&&(Ye=document.createElement("div"),Ye.innerHTML=Se.innerHTML,Ye.style.cssText="position:fixed;z-index:300;pointer-events:none;width:36px;height:36px;display:flex;align-items:center;justify-content:center;background:var(--color-card);border:1px solid var(--color-accent);border-radius:10px;box-shadow:0 4px 14px rgba(0,0,0,.18);opacity:.92;",document.body.appendChild(Ye)),Ye&&(Ye.style.left=`${Mt.clientX-18}px`,Ye.style.top=`${Mt.clientY-18}px`)},bt=Mt=>{window.removeEventListener("pointermove",Ze),window.removeEventListener("pointerup",bt);const Ht=!!Ye;Ye?.remove(),xe(Ht?{x:Mt.clientX,y:Mt.clientY}:null)};window.addEventListener("pointermove",Ze),window.addEventListener("pointerup",bt)},[]),se=j.useCallback(ee=>{const xe=F.current?.screenToFlowPosition(ee??{x:window.innerWidth/2,y:window.innerHeight/2})??{x:140,y:140};return{x:xe.x-200,y:xe.y-60}},[]);j.useEffect(()=>{const ee=_e=>{ht.current={x:_e.clientX,y:_e.clientY}},xe=_e=>{if(vt)return;const Ue=_e.target;if(Ue&&(Ue.tagName==="INPUT"||Ue.tagName==="TEXTAREA"||Ue.isContentEditable))return;const Se=Nn.getState(),Ye=Se.projects.find(kn=>kn.id===Se.activeId)?.kind==="paradigm";if(oe.getState().nodes.length===0&&!Ye)return;const Ze=_e.clipboardData;if(!Ze)return;const bt=se(ht.current),Mt=Ze.getData("text/plain").trim(),Ht=Array.from(Ze.files),ca=Ht.some(kn=>!kn.type.startsWith("image/"));if(Ht.length>0&&(ca||!Mt)){_e.preventDefault();const kn=Qr("file",bt);fd(kn,Ht);return}if(Mt)if(_e.preventDefault(),/^https?:\/\/\S+$/.test(Mt)){const kn=Qr("link",bt,{linkUrl:Mt});yN(kn,Mt)}else Qr("note",bt,{question:ote(Mt)})};return window.addEventListener("mousemove",ee),window.addEventListener("paste",xe),()=>{window.removeEventListener("mousemove",ee),window.removeEventListener("paste",xe)}},[se]);const He=j.useCallback(async()=>{const ee=oe.getState();if(ee.nodes.length===0)return;const{nodes:xe,edges:_e}=WH(ee.nodes,ee.edges),Ue=Nn.getState(),Se=Ue.projects.find(Ze=>Ze.id===Ue.activeId)?.name??"Paradigm",Ye=crypto.randomUUID();await zr(ni(Ye),JSON.stringify({state:{nodes:xe,edges:_e},version:1})),await jc(Ye,`▶ ${Se}`,"chat"),await B7(Ye,Se),re.current=oe.getState().nodes.length,setTimeout(()=>F.current?.fitView({duration:400,padding:.15}),150)},[]);j.useEffect(()=>{e.length===0&&!ze&&!localStorage.getItem("thoughtdag.seeded")&&localStorage.setItem("thoughtdag.seeded","yes")},[]),j.useEffect(()=>{if(e.length>re.current&&F.current){const ee=e[e.length-1];ee&&setTimeout(()=>be(ee,{zoom:1,duration:400,offX:220}),100)}re.current=e.length},[e,be]);const ge=j.useCallback(ee=>{const xe=oe.getState().nodes;n(m8(ee,xe))},[n]),Ve=j.useCallback(ee=>a(p8(ee,oe.getState().edges)),[a]),dt=j.useRef(null),xt=j.useCallback((ee,xe)=>{if(xe.data.stepKind!=="frame"||xe.data.frameCarry===!1)return;const _e=oe.getState(),Ue=_e.nodes.find(bt=>bt.id===xe.id);if(!Ue)return;const Se=Ue.measured?.width??Ue.width??0,Ye=Ue.measured?.height??Ue.height??0,Ze=_e.nodes.filter(bt=>{if(bt.id===Ue.id||bt.data.stepKind==="frame"||bt.selected)return!1;const Mt=bt.position.x+(bt.measured?.width??520)/2,Ht=bt.position.y+(bt.measured?.height??120)/2;return Mt>=Ue.position.x&&Mt<=Ue.position.x+Se&&Ht>=Ue.position.y&&Ht<=Ue.position.y+Ye}).map(bt=>({id:bt.id,start:bt.position}));Ze.length!==0&&(dt.current={frameId:Ue.id,start:Ue.position,members:Ze})},[]),St=j.useCallback((ee,xe)=>{const _e=dt.current;if(!_e||xe.id!==_e.frameId)return;const Ue=xe.position.x-_e.start.x,Se=xe.position.y-_e.start.y,Ye=new Map(_e.members.map(Ze=>[Ze.id,{x:Ze.start.x+Ue,y:Ze.start.y+Se}]));oe.setState(Ze=>({nodes:Ze.nodes.map(bt=>{const Mt=Ye.get(bt.id);return Mt?{...bt,position:Mt}:bt})}))},[]),Ft=j.useCallback(()=>{dt.current=null},[]),[un,yn]=j.useState(null),[$t,vn]=j.useState(null),an=j.useCallback((ee,xe)=>{vt||window.getSelection()?.toString()||(ee.preventDefault(),vn({x:ee.clientX,y:ee.clientY,nodeId:xe.id}))},[]),wa=j.useCallback((ee,xe)=>{ee.preventDefault(),yn({x:ee.clientX,y:ee.clientY,edgeId:xe.id})},[]);j.useEffect(()=>{if(!un)return;const ee=()=>yn(null);return window.addEventListener("click",ee),()=>window.removeEventListener("click",ee)},[un]);const qn=oe(ee=>ee.deleteEdges),lr=j.useCallback(ee=>{qn([ee]),yn(null)},[qn]),Qa=j.useCallback(ee=>{ee.source&&ee.target&&c(ee.source,ee.target)},[c]),Jn=j.useCallback(()=>{window.getSelection()?.removeAllRanges(),document.body.classList.add("tdag-connecting")},[]),ja=j.useCallback((ee,xe)=>{if(document.body.classList.remove("tdag-connecting"),ze||xe.isValid||xe.fromHandle?.type!=="source"||!xe.fromNode)return;const _e=xe.fromNode.id,Ue=ee.target?.closest?.(".react-flow__node");if(Ue){const Ht=Ue.getAttribute("data-id");if(Ht&&Ht!==_e){const ca=oe.getState().nodes.find(Rn=>Rn.id===Ht),kn=ca?.data.stepKind??"";ca&&!["note","file","link","frame"].includes(kn)&&oe.getState().addCrossLink(_e,Ht)}return}const{clientX:Se,clientY:Ye}="changedTouches"in ee?ee.changedTouches[0]:ee,Ze=se({x:Se,y:Ye}),bt=oe.getState();if(bt.nodes.find(Ht=>Ht.id===_e)?.data.stepKind==="frame")return;const Mt=zt(Ze);bt.setEdges([...oe.getState().edges,{id:`edge-${_e}-${Mt}`,source:_e,target:Mt,sourceHandle:"continue",targetHandle:"top",type:"smoothstep",style:{stroke:nt.accent,strokeWidth:2},animated:!1,markerEnd:{type:"arrowclosed",color:nt.accent,width:18,height:18},data:{}}]),oe.getState().pushHistory()},[ze,se,zt]),Zt=oe(ee=>ee.selectedNodeId),ce=oe(ee=>ee.selectedNodeIds),Be=ye(ee=>ee.panelOpen),ft=ye(ee=>ee.viewerLoadError),It=oe(ee=>ee.staleIds.length),wn=ye(ee=>ee.panelWidth),rn=e.find(ee=>ee.id===Zt)?.data.stepKind,yt=Wf(rn)||rn==="frame",mt=Be&&!!Zt&&!ze&&!yt,Rt=ce.length>1,On=oe(ee=>ee.batchDelete);j.useEffect(()=>{const ee=xe=>{if(!ye.getState().confirmRequest&&!(vt&&!((xe.metaKey||xe.ctrlKey)&&xe.key==="f"))){if((xe.metaKey||xe.ctrlKey)&&xe.key==="z"&&(xe.shiftKey?(xe.preventDefault(),l()):(xe.preventDefault(),s())),(xe.metaKey||xe.ctrlKey)&&xe.key==="f"){xe.preventDefault(),C(!0);return}{const _e=xe.target;if(!(_e.tagName==="INPUT"||_e.tagName==="TEXTAREA"||_e.isContentEditable)&&Zt&&!ze&&!xe.metaKey&&!xe.ctrlKey&&!xe.altKey){const{nodes:Se,edges:Ye}=oe.getState();if(xe.key===" "){xe.preventDefault(),oe.getState().toggleCollapse(Zt);return}if(xe.key==="r"||xe.key==="R"){xe.preventDefault(),oe.getState().rerunNode(Zt,{});return}if(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(xe.key)){const Ze=Ye.filter(Mt=>!Mt.data?.isCrossLink);let bt;if(xe.key==="ArrowUp")bt=Ze.find(Mt=>Mt.target===Zt)?.source;else if(xe.key==="ArrowDown")bt=Ze.find(Mt=>Mt.source===Zt)?.target;else{const Mt=Ze.find(kn=>kn.target===Zt),Ht=Mt?Ze.filter(kn=>kn.source===Mt.source).map(kn=>kn.target):Se.filter(kn=>!Ze.some(Rn=>Rn.target===kn.id)).map(kn=>kn.id),ca=Ht.indexOf(Zt);ca!==-1&&Ht.length>1&&(bt=Ht[(ca+(xe.key==="ArrowRight"?1:Ht.length-1))%Ht.length])}if(bt){xe.preventDefault(),d(bt);const Mt=Se.find(Ht=>Ht.id===bt);Mt&&be(Mt,{zoom:1,duration:300})}return}}}if(xe.key==="Escape"){const _e=xe.target;if(_e.tagName==="INPUT"||_e.tagName==="TEXTAREA"||_e.isContentEditable)return;ce.length>1?h([]):Zt&&d(null);return}if(xe.key==="Delete"||xe.key==="Backspace"){const _e=xe.target;if(_e.tagName==="INPUT"||_e.tagName==="TEXTAREA"||_e.isContentEditable)return;if(ce.length>1)xe.preventDefault(),Es({title:Ie("confirm.deleteNodesTitle"),message:qe(Ie("confirm.deleteNodes"),{n:ce.length}),confirmLabel:Ie("common.delete"),danger:!0}).then(Ue=>{Ue&&On(ce)});else{const Ue=t.filter(Se=>Se.selected).map(Se=>Se.id);Ue.length>0&&(xe.preventDefault(),qn(Ue))}}}};return window.addEventListener("keydown",ee),()=>window.removeEventListener("keydown",ee)},[s,l,Zt,ce,d,h,On,t,qn,ze,be]);const Mn=()=>{w.trim()&&(r(w.trim(),{rolePrompt:O.trim()||void 0,initialAttachments:H.length>0?H:void 0}),_(""),D(""),N(!1),Y([]))},pe=async ee=>{for(const xe of Array.from(ee))await Xd(xe,{add:_e=>Y(Ue=>[...Ue,_e]),update:(_e,Ue)=>Y(Se=>Se.map(Ye=>Ye.id===_e?{...Ye,...Ue}:Ye))})},Qe=ee=>{ee.key==="Enter"&&!ee.shiftKey&&!Ya(ee)&&(ee.preventDefault(),Mn())},At=j.useCallback(({nodes:ee})=>{const xe=ee.map(_e=>_e.id);xe.length>1?h(xe):xe.length===1&&d(xe[0])},[d,h]),Nt=j.useMemo(()=>e.filter(ee=>ee.data.stepKind==="frame"),[e]),[lt,Lt]=j.useState(!1),Jt=j.useRef(null);j.useEffect(()=>{if(!lt)return;const ee=xe=>{Jt.current?.contains(xe.target)||Lt(!1)};return window.addEventListener("mousedown",ee),()=>window.removeEventListener("mousedown",ee)},[lt]);const[Xt,Cn]=j.useState(!1),[he,jt]=j.useState(0),dn=ye(ee=>ee.searchHitIds!==null),En=j.useRef(null);j.useEffect(()=>{if(!Xt)return;const ee=xe=>{En.current?.contains(xe.target)||Cn(!1)};return window.addEventListener("mousedown",ee),()=>window.removeEventListener("mousedown",ee)},[Xt]);const mn=ye(ee=>ee.searchHitIds),zn=j.useMemo(()=>{if(!Zt||ce.length>1||!e.some(Ze=>Ze.id===Zt))return null;const ee=cm(Zt,e,t),xe=new Set;for(const Ze of ee.mainline)Ze.id!==Zt&&xe.add(Ze.id);for(const Ze of ee.materials)xe.add(Ze.id);for(const Ze of ee.references)xe.add(Ze.source.id);const _e=t.filter(Ze=>!Ze.data?.isCrossLink),Ue=Br(Zt,e,_e).visitedEdgeIds,Se=new Set(ee.references.map(Ze=>Ze.edge.id)),Ye=_e.filter(Ze=>Ze.source===Zt);return{ctx:xe,down:new Set(Ye.map(Ze=>Ze.target)),pathEdgeIds:Ue,refEdgeIds:Se,downEdgeIds:new Set(Ye.map(Ze=>Ze.id))}},[Zt,ce,e,t]),kr=j.useMemo(()=>{let ee=e;return E&&(ee=ee.map(xe=>{const _e=xe.data.stepKind,Ue=Wf(_e)&&!t.some(Se=>Se.source===xe.id||Se.target===xe.id);return _e==="frame"||Ue?{...xe,hidden:!0}:xe})),mn!==null&&(ee=ee.map(xe=>mn.has(xe.id)||xe.data.stepKind==="frame"?{...xe,className:"search-hit"}:xe.className==="search-hit"?{...xe,className:void 0}:xe)),zn&&(ee=ee.map(xe=>{const _e=xe.id===Zt?"target":zn.ctx.has(xe.id)?"ctx":zn.down.has(xe.id)?"down":xe.data.stepKind==="frame"?void 0:"dim";return _e?{...xe,className:[xe.className,`focus-${_e}`].filter(Boolean).join(" "),..._e!=="dim"?{data:{...xe.data,focusRole:_e}}:{}}:xe})),ee},[e,t,E,mn,zn,Zt]),Ur=j.useMemo(()=>{const ee=t.map(Ue=>{const Se=Ue.data?.isBranchFromSelection?{...Ue,animated:!1,style:{...Ue.style,strokeDasharray:void 0}}:Ue,Ye=typeof Se.style?.stroke=="string"?NE[Se.style.stroke.toUpperCase()]:void 0,Ze=Se.markerEnd&&typeof Se.markerEnd=="object"?Se.markerEnd:void 0,bt=typeof Ze?.color=="string"?NE[Ze.color.toUpperCase()]:void 0;return!Ye&&!bt?Se:{...Se,...Ye?{style:{...Se.style,stroke:me[Ye]}}:{},...bt&&Ze?{markerEnd:{...Ze,color:me[bt]}}:{}}});if(zn)return ee.map(Ue=>zn.pathEdgeIds.has(Ue.id)?{...Ue,className:"focus-e-path",style:{...Ue.style,stroke:me.accent,strokeWidth:3.5,opacity:1},markerEnd:{type:"arrowclosed",...Ue.markerEnd&&typeof Ue.markerEnd=="object"?Ue.markerEnd:{},color:me.accent},zIndex:10,data:{...Ue.data,focusRole:"path"}}:zn.refEdgeIds.has(Ue.id)?{...Ue,style:{...Ue.style,opacity:.9},zIndex:5,data:{...Ue.data,focusRole:"ref"}}:zn.downEdgeIds.has(Ue.id)?{...Ue,className:"focus-e-down",style:{...Ue.style,strokeWidth:2.5,opacity:.85},markerEnd:{type:"arrowclosed",...Ue.markerEnd&&typeof Ue.markerEnd=="object"?Ue.markerEnd:{}},zIndex:5,data:{...Ue.data,focusRole:"down"}}:{...Ue,style:{...Ue.style,strokeWidth:1.5,opacity:.2},zIndex:0});const xe=ce.length>1?ce:[];if(xe.length===0)return ee;const{visitedEdgeIds:_e}=Br(xe,e,t);return ee.map(Ue=>_e.has(Ue.id)?{...Ue,style:{...Ue.style,stroke:me.trace,strokeWidth:3.5,opacity:1},markerEnd:{type:"arrowclosed",...Ue.markerEnd&&typeof Ue.markerEnd=="object"?Ue.markerEnd:{},color:me.trace},zIndex:10}:{...Ue,style:{...Ue.style,strokeWidth:1.5,opacity:.2},zIndex:0})},[e,t,ce,me,zn]);return j.useEffect(()=>{if(!mt||!Zt)return;const ee=setTimeout(()=>{const xe=F.current;if(!xe)return;const _e=oe.getState().nodes.find(bt=>bt.id===Zt);if(!_e)return;const Ue=xe.getViewport(),Se=_e.measured?.width??_e.width??480,Ye=(_e.position.x+Se)*Ue.zoom+Ue.x,Ze=window.innerWidth-ye.getState().panelWidth-ad-24;if(Ye>Ze){const bt=(_e.position.x+Se/2)*Ue.zoom+Ue.x;xe.setViewport({...Ue,x:Ue.x-(bt-Ze/2)},{duration:300})}},60);return()=>clearTimeout(ee)},[mt,Zt]),u.jsxs("div",{className:"relative w-full h-full","data-searching":dn||void 0,children:[u.jsxs("div",{className:"relative h-full w-full",onDoubleClick:ee=>{ee.target.classList.contains("react-flow__pane")&&!ze&&zt(se({x:ee.clientX,y:ee.clientY}))},onDragOver:ee=>{(ee.dataTransfer.types.includes("application/thoughtdag-content")||ee.dataTransfer.types.includes("Files"))&&(ee.preventDefault(),ee.dataTransfer.dropEffect="copy",!G&&!ze&&q(!0))},onDrop:ee=>{if(vt)return;const xe=ee.target;if(!G&&!ze&&ee.dataTransfer.files.length>0){ee.preventDefault(),q(!1),We(ee.dataTransfer.files);return}const _e=xe.closest?.(".react-flow__node"),Ue=_e&&oe.getState().nodes.find(Ze=>Ze.id===_e.getAttribute("data-id"))?.data.stepKind==="frame";if(!xe.classList?.contains("react-flow__pane")&&!Ue)return;const Se=se({x:ee.clientX,y:ee.clientY}),Ye=ee.dataTransfer.getData("application/thoughtdag-content");if(Ye==="ask"){ee.preventDefault(),zt(Se);return}if(Ye==="frame"){ee.preventDefault(),at(Se);return}if(Ye==="note"||Ye==="file"){ee.preventDefault(),Qr(Ye,Se);return}if(ee.dataTransfer.files.length>0){ee.preventDefault();const Ze=wt(ee.dataTransfer.files);if(Ze.length===0)return;const bt=Qr("file",Se);fd(bt,Ze)}},children:[u.jsxs(ML,{onInit:ee=>{F.current=ee,EN.current=ee;const xe=ye.getState().arrivalFocusNodeId;if(xe){ye.getState().setArrivalFocusNodeId(null);const _e=oe.getState().nodes.find(Ue=>Ue.id===xe);_e&&window.setTimeout(()=>{ee.setCenter(_e.position.x+260,_e.position.y+140,{zoom:.9,duration:400})},150)}},nodes:kr,edges:Ur,onNodesChange:ge,onEdgesChange:Ve,onNodeDragStart:xt,onNodeDrag:St,onNodeDragStop:Ft,onConnect:Qa,onConnectStart:Jn,onConnectEnd:ja,onEdgeContextMenu:wa,onNodeContextMenu:an,nodeTypes:wae,edgeTypes:Eae,deleteKeyCode:null,fitView:!0,onlyRenderVisibleElements:!0,minZoom:.04,maxZoom:2,defaultEdgeOptions:{type:"smoothstep",animated:!1,style:{stroke:me.accent,strokeWidth:2},markerEnd:{type:"arrowclosed",color:me.accent,width:18,height:18}},snapToGrid:W==="grid",snapGrid:[22,22],proOptions:{hideAttribution:!0},nodeDragThreshold:5,connectionRadius:40,selectionMode:Sc.Partial,selectionOnDrag:!vt,nodesDraggable:!vt,nodesConnectable:!vt,panOnDrag:vt?!0:[1,2],zoomOnDoubleClick:!1,connectionLineStyle:{stroke:me.accent,strokeDasharray:"8 4",strokeWidth:2},onSelectionChange:At,onPaneClick:()=>{d(null),h([]),vn(null)},children:[W==="grid"?u.jsxs(u.Fragment,{children:[u.jsx(Jg,{id:"grid-fine",variant:pi.Lines,gap:22,color:"var(--canvas-grid-fine)"}),u.jsx(Jg,{id:"grid-major",variant:pi.Lines,gap:110,color:"var(--canvas-grid-major)"})]}):u.jsx(Jg,{variant:pi.Dots,gap:24,size:1,color:"var(--canvas-dot)"}),u.jsx(Aae,{}),u.jsx(Sae,{panelShiftWidth:mt?wn:0}),u.jsx(gae,{}),u.jsx(FL,{position:"bottom-left"}),e.length>0&&u.jsx(tj,{nodeColor:ee=>{const xe=ee.data;if(xe.archived)return ke.archived;const _e=xe.stepKind;return _e==="note"?"#D97706":_e==="file"||_e==="link"?"#64748B":Array.isArray(xe.condensedFrom)&&xe.condensedFrom.length?"#8B7CF0":xe.isRoot?me.accent:xe.isBranch?me.warm:ke.ordinary},maskColor:ke.mask,style:{width:200,height:140},pannable:!0,zoomable:!0,position:"bottom-right"})]}),!G&&ze&&u.jsx("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:u.jsxs("div",{className:"text-center pointer-events-auto",children:[u.jsx("p",{className:"text-sm text-ink-muted mb-1 font-medium",children:b("paradigm.emptyTitle")}),u.jsx("p",{className:"text-xs text-ink-faint mb-4 max-w-sm leading-relaxed",children:b("paradigm.emptyHint")}),u.jsxs("div",{className:"flex items-center justify-center gap-2",children:[u.jsxs("button",{onClick:()=>Xe("human"),className:"text-sm border-2 border-dashed border-warm/60 text-warm hover:bg-warm/10 px-4 py-2.5 rounded-xl transition-colors flex items-center gap-1.5",children:[u.jsx(af,{size:15,strokeWidth:1.75})," ",b("paradigm.addHuman")]}),u.jsxs("button",{onClick:()=>Xe("prompt"),className:"text-sm border-2 border-dashed border-accent/50 text-accent hover:bg-accent/10 px-4 py-2.5 rounded-xl transition-colors flex items-center gap-1.5",children:[u.jsx(Ad,{size:15,strokeWidth:1.75})," ",b("paradigm.addPrompt")]})]})]})}),vt&&!G&&u.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:u.jsx("div",{className:"text-center max-w-[420px] px-6",children:ft?u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"text-3xl mb-3",children:"🔗"}),u.jsx("div",{className:"text-sm font-semibold text-ink mb-1.5",children:b("viewer.loadError")}),u.jsx("p",{className:"text-xs text-ink-muted leading-relaxed",children:b("viewer.loadErrorHint")})]}):u.jsxs("div",{className:"flex items-center gap-2 text-sm text-ink-muted justify-center",children:[u.jsx(Xn,{size:16,strokeWidth:1.75,className:"animate-spin text-accent"})," ",b("viewer.loading")]})})}),!G&&!ze&&!vt&&u.jsxs("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none overflow-hidden",children:[u.jsxs("svg",{className:"absolute -left-10 top-[8%] w-[360px] h-[300px] opacity-[0.35] pointer-events-none",viewBox:"0 0 360 300","aria-hidden":!0,children:[u.jsx("path",{d:"M80 40 C80 90 80 90 80 130 M80 170 C80 210 80 210 80 250",stroke:nt.line,strokeWidth:"2",fill:"none"}),u.jsx("path",{d:"M95 150 C150 150 150 90 205 88",stroke:nt.line,strokeWidth:"2",strokeDasharray:"6 5",fill:"none"}),u.jsx("circle",{cx:"80",cy:"30",r:"7",fill:nt.line}),u.jsx("circle",{cx:"80",cy:"150",r:"7",fill:"none",stroke:nt.line,strokeWidth:"2.5"}),u.jsx("circle",{cx:"80",cy:"262",r:"7",fill:nt.line}),u.jsx("circle",{cx:"218",cy:"88",r:"7",fill:nt.line})]}),u.jsxs("svg",{className:"absolute right-[-30px] bottom-[10%] w-[320px] h-[280px] opacity-[0.35] pointer-events-none",viewBox:"0 0 320 280","aria-hidden":!0,children:[u.jsx("path",{d:"M240 30 C240 80 240 80 240 120 M240 160 C240 200 240 200 240 240",stroke:nt.line,strokeWidth:"2",fill:"none"}),u.jsx("path",{d:"M225 140 C170 140 170 210 115 212",stroke:nt.line,strokeWidth:"2",strokeDasharray:"6 5",fill:"none"}),u.jsx("circle",{cx:"240",cy:"20",r:"7",fill:nt.line}),u.jsx("circle",{cx:"240",cy:"140",r:"7",fill:"none",stroke:nt.line,strokeWidth:"2.5"}),u.jsx("circle",{cx:"240",cy:"252",r:"7",fill:nt.line}),u.jsx("circle",{cx:"102",cy:"212",r:"7",fill:nt.line})]}),u.jsxs("div",{className:"pointer-events-auto w-[560px] animate-fade-in relative",children:[u.jsxs("div",{className:"text-center mb-8",children:[u.jsxs("svg",{width:"52",height:"52",viewBox:"0 0 44 44",className:"mx-auto mb-4","aria-hidden":!0,children:[u.jsx("circle",{className:"dag-pop",style:{animationDelay:"0.05s"},cx:"22",cy:"7",r:"3.5",fill:nt.accent}),u.jsx("line",{className:"dag-pop",style:{animationDelay:"0.2s"},x1:"22",y1:"11",x2:"22",y2:"19",stroke:nt.accent,strokeWidth:"2",strokeLinecap:"round"}),u.jsx("circle",{className:"dag-pop",style:{animationDelay:"0.35s"},cx:"22",cy:"22",r:"3.5",fill:"none",stroke:nt.accent,strokeWidth:"2.5"}),u.jsx("line",{className:"dag-pop",style:{animationDelay:"0.5s"},x1:"22",y1:"25",x2:"22",y2:"33",stroke:nt.accent,strokeWidth:"2",strokeLinecap:"round"}),u.jsx("circle",{className:"dag-pop",style:{animationDelay:"0.65s"},cx:"22",cy:"37",r:"3.5",fill:nt.accent,opacity:"0.35"}),u.jsx("line",{className:"dag-pop",style:{animationDelay:"0.8s"},x1:"25.5",y1:"23.5",x2:"33",y2:"28.5",stroke:nt.warm,strokeWidth:"2",strokeLinecap:"round",strokeDasharray:"3 3"}),u.jsx("circle",{className:"dag-pop",style:{animationDelay:"0.95s"},cx:"36",cy:"30",r:"3.5",fill:nt.warm})]}),u.jsx("h1",{className:"text-4xl font-semibold tracking-tight text-ink mb-2.5",children:"ThoughtDAG"}),u.jsx("p",{className:"text-sm text-ink-muted",children:b("landing.tagline")}),u.jsx("p",{className:"text-xs text-ink-muted mt-1.5 font-medium",children:b("landing.mechanism")})]}),u.jsxs("div",{className:"bg-card border border-line rounded-xl px-5 py-4 shadow-lg transition-all focus-within:border-accent/50 focus-within:shadow-xl",children:[u.jsx("textarea",{value:w,onChange:ee=>_(ee.target.value),onKeyDown:Qe,onPaste:ee=>{if(ee.clipboardData.getData("text/plain").trim())return;const xe=Array.from(ee.clipboardData.items).filter(_e=>_e.kind==="file").map(_e=>_e.getAsFile()).filter(Boolean);xe.length&&pe(xe)},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}),H.length>0&&u.jsx("div",{className:"flex flex-wrap gap-2 mt-2 pb-1",children:H.map(ee=>u.jsxs("div",{className:"flex items-center gap-1.5 bg-wash rounded-lg px-2.5 py-1.5 group",children:[ee.thumbnailUrl?u.jsx("img",{src:ee.thumbnailUrl,className:"w-6 h-6 rounded object-cover",alt:ee.name}):u.jsx("span",{className:"text-xs",children:u.jsx(gi,{size:16,strokeWidth:1.75})}),u.jsx("span",{className:"text-xs text-ink-muted max-w-[100px] truncate",children:ee.name}),ee.isExtracting&&u.jsx("span",{className:"text-2xs text-accent",children:u.jsx(Xn,{className:"animate-spin",size:12,strokeWidth:1.75})}),ee.numPages!=null&&u.jsxs("span",{className:"text-2xs text-ink-faint",children:[ee.numPages,"p"]}),u.jsx("button",{onClick:()=>Y(xe=>xe.filter(_e=>_e.id!==ee.id)),className:"text-ink-faint hover:text-red-500 text-xs opacity-0 group-hover:opacity-100 transition-opacity",children:u.jsx(bn,{size:14,strokeWidth:1.75})})]},ee.id))}),M&&u.jsxs("div",{className:"space-y-1 mt-2",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx("span",{className:"text-xs text-ink-muted font-medium",children:b("landing.roleLabel")}),u.jsx("button",{onClick:()=>{N(!1),D("")},className:"text-xs text-ink-faint hover:text-ink-muted",children:u.jsx(bn,{size:14,strokeWidth:1.75})})]}),u.jsx("textarea",{value:O,onChange:ee=>D(ee.target.value),placeholder:b("landing.rolePlaceholder"),className:"w-full text-xs border border-line rounded-lg px-3 py-2 focus:outline-none focus:ring-1 focus:ring-accent bg-surface resize-none leading-relaxed",rows:2,autoFocus:!0}),u.jsx(vN,{onPick:D})]}),u.jsxs("div",{className:"flex items-center justify-end mt-2 gap-2",children:[u.jsx(Bb,{}),u.jsx("button",{onClick:()=>N(!M),title:b("landing.roleTrayTitle"),className:`rounded-full w-8 h-8 flex items-center justify-center transition-colors shrink-0 ${M||O?"text-accent bg-accent/10 hover:bg-accent/20":"text-ink-faint hover:text-ink-muted hover:bg-line"}`,children:u.jsx(sP,{size:16,strokeWidth:1.75})}),u.jsx("button",{onClick:()=>K.current?.click(),className:"text-ink-faint hover:text-accent hover:bg-wash rounded-xl px-3 py-2 transition-colors text-sm",title:b("landing.attach"),children:u.jsx(xi,{size:16,strokeWidth:1.75})}),u.jsx("input",{ref:K,type:"file",multiple:!0,accept:Cd,className:"hidden",onChange:ee=>{pe(ee.target.files||[]),ee.target.value=""}}),u.jsx("button",{onClick:Mn,disabled:!w.trim()||H.some(ee=>ee.isExtracting),className:"bg-accent hover:bg-accent-strong disabled:opacity-30 disabled:cursor-not-allowed text-white text-sm px-5 py-2 rounded-xl transition-all",children:H.some(ee=>ee.isExtracting)?b("landing.extracting"):b("landing.send")})]})]}),u.jsxs("div",{onClick:()=>U.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(To,{size:15,strokeWidth:1.75,className:"text-accent"})," ",b("landing.docStart")]}),u.jsx("p",{className:"text-2xs text-ink-faint mt-1.5",children:b("landing.docFormats")}),u.jsx("p",{className:"text-2xs text-ink-faint mt-0.5",children:b("landing.docPrivacy")})]}),!!window.desktopSessions&&u.jsxs("button",{onClick:()=>B(!0),className:"w-full mt-3 bg-card/60 backdrop-blur border border-line rounded-xl px-5 py-3.5 hover:border-accent/40 hover:bg-accent/5 transition-all text-center","data-landing-atlas":!0,children:[u.jsxs("div",{className:"flex items-center justify-center gap-2 text-sm text-ink-muted font-medium",children:[u.jsx(Ij,{size:15,strokeWidth:1.75,className:"text-accent shrink-0"}),u.jsx("span",{children:b("landing.atlasStart")}),u.jsx(Sj,{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:U,type:"file",multiple:!0,accept:Cd,className:"hidden",onChange:ee=>{We(ee.target.files||[]),ee.target.value=""}}),R&&u.jsx(_N,{onClose:()=>B(!1),onSwitched:()=>{B(!1),kt()}}),(!rt||(rt.models?.length??0)===0)&&u.jsxs("div",{className:"mt-3 bg-card/60 backdrop-blur border border-line rounded-xl px-5 py-3.5 text-center","data-quick-connect":!0,children:[u.jsxs("div",{className:"flex items-center justify-center gap-2 text-sm text-ink-muted font-medium",children:[u.jsx(Sd,{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:[Le==="zh"&&u.jsx("button",{onClick:()=>{ye.getState().setApiKeyPresetHint("zhipu"),ye.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:()=>{IN()},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:()=>ye.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:()=>ye.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:Pi,title:"landing.feature1.title",desc:"landing.feature1.desc"},{icon:B5,title:"landing.feature2.title",desc:"landing.feature2.desc"},{icon:r7,title:"landing.feature3.title",desc:"landing.feature3.desc"}].map(({icon:ee,title:xe,desc:_e})=>u.jsxs("div",{className:"bg-card/60 backdrop-blur border border-line rounded-xl px-4 py-3.5",children:[u.jsx(ee,{size:16,strokeWidth:1.75,className:"text-accent mb-2"}),u.jsx("h3",{className:"text-xs font-semibold text-ink mb-1",children:b(xe)}),u.jsx("p",{className:"text-2xs text-ink-faint leading-relaxed",children:b(_e)})]},xe))}),u.jsxs("div",{className:"text-center mt-6 flex items-center justify-center gap-5",children:[u.jsxs("button",{onClick:ot,className:"text-xs text-accent hover:text-accent-strong font-medium transition-colors inline-flex items-center gap-1.5",children:[u.jsx(B5,{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(R5,{size:14,strokeWidth:1.75})," ",b("landing.howItWorks")]})]})]})]}),!vt&&u.jsx(xne,{onSwitched:kt}),(G||ze)&&!vt&&u.jsxs("div",{className:"absolute top-[38%] -translate-y-1/2 left-4 z-10 flex flex-col gap-1.5 bg-card/90 backdrop-blur border border-line rounded-xl p-1.5 shadow-sm",children:[!ze&&u.jsx("button",{onClick:()=>zt(se(null)),draggable:!0,onDragStart:ee=>{ee.dataTransfer.setData("application/thoughtdag-content","ask"),ee.dataTransfer.effectAllowed="copy"},title:b("palette.askTitle"),className:"w-9 h-9 rounded-lg flex items-center justify-center text-accent hover:bg-accent/10 transition-colors cursor-grab",children:u.jsx(af,{size:17,strokeWidth:1.75})}),u.jsx("button",{onPointerDown:ee=>Bt(ee,xe=>Qr("note",se(xe))),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(Bi,{size:17,strokeWidth:1.75})}),u.jsx("button",{onPointerDown:ee=>Bt(ee,xe=>Qr("file",se(xe))),title:b("palette.fileTitle"),className:"w-9 h-9 rounded-lg flex items-center justify-center text-ink-muted hover:bg-wash transition-colors",children:u.jsx(xi,{size:17,strokeWidth:1.75})}),u.jsx("button",{onPointerDown:ee=>Bt(ee,xe=>at(se(xe))),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(vx,{size:17,strokeWidth:1.75})})]}),vt&&u.jsxs("div",{className:"absolute top-4 z-10 flex gap-1.5 items-center transition-[right] duration-200",style:{right:mt?wn+ad+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(kd,{size:14,strokeWidth:1.75})," ",b("viewer.badge")]}),u.jsx("button",{onClick:()=>C(!0),className:"bg-card/90 backdrop-blur border border-line rounded-lg w-8 h-8 flex items-center justify-center shadow-sm hover:bg-wash transition-colors text-ink-muted hover:text-accent",title:b("search.entryTitle"),"data-search-entry":!0,children:u.jsx(Af,{size:15,strokeWidth:1.75})}),u.jsx(ZE,{}),u.jsx("button",{onClick:()=>of(),className:"bg-card/90 backdrop-blur border border-line rounded-lg w-8 h-8 flex items-center justify-center shadow-sm hover:bg-wash transition-colors text-ink-muted hover:text-accent",title:b("viewer.downloadJson"),children:u.jsx(Ed,{size:15,strokeWidth:1.75})}),u.jsx("a",{href:"https://github.com/chenxiachan/thoughtdag",target:"_blank",rel:"noreferrer",className:"bg-ink text-white rounded-lg h-8 px-3 flex items-center gap-1.5 shadow-sm hover:bg-ink/85 transition-colors text-xs font-medium",children:b("viewer.openApp")})]}),!vt&&u.jsxs("div",{className:"absolute top-4 z-10 flex gap-1.5 items-center transition-[right] duration-200",style:{right:mt?wn+ad+12:16},children:[ze&&u.jsxs(u.Fragment,{children:[u.jsxs("button",{onClick:()=>Xe("human"),className:"bg-card/90 backdrop-blur border border-warm/40 rounded-lg h-8 px-3 flex items-center gap-1.5 shadow-sm hover:bg-warm/10 transition-colors text-warm text-xs font-medium",children:[u.jsx(af,{size:14,strokeWidth:1.75})," ",b("paradigm.addHuman")]}),u.jsxs("button",{onClick:()=>Xe("prompt"),className:"bg-card/90 backdrop-blur border border-accent/40 rounded-lg h-8 px-3 flex items-center gap-1.5 shadow-sm hover:bg-accent/10 transition-colors text-accent text-xs font-medium",children:[u.jsx(Ad,{size:14,strokeWidth:1.75})," ",b("paradigm.addPrompt")]}),u.jsxs("button",{onClick:()=>{He()},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")]})]}),!ze&&u.jsx(wN,{}),!G&&u.jsx("button",{onClick:()=>ye.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(Sd,{size:15,strokeWidth:1.75})}),It>0&&!ze&&u.jsxs("button",{onClick:()=>{const{nodes:ee,edges:xe,staleIds:_e}=oe.getState(),Ue=_e.reduce((Se,Ye)=>{const Ze=ee.map(Ht=>Ht.id===Ye?{...Ht,data:{...Ht.data,question:"",response:""}}:Ht),{layerTokens:bt}=yr(Ye,Ze,xe),Mt=ee.find(Ht=>Ht.id===Ye)?.data.question??"";return Se+bt.material+bt.reference+bt.chain+$n(Mt)},0);Es({title:b("replay.confirmTitle"),message:qe(b("replay.confirmMsg"),{n:It,tok:Ue.toLocaleString()}),confirmLabel:b("replay.confirmBtn")}).then(Se=>{Se&&oe.getState().replayStale()})},className:"bg-amber-500/10 backdrop-blur border border-amber-500/40 rounded-lg h-8 px-3 flex items-center gap-1.5 shadow-sm hover:bg-amber-500/20 transition-colors text-amber-600 text-xs font-medium",title:b("replay.chipTitle"),children:[u.jsx(VP,{size:14,strokeWidth:1.75})," ",It]}),G&&Nt.length>0&&u.jsxs("div",{ref:Jt,className:"relative",children:[u.jsx("button",{onClick:()=>Lt(ee=>!ee),className:`bg-card/90 backdrop-blur border rounded-lg w-8 h-8 flex items-center justify-center shadow-sm transition-colors ${lt?"border-accent/40 text-accent":"border-line text-ink-faint hover:bg-wash"}`,title:b("toolbar.frames"),children:u.jsx(vx,{size:15,strokeWidth:1.75})}),lt&&u.jsx("div",{className:"absolute right-0 top-full mt-1.5 bg-card border border-line rounded-xl shadow-lg py-1 w-[230px] max-h-[320px] overflow-y-auto z-30 animate-fade-in",children:Nt.map(ee=>u.jsxs("button",{onClick:()=>{Lt(!1),F.current?.fitBounds({x:ee.position.x,y:ee.position.y,width:ee.width??640,height:ee.height??420},{duration:400,padding:.15})},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2",children:[u.jsx("span",{className:`w-2.5 h-2.5 rounded-sm shrink-0 ${(nd[ee.data.frameColor??"gray"]??nd.gray).dot}`}),u.jsx("span",{className:"truncate",children:ee.data.question||b("frame.untitled")})]},ee.id))})]}),G&&u.jsx("button",{onClick:()=>C(!0),className:"bg-card/90 backdrop-blur border border-line rounded-lg w-8 h-8 flex items-center justify-center shadow-sm hover:bg-wash transition-colors text-ink-faint hover:text-accent",title:b("search.entryTitle"),"data-search-entry":!0,children:u.jsx(Af,{size:15,strokeWidth:1.75})}),u.jsx(ZE,{}),G&&!ze&&u.jsx(qte,{showTrigger:!1,openPing:he,onLocate:ee=>{const xe=oe.getState().nodes.find(_e=>_e.id===ee);xe&&(d(ee),be(xe,{zoom:1}))}}),je&&!vt&&u.jsxs("button",{onClick:()=>ye.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:qe(b("condense.entryBuilding"),{i:String(Oe.current),n:String(Oe.total)}),"data-condense-entry":!0,children:[u.jsx(Xn,{size:14,strokeWidth:1.75,className:"animate-spin"}),u.jsxs("span",{className:"text-2xs font-mono",children:[Oe.current,"/",Oe.total]})]}),Om&&u.jsx("button",{onClick:()=>ye.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(X8,{size:15,strokeWidth:1.75})}),u.jsxs("div",{ref:En,className:"relative",children:[u.jsx("button",{onClick:()=>Cn(ee=>!ee),className:`bg-card/90 backdrop-blur border rounded-lg w-8 h-8 flex items-center justify-center shadow-sm transition-colors ${Xt?"border-accent/40 text-accent":"border-line text-ink-faint hover:bg-wash"}`,title:b("toolbar.more"),"data-toolbar-more":!0,children:u.jsx(G8,{size:15,strokeWidth:1.75})}),Xt&&u.jsxs("div",{className:"absolute right-0 top-full mt-1.5 bg-card border border-line rounded-xl shadow-lg py-1 w-[220px] z-30 animate-fade-in",children:[G&&u.jsxs("button",{onClick:()=>{Cn(!1),T(!E)},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(E?"toolbar.showAnnotations":"toolbar.hideAnnotations"),children:[u.jsx(Bi,{size:14,strokeWidth:1.75,className:`shrink-0 ${E?"text-accent":"text-ink-faint"}`})," ",b(E?"toolbar.menuAnnotationsShow":"toolbar.menuAnnotationsHide")]}),G&&u.jsxs("button",{onClick:()=>{Cn(!1),Es({title:b("confirm.relayoutTitle"),message:b("confirm.relayoutMsg"),confirmLabel:b("toolbar.relayout")}).then(ee=>{ee&&(x(),setTimeout(()=>F.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(HP,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("toolbar.relayout")]}),X>0&&u.jsxs("button",{onClick:()=>{Cn(!1),ye.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(Td,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",qe(b("hlov.entry"),{n:X})]}),P>0&&u.jsxs("button",{onClick:()=>{Cn(!1),ye.getState().setMaterialsOverviewOpen(!0)},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5",title:b("matov.entryTitle"),"data-matov-entry":!0,children:[u.jsx(xi,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",qe(b("matov.entry"),{n:P})]}),G&&u.jsx("div",{className:"border-t border-line/60 my-1"}),G&&!ze&&!vt&&u.jsxs("button",{onClick:()=>{Cn(!1),ye.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(om,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("condense.title"),"…"]}),G&&!ze&&u.jsxs("button",{onClick:()=>{Cn(!1),jt(ee=>ee+1)},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5",title:b("toolbar.diagnose"),"data-menu-diagnose":!0,children:[u.jsx(i7,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("toolbar.menuDiagnose")]}),G&&!ze&&u.jsxs("button",{onClick:()=>{Cn(!1),(async()=>{const{nodes:ee,edges:xe}=oe.getState(),{confirmIfSensitive:_e}=await Kt(async()=>{const{confirmIfSensitive:Se}=await import("./sensitive-scan-NBqP2Srd.js");return{confirmIfSensitive:Se}},[]);if(!await _e(ee))return;const Ue=await gB(ee,xe);await navigator.clipboard.writeText(Ue).catch(()=>{}),ye.getState().setShareDialogUrl(Ue)})()},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(bz,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("toolbar.menuShare")]}),G&&u.jsxs("button",{onClick:()=>{Cn(!1),ze?GH():of()},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5","data-menu-export":!0,children:[u.jsx(Ed,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b(ze?"paradigm.exportParadigm":"switcher.exportBackup")]}),ne&&u.jsxs("button",{onClick:()=>{Cn(!1),QH()},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5",title:b("toolbar.exportEventsTitle"),children:[u.jsx(gi,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("toolbar.exportEvents")]}),G&&u.jsx("div",{className:"border-t border-line/60 my-1"}),u.jsxs("div",{className:"px-3 pt-2 pb-1","data-appearance-lighting":!0,children:[u.jsx("div",{className:"text-2xs text-ink-faint mb-1.5",children:b("appearance.lighting")}),u.jsx("div",{className:"flex rounded-lg border border-line overflow-hidden text-2xs",children:[["light",b("appearance.light")],["dark",b("appearance.dark")],["system",b("appearance.system")]].map(([ee,xe],_e)=>u.jsx("button",{onClick:()=>bs.getState().setLighting(ee),className:`flex-1 px-1 py-1.5 transition-colors ${_e>0?"border-l border-line":""} ${ae===ee?"bg-accent/10 text-accent font-medium":"text-ink-muted hover:bg-wash"}`,children:xe},ee))})]}),u.jsxs("div",{className:"px-3 pt-1 pb-2","data-appearance-paper":!0,children:[u.jsx("div",{className:"text-2xs text-ink-faint mb-1.5",children:b("appearance.paper")}),u.jsx("div",{className:"flex rounded-lg border border-line overflow-hidden text-2xs",children:[["plain",b("appearance.plain")],["grid",b("appearance.grid")]].map(([ee,xe],_e)=>u.jsx("button",{onClick:()=>bs.getState().setPaper(ee),className:`flex-1 px-1 py-1.5 transition-colors ${_e>0?"border-l border-line":""} ${W===ee?"bg-accent/10 text-accent font-medium":"text-ink-muted hover:bg-wash"}`,children:xe},ee))})]}),u.jsx("div",{className:"border-t border-line/60 my-1"}),u.jsxs("button",{onClick:()=>{Cn(!1),ye.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(Oj,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("memory.managerTitle")]}),u.jsxs("button",{onClick:()=>{Cn(!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(R5,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("landing.howItWorks")]})]})]}),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(o7,{size:16,strokeWidth:1.75})}),u.jsx("button",{onClick:l,disabled:p>=m.length-1,className:"bg-card/90 backdrop-blur border border-line rounded-lg w-8 h-8 flex items-center justify-center shadow-sm hover:bg-wash transition-colors disabled:opacity-20 disabled:cursor-not-allowed",title:b("canvas.redo"),children:u.jsx(oz,{size:16,strokeWidth:1.75})})]}),Rt&&!vt&&u.jsx(Mte,{}),u.jsx(Ute,{open:A,onClose:()=>C(!1),onLocate:ee=>{const xe=oe.getState().nodes.find(_e=>_e.id===ee);xe&&(d(ee),be(xe,{zoom:1}))}}),$t&&u.jsx(Dte,{x:$t.x,y:$t.y,nodeId:$t.nodeId,onClose:()=>vn(null)}),u.jsx(Lte,{onLocate:ee=>{const xe=oe.getState().nodes.find(_e=>_e.id===ee);xe&&(d(ee),be(xe,{zoom:1}))}}),u.jsx(yae,{onLocate:ee=>{const xe=oe.getState().nodes.find(_e=>_e.id===ee);xe&&(d(ee),be(xe,{zoom:1}))}}),u.jsx(Ote,{onLocate:ee=>{const xe=oe.getState().nodes.find(_e=>_e.id===ee);xe&&(d(ee),be(xe,{zoom:1}))}}),un&&u.jsx("div",{className:"fixed z-50 bg-card border border-line rounded-xl shadow-lg py-1 min-w-[120px]",style:{left:un.x,top:un.y},children:u.jsxs("button",{onClick:()=>lr(un.edgeId),className:"w-full text-left px-4 py-2 text-sm text-red-600 hover:bg-red-50 transition-colors flex items-center gap-1.5",children:[u.jsx(Ua,{size:14,strokeWidth:1.75}),b("canvas.deleteEdge")]})})]}),u.jsx(cae,{onFocusSegment:ee=>{const xe=F.current,_e=oe.getState().nodes.filter(Ht=>ee.includes(Ht.id));if(!xe||_e.length===0)return;const Ue=_e.map(Ht=>Ht.position.x),Se=_e.map(Ht=>Ht.position.y),Ye=Math.min(...Ue),Ze=Math.min(...Se),bt=Math.max(...Ue)+520-Ye,Mt=Math.max(...Se)+240-Ze;xe.fitBounds({x:Ye,y:Ze,width:bt+700,height:Mt},{duration:350,padding:.15})}}),mt&&u.jsx(_te,{onFocusNode:ee=>{const xe=e.find(_e=>_e.id===ee);xe&&be(xe,{duration:300})}}),u.jsx(ene,{onLocate:ee=>{const xe=oe.getState().nodes.find(_e=>_e.id===ee);xe&&(d(ee),be(xe,{zoom:1}))}})]})}function Sae({panelShiftWidth:e}){const t=Qd(),n=Gt(),a=wl(),r=oe(d=>d.nodes.length),s=oe(d=>d.nodes),l=j.useMemo(()=>{let d=null,h="";for(const m of s){if(m.data.stepKind&&m.data.stepKind!=="human"&&m.data.stepKind!=="prompt")continue;const p=[m.data.lastGeneratedAt,m.data.askedAt,m.data.createdAt,...m.data.editedAts??[]].filter(Boolean).sort().pop();p&&p>h&&(h=p,d=m)}return d?{node:d,at:h}:null},[s]);if(vt||t==="work"||r<2)return null;const c=()=>{if(!l)return;ye.getState().setBeaconNodeId(null);const{node:d}=l;a.setCenter(d.position.x+260,d.position.y+110,{zoom:1,duration:1100}),window.setTimeout(()=>{oe.getState().setSelectedNodeId(d.id),ye.getState().setPanelOpen(!0),window.setTimeout(()=>{a.setCenter(d.position.x+260+$f(d.id)/2,d.position.y+110,{zoom:1,duration:300})},60)},1150),window.setTimeout(()=>{Ke("success",n("continue.arrived"),12e3,{label:n("continue.summarize"),run:()=>{kN(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:()=>ye.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(Sb,{size:16,strokeWidth:1.75})," ",n("tmap.export")]}),l&&u.jsxs("button",{onClick:c,onMouseEnter:()=>ye.getState().setBeaconNodeId(l.node.id),onMouseLeave:()=>ye.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(uz,{size:16,strokeWidth:1.75})," ",n("continue.button")]})]})}function Aae(){const e=Qd(),t=ln(n=>n.transform[2]);return j.useEffect(()=>{document.querySelector(".react-flow")?.setAttribute("data-zoom-tier",e)},[e]),j.useEffect(()=>{document.querySelector(".react-flow")?.style.setProperty("--tdag-zoom",String(t))},[t]),null}rte();const Nae="/thoughtdag/api";window.desktopSessions||lH(Nae);vt?bB():(H7(),navigator.storage?.persist&&navigator.storage.persist(),Kt(()=>Promise.resolve().then(()=>Zne),void 0).then(e=>e.bootAutoBackup()));Kt(()=>import("./update-check-Ca6SiYKC.js"),[]).then(e=>e.bootUpdateCheck());window.addEventListener("hashchange",()=>{window.location.hash.startsWith("#view=")!==vt&&window.location.reload()});QC.createRoot(document.getElementById("root")).render(u.jsx(j.StrictMode,{children:u.jsx(kae,{})}));export{zd as A,nr as B,Jz as C,Mae as D,K7 as E,um as F,Lb as G,mm as H,Kt as _,Ie as a,oe as b,Nn as c,Ts as d,vt as e,qe as f,U7 as g,ks as h,Rae as i,zr as j,jc as k,fm as l,_x as m,jH as n,In as o,ni as p,RH as q,LH as r,Ao as s,Ke as t,ye as u,W7 as v,Es as w,Iae as x,_ae as y,Cae as z};
|