@m6d/cortex-react 1.5.0 → 1.7.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.
- package/dist/index.d.ts +18 -0
- package/dist/index.js +2 -2
- package/dist/styles.css +120 -4
- package/package.json +2 -2
- package/src/chat-session.tsx +2 -1
- package/src/components/ChatComposer.tsx +37 -33
- package/src/components/ChatLanding.tsx +76 -0
- package/src/components/CortexChatWidget.tsx +47 -26
- package/src/components/ThreadList.tsx +28 -2
- package/src/components/ToolAnimation.tsx +8 -5
- package/src/context.ts +2 -0
package/dist/index.d.ts
CHANGED
|
@@ -20,6 +20,8 @@ export type CortexTransport = {
|
|
|
20
20
|
baseUrl: string | (() => string);
|
|
21
21
|
getHeaders: () => CortexHeaders | Promise<CortexHeaders>;
|
|
22
22
|
};
|
|
23
|
+
/** One value for every locale, or a map keyed by locale ('en', 'ar', …). */
|
|
24
|
+
export type Localized<T> = T | Partial<Record<string, T>>;
|
|
23
25
|
export type CortexViewMode = "helper" | "full";
|
|
24
26
|
export type CortexTheme = "light" | "dark" | "system";
|
|
25
27
|
export type CortexToolCallContext = {
|
|
@@ -55,7 +57,23 @@ export type CortexConfig = {
|
|
|
55
57
|
viewMode?: CortexViewMode;
|
|
56
58
|
/** Color scheme; `'system'` follows the OS preference. Defaults to `'light'`. */
|
|
57
59
|
theme?: CortexTheme;
|
|
60
|
+
/**
|
|
61
|
+
* Chat header title while no thread is selected; defaults to a localized
|
|
62
|
+
* "New Chat". Like the other copy props, either one value for every locale
|
|
63
|
+
* or a map keyed by locale (`{ en: 'Support', ar: 'الدعم' }`).
|
|
64
|
+
*/
|
|
65
|
+
agentName?: Localized<string>;
|
|
66
|
+
/** Headline of the blank-chat landing; defaults to a localized greeting. */
|
|
67
|
+
greeting?: Localized<string>;
|
|
68
|
+
/** Prompt chips on the blank-chat landing; clicking one sends it as the first message. */
|
|
69
|
+
suggestions?: Localized<string[]>;
|
|
58
70
|
showDebugButton?: boolean;
|
|
71
|
+
/**
|
|
72
|
+
* Embedder override for the file-upload controls (attach button, drop,
|
|
73
|
+
* paste). The widget already hides them when the server's capability
|
|
74
|
+
* handshake says the agent refuses uploads; `false` hides them regardless.
|
|
75
|
+
*/
|
|
76
|
+
attachments?: boolean;
|
|
59
77
|
/**
|
|
60
78
|
* Render embedded tool pages served from this page's own origin with their
|
|
61
79
|
* full identity — which, same-origin, means no effective sandbox at all: such
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{useCallback as
|
|
2
|
-
`)}]:[]}):[],L=_;if(N){let Z=Object.fromEntries(Object.entries(N).filter(([J])=>!Object.hasOwn(c1,J)));L=Object.keys(Z).length>0?Z:null}return{codeSnippets:k,remainingInput:L,remainingInputText:L?JSON.stringify(L,null,2):""}}var I1=10,h0={"awaiting-input":"starting","input-streaming":"starting","input-complete":"processing","approval-requested":"processing","approval-responded":"processing",complete:"complete",error:"error"};function r0(_){let N=0;for(let k=0;k<_.length;k++)N=N*31+_.charCodeAt(k)|0;return Math.abs(N)%I1}function a_(_){let N=h0[_.state]??"processing",k=_.name==="readAttachment"?"attachment":"tool",L=k==="tool"?`_${r0(_.id)}`:"";return{state:N,active:N==="starting"||N==="processing",titleKey:N==="error"?"translate_tool_error":`translate_${k}_${N==="complete"?"done":"status"}${L}`}}function Z_(_){return Array.from({length:I1},(N,k)=>`translate_${_}_${k}`)}var C1=["queryGraph","executeCode"];function t_(_,N,k){if(_.type==="thinking")return!(k&&N);if(_.type!=="tool-call")return!1;return C1.includes(_.name)&&G_(_.state)}import{EventType as x0}from"@tanstack/ai";import{fetchServerSentEvents as f1}from"@tanstack/ai-client";var s_=["image/png","image/jpeg","image/webp","application/pdf"];var S1=5;function n1(_,N){if(!s_.some((k)=>k===_))return"type";if(N>10485760)return"size";return"ok"}var g1="clientToolAnswers";function e_(_){return{id:_.id,role:_.role,parts:_.parts}}function T1(_){for(let N=_.length-1;N>=0;N-=1){let k=_[N],L="parts"in k&&k.parts.some((Z)=>Z.type==="tool-result");if(k.role==="user"||L)return _.slice(N,N+1)}return _.slice(-1)}function i0(_){let[N]=_;if(!N||N.role!=="assistant"||!("parts"in N))return null;if(!N.parts.some((L)=>L.type==="tool-result"))return null;let k=N.parts.flatMap((L)=>L.type==="tool-call"&&G_(L.state)?[{toolCallId:L.id,output:L.output??null,state:L.state==="error"?"error":"complete"}]:[]);return k.length>0?k:null}function R_(_){return new Map(_.flatMap((N)=>N.metadata?[[N.id,N.metadata]]:[]))}function _1(_){let{api:N,thread:k}=_,L=async()=>({headers:await N.resolveHeaders()}),Z=f1(()=>N.resolveUrl("/chat"),L),J=function($,K,Q,M){let q=T1($),y=i0(q);return y?Z.connect([],{...K,[g1]:y},Q,M):Z.connect(q,K,Q,M)},X=f1(()=>N.resolveUrl(`/chat/${k.id}/stream`),L),G=[];return{connect:J,async*joinRun($,K){yield{type:x0.MESSAGES_SNAPSHOT,timestamp:Date.now(),messages:G},yield*X.joinRun($,K)},hydrate:async()=>{let $=await d0(_);return G=$.messages,$}}}async function d0(_){let{api:N,thread:k,mode:L}=_,Z=k.isRunning?{runId:k.id}:null;if(L==="skip")return{messages:[],activeRun:Z,interrupts:null};if(L==="load")_.setLoadingMessages?.(!0);try{let J=await N.listMessages(k.id),X=J.map(e_);return _.onHydrated?.(J,X),{messages:X,activeRun:Z,interrupts:null}}finally{_.setLoadingMessages?.(!1)}}async function N1(_){try{let N=await _.api.listMessages(_.threadId);if(_.isStale?.())return;if(_.absorbMetadata(R_(N)),_.isStreaming())return;_.setMessages(N.map(e_))}catch{}}function k1(_){let{api:N}=_,k=new Set,L=new Set,Z=[],J=[];function X(){return Z}function G(F){return k.add(F),()=>{k.delete(F)}}function $(F){Z=F;for(let V of k)V()}function K(F,V){$(Z.map((Y)=>Y.localId===F?{...Y,...V}:Y))}function Q(F){if(L.delete(F))return;K(F,{status:"error"})}function M(F){let V=[];for(let Y of F){let I=n1(Y.type,Y.size)!=="ok"||Z.filter((O)=>O.status!=="error").length>=S1,n=crypto.randomUUID();if($([...Z,{localId:n,filename:Y.name,status:I?"error":"uploading"}]),!I)V.push({localId:n,file:Y})}if(!V.length)return;_.ensureThread().then((Y)=>{for(let{localId:I,file:n}of V){if(L.delete(I))continue;K(I,{threadId:Y}),N.uploadAttachment(Y,n).then((O)=>{if(L.delete(I)){N.deleteAttachment(O.id).catch(()=>{});return}K(I,{status:"ready",attachmentId:O.id,summary:O})},()=>Q(I))}},()=>{for(let{localId:Y}of V)Q(Y)})}function q(F){let V=Z.find((Y)=>Y.localId===F);if(!V)return;if(V.status==="uploading"){L.add(F),$(Z.filter((Y)=>Y.localId!==F));return}if(V.attachmentId){K(F,{status:"deleting"}),N.deleteAttachment(V.attachmentId).then(()=>$(Z.filter((Y)=>Y.localId!==F)),()=>K(F,{status:"error"}));return}$(Z.filter((Y)=>Y.localId!==F))}function y(F){let V=[];for(let Y of Z){if(Y.threadId!==void 0&&Y.threadId!==F){V.push(Y);continue}if(Y.status==="uploading")L.add(Y.localId);else if(Y.status==="ready"&&Y.threadId===F&&Y.attachmentId)N.deleteAttachment(Y.attachmentId).catch(()=>{})}$(V)}function U(){let F=Z.flatMap((V)=>V.status==="ready"&&V.summary?[{...V,status:"ready",summary:V.summary}]:[]);return $(Z.filter((V)=>V.status!=="ready")),J=F,F}function H(F){let V=J;if(J=[],V.some((Y)=>Y.threadId!==F))return;$([...V.map((Y)=>({...Y,status:"error"})),...Z])}function S(){J=[]}return{getState:X,subscribe:G,accept:M,remove:q,clear:y,consumeReady:U,restoreConsumed:H,discardConsumed:S}}function L1(_){return{uploading:_.some((N)=>N.status==="uploading"),busy:_.some((N)=>N.status==="uploading"||N.status==="deleting"),hasReady:_.some((N)=>N.status==="ready")}}var a0=["completed","cancelled","failed"];function p1(_,N,k){if(N!==k)return null;if(typeof _!=="object"||_===null)return null;let L=_;if(L.type!=="cortex:client-tool")return null;let Z=a0.find((X)=>X===L.status);if(!Z)return null;let J=L.reference;return{type:"cortex:client-tool",status:Z,...typeof J==="string"?{reference:J}:{},...L.result!==void 0?{result:L.result}:{}}}function Z1(_,N,k){try{return new URL(_).origin===N&&!k?"allow-scripts allow-forms allow-popups":"allow-scripts allow-forms allow-popups allow-same-origin"}catch{return"allow-scripts allow-forms allow-popups"}}function J1(_,N,k){try{return k===!0&&new URL(_).origin===N}catch{return!1}}function $1(_,N){try{return _.contentWindow?.location.origin===N}catch{return!1}}function X1(_){let N=!1,k=!1,L,Z;function J($){if(!N)_.onState($)}function X(){if(N)return;k=!1,J({phase:"error"})}function G($){if(N||k)return;k=!0,J({phase:"settling"});try{let K=_.submit($);if(K instanceof Promise)K.catch(X)}catch{X()}}return{async start(){J({phase:"initiating"});try{let $=await _.initiate();if(!$.embed){J({phase:"unavailable"});return}if(!/^https?:$/.test(new URL($.embedUrl).protocol)){J({phase:"error"});return}L=$.embedOrigin,J({phase:"embedded",embedUrl:$.embedUrl,surface:$.surface,embedOrigin:$.embedOrigin})}catch($){let K=$ instanceof Error?$.message:"";J({phase:/HTTP 404/.test(K)?"unavailable":"error"})}},setSource($){if($!==null&&$!==void 0)Z=$},handleMessage($){if(!L)return;if(Z===void 0||$.source!==Z)return;let K=p1($.data,$.origin,L);if(!K)return;G({status:K.status,reference:K.reference,result:K.result})},cancel(){G({status:"cancelled"})},terminate(){if(N||k)return;L=void 0,Z=void 0,J({phase:"error"})},dispose(){N=!0}}}function t0(_){return Math.min(1000*2**(_-1),30000)}var s0=1e4;function G1(_){let N,k,L=0,Z=!1;function J(){let G=typeof _.wsUrl==="function"?_.wsUrl():_.wsUrl;if(G===!1)return;let $=e0(G,_.transport.baseUrl);U_(_.transport).then((K)=>{if(Z)return;N=new WebSocket(Z2($,K)),N.addEventListener("open",()=>{let Q=N;setTimeout(()=>{if(N===Q&&!Z)L=0},s0),_.onOpen?.()}),N.addEventListener("message",(Q)=>{let M=Q.data;if(typeof M!=="string")return;let q;try{q=JSON.parse(M)}catch{return}_.onEvent(q)}),N.addEventListener("close",X)}).catch(X)}function X(){if(Z||k)return;L+=1,k=setTimeout(()=>{k=void 0,J()},t0(L))}return J(),{close(){Z=!0,clearTimeout(k),N?.close()}}}function e0(_,N){let k=_??_2(N);if(!_)return k;let L=N2(N);if(!L)return k;return k2(k,L)}function _2(_){let N=typeof _==="string"?_:_(),k=new URL(N,window.location.origin);return k.protocol=k.protocol==="https:"?"wss:":"ws:",k.pathname=k.pathname.replace(/\/$/,"")+"/ws",k.toString()}function N2(_){let N=typeof _==="string"?_:_(),L=new URL(N,window.location.origin).pathname.split("/").filter(Boolean),Z=L.lastIndexOf("agents");if(Z===-1)return;return L[Z+1]}function k2(_,N){let k=new URL(_,window.location.origin);if(k.searchParams.has("agentId")||L2(k))return k.toString();return k.searchParams.set("agentId",N),k.toString()}function L2(_){let N=_.pathname.split("/").filter(Boolean),k=N.lastIndexOf("agents");return k!==-1&&Boolean(N[k+1])}function Z2(_,N){let k=N.Authorization??N.authorization;if(!k?.startsWith("Bearer "))return _;let L=new URL(_,window.location.origin);if(L.searchParams.has("token"))return L.toString();return L.searchParams.set("token",k.slice(7)),L.toString()}function c_(_){return[..._].sort((N,k)=>{let L=Date.parse(k.updatedAt)-Date.parse(N.updatedAt);if(L!==0)return L;return Date.parse(k.createdAt)-Date.parse(N.createdAt)})}function B_(_,N){let k=[..._],L=k.findIndex((Z)=>Z.id===N.id);if(L===-1)k.push(N);else k[L]={...k[L],...N};return c_(k)}function I_(_,N){return _.filter((k)=>k.id!==N)}function V1(_,N){switch(N.type){case"thread:deleted":return I_(_,N.payload.threadId);case"thread:created":case"thread:title-updated":case"thread:run-started":case"thread:run-finished":case"thread:messages-updated":return B_(_,N.payload.thread);default:return _}}import{marked as J2}from"marked";import $2 from"dompurify";function K1(_){if(!_)return"";let N=J2.parse(_,{async:!1});return N=N.replace(/<table>/g,'<div style="overflow-x:auto"><table style="width:auto">').replace(/<\/table>/g,"</table></div>").replace(/<(t[hd])([\s>])/g,'<$1 style="padding:0.5rem 1rem"$2'),$2.sanitize(N)}import y_ from"highlight.js/lib/core";import X2 from"highlight.js/lib/languages/javascript";import G2 from"highlight.js/lib/languages/json";import V2 from"highlight.js/lib/languages/sql";var m1=!1;function K2(){if(m1)return;m1=!0,y_.registerLanguage("javascript",X2),y_.registerLanguage("json",G2),y_.registerLanguage("cypher",V2)}function W1(_,N){if(!_)return"";return K2(),y_.getLanguage(N)?y_.highlight(_,{language:N}).value:W2(_)}function W2(_){return _.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var u1={translate_new:"جديد",translate_threads:"المحادثات",translate_n_conversations:"{{count}} محادثات",translate_one_conversation:"محادثة واحدة",translate_no_threads_yet:"لا توجد محادثات بعد",translate_start_a_new_conversation:"ابدأ محادثة جديدة",translate_untitled:"بدون عنوان",translate_new_chat:"محادثة جديدة",translate_normal:"عادي",translate_debug:"تصحيح",translate_type_a_message:"اكتب رسالة...",translate_thinking:"جارٍ معالجة الطلب...",translate_reasoned:"تم الاستنتاج",translate_knowledge_graph_query:"استعلام الرسم البياني المعرفي",translate_javascript_code_execution:"تنفيذ كود جافاسكريبت",translate_completed:"مكتمل",translate_attach_files:"إرفاق ملفات",translate_drop_files_here:"أفلت ملفاتك هنا...",translate_remove_attachment:"إزالة المرفق",translate_attachment_rejected:"لا يمكن إرفاق هذا الملف",translate_attachment_caption:"من فضلك اطّلع على الملفات المرفقة.",translate_download:"تنزيل",translate_tool_status_0:"جارٍ جلب البيانات…",translate_tool_status_1:"جارٍ تحليل المعلومات…",translate_tool_status_2:"جارٍ معالجة الطلب…",translate_tool_status_3:"جارٍ تجميع النتائج…",translate_tool_status_4:"جارٍ تحضير الرد…",translate_tool_status_5:"جارٍ البحث…",translate_tool_status_6:"جارٍ فحص السجلات…",translate_tool_status_7:"جارٍ مراجعة التفاصيل…",translate_tool_status_8:"جارٍ إجراء الحسابات…",translate_tool_status_9:"جارٍ سحب المعلومات…",translate_tool_done_0:"تم جلب البيانات بنجاح",translate_tool_done_1:"تم التحليل بنجاح",translate_tool_done_2:"تمت معالجة الطلب بنجاح",translate_tool_done_3:"تم تجميع النتائج بنجاح",translate_tool_done_4:"تم تحضير الرد بنجاح",translate_tool_done_5:"تم البحث بنجاح",translate_tool_done_6:"تم فحص السجلات بنجاح",translate_tool_done_7:"تمت المراجعة بنجاح",translate_tool_done_8:"تمت الحسابات بنجاح",translate_tool_done_9:"تم استرجاع المعلومات بنجاح",translate_tool_error:"حدث خطأ",translate_attachment_status:"جارٍ قراءة الملف المرفق…",translate_attachment_done:"تمت قراءة الملف المرفق",translate_graph_0:"جارٍ استكشاف الروابط...",translate_graph_1:"جارٍ رسم الخريطة...",translate_graph_2:"جارٍ اكتشاف العلاقات...",translate_graph_3:"جارٍ تتبع الروابط...",translate_graph_4:"جارٍ التنقل في المعرفة...",translate_graph_5:"جارٍ كشف الرؤى...",translate_graph_6:"جارٍ ربط النقاط...",translate_graph_7:"جارٍ تتبع المسار...",translate_graph_8:"جارٍ تجميع الأجزاء...",translate_graph_9:"جارٍ بناء الصورة...",translate_code_0:"جارٍ حساب الأرقام...",translate_code_1:"جارٍ معالجة البيانات...",translate_code_2:"جارٍ تنفيذ طلبك...",translate_code_3:"جارٍ تحليل الأرقام...",translate_code_4:"جارٍ تجميع كل شيء...",translate_code_5:"جارٍ تحليل النتائج...",translate_code_6:"جارٍ العمل خلف الكواليس...",translate_code_7:"جارٍ ترتيب التفاصيل...",translate_code_8:"جارٍ تحضير إجابتك...",translate_code_9:"أوشك على الانتهاء...",translate_reasoning_0:"جارٍ التفكير...",translate_reasoning_1:"جارٍ دراسة الخيارات...",translate_reasoning_2:"جارٍ تقييم الاحتمالات...",translate_reasoning_3:"جارٍ التأمل في هذا...",translate_reasoning_4:"جارٍ إيجاد الحل...",translate_reasoning_5:"جارٍ ترتيب الأفكار...",translate_reasoning_6:"جارٍ التمعن في الأمر...",translate_reasoning_7:"جارٍ إيجاد أفضل طريقة...",translate_reasoning_8:"جارٍ تنظيم أفكاري...",translate_reasoning_9:"أوشك على الانتهاء...",translate_running:"قيد التنفيذ",translate_aborted:"تم الإلغاء",translate_input:"المدخلات",translate_output:"المخرجات",translate_calling:"جارٍ الاستدعاء",translate_input_ready:"المدخلات جاهزة",translate_needs_approval:"بحاجة إلى موافقة",translate_approved:"تمت الموافقة",translate_responded:"تم الرد",translate_error:"خطأ",translate_approval_requested:"طلب موافقة",translate_approval_response:"رد الموافقة",translate_waiting_for_approval:"في انتظار الموافقة لتنفيذ هذه الأداة.",translate_tool_approved:"تمت الموافقة.",translate_tool_response_received:"تم استلام الرد.",translate_tokens:"رمز",translate_fresh:"جديد",translate_cache_read:"قراءة من الذاكرة",translate_cache_write:"كتابة في الذاكرة",translate_n_percent_cached:"{{percent}}٪ مخزّن مؤقتًا",translate_text:"نص",translate_reasoning:"الاستنتاج",translate_read:"قراءة",translate_write:"كتابة",translate_total:"الإجمالي",translate_request:"الطلب",translate_response:"الرد",translate_step_n:"الخطوة {{number}}",translate_inspect_llm_requests:"فحص طلبات النموذج",translate_loading:"جارٍ التحميل…",translate_no_llm_requests:"لا توجد طلبات نموذج مسجّلة لهذه الرسالة.",translate_unhandled_type:"نوع غير مدعوم:",translate_client_tool_title:"أكمل هذه الخطوة للمتابعة",translate_client_tool_loading:"جارٍ تجهيز خطوة آمنة...",translate_client_tool_failed:"تعذّر تحميل هذه الخطوة",translate_client_tool_retry:"حاول مرة أخرى",translate_client_tool_cancel:"إلغاء"};var l1={translate_new:"New",translate_threads:"Threads",translate_n_conversations:"{{count}} conversations",translate_one_conversation:"1 conversation",translate_no_threads_yet:"No threads yet",translate_start_a_new_conversation:"Start a new conversation",translate_untitled:"Untitled",translate_new_chat:"New Chat",translate_normal:"Normal",translate_debug:"Debug",translate_type_a_message:"Type a message...",translate_thinking:"Thinking things through...",translate_reasoned:"Reasoned",translate_knowledge_graph_query:"Knowledge Graph Query",translate_javascript_code_execution:"JavaScript Code Execution",translate_completed:"Completed",translate_attach_files:"Attach files",translate_drop_files_here:"Drop your files here...",translate_remove_attachment:"Remove attachment",translate_attachment_rejected:"This file cannot be attached",translate_attachment_caption:"Please take a look at the attached files.",translate_download:"Download",translate_tool_status_0:"Fetching data...",translate_tool_status_1:"Analyzing information...",translate_tool_status_2:"Processing request...",translate_tool_status_3:"Gathering results...",translate_tool_status_4:"Preparing response...",translate_tool_status_5:"Looking things up...",translate_tool_status_6:"Checking records...",translate_tool_status_7:"Reviewing details...",translate_tool_status_8:"Running calculations...",translate_tool_status_9:"Pulling information...",translate_tool_done_0:"Data fetched successfully",translate_tool_done_1:"Analysis completed successfully",translate_tool_done_2:"Request processed successfully",translate_tool_done_3:"Results gathered successfully",translate_tool_done_4:"Response prepared successfully",translate_tool_done_5:"Lookup completed successfully",translate_tool_done_6:"Records checked successfully",translate_tool_done_7:"Review completed successfully",translate_tool_done_8:"Calculations completed successfully",translate_tool_done_9:"Information retrieved successfully",translate_tool_error:"Something went wrong",translate_attachment_status:"Reading the attached file...",translate_attachment_done:"Finished reading the file",translate_graph_0:"Exploring connections...",translate_graph_1:"Mapping out the links...",translate_graph_2:"Discovering relationships...",translate_graph_3:"Tracing the connections...",translate_graph_4:"Navigating the knowledge...",translate_graph_5:"Uncovering insights...",translate_graph_6:"Connecting the dots...",translate_graph_7:"Following the trail...",translate_graph_8:"Piecing things together...",translate_graph_9:"Building the picture...",translate_code_0:"Running the numbers...",translate_code_1:"Working through the data...",translate_code_2:"Processing your request...",translate_code_3:"Crunching the figures...",translate_code_4:"Putting it all together...",translate_code_5:"Analyzing the results...",translate_code_6:"Working behind the scenes...",translate_code_7:"Sorting through the details...",translate_code_8:"Preparing your answer...",translate_code_9:"Almost ready...",translate_reasoning_0:"Thinking it through...",translate_reasoning_1:"Considering the options...",translate_reasoning_2:"Weighing the possibilities...",translate_reasoning_3:"Reflecting on this...",translate_reasoning_4:"Working it out...",translate_reasoning_5:"Putting thoughts together...",translate_reasoning_6:"Mulling it over...",translate_reasoning_7:"Finding the best approach...",translate_reasoning_8:"Organizing my thoughts...",translate_reasoning_9:"Almost there...",translate_running:"Running",translate_aborted:"Aborted",translate_input:"Input",translate_output:"Output",translate_calling:"Calling",translate_input_ready:"Input ready",translate_needs_approval:"Needs approval",translate_approved:"Approved",translate_responded:"Responded",translate_error:"Error",translate_approval_requested:"Approval requested",translate_approval_response:"Approval response",translate_waiting_for_approval:"Waiting for approval to execute this tool.",translate_tool_approved:"Approved.",translate_tool_response_received:"Response received.",translate_tokens:"tokens",translate_fresh:"Fresh",translate_cache_read:"Cache read",translate_cache_write:"Cache write",translate_n_percent_cached:"{{percent}}% cached",translate_text:"Text",translate_reasoning:"Reasoning",translate_read:"Read",translate_write:"Write",translate_total:"Total",translate_request:"Request",translate_response:"Response",translate_step_n:"Step {{number}}",translate_inspect_llm_requests:"Inspect LLM requests",translate_loading:"loading…",translate_no_llm_requests:"No LLM requests recorded for this message.",translate_unhandled_type:"Unhandled type:",translate_client_tool_title:"Complete this step to continue",translate_client_tool_loading:"Preparing a secure step...",translate_client_tool_failed:"This step could not be loaded",translate_client_tool_retry:"Try again",translate_client_tool_cancel:"Cancel"};var C_={en:l1,ar:u1};function Y1(_,N,k){let Z=(C_[_]??C_.en)?.[N]??C_.en?.[N]??N;if(!k)return Z;return Z.replace(/\{\{\s*(\w+)\s*\}\}/g,(J,X)=>(X in k)?String(k[X]):J)}function V_(_){if(typeof _==="string"){let N=_.trim();if(!(N.startsWith("{")&&N.endsWith("}")||N.startsWith("[")&&N.endsWith("]")))return _;try{return V_(JSON.parse(N))}catch{return _}}if(Array.isArray(_))return _.map((N)=>V_(N));if(_!==null&&typeof _==="object"){let N={};for(let[k,L]of Object.entries(_))N[k]=V_(L);return N}return _}function Q1(_,N){if(Array.isArray(_)){let k=_;return{kind:"container",open:"[",close:"]",summary:o1(k.length,"item","items"),entries:k.map((L,Z)=>({key:null,value:L,path:`${N}[${Z}]`}))}}if(_!==null&&typeof _==="object"){let k=Object.entries(_);return{kind:"container",open:"{",close:"}",summary:o1(k.length,"property","properties"),entries:k.map(([L,Z])=>({key:L,value:Z,path:`${N}.${L}`}))}}return{kind:"primitive",text:z2(_),className:F2(_)}}function o1(_,N,k){return`${_} ${_===1?N:k}`}function z2(_){if(_===null||_===void 0)return"null";if(typeof _==="string")return JSON.stringify(_);if(typeof _==="number"||typeof _==="boolean")return String(_);return JSON.stringify(_)??"null"}function F2(_){if(_===null||_===void 0)return"jt-null";if(typeof _==="string")return"jt-string";if(typeof _==="number")return"jt-number";if(typeof _==="boolean")return"jt-boolean";return""}function S_(_){if(!_)return null;try{return JSON.parse(_)}catch{return _}}function n_(_){if(!_)return"";try{return JSON.stringify(JSON.parse(_),null,2)}catch{return _}}var z1=[["year",31536000000],["month",2592000000],["week",604800000],["day",86400000],["hour",3600000],["minute",60000],["second",1000]];function F1(_,N,k=Date.now()){let L=Date.parse(_);if(Number.isNaN(L))return"";let Z=L-k,[J,X]=z1.find(([,G])=>Math.abs(Z)>=G)??z1[z1.length-1];return new Intl.RelativeTimeFormat(N,{numeric:"auto"}).format(Math.round(Z/X),J)}function q1(_,N){let k=URL.createObjectURL(_),L=document.createElement("a");L.href=k,L.download=N,L.click(),URL.revokeObjectURL(k)}class J_{onUpdate;fullText="";displayedLength=0;animationFrameId=null;isDone=!1;static DRAIN_FRACTION=0.03;static MIN_CHARS_PER_FRAME=1;static DONE_DRAIN_FRACTION=0.1;constructor(_){this.onUpdate=_}seed(_){this.fullText=_,this.displayedLength=_.length,this.onUpdate(_)}update(_,N){if(this.fullText=_,this.isDone=N,this.displayedLength=Math.min(this.displayedLength,this.fullText.length),N&&this.displayedLength>=this.fullText.length){this.onUpdate(this.fullText),this.stopAnimation();return}if(!this.animationFrameId)this.scheduleFrame()}destroy(){this.stopAnimation()}scheduleFrame(){this.animationFrameId=requestAnimationFrame(()=>this.tick())}tick(){let _=this.fullText.length-this.displayedLength;if(_<=0){this.animationFrameId=null;return}let N=this.isDone?J_.DONE_DRAIN_FRACTION:J_.DRAIN_FRACTION,k=Math.max(J_.MIN_CHARS_PER_FRAME,Math.ceil(_*N));if(this.displayedLength=Math.min(this.fullText.length,this.displayedLength+k),this.onUpdate(this.fullText.substring(0,this.displayedLength)),this.displayedLength<this.fullText.length)this.scheduleFrame();else this.animationFrameId=null}stopAnimation(){if(this.animationFrameId)cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null}}function O_(_){if(_.input.total<=0)return null;return Math.round(_.input.cacheRead/_.input.total*100)}import{useEffect as M_,useLayoutEffect as j1,useMemo as q2,useRef as d}from"react";import{useChat as H2}from"@tanstack/ai-react";function h1(_){let{thread:N,api:k,patchUi:L}=_,Z=d(!0),J=d(!1),X=d(!1),G=d(!1),$=d(!1),K=d(new Set),Q=d(Promise.resolve()),M=q2(()=>_1({api:k,thread:{id:N.id,isRunning:N.isRunning},mode:_.mode,onHydrated:(D)=>{if(!Z.current)return;L({messageMetadata:R_(D)})},setLoadingMessages:(D)=>{if(Z.current)L({isLoadingMessages:D})}}),[]),q=H2({threadId:N.id,persistence:!0,initialMessages:_.initialMessages,connection:M,onChunk:()=>{if(!Z.current)return;X.current=!0},onError:()=>{if(!Z.current)return;if(X.current)_.onTurnFinished();else _.onSendFailed()}}),y=d(q);y.current=q;let U=d(q.isLoading);U.current=q.isLoading;async function H(D,b){let f=b({toolCallId:D.id,toolName:D.name,input:D.input},{threadId:N.id});if(f===null||f===void 0)return;let u=await Promise.resolve(f);if(u===null||u===void 0)return;if(!Z.current)return;await y.current.addToolResult({toolCallId:D.id,tool:D.name,output:u})}function S(){let D=v_(y.current.messages),b=_.configRef.current.hooks?.onToolCall;if(!b)return D.length>0;for(let f of D){if(f.state!=="input-complete")continue;if(K.current.has(f.id))continue;K.current.add(f.id),H(f,b)}return D.length>0}async function F(D){if(!Z.current||D!==N.id)return;await N1({api:k,threadId:D,isStale:()=>!Z.current,isStreaming:()=>U.current,absorbMetadata:(b)=>L({messageMetadata:b}),setMessages:(b)=>{y.current.setMessages(b)}})}function V(D){return Q.current=Q.current.then(()=>F(D)),Q.current}async function Y(){if(G.current){G.current=!1;return}if(J.current&&S())return;await V(N.id)}async function I(D,b){_.setRunning(N.id,!0),J.current=!0,X.current=!1;let f={id:crypto.randomUUID(),role:"user",parts:[{type:"text",content:D}]};if(b.length)L((u)=>({messageMetadata:new Map(u.messageMetadata).set(f.id,{attachments:b})}));await y.current.append(f)}async function n(){if(!U.current)return;let{aborted:D}=await k.abortStream(N.id).catch(()=>({aborted:!1}));if(!Z.current)return;if(D)G.current=!0,_.setRunning(N.id,!1);y.current.stop()}function O(D,b,f){return y.current.addToolResult({toolCallId:D,tool:b,output:f}).catch((u)=>{throw V(N.id),u})}function i(D){if(U.current)return;if(D.isRunning){_.remount(D);return}V(D.id)}M_(()=>{return Z.current=!0,()=>{Z.current=!1}},[]);let L_=d(void 0);return L_.current={threadId:N.id,send:I,abort:n,addToolResult:O,reattach:i,refreshMessages:(D)=>{V(D)}},j1(()=>{_.sessionRef.current=L_.current}),j1(()=>{return()=>{if(_.sessionRef.current===L_.current)_.sessionRef.current=void 0}},[]),M_(()=>{if(!_.pendingSendRef.current.length)return;let D=setTimeout(()=>{let b=_.pendingSendRef.current;_.pendingSendRef.current=[],(async()=>{for(let{prompt:f,attachments:u}of b)await I(f,u)})()});return()=>clearTimeout(D)},[]),M_(()=>{L({messages:q.messages})},[q.messages]),M_(()=>{L({hasPendingToolCalls:!q.isLoading&&v_(q.messages).length>0})},[q.messages,q.isLoading]),M_(()=>{if(L({isAgentWorking:q.isLoading}),q.isLoading){$.current=!0;return}if(!$.current)return;$.current=!1,_.onTurnFinished(),Y()},[q.isLoading]),null}import{createContext as D2,useContext as B2}from"react";var H1=D2(void 0);function B(){let _=B2(H1);if(!_)throw Error("useCortex must be used inside <CortexChatWidget>");return _}function z(..._){return _.filter(Boolean).join(" ")}import{forwardRef as y2,useEffect as O2,useImperativeHandle as M2,useRef as B1,useState as x1}from"react";import{jsx as t,jsxs as D1}from"react/jsx-runtime";function r1(){let{queue:_,t:N}=B();if(!_.items.length)return null;return t("div",{className:"cortex-attachment-queue",children:_.items.map((k)=>D1("div",{className:z("cortex-attachment-chip",k.status==="error"&&"cortex-attachment-chip--error"),title:k.status==="error"?N("translate_attachment_rejected"):"",children:[k.status==="uploading"||k.status==="deleting"?D1("svg",{className:"cortex-attachment-chip__spinner",viewBox:"0 0 16 16",fill:"none",children:[t("circle",{cx:"8",cy:"8",r:"6",stroke:"currentColor",strokeWidth:"2",className:"cortex-attachment-chip__spinner-track"}),t("path",{d:"M14 8a6 6 0 0 0-6-6",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]}):D1("svg",{viewBox:"0 0 16 16",className:"cortex-attachment-chip__icon",fill:"none",children:[t("path",{d:"M4 1.5h5.172a2 2 0 0 1 1.414.586l2.328 2.328a2 2 0 0 1 .586 1.414V12.5a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-9a2 2 0 0 1 2-2Z",stroke:"currentColor",strokeWidth:"1.25"}),t("path",{d:"M9.5 1.5v2a2 2 0 0 0 2 2h2",stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round"})]}),t("span",{className:"cortex-attachment-chip__name",children:k.filename}),t("button",{type:"button",onClick:()=>_.remove(k.localId),className:"cortex-attachment-chip__remove",disabled:k.status==="deleting","aria-label":N("translate_remove_attachment"),children:t("svg",{viewBox:"0 0 16 16",fill:"none",children:t("path",{d:"M4.5 4.5l7 7m0-7l-7 7",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})})})]},k.localId))})}import{jsx as h,jsxs as g_}from"react/jsx-runtime";var E2=s_.join(","),i1=y2(function(N,k){let{t:L,queue:Z,isAgentWorking:J,send:X,abort:G}=B(),[$,K]=x1(""),[Q,M]=x1(!1),q=B1(null),y=B1(null);M2(k,()=>({focusInput:()=>q.current?.focus()}));let U=B1(J);O2(()=>{if(U.current&&!J)q.current?.focus();U.current=J},[J]);let H=!Z.busy&&(Boolean($.trim())||Z.hasReady);function S(){if(J||!H)return;let O="translate_attachment_caption",i=L(O),L_=i!==O?i:"Please take a look at the attached files.",D=$.trim()||L_,b=Z.consumeReady();K(""),X(D,b.map((f)=>f.summary))}function F(O){if(O.key==="Enter"&&!O.shiftKey)O.preventDefault(),S()}function V(O){O.preventDefault(),M(!0)}function Y(O){if(!O.currentTarget.contains(O.relatedTarget))M(!1)}function I(O){O.preventDefault(),M(!1),Z.accept([...O.dataTransfer.files])}function n(O){let i=O.clipboardData.files;if(!i.length)return;O.preventDefault(),Z.accept([...i])}return g_("div",{className:"cortex-widget__input-area",onDragOver:V,onDragLeave:Y,onDrop:I,children:[h(r1,{}),g_("div",{className:z("cortex-widget__input-box",J&&"cortex-widget__input-box--disabled",!J&&"cortex-widget__input-box--enabled",Q&&"cortex-widget__input-box--dragging"),children:[h("textarea",{ref:q,onKeyDown:F,onPaste:n,value:$,onChange:(O)=>K(O.target.value),placeholder:Q?L("translate_drop_files_here"):J?"":L("translate_type_a_message"),disabled:J,rows:1,className:z("cortex-widget__textarea",J&&"cortex-widget__textarea--disabled")}),J?g_("button",{onClick:()=>void G(),className:"cortex-stop-btn",children:[h("span",{className:"cortex-stop-btn__ring"}),h("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",className:"cortex-stop-btn__icon",children:h("rect",{x:"1",y:"1",width:"10",height:"10",rx:"2.5",fill:"currentColor"})})]}):g_("div",{className:"cortex-widget__input-actions",children:[h("button",{type:"button",onClick:()=>y.current?.click(),className:"cortex-widget__attach-btn","aria-label":L("translate_attach_files"),children:h("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:h("path",{d:"M10.5 5.5 6.2 9.8a1.4 1.4 0 0 0 2 2l4.6-4.6a2.8 2.8 0 0 0-4-4L4.2 7.8a4.2 4.2 0 0 0 6 6l4-4",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"})})}),h("input",{ref:y,type:"file",multiple:!0,accept:E2,onChange:(O)=>{Z.accept([...O.target.files??[]]),O.target.value=""},className:"cortex-widget__file-input"}),h("button",{onClick:S,className:z("cortex-widget__send-btn",!H&&"cortex-widget__send-btn--empty",H&&"cortex-widget__send-btn--ready"),disabled:!H,children:h("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",className:"cortex-widget__send-icon",children:h("path",{d:"M3 8h10M9 4l4 4-4 4",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})})]})]})]})});import{useEffect as m_,useRef as u_,useState as o2}from"react";import{jsx as f_,jsxs as d1}from"react/jsx-runtime";function a1(){let{t:_}=B();return d1("div",{className:"cortex-aborted-flag",children:[f_("span",{className:"cortex-aborted-flag__line"}),d1("span",{className:"cortex-aborted-flag__label",children:[f_("svg",{className:"cortex-aborted-flag__icon",width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:f_("path",{d:"M6 1.5v5M6 8.75v.5",stroke:"currentColor",strokeWidth:"1.4",strokeLinecap:"round"})}),_("translate_aborted")]}),f_("span",{className:"cortex-aborted-flag__line"})]})}import{jsx as K_,jsxs as t1}from"react/jsx-runtime";function s1(_){let{api:N,t:k}=B();async function L(Z){let{blob:J,name:X}=await N.downloadAttachment(Z);q1(J,X)}return K_("div",{className:"cortex-message-attachments",children:_.attachments.map((Z)=>t1("button",{type:"button",onClick:()=>void L(Z.id),className:"cortex-message-attachment","aria-label":`${k("translate_download")}: ${Z.filename}`,children:[t1("svg",{viewBox:"0 0 16 16",className:"cortex-message-attachment__icon",fill:"none",children:[K_("path",{d:"M4 1.5h5.172a2 2 0 0 1 1.414.586l2.328 2.328a2 2 0 0 1 .586 1.414V12.5a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-9a2 2 0 0 1 2-2Z",stroke:"currentColor",strokeWidth:"1.25"}),K_("path",{d:"M9.5 1.5v2a2 2 0 0 0 2 2h2",stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round"})]}),K_("span",{className:"cortex-message-attachment__name",children:Z.filename}),K_("svg",{viewBox:"0 0 16 16",className:"cortex-message-attachment__dl-icon",fill:"none",children:K_("path",{d:"M8 3v7m0 0L5.5 7.5M8 10l2.5-2.5M3 13h10",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]},Z.id))})}import{useRef as b2,useState as E_}from"react";import{useRef as A2,useState as w2}from"react";import{jsx as W_,jsxs as P2}from"react/jsx-runtime";function e({value:_,className:N}){let[k,L]=w2(!1),Z=A2(null);async function J(X){X.stopPropagation(),X.preventDefault();try{if(await navigator.clipboard.writeText(_),L(!0),Z.current)clearTimeout(Z.current);Z.current=setTimeout(()=>L(!1),1500)}catch{}}return W_("span",{className:z("cortex-copy-btn",N),children:W_("button",{className:z("cortex-copy-btn__button",k&&"cortex-copy-btn__button--copied"),onClick:(X)=>void J(X),"aria-label":k?"Copied":"Copy to clipboard",type:"button",children:k?W_("svg",{className:"cortex-copy-btn__icon cortex-copy-btn__icon--check",width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",children:W_("path",{d:"M5 13l4 4L19 7",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"})}):P2("svg",{className:"cortex-copy-btn__icon",width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",children:[W_("rect",{x:"9",y:"9",width:"12",height:"12",rx:"2",stroke:"currentColor",strokeWidth:"2"}),W_("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]})})})}import{useMemo as U2,useState as v2}from"react";import{jsx as o,jsxs as $_,Fragment as T_}from"react/jsx-runtime";function X_({data:_,expandDepth:N=1,className:k}){let L=U2(()=>V_(_),[_]),[Z,J]=v2({});function X($,K){return Z[$]??K>=N}function G($,K){J((Q)=>({...Q,[$]:!X($,K)}))}return o("div",{className:z("cortex-json-tree",k),children:o(e1,{value:L,path:"$",depth:0,isCollapsed:X,toggle:G})})}function e1({value:_,path:N,depth:k,isCollapsed:L,toggle:Z}){let J=Q1(_,N);if(J.kind==="primitive")return o("span",{className:J.className,children:J.text});if(J.entries.length===0)return $_("span",{className:"jt-bracket",children:[J.open,J.close]});let X=L(N,k);function G($){Z(N,k),$.stopPropagation()}return $_(T_,{children:[$_("span",{className:"jt-toggle",onClick:G,role:"button",children:[o("span",{className:z("jt-arrow",X&&"jt-arrow--collapsed"),children:"▾"}),o("span",{className:"jt-bracket",children:J.open})]}),X?$_(T_,{children:[o("span",{className:"jt-collapsed-hint",onClick:G,role:"button",children:J.summary}),o("span",{className:"jt-bracket",children:J.close})]}):$_(T_,{children:[o("div",{className:"jt-indent",children:J.entries.map(($,K)=>$_("div",{className:"jt-line",children:[$.key!==null&&$_(T_,{children:[o("span",{className:"jt-key",children:`"${$.key}"`}),o("span",{className:"jt-colon",children:": "})]}),o(e1,{value:$.value,path:$.path,depth:k+1,isCollapsed:L,toggle:Z}),K<J.entries.length-1&&o("span",{className:"jt-comma",children:","})]},$.path))}),o("span",{className:"jt-bracket",children:J.close})]})]})}function R(_){return _.toLocaleString("en-US")}import{jsx as Y_,jsxs as Q_}from"react/jsx-runtime";function _0({usage:_}){let{t:N}=B();return Q_("div",{className:"cortex-llm-inspector__usage-rows",children:[Q_("div",{className:"cortex-llm-inspector__usage-row",children:[Y_("span",{className:"cortex-llm-inspector__usage-lbl",children:N("translate_input")}),Y_("span",{className:"cortex-llm-inspector__usage-val",children:R(_.input.total)}),Q_("span",{className:"cortex-llm-inspector__usage-detail",children:[N("translate_fresh")," ",R(_.input.noCache)," · ",N("translate_read")," ",R(_.input.cacheRead)," · ",N("translate_write")," ",R(_.input.cacheWrite)]})]}),Q_("div",{className:"cortex-llm-inspector__usage-row",children:[Y_("span",{className:"cortex-llm-inspector__usage-lbl",children:N("translate_output")}),Y_("span",{className:"cortex-llm-inspector__usage-val",children:R(_.output.total)}),Q_("span",{className:"cortex-llm-inspector__usage-detail",children:[N("translate_text")," ",R(_.output.text)," · ",N("translate_reasoning")," ",R(_.output.reasoning)]})]}),Q_("div",{className:"cortex-llm-inspector__usage-row cortex-llm-inspector__usage-row--total",children:[Y_("span",{className:"cortex-llm-inspector__usage-lbl",children:N("translate_total")}),Y_("span",{className:"cortex-llm-inspector__usage-val",children:R(_.total)})]})]})}import{jsx as y1,jsxs as p_}from"react/jsx-runtime";function N0({usage:_}){let N=O_(_);return y1("span",{children:p_("span",{className:"cortex-llm-inspector__step-metrics",children:[p_("span",{className:"cortex-llm-inspector__metric",children:[y1("span",{className:"cortex-llm-inspector__dot cortex-llm-inspector__dot--input"}),R(_.input.total)]}),p_("span",{className:"cortex-llm-inspector__metric",children:[y1("span",{className:"cortex-llm-inspector__dot cortex-llm-inspector__dot--output"}),R(_.output.total)]}),N!==null?p_("span",{className:"cortex-llm-inspector__cache-pct",children:[N,"%"]}):null]})})}import{jsx as c,jsxs as __}from"react/jsx-runtime";function k0({messageId:_}){let{t:N,api:k}=B(),[L,Z]=E_(!1),[J,X]=E_(!1),[G,$]=E_([]),[K,Q]=E_(null),[M,q]=E_({}),y=b2(!1);async function U(){if(!y.current){X(!0);try{$(await k.listLlmRequests(_))}finally{X(!1),y.current=!0}}Z((V)=>!V)}function H(V){Q((Y)=>Y===V?null:V)}function S(V){return M[V]??"prompt"}function F(V,Y){q((I)=>({...I,[V]:Y}))}return __("div",{className:z("cortex-llm-inspector",L&&"cortex-llm-inspector--open"),children:[__("button",{className:"cortex-llm-inspector__trigger",onClick:()=>void U(),children:[c("svg",{className:"cortex-llm-inspector__icon",width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",children:c("path",{d:"M6 2a4 4 0 1 0 0 8 4 4 0 0 0 0-8ZM0 6a6 6 0 1 1 10.89 3.477l4.817 4.816a1 1 0 0 1-1.414 1.414l-4.816-4.816A6 6 0 0 1 0 6Z",fill:"currentColor"})}),c("span",{children:N("translate_inspect_llm_requests")}),J?c("span",{className:"cortex-llm-inspector__loading",children:N("translate_loading")}):G.length>0?c("span",{className:"cortex-llm-inspector__badge",children:G.length}):null,c("svg",{className:"cortex-llm-inspector__chevron",width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:c("path",{d:"M3 4.5L6 7.5L9 4.5",stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round"})})]}),c("div",{className:"cortex-llm-inspector__panel-wrapper",children:c("div",{className:"cortex-llm-inspector__panel-inner",children:__("div",{className:"cortex-llm-inspector__panel",children:[G.length===0&&!J?c("div",{className:"cortex-llm-inspector__empty",children:N("translate_no_llm_requests")}):null,G.map((V,Y)=>__("div",{className:z("cortex-llm-inspector__step",K===V.id&&"cortex-llm-inspector__step--expanded"),children:[__("button",{className:"cortex-llm-inspector__step-header",onClick:()=>H(V.id),children:[c("span",{className:"cortex-llm-inspector__step-label",children:N("translate_step_n",{number:Y+1})}),V.tokenUsage?c(N0,{usage:V.tokenUsage}):null,c("svg",{className:"cortex-llm-inspector__step-chevron",width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",children:c("path",{d:"M3 4.5L6 7.5L9 4.5",stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round"})})]}),c("div",{className:"cortex-llm-inspector__step-body-wrapper",children:c("div",{className:"cortex-llm-inspector__step-body-inner",children:__("div",{className:"cortex-llm-inspector__step-body",children:[V.tokenUsage?c(_0,{usage:V.tokenUsage}):null,__("div",{className:"cortex-llm-inspector__tabs",children:[c("button",{className:z("cortex-llm-inspector__tab",S(V.id)==="prompt"&&"cortex-llm-inspector__tab--active"),onClick:()=>F(V.id,"prompt"),children:N("translate_request")}),c("button",{className:z("cortex-llm-inspector__tab",S(V.id)==="response"&&"cortex-llm-inspector__tab--active"),onClick:()=>F(V.id,"response"),children:N("translate_response")})]}),__("div",{className:"cortex-llm-inspector__json-pane",children:[c(e,{className:"cortex-llm-inspector__json-copy",value:S(V.id)==="prompt"?n_(V.prompt):n_(V.output)}),S(V.id)==="prompt"?c(X_,{data:S_(V.prompt),expandDepth:2}):c(X_,{data:S_(V.output),expandDepth:2})]})]})})})]},V.id))]})})})]})}import{useEffect as R2,useRef as c2,useState as L0}from"react";import{jsx as A_,jsxs as Z0}from"react/jsx-runtime";function z_({labels:_,className:N}){let{t:k}=B(),[L,Z]=L0(0),[J,X]=L0("idle"),G=c2(_.length);return G.current=_.length,R2(()=>{let $,K;function Q(){$=setTimeout(()=>{X("exiting"),$=setTimeout(()=>{Z((M)=>(M+1)%G.current),X("enter-start"),K=requestAnimationFrame(()=>{X("entering"),$=setTimeout(()=>{X("idle"),Q()},300)})},300)},2000)}return Q(),()=>{if($)clearTimeout($);if(K)cancelAnimationFrame(K)}},[]),Z0("div",{className:z("cortex-subtle-activity",N),children:[Z0("div",{className:"cortex-subtle-activity__dots",children:[A_("span",{className:"cortex-subtle-activity__dot"}),A_("span",{className:"cortex-subtle-activity__dot cortex-subtle-activity__dot--d1"}),A_("span",{className:"cortex-subtle-activity__dot cortex-subtle-activity__dot--d2"})]}),A_("div",{className:"cortex-subtle-activity__label-mask",children:A_("span",{className:z("cortex-subtle-activity__label",`cortex-subtle-activity__label--${J}`),children:k(_[L])})})]})}import{jsx as J0}from"react/jsx-runtime";var I2=Z_("reasoning");function $0(){return J0("div",{className:"cortex-reasoning-animated",children:J0(z_,{labels:I2})})}import{jsx as r,jsxs as w_}from"react/jsx-runtime";function X0(_){let{reasoningPart:N,streaming:k=!1}=_,{t:L}=B();return w_("details",{className:"cortex-reasoning-details",children:[w_("summary",{className:"cortex-reasoning-details__summary",children:[w_("div",{className:"cortex-reasoning-details__header",children:[r("span",{className:"cortex-reasoning-details__icon",children:w_("svg",{width:"14",height:"14",viewBox:"0 0 20 20",fill:"none","aria-hidden":"true",children:[r("path",{d:"M10 2C6.686 2 4 4.686 4 8c0 1.655.672 3.154 1.757 4.243.362.363.576.858.576 1.371V14.5a1 1 0 0 0 1 1h5.334a1 1 0 0 0 1-1v-.886c0-.513.214-1.008.576-1.371A5.978 5.978 0 0 0 16 8c0-3.314-2.686-6-6-6Z",stroke:"currentColor",strokeWidth:"1.4",strokeLinecap:"round",strokeLinejoin:"round"}),r("path",{d:"M7.5 17.5h5M8.5 8a2 2 0 0 1 2-2",stroke:"currentColor",strokeWidth:"1.4",strokeLinecap:"round",strokeLinejoin:"round"})]})}),r("div",{className:"cortex-reasoning-details__title-group",children:w_("div",{className:"cortex-reasoning-details__title-row",children:[r("div",{className:"cortex-reasoning-details__title",children:L("translate_reasoning")}),r("span",{className:z("cortex-reasoning-details__badge",k?"cortex-reasoning-details__badge--streaming":"cortex-reasoning-details__badge--done"),children:k?"Streaming":"Done"})]})})]}),r("span",{className:"cortex-reasoning-details__chevron","aria-hidden":"true",children:r("svg",{width:"14",height:"14",viewBox:"0 0 20 20",fill:"none",children:r("path",{d:"m5.75 8.25 4.25 4.25 4.25-4.25",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})})]}),r("div",{className:"cortex-reasoning-details__body",children:r("div",{className:"cortex-reasoning-details__content",children:r("pre",{className:"cortex-reasoning-details__pre",children:N.content.trim()?N.content:"No reasoning provided."})})})]})}import{useEffect as G0,useRef as O1,useState as C2}from"react";import{jsx as V0}from"react/jsx-runtime";function K0(_){let{role:N,textPart:k,streaming:L=!1}=_,Z=N==="assistant"&&L?"":k.content,[J,X]=C2(Z),G=O1(Z),$=O1(null),K=O1(!0);return G0(()=>{function Q(M){G.current=M,X(M)}if(N!=="assistant"||!L){$.current?.destroy(),$.current=null,Q(k.content),K.current=!1;return}if(!$.current)$.current=new J_(Q),$.current.seed(G.current);if(K.current){K.current=!1,$.current.seed(k.content);return}$.current.update(k.content,!1)},[N,L,k]),G0(()=>()=>{$.current?.destroy(),$.current=null},[]),V0("div",{className:z("cortex-text-part",N==="assistant"&&"cortex-text-part--assistant",N==="user"&&"cortex-text-part--user"),children:V0("div",{className:z("cortex-text-bubble",N==="assistant"&&"cortex-text-bubble--assistant",N==="user"&&"cortex-text-bubble--user"),dangerouslySetInnerHTML:{__html:K1(J)}})})}import{jsx as p,jsxs as N_}from"react/jsx-runtime";function W0({toolCallPart:_}){let{t:N}=B(),{state:k,approval:L}=_,Z=_.output,J=i_(_);function X(){if(k==="complete")return N_("div",{className:"dbg-tool__section dbg-tool__section--success",children:[N_("div",{className:"dbg-tool__section-bar",children:[p("span",{className:"dbg-tool__section-label dbg-tool__section-label--success",children:N("translate_output")}),p("span",{className:"dbg-tool__section-lang",children:"json"}),p(e,{value:J})]}),p("div",{dir:"ltr",className:"dbg-tool__tree",children:p(X_,{data:Z,expandDepth:2})})]});if(k==="error")return N_("div",{className:"dbg-tool__section dbg-tool__section--error",children:[N_("div",{className:"dbg-tool__section-bar",children:[p("span",{className:"dbg-tool__section-label dbg-tool__section-label--error",children:N("translate_error")}),p(e,{value:J})]}),p("pre",{dir:"ltr",className:"dbg-tool__error-pre",children:J})]});if(k==="approval-requested")return N_("div",{className:"dbg-tool__section dbg-tool__section--approval",children:[N_("div",{className:"dbg-tool__section-bar",children:[p("span",{className:"dbg-tool__section-label dbg-tool__section-label--approval",children:N("translate_approval_requested")}),p("span",{className:"dbg-tool__section-lang",children:L?.id})]}),p("div",{className:"dbg-tool__message dbg-tool__message--approval",children:N("translate_waiting_for_approval")})]});if(k==="approval-responded")return N_("div",{className:"dbg-tool__section dbg-tool__section--approval",children:[N_("div",{className:"dbg-tool__section-bar",children:[p("span",{className:"dbg-tool__section-label dbg-tool__section-label--approval",children:N("translate_approval_response")}),p("span",{className:"dbg-tool__section-lang",children:L?.id})]}),p("div",{className:"dbg-tool__message dbg-tool__message--approval",children:N(L?.approved?"translate_tool_approved":"translate_tool_response_received")})]});return null}return p("div",{children:X()})}import{jsx as Y0,jsxs as S2}from"react/jsx-runtime";function Q0({toolCallPart:_}){let{t:N}=B(),k=x_(_);return Y0("span",{children:S2("span",{className:z("dbg-tool__state",k.modifier&&`dbg-tool__state--${k.modifier}`),children:[k.pulse&&Y0("span",{className:z("dbg-tool__pulse",k.pulse==="violet"&&"dbg-tool__pulse--violet")}),N(k.labelKey)]})})}import{jsx as T,jsxs as s}from"react/jsx-runtime";function z0({toolCallPart:_}){let{t:N}=B(),{codeSnippets:k,remainingInput:L,remainingInputText:Z}=d_(_.input);return s("details",{className:"dbg-tool","data-state":_.state,children:[T("summary",{className:"dbg-tool__summary",children:s("div",{className:"dbg-tool__header",children:[s("div",{className:"dbg-tool__meta",children:[T("div",{className:"dbg-tool__title-row",children:T("span",{className:"dbg-tool__name",title:_.name,children:_.name})}),T("div",{className:"dbg-tool__id-row",children:T("span",{className:"dbg-tool__id",children:_.id})})]}),s("div",{className:"dbg-tool__actions",children:[T(Q0,{toolCallPart:_}),T("svg",{className:"dbg-tool__chevron",width:"14",height:"14",viewBox:"0 0 20 20",fill:"none",children:T("path",{d:"m5.75 8.25 4.25 4.25 4.25-4.25",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})]})}),s("div",{className:"dbg-tool__body",children:[k.map((J)=>s("div",{className:"dbg-tool__section",children:[s("div",{className:"dbg-tool__section-bar",children:[T("span",{className:"dbg-tool__section-label",children:J.key}),T("span",{className:"dbg-tool__section-lang",children:J.lang}),T(e,{value:J.value})]}),T("pre",{dir:"ltr",className:"dbg-tool__pre",children:T("code",{className:"hljs",dangerouslySetInnerHTML:{__html:W1(J.value,J.lang)}})})]},J.key)),!!L&&s("div",{className:"dbg-tool__section",children:[s("div",{className:"dbg-tool__section-bar",children:[T("span",{className:"dbg-tool__section-label",children:N("translate_input")}),T("span",{className:"dbg-tool__section-lang",children:"json"}),T(e,{value:Z})]}),T("div",{dir:"ltr",className:"dbg-tool__tree",children:T(X_,{data:L,expandDepth:2})})]}),T(W0,{toolCallPart:_})]})]})}import{useEffect as q0,useRef as M1,useState as F0}from"react";import{jsx as C,jsxs as P_}from"react/jsx-runtime";function H0({message:_,toolCallPart:N}){let{config:k,addToolResult:L,isAgentWorking:Z}=B(),J=k.toolComponents?.[N.name];if(J)return C("div",{className:"cortex-tool-call-animated",children:C(J,{toolCallPart:N,message:_,setOutput:(X)=>void L(N.id,N.name,X)})});if(N.state==="input-complete"&&!Z)return C("div",{className:"cortex-tool-call-animated",children:C(n2,{toolCallPart:N})});return C("div",{className:"cortex-tool-call-animated",children:C(D0,{toolCallPart:N})})}function n2({toolCallPart:_}){let{api:N,t:k,addToolResult:L,selectedThread:Z,config:J}=B(),X=Z?.id,[G,$]=F0({phase:"initiating"}),[K]=F0(J.trustSameOriginEmbeds),Q=M1(void 0),M=M1({api:N,addToolResult:L,toolName:_.name});if(M.current={api:N,addToolResult:L,toolName:_.name},q0(()=>{if(!X)return;let y=X1({initiate:()=>M.current.api.initiateToolCall(X,_.id),onState:$,submit:(H)=>M.current.addToolResult(_.id,M.current.toolName,H)});Q.current=y,y.start();let U=(H)=>y.handleMessage(H);return window.addEventListener("message",U),()=>{if(window.removeEventListener("message",U),y.dispose(),Q.current===y)Q.current=void 0}},[_.id,X]),!X||G.phase==="unavailable"||G.phase==="settling")return C(D0,{toolCallPart:_});let q=P_("div",{className:"cortex-client-tool-embed",children:[P_("div",{className:"cortex-client-tool-embed__bar",children:[C("span",{children:k("translate_client_tool_title")}),C("button",{type:"button",className:"cortex-client-tool-embed__cancel",onClick:()=>Q.current?.cancel(),children:k("translate_client_tool_cancel")})]}),G.phase==="embedded"?C("iframe",{className:"cortex-client-tool-embed__frame",src:G.embedUrl,sandbox:Z1(G.embedUrl,window.location.origin,K),title:k("translate_client_tool_title"),ref:(y)=>Q.current?.setSource(y?.contentWindow),onLoad:(y)=>{if(!J1(G.embedUrl,window.location.origin,K)&&$1(y.currentTarget,window.location.origin))Q.current?.terminate()}}):G.phase==="error"?P_("div",{className:"cortex-client-tool-embed__status",children:[C("span",{children:k("translate_client_tool_failed")}),C("button",{type:"button",className:"cortex-client-tool-embed__retry",onClick:()=>void Q.current?.start(),children:k("translate_client_tool_retry")})]}):C("div",{className:"cortex-client-tool-embed__status",children:k("translate_client_tool_loading")})]});return G.phase==="embedded"&&G.surface==="modal"?C(g2,{label:k("translate_client_tool_title"),onCancel:()=>Q.current?.cancel(),children:q}):q}function g2({label:_,onCancel:N,children:k}){let L=M1(null);return q0(()=>{let Z=L.current;return Z?.showModal(),()=>Z?.close()},[]),C("dialog",{ref:L,className:"cortex-client-tool-embed-dialog","aria-label":_,onCancel:(Z)=>{Z.preventDefault(),N()},children:k})}function D0({toolCallPart:_}){let{t:N}=B(),{state:k,active:L,titleKey:Z}=a_(_);return P_("div",{className:"cortex-tool-pill",children:[P_("span",{className:"cortex-tool-pill__icon",children:[C("span",{className:z("cortex-tool-pill__spinner",L&&"cortex-tool-pill__spinner--visible")}),C("svg",{className:z("cortex-tool-pill__svg","cortex-tool-pill__svg--check",k==="complete"&&"cortex-tool-pill__svg--visible"),viewBox:"0 0 20 20",fill:"none",children:C("path",{d:"M5.5 10.5 L8.5 13.5 L14.5 7",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),C("svg",{className:z("cortex-tool-pill__svg","cortex-tool-pill__svg--error",k==="error"&&"cortex-tool-pill__svg--visible"),viewBox:"0 0 20 20",fill:"none",children:C("path",{d:"M6.5 6.5 L13.5 13.5 M13.5 6.5 L6.5 13.5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})})]}),C("span",{className:z("cortex-tool-pill__title",k==="error"&&"cortex-tool-pill__title--error"),children:N(Z)})]})}import{jsx as T2}from"react/jsx-runtime";var f2=Z_("code");function B0(){return T2(z_,{labels:f2})}import{jsx as m2}from"react/jsx-runtime";var p2=Z_("graph");function y0(){return m2(z_,{labels:p2})}import{jsx as E1}from"react/jsx-runtime";function O0({message:_,toolCallPart:N}){if(N.name==="queryGraph")return E1(y0,{});if(N.name==="executeCode")return E1(B0,{});return E1(H0,{toolCallPart:N,message:_})}import{jsx as F_,jsxs as u2}from"react/jsx-runtime";function M0(_){let{message:N,part:k,debugMode:L=!1,animate:Z=!1,streaming:J=!1}=_,{t:X}=B();function G(){switch(k.type){case"text":return F_(K0,{textPart:k,role:N.role,streaming:J});case"thinking":return L?F_(X0,{reasoningPart:k,streaming:J}):F_($0,{});case"tool-call":return L?F_(z0,{toolCallPart:k}):F_(O0,{toolCallPart:k,message:N});default:return u2("p",{className:"cortex-unhandled-type",children:[X("translate_unhandled_type")," ",k.type]})}}return F_("div",{className:z("cortex-message-part",Z&&"cortex-message-part--animated"),children:G()})}import{useState as l2}from"react";import{jsx as P,jsxs as g}from"react/jsx-runtime";function E0({usage:_,modelId:N}){let{t:k}=B(),[L,Z]=l2(!1),J=O_(_)??0;return g("div",{className:z("cortex-token-usage",L&&"cortex-token-usage--expanded"),children:[g("button",{className:"cortex-token-usage__summary",onClick:()=>Z((X)=>!X),children:[g("span",{className:"cortex-token-usage__total",children:[P("span",{className:"cortex-token-usage__total-number",children:R(_.total)}),P("span",{className:"cortex-token-usage__total-label",children:k("translate_tokens")})]}),N?P("span",{className:"cortex-token-usage__model",children:N}):null,g("span",{className:"cortex-token-usage__pills",children:[g("span",{className:"cortex-token-usage__pill",children:[P("span",{className:"cortex-token-usage__dot cortex-token-usage__dot--input"}),R(_.input.total)]}),g("span",{className:"cortex-token-usage__pill",children:[P("span",{className:"cortex-token-usage__dot cortex-token-usage__dot--output"}),R(_.output.total)]})]}),J>0?g("span",{className:"cortex-token-usage__cache-badge",children:[J,"%"]}):null,P("svg",{className:"cortex-token-usage__chevron",width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:P("path",{d:"M3 4.5L6 7.5L9 4.5",stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round"})})]}),P("div",{className:"cortex-token-usage__details",children:P("div",{className:"cortex-token-usage__details-inner",children:g("div",{className:"cortex-token-usage__columns",children:[g("div",{className:"cortex-token-usage__col",children:[g("div",{className:"cortex-token-usage__col-header",children:[P("span",{className:"cortex-token-usage__dot cortex-token-usage__dot--input"}),P("span",{className:"cortex-token-usage__col-label",children:k("translate_input")}),P("span",{className:"cortex-token-usage__col-total",children:R(_.input.total)})]}),g("div",{className:"cortex-token-usage__rows",children:[_.input.noCache?g("div",{className:"cortex-token-usage__row",children:[P("span",{className:"cortex-token-usage__row-label",children:k("translate_fresh")}),P("span",{className:"cortex-token-usage__row-value",children:R(_.input.noCache)})]}):null,_.input.cacheRead?g("div",{className:"cortex-token-usage__row",children:[P("span",{className:"cortex-token-usage__row-label",children:k("translate_cache_read")}),P("span",{className:"cortex-token-usage__row-value",children:R(_.input.cacheRead)})]}):null,_.input.cacheWrite?g("div",{className:"cortex-token-usage__row",children:[P("span",{className:"cortex-token-usage__row-label",children:k("translate_cache_write")}),P("span",{className:"cortex-token-usage__row-value",children:R(_.input.cacheWrite)})]}):null]}),J>0?g("div",{className:"cortex-token-usage__cache-bar-row",children:[P("div",{className:"cortex-token-usage__cache-bar",children:P("div",{className:"cortex-token-usage__cache-fill",style:{width:`${J}%`}})}),P("span",{className:"cortex-token-usage__cache-label",children:k("translate_n_percent_cached",{percent:J})})]}):null]}),g("div",{className:"cortex-token-usage__col",children:[g("div",{className:"cortex-token-usage__col-header",children:[P("span",{className:"cortex-token-usage__dot cortex-token-usage__dot--output"}),P("span",{className:"cortex-token-usage__col-label",children:k("translate_output")}),P("span",{className:"cortex-token-usage__col-total",children:R(_.output.total)})]}),g("div",{className:"cortex-token-usage__rows",children:[_.output.text?g("div",{className:"cortex-token-usage__row",children:[P("span",{className:"cortex-token-usage__row-label",children:k("translate_text")}),P("span",{className:"cortex-token-usage__row-value",children:R(_.output.text)})]}):null,_.output.reasoning?g("div",{className:"cortex-token-usage__row",children:[P("span",{className:"cortex-token-usage__row-label",children:k("translate_reasoning")}),P("span",{className:"cortex-token-usage__row-value",children:R(_.output.reasoning)})]}):null]})]})]})})})]})}import{jsx as q_,jsxs as A0}from"react/jsx-runtime";function w0(_){let{message:N,debugMode:k=!1,animate:L=!1}=_,{messages:Z,isAgentWorking:J,messageMetadata:X}=B(),G=J&&b_(Z)?.id===N.id,$=N.role==="assistant",K=N.parts,Q=K.filter((F,V)=>{if(F.type==="tool-result")return!1;return k||!t_(F,V===K.length-1,G)}),M=G?Q.length-1:-1,q=X.get(N.id),y=Boolean(q?.isAborted),U=q?.tokenUsage,H=N.role==="user"?q?.attachments??[]:[],S=k&&!G&&(Boolean(U)||$);return q_("div",{className:"cortex-message",children:Q.length>0&&A0("div",{className:"cortex-message-parts",children:[Q.map((F,V)=>q_(M0,{part:F,message:N,debugMode:k,animate:L,streaming:V===M},V)),H.length>0&&q_(s1,{attachments:H}),y&&q_(a1,{}),S&&A0("div",{className:"cortex-message-debug-zone",children:[U&&q_(E0,{usage:U,modelId:q?.modelId}),$&&q_(k0,{messageId:N.id})]})]})})}import{jsx as A1}from"react/jsx-runtime";function P0(_){let{messages:N,selectedThread:k}=B(),L=u_(null),Z=u_(!0),J=u_(!0),X=u_(!1),[G,$]=o2(!1);function K(){let H=L.current;if(H)H.scrollTop=H.scrollHeight}function Q(){if(X.current)return;X.current=!0,queueMicrotask(()=>{X.current=!1,K(),Z.current=!1})}m_(()=>{let H=L.current;if(Q(),$(!0),!H||typeof MutationObserver>"u")return;let S=new MutationObserver(()=>{if(!Z.current&&!J.current)return;Q()});return S.observe(H,{childList:!0,subtree:!0,characterData:!0}),()=>S.disconnect()},[]);let M=k?.id;m_(()=>{$(!1),Z.current=!0,queueMicrotask(()=>$(!0))},[M]);let q=N[N.length-1],y=q?.role==="user"?q.id:void 0;m_(()=>{if(y)Z.current=!0},[y]),m_(()=>{if(!Z.current&&!J.current)return;Q()},[N]);function U(){let H=L.current;if(!H)return;J.current=H.scrollHeight-H.scrollTop-H.clientHeight<100}return A1("div",{className:_.className,children:A1("div",{ref:L,className:"cortex-message-list",onScroll:U,children:N.map((H)=>A1(w0,{message:H,debugMode:_.debugMode,animate:G},H.id))})})}import{jsx as v,jsxs as x,Fragment as j2}from"react/jsx-runtime";var U0="M13.5 7.6c0 2.4-2.5 4.4-5.5 4.4-.6 0-1.2-.08-1.7-.23L3 13l.8-2.3C3 9.8 2.5 8.7 2.5 7.6 2.5 5.2 5 3.2 8 3.2s5.5 2 5.5 4.4Z";function v0(_){let{config:N,t:k,threads:L,selectedThread:Z,deleteThread:J}=B(),X=N.locale??"en";return x("div",{className:_.className,children:[x("div",{className:"cortex-widget__threads-header",children:[x("div",{children:[v("h2",{className:"cortex-widget__threads-title",children:k("translate_threads")}),v("p",{className:"cortex-widget__threads-count",children:k(L?.length===1?"translate_one_conversation":"translate_n_conversations",{count:L?.length??0})})]}),x("button",{onClick:()=>_.onNewChatRequested(),className:"cortex-widget__new-chat-btn",children:[v("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"none",children:v("path",{d:"M8 3v10M3 8h10",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})}),k("translate_new")]})]}),v("div",{className:"cortex-widget__threads-list",children:L===void 0?[1,2,3,4].map((G)=>x("div",{className:"cortex-widget__thread-skeleton",children:[v("div",{className:"cortex-skeleton cortex-widget__thread-skeleton-icon"}),v("div",{className:"cortex-widget__thread-skeleton-lines",children:v("div",{className:"cortex-skeleton cortex-widget__thread-skeleton-line",style:{width:`${40+G*12}%`}})})]},G)):x(j2,{children:[L.map((G)=>{let $=G.id===Z?.id,K=F1(G.updatedAt,X);return x("button",{onClick:()=>_.onThreadSelected(G),className:z("cortex-widget__thread-item",$&&"cortex-widget__thread-item--active"),children:[v("div",{className:z("cortex-widget__thread-icon",$&&"cortex-widget__thread-icon--active"),children:v("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",children:v("path",{d:U0,stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"})})}),x("div",{className:"cortex-widget__thread-info",children:[x("div",{className:"cortex-widget__thread-title-row",children:[v("p",{className:z("cortex-widget__thread-title",$&&"cortex-widget__thread-title--active"),children:G.title??k("translate_untitled")}),G.isRunning&&x("span",{className:z("cortex-widget__thread-running",$&&"cortex-widget__thread-running--active"),children:[v("span",{className:"cortex-widget__thread-running-dot"}),k("translate_running")]})]}),K&&v("p",{className:"cortex-widget__thread-time",children:K})]}),v("span",{role:"button",tabIndex:0,onClick:(Q)=>{Q.stopPropagation(),J(G.id)},onKeyDown:(Q)=>{if(Q.key!=="Enter"&&Q.key!==" ")return;Q.preventDefault(),Q.stopPropagation(),J(G.id)},className:z("cortex-widget__thread-delete",$&&"cortex-widget__thread-delete--active"),children:v("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"none",children:v("path",{d:"M4 4l8 8M12 4l-8 8",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round"})})}),v("svg",{className:z("cortex-widget__thread-arrow",$&&"cortex-widget__thread-arrow--active"),width:"10",height:"10",viewBox:"0 0 16 16",fill:"none",children:v("path",{d:"M6 4l4 4-4 4",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]},G.id)}),!L.length&&x("div",{className:"cortex-widget__threads-empty",children:[v("div",{className:"cortex-widget__threads-empty-icon",children:v("svg",{width:"18",height:"18",viewBox:"0 0 16 16",fill:"none",className:"cortex-widget__threads-empty-svg",children:v("path",{d:U0,stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"})})}),v("p",{className:"cortex-widget__threads-empty-title",children:k("translate_no_threads_yet")}),v("p",{className:"cortex-widget__threads-empty-subtitle",children:k("translate_start_a_new_conversation")}),v("button",{onClick:()=>_.onNewChatRequested(),className:"cortex-widget__new-chat-btn cortex-widget__new-chat-btn--empty-state",children:k("translate_new_chat")})]})]})})]})}import{jsx as E,jsxs as a}from"react/jsx-runtime";var P1={messages:[],isAgentWorking:!1,isLoadingMessages:!1,hasPendingToolCalls:!1,messageMetadata:new Map};function r2({config:_,className:N}){let k=k_(_);k.current=_;let[L,Z]=H_(),[J,X]=H_(),[G,$]=H_(P1),[K,Q]=H_(!1),[M,q]=H_("threads"),[y,U]=H_(!1),H=k_(void 0),S=k_([]),F=k_(void 0),V=k_(null),Y=w1(()=>r_(()=>k.current.transport),[]),I=w1(()=>{let W=J?.thread;if(!W)return;return L?.find((A)=>A.id===W.id)??W},[L,J]),n=k_(I);n.current=I;let O=k_(G);O.current=G;let i=m((W)=>{$((A)=>({...A,...typeof W==="function"?W(A):W}))},[]),L_=m((W,A)=>{Z((w)=>{let l=w?.find((h_)=>h_.id===W);return l?B_(w??[],{...l,isRunning:A}):w})},[]),D=m((W,A)=>{if(n.current?.id===W.id&&H.current)return;let w=n.current;if(n.current=W,$(P1),X({thread:W,mode:A?.skipLoadingMessages?"skip":"load",epoch:0}),w&&w.id!==W.id)k.current.hooks?.onThreadDeselected?.(w);k.current.hooks?.onThreadSelected?.(W)},[]),b=m(()=>{let W=n.current;if(!W&&!H.current)return;if(n.current=void 0,X(void 0),$(P1),W)k.current.hooks?.onThreadDeselected?.(W)},[]),f=m((W)=>{X((A)=>({thread:W,mode:"reload",epoch:(A?.epoch??0)+1,initialMessages:O.current.messages}))},[]),u=m((W)=>{let A=n.current;if(A)return Promise.resolve(A.id);return F.current??=Y.createThread(W).then((w)=>{return F.current=void 0,Z((l)=>B_(l??[],w)),D(w,{skipLoadingMessages:!0}),w.id},(w)=>{throw F.current=void 0,w}),F.current},[Y,D]),j=w1(()=>k1({api:Y,ensureThread:()=>u()}),[Y,u]),U1=h2(j.subscribe,j.getState,j.getState),R0=m(async(W,A=[])=>{if(O.current.isAgentWorking||O.current.hasPendingToolCalls)return;let w=H.current;if(w){await w.send(W,A);return}S.current.push({prompt:W,attachments:A});try{await u(W)}catch(l){throw S.current=[],l}},[u]),c0=m(async()=>{await H.current?.abort()},[]),I0=m((W,A,w)=>H.current?.addToolResult(W,A,w)??Promise.resolve(),[]),C0=m(async(W)=>{if(n.current?.id===W)b();await Y.deleteThread(W),Z((A)=>A?I_(A,W):A)},[Y,b]),S0=m(()=>{j.discardConsumed(),setTimeout(()=>V.current?.focusInput())},[j]),n0=m(()=>{j.restoreConsumed(n.current?.id)},[j]),l_=m(async()=>{let W=c_(await Y.listThreads());return Z(W),W},[Y]),v1=m((W)=>{Z((w)=>{let l=V1(w??[],W);return w||l.length?l:w});let A=n.current?.id;switch(W.type){case"thread:deleted":if(A===W.payload.threadId)b();break;case"thread:run-started":if(A===W.payload.thread.id)H.current?.reattach(W.payload.thread);break;case"thread:messages-updated":H.current?.refreshMessages(W.payload.threadId);break}},[b]);b0(()=>{l_();let W=!1,A=G1({wsUrl:()=>k.current.wsUrl,transport:{baseUrl:()=>{let w=k.current.transport.baseUrl;return typeof w==="string"?w:w()},getHeaders:()=>k.current.transport.getHeaders()},onEvent:v1,onOpen:()=>{if(!W){W=!0;return}l_().then((w)=>{let l=n.current;if(!l)return;H.current?.reattach(w.find((h_)=>h_.id===l.id)??l)})}});return()=>{A.close()}},[v1,l_]);let o_=k_(void 0),j_=I?.id;b0(()=>{if(j_===o_.current)return;j.clear(o_.current),o_.current=j_},[j_,j]);let b1=_.locale??"en",D_=m((W,A)=>Y1(b1,W,A),[b1]),g0=_.viewMode??"helper",f0={config:_,t:D_,api:Y,debugMode:K,threads:L,selectedThread:I,deleteThread:C0,...G,send:R0,abort:c0,addToolResult:I0,queue:{items:U1,...L1(U1),accept:j.accept,remove:j.remove,consumeReady:j.consumeReady}};function T0(W){D(W),q("chat"),U(!1)}function p0(){b(),q("chat"),U(!1)}function m0(){b(),q("threads")}return E(H1.Provider,{value:f0,children:a("div",{className:z("cortex-widget",N),"data-cortex-theme":_.theme,children:[a("div",{className:z("cortex-widget__container",g0==="full"&&"cortex-widget__container--full",y&&"cortex-widget__container--sidebar-open"),onDragOver:(W)=>W.preventDefault(),onDrop:(W)=>W.preventDefault(),children:[E(v0,{className:z("cortex-widget__screen",M==="threads"&&"cortex-widget__screen--active",M!=="threads"&&"cortex-widget__screen--left"),onThreadSelected:T0,onNewChatRequested:p0}),a("div",{className:z("cortex-widget__screen",M==="chat"&&"cortex-widget__screen--active",M!=="chat"&&"cortex-widget__screen--right"),children:[a("div",{className:"cortex-widget__chat-header",children:[E("button",{onClick:()=>U((W)=>!W),className:"cortex-widget__sidebar-toggle-btn",children:E("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:E("path",{d:"M2.5 4h11M2.5 8h11M2.5 12h11",stroke:"currentColor",strokeWidth:"1.4",strokeLinecap:"round"})})}),E("button",{onClick:m0,className:"cortex-widget__back-btn",children:E("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",className:"cortex-widget__back-icon",children:E("path",{d:"M10 3L5 8l5 5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),E("div",{className:"cortex-widget__chat-title-wrap",children:E("p",{className:"cortex-widget__chat-title",children:I?.title??D_("translate_new_chat")})}),_.showDebugButton&&E("button",{onClick:()=>Q((W)=>!W),className:z("cortex-widget__debug-btn",K?"cortex-widget__debug-btn--on":"cortex-widget__debug-btn--off"),children:K?D_("translate_debug"):D_("translate_normal")})]}),G.isLoadingMessages&&!G.isAgentWorking?a("div",{className:"cortex-widget__messages-skeleton",children:[E("div",{className:"cortex-widget__msg-skel cortex-widget__msg-skel--user",children:a("div",{className:"cortex-widget__msg-skel-bubble cortex-widget__msg-skel-bubble--user",children:[E("div",{className:"cortex-skeleton cortex-widget__msg-skel-line",style:{width:"13rem"}}),E("div",{className:"cortex-skeleton cortex-widget__msg-skel-line",style:{width:"9rem"}})]})}),E("div",{className:"cortex-widget__msg-skel cortex-widget__msg-skel--assistant",children:a("div",{className:"cortex-widget__msg-skel-bubble cortex-widget__msg-skel-bubble--assistant",children:[E("div",{className:"cortex-skeleton cortex-widget__msg-skel-line",style:{width:"16rem"}}),E("div",{className:"cortex-skeleton cortex-widget__msg-skel-line",style:{width:"18rem"}}),E("div",{className:"cortex-skeleton cortex-widget__msg-skel-line",style:{width:"12rem"}})]})}),E("div",{className:"cortex-widget__msg-skel cortex-widget__msg-skel--user",children:E("div",{className:"cortex-widget__msg-skel-bubble cortex-widget__msg-skel-bubble--user",children:E("div",{className:"cortex-skeleton cortex-widget__msg-skel-line",style:{width:"11rem"}})})}),E("div",{className:"cortex-widget__msg-skel cortex-widget__msg-skel--assistant",children:a("div",{className:"cortex-widget__msg-skel-bubble cortex-widget__msg-skel-bubble--assistant",children:[E("div",{className:"cortex-skeleton cortex-widget__msg-skel-line",style:{width:"14rem"}}),E("div",{className:"cortex-skeleton cortex-widget__msg-skel-line",style:{width:"15rem"}})]})})]}):E(P0,{className:"cortex-widget__messages",debugMode:K}),G.isAgentWorking&&!G.hasPendingToolCalls&&a("div",{className:"cortex-widget__working",children:[a("div",{className:"cortex-widget__working-dots",children:[E("span",{className:"cortex-working-dot"}),E("span",{className:"cortex-working-dot"}),E("span",{className:"cortex-working-dot"})]}),E("span",{className:"cortex-widget__working-text",children:D_("translate_thinking")})]}),!G.hasPendingToolCalls&&E(i1,{ref:V})]}),E("div",{className:"cortex-widget__sidebar-backdrop",onClick:()=>U(!1)})]}),J&&E(h1,{thread:J.thread,mode:J.mode,initialMessages:J.initialMessages,api:Y,configRef:k,sessionRef:H,pendingSendRef:S,patchUi:i,setRunning:L_,remount:f,onTurnFinished:S0,onSendFailed:n0},`${J.thread.id}:${J.epoch}`)]})})}export{r2 as CortexChatWidget};
|
|
1
|
+
import{useCallback as o,useEffect as C0,useMemo as c1,useRef as $_,useState as V_,useSyncExternalStore as d2}from"react";function n_(_){return Promise.resolve(_.getHeaders())}function f1(_,N){let k=_.baseUrl;return(typeof k==="string"?k:k()).replace(/\/$/,"")+N}function i0(_){let N=_?.match(/filename\*\s*=\s*[^']*'[^']*'([^;\r\n]+)/i)?.[1]?.trim().replace(/^"|"$/g,"");if(N)try{return decodeURIComponent(N)}catch{}return _?.match(/filename\s*=\s*"?([^";\r\n]+)"?/i)?.[1]}function _1(_){function N(){return n_(_())}function k($){return f1(_(),$)}async function L($,Z){let G=new Headers(await N());if(new Headers(Z?.headers).forEach(function(W,Y){G.set(Y,W)}),Z?.body instanceof FormData)G.delete("Content-Type");else if(!G.has("Content-Type"))G.set("Content-Type","application/json");let X=await fetch(k($),{...Z,headers:G});if(!X.ok)throw Error(`HTTP ${X.status}: ${X.statusText}`);let J=await X.text();return J?JSON.parse(J):void 0}return{getCapabilities(){return L("/capabilities")},listThreads(){return L("/threads")},createThread($){return L("/threads",{method:"POST",body:JSON.stringify({prompt:$})})},deleteThread($){return L(`/threads/${$}`,{method:"DELETE"})},listMessages($){return L(`/threads/${$}/messages`)},listLlmRequests($){return L(`/messages/${$}/llm-requests`)},abortStream($){return L(`/chat/${$}/abort`,{method:"POST"})},initiateToolCall($,Z){return L(`/chat/${$}/tools/${Z}/initiate`,{method:"POST"})},async uploadAttachment($,Z){let G=new FormData;return G.append("file",Z),await L(`/threads/${$}/files`,{method:"POST",body:G})},deleteAttachment($){return L(`/files/${$}`,{method:"DELETE"})},async downloadAttachment($){let Z=await fetch(k(`/files/${$}`),{headers:await N()});if(!Z.ok)throw Error(`HTTP ${Z.status}: ${Z.statusText}`);return{blob:await Z.blob(),name:i0(Z.headers.get("Content-Disposition"))??$}},resolveHeaders:N,resolveUrl:k}}var d0={complete:"success",error:"error","approval-requested":"approval","approval-responded":"approval","awaiting-input":"pending","input-streaming":"pending","input-complete":"pending"},a0={"awaiting-input":"translate_calling","input-streaming":"translate_calling","input-complete":"translate_input_ready","approval-requested":"translate_needs_approval","approval-responded":"translate_responded",complete:"translate_completed",error:"translate_error"};function N1(_){let{state:N,approval:k}=_;return{modifier:d0[N],labelKey:N==="approval-responded"&&k?.approved?"translate_approved":a0[N],pulse:N==="awaiting-input"||N==="input-streaming"?"default":N==="approval-requested"?"violet":void 0}}function k1(_){let N=_.output;if(N===void 0||N===null)return"";if(typeof N==="string")return N;return JSON.stringify(N,null,2)}var T1={code:"javascript",query:"cypher"};function L1(_){let N=_&&typeof _==="object"?_:null,k=N?Object.entries(T1).flatMap(([$,Z])=>{let G=N[$];return typeof G==="string"?[{key:$,lang:Z,value:G.replace(/\\n/g,`
|
|
2
|
+
`)}]:[]}):[],L=_;if(N){let $=Object.fromEntries(Object.entries(N).filter(([Z])=>!Object.hasOwn(T1,Z)));L=Object.keys($).length>0?$:null}return{codeSnippets:k,remainingInput:L,remainingInputText:L?JSON.stringify(L,null,2):""}}var p1=10,t0={"awaiting-input":"starting","input-streaming":"starting","input-complete":"processing","approval-requested":"processing","approval-responded":"processing",complete:"complete",error:"error"};function s0(_){let N=0;for(let k=0;k<_.length;k++)N=N*31+_.charCodeAt(k)|0;return Math.abs(N)%p1}function $1(_){let N=t0[_.state]??"processing",k=_.name==="readAttachment"?"attachment":"tool",L=k==="tool"?`_${s0(_.id)}`:"";return{state:N,active:N==="starting"||N==="processing",titleKey:N==="error"?"translate_tool_error":`translate_${k}_${N==="complete"?"done":"status"}${L}`}}function Z_(_){return Array.from({length:p1},(N,k)=>`translate_${_}_${k}`)}function Z1(_,N,k){return _.type==="thinking"&&!(k&&N)}import{EventType as _2}from"@tanstack/ai";import{fetchServerSentEvents as o1}from"@tanstack/ai-client";var J1=["image/png","image/jpeg","image/webp","application/pdf"];var m1=5;function u1(_,N){if(!J1.some((k)=>k===_))return"type";if(N>10485760)return"size";return"ok"}var l1="clientToolAnswers";var e0=new Set(["complete","error"]);function K_(_){return e0.has(_)}function S_(_){return(C_(_)?.parts??[]).filter((k)=>k.type==="tool-call"&&!K_(k.state))}function C_(_){for(let N=_.length-1;N>=0;N-=1){let k=_[N];if(k?.role==="assistant")return k}return}function G1(_){return{id:_.id,role:_.role,parts:_.parts}}function j1(_){for(let N=_.length-1;N>=0;N-=1){let k=_[N],L="parts"in k&&k.parts.some(($)=>$.type==="tool-result");if(k.role==="user"||L)return _.slice(N,N+1)}return _.slice(-1)}function N2(_){let[N]=_;if(!N||N.role!=="assistant"||!("parts"in N))return null;if(!N.parts.some((L)=>L.type==="tool-result"))return null;let k=N.parts.flatMap((L)=>L.type==="tool-call"&&K_(L.state)?[{toolCallId:L.id,output:L.output??null,state:L.state==="error"?"error":"complete"}]:[]);return k.length>0?k:null}function g_(_){return new Map(_.flatMap((N)=>N.metadata?[[N.id,N.metadata]]:[]))}function X1(_){let{api:N,thread:k}=_,L=async()=>({headers:await N.resolveHeaders()}),$=o1(()=>N.resolveUrl("/chat"),L),Z=function(J,W,Y,U){let q=j1(J),D=N2(q);return D?$.connect([],{...W,[l1]:D},Y,U):$.connect(q,W,Y,U)},G=o1(()=>N.resolveUrl(`/chat/${k.id}/stream`),L),X=[];return{connect:Z,async*joinRun(J,W){yield{type:_2.MESSAGES_SNAPSHOT,timestamp:Date.now(),messages:X},yield*G.joinRun(J,W)},hydrate:async()=>{let J=await k2(_);return X=J.messages,J}}}async function k2(_){let{api:N,thread:k,mode:L}=_,$=k.isRunning?{runId:k.id}:null;if(L==="skip")return{messages:[],activeRun:$,interrupts:null};if(L==="load")_.setLoadingMessages?.(!0);try{let Z=await N.listMessages(k.id),G=Z.map(G1);return _.onHydrated?.(Z,G),{messages:G,activeRun:$,interrupts:null}}finally{_.setLoadingMessages?.(!1)}}async function V1(_){try{let N=await _.api.listMessages(_.threadId);if(_.isStale?.())return;if(_.absorbMetadata(g_(N)),_.isStreaming())return;_.setMessages(N.map(G1))}catch{}}function O_(){if(typeof crypto.randomUUID==="function")return crypto.randomUUID();let _=crypto.getRandomValues(new Uint8Array(16));_[6]=_[6]&15|64,_[8]=_[8]&63|128;let N=Array.from(_,(k)=>k.toString(16).padStart(2,"0")).join("");return`${N.slice(0,8)}-${N.slice(8,12)}-${N.slice(12,16)}-${N.slice(16,20)}-${N.slice(20)}`}function W1(_){let{api:N}=_,k=new Set,L=new Set,$=[],Z=[];function G(){return $}function X(Q){return k.add(Q),()=>{k.delete(Q)}}function J(Q){$=Q;for(let V of k)V()}function W(Q,V){J($.map((z)=>z.localId===Q?{...z,...V}:z))}function Y(Q){if(L.delete(Q))return;W(Q,{status:"error"})}function U(Q){let V=[];for(let z of Q){let T=u1(z.type,z.size)!=="ok"||$.filter((p)=>p.status!=="error").length>=m1,c=O_();if(J([...$,{localId:c,filename:z.name,status:T?"error":"uploading"}]),!T)V.push({localId:c,file:z})}if(!V.length)return;_.ensureThread().then((z)=>{for(let{localId:T,file:c}of V){if(L.delete(T))continue;W(T,{threadId:z}),N.uploadAttachment(z,c).then((p)=>{if(L.delete(T)){N.deleteAttachment(p.id).catch(()=>{});return}W(T,{status:"ready",attachmentId:p.id,summary:p})},()=>Y(T))}},()=>{for(let{localId:z}of V)Y(z)})}function q(Q){let V=$.find((z)=>z.localId===Q);if(!V)return;if(V.status==="uploading"){L.add(Q),J($.filter((z)=>z.localId!==Q));return}if(V.attachmentId){W(Q,{status:"deleting"}),N.deleteAttachment(V.attachmentId).then(()=>J($.filter((z)=>z.localId!==Q)),()=>W(Q,{status:"error"}));return}J($.filter((z)=>z.localId!==Q))}function D(Q){let V=[];for(let z of $){if(z.threadId!==void 0&&z.threadId!==Q){V.push(z);continue}if(z.status==="uploading")L.add(z.localId);else if(z.status==="ready"&&z.threadId===Q&&z.attachmentId)N.deleteAttachment(z.attachmentId).catch(()=>{})}J(V)}function b(){let Q=$.flatMap((V)=>V.status==="ready"&&V.summary?[{...V,status:"ready",summary:V.summary}]:[]);return J($.filter((V)=>V.status!=="ready")),Z=Q,Q}function M(Q){let V=Z;if(Z=[],V.some((z)=>z.threadId!==Q))return;J([...V.map((z)=>({...z,status:"error"})),...$])}function R(){Z=[]}return{getState:G,subscribe:X,accept:U,remove:q,clear:D,consumeReady:b,restoreConsumed:M,discardConsumed:R}}function K1(_){return{uploading:_.some((N)=>N.status==="uploading"),busy:_.some((N)=>N.status==="uploading"||N.status==="deleting"),hasReady:_.some((N)=>N.status==="ready")}}var L2=["completed","cancelled","failed"];function r1(_,N,k){if(N!==k)return null;if(typeof _!=="object"||_===null)return null;let L=_;if(L.type!=="cortex:client-tool")return null;let $=L2.find((G)=>G===L.status);if(!$)return null;let Z=L.reference;return{type:"cortex:client-tool",status:$,...typeof Z==="string"?{reference:Z}:{},...L.result!==void 0?{result:L.result}:{}}}function Y1(_,N,k){try{return new URL(_).origin===N&&!k?"allow-scripts allow-forms allow-popups":"allow-scripts allow-forms allow-popups allow-same-origin"}catch{return"allow-scripts allow-forms allow-popups"}}function Q1(_,N,k){try{return k===!0&&new URL(_).origin===N}catch{return!1}}function z1(_,N){try{return _.contentWindow?.location.origin===N}catch{return!1}}function F1(_){let N=!1,k=!1,L,$;function Z(J){if(!N)_.onState(J)}function G(){if(N)return;k=!1,Z({phase:"error"})}function X(J){if(N||k)return;k=!0,Z({phase:"settling"});try{let W=_.submit(J);if(W instanceof Promise)W.catch(G)}catch{G()}}return{async start(){Z({phase:"initiating"});try{let J=await _.initiate();if(!J.embed){Z({phase:"unavailable"});return}if(!/^https?:$/.test(new URL(J.embedUrl).protocol)){Z({phase:"error"});return}L=J.embedOrigin,Z({phase:"embedded",embedUrl:J.embedUrl,surface:J.surface,embedOrigin:J.embedOrigin})}catch(J){let W=J instanceof Error?J.message:"";Z({phase:/HTTP 404/.test(W)?"unavailable":"error"})}},setSource(J){if(J!==null&&J!==void 0)$=J},handleMessage(J){if(!L)return;if($===void 0||J.source!==$)return;let W=r1(J.data,J.origin,L);if(!W)return;X({status:W.status,reference:W.reference,result:W.result})},cancel(){X({status:"cancelled"})},terminate(){if(N||k)return;L=void 0,$=void 0,Z({phase:"error"})},dispose(){N=!0}}}function $2(_){return Math.min(1000*2**(_-1),30000)}var Z2=1e4;function q1(_){let N,k,L=0,$=!1;function Z(){let X=typeof _.wsUrl==="function"?_.wsUrl():_.wsUrl;if(X===!1)return;let J=J2(X,_.transport.baseUrl);n_(_.transport).then((W)=>{if($)return;N=new WebSocket(G2(J,W)),N.addEventListener("open",()=>{let Y=N;setTimeout(()=>{if(N===Y&&!$)L=0},Z2),_.onOpen?.()}),N.addEventListener("message",(Y)=>{let U=Y.data;if(typeof U!=="string")return;let q;try{q=JSON.parse(U)}catch{return}_.onEvent(q)}),N.addEventListener("close",G)}).catch(G)}function G(){if($||k)return;L+=1,k=setTimeout(()=>{k=void 0,Z()},$2(L))}return Z(),{close(){$=!0,clearTimeout(k),N?.close()}}}function J2(_,N){if(_)return _;let k=typeof N==="string"?N:N(),L=new URL(k,window.location.origin);return L.protocol=L.protocol==="https:"?"wss:":"ws:",L.pathname=L.pathname.replace(/\/$/,"")+"/ws",L.toString()}function G2(_,N){let k=N.Authorization??N.authorization;if(!k?.startsWith("Bearer "))return _;let L=new URL(_,window.location.origin);if(L.searchParams.has("token"))return L.toString();return L.searchParams.set("token",k.slice(7)),L.toString()}function f_(_){return[..._].sort((N,k)=>{let L=Date.parse(k.updatedAt)-Date.parse(N.updatedAt);if(L!==0)return L;return Date.parse(k.createdAt)-Date.parse(N.createdAt)})}function M_(_,N){let k=[..._],L=k.findIndex(($)=>$.id===N.id);if(L===-1)k.push(N);else k[L]={...k[L],...N};return f_(k)}function T_(_,N){return _.filter((k)=>k.id!==N)}function D1(_,N){switch(N.type){case"thread:deleted":return T_(_,N.payload.threadId);case"thread:created":case"thread:title-updated":case"thread:run-started":case"thread:run-finished":case"thread:messages-updated":return M_(_,N.payload.thread);default:return _}}import{marked as X2}from"marked";import V2 from"dompurify";function H1(_){if(!_)return"";let N=X2.parse(_,{async:!1});return N=N.replace(/<table>/g,'<div style="overflow-x:auto"><table style="width:auto">').replace(/<\/table>/g,"</table></div>").replace(/<(t[hd])([\s>])/g,'<$1 style="padding:0.5rem 1rem"$2'),V2.sanitize(N)}import U_ from"highlight.js/lib/core";import W2 from"highlight.js/lib/languages/javascript";import K2 from"highlight.js/lib/languages/json";import Y2 from"highlight.js/lib/languages/sql";var h1=!1;function Q2(){if(h1)return;h1=!0,U_.registerLanguage("javascript",W2),U_.registerLanguage("json",K2),U_.registerLanguage("cypher",Y2)}function B1(_,N){if(!_)return"";return Q2(),U_.getLanguage(N)?U_.highlight(_,{language:N}).value:z2(_)}function z2(_){return _.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var x1={translate_new:"جديد",translate_history:"السجل",translate_back:"رجوع",translate_greeting:"بماذا يمكنني مساعدتك اليوم؟",translate_n_conversations:"{{count}} محادثات",translate_one_conversation:"محادثة واحدة",translate_no_threads_yet:"لا توجد محادثات بعد",translate_start_a_new_conversation:"ابدأ محادثة جديدة",translate_untitled:"بدون عنوان",translate_new_chat:"محادثة جديدة",translate_normal:"عادي",translate_debug:"تصحيح",translate_type_a_message:"اكتب رسالة...",translate_thinking:"جارٍ معالجة الطلب...",translate_reasoned:"تم الاستنتاج",translate_knowledge_graph_query:"استعلام الرسم البياني المعرفي",translate_javascript_code_execution:"تنفيذ كود جافاسكريبت",translate_completed:"مكتمل",translate_attach_files:"إرفاق ملفات",translate_drop_files_here:"أفلت ملفاتك هنا...",translate_remove_attachment:"إزالة المرفق",translate_attachment_rejected:"لا يمكن إرفاق هذا الملف",translate_attachment_caption:"من فضلك اطّلع على الملفات المرفقة.",translate_download:"تنزيل",translate_tool_status_0:"جارٍ جلب البيانات…",translate_tool_status_1:"جارٍ تحليل المعلومات…",translate_tool_status_2:"جارٍ معالجة الطلب…",translate_tool_status_3:"جارٍ تجميع النتائج…",translate_tool_status_4:"جارٍ تحضير الرد…",translate_tool_status_5:"جارٍ البحث…",translate_tool_status_6:"جارٍ فحص السجلات…",translate_tool_status_7:"جارٍ مراجعة التفاصيل…",translate_tool_status_8:"جارٍ إجراء الحسابات…",translate_tool_status_9:"جارٍ سحب المعلومات…",translate_tool_done_0:"تم جلب البيانات بنجاح",translate_tool_done_1:"تم التحليل بنجاح",translate_tool_done_2:"تمت معالجة الطلب بنجاح",translate_tool_done_3:"تم تجميع النتائج بنجاح",translate_tool_done_4:"تم تحضير الرد بنجاح",translate_tool_done_5:"تم البحث بنجاح",translate_tool_done_6:"تم فحص السجلات بنجاح",translate_tool_done_7:"تمت المراجعة بنجاح",translate_tool_done_8:"تمت الحسابات بنجاح",translate_tool_done_9:"تم استرجاع المعلومات بنجاح",translate_tool_error:"حدث خطأ",translate_attachment_status:"جارٍ قراءة الملف المرفق…",translate_attachment_done:"تمت قراءة الملف المرفق",translate_graph_0:"جارٍ استكشاف الروابط...",translate_graph_1:"جارٍ رسم الخريطة...",translate_graph_2:"جارٍ اكتشاف العلاقات...",translate_graph_3:"جارٍ تتبع الروابط...",translate_graph_4:"جارٍ التنقل في المعرفة...",translate_graph_5:"جارٍ كشف الرؤى...",translate_graph_6:"جارٍ ربط النقاط...",translate_graph_7:"جارٍ تتبع المسار...",translate_graph_8:"جارٍ تجميع الأجزاء...",translate_graph_9:"جارٍ بناء الصورة...",translate_code_0:"جارٍ حساب الأرقام...",translate_code_1:"جارٍ معالجة البيانات...",translate_code_2:"جارٍ تنفيذ طلبك...",translate_code_3:"جارٍ تحليل الأرقام...",translate_code_4:"جارٍ تجميع كل شيء...",translate_code_5:"جارٍ تحليل النتائج...",translate_code_6:"جارٍ العمل خلف الكواليس...",translate_code_7:"جارٍ ترتيب التفاصيل...",translate_code_8:"جارٍ تحضير إجابتك...",translate_code_9:"أوشك على الانتهاء...",translate_reasoning_0:"جارٍ التفكير...",translate_reasoning_1:"جارٍ دراسة الخيارات...",translate_reasoning_2:"جارٍ تقييم الاحتمالات...",translate_reasoning_3:"جارٍ التأمل في هذا...",translate_reasoning_4:"جارٍ إيجاد الحل...",translate_reasoning_5:"جارٍ ترتيب الأفكار...",translate_reasoning_6:"جارٍ التمعن في الأمر...",translate_reasoning_7:"جارٍ إيجاد أفضل طريقة...",translate_reasoning_8:"جارٍ تنظيم أفكاري...",translate_reasoning_9:"أوشك على الانتهاء...",translate_running:"قيد التنفيذ",translate_aborted:"تم الإلغاء",translate_input:"المدخلات",translate_output:"المخرجات",translate_calling:"جارٍ الاستدعاء",translate_input_ready:"المدخلات جاهزة",translate_needs_approval:"بحاجة إلى موافقة",translate_approved:"تمت الموافقة",translate_responded:"تم الرد",translate_error:"خطأ",translate_approval_requested:"طلب موافقة",translate_approval_response:"رد الموافقة",translate_waiting_for_approval:"في انتظار الموافقة لتنفيذ هذه الأداة.",translate_tool_approved:"تمت الموافقة.",translate_tool_response_received:"تم استلام الرد.",translate_tokens:"رمز",translate_fresh:"جديد",translate_cache_read:"قراءة من الذاكرة",translate_cache_write:"كتابة في الذاكرة",translate_n_percent_cached:"{{percent}}٪ مخزّن مؤقتًا",translate_text:"نص",translate_reasoning:"الاستنتاج",translate_read:"قراءة",translate_write:"كتابة",translate_total:"الإجمالي",translate_request:"الطلب",translate_response:"الرد",translate_step_n:"الخطوة {{number}}",translate_inspect_llm_requests:"فحص طلبات النموذج",translate_loading:"جارٍ التحميل…",translate_no_llm_requests:"لا توجد طلبات نموذج مسجّلة لهذه الرسالة.",translate_unhandled_type:"نوع غير مدعوم:",translate_client_tool_title:"أكمل هذه الخطوة للمتابعة",translate_client_tool_loading:"جارٍ تجهيز خطوة آمنة...",translate_client_tool_failed:"تعذّر تحميل هذه الخطوة",translate_client_tool_retry:"حاول مرة أخرى",translate_client_tool_cancel:"إلغاء"};var i1={translate_new:"New",translate_history:"History",translate_back:"Back",translate_greeting:"What can I help you with today?",translate_n_conversations:"{{count}} conversations",translate_one_conversation:"1 conversation",translate_no_threads_yet:"No threads yet",translate_start_a_new_conversation:"Start a new conversation",translate_untitled:"Untitled",translate_new_chat:"New Chat",translate_normal:"Normal",translate_debug:"Debug",translate_type_a_message:"Type a message...",translate_thinking:"Thinking things through...",translate_reasoned:"Reasoned",translate_knowledge_graph_query:"Knowledge Graph Query",translate_javascript_code_execution:"JavaScript Code Execution",translate_completed:"Completed",translate_attach_files:"Attach files",translate_drop_files_here:"Drop your files here...",translate_remove_attachment:"Remove attachment",translate_attachment_rejected:"This file cannot be attached",translate_attachment_caption:"Please take a look at the attached files.",translate_download:"Download",translate_tool_status_0:"Fetching data...",translate_tool_status_1:"Analyzing information...",translate_tool_status_2:"Processing request...",translate_tool_status_3:"Gathering results...",translate_tool_status_4:"Preparing response...",translate_tool_status_5:"Looking things up...",translate_tool_status_6:"Checking records...",translate_tool_status_7:"Reviewing details...",translate_tool_status_8:"Running calculations...",translate_tool_status_9:"Pulling information...",translate_tool_done_0:"Data fetched successfully",translate_tool_done_1:"Analysis completed successfully",translate_tool_done_2:"Request processed successfully",translate_tool_done_3:"Results gathered successfully",translate_tool_done_4:"Response prepared successfully",translate_tool_done_5:"Lookup completed successfully",translate_tool_done_6:"Records checked successfully",translate_tool_done_7:"Review completed successfully",translate_tool_done_8:"Calculations completed successfully",translate_tool_done_9:"Information retrieved successfully",translate_tool_error:"Something went wrong",translate_attachment_status:"Reading the attached file...",translate_attachment_done:"Finished reading the file",translate_graph_0:"Exploring connections...",translate_graph_1:"Mapping out the links...",translate_graph_2:"Discovering relationships...",translate_graph_3:"Tracing the connections...",translate_graph_4:"Navigating the knowledge...",translate_graph_5:"Uncovering insights...",translate_graph_6:"Connecting the dots...",translate_graph_7:"Following the trail...",translate_graph_8:"Piecing things together...",translate_graph_9:"Building the picture...",translate_code_0:"Running the numbers...",translate_code_1:"Working through the data...",translate_code_2:"Processing your request...",translate_code_3:"Crunching the figures...",translate_code_4:"Putting it all together...",translate_code_5:"Analyzing the results...",translate_code_6:"Working behind the scenes...",translate_code_7:"Sorting through the details...",translate_code_8:"Preparing your answer...",translate_code_9:"Almost ready...",translate_reasoning_0:"Thinking it through...",translate_reasoning_1:"Considering the options...",translate_reasoning_2:"Weighing the possibilities...",translate_reasoning_3:"Reflecting on this...",translate_reasoning_4:"Working it out...",translate_reasoning_5:"Putting thoughts together...",translate_reasoning_6:"Mulling it over...",translate_reasoning_7:"Finding the best approach...",translate_reasoning_8:"Organizing my thoughts...",translate_reasoning_9:"Almost there...",translate_running:"Running",translate_aborted:"Aborted",translate_input:"Input",translate_output:"Output",translate_calling:"Calling",translate_input_ready:"Input ready",translate_needs_approval:"Needs approval",translate_approved:"Approved",translate_responded:"Responded",translate_error:"Error",translate_approval_requested:"Approval requested",translate_approval_response:"Approval response",translate_waiting_for_approval:"Waiting for approval to execute this tool.",translate_tool_approved:"Approved.",translate_tool_response_received:"Response received.",translate_tokens:"tokens",translate_fresh:"Fresh",translate_cache_read:"Cache read",translate_cache_write:"Cache write",translate_n_percent_cached:"{{percent}}% cached",translate_text:"Text",translate_reasoning:"Reasoning",translate_read:"Read",translate_write:"Write",translate_total:"Total",translate_request:"Request",translate_response:"Response",translate_step_n:"Step {{number}}",translate_inspect_llm_requests:"Inspect LLM requests",translate_loading:"loading…",translate_no_llm_requests:"No LLM requests recorded for this message.",translate_unhandled_type:"Unhandled type:",translate_client_tool_title:"Complete this step to continue",translate_client_tool_loading:"Preparing a secure step...",translate_client_tool_failed:"This step could not be loaded",translate_client_tool_retry:"Try again",translate_client_tool_cancel:"Cancel"};var p_={en:i1,ar:x1};function y1(_,N,k){let $=(p_[_]??p_.en)?.[N]??p_.en?.[N]??N;if(!k)return $;return $.replace(/\{\{\s*(\w+)\s*\}\}/g,(Z,G)=>(G in k)?String(k[G]):Z)}function Y_(_){if(typeof _==="string"){let N=_.trim();if(!(N.startsWith("{")&&N.endsWith("}")||N.startsWith("[")&&N.endsWith("]")))return _;try{return Y_(JSON.parse(N))}catch{return _}}if(Array.isArray(_))return _.map((N)=>Y_(N));if(_!==null&&typeof _==="object"){let N={};for(let[k,L]of Object.entries(_))N[k]=Y_(L);return N}return _}function O1(_,N){if(Array.isArray(_)){let k=_;return{kind:"container",open:"[",close:"]",summary:d1(k.length,"item","items"),entries:k.map((L,$)=>({key:null,value:L,path:`${N}[${$}]`}))}}if(_!==null&&typeof _==="object"){let k=Object.entries(_);return{kind:"container",open:"{",close:"}",summary:d1(k.length,"property","properties"),entries:k.map(([L,$])=>({key:L,value:$,path:`${N}.${L}`}))}}return{kind:"primitive",text:D2(_),className:H2(_)}}function d1(_,N,k){return`${_} ${_===1?N:k}`}function D2(_){if(_===null||_===void 0)return"null";if(typeof _==="string")return JSON.stringify(_);if(typeof _==="number"||typeof _==="boolean")return String(_);return JSON.stringify(_)??"null"}function H2(_){if(_===null||_===void 0)return"jt-null";if(typeof _==="string")return"jt-string";if(typeof _==="number")return"jt-number";if(typeof _==="boolean")return"jt-boolean";return""}function m_(_){if(!_)return null;try{return JSON.parse(_)}catch{return _}}function u_(_){if(!_)return"";try{return JSON.stringify(JSON.parse(_),null,2)}catch{return _}}function Q_(_,N){if(_===void 0||typeof _==="string"||Array.isArray(_))return _;return _[N]??_.en??Object.values(_)[0]}var M1=[["year",31536000000],["month",2592000000],["week",604800000],["day",86400000],["hour",3600000],["minute",60000],["second",1000]];function A_(_,N,k=Date.now()){let L=Date.parse(_);if(Number.isNaN(L))return"";let $=L-k,[Z,G]=M1.find(([,X])=>Math.abs($)>=X)??M1[M1.length-1];return new Intl.RelativeTimeFormat(N,{numeric:"auto"}).format(Math.round($/G),Z)}function U1(_,N){let k=URL.createObjectURL(_),L=document.createElement("a");L.href=k,L.download=N,L.click(),URL.revokeObjectURL(k)}class J_{onUpdate;fullText="";displayedLength=0;animationFrameId=null;isDone=!1;static DRAIN_FRACTION=0.03;static MIN_CHARS_PER_FRAME=1;static DONE_DRAIN_FRACTION=0.1;constructor(_){this.onUpdate=_}seed(_){this.fullText=_,this.displayedLength=_.length,this.onUpdate(_)}update(_,N){if(this.fullText=_,this.isDone=N,this.displayedLength=Math.min(this.displayedLength,this.fullText.length),N&&this.displayedLength>=this.fullText.length){this.onUpdate(this.fullText),this.stopAnimation();return}if(!this.animationFrameId)this.scheduleFrame()}destroy(){this.stopAnimation()}scheduleFrame(){this.animationFrameId=requestAnimationFrame(()=>this.tick())}tick(){let _=this.fullText.length-this.displayedLength;if(_<=0){this.animationFrameId=null;return}let N=this.isDone?J_.DONE_DRAIN_FRACTION:J_.DRAIN_FRACTION,k=Math.max(J_.MIN_CHARS_PER_FRAME,Math.ceil(_*N));if(this.displayedLength=Math.min(this.fullText.length,this.displayedLength+k),this.onUpdate(this.fullText.substring(0,this.displayedLength)),this.displayedLength<this.fullText.length)this.scheduleFrame();else this.animationFrameId=null}stopAnimation(){if(this.animationFrameId)cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null}}function E_(_){if(_.input.total<=0)return null;return Math.round(_.input.cacheRead/_.input.total*100)}import{useEffect as w_,useLayoutEffect as a1,useMemo as B2,useRef as t}from"react";import{useChat as y2}from"@tanstack/ai-react";function t1(_){let{thread:N,api:k,patchUi:L}=_,$=t(!0),Z=t(!1),G=t(!1),X=t(!1),J=t(!1),W=t(new Set),Y=t(Promise.resolve()),U=B2(()=>X1({api:k,thread:{id:N.id,isRunning:N.isRunning},mode:_.mode,onHydrated:(y)=>{if(!$.current)return;L({messageMetadata:g_(y)})},setLoadingMessages:(y)=>{if($.current)L({isLoadingMessages:y})}}),[]),q=y2({threadId:N.id,persistence:!0,initialMessages:_.initialMessages,connection:U,onChunk:()=>{if(!$.current)return;G.current=!0},onError:()=>{if(!$.current)return;if(G.current)_.onTurnFinished();else _.onSendFailed()}}),D=t(q);D.current=q;let b=t(q.isLoading);b.current=q.isLoading;async function M(y,g){let n=g({toolCallId:y.id,toolName:y.name,input:y.input},{threadId:N.id});if(n===null||n===void 0)return;let m=await Promise.resolve(n);if(m===null||m===void 0)return;if(!$.current)return;await D.current.addToolResult({toolCallId:y.id,tool:y.name,output:m})}function R(){let y=S_(D.current.messages),g=_.configRef.current.hooks?.onToolCall;if(!g)return y.length>0;for(let n of y){if(n.state!=="input-complete")continue;if(W.current.has(n.id))continue;W.current.add(n.id),M(n,g)}return y.length>0}async function Q(y){if(!$.current||y!==N.id)return;await V1({api:k,threadId:y,isStale:()=>!$.current,isStreaming:()=>b.current,absorbMetadata:(g)=>L({messageMetadata:g}),setMessages:(g)=>{D.current.setMessages(g)}})}function V(y){return Y.current=Y.current.then(()=>Q(y)),Y.current}async function z(){if(X.current){X.current=!1;return}if(Z.current&&R())return;await V(N.id)}async function T(y,g){_.setRunning(N.id,!0),Z.current=!0,G.current=!1;let n={id:O_(),role:"user",parts:[{type:"text",content:y}]};if(g.length)L((m)=>({messageMetadata:new Map(m.messageMetadata).set(n.id,{attachments:g})}));await D.current.append(n)}async function c(){if(!b.current)return;let{aborted:y}=await k.abortStream(N.id).catch(()=>({aborted:!1}));if(!$.current)return;if(y)X.current=!0,_.setRunning(N.id,!1);D.current.stop()}function p(y,g,n){return D.current.addToolResult({toolCallId:y,tool:g,output:n}).catch((m)=>{throw V(N.id),m})}function B(y){if(b.current)return;if(y.isRunning){_.remount(y);return}V(y.id)}w_(()=>{return $.current=!0,()=>{$.current=!1}},[]);let u=t(void 0);return u.current={threadId:N.id,send:T,abort:c,addToolResult:p,reattach:B,refreshMessages:(y)=>{V(y)}},a1(()=>{_.sessionRef.current=u.current}),a1(()=>{return()=>{if(_.sessionRef.current===u.current)_.sessionRef.current=void 0}},[]),w_(()=>{if(!_.pendingSendRef.current.length)return;let y=setTimeout(()=>{let g=_.pendingSendRef.current;_.pendingSendRef.current=[],(async()=>{for(let{prompt:n,attachments:m}of g)await T(n,m)})()});return()=>clearTimeout(y)},[]),w_(()=>{L({messages:q.messages})},[q.messages]),w_(()=>{L({hasPendingToolCalls:!q.isLoading&&S_(q.messages).length>0})},[q.messages,q.isLoading]),w_(()=>{if(L({isAgentWorking:q.isLoading}),q.isLoading){J.current=!0;return}if(!J.current)return;J.current=!1,_.onTurnFinished(),z()},[q.isLoading]),null}import{createContext as O2,useContext as M2}from"react";var A1=O2(void 0);function H(){let _=M2(A1);if(!_)throw Error("useCortex must be used inside <CortexChatWidget>");return _}function F(..._){return _.filter(Boolean).join(" ")}import{forwardRef as U2,useEffect as A2,useImperativeHandle as E2,useRef as w1,useState as e1}from"react";import{jsx as e,jsxs as E1}from"react/jsx-runtime";function s1(){let{queue:_,t:N}=H();if(!_.items.length)return null;return e("div",{className:"cortex-attachment-queue",children:_.items.map((k)=>E1("div",{className:F("cortex-attachment-chip",k.status==="error"&&"cortex-attachment-chip--error"),title:k.status==="error"?N("translate_attachment_rejected"):"",children:[k.status==="uploading"||k.status==="deleting"?E1("svg",{className:"cortex-attachment-chip__spinner",viewBox:"0 0 16 16",fill:"none",children:[e("circle",{cx:"8",cy:"8",r:"6",stroke:"currentColor",strokeWidth:"2",className:"cortex-attachment-chip__spinner-track"}),e("path",{d:"M14 8a6 6 0 0 0-6-6",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]}):E1("svg",{viewBox:"0 0 16 16",className:"cortex-attachment-chip__icon",fill:"none",children:[e("path",{d:"M4 1.5h5.172a2 2 0 0 1 1.414.586l2.328 2.328a2 2 0 0 1 .586 1.414V12.5a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-9a2 2 0 0 1 2-2Z",stroke:"currentColor",strokeWidth:"1.25"}),e("path",{d:"M9.5 1.5v2a2 2 0 0 0 2 2h2",stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round"})]}),e("span",{className:"cortex-attachment-chip__name",children:k.filename}),e("button",{type:"button",onClick:()=>_.remove(k.localId),className:"cortex-attachment-chip__remove",disabled:k.status==="deleting","aria-label":N("translate_remove_attachment"),children:e("svg",{viewBox:"0 0 16 16",fill:"none",children:e("path",{d:"M4.5 4.5l7 7m0-7l-7 7",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})})})]},k.localId))})}import{jsx as x,jsxs as P_,Fragment as P2}from"react/jsx-runtime";var w2=J1.join(","),l_=U2(function(N,k){let{t:L,queue:$,isAgentWorking:Z,send:G,abort:X,attachmentsEnabled:J}=H(),[W,Y]=e1(""),[U,q]=e1(!1),D=w1(null),b=w1(null);E2(k,()=>({focusInput:()=>D.current?.focus()}));let M=w1(Z);A2(()=>{if(M.current&&!Z)D.current?.focus();M.current=Z},[Z]);let R=!$.busy&&(Boolean(W.trim())||$.hasReady);function Q(){if(Z||!R)return;let B="translate_attachment_caption",u=L(B),y=u!==B?u:"Please take a look at the attached files.",g=W.trim()||y,n=$.consumeReady();Y(""),G(g,n.map((m)=>m.summary))}function V(B){if(B.key==="Enter"&&!B.shiftKey)B.preventDefault(),Q()}function z(B){if(B.preventDefault(),J)q(!0)}function T(B){if(!B.currentTarget.contains(B.relatedTarget))q(!1)}function c(B){if(B.preventDefault(),q(!1),J)$.accept([...B.dataTransfer.files])}function p(B){let u=B.clipboardData.files;if(!J||!u.length)return;B.preventDefault(),$.accept([...u])}return P_("div",{className:"cortex-widget__input-area",onDragOver:z,onDragLeave:T,onDrop:c,children:[x(s1,{}),P_("div",{className:F("cortex-widget__input-box",Z&&"cortex-widget__input-box--disabled",!Z&&"cortex-widget__input-box--enabled",U&&"cortex-widget__input-box--dragging"),children:[x("textarea",{ref:D,onKeyDown:V,onPaste:p,value:W,onChange:(B)=>Y(B.target.value),placeholder:U?L("translate_drop_files_here"):Z?"":L("translate_type_a_message"),disabled:Z,rows:1,className:F("cortex-widget__textarea",Z&&"cortex-widget__textarea--disabled")}),Z?P_("button",{onClick:()=>void X(),className:"cortex-stop-btn",children:[x("span",{className:"cortex-stop-btn__ring"}),x("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",className:"cortex-stop-btn__icon",children:x("rect",{x:"1",y:"1",width:"10",height:"10",rx:"2.5",fill:"currentColor"})})]}):P_("div",{className:"cortex-widget__input-actions",children:[J?P_(P2,{children:[x("button",{type:"button",onClick:()=>b.current?.click(),className:"cortex-widget__attach-btn","aria-label":L("translate_attach_files"),children:x("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:x("path",{d:"M10.5 5.5 6.2 9.8a1.4 1.4 0 0 0 2 2l4.6-4.6a2.8 2.8 0 0 0-4-4L4.2 7.8a4.2 4.2 0 0 0 6 6l4-4",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"})})}),x("input",{ref:b,type:"file",multiple:!0,accept:w2,onChange:(B)=>{$.accept([...B.target.files??[]]),B.target.value=""},className:"cortex-widget__file-input"})]}):null,x("button",{onClick:Q,className:F("cortex-widget__send-btn",!R&&"cortex-widget__send-btn--empty",R&&"cortex-widget__send-btn--ready"),disabled:!R,children:x("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",className:"cortex-widget__send-icon",children:x("path",{d:"M3 8h10M9 4l4 4-4 4",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})})]})]})]})});import{jsx as w,jsxs as d,Fragment as b2}from"react/jsx-runtime";var o_="M13.5 7.6c0 2.4-2.5 4.4-5.5 4.4-.6 0-1.2-.08-1.7-.23L3 13l.8-2.3C3 9.8 2.5 8.7 2.5 7.6 2.5 5.2 5 3.2 8 3.2s5.5 2 5.5 4.4Z";function _0(_){let{config:N,t:k,threads:L,selectedThread:$,deleteThread:Z}=H(),G=N.locale??"en";return d("div",{className:_.className,children:[d("div",{className:"cortex-widget__threads-header",children:[w("button",{type:"button",onClick:()=>_.onBackRequested(),"aria-label":k("translate_back"),className:"cortex-widget__back-btn",children:w("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none","aria-hidden":"true",className:"cortex-widget__back-icon",children:w("path",{d:"M10 3L5 8l5 5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),d("div",{children:[w("h2",{className:"cortex-widget__threads-title",children:k("translate_history")}),w("p",{className:"cortex-widget__threads-count",children:k(L?.length===1?"translate_one_conversation":"translate_n_conversations",{count:L?.length??0})})]}),d("button",{onClick:()=>_.onNewChatRequested(),className:"cortex-widget__new-chat-btn",children:[w("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"none",children:w("path",{d:"M8 3v10M3 8h10",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})}),k("translate_new")]})]}),w("div",{className:"cortex-widget__threads-list",children:L===void 0?[1,2,3,4].map((X)=>d("div",{className:"cortex-widget__thread-skeleton",children:[w("div",{className:"cortex-skeleton cortex-widget__thread-skeleton-icon"}),w("div",{className:"cortex-widget__thread-skeleton-lines",children:w("div",{className:"cortex-skeleton cortex-widget__thread-skeleton-line",style:{width:`${40+X*12}%`}})})]},X)):d(b2,{children:[L.map((X)=>{let J=X.id===$?.id,W=A_(X.updatedAt,G);return d("button",{onClick:()=>_.onThreadSelected(X),className:F("cortex-widget__thread-item",J&&"cortex-widget__thread-item--active"),children:[w("div",{className:F("cortex-widget__thread-icon",J&&"cortex-widget__thread-icon--active"),children:w("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",children:w("path",{d:o_,stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"})})}),d("div",{className:"cortex-widget__thread-info",children:[d("div",{className:"cortex-widget__thread-title-row",children:[w("p",{className:F("cortex-widget__thread-title",J&&"cortex-widget__thread-title--active"),children:X.title??k("translate_untitled")}),X.isRunning&&d("span",{className:F("cortex-widget__thread-running",J&&"cortex-widget__thread-running--active"),children:[w("span",{className:"cortex-widget__thread-running-dot"}),k("translate_running")]})]}),W&&w("p",{className:"cortex-widget__thread-time",children:W})]}),w("span",{role:"button",tabIndex:0,onClick:(Y)=>{Y.stopPropagation(),Z(X.id)},onKeyDown:(Y)=>{if(Y.key!=="Enter"&&Y.key!==" ")return;Y.preventDefault(),Y.stopPropagation(),Z(X.id)},className:F("cortex-widget__thread-delete",J&&"cortex-widget__thread-delete--active"),children:w("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"none",children:w("path",{d:"M4 4l8 8M12 4l-8 8",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round"})})}),w("svg",{className:F("cortex-widget__thread-arrow",J&&"cortex-widget__thread-arrow--active"),width:"10",height:"10",viewBox:"0 0 16 16",fill:"none",children:w("path",{d:"M6 4l4 4-4 4",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]},X.id)}),!L.length&&d("div",{className:"cortex-widget__threads-empty",children:[w("div",{className:"cortex-widget__threads-empty-icon",children:w("svg",{width:"18",height:"18",viewBox:"0 0 16 16",fill:"none",className:"cortex-widget__threads-empty-svg",children:w("path",{d:o_,stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"})})}),w("p",{className:"cortex-widget__threads-empty-title",children:k("translate_no_threads_yet")}),w("p",{className:"cortex-widget__threads-empty-subtitle",children:k("translate_start_a_new_conversation")}),w("button",{onClick:()=>_.onNewChatRequested(),className:"cortex-widget__new-chat-btn cortex-widget__new-chat-btn--empty-state",children:k("translate_new_chat")})]})]})})]})}import{jsx as s,jsxs as N0}from"react/jsx-runtime";function k0(_){let{config:N,t:k,threads:L,send:$}=H(),Z=N.locale??"en",G=Q_(N.suggestions,Z);return N0("div",{className:"cortex-widget__landing",children:[s("div",{className:"cortex-widget__landing-icon",children:s("svg",{width:"18",height:"18",viewBox:"0 0 16 16",fill:"none",children:s("path",{d:o_,stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"})})}),s("p",{className:"cortex-widget__landing-greeting",children:Q_(N.greeting,Z)??k("translate_greeting")}),!!G?.length&&s("div",{className:"cortex-widget__landing-chips",children:G.map((X,J)=>s("button",{type:"button",onClick:()=>void $(X),className:"cortex-widget__landing-chip",children:X},J))}),s(l_,{}),!!L?.length&&s("div",{className:"cortex-widget__landing-recent",children:L.slice(0,2).map((X)=>{let J=A_(X.updatedAt,Z);return N0("button",{type:"button",onClick:()=>_.onThreadSelected(X),className:"cortex-widget__landing-recent-item",children:[s("p",{className:"cortex-widget__landing-recent-title",children:X.title??k("translate_untitled")}),J&&s("p",{className:"cortex-widget__landing-recent-time",children:J})]},X.id)})})]})}import{useEffect as x_,useRef as i_,useState as i2}from"react";import{jsx as j_,jsxs as L0}from"react/jsx-runtime";function $0(){let{t:_}=H();return L0("div",{className:"cortex-aborted-flag",children:[j_("span",{className:"cortex-aborted-flag__line"}),L0("span",{className:"cortex-aborted-flag__label",children:[j_("svg",{className:"cortex-aborted-flag__icon",width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:j_("path",{d:"M6 1.5v5M6 8.75v.5",stroke:"currentColor",strokeWidth:"1.4",strokeLinecap:"round"})}),_("translate_aborted")]}),j_("span",{className:"cortex-aborted-flag__line"})]})}import{jsx as z_,jsxs as Z0}from"react/jsx-runtime";function J0(_){let{api:N,t:k}=H();async function L($){let{blob:Z,name:G}=await N.downloadAttachment($);U1(Z,G)}return z_("div",{className:"cortex-message-attachments",children:_.attachments.map(($)=>Z0("button",{type:"button",onClick:()=>void L($.id),className:"cortex-message-attachment","aria-label":`${k("translate_download")}: ${$.filename}`,children:[Z0("svg",{viewBox:"0 0 16 16",className:"cortex-message-attachment__icon",fill:"none",children:[z_("path",{d:"M4 1.5h5.172a2 2 0 0 1 1.414.586l2.328 2.328a2 2 0 0 1 .586 1.414V12.5a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-9a2 2 0 0 1 2-2Z",stroke:"currentColor",strokeWidth:"1.25"}),z_("path",{d:"M9.5 1.5v2a2 2 0 0 0 2 2h2",stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round"})]}),z_("span",{className:"cortex-message-attachment__name",children:$.filename}),z_("svg",{viewBox:"0 0 16 16",className:"cortex-message-attachment__dl-icon",fill:"none",children:z_("path",{d:"M8 3v7m0 0L5.5 7.5M8 10l2.5-2.5M3 13h10",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]},$.id))})}import{useRef as S2,useState as b_}from"react";import{useRef as R2,useState as v2}from"react";import{jsx as F_,jsxs as I2}from"react/jsx-runtime";function N_({value:_,className:N}){let[k,L]=v2(!1),$=R2(null);async function Z(G){G.stopPropagation(),G.preventDefault();try{if(await navigator.clipboard.writeText(_),L(!0),$.current)clearTimeout($.current);$.current=setTimeout(()=>L(!1),1500)}catch{}}return F_("span",{className:F("cortex-copy-btn",N),children:F_("button",{className:F("cortex-copy-btn__button",k&&"cortex-copy-btn__button--copied"),onClick:(G)=>void Z(G),"aria-label":k?"Copied":"Copy to clipboard",type:"button",children:k?F_("svg",{className:"cortex-copy-btn__icon cortex-copy-btn__icon--check",width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",children:F_("path",{d:"M5 13l4 4L19 7",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"})}):I2("svg",{className:"cortex-copy-btn__icon",width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",children:[F_("rect",{x:"9",y:"9",width:"12",height:"12",rx:"2",stroke:"currentColor",strokeWidth:"2"}),F_("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]})})})}import{useMemo as c2,useState as n2}from"react";import{jsx as r,jsxs as G_,Fragment as r_}from"react/jsx-runtime";function X_({data:_,expandDepth:N=1,className:k}){let L=c2(()=>Y_(_),[_]),[$,Z]=n2({});function G(J,W){return $[J]??W>=N}function X(J,W){Z((Y)=>({...Y,[J]:!G(J,W)}))}return r("div",{className:F("cortex-json-tree",k),children:r(G0,{value:L,path:"$",depth:0,isCollapsed:G,toggle:X})})}function G0({value:_,path:N,depth:k,isCollapsed:L,toggle:$}){let Z=O1(_,N);if(Z.kind==="primitive")return r("span",{className:Z.className,children:Z.text});if(Z.entries.length===0)return G_("span",{className:"jt-bracket",children:[Z.open,Z.close]});let G=L(N,k);function X(J){$(N,k),J.stopPropagation()}return G_(r_,{children:[G_("span",{className:"jt-toggle",onClick:X,role:"button",children:[r("span",{className:F("jt-arrow",G&&"jt-arrow--collapsed"),children:"▾"}),r("span",{className:"jt-bracket",children:Z.open})]}),G?G_(r_,{children:[r("span",{className:"jt-collapsed-hint",onClick:X,role:"button",children:Z.summary}),r("span",{className:"jt-bracket",children:Z.close})]}):G_(r_,{children:[r("div",{className:"jt-indent",children:Z.entries.map((J,W)=>G_("div",{className:"jt-line",children:[J.key!==null&&G_(r_,{children:[r("span",{className:"jt-key",children:`"${J.key}"`}),r("span",{className:"jt-colon",children:": "})]}),r(G0,{value:J.value,path:J.path,depth:k+1,isCollapsed:L,toggle:$}),W<Z.entries.length-1&&r("span",{className:"jt-comma",children:","})]},J.path))}),r("span",{className:"jt-bracket",children:Z.close})]})]})}function v(_){return _.toLocaleString("en-US")}import{jsx as q_,jsxs as D_}from"react/jsx-runtime";function X0({usage:_}){let{t:N}=H();return D_("div",{className:"cortex-llm-inspector__usage-rows",children:[D_("div",{className:"cortex-llm-inspector__usage-row",children:[q_("span",{className:"cortex-llm-inspector__usage-lbl",children:N("translate_input")}),q_("span",{className:"cortex-llm-inspector__usage-val",children:v(_.input.total)}),D_("span",{className:"cortex-llm-inspector__usage-detail",children:[N("translate_fresh")," ",v(_.input.noCache)," · ",N("translate_read")," ",v(_.input.cacheRead)," · ",N("translate_write")," ",v(_.input.cacheWrite)]})]}),D_("div",{className:"cortex-llm-inspector__usage-row",children:[q_("span",{className:"cortex-llm-inspector__usage-lbl",children:N("translate_output")}),q_("span",{className:"cortex-llm-inspector__usage-val",children:v(_.output.total)}),D_("span",{className:"cortex-llm-inspector__usage-detail",children:[N("translate_text")," ",v(_.output.text)," · ",N("translate_reasoning")," ",v(_.output.reasoning)]})]}),D_("div",{className:"cortex-llm-inspector__usage-row cortex-llm-inspector__usage-row--total",children:[q_("span",{className:"cortex-llm-inspector__usage-lbl",children:N("translate_total")}),q_("span",{className:"cortex-llm-inspector__usage-val",children:v(_.total)})]})]})}import{jsx as P1,jsxs as h_}from"react/jsx-runtime";function V0({usage:_}){let N=E_(_);return P1("span",{children:h_("span",{className:"cortex-llm-inspector__step-metrics",children:[h_("span",{className:"cortex-llm-inspector__metric",children:[P1("span",{className:"cortex-llm-inspector__dot cortex-llm-inspector__dot--input"}),v(_.input.total)]}),h_("span",{className:"cortex-llm-inspector__metric",children:[P1("span",{className:"cortex-llm-inspector__dot cortex-llm-inspector__dot--output"}),v(_.output.total)]}),N!==null?h_("span",{className:"cortex-llm-inspector__cache-pct",children:[N,"%"]}):null]})})}import{jsx as I,jsxs as k_}from"react/jsx-runtime";function W0({messageId:_}){let{t:N,api:k}=H(),[L,$]=b_(!1),[Z,G]=b_(!1),[X,J]=b_([]),[W,Y]=b_(null),[U,q]=b_({}),D=S2(!1);async function b(){if(!D.current){G(!0);try{J(await k.listLlmRequests(_))}finally{G(!1),D.current=!0}}$((V)=>!V)}function M(V){Y((z)=>z===V?null:V)}function R(V){return U[V]??"prompt"}function Q(V,z){q((T)=>({...T,[V]:z}))}return k_("div",{className:F("cortex-llm-inspector",L&&"cortex-llm-inspector--open"),children:[k_("button",{className:"cortex-llm-inspector__trigger",onClick:()=>void b(),children:[I("svg",{className:"cortex-llm-inspector__icon",width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",children:I("path",{d:"M6 2a4 4 0 1 0 0 8 4 4 0 0 0 0-8ZM0 6a6 6 0 1 1 10.89 3.477l4.817 4.816a1 1 0 0 1-1.414 1.414l-4.816-4.816A6 6 0 0 1 0 6Z",fill:"currentColor"})}),I("span",{children:N("translate_inspect_llm_requests")}),Z?I("span",{className:"cortex-llm-inspector__loading",children:N("translate_loading")}):X.length>0?I("span",{className:"cortex-llm-inspector__badge",children:X.length}):null,I("svg",{className:"cortex-llm-inspector__chevron",width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:I("path",{d:"M3 4.5L6 7.5L9 4.5",stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round"})})]}),I("div",{className:"cortex-llm-inspector__panel-wrapper",children:I("div",{className:"cortex-llm-inspector__panel-inner",children:k_("div",{className:"cortex-llm-inspector__panel",children:[X.length===0&&!Z?I("div",{className:"cortex-llm-inspector__empty",children:N("translate_no_llm_requests")}):null,X.map((V,z)=>k_("div",{className:F("cortex-llm-inspector__step",W===V.id&&"cortex-llm-inspector__step--expanded"),children:[k_("button",{className:"cortex-llm-inspector__step-header",onClick:()=>M(V.id),children:[I("span",{className:"cortex-llm-inspector__step-label",children:N("translate_step_n",{number:z+1})}),V.tokenUsage?I(V0,{usage:V.tokenUsage}):null,I("svg",{className:"cortex-llm-inspector__step-chevron",width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",children:I("path",{d:"M3 4.5L6 7.5L9 4.5",stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round"})})]}),I("div",{className:"cortex-llm-inspector__step-body-wrapper",children:I("div",{className:"cortex-llm-inspector__step-body-inner",children:k_("div",{className:"cortex-llm-inspector__step-body",children:[V.tokenUsage?I(X0,{usage:V.tokenUsage}):null,k_("div",{className:"cortex-llm-inspector__tabs",children:[I("button",{className:F("cortex-llm-inspector__tab",R(V.id)==="prompt"&&"cortex-llm-inspector__tab--active"),onClick:()=>Q(V.id,"prompt"),children:N("translate_request")}),I("button",{className:F("cortex-llm-inspector__tab",R(V.id)==="response"&&"cortex-llm-inspector__tab--active"),onClick:()=>Q(V.id,"response"),children:N("translate_response")})]}),k_("div",{className:"cortex-llm-inspector__json-pane",children:[I(N_,{className:"cortex-llm-inspector__json-copy",value:R(V.id)==="prompt"?u_(V.prompt):u_(V.output)}),R(V.id)==="prompt"?I(X_,{data:m_(V.prompt),expandDepth:2}):I(X_,{data:m_(V.output),expandDepth:2})]})]})})})]},V.id))]})})})]})}import{useEffect as C2,useRef as g2,useState as K0}from"react";import{jsx as R_,jsxs as Y0}from"react/jsx-runtime";function H_({labels:_,className:N}){let{t:k}=H(),[L,$]=K0(0),[Z,G]=K0("idle"),X=g2(_.length);return X.current=_.length,C2(()=>{let J,W;function Y(){J=setTimeout(()=>{G("exiting"),J=setTimeout(()=>{$((U)=>(U+1)%X.current),G("enter-start"),W=requestAnimationFrame(()=>{G("entering"),J=setTimeout(()=>{G("idle"),Y()},300)})},300)},2000)}return Y(),()=>{if(J)clearTimeout(J);if(W)cancelAnimationFrame(W)}},[]),Y0("div",{className:F("cortex-subtle-activity",N),children:[Y0("div",{className:"cortex-subtle-activity__dots",children:[R_("span",{className:"cortex-subtle-activity__dot"}),R_("span",{className:"cortex-subtle-activity__dot cortex-subtle-activity__dot--d1"}),R_("span",{className:"cortex-subtle-activity__dot cortex-subtle-activity__dot--d2"})]}),R_("div",{className:"cortex-subtle-activity__label-mask",children:R_("span",{className:F("cortex-subtle-activity__label",`cortex-subtle-activity__label--${Z}`),children:k(_[L])})})]})}import{jsx as Q0}from"react/jsx-runtime";var f2=Z_("reasoning");function z0(){return Q0("div",{className:"cortex-reasoning-animated",children:Q0(H_,{labels:f2})})}import{jsx as i,jsxs as v_}from"react/jsx-runtime";function F0(_){let{reasoningPart:N,streaming:k=!1}=_,{t:L}=H();return v_("details",{className:"cortex-reasoning-details",children:[v_("summary",{className:"cortex-reasoning-details__summary",children:[v_("div",{className:"cortex-reasoning-details__header",children:[i("span",{className:"cortex-reasoning-details__icon",children:v_("svg",{width:"14",height:"14",viewBox:"0 0 20 20",fill:"none","aria-hidden":"true",children:[i("path",{d:"M10 2C6.686 2 4 4.686 4 8c0 1.655.672 3.154 1.757 4.243.362.363.576.858.576 1.371V14.5a1 1 0 0 0 1 1h5.334a1 1 0 0 0 1-1v-.886c0-.513.214-1.008.576-1.371A5.978 5.978 0 0 0 16 8c0-3.314-2.686-6-6-6Z",stroke:"currentColor",strokeWidth:"1.4",strokeLinecap:"round",strokeLinejoin:"round"}),i("path",{d:"M7.5 17.5h5M8.5 8a2 2 0 0 1 2-2",stroke:"currentColor",strokeWidth:"1.4",strokeLinecap:"round",strokeLinejoin:"round"})]})}),i("div",{className:"cortex-reasoning-details__title-group",children:v_("div",{className:"cortex-reasoning-details__title-row",children:[i("div",{className:"cortex-reasoning-details__title",children:L("translate_reasoning")}),i("span",{className:F("cortex-reasoning-details__badge",k?"cortex-reasoning-details__badge--streaming":"cortex-reasoning-details__badge--done"),children:k?"Streaming":"Done"})]})})]}),i("span",{className:"cortex-reasoning-details__chevron","aria-hidden":"true",children:i("svg",{width:"14",height:"14",viewBox:"0 0 20 20",fill:"none",children:i("path",{d:"m5.75 8.25 4.25 4.25 4.25-4.25",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})})]}),i("div",{className:"cortex-reasoning-details__body",children:i("div",{className:"cortex-reasoning-details__content",children:i("pre",{className:"cortex-reasoning-details__pre",children:N.content.trim()?N.content:"No reasoning provided."})})})]})}import{useEffect as q0,useRef as b1,useState as T2}from"react";import{jsx as D0}from"react/jsx-runtime";function H0(_){let{role:N,textPart:k,streaming:L=!1}=_,$=N==="assistant"&&L?"":k.content,[Z,G]=T2($),X=b1($),J=b1(null),W=b1(!0);return q0(()=>{function Y(U){X.current=U,G(U)}if(N!=="assistant"||!L){J.current?.destroy(),J.current=null,Y(k.content),W.current=!1;return}if(!J.current)J.current=new J_(Y),J.current.seed(X.current);if(W.current){W.current=!1,J.current.seed(k.content);return}J.current.update(k.content,!1)},[N,L,k]),q0(()=>()=>{J.current?.destroy(),J.current=null},[]),D0("div",{className:F("cortex-text-part",N==="assistant"&&"cortex-text-part--assistant",N==="user"&&"cortex-text-part--user"),children:D0("div",{className:F("cortex-text-bubble",N==="assistant"&&"cortex-text-bubble--assistant",N==="user"&&"cortex-text-bubble--user"),dangerouslySetInnerHTML:{__html:H1(Z)}})})}import{jsx as l,jsxs as L_}from"react/jsx-runtime";function B0({toolCallPart:_}){let{t:N}=H(),{state:k,approval:L}=_,$=_.output,Z=k1(_);function G(){if(k==="complete")return L_("div",{className:"dbg-tool__section dbg-tool__section--success",children:[L_("div",{className:"dbg-tool__section-bar",children:[l("span",{className:"dbg-tool__section-label dbg-tool__section-label--success",children:N("translate_output")}),l("span",{className:"dbg-tool__section-lang",children:"json"}),l(N_,{value:Z})]}),l("div",{dir:"ltr",className:"dbg-tool__tree",children:l(X_,{data:$,expandDepth:2})})]});if(k==="error")return L_("div",{className:"dbg-tool__section dbg-tool__section--error",children:[L_("div",{className:"dbg-tool__section-bar",children:[l("span",{className:"dbg-tool__section-label dbg-tool__section-label--error",children:N("translate_error")}),l(N_,{value:Z})]}),l("pre",{dir:"ltr",className:"dbg-tool__error-pre",children:Z})]});if(k==="approval-requested")return L_("div",{className:"dbg-tool__section dbg-tool__section--approval",children:[L_("div",{className:"dbg-tool__section-bar",children:[l("span",{className:"dbg-tool__section-label dbg-tool__section-label--approval",children:N("translate_approval_requested")}),l("span",{className:"dbg-tool__section-lang",children:L?.id})]}),l("div",{className:"dbg-tool__message dbg-tool__message--approval",children:N("translate_waiting_for_approval")})]});if(k==="approval-responded")return L_("div",{className:"dbg-tool__section dbg-tool__section--approval",children:[L_("div",{className:"dbg-tool__section-bar",children:[l("span",{className:"dbg-tool__section-label dbg-tool__section-label--approval",children:N("translate_approval_response")}),l("span",{className:"dbg-tool__section-lang",children:L?.id})]}),l("div",{className:"dbg-tool__message dbg-tool__message--approval",children:N(L?.approved?"translate_tool_approved":"translate_tool_response_received")})]});return null}return l("div",{children:G()})}import{jsx as y0,jsxs as p2}from"react/jsx-runtime";function O0({toolCallPart:_}){let{t:N}=H(),k=N1(_);return y0("span",{children:p2("span",{className:F("dbg-tool__state",k.modifier&&`dbg-tool__state--${k.modifier}`),children:[k.pulse&&y0("span",{className:F("dbg-tool__pulse",k.pulse==="violet"&&"dbg-tool__pulse--violet")}),N(k.labelKey)]})})}import{jsx as f,jsxs as __}from"react/jsx-runtime";function M0({toolCallPart:_}){let{t:N}=H(),{codeSnippets:k,remainingInput:L,remainingInputText:$}=L1(_.input);return __("details",{className:"dbg-tool","data-state":_.state,children:[f("summary",{className:"dbg-tool__summary",children:__("div",{className:"dbg-tool__header",children:[__("div",{className:"dbg-tool__meta",children:[f("div",{className:"dbg-tool__title-row",children:f("span",{className:"dbg-tool__name",title:_.name,children:_.name})}),f("div",{className:"dbg-tool__id-row",children:f("span",{className:"dbg-tool__id",children:_.id})})]}),__("div",{className:"dbg-tool__actions",children:[f(O0,{toolCallPart:_}),f("svg",{className:"dbg-tool__chevron",width:"14",height:"14",viewBox:"0 0 20 20",fill:"none",children:f("path",{d:"m5.75 8.25 4.25 4.25 4.25-4.25",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})]})}),__("div",{className:"dbg-tool__body",children:[k.map((Z)=>__("div",{className:"dbg-tool__section",children:[__("div",{className:"dbg-tool__section-bar",children:[f("span",{className:"dbg-tool__section-label",children:Z.key}),f("span",{className:"dbg-tool__section-lang",children:Z.lang}),f(N_,{value:Z.value})]}),f("pre",{dir:"ltr",className:"dbg-tool__pre",children:f("code",{className:"hljs",dangerouslySetInnerHTML:{__html:B1(Z.value,Z.lang)}})})]},Z.key)),!!L&&__("div",{className:"dbg-tool__section",children:[__("div",{className:"dbg-tool__section-bar",children:[f("span",{className:"dbg-tool__section-label",children:N("translate_input")}),f("span",{className:"dbg-tool__section-lang",children:"json"}),f(N_,{value:$})]}),f("div",{dir:"ltr",className:"dbg-tool__tree",children:f(X_,{data:L,expandDepth:2})})]}),f(B0,{toolCallPart:_})]})]})}import{useEffect as A0,useRef as R1,useState as U0}from"react";import{jsx as S,jsxs as I_}from"react/jsx-runtime";function E0({message:_,toolCallPart:N}){let{config:k,addToolResult:L,isAgentWorking:$}=H(),Z=k.toolComponents?.[N.name];if(Z)return S("div",{className:"cortex-tool-call-animated",children:S(Z,{toolCallPart:N,message:_,setOutput:(G)=>void L(N.id,N.name,G)})});if(N.state==="input-complete"&&!$)return S("div",{className:"cortex-tool-call-animated",children:S(m2,{toolCallPart:N})});return S("div",{className:"cortex-tool-call-animated",children:S(w0,{toolCallPart:N})})}function m2({toolCallPart:_}){let{api:N,t:k,addToolResult:L,selectedThread:$,config:Z}=H(),G=$?.id,[X,J]=U0({phase:"initiating"}),[W]=U0(Z.trustSameOriginEmbeds),Y=R1(void 0),U=R1({api:N,addToolResult:L,toolName:_.name});if(U.current={api:N,addToolResult:L,toolName:_.name},A0(()=>{if(!G)return;let D=F1({initiate:()=>U.current.api.initiateToolCall(G,_.id),onState:J,submit:(M)=>U.current.addToolResult(_.id,U.current.toolName,M)});Y.current=D,D.start();let b=(M)=>D.handleMessage(M);return window.addEventListener("message",b),()=>{if(window.removeEventListener("message",b),D.dispose(),Y.current===D)Y.current=void 0}},[_.id,G]),!G||X.phase==="unavailable"||X.phase==="settling")return S(w0,{toolCallPart:_});let q=I_("div",{className:"cortex-client-tool-embed",children:[I_("div",{className:"cortex-client-tool-embed__bar",children:[S("span",{children:k("translate_client_tool_title")}),S("button",{type:"button",className:"cortex-client-tool-embed__cancel",onClick:()=>Y.current?.cancel(),children:k("translate_client_tool_cancel")})]}),X.phase==="embedded"?S("iframe",{className:"cortex-client-tool-embed__frame",src:X.embedUrl,sandbox:Y1(X.embedUrl,window.location.origin,W),title:k("translate_client_tool_title"),ref:(D)=>Y.current?.setSource(D?.contentWindow),onLoad:(D)=>{if(!Q1(X.embedUrl,window.location.origin,W)&&z1(D.currentTarget,window.location.origin))Y.current?.terminate()}}):X.phase==="error"?I_("div",{className:"cortex-client-tool-embed__status",children:[S("span",{children:k("translate_client_tool_failed")}),S("button",{type:"button",className:"cortex-client-tool-embed__retry",onClick:()=>void Y.current?.start(),children:k("translate_client_tool_retry")})]}):S("div",{className:"cortex-client-tool-embed__status",children:k("translate_client_tool_loading")})]});return X.phase==="embedded"&&X.surface==="modal"?S(u2,{label:k("translate_client_tool_title"),onCancel:()=>Y.current?.cancel(),children:q}):q}function u2({label:_,onCancel:N,children:k}){let L=R1(null);return A0(()=>{let $=L.current;return $?.showModal(),()=>$?.close()},[]),S("dialog",{ref:L,className:"cortex-client-tool-embed-dialog","aria-label":_,onCancel:($)=>{$.preventDefault(),N()},children:k})}function w0({toolCallPart:_}){let{t:N}=H(),{state:k,active:L,titleKey:$}=$1(_);return I_("div",{className:"cortex-tool-pill",children:[I_("span",{className:"cortex-tool-pill__icon",children:[S("span",{className:F("cortex-tool-pill__spinner",L&&"cortex-tool-pill__spinner--visible")}),S("svg",{className:F("cortex-tool-pill__svg","cortex-tool-pill__svg--check",k==="complete"&&"cortex-tool-pill__svg--visible"),viewBox:"0 0 20 20",fill:"none",children:S("path",{d:"M5.5 10.5 L8.5 13.5 L14.5 7",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),S("svg",{className:F("cortex-tool-pill__svg","cortex-tool-pill__svg--error",k==="error"&&"cortex-tool-pill__svg--visible"),viewBox:"0 0 20 20",fill:"none",children:S("path",{d:"M6.5 6.5 L13.5 13.5 M13.5 6.5 L6.5 13.5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})})]}),S("span",{className:F("cortex-tool-pill__title",k==="error"&&"cortex-tool-pill__title--error"),children:N($)})]})}import{jsx as o2}from"react/jsx-runtime";var l2=Z_("code");function P0(){return o2(H_,{labels:l2})}import{jsx as r2}from"react/jsx-runtime";var j2=Z_("graph");function b0(){return r2(H_,{labels:j2})}import{jsx as v1}from"react/jsx-runtime";function R0({message:_,toolCallPart:N}){if(!K_(N.state)){if(N.name==="queryGraph")return v1(b0,{});if(N.name==="executeCode")return v1(P0,{})}return v1(E0,{toolCallPart:N,message:_})}import{jsx as B_,jsxs as h2}from"react/jsx-runtime";function v0(_){let{message:N,part:k,debugMode:L=!1,animate:$=!1,streaming:Z=!1}=_,{t:G}=H();function X(){switch(k.type){case"text":return B_(H0,{textPart:k,role:N.role,streaming:Z});case"thinking":return L?B_(F0,{reasoningPart:k,streaming:Z}):B_(z0,{});case"tool-call":return L?B_(M0,{toolCallPart:k}):B_(R0,{toolCallPart:k,message:N});default:return h2("p",{className:"cortex-unhandled-type",children:[G("translate_unhandled_type")," ",k.type]})}}return B_("div",{className:F("cortex-message-part",$&&"cortex-message-part--animated"),children:X()})}import{useState as x2}from"react";import{jsx as P,jsxs as C}from"react/jsx-runtime";function I0({usage:_,modelId:N}){let{t:k}=H(),[L,$]=x2(!1),Z=E_(_)??0;return C("div",{className:F("cortex-token-usage",L&&"cortex-token-usage--expanded"),children:[C("button",{className:"cortex-token-usage__summary",onClick:()=>$((G)=>!G),children:[C("span",{className:"cortex-token-usage__total",children:[P("span",{className:"cortex-token-usage__total-number",children:v(_.total)}),P("span",{className:"cortex-token-usage__total-label",children:k("translate_tokens")})]}),N?P("span",{className:"cortex-token-usage__model",children:N}):null,C("span",{className:"cortex-token-usage__pills",children:[C("span",{className:"cortex-token-usage__pill",children:[P("span",{className:"cortex-token-usage__dot cortex-token-usage__dot--input"}),v(_.input.total)]}),C("span",{className:"cortex-token-usage__pill",children:[P("span",{className:"cortex-token-usage__dot cortex-token-usage__dot--output"}),v(_.output.total)]})]}),Z>0?C("span",{className:"cortex-token-usage__cache-badge",children:[Z,"%"]}):null,P("svg",{className:"cortex-token-usage__chevron",width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:P("path",{d:"M3 4.5L6 7.5L9 4.5",stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round"})})]}),P("div",{className:"cortex-token-usage__details",children:P("div",{className:"cortex-token-usage__details-inner",children:C("div",{className:"cortex-token-usage__columns",children:[C("div",{className:"cortex-token-usage__col",children:[C("div",{className:"cortex-token-usage__col-header",children:[P("span",{className:"cortex-token-usage__dot cortex-token-usage__dot--input"}),P("span",{className:"cortex-token-usage__col-label",children:k("translate_input")}),P("span",{className:"cortex-token-usage__col-total",children:v(_.input.total)})]}),C("div",{className:"cortex-token-usage__rows",children:[_.input.noCache?C("div",{className:"cortex-token-usage__row",children:[P("span",{className:"cortex-token-usage__row-label",children:k("translate_fresh")}),P("span",{className:"cortex-token-usage__row-value",children:v(_.input.noCache)})]}):null,_.input.cacheRead?C("div",{className:"cortex-token-usage__row",children:[P("span",{className:"cortex-token-usage__row-label",children:k("translate_cache_read")}),P("span",{className:"cortex-token-usage__row-value",children:v(_.input.cacheRead)})]}):null,_.input.cacheWrite?C("div",{className:"cortex-token-usage__row",children:[P("span",{className:"cortex-token-usage__row-label",children:k("translate_cache_write")}),P("span",{className:"cortex-token-usage__row-value",children:v(_.input.cacheWrite)})]}):null]}),Z>0?C("div",{className:"cortex-token-usage__cache-bar-row",children:[P("div",{className:"cortex-token-usage__cache-bar",children:P("div",{className:"cortex-token-usage__cache-fill",style:{width:`${Z}%`}})}),P("span",{className:"cortex-token-usage__cache-label",children:k("translate_n_percent_cached",{percent:Z})})]}):null]}),C("div",{className:"cortex-token-usage__col",children:[C("div",{className:"cortex-token-usage__col-header",children:[P("span",{className:"cortex-token-usage__dot cortex-token-usage__dot--output"}),P("span",{className:"cortex-token-usage__col-label",children:k("translate_output")}),P("span",{className:"cortex-token-usage__col-total",children:v(_.output.total)})]}),C("div",{className:"cortex-token-usage__rows",children:[_.output.text?C("div",{className:"cortex-token-usage__row",children:[P("span",{className:"cortex-token-usage__row-label",children:k("translate_text")}),P("span",{className:"cortex-token-usage__row-value",children:v(_.output.text)})]}):null,_.output.reasoning?C("div",{className:"cortex-token-usage__row",children:[P("span",{className:"cortex-token-usage__row-label",children:k("translate_reasoning")}),P("span",{className:"cortex-token-usage__row-value",children:v(_.output.reasoning)})]}):null]})]})]})})})]})}import{jsx as y_,jsxs as c0}from"react/jsx-runtime";function n0(_){let{message:N,debugMode:k=!1,animate:L=!1}=_,{messages:$,isAgentWorking:Z,messageMetadata:G}=H(),X=Z&&C_($)?.id===N.id,J=N.role==="assistant",W=N.parts,Y=W.filter((Q,V)=>{if(Q.type==="tool-result")return!1;return k||!Z1(Q,V===W.length-1,X)}),U=X?Y.length-1:-1,q=G.get(N.id),D=Boolean(q?.isAborted),b=q?.tokenUsage,M=N.role==="user"?q?.attachments??[]:[],R=k&&!X&&(Boolean(b)||J);return y_("div",{className:"cortex-message",children:Y.length>0&&c0("div",{className:"cortex-message-parts",children:[Y.map((Q,V)=>y_(v0,{part:Q,message:N,debugMode:k,animate:L,streaming:V===U},V)),M.length>0&&y_(J0,{attachments:M}),D&&y_($0,{}),R&&c0("div",{className:"cortex-message-debug-zone",children:[b&&y_(I0,{usage:b,modelId:q?.modelId}),J&&y_(W0,{messageId:N.id})]})]})})}import{jsx as I1}from"react/jsx-runtime";function S0(_){let{messages:N,selectedThread:k}=H(),L=i_(null),$=i_(!0),Z=i_(!0),G=i_(!1),[X,J]=i2(!1);function W(){let M=L.current;if(M)M.scrollTop=M.scrollHeight}function Y(){if(G.current)return;G.current=!0,queueMicrotask(()=>{G.current=!1,W(),$.current=!1})}x_(()=>{let M=L.current;if(Y(),J(!0),!M||typeof MutationObserver>"u")return;let R=new MutationObserver(()=>{if(!$.current&&!Z.current)return;Y()});return R.observe(M,{childList:!0,subtree:!0,characterData:!0}),()=>R.disconnect()},[]);let U=k?.id;x_(()=>{J(!1),$.current=!0,queueMicrotask(()=>J(!0))},[U]);let q=N[N.length-1],D=q?.role==="user"?q.id:void 0;x_(()=>{if(D)$.current=!0},[D]),x_(()=>{if(!$.current&&!Z.current)return;Y()},[N]);function b(){let M=L.current;if(!M)return;Z.current=M.scrollHeight-M.scrollTop-M.clientHeight<100}return I1("div",{className:_.className,children:I1("div",{ref:L,className:"cortex-message-list",onScroll:b,children:N.map((M)=>I1(n0,{message:M,debugMode:_.debugMode,animate:X},M.id))})})}import{jsx as O,jsxs as a}from"react/jsx-runtime";var n1={messages:[],isAgentWorking:!1,isLoadingMessages:!1,hasPendingToolCalls:!1,messageMetadata:new Map};function a2({config:_,className:N}){let k=$_(_);k.current=_;let[L,$]=V_(),[Z,G]=V_(),[X,J]=V_(n1),[W,Y]=V_(!1),[U,q]=V_(!0),[D,b]=V_("chat"),[M,R]=V_(!1),Q=$_(void 0),V=$_([]),z=$_(void 0),T=$_(null),c=c1(()=>_1(()=>k.current.transport),[]),p=c1(()=>{let K=Z?.thread;if(!K)return;return L?.find((E)=>E.id===K.id)??K},[L,Z]),B=$_(p);B.current=p;let u=$_(X);u.current=X;let y=o((K)=>{J((E)=>({...E,...typeof K==="function"?K(E):K}))},[]),g=o((K,E)=>{$((A)=>{let j=A?.find((e_)=>e_.id===K);return j?M_(A??[],{...j,isRunning:E}):A})},[]),n=o((K,E)=>{if(B.current?.id===K.id&&Q.current)return;let A=B.current;if(B.current=K,J(n1),G({thread:K,mode:E?.skipLoadingMessages?"skip":"load",epoch:0}),A&&A.id!==K.id)k.current.hooks?.onThreadDeselected?.(A);k.current.hooks?.onThreadSelected?.(K)},[]),m=o(()=>{let K=B.current;if(!K&&!Q.current)return;if(B.current=void 0,G(void 0),J(n1),K)k.current.hooks?.onThreadDeselected?.(K)},[]),g0=o((K)=>{G((E)=>({thread:K,mode:"reload",epoch:(E?.epoch??0)+1,initialMessages:u.current.messages}))},[]),c_=o((K)=>{let E=B.current;if(E)return Promise.resolve(E.id);return z.current??=c.createThread(K).then((A)=>{return z.current=void 0,$((j)=>M_(j??[],A)),n(A,{skipLoadingMessages:!0}),A.id},(A)=>{throw z.current=void 0,A}),z.current},[c,n]),h=c1(()=>W1({api:c,ensureThread:()=>c_()}),[c,c_]),S1=d2(h.subscribe,h.getState,h.getState),f0=o(async(K,E=[])=>{if(u.current.isAgentWorking||u.current.hasPendingToolCalls)return;let A=Q.current;if(A){await A.send(K,E);return}V.current.push({prompt:K,attachments:E});try{await c_(K)}catch(j){throw V.current=[],j}},[c_]),T0=o(async()=>{await Q.current?.abort()},[]),p0=o((K,E,A)=>Q.current?.addToolResult(K,E,A)??Promise.resolve(),[]),m0=o(async(K)=>{if(B.current?.id===K)m();await c.deleteThread(K),$((E)=>E?T_(E,K):E)},[c,m]),u0=o(()=>{h.discardConsumed(),setTimeout(()=>T.current?.focusInput())},[h]),l0=o(()=>{h.restoreConsumed(B.current?.id)},[h]),d_=o(async()=>{let K=f_(await c.listThreads());return $(K),K},[c]),C1=o((K)=>{$((A)=>{let j=D1(A??[],K);return A||j.length?j:A});let E=B.current?.id;switch(K.type){case"thread:deleted":if(E===K.payload.threadId)m();break;case"thread:run-started":if(E===K.payload.thread.id)Q.current?.reattach(K.payload.thread);break;case"thread:messages-updated":Q.current?.refreshMessages(K.payload.threadId);break}},[m]);C0(()=>{d_(),c.getCapabilities().then((A)=>q(A.attachments)).catch(()=>{});let K=!1,E=q1({wsUrl:()=>k.current.wsUrl,transport:{baseUrl:()=>{let A=k.current.transport.baseUrl;return typeof A==="string"?A:A()},getHeaders:()=>k.current.transport.getHeaders()},onEvent:C1,onOpen:()=>{if(!K){K=!0;return}d_().then((A)=>{let j=B.current;if(!j)return;Q.current?.reattach(A.find((e_)=>e_.id===j.id)??j)})}});return()=>{E.close()}},[c,C1,d_]);let a_=$_(void 0),t_=p?.id;C0(()=>{if(t_===a_.current)return;h.clear(a_.current),a_.current=t_},[t_,h]);let s_=_.locale??"en",W_=o((K,E)=>y1(s_,K,E),[s_]),o0=_.viewMode??"helper",j0={config:_,t:W_,api:c,debugMode:W,attachmentsEnabled:_.attachments!==!1&&U,threads:L,selectedThread:p,deleteThread:m0,...X,send:f0,abort:T0,addToolResult:p0,queue:{items:S1,...K1(S1),accept:h.accept,remove:h.remove,consumeReady:h.consumeReady}};function g1(K){n(K),b("chat"),R(!1)}function r0(){m(),b("chat"),R(!1)}function h0(){b("threads")}function x0(){b("chat")}return O(A1.Provider,{value:j0,children:a("div",{className:F("cortex-widget",N),"data-cortex-theme":_.theme,children:[a("div",{className:F("cortex-widget__container",o0==="full"&&"cortex-widget__container--full",M&&"cortex-widget__container--sidebar-open"),onDragOver:(K)=>K.preventDefault(),onDrop:(K)=>K.preventDefault(),children:[O(_0,{className:F("cortex-widget__screen",D==="threads"&&"cortex-widget__screen--active",D!=="threads"&&"cortex-widget__screen--left"),onThreadSelected:g1,onNewChatRequested:r0,onBackRequested:x0}),a("div",{className:F("cortex-widget__screen",D==="chat"&&"cortex-widget__screen--active",D!=="chat"&&"cortex-widget__screen--right"),children:[a("div",{className:"cortex-widget__chat-header",children:[O("button",{onClick:()=>R((K)=>!K),className:"cortex-widget__sidebar-toggle-btn",children:O("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:O("path",{d:"M2.5 4h11M2.5 8h11M2.5 12h11",stroke:"currentColor",strokeWidth:"1.4",strokeLinecap:"round"})})}),O("div",{className:"cortex-widget__chat-title-wrap",children:O("p",{className:"cortex-widget__chat-title",children:p?.title??Q_(_.agentName,s_)??W_("translate_new_chat")})}),_.showDebugButton&&O("button",{onClick:()=>Y((K)=>!K),className:F("cortex-widget__debug-btn",W?"cortex-widget__debug-btn--on":"cortex-widget__debug-btn--off"),children:W?W_("translate_debug"):W_("translate_normal")}),O("button",{type:"button",onClick:h0,"aria-label":W_("translate_history"),className:"cortex-widget__history-btn",children:a("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none","aria-hidden":"true",children:[O("circle",{cx:"8",cy:"8",r:"5.75",stroke:"currentColor",strokeWidth:"1.3"}),O("path",{d:"M8 5v3l2 1.5",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"})]})})]}),!p?O(k0,{onThreadSelected:g1}):X.isLoadingMessages&&!X.isAgentWorking?a("div",{className:"cortex-widget__messages-skeleton",children:[O("div",{className:"cortex-widget__msg-skel cortex-widget__msg-skel--user",children:a("div",{className:"cortex-widget__msg-skel-bubble cortex-widget__msg-skel-bubble--user",children:[O("div",{className:"cortex-skeleton cortex-widget__msg-skel-line",style:{width:"13rem"}}),O("div",{className:"cortex-skeleton cortex-widget__msg-skel-line",style:{width:"9rem"}})]})}),O("div",{className:"cortex-widget__msg-skel cortex-widget__msg-skel--assistant",children:a("div",{className:"cortex-widget__msg-skel-bubble cortex-widget__msg-skel-bubble--assistant",children:[O("div",{className:"cortex-skeleton cortex-widget__msg-skel-line",style:{width:"16rem"}}),O("div",{className:"cortex-skeleton cortex-widget__msg-skel-line",style:{width:"18rem"}}),O("div",{className:"cortex-skeleton cortex-widget__msg-skel-line",style:{width:"12rem"}})]})}),O("div",{className:"cortex-widget__msg-skel cortex-widget__msg-skel--user",children:O("div",{className:"cortex-widget__msg-skel-bubble cortex-widget__msg-skel-bubble--user",children:O("div",{className:"cortex-skeleton cortex-widget__msg-skel-line",style:{width:"11rem"}})})}),O("div",{className:"cortex-widget__msg-skel cortex-widget__msg-skel--assistant",children:a("div",{className:"cortex-widget__msg-skel-bubble cortex-widget__msg-skel-bubble--assistant",children:[O("div",{className:"cortex-skeleton cortex-widget__msg-skel-line",style:{width:"14rem"}}),O("div",{className:"cortex-skeleton cortex-widget__msg-skel-line",style:{width:"15rem"}})]})})]}):O(S0,{className:"cortex-widget__messages",debugMode:W}),X.isAgentWorking&&!X.hasPendingToolCalls&&a("div",{className:"cortex-widget__working",children:[a("div",{className:"cortex-widget__working-dots",children:[O("span",{className:"cortex-working-dot"}),O("span",{className:"cortex-working-dot"}),O("span",{className:"cortex-working-dot"})]}),O("span",{className:"cortex-widget__working-text",children:W_("translate_thinking")})]}),p&&!X.hasPendingToolCalls&&O(l_,{ref:T})]}),O("div",{className:"cortex-widget__sidebar-backdrop",onClick:()=>R(!1)})]}),Z&&O(t1,{thread:Z.thread,mode:Z.mode,initialMessages:Z.initialMessages,api:c,configRef:k,sessionRef:Q,pendingSendRef:V,patchUi:y,setRunning:g,remount:g0,onTurnFinished:u0,onSendFailed:l0},`${Z.thread.id}:${Z.epoch}`)]})})}export{a2 as CortexChatWidget};
|
package/dist/styles.css
CHANGED
|
@@ -270,7 +270,8 @@
|
|
|
270
270
|
background: var(--cortex-color-surface);
|
|
271
271
|
}
|
|
272
272
|
|
|
273
|
-
.cortex-widget__back-btn
|
|
273
|
+
.cortex-widget__back-btn,
|
|
274
|
+
.cortex-widget__history-btn {
|
|
274
275
|
flex-shrink: 0;
|
|
275
276
|
width: 2rem;
|
|
276
277
|
height: 2rem;
|
|
@@ -284,7 +285,8 @@
|
|
|
284
285
|
transition: color 0.15s, background-color 0.15s;
|
|
285
286
|
color: var(--cortex-color-text-muted);
|
|
286
287
|
}
|
|
287
|
-
.cortex-widget__back-btn:hover
|
|
288
|
+
.cortex-widget__back-btn:hover,
|
|
289
|
+
.cortex-widget__history-btn:hover {
|
|
288
290
|
color: var(--cortex-color-text);
|
|
289
291
|
background: var(--cortex-color-surface-muted);
|
|
290
292
|
}
|
|
@@ -383,6 +385,116 @@
|
|
|
383
385
|
overflow: hidden;
|
|
384
386
|
}
|
|
385
387
|
|
|
388
|
+
.cortex-widget__landing {
|
|
389
|
+
flex: 1;
|
|
390
|
+
min-height: 0;
|
|
391
|
+
overflow-y: auto;
|
|
392
|
+
display: flex;
|
|
393
|
+
flex-direction: column;
|
|
394
|
+
align-items: center;
|
|
395
|
+
justify-content: center;
|
|
396
|
+
padding: 1.25rem;
|
|
397
|
+
text-align: center;
|
|
398
|
+
}
|
|
399
|
+
.cortex-widget__landing .cortex-widget__input-area {
|
|
400
|
+
width: 100%;
|
|
401
|
+
max-width: 26rem;
|
|
402
|
+
padding: 1rem 0 0;
|
|
403
|
+
border-top: 0;
|
|
404
|
+
background: transparent;
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
.cortex-widget__landing-icon {
|
|
408
|
+
width: 2.5rem;
|
|
409
|
+
height: 2.5rem;
|
|
410
|
+
border-radius: var(--cortex-radius);
|
|
411
|
+
background: var(--cortex-color-accent-surface);
|
|
412
|
+
color: var(--cortex-color-accent);
|
|
413
|
+
display: flex;
|
|
414
|
+
align-items: center;
|
|
415
|
+
justify-content: center;
|
|
416
|
+
margin-bottom: 0.875rem;
|
|
417
|
+
}
|
|
418
|
+
[dir=rtl] .cortex-widget__landing-icon {
|
|
419
|
+
transform: scaleX(-1);
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
.cortex-widget__landing-greeting {
|
|
423
|
+
font-family: var(--cortex-font-display, inherit);
|
|
424
|
+
font-size: 1.0625rem;
|
|
425
|
+
font-weight: 600;
|
|
426
|
+
line-height: 1.3;
|
|
427
|
+
color: var(--cortex-color-text-heading);
|
|
428
|
+
margin: 0;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
.cortex-widget__landing-chips {
|
|
432
|
+
display: flex;
|
|
433
|
+
flex-wrap: wrap;
|
|
434
|
+
justify-content: center;
|
|
435
|
+
gap: 0.5rem;
|
|
436
|
+
margin-top: 0.875rem;
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
.cortex-widget__landing-chip {
|
|
440
|
+
border: 1px solid var(--cortex-color-border);
|
|
441
|
+
border-radius: 999px;
|
|
442
|
+
background: var(--cortex-color-surface);
|
|
443
|
+
color: var(--cortex-color-text-strong);
|
|
444
|
+
font-size: 0.75rem;
|
|
445
|
+
font-weight: 500;
|
|
446
|
+
padding: 0.375rem 0.75rem;
|
|
447
|
+
cursor: pointer;
|
|
448
|
+
transition: border-color 0.15s, color 0.15s;
|
|
449
|
+
}
|
|
450
|
+
.cortex-widget__landing-chip:hover {
|
|
451
|
+
border-color: var(--cortex-color-accent);
|
|
452
|
+
color: var(--cortex-color-accent);
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
.cortex-widget__landing-recent {
|
|
456
|
+
width: 100%;
|
|
457
|
+
max-width: 26rem;
|
|
458
|
+
margin-top: 1rem;
|
|
459
|
+
display: flex;
|
|
460
|
+
flex-direction: column;
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
.cortex-widget__landing-recent-item {
|
|
464
|
+
display: flex;
|
|
465
|
+
align-items: center;
|
|
466
|
+
gap: 0.75rem;
|
|
467
|
+
padding: 0.4375rem 0.625rem;
|
|
468
|
+
border: 0;
|
|
469
|
+
border-radius: calc(var(--cortex-radius) * 0.75);
|
|
470
|
+
background: transparent;
|
|
471
|
+
cursor: pointer;
|
|
472
|
+
transition: background-color 0.15s;
|
|
473
|
+
}
|
|
474
|
+
.cortex-widget__landing-recent-item:hover {
|
|
475
|
+
background: var(--cortex-color-hover);
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
.cortex-widget__landing-recent-title {
|
|
479
|
+
flex: 1;
|
|
480
|
+
min-width: 0;
|
|
481
|
+
text-align: start;
|
|
482
|
+
font-size: var(--cortex-font-size);
|
|
483
|
+
font-weight: 500;
|
|
484
|
+
color: var(--cortex-color-text-strong);
|
|
485
|
+
overflow: hidden;
|
|
486
|
+
text-overflow: ellipsis;
|
|
487
|
+
white-space: nowrap;
|
|
488
|
+
margin: 0;
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
.cortex-widget__landing-recent-time {
|
|
492
|
+
flex-shrink: 0;
|
|
493
|
+
font-size: 0.6875rem;
|
|
494
|
+
color: var(--cortex-color-text-muted);
|
|
495
|
+
margin: 0;
|
|
496
|
+
}
|
|
497
|
+
|
|
386
498
|
@keyframes cortex-working-slide-in {
|
|
387
499
|
from {
|
|
388
500
|
opacity: 0;
|
|
@@ -656,7 +768,8 @@ cortex-chat-composer {
|
|
|
656
768
|
flex: 1;
|
|
657
769
|
min-width: 0;
|
|
658
770
|
}
|
|
659
|
-
.cortex-widget__container--full .cortex-widget__back-btn
|
|
771
|
+
.cortex-widget__container--full .cortex-widget__back-btn,
|
|
772
|
+
.cortex-widget__container--full .cortex-widget__history-btn {
|
|
660
773
|
display: none;
|
|
661
774
|
}
|
|
662
775
|
.cortex-widget__container--full .cortex-widget__chat-title {
|
|
@@ -759,7 +872,10 @@ cortex-chat-composer {
|
|
|
759
872
|
padding: 1.25rem 1.25rem 1rem;
|
|
760
873
|
display: flex;
|
|
761
874
|
align-items: center;
|
|
762
|
-
|
|
875
|
+
gap: 0.75rem;
|
|
876
|
+
}
|
|
877
|
+
.cortex-widget__threads-header .cortex-widget__new-chat-btn {
|
|
878
|
+
margin-inline-start: auto;
|
|
763
879
|
}
|
|
764
880
|
|
|
765
881
|
.cortex-widget__threads-title {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@m6d/cortex-react",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.7.0",
|
|
4
4
|
"description": "React chat widget SDK for cortex servers",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"sideEffects": [
|
|
@@ -41,7 +41,7 @@
|
|
|
41
41
|
"@tanstack/ai": "^0.43.1",
|
|
42
42
|
"@tanstack/ai-client": "^0.23.1",
|
|
43
43
|
"@tanstack/ai-react": "^0.19.1",
|
|
44
|
-
"@types/bun": "
|
|
44
|
+
"@types/bun": "1.3.14",
|
|
45
45
|
"@types/react": "^19",
|
|
46
46
|
"@types/react-dom": "^19",
|
|
47
47
|
"dompurify": "^3.3.3",
|
package/src/chat-session.tsx
CHANGED
|
@@ -4,6 +4,7 @@ import { useChat } from '@tanstack/ai-react';
|
|
|
4
4
|
import {
|
|
5
5
|
createCortexConnection,
|
|
6
6
|
metadataByMessageId,
|
|
7
|
+
randomId,
|
|
7
8
|
settleTurn,
|
|
8
9
|
unansweredToolCalls,
|
|
9
10
|
type CortexApiClient,
|
|
@@ -229,7 +230,7 @@ export function ChatSession(props: ChatSessionProps) {
|
|
|
229
230
|
serverAnswered.current = false;
|
|
230
231
|
|
|
231
232
|
const message = {
|
|
232
|
-
id:
|
|
233
|
+
id: randomId(),
|
|
233
234
|
role: 'user',
|
|
234
235
|
parts: [{ type: 'text', content: prompt }],
|
|
235
236
|
} satisfies UIMessage;
|
|
@@ -15,7 +15,7 @@ export type ChatComposerHandle = {
|
|
|
15
15
|
// where a plain function component never receives `ref`.
|
|
16
16
|
// fallow-ignore-next-line complexity -- 1:1 transcription of the Angular source; restructuring would risk parity drift
|
|
17
17
|
export const ChatComposer = forwardRef<ChatComposerHandle>(function ChatComposer(_props, ref) {
|
|
18
|
-
const { t, queue, isAgentWorking, send, abort } = useCortex();
|
|
18
|
+
const { t, queue, isAgentWorking, send, abort, attachmentsEnabled } = useCortex();
|
|
19
19
|
const [text, setText] = useState('');
|
|
20
20
|
const [dragging, setDragging] = useState(false);
|
|
21
21
|
const messageInput = useRef<HTMLTextAreaElement>(null);
|
|
@@ -65,7 +65,7 @@ export const ChatComposer = forwardRef<ChatComposerHandle>(function ChatComposer
|
|
|
65
65
|
|
|
66
66
|
function onDragOver(event: DragEvent<HTMLDivElement>) {
|
|
67
67
|
event.preventDefault();
|
|
68
|
-
setDragging(true);
|
|
68
|
+
if (attachmentsEnabled) setDragging(true);
|
|
69
69
|
}
|
|
70
70
|
|
|
71
71
|
function onDragLeave(event: DragEvent<HTMLDivElement>) {
|
|
@@ -80,12 +80,12 @@ export const ChatComposer = forwardRef<ChatComposerHandle>(function ChatComposer
|
|
|
80
80
|
function onDrop(event: DragEvent<HTMLDivElement>) {
|
|
81
81
|
event.preventDefault();
|
|
82
82
|
setDragging(false);
|
|
83
|
-
queue.accept([...event.dataTransfer.files]);
|
|
83
|
+
if (attachmentsEnabled) queue.accept([...event.dataTransfer.files]);
|
|
84
84
|
}
|
|
85
85
|
|
|
86
86
|
function onPaste(event: ClipboardEvent<HTMLTextAreaElement>) {
|
|
87
87
|
const files = event.clipboardData.files;
|
|
88
|
-
if (!files.length) return;
|
|
88
|
+
if (!attachmentsEnabled || !files.length) return;
|
|
89
89
|
|
|
90
90
|
event.preventDefault();
|
|
91
91
|
queue.accept([...files]);
|
|
@@ -146,36 +146,40 @@ export const ChatComposer = forwardRef<ChatComposerHandle>(function ChatComposer
|
|
|
146
146
|
</button>
|
|
147
147
|
) : (
|
|
148
148
|
<div className="cortex-widget__input-actions">
|
|
149
|
-
{
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
149
|
+
{attachmentsEnabled ? (
|
|
150
|
+
<>
|
|
151
|
+
{/* Attach button */}
|
|
152
|
+
<button
|
|
153
|
+
type="button"
|
|
154
|
+
onClick={() => fileInput.current?.click()}
|
|
155
|
+
className="cortex-widget__attach-btn"
|
|
156
|
+
aria-label={t('translate_attach_files')}
|
|
157
|
+
>
|
|
158
|
+
<svg width="16" height="16" viewBox="0 0 16 16" fill="none">
|
|
159
|
+
<path
|
|
160
|
+
d="M10.5 5.5 6.2 9.8a1.4 1.4 0 0 0 2 2l4.6-4.6a2.8 2.8 0 0 0-4-4L4.2 7.8a4.2 4.2 0 0 0 6 6l4-4"
|
|
161
|
+
stroke="currentColor"
|
|
162
|
+
strokeWidth="1.3"
|
|
163
|
+
strokeLinecap="round"
|
|
164
|
+
strokeLinejoin="round"
|
|
165
|
+
/>
|
|
166
|
+
</svg>
|
|
167
|
+
</button>
|
|
168
|
+
<input
|
|
169
|
+
ref={fileInput}
|
|
170
|
+
type="file"
|
|
171
|
+
multiple
|
|
172
|
+
accept={ACCEPTED_TYPES}
|
|
173
|
+
onChange={(event) => {
|
|
174
|
+
queue.accept([...(event.target.files ?? [])]);
|
|
175
|
+
|
|
176
|
+
// Cleared so picking the same file again still fires `change`.
|
|
177
|
+
event.target.value = '';
|
|
178
|
+
}}
|
|
179
|
+
className="cortex-widget__file-input"
|
|
163
180
|
/>
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
<input
|
|
167
|
-
ref={fileInput}
|
|
168
|
-
type="file"
|
|
169
|
-
multiple
|
|
170
|
-
accept={ACCEPTED_TYPES}
|
|
171
|
-
onChange={(event) => {
|
|
172
|
-
queue.accept([...(event.target.files ?? [])]);
|
|
173
|
-
|
|
174
|
-
// Cleared so picking the same file again still fires `change`.
|
|
175
|
-
event.target.value = '';
|
|
176
|
-
}}
|
|
177
|
-
className="cortex-widget__file-input"
|
|
178
|
-
/>
|
|
181
|
+
</>
|
|
182
|
+
) : null}
|
|
179
183
|
|
|
180
184
|
{/* Send button */}
|
|
181
185
|
<button
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { localized, relativeTimeLabel } from '@cortex/client';
|
|
2
|
+
import type { ThreadSummary } from '@cortex/contracts/wire';
|
|
3
|
+
import { useCortex } from '../context';
|
|
4
|
+
import { ChatComposer } from './ChatComposer';
|
|
5
|
+
import { BUBBLE_PATH } from './ThreadList';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The blank-chat landing: greeting, suggestion chips, the composer mid-panel
|
|
9
|
+
* and the freshest threads. The first send creates the thread, which swaps
|
|
10
|
+
* this for the message list.
|
|
11
|
+
*/
|
|
12
|
+
export function ChatLanding(props: { onThreadSelected: (thread: ThreadSummary) => void }) {
|
|
13
|
+
const { config, t, threads, send } = useCortex();
|
|
14
|
+
const locale = config.locale ?? 'en';
|
|
15
|
+
const suggestions = localized(config.suggestions, locale);
|
|
16
|
+
|
|
17
|
+
return (
|
|
18
|
+
<div className="cortex-widget__landing">
|
|
19
|
+
<div className="cortex-widget__landing-icon">
|
|
20
|
+
<svg width="18" height="18" viewBox="0 0 16 16" fill="none">
|
|
21
|
+
<path
|
|
22
|
+
d={BUBBLE_PATH}
|
|
23
|
+
stroke="currentColor"
|
|
24
|
+
strokeWidth="1.3"
|
|
25
|
+
strokeLinecap="round"
|
|
26
|
+
strokeLinejoin="round"
|
|
27
|
+
/>
|
|
28
|
+
</svg>
|
|
29
|
+
</div>
|
|
30
|
+
|
|
31
|
+
<p className="cortex-widget__landing-greeting">
|
|
32
|
+
{localized(config.greeting, locale) ?? t('translate_greeting')}
|
|
33
|
+
</p>
|
|
34
|
+
|
|
35
|
+
{!!suggestions?.length && (
|
|
36
|
+
<div className="cortex-widget__landing-chips">
|
|
37
|
+
{suggestions.map((suggestion, index) => (
|
|
38
|
+
<button
|
|
39
|
+
key={index}
|
|
40
|
+
type="button"
|
|
41
|
+
onClick={() => void send(suggestion)}
|
|
42
|
+
className="cortex-widget__landing-chip"
|
|
43
|
+
>
|
|
44
|
+
{suggestion}
|
|
45
|
+
</button>
|
|
46
|
+
))}
|
|
47
|
+
</div>
|
|
48
|
+
)}
|
|
49
|
+
|
|
50
|
+
<ChatComposer />
|
|
51
|
+
|
|
52
|
+
{!!threads?.length && (
|
|
53
|
+
<div className="cortex-widget__landing-recent">
|
|
54
|
+
{threads.slice(0, 2).map((thread) => {
|
|
55
|
+
// Rendered once per paint: the label goes stale while the panel
|
|
56
|
+
// sits open, which is cheaper than a timer per row.
|
|
57
|
+
const time = relativeTimeLabel(thread.updatedAt, locale);
|
|
58
|
+
return (
|
|
59
|
+
<button
|
|
60
|
+
key={thread.id}
|
|
61
|
+
type="button"
|
|
62
|
+
onClick={() => props.onThreadSelected(thread)}
|
|
63
|
+
className="cortex-widget__landing-recent-item"
|
|
64
|
+
>
|
|
65
|
+
<p className="cortex-widget__landing-recent-title">
|
|
66
|
+
{thread.title ?? t('translate_untitled')}
|
|
67
|
+
</p>
|
|
68
|
+
{time && <p className="cortex-widget__landing-recent-time">{time}</p>}
|
|
69
|
+
</button>
|
|
70
|
+
);
|
|
71
|
+
})}
|
|
72
|
+
</div>
|
|
73
|
+
)}
|
|
74
|
+
</div>
|
|
75
|
+
);
|
|
76
|
+
}
|
|
@@ -5,6 +5,7 @@ import {
|
|
|
5
5
|
createAttachmentQueue,
|
|
6
6
|
createCortexApiClient,
|
|
7
7
|
createCortexSocket,
|
|
8
|
+
localized,
|
|
8
9
|
removeThread,
|
|
9
10
|
sortThreads,
|
|
10
11
|
translate,
|
|
@@ -23,6 +24,7 @@ import type { CortexReactConfig } from '../config';
|
|
|
23
24
|
import { CortexContext, type CortexContextValue } from '../context';
|
|
24
25
|
import { cx } from '../cx';
|
|
25
26
|
import { ChatComposer, type ChatComposerHandle } from './ChatComposer';
|
|
27
|
+
import { ChatLanding } from './ChatLanding';
|
|
26
28
|
import { MessageList } from './MessageList';
|
|
27
29
|
import { ThreadList } from './ThreadList';
|
|
28
30
|
|
|
@@ -57,7 +59,10 @@ export function CortexChatWidget({
|
|
|
57
59
|
const [session, setSession] = useState<MountedSession>();
|
|
58
60
|
const [sessionUi, setSessionUi] = useState<SessionUi>(initialSessionUi);
|
|
59
61
|
const [debugMode, setDebugMode] = useState(false);
|
|
60
|
-
|
|
62
|
+
// Optimistically true until the handshake answers; most agents accept files
|
|
63
|
+
// and a briefly hidden button would flicker for them.
|
|
64
|
+
const [serverAcceptsAttachments, setServerAcceptsAttachments] = useState(true);
|
|
65
|
+
const [screen, setScreen] = useState<'threads' | 'chat'>('chat');
|
|
61
66
|
const [sidebarOpen, setSidebarOpen] = useState(false);
|
|
62
67
|
|
|
63
68
|
const sessionRef = useRef<SessionHandle | undefined>(undefined);
|
|
@@ -273,6 +278,12 @@ export function CortexChatWidget({
|
|
|
273
278
|
|
|
274
279
|
useEffect(() => {
|
|
275
280
|
void reloadThreads();
|
|
281
|
+
// A failed handshake keeps the optimistic default; the server still
|
|
282
|
+
// enforces its side on upload.
|
|
283
|
+
void api
|
|
284
|
+
.getCapabilities()
|
|
285
|
+
.then((capabilities) => setServerAcceptsAttachments(capabilities.attachments))
|
|
286
|
+
.catch(() => {});
|
|
276
287
|
|
|
277
288
|
// The first open is startup; only a socket that comes back marks a gap.
|
|
278
289
|
let openedOnce = false;
|
|
@@ -309,7 +320,7 @@ export function CortexChatWidget({
|
|
|
309
320
|
return () => {
|
|
310
321
|
socket.close();
|
|
311
322
|
};
|
|
312
|
-
}, [handleWsEvent, reloadThreads]);
|
|
323
|
+
}, [api, handleWsEvent, reloadThreads]);
|
|
313
324
|
|
|
314
325
|
// Leaving a thread abandons the files queued for it.
|
|
315
326
|
const previousThreadId = useRef<string | undefined>(undefined);
|
|
@@ -334,6 +345,7 @@ export function CortexChatWidget({
|
|
|
334
345
|
t,
|
|
335
346
|
api,
|
|
336
347
|
debugMode,
|
|
348
|
+
attachmentsEnabled: config.attachments !== false && serverAcceptsAttachments,
|
|
337
349
|
threads,
|
|
338
350
|
selectedThread,
|
|
339
351
|
deleteThread,
|
|
@@ -362,11 +374,15 @@ export function CortexChatWidget({
|
|
|
362
374
|
setSidebarOpen(false);
|
|
363
375
|
}
|
|
364
376
|
|
|
365
|
-
|
|
366
|
-
|
|
377
|
+
// History leaves the open thread mounted; closing it returns to that chat.
|
|
378
|
+
function openHistory() {
|
|
367
379
|
setScreen('threads');
|
|
368
380
|
}
|
|
369
381
|
|
|
382
|
+
function closeHistory() {
|
|
383
|
+
setScreen('chat');
|
|
384
|
+
}
|
|
385
|
+
|
|
370
386
|
return (
|
|
371
387
|
<CortexContext.Provider value={contextValue}>
|
|
372
388
|
<div className={cx('cortex-widget', className)} data-cortex-theme={config.theme}>
|
|
@@ -388,6 +404,7 @@ export function CortexChatWidget({
|
|
|
388
404
|
)}
|
|
389
405
|
onThreadSelected={openThread}
|
|
390
406
|
onNewChatRequested={newChat}
|
|
407
|
+
onBackRequested={closeHistory}
|
|
391
408
|
/>
|
|
392
409
|
|
|
393
410
|
{/* SCREEN 2: CHAT */}
|
|
@@ -414,28 +431,11 @@ export function CortexChatWidget({
|
|
|
414
431
|
</svg>
|
|
415
432
|
</button>
|
|
416
433
|
|
|
417
|
-
{/* Back button */}
|
|
418
|
-
<button onClick={goBack} className="cortex-widget__back-btn">
|
|
419
|
-
<svg
|
|
420
|
-
width="14"
|
|
421
|
-
height="14"
|
|
422
|
-
viewBox="0 0 16 16"
|
|
423
|
-
fill="none"
|
|
424
|
-
className="cortex-widget__back-icon"
|
|
425
|
-
>
|
|
426
|
-
<path
|
|
427
|
-
d="M10 3L5 8l5 5"
|
|
428
|
-
stroke="currentColor"
|
|
429
|
-
strokeWidth="1.5"
|
|
430
|
-
strokeLinecap="round"
|
|
431
|
-
strokeLinejoin="round"
|
|
432
|
-
/>
|
|
433
|
-
</svg>
|
|
434
|
-
</button>
|
|
435
|
-
|
|
436
434
|
<div className="cortex-widget__chat-title-wrap">
|
|
437
435
|
<p className="cortex-widget__chat-title">
|
|
438
|
-
{selectedThread?.title ??
|
|
436
|
+
{selectedThread?.title ??
|
|
437
|
+
localized(config.agentName, locale) ??
|
|
438
|
+
t('translate_new_chat')}
|
|
439
439
|
</p>
|
|
440
440
|
</div>
|
|
441
441
|
|
|
@@ -450,9 +450,30 @@ export function CortexChatWidget({
|
|
|
450
450
|
{debugMode ? t('translate_debug') : t('translate_normal')}
|
|
451
451
|
</button>
|
|
452
452
|
)}
|
|
453
|
+
|
|
454
|
+
{/* History button */}
|
|
455
|
+
<button
|
|
456
|
+
type="button"
|
|
457
|
+
onClick={openHistory}
|
|
458
|
+
aria-label={t('translate_history')}
|
|
459
|
+
className="cortex-widget__history-btn"
|
|
460
|
+
>
|
|
461
|
+
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true">
|
|
462
|
+
<circle cx="8" cy="8" r="5.75" stroke="currentColor" strokeWidth="1.3" />
|
|
463
|
+
<path
|
|
464
|
+
d="M8 5v3l2 1.5"
|
|
465
|
+
stroke="currentColor"
|
|
466
|
+
strokeWidth="1.3"
|
|
467
|
+
strokeLinecap="round"
|
|
468
|
+
strokeLinejoin="round"
|
|
469
|
+
/>
|
|
470
|
+
</svg>
|
|
471
|
+
</button>
|
|
453
472
|
</div>
|
|
454
473
|
|
|
455
|
-
{
|
|
474
|
+
{!selectedThread ? (
|
|
475
|
+
<ChatLanding onThreadSelected={openThread} />
|
|
476
|
+
) : sessionUi.isLoadingMessages && !sessionUi.isAgentWorking ? (
|
|
456
477
|
<div className="cortex-widget__messages-skeleton">
|
|
457
478
|
<div className="cortex-widget__msg-skel cortex-widget__msg-skel--user">
|
|
458
479
|
<div className="cortex-widget__msg-skel-bubble cortex-widget__msg-skel-bubble--user">
|
|
@@ -518,7 +539,7 @@ export function CortexChatWidget({
|
|
|
518
539
|
</div>
|
|
519
540
|
)}
|
|
520
541
|
|
|
521
|
-
{!sessionUi.hasPendingToolCalls && <ChatComposer ref={composerRef} />}
|
|
542
|
+
{selectedThread && !sessionUi.hasPendingToolCalls && <ChatComposer ref={composerRef} />}
|
|
522
543
|
</div>
|
|
523
544
|
|
|
524
545
|
{/* Sidebar overlay backdrop (full mode, small screens) */}
|
|
@@ -4,13 +4,14 @@ import { useCortex } from '../context';
|
|
|
4
4
|
import { cx } from '../cx';
|
|
5
5
|
|
|
6
6
|
/** Rounded speech bubble with a tail, on the shared 16x16 icon grid. */
|
|
7
|
-
const BUBBLE_PATH =
|
|
7
|
+
export const BUBBLE_PATH =
|
|
8
8
|
'M13.5 7.6c0 2.4-2.5 4.4-5.5 4.4-.6 0-1.2-.08-1.7-.23L3 13l.8-2.3C3 9.8 2.5 8.7 2.5 7.6 2.5 5.2 5 3.2 8 3.2s5.5 2 5.5 4.4Z';
|
|
9
9
|
|
|
10
10
|
type ThreadListProps = {
|
|
11
11
|
className?: string;
|
|
12
12
|
onThreadSelected: (thread: ThreadSummary) => void;
|
|
13
13
|
onNewChatRequested: () => void;
|
|
14
|
+
onBackRequested: () => void;
|
|
14
15
|
};
|
|
15
16
|
|
|
16
17
|
/**
|
|
@@ -28,8 +29,33 @@ export function ThreadList(props: ThreadListProps) {
|
|
|
28
29
|
<div className={props.className}>
|
|
29
30
|
{/* Threads header */}
|
|
30
31
|
<div className="cortex-widget__threads-header">
|
|
32
|
+
{/* Back to chat (helper mode; full mode hides it, the sidebar is always visible) */}
|
|
33
|
+
<button
|
|
34
|
+
type="button"
|
|
35
|
+
onClick={() => props.onBackRequested()}
|
|
36
|
+
aria-label={t('translate_back')}
|
|
37
|
+
className="cortex-widget__back-btn"
|
|
38
|
+
>
|
|
39
|
+
<svg
|
|
40
|
+
width="14"
|
|
41
|
+
height="14"
|
|
42
|
+
viewBox="0 0 16 16"
|
|
43
|
+
fill="none"
|
|
44
|
+
aria-hidden="true"
|
|
45
|
+
className="cortex-widget__back-icon"
|
|
46
|
+
>
|
|
47
|
+
<path
|
|
48
|
+
d="M10 3L5 8l5 5"
|
|
49
|
+
stroke="currentColor"
|
|
50
|
+
strokeWidth="1.5"
|
|
51
|
+
strokeLinecap="round"
|
|
52
|
+
strokeLinejoin="round"
|
|
53
|
+
/>
|
|
54
|
+
</svg>
|
|
55
|
+
</button>
|
|
56
|
+
|
|
31
57
|
<div>
|
|
32
|
-
<h2 className="cortex-widget__threads-title">{t('
|
|
58
|
+
<h2 className="cortex-widget__threads-title">{t('translate_history')}</h2>
|
|
33
59
|
<p className="cortex-widget__threads-count">
|
|
34
60
|
{t(threads?.length === 1 ? 'translate_one_conversation' : 'translate_n_conversations', {
|
|
35
61
|
count: threads?.length ?? 0,
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { ToolCallPart, UIMessage } from '@tanstack/ai';
|
|
2
|
+
import { isSettledToolState } from '@cortex/client';
|
|
2
3
|
import { MessageToolCallAnimated } from './MessageToolCallAnimated';
|
|
3
4
|
import { ToolExecuteCodeAnimated } from './ToolExecuteCodeAnimated';
|
|
4
5
|
import { ToolQueryGraphAnimated } from './ToolQueryGraphAnimated';
|
|
@@ -10,13 +11,15 @@ type ToolAnimationProps = {
|
|
|
10
11
|
|
|
11
12
|
/**
|
|
12
13
|
* Which animation stands in for a tool call while the user is not in debug mode.
|
|
13
|
-
* Two tools have a bespoke animation
|
|
14
|
-
*
|
|
15
|
-
*
|
|
14
|
+
* Two tools have a bespoke in-progress animation; once a call settles they fall
|
|
15
|
+
* through to the generic pill like everyone else, so every tool leaves the same
|
|
16
|
+
* quiet done-or-failed mark in the transcript.
|
|
16
17
|
*/
|
|
17
18
|
export function ToolAnimation({ message, toolCallPart }: ToolAnimationProps) {
|
|
18
|
-
if (toolCallPart.
|
|
19
|
-
|
|
19
|
+
if (!isSettledToolState(toolCallPart.state)) {
|
|
20
|
+
if (toolCallPart.name === 'queryGraph') return <ToolQueryGraphAnimated />;
|
|
21
|
+
if (toolCallPart.name === 'executeCode') return <ToolExecuteCodeAnimated />;
|
|
22
|
+
}
|
|
20
23
|
|
|
21
24
|
return <MessageToolCallAnimated toolCallPart={toolCallPart} message={message} />;
|
|
22
25
|
}
|
package/src/context.ts
CHANGED
|
@@ -14,6 +14,8 @@ export type CortexContextValue = {
|
|
|
14
14
|
t: (key: string, params?: Record<string, string | number>) => string;
|
|
15
15
|
api: CortexApiClient;
|
|
16
16
|
debugMode: boolean;
|
|
17
|
+
/** Server capability AND the embedder's `config.attachments` override. */
|
|
18
|
+
attachmentsEnabled: boolean;
|
|
17
19
|
|
|
18
20
|
threads: ThreadSummary[] | undefined;
|
|
19
21
|
selectedThread: ThreadSummary | undefined;
|