@runfusion/fusion 0.24.0 → 0.25.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 (106) hide show
  1. package/dist/bin.js +2254 -1349
  2. package/dist/client/assets/AgentDetailView-ZbHEbYRT.js +18 -0
  3. package/dist/client/assets/{AgentsView-BkB9FiMT.js → AgentsView-B3jYk8Kt.js} +3 -3
  4. package/dist/client/assets/ChatView-DhPkiEGs.js +1 -0
  5. package/dist/client/assets/{DevServerView-BkvtjZBa.js → DevServerView-DyGDEiBP.js} +1 -1
  6. package/dist/client/assets/{DirectoryPicker-BK-KbnhP.js → DirectoryPicker-D5UIeIl6.js} +1 -1
  7. package/dist/client/assets/{DocumentsView-BEg1CQAk.js → DocumentsView-DNHu1T8K.js} +1 -1
  8. package/dist/client/assets/{EvalsView-Berf9bQm.js → EvalsView-CpRobtDi.js} +1 -1
  9. package/dist/client/assets/{ExperimentalAgentOnboardingModal-jcInE50G.js → ExperimentalAgentOnboardingModal-DOY_oZi7.js} +1 -1
  10. package/dist/client/assets/{InsightsView-BX5bSF1J.js → InsightsView-vp0RE8Mg.js} +1 -1
  11. package/dist/client/assets/MemoryView-PSc5lGJt.js +2 -0
  12. package/dist/client/assets/MemoryView-zaXewZzi.css +1 -0
  13. package/dist/client/assets/{NodesView-DLUOBLf6.js → NodesView-DMj6HGeC.js} +1 -1
  14. package/dist/client/assets/{PiExtensionsManager-COlJf0Kx.js → PiExtensionsManager-DL_QcN56.js} +2 -2
  15. package/dist/client/assets/PluginManager-BtYKm8IT.js +1 -0
  16. package/dist/client/assets/{ResearchView-B256Lr8I.js → ResearchView-BhWqfdV0.js} +1 -1
  17. package/dist/client/assets/{SettingsModal-BeA_nQtW.js → SettingsModal-BAgB4_AR.js} +4 -4
  18. package/dist/client/assets/{SettingsModal-yRqM4DV8.js → SettingsModal-CUCyaAyE.js} +1 -1
  19. package/dist/client/assets/{SetupWizardModal-uUZk3TKT.js → SetupWizardModal-BKscasuh.js} +1 -1
  20. package/dist/client/assets/{SkillsView-CP8JX0P_.js → SkillsView-BdELqTy7.js} +1 -1
  21. package/dist/client/assets/{TodoView-DCRIkDZ-.js → TodoView-DFNGBDNV.js} +1 -1
  22. package/dist/client/assets/{folder-open-DHjELt8-.js → folder-open-k1xmUMyr.js} +1 -1
  23. package/dist/client/assets/index-Qq2JOOWx.css +1 -0
  24. package/dist/client/assets/{index-CQyVRLOb.js → index-TFYXEVpn.js} +160 -160
  25. package/dist/client/assets/{star-DYesq1AV.js → star-ne32r3Y4.js} +1 -1
  26. package/dist/client/assets/{upload-DTWF3Db5.js → upload-MS-2Gx53.js} +1 -1
  27. package/dist/client/assets/{users--syrel4l.js → users-C519GSjH.js} +1 -1
  28. package/dist/client/index.html +2 -2
  29. package/dist/client/version.json +1 -1
  30. package/dist/droid-cli/package.json +1 -1
  31. package/dist/extension.js +1370 -629
  32. package/dist/pi-claude-cli/package.json +1 -1
  33. package/dist/plugins/fusion-plugin-cursor-runtime/bundled.js +9 -11
  34. package/dist/plugins/fusion-plugin-cursor-runtime/package.json +1 -1
  35. package/dist/plugins/fusion-plugin-dependency-graph/bundled.js +30 -0
  36. package/dist/plugins/fusion-plugin-dependency-graph/package.json +3 -28
  37. package/dist/plugins/fusion-plugin-droid-runtime/bundled.js +899 -895
  38. package/dist/plugins/fusion-plugin-droid-runtime/package.json +1 -1
  39. package/dist/plugins/fusion-plugin-hermes-runtime/bundled.js +68 -71
  40. package/dist/plugins/fusion-plugin-hermes-runtime/package.json +1 -1
  41. package/dist/plugins/fusion-plugin-openclaw-runtime/bundled.js +47 -50
  42. package/dist/plugins/fusion-plugin-openclaw-runtime/package.json +1 -1
  43. package/dist/plugins/fusion-plugin-paperclip-runtime/bundled.js +155 -109
  44. package/dist/plugins/fusion-plugin-paperclip-runtime/package.json +1 -1
  45. package/dist/plugins/fusion-plugin-reports/package.json +1 -1
  46. package/dist/plugins/fusion-plugin-reports/src/index.ts +49 -3
  47. package/dist/plugins/fusion-plugin-reports/src/report-schema.ts +38 -0
  48. package/dist/plugins/fusion-plugin-reports/src/store/__tests__/report-schema.test.ts +66 -0
  49. package/dist/plugins/fusion-plugin-reports/src/store/__tests__/report-store.test.ts +177 -0
  50. package/dist/plugins/fusion-plugin-reports/src/store/report-store.ts +341 -0
  51. package/dist/plugins/fusion-plugin-reports/src/store/report-types.ts +77 -0
  52. package/dist/plugins/fusion-plugin-roadmap/package.json +1 -1
  53. package/dist/plugins/fusion-plugin-whatsapp-chat/package.json +1 -1
  54. package/package.json +1 -1
  55. package/dist/client/assets/AgentDetailView-gy_5SUj2.js +0 -18
  56. package/dist/client/assets/ChatView-B_-B8fqu.js +0 -1
  57. package/dist/client/assets/MemoryView-CKElJY_3.js +0 -2
  58. package/dist/client/assets/MemoryView-DiajLXby.css +0 -1
  59. package/dist/client/assets/PluginManager-CfW55BF4.js +0 -1
  60. package/dist/client/assets/createLucideIcon-BazL2hk5.js +0 -21
  61. package/dist/client/assets/dashboard-view-BkTMSZYn.css +0 -1
  62. package/dist/client/assets/dashboard-view-CyWN-d02.js +0 -63
  63. package/dist/client/assets/dashboard-view-DdGlfuu-.css +0 -1
  64. package/dist/client/assets/dashboard-view-lR7YYmSC.js +0 -21
  65. package/dist/client/assets/index-CxA2Nn0_.css +0 -1
  66. package/dist/plugins/fusion-plugin-dependency-graph/src/DependencyGraph.css +0 -58
  67. package/dist/plugins/fusion-plugin-dependency-graph/src/DependencyGraph.tsx +0 -301
  68. package/dist/plugins/fusion-plugin-dependency-graph/src/GraphHighlight.css +0 -27
  69. package/dist/plugins/fusion-plugin-dependency-graph/src/GraphTaskNode.css +0 -157
  70. package/dist/plugins/fusion-plugin-dependency-graph/src/GraphTaskNode.tsx +0 -126
  71. package/dist/plugins/fusion-plugin-dependency-graph/src/GraphToolbar.css +0 -35
  72. package/dist/plugins/fusion-plugin-dependency-graph/src/GraphToolbar.tsx +0 -36
  73. package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/DependencyGraph.highlighting.test.tsx +0 -112
  74. package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/DependencyGraph.persistence.test.tsx +0 -115
  75. package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/DependencyGraph.test.tsx +0 -128
  76. package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/GraphTaskNode.drag.test.tsx +0 -82
  77. package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/GraphTaskNode.test.tsx +0 -307
  78. package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/GraphToolbar.test.tsx +0 -60
  79. package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/edges.test.tsx +0 -75
  80. package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/filtering.test.tsx +0 -62
  81. package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/filters.test.ts +0 -78
  82. package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/graphPositionStorage.test.ts +0 -95
  83. package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/host-integration.test.ts +0 -74
  84. package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/index.test.ts +0 -58
  85. package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/interactions.test.tsx +0 -121
  86. package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/layout.test.ts +0 -70
  87. package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/persistence.test.tsx +0 -89
  88. package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/useGraphData.test.ts +0 -86
  89. package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/useGraphInteraction.test.ts +0 -167
  90. package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/useGraphPositions.test.ts +0 -66
  91. package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/useNodeDrag.test.ts +0 -81
  92. package/dist/plugins/fusion-plugin-dependency-graph/src/dashboard-interop.d.ts +0 -35
  93. package/dist/plugins/fusion-plugin-dependency-graph/src/dashboard-view.tsx +0 -19
  94. package/dist/plugins/fusion-plugin-dependency-graph/src/edges.tsx +0 -70
  95. package/dist/plugins/fusion-plugin-dependency-graph/src/filters.ts +0 -8
  96. package/dist/plugins/fusion-plugin-dependency-graph/src/hooks/__tests__/useDependencyChain.test.ts +0 -53
  97. package/dist/plugins/fusion-plugin-dependency-graph/src/hooks/useDependencyChain.ts +0 -60
  98. package/dist/plugins/fusion-plugin-dependency-graph/src/hooks/useGraphPositions.ts +0 -45
  99. package/dist/plugins/fusion-plugin-dependency-graph/src/hooks/useNodeDrag.ts +0 -114
  100. package/dist/plugins/fusion-plugin-dependency-graph/src/index.ts +0 -24
  101. package/dist/plugins/fusion-plugin-dependency-graph/src/layout.ts +0 -91
  102. package/dist/plugins/fusion-plugin-dependency-graph/src/styles/drag.css +0 -15
  103. package/dist/plugins/fusion-plugin-dependency-graph/src/types.ts +0 -21
  104. package/dist/plugins/fusion-plugin-dependency-graph/src/useGraphData.ts +0 -17
  105. package/dist/plugins/fusion-plugin-dependency-graph/src/useGraphInteraction.ts +0 -292
  106. package/dist/plugins/fusion-plugin-dependency-graph/src/utils/graphPositionStorage.ts +0 -65
