@hsafa/ui-sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,188 @@
1
+ import * as React from 'react';
2
+ import React__default, { ComponentType } from 'react';
3
+ import * as react_jsx_runtime from 'react/jsx-runtime';
4
+
5
+ /**
6
+ * Props for the Button component
7
+ */
8
+ interface ButtonProps extends React__default.ButtonHTMLAttributes<HTMLButtonElement> {
9
+ /** Visual style variant of the button */
10
+ variant?: "primary" | "secondary" | "outline" | "ghost";
11
+ /** Size of the button */
12
+ size?: "sm" | "md" | "lg";
13
+ /** Whether the button is in a loading state */
14
+ loading?: boolean;
15
+ /** Content to be displayed inside the button */
16
+ children: React__default.ReactNode;
17
+ }
18
+ /**
19
+ * A versatile button component with multiple variants, sizes, and states.
20
+ *
21
+ * @example
22
+ * ```tsx
23
+ * // Basic usage
24
+ * <Button>Click me</Button>
25
+ *
26
+ * // With variant and size
27
+ * <Button variant="secondary" size="lg">Large Secondary Button</Button>
28
+ *
29
+ * // Loading state
30
+ * <Button loading>Processing...</Button>
31
+ *
32
+ * // With click handler
33
+ * <Button onClick={() => console.log('Clicked!')}>Click me</Button>
34
+ * ```
35
+ */
36
+ declare const Button: React__default.FC<ButtonProps>;
37
+
38
+ interface UseToggleReturn {
39
+ /** Current toggle state */
40
+ on: boolean;
41
+ /** Toggle the state */
42
+ toggle: () => void;
43
+ /** Set the state directly */
44
+ setOn: (value: boolean | ((prev: boolean) => boolean)) => void;
45
+ /** Set state to true */
46
+ setTrue: () => void;
47
+ /** Set state to false */
48
+ setFalse: () => void;
49
+ }
50
+ /**
51
+ * A hook for managing boolean toggle state
52
+ * @param initial - Initial state value (default: false)
53
+ * @returns Object with toggle state and control functions
54
+ */
55
+ declare function useToggle(initial?: boolean): UseToggleReturn;
56
+
57
+ declare function useAutoScroll<T extends HTMLElement>(): React.MutableRefObject<T | null>;
58
+
59
+ /**
60
+ * Handler function for custom actions that can be triggered by the AI agent
61
+ */
62
+ type HsafaActionHandler = (params: any, meta: {
63
+ /** Name of the action being called */
64
+ name: string;
65
+ /** When the action is being triggered */
66
+ trigger: 'partial' | 'final' | 'params_complete';
67
+ /** Index of the action in the sequence */
68
+ index: number;
69
+ /** ID of the assistant message that triggered this action */
70
+ assistantMessageId?: string;
71
+ /** ID of the current chat session */
72
+ chatId?: string;
73
+ }) => Promise<any> | any;
74
+ /**
75
+ * Configuration options for the Hsafa SDK
76
+ */
77
+ interface HsafaConfig {
78
+ /** Base URL for agent API calls, e.g. "" (same origin) or "https://example.com" */
79
+ baseUrl?: string;
80
+ }
81
+ /**
82
+ * Context value provided by HsafaProvider
83
+ */
84
+ interface HsafaContextValue extends HsafaConfig {
85
+ /** Registered custom actions */
86
+ actions: Map<string, HsafaActionHandler>;
87
+ /** Registered custom components */
88
+ components: Map<string, React__default.ComponentType<any>>;
89
+ /** Register a custom action handler */
90
+ registerAction: (name: string, handler: HsafaActionHandler) => () => void;
91
+ /** Unregister a custom action handler */
92
+ unregisterAction: (name: string, handler?: HsafaActionHandler) => void;
93
+ /** Register a custom component */
94
+ registerComponent: (name: string, component: React__default.ComponentType<any>) => () => void;
95
+ /** Unregister a custom component */
96
+ unregisterComponent: (name: string, component?: React__default.ComponentType<any>) => void;
97
+ }
98
+ /**
99
+ * Props for the HsafaProvider component
100
+ */
101
+ interface HsafaProviderProps extends HsafaConfig {
102
+ /** Child components that will have access to the Hsafa context */
103
+ children: React__default.ReactNode;
104
+ }
105
+ /**
106
+ * Provider component that sets up the Hsafa context for the SDK.
107
+ * Wrap your app or chat components with this provider to enable Hsafa functionality.
108
+ *
109
+ * @example
110
+ * ```tsx
111
+ * <HsafaProvider baseUrl="https://api.example.com">
112
+ * <HsafaChat agentId="my-agent" />
113
+ * </HsafaProvider>
114
+ * ```
115
+ */
116
+ declare function HsafaProvider({ baseUrl, children }: HsafaProviderProps): react_jsx_runtime.JSX.Element;
117
+ /**
118
+ * Hook to access the Hsafa context.
119
+ * Must be used within a HsafaProvider.
120
+ *
121
+ * @returns The Hsafa context value with actions, components, and configuration
122
+ *
123
+ * @example
124
+ * ```tsx
125
+ * function MyComponent() {
126
+ * const { registerAction, baseUrl } = useHsafa();
127
+ *
128
+ * useEffect(() => {
129
+ * const unregister = registerAction('myAction', async (params) => {
130
+ * console.log('Action called with:', params);
131
+ * return { success: true };
132
+ * });
133
+ *
134
+ * return unregister;
135
+ * }, [registerAction]);
136
+ *
137
+ * return <div>My Component</div>;
138
+ * }
139
+ * ```
140
+ */
141
+ declare function useHsafa(): HsafaContextValue;
142
+
143
+ /**
144
+ * Register an action handler by name within the nearest HsafaProvider.
145
+ * The handler will be automatically unregistered on unmount.
146
+ */
147
+ declare function useHsafaAction(name: string, handler: HsafaActionHandler): void;
148
+
149
+ /**
150
+ * Register a UI component by name within the nearest HsafaProvider.
151
+ * The component will be automatically unregistered on unmount.
152
+ */
153
+ declare function useHsafaComponent(name: string, component: ComponentType<any>): void;
154
+
155
+ interface HsafaChatProps {
156
+ agentId: string;
157
+ children?: React__default.ReactNode;
158
+ theme?: 'dark' | 'light';
159
+ primaryColor?: string;
160
+ backgroundColor?: string;
161
+ borderColor?: string;
162
+ textColor?: string;
163
+ accentColor?: string;
164
+ width?: number | string;
165
+ maxWidth?: number | string;
166
+ height?: string;
167
+ expandable?: boolean;
168
+ alwaysOpen?: boolean;
169
+ defaultOpen?: boolean;
170
+ floatingButtonPosition?: {
171
+ bottom?: number | string;
172
+ right?: number | string;
173
+ top?: number | string;
174
+ left?: number | string;
175
+ };
176
+ enableBorderAnimation?: boolean;
177
+ enableContentPadding?: boolean;
178
+ borderRadius?: number | string;
179
+ enableContentBorder?: boolean;
180
+ placeholder?: string;
181
+ title?: string;
182
+ className?: string;
183
+ chatContainerClassName?: string;
184
+ dir?: 'rtl' | 'ltr';
185
+ }
186
+ declare function HsafaChat({ agentId, children, theme, primaryColor, backgroundColor, borderColor, textColor, accentColor, width, maxWidth, height, expandable, alwaysOpen, defaultOpen, dir, floatingButtonPosition, enableBorderAnimation, enableContentPadding, borderRadius, enableContentBorder, placeholder, title, className, chatContainerClassName }: HsafaChatProps): react_jsx_runtime.JSX.Element;
187
+
188
+ export { Button, type ButtonProps, HsafaChat, HsafaProvider, type UseToggleReturn, useAutoScroll, useHsafa, useHsafaAction, useHsafaComponent, useToggle };
package/dist/index.js ADDED
@@ -0,0 +1,30 @@
1
+ import {jsxs,jsx,Fragment}from'react/jsx-runtime';import {createContext,useState,useCallback,useRef,useEffect,useMemo,useContext}from'react';import {createPortal}from'react-dom';import {IconArrowsMaximize,IconPlus,IconHistory,IconTrash,IconChevronRight,IconPaperclip,IconLink,IconPlayerStop,IconArrowUp,IconMessage}from'@tabler/icons-react';var Z={};var er=({variant:a="primary",size:u="md",loading:p=false,disabled:m,children:A,className:T,...z})=>{let j=[Z.button,Z[a],Z[u],p&&Z.loading,T].filter(Boolean).join(" ");return jsxs("button",{className:j,disabled:m||p,...z,children:[p&&jsx("span",{className:Z.spinner}),jsx("span",{className:p?Z.hiddenText:void 0,children:A})]})};function nr(a=false){let[u,p]=useState(a),m=useCallback(()=>p(z=>!z),[]),A=useCallback(()=>p(true),[]),T=useCallback(()=>p(false),[]);return {on:u,toggle:m,setOn:p,setTrue:A,setFalse:T}}function lr(){let a=useRef(null);return useEffect(()=>{let u=a.current;if(!u)return;let p=new MutationObserver(()=>{u.scrollTop=u.scrollHeight;});return p.observe(u,{childList:true,subtree:true}),u.scrollTop=u.scrollHeight,()=>p.disconnect()},[]),a}var We=createContext(void 0);function Et({baseUrl:a,children:u}){let[p,m]=useState(new Map),[A,T]=useState(new Map),z=useCallback((M,v)=>(m($=>{let g=new Map($);return g.set(String(M),v),g}),()=>{m($=>{let g=new Map($),y=g.get(String(M));return (!v||y===v)&&g.delete(String(M)),g});}),[]),j=useCallback((M,v)=>{m($=>{let g=new Map($),y=g.get(String(M));return (!v||y===v)&&g.delete(String(M)),g});},[]),Y=useCallback((M,v)=>(T($=>{let g=new Map($);return g.set(String(M),v),g}),()=>{T($=>{let g=new Map($),y=g.get(String(M));return (!v||y===v)&&g.delete(String(M)),g});}),[]),te=useCallback((M,v)=>{T($=>{let g=new Map($),y=g.get(String(M));return (!v||y===v)&&g.delete(String(M)),g});},[]),ce=useMemo(()=>({baseUrl:a,actions:p,components:A,registerAction:z,unregisterAction:j,registerComponent:Y,unregisterComponent:te}),[a,p,A,z,j,Y,te]);return jsx(We.Provider,{value:ce,children:u})}function ee(){let a=useContext(We);return a||{baseUrl:void 0,actions:new Map,components:new Map,registerAction:()=>()=>{},unregisterAction:()=>{},registerComponent:()=>()=>{},unregisterComponent:()=>{}}}function mr(a,u){let{registerAction:p}=ee(),m=useRef(u);useEffect(()=>{m.current=u;},[u]),useEffect(()=>!a||typeof m.current!="function"?void 0:p(a,(T,z)=>m.current(T,z)),[a,p]);}function Cr(a,u){let{registerComponent:p}=ee(),m=useRef(u);useEffect(()=>{m.current=u;},[u]),useEffect(()=>!a||typeof m.current!="function"?void 0:p(a,m.current),[a,p]);}function _t(a){let u=Date.now()-a,p=Math.max(1,Math.floor(u/1e3));if(p<60)return `${p}s`;let m=Math.floor(p/60);if(m<60)return `${m}m`;let A=Math.floor(m/60);if(A<24)return `${A}h`;let T=Math.floor(A/24);if(T<7)return `${T}d`;let z=Math.floor(T/7);if(z<4)return `${z}w`;let j=Math.floor(T/30);return j<12?`${j}mo`:`${Math.floor(j/12)}y`}function Qe(a,u){if(!a)return u;let p=a.endsWith("/")?a.slice(0,-1):a,m=u.startsWith("/")?u:`/${u}`;return `${p}${m}`}var Wt={dark:{primaryColor:"#4D78FF",backgroundColor:"#0B0B0F",borderColor:"#2A2C33",textColor:"#EDEEF0",accentColor:"#17181C",mutedTextColor:"#9AA0A6",inputBackground:"#17181C",cardBackground:"#121318",hoverBackground:"#1c1e25"},light:{primaryColor:"#2563EB",backgroundColor:"#FFFFFF",borderColor:"#E5E7EB",textColor:"#111827",accentColor:"#F9FAFB",mutedTextColor:"#6B7280",inputBackground:"#F9FAFB",cardBackground:"#F3F4F6",hoverBackground:"#F3F4F6"}};function Xt({agentId:a,children:u,theme:p="dark",primaryColor:m,backgroundColor:A,borderColor:T,textColor:z,accentColor:j,width:Y=420,maxWidth:te=420,height:ce="100vh",expandable:M=true,alwaysOpen:v=false,defaultOpen:$=true,dir:g="ltr",floatingButtonPosition:y=g==="rtl"?{bottom:16,left:16}:{bottom:16,right:16},enableBorderAnimation:Ae=true,enableContentPadding:Ze=true,borderRadius:Ce=16,enableContentBorder:$e=true,placeholder:et="Ask your question...",title:He="Agent",className:tt="",chatContainerClassName:rt=""}){let{baseUrl:Ie,actions:Ee,components:ot}=ee(),ue="hsafaChat",Re=`${ue}.chats`,he=e=>`${ue}.chat.${e}`,V=`${ue}.currentChatId`,Be=`${ue}.showChat`,[de,Fe]=useState(""),[_,pe]=useState(()=>{if(v)return true;try{let e=localStorage.getItem(Be);return e!==null?e==="true":$}catch{return $}});async function ze(e,n){if(!a)return;let r=n.trim();if(!r)return;U(null),re(true);let s=N.findIndex(d=>d.id===e);if(s===-1||N[s].role!=="user"){re(false);return}let c=N.slice(0,s),H={id:e,role:"user",text:r},O=ie(),C=[...c,H,{id:O,role:"assistant",items:[],reasoning:"",reasoningOpen:false}];w(C),ge(null);try{let d=[...c.map(E=>E.role==="user"?{role:"user",content:E.text}:{role:"assistant",items:Array.isArray(E.items)?E.items:[]}),{role:"user",content:r}],I={prompt:r,chatId:k??void 0,messages:d};w(E=>E.map(q=>q.id===O||q.id===e?{...q,requestParams:I}:q));let S=await fetch(Qe(Ie,`/api/run/${a}`),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(I)});if(!S.ok||!S.body){let E=await S.text().catch(()=>"");throw new Error(E||`Request failed with ${S.status}`)}let P=S.body.getReader(),Q=new TextDecoder,D="";for(;;){let{done:E,value:q}=await P.read();if(E)break;D+=Q.decode(q,{stream:!0});let f;for(;(f=D.indexOf(`
2
+ `))!==-1;){let R=D.slice(0,f).trim();if(D=D.slice(f+1),!!R)try{let i=JSON.parse(R);if(i?.type==="meta"){if(i.actionExecuteMap&&typeof i.actionExecuteMap=="object"&&(Te.current=i.actionExecuteMap),i.assistantMessageId&&(oe.current=String(i.assistantMessageId),me.current.clear(),ye.current.clear(),G.current.clear(),ne(new Map)),i.chatId&&!k){W(i.chatId),L.current=!0;let l=r,K=(X.current||l||"New chat").slice(0,80),b=Date.now();le({id:i.chatId,title:K,createdAt:b,updatedAt:b}),se({id:i.chatId,messages:C,agentId:a});try{localStorage.setItem(V,i.chatId);}catch{}}continue}if(i?.type==="reasoning"){let l=String(i.text??"");w(K=>K.map(b=>b.id===O&&b.role==="assistant"?{...b,reasoning:(b.reasoning??"")+l}:b));continue}if(i?.type==="partial"||i?.type==="final"){let l=i.value;l&&Array.isArray(l.items)&&(w(K=>K.map(b=>b.id===O&&b.role==="assistant"?{...b,items:l.items}:b)),Ue(l.items,i.type==="partial"?"partial":"final")),i?.type==="final"&&w(K=>K.map(b=>b.id===O&&b.role==="assistant"?{...b,reasoningOpen:!1}:b));continue}if(i?.type==="usage"){let l=i?.value?.reasoningTokens;typeof l=="number"&&w(K=>K.map(b=>b.id===O&&b.role==="assistant"?{...b,reasoningTokens:l}:b));continue}if(i?.type==="error"){U(String(i.error??"Unknown error"));continue}}catch{}}}}catch(d){U(String(d?.message??d));}finally{if(re(false),!k&&!L.current){let d=`local-${ie()}`;W(d),L.current=true;let I=(X.current||"New chat").slice(0,80),S=Date.now();le({id:d,title:I,createdAt:S,updatedAt:S}),se({id:d,messages:N,agentId:a});try{localStorage.setItem(V,d);}catch{}}}}let[N,w]=useState([]),[h,re]=useState(false),[Oe,U]=useState(null),ae=useRef(null),[k,W]=useState(null),[nt,ve]=useState(false),[De,at]=useState(""),[Gt,st]=useState(0),[lt,it]=useState(false),[ct,ge]=useState(null),[fe,Le]=useState(""),ut=useRef(null),Pe=useRef(null),dt=useRef(null),[ke,pt]=useState(true),we=useRef(false),L=useRef(false),X=useRef(null),gt=useRef(null),ft=useRef(null),Te=useRef({}),oe=useRef(void 0),me=useRef(new Set),ye=useRef(new Map),G=useRef(new Map),[mt,ne]=useState(new Map),je=useCallback((e,n)=>{let r=ye.current.get(e)||[],s=JSON.stringify(n);if(r.push(s),r.length>3&&r.shift(),ye.current.set(e,r),r.length>=2){let c=r.slice(-2);return c[0]===c[1]}return false},[]),Ue=useCallback((e,n)=>{!Array.isArray(e)||e.length===0||e.forEach((r,s)=>{if(!(!r||typeof r!="object")&&r.type==="action"){let c=String(r.name??"").trim();if(!c)return;let H=Ee.get(c);if(!H)return;let O=!!Te.current[c],C=`${oe.current||"assist"}:${c}:${s}`,d=`${c}:${s}`;try{if(n==="partial"&&O)ne(I=>new Map(I).set(d,"executing")),Promise.resolve(H(r.params,{name:c,trigger:n,index:s,assistantMessageId:oe.current,chatId:k||void 0})).catch(()=>{});else if(n==="partial"&&!O){let I=je(d,r.params),S=G.current.get(d);I&&S!=="executed"?(G.current.set(d,"executed"),ne(P=>new Map(P).set(d,"executed")),Promise.resolve(H(r.params,{name:c,trigger:"params_complete",index:s,assistantMessageId:oe.current,chatId:k||void 0})).catch(()=>{})):S||(G.current.set(d,"executing"),ne(P=>new Map(P).set(d,"executing")));}else n==="final"&&G.current.get(d)!=="executed"&&!me.current.has(C)&&(me.current.add(C),G.current.set(d,"executed"),ne(S=>new Map(S).set(d,"executed")),Promise.resolve(H(r.params,{name:c,trigger:O?"final":"params_complete",index:s,assistantMessageId:oe.current,chatId:k||void 0})).catch(()=>{}));}catch{}}});},[Ee,k,je]),Me=()=>{try{let e=localStorage.getItem(Re);return e?JSON.parse(e):[]}catch{return []}},Je=e=>{try{localStorage.setItem(Re,JSON.stringify(e));}catch{}},qe=e=>{try{let n=localStorage.getItem(he(e));return n?JSON.parse(n):null}catch{return null}},se=e=>{try{localStorage.setItem(he(e.id),JSON.stringify(e));}catch{}},le=e=>{let n=Me(),r=n.findIndex(s=>s.id===e.id);r>=0?n[r]=e:n.unshift(e),Je(n);},yt=e=>{let r=Me().filter(s=>s.id!==e);Je(r);},bt=e=>{try{localStorage.removeItem(he(e));}catch{}},xt=e=>{if(bt(e),yt(e),k===e){w([]),U(null),W(null),L.current=false,X.current=null;try{localStorage.removeItem(V);}catch{}}};useEffect(()=>{if(we.current){we.current=false;return}ke&&Pe.current?.scrollIntoView({behavior:"smooth",block:"end"});},[N,h,ke]),useEffect(()=>{try{let e=localStorage.getItem(V);if(e){let n=qe(e);n&&(W(n.id),L.current=!0,w(n.messages||[]));}}catch{}},[]),useEffect(()=>{try{localStorage.setItem(Be,String(_));}catch{}},[_]),useEffect(()=>{if(!k||!L.current)return;se({id:k,messages:N,agentId:a});let n=N.find(c=>c.role==="user"),r=(X.current||(n?.text??"New chat")).slice(0,80),s={id:k,title:r,createdAt:Date.now(),updatedAt:Date.now()};le(s);try{localStorage.setItem(V,k);}catch{}},[N,k,a]);let ie=()=>`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;function Ct(){ae.current&&(ae.current.abort(),ae.current=null),re(false),U("Request stopped by user");}async function Ke(){if(!a)return;let e=de.trim();if(!e)return;U(null),re(true),!k&&N.length===0&&(X.current=e);let n=ie(),r=ie(),s={id:n,role:"user",text:e},c={id:r,role:"assistant",items:[],reasoning:"",reasoningOpen:false},H=[...N,s,c],O=[...N.map(C=>C.role==="user"?{role:"user",content:C.text}:{role:"assistant",items:Array.isArray(C.items)?C.items:[]}),{role:"user",content:e}];w(H),Fe("");try{ae.current=new AbortController;let C={prompt:e,chatId:k??void 0,messages:O};w(Q=>Q.map(D=>D.id===r||D.id===n?{...D,requestParams:C}:D));let d=await fetch(Qe(Ie,`/api/run/${a}`),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(C),signal:ae.current.signal});if(!d.ok||!d.body){let Q=await d.text().catch(()=>"");throw new Error(Q||`Request failed with ${d.status}`)}let I=d.body.getReader(),S=new TextDecoder,P="";for(;;){let{done:Q,value:D}=await I.read();if(Q)break;P+=S.decode(D,{stream:!0});let E;for(;(E=P.indexOf(`
3
+ `))!==-1;){let q=P.slice(0,E).trim();if(P=P.slice(E+1),!!q)try{let f=JSON.parse(q);if(f?.type==="meta"){if(f.actionExecuteMap&&typeof f.actionExecuteMap=="object"&&(Te.current=f.actionExecuteMap),f.assistantMessageId&&(oe.current=String(f.assistantMessageId),me.current.clear(),ye.current.clear(),G.current.clear(),ne(new Map)),f.chatId&&!k){W(f.chatId),L.current=!0;let R=e,i=(X.current||R||"New chat").slice(0,80),l=Date.now();le({id:f.chatId,title:i,createdAt:l,updatedAt:l}),se({id:f.chatId,messages:H,agentId:a});try{localStorage.setItem(V,f.chatId);}catch{}}continue}if(f?.type==="reasoning"){let R=String(f.text??"");w(i=>i.map(l=>l.id===r&&l.role==="assistant"?{...l,reasoning:(l.reasoning??"")+R}:l));continue}if(f?.type==="partial"||f?.type==="final"){let R=f.value;R&&Array.isArray(R.items)&&(w(i=>i.map(l=>l.id===r&&l.role==="assistant"?{...l,items:R.items}:l)),Ue(R.items,f.type==="partial"?"partial":"final")),f?.type==="final"&&w(i=>i.map(l=>l.id===r&&l.role==="assistant"?{...l,reasoningOpen:!1}:l));continue}if(f?.type==="usage"){let R=f?.value?.reasoningTokens;typeof R=="number"&&w(i=>i.map(l=>l.id===r&&l.role==="assistant"?{...l,reasoningTokens:R}:l));continue}if(f?.type==="error"){U(String(f.error??"Unknown error"));continue}}catch{}}}}catch(C){U(String(C?.message??C));}finally{if(re(false),!k&&!L.current){let C=`local-${ie()}`;W(C),L.current=true;let d=(X.current||"New chat").slice(0,80),I=Date.now();le({id:C,title:d,createdAt:I,updatedAt:I}),se({id:C,messages:N,agentId:a});try{localStorage.setItem(V,C);}catch{}}}}function ht(e){return !Array.isArray(e)||e.length===0?null:jsx("div",{className:"space-y-3",children:e.map((n,r)=>{let s=`it-${r}`;if(typeof n=="string")return jsx("div",{className:"rounded-xl p-4 text-[14px] whitespace-pre-wrap",children:n},s);if(n&&typeof n=="object"){if(n.type==="action"){let c=`${String(n.name??"action")}:${r}`,H=mt.get(c);return jsx("div",{className:"space-y-2",children:jsx("div",{className:"px-2 py-1 text-xs",style:{color:t.mutedTextColor},children:H==="executing"?jsxs("span",{className:"flex items-center gap-2",children:[jsxs("svg",{className:"animate-spin h-3 w-3",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),jsx("path",{className:"opacity-75",fill:"currentColor",d:"m4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),String(n.name??"action")," is executing"]}):jsxs("span",{className:"flex items-center gap-1",children:[jsx("span",{className:"inline-block h-1.5 w-1.5 rounded-full",style:{backgroundColor:"#10b981"}}),String(n.name??"action")," has executed"]})})},s)}if(n.type==="ui-component"||n.type==="ui"){let c=String(n.name??n.component??"").trim(),H=c?ot.get(c):void 0;return H?jsx(H,{...n.props||{}}):jsxs("div",{className:"rounded-xl p-4",style:{backgroundColor:t.inputBackground,border:`1px solid ${t.borderColor}`},children:[jsxs("div",{className:"inline-flex items-center gap-2 text-xs mb-2",style:{color:t.mutedTextColor},children:[jsx("span",{className:"px-2 py-0.5 rounded",style:{backgroundColor:t.accentColor,border:`1px solid ${t.borderColor}`},children:"UI"}),jsx("span",{children:c||"component"}),jsx("span",{className:"ml-2 opacity-70",children:"(unregistered)"})]}),jsx("pre",{className:"text-xs overflow-auto",style:{color:t.mutedTextColor},children:JSON.stringify(n.props??{},null,2)})]},s)}return jsx("div",{className:"rounded-xl p-4 text-[14px]",style:{backgroundColor:t.cardBackground,border:`1px solid ${t.borderColor}`},children:jsx("pre",{className:"text-xs overflow-auto",style:{color:t.mutedTextColor},children:JSON.stringify(n,null,2)})},s)}return null})})}let J=Wt[p],t={primaryColor:m||J.primaryColor,backgroundColor:A||J.backgroundColor,borderColor:T||J.borderColor,textColor:z||J.textColor,accentColor:j||J.accentColor,mutedTextColor:J.mutedTextColor,inputBackground:J.inputBackground,cardBackground:J.cardBackground,hoverBackground:J.hoverBackground},vt={backgroundColor:t.backgroundColor,color:t.textColor,height:ce},kt={width:typeof Y=="number"?`${Y}px`:Y,maxWidth:typeof te=="number"?`${te}px`:te},wt={position:"fixed",bottom:typeof y.bottom=="number"?`${y.bottom}px`:y.bottom,right:y.right?typeof y.right=="number"?`${y.right}px`:y.right:void 0,top:y.top?typeof y.top=="number"?`${y.top}px`:y.top:void 0,left:y.left?typeof y.left=="number"?`${y.left}px`:y.left:void 0},Ne=typeof Ce=="number"?`${Ce}px`:Ce;return jsxs("div",{className:`flex h-full w-full ${tt}`,style:vt,dir:g,children:[jsx("div",{className:`flex items-stretch transition-all duration-1000 justify-stretch w-full h-full ${_&&Ze?"p-4":"p-0"}`,children:jsx("div",{className:"relative flex w-full h-full transition-all duration-1000 ease-out",style:{borderRadius:_&&$e?Ne:"0"},children:_&&$e?jsx("div",{className:`w-full h-full transition-all duration-600 ease-out ${h&&Ae?"tc-animated-border p-[1.5px]":"border p-0"}`,style:{borderRadius:Ne,borderColor:!h||!Ae?t.borderColor:"transparent"},children:jsx("div",{className:"w-full h-full",style:{borderRadius:Ne,backgroundColor:t.backgroundColor},children:u})}):jsx("div",{className:"w-full h-full",children:u})})}),jsxs("div",{className:`${rt} flex flex-col transition-all duration-300 ease-out overflow-hidden ${_||v?lt&&M?"fixed inset-0 z-50 w-full max-w-full px-6 py-6":"px-4 py-6 opacity-100 translate-x-0":`w-0 max-w-0 px-0 py-6 opacity-0 ${g==="rtl"?"translate-x-2":"-translate-x-2"} pointer-events-none`}`,style:{...kt,height:ce,backgroundColor:_||v?t.backgroundColor:"transparent"},children:[jsxs("div",{className:"mb-6 flex items-center justify-between",children:[jsx("div",{className:"min-w-0",children:jsx("h1",{title:He,className:"truncate text-[18px] font-semibold",style:{color:t.textColor},children:He})}),jsxs("div",{className:"flex items-center gap-2 relative",style:{color:t.mutedTextColor},children:[M&&jsx("button",{"aria-label":"Pop out",className:"rounded-lg p-2 transition-all duration-200 ease-out",style:{backgroundColor:"transparent",color:t.mutedTextColor},onMouseEnter:e=>{e.currentTarget.style.backgroundColor=t.hoverBackground,e.currentTarget.style.color=t.textColor;},onMouseLeave:e=>{e.currentTarget.style.backgroundColor="transparent",e.currentTarget.style.color=t.mutedTextColor;},onClick:()=>{pe(true),it(e=>!e);},children:jsx(IconArrowsMaximize,{size:20,stroke:2})}),jsx("button",{"aria-label":"New",className:"rounded-lg p-2 transition-all duration-200 ease-out",style:{backgroundColor:"transparent",color:t.mutedTextColor},onMouseEnter:e=>{e.currentTarget.style.backgroundColor=t.hoverBackground,e.currentTarget.style.color=t.textColor;},onMouseLeave:e=>{e.currentTarget.style.backgroundColor="transparent",e.currentTarget.style.color=t.mutedTextColor;},onClick:()=>{h||(w([]),U(null),W(null),L.current=false,X.current=null);},children:jsx(IconPlus,{size:20,stroke:2})}),jsx("button",{"aria-label":"History",className:"rounded-lg p-2 transition-all duration-200 ease-out",style:{backgroundColor:"transparent",color:t.mutedTextColor},onMouseEnter:e=>{e.currentTarget.style.backgroundColor=t.hoverBackground,e.currentTarget.style.color=t.textColor;},onMouseLeave:e=>{e.currentTarget.style.backgroundColor="transparent",e.currentTarget.style.color=t.mutedTextColor;},onClick:()=>ve(e=>!e),ref:gt,children:jsx(IconHistory,{size:20,stroke:2})}),nt&&createPortal(jsxs(Fragment,{children:[jsx("div",{className:"fixed inset-0 z-[900] bg-black/40 backdrop-blur-sm",onClick:()=>ve(false)}),jsxs("div",{ref:ft,className:"fixed left-1/2 top-16 -translate-x-1/2 z-[1000] w-[680px] max-w-[94vw] overflow-hidden rounded-2xl border border-[#2A2C33] bg-[#0F1116]/95 shadow-2xl ring-1 ring-black/10",children:[jsx("div",{className:"flex items-center gap-3 border-b border-[#2A2C33] px-4 py-3",children:jsx("div",{className:"flex-1",children:jsx("input",{autoFocus:true,value:De,onChange:e=>at(e.target.value),placeholder:"Search",className:"w-full rounded-lg bg-[#0B0B0F] px-3 py-2 text-sm text-[#EDEEF0] placeholder:text-[#9AA0A6] outline-none border border-[#2A2C33] focus:border-[#3a3d46]"})})}),jsx("div",{className:"max-h-[60vh] overflow-y-auto",children:(()=>{let e=De.toLowerCase().trim(),n=Me();return e&&(n=n.filter(r=>(r.title||"").toLowerCase().includes(e))),!n||n.length===0?jsx("div",{className:"p-6 text-[#9AA0A6]",children:"No chats found."}):jsx("ul",{className:"divide-y divide-[#2A2C33]",children:n.map(r=>jsx("li",{children:jsxs("div",{className:`flex w-full items-center justify-between gap-3 p-3 ${r.id===k?"bg-[#121318]":""}`,children:[jsx("button",{className:"flex-1 text-left transition-colors hover:bg-[#17181C] rounded-lg px-2 py-2",onClick:()=>{let s=qe(r.id);if(s){W(r.id),L.current=true,w(s.messages||[]);try{localStorage.setItem(V,r.id);}catch{}ve(false),pe(true);}},children:jsxs("div",{className:"flex items-center justify-between gap-3",children:[jsx("div",{className:"min-w-0",children:jsx("div",{className:"truncate text-[14px] text-[#EDEEF0]",children:r.title||"Untitled chat"})}),jsx("div",{className:"shrink-0 text-[12px] text-[#9AA0A6]",children:_t(r.updatedAt)})]})}),jsx("button",{className:"shrink-0 rounded-md p-2 text-[#9AA0A6] hover:text-red-300 hover:bg-red-500/10 border border-transparent hover:border-red-500/30",title:"Delete chat",onClick:s=>{s.stopPropagation(),xt(r.id),st(c=>c+1);},children:jsx(IconTrash,{size:16,stroke:2})})]})},r.id))})})()})]})]}),document.body),!v&&jsx("button",{"aria-label":"Close chat",className:"rounded-lg p-2 transition-all duration-200 ease-out",style:{backgroundColor:"transparent",color:t.mutedTextColor},onMouseEnter:e=>{e.currentTarget.style.backgroundColor=t.hoverBackground,e.currentTarget.style.color=t.textColor;},onMouseLeave:e=>{e.currentTarget.style.backgroundColor="transparent",e.currentTarget.style.color=t.mutedTextColor;},onClick:()=>pe(false),children:jsx(IconChevronRight,{size:20,stroke:2,style:{transform:g==="rtl"?"rotate(180deg)":"none"}})})]})]}),jsxs("div",{className:"flex-1 overflow-y-auto space-y-4 px-1 pb-4 pt-4",ref:dt,onScroll:e=>{let n=e.currentTarget,c=n.scrollHeight-(n.scrollTop+n.clientHeight)<=64;c!==ke&&pt(c);},children:[Oe&&jsx("div",{className:"mx-2 rounded-xl bg-red-500/10 text-red-300 border border-red-500/30 p-3 text-sm",children:Oe}),N.length===0&&!h&&jsx("div",{className:"mx-2 rounded-xl p-4",style:{border:`1px solid ${t.borderColor}`,backgroundColor:t.accentColor,color:t.mutedTextColor},children:"Start by sending a message to the agent."}),jsx("ul",{className:"space-y-4",children:N.map((e,n)=>jsx("li",{className:"px-1",children:e.role==="user"?ct===e.id?jsxs("div",{className:"max-w-[720px] rounded-2xl p-2 text-[15px] ring-2",style:{backgroundColor:t.accentColor,color:t.textColor,borderColor:t.primaryColor},children:[jsx("textarea",{autoFocus:true,className:"w-full resize-none bg-transparent p-2 leading-relaxed outline-none",rows:Math.max(2,Math.min(10,Math.ceil((fe||e.text).length/60))),value:fe,onChange:r=>Le(r.target.value),onKeyDown:r=>{r.key==="Escape"?ge(null):r.key==="Enter"&&!r.shiftKey&&(r.preventDefault(),h||ze(e.id,fe||e.text));}}),jsxs("div",{className:"flex items-center justify-end gap-2 px-2 pb-2",children:[jsx("button",{className:"rounded-lg px-3 py-1 text-sm transition-colors",style:{border:`1px solid ${t.borderColor}`,color:t.mutedTextColor,backgroundColor:"transparent"},onMouseEnter:r=>r.currentTarget.style.backgroundColor=t.inputBackground,onMouseLeave:r=>r.currentTarget.style.backgroundColor="transparent",onClick:()=>ge(null),children:"Cancel"}),jsx("button",{className:"rounded-lg px-3 py-1 text-sm transition-colors",style:{border:`1px solid ${t.borderColor}`,backgroundColor:t.cardBackground,color:t.textColor},onMouseEnter:r=>r.currentTarget.style.borderColor=t.primaryColor,onMouseLeave:r=>r.currentTarget.style.borderColor=t.borderColor,onClick:()=>{h||ze(e.id,fe||e.text);},children:"Save"})]})]}):jsx("div",{title:"Click to edit",onClick:()=>{h||(ge(e.id),Le(e.text));},className:"max-w-[720px] rounded-2xl p-4 text-[15px] leading-relaxed whitespace-pre-wrap cursor-pointer transition",style:{backgroundColor:t.accentColor,color:t.textColor},onMouseEnter:r=>r.currentTarget.style.backgroundColor=t.hoverBackground,onMouseLeave:r=>r.currentTarget.style.backgroundColor=t.accentColor,children:e.text}):jsxs("div",{className:"space-y-3",children:[e.reasoning&&jsxs("div",{className:"rounded-xl p-3 cursor-pointer",style:{backgroundColor:t.inputBackground,border:`1px solid ${t.borderColor}`},onClick:()=>{we.current=true,w(r=>r.map(s=>s.id===e.id&&s.role==="assistant"?{...s,reasoningOpen:!s.reasoningOpen}:s));},children:[jsxs("div",{className:"flex items-center justify-between mb-1",children:[jsx("div",{className:"text-xs",style:{color:t.mutedTextColor},children:"Reasoning"}),jsx("button",{type:"button",className:"text-xs transition-colors",style:{color:t.mutedTextColor},onMouseEnter:r=>r.currentTarget.style.color=t.textColor,onMouseLeave:r=>r.currentTarget.style.color=t.mutedTextColor,children:e.reasoningOpen?"Hide":"Show full"})]}),e.reasoningOpen?jsx("pre",{className:"text-xs whitespace-pre-wrap break-words",style:{color:t.mutedTextColor},children:e.reasoning}):(()=>{let r=(e.reasoning||"").trim().split(`
4
+ `).filter(c=>c.trim()),s=r.length>0?r[r.length-1]:"";return jsx("pre",{className:"text-xs whitespace-pre-wrap break-words",style:{color:t.mutedTextColor},children:s||"\u2026"})})()]}),ht(e.items),h&&n===N.length-1&&jsxs("div",{className:"flex items-center gap-2 text-xs",style:{color:t.mutedTextColor},children:[jsx("span",{className:"inline-block h-2 w-2 rounded-full animate-pulse",style:{backgroundColor:t.mutedTextColor}}),jsx("span",{children:"Working\u2026"})]})]})},e.id))}),jsx("div",{ref:Pe})]}),jsx("div",{className:"sticky bottom-0 mt-auto space-y-2 pb-2 pt-1",style:{backgroundColor:t.backgroundColor},children:jsx("div",{className:"relative flex-1",children:jsxs("div",{className:"relative w-full rounded-2xl pb-12 pt-4",style:{border:`1px solid ${t.borderColor}`,backgroundColor:t.accentColor},children:[jsx("div",{className:"px-4",children:jsx("textarea",{"aria-label":"Prompt",rows:2,className:"h-auto w-full resize-none bg-transparent text-[15px] leading-relaxed focus:outline-none hsafa-chat-textarea",style:{color:t.textColor},placeholder:et,value:de,onChange:e=>Fe(e.target.value),onKeyDown:e=>{e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),h||Ke());},ref:ut})}),jsxs("div",{className:"absolute bottom-2 left-2 flex items-center gap-1",style:{color:t.mutedTextColor},children:[jsx("button",{className:"rounded-lg p-2 transition-colors",style:{backgroundColor:"transparent"},onMouseEnter:e=>{e.currentTarget.style.backgroundColor=`${t.backgroundColor}99`,e.currentTarget.style.color=t.textColor;},onMouseLeave:e=>{e.currentTarget.style.backgroundColor="transparent",e.currentTarget.style.color=t.mutedTextColor;},"aria-label":"Attach files",children:jsx(IconPaperclip,{size:18,stroke:2})}),jsx("button",{className:"rounded-lg p-2 transition-colors",style:{backgroundColor:"transparent"},onMouseEnter:e=>{e.currentTarget.style.backgroundColor=`${t.backgroundColor}99`,e.currentTarget.style.color=t.textColor;},onMouseLeave:e=>{e.currentTarget.style.backgroundColor="transparent",e.currentTarget.style.color=t.mutedTextColor;},"aria-label":"Insert link",children:jsx(IconLink,{size:18,stroke:2})})]}),jsx("div",{className:"absolute bottom-2 right-2",children:jsx("button",{"aria-label":h?"Stop":"Send",disabled:!h&&!de.trim(),className:"rounded-xl p-3 transition-all duration-200 ease-out",style:{border:`1px solid ${h?"#ef4444":t.borderColor}`,backgroundColor:h?"#ef444420":t.cardBackground,color:h?"#ef4444":t.mutedTextColor,opacity:!h&&!de.trim()?.4:1},onMouseEnter:e=>{e.currentTarget.disabled||(h?(e.currentTarget.style.borderColor="#dc2626",e.currentTarget.style.backgroundColor="#dc262630",e.currentTarget.style.color="#dc2626"):(e.currentTarget.style.borderColor=t.primaryColor,e.currentTarget.style.backgroundColor=t.hoverBackground,e.currentTarget.style.color=t.textColor));},onMouseLeave:e=>{e.currentTarget.disabled||(h?(e.currentTarget.style.borderColor="#ef4444",e.currentTarget.style.backgroundColor="#ef444420",e.currentTarget.style.color="#ef4444"):(e.currentTarget.style.borderColor=t.borderColor,e.currentTarget.style.backgroundColor=t.cardBackground,e.currentTarget.style.color=t.mutedTextColor));},onClick:()=>{h?Ct():Ke();},children:h?jsx(IconPlayerStop,{size:18,stroke:2}):jsx(IconArrowUp,{size:18,stroke:2})})})]})})})]}),!_&&!v&&jsx("button",{"aria-label":"Open chat",onClick:()=>pe(true),className:"rounded-full border p-3 shadow-md transition-colors",style:{...wt,borderColor:t.borderColor,backgroundColor:t.accentColor,color:t.textColor,borderRadius:"50%"},onMouseEnter:e=>{e.currentTarget.style.borderColor=t.primaryColor,e.currentTarget.style.backgroundColor=`${t.accentColor}dd`;},onMouseLeave:e=>{e.currentTarget.style.borderColor=t.borderColor,e.currentTarget.style.backgroundColor=t.accentColor;},children:jsx(IconMessage,{size:20,stroke:2})}),jsx("style",{children:`
5
+ @keyframes tc-border-flow {
6
+ 0% { background-position: 0% 50%; }
7
+ 50% { background-position: 100% 50%; }
8
+ 100% { background-position: 0% 50%; }
9
+ }
10
+
11
+ .tc-animated-border {
12
+ position: relative;
13
+ /* Animated shimmer border using primary color */
14
+ background: linear-gradient(120deg,
15
+ ${t.primaryColor}dd 0%,
16
+ ${t.primaryColor}88 25%,
17
+ ${t.primaryColor}00 50%,
18
+ ${t.primaryColor}88 75%,
19
+ ${t.primaryColor}dd 100%
20
+ );
21
+ background-size: 300% 300%;
22
+ animation: tc-border-flow 3s ease-in-out infinite;
23
+ filter: drop-shadow(0 0 10px ${t.primaryColor}40);
24
+ }
25
+
26
+ .hsafa-chat-textarea::placeholder {
27
+ color: ${t.mutedTextColor};
28
+ }
29
+ `})]})}export{er as Button,Xt as HsafaChat,Et as HsafaProvider,lr as useAutoScroll,ee as useHsafa,mr as useHsafaAction,Cr as useHsafaComponent,nr as useToggle};//# sourceMappingURL=index.js.map
30
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/components/Button.module.css","../src/components/Button.tsx","../src/hooks/useToggle.ts","../src/hooks/useAutoScroll.ts","../src/providers/HsafaProvider.tsx","../src/hooks/useHsafaAction.ts","../src/hooks/useHsafaComponent.ts","../src/components/HsafaChat.tsx"],"names":["Button_default","Button","variant","size","loading","disabled","children","className","props","buttonClasses","jsxs","jsx","useToggle","initial","on","setOn","useState","toggle","useCallback","prev","setTrue","setFalse","useAutoScroll","ref","useRef","useEffect","el","observer","HsafaContext","createContext","HsafaProvider","baseUrl","actions","setActions","components","setComponents","registerAction","name","handler","next","existing","unregisterAction","registerComponent","component","unregisterComponent","value","useMemo","useHsafa","ctx","useContext","useHsafaAction","handlerRef","params","meta","useHsafaComponent","componentRef","timeAgo","ts","diff","s","h","d","w","months","joinUrl","path","a","b","themeColors","HsafaChat","agentId","theme","primaryColor","backgroundColor","borderColor","textColor","accentColor","width","maxWidth","height","expandable","alwaysOpen","defaultOpen","dir","floatingButtonPosition","enableBorderAnimation","enableContentPadding","borderRadius","enableContentBorder","placeholder","title","chatContainerClassName","LS_PREFIX","chatsIndexKey","chatKey","id","currentChatKey","showChatKey","setValue","showChat","setShowChat","savedShow","submitEdit_impl","messageId","newText","userText","setError","setStreaming","idx","messages","m","base","updatedUser","assistantId","genId","newMessages","setMessages","setEditingMessageId","history","payload","currentChatId","res","t","reader","decoder","buffer","done","idxNew","line","evt","actionExecMapRef","assistantMsgIdRef","calledFinalActionsRef","actionParamsHistoryRef","actionExecutionStatusRef","setActionStatuses","setCurrentChatId","hasChatRecordRef","firstUser","pendingFirstTitleRef","now","upsertChatMeta","saveChat","chunk","val","processActions","tokens","e","localId","streaming","error","abortControllerRef","historyOpen","setHistoryOpen","historySearch","setHistorySearch","historyTick","setHistoryTick","maximized","setMaximized","editingMessageId","editingMessageText","setEditingMessageText","textareaRef","scrollAnchorRef","scrollContainerRef","isAtBottom","setIsAtBottom","suppressNextScrollRef","historyBtnRef","historyPopupRef","actionStatuses","hasActionParamsStabilized","actionKey","currentParams","stringifiedParams","lastTwo","items","trigger","it","executeOnStream","key","isStabilized","currentStatus","loadChatsIndex","raw","saveChatsIndex","list","loadChat","data","x","deleteChatMeta","deleteChatData","deleteChat","savedCurrent","cd","handleStop","handleSend","userId","newUser","newAssistant","renderAssistantItems","status","resolvedColors","compName","Comp","themeColorScheme","containerStyles","chatPanelStyles","floatingButtonStyles","contentBorderRadius","IconArrowsMaximize","IconPlus","o","IconHistory","createPortal","Fragment","q","IconTrash","IconChevronRight","atBottom","i","lines","finalLine","IconPaperclip","IconLink","IconPlayerStop","IconArrowUp","IconMessage"],"mappings":"qVAAA,IAAAA,EAAA,EAAA,CCmCO,IAAMC,EAAAA,CAAgC,CAAC,CAC5C,OAAA,CAAAC,CAAAA,CAAU,SAAA,CACV,KAAAC,CAAAA,CAAO,IAAA,CACP,OAAA,CAAAC,CAAAA,CAAU,MACV,QAAA,CAAAC,CAAAA,CACA,QAAA,CAAAC,CAAAA,CACA,UAAAC,CAAAA,CACA,GAAGC,CACL,CAAA,GAAM,CACJ,IAAMC,CAAAA,CAAgB,CACpBT,CAAAA,CAAO,OACPA,CAAAA,CAAOE,CAAO,CAAA,CACdF,CAAAA,CAAOG,CAAI,CAAA,CACXC,CAAAA,EAAWJ,CAAAA,CAAO,OAAA,CAClBO,CACF,CAAA,CACG,MAAA,CAAO,OAAO,CAAA,CACd,KAAK,GAAG,CAAA,CAEX,OACEG,IAAAA,CAAC,UACC,SAAA,CAAWD,CAAAA,CACX,QAAA,CAAUJ,CAAAA,EAAYD,EACrB,GAAGI,CAAAA,CAEH,QAAA,CAAA,CAAAJ,CAAAA,EAAWO,IAAC,MAAA,CAAA,CAAK,SAAA,CAAWX,CAAAA,CAAO,OAAA,CAAS,EAC7CW,GAAAA,CAAC,MAAA,CAAA,CAAK,SAAA,CAAWP,CAAAA,CAAUJ,EAAO,UAAA,CAAa,MAAA,CAC5C,QAAA,CAAAM,CAAAA,CACH,GACF,CAE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A;AAAA;AAAA;AAAA;AAAA,cAAA,EAWOgM,EAAe,YAAY,CAAA;AAAA,cAAA,EAC3BA,EAAe,YAAY,CAAA;AAAA,cAAA,EAC3BA,EAAe,YAAY,CAAA;AAAA,cAAA,EAC3BA,EAAe,YAAY,CAAA;AAAA,cAAA,EAC3BA,EAAe,YAAY,CAAA;AAAA;AAAA;AAAA;AAAA,yCAAA,EAIAA,EAAe,YAAY,CAAA;AAAA;AAAA;AAAA;AAAA,mBAAA,EAIjDA,EAAe,cAAc,CAAA;AAAA;AAAA,QAAA,CAAA,CAG5C,GACF,CAEJ","file":"index.js","sourcesContent":["/* Base button styles */\n.button {\n position: relative;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n gap: 0.5rem;\n border: 1px solid transparent;\n border-radius: 0.75rem;\n font-weight: 600;\n font-family: inherit;\n cursor: pointer;\n transition: all 0.2s ease-in-out;\n text-decoration: none;\n white-space: nowrap;\n -webkit-user-select: none;\n -moz-user-select: none;\n user-select: none;\n}\n\n.button:disabled {\n cursor: not-allowed;\n opacity: 0.6;\n}\n\n/* Size variants */\n.sm {\n padding: 0.375rem 0.75rem;\n font-size: 0.875rem;\n line-height: 1.25rem;\n}\n\n.md {\n padding: 0.5rem 1rem;\n font-size: 1rem;\n line-height: 1.5rem;\n}\n\n.lg {\n padding: 0.75rem 1.5rem;\n font-size: 1.125rem;\n line-height: 1.75rem;\n}\n\n/* Color variants */\n.primary {\n background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);\n color: white;\n border-color: transparent;\n}\n\n.primary:hover:not(:disabled) {\n background: linear-gradient(135deg, #5a67d8 0%, #6b46c1 100%);\n transform: translateY(-1px);\n box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);\n}\n\n.secondary {\n background-color: #f7fafc;\n color: #2d3748;\n border-color: #e2e8f0;\n}\n\n.secondary:hover:not(:disabled) {\n background-color: #edf2f7;\n border-color: #cbd5e0;\n}\n\n.outline {\n background-color: transparent;\n color: #667eea;\n border-color: #667eea;\n}\n\n.outline:hover:not(:disabled) {\n background-color: #667eea;\n color: white;\n}\n\n.ghost {\n background-color: transparent;\n color: #4a5568;\n border-color: transparent;\n}\n\n.ghost:hover:not(:disabled) {\n background-color: #f7fafc;\n color: #2d3748;\n}\n\n/* Loading state */\n.loading {\n pointer-events: none;\n}\n\n.hiddenText {\n opacity: 0;\n}\n\n.spinner {\n position: absolute;\n width: 1rem;\n height: 1rem;\n border: 2px solid transparent;\n border-top: 2px solid currentColor;\n border-radius: 50%;\n animation: spin 1s linear infinite;\n}\n\n@keyframes spin {\n from {\n transform: rotate(0deg);\n }\n to {\n transform: rotate(360deg);\n }\n}\n","import React from \"react\";\nimport styles from \"./Button.module.css\";\n\n/**\n * Props for the Button component\n */\nexport interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {\n /** Visual style variant of the button */\n variant?: \"primary\" | \"secondary\" | \"outline\" | \"ghost\";\n /** Size of the button */\n size?: \"sm\" | \"md\" | \"lg\";\n /** Whether the button is in a loading state */\n loading?: boolean;\n /** Content to be displayed inside the button */\n children: React.ReactNode;\n}\n\n/**\n * A versatile button component with multiple variants, sizes, and states.\n * \n * @example\n * ```tsx\n * // Basic usage\n * <Button>Click me</Button>\n * \n * // With variant and size\n * <Button variant=\"secondary\" size=\"lg\">Large Secondary Button</Button>\n * \n * // Loading state\n * <Button loading>Processing...</Button>\n * \n * // With click handler\n * <Button onClick={() => console.log('Clicked!')}>Click me</Button>\n * ```\n */\nexport const Button: React.FC<ButtonProps> = ({\n variant = \"primary\",\n size = \"md\",\n loading = false,\n disabled,\n children,\n className,\n ...props\n}) => {\n const buttonClasses = [\n styles.button,\n styles[variant],\n styles[size],\n loading && styles.loading,\n className,\n ]\n .filter(Boolean)\n .join(\" \");\n\n return (\n <button\n className={buttonClasses}\n disabled={disabled || loading}\n {...props}\n >\n {loading && <span className={styles.spinner} />}\n <span className={loading ? styles.hiddenText : undefined}>\n {children}\n </span>\n </button>\n );\n};\n","import { useCallback, useState } from \"react\";\n\nexport interface UseToggleReturn {\n /** Current toggle state */\n on: boolean;\n /** Toggle the state */\n toggle: () => void;\n /** Set the state directly */\n setOn: (value: boolean | ((prev: boolean) => boolean)) => void;\n /** Set state to true */\n setTrue: () => void;\n /** Set state to false */\n setFalse: () => void;\n}\n\n/**\n * A hook for managing boolean toggle state\n * @param initial - Initial state value (default: false)\n * @returns Object with toggle state and control functions\n */\nexport function useToggle(initial = false): UseToggleReturn {\n const [on, setOn] = useState(initial);\n \n const toggle = useCallback(() => setOn(prev => !prev), []);\n const setTrue = useCallback(() => setOn(true), []);\n const setFalse = useCallback(() => setOn(false), []);\n\n return { \n on, \n toggle, \n setOn, \n setTrue, \n setFalse \n };\n}\n","import { useEffect, useRef } from \"react\";\n\nexport function useAutoScroll<T extends HTMLElement>() {\n const ref = useRef<T | null>(null);\n\n useEffect(() => {\n const el = ref.current;\n if (!el) return;\n\n const observer = new MutationObserver(() => {\n el.scrollTop = el.scrollHeight;\n });\n\n observer.observe(el, { childList: true, subtree: true });\n el.scrollTop = el.scrollHeight;\n\n return () => observer.disconnect();\n }, []);\n\n return ref;\n}\n","import React, { createContext, useCallback, useContext, useMemo, useState } from \"react\";\n\n/**\n * Handler function for custom actions that can be triggered by the AI agent\n */\nexport type HsafaActionHandler = (params: any, meta: {\n /** Name of the action being called */\n name: string;\n /** When the action is being triggered */\n trigger: 'partial' | 'final' | 'params_complete';\n /** Index of the action in the sequence */\n index: number;\n /** ID of the assistant message that triggered this action */\n assistantMessageId?: string;\n /** ID of the current chat session */\n chatId?: string;\n}) => Promise<any> | any;\n\n/**\n * Configuration options for the Hsafa SDK\n */\nexport interface HsafaConfig {\n /** Base URL for agent API calls, e.g. \"\" (same origin) or \"https://example.com\" */\n baseUrl?: string;\n}\n\n/**\n * Context value provided by HsafaProvider\n */\nexport interface HsafaContextValue extends HsafaConfig {\n /** Registered custom actions */\n actions: Map<string, HsafaActionHandler>;\n /** Registered custom components */\n components: Map<string, React.ComponentType<any>>;\n /** Register a custom action handler */\n registerAction: (name: string, handler: HsafaActionHandler) => () => void;\n /** Unregister a custom action handler */\n unregisterAction: (name: string, handler?: HsafaActionHandler) => void;\n /** Register a custom component */\n registerComponent: (name: string, component: React.ComponentType<any>) => () => void;\n /** Unregister a custom component */\n unregisterComponent: (name: string, component?: React.ComponentType<any>) => void;\n}\n\nconst HsafaContext = createContext<HsafaContextValue | undefined>(undefined);\n\n/**\n * Props for the HsafaProvider component\n */\nexport interface HsafaProviderProps extends HsafaConfig {\n /** Child components that will have access to the Hsafa context */\n children: React.ReactNode;\n}\n\n/**\n * Provider component that sets up the Hsafa context for the SDK.\n * Wrap your app or chat components with this provider to enable Hsafa functionality.\n * \n * @example\n * ```tsx\n * <HsafaProvider baseUrl=\"https://api.example.com\">\n * <HsafaChat agentId=\"my-agent\" />\n * </HsafaProvider>\n * ```\n */\nexport function HsafaProvider({ baseUrl, children }: HsafaProviderProps) {\n const [actions, setActions] = useState<Map<string, HsafaActionHandler>>(new Map());\n const [components, setComponents] = useState<Map<string, React.ComponentType<any>>>(new Map());\n\n const registerAction = useCallback((name: string, handler: HsafaActionHandler) => {\n setActions(prev => {\n const next = new Map(prev);\n next.set(String(name), handler);\n return next;\n });\n return () => {\n setActions(prev => {\n const next = new Map(prev);\n const existing = next.get(String(name));\n if (!handler || existing === handler) next.delete(String(name));\n return next;\n });\n };\n }, []);\n\n const unregisterAction = useCallback((name: string, handler?: HsafaActionHandler) => {\n setActions(prev => {\n const next = new Map(prev);\n const existing = next.get(String(name));\n if (!handler || existing === handler) next.delete(String(name));\n return next;\n });\n }, []);\n\n const registerComponent = useCallback((name: string, component: React.ComponentType<any>) => {\n setComponents(prev => {\n const next = new Map(prev);\n next.set(String(name), component);\n return next;\n });\n return () => {\n setComponents(prev => {\n const next = new Map(prev);\n const existing = next.get(String(name));\n if (!component || existing === component) next.delete(String(name));\n return next;\n });\n };\n }, []);\n\n const unregisterComponent = useCallback((name: string, component?: React.ComponentType<any>) => {\n setComponents(prev => {\n const next = new Map(prev);\n const existing = next.get(String(name));\n if (!component || existing === component) next.delete(String(name));\n return next;\n });\n }, []);\n\n const value: HsafaContextValue = useMemo(() => ({\n baseUrl,\n actions,\n components,\n registerAction,\n unregisterAction,\n registerComponent,\n unregisterComponent,\n }), [baseUrl, actions, components, registerAction, unregisterAction, registerComponent, unregisterComponent]);\n\n return (\n <HsafaContext.Provider value={value}>\n {children}\n </HsafaContext.Provider>\n );\n}\n\n/**\n * Hook to access the Hsafa context.\n * Must be used within a HsafaProvider.\n * \n * @returns The Hsafa context value with actions, components, and configuration\n * \n * @example\n * ```tsx\n * function MyComponent() {\n * const { registerAction, baseUrl } = useHsafa();\n * \n * useEffect(() => {\n * const unregister = registerAction('myAction', async (params) => {\n * console.log('Action called with:', params);\n * return { success: true };\n * });\n * \n * return unregister;\n * }, [registerAction]);\n * \n * return <div>My Component</div>;\n * }\n * ```\n */\nexport function useHsafa(): HsafaContextValue {\n const ctx = useContext(HsafaContext);\n if (!ctx) return {\n baseUrl: undefined,\n actions: new Map(),\n components: new Map(),\n registerAction: () => () => undefined,\n unregisterAction: () => undefined,\n registerComponent: () => () => undefined,\n unregisterComponent: () => undefined,\n };\n return ctx;\n}\n","import { useEffect, useRef } from 'react';\nimport { useHsafa } from '../providers/HsafaProvider';\nimport type { HsafaActionHandler } from '../providers/HsafaProvider';\n\n/**\n * Register an action handler by name within the nearest HsafaProvider.\n * The handler will be automatically unregistered on unmount.\n */\nexport function useHsafaAction(name: string, handler: HsafaActionHandler) {\n const { registerAction } = useHsafa();\n const handlerRef = useRef(handler);\n\n // Keep latest handler without re-registering name\n useEffect(() => {\n handlerRef.current = handler;\n }, [handler]);\n\n useEffect(() => {\n if (!name || typeof handlerRef.current !== 'function') return;\n const unregister = registerAction(name, (params, meta) => handlerRef.current(params, meta));\n return unregister;\n }, [name, registerAction]);\n}\n","import { useEffect, useRef } from 'react';\nimport type { ComponentType } from 'react';\nimport { useHsafa } from '../providers/HsafaProvider';\n\n/**\n * Register a UI component by name within the nearest HsafaProvider.\n * The component will be automatically unregistered on unmount.\n */\nexport function useHsafaComponent(name: string, component: ComponentType<any>) {\n const { registerComponent } = useHsafa();\n const componentRef = useRef(component);\n\n // Keep latest component without re-registering name\n useEffect(() => {\n componentRef.current = component;\n }, [component]);\n\n useEffect(() => {\n if (!name || typeof componentRef.current !== 'function') return;\n const unregister = registerComponent(name, componentRef.current as ComponentType<any>);\n return unregister;\n }, [name, registerComponent]);\n}\n","import React, { useCallback, useEffect, useRef, useState } from \"react\";\nimport { createPortal } from \"react-dom\";\nimport {\n IconArrowsMaximize,\n IconPlus,\n IconHistory,\n IconChevronRight,\n IconPaperclip,\n IconLink,\n IconArrowUp,\n IconMessage,\n IconTrash,\n IconPlayerStop,\n} from \"@tabler/icons-react\";\nimport { useHsafa } from \"../providers/HsafaProvider\";\n\n// Lightweight relative time helper (e.g., 1m, 6h, 7h)\nfunction timeAgo(ts: number): string {\n const diff = Date.now() - ts;\n const s = Math.max(1, Math.floor(diff / 1000));\n if (s < 60) return `${s}s`;\n const m = Math.floor(s / 60);\n if (m < 60) return `${m}m`;\n const h = Math.floor(m / 60);\n if (h < 24) return `${h}h`;\n const d = Math.floor(h / 24);\n if (d < 7) return `${d}d`;\n const w = Math.floor(d / 7);\n if (w < 4) return `${w}w`;\n const months = Math.floor(d / 30);\n if (months < 12) return `${months}mo`;\n const y = Math.floor(months / 12);\n return `${y}y`;\n}\n\nexport interface HsafaChatProps {\n agentId: string;\n children?: React.ReactNode;\n \n // Theme\n theme?: 'dark' | 'light';\n \n // Color customization (overrides theme colors if provided)\n primaryColor?: string;\n backgroundColor?: string;\n borderColor?: string;\n textColor?: string;\n accentColor?: string;\n \n // Layout customization\n width?: number | string;\n maxWidth?: number | string;\n height?: string;\n \n // Behavior customization\n expandable?: boolean;\n alwaysOpen?: boolean;\n defaultOpen?: boolean;\n \n // Floating button customization\n floatingButtonPosition?: {\n bottom?: number | string;\n right?: number | string;\n top?: number | string;\n left?: number | string;\n };\n \n // Border and styling customization\n enableBorderAnimation?: boolean;\n enableContentPadding?: boolean;\n borderRadius?: number | string;\n enableContentBorder?: boolean;\n \n // Additional customization\n placeholder?: string;\n title?: string;\n className?: string;\n chatContainerClassName?: string;\n \n // Text direction\n dir?: 'rtl' | 'ltr';\n}\n\ntype ChatMessage =\n | { id: string; role: 'user'; text: string; requestParams?: any }\n | {\n id: string;\n role: 'assistant';\n items: any[];\n reasoning?: string;\n reasoningOpen?: boolean;\n reasoningTokens?: number;\n requestParams?: any;\n };\n\nfunction joinUrl(baseUrl: string | undefined, path: string): string {\n if (!baseUrl) return path;\n const a = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl;\n const b = path.startsWith('/') ? path : `/${path}`;\n return `${a}${b}`;\n}\n\n// Theme color schemes\nconst themeColors = {\n dark: {\n primaryColor: '#4D78FF',\n backgroundColor: '#0B0B0F',\n borderColor: '#2A2C33',\n textColor: '#EDEEF0',\n accentColor: '#17181C',\n mutedTextColor: '#9AA0A6',\n inputBackground: '#17181C',\n cardBackground: '#121318',\n hoverBackground: '#1c1e25',\n },\n light: {\n primaryColor: '#2563EB',\n backgroundColor: '#FFFFFF',\n borderColor: '#E5E7EB',\n textColor: '#111827',\n accentColor: '#F9FAFB',\n mutedTextColor: '#6B7280',\n inputBackground: '#F9FAFB',\n cardBackground: '#F3F4F6',\n hoverBackground: '#F3F4F6',\n }\n};\n\nexport function HsafaChat({ \n agentId, \n children,\n // Theme\n theme = 'dark',\n // Color customization (overrides theme colors if provided)\n primaryColor,\n backgroundColor,\n borderColor,\n textColor,\n accentColor,\n // Layout customization\n width = 420,\n maxWidth = 420,\n height = '100vh',\n // Behavior customization\n expandable = true,\n alwaysOpen = false,\n defaultOpen = true,\n // Text direction\n dir = 'ltr',\n // Floating button customization\n floatingButtonPosition = dir === 'rtl' ? { bottom: 16, left: 16 } : { bottom: 16, right: 16 },\n // Border and styling customization\n enableBorderAnimation = true,\n enableContentPadding = true,\n borderRadius = 16,\n enableContentBorder = true,\n // Additional customization\n placeholder = 'Ask your question...',\n title = 'Agent',\n className = '',\n chatContainerClassName = ''\n}: HsafaChatProps) {\n const { baseUrl, actions, components } = useHsafa();\n const LS_PREFIX = 'hsafaChat';\n const chatsIndexKey = `${LS_PREFIX}.chats`;\n const chatKey = (id: string) => `${LS_PREFIX}.chat.${id}`;\n const currentChatKey = `${LS_PREFIX}.currentChatId`;\n const showChatKey = `${LS_PREFIX}.showChat`;\n\n const [value, setValue] = useState<string>(\"\");\n const [showChat, setShowChat] = useState<boolean>(() => {\n if (alwaysOpen) return true;\n try {\n const savedShow = localStorage.getItem(showChatKey);\n return savedShow !== null ? savedShow === 'true' : defaultOpen;\n } catch {\n return defaultOpen;\n }\n });\n\n // Submit an inline edit: replace the clicked user message, truncate after it, and re-run\n async function submitEdit_impl(messageId: string, newText: string) {\n if (!agentId) return;\n const userText = newText.trim();\n if (!userText) return;\n setError(null);\n setStreaming(true);\n\n const idx = messages.findIndex(m => m.id === messageId);\n if (idx === -1 || messages[idx].role !== 'user') {\n setStreaming(false);\n return;\n }\n\n const base = messages.slice(0, idx); // messages before the edited one\n const updatedUser: ChatMessage = { id: messageId, role: 'user', text: userText };\n const assistantId = genId();\n const newMessages: ChatMessage[] = [\n ...base,\n updatedUser,\n { id: assistantId, role: 'assistant', items: [], reasoning: '', reasoningOpen: false },\n ];\n setMessages(newMessages);\n setEditingMessageId(null);\n\n try {\n // Build history: base mapped + edited user\n const history = [\n ...base.map(m => (m.role === 'user' ? { role: 'user' as const, content: m.text } : { role: 'assistant' as const, items: Array.isArray(m.items) ? m.items : [] })),\n { role: 'user' as const, content: userText },\n ];\n const payload: any = {\n prompt: userText,\n chatId: currentChatId ?? undefined,\n messages: history,\n };\n setMessages(prev => prev.map(m => (m.id === assistantId || m.id === messageId ? { ...m, requestParams: payload } as any : m)));\n\n const res = await fetch(joinUrl(baseUrl, `/api/run/${agentId}`), {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(payload),\n });\n if (!res.ok || !res.body) {\n const t = await res.text().catch(() => '');\n throw new Error(t || `Request failed with ${res.status}`);\n }\n const reader = res.body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value, { stream: true });\n let idxNew;\n while ((idxNew = buffer.indexOf('\\n')) !== -1) {\n const line = buffer.slice(0, idxNew).trim();\n buffer = buffer.slice(idxNew + 1);\n if (!line) continue;\n try {\n const evt = JSON.parse(line);\n if (evt?.type === 'meta') {\n // Capture execution preferences and assistant message id\n if (evt.actionExecuteMap && typeof evt.actionExecuteMap === 'object') {\n actionExecMapRef.current = evt.actionExecuteMap as Record<string, boolean>;\n }\n if (evt.assistantMessageId) {\n assistantMsgIdRef.current = String(evt.assistantMessageId);\n calledFinalActionsRef.current.clear();\n // Reset action tracking for new message\n actionParamsHistoryRef.current.clear();\n actionExecutionStatusRef.current.clear();\n setActionStatuses(new Map());\n }\n if (evt.chatId && !currentChatId) {\n setCurrentChatId(evt.chatId);\n hasChatRecordRef.current = true;\n const firstUser = userText;\n const title = (pendingFirstTitleRef.current || firstUser || 'New chat').slice(0, 80);\n const now = Date.now();\n upsertChatMeta({ id: evt.chatId, title, createdAt: now, updatedAt: now });\n saveChat({ id: evt.chatId, messages: newMessages, agentId });\n try { localStorage.setItem(currentChatKey, evt.chatId); } catch {}\n }\n continue;\n }\n if (evt?.type === 'reasoning') {\n const chunk = String(evt.text ?? '');\n setMessages(prev => prev.map(m => (m.id === assistantId && m.role === 'assistant' ? { ...m, reasoning: (m.reasoning ?? '') + chunk } : m)));\n continue;\n }\n if (evt?.type === 'partial' || evt?.type === 'final') {\n const val = evt.value;\n if (val && Array.isArray(val.items)) {\n setMessages(prev => prev.map(m => (m.id === assistantId && m.role === 'assistant' ? { ...m, items: val.items } : m)));\n // Process actions based on trigger and executeOnStream preference\n processActions(val.items, evt.type === 'partial' ? 'partial' : 'final');\n }\n if (evt?.type === 'final') {\n setMessages(prev => prev.map(m => (m.id === assistantId && m.role === 'assistant' ? { ...m, reasoningOpen: false } : m)));\n }\n continue;\n }\n if (evt?.type === 'usage') {\n const tokens = evt?.value?.reasoningTokens;\n if (typeof tokens === 'number') {\n setMessages(prev => prev.map(m => (m.id === assistantId && m.role === 'assistant' ? { ...m, reasoningTokens: tokens } : m)));\n }\n continue;\n }\n if (evt?.type === 'error') {\n setError(String(evt.error ?? 'Unknown error'));\n continue;\n }\n } catch {\n // ignore malformed lines\n }\n }\n }\n } catch (e: any) {\n setError(String(e?.message ?? e));\n } finally {\n setStreaming(false);\n if (!currentChatId && !hasChatRecordRef.current) {\n const localId = `local-${genId()}`;\n setCurrentChatId(localId);\n hasChatRecordRef.current = true;\n const title = (pendingFirstTitleRef.current || 'New chat').slice(0, 80);\n const now = Date.now();\n upsertChatMeta({ id: localId, title, createdAt: now, updatedAt: now });\n saveChat({ id: localId, messages: messages, agentId });\n try { localStorage.setItem(currentChatKey, localId); } catch {}\n }\n }\n }\n\n const [messages, setMessages] = useState<ChatMessage[]>([]);\n const [streaming, setStreaming] = useState(false);\n const [error, setError] = useState<string | null>(null);\n const abortControllerRef = useRef<AbortController | null>(null);\n const [currentChatId, setCurrentChatId] = useState<string | null>(null);\n const [historyOpen, setHistoryOpen] = useState<boolean>(false);\n const [historySearch, setHistorySearch] = useState<string>(\"\");\n const [historyTick, setHistoryTick] = useState<number>(0);\n const [maximized, setMaximized] = useState<boolean>(false);\n const [editingMessageId, setEditingMessageId] = useState<string | null>(null);\n const [editingMessageText, setEditingMessageText] = useState<string>(\"\");\n const textareaRef = useRef<HTMLTextAreaElement | null>(null);\n\n const scrollAnchorRef = useRef<HTMLDivElement | null>(null);\n const scrollContainerRef = useRef<HTMLDivElement | null>(null);\n const [isAtBottom, setIsAtBottom] = useState<boolean>(true);\n const suppressNextScrollRef = useRef<boolean>(false);\n const hasChatRecordRef = useRef<boolean>(false);\n const pendingFirstTitleRef = useRef<string | null>(null);\n const historyBtnRef = useRef<HTMLButtonElement | null>(null);\n const historyPopupRef = useRef<HTMLDivElement | null>(null);\n\n // Streaming meta refs\n const actionExecMapRef = useRef<Record<string, boolean>>({});\n const assistantMsgIdRef = useRef<string | undefined>(undefined);\n const calledFinalActionsRef = useRef<Set<string>>(new Set());\n \n // Action parameter tracking for completion detection\n const actionParamsHistoryRef = useRef<Map<string, any[]>>(new Map());\n const actionExecutionStatusRef = useRef<Map<string, 'executing' | 'executed'>>(new Map());\n const [actionStatuses, setActionStatuses] = useState<Map<string, 'executing' | 'executed'>>(new Map());\n\n // Helper to detect if action parameters have stabilized (finished streaming)\n const hasActionParamsStabilized = useCallback((actionKey: string, currentParams: any): boolean => {\n const history = actionParamsHistoryRef.current.get(actionKey) || [];\n const stringifiedParams = JSON.stringify(currentParams);\n \n // Add current params to history\n history.push(stringifiedParams);\n \n // Keep only last 3 entries to detect stabilization\n if (history.length > 3) {\n history.shift();\n }\n \n actionParamsHistoryRef.current.set(actionKey, history);\n \n // Consider stabilized if params haven't changed in last 2 updates\n if (history.length >= 2) {\n const lastTwo = history.slice(-2);\n return lastTwo[0] === lastTwo[1];\n }\n \n return false;\n }, []);\n\n const processActions = useCallback((items: any[] | undefined, trigger: 'partial' | 'final') => {\n if (!Array.isArray(items) || items.length === 0) return;\n \n items.forEach((it, idx) => {\n if (!it || typeof it !== 'object') return;\n if (it.type === 'action') {\n const name = String(it.name ?? '').trim();\n if (!name) return;\n const handler = actions.get(name);\n if (!handler) return;\n \n const executeOnStream = !!actionExecMapRef.current[name];\n const key = `${assistantMsgIdRef.current || 'assist'}:${name}:${idx}`;\n const actionKey = `${name}:${idx}`;\n \n try {\n if (trigger === 'partial' && executeOnStream) {\n // Execute on each partial update (streaming mode)\n setActionStatuses(prev => new Map(prev).set(actionKey, 'executing'));\n Promise.resolve(handler(it.params, { name, trigger, index: idx, assistantMessageId: assistantMsgIdRef.current, chatId: currentChatId || undefined })).catch(() => {});\n } else if (trigger === 'partial' && !executeOnStream) {\n // Check if action parameters have stabilized (finished streaming)\n const isStabilized = hasActionParamsStabilized(actionKey, it.params);\n const currentStatus = actionExecutionStatusRef.current.get(actionKey);\n \n if (isStabilized && currentStatus !== 'executed') {\n // Parameters have stabilized, execute the action\n actionExecutionStatusRef.current.set(actionKey, 'executed');\n setActionStatuses(prev => new Map(prev).set(actionKey, 'executed'));\n \n Promise.resolve(handler(it.params, { \n name, \n trigger: 'params_complete', \n index: idx, \n assistantMessageId: assistantMsgIdRef.current, \n chatId: currentChatId || undefined \n })).catch(() => {});\n } else if (!currentStatus) {\n // First time seeing this action, mark as executing\n actionExecutionStatusRef.current.set(actionKey, 'executing');\n setActionStatuses(prev => new Map(prev).set(actionKey, 'executing'));\n }\n } else if (trigger === 'final') {\n // Final trigger - ensure action is executed if not already\n const currentStatus = actionExecutionStatusRef.current.get(actionKey);\n if (currentStatus !== 'executed' && !calledFinalActionsRef.current.has(key)) {\n calledFinalActionsRef.current.add(key);\n actionExecutionStatusRef.current.set(actionKey, 'executed');\n setActionStatuses(prev => new Map(prev).set(actionKey, 'executed'));\n \n Promise.resolve(handler(it.params, { \n name, \n trigger: executeOnStream ? 'final' : 'params_complete', \n index: idx, \n assistantMessageId: assistantMsgIdRef.current, \n chatId: currentChatId || undefined \n })).catch(() => {});\n }\n }\n } catch {}\n }\n });\n }, [actions, currentChatId, hasActionParamsStabilized]);\n\n type ChatMeta = { id: string; title: string; createdAt: number; updatedAt: number };\n type ChatData = { id: string; messages: ChatMessage[]; agentId?: string };\n\n const loadChatsIndex = (): ChatMeta[] => {\n try {\n const raw = localStorage.getItem(chatsIndexKey);\n return raw ? JSON.parse(raw) : [];\n } catch { return []; }\n };\n const saveChatsIndex = (list: ChatMeta[]) => {\n try { localStorage.setItem(chatsIndexKey, JSON.stringify(list)); } catch {}\n };\n const loadChat = (id: string): ChatData | null => {\n try { const raw = localStorage.getItem(chatKey(id)); return raw ? JSON.parse(raw) : null; } catch { return null; }\n };\n const saveChat = (data: ChatData) => {\n try { localStorage.setItem(chatKey(data.id), JSON.stringify(data)); } catch {}\n };\n const upsertChatMeta = (meta: ChatMeta) => {\n const list = loadChatsIndex();\n const idx = list.findIndex(x => x.id === meta.id);\n if (idx >= 0) list[idx] = meta; else list.unshift(meta);\n saveChatsIndex(list);\n };\n const deleteChatMeta = (id: string) => {\n const list = loadChatsIndex();\n const next = list.filter(x => x.id !== id);\n saveChatsIndex(next);\n };\n const deleteChatData = (id: string) => {\n try { localStorage.removeItem(chatKey(id)); } catch {}\n };\n const deleteChat = (id: string) => {\n deleteChatData(id);\n deleteChatMeta(id);\n if (currentChatId === id) {\n setMessages([]);\n setError(null);\n setCurrentChatId(null);\n hasChatRecordRef.current = false;\n pendingFirstTitleRef.current = null;\n try { localStorage.removeItem(currentChatKey); } catch {}\n }\n };\n\n useEffect(() => {\n if (suppressNextScrollRef.current) {\n suppressNextScrollRef.current = false;\n return;\n }\n if (!isAtBottom) return;\n scrollAnchorRef.current?.scrollIntoView({ behavior: 'smooth', block: 'end' });\n }, [messages, streaming, isAtBottom]);\n\n useEffect(() => {\n try {\n const savedCurrent = localStorage.getItem(currentChatKey);\n if (savedCurrent) {\n const cd = loadChat(savedCurrent);\n if (cd) {\n setCurrentChatId(cd.id);\n hasChatRecordRef.current = true;\n setMessages(cd.messages || []);\n }\n }\n } catch {}\n }, []);\n\n useEffect(() => {\n try { localStorage.setItem(showChatKey, String(showChat)); } catch {}\n }, [showChat]);\n\n useEffect(() => {\n if (!currentChatId || !hasChatRecordRef.current) return;\n const data: ChatData = { id: currentChatId, messages, agentId };\n saveChat(data);\n const firstUser = messages.find(m => (m as any).role === 'user') as any;\n const title = (pendingFirstTitleRef.current || (firstUser?.text ?? 'New chat')).slice(0, 80);\n const meta: ChatMeta = { id: currentChatId, title, createdAt: Date.now(), updatedAt: Date.now() };\n upsertChatMeta(meta);\n try { localStorage.setItem(currentChatKey, currentChatId); } catch {}\n }, [messages, currentChatId, agentId]);\n\n const genId = () => `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;\n\n function handleStop() {\n if (abortControllerRef.current) {\n abortControllerRef.current.abort();\n abortControllerRef.current = null;\n }\n setStreaming(false);\n setError(\"Request stopped by user\");\n }\n\n async function handleSend() {\n if (!agentId) return;\n const userText = value.trim();\n if (!userText) return;\n setError(null);\n setStreaming(true);\n if (!currentChatId && messages.length === 0) {\n pendingFirstTitleRef.current = userText;\n }\n\n let userId = genId();\n let assistantId = genId();\n const newUser = { id: userId, role: 'user' as const, text: userText };\n const newAssistant = { id: assistantId, role: 'assistant' as const, items: [], reasoning: '', reasoningOpen: false };\n const newMessages: ChatMessage[] = [...messages, newUser, newAssistant];\n const history = [\n ...messages.map(m => (m.role === 'user' ? { role: 'user' as const, content: m.text } : { role: 'assistant' as const, items: Array.isArray(m.items) ? m.items : [] })),\n { role: 'user' as const, content: userText },\n ];\n setMessages(newMessages);\n setValue(\"\");\n\n try {\n // Create new AbortController for this request\n abortControllerRef.current = new AbortController();\n \n const payload: any = {\n prompt: userText,\n chatId: currentChatId ?? undefined,\n messages: history,\n };\n\n setMessages(prev => prev.map(m => (m.id === assistantId || m.id === userId ? { ...m, requestParams: payload } as any : m)));\n\n const res = await fetch(joinUrl(baseUrl, `/api/run/${agentId}`), {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(payload),\n signal: abortControllerRef.current.signal,\n });\n if (!res.ok || !res.body) {\n const t = await res.text().catch(() => '');\n throw new Error(t || `Request failed with ${res.status}`);\n }\n const reader = res.body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value, { stream: true });\n let idx;\n while ((idx = buffer.indexOf('\\n')) !== -1) {\n const line = buffer.slice(0, idx).trim();\n buffer = buffer.slice(idx + 1);\n if (!line) continue;\n try {\n const evt = JSON.parse(line);\n if (evt?.type === 'meta') {\n // Capture execution preferences and assistant message id\n if (evt.actionExecuteMap && typeof evt.actionExecuteMap === 'object') {\n actionExecMapRef.current = evt.actionExecuteMap as Record<string, boolean>;\n }\n if (evt.assistantMessageId) {\n assistantMsgIdRef.current = String(evt.assistantMessageId);\n calledFinalActionsRef.current.clear();\n // Reset action tracking for new message\n actionParamsHistoryRef.current.clear();\n actionExecutionStatusRef.current.clear();\n setActionStatuses(new Map());\n }\n if (evt.chatId && !currentChatId) {\n setCurrentChatId(evt.chatId);\n hasChatRecordRef.current = true;\n const firstUser = userText;\n const title = (pendingFirstTitleRef.current || firstUser || 'New chat').slice(0, 80);\n const now = Date.now();\n upsertChatMeta({ id: evt.chatId, title, createdAt: now, updatedAt: now });\n saveChat({ id: evt.chatId, messages: newMessages, agentId });\n try { localStorage.setItem(currentChatKey, evt.chatId); } catch {}\n }\n continue;\n }\n if (evt?.type === 'reasoning') {\n const chunk = String(evt.text ?? '');\n setMessages(prev => prev.map(m => (m.id === assistantId && m.role === 'assistant' ? { ...m, reasoning: (m.reasoning ?? '') + chunk } : m)));\n continue;\n }\n if (evt?.type === 'partial' || evt?.type === 'final') {\n const val = evt.value;\n if (val && Array.isArray(val.items)) {\n setMessages(prev => prev.map(m => (m.id === assistantId && m.role === 'assistant' ? { ...m, items: val.items } : m)));\n // Process actions based on trigger and executeOnStream preference\n processActions(val.items, evt.type === 'partial' ? 'partial' : 'final');\n }\n if (evt?.type === 'final') {\n setMessages(prev => prev.map(m => (m.id === assistantId && m.role === 'assistant' ? { ...m, reasoningOpen: false } : m)));\n }\n continue;\n }\n if (evt?.type === 'usage') {\n const tokens = evt?.value?.reasoningTokens;\n if (typeof tokens === 'number') {\n setMessages(prev => prev.map(m => (m.id === assistantId && m.role === 'assistant' ? { ...m, reasoningTokens: tokens } : m)));\n }\n continue;\n }\n if (evt?.type === 'error') {\n setError(String(evt.error ?? 'Unknown error'));\n continue;\n }\n } catch {\n // ignore malformed lines\n }\n }\n }\n } catch (e: any) {\n setError(String(e?.message ?? e));\n } finally {\n setStreaming(false);\n if (!currentChatId && !hasChatRecordRef.current) {\n const localId = `local-${genId()}`;\n setCurrentChatId(localId);\n hasChatRecordRef.current = true;\n const title = (pendingFirstTitleRef.current || 'New chat').slice(0, 80);\n const now = Date.now();\n upsertChatMeta({ id: localId, title, createdAt: now, updatedAt: now });\n saveChat({ id: localId, messages: messages, agentId });\n try { localStorage.setItem(currentChatKey, localId); } catch {}\n }\n }\n }\n\n function renderAssistantItems(items: any[]) {\n if (!Array.isArray(items) || items.length === 0) return null;\n return (\n <div className=\"space-y-3\">\n {items.map((it, idx) => {\n const key = `it-${idx}`;\n if (typeof it === 'string') {\n return (\n <div key={key} className=\"rounded-xl p-4 text-[14px] whitespace-pre-wrap\">\n {it}\n </div>\n );\n }\n if (it && typeof it === 'object') {\n if (it.type === 'action') {\n const actionKey = `${String(it.name ?? 'action')}:${idx}`;\n const status = actionStatuses.get(actionKey);\n \n return (\n <div key={key} className=\"space-y-2\">\n {/* <div className=\"rounded-xl p-4 text-[14px]\" style={{ backgroundColor: resolvedColors.cardBackground, border: `1px solid ${resolvedColors.borderColor}`, color: resolvedColors.textColor }}>\n <div className=\"mb-2 text-xs\" style={{ color: resolvedColors.mutedTextColor }}>Action</div>\n <div className=\"font-semibold\">{String(it.name ?? 'action')}</div>\n <pre className=\"mt-2 text-xs overflow-auto\" style={{ color: resolvedColors.mutedTextColor }}>{JSON.stringify(it.params ?? {}, null, 2)}</pre>\n </div> */}\n \n {/* Action execution status */}\n {(\n <div className=\"px-2 py-1 text-xs\" style={{ color: resolvedColors.mutedTextColor }}>\n {status === 'executing' ? (\n <span className=\"flex items-center gap-2\">\n <svg \n className=\"animate-spin h-3 w-3\" \n xmlns=\"http://www.w3.org/2000/svg\" \n fill=\"none\" \n viewBox=\"0 0 24 24\"\n >\n <circle \n className=\"opacity-25\" \n cx=\"12\" \n cy=\"12\" \n r=\"10\" \n stroke=\"currentColor\" \n strokeWidth=\"4\"\n />\n <path \n className=\"opacity-75\" \n fill=\"currentColor\" \n d=\"m4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z\"\n />\n </svg>\n {String(it.name ?? 'action')} is executing\n </span>\n ) : (\n <span className=\"flex items-center gap-1\">\n <span className=\"inline-block h-1.5 w-1.5 rounded-full\" style={{ backgroundColor: '#10b981' }} />\n {String(it.name ?? 'action')} has executed\n </span>\n )}\n </div>\n )}\n </div>\n );\n }\n if (it.type === 'ui-component' || it.type === 'ui') {\n const compName = String(it.name ?? it.component ?? '').trim();\n const Comp = compName ? components.get(compName) : undefined;\n if (Comp) {\n return (\n // <div key={key} className=\"rounded-xl p-3\" style={{ backgroundColor: resolvedColors.inputBackground, border: `1px solid ${resolvedColors.borderColor}` }}>\n <Comp {...(it.props || {})} />\n // </div>\n );\n }\n return (\n <div key={key} className=\"rounded-xl p-4\" style={{ backgroundColor: resolvedColors.inputBackground, border: `1px solid ${resolvedColors.borderColor}` }}>\n <div className=\"inline-flex items-center gap-2 text-xs mb-2\" style={{ color: resolvedColors.mutedTextColor }}>\n <span className=\"px-2 py-0.5 rounded\" style={{ backgroundColor: resolvedColors.accentColor, border: `1px solid ${resolvedColors.borderColor}` }}>UI</span>\n <span>{compName || 'component'}</span>\n <span className=\"ml-2 opacity-70\">(unregistered)</span>\n </div>\n <pre className=\"text-xs overflow-auto\" style={{ color: resolvedColors.mutedTextColor }}>{JSON.stringify(it.props ?? {}, null, 2)}</pre>\n </div>\n );\n }\n return (\n <div key={key} className=\"rounded-xl p-4 text-[14px]\" style={{ backgroundColor: resolvedColors.cardBackground, border: `1px solid ${resolvedColors.borderColor}` }}>\n <pre className=\"text-xs overflow-auto\" style={{ color: resolvedColors.mutedTextColor }}>{JSON.stringify(it, null, 2)}</pre>\n </div>\n );\n }\n return null;\n })}\n </div>\n );\n }\n\n // Apply theme colors with prop overrides\n const themeColorScheme = themeColors[theme];\n const resolvedColors = {\n primaryColor: primaryColor || themeColorScheme.primaryColor,\n backgroundColor: backgroundColor || themeColorScheme.backgroundColor,\n borderColor: borderColor || themeColorScheme.borderColor,\n textColor: textColor || themeColorScheme.textColor,\n accentColor: accentColor || themeColorScheme.accentColor,\n mutedTextColor: themeColorScheme.mutedTextColor,\n inputBackground: themeColorScheme.inputBackground,\n cardBackground: themeColorScheme.cardBackground,\n hoverBackground: themeColorScheme.hoverBackground,\n };\n\n // Generate dynamic styles based on props\n const containerStyles = {\n backgroundColor: resolvedColors.backgroundColor,\n color: resolvedColors.textColor,\n height\n };\n \n const chatPanelStyles = {\n width: typeof width === 'number' ? `${width}px` : width,\n maxWidth: typeof maxWidth === 'number' ? `${maxWidth}px` : maxWidth,\n };\n \n const floatingButtonStyles = {\n position: 'fixed' as const,\n bottom: typeof floatingButtonPosition.bottom === 'number' ? `${floatingButtonPosition.bottom}px` : floatingButtonPosition.bottom,\n right: floatingButtonPosition.right ? (typeof floatingButtonPosition.right === 'number' ? `${floatingButtonPosition.right}px` : floatingButtonPosition.right) : undefined,\n top: floatingButtonPosition.top ? (typeof floatingButtonPosition.top === 'number' ? `${floatingButtonPosition.top}px` : floatingButtonPosition.top) : undefined,\n left: floatingButtonPosition.left ? (typeof floatingButtonPosition.left === 'number' ? `${floatingButtonPosition.left}px` : floatingButtonPosition.left) : undefined,\n };\n\n const contentBorderRadius = typeof borderRadius === 'number' ? `${borderRadius}px` : borderRadius;\n\n return (\n <div className={`flex h-full w-full ${className}`} style={containerStyles} dir={dir}>\n\n <div className={`flex items-stretch transition-all duration-1000 justify-stretch w-full h-full ${showChat && enableContentPadding ? \"p-4\" : \"p-0\"}`}>\n <div className={`relative flex w-full h-full transition-all duration-1000 ease-out`} style={{ borderRadius: showChat && enableContentBorder ? contentBorderRadius : '0' }}>\n {showChat && enableContentBorder ? (\n <div\n className={`w-full h-full transition-all duration-600 ease-out ${\n streaming && enableBorderAnimation\n ? \"tc-animated-border p-[1.5px]\"\n : \"border p-0\"\n }`}\n style={{\n borderRadius: contentBorderRadius,\n borderColor: !streaming || !enableBorderAnimation ? resolvedColors.borderColor : 'transparent'\n }}\n >\n <div className=\"w-full h-full\" style={{ borderRadius: contentBorderRadius, backgroundColor: resolvedColors.backgroundColor }}>\n {children}\n </div>\n </div>\n ) : (\n <div className=\"w-full h-full\">{children}</div>\n )}\n </div>\n </div>\n {/* Right chat column */}\n <div\n className={`${chatContainerClassName} flex flex-col transition-all duration-300 ease-out overflow-hidden ${\n showChat || alwaysOpen\n ? (maximized && expandable\n ? \"fixed inset-0 z-50 w-full max-w-full px-6 py-6\"\n : \"px-4 py-6 opacity-100 translate-x-0\")\n : `w-0 max-w-0 px-0 py-6 opacity-0 ${dir === 'rtl' ? 'translate-x-2' : '-translate-x-2'} pointer-events-none`\n }`}\n style={{\n ...chatPanelStyles,\n height,\n backgroundColor: showChat || alwaysOpen ? resolvedColors.backgroundColor : 'transparent'\n }}\n >\n {/* Header */}\n <div className=\"mb-6 flex items-center justify-between\">\n <div className=\"min-w-0\">\n <h1\n title={title}\n className=\"truncate text-[18px] font-semibold\"\n style={{ color: resolvedColors.textColor }}\n >\n {title}\n </h1>\n \n </div>\n <div className=\"flex items-center gap-2 relative\" style={{ color: resolvedColors.mutedTextColor }}>\n {/* Expand / Pop-out */}\n {expandable && (\n <button\n aria-label=\"Pop out\"\n className=\"rounded-lg p-2 transition-all duration-200 ease-out\"\n style={{ \n backgroundColor: 'transparent',\n color: resolvedColors.mutedTextColor\n }}\n onMouseEnter={(e) => {\n e.currentTarget.style.backgroundColor = resolvedColors.hoverBackground;\n e.currentTarget.style.color = resolvedColors.textColor;\n }}\n onMouseLeave={(e) => {\n e.currentTarget.style.backgroundColor = 'transparent';\n e.currentTarget.style.color = resolvedColors.mutedTextColor;\n }}\n onClick={() => { setShowChat(true); setMaximized(m => !m); }}\n >\n <IconArrowsMaximize size={20} stroke={2} />\n </button>\n )}\n {/* New */}\n <button\n aria-label=\"New\"\n className=\"rounded-lg p-2 transition-all duration-200 ease-out\"\n style={{ \n backgroundColor: 'transparent',\n color: resolvedColors.mutedTextColor\n }}\n onMouseEnter={(e) => {\n e.currentTarget.style.backgroundColor = resolvedColors.hoverBackground;\n e.currentTarget.style.color = resolvedColors.textColor;\n }}\n onMouseLeave={(e) => {\n e.currentTarget.style.backgroundColor = 'transparent';\n e.currentTarget.style.color = resolvedColors.mutedTextColor;\n }}\n onClick={() => {\n if (streaming) return; // don't interrupt streaming\n setMessages([]);\n setError(null);\n setCurrentChatId(null);\n hasChatRecordRef.current = false;\n pendingFirstTitleRef.current = null;\n }}\n >\n <IconPlus size={20} stroke={2} />\n </button>\n {/* History */}\n <button\n aria-label=\"History\"\n className=\"rounded-lg p-2 transition-all duration-200 ease-out\"\n style={{ \n backgroundColor: 'transparent',\n color: resolvedColors.mutedTextColor\n }}\n onMouseEnter={(e) => {\n e.currentTarget.style.backgroundColor = resolvedColors.hoverBackground;\n e.currentTarget.style.color = resolvedColors.textColor;\n }}\n onMouseLeave={(e) => {\n e.currentTarget.style.backgroundColor = 'transparent';\n e.currentTarget.style.color = resolvedColors.mutedTextColor;\n }}\n onClick={() => setHistoryOpen(o => !o)}\n ref={historyBtnRef}\n >\n <IconHistory size={20} stroke={2} />\n </button>\n {historyOpen && createPortal((\n <>\n {/* Backdrop with blur */}\n <div\n className=\"fixed inset-0 z-[900] bg-black/40 backdrop-blur-sm\"\n onClick={() => setHistoryOpen(false)}\n />\n {/* Command palette panel */}\n <div\n ref={historyPopupRef}\n className=\"fixed left-1/2 top-16 -translate-x-1/2 z-[1000] w-[680px] max-w-[94vw] overflow-hidden rounded-2xl border border-[#2A2C33] bg-[#0F1116]/95 shadow-2xl ring-1 ring-black/10\"\n >\n <div className=\"flex items-center gap-3 border-b border-[#2A2C33] px-4 py-3\">\n <div className=\"flex-1\">\n <input\n autoFocus\n value={historySearch}\n onChange={(e) => setHistorySearch(e.target.value)}\n placeholder=\"Search\"\n className=\"w-full rounded-lg bg-[#0B0B0F] px-3 py-2 text-sm text-[#EDEEF0] placeholder:text-[#9AA0A6] outline-none border border-[#2A2C33] focus:border-[#3a3d46]\"\n />\n </div>\n </div>\n <div className=\"max-h-[60vh] overflow-y-auto\">\n {(() => {\n const q = historySearch.toLowerCase().trim();\n let list = loadChatsIndex();\n if (q) list = list.filter(m => (m.title || '').toLowerCase().includes(q));\n if (!list || list.length === 0) return (\n <div className=\"p-6 text-[#9AA0A6]\">No chats found.</div>\n );\n return (\n <ul className=\"divide-y divide-[#2A2C33]\">\n {list.map(meta => (\n <li key={meta.id}>\n <div className={`flex w-full items-center justify-between gap-3 p-3 ${meta.id === currentChatId ? 'bg-[#121318]' : ''}`}>\n <button\n className=\"flex-1 text-left transition-colors hover:bg-[#17181C] rounded-lg px-2 py-2\"\n onClick={() => {\n const data = loadChat(meta.id);\n if (data) {\n setCurrentChatId(meta.id);\n hasChatRecordRef.current = true;\n setMessages(data.messages || []);\n try { localStorage.setItem(currentChatKey, meta.id); } catch {}\n setHistoryOpen(false);\n setShowChat(true);\n }\n }}\n >\n <div className=\"flex items-center justify-between gap-3\">\n <div className=\"min-w-0\">\n <div className=\"truncate text-[14px] text-[#EDEEF0]\">{meta.title || 'Untitled chat'}</div>\n </div>\n <div className=\"shrink-0 text-[12px] text-[#9AA0A6]\">{timeAgo(meta.updatedAt)}</div>\n </div>\n </button>\n <button\n className=\"shrink-0 rounded-md p-2 text-[#9AA0A6] hover:text-red-300 hover:bg-red-500/10 border border-transparent hover:border-red-500/30\"\n title=\"Delete chat\"\n onClick={(e) => {\n e.stopPropagation();\n deleteChat(meta.id);\n setHistoryTick(t => t + 1);\n }}\n >\n <IconTrash size={16} stroke={2} />\n </button>\n </div>\n </li>\n ))}\n </ul>\n );\n })()}\n </div>\n </div>\n </>\n ), document.body)}\n {/* More / Next */}\n {!alwaysOpen && (\n <button\n aria-label=\"Close chat\"\n className=\"rounded-lg p-2 transition-all duration-200 ease-out\"\n style={{ \n backgroundColor: 'transparent',\n color: resolvedColors.mutedTextColor\n }}\n onMouseEnter={(e) => {\n e.currentTarget.style.backgroundColor = resolvedColors.hoverBackground;\n e.currentTarget.style.color = resolvedColors.textColor;\n }}\n onMouseLeave={(e) => {\n e.currentTarget.style.backgroundColor = 'transparent';\n e.currentTarget.style.color = resolvedColors.mutedTextColor;\n }}\n onClick={() => setShowChat(false)}\n >\n <IconChevronRight size={20} stroke={2} style={{ transform: dir === 'rtl' ? 'rotate(180deg)' : 'none' }} />\n </button>\n )}\n </div>\n </div>\n\n {/* Scrollable content area (conversation + status) */}\n <div\n className=\"flex-1 overflow-y-auto space-y-4 px-1 pb-4 pt-4\"\n ref={scrollContainerRef}\n onScroll={(e) => {\n const el = e.currentTarget;\n const threshold = 64; // px from bottom considered \"at bottom\"\n const distanceFromBottom = el.scrollHeight - (el.scrollTop + el.clientHeight);\n const atBottom = distanceFromBottom <= threshold;\n if (atBottom !== isAtBottom) setIsAtBottom(atBottom);\n }}\n >\n {error && (\n <div className=\"mx-2 rounded-xl bg-red-500/10 text-red-300 border border-red-500/30 p-3 text-sm\">{error}</div>\n )}\n {messages.length === 0 && !streaming && (\n <div className=\"mx-2 rounded-xl p-4\" style={{ border: `1px solid ${resolvedColors.borderColor}`, backgroundColor: resolvedColors.accentColor, color: resolvedColors.mutedTextColor }}>\n Start by sending a message to the agent.\n </div>\n )}\n <ul className=\"space-y-4\">\n {messages.map((m, i) => (\n <li key={m.id} className=\"px-1\">\n {m.role === 'user' ? (\n editingMessageId === m.id ? (\n <div className=\"max-w-[720px] rounded-2xl p-2 text-[15px] ring-2\" style={{ backgroundColor: resolvedColors.accentColor, color: resolvedColors.textColor, borderColor: resolvedColors.primaryColor }}>\n <textarea\n autoFocus\n className=\"w-full resize-none bg-transparent p-2 leading-relaxed outline-none\"\n rows={Math.max(2, Math.min(10, Math.ceil((editingMessageText || m.text).length / 60)))}\n value={editingMessageText}\n onChange={(e) => setEditingMessageText(e.target.value)}\n onKeyDown={(e) => {\n if (e.key === 'Escape') {\n setEditingMessageId(null);\n } else if (e.key === 'Enter' && !e.shiftKey) {\n e.preventDefault();\n if (!streaming) submitEdit_impl(m.id, editingMessageText || m.text);\n }\n }}\n />\n <div className=\"flex items-center justify-end gap-2 px-2 pb-2\">\n <button\n className=\"rounded-lg px-3 py-1 text-sm transition-colors\"\n style={{ border: `1px solid ${resolvedColors.borderColor}`, color: resolvedColors.mutedTextColor, backgroundColor: 'transparent' }}\n onMouseEnter={(e) => e.currentTarget.style.backgroundColor = resolvedColors.inputBackground}\n onMouseLeave={(e) => e.currentTarget.style.backgroundColor = 'transparent'}\n onClick={() => setEditingMessageId(null)}\n >\n Cancel\n </button>\n <button\n className=\"rounded-lg px-3 py-1 text-sm transition-colors\"\n style={{ border: `1px solid ${resolvedColors.borderColor}`, backgroundColor: resolvedColors.cardBackground, color: resolvedColors.textColor }}\n onMouseEnter={(e) => e.currentTarget.style.borderColor = resolvedColors.primaryColor}\n onMouseLeave={(e) => e.currentTarget.style.borderColor = resolvedColors.borderColor}\n onClick={() => { if (!streaming) submitEdit_impl(m.id, editingMessageText || m.text); }}\n >\n Save\n </button>\n </div>\n </div>\n ) : (\n <div\n title=\"Click to edit\"\n onClick={() => {\n if (streaming) return;\n setEditingMessageId(m.id);\n setEditingMessageText(m.text);\n }}\n className=\"max-w-[720px] rounded-2xl p-4 text-[15px] leading-relaxed whitespace-pre-wrap cursor-pointer transition\"\n style={{ backgroundColor: resolvedColors.accentColor, color: resolvedColors.textColor }}\n onMouseEnter={(e) => e.currentTarget.style.backgroundColor = resolvedColors.hoverBackground}\n onMouseLeave={(e) => e.currentTarget.style.backgroundColor = resolvedColors.accentColor}\n >\n {m.text}\n </div>\n )\n ) : (\n <div className=\"space-y-3\">\n {m.reasoning && (\n <div className=\"rounded-xl p-3 cursor-pointer\" style={{ backgroundColor: resolvedColors.inputBackground, border: `1px solid ${resolvedColors.borderColor}` }} onClick={() => {\n suppressNextScrollRef.current = true;\n setMessages(prev => prev.map(x => x.id === m.id && x.role === 'assistant' ? { ...x, reasoningOpen: !x.reasoningOpen } : x));\n }}>\n <div className=\"flex items-center justify-between mb-1\">\n <div className=\"text-xs\" style={{ color: resolvedColors.mutedTextColor }}>Reasoning</div>\n <button\n type=\"button\"\n className=\"text-xs transition-colors\"\n style={{ color: resolvedColors.mutedTextColor }}\n onMouseEnter={(e) => e.currentTarget.style.color = resolvedColors.textColor}\n onMouseLeave={(e) => e.currentTarget.style.color = resolvedColors.mutedTextColor}\n \n >\n {m.reasoningOpen ? 'Hide' : 'Show full'}\n </button>\n </div>\n {m.reasoningOpen ? (\n <pre className=\"text-xs whitespace-pre-wrap break-words\" style={{ color: resolvedColors.mutedTextColor }}>{m.reasoning}</pre>\n ) : (\n (() => {\n const lines = (m.reasoning || '').trim().split('\\n').filter(line => line.trim());\n const finalLine = lines.length > 0 ? lines[lines.length - 1] : '';\n return (\n <pre className=\"text-xs whitespace-pre-wrap break-words\" style={{ color: resolvedColors.mutedTextColor }}>\n {finalLine || '…'}\n </pre>\n );\n })()\n )}\n </div>\n )}\n {renderAssistantItems(m.items)}\n {streaming && i === messages.length - 1 && (\n <div className=\"flex items-center gap-2 text-xs\" style={{ color: resolvedColors.mutedTextColor }}>\n <span className=\"inline-block h-2 w-2 rounded-full animate-pulse\" style={{ backgroundColor: resolvedColors.mutedTextColor }} />\n <span>Working…</span>\n </div>\n )}\n </div>\n )}\n </li>\n ))}\n </ul>\n <div ref={scrollAnchorRef} />\n </div>\n\n {/* Composer */}\n <div className=\"sticky bottom-0 mt-auto space-y-2 pb-2 pt-1\" style={{ backgroundColor: resolvedColors.backgroundColor }}>\n {/* Unified input container */}\n <div className=\"relative flex-1\">\n {/* The box */}\n <div className=\"relative w-full rounded-2xl pb-12 pt-4\" style={{ border: `1px solid ${resolvedColors.borderColor}`, backgroundColor: resolvedColors.accentColor }}>\n \n\n {/* Text area */}\n <div className=\"px-4\">\n <textarea\n aria-label=\"Prompt\"\n rows={2}\n className=\"h-auto w-full resize-none bg-transparent text-[15px] leading-relaxed focus:outline-none hsafa-chat-textarea\"\n style={{ color: resolvedColors.textColor }}\n placeholder={placeholder}\n value={value}\n onChange={(e) => setValue(e.target.value)}\n onKeyDown={(e) => {\n if (e.key === 'Enter' && !e.shiftKey) {\n e.preventDefault();\n if (!streaming) handleSend();\n }\n }}\n ref={textareaRef}\n />\n </div>\n\n {/* Bottom-left actions inside the box */}\n <div className=\"absolute bottom-2 left-2 flex items-center gap-1\" style={{ color: resolvedColors.mutedTextColor }}>\n <button\n className=\"rounded-lg p-2 transition-colors\"\n style={{ backgroundColor: 'transparent' }}\n onMouseEnter={(e) => {\n e.currentTarget.style.backgroundColor = `${resolvedColors.backgroundColor}99`;\n e.currentTarget.style.color = resolvedColors.textColor;\n }}\n onMouseLeave={(e) => {\n e.currentTarget.style.backgroundColor = 'transparent';\n e.currentTarget.style.color = resolvedColors.mutedTextColor;\n }}\n aria-label=\"Attach files\"\n >\n <IconPaperclip size={18} stroke={2} />\n </button>\n <button\n className=\"rounded-lg p-2 transition-colors\"\n style={{ backgroundColor: 'transparent' }}\n onMouseEnter={(e) => {\n e.currentTarget.style.backgroundColor = `${resolvedColors.backgroundColor}99`;\n e.currentTarget.style.color = resolvedColors.textColor;\n }}\n onMouseLeave={(e) => {\n e.currentTarget.style.backgroundColor = 'transparent';\n e.currentTarget.style.color = resolvedColors.mutedTextColor;\n }}\n aria-label=\"Insert link\"\n >\n <IconLink size={18} stroke={2} />\n </button>\n </div>\n\n {/* Bottom-right send button */}\n <div className=\"absolute bottom-2 right-2\">\n <button\n aria-label={streaming ? \"Stop\" : \"Send\"}\n disabled={!streaming && !value.trim()}\n className=\"rounded-xl p-3 transition-all duration-200 ease-out\"\n style={{\n border: `1px solid ${streaming ? '#ef4444' : resolvedColors.borderColor}`,\n backgroundColor: streaming ? '#ef444420' : resolvedColors.cardBackground,\n color: streaming ? '#ef4444' : resolvedColors.mutedTextColor,\n opacity: (!streaming && !value.trim()) ? 0.4 : 1\n }}\n onMouseEnter={(e) => {\n if (!e.currentTarget.disabled) {\n if (streaming) {\n e.currentTarget.style.borderColor = '#dc2626';\n e.currentTarget.style.backgroundColor = '#dc262630';\n e.currentTarget.style.color = '#dc2626';\n } else {\n e.currentTarget.style.borderColor = resolvedColors.primaryColor;\n e.currentTarget.style.backgroundColor = resolvedColors.hoverBackground;\n e.currentTarget.style.color = resolvedColors.textColor;\n }\n }\n }}\n onMouseLeave={(e) => {\n if (!e.currentTarget.disabled) {\n if (streaming) {\n e.currentTarget.style.borderColor = '#ef4444';\n e.currentTarget.style.backgroundColor = '#ef444420';\n e.currentTarget.style.color = '#ef4444';\n } else {\n e.currentTarget.style.borderColor = resolvedColors.borderColor;\n e.currentTarget.style.backgroundColor = resolvedColors.cardBackground;\n e.currentTarget.style.color = resolvedColors.mutedTextColor;\n }\n }\n }}\n onClick={() => {\n if (streaming) {\n handleStop();\n } else {\n handleSend();\n }\n }}\n >\n {streaming ? (\n <IconPlayerStop size={18} stroke={2} />\n ) : (\n <IconArrowUp size={18} stroke={2} />\n )}\n </button>\n </div>\n </div>\n </div>\n </div>\n </div>\n {/* Floating reopen button when chat is closed */}\n {!showChat && !alwaysOpen && (\n <button\n aria-label=\"Open chat\"\n onClick={() => setShowChat(true)}\n className=\"rounded-full border p-3 shadow-md transition-colors\"\n style={{\n ...floatingButtonStyles,\n borderColor: resolvedColors.borderColor,\n backgroundColor: resolvedColors.accentColor,\n color: resolvedColors.textColor,\n borderRadius: '50%'\n }}\n onMouseEnter={(e) => {\n e.currentTarget.style.borderColor = resolvedColors.primaryColor;\n e.currentTarget.style.backgroundColor = `${resolvedColors.accentColor}dd`;\n }}\n onMouseLeave={(e) => {\n e.currentTarget.style.borderColor = resolvedColors.borderColor;\n e.currentTarget.style.backgroundColor = resolvedColors.accentColor;\n }}\n >\n <IconMessage size={20} stroke={2} />\n </button>\n )}\n {/* Animated border styles (scoped by unique class prefix) */}\n <style>\n {`\n @keyframes tc-border-flow {\n 0% { background-position: 0% 50%; }\n 50% { background-position: 100% 50%; }\n 100% { background-position: 0% 50%; }\n }\n\n .tc-animated-border {\n position: relative;\n /* Animated shimmer border using primary color */\n background: linear-gradient(120deg,\n ${resolvedColors.primaryColor}dd 0%,\n ${resolvedColors.primaryColor}88 25%,\n ${resolvedColors.primaryColor}00 50%,\n ${resolvedColors.primaryColor}88 75%,\n ${resolvedColors.primaryColor}dd 100%\n );\n background-size: 300% 300%;\n animation: tc-border-flow 3s ease-in-out infinite;\n filter: drop-shadow(0 0 10px ${resolvedColors.primaryColor}40);\n }\n \n .hsafa-chat-textarea::placeholder {\n color: ${resolvedColors.mutedTextColor};\n }\n `}\n </style>\n </div>\n );\n}\n"]}