@runfusion/fusion 0.11.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/dist/bin.js +1122 -356
  2. package/dist/client/assets/{AgentDetailView-DQBjJSPJ.js → AgentDetailView-B20ApPe1.js} +3 -3
  3. package/dist/client/assets/{AgentsView-xm_3NO4M.css → AgentsView-Bkk-uBij.css} +1 -1
  4. package/dist/client/assets/{AgentsView-DlA0yHBg.js → AgentsView-ChN1tgQ0.js} +17 -17
  5. package/dist/client/assets/ChatView-oPMFwmoc.js +1 -0
  6. package/dist/client/assets/{DevServerView-BVixhlF0.js → DevServerView-DQrVLbK5.js} +1 -1
  7. package/dist/client/assets/{DirectoryPicker-tvBgHxa7.js → DirectoryPicker-DVmy6sLM.js} +1 -1
  8. package/dist/client/assets/{DocumentsView-DVw_wT6V.js → DocumentsView-DHEv-Q2a.js} +1 -1
  9. package/dist/client/assets/{InsightsView-G3MZhwSx.js → InsightsView-ByyY7GX7.js} +2 -2
  10. package/dist/client/assets/{MemoryView-Bl9gx2Dw.js → MemoryView-Udiu0u8R.js} +1 -1
  11. package/dist/client/assets/{NodesView-dwVhD4V2.js → NodesView-CupS-GGc.js} +4 -4
  12. package/dist/client/assets/{PiExtensionsManager-CEHp6_Mj.js → PiExtensionsManager-DXs2xI8K.js} +2 -2
  13. package/dist/client/assets/PluginManager-BCpiZf4_.js +1 -0
  14. package/dist/client/assets/{ResearchView-BvlLYC_1.js → ResearchView-BG9Feaeb.js} +1 -1
  15. package/dist/client/assets/ResearchView-BzRdUzNq.css +1 -0
  16. package/dist/client/assets/{RoadmapsView-DdYXssP2.js → RoadmapsView-BTJtmBnF.js} +2 -2
  17. package/dist/client/assets/SettingsModal-DZ_LaEhd.js +31 -0
  18. package/dist/client/assets/{SettingsModal-CriZP5Lp.css → SettingsModal-DcGFm6NR.css} +1 -1
  19. package/dist/client/assets/{SettingsModal-CGWipm3s.js → SettingsModal-eNCZiHa6.js} +1 -1
  20. package/dist/client/assets/{SetupWizardModal-CKsJduYM.js → SetupWizardModal-yf79TN1L.js} +1 -1
  21. package/dist/client/assets/SkillMultiselect-DDHJnrkn.css +1 -0
  22. package/dist/client/assets/SkillMultiselect-DOj5vX4U.js +1 -0
  23. package/dist/client/assets/SkillsView-CgnCnikX.js +1 -0
  24. package/dist/client/assets/{TodoView-ByXJ90yL.js → TodoView-67BMyICY.js} +2 -2
  25. package/dist/client/assets/{folder-open-CxOUgHDf.js → folder-open-D11gjHGK.js} +1 -1
  26. package/dist/client/assets/index-BLn1R7Ob.css +1 -0
  27. package/dist/client/assets/index-CLAHcGnI.js +656 -0
  28. package/dist/client/assets/{list-checks--sf9u9ox.js → list-checks-CBzPc3GA.js} +1 -1
  29. package/dist/client/assets/{star-CF1f2iPu.js → star-BWcRk8nt.js} +1 -1
  30. package/dist/client/assets/{upload-rOBd4OhB.js → upload-91TM4ljC.js} +1 -1
  31. package/dist/client/assets/{users-De-vFat1.js → users-BAsI___L.js} +1 -1
  32. package/dist/client/index.html +2 -2
  33. package/dist/client/theme-data.css +1 -1
  34. package/dist/client/version.json +1 -1
  35. package/dist/extension.js +479 -74
  36. package/dist/pi-claude-cli/package.json +1 -1
  37. package/package.json +1 -1
  38. package/skill/fusion/references/cli-commands.md +14 -0
  39. package/skill/fusion/references/engine-tools.md +1 -0
  40. package/dist/client/assets/ChatView-DK5CmiAk.js +0 -1
  41. package/dist/client/assets/PluginManager-Dx0mcwat.js +0 -1
  42. package/dist/client/assets/ResearchView-BVJFgfat.css +0 -1
  43. package/dist/client/assets/SettingsModal-Bgjg_4CD.js +0 -31
  44. package/dist/client/assets/SkillsView-C4Tz7CxC.js +0 -1
  45. package/dist/client/assets/index-BCz4ye4p.css +0 -1
  46. package/dist/client/assets/index-D7gT6mCr.js +0 -656