@@ -0,0 +1 @@
1
+ import{r as s,a as Ns,j as t}from"./vendor-react-K0fH_qHe.js";import{i as at,b1 as Ut,t as Xt,b2 as js,b3 as Ot,b4 as Ms,w as Mt,b5 as Le,b6 as Rs,b7 as As,b8 as Es,b9 as Ts,ba as Ds,bb as Ps,s as Qt,bc as $s,bd as Ls,be as Fs,bf as Is,bg as zs,bh as _s,bi as Us,k as Zt,bj as Os,p as Hs,bk as Bs,bl as Ws,u as Gs,bm as Vs,ab as es,ac as ts,bn as Ks,bo as qs,S as Js,W as kt,P as tt,I as Xe,am as Ys,bp as Ht,bq as Bt,B as nt,a8 as Xs,a9 as Qs,a as Zs,br as en,bs as tn,bt as sn,aQ as nn,bu as an,bv as Wt,bw as rn,h as on,j as Gt,m as cn}from"./index-TFYXEVpn.js";import"./vendor-xterm-DzcZoU0P.js";const Ct="kb-chat-active-session";function Vt(n){const r=typeof n=="string"?n.trim():"",o=r.indexOf("/");return!r||o<=0||o>=r.length-1?{}:{modelProvider:r.slice(0,o),modelId:r.slice(o+1)}}function ln(n){const r=n?.toolCalls;if(!Array.isArray(r))return;const o=r.map(d=>{if(!d||typeof d!="object")return null;const c=d,x=typeof c.toolName=="string"?c.toolName:"";if(!x)return null;const A=c.args;return{toolName:x,...A&&typeof A=="object"?{args:A}:{},isError:!!c.isError,result:c.result,status:"completed"}}).filter(d=>d!==null);return o.length>0?o:void 0}function dn(n){const r=n?.fallback;if(!r||typeof r!="object")return;const o=r,d=typeof o.primaryModel=="string"?o.primaryModel:"",c=typeof o.fallbackModel=="string"?o.fallbackModel:"",x=o.triggerPoint;if(!(!d||!c||x!=="session-creation"&&x!=="prompt-time"))return{primaryModel:d,fallbackModel:c,triggerPoint:x}}function Nt(n){return{id:n.id,sessionId:n.sessionId,role:n.role,content:n.content,thinkingOutput:n.thinkingOutput,toolCalls:ln(n.metadata),fallbackInfo:dn(n.metadata),attachments:n.attachments,createdAt:n.createdAt}}function un(n,r){const[o,d]=s.useState([]),[c,x]=s.useState(null),[A,E]=s.useState(!0),[P,w]=s.useState([]),[X,p]=s.useState(!1),[J,C]=s.useState(!1),[Z,b]=s.useState(""),[T,m]=s.useState(""),[j,M]=s.useState([]),[D,F]=s.useState(""),[G,$]=s.useState(""),[K,v]=s.useState(!0),[h,u]=s.useState(new Map),i=s.useRef(null),f=s.useRef(!1),y=s.useRef(""),I=s.useRef(null),de=s.useRef(o),Y=s.useRef(c),ae=s.useRef(J);de.current=o,Y.current=c,ae.current=J,s.useEffect(()=>{y.current=D},[D]);const re=s.useRef(new Set),me=s.useRef(0),Ge=s.useRef(n);Ge.current!==n&&(Ge.current=n,me.current++),s.useEffect(()=>{const g=me.current;at(void 0,n).then(k=>{if(me.current!==g)return;const S=new Map;for(const R of k)S.set(R.id,R);u(S)}).catch(()=>{})},[n]);const he=s.useCallback(async()=>{E(!0);try{const k=[...(await Ut(n)).sessions].sort((S,R)=>new Date(R.updatedAt).getTime()-new Date(S.updatedAt).getTime());d(k)}catch{}finally{E(!1)}},[n]);s.useEffect(()=>{he()},[he]);const _=s.useRef(()=>{}),oe=s.useRef(!1);s.useEffect(()=>{oe.current=!1},[n]),s.useEffect(()=>{if(A||oe.current||Y.current)return;const g=Xt(Ct,n);if(!g){oe.current=!0;return}const k=o.find(S=>S.id===g);if(k){oe.current=!0,_.current(g,k);return}oe.current=!0},[A,o,n]);const ie=s.useCallback(async(g,k)=>{p(!0);try{const S=await js(g,{limit:50,...k},n),R=S.messages.map(Nt);k?.offset&&k.offset>0?w(q=>[...R,...q]):w(R),v(S.messages.length>=50)}catch{}finally{p(!1)}},[n]),we=s.useCallback(()=>{I.current?.(),I.current=null,y.current="",F(""),b(""),m(""),M([]),C(!1)},[]),fe=s.useCallback(g=>{if(i.current||!g)return!0;f.current=!1,C(!0);const{handlers:k}=Ot({sessionId:g,tempUserMessageId:"",setStreamingText:b,setStreamingThinking:m,setStreamingToolCalls:M,cancelStreamingFlushesRef:I,addToast:r,onFallbackSession:(R,q)=>{const L=Vt(R.fallbackModel);d(ee=>ee.map(U=>U.id===q?{...U,...L}:U)),x(ee=>ee&&ee.id===q?{...ee,...L}:ee)},onDone:()=>{b(""),m(""),M([]),C(!1),ae.current=!1,i.current=null,ie(g)},onError:R=>{b(""),m(""),M([]),C(!1),ae.current=!1,i.current=null;const q=typeof R=="string"&&R.trim()?R:"Failed to get response";r?.(q,"error"),ie(g)}}),S=Ms(g,k,n);return i.current=S,!0},[r,ie,n]),Re=s.useCallback((g,k)=>{const S=Y.current?.id??null;if(g&&S===g&&!k)return;i.current&&(i.current.close(),i.current=null);const R=k??o.find(q=>q.id===g);x(R||null),we(),v(!0),g?ie(g):w([]),R?.isGenerating&&(b(""),fe(R.id)),g?Mt(Ct,g,n):Le(Ct,n)},[fe,o,ie,n,we]);_.current=Re;const Ve=s.useCallback(async g=>{const k=await Rs(g,n);i.current&&(i.current.close(),i.current=null);const S={id:k.session.id,title:k.session.title,agentId:k.session.agentId,status:k.session.status,modelProvider:k.session.modelProvider,modelId:k.session.modelId,createdAt:k.session.createdAt,updatedAt:k.session.updatedAt};return d(R=>R.some(q=>q.id===S.id)?R:[S,...R]),we(),Re(S.id,S),w([]),S},[n,we,Re]),ye=s.useCallback(async g=>{await As(g,{status:"archived"},n),d(k=>k.filter(S=>S.id!==g)),c?.id===g&&(x(null),w([]))},[c,n]),Se=s.useCallback(async g=>{c?.id===g&&i.current&&(i.current.close(),i.current=null),await Es(g,n),d(k=>k.filter(S=>S.id!==g)),c?.id===g&&(x(null),w([]))},[c,n]),Ie=s.useCallback(async()=>{!c||!K||await ie(c.id,{offset:P.length})},[c,K,ie,P.length]),Ae=s.useCallback(()=>{c&&(f.current=!0,I.current?.(),I.current=null,i.current?.close(),i.current=null,Ts(c.id,n).catch(()=>{}),C(!1),b(""),m(""),M([]))},[c,n]),Ee=s.useCallback(()=>{y.current="",F("")},[]),ge=s.useRef(()=>{}),ke=Ds(),pe=s.useCallback((g,k)=>{if(!c)return;if(ae.current){y.current=g,F(g),r?.("Still waiting for previous response — message queued","warning");return}f.current=!1,i.current&&(i.current.close(),i.current=null);const S=`temp-${Date.now()}`,R={id:S,sessionId:c.id,role:"user",content:g,createdAt:new Date().toISOString()};w(L=>[...L,R]),b(""),m(""),M([]),C(!0);const{handlers:q}=Ot({sessionId:c.id,tempUserMessageId:S,setStreamingText:b,setStreamingThinking:m,setStreamingToolCalls:M,cancelStreamingFlushesRef:I,addToast:r,onFallbackSession:(L,ee)=>{const U=Vt(L.fallbackModel);d(te=>te.map(H=>H.id===ee?{...H,...U}:H)),x(te=>te&&te.id===ee?{...te,...U}:te)},onDone:({messageId:L,message:ee,accumulated:U})=>{const te=ee?Nt(ee):{id:L||`msg-${Date.now()}`,sessionId:c.id,role:"assistant",content:U.text,thinkingOutput:U.thinking,toolCalls:U.toolCalls.length>0?U.toolCalls:void 0,fallbackInfo:U.fallbackInfo,createdAt:new Date().toISOString()};re.current.add(te.id),w(O=>[...O,te]),b(""),m(""),M([]),C(!1),ae.current=!1,i.current=null,setTimeout(()=>{re.current.delete(te.id)},1e3),he();const H=y.current.trim();H&&(y.current="",F(""),ge.current(H))},onError:(L,ee)=>{w(H=>H.filter(O=>O.id!==ee)),b(""),m(""),M([]),C(!1),ae.current=!1,i.current=null,console.error("[useChat] Stream error:",L);const U=typeof L=="string"&&L.trim()?L:"Failed to get response";if(typeof L=="string"&&$s(L)&&(ke.isHiddenNow()||ke.wasRecentlyHidden(5e3))?(console.info("[useChat] Suppressed tab-suspension stream error:",L),c?.id&&ie(c.id)):r?.(U,"error"),!f.current){const H=y.current.trim();H&&(y.current="",F(""),ge.current(H))}}});i.current=Ps(c.id,g,q,k,n)},[c,n,he,r,ie,ke]);ge.current=pe;const ue=G?o.filter(g=>g.title?.toLowerCase().includes(G.toLowerCase())||g.agentId.toLowerCase().includes(G.toLowerCase())):o;return s.useEffect(()=>{if(!Y.current?.isGenerating||(i.current||fe(Y.current.id),!ae.current||i.current||!Y.current))return;const g=setInterval(async()=>{if(!ae.current||i.current||!Y.current){clearInterval(g);return}try{(await Ut(n)).sessions.find(R=>R.id===Y.current?.id)?.isGenerating||(clearInterval(g),await ie(Y.current.id),b(""),m(""),M([]),C(!1))}catch{}},3e3);return()=>clearInterval(g)},[fe,ie,n,c]),s.useEffect(()=>{const g=me.current,k=n?`?projectId=${encodeURIComponent(n)}`:"",S=()=>me.current!==g,R=H=>{if(S())return;const O=JSON.parse(H.data);d(B=>B.some(Q=>Q.id===O.id)?B:[O,...B])},q=H=>{if(S())return;const O=JSON.parse(H.data);d(B=>[...B.map(se=>se.id===O.id?O:se)]),Y.current?.id===O.id&&(x(O),O.isGenerating&&!i.current&&(b(""),fe(O.id)))},L=H=>{if(S())return;const{id:O}=JSON.parse(H.data);d(B=>B.filter(Q=>Q.id!==O)),Y.current?.id===O&&(x(null),w([]))},ee=H=>{if(S())return;const O=JSON.parse(H.data),B=Nt(O);if(!re.current.has(B.id)){if(Y.current?.id===B.sessionId&&ae.current&&!i.current&&B.role==="assistant"){w(Q=>Q.some(se=>se.id===B.id)?Q:[...Q,B]),b(""),m(""),M([]),C(!1);return}Y.current?.id===B.sessionId&&!ae.current&&w(Q=>{if(Q.some(se=>se.id===B.id))return Q;if(B.role==="user"){const se=Q.findIndex(be=>be.role==="user"&&be.id.startsWith("temp-")&&be.content.trim()===B.content.trim());if(se>=0){const be=[...Q];return be[se]=B,be}}return[...Q,B]})}},U=H=>{if(S())return;const{id:O}=JSON.parse(H.data);w(B=>B.filter(Q=>Q.id!==O))};return Qt(`/api/events${k}`,{events:{"chat:session:created":R,"chat:session:updated":q,"chat:session:deleted":L,"chat:message:added":ee,"chat:message:deleted":U}})},[fe,n]),s.useEffect(()=>()=>{i.current&&(i.current.close(),i.current=null)},[]),{sessions:o,activeSession:c,sessionsLoading:A,messages:P,messagesLoading:X,isStreaming:J,streamingText:Z,streamingThinking:T,streamingToolCalls:j,pendingMessage:D,selectSession:Re,createSession:Ve,archiveSession:ye,deleteSession:Se,sendMessage:pe,stopStreaming:Ae,clearPendingMessage:Ee,loadMoreMessages:Ie,hasMoreMessages:K,searchQuery:G,setSearchQuery:$,filteredSessions:ue,refreshSessions:he,agentsMap:h}}const Ce="fusion:chat-active-room";function Rt(n){return[...n].sort((r,o)=>new Date(o.updatedAt).getTime()-new Date(r.updatedAt).getTime())}function Qe(n,r){const o=n.findIndex(c=>c.id===r.id);if(o===-1)return Rt([r,...n]);const d=[...n];return d[o]=r,Rt(d)}function Ne(n){try{return JSON.parse(n.data)}catch{return null}}function mn(n,r){const[o,d]=s.useState([]),[c,x]=s.useState(!0),[A,E]=s.useState(null),[P,w]=s.useState(null),[X,p]=s.useState([]),[J,C]=s.useState([]),[Z,b]=s.useState(!1),T=s.useRef(o),m=s.useRef(P),j=s.useRef(0),M=s.useRef(n);T.current=o,m.current=P,M.current!==n&&(M.current=n,j.current+=1);const D=s.useCallback(async(h,u=!0)=>{if(!h){p([]),C([]),b(!1);return}u&&C([]),b(!0);try{const[i,f]=await Promise.all([Ls(h.id,n),Fs(h.id,{limit:100},n)]);p(i.members),C(f.messages)}catch{p([]),C([])}finally{b(!1)}},[n]),F=s.useCallback(async()=>{x(!0);try{const h=await Is({},n),u=Rt(h.rooms);d(u),E(null);const i=Xt(Ce,n);if(i){const f=u.find(y=>y.id===i)??null;f?(w(f),D(f,!0)):Le(Ce,n)}}catch(h){const u=h instanceof Error?h.message:"Failed to load chat rooms";E(u),r?.(u,"error")}finally{x(!1)}},[r,D,n]),G=s.useCallback(h=>{if(!h){w(null),Le(Ce,n),D(null,!0);return}const u=T.current.find(i=>i.id===h)??null;w(u),u&&(Mt(Ce,u.id,n),D(u,!0))},[D,n]),$=s.useCallback(async h=>{const i=(await zs({name:h.name,memberAgentIds:h.memberAgentIds},n)).room;return d(f=>Qe(f,i)),w(i),Mt(Ce,i.id,n),await D(i,!0),i},[D,n]),K=s.useCallback(async h=>{await _s(h,n),d(u=>u.filter(i=>i.id!==h)),m.current?.id===h&&(w(null),p([]),C([]),Le(Ce,n))},[n]),v=s.useCallback(async(h,u)=>{const i=m.current?.id;if(!i)throw new Error("Select a room before sending a message");await Us(i,{content:h,...u?.attachments?{attachments:u.attachments}:{}},n)},[n]);return s.useEffect(()=>{F()},[F]),s.useEffect(()=>{const h=j.current,u=n?`/api/events?projectId=${encodeURIComponent(n)}`:"/api/events";return Qt(u,{onReconnect:()=>{F()},events:{"chat:room:created":i=>{if(j.current!==h)return;const f=Ne(i);f&&d(y=>Qe(y,f))},"chat:room:updated":i=>{if(j.current!==h)return;const f=Ne(i);f&&(d(y=>Qe(y,f)),m.current?.id===f.id&&w(f))},"chat:room:deleted":i=>{if(j.current!==h)return;const f=Ne(i);f?.id&&(d(y=>y.filter(I=>I.id!==f.id)),m.current?.id===f.id&&(w(null),p([]),C([]),Le(Ce,n)))},"chat:room:member:added":i=>{if(j.current!==h)return;const f=Ne(i);!f||m.current?.id!==f.roomId||p(y=>y.some(I=>I.agentId===f.agentId)?y:[...y,f])},"chat:room:member:removed":i=>{if(j.current!==h)return;const f=Ne(i);!f||m.current?.id!==f.roomId||p(y=>y.filter(I=>I.agentId!==f.agentId))},"chat:room:message:added":i=>{if(j.current!==h)return;const f=Ne(i);f&&(d(y=>{const I=y.find(de=>de.id===f.roomId);return I?Qe(y,{...I,updatedAt:f.createdAt}):y}),m.current?.id===f.roomId&&C(y=>y.some(I=>I.id===f.id)?y:[...y,f]))},"chat:room:message:updated":i=>{if(j.current!==h)return;const f=Ne(i);!f||m.current?.id!==f.roomId||C(y=>y.map(I=>I.id===f.id?f:I))},"chat:room:message:deleted":i=>{if(j.current!==h)return;const f=Ne(i);f?.id&&C(y=>y.filter(I=>I.id!==f.id))}}})},[n,F]),s.useEffect(()=>{P&&(o.some(h=>h.id===P.id)||(w(null),p([]),C([]),Le(Ce,n)))},[P,n,o]),{rooms:o,roomsLoading:c,roomsError:A,activeRoom:P,activeRoomMembers:X,messages:J,messagesLoading:Z,selectRoom:G,createRoom:$,deleteRoom:K,sendRoomMessage:v,refreshRooms:F}}function hn(n,r=[]){const o=n.trim().replace(/^#/,"");if(!o)return{ok:!1,error:"Room name is required."};if(/[A-Z]/.test(o))return{ok:!1,error:"Use lowercase letters only."};const d=o.toLowerCase();return d.length>80?{ok:!1,error:"Room names can be at most 80 characters."}:/^[a-z0-9_-]+$/.test(d)?/^[-_]|[-_]$/.test(d)?{ok:!1,error:"Room names cannot start or end with a hyphen or underscore."}:r.some(c=>c.toLowerCase()===d)?{ok:!1,error:"A room with this name already exists."}:{ok:!0,name:d}:{ok:!1,error:"Use lowercase letters, numbers, hyphens, or underscores only."}}function fn({isOpen:n,onClose:r,onCreate:o,projectId:d,existingRoomNames:c=[]}){const[x,A]=s.useState(""),[E,P]=s.useState([]),[w,X]=s.useState(""),[p,J]=s.useState([]),[C,Z]=s.useState(!1),[b,T]=s.useState(null),[m,j]=s.useState(!1),M=s.useRef(null),D=s.useRef(null);s.useEffect(()=>{n&&(D.current=document.activeElement instanceof HTMLElement?document.activeElement:null,Z(!0),T(null),at(void 0,d).then(u=>P(u)).catch(()=>{P([]),T("Failed to load agents.")}).finally(()=>Z(!1)))},[n,d]),s.useEffect(()=>{if(!n){A(""),X(""),J([]),T(null),j(!1);return}const u=window.requestAnimationFrame(()=>M.current?.focus());return()=>window.cancelAnimationFrame(u)},[n]),s.useEffect(()=>{if(!n)return;const u=i=>{i.key==="Escape"&&r()};return document.addEventListener("keydown",u),()=>document.removeEventListener("keydown",u)},[n,r]),s.useEffect(()=>{n||D.current?.focus()},[n]);const F=s.useMemo(()=>hn(x,c),[x,c]),G=s.useMemo(()=>{const u=w.trim().toLowerCase();return u?E.filter(i=>i.name.toLowerCase().includes(u)):E},[E,w]),$=s.useMemo(()=>E.filter(u=>p.includes(u.id)),[E,p]),K=F.ok&&p.length>0&&!m&&!C;if(!n)return null;const v=u=>{m||J(i=>i.includes(u)?i.filter(f=>f!==u):[...i,u])},h=async()=>{if(!F.ok){T(F.error);return}if(p.length===0){T("Select at least one member.");return}T(null),j(!0);try{await o({name:F.name,displayName:`#${F.name}`,memberAgentIds:p}),r()}catch(u){T(u instanceof Error?u.message:"Failed to create room.")}finally{j(!1)}};return Ns.createPortal(t.jsx("div",{className:"modal-overlay open",onClick:u=>u.target===u.currentTarget&&r(),children:t.jsxs("div",{className:"modal modal-lg create-room-modal",role:"dialog","aria-modal":"true","aria-label":"Create room",onClick:u=>u.stopPropagation(),children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h3",{children:"Create room"}),t.jsx("button",{type:"button",className:"modal-close","aria-label":"Close",onClick:r,children:"×"})]}),t.jsxs("div",{className:"form-group create-room-modal-name-group",children:[t.jsx("label",{htmlFor:"create-room-name",children:"Room name"}),t.jsxs("div",{className:"create-room-modal-name-field",children:[t.jsx("span",{"aria-hidden":"true",className:"create-room-modal-name-hash",children:"#"}),t.jsx("input",{ref:M,id:"create-room-name",className:"input",value:x,disabled:m,onChange:u=>{const i=u.target.value.replace(/^#/,"").replace(/\s+/g,"-").toLowerCase();A(i)}})]}),!F.ok&&t.jsx("div",{className:"form-error",children:F.error})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"create-room-member-search",children:"Members"}),t.jsx("input",{id:"create-room-member-search",className:"input",placeholder:"Search agents",value:w,disabled:m,onChange:u=>X(u.target.value)})]}),$.length>0&&t.jsx("div",{className:"create-room-modal-selected","data-testid":"create-room-selected-chips",children:$.map(u=>t.jsxs("button",{type:"button",className:"btn btn-sm create-room-modal-chip",onClick:()=>v(u.id),disabled:m,children:[u.name," ×"]},u.id))}),t.jsx("div",{className:"create-room-modal-member-list","data-testid":"create-room-member-list",children:C?t.jsx("div",{className:"create-room-modal-empty",children:"Loading agents..."}):G.length===0?t.jsx("div",{className:"create-room-modal-empty",children:E.length===0?"No agents in this project yet.":"No agents match your search."}):G.map(u=>{const i=p.includes(u.id);return t.jsxs("button",{type:"button",className:`create-room-modal-member-row${i?" create-room-modal-member-row--selected":""}`,onClick:()=>v(u.id),disabled:m,children:[t.jsx(Zt,{agent:u,size:20}),t.jsx("span",{children:u.name}),t.jsx("span",{className:"create-room-modal-member-role",children:u.role})]},u.id)})}),b&&t.jsx("div",{className:"form-group",children:t.jsx("div",{className:"form-error",children:b})}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{type:"button",className:"btn",onClick:r,disabled:m,children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:()=>void h(),disabled:!K,children:m?"Creating...":"Create room"})]})]})}),document.body)}function ss(n){const r=new Date(n),d=new Date().getTime()-r.getTime(),c=Math.floor(d/1e3),x=Math.floor(c/60),A=Math.floor(x/60),E=Math.floor(A/24);return c<60?"just now":x<60?`${x}m ago`:A<24?`${A}h ago`:E<7?`${E}d ago`:r.toLocaleDateString()}function Kt(n,r){if(!n||!r)return null;const o=r.toLowerCase();if(o.includes("claude")){let c=r.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(o.includes("gpt")||o.includes("openai")){const c=r.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(o.includes("gemini")){const c=r.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 d=r.replace(/-/g," ").replace(/^\w/,c=>c.toUpperCase()).replace(/\s+/g," ").trim();return d.length>30?d.slice(0,30)+"…":d}function st(n,r){return n.length<=r?n:`${n.slice(0,r)}…`}function gn(n){if(!n)return null;const r=Object.entries(n);return r.length===0?null:r.map(([o,d])=>{const c=typeof d=="string"?d:(()=>{try{return JSON.stringify(d)}catch{return String(d)}})();return`${o}=${st(c,50)}`}).join(", ")}function pn(n){if(n===void 0)return null;if(typeof n=="string")return st(n,200);try{return st(JSON.stringify(n),200)}catch{return st(String(n),200)}}function ns(n){if(!n||n.length===0)return null;const r=(p,J)=>{const C=p.status==="running",Z=p.status==="completed"&&p.isError,b=gn(p.args),T=pn(p.result),m=C?b:T?`result: ${T}`:b?`args: ${b}`:null,j=C?"running":Z?"error":"completed";return t.jsxs("details",{className:`chat-tool-call${C?" chat-tool-call--running":""}${Z?" 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",title:p.toolName,children:p.toolName}),m&&t.jsx("span",{className:"chat-tool-call-preview",title:m,children:m}),t.jsx("span",{className:"chat-tool-call-status-text",children:j})]}),t.jsxs("div",{className:"chat-tool-call-content",children:[b&&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:b})]}),T&&t.jsxs("div",{className:`chat-tool-call-row${Z?" 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:T})]})]})]},`${p.toolName}-${J}`)},o="chat-tool-calls";if(n.length===1)return t.jsxs("div",{className:o,"data-testid":"chat-tool-calls",children:[t.jsxs("div",{className:"chat-tool-calls-header",children:[t.jsx(Wt,{size:12,"aria-hidden":"true"}),t.jsx("span",{children:"Tool calls"})]}),r(n[0],0)]});const d=n.filter(p=>p.status==="running").length,c=n.filter(p=>p.status==="completed"&&p.isError).length,x=d>0,A=Array.from(new Set(n.map(p=>p.toolName))),E=A.slice(0,5),P=Math.max(0,A.length-E.length),w=P>0?`${E.join(", ")}, +${P} more`:E.join(", "),X=x?`(${d} running)`:c>0?`(${c} ${c===1?"error":"errors"})`:null;return t.jsx("div",{className:o,"data-testid":"chat-tool-calls",children:t.jsxs("details",{className:"chat-tool-calls-group","data-testid":"chat-tool-calls-group",open:x,children:[t.jsxs("summary",{className:"chat-tool-calls-group-summary",children:[t.jsx(Wt,{size:12,"aria-hidden":"true"}),t.jsxs("span",{className:"chat-tool-calls-count",children:[n.length," tool calls"]}),t.jsx("span",{className:"chat-tool-calls-names",title:w,children:w}),X&&t.jsx("span",{className:"chat-tool-calls-group-status",children:X})]}),n.map((p,J)=>r(p,J))]})})}const as={pre:({children:n,...r})=>t.jsx("pre",{...r,className:"chat-markdown-pre",children:n}),table:({children:n,...r})=>t.jsx("table",{...r,className:"chat-markdown-table",children:n})},Fe="__fn_agent__",bn=280,Ze=180,et=500,qt="fusion:chat-sidebar-width",Jt="fusion:chat-scope",vn=["image/png","image/jpeg","image/gif","image/webp","text/plain","application/json","text/yaml","text/markdown","text/csv","application/xml","text/x-log"];function Yt(n){const r=/(^|[\s])\/([^\s]*)$/.exec(n);if(!r)return null;const o=r[1]??"",d=r[2]??"",c=r.index+o.length;return{filter:d,start:c,end:n.length}}function xn(n,r){const o=n.slice(0,r),d=/(^|[\s\n])@([\w-]*)$/.exec(o);if(!d)return null;const c=d[2]??"",x=o.length-c.length-1;return{filter:c,start:x,end:r}}function wn({projectId:n,onClose:r,onCreate:o}){const[d,c]=s.useState("agent"),[x,A]=s.useState([]),[E,P]=s.useState(!0),[w,X]=s.useState(""),[p,J]=s.useState([]),[C,Z]=s.useState(!0),[b,T]=s.useState(""),[m,j]=s.useState([]),[M,D]=s.useState([]);s.useEffect(()=>{let v=!1;return P(!0),at(void 0,n).then(h=>{v||A(h)}).catch(()=>{v||A([])}).finally(()=>{v||P(!1)}),()=>{v=!0}},[n]),s.useEffect(()=>{Z(!0),on().then(v=>{J(v.models),j(v.favoriteProviders),D(v.favoriteModels)}).catch(()=>{J([]),j([]),D([])}).finally(()=>{Z(!1)})},[]);const F=s.useCallback(async v=>{const h=m,i=h.includes(v)?h.filter(f=>f!==v):[v,...h];j(i);try{await Gt({favoriteProviders:i,favoriteModels:M})}catch{j(h)}},[m,M]),G=s.useCallback(async v=>{const h=M,i=h.includes(v)?h.filter(f=>f!==v):[v,...h];D(i);try{await Gt({favoriteProviders:m,favoriteModels:i})}catch{D(h)}},[M,m]),$=v=>{if(v.preventDefault(),d==="agent"){if(!w)return;o({agentId:w});return}if(!b)return;const h=b.indexOf("/");if(h<=0)return;const u=b.slice(0,h),i=b.slice(h+1);o({agentId:Fe,modelProvider:u,modelId:i})},K=d==="agent"?!w:!b;return t.jsx("div",{className:"chat-new-dialog-backdrop chat-view-dialog-backdrop",onClick:r,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"chat-new-dialog chat-view-dialog",onClick:v=>v.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${d==="agent"?" chat-new-dialog-mode-btn--active":""}`,"data-testid":"chat-new-dialog-mode-agent",onClick:()=>{c("agent"),T("")},children:"Agent"}),t.jsx("button",{type:"button",className:`chat-new-dialog-mode-btn${d==="model"?" chat-new-dialog-mode-btn--active":""}`,"data-testid":"chat-new-dialog-mode-model",onClick:()=>{c("model"),X("")},children:"Model"})]}),t.jsxs("form",{onSubmit:$,children:[d==="agent"&&t.jsxs("label",{className:"chat-new-dialog-model-label",children:["Agent",E?t.jsx("div",{className:"chat-new-dialog-loading",children:"Loading agents..."}):x.length===0?t.jsx("div",{className:"chat-new-dialog-empty",children:"No agents available"}):t.jsx("div",{className:"chat-new-dialog-agent-list",children:x.map(v=>t.jsxs("button",{type:"button",className:`chat-new-dialog-agent-item${w===v.id?" chat-new-dialog-agent-item--selected":""}`,onClick:()=>X(v.id),"data-testid":`agent-option-${v.id}`,children:[t.jsx(nt,{size:16}),t.jsx("span",{className:"chat-new-dialog-agent-name",children:v.name}),t.jsx("span",{className:"chat-new-dialog-agent-role",children:v.role})]},v.id))})]}),d==="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(cn,{models:p,value:b,onChange:T,label:"Model",placeholder:"Select a model",favoriteProviders:m,onToggleFavorite:F,favoriteModels:M,onToggleModelFavorite:G})}),t.jsxs("div",{className:"chat-new-dialog-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:r,children:"Cancel"}),t.jsx("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:K,children:"Create"})]})]})]})})}const jt=s.memo(function({message:r,forcePlain:o,agentName:d,hideAssistantIdentity:c,showAssistantModelTag:x,activeModelTag:A,activeModelProvider:E,activeSessionId:P,mentionAgentsByName:w,copyAction:X}){const p=r.role==="assistant",J=s.useMemo(()=>{if(p)return null;const b=r.content,T=/@([\w-]+)/g,m=[];let j=0,M=T.exec(b);for(;M;){const[D,F=""]=M,G=M.index;G>j&&m.push(b.slice(j,G));const $=F.replace(/_/g," ").toLowerCase(),K=w.get($);K?m.push(t.jsxs("span",{className:"chat-mention-chip",children:["@",K.name.replace(/\s+/g,"_")]},`${K.id}-${G}`)):m.push(D),j=G+D.length,M=T.exec(b)}return j<b.length&&m.push(b.slice(j)),m.length===0?b:m},[p,r.content,w]),C=s.useMemo(()=>{const b=r.attachments;if(!b||b.length===0||!P)return null;const T=`/api/chat/sessions/${encodeURIComponent(P)}/attachments/`;return t.jsx("div",{className:"chat-message-attachments",children:b.map(m=>{const j=m.mimeType.startsWith("image/"),M=m.id||m.filename,D=`${T}${encodeURIComponent(m.filename)}`;return j?t.jsx("a",{className:"chat-message-attachment-link","data-testid":"chat-message-attachment",href:D,target:"_blank",rel:"noopener noreferrer",children:t.jsx("img",{className:"chat-message-attachment",src:D,alt:m.originalName})},M):t.jsxs("a",{className:"chat-message-attachment-file","data-testid":"chat-message-attachment",href:D,target:"_blank",rel:"noopener noreferrer",children:[t.jsx(an,{size:14}),t.jsx("span",{children:m.originalName})]},M)})})},[r.attachments,P]),Z=s.useMemo(()=>p?o?t.jsx("div",{className:"chat-message-content chat-message-content--plain",children:r.content}):t.jsx("div",{className:"chat-message-content chat-message-content--markdown",children:t.jsx(es,{remarkPlugins:[ts],components:as,children:r.content})}):null,[p,o,r.content]);return t.jsxs("div",{className:`chat-message chat-message--${r.role}`,"data-testid":`chat-message-${r.id}`,children:[p&&!c&&t.jsxs("div",{className:"chat-message-avatar",children:[E?t.jsx(tt,{provider:E,size:"sm"}):t.jsx(nt,{size:14}),t.jsx("span",{children:d}),x&&A&&t.jsx("span",{className:"chat-model-tag",children:A})]}),p?Z:t.jsx("div",{className:"chat-message-content",children:J}),X,ns(r.toolCalls),r.thinkingOutput&&t.jsxs("details",{className:"chat-message-thinking",children:[t.jsx("summary",{children:"Thinking"}),t.jsx("pre",{className:"chat-message-thinking-content",children:r.thinkingOutput})]}),C,t.jsx("div",{className:"chat-message-time",children:ss(r.createdAt)})]})});function Nn({projectId:n,addToast:r}){const{activeSession:o,sessionsLoading:d,messages:c,messagesLoading:x,isStreaming:A,streamingText:E,streamingThinking:P,streamingToolCalls:w,selectSession:X,createSession:p,archiveSession:J,deleteSession:C,sendMessage:Z,stopStreaming:b,pendingMessage:T,clearPendingMessage:m,searchQuery:j,setSearchQuery:M,filteredSessions:D}=un(n,r),[F,G]=s.useState(!1),[$,K]=s.useState(""),[v,h]=s.useState(null),[u,i]=s.useState(null),[f,y]=s.useState(null),[I,de]=s.useState(!0),[Y,ae]=s.useState(bn),[re,me]=s.useState("direct"),[Ge,he]=s.useState(!1),_=mn(n,r),[oe,ie]=s.useState(new Map),[we,fe]=s.useState([]),[Re,Ve]=s.useState(!0),[ye,Se]=s.useState(!1),[Ie,Ae]=s.useState(""),[Ee,ge]=s.useState(0),[ke,pe]=s.useState(""),[ue,g]=s.useState(!1),[k,S]=s.useState(0),[R,q]=s.useState(-1),[L,ee]=s.useState(!1),[U,te]=s.useState([]),[H,O]=s.useState(!1),[B,Q]=s.useState(!1),[se,be]=s.useState({}),[,ze]=s.useState(!1),[rs,os]=s.useState({top:0,left:0}),z=Os({projectId:n}),rt=s.useCallback(e=>{if(!e||!z.mentionActive)return;const a=e.getBoundingClientRect();os({top:a.top-260,left:a.left+8})},[z.mentionActive]),At=s.useRef(null),ot=s.useRef(!1),it=s.useRef(null),ve=s.useRef(null),Te=s.useRef(null),ne=s.useRef(null),Et=s.useRef(null),Tt=s.useRef([]),_e=s.useRef(0),Ue=s.useRef(new Map),V=Hs()==="mobile";s.useEffect(()=>{try{const e=localStorage.getItem(qt);if(!e)return;const a=Number.parseInt(e,10);if(Number.isNaN(a))return;const l=Math.max(Ze,Math.min(et,a));ae(l)}catch{}},[]),s.useEffect(()=>{try{const e=localStorage.getItem(Jt);(e==="direct"||e==="rooms")&&me(e)}catch{}},[]),s.useEffect(()=>{try{localStorage.setItem(Jt,re)}catch{}},[re]);const{keyboardOverlap:Ke,viewportHeight:Dt,viewportOffsetTop:Pt,keyboardOpen:Oe}=Bs({enabled:V&&!!o}),$t=Ke>0||Pt>0,is=Oe&&$t?{"--keyboard-overlap":`${Ke}px`,"--vv-offset-top":`${Pt}px`,...Dt!==null?{"--vv-height":`${Dt}px`}:{}}:{},ce=s.useMemo(()=>{const e=Ie.trim().toLowerCase();return(e?we.filter(l=>l.name.toLowerCase().includes(e)):we).slice(0,10)},[we,Ie]),He=s.useMemo(()=>Array.from(oe.values()),[oe]),je=s.useMemo(()=>He.filter(e=>Ws(e.name,ke)),[He,ke]),ct=s.useMemo(()=>{const e=new Map;for(const a of He)e.set(a.name.toLowerCase(),a);return e},[He]);s.useEffect(()=>{ge(0)},[ce]),s.useEffect(()=>{S(0)},[ke,ue]),s.useEffect(()=>()=>{ve.current!==null&&window.clearTimeout(ve.current)},[]);const Lt=s.useCallback(()=>{const e=Te.current;if(!e)return;const l=e.scrollTop+e.clientHeight>=e.scrollHeight-50;Q(!l),ot.current=!l},[]),qe=s.useCallback(e=>{if(!e.isConnected)return;let a=0,l=0,N=-1;const W=6,le=()=>{if(e.isConnected){if(e.scrollTop=e.scrollHeight,e.scrollHeight===N?l+=1:(l=0,N=e.scrollHeight),a+=1,a>=W||l>=2){Q(!1),ot.current=!1;return}window.requestAnimationFrame(le)}};le()},[]),Be=s.useCallback(()=>{const e=Te.current;e&&qe(e)},[qe]);s.useLayoutEffect(()=>{const e=o?.id??null;if(!e){it.current=null;return}const a={sessionId:e,loaded:!x,hasMessages:c.length>0},l=it.current,N=l?.sessionId!==e,W=l?.sessionId===e&&!l.loaded&&a.loaded,le=l?.sessionId===e&&!l.hasMessages&&a.hasMessages;if(!(l===null||N||W||le))return;const xe=Te.current;xe&&(qe(xe),it.current=a)},[o?.id,c.length,x,qe]),s.useEffect(()=>{ot.current||Be()},[c,E,P,A,Be]),s.useEffect(()=>{Ke<=0||!Te.current||Be()},[Ke,Be]),Gs(V&&Oe),s.useEffect(()=>{const e=()=>h(null);if(v)return document.addEventListener("click",e),()=>document.removeEventListener("click",e)},[v]),s.useEffect(()=>{if(!V||!Oe)return;const e=a=>{a.target?.closest(".chat-messages")||a.preventDefault()};return document.addEventListener("touchmove",e,{passive:!1}),()=>{document.removeEventListener("touchmove",e)}},[V,Oe]),s.useEffect(()=>{if(!V||!o)return;const e=()=>{const a=ne.current;a&&document.activeElement===a&&(a.blur(),window.setTimeout(()=>{a.focus({preventScroll:!0})},0))};return document.addEventListener("visibilitychange",e),window.addEventListener("pageshow",e),()=>{document.removeEventListener("visibilitychange",e),window.removeEventListener("pageshow",e)}},[V,o]),s.useEffect(()=>{let e=!1;const a=n;return at(void 0,n).then(l=>{if(e||a!==n)return;const N=new Map;for(const W of l)N.set(W.id,W);ie(N)}).catch(()=>{}),()=>{e=!0}},[n]),s.useEffect(()=>{let e=!1;return Ve(!0),Vs(n).then(a=>{e||fe(a)}).catch(()=>{e||fe([])}).finally(()=>{e||Ve(!1)}),()=>{e=!0}},[n]),s.useEffect(()=>{Tt.current=U},[U]),s.useEffect(()=>()=>{for(const e of Tt.current)e.previewUrl&&URL.revokeObjectURL(e.previewUrl);for(const e of Ue.current.values())window.clearTimeout(e);Ue.current.clear()},[]);const Je=s.useCallback(e=>{if(!e||e.length===0)return;const a=[];for(const l of Array.from(e)){if(!vn.includes(l.type))continue;const N=l.type.startsWith("image/");a.push({file:l,previewUrl:N?URL.createObjectURL(l):""})}a.length>0&&te(l=>[...l,...a])},[]),cs=s.useCallback(e=>{te(a=>{const l=a[e];return l?.previewUrl&&URL.revokeObjectURL(l.previewUrl),a.filter((N,W)=>W!==e)})},[]),ls=s.useCallback(e=>{const a=e.clipboardData?.files;if(!a||a.length===0)return;const l=Array.from(a).filter(N=>N.type.startsWith("image/"));l.length!==0&&Je(l)},[Je]),ds=s.useCallback(async e=>{try{await p(e),G(!1),V&&de(!1)}catch{r("Failed to create chat session","error")}},[p,r,V]),lt=s.useCallback(()=>{K(""),Se(!1),Ae(""),g(!1),pe(""),q(-1),te(e=>{for(const a of e)a.previewUrl&&URL.revokeObjectURL(a.previewUrl);return[]})},[]),dt=s.useCallback(()=>{const e=$.trim(),a=U.map(l=>l.file);if(!(!e&&a.length===0||!o)){if(e==="/clear"){lt(),b(),m(),p({agentId:o.agentId,modelProvider:o.modelProvider??void 0,modelId:o.modelId??void 0}).catch(()=>{r("Failed to clear conversation","error")});return}lt(),Z(e,a)}},[$,U,o,lt,b,m,p,r,Z]),ut=s.useCallback(async()=>{const e=$.trim();if(e){if(re==="rooms"){if(!_.activeRoom)return;await _.sendRoomMessage(e),K("");return}dt()}},[$,re,_,dt]),mt=s.useCallback(e=>{K(a=>{const l=Yt(a);if(!l)return a;const N=`/skill:${e.name} `,W=a.slice(0,l.start)+N+a.slice(l.end);return window.requestAnimationFrame(()=>{ne.current&&(ne.current.style.height="auto",ne.current.style.height=`${Math.min(ne.current.scrollHeight,120)}px`,ne.current.focus())}),W}),Se(!1),Ae(""),ge(0)},[]),ht=s.useCallback(e=>{const a=ne.current;if(!a||R<0)return;const l=a.selectionStart??_e.current,N=a.selectionEnd??l,W=Math.max(l,N),le=Math.min(R,W),xe=`${`@${e.name.replace(/\s+/g,"_")}`} `,St=$.slice(0,le)+xe+$.slice(W),$e=le+xe.length;K(St),g(!1),pe(""),S(0),q(-1),window.requestAnimationFrame(()=>{ne.current&&(ne.current.style.height="auto",ne.current.style.height=`${Math.min(ne.current.scrollHeight,120)}px`,ne.current.focus(),ne.current.setSelectionRange($e,$e))})},[R,$]),Ft=s.useCallback(e=>{if(_e.current=e.currentTarget.selectionStart??_e.current,z.mentionActive&&z.files.length>0){if(z.handleKeyDown(e,$),e.key==="Enter"||e.key==="Tab"){const a=z.files[z.selectedIndex];if(a){const l=z.selectFile(a,$);K(l),z.dismissMention(),ze(!1)}}return}if(ue&&e.key==="ArrowDown"){e.preventDefault(),je.length>0&&S(a=>(a+1)%je.length);return}if(ue&&e.key==="ArrowUp"){e.preventDefault(),je.length>0&&S(a=>a===0?je.length-1:a-1);return}if(ue&&e.key==="Enter"){e.preventDefault();const a=je[k]??je[0];a&&ht(a);return}if(ue&&e.key==="Escape"){e.preventDefault(),g(!1),pe(""),q(-1);return}if(ye&&e.key==="ArrowDown"){e.preventDefault(),ce.length>0&&ge(a=>(a+1)%ce.length);return}if(ye&&e.key==="ArrowUp"){e.preventDefault(),ce.length>0&&ge(a=>a===0?ce.length-1:a-1);return}if(ye&&(e.key==="Enter"||e.key==="Tab")&&ce.length>0){e.preventDefault();const a=ce[Ee]??ce[0];a&&mt(a);return}if(ye&&e.key==="Escape"){e.preventDefault(),Se(!1);return}e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),ut())},[ue,je,k,ht,ye,ce,Ee,mt,ut,z,$]),Ye=s.useCallback((e,a)=>{const l=xn(e,a);if(l){g(!0),pe(l.filter),q(l.start);return}g(!1),pe(""),q(-1)},[]),It=s.useCallback(e=>{const a=e.target,l=a.value,N=a.selectionStart??l.length;_e.current=N,K(l);const W=Yt(l);W?(Se(!0),Ae(W.filter)):(Se(!1),Ae("")),Ye(l,N),z.detectMention(l,N),ze(z.mentionActive),z.mentionActive&&rt(a),a.style.height="auto",a.style.height=`${Math.min(a.scrollHeight,120)}px`},[Ye]),ft=s.useCallback(e=>{const a=e.currentTarget,l=a.selectionStart??a.value.length;_e.current=l,Ye(a.value,l),z.detectMention(a.value,l),ze(z.mentionActive),z.mentionActive&&rt(a)},[Ye,z,rt]),us=s.useCallback(e=>{e.key!=="Escape"&&ft(e)},[ft]),ms=s.useCallback(()=>{ve.current!==null&&window.clearTimeout(ve.current),ve.current=window.setTimeout(()=>{Se(!1),g(!1),pe(""),q(-1),ze(!1),z.dismissMention(),ve.current=null},120)},[z]),hs=s.useCallback(()=>{ve.current!==null&&(window.clearTimeout(ve.current),ve.current=null),typeof window<"u"&&window.innerWidth<=768&&window.setTimeout(()=>{(window.scrollY!==0||window.scrollX!==0)&&window.scrollTo(0,0)},0)},[]),fs=s.useCallback(async e=>{h(null);try{await J(e),r("Conversation archived","success")}catch{r("Failed to archive conversation","error")}},[J,r]),gs=s.useCallback(async e=>{i(null),h(null);try{await C(e),r("Conversation deleted","success")}catch{r("Failed to delete conversation","error")}},[C,r]),We=s.useCallback(e=>{try{localStorage.setItem(qt,String(e))}catch{}},[]),ps=s.useCallback(e=>{if(V)return;e.preventDefault(),e.stopPropagation();const a=e.currentTarget;typeof a.setPointerCapture=="function"&&a.setPointerCapture(e.pointerId);const l=e.clientX,N=Y;let W=N;document.body.style.userSelect="none";const le=xe=>{const St=xe.clientX-l,$e=Math.max(Ze,Math.min(et,N+St));W=$e,ae($e),We($e)},Pe=xe=>{typeof a.releasePointerCapture=="function"&&a.releasePointerCapture(xe.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",le),document.removeEventListener("pointerup",Pe),We(W)};document.addEventListener("pointermove",le),document.addEventListener("pointerup",Pe)},[V,We,Y]),bs=s.useCallback(e=>{if(V||e.key!=="ArrowLeft"&&e.key!=="ArrowRight")return;e.preventDefault();const a=e.shiftKey?50:10,l=e.key==="ArrowLeft"?-a:a,N=Math.max(Ze,Math.min(et,Y+l));ae(N),We(N)},[V,We,Y]),vs=s.useCallback(e=>{X(e),V&&de(!1)},[X,V]),xs=s.useCallback(()=>{X(""),de(!0)},[X]),ws=()=>t.jsxs("div",{className:"chat-empty-state",children:[t.jsx(rn,{size:48,strokeWidth:1.5}),t.jsx("h2",{children:"Start a new conversation"}),t.jsxs("button",{className:"btn btn-primary",onClick:()=>G(!0),children:[t.jsx(Xe,{size:16}),"New Chat"]})]}),Me=Kt(o?.modelProvider,o?.modelId),De=o?.modelProvider??null,gt=!!(o||A||c.length>0),zt=o?.agentId===Fe?Me??"Fusion":o?.title||oe.get(o?.agentId??"")?.name||o?.agentId||"Chat",ys=!!(Me&&Me!==zt),pt=oe.get(o?.agentId??"")?.name||(o?.agentId===Fe?Me??"Fusion":o?.agentId?.slice(0,30)??"Fusion"),bt=!1,vt=o?.agentId===Fe,Ss=T.length>50?`${T.slice(0,50)}…`:T,ks=s.useCallback(()=>{ee(e=>!e)},[]),xt=s.useCallback((e,a)=>{const l=Ue.current.get(e);l&&window.clearTimeout(l),be(W=>({...W,[e]:a}));const N=window.setTimeout(()=>{be(W=>{const{[e]:le,...Pe}=W;return Pe}),Ue.current.delete(e)},2e3);Ue.current.set(e,N)},[]),_t=s.useCallback(async(e,a)=>{try{if(!navigator.clipboard?.writeText)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(a),xt(e,"success")}catch{xt(e,"error")}},[xt]),Cs=s.useCallback((e,a=!1)=>a?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(es,{remarkPlugins:[ts],components:as,children:e})}),[]),wt=o?.agentId===Fe,yt=s.useCallback((e,a,l)=>t.jsx("button",{type:"button",className:`btn-icon chat-message-copy-action${se[e]==="success"?" chat-message-copy-action--success":""}${se[e]==="error"?" chat-message-copy-action--error":""}`,"data-testid":l??`chat-copy-response-${e}`,"aria-label":se[e]==="success"?"Response copied":se[e]==="error"?"Copy failed":"Copy response",onClick:()=>{_t(e,a)},children:se[e]==="success"?t.jsx(Ks,{size:14}):t.jsx(qs,{size:14})}),[se,_t]);return t.jsxs("div",{className:"chat-view",children:[t.jsxs("div",{className:`chat-sidebar${I?"":" chat-sidebar--hidden"}`,style:V?void 0:{width:`${Y}px`},children:[t.jsxs("div",{className:"chat-sidebar-scope-toggle",role:"tablist","data-testid":"chat-sidebar-scope-toggle",children:[t.jsx("button",{type:"button",role:"tab",className:`chat-sidebar-scope-btn${re==="direct"?" chat-sidebar-scope-btn--active":""}`,"aria-selected":re==="direct","data-testid":"chat-sidebar-scope-direct",onClick:()=>me("direct"),children:"Direct"}),t.jsx("button",{type:"button",role:"tab",className:`chat-sidebar-scope-btn${re==="rooms"?" chat-sidebar-scope-btn--active":""}`,"aria-selected":re==="rooms","data-testid":"chat-sidebar-scope-rooms",onClick:()=>me("rooms"),children:"Rooms"})]}),re==="direct"?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"chat-sidebar-search-container",children:t.jsxs("div",{className:"chat-sidebar-search-wrapper",children:[t.jsx(Js,{size:14,className:"chat-sidebar-search-icon"}),t.jsx("input",{type:"text",className:"chat-sidebar-search",placeholder:"Search conversations...",value:j,onChange:e=>M(e.target.value),"data-testid":"chat-search-input"})]})}),t.jsx("div",{className:"chat-session-list chat-sidebar-list",children:d?t.jsx("div",{style:{padding:"12px",color:"var(--text-secondary)",fontSize:"13px"},children:"Loading..."}):D.length===0?t.jsx("div",{style:{padding:"12px",color:"var(--text-secondary)",fontSize:"13px"},children:"No conversations yet"}):D.map(e=>t.jsxs("div",{className:`chat-session-item${o?.id===e.id?" chat-session-item--active":""}`,onClick:()=>vs(e.id),onContextMenu:a=>{a.preventDefault(),h({sessionId:e.id,x:a.clientX,y:a.clientY})},"data-testid":`chat-session-${e.id}`,children:[t.jsx("button",{className:"chat-session-delete-btn",onClick:a=>{a.stopPropagation(),i(e.id)},"data-testid":"chat-session-delete-btn","aria-label":"Delete conversation",children:t.jsx(kt,{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.jsxs("span",{className:"chat-session-meta-model",children:[e.modelProvider&&t.jsx(tt,{provider:e.modelProvider,size:"sm"}),t.jsx("span",{children:oe.get(e.agentId)?.name||(e.agentId===Fe?Kt(e.modelProvider,e.modelId)??"Fusion":e.agentId.slice(0,30))})]}),t.jsx("span",{children:e.updatedAt?ss(e.updatedAt):""})]})]},e.id))})]}):t.jsxs("div",{className:"chat-sidebar-rooms","data-testid":"chat-sidebar-rooms",children:[t.jsx("div",{className:"chat-sidebar-rooms-header",children:t.jsxs("button",{type:"button",className:"btn btn-sm btn-primary","data-testid":"chat-create-room-btn",onClick:()=>he(!0),children:[t.jsx(Xe,{size:14}),"Create room"]})}),_.rooms.length===0?t.jsx("div",{className:"chat-sidebar-rooms-empty","data-testid":"chat-sidebar-rooms-empty",children:"No rooms yet."}):t.jsx("div",{className:"chat-session-list chat-sidebar-list",children:_.rooms.map(e=>{const a=_.activeRoom?.id===e.id,l=a?_.activeRoomMembers.length:"—";return t.jsxs("div",{role:"button",tabIndex:0,className:`chat-room-item${a?" chat-room-item--active":""}`,"data-testid":`chat-room-item-${e.slug}`,onClick:()=>{_.selectRoom(e.id),V&&de(!1)},onKeyDown:N=>{(N.key==="Enter"||N.key===" ")&&(N.preventDefault(),_.selectRoom(e.id),V&&de(!1))},children:[t.jsxs("span",{className:"chat-room-item-details",children:[t.jsxs("span",{className:"chat-room-item-name",children:["#",e.name]}),t.jsxs("span",{className:"chat-room-item-meta",children:[l," ",l===1?"member":"members"]})]}),t.jsx("button",{type:"button",className:"btn-icon chat-room-item-delete","data-testid":`chat-room-delete-${e.slug}`,"aria-label":`Delete room ${e.name}`,onClick:N=>{N.stopPropagation(),y(e.id)},children:t.jsx(kt,{size:14})})]},e.id)})})]}),t.jsx("div",{className:"chat-sidebar-footer",children:t.jsxs("button",{className:"btn btn-sm btn-primary chat-sidebar-footer-btn",onClick:()=>G(!0),"data-testid":"chat-new-btn",children:[t.jsx(Xe,{size:14}),"New Chat"]})})]}),!V&&I&&t.jsx("div",{className:"chat-sidebar-resize-handle",role:"separator","aria-orientation":"vertical","aria-valuemin":Ze,"aria-valuemax":et,"aria-valuenow":Y,"aria-label":"Resize chat sidebar",tabIndex:0,onPointerDown:ps,onKeyDown:bs}),v&&t.jsxs("div",{className:"chat-session-context-menu",style:{top:v.y,left:v.x},onClick:e=>e.stopPropagation(),children:[t.jsxs("button",{onClick:()=>fs(v.sessionId),"data-testid":"chat-context-archive",children:[t.jsx(Ys,{size:14}),"Archive"]}),t.jsxs("button",{onClick:()=>{h(null),i(v.sessionId)},"data-testid":"chat-context-delete",children:[t.jsx(kt,{size:14}),"Delete"]})]}),u&&t.jsx("div",{className:"chat-new-dialog-backdrop chat-view-dialog-backdrop",onClick:()=>i(null),children:t.jsxs("div",{className:"chat-new-dialog chat-view-dialog",onClick:e=>e.stopPropagation(),children:[t.jsx("h3",{children:"Delete Conversation?"}),t.jsx("p",{className:"chat-view-delete-dialog-copy",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:()=>i(null),children:"Cancel"}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>void gs(u),children:"Delete"})]})]})}),f&&t.jsx("div",{className:"chat-new-dialog-backdrop chat-view-dialog-backdrop",onClick:()=>y(null),children:t.jsxs("div",{className:"chat-new-dialog chat-view-dialog",onClick:e=>e.stopPropagation(),children:[t.jsx("h3",{children:"Delete Room?"}),t.jsx("p",{className:"chat-view-delete-dialog-copy",children:"This action cannot be undone. This room and all its messages will be permanently deleted."}),t.jsxs("div",{className:"chat-new-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>y(null),children:"Cancel"}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>{(async()=>{try{await _.deleteRoom(f),y(null)}catch{r("Failed to delete room","error")}})()},children:"Delete"})]})]})}),re==="rooms"?t.jsxs("div",{className:"chat-thread",children:[_.activeRoom?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"chat-room-thread-header",children:[V&&t.jsx("button",{className:"btn-icon",onClick:()=>{_.selectRoom(null),de(!0)},"data-testid":"chat-back-btn",children:t.jsx(Ht,{size:16})}),t.jsxs("div",{className:"chat-thread-header-title",children:["#",_.activeRoom.name]}),t.jsx("div",{className:"chat-room-thread-members",children:_.activeRoomMembers.map(e=>t.jsx(Zt,{agent:oe.get(e.agentId)??null},e.agentId))})]}),t.jsxs("div",{className:"chat-messages",ref:Te,onScroll:Lt,children:[_.messagesLoading?t.jsx("div",{style:{color:"var(--text-secondary)",fontSize:"13px"},children:"Loading messages..."}):_.messages.length===0?t.jsx("div",{style:{color:"var(--text-secondary)",fontSize:"13px"},children:"No messages yet. Start the conversation!"}):_.messages.map(e=>{const a=e.senderAgentId?oe.get(e.senderAgentId)?.name??e.senderAgentId.slice(0,30):"You",l={id:e.id,sessionId:e.roomId,role:e.role,content:e.content,thinkingOutput:e.thinkingOutput??void 0,toolCalls:void 0,fallbackInfo:void 0,attachments:e.attachments,createdAt:e.createdAt};return t.jsx(jt,{message:l,forcePlain:L,agentName:a,hideAssistantIdentity:!1,showAssistantModelTag:!1,activeModelTag:null,activeModelProvider:null,activeSessionId:_.activeRoom?.id??null,mentionAgentsByName:ct},e.id)}),t.jsx("div",{ref:At})]})]}):t.jsx("div",{className:"chat-room-empty-pane","data-testid":"chat-rooms-empty-pane",children:"Select a room or create one"}),_.activeRoom&&t.jsx("div",{className:"chat-input-area",children:t.jsxs("div",{className:"chat-input-row",children:[t.jsx("div",{className:"chat-input-wrapper",children:t.jsx("textarea",{ref:ne,className:"chat-input-textarea",placeholder:"Type a message...",value:$,onChange:It,onKeyDown:Ft,rows:1,"data-testid":"chat-input"})}),t.jsx("button",{type:"button",className:"chat-input-send",onClick:()=>{ut()},disabled:!$.trim(),"data-testid":"chat-send-btn",style:{touchAction:"manipulation"},children:t.jsx(Bt,{size:16})})]})})]}):t.jsxs("div",{className:`chat-thread${Oe&&$t?" chat-thread--keyboard-active":""}`,style:is,children:[(gt||!V)&&t.jsxs("div",{className:"chat-thread-header",children:[V&&gt&&t.jsx("button",{className:"btn-icon",onClick:xs,"data-testid":"chat-back-btn",children:t.jsx(Ht,{size:16})}),t.jsxs("div",{className:"chat-thread-header-identity","data-testid":"chat-thread-header-identity",children:[De?t.jsx(tt,{provider:De,size:"md"}):t.jsx(nt,{size:16}),t.jsx("span",{className:"chat-thread-header-title",children:zt}),ys&&t.jsx("span",{className:"chat-model-tag",children:Me})]}),gt&&t.jsx("button",{type:"button",className:`chat-thread-header-render-toggle${L?" chat-thread-header-render-toggle--plain":""}`,"data-testid":"chat-thread-render-toggle","aria-label":L?"Show all messages as rendered Markdown":"Show all messages as plain text",onClick:ks,children:L?t.jsx(Xs,{size:14}):t.jsx(Qs,{size:14})}),!V&&t.jsxs("button",{className:"btn btn-sm btn-primary chat-thread-header-new-chat",onClick:()=>G(!0),"data-testid":"chat-thread-new-chat-btn",children:[t.jsx(Xe,{size:14}),"New Chat"]})]}),t.jsxs("div",{className:"chat-messages",ref:Te,onScroll:Lt,children:[A?t.jsxs(t.Fragment,{children:[c.map(e=>t.jsx(jt,{message:e,forcePlain:L,agentName:pt,hideAssistantIdentity:vt,showAssistantModelTag:bt,activeModelTag:Me,activeModelProvider:De,activeSessionId:o?.id??null,mentionAgentsByName:ct,copyAction:wt&&e.role==="assistant"?yt(e.id,e.content):void 0},e.id)),t.jsxs("div",{className:"chat-message chat-message--assistant chat-message--streaming",children:[!vt&&t.jsxs("div",{className:"chat-message-avatar",children:[De?t.jsx(tt,{provider:De,size:"sm"}):t.jsx(nt,{size:14}),t.jsx("span",{children:pt}),bt]}),E?Cs(E,L):t.jsx("div",{className:"chat-message-content chat-message-content--waiting",children:P?"Thinking…":"Connecting…"}),wt&&E&&yt("__streaming__",E,"chat-copy-response-streaming"),ns(w),P&&t.jsxs("details",{className:"chat-message-thinking",children:[t.jsx("summary",{children:"Thinking"}),t.jsx("pre",{className:"chat-message-thinking-content",children:P})]}),t.jsxs("div",{className:"chat-typing-indicator",children:[t.jsx("span",{}),t.jsx("span",{}),t.jsx("span",{})]})]})]}):x?t.jsx("div",{style:{color:"var(--text-secondary)",fontSize:"13px"},children:"Loading messages..."}):c.length===0&&!o?ws():c.length===0&&o?t.jsx("div",{style:{color:"var(--text-secondary)",fontSize:"13px"},children:"No messages yet. Start the conversation!"}):t.jsx(t.Fragment,{children:c.map(e=>t.jsx(jt,{message:e,forcePlain:L,agentName:pt,hideAssistantIdentity:vt,showAssistantModelTag:bt,activeModelTag:Me,activeModelProvider:De,activeSessionId:o?.id??null,mentionAgentsByName:ct,copyAction:wt&&e.role==="assistant"?yt(e.id,e.content):void 0},e.id))}),t.jsx("div",{ref:At})]}),B&&t.jsxs("button",{type:"button",className:"btn btn-sm chat-jump-to-latest","data-testid":"chat-jump-to-latest",onClick:Be,children:[t.jsx(Zs,{size:14}),"Latest"]}),o&&t.jsxs("div",{className:"chat-input-area",children:[t.jsx("input",{ref:Et,type:"file",accept:"image/*,.txt,.json,.yaml,.yml,.log,.csv,.xml,.md",multiple:!0,style:{display:"none"},onChange:e=>{Je(e.target.files),e.target.value=""}}),ye&&t.jsx("div",{className:"chat-skill-menu","data-testid":"chat-skill-menu",role:"listbox","aria-label":"Skill suggestions",children:Re?t.jsx("div",{className:"chat-skill-menu-empty",children:"Loading skills…"}):ce.length===0?t.jsx("div",{className:"chat-skill-menu-empty",children:Ie?"No skills found":"No skills available"}):ce.map((e,a)=>t.jsxs("button",{type:"button",role:"option","aria-selected":a===Ee,className:`chat-skill-menu-item${a===Ee?" chat-skill-menu-item--highlighted":""}`,onMouseDown:l=>l.preventDefault(),onMouseEnter:()=>ge(a),onClick:()=>mt(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))}),U.length>0&&t.jsx("div",{className:"chat-attachment-previews","data-testid":"chat-attachment-previews",children:U.map((e,a)=>t.jsxs("div",{className:"chat-attachment-preview","data-testid":`chat-attachment-preview-${a}`,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:()=>cs(a),"data-testid":`chat-attachment-remove-${a}`,"aria-label":`Remove ${e.file.name}`,children:"×"})]},e.previewUrl||`${e.file.name}-${a}`))}),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:()=>Et.current?.click(),children:t.jsx(en,{size:16})}),t.jsxs("div",{className:`chat-input-wrapper${H?" chat-input-wrapper--dragover":""}`,onDragOver:e=>{e.preventDefault(),O(!0)},onDragLeave:()=>O(!1),onDrop:e=>{e.preventDefault(),O(!1),Je(e.dataTransfer.files)},children:[t.jsx("textarea",{ref:ne,className:"chat-input-textarea",placeholder:"Type a message...",value:$,onChange:It,onKeyDown:Ft,onKeyUp:us,onClick:ft,onBlur:ms,onFocus:hs,onPaste:ls,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(tn,{agents:He,filter:ke,highlightedIndex:k,visible:ue,onSelect:ht,position:"below"}),t.jsx(sn,{visible:z.mentionActive&&!ue,position:rs,files:z.files,selectedIndex:z.selectedIndex,onSelect:e=>{const a=z.selectFile(e,$);K(a),z.dismissMention(),ze(!1),ne.current?.focus()},loading:z.loading}),T&&t.jsxs("div",{className:"chat-pending-message","data-testid":"chat-pending-indicator",children:[t.jsx("span",{children:`Queued: ${Ss}`}),t.jsx("button",{type:"button",className:"chat-pending-message-dismiss","aria-label":"Dismiss queued message","data-testid":"chat-pending-dismiss",onClick:m,children:"×"})]})]}),A?t.jsx("button",{className:"chat-input-stop",onClick:b,"aria-label":"Stop generation","data-testid":"chat-stop-btn",children:t.jsx(nn,{size:14})}):t.jsx("button",{type:"button",className:"chat-input-send",onPointerDown:e=>{e.pointerType&&e.pointerType!=="mouse"&&e.preventDefault()},onMouseDown:e=>{e.preventDefault()},onClick:()=>{dt()},disabled:!$.trim()&&U.length===0,"data-testid":"chat-send-btn",style:{touchAction:"manipulation"},children:t.jsx(Bt,{size:16})})]})]})]}),t.jsx(fn,{isOpen:Ge,onClose:()=>he(!1),projectId:n,existingRoomNames:_.rooms.map(e=>e.name),onCreate:async e=>{await _.createRoom({name:e.name,memberAgentIds:e.memberAgentIds}),he(!1)}}),F&&t.jsx(wn,{projectId:n,onClose:()=>G(!1),onCreate:ds})]})}export{Nn as ChatView};
@@ -1 +1 @@
1
- import{r,j as t}from"./vendor-react-K0fH_qHe.js";import{bP as De,bQ as de,bR as Ze,bS as ue,s as Ue,bT as ge,bU as we,bV as xe,bW as ye,bX as et,bY as ae,bZ as tt,b_ as rt,b$ as st,c0 as nt,c1 as at,c2 as ie,L as ee,S as it,M as lt,c3 as ct,a as ot,c4 as Me,T as Ae,c5 as dt,U as ut,aQ as vt,aR as mt,a9 as ft,ar as pt,R as ht}from"./index-CQyVRLOb.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 G(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=G(l.data);if(v?.lines){const N=v.lines.map(Y);f(Pe(N))}},log:l=>{if(n.current!==s)return;const v=G(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=G(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=G(l.data);v?.line&&f(N=>le(N,v.line))},status:l=>{if(n.current!==s)return;const v=G(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=G(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:I,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 Q=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(Q){F(Q.command);return}b.length>0&&F(m=>m.trim().length>0?m:b[0]?.command??"")},[b,Q,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),I();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),I()}catch{q.current.src=h,W(!1),I()}},[h,q,I]),J=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=Q?.cwd??$;J("start",()=>k(m,ne),"Dev server started.")},Xe=()=>{J("stop",U,"Dev server stopped.")},qe=()=>{J("restart",C,"Dev server restarted.")},Ge=()=>{const m=O.trim(),$=m.length>0?m:null;J("preview",()=>P($),$?"Preview URL updated.":"Preview URL override cleared.")},Ie=r.useCallback(()=>{f&&u()},[f,u]),Qe=n==="starting"||n==="running"||s!==null,Je=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:Qe,"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:Je,"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:Ie,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:Ge,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,{})}),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,{})})]})]}),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
+ import{r,j as t}from"./vendor-react-K0fH_qHe.js";import{bP as De,bQ as de,bR as Ze,bS as ue,s as Ue,bT as ge,bU as we,bV as xe,bW as ye,bX as et,bY as ae,bZ as tt,b_ as rt,b$ as st,c0 as nt,c1 as at,c2 as ie,L as ee,S as it,M as lt,c3 as ct,a as ot,c4 as Me,T as Ae,c5 as dt,U as ut,aQ as vt,aR as mt,a9 as ft,ar as pt,R as ht}from"./index-TFYXEVpn.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 G(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=G(l.data);if(v?.lines){const N=v.lines.map(Y);f(Pe(N))}},log:l=>{if(n.current!==s)return;const v=G(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=G(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=G(l.data);v?.line&&f(N=>le(N,v.line))},status:l=>{if(n.current!==s)return;const v=G(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=G(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:I,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 Q=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(Q){F(Q.command);return}b.length>0&&F(m=>m.trim().length>0?m:b[0]?.command??"")},[b,Q,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),I();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),I()}catch{q.current.src=h,W(!1),I()}},[h,q,I]),J=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=Q?.cwd??$;J("start",()=>k(m,ne),"Dev server started.")},Xe=()=>{J("stop",U,"Dev server stopped.")},qe=()=>{J("restart",C,"Dev server restarted.")},Ge=()=>{const m=O.trim(),$=m.length>0?m:null;J("preview",()=>P($),$?"Preview URL updated.":"Preview URL override cleared.")},Ie=r.useCallback(()=>{f&&u()},[f,u]),Qe=n==="starting"||n==="running"||s!==null,Je=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:Qe,"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:Je,"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:Ie,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:Ge,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,{})}),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,{})})]})]}),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{ep as f,eq as g,da as b,b as y,ad as P,a8 as H,a9 as C,L as O,ao as v}from"./index-CQyVRLOb.js";import{F as z}from"./folder-open-DHjELt8-.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{en as f,eo as g,d8 as b,b as y,ad as P,a8 as H,a9 as C,L as O,ao as v}from"./index-TFYXEVpn.js";import{F as z}from"./folder-open-k1xmUMyr.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 +1 @@
1
- import{r as s,j as e}from"./vendor-react-K0fH_qHe.js";import{a5 as oe,a6 as K,f as le,a7 as ie,F as z,a8 as de,a9 as ue,S as me,X as he,R as pe,aa as fe,ab as W,ac as V,a as X,b as je,ad as xe}from"./index-CQyVRLOb.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("")},[]),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)," · ",_(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{a5 as oe,a6 as K,f as le,a7 as ie,F as z,a8 as de,a9 as ue,S as me,X as he,R as pe,aa as fe,ab as W,ac as V,a as X,b as je,ad as xe}from"./index-TFYXEVpn.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("")},[]),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)," · ",_(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 +1 @@
1
- import{r as l,j as e}from"./vendor-react-K0fH_qHe.js";import{aF as L,aG as z,aH as O,x as U,an as _,R as D,ar as V}from"./index-CQyVRLOb.js";import"./vendor-xterm-DzcZoU0P.js";const $=300,P=15e3;function T(a){if(!a.trim())return;const t=Number(a);return Number.isFinite(t)?t:void 0}function j(...a){for(const t of a)if(Array.isArray(t))return t;return[]}function v(a){return typeof a=="object"&&a!==null?a:{}}function q(a){const t=v(a),r=v(t.taskSnapshot);return{id:String(t.id??t.evalId??""),runId:String(t.runId??t.batchId??""),taskId:String(t.taskId??r.taskId??""),taskTitle:String(r.title??t.taskTitle??t.title??"Untitled task"),createdAt:String(t.createdAt??t.timestamp??t.updatedAt??new Date(0).toISOString()),overallScore:typeof t.overallScore=="number"?t.overallScore:null,maxScore:typeof t.maxScore=="number"?t.maxScore:null,categoryScores:j(t.categoryScores,v(t.scores).categories)}}function B(a){const t=v(a);return{...q(t),rationale:String(t.rationale??t.summary??""),evidence:j(t.evidence,v(t.details).evidence),followUps:j(t.followUps,v(t.recommendations).followUps)}}function G(a){const t=a?.projectId,[r,g]=l.useState({q:"",runId:"",scoreMin:"",scoreMax:""}),[S,h]=l.useState([]),[k,p]=l.useState([]),[i,f]=l.useState(null),[I,c]=l.useState(null),[E,w]=l.useState(0),[N,b]=l.useState(!0),[R,s]=l.useState(null),n=l.useRef(0),d=l.useCallback(async()=>{const u=++n.current;b(!0),s(null);try{const[o,y]=await Promise.all([L({q:r.q||void 0,runId:r.runId||void 0,scoreMin:T(r.scoreMin),scoreMax:T(r.scoreMax),limit:100,offset:0},t),z(t)]);if(u!==n.current)return;const M=j(o.results,o.evals,o.items).map(q);p(M),w(typeof o.count=="number"?o.count:M.length);const F=j(y.runs,y.items);h(F.map(C=>{const x=v(C),A=v(x.counts);return{id:String(x.id??""),createdAt:String(x.createdAt??""),completedAt:typeof x.completedAt=="string"?x.completedAt:void 0,status:String(x.status??"pending"),evaluatedTaskCount:typeof A.totalTasks=="number"?A.totalTasks:0}})),i&&!M.some(C=>C.id===i)&&(f(null),c(null))}catch(o){if(u!==n.current)return;s(o instanceof Error?o.message:"Failed to load evals")}finally{u===n.current&&b(!1)}},[r.q,r.runId,r.scoreMax,r.scoreMin,t,i]),m=l.useCallback(async u=>{const o=await O(u,t),y=o.result??o;c(B(y))},[t]);return l.useEffect(()=>{const u=window.setTimeout(()=>{d()},$);return()=>window.clearTimeout(u)},[d]),l.useEffect(()=>{if(!i){c(null);return}m(i)},[m,i]),l.useEffect(()=>{const u=window.setInterval(()=>{d(),i&&m(i)},P);return()=>window.clearInterval(u)},[m,d,i]),{loading:N,error:R,results:k,count:E,runs:S,filters:r,setFilters:g,refresh:d,selectedEvalId:i,setSelectedEvalId:f,selectedEval:I}}function W({projectId:a,onOpenSettings:t,onOpenTaskDetail:r}){const{loading:g,error:S,results:h,runs:k,filters:p,setFilters:i,selectedEvalId:f,setSelectedEvalId:I,selectedEval:c,refresh:E}=G({projectId:a}),[w,N]=l.useState(!0);l.useEffect(()=>{let s=!1;return U(a).then(n=>{if(s)return;const d=n.evalSettings?.enabled;N(d??!1)}).catch(()=>{s||N(!1)}),()=>{s=!0}},[a]);const b=h.length>0,R=l.useMemo(()=>h.find(s=>s.id===f)??null,[h,f]);return w?e.jsxs("section",{className:"evals-view","data-testid":"evals-view",children:[e.jsxs("div",{className:"evals-list card",children:[e.jsxs("div",{className:"evals-toolbar",children:[e.jsx("input",{className:"input",placeholder:"Search task or rationale",value:p.q,onChange:s=>i(n=>({...n,q:s.target.value}))}),e.jsxs("select",{className:"select",value:p.runId,onChange:s=>i(n=>({...n,runId:s.target.value})),children:[e.jsx("option",{value:"",children:"All runs"}),k.map(s=>e.jsx("option",{value:s.id,children:s.id},s.id))]}),e.jsx("input",{className:"input",placeholder:"Min score",value:p.scoreMin,onChange:s=>i(n=>({...n,scoreMin:s.target.value}))}),e.jsx("input",{className:"input",placeholder:"Max score",value:p.scoreMax,onChange:s=>i(n=>({...n,scoreMax:s.target.value}))}),e.jsx("button",{className:"btn btn-icon",type:"button",onClick:()=>void E(),"aria-label":"Refresh evals",children:e.jsx(D,{size:16})})]}),g&&e.jsx("p",{className:"evals-state","data-testid":"evals-loading",children:"Loading evals…"}),S&&e.jsx("p",{className:"evals-state evals-state--error",children:S}),!g&&!S&&!b&&e.jsx("p",{className:"evals-state",children:"No evals yet. Scheduled evals review tasks completed since the last run."}),e.jsx("ul",{className:"evals-results","data-testid":"evals-results",children:h.map(s=>e.jsx("li",{children:e.jsxs("button",{className:`evals-result ${s.id===f?"evals-result--active":""}`,type:"button",onClick:()=>I(s.id),children:[e.jsx("span",{className:"evals-result-title",children:s.taskTitle}),e.jsxs("span",{className:"evals-result-meta",children:[s.taskId," · ",s.runId," · ",s.overallScore??"n/a"]})]})},s.id))})]}),e.jsxs("div",{className:"evals-detail card","data-testid":"evals-detail",children:[!c&&e.jsx("p",{className:"evals-state",children:"Select an evaluation to inspect scores, rationale, and evidence."}),c&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"evals-detail-title",children:R?.taskTitle??c.taskTitle}),e.jsxs("p",{className:"evals-result-meta",children:[c.taskId," · ",c.runId]}),e.jsxs("p",{className:"evals-score",children:["Overall score: ",c.overallScore??"n/a"]}),e.jsx("ul",{className:"evals-categories",children:c.categoryScores.map(s=>e.jsxs("li",{children:[s.category,": ",s.finalScore]},s.category))}),e.jsx("p",{className:"evals-rationale",children:c.rationale||"No rationale recorded."}),e.jsxs("div",{children:[e.jsx("h4",{children:"Evidence"}),e.jsx("ul",{className:"evals-links",children:c.evidence.map((s,n)=>{const d=typeof s.metadata?.taskId=="string"?s.metadata.taskId:void 0,m=typeof s.metadata?.url=="string"?s.metadata.url:void 0;return e.jsx("li",{children:d?e.jsx("button",{type:"button",className:"btn",onClick:()=>r?.(d),children:s.ref}):m?e.jsxs("a",{href:m,target:"_blank",rel:"noreferrer",className:"evals-external-link",children:[s.ref,e.jsx(V,{size:14})]}):e.jsx("span",{children:s.ref})},`${s.ref}-${n}`)})})]}),e.jsxs("div",{children:[e.jsx("h4",{children:"Suggested follow-up tasks"}),e.jsxs("ul",{className:"evals-follow-ups",children:[c.followUps.length===0&&e.jsx("li",{children:"None"}),c.followUps.map(s=>e.jsxs("li",{children:[e.jsx("strong",{children:s.title}),e.jsx("p",{children:s.rationale})]},s.suggestionId))]})]})]})]})]}):e.jsxs("section",{className:"evals-view card","data-testid":"evals-disabled",children:[e.jsx("h2",{className:"evals-title",children:"Scheduled evals are disabled"}),e.jsx("p",{className:"evals-empty-copy",children:"Enable Scheduled Evals to review scored tasks, evidence, and follow-up recommendations."}),e.jsxs("button",{className:"btn btn-primary",type:"button",onClick:()=>t?.("scheduled-evals"),children:[e.jsx(_,{size:16}),"Open Scheduled Evals Settings"]})]})}export{W as EvalsView};
1
+ import{r as l,j as e}from"./vendor-react-K0fH_qHe.js";import{aF as L,aG as z,aH as O,x as U,an as _,R as D,ar as V}from"./index-TFYXEVpn.js";import"./vendor-xterm-DzcZoU0P.js";const $=300,P=15e3;function T(a){if(!a.trim())return;const t=Number(a);return Number.isFinite(t)?t:void 0}function j(...a){for(const t of a)if(Array.isArray(t))return t;return[]}function v(a){return typeof a=="object"&&a!==null?a:{}}function q(a){const t=v(a),r=v(t.taskSnapshot);return{id:String(t.id??t.evalId??""),runId:String(t.runId??t.batchId??""),taskId:String(t.taskId??r.taskId??""),taskTitle:String(r.title??t.taskTitle??t.title??"Untitled task"),createdAt:String(t.createdAt??t.timestamp??t.updatedAt??new Date(0).toISOString()),overallScore:typeof t.overallScore=="number"?t.overallScore:null,maxScore:typeof t.maxScore=="number"?t.maxScore:null,categoryScores:j(t.categoryScores,v(t.scores).categories)}}function B(a){const t=v(a);return{...q(t),rationale:String(t.rationale??t.summary??""),evidence:j(t.evidence,v(t.details).evidence),followUps:j(t.followUps,v(t.recommendations).followUps)}}function G(a){const t=a?.projectId,[r,g]=l.useState({q:"",runId:"",scoreMin:"",scoreMax:""}),[S,h]=l.useState([]),[k,p]=l.useState([]),[i,f]=l.useState(null),[I,c]=l.useState(null),[E,w]=l.useState(0),[N,b]=l.useState(!0),[R,s]=l.useState(null),n=l.useRef(0),d=l.useCallback(async()=>{const u=++n.current;b(!0),s(null);try{const[o,y]=await Promise.all([L({q:r.q||void 0,runId:r.runId||void 0,scoreMin:T(r.scoreMin),scoreMax:T(r.scoreMax),limit:100,offset:0},t),z(t)]);if(u!==n.current)return;const M=j(o.results,o.evals,o.items).map(q);p(M),w(typeof o.count=="number"?o.count:M.length);const F=j(y.runs,y.items);h(F.map(C=>{const x=v(C),A=v(x.counts);return{id:String(x.id??""),createdAt:String(x.createdAt??""),completedAt:typeof x.completedAt=="string"?x.completedAt:void 0,status:String(x.status??"pending"),evaluatedTaskCount:typeof A.totalTasks=="number"?A.totalTasks:0}})),i&&!M.some(C=>C.id===i)&&(f(null),c(null))}catch(o){if(u!==n.current)return;s(o instanceof Error?o.message:"Failed to load evals")}finally{u===n.current&&b(!1)}},[r.q,r.runId,r.scoreMax,r.scoreMin,t,i]),m=l.useCallback(async u=>{const o=await O(u,t),y=o.result??o;c(B(y))},[t]);return l.useEffect(()=>{const u=window.setTimeout(()=>{d()},$);return()=>window.clearTimeout(u)},[d]),l.useEffect(()=>{if(!i){c(null);return}m(i)},[m,i]),l.useEffect(()=>{const u=window.setInterval(()=>{d(),i&&m(i)},P);return()=>window.clearInterval(u)},[m,d,i]),{loading:N,error:R,results:k,count:E,runs:S,filters:r,setFilters:g,refresh:d,selectedEvalId:i,setSelectedEvalId:f,selectedEval:I}}function W({projectId:a,onOpenSettings:t,onOpenTaskDetail:r}){const{loading:g,error:S,results:h,runs:k,filters:p,setFilters:i,selectedEvalId:f,setSelectedEvalId:I,selectedEval:c,refresh:E}=G({projectId:a}),[w,N]=l.useState(!0);l.useEffect(()=>{let s=!1;return U(a).then(n=>{if(s)return;const d=n.evalSettings?.enabled;N(d??!1)}).catch(()=>{s||N(!1)}),()=>{s=!0}},[a]);const b=h.length>0,R=l.useMemo(()=>h.find(s=>s.id===f)??null,[h,f]);return w?e.jsxs("section",{className:"evals-view","data-testid":"evals-view",children:[e.jsxs("div",{className:"evals-list card",children:[e.jsxs("div",{className:"evals-toolbar",children:[e.jsx("input",{className:"input",placeholder:"Search task or rationale",value:p.q,onChange:s=>i(n=>({...n,q:s.target.value}))}),e.jsxs("select",{className:"select",value:p.runId,onChange:s=>i(n=>({...n,runId:s.target.value})),children:[e.jsx("option",{value:"",children:"All runs"}),k.map(s=>e.jsx("option",{value:s.id,children:s.id},s.id))]}),e.jsx("input",{className:"input",placeholder:"Min score",value:p.scoreMin,onChange:s=>i(n=>({...n,scoreMin:s.target.value}))}),e.jsx("input",{className:"input",placeholder:"Max score",value:p.scoreMax,onChange:s=>i(n=>({...n,scoreMax:s.target.value}))}),e.jsx("button",{className:"btn btn-icon",type:"button",onClick:()=>void E(),"aria-label":"Refresh evals",children:e.jsx(D,{size:16})})]}),g&&e.jsx("p",{className:"evals-state","data-testid":"evals-loading",children:"Loading evals…"}),S&&e.jsx("p",{className:"evals-state evals-state--error",children:S}),!g&&!S&&!b&&e.jsx("p",{className:"evals-state",children:"No evals yet. Scheduled evals review tasks completed since the last run."}),e.jsx("ul",{className:"evals-results","data-testid":"evals-results",children:h.map(s=>e.jsx("li",{children:e.jsxs("button",{className:`evals-result ${s.id===f?"evals-result--active":""}`,type:"button",onClick:()=>I(s.id),children:[e.jsx("span",{className:"evals-result-title",children:s.taskTitle}),e.jsxs("span",{className:"evals-result-meta",children:[s.taskId," · ",s.runId," · ",s.overallScore??"n/a"]})]})},s.id))})]}),e.jsxs("div",{className:"evals-detail card","data-testid":"evals-detail",children:[!c&&e.jsx("p",{className:"evals-state",children:"Select an evaluation to inspect scores, rationale, and evidence."}),c&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"evals-detail-title",children:R?.taskTitle??c.taskTitle}),e.jsxs("p",{className:"evals-result-meta",children:[c.taskId," · ",c.runId]}),e.jsxs("p",{className:"evals-score",children:["Overall score: ",c.overallScore??"n/a"]}),e.jsx("ul",{className:"evals-categories",children:c.categoryScores.map(s=>e.jsxs("li",{children:[s.category,": ",s.finalScore]},s.category))}),e.jsx("p",{className:"evals-rationale",children:c.rationale||"No rationale recorded."}),e.jsxs("div",{children:[e.jsx("h4",{children:"Evidence"}),e.jsx("ul",{className:"evals-links",children:c.evidence.map((s,n)=>{const d=typeof s.metadata?.taskId=="string"?s.metadata.taskId:void 0,m=typeof s.metadata?.url=="string"?s.metadata.url:void 0;return e.jsx("li",{children:d?e.jsx("button",{type:"button",className:"btn",onClick:()=>r?.(d),children:s.ref}):m?e.jsxs("a",{href:m,target:"_blank",rel:"noreferrer",className:"evals-external-link",children:[s.ref,e.jsx(V,{size:14})]}):e.jsx("span",{children:s.ref})},`${s.ref}-${n}`)})})]}),e.jsxs("div",{children:[e.jsx("h4",{children:"Suggested follow-up tasks"}),e.jsxs("ul",{className:"evals-follow-ups",children:[c.followUps.length===0&&e.jsx("li",{children:"None"}),c.followUps.map(s=>e.jsxs("li",{children:[e.jsx("strong",{children:s.title}),e.jsx("p",{children:s.rationale})]},s.suggestionId))]})]})]})]})]}):e.jsxs("section",{className:"evals-view card","data-testid":"evals-disabled",children:[e.jsx("h2",{className:"evals-title",children:"Scheduled evals are disabled"}),e.jsx("p",{className:"evals-empty-copy",children:"Enable Scheduled Evals to review scored tasks, evidence, and follow-up recommendations."}),e.jsxs("button",{className:"btn btn-primary",type:"button",onClick:()=>t?.("scheduled-evals"),children:[e.jsx(_,{size:16}),"Open Scheduled Evals Settings"]})]})}export{W as EvalsView};
@@ -1,4 +1,4 @@
1
- import{r as s,j as e}from"./vendor-react-K0fH_qHe.js";import{bm as L,e9 as F,ea as H,eb as V,ec as U,ed as K}from"./index-CQyVRLOb.js";function fe({value:o,onChange:u,projectId:h,disabled:m=!1,id:g,label:w="Skills"}){const[k,l]=s.useState([]),[c,f]=s.useState(!0);s.useEffect(()=>{let n=!1;return f(!0),L(h).then(p=>{n||l(p)}).catch(()=>{n||l([])}).finally(()=>{n||f(!1)}),()=>{n=!0}},[h]);const j=n=>{o.includes(n)||u([...o,n])},d=n=>{u(o.filter(p=>p!==n))},I=n=>k.find(S=>S.id===n)?.name??n,x=k.filter(n=>!o.includes(n.id));return e.jsxs("div",{className:"skill-multiselect","data-testid":"skill-multiselect",children:[w&&e.jsx("label",{htmlFor:g?`${g}-select`:void 0,className:"skill-multiselect-label",children:w}),o.length>0&&e.jsx("div",{className:"skill-multiselect-chips","data-testid":"skill-chips",children:o.map(n=>e.jsxs("span",{className:"skill-chip","data-testid":`skill-chip-${n}`,children:[e.jsx("span",{className:"skill-chip-name",children:I(n)}),e.jsx("button",{type:"button",className:"skill-chip-remove",onClick:()=>d(n),disabled:m,"aria-label":`Remove ${I(n)}`,"data-testid":`remove-skill-${n}`,children:"×"})]},n))}),e.jsx("div",{className:"skill-multiselect-add",children:c?e.jsx("span",{className:"skill-multiselect-loading","data-testid":"skills-loading",children:"Loading skills…"}):x.length===0?e.jsx("span",{className:"skill-multiselect-empty","data-testid":"skills-empty",children:o.length===0?"No skills discovered":"All skills selected"}):e.jsxs("select",{id:g?`${g}-select`:void 0,className:"select skill-multiselect-dropdown",value:"",onChange:n=>{n.target.value&&(j(n.target.value),n.target.value="")},disabled:m,"data-testid":"skill-dropdown",children:[e.jsx("option",{value:"",children:"Add a skill…"}),x.map(n=>e.jsx("option",{value:n.id,children:n.name},n.id))]})})]})}const B=/(?:^|\/)skills\/([^/]+)\/SKILL\.md$/i;function ye(o){const u=o.trim();if(!u)return o;const h=u.match(B);return h?.[1]?h[1]:u}const Q=`# Soul: Chief Executive Officer
1
+ import{r as s,j as e}from"./vendor-react-K0fH_qHe.js";import{bm as L,e7 as F,e8 as H,e9 as V,ea as U,eb as K}from"./index-TFYXEVpn.js";function fe({value:o,onChange:u,projectId:h,disabled:m=!1,id:g,label:w="Skills"}){const[k,l]=s.useState([]),[c,f]=s.useState(!0);s.useEffect(()=>{let n=!1;return f(!0),L(h).then(p=>{n||l(p)}).catch(()=>{n||l([])}).finally(()=>{n||f(!1)}),()=>{n=!0}},[h]);const j=n=>{o.includes(n)||u([...o,n])},d=n=>{u(o.filter(p=>p!==n))},I=n=>k.find(S=>S.id===n)?.name??n,x=k.filter(n=>!o.includes(n.id));return e.jsxs("div",{className:"skill-multiselect","data-testid":"skill-multiselect",children:[w&&e.jsx("label",{htmlFor:g?`${g}-select`:void 0,className:"skill-multiselect-label",children:w}),o.length>0&&e.jsx("div",{className:"skill-multiselect-chips","data-testid":"skill-chips",children:o.map(n=>e.jsxs("span",{className:"skill-chip","data-testid":`skill-chip-${n}`,children:[e.jsx("span",{className:"skill-chip-name",children:I(n)}),e.jsx("button",{type:"button",className:"skill-chip-remove",onClick:()=>d(n),disabled:m,"aria-label":`Remove ${I(n)}`,"data-testid":`remove-skill-${n}`,children:"×"})]},n))}),e.jsx("div",{className:"skill-multiselect-add",children:c?e.jsx("span",{className:"skill-multiselect-loading","data-testid":"skills-loading",children:"Loading skills…"}):x.length===0?e.jsx("span",{className:"skill-multiselect-empty","data-testid":"skills-empty",children:o.length===0?"No skills discovered":"All skills selected"}):e.jsxs("select",{id:g?`${g}-select`:void 0,className:"select skill-multiselect-dropdown",value:"",onChange:n=>{n.target.value&&(j(n.target.value),n.target.value="")},disabled:m,"data-testid":"skill-dropdown",children:[e.jsx("option",{value:"",children:"Add a skill…"}),x.map(n=>e.jsx("option",{value:n.id,children:n.name},n.id))]})})]})}const B=/(?:^|\/)skills\/([^/]+)\/SKILL\.md$/i;function ye(o){const u=o.trim();if(!u)return o;const h=u.match(B);return h?.[1]?h[1]:u}const Q=`# Soul: Chief Executive Officer
2
2
 
