dsh-thoughtdag 0.4.16 → 0.4.17
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/dist-app/assets/{canonical-ChxvAi6N.js → canonical-D4SquoNo.js} +2 -2
- package/dist-app/assets/{canvas-record-Be2aKIf8.js → canvas-record--EHyNDCM.js} +1 -1
- package/dist-app/assets/{claude-code-session-B51keZPd.js → claude-code-session-CJTZw-s-.js} +1 -1
- package/dist-app/assets/{codex-session-BR_x_Fzf.js → codex-session-kzdkETJK.js} +1 -1
- package/dist-app/assets/{dsh-session-D0yZa0_o.js → dsh-session-DrnTTQ3v.js} +1 -1
- package/dist-app/assets/{experiment-loop-pAs6MwPV.js → experiment-loop-BysOJBTB.js} +1 -1
- package/dist-app/assets/{index-JMt9ljo3.js → index-C1uc774A.js} +11 -11
- package/dist-app/assets/{index-DvBTIsHr.js → index-DE_CLHc3.js} +1 -1
- package/dist-app/assets/{index-_B6z8_Ff.js → index-DMEJ2pfg.js} +3 -3
- package/dist-app/assets/{index-962V9CYS.js → index-k_sPEfl2.js} +1 -1
- package/dist-app/assets/{live-mirror-C9sTXAvv.js → live-mirror-CkSO5X2s.js} +2 -2
- package/dist-app/assets/{pi-session-B7frsRRp.js → pi-session-CIlDUNBG.js} +1 -1
- package/dist-app/assets/{sensitive-scan-Cwg4RAEk.js → sensitive-scan-OXO0A60C.js} +1 -1
- package/dist-app/assets/{session-handoff-BXosSY-e.js → session-handoff-DF4fnjEz.js} +2 -2
- package/dist-app/assets/{shared-L3KzXorg.js → shared-ClPLXGBi.js} +1 -1
- package/dist-app/assets/{turndown-plugin-gfm.cjs-pG4f1F8S.js → turndown-plugin-gfm.cjs-DeGwvSez.js} +1 -1
- package/dist-app/assets/{update-check-lHz7ROW6.js → update-check-CNsM71E0.js} +1 -1
- package/dist-app/index.html +1 -1
- package/lib/index.js +34 -6
- package/package.json +1 -1
|
@@ -46,7 +46,7 @@ Economist: You analyze through incentives and trade-offs...`,"fanout.confirm":"F
|
|
|
46
46
|
`);m=k.pop()||"";for(const S of k){const w=S.trim();if(!w.startsWith("data: "))continue;const C=w.slice(6);if(C==="[DONE]")continue;let T;try{T=JSON.parse(C)}catch{continue}if(T.error){const M=typeof T.error=="string"?T.error:T.error.message;throw new Error(M||"Upstream stream error")}const N=T.choices?.[0];if(!N)continue;const D=N.delta;D?.content&&(p+=D.content,a(D.content));const O=D?.reasoning??D?.reasoning_content;O&&r(O);for(const M of D?.annotations??[]){const _=M.url_citation;_?.url&&!s.has(_.url)&&s.set(_.url,{title:_.title||_.url,url:_.url,media:"Web"})}N.finish_reason&&(x=N.finish_reason)}}return{text:p,finishReason:x}}async function _H(e,t,n,a,r,s,o,c){const d=t7(n,s),h=Zb(e.baseURL)&&c!==!1,m=new Map;let p="",x="";const b=k=>{p+=k,a(k,p)},y=k=>{x+=k,o?.onReasoning?.(k,x)};try{let k=await D5(e,h?`${t}:online`:t,d,b,y,m,r);if(h&&p.length===0&&(k=await D5(e,t,d,b,y,m,r)),p.length===0)throw new Error(`Model produced no text (finish: ${k.finishReason}, model: ${t}${h?" via :online":""})`);return m.size>0&&o?.onSources?.([...m.values()]),p}catch(k){throw n7(k)}}async function MH(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:t7(n,a)})});if(!r.ok){const o=await r.json().catch(()=>null);throw new Error(o?.error?.message||`HTTP ${r.status}`)}return(await r.json()).choices?.[0]?.message?.content??""}catch(r){throw n7(r)}}const IH=`${$i}/api/claude`,a7=()=>{const e=oi();return e.length>0?e:void 0},DH=`${$i}/api/stream`,OH=`${$i}/api/pdf-extract`,RH=`${$i}/api/approvals`;async function LH(e,t){const n=e.id,a=typeof t=="string"?{confirmed:t!=="rejected",...t==="allowed-session"?{scope:"session"}:{}}:t;if(e.channel?.runId&&window.desktopAgents)try{return await window.desktopAgents.answer(e.channel.runId,n,a)}catch{return!1}const r="confirmed"in a&&a.confirmed?"allowed-once":"rejected";try{return(await fetch(`${RH}/${encodeURIComponent(n)}`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"same-origin",body:JSON.stringify({outcome:r})})).ok}catch{return!1}}async function jH(e){const t=await fetch(OH,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({base64:e})});if(!t.ok){const n=await t.json().catch(()=>({error:`HTTP ${t.status}`}));throw new Error(kl(n,`HTTP ${t.status}`))}return t.json()}async function PH(e){try{const t=await fetch(`${$i}/api/fetch-url`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:e})});if(!t.ok){const n=await t.json().catch(()=>({error:t.status===404?"Proxy has no /api/fetch-url — restart it (npm run server)":`HTTP ${t.status}`}));throw new Error(kl(n,`HTTP ${t.status}`))}return t.json()}catch(t){throw e2(t)}}function e2(e){if(e instanceof DOMException&&e.name==="AbortError")return e;const t=e instanceof Error?e.message:"Unknown error";return new Error(/fetch|network|Failed to fetch/i.test(t)?`${t} — is the proxy running? (npm run server)`:t)}async function r7(e,t){if(!t?.length)return t;const n=await Fs(),a=e??n?.default??void 0,r=a?n?.models.find(s=>s.id===a):void 0;if(!(r&&r.vision===!1&&t.every(s=>s.hasCompanion)))return t}async function i7(e,t){if(!t?.length)return;const n=await Fs(),a=e??n?.default??void 0,r=a?n?.models.find(s=>s.id===a):void 0;if(r&&r.vision===!1)throw new Error(De("error.textOnlyModelImages"))}async function Bo(e,t,n){const a=n||pe.getState().selectedModel||void 0;t=await r7(a,t);const r=Jb();if(r&&a)return await i7(a,t),MH(r,a,e,t);try{const s=await fetch(IH,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({messages:e,images:t?.length?t:void 0,model:n||pe.getState().selectedModel||void 0,providers:a7()})});if(!s.ok){const c=await s.json().catch(()=>({error:"Unknown error"}));throw new Error(kl(c,`HTTP ${s.status}`))}return(await s.json()).text}catch(s){throw e2(s)}}async function s7(e,t,n,a,r,s,o,c){const d=o||pe.getState().selectedModel||void 0;if(d&&zc(d)&&window.desktopAgents)return r?.onDispatch?.({messages:e,images:a??[],model:d,toolPrefs:s??{},lane:"proxy"}),GU(e,t,n,a,r,d,c?.cwd?{cwd:c.cwd,sessionPath:c.sessionPath,forkEntryId:c.forkEntryId,continue:c.continue}:void 0,c?.nodeId);a=await r7(d,a);let h=!1;const m={...r,onRerouted:(k,S)=>{h=!0,r?.onRerouted?.(k,S)}},p=async(k,S)=>{const w=Jb();return w&&d?(await i7(d,k),r?.onDispatch?.({messages:e,images:k??[],model:d,toolPrefs:s??{},lane:"direct"}),_H(w,d,e,S,n,k,m,s?.web)):(r?.onDispatch?.({messages:e,images:k??[],model:d??"",toolPrefs:s??{},lane:"proxy"}),y(k,S))},x=d?tH(d):void 0,b=!!d&&oi().some(k=>k.models.some(S=>S.id===d));if(a?.length&&d&&b&&x!==!1){const k=d.split("/").pop()??d,S=(C,T)=>{nH(d,C)&&(o0(oi()).then(Tl).catch(()=>{}),Qe("info",We(De(T),{m:k})))};let w=!1;try{const C=await p(a,(T,N)=>{w=!0,t(T,N)});return x===void 0&&!h&&C.trim()&&S(!0,"toast.visionLearnedTrue"),C}catch(C){if(C instanceof DOMException&&C.name==="AbortError"||w||h)throw C;if(x===!0){const N=C instanceof Error?C.message:String(C);throw new Error(`${N} ${De("error.visionDeclaredHint")}`)}const T=await p(void 0,t);return T.trim()&&S(!1,"toast.visionLearnedFalse"),T}}return p(a,t);async function y(k,S){try{const w=await fetch(DH,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({messages:e,images:k?.length?k:void 0,webSearch:s?.web,scholarSearch:s?.scholar,mcpTools:s?.mcp,...pe.getState().searchEnginePref!=="server"?{searchEngine:pe.getState().searchEnginePref}:{},...pe.getState().anysearchKey?{anysearchKey:pe.getState().anysearchKey}:{},model:o||pe.getState().selectedModel||void 0,providers:a7(),...c?{harness:c}:{}}),signal:n});if(!w.ok){const M=await w.json().catch(()=>({error:"Unknown error"}));throw new Error(kl(M,`HTTP ${w.status}`))}const C=w.body.getReader(),T=new TextDecoder;let N="",D="",O="";for(;;){const{done:M,value:_}=await C.read();if(M)break;N+=T.decode(_,{stream:!0});const R=N.split(`
|
|
47
47
|
`);N=R.pop()||"";for(const G of R){const P=G.trim();if(!P||!P.startsWith("data: "))continue;const V=P.slice(6);if(V!=="[DONE]")try{const J=JSON.parse(V);if(J.error)throw new Error(kl(J.error,"Upstream stream error"));J.text&&(D+=J.text,S(J.text,D)),J.reasoning&&(O+=J.reasoning,m.onReasoning?.(J.reasoning,O)),J.tool?.query&&m.onToolCall?.(J.tool.name,J.tool.query),J.gatewaySearch&&m.onGatewaySearch?.(),typeof J.harnessSession=="string"&&m.onHarnessSession?.(J.harnessSession,!!J.continued),J.harnessTurn?.session&&m.onHarnessTurn?.(J.harnessTurn),J.approval?.id&&m.onApproval?.(J.approval),J.approvalDecided?.id&&m.onApprovalDecided?.(J.approvalDecided),Array.isArray(J.sources)&&m.onSources?.(J.sources),J.rerouted?.to&&(Qe("info",We(De("toast.visionRerouted"),{from:J.rerouted.from,to:J.rerouted.to}),7e3),m.onRerouted?.(J.rerouted.from,J.rerouted.to)),J.imageFallback?.model&&(Qe("info",We(De("toast.imagesAsText"),{model:J.imageFallback.model}),9e3),m.onImageFallback?.(J.imageFallback.model))}catch(J){if(J instanceof Error&&J.message!==V)throw J}}}return D}catch(w){throw e2(w)}}}const Ux="att-content:",o7=e=>`${Ux}${e}`,l7=e=>e.type==="application/pdf"&&!!e.content&&!e.contentInVault;async function t2(e){return l7(e)?(await Hr(o7(e.id),e.content),{...e,content:"",contentInVault:!0}):e}async function n2(e){return e.contentInVault?await El(o7(e.id))??"":e.content}async function a2(e){const t=[];for(const n of e){const a=n.data.attachments;if(!a?.some(s=>s.contentInVault)){t.push(n);continue}const r=[];for(const s of a){if(!s.contentInVault){r.push(s);continue}const o=await n2(s),c={...s,content:o};delete c.contentInVault,r.push(c)}t.push({...n,data:{...n.data,attachments:r}})}return t}async function Tm(e){const t=[];for(const n of e){const a=n.data.attachments;if(!a?.some(l7)){t.push(n);continue}const r=[];for(const s of a)r.push(await t2(s));t.push({...n,data:{...n.data,attachments:r}})}return t}async function c7(e){const t=await XS();let n=0;for(const a of t)typeof a!="string"||!a.startsWith(Ux)||e.has(a.slice(Ux.length))||(await Vc(a),n++);return n}const zH=Object.freeze(Object.defineProperty({__proto__:null,gcVault:c7,inlineVaultedContent:a2,internAttachment:t2,internNodes:Tm,loadAttachmentContent:n2},Symbol.toStringTag,{value:"Module"}));function BH(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 HH=/\.(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,UH=/\.x?html?$/i,FH=/\.(pptx?|key|odp|doc|rtf|odt|xlsx?|numbers|ods)$/i,Ud="image/*,.pdf,.txt,.md,.js,.ts,.tsx,.jsx,.py,.json,.csv,.yaml,.yml,.toml,.sh,.c,.cpp,.h,.java,.rs,.go,.rb,.swift,.css,.html,.htm,.xml,.sql";function Ac(e){return`${e.name}|${e.size}|${e.content?.substring(0,100)}`}function qH(e){return new Promise(t=>{const n=In(),a=new Date().toISOString(),r=e.type.startsWith("image/"),s=e.type==="application/pdf"||e.name.endsWith(".pdf"),o=e.type==="text/html"||UH.test(e.name),c=e.type.startsWith("text/")||HH.test(e.name),d=e.name.toLowerCase().endsWith(".docx");if(r){const h=new FileReader;h.onload=()=>{const m=h.result.split(",")[1];t({id:n,name:e.name,type:e.type,size:e.size,addedAt:a,content:m,thumbnailUrl:h.result})},h.readAsDataURL(e)}else if(s){const h=new FileReader;h.onload=()=>{const m=h.result.split(",")[1];t({id:n,name:e.name,type:"application/pdf",size:e.size,addedAt:a,content:m})},h.readAsDataURL(e)}else d?e.arrayBuffer().then(async h=>{try{const p=await(await Tt(()=>import("./index-
|
|
49
|
+
`).trim()}const HH=/\.(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,UH=/\.x?html?$/i,FH=/\.(pptx?|key|odp|doc|rtf|odt|xlsx?|numbers|ods)$/i,Ud="image/*,.pdf,.txt,.md,.js,.ts,.tsx,.jsx,.py,.json,.csv,.yaml,.yml,.toml,.sh,.c,.cpp,.h,.java,.rs,.go,.rb,.swift,.css,.html,.htm,.xml,.sql";function Ac(e){return`${e.name}|${e.size}|${e.content?.substring(0,100)}`}function qH(e){return new Promise(t=>{const n=In(),a=new Date().toISOString(),r=e.type.startsWith("image/"),s=e.type==="application/pdf"||e.name.endsWith(".pdf"),o=e.type==="text/html"||UH.test(e.name),c=e.type.startsWith("text/")||HH.test(e.name),d=e.name.toLowerCase().endsWith(".docx");if(r){const h=new FileReader;h.onload=()=>{const m=h.result.split(",")[1];t({id:n,name:e.name,type:e.type,size:e.size,addedAt:a,content:m,thumbnailUrl:h.result})},h.readAsDataURL(e)}else if(s){const h=new FileReader;h.onload=()=>{const m=h.result.split(",")[1];t({id:n,name:e.name,type:"application/pdf",size:e.size,addedAt:a,content:m})},h.readAsDataURL(e)}else d?e.arrayBuffer().then(async h=>{try{const p=await(await Tt(()=>import("./index-k_sPEfl2.js").then(x=>x.i),[])).extractRawText({arrayBuffer:h});t({id:n,name:e.name,type:"text/plain",size:e.size,addedAt:a,content:p.value.trim()})}catch{t(null)}}):o?e.text().then(h=>{t({id:n,name:e.name,type:"text/html",size:e.size,addedAt:a,content:h})}):c?e.text().then(h=>{t({id:n,name:e.name,type:e.type||"text/plain",size:e.size,addedAt:a,content:h})}):t(null)})}async function O5(e){const[t,n]=await Promise.all([Tt(()=>import("./pdf-gh-BrLFn.js"),[]),Tt(()=>import("./pdf.worker.min-C_APr3k7.js"),[])]);t.GlobalWorkerOptions.workerSrc=n.default;const a=Uint8Array.from(atob(e),r=>r.charCodeAt(0));return t.getDocument({data:a,verbosity:0}).promise}const WH=150;async function R5(e){const t=WH/72,n=[];for(let a=1;a<=e.numPages;a++){const r=document.createElement("canvas");try{const s=await e.getPage(a),o=s.getViewport({scale:t});r.width=Math.ceil(o.width),r.height=Math.ceil(o.height);const c=r.getContext("2d");if(!c)throw new Error("no 2d context");await s.render({canvasContext:c,viewport:o}).promise}catch{r.width=8,r.height=8}n.push(r.toDataURL("image/png").split(",")[1])}return n}async function l0(e,t){if(FH.test(e.name)){Qe("info",`${e.name}: ${De("content.officeExportHint")}`);return}const n=await qH(e);if(!n)return;if(n.type==="text/html"){t.add({...n,isExtracting:!0});try{const{extractHtmlMaterial:r}=await Tt(async()=>{const{extractHtmlMaterial:o}=await Promise.resolve().then(()=>g9);return{extractHtmlMaterial:o}},void 0),s=await r(n.content);t.update(n.id,{extractedText:s.markdown,numPages:s.numPages,isExtracting:!1})}catch{t.update(n.id,{extractedText:BH(n.content),isExtracting:!1})}return}if(n.type!=="application/pdf"){t.add(n);return}const a=await t2(n);t.add({...a,isExtracting:!0});try{const r=await jH(n.content);if(!r.numPages&&!r.text?.trim())throw new Error("empty extraction result");const s=r.numPages||0;let o=r.images;if(!o?.length)try{const c=await O5(n.content);o=await R5(c),c.destroy()}catch{o=void 0}t.update(n.id,{extractedText:r.text,pageImages:o?.length?o:void 0,numPages:s,renderMode:s>b5?"text-only":"full",isExtracting:!1})}catch{try{const r=await O5(n.content),s=[];for(let c=1;c<=r.numPages;c++)try{const h=await(await r.getPage(c)).getTextContent();s.push(h.items.map(m=>"str"in m?m.str:"").join(" "))}catch{s.push("")}let o;try{o=await R5(r)}catch{o=void 0}r.destroy(),t.update(n.id,{extractedText:s.join(`
|
|
50
50
|
|
|
51
51
|
`).trim(),pageImages:o?.length?o:void 0,numPages:r.numPages,renderMode:r.numPages>b5?"text-only":"full",isExtracting:!1})}catch{t.update(n.id,{isExtracting:!1})}}}const Xu="[*_`~()#>\\[\\]|-]*",VH="\\s+(?:(?:\\d{1,3}[.)]|[-*+>|]|#{1,6}|[-:|]{3,})\\s+)*";function r2(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(`${Xu}${VH}${Xu}${s}`):n.push(`${Xu}${s}`),a=!1}try{return new RegExp(Xu+n.join("")+Xu,"g")}catch{return null}}function GH(e,t){const n=r2(t);return n?n.test(e):!1}function xf(e,t){const n=e??[],a=n.filter(r=>GH(t,r.text));return a.length===n.length?n:a}function L5(e){const t=e.data.question.replace(/\s+/g," ").trim();return t.length>60?`${t.slice(0,60)}…`:t}function u7(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 @@ ${H}`:`[File: ${V.name} — HTML with no extractable text yet]`}),h.push(R(V))}e
|
|
|
58
58
|
${V.content}`}),h.push(R(V))}if(G.size>0&&P){const V=[...G.entries()].map(([H,F])=>`${H}: ${[...F].join(", ")}`),J=M.data.agentSession?.cwd??M.data.importSource?.cwd;c.push({role:"user",content:`[Files this turn touched${J?` in ${J}`:""} — contents not included] ${V.join("; ")}`}),h.push(R(P))}};for(const M of k)if(!M.data.archived&&(D(M,"material"),M.data.question)){const _=M.data.stepKind==="note"?`[Note]
|
|
59
59
|
${M.data.question}`:M.data.stepKind==="link"?`[Link snapshot: ${M.data.linkUrl??""} @ ${(M.data.linkFetchedAt??"").slice(0,10)}]
|
|
60
60
|
${M.data.question}`:M.data.question;c.push({role:"user",content:_}),h.push({layer:"material",nodeId:M.id,part:"question"})}b("material");for(const M of S)M.source.data.archived||(c.push({role:"user",content:Fd(M)}),h.push({layer:"reference",refSourceId:M.source.id,part:"reference"}));b("reference");for(const M of w)if(!M.data.archived&&(D(M,"chain"),M.data.question&&(c.push({role:"user",content:M.data.question}),h.push({layer:"chain",nodeId:M.id,part:"question"})),M.data.response)){const _=u7(M);c.push({role:"assistant",content:y.has(M.id)?`${YH}
|
|
61
|
-
${_}`:_}),h.push({layer:"chain",nodeId:M.id,part:"response"})}a&&(c.push({role:"user",content:`[Regarding this passage: "${a}"]`}),h.push({layer:"branch",nodeId:e,part:"passage"})),b("chain");const O=h7(w,t);return O&&(c.unshift({role:"system",content:O}),h.unshift({layer:"system",part:"role"})),{messages:c,images:d,layerTokens:p,sources:h,imageSources:m}}function P5(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 z5(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 Rr(){return pe.getState().condenseRun.status!=="building"?!1:(Qe("info",De("condense.editLocked")),!0)}const XH=(e,t)=>({history:[{nodes:[],edges:[]}],historyIndex:0,pushHistory:()=>{const{nodes:n,edges:a,history:r,historyIndex:s}=t(),o=r.slice(0,s+1);o.push({nodes:n,edges:a}),o.length>GB&&o.shift(),e({history:o,historyIndex:o.length-1})},undo:()=>{if(Rr())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(Rr())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 Fx(e){return{x:e.position.x,y:e.position.y,width:e.measured?.width??e.width??0,height:e.measured?.height??e.height??0}}function QH(e){return{x:e.position.x+(e.measured?.width??520)/2,y:e.position.y+(e.measured?.height??120)/2}}const f7=e=>e.data.stepKind==="frame";function m7(e,t){return e.width*e.height>t.width*t.height&&t.x>=e.x&&t.y>=e.y&&t.x+t.width<=e.x+e.width&&t.y+t.height<=e.y+e.height}function p7(e,t){const n=Fx(e);return t.filter(a=>{if(a.id===e.id)return!1;if(f7(a))return m7(n,Fx(a));const r=QH(a);return r.x>=n.x&&r.x<=n.x+n.width&&r.y>=n.y&&r.y<=n.y+n.height})}function g7(e){if(e.data.isCollapsed)return $B;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 Ss(e){return Math.max(e.measured?.height??0,g7(e))}function ZH(e,t){const n=e.filter(r=>r.data.stepKind==="note"&&r.data.importSource&&t.some(s=>s.target===r.id));if(n.length===0)return t;let a=[...t];for(const r of n){const s=a.filter(c=>c.target===r.id),o=a.find(c=>c.source===r.id);if(a=a.filter(c=>c.target!==r.id),!!o)for(const c of s)a.some(d=>d.source===c.source&&d.target===o.target)||a.push({...c,target:o.target})}return a}const JH=36,eU=44,tU=24,nU=280,aU=180;function rU(e){const n=e.filter(o=>o.data.stepKind==="frame"&&o.data.frameCarry!==!1).map(o=>{const c=p7(o,e).filter(d=>!f7(d)).map(d=>d.id);return{id:o.id,memberIds:c,rect:Fx(o),nestingLevel:0}}),a=(o,c)=>o.id!==c.id&&m7(o.rect,c.rect),r=new Map,s=o=>{const c=r.get(o.id);if(c!==void 0)return c;const d=n.filter(m=>a(o,m)),h=d.length===0?0:1+Math.max(...d.map(s));return r.set(o.id,h),h};for(const o of n)o.nestingLevel=s(o);return n}function rr(e,t){if(e.length===0)return e;const n=rU(e),a=new Set(e.filter(X=>["note","file","link","frame"].includes(X.data.stepKind??"")).map(X=>X.id)),r=e.filter(X=>!a.has(X.id)),s=t.filter(X=>!a.has(X.source)&&!a.has(X.target)),o=g1,c=y5,d=v5,h=24,m=s.filter(X=>!X.data?.isCrossLink),p=new Set(m.map(X=>X.target));for(const X of s)X.data?.isCrossLink&&!X.data?.isWatch&&!p.has(X.target)&&(m.push(X),p.add(X.target));const x=new Set(m.map(X=>X.target)),b=r.filter(X=>!x.has(X.id)),y=new Map;for(const X of m){const oe=y.get(X.target)||[];oe.push(X.source),y.set(X.target,oe)}const k=new Map,S=new Map;for(const X of b){const oe=t.filter(Re=>Re.target===X.id&&!Re.data?.isCrossLink&&a.has(Re.source)).map(Re=>e.find(Ce=>Ce.id===Re.source)).filter(Re=>!!Re);if(oe.length===0)continue;const ve=oe.reduce((Re,Ce)=>Re.position.y+Ss(Re)>Ce.position.y+Ss(Ce)?Re:Ce),Le=S.get(ve.id)??0;S.set(ve.id,Le+1),k.set(X.id,{x:ve.position.x-60+Le*(g1+y5),y:ve.position.y+Ss(ve)+v5})}const w=new Map;for(const X of m){const oe=w.get(X.source)||[];oe.push(X.target),w.set(X.source,oe)}const C=(X,oe)=>`${X}\0${oe}`,T=new Set(s.filter(X=>X.data?.isBranchFromSelection).map(X=>C(X.source,X.target)));function N(X,oe){const ve=(w.get(X)||[]).filter(Ce=>(oe.get(Ce)??X)===X),Le=ve.filter(Ce=>!T.has(C(X,Ce))),Re=ve.filter(Ce=>T.has(C(X,Ce)));return{continuation:Le[0]??null,regenerates:Le.slice(1),explores:Re}}const D=1e5;function O(X){const oe=new Map;let ve=0,Le=D;const Re=new Map,Ce=Ve=>Re.get(Ve)??Ve*(o+c);function tt(Ve,ze){if(oe.has(Ve))return;oe.set(Ve,ze);const{continuation:bt,regenerates:ct,explores:Ke}=N(Ve,X);bt&&tt(bt,ze);for(let vt=0;vt<ct.length;vt++){let He;ze>=D?(He=Le++,Re.set(He,Ce(ze)+(vt+1)*(o+c))):(He=ze+1+vt,ve=Math.max(ve,He+1)),tt(ct[vt],He)}let it=0;for(const vt of Ke){let He;ze>=D?(He=Le++,Re.set(He,Ce(ze)+(ct.length+1+it)*(o+c)),it++):(He=ve,ve++),tt(vt,He)}}for(const Ve of b){const ze=k.get(Ve.id);if(ze){const bt=Le++;Re.set(bt,ze.x),tt(Ve.id,bt)}else{const bt=ve;ve++,tt(Ve.id,bt)}}for(let Ve=0;Ve<r.length;Ve++){let ze=!1;for(const bt of r){if(oe.has(bt.id))continue;const ct=(y.get(bt.id)||[]).map(Ke=>oe.get(Ke)).filter(Ke=>Ke!==void 0).sort((Ke,it)=>Ke-it);ct.length&&(tt(bt.id,ct[Math.floor((ct.length-1)/2)]),ze=!0)}if(!ze)break}return{nodeColumn:oe,colX:Ce}}const M=new Map;for(const[X,oe]of y){if(oe.length<2)continue;const ve=oe.filter(Re=>!T.has(C(Re,X))),Le=ve.length?ve:oe;M.set(X,Le[0])}const{nodeColumn:_,colX:R}=O(M),G=new Map;for(const X of r)G.set(X.id,Ss(X));const P=new Map,V=new Set,J=[...b.map(X=>X.id)];for(const X of J){const oe=_.get(X)??0,ve=k.get(X);P.set(X,{x:R(oe),y:ve?.y??0}),V.add(X)}for(;J.length>0;){const X=J.shift(),oe=P.get(X),ve=G.get(X)||220,{continuation:Le,regenerates:Re,explores:Ce}=N(X,M);if(Le&&!V.has(Le)){V.add(Le);const Ve=_.get(Le)??0;P.set(Le,{x:R(Ve),y:oe.y+ve+d}),J.push(Le)}const tt=oe.y+ve+d;for(const Ve of Re){if(V.has(Ve))continue;V.add(Ve);const ze=_.get(Ve)??0;P.set(Ve,{x:R(ze),y:tt}),J.push(Ve)}for(const Ve of Ce){if(V.has(Ve))continue;V.add(Ve);const ze=_.get(Ve)??0;P.set(Ve,{x:R(ze),y:oe.y+ve*.25}),J.push(Ve)}}for(let X=0;X<r.length;X++){let oe=!1;for(const ve of r){if(P.has(ve.id))continue;const Le=(y.get(ve.id)||[]).filter(Ce=>P.has(Ce));if(!Le.length)continue;const Re=Math.max(...Le.map(Ce=>P.get(Ce).y+(G.get(Ce)||220)));P.set(ve.id,{x:R(_.get(ve.id)??0),y:Re+d}),oe=!0}if(!oe)break}for(const X of r)P.has(X.id)||P.set(X.id,{x:0,y:0});for(let X=0;X<5;X++){let oe=!1;for(const ve of r){const Le=P.get(ve.id);if(!Le)continue;const Re=(y.get(ve.id)||[]).filter(ze=>P.has(ze));if(Re.length<2)continue;const Ce=Re.filter(ze=>!T.has(`${ze}\0${ve.id}`)),tt=Re.filter(ze=>T.has(`${ze}\0${ve.id}`));let Ve=-1/0;for(const ze of Ce)Ve=Math.max(Ve,P.get(ze).y+(G.get(ze)||220)+d);for(const ze of tt)Ve=Math.max(Ve,P.get(ze).y);if(Ve>-1/0&&Le.y<Ve){const ze=Ve-Le.y;Le.y=Ve;for(const bt of new Set(Mo(ve.id,m))){const ct=P.get(bt);ct&&(ct.y+=ze)}oe=!0}}if(!oe)break}const H=new Map;for(const X of r){const oe=_.get(X.id)??0,ve=H.get(oe)||[];ve.push(X.id),H.set(oe,ve)}for(let X=0;X<5;X++){let oe=!1;for(const[,ve]of H){ve.sort((Le,Re)=>P.get(Le).y-P.get(Re).y);for(let Le=1;Le<ve.length;Le++){const Re=ve[Le-1],Ce=ve[Le],tt=P.get(Re),Ve=P.get(Ce),ze=G.get(Re)||220,bt=tt.y+ze+h;if(Ve.y<bt){const ct=bt-Ve.y;Ve.y=bt,oe=!0;for(const Ke of new Set(Mo(Ce,m))){const it=P.get(Ke);it&&(it.y+=ct)}}}}if(!oe)break}const F=8e3,B=180,W=e.filter(X=>X.data.stepKind==="note"&&X.data.importSource),Q=new Set(t.filter(X=>W.some(oe=>oe.id===X.source)).map(X=>X.target));for(const X of b){const oe=[];let ve=X.id,Le=!0;for(;ve;){oe.push(ve);const Ke=w.get(ve)||[];if(Ke.length>1){Le=!1;break}ve=Ke[0]}if(!Le||oe.length<8)continue;const Re=new Set(oe),Ce=P.get(oe[0]),tt=oe[oe.length-1];if(P.get(tt).y+(G.get(tt)||220)-Ce.y<=F||r.some(Ke=>!Re.has(Ke.id)&&P.get(Ke.id).x>Ce.x+o/2))continue;let bt=0,ct=Ce.y;for(const Ke of oe){const it=G.get(Ke)||220,vt=ct-Ce.y,He=vt+it>F,It=Q.has(Ke)&&vt>F*.6;(He||It)&&ct!==Ce.y&&(bt++,ct=Ce.y);const re=P.get(Ke);re.x=Ce.x+bt*(o+B),re.y=ct,ct+=it+d}}const K=r.map(X=>{const oe=P.get(X.id);return{x:oe.x,y:oe.y,w:o,h:G.get(X.id)||220}}),U=460,q=130,te=(X,oe)=>K.some(ve=>X<ve.x+ve.w&&X+U>ve.x&&oe<ve.y+ve.h&&oe+q>ve.y),$=new Map;for(const X of W){const oe=t.find(Ce=>Ce.source===X.id)?.target,ve=oe?P.get(oe):void 0;if(!ve)continue;let Le=ve.x-520,Re=ve.y;if(te(Le,Re)&&(Le=ve.x,Re=ve.y-q-40),te(Le,Re)){const Ce=Math.round(ve.x),tt=Math.min(...r.filter(ze=>Math.round(P.get(ze.id).x)===Ce).map(ze=>P.get(ze.id).y)),Ve=$.get(Ce)??0;$.set(Ce,Ve+1),Le=ve.x,Re=tt-q-40-Ve*(q+30)}P.set(X.id,{x:Le,y:Re})}const be=new Map,Te=new Map(e.map(X=>[X.id,X])),Se=new Set(["note","file","link"]),Be=[...n].sort((X,oe)=>X.nestingLevel-oe.nestingLevel);for(const X of Be){if(X.memberIds.length===0)continue;const oe=X.memberIds.map(it=>{const vt=Te.get(it);if(!vt)return null;const He=P.get(it)??vt.position,It=vt.measured?.width??vt.width??g1,re=Se.has(vt.data.stepKind??"")?vt.measured?.height??vt.height??120:Math.max(vt.measured?.height??0,vt.height??0,Ss(vt));return{x:He.x,y:He.y,width:It,height:re}}).filter(it=>it!==null);if(oe.length===0)continue;const ve=Math.min(...oe.map(it=>it.x)),Le=Math.min(...oe.map(it=>it.y)),Re=Math.max(...oe.map(it=>it.x+it.width)),Ce=Math.max(...oe.map(it=>it.y+it.height)),tt=JH+X.nestingLevel*tU,Ve=tt+eU,ze=ve-tt,bt=Le-Ve,ct=Math.max(nU,Re-ve+tt*2),Ke=Math.max(aU,Ce-Le+Ve+tt);be.set(X.id,{position:{x:ze,y:bt},width:ct,height:Ke})}return e.map(X=>{const oe=be.get(X.id);if(oe)return{...X,...oe};const ve=P.get(X.id);return ve?{...X,position:ve}:X})}const iU=(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(Rr())return;t().logEvent("delete",n,{n:1}),t().pushHistory();const{edges:a}=t(),r=Mo(n,a),s=new Set([n,...r]);e(o=>({nodes:o.nodes.filter(c=>!s.has(c.id)),edges:o.edges.filter(c=>!s.has(c.source)&&!s.has(c.target))})),t().pushHistory(),Tt(()=>import("./canonical-ChxvAi6N.js"),[]).then(o=>o.unsubscribeOrphanedSessions())},deleteEdges:n=>{if(Rr())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(Rr())return;t().logEvent("edit-response",n,{chars:a.length}),t().pushHistory();const r=$n(t().nodes.find(s=>s.id===n)?.data.question+a||a);e(s=>({nodes:s.nodes.map(o=>o.id===n?{...o,data:{...o.data,response:a,responses:o.data.responses.map((c,d)=>d===o.data.responseIndex?a:c),summaries:o.data.summaries?.map((c,d)=>d===o.data.responseIndex?void 0:c),summaryTypes:o.data.summaryTypes?.map((c,d)=>d===o.data.responseIndex?void 0:c),editedAts:o.data.responses.map((c,d)=>d===o.data.responseIndex?new Date().toISOString():o.data.editedAts?.[d]),highlights:xf(o.data.highlights,a),isEditingResponse:!1,tokenCount:r}}:o)})),t().pushHistory()},toggleCollapse:n=>{const a=t().nodes.find(h=>h.id===n);if(!a)return;const r=Ss(a),o=g7({...a,data:{...a.data,isCollapsed:!a.data.isCollapsed}})-r,c=Mo(n,t().edges),d=new Set(c);e(h=>({nodes:h.nodes.map(m=>m.id===n?{...m,data:{...m.data,isCollapsed:!m.data.isCollapsed}}:d.has(m.id)?{...m,position:{...m.position,y:m.position.y+o}}:m)}))},setEditing:(n,a)=>{a&&Rr()||e(r=>({nodes:r.nodes.map(s=>s.id===n?{...s,data:{...s.data,isEditing:a}}:s)}))},setEditingResponse:(n,a)=>{a&&Rr()||e(r=>({nodes:r.nodes.map(s=>s.id===n?{...s,data:{...s.data,isEditingResponse:a}}:s)}))},duplicateNode:n=>{const a=t().nodes.find(m=>m.id===n);if(!a)return;t().pushHistory();const r=In(),s={id:r,type:"thought",position:{x:0,y:0},dragHandle:".drag-handle",data:{...a.data,isCollapsed:!0,isEditing:!1,isEditingResponse:!1,isLoading:!1,highlights:a.data.highlights.map(m=>({...m,id:In()}))}},o=t().edges.find(m=>m.target===n),c=o?{...o,id:`edge-${o.source}-${r}`,target:r}:null,d=c?[...t().edges,c]:t().edges,h=rr([...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:rt.accent,strokeDasharray:"8 4",strokeWidth:2},animated:!0,data:{isCrossLink:!0,createdAt:new Date().toISOString()}};e(y=>({edges:[...y.edges,x]})),t().logEvent("connect",x.id),t().setEdgeStructural(x.id,!0);const b=t().edges.find(y=>y.id===x.id);if(b&&!b.data?.isCrossLink){const k=wr(n,t().nodes,t().edges).messages.reduce((S,w)=>S+$n(w.content),0);Qe("success",We(De("edge.materialWiredFull"),{n:k.toLocaleString()}),8e3,{label:De("edge.materialMakeQuote"),run:()=>t().setEdgeStructural(x.id,!1)})}return}t().pushHistory();const d=s.find(x=>x.id===n),h=s.find(x=>x.id===a),m=!!d&&!!h&&h.position.y>d.position.y+60&&Math.abs(h.position.x-d.position.x)<320,p={id:`crosslink-${n}-${a}`,source:n,sourceHandle:m?"continue":"branch",target:a,targetHandle:m?"top":"left",type:"smoothstep",style:{stroke:rt.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}=Ur(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(Fd({source:d,depth:"quote",chain:b})),S=wr(n,s,r).messages.reduce((w,C)=>w+$n(C.content),0)+$n(d.data.question+d.data.response);Qe("info",We(De("edge.linkedQuote"),{n:y}),8e3,{label:We(De("edge.makeFull"),{m:S}),run:()=>t().setEdgeStructural(p.id,!0)})}}},staleIds:[],recomputeStaleness:()=>{const{nodes:n,edges:a}=t(),r=[];for(const o of n)!o.data.lastContextHash||!o.data.response||["note","file","link","frame"].includes(o.data.stepKind??"")||d7(o.id,n,a)!==o.data.lastContextHash&&r.push(o.id);const s=t().staleIds;s.length===r.length&&s.every((o,c)=>o===r[c])||e({staleIds:r})},setEdgeStructural:(n,a)=>{const{nodes:r,edges:s}=t(),o=s.find(c=>c.id===n);if(o){if(a){const c=s.filter(h=>!h.data?.isCrossLink),{ordered:d}=Ur(o.source,r,c);if(d.some(h=>h.id===o.target)){Qe("error",De("edge.cycleBlocked"));return}}t().pushHistory(),t().logEvent(a?"connect":"disconnect",n,{convert:!0}),e(c=>({edges:c.edges.map(d=>{if(d.id!==n)return d;if(a){const h={...d.data??{}};return delete h.isCrossLink,delete h.contextDepth,delete h.isWatch,{...d,sourceHandle:"continue",targetHandle:"top",animated:!1,style:{stroke:rt.accent,strokeWidth:2},markerEnd:{type:"arrowclosed",color:rt.accent,width:18,height:18},data:h}}return{...d,animated:!0,style:{stroke:rt.accent,strokeDasharray:"8 4",strokeWidth:2},markerEnd:{type:"arrowclosed",color:rt.accent,width:18,height:18},data:{...d.data??{},isCrossLink:!0,contextDepth:void 0}}})})),e(c=>({nodes:rr(c.nodes,c.edges)})),t().pushHistory()}},setCrossLinkDepth:(n,a)=>{t().pushHistory(),e(r=>({edges:r.edges.map(s=>s.id!==n||!s.data?.isCrossLink?s:{...s,style:{...s.style,strokeDasharray:a==="full"?"12 3":"8 4",strokeWidth:a==="full"?3:2},data:{...s.data,contextDepth:a==="full"?"full":void 0}})})),t().pushHistory()},navigateVersion:(n,a)=>{e(r=>({nodes:r.nodes.map(s=>{if(s.id!==n)return s;const{responses:o,responseIndex:c}=s.data;let d=a==="prev"?c-1:c+1;return d<0&&(d=o.length-1),d>=o.length&&(d=0),{...s,data:{...s.data,responseIndex:d,response:o[d],question:s.data.questions?.[d]??s.data.question,generationFailed:void 0,highlights:xf(s.data.highlights,o[d])}}})}))},deleteVersion:(n,a)=>{t().pushHistory(),e(r=>({nodes:r.nodes.map(s=>{if(s.id!==n)return s;const o=s.data.responses.filter((d,h)=>h!==a);if(o.length===0)return s;const c=Math.min(s.data.responseIndex,o.length-1);return{...s,data:{...s.data,responses:o,responseIndex:c,response:o[c],questions:s.data.questions?.filter((d,h)=>h!==a),question:s.data.questions?.filter((d,h)=>h!==a)[c]??s.data.question,summaries:s.data.summaries?.filter((d,h)=>h!==a),generatedBy:s.data.generatedBy?.filter((d,h)=>h!==a),summaryTypes:s.data.summaryTypes?.filter((d,h)=>h!==a),reasonings:s.data.reasonings?.filter((d,h)=>h!==a),generatedAts:s.data.generatedAts?.filter((d,h)=>h!==a),editedAts:s.data.editedAts?.filter((d,h)=>h!==a),highlights:xf(s.data.highlights,o[c])}}})})),t().pushHistory()},relayout:()=>{Rr()||(t().pushHistory(),e(n=>{const a=ZH(n.nodes,n.edges);return{nodes:rr(n.nodes,a),edges:a}}),t().pushHistory())},setArchived:(n,a)=>{const r=new Set(n);t().pushHistory(),t().logEvent(a?"archive":"unarchive",n[0],{n:n.length}),e(s=>({nodes:s.nodes.map(o=>r.has(o.id)?{...o,data:{...o.data,archived:a||void 0,archivedAt:a?new Date().toISOString():void 0}}:o)})),t().pushHistory()},setNodeModel:(n,a)=>{e(r=>({nodes:r.nodes.map(s=>s.id===n?{...s,data:{...s.data,model:a}}:s)}))},alignSelection:n=>{if(n.length<2)return;const a=new Set(n),{nodes:r,edges:s}=t(),o=new Map,c=s.filter(b=>!b.data?.isWatch),d=(b,y)=>{if(o.has(b))return o.get(b);if(y.has(b))return 0;y.add(b);const k=c.filter(w=>w.target===b&&a.has(w.source)),S=k.length===0?0:1+Math.max(...k.map(w=>d(w.source,y)));return o.set(b,S),S},h=n.map(b=>r.find(y=>y.id===b)).filter(b=>!!b).sort((b,y)=>d(b.id,new Set)-d(y.id,new Set)||b.position.y-y.position.y);t().pushHistory();const m=h[0].position;let p=m.y;const x=new Map;for(const b of h)x.set(b.id,{x:m.x,y:p}),p+=Ss(b)+40;e(b=>({nodes:b.nodes.map(y=>{const k=x.get(y.id);return k?{...y,position:k}:y})})),t().pushHistory()},batchDelete:n=>{if(Rr())return;t().logEvent("delete",n[0],{n:n.length}),t().pushHistory();const a=new Set(n);e(r=>({nodes:r.nodes.filter(s=>!a.has(s.id)),edges:r.edges.filter(s=>!a.has(s.source)&&!a.has(s.target)),selectedNodeId:null,selectedNodeIds:[]})),t().pushHistory(),Tt(()=>import("./canonical-ChxvAi6N.js"),[]).then(r=>r.unsubscribeOrphanedSessions())},duplicateSelection:n=>{const{nodes:a,edges:r}=t(),s=new Set(n),o=a.filter(M=>s.has(M.id));if(o.length===0)return;t().pushHistory();const c=M=>({x:M.position.x,y:M.position.y,w:M.measured?.width??M.width??520,h:M.measured?.height??M.height??Ss(M)}),d=o.map(c),h={x:Math.min(...d.map(M=>M.x)),y:Math.min(...d.map(M=>M.y)),right:Math.max(...d.map(M=>M.x+M.w)),bottom:Math.max(...d.map(M=>M.y+M.h))},m=80,p=h.right-h.x+m,x=h.bottom-h.y+m,b=[];for(let M=1;M<=6;M++)b.push({dx:M*p,dy:0},{dx:0,dy:M*x},{dx:M*p,dy:M*x});const y=a.filter(M=>M.data.stepKind!=="frame").map(c),k=(M,_)=>M.x<_.x+_.w&&M.x+M.w>_.x&&M.y<_.y+_.h&&M.y+M.h>_.y,S=b.find(M=>!d.some(_=>y.some(R=>k({..._,x:_.x+M.dx,y:_.y+M.dy},R))))??{dx:p,dy:x},w=new Map,C=new Map;for(const M of o){w.set(M.id,In());for(const _ of M.data.attachments??[])C.set(_.id,In())}const T=M=>(M??[]).map(_=>C.get(_)??_),N=o.map(M=>({...M,id:w.get(M.id),position:{x:M.position.x+S.dx,y:M.position.y+S.dy},selected:!0,data:{...M.data,attachments:(M.data.attachments??[]).map(_=>({..._,id:C.get(_.id)})),excludedAttachmentIds:T(M.data.excludedAttachmentIds),includedAttachmentIds:T(M.data.includedAttachmentIds),digestOf:M.data.digestOf?C.get(M.data.digestOf)??M.data.digestOf:void 0,highlights:(M.data.highlights??[]).map(_=>({..._,id:In()})),isEditing:!1,isEditingResponse:!1,isLoading:!1}})),D=r.filter(M=>s.has(M.source)&&s.has(M.target)).map(M=>({...M,id:`edge-${w.get(M.source)}-${w.get(M.target)}`,source:w.get(M.source),target:w.get(M.target),data:M.data?{...M.data}:M.data})),O=N.map(M=>M.id);e(M=>({nodes:[...M.nodes.map(_=>_.selected?{..._,selected:!1}:_),...N],edges:[...M.edges,...D],selectedNodeId:O.length===1?O[0]:null,selectedNodeIds:O})),t().pushHistory()}});function i2(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 Uf(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 sU(e,t){const n=[...e].sort((r,s)=>r.id<s.id?-1:1).map(r=>({id:r.id,stepKind:r.data.stepKind,question:r.data.question,response:r.data.response,archived:r.data.archived||void 0,branchContext:r.data.branchContext||void 0,highlightMode:r.data.highlightMode!=="off"?r.data.highlightMode:void 0,highlights:(r.data.highlights??[]).length>0?r.data.highlights.map(s=>s.text):void 0,linkUrl:r.data.linkUrl,linkFetchedAt:r.data.linkFetchedAt,rolePrompt:r.data.rolePrompt,roleMode:r.data.roleMode,excludedAttachmentIds:r.data.excludedAttachmentIds?.length?r.data.excludedAttachmentIds:void 0,attachments:(r.data.attachments??[]).map(s=>({id:s.id,name:s.name,type:s.type,fingerprint:Ac(s),extractedText:s.extractedText,renderMode:s.renderMode}))})),a=[...t].sort((r,s)=>r.id<s.id?-1:1).map(r=>({source:r.source,target:r.target,isCrossLink:r.data?.isCrossLink||void 0,isWatch:r.data?.isWatch||void 0,contextDepth:r.data?.contextDepth}));return{nodes:n,edges:a}}async function oU(e,t){return`sha256:${await Uf(i2(sU(e,t)))}`}function lU(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 pie(e,t,n,a){const r=wr(e,t,n,a.branchContext,void 0,void 0,a.staleIds),s=t.find(x=>x.id===e),o=r.messages.map((x,b)=>{const y=r.sources[b]??{layer:"chain"};return{id:`item_${String(b+1).padStart(3,"0")}`,kind:"message",role:x.role,content:[{type:"text",text:x.content}],source:{layer:y.layer,part:y.part,node_id:y.nodeId??y.refSourceId,attachment_id:y.attachmentId},selection:{mode:"full",reason:`structural-${y.layer}`}}}),c=new Map,d=(x,b)=>{if(!x||!b||c.has(b))return;const y=t.find(S=>S.id===x),k=y?.data.attachments?.find(S=>S.id===b);!y||!k||c.set(b,{id:b,kind:k.type.startsWith("image/")?"image":"document",name:k.name,mime_type:k.type,size:k.size,fingerprint:Ac(k),model_projection:{mode:lU(k)},source:{node_id:y.id}})};r.sources.forEach(x=>d(x.nodeId,x.attachmentId)),r.imageSources.forEach(x=>d(x.nodeId,x.attachmentId));const h=r.sources.filter(x=>x.layer==="reference"&&x.refSourceId).map(x=>({source_node_id:x.refSourceId})),m={format:"thoughtdag.context-bundle",version:0,graph:{project_id:a.projectId??null,snapshot_hash:await oU(t,n),target_node_id:e},intent:{task:a.task??s?.data.question??"",language:a.language??null},context:{messages:o,materials:[...c.values()],references:h},execution_hints:{preferred_model:a.preferredModel??s?.data.model??null,required_tools:[],required_mcp_servers:[]},budget:{estimated_tokens:r.messages.reduce((x,b)=>x+$n(b.content),0),limit:null,truncation:"none"}},p=await Uf(i2(m));return{...m,id:`cb_${p.slice(0,16)}`,created_at:a.now,provenance:{source_runs:[],compiler:{name:"thoughtdag",adapter_id:null}},integrity:{content_hash:`sha256:${p}`}}}const hc="dsh-sessions",k1="/session.jsonl.zstd",cU=1500,uU=2500,dU=6e4,hU=6e4,fU=600*1e3;let qx=null;function mU(e){if(window.desktopSessions)return;const t=e.replace(/\/+$/,""),n=async F=>{const B=await fetch(t+F,{credentials:"same-origin"});if(!B.ok)throw new Error(`${F}: ${B.status}`);return B.json()},a=async F=>{const B=await fetch(t+F,{credentials:"same-origin"});if(!B.ok)throw new Error(`${F}: ${B.status}`);return B.text()},r=new Map,s=F=>`${F}${k1}`,o=(F,B)=>{const W=F.indexOf(`
|
|
61
|
+
${_}`:_}),h.push({layer:"chain",nodeId:M.id,part:"response"})}a&&(c.push({role:"user",content:`[Regarding this passage: "${a}"]`}),h.push({layer:"branch",nodeId:e,part:"passage"})),b("chain");const O=h7(w,t);return O&&(c.unshift({role:"system",content:O}),h.unshift({layer:"system",part:"role"})),{messages:c,images:d,layerTokens:p,sources:h,imageSources:m}}function P5(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 z5(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 Rr(){return pe.getState().condenseRun.status!=="building"?!1:(Qe("info",De("condense.editLocked")),!0)}const XH=(e,t)=>({history:[{nodes:[],edges:[]}],historyIndex:0,pushHistory:()=>{const{nodes:n,edges:a,history:r,historyIndex:s}=t(),o=r.slice(0,s+1);o.push({nodes:n,edges:a}),o.length>GB&&o.shift(),e({history:o,historyIndex:o.length-1})},undo:()=>{if(Rr())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(Rr())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 Fx(e){return{x:e.position.x,y:e.position.y,width:e.measured?.width??e.width??0,height:e.measured?.height??e.height??0}}function QH(e){return{x:e.position.x+(e.measured?.width??520)/2,y:e.position.y+(e.measured?.height??120)/2}}const f7=e=>e.data.stepKind==="frame";function m7(e,t){return e.width*e.height>t.width*t.height&&t.x>=e.x&&t.y>=e.y&&t.x+t.width<=e.x+e.width&&t.y+t.height<=e.y+e.height}function p7(e,t){const n=Fx(e);return t.filter(a=>{if(a.id===e.id)return!1;if(f7(a))return m7(n,Fx(a));const r=QH(a);return r.x>=n.x&&r.x<=n.x+n.width&&r.y>=n.y&&r.y<=n.y+n.height})}function g7(e){if(e.data.isCollapsed)return $B;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 Ss(e){return Math.max(e.measured?.height??0,g7(e))}function ZH(e,t){const n=e.filter(r=>r.data.stepKind==="note"&&r.data.importSource&&t.some(s=>s.target===r.id));if(n.length===0)return t;let a=[...t];for(const r of n){const s=a.filter(c=>c.target===r.id),o=a.find(c=>c.source===r.id);if(a=a.filter(c=>c.target!==r.id),!!o)for(const c of s)a.some(d=>d.source===c.source&&d.target===o.target)||a.push({...c,target:o.target})}return a}const JH=36,eU=44,tU=24,nU=280,aU=180;function rU(e){const n=e.filter(o=>o.data.stepKind==="frame"&&o.data.frameCarry!==!1).map(o=>{const c=p7(o,e).filter(d=>!f7(d)).map(d=>d.id);return{id:o.id,memberIds:c,rect:Fx(o),nestingLevel:0}}),a=(o,c)=>o.id!==c.id&&m7(o.rect,c.rect),r=new Map,s=o=>{const c=r.get(o.id);if(c!==void 0)return c;const d=n.filter(m=>a(o,m)),h=d.length===0?0:1+Math.max(...d.map(s));return r.set(o.id,h),h};for(const o of n)o.nestingLevel=s(o);return n}function rr(e,t){if(e.length===0)return e;const n=rU(e),a=new Set(e.filter(X=>["note","file","link","frame"].includes(X.data.stepKind??"")).map(X=>X.id)),r=e.filter(X=>!a.has(X.id)),s=t.filter(X=>!a.has(X.source)&&!a.has(X.target)),o=g1,c=y5,d=v5,h=24,m=s.filter(X=>!X.data?.isCrossLink),p=new Set(m.map(X=>X.target));for(const X of s)X.data?.isCrossLink&&!X.data?.isWatch&&!p.has(X.target)&&(m.push(X),p.add(X.target));const x=new Set(m.map(X=>X.target)),b=r.filter(X=>!x.has(X.id)),y=new Map;for(const X of m){const oe=y.get(X.target)||[];oe.push(X.source),y.set(X.target,oe)}const k=new Map,S=new Map;for(const X of b){const oe=t.filter(Re=>Re.target===X.id&&!Re.data?.isCrossLink&&a.has(Re.source)).map(Re=>e.find(Ce=>Ce.id===Re.source)).filter(Re=>!!Re);if(oe.length===0)continue;const ve=oe.reduce((Re,Ce)=>Re.position.y+Ss(Re)>Ce.position.y+Ss(Ce)?Re:Ce),Le=S.get(ve.id)??0;S.set(ve.id,Le+1),k.set(X.id,{x:ve.position.x-60+Le*(g1+y5),y:ve.position.y+Ss(ve)+v5})}const w=new Map;for(const X of m){const oe=w.get(X.source)||[];oe.push(X.target),w.set(X.source,oe)}const C=(X,oe)=>`${X}\0${oe}`,T=new Set(s.filter(X=>X.data?.isBranchFromSelection).map(X=>C(X.source,X.target)));function N(X,oe){const ve=(w.get(X)||[]).filter(Ce=>(oe.get(Ce)??X)===X),Le=ve.filter(Ce=>!T.has(C(X,Ce))),Re=ve.filter(Ce=>T.has(C(X,Ce)));return{continuation:Le[0]??null,regenerates:Le.slice(1),explores:Re}}const D=1e5;function O(X){const oe=new Map;let ve=0,Le=D;const Re=new Map,Ce=Ve=>Re.get(Ve)??Ve*(o+c);function tt(Ve,ze){if(oe.has(Ve))return;oe.set(Ve,ze);const{continuation:bt,regenerates:ct,explores:Ke}=N(Ve,X);bt&&tt(bt,ze);for(let vt=0;vt<ct.length;vt++){let He;ze>=D?(He=Le++,Re.set(He,Ce(ze)+(vt+1)*(o+c))):(He=ze+1+vt,ve=Math.max(ve,He+1)),tt(ct[vt],He)}let it=0;for(const vt of Ke){let He;ze>=D?(He=Le++,Re.set(He,Ce(ze)+(ct.length+1+it)*(o+c)),it++):(He=ve,ve++),tt(vt,He)}}for(const Ve of b){const ze=k.get(Ve.id);if(ze){const bt=Le++;Re.set(bt,ze.x),tt(Ve.id,bt)}else{const bt=ve;ve++,tt(Ve.id,bt)}}for(let Ve=0;Ve<r.length;Ve++){let ze=!1;for(const bt of r){if(oe.has(bt.id))continue;const ct=(y.get(bt.id)||[]).map(Ke=>oe.get(Ke)).filter(Ke=>Ke!==void 0).sort((Ke,it)=>Ke-it);ct.length&&(tt(bt.id,ct[Math.floor((ct.length-1)/2)]),ze=!0)}if(!ze)break}return{nodeColumn:oe,colX:Ce}}const M=new Map;for(const[X,oe]of y){if(oe.length<2)continue;const ve=oe.filter(Re=>!T.has(C(Re,X))),Le=ve.length?ve:oe;M.set(X,Le[0])}const{nodeColumn:_,colX:R}=O(M),G=new Map;for(const X of r)G.set(X.id,Ss(X));const P=new Map,V=new Set,J=[...b.map(X=>X.id)];for(const X of J){const oe=_.get(X)??0,ve=k.get(X);P.set(X,{x:R(oe),y:ve?.y??0}),V.add(X)}for(;J.length>0;){const X=J.shift(),oe=P.get(X),ve=G.get(X)||220,{continuation:Le,regenerates:Re,explores:Ce}=N(X,M);if(Le&&!V.has(Le)){V.add(Le);const Ve=_.get(Le)??0;P.set(Le,{x:R(Ve),y:oe.y+ve+d}),J.push(Le)}const tt=oe.y+ve+d;for(const Ve of Re){if(V.has(Ve))continue;V.add(Ve);const ze=_.get(Ve)??0;P.set(Ve,{x:R(ze),y:tt}),J.push(Ve)}for(const Ve of Ce){if(V.has(Ve))continue;V.add(Ve);const ze=_.get(Ve)??0;P.set(Ve,{x:R(ze),y:oe.y+ve*.25}),J.push(Ve)}}for(let X=0;X<r.length;X++){let oe=!1;for(const ve of r){if(P.has(ve.id))continue;const Le=(y.get(ve.id)||[]).filter(Ce=>P.has(Ce));if(!Le.length)continue;const Re=Math.max(...Le.map(Ce=>P.get(Ce).y+(G.get(Ce)||220)));P.set(ve.id,{x:R(_.get(ve.id)??0),y:Re+d}),oe=!0}if(!oe)break}for(const X of r)P.has(X.id)||P.set(X.id,{x:0,y:0});for(let X=0;X<5;X++){let oe=!1;for(const ve of r){const Le=P.get(ve.id);if(!Le)continue;const Re=(y.get(ve.id)||[]).filter(ze=>P.has(ze));if(Re.length<2)continue;const Ce=Re.filter(ze=>!T.has(`${ze}\0${ve.id}`)),tt=Re.filter(ze=>T.has(`${ze}\0${ve.id}`));let Ve=-1/0;for(const ze of Ce)Ve=Math.max(Ve,P.get(ze).y+(G.get(ze)||220)+d);for(const ze of tt)Ve=Math.max(Ve,P.get(ze).y);if(Ve>-1/0&&Le.y<Ve){const ze=Ve-Le.y;Le.y=Ve;for(const bt of new Set(Mo(ve.id,m))){const ct=P.get(bt);ct&&(ct.y+=ze)}oe=!0}}if(!oe)break}const H=new Map;for(const X of r){const oe=_.get(X.id)??0,ve=H.get(oe)||[];ve.push(X.id),H.set(oe,ve)}for(let X=0;X<5;X++){let oe=!1;for(const[,ve]of H){ve.sort((Le,Re)=>P.get(Le).y-P.get(Re).y);for(let Le=1;Le<ve.length;Le++){const Re=ve[Le-1],Ce=ve[Le],tt=P.get(Re),Ve=P.get(Ce),ze=G.get(Re)||220,bt=tt.y+ze+h;if(Ve.y<bt){const ct=bt-Ve.y;Ve.y=bt,oe=!0;for(const Ke of new Set(Mo(Ce,m))){const it=P.get(Ke);it&&(it.y+=ct)}}}}if(!oe)break}const F=8e3,B=180,W=e.filter(X=>X.data.stepKind==="note"&&X.data.importSource),Q=new Set(t.filter(X=>W.some(oe=>oe.id===X.source)).map(X=>X.target));for(const X of b){const oe=[];let ve=X.id,Le=!0;for(;ve;){oe.push(ve);const Ke=w.get(ve)||[];if(Ke.length>1){Le=!1;break}ve=Ke[0]}if(!Le||oe.length<8)continue;const Re=new Set(oe),Ce=P.get(oe[0]),tt=oe[oe.length-1];if(P.get(tt).y+(G.get(tt)||220)-Ce.y<=F||r.some(Ke=>!Re.has(Ke.id)&&P.get(Ke.id).x>Ce.x+o/2))continue;let bt=0,ct=Ce.y;for(const Ke of oe){const it=G.get(Ke)||220,vt=ct-Ce.y,He=vt+it>F,It=Q.has(Ke)&&vt>F*.6;(He||It)&&ct!==Ce.y&&(bt++,ct=Ce.y);const re=P.get(Ke);re.x=Ce.x+bt*(o+B),re.y=ct,ct+=it+d}}const K=r.map(X=>{const oe=P.get(X.id);return{x:oe.x,y:oe.y,w:o,h:G.get(X.id)||220}}),U=460,q=130,te=(X,oe)=>K.some(ve=>X<ve.x+ve.w&&X+U>ve.x&&oe<ve.y+ve.h&&oe+q>ve.y),$=new Map;for(const X of W){const oe=t.find(Ce=>Ce.source===X.id)?.target,ve=oe?P.get(oe):void 0;if(!ve)continue;let Le=ve.x-520,Re=ve.y;if(te(Le,Re)&&(Le=ve.x,Re=ve.y-q-40),te(Le,Re)){const Ce=Math.round(ve.x),tt=Math.min(...r.filter(ze=>Math.round(P.get(ze.id).x)===Ce).map(ze=>P.get(ze.id).y)),Ve=$.get(Ce)??0;$.set(Ce,Ve+1),Le=ve.x,Re=tt-q-40-Ve*(q+30)}P.set(X.id,{x:Le,y:Re})}const be=new Map,Te=new Map(e.map(X=>[X.id,X])),Se=new Set(["note","file","link"]),Be=[...n].sort((X,oe)=>X.nestingLevel-oe.nestingLevel);for(const X of Be){if(X.memberIds.length===0)continue;const oe=X.memberIds.map(it=>{const vt=Te.get(it);if(!vt)return null;const He=P.get(it)??vt.position,It=vt.measured?.width??vt.width??g1,re=Se.has(vt.data.stepKind??"")?vt.measured?.height??vt.height??120:Math.max(vt.measured?.height??0,vt.height??0,Ss(vt));return{x:He.x,y:He.y,width:It,height:re}}).filter(it=>it!==null);if(oe.length===0)continue;const ve=Math.min(...oe.map(it=>it.x)),Le=Math.min(...oe.map(it=>it.y)),Re=Math.max(...oe.map(it=>it.x+it.width)),Ce=Math.max(...oe.map(it=>it.y+it.height)),tt=JH+X.nestingLevel*tU,Ve=tt+eU,ze=ve-tt,bt=Le-Ve,ct=Math.max(nU,Re-ve+tt*2),Ke=Math.max(aU,Ce-Le+Ve+tt);be.set(X.id,{position:{x:ze,y:bt},width:ct,height:Ke})}return e.map(X=>{const oe=be.get(X.id);if(oe)return{...X,...oe};const ve=P.get(X.id);return ve?{...X,position:ve}:X})}const iU=(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(Rr())return;t().logEvent("delete",n,{n:1}),t().pushHistory();const{edges:a}=t(),r=Mo(n,a),s=new Set([n,...r]);e(o=>({nodes:o.nodes.filter(c=>!s.has(c.id)),edges:o.edges.filter(c=>!s.has(c.source)&&!s.has(c.target))})),t().pushHistory(),Tt(()=>import("./canonical-D4SquoNo.js"),[]).then(o=>o.unsubscribeOrphanedSessions())},deleteEdges:n=>{if(Rr())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(Rr())return;t().logEvent("edit-response",n,{chars:a.length}),t().pushHistory();const r=$n(t().nodes.find(s=>s.id===n)?.data.question+a||a);e(s=>({nodes:s.nodes.map(o=>o.id===n?{...o,data:{...o.data,response:a,responses:o.data.responses.map((c,d)=>d===o.data.responseIndex?a:c),summaries:o.data.summaries?.map((c,d)=>d===o.data.responseIndex?void 0:c),summaryTypes:o.data.summaryTypes?.map((c,d)=>d===o.data.responseIndex?void 0:c),editedAts:o.data.responses.map((c,d)=>d===o.data.responseIndex?new Date().toISOString():o.data.editedAts?.[d]),highlights:xf(o.data.highlights,a),isEditingResponse:!1,tokenCount:r}}:o)})),t().pushHistory()},toggleCollapse:n=>{const a=t().nodes.find(h=>h.id===n);if(!a)return;const r=Ss(a),o=g7({...a,data:{...a.data,isCollapsed:!a.data.isCollapsed}})-r,c=Mo(n,t().edges),d=new Set(c);e(h=>({nodes:h.nodes.map(m=>m.id===n?{...m,data:{...m.data,isCollapsed:!m.data.isCollapsed}}:d.has(m.id)?{...m,position:{...m.position,y:m.position.y+o}}:m)}))},setEditing:(n,a)=>{a&&Rr()||e(r=>({nodes:r.nodes.map(s=>s.id===n?{...s,data:{...s.data,isEditing:a}}:s)}))},setEditingResponse:(n,a)=>{a&&Rr()||e(r=>({nodes:r.nodes.map(s=>s.id===n?{...s,data:{...s.data,isEditingResponse:a}}:s)}))},duplicateNode:n=>{const a=t().nodes.find(m=>m.id===n);if(!a)return;t().pushHistory();const r=In(),s={id:r,type:"thought",position:{x:0,y:0},dragHandle:".drag-handle",data:{...a.data,isCollapsed:!0,isEditing:!1,isEditingResponse:!1,isLoading:!1,highlights:a.data.highlights.map(m=>({...m,id:In()}))}},o=t().edges.find(m=>m.target===n),c=o?{...o,id:`edge-${o.source}-${r}`,target:r}:null,d=c?[...t().edges,c]:t().edges,h=rr([...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:rt.accent,strokeDasharray:"8 4",strokeWidth:2},animated:!0,data:{isCrossLink:!0,createdAt:new Date().toISOString()}};e(y=>({edges:[...y.edges,x]})),t().logEvent("connect",x.id),t().setEdgeStructural(x.id,!0);const b=t().edges.find(y=>y.id===x.id);if(b&&!b.data?.isCrossLink){const k=wr(n,t().nodes,t().edges).messages.reduce((S,w)=>S+$n(w.content),0);Qe("success",We(De("edge.materialWiredFull"),{n:k.toLocaleString()}),8e3,{label:De("edge.materialMakeQuote"),run:()=>t().setEdgeStructural(x.id,!1)})}return}t().pushHistory();const d=s.find(x=>x.id===n),h=s.find(x=>x.id===a),m=!!d&&!!h&&h.position.y>d.position.y+60&&Math.abs(h.position.x-d.position.x)<320,p={id:`crosslink-${n}-${a}`,source:n,sourceHandle:m?"continue":"branch",target:a,targetHandle:m?"top":"left",type:"smoothstep",style:{stroke:rt.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}=Ur(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(Fd({source:d,depth:"quote",chain:b})),S=wr(n,s,r).messages.reduce((w,C)=>w+$n(C.content),0)+$n(d.data.question+d.data.response);Qe("info",We(De("edge.linkedQuote"),{n:y}),8e3,{label:We(De("edge.makeFull"),{m:S}),run:()=>t().setEdgeStructural(p.id,!0)})}}},staleIds:[],recomputeStaleness:()=>{const{nodes:n,edges:a}=t(),r=[];for(const o of n)!o.data.lastContextHash||!o.data.response||["note","file","link","frame"].includes(o.data.stepKind??"")||d7(o.id,n,a)!==o.data.lastContextHash&&r.push(o.id);const s=t().staleIds;s.length===r.length&&s.every((o,c)=>o===r[c])||e({staleIds:r})},setEdgeStructural:(n,a)=>{const{nodes:r,edges:s}=t(),o=s.find(c=>c.id===n);if(o){if(a){const c=s.filter(h=>!h.data?.isCrossLink),{ordered:d}=Ur(o.source,r,c);if(d.some(h=>h.id===o.target)){Qe("error",De("edge.cycleBlocked"));return}}t().pushHistory(),t().logEvent(a?"connect":"disconnect",n,{convert:!0}),e(c=>({edges:c.edges.map(d=>{if(d.id!==n)return d;if(a){const h={...d.data??{}};return delete h.isCrossLink,delete h.contextDepth,delete h.isWatch,{...d,sourceHandle:"continue",targetHandle:"top",animated:!1,style:{stroke:rt.accent,strokeWidth:2},markerEnd:{type:"arrowclosed",color:rt.accent,width:18,height:18},data:h}}return{...d,animated:!0,style:{stroke:rt.accent,strokeDasharray:"8 4",strokeWidth:2},markerEnd:{type:"arrowclosed",color:rt.accent,width:18,height:18},data:{...d.data??{},isCrossLink:!0,contextDepth:void 0}}})})),e(c=>({nodes:rr(c.nodes,c.edges)})),t().pushHistory()}},setCrossLinkDepth:(n,a)=>{t().pushHistory(),e(r=>({edges:r.edges.map(s=>s.id!==n||!s.data?.isCrossLink?s:{...s,style:{...s.style,strokeDasharray:a==="full"?"12 3":"8 4",strokeWidth:a==="full"?3:2},data:{...s.data,contextDepth:a==="full"?"full":void 0}})})),t().pushHistory()},navigateVersion:(n,a)=>{e(r=>({nodes:r.nodes.map(s=>{if(s.id!==n)return s;const{responses:o,responseIndex:c}=s.data;let d=a==="prev"?c-1:c+1;return d<0&&(d=o.length-1),d>=o.length&&(d=0),{...s,data:{...s.data,responseIndex:d,response:o[d],question:s.data.questions?.[d]??s.data.question,generationFailed:void 0,highlights:xf(s.data.highlights,o[d])}}})}))},deleteVersion:(n,a)=>{t().pushHistory(),e(r=>({nodes:r.nodes.map(s=>{if(s.id!==n)return s;const o=s.data.responses.filter((d,h)=>h!==a);if(o.length===0)return s;const c=Math.min(s.data.responseIndex,o.length-1);return{...s,data:{...s.data,responses:o,responseIndex:c,response:o[c],questions:s.data.questions?.filter((d,h)=>h!==a),question:s.data.questions?.filter((d,h)=>h!==a)[c]??s.data.question,summaries:s.data.summaries?.filter((d,h)=>h!==a),generatedBy:s.data.generatedBy?.filter((d,h)=>h!==a),summaryTypes:s.data.summaryTypes?.filter((d,h)=>h!==a),reasonings:s.data.reasonings?.filter((d,h)=>h!==a),generatedAts:s.data.generatedAts?.filter((d,h)=>h!==a),editedAts:s.data.editedAts?.filter((d,h)=>h!==a),highlights:xf(s.data.highlights,o[c])}}})})),t().pushHistory()},relayout:()=>{Rr()||(t().pushHistory(),e(n=>{const a=ZH(n.nodes,n.edges);return{nodes:rr(n.nodes,a),edges:a}}),t().pushHistory())},setArchived:(n,a)=>{const r=new Set(n);t().pushHistory(),t().logEvent(a?"archive":"unarchive",n[0],{n:n.length}),e(s=>({nodes:s.nodes.map(o=>r.has(o.id)?{...o,data:{...o.data,archived:a||void 0,archivedAt:a?new Date().toISOString():void 0}}:o)})),t().pushHistory()},setNodeModel:(n,a)=>{e(r=>({nodes:r.nodes.map(s=>s.id===n?{...s,data:{...s.data,model:a}}:s)}))},alignSelection:n=>{if(n.length<2)return;const a=new Set(n),{nodes:r,edges:s}=t(),o=new Map,c=s.filter(b=>!b.data?.isWatch),d=(b,y)=>{if(o.has(b))return o.get(b);if(y.has(b))return 0;y.add(b);const k=c.filter(w=>w.target===b&&a.has(w.source)),S=k.length===0?0:1+Math.max(...k.map(w=>d(w.source,y)));return o.set(b,S),S},h=n.map(b=>r.find(y=>y.id===b)).filter(b=>!!b).sort((b,y)=>d(b.id,new Set)-d(y.id,new Set)||b.position.y-y.position.y);t().pushHistory();const m=h[0].position;let p=m.y;const x=new Map;for(const b of h)x.set(b.id,{x:m.x,y:p}),p+=Ss(b)+40;e(b=>({nodes:b.nodes.map(y=>{const k=x.get(y.id);return k?{...y,position:k}:y})})),t().pushHistory()},batchDelete:n=>{if(Rr())return;t().logEvent("delete",n[0],{n:n.length}),t().pushHistory();const a=new Set(n);e(r=>({nodes:r.nodes.filter(s=>!a.has(s.id)),edges:r.edges.filter(s=>!a.has(s.source)&&!a.has(s.target)),selectedNodeId:null,selectedNodeIds:[]})),t().pushHistory(),Tt(()=>import("./canonical-D4SquoNo.js"),[]).then(r=>r.unsubscribeOrphanedSessions())},duplicateSelection:n=>{const{nodes:a,edges:r}=t(),s=new Set(n),o=a.filter(M=>s.has(M.id));if(o.length===0)return;t().pushHistory();const c=M=>({x:M.position.x,y:M.position.y,w:M.measured?.width??M.width??520,h:M.measured?.height??M.height??Ss(M)}),d=o.map(c),h={x:Math.min(...d.map(M=>M.x)),y:Math.min(...d.map(M=>M.y)),right:Math.max(...d.map(M=>M.x+M.w)),bottom:Math.max(...d.map(M=>M.y+M.h))},m=80,p=h.right-h.x+m,x=h.bottom-h.y+m,b=[];for(let M=1;M<=6;M++)b.push({dx:M*p,dy:0},{dx:0,dy:M*x},{dx:M*p,dy:M*x});const y=a.filter(M=>M.data.stepKind!=="frame").map(c),k=(M,_)=>M.x<_.x+_.w&&M.x+M.w>_.x&&M.y<_.y+_.h&&M.y+M.h>_.y,S=b.find(M=>!d.some(_=>y.some(R=>k({..._,x:_.x+M.dx,y:_.y+M.dy},R))))??{dx:p,dy:x},w=new Map,C=new Map;for(const M of o){w.set(M.id,In());for(const _ of M.data.attachments??[])C.set(_.id,In())}const T=M=>(M??[]).map(_=>C.get(_)??_),N=o.map(M=>({...M,id:w.get(M.id),position:{x:M.position.x+S.dx,y:M.position.y+S.dy},selected:!0,data:{...M.data,attachments:(M.data.attachments??[]).map(_=>({..._,id:C.get(_.id)})),excludedAttachmentIds:T(M.data.excludedAttachmentIds),includedAttachmentIds:T(M.data.includedAttachmentIds),digestOf:M.data.digestOf?C.get(M.data.digestOf)??M.data.digestOf:void 0,highlights:(M.data.highlights??[]).map(_=>({..._,id:In()})),isEditing:!1,isEditingResponse:!1,isLoading:!1}})),D=r.filter(M=>s.has(M.source)&&s.has(M.target)).map(M=>({...M,id:`edge-${w.get(M.source)}-${w.get(M.target)}`,source:w.get(M.source),target:w.get(M.target),data:M.data?{...M.data}:M.data})),O=N.map(M=>M.id);e(M=>({nodes:[...M.nodes.map(_=>_.selected?{..._,selected:!1}:_),...N],edges:[...M.edges,...D],selectedNodeId:O.length===1?O[0]:null,selectedNodeIds:O})),t().pushHistory()}});function i2(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 Uf(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 sU(e,t){const n=[...e].sort((r,s)=>r.id<s.id?-1:1).map(r=>({id:r.id,stepKind:r.data.stepKind,question:r.data.question,response:r.data.response,archived:r.data.archived||void 0,branchContext:r.data.branchContext||void 0,highlightMode:r.data.highlightMode!=="off"?r.data.highlightMode:void 0,highlights:(r.data.highlights??[]).length>0?r.data.highlights.map(s=>s.text):void 0,linkUrl:r.data.linkUrl,linkFetchedAt:r.data.linkFetchedAt,rolePrompt:r.data.rolePrompt,roleMode:r.data.roleMode,excludedAttachmentIds:r.data.excludedAttachmentIds?.length?r.data.excludedAttachmentIds:void 0,attachments:(r.data.attachments??[]).map(s=>({id:s.id,name:s.name,type:s.type,fingerprint:Ac(s),extractedText:s.extractedText,renderMode:s.renderMode}))})),a=[...t].sort((r,s)=>r.id<s.id?-1:1).map(r=>({source:r.source,target:r.target,isCrossLink:r.data?.isCrossLink||void 0,isWatch:r.data?.isWatch||void 0,contextDepth:r.data?.contextDepth}));return{nodes:n,edges:a}}async function oU(e,t){return`sha256:${await Uf(i2(sU(e,t)))}`}function lU(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 pie(e,t,n,a){const r=wr(e,t,n,a.branchContext,void 0,void 0,a.staleIds),s=t.find(x=>x.id===e),o=r.messages.map((x,b)=>{const y=r.sources[b]??{layer:"chain"};return{id:`item_${String(b+1).padStart(3,"0")}`,kind:"message",role:x.role,content:[{type:"text",text:x.content}],source:{layer:y.layer,part:y.part,node_id:y.nodeId??y.refSourceId,attachment_id:y.attachmentId},selection:{mode:"full",reason:`structural-${y.layer}`}}}),c=new Map,d=(x,b)=>{if(!x||!b||c.has(b))return;const y=t.find(S=>S.id===x),k=y?.data.attachments?.find(S=>S.id===b);!y||!k||c.set(b,{id:b,kind:k.type.startsWith("image/")?"image":"document",name:k.name,mime_type:k.type,size:k.size,fingerprint:Ac(k),model_projection:{mode:lU(k)},source:{node_id:y.id}})};r.sources.forEach(x=>d(x.nodeId,x.attachmentId)),r.imageSources.forEach(x=>d(x.nodeId,x.attachmentId));const h=r.sources.filter(x=>x.layer==="reference"&&x.refSourceId).map(x=>({source_node_id:x.refSourceId})),m={format:"thoughtdag.context-bundle",version:0,graph:{project_id:a.projectId??null,snapshot_hash:await oU(t,n),target_node_id:e},intent:{task:a.task??s?.data.question??"",language:a.language??null},context:{messages:o,materials:[...c.values()],references:h},execution_hints:{preferred_model:a.preferredModel??s?.data.model??null,required_tools:[],required_mcp_servers:[]},budget:{estimated_tokens:r.messages.reduce((x,b)=>x+$n(b.content),0),limit:null,truncation:"none"}},p=await Uf(i2(m));return{...m,id:`cb_${p.slice(0,16)}`,created_at:a.now,provenance:{source_runs:[],compiler:{name:"thoughtdag",adapter_id:null}},integrity:{content_hash:`sha256:${p}`}}}const hc="dsh-sessions",k1="/session.jsonl.zstd",cU=1500,uU=2500,dU=6e4,hU=6e4,fU=600*1e3;let qx=null;function mU(e){if(window.desktopSessions)return;const t=e.replace(/\/+$/,""),n=async F=>{const B=await fetch(t+F,{credentials:"same-origin"});if(!B.ok)throw new Error(`${F}: ${B.status}`);return B.json()},a=async F=>{const B=await fetch(t+F,{credentials:"same-origin"});if(!B.ok)throw new Error(`${F}: ${B.status}`);return B.text()},r=new Map,s=F=>`${F}${k1}`,o=(F,B)=>{const W=F.indexOf(`
|
|
62
62
|
`),Q=W<0?F:F.slice(0,W);try{const K=JSON.parse(Q);if(K.type==="session"&&K.cwd===void 0)return K.cwd=B,JSON.stringify(K)+(W<0?"":F.slice(W))}catch{}return F},c=F=>F.endsWith(k1)?F.slice(0,-k1.length):null,d=async()=>{const[F,B]=await Promise.all([n("/disksessions").then(Q=>Q.sessions).catch(()=>[]),n("/sessions").then(Q=>Q.sessions).catch(()=>[])]),W=new Set;for(const Q of F){W.add(Q.id);const K=r.get(Q.id);r.set(Q.id,{id:Q.id,live:!1,size:Q.size,mtime:Q.mtime,seq:K?.seq??null,cwd:Q.cwd??K?.cwd??null})}for(const Q of B)W.add(Q.id),h(Q);for(const Q of[...r.keys()])W.has(Q)||r.delete(Q);return[...r.values()]},h=F=>{const B=r.get(F.id),W=typeof F.seq=="number"?F.seq:null,Q=W!==null&&B?.seq!==null&&B?.seq!==void 0&&W>B.seq;r.set(F.id,{id:F.id,live:!0,size:B?.size??0,mtime:Q||!B?Date.now():B.mtime,seq:W,cwd:B?.cwd??null})},m=async()=>{const F=await n("/sessions").then(B=>B.sessions).catch(()=>[]);for(const B of F)h(B);return[...r.values()]},p=new Map,x=async F=>{const B=r.get(F)??(await d(),r.get(F));if(!B)return"";const W=p.get(F);if(W&&Date.now()-W.at<cU&&W.seq===B.seq)return W.text;let Q;if(B.live&&W&&W.seq!==null&&B.seq!==null&&B.seq>W.seq&&W.text){const K=await a(`/sessions/${encodeURIComponent(F)}/log?since=${W.seq}`).catch(()=>null);K===null?Q=W.text:Q=K?`${W.text}
|
|
63
63
|
${K}`:W.text}else Q=await a(B.live?`/sessions/${encodeURIComponent(F)}/log`:`/disksessions/${encodeURIComponent(F)}/log`).catch(()=>""),B.live&&B.cwd&&(Q=o(Q,B.cwd));return p.set(F,{at:Date.now(),seq:B.seq,text:Q}),Q};let b=null;const y=async()=>b||(b=await n("/roots").then(F=>F.roots.filter(B=>B.exists)).catch(()=>[]),b),k=new Map,S=async F=>n(`/roots/${encodeURIComponent(F)}/list`).then(B=>B.files).catch(()=>[]),w=(F,B,W,Q="")=>`/roots/${encodeURIComponent(F)}/${B}?rel=${encodeURIComponent(W)}${Q}`,C=[];let T=!1;const N=new Map;let D=0;const O=(F,B)=>{const W=`${F}|${B.rel}`,Q=k.get(W);if(k.set(W,B.mtime),Date.now()-B.mtime<fU?N.set(W,{rootKey:F,rel:B.rel,mtime:B.mtime}):N.delete(W),Q!==void 0&&B.mtime>Q)for(const K of C)K({rootKey:F,rel:B.rel})},M=async()=>{const F=Date.now()-D>=hU,B=new Map([...r].map(([Q,K])=>[Q,K.seq])),W=await(F?d():m()).catch(()=>[]);for(const Q of W){if(!Q.live)continue;const K=B.get(Q.id);if(K===void 0||Q.seq!==null&&K!==null&&Q.seq>K)for(const U of C)U({rootKey:hc,rel:s(Q.id)})}if(F){D=Date.now();for(const Q of await y())for(const K of await S(Q.key))O(Q.key,K);return}for(const Q of[...N.values()]){const K=await n(w(Q.rootKey,"stat",Q.rel)).catch(()=>null);if(!K){N.delete(`${Q.rootKey}|${Q.rel}`);continue}O(Q.rootKey,{rel:Q.rel,size:K.size,mtime:K.mtime})}};let _=!0,R=null;const G=()=>_&&document.visibilityState!=="hidden",P=()=>{R!==null&&window.clearTimeout(R),R=window.setTimeout(async()=>{await M().catch(()=>{}),P()},G()?uU:dU)},V=()=>{!T||!G()||M().catch(()=>{}).then(P)};document.addEventListener("visibilitychange",V);const J=F=>{window.parent.postMessage({source:"dsh-thoughtdag",type:"td:select-session",session:F},window.location.origin)},H={roots:async()=>[{key:hc,path:"~/.dsh/sessions",builtin:!0,exists:!0},...await y()],addRoot:async()=>null,removeRoot:async()=>{},list:async F=>{if(F!==hc){const B=await S(F);for(const W of B)k.set(`${F}|${W.rel}`,W.mtime);return B}return(await d()).map(B=>({rel:s(B.id),size:B.size,mtime:B.mtime}))},head:async(F,B,W)=>{if(F!==hc)return a(w(F,"head",B,`&bytes=${Math.max(1024,W|0)}`)).catch(()=>"");const Q=c(B);return Q?(await x(Q)).slice(0,Math.min(Math.max(1024,W|0),524288)):""},read:async(F,B)=>{if(F!==hc)return a(w(F,"read",B)).catch(()=>"");const W=c(B);return W?x(W):""},readRange:async(F,B,W,Q)=>{if(F!==hc)return n(w(F,"range",B,`&start=${W|0}&length=${Q|0}`)).catch(()=>({text:"",nextStart:W|0,eof:!0}));const K=c(B),U=K?await x(K):"",q=Math.max(0,W|0),te=Math.min(Math.max(65536,Q|0),32*1024*1024),$=Math.min(te,Math.max(0,U.length-q));if($===0)return{text:"",nextStart:q,eof:!0};let be=U.slice(q,q+$);const Te=q+$>=U.length;if(!Te){const Se=be.lastIndexOf(`
|
|
64
64
|
`);if(Se<0)return{text:"",nextStart:q+$,eof:!1};be=be.slice(0,Se+1)}return{text:be,nextStart:q+be.length,eof:Te}},openInCli:async(F,B,W)=>{if(F==="dsh")return J(W),{opened:!0,via:"app",command:""};try{const Q=await fetch(t+"/agents/open-in-cli",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"same-origin",body:JSON.stringify({runner:F,cwd:B,sessionId:W})});if(Q.ok){const K=await Q.json();return{opened:!!K.opened,via:"terminal",command:K.command??""}}}catch{}return{opened:!1,via:"app",command:""}},openTargets:async()=>({terminals:[],apps:[{runner:"dsh",name:"DeepSeek Harness"}],prefs:{terminal:""},canAddCustom:!1}),setOpenPrefs:async F=>F,addTerminal:async()=>null,watchStart:async()=>{if(!T){T=!0,await d().catch(()=>{}),D=Date.now();for(const F of await y())for(const B of await S(F.key))O(F.key,B);P()}return!0},onSessionsChanged:F=>{C.push(F)}};window.desktopSessions=H,window.addEventListener("message",F=>{const B=F.data;if(!(F.origin!==window.location.origin||B?.source!=="dsh-thoughtdag")&&(B.type==="td:current-session"&&(qx=B.session??null,window.dispatchEvent(new CustomEvent("td:dsh-current",{detail:qx}))),B.type==="td:view")){const W=_;_=B.shown!==!1,_&&!W?V():!_&&W&&P()}}),window.parent.postMessage({source:"dsh-thoughtdag",type:"td:request-current"},window.location.origin)}const B5="harness/agent",pU=e=>!!e&&(e===B5||e.startsWith(B5+"/"));async function gU(){try{const{useStore:e}=await Tt(async()=>{const{useStore:r}=await Promise.resolve().then(()=>Us);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 xU(e,t){if(!window.desktopSessions||!pU(t))return;const n=await gU()??qx?.cwd??void 0;try{const{useStore:a}=await Tt(async()=>{const{useStore:p}=await Promise.resolve().then(()=>Us);return{useStore:p}},void 0),{useProjects:r}=await Tt(async()=>{const{useProjects:p}=await Promise.resolve().then(()=>Fr);return{useProjects:p}},void 0),{projects:s,activeId:o}=r.getState(),c=s.find(p=>p.id===o)?.sourceSession,{nodes:d,edges:h}=a.getState(),m=h.filter(p=>p.target===e);if(m.length===1){const p=m[0].source,b=(c?[c,...c.chapters??[],...c.branches??[]].filter(S=>S.runner==="dsh"&&S.sessionId):[]).find(S=>S.tailNodeId===p);if(b)return{...n?{cwd:n}:{},session:b.sessionId};const k=d.find(S=>S.id===p)?.data.importSource;if(k?.runner==="dsh"&&k.sessionId&&k.itemIds?.[0])return{...n?{cwd:n}:{},forkSession:k.sessionId,forkAnchor:k.itemIds[0]}}}catch{}return n?{cwd:n}:{}}const x7=(e,t,n,a,r,s)=>{const o=r?[r]:[];e(c=>({nodes:c.nodes.map(d=>d.id===t?{...d,data:{...d.data,importSource:{runner:"dsh",sessionId:n,itemIds:o,...a.cwd?{cwd:a.cwd}:{}},...s?{source:s}:{}}}:d)}))};async function b7(e,t){if(!e)return!1;const{useProjects:n,patchLedgerEntry:a}=await Tt(async()=>{const{useProjects:d,patchLedgerEntry:h}=await Promise.resolve().then(()=>Fr);return{useProjects:d,patchLedgerEntry:h}},void 0),{projects:r,activeId:s}=n.getState();if(!s)return!1;const o=r.find(d=>d.id===s)?.sourceSession;if(!o)return!1;const c=o.sessionId===e?o:o.chapters?.find(d=>d.sessionId===e)??o.branches?.find(d=>d.sessionId===e);return c?(await a(s,e,{importedCount:c.importedCount+1,tailNodeId:t}),!0):!1}async function bU(e,t,n,a){return window.desktopSessions?(x7(e,t,n.session??a.session,n,a.userMessageId),b7(n.session,t)):!1}async function yU(e,t,n,a,r,s,o,c=!1){if(!window.desktopSessions)return;const d=r.session??o?.session??s;d&&(x7(e,n,d,r,o?.userMessageId??null,{question:a.question,response:a.response}),c||await b7(r.session,n))}const vU=45,wU=3,kU=/sk-[a-zA-Z0-9_-]{8,}|api[ _-]?key|password|token|secret/i,Wx=new Map;function EU(e){return e.category!=="project"?!0:(Date.now()-new Date(e.at).getTime())/864e5<=vU}function SU(){const{memoryEnabled:e,memories:t}=pe.getState();if(!e)return null;const n=t.filter(EU);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:
|
|
@@ -145,7 +145,7 @@ ${c.content.trim()}`).join(`
|
|
|
145
145
|
|
|
146
146
|
---
|
|
147
147
|
|
|
148
|
-
${p}`:p,w=pe.getState().agentEffort||void 0,C=[...new Set(se.getState().nodes.flatMap(_=>(_.data.approvals??[]).filter(R=>R.outcome==="allowed-session"&&typeof R.rule=="string"&&R.rule.startsWith(h.runtime==="claude-code"?"claude:":h.runtime+":")).map(R=>R.rule)))];WU();let T="",N="",D="";const M=await new Promise(_=>{d.run({runtime:h.runtime,cwd:m,prompt:S,...o?.sessionPath?{sessionPath:o.sessionPath}:{},...o?.forkEntryId?{forkEntryId:o.forkEntryId}:{},images:(a??[]).map(R=>({type:"image",data:R.data,mimeType:R.mimeType})),model:{provider:h.provider,id:h.id},...w?{effort:w}:{},...C.length?{allowRules:C}:{}}).then(R=>{const G=()=>{d.abort(R)};n?.aborted&&G(),n?.addEventListener("abort",G,{once:!0}),bf.set(R,P=>{switch(P.type){case"session":{const V=P.model?.resolved;V&&window.dispatchEvent(new CustomEvent("td:agent-model-resolved",{detail:{id:s,resolved:V}})),r?.onAgentSession?.({runtime:h.runtime,sessionId:P.sessionId??null,sessionFile:P.sessionFile??null,cwd:P.cwd??m,...typeof P.effort=="string"&&P.effort?{effort:P.effort}:{}});break}case"message_update":{const V=P.assistantMessageEvent;V?.type==="text_delta"&&V.delta?(T+=V.delta,t(V.delta,T)):V?.type==="thinking_delta"&&V.delta&&(N+=V.delta,r?.onReasoning?.(V.delta,N));break}case"tool_execution_start":{const V=String(P.toolName??"tool"),J=VU(V,P.args);r?.onAgentTool?.({id:String(P.toolCallId??""),name:V,query:J,phase:"start"});break}case"tool_execution_end":r?.onAgentTool?.({id:String(P.toolCallId??""),name:String(P.toolName??"tool"),query:"",phase:"end",isError:!!P.isError});break;case"extension_ui_cancelled":{const V=`dialog-${Date.now()}`,J=String(P.title??P.method??"dialog");r?.onAgentTool?.({id:V,name:"dialog",query:J,phase:"start"}),r?.onAgentTool?.({id:V,name:"dialog",query:"",phase:"end",isError:!0});break}case"question_answered":r?.onApprovalDecided?.({...P.auto?{auto:!0,name:String(P.title??""),query:String(P.message??""),rule:typeof P.rule=="string"?P.rule:null}:{},id:String(P.id),outcome:P.outcome??"cancelled",value:typeof P.value=="string"?P.value:null});break;case"question":r?.onApproval?.({id:String(P.id),kind:P.kind??"confirm",toolName:h.runtime,callId:null,reason:null,name:String(P.title??""),query:String(P.message??""),arguments:null,options:Array.isArray(P.options)?P.options:[],placeholder:typeof P.placeholder=="string"?P.placeholder:null,prefill:typeof P.prefill=="string"?P.prefill:null,channel:{runId:R},paths:Array.isArray(P.paths)?P.paths:[],suggest:typeof P.suggest=="string"?P.suggest:null,rule:typeof P.rule=="string"?P.rule:null});break;case"fs_changes":r?.onAgentChanges?.({changed:P.changed??[],added:P.added??[],removed:P.removed??[],truncated:!!P.truncated});break;case"run_end":D=typeof P.text=="string"&&P.text?P.text:T,bf.delete(R),n?.removeEventListener("abort",G),_({how:String(P.how??"end")});break;case"run_error":bf.delete(R),n?.removeEventListener("abort",G),_({how:"error",error:String(P.message??"agent run failed")});break}})}).catch(R=>_({how:"error",error:R instanceof Error?R.message:String(R)}))});if(n?.aborted)throw new DOMException("The operation was aborted.","AbortError");if(M.how==="error")throw new Error(M.error??"agent run failed");return D||T}async function $U(e,t,n){const a=o=>(console.warn("[agent] turn not adopted:",o,t.runtime,t.sessionFile),!1),r=window.desktopSessions;if(!r||!t.sessionFile)return a(r?"no session file":"no sessions bridge");const s=$c[t.runtime].rootKey;try{const c=(await r.roots()).find(H=>H.key===s);if(!c)return a("no root "+s);const d=c.path.replace(/\/$/,"")+"/";if(!t.sessionFile.startsWith(d))return a("file outside root "+d);const h=t.sessionFile.slice(d.length),{anyRunnerSessionConversation:m}=await Tt(async()=>{const{anyRunnerSessionConversation:H}=await import("./index-
|
|
148
|
+
${p}`:p,w=pe.getState().agentEffort||void 0,C=[...new Set(se.getState().nodes.flatMap(_=>(_.data.approvals??[]).filter(R=>R.outcome==="allowed-session"&&typeof R.rule=="string"&&R.rule.startsWith(h.runtime==="claude-code"?"claude:":h.runtime+":")).map(R=>R.rule)))];WU();let T="",N="",D="";const M=await new Promise(_=>{d.run({runtime:h.runtime,cwd:m,prompt:S,...o?.sessionPath?{sessionPath:o.sessionPath}:{},...o?.forkEntryId?{forkEntryId:o.forkEntryId}:{},images:(a??[]).map(R=>({type:"image",data:R.data,mimeType:R.mimeType})),model:{provider:h.provider,id:h.id},...w?{effort:w}:{},...C.length?{allowRules:C}:{}}).then(R=>{const G=()=>{d.abort(R)};n?.aborted&&G(),n?.addEventListener("abort",G,{once:!0}),bf.set(R,P=>{switch(P.type){case"session":{const V=P.model?.resolved;V&&window.dispatchEvent(new CustomEvent("td:agent-model-resolved",{detail:{id:s,resolved:V}})),r?.onAgentSession?.({runtime:h.runtime,sessionId:P.sessionId??null,sessionFile:P.sessionFile??null,cwd:P.cwd??m,...typeof P.effort=="string"&&P.effort?{effort:P.effort}:{}});break}case"message_update":{const V=P.assistantMessageEvent;V?.type==="text_delta"&&V.delta?(T+=V.delta,t(V.delta,T)):V?.type==="thinking_delta"&&V.delta&&(N+=V.delta,r?.onReasoning?.(V.delta,N));break}case"tool_execution_start":{const V=String(P.toolName??"tool"),J=VU(V,P.args);r?.onAgentTool?.({id:String(P.toolCallId??""),name:V,query:J,phase:"start"});break}case"tool_execution_end":r?.onAgentTool?.({id:String(P.toolCallId??""),name:String(P.toolName??"tool"),query:"",phase:"end",isError:!!P.isError});break;case"extension_ui_cancelled":{const V=`dialog-${Date.now()}`,J=String(P.title??P.method??"dialog");r?.onAgentTool?.({id:V,name:"dialog",query:J,phase:"start"}),r?.onAgentTool?.({id:V,name:"dialog",query:"",phase:"end",isError:!0});break}case"question_answered":r?.onApprovalDecided?.({...P.auto?{auto:!0,name:String(P.title??""),query:String(P.message??""),rule:typeof P.rule=="string"?P.rule:null}:{},id:String(P.id),outcome:P.outcome??"cancelled",value:typeof P.value=="string"?P.value:null});break;case"question":r?.onApproval?.({id:String(P.id),kind:P.kind??"confirm",toolName:h.runtime,callId:null,reason:null,name:String(P.title??""),query:String(P.message??""),arguments:null,options:Array.isArray(P.options)?P.options:[],placeholder:typeof P.placeholder=="string"?P.placeholder:null,prefill:typeof P.prefill=="string"?P.prefill:null,channel:{runId:R},paths:Array.isArray(P.paths)?P.paths:[],suggest:typeof P.suggest=="string"?P.suggest:null,rule:typeof P.rule=="string"?P.rule:null});break;case"fs_changes":r?.onAgentChanges?.({changed:P.changed??[],added:P.added??[],removed:P.removed??[],truncated:!!P.truncated});break;case"run_end":D=typeof P.text=="string"&&P.text?P.text:T,bf.delete(R),n?.removeEventListener("abort",G),_({how:String(P.how??"end")});break;case"run_error":bf.delete(R),n?.removeEventListener("abort",G),_({how:"error",error:String(P.message??"agent run failed")});break}})}).catch(R=>_({how:"error",error:R instanceof Error?R.message:String(R)}))});if(n?.aborted)throw new DOMException("The operation was aborted.","AbortError");if(M.how==="error")throw new Error(M.error??"agent run failed");return D||T}async function $U(e,t,n){const a=o=>(console.warn("[agent] turn not adopted:",o,t.runtime,t.sessionFile),!1),r=window.desktopSessions;if(!r||!t.sessionFile)return a(r?"no session file":"no sessions bridge");const s=$c[t.runtime].rootKey;try{const c=(await r.roots()).find(H=>H.key===s);if(!c)return a("no root "+s);const d=c.path.replace(/\/$/,"")+"/";if(!t.sessionFile.startsWith(d))return a("file outside root "+d);const h=t.sessionFile.slice(d.length),{anyRunnerSessionConversation:m}=await Tt(async()=>{const{anyRunnerSessionConversation:H}=await import("./index-DMEJ2pfg.js");return{anyRunnerSessionConversation:H}},[]),{useStore:p}=await Tt(async()=>{const{useStore:H}=await Promise.resolve().then(()=>Us);return{useStore:H}},void 0),{useProjects:x,registerLedgerEntry:b,updateSourceSession:y,subscribedSessionIds:k}=await Tt(async()=>{const{useProjects:H,registerLedgerEntry:F,updateSourceSession:B,subscribedSessionIds:W}=await Promise.resolve().then(()=>Fr);return{useProjects:H,registerLedgerEntry:F,updateSourceSession:B,subscribedSessionIds:W}},void 0),S=await r.read(s,h);if(!S)return a("empty file");const w=await m(S);if(!w?.sessionId)return a("no conversation recognized");const T=w.build().nodes.filter(H=>H.data.importSource),N=n.trim();let D=-1;for(let H=T.length-1;H>=0;H--){const F=T[H].data.question.trim();if(F===N||F.endsWith(N)||N.endsWith(F)){D=H;break}}if(D<0&&(D=T.length-1),D<0)return a("no turn in file yet");const O=T[D],M=O.data.attachments??[],_=KU(t,M),R=_?[...M,_]:M;p.setState(H=>({nodes:H.nodes.map(F=>F.id===e?{...F,data:{...F.data,attachments:[...(F.data.attachments??[]).filter(B=>!B.op),...R],excludedAttachmentIds:[...new Set([...F.data.excludedAttachmentIds??[],...R.map(B=>B.id)])],importSource:O.data.importSource,source:O.data.source??{question:O.data.question,response:O.data.response},agentTrace:void 0}}:F)}));const{projects:G,activeId:P}=x.getState(),V=P?G.find(H=>H.id===P):void 0;if(!V)return!0;const J={sessionId:w.sessionId,runner:t.runtime,importedCount:D+1,tailNodeId:e};if(k(V).includes(w.sessionId)){const{patchLedgerEntry:H}=await Tt(async()=>{const{patchLedgerEntry:F}=await Promise.resolve().then(()=>Fr);return{patchLedgerEntry:F}},void 0);await H(P,w.sessionId,{importedCount:D+1,tailNodeId:e})}else V.sourceSession?await b(P,"chapter",J):(await y(P,J),x.getState().projects.find(H=>H.id===P)?.sourceSession||(x.setState(H=>({projects:H.projects.map(F=>F.id===P?{...F,sourceSession:J}:F)})),await b(P,"chapter",J).catch(()=>{}),x.setState(H=>({projects:H.projects.map(F=>F.id===P&&F.sourceSession?{...F,sourceSession:{...F.sourceSession,chapters:(F.sourceSession.chapters??[]).filter(B=>B.sessionId!==J.sessionId)}}:F)}))));return!0}catch(o){return a("threw: "+(o instanceof Error?o.message:String(o)))}}async function YU(){try{const{useProjects:e}=await Tt(async()=>{const{useProjects:r}=await Promise.resolve().then(()=>Fr);return{useProjects:r}},void 0),{projects:t,activeId:n}=e.getState(),a=t.find(r=>r.id===n)?.agentGuard;return{mode:a?.mode==="allow"?"allow":"ask",allow:a?.allow??[]}}catch{return{mode:"ask",allow:[]}}}async function l2(e){if(!window.desktopAgents)return;const t=e??(await o2())?.cwd;if(t)try{await window.desktopAgents.guardWrite(t,await YU())}catch{}}async function W5(e){const{useProjects:t,setProjectAgentGuard:n}=await Tt(async()=>{const{useProjects:o,setProjectAgentGuard:c}=await Promise.resolve().then(()=>Fr);return{useProjects:o,setProjectAgentGuard:c}},void 0),{projects:a,activeId:r}=t.getState();if(!r)return;const s=a.find(o=>o.id===r)?.agentGuard;await n(r,{mode:e,allow:s?.allow??[]}),await l2()}async function w7(e,t=!1){const{useProjects:n,setProjectAgentGuard:a}=await Tt(async()=>{const{useProjects:d,setProjectAgentGuard:h}=await Promise.resolve().then(()=>Fr);return{useProjects:d,setProjectAgentGuard:h}},void 0),{projects:r,activeId:s}=n.getState();if(!s)return;const o=r.find(d=>d.id===s)?.agentGuard,c=t?(o?.allow??[]).filter(d=>d!==e):[...new Set([...o?.allow??[],e])];await a(s,{mode:o?.mode??"ask",allow:c}),await l2()}function KU(e,t){const n=e.changes;if(!n)return null;const a=new Set;for(const d of t)for(const h of d.paths??[])a.add(h.startsWith("/")?h:`${e.cwd.replace(/\/$/,"")}/${h}`);const r=[...n.changed,...n.added].filter(d=>!a.has(d)),s=n.removed.filter(d=>!a.has(d));if(r.length===0&&s.length===0&&!n.truncated)return null;const o=d=>d.startsWith(e.cwd)?d.slice(e.cwd.length).replace(/^\//,""):d,c=[];return r.length&&c.push("Changed on disk during this turn (seen by the file system, not declared by a tool):",...r.map(d=>"- "+o(d))),s.length&&c.push("Removed:",...s.map(d=>"- "+o(d))),n.truncated&&c.push("(the directory was too large to scan completely)"),{id:`fs-${Date.now().toString(36)}`,name:"tool: fs-changes",type:"text/plain",size:0,content:c.join(`
|
|
149
149
|
`),op:"write",paths:[...r,...s]}}let Wa=null,Vx=null;const bd=new Set;function Fs(){return Wa?Promise.resolve(Wa):(Vx??=(async()=>{const e=oi();let t=null;if(e.length>0)try{t=await o0(e)}catch{}return t||(t=await fetch(`${$i}/api/models`).then(n=>n.json()).then(n=>({models:n.models??[],default:n.default??null,capabilities:n.capabilities})).catch(()=>null)),t?(Wa=S7(t),Wa):null})(),Vx)}function V5(e){return(e.split("/").pop()??e).toLowerCase()}function k7(e,t){if(t.some(r=>r.id===e))return e;const n=V5(e),a=t.find(r=>V5(r.id)===n);return a?a.id:null}const c2="thoughtdag.agentModels",E7="thoughtdag.agentModelNames",Am=()=>typeof window<"u"&&!!window.desktopAgents,Bc=e=>e.provider===fi&&zc(e.id);function u2(){try{const e=JSON.parse(localStorage.getItem(E7)??"{}");return e&&typeof e=="object"?e:{}}catch{return{}}}function d2(e){const t=u2();return e.map(n=>{const a=n.provider===fi?t[n.id]:void 0;return!a||n.id.endsWith("/"+a)||n.name.includes(a)?n:{...n,name:`${n.name} · ${a}`}})}function Ff(e,t,n){if(!e)return"";const a=y7(e);if(!a)return e.split("/").pop()??e;let r=[];try{r=JSON.parse(localStorage.getItem(c2)??"[]")}catch{r=[]}const o=r.find(h=>h&&h.id===e)?.name??`${$c[a.runtime].label} · ${a.id}`,c=n?.compact?void 0:u2()[e],d=c&&!o.includes(c)?`${o} · ${c}`:o;return t?`${d} · ${t}`:d}function S7(e){if(!Am())return e;let t=[];try{t=JSON.parse(localStorage.getItem(c2)??"[]")}catch{t=[]}const n=e.models.filter(a=>!Bc(a));return{...e,models:[...n,...d2(t.filter(a=>a&&Bc(a)))],agentsPending:!1}}let Gx=!1,Qu=null;async function T7(){if(!(!Am()||!Wa))return Qu||(Qu=(async()=>{const e=Wa;Tl({...e,agentsPending:!0});const t=await zU().catch(()=>[]);try{localStorage.setItem(c2,JSON.stringify(t))}catch{}const n=(Wa??e).models.filter(a=>!Bc(a));Tl({...Wa??e,models:[...n,...d2(t)],agentsPending:!1})})().finally(()=>{Qu=null}),Qu)}function XU(){Gx||!Am()||(Gx=!0,Fs().then(()=>T7()))}function QU(e,t){if(!e||!t)return;const n=u2();if(n[e]===t)return;n[e]=t;try{localStorage.setItem(E7,JSON.stringify(n))}catch{}if(!Wa)return;const a=Wa.models.filter(s=>!Bc(s)),r=Wa.models.filter(Bc).map(s=>({...s,name:s.name.split(" · ").slice(0,2).join(" · ")}));Tl({...Wa,models:[...a,...d2(r)]})}typeof window<"u"&&window.addEventListener("td:agent-model-resolved",e=>{const t=e.detail;t?.id&&t?.resolved&&QU(t.id,t.resolved)});function Tl(e){Wa=e,Vx=Promise.resolve(e);for(const t of bd)t(e);if(e.agentsPending===void 0&&Am()&&!e.models.some(Bc)){Wa=S7(e);for(const t of bd)t(Wa);Gx&&T7()}}function _l(){const[e,t]=L.useState(Wa);return L.useEffect(()=>{const n=a=>t(a);return bd.add(n),Wa||Fs().then(a=>{bd.has(n)&&a&&t(a)}),()=>{bd.delete(n)}},[]),e}const ZU=[[/^(Read|NotebookRead)$/i,"📖"],[/^(Edit|Write|MultiEdit|NotebookEdit)$/i,"✏️"],[/^(Bash|BashOutput|Shell)$/i,"⌨️"],[/^(Grep|Glob|LS|Search|WebSearch)$/i,"🔍"],[/^(WebFetch|Fetch)$/i,"🌐"],[/^(Task|Agent)$/i,"🤖"]],A7=/^tool: (\S+?)( \(truncated\))?$/;function JU(e){const t=new Map;for(const n of e.attachments??[]){const a=n.name.match(A7);if(!a)continue;const r=a[1],s=ZU.find(([c])=>c.test(r))?.[1]??"🔧",o=t.get(r);o?o.count+=1:t.set(r,{glyph:s,name:r,count:1})}return[...t.values()]}function eF(e){let t=0;for(const s of e.attachments??[])A7.test(s.name)&&(t+=$n(s.content));if(t===0)return null;const n=$n(e.question),a=$n(e.response),r=n+a+t;return{q:n,a,tool:t,total:r,toolShare:r>0?t/r:0}}function tF(e){const t=new Map;for(const n of e.attachments??[])if(!(!n.paths?.length||n.op!=="read"&&n.op!=="write"&&n.op!=="edit"))for(const a of n.paths){const r=t.get(a);r?r.op==="read"&&n.op!=="read"&&(r.op=n.op):t.set(a,{path:a,name:a.split("/").filter(Boolean).pop()??a,op:n.op})}return[...t.values()].sort((n,a)=>(n.op==="read"?1:0)-(a.op==="read"?1:0))}function nF(e,t=140){const n=e.replace(/```[\s\S]*?```/g,"").split(/\n\s*\n/).map(s=>s.replace(/!?\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/[#*`>|_~]/g,"").replace(/^\s*[-•\d.)]+\s*/gm,"").replace(/\s+/g," ").trim()).filter(s=>s.length>12&&!/[::]$/.test(s)&&!/^(sources?|references?|来源|参考)\b/i.test(s)),a=n.filter(s=>s.length>=30),r=a[a.length-1]??n[n.length-1]??e.replace(/[#*`>-]/g,"").replace(/\s+/g," ").trim();return r.length>t?`${r.slice(0,t)}…`:r}function c0(){const e=L.useRef("work");return un(t=>{const n=t.transform[2],a=e.current;return a==="work"?n<=.8&&(e.current=n<=.32?"glyph":"map"):a==="map"?n>=.9?e.current="work":n<=.32&&(e.current="glyph"):n>=.9?e.current="work":n>=.4&&(e.current="map"),e.current})}const G5={en:{name:"Rule-out / Rule-in",steps:[{id:"q",kind:"human",x:560,y:40,title:"Research question",instruction:"Type the question to differentiate: what phenomenon needs explaining?"},{id:"mechA",kind:"prompt",x:20,y:440,title:"Candidate: Mechanism A",instruction:`You advocate a low-level mechanistic account of the phenomenon. Be concrete and falsifiable.
|
|
150
150
|
From this lens, give the single best candidate explanation for the question above: name the mechanism, its testable predictions, and what evidence would rule it in or out.`},{id:"mechB",kind:"prompt",x:500,y:440,title:"Candidate: Mechanism B",instruction:`You advocate a higher-level / systems account. Name the mechanism and its boundary conditions.
|
|
151
151
|
From this lens, give the single best candidate explanation for the question above: name the mechanism, its testable predictions, and what evidence would rule it in or out.`},{id:"conf",kind:"prompt",x:980,y:440,title:"Candidate: Confound",instruction:`You argue the effect is an artifact or confound, not the phenomenon of interest.
|
|
@@ -156,13 +156,13 @@ For each candidate above, judge what evidence would rule it OUT and what would r
|
|
|
156
156
|
严格从这个视角,为上面的问题给出唯一最佳的候选解释:说清机制、可检验的预测,以及什么证据能确认或排除它。`},{id:"conf",kind:"prompt",x:980,y:440,title:"候选:混杂",instruction:`你主张这个效应是假象或混杂因素,而非目标现象。
|
|
157
157
|
严格从这个视角,为上面的问题给出唯一最佳的候选解释:说清疑似的混杂来源、可检验的预测,以及什么证据能确认或排除它。`},{id:"null",kind:"prompt",x:1460,y:440,title:"候选:零假设",instruction:`你主张这个效应可能不真实或被夸大,给出最强的收缩性论证。
|
|
158
158
|
严格从这个视角回答上面的问题:什么会让效应消失,以及什么证据能确认或排除这一解释。`},{id:"rev",kind:"prompt",x:560,y:920,title:"鉴别评审",instruction:`你是一位严谨的方法学家,正在对相互竞争的解释做鉴别诊断。
|
|
159
|
-
对上面每个候选,判断什么证据能将它排除(rule out)、什么能将它确认(rule in)。按可区分度排序:哪个检验最能把它们分开?`},{id:"syn",kind:"prompt",x:560,y:1360,title:"收敛",instruction:"综合上面的候选与区分性检验:先确认哪个解释、排除哪个,以及信息量最大的下一个实验是什么。"}],edges:[["q","mechA"],["q","mechB"],["q","conf"],["q","null"],["mechA","rev"],["mechB","rev"],["conf","rev"],["null","rev"],["rev","syn"]]}};function aF(e){const{name:t,steps:n,edges:a}=G5[e]??G5.en,r=n.map(o=>({id:`p-${o.id}`,type:"thought",position:{x:o.x,y:o.y},dragHandle:".drag-handle",data:{question:o.title,instruction:o.instruction,stepKind:o.kind,response:"",responses:[],responseIndex:-1,isCollapsed:!1,isEditing:!1,isEditingResponse:!1,isLoading:!1,tokenCount:0,highlights:[],highlightMode:"tag",attachments:[],excludedAttachmentIds:[],includedAttachmentIds:[],roleMode:"inherit",isRoot:o.id==="q",isBranch:!1}})),s=a.map(([o,c])=>({id:`p-e-${o}-${c}`,source:`p-${o}`,target:`p-${c}`,type:"smoothstep",sourceHandle:"continue",targetHandle:"top",style:{stroke:"#6B5CE7",strokeWidth:2},markerEnd:{type:"arrowclosed",color:"#6B5CE7",width:18,height:18},data:{}}));return{name:t,nodes:r,edges:s}}const $x="thoughtdag:projects",$5="thoughtdag",si=e=>`thoughtdag:project:${e}`;async function qf(e,t){const{projects:n,activeId:a}=rn.getState();if(t&&e===a){const r=n.filter(s=>s.id!==e&&!s.archived).sort((s,o)=>o.updatedAt-s.updatedAt);r.length>0?await Ms(r[0].id):await Nm("My Canvas")}rn.setState(r=>({projects:r.projects.map(s=>s.id===e?{...s,archived:t}:s)})),await Er()}async function rF(e,t){rn.setState(n=>({projects:n.projects.map(a=>a.id===e&&a.sourceSession?{...a,sourceSession:{...a.sourceSession,...t}}:a)})),await Er()}async function iF(e,t,n){rn.setState(a=>({projects:a.projects.map(r=>{if(r.id!==e||!r.sourceSession)return r;const s=r.sourceSession;return s.sessionId===t?{...r,sourceSession:{...s,...n}}:{...r,sourceSession:{...s,chapters:s.chapters?.map(o=>o.sessionId===t?{...o,...n}:o),branches:s.branches?.map(o=>o.sessionId===t?{...o,...n}:o)}}})})),await Er()}async function sF(e,t,n){rn.setState(a=>({projects:a.projects.map(r=>{if(r.id!==e)return r;const s=r.sourceSession??{sessionId:"",runner:"",importedCount:0,tailNodeId:""};return t==="chapter"?{...r,sourceSession:{...s,chapters:[...s.chapters??[],{sessionId:n.sessionId,runner:n.runner,importedCount:n.importedCount,tailNodeId:n.tailNodeId}]}}:{...r,sourceSession:{...s,branches:[...s.branches??[],{...n,anchorNodeId:n.anchorNodeId??""}]}}})})),await Er()}async function oF(e,t){rn.setState(n=>({projects:n.projects.map(a=>{if(a.id!==e||!a.sourceSession)return a;const r=a.sourceSession,s=(r.chapters??[]).filter(d=>d.sessionId!==t),o=(r.branches??[]).filter(d=>d.sessionId!==t),c={...r,chapters:s.length?s:void 0,branches:o.length?o:void 0};return c.sessionId===t&&(c.sessionId="",c.runner="",c.importedCount=0,c.tailNodeId=""),!c.sessionId&&s.length===0&&o.length===0?{...a,sourceSession:void 0}:{...a,sourceSession:c}})})),await Er()}function Yx(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 N7(e,t){rn.setState(n=>({projects:n.projects.map(a=>a.id===e?{...a,instantiatedFrom:{name:t,at:new Date().toISOString()}}:a)})),await Er()}const rn=s0(()=>({projects:[],activeId:null,switching:!1}));async function Er(){const{projects:e,activeId:t}=rn.getState();await Hr($x,{projects:e,activeId:t})}let Y5=null;function C7(){return Y5??=(async()=>{let e=await El($x);if(!e||e.projects.length===0){const t=await El($5),n=crypto.randomUUID(),a=Date.now();t&&await Hr(si(n),t),e={projects:[{id:n,name:"My Canvas",createdAt:a,updatedAt:a}],activeId:n},await Hr($x,e),t&&await Vc($5)}e.projects.some(t=>t.id===e.activeId)||(e.activeId=e.projects[0].id),rn.setState({projects:e.projects,activeId:e.activeId}),se.persist.setOptions({name:si(e.activeId)}),await se.persist.rehydrate()})().catch(async e=>{console.error("[thoughtdag] project boot failed:",e),Qe("error",De("toast.projectsLoadFailed")),se.persist.setOptions({name:si("recovery")}),await se.persist.rehydrate()}),Y5}let Kx=!1;async function lF(){for(const t of Cs.values())t.abort();const e=Date.now()+1e3;for(;Cs.size>0&&Date.now()<e;)await new Promise(t=>setTimeout(t,30));await new Promise(t=>setTimeout(t,0))}const _7=[];async function Ms(e){for(const r of _7)await r().catch(()=>{});const{activeId:t,switching:n,projects:a}=rn.getState();if(!(n||e===t||!a.some(r=>r.id===e))){rn.setState({switching:!0});try{await lF(),await yH(),Kx=!0,se.persist.setOptions({name:si(e)}),await se.persist.rehydrate(),se.setState({selectedNodeId:null,selectedNodeIds:[]}),rn.setState(r=>({activeId:e,projects:r.projects.map(s=>s.id===e&&s.archived?{...s,archived:!1}:s)})),await Er()}finally{Kx=!1,rn.setState({switching:!1})}}}async function Nm(e="Untitled",t="chat"){const n=crypto.randomUUID(),a=Date.now();return rn.setState(r=>({projects:[...r.projects,{id:n,name:e,createdAt:a,updatedAt:a,kind:t}]})),await Er(),await Ms(n),n}async function h2(e,t){rn.setState(n=>({projects:n.projects.map(a=>a.id===e?{...a,agentCwd:t}:a)})),await Er()}async function cF(e,t){rn.setState(n=>({projects:n.projects.map(a=>a.id===e?{...a,agentGuard:t}:a)})),await Er()}async function M7(e,t){rn.setState(n=>({projects:n.projects.map(a=>a.id===e?{...a,name:t}:a)})),await Er()}async function I7(e){const{projects:t,activeId:n}=rn.getState();if(e===n){const a=t.filter(r=>r.id!==e);a.length>0?await Ms(a[0].id):await Nm("My Canvas")}await Vc(si(e)),rn.setState(a=>({projects:a.projects.filter(r=>r.id!==e)})),await Er(),Tt(()=>import("./canvas-record
|
|
159
|
+
对上面每个候选,判断什么证据能将它排除(rule out)、什么能将它确认(rule in)。按可区分度排序:哪个检验最能把它们分开?`},{id:"syn",kind:"prompt",x:560,y:1360,title:"收敛",instruction:"综合上面的候选与区分性检验:先确认哪个解释、排除哪个,以及信息量最大的下一个实验是什么。"}],edges:[["q","mechA"],["q","mechB"],["q","conf"],["q","null"],["mechA","rev"],["mechB","rev"],["conf","rev"],["null","rev"],["rev","syn"]]}};function aF(e){const{name:t,steps:n,edges:a}=G5[e]??G5.en,r=n.map(o=>({id:`p-${o.id}`,type:"thought",position:{x:o.x,y:o.y},dragHandle:".drag-handle",data:{question:o.title,instruction:o.instruction,stepKind:o.kind,response:"",responses:[],responseIndex:-1,isCollapsed:!1,isEditing:!1,isEditingResponse:!1,isLoading:!1,tokenCount:0,highlights:[],highlightMode:"tag",attachments:[],excludedAttachmentIds:[],includedAttachmentIds:[],roleMode:"inherit",isRoot:o.id==="q",isBranch:!1}})),s=a.map(([o,c])=>({id:`p-e-${o}-${c}`,source:`p-${o}`,target:`p-${c}`,type:"smoothstep",sourceHandle:"continue",targetHandle:"top",style:{stroke:"#6B5CE7",strokeWidth:2},markerEnd:{type:"arrowclosed",color:"#6B5CE7",width:18,height:18},data:{}}));return{name:t,nodes:r,edges:s}}const $x="thoughtdag:projects",$5="thoughtdag",si=e=>`thoughtdag:project:${e}`;async function qf(e,t){const{projects:n,activeId:a}=rn.getState();if(t&&e===a){const r=n.filter(s=>s.id!==e&&!s.archived).sort((s,o)=>o.updatedAt-s.updatedAt);r.length>0?await Ms(r[0].id):await Nm("My Canvas")}rn.setState(r=>({projects:r.projects.map(s=>s.id===e?{...s,archived:t}:s)})),await Er()}async function rF(e,t){rn.setState(n=>({projects:n.projects.map(a=>a.id===e&&a.sourceSession?{...a,sourceSession:{...a.sourceSession,...t}}:a)})),await Er()}async function iF(e,t,n){rn.setState(a=>({projects:a.projects.map(r=>{if(r.id!==e||!r.sourceSession)return r;const s=r.sourceSession;return s.sessionId===t?{...r,sourceSession:{...s,...n}}:{...r,sourceSession:{...s,chapters:s.chapters?.map(o=>o.sessionId===t?{...o,...n}:o),branches:s.branches?.map(o=>o.sessionId===t?{...o,...n}:o)}}})})),await Er()}async function sF(e,t,n){rn.setState(a=>({projects:a.projects.map(r=>{if(r.id!==e)return r;const s=r.sourceSession??{sessionId:"",runner:"",importedCount:0,tailNodeId:""};return t==="chapter"?{...r,sourceSession:{...s,chapters:[...s.chapters??[],{sessionId:n.sessionId,runner:n.runner,importedCount:n.importedCount,tailNodeId:n.tailNodeId}]}}:{...r,sourceSession:{...s,branches:[...s.branches??[],{...n,anchorNodeId:n.anchorNodeId??""}]}}})})),await Er()}async function oF(e,t){rn.setState(n=>({projects:n.projects.map(a=>{if(a.id!==e||!a.sourceSession)return a;const r=a.sourceSession,s=(r.chapters??[]).filter(d=>d.sessionId!==t),o=(r.branches??[]).filter(d=>d.sessionId!==t),c={...r,chapters:s.length?s:void 0,branches:o.length?o:void 0};return c.sessionId===t&&(c.sessionId="",c.runner="",c.importedCount=0,c.tailNodeId=""),!c.sessionId&&s.length===0&&o.length===0?{...a,sourceSession:void 0}:{...a,sourceSession:c}})})),await Er()}function Yx(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 N7(e,t){rn.setState(n=>({projects:n.projects.map(a=>a.id===e?{...a,instantiatedFrom:{name:t,at:new Date().toISOString()}}:a)})),await Er()}const rn=s0(()=>({projects:[],activeId:null,switching:!1}));async function Er(){const{projects:e,activeId:t}=rn.getState();await Hr($x,{projects:e,activeId:t})}let Y5=null;function C7(){return Y5??=(async()=>{let e=await El($x);if(!e||e.projects.length===0){const t=await El($5),n=crypto.randomUUID(),a=Date.now();t&&await Hr(si(n),t),e={projects:[{id:n,name:"My Canvas",createdAt:a,updatedAt:a}],activeId:n},await Hr($x,e),t&&await Vc($5)}e.projects.some(t=>t.id===e.activeId)||(e.activeId=e.projects[0].id),rn.setState({projects:e.projects,activeId:e.activeId}),se.persist.setOptions({name:si(e.activeId)}),await se.persist.rehydrate()})().catch(async e=>{console.error("[thoughtdag] project boot failed:",e),Qe("error",De("toast.projectsLoadFailed")),se.persist.setOptions({name:si("recovery")}),await se.persist.rehydrate()}),Y5}let Kx=!1;async function lF(){for(const t of Cs.values())t.abort();const e=Date.now()+1e3;for(;Cs.size>0&&Date.now()<e;)await new Promise(t=>setTimeout(t,30));await new Promise(t=>setTimeout(t,0))}const _7=[];async function Ms(e){for(const r of _7)await r().catch(()=>{});const{activeId:t,switching:n,projects:a}=rn.getState();if(!(n||e===t||!a.some(r=>r.id===e))){rn.setState({switching:!0});try{await lF(),await yH(),Kx=!0,se.persist.setOptions({name:si(e)}),await se.persist.rehydrate(),se.setState({selectedNodeId:null,selectedNodeIds:[]}),rn.setState(r=>({activeId:e,projects:r.projects.map(s=>s.id===e&&s.archived?{...s,archived:!1}:s)})),await Er()}finally{Kx=!1,rn.setState({switching:!1})}}}async function Nm(e="Untitled",t="chat"){const n=crypto.randomUUID(),a=Date.now();return rn.setState(r=>({projects:[...r.projects,{id:n,name:e,createdAt:a,updatedAt:a,kind:t}]})),await Er(),await Ms(n),n}async function h2(e,t){rn.setState(n=>({projects:n.projects.map(a=>a.id===e?{...a,agentCwd:t}:a)})),await Er()}async function cF(e,t){rn.setState(n=>({projects:n.projects.map(a=>a.id===e?{...a,agentGuard:t}:a)})),await Er()}async function M7(e,t){rn.setState(n=>({projects:n.projects.map(a=>a.id===e?{...a,name:t}:a)})),await Er()}async function I7(e){const{projects:t,activeId:n}=rn.getState();if(e===n){const a=t.filter(r=>r.id!==e);a.length>0?await Ms(a[0].id):await Nm("My Canvas")}await Vc(si(e)),rn.setState(a=>({projects:a.projects.filter(r=>r.id!==e)})),await Er(),Tt(()=>import("./canvas-record--EHyNDCM.js"),[]).then(a=>a.removeCanvasRecord(e)).catch(()=>{})}async function Yc(e,t,n="chat",a){const r=Date.now();rn.setState(s=>({projects:[...s.projects,{id:e,name:t,createdAt:r,updatedAt:r,kind:n,...a}]})),await Er(),await Ms(e)}async function uF(e){const{name:t,nodes:n,edges:a}=aF(e),r=crypto.randomUUID();await Hr(si(r),JSON.stringify({state:{nodes:n,edges:a},version:1})),await Yc(r,t,"paradigm")}let S1=null;se.subscribe((e,t)=>{Kx||e.nodes===t.nodes&&e.edges===t.edges||(S1&&clearTimeout(S1),S1=setTimeout(()=>{const{activeId:n}=rn.getState();if(!n)return;const a=[...new Set(se.getState().nodes.map(r=>r.data.importSource?.sessionId).filter(r=>!!r))];rn.setState(r=>({projects:r.projects.map(s=>s.id===n?{...s,updatedAt:Date.now(),provenanceSessions:a}:s)})),Er()},1e3))});const Fr=Object.freeze(Object.defineProperty({__proto__:null,adoptImportedProject:Yc,beforeSwitchHooks:_7,bootProjects:C7,createBuiltinParadigm:uF,createProject:Nm,deleteProject:I7,markInstantiatedFrom:N7,patchLedgerEntry:iF,projectStorageKey:si,registerLedgerEntry:sF,removeLedgerEntry:oF,renameProject:M7,setProjectAgentCwd:h2,setProjectAgentGuard:cF,setProjectArchived:qf,subscribedSessionIds:Yx,switchProject:Ms,updateSourceSession:rF,useProjects:rn},Symbol.toStringTag,{value:"Module"}));function D7(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 O7(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 R7(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 L7(e){const t=e.message?.content?.parts;return Array.isArray(t)?t.filter(n=>typeof n=="string").join(`
|
|
160
160
|
`).trim():""}function dF(e){const t=[],n=[],a=Object.values(e).filter(s=>!s.parent||!e[s.parent]),r=(s,o,c)=>{const d=e[s];if(!d)return;const h=d.message?.author?.role,m=L7(d);let p=o,x=c;if(h==="user"&&m)p=m;else if(h==="assistant"&&m){if(p!==null){const b=O7(p,m,c===null);t.push(b),c&&n.push(R7(c,b.id)),x=b.id,p=null}else if(x){const b=t.find(y=>y.id===x);b&&(b.data.response+=`
|
|
161
161
|
|
|
162
162
|
`+m,b.data.responses=[b.data.response])}}for(const b of d.children??[])r(b,p,x)};for(const s of a)r(s.id,null,null);return{nodes:rr(t,n),edges:n}}function j7(e){return typeof e.text=="string"&&e.text.trim()?e.text.trim():Array.isArray(e.content)?e.content.filter(t=>t?.type==="text"&&typeof t.text=="string").map(t=>t.text).join(`
|
|
163
163
|
`).trim():""}function hF(e){const t=[],n=[];let a=null,r=null;for(const s of e){const o=j7(s);if(o){if(s.sender==="human")a=o;else if(s.sender==="assistant"){if(a!==null){const c=O7(a,o,r===null);t.push(c),r&&n.push(R7(r,c.id)),r=c.id,a=null}else if(r){const c=t.find(d=>d.id===r);c&&(c.data.response+=`
|
|
164
164
|
|
|
165
|
-
`+o,c.data.responses=[c.data.response])}}}}return{nodes:rr(t,n),edges:n}}function fF(e){const t=D7(e),n=[];if(t==="chatgpt")for(const a of e){const r=a.mapping??{},s=Object.values(r).filter(o=>["user","assistant"].includes(o.message?.author?.role??"")&&L7(o)).length;s!==0&&n.push({title:a.title||"Untitled",messageCount:s,source:"chatgpt",build:()=>dF(r)})}else if(t==="claude")for(const a of e){const r=a.chat_messages??[],s=r.filter(o=>j7(o)).length;s!==0&&n.push({title:a.name||"Untitled",messageCount:s,source:"claude",build:()=>hF(r)})}return n}function mF(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 pF(e){const t=e;return!!t&&typeof t=="object"&&t.kind==="thoughtdag-paradigm"&&Array.isArray(t.nodes)&&Array.isArray(t.edges)}const gF=()=>({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 xF(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={...gF(),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:rt.watch,strokeWidth:2,strokeDasharray:"4 4"},animated:!0,markerEnd:{type:"arrowclosed",color:rt.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:rt.accent,strokeWidth:2},animated:!1,markerEnd:{type:"arrowclosed",color:rt.accent,width:18,height:18},data:{}}}),o=new Set(s.map(c=>c.target));for(const c of a)o.has(c.id)||(c.data.isRoot=!0);return{nodes:rr(a,s),edges:s}}const P7=1,f2=1;function Cm(e){return e.replace(/[\\/:*?"<>|]/g,"_").trim()||"canvas"}function u0(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 m2(e){await navigator.clipboard.writeText(e),Qe("success",De("toast.copied"))}function Is(){const{projects:e,activeId:t}=rn.getState();return e.find(n=>n.id===t)?.name??"canvas"}async function yf(e){const{nodes:t}=se.getState(),{confirmIfSensitive:n}=await Tt(async()=>{const{confirmIfSensitive:p}=await import("./sensitive-scan-
|
|
165
|
+
`+o,c.data.responses=[c.data.response])}}}}return{nodes:rr(t,n),edges:n}}function fF(e){const t=D7(e),n=[];if(t==="chatgpt")for(const a of e){const r=a.mapping??{},s=Object.values(r).filter(o=>["user","assistant"].includes(o.message?.author?.role??"")&&L7(o)).length;s!==0&&n.push({title:a.title||"Untitled",messageCount:s,source:"chatgpt",build:()=>dF(r)})}else if(t==="claude")for(const a of e){const r=a.chat_messages??[],s=r.filter(o=>j7(o)).length;s!==0&&n.push({title:a.name||"Untitled",messageCount:s,source:"claude",build:()=>hF(r)})}return n}function mF(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 pF(e){const t=e;return!!t&&typeof t=="object"&&t.kind==="thoughtdag-paradigm"&&Array.isArray(t.nodes)&&Array.isArray(t.edges)}const gF=()=>({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 xF(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={...gF(),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:rt.watch,strokeWidth:2,strokeDasharray:"4 4"},animated:!0,markerEnd:{type:"arrowclosed",color:rt.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:rt.accent,strokeWidth:2},animated:!1,markerEnd:{type:"arrowclosed",color:rt.accent,width:18,height:18},data:{}}}),o=new Set(s.map(c=>c.target));for(const c of a)o.has(c.id)||(c.data.isRoot=!0);return{nodes:rr(a,s),edges:s}}const P7=1,f2=1;function Cm(e){return e.replace(/[\\/:*?"<>|]/g,"_").trim()||"canvas"}function u0(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 m2(e){await navigator.clipboard.writeText(e),Qe("success",De("toast.copied"))}function Is(){const{projects:e,activeId:t}=rn.getState();return e.find(n=>n.id===t)?.name??"canvas"}async function yf(e){const{nodes:t}=se.getState(),{confirmIfSensitive:n}=await Tt(async()=>{const{confirmIfSensitive:p}=await import("./sensitive-scan-OXO0A60C.js");return{confirmIfSensitive:p}},[]);if(!await n(t))return;localStorage.setItem("thoughtdag.lastBackupAt",String(Date.now()));const{nodes:a,edges:r,events:s}=se.getState(),o=await a2(a),{projects:c,activeId:d}=rn.getState(),h=Is(),m=JSON.stringify({version:P7,name:h,projectId:d,exportedAt:new Date().toISOString(),instantiatedFrom:c.find(p=>p.id===d)?.instantiatedFrom,...e?.sharedReadonly?{sharedReadonly:!0}:{},nodes:Ro(o),edges:r,events:s});u0(`${Cm(h)}.thoughtdag.json`,m,"application/json"),Qe("success",We(De("toast.exported"),{name:h}))}function bF(){const{nodes:e,edges:t}=se.getState(),n=Is(),a=JSON.stringify({kind:"thoughtdag-paradigm",version:1,name:n,nodes:Ro(e),edges:t});u0(`${Cm(n)}.paradigm.json`,a,"application/json"),Qe("success",We(De("toast.exported"),{name:n}))}async function yF(e){const t=await e.text();let n;try{n=JSON.parse(t)}catch{const{anyRunnerSessionConversation:r}=await Tt(async()=>{const{anyRunnerSessionConversation:o}=await import("./index-DMEJ2pfg.js");return{anyRunnerSessionConversation:o}},[]),s=await r(t);return s?{kind:"chat",conversations:[s]}:(Qe("error",De("toast.importFailedJson")),{kind:"error"})}if(pF(n)){const r=crypto.randomUUID(),s=await Tm(await z7(n.nodes));return await Hr(si(r),JSON.stringify({state:{nodes:s,edges:n.edges},version:f2})),await Yc(r,n.name||"Paradigm","paradigm"),Qe("success",We(De("toast.imported"),{name:n.name,n:n.nodes.length})),{kind:"own",ok:!0}}if(n?.format==="thoughtdag-manifest")return Qe("error",De("toast.importManifest"),9e3),{kind:"error"};const a=D7(n);if(a==="chatgpt"||a==="claude"){const r=fF(n);return r.length===0?(Qe("error",De("toast.importNoConversations")),{kind:"error"}):{kind:"chat",conversations:r}}return{kind:"own",ok:await kF(e,n)}}function vF(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 wF(e){let t=null,n=0;for(const a of e){const{nodes:r,edges:s}=a.build();if(r.length===0)continue;if(t===null){const{useUiStore:c}=await Tt(async()=>{const{useUiStore:d}=await Promise.resolve().then(()=>Em);return{useUiStore:d}},void 0);c.getState().setArrivalFocusNodeId(r[r.length-1].id)}const o=crypto.randomUUID();await Hr(si(o),JSON.stringify({state:{nodes:Ro(r),edges:s},version:f2})),await Yc(o,a.title.slice(0,60)),t??=o,n+=r.length}t&&Qe("success",We(De("toast.importedChats"),{n:e.length,m:n}))}async function z7(e){const t=await Fs();if(!t||t.models.length===0)return e;const n=new Set,a=new Set,r=e.map(s=>{const o=s.data?.model;if(!o)return s;const c=k7(o,t.models);return c===o?s:c?(n.add(`${o} → ${c}`),{...s,data:{...s.data,model:c}}):(a.add(o),s)});return n.size&&Qe("info",We(De("import.modelsRemapped"),{list:[...n].join(",")}),9e3),a.size&&Qe("info",We(De("import.modelsMissing"),{list:[...a].join(",")}),1e4),r}async function kF(e,t){let n;try{n=t??JSON.parse(await e.text())}catch{return Qe("error",De("toast.importFailedJson")),!1}if(!Array.isArray(n.nodes)||!Array.isArray(n.edges))return Qe("error",De("toast.importFailedMissing")),!1;if(n.nodes.length>0&&!vF(n.nodes))return Qe("error",De("toast.importFailedShape"),9e3),!1;if(n.sharedReadonly&&!await _s({title:De("import.readonlyTitle"),message:De("import.readonlyConfirm"),confirmLabel:De("common.confirm")}))return!1;if(n.sourceSession?.sessionId){const{useProjects:o,switchProject:c}=await Tt(async()=>{const{useProjects:h,switchProject:m}=await Promise.resolve().then(()=>Fr);return{useProjects:h,switchProject:m}},void 0),d=o.getState().projects.find(h=>h.sourceSession?.sessionId===n.sourceSession.sessionId);if(d)return await c(d.id),Qe("info",We(De("toast.importAlreadySubscribed"),{name:d.name}),9e3),!0}const a=crypto.randomUUID(),r=await Tm(await z7(n.nodes));await Hr(si(a),JSON.stringify({state:{nodes:Ro(r),edges:n.edges,...Array.isArray(n.events)?{events:n.events}:{}},version:f2}));const s=n.name?.trim()||e.name.replace(/\.thoughtdag\.json$|\.json$/i,"")||"Imported canvas";return await Yc(a,s,"chat",{instantiatedFrom:n.instantiatedFrom,sourceSession:n.sourceSession}),Qe("success",We(De("toast.imported"),{name:s,n:n.nodes.length})),!0}function EF(){const{events:e}=se.getState();if(e.length===0)return;const t=r=>`"${r.replace(/"/g,'""')}"`,a=["t,op,id,detail",...e.map(r=>[r.t,r.op,r.id??"",r.d?t(JSON.stringify(r.d)):""].join(","))].join(`
|
|
166
166
|
`);u0(`${Cm(Is())}.events.csv`,a,"text/csv"),Qe("success",We(De("toast.exported"),{name:Is()}))}function SF(e){const t=[`## Q: ${e.data.question}`,""],n=e.data.attachments||[];return n.length>0&&t.push(`> ${De("export.attachmentsLabel")} ${n.map(a=>a.name).join(", ")}`,""),e.data.branchContext&&t.push(`> Exploring from: "${e.data.branchContext.slice(0,120)}"`,""),t.push(e.data.response||"_(no response)_",""),t.join(`
|
|
167
167
|
`)}function B7(e,t){const n=e.reduce((a,r)=>a+$n(r.data.question+r.data.response),0);return[`# ${Is()}`,"",`> ${t} · exported ${new Date().toISOString().slice(0,10)} · ${e.length} nodes · ~${n} tok`,"",e.map(SF).join(`
|
|
168
168
|
---
|
|
@@ -517,17 +517,17 @@ ${De("continue.genOpen")}
|
|
|
517
517
|
${c.join(`
|
|
518
518
|
`)||"-"}`}]),h=e7(new Date().toISOString()).slice(0,10),m=lae(n.position);ei("note",m,{question:`**📌 ${h} · ${De("continue.recapTag")}**
|
|
519
519
|
|
|
520
|
-
${d.trim()}`}),h9.current?.setCenter((n.position.x+m.x)/2+260,(n.position.y+m.y)/2+140,{zoom:.75,duration:600}),Qe("success",De("continue.noteDropped"))}catch(a){Qe("error",a instanceof Error?a.message:String(a))}}}function cae({x:e,y:t,nodeId:n,onClose:a}){const r=zt(),s=L.useRef(null),o=se(C=>C.nodes.find(T=>T.id===n));if(L.useEffect(()=>{const C=N=>{s.current?.contains(N.target)||a()},T=N=>{N.key==="Escape"&&a()};return window.addEventListener("mousedown",C),window.addEventListener("keydown",T),()=>{window.removeEventListener("mousedown",C),window.removeEventListener("keydown",T)}},[a]),!o)return null;const c=o.data.stepKind,d=!!c,h=!d&&!!o.data.response&&!o.data.isLoading,m=d?c==="note"||c==="link"?o.data.question:"":o.data.response,p="w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5",x="text-ink-faint shrink-0",b=200,y=340,k=Math.min(e,window.innerWidth-b-8),S=Math.min(t,window.innerHeight-y-8),w=C=>()=>{a(),C()};return Qa.createPortal(u.jsxs("div",{ref:s,className:"fixed z-[70] bg-card border border-line rounded-xl shadow-lg py-1 w-[200px] animate-fade-in",style:{left:k,top:S},children:[!d&&u.jsxs("button",{className:p,onClick:w(()=>{se.getState().setSelectedNodeId(n),pe.getState().setPanelOpen(!0)}),children:[u.jsx(Io,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.openPanel")]}),h&&u.jsxs("button",{className:p,onClick:w(()=>pe.getState().setResponseViewerNodeId(n)),children:[u.jsx(jS,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.readingView")]}),h&&u.jsxs("button",{className:p,onClick:w(()=>{se.getState().rerunNode(n)}),children:[u.jsx(or,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.rerun")]}),h&&u.jsxs("button",{className:p,title:De("actions.regenBranchTitle"),onClick:w(()=>{se.getState().regenerate(n)}),children:[u.jsx(DS,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.regenBranch")]}),h&&u.jsxs("button",{className:p,onClick:w(()=>{f9(n)}),children:[u.jsx(Vi,{size:14,strokeWidth:1.75,className:x})," ",r("continue.summarize")]}),m&&u.jsxs("button",{className:p,onClick:w(()=>{navigator.clipboard.writeText(m).then(()=>Qe("success",De("ctx.copied")))}),children:[u.jsx(Hs,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.copyContent")]}),!d&&u.jsxs("button",{className:p,title:De("exp.takeTitle"),onClick:w(()=>{Tt(()=>import("./experiment-loop-
|
|
520
|
+
${d.trim()}`}),h9.current?.setCenter((n.position.x+m.x)/2+260,(n.position.y+m.y)/2+140,{zoom:.75,duration:600}),Qe("success",De("continue.noteDropped"))}catch(a){Qe("error",a instanceof Error?a.message:String(a))}}}function cae({x:e,y:t,nodeId:n,onClose:a}){const r=zt(),s=L.useRef(null),o=se(C=>C.nodes.find(T=>T.id===n));if(L.useEffect(()=>{const C=N=>{s.current?.contains(N.target)||a()},T=N=>{N.key==="Escape"&&a()};return window.addEventListener("mousedown",C),window.addEventListener("keydown",T),()=>{window.removeEventListener("mousedown",C),window.removeEventListener("keydown",T)}},[a]),!o)return null;const c=o.data.stepKind,d=!!c,h=!d&&!!o.data.response&&!o.data.isLoading,m=d?c==="note"||c==="link"?o.data.question:"":o.data.response,p="w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5",x="text-ink-faint shrink-0",b=200,y=340,k=Math.min(e,window.innerWidth-b-8),S=Math.min(t,window.innerHeight-y-8),w=C=>()=>{a(),C()};return Qa.createPortal(u.jsxs("div",{ref:s,className:"fixed z-[70] bg-card border border-line rounded-xl shadow-lg py-1 w-[200px] animate-fade-in",style:{left:k,top:S},children:[!d&&u.jsxs("button",{className:p,onClick:w(()=>{se.getState().setSelectedNodeId(n),pe.getState().setPanelOpen(!0)}),children:[u.jsx(Io,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.openPanel")]}),h&&u.jsxs("button",{className:p,onClick:w(()=>pe.getState().setResponseViewerNodeId(n)),children:[u.jsx(jS,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.readingView")]}),h&&u.jsxs("button",{className:p,onClick:w(()=>{se.getState().rerunNode(n)}),children:[u.jsx(or,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.rerun")]}),h&&u.jsxs("button",{className:p,title:De("actions.regenBranchTitle"),onClick:w(()=>{se.getState().regenerate(n)}),children:[u.jsx(DS,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.regenBranch")]}),h&&u.jsxs("button",{className:p,onClick:w(()=>{f9(n)}),children:[u.jsx(Vi,{size:14,strokeWidth:1.75,className:x})," ",r("continue.summarize")]}),m&&u.jsxs("button",{className:p,onClick:w(()=>{navigator.clipboard.writeText(m).then(()=>Qe("success",De("ctx.copied")))}),children:[u.jsx(Hs,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.copyContent")]}),!d&&u.jsxs("button",{className:p,title:De("exp.takeTitle"),onClick:w(()=>{Tt(()=>import("./experiment-loop-BysOJBTB.js"),[]).then(C=>C.takeToExperiment(n,"branch"))}),"data-take-to-experiment":!0,children:[u.jsx(cz,{size:14,strokeWidth:1.75,className:x})," ",r("exp.take")]}),!d&&u.jsxs("button",{className:p,title:De("exp.continueTitle"),onClick:w(()=>{Tt(()=>import("./experiment-loop-BysOJBTB.js"),[]).then(C=>C.takeToExperiment(n,"continue"))}),"data-take-to-continue":!0,children:[u.jsx(Io,{size:14,strokeWidth:1.75,className:x})," ",r("exp.continue")]}),u.jsxs("button",{className:p,onClick:w(()=>se.getState().duplicateNode(n)),children:[u.jsx(oz,{size:14,strokeWidth:1.75,className:x})," ",r("ctx.duplicate")]}),u.jsxs("button",{className:p,onClick:w(()=>se.getState().setArchived([n],!o.data.archived)),children:[o.data.archived?u.jsx(NS,{size:14,strokeWidth:1.75,className:x}):u.jsx(zo,{size:14,strokeWidth:1.75,className:x}),o.data.archived?r("ctx.unarchive"):r("archive.label")]}),u.jsx("div",{className:"h-px bg-line my-1"}),u.jsxs("button",{className:"w-full text-left px-3 py-2 text-xs text-red-600 hover:bg-red-50 transition-colors flex items-center gap-2.5",onClick:w(()=>{_s({title:De("confirm.deleteNodesTitle"),message:We(De("confirm.deleteNodes"),{n:1}),confirmLabel:De("common.delete"),danger:!0}).then(C=>{C&&se.getState().deleteNode(n)})}),children:[u.jsx(Va,{size:14,strokeWidth:1.75,className:"shrink-0"})," ",r("common.delete")]})]}),document.body)}function uae({onLocate:e}){const t=pe(N=>N.highlightsOverviewOpen),n=pe(N=>N.setHighlightsOverviewOpen),a=se(N=>N.nodes),r=se(N=>N.removeHighlight),s=se(N=>N.weaveHighlights),o=zt(),[c,d]=L.useState("time"),[h,m]=L.useState(new Set),[p,x]=L.useState(""),b=L.useMemo(()=>{const N=[];for(const O of a){const M=O.data.question.replace(/\s+/g," ").trim().slice(0,60)||"—";for(const _ of O.data.highlights||[])N.push({hlId:_.id,text:_.text,at:_.at,nodeId:O.id,nodeTitle:M})}const D=c==="time"?[...N].sort((O,M)=>(M.at??"").localeCompare(O.at??"")):N;return D.map((O,M)=>({...O,showGroup:c==="node"&&(M===0||D[M-1].nodeTitle!==O.nodeTitle)}))},[a,c]);if(!t)return null;const y=N=>{const D=new Set(h);D.has(N)?D.delete(N):D.add(N),m(D)},k=()=>{n(!1),m(new Set),x("")},S=()=>{const N=[...h].filter(O=>b.some(M=>M.hlId===O));if(N.length===0)return;const D=[...new Set(b.filter(O=>N.includes(O.hlId)).map(O=>O.nodeId))];k(),s(D,p.trim()||void 0,N)},w=()=>{const N=b.map(D=>`- ${D.text}
|
|
521
521
|
— ${D.nodeTitle}${D.at?` · ${D.at.slice(0,10)}`:""}`);p2(`# ${o("hlov.title")}
|
|
522
522
|
|
|
523
523
|
${N.join(`
|
|
524
524
|
`)}
|
|
525
525
|
`)},C="shrink-0 text-2xs font-mono text-accent bg-accent/10 hover:bg-accent/20 rounded-full px-1.5 py-0.5 transition-colors",T=(N,D)=>u.jsx("button",{onClick:()=>d(N),className:`text-2xs px-2.5 py-1 rounded-full transition-colors ${c===N?"bg-accent/10 text-accent":"text-ink-faint hover:bg-wash"}`,children:D});return Qa.createPortal(u.jsx("div",{className:"fixed inset-0 z-[60] bg-ink/30 backdrop-blur-sm flex items-center justify-center p-6",onClick:k,children:u.jsxs("div",{className:"bg-card rounded-2xl shadow-2xl border border-line w-[640px] max-h-[80vh] flex flex-col",onClick:N=>N.stopPropagation(),children:[u.jsxs("div",{className:"flex items-center gap-2 px-5 py-3 border-b border-line shrink-0",children:[u.jsx(zd,{size:15,strokeWidth:1.75,className:"text-amber-500"}),u.jsx("span",{className:"text-sm font-semibold text-ink",children:o("hlov.title")}),u.jsx("span",{className:"text-2xs text-ink-faint",children:We(o("hlov.count"),{n:b.length})}),u.jsx("div",{className:"flex-1"}),T("time",o("hlov.byTime")),T("node",o("hlov.byNode")),u.jsx("button",{onClick:k,className:"text-ink-faint hover:text-ink w-7 h-7 rounded-lg hover:bg-wash flex items-center justify-center transition-colors ml-1",children:u.jsx(mn,{size:15,strokeWidth:1.75})})]}),u.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-5 py-3",children:[b.length===0&&u.jsx("p",{className:"text-xs text-ink-faint italic py-2",children:o("hlov.empty")}),b.map(N=>u.jsxs("div",{children:[N.showGroup&&u.jsx("div",{className:"text-2xs text-ink-faint font-medium mt-3 mb-1 first:mt-0 truncate",children:N.nodeTitle}),u.jsxs("div",{className:"group flex items-start gap-2.5 py-1.5 border-b border-line/50 last:border-0",children:[u.jsx("input",{type:"checkbox",checked:h.has(N.hlId),onChange:()=>y(N.hlId),className:"mt-1 accent-amber-500 shrink-0"}),u.jsx("span",{className:"flex-1 text-sm text-ink leading-relaxed min-w-0",children:u.jsx("mark",{className:"bg-amber-100 text-amber-800 px-0.5 rounded",children:N.text})}),c==="time"&&u.jsxs("button",{className:C,onClick:()=>{k(),e(N.nodeId)},title:o("hlov.locateTitle"),children:[N.nodeTitle.slice(0,14),N.nodeTitle.length>14?"…":""]}),c==="node"&&u.jsx("button",{className:C,onClick:()=>{k(),e(N.nodeId)},title:o("hlov.locateTitle"),children:"↦"}),N.at&&u.jsx("span",{className:"shrink-0 text-2xs text-ink-faint font-mono mt-0.5",children:N.at.slice(5,10)}),u.jsx("button",{onClick:()=>r(N.nodeId,N.hlId),title:o("common.delete"),className:"text-ink-faint hover:text-red-500 w-5 h-5 rounded-full flex items-center justify-center transition-colors shrink-0 opacity-0 group-hover:opacity-100",children:u.jsx(Va,{size:12,strokeWidth:1.75})})]})]},N.hlId))]}),u.jsxs("div",{className:"px-5 py-3 border-t border-line shrink-0 space-y-2",children:[h.size>0&&u.jsxs("div",{className:"flex gap-1.5",children:[u.jsx("input",{type:"text",value:p,onChange:N=>x(N.target.value),onKeyDown:N=>{N.key==="Enter"&&!Xa(N)&&S()},placeholder:o("toolbar.intentPlaceholder"),className:"flex-1 text-xs border border-amber-500/30 rounded-lg px-3 py-2 focus:outline-none focus:ring-1 focus:ring-amber-500 bg-amber-500/5"}),u.jsx("button",{onClick:S,className:"text-xs bg-amber-500 hover:bg-amber-400 text-white px-3 py-2 rounded-lg transition-colors shrink-0",children:We(o("hlov.weavePicked"),{n:h.size})})]}),u.jsxs("div",{className:"flex items-center",children:[u.jsx("span",{className:"text-2xs text-ink-faint",children:h.size>0?We(o("hlov.picked"),{n:h.size}):o("hlov.pickHint")}),u.jsx("div",{className:"flex-1"}),b.length>0&&u.jsxs("button",{onClick:w,className:"flex items-center gap-1.5 text-2xs text-ink-faint hover:text-ink-muted transition-colors",title:o("hlov.exportTitle"),children:[u.jsx(Tc,{size:12,strokeWidth:1.75})," ",o("hlov.export")]})]})]})]})}),document.body)}const dae={pdf:vi,img:Sz,txt:vi,note:Vi,link:Do};function hae({onLocate:e}){const t=pe(x=>x.materialsOverviewOpen),n=pe(x=>x.setMaterialsOverviewOpen),a=se(x=>x.nodes),r=zt(),[s,o]=L.useState("time"),c=L.useMemo(()=>{const x=[];for(const y of a){const k=y.data.stepKind;if(k==="note"||k==="link"){const w=k==="link"?y.data.linkTitle||y.data.linkUrl||"—":y.data.question.split(`
|
|
526
|
-
`)[0].replace(/^#+\s*/,"").slice(0,60)||"—";x.push({key:y.id,name:w,icon:k,at:y.data.createdAt,nodeId:y.id,nodeTitle:w,canOpen:!0});continue}const S=y.data.question.replace(/\s+/g," ").trim().slice(0,60)||(k==="file"?r("glyph.file"):"—");for(const w of y.data.attachments||[]){const C=w.type==="application/pdf"?"pdf":w.type.startsWith("image/")?"img":"txt";x.push({key:w.id,name:w.name,icon:C,sizeKB:w.size/1024,at:w.addedAt,nodeId:y.id,nodeTitle:S,canOpen:C==="pdf"})}}const b=s==="time"?[...x].sort((y,k)=>(k.at??"").localeCompare(y.at??"")):x;return b.map((y,k)=>({...y,showGroup:s==="node"&&(k===0||b[k-1].nodeTitle!==y.nodeTitle)}))},[a,s,r]);if(!t)return null;const d=()=>n(!1),h=x=>{d(),pe.getState().setReaderNodeId(x)},m="shrink-0 text-2xs font-mono text-accent bg-accent/10 hover:bg-accent/20 rounded-full px-1.5 py-0.5 transition-colors",p=(x,b)=>u.jsx("button",{onClick:()=>o(x),className:`text-2xs px-2.5 py-1 rounded-full transition-colors ${s===x?"bg-accent/10 text-accent":"text-ink-faint hover:bg-wash"}`,children:b});return Qa.createPortal(u.jsx("div",{className:"fixed inset-0 z-[60] bg-ink/30 backdrop-blur-sm flex items-center justify-center p-6",onClick:d,children:u.jsxs("div",{className:"bg-card rounded-2xl shadow-2xl border border-line w-[640px] max-h-[80vh] flex flex-col",onClick:x=>x.stopPropagation(),children:[u.jsxs("div",{className:"flex items-center gap-2 px-5 py-3 border-b border-line shrink-0",children:[u.jsx(wi,{size:15,strokeWidth:1.75,className:"text-warm"}),u.jsx("span",{className:"text-sm font-semibold text-ink",children:r("matov.title")}),u.jsx("span",{className:"text-2xs text-ink-faint",children:We(r("matov.count"),{n:c.length})}),u.jsx("div",{className:"flex-1"}),p("time",r("hlov.byTime")),p("node",r("hlov.byNode")),u.jsx("button",{onClick:d,className:"text-ink-faint hover:text-ink w-7 h-7 rounded-lg hover:bg-wash flex items-center justify-center transition-colors ml-1",children:u.jsx(mn,{size:15,strokeWidth:1.75})})]}),u.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-5 py-3",children:[c.length===0&&u.jsx("p",{className:"text-xs text-ink-faint italic py-2",children:r("matov.empty")}),c.map(x=>{const b=dae[x.icon];return u.jsxs("div",{children:[x.showGroup&&u.jsx("div",{className:"text-2xs text-ink-faint font-medium mt-3 mb-1 first:mt-0 truncate",children:x.nodeTitle}),u.jsxs("div",{className:"group flex items-center gap-2.5 py-1.5 border-b border-line/50 last:border-0",children:[u.jsx("span",{className:`w-7 h-7 rounded-lg flex items-center justify-center shrink-0 ${x.icon==="note"?"bg-amber-100 text-amber-600":x.icon==="link"?"bg-cyan-100 text-cyan-700":"bg-wash text-ink-muted"}`,children:u.jsx(b,{size:14,strokeWidth:1.75})}),u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsx("p",{className:"text-sm text-ink truncate",children:x.name}),u.jsxs("p",{className:"text-2xs text-ink-faint",children:[x.sizeKB!=null?`${x.sizeKB.toFixed(1)} KB`:r(`matov.kind.${x.icon}`),x.at?` · ${x.at.slice(0,10)}`:""]})]}),s==="time"&&u.jsxs("button",{className:m,onClick:()=>{d(),e(x.nodeId)},title:r("hlov.locateTitle"),children:[x.nodeTitle.slice(0,14),x.nodeTitle.length>14?"…":""]}),s==="node"&&u.jsx("button",{className:m,onClick:()=>{d(),e(x.nodeId)},title:r("hlov.locateTitle"),children:"↦"}),x.canOpen&&u.jsx("button",{onClick:()=>h(x.nodeId),title:r("attach.openReader"),className:"w-7 h-7 rounded-lg text-ink-faint hover:text-accent hover:bg-wash flex items-center justify-center transition-colors shrink-0",children:u.jsx(Io,{size:14,strokeWidth:1.75})})]})]},x.key)})]})]})}),document.body)}function fae(e){const t=e.data.stepKind;return t==="note"||t==="file"||t==="link"||t==="frame"?t:e.data.condensedFrom?.length?"distill":"qa"}function mae(e,t){let n=0,a=e.indexOf(t);for(;a!==-1;)n+=1,a=e.indexOf(t,a+t.length);return n}function pae(e,t,n){const r=Math.max(0,t-40),s=Math.min(e.length,t+n+60),o=r>0?"…":"",c=s<e.length?"…":"";return{snippet:o+e.slice(r,s)+c,matchStart:o.length+(t-r)}}function gae(e,t){const n=t.trim().toLowerCase();if(!n)return[];const a=[];for(const r of e){const s=r.data;if(s.stepKind==="fanout")continue;const o=[s.question??"",s.response??"",...(s.highlights??[]).map(p=>p.text),s.linkTitle??"",...(s.attachments??[]).map(p=>p.name),s.summaries?.[s.responseIndex]??s.summary??""];let c=0,d=null;for(const p of o){if(!p)continue;const x=p.toLowerCase(),b=x.indexOf(n);b!==-1&&(c+=mae(x,n),d||(d={text:p,at:b}))}if(!d)continue;const{snippet:h,matchStart:m}=pae(d.text,d.at,n.length);a.push({nodeId:r.id,kind:fae(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 xae={qa:PS,note:Vi,file:vi,link:Do,frame:Px,distill:vm},lx=50;function bae({open:e,onClose:t,onLocate:n}){const a=zt(),r=se(w=>w.nodes),s=pe(w=>w.setSearchHitIds),[o,c]=L.useState(""),[d,h]=L.useState(0),m=L.useRef(null),[p,x]=L.useState(e);p!==e&&(x(e),e&&(c(""),h(0))),L.useEffect(()=>{e&&setTimeout(()=>m.current?.focus(),50)},[e]);const[b,y]=L.useState("");L.useEffect(()=>{const w=setTimeout(()=>y(o),120);return()=>clearTimeout(w)},[o]);const k=L.useMemo(()=>e?gae(r,b):[],[e,r,b]);if(L.useEffect(()=>{if(!e||!b.trim()){s(null);return}s(new Set(k.map(w=>w.nodeId)))},[e,b,k,s]),L.useEffect(()=>()=>s(null),[s]),!e)return null;const S=w=>{n(w.nodeId);const C=b.trim().toLowerCase();setTimeout(()=>{const T=document.querySelector("[data-focus-panel]");if(!T||!C)return;const N=document.createTreeWalker(T,NodeFilter.SHOW_TEXT);let D;for(;D=N.nextNode();)if(D.textContent?.toLowerCase().includes(C)){const O=D.parentElement;O?.scrollIntoView({block:"center",behavior:"smooth"}),O?.animate([{backgroundColor:"rgba(107, 92, 231, 0.22)"},{backgroundColor:"transparent"}],{duration:1800,easing:"ease-out"});break}},500)};return u.jsx("div",{className:"absolute top-4 left-1/2 -translate-x-1/2 z-20 w-[460px]","data-canvas-search":!0,children:u.jsxs("div",{className:"bg-card border border-line rounded-xl shadow-xl overflow-hidden",children:[u.jsxs("div",{className:"flex items-center gap-2 px-4 py-2.5 transition-shadow focus-within:ring-1 focus-within:ring-accent/40",children:[u.jsx(zf,{size:15,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),u.jsx("input",{ref:m,type:"text",value:o,onChange:w=>{c(w.target.value),h(0)},onKeyDown:w=>{w.key==="Escape"&&(w.stopPropagation(),t()),w.key==="ArrowDown"&&(w.preventDefault(),h(C=>Math.min(C+1,k.length-1))),w.key==="ArrowUp"&&(w.preventDefault(),h(C=>Math.max(C-1,0))),w.key==="Enter"&&!Xa(w)&&k[d]&&(w.preventDefault(),S(k[d]))},placeholder:a("search.placeholder"),className:"flex-1 bg-transparent text-sm text-ink placeholder-ink-faint focus:outline-none","data-search-input":!0}),o&&u.jsx("span",{className:"text-2xs text-ink-faint shrink-0",children:We(a("search.count"),{n:k.length})}),u.jsx("button",{onClick:t,className:"text-ink-faint hover:text-ink transition-colors shrink-0",children:u.jsx(mn,{size:14,strokeWidth:1.75})})]}),k.length>0&&u.jsxs("ul",{className:"border-t border-line/60 max-h-72 overflow-y-auto py-1",children:[k.slice(0,lx).map((w,C)=>{const T=xae[w.kind],D=r.find(O=>O.id===w.nodeId)?.data.question||"—";return u.jsx("li",{children:u.jsxs("button",{onClick:()=>S(w),onMouseEnter:()=>h(C),className:`w-full text-left px-4 py-2 transition-colors ${C===d?"bg-accent/8":""} ${w.archived?"opacity-55":""}`,"data-search-hit-row":!0,children:[u.jsxs("p",{className:`text-xs font-medium truncate flex items-center gap-1.5 ${C===d?"text-accent":"text-ink"}`,children:[u.jsx(T,{size:12,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),u.jsx("span",{className:"truncate flex-1 min-w-0",children:D}),w.archived&&u.jsx(zo,{size:11,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),w.count>1&&u.jsxs("span",{className:"text-2xs text-ink-faint font-normal shrink-0",children:["×",w.count]})]}),u.jsxs("p",{className:"text-2xs text-ink-faint mt-0.5 break-all leading-relaxed",children:[w.snippet.slice(0,w.matchStart),u.jsx("mark",{className:"bg-accent/20 text-accent rounded-sm px-px",children:w.snippet.slice(w.matchStart,w.matchStart+w.matchLen)}),w.snippet.slice(w.matchStart+w.matchLen)]})]})},w.nodeId)}),k.length>lx&&u.jsx("li",{className:"px-4 py-2 text-2xs text-ink-faint",children:We(a("search.more"),{n:k.length-lx})})]})]})})}const fE=new Set(["note","file","link"]),Mi=e=>{const t=(e?.data.question??"").replace(/\s+/g," ").trim();return t.length>24?`${t.slice(0,24)}…`:t||"(空)"};function cx(e,t,n){const a=new Set([e]),r=[e];for(;r.length;){const s=r.shift();for(const o of n.get(s)??[]){if(o===t)return!0;a.has(o)||(a.add(o),r.push(o))}}return!1}function ux(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 mE(e,t){const n=[],a=new Map(e.map(_=>[_.id,_])),r=t.filter(_=>!_.data?.isCrossLink),s=t.filter(_=>_.data?.isCrossLink),o=ux(r),c=ux(t);for(const _ of r){const R=ux(r.filter(G=>G.id!==_.id));cx(_.source,_.target,R)&&n.push({tier:1,kind:"residual-edge",fixable:!0,params:{a:Mi(a.get(_.source)),b:Mi(a.get(_.target))},nodeIds:[_.target,_.source],edgeIds:[_.id]})}for(const _ of s)cx(_.source,_.target,o)&&n.push({tier:1,kind:"shadow-reference",fixable:!0,params:{a:Mi(a.get(_.source)),b:Mi(a.get(_.target))},nodeIds:[_.target,_.source],edgeIds:[_.id]});const d=new Map;for(const _ of r)d.has(_.source)||d.set(_.source,[]),d.get(_.source).push(_.target);const h=[];for(const _ of d.values()){const R=_.filter(P=>a.get(P)?.data.stepKind==="prompt"),G=_.filter(P=>a.get(P)?.data.isBranch);R.length>=2&&h.push(R),G.length>=2&&h.push(G)}for(const _ of h)for(const R of _)for(const G of _)if(R!==G&&cx(R,G,c)){const P=t.find(V=>V.source===R&&V.target===G);n.push({tier:1,kind:"blind-pool-breach",fixable:!!P,params:{a:Mi(a.get(G)),b:Mi(a.get(R))},nodeIds:[G,R],edgeIds:P?[P.id]:[]})}for(const _ of h){const R=_.map(P=>new Set(t.filter(V=>V.target===P).map(V=>V.source))),G=new Set([...R[0]].filter(P=>R.every(V=>V.has(P))));_.forEach((P,V)=>{const J=[...R[V]].filter(H=>!G.has(H)&&!_.includes(H));J.length>0&&n.push({tier:1,kind:"pool-asymmetry",fixable:!1,params:{a:Mi(a.get(P)),n:J.length},nodeIds:[P,...J],edgeIds:[]})})}const m=e.filter(_=>!fE.has(_.data.stepKind??"")&&_.data.stepKind!=="frame"),p=new Map,x=new Map,b=_=>$n(_.data.question+_.data.response),y=new Map;for(const _ of m)y.set(_.id,0);for(const _ of r)y.has(_.target)&&y.has(_.source)&&y.set(_.target,(y.get(_.target)??0)+1);const k=m.filter(_=>(y.get(_.id)??0)===0).map(_=>_.id),S=[],w=new Map(y);for(;k.length;){const _=k.shift();S.push(_);for(const R of o.get(_)??[])w.has(R)&&(w.set(R,w.get(R)-1),w.get(R)===0&&k.push(R))}for(const _ of S){const R=a.get(_),G=r.filter(J=>J.target===_&&p.has(J.source)),P=G.length?Math.max(...G.map(J=>p.get(J.source)))+1:1,V=G.length?Math.max(...G.map(J=>x.get(J.source)))+b(R):b(R);p.set(_,P),x.set(_,V)}const C=m.filter(_=>!(o.get(_.id)??[]).length&&!_.data.archived),T=C.filter(_=>(p.get(_.id)??0)>=8||(x.get(_.id)??0)>=15e3).sort((_,R)=>(p.get(R.id)??0)-(p.get(_.id)??0)).slice(0,3);for(const _ of T)n.push({tier:2,kind:"long-chain",fixable:!1,params:{a:Mi(_),d:p.get(_.id)??0,tok:x.get(_.id)??0},nodeIds:[_.id],edgeIds:[]});const N=C.filter(_=>_.data.response);N.length>=4&&n.push({tier:2,kind:"open-branches",fixable:!1,params:{n:N.length},nodeIds:N.map(_=>_.id),edgeIds:[]});for(const _ of m){const R=r.filter(P=>P.target===_.id).length,G=(o.get(_.id)??[]).length;R>=2&&G>=1&&n.push({tier:2,kind:"collider-continuation",fixable:!1,params:{a:Mi(_),n:R},nodeIds:[_.id],edgeIds:[]})}const D=e.filter(_=>fE.has(_.data.stepKind??"")&&!t.some(R=>R.source===_.id));D.length>0&&n.push({tier:2,kind:"orphan-materials",fixable:!1,params:{n:D.length},nodeIds:D.map(_=>_.id),edgeIds:[]});const O=_=>{const R=new Set,G=[_];for(;G.length;)for(const P of o.get(G.shift())??[])R.has(P)||(R.add(P),G.push(P));return R.size},M=m.map(_=>({n:_,c:O(_.id)})).filter(({c:_})=>_>=5).sort((_,R)=>R.c-_.c).slice(0,3);for(const{n:_,c:R}of M)n.push({tier:2,kind:"load-bearing",fixable:!1,params:{a:Mi(_),n:R},nodeIds:[_.id],edgeIds:[]});return n.sort((_,R)=>_.tier-R.tier)}const yae={"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 vae({onLocate:e,openPing:t=0,showTrigger:n=!0}){const a=se(w=>w.deleteEdges),r=zt(),[s,o]=L.useState(!1),[c,d]=L.useState([]),h=L.useRef(null),[m,p]=L.useState(t);L.useEffect(()=>{if(!s)return;const w=C=>{h.current?.contains(C.target)||o(!1)};return window.addEventListener("mousedown",w),()=>window.removeEventListener("mousedown",w)},[s]);const x=()=>{const{nodes:w,edges:C}=se.getState();d(mE(w,C)),o(!0)};t!==m&&(p(t),x());const b=w=>{a(w.edgeIds);const{nodes:C,edges:T}=se.getState();d(mE(C,T))},y=c.filter(w=>w.tier===1),k=c.filter(w=>w.tier===2),S=(w,C)=>u.jsxs("div",{className:"px-3 py-2 border-b border-line/50 last:border-0 flex items-start gap-2",children:[u.jsx("span",{className:`w-1.5 h-1.5 rounded-full mt-1.5 shrink-0 ${w.tier===1?"bg-red-400":"bg-amber-400"}`}),u.jsx("span",{className:"text-xs text-ink-muted leading-relaxed flex-1 min-w-0",children:We(r(yae[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(ud,{size:13,strokeWidth:1.75})}),w.fixable&&u.jsx("button",{onClick:()=>b(w),title:r("diag.fix"),className:"w-6 h-6 rounded-md text-ink-faint hover:text-red-500 hover:bg-red-50 flex items-center justify-center transition-colors",children:u.jsx(Va,{size:13,strokeWidth:1.75})})]})]},`${w.kind}-${C}`);return u.jsxs("div",{ref:h,className:"relative",children:[n&&u.jsx("button",{onClick:()=>s?o(!1):x(),className:`bg-card/90 backdrop-blur border rounded-lg w-8 h-8 flex items-center justify-center shadow-sm transition-colors ${s?"border-accent/40 text-accent":"border-line text-ink-faint hover:bg-wash"}`,title:r("toolbar.diagnose"),children:u.jsx(HS,{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?"":We(r("diag.summary"),{a:y.length,b:k.length})})]}),c.length===0&&u.jsx("p",{className:"px-3 py-3 text-xs text-ink-faint italic",children:r("diag.clean")}),y.length>0&&u.jsxs(u.Fragment,{children:[u.jsx("p",{className:"px-3 pt-2 pb-1 text-2xs font-semibold text-red-500",children:r("diag.tier1")}),y.map(S)]}),k.length>0&&u.jsxs(u.Fragment,{children:[u.jsx("p",{className:"px-3 pt-2 pb-1 text-2xs font-semibold text-amber-600",children:r("diag.tier2")}),k.map(S)]})]})]})}async function m9(e,t){const{default:n}=await Tt(async()=>{const{default:s}=await import("./purify.es-Cz4mVeUR.js");return{default:s}},[]),a=n.sanitize(e,{WHOLE_DOCUMENT:!0,ADD_TAGS:["style"],FORBID_TAGS:["script","iframe","object","embed","form","base","meta",...t?.baseUrl?[]:["link"]]}),r=new DOMParser().parseFromString(a,"text/html");return t?.baseUrl&&wae(r,t.baseUrl),r}function wae(e,t){const n=a=>{try{const r=new URL(a,t);return/^https?:$/.test(r.protocol)?r.href:null}catch{return null}};e.querySelectorAll("link").forEach(a=>{const r=a.getAttribute("href"),s=r?n(r):null;(a.getAttribute("rel")??"").toLowerCase()!=="stylesheet"||!s?a.remove():a.setAttribute("href",s)});for(const[a,r]of[["img","src"],["source","src"],["video","poster"],["a","href"]])e.querySelectorAll(`${a}[${r}]`).forEach(s=>{const o=s.getAttribute(r),c=o?n(o):null;c?s.setAttribute(r,c):s.removeAttribute(r)});e.querySelectorAll("img[srcset], source[srcset]").forEach(a=>a.removeAttribute("srcset"))}async function kae(){const[{default:e},t]=await Promise.all([Tt(()=>import("./turndown.browser.es-kLzRgxYD.js"),[]),Tt(()=>import("./turndown-plugin-gfm.cjs-pG4f1F8S.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 pE(e){return(e.textContent??"").trim().length>0||!!e.querySelector("img,svg,canvas,video")}function uy(e){const t=Array.from(e.querySelectorAll(".reveal .slides > section"));if(t.length>=2){const s=[];for(const o of t){const c=Array.from(o.children).filter(d=>d.tagName==="SECTION");c.length>0?s.push(...c):s.push(o)}return s}const n=new Map;for(const s of Array.from(e.body?.querySelectorAll("[class]")??[])){const o=s.getAttribute("class")??"";if(!/(?:^|[\s_-])(?:slide|page)(?:[\s_-]|$)/i.test(o)||!pE(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(pE);return r.length>=3?r:null}async function Eae(e,t){const n=await m9(e,t),a=await kae(),r=uy(n);if(r)return{markdown:r.map((d,h)=>`<!-- tdag-page:${h+1} -->
|
|
526
|
+
`)[0].replace(/^#+\s*/,"").slice(0,60)||"—";x.push({key:y.id,name:w,icon:k,at:y.data.createdAt,nodeId:y.id,nodeTitle:w,canOpen:!0});continue}const S=y.data.question.replace(/\s+/g," ").trim().slice(0,60)||(k==="file"?r("glyph.file"):"—");for(const w of y.data.attachments||[]){const C=w.type==="application/pdf"?"pdf":w.type.startsWith("image/")?"img":"txt";x.push({key:w.id,name:w.name,icon:C,sizeKB:w.size/1024,at:w.addedAt,nodeId:y.id,nodeTitle:S,canOpen:C==="pdf"})}}const b=s==="time"?[...x].sort((y,k)=>(k.at??"").localeCompare(y.at??"")):x;return b.map((y,k)=>({...y,showGroup:s==="node"&&(k===0||b[k-1].nodeTitle!==y.nodeTitle)}))},[a,s,r]);if(!t)return null;const d=()=>n(!1),h=x=>{d(),pe.getState().setReaderNodeId(x)},m="shrink-0 text-2xs font-mono text-accent bg-accent/10 hover:bg-accent/20 rounded-full px-1.5 py-0.5 transition-colors",p=(x,b)=>u.jsx("button",{onClick:()=>o(x),className:`text-2xs px-2.5 py-1 rounded-full transition-colors ${s===x?"bg-accent/10 text-accent":"text-ink-faint hover:bg-wash"}`,children:b});return Qa.createPortal(u.jsx("div",{className:"fixed inset-0 z-[60] bg-ink/30 backdrop-blur-sm flex items-center justify-center p-6",onClick:d,children:u.jsxs("div",{className:"bg-card rounded-2xl shadow-2xl border border-line w-[640px] max-h-[80vh] flex flex-col",onClick:x=>x.stopPropagation(),children:[u.jsxs("div",{className:"flex items-center gap-2 px-5 py-3 border-b border-line shrink-0",children:[u.jsx(wi,{size:15,strokeWidth:1.75,className:"text-warm"}),u.jsx("span",{className:"text-sm font-semibold text-ink",children:r("matov.title")}),u.jsx("span",{className:"text-2xs text-ink-faint",children:We(r("matov.count"),{n:c.length})}),u.jsx("div",{className:"flex-1"}),p("time",r("hlov.byTime")),p("node",r("hlov.byNode")),u.jsx("button",{onClick:d,className:"text-ink-faint hover:text-ink w-7 h-7 rounded-lg hover:bg-wash flex items-center justify-center transition-colors ml-1",children:u.jsx(mn,{size:15,strokeWidth:1.75})})]}),u.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-5 py-3",children:[c.length===0&&u.jsx("p",{className:"text-xs text-ink-faint italic py-2",children:r("matov.empty")}),c.map(x=>{const b=dae[x.icon];return u.jsxs("div",{children:[x.showGroup&&u.jsx("div",{className:"text-2xs text-ink-faint font-medium mt-3 mb-1 first:mt-0 truncate",children:x.nodeTitle}),u.jsxs("div",{className:"group flex items-center gap-2.5 py-1.5 border-b border-line/50 last:border-0",children:[u.jsx("span",{className:`w-7 h-7 rounded-lg flex items-center justify-center shrink-0 ${x.icon==="note"?"bg-amber-100 text-amber-600":x.icon==="link"?"bg-cyan-100 text-cyan-700":"bg-wash text-ink-muted"}`,children:u.jsx(b,{size:14,strokeWidth:1.75})}),u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsx("p",{className:"text-sm text-ink truncate",children:x.name}),u.jsxs("p",{className:"text-2xs text-ink-faint",children:[x.sizeKB!=null?`${x.sizeKB.toFixed(1)} KB`:r(`matov.kind.${x.icon}`),x.at?` · ${x.at.slice(0,10)}`:""]})]}),s==="time"&&u.jsxs("button",{className:m,onClick:()=>{d(),e(x.nodeId)},title:r("hlov.locateTitle"),children:[x.nodeTitle.slice(0,14),x.nodeTitle.length>14?"…":""]}),s==="node"&&u.jsx("button",{className:m,onClick:()=>{d(),e(x.nodeId)},title:r("hlov.locateTitle"),children:"↦"}),x.canOpen&&u.jsx("button",{onClick:()=>h(x.nodeId),title:r("attach.openReader"),className:"w-7 h-7 rounded-lg text-ink-faint hover:text-accent hover:bg-wash flex items-center justify-center transition-colors shrink-0",children:u.jsx(Io,{size:14,strokeWidth:1.75})})]})]},x.key)})]})]})}),document.body)}function fae(e){const t=e.data.stepKind;return t==="note"||t==="file"||t==="link"||t==="frame"?t:e.data.condensedFrom?.length?"distill":"qa"}function mae(e,t){let n=0,a=e.indexOf(t);for(;a!==-1;)n+=1,a=e.indexOf(t,a+t.length);return n}function pae(e,t,n){const r=Math.max(0,t-40),s=Math.min(e.length,t+n+60),o=r>0?"…":"",c=s<e.length?"…":"";return{snippet:o+e.slice(r,s)+c,matchStart:o.length+(t-r)}}function gae(e,t){const n=t.trim().toLowerCase();if(!n)return[];const a=[];for(const r of e){const s=r.data;if(s.stepKind==="fanout")continue;const o=[s.question??"",s.response??"",...(s.highlights??[]).map(p=>p.text),s.linkTitle??"",...(s.attachments??[]).map(p=>p.name),s.summaries?.[s.responseIndex]??s.summary??""];let c=0,d=null;for(const p of o){if(!p)continue;const x=p.toLowerCase(),b=x.indexOf(n);b!==-1&&(c+=mae(x,n),d||(d={text:p,at:b}))}if(!d)continue;const{snippet:h,matchStart:m}=pae(d.text,d.at,n.length);a.push({nodeId:r.id,kind:fae(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 xae={qa:PS,note:Vi,file:vi,link:Do,frame:Px,distill:vm},lx=50;function bae({open:e,onClose:t,onLocate:n}){const a=zt(),r=se(w=>w.nodes),s=pe(w=>w.setSearchHitIds),[o,c]=L.useState(""),[d,h]=L.useState(0),m=L.useRef(null),[p,x]=L.useState(e);p!==e&&(x(e),e&&(c(""),h(0))),L.useEffect(()=>{e&&setTimeout(()=>m.current?.focus(),50)},[e]);const[b,y]=L.useState("");L.useEffect(()=>{const w=setTimeout(()=>y(o),120);return()=>clearTimeout(w)},[o]);const k=L.useMemo(()=>e?gae(r,b):[],[e,r,b]);if(L.useEffect(()=>{if(!e||!b.trim()){s(null);return}s(new Set(k.map(w=>w.nodeId)))},[e,b,k,s]),L.useEffect(()=>()=>s(null),[s]),!e)return null;const S=w=>{n(w.nodeId);const C=b.trim().toLowerCase();setTimeout(()=>{const T=document.querySelector("[data-focus-panel]");if(!T||!C)return;const N=document.createTreeWalker(T,NodeFilter.SHOW_TEXT);let D;for(;D=N.nextNode();)if(D.textContent?.toLowerCase().includes(C)){const O=D.parentElement;O?.scrollIntoView({block:"center",behavior:"smooth"}),O?.animate([{backgroundColor:"rgba(107, 92, 231, 0.22)"},{backgroundColor:"transparent"}],{duration:1800,easing:"ease-out"});break}},500)};return u.jsx("div",{className:"absolute top-4 left-1/2 -translate-x-1/2 z-20 w-[460px]","data-canvas-search":!0,children:u.jsxs("div",{className:"bg-card border border-line rounded-xl shadow-xl overflow-hidden",children:[u.jsxs("div",{className:"flex items-center gap-2 px-4 py-2.5 transition-shadow focus-within:ring-1 focus-within:ring-accent/40",children:[u.jsx(zf,{size:15,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),u.jsx("input",{ref:m,type:"text",value:o,onChange:w=>{c(w.target.value),h(0)},onKeyDown:w=>{w.key==="Escape"&&(w.stopPropagation(),t()),w.key==="ArrowDown"&&(w.preventDefault(),h(C=>Math.min(C+1,k.length-1))),w.key==="ArrowUp"&&(w.preventDefault(),h(C=>Math.max(C-1,0))),w.key==="Enter"&&!Xa(w)&&k[d]&&(w.preventDefault(),S(k[d]))},placeholder:a("search.placeholder"),className:"flex-1 bg-transparent text-sm text-ink placeholder-ink-faint focus:outline-none","data-search-input":!0}),o&&u.jsx("span",{className:"text-2xs text-ink-faint shrink-0",children:We(a("search.count"),{n:k.length})}),u.jsx("button",{onClick:t,className:"text-ink-faint hover:text-ink transition-colors shrink-0",children:u.jsx(mn,{size:14,strokeWidth:1.75})})]}),k.length>0&&u.jsxs("ul",{className:"border-t border-line/60 max-h-72 overflow-y-auto py-1",children:[k.slice(0,lx).map((w,C)=>{const T=xae[w.kind],D=r.find(O=>O.id===w.nodeId)?.data.question||"—";return u.jsx("li",{children:u.jsxs("button",{onClick:()=>S(w),onMouseEnter:()=>h(C),className:`w-full text-left px-4 py-2 transition-colors ${C===d?"bg-accent/8":""} ${w.archived?"opacity-55":""}`,"data-search-hit-row":!0,children:[u.jsxs("p",{className:`text-xs font-medium truncate flex items-center gap-1.5 ${C===d?"text-accent":"text-ink"}`,children:[u.jsx(T,{size:12,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),u.jsx("span",{className:"truncate flex-1 min-w-0",children:D}),w.archived&&u.jsx(zo,{size:11,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),w.count>1&&u.jsxs("span",{className:"text-2xs text-ink-faint font-normal shrink-0",children:["×",w.count]})]}),u.jsxs("p",{className:"text-2xs text-ink-faint mt-0.5 break-all leading-relaxed",children:[w.snippet.slice(0,w.matchStart),u.jsx("mark",{className:"bg-accent/20 text-accent rounded-sm px-px",children:w.snippet.slice(w.matchStart,w.matchStart+w.matchLen)}),w.snippet.slice(w.matchStart+w.matchLen)]})]})},w.nodeId)}),k.length>lx&&u.jsx("li",{className:"px-4 py-2 text-2xs text-ink-faint",children:We(a("search.more"),{n:k.length-lx})})]})]})})}const fE=new Set(["note","file","link"]),Mi=e=>{const t=(e?.data.question??"").replace(/\s+/g," ").trim();return t.length>24?`${t.slice(0,24)}…`:t||"(空)"};function cx(e,t,n){const a=new Set([e]),r=[e];for(;r.length;){const s=r.shift();for(const o of n.get(s)??[]){if(o===t)return!0;a.has(o)||(a.add(o),r.push(o))}}return!1}function ux(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 mE(e,t){const n=[],a=new Map(e.map(_=>[_.id,_])),r=t.filter(_=>!_.data?.isCrossLink),s=t.filter(_=>_.data?.isCrossLink),o=ux(r),c=ux(t);for(const _ of r){const R=ux(r.filter(G=>G.id!==_.id));cx(_.source,_.target,R)&&n.push({tier:1,kind:"residual-edge",fixable:!0,params:{a:Mi(a.get(_.source)),b:Mi(a.get(_.target))},nodeIds:[_.target,_.source],edgeIds:[_.id]})}for(const _ of s)cx(_.source,_.target,o)&&n.push({tier:1,kind:"shadow-reference",fixable:!0,params:{a:Mi(a.get(_.source)),b:Mi(a.get(_.target))},nodeIds:[_.target,_.source],edgeIds:[_.id]});const d=new Map;for(const _ of r)d.has(_.source)||d.set(_.source,[]),d.get(_.source).push(_.target);const h=[];for(const _ of d.values()){const R=_.filter(P=>a.get(P)?.data.stepKind==="prompt"),G=_.filter(P=>a.get(P)?.data.isBranch);R.length>=2&&h.push(R),G.length>=2&&h.push(G)}for(const _ of h)for(const R of _)for(const G of _)if(R!==G&&cx(R,G,c)){const P=t.find(V=>V.source===R&&V.target===G);n.push({tier:1,kind:"blind-pool-breach",fixable:!!P,params:{a:Mi(a.get(G)),b:Mi(a.get(R))},nodeIds:[G,R],edgeIds:P?[P.id]:[]})}for(const _ of h){const R=_.map(P=>new Set(t.filter(V=>V.target===P).map(V=>V.source))),G=new Set([...R[0]].filter(P=>R.every(V=>V.has(P))));_.forEach((P,V)=>{const J=[...R[V]].filter(H=>!G.has(H)&&!_.includes(H));J.length>0&&n.push({tier:1,kind:"pool-asymmetry",fixable:!1,params:{a:Mi(a.get(P)),n:J.length},nodeIds:[P,...J],edgeIds:[]})})}const m=e.filter(_=>!fE.has(_.data.stepKind??"")&&_.data.stepKind!=="frame"),p=new Map,x=new Map,b=_=>$n(_.data.question+_.data.response),y=new Map;for(const _ of m)y.set(_.id,0);for(const _ of r)y.has(_.target)&&y.has(_.source)&&y.set(_.target,(y.get(_.target)??0)+1);const k=m.filter(_=>(y.get(_.id)??0)===0).map(_=>_.id),S=[],w=new Map(y);for(;k.length;){const _=k.shift();S.push(_);for(const R of o.get(_)??[])w.has(R)&&(w.set(R,w.get(R)-1),w.get(R)===0&&k.push(R))}for(const _ of S){const R=a.get(_),G=r.filter(J=>J.target===_&&p.has(J.source)),P=G.length?Math.max(...G.map(J=>p.get(J.source)))+1:1,V=G.length?Math.max(...G.map(J=>x.get(J.source)))+b(R):b(R);p.set(_,P),x.set(_,V)}const C=m.filter(_=>!(o.get(_.id)??[]).length&&!_.data.archived),T=C.filter(_=>(p.get(_.id)??0)>=8||(x.get(_.id)??0)>=15e3).sort((_,R)=>(p.get(R.id)??0)-(p.get(_.id)??0)).slice(0,3);for(const _ of T)n.push({tier:2,kind:"long-chain",fixable:!1,params:{a:Mi(_),d:p.get(_.id)??0,tok:x.get(_.id)??0},nodeIds:[_.id],edgeIds:[]});const N=C.filter(_=>_.data.response);N.length>=4&&n.push({tier:2,kind:"open-branches",fixable:!1,params:{n:N.length},nodeIds:N.map(_=>_.id),edgeIds:[]});for(const _ of m){const R=r.filter(P=>P.target===_.id).length,G=(o.get(_.id)??[]).length;R>=2&&G>=1&&n.push({tier:2,kind:"collider-continuation",fixable:!1,params:{a:Mi(_),n:R},nodeIds:[_.id],edgeIds:[]})}const D=e.filter(_=>fE.has(_.data.stepKind??"")&&!t.some(R=>R.source===_.id));D.length>0&&n.push({tier:2,kind:"orphan-materials",fixable:!1,params:{n:D.length},nodeIds:D.map(_=>_.id),edgeIds:[]});const O=_=>{const R=new Set,G=[_];for(;G.length;)for(const P of o.get(G.shift())??[])R.has(P)||(R.add(P),G.push(P));return R.size},M=m.map(_=>({n:_,c:O(_.id)})).filter(({c:_})=>_>=5).sort((_,R)=>R.c-_.c).slice(0,3);for(const{n:_,c:R}of M)n.push({tier:2,kind:"load-bearing",fixable:!1,params:{a:Mi(_),n:R},nodeIds:[_.id],edgeIds:[]});return n.sort((_,R)=>_.tier-R.tier)}const yae={"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 vae({onLocate:e,openPing:t=0,showTrigger:n=!0}){const a=se(w=>w.deleteEdges),r=zt(),[s,o]=L.useState(!1),[c,d]=L.useState([]),h=L.useRef(null),[m,p]=L.useState(t);L.useEffect(()=>{if(!s)return;const w=C=>{h.current?.contains(C.target)||o(!1)};return window.addEventListener("mousedown",w),()=>window.removeEventListener("mousedown",w)},[s]);const x=()=>{const{nodes:w,edges:C}=se.getState();d(mE(w,C)),o(!0)};t!==m&&(p(t),x());const b=w=>{a(w.edgeIds);const{nodes:C,edges:T}=se.getState();d(mE(C,T))},y=c.filter(w=>w.tier===1),k=c.filter(w=>w.tier===2),S=(w,C)=>u.jsxs("div",{className:"px-3 py-2 border-b border-line/50 last:border-0 flex items-start gap-2",children:[u.jsx("span",{className:`w-1.5 h-1.5 rounded-full mt-1.5 shrink-0 ${w.tier===1?"bg-red-400":"bg-amber-400"}`}),u.jsx("span",{className:"text-xs text-ink-muted leading-relaxed flex-1 min-w-0",children:We(r(yae[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(ud,{size:13,strokeWidth:1.75})}),w.fixable&&u.jsx("button",{onClick:()=>b(w),title:r("diag.fix"),className:"w-6 h-6 rounded-md text-ink-faint hover:text-red-500 hover:bg-red-50 flex items-center justify-center transition-colors",children:u.jsx(Va,{size:13,strokeWidth:1.75})})]})]},`${w.kind}-${C}`);return u.jsxs("div",{ref:h,className:"relative",children:[n&&u.jsx("button",{onClick:()=>s?o(!1):x(),className:`bg-card/90 backdrop-blur border rounded-lg w-8 h-8 flex items-center justify-center shadow-sm transition-colors ${s?"border-accent/40 text-accent":"border-line text-ink-faint hover:bg-wash"}`,title:r("toolbar.diagnose"),children:u.jsx(HS,{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?"":We(r("diag.summary"),{a:y.length,b:k.length})})]}),c.length===0&&u.jsx("p",{className:"px-3 py-3 text-xs text-ink-faint italic",children:r("diag.clean")}),y.length>0&&u.jsxs(u.Fragment,{children:[u.jsx("p",{className:"px-3 pt-2 pb-1 text-2xs font-semibold text-red-500",children:r("diag.tier1")}),y.map(S)]}),k.length>0&&u.jsxs(u.Fragment,{children:[u.jsx("p",{className:"px-3 pt-2 pb-1 text-2xs font-semibold text-amber-600",children:r("diag.tier2")}),k.map(S)]})]})]})}async function m9(e,t){const{default:n}=await Tt(async()=>{const{default:s}=await import("./purify.es-Cz4mVeUR.js");return{default:s}},[]),a=n.sanitize(e,{WHOLE_DOCUMENT:!0,ADD_TAGS:["style"],FORBID_TAGS:["script","iframe","object","embed","form","base","meta",...t?.baseUrl?[]:["link"]]}),r=new DOMParser().parseFromString(a,"text/html");return t?.baseUrl&&wae(r,t.baseUrl),r}function wae(e,t){const n=a=>{try{const r=new URL(a,t);return/^https?:$/.test(r.protocol)?r.href:null}catch{return null}};e.querySelectorAll("link").forEach(a=>{const r=a.getAttribute("href"),s=r?n(r):null;(a.getAttribute("rel")??"").toLowerCase()!=="stylesheet"||!s?a.remove():a.setAttribute("href",s)});for(const[a,r]of[["img","src"],["source","src"],["video","poster"],["a","href"]])e.querySelectorAll(`${a}[${r}]`).forEach(s=>{const o=s.getAttribute(r),c=o?n(o):null;c?s.setAttribute(r,c):s.removeAttribute(r)});e.querySelectorAll("img[srcset], source[srcset]").forEach(a=>a.removeAttribute("srcset"))}async function kae(){const[{default:e},t]=await Promise.all([Tt(()=>import("./turndown.browser.es-kLzRgxYD.js"),[]),Tt(()=>import("./turndown-plugin-gfm.cjs-DeGwvSez.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 pE(e){return(e.textContent??"").trim().length>0||!!e.querySelector("img,svg,canvas,video")}function uy(e){const t=Array.from(e.querySelectorAll(".reveal .slides > section"));if(t.length>=2){const s=[];for(const o of t){const c=Array.from(o.children).filter(d=>d.tagName==="SECTION");c.length>0?s.push(...c):s.push(o)}return s}const n=new Map;for(const s of Array.from(e.body?.querySelectorAll("[class]")??[])){const o=s.getAttribute("class")??"";if(!/(?:^|[\s_-])(?:slide|page)(?:[\s_-]|$)/i.test(o)||!pE(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(pE);return r.length>=3?r:null}async function Eae(e,t){const n=await m9(e,t),a=await kae(),r=uy(n);if(r)return{markdown:r.map((d,h)=>`<!-- tdag-page:${h+1} -->
|
|
527
527
|
|
|
528
528
|
${a.turndown(d.cloneNode(!0).outerHTML).trim()}`).join(`
|
|
529
529
|
|
|
530
|
-
`).trim(),numPages:r.length,title:n.title||void 0};let s=n.title||void 0,o=null;try{const{default:c}=await Tt(async()=>{const{default:h}=await import("./index-
|
|
530
|
+
`).trim(),numPages:r.length,title:n.title||void 0};let s=n.title||void 0,o=null;try{const{default:c}=await Tt(async()=>{const{default:h}=await import("./index-DE_CLHc3.js").then(m=>m.i);return{default:h}},[]),d=new c(n.cloneNode(!0)).parse();d?.content&&d.content.replace(/<[^>]+>/g," ").trim().length>40&&(o=d.content,d.title&&(s=d.title))}catch{}if(o==null&&n.body){const c=n.body.cloneNode(!0);c.querySelectorAll("script,style,noscript,nav,header,footer,aside").forEach(d=>d.remove()),o=c.innerHTML}return{markdown:o?a.turndown(o).trim():"",title:s}}const Sae=[":root{color-scheme:light}","html,body{margin:0;padding:0;overflow-x:hidden}","[data-tdag-shell]{position:static !important;transform:none !important;width:auto !important;height:auto !important;min-height:0 !important;max-height:none !important;overflow:visible !important;display:block !important;margin:0 !important;padding:0 !important}","[data-tdag-slide]{display:block !important;visibility:visible !important;opacity:1 !important;position:relative !important;inset:auto !important;transform:none !important;margin:0 auto !important}"].join(`
|
|
531
531
|
`);function kb(e){return e.replace(/&/g,"&").replace(/"/g,""")}function Tae(e,t){const n=e.tagName.toLowerCase(),a=["class","id","style"].map(r=>{const s=e.getAttribute(r);return s?` ${r}="${kb(s)}"`:""}).join("");return`<${n}${a} data-tdag-shell>${t}</${n}>`}function gE(e,t,n,a){const r=n?` class="${kb(n)}"`:"",s=a?` style="${kb(a)}"`:"";return`<!doctype html><html><head><meta charset="utf-8">${e}<style>${Sae}</style></head><body${r}${s}>${t}</body></html>`}async function p9(e,t){const n=await m9(e,t),a=Array.from(n.querySelectorAll('style, link[rel="stylesheet" i]')).map(c=>c.outerHTML).join(`
|
|
532
532
|
`),r=n.body?.getAttribute("class"),s=n.body?.getAttribute("style"),o=uy(n);return o?o.map((c,d)=>{const h=c.cloneNode(!0);h.setAttribute("data-tdag-slide","");let m=h.outerHTML;for(let p=c.parentElement;p&&p!==n.body&&p.tagName!=="HTML";p=p.parentElement)m=Tae(p,m);return{page:d+1,srcdoc:gE(a,m,r,s)}}):[{page:null,srcdoc:gE(a,n.body?.innerHTML??"",r,s)}]}const g9=Object.freeze(Object.defineProperty({__proto__:null,buildReaderPages:p9,detectSlides:uy,extractHtmlMaterial:Eae},Symbol.toStringTag,{value:"Module"}));function xE({att:e,onSelect:t,clipMode:n,onClipped:a,baseUrl:r}){const s=zt(),[o,c]=L.useState(null),[d,h]=L.useState(!1);return L.useEffect(()=>{let m=!1;return p9(e.content,r?{baseUrl:r}:void 0).then(p=>{m||c(p)}).catch(()=>{m||h(!0)}),()=>{m=!0}},[]),d?u.jsx("p",{className:"text-sm text-ink-faint italic py-10 text-center",children:s("reader.htmlNoText")}):o?u.jsx("div",{className:"flex flex-col items-center py-6 px-4",children:o.map(m=>u.jsxs("div",{"data-page":m.page??void 0,className:"w-full max-w-[860px]",children:[m.page!=null&&u.jsxs("div",{className:"text-2xs text-ink-faint font-mono text-center select-none pt-4 pb-2",children:["— p.",m.page," —"]}),u.jsx(Aae,{srcdoc:m.srcdoc,page:m.page,onSelect:t,clipMode:n,onClipped:a,clipFailedText:s("reader.clipFailed")})]},m.page??0))}):u.jsxs("div",{className:"flex items-center justify-center gap-2 h-full min-h-[200px] text-sm text-ink-muted",children:[u.jsx(Un,{size:16,strokeWidth:1.75,className:"animate-spin text-accent"})," ",s("reader.loading")]})}function Aae({srcdoc:e,page:t,onSelect:n,clipMode:a,onClipped:r,clipFailedText:s}){const o=L.useRef(null),c=L.useRef(null),[d,h]=L.useState(120),[m,p]=L.useState(null),[x,b]=L.useState(!1),y=()=>{const w=c.current,C=w?.contentDocument;if(!w||!C?.body)return;const T=C.body.scrollWidth||C.documentElement.scrollWidth,N=w.clientWidth;T>N+2&&(C.body.style.zoom=String(N/T)),h(Math.max(40,C.documentElement.scrollHeight+2)),C.addEventListener("mouseup",()=>{const D=w.contentWindow?.getSelection();if(!D||D.isCollapsed){n(null);return}const O=D.toString().replace(/\s+/g," ").trim();if(O.length<2)return;const M=D.getRangeAt(0).getBoundingClientRect(),_=w.getBoundingClientRect();n({text:O,page:t,x:_.left+M.left+M.width/2,y:_.top+M.bottom})})},k=w=>{const C=o.current.getBoundingClientRect();return{x:Math.min(1,Math.max(0,(w.clientX-C.left)/C.width)),y:Math.min(1,Math.max(0,(w.clientY-C.top)/C.height))}},S=()=>{if(!m||x){p(null);return}const w=Math.min(m.x0,m.x1),C=Math.min(m.y0,m.y1),T=Math.abs(m.x1-m.x0),N=Math.abs(m.y1-m.y0);if(p(null),T<.02||N<.01)return;const D=c.current?.contentDocument;!D?.documentElement||!r||(b(!0),(async()=>{const{toCanvas:O}=await Tt(async()=>{const{toCanvas:F}=await import("./index-BeoRn2gJ.js");return{toCanvas:F}},[]),M=await O(D.documentElement,{pixelRatio:2}),_=Math.floor(w*M.width),R=Math.floor(C*M.height),G=Math.max(1,Math.floor(T*M.width)),P=Math.max(1,Math.floor(N*M.height)),V=document.createElement("canvas");V.width=G,V.height=P,V.getContext("2d").drawImage(M,_,R,G,P,0,0,G,P);const J=o.current.getBoundingClientRect(),H={left:J.left+w*J.width,top:J.top+C*J.height,width:T*J.width,height:N*J.height};r(t??1,[w,C,T,N],V.toDataURL("image/png"),H)})().catch(()=>Qe("error",s)).finally(()=>b(!1)))};return u.jsxs("div",{ref:o,className:"relative",children:[u.jsx("iframe",{ref:c,sandbox:"allow-same-origin",srcDoc:e,onLoad:y,style:{height:d},className:"w-full border-0 bg-white shadow-md rounded-sm","aria-label":t!=null?`p.${t}`:"document"}),a&&u.jsxs("div",{className:"absolute inset-0 cursor-crosshair",style:{zIndex:6},"data-clip-overlay":t??1,onMouseDown:w=>{w.preventDefault();const C=k(w);p({x0:C.x,y0:C.y,x1:C.x,y1:C.y})},onMouseMove:w=>{if(m){const C=k(w);p({...m,x1:C.x,y1:C.y})}},onMouseUp:S,onMouseLeave:()=>{m&&S()},children:[x&&u.jsx("div",{className:"absolute top-2 right-2 flex items-center gap-1.5 text-2xs text-warm bg-card/95 border border-line rounded-lg px-2 py-1 shadow-sm",children:u.jsx(Un,{size:11,strokeWidth:1.75,className:"animate-spin"})}),m&&u.jsx("div",{className:"absolute border-2 border-warm bg-warm/10 rounded-sm pointer-events-none",style:{left:`${Math.min(m.x0,m.x1)*100}%`,top:`${Math.min(m.y0,m.y1)*100}%`,width:`${Math.abs(m.x1-m.x0)*100}%`,height:`${Math.abs(m.y1-m.y0)*100}%`}})]})]})}let dx=null;function Nae(){return dx||(dx=Promise.all([Tt(()=>import("./pdf-gh-BrLFn.js"),[]),Tt(()=>import("./pdf.worker.min-C_APr3k7.js"),[])]).then(([e,t])=>(e.GlobalWorkerOptions.workerSrc=t.default,e))),dx}function Cae(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 _ae=/<!--\s*tdag-page:(\d+)\s*-->/;function Mae(e){const t=e.split(_ae),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 hx=60,bE=new Map;function Iae({onLocate:e}){const t=pe(a=>a.readerNodeId),n=se(a=>t?a.nodes.find(r=>r.id===t):void 0);return L.useEffect(()=>{t&&!n&&pe.getState().setReaderNodeId(null)},[t,n]),n?u.jsx(Dae,{node:n,onLocate:e},n.id):null}function Dae({node:e,onLocate:t}){const n=zt(),a=e.data,r=a.stepKind==="file"||!a.stepKind&&(a.attachments??[]).some(ge=>ge.type==="application/pdf")?"file":a.stepKind==="link"?"link":"note",s=L.useMemo(()=>a.attachments??[],[a.attachments]),o=s.find(ge=>ge.type==="application/pdf"),c=s.find(ge=>ge.type==="text/html"),d=r==="link"?a.linkSnapshotHtml:void 0,h=L.useMemo(()=>d?{id:`link-snapshot-${e.id}`,name:a.linkTitle||a.linkUrl||"snapshot",type:"text/html",size:d.length,content:d}:null,[d,e.id,a.linkTitle,a.linkUrl]),m=L.useMemo(()=>s.filter(ge=>ge.type.startsWith("image/")),[s]),p=()=>pe.getState().setReaderNodeId(null),x=L.useMemo(()=>{if(o)return o.extractedText??"";if(r==="file"){const ge=s.filter(Nt=>!Nt.type.startsWith("image/")&&Nt.type!=="application/pdf"),Je=ge.map(Nt=>{const Ct=Nt.type==="text/html"?Nt.extractedText??"":Nt.content;return ge.length>1?`### ${Nt.name}
|
|
533
533
|
|
|
@@ -544,7 +544,7 @@ ${Nt.extractedText}`:Nt.extractedText);return Je.join(`
|
|
|
544
544
|
`))if(t.includes('"user"'))try{const n=JSON.parse(t);let a=null;if(n.type==="user"&&typeof n.message?.content=="string"?a=n.message.content:n.type==="response_item"&&n.payload?.type==="message"&&n.payload.role==="user"&&(a=(n.payload.content??[]).find(r=>r.type==="input_text"&&r.text)?.text??null),a&&a.trim()&&!a.startsWith("<")&&!a.startsWith("# AGENTS.md instructions for "))return a.trim().split(`
|
|
545
545
|
`)[0].slice(0,80)}catch{}return null}function Pae(e){for(const t of e){if(t.type!=="user/message")continue;const n=t.data;if(!n||n.source?.kind&&n.source.kind!=="user")continue;const a=(n.content??[]).filter(r=>r.type==="text"&&r.text).map(r=>r.text).join(`
|
|
546
546
|
`).trim();if(a&&!a.startsWith("<"))return a.split(`
|
|
547
|
-
`)[0].slice(0,80)}return null}const x9="thoughtdag.atlas.disabledRoots",dy=()=>{try{return new Set(JSON.parse(localStorage.getItem(x9)??"[]"))}catch{return new Set}};function zae(e,t){const n=dy();t?n.add(e):n.delete(e),localStorage.setItem(x9,JSON.stringify([...n]))}const im=new Set;async function Bae(){const e=window.desktopSessions;if(!e)return[];const t=dy(),n=(await e.roots().catch(()=>[])).filter(r=>r.exists&&!t.has(r.key)).map(r=>r.key),a=[];for(const r of n){const o=[...await e.list(r).catch(()=>[])].sort((d,h)=>h.mtime-d.mtime),c=12;for(let d=0;d<o.length;d+=c){const h=await Promise.all(o.slice(d,d+c).map(async m=>{const p=m.rel.endsWith(".zstd")?yE:jae,x=await e.head(r,m.rel,p).catch(()=>"");if(!x)return null;const b=vE(r,m.rel,x,m.mtime,m.size);if(b)return b;const y=await e.head(r,m.rel,yE).catch(()=>"");return y.length>x.length?vE(r,m.rel,y,m.mtime,m.size):null}));for(const m of h)m&&a.push(m)}}im.clear();for(const r of a)im.add(r.sessionId);return a.sort((r,s)=>s.mtime-r.mtime)}function Hae(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 b9="thoughtdag.atlas.watermark",Ao=e=>`${e.rootKey}:${e.rel}`;function hy(){try{return JSON.parse(localStorage.getItem(b9)??"{}")}catch{return{}}}function sm(e){localStorage.setItem(b9,JSON.stringify(e))}function Uae(e){const t=hy(),n=new Map;if(Object.keys(t).length===0)return sm(Object.fromEntries(e.map(s=>[Ao(s),{mtime:s.mtime,size:s.size}]))),n;const a=new Set(e.map(Ao));let r=!1;for(const s of Object.keys(t))a.has(s)||(delete t[s],r=!0);for(const s of e){const o=t[Ao(s)];o?(s.size>o.size||s.mtime>o.mtime+1e3)&&n.set(Ao(s),{kind:"updated",deltaSize:Math.max(0,s.size-o.size)}):n.set(Ao(s),{kind:"new",deltaSize:s.size})}return r&&sm(t),n}function Fae(e){const t=hy();t[Ao(e)]={mtime:e.mtime,size:e.size},sm(t)}function qae(e){const t=hy();for(const n of e)t[Ao(n)]={mtime:n.mtime,size:n.size};sm(t)}const gc=Ao,mx=e=>new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),wE=e=>e>1e6?`${(e/1e6).toFixed(1)} MB`:`${Math.max(1,Math.round(e/1024))} KB`,Wae={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 Vae({roots:e,counts:t,onChanged:n,onClose:a}){const r=zt(),s=dy(),o={"claude-projects":"Claude Code","codex-sessions":"Codex","dsh-sessions":"DeepSeek Harness","pi-sessions":"Pi"},[c,d]=L.useState(null),h=()=>{window.desktopSessions?.commandsStatus?.().then(d).catch(()=>{})};L.useEffect(h,[]);const m={"claude-code":"Claude Code",codex:"Codex",dsh:"DeepSeek Harness",pi:"Pi"},p=x=>u.jsxs("div",{className:"flex items-center gap-3 px-4 py-2.5 border-b border-line last:border-b-0","data-atlas-source":x.key,children:[u.jsx("input",{type:"checkbox",checked:!s.has(x.key),disabled:!x.exists,onChange:b=>{zae(x.key,!b.target.checked),n()},className:"shrink-0"}),u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsx("div",{className:"text-sm text-ink",children:o[x.key]??x.path.split("/").filter(Boolean).pop()}),u.jsx("div",{className:"text-2xs text-ink-faint truncate",children:x.path})]}),u.jsx("span",{className:"text-2xs text-ink-faint shrink-0",children:x.exists?t.get(x.key)??0:r("atlas.rootMissing")}),!x.builtin&&u.jsx("button",{className:"text-ink-faint hover:text-red-500 p-1 rounded transition-colors shrink-0",onClick:()=>{window.desktopSessions.removeRoot(x.key).then(n)},children:u.jsx(Va,{size:14,strokeWidth:1.75})})]},x.key);return u.jsx("div",{className:"absolute inset-0 z-10 bg-ink/20 flex items-center justify-center",onClick:a,children:u.jsxs("div",{className:"bg-surface border border-line rounded-2xl shadow-xl w-[440px] max-h-[80%] overflow-y-auto",onClick:x=>x.stopPropagation(),"data-atlas-sources-dialog":!0,children:[u.jsxs("div",{className:"px-4 pt-3.5 pb-2.5 border-b border-line",children:[u.jsx("div",{className:"text-sm font-semibold text-ink",children:r("atlas.sourcesTitle")}),u.jsx("div",{className:"text-2xs text-ink-muted mt-0.5",children:r("atlas.sourcesHint")})]}),e.filter(x=>x.builtin).map(p),c&&Object.values(c).some(x=>x.state!=="unavailable")&&u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"px-4 pt-3 pb-1.5 text-2xs uppercase tracking-wide text-ink-faint",children:r("atlas.handoffTitle")}),Object.entries(c).filter(([,x])=>x.state!=="unavailable").map(([x,b])=>u.jsxs("div",{className:"flex items-center gap-3 px-4 py-2.5 border-b border-line","data-atlas-handoff":x,"data-handoff-state":b.state,children:[u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsxs("div",{className:"text-sm text-ink flex items-center gap-2",children:[m[x]??x,u.jsx("code",{className:"text-2xs bg-wash border border-line rounded px-1.5 py-px font-mono",children:b.invoke})]}),u.jsx("div",{className:"text-2xs text-ink-faint truncate",children:r(b.state==="installed"?"atlas.handoffOn":b.state==="outdated"?"atlas.handoffOutdated":"atlas.handoffOff")})]}),b.state!=="installed"&&u.jsx("button",{className:"text-2xs bg-accent/10 text-accent hover:bg-accent/20 font-medium px-2.5 py-1 rounded-lg transition-colors shrink-0","data-handoff-install":!0,onClick:()=>{(async()=>{const{confirmDialog:y}=await Tt(async()=>{const{confirmDialog:w}=await Promise.resolve().then(()=>Em);return{confirmDialog:w}},void 0);if(!await y({title:De("atlas.handoffEnableTitle"),message:We(De("confirm.installCommand"),{path:b.dest}),confirmLabel:De(b.state==="outdated"?"atlas.handoffUpdate":"atlas.handoffEnable")}))return;const S=await window.desktopSessions.commandsInstall(x);S.ok?Qe("success",We(De("atlas.handoffInstalled"),{cmd:b.invoke}),8e3):Qe("error",S.error??"install failed"),h()})()},children:r(b.state==="outdated"?"atlas.handoffUpdate":"atlas.handoffEnable")}),(b.state==="installed"||b.state==="outdated")&&u.jsx("button",{className:"text-ink-faint hover:text-red-500 p-1 rounded transition-colors shrink-0",title:r("atlas.handoffRemove"),"data-handoff-remove":!0,onClick:()=>{window.desktopSessions.commandsRemove(x).then(h)},children:u.jsx(Va,{size:14,strokeWidth:1.75})})]},x))]}),e.filter(x=>!x.builtin).map(p),u.jsxs("div",{className:"flex items-center gap-2 px-4 py-3",children:[u.jsxs("button",{onClick:n,className:"flex items-center gap-1.5 text-sm text-ink-muted hover:text-ink border border-line rounded-lg px-2.5 py-1.5 hover:bg-wash transition-colors",children:[u.jsx(or,{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(zS,{size:13,strokeWidth:1.75})," ",r("atlas.addDir")]})]})]})})}function y9({onClose:e,onSwitched:t,focusSessionId:n}){const a=zt(),r=rn(re=>re.projects),s=rn(re=>re.projects.find(qe=>qe.id===re.activeId)?.sourceSession?.sessionId),o=!!window.desktopSessions,[c,d]=L.useState(null),[h,m]=L.useState([]),[p,x]=L.useState(!1),[b,y]=L.useState(window.desktopSessions?null:"canvases"),[k,S]=L.useState(null),[w,C]=L.useState(!1),[T,N]=L.useState(null),[D,O]=L.useState(new Map),[M,_]=L.useState(new Map),[R,G]=L.useState(new Map),[P,V]=L.useState(!1),J=re=>`${re.rootKey}|${re.rel}`,H=re=>G(qe=>{const xe=new Map(qe),$e=J(re);return xe.has($e)?xe.delete($e):xe.set($e,re),xe}),F=re=>r.find(qe=>Yx(qe).includes(re)),[B,W]=L.useState(""),[Q,K]=L.useState(new Set),[U,q]=L.useState("time"),[te,$]=L.useState(!1),[be,Te]=L.useState(!1),[Se,Be]=L.useState(new Map),[X,oe]=L.useState(null);L.useEffect(()=>{window.desktopSessions?.openTargets().then(oe).catch(()=>{})},[]);const ve=L.useMemo(()=>new Map((X?.apps??[]).map(re=>[re.runner,re.name])),[X]),Le=async()=>{x(!0);try{m(await window.desktopSessions?.roots().catch(()=>[])??[]);const re=await Bae();if(d(re),Be(Uae(re)),window.desktopSessions?.codexThreads?.().then(qe=>{qe&&(O(new Map(qe.filter(xe=>xe.name&&xe.sessionId).map(xe=>[xe.sessionId,xe.name]))),_(new Map(qe.filter(xe=>xe.forkedFromId&&xe.sessionId).map(xe=>[xe.sessionId,xe.forkedFromId]))))}).catch(()=>{}),n){const qe=re.find(xe=>xe.sessionId===n);qe&&y(qe.cwd??"")}}finally{x(!1)}};L.useEffect(()=>{Le()},[]),L.useEffect(()=>{let re=!1;const qe=()=>{re||p||(re=!0,setTimeout(()=>{re=!1,Le()},2e3))};return window.addEventListener("td:sessions-changed",qe),()=>window.removeEventListener("td:sessions-changed",qe)},[p]);const Re=L.useCallback(re=>D.get(re.sessionId)??re.title,[D]),Ce=L.useMemo(()=>(c??[]).filter(re=>!Q.has(re.runner)&&(be||!re.subagent)&&(!te||Se.has(gc(re)))&&(!B.trim()||Re(re).toLowerCase().includes(B.trim().toLowerCase()))),[c,Q,B,te,Se,be,Re]),tt=L.useMemo(()=>Hae(Ce),[Ce]),Ve=L.useMemo(()=>[...new Set((c??[]).map(re=>re.runner))].sort(),[c]),ze=L.useMemo(()=>{const re=new Map;for(const qe of c??[])re.set(qe.rootKey,(re.get(qe.rootKey)??0)+1);return re},[c]),bt=b==="canvases"?null:tt.find(re=>(re.cwd??"")===(b??tt[0]?.cwd??""))??tt[0]??null,ct=L.useMemo(()=>{if(!bt)return[];const re=U==="name"?(qe,xe)=>Re(qe).localeCompare(Re(xe)):Wae[U];return[...bt.cards].sort(re)},[bt,U,Re]),Ke=re=>{Fae(re),Be(qe=>{const xe=new Map(qe);return xe.delete(gc(re)),xe})},it=async re=>{if(!k){S(re.rel),Ke(re);try{const{streamRunnerConversation:qe}=await Tt(async()=>{const{streamRunnerConversation:At}=await import("./index-_B6z8_Ff.js");return{streamRunnerConversation:At}},[]),{importOrAppendConversation:xe,shellSessionReader:$e}=await Tt(async()=>{const{importOrAppendConversation:At,shellSessionReader:qt}=await import("./canonical-ChxvAi6N.js");return{importOrAppendConversation:At,shellSessionReader:qt}},[]),ft=await qe($e(re.rootKey,re.rel)),yt=await xe(ft);if(!yt)throw new Error(De("handoff.notASession"));yt.kind==="appended"?Qe("success",We(De("atlas.appended"),{n:yt.turns}),9e3):yt.kind==="mounted"?Qe("success",We(De(yt.mode==="continue"?"atlas.mountedChapter":"atlas.mountedBranch"),{n:yt.turns}),9e3):yt.kind==="opened"?Qe("info",De("atlas.upToDate"),6e3):Qe("success",We(De("toast.importedChats"),{n:1,m:yt.nodeCount}),9e3),e(),t()}catch(qe){Qe("error",We(De("atlas.parseFailed"),{msg:qe instanceof Error?qe.message:String(qe)}))}finally{S(null)}}},vt=async re=>{if(!(k||R.size<2)){S("__merge__");try{const{streamRunnerConversation:qe}=await Tt(async()=>{const{streamRunnerConversation:At}=await import("./index-_B6z8_Ff.js");return{streamRunnerConversation:At}},[]),{mergeSessionsIntoProject:xe,shellSessionReader:$e}=await Tt(async()=>{const{mergeSessionsIntoProject:At,shellSessionReader:qt}=await import("./canonical-ChxvAi6N.js");return{mergeSessionsIntoProject:At,shellSessionReader:qt}},[]),ft=[];for(const At of R.values())ft.push(await qe($e(At.rootKey,At.rel))),Ke(At);const yt=await xe(ft,re);if(!yt)throw new Error(De("handoff.notASession"));Qe("success",We(De("atlas.merged"),{n:yt.mounted}),1e4),yt.skipped>0&&Qe("info",We(De("atlas.mergeSkippedInfo"),{n:yt.skipped}),8e3),G(new Map),e(),t()}catch(qe){Qe("error",We(De("atlas.parseFailed"),{msg:qe instanceof Error?qe.message:String(qe)}))}finally{S(null)}}},He=async re=>{const qe=rn.getState().projects.find(ft=>ft.sourceSession?.sessionId===re.sessionId);if(!qe||k)return;const{confirmDialog:xe}=await Tt(async()=>{const{confirmDialog:ft}=await Promise.resolve().then(()=>Em);return{confirmDialog:ft}},void 0);if(await xe({title:De("confirm.recastTitle"),message:We(De("confirm.recast"),{name:qe.name}),confirmLabel:De("confirm.recastTitle"),danger:!0})){S(re.rel);try{const{streamRunnerConversation:ft}=await Tt(async()=>{const{streamRunnerConversation:Yt}=await import("./index-_B6z8_Ff.js");return{streamRunnerConversation:Yt}},[]),{importOrAppendConversation:yt,shellSessionReader:At}=await Tt(async()=>{const{importOrAppendConversation:Yt,shellSessionReader:kn}=await import("./canonical-ChxvAi6N.js");return{importOrAppendConversation:Yt,shellSessionReader:kn}},[]),qt=await ft(At(re.rootKey,re.rel));if(!qt)throw new Error(De("handoff.notASession"));const{deleteProject:hn}=await Tt(async()=>{const{deleteProject:Yt}=await Promise.resolve().then(()=>Fr);return{deleteProject:Yt}},void 0);if(await hn(qe.id),!await yt(qt))throw new Error(De("handoff.notASession"));Qe("success",De("atlas.recastDone"),8e3),e(),t()}catch(ft){Qe("error",We(De("atlas.parseFailed"),{msg:ft instanceof Error?ft.message:String(ft)}))}finally{S(null)}}},It=async(re,qe)=>{const xe=await window.desktopSessions.openInCli(re.runner,re.cwd,re.sessionId,qe).catch(()=>({opened:!1,via:"",command:""}));xe.opened&&xe.via==="app"?(await navigator.clipboard.writeText(re.sessionId).catch(()=>{}),Qe("success",De("atlas.appOpened"),9e3)):xe.opened?Qe("success",De("atlas.opened")):xe.command&&(await navigator.clipboard.writeText(xe.command).catch(()=>{}),Qe("info",De("atlas.cmdCopied"),9e3))};return Qa.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")}),Se.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:We(a("atlas.changesSummary"),{n:[...Se.values()].filter(re=>re.kind==="new").length,m:[...Se.values()].filter(re=>re.kind==="updated").length})}),u.jsx("button",{className:"text-ink-faint hover:text-ink underline decoration-dotted transition-colors",onClick:()=>{qae(c??[]),Be(new Map)},"data-atlas-mark-all":!0,children:a("atlas.markAllSeen")})]})]}),o&&X&&X.terminals.length>0&&u.jsxs("label",{className:"flex items-center gap-1.5 text-sm text-ink-muted border border-line rounded-lg px-2.5 py-1.5 cursor-pointer",title:a("atlas.terminalChoice"),children:[u.jsx(Oo,{size:14,strokeWidth:1.75}),u.jsxs("select",{value:X.prefs.terminal,onChange:re=>{const qe=re.target.value;if(qe==="__add__"){window.desktopSessions?.addTerminal().then(()=>window.desktopSessions?.openTargets().then(oe));return}window.desktopSessions?.setOpenPrefs({terminal:qe}).then(xe=>oe($e=>$e&&{...$e,prefs:xe}))},className:"bg-transparent focus:outline-none text-sm text-ink cursor-pointer","data-atlas-terminal-select":!0,children:[X.terminals.map(re=>u.jsx("option",{value:re.id,children:re.name},re.id)),X.canAddCustom&&u.jsx("option",{value:"__add__",children:a("atlas.otherTerminal")})]})]}),o&&u.jsxs("button",{onClick:()=>C(!0),className:"flex items-center gap-1.5 text-sm text-ink-muted hover:text-ink border border-line rounded-lg px-2.5 py-1.5 hover:bg-wash transition-colors","data-atlas-sources":!0,children:[u.jsx(zS,{size:14,strokeWidth:1.75})," ",a("atlas.sources")]}),o&&u.jsxs("button",{onClick:()=>{Le()},disabled:p,className:"flex items-center gap-1.5 text-sm text-ink-muted hover:text-ink border border-line rounded-lg px-2.5 py-1.5 hover:bg-wash transition-colors disabled:opacity-60","data-atlas-refresh":!0,children:[p?u.jsx(Un,{size:14,className:"animate-spin"}):u.jsx(or,{size:14,strokeWidth:1.75}),a(p?"atlas.scanning":"atlas.refresh")]}),u.jsx("button",{onClick:e,className:"text-ink-faint hover:text-ink p-1.5 rounded-lg hover:bg-wash transition-colors","data-atlas-close":!0,children:u.jsx(mn,{size:18,strokeWidth:1.75})})]}),u.jsxs("div",{className:"flex-1 flex min-h-0",children:[u.jsxs("div",{className:"w-[260px] border-r border-line overflow-y-auto py-2 shrink-0",children:[u.jsx("div",{className:"px-4 py-1 text-2xs uppercase tracking-wide text-ink-faint",children:a("atlas.recent")}),r.filter(re=>!re.archived).sort((re,qe)=>qe.updatedAt-re.updatedAt).slice(0,6).map(re=>u.jsxs("button",{onClick:()=>{e(),Ms(re.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":re.id,children:[re.sourceSession?.sessionId?u.jsx("span",{className:"text-2xs font-mono border border-line rounded px-1 py-px shrink-0 text-ink-faint",children:re.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:re.name})]},re.id)),u.jsx("div",{className:"border-t border-line mt-2 pt-2 px-4 py-1 text-2xs uppercase tracking-wide text-ink-faint",children:a("atlas.folders")}),!o&&u.jsx("div",{className:"px-4 py-2 text-xs text-ink-faint",children:a("atlas.webNoScan")}),o&&c===null&&u.jsxs("div",{className:"px-4 py-2 text-sm text-ink-faint flex items-center gap-2",children:[u.jsx(Un,{size:14,className:"animate-spin"})," ",a("atlas.scanning")]}),o&&c!==null&&tt.length===0&&u.jsx("div",{className:"px-4 py-2 text-xs text-ink-faint",children:a("atlas.empty")}),tt.map(re=>{const qe=re.cwd??"",xe=b!=="canvases"&&bt===re;return u.jsxs("button",{onClick:()=>y(qe),className:`w-full text-left px-4 py-2 flex items-center gap-2 transition-colors ${xe?"bg-accent/5 text-accent":"text-ink hover:bg-wash"}`,"data-atlas-folder":re.name||"unfiled",children:[xe?u.jsx(Pc,{size:15,strokeWidth:1.75,className:"shrink-0"}):u.jsx(fz,{size:15,strokeWidth:1.75,className:"shrink-0 text-ink-faint"}),u.jsx("span",{className:"flex-1 truncate text-sm",children:re.name||a("atlas.unfiled")}),(()=>{const $e=re.cards.filter(ft=>Se.has(gc(ft))).length;return $e>0?u.jsxs("span",{className:"text-2xs text-accent shrink-0","data-atlas-folder-changes":!0,children:["+",$e]}):null})(),u.jsx("span",{className:"text-2xs text-ink-faint shrink-0",children:re.cards.length})]},qe)}),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(re=>!re.archived).sort((re,qe)=>qe.updatedAt-re.updatedAt).map(re=>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(),Ms(re.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:re.name}),u.jsxs("div",{className:"text-2xs text-ink-faint mt-0.5 flex items-center gap-1.5",children:[u.jsx("span",{children:mx(re.updatedAt)}),!!re.sourceSession?.sessionId&&u.jsx("span",{className:"font-mono border border-line rounded px-1 py-px",children:re.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:qe=>{qe.stopPropagation(),qf(re.id,!0)},"data-atlas-archive":!0,children:u.jsx(zo,{size:15,strokeWidth:1.75})}),!!re.sourceSession&&Yx(re).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:[re.sourceSession.sessionId&&u.jsxs("span",{children:["◉ ",re.sourceSession.runner," ",re.sourceSession.sessionId.slice(0,8)," · ",We(a("atlas.turnsN"),{n:re.sourceSession.importedCount})]}),(re.sourceSession.chapters??[]).map(qe=>u.jsxs("span",{children:["↳ ",qe.runner," ",qe.sessionId.slice(0,8)," · ",We(a("atlas.turnsN"),{n:qe.importedCount})]},qe.sessionId)),(re.sourceSession.branches??[]).map(qe=>u.jsxs("span",{children:["⑂ ",qe.runner," ",qe.sessionId.slice(0,8)," · ",We(a("atlas.turnsN"),{n:qe.importedCount})]},qe.sessionId))]})]},re.id)),r.some(re=>re.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:We(a("atlas.archivedGroup"),{n:r.filter(re=>re.archived).length})}),u.jsx("div",{className:"space-y-1.5 mt-1.5",children:r.filter(re=>re.archived).sort((re,qe)=>qe.updatedAt-re.updatedAt).map(re=>u.jsxs("button",{title:a("atlas.restoreOpen"),onClick:()=>{qf(re.id,!1).then(()=>{e(),Ms(re.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:re.name}),!!re.sourceSession?.sessionId&&u.jsx("span",{className:"text-2xs font-mono border border-line rounded px-1 py-px shrink-0 text-ink-faint",children:re.sourceSession.runner})]}),u.jsx("div",{className:"text-2xs text-ink-faint mt-0.5",children:mx(re.updatedAt)})]},re.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(zf,{size:13,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),u.jsx("input",{value:B,onChange:re=>W(re.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})]}),Ve.map(re=>u.jsx("button",{onClick:()=>K(qe=>{const xe=new Set(qe);return xe.has(re)?xe.delete(re):xe.add(re),xe}),className:`text-2xs font-mono border rounded-lg px-2 py-1 transition-colors ${Q.has(re)?"border-line text-ink-faint line-through":"border-accent/40 text-accent bg-accent/5"}`,"data-atlas-runner-toggle":re,children:re},re)),Se.size>0&&u.jsx("button",{onClick:()=>$(re=>!re),className:`text-2xs border rounded-lg px-2 py-1 transition-colors ${te?"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(re=>re.subagent)&&u.jsx("button",{onClick:()=>Te(re=>!re),className:`text-2xs border rounded-lg px-2 py-1 transition-colors ${be?"border-accent text-accent bg-accent/5":"border-line text-ink-faint hover:text-ink"}`,"data-atlas-show-sub":!0,children:a("atlas.showSub")}),u.jsxs("button",{onClick:()=>q(re=>({time:"name",name:"size",size:"runner",runner:"time"})[re]),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(dP,{size:12,strokeWidth:1.75}),a(`atlas.sort${U[0].toUpperCase()}${U.slice(1)}`)]})]}),bt?u.jsxs(u.Fragment,{children:[bt.cwd&&u.jsxs("div",{className:"text-2xs text-ink-faint mb-3 truncate",children:[bt.cwd," · ",We(a("atlas.sessions"),{n:bt.cards.length})]}),u.jsx("div",{className:"space-y-1.5",children:ct.map(re=>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(J(re))?"border-accent/60 bg-accent/5":"border-line"}`,onClick:()=>{it(re)},"data-atlas-session":re.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:Re(re)}),M.has(re.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(re.sessionId)}`,"data-atlas-fork":!0,children:"⑂"}),Se.get(gc(re))?.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")}),Se.get(gc(re))?.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:["+",wE(Se.get(gc(re)).deltaSize)]}),re.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 qe=F(re.sessionId);return qe?u.jsx("span",{className:"text-2xs text-ink-faint border border-line rounded px-1 py-px shrink-0",title:qe.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:re.runner}),u.jsx("span",{children:mx(re.mtime)}),u.jsx("span",{children:wE(re.size)})]})]}),k===re.rel?u.jsx(Un,{size:16,className:"animate-spin text-accent shrink-0"}):u.jsxs("div",{className:`${R.has(J(re))?"":"opacity-0 group-hover:opacity-100"} transition-opacity flex items-center gap-1 shrink-0`,children:[!F(re.sessionId)&&!!re.sessionId&&u.jsx("button",{title:a("atlas.pickForMerge"),className:`p-1.5 rounded transition-colors ${R.has(J(re))?"text-accent":"text-ink-faint hover:text-accent"}`,onClick:qe=>{qe.stopPropagation(),H(re)},"data-atlas-pick":R.has(J(re))?"on":"off",children:R.has(J(re))?u.jsx(EB,{size:16,strokeWidth:1.75}):u.jsx(Kb,{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(Az,{size:16,strokeWidth:1.75})}),r.some(qe=>qe.sourceSession?.sessionId===re.sessionId)&&u.jsx("button",{title:a("atlas.recast"),className:"text-ink-faint hover:text-red-500 p-1.5 rounded transition-colors",onClick:qe=>{qe.stopPropagation(),He(re)},"data-atlas-recast":!0,children:u.jsx(iB,{size:16,strokeWidth:1.75})}),!F(re.sessionId)&&u.jsx("button",{title:a("atlas.mountTo"),className:"text-ink-faint hover:text-accent p-1.5 rounded transition-colors",onClick:qe=>{qe.stopPropagation(),N(re)},"data-atlas-mount":!0,children:u.jsx(Do,{size:16,strokeWidth:1.75})}),ve.has(re.runner)&&u.jsx("button",{title:We(a("atlas.openApp"),{name:ve.get(re.runner)}),className:"text-ink-faint hover:text-accent p-1.5 rounded transition-colors",onClick:qe=>{qe.stopPropagation(),It(re,"app")},"data-atlas-open-app":!0,children:u.jsx(oP,{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:qe=>{qe.stopPropagation(),It(re,"terminal")},"data-atlas-open-cli":!0,children:u.jsx(Oo,{size:16,strokeWidth:1.75})})]})]},re.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&&!P&&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:We(a("atlas.mergeSelected"),{n:R.size})}),k==="__merge__"?u.jsx(Un,{size:15,className:"animate-spin text-accent"}):u.jsxs(u.Fragment,{children:[u.jsx("button",{className:"text-xs bg-accent hover:bg-accent-strong text-white font-medium px-3 py-1.5 rounded-lg transition-colors whitespace-nowrap",onClick:()=>{vt()},"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:()=>V(!0),"data-atlas-merge-into":!0,children:a("atlas.mergeInto")})]}),u.jsx("button",{className:"text-ink-faint hover:text-ink p-1",onClick:()=>G(new Map),title:a("common.cancel"),children:u.jsx(mn,{size:14,strokeWidth:1.75})})]}),(T||P)&&u.jsx("div",{className:"absolute inset-0 z-10 bg-ink/20 flex items-center justify-center",onClick:()=>{N(null),V(!1)},children:u.jsxs("div",{className:"bg-surface border border-line rounded-2xl shadow-xl w-[400px] max-h-[70%] overflow-y-auto",onClick:re=>re.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(P?"atlas.mergeInto":"atlas.mountTo")}),u.jsx("div",{className:"text-2xs text-ink-muted mt-0.5",children:a(P?"atlas.mergeSelected":"atlas.mountHint").replace("{n}",String(R.size))})]}),r.filter(re=>!re.archived&&re.kind!=="paradigm").sort((re,qe)=>qe.updatedAt-re.updatedAt).map(re=>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(P){V(!1),vt(re.id);return}const qe=T;N(null),(async()=>{S(qe.rel);try{const{streamRunnerConversation:xe}=await Tt(async()=>{const{streamRunnerConversation:qt}=await import("./index-_B6z8_Ff.js");return{streamRunnerConversation:qt}},[]),{mountConversationToProject:$e,shellSessionReader:ft}=await Tt(async()=>{const{mountConversationToProject:qt,shellSessionReader:hn}=await import("./canonical-ChxvAi6N.js");return{mountConversationToProject:qt,shellSessionReader:hn}},[]),yt=await xe(ft(qe.rootKey,qe.rel)),At=await $e(yt,re.id);if(!At)throw new Error(De("handoff.notASession"));Qe("success",We(De("atlas.mountedChapter"),{n:At.kind==="mounted"||At.kind==="appended"?At.turns:0}),9e3),e(),t()}catch(xe){Qe("error",We(De("atlas.parseFailed"),{msg:xe instanceof Error?xe.message:String(xe)}))}finally{S(null)}})()},children:re.name},re.id))]})}),w&&u.jsx(Vae,{roots:h,counts:ze,onChanged:()=>{Le()},onClose:()=>C(!1)})]})}),document.body)}function Gae({conversations:e,onClose:t,onDone:n}){const a=zt(),[r,s]=L.useState(new Set),[o,c]=L.useState(!1),d=p=>{s(x=>{const b=new Set(x);return b.has(p)?b.delete(p):b.add(p),b})},h=r.size===e.length,m=async()=>{r.size===0||o||(c(!0),await wF([...r].sort((p,x)=>p-x).map(p=>e[p])),c(!1),n())};return u.jsx("div",{className:"fixed inset-0 z-50 bg-ink/30 backdrop-blur-sm flex items-center justify-center p-6",onClick:t,children:u.jsxs("div",{className:"bg-card border border-line rounded-2xl shadow-2xl w-full max-w-lg max-h-[80vh] flex flex-col",onClick:p=>p.stopPropagation(),children:[u.jsxs("div",{className:"px-6 py-4 border-b border-line flex items-start justify-between gap-4",children:[u.jsxs("div",{children:[u.jsx("h2",{className:"text-base font-semibold text-ink",children:a("import.title")}),u.jsx("p",{className:"text-xs text-ink-muted mt-1 leading-relaxed",children:a("import.subtitle")})]}),u.jsx("button",{onClick:t,className:"text-ink-faint hover:text-ink transition-colors shrink-0 mt-0.5",children:u.jsx(mn,{size:16,strokeWidth:1.75})})]}),u.jsx("div",{className:"px-6 py-2 border-b border-line/60",children:u.jsxs("label",{className:"flex items-center gap-2 text-xs text-ink-muted cursor-pointer select-none py-1",children:[u.jsx("input",{type:"checkbox",checked:h,onChange:()=>s(h?new Set:new Set(e.map((p,x)=>x))),className:"rounded border-line text-accent focus:ring-accent w-3.5 h-3.5"}),a("import.selectAll"),u.jsx("span",{className:"ml-auto text-2xs text-ink-faint uppercase tracking-wider",children:e[0]?.source})]})}),u.jsx("ul",{className:"flex-1 overflow-y-auto py-1",children:e.map((p,x)=>u.jsx("li",{children:u.jsxs("label",{className:"flex items-center gap-3 px-6 py-2 hover:bg-wash transition-colors cursor-pointer select-none",children:[u.jsx("input",{type:"checkbox",checked:r.has(x),onChange:()=>d(x),className:"rounded border-line text-accent focus:ring-accent w-3.5 h-3.5 shrink-0"}),u.jsx(PS,{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:We(a("import.messages"),{n:p.messageCount})})]})},x))}),u.jsxs("div",{className:"px-6 py-4 border-t border-line flex justify-end gap-2",children:[u.jsx("button",{onClick:t,className:"text-xs text-ink-muted hover:text-ink px-4 py-2 rounded-lg hover:bg-wash transition-colors",children:a("common.cancel")}),u.jsx("button",{onClick:()=>{m()},disabled:r.size===0||o,className:"text-xs bg-accent hover:bg-accent-strong text-white px-5 py-2 rounded-lg transition-colors disabled:opacity-30",children:o?"…":We(a("import.confirm"),{n:r.size})})]})]})})}function $ae(e){const t=Date.now()-e,n=Math.floor(t/6e4);if(n<1)return De("switcher.justNow");if(n<60)return We(De("switcher.minAgo"),{n});const a=Math.floor(n/60);if(a<24)return We(De("switcher.hourAgo"),{n:a});const r=Math.floor(a/24);return r<30?We(De("switcher.dayAgo"),{n:r}):new Date(e).toLocaleDateString(Ra.getState().lang==="zh"?"zh-CN":"en-US")}function Yae({onSwitched:e}){const t=zt(),n=rn(_=>_.projects),a=rn(_=>_.activeId),r=rn(_=>_.switching),s=n.find(_=>_.id===a)?.kind==="paradigm",[o,c]=L.useState(!1),[d,h]=L.useState(null),[m,p]=L.useState(!1),[x,b]=L.useState(void 0),[y,k]=L.useState(null),[S,w]=L.useState(""),C=L.useRef(null),T=L.useRef(null),N=n.find(_=>_.id===a),D=n.filter(_=>!_.archived).sort((_,R)=>R.updatedAt-_.updatedAt).slice(0,7),O=async _=>{const{canvasUniqueness:R}=await Tt(async()=>{const{canvasUniqueness:J}=await import("./canonical-ChxvAi6N.js");return{canvasUniqueness:J}},[]),G=await R(_.id),P=G==="native"?"confirm.deleteNative":G==="diverged-mirror"?"confirm.deleteDiverged":"confirm.deletePristine";await _s({title:De("confirm.deleteCanvasTitle"),message:We(De(P),{name:_.name}),confirmLabel:De("common.delete"),danger:G!=="pristine-mirror"})&&I7(_.id).then(e)};L.useEffect(()=>{if(!o)return;const _=R=>{T.current?.contains(R.target)||c(!1)};return window.addEventListener("mousedown",_),()=>window.removeEventListener("mousedown",_)},[o]);const M=async _=>{c(!1),await Ms(_),e(),Tt(()=>import("./canonical-ChxvAi6N.js"),[]).then(R=>R.unsubscribeOrphanedSessions()),Tt(()=>import("./live-mirror-C9sTXAvv.js"),[]).then(R=>R.sweepRecentSessions())};return u.jsxs("div",{ref:T,className:"absolute top-4 left-4 z-20",children:[u.jsxs("div",{className:"flex items-center gap-1.5",children:[u.jsxs("button",{onClick:()=>c(!o),disabled:r,className:"bg-card/90 backdrop-blur border border-line rounded-xl px-3.5 py-2 shadow-sm hover:bg-wash transition-colors flex items-center gap-2 text-sm text-ink max-w-[240px] disabled:opacity-60",children:[r?u.jsx(Un,{size:16,strokeWidth:1.75,className:"animate-spin shrink-0 text-accent"}):s?u.jsx(KP,{size:16,strokeWidth:1.75,className:"shrink-0 text-accent"}):u.jsx(Pc,{size:16,strokeWidth:1.75,className:"shrink-0 text-ink-muted"}),u.jsx("span",{className:"truncate font-medium",children:N?.name??"…"}),u.jsx(Cl,{size:14,strokeWidth:1.75,className:"shrink-0 text-ink-faint"})]}),!!N?.sourceSession?.sessionId&&(()=>{const _=im.size>0&&!im.has(N.sourceSession.sessionId);return u.jsxs("button",{title:_?De("switcher.mirrorBadgeGone"):We(De("switcher.mirrorBadge"),{runner:N.sourceSession.runner}),onClick:()=>{b(N.sourceSession.sessionId),p(!0)},className:`bg-card/90 backdrop-blur border border-line rounded-xl px-2 py-2 shadow-sm hover:bg-wash transition-colors text-2xs font-mono flex items-center gap-1 ${_?"text-ink-faint/50 line-through decoration-1":"text-ink-faint hover:text-accent"}`,"data-twin-badge":_?"unreachable":"live",children:["⇄ ",N.sourceSession.runner]})})()]}),o&&u.jsxs("div",{className:"mt-1.5 bg-card border border-line rounded-xl shadow-lg py-1.5 w-[320px] animate-fade-in",children:[u.jsx("div",{className:"max-h-[320px] overflow-y-auto",children:D.map(_=>u.jsx("div",{className:`group flex items-center gap-1 px-3 py-2 hover:bg-wash cursor-pointer transition-colors ${_.id===a?"bg-accent/5":""}`,onClick:()=>{y!==_.id&&_.id!==a&&M(_.id)},children:y===_.id?u.jsx("input",{autoFocus:!0,value:S,onChange:R=>w(R.target.value),onClick:R=>R.stopPropagation(),onKeyDown:R=>{R.key==="Enter"&&!Xa(R)&&S.trim()&&(M7(_.id,S.trim()),k(null)),R.key==="Escape"&&k(null)},onBlur:()=>k(null),className:"flex-1 text-sm text-ink border border-accent/40 rounded-lg px-2 py-1 bg-surface focus:outline-none"}):u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsx("div",{className:`text-sm truncate ${_.id===a?"text-accent font-medium":"text-ink"}`,children:_.name}),u.jsxs("div",{className:"text-2xs text-ink-faint flex items-center gap-1.5",children:[u.jsx("span",{children:$ae(_.updatedAt)}),!!_.sourceSession?.sessionId&&u.jsx("span",{className:"font-mono border border-line rounded px-1 py-px","data-mirror-mark":!0,children:_.sourceSession.runner})]})]}),u.jsx("button",{title:t("switcher.rename"),className:"opacity-0 group-hover:opacity-100 text-ink-faint hover:text-ink p-1 rounded transition-all shrink-0",onClick:R=>{R.stopPropagation(),k(_.id),w(_.name)},children:u.jsx(Wc,{size:14,strokeWidth:1.75})}),u.jsx("button",{title:t("common.delete"),className:"opacity-0 group-hover:opacity-100 text-ink-faint hover:text-red-500 p-1 rounded transition-all shrink-0",onClick:R=>{R.stopPropagation(),O(_)},children:u.jsx(Va,{size:14,strokeWidth:1.75})}),u.jsx("button",{title:t("switcher.archive"),className:"opacity-0 group-hover:opacity-100 text-ink-faint hover:text-amber-600 p-1 rounded transition-all shrink-0",onClick:R=>{R.stopPropagation(),qf(_.id,!0).then(e)},"data-archive-canvas":!0,children:u.jsx(zo,{size:14,strokeWidth:1.75})})]})},_.id))}),u.jsxs("div",{className:"border-t border-line mt-1 pt-1",children:[u.jsxs("button",{onClick:()=>{c(!1),Nm().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(wm,{size:15,strokeWidth:1.75})," ",t("switcher.newCanvas")]}),u.jsxs("button",{onClick:()=>C.current?.click(),className:"w-full text-left px-3 py-2 text-sm text-ink-muted hover:bg-wash transition-colors flex items-center gap-2",children:[u.jsx(LB,{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(zz,{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(or,{size:15,strokeWidth:1.75})," ",t("update.checkMenu"),u.jsxs("span",{className:"ml-auto text-2xs text-ink-faint",children:["v",new URLSearchParams(window.location.search).get("dv")]})]}),u.jsx("input",{ref:C,type:"file",accept:".json,.jsonl,application/json",className:"hidden",onChange:_=>{const R=_.target.files?.[0];R&&yF(R).then(G=>{G.kind==="own"&&G.ok?(c(!1),e()):G.kind==="chat"&&(c(!1),h(G.conversations))}).catch(G=>{Qe("error",We(De("toast.importFailedGeneric"),{msg:G instanceof Error?G.message:String(G)}))}),_.target.value=""}})]})]}),d&&u.jsx(Gae,{conversations:d,onClose:()=>h(null),onDone:()=>{h(null),e()}}),m&&u.jsx(y9,{onClose:()=>{p(!1),b(void 0)},onSwitched:e,focusSessionId:x})]})}const Kae="JVBERi0xLjQKMSAwIG9iago8PCAvVHlwZSAvQ2F0YWxvZyAvUGFnZXMgMiAwIFIgPj4KZW5kb2JqCjIgMCBvYmoKPDwgL1R5cGUgL1BhZ2VzIC9LaWRzIFszIDAgUiA0IDAgUl0gL0NvdW50IDIgPj4KZW5kb2JqCjMgMCBvYmoKPDwgL1R5cGUgL1BhZ2UgL1BhcmVudCAyIDAgUiAvTWVkaWFCb3ggWzAgMCA1OTUgODQyXSAvQ29udGVudHMgNSAwIFIgL1Jlc291cmNlcyA8PCAvRm9udCA8PCAvRjEgNyAwIFIgL0YyIDggMCBSID4+ID4+ID4+CmVuZG9iago0IDAgb2JqCjw8IC9UeXBlIC9QYWdlIC9QYXJlbnQgMiAwIFIgL01lZGlhQm94IFswIDAgNTk1IDg0Ml0gL0NvbnRlbnRzIDYgMCBSIC9SZXNvdXJjZXMgPDwgL0ZvbnQgPDwgL0YxIDcgMCBSIC9GMiA4IDAgUiA+PiA+PiA+PgplbmRvYmoKNSAwIG9iago8PCAvTGVuZ3RoIDExMTIgPj4Kc3RyZWFtCkJUCi9GMiAxOSBUZiAxIDAgMCAxIDY0IDcyNS4wIFRtIChXaHkgU2F2ZWQgQXJ0aWNsZXMgU3RheSBVbnJlYWQpIFRqCi9GMSAxMSBUZiAxIDAgMCAxIDY0IDcwOC4wIFRtIChBIHNob3J0IGJyaWVmIG9uIGRpZ2l0YWwgaG9hcmRpbmcgYW5kIHRoZSBjb2xsZWN0b3IncyBmYWxsYWN5KSBUagovRjIgMTMgVGYgMSAwIDAgMSA2NCA2NjkuMCBUbSAoMS4gVGhlIHBoZW5vbWVub24pIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNjUxLjUgVG0gKFJlYWQtaXQtbGF0ZXIgc2VydmljZXMgcmVwb3J0IHRoYXQgbW9zdCBzYXZlZCBpdGVtcyBhcmUgbmV2ZXIpIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNjM0LjAgVG0gKHJlb3BlbmVkLiBBY3Jvc3MgcHVibGlzaGVkIHVzYWdlIHN0dWRpZXMsIHRoZSBzaGFyZSBvZiBzYXZlZCkgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA2MTYuNSBUbSAoYXJ0aWNsZXMgdGhhdCBnZXQgYSBzZWNvbmQgdmlzaXQgaXMgc21hbGwsIGFuZCBjb21wbGV0aW9uIHJhdGVzKSBUagovRjEgMTEuNSBUZiAxIDAgMCAxIDY0IDU5OS4wIFRtIChhcmUgc21hbGxlciBzdGlsbC4gVGhlIGFyY2hpdmUgZ3Jvd3M7IHRoZSByZWFkaW5nIGRvZXMgbm90LikgVGoKL0YyIDEzIFRmIDEgMCAwIDEgNjQgNTYwLjAgVG0gKDIuIFRoZSBjb2xsZWN0b3IncyBmYWxsYWN5KSBUagovRjEgMTEuNSBUZiAxIDAgMCAxIDY0IDU0Mi41IFRtIChDb2xsZWN0aW5nIHByb2R1Y2VzIGFuIGltbWVkaWF0ZSBzZW5zZSBvZiBwcm9ncmVzcyB3aGlsZSB0aGUpIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNTI1LjAgVG0gKHVuZGVyc3RhbmRpbmcgaXQgcHJvbWlzZXMgaXMgZGVmZXJyZWQuIFNhdmluZyBhIHRleHQgZmVlbHMgbGlrZSkgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA1MDcuNSBUbSAoYSBmaXJzdCBzdGVwIG9mIHJlYWRpbmcgaXQsIGJ1dCBubyBwYXJ0IG9mIHRoZSByZWFkaW5nIGhhcykgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA0OTAuMCBUbSAoaGFwcGVuZWQuKSBUagovRjIgMTEuNSBUZiAxIDAgMCAxIDY0IDQ3Mi41IFRtIChUaGUgYWN0IG9mIHNhdmluZyBpcyBtaXN0YWtlbiBmb3IgdGhlIGFjdCBvZiBsZWFybmluZy4pIFRqCkVUCmVuZHN0cmVhbQplbmRvYmoKNiAwIG9iago8PCAvTGVuZ3RoIDkwOCA+PgpzdHJlYW0KQlQKL0YyIDEzIFRmIDEgMCAwIDEgNjQgNzI1LjAgVG0gKDMuIFdoeSBpdCBwZXJzaXN0cykgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA3MDcuNSBUbSAoVGhlIGNvc3RzIGFyZSBhc3ltbWV0cmljOiBzYXZpbmcgdGFrZXMgb25lIHNlY29uZCBhbmQgcGF5cyBvdXQpIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNjkwLjAgVG0gKGEgc21hbGwgcmV3YXJkIG5vdzsgcmVhZGluZyB0YWtlcyBhbiBob3VyIGFuZCBwYXlzIG91dCBsYXRlci4pIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNjcyLjUgVG0gKEhhYml0cyBmb2xsb3cgdGhlIGNoZWFwZXIgbG9vcCwgc28gbGlicmFyaWVzIGluZmxhdGUgYnkgZGVmYXVsdC4pIFRqCi9GMiAxMyBUZiAxIDAgMCAxIDY0IDYzMy41IFRtICg0LiBXaGF0IGhlbHBzKSBUagovRjEgMTEuNSBUZiAxIDAgMCAxIDY0IDYxNi4wIFRtIChJbnRlcnZlbnRpb25zIHRoYXQgd29yayBtb3ZlIHByb2Nlc3NpbmcgdG8gdGhlIG1vbWVudCBvZiBjYXB0dXJlOikgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA1OTguNSBUbSAod3JpdGUgb25lIGxpbmUgaW4geW91ciBvd24gd29yZHMgYWJvdXQgd2h5IHRoZSBpdGVtIG1hdHRlcnMsIGFuZCkgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA1ODEuMCBUbSAoc2NoZWR1bGUgYSByZXZpZXcgcGFzcyBpbnN0ZWFkIG9mIHRydXN0aW5nIHRoZSBhcmNoaXZlIHRvKSBUagovRjEgMTEuNSBUZiAxIDAgMCAxIDY0IDU2My41IFRtIChyZXN1cmZhY2UgaXQuKSBUagovRjEgMTEuNSBUZiAxIDAgMCAxIDY0IDUzMi4wIFRtIChBIHNtYWxsZXIgbGlicmFyeSB0aGF0IGdldHMgcHJvY2Vzc2VkIGJlYXRzIGEgY29tcGxldGUgb25lIHRoYXQpIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNTE0LjUgVG0gKGRvZXMgbm90LikgVGoKRVQKZW5kc3RyZWFtCmVuZG9iago3IDAgb2JqCjw8IC9UeXBlIC9Gb250IC9TdWJ0eXBlIC9UeXBlMSAvQmFzZUZvbnQgL0hlbHZldGljYSA+PgplbmRvYmoKOCAwIG9iago8PCAvVHlwZSAvRm9udCAvU3VidHlwZSAvVHlwZTEgL0Jhc2VGb250IC9IZWx2ZXRpY2EtQm9sZCA+PgplbmRvYmoKeHJlZgowIDkKMDAwMDAwMDAwMCA2NTUzNSBmIAowMDAwMDAwMDA5IDAwMDAwIG4gCjAwMDAwMDAwNTggMDAwMDAgbiAKMDAwMDAwMDEyMSAwMDAwMCBuIAowMDAwMDAwMjU3IDAwMDAwIG4gCjAwMDAwMDAzOTMgMDAwMDAgbiAKMDAwMDAwMTU1NyAwMDAwMCBuIAowMDAwMDAyNTE2IDAwMDAwIG4gCjAwMDAwMDI1ODYgMDAwMDAgbiAKdHJhaWxlcgo8PCAvU2l6ZSA5IC9Sb290IDEgMCBSID4+CnN0YXJ0eHJlZgoyNjYxCiUlRU9G",Xae=`<!-- tdag-page:1 -->
|
|
547
|
+
`)[0].slice(0,80)}return null}const x9="thoughtdag.atlas.disabledRoots",dy=()=>{try{return new Set(JSON.parse(localStorage.getItem(x9)??"[]"))}catch{return new Set}};function zae(e,t){const n=dy();t?n.add(e):n.delete(e),localStorage.setItem(x9,JSON.stringify([...n]))}const im=new Set;async function Bae(){const e=window.desktopSessions;if(!e)return[];const t=dy(),n=(await e.roots().catch(()=>[])).filter(r=>r.exists&&!t.has(r.key)).map(r=>r.key),a=[];for(const r of n){const o=[...await e.list(r).catch(()=>[])].sort((d,h)=>h.mtime-d.mtime),c=12;for(let d=0;d<o.length;d+=c){const h=await Promise.all(o.slice(d,d+c).map(async m=>{const p=m.rel.endsWith(".zstd")?yE:jae,x=await e.head(r,m.rel,p).catch(()=>"");if(!x)return null;const b=vE(r,m.rel,x,m.mtime,m.size);if(b)return b;const y=await e.head(r,m.rel,yE).catch(()=>"");return y.length>x.length?vE(r,m.rel,y,m.mtime,m.size):null}));for(const m of h)m&&a.push(m)}}im.clear();for(const r of a)im.add(r.sessionId);return a.sort((r,s)=>s.mtime-r.mtime)}function Hae(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 b9="thoughtdag.atlas.watermark",Ao=e=>`${e.rootKey}:${e.rel}`;function hy(){try{return JSON.parse(localStorage.getItem(b9)??"{}")}catch{return{}}}function sm(e){localStorage.setItem(b9,JSON.stringify(e))}function Uae(e){const t=hy(),n=new Map;if(Object.keys(t).length===0)return sm(Object.fromEntries(e.map(s=>[Ao(s),{mtime:s.mtime,size:s.size}]))),n;const a=new Set(e.map(Ao));let r=!1;for(const s of Object.keys(t))a.has(s)||(delete t[s],r=!0);for(const s of e){const o=t[Ao(s)];o?(s.size>o.size||s.mtime>o.mtime+1e3)&&n.set(Ao(s),{kind:"updated",deltaSize:Math.max(0,s.size-o.size)}):n.set(Ao(s),{kind:"new",deltaSize:s.size})}return r&&sm(t),n}function Fae(e){const t=hy();t[Ao(e)]={mtime:e.mtime,size:e.size},sm(t)}function qae(e){const t=hy();for(const n of e)t[Ao(n)]={mtime:n.mtime,size:n.size};sm(t)}const gc=Ao,mx=e=>new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),wE=e=>e>1e6?`${(e/1e6).toFixed(1)} MB`:`${Math.max(1,Math.round(e/1024))} KB`,Wae={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 Vae({roots:e,counts:t,onChanged:n,onClose:a}){const r=zt(),s=dy(),o={"claude-projects":"Claude Code","codex-sessions":"Codex","dsh-sessions":"DeepSeek Harness","pi-sessions":"Pi"},[c,d]=L.useState(null),h=()=>{window.desktopSessions?.commandsStatus?.().then(d).catch(()=>{})};L.useEffect(h,[]);const m={"claude-code":"Claude Code",codex:"Codex",dsh:"DeepSeek Harness",pi:"Pi"},p=x=>u.jsxs("div",{className:"flex items-center gap-3 px-4 py-2.5 border-b border-line last:border-b-0","data-atlas-source":x.key,children:[u.jsx("input",{type:"checkbox",checked:!s.has(x.key),disabled:!x.exists,onChange:b=>{zae(x.key,!b.target.checked),n()},className:"shrink-0"}),u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsx("div",{className:"text-sm text-ink",children:o[x.key]??x.path.split("/").filter(Boolean).pop()}),u.jsx("div",{className:"text-2xs text-ink-faint truncate",children:x.path})]}),u.jsx("span",{className:"text-2xs text-ink-faint shrink-0",children:x.exists?t.get(x.key)??0:r("atlas.rootMissing")}),!x.builtin&&u.jsx("button",{className:"text-ink-faint hover:text-red-500 p-1 rounded transition-colors shrink-0",onClick:()=>{window.desktopSessions.removeRoot(x.key).then(n)},children:u.jsx(Va,{size:14,strokeWidth:1.75})})]},x.key);return u.jsx("div",{className:"absolute inset-0 z-10 bg-ink/20 flex items-center justify-center",onClick:a,children:u.jsxs("div",{className:"bg-surface border border-line rounded-2xl shadow-xl w-[440px] max-h-[80%] overflow-y-auto",onClick:x=>x.stopPropagation(),"data-atlas-sources-dialog":!0,children:[u.jsxs("div",{className:"px-4 pt-3.5 pb-2.5 border-b border-line",children:[u.jsx("div",{className:"text-sm font-semibold text-ink",children:r("atlas.sourcesTitle")}),u.jsx("div",{className:"text-2xs text-ink-muted mt-0.5",children:r("atlas.sourcesHint")})]}),e.filter(x=>x.builtin).map(p),c&&Object.values(c).some(x=>x.state!=="unavailable")&&u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"px-4 pt-3 pb-1.5 text-2xs uppercase tracking-wide text-ink-faint",children:r("atlas.handoffTitle")}),Object.entries(c).filter(([,x])=>x.state!=="unavailable").map(([x,b])=>u.jsxs("div",{className:"flex items-center gap-3 px-4 py-2.5 border-b border-line","data-atlas-handoff":x,"data-handoff-state":b.state,children:[u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsxs("div",{className:"text-sm text-ink flex items-center gap-2",children:[m[x]??x,u.jsx("code",{className:"text-2xs bg-wash border border-line rounded px-1.5 py-px font-mono",children:b.invoke})]}),u.jsx("div",{className:"text-2xs text-ink-faint truncate",children:r(b.state==="installed"?"atlas.handoffOn":b.state==="outdated"?"atlas.handoffOutdated":"atlas.handoffOff")})]}),b.state!=="installed"&&u.jsx("button",{className:"text-2xs bg-accent/10 text-accent hover:bg-accent/20 font-medium px-2.5 py-1 rounded-lg transition-colors shrink-0","data-handoff-install":!0,onClick:()=>{(async()=>{const{confirmDialog:y}=await Tt(async()=>{const{confirmDialog:w}=await Promise.resolve().then(()=>Em);return{confirmDialog:w}},void 0);if(!await y({title:De("atlas.handoffEnableTitle"),message:We(De("confirm.installCommand"),{path:b.dest}),confirmLabel:De(b.state==="outdated"?"atlas.handoffUpdate":"atlas.handoffEnable")}))return;const S=await window.desktopSessions.commandsInstall(x);S.ok?Qe("success",We(De("atlas.handoffInstalled"),{cmd:b.invoke}),8e3):Qe("error",S.error??"install failed"),h()})()},children:r(b.state==="outdated"?"atlas.handoffUpdate":"atlas.handoffEnable")}),(b.state==="installed"||b.state==="outdated")&&u.jsx("button",{className:"text-ink-faint hover:text-red-500 p-1 rounded transition-colors shrink-0",title:r("atlas.handoffRemove"),"data-handoff-remove":!0,onClick:()=>{window.desktopSessions.commandsRemove(x).then(h)},children:u.jsx(Va,{size:14,strokeWidth:1.75})})]},x))]}),e.filter(x=>!x.builtin).map(p),u.jsxs("div",{className:"flex items-center gap-2 px-4 py-3",children:[u.jsxs("button",{onClick:n,className:"flex items-center gap-1.5 text-sm text-ink-muted hover:text-ink border border-line rounded-lg px-2.5 py-1.5 hover:bg-wash transition-colors",children:[u.jsx(or,{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(zS,{size:13,strokeWidth:1.75})," ",r("atlas.addDir")]})]})]})})}function y9({onClose:e,onSwitched:t,focusSessionId:n}){const a=zt(),r=rn(re=>re.projects),s=rn(re=>re.projects.find(qe=>qe.id===re.activeId)?.sourceSession?.sessionId),o=!!window.desktopSessions,[c,d]=L.useState(null),[h,m]=L.useState([]),[p,x]=L.useState(!1),[b,y]=L.useState(window.desktopSessions?null:"canvases"),[k,S]=L.useState(null),[w,C]=L.useState(!1),[T,N]=L.useState(null),[D,O]=L.useState(new Map),[M,_]=L.useState(new Map),[R,G]=L.useState(new Map),[P,V]=L.useState(!1),J=re=>`${re.rootKey}|${re.rel}`,H=re=>G(qe=>{const xe=new Map(qe),$e=J(re);return xe.has($e)?xe.delete($e):xe.set($e,re),xe}),F=re=>r.find(qe=>Yx(qe).includes(re)),[B,W]=L.useState(""),[Q,K]=L.useState(new Set),[U,q]=L.useState("time"),[te,$]=L.useState(!1),[be,Te]=L.useState(!1),[Se,Be]=L.useState(new Map),[X,oe]=L.useState(null);L.useEffect(()=>{window.desktopSessions?.openTargets().then(oe).catch(()=>{})},[]);const ve=L.useMemo(()=>new Map((X?.apps??[]).map(re=>[re.runner,re.name])),[X]),Le=async()=>{x(!0);try{m(await window.desktopSessions?.roots().catch(()=>[])??[]);const re=await Bae();if(d(re),Be(Uae(re)),window.desktopSessions?.codexThreads?.().then(qe=>{qe&&(O(new Map(qe.filter(xe=>xe.name&&xe.sessionId).map(xe=>[xe.sessionId,xe.name]))),_(new Map(qe.filter(xe=>xe.forkedFromId&&xe.sessionId).map(xe=>[xe.sessionId,xe.forkedFromId]))))}).catch(()=>{}),n){const qe=re.find(xe=>xe.sessionId===n);qe&&y(qe.cwd??"")}}finally{x(!1)}};L.useEffect(()=>{Le()},[]),L.useEffect(()=>{let re=!1;const qe=()=>{re||p||(re=!0,setTimeout(()=>{re=!1,Le()},2e3))};return window.addEventListener("td:sessions-changed",qe),()=>window.removeEventListener("td:sessions-changed",qe)},[p]);const Re=L.useCallback(re=>D.get(re.sessionId)??re.title,[D]),Ce=L.useMemo(()=>(c??[]).filter(re=>!Q.has(re.runner)&&(be||!re.subagent)&&(!te||Se.has(gc(re)))&&(!B.trim()||Re(re).toLowerCase().includes(B.trim().toLowerCase()))),[c,Q,B,te,Se,be,Re]),tt=L.useMemo(()=>Hae(Ce),[Ce]),Ve=L.useMemo(()=>[...new Set((c??[]).map(re=>re.runner))].sort(),[c]),ze=L.useMemo(()=>{const re=new Map;for(const qe of c??[])re.set(qe.rootKey,(re.get(qe.rootKey)??0)+1);return re},[c]),bt=b==="canvases"?null:tt.find(re=>(re.cwd??"")===(b??tt[0]?.cwd??""))??tt[0]??null,ct=L.useMemo(()=>{if(!bt)return[];const re=U==="name"?(qe,xe)=>Re(qe).localeCompare(Re(xe)):Wae[U];return[...bt.cards].sort(re)},[bt,U,Re]),Ke=re=>{Fae(re),Be(qe=>{const xe=new Map(qe);return xe.delete(gc(re)),xe})},it=async re=>{if(!k){S(re.rel),Ke(re);try{const{streamRunnerConversation:qe}=await Tt(async()=>{const{streamRunnerConversation:At}=await import("./index-DMEJ2pfg.js");return{streamRunnerConversation:At}},[]),{importOrAppendConversation:xe,shellSessionReader:$e}=await Tt(async()=>{const{importOrAppendConversation:At,shellSessionReader:qt}=await import("./canonical-D4SquoNo.js");return{importOrAppendConversation:At,shellSessionReader:qt}},[]),ft=await qe($e(re.rootKey,re.rel)),yt=await xe(ft);if(!yt)throw new Error(De("handoff.notASession"));yt.kind==="appended"?Qe("success",We(De("atlas.appended"),{n:yt.turns}),9e3):yt.kind==="mounted"?Qe("success",We(De(yt.mode==="continue"?"atlas.mountedChapter":"atlas.mountedBranch"),{n:yt.turns}),9e3):yt.kind==="opened"?Qe("info",De("atlas.upToDate"),6e3):Qe("success",We(De("toast.importedChats"),{n:1,m:yt.nodeCount}),9e3),e(),t()}catch(qe){Qe("error",We(De("atlas.parseFailed"),{msg:qe instanceof Error?qe.message:String(qe)}))}finally{S(null)}}},vt=async re=>{if(!(k||R.size<2)){S("__merge__");try{const{streamRunnerConversation:qe}=await Tt(async()=>{const{streamRunnerConversation:At}=await import("./index-DMEJ2pfg.js");return{streamRunnerConversation:At}},[]),{mergeSessionsIntoProject:xe,shellSessionReader:$e}=await Tt(async()=>{const{mergeSessionsIntoProject:At,shellSessionReader:qt}=await import("./canonical-D4SquoNo.js");return{mergeSessionsIntoProject:At,shellSessionReader:qt}},[]),ft=[];for(const At of R.values())ft.push(await qe($e(At.rootKey,At.rel))),Ke(At);const yt=await xe(ft,re);if(!yt)throw new Error(De("handoff.notASession"));Qe("success",We(De("atlas.merged"),{n:yt.mounted}),1e4),yt.skipped>0&&Qe("info",We(De("atlas.mergeSkippedInfo"),{n:yt.skipped}),8e3),G(new Map),e(),t()}catch(qe){Qe("error",We(De("atlas.parseFailed"),{msg:qe instanceof Error?qe.message:String(qe)}))}finally{S(null)}}},He=async re=>{const qe=rn.getState().projects.find(ft=>ft.sourceSession?.sessionId===re.sessionId);if(!qe||k)return;const{confirmDialog:xe}=await Tt(async()=>{const{confirmDialog:ft}=await Promise.resolve().then(()=>Em);return{confirmDialog:ft}},void 0);if(await xe({title:De("confirm.recastTitle"),message:We(De("confirm.recast"),{name:qe.name}),confirmLabel:De("confirm.recastTitle"),danger:!0})){S(re.rel);try{const{streamRunnerConversation:ft}=await Tt(async()=>{const{streamRunnerConversation:Yt}=await import("./index-DMEJ2pfg.js");return{streamRunnerConversation:Yt}},[]),{importOrAppendConversation:yt,shellSessionReader:At}=await Tt(async()=>{const{importOrAppendConversation:Yt,shellSessionReader:kn}=await import("./canonical-D4SquoNo.js");return{importOrAppendConversation:Yt,shellSessionReader:kn}},[]),qt=await ft(At(re.rootKey,re.rel));if(!qt)throw new Error(De("handoff.notASession"));const{deleteProject:hn}=await Tt(async()=>{const{deleteProject:Yt}=await Promise.resolve().then(()=>Fr);return{deleteProject:Yt}},void 0);if(await hn(qe.id),!await yt(qt))throw new Error(De("handoff.notASession"));Qe("success",De("atlas.recastDone"),8e3),e(),t()}catch(ft){Qe("error",We(De("atlas.parseFailed"),{msg:ft instanceof Error?ft.message:String(ft)}))}finally{S(null)}}},It=async(re,qe)=>{const xe=await window.desktopSessions.openInCli(re.runner,re.cwd,re.sessionId,qe).catch(()=>({opened:!1,via:"",command:""}));xe.opened&&xe.via==="app"?(await navigator.clipboard.writeText(re.sessionId).catch(()=>{}),Qe("success",De("atlas.appOpened"),9e3)):xe.opened?Qe("success",De("atlas.opened")):xe.command&&(await navigator.clipboard.writeText(xe.command).catch(()=>{}),Qe("info",De("atlas.cmdCopied"),9e3))};return Qa.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")}),Se.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:We(a("atlas.changesSummary"),{n:[...Se.values()].filter(re=>re.kind==="new").length,m:[...Se.values()].filter(re=>re.kind==="updated").length})}),u.jsx("button",{className:"text-ink-faint hover:text-ink underline decoration-dotted transition-colors",onClick:()=>{qae(c??[]),Be(new Map)},"data-atlas-mark-all":!0,children:a("atlas.markAllSeen")})]})]}),o&&X&&X.terminals.length>0&&u.jsxs("label",{className:"flex items-center gap-1.5 text-sm text-ink-muted border border-line rounded-lg px-2.5 py-1.5 cursor-pointer",title:a("atlas.terminalChoice"),children:[u.jsx(Oo,{size:14,strokeWidth:1.75}),u.jsxs("select",{value:X.prefs.terminal,onChange:re=>{const qe=re.target.value;if(qe==="__add__"){window.desktopSessions?.addTerminal().then(()=>window.desktopSessions?.openTargets().then(oe));return}window.desktopSessions?.setOpenPrefs({terminal:qe}).then(xe=>oe($e=>$e&&{...$e,prefs:xe}))},className:"bg-transparent focus:outline-none text-sm text-ink cursor-pointer","data-atlas-terminal-select":!0,children:[X.terminals.map(re=>u.jsx("option",{value:re.id,children:re.name},re.id)),X.canAddCustom&&u.jsx("option",{value:"__add__",children:a("atlas.otherTerminal")})]})]}),o&&u.jsxs("button",{onClick:()=>C(!0),className:"flex items-center gap-1.5 text-sm text-ink-muted hover:text-ink border border-line rounded-lg px-2.5 py-1.5 hover:bg-wash transition-colors","data-atlas-sources":!0,children:[u.jsx(zS,{size:14,strokeWidth:1.75})," ",a("atlas.sources")]}),o&&u.jsxs("button",{onClick:()=>{Le()},disabled:p,className:"flex items-center gap-1.5 text-sm text-ink-muted hover:text-ink border border-line rounded-lg px-2.5 py-1.5 hover:bg-wash transition-colors disabled:opacity-60","data-atlas-refresh":!0,children:[p?u.jsx(Un,{size:14,className:"animate-spin"}):u.jsx(or,{size:14,strokeWidth:1.75}),a(p?"atlas.scanning":"atlas.refresh")]}),u.jsx("button",{onClick:e,className:"text-ink-faint hover:text-ink p-1.5 rounded-lg hover:bg-wash transition-colors","data-atlas-close":!0,children:u.jsx(mn,{size:18,strokeWidth:1.75})})]}),u.jsxs("div",{className:"flex-1 flex min-h-0",children:[u.jsxs("div",{className:"w-[260px] border-r border-line overflow-y-auto py-2 shrink-0",children:[u.jsx("div",{className:"px-4 py-1 text-2xs uppercase tracking-wide text-ink-faint",children:a("atlas.recent")}),r.filter(re=>!re.archived).sort((re,qe)=>qe.updatedAt-re.updatedAt).slice(0,6).map(re=>u.jsxs("button",{onClick:()=>{e(),Ms(re.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":re.id,children:[re.sourceSession?.sessionId?u.jsx("span",{className:"text-2xs font-mono border border-line rounded px-1 py-px shrink-0 text-ink-faint",children:re.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:re.name})]},re.id)),u.jsx("div",{className:"border-t border-line mt-2 pt-2 px-4 py-1 text-2xs uppercase tracking-wide text-ink-faint",children:a("atlas.folders")}),!o&&u.jsx("div",{className:"px-4 py-2 text-xs text-ink-faint",children:a("atlas.webNoScan")}),o&&c===null&&u.jsxs("div",{className:"px-4 py-2 text-sm text-ink-faint flex items-center gap-2",children:[u.jsx(Un,{size:14,className:"animate-spin"})," ",a("atlas.scanning")]}),o&&c!==null&&tt.length===0&&u.jsx("div",{className:"px-4 py-2 text-xs text-ink-faint",children:a("atlas.empty")}),tt.map(re=>{const qe=re.cwd??"",xe=b!=="canvases"&&bt===re;return u.jsxs("button",{onClick:()=>y(qe),className:`w-full text-left px-4 py-2 flex items-center gap-2 transition-colors ${xe?"bg-accent/5 text-accent":"text-ink hover:bg-wash"}`,"data-atlas-folder":re.name||"unfiled",children:[xe?u.jsx(Pc,{size:15,strokeWidth:1.75,className:"shrink-0"}):u.jsx(fz,{size:15,strokeWidth:1.75,className:"shrink-0 text-ink-faint"}),u.jsx("span",{className:"flex-1 truncate text-sm",children:re.name||a("atlas.unfiled")}),(()=>{const $e=re.cards.filter(ft=>Se.has(gc(ft))).length;return $e>0?u.jsxs("span",{className:"text-2xs text-accent shrink-0","data-atlas-folder-changes":!0,children:["+",$e]}):null})(),u.jsx("span",{className:"text-2xs text-ink-faint shrink-0",children:re.cards.length})]},qe)}),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(re=>!re.archived).sort((re,qe)=>qe.updatedAt-re.updatedAt).map(re=>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(),Ms(re.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:re.name}),u.jsxs("div",{className:"text-2xs text-ink-faint mt-0.5 flex items-center gap-1.5",children:[u.jsx("span",{children:mx(re.updatedAt)}),!!re.sourceSession?.sessionId&&u.jsx("span",{className:"font-mono border border-line rounded px-1 py-px",children:re.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:qe=>{qe.stopPropagation(),qf(re.id,!0)},"data-atlas-archive":!0,children:u.jsx(zo,{size:15,strokeWidth:1.75})}),!!re.sourceSession&&Yx(re).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:[re.sourceSession.sessionId&&u.jsxs("span",{children:["◉ ",re.sourceSession.runner," ",re.sourceSession.sessionId.slice(0,8)," · ",We(a("atlas.turnsN"),{n:re.sourceSession.importedCount})]}),(re.sourceSession.chapters??[]).map(qe=>u.jsxs("span",{children:["↳ ",qe.runner," ",qe.sessionId.slice(0,8)," · ",We(a("atlas.turnsN"),{n:qe.importedCount})]},qe.sessionId)),(re.sourceSession.branches??[]).map(qe=>u.jsxs("span",{children:["⑂ ",qe.runner," ",qe.sessionId.slice(0,8)," · ",We(a("atlas.turnsN"),{n:qe.importedCount})]},qe.sessionId))]})]},re.id)),r.some(re=>re.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:We(a("atlas.archivedGroup"),{n:r.filter(re=>re.archived).length})}),u.jsx("div",{className:"space-y-1.5 mt-1.5",children:r.filter(re=>re.archived).sort((re,qe)=>qe.updatedAt-re.updatedAt).map(re=>u.jsxs("button",{title:a("atlas.restoreOpen"),onClick:()=>{qf(re.id,!1).then(()=>{e(),Ms(re.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:re.name}),!!re.sourceSession?.sessionId&&u.jsx("span",{className:"text-2xs font-mono border border-line rounded px-1 py-px shrink-0 text-ink-faint",children:re.sourceSession.runner})]}),u.jsx("div",{className:"text-2xs text-ink-faint mt-0.5",children:mx(re.updatedAt)})]},re.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(zf,{size:13,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),u.jsx("input",{value:B,onChange:re=>W(re.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})]}),Ve.map(re=>u.jsx("button",{onClick:()=>K(qe=>{const xe=new Set(qe);return xe.has(re)?xe.delete(re):xe.add(re),xe}),className:`text-2xs font-mono border rounded-lg px-2 py-1 transition-colors ${Q.has(re)?"border-line text-ink-faint line-through":"border-accent/40 text-accent bg-accent/5"}`,"data-atlas-runner-toggle":re,children:re},re)),Se.size>0&&u.jsx("button",{onClick:()=>$(re=>!re),className:`text-2xs border rounded-lg px-2 py-1 transition-colors ${te?"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(re=>re.subagent)&&u.jsx("button",{onClick:()=>Te(re=>!re),className:`text-2xs border rounded-lg px-2 py-1 transition-colors ${be?"border-accent text-accent bg-accent/5":"border-line text-ink-faint hover:text-ink"}`,"data-atlas-show-sub":!0,children:a("atlas.showSub")}),u.jsxs("button",{onClick:()=>q(re=>({time:"name",name:"size",size:"runner",runner:"time"})[re]),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(dP,{size:12,strokeWidth:1.75}),a(`atlas.sort${U[0].toUpperCase()}${U.slice(1)}`)]})]}),bt?u.jsxs(u.Fragment,{children:[bt.cwd&&u.jsxs("div",{className:"text-2xs text-ink-faint mb-3 truncate",children:[bt.cwd," · ",We(a("atlas.sessions"),{n:bt.cards.length})]}),u.jsx("div",{className:"space-y-1.5",children:ct.map(re=>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(J(re))?"border-accent/60 bg-accent/5":"border-line"}`,onClick:()=>{it(re)},"data-atlas-session":re.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:Re(re)}),M.has(re.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(re.sessionId)}`,"data-atlas-fork":!0,children:"⑂"}),Se.get(gc(re))?.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")}),Se.get(gc(re))?.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:["+",wE(Se.get(gc(re)).deltaSize)]}),re.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 qe=F(re.sessionId);return qe?u.jsx("span",{className:"text-2xs text-ink-faint border border-line rounded px-1 py-px shrink-0",title:qe.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:re.runner}),u.jsx("span",{children:mx(re.mtime)}),u.jsx("span",{children:wE(re.size)})]})]}),k===re.rel?u.jsx(Un,{size:16,className:"animate-spin text-accent shrink-0"}):u.jsxs("div",{className:`${R.has(J(re))?"":"opacity-0 group-hover:opacity-100"} transition-opacity flex items-center gap-1 shrink-0`,children:[!F(re.sessionId)&&!!re.sessionId&&u.jsx("button",{title:a("atlas.pickForMerge"),className:`p-1.5 rounded transition-colors ${R.has(J(re))?"text-accent":"text-ink-faint hover:text-accent"}`,onClick:qe=>{qe.stopPropagation(),H(re)},"data-atlas-pick":R.has(J(re))?"on":"off",children:R.has(J(re))?u.jsx(EB,{size:16,strokeWidth:1.75}):u.jsx(Kb,{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(Az,{size:16,strokeWidth:1.75})}),r.some(qe=>qe.sourceSession?.sessionId===re.sessionId)&&u.jsx("button",{title:a("atlas.recast"),className:"text-ink-faint hover:text-red-500 p-1.5 rounded transition-colors",onClick:qe=>{qe.stopPropagation(),He(re)},"data-atlas-recast":!0,children:u.jsx(iB,{size:16,strokeWidth:1.75})}),!F(re.sessionId)&&u.jsx("button",{title:a("atlas.mountTo"),className:"text-ink-faint hover:text-accent p-1.5 rounded transition-colors",onClick:qe=>{qe.stopPropagation(),N(re)},"data-atlas-mount":!0,children:u.jsx(Do,{size:16,strokeWidth:1.75})}),ve.has(re.runner)&&u.jsx("button",{title:We(a("atlas.openApp"),{name:ve.get(re.runner)}),className:"text-ink-faint hover:text-accent p-1.5 rounded transition-colors",onClick:qe=>{qe.stopPropagation(),It(re,"app")},"data-atlas-open-app":!0,children:u.jsx(oP,{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:qe=>{qe.stopPropagation(),It(re,"terminal")},"data-atlas-open-cli":!0,children:u.jsx(Oo,{size:16,strokeWidth:1.75})})]})]},re.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&&!P&&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:We(a("atlas.mergeSelected"),{n:R.size})}),k==="__merge__"?u.jsx(Un,{size:15,className:"animate-spin text-accent"}):u.jsxs(u.Fragment,{children:[u.jsx("button",{className:"text-xs bg-accent hover:bg-accent-strong text-white font-medium px-3 py-1.5 rounded-lg transition-colors whitespace-nowrap",onClick:()=>{vt()},"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:()=>V(!0),"data-atlas-merge-into":!0,children:a("atlas.mergeInto")})]}),u.jsx("button",{className:"text-ink-faint hover:text-ink p-1",onClick:()=>G(new Map),title:a("common.cancel"),children:u.jsx(mn,{size:14,strokeWidth:1.75})})]}),(T||P)&&u.jsx("div",{className:"absolute inset-0 z-10 bg-ink/20 flex items-center justify-center",onClick:()=>{N(null),V(!1)},children:u.jsxs("div",{className:"bg-surface border border-line rounded-2xl shadow-xl w-[400px] max-h-[70%] overflow-y-auto",onClick:re=>re.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(P?"atlas.mergeInto":"atlas.mountTo")}),u.jsx("div",{className:"text-2xs text-ink-muted mt-0.5",children:a(P?"atlas.mergeSelected":"atlas.mountHint").replace("{n}",String(R.size))})]}),r.filter(re=>!re.archived&&re.kind!=="paradigm").sort((re,qe)=>qe.updatedAt-re.updatedAt).map(re=>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(P){V(!1),vt(re.id);return}const qe=T;N(null),(async()=>{S(qe.rel);try{const{streamRunnerConversation:xe}=await Tt(async()=>{const{streamRunnerConversation:qt}=await import("./index-DMEJ2pfg.js");return{streamRunnerConversation:qt}},[]),{mountConversationToProject:$e,shellSessionReader:ft}=await Tt(async()=>{const{mountConversationToProject:qt,shellSessionReader:hn}=await import("./canonical-D4SquoNo.js");return{mountConversationToProject:qt,shellSessionReader:hn}},[]),yt=await xe(ft(qe.rootKey,qe.rel)),At=await $e(yt,re.id);if(!At)throw new Error(De("handoff.notASession"));Qe("success",We(De("atlas.mountedChapter"),{n:At.kind==="mounted"||At.kind==="appended"?At.turns:0}),9e3),e(),t()}catch(xe){Qe("error",We(De("atlas.parseFailed"),{msg:xe instanceof Error?xe.message:String(xe)}))}finally{S(null)}})()},children:re.name},re.id))]})}),w&&u.jsx(Vae,{roots:h,counts:ze,onChanged:()=>{Le()},onClose:()=>C(!1)})]})}),document.body)}function Gae({conversations:e,onClose:t,onDone:n}){const a=zt(),[r,s]=L.useState(new Set),[o,c]=L.useState(!1),d=p=>{s(x=>{const b=new Set(x);return b.has(p)?b.delete(p):b.add(p),b})},h=r.size===e.length,m=async()=>{r.size===0||o||(c(!0),await wF([...r].sort((p,x)=>p-x).map(p=>e[p])),c(!1),n())};return u.jsx("div",{className:"fixed inset-0 z-50 bg-ink/30 backdrop-blur-sm flex items-center justify-center p-6",onClick:t,children:u.jsxs("div",{className:"bg-card border border-line rounded-2xl shadow-2xl w-full max-w-lg max-h-[80vh] flex flex-col",onClick:p=>p.stopPropagation(),children:[u.jsxs("div",{className:"px-6 py-4 border-b border-line flex items-start justify-between gap-4",children:[u.jsxs("div",{children:[u.jsx("h2",{className:"text-base font-semibold text-ink",children:a("import.title")}),u.jsx("p",{className:"text-xs text-ink-muted mt-1 leading-relaxed",children:a("import.subtitle")})]}),u.jsx("button",{onClick:t,className:"text-ink-faint hover:text-ink transition-colors shrink-0 mt-0.5",children:u.jsx(mn,{size:16,strokeWidth:1.75})})]}),u.jsx("div",{className:"px-6 py-2 border-b border-line/60",children:u.jsxs("label",{className:"flex items-center gap-2 text-xs text-ink-muted cursor-pointer select-none py-1",children:[u.jsx("input",{type:"checkbox",checked:h,onChange:()=>s(h?new Set:new Set(e.map((p,x)=>x))),className:"rounded border-line text-accent focus:ring-accent w-3.5 h-3.5"}),a("import.selectAll"),u.jsx("span",{className:"ml-auto text-2xs text-ink-faint uppercase tracking-wider",children:e[0]?.source})]})}),u.jsx("ul",{className:"flex-1 overflow-y-auto py-1",children:e.map((p,x)=>u.jsx("li",{children:u.jsxs("label",{className:"flex items-center gap-3 px-6 py-2 hover:bg-wash transition-colors cursor-pointer select-none",children:[u.jsx("input",{type:"checkbox",checked:r.has(x),onChange:()=>d(x),className:"rounded border-line text-accent focus:ring-accent w-3.5 h-3.5 shrink-0"}),u.jsx(PS,{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:We(a("import.messages"),{n:p.messageCount})})]})},x))}),u.jsxs("div",{className:"px-6 py-4 border-t border-line flex justify-end gap-2",children:[u.jsx("button",{onClick:t,className:"text-xs text-ink-muted hover:text-ink px-4 py-2 rounded-lg hover:bg-wash transition-colors",children:a("common.cancel")}),u.jsx("button",{onClick:()=>{m()},disabled:r.size===0||o,className:"text-xs bg-accent hover:bg-accent-strong text-white px-5 py-2 rounded-lg transition-colors disabled:opacity-30",children:o?"…":We(a("import.confirm"),{n:r.size})})]})]})})}function $ae(e){const t=Date.now()-e,n=Math.floor(t/6e4);if(n<1)return De("switcher.justNow");if(n<60)return We(De("switcher.minAgo"),{n});const a=Math.floor(n/60);if(a<24)return We(De("switcher.hourAgo"),{n:a});const r=Math.floor(a/24);return r<30?We(De("switcher.dayAgo"),{n:r}):new Date(e).toLocaleDateString(Ra.getState().lang==="zh"?"zh-CN":"en-US")}function Yae({onSwitched:e}){const t=zt(),n=rn(_=>_.projects),a=rn(_=>_.activeId),r=rn(_=>_.switching),s=n.find(_=>_.id===a)?.kind==="paradigm",[o,c]=L.useState(!1),[d,h]=L.useState(null),[m,p]=L.useState(!1),[x,b]=L.useState(void 0),[y,k]=L.useState(null),[S,w]=L.useState(""),C=L.useRef(null),T=L.useRef(null),N=n.find(_=>_.id===a),D=n.filter(_=>!_.archived).sort((_,R)=>R.updatedAt-_.updatedAt).slice(0,7),O=async _=>{const{canvasUniqueness:R}=await Tt(async()=>{const{canvasUniqueness:J}=await import("./canonical-D4SquoNo.js");return{canvasUniqueness:J}},[]),G=await R(_.id),P=G==="native"?"confirm.deleteNative":G==="diverged-mirror"?"confirm.deleteDiverged":"confirm.deletePristine";await _s({title:De("confirm.deleteCanvasTitle"),message:We(De(P),{name:_.name}),confirmLabel:De("common.delete"),danger:G!=="pristine-mirror"})&&I7(_.id).then(e)};L.useEffect(()=>{if(!o)return;const _=R=>{T.current?.contains(R.target)||c(!1)};return window.addEventListener("mousedown",_),()=>window.removeEventListener("mousedown",_)},[o]);const M=async _=>{c(!1),await Ms(_),e(),Tt(()=>import("./canonical-D4SquoNo.js"),[]).then(R=>R.unsubscribeOrphanedSessions()),Tt(()=>import("./live-mirror-CkSO5X2s.js"),[]).then(R=>R.sweepRecentSessions())};return u.jsxs("div",{ref:T,className:"absolute top-4 left-4 z-20",children:[u.jsxs("div",{className:"flex items-center gap-1.5",children:[u.jsxs("button",{onClick:()=>c(!o),disabled:r,className:"bg-card/90 backdrop-blur border border-line rounded-xl px-3.5 py-2 shadow-sm hover:bg-wash transition-colors flex items-center gap-2 text-sm text-ink max-w-[240px] disabled:opacity-60",children:[r?u.jsx(Un,{size:16,strokeWidth:1.75,className:"animate-spin shrink-0 text-accent"}):s?u.jsx(KP,{size:16,strokeWidth:1.75,className:"shrink-0 text-accent"}):u.jsx(Pc,{size:16,strokeWidth:1.75,className:"shrink-0 text-ink-muted"}),u.jsx("span",{className:"truncate font-medium",children:N?.name??"…"}),u.jsx(Cl,{size:14,strokeWidth:1.75,className:"shrink-0 text-ink-faint"})]}),!!N?.sourceSession?.sessionId&&(()=>{const _=im.size>0&&!im.has(N.sourceSession.sessionId);return u.jsxs("button",{title:_?De("switcher.mirrorBadgeGone"):We(De("switcher.mirrorBadge"),{runner:N.sourceSession.runner}),onClick:()=>{b(N.sourceSession.sessionId),p(!0)},className:`bg-card/90 backdrop-blur border border-line rounded-xl px-2 py-2 shadow-sm hover:bg-wash transition-colors text-2xs font-mono flex items-center gap-1 ${_?"text-ink-faint/50 line-through decoration-1":"text-ink-faint hover:text-accent"}`,"data-twin-badge":_?"unreachable":"live",children:["⇄ ",N.sourceSession.runner]})})()]}),o&&u.jsxs("div",{className:"mt-1.5 bg-card border border-line rounded-xl shadow-lg py-1.5 w-[320px] animate-fade-in",children:[u.jsx("div",{className:"max-h-[320px] overflow-y-auto",children:D.map(_=>u.jsx("div",{className:`group flex items-center gap-1 px-3 py-2 hover:bg-wash cursor-pointer transition-colors ${_.id===a?"bg-accent/5":""}`,onClick:()=>{y!==_.id&&_.id!==a&&M(_.id)},children:y===_.id?u.jsx("input",{autoFocus:!0,value:S,onChange:R=>w(R.target.value),onClick:R=>R.stopPropagation(),onKeyDown:R=>{R.key==="Enter"&&!Xa(R)&&S.trim()&&(M7(_.id,S.trim()),k(null)),R.key==="Escape"&&k(null)},onBlur:()=>k(null),className:"flex-1 text-sm text-ink border border-accent/40 rounded-lg px-2 py-1 bg-surface focus:outline-none"}):u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsx("div",{className:`text-sm truncate ${_.id===a?"text-accent font-medium":"text-ink"}`,children:_.name}),u.jsxs("div",{className:"text-2xs text-ink-faint flex items-center gap-1.5",children:[u.jsx("span",{children:$ae(_.updatedAt)}),!!_.sourceSession?.sessionId&&u.jsx("span",{className:"font-mono border border-line rounded px-1 py-px","data-mirror-mark":!0,children:_.sourceSession.runner})]})]}),u.jsx("button",{title:t("switcher.rename"),className:"opacity-0 group-hover:opacity-100 text-ink-faint hover:text-ink p-1 rounded transition-all shrink-0",onClick:R=>{R.stopPropagation(),k(_.id),w(_.name)},children:u.jsx(Wc,{size:14,strokeWidth:1.75})}),u.jsx("button",{title:t("common.delete"),className:"opacity-0 group-hover:opacity-100 text-ink-faint hover:text-red-500 p-1 rounded transition-all shrink-0",onClick:R=>{R.stopPropagation(),O(_)},children:u.jsx(Va,{size:14,strokeWidth:1.75})}),u.jsx("button",{title:t("switcher.archive"),className:"opacity-0 group-hover:opacity-100 text-ink-faint hover:text-amber-600 p-1 rounded transition-all shrink-0",onClick:R=>{R.stopPropagation(),qf(_.id,!0).then(e)},"data-archive-canvas":!0,children:u.jsx(zo,{size:14,strokeWidth:1.75})})]})},_.id))}),u.jsxs("div",{className:"border-t border-line mt-1 pt-1",children:[u.jsxs("button",{onClick:()=>{c(!1),Nm().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(wm,{size:15,strokeWidth:1.75})," ",t("switcher.newCanvas")]}),u.jsxs("button",{onClick:()=>C.current?.click(),className:"w-full text-left px-3 py-2 text-sm text-ink-muted hover:bg-wash transition-colors flex items-center gap-2",children:[u.jsx(LB,{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(zz,{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(or,{size:15,strokeWidth:1.75})," ",t("update.checkMenu"),u.jsxs("span",{className:"ml-auto text-2xs text-ink-faint",children:["v",new URLSearchParams(window.location.search).get("dv")]})]}),u.jsx("input",{ref:C,type:"file",accept:".json,.jsonl,application/json",className:"hidden",onChange:_=>{const R=_.target.files?.[0];R&&yF(R).then(G=>{G.kind==="own"&&G.ok?(c(!1),e()):G.kind==="chat"&&(c(!1),h(G.conversations))}).catch(G=>{Qe("error",We(De("toast.importFailedGeneric"),{msg:G instanceof Error?G.message:String(G)}))}),_.target.value=""}})]})]}),d&&u.jsx(Gae,{conversations:d,onClose:()=>h(null),onDone:()=>{h(null),e()}}),m&&u.jsx(y9,{onClose:()=>{p(!1),b(void 0)},onSwitched:e,focusSessionId:x})]})}const Kae="JVBERi0xLjQKMSAwIG9iago8PCAvVHlwZSAvQ2F0YWxvZyAvUGFnZXMgMiAwIFIgPj4KZW5kb2JqCjIgMCBvYmoKPDwgL1R5cGUgL1BhZ2VzIC9LaWRzIFszIDAgUiA0IDAgUl0gL0NvdW50IDIgPj4KZW5kb2JqCjMgMCBvYmoKPDwgL1R5cGUgL1BhZ2UgL1BhcmVudCAyIDAgUiAvTWVkaWFCb3ggWzAgMCA1OTUgODQyXSAvQ29udGVudHMgNSAwIFIgL1Jlc291cmNlcyA8PCAvRm9udCA8PCAvRjEgNyAwIFIgL0YyIDggMCBSID4+ID4+ID4+CmVuZG9iago0IDAgb2JqCjw8IC9UeXBlIC9QYWdlIC9QYXJlbnQgMiAwIFIgL01lZGlhQm94IFswIDAgNTk1IDg0Ml0gL0NvbnRlbnRzIDYgMCBSIC9SZXNvdXJjZXMgPDwgL0ZvbnQgPDwgL0YxIDcgMCBSIC9GMiA4IDAgUiA+PiA+PiA+PgplbmRvYmoKNSAwIG9iago8PCAvTGVuZ3RoIDExMTIgPj4Kc3RyZWFtCkJUCi9GMiAxOSBUZiAxIDAgMCAxIDY0IDcyNS4wIFRtIChXaHkgU2F2ZWQgQXJ0aWNsZXMgU3RheSBVbnJlYWQpIFRqCi9GMSAxMSBUZiAxIDAgMCAxIDY0IDcwOC4wIFRtIChBIHNob3J0IGJyaWVmIG9uIGRpZ2l0YWwgaG9hcmRpbmcgYW5kIHRoZSBjb2xsZWN0b3IncyBmYWxsYWN5KSBUagovRjIgMTMgVGYgMSAwIDAgMSA2NCA2NjkuMCBUbSAoMS4gVGhlIHBoZW5vbWVub24pIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNjUxLjUgVG0gKFJlYWQtaXQtbGF0ZXIgc2VydmljZXMgcmVwb3J0IHRoYXQgbW9zdCBzYXZlZCBpdGVtcyBhcmUgbmV2ZXIpIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNjM0LjAgVG0gKHJlb3BlbmVkLiBBY3Jvc3MgcHVibGlzaGVkIHVzYWdlIHN0dWRpZXMsIHRoZSBzaGFyZSBvZiBzYXZlZCkgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA2MTYuNSBUbSAoYXJ0aWNsZXMgdGhhdCBnZXQgYSBzZWNvbmQgdmlzaXQgaXMgc21hbGwsIGFuZCBjb21wbGV0aW9uIHJhdGVzKSBUagovRjEgMTEuNSBUZiAxIDAgMCAxIDY0IDU5OS4wIFRtIChhcmUgc21hbGxlciBzdGlsbC4gVGhlIGFyY2hpdmUgZ3Jvd3M7IHRoZSByZWFkaW5nIGRvZXMgbm90LikgVGoKL0YyIDEzIFRmIDEgMCAwIDEgNjQgNTYwLjAgVG0gKDIuIFRoZSBjb2xsZWN0b3IncyBmYWxsYWN5KSBUagovRjEgMTEuNSBUZiAxIDAgMCAxIDY0IDU0Mi41IFRtIChDb2xsZWN0aW5nIHByb2R1Y2VzIGFuIGltbWVkaWF0ZSBzZW5zZSBvZiBwcm9ncmVzcyB3aGlsZSB0aGUpIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNTI1LjAgVG0gKHVuZGVyc3RhbmRpbmcgaXQgcHJvbWlzZXMgaXMgZGVmZXJyZWQuIFNhdmluZyBhIHRleHQgZmVlbHMgbGlrZSkgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA1MDcuNSBUbSAoYSBmaXJzdCBzdGVwIG9mIHJlYWRpbmcgaXQsIGJ1dCBubyBwYXJ0IG9mIHRoZSByZWFkaW5nIGhhcykgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA0OTAuMCBUbSAoaGFwcGVuZWQuKSBUagovRjIgMTEuNSBUZiAxIDAgMCAxIDY0IDQ3Mi41IFRtIChUaGUgYWN0IG9mIHNhdmluZyBpcyBtaXN0YWtlbiBmb3IgdGhlIGFjdCBvZiBsZWFybmluZy4pIFRqCkVUCmVuZHN0cmVhbQplbmRvYmoKNiAwIG9iago8PCAvTGVuZ3RoIDkwOCA+PgpzdHJlYW0KQlQKL0YyIDEzIFRmIDEgMCAwIDEgNjQgNzI1LjAgVG0gKDMuIFdoeSBpdCBwZXJzaXN0cykgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA3MDcuNSBUbSAoVGhlIGNvc3RzIGFyZSBhc3ltbWV0cmljOiBzYXZpbmcgdGFrZXMgb25lIHNlY29uZCBhbmQgcGF5cyBvdXQpIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNjkwLjAgVG0gKGEgc21hbGwgcmV3YXJkIG5vdzsgcmVhZGluZyB0YWtlcyBhbiBob3VyIGFuZCBwYXlzIG91dCBsYXRlci4pIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNjcyLjUgVG0gKEhhYml0cyBmb2xsb3cgdGhlIGNoZWFwZXIgbG9vcCwgc28gbGlicmFyaWVzIGluZmxhdGUgYnkgZGVmYXVsdC4pIFRqCi9GMiAxMyBUZiAxIDAgMCAxIDY0IDYzMy41IFRtICg0LiBXaGF0IGhlbHBzKSBUagovRjEgMTEuNSBUZiAxIDAgMCAxIDY0IDYxNi4wIFRtIChJbnRlcnZlbnRpb25zIHRoYXQgd29yayBtb3ZlIHByb2Nlc3NpbmcgdG8gdGhlIG1vbWVudCBvZiBjYXB0dXJlOikgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA1OTguNSBUbSAod3JpdGUgb25lIGxpbmUgaW4geW91ciBvd24gd29yZHMgYWJvdXQgd2h5IHRoZSBpdGVtIG1hdHRlcnMsIGFuZCkgVGoKL0YxIDExLjUgVGYgMSAwIDAgMSA2NCA1ODEuMCBUbSAoc2NoZWR1bGUgYSByZXZpZXcgcGFzcyBpbnN0ZWFkIG9mIHRydXN0aW5nIHRoZSBhcmNoaXZlIHRvKSBUagovRjEgMTEuNSBUZiAxIDAgMCAxIDY0IDU2My41IFRtIChyZXN1cmZhY2UgaXQuKSBUagovRjEgMTEuNSBUZiAxIDAgMCAxIDY0IDUzMi4wIFRtIChBIHNtYWxsZXIgbGlicmFyeSB0aGF0IGdldHMgcHJvY2Vzc2VkIGJlYXRzIGEgY29tcGxldGUgb25lIHRoYXQpIFRqCi9GMSAxMS41IFRmIDEgMCAwIDEgNjQgNTE0LjUgVG0gKGRvZXMgbm90LikgVGoKRVQKZW5kc3RyZWFtCmVuZG9iago3IDAgb2JqCjw8IC9UeXBlIC9Gb250IC9TdWJ0eXBlIC9UeXBlMSAvQmFzZUZvbnQgL0hlbHZldGljYSA+PgplbmRvYmoKOCAwIG9iago8PCAvVHlwZSAvRm9udCAvU3VidHlwZSAvVHlwZTEgL0Jhc2VGb250IC9IZWx2ZXRpY2EtQm9sZCA+PgplbmRvYmoKeHJlZgowIDkKMDAwMDAwMDAwMCA2NTUzNSBmIAowMDAwMDAwMDA5IDAwMDAwIG4gCjAwMDAwMDAwNTggMDAwMDAgbiAKMDAwMDAwMDEyMSAwMDAwMCBuIAowMDAwMDAwMjU3IDAwMDAwIG4gCjAwMDAwMDAzOTMgMDAwMDAgbiAKMDAwMDAwMTU1NyAwMDAwMCBuIAowMDAwMDAyNTE2IDAwMDAwIG4gCjAwMDAwMDI1ODYgMDAwMDAgbiAKdHJhaWxlcgo8PCAvU2l6ZSA5IC9Sb290IDEgMCBSID4+CnN0YXJ0eHJlZgoyNjYxCiUlRU9G",Xae=`<!-- tdag-page:1 -->
|
|
548
548
|
|
|
549
549
|
# Why Saved Articles Stay Unread
|
|
550
550
|
|
|
@@ -778,11 +778,11 @@ ${n==="zh"?"**高光(原文保真)**":"**Highlights (verbatim)**"}
|
|
|
778
778
|
${T.map(_=>`> ${_.text}`).join(`
|
|
779
779
|
`)}`:"",D=In();x.push(D);const O=`${n==="zh"?"凝练":"Condensed"}: ${w.data.question.replace(/\s+/g," ").slice(0,60)} → ${C.data.question.replace(/\s+/g," ").slice(0,60)}`,M=`${t[S]||""}${N}`;p.push({id:D,type:"thought",position:{x:w.position.x+h,y:w.position.y},dragHandle:".drag-handle",data:{question:O,response:M,responses:[M],responseIndex:0,condensedFrom:k.nodeIds,createdAt:new Date().toISOString(),isCollapsed:!1,isEditing:!1,isEditingResponse:!1,isLoading:!1,tokenCount:$n(`${O}
|
|
780
780
|
${M}`),highlights:[],highlightMode:"tag",attachments:[],excludedAttachmentIds:[],includedAttachmentIds:[],roleMode:"inherit",isRoot:!1,isBranch:!1}}),k.nodeIds.forEach(_=>m.set(_,D))});for(const k of r){if(c.has(k.id))continue;const S=In();m.set(k.id,S);const w=k.data;p.push({...k,id:S,position:{x:k.position.x+h,y:k.position.y},selected:!1,data:{...w,isEditing:!1,isEditingResponse:!1,isLoading:!1}})}const b=[],y=new Set;for(const k of s){const S=m.get(k.source),w=m.get(k.target);if(!S||!w||S===w)continue;const C=`${S}→${w}`;y.has(C)||(y.add(C),b.push({...k,id:`e-${In()}`,source:S,target:w,selected:!1}))}return a.pushHistory(),se.setState(k=>{const S=[...k.nodes,...p],w=[...k.edges,...b];return{nodes:rr(S,w),edges:w}}),{copiedNodes:p.length,collapsedRuns:e.length,distillIds:x}}let ul=0;function zre(){ul++,pe.getState().setCondenseRun({status:"idle",current:0,total:0,streaming:""})}async function Bre(e,t,n){if(e.length===0)return;const a=++ul,r=pe.getState(),s=se.getState().nodes.map(o=>o.id);r.setCondenseRun({status:"building",current:0,total:e.length,streaming:"",error:void 0,originalIds:s,distillIds:[]});try{const o=[];let c="";for(let h=0;h<e.length;h++){if(ul!==a)return;pe.getState().setCondenseRun({current:h+1,streaming:""});const m=await Lre(e[h],t,n,p=>{ul===a&&pe.getState().setCondenseRun({streaming:p})},c||void 0);if(ul!==a)return;o.push(m),c=`${c}
|
|
781
|
-
${m}`.slice(-1500)}const d=Pre(e,o,t);if(ul!==a)return;pe.getState().setCondenseRun({status:"done",streaming:"",distillIds:d.distillIds}),Qe("success",De("condense.copyReady"),8e3,{label:De("tmap.export"),run:()=>pe.getState().setThoughtMapOpen(!0)})}catch(o){if(ul!==a)return;pe.getState().setCondenseRun({status:"error",error:o instanceof Error?o.message:String(o)})}}function Hre({onFocusSegment:e}){const t=pe(P=>P.condenseDialogOpen),n=pe(P=>P.condenseRun),a=zt(),r=Ra(P=>P.lang),s=se(P=>P.nodes),o=se(P=>P.edges),[c,d]=L.useState(0),h=L.useMemo(()=>t&&n.status==="idle"?Ore(s,o):[],[t,n.status,s,o,c]),m=pe(P=>P.selectedModel),p=_l()?.models??[],[x,b]=L.useState(""),[y,k]=L.useState(new Set),[S,w]=L.useState(null),C=L.useRef(null),T=P=>{const V=C.current?.getBoundingClientRect();if(!V)return;const J=P.clientX-V.left,H=P.clientY-V.top,F=W=>w({x:Math.min(window.innerWidth-120,Math.max(0,W.clientX-J)),y:Math.min(window.innerHeight-80,Math.max(0,W.clientY-H))}),B=()=>{window.removeEventListener("mousemove",F),window.removeEventListener("mouseup",B)};window.addEventListener("mousemove",F),window.addEventListener("mouseup",B)},N=P=>P.nodeIds.join(","),D=h.filter(P=>!y.has(N(P))),O=D.reduce((P,V)=>P+V.saving,0),M=()=>{pe.getState().setCondenseDialogOpen(!1),pe.getState().setCondenseHighlightIds([])};if(L.useEffect(()=>{if(!t)return;const P=V=>{V.key==="Escape"&&M()};return window.addEventListener("keydown",P),()=>window.removeEventListener("keydown",P)},[t]),!t)return null;const _=()=>{D.length!==0&&Bre(D,r,x||m||void 0)},R=()=>{se.getState().setArchived(n.originalIds,!0),Qe("success",a("condense.originalArchived")),pe.getState().setCondenseRun({status:"idle",current:0,total:0,streaming:"",originalIds:[],distillIds:[]}),M()},G=()=>{const V=se.getState().nodes.filter(J=>n.distillIds.includes(J.id));V.length&&e?.(V.map(J=>J.id))};return Qa.createPortal(u.jsxs("div",{ref:C,className:"fixed z-[70] bg-surface border border-line rounded-2xl shadow-2xl w-[400px] max-h-[72vh] flex flex-col p-4 animate-fade-in",style:S?{left:S.x,top:S.y}:{left:80,bottom:16},"data-condense-dialog":!0,onClick:P=>P.stopPropagation(),children:[u.jsxs("div",{className:"flex items-start justify-between mb-1 cursor-grab active:cursor-grabbing select-none",onMouseDown:T,children:[u.jsxs("div",{className:"text-sm font-semibold text-ink flex items-center gap-2",children:[u.jsx(vm,{size:15,strokeWidth:1.75,className:"text-accent"})," ",a("condense.title")]}),u.jsx("button",{onClick:M,title:n.status==="building"?a("condense.runningBg"):void 0,className:"text-ink-faint hover:text-ink rounded-lg w-7 h-7 flex items-center justify-center hover:bg-wash transition-colors",children:u.jsx(mn,{size:15})})]}),n.status==="idle"&&u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"flex items-center justify-between gap-2 mb-2",children:[u.jsx("p",{className:"text-2xs text-ink-faint leading-snug",title:a("condense.copyIntroFull"),children:a("condense.copyIntroShort")}),u.jsxs("button",{onClick:()=>d(P=>P+1),title:a("condense.rescanTitle"),"data-condense-rescan":!0,className:"text-2xs text-ink-muted hover:text-accent px-2 py-1 rounded-lg hover:bg-wash transition-colors shrink-0",children:["⟳ ",a("condense.rescan")]})]}),u.jsx("p",{className:"text-2xs text-ink-faint mb-2","data-condense-scanline":!0,children:We(a("condense.scanLine"),{turns:String(s.filter(P=>P.data.response&&!P.data.stepKind).length),n:String(h.length)})}),u.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[u.jsx("label",{className:"text-2xs text-ink-muted shrink-0",children:a("condense.modelLabel")}),u.jsxs("select",{value:x,onChange:P=>b(P.target.value),"data-condense-model":!0,className:"text-xs bg-wash text-ink rounded-lg px-2 py-1.5 focus:outline-none focus:ring-1 focus:ring-accent/40 max-w-[220px] truncate",children:[u.jsx("option",{value:"",children:We(a("condense.modelGlobal"),{model:m||"auto"})}),p.map(P=>u.jsx("option",{value:P.id,children:P.id},P.id))]})]}),h.length===0?u.jsx("p",{className:"text-xs text-ink-muted py-4",children:a("condense.segNothing")}):u.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto space-y-2 pr-1",children:h.map(P=>{const V=N(P),J=!y.has(V);return u.jsxs("div",{"data-condense-item":!0,className:`border rounded-xl p-3 transition-colors cursor-pointer ${J?"border-accent/60 bg-accent/5":"border-line opacity-60"}`,onClick:()=>{pe.getState().setCondenseHighlightIds(P.nodeIds),e?.(P.nodeIds)},children:[u.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[u.jsx("input",{type:"checkbox",checked:J,onClick:H=>H.stopPropagation(),onChange:()=>k(H=>{const F=new Set(H);return F.has(V)?F.delete(V):F.add(V),F}),className:"accent-[var(--color-accent)]","data-condense-check":!0}),u.jsx("span",{className:"text-2xs text-ink-faint font-mono",children:We(a("condense.segMeta"),{n:String(P.nodeIds.length),tok:String(P.saving)})})]}),u.jsx("p",{className:"text-xs text-ink mt-1 leading-snug line-clamp-2",children:P.headQuestion})]},V)})}),h.length>0&&u.jsxs("div",{className:"flex items-center justify-between gap-2 pt-3 mt-2 border-t border-line",children:[u.jsx("span",{className:"text-2xs text-ink-faint",children:a("condense.copyFootnote")}),u.jsxs("button",{onClick:_,disabled:D.length===0,"data-condense-build":!0,className:"text-xs bg-accent text-white px-3.5 py-2 rounded-lg disabled:opacity-40 transition-colors flex items-center gap-1.5 shrink-0",children:[u.jsx(Hs,{size:13,strokeWidth:1.75}),We(a("condense.buildCopy"),{n:String(D.length),tok:String(O)})]})]})]}),n.status==="building"&&u.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",children:[u.jsxs("div",{className:"flex items-center gap-2 text-sm text-ink-muted mb-1.5",children:[u.jsx(Un,{size:15,className:"animate-spin text-accent"}),We(a("condense.buildingRun"),{i:String(n.current),n:String(n.total)})]}),u.jsx("p",{className:"text-2xs text-ink-faint mb-2",children:a("condense.runningBg")}),n.streaming&&u.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto text-2xs text-ink-muted bg-wash rounded-lg p-2.5 whitespace-pre-wrap leading-relaxed","data-condense-streaming":!0,children:n.streaming}),u.jsx("button",{onClick:()=>zre(),"data-condense-cancel":!0,className:"self-start mt-3 text-xs text-ink-muted hover:text-red-600 px-3 py-1.5 rounded-lg hover:bg-wash transition-colors",children:a("common.cancel")})]}),n.status==="error"&&u.jsxs("div",{className:"flex flex-col gap-2 py-3",children:[u.jsx("p",{className:"text-2xs text-red-600",children:n.error}),u.jsx("button",{onClick:()=>pe.getState().setCondenseRun({status:"idle",error:void 0}),className:"self-start text-xs text-ink-muted hover:text-ink px-3 py-1.5 rounded-lg hover:bg-wash transition-colors",children:a("common.cancel")})]}),n.status==="done"&&u.jsxs("div",{className:"flex flex-col gap-3 py-3",children:[u.jsxs("div",{className:"flex items-center gap-2 text-sm text-green-700",children:[u.jsx(ri,{size:16})," ",a("condense.copyReady")]}),u.jsx("p",{className:"text-2xs text-ink-faint leading-relaxed",children:a("condense.copyCompareHint")}),u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx("button",{onClick:G,className:"text-xs bg-accent/10 text-accent hover:bg-accent/20 px-3 py-2 rounded-lg transition-colors",children:a("condense.viewCopy")}),u.jsxs("button",{onClick:R,"data-condense-archive-original":!0,className:"text-xs border border-line text-ink-muted hover:text-ink hover:bg-wash px-3 py-2 rounded-lg transition-colors flex items-center gap-1.5",children:[u.jsx(zo,{size:13,strokeWidth:1.75})," ",a("condense.archiveOriginal")]})]}),u.jsx("button",{onClick:()=>{pe.getState().setCondenseRun({status:"idle"}),M()},className:"self-start text-xs text-ink-faint hover:text-ink transition-colors",children:a("common.close")})]})]}),document.body)}function OE(){const e=Ra(n=>n.lang),t=Ra(n=>n.setLang);return u.jsx("div",{className:"flex items-center bg-card/90 backdrop-blur border border-line rounded-lg shadow-sm overflow-hidden",children:["en","zh"].map(n=>u.jsx("button",{onClick:()=>t(n),className:`px-2 h-8 text-2xs font-medium transition-colors ${e===n?"bg-accent text-white":"text-ink-muted hover:bg-wash"}`,children:n==="en"?"EN":"中"},n))})}function da({x:e,y:t,w:n=34,h:a=20,tone:r="plain"}){return u.jsxs("g",{children:[u.jsx("rect",{x:e,y:t,width:n,height:a,rx:4,fill:"white",stroke:rt.line,strokeWidth:1}),r!=="plain"&&u.jsx("rect",{x:e,y:t,width:2.5,height:a,rx:1.25,fill:r==="accent"?rt.accent:rt.warm})]})}const Ure={1:u.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[u.jsx(da,{x:43,y:32,tone:"accent"}),u.jsx("circle",{cx:60,cy:28,r:2.5,fill:rt.accent})]}),2:u.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[u.jsx(da,{x:43,y:12,tone:"accent"}),u.jsx("line",{x1:60,y1:32,x2:60,y2:50,stroke:rt.accent,strokeWidth:1.75}),u.jsx("path",{d:"M 57 47 L 60 52 L 63 47 Z",fill:rt.accent}),u.jsx(da,{x:43,y:52})]}),3:u.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[u.jsx(da,{x:20,y:12,tone:"accent"}),u.jsx("line",{x1:37,y1:32,x2:37,y2:50,stroke:rt.accent,strokeWidth:1.75}),u.jsx("path",{d:"M 34 47 L 37 52 L 40 47 Z",fill:rt.accent}),u.jsx(da,{x:20,y:52}),u.jsx("rect",{x:26,y:58,width:14,height:3,rx:1.5,fill:rt.trace,opacity:.6}),u.jsx("path",{d:"M 54 62 C 64 62, 62 40, 72 38",stroke:rt.warm,strokeWidth:1.75,fill:"none",strokeDasharray:"4 3"}),u.jsx("path",{d:"M 69 35.5 L 74 38 L 70 41 Z",fill:rt.warm}),u.jsx(da,{x:74,y:28,tone:"warm"})]}),4:u.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[u.jsx(da,{x:43,y:10,tone:"accent"}),u.jsx("line",{x1:60,y1:30,x2:60,y2:52,stroke:rt.line,strokeWidth:1.75,strokeDasharray:"3 3"}),u.jsx("circle",{cx:60,cy:41,r:7,fill:"white",stroke:"#FCA5A5",strokeWidth:1}),u.jsx("line",{x1:57,y1:38,x2:63,y2:44,stroke:"#EF4444",strokeWidth:1.5,strokeLinecap:"round"}),u.jsx("line",{x1:63,y1:38,x2:57,y2:44,stroke:"#EF4444",strokeWidth:1.5,strokeLinecap:"round"}),u.jsx(da,{x:43,y:54})]}),5:u.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[u.jsx(da,{x:12,y:14,w:40,h:15}),u.jsx("circle",{cx:14,cy:16,r:4.5,fill:"#D64533"}),u.jsx("text",{x:14,y:18.4,textAnchor:"middle",fontSize:6,fontWeight:700,fill:"white",children:"✕"}),u.jsx(da,{x:12,y:35,w:40,h:15}),u.jsx("circle",{cx:14,cy:37,r:4.5,fill:rt.accent}),u.jsx("text",{x:14,y:39.4,textAnchor:"middle",fontSize:6,fontWeight:700,fill:"white",children:"⚖"}),u.jsx(da,{x:12,y:56,w:40,h:15}),u.jsx("circle",{cx:14,cy:58,r:4.5,fill:"#C9A227"}),u.jsx("text",{x:14,y:60.4,textAnchor:"middle",fontSize:6,fontWeight:700,fill:"white",children:"?"}),u.jsx("path",{d:"M 62 42 L 74 42",stroke:rt.inkMuted,strokeWidth:1.2}),u.jsx("path",{d:"M 71.5 39.5 L 76 42 L 71.5 44.5 Z",fill:rt.inkMuted}),u.jsx("rect",{x:86,y:14,width:13,height:13,rx:4.5,fill:"#D64533"}),u.jsx("line",{x1:92.5,y1:27,x2:92.5,y2:35,stroke:rt.accent,strokeWidth:1.4}),u.jsx("rect",{x:86,y:35,width:13,height:13,rx:4.5,fill:rt.accent}),u.jsx("line",{x1:92.5,y1:48,x2:92.5,y2:56,stroke:rt.accent,strokeWidth:1.4}),u.jsx("rect",{x:86,y:56,width:13,height:13,rx:4.5,fill:"#C9A227"})]}),7:u.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[u.jsx("rect",{x:14,y:12,width:30,height:22,rx:3,fill:"#FEF3C7",stroke:"#F59E0B",strokeWidth:.8}),u.jsx("line",{x1:29,y1:34,x2:29,y2:50,stroke:rt.accent,strokeWidth:1.75}),u.jsx("path",{d:"M 26 47 L 29 52 L 32 47 Z",fill:rt.accent}),u.jsx(da,{x:12,y:52,tone:"accent"}),u.jsx("path",{d:"M 100 22 C 80 22, 70 55, 50 60",stroke:rt.accent,strokeWidth:1.75,fill:"none",strokeDasharray:"5 3"}),u.jsx("path",{d:"M 52 57 L 47 61 L 52 64 Z",fill:rt.accent}),u.jsx(da,{x:82,y:12})]}),9:u.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[u.jsx(da,{x:43,y:10,tone:"accent"}),u.jsx("line",{x1:60,y1:30,x2:60,y2:48,stroke:rt.accent,strokeWidth:1.75}),u.jsx("path",{d:"M 57 45 L 60 50 L 63 45 Z",fill:rt.accent}),u.jsx(da,{x:43,y:50}),u.jsx("circle",{cx:75,cy:53,r:4,fill:"#F59E0B"}),u.jsx("path",{d:"M 73.5 53 a 1.5 1.5 0 1 1 3 0",stroke:"white",strokeWidth:.9,fill:"none"}),u.jsx("text",{x:60,y:80,textAnchor:"middle",fontSize:7,fill:rt.inkMuted,fontFamily:"JetBrains Mono Variable, monospace",children:"v2/2 · replay"})]}),6:u.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[u.jsx("rect",{x:8,y:18,width:14,height:48,rx:4,fill:"white",stroke:rt.line,strokeWidth:1}),u.jsx("circle",{cx:15,cy:27,r:3,fill:rt.accent,opacity:.7}),u.jsx("rect",{x:12,y:37,width:6,height:6,rx:1,fill:"#F59E0B",opacity:.8}),u.jsx("rect",{x:12,y:49,width:6,height:6,rx:1,fill:rt.inkMuted,opacity:.5}),u.jsx("rect",{x:38,y:14,width:32,height:24,rx:3,fill:"#FEF3C7",stroke:"#F59E0B",strokeWidth:.8}),u.jsx("rect",{x:80,y:14,width:32,height:24,rx:3,fill:"white",stroke:rt.line,strokeWidth:1}),u.jsx("circle",{cx:88,cy:22,r:3,fill:rt.line}),u.jsx("path",{d:"M 82 34 L 92 26 L 100 32 L 108 24",stroke:rt.inkMuted,strokeWidth:1.2,fill:"none"}),u.jsx("text",{x:72,y:62,textAnchor:"middle",fontSize:7,fill:rt.inkMuted,fontFamily:"JetBrains Mono Variable, monospace",children:"⌘V paste anything"})]}),8:u.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[u.jsx("rect",{x:8,y:8,width:70,height:52,rx:3,fill:rt.accent,opacity:.06,stroke:rt.accent,strokeWidth:.8,strokeDasharray:"3 2"}),u.jsx(da,{x:14,y:14,w:26,h:16}),u.jsx(da,{x:46,y:14,w:26,h:16}),u.jsx(da,{x:30,y:38,w:26,h:16}),u.jsx("path",{d:"M 40 46 C 60 50, 70 50, 84 48",stroke:rt.accent,strokeWidth:1.4,fill:"none"}),u.jsx("path",{d:"M 59 30 C 70 36, 76 42, 84 46",stroke:rt.accent,strokeWidth:1.4,fill:"none"}),u.jsx("path",{d:"M 43 22 C 66 24, 76 38, 84 44",stroke:rt.accent,strokeWidth:1.4,fill:"none"}),u.jsx(da,{x:84,y:40,w:28,h:18,tone:"accent"})]}),10:u.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[u.jsx(da,{x:10,y:18,w:30,h:17,tone:"accent"}),u.jsx("line",{x1:25,y1:35,x2:25,y2:48,stroke:rt.accent,strokeWidth:1.5}),u.jsx("path",{d:"M 22.5 45.5 L 25 50 L 27.5 45.5 Z",fill:rt.accent}),u.jsx(da,{x:10,y:50,w:30,h:17}),u.jsx("path",{d:"M 46 42 L 60 42",stroke:rt.inkMuted,strokeWidth:1.2}),u.jsx("path",{d:"M 57.5 39.5 L 62 42 L 57.5 44.5 Z",fill:rt.inkMuted}),u.jsx("rect",{x:68,y:20,width:44,height:44,rx:5,fill:"white",stroke:rt.line,strokeWidth:1}),u.jsx(da,{x:74,y:30,w:20,h:11,tone:"accent"}),u.jsx(da,{x:88,y:46,w:20,h:11}),u.jsx("rect",{x:76,y:14,width:28,height:11,rx:5.5,fill:"#2B2A28"}),u.jsx("circle",{cx:84,cy:19.5,r:2.6,fill:"none",stroke:"white",strokeWidth:1}),u.jsx("circle",{cx:84,cy:19.5,r:.9,fill:"white"}),u.jsx("text",{x:90,y:22,fontSize:6,fill:"white",fontFamily:"JetBrains Mono Variable, monospace",children:"view"}),u.jsx("text",{x:60,y:78,textAnchor:"middle",fontSize:7,fill:rt.inkMuted,fontFamily:"JetBrains Mono Variable, monospace",children:"#view= · read-only"})]})},RE={4:"prune",5:"map",6:"reading",7:"ref"};function Fre(){const e=pe(h=>h.tutorialOpen),t=pe(h=>h.setTutorialOpen);L.useEffect(()=>{if(!e)return;const h=m=>{m.key==="Escape"&&t(!1)};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[e,t]);const n=zt(),a=Ra(h=>h.lang),[r,s]=L.useState(0),o=[{label:n("tutorial.pg1"),steps:[1,2,3]},{label:n("tutorial.pg2"),steps:[4,5]},{label:n("tutorial.pg3"),steps:[6,7]},{label:n("tutorial.pg4"),steps:[8,9,10]}],c=r===o.length-1;if(L.useEffect(()=>{if(!e)return;s(0);const h=m=>{m.key==="ArrowRight"&&s(p=>Math.min(p+1,o.length-1)),m.key==="ArrowLeft"&&s(p=>Math.max(p-1,0))};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[e]),!e)return null;const d=o[r];return u.jsx("div",{className:"fixed inset-0 z-[95] bg-black/25 flex items-center justify-center animate-fade-in p-6",onClick:()=>t(!1),children:u.jsxs("div",{className:"bg-card border border-line rounded-2xl shadow-2xl w-[min(980px,94vw)] flex flex-col",onClick:h=>h.stopPropagation(),children:[u.jsxs("div",{className:"flex items-start justify-between px-7 pt-5 pb-1 shrink-0",children:[u.jsxs("div",{className:"flex items-baseline gap-3 min-w-0",children:[u.jsx("h2",{className:"text-lg font-semibold text-ink tracking-tight shrink-0",children:n("tutorial.title")}),u.jsx("p",{className:"text-xs text-ink-faint truncate",children:n("tutorial.subtitle")})]}),u.jsx("button",{onClick:()=>t(!1),className:"text-ink-faint hover:text-ink transition-colors mt-1",children:u.jsx(mn,{size:18,strokeWidth:1.75})})]}),u.jsxs("div",{className:"px-7 pt-3 pb-1 min-h-[380px]",children:[u.jsx("p",{className:"text-2xs font-semibold text-accent mb-3 uppercase tracking-wider",children:d.label}),u.jsx("div",{className:`grid gap-4 ${d.steps.length===3?"grid-cols-1 sm:grid-cols-3":"grid-cols-1 sm:grid-cols-2"}`,children:d.steps.map(h=>u.jsxs("div",{className:"bg-surface border border-line/70 rounded-xl p-4 flex flex-col animate-fade-in",children:[u.jsx("div",{className:"w-full aspect-[120/72] bg-card rounded-lg border border-line/60 mb-3 overflow-hidden",children:RE[h]?u.jsx("img",{src:`/thoughtdag/tutorial/${RE[h]}-${a}.gif`,loading:"lazy",alt:"",className:"w-full h-full object-cover"}):Ure[h]}),u.jsx("h3",{className:"text-[13px] font-semibold text-ink leading-snug",children:n(`tutorial.step${h}.title`)}),u.jsx("p",{className:"text-xs text-ink-muted leading-relaxed mt-1.5",children:n(`tutorial.step${h}.desc`)})]},h))})]}),u.jsxs("div",{className:"px-7 py-4 shrink-0 flex items-center justify-between",children:[u.jsx("button",{onClick:()=>s(h=>Math.max(h-1,0)),disabled:r===0,className:"w-8 h-8 rounded-lg border border-line text-ink-muted hover:bg-wash transition-colors flex items-center justify-center disabled:opacity-25 disabled:cursor-not-allowed",children:u.jsx(jf,{size:16,strokeWidth:1.75})}),u.jsx("div",{className:"flex items-center gap-2",children:o.map((h,m)=>u.jsx("button",{onClick:()=>s(m),className:`h-2 rounded-full transition-all ${m===r?"w-6 bg-accent":"w-2 bg-line hover:bg-line-strong"}`,"aria-label":`${m+1}/${o.length}`},m))}),c?u.jsx("button",{onClick:()=>t(!1),className:"text-xs bg-accent hover:bg-accent-strong text-white px-5 py-2 rounded-lg transition-colors",children:n("tutorial.close")}):u.jsx("button",{onClick:()=>s(h=>h+1),className:"w-8 h-8 rounded-lg border border-line text-ink-muted hover:bg-wash transition-colors flex items-center justify-center",children:u.jsx(Fi,{size:16,strokeWidth:1.75})})]}),u.jsxs("div",{className:"px-7 py-2.5 border-t border-line/60 shrink-0 flex flex-wrap gap-x-4 gap-y-1 text-2xs text-ink-faint font-mono",children:[u.jsxs("span",{children:[n("shortcut.panKeys")," ",n("shortcut.pan")]}),u.jsxs("span",{children:[n("shortcut.marqueeKeys")," ",n("shortcut.marquee")]}),u.jsxs("span",{children:["⌘","F ",n("shortcut.search")]}),u.jsxs("span",{children:["Space ",n("shortcut.collapse")]}),u.jsxs("span",{children:["R ",n("shortcut.regenerate")]}),u.jsxs("span",{children:["↑↓←→"," ",n("shortcut.navigate")]}),u.jsxs("span",{children:["⌘","Z/","⇧","⌘","Z ",n("shortcut.undo")]}),u.jsxs("span",{children:["Del ",n("shortcut.delete")]}),u.jsxs("span",{children:["Esc ",n("shortcut.escape")]})]})]})})}const qre=new URLSearchParams(window.location.search),Pi=qre.get("dv"),df="https://chenxiachan.github.io/thoughtdag/docs",C9=[{version:"0.4.16",date:"2026-09-17",announce:!1,lead:{zh:"分区框:两个只是部分重叠的框不再互相收编。拖动大框时,重叠的小框和它自己的节点留在原地;拖动和一键排版现在用同一条成员规则,普通节点按中心点归属,框只有完整落在另一个框里才算它的成员(#40,感谢 @nanami-0713)。DeepSeek Harness 插件:「插件有新版本」提示复制的命令带上具体版本号,发版当天也能立刻装到新版。",en:"Frames: two frames that merely overlap no longer own each other. Dragging the larger one leaves the overlapping smaller frame and its own nodes in place; dragging and auto layout now share one membership rule, nodes by centre and a frame only when it lies fully inside another (#40, thanks @nanami-0713). DeepSeek Harness plugin: the update hint now copies a command naming the exact version, so a release installs on its first day too."},items:[]},{version:"0.4.15",date:"2026-09-15",announce:!1,lead:{zh:"分区框三件事:一键排版后,框跟着框内的节点重新包好(#32);拖动外框会带动嵌套在里面的框;重叠时小框叠在大框上面,标题栏不再被盖住。三项均来自 @hexu321。DeepSeek Harness 插件:「对话 | 思维图」切换器移进会话标题栏,不再遮挡标题;返回按钮居中,画布右上的工具栏保持可见;从画布切回会话的跳转修好了(#30,来自 @nanami-0713)。插件重新在 npm 上发布,安装命令恢复为包名。",en:"Frames, three fixes: after auto layout a frame re-wraps the nodes it held (#32); dragging an outer frame carries the frames nested inside it; where frames overlap, the smaller one stacks on top so its title bar stays reachable. All three by @hexu321. DeepSeek Harness plugin: the 对话 | 思维图 switch moves into the session header and no longer covers the title; the back button sits top centre, clear of the canvas toolbar; jumping from the canvas back to a session works again (#30, by @nanami-0713). The plugin is back on npm and the install command is the package name again."},items:[]},{version:"0.4.14",date:"2026-09-11",announce:!1,lead:{zh:"插件的「有新版本」提示现在复制 dsh plugin --profile web add dsh-thoughtdag@latest,这条命令对从 npm 装和从 Release 文件装的用户都有效(update 对文件安装无效)。其余同 0.4.13。",en:"The plugin's update hint now copies dsh plugin --profile web add dsh-thoughtdag@latest, which works for installs from npm and from a release file alike (update does nothing for a file install). Otherwise the same as 0.4.13."},items:[]},{version:"0.4.13",date:"2026-09-11",announce:!1,lead:{zh:"修复:DeepSeek Harness 插件里,模型选择器丢失了「Harness · 模型」这一组 Agent 条目(0.4.11 起,机器上没装 Pi、Codex 等命令行时整组消失)。原因是思维图把 Harness 给的条目当成本机命令行的探测结果替换掉了,现在只替换命令行报来的那几种。插件里「如何使用」的教程动图也能显示了(#35,感谢 @Moya-Doc)。",en:`Fix: inside the DeepSeek Harness plugin, the model picker lost the "Harness · model" agent entries (since 0.4.11; with no Pi or Codex CLI on the machine the whole group vanished). The canvas had been replacing the harness's entries with the local CLI probe; now only the entries the CLIs report get replaced. The tutorial gifs inside the plugin load again (#35, thanks @Moya-Doc).`},items:[]},{version:"0.4.12",date:"2026-09-10",announce:!1,lead:{zh:"DeepSeek Harness 插件里,Agent 子节点现在续接父节点的会话;同一父节点下的第二个分支从父节点那一轮分叉出自己的会话,preset 的会话状态不再在每个子节点重头开始(#28、#29)。插件的构建脚本在 Windows 上也能跑了(#24、#26)。桌面版本次只同步版本号。",en:"Inside the DeepSeek Harness plugin, an agent child node now continues its parent's session, and a second branch off the same parent forks its own session at that parent's turn, so a preset's session state no longer restarts at every child (#28, #29). The plugin's build script runs on Windows too (#24, #26). The desktop app only moves its version number."},items:[]},{version:"0.4.11",date:"2026-09-08",announce:!1,lead:{zh:"性能优化:启动更快,后台更省,多个工具调用并行时更稳;300 节点以上的画布实测流畅。ThoughtDAG 现在可以用 Claude Code、Codex、Pi 作为节点的 Agent 运行时,处于测试阶段。",en:"Performance: faster launch, lighter in the background, steadier when several tool calls run in parallel; canvases past 300 nodes measured smooth. ThoughtDAG can now run a node through Claude Code, Codex or Pi as its agent runtime, in testing."},items:[]},{version:"0.4.10",date:"2026-09-07",announce:!1,lead:{zh:"Agent 执行预览继续:Codex 加入,和 Pi 一样在画布里带工具作答;这条通道现在在桌面版、本地网页版和 DeepSeek Harness 插件里都可用;插件里的 Harness Agent 按模型平铺;插件有新版本时画布会提示。",en:"Agent runs, preview continued: Codex joins Pi, answering with tools right from the canvas; the lane now works in the desktop app, the local web app and the DeepSeek Harness plugin alike; inside the plugin the Harness agent lists one entry per model; the canvas tells you when a newer plugin is out."},items:[]},{version:"0.4.9",date:"2026-09-07",announce:!1,lead:{zh:"Agent 执行预览:桌面版的模型选择器多了「Agent 执行」组,装了 Pi 的话可以直接在画布里让它带工具作答,轨迹、足迹、审批和提问都落在节点上,工作目录在顶栏可见可改。正式版会连同 Claude Code 与 Codex 一起发布。DeepSeek Harness 插件里的审批卡片同步更新。",en:'Agent runs, preview: the desktop picker gains an "Agent runs" group; with Pi installed, a question runs through it with tools right from the canvas, and the trace, footprints, approvals and questions land on the node, with the working directory visible on the toolbar. The full release will arrive together with Claude Code and Codex. The approval card inside the DeepSeek Harness plugin is updated alike.'},items:[]},{version:"0.4.8",date:"2026-09-07",announce:!1,lead:{zh:"DeepSeek Harness 插件在 Windows 上能打开了:静态资源和会话目录的路径守卫此前只认正斜杠,Windows 用户看到的是一片 403。感谢 GitHub 上的报告(#23)。桌面版本次只同步版本号。",en:"The DeepSeek Harness plugin now opens on Windows: the path guards for static assets and session directories only accepted forward slashes, so Windows users saw nothing but 403s. Thanks to the report on GitHub (#23). The desktop app only moves its version number this time."},items:[]},{version:"0.4.7",date:"2026-09-07",announce:!1,lead:{zh:"DeepSeek Harness 插件里,Agent 需要你批准的操作现在直接出现在节点上:工具、命令、理由,允许一次或拒绝,决定留在节点记录里。桌面版本次只同步版本号。",en:"Inside the DeepSeek Harness plugin, an action the agent needs approved now appears on the node itself: tool, command, reason, allow once or reject, and the decision stays in the node's record. The desktop app only moves its version number this time."},items:[]},{version:"0.4.6",date:"2026-09-06",announce:!0,lead:{zh:"🎉 Pi 的会话进了对话地图,「⋯」菜单里多了更新历史,随时能回看每一版改了什么。",en:"🎉 Pi sessions join the Session Atlas, and the ⋯ menu gains a release history, so what every version changed is one click away."},items:[{title:{zh:"Pi 的会话也在地图上了",en:"Pi sessions are on the map"},body:{zh:"本地 Pi 会话按项目聚在一起,打开就是一张图。Pi 里的每次分叉在图上就是一条支线,不再压成一条直线。命令行 why 和 MCP 也同步认识 Pi 留下的文件足迹。",en:"Local Pi sessions group by project and open as a graph. Every fork you made in Pi shows up as a branch instead of being flattened into one line. The why command and MCP index Pi's file footprints too."},link:{label:{zh:"怎么用",en:"How it works"},href:`${df}/zh/guides/session-atlas`}},{title:{zh:"更新历史,随时补看",en:"Release history, whenever you like"},body:{zh:"右上「⋯」菜单,「如何使用」下面。每个版本改了什么都在这里,从新到旧,当前版本有标记。",en:"In the ⋯ menu, under How it works: what each release changed, newest first, with the version you are running marked."}}]},{version:"0.4.5",date:"2026-09-06",announce:!0,lead:{zh:"🎉 这是 ThoughtDAG 到目前为止最大的一次升级:散在各个 Agent 里的对话接成了一张地图,能从画布里查,还能直接在 DeepSeek Harness 里用。四件新东西,都值得试一试。",en:"🎉 The biggest ThoughtDAG release so far: the conversations scattered across your agents become one map, you can query them, and it all runs inside DeepSeek Harness. Four new things, each worth a try."},items:[{title:{zh:"跨 Agent 的对话地图,终于连成一张",en:"Session Atlas: all your agents, one map"},body:{zh:"Claude Code、Codex 和 DeepSeek Harness 的本地会话按项目文件夹聚在一起,点开就是一张图,随对话实时生长。",en:"Local Claude Code, Codex and DeepSeek Harness sessions, grouped by project; open one as a graph and it follows the conversation live."},link:{label:{zh:"怎么用",en:"How it works"},href:`${df}/zh/guides/session-atlas`}},{title:{zh:"命令行 why:一条命令找回塑造文件的那些对话",en:"thoughtdag why: one command finds the conversations that shaped a file"},body:{zh:"npx thoughtdag why <文件> 列出哪些轮次读过、改过它,当时问了什么、改了什么;find 按原话搜,MCP 让 Agent 自己来查。",en:"npx thoughtdag why <file> lists the turns that read or changed it, what was asked and what changed; find searches verbatim; MCP lets your agent ask."},link:{label:{zh:"命令与 MCP",en:"CLI and MCP"},href:`${df}/zh/guides/why-layer`}},{title:{zh:"DeepSeek Harness 插件上线",en:"DeepSeek Harness plugin is live"},body:{zh:'dsh plugin --profile web add dsh-thoughtdag,Harness 的网页里多一个"思维图"视图:在画布上提问、让 Harness 的 Agent 带工具作答,why 也成了它的原生工具。',en:"dsh plugin --profile web add dsh-thoughtdag adds a canvas view to the Harness web UI: ask from the canvas, let its agent answer with tools, and why becomes a native tool there."},link:{label:{zh:"插件说明",en:"Plugin README"},href:"https://github.com/chenxiachan/thoughtdag/tree/main/dsh#readme"}},{title:{zh:"文档站上线",en:"The docs site is live"},body:{zh:"概念、任务指南、命令字典和隐私说明各有一页,中英文对照。感谢一路同行,欢迎来 Discussions 说说你怎么用它。",en:"Concepts, task guides, the command dictionary and the privacy notes, each on its own page, in both languages. Thank you for coming this far with us; tell us how you use it in Discussions."},link:{label:{zh:"打开文档",en:"Open the docs"},href:`${df}/zh/`}}]},{version:"0.4.4",date:"2026-09-04",announce:!1,lead:{zh:"DeepSeek Harness 成为对话地图的内置来源:它的 zstd 日志由桌面壳逐帧解码,每条消息一个节点,工具调用与结果配对成附件。",en:"DeepSeek Harness becomes a built-in Atlas source: the shell decodes its zstd logs frame by frame, one node per message, tool calls paired with their results as attachments."},items:[]},{version:"0.4.3",date:"2026-09-03",announce:!1,lead:{zh:"深链接可以直达某一轮,画布可以按稳定 id 打开;子 Agent 的会话文件不再打扰实时监听。",en:"A deep link can land on a turn and a canvas opens by its stable id; subagent session files no longer disturb the live watcher."},items:[]},{version:"0.4.2",date:"2026-09-02",announce:!1,lead:{zh:"镜像节点列出那一轮碰过的文件(✏️ 改过、📖 读过),预览用结论而不是开头;子 Agent 的会话作为子线程识别,报告折回发起它的那一轮。",en:"A mirrored node lists the files its turn touched (✏️ edited, 📖 read) and previews the conclusion rather than the opening line; subagent files are recognized as sub-threads and their reports fold into the launching turn."},items:[]},{version:"0.4.1",date:"2026-09-01",announce:!1,lead:{zh:"Agent 对话地图首发:本地 Claude Code 与 Codex 的会话按项目文件夹聚成一张图,一键接入,随对话实时生长。",en:"Session Atlas debuts: local Claude Code and Codex sessions group by project folder into one map, connect in one click, and grow with the conversation."},items:[]}];function Ab(e,t){const n=e.split(".").map(r=>parseInt(r,10)||0),a=t.split(".").map(r=>parseInt(r,10)||0);for(let r=0;r<Math.max(n.length,a.length);r++){const s=(n[r]??0)-(a[r]??0);if(s!==0)return s}return 0}function vx(e,t){return C9.filter(n=>n.announce&&Ab(n.version,t)<=0&&(e===null||Ab(n.version,e)>0))}const Nb="thoughtdag.whatsNewSeen",Wre=new URLSearchParams(window.location.search);function Vre(){if(!Pi)return[];if(Wre.get("wn")==="1")return vx(null,Pi);let t=null;try{t=localStorage.getItem(Nb)}catch{}if(t===null){let n=!1;try{n=!!(localStorage.getItem("thoughtdag.tutorialDone")||localStorage.getItem("thoughtdag.lastBackupAt"))}catch{}if(!n){try{localStorage.setItem(Nb,Pi)}catch{}return[]}return vx(null,Pi)}return t===Pi?[]:vx(t,Pi)}function _9({items:e,lang:t}){return e.length===0?null:u.jsx("ol",{className:"divide-y divide-line",children:e.map((n,a)=>u.jsxs("li",{className:"py-3 flex gap-3.5",children:[u.jsx("span",{className:"shrink-0 w-6 h-6 rounded-full bg-accent/10 text-accent text-xs font-semibold flex items-center justify-center mt-0.5",children:a+1}),u.jsxs("div",{className:"min-w-0",children:[u.jsx("div",{className:"text-sm font-medium text-ink",children:n.title[t]}),u.jsx("p",{className:"text-sm text-ink-muted leading-relaxed mt-1 [overflow-wrap:anywhere]",children:n.body[t]}),n.link&&u.jsxs("a",{href:n.link.href,target:"_blank",rel:"noreferrer",className:"inline-block mt-1.5 text-xs font-medium text-accent hover:underline",children:[n.link.label[t]," →"]})]})]},a))})}function Gre(){const[e,t]=L.useState(()=>Vre()),n=e.length>0,a=Ra(c=>c.lang),r=zt(),s=L.useRef(null),o=()=>{if(Pi)try{localStorage.setItem(Nb,Pi)}catch{}t([])};return L.useEffect(()=>{if(!n)return;s.current?.focus({preventScroll:!0});const c=d=>{d.stopPropagation(),(d.key==="Escape"||d.key==="Enter")&&o()};return window.addEventListener("keydown",c,!0),()=>window.removeEventListener("keydown",c,!0)},[n]),n?u.jsx("div",{className:"fixed inset-0 z-[100] bg-black/25 flex items-center justify-center animate-fade-in p-6",onClick:o,children:u.jsxs("div",{className:"bg-card border border-line rounded-2xl shadow-xl w-[680px] max-w-full max-h-[85vh] overflow-y-auto",onClick:c=>c.stopPropagation(),role:"dialog","aria-labelledby":"whats-new-title","data-whats-new":!0,children:[u.jsxs("div",{className:"px-6 pt-5 pb-4 border-b border-line",children:[u.jsx("div",{className:"text-2xs uppercase tracking-wide text-ink-faint",children:"ThoughtDAG"}),u.jsx("h2",{id:"whats-new-title",className:"text-base font-semibold text-ink mt-0.5",children:We(r("whatsNew.title"),{v:Pi??""})}),e.length>1&&u.jsx("p",{className:"text-xs text-ink-faint mt-1",children:r("whatsNew.multi")})]}),u.jsx("ol",{className:"px-6 divide-y divide-line",children:e.map(c=>u.jsxs("li",{className:"py-4","data-release":c.version,children:[e.length>1&&u.jsxs("div",{className:"flex items-baseline gap-2.5 mb-1.5",children:[u.jsxs("span",{className:"text-sm font-semibold text-ink tabular-nums",children:["v",c.version]}),u.jsx("span",{className:"text-xs text-ink-faint tabular-nums",children:c.date})]}),u.jsx("p",{className:"text-sm text-ink-muted leading-relaxed [overflow-wrap:anywhere]",children:c.lead[a]}),u.jsx(_9,{items:c.items,lang:a})]},c.version))}),u.jsxs("div",{className:"sticky bottom-0 bg-card px-6 py-4 border-t border-line flex items-center justify-between gap-4",children:[u.jsx("button",{onClick:()=>{o(),pe.getState().setReleaseNotesOpen(!0)},className:"text-xs text-ink-muted hover:text-ink hover:underline transition-colors","data-whats-new-all":!0,children:r("whatsNew.seeAll")}),u.jsx("button",{ref:s,onClick:o,className:"text-xs text-white px-4 py-2 rounded-lg bg-accent hover:bg-accent-strong transition-colors",children:r("whatsNew.ok")})]})]})}):null}function $re(){const e=pe(r=>r.releaseNotesOpen),t=pe(r=>r.setReleaseNotesOpen),n=Ra(r=>r.lang),a=zt();return L.useEffect(()=>{if(!e)return;const r=s=>{s.key==="Escape"&&(s.stopPropagation(),t(!1))};return window.addEventListener("keydown",r,!0),()=>window.removeEventListener("keydown",r,!0)},[e,t]),e?u.jsx("div",{className:"fixed inset-0 z-[100] bg-black/25 flex items-center justify-center animate-fade-in p-6",onClick:()=>t(!1),children:u.jsxs("div",{className:"bg-card border border-line rounded-2xl shadow-xl w-[680px] max-w-full max-h-[85vh] overflow-y-auto",onClick:r=>r.stopPropagation(),role:"dialog","aria-labelledby":"release-notes-title","data-release-notes":!0,children:[u.jsxs("div",{className:"px-6 pt-5 pb-4 border-b border-line",children:[u.jsx("div",{className:"text-2xs uppercase tracking-wide text-ink-faint",children:"ThoughtDAG"}),u.jsx("h2",{id:"release-notes-title",className:"text-base font-semibold text-ink mt-0.5",children:a("releaseNotes.title")})]}),u.jsx("ol",{className:"px-6 divide-y divide-line",children:C9.map(r=>{const s=Pi===r.version;return u.jsxs("li",{className:"py-4","data-release":r.version,children:[u.jsxs("div",{className:"flex items-baseline gap-2.5 flex-wrap",children:[u.jsxs("span",{className:"text-sm font-semibold text-ink tabular-nums",children:["v",r.version]}),u.jsx("span",{className:"text-xs text-ink-faint tabular-nums",children:r.date}),s&&u.jsx("span",{className:"text-2xs font-medium uppercase tracking-wide text-accent bg-accent/10 rounded-full px-2 py-0.5",children:a("releaseNotes.current")})]}),u.jsx("p",{className:"text-sm text-ink-muted leading-relaxed mt-1.5 [overflow-wrap:anywhere]",children:r.lead[n]}),u.jsx(_9,{items:r.items,lang:n})]},r.version)})}),u.jsx("div",{className:"sticky bottom-0 bg-card px-6 py-4 border-t border-line flex justify-end",children:u.jsx("button",{onClick:()=>t(!1),className:"text-xs text-ink px-4 py-2 rounded-lg border border-line hover:bg-wash transition-colors",children:a("common.close")})})]})}):null}const wx=e=>e.split("/").filter(Boolean).slice(-1)[0]??e;function Yre(){const e=zt(),t=pe(D=>D.selectedModel),n=rn(D=>D.activeId),a=rn(D=>D.projects),r=se(D=>D.nodes.length),[s,o]=L.useState(null),[c,d]=L.useState(null),[h,m]=L.useState(!1),[p,x]=L.useState(""),b=L.useRef(null),y=!!window.desktopAgents&&zc(t);if(L.useEffect(()=>{if(!y)return;let D=!0;return o2().then(O=>{D&&o(O)}),BU().then(O=>{D&&d(O)}),()=>{D=!1}},[y,n,a,r]),L.useEffect(()=>{if(!h)return;const D=M=>{b.current&&!b.current.contains(M.target)&&m(!1)},O=M=>{M.key==="Escape"&&m(!1)};return document.addEventListener("mousedown",D),document.addEventListener("keydown",O),()=>{document.removeEventListener("mousedown",D),document.removeEventListener("keydown",O)}},[h]),!y||!s)return null;const k=a.find(D=>D.id===n),S=[...new Set(a.map(D=>D.agentCwd).filter(D=>!!D))].filter(D=>D!==k?.agentCwd).slice(0,5),w=async D=>{n&&(await h2(n,D),m(!1))},C=window.desktopAgents?.capabilities?.nativePicker!==!1,T=async()=>{const D=await window.desktopAgents.pickCwd();D&&await w(D)},N=async()=>{const D=p.trim();D.startsWith("/")&&await w(D)};return u.jsxs("div",{ref:b,className:"relative",children:[u.jsxs("button",{onClick:D=>{D.stopPropagation(),m(O=>!O)},className:"bg-card/90 backdrop-blur border border-line rounded-lg h-8 px-2.5 flex items-center gap-1.5 shadow-sm hover:bg-wash transition-colors text-xs text-ink max-w-[220px]",title:`${e("agent.cwd")} · ${s.cwd}`,"data-agent-cwd":s.kind,children:[u.jsx(Pc,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),u.jsx("span",{className:"truncate",children:s.kind==="workspace"?e("agent.cwdWorkspace"):wx(s.cwd)}),u.jsx(Cl,{size:12,strokeWidth:1.75,className:"text-ink-faint shrink-0"})]}),h&&u.jsxs("div",{className:"absolute right-0 top-full mt-1.5 w-[320px] bg-card border border-line rounded-xl shadow-lg py-1.5 z-50 animate-fade-in",onClick:D=>D.stopPropagation(),children:[u.jsx("p",{className:"text-2xs text-ink-faint uppercase tracking-wider font-medium px-3 pt-1 pb-1",children:e("agent.cwd")}),u.jsxs("button",{onClick:()=>{w(void 0)},className:"w-full text-left px-3 py-2 text-xs hover:bg-wash flex items-center gap-2",children:[u.jsxs("span",{className:"flex-1 min-w-0",children:[u.jsx("span",{className:"block text-ink",children:e(c?"agent.cwdMirrored":"agent.cwdWorkspace")}),u.jsx("span",{className:"block text-2xs text-ink-faint truncate",children:c??e("agent.cwdWorkspaceHint")})]}),!k?.agentCwd&&u.jsx(ri,{size:13,strokeWidth:2,className:"shrink-0 text-accent"})]}),k?.agentCwd&&u.jsxs("button",{onClick:()=>{w(k.agentCwd)},className:"w-full text-left px-3 py-2 text-xs hover:bg-wash flex items-center gap-2",children:[u.jsxs("span",{className:"flex-1 min-w-0",children:[u.jsx("span",{className:"block text-ink",children:wx(k.agentCwd)}),u.jsx("span",{className:"block text-2xs text-ink-faint truncate",children:k.agentCwd})]}),u.jsx(ri,{size:13,strokeWidth:2,className:"shrink-0 text-accent"})]}),S.length>0&&u.jsx("p",{className:"text-2xs text-ink-faint uppercase tracking-wider font-medium px-3 pt-2 pb-1",children:e("agent.cwdRecent")}),S.map(D=>u.jsx("button",{onClick:()=>{w(D)},className:"w-full text-left px-3 py-1.5 text-xs hover:bg-wash flex items-center gap-2",children:u.jsxs("span",{className:"flex-1 min-w-0",children:[u.jsx("span",{className:"block text-ink",children:wx(D)}),u.jsx("span",{className:"block text-2xs text-ink-faint truncate",children:D})]})},D)),u.jsx("div",{className:"border-t border-line/60 my-1"}),C?u.jsxs("button",{onClick:()=>{T()},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash flex items-center gap-2","data-agent-cwd-pick":!0,children:[u.jsx(Pc,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",e("agent.cwdPick")]}):u.jsxs("div",{className:"px-3 py-2 flex items-center gap-2",children:[u.jsx("input",{value:p,onChange:D=>x(D.target.value),onKeyDown:D=>{D.stopPropagation(),D.key==="Enter"&&N()},placeholder:e("agent.cwdType"),className:"flex-1 min-w-0 text-xs font-mono bg-wash border border-line rounded-md px-2 py-1 focus:outline-none focus:border-accent/60","data-agent-cwd-input":!0}),u.jsx("button",{onClick:()=>{N()},className:"text-xs text-accent hover:underline shrink-0",children:e("agent.cwdUse")})]}),u.jsx("div",{className:"border-t border-line/60 my-1"}),u.jsx("p",{className:"text-2xs text-ink-faint uppercase tracking-wider font-medium px-3 pt-1 pb-1",children:e("agent.guard")}),u.jsxs("button",{onClick:()=>{W5("ask"),m(!1)},className:"w-full text-left px-3 py-1.5 text-xs hover:bg-wash flex items-center gap-2","data-agent-guard":"ask",children:[u.jsx(pB,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),u.jsxs("span",{className:"flex-1 min-w-0",children:[u.jsx("span",{className:"block text-ink",children:e("agent.guardAsk")}),u.jsx("span",{className:"block text-2xs text-ink-faint",children:e("agent.guardAskHint")})]}),(k?.agentGuard?.mode??"ask")==="ask"&&u.jsx(ri,{size:13,strokeWidth:2,className:"shrink-0 text-accent"})]}),u.jsxs("button",{onClick:()=>{W5("allow"),m(!1)},className:"w-full text-left px-3 py-1.5 text-xs hover:bg-wash flex items-center gap-2","data-agent-guard":"allow",children:[u.jsx(xB,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),u.jsxs("span",{className:"flex-1 min-w-0",children:[u.jsx("span",{className:"block text-ink",children:e("agent.guardAllow")}),u.jsx("span",{className:"block text-2xs text-ink-faint",children:e("agent.guardAllowHint")})]}),k?.agentGuard?.mode==="allow"&&u.jsx(ri,{size:13,strokeWidth:2,className:"shrink-0 text-accent"})]}),(k?.agentGuard?.allow?.length??0)>0&&u.jsxs(u.Fragment,{children:[u.jsx("p",{className:"text-2xs text-ink-faint px-3 pt-2 pb-1",children:e("agent.guardAllowed")}),k.agentGuard.allow.map(D=>u.jsxs("div",{className:"px-3 py-1 text-xs flex items-center gap-2 min-w-0","data-agent-guard-allowed":D,children:[u.jsx("span",{className:"flex-1 min-w-0 truncate text-ink-muted font-mono",title:D,children:D}),u.jsx("button",{onClick:()=>{w7(D,!0)},className:"text-ink-faint hover:text-red-500 shrink-0",title:e("agent.guardRemove"),children:u.jsx(mn,{size:12,strokeWidth:2})})]},D))]})]})]})}const LE="thoughtdag.pluginUpdateNotified";function Cb(e){return`dsh plugin --profile web add dsh-thoughtdag@${e||"latest"}`}async function Kre(e){try{const t=await fetch(e.replace(/\/+$/,"")+"/version",{credentials:"same-origin"});if(!t.ok)return;const n=await t.json();if(!n.version||!n.latest||Ab(n.latest,n.version)<=0)return;pe.getState().setPluginUpdate({current:n.version,latest:n.latest});let a=null;try{a=localStorage.getItem(LE)}catch{}if(a!==n.latest){try{localStorage.setItem(LE,n.latest)}catch{}Qe("info",We(De("plugin.updateAvailable"),{v:n.latest}),9e3)}}catch{}}const Xre=Object.freeze(Object.defineProperty({__proto__:null,bootPluginUpdateCheck:Kre,pluginUpdateCommand:Cb},Symbol.toStringTag,{value:"Module"})),Qre={ruleout:"#ef4444",decision:"#6B5CE7",pivot:"#e8890c",open:"#d97706",insight:"#0284c7"},jE=e=>{if(e){for(let t=e.length-1;t>=0;t--)if(e[t])return e[t]}};function Zre(e){if(e.stepKind==="file")return e.attachments?.[0]?.name;if(e.stepKind==="link")return e.linkTitle||e.linkUrl;if(e.stepKind==="note")return e.question?.split(`
|
|
781
|
+
${m}`.slice(-1500)}const d=Pre(e,o,t);if(ul!==a)return;pe.getState().setCondenseRun({status:"done",streaming:"",distillIds:d.distillIds}),Qe("success",De("condense.copyReady"),8e3,{label:De("tmap.export"),run:()=>pe.getState().setThoughtMapOpen(!0)})}catch(o){if(ul!==a)return;pe.getState().setCondenseRun({status:"error",error:o instanceof Error?o.message:String(o)})}}function Hre({onFocusSegment:e}){const t=pe(P=>P.condenseDialogOpen),n=pe(P=>P.condenseRun),a=zt(),r=Ra(P=>P.lang),s=se(P=>P.nodes),o=se(P=>P.edges),[c,d]=L.useState(0),h=L.useMemo(()=>t&&n.status==="idle"?Ore(s,o):[],[t,n.status,s,o,c]),m=pe(P=>P.selectedModel),p=_l()?.models??[],[x,b]=L.useState(""),[y,k]=L.useState(new Set),[S,w]=L.useState(null),C=L.useRef(null),T=P=>{const V=C.current?.getBoundingClientRect();if(!V)return;const J=P.clientX-V.left,H=P.clientY-V.top,F=W=>w({x:Math.min(window.innerWidth-120,Math.max(0,W.clientX-J)),y:Math.min(window.innerHeight-80,Math.max(0,W.clientY-H))}),B=()=>{window.removeEventListener("mousemove",F),window.removeEventListener("mouseup",B)};window.addEventListener("mousemove",F),window.addEventListener("mouseup",B)},N=P=>P.nodeIds.join(","),D=h.filter(P=>!y.has(N(P))),O=D.reduce((P,V)=>P+V.saving,0),M=()=>{pe.getState().setCondenseDialogOpen(!1),pe.getState().setCondenseHighlightIds([])};if(L.useEffect(()=>{if(!t)return;const P=V=>{V.key==="Escape"&&M()};return window.addEventListener("keydown",P),()=>window.removeEventListener("keydown",P)},[t]),!t)return null;const _=()=>{D.length!==0&&Bre(D,r,x||m||void 0)},R=()=>{se.getState().setArchived(n.originalIds,!0),Qe("success",a("condense.originalArchived")),pe.getState().setCondenseRun({status:"idle",current:0,total:0,streaming:"",originalIds:[],distillIds:[]}),M()},G=()=>{const V=se.getState().nodes.filter(J=>n.distillIds.includes(J.id));V.length&&e?.(V.map(J=>J.id))};return Qa.createPortal(u.jsxs("div",{ref:C,className:"fixed z-[70] bg-surface border border-line rounded-2xl shadow-2xl w-[400px] max-h-[72vh] flex flex-col p-4 animate-fade-in",style:S?{left:S.x,top:S.y}:{left:80,bottom:16},"data-condense-dialog":!0,onClick:P=>P.stopPropagation(),children:[u.jsxs("div",{className:"flex items-start justify-between mb-1 cursor-grab active:cursor-grabbing select-none",onMouseDown:T,children:[u.jsxs("div",{className:"text-sm font-semibold text-ink flex items-center gap-2",children:[u.jsx(vm,{size:15,strokeWidth:1.75,className:"text-accent"})," ",a("condense.title")]}),u.jsx("button",{onClick:M,title:n.status==="building"?a("condense.runningBg"):void 0,className:"text-ink-faint hover:text-ink rounded-lg w-7 h-7 flex items-center justify-center hover:bg-wash transition-colors",children:u.jsx(mn,{size:15})})]}),n.status==="idle"&&u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"flex items-center justify-between gap-2 mb-2",children:[u.jsx("p",{className:"text-2xs text-ink-faint leading-snug",title:a("condense.copyIntroFull"),children:a("condense.copyIntroShort")}),u.jsxs("button",{onClick:()=>d(P=>P+1),title:a("condense.rescanTitle"),"data-condense-rescan":!0,className:"text-2xs text-ink-muted hover:text-accent px-2 py-1 rounded-lg hover:bg-wash transition-colors shrink-0",children:["⟳ ",a("condense.rescan")]})]}),u.jsx("p",{className:"text-2xs text-ink-faint mb-2","data-condense-scanline":!0,children:We(a("condense.scanLine"),{turns:String(s.filter(P=>P.data.response&&!P.data.stepKind).length),n:String(h.length)})}),u.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[u.jsx("label",{className:"text-2xs text-ink-muted shrink-0",children:a("condense.modelLabel")}),u.jsxs("select",{value:x,onChange:P=>b(P.target.value),"data-condense-model":!0,className:"text-xs bg-wash text-ink rounded-lg px-2 py-1.5 focus:outline-none focus:ring-1 focus:ring-accent/40 max-w-[220px] truncate",children:[u.jsx("option",{value:"",children:We(a("condense.modelGlobal"),{model:m||"auto"})}),p.map(P=>u.jsx("option",{value:P.id,children:P.id},P.id))]})]}),h.length===0?u.jsx("p",{className:"text-xs text-ink-muted py-4",children:a("condense.segNothing")}):u.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto space-y-2 pr-1",children:h.map(P=>{const V=N(P),J=!y.has(V);return u.jsxs("div",{"data-condense-item":!0,className:`border rounded-xl p-3 transition-colors cursor-pointer ${J?"border-accent/60 bg-accent/5":"border-line opacity-60"}`,onClick:()=>{pe.getState().setCondenseHighlightIds(P.nodeIds),e?.(P.nodeIds)},children:[u.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[u.jsx("input",{type:"checkbox",checked:J,onClick:H=>H.stopPropagation(),onChange:()=>k(H=>{const F=new Set(H);return F.has(V)?F.delete(V):F.add(V),F}),className:"accent-[var(--color-accent)]","data-condense-check":!0}),u.jsx("span",{className:"text-2xs text-ink-faint font-mono",children:We(a("condense.segMeta"),{n:String(P.nodeIds.length),tok:String(P.saving)})})]}),u.jsx("p",{className:"text-xs text-ink mt-1 leading-snug line-clamp-2",children:P.headQuestion})]},V)})}),h.length>0&&u.jsxs("div",{className:"flex items-center justify-between gap-2 pt-3 mt-2 border-t border-line",children:[u.jsx("span",{className:"text-2xs text-ink-faint",children:a("condense.copyFootnote")}),u.jsxs("button",{onClick:_,disabled:D.length===0,"data-condense-build":!0,className:"text-xs bg-accent text-white px-3.5 py-2 rounded-lg disabled:opacity-40 transition-colors flex items-center gap-1.5 shrink-0",children:[u.jsx(Hs,{size:13,strokeWidth:1.75}),We(a("condense.buildCopy"),{n:String(D.length),tok:String(O)})]})]})]}),n.status==="building"&&u.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",children:[u.jsxs("div",{className:"flex items-center gap-2 text-sm text-ink-muted mb-1.5",children:[u.jsx(Un,{size:15,className:"animate-spin text-accent"}),We(a("condense.buildingRun"),{i:String(n.current),n:String(n.total)})]}),u.jsx("p",{className:"text-2xs text-ink-faint mb-2",children:a("condense.runningBg")}),n.streaming&&u.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto text-2xs text-ink-muted bg-wash rounded-lg p-2.5 whitespace-pre-wrap leading-relaxed","data-condense-streaming":!0,children:n.streaming}),u.jsx("button",{onClick:()=>zre(),"data-condense-cancel":!0,className:"self-start mt-3 text-xs text-ink-muted hover:text-red-600 px-3 py-1.5 rounded-lg hover:bg-wash transition-colors",children:a("common.cancel")})]}),n.status==="error"&&u.jsxs("div",{className:"flex flex-col gap-2 py-3",children:[u.jsx("p",{className:"text-2xs text-red-600",children:n.error}),u.jsx("button",{onClick:()=>pe.getState().setCondenseRun({status:"idle",error:void 0}),className:"self-start text-xs text-ink-muted hover:text-ink px-3 py-1.5 rounded-lg hover:bg-wash transition-colors",children:a("common.cancel")})]}),n.status==="done"&&u.jsxs("div",{className:"flex flex-col gap-3 py-3",children:[u.jsxs("div",{className:"flex items-center gap-2 text-sm text-green-700",children:[u.jsx(ri,{size:16})," ",a("condense.copyReady")]}),u.jsx("p",{className:"text-2xs text-ink-faint leading-relaxed",children:a("condense.copyCompareHint")}),u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx("button",{onClick:G,className:"text-xs bg-accent/10 text-accent hover:bg-accent/20 px-3 py-2 rounded-lg transition-colors",children:a("condense.viewCopy")}),u.jsxs("button",{onClick:R,"data-condense-archive-original":!0,className:"text-xs border border-line text-ink-muted hover:text-ink hover:bg-wash px-3 py-2 rounded-lg transition-colors flex items-center gap-1.5",children:[u.jsx(zo,{size:13,strokeWidth:1.75})," ",a("condense.archiveOriginal")]})]}),u.jsx("button",{onClick:()=>{pe.getState().setCondenseRun({status:"idle"}),M()},className:"self-start text-xs text-ink-faint hover:text-ink transition-colors",children:a("common.close")})]})]}),document.body)}function OE(){const e=Ra(n=>n.lang),t=Ra(n=>n.setLang);return u.jsx("div",{className:"flex items-center bg-card/90 backdrop-blur border border-line rounded-lg shadow-sm overflow-hidden",children:["en","zh"].map(n=>u.jsx("button",{onClick:()=>t(n),className:`px-2 h-8 text-2xs font-medium transition-colors ${e===n?"bg-accent text-white":"text-ink-muted hover:bg-wash"}`,children:n==="en"?"EN":"中"},n))})}function da({x:e,y:t,w:n=34,h:a=20,tone:r="plain"}){return u.jsxs("g",{children:[u.jsx("rect",{x:e,y:t,width:n,height:a,rx:4,fill:"white",stroke:rt.line,strokeWidth:1}),r!=="plain"&&u.jsx("rect",{x:e,y:t,width:2.5,height:a,rx:1.25,fill:r==="accent"?rt.accent:rt.warm})]})}const Ure={1:u.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[u.jsx(da,{x:43,y:32,tone:"accent"}),u.jsx("circle",{cx:60,cy:28,r:2.5,fill:rt.accent})]}),2:u.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[u.jsx(da,{x:43,y:12,tone:"accent"}),u.jsx("line",{x1:60,y1:32,x2:60,y2:50,stroke:rt.accent,strokeWidth:1.75}),u.jsx("path",{d:"M 57 47 L 60 52 L 63 47 Z",fill:rt.accent}),u.jsx(da,{x:43,y:52})]}),3:u.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[u.jsx(da,{x:20,y:12,tone:"accent"}),u.jsx("line",{x1:37,y1:32,x2:37,y2:50,stroke:rt.accent,strokeWidth:1.75}),u.jsx("path",{d:"M 34 47 L 37 52 L 40 47 Z",fill:rt.accent}),u.jsx(da,{x:20,y:52}),u.jsx("rect",{x:26,y:58,width:14,height:3,rx:1.5,fill:rt.trace,opacity:.6}),u.jsx("path",{d:"M 54 62 C 64 62, 62 40, 72 38",stroke:rt.warm,strokeWidth:1.75,fill:"none",strokeDasharray:"4 3"}),u.jsx("path",{d:"M 69 35.5 L 74 38 L 70 41 Z",fill:rt.warm}),u.jsx(da,{x:74,y:28,tone:"warm"})]}),4:u.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[u.jsx(da,{x:43,y:10,tone:"accent"}),u.jsx("line",{x1:60,y1:30,x2:60,y2:52,stroke:rt.line,strokeWidth:1.75,strokeDasharray:"3 3"}),u.jsx("circle",{cx:60,cy:41,r:7,fill:"white",stroke:"#FCA5A5",strokeWidth:1}),u.jsx("line",{x1:57,y1:38,x2:63,y2:44,stroke:"#EF4444",strokeWidth:1.5,strokeLinecap:"round"}),u.jsx("line",{x1:63,y1:38,x2:57,y2:44,stroke:"#EF4444",strokeWidth:1.5,strokeLinecap:"round"}),u.jsx(da,{x:43,y:54})]}),5:u.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[u.jsx(da,{x:12,y:14,w:40,h:15}),u.jsx("circle",{cx:14,cy:16,r:4.5,fill:"#D64533"}),u.jsx("text",{x:14,y:18.4,textAnchor:"middle",fontSize:6,fontWeight:700,fill:"white",children:"✕"}),u.jsx(da,{x:12,y:35,w:40,h:15}),u.jsx("circle",{cx:14,cy:37,r:4.5,fill:rt.accent}),u.jsx("text",{x:14,y:39.4,textAnchor:"middle",fontSize:6,fontWeight:700,fill:"white",children:"⚖"}),u.jsx(da,{x:12,y:56,w:40,h:15}),u.jsx("circle",{cx:14,cy:58,r:4.5,fill:"#C9A227"}),u.jsx("text",{x:14,y:60.4,textAnchor:"middle",fontSize:6,fontWeight:700,fill:"white",children:"?"}),u.jsx("path",{d:"M 62 42 L 74 42",stroke:rt.inkMuted,strokeWidth:1.2}),u.jsx("path",{d:"M 71.5 39.5 L 76 42 L 71.5 44.5 Z",fill:rt.inkMuted}),u.jsx("rect",{x:86,y:14,width:13,height:13,rx:4.5,fill:"#D64533"}),u.jsx("line",{x1:92.5,y1:27,x2:92.5,y2:35,stroke:rt.accent,strokeWidth:1.4}),u.jsx("rect",{x:86,y:35,width:13,height:13,rx:4.5,fill:rt.accent}),u.jsx("line",{x1:92.5,y1:48,x2:92.5,y2:56,stroke:rt.accent,strokeWidth:1.4}),u.jsx("rect",{x:86,y:56,width:13,height:13,rx:4.5,fill:"#C9A227"})]}),7:u.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[u.jsx("rect",{x:14,y:12,width:30,height:22,rx:3,fill:"#FEF3C7",stroke:"#F59E0B",strokeWidth:.8}),u.jsx("line",{x1:29,y1:34,x2:29,y2:50,stroke:rt.accent,strokeWidth:1.75}),u.jsx("path",{d:"M 26 47 L 29 52 L 32 47 Z",fill:rt.accent}),u.jsx(da,{x:12,y:52,tone:"accent"}),u.jsx("path",{d:"M 100 22 C 80 22, 70 55, 50 60",stroke:rt.accent,strokeWidth:1.75,fill:"none",strokeDasharray:"5 3"}),u.jsx("path",{d:"M 52 57 L 47 61 L 52 64 Z",fill:rt.accent}),u.jsx(da,{x:82,y:12})]}),9:u.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[u.jsx(da,{x:43,y:10,tone:"accent"}),u.jsx("line",{x1:60,y1:30,x2:60,y2:48,stroke:rt.accent,strokeWidth:1.75}),u.jsx("path",{d:"M 57 45 L 60 50 L 63 45 Z",fill:rt.accent}),u.jsx(da,{x:43,y:50}),u.jsx("circle",{cx:75,cy:53,r:4,fill:"#F59E0B"}),u.jsx("path",{d:"M 73.5 53 a 1.5 1.5 0 1 1 3 0",stroke:"white",strokeWidth:.9,fill:"none"}),u.jsx("text",{x:60,y:80,textAnchor:"middle",fontSize:7,fill:rt.inkMuted,fontFamily:"JetBrains Mono Variable, monospace",children:"v2/2 · replay"})]}),6:u.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[u.jsx("rect",{x:8,y:18,width:14,height:48,rx:4,fill:"white",stroke:rt.line,strokeWidth:1}),u.jsx("circle",{cx:15,cy:27,r:3,fill:rt.accent,opacity:.7}),u.jsx("rect",{x:12,y:37,width:6,height:6,rx:1,fill:"#F59E0B",opacity:.8}),u.jsx("rect",{x:12,y:49,width:6,height:6,rx:1,fill:rt.inkMuted,opacity:.5}),u.jsx("rect",{x:38,y:14,width:32,height:24,rx:3,fill:"#FEF3C7",stroke:"#F59E0B",strokeWidth:.8}),u.jsx("rect",{x:80,y:14,width:32,height:24,rx:3,fill:"white",stroke:rt.line,strokeWidth:1}),u.jsx("circle",{cx:88,cy:22,r:3,fill:rt.line}),u.jsx("path",{d:"M 82 34 L 92 26 L 100 32 L 108 24",stroke:rt.inkMuted,strokeWidth:1.2,fill:"none"}),u.jsx("text",{x:72,y:62,textAnchor:"middle",fontSize:7,fill:rt.inkMuted,fontFamily:"JetBrains Mono Variable, monospace",children:"⌘V paste anything"})]}),8:u.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[u.jsx("rect",{x:8,y:8,width:70,height:52,rx:3,fill:rt.accent,opacity:.06,stroke:rt.accent,strokeWidth:.8,strokeDasharray:"3 2"}),u.jsx(da,{x:14,y:14,w:26,h:16}),u.jsx(da,{x:46,y:14,w:26,h:16}),u.jsx(da,{x:30,y:38,w:26,h:16}),u.jsx("path",{d:"M 40 46 C 60 50, 70 50, 84 48",stroke:rt.accent,strokeWidth:1.4,fill:"none"}),u.jsx("path",{d:"M 59 30 C 70 36, 76 42, 84 46",stroke:rt.accent,strokeWidth:1.4,fill:"none"}),u.jsx("path",{d:"M 43 22 C 66 24, 76 38, 84 44",stroke:rt.accent,strokeWidth:1.4,fill:"none"}),u.jsx(da,{x:84,y:40,w:28,h:18,tone:"accent"})]}),10:u.jsxs("svg",{viewBox:"0 0 120 84",className:"w-full h-full",children:[u.jsx(da,{x:10,y:18,w:30,h:17,tone:"accent"}),u.jsx("line",{x1:25,y1:35,x2:25,y2:48,stroke:rt.accent,strokeWidth:1.5}),u.jsx("path",{d:"M 22.5 45.5 L 25 50 L 27.5 45.5 Z",fill:rt.accent}),u.jsx(da,{x:10,y:50,w:30,h:17}),u.jsx("path",{d:"M 46 42 L 60 42",stroke:rt.inkMuted,strokeWidth:1.2}),u.jsx("path",{d:"M 57.5 39.5 L 62 42 L 57.5 44.5 Z",fill:rt.inkMuted}),u.jsx("rect",{x:68,y:20,width:44,height:44,rx:5,fill:"white",stroke:rt.line,strokeWidth:1}),u.jsx(da,{x:74,y:30,w:20,h:11,tone:"accent"}),u.jsx(da,{x:88,y:46,w:20,h:11}),u.jsx("rect",{x:76,y:14,width:28,height:11,rx:5.5,fill:"#2B2A28"}),u.jsx("circle",{cx:84,cy:19.5,r:2.6,fill:"none",stroke:"white",strokeWidth:1}),u.jsx("circle",{cx:84,cy:19.5,r:.9,fill:"white"}),u.jsx("text",{x:90,y:22,fontSize:6,fill:"white",fontFamily:"JetBrains Mono Variable, monospace",children:"view"}),u.jsx("text",{x:60,y:78,textAnchor:"middle",fontSize:7,fill:rt.inkMuted,fontFamily:"JetBrains Mono Variable, monospace",children:"#view= · read-only"})]})},RE={4:"prune",5:"map",6:"reading",7:"ref"};function Fre(){const e=pe(h=>h.tutorialOpen),t=pe(h=>h.setTutorialOpen);L.useEffect(()=>{if(!e)return;const h=m=>{m.key==="Escape"&&t(!1)};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[e,t]);const n=zt(),a=Ra(h=>h.lang),[r,s]=L.useState(0),o=[{label:n("tutorial.pg1"),steps:[1,2,3]},{label:n("tutorial.pg2"),steps:[4,5]},{label:n("tutorial.pg3"),steps:[6,7]},{label:n("tutorial.pg4"),steps:[8,9,10]}],c=r===o.length-1;if(L.useEffect(()=>{if(!e)return;s(0);const h=m=>{m.key==="ArrowRight"&&s(p=>Math.min(p+1,o.length-1)),m.key==="ArrowLeft"&&s(p=>Math.max(p-1,0))};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[e]),!e)return null;const d=o[r];return u.jsx("div",{className:"fixed inset-0 z-[95] bg-black/25 flex items-center justify-center animate-fade-in p-6",onClick:()=>t(!1),children:u.jsxs("div",{className:"bg-card border border-line rounded-2xl shadow-2xl w-[min(980px,94vw)] flex flex-col",onClick:h=>h.stopPropagation(),children:[u.jsxs("div",{className:"flex items-start justify-between px-7 pt-5 pb-1 shrink-0",children:[u.jsxs("div",{className:"flex items-baseline gap-3 min-w-0",children:[u.jsx("h2",{className:"text-lg font-semibold text-ink tracking-tight shrink-0",children:n("tutorial.title")}),u.jsx("p",{className:"text-xs text-ink-faint truncate",children:n("tutorial.subtitle")})]}),u.jsx("button",{onClick:()=>t(!1),className:"text-ink-faint hover:text-ink transition-colors mt-1",children:u.jsx(mn,{size:18,strokeWidth:1.75})})]}),u.jsxs("div",{className:"px-7 pt-3 pb-1 min-h-[380px]",children:[u.jsx("p",{className:"text-2xs font-semibold text-accent mb-3 uppercase tracking-wider",children:d.label}),u.jsx("div",{className:`grid gap-4 ${d.steps.length===3?"grid-cols-1 sm:grid-cols-3":"grid-cols-1 sm:grid-cols-2"}`,children:d.steps.map(h=>u.jsxs("div",{className:"bg-surface border border-line/70 rounded-xl p-4 flex flex-col animate-fade-in",children:[u.jsx("div",{className:"w-full aspect-[120/72] bg-card rounded-lg border border-line/60 mb-3 overflow-hidden",children:RE[h]?u.jsx("img",{src:`/thoughtdag/tutorial/${RE[h]}-${a}.gif`,loading:"lazy",alt:"",className:"w-full h-full object-cover"}):Ure[h]}),u.jsx("h3",{className:"text-[13px] font-semibold text-ink leading-snug",children:n(`tutorial.step${h}.title`)}),u.jsx("p",{className:"text-xs text-ink-muted leading-relaxed mt-1.5",children:n(`tutorial.step${h}.desc`)})]},h))})]}),u.jsxs("div",{className:"px-7 py-4 shrink-0 flex items-center justify-between",children:[u.jsx("button",{onClick:()=>s(h=>Math.max(h-1,0)),disabled:r===0,className:"w-8 h-8 rounded-lg border border-line text-ink-muted hover:bg-wash transition-colors flex items-center justify-center disabled:opacity-25 disabled:cursor-not-allowed",children:u.jsx(jf,{size:16,strokeWidth:1.75})}),u.jsx("div",{className:"flex items-center gap-2",children:o.map((h,m)=>u.jsx("button",{onClick:()=>s(m),className:`h-2 rounded-full transition-all ${m===r?"w-6 bg-accent":"w-2 bg-line hover:bg-line-strong"}`,"aria-label":`${m+1}/${o.length}`},m))}),c?u.jsx("button",{onClick:()=>t(!1),className:"text-xs bg-accent hover:bg-accent-strong text-white px-5 py-2 rounded-lg transition-colors",children:n("tutorial.close")}):u.jsx("button",{onClick:()=>s(h=>h+1),className:"w-8 h-8 rounded-lg border border-line text-ink-muted hover:bg-wash transition-colors flex items-center justify-center",children:u.jsx(Fi,{size:16,strokeWidth:1.75})})]}),u.jsxs("div",{className:"px-7 py-2.5 border-t border-line/60 shrink-0 flex flex-wrap gap-x-4 gap-y-1 text-2xs text-ink-faint font-mono",children:[u.jsxs("span",{children:[n("shortcut.panKeys")," ",n("shortcut.pan")]}),u.jsxs("span",{children:[n("shortcut.marqueeKeys")," ",n("shortcut.marquee")]}),u.jsxs("span",{children:["⌘","F ",n("shortcut.search")]}),u.jsxs("span",{children:["Space ",n("shortcut.collapse")]}),u.jsxs("span",{children:["R ",n("shortcut.regenerate")]}),u.jsxs("span",{children:["↑↓←→"," ",n("shortcut.navigate")]}),u.jsxs("span",{children:["⌘","Z/","⇧","⌘","Z ",n("shortcut.undo")]}),u.jsxs("span",{children:["Del ",n("shortcut.delete")]}),u.jsxs("span",{children:["Esc ",n("shortcut.escape")]})]})]})})}const qre=new URLSearchParams(window.location.search),Pi=qre.get("dv"),df="https://chenxiachan.github.io/thoughtdag/docs",C9=[{version:"0.4.17",date:"2026-09-21",announce:!1,lead:{zh:"DeepSeek Harness 插件:从画布向 Harness 提问时,节点只接自己那一轮。此前如果你同时在聊天框里发消息,画布节点会拿到你那轮的回答、在你那轮结束时提前收尾,并把镜像标记挂到错误的轮次上,产生重复节点;工具审批也可能被画布抢走。现在 Host 用 dsh 记在消息上的请求 id 精确认出自己的那一轮,文本、工具调用、审批、结束全部按这一轮过滤(#42,感谢 @nanami-0713)。桌面版本次只同步版本号。",en:"DeepSeek Harness plugin: a question asked from the canvas now receives only its own turn. Before, if you were also typing in the chat, the canvas node could receive your turn's answer, finish early when your turn ended, and stamp its mirror mark on the wrong turn, leaving duplicate nodes; tool approvals could be captured by the canvas as well. The host now recognises its own turn by the request id dsh records on the message, and filters text, tool calls, approvals and the end of turn to that turn alone (#42, thanks @nanami-0713). The desktop app only moves its version number."},items:[]},{version:"0.4.16",date:"2026-09-17",announce:!1,lead:{zh:"分区框:两个只是部分重叠的框不再互相收编。拖动大框时,重叠的小框和它自己的节点留在原地;拖动和一键排版现在用同一条成员规则,普通节点按中心点归属,框只有完整落在另一个框里才算它的成员(#40,感谢 @nanami-0713)。DeepSeek Harness 插件:「插件有新版本」提示复制的命令带上具体版本号,发版当天也能立刻装到新版。",en:"Frames: two frames that merely overlap no longer own each other. Dragging the larger one leaves the overlapping smaller frame and its own nodes in place; dragging and auto layout now share one membership rule, nodes by centre and a frame only when it lies fully inside another (#40, thanks @nanami-0713). DeepSeek Harness plugin: the update hint now copies a command naming the exact version, so a release installs on its first day too."},items:[]},{version:"0.4.15",date:"2026-09-15",announce:!1,lead:{zh:"分区框三件事:一键排版后,框跟着框内的节点重新包好(#32);拖动外框会带动嵌套在里面的框;重叠时小框叠在大框上面,标题栏不再被盖住。三项均来自 @hexu321。DeepSeek Harness 插件:「对话 | 思维图」切换器移进会话标题栏,不再遮挡标题;返回按钮居中,画布右上的工具栏保持可见;从画布切回会话的跳转修好了(#30,来自 @nanami-0713)。插件重新在 npm 上发布,安装命令恢复为包名。",en:"Frames, three fixes: after auto layout a frame re-wraps the nodes it held (#32); dragging an outer frame carries the frames nested inside it; where frames overlap, the smaller one stacks on top so its title bar stays reachable. All three by @hexu321. DeepSeek Harness plugin: the 对话 | 思维图 switch moves into the session header and no longer covers the title; the back button sits top centre, clear of the canvas toolbar; jumping from the canvas back to a session works again (#30, by @nanami-0713). The plugin is back on npm and the install command is the package name again."},items:[]},{version:"0.4.14",date:"2026-09-11",announce:!1,lead:{zh:"插件的「有新版本」提示现在复制 dsh plugin --profile web add dsh-thoughtdag@latest,这条命令对从 npm 装和从 Release 文件装的用户都有效(update 对文件安装无效)。其余同 0.4.13。",en:"The plugin's update hint now copies dsh plugin --profile web add dsh-thoughtdag@latest, which works for installs from npm and from a release file alike (update does nothing for a file install). Otherwise the same as 0.4.13."},items:[]},{version:"0.4.13",date:"2026-09-11",announce:!1,lead:{zh:"修复:DeepSeek Harness 插件里,模型选择器丢失了「Harness · 模型」这一组 Agent 条目(0.4.11 起,机器上没装 Pi、Codex 等命令行时整组消失)。原因是思维图把 Harness 给的条目当成本机命令行的探测结果替换掉了,现在只替换命令行报来的那几种。插件里「如何使用」的教程动图也能显示了(#35,感谢 @Moya-Doc)。",en:`Fix: inside the DeepSeek Harness plugin, the model picker lost the "Harness · model" agent entries (since 0.4.11; with no Pi or Codex CLI on the machine the whole group vanished). The canvas had been replacing the harness's entries with the local CLI probe; now only the entries the CLIs report get replaced. The tutorial gifs inside the plugin load again (#35, thanks @Moya-Doc).`},items:[]},{version:"0.4.12",date:"2026-09-10",announce:!1,lead:{zh:"DeepSeek Harness 插件里,Agent 子节点现在续接父节点的会话;同一父节点下的第二个分支从父节点那一轮分叉出自己的会话,preset 的会话状态不再在每个子节点重头开始(#28、#29)。插件的构建脚本在 Windows 上也能跑了(#24、#26)。桌面版本次只同步版本号。",en:"Inside the DeepSeek Harness plugin, an agent child node now continues its parent's session, and a second branch off the same parent forks its own session at that parent's turn, so a preset's session state no longer restarts at every child (#28, #29). The plugin's build script runs on Windows too (#24, #26). The desktop app only moves its version number."},items:[]},{version:"0.4.11",date:"2026-09-08",announce:!1,lead:{zh:"性能优化:启动更快,后台更省,多个工具调用并行时更稳;300 节点以上的画布实测流畅。ThoughtDAG 现在可以用 Claude Code、Codex、Pi 作为节点的 Agent 运行时,处于测试阶段。",en:"Performance: faster launch, lighter in the background, steadier when several tool calls run in parallel; canvases past 300 nodes measured smooth. ThoughtDAG can now run a node through Claude Code, Codex or Pi as its agent runtime, in testing."},items:[]},{version:"0.4.10",date:"2026-09-07",announce:!1,lead:{zh:"Agent 执行预览继续:Codex 加入,和 Pi 一样在画布里带工具作答;这条通道现在在桌面版、本地网页版和 DeepSeek Harness 插件里都可用;插件里的 Harness Agent 按模型平铺;插件有新版本时画布会提示。",en:"Agent runs, preview continued: Codex joins Pi, answering with tools right from the canvas; the lane now works in the desktop app, the local web app and the DeepSeek Harness plugin alike; inside the plugin the Harness agent lists one entry per model; the canvas tells you when a newer plugin is out."},items:[]},{version:"0.4.9",date:"2026-09-07",announce:!1,lead:{zh:"Agent 执行预览:桌面版的模型选择器多了「Agent 执行」组,装了 Pi 的话可以直接在画布里让它带工具作答,轨迹、足迹、审批和提问都落在节点上,工作目录在顶栏可见可改。正式版会连同 Claude Code 与 Codex 一起发布。DeepSeek Harness 插件里的审批卡片同步更新。",en:'Agent runs, preview: the desktop picker gains an "Agent runs" group; with Pi installed, a question runs through it with tools right from the canvas, and the trace, footprints, approvals and questions land on the node, with the working directory visible on the toolbar. The full release will arrive together with Claude Code and Codex. The approval card inside the DeepSeek Harness plugin is updated alike.'},items:[]},{version:"0.4.8",date:"2026-09-07",announce:!1,lead:{zh:"DeepSeek Harness 插件在 Windows 上能打开了:静态资源和会话目录的路径守卫此前只认正斜杠,Windows 用户看到的是一片 403。感谢 GitHub 上的报告(#23)。桌面版本次只同步版本号。",en:"The DeepSeek Harness plugin now opens on Windows: the path guards for static assets and session directories only accepted forward slashes, so Windows users saw nothing but 403s. Thanks to the report on GitHub (#23). The desktop app only moves its version number this time."},items:[]},{version:"0.4.7",date:"2026-09-07",announce:!1,lead:{zh:"DeepSeek Harness 插件里,Agent 需要你批准的操作现在直接出现在节点上:工具、命令、理由,允许一次或拒绝,决定留在节点记录里。桌面版本次只同步版本号。",en:"Inside the DeepSeek Harness plugin, an action the agent needs approved now appears on the node itself: tool, command, reason, allow once or reject, and the decision stays in the node's record. The desktop app only moves its version number this time."},items:[]},{version:"0.4.6",date:"2026-09-06",announce:!0,lead:{zh:"🎉 Pi 的会话进了对话地图,「⋯」菜单里多了更新历史,随时能回看每一版改了什么。",en:"🎉 Pi sessions join the Session Atlas, and the ⋯ menu gains a release history, so what every version changed is one click away."},items:[{title:{zh:"Pi 的会话也在地图上了",en:"Pi sessions are on the map"},body:{zh:"本地 Pi 会话按项目聚在一起,打开就是一张图。Pi 里的每次分叉在图上就是一条支线,不再压成一条直线。命令行 why 和 MCP 也同步认识 Pi 留下的文件足迹。",en:"Local Pi sessions group by project and open as a graph. Every fork you made in Pi shows up as a branch instead of being flattened into one line. The why command and MCP index Pi's file footprints too."},link:{label:{zh:"怎么用",en:"How it works"},href:`${df}/zh/guides/session-atlas`}},{title:{zh:"更新历史,随时补看",en:"Release history, whenever you like"},body:{zh:"右上「⋯」菜单,「如何使用」下面。每个版本改了什么都在这里,从新到旧,当前版本有标记。",en:"In the ⋯ menu, under How it works: what each release changed, newest first, with the version you are running marked."}}]},{version:"0.4.5",date:"2026-09-06",announce:!0,lead:{zh:"🎉 这是 ThoughtDAG 到目前为止最大的一次升级:散在各个 Agent 里的对话接成了一张地图,能从画布里查,还能直接在 DeepSeek Harness 里用。四件新东西,都值得试一试。",en:"🎉 The biggest ThoughtDAG release so far: the conversations scattered across your agents become one map, you can query them, and it all runs inside DeepSeek Harness. Four new things, each worth a try."},items:[{title:{zh:"跨 Agent 的对话地图,终于连成一张",en:"Session Atlas: all your agents, one map"},body:{zh:"Claude Code、Codex 和 DeepSeek Harness 的本地会话按项目文件夹聚在一起,点开就是一张图,随对话实时生长。",en:"Local Claude Code, Codex and DeepSeek Harness sessions, grouped by project; open one as a graph and it follows the conversation live."},link:{label:{zh:"怎么用",en:"How it works"},href:`${df}/zh/guides/session-atlas`}},{title:{zh:"命令行 why:一条命令找回塑造文件的那些对话",en:"thoughtdag why: one command finds the conversations that shaped a file"},body:{zh:"npx thoughtdag why <文件> 列出哪些轮次读过、改过它,当时问了什么、改了什么;find 按原话搜,MCP 让 Agent 自己来查。",en:"npx thoughtdag why <file> lists the turns that read or changed it, what was asked and what changed; find searches verbatim; MCP lets your agent ask."},link:{label:{zh:"命令与 MCP",en:"CLI and MCP"},href:`${df}/zh/guides/why-layer`}},{title:{zh:"DeepSeek Harness 插件上线",en:"DeepSeek Harness plugin is live"},body:{zh:'dsh plugin --profile web add dsh-thoughtdag,Harness 的网页里多一个"思维图"视图:在画布上提问、让 Harness 的 Agent 带工具作答,why 也成了它的原生工具。',en:"dsh plugin --profile web add dsh-thoughtdag adds a canvas view to the Harness web UI: ask from the canvas, let its agent answer with tools, and why becomes a native tool there."},link:{label:{zh:"插件说明",en:"Plugin README"},href:"https://github.com/chenxiachan/thoughtdag/tree/main/dsh#readme"}},{title:{zh:"文档站上线",en:"The docs site is live"},body:{zh:"概念、任务指南、命令字典和隐私说明各有一页,中英文对照。感谢一路同行,欢迎来 Discussions 说说你怎么用它。",en:"Concepts, task guides, the command dictionary and the privacy notes, each on its own page, in both languages. Thank you for coming this far with us; tell us how you use it in Discussions."},link:{label:{zh:"打开文档",en:"Open the docs"},href:`${df}/zh/`}}]},{version:"0.4.4",date:"2026-09-04",announce:!1,lead:{zh:"DeepSeek Harness 成为对话地图的内置来源:它的 zstd 日志由桌面壳逐帧解码,每条消息一个节点,工具调用与结果配对成附件。",en:"DeepSeek Harness becomes a built-in Atlas source: the shell decodes its zstd logs frame by frame, one node per message, tool calls paired with their results as attachments."},items:[]},{version:"0.4.3",date:"2026-09-03",announce:!1,lead:{zh:"深链接可以直达某一轮,画布可以按稳定 id 打开;子 Agent 的会话文件不再打扰实时监听。",en:"A deep link can land on a turn and a canvas opens by its stable id; subagent session files no longer disturb the live watcher."},items:[]},{version:"0.4.2",date:"2026-09-02",announce:!1,lead:{zh:"镜像节点列出那一轮碰过的文件(✏️ 改过、📖 读过),预览用结论而不是开头;子 Agent 的会话作为子线程识别,报告折回发起它的那一轮。",en:"A mirrored node lists the files its turn touched (✏️ edited, 📖 read) and previews the conclusion rather than the opening line; subagent files are recognized as sub-threads and their reports fold into the launching turn."},items:[]},{version:"0.4.1",date:"2026-09-01",announce:!1,lead:{zh:"Agent 对话地图首发:本地 Claude Code 与 Codex 的会话按项目文件夹聚成一张图,一键接入,随对话实时生长。",en:"Session Atlas debuts: local Claude Code and Codex sessions group by project folder into one map, connect in one click, and grow with the conversation."},items:[]}];function Ab(e,t){const n=e.split(".").map(r=>parseInt(r,10)||0),a=t.split(".").map(r=>parseInt(r,10)||0);for(let r=0;r<Math.max(n.length,a.length);r++){const s=(n[r]??0)-(a[r]??0);if(s!==0)return s}return 0}function vx(e,t){return C9.filter(n=>n.announce&&Ab(n.version,t)<=0&&(e===null||Ab(n.version,e)>0))}const Nb="thoughtdag.whatsNewSeen",Wre=new URLSearchParams(window.location.search);function Vre(){if(!Pi)return[];if(Wre.get("wn")==="1")return vx(null,Pi);let t=null;try{t=localStorage.getItem(Nb)}catch{}if(t===null){let n=!1;try{n=!!(localStorage.getItem("thoughtdag.tutorialDone")||localStorage.getItem("thoughtdag.lastBackupAt"))}catch{}if(!n){try{localStorage.setItem(Nb,Pi)}catch{}return[]}return vx(null,Pi)}return t===Pi?[]:vx(t,Pi)}function _9({items:e,lang:t}){return e.length===0?null:u.jsx("ol",{className:"divide-y divide-line",children:e.map((n,a)=>u.jsxs("li",{className:"py-3 flex gap-3.5",children:[u.jsx("span",{className:"shrink-0 w-6 h-6 rounded-full bg-accent/10 text-accent text-xs font-semibold flex items-center justify-center mt-0.5",children:a+1}),u.jsxs("div",{className:"min-w-0",children:[u.jsx("div",{className:"text-sm font-medium text-ink",children:n.title[t]}),u.jsx("p",{className:"text-sm text-ink-muted leading-relaxed mt-1 [overflow-wrap:anywhere]",children:n.body[t]}),n.link&&u.jsxs("a",{href:n.link.href,target:"_blank",rel:"noreferrer",className:"inline-block mt-1.5 text-xs font-medium text-accent hover:underline",children:[n.link.label[t]," →"]})]})]},a))})}function Gre(){const[e,t]=L.useState(()=>Vre()),n=e.length>0,a=Ra(c=>c.lang),r=zt(),s=L.useRef(null),o=()=>{if(Pi)try{localStorage.setItem(Nb,Pi)}catch{}t([])};return L.useEffect(()=>{if(!n)return;s.current?.focus({preventScroll:!0});const c=d=>{d.stopPropagation(),(d.key==="Escape"||d.key==="Enter")&&o()};return window.addEventListener("keydown",c,!0),()=>window.removeEventListener("keydown",c,!0)},[n]),n?u.jsx("div",{className:"fixed inset-0 z-[100] bg-black/25 flex items-center justify-center animate-fade-in p-6",onClick:o,children:u.jsxs("div",{className:"bg-card border border-line rounded-2xl shadow-xl w-[680px] max-w-full max-h-[85vh] overflow-y-auto",onClick:c=>c.stopPropagation(),role:"dialog","aria-labelledby":"whats-new-title","data-whats-new":!0,children:[u.jsxs("div",{className:"px-6 pt-5 pb-4 border-b border-line",children:[u.jsx("div",{className:"text-2xs uppercase tracking-wide text-ink-faint",children:"ThoughtDAG"}),u.jsx("h2",{id:"whats-new-title",className:"text-base font-semibold text-ink mt-0.5",children:We(r("whatsNew.title"),{v:Pi??""})}),e.length>1&&u.jsx("p",{className:"text-xs text-ink-faint mt-1",children:r("whatsNew.multi")})]}),u.jsx("ol",{className:"px-6 divide-y divide-line",children:e.map(c=>u.jsxs("li",{className:"py-4","data-release":c.version,children:[e.length>1&&u.jsxs("div",{className:"flex items-baseline gap-2.5 mb-1.5",children:[u.jsxs("span",{className:"text-sm font-semibold text-ink tabular-nums",children:["v",c.version]}),u.jsx("span",{className:"text-xs text-ink-faint tabular-nums",children:c.date})]}),u.jsx("p",{className:"text-sm text-ink-muted leading-relaxed [overflow-wrap:anywhere]",children:c.lead[a]}),u.jsx(_9,{items:c.items,lang:a})]},c.version))}),u.jsxs("div",{className:"sticky bottom-0 bg-card px-6 py-4 border-t border-line flex items-center justify-between gap-4",children:[u.jsx("button",{onClick:()=>{o(),pe.getState().setReleaseNotesOpen(!0)},className:"text-xs text-ink-muted hover:text-ink hover:underline transition-colors","data-whats-new-all":!0,children:r("whatsNew.seeAll")}),u.jsx("button",{ref:s,onClick:o,className:"text-xs text-white px-4 py-2 rounded-lg bg-accent hover:bg-accent-strong transition-colors",children:r("whatsNew.ok")})]})]})}):null}function $re(){const e=pe(r=>r.releaseNotesOpen),t=pe(r=>r.setReleaseNotesOpen),n=Ra(r=>r.lang),a=zt();return L.useEffect(()=>{if(!e)return;const r=s=>{s.key==="Escape"&&(s.stopPropagation(),t(!1))};return window.addEventListener("keydown",r,!0),()=>window.removeEventListener("keydown",r,!0)},[e,t]),e?u.jsx("div",{className:"fixed inset-0 z-[100] bg-black/25 flex items-center justify-center animate-fade-in p-6",onClick:()=>t(!1),children:u.jsxs("div",{className:"bg-card border border-line rounded-2xl shadow-xl w-[680px] max-w-full max-h-[85vh] overflow-y-auto",onClick:r=>r.stopPropagation(),role:"dialog","aria-labelledby":"release-notes-title","data-release-notes":!0,children:[u.jsxs("div",{className:"px-6 pt-5 pb-4 border-b border-line",children:[u.jsx("div",{className:"text-2xs uppercase tracking-wide text-ink-faint",children:"ThoughtDAG"}),u.jsx("h2",{id:"release-notes-title",className:"text-base font-semibold text-ink mt-0.5",children:a("releaseNotes.title")})]}),u.jsx("ol",{className:"px-6 divide-y divide-line",children:C9.map(r=>{const s=Pi===r.version;return u.jsxs("li",{className:"py-4","data-release":r.version,children:[u.jsxs("div",{className:"flex items-baseline gap-2.5 flex-wrap",children:[u.jsxs("span",{className:"text-sm font-semibold text-ink tabular-nums",children:["v",r.version]}),u.jsx("span",{className:"text-xs text-ink-faint tabular-nums",children:r.date}),s&&u.jsx("span",{className:"text-2xs font-medium uppercase tracking-wide text-accent bg-accent/10 rounded-full px-2 py-0.5",children:a("releaseNotes.current")})]}),u.jsx("p",{className:"text-sm text-ink-muted leading-relaxed mt-1.5 [overflow-wrap:anywhere]",children:r.lead[n]}),u.jsx(_9,{items:r.items,lang:n})]},r.version)})}),u.jsx("div",{className:"sticky bottom-0 bg-card px-6 py-4 border-t border-line flex justify-end",children:u.jsx("button",{onClick:()=>t(!1),className:"text-xs text-ink px-4 py-2 rounded-lg border border-line hover:bg-wash transition-colors",children:a("common.close")})})]})}):null}const wx=e=>e.split("/").filter(Boolean).slice(-1)[0]??e;function Yre(){const e=zt(),t=pe(D=>D.selectedModel),n=rn(D=>D.activeId),a=rn(D=>D.projects),r=se(D=>D.nodes.length),[s,o]=L.useState(null),[c,d]=L.useState(null),[h,m]=L.useState(!1),[p,x]=L.useState(""),b=L.useRef(null),y=!!window.desktopAgents&&zc(t);if(L.useEffect(()=>{if(!y)return;let D=!0;return o2().then(O=>{D&&o(O)}),BU().then(O=>{D&&d(O)}),()=>{D=!1}},[y,n,a,r]),L.useEffect(()=>{if(!h)return;const D=M=>{b.current&&!b.current.contains(M.target)&&m(!1)},O=M=>{M.key==="Escape"&&m(!1)};return document.addEventListener("mousedown",D),document.addEventListener("keydown",O),()=>{document.removeEventListener("mousedown",D),document.removeEventListener("keydown",O)}},[h]),!y||!s)return null;const k=a.find(D=>D.id===n),S=[...new Set(a.map(D=>D.agentCwd).filter(D=>!!D))].filter(D=>D!==k?.agentCwd).slice(0,5),w=async D=>{n&&(await h2(n,D),m(!1))},C=window.desktopAgents?.capabilities?.nativePicker!==!1,T=async()=>{const D=await window.desktopAgents.pickCwd();D&&await w(D)},N=async()=>{const D=p.trim();D.startsWith("/")&&await w(D)};return u.jsxs("div",{ref:b,className:"relative",children:[u.jsxs("button",{onClick:D=>{D.stopPropagation(),m(O=>!O)},className:"bg-card/90 backdrop-blur border border-line rounded-lg h-8 px-2.5 flex items-center gap-1.5 shadow-sm hover:bg-wash transition-colors text-xs text-ink max-w-[220px]",title:`${e("agent.cwd")} · ${s.cwd}`,"data-agent-cwd":s.kind,children:[u.jsx(Pc,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),u.jsx("span",{className:"truncate",children:s.kind==="workspace"?e("agent.cwdWorkspace"):wx(s.cwd)}),u.jsx(Cl,{size:12,strokeWidth:1.75,className:"text-ink-faint shrink-0"})]}),h&&u.jsxs("div",{className:"absolute right-0 top-full mt-1.5 w-[320px] bg-card border border-line rounded-xl shadow-lg py-1.5 z-50 animate-fade-in",onClick:D=>D.stopPropagation(),children:[u.jsx("p",{className:"text-2xs text-ink-faint uppercase tracking-wider font-medium px-3 pt-1 pb-1",children:e("agent.cwd")}),u.jsxs("button",{onClick:()=>{w(void 0)},className:"w-full text-left px-3 py-2 text-xs hover:bg-wash flex items-center gap-2",children:[u.jsxs("span",{className:"flex-1 min-w-0",children:[u.jsx("span",{className:"block text-ink",children:e(c?"agent.cwdMirrored":"agent.cwdWorkspace")}),u.jsx("span",{className:"block text-2xs text-ink-faint truncate",children:c??e("agent.cwdWorkspaceHint")})]}),!k?.agentCwd&&u.jsx(ri,{size:13,strokeWidth:2,className:"shrink-0 text-accent"})]}),k?.agentCwd&&u.jsxs("button",{onClick:()=>{w(k.agentCwd)},className:"w-full text-left px-3 py-2 text-xs hover:bg-wash flex items-center gap-2",children:[u.jsxs("span",{className:"flex-1 min-w-0",children:[u.jsx("span",{className:"block text-ink",children:wx(k.agentCwd)}),u.jsx("span",{className:"block text-2xs text-ink-faint truncate",children:k.agentCwd})]}),u.jsx(ri,{size:13,strokeWidth:2,className:"shrink-0 text-accent"})]}),S.length>0&&u.jsx("p",{className:"text-2xs text-ink-faint uppercase tracking-wider font-medium px-3 pt-2 pb-1",children:e("agent.cwdRecent")}),S.map(D=>u.jsx("button",{onClick:()=>{w(D)},className:"w-full text-left px-3 py-1.5 text-xs hover:bg-wash flex items-center gap-2",children:u.jsxs("span",{className:"flex-1 min-w-0",children:[u.jsx("span",{className:"block text-ink",children:wx(D)}),u.jsx("span",{className:"block text-2xs text-ink-faint truncate",children:D})]})},D)),u.jsx("div",{className:"border-t border-line/60 my-1"}),C?u.jsxs("button",{onClick:()=>{T()},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash flex items-center gap-2","data-agent-cwd-pick":!0,children:[u.jsx(Pc,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",e("agent.cwdPick")]}):u.jsxs("div",{className:"px-3 py-2 flex items-center gap-2",children:[u.jsx("input",{value:p,onChange:D=>x(D.target.value),onKeyDown:D=>{D.stopPropagation(),D.key==="Enter"&&N()},placeholder:e("agent.cwdType"),className:"flex-1 min-w-0 text-xs font-mono bg-wash border border-line rounded-md px-2 py-1 focus:outline-none focus:border-accent/60","data-agent-cwd-input":!0}),u.jsx("button",{onClick:()=>{N()},className:"text-xs text-accent hover:underline shrink-0",children:e("agent.cwdUse")})]}),u.jsx("div",{className:"border-t border-line/60 my-1"}),u.jsx("p",{className:"text-2xs text-ink-faint uppercase tracking-wider font-medium px-3 pt-1 pb-1",children:e("agent.guard")}),u.jsxs("button",{onClick:()=>{W5("ask"),m(!1)},className:"w-full text-left px-3 py-1.5 text-xs hover:bg-wash flex items-center gap-2","data-agent-guard":"ask",children:[u.jsx(pB,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),u.jsxs("span",{className:"flex-1 min-w-0",children:[u.jsx("span",{className:"block text-ink",children:e("agent.guardAsk")}),u.jsx("span",{className:"block text-2xs text-ink-faint",children:e("agent.guardAskHint")})]}),(k?.agentGuard?.mode??"ask")==="ask"&&u.jsx(ri,{size:13,strokeWidth:2,className:"shrink-0 text-accent"})]}),u.jsxs("button",{onClick:()=>{W5("allow"),m(!1)},className:"w-full text-left px-3 py-1.5 text-xs hover:bg-wash flex items-center gap-2","data-agent-guard":"allow",children:[u.jsx(xB,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"}),u.jsxs("span",{className:"flex-1 min-w-0",children:[u.jsx("span",{className:"block text-ink",children:e("agent.guardAllow")}),u.jsx("span",{className:"block text-2xs text-ink-faint",children:e("agent.guardAllowHint")})]}),k?.agentGuard?.mode==="allow"&&u.jsx(ri,{size:13,strokeWidth:2,className:"shrink-0 text-accent"})]}),(k?.agentGuard?.allow?.length??0)>0&&u.jsxs(u.Fragment,{children:[u.jsx("p",{className:"text-2xs text-ink-faint px-3 pt-2 pb-1",children:e("agent.guardAllowed")}),k.agentGuard.allow.map(D=>u.jsxs("div",{className:"px-3 py-1 text-xs flex items-center gap-2 min-w-0","data-agent-guard-allowed":D,children:[u.jsx("span",{className:"flex-1 min-w-0 truncate text-ink-muted font-mono",title:D,children:D}),u.jsx("button",{onClick:()=>{w7(D,!0)},className:"text-ink-faint hover:text-red-500 shrink-0",title:e("agent.guardRemove"),children:u.jsx(mn,{size:12,strokeWidth:2})})]},D))]})]})]})}const LE="thoughtdag.pluginUpdateNotified";function Cb(e){return`dsh plugin --profile web add dsh-thoughtdag@${e||"latest"}`}async function Kre(e){try{const t=await fetch(e.replace(/\/+$/,"")+"/version",{credentials:"same-origin"});if(!t.ok)return;const n=await t.json();if(!n.version||!n.latest||Ab(n.latest,n.version)<=0)return;pe.getState().setPluginUpdate({current:n.version,latest:n.latest});let a=null;try{a=localStorage.getItem(LE)}catch{}if(a!==n.latest){try{localStorage.setItem(LE,n.latest)}catch{}Qe("info",We(De("plugin.updateAvailable"),{v:n.latest}),9e3)}}catch{}}const Xre=Object.freeze(Object.defineProperty({__proto__:null,bootPluginUpdateCheck:Kre,pluginUpdateCommand:Cb},Symbol.toStringTag,{value:"Module"})),Qre={ruleout:"#ef4444",decision:"#6B5CE7",pivot:"#e8890c",open:"#d97706",insight:"#0284c7"},jE=e=>{if(e){for(let t=e.length-1;t>=0;t--)if(e[t])return e[t]}};function Zre(e){if(e.stepKind==="file")return e.attachments?.[0]?.name;if(e.stepKind==="link")return e.linkTitle||e.linkUrl;if(e.stepKind==="note")return e.question?.split(`
|
|
782
782
|
`)[0].replace(/^#+\s*/,"")||void 0}function my(e,t){return e.filter(n=>n.data.stepKind!=="frame").map((n,a)=>{const r=n.data,s=r.createdAt??r.askedAt??r.generatedAts?.[0]??r.lastGeneratedAt,o=[r.askedAt,jE(r.generatedAts),jE(r.editedAts)].filter(Boolean).sort().pop(),c=r.summaryTypes?.[r.responseIndex??0]??void 0,d=r.summaries?.[r.responseIndex??0],h=r.summaryTopics?.[r.responseIndex??0]??void 0,m=s?Date.parse(s):NaN,p=o?Date.parse(o):NaN;return{entry:{id:n.id,label:(d||Zre(r)||r.question||"").slice(0,120),topic:h,badged:!!c&&c!=="insight",type:c??void 0,createdAt:s,modifiedAt:o,color:c&&Qre[c]||"#b8b3c7",archived:!!r.archived,recentlyEdited:!isNaN(m)&&!isNaN(p)&&p-m>6e4&&t-p<30*6e4,x:n.position.x,y:n.position.y},i:a}}).sort((n,a)=>{const r=n.entry.createdAt??"",s=a.entry.createdAt??"";return r<s?-1:r>s?1:n.i-a.i}).map(({entry:n})=>n)}const Jre=e=>e?24:16,eie=(e,t,n)=>{const a=Jre(n);if(t==null)return a;const r=Math.abs(e-t);return r===0?a+14:r===1?a+7:r===2?a+3:a};function tie(){const e=c0(),t=se(N=>N.nodes),n=se(N=>N.setSelectedNodeId),a=pe(N=>N.setTimelineOverviewOpen),r=Nl(),s=zt(),o=WS(),[c,d]=L.useState(null),[h,m]=L.useState(()=>Date.now());L.useEffect(()=>{const N=setInterval(()=>m(Date.now()),6e4);return()=>clearInterval(N)},[]);const p=un(N=>N.transform),x=un(N=>N.width),b=un(N=>N.height),y=L.useMemo(()=>my(t,h),[t,h]),k=L.useMemo(()=>{const[N,D,O]=p,M=-N/O,_=-D/O,R=(x-N)/O,G=(b-D)/O,P=new Set;for(const V of y)V.x+520>M&&V.x<R&&V.y+220>_&&V.y<G&&P.add(V.id);return P},[y,p,x,b]);if(e==="work"||y.length<2)return null;const S=N=>N?N.slice(0,10):"",w=N=>N.slice(5).replace("-","/"),C=N=>N?new Date(N).toLocaleString(o):"",T=c?y.find(N=>N.id===c.id):null;return u.jsxs("div",{className:"absolute left-[2px] top-[calc(38%+116px)] w-[100px] z-10 tdag-timeline pointer-events-none flex flex-col items-stretch","data-timeline-bar":!0,role:"navigation","aria-label":s("timeline.label"),children:[T&&c&&u.jsxs("div",{className:"fixed left-[108px] max-w-[320px] bg-card border border-line rounded-lg shadow-md px-3 py-2 text-xs pointer-events-none z-20",style:{top:c.y-14},children:[u.jsxs("div",{className:"font-medium text-ink truncate",children:[T.topic&&u.jsxs("span",{className:"text-accent",children:[T.topic," · "]}),T.label||"…"]}),T.createdAt&&u.jsxs("div",{className:"text-ink-faint mt-0.5",children:[s("timeline.created")," ",C(T.createdAt)]}),T.modifiedAt&&T.modifiedAt!==T.createdAt&&u.jsxs("div",{className:"text-ink-faint",children:[s("timeline.modified")," ",C(T.modifiedAt)]}),u.jsx("div",{className:"text-[10px] text-ink-faint/80 mt-1",children:s("timeline.clickHint")})]}),u.jsx("button",{onClick:()=>a(!0),title:s("timeline.openOverview"),"data-timeline-overview-btn":!0,className:"pointer-events-auto self-start ml-[25px] w-7 h-7 rounded-lg flex items-center justify-center text-ink-faint/70 hover:text-accent hover:bg-accent/10 transition-colors",children:u.jsx($b,{size:14,strokeWidth:1.75})}),u.jsx("div",{className:"pointer-events-auto overflow-y-auto tdag-noscrollbar max-h-[170px] mt-0.5",children:u.jsx("div",{className:"flex flex-col py-1",children:y.map((N,D)=>{const O=D>0?S(y[D-1].createdAt):"",M=S(N.createdAt),_=M!==""&&M!==O;return u.jsxs("button",{"data-timeline-dot":N.id,onMouseEnter:R=>d({id:N.id,idx:D,y:R.currentTarget.getBoundingClientRect().top}),onMouseLeave:()=>d(R=>R?.id===N.id?null:R),onClick:()=>{n(N.id);const R=r.getViewport().zoom;r.setCenter(N.x+260+om(N.id)/(2*R),N.y+110,{zoom:R,duration:300})},onDoubleClick:()=>{n(N.id),r.setCenter(N.x+260+om(N.id)/2,N.y+110,{zoom:1,duration:350})},className:"relative flex items-center w-full h-[14px] shrink-0 pl-[29px] cursor-pointer","aria-label":N.label,children:[u.jsx("span",{className:`rounded-full ${N.recentlyEdited?"tdag-timeline-pulse":""}`,style:{width:eie(D,c?.idx??null,N.badged),height:4,background:N.color,opacity:N.archived?.3:k.has(N.id)?1:.45,transition:"width .18s ease, opacity .3s ease"}}),_&&u.jsx("span",{className:"absolute left-[67px] top-1/2 -translate-y-1/2 text-[10px] leading-none text-ink-faint select-none whitespace-nowrap",children:w(M)})]},N.id)})})})]})}function M9(e){const t=e.filter(a=>!a.data.archived).map(a=>`${a.id}:${Gc(a.data)??""}:${a.data.summaryTypes?.[a.data.responseIndex]??""}`).sort();let n=5381;for(const a of t)for(let r=0;r<a.length;r++)n=(n<<5)+n+a.charCodeAt(r)|0;return String(n>>>0)}const _b=new Map,nie=(e,t)=>_b.get(`${t}:${e}`),PE={ruleout:"RULEOUT",decision:"DECISION",pivot:"PIVOT",open:"OPEN",insight:"INSIGHT"};async function aie(e,t,n){const a=M9(e),r=_b.get(`${n}:${a}`);if(r)return r;const s=e.find(b=>b.data.isRoot),o=my(e.filter(b=>!b.data.archived),0),d=o.length>60?o.filter((b,y)=>b.badged||y<10||y>=o.length-10):o,h=o.length-d.length,m=d.map(b=>{const y=e.find(C=>C.id===b.id);if(!y)return null;const k=y.data,S=Gc(k);if(!S)return null;const w=k.summaryTypes?.[k.responseIndex]??void 0;return`- ${w&&PE[w]?`${PE[w]}: `:""}${b.topic?`[${b.topic}] `:""}${S}`}).filter(b=>!!b);h>0&&m.push(`(${h} plain steps omitted from this list)`);const x={text:(await Bo([{role:"user",content:`Opening question of a thinking map: ${s?.data.question?.slice(0,300)??"(untitled)"}
|
|
783
783
|
|
|
784
784
|
The takeaway of every step, in the order they were thought (tags: RULEOUT = killed an option, DECISION = chose, PIVOT = reframed, OPEN = still unresolved):
|
|
785
785
|
${m.join(`
|
|
786
786
|
`)}
|
|
787
787
|
|
|
788
|
-
Write the JOURNEY of this thinking as one flowing paragraph a reader absorbs in twenty seconds: where it started, what got ruled out, where it turned, where it landed, what remains open. Only the turns that mattered — do not enumerate every step. Hard limit: 250 characters for CJK languages, 500 characters otherwise. Write in ${n==="zh"?"Chinese":"English"} (the reader's interface language), even if the takeaway lines mix languages. Never use dash characters (—, –, -); use commas, colons or full stops. Output only the paragraph.`}])).trim(),fp:a,at:new Date().toISOString(),lang:n};return _b.set(`${n}:${a}`,x),x}function rie({onLocate:e}){const t=pe(D=>D.timelineOverviewOpen),n=pe(D=>D.setTimelineOverviewOpen),a=se(D=>D.nodes),r=zt(),s=WS(),o=Ra(D=>D.lang),c=L.useMemo(()=>my(a,0),[a]),d=L.useMemo(()=>M9(a),[a]),[h,m]=L.useState(null),[p,x]=L.useState(!1),[b,y]=L.useState(!1),k=nie(d,o)??h,S=!!k&&(k.fp!==d||k.lang!==o),w=()=>{x(!0),y(!1);const{nodes:D,edges:O}=se.getState();aie(D,O,o).then(m).catch(()=>y(!0)).finally(()=>x(!1))};if(!t)return null;const C=()=>n(!1),T=D=>D?D.slice(0,10):"",N=D=>D?new Date(D).toLocaleTimeString(s,{hour:"2-digit",minute:"2-digit"}):"—";return Qa.createPortal(u.jsx("div",{className:"fixed inset-0 z-[60] bg-ink/30 backdrop-blur-sm flex items-center justify-center p-6",onClick:C,children:u.jsxs("div",{className:"bg-card rounded-2xl shadow-2xl border border-line w-[640px] max-h-[80vh] flex flex-col",onClick:D=>D.stopPropagation(),children:[u.jsxs("div",{className:"flex items-center gap-2 px-5 py-3 border-b border-line shrink-0",children:[u.jsx($b,{size:15,strokeWidth:1.75,className:"text-accent"}),u.jsx("span",{className:"text-sm font-semibold text-ink",children:r("tlov.title")}),u.jsx("span",{className:"text-2xs text-ink-faint",children:We(r("tlov.count"),{n:c.length})}),u.jsx("div",{className:"flex-1"}),u.jsxs("button",{onClick:()=>{C(),pe.getState().setThoughtMapOpen(!0)},disabled:c.length===0,"data-tmap-from-timeline":!0,className:"flex items-center gap-1.5 text-2xs text-ink-muted hover:text-accent hover:bg-accent/10 rounded-full px-2.5 py-1 transition-colors disabled:opacity-50",children:[u.jsx(Yb,{size:13,strokeWidth:1.75}),r("tmap.export")]}),u.jsx("button",{onClick:C,className:"text-ink-faint hover:text-ink w-7 h-7 rounded-lg hover:bg-wash flex items-center justify-center transition-colors",children:u.jsx(mn,{size:15,strokeWidth:1.75})})]}),u.jsxs("div",{className:"px-5 pt-3 shrink-0","data-gedankengang":!0,children:[!k&&!p&&u.jsxs("button",{onClick:w,className:"flex items-center gap-1.5 text-2xs text-accent bg-accent/10 hover:bg-accent/20 rounded-full px-3 py-1.5 transition-colors",children:[u.jsx(Bf,{size:12,strokeWidth:1.75}),r("tlov.gedankenGenerate")]}),p&&u.jsx("p",{className:"text-2xs text-ink-faint italic py-1.5",children:r("tlov.gedankenLoading")}),b&&!p&&u.jsx("p",{className:"text-2xs text-red-500 py-1",children:r("tlov.gedankenFailed")}),k&&!p&&u.jsxs("div",{className:`rounded-xl bg-wash px-4 py-3 ${S?"opacity-60":""}`,children:[u.jsx("p",{className:"text-sm text-ink leading-relaxed",children:k.text}),u.jsxs("div",{className:"flex items-center gap-2 mt-1.5",children:[u.jsx("span",{className:"text-2xs text-ink-faint",children:S?r("tlov.gedankenStale"):new Date(k.at).toLocaleString(s)}),S&&u.jsx("button",{onClick:w,className:"text-2xs text-accent hover:underline",children:r("tlov.gedankenRedo")})]})]})]}),u.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-5 py-3","data-timeline-overview":!0,children:[c.length===0&&u.jsx("p",{className:"text-xs text-ink-faint italic py-2",children:r("tlov.empty")}),c.map((D,O)=>{const M=O>0?T(c[O-1].createdAt):void 0,_=T(D.createdAt),R=O===0||_!==M;return u.jsxs("div",{children:[R&&u.jsx("div",{className:"sticky top-0 bg-card text-2xs text-ink-faint font-medium pt-3 pb-1 first:pt-0",children:_||r("tlov.undated")}),u.jsxs("div",{className:"group flex items-center gap-2.5 py-1.5 border-b border-line/50 last:border-0",children:[u.jsx("span",{className:"w-2 h-2 rounded-full shrink-0",style:{background:D.color,opacity:D.archived?.35:1}}),u.jsx("span",{className:"text-2xs font-mono text-ink-faint shrink-0 w-11",children:N(D.createdAt)}),u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsxs("p",{className:`text-sm truncate ${D.archived?"text-ink-faint line-through":D.badged?"text-ink":"text-ink-muted"}`,children:[D.topic&&u.jsxs("span",{className:"font-medium text-accent",children:[D.topic," · "]}),D.label||"…"]}),D.modifiedAt&&D.modifiedAt!==D.createdAt&&u.jsxs("p",{className:"text-2xs text-ink-faint",children:[r("timeline.modified")," ",new Date(D.modifiedAt).toLocaleString(s)]})]}),u.jsx("button",{className:"shrink-0 text-2xs font-mono text-accent bg-accent/10 hover:bg-accent/20 rounded-full px-1.5 py-0.5 transition-colors opacity-0 group-hover:opacity-100",onClick:()=>{C(),e(D.id)},title:r("hlov.locateTitle"),children:r("tlov.locate")})]})]},D.id)})]})]})}),document.body)}const iie=L.memo(function(t){const n=rn(a=>a.projects.find(r=>r.id===a.activeId)?.kind==="paradigm");return t.data?.stepKind==="frame"?u.jsx(Hne,{...t}):rm(t.data?.stepKind)?u.jsx(Bne,{...t}):n?u.jsx(Mne,{...t}):u.jsx(Nne,{...t})}),sie={thought:iie},oie={smoothstep:L.memo(qne)};function lie(){const[e,t]=L.useState(kt||se.persist.hasHydrated());return L.useEffect(()=>se.persist.onFinishHydration(()=>t(!0)),[]),L.useEffect(()=>{if(!e||kt)return;let n;const a=()=>{clearTimeout(n),n=setTimeout(()=>{Jae()},800)},r=se.subscribe((s,o)=>{s.nodes!==o.nodes&&a()});return a(),()=>{r(),clearTimeout(n)}},[e]),L.useEffect(()=>{pe.getState().condenseRun.status==="building"&&pe.getState().setCondenseRun({status:"idle",current:0,total:0,streaming:""})},[]),L.useEffect(()=>{if(kt)return;const n=setTimeout(()=>{ere()},6e3);return()=>clearTimeout(n)},[]),L.useEffect(()=>{if(!e||kt||localStorage.getItem("thoughtdag.tutorialDone")||se.getState().nodes.length>0)return;const n=setTimeout(()=>pe.getState().setTutorialOpen(!0),900);return()=>clearTimeout(n)},[e]),L.useEffect(()=>{ire()},[]),L.useEffect(()=>{kt||(Tt(()=>import("./session-handoff-BXosSY-e.js"),[]).then(n=>n.consumeSessionHandoff()),Tt(()=>import("./live-mirror-C9sTXAvv.js"),[]).then(n=>n.startLiveMirror()),Tt(()=>import("./canvas-record-Be2aKIf8.js"),[]).then(n=>n.startCanvasRecord()),Tt(()=>import("./canonical-ChxvAi6N.js"),[]).then(n=>n.unsubscribeOrphanedSessions()))},[]),L.useEffect(()=>{kt||rre().then(n=>{n&&(n.status==="minted"?(Qe("success",De("provider.oauthMinted")),k9(n.key)):Qe("error",We(De("provider.oauthFailed"),{error:n.error})))})},[]),u.jsxs(u.Fragment,{children:[e&&u.jsx(cie,{}),u.jsx(cre,{}),u.jsx(dre,{}),u.jsx(mre,{}),u.jsx(pre,{}),u.jsx(gre,{}),u.jsx(xre,{}),u.jsx(bre,{}),u.jsx(Sre,{}),u.jsx(Mre,{}),u.jsx(sre,{}),u.jsx(Fre,{}),u.jsx(Gre,{}),u.jsx($re,{})]})}function cie(){const{nodes:e,edges:t,setNodes:n,setEdges:a,addQuestion:r,undo:s,redo:o,addCrossLink:c,setSelectedNodeId:d,setSelectedNodeIds:h,history:m,historyIndex:p,relayout:x}=se(),b=zt(),y=pe(ae=>ae.setTutorialOpen),k=pe(ae=>ae.annotationsHidden),S=pe(ae=>ae.setAnnotationsHidden),[w,C]=L.useState(""),[T,N]=L.useState(!1),[D,O]=L.useState(""),[M,_]=L.useState(!1),[R,G]=L.useState(!1),[P,V]=L.useState([]),[J,H]=L.useState(!1),F=L.useRef(null),B=L.useRef(null),W=e.length>0,Q=se(ae=>ae.events.length>0),K=se(ae=>ae.nodes.reduce((ke,Ne)=>ke+(Ne.data.highlights?.length??0),0)),U=se(ae=>ae.nodes.reduce((ke,Ne)=>ke+(Ne.data.attachments?.length??0)+(["note","link"].includes(Ne.data.stepKind??"")?1:0),0)),q=L.useRef(null),te=pe(ae=>ae.arrivalFocusNodeId);L.useEffect(()=>{if(!te)return;const ae=se.getState().nodes.find(ke=>ke.id===te);ae&&(pe.getState().setArrivalFocusNodeId(null),window.setTimeout(()=>{q.current?.setCenter(ae.position.x+260,ae.position.y+140,{zoom:.9,duration:400})},150))},[te]);const $=As(ae=>ae.paper),be=As(ae=>ae.lighting),Te=As(ae=>ae.resolved),Se=L.useMemo(()=>One(),[Te]),Be=L.useMemo(()=>{const ae=getComputedStyle(document.documentElement),ke=(ae.getPropertyValue("--color-surface").trim()||"#FAF9F7").replace("#",""),[Ne,ce,je]=[0,2,4].map(Ze=>parseInt(ke.slice(Ze,Ze+2),16));return{mask:`rgba(${Ne},${ce},${je},0.7)`,archived:ae.getPropertyValue("--color-wash").trim()||"#EFEDE9",ordinary:Te==="dark"?"#6E6759":"#B9B3AB"}},[Te]),X=L.useRef(e.length),oe=L.useCallback((ae,ke={})=>{const Ne=q.current;if(!Ne)return;const ce=ke.zoom??Ne.getZoom();Ne.setCenter(ae.position.x+(ke.offX??260)+om(ae.id)/(2*ce),ae.position.y+110,{zoom:ce,duration:ke.duration??350})},[]),ve=Ra(ae=>ae.lang),Le=pe(ae=>ae.condenseRun),Re=Le.status==="building",Ce=rn(ae=>ae.projects.find(ke=>ke.id===ae.activeId)?.kind==="paradigm"),tt=_l();L.useEffect(()=>{if(kt||!W||se.getState().nodes.length<10)return;const ae=Number(localStorage.getItem("thoughtdag.lastBackupAt")??0);if(ae===0){localStorage.setItem("thoughtdag.lastBackupAt",String(Date.now()));return}Date.now()-ae<168*3600*1e3||sessionStorage.getItem("thoughtdag.backupNudged")||(sessionStorage.setItem("thoughtdag.backupNudged","yes"),Qe("info",De("backup.nudge"),0,{label:De("backup.nudgeBtn"),run:()=>yf()}))},[W]);const Ve=L.useCallback(()=>{const{nodes:ae,edges:ke}=Zae(ve),Ne=se.getState();Ne.setNodes([...Ne.nodes,...ae.filter(ce=>!Ne.nodes.some(je=>je.id===ce.id))]),Ne.setEdges([...Ne.edges,...ke.filter(ce=>!Ne.edges.some(je=>je.id===ce.id))]),Ne.pushHistory(),setTimeout(()=>{const ce=q.current;ce&&(ce.fitView({duration:500,padding:.1}),setTimeout(()=>{if(ce.getViewport().zoom<.34){const je=[...se.getState().nodes].sort((Ze,st)=>(Ze.data.createdAt??"").localeCompare(st.data.createdAt??""))[0];je&&ce.setCenter(je.position.x+300,je.position.y+240,{zoom:.6,duration:550})}},680))},100),localStorage.getItem("thoughtdag.tutorialDone")||y(!0)},[ve,y]),ze=L.useCallback(ae=>{const ke=se.getState(),Ne=ke.nodes[ke.nodes.length-1],ce=Ne?{x:Ne.position.x,y:Ne.position.y+340}:{x:120,y:80},je=In();ke.setNodes([...ke.nodes,{id:je,type:"thought",position:ce,dragHandle:".drag-handle",data:{question:"",instruction:"",stepKind:ae,response:"",responses:[],responseIndex:-1,isCollapsed:!1,isEditing:!1,isEditingResponse:!1,isLoading:!1,tokenCount:0,highlights:[],highlightMode:"tag",attachments:[],excludedAttachmentIds:[],includedAttachmentIds:[],roleMode:"inherit",isRoot:ke.nodes.length===0,isBranch:!1}}]),ke.pushHistory()},[]),bt=L.useCallback(()=>{X.current=se.getState().nodes.length,setTimeout(()=>q.current?.fitView({duration:300,padding:.2}),50)},[]),ct=L.useRef(null),Ke=L.useCallback(ae=>{const ke=se.getState(),Ne=In();ke.setNodes([...ke.nodes,{id:Ne,type:"thought",position:ae,width:640,height:420,zIndex:-1,dragHandle:".drag-handle",data:{question:"",stepKind:"frame",frameCarry:!1,response:"",responses:[],responseIndex:-1,isCollapsed:!1,isEditing:!1,isEditingResponse:!1,isLoading:!1,tokenCount:0,highlights:[],highlightMode:"tag",attachments:[],excludedAttachmentIds:[],includedAttachmentIds:[],roleMode:"inherit",isRoot:!1,isBranch:!1}}]),ke.pushHistory()},[]),it=L.useCallback(ae=>{const ke=[];for(const Ne of Array.from(ae)){const ce=Ne.name.split(".").pop()?.toLowerCase()??"";Ne.type.startsWith("image/")||Ne.type==="application/pdf"||Ne.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(ce)?ke.push(Ne):Qe("info",We(De("toast.unsupportedFile"),{name:Ne.name}))}return ke},[]),vt=L.useCallback(ae=>{const ke=se.getState(),Ne=In();return ke.setNodes([...ke.nodes,{id:Ne,type:"thought",position:ae,dragHandle:".drag-handle",data:{question:"",response:"",responses:[],responseIndex:-1,isCollapsed:!1,isEditing:!1,isEditingResponse:!1,isLoading:!1,tokenCount:0,highlights:[],highlightMode:"tag",attachments:[],excludedAttachmentIds:[],includedAttachmentIds:[],roleMode:"inherit",isRoot:!1,isBranch:!1,webSearch:pe.getState().webSearchEnabled,scholarSearch:pe.getState().scholarSearchEnabled}}]),ke.pushHistory(),Ne},[]),He=L.useCallback(ae=>{const ke=it(ae);if(ke.length===0)return;let Ne=null;ke.forEach((ce,je)=>{const Ze=ei("file",{x:120+je%3*480,y:120+Math.floor(je/3)*620});Cd(Ze,[ce]),!Ne&&!ce.type.startsWith("image/")&&(Ne=Ze)}),Ne&&pe.getState().setReaderNodeId(Ne),setTimeout(()=>q.current?.fitView({duration:400,padding:.2}),120)},[it]),It=L.useCallback((ae,ke)=>{const Ne=ae.clientX,ce=ae.clientY,je=ae.currentTarget;let Ze=null;const st=Ut=>{!Ze&&Math.hypot(Ut.clientX-Ne,Ut.clientY-ce)>6&&(Ze=document.createElement("div"),Ze.innerHTML=je.innerHTML,Ze.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(Ze)),Ze&&(Ze.style.left=`${Ut.clientX-18}px`,Ze.style.top=`${Ut.clientY-18}px`)},Pt=Ut=>{window.removeEventListener("pointermove",st),window.removeEventListener("pointerup",Pt);const Kt=!!Ze;Ze?.remove(),ke(Kt?{x:Ut.clientX,y:Ut.clientY}:null)};window.addEventListener("pointermove",st),window.addEventListener("pointerup",Pt)},[]),re=L.useCallback(ae=>{const ke=q.current?.screenToFlowPosition(ae??{x:window.innerWidth/2,y:window.innerHeight/2})??{x:140,y:140};return{x:ke.x-200,y:ke.y-60}},[]);L.useEffect(()=>{const ae=Ne=>{ct.current={x:Ne.clientX,y:Ne.clientY}},ke=Ne=>{if(kt)return;const ce=Ne.target;if(ce&&(ce.tagName==="INPUT"||ce.tagName==="TEXTAREA"||ce.isContentEditable))return;const je=rn.getState(),Ze=je.projects.find(Qt=>Qt.id===je.activeId)?.kind==="paradigm";if(se.getState().nodes.length===0&&!Ze)return;const st=Ne.clipboardData;if(!st)return;const Pt=re(ct.current),Ut=st.getData("text/plain").trim(),Kt=Array.from(st.files),ia=Kt.some(Qt=>!Qt.type.startsWith("image/"));if(Kt.length>0&&(ia||!Ut)){Ne.preventDefault();const Qt=ei("file",Pt);Cd(Qt,Kt);return}if(Ut)if(Ne.preventDefault(),/^https?:\/\/\S+$/.test(Ut)){const Qt=ei("link",Pt,{linkUrl:Ut});c9(Qt,Ut)}else ei("note",Pt,{question:Lne(Ut)})};return window.addEventListener("mousemove",ae),window.addEventListener("paste",ke),()=>{window.removeEventListener("mousemove",ae),window.removeEventListener("paste",ke)}},[re]);const qe=L.useCallback(async()=>{const ae=se.getState();if(ae.nodes.length===0)return;const{nodes:ke,edges:Ne}=xF(ae.nodes,ae.edges),ce=rn.getState(),je=ce.projects.find(st=>st.id===ce.activeId)?.name??"Paradigm",Ze=crypto.randomUUID();await Hr(si(Ze),JSON.stringify({state:{nodes:ke,edges:Ne},version:1})),await Yc(Ze,`▶ ${je}`,"chat"),await N7(Ze,je),X.current=se.getState().nodes.length,setTimeout(()=>q.current?.fitView({duration:400,padding:.15}),150)},[]);L.useEffect(()=>{e.length===0&&!Ce&&!localStorage.getItem("thoughtdag.seeded")&&localStorage.setItem("thoughtdag.seeded","yes")},[]),L.useEffect(()=>{if(e.length>X.current&&q.current){const ae=e[e.length-1];ae&&setTimeout(()=>oe(ae,{zoom:1,duration:400,offX:220}),100)}X.current=e.length},[e,oe]);const xe=L.useCallback(ae=>{const ke=se.getState().nodes;n(X8(ae,ke))},[n]),$e=L.useCallback(ae=>a(Q8(ae,se.getState().edges)),[a]),ft=L.useRef(null),yt=L.useCallback((ae,ke)=>{if(ke.data.stepKind!=="frame"||ke.data.frameCarry===!1)return;const Ne=se.getState(),ce=Ne.nodes.find(Ze=>Ze.id===ke.id);if(!ce)return;const je=p7(ce,Ne.nodes).filter(Ze=>!Ze.selected).map(Ze=>({id:Ze.id,start:Ze.position}));je.length!==0&&(ft.current={frameId:ce.id,start:ce.position,members:je})},[]),At=L.useCallback((ae,ke)=>{const Ne=ft.current;if(!Ne||ke.id!==Ne.frameId)return;const ce=ke.position.x-Ne.start.x,je=ke.position.y-Ne.start.y,Ze=new Map(Ne.members.map(st=>[st.id,{x:st.start.x+ce,y:st.start.y+je}]));se.setState(st=>({nodes:st.nodes.map(Pt=>{const Ut=Ze.get(Pt.id);return Ut?{...Pt,position:Ut}:Pt})}))},[]),qt=L.useCallback(()=>{ft.current=null},[]),[hn,wn]=L.useState(null),[Yt,kn]=L.useState(null),sn=L.useCallback((ae,ke)=>{kt||window.getSelection()?.toString()||(ae.preventDefault(),kn({x:ae.clientX,y:ae.clientY,nodeId:ke.id}))},[]),ka=L.useCallback((ae,ke)=>{ae.preventDefault(),wn({x:ae.clientX,y:ae.clientY,edgeId:ke.id})},[]);L.useEffect(()=>{if(!hn)return;const ae=()=>wn(null);return window.addEventListener("click",ae),()=>window.removeEventListener("click",ae)},[hn]);const Fn=se(ae=>ae.deleteEdges),ur=L.useCallback(ae=>{Fn([ae]),wn(null)},[Fn]),er=L.useCallback(ae=>{ae.source&&ae.target&&c(ae.source,ae.target)},[c]),Qn=L.useCallback(()=>{window.getSelection()?.removeAllRanges(),document.body.classList.add("tdag-connecting")},[]),Ba=L.useCallback((ae,ke)=>{if(document.body.classList.remove("tdag-connecting"),Ce||ke.isValid||ke.fromHandle?.type!=="source"||!ke.fromNode)return;const Ne=ke.fromNode.id,ce=ae.target?.closest?.(".react-flow__node");if(ce){const Kt=ce.getAttribute("data-id");if(Kt&&Kt!==Ne){const ia=se.getState().nodes.find(Da=>Da.id===Kt),Qt=ia?.data.stepKind??"";ia&&!["note","file","link","frame"].includes(Qt)&&se.getState().addCrossLink(Ne,Kt)}return}const{clientX:je,clientY:Ze}="changedTouches"in ae?ae.changedTouches[0]:ae,st=re({x:je,y:Ze}),Pt=se.getState();if(Pt.nodes.find(Kt=>Kt.id===Ne)?.data.stepKind==="frame")return;const Ut=vt(st);Pt.setEdges([...se.getState().edges,{id:`edge-${Ne}-${Ut}`,source:Ne,target:Ut,sourceHandle:"continue",targetHandle:"top",type:"smoothstep",style:{stroke:rt.accent,strokeWidth:2},animated:!1,markerEnd:{type:"arrowclosed",color:rt.accent,width:18,height:18},data:{}}]),se.getState().pushHistory()},[Ce,re,vt]),Jt=se(ae=>ae.selectedNodeId),ue=se(ae=>ae.selectedNodeIds),Fe=pe(ae=>ae.panelOpen),mt=pe(ae=>ae.viewerLoadError),Dt=se(ae=>ae.staleIds.length),En=pe(ae=>ae.panelWidth),on=e.find(ae=>ae.id===Jt)?.data.stepKind,wt=rm(on)||on==="frame",pt=Fe&&!!Jt&&!Ce&&!wt,Lt=ue.length>1,On=se(ae=>ae.batchDelete);L.useEffect(()=>{const ae=ke=>{if(!pe.getState().confirmRequest&&!(kt&&!((ke.metaKey||ke.ctrlKey)&&ke.key==="f"))){if((ke.metaKey||ke.ctrlKey)&&ke.key==="z"&&(ke.shiftKey?(ke.preventDefault(),o()):(ke.preventDefault(),s())),(ke.metaKey||ke.ctrlKey)&&ke.key==="f"){ke.preventDefault(),N(!0);return}{const Ne=ke.target;if(!(Ne.tagName==="INPUT"||Ne.tagName==="TEXTAREA"||Ne.isContentEditable)&&Jt&&!Ce&&!ke.metaKey&&!ke.ctrlKey&&!ke.altKey){const{nodes:je,edges:Ze}=se.getState();if(ke.key===" "){ke.preventDefault(),se.getState().toggleCollapse(Jt);return}if(ke.key==="r"||ke.key==="R"){ke.preventDefault(),se.getState().rerunNode(Jt,{});return}if(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(ke.key)){const st=Ze.filter(Ut=>!Ut.data?.isCrossLink);let Pt;if(ke.key==="ArrowUp")Pt=st.find(Ut=>Ut.target===Jt)?.source;else if(ke.key==="ArrowDown")Pt=st.find(Ut=>Ut.source===Jt)?.target;else{const Ut=st.find(Qt=>Qt.target===Jt),Kt=Ut?st.filter(Qt=>Qt.source===Ut.source).map(Qt=>Qt.target):je.filter(Qt=>!st.some(Da=>Da.target===Qt.id)).map(Qt=>Qt.id),ia=Kt.indexOf(Jt);ia!==-1&&Kt.length>1&&(Pt=Kt[(ia+(ke.key==="ArrowRight"?1:Kt.length-1))%Kt.length])}if(Pt){ke.preventDefault(),d(Pt);const Ut=je.find(Kt=>Kt.id===Pt);Ut&&oe(Ut,{zoom:1,duration:300})}return}}}if(ke.key==="Escape"){const Ne=ke.target;if(Ne.tagName==="INPUT"||Ne.tagName==="TEXTAREA"||Ne.isContentEditable)return;ue.length>1?h([]):Jt&&d(null);return}if(ke.key==="Delete"||ke.key==="Backspace"){const Ne=ke.target;if(Ne.tagName==="INPUT"||Ne.tagName==="TEXTAREA"||Ne.isContentEditable)return;if(ue.length>1)ke.preventDefault(),_s({title:De("confirm.deleteNodesTitle"),message:We(De("confirm.deleteNodes"),{n:ue.length}),confirmLabel:De("common.delete"),danger:!0}).then(ce=>{ce&&On(ue)});else{const ce=t.filter(je=>je.selected).map(je=>je.id);ce.length>0&&(ke.preventDefault(),Fn(ce))}}}};return window.addEventListener("keydown",ae),()=>window.removeEventListener("keydown",ae)},[s,o,Jt,ue,d,h,On,t,Fn,Ce,oe]);const Mn=()=>{w.trim()&&(r(w.trim(),{rolePrompt:D.trim()||void 0,initialAttachments:P.length>0?P:void 0}),C(""),O(""),_(!1),V([]))},ge=async ae=>{for(const ke of Array.from(ae))await l0(ke,{add:Ne=>V(ce=>[...ce,Ne]),update:(Ne,ce)=>V(je=>je.map(Ze=>Ze.id===Ne?{...Ze,...ce}:Ze))})},Je=ae=>{ae.key==="Enter"&&!ae.shiftKey&&!Xa(ae)&&(ae.preventDefault(),Mn())},Nt=L.useCallback(({nodes:ae})=>{const ke=ae.map(Ne=>Ne.id);ke.length>1?h(ke):ke.length===1&&d(ke[0])},[d,h]),Ct=L.useMemo(()=>e.filter(ae=>ae.data.stepKind==="frame"),[e]),[ut,jt]=L.useState(!1),en=L.useRef(null);L.useEffect(()=>{if(!ut)return;const ae=ke=>{en.current?.contains(ke.target)||jt(!1)};return window.addEventListener("mousedown",ae),()=>window.removeEventListener("mousedown",ae)},[ut]);const[Xt,xn]=L.useState(!1),he=pe(ae=>ae.pluginUpdate),[Bt,fn]=L.useState(0),Cn=pe(ae=>ae.searchHitIds!==null),Sn=L.useRef(null);L.useEffect(()=>{if(!Xt)return;const ae=ke=>{Sn.current?.contains(ke.target)||xn(!1)};return window.addEventListener("mousedown",ae),()=>window.removeEventListener("mousedown",ae)},[Xt]);const ea=pe(ae=>ae.searchHitIds),xa=L.useMemo(()=>{if(!Jt||ue.length>1||!e.some(st=>st.id===Jt))return null;const ae=Sm(Jt,e,t),ke=new Set;for(const st of ae.mainline)st.id!==Jt&&ke.add(st.id);for(const st of ae.materials)ke.add(st.id);for(const st of ae.references)ke.add(st.source.id);const Ne=t.filter(st=>!st.data?.isCrossLink),ce=Ur(Jt,e,Ne).visitedEdgeIds,je=new Set(ae.references.map(st=>st.edge.id)),Ze=Ne.filter(st=>st.source===Jt);return{ctx:ke,down:new Set(Ze.map(st=>st.target)),pathEdgeIds:ce,refEdgeIds:je,downEdgeIds:new Set(Ze.map(st=>st.id))}},[Jt,ue,e,t]),Wr=L.useMemo(()=>{const ae=e.filter(ce=>ce.data.stepKind==="frame").map((ce,je)=>({id:ce.id,order:je,area:(ce.measured?.width??ce.width??640)*(ce.measured?.height??ce.height??420)})).sort((ce,je)=>je.area-ce.area||ce.order-je.order),ke=new Map(ae.map((ce,je)=>[ce.id,je-ae.length]));let Ne=e.map(ce=>ce.data.stepKind==="frame"?{...ce,zIndex:ke.get(ce.id)??-1}:ce);return k&&(Ne=Ne.map(ce=>{const je=ce.data.stepKind,Ze=rm(je)&&!t.some(st=>st.source===ce.id||st.target===ce.id);return je==="frame"||Ze?{...ce,hidden:!0}:ce})),ea!==null&&(Ne=Ne.map(ce=>ea.has(ce.id)||ce.data.stepKind==="frame"?{...ce,className:"search-hit"}:ce.className==="search-hit"?{...ce,className:void 0}:ce)),xa&&(Ne=Ne.map(ce=>{const je=ce.id===Jt?"target":xa.ctx.has(ce.id)?"ctx":xa.down.has(ce.id)?"down":ce.data.stepKind==="frame"?void 0:"dim";return je?{...ce,className:[ce.className,`focus-${je}`].filter(Boolean).join(" "),...je!=="dim"?{data:{...ce.data,focusRole:je}}:{}}:ce})),Ne},[e,t,k,ea,xa,Jt]),ra=L.useMemo(()=>{const ae=t.map(ce=>{const je=ce.data?.isBranchFromSelection?{...ce,animated:!1,style:{...ce.style,strokeDasharray:void 0}}:ce,Ze=typeof je.style?.stroke=="string"?lE[je.style.stroke.toUpperCase()]:void 0,st=je.markerEnd&&typeof je.markerEnd=="object"?je.markerEnd:void 0,Pt=typeof st?.color=="string"?lE[st.color.toUpperCase()]:void 0;return!Ze&&!Pt?je:{...je,...Ze?{style:{...je.style,stroke:Se[Ze]}}:{},...Pt&&st?{markerEnd:{...st,color:Se[Pt]}}:{}}});if(xa)return ae.map(ce=>xa.pathEdgeIds.has(ce.id)?{...ce,className:"focus-e-path",style:{...ce.style,stroke:Se.accent,strokeWidth:3.5,opacity:1},markerEnd:{type:"arrowclosed",...ce.markerEnd&&typeof ce.markerEnd=="object"?ce.markerEnd:{},color:Se.accent},zIndex:10,data:{...ce.data,focusRole:"path"}}:xa.refEdgeIds.has(ce.id)?{...ce,style:{...ce.style,opacity:.9},zIndex:5,data:{...ce.data,focusRole:"ref"}}:xa.downEdgeIds.has(ce.id)?{...ce,className:"focus-e-down",style:{...ce.style,strokeWidth:2.5,opacity:.85},markerEnd:{type:"arrowclosed",...ce.markerEnd&&typeof ce.markerEnd=="object"?ce.markerEnd:{}},zIndex:5,data:{...ce.data,focusRole:"down"}}:{...ce,style:{...ce.style,strokeWidth:1.5,opacity:.2},zIndex:0});const ke=ue.length>1?ue:[];if(ke.length===0)return ae;const{visitedEdgeIds:Ne}=Ur(ke,e,t);return ae.map(ce=>Ne.has(ce.id)?{...ce,style:{...ce.style,stroke:Se.trace,strokeWidth:3.5,opacity:1},markerEnd:{type:"arrowclosed",...ce.markerEnd&&typeof ce.markerEnd=="object"?ce.markerEnd:{},color:Se.trace},zIndex:10}:{...ce,style:{...ce.style,strokeWidth:1.5,opacity:.2},zIndex:0})},[e,t,ue,Se,xa]);return L.useEffect(()=>{if(!pt||!Jt)return;const ae=setTimeout(()=>{const ke=q.current;if(!ke)return;const Ne=se.getState().nodes.find(Pt=>Pt.id===Jt);if(!Ne)return;const ce=ke.getViewport(),je=Ne.measured?.width??Ne.width??480,Ze=(Ne.position.x+je)*ce.zoom+ce.x,st=window.innerWidth-pe.getState().panelWidth-xd-24;if(Ze>st){const Pt=(Ne.position.x+je/2)*ce.zoom+ce.x;ke.setViewport({...ce,x:ce.x-(Pt-st/2)},{duration:300})}},60);return()=>clearTimeout(ae)},[pt,Jt]),u.jsxs("div",{className:"relative w-full h-full","data-searching":Cn||void 0,children:[u.jsxs("div",{className:"relative h-full w-full",onDoubleClick:ae=>{ae.target.classList.contains("react-flow__pane")&&!Ce&&vt(re({x:ae.clientX,y:ae.clientY}))},onDragOver:ae=>{(ae.dataTransfer.types.includes("application/thoughtdag-content")||ae.dataTransfer.types.includes("Files"))&&(ae.preventDefault(),ae.dataTransfer.dropEffect="copy",!W&&!Ce&&H(!0))},onDrop:ae=>{if(kt)return;const ke=ae.target;if(!W&&!Ce&&ae.dataTransfer.files.length>0){ae.preventDefault(),H(!1),He(ae.dataTransfer.files);return}const Ne=ke.closest?.(".react-flow__node"),ce=Ne&&se.getState().nodes.find(st=>st.id===Ne.getAttribute("data-id"))?.data.stepKind==="frame";if(!ke.classList?.contains("react-flow__pane")&&!ce)return;const je=re({x:ae.clientX,y:ae.clientY}),Ze=ae.dataTransfer.getData("application/thoughtdag-content");if(Ze==="ask"){ae.preventDefault(),vt(je);return}if(Ze==="frame"){ae.preventDefault(),Ke(je);return}if(Ze==="note"||Ze==="file"){ae.preventDefault(),ei(Ze,je);return}if(ae.dataTransfer.files.length>0){ae.preventDefault();const st=it(ae.dataTransfer.files);if(st.length===0)return;const Pt=ei("file",je);Cd(Pt,st)}},children:[u.jsxs(kj,{onInit:ae=>{q.current=ae,h9.current=ae;const ke=pe.getState().arrivalFocusNodeId;if(ke){pe.getState().setArrivalFocusNodeId(null);const Ne=se.getState().nodes.find(ce=>ce.id===ke);Ne&&window.setTimeout(()=>{ae.setCenter(Ne.position.x+260,Ne.position.y+140,{zoom:.9,duration:400})},150)}},nodes:Wr,edges:ra,onNodesChange:xe,onEdgesChange:$e,onNodeDragStart:yt,onNodeDrag:At,onNodeDragStop:qt,onConnect:er,onConnectStart:Qn,onConnectEnd:Ba,onEdgeContextMenu:ka,onNodeContextMenu:sn,nodeTypes:sie,edgeTypes:oie,deleteKeyCode:null,fitView:!0,onlyRenderVisibleElements:!0,minZoom:.04,maxZoom:2,defaultEdgeOptions:{type:"smoothstep",animated:!1,style:{stroke:Se.accent,strokeWidth:2},markerEnd:{type:"arrowclosed",color:Se.accent,width:18,height:18}},snapToGrid:$==="grid",snapGrid:[22,22],proOptions:{hideAttribution:!0},nodeDragThreshold:5,connectionRadius:40,selectionMode:Oc.Partial,selectionOnDrag:!kt,nodesDraggable:!kt,nodesConnectable:!kt,panOnDrag:kt?!0:[1,2],zoomOnDoubleClick:!1,connectionLineStyle:{stroke:Se.accent,strokeDasharray:"8 4",strokeWidth:2},onSelectionChange:Nt,onPaneClick:()=>{d(null),h([]),kn(null)},children:[$==="grid"?u.jsxs(u.Fragment,{children:[u.jsx(h1,{id:"grid-fine",variant:yi.Lines,gap:22,color:"var(--canvas-grid-fine)"}),u.jsx(h1,{id:"grid-major",variant:yi.Lines,gap:110,color:"var(--canvas-grid-major)"})]}):u.jsx(h1,{variant:yi.Dots,gap:24,size:1,color:"var(--canvas-dot)"}),u.jsx(die,{}),u.jsx(uie,{panelShiftWidth:pt?En:0}),u.jsx(tie,{}),u.jsx(Rj,{position:"bottom-left"}),e.length>0&&u.jsx($j,{nodeColor:ae=>{const ke=ae.data;if(ke.archived)return Be.archived;const Ne=ke.stepKind;return Ne==="note"?"#D97706":Ne==="file"||Ne==="link"?"#64748B":Array.isArray(ke.condensedFrom)&&ke.condensedFrom.length?"#8B7CF0":ke.isRoot?Se.accent:ke.isBranch?Se.warm:Be.ordinary},maskColor:Be.mask,style:{width:200,height:140},pannable:!0,zoomable:!0,position:"bottom-right"})]}),!W&&Ce&&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:()=>ze("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(pd,{size:15,strokeWidth:1.75})," ",b("paradigm.addHuman")]}),u.jsxs("button",{onClick:()=>ze("prompt"),className:"text-sm border-2 border-dashed border-accent/50 text-accent hover:bg-accent/10 px-4 py-2.5 rounded-xl transition-colors flex items-center gap-1.5",children:[u.jsx(Oo,{size:15,strokeWidth:1.75})," ",b("paradigm.addPrompt")]})]})]})}),kt&&!W&&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:mt?u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"text-3xl mb-3",children:"🔗"}),u.jsx("div",{className:"text-sm font-semibold text-ink mb-1.5",children:b("viewer.loadError")}),u.jsx("p",{className:"text-xs text-ink-muted leading-relaxed",children:b("viewer.loadErrorHint")})]}):u.jsxs("div",{className:"flex items-center gap-2 text-sm text-ink-muted justify-center",children:[u.jsx(Un,{size:16,strokeWidth:1.75,className:"animate-spin text-accent"})," ",b("viewer.loading")]})})}),!W&&!Ce&&!kt&&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:rt.line,strokeWidth:"2",fill:"none"}),u.jsx("path",{d:"M95 150 C150 150 150 90 205 88",stroke:rt.line,strokeWidth:"2",strokeDasharray:"6 5",fill:"none"}),u.jsx("circle",{cx:"80",cy:"30",r:"7",fill:rt.line}),u.jsx("circle",{cx:"80",cy:"150",r:"7",fill:"none",stroke:rt.line,strokeWidth:"2.5"}),u.jsx("circle",{cx:"80",cy:"262",r:"7",fill:rt.line}),u.jsx("circle",{cx:"218",cy:"88",r:"7",fill:rt.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:rt.line,strokeWidth:"2",fill:"none"}),u.jsx("path",{d:"M225 140 C170 140 170 210 115 212",stroke:rt.line,strokeWidth:"2",strokeDasharray:"6 5",fill:"none"}),u.jsx("circle",{cx:"240",cy:"20",r:"7",fill:rt.line}),u.jsx("circle",{cx:"240",cy:"140",r:"7",fill:"none",stroke:rt.line,strokeWidth:"2.5"}),u.jsx("circle",{cx:"240",cy:"252",r:"7",fill:rt.line}),u.jsx("circle",{cx:"102",cy:"212",r:"7",fill:rt.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:rt.accent}),u.jsx("line",{className:"dag-pop",style:{animationDelay:"0.2s"},x1:"22",y1:"11",x2:"22",y2:"19",stroke:rt.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:rt.accent,strokeWidth:"2.5"}),u.jsx("line",{className:"dag-pop",style:{animationDelay:"0.5s"},x1:"22",y1:"25",x2:"22",y2:"33",stroke:rt.accent,strokeWidth:"2",strokeLinecap:"round"}),u.jsx("circle",{className:"dag-pop",style:{animationDelay:"0.65s"},cx:"22",cy:"37",r:"3.5",fill:rt.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:rt.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:rt.warm})]}),u.jsx("h1",{className:"text-4xl font-semibold tracking-tight text-ink mb-2.5",children:"ThoughtDAG"}),u.jsx("p",{className:"text-sm text-ink-muted",children:b("landing.tagline")}),u.jsx("p",{className:"text-xs text-ink-muted mt-1.5 font-medium",children:b("landing.mechanism")})]}),u.jsxs("div",{className:"bg-card border border-line rounded-xl px-5 py-4 shadow-lg transition-all focus-within:border-accent/50 focus-within:shadow-xl",children:[u.jsx("textarea",{value:w,onChange:ae=>C(ae.target.value),onKeyDown:Je,onPaste:ae=>{if(ae.clipboardData.getData("text/plain").trim())return;const ke=Array.from(ae.clipboardData.items).filter(Ne=>Ne.kind==="file").map(Ne=>Ne.getAsFile()).filter(Boolean);ke.length&&ge(ke)},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}),P.length>0&&u.jsx("div",{className:"flex flex-wrap gap-2 mt-2 pb-1",children:P.map(ae=>u.jsxs("div",{className:"flex items-center gap-1.5 bg-wash rounded-lg px-2.5 py-1.5 group",children:[ae.thumbnailUrl?u.jsx("img",{src:ae.thumbnailUrl,className:"w-6 h-6 rounded object-cover",alt:ae.name}):u.jsx("span",{className:"text-xs",children:u.jsx(vi,{size:16,strokeWidth:1.75})}),u.jsx("span",{className:"text-xs text-ink-muted max-w-[100px] truncate",children:ae.name}),ae.isExtracting&&u.jsx("span",{className:"text-2xs text-accent",children:u.jsx(Un,{className:"animate-spin",size:12,strokeWidth:1.75})}),ae.numPages!=null&&u.jsxs("span",{className:"text-2xs text-ink-faint",children:[ae.numPages,"p"]}),u.jsx("button",{onClick:()=>V(ke=>ke.filter(Ne=>Ne.id!==ae.id)),className:"text-ink-faint hover:text-red-500 text-xs opacity-0 group-hover:opacity-100 transition-opacity",children:u.jsx(mn,{size:14,strokeWidth:1.75})})]},ae.id))}),M&&u.jsxs("div",{className:"space-y-1 mt-2",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx("span",{className:"text-xs text-ink-muted font-medium",children:b("landing.roleLabel")}),u.jsx("button",{onClick:()=>{_(!1),O("")},className:"text-xs text-ink-faint hover:text-ink-muted",children:u.jsx(mn,{size:14,strokeWidth:1.75})})]}),u.jsx("textarea",{value:D,onChange:ae=>O(ae.target.value),placeholder:b("landing.rolePlaceholder"),className:"w-full text-xs border border-line rounded-lg px-3 py-2 focus:outline-none focus:ring-1 focus:ring-accent bg-surface resize-none leading-relaxed",rows:2,autoFocus:!0}),u.jsx(u9,{onPick:O})]}),u.jsxs("div",{className:"flex items-center justify-end mt-2 gap-2",children:[u.jsx(g2,{}),u.jsx("button",{onClick:()=>_(!M),title:b("landing.roleTrayTitle"),className:`rounded-full w-8 h-8 flex items-center justify-center transition-colors shrink-0 ${M||D?"text-accent bg-accent/10 hover:bg-accent/20":"text-ink-faint hover:text-ink-muted hover:bg-line"}`,children:u.jsx(ZP,{size:16,strokeWidth:1.75})}),u.jsx("button",{onClick:()=>F.current?.click(),className:"text-ink-faint hover:text-accent hover:bg-wash rounded-xl px-3 py-2 transition-colors text-sm",title:b("landing.attach"),children:u.jsx(wi,{size:16,strokeWidth:1.75})}),u.jsx("input",{ref:F,type:"file",multiple:!0,accept:Ud,className:"hidden",onChange:ae=>{ge(ae.target.files||[]),ae.target.value=""}}),u.jsx("button",{onClick:Mn,disabled:!w.trim()||P.some(ae=>ae.isExtracting),className:"bg-accent hover:bg-accent-strong disabled:opacity-30 disabled:cursor-not-allowed text-white text-sm px-5 py-2 rounded-xl transition-all",children:P.some(ae=>ae.isExtracting)?b("landing.extracting"):b("landing.send")})]})]}),u.jsxs("div",{onClick:()=>B.current?.click(),className:`mt-3 border-2 border-dashed rounded-xl px-5 py-3.5 cursor-pointer transition-all text-center bg-card/60 backdrop-blur ${J?"border-accent bg-accent/5 ring-2 ring-accent/20":"border-line hover:border-accent/40 hover:bg-accent/5"}`,children:[u.jsxs("div",{className:"flex items-center justify-center gap-2 text-sm text-ink-muted font-medium",children:[u.jsx(Io,{size:15,strokeWidth:1.75,className:"text-accent"})," ",b("landing.docStart")]}),u.jsx("p",{className:"text-2xs text-ink-faint mt-1.5",children:b("landing.docFormats")}),u.jsx("p",{className:"text-2xs text-ink-faint mt-0.5",children:b("landing.docPrivacy")})]}),!!window.desktopSessions&&u.jsxs("button",{onClick:()=>G(!0),className:"w-full mt-3 bg-card/60 backdrop-blur border border-line rounded-xl px-5 py-3.5 hover:border-accent/40 hover:bg-accent/5 transition-all text-center","data-landing-atlas":!0,children:[u.jsxs("div",{className:"flex items-center justify-center gap-2 text-sm text-ink-muted font-medium",children:[u.jsx(EP,{size:15,strokeWidth:1.75,className:"text-accent shrink-0"}),u.jsx("span",{children:b("landing.atlasStart")}),u.jsx(xP,{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:B,type:"file",multiple:!0,accept:Ud,className:"hidden",onChange:ae=>{He(ae.target.files||[]),ae.target.value=""}}),R&&u.jsx(y9,{onClose:()=>G(!1),onSwitched:()=>{G(!1),bt()}}),(!tt||(tt.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(Bd,{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:[ve==="zh"&&u.jsx("button",{onClick:()=>{pe.getState().setApiKeyPresetHint("zhipu"),pe.getState().setApiKeyModalOpen(!0)},className:"text-2xs bg-accent/10 text-accent hover:bg-accent/20 font-medium px-3 py-1.5 rounded-lg transition-colors shrink-0","data-quick-zhipu":!0,children:b("landing.quickZhipu")}),u.jsx("button",{onClick:()=>{w9()},className:"text-2xs bg-accent/10 text-accent hover:bg-accent/20 font-medium px-3 py-1.5 rounded-lg transition-colors shrink-0","data-quick-primary":!0,children:b("landing.quickOpenRouter")}),u.jsx("button",{onClick:()=>pe.getState().setApiKeyModalOpen(!0),className:"text-2xs text-ink-muted hover:text-ink hover:bg-wash font-medium px-3 py-1.5 rounded-lg transition-colors shrink-0",children:b("landing.quickOther")})]}),u.jsx("button",{onClick:()=>pe.getState().setApiKeyModalOpen(!0),className:"mt-2 mx-auto text-2xs text-ink-faint hover:text-accent transition-colors block","data-quick-subs":!0,children:b("landing.quickSubs")})]}),u.jsx("div",{className:"grid grid-cols-3 gap-3 mt-6",children:[{icon:qi,title:"landing.feature1.title",desc:"landing.feature1.desc"},{icon:x5,title:"landing.feature2.title",desc:"landing.feature2.desc"},{icon:BS,title:"landing.feature3.title",desc:"landing.feature3.desc"}].map(({icon:ae,title:ke,desc:Ne})=>u.jsxs("div",{className:"bg-card/60 backdrop-blur border border-line rounded-xl px-4 py-3.5",children:[u.jsx(ae,{size:16,strokeWidth:1.75,className:"text-accent mb-2"}),u.jsx("h3",{className:"text-xs font-semibold text-ink mb-1",children:b(ke)}),u.jsx("p",{className:"text-2xs text-ink-faint leading-relaxed",children:b(Ne)})]},ke))}),u.jsxs("div",{className:"text-center mt-6 flex items-center justify-center gap-5",children:[u.jsxs("button",{onClick:Ve,className:"text-xs text-accent hover:text-accent-strong font-medium transition-colors inline-flex items-center gap-1.5",children:[u.jsx(x5,{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(h5,{size:14,strokeWidth:1.75})," ",b("landing.howItWorks")]})]})]})]}),!kt&&u.jsx(Yae,{onSwitched:bt}),(W||Ce)&&!kt&&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:[!Ce&&u.jsx("button",{onClick:()=>vt(re(null)),draggable:!0,onDragStart:ae=>{ae.dataTransfer.setData("application/thoughtdag-content","ask"),ae.dataTransfer.effectAllowed="copy"},title:b("palette.askTitle"),className:"w-9 h-9 rounded-lg flex items-center justify-center text-accent hover:bg-accent/10 transition-colors cursor-grab",children:u.jsx(pd,{size:17,strokeWidth:1.75})}),u.jsx("button",{onPointerDown:ae=>It(ae,ke=>ei("note",re(ke))),title:b("palette.noteTitle"),className:"w-9 h-9 rounded-lg flex items-center justify-center text-amber-600 hover:bg-amber-500/10 transition-colors",children:u.jsx(Vi,{size:17,strokeWidth:1.75})}),u.jsx("button",{onPointerDown:ae=>It(ae,ke=>ei("file",re(ke))),title:b("palette.fileTitle"),className:"w-9 h-9 rounded-lg flex items-center justify-center text-ink-muted hover:bg-wash transition-colors",children:u.jsx(wi,{size:17,strokeWidth:1.75})}),u.jsx("button",{onPointerDown:ae=>It(ae,ke=>Ke(re(ke))),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(Px,{size:17,strokeWidth:1.75})})]}),kt&&u.jsxs("div",{className:"absolute top-4 z-10 flex gap-1.5 items-center transition-[right] duration-200",style:{right:pt?En+xd+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(Pd,{size:14,strokeWidth:1.75})," ",b("viewer.badge")]}),u.jsx("button",{onClick:()=>N(!0),className:"bg-card/90 backdrop-blur border border-line rounded-lg w-8 h-8 flex items-center justify-center shadow-sm hover:bg-wash transition-colors text-ink-muted hover:text-accent",title:b("search.entryTitle"),"data-search-entry":!0,children:u.jsx(zf,{size:15,strokeWidth:1.75})}),u.jsx(OE,{}),u.jsx("button",{onClick:()=>yf(),className:"bg-card/90 backdrop-blur border border-line rounded-lg w-8 h-8 flex items-center justify-center shadow-sm hover:bg-wash transition-colors text-ink-muted hover:text-accent",title:b("viewer.downloadJson"),children:u.jsx(Tc,{size:15,strokeWidth:1.75})}),u.jsx("a",{href:"https://github.com/chenxiachan/thoughtdag",target:"_blank",rel:"noreferrer",className:"bg-ink text-white rounded-lg h-8 px-3 flex items-center gap-1.5 shadow-sm hover:bg-ink/85 transition-colors text-xs font-medium",children:b("viewer.openApp")})]}),!kt&&u.jsxs("div",{className:"absolute top-4 z-10 flex gap-1.5 items-center transition-[right] duration-200",style:{right:pt?En+xd+12:16},children:[Ce&&u.jsxs(u.Fragment,{children:[u.jsxs("button",{onClick:()=>ze("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(pd,{size:14,strokeWidth:1.75})," ",b("paradigm.addHuman")]}),u.jsxs("button",{onClick:()=>ze("prompt"),className:"bg-card/90 backdrop-blur border border-accent/40 rounded-lg h-8 px-3 flex items-center gap-1.5 shadow-sm hover:bg-accent/10 transition-colors text-accent text-xs font-medium",children:[u.jsx(Oo,{size:14,strokeWidth:1.75})," ",b("paradigm.addPrompt")]}),u.jsxs("button",{onClick:()=>{qe()},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")]})]}),!Ce&&u.jsx(Yre,{}),!Ce&&u.jsx(d9,{}),!W&&u.jsx("button",{onClick:()=>pe.getState().setApiKeyModalOpen(!0),className:"bg-card/90 backdrop-blur border border-line rounded-lg w-8 h-8 flex items-center justify-center shadow-sm hover:bg-wash transition-colors text-ink-faint hover:text-accent",title:b("apikey.entryTitle"),"data-apikey-entry":!0,children:u.jsx(Bd,{size:15,strokeWidth:1.75})}),Dt>0&&!Ce&&u.jsxs("button",{onClick:()=>{const{nodes:ae,edges:ke,staleIds:Ne}=se.getState(),ce=Ne.reduce((je,Ze)=>{const st=ae.map(Kt=>Kt.id===Ze?{...Kt,data:{...Kt.data,question:"",response:""}}:Kt),{layerTokens:Pt}=wr(Ze,st,ke),Ut=ae.find(Kt=>Kt.id===Ze)?.data.question??"";return je+Pt.material+Pt.reference+Pt.chain+$n(Ut)},0);_s({title:b("replay.confirmTitle"),message:We(b("replay.confirmMsg"),{n:Dt,tok:ce.toLocaleString()}),confirmLabel:b("replay.confirmBtn")}).then(je=>{je&&se.getState().replayStale()})},className:"bg-amber-500/10 backdrop-blur border border-amber-500/40 rounded-lg h-8 px-3 flex items-center gap-1.5 shadow-sm hover:bg-amber-500/20 transition-colors text-amber-600 text-xs font-medium",title:b("replay.chipTitle"),children:[u.jsx(Lz,{size:14,strokeWidth:1.75})," ",Dt]}),W&&Ct.length>0&&u.jsxs("div",{ref:en,className:"relative",children:[u.jsx("button",{onClick:()=>jt(ae=>!ae),className:`bg-card/90 backdrop-blur border rounded-lg w-8 h-8 flex items-center justify-center shadow-sm transition-colors ${ut?"border-accent/40 text-accent":"border-line text-ink-faint hover:bg-wash"}`,title:b("toolbar.frames"),children:u.jsx(Px,{size:15,strokeWidth:1.75})}),ut&&u.jsx("div",{className:"absolute right-0 top-full mt-1.5 bg-card border border-line rounded-xl shadow-lg py-1 w-[230px] max-h-[320px] overflow-y-auto z-30 animate-fade-in",children:Ct.map(ae=>u.jsxs("button",{onClick:()=>{jt(!1),q.current?.fitBounds({x:ae.position.x,y:ae.position.y,width:ae.width??640,height:ae.height??420},{duration:400,padding:.15})},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2",children:[u.jsx("span",{className:`w-2.5 h-2.5 rounded-sm shrink-0 ${(gd[ae.data.frameColor??"gray"]??gd.gray).dot}`}),u.jsx("span",{className:"truncate",children:ae.data.question||b("frame.untitled")})]},ae.id))})]}),W&&u.jsx("button",{onClick:()=>N(!0),className:"bg-card/90 backdrop-blur border border-line rounded-lg w-8 h-8 flex items-center justify-center shadow-sm hover:bg-wash transition-colors text-ink-faint hover:text-accent",title:b("search.entryTitle"),"data-search-entry":!0,children:u.jsx(zf,{size:15,strokeWidth:1.75})}),u.jsx(OE,{}),W&&!Ce&&u.jsx(vae,{showTrigger:!1,openPing:Bt,onLocate:ae=>{const ke=se.getState().nodes.find(Ne=>Ne.id===ae);ke&&(d(ae),oe(ke,{zoom:1}))}}),Re&&!kt&&u.jsxs("button",{onClick:()=>pe.getState().setCondenseDialogOpen(!0),className:"bg-card/90 backdrop-blur border border-accent/50 rounded-lg h-8 px-2 flex items-center justify-center gap-1.5 shadow-sm hover:bg-wash transition-colors text-accent",title:We(b("condense.entryBuilding"),{i:String(Le.current),n:String(Le.total)}),"data-condense-entry":!0,children:[u.jsx(Un,{size:14,strokeWidth:1.75,className:"animate-spin"}),u.jsxs("span",{className:"text-2xs font-mono",children:[Le.current,"/",Le.total]})]}),Gm&&u.jsx("button",{onClick:()=>pe.getState().setBackupDialogOpen(!0),className:"bg-card/90 backdrop-blur border border-line rounded-lg w-8 h-8 flex items-center justify-center shadow-sm hover:bg-wash transition-colors text-ink-muted hover:text-accent",title:b("backup.dialogTitle"),"data-backup-entry":!0,children:u.jsx(IS,{size:15,strokeWidth:1.75})}),u.jsxs("div",{ref:Sn,className:"relative",children:[u.jsx("button",{onClick:()=>xn(ae=>!ae),className:`bg-card/90 backdrop-blur border rounded-lg w-8 h-8 flex items-center justify-center shadow-sm transition-colors ${Xt?"border-accent/40 text-accent":"border-line text-ink-faint hover:bg-wash"}`,title:b("toolbar.more"),"data-toolbar-more":!0,children:u.jsx(CS,{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:[W&&u.jsxs("button",{onClick:()=>{xn(!1),S(!k)},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5",title:b(k?"toolbar.showAnnotations":"toolbar.hideAnnotations"),children:[u.jsx(Vi,{size:14,strokeWidth:1.75,className:`shrink-0 ${k?"text-accent":"text-ink-faint"}`})," ",b(k?"toolbar.menuAnnotationsShow":"toolbar.menuAnnotationsHide")]}),W&&u.jsxs("button",{onClick:()=>{xn(!1),_s({title:b("confirm.relayoutTitle"),message:b("confirm.relayoutMsg"),confirmLabel:b("toolbar.relayout")}).then(ae=>{ae&&(x(),setTimeout(()=>q.current?.fitView({duration:400,padding:.15}),50))})},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5",children:[u.jsx(Iz,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("toolbar.relayout")]}),K>0&&u.jsxs("button",{onClick:()=>{xn(!1),pe.getState().setHighlightsOverviewOpen(!0)},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5",title:b("hlov.entryTitle"),"data-hlov-entry":!0,children:[u.jsx(zd,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",We(b("hlov.entry"),{n:K})]}),U>0&&u.jsxs("button",{onClick:()=>{xn(!1),pe.getState().setMaterialsOverviewOpen(!0)},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5",title:b("matov.entryTitle"),"data-matov-entry":!0,children:[u.jsx(wi,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",We(b("matov.entry"),{n:U})]}),W&&u.jsx("div",{className:"border-t border-line/60 my-1"}),W&&!Ce&&!kt&&u.jsxs("button",{onClick:()=>{xn(!1),pe.getState().setCondenseDialogOpen(!0)},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5",title:b("condense.entryTitle"),children:[u.jsx(vm,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("condense.title"),"…"]}),W&&!Ce&&u.jsxs("button",{onClick:()=>{xn(!1),fn(ae=>ae+1)},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5",title:b("toolbar.diagnose"),"data-menu-diagnose":!0,children:[u.jsx(HS,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("toolbar.menuDiagnose")]}),W&&!Ce&&u.jsxs("button",{onClick:()=>{xn(!1),(async()=>{const{nodes:ae,edges:ke}=se.getState(),{confirmIfSensitive:Ne}=await Tt(async()=>{const{confirmIfSensitive:je}=await import("./sensitive-scan-Cwg4RAEk.js");return{confirmIfSensitive:je}},[]);if(!await Ne(ae))return;const ce=await wH(ae,ke);await navigator.clipboard.writeText(ce).catch(()=>{}),pe.getState().setShareDialogUrl(ce)})()},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(dB,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("toolbar.menuShare")]}),W&&u.jsxs("button",{onClick:()=>{xn(!1),Ce?bF():yf()},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5","data-menu-export":!0,children:[u.jsx(Tc,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b(Ce?"paradigm.exportParadigm":"switcher.exportBackup")]}),Q&&u.jsxs("button",{onClick:()=>{xn(!1),EF()},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5",title:b("toolbar.exportEventsTitle"),children:[u.jsx(vi,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("toolbar.exportEvents")]}),W&&u.jsx("div",{className:"border-t border-line/60 my-1"}),u.jsxs("div",{className:"px-3 pt-2 pb-1","data-appearance-lighting":!0,children:[u.jsx("div",{className:"text-2xs text-ink-faint mb-1.5",children:b("appearance.lighting")}),u.jsx("div",{className:"flex rounded-lg border border-line overflow-hidden text-2xs",children:[["light",b("appearance.light")],["dark",b("appearance.dark")],["system",b("appearance.system")]].map(([ae,ke],Ne)=>u.jsx("button",{onClick:()=>As.getState().setLighting(ae),className:`flex-1 px-1 py-1.5 transition-colors ${Ne>0?"border-l border-line":""} ${be===ae?"bg-accent/10 text-accent font-medium":"text-ink-muted hover:bg-wash"}`,children:ke},ae))})]}),u.jsxs("div",{className:"px-3 pt-1 pb-2","data-appearance-paper":!0,children:[u.jsx("div",{className:"text-2xs text-ink-faint mb-1.5",children:b("appearance.paper")}),u.jsx("div",{className:"flex rounded-lg border border-line overflow-hidden text-2xs",children:[["plain",b("appearance.plain")],["grid",b("appearance.grid")]].map(([ae,ke],Ne)=>u.jsx("button",{onClick:()=>As.getState().setPaper(ae),className:`flex-1 px-1 py-1.5 transition-colors ${Ne>0?"border-l border-line":""} ${$===ae?"bg-accent/10 text-accent font-medium":"text-ink-muted hover:bg-wash"}`,children:ke},ae))})]}),u.jsx("div",{className:"border-t border-line/60 my-1"}),u.jsxs("button",{onClick:()=>{xn(!1),pe.getState().setMemoryManagerOpen(!0)},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5",title:b("memory.entryTitle"),children:[u.jsx(TP,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("memory.managerTitle")]}),u.jsxs("button",{onClick:()=>{xn(!1),y(!0)},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5",children:[u.jsx(h5,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("landing.howItWorks")]}),he&&u.jsxs("button",{onClick:()=>{xn(!1),navigator.clipboard.writeText(Cb(he.latest)).then(()=>Qe("success",b("plugin.updateCopied"),6e3)).catch(()=>{})},className:"w-full text-left px-3 py-2 text-xs text-accent hover:bg-wash transition-colors flex items-center gap-2.5",title:We(b("plugin.updateHint"),{cmd:Cb(he.latest)}),"data-plugin-update":!0,children:[u.jsx(Tc,{size:14,strokeWidth:1.75,className:"shrink-0"})," ",We(b("plugin.updateAvailable"),{v:he.latest})]}),u.jsxs("button",{onClick:()=>{xn(!1),pe.getState().setReleaseNotesOpen(!0)},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5","data-open-release-notes":!0,children:[u.jsx($b,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("releaseNotes.entry")]})]})]}),u.jsx("button",{onClick:s,disabled:p<=0,className:"bg-card/90 backdrop-blur border border-line rounded-lg w-8 h-8 flex items-center justify-center shadow-sm hover:bg-wash transition-colors disabled:opacity-20 disabled:cursor-not-allowed",title:b("canvas.undo"),children:u.jsx(FS,{size:16,strokeWidth:1.75})}),u.jsx("button",{onClick:o,disabled:p>=m.length-1,className:"bg-card/90 backdrop-blur border border-line rounded-lg w-8 h-8 flex items-center justify-center shadow-sm hover:bg-wash transition-colors disabled:opacity-20 disabled:cursor-not-allowed",title:b("canvas.redo"),children:u.jsx(eB,{size:16,strokeWidth:1.75})})]}),Lt&&!kt&&u.jsx(oae,{}),u.jsx(bae,{open:T,onClose:()=>N(!1),onLocate:ae=>{const ke=se.getState().nodes.find(Ne=>Ne.id===ae);ke&&(d(ae),oe(ke,{zoom:1}))}}),Yt&&u.jsx(cae,{x:Yt.x,y:Yt.y,nodeId:Yt.nodeId,onClose:()=>kn(null)}),u.jsx(hae,{onLocate:ae=>{const ke=se.getState().nodes.find(Ne=>Ne.id===ae);ke&&(d(ae),oe(ke,{zoom:1}))}}),u.jsx(rie,{onLocate:ae=>{const ke=se.getState().nodes.find(Ne=>Ne.id===ae);ke&&(d(ae),oe(ke,{zoom:1}))}}),u.jsx(uae,{onLocate:ae=>{const ke=se.getState().nodes.find(Ne=>Ne.id===ae);ke&&(d(ae),oe(ke,{zoom:1}))}}),hn&&u.jsx("div",{className:"fixed z-50 bg-card border border-line rounded-xl shadow-lg py-1 min-w-[120px]",style:{left:hn.x,top:hn.y},children:u.jsxs("button",{onClick:()=>ur(hn.edgeId),className:"w-full text-left px-4 py-2 text-sm text-red-600 hover:bg-red-50 transition-colors flex items-center gap-1.5",children:[u.jsx(Va,{size:14,strokeWidth:1.75}),b("canvas.deleteEdge")]})})]}),u.jsx(Hre,{onFocusSegment:ae=>{const ke=q.current,Ne=se.getState().nodes.filter(Kt=>ae.includes(Kt.id));if(!ke||Ne.length===0)return;const ce=Ne.map(Kt=>Kt.position.x),je=Ne.map(Kt=>Kt.position.y),Ze=Math.min(...ce),st=Math.min(...je),Pt=Math.max(...ce)+520-Ze,Ut=Math.max(...je)+240-st;ke.fitBounds({x:Ze,y:st,width:Pt+700,height:Ut},{duration:350,padding:.15})}}),pt&&u.jsx(sae,{onFocusNode:ae=>{const ke=e.find(Ne=>Ne.id===ae);ke&&oe(ke,{duration:300})}}),u.jsx(Iae,{onLocate:ae=>{const ke=se.getState().nodes.find(Ne=>Ne.id===ae);ke&&(d(ae),oe(ke,{zoom:1}))}})]})}function uie({panelShiftWidth:e}){const t=c0(),n=zt(),a=Nl(),r=se(d=>d.nodes.length),s=se(d=>d.nodes),o=L.useMemo(()=>{let d=null,h="";for(const m of s){if(m.data.stepKind&&m.data.stepKind!=="human"&&m.data.stepKind!=="prompt")continue;const p=[m.data.lastGeneratedAt,m.data.askedAt,m.data.createdAt,...m.data.editedAts??[]].filter(Boolean).sort().pop();p&&p>h&&(h=p,d=m)}return d?{node:d,at:h}:null},[s]);if(kt||t==="work"||r<2)return null;const c=()=>{if(!o)return;pe.getState().setBeaconNodeId(null);const{node:d}=o;a.setCenter(d.position.x+260,d.position.y+110,{zoom:1,duration:1100}),window.setTimeout(()=>{se.getState().setSelectedNodeId(d.id),pe.getState().setPanelOpen(!0),window.setTimeout(()=>{a.setCenter(d.position.x+260+om(d.id)/2,d.position.y+110,{zoom:1,duration:300})},60)},1150),window.setTimeout(()=>{Qe("success",n("continue.arrived"),12e3,{label:n("continue.summarize"),run:()=>{f9(d.id)}})},1550)};return u.jsxs("div",{className:"absolute bottom-6 z-10 flex items-center gap-2 -translate-x-1/2 transition-[left] duration-300",style:{left:`calc((100% - ${e}px) / 2)`},"data-map-dock":!0,children:[u.jsxs("button",{onClick:()=>pe.getState().setThoughtMapOpen(!0),"data-tmap-pill":!0,className:"flex items-center gap-2 bg-card/95 backdrop-blur border border-line-strong rounded-full px-5 py-2.5 text-sm text-ink shadow-lg hover:border-accent/40 hover:text-accent transition-colors",children:[u.jsx(Yb,{size:16,strokeWidth:1.75})," ",n("tmap.export")]}),o&&u.jsxs("button",{onClick:c,onMouseEnter:()=>pe.getState().setBeaconNodeId(o.node.id),onMouseLeave:()=>pe.getState().setBeaconNodeId(null),title:n("continue.buttonTitle"),"data-continue-pill":!0,className:"flex items-center gap-2 bg-accent text-white rounded-full px-5 py-2.5 text-sm shadow-lg hover:bg-accent-strong transition-colors",children:[u.jsx(aB,{size:16,strokeWidth:1.75})," ",n("continue.button")]})]})}function die(){const e=c0(),t=un(n=>n.transform[2]);return L.useEffect(()=>{document.querySelector(".react-flow")?.setAttribute("data-zoom-tier",e)},[e]),L.useEffect(()=>{document.querySelector(".react-flow")?.style.setProperty("--tdag-zoom",String(t))},[t]),null}Dne();const py="/thoughtdag/api";window.desktopSessions||mU(py);Tt(()=>Promise.resolve().then(()=>Xre),void 0).then(e=>e.bootPluginUpdateCheck(py));if(!window.desktopAgents){const e=py;Tt(()=>import("./http-bridge-mmwHcDuo.js"),[]).then(async t=>{await t.installAgentsHttpBridge(e)&&window.dispatchEvent(new CustomEvent("td:agents-ready"))})}kt?EH():(C7(),navigator.storage?.persist&&navigator.storage.persist(),Tt(()=>Promise.resolve().then(()=>_re),void 0).then(e=>e.bootAutoBackup()));Tt(()=>import("./update-check-lHz7ROW6.js"),[]).then(e=>e.bootUpdateCheck());window.addEventListener("hashchange",()=>{window.location.hash.startsWith("#view=")!==kt&&window.location.reload()});q_.createRoot(document.getElementById("root")).render(u.jsx(L.StrictMode,{children:u.jsx(lie,{})}));export{Qd as A,rr as B,nF as C,Em as D,P7 as E,mie as F,Us as G,Fr as H,Tt as _,De as a,se as b,rn as c,Is as d,kt as e,We as f,_7 as g,Ms as h,bie as i,Hr as j,Yc as k,Nm as l,Yx as m,oF as n,In as o,si as p,iF as q,sF as r,Ro as s,Qe as t,pe as u,O7 as v,_s as w,pie as x,fie as y,hie as z};
|
|
788
|
+
Write the JOURNEY of this thinking as one flowing paragraph a reader absorbs in twenty seconds: where it started, what got ruled out, where it turned, where it landed, what remains open. Only the turns that mattered — do not enumerate every step. Hard limit: 250 characters for CJK languages, 500 characters otherwise. Write in ${n==="zh"?"Chinese":"English"} (the reader's interface language), even if the takeaway lines mix languages. Never use dash characters (—, –, -); use commas, colons or full stops. Output only the paragraph.`}])).trim(),fp:a,at:new Date().toISOString(),lang:n};return _b.set(`${n}:${a}`,x),x}function rie({onLocate:e}){const t=pe(D=>D.timelineOverviewOpen),n=pe(D=>D.setTimelineOverviewOpen),a=se(D=>D.nodes),r=zt(),s=WS(),o=Ra(D=>D.lang),c=L.useMemo(()=>my(a,0),[a]),d=L.useMemo(()=>M9(a),[a]),[h,m]=L.useState(null),[p,x]=L.useState(!1),[b,y]=L.useState(!1),k=nie(d,o)??h,S=!!k&&(k.fp!==d||k.lang!==o),w=()=>{x(!0),y(!1);const{nodes:D,edges:O}=se.getState();aie(D,O,o).then(m).catch(()=>y(!0)).finally(()=>x(!1))};if(!t)return null;const C=()=>n(!1),T=D=>D?D.slice(0,10):"",N=D=>D?new Date(D).toLocaleTimeString(s,{hour:"2-digit",minute:"2-digit"}):"—";return Qa.createPortal(u.jsx("div",{className:"fixed inset-0 z-[60] bg-ink/30 backdrop-blur-sm flex items-center justify-center p-6",onClick:C,children:u.jsxs("div",{className:"bg-card rounded-2xl shadow-2xl border border-line w-[640px] max-h-[80vh] flex flex-col",onClick:D=>D.stopPropagation(),children:[u.jsxs("div",{className:"flex items-center gap-2 px-5 py-3 border-b border-line shrink-0",children:[u.jsx($b,{size:15,strokeWidth:1.75,className:"text-accent"}),u.jsx("span",{className:"text-sm font-semibold text-ink",children:r("tlov.title")}),u.jsx("span",{className:"text-2xs text-ink-faint",children:We(r("tlov.count"),{n:c.length})}),u.jsx("div",{className:"flex-1"}),u.jsxs("button",{onClick:()=>{C(),pe.getState().setThoughtMapOpen(!0)},disabled:c.length===0,"data-tmap-from-timeline":!0,className:"flex items-center gap-1.5 text-2xs text-ink-muted hover:text-accent hover:bg-accent/10 rounded-full px-2.5 py-1 transition-colors disabled:opacity-50",children:[u.jsx(Yb,{size:13,strokeWidth:1.75}),r("tmap.export")]}),u.jsx("button",{onClick:C,className:"text-ink-faint hover:text-ink w-7 h-7 rounded-lg hover:bg-wash flex items-center justify-center transition-colors",children:u.jsx(mn,{size:15,strokeWidth:1.75})})]}),u.jsxs("div",{className:"px-5 pt-3 shrink-0","data-gedankengang":!0,children:[!k&&!p&&u.jsxs("button",{onClick:w,className:"flex items-center gap-1.5 text-2xs text-accent bg-accent/10 hover:bg-accent/20 rounded-full px-3 py-1.5 transition-colors",children:[u.jsx(Bf,{size:12,strokeWidth:1.75}),r("tlov.gedankenGenerate")]}),p&&u.jsx("p",{className:"text-2xs text-ink-faint italic py-1.5",children:r("tlov.gedankenLoading")}),b&&!p&&u.jsx("p",{className:"text-2xs text-red-500 py-1",children:r("tlov.gedankenFailed")}),k&&!p&&u.jsxs("div",{className:`rounded-xl bg-wash px-4 py-3 ${S?"opacity-60":""}`,children:[u.jsx("p",{className:"text-sm text-ink leading-relaxed",children:k.text}),u.jsxs("div",{className:"flex items-center gap-2 mt-1.5",children:[u.jsx("span",{className:"text-2xs text-ink-faint",children:S?r("tlov.gedankenStale"):new Date(k.at).toLocaleString(s)}),S&&u.jsx("button",{onClick:w,className:"text-2xs text-accent hover:underline",children:r("tlov.gedankenRedo")})]})]})]}),u.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-5 py-3","data-timeline-overview":!0,children:[c.length===0&&u.jsx("p",{className:"text-xs text-ink-faint italic py-2",children:r("tlov.empty")}),c.map((D,O)=>{const M=O>0?T(c[O-1].createdAt):void 0,_=T(D.createdAt),R=O===0||_!==M;return u.jsxs("div",{children:[R&&u.jsx("div",{className:"sticky top-0 bg-card text-2xs text-ink-faint font-medium pt-3 pb-1 first:pt-0",children:_||r("tlov.undated")}),u.jsxs("div",{className:"group flex items-center gap-2.5 py-1.5 border-b border-line/50 last:border-0",children:[u.jsx("span",{className:"w-2 h-2 rounded-full shrink-0",style:{background:D.color,opacity:D.archived?.35:1}}),u.jsx("span",{className:"text-2xs font-mono text-ink-faint shrink-0 w-11",children:N(D.createdAt)}),u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsxs("p",{className:`text-sm truncate ${D.archived?"text-ink-faint line-through":D.badged?"text-ink":"text-ink-muted"}`,children:[D.topic&&u.jsxs("span",{className:"font-medium text-accent",children:[D.topic," · "]}),D.label||"…"]}),D.modifiedAt&&D.modifiedAt!==D.createdAt&&u.jsxs("p",{className:"text-2xs text-ink-faint",children:[r("timeline.modified")," ",new Date(D.modifiedAt).toLocaleString(s)]})]}),u.jsx("button",{className:"shrink-0 text-2xs font-mono text-accent bg-accent/10 hover:bg-accent/20 rounded-full px-1.5 py-0.5 transition-colors opacity-0 group-hover:opacity-100",onClick:()=>{C(),e(D.id)},title:r("hlov.locateTitle"),children:r("tlov.locate")})]})]},D.id)})]})]})}),document.body)}const iie=L.memo(function(t){const n=rn(a=>a.projects.find(r=>r.id===a.activeId)?.kind==="paradigm");return t.data?.stepKind==="frame"?u.jsx(Hne,{...t}):rm(t.data?.stepKind)?u.jsx(Bne,{...t}):n?u.jsx(Mne,{...t}):u.jsx(Nne,{...t})}),sie={thought:iie},oie={smoothstep:L.memo(qne)};function lie(){const[e,t]=L.useState(kt||se.persist.hasHydrated());return L.useEffect(()=>se.persist.onFinishHydration(()=>t(!0)),[]),L.useEffect(()=>{if(!e||kt)return;let n;const a=()=>{clearTimeout(n),n=setTimeout(()=>{Jae()},800)},r=se.subscribe((s,o)=>{s.nodes!==o.nodes&&a()});return a(),()=>{r(),clearTimeout(n)}},[e]),L.useEffect(()=>{pe.getState().condenseRun.status==="building"&&pe.getState().setCondenseRun({status:"idle",current:0,total:0,streaming:""})},[]),L.useEffect(()=>{if(kt)return;const n=setTimeout(()=>{ere()},6e3);return()=>clearTimeout(n)},[]),L.useEffect(()=>{if(!e||kt||localStorage.getItem("thoughtdag.tutorialDone")||se.getState().nodes.length>0)return;const n=setTimeout(()=>pe.getState().setTutorialOpen(!0),900);return()=>clearTimeout(n)},[e]),L.useEffect(()=>{ire()},[]),L.useEffect(()=>{kt||(Tt(()=>import("./session-handoff-DF4fnjEz.js"),[]).then(n=>n.consumeSessionHandoff()),Tt(()=>import("./live-mirror-CkSO5X2s.js"),[]).then(n=>n.startLiveMirror()),Tt(()=>import("./canvas-record--EHyNDCM.js"),[]).then(n=>n.startCanvasRecord()),Tt(()=>import("./canonical-D4SquoNo.js"),[]).then(n=>n.unsubscribeOrphanedSessions()))},[]),L.useEffect(()=>{kt||rre().then(n=>{n&&(n.status==="minted"?(Qe("success",De("provider.oauthMinted")),k9(n.key)):Qe("error",We(De("provider.oauthFailed"),{error:n.error})))})},[]),u.jsxs(u.Fragment,{children:[e&&u.jsx(cie,{}),u.jsx(cre,{}),u.jsx(dre,{}),u.jsx(mre,{}),u.jsx(pre,{}),u.jsx(gre,{}),u.jsx(xre,{}),u.jsx(bre,{}),u.jsx(Sre,{}),u.jsx(Mre,{}),u.jsx(sre,{}),u.jsx(Fre,{}),u.jsx(Gre,{}),u.jsx($re,{})]})}function cie(){const{nodes:e,edges:t,setNodes:n,setEdges:a,addQuestion:r,undo:s,redo:o,addCrossLink:c,setSelectedNodeId:d,setSelectedNodeIds:h,history:m,historyIndex:p,relayout:x}=se(),b=zt(),y=pe(ae=>ae.setTutorialOpen),k=pe(ae=>ae.annotationsHidden),S=pe(ae=>ae.setAnnotationsHidden),[w,C]=L.useState(""),[T,N]=L.useState(!1),[D,O]=L.useState(""),[M,_]=L.useState(!1),[R,G]=L.useState(!1),[P,V]=L.useState([]),[J,H]=L.useState(!1),F=L.useRef(null),B=L.useRef(null),W=e.length>0,Q=se(ae=>ae.events.length>0),K=se(ae=>ae.nodes.reduce((ke,Ne)=>ke+(Ne.data.highlights?.length??0),0)),U=se(ae=>ae.nodes.reduce((ke,Ne)=>ke+(Ne.data.attachments?.length??0)+(["note","link"].includes(Ne.data.stepKind??"")?1:0),0)),q=L.useRef(null),te=pe(ae=>ae.arrivalFocusNodeId);L.useEffect(()=>{if(!te)return;const ae=se.getState().nodes.find(ke=>ke.id===te);ae&&(pe.getState().setArrivalFocusNodeId(null),window.setTimeout(()=>{q.current?.setCenter(ae.position.x+260,ae.position.y+140,{zoom:.9,duration:400})},150))},[te]);const $=As(ae=>ae.paper),be=As(ae=>ae.lighting),Te=As(ae=>ae.resolved),Se=L.useMemo(()=>One(),[Te]),Be=L.useMemo(()=>{const ae=getComputedStyle(document.documentElement),ke=(ae.getPropertyValue("--color-surface").trim()||"#FAF9F7").replace("#",""),[Ne,ce,je]=[0,2,4].map(Ze=>parseInt(ke.slice(Ze,Ze+2),16));return{mask:`rgba(${Ne},${ce},${je},0.7)`,archived:ae.getPropertyValue("--color-wash").trim()||"#EFEDE9",ordinary:Te==="dark"?"#6E6759":"#B9B3AB"}},[Te]),X=L.useRef(e.length),oe=L.useCallback((ae,ke={})=>{const Ne=q.current;if(!Ne)return;const ce=ke.zoom??Ne.getZoom();Ne.setCenter(ae.position.x+(ke.offX??260)+om(ae.id)/(2*ce),ae.position.y+110,{zoom:ce,duration:ke.duration??350})},[]),ve=Ra(ae=>ae.lang),Le=pe(ae=>ae.condenseRun),Re=Le.status==="building",Ce=rn(ae=>ae.projects.find(ke=>ke.id===ae.activeId)?.kind==="paradigm"),tt=_l();L.useEffect(()=>{if(kt||!W||se.getState().nodes.length<10)return;const ae=Number(localStorage.getItem("thoughtdag.lastBackupAt")??0);if(ae===0){localStorage.setItem("thoughtdag.lastBackupAt",String(Date.now()));return}Date.now()-ae<168*3600*1e3||sessionStorage.getItem("thoughtdag.backupNudged")||(sessionStorage.setItem("thoughtdag.backupNudged","yes"),Qe("info",De("backup.nudge"),0,{label:De("backup.nudgeBtn"),run:()=>yf()}))},[W]);const Ve=L.useCallback(()=>{const{nodes:ae,edges:ke}=Zae(ve),Ne=se.getState();Ne.setNodes([...Ne.nodes,...ae.filter(ce=>!Ne.nodes.some(je=>je.id===ce.id))]),Ne.setEdges([...Ne.edges,...ke.filter(ce=>!Ne.edges.some(je=>je.id===ce.id))]),Ne.pushHistory(),setTimeout(()=>{const ce=q.current;ce&&(ce.fitView({duration:500,padding:.1}),setTimeout(()=>{if(ce.getViewport().zoom<.34){const je=[...se.getState().nodes].sort((Ze,st)=>(Ze.data.createdAt??"").localeCompare(st.data.createdAt??""))[0];je&&ce.setCenter(je.position.x+300,je.position.y+240,{zoom:.6,duration:550})}},680))},100),localStorage.getItem("thoughtdag.tutorialDone")||y(!0)},[ve,y]),ze=L.useCallback(ae=>{const ke=se.getState(),Ne=ke.nodes[ke.nodes.length-1],ce=Ne?{x:Ne.position.x,y:Ne.position.y+340}:{x:120,y:80},je=In();ke.setNodes([...ke.nodes,{id:je,type:"thought",position:ce,dragHandle:".drag-handle",data:{question:"",instruction:"",stepKind:ae,response:"",responses:[],responseIndex:-1,isCollapsed:!1,isEditing:!1,isEditingResponse:!1,isLoading:!1,tokenCount:0,highlights:[],highlightMode:"tag",attachments:[],excludedAttachmentIds:[],includedAttachmentIds:[],roleMode:"inherit",isRoot:ke.nodes.length===0,isBranch:!1}}]),ke.pushHistory()},[]),bt=L.useCallback(()=>{X.current=se.getState().nodes.length,setTimeout(()=>q.current?.fitView({duration:300,padding:.2}),50)},[]),ct=L.useRef(null),Ke=L.useCallback(ae=>{const ke=se.getState(),Ne=In();ke.setNodes([...ke.nodes,{id:Ne,type:"thought",position:ae,width:640,height:420,zIndex:-1,dragHandle:".drag-handle",data:{question:"",stepKind:"frame",frameCarry:!1,response:"",responses:[],responseIndex:-1,isCollapsed:!1,isEditing:!1,isEditingResponse:!1,isLoading:!1,tokenCount:0,highlights:[],highlightMode:"tag",attachments:[],excludedAttachmentIds:[],includedAttachmentIds:[],roleMode:"inherit",isRoot:!1,isBranch:!1}}]),ke.pushHistory()},[]),it=L.useCallback(ae=>{const ke=[];for(const Ne of Array.from(ae)){const ce=Ne.name.split(".").pop()?.toLowerCase()??"";Ne.type.startsWith("image/")||Ne.type==="application/pdf"||Ne.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(ce)?ke.push(Ne):Qe("info",We(De("toast.unsupportedFile"),{name:Ne.name}))}return ke},[]),vt=L.useCallback(ae=>{const ke=se.getState(),Ne=In();return ke.setNodes([...ke.nodes,{id:Ne,type:"thought",position:ae,dragHandle:".drag-handle",data:{question:"",response:"",responses:[],responseIndex:-1,isCollapsed:!1,isEditing:!1,isEditingResponse:!1,isLoading:!1,tokenCount:0,highlights:[],highlightMode:"tag",attachments:[],excludedAttachmentIds:[],includedAttachmentIds:[],roleMode:"inherit",isRoot:!1,isBranch:!1,webSearch:pe.getState().webSearchEnabled,scholarSearch:pe.getState().scholarSearchEnabled}}]),ke.pushHistory(),Ne},[]),He=L.useCallback(ae=>{const ke=it(ae);if(ke.length===0)return;let Ne=null;ke.forEach((ce,je)=>{const Ze=ei("file",{x:120+je%3*480,y:120+Math.floor(je/3)*620});Cd(Ze,[ce]),!Ne&&!ce.type.startsWith("image/")&&(Ne=Ze)}),Ne&&pe.getState().setReaderNodeId(Ne),setTimeout(()=>q.current?.fitView({duration:400,padding:.2}),120)},[it]),It=L.useCallback((ae,ke)=>{const Ne=ae.clientX,ce=ae.clientY,je=ae.currentTarget;let Ze=null;const st=Ut=>{!Ze&&Math.hypot(Ut.clientX-Ne,Ut.clientY-ce)>6&&(Ze=document.createElement("div"),Ze.innerHTML=je.innerHTML,Ze.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(Ze)),Ze&&(Ze.style.left=`${Ut.clientX-18}px`,Ze.style.top=`${Ut.clientY-18}px`)},Pt=Ut=>{window.removeEventListener("pointermove",st),window.removeEventListener("pointerup",Pt);const Kt=!!Ze;Ze?.remove(),ke(Kt?{x:Ut.clientX,y:Ut.clientY}:null)};window.addEventListener("pointermove",st),window.addEventListener("pointerup",Pt)},[]),re=L.useCallback(ae=>{const ke=q.current?.screenToFlowPosition(ae??{x:window.innerWidth/2,y:window.innerHeight/2})??{x:140,y:140};return{x:ke.x-200,y:ke.y-60}},[]);L.useEffect(()=>{const ae=Ne=>{ct.current={x:Ne.clientX,y:Ne.clientY}},ke=Ne=>{if(kt)return;const ce=Ne.target;if(ce&&(ce.tagName==="INPUT"||ce.tagName==="TEXTAREA"||ce.isContentEditable))return;const je=rn.getState(),Ze=je.projects.find(Qt=>Qt.id===je.activeId)?.kind==="paradigm";if(se.getState().nodes.length===0&&!Ze)return;const st=Ne.clipboardData;if(!st)return;const Pt=re(ct.current),Ut=st.getData("text/plain").trim(),Kt=Array.from(st.files),ia=Kt.some(Qt=>!Qt.type.startsWith("image/"));if(Kt.length>0&&(ia||!Ut)){Ne.preventDefault();const Qt=ei("file",Pt);Cd(Qt,Kt);return}if(Ut)if(Ne.preventDefault(),/^https?:\/\/\S+$/.test(Ut)){const Qt=ei("link",Pt,{linkUrl:Ut});c9(Qt,Ut)}else ei("note",Pt,{question:Lne(Ut)})};return window.addEventListener("mousemove",ae),window.addEventListener("paste",ke),()=>{window.removeEventListener("mousemove",ae),window.removeEventListener("paste",ke)}},[re]);const qe=L.useCallback(async()=>{const ae=se.getState();if(ae.nodes.length===0)return;const{nodes:ke,edges:Ne}=xF(ae.nodes,ae.edges),ce=rn.getState(),je=ce.projects.find(st=>st.id===ce.activeId)?.name??"Paradigm",Ze=crypto.randomUUID();await Hr(si(Ze),JSON.stringify({state:{nodes:ke,edges:Ne},version:1})),await Yc(Ze,`▶ ${je}`,"chat"),await N7(Ze,je),X.current=se.getState().nodes.length,setTimeout(()=>q.current?.fitView({duration:400,padding:.15}),150)},[]);L.useEffect(()=>{e.length===0&&!Ce&&!localStorage.getItem("thoughtdag.seeded")&&localStorage.setItem("thoughtdag.seeded","yes")},[]),L.useEffect(()=>{if(e.length>X.current&&q.current){const ae=e[e.length-1];ae&&setTimeout(()=>oe(ae,{zoom:1,duration:400,offX:220}),100)}X.current=e.length},[e,oe]);const xe=L.useCallback(ae=>{const ke=se.getState().nodes;n(X8(ae,ke))},[n]),$e=L.useCallback(ae=>a(Q8(ae,se.getState().edges)),[a]),ft=L.useRef(null),yt=L.useCallback((ae,ke)=>{if(ke.data.stepKind!=="frame"||ke.data.frameCarry===!1)return;const Ne=se.getState(),ce=Ne.nodes.find(Ze=>Ze.id===ke.id);if(!ce)return;const je=p7(ce,Ne.nodes).filter(Ze=>!Ze.selected).map(Ze=>({id:Ze.id,start:Ze.position}));je.length!==0&&(ft.current={frameId:ce.id,start:ce.position,members:je})},[]),At=L.useCallback((ae,ke)=>{const Ne=ft.current;if(!Ne||ke.id!==Ne.frameId)return;const ce=ke.position.x-Ne.start.x,je=ke.position.y-Ne.start.y,Ze=new Map(Ne.members.map(st=>[st.id,{x:st.start.x+ce,y:st.start.y+je}]));se.setState(st=>({nodes:st.nodes.map(Pt=>{const Ut=Ze.get(Pt.id);return Ut?{...Pt,position:Ut}:Pt})}))},[]),qt=L.useCallback(()=>{ft.current=null},[]),[hn,wn]=L.useState(null),[Yt,kn]=L.useState(null),sn=L.useCallback((ae,ke)=>{kt||window.getSelection()?.toString()||(ae.preventDefault(),kn({x:ae.clientX,y:ae.clientY,nodeId:ke.id}))},[]),ka=L.useCallback((ae,ke)=>{ae.preventDefault(),wn({x:ae.clientX,y:ae.clientY,edgeId:ke.id})},[]);L.useEffect(()=>{if(!hn)return;const ae=()=>wn(null);return window.addEventListener("click",ae),()=>window.removeEventListener("click",ae)},[hn]);const Fn=se(ae=>ae.deleteEdges),ur=L.useCallback(ae=>{Fn([ae]),wn(null)},[Fn]),er=L.useCallback(ae=>{ae.source&&ae.target&&c(ae.source,ae.target)},[c]),Qn=L.useCallback(()=>{window.getSelection()?.removeAllRanges(),document.body.classList.add("tdag-connecting")},[]),Ba=L.useCallback((ae,ke)=>{if(document.body.classList.remove("tdag-connecting"),Ce||ke.isValid||ke.fromHandle?.type!=="source"||!ke.fromNode)return;const Ne=ke.fromNode.id,ce=ae.target?.closest?.(".react-flow__node");if(ce){const Kt=ce.getAttribute("data-id");if(Kt&&Kt!==Ne){const ia=se.getState().nodes.find(Da=>Da.id===Kt),Qt=ia?.data.stepKind??"";ia&&!["note","file","link","frame"].includes(Qt)&&se.getState().addCrossLink(Ne,Kt)}return}const{clientX:je,clientY:Ze}="changedTouches"in ae?ae.changedTouches[0]:ae,st=re({x:je,y:Ze}),Pt=se.getState();if(Pt.nodes.find(Kt=>Kt.id===Ne)?.data.stepKind==="frame")return;const Ut=vt(st);Pt.setEdges([...se.getState().edges,{id:`edge-${Ne}-${Ut}`,source:Ne,target:Ut,sourceHandle:"continue",targetHandle:"top",type:"smoothstep",style:{stroke:rt.accent,strokeWidth:2},animated:!1,markerEnd:{type:"arrowclosed",color:rt.accent,width:18,height:18},data:{}}]),se.getState().pushHistory()},[Ce,re,vt]),Jt=se(ae=>ae.selectedNodeId),ue=se(ae=>ae.selectedNodeIds),Fe=pe(ae=>ae.panelOpen),mt=pe(ae=>ae.viewerLoadError),Dt=se(ae=>ae.staleIds.length),En=pe(ae=>ae.panelWidth),on=e.find(ae=>ae.id===Jt)?.data.stepKind,wt=rm(on)||on==="frame",pt=Fe&&!!Jt&&!Ce&&!wt,Lt=ue.length>1,On=se(ae=>ae.batchDelete);L.useEffect(()=>{const ae=ke=>{if(!pe.getState().confirmRequest&&!(kt&&!((ke.metaKey||ke.ctrlKey)&&ke.key==="f"))){if((ke.metaKey||ke.ctrlKey)&&ke.key==="z"&&(ke.shiftKey?(ke.preventDefault(),o()):(ke.preventDefault(),s())),(ke.metaKey||ke.ctrlKey)&&ke.key==="f"){ke.preventDefault(),N(!0);return}{const Ne=ke.target;if(!(Ne.tagName==="INPUT"||Ne.tagName==="TEXTAREA"||Ne.isContentEditable)&&Jt&&!Ce&&!ke.metaKey&&!ke.ctrlKey&&!ke.altKey){const{nodes:je,edges:Ze}=se.getState();if(ke.key===" "){ke.preventDefault(),se.getState().toggleCollapse(Jt);return}if(ke.key==="r"||ke.key==="R"){ke.preventDefault(),se.getState().rerunNode(Jt,{});return}if(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(ke.key)){const st=Ze.filter(Ut=>!Ut.data?.isCrossLink);let Pt;if(ke.key==="ArrowUp")Pt=st.find(Ut=>Ut.target===Jt)?.source;else if(ke.key==="ArrowDown")Pt=st.find(Ut=>Ut.source===Jt)?.target;else{const Ut=st.find(Qt=>Qt.target===Jt),Kt=Ut?st.filter(Qt=>Qt.source===Ut.source).map(Qt=>Qt.target):je.filter(Qt=>!st.some(Da=>Da.target===Qt.id)).map(Qt=>Qt.id),ia=Kt.indexOf(Jt);ia!==-1&&Kt.length>1&&(Pt=Kt[(ia+(ke.key==="ArrowRight"?1:Kt.length-1))%Kt.length])}if(Pt){ke.preventDefault(),d(Pt);const Ut=je.find(Kt=>Kt.id===Pt);Ut&&oe(Ut,{zoom:1,duration:300})}return}}}if(ke.key==="Escape"){const Ne=ke.target;if(Ne.tagName==="INPUT"||Ne.tagName==="TEXTAREA"||Ne.isContentEditable)return;ue.length>1?h([]):Jt&&d(null);return}if(ke.key==="Delete"||ke.key==="Backspace"){const Ne=ke.target;if(Ne.tagName==="INPUT"||Ne.tagName==="TEXTAREA"||Ne.isContentEditable)return;if(ue.length>1)ke.preventDefault(),_s({title:De("confirm.deleteNodesTitle"),message:We(De("confirm.deleteNodes"),{n:ue.length}),confirmLabel:De("common.delete"),danger:!0}).then(ce=>{ce&&On(ue)});else{const ce=t.filter(je=>je.selected).map(je=>je.id);ce.length>0&&(ke.preventDefault(),Fn(ce))}}}};return window.addEventListener("keydown",ae),()=>window.removeEventListener("keydown",ae)},[s,o,Jt,ue,d,h,On,t,Fn,Ce,oe]);const Mn=()=>{w.trim()&&(r(w.trim(),{rolePrompt:D.trim()||void 0,initialAttachments:P.length>0?P:void 0}),C(""),O(""),_(!1),V([]))},ge=async ae=>{for(const ke of Array.from(ae))await l0(ke,{add:Ne=>V(ce=>[...ce,Ne]),update:(Ne,ce)=>V(je=>je.map(Ze=>Ze.id===Ne?{...Ze,...ce}:Ze))})},Je=ae=>{ae.key==="Enter"&&!ae.shiftKey&&!Xa(ae)&&(ae.preventDefault(),Mn())},Nt=L.useCallback(({nodes:ae})=>{const ke=ae.map(Ne=>Ne.id);ke.length>1?h(ke):ke.length===1&&d(ke[0])},[d,h]),Ct=L.useMemo(()=>e.filter(ae=>ae.data.stepKind==="frame"),[e]),[ut,jt]=L.useState(!1),en=L.useRef(null);L.useEffect(()=>{if(!ut)return;const ae=ke=>{en.current?.contains(ke.target)||jt(!1)};return window.addEventListener("mousedown",ae),()=>window.removeEventListener("mousedown",ae)},[ut]);const[Xt,xn]=L.useState(!1),he=pe(ae=>ae.pluginUpdate),[Bt,fn]=L.useState(0),Cn=pe(ae=>ae.searchHitIds!==null),Sn=L.useRef(null);L.useEffect(()=>{if(!Xt)return;const ae=ke=>{Sn.current?.contains(ke.target)||xn(!1)};return window.addEventListener("mousedown",ae),()=>window.removeEventListener("mousedown",ae)},[Xt]);const ea=pe(ae=>ae.searchHitIds),xa=L.useMemo(()=>{if(!Jt||ue.length>1||!e.some(st=>st.id===Jt))return null;const ae=Sm(Jt,e,t),ke=new Set;for(const st of ae.mainline)st.id!==Jt&&ke.add(st.id);for(const st of ae.materials)ke.add(st.id);for(const st of ae.references)ke.add(st.source.id);const Ne=t.filter(st=>!st.data?.isCrossLink),ce=Ur(Jt,e,Ne).visitedEdgeIds,je=new Set(ae.references.map(st=>st.edge.id)),Ze=Ne.filter(st=>st.source===Jt);return{ctx:ke,down:new Set(Ze.map(st=>st.target)),pathEdgeIds:ce,refEdgeIds:je,downEdgeIds:new Set(Ze.map(st=>st.id))}},[Jt,ue,e,t]),Wr=L.useMemo(()=>{const ae=e.filter(ce=>ce.data.stepKind==="frame").map((ce,je)=>({id:ce.id,order:je,area:(ce.measured?.width??ce.width??640)*(ce.measured?.height??ce.height??420)})).sort((ce,je)=>je.area-ce.area||ce.order-je.order),ke=new Map(ae.map((ce,je)=>[ce.id,je-ae.length]));let Ne=e.map(ce=>ce.data.stepKind==="frame"?{...ce,zIndex:ke.get(ce.id)??-1}:ce);return k&&(Ne=Ne.map(ce=>{const je=ce.data.stepKind,Ze=rm(je)&&!t.some(st=>st.source===ce.id||st.target===ce.id);return je==="frame"||Ze?{...ce,hidden:!0}:ce})),ea!==null&&(Ne=Ne.map(ce=>ea.has(ce.id)||ce.data.stepKind==="frame"?{...ce,className:"search-hit"}:ce.className==="search-hit"?{...ce,className:void 0}:ce)),xa&&(Ne=Ne.map(ce=>{const je=ce.id===Jt?"target":xa.ctx.has(ce.id)?"ctx":xa.down.has(ce.id)?"down":ce.data.stepKind==="frame"?void 0:"dim";return je?{...ce,className:[ce.className,`focus-${je}`].filter(Boolean).join(" "),...je!=="dim"?{data:{...ce.data,focusRole:je}}:{}}:ce})),Ne},[e,t,k,ea,xa,Jt]),ra=L.useMemo(()=>{const ae=t.map(ce=>{const je=ce.data?.isBranchFromSelection?{...ce,animated:!1,style:{...ce.style,strokeDasharray:void 0}}:ce,Ze=typeof je.style?.stroke=="string"?lE[je.style.stroke.toUpperCase()]:void 0,st=je.markerEnd&&typeof je.markerEnd=="object"?je.markerEnd:void 0,Pt=typeof st?.color=="string"?lE[st.color.toUpperCase()]:void 0;return!Ze&&!Pt?je:{...je,...Ze?{style:{...je.style,stroke:Se[Ze]}}:{},...Pt&&st?{markerEnd:{...st,color:Se[Pt]}}:{}}});if(xa)return ae.map(ce=>xa.pathEdgeIds.has(ce.id)?{...ce,className:"focus-e-path",style:{...ce.style,stroke:Se.accent,strokeWidth:3.5,opacity:1},markerEnd:{type:"arrowclosed",...ce.markerEnd&&typeof ce.markerEnd=="object"?ce.markerEnd:{},color:Se.accent},zIndex:10,data:{...ce.data,focusRole:"path"}}:xa.refEdgeIds.has(ce.id)?{...ce,style:{...ce.style,opacity:.9},zIndex:5,data:{...ce.data,focusRole:"ref"}}:xa.downEdgeIds.has(ce.id)?{...ce,className:"focus-e-down",style:{...ce.style,strokeWidth:2.5,opacity:.85},markerEnd:{type:"arrowclosed",...ce.markerEnd&&typeof ce.markerEnd=="object"?ce.markerEnd:{}},zIndex:5,data:{...ce.data,focusRole:"down"}}:{...ce,style:{...ce.style,strokeWidth:1.5,opacity:.2},zIndex:0});const ke=ue.length>1?ue:[];if(ke.length===0)return ae;const{visitedEdgeIds:Ne}=Ur(ke,e,t);return ae.map(ce=>Ne.has(ce.id)?{...ce,style:{...ce.style,stroke:Se.trace,strokeWidth:3.5,opacity:1},markerEnd:{type:"arrowclosed",...ce.markerEnd&&typeof ce.markerEnd=="object"?ce.markerEnd:{},color:Se.trace},zIndex:10}:{...ce,style:{...ce.style,strokeWidth:1.5,opacity:.2},zIndex:0})},[e,t,ue,Se,xa]);return L.useEffect(()=>{if(!pt||!Jt)return;const ae=setTimeout(()=>{const ke=q.current;if(!ke)return;const Ne=se.getState().nodes.find(Pt=>Pt.id===Jt);if(!Ne)return;const ce=ke.getViewport(),je=Ne.measured?.width??Ne.width??480,Ze=(Ne.position.x+je)*ce.zoom+ce.x,st=window.innerWidth-pe.getState().panelWidth-xd-24;if(Ze>st){const Pt=(Ne.position.x+je/2)*ce.zoom+ce.x;ke.setViewport({...ce,x:ce.x-(Pt-st/2)},{duration:300})}},60);return()=>clearTimeout(ae)},[pt,Jt]),u.jsxs("div",{className:"relative w-full h-full","data-searching":Cn||void 0,children:[u.jsxs("div",{className:"relative h-full w-full",onDoubleClick:ae=>{ae.target.classList.contains("react-flow__pane")&&!Ce&&vt(re({x:ae.clientX,y:ae.clientY}))},onDragOver:ae=>{(ae.dataTransfer.types.includes("application/thoughtdag-content")||ae.dataTransfer.types.includes("Files"))&&(ae.preventDefault(),ae.dataTransfer.dropEffect="copy",!W&&!Ce&&H(!0))},onDrop:ae=>{if(kt)return;const ke=ae.target;if(!W&&!Ce&&ae.dataTransfer.files.length>0){ae.preventDefault(),H(!1),He(ae.dataTransfer.files);return}const Ne=ke.closest?.(".react-flow__node"),ce=Ne&&se.getState().nodes.find(st=>st.id===Ne.getAttribute("data-id"))?.data.stepKind==="frame";if(!ke.classList?.contains("react-flow__pane")&&!ce)return;const je=re({x:ae.clientX,y:ae.clientY}),Ze=ae.dataTransfer.getData("application/thoughtdag-content");if(Ze==="ask"){ae.preventDefault(),vt(je);return}if(Ze==="frame"){ae.preventDefault(),Ke(je);return}if(Ze==="note"||Ze==="file"){ae.preventDefault(),ei(Ze,je);return}if(ae.dataTransfer.files.length>0){ae.preventDefault();const st=it(ae.dataTransfer.files);if(st.length===0)return;const Pt=ei("file",je);Cd(Pt,st)}},children:[u.jsxs(kj,{onInit:ae=>{q.current=ae,h9.current=ae;const ke=pe.getState().arrivalFocusNodeId;if(ke){pe.getState().setArrivalFocusNodeId(null);const Ne=se.getState().nodes.find(ce=>ce.id===ke);Ne&&window.setTimeout(()=>{ae.setCenter(Ne.position.x+260,Ne.position.y+140,{zoom:.9,duration:400})},150)}},nodes:Wr,edges:ra,onNodesChange:xe,onEdgesChange:$e,onNodeDragStart:yt,onNodeDrag:At,onNodeDragStop:qt,onConnect:er,onConnectStart:Qn,onConnectEnd:Ba,onEdgeContextMenu:ka,onNodeContextMenu:sn,nodeTypes:sie,edgeTypes:oie,deleteKeyCode:null,fitView:!0,onlyRenderVisibleElements:!0,minZoom:.04,maxZoom:2,defaultEdgeOptions:{type:"smoothstep",animated:!1,style:{stroke:Se.accent,strokeWidth:2},markerEnd:{type:"arrowclosed",color:Se.accent,width:18,height:18}},snapToGrid:$==="grid",snapGrid:[22,22],proOptions:{hideAttribution:!0},nodeDragThreshold:5,connectionRadius:40,selectionMode:Oc.Partial,selectionOnDrag:!kt,nodesDraggable:!kt,nodesConnectable:!kt,panOnDrag:kt?!0:[1,2],zoomOnDoubleClick:!1,connectionLineStyle:{stroke:Se.accent,strokeDasharray:"8 4",strokeWidth:2},onSelectionChange:Nt,onPaneClick:()=>{d(null),h([]),kn(null)},children:[$==="grid"?u.jsxs(u.Fragment,{children:[u.jsx(h1,{id:"grid-fine",variant:yi.Lines,gap:22,color:"var(--canvas-grid-fine)"}),u.jsx(h1,{id:"grid-major",variant:yi.Lines,gap:110,color:"var(--canvas-grid-major)"})]}):u.jsx(h1,{variant:yi.Dots,gap:24,size:1,color:"var(--canvas-dot)"}),u.jsx(die,{}),u.jsx(uie,{panelShiftWidth:pt?En:0}),u.jsx(tie,{}),u.jsx(Rj,{position:"bottom-left"}),e.length>0&&u.jsx($j,{nodeColor:ae=>{const ke=ae.data;if(ke.archived)return Be.archived;const Ne=ke.stepKind;return Ne==="note"?"#D97706":Ne==="file"||Ne==="link"?"#64748B":Array.isArray(ke.condensedFrom)&&ke.condensedFrom.length?"#8B7CF0":ke.isRoot?Se.accent:ke.isBranch?Se.warm:Be.ordinary},maskColor:Be.mask,style:{width:200,height:140},pannable:!0,zoomable:!0,position:"bottom-right"})]}),!W&&Ce&&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:()=>ze("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(pd,{size:15,strokeWidth:1.75})," ",b("paradigm.addHuman")]}),u.jsxs("button",{onClick:()=>ze("prompt"),className:"text-sm border-2 border-dashed border-accent/50 text-accent hover:bg-accent/10 px-4 py-2.5 rounded-xl transition-colors flex items-center gap-1.5",children:[u.jsx(Oo,{size:15,strokeWidth:1.75})," ",b("paradigm.addPrompt")]})]})]})}),kt&&!W&&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:mt?u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"text-3xl mb-3",children:"🔗"}),u.jsx("div",{className:"text-sm font-semibold text-ink mb-1.5",children:b("viewer.loadError")}),u.jsx("p",{className:"text-xs text-ink-muted leading-relaxed",children:b("viewer.loadErrorHint")})]}):u.jsxs("div",{className:"flex items-center gap-2 text-sm text-ink-muted justify-center",children:[u.jsx(Un,{size:16,strokeWidth:1.75,className:"animate-spin text-accent"})," ",b("viewer.loading")]})})}),!W&&!Ce&&!kt&&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:rt.line,strokeWidth:"2",fill:"none"}),u.jsx("path",{d:"M95 150 C150 150 150 90 205 88",stroke:rt.line,strokeWidth:"2",strokeDasharray:"6 5",fill:"none"}),u.jsx("circle",{cx:"80",cy:"30",r:"7",fill:rt.line}),u.jsx("circle",{cx:"80",cy:"150",r:"7",fill:"none",stroke:rt.line,strokeWidth:"2.5"}),u.jsx("circle",{cx:"80",cy:"262",r:"7",fill:rt.line}),u.jsx("circle",{cx:"218",cy:"88",r:"7",fill:rt.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:rt.line,strokeWidth:"2",fill:"none"}),u.jsx("path",{d:"M225 140 C170 140 170 210 115 212",stroke:rt.line,strokeWidth:"2",strokeDasharray:"6 5",fill:"none"}),u.jsx("circle",{cx:"240",cy:"20",r:"7",fill:rt.line}),u.jsx("circle",{cx:"240",cy:"140",r:"7",fill:"none",stroke:rt.line,strokeWidth:"2.5"}),u.jsx("circle",{cx:"240",cy:"252",r:"7",fill:rt.line}),u.jsx("circle",{cx:"102",cy:"212",r:"7",fill:rt.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:rt.accent}),u.jsx("line",{className:"dag-pop",style:{animationDelay:"0.2s"},x1:"22",y1:"11",x2:"22",y2:"19",stroke:rt.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:rt.accent,strokeWidth:"2.5"}),u.jsx("line",{className:"dag-pop",style:{animationDelay:"0.5s"},x1:"22",y1:"25",x2:"22",y2:"33",stroke:rt.accent,strokeWidth:"2",strokeLinecap:"round"}),u.jsx("circle",{className:"dag-pop",style:{animationDelay:"0.65s"},cx:"22",cy:"37",r:"3.5",fill:rt.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:rt.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:rt.warm})]}),u.jsx("h1",{className:"text-4xl font-semibold tracking-tight text-ink mb-2.5",children:"ThoughtDAG"}),u.jsx("p",{className:"text-sm text-ink-muted",children:b("landing.tagline")}),u.jsx("p",{className:"text-xs text-ink-muted mt-1.5 font-medium",children:b("landing.mechanism")})]}),u.jsxs("div",{className:"bg-card border border-line rounded-xl px-5 py-4 shadow-lg transition-all focus-within:border-accent/50 focus-within:shadow-xl",children:[u.jsx("textarea",{value:w,onChange:ae=>C(ae.target.value),onKeyDown:Je,onPaste:ae=>{if(ae.clipboardData.getData("text/plain").trim())return;const ke=Array.from(ae.clipboardData.items).filter(Ne=>Ne.kind==="file").map(Ne=>Ne.getAsFile()).filter(Boolean);ke.length&&ge(ke)},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}),P.length>0&&u.jsx("div",{className:"flex flex-wrap gap-2 mt-2 pb-1",children:P.map(ae=>u.jsxs("div",{className:"flex items-center gap-1.5 bg-wash rounded-lg px-2.5 py-1.5 group",children:[ae.thumbnailUrl?u.jsx("img",{src:ae.thumbnailUrl,className:"w-6 h-6 rounded object-cover",alt:ae.name}):u.jsx("span",{className:"text-xs",children:u.jsx(vi,{size:16,strokeWidth:1.75})}),u.jsx("span",{className:"text-xs text-ink-muted max-w-[100px] truncate",children:ae.name}),ae.isExtracting&&u.jsx("span",{className:"text-2xs text-accent",children:u.jsx(Un,{className:"animate-spin",size:12,strokeWidth:1.75})}),ae.numPages!=null&&u.jsxs("span",{className:"text-2xs text-ink-faint",children:[ae.numPages,"p"]}),u.jsx("button",{onClick:()=>V(ke=>ke.filter(Ne=>Ne.id!==ae.id)),className:"text-ink-faint hover:text-red-500 text-xs opacity-0 group-hover:opacity-100 transition-opacity",children:u.jsx(mn,{size:14,strokeWidth:1.75})})]},ae.id))}),M&&u.jsxs("div",{className:"space-y-1 mt-2",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx("span",{className:"text-xs text-ink-muted font-medium",children:b("landing.roleLabel")}),u.jsx("button",{onClick:()=>{_(!1),O("")},className:"text-xs text-ink-faint hover:text-ink-muted",children:u.jsx(mn,{size:14,strokeWidth:1.75})})]}),u.jsx("textarea",{value:D,onChange:ae=>O(ae.target.value),placeholder:b("landing.rolePlaceholder"),className:"w-full text-xs border border-line rounded-lg px-3 py-2 focus:outline-none focus:ring-1 focus:ring-accent bg-surface resize-none leading-relaxed",rows:2,autoFocus:!0}),u.jsx(u9,{onPick:O})]}),u.jsxs("div",{className:"flex items-center justify-end mt-2 gap-2",children:[u.jsx(g2,{}),u.jsx("button",{onClick:()=>_(!M),title:b("landing.roleTrayTitle"),className:`rounded-full w-8 h-8 flex items-center justify-center transition-colors shrink-0 ${M||D?"text-accent bg-accent/10 hover:bg-accent/20":"text-ink-faint hover:text-ink-muted hover:bg-line"}`,children:u.jsx(ZP,{size:16,strokeWidth:1.75})}),u.jsx("button",{onClick:()=>F.current?.click(),className:"text-ink-faint hover:text-accent hover:bg-wash rounded-xl px-3 py-2 transition-colors text-sm",title:b("landing.attach"),children:u.jsx(wi,{size:16,strokeWidth:1.75})}),u.jsx("input",{ref:F,type:"file",multiple:!0,accept:Ud,className:"hidden",onChange:ae=>{ge(ae.target.files||[]),ae.target.value=""}}),u.jsx("button",{onClick:Mn,disabled:!w.trim()||P.some(ae=>ae.isExtracting),className:"bg-accent hover:bg-accent-strong disabled:opacity-30 disabled:cursor-not-allowed text-white text-sm px-5 py-2 rounded-xl transition-all",children:P.some(ae=>ae.isExtracting)?b("landing.extracting"):b("landing.send")})]})]}),u.jsxs("div",{onClick:()=>B.current?.click(),className:`mt-3 border-2 border-dashed rounded-xl px-5 py-3.5 cursor-pointer transition-all text-center bg-card/60 backdrop-blur ${J?"border-accent bg-accent/5 ring-2 ring-accent/20":"border-line hover:border-accent/40 hover:bg-accent/5"}`,children:[u.jsxs("div",{className:"flex items-center justify-center gap-2 text-sm text-ink-muted font-medium",children:[u.jsx(Io,{size:15,strokeWidth:1.75,className:"text-accent"})," ",b("landing.docStart")]}),u.jsx("p",{className:"text-2xs text-ink-faint mt-1.5",children:b("landing.docFormats")}),u.jsx("p",{className:"text-2xs text-ink-faint mt-0.5",children:b("landing.docPrivacy")})]}),!!window.desktopSessions&&u.jsxs("button",{onClick:()=>G(!0),className:"w-full mt-3 bg-card/60 backdrop-blur border border-line rounded-xl px-5 py-3.5 hover:border-accent/40 hover:bg-accent/5 transition-all text-center","data-landing-atlas":!0,children:[u.jsxs("div",{className:"flex items-center justify-center gap-2 text-sm text-ink-muted font-medium",children:[u.jsx(EP,{size:15,strokeWidth:1.75,className:"text-accent shrink-0"}),u.jsx("span",{children:b("landing.atlasStart")}),u.jsx(xP,{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:B,type:"file",multiple:!0,accept:Ud,className:"hidden",onChange:ae=>{He(ae.target.files||[]),ae.target.value=""}}),R&&u.jsx(y9,{onClose:()=>G(!1),onSwitched:()=>{G(!1),bt()}}),(!tt||(tt.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(Bd,{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:[ve==="zh"&&u.jsx("button",{onClick:()=>{pe.getState().setApiKeyPresetHint("zhipu"),pe.getState().setApiKeyModalOpen(!0)},className:"text-2xs bg-accent/10 text-accent hover:bg-accent/20 font-medium px-3 py-1.5 rounded-lg transition-colors shrink-0","data-quick-zhipu":!0,children:b("landing.quickZhipu")}),u.jsx("button",{onClick:()=>{w9()},className:"text-2xs bg-accent/10 text-accent hover:bg-accent/20 font-medium px-3 py-1.5 rounded-lg transition-colors shrink-0","data-quick-primary":!0,children:b("landing.quickOpenRouter")}),u.jsx("button",{onClick:()=>pe.getState().setApiKeyModalOpen(!0),className:"text-2xs text-ink-muted hover:text-ink hover:bg-wash font-medium px-3 py-1.5 rounded-lg transition-colors shrink-0",children:b("landing.quickOther")})]}),u.jsx("button",{onClick:()=>pe.getState().setApiKeyModalOpen(!0),className:"mt-2 mx-auto text-2xs text-ink-faint hover:text-accent transition-colors block","data-quick-subs":!0,children:b("landing.quickSubs")})]}),u.jsx("div",{className:"grid grid-cols-3 gap-3 mt-6",children:[{icon:qi,title:"landing.feature1.title",desc:"landing.feature1.desc"},{icon:x5,title:"landing.feature2.title",desc:"landing.feature2.desc"},{icon:BS,title:"landing.feature3.title",desc:"landing.feature3.desc"}].map(({icon:ae,title:ke,desc:Ne})=>u.jsxs("div",{className:"bg-card/60 backdrop-blur border border-line rounded-xl px-4 py-3.5",children:[u.jsx(ae,{size:16,strokeWidth:1.75,className:"text-accent mb-2"}),u.jsx("h3",{className:"text-xs font-semibold text-ink mb-1",children:b(ke)}),u.jsx("p",{className:"text-2xs text-ink-faint leading-relaxed",children:b(Ne)})]},ke))}),u.jsxs("div",{className:"text-center mt-6 flex items-center justify-center gap-5",children:[u.jsxs("button",{onClick:Ve,className:"text-xs text-accent hover:text-accent-strong font-medium transition-colors inline-flex items-center gap-1.5",children:[u.jsx(x5,{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(h5,{size:14,strokeWidth:1.75})," ",b("landing.howItWorks")]})]})]})]}),!kt&&u.jsx(Yae,{onSwitched:bt}),(W||Ce)&&!kt&&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:[!Ce&&u.jsx("button",{onClick:()=>vt(re(null)),draggable:!0,onDragStart:ae=>{ae.dataTransfer.setData("application/thoughtdag-content","ask"),ae.dataTransfer.effectAllowed="copy"},title:b("palette.askTitle"),className:"w-9 h-9 rounded-lg flex items-center justify-center text-accent hover:bg-accent/10 transition-colors cursor-grab",children:u.jsx(pd,{size:17,strokeWidth:1.75})}),u.jsx("button",{onPointerDown:ae=>It(ae,ke=>ei("note",re(ke))),title:b("palette.noteTitle"),className:"w-9 h-9 rounded-lg flex items-center justify-center text-amber-600 hover:bg-amber-500/10 transition-colors",children:u.jsx(Vi,{size:17,strokeWidth:1.75})}),u.jsx("button",{onPointerDown:ae=>It(ae,ke=>ei("file",re(ke))),title:b("palette.fileTitle"),className:"w-9 h-9 rounded-lg flex items-center justify-center text-ink-muted hover:bg-wash transition-colors",children:u.jsx(wi,{size:17,strokeWidth:1.75})}),u.jsx("button",{onPointerDown:ae=>It(ae,ke=>Ke(re(ke))),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(Px,{size:17,strokeWidth:1.75})})]}),kt&&u.jsxs("div",{className:"absolute top-4 z-10 flex gap-1.5 items-center transition-[right] duration-200",style:{right:pt?En+xd+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(Pd,{size:14,strokeWidth:1.75})," ",b("viewer.badge")]}),u.jsx("button",{onClick:()=>N(!0),className:"bg-card/90 backdrop-blur border border-line rounded-lg w-8 h-8 flex items-center justify-center shadow-sm hover:bg-wash transition-colors text-ink-muted hover:text-accent",title:b("search.entryTitle"),"data-search-entry":!0,children:u.jsx(zf,{size:15,strokeWidth:1.75})}),u.jsx(OE,{}),u.jsx("button",{onClick:()=>yf(),className:"bg-card/90 backdrop-blur border border-line rounded-lg w-8 h-8 flex items-center justify-center shadow-sm hover:bg-wash transition-colors text-ink-muted hover:text-accent",title:b("viewer.downloadJson"),children:u.jsx(Tc,{size:15,strokeWidth:1.75})}),u.jsx("a",{href:"https://github.com/chenxiachan/thoughtdag",target:"_blank",rel:"noreferrer",className:"bg-ink text-white rounded-lg h-8 px-3 flex items-center gap-1.5 shadow-sm hover:bg-ink/85 transition-colors text-xs font-medium",children:b("viewer.openApp")})]}),!kt&&u.jsxs("div",{className:"absolute top-4 z-10 flex gap-1.5 items-center transition-[right] duration-200",style:{right:pt?En+xd+12:16},children:[Ce&&u.jsxs(u.Fragment,{children:[u.jsxs("button",{onClick:()=>ze("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(pd,{size:14,strokeWidth:1.75})," ",b("paradigm.addHuman")]}),u.jsxs("button",{onClick:()=>ze("prompt"),className:"bg-card/90 backdrop-blur border border-accent/40 rounded-lg h-8 px-3 flex items-center gap-1.5 shadow-sm hover:bg-accent/10 transition-colors text-accent text-xs font-medium",children:[u.jsx(Oo,{size:14,strokeWidth:1.75})," ",b("paradigm.addPrompt")]}),u.jsxs("button",{onClick:()=>{qe()},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")]})]}),!Ce&&u.jsx(Yre,{}),!Ce&&u.jsx(d9,{}),!W&&u.jsx("button",{onClick:()=>pe.getState().setApiKeyModalOpen(!0),className:"bg-card/90 backdrop-blur border border-line rounded-lg w-8 h-8 flex items-center justify-center shadow-sm hover:bg-wash transition-colors text-ink-faint hover:text-accent",title:b("apikey.entryTitle"),"data-apikey-entry":!0,children:u.jsx(Bd,{size:15,strokeWidth:1.75})}),Dt>0&&!Ce&&u.jsxs("button",{onClick:()=>{const{nodes:ae,edges:ke,staleIds:Ne}=se.getState(),ce=Ne.reduce((je,Ze)=>{const st=ae.map(Kt=>Kt.id===Ze?{...Kt,data:{...Kt.data,question:"",response:""}}:Kt),{layerTokens:Pt}=wr(Ze,st,ke),Ut=ae.find(Kt=>Kt.id===Ze)?.data.question??"";return je+Pt.material+Pt.reference+Pt.chain+$n(Ut)},0);_s({title:b("replay.confirmTitle"),message:We(b("replay.confirmMsg"),{n:Dt,tok:ce.toLocaleString()}),confirmLabel:b("replay.confirmBtn")}).then(je=>{je&&se.getState().replayStale()})},className:"bg-amber-500/10 backdrop-blur border border-amber-500/40 rounded-lg h-8 px-3 flex items-center gap-1.5 shadow-sm hover:bg-amber-500/20 transition-colors text-amber-600 text-xs font-medium",title:b("replay.chipTitle"),children:[u.jsx(Lz,{size:14,strokeWidth:1.75})," ",Dt]}),W&&Ct.length>0&&u.jsxs("div",{ref:en,className:"relative",children:[u.jsx("button",{onClick:()=>jt(ae=>!ae),className:`bg-card/90 backdrop-blur border rounded-lg w-8 h-8 flex items-center justify-center shadow-sm transition-colors ${ut?"border-accent/40 text-accent":"border-line text-ink-faint hover:bg-wash"}`,title:b("toolbar.frames"),children:u.jsx(Px,{size:15,strokeWidth:1.75})}),ut&&u.jsx("div",{className:"absolute right-0 top-full mt-1.5 bg-card border border-line rounded-xl shadow-lg py-1 w-[230px] max-h-[320px] overflow-y-auto z-30 animate-fade-in",children:Ct.map(ae=>u.jsxs("button",{onClick:()=>{jt(!1),q.current?.fitBounds({x:ae.position.x,y:ae.position.y,width:ae.width??640,height:ae.height??420},{duration:400,padding:.15})},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2",children:[u.jsx("span",{className:`w-2.5 h-2.5 rounded-sm shrink-0 ${(gd[ae.data.frameColor??"gray"]??gd.gray).dot}`}),u.jsx("span",{className:"truncate",children:ae.data.question||b("frame.untitled")})]},ae.id))})]}),W&&u.jsx("button",{onClick:()=>N(!0),className:"bg-card/90 backdrop-blur border border-line rounded-lg w-8 h-8 flex items-center justify-center shadow-sm hover:bg-wash transition-colors text-ink-faint hover:text-accent",title:b("search.entryTitle"),"data-search-entry":!0,children:u.jsx(zf,{size:15,strokeWidth:1.75})}),u.jsx(OE,{}),W&&!Ce&&u.jsx(vae,{showTrigger:!1,openPing:Bt,onLocate:ae=>{const ke=se.getState().nodes.find(Ne=>Ne.id===ae);ke&&(d(ae),oe(ke,{zoom:1}))}}),Re&&!kt&&u.jsxs("button",{onClick:()=>pe.getState().setCondenseDialogOpen(!0),className:"bg-card/90 backdrop-blur border border-accent/50 rounded-lg h-8 px-2 flex items-center justify-center gap-1.5 shadow-sm hover:bg-wash transition-colors text-accent",title:We(b("condense.entryBuilding"),{i:String(Le.current),n:String(Le.total)}),"data-condense-entry":!0,children:[u.jsx(Un,{size:14,strokeWidth:1.75,className:"animate-spin"}),u.jsxs("span",{className:"text-2xs font-mono",children:[Le.current,"/",Le.total]})]}),Gm&&u.jsx("button",{onClick:()=>pe.getState().setBackupDialogOpen(!0),className:"bg-card/90 backdrop-blur border border-line rounded-lg w-8 h-8 flex items-center justify-center shadow-sm hover:bg-wash transition-colors text-ink-muted hover:text-accent",title:b("backup.dialogTitle"),"data-backup-entry":!0,children:u.jsx(IS,{size:15,strokeWidth:1.75})}),u.jsxs("div",{ref:Sn,className:"relative",children:[u.jsx("button",{onClick:()=>xn(ae=>!ae),className:`bg-card/90 backdrop-blur border rounded-lg w-8 h-8 flex items-center justify-center shadow-sm transition-colors ${Xt?"border-accent/40 text-accent":"border-line text-ink-faint hover:bg-wash"}`,title:b("toolbar.more"),"data-toolbar-more":!0,children:u.jsx(CS,{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:[W&&u.jsxs("button",{onClick:()=>{xn(!1),S(!k)},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5",title:b(k?"toolbar.showAnnotations":"toolbar.hideAnnotations"),children:[u.jsx(Vi,{size:14,strokeWidth:1.75,className:`shrink-0 ${k?"text-accent":"text-ink-faint"}`})," ",b(k?"toolbar.menuAnnotationsShow":"toolbar.menuAnnotationsHide")]}),W&&u.jsxs("button",{onClick:()=>{xn(!1),_s({title:b("confirm.relayoutTitle"),message:b("confirm.relayoutMsg"),confirmLabel:b("toolbar.relayout")}).then(ae=>{ae&&(x(),setTimeout(()=>q.current?.fitView({duration:400,padding:.15}),50))})},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5",children:[u.jsx(Iz,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("toolbar.relayout")]}),K>0&&u.jsxs("button",{onClick:()=>{xn(!1),pe.getState().setHighlightsOverviewOpen(!0)},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5",title:b("hlov.entryTitle"),"data-hlov-entry":!0,children:[u.jsx(zd,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",We(b("hlov.entry"),{n:K})]}),U>0&&u.jsxs("button",{onClick:()=>{xn(!1),pe.getState().setMaterialsOverviewOpen(!0)},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5",title:b("matov.entryTitle"),"data-matov-entry":!0,children:[u.jsx(wi,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",We(b("matov.entry"),{n:U})]}),W&&u.jsx("div",{className:"border-t border-line/60 my-1"}),W&&!Ce&&!kt&&u.jsxs("button",{onClick:()=>{xn(!1),pe.getState().setCondenseDialogOpen(!0)},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5",title:b("condense.entryTitle"),children:[u.jsx(vm,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("condense.title"),"…"]}),W&&!Ce&&u.jsxs("button",{onClick:()=>{xn(!1),fn(ae=>ae+1)},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5",title:b("toolbar.diagnose"),"data-menu-diagnose":!0,children:[u.jsx(HS,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("toolbar.menuDiagnose")]}),W&&!Ce&&u.jsxs("button",{onClick:()=>{xn(!1),(async()=>{const{nodes:ae,edges:ke}=se.getState(),{confirmIfSensitive:Ne}=await Tt(async()=>{const{confirmIfSensitive:je}=await import("./sensitive-scan-OXO0A60C.js");return{confirmIfSensitive:je}},[]);if(!await Ne(ae))return;const ce=await wH(ae,ke);await navigator.clipboard.writeText(ce).catch(()=>{}),pe.getState().setShareDialogUrl(ce)})()},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(dB,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("toolbar.menuShare")]}),W&&u.jsxs("button",{onClick:()=>{xn(!1),Ce?bF():yf()},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5","data-menu-export":!0,children:[u.jsx(Tc,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b(Ce?"paradigm.exportParadigm":"switcher.exportBackup")]}),Q&&u.jsxs("button",{onClick:()=>{xn(!1),EF()},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5",title:b("toolbar.exportEventsTitle"),children:[u.jsx(vi,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("toolbar.exportEvents")]}),W&&u.jsx("div",{className:"border-t border-line/60 my-1"}),u.jsxs("div",{className:"px-3 pt-2 pb-1","data-appearance-lighting":!0,children:[u.jsx("div",{className:"text-2xs text-ink-faint mb-1.5",children:b("appearance.lighting")}),u.jsx("div",{className:"flex rounded-lg border border-line overflow-hidden text-2xs",children:[["light",b("appearance.light")],["dark",b("appearance.dark")],["system",b("appearance.system")]].map(([ae,ke],Ne)=>u.jsx("button",{onClick:()=>As.getState().setLighting(ae),className:`flex-1 px-1 py-1.5 transition-colors ${Ne>0?"border-l border-line":""} ${be===ae?"bg-accent/10 text-accent font-medium":"text-ink-muted hover:bg-wash"}`,children:ke},ae))})]}),u.jsxs("div",{className:"px-3 pt-1 pb-2","data-appearance-paper":!0,children:[u.jsx("div",{className:"text-2xs text-ink-faint mb-1.5",children:b("appearance.paper")}),u.jsx("div",{className:"flex rounded-lg border border-line overflow-hidden text-2xs",children:[["plain",b("appearance.plain")],["grid",b("appearance.grid")]].map(([ae,ke],Ne)=>u.jsx("button",{onClick:()=>As.getState().setPaper(ae),className:`flex-1 px-1 py-1.5 transition-colors ${Ne>0?"border-l border-line":""} ${$===ae?"bg-accent/10 text-accent font-medium":"text-ink-muted hover:bg-wash"}`,children:ke},ae))})]}),u.jsx("div",{className:"border-t border-line/60 my-1"}),u.jsxs("button",{onClick:()=>{xn(!1),pe.getState().setMemoryManagerOpen(!0)},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5",title:b("memory.entryTitle"),children:[u.jsx(TP,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("memory.managerTitle")]}),u.jsxs("button",{onClick:()=>{xn(!1),y(!0)},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5",children:[u.jsx(h5,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("landing.howItWorks")]}),he&&u.jsxs("button",{onClick:()=>{xn(!1),navigator.clipboard.writeText(Cb(he.latest)).then(()=>Qe("success",b("plugin.updateCopied"),6e3)).catch(()=>{})},className:"w-full text-left px-3 py-2 text-xs text-accent hover:bg-wash transition-colors flex items-center gap-2.5",title:We(b("plugin.updateHint"),{cmd:Cb(he.latest)}),"data-plugin-update":!0,children:[u.jsx(Tc,{size:14,strokeWidth:1.75,className:"shrink-0"})," ",We(b("plugin.updateAvailable"),{v:he.latest})]}),u.jsxs("button",{onClick:()=>{xn(!1),pe.getState().setReleaseNotesOpen(!0)},className:"w-full text-left px-3 py-2 text-xs text-ink hover:bg-wash transition-colors flex items-center gap-2.5","data-open-release-notes":!0,children:[u.jsx($b,{size:14,strokeWidth:1.75,className:"text-ink-faint shrink-0"})," ",b("releaseNotes.entry")]})]})]}),u.jsx("button",{onClick:s,disabled:p<=0,className:"bg-card/90 backdrop-blur border border-line rounded-lg w-8 h-8 flex items-center justify-center shadow-sm hover:bg-wash transition-colors disabled:opacity-20 disabled:cursor-not-allowed",title:b("canvas.undo"),children:u.jsx(FS,{size:16,strokeWidth:1.75})}),u.jsx("button",{onClick:o,disabled:p>=m.length-1,className:"bg-card/90 backdrop-blur border border-line rounded-lg w-8 h-8 flex items-center justify-center shadow-sm hover:bg-wash transition-colors disabled:opacity-20 disabled:cursor-not-allowed",title:b("canvas.redo"),children:u.jsx(eB,{size:16,strokeWidth:1.75})})]}),Lt&&!kt&&u.jsx(oae,{}),u.jsx(bae,{open:T,onClose:()=>N(!1),onLocate:ae=>{const ke=se.getState().nodes.find(Ne=>Ne.id===ae);ke&&(d(ae),oe(ke,{zoom:1}))}}),Yt&&u.jsx(cae,{x:Yt.x,y:Yt.y,nodeId:Yt.nodeId,onClose:()=>kn(null)}),u.jsx(hae,{onLocate:ae=>{const ke=se.getState().nodes.find(Ne=>Ne.id===ae);ke&&(d(ae),oe(ke,{zoom:1}))}}),u.jsx(rie,{onLocate:ae=>{const ke=se.getState().nodes.find(Ne=>Ne.id===ae);ke&&(d(ae),oe(ke,{zoom:1}))}}),u.jsx(uae,{onLocate:ae=>{const ke=se.getState().nodes.find(Ne=>Ne.id===ae);ke&&(d(ae),oe(ke,{zoom:1}))}}),hn&&u.jsx("div",{className:"fixed z-50 bg-card border border-line rounded-xl shadow-lg py-1 min-w-[120px]",style:{left:hn.x,top:hn.y},children:u.jsxs("button",{onClick:()=>ur(hn.edgeId),className:"w-full text-left px-4 py-2 text-sm text-red-600 hover:bg-red-50 transition-colors flex items-center gap-1.5",children:[u.jsx(Va,{size:14,strokeWidth:1.75}),b("canvas.deleteEdge")]})})]}),u.jsx(Hre,{onFocusSegment:ae=>{const ke=q.current,Ne=se.getState().nodes.filter(Kt=>ae.includes(Kt.id));if(!ke||Ne.length===0)return;const ce=Ne.map(Kt=>Kt.position.x),je=Ne.map(Kt=>Kt.position.y),Ze=Math.min(...ce),st=Math.min(...je),Pt=Math.max(...ce)+520-Ze,Ut=Math.max(...je)+240-st;ke.fitBounds({x:Ze,y:st,width:Pt+700,height:Ut},{duration:350,padding:.15})}}),pt&&u.jsx(sae,{onFocusNode:ae=>{const ke=e.find(Ne=>Ne.id===ae);ke&&oe(ke,{duration:300})}}),u.jsx(Iae,{onLocate:ae=>{const ke=se.getState().nodes.find(Ne=>Ne.id===ae);ke&&(d(ae),oe(ke,{zoom:1}))}})]})}function uie({panelShiftWidth:e}){const t=c0(),n=zt(),a=Nl(),r=se(d=>d.nodes.length),s=se(d=>d.nodes),o=L.useMemo(()=>{let d=null,h="";for(const m of s){if(m.data.stepKind&&m.data.stepKind!=="human"&&m.data.stepKind!=="prompt")continue;const p=[m.data.lastGeneratedAt,m.data.askedAt,m.data.createdAt,...m.data.editedAts??[]].filter(Boolean).sort().pop();p&&p>h&&(h=p,d=m)}return d?{node:d,at:h}:null},[s]);if(kt||t==="work"||r<2)return null;const c=()=>{if(!o)return;pe.getState().setBeaconNodeId(null);const{node:d}=o;a.setCenter(d.position.x+260,d.position.y+110,{zoom:1,duration:1100}),window.setTimeout(()=>{se.getState().setSelectedNodeId(d.id),pe.getState().setPanelOpen(!0),window.setTimeout(()=>{a.setCenter(d.position.x+260+om(d.id)/2,d.position.y+110,{zoom:1,duration:300})},60)},1150),window.setTimeout(()=>{Qe("success",n("continue.arrived"),12e3,{label:n("continue.summarize"),run:()=>{f9(d.id)}})},1550)};return u.jsxs("div",{className:"absolute bottom-6 z-10 flex items-center gap-2 -translate-x-1/2 transition-[left] duration-300",style:{left:`calc((100% - ${e}px) / 2)`},"data-map-dock":!0,children:[u.jsxs("button",{onClick:()=>pe.getState().setThoughtMapOpen(!0),"data-tmap-pill":!0,className:"flex items-center gap-2 bg-card/95 backdrop-blur border border-line-strong rounded-full px-5 py-2.5 text-sm text-ink shadow-lg hover:border-accent/40 hover:text-accent transition-colors",children:[u.jsx(Yb,{size:16,strokeWidth:1.75})," ",n("tmap.export")]}),o&&u.jsxs("button",{onClick:c,onMouseEnter:()=>pe.getState().setBeaconNodeId(o.node.id),onMouseLeave:()=>pe.getState().setBeaconNodeId(null),title:n("continue.buttonTitle"),"data-continue-pill":!0,className:"flex items-center gap-2 bg-accent text-white rounded-full px-5 py-2.5 text-sm shadow-lg hover:bg-accent-strong transition-colors",children:[u.jsx(aB,{size:16,strokeWidth:1.75})," ",n("continue.button")]})]})}function die(){const e=c0(),t=un(n=>n.transform[2]);return L.useEffect(()=>{document.querySelector(".react-flow")?.setAttribute("data-zoom-tier",e)},[e]),L.useEffect(()=>{document.querySelector(".react-flow")?.style.setProperty("--tdag-zoom",String(t))},[t]),null}Dne();const py="/thoughtdag/api";window.desktopSessions||mU(py);Tt(()=>Promise.resolve().then(()=>Xre),void 0).then(e=>e.bootPluginUpdateCheck(py));if(!window.desktopAgents){const e=py;Tt(()=>import("./http-bridge-mmwHcDuo.js"),[]).then(async t=>{await t.installAgentsHttpBridge(e)&&window.dispatchEvent(new CustomEvent("td:agents-ready"))})}kt?EH():(C7(),navigator.storage?.persist&&navigator.storage.persist(),Tt(()=>Promise.resolve().then(()=>_re),void 0).then(e=>e.bootAutoBackup()));Tt(()=>import("./update-check-CNsM71E0.js"),[]).then(e=>e.bootUpdateCheck());window.addEventListener("hashchange",()=>{window.location.hash.startsWith("#view=")!==kt&&window.location.reload()});q_.createRoot(document.getElementById("root")).render(u.jsx(L.StrictMode,{children:u.jsx(lie,{})}));export{Qd as A,rr as B,nF as C,Em as D,P7 as E,mie as F,Us as G,Fr as H,Tt as _,De as a,se as b,rn as c,Is as d,kt as e,We as f,_7 as g,Ms as h,bie as i,Hr as j,Yc as k,Nm as l,Yx as m,oF as n,In as o,si as p,iF as q,sF as r,Ro as s,Qe as t,pe as u,O7 as v,_s as w,pie as x,fie as y,hie as z};
|