flock-core 0.5.4__py3-none-any.whl → 0.5.6__py3-none-any.whl

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.

Potentially problematic release.


This version of flock-core might be problematic. Click here for more details.

@@ -102,7 +102,7 @@ and limitations under the License.
102
102
  ***************************************************************************** */var ib=function(e,n){return ib=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(a,i){a.__proto__=i}||function(a,i){for(var o in i)i.hasOwnProperty(o)&&(a[o]=i[o])},ib(e,n)};function W7(e,n){ib(e,n);function a(){this.constructor=e}e.prototype=n===null?Object.create(n):(a.prototype=n.prototype,new a)}var Mt=function(){return Mt=Object.assign||function(n){for(var a,i=1,o=arguments.length;i<o;i++){a=arguments[i];for(var l in a)Object.prototype.hasOwnProperty.call(a,l)&&(n[l]=a[l])}return n},Mt.apply(this,arguments)};function X7(e,n){var a={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&n.indexOf(i)<0&&(a[i]=e[i]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,i=Object.getOwnPropertySymbols(e);o<i.length;o++)n.indexOf(i[o])<0&&Object.prototype.propertyIsEnumerable.call(e,i[o])&&(a[i[o]]=e[i[o]]);return a}var K7={width:"auto",height:"auto",display:"inline-block",position:"absolute",top:0,left:0},Z7=function(e){return{bottom:e,bottomLeft:e,bottomRight:e,left:e,right:e,top:e,topLeft:e,topRight:e}},ez=(function(e){W7(n,e);function n(a){var i=e.call(this,a)||this;return i.resizingPosition={x:0,y:0},i.offsetFromParent={left:0,top:0},i.resizableElement={current:null},i.originalPosition={x:0,y:0},i.state={resizing:!1,bounds:{top:0,right:0,bottom:0,left:0},maxWidth:a.maxWidth,maxHeight:a.maxHeight},i.onResizeStart=i.onResizeStart.bind(i),i.onResize=i.onResize.bind(i),i.onResizeStop=i.onResizeStop.bind(i),i.onDragStart=i.onDragStart.bind(i),i.onDrag=i.onDrag.bind(i),i.onDragStop=i.onDragStop.bind(i),i.getMaxSizesFromProps=i.getMaxSizesFromProps.bind(i),i}return n.prototype.componentDidMount=function(){this.updateOffsetFromParent();var a=this.offsetFromParent,i=a.left,o=a.top,l=this.getDraggablePosition(),c=l.x,d=l.y;this.draggable.setState({x:c-i,y:d-o}),this.forceUpdate()},n.prototype.getDraggablePosition=function(){var a=this.draggable.state,i=a.x,o=a.y;return{x:i,y:o}},n.prototype.getParent=function(){return this.resizable&&this.resizable.parentNode},n.prototype.getParentSize=function(){return this.resizable.getParentSize()},n.prototype.getMaxSizesFromProps=function(){var a=typeof this.props.maxWidth>"u"?Number.MAX_SAFE_INTEGER:this.props.maxWidth,i=typeof this.props.maxHeight>"u"?Number.MAX_SAFE_INTEGER:this.props.maxHeight;return{maxWidth:a,maxHeight:i}},n.prototype.getSelfElement=function(){return this.resizable&&this.resizable.resizable},n.prototype.getOffsetHeight=function(a){var i=this.props.scale;switch(this.props.bounds){case"window":return window.innerHeight/i;case"body":return document.body.offsetHeight/i;default:return a.offsetHeight}},n.prototype.getOffsetWidth=function(a){var i=this.props.scale;switch(this.props.bounds){case"window":return window.innerWidth/i;case"body":return document.body.offsetWidth/i;default:return a.offsetWidth}},n.prototype.onDragStart=function(a,i){this.props.onDragStart&&this.props.onDragStart(a,i);var o=this.getDraggablePosition();if(this.originalPosition=o,!!this.props.bounds){var l=this.getParent(),c=this.props.scale,d;if(this.props.bounds==="parent")d=l;else if(this.props.bounds==="body"){var f=l.getBoundingClientRect(),h=f.left,p=f.top,v=document.body.getBoundingClientRect(),m=-(h-l.offsetLeft*c-v.left)/c,b=-(p-l.offsetTop*c-v.top)/c,_=(document.body.offsetWidth-this.resizable.size.width*c)/c+m,S=(document.body.offsetHeight-this.resizable.size.height*c)/c+b;return this.setState({bounds:{top:b,right:_,bottom:S,left:m}})}else if(this.props.bounds==="window"){if(!this.resizable)return;var w=l.getBoundingClientRect(),C=w.left,T=w.top,E=-(C-l.offsetLeft*c)/c,N=-(T-l.offsetTop*c)/c,_=(window.innerWidth-this.resizable.size.width*c)/c+E,S=(window.innerHeight-this.resizable.size.height*c)/c+N;return this.setState({bounds:{top:N,right:_,bottom:S,left:E}})}else typeof this.props.bounds=="string"?d=document.querySelector(this.props.bounds):this.props.bounds instanceof HTMLElement&&(d=this.props.bounds);if(!(!(d instanceof HTMLElement)||!(l instanceof HTMLElement))){var R=d.getBoundingClientRect(),z=R.left,j=R.top,A=l.getBoundingClientRect(),D=A.left,I=A.top,P=(z-D)/c,V=j-I;if(this.resizable){this.updateOffsetFromParent();var $=this.offsetFromParent;this.setState({bounds:{top:V-$.top,right:P+(d.offsetWidth-this.resizable.size.width)-$.left/c,bottom:V+(d.offsetHeight-this.resizable.size.height)-$.top,left:P-$.left/c}})}}}},n.prototype.onDrag=function(a,i){if(this.props.onDrag){var o=this.offsetFromParent,l=o.left,c=o.top;if(!this.props.dragAxis||this.props.dragAxis==="both")return this.props.onDrag(a,Mt(Mt({},i),{x:i.x+l,y:i.y+c}));if(this.props.dragAxis==="x")return this.props.onDrag(a,Mt(Mt({},i),{x:i.x+l,y:this.originalPosition.y+c,deltaY:0}));if(this.props.dragAxis==="y")return this.props.onDrag(a,Mt(Mt({},i),{x:this.originalPosition.x+l,y:i.y+c,deltaX:0}))}},n.prototype.onDragStop=function(a,i){if(this.props.onDragStop){var o=this.offsetFromParent,l=o.left,c=o.top;if(!this.props.dragAxis||this.props.dragAxis==="both")return this.props.onDragStop(a,Mt(Mt({},i),{x:i.x+l,y:i.y+c}));if(this.props.dragAxis==="x")return this.props.onDragStop(a,Mt(Mt({},i),{x:i.x+l,y:this.originalPosition.y+c,deltaY:0}));if(this.props.dragAxis==="y")return this.props.onDragStop(a,Mt(Mt({},i),{x:this.originalPosition.x+l,y:i.y+c,deltaX:0}))}},n.prototype.onResizeStart=function(a,i,o){a.stopPropagation(),this.setState({resizing:!0});var l=this.props.scale,c=this.offsetFromParent,d=this.getDraggablePosition();if(this.resizingPosition={x:d.x+c.left,y:d.y+c.top},this.originalPosition=d,this.props.bounds){var f=this.getParent(),h=void 0;this.props.bounds==="parent"?h=f:this.props.bounds==="body"?h=document.body:this.props.bounds==="window"?h=window:typeof this.props.bounds=="string"?h=document.querySelector(this.props.bounds):this.props.bounds instanceof HTMLElement&&(h=this.props.bounds);var p=this.getSelfElement();if(p instanceof Element&&(h instanceof HTMLElement||h===window)&&f instanceof HTMLElement){var v=this.getMaxSizesFromProps(),m=v.maxWidth,b=v.maxHeight,_=this.getParentSize();if(m&&typeof m=="string")if(m.endsWith("%")){var S=Number(m.replace("%",""))/100;m=_.width*S}else m.endsWith("px")&&(m=Number(m.replace("px","")));if(b&&typeof b=="string")if(b.endsWith("%")){var S=Number(b.replace("%",""))/100;b=_.height*S}else b.endsWith("px")&&(b=Number(b.replace("px","")));var w=p.getBoundingClientRect(),C=w.left,T=w.top,E=this.props.bounds==="window"?{left:0,top:0}:h.getBoundingClientRect(),N=E.left,R=E.top,z=this.getOffsetWidth(h),j=this.getOffsetHeight(h),A=i.toLowerCase().endsWith("left"),D=i.toLowerCase().endsWith("right"),I=i.startsWith("top"),P=i.startsWith("bottom");if((A||I)&&this.resizable){var V=(C-N)/l+this.resizable.size.width;this.setState({maxWidth:V>Number(m)?m:V})}if(D||this.props.lockAspectRatio&&!A&&!I){var V=z+(N-C)/l;this.setState({maxWidth:V>Number(m)?m:V})}if((I||A)&&this.resizable){var V=(T-R)/l+this.resizable.size.height;this.setState({maxHeight:V>Number(b)?b:V})}if(P||this.props.lockAspectRatio&&!I&&!A){var V=j+(R-T)/l;this.setState({maxHeight:V>Number(b)?b:V})}}}else this.setState({maxWidth:this.props.maxWidth,maxHeight:this.props.maxHeight});this.props.onResizeStart&&this.props.onResizeStart(a,i,o)},n.prototype.onResize=function(a,i,o,l){var c=this,d={x:this.originalPosition.x,y:this.originalPosition.y},f=-l.width,h=-l.height,p=["top","left","topLeft","bottomLeft","topRight"];p.includes(i)&&(i==="bottomLeft"?d.x+=f:(i==="topRight"||(d.x+=f),d.y+=h));var v=this.draggable.state;(d.x!==v.x||d.y!==v.y)&&_b.flushSync(function(){c.draggable.setState(d)}),this.updateOffsetFromParent();var m=this.offsetFromParent,b=this.getDraggablePosition().x+m.left,_=this.getDraggablePosition().y+m.top;this.resizingPosition={x:b,y:_},this.props.onResize&&this.props.onResize(a,i,o,l,{x:b,y:_})},n.prototype.onResizeStop=function(a,i,o,l){this.setState({resizing:!1});var c=this.getMaxSizesFromProps(),d=c.maxWidth,f=c.maxHeight;this.setState({maxWidth:d,maxHeight:f}),this.props.onResizeStop&&this.props.onResizeStop(a,i,o,l,this.resizingPosition)},n.prototype.updateSize=function(a){this.resizable&&this.resizable.updateSize({width:a.width,height:a.height})},n.prototype.updatePosition=function(a){this.draggable.setState(a)},n.prototype.updateOffsetFromParent=function(){var a=this.props.scale,i=this.getParent(),o=this.getSelfElement();if(!i||o===null)return{top:0,left:0};var l=i.getBoundingClientRect(),c=l.left,d=l.top,f=o.getBoundingClientRect(),h=this.getDraggablePosition(),p=i.scrollLeft,v=i.scrollTop;this.offsetFromParent={left:f.left-c+p-h.x*a,top:f.top-d+v-h.y*a}},n.prototype.render=function(){var a=this,i=this.props,o=i.disableDragging,l=i.style,c=i.dragHandleClassName,d=i.position,f=i.onMouseDown,h=i.onMouseUp,p=i.dragAxis,v=i.dragGrid,m=i.bounds,b=i.enableUserSelectHack,_=i.cancel,S=i.children;i.onResizeStart,i.onResize,i.onResizeStop,i.onDragStart,i.onDrag,i.onDragStop;var w=i.resizeHandleStyles,C=i.resizeHandleClasses,T=i.resizeHandleComponent,E=i.enableResizing,N=i.resizeGrid,R=i.resizeHandleWrapperClass,z=i.resizeHandleWrapperStyle,j=i.scale,A=i.allowAnyClick,D=i.dragPositionOffset,I=X7(i,["disableDragging","style","dragHandleClassName","position","onMouseDown","onMouseUp","dragAxis","dragGrid","bounds","enableUserSelectHack","cancel","children","onResizeStart","onResize","onResizeStop","onDragStart","onDrag","onDragStop","resizeHandleStyles","resizeHandleClasses","resizeHandleComponent","enableResizing","resizeGrid","resizeHandleWrapperClass","resizeHandleWrapperStyle","scale","allowAnyClick","dragPositionOffset"]),P=this.props.default?Mt({},this.props.default):void 0;delete I.default;var V=o||c?{cursor:"auto"}:{cursor:"move"},$=Mt(Mt(Mt({},K7),V),l),L=this.offsetFromParent,H=L.left,O=L.top,F;d&&(F={x:d.x-H,y:d.y-O});var J=this.state.resizing?void 0:F,G=this.state.resizing?"both":p;return q.createElement(L7,{ref:function(re){re&&(a.draggable=re)},handle:c?".".concat(c):void 0,defaultPosition:P,onMouseDown:f,onMouseUp:h,onStart:this.onDragStart,onDrag:this.onDrag,onStop:this.onDragStop,axis:G,disabled:o,grid:v,bounds:m?this.state.bounds:void 0,position:J,enableUserSelectHack:b,cancel:_,scale:j,allowAnyClick:A,nodeRef:this.resizableElement,positionOffset:D},q.createElement(Y7,Mt({},I,{ref:function(re){re&&(a.resizable=re,a.resizableElement.current=re.resizable)},defaultSize:P,size:this.props.size,enable:typeof E=="boolean"?Z7(E):E,onResizeStart:this.onResizeStart,onResize:this.onResize,onResizeStop:this.onResizeStop,style:$,minWidth:this.props.minWidth,minHeight:this.props.minHeight,maxWidth:this.state.resizing?this.state.maxWidth:this.props.maxWidth,maxHeight:this.state.resizing?this.state.maxHeight:this.props.maxHeight,grid:N,handleWrapperClass:R,handleWrapperStyle:z,lockAspectRatio:this.props.lockAspectRatio,lockAspectRatioExtraWidth:this.props.lockAspectRatioExtraWidth,lockAspectRatioExtraHeight:this.props.lockAspectRatioExtraHeight,handleStyles:w,handleClasses:C,handleComponent:T,scale:this.props.scale}),S))},n.defaultProps={maxWidth:Number.MAX_SAFE_INTEGER,maxHeight:Number.MAX_SAFE_INTEGER,scale:1,onResizeStart:function(){},onResize:function(){},onResizeStop:function(){},onDragStart:function(){},onDrag:function(){},onDragStop:function(){}},n})(q.PureComponent);const IN=Ya()(co((e,n)=>({outputs:new Map,addOutput:(a,i)=>e(o=>{const l=new Map(o.outputs),d=[...l.get(a)||[],i];return l.set(a,d),{outputs:l}}),clearOutputs:a=>e(i=>{const o=new Map(i.outputs);return o.delete(a),{outputs:o}}),getOutputs:a=>n().outputs.get(a)||[]}),{name:"streamStore"})),at=Ya()(co(e=>({status:"disconnected",lastError:null,reconnectAttempts:0,setStatus:n=>e({status:n}),setError:n=>e({lastError:n}),incrementAttempts:()=>e(n=>({reconnectAttempts:n.reconnectAttempts+1})),resetAttempts:()=>e({reconnectAttempts:0})}),{name:"wsStore"}));class Q7{ws=null;reconnectTimeout=null;reconnectAttempt=0;maxReconnectDelay=3e4;connectionTimeout=null;connectionTimeoutMs=1e4;messageBuffer=[];maxBufferSize=100;eventHandlers=new Map;url;shouldReconnect=!0;heartbeatInterval=null;heartbeatTimeout=null;connectionStatus="disconnected";store;enableHeartbeat;constructor(n,a){this.url=n,this.store=a||{addAgent:i=>Me.getState().addAgent(i),updateAgent:(i,o)=>Me.getState().updateAgent(i,o),addMessage:i=>Me.getState().addMessage(i),updateMessage:(i,o)=>Me.getState().updateMessage(i,o),batchUpdate:i=>Me.getState().batchUpdate(i)},this.enableHeartbeat=!1,this.setupEventHandlers()}updateFilterStateFromPublishedMessage(n){const a=Te.getState(),i=typeof n.artifact_type=="string"?n.artifact_type:"",o=typeof n.produced_by=="string"?n.produced_by:"",l=Array.isArray(n.tags)?n.tags.filter(_=>typeof _=="string"&&_.length>0):[],c=(typeof n.visibility=="object"&&n.visibility&&typeof n.visibility.kind=="string"?n.visibility.kind:void 0)||(typeof n.visibility_kind=="string"?n.visibility_kind:void 0)||(typeof n.visibility=="string"?n.visibility:void 0)||"",d=i?[...a.availableArtifactTypes,i]:[...a.availableArtifactTypes],f=o?[...a.availableProducers,o]:[...a.availableProducers],h=l.length>0?[...a.availableTags,...l]:[...a.availableTags],p=c?[...a.availableVisibility,c]:[...a.availableVisibility];a.updateAvailableFacets({artifactTypes:d,producers:f,tags:h,visibilities:p});const v=a.summary??{total:0,by_type:{},by_producer:{},by_visibility:{},tag_counts:{},earliest_created_at:null,latest_created_at:null},m=(typeof n.timestamp=="string"?n.timestamp:void 0)??new Date().toISOString(),b={total:v.total+1,by_type:{...v.by_type},by_producer:{...v.by_producer},by_visibility:{...v.by_visibility},tag_counts:{...v.tag_counts},earliest_created_at:v.earliest_created_at===null||m<v.earliest_created_at?m:v.earliest_created_at,latest_created_at:v.latest_created_at===null||m>v.latest_created_at?m:v.latest_created_at};if(i&&(b.by_type[i]=(b.by_type[i]||0)+1),o&&(b.by_producer[o]=(b.by_producer[o]||0)+1),c&&(b.by_visibility[c]=(b.by_visibility[c]||0)+1),l.forEach(_=>{b.tag_counts[_]=(b.tag_counts[_]||0)+1}),a.setSummary(b),typeof n.correlation_id=="string"&&n.correlation_id.length>0){const _=typeof n.timestamp=="string"?new Date(n.timestamp).getTime():Date.now(),S=a.availableCorrelationIds.find(T=>T.correlation_id===n.correlation_id),w=S?{...S,artifact_count:S.artifact_count+1,first_seen:Math.min(S.first_seen,_)}:{correlation_id:n.correlation_id,first_seen:_,artifact_count:1,run_count:0},C=[...a.availableCorrelationIds.filter(T=>T.correlation_id!==n.correlation_id),w];a.updateAvailableCorrelationIds(C)}}setupEventHandlers(){this.on("agent_activated",n=>{const a=Me.getState().agents,i=Me.getState().messages,o=a.get(n.agent_id),l={...o?.receivedByType||{}};n.consumed_artifacts&&n.consumed_artifacts.length>0&&n.consumed_artifacts.forEach(f=>{const h=i.get(f);h&&(l[h.type]=(l[h.type]||0)+1)});const c={id:n.agent_id,name:n.agent_name,status:"running",subscriptions:n.consumed_types||[],lastActive:Date.now(),sentCount:o?.sentCount||0,recvCount:(o?.recvCount||0)+(n.consumed_artifacts?.length||0),outputTypes:n.produced_types||[],receivedByType:l,sentByType:o?.sentByType||{}};this.store.addAgent(c),n.consumed_artifacts&&n.consumed_artifacts.length>0&&Me.getState().recordConsumption(n.consumed_artifacts,n.agent_id);const d={run_id:n.run_id||`run_${Date.now()}`,agent_name:n.agent_name,correlation_id:n.correlation_id,status:"active",consumed_artifacts:n.consumed_artifacts||[],produced_artifacts:[],started_at:new Date().toISOString()};this.store.batchUpdate&&this.store.batchUpdate({runs:[d]})}),this.on("message_published",n=>{const a=Me.getState().messages,i=`streaming_${n.produced_by}_${n.correlation_id}`,o=a.get(i);if(o){const d=Array.isArray(n.tags)?n.tags:[],f=n.visibility?.kind||n.visibility_kind||"Unknown",h={...o,id:n.artifact_id,type:n.artifact_type,payload:n.payload,tags:d,visibilityKind:f,partitionKey:n.partition_key??null,version:n.version??1,isStreaming:!1,streamingText:""};Me.getState().finalizeStreamingMessage(i,h)}else{const d=Array.isArray(n.tags)?n.tags:[],f=n.visibility?.kind||n.visibility_kind||"Unknown",h={id:n.artifact_id,type:n.artifact_type,payload:n.payload,timestamp:n.timestamp?new Date(n.timestamp).getTime():Date.now(),correlationId:n.correlation_id||"",producedBy:n.produced_by,tags:d,visibilityKind:f,partitionKey:n.partition_key??null,version:n.version??1,isStreaming:!1};this.store.addMessage(h)}const l=Me.getState().agents.get(n.produced_by);if(l){const d={...l.sentByType||{}};d[n.artifact_type]=(d[n.artifact_type]||0)+1,this.store.updateAgent(n.produced_by,{sentCount:(l.sentCount||0)+1,lastActive:Date.now(),sentByType:d})}else this.store.addAgent({id:n.produced_by,name:n.produced_by,status:"idle",subscriptions:[],lastActive:Date.now(),sentCount:1,recvCount:0,outputTypes:[n.artifact_type],sentByType:{[n.artifact_type]:1},receivedByType:{}});if(n.consumers&&Array.isArray(n.consumers)){const d=Me.getState().agents;n.consumers.forEach(f=>{const h=d.get(f);h&&this.store.updateAgent(f,{recvCount:(h.recvCount||0)+1,lastActive:Date.now()})})}if(n.correlation_id&&this.store.batchUpdate){const d=Me.getState().runs,f=Array.from(d.values()).find(h=>h.agent_name===n.produced_by&&h.correlation_id===n.correlation_id&&h.status==="active");if(f&&!f.produced_artifacts.includes(n.artifact_id)){const h={...f,produced_artifacts:[...f.produced_artifacts,n.artifact_id]};this.store.batchUpdate({runs:[h]})}}this.updateFilterStateFromPublishedMessage(n);const c=ut.getState().mode;c==="blackboard"?Me.getState().generateBlackboardViewGraph():c==="agent"&&Me.getState().generateAgentViewGraph()}),this.on("streaming_output",n=>{if(console.log("[WebSocket] Streaming output:",n),n.agent_name&&n.output_type==="llm_token"){const l=[...Me.getState().agents.get(n.agent_name)?.streamingTokens||[],n.content].slice(-6);this.store.updateAgent(n.agent_name,{lastActive:Date.now(),streamingTokens:l})}if(n.output_type==="llm_token"&&n.agent_name&&n.correlation_id){const a=Me.getState().messages,i=`streaming_${n.agent_name}_${n.correlation_id}`,o=a.get(i);if(o)this.store.updateMessage(i,{streamingText:(o.streamingText||"")+n.content,timestamp:n.timestamp?new Date(n.timestamp).getTime():Date.now()});else if(n.sequence===0||!o){const d=Me.getState().agents.get(n.agent_name)?.outputTypes?.[0]||"output",f={id:i,type:d,payload:{},timestamp:n.timestamp?new Date(n.timestamp).getTime():Date.now(),correlationId:n.correlation_id||"",producedBy:n.agent_name,tags:[],visibilityKind:"Unknown",isStreaming:!0,streamingText:n.content};this.store.addMessage(f)}}}),this.on("agent_completed",n=>{if(this.store.updateAgent(n.agent_name,{status:"idle",lastActive:Date.now(),streamingTokens:[]}),n.run_id&&this.store.batchUpdate){const i=Me.getState().runs.get(n.run_id);if(i){const o={...i,status:"completed",completed_at:new Date().toISOString(),duration_ms:n.duration_ms};this.store.batchUpdate({runs:[o]})}}}),this.on("agent_error",n=>{if(this.store.updateAgent(n.agent_name,{status:"error",lastActive:Date.now()}),n.run_id&&this.store.batchUpdate){const i=Me.getState().runs.get(n.run_id);if(i){const o={...i,status:"error",completed_at:new Date().toISOString(),error_message:n.error_message||"Unknown error"};this.store.batchUpdate({runs:[o]})}}}),this.on("ping",()=>{this.send({type:"pong",timestamp:Date.now()})})}connect(){if(!(this.ws?.readyState===WebSocket.OPEN||this.ws?.readyState===WebSocket.CONNECTING))try{this.connectionStatus="connecting",typeof at<"u"&&at.getState().setStatus("connecting"),this.ws=new WebSocket(this.url),this.connectionTimeout=window.setTimeout(()=>{console.warn("[WebSocket] Connection timeout"),this.ws&&this.ws.readyState!==WebSocket.OPEN&&(this.ws.close(),this.connectionStatus="error",typeof at<"u"&&(at.getState().setStatus("disconnected"),at.getState().setError("Connection timeout")),this.shouldReconnect&&this.reconnect())},this.connectionTimeoutMs),this.ws.onopen=()=>{console.log("[WebSocket] Connected"),this.connectionTimeout!==null&&(clearTimeout(this.connectionTimeout),this.connectionTimeout=null),this.connectionStatus="connected",typeof at<"u"&&(at.getState().setStatus("connected"),at.getState().setError(null),at.getState().resetAttempts()),this.reconnectAttempt=0,this.flushBuffer(),this.enableHeartbeat&&this.startHeartbeat()},this.ws.onmessage=n=>{this.handleMessage(n)},this.ws.onerror=n=>{console.error("[WebSocket] Error:",n),this.connectionStatus="error",typeof at<"u"&&(at.getState().setError("Connection error"),at.getState().setStatus("disconnected"))},this.ws.onclose=n=>{console.log("[WebSocket] Closed:",n.code,n.reason),this.stopHeartbeat(),this.connectionStatus!=="error"&&(this.shouldReconnect&&n.code!==1e3?(this.connectionStatus="connecting",typeof at<"u"&&at.getState().setStatus("reconnecting"),this.reconnect()):(this.connectionStatus="disconnected",typeof at<"u"&&at.getState().setStatus("disconnected")))}}catch(n){console.error("[WebSocket] Connection failed:",n),this.connectionStatus="error",typeof at<"u"&&(at.getState().setStatus("disconnected"),at.getState().setError(n instanceof Error?n.message:"Connection failed")),this.shouldReconnect&&this.reconnect()}}reconnect(){if(this.reconnectTimeout!==null)return;const n=Math.min(1e3*Math.pow(2,this.reconnectAttempt),this.maxReconnectDelay);typeof at<"u"&&at.getState().incrementAttempts(),this.reconnectAttempt++,console.log(`[WebSocket] Reconnecting in ${n}ms (attempt ${this.reconnectAttempt})`),this.reconnectTimeout=window.setTimeout(()=>{this.reconnectTimeout=null,this.connect()},n)}handleMessage(n){try{const a=JSON.parse(n.data);if(a.type==="ping"){this.send({type:"pong",timestamp:Date.now()});return}if(a.type==="pong"){this.resetHeartbeatTimeout();return}const i=a;if(i.event_type==="pong"){this.resetHeartbeatTimeout();return}const o=i.event_type?i.data:a;let l=i.event_type;if(l||(a.agent_id&&a.consumed_types?l="agent_activated":a.artifact_id&&a.artifact_type?l="message_published":a.run_id&&a.output_type?l="streaming_output":a.run_id&&a.duration_ms!==void 0?l="agent_completed":a.run_id&&a.error_type&&(l="agent_error")),l){const c=this.eventHandlers.get(l);c&&c.forEach(d=>{try{d(o)}catch(f){console.error(`[WebSocket] Handler error for ${l}:`,f)}})}}catch(a){console.error("[WebSocket] Failed to parse message:",a)}}send(n){if(this.ws?.readyState===WebSocket.OPEN)try{this.ws.send(JSON.stringify(n))}catch(a){console.error("[WebSocket] Send failed:",a),this.bufferMessage(n)}else this.bufferMessage(n)}bufferMessage(n){this.messageBuffer.length>=this.maxBufferSize&&this.messageBuffer.shift(),this.messageBuffer.push(n)}flushBuffer(){if(this.messageBuffer.length===0)return;console.log(`[WebSocket] Flushing ${this.messageBuffer.length} buffered messages`);const n=[...this.messageBuffer];this.messageBuffer=[],n.forEach(a=>{if(this.ws?.readyState===WebSocket.OPEN)try{this.ws.send(JSON.stringify(a))}catch(i){console.error("[WebSocket] Failed to send buffered message:",i)}})}on(n,a){this.eventHandlers.has(n)||this.eventHandlers.set(n,[]),this.eventHandlers.get(n).push(a)}off(n,a){const i=this.eventHandlers.get(n);if(i){const o=i.indexOf(a);o>-1&&i.splice(o,1)}}startHeartbeat(){this.stopHeartbeat(),this.heartbeatInterval=window.setInterval(()=>{this.ws?.readyState===WebSocket.OPEN&&(this.send({type:"ping"}),this.heartbeatTimeout=window.setTimeout(()=>{console.warn("[WebSocket] Heartbeat timeout, closing connection"),this.ws?.close()},1e4))},12e4)}stopHeartbeat(){this.heartbeatInterval!==null&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null),this.heartbeatTimeout!==null&&(clearTimeout(this.heartbeatTimeout),this.heartbeatTimeout=null)}resetHeartbeatTimeout(){this.heartbeatTimeout!==null&&(clearTimeout(this.heartbeatTimeout),this.heartbeatTimeout=null)}disconnect(){this.shouldReconnect=!1,this.connectionStatus="disconnecting",this.reconnectTimeout!==null&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null),this.connectionTimeout!==null&&(clearTimeout(this.connectionTimeout),this.connectionTimeout=null),this.stopHeartbeat(),this.ws&&(this.ws.close(),this.ws=null)}reconnectManually(){this.shouldReconnect=!0,this.reconnectAttempt=0,typeof at<"u"&&at.getState().resetAttempts(),this.connect()}isConnected(){return this.ws?.readyState===WebSocket.OPEN&&this.connectionStatus!=="error"}getConnectionStatus(){return this.connectionStatus}getBufferedMessageCount(){return this.messageBuffer.length}getStatus(){if(!this.ws)return"disconnected";switch(this.ws.readyState){case WebSocket.CONNECTING:return"connecting";case WebSocket.OPEN:return"connected";case WebSocket.CLOSING:return"disconnecting";case WebSocket.CLOSED:return"disconnected";default:return"disconnected"}}}let Zi=null;const J7=e=>{if(!Zi)throw new Error("WebSocket client not initialized");return Zi},eU=e=>(Zi&&Zi.disconnect(),Zi=new Q7(e),Zi),tU=[],nU=({nodeId:e,nodeType:n})=>{const[a,i]=q.useState(!0),[o,l]=q.useState(!1),c=IN(v=>v.outputs.get(e)??tU),d=IN(v=>v.addOutput);q.useEffect(()=>{if(n!=="agent")return;(async()=>{l(!0);try{const m=await fetch(`/api/streaming-history/${e}`);if(m.ok){const b=await m.json();b.events&&Array.isArray(b.events)&&b.events.forEach(_=>{d(e,_)})}}catch(m){console.error(`Failed to fetch streaming history for ${e}:`,m)}finally{l(!1)}})()},[e,n,d]),q.useEffect(()=>{if(n!=="agent")return;const v=J7(),m=b=>{b.agent_name===e&&d(e,b)};return v.on("streaming_output",m),()=>{v.off("streaming_output",m)}},[e,n,d]);const f=q.useMemo(()=>{let v="";for(const m of c)m.output_type==="llm_token"?v+=m.content:(v&&!v.endsWith(`
103
103
  `)&&(v+=`
104
104
  `),v+=m.content,v+=`
105
- `);return v},[c]),h=q.useRef(null);q.useEffect(()=>{a&&h.current&&h.current.scrollIntoView({behavior:"smooth"})},[f,a]);const p=c.some(v=>v.is_final);return g.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",background:"var(--color-bg-elevated)"},children:[g.jsxs("div",{style:{padding:"var(--space-component-sm) var(--space-component-md)",background:"var(--color-bg-surface)",borderBottom:"var(--border-width-1) solid var(--color-border-subtle)",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[g.jsxs("span",{style:{color:"var(--color-text-tertiary)",fontSize:"var(--font-size-caption)",fontWeight:"var(--font-weight-medium)",fontFamily:"var(--font-family-sans)"},children:[c.length," ",c.length===1?"event":"events"]}),g.jsxs("label",{style:{color:"var(--color-text-tertiary)",fontSize:"var(--font-size-caption)",fontFamily:"var(--font-family-sans)",display:"flex",alignItems:"center",gap:"var(--gap-sm)",cursor:"pointer",userSelect:"none"},children:[g.jsx("input",{type:"checkbox",checked:a,onChange:v=>i(v.target.checked),style:{cursor:"pointer",accentColor:"var(--color-primary-500)"}}),"Auto-scroll"]})]}),g.jsx("div",{"data-testid":`live-output-${e}`,style:{flex:1,overflow:"auto",position:"relative",padding:"var(--spacing-2)"},children:o?g.jsx("div",{style:{padding:"var(--space-layout-md)",color:"var(--color-text-muted)",fontSize:"var(--font-size-body-sm)",fontFamily:"var(--font-family-sans)",textAlign:"center"},children:"Loading history..."}):c.length===0?g.jsx("div",{"data-testid":"empty-output",style:{padding:"var(--space-layout-md)",color:"var(--color-text-muted)",fontSize:"var(--font-size-body-sm)",fontFamily:"var(--font-family-sans)",textAlign:"center"},children:"Idle - no output"}):g.jsxs(g.Fragment,{children:[g.jsx("pre",{style:{margin:0,color:"var(--color-tertiary-400)",fontFamily:"var(--font-family-mono)",fontSize:"var(--font-size-caption)",whiteSpace:"pre-wrap",wordBreak:"break-word",lineHeight:"var(--line-height-relaxed)"},children:f}),p&&g.jsx("div",{"data-testid":"final-marker",style:{color:"var(--color-text-muted)",fontSize:"var(--font-size-caption)",fontFamily:"var(--font-family-mono)",padding:"var(--spacing-2) 0",borderTop:"var(--border-width-1) solid var(--color-border-subtle)",marginTop:"var(--spacing-2)"},children:"--- End of output ---"}),g.jsx("div",{ref:h})]})})]})},rU=({nodeId:e,nodeType:n})=>{const a=Me(p=>p.messages),i=Me(p=>p.agents),[o,l]=q.useState(new Set),c=q.useMemo(()=>{const p=[];if(n==="agent"){const v=i.get(e);if(!v)return p;a.forEach(m=>{const b=v.subscriptions.includes(m.type),_=m.producedBy===e;b&&p.push({id:m.id,type:m.type,direction:"consumed",payload:m.payload,timestamp:m.timestamp,correlationId:m.correlationId}),_&&p.push({id:`${m.id}-published`,type:m.type,direction:"published",payload:m.payload,timestamp:m.timestamp,correlationId:m.correlationId})})}else if(n==="message"){const v=a.get(e);v&&p.push({id:v.id,type:v.type,direction:"published",payload:v.payload,timestamp:v.timestamp,correlationId:v.correlationId})}return p.sort((v,m)=>m.timestamp-v.timestamp)},[e,n,a,i]),d=p=>new Date(p).toLocaleString(),f=p=>{try{return JSON.stringify(p,null,2)}catch{return String(p)}},h=p=>{l(v=>{const m=new Set(v);return m.has(p)?m.delete(p):m.add(p),m})};return g.jsx("div",{"data-testid":`message-history-${e}`,style:{height:"100%",overflow:"auto",background:"var(--color-bg-elevated)",color:"var(--color-text-primary)"},children:c.length===0?g.jsx("div",{"data-testid":"empty-messages",style:{padding:"var(--space-layout-md)",color:"var(--color-text-muted)",fontSize:"var(--font-size-body-sm)",fontFamily:"var(--font-family-sans)",textAlign:"center"},children:"No messages yet"}):g.jsxs("table",{"data-testid":"message-table",style:{width:"100%",borderCollapse:"collapse",fontSize:"var(--font-size-caption)",fontFamily:"var(--font-family-sans)"},children:[g.jsx("thead",{children:g.jsxs("tr",{style:{background:"var(--color-bg-surface)",borderBottom:"var(--border-width-1) solid var(--color-border-subtle)",position:"sticky",top:0,zIndex:1},children:[g.jsx("th",{style:{padding:"var(--space-component-sm) var(--space-component-md)",textAlign:"left",fontWeight:"var(--font-weight-semibold)",color:"var(--color-text-secondary)"},children:"Time"}),g.jsx("th",{style:{padding:"var(--space-component-sm) var(--space-component-md)",textAlign:"left",fontWeight:"var(--font-weight-semibold)",color:"var(--color-text-secondary)"},children:"Direction"}),g.jsx("th",{style:{padding:"var(--space-component-sm) var(--space-component-md)",textAlign:"left",fontWeight:"var(--font-weight-semibold)",color:"var(--color-text-secondary)"},children:"Type"}),g.jsx("th",{style:{padding:"var(--space-component-sm) var(--space-component-md)",textAlign:"left",fontWeight:"var(--font-weight-semibold)",color:"var(--color-text-secondary)"},children:"Correlation ID"}),g.jsx("th",{style:{padding:"var(--space-component-sm) var(--space-component-md)",textAlign:"left",fontWeight:"var(--font-weight-semibold)",color:"var(--color-text-secondary)"},children:"Payload"})]})}),g.jsx("tbody",{children:c.map(p=>{const v=o.has(p.id);return g.jsx(Kn.Fragment,{children:g.jsxs("tr",{"data-testid":`message-row-${p.id}`,style:{borderBottom:"var(--border-width-1) solid var(--color-border-subtle)",cursor:"pointer",transition:"var(--transition-colors)"},onClick:()=>h(p.id),onMouseEnter:m=>{m.currentTarget.style.background="var(--color-bg-surface)"},onMouseLeave:m=>{m.currentTarget.style.background="transparent"},children:[g.jsx("td",{"data-testid":`msg-time-${p.id}`,style:{padding:"var(--space-component-sm) var(--space-component-md)",whiteSpace:"nowrap",color:"var(--color-text-tertiary)"},children:d(p.timestamp)}),g.jsx("td",{"data-testid":`msg-direction-${p.id}`,style:{padding:"var(--space-component-sm) var(--space-component-md)",color:p.direction==="consumed"?"var(--color-tertiary-400)":"var(--color-success-light)",fontWeight:"var(--font-weight-semibold)"},children:p.direction==="consumed"?"↓ Consumed":"↑ Published"}),g.jsx("td",{"data-testid":`msg-type-${p.id}`,style:{padding:"var(--space-component-sm) var(--space-component-md)",fontFamily:"var(--font-family-mono)",color:"var(--color-text-primary)"},children:p.type}),g.jsx("td",{"data-testid":`msg-correlation-${p.id}`,style:{padding:"var(--space-component-sm) var(--space-component-md)",fontFamily:"var(--font-family-mono)",fontSize:"var(--font-size-overline)",color:"var(--color-text-muted)"},children:p.correlationId}),g.jsx("td",{"data-testid":`msg-payload-${p.id}`,style:{padding:"var(--space-component-sm) var(--space-component-md)",maxWidth:"300px"},children:g.jsx("pre",{style:{fontSize:"var(--font-size-overline)",fontFamily:"var(--font-family-mono)",maxHeight:v?"none":"60px",overflow:v?"visible":"hidden",textOverflow:"ellipsis",margin:0,whiteSpace:v?"pre-wrap":"nowrap",color:"var(--color-text-secondary)",background:"var(--color-bg-base)",padding:"var(--spacing-1)",borderRadius:"var(--radius-sm)"},children:f(p.payload)})})]})},p.id)})})]})})},aU=({nodeId:e,nodeType:n})=>{const a=Me(f=>f.runs),i=q.useMemo(()=>{const f=[];return n!=="agent"?f:(a.forEach(h=>{if(h.agent_name===e){const p=h.started_at?new Date(h.started_at).getTime():Date.now(),v=h.completed_at?new Date(h.completed_at).getTime():Date.now();let m="idle";h.status==="active"?m="processing":h.status==="error"?m="error":m="idle",f.push({runId:h.run_id,startTime:p,endTime:v,duration:h.duration_ms||0,status:m,metrics:h.metrics||{},errorMessage:h.error_message||void 0})}}),f.sort((h,p)=>p.startTime-h.startTime))},[e,n,a]),o=f=>new Date(f).toLocaleString(),l=f=>f<1e3?`${f}ms`:f<6e4?`${(f/1e3).toFixed(2)}s`:`${(f/6e4).toFixed(2)}m`,c=f=>{switch(f){case"idle":return"var(--color-success-light)";case"processing":return"var(--color-tertiary-400)";case"error":return"var(--color-error-light)";default:return"var(--color-text-primary)"}},d=f=>{switch(f){case"idle":return"Completed";case"processing":return"Processing";case"error":return"Error";default:return f}};return g.jsx("div",{"data-testid":`run-status-${e}`,style:{height:"100%",overflow:"auto",background:"var(--color-bg-elevated)",color:"var(--color-text-primary)"},children:i.length===0?g.jsx("div",{"data-testid":"empty-runs",style:{padding:"var(--space-layout-md)",color:"var(--color-text-muted)",fontSize:"var(--font-size-body-sm)",fontFamily:"var(--font-family-sans)",textAlign:"center"},children:"No previous runs"}):g.jsxs("table",{"data-testid":"run-table",style:{width:"100%",borderCollapse:"collapse",fontSize:"var(--font-size-caption)",fontFamily:"var(--font-family-sans)"},children:[g.jsx("thead",{children:g.jsxs("tr",{style:{background:"var(--color-bg-surface)",borderBottom:"var(--border-width-1) solid var(--color-border-subtle)",position:"sticky",top:0,zIndex:1},children:[g.jsx("th",{style:{padding:"var(--space-component-sm) var(--space-component-md)",textAlign:"left",fontWeight:"var(--font-weight-semibold)",color:"var(--color-text-secondary)"},children:"Run ID"}),g.jsx("th",{style:{padding:"var(--space-component-sm) var(--space-component-md)",textAlign:"left",fontWeight:"var(--font-weight-semibold)",color:"var(--color-text-secondary)"},children:"Start Time"}),g.jsx("th",{style:{padding:"var(--space-component-sm) var(--space-component-md)",textAlign:"left",fontWeight:"var(--font-weight-semibold)",color:"var(--color-text-secondary)"},children:"Duration"}),g.jsx("th",{style:{padding:"var(--space-component-sm) var(--space-component-md)",textAlign:"left",fontWeight:"var(--font-weight-semibold)",color:"var(--color-text-secondary)"},children:"Status"}),g.jsx("th",{style:{padding:"var(--space-component-sm) var(--space-component-md)",textAlign:"left",fontWeight:"var(--font-weight-semibold)",color:"var(--color-text-secondary)"},children:"Metrics"})]})}),g.jsx("tbody",{children:i.map(f=>g.jsxs("tr",{"data-testid":`run-row-${f.runId}`,style:{borderBottom:"var(--border-width-1) solid var(--color-border-subtle)",transition:"var(--transition-colors)"},onMouseEnter:h=>{h.currentTarget.style.background="var(--color-bg-surface)"},onMouseLeave:h=>{h.currentTarget.style.background="transparent"},children:[g.jsx("td",{"data-testid":`run-id-${f.runId}`,style:{padding:"var(--space-component-sm) var(--space-component-md)",fontFamily:"var(--font-family-mono)",fontSize:"var(--font-size-overline)",maxWidth:"150px",overflow:"hidden",textOverflow:"ellipsis",color:"var(--color-text-muted)"},children:f.runId}),g.jsx("td",{"data-testid":`run-start-${f.runId}`,style:{padding:"var(--space-component-sm) var(--space-component-md)",whiteSpace:"nowrap",color:"var(--color-text-tertiary)"},children:o(f.startTime)}),g.jsx("td",{"data-testid":`run-duration-${f.runId}`,style:{padding:"var(--space-component-sm) var(--space-component-md)",fontFamily:"var(--font-family-mono)",color:"var(--color-text-secondary)"},children:l(f.duration)}),g.jsxs("td",{"data-testid":`run-status-${f.runId}`,style:{padding:"var(--space-component-sm) var(--space-component-md)",color:c(f.status),fontWeight:"var(--font-weight-semibold)"},children:[d(f.status),f.errorMessage&&g.jsx("div",{style:{fontSize:"var(--font-size-overline)",color:"var(--color-text-muted)",marginTop:"var(--spacing-1)",fontStyle:"italic"},children:f.errorMessage})]}),g.jsx("td",{"data-testid":`run-metrics-${f.runId}`,style:{padding:"var(--space-component-sm) var(--space-component-md)"},children:g.jsxs("div",{style:{fontSize:"var(--font-size-overline)",fontFamily:"var(--font-family-mono)",color:"var(--color-text-muted)"},children:[f.metrics.tokensUsed!==void 0&&g.jsxs("div",{children:["Tokens: ",f.metrics.tokensUsed]}),f.metrics.costUsd!==void 0&&g.jsxs("div",{children:["Cost: $",f.metrics.costUsd.toFixed(4)]}),f.metrics.artifactsProduced!==void 0&&g.jsxs("div",{children:["Artifacts: ",f.metrics.artifactsProduced]}),Object.keys(f.metrics).length===0&&g.jsx("div",{children:"-"})]})})]},f.runId))})]})})},iU=({nodeId:e,nodeType:n="agent"})=>{const a=ut(p=>p.detailWindows.get(e)),i=ut(p=>p.updateDetailWindow),o=ut(p=>p.closeDetailWindow),l=q.useCallback(()=>{o(e)},[e,o]),c=q.useCallback(p=>{i(e,{activeTab:p})},[e,i]);if(!a)return null;const{position:d,size:f,activeTab:h}=a;return g.jsx(ez,{position:d,size:f,onDragStop:(p,v)=>{i(e,{position:{x:v.x,y:v.y}})},onResizeStop:(p,v,m,b,_)=>{i(e,{size:{width:parseInt(m.style.width,10),height:parseInt(m.style.height,10)},position:_})},minWidth:600,minHeight:400,bounds:"parent",dragHandleClassName:"window-header",style:{zIndex:1e3,display:"flex",flexDirection:"column",pointerEvents:"all"},children:g.jsxs("div",{style:{display:"flex",flexDirection:"column",width:"100%",height:"100%",background:"var(--color-glass-bg)",border:"var(--border-width-1) solid var(--color-glass-border)",borderRadius:"var(--radius-xl)",overflow:"hidden",boxShadow:"var(--shadow-xl)",backdropFilter:"blur(var(--blur-lg))",WebkitBackdropFilter:"blur(var(--blur-lg))"},children:[g.jsxs("div",{className:"window-header",style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"var(--space-component-md) var(--space-component-lg)",background:"rgba(42, 42, 50, 0.5)",borderBottom:"var(--border-width-1) solid var(--color-border-subtle)",cursor:"move",userSelect:"none"},children:[g.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"var(--gap-md)"},children:[g.jsx("div",{style:{width:"10px",height:"10px",borderRadius:"var(--radius-circle)",background:n==="agent"?"var(--color-primary-500)":"var(--color-warning)",boxShadow:n==="agent"?"0 0 8px var(--color-primary-500)":"0 0 8px var(--color-warning)"}}),g.jsxs("span",{style:{color:"var(--color-text-primary)",fontSize:"var(--font-size-body-sm)",fontWeight:"var(--font-weight-semibold)",fontFamily:"var(--font-family-sans)"},children:[n==="agent"?"Agent":"Message",": ",e]})]}),g.jsx("button",{onClick:l,"aria-label":"Close window",style:{background:"transparent",border:"none",color:"var(--color-text-secondary)",fontSize:"var(--font-size-h3)",cursor:"pointer",padding:"var(--spacing-1) var(--spacing-2)",lineHeight:1,borderRadius:"var(--radius-md)",transition:"var(--transition-colors)",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:p=>{p.currentTarget.style.color="var(--color-error)",p.currentTarget.style.background="var(--color-error-bg)"},onMouseLeave:p=>{p.currentTarget.style.color="var(--color-text-secondary)",p.currentTarget.style.background="transparent"},children:"×"})]}),g.jsx("div",{style:{display:"flex",gap:"var(--gap-sm)",padding:"var(--space-component-sm) var(--space-component-lg)",background:"rgba(35, 35, 41, 0.4)",borderBottom:"var(--border-width-1) solid var(--color-border-subtle)"},children:["liveOutput","messageHistory","runStatus"].map(p=>{const v=h===p;return g.jsx("button",{onClick:()=>c(p),style:{position:"relative",padding:"var(--space-component-sm) var(--space-component-md)",background:v?"var(--color-bg-surface)":"transparent",border:"none",borderRadius:"var(--radius-md)",color:v?"var(--color-text-primary)":"var(--color-text-secondary)",fontSize:"var(--font-size-body-sm)",fontWeight:v?"var(--font-weight-semibold)":"var(--font-weight-medium)",fontFamily:"var(--font-family-sans)",cursor:"pointer",transition:"var(--transition-colors)",borderBottom:v?"2px solid var(--color-primary-500)":"2px solid transparent"},onMouseEnter:m=>{v||(m.currentTarget.style.background="var(--color-bg-elevated)",m.currentTarget.style.color="var(--color-text-primary)")},onMouseLeave:m=>{v||(m.currentTarget.style.background="transparent",m.currentTarget.style.color="var(--color-text-secondary)")},children:p==="liveOutput"?"Live Output":p==="messageHistory"?"Message History":"Run Status"},p)})}),g.jsxs("div",{style:{flex:1,overflow:"hidden",background:"var(--color-bg-surface)"},children:[h==="liveOutput"&&g.jsx(nU,{nodeId:e,nodeType:n}),h==="messageHistory"&&g.jsx(rU,{nodeId:e,nodeType:n}),h==="runStatus"&&g.jsx(aU,{nodeId:e,nodeType:n})]})]})})},oU=()=>{const e=ut(l=>l.detailWindows),n=ut(l=>l.mode),a=Me(l=>l.agents),i=Me(l=>l.messages),o=Array.from(e.entries());return g.jsx("div",{style:{position:"fixed",top:0,left:0,right:0,bottom:0,pointerEvents:"none",zIndex:999},children:g.jsx("div",{style:{position:"relative",width:"100%",height:"100%",pointerEvents:"none"},children:o.map(([l,c])=>{let d="agent";return n==="agent"?a.has(l)&&(d="agent"):n==="blackboard"&&i.has(l)&&(d="message"),g.jsx(iU,{nodeId:l,nodeType:d},l)})})})},sU="_container_18lbh_1",lU="_inputWrapper_18lbh_11",cU="_input_18lbh_11",uU="_clearButton_18lbh_67",dU="_dropdown_18lbh_105",fU="_dropdownEmpty_18lbh_135",hU="_dropdownItem_18lbh_149",pU="_correlationId_18lbh_179",gU="_metadata_18lbh_197",Cr={container:sU,inputWrapper:lU,input:cU,clearButton:uU,dropdown:dU,dropdownEmpty:fU,dropdownItem:hU,correlationId:pU,metadata:gU},vU=e=>{const n=Math.floor((Date.now()-e)/1e3);if(n<60)return`${n}s ago`;const a=Math.floor(n/60);if(a<60)return`${a}m ago`;const i=Math.floor(a/60);return i<24?`${i}h ago`:`${Math.floor(i/24)}d ago`},mU=()=>{const e=Te(_=>_.correlationId),n=Te(_=>_.availableCorrelationIds),a=Te(_=>_.setCorrelationId),[i,o]=q.useState(e||""),[l,c]=q.useState(!1),d=q.useRef(null);q.useEffect(()=>{o(e||"")},[e]),q.useEffect(()=>{const _=S=>{d.current&&!d.current.contains(S.target)&&c(!1)};return document.addEventListener("mousedown",_),()=>document.removeEventListener("mousedown",_)},[]);const f=n.filter(_=>_.correlation_id.toLowerCase().includes(i.toLowerCase())),h=_=>{a(_),o(_),c(!1)},p=()=>{a(null),o(""),c(!1)},v=_=>{o(_.target.value),c(!0)},m=()=>{c(!0)},b=()=>{setTimeout(()=>c(!1),200)};return g.jsxs("div",{ref:d,className:Cr.container,children:[g.jsxs("div",{className:Cr.inputWrapper,children:[g.jsx("input",{type:"text",value:i,onChange:v,onFocus:m,onBlur:b,placeholder:"Search correlation ID...",className:Cr.input}),e&&g.jsx("button",{onClick:p,"aria-label":"Clear",className:Cr.clearButton,children:"×"})]}),l&&g.jsx("div",{className:Cr.dropdown,children:f.length===0?g.jsx("div",{className:Cr.dropdownEmpty,children:"No correlation IDs found"}):f.map(_=>g.jsxs("div",{onClick:()=>h(_.correlation_id),className:Cr.dropdownItem,children:[g.jsx("div",{className:Cr.correlationId,children:_.correlation_id}),g.jsxs("div",{className:Cr.metadata,children:[_.artifact_count," messages, ",vU(_.first_seen)]})]},_.correlation_id))})]})},yU="_container_kluuc_1",bU="_presetButtons_kluuc_13",xU="_presetButton_kluuc_13",_U="_active_kluuc_65",SU="_presetButtonAll_kluuc_87",wU="_customRange_kluuc_133",EU="_dateInputGroup_kluuc_153",CU="_dateLabel_kluuc_165",TU="_dateInput_kluuc_153",En={container:yU,presetButtons:bU,presetButton:xU,active:_U,presetButtonAll:SU,customRange:wU,dateInputGroup:EU,dateLabel:CU,dateInput:TU},jU=()=>{const e=Te(d=>d.timeRange),n=Te(d=>d.setTimeRange),a=d=>{if(d==="custom"){const f=Date.now(),h=f-36e5;n({preset:"custom",start:h,end:f})}else n({preset:d})},i=d=>{const f=new Date(d.target.value).getTime();n({preset:"custom",start:f,end:e.end||Date.now()})},o=d=>{const f=new Date(d.target.value).getTime();n({preset:"custom",start:e.start||Date.now()-36e5,end:f})},l=d=>new Date(d).toISOString().slice(0,16),c=[{preset:"all",label:"All"},{preset:"last5min",label:"Last 5 min"},{preset:"last10min",label:"Last 10 min"},{preset:"last1hour",label:"Last hour"},{preset:"custom",label:"Custom"}];return g.jsxs("div",{className:En.container,children:[g.jsx("div",{className:En.presetButtons,children:c.map(({preset:d,label:f})=>g.jsx("button",{onClick:()=>a(d),className:[En.presetButton,d==="all"?En.presetButtonAll:"",e.preset===d?En.active:""].filter(Boolean).join(" "),children:f},d))}),e.preset==="custom"&&g.jsxs("div",{className:En.customRange,children:[g.jsxs("div",{className:En.dateInputGroup,children:[g.jsx("label",{htmlFor:"start-time",className:En.dateLabel,children:"Start"}),g.jsx("input",{id:"start-time",type:"datetime-local",value:e.start?l(e.start):"",onChange:i,className:En.dateInput})]}),g.jsxs("div",{className:En.dateInputGroup,children:[g.jsx("label",{htmlFor:"end-time",className:En.dateLabel,children:"End"}),g.jsx("input",{id:"end-time",type:"datetime-local",value:e.end?l(e.end):"",onChange:o,className:En.dateInput})]})]})]})},so=({options:e,selected:n,onChange:a,placeholder:i="Select items...",disabled:o=!1})=>{const[l,c]=q.useState(!1),[d,f]=q.useState(""),[h,p]=q.useState(0),v=q.useRef(null),m=q.useRef(null),b=e.filter(C=>!n.includes(C)&&C.toLowerCase().includes(d.toLowerCase()));q.useEffect(()=>{const C=T=>{v.current&&!v.current.contains(T.target)&&(c(!1),f(""))};return document.addEventListener("mousedown",C),()=>document.removeEventListener("mousedown",C)},[]);const _=C=>{a([...n,C]),f(""),p(0),m.current?.focus()},S=C=>{a(n.filter(T=>T!==C))},w=C=>{if(!o)switch(C.key){case"ArrowDown":C.preventDefault(),p(T=>Math.min(T+1,b.length-1));break;case"ArrowUp":C.preventDefault(),p(T=>Math.max(T-1,0));break;case"Enter":C.preventDefault(),b[h]&&_(b[h]);break;case"Escape":c(!1),f("");break;case"Backspace":if(d===""&&n.length>0){const T=n[n.length-1];T&&S(T)}break}};return g.jsxs("div",{ref:v,style:{position:"relative"},children:[g.jsxs("div",{onClick:()=>!o&&m.current?.focus(),style:{minHeight:"38px",padding:"var(--space-xs)",backgroundColor:o?"rgba(0, 0, 0, 0.2)":"rgba(0, 0, 0, 0.3)",border:`1px solid ${l?"rgba(96, 165, 250, 0.5)":"rgba(255, 255, 255, 0.1)"}`,borderRadius:"var(--radius-sm)",display:"flex",flexWrap:"wrap",gap:"var(--gap-xs)",cursor:o?"not-allowed":"text",transition:"border-color 0.2s",opacity:o?.6:1},children:[n.map(C=>g.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"var(--gap-xs)",padding:"2px 8px",backgroundColor:"rgba(96, 165, 250, 0.2)",border:"1px solid rgba(96, 165, 250, 0.4)",borderRadius:"var(--radius-sm)",fontSize:"var(--font-size-sm)",color:"#60a5fa",maxWidth:"100%",overflow:"hidden"},children:[g.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},title:C,children:C}),!o&&g.jsx("button",{onClick:T=>{T.stopPropagation(),S(C)},style:{background:"none",border:"none",color:"#60a5fa",cursor:"pointer",padding:0,display:"flex",alignItems:"center",fontSize:"14px",lineHeight:1,flexShrink:0},children:"×"})]},C)),g.jsx("input",{ref:m,type:"text",value:d,onChange:C=>{f(C.target.value),c(!0),p(0)},onFocus:()=>!o&&c(!0),onKeyDown:w,placeholder:n.length===0?i:"",disabled:o,style:{flex:1,minWidth:"120px",background:"transparent",border:"none",outline:"none",color:"var(--color-text-primary)",fontSize:"var(--font-size-base)",padding:"4px"}})]}),l&&!o&&b.length>0&&g.jsx("div",{style:{position:"absolute",top:"calc(100% + 4px)",left:0,right:0,maxHeight:"240px",overflowY:"auto",backgroundColor:"rgba(0, 0, 0, 0.9)",border:"1px solid rgba(96, 165, 250, 0.3)",borderRadius:"var(--radius-sm)",boxShadow:"0 4px 12px rgba(0, 0, 0, 0.5)",zIndex:1e3},children:b.map((C,T)=>g.jsx("div",{onClick:()=>_(C),onMouseEnter:()=>p(T),style:{padding:"var(--space-xs) var(--space-sm)",cursor:"pointer",backgroundColor:T===h?"rgba(96, 165, 250, 0.2)":"transparent",color:T===h?"#60a5fa":"var(--color-text-primary)",fontSize:"var(--font-size-sm)",transition:"background-color 0.15s"},children:C},C))})]})},NU=()=>{const e=Te(i=>i.availableArtifactTypes),n=Te(i=>i.selectedArtifactTypes),a=Te(i=>i.setArtifactTypes);return g.jsx(so,{options:e,selected:n,onChange:a,placeholder:e.length?"Select types…":"No types available",disabled:e.length===0})},RU=()=>{const e=Te(i=>i.availableProducers),n=Te(i=>i.selectedProducers),a=Te(i=>i.setProducers);return g.jsx(so,{options:e,selected:n,onChange:a,placeholder:e.length?"Select producers…":"No producers",disabled:e.length===0})},MU=()=>{const e=Te(i=>i.availableTags),n=Te(i=>i.selectedTags),a=Te(i=>i.setTags);return g.jsx(so,{options:e,selected:n,onChange:a,placeholder:e.length?"Select tags…":"No tags available",disabled:e.length===0})},AU=()=>{const e=Te(i=>i.availableVisibility),n=Te(i=>i.selectedVisibility),a=Te(i=>i.setVisibility);return g.jsx(so,{options:e,selected:n,onChange:a,placeholder:e.length?"Select visibility…":"No visibility options",disabled:e.length===0})},zU="_container_9ted7_1",DU="_controlsRow_9ted7_13",kU="_select_9ted7_27",OU="_saveButton_9ted7_45",qU="_applyButton_9ted7_47",BU="_deleteButton_9ted7_49",LU="_error_9ted7_113",qa={container:zU,controlsRow:DU,select:kU,saveButton:OU,applyButton:qU,deleteButton:BU,error:LU},HU=()=>{const e=Te(w=>w.savedFilters),n=Te(w=>w.setSavedFilters),a=Te(w=>w.addSavedFilter),i=Te(w=>w.removeSavedFilter),o=Te(w=>w.getFilterSnapshot),l=Te(w=>w.applyFilterSnapshot),[c,d]=q.useState(""),[f,h]=q.useState(!0),[p,v]=q.useState(null),m=q.useRef(0);m.current+=1,q.useEffect(()=>{let w=!0;return(async()=>{try{await Cn.initialize();const C=await Cn.getAllFilterPresets();if(!w)return;n(C),C.length>0?d(C[0]?.filter_id??""):d(""),v(null)}catch(C){console.error("[SavedFilters] Failed to load presets",C),w&&v("Unable to load saved presets")}finally{w&&h(!1)}})(),()=>{w=!1}},[n]);const b=async()=>{const w=window.prompt("Save current filters as preset. Enter a name:");if(!(!w||!w.trim()))try{const C={filter_id:typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`filter-${Date.now()}`,name:w.trim(),created_at:Date.now(),filters:o()};await Cn.saveFilterPreset(C),a(C),d(C.filter_id),v(null)}catch(C){console.error("[SavedFilters] Failed to save preset",C),v("Failed to save preset")}},_=()=>{if(!c)return;const w=e.find(C=>C.filter_id===c);w&&l(w.filters)},S=async()=>{if(c)try{await Cn.deleteFilterPreset(c),i(c);const w=e.filter(C=>C.filter_id!==c);d(w[0]?.filter_id??""),v(null)}catch(w){console.error("[SavedFilters] Failed to delete preset",w),v("Failed to delete preset")}};return g.jsxs("div",{className:qa.container,children:[g.jsxs("div",{className:qa.controlsRow,children:[g.jsx("button",{type:"button",className:qa.saveButton,onClick:b,disabled:f,children:"Save Current"}),g.jsxs("select",{className:qa.select,value:c,onChange:w=>d(w.target.value),disabled:f||e.length===0,"aria-label":"Saved filter presets",children:[e.length===0&&g.jsx("option",{value:"",children:"No presets"}),e.map(w=>g.jsx("option",{value:w.filter_id,children:w.name},w.filter_id))]}),g.jsx("button",{type:"button",className:qa.applyButton,onClick:_,disabled:!c,children:"Apply"}),g.jsx("button",{type:"button",className:qa.deleteButton,onClick:S,disabled:!c,children:"Delete"})]}),p&&g.jsx("div",{className:qa.error,children:p})]})},IU="_panel_knkln_1",UU="_header_knkln_33",VU="_title_knkln_51",FU="_subtitle_knkln_63",PU="_closeButton_knkln_75",GU="_content_knkln_109",$U="_section_knkln_127",YU="_sectionLabel_knkln_139",WU="_separator_knkln_155",rt={panel:IU,header:UU,title:VU,subtitle:FU,closeButton:PU,content:GU,section:$U,sectionLabel:YU,separator:WU},XU=({onClose:e})=>g.jsxs("aside",{className:rt.panel,role:"dialog","aria-label":"Filters",children:[g.jsxs("header",{className:rt.header,children:[g.jsxs("div",{children:[g.jsx("h2",{className:rt.title,children:"Filters"}),g.jsx("p",{className:rt.subtitle,children:"Slice historical data without losing your place."})]}),g.jsx("button",{type:"button",className:rt.closeButton,onClick:e,"aria-label":"Close filters",children:"×"})]}),g.jsxs("div",{className:rt.content,children:[g.jsxs("section",{className:rt.section,children:[g.jsx("h3",{className:rt.sectionLabel,children:"Presets"}),g.jsx(HU,{})]}),g.jsx("div",{className:rt.separator,role:"presentation"}),g.jsxs("section",{className:rt.section,children:[g.jsx("h3",{className:rt.sectionLabel,children:"Correlation"}),g.jsx(mU,{})]}),g.jsx("div",{className:rt.separator,role:"presentation"}),g.jsxs("section",{className:rt.section,children:[g.jsx("h3",{className:rt.sectionLabel,children:"Time Range"}),g.jsx(jU,{})]}),g.jsx("div",{className:rt.separator,role:"presentation"}),g.jsxs("section",{className:rt.section,children:[g.jsx("h3",{className:rt.sectionLabel,children:"Artifact Types"}),g.jsx(NU,{})]}),g.jsx("div",{className:rt.separator,role:"presentation"}),g.jsxs("section",{className:rt.section,children:[g.jsx("h3",{className:rt.sectionLabel,children:"Producers"}),g.jsx(RU,{})]}),g.jsx("div",{className:rt.separator,role:"presentation"}),g.jsxs("section",{className:rt.section,children:[g.jsx("h3",{className:rt.sectionLabel,children:"Tags"}),g.jsx(MU,{})]}),g.jsx("div",{className:rt.separator,role:"presentation"}),g.jsxs("section",{className:rt.section,children:[g.jsx("h3",{className:rt.sectionLabel,children:"Visibility"}),g.jsx(AU,{})]})]})]}),KU="_wrapper_1qq57_1",ZU="_container_1qq57_15",QU="_toggleButton_1qq57_37",JU="_toggleButtonActive_1qq57_103",eV="_toggleIcon_1qq57_125",tV="_toggleLabel_1qq57_155",nV="_pill_1qq57_163",rV="_pillAccent_1qq57_227",aV="_textGroup_1qq57_245",iV="_pillTitle_1qq57_259",oV="_pillValue_1qq57_275",sV="_removeButton_1qq57_289",lV="_removeIcon_1qq57_349",dn={wrapper:KU,container:ZU,toggleButton:QU,toggleButtonActive:JU,toggleIcon:eV,toggleLabel:tV,pill:nV,pillAccent:rV,textGroup:aV,pillTitle:iV,pillValue:oV,removeButton:sV,removeIcon:lV},cV=e=>{const n=e.match(/^([^:]+):(.*)$/),a=n?.[1]?.trim()??e.trim(),i=n?.[2]?.trim()??"";return{title:a,value:i}},uV=()=>{const e=_e(p=>p.ui.showFilters),n=_e(p=>p.setShowFilters),a=Te(p=>p.correlationId),i=Te(p=>p.timeRange),o=Te(p=>p.selectedArtifactTypes),l=Te(p=>p.selectedProducers),c=Te(p=>p.selectedTags),d=Te(p=>p.selectedVisibility),f=Te(p=>p.removeFilter),h=q.useMemo(()=>{const p=[];return a&&p.push({type:"correlationId",value:a,label:`Correlation ID: ${a}`}),p.push({type:"timeRange",value:i,label:`Time: ${ab(i)}`}),o.forEach(v=>{p.push({type:"artifactTypes",value:v,label:`Type: ${v}`})}),l.forEach(v=>{p.push({type:"producers",value:v,label:`Producer: ${v}`})}),c.forEach(v=>{p.push({type:"tags",value:v,label:`Tag: ${v}`})}),d.forEach(v=>{p.push({type:"visibility",value:v,label:`Visibility: ${v}`})}),p},[a,i,o,l,c,d]);return h.length===0?null:g.jsxs("div",{className:dn.wrapper,children:[g.jsxs("button",{type:"button",onClick:()=>n(!e),className:`${dn.toggleButton} ${e?dn.toggleButtonActive:""}`,title:`${e?"Hide":"Show"} filter panel (Ctrl+Shift+F)`,"aria-pressed":e,"aria-label":e?"Hide filter panel":"Show filter panel",children:[g.jsx("span",{className:dn.toggleIcon,"aria-hidden":"true",children:g.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:g.jsx("path",{d:"M2.667 2.667h10.666L9.333 7v4.667l-2.666 1.333V7L2.667 2.667z",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),g.jsx("span",{className:dn.toggleLabel,children:"Filter"})]}),g.jsx("div",{className:dn.container,role:"list",children:h.map((p,v)=>{const m=p.type==="timeRange"&&typeof p.value!="string"?`Time: ${ab(p.value)}`:p.label,{title:b,value:_}=cV(m),S=_?`${b} ${_}`:b;return g.jsxs("div",{className:dn.pill,"data-filter-type":p.type,role:"listitem",children:[g.jsx("span",{className:dn.pillAccent,"aria-hidden":"true"}),g.jsxs("div",{className:dn.textGroup,children:[g.jsx("span",{className:dn.pillTitle,children:b}),_&&g.jsx("span",{className:dn.pillValue,children:_})]}),g.jsx("button",{onClick:()=>f(p),"aria-label":`Remove ${S} filter`,className:dn.removeButton,type:"button",children:g.jsx("span",{"aria-hidden":"true",className:dn.removeIcon,children:"×"})})]},`${p.type}-${String(p.value)}-${v}`)})})]})},Ks="/api";class er extends Error{constructor(n,a){super(a.message||a.error),this.status=n,this.errorResponse=a,this.name="ApiError"}}async function dV(){try{const e=await fetch(`${Ks}/artifact-types`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!e.ok){const a=await e.json().catch(()=>({error:"Unknown error",message:"Failed to fetch artifact types"}));throw new er(e.status,a)}return(await e.json()).artifact_types}catch(e){throw e instanceof er?e:new Error("Failed to connect to API server")}}async function fV(){try{const e=await fetch(`${Ks}/agents`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!e.ok){const a=await e.json().catch(()=>({error:"Unknown error",message:"Failed to fetch agents"}));throw new er(e.status,a)}return(await e.json()).agents}catch(e){throw e instanceof er?e:new Error("Failed to connect to API server")}}async function hV(){return(await fV()).map(n=>({id:n.name,name:n.name,status:"idle",subscriptions:n.subscriptions||[],outputTypes:n.output_types||[],lastActive:Date.now(),sentCount:0,recvCount:0,receivedByType:{},sentByType:{}}))}async function pV(e,n){try{const a=await fetch(`${Ks}/control/publish`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({artifact_type:e,content:n})});if(!a.ok){const i=await a.json().catch(()=>({error:"Unknown error",message:"Failed to publish artifact"}));throw new er(a.status,i)}return await a.json()}catch(a){throw a instanceof er?a:new Error("Failed to connect to API server")}}const tz=e=>{const n=new URLSearchParams;return e.types?.forEach(a=>n.append("type",a)),e.producers?.forEach(a=>n.append("produced_by",a)),e.tags?.forEach(a=>n.append("tag",a)),e.visibility?.forEach(a=>n.append("visibility",a)),e.correlationId&&n.append("correlation_id",e.correlationId),e.from&&n.append("from",e.from),e.to&&n.append("to",e.to),typeof e.limit=="number"&&n.append("limit",String(e.limit)),typeof e.offset=="number"&&n.append("offset",String(e.offset)),e.embedMeta&&n.append("embed_meta","true"),n.toString()};async function nz(e={}){const n=tz(e);try{const a=await fetch(`${Ks}/v1/artifacts${n?`?${n}`:""}`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!a.ok){const o=await a.json().catch(()=>({error:"Unknown error",message:"Failed to fetch artifacts"}));throw new er(a.status,o)}return await a.json()}catch(a){throw a instanceof er?a:new Error("Failed to connect to API server")}}async function rz(e={}){const n=tz(e);try{const a=await fetch(`${Ks}/v1/artifacts/summary${n?`?${n}`:""}`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!a.ok){const o=await a.json().catch(()=>({error:"Unknown error",message:"Failed to fetch artifact summary"}));throw new er(a.status,o)}return(await a.json()).summary}catch(a){throw a instanceof er?a:new Error("Failed to connect to API server")}}const gV=()=>{const[e,n]=q.useState([]),[a,i]=q.useState(""),[o,l]=q.useState({}),[c,d]=q.useState(!1),[f,h]=q.useState(!0),[p,v]=q.useState({}),[m,b]=q.useState(""),[_,S]=q.useState(""),[w,C]=q.useState(!0),T=_e(j=>j.setShowControls),E=()=>{T(!1)};q.useEffect(()=>{(async()=>{try{h(!0);const A=await dV();n(A)}catch(A){console.error("Failed to fetch artifact types:",A),S("Failed to load artifact types")}finally{h(!1)}})()},[]),q.useEffect(()=>{if(a){const j=e.find(A=>A.name===a);if(j&&j.schema.properties){const A={};Object.keys(j.schema.properties).forEach(D=>{const I=j.schema.properties[D];I.type==="boolean"?A[D]=!1:(I.type==="number"||I.type,A[D]=I.default??"")}),l(A)}}else l({});v({})},[a,e]);const N=()=>{const j={};if(!a)return j.artifactType="Artifact type is required",v(j),!1;const A=e.find(D=>D.name===a);return A?(A.schema.properties&&Object.entries(A.schema.properties).forEach(([D,I])=>{const P=o[D];if(P===""||P===null||P===void 0){j[D]=`${D} is required`;return}(I.type==="number"||I.type==="integer")&&isNaN(Number(P))&&(j[D]=`${D} must be a number`)}),v(j),Object.keys(j).length===0):(j.artifactType="Invalid artifact type",v(j),!1)},R=async j=>{if(j.preventDefault(),b(""),S(""),!!N()){d(!0);try{const A=e.find(P=>P.name===a),D={};A&&A.schema.properties&&Object.entries(o).forEach(([P,V])=>{const $=A.schema.properties[P];$.type==="number"||$.type==="integer"?D[P]=Number(V):$.type==="boolean"?D[P]=!!V:D[P]=V});const I=await pV(a,D);w&&I.correlation_id?(Te.setState({correlationId:I.correlation_id}),b(`Successfully published artifact. Filter set to: ${I.correlation_id}`)):b(`Successfully published artifact. Correlation ID: ${I.correlation_id}`),i(""),l({}),v({}),setTimeout(()=>{T(!1)},800)}catch(A){A.message.includes("Network error")||A.message.includes("Failed to connect")?S("Network error. Failed to connect to API server."):S(A.message||"Failed to publish artifact")}finally{d(!1)}}},z=(j,A)=>{const D=o[j]??"",I=!!p[j],P=$=>{if(l({...o,[j]:$}),p[j]){const L={...p};delete L[j],v(L)}};return A.type==="boolean"?g.jsxs("div",{className:"publish-control__field",children:[g.jsxs("div",{className:"publish-control__checkbox-wrapper",children:[g.jsx("input",{type:"checkbox",id:`field-${j}`,checked:!!D,onChange:$=>P($.target.checked),disabled:c,className:"publish-control__checkbox"}),g.jsxs("label",{htmlFor:`field-${j}`,className:"publish-control__checkbox-label",children:[A.title||j,A.description&&g.jsxs("span",{className:"publish-control__field-hint",children:[" — ",A.description]})]})]}),I&&g.jsx("div",{className:"publish-control__error-text",children:p[j]})]},j):A.type==="number"||A.type==="integer"?g.jsxs("div",{className:"publish-control__field",children:[g.jsxs("label",{htmlFor:`field-${j}`,className:"publish-control__label",children:[A.title||j,A.description&&g.jsxs("span",{className:"publish-control__field-hint",children:[" — ",A.description]})]}),g.jsx("input",{type:"number",id:`field-${j}`,value:D,onChange:$=>P($.target.value),disabled:c,step:A.type==="integer"?1:"any",className:`publish-control__input ${I?"publish-control__input--error":""}`}),I&&g.jsx("div",{className:"publish-control__error-text",children:p[j]})]},j):A.enum&&Array.isArray(A.enum)?g.jsxs("div",{className:"publish-control__field",children:[g.jsxs("label",{htmlFor:`field-${j}`,className:"publish-control__label",children:[A.title||j,A.description&&g.jsxs("span",{className:"publish-control__field-hint",children:[" — ",A.description]})]}),g.jsxs("select",{id:`field-${j}`,value:D,onChange:$=>P($.target.value),disabled:c,className:`publish-control__select ${I?"publish-control__select--error":""}`,children:[g.jsx("option",{value:"",children:"Select..."}),A.enum.map($=>g.jsx("option",{value:$,children:$},$))]}),I&&g.jsx("div",{className:"publish-control__error-text",children:p[j]})]},j):A.maxLength>100||j.toLowerCase().includes("description")?g.jsxs("div",{className:"publish-control__field",children:[g.jsxs("label",{htmlFor:`field-${j}`,className:"publish-control__label",children:[A.title||j,A.description&&g.jsxs("span",{className:"publish-control__field-hint",children:[" — ",A.description]})]}),g.jsx("textarea",{id:`field-${j}`,value:D,onChange:$=>P($.target.value),disabled:c,rows:4,className:`publish-control__textarea ${I?"publish-control__textarea--error":""}`}),I&&g.jsx("div",{className:"publish-control__error-text",children:p[j]})]},j):g.jsxs("div",{className:"publish-control__field",children:[g.jsxs("label",{htmlFor:`field-${j}`,className:"publish-control__label",children:[A.title||j,A.description&&g.jsxs("span",{className:"publish-control__field-hint",children:[" — ",A.description]})]}),g.jsx("input",{type:"text",id:`field-${j}`,value:D,onChange:$=>P($.target.value),disabled:c,placeholder:A.examples?.[0]||"",className:`publish-control__input ${I?"publish-control__input--error":""}`}),I&&g.jsx("div",{className:"publish-control__error-text",children:p[j]})]},j)};return g.jsx("div",{className:"publish-control-panel",children:g.jsxs("div",{className:"publish-control-panel-inner",children:[g.jsxs("div",{className:"publish-control-header",children:[g.jsx("h2",{className:"publish-control-title",children:"Publish Artifact"}),g.jsx("button",{onClick:E,className:"publish-control-close-button","aria-label":"Close publish panel",title:"Close publish panel (Esc)",children:g.jsx("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:g.jsx("path",{d:"M15 5L5 15M5 5l10 10",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]}),g.jsx("div",{className:"publish-control-content",children:g.jsxs("form",{className:"publish-control__form",onSubmit:R,children:[g.jsxs("div",{className:"publish-control__field",children:[g.jsx("label",{htmlFor:"artifact-type",className:"publish-control__label",children:"Artifact Type"}),g.jsxs("select",{id:"artifact-type",value:a,onChange:j=>{i(j.target.value),v({...p,artifactType:void 0})},disabled:f||c,className:`publish-control__select ${p.artifactType?"publish-control__select--error":""}`,children:[g.jsx("option",{value:"",children:"Select an artifact type..."}),e.map(j=>g.jsx("option",{value:j.name,children:j.name},j.name))]}),p.artifactType&&g.jsx("div",{className:"publish-control__error-text",children:p.artifactType})]}),a&&(()=>{const j=e.find(A=>A.name===a);return j&&j.schema.properties?Object.entries(j.schema.properties).map(([A,D])=>z(A,D)):g.jsx("div",{className:"publish-control__field",children:g.jsx("p",{className:"publish-control__hint",children:"Select an artifact type to see form fields"})})})(),g.jsxs("div",{className:"publish-control__checkbox-wrapper",children:[g.jsx("input",{type:"checkbox",id:"auto-set-filter",checked:w,onChange:j=>C(j.target.checked),disabled:c,className:"publish-control__checkbox"}),g.jsx("label",{htmlFor:"auto-set-filter",className:"publish-control__checkbox-label",children:"Set filter to correlation ID (show only this execution)"})]}),g.jsx("button",{type:"submit",disabled:c||f,className:"publish-control__submit",children:c?"Publishing...":"Publish Artifact"}),m&&g.jsx("div",{className:"publish-control__message publish-control__message--success",children:m}),_&&g.jsx("div",{className:"publish-control__message publish-control__message--error",children:_})]})})]})})};function vV(){const e=jr(b=>b.instances),n=Me(b=>b.agents),a=Me(b=>b.messages),i=Me(b=>b.events),o=Te(b=>b.correlationId),l=Te(b=>b.timeRange),c=Te(b=>b.selectedArtifactTypes),d=Te(b=>b.selectedProducers),f=Te(b=>b.selectedTags),h=Te(b=>b.selectedVisibility),p=Te(b=>b.summary),v=q.useRef(new Map),m=q.useMemo(()=>({agents:n,messages:a,events:i,filters:{correlationId:o,timeRange:l,artifactTypes:c,producers:d,tags:f,visibility:h},summary:p,publish:b=>{console.log("[Module Context] Publish artifact:",b)},invoke:(b,_)=>{console.log("[Module Context] Invoke agent:",b,"with inputs:",_)}}),[n,a,i,o,l,c,d,f,h,p]);return q.useEffect(()=>{const b=e,_=v.current,S=new Map;b.forEach((C,T)=>{_.has(T)||S.set(T,C)});const w=new Map;return _.forEach((C,T)=>{b.has(T)||w.set(T,C)}),S.forEach(C=>{const T=Va.get(C.type);if(T?.onMount){console.log(`[useModules] Calling onMount for module: ${T.name} (${C.id})`);try{T.onMount(m)}catch(E){console.error(`[useModules] Error in onMount for module ${T.name}:`,E)}}}),w.forEach(C=>{const T=Va.get(C.type);if(T?.onUnmount){console.log(`[useModules] Calling onUnmount for module: ${T.name} (${C.id})`);try{T.onUnmount()}catch(E){console.error(`[useModules] Error in onUnmount for module ${T.name}:`,E)}}}),v.current=new Map(b),()=>{b.forEach(C=>{const T=Va.get(C.type);if(T?.onUnmount){console.log(`[useModules] Cleanup: Calling onUnmount for module: ${T.name} (${C.id})`);try{T.onUnmount()}catch(E){console.error(`[useModules] Error in cleanup onUnmount for module ${T.name}:`,E)}}})}},[e,m]),{context:m}}const az=q.memo(({instanceId:e})=>{const n=jr(v=>v.instances.get(e)),a=jr(v=>v.updateModule),i=jr(v=>v.removeModule),{context:o}=vV(),l=q.useCallback(()=>{i(e)},[e,i]),c=q.useCallback(()=>{n&&(n.maximized?a(e,{maximized:!1,position:n.preMaximizePosition||n.position,size:n.preMaximizeSize||n.size}):a(e,{maximized:!0,preMaximizePosition:n.position,preMaximizeSize:n.size,position:{x:0,y:0},size:{width:window.innerWidth,height:window.innerHeight}}))},[e,n,a]);if(!n||!n.visible)return null;const d=Va.get(n.type);if(!d)return console.error(`Module definition not found for type: ${n.type}`),null;const{position:f,size:h}=n,p=d.component;return g.jsx(ez,{position:f,size:h,disableDragging:n.maximized,enableResizing:!n.maximized,onDragStop:(v,m)=>{a(e,{position:{x:m.x,y:m.y}})},onResizeStop:(v,m,b,_,S)=>{a(e,{size:{width:parseInt(b.style.width,10),height:parseInt(b.style.height,10)},position:S})},minWidth:1e3,minHeight:500,bounds:"parent",dragHandleClassName:"module-window-header",style:{zIndex:1e3,display:"flex",flexDirection:"column"},children:g.jsxs("div",{style:{display:"flex",flexDirection:"column",width:"100%",height:"100%",background:"var(--color-glass-bg)",border:"var(--border-width-1) solid var(--color-glass-border)",borderRadius:"var(--radius-xl)",overflow:"hidden",boxShadow:"var(--shadow-xl)",backdropFilter:"blur(var(--blur-lg))",WebkitBackdropFilter:"blur(var(--blur-lg))"},children:[g.jsxs("div",{className:"module-window-header",style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"var(--space-component-md) var(--space-component-lg)",background:"rgba(42, 42, 50, 0.5)",borderBottom:"var(--border-width-1) solid var(--color-border-subtle)",cursor:n.maximized?"default":"move",userSelect:"none"},children:[g.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"var(--gap-md)"},children:[d.icon&&g.jsx("span",{style:{fontSize:16},children:d.icon}),g.jsx("span",{style:{color:"var(--color-text-primary)",fontSize:"var(--font-size-body-sm)",fontWeight:"var(--font-weight-semibold)",fontFamily:"var(--font-family-sans)"},children:d.name})]}),g.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"var(--gap-xs)"},children:[g.jsx("button",{onClick:c,"aria-label":n.maximized?"Restore window":"Maximize window",title:n.maximized?"Restore":"Maximize",style:{background:"transparent",border:"none",color:"var(--color-text-secondary)",fontSize:"16px",cursor:"pointer",padding:"var(--spacing-1) var(--spacing-2)",lineHeight:1,borderRadius:"var(--radius-md)",transition:"var(--transition-colors)",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:v=>{v.currentTarget.style.color="var(--color-text-primary)",v.currentTarget.style.background="var(--color-bg-elevated)"},onMouseLeave:v=>{v.currentTarget.style.color="var(--color-text-secondary)",v.currentTarget.style.background="transparent"},children:n.maximized?g.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"1.5",children:[g.jsx("rect",{x:"4",y:"4",width:"6",height:"6"}),g.jsx("path",{d:"M2 2h4v4M12 12H8V8"})]}):g.jsx("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"1.5",children:g.jsx("rect",{x:"2",y:"2",width:"10",height:"10"})})}),g.jsx("button",{onClick:l,"aria-label":"Close window",title:"Close",style:{background:"transparent",border:"none",color:"var(--color-text-secondary)",fontSize:"var(--font-size-h3)",cursor:"pointer",padding:"var(--spacing-1) var(--spacing-2)",lineHeight:1,borderRadius:"var(--radius-md)",transition:"var(--transition-colors)",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:v=>{v.currentTarget.style.color="var(--color-error)",v.currentTarget.style.background="var(--color-error-bg)"},onMouseLeave:v=>{v.currentTarget.style.color="var(--color-text-secondary)",v.currentTarget.style.background="transparent"},children:"×"})]})]}),g.jsx("div",{style:{flex:1,overflow:"hidden",background:"var(--color-bg-surface)"},children:g.jsx(p,{context:o})})]})})});az.displayName="ModuleWindow";const mV=()=>{const e=_e(f=>f.graph.edgeType),n=_e(f=>f.graph.edgeStrokeWidth),a=_e(f=>f.graph.edgeAnimation),i=_e(f=>f.graph.showEdgeLabels),o=_e(f=>f.setEdgeType),l=_e(f=>f.setEdgeStrokeWidth),c=_e(f=>f.setEdgeAnimation),d=_e(f=>f.setShowEdgeLabels);return g.jsxs("div",{children:[g.jsxs("div",{className:"settings-section",children:[g.jsx("h3",{className:"settings-section-title",children:"Edge Appearance"}),g.jsxs("div",{className:"settings-field",children:[g.jsx("label",{htmlFor:"edge-type",className:"settings-label",children:"Edge Type"}),g.jsx("p",{className:"settings-description",children:"Choose how connections between nodes are drawn"}),g.jsxs("select",{id:"edge-type",value:e,onChange:f=>o(f.target.value),className:"settings-select",children:[g.jsx("option",{value:"bezier",children:"Bezier (Curved) - Default"}),g.jsx("option",{value:"smoothstep",children:"Smooth Step"}),g.jsx("option",{value:"straight",children:"Straight (90° Angles)"}),g.jsx("option",{value:"simplebezier",children:"Simple Bezier"})]})]}),g.jsxs("div",{className:"settings-field",children:[g.jsxs("label",{htmlFor:"edge-width",className:"settings-label",children:["Edge Stroke Width: ",n,"px"]}),g.jsx("input",{id:"edge-width",type:"range",min:"1",max:"5",step:"0.5",value:n,onChange:f=>l(parseFloat(f.target.value)),className:"settings-input"})]})]}),g.jsxs("div",{className:"settings-section",children:[g.jsx("h3",{className:"settings-section-title",children:"Edge Behavior"}),g.jsxs("div",{className:"settings-field",children:[g.jsxs("div",{className:"settings-checkbox-wrapper",children:[g.jsx("input",{id:"edge-animation",type:"checkbox",checked:a,onChange:f=>c(f.target.checked),className:"settings-checkbox"}),g.jsx("label",{htmlFor:"edge-animation",className:"settings-checkbox-label",children:"Enable edge animation"})]}),g.jsx("p",{className:"settings-description",children:"Animate message flow along edges (may impact performance)"})]}),g.jsxs("div",{className:"settings-field",children:[g.jsxs("div",{className:"settings-checkbox-wrapper",children:[g.jsx("input",{id:"edge-labels",type:"checkbox",checked:i,onChange:f=>d(f.target.checked),className:"settings-checkbox"}),g.jsx("label",{htmlFor:"edge-labels",className:"settings-checkbox-label",children:"Show edge labels"})]}),g.jsx("p",{className:"settings-description",children:"Display correlation IDs and other metadata on edges"})]})]})]})},iz="/api";async function yV(){try{const e=await fetch(`${iz}/themes`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!e.ok)throw new Error(`Failed to fetch themes: ${e.statusText}`);return(await e.json()).themes}catch(e){throw console.error("Error fetching theme list:",e),e}}async function UN(e){try{const n=await fetch(`${iz}/themes/${e}`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!n.ok)throw new Error(`Failed to fetch theme "${e}": ${n.statusText}`);const a=await n.json();return{name:a.name,colors:a.data.colors}}catch(n){throw console.error(`Error fetching theme "${e}":`,n),n}}const Iy=["dracula","nord","catppuccin-mocha","tokyonight","gruvboxdark","solarized-dark","github-dark","one-half-dark","monokai","material"];function ms(e,n){const a=parseInt(e.slice(1,3),16),i=parseInt(e.slice(3,5),16),o=parseInt(e.slice(5,7),16);return`rgba(${a}, ${i}, ${o}, ${n})`}function VN(e){const n=document.documentElement,{colors:a}=e;n.style.setProperty("--color-bg-base",a.primary.background),n.style.setProperty("--color-bg-elevated",a.selection.background),n.style.setProperty("--color-bg-surface",a.normal.black),n.style.setProperty("--color-bg-overlay",a.bright.black),n.style.setProperty("--color-bg-float",ms(a.normal.white,.1)),n.style.setProperty("--color-text-primary",a.primary.foreground),n.style.setProperty("--color-text-secondary",a.bright.white),n.style.setProperty("--color-text-tertiary",a.selection.text),n.style.setProperty("--color-text-muted",a.cursor.text),n.style.setProperty("--color-text-on-primary",a.selection.text),n.style.setProperty("--color-primary-500",a.normal.blue),n.style.setProperty("--color-primary-400",a.bright.blue),n.style.setProperty("--color-primary-600",a.normal.blue),n.style.setProperty("--color-secondary-500",a.normal.magenta),n.style.setProperty("--color-secondary-400",a.bright.magenta),n.style.setProperty("--color-tertiary-500",a.normal.cyan),n.style.setProperty("--color-success",a.normal.green),n.style.setProperty("--color-success-light",a.bright.green),n.style.setProperty("--color-error",a.normal.red),n.style.setProperty("--color-error-light",a.bright.red),n.style.setProperty("--color-warning",a.normal.yellow),n.style.setProperty("--color-warning-light",a.bright.yellow),n.style.setProperty("--color-info",a.normal.cyan),n.style.setProperty("--color-info-light",a.bright.cyan);const i=n.style.getPropertyValue("--agent-idle-color");(!i||i==="#60a5fa")&&n.style.setProperty("--agent-idle-color",a.normal.cyan);const o=n.style.getPropertyValue("--agent-active-color");(!o||o==="#10b981")&&n.style.setProperty("--agent-active-color",a.normal.green);const l=n.style.getPropertyValue("--agent-error-color");(!l||l==="#ef4444")&&n.style.setProperty("--agent-error-color",a.normal.red),n.style.setProperty("--color-border-default",a.bright.black),n.style.setProperty("--color-border-subtle",ms(a.normal.white,.2)),n.style.setProperty("--color-border-strong",a.cursor.cursor),n.style.setProperty("--color-border-focus",a.normal.blue),n.style.setProperty("--color-border-error",a.normal.red),n.style.setProperty("--color-glass-bg",ms(a.selection.background,.8)),n.style.setProperty("--color-glow-primary",a.cursor.cursor),n.style.setProperty("--shadow-glow-primary",`0 0 0 3px ${ms(a.bright.blue,.5)}`),n.style.setProperty("--shadow-glow-error",`0 0 0 3px ${ms(a.bright.red,.5)}`),n.style.setProperty("--color-edge-default",a.bright.black),n.style.setProperty("--color-edge-message",a.bright.yellow),n.style.setProperty("--color-edge-active",a.bright.blue),n.style.setProperty("--color-node-message-border",a.normal.magenta),console.log(`[Theme] Applied theme: ${e.name}`)}function Uy(){const e=document.documentElement;e.style.setProperty("--color-bg-base","#0a0a0b"),e.style.setProperty("--color-bg-elevated","#121214"),e.style.setProperty("--color-bg-surface","#1a1a1e"),e.style.setProperty("--color-bg-overlay","#232329"),e.style.setProperty("--color-bg-float","#2a2a32"),e.style.setProperty("--color-text-primary","#e5e7eb"),e.style.setProperty("--color-text-secondary","#9ca3af"),e.style.setProperty("--color-text-tertiary","#6b7280"),e.style.setProperty("--color-primary-500","#6366f1"),e.style.setProperty("--color-primary-400","#818cf8"),e.style.setProperty("--color-primary-600","#4f46e5"),console.log("[Theme] Reset to default theme")}const bV=()=>{const[e,n]=q.useState([]),[a,i]=q.useState(!1),[o,l]=q.useState(null),[c,d]=q.useState(""),[f,h]=q.useState(null),p=_e(R=>R.appearance.theme),v=_e(R=>R.setTheme);q.useEffect(()=>{m()},[]);const m=async()=>{try{i(!0),l(null);const R=await yV();n(R)}catch(R){l("Failed to load themes. Backend may not be running."),console.error("Theme loading error:",R),n(Iy)}finally{i(!1)}},b=async R=>{try{if(l(null),R==="default"){Uy(),v("default"),h(null);return}const z=await UN(R);VN(z),v(R),h(null)}catch(z){l(`Failed to load theme "${R}"`),console.error("Theme application error:",z)}},_=async R=>{try{if(R==="default"){Uy(),h(null);return}const z=await UN(R);h(z),VN(z)}catch(z){console.error("Theme preview error:",z)}},S=()=>{Uy(),v("default"),h(null)},C=["default",...e].filter(R=>R.toLowerCase().includes(c.toLowerCase())),T=C.filter(R=>Iy.includes(R)),E=C.includes("default")?["default"]:[],N=C.filter(R=>!Iy.includes(R)&&R!=="default");return g.jsxs("div",{children:[g.jsxs("div",{className:"settings-field",children:[g.jsx("label",{htmlFor:"theme-search",className:"settings-label",children:"Search Themes"}),g.jsx("input",{id:"theme-search",type:"text",value:c,onChange:R=>d(R.target.value),placeholder:"Search 300+ themes...",className:"settings-input",disabled:a})]}),o&&g.jsx("div",{style:{padding:"var(--space-component-sm)",background:"var(--color-error-bg)",color:"var(--color-error-light)",borderRadius:"var(--radius-md)",marginBottom:"var(--space-component-md)",fontSize:"var(--font-size-caption)"},children:o}),a&&g.jsx("div",{style:{padding:"var(--space-component-md)",textAlign:"center",color:"var(--color-text-secondary)"},children:"Loading themes..."}),!a&&g.jsxs(g.Fragment,{children:[g.jsxs("div",{className:"settings-field",children:[g.jsx("label",{className:"settings-label",children:"Current Theme"}),g.jsxs("div",{style:{padding:"var(--space-component-sm)",background:"var(--color-bg-elevated)",borderRadius:"var(--radius-md)",border:"var(--border-default)",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[g.jsx("span",{style:{color:"var(--color-text-primary)"},children:p==="default"?"Default (Flock Flow)":p}),p!=="default"&&g.jsx("button",{onClick:S,style:{padding:"4px 8px",background:"transparent",border:"var(--border-default)",borderRadius:"var(--radius-sm)",color:"var(--color-text-secondary)",fontSize:"var(--font-size-caption)",cursor:"pointer"},children:"Reset"})]})]}),E.length>0&&g.jsxs("div",{className:"settings-field",children:[g.jsx("label",{className:"settings-label",children:"Built-in Theme"}),g.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"var(--gap-xs)"},children:g.jsx("button",{onClick:()=>b("default"),onMouseEnter:()=>_("default"),style:{padding:"var(--space-component-sm)",background:p==="default"?"var(--color-primary-500)":"var(--color-bg-elevated)",border:"var(--border-default)",borderRadius:"var(--radius-md)",color:p==="default"?"white":"var(--color-text-primary)",fontSize:"var(--font-size-body-sm)",cursor:"pointer",textAlign:"left",transition:"var(--transition-all)"},children:"Default (Flock Flow)"})})]}),T.length>0&&g.jsxs("div",{className:"settings-field",children:[g.jsx("label",{className:"settings-label",children:"Popular Themes"}),g.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"var(--gap-xs)"},children:T.map(R=>g.jsx("button",{onClick:()=>b(R),onMouseEnter:()=>_(R),style:{padding:"var(--space-component-sm)",background:p===R?"var(--color-primary-500)":"var(--color-bg-elevated)",border:"var(--border-default)",borderRadius:"var(--radius-md)",color:p===R?"white":"var(--color-text-primary)",fontSize:"var(--font-size-body-sm)",cursor:"pointer",textAlign:"left",transition:"var(--transition-all)"},children:R},R))})]}),N.length>0&&g.jsxs("div",{className:"settings-field",children:[g.jsxs("label",{className:"settings-label",children:["All Themes (",N.length,")"]}),g.jsx("div",{style:{maxHeight:"300px",overflowY:"auto",display:"flex",flexDirection:"column",gap:"var(--gap-xs)",padding:"var(--space-component-xs)",background:"var(--color-bg-base)",borderRadius:"var(--radius-md)"},children:N.map(R=>g.jsx("button",{onClick:()=>b(R),onMouseEnter:()=>_(R),style:{padding:"var(--space-component-sm)",background:p===R?"var(--color-primary-500)":"var(--color-bg-elevated)",border:"var(--border-default)",borderRadius:"var(--radius-sm)",color:p===R?"white":"var(--color-text-primary)",fontSize:"var(--font-size-body-sm)",cursor:"pointer",textAlign:"left",transition:"var(--transition-all)"},children:R},R))})]}),C.length===0&&!a&&g.jsxs("div",{style:{padding:"var(--space-component-md)",textAlign:"center",color:"var(--color-text-tertiary)"},children:['No themes found matching "',c,'"']})]}),f&&g.jsxs("div",{style:{padding:"var(--space-component-sm)",background:"var(--color-bg-overlay)",borderRadius:"var(--radius-md)",marginTop:"var(--space-component-md)",fontSize:"var(--font-size-caption)",color:"var(--color-text-tertiary)",textAlign:"center"},children:["Previewing: ",f.name," (click to apply)"]})]})},xV=()=>{const e=_e(m=>m.appearance.agentIdleColor),n=_e(m=>m.appearance.agentActiveColor),a=_e(m=>m.appearance.agentErrorColor),i=_e(m=>m.appearance.nodeShadow),o=_e(m=>m.appearance.showStatusPulse),l=_e(m=>m.appearance.compactNodeView),c=_e(m=>m.setAgentIdleColor),d=_e(m=>m.setAgentActiveColor),f=_e(m=>m.setAgentErrorColor),h=_e(m=>m.setNodeShadow),p=_e(m=>m.setShowStatusPulse),v=_e(m=>m.setCompactNodeView);return g.jsxs("div",{children:[g.jsxs("div",{className:"settings-section",children:[g.jsx("h3",{className:"settings-section-title",children:"Theme"}),g.jsx("p",{className:"settings-description",style:{marginBottom:"var(--space-component-md)"},children:"Choose from 300+ terminal color themes. Themes are loaded from the backend and applied in real-time."}),g.jsx(bV,{})]}),g.jsxs("div",{className:"settings-section",children:[g.jsx("h3",{className:"settings-section-title",children:"Agent Colors"}),g.jsxs("div",{className:"settings-field",children:[g.jsx("label",{htmlFor:"idle-color",className:"settings-label",children:"Idle Agent Color"}),g.jsx("p",{className:"settings-description",children:"Border and indicator color for idle agents"}),g.jsxs("div",{style:{display:"flex",gap:"var(--gap-sm)",alignItems:"center"},children:[g.jsx("input",{id:"idle-color",type:"color",value:e,onChange:m=>c(m.target.value),style:{width:"60px",height:"36px",cursor:"pointer"}}),g.jsx("input",{type:"text",value:e,onChange:m=>c(m.target.value),className:"settings-input",placeholder:"#60a5fa"})]})]}),g.jsxs("div",{className:"settings-field",children:[g.jsx("label",{htmlFor:"active-color",className:"settings-label",children:"Active Agent Color"}),g.jsx("p",{className:"settings-description",children:"Border and indicator color for running agents (thick border)"}),g.jsxs("div",{style:{display:"flex",gap:"var(--gap-sm)",alignItems:"center"},children:[g.jsx("input",{id:"active-color",type:"color",value:n,onChange:m=>d(m.target.value),style:{width:"60px",height:"36px",cursor:"pointer"}}),g.jsx("input",{type:"text",value:n,onChange:m=>d(m.target.value),className:"settings-input",placeholder:"#10b981"})]})]}),g.jsxs("div",{className:"settings-field",children:[g.jsx("label",{htmlFor:"error-color",className:"settings-label",children:"Error Agent Color"}),g.jsx("p",{className:"settings-description",children:"Border and indicator color for agents in error state"}),g.jsxs("div",{style:{display:"flex",gap:"var(--gap-sm)",alignItems:"center"},children:[g.jsx("input",{id:"error-color",type:"color",value:a,onChange:m=>f(m.target.value),style:{width:"60px",height:"36px",cursor:"pointer"}}),g.jsx("input",{type:"text",value:a,onChange:m=>f(m.target.value),className:"settings-input",placeholder:"#ef4444"})]})]})]}),g.jsxs("div",{className:"settings-section",children:[g.jsx("h3",{className:"settings-section-title",children:"Node Appearance"}),g.jsxs("div",{className:"settings-field",children:[g.jsx("label",{htmlFor:"node-shadow",className:"settings-label",children:"Node Shadow"}),g.jsx("p",{className:"settings-description",children:"Shadow intensity for node elevation effect"}),g.jsxs("select",{id:"node-shadow",value:i,onChange:m=>h(m.target.value),className:"settings-select",children:[g.jsx("option",{value:"none",children:"None"}),g.jsx("option",{value:"small",children:"Small"}),g.jsx("option",{value:"medium",children:"Medium (Default)"}),g.jsx("option",{value:"large",children:"Large"})]})]}),g.jsxs("div",{className:"settings-field",children:[g.jsxs("div",{className:"settings-checkbox-wrapper",children:[g.jsx("input",{id:"status-pulse",type:"checkbox",checked:o,onChange:m=>p(m.target.checked),className:"settings-checkbox"}),g.jsx("label",{htmlFor:"status-pulse",className:"settings-checkbox-label",children:"Show status pulse animation"})]}),g.jsx("p",{className:"settings-description",children:"Animate status indicator for running agents"})]}),g.jsxs("div",{className:"settings-field",children:[g.jsxs("div",{className:"settings-checkbox-wrapper",children:[g.jsx("input",{id:"compact-view",type:"checkbox",checked:l,onChange:m=>v(m.target.checked),className:"settings-checkbox"}),g.jsx("label",{htmlFor:"compact-view",className:"settings-checkbox-label",children:"Compact node view"})]}),g.jsx("p",{className:"settings-description",children:"Reduce node size and spacing (useful for large graphs)"})]})]})]})},_V=()=>{const e=_e(b=>b.advanced.layoutDirection),n=_e(b=>b.advanced.nodeSpacing),a=_e(b=>b.advanced.rankSpacing),i=_e(b=>b.advanced.debugMode),o=_e(b=>b.advanced.performanceMode),l=_e(b=>b.setLayoutDirection),c=_e(b=>b.setNodeSpacing),d=_e(b=>b.setRankSpacing),f=_e(b=>b.setDebugMode),h=_e(b=>b.setPerformanceMode),[p,v]=q.useState("Loading..."),m="0.1.1";return q.useEffect(()=>{(async()=>{try{const _=await fetch("/api/version");if(_.ok){const S=await _.json();v(S.backend_version||"Unknown")}else v("Error fetching version")}catch(_){console.error("Failed to fetch version:",_),v("Error fetching version")}})()},[]),g.jsxs("div",{children:[g.jsxs("div",{className:"settings-section",children:[g.jsx("h3",{className:"settings-section-title",children:"Graph Layout"}),g.jsxs("div",{className:"settings-field",children:[g.jsx("label",{htmlFor:"layout-direction",className:"settings-label",children:"Layout Direction"}),g.jsx("p",{className:"settings-description",children:"Direction for manual layout algorithm (right-click → Auto Layout)"}),g.jsxs("select",{id:"layout-direction",value:e,onChange:b=>l(b.target.value),className:"settings-select",children:[g.jsx("option",{value:"LR",children:"Left to Right (Default)"}),g.jsx("option",{value:"TB",children:"Top to Bottom"})]})]}),g.jsxs("div",{className:"settings-field",children:[g.jsxs("label",{htmlFor:"node-spacing",className:"settings-label",children:["Node Spacing: ",n,"px"]}),g.jsx("p",{className:"settings-description",children:"Horizontal space between nodes when using manual layout (affects edge label visibility)"}),g.jsx("input",{id:"node-spacing",type:"range",min:"25",max:"150",step:"5",value:n,onChange:b=>c(parseFloat(b.target.value)),className:"settings-input"})]}),g.jsxs("div",{className:"settings-field",children:[g.jsxs("label",{htmlFor:"rank-spacing",className:"settings-label",children:["Rank Spacing: ",a,"px"]}),g.jsx("p",{className:"settings-description",children:"Vertical space between graph layers when using manual layout"}),g.jsx("input",{id:"rank-spacing",type:"range",min:"50",max:"300",step:"10",value:a,onChange:b=>d(parseFloat(b.target.value)),className:"settings-input"})]})]}),g.jsxs("div",{className:"settings-section",children:[g.jsx("h3",{className:"settings-section-title",children:"Developer Options"}),g.jsxs("div",{className:"settings-field",children:[g.jsxs("div",{className:"settings-checkbox-wrapper",children:[g.jsx("input",{id:"debug-mode",type:"checkbox",checked:i,onChange:b=>f(b.target.checked),className:"settings-checkbox"}),g.jsx("label",{htmlFor:"debug-mode",className:"settings-checkbox-label",children:"Debug mode"})]}),g.jsx("p",{className:"settings-description",children:"Show node IDs, detailed message counts, and verbose console logging"})]}),g.jsxs("div",{className:"settings-field",children:[g.jsxs("div",{className:"settings-checkbox-wrapper",children:[g.jsx("input",{id:"performance-mode",type:"checkbox",checked:o,onChange:b=>h(b.target.checked),className:"settings-checkbox"}),g.jsx("label",{htmlFor:"performance-mode",className:"settings-checkbox-label",children:"Performance mode"})]}),g.jsx("p",{className:"settings-description",children:"Disable animations, shadows, and blur effects for better performance"})]})]}),g.jsxs("div",{className:"settings-section",children:[g.jsx("h3",{className:"settings-section-title",children:"Information"}),g.jsxs("div",{className:"settings-field",children:[g.jsxs("p",{className:"settings-description",style:{marginBottom:"var(--spacing-2)"},children:[g.jsx("strong",{children:"Dashboard Version:"})," ",m]}),g.jsxs("p",{className:"settings-description",style:{marginBottom:"var(--spacing-2)"},children:[g.jsx("strong",{children:"Backend Version:"})," ",p]}),g.jsxs("p",{className:"settings-description",style:{marginBottom:"var(--spacing-2)"},children:[g.jsx("strong",{children:"React Flow Version:"})," 12.8.6"]}),g.jsxs("p",{className:"settings-description",children:[g.jsx("strong",{children:"Local Storage Used:"})," ",localStorage.length," keys"]})]})]})]})},SV=()=>{const e="mgljr9wlkbscmlh",n="2025-10-11T00:38:22.437Z",a=new Date(n).toLocaleString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"});return g.jsxs("div",{style:{fontSize:"10px",color:"var(--color-text-tertiary, #6b7280)",fontFamily:"monospace",lineHeight:"1.4",opacity:.7},children:[g.jsxs("div",{children:["Build: ",e]}),g.jsx("div",{children:a})]})},wV=()=>{const[e,n]=q.useState("graph"),a=_e(c=>c.setShowSettings),i=_e(c=>c.resetToDefaults),o=()=>{a(!1)},l=()=>{confirm("Reset all settings to defaults? This cannot be undone.")&&i()};return g.jsx("div",{className:"settings-panel",children:g.jsxs("div",{className:"settings-panel-inner",children:[g.jsxs("div",{className:"settings-header",children:[g.jsx("h2",{className:"settings-title",children:"Settings"}),g.jsx("button",{onClick:o,className:"settings-close-button","aria-label":"Close settings",title:"Close settings (Esc)",children:g.jsx("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:g.jsx("path",{d:"M15 5L5 15M5 5l10 10",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]}),g.jsxs("div",{className:"settings-tabs",children:[g.jsxs("button",{onClick:()=>n("graph"),className:`settings-tab ${e==="graph"?"active":""}`,children:[g.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:[g.jsx("circle",{cx:"4",cy:"8",r:"2",stroke:"currentColor",strokeWidth:"1.5"}),g.jsx("circle",{cx:"12",cy:"4",r:"2",stroke:"currentColor",strokeWidth:"1.5"}),g.jsx("circle",{cx:"12",cy:"12",r:"2",stroke:"currentColor",strokeWidth:"1.5"}),g.jsx("path",{d:"M6 8h4M10 5l2 6",stroke:"currentColor",strokeWidth:"1.5"})]}),"Graph"]}),g.jsxs("button",{onClick:()=>n("appearance"),className:`settings-tab ${e==="appearance"?"active":""}`,children:[g.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:g.jsx("path",{d:"M8 2v12M2 8h12M4.343 4.343l7.314 7.314M11.657 4.343L4.343 11.657",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})}),"Appearance"]}),g.jsxs("button",{onClick:()=>n("advanced"),className:`settings-tab ${e==="advanced"?"active":""}`,children:[g.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:[g.jsx("path",{d:"M8 10.667a2.667 2.667 0 100-5.334 2.667 2.667 0 000 5.334z",stroke:"currentColor",strokeWidth:"1.5"}),g.jsx("path",{d:"M13 8a5 5 0 01-5 5m0-10a5 5 0 015 5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})]}),"Advanced"]})]}),g.jsxs("div",{className:"settings-content",children:[e==="graph"&&g.jsx(mV,{}),e==="appearance"&&g.jsx(xV,{}),e==="advanced"&&g.jsx(_V,{})]}),g.jsxs("div",{className:"settings-footer",children:[g.jsx("div",{className:"settings-footer-left",children:g.jsx(SV,{})}),g.jsx("button",{onClick:l,className:"settings-reset-button",children:"Reset to Defaults"})]})]})})},Ba=typeof navigator<"u"&&navigator.platform.toUpperCase().indexOf("MAC")>=0,EV=[{keys:Ba?["⌘","M"]:["Ctrl","M"],description:"Toggle Agent/Blackboard View",category:"Navigation"},{keys:Ba?["⌘","F"]:["Ctrl","F"],description:"Focus filter input",category:"Navigation"},{keys:Ba?["⌘","Shift","P"]:["Ctrl","Shift","P"],description:"Toggle Publish Panel",category:"Panels"},{keys:Ba?["⌘","Shift","D"]:["Ctrl","Shift","D"],description:"Toggle Agent Details",category:"Panels"},{keys:Ba?["⌘","Shift","F"]:["Ctrl","Shift","F"],description:"Toggle Filters Panel",category:"Panels"},{keys:Ba?["⌘",","]:["Ctrl",","],description:"Toggle Settings Panel",category:"Panels"},{keys:["Esc"],description:"Close panels and windows",category:"General"},{keys:Ba?["⌘","/"]:["Ctrl","/"],description:"Show this help dialog",category:"General"}],CV=({isOpen:e,onClose:n})=>{if(q.useEffect(()=>{if(!e)return;const i=o=>{o.key==="Escape"&&(o.preventDefault(),o.stopPropagation(),n())};return window.addEventListener("keydown",i,{capture:!0}),()=>{window.removeEventListener("keydown",i,{capture:!0})}},[e,n]),!e)return null;const a=EV.reduce((i,o)=>(i[o.category]||(i[o.category]=[]),i[o.category].push(o),i),{});return g.jsx("div",{className:"keyboard-shortcuts-overlay",onClick:n,children:g.jsxs("div",{className:"keyboard-shortcuts-dialog",onClick:i=>i.stopPropagation(),children:[g.jsxs("div",{className:"keyboard-shortcuts-header",children:[g.jsx("h2",{className:"keyboard-shortcuts-title",children:"Keyboard Shortcuts"}),g.jsx("button",{className:"keyboard-shortcuts-close",onClick:n,"aria-label":"Close keyboard shortcuts",children:g.jsx("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:g.jsx("path",{d:"M15 5L5 15M5 5l10 10",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]}),g.jsx("div",{className:"keyboard-shortcuts-content",children:Object.entries(a).map(([i,o])=>g.jsxs("div",{className:"keyboard-shortcuts-category",children:[g.jsx("h3",{className:"keyboard-shortcuts-category-title",children:i}),g.jsx("div",{className:"keyboard-shortcuts-list",children:o.map((l,c)=>g.jsxs("div",{className:"keyboard-shortcut-item",children:[g.jsx("div",{className:"keyboard-shortcut-keys",children:l.keys.map((d,f)=>g.jsxs(Kn.Fragment,{children:[g.jsx("kbd",{className:"keyboard-key",children:d}),f<l.keys.length-1&&g.jsx("span",{className:"keyboard-key-separator",children:"+"})]},f))}),g.jsx("div",{className:"keyboard-shortcut-description",children:l.description})]},c))})]},i))}),g.jsx("div",{className:"keyboard-shortcuts-footer",children:g.jsxs("p",{className:"keyboard-shortcuts-hint",children:["Press ",g.jsx("kbd",{className:"keyboard-key",children:"Esc"})," or click outside to close"]})})]})})},TV=()=>{const e=jr(c=>c.instances),n=jr(c=>c.addModule),a=q.useRef(new Map),i=q.useRef({});q.useEffect(()=>{(async()=>{try{const d=await Cn.getAllModuleInstances();d.forEach(f=>{const h={id:f.instance_id,type:f.type,position:f.position,size:f.size,visible:f.visible};n(h)}),console.log(`[ModulePersistence] Restored ${d.length} module instances`)}catch(d){console.error("[ModulePersistence] Failed to load module instances:",d)}})()},[]);const o=q.useCallback(async c=>{i.current[c.id]&&clearTimeout(i.current[c.id]),i.current[c.id]=setTimeout(async()=>{try{const d=new Date().toISOString(),f={instance_id:c.id,type:c.type,position:c.position,size:c.size,visible:c.visible,created_at:d,updated_at:d};await Cn.saveModuleInstance(f),console.log(`[ModulePersistence] Saved instance: ${c.id}`)}catch(d){console.error(`[ModulePersistence] Failed to save instance ${c.id}:`,d)}delete i.current[c.id]},300)},[]),l=q.useCallback(async c=>{i.current[c]&&(clearTimeout(i.current[c]),delete i.current[c]);try{await Cn.deleteModuleInstance(c),console.log(`[ModulePersistence] Deleted instance: ${c}`)}catch(d){console.error(`[ModulePersistence] Failed to delete instance ${c}:`,d)}},[]);q.useEffect(()=>{const c=new Set(e.keys()),d=new Set(a.current.keys());c.forEach(f=>{if(!d.has(f)){const h=e.get(f);h&&(console.log(`[ModulePersistence] Detected new instance: ${f}`),o(h))}}),e.forEach((f,h)=>{const p=a.current.get(h);if(p){const v=p.position.x!==f.position.x||p.position.y!==f.position.y,m=p.size.width!==f.size.width||p.size.height!==f.size.height,b=p.visible!==f.visible;(v||m||b)&&(console.log(`[ModulePersistence] Detected update to instance: ${h}`),o(f))}}),d.forEach(f=>{c.has(f)||(console.log(`[ModulePersistence] Detected removed instance: ${f}`),l(f))}),a.current=new Map(e)},[e,o,l]),q.useEffect(()=>()=>{Object.values(i.current).forEach(clearTimeout)},[])},oz=(e={})=>{q.useEffect(()=>{const n=a=>{const i=a.ctrlKey||a.metaKey;if(i&&a.key===","){a.preventDefault();const o=_e.getState().ui.showSettings;_e.getState().setShowSettings(!o);return}if(i&&a.shiftKey&&a.key==="F"){a.preventDefault();const o=_e.getState().ui.showFilters;_e.getState().setShowFilters(!o);return}if(i&&a.shiftKey&&a.key==="P"){a.preventDefault();const o=_e.getState().ui.showControls;_e.getState().setShowControls(!o);return}if(i&&a.shiftKey&&a.key==="D"){a.preventDefault(),e.onToggleAgentDetails&&e.onToggleAgentDetails();return}if(i&&a.key==="/"){a.preventDefault(),e.onToggleHelp&&e.onToggleHelp();return}if(i&&a.key==="m"){if(a.preventDefault(),e.onToggleMode)e.onToggleMode();else{const o=ut.getState().mode;ut.getState().setMode(o==="agent"?"blackboard":"agent")}return}if(i&&a.key==="f"){const o=document.activeElement;if(!(o?.tagName==="INPUT"||o?.tagName==="TEXTAREA"))if(a.preventDefault(),e.onFocusFilter)e.onFocusFilter();else{const c=document.querySelector('input[placeholder*="correlation"], input[placeholder*="Correlation"]');c&&(c.focus(),c.select())}return}if(a.key==="Escape"){if(e.onCloseWindows)e.onCloseWindows();else{const{showSettings:o,showFilters:l,showControls:c}=_e.getState().ui,d=ut.getState().detailWindows;o?(a.preventDefault(),_e.getState().setShowSettings(!1)):c?(a.preventDefault(),_e.getState().setShowControls(!1)):l?(a.preventDefault(),_e.getState().setShowFilters(!1)):d.size>0&&(a.preventDefault(),d.clear(),ut.setState({detailWindows:new Map}))}return}};return window.addEventListener("keydown",n),()=>{window.removeEventListener("keydown",n)}},[e])},jV="_connectionBadge_kl6ey_1",NV="_hasError_kl6ey_27",RV="_connected_kl6ey_37",MV="_connecting_kl6ey_49",AV="_reconnecting_kl6ey_51",zV="_disconnected_kl6ey_63",DV="_statusIndicator_kl6ey_77",kV="_statusPulse_kl6ey_1",OV="_statusText_kl6ey_121",$i={connectionBadge:jV,hasError:NV,connected:RV,connecting:MV,reconnecting:AV,disconnected:zV,statusIndicator:DV,statusPulse:kV,statusText:OV},qV=({status:e,attempts:n,error:a})=>{const i={connected:"Connected",connecting:"Connecting...",reconnecting:`Reconnecting (${n})...`,disconnected:"Disconnected"},o=[$i.connectionBadge,$i[e],a?$i.hasError:""].filter(Boolean).join(" "),l=[$i.statusIndicator,$i[e]].join(" ");return g.jsxs("div",{className:o,title:a||void 0,role:"status","aria-live":"polite","aria-label":`WebSocket connection status: ${i[e]}`,children:[g.jsx("div",{className:l,"aria-hidden":"true"}),g.jsx("span",{className:$i.statusText,children:i[e]})]})},BV=()=>{const e=at(i=>i.status),n=at(i=>i.reconnectAttempts),a=at(i=>i.lastError);return g.jsx(qV,{status:e,attempts:n,error:a})},LV=()=>{const e=ut(_=>_.mode),n=ut(_=>_.setMode),a=jr(_=>_.instances),i=ut(_=>_.detailWindows),o=_e(_=>_.ui.showFilters),l=_e(_=>_.ui.showControls),c=_e(_=>_.ui.showSettings),d=_e(_=>_.setShowFilters),f=_e(_=>_.setShowControls),h=_e(_=>_.setShowSettings),[p,v]=q.useState(!1);TV();const m=()=>{const _=ut.getState().detailWindows,S=Me.getState().agents;_.size>0?_.forEach((w,C)=>{ut.getState().closeDetailWindow(C)}):S.forEach(w=>{ut.getState().openDetailWindow(w.id)})};oz({onToggleHelp:()=>v(_=>!_),onToggleAgentDetails:m});const b=()=>{confirm("Clear all dashboard data? This will remove all agents, messages, and session data.")&&(Me.setState({agents:new Map,messages:new Map,events:[],runs:new Map,nodes:[],edges:[]}),ut.setState({mode:"agent"}),Te.setState({correlationId:void 0,timeRange:void 0}),jr.getState().instances.clear(),indexedDB.databases().then(_=>{_.forEach(S=>{S.name&&indexedDB.deleteDatabase(S.name)})}),localStorage.clear(),window.location.reload())};return g.jsxs("div",{className:"dashboard-layout",children:[g.jsxs("header",{className:"dashboard-header",children:[g.jsx("h1",{className:"dashboard-title",children:"🦆🐓 Flock 🐤🐧"}),g.jsxs("div",{className:"view-toggle-container",children:[g.jsx("span",{className:"view-toggle-label",children:"View:"}),g.jsxs("div",{className:"view-toggle-group",children:[g.jsx("button",{type:"button",onClick:()=>n("agent"),className:`view-toggle-button ${e==="agent"?"active":""}`,children:"Agent View"}),g.jsx("button",{type:"button",onClick:()=>n("blackboard"),className:`view-toggle-button ${e==="blackboard"?"active":""}`,children:"Blackboard View"})]})]}),g.jsxs("div",{className:"dashboard-actions",children:[g.jsxs("button",{type:"button",onClick:()=>f(!l),className:`controls-toggle primary ${l?"active":""}`,title:"Publish artifacts to the blackboard (Ctrl+Shift+P)","aria-pressed":l?"true":"false","aria-label":l?"Publish panel open":"Publish panel closed",children:[g.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:g.jsx("path",{d:"M8 2.667v10.666M2.667 8h10.666",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),g.jsx("span",{children:"Publish"})]}),g.jsxs("button",{type:"button",onClick:m,className:`controls-toggle ${i.size>0?"active":""}`,title:`${i.size>0?"Close":"Show"} agent detail windows (Ctrl+Shift+D)`,"aria-pressed":i.size>0?"true":"false","aria-label":i.size>0?"Agent details shown":"Agent details hidden",children:[g.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:g.jsx("path",{d:"M2 4.667h12M2 8h12M2 11.333h12",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),g.jsx("span",{children:"Agent Details"})]}),g.jsxs("button",{type:"button",onClick:()=>h(!c),className:`controls-toggle ${c?"active":""}`,title:`${c?"Hide":"Show"} settings panel (Ctrl+,)`,"aria-pressed":c?"true":"false","aria-label":c?"Settings shown":"Settings hidden",children:[g.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:[g.jsx("path",{d:"M8 10a2 2 0 100-4 2 2 0 000 4z",stroke:"currentColor",strokeWidth:"1.5"}),g.jsx("path",{d:"M13.333 8c0-.367-.2-.7-.533-.867l-.933-.467a.933.933 0 01-.467-.8v-.133c0-.334.133-.6.467-.8l.933-.467c.333-.166.533-.5.533-.866 0-.367-.2-.7-.533-.867L11.867 2.4a.933.933 0 01-.467-.8V1.333c0-.366-.233-.666-.6-.666H9.2c-.366 0-.666.3-.666.666V1.6c0 .334-.267.634-.6.8l-.934.467c-.333.166-.7.166-1 0l-.933-.467a.933.933 0 00-.8 0L2.533 3.067c-.333.166-.533.5-.533.866 0 .367.2.7.533.867l.933.467c.334.2.467.466.467.8v.133c0 .334-.133.6-.467.8l-.933.467c-.333.166-.533.5-.533.866 0 .367.2.7.533.867l.934.533c.333.2.6.5.6.8v.267c0 .366.3.666.666.666h1.6c.367 0 .667-.3.667-.666v-.267c0-.3.267-.6.6-.8l.933-.533c.334-.167.7-.167 1 0l.934.533c.333.2.6.5.6.8v.267c0 .366.3.666.666.666H9.2c.367 0 .667-.3.667-.666v-.267c0-.3.266-.6.6-.8l.933-.533c.333-.167.533-.5.533-.867z",stroke:"currentColor",strokeWidth:"1.5"})]}),g.jsx("span",{children:"Settings"})]}),g.jsx("button",{type:"button",onClick:()=>v(!0),className:"icon-button help-button",title:"Keyboard shortcuts (Ctrl+/)","aria-label":"Show keyboard shortcuts",children:g.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:[g.jsx("circle",{cx:"8",cy:"8",r:"6.5",stroke:"currentColor",strokeWidth:"1.5"}),g.jsx("path",{d:"M8 11.5v-.5M8 8.5v-2a1.5 1.5 0 10-1.5-1.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"}),g.jsx("circle",{cx:"8",cy:"11.5",r:"0.5",fill:"currentColor"})]})}),g.jsx("button",{type:"button",onClick:b,className:"icon-button clear-button",title:"Clear all dashboard data","aria-label":"Clear all dashboard data",children:g.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:g.jsx("path",{d:"M2 4h12M5.333 4V2.667a1.333 1.333 0 011.334-1.334h2.666a1.333 1.333 0 011.334 1.334V4m2 0v9.333a1.333 1.333 0 01-1.334 1.334H4.667a1.333 1.333 0 01-1.334-1.334V4h9.334z",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),g.jsx(BV,{})]})]}),g.jsx("div",{className:"filter-pills-bar",children:g.jsx(uV,{})}),o&&g.jsx(XU,{onClose:()=>d(!1)}),g.jsx("div",{className:"dashboard-main",children:g.jsx("main",{className:"graph-container",children:g.jsx(SR,{children:g.jsx(N7,{})})})}),g.jsx(oU,{}),Array.from(a.values()).map(_=>g.jsx(az,{instanceId:_.id},_.id)),l&&g.jsx(gV,{}),c&&g.jsx(wV,{}),g.jsx(CV,{isOpen:p,onClose:()=>v(!1)})]})},HV="_container_z8335_5",IV="_content_z8335_23",UV="_icon_z8335_43",VV="_title_z8335_55",FV="_description_z8335_71",PV="_actions_z8335_175",GV="_primaryButton_z8335_187",$V="_secondaryButton_z8335_245",da={container:HV,content:IV,icon:UV,title:VV,description:FV,actions:PV,primaryButton:GV,secondaryButton:$V};class YV extends q.Component{constructor(n){super(n),this.state={hasError:!1,error:null,errorInfo:null}}static getDerivedStateFromError(n){return{hasError:!0,error:n}}componentDidCatch(n,a){console.error("ErrorBoundary caught an error:",n,a),this.setState({errorInfo:a})}handleReset=()=>{this.setState({hasError:!1,error:null,errorInfo:null})};handleReload=()=>{window.location.reload()};render(){return this.state.hasError?this.props.fallback?this.props.fallback:g.jsx("div",{className:da.container,role:"alert",children:g.jsxs("div",{className:da.content,children:[g.jsx("div",{className:da.icon,children:g.jsxs("svg",{width:"64",height:"64",viewBox:"0 0 64 64",fill:"none",children:[g.jsx("circle",{cx:"32",cy:"32",r:"28",stroke:"currentColor",strokeWidth:"2",fill:"none"}),g.jsx("path",{d:"M32 20v16M32 44v.5",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round"})]})}),g.jsx("h2",{className:da.title,children:"Something went wrong"}),g.jsx("p",{className:da.description,children:"An unexpected error occurred. You can try resetting the component or reloading the page."}),this.state.error&&!1,g.jsxs("div",{className:da.actions,children:[g.jsx("button",{className:da.primaryButton,onClick:this.handleReset,children:"Try Again"}),g.jsx("button",{className:da.secondaryButton,onClick:this.handleReload,children:"Reload Page"})]})]})}):this.props.children}}function WV(e,n,a){performance.mark(a);const i=performance.measure(`${e}-render`,n,a);return console.log(`[Performance] ${e} render time: ${i.duration.toFixed(2)}ms`),i.duration}const sz=({value:e,maxStringLength:n=200})=>{const[a,i]=q.useState(2);try{const o=JSON.parse(e);return typeof o=="string"||typeof o=="number"||typeof o=="boolean"||o===null?g.jsx("div",{style:{fontFamily:"var(--font-family-mono)",fontSize:"var(--font-size-body-xs)",color:"var(--color-text-secondary)",wordBreak:"break-word"},children:String(o)}):g.jsxs("div",{children:[g.jsxs("div",{style:{display:"flex",gap:"var(--gap-xs)",marginBottom:"var(--gap-xs)"},children:[g.jsx("button",{onClick:()=>i(!1),style:{padding:"2px 8px",fontSize:"var(--font-size-body-xs)",color:"var(--color-text-secondary)",backgroundColor:"var(--color-bg-elevated)",border:"1px solid var(--color-border-subtle)",borderRadius:"var(--radius-xs)",cursor:"pointer",fontFamily:"var(--font-family-mono)"},onMouseEnter:l=>{l.currentTarget.style.backgroundColor="var(--color-bg-hover)"},onMouseLeave:l=>{l.currentTarget.style.backgroundColor="var(--color-bg-elevated)"},children:"Expand All"}),g.jsx("button",{onClick:()=>i(!0),style:{padding:"2px 8px",fontSize:"var(--font-size-body-xs)",color:"var(--color-text-secondary)",backgroundColor:"var(--color-bg-elevated)",border:"1px solid var(--color-border-subtle)",borderRadius:"var(--radius-xs)",cursor:"pointer",fontFamily:"var(--font-family-mono)"},onMouseEnter:l=>{l.currentTarget.style.backgroundColor="var(--color-bg-hover)"},onMouseLeave:l=>{l.currentTarget.style.backgroundColor="var(--color-bg-elevated)"},children:"Collapse All"})]}),g.jsx("div",{style:{maxHeight:"400px",overflowY:"auto",overflowX:"auto"},children:g.jsx(Ye,{value:o,collapsed:a,displayDataTypes:!1,shortenTextAfterLength:0,style:{backgroundColor:"var(--color-bg-elevated)",fontSize:"var(--font-size-body-xs)",fontFamily:"var(--font-family-mono)",padding:"var(--space-component-sm)",borderRadius:"var(--radius-sm)","--w-rjv-line-color":"var(--color-text-tertiary)","--w-rjv-key-string":"var(--color-primary-500)","--w-rjv-info-color":"var(--color-text-secondary)","--w-rjv-curlybraces-color":"var(--color-text-tertiary)","--w-rjv-brackets-color":"var(--color-text-tertiary)","--w-rjv-arrow-color":"var(--color-text-tertiary)","--w-rjv-edit-color":"var(--color-primary-500)","--w-rjv-add-color":"var(--color-success)","--w-rjv-del-color":"var(--color-error)","--w-rjv-update-color":"var(--color-warning)","--w-rjv-border-left-color":"var(--color-border-subtle)"}})})]})}catch{const l=e.length>n?e.substring(0,n)+"...":e;return g.jsx("div",{style:{fontFamily:"var(--font-family-mono)",fontSize:"var(--font-size-body-xs)",color:"var(--color-text-secondary)",wordBreak:"break-word",whiteSpace:"pre-wrap"},children:l})}},XV=()=>{const[e,n]=q.useState(!1),[a,i]=q.useState(!0),[o,l]=q.useState(!1),[c,d]=q.useState(30),[f,h]=q.useState([]),[p,v]=q.useState([]),[m,b]=q.useState([]),[_,S]=q.useState([]),[w,C]=q.useState(null),[T,E]=q.useState(!1),[N,R]=q.useState(null),[z,j]=q.useState(null);q.useEffect(()=>{A(),D(),I()},[]);const A=async()=>{try{const H=await fetch("/api/traces/services");if(!H.ok)throw new Error("Failed to load trace services");const O=await H.json();h(O.services),v(O.operations)}catch(H){console.error("Error loading trace services:",H)}},D=async()=>{try{const H=await fetch("/api/traces/stats");if(!H.ok)throw new Error("Failed to load trace stats");const O=await H.json();C(O)}catch(H){console.error("Error loading trace stats:",H)}},I=async()=>{n(!0),i(!0),l(!1),d(30),b(["flock","agent","dspyengine","outpututilitycomponent"]),S(["DashboardEventCollector.set_websocket_manager"])},P=async()=>{if(confirm("Clear all traces from the database? This cannot be undone.")){E(!0),R(null),j(null);try{const H=await fetch("/api/traces/clear",{method:"POST"});if(!H.ok)throw new Error("Failed to clear traces");const O=await H.json();O.success?(j(`Successfully deleted ${O.deleted_count} trace spans`),D()):R(O.error||"Failed to clear traces")}catch(H){R(H instanceof Error?H.message:"Unknown error")}finally{E(!1),setTimeout(()=>j(null),5e3)}}},V=async()=>{E(!0),R(null),j(null);try{j("Settings saved successfully (persistence coming soon)")}catch(H){R(H instanceof Error?H.message:"Failed to save settings")}finally{E(!1),setTimeout(()=>j(null),5e3)}},$=H=>H?new Date(H).toLocaleString():"N/A",L=H=>H<1?`${(H*1024).toFixed(1)} KB`:`${H.toFixed(2)} MB`;return g.jsxs("div",{children:[N&&g.jsx("div",{className:"settings-message settings-message-error",style:{padding:"var(--space-component-sm)",marginBottom:"var(--space-component-md)",backgroundColor:"rgba(239, 68, 68, 0.1)",border:"1px solid rgba(239, 68, 68, 0.3)",borderRadius:"var(--radius-md)",color:"#ef4444"},children:N}),z&&g.jsx("div",{className:"settings-message settings-message-success",style:{padding:"var(--space-component-sm)",marginBottom:"var(--space-component-md)",backgroundColor:"rgba(16, 185, 129, 0.1)",border:"1px solid rgba(16, 185, 129, 0.3)",borderRadius:"var(--radius-md)",color:"#10b981"},children:z}),g.jsxs("div",{className:"settings-section",children:[g.jsx("h3",{className:"settings-section-title",children:"OpenTelemetry Tracing"}),g.jsxs("div",{className:"settings-field",children:[g.jsxs("div",{className:"settings-checkbox-wrapper",children:[g.jsx("input",{id:"auto-trace",type:"checkbox",checked:e,onChange:H=>n(H.target.checked),className:"settings-checkbox"}),g.jsx("label",{htmlFor:"auto-trace",className:"settings-checkbox-label",children:"Enable auto-tracing (FLOCK_AUTO_TRACE)"})]}),g.jsx("p",{className:"settings-description",children:"Automatically trace all agent operations and system events with OpenTelemetry"})]}),g.jsxs("div",{className:"settings-field",children:[g.jsxs("div",{className:"settings-checkbox-wrapper",children:[g.jsx("input",{id:"trace-file",type:"checkbox",checked:a,onChange:H=>i(H.target.checked),className:"settings-checkbox",disabled:!e}),g.jsx("label",{htmlFor:"trace-file",className:"settings-checkbox-label",children:"Store traces in DuckDB (FLOCK_TRACE_FILE)"})]}),g.jsx("p",{className:"settings-description",children:"Save traces to .flock/traces.duckdb for analysis and debugging"})]}),g.jsxs("div",{className:"settings-field",children:[g.jsxs("div",{className:"settings-checkbox-wrapper",children:[g.jsx("input",{id:"auto-workflow",type:"checkbox",checked:o,onChange:H=>l(H.target.checked),className:"settings-checkbox",disabled:!e}),g.jsx("label",{htmlFor:"auto-workflow",className:"settings-checkbox-label",children:"Unified workflow tracing (FLOCK_AUTO_WORKFLOW_TRACE)"})]}),g.jsx("p",{className:"settings-description",children:"Automatically wrap operations in unified workflow traces (experimental)"})]}),g.jsxs("div",{className:"settings-field",children:[g.jsx("label",{htmlFor:"trace-ttl",className:"settings-label",children:"Trace Time-To-Live (FLOCK_TRACE_TTL_DAYS)"}),g.jsx("p",{className:"settings-description",children:"Auto-delete traces older than specified days (leave empty to keep forever)"}),g.jsx("input",{id:"trace-ttl",type:"number",min:"1",max:"365",value:c??"",onChange:H=>d(H.target.value?parseInt(H.target.value):null),className:"settings-input",placeholder:"30",disabled:!e})]})]}),g.jsxs("div",{className:"settings-section",children:[g.jsx("h3",{className:"settings-section-title",children:"Service Whitelist (FLOCK_TRACE_SERVICES)"}),g.jsx("p",{className:"settings-description",style:{marginBottom:"var(--space-component-md)"},children:"Only trace specific services. Leave empty to trace all services."}),g.jsx(so,{options:f,selected:m,onChange:b,placeholder:"Select services to trace...",disabled:!e})]}),g.jsxs("div",{className:"settings-section",children:[g.jsx("h3",{className:"settings-section-title",children:"Operation Blacklist (FLOCK_TRACE_IGNORE)"}),g.jsx("p",{className:"settings-description",style:{marginBottom:"var(--space-component-md)"},children:"Exclude specific operations from tracing (format: Service.method)"}),g.jsx(so,{options:p,selected:_,onChange:S,placeholder:"Select operations to ignore...",disabled:!e})]}),g.jsxs("div",{className:"settings-section",children:[g.jsx("h3",{className:"settings-section-title",children:"Trace Database Statistics"}),w&&g.jsx("div",{style:{backgroundColor:"rgba(96, 165, 250, 0.05)",border:"1px solid rgba(96, 165, 250, 0.2)",borderRadius:"var(--radius-md)",padding:"var(--space-component-md)"},children:g.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"var(--gap-md)"},children:[g.jsxs("div",{children:[g.jsx("div",{style:{fontSize:"var(--font-size-sm)",color:"var(--color-text-secondary)",marginBottom:"var(--space-xs)"},children:"Total Spans"}),g.jsx("div",{style:{fontSize:"var(--font-size-lg)",fontWeight:600},children:w.total_spans.toLocaleString()})]}),g.jsxs("div",{children:[g.jsx("div",{style:{fontSize:"var(--font-size-sm)",color:"var(--color-text-secondary)",marginBottom:"var(--space-xs)"},children:"Total Traces"}),g.jsx("div",{style:{fontSize:"var(--font-size-lg)",fontWeight:600},children:w.total_traces.toLocaleString()})]}),g.jsxs("div",{children:[g.jsx("div",{style:{fontSize:"var(--font-size-sm)",color:"var(--color-text-secondary)",marginBottom:"var(--space-xs)"},children:"Services Traced"}),g.jsx("div",{style:{fontSize:"var(--font-size-lg)",fontWeight:600},children:w.services_count})]}),g.jsxs("div",{children:[g.jsx("div",{style:{fontSize:"var(--font-size-sm)",color:"var(--color-text-secondary)",marginBottom:"var(--space-xs)"},children:"Database Size"}),g.jsx("div",{style:{fontSize:"var(--font-size-lg)",fontWeight:600},children:L(w.database_size_mb)})]}),g.jsxs("div",{children:[g.jsx("div",{style:{fontSize:"var(--font-size-sm)",color:"var(--color-text-secondary)",marginBottom:"var(--space-xs)"},children:"Oldest Trace"}),g.jsx("div",{style:{fontSize:"var(--font-size-xs)"},children:$(w.oldest_trace)})]}),g.jsxs("div",{children:[g.jsx("div",{style:{fontSize:"var(--font-size-sm)",color:"var(--color-text-secondary)",marginBottom:"var(--space-xs)"},children:"Newest Trace"}),g.jsx("div",{style:{fontSize:"var(--font-size-xs)"},children:$(w.newest_trace)})]})]})}),g.jsxs("div",{style:{marginTop:"var(--space-component-md)"},children:[g.jsx("button",{onClick:P,disabled:T||!w||w.total_spans===0,className:"settings-reset-button",style:{backgroundColor:"rgba(239, 68, 68, 0.1)",border:"1px solid rgba(239, 68, 68, 0.3)",color:"#ef4444"},children:T?"Clearing...":"Clear All Traces"}),g.jsx("p",{className:"settings-description",style:{marginTop:"var(--space-xs)"},children:"Delete all spans and run VACUUM to reclaim disk space"})]})]}),g.jsxs("div",{className:"settings-section",children:[g.jsx("button",{onClick:V,disabled:T,className:"settings-save-button",style:{backgroundColor:"rgba(96, 165, 250, 0.1)",border:"1px solid rgba(96, 165, 250, 0.3)",color:"#60a5fa",padding:"var(--space-component-sm) var(--space-component-md)",borderRadius:"var(--radius-md)",fontSize:"var(--font-size-base)",fontWeight:500,cursor:T?"not-allowed":"pointer",opacity:T?.6:1},children:T?"Saving...":"Save Tracing Settings"}),g.jsx("p",{className:"settings-description",style:{marginTop:"var(--space-xs)"},children:"Settings will be persisted to .env file (requires backend restart)"})]})]})},KV=()=>{const[e,n]=q.useState([]),[a,i]=q.useState(!0),[o,l]=q.useState(null),[c,d]=q.useState(new Set),[f,h]=q.useState(new Set),[p,v]=q.useState(new Set),[m,b]=q.useState(""),[_,S]=q.useState("timeline"),[w,C]=q.useState(null),[T,E]=q.useState(new Set),[N,R]=q.useState("SELECT * FROM spans LIMIT 10"),[z,j]=q.useState(null),[A,D]=q.useState([]),[I,P]=q.useState(!1),[V,$]=q.useState(null),[L,H]=q.useState("date"),[O,F]=q.useState("desc"),J=q.useRef(null),G=q.useRef(0),re=async()=>{P(!0),$(null);try{const W=await fetch("/api/traces/query",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:N})});if(!W.ok){const te=await W.json();throw new Error(te.error||"Query failed")}const se=await W.json();j(se.results),D(se.columns)}catch(W){$(W instanceof Error?W.message:"Unknown error"),j(null),D([])}finally{P(!1)}},B=q.useMemo(()=>{const W=["#3b82f6","#10b981","#f59e0b","#ef4444","#8b5cf6","#ec4899","#06b6d4","#f97316"],se=new Map,te=[],me=[];return e.forEach(ve=>{const Se=ve.name.split(".")[0]||ve.resource["service.name"]||"unknown";te.includes(Se)||te.push(Se);const Ee=ve.name.split(".")[0]||ve.name;Ee&&!me.includes(Ee)&&me.push(Ee)}),te.length===1?me.forEach((ve,Se)=>{const Ee=W[Se%W.length]||"#6366f1";se.set(ve,Ee)}):te.forEach((ve,Se)=>{const Ee=W[Se%W.length]||"#6366f1";se.set(ve,Ee)}),{colorMap:se,useSpanType:te.length===1}},[e]);q.useEffect(()=>{const W=async()=>{try{e.length===0&&i(!0);const te=await fetch("/api/traces");if(!te.ok)throw new Error(`HTTP ${te.status}: ${te.statusText}`);const me=await te.json();if(JSON.stringify(me)!==JSON.stringify(e)){const ve=J.current?.scrollTop||0;n(me),l(null),requestAnimationFrame(()=>{J.current&&me.length===G.current&&(J.current.scrollTop=ve)}),G.current=me.length}}catch(te){l(te instanceof Error?te.message:"Failed to load traces")}finally{i(!1)}};W();const se=setInterval(W,5e3);return()=>clearInterval(se)},[e]);const Y=q.useMemo(()=>{const W=new Map;return e.forEach(se=>{const te=se.context.trace_id;W.has(te)||W.set(te,[]),W.get(te).push(se)}),Array.from(W.entries()).map(([se,te])=>{const me=Math.min(...te.map(qe=>qe.start_time)),ve=Math.max(...te.map(qe=>qe.end_time)),Se=(ve-me)/1e6,Ee=te.some(qe=>qe.status.status_code==="ERROR"),Ve=new Set(te.map(qe=>qe.name.split(".")[0]||qe.resource["service.name"]||"unknown"));return{traceId:se,spans:te.sort((qe,lt)=>qe.start_time-lt.start_time),startTime:me,endTime:ve,duration:Se,spanCount:te.length,hasError:Ee,services:Ve}})},[e]),ae=q.useMemo(()=>{let W=Y;if(m){const se=m.toLowerCase();W=W.filter(te=>te.traceId.toLowerCase().includes(se)||te.spans.some(me=>me.name.toLowerCase().includes(se)||Object.values(me.attributes).some(ve=>typeof ve=="string"&&ve.toLowerCase().includes(se))))}return[...W].sort((se,te)=>{let me=0;switch(L){case"date":me=se.startTime-te.startTime;break;case"spans":me=se.spanCount-te.spanCount;break;case"duration":me=se.duration-te.duration;break}return O==="asc"?me:-me})},[Y,m,L,O]),U=q.useMemo(()=>{const W=new Map;return e.forEach(se=>{const te=se.name.split(".")[0]||"unknown";W.has(te)||W.set(te,{service:te,totalSpans:0,errorSpans:0,avgDuration:0,p95Duration:0,p99Duration:0,rate:0});const me=W.get(te);me.totalSpans++,se.status.status_code==="ERROR"&&me.errorSpans++}),W.forEach((se,te)=>{const me=e.filter(Se=>(Se.name.split(".")[0]||"unknown")===te),ve=me.map(Se=>(Se.end_time-Se.start_time)/1e6).sort((Se,Ee)=>Se-Ee);if(se.avgDuration=ve.reduce((Se,Ee)=>Se+Ee,0)/ve.length||0,se.p95Duration=ve[Math.floor(ve.length*.95)]||0,se.p99Duration=ve[Math.floor(ve.length*.99)]||0,me.length>1){const Se=(Math.max(...me.map(Ee=>Ee.end_time))-Math.min(...me.map(Ee=>Ee.start_time)))/1e9;se.rate=me.length/Math.max(Se,1)}}),Array.from(W.values()).sort((se,te)=>te.totalSpans-se.totalSpans)},[e]),Z=q.useMemo(()=>{const W=new Map;return Y.forEach(se=>{se.spans.forEach(te=>{if(te.parent_id){const me=se.spans.find(ve=>ve.context.span_id===te.parent_id);if(me){const ve=me.name.split(".")[0]||"unknown",Se=te.name.split(".")[0]||"unknown";if(ve!==Se){const Ee=`${ve}->${Se}`;W.has(Ee)||W.set(Ee,{from:ve,to:Se,operations:new Map});const Ve=W.get(Ee),qe=`${me.name} → ${te.name}`;Ve.operations.has(qe)||Ve.operations.set(qe,{operation:qe,service:Se,totalCalls:0,errorCalls:0,avgDuration:0,p95Duration:0});const lt=Ve.operations.get(qe);lt.totalCalls++,te.status.status_code==="ERROR"&&lt.errorCalls++}}}})}),W.forEach(se=>{se.operations.forEach((te,me)=>{const ve=me.split(" → ")[1],Ee=e.filter(Ve=>Ve.name===ve).map(Ve=>(Ve.end_time-Ve.start_time)/1e6).sort((Ve,qe)=>Ve-qe);te.avgDuration=Ee.reduce((Ve,qe)=>Ve+qe,0)/Ee.length||0,te.p95Duration=Ee[Math.floor(Ee.length*.95)]||0})}),Array.from(W.values())},[Y,e]),ne=W=>{const se=new Map,te=[];W.forEach(ve=>{se.set(ve.context.span_id,{...ve,children:[],depth:0})}),W.forEach(ve=>{const Se=se.get(ve.context.span_id);if(ve.parent_id&&se.has(ve.parent_id)){const Ee=se.get(ve.parent_id);Ee.children.push(Se),Se.depth=Ee.depth+1}else te.push(Se)});const me=ve=>{ve.children.sort((Se,Ee)=>Se.start_time-Ee.start_time),ve.children.forEach(me)};return te.forEach(me),te},le=W=>{h(se=>{const te=new Set(se);return te.has(W)?te.delete(W):te.add(W),te})},K=W=>{v(se=>{const te=new Set(se);return te.has(W)?te.delete(W):te.add(W),te})},de=(W,se)=>{if(B.useSpanType){const te=se.split(".")[0]||se;return B.colorMap.get(te)||"#6366f1"}return W&&B.colorMap.get(W)||"#6366f1"},ye=W=>g.jsx("div",{style:{marginTop:"var(--space-component-md)",background:"var(--color-bg-base)",borderRadius:"var(--radius-lg)",overflow:"hidden"},children:g.jsxs("table",{style:{width:"100%",fontSize:"var(--font-size-body-sm)",fontFamily:"var(--font-family-mono)",borderCollapse:"collapse"},children:[g.jsx("thead",{children:g.jsxs("tr",{style:{background:"var(--color-bg-surface)",borderBottom:"2px solid var(--color-border-subtle)"},children:[g.jsx("th",{style:{padding:"12px",textAlign:"left",color:"var(--color-text-secondary)",fontWeight:"var(--font-weight-bold)"},children:"Service"}),g.jsx("th",{style:{padding:"12px",textAlign:"left",color:"var(--color-text-secondary)",fontWeight:"var(--font-weight-bold)"},children:"Operation"}),g.jsx("th",{style:{padding:"12px",textAlign:"right",color:"var(--color-text-secondary)",fontWeight:"var(--font-weight-bold)"},children:"Duration"}),g.jsx("th",{style:{padding:"12px",textAlign:"right",color:"var(--color-text-secondary)",fontWeight:"var(--font-weight-bold)"},children:"Start Time"}),g.jsx("th",{style:{padding:"12px",textAlign:"center",color:"var(--color-text-secondary)",fontWeight:"var(--font-weight-bold)"},children:"Status"})]})}),g.jsx("tbody",{children:W.spans.map((se,te)=>{const me=(se.end_time-se.start_time)/1e6,ve=(se.start_time-W.startTime)/1e6,Se=se.name.split(".")[0]||se.resource["service.name"]||"unknown";return g.jsxs("tr",{style:{background:te%2===0?"transparent":"var(--color-bg-surface)",borderBottom:"1px solid var(--color-border-subtle)"},children:[g.jsxs("td",{style:{padding:"10px"},children:[g.jsx("span",{style:{display:"inline-block",width:"8px",height:"8px",borderRadius:"50%",background:de(Se,se.name),marginRight:"8px"}}),Se]}),g.jsx("td",{style:{padding:"10px",color:"var(--color-text-primary)"},children:se.name}),g.jsxs("td",{style:{padding:"10px",textAlign:"right",color:"var(--color-text-primary)",fontWeight:"var(--font-weight-medium)"},children:[me.toFixed(2),"ms"]}),g.jsxs("td",{style:{padding:"10px",textAlign:"right",color:"var(--color-text-tertiary)"},children:["+",ve.toFixed(2),"ms"]}),g.jsx("td",{style:{padding:"10px",textAlign:"center"},children:g.jsx("span",{style:{padding:"2px 8px",borderRadius:"var(--radius-sm)",fontSize:"var(--font-size-body-xs)",fontWeight:"var(--font-weight-medium)",background:se.status.status_code==="ERROR"?"rgba(239, 68, 68, 0.2)":"rgba(16, 185, 129, 0.2)",color:se.status.status_code==="ERROR"?"#ef4444":"#10b981"},children:se.status.status_code})})]},se.context.span_id)})})]})}),xe=(W,se,te)=>{const me=(W.start_time-se)/1e6,ve=(W.end_time-W.start_time)/1e6,Se=Math.min(me/te*100,100),Ee=Math.min(ve/te*100,100-Se),Ve=Math.max(Ee,.5),qe=f.has(W.context.span_id),lt=p.has(W.context.span_id),tt=W.children.length>0,nt=W.name.split(".")[0]||W.resource["service.name"]||"unknown",Ft=de(nt,W.name),$t=w===W.context.span_id;return g.jsxs("div",{style:{marginBottom:"1px",opacity:$t?1:w?.4:1},children:[g.jsxs("div",{style:{display:"grid",gridTemplateColumns:"400px 1fr",alignItems:"center",background:qe?"var(--color-bg-elevated)":"transparent",borderBottom:"1px solid rgba(255, 255, 255, 0.03)"},children:[g.jsxs("div",{style:{padding:"8px 12px",fontSize:"var(--font-size-body-sm)",fontFamily:"var(--font-family-mono)",color:"var(--color-text-primary)",display:"flex",alignItems:"center",gap:"8px",paddingLeft:`${12+W.depth*20}px`,borderRight:"1px solid var(--color-border-subtle)"},children:[tt&&g.jsx("span",{onClick:()=>K(W.context.span_id),style:{cursor:"pointer",userSelect:"none",width:"12px",opacity:.6,fontSize:"10px"},children:lt?"►":"▼"}),!tt&&g.jsx("span",{style:{width:"12px"}}),g.jsx("span",{style:{display:"inline-block",width:"6px",height:"6px",borderRadius:"50%",background:Ft,flexShrink:0}}),g.jsx("span",{onClick:At=>{At.shiftKey?C($t?null:W.context.span_id):le(W.context.span_id)},style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",cursor:"pointer",display:"flex",alignItems:"center",gap:"4px"},title:`${W.name}
105
+ `);return v},[c]),h=q.useRef(null);q.useEffect(()=>{a&&h.current&&h.current.scrollIntoView({behavior:"smooth"})},[f,a]);const p=c.some(v=>v.is_final);return g.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",background:"var(--color-bg-elevated)"},children:[g.jsxs("div",{style:{padding:"var(--space-component-sm) var(--space-component-md)",background:"var(--color-bg-surface)",borderBottom:"var(--border-width-1) solid var(--color-border-subtle)",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[g.jsxs("span",{style:{color:"var(--color-text-tertiary)",fontSize:"var(--font-size-caption)",fontWeight:"var(--font-weight-medium)",fontFamily:"var(--font-family-sans)"},children:[c.length," ",c.length===1?"event":"events"]}),g.jsxs("label",{style:{color:"var(--color-text-tertiary)",fontSize:"var(--font-size-caption)",fontFamily:"var(--font-family-sans)",display:"flex",alignItems:"center",gap:"var(--gap-sm)",cursor:"pointer",userSelect:"none"},children:[g.jsx("input",{type:"checkbox",checked:a,onChange:v=>i(v.target.checked),style:{cursor:"pointer",accentColor:"var(--color-primary-500)"}}),"Auto-scroll"]})]}),g.jsx("div",{"data-testid":`live-output-${e}`,style:{flex:1,overflow:"auto",position:"relative",padding:"var(--spacing-2)"},children:o?g.jsx("div",{style:{padding:"var(--space-layout-md)",color:"var(--color-text-muted)",fontSize:"var(--font-size-body-sm)",fontFamily:"var(--font-family-sans)",textAlign:"center"},children:"Loading history..."}):c.length===0?g.jsx("div",{"data-testid":"empty-output",style:{padding:"var(--space-layout-md)",color:"var(--color-text-muted)",fontSize:"var(--font-size-body-sm)",fontFamily:"var(--font-family-sans)",textAlign:"center"},children:"Idle - no output"}):g.jsxs(g.Fragment,{children:[g.jsx("pre",{style:{margin:0,color:"var(--color-tertiary-400)",fontFamily:"var(--font-family-mono)",fontSize:"var(--font-size-caption)",whiteSpace:"pre-wrap",wordBreak:"break-word",lineHeight:"var(--line-height-relaxed)"},children:f}),p&&g.jsx("div",{"data-testid":"final-marker",style:{color:"var(--color-text-muted)",fontSize:"var(--font-size-caption)",fontFamily:"var(--font-family-mono)",padding:"var(--spacing-2) 0",borderTop:"var(--border-width-1) solid var(--color-border-subtle)",marginTop:"var(--spacing-2)"},children:"--- End of output ---"}),g.jsx("div",{ref:h})]})})]})},rU=({nodeId:e,nodeType:n})=>{const a=Me(p=>p.messages),i=Me(p=>p.agents),[o,l]=q.useState(new Set),c=q.useMemo(()=>{const p=[];if(n==="agent"){const v=i.get(e);if(!v)return p;a.forEach(m=>{const b=v.subscriptions.includes(m.type),_=m.producedBy===e;b&&p.push({id:m.id,type:m.type,direction:"consumed",payload:m.payload,timestamp:m.timestamp,correlationId:m.correlationId}),_&&p.push({id:`${m.id}-published`,type:m.type,direction:"published",payload:m.payload,timestamp:m.timestamp,correlationId:m.correlationId})})}else if(n==="message"){const v=a.get(e);v&&p.push({id:v.id,type:v.type,direction:"published",payload:v.payload,timestamp:v.timestamp,correlationId:v.correlationId})}return p.sort((v,m)=>m.timestamp-v.timestamp)},[e,n,a,i]),d=p=>new Date(p).toLocaleString(),f=p=>{try{return JSON.stringify(p,null,2)}catch{return String(p)}},h=p=>{l(v=>{const m=new Set(v);return m.has(p)?m.delete(p):m.add(p),m})};return g.jsx("div",{"data-testid":`message-history-${e}`,style:{height:"100%",overflow:"auto",background:"var(--color-bg-elevated)",color:"var(--color-text-primary)"},children:c.length===0?g.jsx("div",{"data-testid":"empty-messages",style:{padding:"var(--space-layout-md)",color:"var(--color-text-muted)",fontSize:"var(--font-size-body-sm)",fontFamily:"var(--font-family-sans)",textAlign:"center"},children:"No messages yet"}):g.jsxs("table",{"data-testid":"message-table",style:{width:"100%",borderCollapse:"collapse",fontSize:"var(--font-size-caption)",fontFamily:"var(--font-family-sans)"},children:[g.jsx("thead",{children:g.jsxs("tr",{style:{background:"var(--color-bg-surface)",borderBottom:"var(--border-width-1) solid var(--color-border-subtle)",position:"sticky",top:0,zIndex:1},children:[g.jsx("th",{style:{padding:"var(--space-component-sm) var(--space-component-md)",textAlign:"left",fontWeight:"var(--font-weight-semibold)",color:"var(--color-text-secondary)"},children:"Time"}),g.jsx("th",{style:{padding:"var(--space-component-sm) var(--space-component-md)",textAlign:"left",fontWeight:"var(--font-weight-semibold)",color:"var(--color-text-secondary)"},children:"Direction"}),g.jsx("th",{style:{padding:"var(--space-component-sm) var(--space-component-md)",textAlign:"left",fontWeight:"var(--font-weight-semibold)",color:"var(--color-text-secondary)"},children:"Type"}),g.jsx("th",{style:{padding:"var(--space-component-sm) var(--space-component-md)",textAlign:"left",fontWeight:"var(--font-weight-semibold)",color:"var(--color-text-secondary)"},children:"Correlation ID"}),g.jsx("th",{style:{padding:"var(--space-component-sm) var(--space-component-md)",textAlign:"left",fontWeight:"var(--font-weight-semibold)",color:"var(--color-text-secondary)"},children:"Payload"})]})}),g.jsx("tbody",{children:c.map(p=>{const v=o.has(p.id);return g.jsx(Kn.Fragment,{children:g.jsxs("tr",{"data-testid":`message-row-${p.id}`,style:{borderBottom:"var(--border-width-1) solid var(--color-border-subtle)",cursor:"pointer",transition:"var(--transition-colors)"},onClick:()=>h(p.id),onMouseEnter:m=>{m.currentTarget.style.background="var(--color-bg-surface)"},onMouseLeave:m=>{m.currentTarget.style.background="transparent"},children:[g.jsx("td",{"data-testid":`msg-time-${p.id}`,style:{padding:"var(--space-component-sm) var(--space-component-md)",whiteSpace:"nowrap",color:"var(--color-text-tertiary)"},children:d(p.timestamp)}),g.jsx("td",{"data-testid":`msg-direction-${p.id}`,style:{padding:"var(--space-component-sm) var(--space-component-md)",color:p.direction==="consumed"?"var(--color-tertiary-400)":"var(--color-success-light)",fontWeight:"var(--font-weight-semibold)"},children:p.direction==="consumed"?"↓ Consumed":"↑ Published"}),g.jsx("td",{"data-testid":`msg-type-${p.id}`,style:{padding:"var(--space-component-sm) var(--space-component-md)",fontFamily:"var(--font-family-mono)",color:"var(--color-text-primary)"},children:p.type}),g.jsx("td",{"data-testid":`msg-correlation-${p.id}`,style:{padding:"var(--space-component-sm) var(--space-component-md)",fontFamily:"var(--font-family-mono)",fontSize:"var(--font-size-overline)",color:"var(--color-text-muted)"},children:p.correlationId}),g.jsx("td",{"data-testid":`msg-payload-${p.id}`,style:{padding:"var(--space-component-sm) var(--space-component-md)",maxWidth:"300px"},children:g.jsx("pre",{style:{fontSize:"var(--font-size-overline)",fontFamily:"var(--font-family-mono)",maxHeight:v?"none":"60px",overflow:v?"visible":"hidden",textOverflow:"ellipsis",margin:0,whiteSpace:v?"pre-wrap":"nowrap",color:"var(--color-text-secondary)",background:"var(--color-bg-base)",padding:"var(--spacing-1)",borderRadius:"var(--radius-sm)"},children:f(p.payload)})})]})},p.id)})})]})})},aU=({nodeId:e,nodeType:n})=>{const a=Me(f=>f.runs),i=q.useMemo(()=>{const f=[];return n!=="agent"?f:(a.forEach(h=>{if(h.agent_name===e){const p=h.started_at?new Date(h.started_at).getTime():Date.now(),v=h.completed_at?new Date(h.completed_at).getTime():Date.now();let m="idle";h.status==="active"?m="processing":h.status==="error"?m="error":m="idle",f.push({runId:h.run_id,startTime:p,endTime:v,duration:h.duration_ms||0,status:m,metrics:h.metrics||{},errorMessage:h.error_message||void 0})}}),f.sort((h,p)=>p.startTime-h.startTime))},[e,n,a]),o=f=>new Date(f).toLocaleString(),l=f=>f<1e3?`${f}ms`:f<6e4?`${(f/1e3).toFixed(2)}s`:`${(f/6e4).toFixed(2)}m`,c=f=>{switch(f){case"idle":return"var(--color-success-light)";case"processing":return"var(--color-tertiary-400)";case"error":return"var(--color-error-light)";default:return"var(--color-text-primary)"}},d=f=>{switch(f){case"idle":return"Completed";case"processing":return"Processing";case"error":return"Error";default:return f}};return g.jsx("div",{"data-testid":`run-status-${e}`,style:{height:"100%",overflow:"auto",background:"var(--color-bg-elevated)",color:"var(--color-text-primary)"},children:i.length===0?g.jsx("div",{"data-testid":"empty-runs",style:{padding:"var(--space-layout-md)",color:"var(--color-text-muted)",fontSize:"var(--font-size-body-sm)",fontFamily:"var(--font-family-sans)",textAlign:"center"},children:"No previous runs"}):g.jsxs("table",{"data-testid":"run-table",style:{width:"100%",borderCollapse:"collapse",fontSize:"var(--font-size-caption)",fontFamily:"var(--font-family-sans)"},children:[g.jsx("thead",{children:g.jsxs("tr",{style:{background:"var(--color-bg-surface)",borderBottom:"var(--border-width-1) solid var(--color-border-subtle)",position:"sticky",top:0,zIndex:1},children:[g.jsx("th",{style:{padding:"var(--space-component-sm) var(--space-component-md)",textAlign:"left",fontWeight:"var(--font-weight-semibold)",color:"var(--color-text-secondary)"},children:"Run ID"}),g.jsx("th",{style:{padding:"var(--space-component-sm) var(--space-component-md)",textAlign:"left",fontWeight:"var(--font-weight-semibold)",color:"var(--color-text-secondary)"},children:"Start Time"}),g.jsx("th",{style:{padding:"var(--space-component-sm) var(--space-component-md)",textAlign:"left",fontWeight:"var(--font-weight-semibold)",color:"var(--color-text-secondary)"},children:"Duration"}),g.jsx("th",{style:{padding:"var(--space-component-sm) var(--space-component-md)",textAlign:"left",fontWeight:"var(--font-weight-semibold)",color:"var(--color-text-secondary)"},children:"Status"}),g.jsx("th",{style:{padding:"var(--space-component-sm) var(--space-component-md)",textAlign:"left",fontWeight:"var(--font-weight-semibold)",color:"var(--color-text-secondary)"},children:"Metrics"})]})}),g.jsx("tbody",{children:i.map(f=>g.jsxs("tr",{"data-testid":`run-row-${f.runId}`,style:{borderBottom:"var(--border-width-1) solid var(--color-border-subtle)",transition:"var(--transition-colors)"},onMouseEnter:h=>{h.currentTarget.style.background="var(--color-bg-surface)"},onMouseLeave:h=>{h.currentTarget.style.background="transparent"},children:[g.jsx("td",{"data-testid":`run-id-${f.runId}`,style:{padding:"var(--space-component-sm) var(--space-component-md)",fontFamily:"var(--font-family-mono)",fontSize:"var(--font-size-overline)",maxWidth:"150px",overflow:"hidden",textOverflow:"ellipsis",color:"var(--color-text-muted)"},children:f.runId}),g.jsx("td",{"data-testid":`run-start-${f.runId}`,style:{padding:"var(--space-component-sm) var(--space-component-md)",whiteSpace:"nowrap",color:"var(--color-text-tertiary)"},children:o(f.startTime)}),g.jsx("td",{"data-testid":`run-duration-${f.runId}`,style:{padding:"var(--space-component-sm) var(--space-component-md)",fontFamily:"var(--font-family-mono)",color:"var(--color-text-secondary)"},children:l(f.duration)}),g.jsxs("td",{"data-testid":`run-status-${f.runId}`,style:{padding:"var(--space-component-sm) var(--space-component-md)",color:c(f.status),fontWeight:"var(--font-weight-semibold)"},children:[d(f.status),f.errorMessage&&g.jsx("div",{style:{fontSize:"var(--font-size-overline)",color:"var(--color-text-muted)",marginTop:"var(--spacing-1)",fontStyle:"italic"},children:f.errorMessage})]}),g.jsx("td",{"data-testid":`run-metrics-${f.runId}`,style:{padding:"var(--space-component-sm) var(--space-component-md)"},children:g.jsxs("div",{style:{fontSize:"var(--font-size-overline)",fontFamily:"var(--font-family-mono)",color:"var(--color-text-muted)"},children:[f.metrics.tokensUsed!==void 0&&g.jsxs("div",{children:["Tokens: ",f.metrics.tokensUsed]}),f.metrics.costUsd!==void 0&&g.jsxs("div",{children:["Cost: $",f.metrics.costUsd.toFixed(4)]}),f.metrics.artifactsProduced!==void 0&&g.jsxs("div",{children:["Artifacts: ",f.metrics.artifactsProduced]}),Object.keys(f.metrics).length===0&&g.jsx("div",{children:"-"})]})})]},f.runId))})]})})},iU=({nodeId:e,nodeType:n="agent"})=>{const a=ut(p=>p.detailWindows.get(e)),i=ut(p=>p.updateDetailWindow),o=ut(p=>p.closeDetailWindow),l=q.useCallback(()=>{o(e)},[e,o]),c=q.useCallback(p=>{i(e,{activeTab:p})},[e,i]);if(!a)return null;const{position:d,size:f,activeTab:h}=a;return g.jsx(ez,{position:d,size:f,onDragStop:(p,v)=>{i(e,{position:{x:v.x,y:v.y}})},onResizeStop:(p,v,m,b,_)=>{i(e,{size:{width:parseInt(m.style.width,10),height:parseInt(m.style.height,10)},position:_})},minWidth:600,minHeight:400,bounds:"parent",dragHandleClassName:"window-header",style:{zIndex:1e3,display:"flex",flexDirection:"column",pointerEvents:"all"},children:g.jsxs("div",{style:{display:"flex",flexDirection:"column",width:"100%",height:"100%",background:"var(--color-glass-bg)",border:"var(--border-width-1) solid var(--color-glass-border)",borderRadius:"var(--radius-xl)",overflow:"hidden",boxShadow:"var(--shadow-xl)",backdropFilter:"blur(var(--blur-lg))",WebkitBackdropFilter:"blur(var(--blur-lg))"},children:[g.jsxs("div",{className:"window-header",style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"var(--space-component-md) var(--space-component-lg)",background:"rgba(42, 42, 50, 0.5)",borderBottom:"var(--border-width-1) solid var(--color-border-subtle)",cursor:"move",userSelect:"none"},children:[g.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"var(--gap-md)"},children:[g.jsx("div",{style:{width:"10px",height:"10px",borderRadius:"var(--radius-circle)",background:n==="agent"?"var(--color-primary-500)":"var(--color-warning)",boxShadow:n==="agent"?"0 0 8px var(--color-primary-500)":"0 0 8px var(--color-warning)"}}),g.jsxs("span",{style:{color:"var(--color-text-primary)",fontSize:"var(--font-size-body-sm)",fontWeight:"var(--font-weight-semibold)",fontFamily:"var(--font-family-sans)"},children:[n==="agent"?"Agent":"Message",": ",e]})]}),g.jsx("button",{onClick:l,"aria-label":"Close window",style:{background:"transparent",border:"none",color:"var(--color-text-secondary)",fontSize:"var(--font-size-h3)",cursor:"pointer",padding:"var(--spacing-1) var(--spacing-2)",lineHeight:1,borderRadius:"var(--radius-md)",transition:"var(--transition-colors)",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:p=>{p.currentTarget.style.color="var(--color-error)",p.currentTarget.style.background="var(--color-error-bg)"},onMouseLeave:p=>{p.currentTarget.style.color="var(--color-text-secondary)",p.currentTarget.style.background="transparent"},children:"×"})]}),g.jsx("div",{style:{display:"flex",gap:"var(--gap-sm)",padding:"var(--space-component-sm) var(--space-component-lg)",background:"rgba(35, 35, 41, 0.4)",borderBottom:"var(--border-width-1) solid var(--color-border-subtle)"},children:["liveOutput","messageHistory","runStatus"].map(p=>{const v=h===p;return g.jsx("button",{onClick:()=>c(p),style:{position:"relative",padding:"var(--space-component-sm) var(--space-component-md)",background:v?"var(--color-bg-surface)":"transparent",border:"none",borderRadius:"var(--radius-md)",color:v?"var(--color-text-primary)":"var(--color-text-secondary)",fontSize:"var(--font-size-body-sm)",fontWeight:v?"var(--font-weight-semibold)":"var(--font-weight-medium)",fontFamily:"var(--font-family-sans)",cursor:"pointer",transition:"var(--transition-colors)",borderBottom:v?"2px solid var(--color-primary-500)":"2px solid transparent"},onMouseEnter:m=>{v||(m.currentTarget.style.background="var(--color-bg-elevated)",m.currentTarget.style.color="var(--color-text-primary)")},onMouseLeave:m=>{v||(m.currentTarget.style.background="transparent",m.currentTarget.style.color="var(--color-text-secondary)")},children:p==="liveOutput"?"Live Output":p==="messageHistory"?"Message History":"Run Status"},p)})}),g.jsxs("div",{style:{flex:1,overflow:"hidden",background:"var(--color-bg-surface)"},children:[h==="liveOutput"&&g.jsx(nU,{nodeId:e,nodeType:n}),h==="messageHistory"&&g.jsx(rU,{nodeId:e,nodeType:n}),h==="runStatus"&&g.jsx(aU,{nodeId:e,nodeType:n})]})]})})},oU=()=>{const e=ut(l=>l.detailWindows),n=ut(l=>l.mode),a=Me(l=>l.agents),i=Me(l=>l.messages),o=Array.from(e.entries());return g.jsx("div",{style:{position:"fixed",top:0,left:0,right:0,bottom:0,pointerEvents:"none",zIndex:999},children:g.jsx("div",{style:{position:"relative",width:"100%",height:"100%",pointerEvents:"none"},children:o.map(([l,c])=>{let d="agent";return n==="agent"?a.has(l)&&(d="agent"):n==="blackboard"&&i.has(l)&&(d="message"),g.jsx(iU,{nodeId:l,nodeType:d},l)})})})},sU="_container_18lbh_1",lU="_inputWrapper_18lbh_11",cU="_input_18lbh_11",uU="_clearButton_18lbh_67",dU="_dropdown_18lbh_105",fU="_dropdownEmpty_18lbh_135",hU="_dropdownItem_18lbh_149",pU="_correlationId_18lbh_179",gU="_metadata_18lbh_197",Cr={container:sU,inputWrapper:lU,input:cU,clearButton:uU,dropdown:dU,dropdownEmpty:fU,dropdownItem:hU,correlationId:pU,metadata:gU},vU=e=>{const n=Math.floor((Date.now()-e)/1e3);if(n<60)return`${n}s ago`;const a=Math.floor(n/60);if(a<60)return`${a}m ago`;const i=Math.floor(a/60);return i<24?`${i}h ago`:`${Math.floor(i/24)}d ago`},mU=()=>{const e=Te(_=>_.correlationId),n=Te(_=>_.availableCorrelationIds),a=Te(_=>_.setCorrelationId),[i,o]=q.useState(e||""),[l,c]=q.useState(!1),d=q.useRef(null);q.useEffect(()=>{o(e||"")},[e]),q.useEffect(()=>{const _=S=>{d.current&&!d.current.contains(S.target)&&c(!1)};return document.addEventListener("mousedown",_),()=>document.removeEventListener("mousedown",_)},[]);const f=n.filter(_=>_.correlation_id.toLowerCase().includes(i.toLowerCase())),h=_=>{a(_),o(_),c(!1)},p=()=>{a(null),o(""),c(!1)},v=_=>{o(_.target.value),c(!0)},m=()=>{c(!0)},b=()=>{setTimeout(()=>c(!1),200)};return g.jsxs("div",{ref:d,className:Cr.container,children:[g.jsxs("div",{className:Cr.inputWrapper,children:[g.jsx("input",{type:"text",value:i,onChange:v,onFocus:m,onBlur:b,placeholder:"Search correlation ID...",className:Cr.input}),e&&g.jsx("button",{onClick:p,"aria-label":"Clear",className:Cr.clearButton,children:"×"})]}),l&&g.jsx("div",{className:Cr.dropdown,children:f.length===0?g.jsx("div",{className:Cr.dropdownEmpty,children:"No correlation IDs found"}):f.map(_=>g.jsxs("div",{onClick:()=>h(_.correlation_id),className:Cr.dropdownItem,children:[g.jsx("div",{className:Cr.correlationId,children:_.correlation_id}),g.jsxs("div",{className:Cr.metadata,children:[_.artifact_count," messages, ",vU(_.first_seen)]})]},_.correlation_id))})]})},yU="_container_kluuc_1",bU="_presetButtons_kluuc_13",xU="_presetButton_kluuc_13",_U="_active_kluuc_65",SU="_presetButtonAll_kluuc_87",wU="_customRange_kluuc_133",EU="_dateInputGroup_kluuc_153",CU="_dateLabel_kluuc_165",TU="_dateInput_kluuc_153",En={container:yU,presetButtons:bU,presetButton:xU,active:_U,presetButtonAll:SU,customRange:wU,dateInputGroup:EU,dateLabel:CU,dateInput:TU},jU=()=>{const e=Te(d=>d.timeRange),n=Te(d=>d.setTimeRange),a=d=>{if(d==="custom"){const f=Date.now(),h=f-36e5;n({preset:"custom",start:h,end:f})}else n({preset:d})},i=d=>{const f=new Date(d.target.value).getTime();n({preset:"custom",start:f,end:e.end||Date.now()})},o=d=>{const f=new Date(d.target.value).getTime();n({preset:"custom",start:e.start||Date.now()-36e5,end:f})},l=d=>new Date(d).toISOString().slice(0,16),c=[{preset:"all",label:"All"},{preset:"last5min",label:"Last 5 min"},{preset:"last10min",label:"Last 10 min"},{preset:"last1hour",label:"Last hour"},{preset:"custom",label:"Custom"}];return g.jsxs("div",{className:En.container,children:[g.jsx("div",{className:En.presetButtons,children:c.map(({preset:d,label:f})=>g.jsx("button",{onClick:()=>a(d),className:[En.presetButton,d==="all"?En.presetButtonAll:"",e.preset===d?En.active:""].filter(Boolean).join(" "),children:f},d))}),e.preset==="custom"&&g.jsxs("div",{className:En.customRange,children:[g.jsxs("div",{className:En.dateInputGroup,children:[g.jsx("label",{htmlFor:"start-time",className:En.dateLabel,children:"Start"}),g.jsx("input",{id:"start-time",type:"datetime-local",value:e.start?l(e.start):"",onChange:i,className:En.dateInput})]}),g.jsxs("div",{className:En.dateInputGroup,children:[g.jsx("label",{htmlFor:"end-time",className:En.dateLabel,children:"End"}),g.jsx("input",{id:"end-time",type:"datetime-local",value:e.end?l(e.end):"",onChange:o,className:En.dateInput})]})]})]})},so=({options:e,selected:n,onChange:a,placeholder:i="Select items...",disabled:o=!1})=>{const[l,c]=q.useState(!1),[d,f]=q.useState(""),[h,p]=q.useState(0),v=q.useRef(null),m=q.useRef(null),b=e.filter(C=>!n.includes(C)&&C.toLowerCase().includes(d.toLowerCase()));q.useEffect(()=>{const C=T=>{v.current&&!v.current.contains(T.target)&&(c(!1),f(""))};return document.addEventListener("mousedown",C),()=>document.removeEventListener("mousedown",C)},[]);const _=C=>{a([...n,C]),f(""),p(0),m.current?.focus()},S=C=>{a(n.filter(T=>T!==C))},w=C=>{if(!o)switch(C.key){case"ArrowDown":C.preventDefault(),p(T=>Math.min(T+1,b.length-1));break;case"ArrowUp":C.preventDefault(),p(T=>Math.max(T-1,0));break;case"Enter":C.preventDefault(),b[h]&&_(b[h]);break;case"Escape":c(!1),f("");break;case"Backspace":if(d===""&&n.length>0){const T=n[n.length-1];T&&S(T)}break}};return g.jsxs("div",{ref:v,style:{position:"relative"},children:[g.jsxs("div",{onClick:()=>!o&&m.current?.focus(),style:{minHeight:"38px",padding:"var(--space-xs)",backgroundColor:o?"rgba(0, 0, 0, 0.2)":"rgba(0, 0, 0, 0.3)",border:`1px solid ${l?"rgba(96, 165, 250, 0.5)":"rgba(255, 255, 255, 0.1)"}`,borderRadius:"var(--radius-sm)",display:"flex",flexWrap:"wrap",gap:"var(--gap-xs)",cursor:o?"not-allowed":"text",transition:"border-color 0.2s",opacity:o?.6:1},children:[n.map(C=>g.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"var(--gap-xs)",padding:"2px 8px",backgroundColor:"rgba(96, 165, 250, 0.2)",border:"1px solid rgba(96, 165, 250, 0.4)",borderRadius:"var(--radius-sm)",fontSize:"var(--font-size-sm)",color:"#60a5fa",maxWidth:"100%",overflow:"hidden"},children:[g.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},title:C,children:C}),!o&&g.jsx("button",{onClick:T=>{T.stopPropagation(),S(C)},style:{background:"none",border:"none",color:"#60a5fa",cursor:"pointer",padding:0,display:"flex",alignItems:"center",fontSize:"14px",lineHeight:1,flexShrink:0},children:"×"})]},C)),g.jsx("input",{ref:m,type:"text",value:d,onChange:C=>{f(C.target.value),c(!0),p(0)},onFocus:()=>!o&&c(!0),onKeyDown:w,placeholder:n.length===0?i:"",disabled:o,style:{flex:1,minWidth:"120px",background:"transparent",border:"none",outline:"none",color:"var(--color-text-primary)",fontSize:"var(--font-size-base)",padding:"4px"}})]}),l&&!o&&b.length>0&&g.jsx("div",{style:{position:"absolute",top:"calc(100% + 4px)",left:0,right:0,maxHeight:"240px",overflowY:"auto",backgroundColor:"rgba(0, 0, 0, 0.9)",border:"1px solid rgba(96, 165, 250, 0.3)",borderRadius:"var(--radius-sm)",boxShadow:"0 4px 12px rgba(0, 0, 0, 0.5)",zIndex:1e3},children:b.map((C,T)=>g.jsx("div",{onClick:()=>_(C),onMouseEnter:()=>p(T),style:{padding:"var(--space-xs) var(--space-sm)",cursor:"pointer",backgroundColor:T===h?"rgba(96, 165, 250, 0.2)":"transparent",color:T===h?"#60a5fa":"var(--color-text-primary)",fontSize:"var(--font-size-sm)",transition:"background-color 0.15s"},children:C},C))})]})},NU=()=>{const e=Te(i=>i.availableArtifactTypes),n=Te(i=>i.selectedArtifactTypes),a=Te(i=>i.setArtifactTypes);return g.jsx(so,{options:e,selected:n,onChange:a,placeholder:e.length?"Select types…":"No types available",disabled:e.length===0})},RU=()=>{const e=Te(i=>i.availableProducers),n=Te(i=>i.selectedProducers),a=Te(i=>i.setProducers);return g.jsx(so,{options:e,selected:n,onChange:a,placeholder:e.length?"Select producers…":"No producers",disabled:e.length===0})},MU=()=>{const e=Te(i=>i.availableTags),n=Te(i=>i.selectedTags),a=Te(i=>i.setTags);return g.jsx(so,{options:e,selected:n,onChange:a,placeholder:e.length?"Select tags…":"No tags available",disabled:e.length===0})},AU=()=>{const e=Te(i=>i.availableVisibility),n=Te(i=>i.selectedVisibility),a=Te(i=>i.setVisibility);return g.jsx(so,{options:e,selected:n,onChange:a,placeholder:e.length?"Select visibility…":"No visibility options",disabled:e.length===0})},zU="_container_9ted7_1",DU="_controlsRow_9ted7_13",kU="_select_9ted7_27",OU="_saveButton_9ted7_45",qU="_applyButton_9ted7_47",BU="_deleteButton_9ted7_49",LU="_error_9ted7_113",qa={container:zU,controlsRow:DU,select:kU,saveButton:OU,applyButton:qU,deleteButton:BU,error:LU},HU=()=>{const e=Te(w=>w.savedFilters),n=Te(w=>w.setSavedFilters),a=Te(w=>w.addSavedFilter),i=Te(w=>w.removeSavedFilter),o=Te(w=>w.getFilterSnapshot),l=Te(w=>w.applyFilterSnapshot),[c,d]=q.useState(""),[f,h]=q.useState(!0),[p,v]=q.useState(null),m=q.useRef(0);m.current+=1,q.useEffect(()=>{let w=!0;return(async()=>{try{await Cn.initialize();const C=await Cn.getAllFilterPresets();if(!w)return;n(C),C.length>0?d(C[0]?.filter_id??""):d(""),v(null)}catch(C){console.error("[SavedFilters] Failed to load presets",C),w&&v("Unable to load saved presets")}finally{w&&h(!1)}})(),()=>{w=!1}},[n]);const b=async()=>{const w=window.prompt("Save current filters as preset. Enter a name:");if(!(!w||!w.trim()))try{const C={filter_id:typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`filter-${Date.now()}`,name:w.trim(),created_at:Date.now(),filters:o()};await Cn.saveFilterPreset(C),a(C),d(C.filter_id),v(null)}catch(C){console.error("[SavedFilters] Failed to save preset",C),v("Failed to save preset")}},_=()=>{if(!c)return;const w=e.find(C=>C.filter_id===c);w&&l(w.filters)},S=async()=>{if(c)try{await Cn.deleteFilterPreset(c),i(c);const w=e.filter(C=>C.filter_id!==c);d(w[0]?.filter_id??""),v(null)}catch(w){console.error("[SavedFilters] Failed to delete preset",w),v("Failed to delete preset")}};return g.jsxs("div",{className:qa.container,children:[g.jsxs("div",{className:qa.controlsRow,children:[g.jsx("button",{type:"button",className:qa.saveButton,onClick:b,disabled:f,children:"Save Current"}),g.jsxs("select",{className:qa.select,value:c,onChange:w=>d(w.target.value),disabled:f||e.length===0,"aria-label":"Saved filter presets",children:[e.length===0&&g.jsx("option",{value:"",children:"No presets"}),e.map(w=>g.jsx("option",{value:w.filter_id,children:w.name},w.filter_id))]}),g.jsx("button",{type:"button",className:qa.applyButton,onClick:_,disabled:!c,children:"Apply"}),g.jsx("button",{type:"button",className:qa.deleteButton,onClick:S,disabled:!c,children:"Delete"})]}),p&&g.jsx("div",{className:qa.error,children:p})]})},IU="_panel_knkln_1",UU="_header_knkln_33",VU="_title_knkln_51",FU="_subtitle_knkln_63",PU="_closeButton_knkln_75",GU="_content_knkln_109",$U="_section_knkln_127",YU="_sectionLabel_knkln_139",WU="_separator_knkln_155",rt={panel:IU,header:UU,title:VU,subtitle:FU,closeButton:PU,content:GU,section:$U,sectionLabel:YU,separator:WU},XU=({onClose:e})=>g.jsxs("aside",{className:rt.panel,role:"dialog","aria-label":"Filters",children:[g.jsxs("header",{className:rt.header,children:[g.jsxs("div",{children:[g.jsx("h2",{className:rt.title,children:"Filters"}),g.jsx("p",{className:rt.subtitle,children:"Slice historical data without losing your place."})]}),g.jsx("button",{type:"button",className:rt.closeButton,onClick:e,"aria-label":"Close filters",children:"×"})]}),g.jsxs("div",{className:rt.content,children:[g.jsxs("section",{className:rt.section,children:[g.jsx("h3",{className:rt.sectionLabel,children:"Presets"}),g.jsx(HU,{})]}),g.jsx("div",{className:rt.separator,role:"presentation"}),g.jsxs("section",{className:rt.section,children:[g.jsx("h3",{className:rt.sectionLabel,children:"Correlation"}),g.jsx(mU,{})]}),g.jsx("div",{className:rt.separator,role:"presentation"}),g.jsxs("section",{className:rt.section,children:[g.jsx("h3",{className:rt.sectionLabel,children:"Time Range"}),g.jsx(jU,{})]}),g.jsx("div",{className:rt.separator,role:"presentation"}),g.jsxs("section",{className:rt.section,children:[g.jsx("h3",{className:rt.sectionLabel,children:"Artifact Types"}),g.jsx(NU,{})]}),g.jsx("div",{className:rt.separator,role:"presentation"}),g.jsxs("section",{className:rt.section,children:[g.jsx("h3",{className:rt.sectionLabel,children:"Producers"}),g.jsx(RU,{})]}),g.jsx("div",{className:rt.separator,role:"presentation"}),g.jsxs("section",{className:rt.section,children:[g.jsx("h3",{className:rt.sectionLabel,children:"Tags"}),g.jsx(MU,{})]}),g.jsx("div",{className:rt.separator,role:"presentation"}),g.jsxs("section",{className:rt.section,children:[g.jsx("h3",{className:rt.sectionLabel,children:"Visibility"}),g.jsx(AU,{})]})]})]}),KU="_wrapper_1qq57_1",ZU="_container_1qq57_15",QU="_toggleButton_1qq57_37",JU="_toggleButtonActive_1qq57_103",eV="_toggleIcon_1qq57_125",tV="_toggleLabel_1qq57_155",nV="_pill_1qq57_163",rV="_pillAccent_1qq57_227",aV="_textGroup_1qq57_245",iV="_pillTitle_1qq57_259",oV="_pillValue_1qq57_275",sV="_removeButton_1qq57_289",lV="_removeIcon_1qq57_349",dn={wrapper:KU,container:ZU,toggleButton:QU,toggleButtonActive:JU,toggleIcon:eV,toggleLabel:tV,pill:nV,pillAccent:rV,textGroup:aV,pillTitle:iV,pillValue:oV,removeButton:sV,removeIcon:lV},cV=e=>{const n=e.match(/^([^:]+):(.*)$/),a=n?.[1]?.trim()??e.trim(),i=n?.[2]?.trim()??"";return{title:a,value:i}},uV=()=>{const e=_e(p=>p.ui.showFilters),n=_e(p=>p.setShowFilters),a=Te(p=>p.correlationId),i=Te(p=>p.timeRange),o=Te(p=>p.selectedArtifactTypes),l=Te(p=>p.selectedProducers),c=Te(p=>p.selectedTags),d=Te(p=>p.selectedVisibility),f=Te(p=>p.removeFilter),h=q.useMemo(()=>{const p=[];return a&&p.push({type:"correlationId",value:a,label:`Correlation ID: ${a}`}),p.push({type:"timeRange",value:i,label:`Time: ${ab(i)}`}),o.forEach(v=>{p.push({type:"artifactTypes",value:v,label:`Type: ${v}`})}),l.forEach(v=>{p.push({type:"producers",value:v,label:`Producer: ${v}`})}),c.forEach(v=>{p.push({type:"tags",value:v,label:`Tag: ${v}`})}),d.forEach(v=>{p.push({type:"visibility",value:v,label:`Visibility: ${v}`})}),p},[a,i,o,l,c,d]);return h.length===0?null:g.jsxs("div",{className:dn.wrapper,children:[g.jsxs("button",{type:"button",onClick:()=>n(!e),className:`${dn.toggleButton} ${e?dn.toggleButtonActive:""}`,title:`${e?"Hide":"Show"} filter panel (Ctrl+Shift+F)`,"aria-pressed":e,"aria-label":e?"Hide filter panel":"Show filter panel",children:[g.jsx("span",{className:dn.toggleIcon,"aria-hidden":"true",children:g.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:g.jsx("path",{d:"M2.667 2.667h10.666L9.333 7v4.667l-2.666 1.333V7L2.667 2.667z",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),g.jsx("span",{className:dn.toggleLabel,children:"Filter"})]}),g.jsx("div",{className:dn.container,role:"list",children:h.map((p,v)=>{const m=p.type==="timeRange"&&typeof p.value!="string"?`Time: ${ab(p.value)}`:p.label,{title:b,value:_}=cV(m),S=_?`${b} ${_}`:b;return g.jsxs("div",{className:dn.pill,"data-filter-type":p.type,role:"listitem",children:[g.jsx("span",{className:dn.pillAccent,"aria-hidden":"true"}),g.jsxs("div",{className:dn.textGroup,children:[g.jsx("span",{className:dn.pillTitle,children:b}),_&&g.jsx("span",{className:dn.pillValue,children:_})]}),g.jsx("button",{onClick:()=>f(p),"aria-label":`Remove ${S} filter`,className:dn.removeButton,type:"button",children:g.jsx("span",{"aria-hidden":"true",className:dn.removeIcon,children:"×"})})]},`${p.type}-${String(p.value)}-${v}`)})})]})},Ks="/api";class er extends Error{constructor(n,a){super(a.message||a.error),this.status=n,this.errorResponse=a,this.name="ApiError"}}async function dV(){try{const e=await fetch(`${Ks}/artifact-types`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!e.ok){const a=await e.json().catch(()=>({error:"Unknown error",message:"Failed to fetch artifact types"}));throw new er(e.status,a)}return(await e.json()).artifact_types}catch(e){throw e instanceof er?e:new Error("Failed to connect to API server")}}async function fV(){try{const e=await fetch(`${Ks}/agents`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!e.ok){const a=await e.json().catch(()=>({error:"Unknown error",message:"Failed to fetch agents"}));throw new er(e.status,a)}return(await e.json()).agents}catch(e){throw e instanceof er?e:new Error("Failed to connect to API server")}}async function hV(){return(await fV()).map(n=>({id:n.name,name:n.name,status:"idle",subscriptions:n.subscriptions||[],outputTypes:n.output_types||[],lastActive:Date.now(),sentCount:0,recvCount:0,receivedByType:{},sentByType:{}}))}async function pV(e,n){try{const a=await fetch(`${Ks}/control/publish`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({artifact_type:e,content:n})});if(!a.ok){const i=await a.json().catch(()=>({error:"Unknown error",message:"Failed to publish artifact"}));throw new er(a.status,i)}return await a.json()}catch(a){throw a instanceof er?a:new Error("Failed to connect to API server")}}const tz=e=>{const n=new URLSearchParams;return e.types?.forEach(a=>n.append("type",a)),e.producers?.forEach(a=>n.append("produced_by",a)),e.tags?.forEach(a=>n.append("tag",a)),e.visibility?.forEach(a=>n.append("visibility",a)),e.correlationId&&n.append("correlation_id",e.correlationId),e.from&&n.append("from",e.from),e.to&&n.append("to",e.to),typeof e.limit=="number"&&n.append("limit",String(e.limit)),typeof e.offset=="number"&&n.append("offset",String(e.offset)),e.embedMeta&&n.append("embed_meta","true"),n.toString()};async function nz(e={}){const n=tz(e);try{const a=await fetch(`${Ks}/v1/artifacts${n?`?${n}`:""}`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!a.ok){const o=await a.json().catch(()=>({error:"Unknown error",message:"Failed to fetch artifacts"}));throw new er(a.status,o)}return await a.json()}catch(a){throw a instanceof er?a:new Error("Failed to connect to API server")}}async function rz(e={}){const n=tz(e);try{const a=await fetch(`${Ks}/v1/artifacts/summary${n?`?${n}`:""}`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!a.ok){const o=await a.json().catch(()=>({error:"Unknown error",message:"Failed to fetch artifact summary"}));throw new er(a.status,o)}return(await a.json()).summary}catch(a){throw a instanceof er?a:new Error("Failed to connect to API server")}}const gV=()=>{const[e,n]=q.useState([]),[a,i]=q.useState(""),[o,l]=q.useState({}),[c,d]=q.useState(!1),[f,h]=q.useState(!0),[p,v]=q.useState({}),[m,b]=q.useState(""),[_,S]=q.useState(""),[w,C]=q.useState(!0),T=_e(j=>j.setShowControls),E=()=>{T(!1)};q.useEffect(()=>{(async()=>{try{h(!0);const A=await dV();n(A)}catch(A){console.error("Failed to fetch artifact types:",A),S("Failed to load artifact types")}finally{h(!1)}})()},[]),q.useEffect(()=>{if(a){const j=e.find(A=>A.name===a);if(j&&j.schema.properties){const A={};Object.keys(j.schema.properties).forEach(D=>{const I=j.schema.properties[D];I.type==="boolean"?A[D]=!1:(I.type==="number"||I.type,A[D]=I.default??"")}),l(A)}}else l({});v({})},[a,e]);const N=()=>{const j={};if(!a)return j.artifactType="Artifact type is required",v(j),!1;const A=e.find(D=>D.name===a);return A?(A.schema.properties&&Object.entries(A.schema.properties).forEach(([D,I])=>{const P=o[D];if(P===""||P===null||P===void 0){j[D]=`${D} is required`;return}(I.type==="number"||I.type==="integer")&&isNaN(Number(P))&&(j[D]=`${D} must be a number`)}),v(j),Object.keys(j).length===0):(j.artifactType="Invalid artifact type",v(j),!1)},R=async j=>{if(j.preventDefault(),b(""),S(""),!!N()){d(!0);try{const A=e.find(P=>P.name===a),D={};A&&A.schema.properties&&Object.entries(o).forEach(([P,V])=>{const $=A.schema.properties[P];$.type==="number"||$.type==="integer"?D[P]=Number(V):$.type==="boolean"?D[P]=!!V:D[P]=V});const I=await pV(a,D);w&&I.correlation_id?(Te.setState({correlationId:I.correlation_id}),b(`Successfully published artifact. Filter set to: ${I.correlation_id}`)):b(`Successfully published artifact. Correlation ID: ${I.correlation_id}`),i(""),l({}),v({}),setTimeout(()=>{T(!1)},800)}catch(A){A.message.includes("Network error")||A.message.includes("Failed to connect")?S("Network error. Failed to connect to API server."):S(A.message||"Failed to publish artifact")}finally{d(!1)}}},z=(j,A)=>{const D=o[j]??"",I=!!p[j],P=$=>{if(l({...o,[j]:$}),p[j]){const L={...p};delete L[j],v(L)}};return A.type==="boolean"?g.jsxs("div",{className:"publish-control__field",children:[g.jsxs("div",{className:"publish-control__checkbox-wrapper",children:[g.jsx("input",{type:"checkbox",id:`field-${j}`,checked:!!D,onChange:$=>P($.target.checked),disabled:c,className:"publish-control__checkbox"}),g.jsxs("label",{htmlFor:`field-${j}`,className:"publish-control__checkbox-label",children:[A.title||j,A.description&&g.jsxs("span",{className:"publish-control__field-hint",children:[" — ",A.description]})]})]}),I&&g.jsx("div",{className:"publish-control__error-text",children:p[j]})]},j):A.type==="number"||A.type==="integer"?g.jsxs("div",{className:"publish-control__field",children:[g.jsxs("label",{htmlFor:`field-${j}`,className:"publish-control__label",children:[A.title||j,A.description&&g.jsxs("span",{className:"publish-control__field-hint",children:[" — ",A.description]})]}),g.jsx("input",{type:"number",id:`field-${j}`,value:D,onChange:$=>P($.target.value),disabled:c,step:A.type==="integer"?1:"any",className:`publish-control__input ${I?"publish-control__input--error":""}`}),I&&g.jsx("div",{className:"publish-control__error-text",children:p[j]})]},j):A.enum&&Array.isArray(A.enum)?g.jsxs("div",{className:"publish-control__field",children:[g.jsxs("label",{htmlFor:`field-${j}`,className:"publish-control__label",children:[A.title||j,A.description&&g.jsxs("span",{className:"publish-control__field-hint",children:[" — ",A.description]})]}),g.jsxs("select",{id:`field-${j}`,value:D,onChange:$=>P($.target.value),disabled:c,className:`publish-control__select ${I?"publish-control__select--error":""}`,children:[g.jsx("option",{value:"",children:"Select..."}),A.enum.map($=>g.jsx("option",{value:$,children:$},$))]}),I&&g.jsx("div",{className:"publish-control__error-text",children:p[j]})]},j):A.maxLength>100||j.toLowerCase().includes("description")?g.jsxs("div",{className:"publish-control__field",children:[g.jsxs("label",{htmlFor:`field-${j}`,className:"publish-control__label",children:[A.title||j,A.description&&g.jsxs("span",{className:"publish-control__field-hint",children:[" — ",A.description]})]}),g.jsx("textarea",{id:`field-${j}`,value:D,onChange:$=>P($.target.value),disabled:c,rows:4,className:`publish-control__textarea ${I?"publish-control__textarea--error":""}`}),I&&g.jsx("div",{className:"publish-control__error-text",children:p[j]})]},j):g.jsxs("div",{className:"publish-control__field",children:[g.jsxs("label",{htmlFor:`field-${j}`,className:"publish-control__label",children:[A.title||j,A.description&&g.jsxs("span",{className:"publish-control__field-hint",children:[" — ",A.description]})]}),g.jsx("input",{type:"text",id:`field-${j}`,value:D,onChange:$=>P($.target.value),disabled:c,placeholder:A.examples?.[0]||"",className:`publish-control__input ${I?"publish-control__input--error":""}`}),I&&g.jsx("div",{className:"publish-control__error-text",children:p[j]})]},j)};return g.jsx("div",{className:"publish-control-panel",children:g.jsxs("div",{className:"publish-control-panel-inner",children:[g.jsxs("div",{className:"publish-control-header",children:[g.jsx("h2",{className:"publish-control-title",children:"Publish Artifact"}),g.jsx("button",{onClick:E,className:"publish-control-close-button","aria-label":"Close publish panel",title:"Close publish panel (Esc)",children:g.jsx("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:g.jsx("path",{d:"M15 5L5 15M5 5l10 10",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]}),g.jsx("div",{className:"publish-control-content",children:g.jsxs("form",{className:"publish-control__form",onSubmit:R,children:[g.jsxs("div",{className:"publish-control__field",children:[g.jsx("label",{htmlFor:"artifact-type",className:"publish-control__label",children:"Artifact Type"}),g.jsxs("select",{id:"artifact-type",value:a,onChange:j=>{i(j.target.value),v({...p,artifactType:void 0})},disabled:f||c,className:`publish-control__select ${p.artifactType?"publish-control__select--error":""}`,children:[g.jsx("option",{value:"",children:"Select an artifact type..."}),e.map(j=>g.jsx("option",{value:j.name,children:j.name},j.name))]}),p.artifactType&&g.jsx("div",{className:"publish-control__error-text",children:p.artifactType})]}),a&&(()=>{const j=e.find(A=>A.name===a);return j&&j.schema.properties?Object.entries(j.schema.properties).map(([A,D])=>z(A,D)):g.jsx("div",{className:"publish-control__field",children:g.jsx("p",{className:"publish-control__hint",children:"Select an artifact type to see form fields"})})})(),g.jsxs("div",{className:"publish-control__checkbox-wrapper",children:[g.jsx("input",{type:"checkbox",id:"auto-set-filter",checked:w,onChange:j=>C(j.target.checked),disabled:c,className:"publish-control__checkbox"}),g.jsx("label",{htmlFor:"auto-set-filter",className:"publish-control__checkbox-label",children:"Set filter to correlation ID (show only this execution)"})]}),g.jsx("button",{type:"submit",disabled:c||f,className:"publish-control__submit",children:c?"Publishing...":"Publish Artifact"}),m&&g.jsx("div",{className:"publish-control__message publish-control__message--success",children:m}),_&&g.jsx("div",{className:"publish-control__message publish-control__message--error",children:_})]})})]})})};function vV(){const e=jr(b=>b.instances),n=Me(b=>b.agents),a=Me(b=>b.messages),i=Me(b=>b.events),o=Te(b=>b.correlationId),l=Te(b=>b.timeRange),c=Te(b=>b.selectedArtifactTypes),d=Te(b=>b.selectedProducers),f=Te(b=>b.selectedTags),h=Te(b=>b.selectedVisibility),p=Te(b=>b.summary),v=q.useRef(new Map),m=q.useMemo(()=>({agents:n,messages:a,events:i,filters:{correlationId:o,timeRange:l,artifactTypes:c,producers:d,tags:f,visibility:h},summary:p,publish:b=>{console.log("[Module Context] Publish artifact:",b)},invoke:(b,_)=>{console.log("[Module Context] Invoke agent:",b,"with inputs:",_)}}),[n,a,i,o,l,c,d,f,h,p]);return q.useEffect(()=>{const b=e,_=v.current,S=new Map;b.forEach((C,T)=>{_.has(T)||S.set(T,C)});const w=new Map;return _.forEach((C,T)=>{b.has(T)||w.set(T,C)}),S.forEach(C=>{const T=Va.get(C.type);if(T?.onMount){console.log(`[useModules] Calling onMount for module: ${T.name} (${C.id})`);try{T.onMount(m)}catch(E){console.error(`[useModules] Error in onMount for module ${T.name}:`,E)}}}),w.forEach(C=>{const T=Va.get(C.type);if(T?.onUnmount){console.log(`[useModules] Calling onUnmount for module: ${T.name} (${C.id})`);try{T.onUnmount()}catch(E){console.error(`[useModules] Error in onUnmount for module ${T.name}:`,E)}}}),v.current=new Map(b),()=>{b.forEach(C=>{const T=Va.get(C.type);if(T?.onUnmount){console.log(`[useModules] Cleanup: Calling onUnmount for module: ${T.name} (${C.id})`);try{T.onUnmount()}catch(E){console.error(`[useModules] Error in cleanup onUnmount for module ${T.name}:`,E)}}})}},[e,m]),{context:m}}const az=q.memo(({instanceId:e})=>{const n=jr(v=>v.instances.get(e)),a=jr(v=>v.updateModule),i=jr(v=>v.removeModule),{context:o}=vV(),l=q.useCallback(()=>{i(e)},[e,i]),c=q.useCallback(()=>{n&&(n.maximized?a(e,{maximized:!1,position:n.preMaximizePosition||n.position,size:n.preMaximizeSize||n.size}):a(e,{maximized:!0,preMaximizePosition:n.position,preMaximizeSize:n.size,position:{x:0,y:0},size:{width:window.innerWidth,height:window.innerHeight}}))},[e,n,a]);if(!n||!n.visible)return null;const d=Va.get(n.type);if(!d)return console.error(`Module definition not found for type: ${n.type}`),null;const{position:f,size:h}=n,p=d.component;return g.jsx(ez,{position:f,size:h,disableDragging:n.maximized,enableResizing:!n.maximized,onDragStop:(v,m)=>{a(e,{position:{x:m.x,y:m.y}})},onResizeStop:(v,m,b,_,S)=>{a(e,{size:{width:parseInt(b.style.width,10),height:parseInt(b.style.height,10)},position:S})},minWidth:1e3,minHeight:500,bounds:"parent",dragHandleClassName:"module-window-header",style:{zIndex:1e3,display:"flex",flexDirection:"column"},children:g.jsxs("div",{style:{display:"flex",flexDirection:"column",width:"100%",height:"100%",background:"var(--color-glass-bg)",border:"var(--border-width-1) solid var(--color-glass-border)",borderRadius:"var(--radius-xl)",overflow:"hidden",boxShadow:"var(--shadow-xl)",backdropFilter:"blur(var(--blur-lg))",WebkitBackdropFilter:"blur(var(--blur-lg))"},children:[g.jsxs("div",{className:"module-window-header",style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"var(--space-component-md) var(--space-component-lg)",background:"rgba(42, 42, 50, 0.5)",borderBottom:"var(--border-width-1) solid var(--color-border-subtle)",cursor:n.maximized?"default":"move",userSelect:"none"},children:[g.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"var(--gap-md)"},children:[d.icon&&g.jsx("span",{style:{fontSize:16},children:d.icon}),g.jsx("span",{style:{color:"var(--color-text-primary)",fontSize:"var(--font-size-body-sm)",fontWeight:"var(--font-weight-semibold)",fontFamily:"var(--font-family-sans)"},children:d.name})]}),g.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"var(--gap-xs)"},children:[g.jsx("button",{onClick:c,"aria-label":n.maximized?"Restore window":"Maximize window",title:n.maximized?"Restore":"Maximize",style:{background:"transparent",border:"none",color:"var(--color-text-secondary)",fontSize:"16px",cursor:"pointer",padding:"var(--spacing-1) var(--spacing-2)",lineHeight:1,borderRadius:"var(--radius-md)",transition:"var(--transition-colors)",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:v=>{v.currentTarget.style.color="var(--color-text-primary)",v.currentTarget.style.background="var(--color-bg-elevated)"},onMouseLeave:v=>{v.currentTarget.style.color="var(--color-text-secondary)",v.currentTarget.style.background="transparent"},children:n.maximized?g.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"1.5",children:[g.jsx("rect",{x:"4",y:"4",width:"6",height:"6"}),g.jsx("path",{d:"M2 2h4v4M12 12H8V8"})]}):g.jsx("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"1.5",children:g.jsx("rect",{x:"2",y:"2",width:"10",height:"10"})})}),g.jsx("button",{onClick:l,"aria-label":"Close window",title:"Close",style:{background:"transparent",border:"none",color:"var(--color-text-secondary)",fontSize:"var(--font-size-h3)",cursor:"pointer",padding:"var(--spacing-1) var(--spacing-2)",lineHeight:1,borderRadius:"var(--radius-md)",transition:"var(--transition-colors)",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:v=>{v.currentTarget.style.color="var(--color-error)",v.currentTarget.style.background="var(--color-error-bg)"},onMouseLeave:v=>{v.currentTarget.style.color="var(--color-text-secondary)",v.currentTarget.style.background="transparent"},children:"×"})]})]}),g.jsx("div",{style:{flex:1,overflow:"hidden",background:"var(--color-bg-surface)"},children:g.jsx(p,{context:o})})]})})});az.displayName="ModuleWindow";const mV=()=>{const e=_e(f=>f.graph.edgeType),n=_e(f=>f.graph.edgeStrokeWidth),a=_e(f=>f.graph.edgeAnimation),i=_e(f=>f.graph.showEdgeLabels),o=_e(f=>f.setEdgeType),l=_e(f=>f.setEdgeStrokeWidth),c=_e(f=>f.setEdgeAnimation),d=_e(f=>f.setShowEdgeLabels);return g.jsxs("div",{children:[g.jsxs("div",{className:"settings-section",children:[g.jsx("h3",{className:"settings-section-title",children:"Edge Appearance"}),g.jsxs("div",{className:"settings-field",children:[g.jsx("label",{htmlFor:"edge-type",className:"settings-label",children:"Edge Type"}),g.jsx("p",{className:"settings-description",children:"Choose how connections between nodes are drawn"}),g.jsxs("select",{id:"edge-type",value:e,onChange:f=>o(f.target.value),className:"settings-select",children:[g.jsx("option",{value:"bezier",children:"Bezier (Curved) - Default"}),g.jsx("option",{value:"smoothstep",children:"Smooth Step"}),g.jsx("option",{value:"straight",children:"Straight (90° Angles)"}),g.jsx("option",{value:"simplebezier",children:"Simple Bezier"})]})]}),g.jsxs("div",{className:"settings-field",children:[g.jsxs("label",{htmlFor:"edge-width",className:"settings-label",children:["Edge Stroke Width: ",n,"px"]}),g.jsx("input",{id:"edge-width",type:"range",min:"1",max:"5",step:"0.5",value:n,onChange:f=>l(parseFloat(f.target.value)),className:"settings-input"})]})]}),g.jsxs("div",{className:"settings-section",children:[g.jsx("h3",{className:"settings-section-title",children:"Edge Behavior"}),g.jsxs("div",{className:"settings-field",children:[g.jsxs("div",{className:"settings-checkbox-wrapper",children:[g.jsx("input",{id:"edge-animation",type:"checkbox",checked:a,onChange:f=>c(f.target.checked),className:"settings-checkbox"}),g.jsx("label",{htmlFor:"edge-animation",className:"settings-checkbox-label",children:"Enable edge animation"})]}),g.jsx("p",{className:"settings-description",children:"Animate message flow along edges (may impact performance)"})]}),g.jsxs("div",{className:"settings-field",children:[g.jsxs("div",{className:"settings-checkbox-wrapper",children:[g.jsx("input",{id:"edge-labels",type:"checkbox",checked:i,onChange:f=>d(f.target.checked),className:"settings-checkbox"}),g.jsx("label",{htmlFor:"edge-labels",className:"settings-checkbox-label",children:"Show edge labels"})]}),g.jsx("p",{className:"settings-description",children:"Display correlation IDs and other metadata on edges"})]})]})]})},iz="/api";async function yV(){try{const e=await fetch(`${iz}/themes`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!e.ok)throw new Error(`Failed to fetch themes: ${e.statusText}`);return(await e.json()).themes}catch(e){throw console.error("Error fetching theme list:",e),e}}async function UN(e){try{const n=await fetch(`${iz}/themes/${e}`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!n.ok)throw new Error(`Failed to fetch theme "${e}": ${n.statusText}`);const a=await n.json();return{name:a.name,colors:a.data.colors}}catch(n){throw console.error(`Error fetching theme "${e}":`,n),n}}const Iy=["dracula","nord","catppuccin-mocha","tokyonight","gruvboxdark","solarized-dark","github-dark","one-half-dark","monokai","material"];function ms(e,n){const a=parseInt(e.slice(1,3),16),i=parseInt(e.slice(3,5),16),o=parseInt(e.slice(5,7),16);return`rgba(${a}, ${i}, ${o}, ${n})`}function VN(e){const n=document.documentElement,{colors:a}=e;n.style.setProperty("--color-bg-base",a.primary.background),n.style.setProperty("--color-bg-elevated",a.selection.background),n.style.setProperty("--color-bg-surface",a.normal.black),n.style.setProperty("--color-bg-overlay",a.bright.black),n.style.setProperty("--color-bg-float",ms(a.normal.white,.1)),n.style.setProperty("--color-text-primary",a.primary.foreground),n.style.setProperty("--color-text-secondary",a.bright.white),n.style.setProperty("--color-text-tertiary",a.selection.text),n.style.setProperty("--color-text-muted",a.cursor.text),n.style.setProperty("--color-text-on-primary",a.selection.text),n.style.setProperty("--color-primary-500",a.normal.blue),n.style.setProperty("--color-primary-400",a.bright.blue),n.style.setProperty("--color-primary-600",a.normal.blue),n.style.setProperty("--color-secondary-500",a.normal.magenta),n.style.setProperty("--color-secondary-400",a.bright.magenta),n.style.setProperty("--color-tertiary-500",a.normal.cyan),n.style.setProperty("--color-success",a.normal.green),n.style.setProperty("--color-success-light",a.bright.green),n.style.setProperty("--color-error",a.normal.red),n.style.setProperty("--color-error-light",a.bright.red),n.style.setProperty("--color-warning",a.normal.yellow),n.style.setProperty("--color-warning-light",a.bright.yellow),n.style.setProperty("--color-info",a.normal.cyan),n.style.setProperty("--color-info-light",a.bright.cyan);const i=n.style.getPropertyValue("--agent-idle-color");(!i||i==="#60a5fa")&&n.style.setProperty("--agent-idle-color",a.normal.cyan);const o=n.style.getPropertyValue("--agent-active-color");(!o||o==="#10b981")&&n.style.setProperty("--agent-active-color",a.normal.green);const l=n.style.getPropertyValue("--agent-error-color");(!l||l==="#ef4444")&&n.style.setProperty("--agent-error-color",a.normal.red),n.style.setProperty("--color-border-default",a.bright.black),n.style.setProperty("--color-border-subtle",ms(a.normal.white,.2)),n.style.setProperty("--color-border-strong",a.cursor.cursor),n.style.setProperty("--color-border-focus",a.normal.blue),n.style.setProperty("--color-border-error",a.normal.red),n.style.setProperty("--color-glass-bg",ms(a.selection.background,.8)),n.style.setProperty("--color-glow-primary",a.cursor.cursor),n.style.setProperty("--shadow-glow-primary",`0 0 0 3px ${ms(a.bright.blue,.5)}`),n.style.setProperty("--shadow-glow-error",`0 0 0 3px ${ms(a.bright.red,.5)}`),n.style.setProperty("--color-edge-default",a.bright.black),n.style.setProperty("--color-edge-message",a.bright.yellow),n.style.setProperty("--color-edge-active",a.bright.blue),n.style.setProperty("--color-node-message-border",a.normal.magenta),console.log(`[Theme] Applied theme: ${e.name}`)}function Uy(){const e=document.documentElement;e.style.setProperty("--color-bg-base","#0a0a0b"),e.style.setProperty("--color-bg-elevated","#121214"),e.style.setProperty("--color-bg-surface","#1a1a1e"),e.style.setProperty("--color-bg-overlay","#232329"),e.style.setProperty("--color-bg-float","#2a2a32"),e.style.setProperty("--color-text-primary","#e5e7eb"),e.style.setProperty("--color-text-secondary","#9ca3af"),e.style.setProperty("--color-text-tertiary","#6b7280"),e.style.setProperty("--color-primary-500","#6366f1"),e.style.setProperty("--color-primary-400","#818cf8"),e.style.setProperty("--color-primary-600","#4f46e5"),console.log("[Theme] Reset to default theme")}const bV=()=>{const[e,n]=q.useState([]),[a,i]=q.useState(!1),[o,l]=q.useState(null),[c,d]=q.useState(""),[f,h]=q.useState(null),p=_e(R=>R.appearance.theme),v=_e(R=>R.setTheme);q.useEffect(()=>{m()},[]);const m=async()=>{try{i(!0),l(null);const R=await yV();n(R)}catch(R){l("Failed to load themes. Backend may not be running."),console.error("Theme loading error:",R),n(Iy)}finally{i(!1)}},b=async R=>{try{if(l(null),R==="default"){Uy(),v("default"),h(null);return}const z=await UN(R);VN(z),v(R),h(null)}catch(z){l(`Failed to load theme "${R}"`),console.error("Theme application error:",z)}},_=async R=>{try{if(R==="default"){Uy(),h(null);return}const z=await UN(R);h(z),VN(z)}catch(z){console.error("Theme preview error:",z)}},S=()=>{Uy(),v("default"),h(null)},C=["default",...e].filter(R=>R.toLowerCase().includes(c.toLowerCase())),T=C.filter(R=>Iy.includes(R)),E=C.includes("default")?["default"]:[],N=C.filter(R=>!Iy.includes(R)&&R!=="default");return g.jsxs("div",{children:[g.jsxs("div",{className:"settings-field",children:[g.jsx("label",{htmlFor:"theme-search",className:"settings-label",children:"Search Themes"}),g.jsx("input",{id:"theme-search",type:"text",value:c,onChange:R=>d(R.target.value),placeholder:"Search 300+ themes...",className:"settings-input",disabled:a})]}),o&&g.jsx("div",{style:{padding:"var(--space-component-sm)",background:"var(--color-error-bg)",color:"var(--color-error-light)",borderRadius:"var(--radius-md)",marginBottom:"var(--space-component-md)",fontSize:"var(--font-size-caption)"},children:o}),a&&g.jsx("div",{style:{padding:"var(--space-component-md)",textAlign:"center",color:"var(--color-text-secondary)"},children:"Loading themes..."}),!a&&g.jsxs(g.Fragment,{children:[g.jsxs("div",{className:"settings-field",children:[g.jsx("label",{className:"settings-label",children:"Current Theme"}),g.jsxs("div",{style:{padding:"var(--space-component-sm)",background:"var(--color-bg-elevated)",borderRadius:"var(--radius-md)",border:"var(--border-default)",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[g.jsx("span",{style:{color:"var(--color-text-primary)"},children:p==="default"?"Default (Flock)":p}),p!=="default"&&g.jsx("button",{onClick:S,style:{padding:"4px 8px",background:"transparent",border:"var(--border-default)",borderRadius:"var(--radius-sm)",color:"var(--color-text-secondary)",fontSize:"var(--font-size-caption)",cursor:"pointer"},children:"Reset"})]})]}),E.length>0&&g.jsxs("div",{className:"settings-field",children:[g.jsx("label",{className:"settings-label",children:"Built-in Theme"}),g.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"var(--gap-xs)"},children:g.jsx("button",{onClick:()=>b("default"),onMouseEnter:()=>_("default"),style:{padding:"var(--space-component-sm)",background:p==="default"?"var(--color-primary-500)":"var(--color-bg-elevated)",border:"var(--border-default)",borderRadius:"var(--radius-md)",color:p==="default"?"white":"var(--color-text-primary)",fontSize:"var(--font-size-body-sm)",cursor:"pointer",textAlign:"left",transition:"var(--transition-all)"},children:"Default (Flock)"})})]}),T.length>0&&g.jsxs("div",{className:"settings-field",children:[g.jsx("label",{className:"settings-label",children:"Popular Themes"}),g.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"var(--gap-xs)"},children:T.map(R=>g.jsx("button",{onClick:()=>b(R),onMouseEnter:()=>_(R),style:{padding:"var(--space-component-sm)",background:p===R?"var(--color-primary-500)":"var(--color-bg-elevated)",border:"var(--border-default)",borderRadius:"var(--radius-md)",color:p===R?"white":"var(--color-text-primary)",fontSize:"var(--font-size-body-sm)",cursor:"pointer",textAlign:"left",transition:"var(--transition-all)"},children:R},R))})]}),N.length>0&&g.jsxs("div",{className:"settings-field",children:[g.jsxs("label",{className:"settings-label",children:["All Themes (",N.length,")"]}),g.jsx("div",{style:{maxHeight:"300px",overflowY:"auto",display:"flex",flexDirection:"column",gap:"var(--gap-xs)",padding:"var(--space-component-xs)",background:"var(--color-bg-base)",borderRadius:"var(--radius-md)"},children:N.map(R=>g.jsx("button",{onClick:()=>b(R),onMouseEnter:()=>_(R),style:{padding:"var(--space-component-sm)",background:p===R?"var(--color-primary-500)":"var(--color-bg-elevated)",border:"var(--border-default)",borderRadius:"var(--radius-sm)",color:p===R?"white":"var(--color-text-primary)",fontSize:"var(--font-size-body-sm)",cursor:"pointer",textAlign:"left",transition:"var(--transition-all)"},children:R},R))})]}),C.length===0&&!a&&g.jsxs("div",{style:{padding:"var(--space-component-md)",textAlign:"center",color:"var(--color-text-tertiary)"},children:['No themes found matching "',c,'"']})]}),f&&g.jsxs("div",{style:{padding:"var(--space-component-sm)",background:"var(--color-bg-overlay)",borderRadius:"var(--radius-md)",marginTop:"var(--space-component-md)",fontSize:"var(--font-size-caption)",color:"var(--color-text-tertiary)",textAlign:"center"},children:["Previewing: ",f.name," (click to apply)"]})]})},xV=()=>{const e=_e(m=>m.appearance.agentIdleColor),n=_e(m=>m.appearance.agentActiveColor),a=_e(m=>m.appearance.agentErrorColor),i=_e(m=>m.appearance.nodeShadow),o=_e(m=>m.appearance.showStatusPulse),l=_e(m=>m.appearance.compactNodeView),c=_e(m=>m.setAgentIdleColor),d=_e(m=>m.setAgentActiveColor),f=_e(m=>m.setAgentErrorColor),h=_e(m=>m.setNodeShadow),p=_e(m=>m.setShowStatusPulse),v=_e(m=>m.setCompactNodeView);return g.jsxs("div",{children:[g.jsxs("div",{className:"settings-section",children:[g.jsx("h3",{className:"settings-section-title",children:"Theme"}),g.jsx("p",{className:"settings-description",style:{marginBottom:"var(--space-component-md)"},children:"Choose from 300+ terminal color themes. Themes are loaded from the backend and applied in real-time."}),g.jsx(bV,{})]}),g.jsxs("div",{className:"settings-section",children:[g.jsx("h3",{className:"settings-section-title",children:"Agent Colors"}),g.jsxs("div",{className:"settings-field",children:[g.jsx("label",{htmlFor:"idle-color",className:"settings-label",children:"Idle Agent Color"}),g.jsx("p",{className:"settings-description",children:"Border and indicator color for idle agents"}),g.jsxs("div",{style:{display:"flex",gap:"var(--gap-sm)",alignItems:"center"},children:[g.jsx("input",{id:"idle-color",type:"color",value:e,onChange:m=>c(m.target.value),style:{width:"60px",height:"36px",cursor:"pointer"}}),g.jsx("input",{type:"text",value:e,onChange:m=>c(m.target.value),className:"settings-input",placeholder:"#60a5fa"})]})]}),g.jsxs("div",{className:"settings-field",children:[g.jsx("label",{htmlFor:"active-color",className:"settings-label",children:"Active Agent Color"}),g.jsx("p",{className:"settings-description",children:"Border and indicator color for running agents (thick border)"}),g.jsxs("div",{style:{display:"flex",gap:"var(--gap-sm)",alignItems:"center"},children:[g.jsx("input",{id:"active-color",type:"color",value:n,onChange:m=>d(m.target.value),style:{width:"60px",height:"36px",cursor:"pointer"}}),g.jsx("input",{type:"text",value:n,onChange:m=>d(m.target.value),className:"settings-input",placeholder:"#10b981"})]})]}),g.jsxs("div",{className:"settings-field",children:[g.jsx("label",{htmlFor:"error-color",className:"settings-label",children:"Error Agent Color"}),g.jsx("p",{className:"settings-description",children:"Border and indicator color for agents in error state"}),g.jsxs("div",{style:{display:"flex",gap:"var(--gap-sm)",alignItems:"center"},children:[g.jsx("input",{id:"error-color",type:"color",value:a,onChange:m=>f(m.target.value),style:{width:"60px",height:"36px",cursor:"pointer"}}),g.jsx("input",{type:"text",value:a,onChange:m=>f(m.target.value),className:"settings-input",placeholder:"#ef4444"})]})]})]}),g.jsxs("div",{className:"settings-section",children:[g.jsx("h3",{className:"settings-section-title",children:"Node Appearance"}),g.jsxs("div",{className:"settings-field",children:[g.jsx("label",{htmlFor:"node-shadow",className:"settings-label",children:"Node Shadow"}),g.jsx("p",{className:"settings-description",children:"Shadow intensity for node elevation effect"}),g.jsxs("select",{id:"node-shadow",value:i,onChange:m=>h(m.target.value),className:"settings-select",children:[g.jsx("option",{value:"none",children:"None"}),g.jsx("option",{value:"small",children:"Small"}),g.jsx("option",{value:"medium",children:"Medium (Default)"}),g.jsx("option",{value:"large",children:"Large"})]})]}),g.jsxs("div",{className:"settings-field",children:[g.jsxs("div",{className:"settings-checkbox-wrapper",children:[g.jsx("input",{id:"status-pulse",type:"checkbox",checked:o,onChange:m=>p(m.target.checked),className:"settings-checkbox"}),g.jsx("label",{htmlFor:"status-pulse",className:"settings-checkbox-label",children:"Show status pulse animation"})]}),g.jsx("p",{className:"settings-description",children:"Animate status indicator for running agents"})]}),g.jsxs("div",{className:"settings-field",children:[g.jsxs("div",{className:"settings-checkbox-wrapper",children:[g.jsx("input",{id:"compact-view",type:"checkbox",checked:l,onChange:m=>v(m.target.checked),className:"settings-checkbox"}),g.jsx("label",{htmlFor:"compact-view",className:"settings-checkbox-label",children:"Compact node view"})]}),g.jsx("p",{className:"settings-description",children:"Reduce node size and spacing (useful for large graphs)"})]})]})]})},_V=()=>{const e=_e(b=>b.advanced.layoutDirection),n=_e(b=>b.advanced.nodeSpacing),a=_e(b=>b.advanced.rankSpacing),i=_e(b=>b.advanced.debugMode),o=_e(b=>b.advanced.performanceMode),l=_e(b=>b.setLayoutDirection),c=_e(b=>b.setNodeSpacing),d=_e(b=>b.setRankSpacing),f=_e(b=>b.setDebugMode),h=_e(b=>b.setPerformanceMode),[p,v]=q.useState("Loading..."),m="0.1.1";return q.useEffect(()=>{(async()=>{try{const _=await fetch("/api/version");if(_.ok){const S=await _.json();v(S.backend_version||"Unknown")}else v("Error fetching version")}catch(_){console.error("Failed to fetch version:",_),v("Error fetching version")}})()},[]),g.jsxs("div",{children:[g.jsxs("div",{className:"settings-section",children:[g.jsx("h3",{className:"settings-section-title",children:"Graph Layout"}),g.jsxs("div",{className:"settings-field",children:[g.jsx("label",{htmlFor:"layout-direction",className:"settings-label",children:"Layout Direction"}),g.jsx("p",{className:"settings-description",children:"Direction for manual layout algorithm (right-click → Auto Layout)"}),g.jsxs("select",{id:"layout-direction",value:e,onChange:b=>l(b.target.value),className:"settings-select",children:[g.jsx("option",{value:"LR",children:"Left to Right (Default)"}),g.jsx("option",{value:"TB",children:"Top to Bottom"})]})]}),g.jsxs("div",{className:"settings-field",children:[g.jsxs("label",{htmlFor:"node-spacing",className:"settings-label",children:["Node Spacing: ",n,"px"]}),g.jsx("p",{className:"settings-description",children:"Horizontal space between nodes when using manual layout (affects edge label visibility)"}),g.jsx("input",{id:"node-spacing",type:"range",min:"25",max:"150",step:"5",value:n,onChange:b=>c(parseFloat(b.target.value)),className:"settings-input"})]}),g.jsxs("div",{className:"settings-field",children:[g.jsxs("label",{htmlFor:"rank-spacing",className:"settings-label",children:["Rank Spacing: ",a,"px"]}),g.jsx("p",{className:"settings-description",children:"Vertical space between graph layers when using manual layout"}),g.jsx("input",{id:"rank-spacing",type:"range",min:"50",max:"300",step:"10",value:a,onChange:b=>d(parseFloat(b.target.value)),className:"settings-input"})]})]}),g.jsxs("div",{className:"settings-section",children:[g.jsx("h3",{className:"settings-section-title",children:"Developer Options"}),g.jsxs("div",{className:"settings-field",children:[g.jsxs("div",{className:"settings-checkbox-wrapper",children:[g.jsx("input",{id:"debug-mode",type:"checkbox",checked:i,onChange:b=>f(b.target.checked),className:"settings-checkbox"}),g.jsx("label",{htmlFor:"debug-mode",className:"settings-checkbox-label",children:"Debug mode"})]}),g.jsx("p",{className:"settings-description",children:"Show node IDs, detailed message counts, and verbose console logging"})]}),g.jsxs("div",{className:"settings-field",children:[g.jsxs("div",{className:"settings-checkbox-wrapper",children:[g.jsx("input",{id:"performance-mode",type:"checkbox",checked:o,onChange:b=>h(b.target.checked),className:"settings-checkbox"}),g.jsx("label",{htmlFor:"performance-mode",className:"settings-checkbox-label",children:"Performance mode"})]}),g.jsx("p",{className:"settings-description",children:"Disable animations, shadows, and blur effects for better performance"})]})]}),g.jsxs("div",{className:"settings-section",children:[g.jsx("h3",{className:"settings-section-title",children:"Information"}),g.jsxs("div",{className:"settings-field",children:[g.jsxs("p",{className:"settings-description",style:{marginBottom:"var(--spacing-2)"},children:[g.jsx("strong",{children:"Dashboard Version:"})," ",m]}),g.jsxs("p",{className:"settings-description",style:{marginBottom:"var(--spacing-2)"},children:[g.jsx("strong",{children:"Backend Version:"})," ",p]}),g.jsxs("p",{className:"settings-description",style:{marginBottom:"var(--spacing-2)"},children:[g.jsx("strong",{children:"React Flow Version:"})," 12.8.6"]}),g.jsxs("p",{className:"settings-description",children:[g.jsx("strong",{children:"Local Storage Used:"})," ",localStorage.length," keys"]})]})]})]})},SV=()=>{const e="mgljr9wlkbscmlh",n="2025-10-11T00:38:22.437Z",a=new Date(n).toLocaleString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"});return g.jsxs("div",{style:{fontSize:"10px",color:"var(--color-text-tertiary, #6b7280)",fontFamily:"monospace",lineHeight:"1.4",opacity:.7},children:[g.jsxs("div",{children:["Build: ",e]}),g.jsx("div",{children:a})]})},wV=()=>{const[e,n]=q.useState("graph"),a=_e(c=>c.setShowSettings),i=_e(c=>c.resetToDefaults),o=()=>{a(!1)},l=()=>{confirm("Reset all settings to defaults? This cannot be undone.")&&i()};return g.jsx("div",{className:"settings-panel",children:g.jsxs("div",{className:"settings-panel-inner",children:[g.jsxs("div",{className:"settings-header",children:[g.jsx("h2",{className:"settings-title",children:"Settings"}),g.jsx("button",{onClick:o,className:"settings-close-button","aria-label":"Close settings",title:"Close settings (Esc)",children:g.jsx("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:g.jsx("path",{d:"M15 5L5 15M5 5l10 10",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]}),g.jsxs("div",{className:"settings-tabs",children:[g.jsxs("button",{onClick:()=>n("graph"),className:`settings-tab ${e==="graph"?"active":""}`,children:[g.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:[g.jsx("circle",{cx:"4",cy:"8",r:"2",stroke:"currentColor",strokeWidth:"1.5"}),g.jsx("circle",{cx:"12",cy:"4",r:"2",stroke:"currentColor",strokeWidth:"1.5"}),g.jsx("circle",{cx:"12",cy:"12",r:"2",stroke:"currentColor",strokeWidth:"1.5"}),g.jsx("path",{d:"M6 8h4M10 5l2 6",stroke:"currentColor",strokeWidth:"1.5"})]}),"Graph"]}),g.jsxs("button",{onClick:()=>n("appearance"),className:`settings-tab ${e==="appearance"?"active":""}`,children:[g.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:g.jsx("path",{d:"M8 2v12M2 8h12M4.343 4.343l7.314 7.314M11.657 4.343L4.343 11.657",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})}),"Appearance"]}),g.jsxs("button",{onClick:()=>n("advanced"),className:`settings-tab ${e==="advanced"?"active":""}`,children:[g.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:[g.jsx("path",{d:"M8 10.667a2.667 2.667 0 100-5.334 2.667 2.667 0 000 5.334z",stroke:"currentColor",strokeWidth:"1.5"}),g.jsx("path",{d:"M13 8a5 5 0 01-5 5m0-10a5 5 0 015 5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})]}),"Advanced"]})]}),g.jsxs("div",{className:"settings-content",children:[e==="graph"&&g.jsx(mV,{}),e==="appearance"&&g.jsx(xV,{}),e==="advanced"&&g.jsx(_V,{})]}),g.jsxs("div",{className:"settings-footer",children:[g.jsx("div",{className:"settings-footer-left",children:g.jsx(SV,{})}),g.jsx("button",{onClick:l,className:"settings-reset-button",children:"Reset to Defaults"})]})]})})},Ba=typeof navigator<"u"&&navigator.platform.toUpperCase().indexOf("MAC")>=0,EV=[{keys:Ba?["⌘","M"]:["Ctrl","M"],description:"Toggle Agent/Blackboard View",category:"Navigation"},{keys:Ba?["⌘","F"]:["Ctrl","F"],description:"Focus filter input",category:"Navigation"},{keys:Ba?["⌘","Shift","P"]:["Ctrl","Shift","P"],description:"Toggle Publish Panel",category:"Panels"},{keys:Ba?["⌘","Shift","D"]:["Ctrl","Shift","D"],description:"Toggle Agent Details",category:"Panels"},{keys:Ba?["⌘","Shift","F"]:["Ctrl","Shift","F"],description:"Toggle Filters Panel",category:"Panels"},{keys:Ba?["⌘",","]:["Ctrl",","],description:"Toggle Settings Panel",category:"Panels"},{keys:["Esc"],description:"Close panels and windows",category:"General"},{keys:Ba?["⌘","/"]:["Ctrl","/"],description:"Show this help dialog",category:"General"}],CV=({isOpen:e,onClose:n})=>{if(q.useEffect(()=>{if(!e)return;const i=o=>{o.key==="Escape"&&(o.preventDefault(),o.stopPropagation(),n())};return window.addEventListener("keydown",i,{capture:!0}),()=>{window.removeEventListener("keydown",i,{capture:!0})}},[e,n]),!e)return null;const a=EV.reduce((i,o)=>(i[o.category]||(i[o.category]=[]),i[o.category].push(o),i),{});return g.jsx("div",{className:"keyboard-shortcuts-overlay",onClick:n,children:g.jsxs("div",{className:"keyboard-shortcuts-dialog",onClick:i=>i.stopPropagation(),children:[g.jsxs("div",{className:"keyboard-shortcuts-header",children:[g.jsx("h2",{className:"keyboard-shortcuts-title",children:"Keyboard Shortcuts"}),g.jsx("button",{className:"keyboard-shortcuts-close",onClick:n,"aria-label":"Close keyboard shortcuts",children:g.jsx("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:g.jsx("path",{d:"M15 5L5 15M5 5l10 10",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]}),g.jsx("div",{className:"keyboard-shortcuts-content",children:Object.entries(a).map(([i,o])=>g.jsxs("div",{className:"keyboard-shortcuts-category",children:[g.jsx("h3",{className:"keyboard-shortcuts-category-title",children:i}),g.jsx("div",{className:"keyboard-shortcuts-list",children:o.map((l,c)=>g.jsxs("div",{className:"keyboard-shortcut-item",children:[g.jsx("div",{className:"keyboard-shortcut-keys",children:l.keys.map((d,f)=>g.jsxs(Kn.Fragment,{children:[g.jsx("kbd",{className:"keyboard-key",children:d}),f<l.keys.length-1&&g.jsx("span",{className:"keyboard-key-separator",children:"+"})]},f))}),g.jsx("div",{className:"keyboard-shortcut-description",children:l.description})]},c))})]},i))}),g.jsx("div",{className:"keyboard-shortcuts-footer",children:g.jsxs("p",{className:"keyboard-shortcuts-hint",children:["Press ",g.jsx("kbd",{className:"keyboard-key",children:"Esc"})," or click outside to close"]})})]})})},TV=()=>{const e=jr(c=>c.instances),n=jr(c=>c.addModule),a=q.useRef(new Map),i=q.useRef({});q.useEffect(()=>{(async()=>{try{const d=await Cn.getAllModuleInstances();d.forEach(f=>{const h={id:f.instance_id,type:f.type,position:f.position,size:f.size,visible:f.visible};n(h)}),console.log(`[ModulePersistence] Restored ${d.length} module instances`)}catch(d){console.error("[ModulePersistence] Failed to load module instances:",d)}})()},[]);const o=q.useCallback(async c=>{i.current[c.id]&&clearTimeout(i.current[c.id]),i.current[c.id]=setTimeout(async()=>{try{const d=new Date().toISOString(),f={instance_id:c.id,type:c.type,position:c.position,size:c.size,visible:c.visible,created_at:d,updated_at:d};await Cn.saveModuleInstance(f),console.log(`[ModulePersistence] Saved instance: ${c.id}`)}catch(d){console.error(`[ModulePersistence] Failed to save instance ${c.id}:`,d)}delete i.current[c.id]},300)},[]),l=q.useCallback(async c=>{i.current[c]&&(clearTimeout(i.current[c]),delete i.current[c]);try{await Cn.deleteModuleInstance(c),console.log(`[ModulePersistence] Deleted instance: ${c}`)}catch(d){console.error(`[ModulePersistence] Failed to delete instance ${c}:`,d)}},[]);q.useEffect(()=>{const c=new Set(e.keys()),d=new Set(a.current.keys());c.forEach(f=>{if(!d.has(f)){const h=e.get(f);h&&(console.log(`[ModulePersistence] Detected new instance: ${f}`),o(h))}}),e.forEach((f,h)=>{const p=a.current.get(h);if(p){const v=p.position.x!==f.position.x||p.position.y!==f.position.y,m=p.size.width!==f.size.width||p.size.height!==f.size.height,b=p.visible!==f.visible;(v||m||b)&&(console.log(`[ModulePersistence] Detected update to instance: ${h}`),o(f))}}),d.forEach(f=>{c.has(f)||(console.log(`[ModulePersistence] Detected removed instance: ${f}`),l(f))}),a.current=new Map(e)},[e,o,l]),q.useEffect(()=>()=>{Object.values(i.current).forEach(clearTimeout)},[])},oz=(e={})=>{q.useEffect(()=>{const n=a=>{const i=a.ctrlKey||a.metaKey;if(i&&a.key===","){a.preventDefault();const o=_e.getState().ui.showSettings;_e.getState().setShowSettings(!o);return}if(i&&a.shiftKey&&a.key==="F"){a.preventDefault();const o=_e.getState().ui.showFilters;_e.getState().setShowFilters(!o);return}if(i&&a.shiftKey&&a.key==="P"){a.preventDefault();const o=_e.getState().ui.showControls;_e.getState().setShowControls(!o);return}if(i&&a.shiftKey&&a.key==="D"){a.preventDefault(),e.onToggleAgentDetails&&e.onToggleAgentDetails();return}if(i&&a.key==="/"){a.preventDefault(),e.onToggleHelp&&e.onToggleHelp();return}if(i&&a.key==="m"){if(a.preventDefault(),e.onToggleMode)e.onToggleMode();else{const o=ut.getState().mode;ut.getState().setMode(o==="agent"?"blackboard":"agent")}return}if(i&&a.key==="f"){const o=document.activeElement;if(!(o?.tagName==="INPUT"||o?.tagName==="TEXTAREA"))if(a.preventDefault(),e.onFocusFilter)e.onFocusFilter();else{const c=document.querySelector('input[placeholder*="correlation"], input[placeholder*="Correlation"]');c&&(c.focus(),c.select())}return}if(a.key==="Escape"){if(e.onCloseWindows)e.onCloseWindows();else{const{showSettings:o,showFilters:l,showControls:c}=_e.getState().ui,d=ut.getState().detailWindows;o?(a.preventDefault(),_e.getState().setShowSettings(!1)):c?(a.preventDefault(),_e.getState().setShowControls(!1)):l?(a.preventDefault(),_e.getState().setShowFilters(!1)):d.size>0&&(a.preventDefault(),d.clear(),ut.setState({detailWindows:new Map}))}return}};return window.addEventListener("keydown",n),()=>{window.removeEventListener("keydown",n)}},[e])},jV="_connectionBadge_kl6ey_1",NV="_hasError_kl6ey_27",RV="_connected_kl6ey_37",MV="_connecting_kl6ey_49",AV="_reconnecting_kl6ey_51",zV="_disconnected_kl6ey_63",DV="_statusIndicator_kl6ey_77",kV="_statusPulse_kl6ey_1",OV="_statusText_kl6ey_121",$i={connectionBadge:jV,hasError:NV,connected:RV,connecting:MV,reconnecting:AV,disconnected:zV,statusIndicator:DV,statusPulse:kV,statusText:OV},qV=({status:e,attempts:n,error:a})=>{const i={connected:"Connected",connecting:"Connecting...",reconnecting:`Reconnecting (${n})...`,disconnected:"Disconnected"},o=[$i.connectionBadge,$i[e],a?$i.hasError:""].filter(Boolean).join(" "),l=[$i.statusIndicator,$i[e]].join(" ");return g.jsxs("div",{className:o,title:a||void 0,role:"status","aria-live":"polite","aria-label":`WebSocket connection status: ${i[e]}`,children:[g.jsx("div",{className:l,"aria-hidden":"true"}),g.jsx("span",{className:$i.statusText,children:i[e]})]})},BV=()=>{const e=at(i=>i.status),n=at(i=>i.reconnectAttempts),a=at(i=>i.lastError);return g.jsx(qV,{status:e,attempts:n,error:a})},LV=()=>{const e=ut(_=>_.mode),n=ut(_=>_.setMode),a=jr(_=>_.instances),i=ut(_=>_.detailWindows),o=_e(_=>_.ui.showFilters),l=_e(_=>_.ui.showControls),c=_e(_=>_.ui.showSettings),d=_e(_=>_.setShowFilters),f=_e(_=>_.setShowControls),h=_e(_=>_.setShowSettings),[p,v]=q.useState(!1);TV();const m=()=>{const _=ut.getState().detailWindows,S=Me.getState().agents;_.size>0?_.forEach((w,C)=>{ut.getState().closeDetailWindow(C)}):S.forEach(w=>{ut.getState().openDetailWindow(w.id)})};oz({onToggleHelp:()=>v(_=>!_),onToggleAgentDetails:m});const b=()=>{confirm("Clear all dashboard data? This will remove all agents, messages, and session data.")&&(Me.setState({agents:new Map,messages:new Map,events:[],runs:new Map,nodes:[],edges:[]}),ut.setState({mode:"agent"}),Te.setState({correlationId:void 0,timeRange:void 0}),jr.getState().instances.clear(),indexedDB.databases().then(_=>{_.forEach(S=>{S.name&&indexedDB.deleteDatabase(S.name)})}),localStorage.clear(),window.location.reload())};return g.jsxs("div",{className:"dashboard-layout",children:[g.jsxs("header",{className:"dashboard-header",children:[g.jsx("h1",{className:"dashboard-title",children:"🦆🐓 Flock 🐤🐧"}),g.jsxs("div",{className:"view-toggle-container",children:[g.jsx("span",{className:"view-toggle-label",children:"View:"}),g.jsxs("div",{className:"view-toggle-group",children:[g.jsx("button",{type:"button",onClick:()=>n("agent"),className:`view-toggle-button ${e==="agent"?"active":""}`,children:"Agent View"}),g.jsx("button",{type:"button",onClick:()=>n("blackboard"),className:`view-toggle-button ${e==="blackboard"?"active":""}`,children:"Blackboard View"})]})]}),g.jsxs("div",{className:"dashboard-actions",children:[g.jsxs("button",{type:"button",onClick:()=>f(!l),className:`controls-toggle primary ${l?"active":""}`,title:"Publish artifacts to the blackboard (Ctrl+Shift+P)","aria-pressed":l?"true":"false","aria-label":l?"Publish panel open":"Publish panel closed",children:[g.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:g.jsx("path",{d:"M8 2.667v10.666M2.667 8h10.666",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),g.jsx("span",{children:"Publish"})]}),g.jsxs("button",{type:"button",onClick:m,className:`controls-toggle ${i.size>0?"active":""}`,title:`${i.size>0?"Close":"Show"} agent detail windows (Ctrl+Shift+D)`,"aria-pressed":i.size>0?"true":"false","aria-label":i.size>0?"Agent details shown":"Agent details hidden",children:[g.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:g.jsx("path",{d:"M2 4.667h12M2 8h12M2 11.333h12",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),g.jsx("span",{children:"Agent Details"})]}),g.jsxs("button",{type:"button",onClick:()=>h(!c),className:`controls-toggle ${c?"active":""}`,title:`${c?"Hide":"Show"} settings panel (Ctrl+,)`,"aria-pressed":c?"true":"false","aria-label":c?"Settings shown":"Settings hidden",children:[g.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:[g.jsx("path",{d:"M8 10a2 2 0 100-4 2 2 0 000 4z",stroke:"currentColor",strokeWidth:"1.5"}),g.jsx("path",{d:"M13.333 8c0-.367-.2-.7-.533-.867l-.933-.467a.933.933 0 01-.467-.8v-.133c0-.334.133-.6.467-.8l.933-.467c.333-.166.533-.5.533-.866 0-.367-.2-.7-.533-.867L11.867 2.4a.933.933 0 01-.467-.8V1.333c0-.366-.233-.666-.6-.666H9.2c-.366 0-.666.3-.666.666V1.6c0 .334-.267.634-.6.8l-.934.467c-.333.166-.7.166-1 0l-.933-.467a.933.933 0 00-.8 0L2.533 3.067c-.333.166-.533.5-.533.866 0 .367.2.7.533.867l.933.467c.334.2.467.466.467.8v.133c0 .334-.133.6-.467.8l-.933.467c-.333.166-.533.5-.533.866 0 .367.2.7.533.867l.934.533c.333.2.6.5.6.8v.267c0 .366.3.666.666.666h1.6c.367 0 .667-.3.667-.666v-.267c0-.3.267-.6.6-.8l.933-.533c.334-.167.7-.167 1 0l.934.533c.333.2.6.5.6.8v.267c0 .366.3.666.666.666H9.2c.367 0 .667-.3.667-.666v-.267c0-.3.266-.6.6-.8l.933-.533c.333-.167.533-.5.533-.867z",stroke:"currentColor",strokeWidth:"1.5"})]}),g.jsx("span",{children:"Settings"})]}),g.jsx("button",{type:"button",onClick:()=>v(!0),className:"icon-button help-button",title:"Keyboard shortcuts (Ctrl+/)","aria-label":"Show keyboard shortcuts",children:g.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:[g.jsx("circle",{cx:"8",cy:"8",r:"6.5",stroke:"currentColor",strokeWidth:"1.5"}),g.jsx("path",{d:"M8 11.5v-.5M8 8.5v-2a1.5 1.5 0 10-1.5-1.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"}),g.jsx("circle",{cx:"8",cy:"11.5",r:"0.5",fill:"currentColor"})]})}),g.jsx("button",{type:"button",onClick:b,className:"icon-button clear-button",title:"Clear all dashboard data","aria-label":"Clear all dashboard data",children:g.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:g.jsx("path",{d:"M2 4h12M5.333 4V2.667a1.333 1.333 0 011.334-1.334h2.666a1.333 1.333 0 011.334 1.334V4m2 0v9.333a1.333 1.333 0 01-1.334 1.334H4.667a1.333 1.333 0 01-1.334-1.334V4h9.334z",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),g.jsx(BV,{})]})]}),g.jsx("div",{className:"filter-pills-bar",children:g.jsx(uV,{})}),o&&g.jsx(XU,{onClose:()=>d(!1)}),g.jsx("div",{className:"dashboard-main",children:g.jsx("main",{className:"graph-container",children:g.jsx(SR,{children:g.jsx(N7,{})})})}),g.jsx(oU,{}),Array.from(a.values()).map(_=>g.jsx(az,{instanceId:_.id},_.id)),l&&g.jsx(gV,{}),c&&g.jsx(wV,{}),g.jsx(CV,{isOpen:p,onClose:()=>v(!1)})]})},HV="_container_z8335_5",IV="_content_z8335_23",UV="_icon_z8335_43",VV="_title_z8335_55",FV="_description_z8335_71",PV="_actions_z8335_175",GV="_primaryButton_z8335_187",$V="_secondaryButton_z8335_245",da={container:HV,content:IV,icon:UV,title:VV,description:FV,actions:PV,primaryButton:GV,secondaryButton:$V};class YV extends q.Component{constructor(n){super(n),this.state={hasError:!1,error:null,errorInfo:null}}static getDerivedStateFromError(n){return{hasError:!0,error:n}}componentDidCatch(n,a){console.error("ErrorBoundary caught an error:",n,a),this.setState({errorInfo:a})}handleReset=()=>{this.setState({hasError:!1,error:null,errorInfo:null})};handleReload=()=>{window.location.reload()};render(){return this.state.hasError?this.props.fallback?this.props.fallback:g.jsx("div",{className:da.container,role:"alert",children:g.jsxs("div",{className:da.content,children:[g.jsx("div",{className:da.icon,children:g.jsxs("svg",{width:"64",height:"64",viewBox:"0 0 64 64",fill:"none",children:[g.jsx("circle",{cx:"32",cy:"32",r:"28",stroke:"currentColor",strokeWidth:"2",fill:"none"}),g.jsx("path",{d:"M32 20v16M32 44v.5",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round"})]})}),g.jsx("h2",{className:da.title,children:"Something went wrong"}),g.jsx("p",{className:da.description,children:"An unexpected error occurred. You can try resetting the component or reloading the page."}),this.state.error&&!1,g.jsxs("div",{className:da.actions,children:[g.jsx("button",{className:da.primaryButton,onClick:this.handleReset,children:"Try Again"}),g.jsx("button",{className:da.secondaryButton,onClick:this.handleReload,children:"Reload Page"})]})]})}):this.props.children}}function WV(e,n,a){performance.mark(a);const i=performance.measure(`${e}-render`,n,a);return console.log(`[Performance] ${e} render time: ${i.duration.toFixed(2)}ms`),i.duration}const sz=({value:e,maxStringLength:n=200})=>{const[a,i]=q.useState(2);try{const o=JSON.parse(e);return typeof o=="string"||typeof o=="number"||typeof o=="boolean"||o===null?g.jsx("div",{style:{fontFamily:"var(--font-family-mono)",fontSize:"var(--font-size-body-xs)",color:"var(--color-text-secondary)",wordBreak:"break-word"},children:String(o)}):g.jsxs("div",{children:[g.jsxs("div",{style:{display:"flex",gap:"var(--gap-xs)",marginBottom:"var(--gap-xs)"},children:[g.jsx("button",{onClick:()=>i(!1),style:{padding:"2px 8px",fontSize:"var(--font-size-body-xs)",color:"var(--color-text-secondary)",backgroundColor:"var(--color-bg-elevated)",border:"1px solid var(--color-border-subtle)",borderRadius:"var(--radius-xs)",cursor:"pointer",fontFamily:"var(--font-family-mono)"},onMouseEnter:l=>{l.currentTarget.style.backgroundColor="var(--color-bg-hover)"},onMouseLeave:l=>{l.currentTarget.style.backgroundColor="var(--color-bg-elevated)"},children:"Expand All"}),g.jsx("button",{onClick:()=>i(!0),style:{padding:"2px 8px",fontSize:"var(--font-size-body-xs)",color:"var(--color-text-secondary)",backgroundColor:"var(--color-bg-elevated)",border:"1px solid var(--color-border-subtle)",borderRadius:"var(--radius-xs)",cursor:"pointer",fontFamily:"var(--font-family-mono)"},onMouseEnter:l=>{l.currentTarget.style.backgroundColor="var(--color-bg-hover)"},onMouseLeave:l=>{l.currentTarget.style.backgroundColor="var(--color-bg-elevated)"},children:"Collapse All"})]}),g.jsx("div",{style:{maxHeight:"400px",overflowY:"auto",overflowX:"auto"},children:g.jsx(Ye,{value:o,collapsed:a,displayDataTypes:!1,shortenTextAfterLength:0,style:{backgroundColor:"var(--color-bg-elevated)",fontSize:"var(--font-size-body-xs)",fontFamily:"var(--font-family-mono)",padding:"var(--space-component-sm)",borderRadius:"var(--radius-sm)","--w-rjv-line-color":"var(--color-text-tertiary)","--w-rjv-key-string":"var(--color-primary-500)","--w-rjv-info-color":"var(--color-text-secondary)","--w-rjv-curlybraces-color":"var(--color-text-tertiary)","--w-rjv-brackets-color":"var(--color-text-tertiary)","--w-rjv-arrow-color":"var(--color-text-tertiary)","--w-rjv-edit-color":"var(--color-primary-500)","--w-rjv-add-color":"var(--color-success)","--w-rjv-del-color":"var(--color-error)","--w-rjv-update-color":"var(--color-warning)","--w-rjv-border-left-color":"var(--color-border-subtle)"}})})]})}catch{const l=e.length>n?e.substring(0,n)+"...":e;return g.jsx("div",{style:{fontFamily:"var(--font-family-mono)",fontSize:"var(--font-size-body-xs)",color:"var(--color-text-secondary)",wordBreak:"break-word",whiteSpace:"pre-wrap"},children:l})}},XV=()=>{const[e,n]=q.useState(!1),[a,i]=q.useState(!0),[o,l]=q.useState(!1),[c,d]=q.useState(30),[f,h]=q.useState([]),[p,v]=q.useState([]),[m,b]=q.useState([]),[_,S]=q.useState([]),[w,C]=q.useState(null),[T,E]=q.useState(!1),[N,R]=q.useState(null),[z,j]=q.useState(null);q.useEffect(()=>{A(),D(),I()},[]);const A=async()=>{try{const H=await fetch("/api/traces/services");if(!H.ok)throw new Error("Failed to load trace services");const O=await H.json();h(O.services),v(O.operations)}catch(H){console.error("Error loading trace services:",H)}},D=async()=>{try{const H=await fetch("/api/traces/stats");if(!H.ok)throw new Error("Failed to load trace stats");const O=await H.json();C(O)}catch(H){console.error("Error loading trace stats:",H)}},I=async()=>{n(!0),i(!0),l(!1),d(30),b(["flock","agent","dspyengine","outpututilitycomponent"]),S(["DashboardEventCollector.set_websocket_manager"])},P=async()=>{if(confirm("Clear all traces from the database? This cannot be undone.")){E(!0),R(null),j(null);try{const H=await fetch("/api/traces/clear",{method:"POST"});if(!H.ok)throw new Error("Failed to clear traces");const O=await H.json();O.success?(j(`Successfully deleted ${O.deleted_count} trace spans`),D()):R(O.error||"Failed to clear traces")}catch(H){R(H instanceof Error?H.message:"Unknown error")}finally{E(!1),setTimeout(()=>j(null),5e3)}}},V=async()=>{E(!0),R(null),j(null);try{j("Settings saved successfully (persistence coming soon)")}catch(H){R(H instanceof Error?H.message:"Failed to save settings")}finally{E(!1),setTimeout(()=>j(null),5e3)}},$=H=>H?new Date(H).toLocaleString():"N/A",L=H=>H<1?`${(H*1024).toFixed(1)} KB`:`${H.toFixed(2)} MB`;return g.jsxs("div",{children:[N&&g.jsx("div",{className:"settings-message settings-message-error",style:{padding:"var(--space-component-sm)",marginBottom:"var(--space-component-md)",backgroundColor:"rgba(239, 68, 68, 0.1)",border:"1px solid rgba(239, 68, 68, 0.3)",borderRadius:"var(--radius-md)",color:"#ef4444"},children:N}),z&&g.jsx("div",{className:"settings-message settings-message-success",style:{padding:"var(--space-component-sm)",marginBottom:"var(--space-component-md)",backgroundColor:"rgba(16, 185, 129, 0.1)",border:"1px solid rgba(16, 185, 129, 0.3)",borderRadius:"var(--radius-md)",color:"#10b981"},children:z}),g.jsxs("div",{className:"settings-section",children:[g.jsx("h3",{className:"settings-section-title",children:"OpenTelemetry Tracing"}),g.jsxs("div",{className:"settings-field",children:[g.jsxs("div",{className:"settings-checkbox-wrapper",children:[g.jsx("input",{id:"auto-trace",type:"checkbox",checked:e,onChange:H=>n(H.target.checked),className:"settings-checkbox"}),g.jsx("label",{htmlFor:"auto-trace",className:"settings-checkbox-label",children:"Enable auto-tracing (FLOCK_AUTO_TRACE)"})]}),g.jsx("p",{className:"settings-description",children:"Automatically trace all agent operations and system events with OpenTelemetry"})]}),g.jsxs("div",{className:"settings-field",children:[g.jsxs("div",{className:"settings-checkbox-wrapper",children:[g.jsx("input",{id:"trace-file",type:"checkbox",checked:a,onChange:H=>i(H.target.checked),className:"settings-checkbox",disabled:!e}),g.jsx("label",{htmlFor:"trace-file",className:"settings-checkbox-label",children:"Store traces in DuckDB (FLOCK_TRACE_FILE)"})]}),g.jsx("p",{className:"settings-description",children:"Save traces to .flock/traces.duckdb for analysis and debugging"})]}),g.jsxs("div",{className:"settings-field",children:[g.jsxs("div",{className:"settings-checkbox-wrapper",children:[g.jsx("input",{id:"auto-workflow",type:"checkbox",checked:o,onChange:H=>l(H.target.checked),className:"settings-checkbox",disabled:!e}),g.jsx("label",{htmlFor:"auto-workflow",className:"settings-checkbox-label",children:"Unified workflow tracing (FLOCK_AUTO_WORKFLOW_TRACE)"})]}),g.jsx("p",{className:"settings-description",children:"Automatically wrap operations in unified workflow traces (experimental)"})]}),g.jsxs("div",{className:"settings-field",children:[g.jsx("label",{htmlFor:"trace-ttl",className:"settings-label",children:"Trace Time-To-Live (FLOCK_TRACE_TTL_DAYS)"}),g.jsx("p",{className:"settings-description",children:"Auto-delete traces older than specified days (leave empty to keep forever)"}),g.jsx("input",{id:"trace-ttl",type:"number",min:"1",max:"365",value:c??"",onChange:H=>d(H.target.value?parseInt(H.target.value):null),className:"settings-input",placeholder:"30",disabled:!e})]})]}),g.jsxs("div",{className:"settings-section",children:[g.jsx("h3",{className:"settings-section-title",children:"Service Whitelist (FLOCK_TRACE_SERVICES)"}),g.jsx("p",{className:"settings-description",style:{marginBottom:"var(--space-component-md)"},children:"Only trace specific services. Leave empty to trace all services."}),g.jsx(so,{options:f,selected:m,onChange:b,placeholder:"Select services to trace...",disabled:!e})]}),g.jsxs("div",{className:"settings-section",children:[g.jsx("h3",{className:"settings-section-title",children:"Operation Blacklist (FLOCK_TRACE_IGNORE)"}),g.jsx("p",{className:"settings-description",style:{marginBottom:"var(--space-component-md)"},children:"Exclude specific operations from tracing (format: Service.method)"}),g.jsx(so,{options:p,selected:_,onChange:S,placeholder:"Select operations to ignore...",disabled:!e})]}),g.jsxs("div",{className:"settings-section",children:[g.jsx("h3",{className:"settings-section-title",children:"Trace Database Statistics"}),w&&g.jsx("div",{style:{backgroundColor:"rgba(96, 165, 250, 0.05)",border:"1px solid rgba(96, 165, 250, 0.2)",borderRadius:"var(--radius-md)",padding:"var(--space-component-md)"},children:g.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"var(--gap-md)"},children:[g.jsxs("div",{children:[g.jsx("div",{style:{fontSize:"var(--font-size-sm)",color:"var(--color-text-secondary)",marginBottom:"var(--space-xs)"},children:"Total Spans"}),g.jsx("div",{style:{fontSize:"var(--font-size-lg)",fontWeight:600},children:w.total_spans.toLocaleString()})]}),g.jsxs("div",{children:[g.jsx("div",{style:{fontSize:"var(--font-size-sm)",color:"var(--color-text-secondary)",marginBottom:"var(--space-xs)"},children:"Total Traces"}),g.jsx("div",{style:{fontSize:"var(--font-size-lg)",fontWeight:600},children:w.total_traces.toLocaleString()})]}),g.jsxs("div",{children:[g.jsx("div",{style:{fontSize:"var(--font-size-sm)",color:"var(--color-text-secondary)",marginBottom:"var(--space-xs)"},children:"Services Traced"}),g.jsx("div",{style:{fontSize:"var(--font-size-lg)",fontWeight:600},children:w.services_count})]}),g.jsxs("div",{children:[g.jsx("div",{style:{fontSize:"var(--font-size-sm)",color:"var(--color-text-secondary)",marginBottom:"var(--space-xs)"},children:"Database Size"}),g.jsx("div",{style:{fontSize:"var(--font-size-lg)",fontWeight:600},children:L(w.database_size_mb)})]}),g.jsxs("div",{children:[g.jsx("div",{style:{fontSize:"var(--font-size-sm)",color:"var(--color-text-secondary)",marginBottom:"var(--space-xs)"},children:"Oldest Trace"}),g.jsx("div",{style:{fontSize:"var(--font-size-xs)"},children:$(w.oldest_trace)})]}),g.jsxs("div",{children:[g.jsx("div",{style:{fontSize:"var(--font-size-sm)",color:"var(--color-text-secondary)",marginBottom:"var(--space-xs)"},children:"Newest Trace"}),g.jsx("div",{style:{fontSize:"var(--font-size-xs)"},children:$(w.newest_trace)})]})]})}),g.jsxs("div",{style:{marginTop:"var(--space-component-md)"},children:[g.jsx("button",{onClick:P,disabled:T||!w||w.total_spans===0,className:"settings-reset-button",style:{backgroundColor:"rgba(239, 68, 68, 0.1)",border:"1px solid rgba(239, 68, 68, 0.3)",color:"#ef4444"},children:T?"Clearing...":"Clear All Traces"}),g.jsx("p",{className:"settings-description",style:{marginTop:"var(--space-xs)"},children:"Delete all spans and run VACUUM to reclaim disk space"})]})]}),g.jsxs("div",{className:"settings-section",children:[g.jsx("button",{onClick:V,disabled:T,className:"settings-save-button",style:{backgroundColor:"rgba(96, 165, 250, 0.1)",border:"1px solid rgba(96, 165, 250, 0.3)",color:"#60a5fa",padding:"var(--space-component-sm) var(--space-component-md)",borderRadius:"var(--radius-md)",fontSize:"var(--font-size-base)",fontWeight:500,cursor:T?"not-allowed":"pointer",opacity:T?.6:1},children:T?"Saving...":"Save Tracing Settings"}),g.jsx("p",{className:"settings-description",style:{marginTop:"var(--space-xs)"},children:"Settings will be persisted to .env file (requires backend restart)"})]})]})},KV=()=>{const[e,n]=q.useState([]),[a,i]=q.useState(!0),[o,l]=q.useState(null),[c,d]=q.useState(new Set),[f,h]=q.useState(new Set),[p,v]=q.useState(new Set),[m,b]=q.useState(""),[_,S]=q.useState("timeline"),[w,C]=q.useState(null),[T,E]=q.useState(new Set),[N,R]=q.useState("SELECT * FROM spans LIMIT 10"),[z,j]=q.useState(null),[A,D]=q.useState([]),[I,P]=q.useState(!1),[V,$]=q.useState(null),[L,H]=q.useState("date"),[O,F]=q.useState("desc"),J=q.useRef(null),G=q.useRef(0),re=async()=>{P(!0),$(null);try{const W=await fetch("/api/traces/query",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:N})});if(!W.ok){const te=await W.json();throw new Error(te.error||"Query failed")}const se=await W.json();j(se.results),D(se.columns)}catch(W){$(W instanceof Error?W.message:"Unknown error"),j(null),D([])}finally{P(!1)}},B=q.useMemo(()=>{const W=["#3b82f6","#10b981","#f59e0b","#ef4444","#8b5cf6","#ec4899","#06b6d4","#f97316"],se=new Map,te=[],me=[];return e.forEach(ve=>{const Se=ve.name.split(".")[0]||ve.resource["service.name"]||"unknown";te.includes(Se)||te.push(Se);const Ee=ve.name.split(".")[0]||ve.name;Ee&&!me.includes(Ee)&&me.push(Ee)}),te.length===1?me.forEach((ve,Se)=>{const Ee=W[Se%W.length]||"#6366f1";se.set(ve,Ee)}):te.forEach((ve,Se)=>{const Ee=W[Se%W.length]||"#6366f1";se.set(ve,Ee)}),{colorMap:se,useSpanType:te.length===1}},[e]);q.useEffect(()=>{const W=async()=>{try{e.length===0&&i(!0);const te=await fetch("/api/traces");if(!te.ok)throw new Error(`HTTP ${te.status}: ${te.statusText}`);const me=await te.json();if(JSON.stringify(me)!==JSON.stringify(e)){const ve=J.current?.scrollTop||0;n(me),l(null),requestAnimationFrame(()=>{J.current&&me.length===G.current&&(J.current.scrollTop=ve)}),G.current=me.length}}catch(te){l(te instanceof Error?te.message:"Failed to load traces")}finally{i(!1)}};W();const se=setInterval(W,5e3);return()=>clearInterval(se)},[e]);const Y=q.useMemo(()=>{const W=new Map;return e.forEach(se=>{const te=se.context.trace_id;W.has(te)||W.set(te,[]),W.get(te).push(se)}),Array.from(W.entries()).map(([se,te])=>{const me=Math.min(...te.map(qe=>qe.start_time)),ve=Math.max(...te.map(qe=>qe.end_time)),Se=(ve-me)/1e6,Ee=te.some(qe=>qe.status.status_code==="ERROR"),Ve=new Set(te.map(qe=>qe.name.split(".")[0]||qe.resource["service.name"]||"unknown"));return{traceId:se,spans:te.sort((qe,lt)=>qe.start_time-lt.start_time),startTime:me,endTime:ve,duration:Se,spanCount:te.length,hasError:Ee,services:Ve}})},[e]),ae=q.useMemo(()=>{let W=Y;if(m){const se=m.toLowerCase();W=W.filter(te=>te.traceId.toLowerCase().includes(se)||te.spans.some(me=>me.name.toLowerCase().includes(se)||Object.values(me.attributes).some(ve=>typeof ve=="string"&&ve.toLowerCase().includes(se))))}return[...W].sort((se,te)=>{let me=0;switch(L){case"date":me=se.startTime-te.startTime;break;case"spans":me=se.spanCount-te.spanCount;break;case"duration":me=se.duration-te.duration;break}return O==="asc"?me:-me})},[Y,m,L,O]),U=q.useMemo(()=>{const W=new Map;return e.forEach(se=>{const te=se.name.split(".")[0]||"unknown";W.has(te)||W.set(te,{service:te,totalSpans:0,errorSpans:0,avgDuration:0,p95Duration:0,p99Duration:0,rate:0});const me=W.get(te);me.totalSpans++,se.status.status_code==="ERROR"&&me.errorSpans++}),W.forEach((se,te)=>{const me=e.filter(Se=>(Se.name.split(".")[0]||"unknown")===te),ve=me.map(Se=>(Se.end_time-Se.start_time)/1e6).sort((Se,Ee)=>Se-Ee);if(se.avgDuration=ve.reduce((Se,Ee)=>Se+Ee,0)/ve.length||0,se.p95Duration=ve[Math.floor(ve.length*.95)]||0,se.p99Duration=ve[Math.floor(ve.length*.99)]||0,me.length>1){const Se=(Math.max(...me.map(Ee=>Ee.end_time))-Math.min(...me.map(Ee=>Ee.start_time)))/1e9;se.rate=me.length/Math.max(Se,1)}}),Array.from(W.values()).sort((se,te)=>te.totalSpans-se.totalSpans)},[e]),Z=q.useMemo(()=>{const W=new Map;return Y.forEach(se=>{se.spans.forEach(te=>{if(te.parent_id){const me=se.spans.find(ve=>ve.context.span_id===te.parent_id);if(me){const ve=me.name.split(".")[0]||"unknown",Se=te.name.split(".")[0]||"unknown";if(ve!==Se){const Ee=`${ve}->${Se}`;W.has(Ee)||W.set(Ee,{from:ve,to:Se,operations:new Map});const Ve=W.get(Ee),qe=`${me.name} → ${te.name}`;Ve.operations.has(qe)||Ve.operations.set(qe,{operation:qe,service:Se,totalCalls:0,errorCalls:0,avgDuration:0,p95Duration:0});const lt=Ve.operations.get(qe);lt.totalCalls++,te.status.status_code==="ERROR"&&lt.errorCalls++}}}})}),W.forEach(se=>{se.operations.forEach((te,me)=>{const ve=me.split(" → ")[1],Ee=e.filter(Ve=>Ve.name===ve).map(Ve=>(Ve.end_time-Ve.start_time)/1e6).sort((Ve,qe)=>Ve-qe);te.avgDuration=Ee.reduce((Ve,qe)=>Ve+qe,0)/Ee.length||0,te.p95Duration=Ee[Math.floor(Ee.length*.95)]||0})}),Array.from(W.values())},[Y,e]),ne=W=>{const se=new Map,te=[];W.forEach(ve=>{se.set(ve.context.span_id,{...ve,children:[],depth:0})}),W.forEach(ve=>{const Se=se.get(ve.context.span_id);if(ve.parent_id&&se.has(ve.parent_id)){const Ee=se.get(ve.parent_id);Ee.children.push(Se),Se.depth=Ee.depth+1}else te.push(Se)});const me=ve=>{ve.children.sort((Se,Ee)=>Se.start_time-Ee.start_time),ve.children.forEach(me)};return te.forEach(me),te},le=W=>{h(se=>{const te=new Set(se);return te.has(W)?te.delete(W):te.add(W),te})},K=W=>{v(se=>{const te=new Set(se);return te.has(W)?te.delete(W):te.add(W),te})},de=(W,se)=>{if(B.useSpanType){const te=se.split(".")[0]||se;return B.colorMap.get(te)||"#6366f1"}return W&&B.colorMap.get(W)||"#6366f1"},ye=W=>g.jsx("div",{style:{marginTop:"var(--space-component-md)",background:"var(--color-bg-base)",borderRadius:"var(--radius-lg)",overflow:"hidden"},children:g.jsxs("table",{style:{width:"100%",fontSize:"var(--font-size-body-sm)",fontFamily:"var(--font-family-mono)",borderCollapse:"collapse"},children:[g.jsx("thead",{children:g.jsxs("tr",{style:{background:"var(--color-bg-surface)",borderBottom:"2px solid var(--color-border-subtle)"},children:[g.jsx("th",{style:{padding:"12px",textAlign:"left",color:"var(--color-text-secondary)",fontWeight:"var(--font-weight-bold)"},children:"Service"}),g.jsx("th",{style:{padding:"12px",textAlign:"left",color:"var(--color-text-secondary)",fontWeight:"var(--font-weight-bold)"},children:"Operation"}),g.jsx("th",{style:{padding:"12px",textAlign:"right",color:"var(--color-text-secondary)",fontWeight:"var(--font-weight-bold)"},children:"Duration"}),g.jsx("th",{style:{padding:"12px",textAlign:"right",color:"var(--color-text-secondary)",fontWeight:"var(--font-weight-bold)"},children:"Start Time"}),g.jsx("th",{style:{padding:"12px",textAlign:"center",color:"var(--color-text-secondary)",fontWeight:"var(--font-weight-bold)"},children:"Status"})]})}),g.jsx("tbody",{children:W.spans.map((se,te)=>{const me=(se.end_time-se.start_time)/1e6,ve=(se.start_time-W.startTime)/1e6,Se=se.name.split(".")[0]||se.resource["service.name"]||"unknown";return g.jsxs("tr",{style:{background:te%2===0?"transparent":"var(--color-bg-surface)",borderBottom:"1px solid var(--color-border-subtle)"},children:[g.jsxs("td",{style:{padding:"10px"},children:[g.jsx("span",{style:{display:"inline-block",width:"8px",height:"8px",borderRadius:"50%",background:de(Se,se.name),marginRight:"8px"}}),Se]}),g.jsx("td",{style:{padding:"10px",color:"var(--color-text-primary)"},children:se.name}),g.jsxs("td",{style:{padding:"10px",textAlign:"right",color:"var(--color-text-primary)",fontWeight:"var(--font-weight-medium)"},children:[me.toFixed(2),"ms"]}),g.jsxs("td",{style:{padding:"10px",textAlign:"right",color:"var(--color-text-tertiary)"},children:["+",ve.toFixed(2),"ms"]}),g.jsx("td",{style:{padding:"10px",textAlign:"center"},children:g.jsx("span",{style:{padding:"2px 8px",borderRadius:"var(--radius-sm)",fontSize:"var(--font-size-body-xs)",fontWeight:"var(--font-weight-medium)",background:se.status.status_code==="ERROR"?"rgba(239, 68, 68, 0.2)":"rgba(16, 185, 129, 0.2)",color:se.status.status_code==="ERROR"?"#ef4444":"#10b981"},children:se.status.status_code})})]},se.context.span_id)})})]})}),xe=(W,se,te)=>{const me=(W.start_time-se)/1e6,ve=(W.end_time-W.start_time)/1e6,Se=Math.min(me/te*100,100),Ee=Math.min(ve/te*100,100-Se),Ve=Math.max(Ee,.5),qe=f.has(W.context.span_id),lt=p.has(W.context.span_id),tt=W.children.length>0,nt=W.name.split(".")[0]||W.resource["service.name"]||"unknown",Ft=de(nt,W.name),$t=w===W.context.span_id;return g.jsxs("div",{style:{marginBottom:"1px",opacity:$t?1:w?.4:1},children:[g.jsxs("div",{style:{display:"grid",gridTemplateColumns:"400px 1fr",alignItems:"center",background:qe?"var(--color-bg-elevated)":"transparent",borderBottom:"1px solid rgba(255, 255, 255, 0.03)"},children:[g.jsxs("div",{style:{padding:"8px 12px",fontSize:"var(--font-size-body-sm)",fontFamily:"var(--font-family-mono)",color:"var(--color-text-primary)",display:"flex",alignItems:"center",gap:"8px",paddingLeft:`${12+W.depth*20}px`,borderRight:"1px solid var(--color-border-subtle)"},children:[tt&&g.jsx("span",{onClick:()=>K(W.context.span_id),style:{cursor:"pointer",userSelect:"none",width:"12px",opacity:.6,fontSize:"10px"},children:lt?"►":"▼"}),!tt&&g.jsx("span",{style:{width:"12px"}}),g.jsx("span",{style:{display:"inline-block",width:"6px",height:"6px",borderRadius:"50%",background:Ft,flexShrink:0}}),g.jsx("span",{onClick:At=>{At.shiftKey?C($t?null:W.context.span_id):le(W.context.span_id)},style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",cursor:"pointer",display:"flex",alignItems:"center",gap:"4px"},title:`${W.name}
106
106
  Shift+click to focus`,children:g.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis"},children:W.name})}),g.jsxs("span",{style:{fontSize:"var(--font-size-body-xs)",color:"var(--color-text-tertiary)",flexShrink:0},children:[ve.toFixed(1),"ms"]})]}),g.jsx("div",{style:{padding:"8px 12px",height:"32px"},children:g.jsx("div",{style:{position:"relative",height:"18px",width:"100%"},children:g.jsx("div",{style:{position:"absolute",left:`${Se}%`,width:`${Ve}%`,height:"100%",background:Ft,border:W.status.status_code==="ERROR"?"2px solid #ef4444":"none",borderRadius:"2px",display:"flex",alignItems:"center",paddingLeft:"4px",fontSize:"10px",color:"white",fontWeight:"var(--font-weight-medium)",cursor:"pointer",boxSizing:"border-box"},onClick:()=>le(W.context.span_id),title:`${W.name}
107
107
  Service: ${nt}
108
108
  ${ve.toFixed(2)}ms