3
3
  I am a strategic leader who connects every decision to business outcomes.
4
4
 
@@ -1,4 +1,4 @@
1
- import{r,j as e}from"./vendor-react-K0fH_qHe.js";import{c as xe,ae as Re,af as De,ag as Pe,ah as Le,ai as Ue,aj as he,ak as Ge,h as Te,j as de,al as w,X as ue,am as ie,R as j,an as _e,m as Oe,C as pe,ao as X,ap as ge,aq as qe,I as ye,ar as Be,as as be,at as He}from"./index-CQyVRLOb.js";import{U as me}from"./users--syrel4l.js";import"./vendor-xterm-DzcZoU0P.js";/**
1
+ import{r,j as e}from"./vendor-react-K0fH_qHe.js";import{c as xe,ae as Re,af as De,ag as Pe,ah as Le,ai as Ue,aj as he,ak as Ge,h as Te,j as de,al as w,X as ue,am as ie,R as j,an as _e,m as Oe,C as pe,ao as X,ap as ge,aq as qe,I as ye,ar as Be,as as be,at as He}from"./index-TFYXEVpn.js";import{U as me}from"./users-C519GSjH.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.
@@ -0,0 +1,2 @@
1
+ import{r as a,j as e}from"./vendor-react-K0fH_qHe.js";import{u as Le}from"./SettingsModal-CUCyaAyE.js";import{bA as Ee,bB as Me,bC as Ie,y as Re,bD as qe,bE as _e,bF as Pe,bG as ke,bH as we,bI as We,bJ as Oe,bK as Te,bL as Ae,bM as $e,x as Ue,bN as He,L as w,bO as Fe}from"./index-TFYXEVpn.js";import"./vendor-xterm-DzcZoU0P.js";const O=".fusion/memory/MEMORY.md",Qe=5e4,Ye="0 3 * * *",Be="0 4 * * *";function he(i){return{memoryEnabled:i.memoryEnabled!==!1,memoryAutoSummarizeEnabled:i.memoryAutoSummarizeEnabled??!1,memoryAutoSummarizeThresholdChars:i.memoryAutoSummarizeThresholdChars??Qe,memoryAutoSummarizeSchedule:i.memoryAutoSummarizeSchedule??Ye,memoryDreamsEnabled:i.memoryDreamsEnabled??!1,memoryDreamsSchedule:i.memoryDreamsSchedule??Be}}function De(i,t){return i.some(m=>m.path===t)?t:i.find(m=>m.path===O)?.path??i[0]?.path??O}function Ge(i={}){const{projectId:t}=i,[m,u]=a.useState(""),[C,A]=a.useState(!0),[E,M]=a.useState(!1),[b,x]=a.useState(!1),[r,p]=a.useState(null),[T,J]=a.useState(!0),[X,L]=a.useState(!1),[S,P]=a.useState(()=>he({})),[F,ee]=a.useState(!0),[ue,$]=a.useState(!1),[o,v]=a.useState([]),[se,I]=a.useState(!0),[c,k]=a.useState(O),[W,y]=a.useState(""),[d,te]=a.useState(!1),[U,f]=a.useState(!1),[ae,H]=a.useState(!1),[ne,Q]=a.useState(!1),[Y,re]=a.useState(!1),[D,z]=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:K,refresh:j}=Le({projectId:t}),be=a.useCallback(n=>{y(n),f(!0)},[]),N=a.useCallback(async n=>{te(!0);try{const{content:l}=await Ee(n,t);k(n),y(l),f(!1)}finally{te(!1)}},[t]),q=a.useCallback(async()=>{I(!0);try{const{files:n}=await Me(t);if(v(n),n.length===0){k(O),y(""),f(!1);return}const l=De(n,c);l!==c&&await N(l)}finally{I(!1)}},[t,c,N]);a.useEffect(()=>{let n=!1;async function l(){try{const s=await $e(t);n||(u(s.content),A(!1))}catch{n||(u(""),A(!1))}}return l(),()=>{n=!0}},[t]),a.useEffect(()=>{let n=!1;async function l(){try{const s=await we(t);n||(p(s.content),L(s.exists),J(!1))}catch{n||(p(null),L(!1),J(!1))}}return l(),()=>{n=!0}},[t]),a.useEffect(()=>{let n=!1;async function l(){ee(!0);try{const s=await Ue(t);n||P(he(s))}catch{n||P(he({}))}finally{n||ee(!1)}}return l(),()=>{n=!0}},[t]),a.useEffect(()=>{let n=!1;async function l(){I(!0);try{const{files:s}=await Me(t);if(n)return;if(v(s),s.length===0){k(O),y(""),f(!1);return}const h=De(s,c),{content:g}=await Ee(h,t);if(n)return;k(h),y(g),f(!1)}catch{n||(v([]),k(O),y(""),f(!1))}finally{n||I(!1)}}return l(),()=>{n=!0}},[t,c]),a.useEffect(()=>{let n=!1;async function l(){try{const s=await ke(t);n||(z(s),R(!1))}catch{n||(z(null),R(!1))}}return l(),()=>{n=!0}},[t]),a.useEffect(()=>{let n=!1;async function l(){try{const s=await He(t);n||V(s)}catch{n||V(null)}}return l(),()=>{n=!0}},[t]);const ce=a.useCallback(n=>{u(n),M(!0)},[]),oe=a.useCallback(async()=>{if(E){x(!0);try{await Ie(m,t),M(!1)}finally{x(!1)}}},[m,E,t]),xe=a.useCallback(async n=>{$(!0);try{const l=await Re(n,t);P(he(l))}finally{$(!1)}},[t]),pe=a.useCallback(async n=>{await N(n)},[N]),fe=a.useCallback(async()=>{if(U){H(!0);try{await qe(c,W,t),f(!1),await q()}finally{H(!1)}}},[W,U,c,t,q]),je=a.useCallback(async()=>{G(!0);try{const n=await _e(t);return await j(),n}finally{G(!1)}},[t,j]),Se=a.useCallback(async n=>Pe(n,t),[t]),Z=a.useCallback(async()=>{try{const n=await ke(t);z(n)}catch{z(null)}},[t]),_=a.useCallback(async()=>{try{const n=await we(t);p(n.content),L(n.exists)}catch{p(null),L(!1)}},[t]),de=a.useCallback(async n=>{await We(n,t),await _()},[t,_]),ve=a.useCallback(async()=>{Q(!0);try{const n=await Oe(t);return await Promise.all([_(),Z()]),{success:n.success,summary:n.summary}}finally{Q(!1)}},[t,_,Z]),Ne=a.useCallback(async()=>{re(!0);try{return await Te(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),y(l.content),f(!1),await q();return}u(l.content),M(!0)}finally{B(!1)}},[t,q]);return{workingMemory:m,workingMemoryLoading:C,workingMemoryDirty:E,setWorkingMemory:ce,saveWorkingMemory:oe,savingWorkingMemory:b,insightsContent:r,insightsLoading:T,insightsExists:X,refreshInsights:_,saveInsights:de,memorySettings:S,settingsLoading:F,savingMemorySettings:ue,saveMemorySettings:xe,memoryFiles:o,memoryFilesLoading:se,selectedFilePath:c,selectedFileContent:W,selectedFileLoading:d,selectedFileDirty:U,setSelectedFileContent:be,selectFile:pe,saveSelectedFile:fe,savingSelectedFile:ae,reloadMemoryFiles:q,backendStatus:me,backendLoading:K,extractInsights:ve,extracting:ne,triggerDreamNow:Ne,dreamRunning:Y,auditReport:D,auditLoading:ye,refreshAudit:Z,compactMemory:Ce,compacting:ge,installQmdAction:je,installingQmd:ie,testRetrieval:Se,stats:le}}const Ve={Patterns:"pattern",Principles:"principle",Conventions:"convention",Pitfalls:"pitfall",Context:"context"},Ke={"long-term":"Long-term",daily:"Daily",dreams:"Dreams"},Ze={"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."},Je=72;function Xe(i,t){if(i.length<=t)return i;const m=Math.max(1,t-1),u=Math.ceil(m/2),C=Math.floor(m/2);return`${i.slice(0,u)}…${i.slice(i.length-C)}`}function es(i){const t=`${i.label} — ${i.path}`;return Xe(t,Je)}function ss(i){if(!i)return[];const t=[],m=i.split(/(?=^## )/m);for(const u of m){const C=u.trim();if(!C)continue;const A=C.match(/^##\s+(.+?)(\n|$)/);if(A){const E=A[1].trim(),M=Ve[E]??E.toLowerCase(),b=C.slice(A[0].length).trim(),x=b.split(`
2
+ `).map(r=>r.replace(/^-\s+/,"").trim()).filter(r=>r.length>0&&(r.startsWith("- ")||r.startsWith("* ")));(x.length>0||b.length>0)&&t.push({name:E,key:M,items:x.length>0?x:b.length>0?[b]:[],expanded:!0})}}return t}function ts(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 as(i){return i.reduce((t,m)=>t+m.items.length,0)}function ns(i){switch(i){case"file":return"File (.fusion/memory/, agent/<agent-name>/memory/)";case"readonly":return"Read-Only";case"qmd":return"QMD (Quantized Memory Distillation)";default:return i}}function rs(i){switch(i){case"healthy":return"Healthy";case"warning":return"Warning";case"issues":return"Issues Found"}}function os({projectId:i,addToast:t}){const[m,u]=a.useState("working"),[C,A]=a.useState(new Set),[E,M]=a.useState(!1),[b,x]=a.useState(null),[r,p]=a.useState({memoryEnabled:!0,memoryAutoSummarizeEnabled:!1,memoryAutoSummarizeThresholdChars:5e4,memoryAutoSummarizeSchedule:"0 3 * * *",memoryDreamsEnabled:!1,memoryDreamsSchedule:"0 4 * * *"}),[T,J]=a.useState(""),[X,L]=a.useState(!1),[S,P]=a.useState(null),{insightsContent:F,insightsLoading:ee,insightsExists:ue,saveInsights:$,memorySettings:o,settingsLoading:v,saveMemorySettings:se,savingMemorySettings:I,backendStatus:c,backendLoading:k,extractInsights:W,extracting:y,auditReport:d,auditLoading:te,refreshAudit:U,compactMemory:f,compacting:ae,installQmdAction:H,installingQmd:ne,testRetrieval:Q,memoryFiles:Y,memoryFilesLoading:re,selectedFilePath:D,selectedFileContent:z,selectedFileLoading:ye,selectedFileDirty:R,setSelectedFileContent:ge,selectFile:B,saveSelectedFile:ie,savingSelectedFile:G,reloadMemoryFiles:le,triggerDreamNow:V,dreamRunning:me}=Ge({projectId:i});a.useEffect(()=>{p(o)},[o]);const K=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]),j=a.useMemo(()=>Y.find(s=>s.path===D),[Y,D]),be=j?Ze[j.layer]:"Edits the selected memory file.",N=a.useMemo(()=>ss(F),[F]),q=a.useMemo(()=>as(N),[N]),ce=a.useMemo(()=>ts(F),[F]),oe=a.useCallback(s=>{A(h=>{const g=new Set(h);return g.has(s)?g.delete(s):g.add(s),g})},[]),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(!K)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")}},[K,r,o,se,t]),je=a.useCallback(async()=>{try{const s=await H();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")}},[H,t]),Se=a.useCallback(async()=>{L(!0),P(null);try{const s=await Q(T);P(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{L(!1)}},[T,Q,t]),Z=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]),_=a.useCallback(async()=>{try{await f(D),t("Memory file compacted","success")}catch{t("Failed to compact memory","error")}},[f,D,t]),de=a.useCallback(async()=>{try{const s=await W();t(s.summary,"success")}catch(s){t(s instanceof Error?s.message:"Failed to extract insights","error")}},[W,t]),ve=a.useCallback(async()=>{if(b!==null)try{await $(b),M(!1),x(null),t("Insights saved","success")}catch{t("Failed to save insights","error")}},[b,$,t]),Ne=a.useCallback(()=>{x(F??""),M(!0)},[F]),Ce=a.useCallback(()=>{M(!1),x(null)},[]),n=!k&&c!==null,l=c?.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":m==="working",className:`memory-view-tab${m==="working"?" memory-view-tab--active":""}`,onClick:()=>u("working"),"data-testid":"memory-tab-working",children:"Working Memory"}),e.jsx("button",{type:"button",role:"tab","aria-selected":m==="insights",className:`memory-view-tab${m==="insights"?" memory-view-tab--active":""}`,onClick:()=>u("insights"),"data-testid":"memory-tab-insights",children:"Insights"}),e.jsx("button",{type:"button",role:"tab","aria-selected":m==="engines",className:`memory-view-tab${m==="engines"?" memory-view-tab--active":""}`,onClick:()=>u("engines"),"data-testid":"memory-tab-engines",children:"Engines"})]}),e.jsxs("div",{className:"memory-view-content",children:[m==="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:D,onChange:s=>{xe(s.target.value)},disabled:R,children:Y.map(s=>e.jsx("option",{value:s.path,title:`${s.label} — ${s.path}`,children:es(s)},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."})]}),j&&e.jsxs("div",{className:"memory-file-summary",children:[e.jsx("span",{children:Ke[j.layer]}),e.jsx("strong",{children:j.path}),e.jsxs("small",{children:[j.size.toLocaleString()," bytes · updated ",new Date(j.updatedAt).toLocaleString()]})]}),e.jsxs("div",{className:"form-group memory-editor-form-group",children:[e.jsx("label",{children:j?.label||"Memory Editor"}),e.jsx("small",{children:be}),e.jsx("div",{className:"memory-editor-container",children:e.jsx(Fe,{content:z,onChange:ge,readOnly:!l,filePath:D})})]})]}),e.jsxs("div",{className:"memory-action-bar",children:[e.jsxs("span",{className:"memory-char-count",children:[z.length," characters"]}),e.jsx("div",{className:"memory-flex-spacer"}),l&&z.length>0&&e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:_,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=>{p(h=>({...h,memoryDreamsEnabled:s.target.checked}))},disabled:!r.memoryEnabled||v}),"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=>{p(h=>({...h,memoryDreamsSchedule:s.target.value}))},placeholder:"0 4 * * *",disabled:v}),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:Z,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=>{p(h=>({...h,memoryAutoSummarizeEnabled:s.target.checked}))},disabled:!r.memoryEnabled||v}),"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=>{p(h=>({...h,memoryAutoSummarizeThresholdChars:parseInt(s.target.value,10)||5e4}))},min:1e3,disabled:v}),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=>{p(h=>({...h,memoryAutoSummarizeSchedule:s.target.value}))},placeholder:"0 3 * * *",disabled:v}),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."}),K&&e.jsx("div",{className:"memory-action-bar",children:e.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:fe,disabled:I||v,children:I?e.jsxs(e.Fragment,{children:[e.jsx(w,{size:14,className:"animate-spin"}),"Saving…"]}):"Save Settings"})})]})]})]}),m==="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…"})]}):E?e.jsxs("div",{className:"memory-insights-editor-layout",children:[e.jsx("div",{className:"memory-editor-container",children:e.jsx(Fe,{content:b??"",onChange:x,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:ve,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:y,children:y?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:y,children:y?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=!C.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:g=>{(g.key==="Enter"||g.key===" ")&&(g.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((g,ze)=>e.jsx("div",{className:"memory-insight-item",children:g.replace(/^-\s+/,"").replace(/^\*\s+/,"")},ze))})]},s.key)})})]})}),m==="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"}),c?.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."})]}):c?.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:c.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:[c?.capabilities?.readable&&e.jsx("span",{className:"memory-capability-badge",children:"Readable"}),c?.capabilities?.writable&&e.jsx("span",{className:"memory-capability-badge",children:"Writable"}),c?.capabilities?.supportsAtomicWrite&&e.jsx("span",{className:"memory-capability-badge",children:"Atomic Writes"}),c?.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:T,onChange:s=>J(s.target.value),placeholder:"Search memory with qmd"}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Se,disabled:X,children:X?"Testing…":"Test Retrieval"})]}),e.jsx("small",{className:"settings-muted",children:"Runs the same qmd-backed memory_search path agents use."}),S&&e.jsxs("div",{className:"memory-test-result",children:[e.jsxs("strong",{children:[S.results.length," result",S.results.length===1?"":"s"," ",'for "',S.query,'"']}),e.jsxs("small",{children:["qmd ",S.qmdAvailable?"available":"missing"," · ",S.usedFallback?"local fallback used":"qmd path used"]}),S.results.length>0?e.jsx("ul",{children:S.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:ns(c?.currentBackend??"unknown")})}),e.jsxs("div",{className:"memory-capability-row",children:[c?.capabilities?.readable&&e.jsx("span",{className:"memory-capability-badge",children:"Readable"}),c?.capabilities?.writable&&e.jsx("span",{className:"memory-capability-badge",children:"Writable"}),c?.capabilities?.supportsAtomicWrite&&e.jsx("span",{className:"memory-capability-badge",children:"Atomic Writes"}),c?.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:rs(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:()=>U(),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{os as MemoryView};