@@ -0,0 +1 @@
1
+ import{r as s,j as t}from"./vendor-react-K0fH_qHe.js";import{i as ze,aN as Dt,g as Et,aO as Pt,a as Ft,aP as Lt,aQ as _t,aR as Ot,aS as It,aT as Ut,aU as zt,s as Ht,aV as Vt,aW as qt,aX as Bt,aY as Gt,ad as it,ae as rt,S as Wt,Y as Xe,M as Ze,aq as Kt,aZ as Yt,B as Ee,aa as lt,ab as ot,a_ as Jt,a$ as Qt,b0 as Xt,b1 as Zt,b2 as es,b3 as ts,b4 as ss,b5 as et,h as ns,u as tt,k as as}from"./index-CLAHcGnI.js";import"./vendor-xterm-DzcZoU0P.js";const Ue="kb-chat-active-session";function is(a){const i=a?.toolCalls;if(!Array.isArray(i))return;const l=i.map(o=>{if(!o||typeof o!="object")return null;const c=o,y=typeof c.toolName=="string"?c.toolName:"";if(!y)return null;const N=c.args;return{toolName:y,...N&&typeof N=="object"?{args:N}:{},isError:!!c.isError,result:c.result,status:"completed"}}).filter(o=>o!==null);return l.length>0?l:void 0}function st(a){return{id:a.id,sessionId:a.sessionId,role:a.role,content:a.content,thinkingOutput:a.thinkingOutput,toolCalls:is(a.metadata),attachments:a.attachments,createdAt:a.createdAt}}function rs(a){const[i,l]=s.useState([]),[o,c]=s.useState(null),[y,N]=s.useState(!0),[$,b]=s.useState([]),[D,z]=s.useState(!1),[p,F]=s.useState(!1),[C,M]=s.useState(""),[g,x]=s.useState(""),[T,k]=s.useState([]),[H,L]=s.useState(""),[ee,K]=s.useState(""),[_,X]=s.useState(!0),[h,j]=s.useState(new Map),v=s.useRef(null),O=s.useRef(!1),V=s.useRef(""),de=s.useRef(null),ue=s.useRef(i),pe=s.useRef(o),xe=s.useRef(p);ue.current=i,pe.current=o,xe.current=p,s.useEffect(()=>{V.current=H},[H]);const ve=s.useRef(new Set),he=s.useRef(0),ye=s.useRef(a);ye.current!==a&&(ye.current=a,he.current++),s.useEffect(()=>{const u=he.current;ze(void 0,a).then(f=>{if(he.current!==u)return;const m=new Map;for(const R of f)m.set(R.id,R);j(m)}).catch(()=>{})},[a]);const Y=s.useCallback(async()=>{N(!0);try{const f=[...(await Dt(a)).sessions].sort((m,R)=>new Date(R.updatedAt).getTime()-new Date(m.updatedAt).getTime());l(f)}catch{}finally{N(!1)}},[a]);s.useEffect(()=>{Y()},[Y]);const se=s.useRef(()=>{});s.useEffect(()=>{if(y)return;const u=Et(Ue,a);u&&i.find(m=>m.id===u)&&se.current(u)},[y,i,a]);const le=s.useCallback(async(u,f)=>{z(!0);try{const m=await Pt(u,{limit:50,...f},a),R=m.messages.map(st);f?.offset&&f.offset>0?b(I=>[...R,...I]):b(R),X(m.messages.length>=50)}catch{}finally{z(!1)}},[a]),ne=s.useCallback((u,f)=>{v.current&&(v.current.close(),v.current=null);const m=f??i.find(R=>R.id===u);c(m||null),M(""),x(""),k([]),F(!1),X(!0),u?le(u):b([]),u?Ft(Ue,u,a):Lt(Ue,a)},[i,le,a]);se.current=ne;const we=s.useCallback(async u=>{const f=await _t(u,a);v.current&&(v.current.close(),v.current=null);const m={id:f.session.id,title:f.session.title,agentId:f.session.agentId,status:f.session.status,modelProvider:f.session.modelProvider,modelId:f.session.modelId,createdAt:f.session.createdAt,updatedAt:f.session.updatedAt};return l(R=>R.some(I=>I.id===m.id)?R:[m,...R]),ne(m.id,m),b([]),m},[a,ne]),me=s.useCallback(async u=>{await Ot(u,{status:"archived"},a),l(f=>f.filter(m=>m.id!==u)),o?.id===u&&(c(null),b([]))},[o,a]),Se=s.useCallback(async u=>{o?.id===u&&v.current&&(v.current.close(),v.current=null),await It(u,a),l(f=>f.filter(m=>m.id!==u)),o?.id===u&&(c(null),b([]))},[o,a]),oe=s.useCallback(async()=>{!o||!_||await le(o.id,{offset:$.length})},[o,_,le,$.length]),te=s.useCallback(()=>{o&&(O.current=!0,de.current?.(),de.current=null,v.current?.close(),v.current=null,Ut(o.id,a).catch(()=>{}),F(!1),M(""),x(""),k([]))},[o,a]),ce=s.useCallback(()=>{V.current="",L("")},[]),fe=s.useCallback((u,f)=>{if(!o)return;if(p){V.current=u,L(u);return}O.current=!1,v.current&&(v.current.close(),v.current=null);const m=`temp-${Date.now()}`,R={id:m,sessionId:o.id,role:"user",content:u,createdAt:new Date().toISOString()};b(w=>[...w,R]),M(""),x(""),k([]),F(!0);let I="",ae="",q=[],J=null,B=null;const G=()=>{J=null,M(I)},E=()=>{B=null,x(ae)},d=()=>{J!==null&&(cancelAnimationFrame(J),J=null),B!==null&&(cancelAnimationFrame(B),B=null)};de.current=d;const U={onThinking:w=>{ae+=w,B===null&&(B=requestAnimationFrame(E))},onText:w=>{I+=w,J===null&&(J=requestAnimationFrame(G))},onToolStart:w=>{q=[...q,{toolName:w.toolName,args:w.args,isError:!1,status:"running"}],k(q)},onToolEnd:w=>{const S=[...q];for(let W=S.length-1;W>=0;W--){const A=S[W];if(A?.toolName===w.toolName&&A.status==="running"){S[W]={...A,status:"completed",isError:w.isError,result:w.result},q=S,k(S);return}}q=[...S,{toolName:w.toolName,isError:w.isError,result:w.result,status:"completed"}],k(q)},onDone:w=>{d();const S={id:w.messageId||`msg-${Date.now()}`,sessionId:o.id,role:"assistant",content:I,thinkingOutput:ae,toolCalls:q.length>0?q:void 0,createdAt:new Date().toISOString()};ve.current.add(S.id),b(A=>[...A,S]),M(""),x(""),k([]),F(!1),v.current=null,setTimeout(()=>{ve.current.delete(S.id)},1e3),Y();const W=V.current.trim();W&&(V.current="",L(""),fe(W))},onError:w=>{if(d(),b(S=>S.filter(W=>W.id!==m)),M(""),x(""),k([]),F(!1),v.current=null,console.error("[useChat] Stream error:",w),!O.current){const S=V.current.trim();S&&(V.current="",L(""),fe(S))}}};v.current=zt(o.id,u,U,f,a)},[o,p,a,Y]),be=ee?i.filter(u=>u.title?.toLowerCase().includes(ee.toLowerCase())||u.agentId.toLowerCase().includes(ee.toLowerCase())):i;return s.useEffect(()=>{const u=he.current,f=a?`?projectId=${encodeURIComponent(a)}`:"",m=()=>he.current!==u,R=G=>{if(m())return;const E=JSON.parse(G.data);l(d=>d.some(U=>U.id===E.id)?d:[E,...d])},I=G=>{if(m())return;const E=JSON.parse(G.data);l(d=>[...d.map(w=>w.id===E.id?E:w)]),pe.current?.id===E.id&&c(E)},ae=G=>{if(m())return;const{id:E}=JSON.parse(G.data);l(d=>d.filter(U=>U.id!==E)),pe.current?.id===E&&(c(null),b([]))},q=G=>{if(m())return;const E=JSON.parse(G.data),d=st(E);ve.current.has(d.id)||pe.current?.id===d.sessionId&&!xe.current&&b(U=>U.some(w=>w.id===d.id)?U:[...U,d])},J=G=>{if(m())return;const{id:E}=JSON.parse(G.data);b(d=>d.filter(U=>U.id!==E))};return Ht(`/api/events${f}`,{events:{"chat:session:created":R,"chat:session:updated":I,"chat:session:deleted":ae,"chat:message:added":q,"chat:message:deleted":J}})},[a]),s.useEffect(()=>()=>{v.current&&(v.current.close(),v.current=null)},[]),{sessions:i,activeSession:o,sessionsLoading:y,messages:$,messagesLoading:D,isStreaming:p,streamingText:C,streamingThinking:g,streamingToolCalls:T,pendingMessage:H,selectSession:ne,createSession:we,archiveSession:me,deleteSession:Se,sendMessage:fe,stopStreaming:te,clearPendingMessage:ce,loadMoreMessages:oe,hasMoreMessages:_,searchQuery:ee,setSearchQuery:K,filteredSessions:be,refreshSessions:Y,agentsMap:h}}function ct(a){const i=new Date(a),o=new Date().getTime()-i.getTime(),c=Math.floor(o/1e3),y=Math.floor(c/60),N=Math.floor(y/60),$=Math.floor(N/24);return c<60?"just now":y<60?`${y}m ago`:N<24?`${N}h ago`:$<7?`${$}d ago`:i.toLocaleDateString()}function nt(a,i){if(!a||!i)return null;const l=i.toLowerCase();if(l.includes("claude")){let c=i.replace(/^claude[- ]/i,"Claude ").replace(/sonnet[- ](\d+)[- ](\d+)/i,"Sonnet $1.$2").replace(/sonnet[- ](\d+)/i,"Sonnet $1").replace(/haiku[- ](\d+)/i,"Haiku $1").replace(/opus[- ](\d+)/i,"Opus $1").replace(/sonnet/i,"Sonnet").replace(/haiku/i,"Haiku").replace(/opus/i,"Opus").replace(/-/g," ").trim();return c=c.replace(/\s+/g," "),c.length>30?c.slice(0,30)+"…":c}if(l.includes("gpt")||l.includes("openai")){const c=i.replace(/^gpt-4-turbo$/i,"GPT-4 Turbo").replace(/^gpt-4o-mini$/i,"GPT-4o Mini").replace(/^gpt-4o$/i,"GPT-4o").replace(/^gpt-4$/i,"GPT-4").replace(/^gpt-o1-preview$/i,"GPT-o1 Preview").replace(/^gpt-o1-mini$/i,"GPT-o1 Mini").replace(/^gpt-o1$/i,"GPT-o1").replace(/^gpt/i,"GPT").trim();return c.length>30?c.slice(0,30)+"…":c}if(l.includes("gemini")){const c=i.replace(/^gemini[- ]/i,"Gemini ").replace(/pro[- ](\d+)[- ](\d+)/i,"Pro $1.$2").replace(/pro[- ](\d+)/i,"Pro $1").replace(/-/g," ").replace(/\s+/g," ").trim();return c.length>30?c.slice(0,30)+"…":c}const o=i.replace(/-/g," ").replace(/^\w/,c=>c.toUpperCase()).replace(/\s+/g," ").trim();return o.length>30?o.slice(0,30)+"…":o}function Re(a,i){return a.length<=i?a:`${a.slice(0,i)}…`}function ls(a){if(!a)return null;const i=Object.entries(a);return i.length===0?null:i.map(([l,o])=>{const c=typeof o=="string"?o:(()=>{try{return JSON.stringify(o)}catch{return String(o)}})();return`${l}=${Re(c,50)}`}).join(", ")}function os(a){if(a===void 0)return null;if(typeof a=="string")return Re(a,200);try{return Re(JSON.stringify(a),200)}catch{return Re(String(a),200)}}function dt(a){if(!a||a.length===0)return null;const i=(p,F)=>{const C=p.status==="running",M=p.status==="completed"&&p.isError,g=ls(p.args),x=os(p.result),T=C?g:x?`result: ${x}`:g?`args: ${g}`:null,k=C?"running":M?"error":"completed";return t.jsxs("details",{className:`chat-tool-call${C?" chat-tool-call--running":""}${M?" chat-tool-call--error":""}`,open:C,children:[t.jsxs("summary",{children:[t.jsx("span",{className:"chat-tool-call-status-dot","aria-hidden":"true"}),t.jsx("span",{className:"chat-tool-call-name",children:p.toolName}),T&&t.jsx("span",{className:"chat-tool-call-preview",title:T,children:T}),t.jsx("span",{className:"chat-tool-call-status-text",children:k})]}),t.jsxs("div",{className:"chat-tool-call-content",children:[g&&t.jsxs("div",{className:"chat-tool-call-row",children:[t.jsx("span",{className:"chat-tool-call-label",children:"args"}),t.jsx("span",{className:"chat-tool-call-value",children:g})]}),x&&t.jsxs("div",{className:`chat-tool-call-row${M?" chat-tool-call-row--error":""}`,children:[t.jsx("span",{className:"chat-tool-call-label",children:"result"}),t.jsx("span",{className:"chat-tool-call-value",children:x})]})]})]},`${p.toolName}-${F}`)},l="chat-tool-calls";if(a.length===1)return t.jsxs("div",{className:l,"data-testid":"chat-tool-calls",children:[t.jsxs("div",{className:"chat-tool-calls-header",children:[t.jsx(et,{size:12,"aria-hidden":"true"}),t.jsx("span",{children:"Tool calls"})]}),i(a[0],0)]});const o=a.filter(p=>p.status==="running").length,c=a.filter(p=>p.status==="completed"&&p.isError).length,y=o>0,N=Array.from(new Set(a.map(p=>p.toolName))),$=N.slice(0,5),b=Math.max(0,N.length-$.length),D=b>0?`${$.join(", ")}, +${b} more`:$.join(", "),z=y?`(${o} running)`:c>0?`(${c} ${c===1?"error":"errors"})`:null;return t.jsx("div",{className:l,"data-testid":"chat-tool-calls",children:t.jsxs("details",{className:"chat-tool-calls-group","data-testid":"chat-tool-calls-group",open:y,children:[t.jsxs("summary",{className:"chat-tool-calls-group-summary",children:[t.jsx(et,{size:12,"aria-hidden":"true"}),t.jsxs("span",{children:[a.length," tool calls"]}),t.jsx("span",{className:"chat-tool-calls-names",title:D,children:D}),z&&t.jsx("span",{className:"chat-tool-calls-group-status",children:z})]}),a.map((p,F)=>i(p,F))]})})}const ut={pre:({children:a,...i})=>t.jsx("pre",{...i,className:"chat-markdown-pre",children:a}),table:({children:a,...i})=>t.jsx("table",{...i,className:"chat-markdown-table",children:a})},De="__fn_agent__",cs=["image/png","image/jpeg","image/gif","image/webp","text/plain","application/json","text/yaml","text/markdown","text/csv","application/xml","text/x-log"];function at(a){const i=/(^|[\s])\/([^\s]*)$/.exec(a);if(!i)return null;const l=i[1]??"",o=i[2]??"",c=i.index+l.length;return{filter:o,start:c,end:a.length}}function ds(a,i){const l=a.slice(0,i),o=/(^|[\s\n])@([\w-]*)$/.exec(l);if(!o)return null;const c=o[2]??"",y=l.length-c.length-1;return{filter:c,start:y,end:i}}function us({projectId:a,onClose:i,onCreate:l}){const[o,c]=s.useState("agent"),[y,N]=s.useState([]),[$,b]=s.useState(!0),[D,z]=s.useState(""),[p,F]=s.useState([]),[C,M]=s.useState(!0),[g,x]=s.useState(""),[T,k]=s.useState([]),[H,L]=s.useState([]);s.useEffect(()=>{let h=!1;return b(!0),ze(void 0,a).then(j=>{h||N(j)}).catch(()=>{h||N([])}).finally(()=>{h||b(!1)}),()=>{h=!0}},[a]),s.useEffect(()=>{M(!0),ns().then(h=>{F(h.models),k(h.favoriteProviders),L(h.favoriteModels)}).catch(()=>{F([]),k([]),L([])}).finally(()=>{M(!1)})},[]);const ee=s.useCallback(async h=>{const j=T,O=j.includes(h)?j.filter(V=>V!==h):[h,...j];k(O);try{await tt({favoriteProviders:O,favoriteModels:H})}catch{k(j)}},[T,H]),K=s.useCallback(async h=>{const j=H,O=j.includes(h)?j.filter(V=>V!==h):[h,...j];L(O);try{await tt({favoriteProviders:T,favoriteModels:O})}catch{L(j)}},[H,T]),_=h=>{if(h.preventDefault(),o==="agent"){if(!D)return;l({agentId:D});return}if(!g)return;const j=g.indexOf("/");if(j<=0)return;const v=g.slice(0,j),O=g.slice(j+1);l({agentId:De,modelProvider:v,modelId:O})},X=o==="agent"?!D:!g;return t.jsx("div",{className:"chat-new-dialog-backdrop",onClick:i,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"chat-new-dialog",onClick:h=>h.stopPropagation(),children:[t.jsx("h3",{children:"New Chat"}),t.jsxs("div",{className:"chat-new-dialog-mode-toggle","data-testid":"chat-new-dialog-mode-toggle",children:[t.jsx("button",{type:"button",className:`chat-new-dialog-mode-btn${o==="agent"?" chat-new-dialog-mode-btn--active":""}`,"data-testid":"chat-new-dialog-mode-agent",onClick:()=>{c("agent"),x("")},children:"Agent"}),t.jsx("button",{type:"button",className:`chat-new-dialog-mode-btn${o==="model"?" chat-new-dialog-mode-btn--active":""}`,"data-testid":"chat-new-dialog-mode-model",onClick:()=>{c("model"),z("")},children:"Model"})]}),t.jsxs("form",{onSubmit:_,children:[o==="agent"&&t.jsxs("label",{className:"chat-new-dialog-model-label",children:["Agent",$?t.jsx("div",{className:"chat-new-dialog-loading",children:"Loading agents..."}):y.length===0?t.jsx("div",{className:"chat-new-dialog-empty",children:"No agents available"}):t.jsx("div",{className:"chat-new-dialog-agent-list",children:y.map(h=>t.jsxs("button",{type:"button",className:`chat-new-dialog-agent-item${D===h.id?" chat-new-dialog-agent-item--selected":""}`,onClick:()=>z(h.id),"data-testid":`agent-option-${h.id}`,children:[t.jsx(Ee,{size:16}),t.jsx("span",{className:"chat-new-dialog-agent-name",children:h.name}),t.jsx("span",{className:"chat-new-dialog-agent-role",children:h.role})]},h.id))})]}),o==="model"&&t.jsx("div",{className:"chat-new-dialog-model-dropdown","data-testid":"chat-new-dialog-model-section",children:C?t.jsx("div",{className:"chat-new-dialog-loading",children:"Loading models..."}):t.jsx(as,{models:p,value:g,onChange:x,label:"Model",placeholder:"Select a model",favoriteProviders:T,onToggleFavorite:ee,favoriteModels:H,onToggleModelFavorite:K})}),t.jsxs("div",{className:"chat-new-dialog-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:i,children:"Cancel"}),t.jsx("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:X,children:"Create"})]})]})]})})}const hs=s.memo(function({message:i,forcePlain:l,agentName:o,showAssistantModelTag:c,activeModelTag:y,activeSessionId:N,mentionAgentsByName:$,onToggleRender:b}){const D=i.role==="assistant",z=s.useMemo(()=>{if(D)return null;const C=i.content,M=/@([\w-]+)/g,g=[];let x=0,T=M.exec(C);for(;T;){const[k,H=""]=T,L=T.index;L>x&&g.push(C.slice(x,L));const ee=H.replace(/_/g," ").toLowerCase(),K=$.get(ee);K?g.push(t.jsxs("span",{className:"chat-mention-chip",children:["@",K.name.replace(/\s+/g,"_")]},`${K.id}-${L}`)):g.push(k),x=L+k.length,T=M.exec(C)}return x<C.length&&g.push(C.slice(x)),g.length===0?C:g},[D,i.content,$]),p=s.useMemo(()=>{const C=i.attachments;if(!C||C.length===0||!N)return null;const M=`/api/chat/sessions/${encodeURIComponent(N)}/attachments/`;return t.jsx("div",{className:"chat-message-attachments",children:C.map(g=>{const x=g.mimeType.startsWith("image/"),T=g.id||g.filename,k=`${M}${encodeURIComponent(g.filename)}`;return x?t.jsx("a",{className:"chat-message-attachment-link","data-testid":"chat-message-attachment",href:k,target:"_blank",rel:"noopener noreferrer",children:t.jsx("img",{className:"chat-message-attachment",src:k,alt:g.originalName})},T):t.jsxs("a",{className:"chat-message-attachment-file","data-testid":"chat-message-attachment",href:k,target:"_blank",rel:"noopener noreferrer",children:[t.jsx(ss,{size:14}),t.jsx("span",{children:g.originalName})]},T)})})},[i.attachments,N]),F=s.useMemo(()=>D?l?t.jsx("div",{className:"chat-message-content chat-message-content--plain",children:i.content}):t.jsx("div",{className:"chat-message-content chat-message-content--markdown",children:t.jsx(it,{remarkPlugins:[rt],components:ut,children:i.content})}):null,[D,l,i.content]);return t.jsxs("div",{className:`chat-message chat-message--${i.role}`,"data-testid":`chat-message-${i.id}`,children:[D&&t.jsxs("div",{className:"chat-message-avatar",children:[t.jsx(Ee,{size:14}),t.jsx("span",{children:o}),c&&y&&t.jsx("span",{className:"chat-model-tag",children:y}),t.jsx("button",{type:"button",className:`chat-message-render-toggle${l?" chat-message-render-toggle--plain":""}`,"data-testid":"chat-message-render-toggle","aria-label":l?"Show rendered markdown":"Show plain text",onClick:()=>b(i.id),children:l?t.jsx(lt,{size:14}):t.jsx(ot,{size:14})})]}),D?F:t.jsx("div",{className:"chat-message-content",children:z}),dt(i.toolCalls),i.thinkingOutput&&t.jsxs("details",{className:"chat-message-thinking",children:[t.jsx("summary",{children:"Thinking"}),t.jsx("pre",{className:"chat-message-thinking-content",children:i.thinkingOutput})]}),p,t.jsx("div",{className:"chat-message-time",children:ct(i.createdAt)})]})});function vs({projectId:a,addToast:i}){const{activeSession:l,sessionsLoading:o,messages:c,messagesLoading:y,isStreaming:N,streamingText:$,streamingThinking:b,streamingToolCalls:D,selectSession:z,createSession:p,archiveSession:F,deleteSession:C,sendMessage:M,stopStreaming:g,pendingMessage:x,clearPendingMessage:T,searchQuery:k,setSearchQuery:H,filteredSessions:L}=rs(a),[ee,K]=s.useState(!1),[_,X]=s.useState(""),[h,j]=s.useState(null),[v,O]=s.useState(null),[V,de]=s.useState(!0),[ue,pe]=s.useState(new Map),[xe,ve]=s.useState([]),[he,ye]=s.useState(!0),[Y,se]=s.useState(!1),[le,ne]=s.useState(""),[we,me]=s.useState(0),[Se,oe]=s.useState(""),[te,ce]=s.useState(!1),[fe,be]=s.useState(0),[u,f]=s.useState(-1),[m,R]=s.useState(()=>new Set),[I,ae]=s.useState([]),[q,J]=s.useState(!1),[,B]=s.useState(!1),[G,E]=s.useState({top:0,left:0}),d=Vt({projectId:a}),U=s.useCallback(e=>{if(!e||!d.mentionActive)return;const n=e.getBoundingClientRect();E({top:n.top-260,left:n.left+8})},[d.mentionActive]),w=s.useRef(null),S=s.useRef(null),W=s.useRef(null),A=s.useRef(null),Ce=s.useRef(!1),Me=s.useRef(!1),He=s.useRef(null),Ve=s.useRef([]),Ne=s.useRef(0),ie=qt()==="mobile",{keyboardOverlap:Pe,viewportHeight:qe,viewportOffsetTop:ht,keyboardOpen:Fe}=Bt({enabled:ie&&!!l}),mt=Fe?{"--keyboard-overlap":`${Pe}px`,"--vv-offset-top":`${ht}px`,...qe!==null?{"--vv-height":`${qe}px`}:{}}:{},Z=s.useMemo(()=>{const e=le.trim().toLowerCase();return(e?xe.filter(r=>r.name.toLowerCase().includes(e)):xe).slice(0,10)},[xe,le]),ke=s.useMemo(()=>Array.from(ue.values()),[ue]),ge=s.useMemo(()=>{const e=Se.trim().toLowerCase();return e?ke.filter(n=>n.name.toLowerCase().includes(e)):ke},[ke,Se]),ft=s.useMemo(()=>{const e=new Map;for(const n of ke)e.set(n.name.toLowerCase(),n);return e},[ke]);s.useEffect(()=>{me(0)},[Z]),s.useEffect(()=>{be(0)},[Se,te]),s.useEffect(()=>()=>{S.current!==null&&window.clearTimeout(S.current)},[]),s.useEffect(()=>{const e=W.current;e&&(e.scrollTop=e.scrollHeight)},[c,$]),s.useEffect(()=>{if(Pe<=0)return;const e=W.current;e&&(e.scrollTop=e.scrollHeight)},[Pe]),s.useEffect(()=>{if(!ie||!Fe)return;const e=document.documentElement,n=document.body,r={htmlOverflow:e.style.overflow,bodyOverflow:n.style.overflow};return e.style.overflow="hidden",n.style.overflow="hidden",()=>{e.style.overflow=r.htmlOverflow,n.style.overflow=r.bodyOverflow}},[ie,Fe]),s.useEffect(()=>{const e=()=>j(null);if(h)return document.addEventListener("click",e),()=>document.removeEventListener("click",e)},[h]),s.useEffect(()=>{let e=!1;const n=a;return ze(void 0,a).then(r=>{if(e||n!==a)return;const P=new Map;for(const Q of r)P.set(Q.id,Q);pe(P)}).catch(()=>{}),()=>{e=!0}},[a]),s.useEffect(()=>{let e=!1;return ye(!0),Gt(a).then(n=>{e||ve(n)}).catch(()=>{e||ve([])}).finally(()=>{e||ye(!1)}),()=>{e=!0}},[a]),s.useEffect(()=>{Ve.current=I},[I]),s.useEffect(()=>()=>{for(const e of Ve.current)e.previewUrl&&URL.revokeObjectURL(e.previewUrl)},[]);const Te=s.useCallback(e=>{if(!e||e.length===0)return;const n=[];for(const r of Array.from(e)){if(!cs.includes(r.type))continue;const P=r.type.startsWith("image/");n.push({file:r,previewUrl:P?URL.createObjectURL(r):""})}n.length>0&&ae(r=>[...r,...n])},[]),gt=s.useCallback(e=>{ae(n=>{const r=n[e];return r?.previewUrl&&URL.revokeObjectURL(r.previewUrl),n.filter((P,Q)=>Q!==e)})},[]),pt=s.useCallback(e=>{const n=e.clipboardData?.files;if(!n||n.length===0)return;const r=Array.from(n).filter(P=>P.type.startsWith("image/"));r.length!==0&&Te(r)},[Te]),xt=s.useCallback(async e=>{try{await p(e),K(!1),ie&&de(!1)}catch{i("Failed to create chat session","error")}},[p,i,ie]),je=s.useCallback(()=>{const e=_.trim(),n=I.map(r=>r.file);!e&&n.length===0||!l||(X(""),se(!1),ne(""),ce(!1),oe(""),f(-1),M(e,n),ae(r=>{for(const P of r)P.previewUrl&&URL.revokeObjectURL(P.previewUrl);return[]}))},[_,I,l,M]),Ae=s.useCallback(()=>{if(typeof window>"u"||window.innerWidth>768)return;const e=A.current;if(!e||e.disabled)return;const n=window.scrollX,r=window.scrollY;e.focus({preventScroll:!0}),window.requestAnimationFrame(()=>{(window.scrollX!==n||window.scrollY!==r)&&window.scrollTo(n,r)})},[]),Be=s.useCallback(()=>{typeof window>"u"||window.innerWidth>768||(Ce.current=!0)},[]),Le=s.useCallback(e=>{X(n=>{const r=at(n);if(!r)return n;const P=`/skill:${e.name} `,Q=n.slice(0,r.start)+P+n.slice(r.end);return window.requestAnimationFrame(()=>{A.current&&(A.current.style.height="auto",A.current.style.height=`${Math.min(A.current.scrollHeight,120)}px`,A.current.focus())}),Q}),se(!1),ne(""),me(0)},[]),_e=s.useCallback(e=>{const n=A.current;if(!n||u<0)return;const r=n.selectionStart??Ne.current,P=n.selectionEnd??r,Q=Math.max(r,P),Ye=Math.min(u,Q),Je=`${`@${e.name.replace(/\s+/g,"_")}`} `,Rt=_.slice(0,Ye)+Je+_.slice(Q),Qe=Ye+Je.length;X(Rt),ce(!1),oe(""),be(0),f(-1),window.requestAnimationFrame(()=>{A.current&&(A.current.style.height="auto",A.current.style.height=`${Math.min(A.current.scrollHeight,120)}px`,A.current.focus(),A.current.setSelectionRange(Qe,Qe))})},[u,_]),vt=s.useCallback(e=>{if(Ne.current=e.currentTarget.selectionStart??Ne.current,d.mentionActive&&d.files.length>0){if(d.handleKeyDown(e,_),e.key==="Enter"||e.key==="Tab"){const n=d.files[d.selectedIndex];if(n){const r=d.selectFile(n,_);X(r),d.dismissMention(),B(!1)}}return}if(te&&e.key==="ArrowDown"){e.preventDefault(),ge.length>0&&be(n=>(n+1)%ge.length);return}if(te&&e.key==="ArrowUp"){e.preventDefault(),ge.length>0&&be(n=>n===0?ge.length-1:n-1);return}if(te&&e.key==="Enter"){e.preventDefault();const n=ge[fe]??ge[0];n&&_e(n);return}if(te&&e.key==="Escape"){e.preventDefault(),ce(!1),oe(""),f(-1);return}if(Y&&e.key==="ArrowDown"){e.preventDefault(),Z.length>0&&me(n=>(n+1)%Z.length);return}if(Y&&e.key==="ArrowUp"){e.preventDefault(),Z.length>0&&me(n=>n===0?Z.length-1:n-1);return}if(Y&&(e.key==="Enter"||e.key==="Tab")&&Z.length>0){e.preventDefault();const n=Z[we]??Z[0];n&&Le(n);return}if(Y&&e.key==="Escape"){e.preventDefault(),se(!1);return}e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),je())},[te,ge,fe,_e,Y,Z,we,Le,je,d,_]),$e=s.useCallback((e,n)=>{const r=ds(e,n);if(r){ce(!0),oe(r.filter),f(r.start);return}ce(!1),oe(""),f(-1)},[]),wt=s.useCallback(e=>{const n=e.target,r=n.value,P=n.selectionStart??r.length;Ne.current=P,X(r);const Q=at(r);Q?(se(!0),ne(Q.filter)):(se(!1),ne("")),$e(r,P),d.detectMention(r,P),B(d.mentionActive),d.mentionActive&&U(n),n.style.height="auto",n.style.height=`${Math.min(n.scrollHeight,120)}px`},[$e]),Oe=s.useCallback(e=>{const n=e.currentTarget,r=n.selectionStart??n.value.length;Ne.current=r,$e(n.value,r),d.detectMention(n.value,r),B(d.mentionActive),d.mentionActive&&U(n)},[$e,d,U]),St=s.useCallback(e=>{e.key!=="Escape"&&Oe(e)},[Oe]),bt=s.useCallback(()=>{if(Ce.current){window.requestAnimationFrame(()=>{Ae()});return}S.current!==null&&window.clearTimeout(S.current),S.current=window.setTimeout(()=>{se(!1),ce(!1),oe(""),f(-1),B(!1),d.dismissMention(),S.current=null},120)},[d,Ae]),kt=s.useCallback(()=>{S.current!==null&&(window.clearTimeout(S.current),S.current=null)},[]),yt=s.useCallback(async e=>{j(null);try{await F(e),i("Conversation archived","success")}catch{i("Failed to archive conversation","error")}},[F,i]),Nt=s.useCallback(async e=>{O(null),j(null);try{await C(e),i("Conversation deleted","success")}catch{i("Failed to delete conversation","error")}},[C,i]),jt=s.useCallback(e=>{z(e),ie&&de(!1)},[z,ie]),Ct=s.useCallback(()=>{z(""),de(!0)},[z]),Mt=()=>t.jsxs("div",{className:"chat-empty-state",children:[t.jsx(ts,{size:48,strokeWidth:1.5}),t.jsx("h2",{children:"Start a new conversation"}),t.jsxs("button",{className:"btn btn-primary",onClick:()=>K(!0),children:[t.jsx(Ze,{size:16}),"New Chat"]})]}),re=nt(l?.modelProvider,l?.modelId),Ge=l?.agentId===De?re??"Fusion":l?.title||ue.get(l?.agentId??"")?.name||l?.agentId||"Chat",Tt=!!(re&&re!==Ge),Ie=ue.get(l?.agentId??"")?.name||(l?.agentId===De?re??"Fusion":l?.agentId?.slice(0,30)??"Fusion"),We=!!(re&&re!==Ie),At=x.length>50?`${x.slice(0,50)}…`:x,Ke=s.useCallback(e=>{R(n=>{const r=new Set(n);return r.has(e)?r.delete(e):r.add(e),r})},[]),$t=s.useCallback((e,n=!1)=>n?t.jsx("div",{className:"chat-message-content chat-message-content--plain",children:e}):t.jsx("div",{className:"chat-message-content chat-message-content--markdown",children:t.jsx(it,{remarkPlugins:[rt],components:ut,children:e})}),[]);return t.jsxs("div",{className:"chat-view",children:[t.jsxs("div",{className:`chat-sidebar${V?"":" chat-sidebar--hidden"}`,children:[t.jsx("div",{className:"chat-sidebar-search",children:t.jsxs("div",{className:"chat-sidebar-search-wrapper",children:[t.jsx(Wt,{size:14,className:"chat-sidebar-search-icon"}),t.jsx("input",{type:"text",className:"chat-sidebar-search",placeholder:"Search conversations...",value:k,onChange:e=>H(e.target.value),"data-testid":"chat-search-input"})]})}),t.jsx("div",{className:"chat-session-list chat-sidebar-list",children:o?t.jsx("div",{style:{padding:"12px",color:"var(--text-secondary)",fontSize:"13px"},children:"Loading..."}):L.length===0?t.jsx("div",{style:{padding:"12px",color:"var(--text-secondary)",fontSize:"13px"},children:"No conversations yet"}):L.map(e=>t.jsxs("div",{className:`chat-session-item${l?.id===e.id?" chat-session-item--active":""}`,onClick:()=>jt(e.id),onContextMenu:n=>{n.preventDefault(),j({sessionId:e.id,x:n.clientX,y:n.clientY})},"data-testid":`chat-session-${e.id}`,children:[t.jsx("button",{className:"chat-session-delete-btn",onClick:n=>{n.stopPropagation(),O(e.id)},"data-testid":"chat-session-delete-btn","aria-label":"Delete conversation",children:t.jsx(Xe,{size:14})}),t.jsx("div",{className:"chat-session-title",children:e.title||"Untitled"}),t.jsx("div",{className:"chat-session-preview",children:e.lastMessagePreview||"No messages"}),t.jsxs("div",{className:"chat-session-meta",children:[t.jsx("span",{children:ue.get(e.agentId)?.name||(e.agentId===De?nt(e.modelProvider,e.modelId)??"Fusion":e.agentId.slice(0,30))}),t.jsx("span",{children:e.updatedAt?ct(e.updatedAt):""})]})]},e.id))}),t.jsx("div",{className:"chat-sidebar-footer",children:t.jsxs("button",{className:"btn btn-sm btn-primary chat-sidebar-footer-btn",onClick:()=>K(!0),"data-testid":"chat-new-btn",children:[t.jsx(Ze,{size:14}),"New Chat"]})})]}),h&&t.jsxs("div",{className:"chat-session-context-menu",style:{top:h.y,left:h.x},onClick:e=>e.stopPropagation(),children:[t.jsxs("button",{onClick:()=>yt(h.sessionId),"data-testid":"chat-context-archive",children:[t.jsx(Kt,{size:14}),"Archive"]}),t.jsxs("button",{onClick:()=>{j(null),O(h.sessionId)},"data-testid":"chat-context-delete",children:[t.jsx(Xe,{size:14}),"Delete"]})]}),v&&t.jsx("div",{className:"chat-new-dialog-backdrop",onClick:()=>O(null),children:t.jsxs("div",{className:"chat-new-dialog",onClick:e=>e.stopPropagation(),children:[t.jsx("h3",{children:"Delete Conversation?"}),t.jsx("p",{style:{fontSize:"14px",color:"var(--text-secondary)",marginBottom:"16px"},children:"This action cannot be undone. All messages in this conversation will be permanently deleted."}),t.jsxs("div",{className:"chat-new-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>O(null),children:"Cancel"}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>void Nt(v),children:"Delete"})]})]})}),t.jsxs("div",{className:"chat-thread",style:mt,children:[(l||!ie)&&t.jsxs("div",{className:"chat-thread-header",children:[ie&&l&&t.jsx("button",{className:"btn-icon",onClick:Ct,"data-testid":"chat-back-btn",children:t.jsx(Yt,{size:16})}),t.jsx(Ee,{size:16}),t.jsx("span",{className:"chat-thread-header-title",children:Ge}),Tt&&t.jsx("span",{className:"chat-model-tag",children:re})]}),t.jsxs("div",{className:"chat-messages",ref:W,children:[y?t.jsx("div",{style:{color:"var(--text-secondary)",fontSize:"13px"},children:"Loading messages..."}):c.length===0&&!l?Mt():c.length===0&&l?t.jsx("div",{style:{color:"var(--text-secondary)",fontSize:"13px"},children:"No messages yet. Start the conversation!"}):t.jsxs(t.Fragment,{children:[c.map(e=>t.jsx(hs,{message:e,forcePlain:m.has(e.id),agentName:Ie,showAssistantModelTag:We,activeModelTag:re,activeSessionId:l?.id??null,mentionAgentsByName:ft,onToggleRender:Ke},e.id)),N&&t.jsxs("div",{className:"chat-message chat-message--assistant chat-message--streaming",children:[t.jsxs("div",{className:"chat-message-avatar",children:[t.jsx(Ee,{size:14}),t.jsx("span",{children:Ie}),We&&t.jsx("span",{className:"chat-model-tag",children:re}),t.jsx("button",{type:"button",className:`chat-message-render-toggle${m.has("__streaming__")?" chat-message-render-toggle--plain":""}`,"data-testid":"chat-message-render-toggle","aria-label":m.has("__streaming__")?"Show rendered markdown":"Show plain text",onClick:()=>Ke("__streaming__"),children:m.has("__streaming__")?t.jsx(lt,{size:14}):t.jsx(ot,{size:14})})]}),$?$t($,m.has("__streaming__")):t.jsx("div",{className:"chat-message-content chat-message-content--waiting",children:b?"Thinking…":"Connecting…"}),dt(D),b&&t.jsxs("details",{className:"chat-message-thinking",children:[t.jsx("summary",{children:"Thinking"}),t.jsx("pre",{className:"chat-message-thinking-content",children:b})]}),t.jsxs("div",{className:"chat-typing-indicator",children:[t.jsx("span",{}),t.jsx("span",{}),t.jsx("span",{})]})]})]}),t.jsx("div",{ref:w})]}),l&&t.jsxs("div",{className:"chat-input-area",children:[t.jsx("input",{ref:He,type:"file",accept:"image/*,.txt,.json,.yaml,.yml,.log,.csv,.xml,.md",multiple:!0,style:{display:"none"},onChange:e=>{Te(e.target.files),e.target.value=""}}),Y&&t.jsx("div",{className:"chat-skill-menu","data-testid":"chat-skill-menu",role:"listbox","aria-label":"Skill suggestions",children:he?t.jsx("div",{className:"chat-skill-menu-empty",children:"Loading skills…"}):Z.length===0?t.jsx("div",{className:"chat-skill-menu-empty",children:le?"No skills found":"No skills available"}):Z.map((e,n)=>t.jsxs("button",{type:"button",role:"option","aria-selected":n===we,className:`chat-skill-menu-item${n===we?" chat-skill-menu-item--highlighted":""}`,onMouseDown:r=>r.preventDefault(),onMouseEnter:()=>me(n),onClick:()=>Le(e),children:[t.jsx("span",{className:"chat-skill-menu-item-name",children:e.name}),t.jsx("span",{className:"chat-skill-menu-item-description",title:e.relativePath,children:e.relativePath})]},e.id))}),I.length>0&&t.jsx("div",{className:"chat-attachment-previews","data-testid":"chat-attachment-previews",children:I.map((e,n)=>t.jsxs("div",{className:"chat-attachment-preview","data-testid":`chat-attachment-preview-${n}`,children:[e.previewUrl?t.jsx("img",{src:e.previewUrl,alt:e.file.name}):t.jsx("span",{className:"chat-attachment-preview-name",children:e.file.name}),t.jsx("button",{type:"button",className:"chat-attachment-remove",onClick:()=>gt(n),"data-testid":`chat-attachment-remove-${n}`,"aria-label":`Remove ${e.file.name}`,children:"×"})]},e.previewUrl||`${e.file.name}-${n}`))}),t.jsxs("div",{className:"chat-input-row",children:[t.jsx("button",{type:"button",className:"btn-icon chat-attach-btn","data-testid":"chat-attach-btn","aria-label":"Attach files",onClick:()=>He.current?.click(),children:t.jsx(Jt,{size:16})}),t.jsxs("div",{className:`chat-input-wrapper${q?" chat-input-wrapper--dragover":""}`,onDragOver:e=>{e.preventDefault(),J(!0)},onDragLeave:()=>J(!1),onDrop:e=>{e.preventDefault(),J(!1),Te(e.dataTransfer.files)},children:[t.jsx("textarea",{ref:A,className:"chat-input-textarea",placeholder:"Type a message...",value:_,onChange:wt,onKeyDown:vt,onKeyUp:St,onClick:Oe,onBlur:bt,onFocus:kt,onPaste:pt,onTouchStart:e=>{typeof window>"u"||window.innerWidth>768||document.activeElement!==e.currentTarget&&(e.preventDefault(),e.currentTarget.focus({preventScroll:!0}))},rows:1,"data-testid":"chat-input"}),t.jsx(Qt,{agents:ke,filter:Se,highlightedIndex:fe,visible:te,onSelect:_e,position:"below"}),t.jsx(Xt,{visible:d.mentionActive&&!te,position:G,files:d.files,selectedIndex:d.selectedIndex,onSelect:e=>{const n=d.selectFile(e,_);X(n),d.dismissMention(),B(!1),A.current?.focus()},loading:d.loading}),x&&t.jsxs("div",{className:"chat-pending-message","data-testid":"chat-pending-indicator",children:[t.jsx("span",{children:`Queued: ${At}`}),t.jsx("button",{type:"button",className:"chat-pending-message-dismiss","aria-label":"Dismiss queued message","data-testid":"chat-pending-dismiss",onClick:T,children:"×"})]})]}),N?t.jsx("button",{className:"chat-input-stop",onClick:g,"aria-label":"Stop generation","data-testid":"chat-stop-btn",children:t.jsx(Zt,{size:14})}):t.jsx("button",{type:"button",className:"chat-input-send",onPointerDown:e=>{typeof window>"u"||window.innerWidth>768||(e.preventDefault(),e.pointerType&&e.pointerType!=="mouse"&&(Me.current=!0,Be(),Ae(),je(),window.setTimeout(()=>{Ce.current=!1},1500)))},onTouchStart:e=>{typeof window>"u"||window.innerWidth>768||(e.preventDefault(),Me.current=!0,Be(),Ae(),je(),window.setTimeout(()=>{Ce.current=!1},1500))},onMouseDown:e=>{typeof window>"u"||window.innerWidth>768||e.preventDefault()},onClick:()=>{if(Me.current){Me.current=!1;return}je()},disabled:!_.trim()&&I.length===0,"data-testid":"chat-send-btn",children:t.jsx(es,{size:16})})]})]})]}),ee&&t.jsx(us,{projectId:a,onClose:()=>K(!1),onCreate:xt})]})}export{vs as ChatView};
@@ -1 +1 @@
1
- import{r,j as t}from"./vendor-react-K0fH_qHe.js";import{bI as De,bJ as de,bK as Ze,bL as ue,s as Ue,bM as ge,bN as we,bO as xe,bP as ye,bQ as et,bR as ae,bS as tt,bT as rt,bU as st,bV as nt,bW as at,bX as ie,L as ee,S as it,bY as lt,bZ as ct,$ as ot,b_ as Me,T as Ae,b$ as dt,W as ut,b1 as vt,c0 as mt,ac as ft,aq as pt,R as ht}from"./index-D7gT6mCr.js";import"./vendor-xterm-DzcZoU0P.js";const ve=500,bt=3e3;function B(e){return e instanceof Error?e.message:String(e)}function Pe(e){return e.length<=ve?e:e.slice(-ve)}function le(e,i){return Pe([...e,i])}function I(e){try{return JSON.parse(e)}catch{return null}}function Y(e){const i=e.text??"";return e.stream==="stderr"?`[stderr] ${i}`:i}function gt(e){return e?.previewUrl??null}async function Se(e){return tt(e)}async function Ne(e,i){return rt(e,i)}async function wt(e){return st(e)}async function xt(e){return nt(e)}async function je(e){return at(e)}function V(e){try{return e()}catch{return null}}function ce(){return typeof V(()=>de)=="function"&&typeof V(()=>De)=="function"}function q(e){return{config:{id:e.id??"default",name:e.name??"Dev Server",command:e.command??"",cwd:e.cwd??"."},status:e.status,runtime:e.pid?{pid:e.pid,startedAt:e.startedAt??new Date().toISOString(),exitCode:e.exitCode??void 0,previewUrl:e.previewUrl}:void 0,previewUrl:e.previewUrl??e.detectedUrl??e.manualUrl??void 0,logHistory:(e.logs??[]).map(i=>({timestamp:new Date().toISOString(),stream:i.startsWith("[stderr]")?"stderr":"stdout",text:i.replace(/^\[stderr\]\s*/,"")}))}}function yt(e){const[i,o]=r.useState(null),[b,y]=r.useState([]),[w,f]=r.useState([]),[k,U]=r.useState([]),[C,P]=r.useState(!0),[S,u]=r.useState(null),n=r.useRef(0),[d,M]=r.useState(null),R=r.useCallback(a=>{if(o(a),a?.logHistory){const s=a.logHistory.slice(-ve).map(Y);f(s)}},[]),A=r.useCallback(async()=>{const a=n.current;try{if(ce())if(d){const s=await De(d,e);if(n.current!==a)return;R(s)}else{const s=await de(e);if(n.current!==a)return;y(s),s.length>0&&(M(s[0].config.id),R(s[0]))}else{const s=await Se(e);if(n.current!==a)return;const c=q(s);y([c]),R(c)}u(null)}catch(s){if(n.current!==a)return;u(B(s))}},[R,e,d]);r.useEffect(()=>{n.current+=1;const a=n.current;o(null),y([]),f([]),U([]),P(!0),u(null),M(null),(async()=>{try{const[c,l]=await Promise.allSettled([ce()?de(e):Se(e).then(N=>[q(N)]),typeof V(()=>ae)=="function"?ae(e):je(e).then(N=>N.map(g=>({name:g.name,command:g.command,cwd:g.cwd,scriptName:g.scriptName,packagePath:g.packagePath})))]);if(n.current!==a)return;let v=null;if(c.status==="fulfilled"){const N=c.value;if(y(N),N.length>0){const g=N[0];ce()&&M(g.config.id),R(g)}}else v=B(c.reason);l.status==="fulfilled"&&U(l.value),v&&u(v)}catch(c){if(n.current!==a)return;u(B(c))}finally{n.current===a&&P(!1)}})()},[R,e]),r.useEffect(()=>{const a=d?Ze(d,e):typeof V(()=>ue)=="function"?ue(e):null;if(!a)return;const s=n.current,c=Ue(a,{events:{history:l=>{if(n.current!==s)return;const v=I(l.data);if(v?.lines){const N=v.lines.map(Y);f(Pe(N))}},log:l=>{if(n.current!==s)return;const v=I(l.data);if(v){const N=typeof v.line=="string"?v.line:Y(v);f(g=>le(g,N))}},"dev-server:log":l=>{if(n.current!==s)return;const v=I(l.data);if(v){const N=typeof v.line=="string"?v.line:Y(v);f(g=>le(g,N))}},"dev-server:output":l=>{if(n.current!==s)return;const v=I(l.data);v?.line&&f(N=>le(N,v.line))},status:l=>{if(n.current!==s)return;const v=I(l.data),N=v?.status;N&&o(g=>g&&{...g,status:N,runtime:v.pid?{...g.runtime??{startedAt:new Date().toISOString()},pid:v.pid}:g.runtime})},"dev-server:status":l=>{if(n.current!==s)return;const v=I(l.data);if(v?.status){const N=q(v);o(N),y([N])}},stopped:()=>{n.current},failed:()=>{n.current}},onReconnect:()=>{n.current===s&&A()},onError:()=>{n.current===s&&u(l=>l??"Lost log stream connection.")}});return()=>{c()}},[e,A,d]),r.useEffect(()=>{if(i?.status!=="running"&&i?.status!=="starting")return;const a=setInterval(()=>{A()},bt);return()=>{clearInterval(a)}},[A,i?.status]);const _=r.useCallback(async(a,s)=>{n.current+=1;const c=n.current;try{let l;if(d&&typeof V(()=>ge)=="function")l=await ge(d,e);else{const v=await Ne({command:a,cwd:s},e);l=q(v)}if(n.current!==c)return;o(l),u(null)}catch(l){if(n.current!==c)return;throw u(B(l)),l}},[e,d]),D=r.useCallback(async()=>{n.current+=1;const a=n.current;try{let s;if(d&&typeof V(()=>we)=="function")s=await we(d,e);else{const c=await wt(e);s=q(c)}if(n.current!==a)return;o(s),u(null)}catch(s){if(n.current!==a)return;throw u(B(s)),s}},[e,d]),j=r.useCallback(async()=>{n.current+=1;const a=n.current;try{let s;if(d&&typeof V(()=>xe)=="function")s=await xe(d,e);else{const c=await xt(e);s=q(c)}if(n.current!==a)return;o(s),u(null)}catch(s){if(n.current!==a)return;throw u(B(s)),s}},[e,d]),T=r.useCallback(async a=>{n.current+=1;const s=n.current;try{let c;if(d&&typeof V(()=>ye)=="function")c=await ye(d,a,e);else{const l=await et({url:a},e);c={url:l.manualUrl??l.previewUrl??l.detectedUrl??null,source:l.manualUrl?"manual":"auto"}}if(n.current!==s)return;o(l=>l?{...l,previewUrl:c.url??void 0}:null),u(null)}catch(c){if(n.current!==s)return;throw u(B(c)),c}},[e,d]),h=r.useCallback(async()=>{n.current+=1;const a=n.current;try{let s;try{s=await ae(e)}catch{s=(await je(e)).map(l=>({name:l.name,command:l.command,cwd:l.cwd,scriptName:l.scriptName,packagePath:l.packagePath}))}if(n.current!==a)return;U(s),u(null)}catch(s){if(n.current!==a)return;throw u(B(s)),s}},[e]),p=r.useCallback(async(a,s)=>{if(typeof a!="string"&&!d)try{const v=a,N=await Ne({command:v.command,cwd:v.cwd,scriptName:v.scriptName,packagePath:v.packagePath??v.cwd},e),g=q(N);o(g),y([g]),u(null);return}catch(v){throw u(B(v)),v}const c=typeof a=="string"?a:a.command,l=typeof a=="string"?s:a.cwd;await _(c,l)},[e,_,d]),E=r.useCallback(async()=>{await D()},[D]),L=r.useCallback(async()=>{await j()},[j]),z=r.useCallback(async a=>{await T(a)},[T]),F=r.useCallback(async()=>{await h()},[h]),O=r.useCallback(async()=>{await A()},[A]),H=gt(i),x=i?{...i,pid:i.runtime?.pid}:null;return{session:i,sessions:b,logs:w,detectedCommands:k,previewUrl:H,isLoading:C,error:S,startServer:_,stopServer:D,restartServer:j,setPreviewUrl:T,detectCommands:h,refresh:A,candidates:k,serverState:x,loading:C,start:p,stop:E,restart:L,setManualUrl:z,detect:F,refreshStatus:O}}const ke=500,Ce=100;function Te(e){return e.length>ke?e.slice(-ke):e}function ze(e){return e==="stderr"?"stderr":"stdout"}function K(e){try{return JSON.parse(e.data)}catch{return null}}function Z(e,i){return{id:typeof e.id=="number"&&Number.isFinite(e.id)?e.id:i,text:typeof e.text=="string"?e.text:"",stream:ze(e.stream),timestamp:typeof e.timestamp=="string"?e.timestamp:""}}function St(e,i){return{id:i,text:e,stream:"stdout",timestamp:""}}function oe(e,i){if(i.length===0)return e;const o=[...e],b=new Set(e.map(y=>y.id));for(const y of i)b.has(y.id)||(b.add(y.id),o.push(y));return o.sort((y,w)=>y.id-w.id),Te(o)}function Nt(e,i){const[o,b]=r.useState([]),[y,w]=r.useState(!1),[f,k]=r.useState(!1),[U,C]=r.useState(!1),[P,S]=r.useState(null),u=r.useRef(null),n=r.useRef(!1),d=r.useRef(0),M=r.useRef(0),R=r.useRef(e),A=r.useRef(i),_=r.useRef(0),D=r.useRef(1);(R.current!==e||A.current!==i)&&(R.current=e,A.current=i,d.current++,n.current=!0,_.current=0,D.current=1,b([]),w(!1),k(!1),C(!1),S(null),u.current&&(u.current(),u.current=null)),r.useEffect(()=>{if(!i){u.current&&(u.current(),u.current=null);return}const E=d.current,L=++M.current;n.current=!1,w(!0);const z=(x,a)=>{const s=Te(x);b(s),S(a),C(a!==null?a>s.length:!1);const c=s.length>0?s[s.length-1].id:0;_.current=c,D.current=c+1},F=x=>{if(n.current||d.current!==E||!x||typeof x!="object")return;const a=x.lines;if(!Array.isArray(a))return;if(a.length>0&&typeof a[0]=="string"){const c=a.filter(l=>typeof l=="string").map((l,v)=>St(l,v+1));z(c,c.length);return}const s=a.filter(c=>!!c&&typeof c=="object").map((c,l)=>Z(c,l+1));z(s,s.length)},O=x=>{if(n.current||d.current!==E)return;const a=typeof x.text=="string"?x.text:typeof x.line=="string"?x.line:null;if(!a)return;const s=D.current,c=typeof x.id=="number"&&Number.isFinite(x.id)?x.id:s,l={id:c,text:a,stream:ze(x.stream),timestamp:typeof x.timestamp=="string"?x.timestamp:""};_.current=Math.max(_.current,c),D.current=Math.max(D.current,c+1),b(v=>oe(v,[l])),S(v=>v===null?v:Math.max(v+1,l.id))};async function H(){try{const a=await ie({maxLines:Ce},e);if(n.current||d.current!==E||M.current!==L)return;const s=a.lines.map((c,l)=>Z(c,l+1));z(s,a.totalLines)}catch{if(n.current||d.current!==E||M.current!==L)return;z([],null)}finally{!n.current&&d.current===E&&M.current===L&&w(!1)}const x=ue(e);u.current=Ue(x,{events:{"dev-server:log":a=>{const s=K(a);s&&O(s)},log:a=>{const s=K(a);s&&O(s)},history:a=>{const s=K(a);F(s)},"dev-server:history":a=>{const s=K(a);F(s)}},onReconnect:()=>{n.current||d.current!==E||ie({lastEventId:_.current,maxLines:50},e).then(a=>{if(n.current||d.current!==E)return;const s=a.lines.map((c,l)=>Z(c,D.current+l));if(s.length>0){const c=s[s.length-1].id;_.current=Math.max(_.current,c),D.current=Math.max(D.current,c+1)}b(c=>oe(c,s)),S(a.totalLines)}).catch(()=>{})}})}return H(),()=>{n.current=!0,u.current&&(u.current(),u.current=null)}},[i,e]);const T=r.useCallback(async()=>{if(!i||f)return;const E=d.current,L=o.length;k(!0);try{const z=await ie({maxLines:Ce,offset:L},e);if(n.current||d.current!==E)return;const F=z.lines.map((O,H)=>Z(O,H+1));b(O=>oe(F,O)),C(z.totalLines>L+F.length),S(z.totalLines)}catch{}finally{k(!1)}},[i,o.length,f,e]),h=r.useCallback(()=>{b([])},[]),p=u.current!==null&&!y&&!n.current;return{entries:o,loading:y,loadingMore:f,hasMore:U,total:P,loadMore:T,clear:h,logs:o,isStreaming:p,clearLogs:h}}const jt="This preview appears to block iframe embedding. Open it in a new tab instead.",kt="The preview URL could not be loaded. Verify the server is running and the URL is correct.",Ct="Preview is taking longer than expected and may block iframe embedding.";function Et(e){return e==="blocked"?jt:e==="error"?kt:null}function Lt(e,i={}){const{loadTimeoutMs:o=1e4,detectionMethod:b=null}=i,y=r.useRef(null),w=r.useRef(null),[f,k]=r.useState("unknown"),[U,C]=r.useState(null),[P]=r.useState(b),S=r.useCallback(()=>{w.current!==null&&(window.clearTimeout(w.current),w.current=null)},[]),u=r.useCallback(j=>{k(j),C(Et(j))},[]),n=r.useCallback(()=>{k("blocked"),C(Ct)},[]);r.useEffect(()=>{if(S(),!e){k("unknown"),C(null);return}k("unknown"),C(null);let j=!1;return queueMicrotask(()=>{j||(k("loading"),C(null))}),()=>{j=!0,S()}},[S,e]),r.useEffect(()=>{if(f!=="loading"){S();return}const j=setTimeout(()=>{w.current=null,n()},o);return w.current=j,()=>{clearTimeout(j),w.current===j&&(w.current=null)}},[S,f,o,n]);const d=r.useCallback(()=>{const j=y.current;if(!j){u("embedded");return}try{if(j.contentWindow?.location?.href==="about:blank"&&j.src!=="about:blank"){u("blocked");return}}catch{}u("embedded")},[u]),M=r.useCallback(()=>{u("error")},[u]);r.useEffect(()=>{if(S(),!e){k("unknown"),C(null);return}k("unknown"),C(null)},[S]);const R=r.useCallback(()=>{S(),k("unknown"),C(null)},[S]),A=R,_=r.useMemo(()=>f==="embedded",[f]),D=r.useMemo(()=>f==="blocked"||f==="error",[f]);return{embedStatus:f,isEmbedded:_,isBlocked:D,blockReason:U,detectionMethod:P,iframeRef:y,resetEmbedStatus:R,setEmbedStatus:u,retry:A,embedContext:U,handleIframeLoad:d,handleIframeError:M}}const Rt=/\x1b\[[0-9;]*m/g;function me(e){return e.replace(Rt,"")}function _t(e){if(!e)return"";const i=new Date(e);return Number.isNaN(i.getTime())?"":i.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1})}function Dt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ut(e){if(e.stream==="stderr")return"error";const i=me(e.text).toLowerCase();return/\b(warn|warning)\b/.test(i)?"warn":/\b(error|fatal)\b/.test(i)?"error":"info"}function Mt(e,i){if(!i)return e;const o=new RegExp(`(${Dt(i)})`,"ig"),b=e.split(o),y=i.toLowerCase();return t.jsx(t.Fragment,{children:b.map((w,f)=>w.toLowerCase()===y?t.jsx("mark",{children:w},`${w}-${f}`):t.jsx("span",{children:w},`${w}-${f}`))})}function At({entries:e,loading:i,loadingMore:o,hasMore:b,total:y,onLoadMore:w,isRunning:f}){const k=r.useRef(null),U=r.useRef(e.length),C=r.useRef(f),[P,S]=r.useState(!1),[u,n]=r.useState(!1),[d,M]=r.useState(""),[R,A]=r.useState("all"),_=r.useMemo(()=>R==="all"?e:e.filter(p=>Ut(p)===R),[e,R]),D=r.useMemo(()=>{const p=d.trim().toLowerCase();return p?_.filter(E=>me(E.text).toLowerCase().includes(p)):_},[_,d]),j=D.length,T=r.useCallback(()=>{const p=k.current;p&&(p.scrollTop=p.scrollHeight,n(!1))},[]);r.useEffect(()=>{const p=C.current,E=U.current,L=e.length>E;f&&(!p||!u&&L)&&T(),C.current=f,U.current=e.length},[e.length,f,u,T]);const h=r.useCallback(()=>{const p=k.current;if(!p)return;const L=p.scrollTop+p.clientHeight>=p.scrollHeight-50;n(!L)},[]);return r.useEffect(()=>{i||e.length===0||!u&&f&&T()},[e,f,u,i,T]),i&&e.length===0?t.jsx("section",{className:"devserver-log-viewer","data-testid":"devserver-log-viewer",children:t.jsxs("div",{className:"devserver-log-viewer__loading","data-testid":"devserver-log-loading",children:[t.jsx(ee,{size:16,className:"devserver-log-viewer__spinner"}),t.jsx("span",{children:"Loading logs…"})]})}):t.jsxs("section",{className:`devserver-log-viewer${P?" devserver-log-viewer--fullscreen":""}`,"data-testid":"devserver-log-viewer",children:[t.jsxs("header",{className:"devserver-log-viewer__toolbar",children:[t.jsxs("div",{className:"devserver-log-viewer__toolbar-meta",children:[t.jsx("span",{className:"devserver-log-viewer__title",children:"Logs"}),t.jsxs("span",{className:"devserver-log-viewer__count","data-testid":"devserver-log-count",children:[y!==null?`${e.length}/${y}`:`${e.length}`," lines"]})]}),t.jsxs("div",{className:"devserver-log-viewer__toolbar-actions",children:[t.jsxs("label",{className:"devserver-log-viewer__severity",htmlFor:"devserver-log-severity-filter",children:[t.jsx("span",{className:"visually-hidden",children:"Filter logs by severity"}),t.jsxs("select",{id:"devserver-log-severity-filter",className:"select devserver-log-viewer__severity-select",value:R,onChange:p=>A(p.target.value),"data-testid":"devserver-log-severity-filter","aria-label":"Filter logs by severity",children:[t.jsx("option",{value:"all",children:"All severities"}),t.jsx("option",{value:"info",children:"Info"}),t.jsx("option",{value:"warn",children:"Warn"}),t.jsx("option",{value:"error",children:"Error"})]})]}),t.jsxs("label",{className:"devserver-log-viewer__search",htmlFor:"devserver-log-search",children:[t.jsx("span",{className:"visually-hidden",children:"Search logs"}),t.jsx(it,{size:14}),t.jsx("input",{id:"devserver-log-search",className:"input devserver-log-viewer__search-input",type:"text",value:d,onChange:p=>M(p.target.value),placeholder:"Search logs","data-testid":"devserver-log-search-input","aria-label":"Search logs"})]}),d.trim().length>0&&t.jsxs("span",{className:"devserver-log-viewer__matches","data-testid":"devserver-log-match-count",children:[j," match",j===1?"":"es"]}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon",onClick:()=>S(p=>!p),"data-testid":"devserver-log-fullscreen-toggle","aria-label":P?"Exit fullscreen logs":"Enter fullscreen logs",children:P?t.jsx(lt,{size:14}):t.jsx(ct,{size:14})})]})]}),t.jsxs("div",{className:"devserver-log-viewer__body",children:[b&&t.jsx("div",{className:"devserver-log-viewer__load-more","data-testid":"devserver-log-load-more",children:t.jsx("button",{type:"button",className:"btn btn-sm touch-target",onClick:w,disabled:o,"data-testid":"devserver-log-load-more-button",children:o?t.jsxs(t.Fragment,{children:[t.jsx(ee,{size:14,className:"devserver-log-viewer__spinner"}),"Loading older logs…"]}):"Load older logs"})}),t.jsxs("div",{ref:k,className:"devserver-log-viewer__content",onScroll:h,"data-testid":"devserver-log-content",children:[!i&&D.length===0&&t.jsx("p",{className:"devserver-log-viewer__empty","data-testid":"devserver-log-empty",children:e.length===0?"No logs yet. Start the dev server to see output.":_.length===0?"No log lines match the selected severity.":"No log lines match your search."}),D.map(p=>{const E=me(p.text),L=_t(p.timestamp);return t.jsxs("div",{className:"devserver-log-line",children:[L&&t.jsx("span",{className:"devserver-log-timestamp","data-testid":"devserver-log-timestamp",children:L}),p.stream==="stderr"&&t.jsx("span",{className:"devserver-log-stream-badge","data-testid":"devserver-log-stderr-badge",children:"ERR"}),t.jsx("span",{className:"devserver-log-text",children:Mt(E,d.trim())})]},p.id)})]}),u&&f&&t.jsxs("button",{type:"button",className:"btn btn-sm devserver-log-viewer__new-logs-button",onClick:T,"data-testid":"devserver-log-jump-button",children:[t.jsx(ot,{size:14}),"New logs"]})]})]})}const Pt="devserver-preview-iframe";function Tt({url:e,embedStatus:i,onEmbedStatusChange:o,iframeRef:b,blockReason:y,onRetry:w,className:f=Pt,embedContext:k}){const U=y??k??null,[C,P]=r.useState(0);r.useEffect(()=>{!e||i!=="unknown"||(P(d=>d+1),o("loading"))},[i,o,e]);const S=r.useCallback(()=>{const d=b.current;if(!d){o("embedded");return}try{if(d.contentWindow?.location?.href==="about:blank"&&d.src!=="about:blank"){o("blocked");return}}catch{}o("embedded")},[b,o]),u=r.useCallback(d=>{d.stopPropagation(),o("error")},[o]),n=r.useCallback(()=>{e&&window.open(e,"_blank","noopener,noreferrer")},[e]);return e?t.jsxs("div",{className:"devserver-preview-iframe-shell",children:[t.jsx("iframe",{src:e,ref:b,sandbox:"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox",className:f,title:"Dev server preview",onLoad:S,onError:u,onErrorCapture:u,"data-testid":"devserver-preview-iframe"},`${e}-${C}`),i==="loading"&&t.jsxs("div",{className:"devserver-preview-overlay","data-testid":"devserver-preview-loading",children:[t.jsx(ee,{size:16,className:"dev-server-spin"}),t.jsx("span",{children:"Loading preview..."})]}),i==="blocked"&&t.jsxs("div",{className:"devserver-preview-blocked-panel",role:"alert","data-testid":"devserver-preview-blocked-panel",children:[t.jsx(Me,{className:"devserver-preview-blocked-icon","aria-hidden":"true"}),t.jsxs("div",{children:[t.jsx("p",{className:"devserver-preview-blocked-title",children:"Preview cannot be embedded"}),U&&t.jsx("p",{className:"devserver-preview-blocked-context",children:U})]}),t.jsx("p",{className:"devserver-preview-blocked-description",children:"You can view the preview in a separate browser tab."}),t.jsxs("div",{className:"devserver-preview-blocked-actions",children:[t.jsx("button",{type:"button",className:"btn btn-primary",onClick:n,children:"Open in new tab"}),w&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:w,children:"Retry"})]})]}),i==="error"&&t.jsxs("div",{className:"devserver-preview-error-panel",role:"alert","data-testid":"devserver-preview-error-panel",children:[t.jsx(Ae,{className:"devserver-preview-blocked-icon","aria-hidden":"true"}),t.jsxs("div",{children:[t.jsx("p",{className:"devserver-preview-blocked-title",children:"Unable to load preview"}),U&&t.jsx("p",{className:"devserver-preview-blocked-context",children:U})]}),t.jsx("p",{className:"devserver-preview-blocked-description",children:"You can view the preview in a separate browser tab."}),t.jsxs("div",{className:"devserver-preview-blocked-actions",children:[t.jsx("button",{type:"button",className:"btn btn-primary",onClick:n,children:"Open in new tab"}),w&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:w,children:"Retry"})]})]})]}):null}const Ee={stopped:{className:"dev-server-status-badge--stopped",label:"Stopped"},starting:{className:"dev-server-status-badge--starting",label:"Starting..."},running:{className:"dev-server-status-badge--running",label:"Running"},stopping:{className:"dev-server-status-badge--starting",label:"Stopping..."},failed:{className:"dev-server-status-badge--failed",label:"Failed"}};function Le(e){return e instanceof Error?e.message:String(e)}function $e(e){return e==="."?"root":e}function Re(e){return e?e==="root"?".":e:null}function _e(e,i,o){return!i||e.scriptName!==i?!1:o?$e(e.cwd)===o:!0}function zt(e){return e.cwd==="."?"root":e.cwd}function $t(e){return e.length<=60?e:`${e.slice(0,60)}…`}function Ht({addToast:e,projectId:i}){const{session:o,detectedCommands:b,previewUrl:y,isLoading:w,error:f,startServer:k,stopServer:U,restartServer:C,setPreviewUrl:P,detectCommands:S,refresh:u}=yt(i),n=o?.status??"stopped",d=n==="running"||n==="starting",M=Ee[n]??Ee.stopped,{entries:R,loading:A,loadingMore:_,hasMore:D,total:j,loadMore:T}=Nt(i,!!i),h=y,p=o?.config?.cwd??null,[E,L]=r.useState(!0),[z,F]=r.useState(""),[O,H]=r.useState(""),[x,a]=r.useState(null),[s,c]=r.useState(null),[l,v]=r.useState("embedded"),N=l==="embedded"?h:null,{embedStatus:g,setEmbedStatus:Fe,resetEmbedStatus:G,iframeRef:X,isEmbedded:Oe,isBlocked:te,blockReason:re,retry:fe}=Lt(N),[pe,W]=r.useState(!1),he=r.useRef(g);r.useEffect(()=>{const m=he.current!==g;te&&m&&W(!0),g==="embedded"&&W(!1),he.current=g},[g,te]),r.useEffect(()=>{W(!1)},[h]);const J=r.useMemo(()=>{if(!x)return null;const m=Re(p);return b.find($=>!($.scriptName!==x||m&&$.cwd!==m||o?.config?.command&&$.command!==o.config.command))??b.find($=>_e($,x,p))??null},[b,o?.config?.command,x,p]);r.useEffect(()=>{typeof S=="function"&&S().catch(m=>{e(Le(m),"error")})},[e,S]),r.useEffect(()=>{if(x){L(!1);return}L(!0)},[x]),r.useEffect(()=>{if(o?.status==="running"||o?.status==="starting"){o.config?.command?.trim().length>0&&F(o.config.command);return}if(J){F(J.command);return}b.length>0&&F(m=>m.trim().length>0?m:b[0]?.command??"")},[b,J,o?.config?.command,o?.status]),r.useEffect(()=>{H(h??"")},[h]);const se=r.useCallback(()=>{h&&window.open(h,"_blank","noopener,noreferrer")},[h]),be=r.useCallback(()=>{W(!1),fe()},[fe]),Be=r.useCallback(()=>{try{const m=X.current;if(m?.contentWindow){m.contentWindow.location.reload(),W(!1),G();return}}catch{}if(!(!h||!X.current))try{const m=new URL(h);m.searchParams.set("_t",Date.now().toString()),X.current.src=m.toString(),W(!1),G()}catch{X.current.src=h,W(!1),G()}},[h,X,G]),Q=r.useCallback(async(m,$,ne)=>{c(m);try{await $(),e(ne,"success")}catch(Ke){e(Le(Ke),"error")}finally{c(null)}},[e]),He=r.useCallback(m=>{a(m.scriptName),L(!1),F(m.command),e(`Selected ${m.scriptName} script.`,"success")},[e]),Ve=r.useCallback(()=>{a(null),L(!0),e("Cleared selected dev server script.","success")},[e]),We=()=>{const m=z.trim();if(m.length===0){e("Enter a command before starting the dev server.","warning");return}const $=Re(p)??".",ne=J?.cwd??$;Q("start",()=>k(m,ne),"Dev server started.")},qe=()=>{Q("stop",U,"Dev server stopped.")},Xe=()=>{Q("restart",C,"Dev server restarted.")},Ie=()=>{const m=O.trim(),$=m.length>0?m:null;Q("preview",()=>P($),$?"Preview URL updated.":"Preview URL override cleared.")},Ge=r.useCallback(()=>{f&&u()},[f,u]),Je=n==="starting"||n==="running"||s!==null,Qe=n==="stopped"||s!==null,Ye=n==="stopped"||n==="starting"||s!==null;return t.jsxs("div",{className:"dev-server-view","data-testid":"dev-server-view",children:[t.jsxs("section",{className:"dev-server-header","aria-label":"Dev server controls header",children:[t.jsxs("div",{className:"dev-server-header-title",children:[t.jsx(dt,{size:16}),t.jsx("h2",{children:"Dev Server"}),t.jsx("span",{className:`dev-server-status-badge ${M.className}`,"data-testid":"dev-server-status-badge",children:M.label})]}),t.jsxs("div",{className:"dev-server-header-actions",children:[t.jsxs("button",{type:"button",className:"btn btn-primary btn-sm",onClick:We,disabled:Je,"data-testid":"dev-server-start-button",children:[t.jsx(ut,{size:14}),t.jsx("span",{children:s==="start"?"Starting...":"Start"})]}),t.jsxs("button",{type:"button",className:"btn btn-danger btn-sm",onClick:qe,disabled:Qe,"data-testid":"dev-server-stop-button",children:[t.jsx(vt,{size:14}),t.jsx("span",{children:s==="stop"?"Stopping...":"Stop"})]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:Xe,disabled:Ye,"data-testid":"dev-server-restart-button",children:[t.jsx(mt,{size:14}),t.jsx("span",{children:s==="restart"?"Restarting...":"Restart"})]})]})]}),t.jsxs("section",{className:"dev-server-panel dev-server-config","aria-label":"Dev server configuration",children:[t.jsxs("div",{className:"dev-server-section-header",children:[t.jsx("h3",{children:"Configuration"}),w&&t.jsx("span",{className:"dev-server-muted",children:"Loading..."})]}),w&&!o&&b.length===0&&t.jsxs("div",{className:"dev-server-loading-state","data-testid":"dev-server-loading-state",children:[t.jsx(ee,{size:16,className:"dev-server-spin"}),t.jsx("span",{children:"Loading dev server configuration..."})]}),f&&t.jsxs("div",{className:"dev-server-error-box",role:"alert","data-testid":"dev-server-error-box",children:[t.jsx("p",{children:f}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:Ge,children:"Retry"})]}),t.jsxs("div",{className:"dev-server-section",children:[t.jsx("h3",{children:"Script Selection"}),x&&t.jsxs("div",{className:"dev-server-selected","data-testid":"dev-server-selected-summary",children:[t.jsx("span",{className:"dev-server-candidate-name",children:x}),t.jsx("span",{className:"dev-server-candidate-source",children:p??"root"}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>L(!0),"data-testid":"dev-server-change-selection",children:"Change"}),t.jsx("button",{type:"button",className:"btn btn-danger btn-sm",onClick:Ve,"data-testid":"dev-server-clear-selection",children:"Clear"})]}),E&&b.length===0&&t.jsxs("p",{className:"dev-server-empty-state","data-testid":"dev-server-empty-candidates",children:["No dev server scripts detected. Check that your project has a ",t.jsx("code",{children:"package.json"})," with a ",t.jsx("code",{children:"dev"}),", ",t.jsx("code",{children:"start"}),", or similar script."]}),E&&b.length>0&&t.jsx("div",{className:"dev-server-candidates","data-testid":"dev-server-candidates",children:b.map(m=>{const $=_e(m,x,p);return t.jsxs("button",{type:"button",className:`dev-server-candidate ${$?"dev-server-candidate--selected":""}`,onClick:()=>He(m),"data-testid":`dev-server-candidate-${m.scriptName}-${$e(m.cwd)}`,children:[t.jsx("span",{className:"dev-server-candidate-name",children:m.scriptName}),t.jsx("span",{className:"dev-server-candidate-command",children:$t(m.command)}),t.jsx("span",{className:"dev-server-candidate-source",children:zt(m)})]},`${m.cwd}::${m.scriptName}::${m.command}`)})})]}),t.jsxs("div",{className:"dev-server-field-group",children:[t.jsx("label",{htmlFor:"dev-server-command",className:"dev-server-label",children:"Command"}),t.jsx("input",{id:"dev-server-command",className:"input",value:z,onChange:m=>F(m.target.value),placeholder:"pnpm dev","data-testid":"dev-server-command-input",readOnly:n==="running"||n==="starting"})]}),(n==="running"||n==="starting")&&o&&t.jsxs("div",{className:"dev-server-current-command","data-testid":"dev-server-current-command",children:[t.jsx("span",{className:"dev-server-label",children:"Running command"}),t.jsx("code",{children:o.config?.command??z})]}),t.jsxs("div",{className:"dev-server-preview-override",children:[t.jsx("label",{htmlFor:"dev-server-preview-input",className:"dev-server-label",children:"Preview URL Override"}),t.jsx("input",{id:"dev-server-preview-input",className:"input",type:"url",value:O,onChange:m=>H(m.target.value),placeholder:"http://localhost:3000","data-testid":"dev-server-preview-input"}),t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:Ie,disabled:s==="preview","data-testid":"dev-server-set-preview",children:"Save"})]}),h&&t.jsxs("p",{className:"dev-server-preview-hint",children:["Auto-detected: ",h]})]}),t.jsx("div",{className:"dev-server-content",children:t.jsxs("section",{className:"dev-server-panel dev-server-logs-panel","data-testid":"dev-server-logs-panel","aria-label":"Dev server logs",children:[t.jsxs("div",{className:"dev-server-section-header",children:[t.jsx("h3",{children:"Logs"}),t.jsxs("span",{className:"dev-server-muted",children:[j??R.length," lines"]})]}),t.jsx("div",{className:"dev-server-logs-viewer","data-testid":"dev-server-log-viewer",children:t.jsx(At,{entries:R,loading:A,loadingMore:_,hasMore:D,total:j,onLoadMore:T,isRunning:d})})]})}),t.jsxs("section",{className:"dev-server-panel devserver-preview-panel","data-testid":"devserver-preview-panel","aria-label":"Dev server preview",children:[t.jsxs("div",{className:"devserver-preview-header",children:[t.jsxs("div",{className:"devserver-preview-title",children:[t.jsx(ft,{size:14}),t.jsx("span",{children:"Preview"})]}),t.jsxs("span",{className:"devserver-preview-url-badge devserver-preview-url-badge--auto",title:h??"No preview URL","data-testid":"devserver-preview-url-badge",children:["Auto",h?` · ${h}`:" · Not available"]}),t.jsxs("div",{className:"devserver-preview-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>v(m=>m==="embedded"?"external":"embedded"),"data-testid":"devserver-preview-mode-toggle",children:l==="embedded"?"External only":"Embedded"}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon",title:"Open in new tab",onClick:se,disabled:!h,"data-testid":"devserver-preview-open-tab",children:t.jsx(pt,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon",title:"Refresh preview",onClick:Be,disabled:!h,"data-testid":"devserver-preview-refresh",children:t.jsx(ht,{size:14})})]})]}),t.jsxs("div",{className:"devserver-preview-container","data-embed-status":g,"data-embedded":Oe?"true":"false",children:[!h&&!d&&t.jsx("p",{className:"devserver-preview-empty",children:"Start a dev server to see a live preview here."}),!h&&d&&t.jsx("p",{className:"devserver-preview-empty",children:"No preview URL detected. Start the dev server or set a manual URL to preview your app."}),h&&l==="external"&&t.jsxs("div",{className:"devserver-preview-external-only","data-testid":"devserver-preview-external-only",children:[t.jsx("p",{children:"Embedded preview is disabled. Open your app in a separate browser tab."}),t.jsx("button",{type:"button",className:"btn btn-primary btn-sm touch-target",onClick:se,"data-testid":"devserver-preview-external-open-tab",children:"Open in new tab"})]}),h&&l==="embedded"&&pe&&te&&t.jsxs("div",{className:g==="error"?"devserver-preview-error-panel":"devserver-preview-blocked-panel","data-testid":"devserver-preview-fallback",role:"alert",children:[g==="error"?t.jsx(Ae,{className:"devserver-preview-blocked-icon","aria-hidden":"true"}):t.jsx(Me,{className:"devserver-preview-blocked-icon","aria-hidden":"true"}),t.jsxs("div",{children:[t.jsx("p",{className:"devserver-preview-blocked-title",children:g==="error"?"Preview failed":"Preview blocked"}),re&&t.jsx("p",{className:"devserver-preview-blocked-context",children:re})]}),t.jsx("p",{className:"devserver-preview-blocked-description",children:"Open the preview in a new tab, or retry embedded mode after checking your server settings."}),t.jsxs("div",{className:"devserver-preview-blocked-actions",children:[t.jsx("button",{type:"button",className:"btn btn-primary",onClick:se,"data-testid":"devserver-preview-fallback-open-tab",children:"Open preview in new tab"}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:be,"data-testid":"devserver-preview-fallback-retry",children:"Retry embedded preview"})]})]}),h&&l==="embedded"&&!pe&&t.jsx(Tt,{url:h,embedStatus:g,onEmbedStatusChange:Fe,iframeRef:X,blockReason:re,onRetry:be})]})]})]})}export{Ht as DevServerView};
1
+ import{r,j as t}from"./vendor-react-K0fH_qHe.js";import{bI as De,bJ as de,bK as Ze,bL as ue,s as Ue,bM as ge,bN as we,bO as xe,bP as ye,bQ as et,bR as ae,bS as tt,bT as rt,bU as st,bV as nt,bW as at,bX as ie,L as ee,S as it,bY as lt,bZ as ct,_ as ot,b_ as Me,T as Ae,b$ as dt,V as ut,b1 as vt,c0 as mt,ab as ft,ap as pt,R as ht}from"./index-CLAHcGnI.js";import"./vendor-xterm-DzcZoU0P.js";const ve=500,bt=3e3;function B(e){return e instanceof Error?e.message:String(e)}function Pe(e){return e.length<=ve?e:e.slice(-ve)}function le(e,i){return Pe([...e,i])}function I(e){try{return JSON.parse(e)}catch{return null}}function Y(e){const i=e.text??"";return e.stream==="stderr"?`[stderr] ${i}`:i}function gt(e){return e?.previewUrl??null}async function Se(e){return tt(e)}async function Ne(e,i){return rt(e,i)}async function wt(e){return st(e)}async function xt(e){return nt(e)}async function je(e){return at(e)}function V(e){try{return e()}catch{return null}}function ce(){return typeof V(()=>de)=="function"&&typeof V(()=>De)=="function"}function X(e){return{config:{id:e.id??"default",name:e.name??"Dev Server",command:e.command??"",cwd:e.cwd??"."},status:e.status,runtime:e.pid?{pid:e.pid,startedAt:e.startedAt??new Date().toISOString(),exitCode:e.exitCode??void 0,previewUrl:e.previewUrl}:void 0,previewUrl:e.previewUrl??e.detectedUrl??e.manualUrl??void 0,logHistory:(e.logs??[]).map(i=>({timestamp:new Date().toISOString(),stream:i.startsWith("[stderr]")?"stderr":"stdout",text:i.replace(/^\[stderr\]\s*/,"")}))}}function yt(e){const[i,o]=r.useState(null),[b,y]=r.useState([]),[w,f]=r.useState([]),[k,U]=r.useState([]),[C,P]=r.useState(!0),[S,u]=r.useState(null),n=r.useRef(0),[d,M]=r.useState(null),R=r.useCallback(a=>{if(o(a),a?.logHistory){const s=a.logHistory.slice(-ve).map(Y);f(s)}},[]),A=r.useCallback(async()=>{const a=n.current;try{if(ce())if(d){const s=await De(d,e);if(n.current!==a)return;R(s)}else{const s=await de(e);if(n.current!==a)return;y(s),s.length>0&&(M(s[0].config.id),R(s[0]))}else{const s=await Se(e);if(n.current!==a)return;const c=X(s);y([c]),R(c)}u(null)}catch(s){if(n.current!==a)return;u(B(s))}},[R,e,d]);r.useEffect(()=>{n.current+=1;const a=n.current;o(null),y([]),f([]),U([]),P(!0),u(null),M(null),(async()=>{try{const[c,l]=await Promise.allSettled([ce()?de(e):Se(e).then(N=>[X(N)]),typeof V(()=>ae)=="function"?ae(e):je(e).then(N=>N.map(g=>({name:g.name,command:g.command,cwd:g.cwd,scriptName:g.scriptName,packagePath:g.packagePath})))]);if(n.current!==a)return;let v=null;if(c.status==="fulfilled"){const N=c.value;if(y(N),N.length>0){const g=N[0];ce()&&M(g.config.id),R(g)}}else v=B(c.reason);l.status==="fulfilled"&&U(l.value),v&&u(v)}catch(c){if(n.current!==a)return;u(B(c))}finally{n.current===a&&P(!1)}})()},[R,e]),r.useEffect(()=>{const a=d?Ze(d,e):typeof V(()=>ue)=="function"?ue(e):null;if(!a)return;const s=n.current,c=Ue(a,{events:{history:l=>{if(n.current!==s)return;const v=I(l.data);if(v?.lines){const N=v.lines.map(Y);f(Pe(N))}},log:l=>{if(n.current!==s)return;const v=I(l.data);if(v){const N=typeof v.line=="string"?v.line:Y(v);f(g=>le(g,N))}},"dev-server:log":l=>{if(n.current!==s)return;const v=I(l.data);if(v){const N=typeof v.line=="string"?v.line:Y(v);f(g=>le(g,N))}},"dev-server:output":l=>{if(n.current!==s)return;const v=I(l.data);v?.line&&f(N=>le(N,v.line))},status:l=>{if(n.current!==s)return;const v=I(l.data),N=v?.status;N&&o(g=>g&&{...g,status:N,runtime:v.pid?{...g.runtime??{startedAt:new Date().toISOString()},pid:v.pid}:g.runtime})},"dev-server:status":l=>{if(n.current!==s)return;const v=I(l.data);if(v?.status){const N=X(v);o(N),y([N])}},stopped:()=>{n.current},failed:()=>{n.current}},onReconnect:()=>{n.current===s&&A()},onError:()=>{n.current===s&&u(l=>l??"Lost log stream connection.")}});return()=>{c()}},[e,A,d]),r.useEffect(()=>{if(i?.status!=="running"&&i?.status!=="starting")return;const a=setInterval(()=>{A()},bt);return()=>{clearInterval(a)}},[A,i?.status]);const _=r.useCallback(async(a,s)=>{n.current+=1;const c=n.current;try{let l;if(d&&typeof V(()=>ge)=="function")l=await ge(d,e);else{const v=await Ne({command:a,cwd:s},e);l=X(v)}if(n.current!==c)return;o(l),u(null)}catch(l){if(n.current!==c)return;throw u(B(l)),l}},[e,d]),D=r.useCallback(async()=>{n.current+=1;const a=n.current;try{let s;if(d&&typeof V(()=>we)=="function")s=await we(d,e);else{const c=await wt(e);s=X(c)}if(n.current!==a)return;o(s),u(null)}catch(s){if(n.current!==a)return;throw u(B(s)),s}},[e,d]),j=r.useCallback(async()=>{n.current+=1;const a=n.current;try{let s;if(d&&typeof V(()=>xe)=="function")s=await xe(d,e);else{const c=await xt(e);s=X(c)}if(n.current!==a)return;o(s),u(null)}catch(s){if(n.current!==a)return;throw u(B(s)),s}},[e,d]),T=r.useCallback(async a=>{n.current+=1;const s=n.current;try{let c;if(d&&typeof V(()=>ye)=="function")c=await ye(d,a,e);else{const l=await et({url:a},e);c={url:l.manualUrl??l.previewUrl??l.detectedUrl??null,source:l.manualUrl?"manual":"auto"}}if(n.current!==s)return;o(l=>l?{...l,previewUrl:c.url??void 0}:null),u(null)}catch(c){if(n.current!==s)return;throw u(B(c)),c}},[e,d]),h=r.useCallback(async()=>{n.current+=1;const a=n.current;try{let s;try{s=await ae(e)}catch{s=(await je(e)).map(l=>({name:l.name,command:l.command,cwd:l.cwd,scriptName:l.scriptName,packagePath:l.packagePath}))}if(n.current!==a)return;U(s),u(null)}catch(s){if(n.current!==a)return;throw u(B(s)),s}},[e]),p=r.useCallback(async(a,s)=>{if(typeof a!="string"&&!d)try{const v=a,N=await Ne({command:v.command,cwd:v.cwd,scriptName:v.scriptName,packagePath:v.packagePath??v.cwd},e),g=X(N);o(g),y([g]),u(null);return}catch(v){throw u(B(v)),v}const c=typeof a=="string"?a:a.command,l=typeof a=="string"?s:a.cwd;await _(c,l)},[e,_,d]),E=r.useCallback(async()=>{await D()},[D]),L=r.useCallback(async()=>{await j()},[j]),z=r.useCallback(async a=>{await T(a)},[T]),F=r.useCallback(async()=>{await h()},[h]),O=r.useCallback(async()=>{await A()},[A]),H=gt(i),x=i?{...i,pid:i.runtime?.pid}:null;return{session:i,sessions:b,logs:w,detectedCommands:k,previewUrl:H,isLoading:C,error:S,startServer:_,stopServer:D,restartServer:j,setPreviewUrl:T,detectCommands:h,refresh:A,candidates:k,serverState:x,loading:C,start:p,stop:E,restart:L,setManualUrl:z,detect:F,refreshStatus:O}}const ke=500,Ce=100;function Te(e){return e.length>ke?e.slice(-ke):e}function ze(e){return e==="stderr"?"stderr":"stdout"}function K(e){try{return JSON.parse(e.data)}catch{return null}}function Z(e,i){return{id:typeof e.id=="number"&&Number.isFinite(e.id)?e.id:i,text:typeof e.text=="string"?e.text:"",stream:ze(e.stream),timestamp:typeof e.timestamp=="string"?e.timestamp:""}}function St(e,i){return{id:i,text:e,stream:"stdout",timestamp:""}}function oe(e,i){if(i.length===0)return e;const o=[...e],b=new Set(e.map(y=>y.id));for(const y of i)b.has(y.id)||(b.add(y.id),o.push(y));return o.sort((y,w)=>y.id-w.id),Te(o)}function Nt(e,i){const[o,b]=r.useState([]),[y,w]=r.useState(!1),[f,k]=r.useState(!1),[U,C]=r.useState(!1),[P,S]=r.useState(null),u=r.useRef(null),n=r.useRef(!1),d=r.useRef(0),M=r.useRef(0),R=r.useRef(e),A=r.useRef(i),_=r.useRef(0),D=r.useRef(1);(R.current!==e||A.current!==i)&&(R.current=e,A.current=i,d.current++,n.current=!0,_.current=0,D.current=1,b([]),w(!1),k(!1),C(!1),S(null),u.current&&(u.current(),u.current=null)),r.useEffect(()=>{if(!i){u.current&&(u.current(),u.current=null);return}const E=d.current,L=++M.current;n.current=!1,w(!0);const z=(x,a)=>{const s=Te(x);b(s),S(a),C(a!==null?a>s.length:!1);const c=s.length>0?s[s.length-1].id:0;_.current=c,D.current=c+1},F=x=>{if(n.current||d.current!==E||!x||typeof x!="object")return;const a=x.lines;if(!Array.isArray(a))return;if(a.length>0&&typeof a[0]=="string"){const c=a.filter(l=>typeof l=="string").map((l,v)=>St(l,v+1));z(c,c.length);return}const s=a.filter(c=>!!c&&typeof c=="object").map((c,l)=>Z(c,l+1));z(s,s.length)},O=x=>{if(n.current||d.current!==E)return;const a=typeof x.text=="string"?x.text:typeof x.line=="string"?x.line:null;if(!a)return;const s=D.current,c=typeof x.id=="number"&&Number.isFinite(x.id)?x.id:s,l={id:c,text:a,stream:ze(x.stream),timestamp:typeof x.timestamp=="string"?x.timestamp:""};_.current=Math.max(_.current,c),D.current=Math.max(D.current,c+1),b(v=>oe(v,[l])),S(v=>v===null?v:Math.max(v+1,l.id))};async function H(){try{const a=await ie({maxLines:Ce},e);if(n.current||d.current!==E||M.current!==L)return;const s=a.lines.map((c,l)=>Z(c,l+1));z(s,a.totalLines)}catch{if(n.current||d.current!==E||M.current!==L)return;z([],null)}finally{!n.current&&d.current===E&&M.current===L&&w(!1)}const x=ue(e);u.current=Ue(x,{events:{"dev-server:log":a=>{const s=K(a);s&&O(s)},log:a=>{const s=K(a);s&&O(s)},history:a=>{const s=K(a);F(s)},"dev-server:history":a=>{const s=K(a);F(s)}},onReconnect:()=>{n.current||d.current!==E||ie({lastEventId:_.current,maxLines:50},e).then(a=>{if(n.current||d.current!==E)return;const s=a.lines.map((c,l)=>Z(c,D.current+l));if(s.length>0){const c=s[s.length-1].id;_.current=Math.max(_.current,c),D.current=Math.max(D.current,c+1)}b(c=>oe(c,s)),S(a.totalLines)}).catch(()=>{})}})}return H(),()=>{n.current=!0,u.current&&(u.current(),u.current=null)}},[i,e]);const T=r.useCallback(async()=>{if(!i||f)return;const E=d.current,L=o.length;k(!0);try{const z=await ie({maxLines:Ce,offset:L},e);if(n.current||d.current!==E)return;const F=z.lines.map((O,H)=>Z(O,H+1));b(O=>oe(F,O)),C(z.totalLines>L+F.length),S(z.totalLines)}catch{}finally{k(!1)}},[i,o.length,f,e]),h=r.useCallback(()=>{b([])},[]),p=u.current!==null&&!y&&!n.current;return{entries:o,loading:y,loadingMore:f,hasMore:U,total:P,loadMore:T,clear:h,logs:o,isStreaming:p,clearLogs:h}}const jt="This preview appears to block iframe embedding. Open it in a new tab instead.",kt="The preview URL could not be loaded. Verify the server is running and the URL is correct.",Ct="Preview is taking longer than expected and may block iframe embedding.";function Et(e){return e==="blocked"?jt:e==="error"?kt:null}function Lt(e,i={}){const{loadTimeoutMs:o=1e4,detectionMethod:b=null}=i,y=r.useRef(null),w=r.useRef(null),[f,k]=r.useState("unknown"),[U,C]=r.useState(null),[P]=r.useState(b),S=r.useCallback(()=>{w.current!==null&&(window.clearTimeout(w.current),w.current=null)},[]),u=r.useCallback(j=>{k(j),C(Et(j))},[]),n=r.useCallback(()=>{k("blocked"),C(Ct)},[]);r.useEffect(()=>{if(S(),!e){k("unknown"),C(null);return}k("unknown"),C(null);let j=!1;return queueMicrotask(()=>{j||(k("loading"),C(null))}),()=>{j=!0,S()}},[S,e]),r.useEffect(()=>{if(f!=="loading"){S();return}const j=setTimeout(()=>{w.current=null,n()},o);return w.current=j,()=>{clearTimeout(j),w.current===j&&(w.current=null)}},[S,f,o,n]);const d=r.useCallback(()=>{const j=y.current;if(!j){u("embedded");return}try{if(j.contentWindow?.location?.href==="about:blank"&&j.src!=="about:blank"){u("blocked");return}}catch{}u("embedded")},[u]),M=r.useCallback(()=>{u("error")},[u]);r.useEffect(()=>{if(S(),!e){k("unknown"),C(null);return}k("unknown"),C(null)},[S]);const R=r.useCallback(()=>{S(),k("unknown"),C(null)},[S]),A=R,_=r.useMemo(()=>f==="embedded",[f]),D=r.useMemo(()=>f==="blocked"||f==="error",[f]);return{embedStatus:f,isEmbedded:_,isBlocked:D,blockReason:U,detectionMethod:P,iframeRef:y,resetEmbedStatus:R,setEmbedStatus:u,retry:A,embedContext:U,handleIframeLoad:d,handleIframeError:M}}const Rt=/\x1b\[[0-9;]*m/g;function me(e){return e.replace(Rt,"")}function _t(e){if(!e)return"";const i=new Date(e);return Number.isNaN(i.getTime())?"":i.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1})}function Dt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ut(e){if(e.stream==="stderr")return"error";const i=me(e.text).toLowerCase();return/\b(warn|warning)\b/.test(i)?"warn":/\b(error|fatal)\b/.test(i)?"error":"info"}function Mt(e,i){if(!i)return e;const o=new RegExp(`(${Dt(i)})`,"ig"),b=e.split(o),y=i.toLowerCase();return t.jsx(t.Fragment,{children:b.map((w,f)=>w.toLowerCase()===y?t.jsx("mark",{children:w},`${w}-${f}`):t.jsx("span",{children:w},`${w}-${f}`))})}function At({entries:e,loading:i,loadingMore:o,hasMore:b,total:y,onLoadMore:w,isRunning:f}){const k=r.useRef(null),U=r.useRef(e.length),C=r.useRef(f),[P,S]=r.useState(!1),[u,n]=r.useState(!1),[d,M]=r.useState(""),[R,A]=r.useState("all"),_=r.useMemo(()=>R==="all"?e:e.filter(p=>Ut(p)===R),[e,R]),D=r.useMemo(()=>{const p=d.trim().toLowerCase();return p?_.filter(E=>me(E.text).toLowerCase().includes(p)):_},[_,d]),j=D.length,T=r.useCallback(()=>{const p=k.current;p&&(p.scrollTop=p.scrollHeight,n(!1))},[]);r.useEffect(()=>{const p=C.current,E=U.current,L=e.length>E;f&&(!p||!u&&L)&&T(),C.current=f,U.current=e.length},[e.length,f,u,T]);const h=r.useCallback(()=>{const p=k.current;if(!p)return;const L=p.scrollTop+p.clientHeight>=p.scrollHeight-50;n(!L)},[]);return r.useEffect(()=>{i||e.length===0||!u&&f&&T()},[e,f,u,i,T]),i&&e.length===0?t.jsx("section",{className:"devserver-log-viewer","data-testid":"devserver-log-viewer",children:t.jsxs("div",{className:"devserver-log-viewer__loading","data-testid":"devserver-log-loading",children:[t.jsx(ee,{size:16,className:"devserver-log-viewer__spinner"}),t.jsx("span",{children:"Loading logs…"})]})}):t.jsxs("section",{className:`devserver-log-viewer${P?" devserver-log-viewer--fullscreen":""}`,"data-testid":"devserver-log-viewer",children:[t.jsxs("header",{className:"devserver-log-viewer__toolbar",children:[t.jsxs("div",{className:"devserver-log-viewer__toolbar-meta",children:[t.jsx("span",{className:"devserver-log-viewer__title",children:"Logs"}),t.jsxs("span",{className:"devserver-log-viewer__count","data-testid":"devserver-log-count",children:[y!==null?`${e.length}/${y}`:`${e.length}`," lines"]})]}),t.jsxs("div",{className:"devserver-log-viewer__toolbar-actions",children:[t.jsxs("label",{className:"devserver-log-viewer__severity",htmlFor:"devserver-log-severity-filter",children:[t.jsx("span",{className:"visually-hidden",children:"Filter logs by severity"}),t.jsxs("select",{id:"devserver-log-severity-filter",className:"select devserver-log-viewer__severity-select",value:R,onChange:p=>A(p.target.value),"data-testid":"devserver-log-severity-filter","aria-label":"Filter logs by severity",children:[t.jsx("option",{value:"all",children:"All severities"}),t.jsx("option",{value:"info",children:"Info"}),t.jsx("option",{value:"warn",children:"Warn"}),t.jsx("option",{value:"error",children:"Error"})]})]}),t.jsxs("label",{className:"devserver-log-viewer__search",htmlFor:"devserver-log-search",children:[t.jsx("span",{className:"visually-hidden",children:"Search logs"}),t.jsx(it,{size:14}),t.jsx("input",{id:"devserver-log-search",className:"input devserver-log-viewer__search-input",type:"text",value:d,onChange:p=>M(p.target.value),placeholder:"Search logs","data-testid":"devserver-log-search-input","aria-label":"Search logs"})]}),d.trim().length>0&&t.jsxs("span",{className:"devserver-log-viewer__matches","data-testid":"devserver-log-match-count",children:[j," match",j===1?"":"es"]}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon",onClick:()=>S(p=>!p),"data-testid":"devserver-log-fullscreen-toggle","aria-label":P?"Exit fullscreen logs":"Enter fullscreen logs",children:P?t.jsx(lt,{size:14}):t.jsx(ct,{size:14})})]})]}),t.jsxs("div",{className:"devserver-log-viewer__body",children:[b&&t.jsx("div",{className:"devserver-log-viewer__load-more","data-testid":"devserver-log-load-more",children:t.jsx("button",{type:"button",className:"btn btn-sm touch-target",onClick:w,disabled:o,"data-testid":"devserver-log-load-more-button",children:o?t.jsxs(t.Fragment,{children:[t.jsx(ee,{size:14,className:"devserver-log-viewer__spinner"}),"Loading older logs…"]}):"Load older logs"})}),t.jsxs("div",{ref:k,className:"devserver-log-viewer__content",onScroll:h,"data-testid":"devserver-log-content",children:[!i&&D.length===0&&t.jsx("p",{className:"devserver-log-viewer__empty","data-testid":"devserver-log-empty",children:e.length===0?"No logs yet. Start the dev server to see output.":_.length===0?"No log lines match the selected severity.":"No log lines match your search."}),D.map(p=>{const E=me(p.text),L=_t(p.timestamp);return t.jsxs("div",{className:"devserver-log-line",children:[L&&t.jsx("span",{className:"devserver-log-timestamp","data-testid":"devserver-log-timestamp",children:L}),p.stream==="stderr"&&t.jsx("span",{className:"devserver-log-stream-badge","data-testid":"devserver-log-stderr-badge",children:"ERR"}),t.jsx("span",{className:"devserver-log-text",children:Mt(E,d.trim())})]},p.id)})]}),u&&f&&t.jsxs("button",{type:"button",className:"btn btn-sm devserver-log-viewer__new-logs-button",onClick:T,"data-testid":"devserver-log-jump-button",children:[t.jsx(ot,{size:14}),"New logs"]})]})]})}const Pt="devserver-preview-iframe";function Tt({url:e,embedStatus:i,onEmbedStatusChange:o,iframeRef:b,blockReason:y,onRetry:w,className:f=Pt,embedContext:k}){const U=y??k??null,[C,P]=r.useState(0);r.useEffect(()=>{!e||i!=="unknown"||(P(d=>d+1),o("loading"))},[i,o,e]);const S=r.useCallback(()=>{const d=b.current;if(!d){o("embedded");return}try{if(d.contentWindow?.location?.href==="about:blank"&&d.src!=="about:blank"){o("blocked");return}}catch{}o("embedded")},[b,o]),u=r.useCallback(d=>{d.stopPropagation(),o("error")},[o]),n=r.useCallback(()=>{e&&window.open(e,"_blank","noopener,noreferrer")},[e]);return e?t.jsxs("div",{className:"devserver-preview-iframe-shell",children:[t.jsx("iframe",{src:e,ref:b,sandbox:"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox",className:f,title:"Dev server preview",onLoad:S,onError:u,onErrorCapture:u,"data-testid":"devserver-preview-iframe"},`${e}-${C}`),i==="loading"&&t.jsxs("div",{className:"devserver-preview-overlay","data-testid":"devserver-preview-loading",children:[t.jsx(ee,{size:16,className:"dev-server-spin"}),t.jsx("span",{children:"Loading preview..."})]}),i==="blocked"&&t.jsxs("div",{className:"devserver-preview-blocked-panel",role:"alert","data-testid":"devserver-preview-blocked-panel",children:[t.jsx(Me,{className:"devserver-preview-blocked-icon","aria-hidden":"true"}),t.jsxs("div",{children:[t.jsx("p",{className:"devserver-preview-blocked-title",children:"Preview cannot be embedded"}),U&&t.jsx("p",{className:"devserver-preview-blocked-context",children:U})]}),t.jsx("p",{className:"devserver-preview-blocked-description",children:"You can view the preview in a separate browser tab."}),t.jsxs("div",{className:"devserver-preview-blocked-actions",children:[t.jsx("button",{type:"button",className:"btn btn-primary",onClick:n,children:"Open in new tab"}),w&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:w,children:"Retry"})]})]}),i==="error"&&t.jsxs("div",{className:"devserver-preview-error-panel",role:"alert","data-testid":"devserver-preview-error-panel",children:[t.jsx(Ae,{className:"devserver-preview-blocked-icon","aria-hidden":"true"}),t.jsxs("div",{children:[t.jsx("p",{className:"devserver-preview-blocked-title",children:"Unable to load preview"}),U&&t.jsx("p",{className:"devserver-preview-blocked-context",children:U})]}),t.jsx("p",{className:"devserver-preview-blocked-description",children:"You can view the preview in a separate browser tab."}),t.jsxs("div",{className:"devserver-preview-blocked-actions",children:[t.jsx("button",{type:"button",className:"btn btn-primary",onClick:n,children:"Open in new tab"}),w&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:w,children:"Retry"})]})]})]}):null}const Ee={stopped:{className:"dev-server-status-badge--stopped",label:"Stopped"},starting:{className:"dev-server-status-badge--starting",label:"Starting..."},running:{className:"dev-server-status-badge--running",label:"Running"},stopping:{className:"dev-server-status-badge--starting",label:"Stopping..."},failed:{className:"dev-server-status-badge--failed",label:"Failed"}};function Le(e){return e instanceof Error?e.message:String(e)}function $e(e){return e==="."?"root":e}function Re(e){return e?e==="root"?".":e:null}function _e(e,i,o){return!i||e.scriptName!==i?!1:o?$e(e.cwd)===o:!0}function zt(e){return e.cwd==="."?"root":e.cwd}function $t(e){return e.length<=60?e:`${e.slice(0,60)}…`}function Ht({addToast:e,projectId:i}){const{session:o,detectedCommands:b,previewUrl:y,isLoading:w,error:f,startServer:k,stopServer:U,restartServer:C,setPreviewUrl:P,detectCommands:S,refresh:u}=yt(i),n=o?.status??"stopped",d=n==="running"||n==="starting",M=Ee[n]??Ee.stopped,{entries:R,loading:A,loadingMore:_,hasMore:D,total:j,loadMore:T}=Nt(i,!!i),h=y,p=o?.config?.cwd??null,[E,L]=r.useState(!0),[z,F]=r.useState(""),[O,H]=r.useState(""),[x,a]=r.useState(null),[s,c]=r.useState(null),[l,v]=r.useState("embedded"),N=l==="embedded"?h:null,{embedStatus:g,setEmbedStatus:Fe,resetEmbedStatus:G,iframeRef:q,isEmbedded:Oe,isBlocked:te,blockReason:re,retry:fe}=Lt(N),[pe,W]=r.useState(!1),he=r.useRef(g);r.useEffect(()=>{const m=he.current!==g;te&&m&&W(!0),g==="embedded"&&W(!1),he.current=g},[g,te]),r.useEffect(()=>{W(!1)},[h]);const J=r.useMemo(()=>{if(!x)return null;const m=Re(p);return b.find($=>!($.scriptName!==x||m&&$.cwd!==m||o?.config?.command&&$.command!==o.config.command))??b.find($=>_e($,x,p))??null},[b,o?.config?.command,x,p]);r.useEffect(()=>{typeof S=="function"&&S().catch(m=>{e(Le(m),"error")})},[e,S]),r.useEffect(()=>{if(x){L(!1);return}L(!0)},[x]),r.useEffect(()=>{if(o?.status==="running"||o?.status==="starting"){o.config?.command?.trim().length>0&&F(o.config.command);return}if(J){F(J.command);return}b.length>0&&F(m=>m.trim().length>0?m:b[0]?.command??"")},[b,J,o?.config?.command,o?.status]),r.useEffect(()=>{H(h??"")},[h]);const se=r.useCallback(()=>{h&&window.open(h,"_blank","noopener,noreferrer")},[h]),be=r.useCallback(()=>{W(!1),fe()},[fe]),Be=r.useCallback(()=>{try{const m=q.current;if(m?.contentWindow){m.contentWindow.location.reload(),W(!1),G();return}}catch{}if(!(!h||!q.current))try{const m=new URL(h);m.searchParams.set("_t",Date.now().toString()),q.current.src=m.toString(),W(!1),G()}catch{q.current.src=h,W(!1),G()}},[h,q,G]),Q=r.useCallback(async(m,$,ne)=>{c(m);try{await $(),e(ne,"success")}catch(Ke){e(Le(Ke),"error")}finally{c(null)}},[e]),He=r.useCallback(m=>{a(m.scriptName),L(!1),F(m.command),e(`Selected ${m.scriptName} script.`,"success")},[e]),Ve=r.useCallback(()=>{a(null),L(!0),e("Cleared selected dev server script.","success")},[e]),We=()=>{const m=z.trim();if(m.length===0){e("Enter a command before starting the dev server.","warning");return}const $=Re(p)??".",ne=J?.cwd??$;Q("start",()=>k(m,ne),"Dev server started.")},Xe=()=>{Q("stop",U,"Dev server stopped.")},qe=()=>{Q("restart",C,"Dev server restarted.")},Ie=()=>{const m=O.trim(),$=m.length>0?m:null;Q("preview",()=>P($),$?"Preview URL updated.":"Preview URL override cleared.")},Ge=r.useCallback(()=>{f&&u()},[f,u]),Je=n==="starting"||n==="running"||s!==null,Qe=n==="stopped"||s!==null,Ye=n==="stopped"||n==="starting"||s!==null;return t.jsxs("div",{className:"dev-server-view","data-testid":"dev-server-view",children:[t.jsxs("section",{className:"dev-server-header","aria-label":"Dev server controls header",children:[t.jsxs("div",{className:"dev-server-header-title",children:[t.jsx(dt,{size:16}),t.jsx("h2",{children:"Dev Server"}),t.jsx("span",{className:`dev-server-status-badge ${M.className}`,"data-testid":"dev-server-status-badge",children:M.label})]}),t.jsxs("div",{className:"dev-server-header-actions",children:[t.jsxs("button",{type:"button",className:"btn btn-primary btn-sm",onClick:We,disabled:Je,"data-testid":"dev-server-start-button",children:[t.jsx(ut,{size:14}),t.jsx("span",{children:s==="start"?"Starting...":"Start"})]}),t.jsxs("button",{type:"button",className:"btn btn-danger btn-sm",onClick:Xe,disabled:Qe,"data-testid":"dev-server-stop-button",children:[t.jsx(vt,{size:14}),t.jsx("span",{children:s==="stop"?"Stopping...":"Stop"})]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:qe,disabled:Ye,"data-testid":"dev-server-restart-button",children:[t.jsx(mt,{size:14}),t.jsx("span",{children:s==="restart"?"Restarting...":"Restart"})]})]})]}),t.jsxs("section",{className:"dev-server-panel dev-server-config","aria-label":"Dev server configuration",children:[t.jsxs("div",{className:"dev-server-section-header",children:[t.jsx("h3",{children:"Configuration"}),w&&t.jsx("span",{className:"dev-server-muted",children:"Loading..."})]}),w&&!o&&b.length===0&&t.jsxs("div",{className:"dev-server-loading-state","data-testid":"dev-server-loading-state",children:[t.jsx(ee,{size:16,className:"dev-server-spin"}),t.jsx("span",{children:"Loading dev server configuration..."})]}),f&&t.jsxs("div",{className:"dev-server-error-box",role:"alert","data-testid":"dev-server-error-box",children:[t.jsx("p",{children:f}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:Ge,children:"Retry"})]}),t.jsxs("div",{className:"dev-server-section",children:[t.jsx("h3",{children:"Script Selection"}),x&&t.jsxs("div",{className:"dev-server-selected","data-testid":"dev-server-selected-summary",children:[t.jsx("span",{className:"dev-server-candidate-name",children:x}),t.jsx("span",{className:"dev-server-candidate-source",children:p??"root"}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>L(!0),"data-testid":"dev-server-change-selection",children:"Change"}),t.jsx("button",{type:"button",className:"btn btn-danger btn-sm",onClick:Ve,"data-testid":"dev-server-clear-selection",children:"Clear"})]}),E&&b.length===0&&t.jsxs("p",{className:"dev-server-empty-state","data-testid":"dev-server-empty-candidates",children:["No dev server scripts detected. Check that your project has a ",t.jsx("code",{children:"package.json"})," with a ",t.jsx("code",{children:"dev"}),", ",t.jsx("code",{children:"start"}),", or similar script."]}),E&&b.length>0&&t.jsx("div",{className:"dev-server-candidates","data-testid":"dev-server-candidates",children:b.map(m=>{const $=_e(m,x,p);return t.jsxs("button",{type:"button",className:`dev-server-candidate ${$?"dev-server-candidate--selected":""}`,onClick:()=>He(m),"data-testid":`dev-server-candidate-${m.scriptName}-${$e(m.cwd)}`,children:[t.jsx("span",{className:"dev-server-candidate-name",children:m.scriptName}),t.jsx("span",{className:"dev-server-candidate-command",children:$t(m.command)}),t.jsx("span",{className:"dev-server-candidate-source",children:zt(m)})]},`${m.cwd}::${m.scriptName}::${m.command}`)})})]}),t.jsxs("div",{className:"dev-server-field-group",children:[t.jsx("label",{htmlFor:"dev-server-command",className:"dev-server-label",children:"Command"}),t.jsx("input",{id:"dev-server-command",className:"input",value:z,onChange:m=>F(m.target.value),placeholder:"pnpm dev","data-testid":"dev-server-command-input",readOnly:n==="running"||n==="starting"})]}),(n==="running"||n==="starting")&&o&&t.jsxs("div",{className:"dev-server-current-command","data-testid":"dev-server-current-command",children:[t.jsx("span",{className:"dev-server-label",children:"Running command"}),t.jsx("code",{children:o.config?.command??z})]}),t.jsxs("div",{className:"dev-server-preview-override",children:[t.jsx("label",{htmlFor:"dev-server-preview-input",className:"dev-server-label",children:"Preview URL Override"}),t.jsx("input",{id:"dev-server-preview-input",className:"input",type:"url",value:O,onChange:m=>H(m.target.value),placeholder:"http://localhost:3000","data-testid":"dev-server-preview-input"}),t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:Ie,disabled:s==="preview","data-testid":"dev-server-set-preview",children:"Save"})]}),h&&t.jsxs("p",{className:"dev-server-preview-hint",children:["Auto-detected: ",h]})]}),t.jsx("div",{className:"dev-server-content",children:t.jsxs("section",{className:"dev-server-panel dev-server-logs-panel","data-testid":"dev-server-logs-panel","aria-label":"Dev server logs",children:[t.jsxs("div",{className:"dev-server-section-header",children:[t.jsx("h3",{children:"Logs"}),t.jsxs("span",{className:"dev-server-muted",children:[j??R.length," lines"]})]}),t.jsx("div",{className:"dev-server-logs-viewer","data-testid":"dev-server-log-viewer",children:t.jsx(At,{entries:R,loading:A,loadingMore:_,hasMore:D,total:j,onLoadMore:T,isRunning:d})})]})}),t.jsxs("section",{className:"dev-server-panel devserver-preview-panel","data-testid":"devserver-preview-panel","aria-label":"Dev server preview",children:[t.jsxs("div",{className:"devserver-preview-header",children:[t.jsxs("div",{className:"devserver-preview-title",children:[t.jsx(ft,{size:14}),t.jsx("span",{children:"Preview"})]}),t.jsxs("span",{className:"devserver-preview-url-badge devserver-preview-url-badge--auto",title:h??"No preview URL","data-testid":"devserver-preview-url-badge",children:["Auto",h?` · ${h}`:" · Not available"]}),t.jsxs("div",{className:"devserver-preview-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>v(m=>m==="embedded"?"external":"embedded"),"data-testid":"devserver-preview-mode-toggle",children:l==="embedded"?"External only":"Embedded"}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon",title:"Open in new tab",onClick:se,disabled:!h,"data-testid":"devserver-preview-open-tab",children:t.jsx(pt,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon",title:"Refresh preview",onClick:Be,disabled:!h,"data-testid":"devserver-preview-refresh",children:t.jsx(ht,{size:14})})]})]}),t.jsxs("div",{className:"devserver-preview-container","data-embed-status":g,"data-embedded":Oe?"true":"false",children:[!h&&!d&&t.jsx("p",{className:"devserver-preview-empty",children:"Start a dev server to see a live preview here."}),!h&&d&&t.jsx("p",{className:"devserver-preview-empty",children:"No preview URL detected. Start the dev server or set a manual URL to preview your app."}),h&&l==="external"&&t.jsxs("div",{className:"devserver-preview-external-only","data-testid":"devserver-preview-external-only",children:[t.jsx("p",{children:"Embedded preview is disabled. Open your app in a separate browser tab."}),t.jsx("button",{type:"button",className:"btn btn-primary btn-sm touch-target",onClick:se,"data-testid":"devserver-preview-external-open-tab",children:"Open in new tab"})]}),h&&l==="embedded"&&pe&&te&&t.jsxs("div",{className:g==="error"?"devserver-preview-error-panel":"devserver-preview-blocked-panel","data-testid":"devserver-preview-fallback",role:"alert",children:[g==="error"?t.jsx(Ae,{className:"devserver-preview-blocked-icon","aria-hidden":"true"}):t.jsx(Me,{className:"devserver-preview-blocked-icon","aria-hidden":"true"}),t.jsxs("div",{children:[t.jsx("p",{className:"devserver-preview-blocked-title",children:g==="error"?"Preview failed":"Preview blocked"}),re&&t.jsx("p",{className:"devserver-preview-blocked-context",children:re})]}),t.jsx("p",{className:"devserver-preview-blocked-description",children:"Open the preview in a new tab, or retry embedded mode after checking your server settings."}),t.jsxs("div",{className:"devserver-preview-blocked-actions",children:[t.jsx("button",{type:"button",className:"btn btn-primary",onClick:se,"data-testid":"devserver-preview-fallback-open-tab",children:"Open preview in new tab"}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:be,"data-testid":"devserver-preview-fallback-retry",children:"Retry embedded preview"})]})]}),h&&l==="embedded"&&!pe&&t.jsx(Tt,{url:h,embedStatus:g,onEmbedStatusChange:Fe,iframeRef:q,blockReason:re,onRetry:be})]})]})]})}export{Ht as DevServerView};
@@ -1 +1 @@
1
- import{r as i,j as r}from"./vendor-react-K0fH_qHe.js";import{dS as f,dT as g,cX as b,U as y,ag as P,ab as H,ac as C,L as O,an as v}from"./index-D7gT6mCr.js";import{F as z}from"./folder-open-CxOUgHDf.js";function D({value:o,onChange:d,placeholder:m,onInputKeyDown:x,nodeId:l,localNodeId:h}){const[e,n]=i.useState({isOpen:!1,loading:!1,error:null,currentPath:"",parentPath:null,entries:[],showHidden:!1}),a=i.useCallback(async(s,c=!1)=>{n(t=>({...t,loading:!0,error:null}));try{const t=await f(s,c,l,h);n(u=>({...u,loading:!1,currentPath:t.currentPath,parentPath:t.parentPath,entries:t.entries}))}catch(t){n(u=>({...u,loading:!1,error:t instanceof Error?t.message:"Failed to browse directory"}))}},[l,h]),j=i.useCallback(()=>{n(s=>s.isOpen?{...s,isOpen:!1}:{...s,isOpen:!0})},[]);i.useEffect(()=>{e.isOpen&&!e.loading&&e.entries.length===0&&!e.error&&a(o||void 0,e.showHidden)},[e.isOpen,e.loading,e.entries.length,e.error,o,e.showHidden,a,l,h]);const p=i.useCallback(s=>{a(s,e.showHidden)},[a,e.showHidden]),k=i.useCallback(()=>{d(e.currentPath),n(s=>({...s,isOpen:!1}))},[e.currentPath,d]),w=i.useCallback(()=>{n(s=>{const c=!s.showHidden;return{...s,showHidden:c}})},[]);i.useEffect(()=>{e.isOpen&&e.currentPath&&a(e.currentPath,e.showHidden)},[e.showHidden]);const N=e.currentPath?g(e.currentPath):[];return r.jsxs("div",{className:"directory-picker",children:[r.jsxs("div",{className:"directory-picker-input-row",children:[r.jsx("input",{type:"text",className:"input directory-picker-input",value:o,onChange:s=>d(s.target.value),onKeyDown:x,placeholder:m||"/path/to/your/project"}),r.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm directory-picker-browse-btn",onClick:j,"aria-label":e.isOpen?"Close directory browser":"Browse directories",children:[e.isOpen?r.jsx(z,{size:16}):r.jsx(b,{size:16}),r.jsx("span",{children:"Browse"})]})]}),e.isOpen&&r.jsxs("div",{className:"directory-picker-browser",role:"tree","aria-label":"Directory browser",children:[r.jsx("div",{className:"directory-picker-breadcrumbs",children:N.map((s,c)=>r.jsxs("span",{className:"directory-picker-breadcrumb-item",children:[c>0&&r.jsx(y,{size:12,className:"directory-picker-breadcrumb-sep"}),r.jsx("button",{type:"button",className:"directory-picker-breadcrumb",onClick:()=>p(s.path),title:s.path,children:s.label})]},s.path))}),r.jsxs("div",{className:"directory-picker-toolbar",children:[e.parentPath&&r.jsxs("button",{type:"button",className:"btn btn-sm btn-secondary directory-picker-up-btn",onClick:()=>p(e.parentPath),"aria-label":"Go to parent directory",title:"Parent directory",children:[r.jsx(P,{size:14}),r.jsx("span",{children:"Up"})]}),r.jsxs("button",{type:"button",className:"btn btn-sm btn-secondary directory-picker-hidden-toggle",onClick:w,"aria-label":e.showHidden?"Hide hidden directories":"Show hidden directories",title:e.showHidden?"Hide hidden":"Show hidden",children:[e.showHidden?r.jsx(H,{size:14}):r.jsx(C,{size:14}),r.jsx("span",{children:e.showHidden?"Hide hidden":"Show hidden"})]})]}),e.loading?r.jsxs("div",{className:"directory-picker-loading",children:[r.jsx(O,{size:20,className:"animate-spin"}),r.jsx("span",{children:"Loading…"})]}):e.error?r.jsxs("div",{className:"directory-picker-error",children:[r.jsx(v,{size:16}),r.jsx("span",{children:e.error})]}):r.jsx("div",{className:"directory-picker-entries",children:e.entries.length===0?r.jsx("div",{className:"directory-picker-empty",children:"No subdirectories"}):e.entries.map(s=>r.jsxs("button",{type:"button",className:"directory-picker-entry",onClick:()=>p(s.path),role:"treeitem",title:s.path,children:[r.jsx(b,{size:16,className:"directory-picker-entry-icon"}),r.jsx("span",{className:"directory-picker-entry-name",children:s.name}),s.hasChildren&&r.jsx(y,{size:14,className:"directory-picker-entry-arrow"})]},s.path))}),r.jsxs("div",{className:"directory-picker-actions",children:[r.jsx("span",{className:"directory-picker-selected-path",title:e.currentPath,children:e.currentPath}),r.jsx("button",{type:"button",className:"btn btn-primary directory-picker-select-btn",onClick:k,children:"Select"})]})]})]})}export{D};
1
+ import{r as i,j as r}from"./vendor-react-K0fH_qHe.js";import{dU as N,dV as g,cY as b,Q as m,af as P,aa as H,ab as C,L as O,am as v}from"./index-CLAHcGnI.js";import{F as z}from"./folder-open-D11gjHGK.js";function D({value:o,onChange:d,placeholder:y,onInputKeyDown:x,nodeId:l,localNodeId:h}){const[e,n]=i.useState({isOpen:!1,loading:!1,error:null,currentPath:"",parentPath:null,entries:[],showHidden:!1}),a=i.useCallback(async(s,c=!1)=>{n(t=>({...t,loading:!0,error:null}));try{const t=await N(s,c,l,h);n(u=>({...u,loading:!1,currentPath:t.currentPath,parentPath:t.parentPath,entries:t.entries}))}catch(t){n(u=>({...u,loading:!1,error:t instanceof Error?t.message:"Failed to browse directory"}))}},[l,h]),j=i.useCallback(()=>{n(s=>s.isOpen?{...s,isOpen:!1}:{...s,isOpen:!0})},[]);i.useEffect(()=>{e.isOpen&&!e.loading&&e.entries.length===0&&!e.error&&a(o||void 0,e.showHidden)},[e.isOpen,e.loading,e.entries.length,e.error,o,e.showHidden,a,l,h]);const p=i.useCallback(s=>{a(s,e.showHidden)},[a,e.showHidden]),k=i.useCallback(()=>{d(e.currentPath),n(s=>({...s,isOpen:!1}))},[e.currentPath,d]),w=i.useCallback(()=>{n(s=>{const c=!s.showHidden;return{...s,showHidden:c}})},[]);i.useEffect(()=>{e.isOpen&&e.currentPath&&a(e.currentPath,e.showHidden)},[e.showHidden]);const f=e.currentPath?g(e.currentPath):[];return r.jsxs("div",{className:"directory-picker",children:[r.jsxs("div",{className:"directory-picker-input-row",children:[r.jsx("input",{type:"text",className:"input directory-picker-input",value:o,onChange:s=>d(s.target.value),onKeyDown:x,placeholder:y||"/path/to/your/project"}),r.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm directory-picker-browse-btn",onClick:j,"aria-label":e.isOpen?"Close directory browser":"Browse directories",children:[e.isOpen?r.jsx(z,{size:16}):r.jsx(b,{size:16}),r.jsx("span",{children:"Browse"})]})]}),e.isOpen&&r.jsxs("div",{className:"directory-picker-browser",role:"tree","aria-label":"Directory browser",children:[r.jsx("div",{className:"directory-picker-breadcrumbs",children:f.map((s,c)=>r.jsxs("span",{className:"directory-picker-breadcrumb-item",children:[c>0&&r.jsx(m,{size:12,className:"directory-picker-breadcrumb-sep"}),r.jsx("button",{type:"button",className:"directory-picker-breadcrumb",onClick:()=>p(s.path),title:s.path,children:s.label})]},s.path))}),r.jsxs("div",{className:"directory-picker-toolbar",children:[e.parentPath&&r.jsxs("button",{type:"button",className:"btn btn-sm btn-secondary directory-picker-up-btn",onClick:()=>p(e.parentPath),"aria-label":"Go to parent directory",title:"Parent directory",children:[r.jsx(P,{size:14}),r.jsx("span",{children:"Up"})]}),r.jsxs("button",{type:"button",className:"btn btn-sm btn-secondary directory-picker-hidden-toggle",onClick:w,"aria-label":e.showHidden?"Hide hidden directories":"Show hidden directories",title:e.showHidden?"Hide hidden":"Show hidden",children:[e.showHidden?r.jsx(H,{size:14}):r.jsx(C,{size:14}),r.jsx("span",{children:e.showHidden?"Hide hidden":"Show hidden"})]})]}),e.loading?r.jsxs("div",{className:"directory-picker-loading",children:[r.jsx(O,{size:20,className:"animate-spin"}),r.jsx("span",{children:"Loading…"})]}):e.error?r.jsxs("div",{className:"directory-picker-error",children:[r.jsx(v,{size:16}),r.jsx("span",{children:e.error})]}):r.jsx("div",{className:"directory-picker-entries",children:e.entries.length===0?r.jsx("div",{className:"directory-picker-empty",children:"No subdirectories"}):e.entries.map(s=>r.jsxs("button",{type:"button",className:"directory-picker-entry",onClick:()=>p(s.path),role:"treeitem",title:s.path,children:[r.jsx(b,{size:16,className:"directory-picker-entry-icon"}),r.jsx("span",{className:"directory-picker-entry-name",children:s.name}),s.hasChildren&&r.jsx(m,{size:14,className:"directory-picker-entry-arrow"})]},s.path))}),r.jsxs("div",{className:"directory-picker-actions",children:[r.jsx("span",{className:"directory-picker-selected-path",title:e.currentPath,children:e.currentPath}),r.jsx("button",{type:"button",className:"btn btn-primary directory-picker-select-btn",onClick:k,children:"Select"})]})]})]})}export{D};
@@ -1 +1 @@
1
- import{r as s,j as e}from"./vendor-react-K0fH_qHe.js";import{a8 as oe,a9 as K,f as le,aa as ie,F as z,ab as de,ac as ue,S as me,X as he,R as pe,ad as fe,ae as W,af as V,$ as X,U as je,ag as xe}from"./index-D7gT6mCr.js";import"./vendor-xterm-DzcZoU0P.js";function we(n){const{projectId:c,searchQuery:u,includeProjectFiles:a=!0}=n??{},[x,l]=s.useState([]),[h,i]=s.useState([]),[o,p]=s.useState(!0),[k,b]=s.useState(null),f=s.useRef(null),g=s.useRef(!1),m=s.useRef(null),j=s.useCallback(async()=>{f.current&&f.current.abort();const C=new AbortController;f.current=C;const E=!g.current;E&&p(!0),b(null);const L=oe(u?{q:u}:void 0,c),y=a?K(c):Promise.resolve({files:[]}),[v,F]=await Promise.allSettled([L,y]);if(C.signal.aborted)return;let R=null;if(v.status==="fulfilled"?(l(v.value),g.current=!0):R=v.reason instanceof Error?v.reason.message:String(v.reason),F.status==="fulfilled"){const M=F.value.files,P=u?.trim().toLowerCase(),T=P?M.filter(N=>N.name.toLowerCase().includes(P)||N.path.toLowerCase().includes(P)):M;i(T)}b(R),E&&p(!1)},[a,c,u]);return s.useEffect(()=>(m.current&&clearTimeout(m.current),m.current=setTimeout(()=>{j()},300),()=>{m.current&&clearTimeout(m.current)}),[j]),s.useEffect(()=>(j(),()=>{f.current&&f.current.abort()}),[]),{documents:x,projectFiles:h,loading:o,error:k,refresh:j}}function ke(n,c){const[u,a]=s.useState([]),[x,l]=s.useState(!0),[h,i]=s.useState(null),o=s.useRef(null),p=s.useRef(!1),k=c?.showHidden??!1,b=s.useCallback(async f=>{o.current&&o.current.abort();const g=new AbortController;o.current=g;const m=!p.current;m&&l(!0),i(null);try{const j=await K(n,{showHidden:f?.showHidden??k});if(g.signal.aborted)return;a(j.files),p.current=!0}catch(j){if(g.signal.aborted)return;i(j instanceof Error?j.message:String(j))}finally{!g.signal.aborted&&m&&l(!1)}},[n,k]);return s.useEffect(()=>(p.current=!1,b({showHidden:k}),()=>{o.current&&o.current.abort()}),[b,k]),{files:u,loading:x,error:h,refresh:b}}const be=768;function _(n){return n?new Date(n).toLocaleString():""}function ge(n){return n<1024?`${n} B`:n<1024*1024?`${(n/1024).toFixed(n>=10*1024?0:1)} KB`:`${(n/(1024*1024)).toFixed(1)} MB`}function ve(n,c=200){return n.length<=c?n:`${n.substring(0,c)}…`}function Ne({document:n,renderMarkdown:c,onToggleMarkdown:u}){const[a,x]=s.useState(!1),l=ve(n.content),h=n.content.length>200;return e.jsxs("div",{className:"document-card",children:[e.jsxs("div",{className:"document-card-header",children:[e.jsxs("div",{className:"document-card-key",children:[e.jsx(z,{size:14}),e.jsx("span",{className:"document-card-key-text",children:n.key}),e.jsxs("span",{className:"document-card-revision-badge",children:["v",n.revision]})]}),e.jsx("div",{className:"document-card-actions",children:e.jsx("button",{className:"btn btn-sm document-card-expand-btn",onClick:()=>x(i=>!i),title:a?"Collapse":"Expand","aria-label":a?"Collapse content":"Expand content",children:a?e.jsx(xe,{size:14}):e.jsx(X,{size:14})})})]}),e.jsxs("div",{className:"document-card-meta",children:[e.jsx("span",{className:"document-card-author",children:n.author}),e.jsx("span",{className:"document-card-separator",children:"·"}),e.jsx("span",{className:"document-card-date",children:_(n.updatedAt)})]}),e.jsxs("div",{className:`document-card-content${a?" document-card-content--expanded":""}`,children:[a?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"document-card-content-header",children:e.jsx("button",{className:"btn btn-sm document-mode-toggle",onClick:u,"aria-label":c?"Switch to plain text":"Switch to markdown","aria-pressed":c,title:c?"Switch to plain text":"Switch to markdown",children:c?"Markdown":"Plain"})}),c?e.jsx("div",{className:"document-card-content-markdown",children:e.jsx("div",{className:"markdown-body",children:e.jsx(W,{remarkPlugins:[V],children:n.content})})}):e.jsx("pre",{className:"document-card-content-text",children:n.content})]}):e.jsx("p",{className:"document-card-preview",children:l}),h&&!a&&e.jsx("p",{className:"document-card-preview-truncated",children:"…"})]})]})}function Se({taskId:n,taskTitle:c,documents:u,onOpenTask:a,renderMarkdownStates:x,onToggleMarkdown:l}){const[h,i]=s.useState(!1);return e.jsxs("div",{className:"documents-group",children:[e.jsxs("div",{className:"documents-group-header",children:[e.jsxs("button",{className:"documents-group-toggle-btn",onClick:()=>i(o=>!o),"aria-expanded":h,"aria-label":`${h?"Collapse":"Expand"} documents for task ${n}`,children:[e.jsx("span",{className:"documents-group-toggle","aria-hidden":"true",children:h?e.jsx(X,{size:16}):e.jsx(je,{size:16})}),e.jsx("span",{className:"documents-group-task-id",children:n}),e.jsx("span",{className:"documents-group-task-title",children:c||"Untitled"})]}),e.jsxs("span",{className:"documents-group-count",children:[u.length," doc",u.length!==1?"s":""]}),e.jsx("button",{className:"documents-group-task-link",onClick:()=>a(n),"aria-label":`Open task ${n}: ${c||"Untitled"}`,children:"Open task"})]}),h&&e.jsx("div",{className:"documents-group-content",children:u.map(o=>e.jsx(Ne,{document:o,renderMarkdown:x.get(o.id)??!1,onToggleMarkdown:()=>l(o.id)},o.id))})]})}function ye({projectId:n,addToast:c,onOpenDetail:u}){const[a,x]=s.useState("project"),[l,h]=s.useState(""),[i,o]=s.useState(null),[p,k]=s.useState(!1),[b,f]=s.useState(null),[g,m]=s.useState(!1),[j,C]=s.useState(null),[E,L]=s.useState(!1),y=s.useRef(0),v=s.useRef(!1),[F,R]=s.useState(!1),[M,P]=s.useState(new Map),T=a==="tasks"?l.trim():"",{documents:N,loading:D,error:J,refresh:B}=we({projectId:n,searchQuery:T||void 0,includeProjectFiles:!1}),{files:S,loading:$,error:Y,refresh:O}=ke(n,{showHidden:p});s.useEffect(()=>{const t=()=>{L(window.innerWidth<=be)};return t(),window.addEventListener("resize",t),()=>{window.removeEventListener("resize",t)}},[]),s.useEffect(()=>{v.current=!1,x("project"),o(null),k(!1),f(null),C(null),m(!1),R(!1),P(new Map)},[n]),s.useEffect(()=>{v.current||D||$||(S.length>0?x("project"):N.length>0&&x("tasks"),v.current=!0)},[N.length,D,S.length,$]);const H=s.useMemo(()=>{const t=new Map;for(const r of N){const d=t.get(r.taskId)||[];t.set(r.taskId,[...d,r])}return Array.from(t.entries()).map(([r,d])=>{const w=[...d].sort((re,ce)=>ce.updatedAt.localeCompare(re.updatedAt));return{taskId:r,taskTitle:w[0]?.taskTitle,documents:w,latestUpdated:w[0]?.updatedAt??""}}).sort((r,d)=>d.latestUpdated.localeCompare(r.latestUpdated))},[N]),A=s.useMemo(()=>{const t=l.trim().toLowerCase();return t?S.filter(r=>{const d=r.path.toLowerCase(),w=r.name.toLowerCase();return d.includes(t)||w.includes(t)}):S},[S,l]);s.useEffect(()=>{if(!i)return;S.some(r=>r.path===i.path)||(o(null),f(null),C(null),m(!1))},[S,i]);const Z=s.useCallback(t=>{h(t.target.value)},[]),I=s.useCallback(()=>{h("")},[]),U=s.useCallback(t=>{x(t)},[]),ee=s.useCallback(async t=>{try{const r=await le(t,n);u(r)}catch{c(`Failed to open task ${t}`,"error")}},[n,u,c]),se=s.useCallback(async t=>{o(t),m(!0),C(null),f(null);const r=y.current+1;y.current=r;try{const d=await ie("project",t.path,n);if(y.current!==r)return;f(d.content)}catch(d){if(y.current!==r)return;const w=d instanceof Error?d.message:`Failed to open ${t.path}`;C(w),c(w,"error")}finally{y.current===r&&m(!1)}},[n,c]),te=s.useCallback(()=>{o(null),f(null),C(null),m(!1)},[]),ne=s.useCallback(t=>{P(r=>{const d=new Map(r),w=d.get(t)??!1;return d.set(t,!w),d})},[]),Q=a==="project"?Y:J,ae=s.useCallback(async()=>{if(a==="project"){await O();return}await B()},[a,O,B]),q=a==="project"?A.length:N.length,G=a==="project"?"Search project markdown files…":"Search task documents…";return e.jsxs("div",{className:"documents-view",children:[e.jsxs("div",{className:"documents-view-header",children:[e.jsxs("div",{className:"documents-view-title-row",children:[e.jsxs("h2",{className:"documents-view-title",children:[e.jsx(z,{size:20}),"Documents"]}),e.jsxs("span",{className:"documents-view-count",children:[q," result",q!==1?"s":""]})]}),e.jsxs("div",{className:"documents-controls-row",children:[e.jsxs("div",{className:"documents-tab-bar",role:"tablist","aria-label":"Documents sections",children:[e.jsxs("button",{className:`btn documents-tab${a==="project"?" active":""}`,role:"tab","aria-selected":a==="project","aria-label":"Show project markdown files",onClick:()=>U("project"),children:["Project Files",e.jsx("span",{className:"documents-tab-count",children:S.length})]}),e.jsxs("button",{className:`btn documents-tab${a==="tasks"?" active":""}`,role:"tab","aria-selected":a==="tasks","aria-label":"Show task documents",onClick:()=>U("tasks"),children:["Task Documents",e.jsx("span",{className:"documents-tab-count",children:H.length})]})]}),a==="project"&&e.jsxs("button",{className:"btn btn-sm documents-hidden-toggle",onClick:()=>k(t=>!t),"aria-pressed":p,"aria-label":p?"Hide hidden project files":"Show hidden project files",title:p?"Hide hidden files":"Show hidden files",children:[p?e.jsx(de,{size:14}):e.jsx(ue,{size:14}),p?"Hide Hidden":"Show Hidden"]}),e.jsxs("div",{className:"documents-search",children:[e.jsx(me,{size:16,className:"documents-search-icon"}),e.jsx("input",{type:"text",className:"documents-search-input",placeholder:G,value:l,onChange:Z,"aria-label":G}),l&&e.jsx("button",{className:"documents-search-clear",onClick:I,"aria-label":"Clear search",children:e.jsx(he,{size:16})})]})]})]}),e.jsx("div",{className:"documents-view-content",children:Q?e.jsxs("div",{className:"documents-view-error",children:[e.jsxs("p",{children:["Failed to load ",a==="project"?"project files":"task documents",": ",Q]}),e.jsxs("button",{className:"btn btn-primary",onClick:()=>void ae(),"aria-label":"Retry loading documents",children:[e.jsx(pe,{size:16}),"Retry"]})]}):a==="project"?$&&S.length===0?e.jsx("div",{className:"documents-view-loading",children:e.jsx("p",{children:"Loading project markdown files…"})}):A.length===0?e.jsx("div",{className:"documents-view-empty",children:l.trim()?e.jsxs("p",{children:['No project markdown files match "',l.trim(),'".']}):e.jsxs(e.Fragment,{children:[e.jsx(z,{size:48,className:"documents-view-empty-icon"}),e.jsx("p",{children:"No Markdown files found in this project."})]})}):e.jsxs("div",{className:`documents-project-layout${E?" documents-project-layout--mobile":""}`,children:[(!E||!i)&&e.jsx("aside",{className:"documents-view-sidebar","aria-label":"Project markdown files",children:e.jsx("ul",{className:"markdown-file-list",children:A.map(t=>{const r=i?.path===t.path;return e.jsx("li",{className:"markdown-file-list-item",children:e.jsxs("button",{className:`markdown-file-item${r?" markdown-file-item--selected":""}`,onClick:()=>void se(t),"aria-label":`Open ${t.path}`,"aria-current":r?"true":void 0,children:[e.jsx("span",{className:"markdown-file-item-name",children:t.name}),e.jsx("span",{className:"markdown-file-item-path",children:t.path}),e.jsxs("span",{className:"markdown-file-item-meta",children:[ge(t.size)," · ",_(t.mtime)]})]})},t.path)})})}),(!E||i)&&e.jsxs("section",{className:"documents-view-main","aria-label":"Project file content preview",children:[E&&i&&e.jsxs("button",{className:"btn btn-sm documents-mobile-back",onClick:te,"aria-label":"Back to project files list",children:[e.jsx(fe,{size:14}),"Back to files"]}),i?e.jsxs("div",{className:"documents-content-viewer",children:[e.jsxs("div",{className:"documents-content-header",children:[e.jsx("p",{className:"documents-file-path-header",children:i.path}),e.jsx("button",{className:"btn btn-sm document-mode-toggle",onClick:()=>R(t=>!t),"aria-label":F?"Switch to plain text":"Switch to markdown","aria-pressed":F,title:F?"Switch to plain text":"Switch to markdown",children:F?"Markdown":"Plain"})]}),g?e.jsx("p",{className:"documents-content-state",children:"Loading file content…"}):j?e.jsx("p",{className:"documents-content-state documents-content-state--error",children:j}):F?e.jsx("div",{className:"documents-content-markdown",children:e.jsx("div",{className:"markdown-body",children:e.jsx(W,{remarkPlugins:[V],children:b??""})})}):e.jsx("pre",{className:"document-card-content-text documents-content-viewer-text",children:b??""})]}):e.jsx("div",{className:"documents-view-empty",children:e.jsx("p",{children:"Select a Markdown file to view its content."})})]})]}):D&&N.length===0?e.jsx("div",{className:"documents-view-loading",children:e.jsx("p",{children:"Loading task documents…"})}):H.length===0?e.jsx("div",{className:"documents-view-empty",children:l.trim()?e.jsxs("p",{children:['No task documents match "',l.trim(),'".']}):e.jsxs(e.Fragment,{children:[e.jsx(z,{size:48,className:"documents-view-empty-icon"}),e.jsx("p",{children:"No task documents yet."}),e.jsx("p",{className:"documents-view-empty-hint",children:"Documents are created in task detail tabs."})]})}):e.jsx("div",{className:"documents-task-list-wrap",children:e.jsx("div",{className:"documents-view-list",children:H.map(({taskId:t,taskTitle:r,documents:d})=>e.jsx(Se,{taskId:t,taskTitle:r,documents:d,onOpenTask:ee,renderMarkdownStates:M,onToggleMarkdown:ne},t))})})})]})}export{ye as DocumentsView};
1
+ import{r as s,j as e}from"./vendor-react-K0fH_qHe.js";import{a7 as oe,a8 as K,f as le,a9 as ie,F as z,aa as de,ab as ue,S as me,X as he,R as pe,ac as fe,ad as W,ae as _,_ as V,Q as je,af as xe}from"./index-CLAHcGnI.js";import"./vendor-xterm-DzcZoU0P.js";function we(n){const{projectId:c,searchQuery:u,includeProjectFiles:a=!0}=n??{},[x,l]=s.useState([]),[h,i]=s.useState([]),[o,p]=s.useState(!0),[k,b]=s.useState(null),f=s.useRef(null),g=s.useRef(!1),m=s.useRef(null),j=s.useCallback(async()=>{f.current&&f.current.abort();const C=new AbortController;f.current=C;const E=!g.current;E&&p(!0),b(null);const L=oe(u?{q:u}:void 0,c),y=a?K(c):Promise.resolve({files:[]}),[v,F]=await Promise.allSettled([L,y]);if(C.signal.aborted)return;let R=null;if(v.status==="fulfilled"?(l(v.value),g.current=!0):R=v.reason instanceof Error?v.reason.message:String(v.reason),F.status==="fulfilled"){const M=F.value.files,P=u?.trim().toLowerCase(),T=P?M.filter(N=>N.name.toLowerCase().includes(P)||N.path.toLowerCase().includes(P)):M;i(T)}b(R),E&&p(!1)},[a,c,u]);return s.useEffect(()=>(m.current&&clearTimeout(m.current),m.current=setTimeout(()=>{j()},300),()=>{m.current&&clearTimeout(m.current)}),[j]),s.useEffect(()=>(j(),()=>{f.current&&f.current.abort()}),[]),{documents:x,projectFiles:h,loading:o,error:k,refresh:j}}function ke(n,c){const[u,a]=s.useState([]),[x,l]=s.useState(!0),[h,i]=s.useState(null),o=s.useRef(null),p=s.useRef(!1),k=c?.showHidden??!1,b=s.useCallback(async f=>{o.current&&o.current.abort();const g=new AbortController;o.current=g;const m=!p.current;m&&l(!0),i(null);try{const j=await K(n,{showHidden:f?.showHidden??k});if(g.signal.aborted)return;a(j.files),p.current=!0}catch(j){if(g.signal.aborted)return;i(j instanceof Error?j.message:String(j))}finally{!g.signal.aborted&&m&&l(!1)}},[n,k]);return s.useEffect(()=>(p.current=!1,b({showHidden:k}),()=>{o.current&&o.current.abort()}),[b,k]),{files:u,loading:x,error:h,refresh:b}}const be=768;function X(n){return n?new Date(n).toLocaleString():""}function ge(n){return n<1024?`${n} B`:n<1024*1024?`${(n/1024).toFixed(n>=10*1024?0:1)} KB`:`${(n/(1024*1024)).toFixed(1)} MB`}function ve(n,c=200){return n.length<=c?n:`${n.substring(0,c)}…`}function Ne({document:n,renderMarkdown:c,onToggleMarkdown:u}){const[a,x]=s.useState(!1),l=ve(n.content),h=n.content.length>200;return e.jsxs("div",{className:"document-card",children:[e.jsxs("div",{className:"document-card-header",children:[e.jsxs("div",{className:"document-card-key",children:[e.jsx(z,{size:14}),e.jsx("span",{className:"document-card-key-text",children:n.key}),e.jsxs("span",{className:"document-card-revision-badge",children:["v",n.revision]})]}),e.jsx("div",{className:"document-card-actions",children:e.jsx("button",{className:"btn btn-sm document-card-expand-btn",onClick:()=>x(i=>!i),title:a?"Collapse":"Expand","aria-label":a?"Collapse content":"Expand content",children:a?e.jsx(xe,{size:14}):e.jsx(V,{size:14})})})]}),e.jsxs("div",{className:"document-card-meta",children:[e.jsx("span",{className:"document-card-author",children:n.author}),e.jsx("span",{className:"document-card-separator",children:"·"}),e.jsx("span",{className:"document-card-date",children:X(n.updatedAt)})]}),e.jsxs("div",{className:`document-card-content${a?" document-card-content--expanded":""}`,children:[a?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"document-card-content-header",children:e.jsx("button",{className:"btn btn-sm document-mode-toggle",onClick:u,"aria-label":c?"Switch to plain text":"Switch to markdown","aria-pressed":c,title:c?"Switch to plain text":"Switch to markdown",children:c?"Markdown":"Plain"})}),c?e.jsx("div",{className:"document-card-content-markdown",children:e.jsx("div",{className:"markdown-body",children:e.jsx(W,{remarkPlugins:[_],children:n.content})})}):e.jsx("pre",{className:"document-card-content-text",children:n.content})]}):e.jsx("p",{className:"document-card-preview",children:l}),h&&!a&&e.jsx("p",{className:"document-card-preview-truncated",children:"…"})]})]})}function Se({taskId:n,taskTitle:c,documents:u,onOpenTask:a,renderMarkdownStates:x,onToggleMarkdown:l}){const[h,i]=s.useState(!1);return e.jsxs("div",{className:"documents-group",children:[e.jsxs("div",{className:"documents-group-header",children:[e.jsxs("button",{className:"documents-group-toggle-btn",onClick:()=>i(o=>!o),"aria-expanded":h,"aria-label":`${h?"Collapse":"Expand"} documents for task ${n}`,children:[e.jsx("span",{className:"documents-group-toggle","aria-hidden":"true",children:h?e.jsx(V,{size:16}):e.jsx(je,{size:16})}),e.jsx("span",{className:"documents-group-task-id",children:n}),e.jsx("span",{className:"documents-group-task-title",children:c||"Untitled"})]}),e.jsxs("span",{className:"documents-group-count",children:[u.length," doc",u.length!==1?"s":""]}),e.jsx("button",{className:"documents-group-task-link",onClick:()=>a(n),"aria-label":`Open task ${n}: ${c||"Untitled"}`,children:"Open task"})]}),h&&e.jsx("div",{className:"documents-group-content",children:u.map(o=>e.jsx(Ne,{document:o,renderMarkdown:x.get(o.id)??!1,onToggleMarkdown:()=>l(o.id)},o.id))})]})}function ye({projectId:n,addToast:c,onOpenDetail:u}){const[a,x]=s.useState("project"),[l,h]=s.useState(""),[i,o]=s.useState(null),[p,k]=s.useState(!1),[b,f]=s.useState(null),[g,m]=s.useState(!1),[j,C]=s.useState(null),[E,L]=s.useState(!1),y=s.useRef(0),v=s.useRef(!1),[F,R]=s.useState(!1),[M,P]=s.useState(new Map),T=a==="tasks"?l.trim():"",{documents:N,loading:D,error:J,refresh:B}=we({projectId:n,searchQuery:T||void 0,includeProjectFiles:!1}),{files:S,loading:$,error:Y,refresh:O}=ke(n,{showHidden:p});s.useEffect(()=>{const t=()=>{L(window.innerWidth<=be)};return t(),window.addEventListener("resize",t),()=>{window.removeEventListener("resize",t)}},[]),s.useEffect(()=>{v.current=!1,x("project"),o(null),k(!1),f(null),C(null),m(!1),R(!1),P(new Map)},[n]),s.useEffect(()=>{v.current||D||$||(S.length>0?x("project"):N.length>0&&x("tasks"),v.current=!0)},[N.length,D,S.length,$]);const H=s.useMemo(()=>{const t=new Map;for(const r of N){const d=t.get(r.taskId)||[];t.set(r.taskId,[...d,r])}return Array.from(t.entries()).map(([r,d])=>{const w=[...d].sort((re,ce)=>ce.updatedAt.localeCompare(re.updatedAt));return{taskId:r,taskTitle:w[0]?.taskTitle,documents:w,latestUpdated:w[0]?.updatedAt??""}}).sort((r,d)=>d.latestUpdated.localeCompare(r.latestUpdated))},[N]),A=s.useMemo(()=>{const t=l.trim().toLowerCase();return t?S.filter(r=>{const d=r.path.toLowerCase(),w=r.name.toLowerCase();return d.includes(t)||w.includes(t)}):S},[S,l]);s.useEffect(()=>{if(!i)return;S.some(r=>r.path===i.path)||(o(null),f(null),C(null),m(!1))},[S,i]);const Z=s.useCallback(t=>{h(t.target.value)},[]),I=s.useCallback(()=>{h("")},[]),Q=s.useCallback(t=>{x(t)},[]),ee=s.useCallback(async t=>{try{const r=await le(t,n);u(r)}catch{c(`Failed to open task ${t}`,"error")}},[n,u,c]),se=s.useCallback(async t=>{o(t),m(!0),C(null),f(null);const r=y.current+1;y.current=r;try{const d=await ie("project",t.path,n);if(y.current!==r)return;f(d.content)}catch(d){if(y.current!==r)return;const w=d instanceof Error?d.message:`Failed to open ${t.path}`;C(w),c(w,"error")}finally{y.current===r&&m(!1)}},[n,c]),te=s.useCallback(()=>{o(null),f(null),C(null),m(!1)},[]),ne=s.useCallback(t=>{P(r=>{const d=new Map(r),w=d.get(t)??!1;return d.set(t,!w),d})},[]),U=a==="project"?Y:J,ae=s.useCallback(async()=>{if(a==="project"){await O();return}await B()},[a,O,B]),q=a==="project"?A.length:N.length,G=a==="project"?"Search project markdown files…":"Search task documents…";return e.jsxs("div",{className:"documents-view",children:[e.jsxs("div",{className:"documents-view-header",children:[e.jsxs("div",{className:"documents-view-title-row",children:[e.jsxs("h2",{className:"documents-view-title",children:[e.jsx(z,{size:20}),"Documents"]}),e.jsxs("span",{className:"documents-view-count",children:[q," result",q!==1?"s":""]})]}),e.jsxs("div",{className:"documents-controls-row",children:[e.jsxs("div",{className:"documents-tab-bar",role:"tablist","aria-label":"Documents sections",children:[e.jsxs("button",{className:`btn documents-tab${a==="project"?" active":""}`,role:"tab","aria-selected":a==="project","aria-label":"Show project markdown files",onClick:()=>Q("project"),children:["Project Files",e.jsx("span",{className:"documents-tab-count",children:S.length})]}),e.jsxs("button",{className:`btn documents-tab${a==="tasks"?" active":""}`,role:"tab","aria-selected":a==="tasks","aria-label":"Show task documents",onClick:()=>Q("tasks"),children:["Task Documents",e.jsx("span",{className:"documents-tab-count",children:H.length})]})]}),a==="project"&&e.jsxs("button",{className:"btn btn-sm documents-hidden-toggle",onClick:()=>k(t=>!t),"aria-pressed":p,"aria-label":p?"Hide hidden project files":"Show hidden project files",title:p?"Hide hidden files":"Show hidden files",children:[p?e.jsx(de,{size:14}):e.jsx(ue,{size:14}),p?"Hide Hidden":"Show Hidden"]}),e.jsxs("div",{className:"documents-search",children:[e.jsx(me,{size:16,className:"documents-search-icon"}),e.jsx("input",{type:"text",className:"documents-search-input",placeholder:G,value:l,onChange:Z,"aria-label":G}),l&&e.jsx("button",{className:"documents-search-clear",onClick:I,"aria-label":"Clear search",children:e.jsx(he,{size:16})})]})]})]}),e.jsx("div",{className:"documents-view-content",children:U?e.jsxs("div",{className:"documents-view-error",children:[e.jsxs("p",{children:["Failed to load ",a==="project"?"project files":"task documents",": ",U]}),e.jsxs("button",{className:"btn btn-primary",onClick:()=>void ae(),"aria-label":"Retry loading documents",children:[e.jsx(pe,{size:16}),"Retry"]})]}):a==="project"?$&&S.length===0?e.jsx("div",{className:"documents-view-loading",children:e.jsx("p",{children:"Loading project markdown files…"})}):A.length===0?e.jsx("div",{className:"documents-view-empty",children:l.trim()?e.jsxs("p",{children:['No project markdown files match "',l.trim(),'".']}):e.jsxs(e.Fragment,{children:[e.jsx(z,{size:48,className:"documents-view-empty-icon"}),e.jsx("p",{children:"No Markdown files found in this project."})]})}):e.jsxs("div",{className:`documents-project-layout${E?" documents-project-layout--mobile":""}`,children:[(!E||!i)&&e.jsx("aside",{className:"documents-view-sidebar","aria-label":"Project markdown files",children:e.jsx("ul",{className:"markdown-file-list",children:A.map(t=>{const r=i?.path===t.path;return e.jsx("li",{className:"markdown-file-list-item",children:e.jsxs("button",{className:`markdown-file-item${r?" markdown-file-item--selected":""}`,onClick:()=>void se(t),"aria-label":`Open ${t.path}`,"aria-current":r?"true":void 0,children:[e.jsx("span",{className:"markdown-file-item-name",children:t.name}),e.jsx("span",{className:"markdown-file-item-path",children:t.path}),e.jsxs("span",{className:"markdown-file-item-meta",children:[ge(t.size)," · ",X(t.mtime)]})]})},t.path)})})}),(!E||i)&&e.jsxs("section",{className:"documents-view-main","aria-label":"Project file content preview",children:[E&&i&&e.jsxs("button",{className:"btn btn-sm documents-mobile-back",onClick:te,"aria-label":"Back to project files list",children:[e.jsx(fe,{size:14}),"Back to files"]}),i?e.jsxs("div",{className:"documents-content-viewer",children:[e.jsxs("div",{className:"documents-content-header",children:[e.jsx("p",{className:"documents-file-path-header",children:i.path}),e.jsx("button",{className:"btn btn-sm document-mode-toggle",onClick:()=>R(t=>!t),"aria-label":F?"Switch to plain text":"Switch to markdown","aria-pressed":F,title:F?"Switch to plain text":"Switch to markdown",children:F?"Markdown":"Plain"})]}),g?e.jsx("p",{className:"documents-content-state",children:"Loading file content…"}):j?e.jsx("p",{className:"documents-content-state documents-content-state--error",children:j}):F?e.jsx("div",{className:"documents-content-markdown",children:e.jsx("div",{className:"markdown-body",children:e.jsx(W,{remarkPlugins:[_],children:b??""})})}):e.jsx("pre",{className:"document-card-content-text documents-content-viewer-text",children:b??""})]}):e.jsx("div",{className:"documents-view-empty",children:e.jsx("p",{children:"Select a Markdown file to view its content."})})]})]}):D&&N.length===0?e.jsx("div",{className:"documents-view-loading",children:e.jsx("p",{children:"Loading task documents…"})}):H.length===0?e.jsx("div",{className:"documents-view-empty",children:l.trim()?e.jsxs("p",{children:['No task documents match "',l.trim(),'".']}):e.jsxs(e.Fragment,{children:[e.jsx(z,{size:48,className:"documents-view-empty-icon"}),e.jsx("p",{children:"No task documents yet."}),e.jsx("p",{className:"documents-view-empty-hint",children:"Documents are created in task detail tabs."})]})}):e.jsx("div",{className:"documents-task-list-wrap",children:e.jsx("div",{className:"documents-view-list",children:H.map(({taskId:t,taskTitle:r,documents:d})=>e.jsx(Se,{taskId:t,taskTitle:r,documents:d,onOpenTask:ee,renderMarkdownStates:M,onToggleMarkdown:ne},t))})})})]})}export{ye as DocumentsView};
@@ -1,4 +1,4 @@
1
- import{r as a,j as s}from"./vendor-react-K0fH_qHe.js";import{c as Q,ah as Z,ai as ss,aj as es,ak as ts,al as is,am as f,X as q,R as w,C as V,an as L,ao as B,ap as as,N as W,aq as ns,ar as rs,as as X}from"./index-D7gT6mCr.js";import{U as P}from"./users-De-vFat1.js";import"./vendor-xterm-DzcZoU0P.js";/**
1
+ import{r as a,j as s}from"./vendor-react-K0fH_qHe.js";import{c as Q,ag as Z,ah as ss,ai as es,aj as ts,ak as is,al as f,X as q,R as w,C as V,am as L,an as B,ao as as,M as W,ap as ns,aq as rs,ar as X}from"./index-CLAHcGnI.js";import{U as P}from"./users-BAsI___L.js";import"./vendor-xterm-DzcZoU0P.js";/**
2
2
  * @license lucide-react v1.7.0 - ISC
3
3
  *
4
4
  * This source code is licensed under the ISC license.
@@ -8,4 +8,4 @@ import{r as a,j as s}from"./vendor-react-K0fH_qHe.js";import{c as Q,ah as Z,ai a
8
8
  *
9
9
  * This source code is licensed under the ISC license.
10
10
  * See the LICENSE file in the root directory of this source tree.
11
- */const os=[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"m19 9-5 5-4-4-3 3",key:"2osh9i"}]],hs=Q("chart-line",os),T=["architecture","quality","workflow","performance","reliability","security","ux","testability","documentation","dependency","features","competitive_analysis","research","trends","other"],Y={quality:"Quality",performance:"Performance",architecture:"Architecture",security:"Security",reliability:"Reliability",ux:"User Experience",testability:"Testability",documentation:"Documentation",dependency:"Dependencies",workflow:"Workflow",other:"Other",features:"Features",competitive_analysis:"Competitive Analysis",research:"Research",trends:"Trends"};function ds(d){const[o,C]=a.useState(()=>T.map(t=>({category:t,label:Y[t]??t,items:[],isLoading:!1,error:null}))),[S,M]=a.useState(!0),[I,E]=a.useState(null),[g,z]=a.useState(null),[F,R]=a.useState(!1),[A,N]=a.useState(null),[D,k]=a.useState(new Map),[$,v]=a.useState(new Map),x=a.useCallback(async()=>{M(!0),E(null);try{const t=await Z({status:void 0,limit:1e3},d),e=new Map;for(const c of T)e.set(c,[]);for(const c of t.insights)if(c.status!=="dismissed"){const y=e.get(c.category)??[];e.set(c.category,[...y,c])}C(T.map(c=>({category:c,label:Y[c]??c,items:e.get(c)??[],isLoading:!1,error:null})));const n=await ss(d);n.runs.length>0&&z(n.runs[0])}catch(t){const e=t instanceof Error?t.message:"Failed to fetch insights";E(e)}finally{M(!1)}},[d]),h=a.useCallback(async()=>{R(!0),N(null);try{const t=await es("manual",void 0,d);z(t),t.status==="completed"?await x():t.status==="failed"&&t.error&&N(t.error)}catch(t){const e=t instanceof Error?t.message:"Failed to generate insights";throw N(e),t}finally{R(!1)}},[d,x]),j=a.useCallback(async t=>{k(e=>{const n=new Map(e);return n.set(t,{running:!0,error:null}),n});try{await ts(t,d),C(e=>e.map(n=>({...n,items:n.items.filter(c=>c.id!==t)}))),k(e=>{const n=new Map(e);return n.set(t,{running:!1,error:null}),n})}catch(e){const n=e instanceof Error?e.message:"Failed to dismiss insight";throw k(c=>{const y=new Map(c);return y.set(t,{running:!1,error:n}),y}),e}},[d]),u=a.useCallback(async t=>{v(e=>{const n=new Map(e);return n.set(t,{running:!0,error:null}),n});try{const e=await is(t,d);return v(n=>{const c=new Map(n);return c.set(t,{running:!1,error:null}),c}),{title:e.suggestedTitle,description:e.suggestedDescription}}catch(e){const n=e instanceof Error?e.message:"Failed to create task";throw v(c=>{const y=new Map(c);return y.set(t,{running:!1,error:n}),y}),e}},[d]),m=a.useMemo(()=>o.reduce((t,e)=>t+e.items.length,0),[o]),p=a.useMemo(()=>0,[o]);return a.useMemo(()=>{x()},[]),{sections:o,loading:S,error:I,latestRun:g,isRunInFlight:F,runError:A,refresh:x,runInsights:h,dismiss:j,createTask:u,dismissStates:D,createTaskStates:$,totalCount:m,dismissedCount:p}}const H={architecture:ls,quality:V,workflow:X,performance:B,reliability:w,security:L,ux:P,testability:rs,documentation:ns,dependency:W,features:as,competitive_analysis:P,research:hs,trends:B,other:f};function ys({projectId:d,addToast:o,onClose:C,onCreateTask:S}){const{sections:M,loading:I,error:E,latestRun:g,isRunInFlight:z,runError:F,refresh:R,runInsights:A,dismiss:N,createTask:D,dismissStates:k,createTaskStates:$,totalCount:v}=ds(d),[x,h]=a.useState(null),[j,u]=a.useState("info"),m=a.useMemo(()=>M.filter(r=>r.items.length>0),[M]),[p,t]=a.useState(null);a.useEffect(()=>{if(m.length===0){p!==null&&t(null);return}p&&m.some(i=>i.category===p)||t(m[0].category)},[m,p]);const e=a.useMemo(()=>m.find(r=>r.category===p)??m[0],[m,p]);a.useEffect(()=>{if(x){const r=setTimeout(()=>h(null),5e3);return()=>clearTimeout(r)}},[x]);const n=a.useCallback(async()=>{try{h("Generating insights..."),u("info"),await A(),h("Insight generation started"),u("success"),o("Insight generation started","success")}catch(r){const i=r instanceof Error?r.message:"Failed to start generation";h(i),u("error"),o(i,"error")}},[A,o]),c=a.useCallback(async(r,i)=>{try{h(`Dismissing "${i}"...`),u("info"),await N(r),h(`Dismissed "${i}"`),u("success"),o(`Insight dismissed: ${i}`,"success")}catch(l){const b=l instanceof Error?l.message:"Failed to dismiss insight";h(b),u("error"),o(b,"error")}},[N,o]),y=a.useCallback(async(r,i)=>{try{h(`Creating task from "${i}"...`),u("info");const l=await D(r);l&&S&&S(l.title,l.description),h(`Task created from "${i}"`),u("success"),o(`Task created: ${l?.title??i}`,"success")}catch(l){const b=l instanceof Error?l.message:"Failed to create task";h(b),u("error"),o(b,"error")}},[D,S,o]),J=r=>{const i=H[r.category]??f,l=e?.category===r.category;return s.jsx("li",{children:s.jsxs("button",{type:"button",className:`insights-category-item${l?" insights-category-item--active":""}`,onClick:()=>t(r.category),"aria-current":l?"true":void 0,"data-testid":`insights-category-${r.category}`,children:[s.jsx(i,{size:16,className:"insights-category-icon"}),s.jsx("span",{className:"insights-category-label",children:r.label}),s.jsx("span",{className:"insights-category-count",children:r.items.length})]})},r.category)},K=()=>{if(!e)return null;const r=H[e.category]??f;return s.jsxs("section",{className:"insights-section","data-testid":`insights-section-${e.category}`,children:[s.jsx("div",{className:"insights-section-header",children:s.jsxs("div",{className:"insights-section-title",children:[s.jsx(r,{size:20,className:"insights-section-icon"}),s.jsx("h3",{children:e.label}),s.jsx("span",{className:"insights-section-count",children:e.items.length})]})}),s.jsx("div",{className:"insights-section-content",children:s.jsx("ul",{className:"insights-list",children:e.items.map(i=>{const l=k.get(i.id),b=$.get(i.id),G=l?.running??!1,_=b?.running??!1,O=e.items.some(U=>k.get(U.id)?.running||$.get(U.id)?.running);return s.jsxs("li",{className:"insight-item","data-insight-id":i.id,children:[s.jsxs("div",{className:"insight-item-header",children:[s.jsx("h4",{className:"insight-item-title",children:i.title}),s.jsxs("div",{className:"insight-item-actions",children:[s.jsx("button",{className:"insight-item-action-btn",onClick:()=>void y(i.id,i.title),disabled:_||O,title:"Create task from this insight","aria-label":"Create task from this insight","data-testid":`create-task-${i.id}`,children:_?s.jsx(w,{size:20,className:"spin"}):s.jsx(W,{size:20})}),s.jsx("button",{className:"insight-item-action-btn",onClick:()=>void c(i.id,i.title),disabled:G||O,title:"Dismiss this insight","aria-label":"Dismiss this insight","data-testid":`dismiss-${i.id}`,children:G?s.jsx(w,{size:20,className:"spin"}):s.jsx(q,{size:20})})]})]}),i.content&&s.jsx("p",{className:"insight-item-content",children:i.content}),s.jsxs("div",{className:"insight-item-meta",children:[s.jsx("span",{className:`insight-item-status insight-item-status--${i.status}`,children:i.status}),i.createdAt&&s.jsxs("span",{className:"insight-item-date",children:[s.jsx(X,{size:12}),new Date(i.createdAt).toLocaleDateString()]})]})]},i.id)})})})]})};return s.jsxs("div",{className:"insights-view","data-testid":"insights-view",children:[s.jsxs("div",{className:"insights-view-header",children:[s.jsxs("div",{className:"insights-view-title",children:[s.jsxs("h2",{children:[s.jsx(f,{size:20}),"Insights"]}),s.jsxs("span",{className:"insights-view-count",children:[v," total"]})]}),s.jsxs("div",{className:"insights-view-actions",children:[C&&s.jsx("button",{className:"btn btn-sm insights-view-close",onClick:C,"aria-label":"Close insights view",title:"Close",children:s.jsx(q,{size:16})}),s.jsxs("button",{className:"btn btn-sm",onClick:()=>void R(),disabled:I,"aria-label":"Refresh insights","data-testid":"refresh-insights",children:[s.jsx(w,{size:14,className:I?"spin":""}),"Refresh"]}),s.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void n(),disabled:z,"aria-label":"Generate new insights","data-testid":"run-insights",children:z?s.jsxs(s.Fragment,{children:[s.jsx(w,{size:14,className:"spin"}),"Generating..."]}):s.jsxs(s.Fragment,{children:[s.jsx(f,{size:14}),"Generate Insights"]})})]})]}),s.jsx("div",{className:"insights-status-region","aria-live":"polite","data-testid":"insights-status",children:x&&s.jsxs("div",{className:`insights-status-message insights-status-message--${j}`,role:j==="error"?"alert":void 0,children:[j==="success"&&s.jsx(V,{size:16}),j==="error"&&s.jsx(L,{size:16}),j==="info"&&s.jsx(f,{size:16}),s.jsx("span",{children:x})]})}),F&&s.jsxs("div",{className:"insights-error-callout",role:"alert","data-testid":"run-error",children:[s.jsx(L,{size:16}),s.jsx("span",{children:F})]}),g&&s.jsx("div",{className:"insights-run-info","data-testid":"latest-run",children:s.jsxs("span",{className:"insights-run-status",children:["Latest run: ",g.status,g.status==="completed"&&s.jsxs(s.Fragment,{children:[" — ",g.insightsCreated," created, ",g.insightsUpdated," updated"]}),g.status==="failed"&&g.error&&s.jsxs(s.Fragment,{children:[" — ",g.error]})]})}),I?s.jsxs("div",{className:"insights-loading","data-testid":"insights-loading",children:[s.jsx(w,{size:24,className:"spin"}),s.jsx("p",{children:"Loading insights..."})]}):E?s.jsxs("div",{className:"insights-error","data-testid":"insights-error",children:[s.jsx(L,{size:24}),s.jsx("p",{children:E}),s.jsx("button",{className:"btn btn-sm",onClick:()=>void R(),children:"Retry"})]}):v===0?s.jsxs("div",{className:"insights-empty","data-testid":"insights-empty",children:[s.jsx(f,{size:48}),s.jsx("h3",{children:"No insights yet"}),s.jsx("p",{children:"Generate insights to get AI-powered recommendations for your project."}),s.jsxs("button",{className:"btn btn-primary",onClick:()=>void n(),children:[s.jsx(f,{size:14}),"Generate First Insights"]})]}):s.jsxs("div",{className:"insights-body",children:[s.jsx("aside",{className:"insights-sidebar","aria-label":"Insight categories",children:s.jsx("ul",{className:"insights-category-list",children:m.map(J)})}),s.jsx("div",{className:"insights-detail",children:K()})]})]})}export{ys as InsightsView};
11
+ */const os=[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"m19 9-5 5-4-4-3 3",key:"2osh9i"}]],hs=Q("chart-line",os),T=["architecture","quality","workflow","performance","reliability","security","ux","testability","documentation","dependency","features","competitive_analysis","research","trends","other"],Y={quality:"Quality",performance:"Performance",architecture:"Architecture",security:"Security",reliability:"Reliability",ux:"User Experience",testability:"Testability",documentation:"Documentation",dependency:"Dependencies",workflow:"Workflow",other:"Other",features:"Features",competitive_analysis:"Competitive Analysis",research:"Research",trends:"Trends"};function ds(d){const[o,C]=a.useState(()=>T.map(t=>({category:t,label:Y[t]??t,items:[],isLoading:!1,error:null}))),[S,M]=a.useState(!0),[I,E]=a.useState(null),[g,z]=a.useState(null),[F,R]=a.useState(!1),[A,k]=a.useState(null),[D,N]=a.useState(new Map),[$,v]=a.useState(new Map),x=a.useCallback(async()=>{M(!0),E(null);try{const t=await Z({status:void 0,limit:1e3},d),e=new Map;for(const c of T)e.set(c,[]);for(const c of t.insights)if(c.status!=="dismissed"){const y=e.get(c.category)??[];e.set(c.category,[...y,c])}C(T.map(c=>({category:c,label:Y[c]??c,items:e.get(c)??[],isLoading:!1,error:null})));const n=await ss(d);n.runs.length>0&&z(n.runs[0])}catch(t){const e=t instanceof Error?t.message:"Failed to fetch insights";E(e)}finally{M(!1)}},[d]),h=a.useCallback(async()=>{R(!0),k(null);try{const t=await es("manual",void 0,d);z(t),t.status==="completed"?await x():t.status==="failed"&&t.error&&k(t.error)}catch(t){const e=t instanceof Error?t.message:"Failed to generate insights";throw k(e),t}finally{R(!1)}},[d,x]),j=a.useCallback(async t=>{N(e=>{const n=new Map(e);return n.set(t,{running:!0,error:null}),n});try{await ts(t,d),C(e=>e.map(n=>({...n,items:n.items.filter(c=>c.id!==t)}))),N(e=>{const n=new Map(e);return n.set(t,{running:!1,error:null}),n})}catch(e){const n=e instanceof Error?e.message:"Failed to dismiss insight";throw N(c=>{const y=new Map(c);return y.set(t,{running:!1,error:n}),y}),e}},[d]),u=a.useCallback(async t=>{v(e=>{const n=new Map(e);return n.set(t,{running:!0,error:null}),n});try{const e=await is(t,d);return v(n=>{const c=new Map(n);return c.set(t,{running:!1,error:null}),c}),{title:e.suggestedTitle,description:e.suggestedDescription}}catch(e){const n=e instanceof Error?e.message:"Failed to create task";throw v(c=>{const y=new Map(c);return y.set(t,{running:!1,error:n}),y}),e}},[d]),m=a.useMemo(()=>o.reduce((t,e)=>t+e.items.length,0),[o]),p=a.useMemo(()=>0,[o]);return a.useMemo(()=>{x()},[]),{sections:o,loading:S,error:I,latestRun:g,isRunInFlight:F,runError:A,refresh:x,runInsights:h,dismiss:j,createTask:u,dismissStates:D,createTaskStates:$,totalCount:m,dismissedCount:p}}const H={architecture:ls,quality:V,workflow:X,performance:B,reliability:w,security:L,ux:P,testability:rs,documentation:ns,dependency:W,features:as,competitive_analysis:P,research:hs,trends:B,other:f};function ys({projectId:d,addToast:o,onClose:C,onCreateTask:S}){const{sections:M,loading:I,error:E,latestRun:g,isRunInFlight:z,runError:F,refresh:R,runInsights:A,dismiss:k,createTask:D,dismissStates:N,createTaskStates:$,totalCount:v}=ds(d),[x,h]=a.useState(null),[j,u]=a.useState("info"),m=a.useMemo(()=>M.filter(r=>r.items.length>0),[M]),[p,t]=a.useState(null);a.useEffect(()=>{if(m.length===0){p!==null&&t(null);return}p&&m.some(i=>i.category===p)||t(m[0].category)},[m,p]);const e=a.useMemo(()=>m.find(r=>r.category===p)??m[0],[m,p]);a.useEffect(()=>{if(x){const r=setTimeout(()=>h(null),5e3);return()=>clearTimeout(r)}},[x]);const n=a.useCallback(async()=>{try{h("Generating insights..."),u("info"),await A(),h("Insight generation started"),u("success"),o("Insight generation started","success")}catch(r){const i=r instanceof Error?r.message:"Failed to start generation";h(i),u("error"),o(i,"error")}},[A,o]),c=a.useCallback(async(r,i)=>{try{h(`Dismissing "${i}"...`),u("info"),await k(r),h(`Dismissed "${i}"`),u("success"),o(`Insight dismissed: ${i}`,"success")}catch(l){const b=l instanceof Error?l.message:"Failed to dismiss insight";h(b),u("error"),o(b,"error")}},[k,o]),y=a.useCallback(async(r,i)=>{try{h(`Creating task from "${i}"...`),u("info");const l=await D(r);l&&S&&S(l.title,l.description),h(`Task created from "${i}"`),u("success"),o(`Task created: ${l?.title??i}`,"success")}catch(l){const b=l instanceof Error?l.message:"Failed to create task";h(b),u("error"),o(b,"error")}},[D,S,o]),J=r=>{const i=H[r.category]??f,l=e?.category===r.category;return s.jsx("li",{children:s.jsxs("button",{type:"button",className:`insights-category-item${l?" insights-category-item--active":""}`,onClick:()=>t(r.category),"aria-current":l?"true":void 0,"data-testid":`insights-category-${r.category}`,children:[s.jsx(i,{size:16,className:"insights-category-icon"}),s.jsx("span",{className:"insights-category-label",children:r.label}),s.jsx("span",{className:"insights-category-count",children:r.items.length})]})},r.category)},K=()=>{if(!e)return null;const r=H[e.category]??f;return s.jsxs("section",{className:"insights-section","data-testid":`insights-section-${e.category}`,children:[s.jsx("div",{className:"insights-section-header",children:s.jsxs("div",{className:"insights-section-title",children:[s.jsx(r,{size:20,className:"insights-section-icon"}),s.jsx("h3",{children:e.label}),s.jsx("span",{className:"insights-section-count",children:e.items.length})]})}),s.jsx("div",{className:"insights-section-content",children:s.jsx("ul",{className:"insights-list",children:e.items.map(i=>{const l=N.get(i.id),b=$.get(i.id),G=l?.running??!1,_=b?.running??!1,O=e.items.some(U=>N.get(U.id)?.running||$.get(U.id)?.running);return s.jsxs("li",{className:"insight-item","data-insight-id":i.id,children:[s.jsxs("div",{className:"insight-item-header",children:[s.jsx("h4",{className:"insight-item-title",children:i.title}),s.jsxs("div",{className:"insight-item-actions",children:[s.jsx("button",{className:"insight-item-action-btn",onClick:()=>void y(i.id,i.title),disabled:_||O,title:"Create task from this insight","aria-label":"Create task from this insight","data-testid":`create-task-${i.id}`,children:_?s.jsx(w,{size:20,className:"spin"}):s.jsx(W,{size:20})}),s.jsx("button",{className:"insight-item-action-btn",onClick:()=>void c(i.id,i.title),disabled:G||O,title:"Dismiss this insight","aria-label":"Dismiss this insight","data-testid":`dismiss-${i.id}`,children:G?s.jsx(w,{size:20,className:"spin"}):s.jsx(q,{size:20})})]})]}),i.content&&s.jsx("p",{className:"insight-item-content",children:i.content}),s.jsxs("div",{className:"insight-item-meta",children:[s.jsx("span",{className:`insight-item-status insight-item-status--${i.status}`,children:i.status}),i.createdAt&&s.jsxs("span",{className:"insight-item-date",children:[s.jsx(X,{size:12}),new Date(i.createdAt).toLocaleDateString()]})]})]},i.id)})})})]})};return s.jsxs("div",{className:"insights-view","data-testid":"insights-view",children:[s.jsxs("div",{className:"insights-view-header",children:[s.jsxs("div",{className:"insights-view-title",children:[s.jsxs("h2",{children:[s.jsx(f,{size:20}),"Insights"]}),s.jsxs("span",{className:"insights-view-count",children:[v," total"]})]}),s.jsxs("div",{className:"insights-view-actions",children:[C&&s.jsx("button",{className:"btn btn-sm insights-view-close",onClick:C,"aria-label":"Close insights view",title:"Close",children:s.jsx(q,{size:16})}),s.jsxs("button",{className:"btn btn-sm",onClick:()=>void R(),disabled:I,"aria-label":"Refresh insights","data-testid":"refresh-insights",children:[s.jsx(w,{size:14,className:I?"spin":""}),"Refresh"]}),s.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void n(),disabled:z,"aria-label":"Generate new insights","data-testid":"run-insights",children:z?s.jsxs(s.Fragment,{children:[s.jsx(w,{size:14,className:"spin"}),"Generating..."]}):s.jsxs(s.Fragment,{children:[s.jsx(f,{size:14}),"Generate Insights"]})})]})]}),s.jsx("div",{className:"insights-status-region","aria-live":"polite","data-testid":"insights-status",children:x&&s.jsxs("div",{className:`insights-status-message insights-status-message--${j}`,role:j==="error"?"alert":void 0,children:[j==="success"&&s.jsx(V,{size:16}),j==="error"&&s.jsx(L,{size:16}),j==="info"&&s.jsx(f,{size:16}),s.jsx("span",{children:x})]})}),F&&s.jsxs("div",{className:"insights-error-callout",role:"alert","data-testid":"run-error",children:[s.jsx(L,{size:16}),s.jsx("span",{children:F})]}),g&&s.jsx("div",{className:"insights-run-info","data-testid":"latest-run",children:s.jsxs("span",{className:"insights-run-status",children:["Latest run: ",g.status,g.status==="completed"&&s.jsxs(s.Fragment,{children:[" — ",g.insightsCreated," created, ",g.insightsUpdated," updated"]}),g.status==="failed"&&g.error&&s.jsxs(s.Fragment,{children:[" — ",g.error]})]})}),I?s.jsxs("div",{className:"insights-loading","data-testid":"insights-loading",children:[s.jsx(w,{size:24,className:"spin"}),s.jsx("p",{children:"Loading insights..."})]}):E?s.jsxs("div",{className:"insights-error","data-testid":"insights-error",children:[s.jsx(L,{size:24}),s.jsx("p",{children:E}),s.jsx("button",{className:"btn btn-sm",onClick:()=>void R(),children:"Retry"})]}):v===0?s.jsxs("div",{className:"insights-empty","data-testid":"insights-empty",children:[s.jsx(f,{size:48}),s.jsx("h3",{children:"No insights yet"}),s.jsx("p",{children:"Generate insights to get AI-powered recommendations for your project."}),s.jsxs("button",{className:"btn btn-primary",onClick:()=>void n(),children:[s.jsx(f,{size:14}),"Generate First Insights"]})]}):s.jsxs("div",{className:"insights-body",children:[s.jsx("aside",{className:"insights-sidebar","aria-label":"Insight categories",children:s.jsx("ul",{className:"insights-category-list",children:m.map(J)})}),s.jsx("div",{className:"insights-detail",children:K()})]})]})}export{ys as InsightsView};
@@ -1,2 +1,2 @@
1
- import{r as a,j as e}from"./vendor-react-K0fH_qHe.js";import{u as Ie}from"./SettingsModal-CGWipm3s.js";import{bt as Ee,bu as ke,bv as Le,E as Re,bw as qe,bx as Pe,by as We,bz as we,bA as Me,bB as Te,bC as _e,bD as Oe,bE as Ae,bF as Ue,D as He,bG as Qe,L as w,bH as Fe}from"./index-D7gT6mCr.js";import"./vendor-xterm-DzcZoU0P.js";const _=".fusion/memory/MEMORY.md",$e=5e4,Ye="0 3 * * *",Be="0 4 * * *";function he(i){return{memoryEnabled:i.memoryEnabled!==!1,memoryAutoSummarizeEnabled:i.memoryAutoSummarizeEnabled??!1,memoryAutoSummarizeThresholdChars:i.memoryAutoSummarizeThresholdChars??$e,memoryAutoSummarizeSchedule:i.memoryAutoSummarizeSchedule??Ye,memoryDreamsEnabled:i.memoryDreamsEnabled??!1,memoryDreamsSchedule:i.memoryDreamsSchedule??Be}}function De(i,t){return i.some(c=>c.path===t)?t:i.find(c=>c.path===_)?.path??i[0]?.path??_}function Ge(i={}){const{projectId:t}=i,[c,j]=a.useState(""),[z,M]=a.useState(!0),[C,E]=a.useState(!1),[g,b]=a.useState(!1),[r,x]=a.useState(null),[O,J]=a.useState(!0),[X,I]=a.useState(!1),[v,W]=a.useState(()=>he({})),[A,ee]=a.useState(!0),[ue,U]=a.useState(!1),[o,S]=a.useState([]),[se,L]=a.useState(!0),[m,k]=a.useState(_),[T,u]=a.useState(""),[d,te]=a.useState(!1),[H,p]=a.useState(!1),[ae,Q]=a.useState(!1),[ne,$]=a.useState(!1),[Y,re]=a.useState(!1),[F,D]=a.useState(null),[ye,R]=a.useState(!0),[ge,B]=a.useState(!1),[ie,G]=a.useState(!1),[le,V]=a.useState(null),{status:me,loading:Z,refresh:f}=Ie({projectId:t}),be=a.useCallback(n=>{u(n),p(!0)},[]),N=a.useCallback(async n=>{te(!0);try{const{content:l}=await Ee(n,t);k(n),u(l),p(!1)}finally{te(!1)}},[t]),q=a.useCallback(async()=>{L(!0);try{const{files:n}=await ke(t);if(S(n),n.length===0){k(_),u(""),p(!1);return}const l=De(n,m);l!==m&&await N(l)}finally{L(!1)}},[t,m,N]);a.useEffect(()=>{let n=!1;async function l(){try{const s=await Ue(t);n||(j(s.content),M(!1))}catch{n||(j(""),M(!1))}}return l(),()=>{n=!0}},[t]),a.useEffect(()=>{let n=!1;async function l(){try{const s=await Me(t);n||(x(s.content),I(s.exists),J(!1))}catch{n||(x(null),I(!1),J(!1))}}return l(),()=>{n=!0}},[t]),a.useEffect(()=>{let n=!1;async function l(){ee(!0);try{const s=await He(t);n||W(he(s))}catch{n||W(he({}))}finally{n||ee(!1)}}return l(),()=>{n=!0}},[t]),a.useEffect(()=>{let n=!1;async function l(){L(!0);try{const{files:s}=await ke(t);if(n)return;if(S(s),s.length===0){k(_),u(""),p(!1);return}const h=De(s,m),{content:y}=await Ee(h,t);if(n)return;k(h),u(y),p(!1)}catch{n||(S([]),k(_),u(""),p(!1))}finally{n||L(!1)}}return l(),()=>{n=!0}},[t,m]),a.useEffect(()=>{let n=!1;async function l(){try{const s=await we(t);n||(D(s),R(!1))}catch{n||(D(null),R(!1))}}return l(),()=>{n=!0}},[t]),a.useEffect(()=>{let n=!1;async function l(){try{const s=await Qe(t);n||V(s)}catch{n||V(null)}}return l(),()=>{n=!0}},[t]);const ce=a.useCallback(n=>{j(n),E(!0)},[]),oe=a.useCallback(async()=>{if(C){b(!0);try{await Le(c,t),E(!1)}finally{b(!1)}}},[c,C,t]),xe=a.useCallback(async n=>{U(!0);try{const l=await Re(n,t);W(he(l))}finally{U(!1)}},[t]),pe=a.useCallback(async n=>{await N(n)},[N]),fe=a.useCallback(async()=>{if(H){Q(!0);try{await qe(m,T,t),p(!1),await q()}finally{Q(!1)}}},[T,H,m,t,q]),je=a.useCallback(async()=>{G(!0);try{const n=await Pe(t);return await f(),n}finally{G(!1)}},[t,f]),ve=a.useCallback(async n=>We(n,t),[t]),K=a.useCallback(async()=>{try{const n=await we(t);D(n)}catch{D(null)}},[t]),P=a.useCallback(async()=>{try{const n=await Me(t);x(n.content),I(n.exists)}catch{x(null),I(!1)}},[t]),de=a.useCallback(async n=>{await Te(n,t),await P()},[t,P]),Se=a.useCallback(async()=>{$(!0);try{const n=await _e(t);return await Promise.all([P(),K()]),{success:n.success,summary:n.summary}}finally{$(!1)}},[t,P,K]),Ne=a.useCallback(async()=>{re(!0);try{return await Oe(t)}finally{re(!1)}},[t]),Ce=a.useCallback(async n=>{B(!0);try{const l=n?await Ae(n,t):await Ae(t);if(n){const s=l.path??n;k(s),u(l.content),p(!1),await q();return}j(l.content),E(!0)}finally{B(!1)}},[t,q]);return{workingMemory:c,workingMemoryLoading:z,workingMemoryDirty:C,setWorkingMemory:ce,saveWorkingMemory:oe,savingWorkingMemory:g,insightsContent:r,insightsLoading:O,insightsExists:X,refreshInsights:P,saveInsights:de,memorySettings:v,settingsLoading:A,savingMemorySettings:ue,saveMemorySettings:xe,memoryFiles:o,memoryFilesLoading:se,selectedFilePath:m,selectedFileContent:T,selectedFileLoading:d,selectedFileDirty:H,setSelectedFileContent:be,selectFile:pe,saveSelectedFile:fe,savingSelectedFile:ae,reloadMemoryFiles:q,backendStatus:me,backendLoading:Z,extractInsights:Se,extracting:ne,triggerDreamNow:Ne,dreamRunning:Y,auditReport:F,auditLoading:ye,refreshAudit:K,compactMemory:Ce,compacting:ge,installQmdAction:je,installingQmd:ie,testRetrieval:ve,stats:le}}const Ve={Patterns:"pattern",Principles:"principle",Conventions:"convention",Pitfalls:"pitfall",Context:"context"},Ze={"long-term":"Long-term",daily:"Daily",dreams:"Dreams"},Ke={"long-term":"Curated durable decisions, conventions, constraints, and pitfalls promoted from dreams.",daily:"Raw daily observations, open loops, and running context for dream processing.",dreams:"Synthesized patterns and open loops promoted from daily memory."};function Je(i){if(!i)return[];const t=[],c=i.split(/(?=^## )/m);for(const j of c){const z=j.trim();if(!z)continue;const M=z.match(/^##\s+(.+?)(\n|$)/);if(M){const C=M[1].trim(),E=Ve[C]??C.toLowerCase(),g=z.slice(M[0].length).trim(),b=g.split(`
1
+ import{r as a,j as e}from"./vendor-react-K0fH_qHe.js";import{u as Ie}from"./SettingsModal-eNCZiHa6.js";import{bt as Ee,bu as ke,bv as Le,D as Re,bw as qe,bx as Pe,by as We,bz as we,bA as Me,bB as Te,bC as _e,bD as Oe,bE as Ae,bF as Ue,z as He,bG as Qe,L as w,bH as Fe}from"./index-CLAHcGnI.js";import"./vendor-xterm-DzcZoU0P.js";const _=".fusion/memory/MEMORY.md",$e=5e4,Ye="0 3 * * *",Be="0 4 * * *";function he(i){return{memoryEnabled:i.memoryEnabled!==!1,memoryAutoSummarizeEnabled:i.memoryAutoSummarizeEnabled??!1,memoryAutoSummarizeThresholdChars:i.memoryAutoSummarizeThresholdChars??$e,memoryAutoSummarizeSchedule:i.memoryAutoSummarizeSchedule??Ye,memoryDreamsEnabled:i.memoryDreamsEnabled??!1,memoryDreamsSchedule:i.memoryDreamsSchedule??Be}}function De(i,t){return i.some(c=>c.path===t)?t:i.find(c=>c.path===_)?.path??i[0]?.path??_}function Ge(i={}){const{projectId:t}=i,[c,j]=a.useState(""),[z,M]=a.useState(!0),[C,E]=a.useState(!1),[g,b]=a.useState(!1),[r,x]=a.useState(null),[O,J]=a.useState(!0),[X,I]=a.useState(!1),[v,W]=a.useState(()=>he({})),[A,ee]=a.useState(!0),[ue,U]=a.useState(!1),[o,S]=a.useState([]),[se,L]=a.useState(!0),[m,k]=a.useState(_),[T,u]=a.useState(""),[d,te]=a.useState(!1),[H,p]=a.useState(!1),[ae,Q]=a.useState(!1),[ne,$]=a.useState(!1),[Y,re]=a.useState(!1),[F,D]=a.useState(null),[ye,R]=a.useState(!0),[ge,B]=a.useState(!1),[ie,G]=a.useState(!1),[le,V]=a.useState(null),{status:me,loading:Z,refresh:f}=Ie({projectId:t}),be=a.useCallback(n=>{u(n),p(!0)},[]),N=a.useCallback(async n=>{te(!0);try{const{content:l}=await Ee(n,t);k(n),u(l),p(!1)}finally{te(!1)}},[t]),q=a.useCallback(async()=>{L(!0);try{const{files:n}=await ke(t);if(S(n),n.length===0){k(_),u(""),p(!1);return}const l=De(n,m);l!==m&&await N(l)}finally{L(!1)}},[t,m,N]);a.useEffect(()=>{let n=!1;async function l(){try{const s=await Ue(t);n||(j(s.content),M(!1))}catch{n||(j(""),M(!1))}}return l(),()=>{n=!0}},[t]),a.useEffect(()=>{let n=!1;async function l(){try{const s=await Me(t);n||(x(s.content),I(s.exists),J(!1))}catch{n||(x(null),I(!1),J(!1))}}return l(),()=>{n=!0}},[t]),a.useEffect(()=>{let n=!1;async function l(){ee(!0);try{const s=await He(t);n||W(he(s))}catch{n||W(he({}))}finally{n||ee(!1)}}return l(),()=>{n=!0}},[t]),a.useEffect(()=>{let n=!1;async function l(){L(!0);try{const{files:s}=await ke(t);if(n)return;if(S(s),s.length===0){k(_),u(""),p(!1);return}const h=De(s,m),{content:y}=await Ee(h,t);if(n)return;k(h),u(y),p(!1)}catch{n||(S([]),k(_),u(""),p(!1))}finally{n||L(!1)}}return l(),()=>{n=!0}},[t,m]),a.useEffect(()=>{let n=!1;async function l(){try{const s=await we(t);n||(D(s),R(!1))}catch{n||(D(null),R(!1))}}return l(),()=>{n=!0}},[t]),a.useEffect(()=>{let n=!1;async function l(){try{const s=await Qe(t);n||V(s)}catch{n||V(null)}}return l(),()=>{n=!0}},[t]);const ce=a.useCallback(n=>{j(n),E(!0)},[]),oe=a.useCallback(async()=>{if(C){b(!0);try{await Le(c,t),E(!1)}finally{b(!1)}}},[c,C,t]),xe=a.useCallback(async n=>{U(!0);try{const l=await Re(n,t);W(he(l))}finally{U(!1)}},[t]),pe=a.useCallback(async n=>{await N(n)},[N]),fe=a.useCallback(async()=>{if(H){Q(!0);try{await qe(m,T,t),p(!1),await q()}finally{Q(!1)}}},[T,H,m,t,q]),je=a.useCallback(async()=>{G(!0);try{const n=await Pe(t);return await f(),n}finally{G(!1)}},[t,f]),ve=a.useCallback(async n=>We(n,t),[t]),K=a.useCallback(async()=>{try{const n=await we(t);D(n)}catch{D(null)}},[t]),P=a.useCallback(async()=>{try{const n=await Me(t);x(n.content),I(n.exists)}catch{x(null),I(!1)}},[t]),de=a.useCallback(async n=>{await Te(n,t),await P()},[t,P]),Se=a.useCallback(async()=>{$(!0);try{const n=await _e(t);return await Promise.all([P(),K()]),{success:n.success,summary:n.summary}}finally{$(!1)}},[t,P,K]),Ne=a.useCallback(async()=>{re(!0);try{return await Oe(t)}finally{re(!1)}},[t]),Ce=a.useCallback(async n=>{B(!0);try{const l=n?await Ae(n,t):await Ae(t);if(n){const s=l.path??n;k(s),u(l.content),p(!1),await q();return}j(l.content),E(!0)}finally{B(!1)}},[t,q]);return{workingMemory:c,workingMemoryLoading:z,workingMemoryDirty:C,setWorkingMemory:ce,saveWorkingMemory:oe,savingWorkingMemory:g,insightsContent:r,insightsLoading:O,insightsExists:X,refreshInsights:P,saveInsights:de,memorySettings:v,settingsLoading:A,savingMemorySettings:ue,saveMemorySettings:xe,memoryFiles:o,memoryFilesLoading:se,selectedFilePath:m,selectedFileContent:T,selectedFileLoading:d,selectedFileDirty:H,setSelectedFileContent:be,selectFile:pe,saveSelectedFile:fe,savingSelectedFile:ae,reloadMemoryFiles:q,backendStatus:me,backendLoading:Z,extractInsights:Se,extracting:ne,triggerDreamNow:Ne,dreamRunning:Y,auditReport:F,auditLoading:ye,refreshAudit:K,compactMemory:Ce,compacting:ge,installQmdAction:je,installingQmd:ie,testRetrieval:ve,stats:le}}const Ve={Patterns:"pattern",Principles:"principle",Conventions:"convention",Pitfalls:"pitfall",Context:"context"},Ze={"long-term":"Long-term",daily:"Daily",dreams:"Dreams"},Ke={"long-term":"Curated durable decisions, conventions, constraints, and pitfalls promoted from dreams.",daily:"Raw daily observations, open loops, and running context for dream processing.",dreams:"Synthesized patterns and open loops promoted from daily memory."};function Je(i){if(!i)return[];const t=[],c=i.split(/(?=^## )/m);for(const j of c){const z=j.trim();if(!z)continue;const M=z.match(/^##\s+(.+?)(\n|$)/);if(M){const C=M[1].trim(),E=Ve[C]??C.toLowerCase(),g=z.slice(M[0].length).trim(),b=g.split(`
2
2
  `).map(r=>r.replace(/^-\s+/,"").trim()).filter(r=>r.length>0&&(r.startsWith("- ")||r.startsWith("* ")));(b.length>0||g.length>0)&&t.push({name:C,key:E,items:b.length>0?b:g.length>0?[g]:[],expanded:!0})}}return t}function Xe(i){if(!i)return null;const t=i.match(/##\s+Last\s+Updated:\s*(\d{4}-\d{2}-\d{2})/i);return t?t[1]:null}function es(i){return i.reduce((t,c)=>t+c.items.length,0)}function ss(i){switch(i){case"file":return"File (.fusion/memory/)";case"readonly":return"Read-Only";case"qmd":return"QMD (Quantized Memory Distillation)";default:return i}}function ts(i){switch(i){case"healthy":return"Healthy";case"warning":return"Warning";case"issues":return"Issues Found"}}function ls({projectId:i,addToast:t}){const[c,j]=a.useState("working"),[z,M]=a.useState(new Set),[C,E]=a.useState(!1),[g,b]=a.useState(null),[r,x]=a.useState({memoryEnabled:!0,memoryAutoSummarizeEnabled:!1,memoryAutoSummarizeThresholdChars:5e4,memoryAutoSummarizeSchedule:"0 3 * * *",memoryDreamsEnabled:!1,memoryDreamsSchedule:"0 4 * * *"}),[O,J]=a.useState(""),[X,I]=a.useState(!1),[v,W]=a.useState(null),{insightsContent:A,insightsLoading:ee,insightsExists:ue,saveInsights:U,memorySettings:o,settingsLoading:S,saveMemorySettings:se,savingMemorySettings:L,backendStatus:m,backendLoading:k,extractInsights:T,extracting:u,auditReport:d,auditLoading:te,refreshAudit:H,compactMemory:p,compacting:ae,installQmdAction:Q,installingQmd:ne,testRetrieval:$,memoryFiles:Y,memoryFilesLoading:re,selectedFilePath:F,selectedFileContent:D,selectedFileLoading:ye,selectedFileDirty:R,setSelectedFileContent:ge,selectFile:B,saveSelectedFile:ie,savingSelectedFile:G,reloadMemoryFiles:le,triggerDreamNow:V,dreamRunning:me}=Ge({projectId:i});a.useEffect(()=>{x(o)},[o]);const Z=a.useMemo(()=>r.memoryEnabled!==o.memoryEnabled||r.memoryAutoSummarizeEnabled!==o.memoryAutoSummarizeEnabled||r.memoryAutoSummarizeThresholdChars!==o.memoryAutoSummarizeThresholdChars||r.memoryAutoSummarizeSchedule!==o.memoryAutoSummarizeSchedule||r.memoryDreamsEnabled!==o.memoryDreamsEnabled||r.memoryDreamsSchedule!==o.memoryDreamsSchedule,[r,o]),f=a.useMemo(()=>Y.find(s=>s.path===F),[Y,F]),be=f?Ke[f.layer]:"Edits the selected memory file.",N=a.useMemo(()=>Je(A),[A]),q=a.useMemo(()=>es(N),[N]),ce=a.useMemo(()=>Xe(A),[A]),oe=a.useCallback(s=>{M(h=>{const y=new Set(h);return y.has(s)?y.delete(s):y.add(s),y})},[]),xe=a.useCallback(async s=>{try{await B(s)}catch{t("Failed to load memory file","error")}},[B,t]),pe=a.useCallback(async()=>{try{await ie(),t("Memory saved","success")}catch{t("Failed to save memory","error")}},[ie,t]),fe=a.useCallback(async()=>{if(!Z)return;const s={};r.memoryEnabled!==o.memoryEnabled&&(s.memoryEnabled=r.memoryEnabled),r.memoryAutoSummarizeEnabled!==o.memoryAutoSummarizeEnabled&&(s.memoryAutoSummarizeEnabled=r.memoryAutoSummarizeEnabled),r.memoryAutoSummarizeThresholdChars!==o.memoryAutoSummarizeThresholdChars&&(s.memoryAutoSummarizeThresholdChars=r.memoryAutoSummarizeThresholdChars),r.memoryAutoSummarizeSchedule!==o.memoryAutoSummarizeSchedule&&(s.memoryAutoSummarizeSchedule=r.memoryAutoSummarizeSchedule),r.memoryDreamsEnabled!==o.memoryDreamsEnabled&&(s.memoryDreamsEnabled=r.memoryDreamsEnabled),r.memoryDreamsSchedule!==o.memoryDreamsSchedule&&(s.memoryDreamsSchedule=r.memoryDreamsSchedule);try{await se(s),t("Memory settings saved","success")}catch{t("Failed to save memory settings","error")}},[Z,r,o,se,t]),je=a.useCallback(async()=>{try{const s=await Q();t(s.qmdAvailable?"qmd installed successfully":"qmd install finished, but qmd is still unavailable",s.qmdAvailable?"success":"info")}catch{t("Failed to install qmd","error")}},[Q,t]),ve=a.useCallback(async()=>{I(!0),W(null);try{const s=await $(O);W(s),t(s.qmdAvailable?"Memory retrieval test complete":"qmd is not installed; local fallback was used",s.qmdAvailable?"success":"info")}catch{t("Failed to test memory retrieval","error")}finally{I(!1)}},[O,$,t]),K=a.useCallback(async()=>{try{await V(),t("Dream processing completed","success"),await le()}catch(s){t(s instanceof Error?s.message:"Failed to run dream processing","error")}},[V,le,t]),P=a.useCallback(async()=>{try{await p(F),t("Memory file compacted","success")}catch{t("Failed to compact memory","error")}},[p,F,t]),de=a.useCallback(async()=>{try{const s=await T();t(s.summary,"success")}catch(s){t(s instanceof Error?s.message:"Failed to extract insights","error")}},[T,t]),Se=a.useCallback(async()=>{if(g!==null)try{await U(g),E(!1),b(null),t("Insights saved","success")}catch{t("Failed to save insights","error")}},[g,U,t]),Ne=a.useCallback(()=>{b(A??""),E(!0)},[A]),Ce=a.useCallback(()=>{E(!1),b(null)},[]),n=!k&&m!==null,l=m?.capabilities?.writable??!1;return e.jsxs("div",{className:"memory-view",children:[e.jsx("div",{className:"memory-view-header",children:e.jsxs("div",{children:[e.jsx("h2",{children:"Memory"}),e.jsx("p",{className:"memory-view-description",children:"Working memory, long-term insights, and engine status"})]})}),e.jsxs("div",{className:"memory-view-tabs",role:"tablist",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":c==="working",className:`memory-view-tab${c==="working"?" memory-view-tab--active":""}`,onClick:()=>j("working"),"data-testid":"memory-tab-working",children:"Working Memory"}),e.jsx("button",{type:"button",role:"tab","aria-selected":c==="insights",className:`memory-view-tab${c==="insights"?" memory-view-tab--active":""}`,onClick:()=>j("insights"),"data-testid":"memory-tab-insights",children:"Insights"}),e.jsx("button",{type:"button",role:"tab","aria-selected":c==="engines",className:`memory-view-tab${c==="engines"?" memory-view-tab--active":""}`,onClick:()=>j("engines"),"data-testid":"memory-tab-engines",children:"Engines"})]}),e.jsxs("div",{className:"memory-view-content",children:[c==="working"&&e.jsxs("div",{className:"memory-working-tab",children:[n&&!l&&e.jsx("div",{className:"memory-readonly-banner",children:"This memory backend is read-only. Changes cannot be saved."}),re||ye?e.jsxs("div",{className:"memory-empty-state",children:[e.jsx(w,{size:20,className:"animate-spin"}),e.jsx("span",{children:"Loading memory file…"})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"memory-editor-section",children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"memoryViewFilePath",children:"Memory File"}),e.jsx("select",{id:"memoryViewFilePath",className:"select",value:F,onChange:s=>{xe(s.target.value)},disabled:R,children:Y.map(s=>e.jsxs("option",{value:s.path,children:[s.label," - ",s.path]},s.path))}),e.jsx("small",{children:R?"Save or discard the current edits before switching files.":"Choose any project memory file to view or edit."})]}),f&&e.jsxs("div",{className:"memory-file-summary",children:[e.jsx("span",{children:Ze[f.layer]}),e.jsx("strong",{children:f.path}),e.jsxs("small",{children:[f.size.toLocaleString()," bytes · updated ",new Date(f.updatedAt).toLocaleString()]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:f?.label||"Memory Editor"}),e.jsx("small",{children:be}),e.jsx("div",{className:"memory-editor-container",children:e.jsx(Fe,{content:D,onChange:ge,readOnly:!l,filePath:F})})]})]}),e.jsxs("div",{className:"memory-action-bar",children:[e.jsxs("span",{className:"memory-char-count",children:[D.length," characters"]}),e.jsx("div",{className:"memory-flex-spacer"}),l&&D.length>0&&e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:P,disabled:ae||R,children:ae?e.jsxs(e.Fragment,{children:[e.jsx(w,{size:14,className:"animate-spin"}),"Compacting…"]}):"Compact Selected File"}),R&&l&&e.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:pe,disabled:G,children:G?e.jsxs(e.Fragment,{children:[e.jsx(w,{size:14,className:"animate-spin"}),"Saving…"]}):"Save"})]}),e.jsxs("div",{className:"memory-config-section",children:[e.jsxs("div",{className:"memory-settings-group",children:[e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"memoryDreamsEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"memoryDreamsEnabled",type:"checkbox",checked:r.memoryDreamsEnabled,onChange:s=>{x(h=>({...h,memoryDreamsEnabled:s.target.checked}))},disabled:!r.memoryEnabled||S}),"Process dreams from daily memory"]}),e.jsx("small",{children:"Turns daily notes into DREAMS.md and promotes reusable lessons into MEMORY.md."})]}),r.memoryEnabled&&r.memoryDreamsEnabled&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"memoryDreamsSchedule",children:"Dream Schedule"}),e.jsx("input",{id:"memoryDreamsSchedule",type:"text",className:"input",value:r.memoryDreamsSchedule,onChange:s=>{x(h=>({...h,memoryDreamsSchedule:s.target.value}))},placeholder:"0 4 * * *",disabled:S}),e.jsx("small",{children:"Cron expression for dream processing."})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("button",{type:"button",className:"btn btn-sm",onClick:K,disabled:me||!r.memoryDreamsEnabled,children:me?e.jsxs(e.Fragment,{children:[e.jsx(w,{size:14,className:"animate-spin"}),"Dreaming…"]}):"Dream Now"}),e.jsx("small",{children:"Manually trigger dream processing now."})]})]})]}),e.jsxs("div",{className:"memory-settings-group",children:[e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"memoryAutoSummarizeEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"memoryAutoSummarizeEnabled",type:"checkbox",checked:r.memoryAutoSummarizeEnabled,onChange:s=>{x(h=>({...h,memoryAutoSummarizeEnabled:s.target.checked}))},disabled:!r.memoryEnabled||S}),"Auto-Summarize Memory"]}),e.jsx("small",{children:"Automatically compact memory when it exceeds the threshold on a schedule"})]}),r.memoryEnabled&&r.memoryAutoSummarizeEnabled&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"memoryAutoSummarizeThresholdChars",children:"Compaction Threshold (chars)"}),e.jsx("input",{id:"memoryAutoSummarizeThresholdChars",type:"number",className:"input",value:r.memoryAutoSummarizeThresholdChars,onChange:s=>{x(h=>({...h,memoryAutoSummarizeThresholdChars:parseInt(s.target.value,10)||5e4}))},min:1e3,disabled:S}),e.jsx("small",{children:"Memory will be compacted when it exceeds this character count"})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"memoryAutoSummarizeSchedule",children:"Schedule (cron)"}),e.jsx("input",{id:"memoryAutoSummarizeSchedule",type:"text",className:"input",value:r.memoryAutoSummarizeSchedule,onChange:s=>{x(h=>({...h,memoryAutoSummarizeSchedule:s.target.value}))},placeholder:"0 3 * * *",disabled:S}),e.jsx("small",{children:"Cron expression for auto-summarize schedule (default: daily at 3 AM)"})]})]})]}),!r.memoryEnabled&&e.jsx("div",{className:"settings-empty-state memory-status-message",children:"Memory is currently disabled. Enable memory tools in Settings to edit these automations."}),Z&&e.jsx("div",{className:"memory-action-bar",children:e.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:fe,disabled:L||S,children:L?e.jsxs(e.Fragment,{children:[e.jsx(w,{size:14,className:"animate-spin"}),"Saving…"]}):"Save Settings"})})]})]})]}),c==="insights"&&e.jsx("div",{className:"memory-insights-tab",children:ee?e.jsxs("div",{className:"memory-empty-state",children:[e.jsx(w,{size:20,className:"animate-spin"}),e.jsx("span",{children:"Loading insights…"})]}):C?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"memory-editor-container",children:e.jsx(Fe,{content:g??"",onChange:b,readOnly:!1,filePath:".fusion/memory/INSIGHTS.md"})}),e.jsxs("div",{className:"memory-action-bar",children:[e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ce,children:"Cancel"}),e.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:Se,children:"Save Insights"})]})]}):!ue||N.length===0?e.jsxs("div",{className:"memory-empty-state",children:[e.jsx("p",{children:"No insights extracted yet."}),e.jsx("p",{children:'Insights are automatically extracted from working memory. Click "Extract Now" to trigger extraction manually.'}),e.jsx("button",{type:"button",className:"btn btn-primary btn-sm memory-empty-extract-button",onClick:de,disabled:u,children:u?e.jsxs(e.Fragment,{children:[e.jsx(w,{size:14,className:"animate-spin"}),"Extracting…"]}):"Extract Now"})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"memory-stats-row",children:[e.jsxs("div",{className:"memory-stat-card",children:[e.jsx("div",{className:"memory-stat-value",children:q}),e.jsx("div",{className:"memory-stat-label",children:"Total Insights"})]}),e.jsxs("div",{className:"memory-stat-card",children:[e.jsx("div",{className:"memory-stat-value",children:N.length}),e.jsx("div",{className:"memory-stat-label",children:"Categories"})]}),ce&&e.jsxs("div",{className:"memory-stat-card",children:[e.jsx("div",{className:"memory-stat-value memory-stat-value--updated",children:ce}),e.jsx("div",{className:"memory-stat-label",children:"Last Updated"})]})]}),e.jsxs("div",{className:"memory-action-bar",children:[e.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:de,disabled:u,children:u?e.jsxs(e.Fragment,{children:[e.jsx(w,{size:14,className:"animate-spin"}),"Extracting…"]}):"Extract Now"}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ne,children:"Edit Raw"})]}),e.jsx("div",{className:"memory-categories-list",children:N.map(s=>{const h=!z.has(s.key);return e.jsxs("div",{className:"memory-category-section",children:[e.jsxs("div",{className:"memory-category-header",onClick:()=>oe(s.key),role:"button",tabIndex:0,onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),oe(s.key))},children:[e.jsx("h4",{children:s.name}),e.jsx("span",{className:"memory-category-count",children:s.items.length})]}),h&&e.jsx("div",{className:"memory-category-items",children:s.items.map((y,ze)=>e.jsx("div",{className:"memory-insight-item",children:y.replace(/^-\s+/,"").replace(/^\*\s+/,"")},ze))})]},s.key)})})]})}),c==="engines"&&e.jsx("div",{className:"memory-engines-tab",children:k||te?e.jsxs("div",{className:"memory-empty-state",children:[e.jsx(w,{size:20,className:"animate-spin"}),e.jsx("span",{children:"Loading engine status…"})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"memory-engine-card memory-qmd-card",children:[e.jsx("h3",{children:"QMD Integration"}),m?.qmdAvailable===!0?e.jsxs("div",{className:"memory-engine-status",children:[e.jsx("span",{className:"memory-health-badge memory-health-badge--healthy",children:"Installed"}),e.jsx("span",{className:"memory-char-count",children:"qmd is available on PATH."})]}):m?.qmdAvailable===!1?e.jsxs("div",{className:"settings-empty-state memory-status-message",children:[e.jsxs("span",{children:["qmd is not installed. Search will use local files. Install indexed retrieval: ",e.jsx("code",{children:m.qmdInstallCommand||"bun install -g @tobilu/qmd"})]}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:je,disabled:ne,children:ne?"Installing…":"Install qmd"})]}):e.jsxs("div",{className:"memory-engine-status",children:[e.jsx("span",{className:"memory-health-badge",children:"Checking"}),e.jsx("span",{className:"memory-char-count",children:"Checking qmd availability…"})]}),e.jsxs("div",{className:"memory-capability-row",children:[m?.capabilities?.readable&&e.jsx("span",{className:"memory-capability-badge",children:"Readable"}),m?.capabilities?.writable&&e.jsx("span",{className:"memory-capability-badge",children:"Writable"}),m?.capabilities?.supportsAtomicWrite&&e.jsx("span",{className:"memory-capability-badge",children:"Atomic Writes"}),m?.capabilities?.persistent&&e.jsx("span",{className:"memory-capability-badge",children:"Persistent"})]})]}),e.jsxs("div",{className:"memory-engine-card memory-retrieval-card",children:[e.jsx("h3",{children:"Test Memory Search"}),e.jsxs("div",{className:"memory-retrieval-input-row",children:[e.jsx("input",{type:"text",className:"input",value:O,onChange:s=>J(s.target.value),placeholder:"Search memory with qmd"}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:ve,disabled:X,children:X?"Testing…":"Test Retrieval"})]}),e.jsx("small",{className:"settings-muted",children:"Runs the same qmd-backed memory_search path agents use."}),v&&e.jsxs("div",{className:"memory-test-result",children:[e.jsxs("strong",{children:[v.results.length," result",v.results.length===1?"":"s"," ",'for "',v.query,'"']}),e.jsxs("small",{children:["qmd ",v.qmdAvailable?"available":"missing"," · ",v.usedFallback?"local fallback used":"qmd path used"]}),v.results.length>0?e.jsx("ul",{children:v.results.map((s,h)=>e.jsxs("li",{children:[e.jsxs("span",{children:[s.path,":",s.lineStart]}),e.jsx("p",{children:s.snippet})]},`${s.path}-${s.lineStart}-${h}`))}):e.jsx("small",{children:"No matching memory found."})]})]}),e.jsxs("div",{className:"memory-engine-card",children:[e.jsx("h3",{children:"Current Backend"}),e.jsx("div",{className:"memory-engine-status",children:e.jsx("span",{className:"memory-emphasis-text",children:ss(m?.currentBackend??"unknown")})}),e.jsxs("div",{className:"memory-capability-row",children:[m?.capabilities?.readable&&e.jsx("span",{className:"memory-capability-badge",children:"Readable"}),m?.capabilities?.writable&&e.jsx("span",{className:"memory-capability-badge",children:"Writable"}),m?.capabilities?.supportsAtomicWrite&&e.jsx("span",{className:"memory-capability-badge",children:"Atomic Writes"}),m?.capabilities?.persistent&&e.jsx("span",{className:"memory-capability-badge",children:"Persistent"})]})]}),d&&e.jsxs("div",{className:"memory-engine-card",children:[e.jsxs("div",{className:"memory-health-header",children:[e.jsx("h3",{children:"Health Status"}),e.jsx("span",{className:`memory-health-badge memory-health-badge--${d.health}`,children:ts(d.health)})]}),e.jsxs("div",{className:"memory-health-grid",children:[e.jsxs("div",{children:[e.jsx("div",{className:"memory-health-label",children:"Working Memory"}),e.jsxs("div",{className:"memory-emphasis-text",children:[d.workingMemory.size," chars"]}),e.jsxs("div",{className:"memory-health-detail",children:[d.workingMemory.sectionCount," sections"]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"memory-health-label",children:"Insights Memory"}),e.jsxs("div",{className:"memory-emphasis-text",children:[d.insightsMemory.size," chars"]}),e.jsxs("div",{className:"memory-health-detail",children:[d.insightsMemory.insightCount," insights"]})]})]}),e.jsxs("div",{className:"memory-health-section",children:[e.jsx("div",{className:"memory-health-label",children:"Last Extraction"}),e.jsx("div",{className:"memory-emphasis-text",children:d.extraction.success?e.jsx("span",{className:"memory-status-text memory-status-text--success",children:"Success"}):e.jsx("span",{className:"memory-status-text memory-status-text--error",children:"Failed"})}),e.jsx("div",{className:"memory-health-detail",children:d.extraction.summary||`${d.extraction.insightCount} insights extracted`})]}),e.jsxs("div",{className:"memory-health-section",children:[e.jsx("div",{className:"memory-health-label",children:"Pruning"}),e.jsx("div",{className:"memory-emphasis-text",children:d.pruning.applied?e.jsx("span",{className:"memory-status-text memory-status-text--warning",children:"Applied"}):e.jsx("span",{className:"memory-status-text memory-status-text--muted",children:"Not needed"})}),d.pruning.applied&&e.jsx("div",{className:"memory-health-detail",children:d.pruning.reason})]})]}),d&&d.checks.length>0&&e.jsxs("div",{className:"memory-engine-card",children:[e.jsx("h3",{children:"Audit Checks"}),e.jsx("div",{children:d.checks.map(s=>e.jsxs("div",{className:"memory-audit-check",children:[e.jsx("span",{className:s.passed?"memory-audit-check-passed":"memory-audit-check-failed",children:s.passed?"✓":"✗"}),e.jsxs("div",{className:"memory-audit-check-content",children:[e.jsx("div",{className:"memory-emphasis-text",children:s.name}),e.jsx("div",{className:"memory-health-detail",children:s.details})]})]},s.id))})]}),e.jsx("div",{className:"memory-action-bar",children:e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>H(),children:"Run Audit"})}),e.jsxs("div",{className:"memory-settings-note",children:[e.jsx("span",{children:"Note: Change backend type in"}),e.jsx("button",{type:"button",className:"memory-settings-note-button",onClick:()=>{t("Open Settings → Memory to change backend type","info")},children:"Settings → Memory"})]})]})})]})]})}export{ls as MemoryView};