@flexkit/studio 0.2.34 → 0.2.35
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/chat-page-IR4RF46H.js +4 -0
- package/dist/chat-page-IR4RF46H.js.map +1 -0
- package/dist/{chunk-CHNQZU2P.js → chunk-7N3LTSVX.js} +2 -2
- package/dist/{chunk-CHNQZU2P.js.map → chunk-7N3LTSVX.js.map} +1 -1
- package/dist/chunk-BTH7HU5Y.js +2 -0
- package/dist/chunk-BTH7HU5Y.js.map +1 -0
- package/dist/chunk-DEG7QP5C.js +30 -0
- package/dist/chunk-DEG7QP5C.js.map +1 -0
- package/dist/{chunk-DFBG7PUJ.js → chunk-FJRDLP7V.js} +4 -4
- package/dist/{chunk-DFBG7PUJ.js.map → chunk-FJRDLP7V.js.map} +1 -1
- package/dist/{chunk-RBGXXVF4.js → chunk-J6EGNRRT.js} +3 -3
- package/dist/{chunk-RBGXXVF4.js.map → chunk-J6EGNRRT.js.map} +1 -1
- package/dist/chunk-KEGJNZLW.js +378 -0
- package/dist/chunk-KEGJNZLW.js.map +1 -0
- package/dist/chunk-PMLDA2FF.js +2 -0
- package/dist/chunk-PMLDA2FF.js.map +1 -0
- package/dist/{chunk-HR4QZ5TD.js → chunk-PWGLA33F.js} +3 -3
- package/dist/chunk-PWGLA33F.js.map +1 -0
- package/dist/chunk-PZWEC6KD.js +2 -0
- package/dist/chunk-PZWEC6KD.js.map +1 -0
- package/dist/{chunk-YC7PBLTK.js → chunk-Q4CWQHBJ.js} +2 -2
- package/dist/{chunk-YC7PBLTK.js.map → chunk-Q4CWQHBJ.js.map} +1 -1
- package/dist/{chunk-PSECMZJC.js → chunk-R6DPAMLC.js} +3 -3
- package/dist/{chunk-PSECMZJC.js.map → chunk-R6DPAMLC.js.map} +1 -1
- package/dist/{chunk-7JA6SI5H.js → chunk-RAUQCO6W.js} +2 -2
- package/dist/{chunk-7JA6SI5H.js.map → chunk-RAUQCO6W.js.map} +1 -1
- package/dist/{chunk-XYFS6X74.js → chunk-RFKMFD2O.js} +2 -2
- package/dist/{chunk-XYFS6X74.js.map → chunk-RFKMFD2O.js.map} +1 -1
- package/dist/{chunk-VRDTHLA3.js → chunk-TI3EHLRE.js} +3 -3
- package/dist/{chunk-VRDTHLA3.js.map → chunk-TI3EHLRE.js.map} +1 -1
- package/dist/chunk-W7JDZHCV.js +2 -0
- package/dist/chunk-W7JDZHCV.js.map +1 -0
- package/dist/chunk-XYE6ZAUB.js +2 -0
- package/dist/{chunk-3OBELKJU.js.map → chunk-XYE6ZAUB.js.map} +1 -1
- package/dist/chunk-ZMONKGWJ.js +4 -0
- package/dist/{chunk-2FCVATRT.js.map → chunk-ZMONKGWJ.js.map} +1 -1
- package/dist/{chunk-6AJRQSFO.js → chunk-ZRTWLY77.js} +3 -3
- package/dist/{chunk-6AJRQSFO.js.map → chunk-ZRTWLY77.js.map} +1 -1
- package/dist/entry-NQRN7SWV.js +2 -0
- package/dist/{entry-APJ4V7PW.js.map → entry-NQRN7SWV.js.map} +1 -1
- package/dist/index.d.ts +5 -1
- package/dist/index.js +7 -7
- package/dist/index.js.map +1 -1
- package/dist/{list-7IHDJM54.js → list-7SCWJXUE.js} +3 -3
- package/dist/{list-7IHDJM54.js.map → list-7SCWJXUE.js.map} +1 -1
- package/dist/list-RPIG75US.js +2 -0
- package/dist/{list-7WFALOUT.js.map → list-RPIG75US.js.map} +1 -1
- package/dist/{pages-BV3ABSFQ.js → pages-KXERA5Z6.js} +3 -3
- package/dist/{pages-BV3ABSFQ.js.map → pages-KXERA5Z6.js.map} +1 -1
- package/dist/{plugin-pages-OWGJPPWV.js → plugin-pages-NXA4BT7Y.js} +2 -2
- package/dist/{plugin-pages-OWGJPPWV.js.map → plugin-pages-NXA4BT7Y.js.map} +1 -1
- package/dist/{project-selector-V5N2724B.js → project-selector-SA6UUVBK.js} +2 -2
- package/dist/{project-selector-V5N2724B.js.map → project-selector-SA6UUVBK.js.map} +1 -1
- package/dist/record-links-RTMCYEPM.js +2 -0
- package/dist/{record-links-3P3XSW66.js.map → record-links-RTMCYEPM.js.map} +1 -1
- package/dist/{root-GBBZ3DX5.js → root-6H6K3YQF.js} +3 -3
- package/dist/{root-GBBZ3DX5.js.map → root-6H6K3YQF.js.map} +1 -1
- package/dist/root-IBZPU2D4.js +23 -0
- package/dist/{root-RGZZYETM.js.map → root-IBZPU2D4.js.map} +1 -1
- package/dist/{root-F2GTYDJM.js → root-MBFQXX4E.js} +2 -2
- package/dist/{root-F2GTYDJM.js.map → root-MBFQXX4E.js.map} +1 -1
- package/dist/root-TSZ3CSJU.js +14 -0
- package/dist/root-TSZ3CSJU.js.map +1 -0
- package/dist/{root-NIL2UHKS.js → root-TZIXWEZO.js} +2 -2
- package/dist/{root-NIL2UHKS.js.map → root-TZIXWEZO.js.map} +1 -1
- package/dist/{root-J62PBDZ2.js → root-W5ZPSNQ2.js} +2 -2
- package/dist/{root-J62PBDZ2.js.map → root-W5ZPSNQ2.js.map} +1 -1
- package/dist/{search-IIGNCQEZ.js → search-ZLEYFT3T.js} +2 -2
- package/dist/{search-IIGNCQEZ.js.map → search-ZLEYFT3T.js.map} +1 -1
- package/dist/{skills-pages-T52MF4DO.js → skills-pages-RPMWIBLS.js} +2 -2
- package/dist/{skills-pages-T52MF4DO.js.map → skills-pages-RPMWIBLS.js.map} +1 -1
- package/dist/source-VYWE5EB5.js +2 -0
- package/dist/{source-IJAAJDGW.js.map → source-VYWE5EB5.js.map} +1 -1
- package/package.json +3 -3
- package/dist/chat-page-7XT4K75G.js +0 -4
- package/dist/chat-page-7XT4K75G.js.map +0 -1
- package/dist/chunk-2FCVATRT.js +0 -4
- package/dist/chunk-3OBELKJU.js +0 -2
- package/dist/chunk-4PUMSUJL.js +0 -30
- package/dist/chunk-4PUMSUJL.js.map +0 -1
- package/dist/chunk-ERDARDGB.js +0 -2
- package/dist/chunk-ERDARDGB.js.map +0 -1
- package/dist/chunk-HR4QZ5TD.js.map +0 -1
- package/dist/chunk-KO2JLLUJ.js +0 -2
- package/dist/chunk-KO2JLLUJ.js.map +0 -1
- package/dist/chunk-PC5Z37LT.js +0 -378
- package/dist/chunk-PC5Z37LT.js.map +0 -1
- package/dist/chunk-U6NFYYTF.js +0 -2
- package/dist/chunk-U6NFYYTF.js.map +0 -1
- package/dist/chunk-XMOSCJOI.js +0 -2
- package/dist/chunk-XMOSCJOI.js.map +0 -1
- package/dist/chunk-YDVO6XWD.js +0 -2
- package/dist/chunk-YDVO6XWD.js.map +0 -1
- package/dist/entry-APJ4V7PW.js +0 -2
- package/dist/list-7WFALOUT.js +0 -2
- package/dist/record-links-3P3XSW66.js +0 -2
- package/dist/root-LYRL7VPN.js +0 -14
- package/dist/root-LYRL7VPN.js.map +0 -1
- package/dist/root-RGZZYETM.js +0 -23
- package/dist/source-IJAAJDGW.js +0 -2
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import'./index.css';import {a}from'./chunk-RFKMFD2O.js';import {f as f$2,b,c,g as g$1,a as a$1,e as e$1,d}from'./chunk-CSUHZFEP.js';import {x,A,u,t,H,o,m,l as l$1,n,p,y,r,s,w,v,k as k$1,e as e$3,G,D,B,g as g$3,j,h as h$1,f as f$3,z,F,I,E,q}from'./chunk-FJRDLP7V.js';import {a as a$2,c as c$2,b as b$2}from'./chunk-ELOJGLAR.js';import'./chunk-QSTWBKPN.js';import {a as a$5,e as e$2,l as l$2,k,d as d$2,g as g$2,h}from'./chunk-PWGLA33F.js';import {c as c$4}from'./chunk-WU2KCXBC.js';import {g,f as f$1,a as a$4}from'./chunk-U6VZY3V2.js';import'./chunk-7N3LTSVX.js';import'./chunk-4ZWQ44NZ.js';import'./chunk-DSLPTDZX.js';import'./chunk-7KLXWCDS.js';import'./chunk-HKN6BX5U.js';import {f,d as d$1}from'./chunk-TI3EHLRE.js';import'./chunk-MBBE4RND.js';import'./chunk-5CVDMZUI.js';import {Nb,M,Lb,Ya,Za,$a,Tb,Wb,Ub,Vb,Xb,Yb,_b,$b,ac,Rb,dc,ec,hc,fc,gc,Gc,cc}from'./chunk-RULCANNM.js';import'./chunk-A4DPLZZF.js';import'./chunk-G5N6HEPW.js';import {l}from'./chunk-5JUG4BEF.js';import'./chunk-S7Z6KKIN.js';import'./chunk-U45E5X3H.js';import {b as b$1,c as c$1,e}from'./chunk-N33S7BSG.js';import {a as a$3,c as c$3}from'./chunk-X3SHNHHM.js';import {useRef,useMemo,useState,useEffect,useLayoutEffect}from'react';import {LoaderCircle,TriangleAlert,CheckCircle2,CornerDownRightIcon,CheckIcon,CopyIcon,PencilIcon}from'lucide-react';import {useParams,useNavigate,useLocation}from'react-router-dom';import ie,{useSWRConfig}from'swr';import {jsx,jsxs}from'react/jsx-runtime';var Nn=1e4,Dn=14,an={queued:"Getting your store ready\u2026",deploying:"Creating 22 entities for catalog, inventory, orders, customers and marketing\u2026",seeding:"Adding the Aven Living sample store\u2026",completed:"Your store is ready",failed:"The starter could not be applied"};function on({canSend:e,onPrompt:t,projectId:n}){let{data:s,mutate:a}=ie(a$5(n),f$1,{refreshInterval:d=>e$2(d?.starter)?Nn:0,revalidateOnFocus:false}),i=s?.starter??null,u=e$2(i),{projectSummaries:x}=f(),b=x.find(d=>d.id===n),A=!b||b.role==="owner",[B,C]=useState(null),[S,v]=useState(false),p=useRef(false);if(useEffect(()=>{u?(p.current=true,l$2({projectId:n})):p.current&&i&&k(i)&&(p.current=false,d$1(n));},[n,u,i]),!i)return null;if(i.state==="failed")return jsxs("div",{className:"fk:mx-auto fk:flex fk:w-full fk:max-w-xl fk:flex-col fk:items-center fk:gap-3 fk:rounded-lg fk:border fk:border-border fk:p-4 fk:text-center fk:text-sm",children:[jsxs("p",{className:"fk:flex fk:items-center fk:gap-2 fk:font-medium",children:[jsx(TriangleAlert,{className:"fk:size-4 fk:text-destructive"}),an.failed]}),jsxs("p",{className:"fk:text-muted-foreground",children:[B??i.error??"Please try again.",A?null:" Ask the project owner to try again."]}),A?jsxs(c$3,{disabled:S,onClick:()=>{v(true),C(null),d$2(n,{template:i.template,sampleData:i.sampleData}).then(async d=>{if(v(false),!d.ok){C(d.message);return}await a({starter:d.starter},{revalidate:false}),l$2({projectId:n});});},size:"sm",variant:"outline",children:[S?jsx(LoaderCircle,{className:"fk:size-4 fk:animate-spin"}):null,"Try again"]}):null]});if(u){let d=i.state==="seeding"&&i.progress?i.progress:null;return jsxs("div",{"aria-live":"polite",className:"fk:mx-auto fk:flex fk:w-full fk:max-w-xl fk:flex-col fk:items-center fk:gap-3 fk:text-center fk:text-sm fk:text-muted-foreground",children:[jsxs("p",{className:"fk:flex fk:items-center fk:gap-2",children:[jsx(LoaderCircle,{className:"fk:size-4 fk:animate-spin"}),an[i.state]]}),d?jsx("div",{className:"fk:h-1.5 fk:w-48 fk:overflow-hidden fk:rounded-full fk:bg-muted",children:jsx("div",{className:"fk:h-full fk:bg-primary fk:transition-[width]",style:{width:`${Math.round(d.done/Math.max(1,d.total)*100).toString()}%`}})}):null,jsx("p",{className:"fk:text-xs",children:"This takes about a minute. You can already ask the agent anything."})]})}return _n(i.completedAt)?i.sampleData?jsxs("div",{className:"fk:mx-auto fk:flex fk:w-full fk:max-w-2xl fk:flex-col fk:items-center fk:gap-3",children:[jsxs("p",{className:"fk:flex fk:items-center fk:gap-2 fk:text-sm fk:text-muted-foreground",children:[jsx(CheckCircle2,{className:"fk:size-4 fk:text-emerald-600"}),"The Aven Living sample store is ready. Try asking:"]}),jsx(je,{canSend:e,onPrompt:t,prompts:g$2})]}):jsxs("p",{className:"fk:mx-auto fk:flex fk:items-center fk:gap-2 fk:text-sm fk:text-muted-foreground",children:[jsx(CheckCircle2,{className:"fk:size-4 fk:text-emerald-600"}),"The commerce starter is ready. Ask the agent to add your products, or to adapt the schema."]}):null}function je({canSend:e,onPrompt:t,prompts:n}){return jsx("div",{className:"fk:flex fk:flex-wrap fk:justify-center fk:gap-2",children:n.map(s=>jsxs("button",{className:"fk:inline-flex fk:max-w-full fk:items-center fk:gap-1.5 fk:rounded-full fk:border fk:border-border/70 fk:bg-muted/40 fk:px-3 fk:py-1.5 fk:text-left fk:text-sm fk:text-muted-foreground fk:transition-colors fk:hover:border-border fk:hover:bg-muted fk:hover:text-foreground fk:disabled:opacity-60 fk:corner-squircle",disabled:!e,onClick:()=>{t(s);},type:"button",children:[jsx(CornerDownRightIcon,{className:"fk:size-3 fk:shrink-0"}),jsx("span",{children:s})]},s))})}function _n(e){let t=e?Date.parse(e):Number.NaN;return Number.isFinite(t)&&Date.now()-t<Dn*24*60*60*1e3}function ln(e,t){let n=Date.parse(e.createdAt)-Date.parse(t.createdAt);return Number.isFinite(n)&&n!==0?n:e.createdAt!==t.createdAt?e.createdAt<t.createdAt?-1:1:e.id===t.id?0:e.id<t.id?-1:1}function pe(e){return [...new Map(e.map(n=>[n.id,n])).values()].sort(ln)}function we(e,t){if(!t)return e;if(!e)return t;let n=new Set(t.messages.map(i=>i.id)),s=t.messages[t.messages.length-1],a=e.messages.filter(i=>!n.has(i.id)&&(!s||ln(i,s)>0));return a.length===0?t:{...t,messages:pe([...t.messages,...a])}}function Ln(e){return e==="pending"||e==="streaming"||e==="awaiting_approval"}function un(e){return e==="queued"||e==="steering"}function Pe(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="assistant"){if(!Ln(n.status))break;return {after:e.slice(t+1),before:e.slice(0,t),live:n}}}return {after:[],before:e,live:null}}function ze(e){return e==="steering"?"Picked up at the next step":e==="queued"?"Sends when this turn ends":null}function fn(e){let t=new Set;for(let n of e)if(!(n.role!=="assistant"||!Array.isArray(n.parts)))for(let s of n.parts){let a=s.type==="data-mid-turn-message"?s.data?.messageId:null;typeof a=="string"&&t.add(a);}return t}function Te(e){return e.find(t=>t.role==="user"&&t.status==="queued"&&t.kind!=="monitor_event")??null}function dn(e){return e.streaming&&!e.hasDraft?"stop":"send"}var qn=6e4,cn=15e3;function Xn(e){if(!e)return 0;if(Pe(e.messages).live||Te(e.messages))return y;if(!e.messages.some(s=>s.role==="assistant"&&s.status==="complete"))return (e.monitors?.length??0)>0?cn:0;let n=new Date(e.chat.lastMessageAt??e.chat.updatedAt).getTime();return Date.now()-n<qn?y:(e.monitors?.length??0)>0?cn:0}function $n(e,t,n){return {chat:{createdAt:n,id:e,lastMessageAt:n,modelId:t,title:null,updatedAt:n},messages:[],pendingApproval:null}}function gn(e,t,n,s,a,i){return e||(t?{chat:t,messages:[],pendingApproval:null}:n||$n(s,a,i))}function pn(e,t){let n=new Set([t.userMessage.id,t.assistantMessage.id]);return {...e,messages:pe([...e.messages.filter(s=>!n.has(s.id)),t.userMessage,t.assistantMessage])}}function Jn(e,t){return {...e,messages:pe([...e.messages.filter(n=>n.id!==t.id),t])}}function Yn(e,t,n){return t?we(e[t],n):n}function Gn(e){return e==="awaiting_approval"?"awaiting_approval":e==="complete"?"success":e==="failed"?"failed":"running"}function qe({attachments:e$1=[],label:t,text:n}){let{textInput:s}=Lb(),[a,i]=useState(false),u=n.trim().length>0;async function x(){await navigator.clipboard.writeText(n),i(true),setTimeout(()=>i(false),1500);}return jsxs("div",{className:"fk:group fk:ml-auto fk:flex fk:w-fit fk:max-w-[70%] fk:flex-col fk:items-end fk:gap-1",children:[jsx(q,{attachments:e$1}),u?jsx("div",{className:"fk:whitespace-pre-wrap fk:rounded-xl fk:bg-muted fk:dark:bg-white/20 fk:px-3.5 fk:py-2 fk:text-base fk:corner-squircle",children:n}):null,t?jsxs("span",{className:"fk:inline-flex fk:items-center fk:gap-1 fk:text-xs fk:text-muted-foreground",children:[jsx(CornerDownRightIcon,{className:"fk:size-3 fk:shrink-0"}),t]}):null,jsxs("div",{className:u?"fk:flex fk:gap-0.5 fk:opacity-0 fk:transition-opacity fk:group-hover:opacity-100":"fk:hidden",children:[jsxs(b$1,{children:[jsx(c$1,{asChild:true,children:jsx(c$3,{"aria-label":"Copy prompt",className:"fk:size-6 fk:text-muted-foreground",size:"icon",variant:"ghost",onClick:()=>{x();},children:a?jsx(CheckIcon,{className:"fk:size-3.5"}):jsx(CopyIcon,{className:"fk:size-3.5"})})}),jsx(e,{children:"Copy"})]}),jsxs(b$1,{children:[jsx(c$1,{asChild:true,children:jsx(c$3,{"aria-label":"Edit prompt",className:"fk:size-6 fk:text-muted-foreground",size:"icon",variant:"ghost",onClick:()=>s.setInput(n),children:jsx(PencilIcon,{className:"fk:size-3.5"})})}),jsx(e,{children:"Edit"})]})]})]})}function vn(e){let n=e.find(s=>s.type==="data-suggested-prompt")?.data?.prompt;return typeof n=="string"&&n.trim()?n:null}function An({prompt:e}){let{textInput:t}=Lb();return jsx("div",{className:"fk:flex fk:justify-start",children:jsxs("button",{className:"fk:inline-flex fk:max-w-full fk:items-center fk:gap-1.5 fk:rounded-full fk:border fk:border-border/70 fk:bg-muted/40 fk:px-3 fk:py-1.5 fk:text-left fk:text-sm fk:text-muted-foreground fk:transition-colors fk:hover:border-border fk:hover:bg-muted fk:hover:ext-foreground fk:corner-squircle",title:"Use as your next message",type:"button",onClick:()=>t.setInput(e),children:[jsx(CornerDownRightIcon,{className:"fk:size-3 fk:shrink-0"}),jsx("span",{className:"fk:truncate",children:e})]})})}function Wn({api:e,part:t,partIndex:n,parts:s}){return t.type.startsWith("tool-")?t.state==="output-error"?jsx(G,{message:t.errorText??"The tool call failed."}):null:jsx(F,{api:e,part:t,partIndex:n,parts:s})}function mn({api:e,message:t,showSuggestion:n=false}){if(t.kind==="monitor_event"){let u=r(t);return u?jsx(s,{data:u,error:t.error}):null}if(t.kind==="plugin_connected"){let u=w(t.parts);return u?jsx(v,{data:u,error:t.error,label:ze(t.status)}):null}if(t.role==="user")return jsx(qe,{attachments:k$1(t.parts),label:ze(t.status),text:t.textContent});let s$1=(Array.isArray(t.parts)?t.parts:[]).filter(u=>!e$3(u)&&!(u.type.startsWith("tool-")&&u.state!=="output-error")),a=s$1.some(u=>u.type==="data-turn-error"),i=n&&!t.error?vn(s$1):null;return s$1.length===0&&!t.error?null:jsxs("div",{className:"fk:w-full fk:min-w-0 fk:space-y-8",children:[s$1.map((u,x)=>jsx(Wn,{api:e,part:u,partIndex:x,parts:s$1},u.toolCallId??`${t.id}-${x.toString()}`)),t.error&&!a?jsx(G,{message:t.error}):null,i?jsx(An,{prompt:i}):null]})}function Vn({api:e,chatId:t,detail:n,message:s,onMidTurnDelivered:a,onStatusChange:i,onTurnUpdated:u,questionAnsweredSignal:x}){let b=Gn(s.status),A=s.workflowRunId?e.getAgentChatStreamUrl(t,s.workflowRunId):"",[B$1,C]=useState(0),[S,v]=useState(false),[p,d]=useState({}),D$1=useRef(null),{message:y,status:M}=D(A,{decidedApprovals:p,recordStatus:b,resumeToken:B$1,suppressApprovalPause:S}),U=useMemo(()=>y?[{...y,parts:y.parts.filter(g=>!e$3(g))}]:[],[y]),_=B(U),X=useRef(u);X.current=u;let $=useRef(i);$.current=i;let J=useMemo(()=>({answerQuestion:async(g,H)=>{let{question:j}=await e.answerAgentChatQuestion(t,g,H);return v(true),C(ue=>ue+1),X.current(),j??null},onApprovalDecided:(g,H)=>{g&&H&&H!=="pending"&&d(j=>({...j,[g]:H})),!(g&&D$1.current===g)&&(g&&(D$1.current=g),v(true),C(j=>j+1),X.current());}}),[e,t]);useEffect(()=>{C(0),v(false),D$1.current=null,d({});},[s.id]);let c=useRef(x);useEffect(()=>{x!==c.current&&(c.current=x,x?.messageId===s.id&&(v(true),C(g=>g+1)));},[s.id,x]),useEffect(()=>{S&&s.status==="streaming"&&v(false);},[s.status,S]),useEffect(()=>{(M==="finished"||M==="paused")&&X.current();},[M]);let F$1=(y?.parts??[]).filter(g=>g.type==="data-mid-turn-message").map(g=>String(g.data?.messageId??"")).join(`
|
|
2
|
+
`),V=useRef(a);V.current=a,useEffect(()=>{F$1&&V.current(F$1.split(`
|
|
3
|
+
`));},[F$1]);let f=!S&&s.status!=="streaming"&&(s.status==="awaiting_approval"||M==="paused"||g$3(y)||j(y)),K=useMemo(()=>new Set(h$1(y)),[y]),L=n.pendingApproval&&!K.has(n.pendingApproval.id)?n.pendingApproval:null,Z=y?.parts[y.parts.length-1],R=Z?.type==="text"&&Z.state==="streaming",re=j(y)?"Waiting for your answer":"Awaiting approval",se=f?re:f$3(y)??"Thinking",P=f?M!=="finished"&&M!=="error":M==="streaming"&&!R;useEffect(()=>{$.current({label:se,visible:P});},[se,P]);let N=!!L&&f,ae=M==="finished"?vn(_.flatMap(g=>g.parts)):null;return _.length===0&&!N?jsx(z.Provider,{value:J,children:null}):jsx(z.Provider,{value:J,children:jsxs("div",{className:"fk:w-full fk:min-w-0 fk:space-y-8",children:[_.map(g=>jsx("div",{className:"fk:space-y-8 fk:min-w-0",children:g.parts.map((H,j)=>jsx(F,{api:e,part:H,partIndex:j,parts:g.parts},j))},g.id)),L&&N?jsx(I,{api:e,message:E(L)}):null,ae?jsx(An,{prompt:ae}):null]})})}function Zn({draftKey:e}){let{textInput:t}=Lb(),{setInput:n,value:s}=t,a=useRef(null);return useLayoutEffect(()=>{if(a.current===e){c$2(e,s);return}a.current=e;let i=b$2(e);i!==s&&n(i);},[e,n,s]),null}function er({onRestored:e,text:t}){let{textInput:n}=Lb(),{setInput:s}=n;return useEffect(()=>{t!==null&&(s(t),e(null));},[e,s,t]),null}function tr({api:e,effort:t,modelKey:n$1,modelPending:s,models:a,onEffortChange:i,onError:u,onModelChange:x,onSend:b$1,onStop:A,placeholder:B,sending:C,streaming:S}){let{attachments:v,textInput:p$1}=Lb(),d$1=o(e,u),{currentProjectId:D}=f(),{data:y,error:M}=ie(D?`/api/flexkit/${D}/plugins`:null,f$1),U=useRef(false),_=a.filter(f=>!f.deprecated||b(f)===n$1),X=c(a,n$1),$=e$1(X),J=d(X,t),c$1=p$1.value.trim().length>0||v.files.length>0,F=dn({hasDraft:c$1,streaming:S}),V=c$1&&!d$1.isUploading&&!C&&!s;return jsxs(Tb,{accept:n,className:"fk:mx-auto fk:max-w-4xl",maxFileSize:l$1,maxFiles:m,multiple:true,onError:f=>u(f.message),onSubmit:({text:f})=>{let K=f?.trim()??"",L=d$1.getUploaded(v.files.map(R=>R.id));if(!K&&L.length===0||d$1.isUploading||C||U.current||s||!y&&!M&&D)return Promise.reject(new Error("The message cannot be sent right now."));let Z=c$4(K,y?.plugins??[]);return Z?(p$1.setInput(Z.tokens.reduce((R,re)=>R.split(re).join(""),f)),u(`That looks like a ${Z.label}. It was removed from your message: connect ${Z.plugin.name} from its connect card or AI \u2192 Plugins instead, where it is stored encrypted and never shown to the agent.`),Promise.reject(new Error("The message contains a plugin token."))):(U.current=true,p$1.clear(),b$1(K,L).catch(R=>{throw p$1.setInput(f),R}).finally(()=>{U.current=false;}))},children:[v.files.length>0?jsx(Wb,{children:jsx(p,{uploads:d$1})}):null,jsx(Ub,{children:jsx(Vb,{disabled:C,placeholder:B})}),jsxs(Xb,{children:[jsxs(Yb,{children:[jsxs(_b,{children:[jsx($b,{"aria-label":"Add attachments",className:"fk:border-0 fk:bg-border fk:corner-round",disabled:C,tooltip:"Add photos or files"}),jsx(ac,{children:jsx(Rb,{})})]}),_.length>0?jsxs(dc,{value:n$1??void 0,onValueChange:x,children:[jsx(ec,{"aria-label":"Model",className:"fk:min-w-44",children:jsx(hc,{placeholder:"Model"})}),jsx(fc,{children:_.map(f=>jsx(gc,{value:b(f),children:f.name},b(f)))})]}):null,$.length>1&&J?jsxs(dc,{value:J,onValueChange:i,children:[jsx(ec,{"aria-label":"Reasoning effort",className:"fk:min-w-28",children:jsx(hc,{placeholder:"Effort"})}),jsx(fc,{children:$.map(f=>jsx(gc,{value:f.value,children:f.label},f.value))})]}):null]}),jsxs("div",{className:"fk:flex fk:items-center fk:gap-3",children:[jsx(Gc,{disabled:C,onAudioRecorded:async(f,K)=>{let{text:L}=await e.transcribeAgentAudio(f,K);return L},onError:f=>u(f.message),onTranscriptionChange:f=>{u(null),p$1.setInput(a$4(p$1.value,f));}}),jsx(cc,{className:"fk:corner-round",disabled:F==="stop"?false:!V,status:F==="stop"?"streaming":void 0,onStop:()=>{A();}})]})]})]})}var Qe={chatId:null,error:null,loading:false,older:[],page:null},nr=3e3;function rr({api:e,chatId:t,projectId:n,pendingFollowUp:s,pendingMessage:a,questionAnsweredSignal:i,resolveDetail:u}){let{data:x,mutate:b}=ie(t?g(n).agentChat(t):null,f$1,{refreshInterval:0}),A=u(x),[B,C]=useState(Qe),S=B.chatId===t?B:Qe,v=useRef(t);v.current=t;let p=(o,k)=>C(w=>{if(w.chatId!==o&&v.current!==o)return w;let O=w.chatId===o?w:{...Qe,chatId:o};return {...O,...k(O)}}),d=useRef({chatId:null,messages:[]}),D=A?.messages;useEffect(()=>{let o=d.current,k=D??[];if(d.current={chatId:t,messages:k},!t||o.chatId!==t)return;let w=new Set(k.map(z=>z.id)),O=o.messages.filter(z=>!w.has(z.id));O.length>0&&p(t,z=>({older:pe([...z.older,...O])}));},[t,D]);let y=new Set(A?.messages.map(o=>o.id)??[]),M=[...S.older.filter(o=>!y.has(o.id)),...A?.messages??[]],U=useRef(A);U.current=A;let _=useRef(void 0);ie(t?`${g(n).agentChat(t)}?view=status`:null,f$1,{refreshInterval:()=>Xn(U.current),onSuccess:o=>{let k=JSON.stringify(o),w=_.current;_.current=k;let{current:O}=U,z=O?[...O.messages].reverse().find(fe=>fe.role==="assistant"):void 0;(w&&w!==k||z&&o.latestMessage&&(z.id!==o.latestMessage.id||z.status!==o.latestMessage.status||z.workflowRunId!==o.latestMessage.workflowRunId||O?.chat.updatedAt!==o.chat.updatedAt))&&b();}});let X=async()=>{let o=S.page?.cursor??A?.nextCursor;if(!t||!o||S.loading)return;let k=t;p(k,()=>({error:null,loading:true}));try{let w=await f$1(`${g(n).agentChat(k)}?before=${encodeURIComponent(o)}`);p(k,O=>({loading:!1,older:pe([...w.messages,...O.older]),page:{cursor:w.nextCursor??null,hasMore:w.hasMore??!1}}));}catch{p(k,()=>({error:"Could not load earlier messages. Try again.",loading:false}));}},{after:$,before:J,live:c}=Pe(M),[F,V]=useState({ids:[],messageId:""}),f=fn(M);for(let o of c&&F.messageId===c.id?F.ids:[])f.add(o);let K=$.filter(o=>un(o.status)&&!f.has(o.id)),L=J.filter(o=>!f.has(o.id)),R=(!c&&!a?Te(M):null)?.id??null,[re,se]=useState(0),P=useRef(null);useEffect(()=>{if(!t||!R||P.current===R)return;P.current=R;let o=false,k=null;return e.startQueuedAgentChatMessage(t,R).then(()=>{},()=>{k=setTimeout(()=>{o||se(w=>w+1);},nr);}).finally(()=>{P.current=null,b();}),()=>{o=true,k&&clearTimeout(k);}},[e,t,b,R,re]);let[N,ae]=useState(null),g$1=c&&N?.messageId===c.id?N.status:null;if(t&&!A&&!a)return jsxs("div",{className:"fk:flex fk:flex-1 fk:items-center fk:justify-center fk:gap-2 fk:text-sm fk:text-muted-foreground",children:[jsx(LoaderCircle,{className:"fk:size-4 fk:animate-spin"}),"Loading chat..."]});let H$1=!!a||!!c,j=[...L].reverse().find(o=>o.role==="assistant")?.id??null,ue=c?g$1?.label??"Thinking":"Sending",oe=c?g$1?.visible??true:true;return jsxs(Ya,{className:"fk:h-0 fk:min-h-0 fk:flex-1",children:[jsx(Za,{className:"fk:gap-0 fk:p-0",children:jsxs("div",{className:"fk:mx-auto fk:w-full fk:max-w-4xl fk:space-y-5 fk:pb-6 fk:pr-4",children:[S.page?.hasMore??A?.hasMore?jsx(c$3,{variant:"ghost",disabled:S.loading,onClick:()=>{X();},children:S.loading?"Loading\u2026":"Load earlier messages"}):null,S.error?jsx("p",{role:"alert",children:S.error}):null,L.map(o=>jsx(mn,{api:e,message:o,showSuggestion:!H$1&&o.id===j},o.id)),c&&t&&A?jsx(Vn,{api:e,chatId:t,detail:A,message:c,onMidTurnDelivered:o=>V({ids:o,messageId:c.id}),onStatusChange:o=>ae({messageId:c.id,status:o}),onTurnUpdated:()=>{b();},questionAnsweredSignal:i}):null,a&&!c?jsx(qe,{attachments:a.attachments,text:a.text}):null,H$1?jsx(H,{label:ue,visible:oe}):null,K.map(o=>jsx(mn,{api:e,message:o},o.id)),s&&c?jsx(qe,{attachments:s.attachments,text:s.text}):null]})}),jsx($a,{})]})}var hn=["Where should we begin?","Ready when you are","What\u2019s on the agenda today?","What\u2019s on your mind today?"];function sr(e){return [`How can I help, ${e}?`,`Good to see you, ${e}.`,`Hey, ${e}. Ready to dive in?`]}function ar(e){let t=e?[...hn,...sr(e)]:hn;return t[Math.floor(Math.random()*t.length)]??"How can I help?"}var Cn="flexkit-ai:lastModelId",Xe="flexkit-ai:lastEffort";function or(){if(typeof localStorage>"u")return null;try{let e=localStorage.getItem(Cn);return e?{effort:localStorage.getItem(Xe),modelKey:e}:null}catch{return null}}function lr(e){return e.selectedModelKey?{effort:e.selectedEffort,modelKey:e.selectedModelKey}:e.awaitingChatModel?{effort:null,modelKey:null}:e.chatSelection?{effort:e.selectedEffort??e.chatSelection.effort,modelKey:e.chatSelection.modelKey}:e.lastUsed?{effort:e.selectedEffort??e.lastUsed.effort,modelKey:e.lastUsed.modelKey}:{effort:e.selectedEffort,modelKey:e.defaultModelKey}}function ir(e){if(!(typeof localStorage>"u"))try{localStorage.setItem(Cn,e.modelKey),e.effort?localStorage.setItem(Xe,e.effort):localStorage.removeItem(Xe);}catch{}}function ur({canSend:e,hasSchema:t,onPrompt:n,projectId:s}){let{data:a,isLoading:i}=ie(g(s).agentProfile(),f$1),u=useMemo(()=>i?null:ar(a?.preferredName??null),[a,i]);return jsxs("div",{className:"fk:flex fk:flex-col fk:items-center fk:gap-6 fk:pb-2 fk:text-center",children:[jsx("h2",{className:"fk:text-2xl fk:font-semibold",children:u??"\xA0"}),jsx(on,{canSend:e,onPrompt:n,projectId:s}),t?null:jsx(fr,{canSend:e,onPrompt:n,projectId:s})]})}function fr({canSend:e,onPrompt:t,projectId:n}){let{data:s,error:a}=ie(a$5(n),f$1,{revalidateOnFocus:false});return s===void 0&&a===void 0||s?.starter?null:jsxs("div",{className:"fk:mx-auto fk:flex fk:w-full fk:max-w-2xl fk:flex-col fk:items-center fk:gap-3",children:[jsx("p",{className:"fk:text-sm fk:text-muted-foreground",children:"This project has no schema yet. Start with:"}),jsx(je,{canSend:e,onPrompt:t,prompts:h})]})}function qr(){let{api:e$1,projectId:t$1}=x(),{currentProject:n,projectSummaries:s}=f(),{chatId:a$4}=useParams(),i=useNavigate(),u$1=useLocation(),x$1=a(),{mutate:b$2}=useSWRConfig(),{data:A$1}=ie(t$1?g(t$1).tools():null,f$1),{data:B}=ie(t$1&&a$4?g(t$1).agentChat(a$4):null,f$1),C=useRef({});function S(l){return Yn(C.current,a$4,l)}let v=S(B),p=useMemo(()=>A$1?.tools.models??[],[A$1]),[d,D]=useState(null),[y,M$1]=useState(null),U=useRef(null),[_,X]=useState(or),[$,J]=useState(false),c$2=useRef(false),[F,V]=useState(null),f$3=F&&F.chatId===a$4?F:void 0,[K,L]=useState(null),[Z,R]=useState(null),re=K&&K.chatId===a$4?K:void 0,[se,P]=useState(null),N=v?.chat.modelId??null,ae=!!a$4&&v===void 0,g$2=useMemo(()=>f$2(N,p)??(N?{effort:null,modelKey:N}:null),[N,p]),H=useMemo(()=>{let l=p.find(h=>!h.deprecated);return l?b(l):null},[p]),j=useMemo(()=>{let l=c(p,_?.modelKey??null);return _&&l&&!l.deprecated?_:null},[p,_]),{effort:ue,modelKey:oe}=lr({awaitingChatModel:ae,chatSelection:g$2,defaultModelKey:H,lastUsed:j,selectedEffort:y,selectedModelKey:d}),o=oe?g$1({effort:ue,modelKey:oe},p):null,k=ae&&!d;useEffect(()=>{U.current=null,D(null),M$1(null),P(null);},[a$4]),useEffect(()=>{d===a$1&&N&&N!==a$1&&N!==U.current&&(D(null),M$1(null));},[N,d]);function w(l){X(l),ir(l);}function O(l){U.current=l===a$1?N:null,D(l),M$1(null),w({effort:null,modelKey:l});}function z(l){M$1(l),oe&&w({effort:l,modelKey:oe});}let fe=u$1.state?.onboardingPrompt,$e=useRef(null),[Sn,Je]=useState(null);if(useEffect(()=>{!fe||$e.current===u$1.key||a$4||!t$1||!e$1||!A$1||k||c$2.current||($e.current=u$1.key,i(u$1.pathname,{replace:true,state:null}),ve(fe,[]).catch(l=>{Je(fe),P(l instanceof Error?l.message:"Failed to send the message.");}));},[e$1,a$4,u$1.key,k,fe,t$1,A$1]),!t$1||!e$1)return jsx("div",{className:"fk:flex fk:h-full fk:items-center fk:justify-center fk:text-sm fk:text-muted-foreground",children:"Select a project to chat with the agent."});let te=e$1,de=t$1,yn=n?.title??s.find(l=>l.id===t$1)?.name??"your project",Ye=!a$4&&!f$3,ke=!!(v&&Pe(v.messages).live);async function Mn(l,h,Y){L({attachments:Y,chatId:l,text:h});try{let I=await te.sendAgentChatFollowUp(l,{attachments:Y,content:h,modelId:o});if("question"in I){R({messageId:I.question.chatMessageId}),await b$2(g(de).agentChat(l));return}await Ge(l,I);}finally{L(null);}}async function Ge(l,h){await b$2(g(de).agentChat(l),Y=>{let I=gn(we(C.current[l],Y),null,B,l,o,"turn"in h?h.turn.userMessage.createdAt:h.followUp.message.createdAt),le="turn"in h?pn(I,h.turn):Jn(I,h.followUp.message);return C.current[l]=le,le},{revalidate:false});}let xn={onConnected:async l=>{if(!a$4)return;let h=a$4;try{await Ge(h,await te.announcePluginConnected(h,l));}catch(Y){P(Y instanceof Error?Y.message:"The agent could not continue after the connection.");}}};async function ve(l,h){if(c$2.current)throw new Error("A message is already being sent.");if(k)throw new Error("This chat is still loading.");c$2.current=true,J(true),P(null);let Y=v?Te(v.messages):null;if(a$4&&(ke||Y)){try{!ke&&Y&&await te.startQueuedAgentChatMessage(a$4,Y.id).catch(()=>{}),await Mn(a$4,l,h);}catch(I){throw P(I instanceof Error?I.message:"Failed to send the message."),I}finally{c$2.current=false,J(false);}return}V({attachments:h,chatId:a$4,text:l});try{let I=a$4?{chat:null,turn:await te.sendAgentChatMessage(a$4,{attachments:h,content:l,modelId:o})}:await te.startAgentChat({attachments:h,content:l,modelId:o}),{chat:le,turn:We}=I,Ae=a$4??le.id;await b$2(g(de).agentChat(Ae),Pn=>{let Ve=pn(gn(we(C.current[Ae],Pn),le,B,Ae,o,We.userMessage.createdAt),We);return C.current[Ae]=Ve,Ve},{revalidate:!1}),le&&i(`${x$1}/chats/${le.id}`),V(null);}catch(I){throw V(null),P(I instanceof Error?I.message:"Failed to send the message."),I}finally{c$2.current=false,J(false);}}async function wn(){if(a$4)try{await te.stopAgentChat(a$4);}catch(l){P(l instanceof Error?l.message:"Failed to stop the turn.");}finally{await b$2(g(de).agentChat(a$4));}}return jsxs(Nb,{children:[jsx(Zn,{draftKey:a$2(de,a$4)}),jsx(er,{onRestored:Je,text:Sn}),jsxs("div",{className:"fk:flex fk:h-full fk:min-h-0 fk:flex-col fk:gap-2",children:[jsxs("div",{className:"fk:mb-2 fk:flex fk:shrink-0 fk:items-start fk:gap-2",children:[jsxs(b$1,{children:[jsx(c$1,{asChild:true,children:jsx(M,{className:"fk:-ml-1 fk:h-4 fk:w-4"})}),jsx(e,{children:"Toggle Sidebar"})]}),jsx(l,{orientation:"vertical",className:"fk:mt-1 fk:h-4"}),jsx("div",{className:"fk:flex fk:flex-1 fk:items-center fk:gap-2",children:jsx("h1",{className:"fk:truncate fk:text-lg fk:font-semibold fk:leading-none fk:tracking-tight",children:a$4?v?.chat.title?.trim()??"Chat":"Agent"})})]}),jsx("div",{className:"fk:flex fk:min-h-0 fk:flex-1 fk:gap-4",children:jsxs("div",{className:a$3("fk:flex fk:min-h-0 fk:min-w-0 fk:flex-1 fk:flex-col fk:gap-3",Ye&&"fk:justify-center fk:pb-[12vh]"),children:[Ye?jsx(ur,{canSend:!$&&!k,hasSchema:n?n.schema.some(l=>!l.name.startsWith("_")):true,onPrompt:l=>{ve(l,[]).catch(h=>{P(h instanceof Error?h.message:"Failed to send the message.");});},projectId:de}):jsx(A.Provider,{value:true,children:jsx(u.Provider,{value:xn,children:jsx(rr,{api:te,chatId:a$4??null,pendingFollowUp:re,pendingMessage:f$3,projectId:t$1,questionAnsweredSignal:Z,resolveDetail:S})})}),jsxs("div",{className:"fk:shrink-0 fk:pb-3",children:[a$4?jsx(t,{api:te,chatId:a$4,projectId:t$1,sending:$||k,onTurnIntoAutomation:l=>{c$2.current||k||ve(`Turn the monitor \u201C${l.description}\u201D into an automation.`,[]).catch(h=>P(h instanceof Error?h.message:"Failed to send the message."));}}):null,se?jsx("p",{className:"fk:mx-auto fk:mb-2 fk:max-w-4xl fk:text-xs fk:text-destructive",children:se}):null,jsx(tr,{api:te,effort:ue,modelKey:oe,modelPending:k,models:p,sending:$,streaming:ke,onEffortChange:z,onError:P,onModelChange:O,onSend:ve,onStop:wn,placeholder:ke?"Add context or steer the agent...":`Ask Flexkit anything about ${yn}...`})]})]})})]})]})}export{qr as AgentChatPage};//# sourceMappingURL=chat-page-IR4RF46H.js.map
|
|
4
|
+
//# sourceMappingURL=chat-page-IR4RF46H.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/apps/ai/agent/starter-panel.tsx","../src/apps/ai/agent/chat-history.ts","../src/apps/ai/agent/follow-ups.ts","../src/apps/ai/agent/chat-page.tsx"],"names":["POLL_MS","SAMPLE_PROMPTS_DAYS","STATE_LABELS","StarterPanel","canSend","onPrompt","projectId","data","mutate","useSWR","starterPath","fetcher","latest","isStarterRunning","starter","running","projectSummaries","useConfig","summary","project","canRetry","retryError","setRetryError","useState","retrying","setRetrying","seenRunning","useRef","useEffect","watchStarter","starterSchemaDeployed","revalidateProjectSchema","jsxs","jsx","TriangleAlert","Button","applyStarter","outcome","LoaderCircle","progress","isRecent","CheckCircle2","StarterPrompts","COMMERCE_STARTER_PROMPTS","prompts","prompt","CornerDownRightIcon","completedAt","time","compareChatMessages","a","b","byTime","sortChatMessages","messages","message","mergeChatDetail","current","incoming","incomingIds","newest","retained","isActiveTurnStatus","status","isFollowUpStatus","splitLiveTurn","index","getFollowUpLabel","getDeliveredMidTurnMessageIds","ids","part","messageId","getNextQueuedMessage","getComposerAction","input","TITLE_POLL_TIMEOUT_MS","MONITOR_POLL_MS","getChatDetailRefreshInterval","latestData","STREAM_RETRY_DELAY_MS","lastActivity","createFallbackChatDetail","chatId","modelId","timestamp","getSeedBaseDetail","createdChat","cachedDetail","appendTurnToDetail","detail","turn","turnIds","appendMessageToDetail","item","resolveSeededChatDetail","seeds","getTurnRecordStatus","UserBubble","attachments","label","text","textInput","usePromptInputController","copied","setCopied","hasText","handleCopy","MessageAttachments","Tooltip","TooltipTrigger","CheckIcon","CopyIcon","TooltipContent","PencilIcon","getSuggestedPrompt","parts","candidate","SuggestedPromptChip","PersistedPart","api","partIndex","ToolErrorLine","MessagePart","HistoryMessage","showSuggestion","monitorEvent","getMonitorEventData","MonitorEventCard","connected","getPluginConnectedData","PluginConnectedNotice","getAttachmentsFromParts","isHiddenReplayPart","hasTurnErrorPart","suggestedPrompt","LiveTurn","onMidTurnDelivered","onStatusChange","onTurnUpdated","questionAnsweredSignal","recordStatus","streamApi","resumeToken","setResumeToken","suppressApprovalPause","setSuppressApprovalPause","decidedApprovals","setDecidedApprovals","lastDecidedApprovalIdRef","streamMessage","useRunStream","rawMessages","useMemo","sessionMessages","useSessionMessages","onTurnUpdatedRef","onStatusChangeRef","replayActions","questionId","response","question","approvalId","decidedStatus","seenQuestionSignalRef","deliveredKey","onMidTurnDeliveredRef","isAwaitingApproval","messageHasPendingMutationApproval","messageHasPendingUserQuestion","streamApprovalIds","getMutationApprovalIds","fallbackApproval","lastPart","contentIsStreaming","awaitingLabel","statusLabel","getLiveStatusLabel","statusVisible","showFallbackApproval","liveSuggestedPrompt","sessionMessage","RunReplayActionsContext","MutationApprovalPart","toMutationApprovalPartData","ComposerDraftSync","draftKey","setInput","value","activeKeyRef","useLayoutEffect","writeComposerDraft","draft","readComposerDraft","ComposerRestore","onRestored","ChatComposer","effort","modelKey","modelPending","models","onEffortChange","onError","onModelChange","onSend","onStop","placeholder","sending","streaming","uploads","useAttachmentUploads","currentProjectId","marketplace","marketplaceError","submittingRef","selectableModels","model","getModelKey","selectedModel","findModelByKey","effortOptions","getEffortOptions","effectiveEffort","coerceEffort","hasDraft","action","canSubmit","PromptInput","ATTACHMENT_ACCEPT","ATTACHMENT_MAX_BYTES","ATTACHMENTS_MAX_PER_MESSAGE","error","trimmed","sentAttachments","file","pasted","findPastedPluginToken","rest","token","PromptInputHeader","ComposerAttachments","PromptInputBody","PromptInputTextarea","PromptInputFooter","PromptInputTools","PromptInputActionMenu","PromptInputActionMenuTrigger","PromptInputActionMenuContent","PromptInputActionAddAttachments","PromptInputSelect","PromptInputSelectTrigger","PromptInputSelectValue","PromptInputSelectContent","PromptInputSelectItem","option","SpeechInput","audioBlob","signal","transcript","appendDictatedText","PromptInputSubmit","EMPTY_CHAT_HISTORY","QUEUED_START_RETRY_MS","ChatConversation","pendingFollowUp","pendingMessage","resolveDetail","rawDetail","paths","historyState","setHistoryState","history","activeChatRef","updateHistory","forChatId","patch","base","windowRef","windowMessages","previous","next","nextIds","dropped","currentIds","detailRef","priorStatus","signature","loadOlder","cursor","requestChatId","result","followUpMessages","earlierMessages","liveMessage","liveDeliveredIds","setLiveDeliveredIds","deliveredIds","id","waitingFollowUps","historyMessages","nextQueuedId","queuedStartAttempt","setQueuedStartAttempt","queuedStartInFlightRef","cancelled","retry","attempt","reportedStatus","setReportedStatus","liveStatus","turnActive","latestAssistantId","Conversation","ConversationContent","TurnStatusLine","ConversationScrollButton","GENERIC_GREETINGS","getNamedGreetings","name","pickGreeting","preferredName","greetings","LAST_AGENT_MODEL_STORAGE_KEY","LAST_AGENT_EFFORT_STORAGE_KEY","readLastAgentModel","stored","resolveComposerSelection","writeLastAgentModel","selection","EmptyConversation","hasSchema","isLoading","greeting","EmptySchemaPrompts","EMPTY_STARTER_PROMPTS","AgentChatPage","useProjectApi","currentProject","useParams","navigate","useNavigate","location","useLocation","agentBase","useAgentBasePath","globalMutate","useSWRConfig","toolsData","rawChatDetail","seededDetailRef","chatDetail","selectedModelKey","setSelectedModelKey","selectedEffort","setSelectedEffort","autoPickedOnModelIdRef","rememberedModel","setRememberedModel","setSending","sendingRef","setPendingMessage","visiblePendingMessage","setPendingFollowUp","setQuestionAnsweredSignal","visiblePendingFollowUp","sendError","setSendError","chatModelId","awaitingChatModel","chatSelection","parseModelSelection","defaultModelKey","lastUsed","formatModelSelection","AUTO_MODEL_KEY","rememberModel","handleModelChange","nextModelKey","handleEffortChange","nextEffort","onboardingPrompt","handledPromptKeyRef","promptToRestore","setPromptToRestore","handleSend","chatApi","chatProjectId","projectName","isNewChat","turnInProgress","sendFollowUp","targetChatId","showSentMessage","pluginConnect","pluginId","queuedBeforeThis","started","chat","handleStop","PromptInputProvider","getComposerDraftKey","SidebarTrigger","Separator","cn","entity","ChatApprovalContext","PluginConnectContext","MonitorChips","monitor"],"mappings":"m7CAiBA,IAAMA,EAAAA,CAAU,GAAA,CAGVC,EAAAA,CAAsB,EAAA,CAEtBC,EAAAA,CAA8D,CAClE,MAAA,CAAQ,gCAAA,CACR,UAAW,oFAAA,CACX,OAAA,CAAS,2CAAA,CACT,SAAA,CAAW,qBAAA,CACX,MAAA,CAAQ,kCACV,CAAA,CAOO,SAASC,EAAAA,CAAa,CAC3B,OAAA,CAAAC,CAAAA,CACA,QAAA,CAAAC,EACA,SAAA,CAAAC,CACF,CAAA,CAIuB,CAGrB,GAAM,CAAE,IAAA,CAAAC,CAAAA,CAAM,MAAA,CAAAC,CAAO,CAAA,CAAIC,EAAAA,CAA0CC,GAAAA,CAAYJ,CAAS,EAAGK,GAAAA,CAAS,CAClG,eAAA,CAAkBC,CAAAA,EAAYC,GAAAA,CAAiBD,CAAAA,EAAQ,OAAO,CAAA,CAAIZ,EAAAA,CAAU,CAAA,CAC5E,iBAAA,CAAmB,KACrB,CAAC,CAAA,CACKc,EAAUP,CAAAA,EAAM,OAAA,EAAW,IAAA,CAC3BQ,CAAAA,CAAUF,GAAAA,CAAiBC,CAAO,CAAA,CAClC,CAAE,gBAAA,CAAAE,CAAiB,CAAA,CAAIC,CAAAA,EAAU,CACjCC,CAAAA,CAAUF,EAAiB,IAAA,CAAMG,CAAAA,EAAYA,CAAAA,CAAQ,EAAA,GAAOb,CAAS,CAAA,CAErEc,CAAAA,CAAW,CAACF,CAAAA,EAAWA,CAAAA,CA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AA2U,EAAAA,CAAU,EACvF,IAAA,CACJ3U,GAAAA,CAACkK,GAAA,CACC,GAAA,CAAK6L,GACL,MAAA,CAAQ5L,EAAAA,CACR,SAAUC,EAAAA,CACV,YAAA,CAAcC,CAAAA,CACd,MAAA,CAAQC,CAAAA,CACR,OAAA,CAASO,EACT,SAAA,CAAWsL,EAAAA,CACX,eAAgBX,CAAAA,CAChB,OAAA,CAASZ,EACT,aAAA,CAAeU,CAAAA,CACf,MAAA,CAAQQ,EAAAA,CACR,MAAA,CAAQc,EAAAA,CACR,YACET,EAAAA,CAAiB,mCAAA,CAAsC,8BAA8BF,EAAW,CAAA,GAAA,CAAA,CAEpG,GACF,CAAA,CAAA,CACF,CAAA,CACF,CAAA,CAAA,CACF,CAAA,CAAA,CACF,CAEJ","file":"chat-page-IR4RF46H.js","sourcesContent":["import { useEffect, useRef, useState, type JSX } from 'react';\nimport { CheckCircle2, CornerDownRightIcon, LoaderCircle, TriangleAlert } from 'lucide-react';\nimport useSWR from 'swr';\nimport {\n applyStarter,\n COMMERCE_STARTER_PROMPTS,\n isStarterRunning,\n starterPath,\n type StarterStatus,\n} from '../../../core/config/onboarding';\nimport { useConfig } from '../../../core/config/config-context';\nimport { revalidateProjectSchema } from '../../../core/config/use-project-schemas';\nimport { Button } from '../../../ui/primitives/button';\nimport { fetcher } from '../api';\nimport { starterSchemaDeployed, watchStarter } from '../starter-watch';\n\n/** A fallback for when the watch below has given up; the watch itself polls every 2 s. */\nconst POLL_MS = 10_000;\n\n/** How long after the sample store was added its questions still greet an empty chat. */\nconst SAMPLE_PROMPTS_DAYS = 14;\n\nconst STATE_LABELS: { [state in StarterStatus['state']]: string } = {\n queued: 'Getting your store ready…',\n deploying: 'Creating 22 entities for catalog, inventory, orders, customers and marketing…',\n seeding: 'Adding the Aven Living sample store…',\n completed: 'Your store is ready',\n failed: 'The starter could not be applied',\n};\n\n/**\n * Empty chat of a project that began from a starter: its progress while the\n * schema and sample data arrive, then questions the sample store answers.\n * Renders nothing for projects without a starter.\n */\nexport function StarterPanel({\n canSend,\n onPrompt,\n projectId,\n}: {\n canSend: boolean;\n onPrompt: (prompt: string) => void;\n projectId: string;\n}): JSX.Element | null {\n // While shown, the panel polls on its own: the watch below gives up after a while (a starter can sit\n // queued for long), and the screen must still catch up when the starter finally runs.\n const { data, mutate } = useSWR<{ starter: StarterStatus | null }>(starterPath(projectId), fetcher, {\n refreshInterval: (latest) => (isStarterRunning(latest?.starter) ? POLL_MS : 0),\n revalidateOnFocus: false,\n });\n const starter = data?.starter ?? null;\n const running = isStarterRunning(starter);\n const { projectSummaries } = useConfig();\n const summary = projectSummaries.find((project) => project.id === projectId);\n // Applying a starter is for owners; without a hosted summary the backend decides.\n const canRetry = !summary || summary.role === 'owner';\n const [retryError, setRetryError] = useState<string | null>(null);\n const [retrying, setRetrying] = useState(false);\n\n const seenRunning = useRef(false);\n\n // The watch outlives this panel, which unmounts as soon as a chat starts. Restart it on every change\n // of a running starter, in case an earlier watch gave up; it runs once per project at a time.\n useEffect(() => {\n if (running) {\n seenRunning.current = true;\n watchStarter({ projectId });\n } else if (seenRunning.current && starter && starterSchemaDeployed(starter)) {\n // This panel saw the deploy finish, possibly after the watch stopped: load the new schema.\n seenRunning.current = false;\n void revalidateProjectSchema(projectId);\n }\n }, [projectId, running, starter]);\n\n if (!starter) {\n return null;\n }\n\n if (starter.state === 'failed') {\n return (\n <div className=\"fk:mx-auto fk:flex fk:w-full fk:max-w-xl fk:flex-col fk:items-center fk:gap-3 fk:rounded-lg fk:border fk:border-border fk:p-4 fk:text-center fk:text-sm\">\n <p className=\"fk:flex fk:items-center fk:gap-2 fk:font-medium\">\n <TriangleAlert className=\"fk:size-4 fk:text-destructive\" />\n {STATE_LABELS.failed}\n </p>\n <p className=\"fk:text-muted-foreground\">\n {retryError ?? starter.error ?? 'Please try again.'}\n {canRetry ? null : ' Ask the project owner to try again.'}\n </p>\n {canRetry ? (\n <Button\n disabled={retrying}\n onClick={() => {\n setRetrying(true);\n setRetryError(null);\n void applyStarter(projectId, { template: starter.template, sampleData: starter.sampleData }).then(\n async (outcome) => {\n setRetrying(false);\n\n if (!outcome.ok) {\n setRetryError(outcome.message);\n\n return;\n }\n\n await mutate({ starter: outcome.starter }, { revalidate: false });\n watchStarter({ projectId });\n }\n );\n }}\n size=\"sm\"\n variant=\"outline\"\n >\n {retrying ? <LoaderCircle className=\"fk:size-4 fk:animate-spin\" /> : null}\n Try again\n </Button>\n ) : null}\n </div>\n );\n }\n\n if (running) {\n const progress = starter.state === 'seeding' && starter.progress ? starter.progress : null;\n\n return (\n <div\n aria-live=\"polite\"\n className=\"fk:mx-auto fk:flex fk:w-full fk:max-w-xl fk:flex-col fk:items-center fk:gap-3 fk:text-center fk:text-sm fk:text-muted-foreground\"\n >\n <p className=\"fk:flex fk:items-center fk:gap-2\">\n <LoaderCircle className=\"fk:size-4 fk:animate-spin\" />\n {STATE_LABELS[starter.state]}\n </p>\n {progress ? (\n <div className=\"fk:h-1.5 fk:w-48 fk:overflow-hidden fk:rounded-full fk:bg-muted\">\n <div\n className=\"fk:h-full fk:bg-primary fk:transition-[width]\"\n style={{ width: `${Math.round((progress.done / Math.max(1, progress.total)) * 100).toString()}%` }}\n />\n </div>\n ) : null}\n <p className=\"fk:text-xs\">This takes about a minute. You can already ask the agent anything.</p>\n </div>\n );\n }\n\n // Past the first days the store is likely real data, or gone.\n if (!isRecent(starter.completedAt)) {\n return null;\n }\n\n // Questions only make sense once the sample store exists.\n if (!starter.sampleData) {\n return (\n <p className=\"fk:mx-auto fk:flex fk:items-center fk:gap-2 fk:text-sm fk:text-muted-foreground\">\n <CheckCircle2 className=\"fk:size-4 fk:text-emerald-600\" />\n The commerce starter is ready. Ask the agent to add your products, or to adapt the schema.\n </p>\n );\n }\n\n return (\n <div className=\"fk:mx-auto fk:flex fk:w-full fk:max-w-2xl fk:flex-col fk:items-center fk:gap-3\">\n <p className=\"fk:flex fk:items-center fk:gap-2 fk:text-sm fk:text-muted-foreground\">\n <CheckCircle2 className=\"fk:size-4 fk:text-emerald-600\" />\n The Aven Living sample store is ready. Try asking:\n </p>\n <StarterPrompts canSend={canSend} onPrompt={onPrompt} prompts={COMMERCE_STARTER_PROMPTS} />\n </div>\n );\n}\n\nexport function StarterPrompts({\n canSend,\n onPrompt,\n prompts,\n}: {\n canSend: boolean;\n onPrompt: (prompt: string) => void;\n prompts: readonly string[];\n}): JSX.Element {\n return (\n <div className=\"fk:flex fk:flex-wrap fk:justify-center fk:gap-2\">\n {prompts.map((prompt) => (\n <button\n className=\"fk:inline-flex fk:max-w-full fk:items-center fk:gap-1.5 fk:rounded-full fk:border fk:border-border/70 fk:bg-muted/40 fk:px-3 fk:py-1.5 fk:text-left fk:text-sm fk:text-muted-foreground fk:transition-colors fk:hover:border-border fk:hover:bg-muted fk:hover:text-foreground fk:disabled:opacity-60 fk:corner-squircle\"\n disabled={!canSend}\n key={prompt}\n onClick={() => {\n onPrompt(prompt);\n }}\n type=\"button\"\n >\n <CornerDownRightIcon className=\"fk:size-3 fk:shrink-0\" />\n <span>{prompt}</span>\n </button>\n ))}\n </div>\n );\n}\n\nfunction isRecent(completedAt: string | undefined): boolean {\n const time = completedAt ? Date.parse(completedAt) : Number.NaN;\n\n return Number.isFinite(time) && Date.now() - time < SAMPLE_PROMPTS_DAYS * 24 * 60 * 60 * 1000;\n}\n","import type { AgentChatDetail, AgentChatMessage } from '../types';\n\n/** Chronological order with the backend's (created_at, id) keyset as tiebreak. */\nexport function compareChatMessages(a: AgentChatMessage, b: AgentChatMessage): number {\n const byTime = Date.parse(a.createdAt) - Date.parse(b.createdAt);\n\n if (Number.isFinite(byTime) && byTime !== 0) {\n return byTime;\n }\n\n // Same millisecond: the server timestamps carry microseconds, so fall back to\n // the string, then to the id, exactly like the keyset cursor.\n if (a.createdAt !== b.createdAt) {\n return a.createdAt < b.createdAt ? -1 : 1;\n }\n\n if (a.id === b.id) {\n return 0;\n }\n\n return a.id < b.id ? -1 : 1;\n}\n\n/** Deduplicates by id (later entries win) and sorts chronologically. */\nexport function sortChatMessages(messages: AgentChatMessage[]): AgentChatMessage[] {\n const byId = new Map(messages.map((message) => [message.id, message]));\n\n return [...byId.values()].sort(compareChatMessages);\n}\n\n/**\n * Keep locally confirmed turns when a stale in-flight GET wins the SWR write.\n *\n * `incoming.messages` is only the latest page of history, so the sole reason a\n * seeded message can be missing from it is that the GET predates the turn:\n * such messages are newer than everything in the page. Anything older merely\n * slid out of the page and belongs to \"Load earlier messages\", so appending it\n * would place old history after the live reply.\n */\nexport function mergeChatDetail(\n current: AgentChatDetail | undefined,\n incoming: AgentChatDetail | undefined\n): AgentChatDetail | undefined {\n if (!incoming) {\n return current;\n }\n\n if (!current) {\n return incoming;\n }\n\n const incomingIds = new Set(incoming.messages.map((message) => message.id));\n const newest = incoming.messages[incoming.messages.length - 1];\n const retained = current.messages.filter(\n (message) => !incomingIds.has(message.id) && (!newest || compareChatMessages(message, newest) > 0)\n );\n\n if (retained.length === 0) {\n return incoming;\n }\n\n return {\n ...incoming,\n messages: sortChatMessages([...incoming.messages, ...retained]),\n };\n}\n","import type { AgentChatMessage, AgentChatMessageStatus } from '../types';\n\n/**\n * Pure helpers for messages sent while a turn runs. The composer stays open\n * during a turn; what the user sends then is stored at once and either\n * steers the running turn or waits as the next one.\n */\n\nexport function isActiveTurnStatus(status: AgentChatMessageStatus): boolean {\n return status === 'pending' || status === 'streaming' || status === 'awaiting_approval';\n}\n\nexport function isFollowUpStatus(status: AgentChatMessageStatus): status is 'queued' | 'steering' {\n return status === 'queued' || status === 'steering';\n}\n\nexport interface LiveTurnSplit {\n /** Messages sent after the live turn started: follow-ups waiting on it. */\n after: AgentChatMessage[];\n before: AgentChatMessage[];\n /** The assistant message still being produced, if any. */\n live: AgentChatMessage | null;\n}\n\n/**\n * Finds the running assistant turn. It is no longer necessarily the last\n * message: follow-ups the user sent meanwhile come after it.\n */\nexport function splitLiveTurn(messages: AgentChatMessage[]): LiveTurnSplit {\n for (let index = messages.length - 1; index >= 0; index--) {\n const message = messages[index]!;\n\n if (message.role !== 'assistant') {\n continue;\n }\n\n if (!isActiveTurnStatus(message.status)) {\n break;\n }\n\n return { after: messages.slice(index + 1), before: messages.slice(0, index), live: message };\n }\n\n return { after: [], before: messages, live: null };\n}\n\n/** The line shown under a follow-up bubble while it waits; null once it was sent normally. */\nexport function getFollowUpLabel(status: AgentChatMessageStatus): string | null {\n if (status === 'steering') {\n return 'Picked up at the next step';\n }\n\n if (status === 'queued') {\n return 'Sends when this turn ends';\n }\n\n return null;\n}\n\n/**\n * Messages the user sent mid-turn that the agent has received: the reply\n * shows them where they landed, so their own rows are not shown again.\n */\nexport function getDeliveredMidTurnMessageIds(messages: AgentChatMessage[]): Set<string> {\n const ids = new Set<string>();\n\n for (const message of messages) {\n if (message.role !== 'assistant' || !Array.isArray(message.parts)) {\n continue;\n }\n\n for (const part of message.parts) {\n const messageId = part.type === 'data-mid-turn-message' ? (part.data as { messageId?: unknown } | undefined)?.messageId : null;\n\n if (typeof messageId === 'string') {\n ids.add(messageId);\n }\n }\n }\n\n return ids;\n}\n\n/**\n * The oldest queued follow-up: the one that starts the next turn. Monitor\n * events are left to the server, which checks the monitor's credit cap first.\n */\nexport function getNextQueuedMessage(messages: AgentChatMessage[]): AgentChatMessage | null {\n return (\n messages.find((message) => message.role === 'user' && message.status === 'queued' && message.kind !== 'monitor_event') ??\n null\n );\n}\n\n/**\n * What the composer's main button does: the turn is stopped while nothing is\n * typed; as soon as there is a draft, the same button sends it, during a turn\n * as a follow-up.\n */\nexport function getComposerAction(input: { hasDraft: boolean; streaming: boolean }): 'send' | 'stop' {\n return input.streaming && !input.hasDraft ? 'stop' : 'send';\n}\n","import type { JSX } from 'react';\nimport { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';\nimport { CheckIcon, CopyIcon, CornerDownRightIcon, LoaderCircle, PencilIcon } from 'lucide-react';\nimport { useLocation, useNavigate, useParams } from 'react-router-dom';\nimport useSWR, { useSWRConfig } from 'swr';\nimport {\n Button,\n Conversation,\n ConversationContent,\n ConversationScrollButton,\n PromptInput,\n PromptInputActionAddAttachments,\n PromptInputActionMenu,\n PromptInputActionMenuContent,\n PromptInputActionMenuTrigger,\n PromptInputBody,\n PromptInputFooter,\n PromptInputHeader,\n PromptInputProvider,\n PromptInputSelect,\n PromptInputSelectContent,\n PromptInputSelectItem,\n PromptInputSelectTrigger,\n PromptInputSelectValue,\n PromptInputSubmit,\n PromptInputTextarea,\n PromptInputTools,\n SpeechInput,\n SidebarTrigger,\n Separator,\n Tooltip,\n TooltipContent,\n TooltipTrigger,\n usePromptInputController,\n} from '../../../ui';\nimport { fetcher, paths, type ApiClient } from '../api';\nimport { EMPTY_STARTER_PROMPTS, starterPath, type OnboardingNavigationState } from '../../../core/config/onboarding';\nimport { StarterPanel, StarterPrompts } from './starter-panel';\nimport { findPastedPluginToken } from '../plugin-token-format';\nimport type { Marketplace } from '../plugin-types';\nimport {\n ChatApprovalContext,\n MessagePart,\n MutationApprovalPart,\n RunReplayActionsContext,\n STREAM_RETRY_DELAY_MS,\n ToolErrorLine,\n TurnStatusLine,\n getLiveStatusLabel,\n getMutationApprovalIds,\n isHiddenReplayPart,\n messageHasPendingMutationApproval,\n messageHasPendingUserQuestion,\n toMutationApprovalPartData,\n useProjectApi,\n useRunStream,\n useSessionMessages,\n type ReplayMessagePart,\n type RunRecordStatus,\n type RunReplayActions,\n type TurnStatus,\n} from '../replay';\nimport type { DecidedApprovals } from '../approval-parts';\nimport type {\n AgentChat,\n AgentChatAttachment,\n AgentChatDetail,\n AgentChatMessage,\n AgentChatMessageStatus,\n AgentChatPart,\n AgentChatTurn,\n AutomationTools,\n} from '../types';\nimport {\n ATTACHMENT_ACCEPT,\n ATTACHMENT_MAX_BYTES,\n ATTACHMENTS_MAX_PER_MESSAGE,\n ComposerAttachments,\n MessageAttachments,\n getAttachmentsFromParts,\n useAttachmentUploads,\n} from './attachments';\nimport { mergeChatDetail, sortChatMessages } from './chat-history';\nimport { useConfig } from '../../../core/config/config-context';\nimport { cn } from '../../../ui/lib/utils';\nimport { useAgentBasePath } from './chat-list';\nimport { getComposerDraftKey, readComposerDraft, writeComposerDraft } from './composer-draft';\nimport { appendDictatedText } from './dictation';\nimport {\n getComposerAction,\n getDeliveredMidTurnMessageIds,\n getFollowUpLabel,\n getNextQueuedMessage,\n isFollowUpStatus,\n splitLiveTurn,\n} from './follow-ups';\nimport { getMonitorEventData, MonitorChips, MonitorEventCard } from './monitor-parts';\nimport { getPluginConnectedData, PluginConnectContext, PluginConnectedNotice } from './plugin-connect-card';\nimport {\n AUTO_MODEL_KEY,\n coerceEffort,\n findModelByKey,\n formatModelSelection,\n getEffortOptions,\n getModelKey,\n parseModelSelection,\n type ModelSelection,\n} from '../model-selection';\n\ninterface ToolsResponse {\n tools: AutomationTools;\n}\n\n/** Keep fetching an untitled chat after the first turn so the generated title can land. */\nconst TITLE_POLL_TIMEOUT_MS = 60_000;\n/** While a monitor watches, a turn it starts must show up without a reload. */\nconst MONITOR_POLL_MS = 15_000;\n\nfunction getChatDetailRefreshInterval(latestData: AgentChatDetail | undefined): number {\n if (!latestData) {\n return 0;\n }\n\n // A live turn, or a follow-up waiting to start the next one, keeps polling.\n if (splitLiveTurn(latestData.messages).live || getNextQueuedMessage(latestData.messages)) {\n return STREAM_RETRY_DELAY_MS;\n }\n\n const hasCompletedAssistant = latestData.messages.some(\n (message) => message.role === 'assistant' && message.status === 'complete'\n );\n\n if (!hasCompletedAssistant) {\n return (latestData.monitors?.length ?? 0) > 0 ? MONITOR_POLL_MS : 0;\n }\n\n const lastActivity = new Date(latestData.chat.lastMessageAt ?? latestData.chat.updatedAt).getTime();\n\n if (Date.now() - lastActivity < TITLE_POLL_TIMEOUT_MS) {\n return STREAM_RETRY_DELAY_MS;\n }\n\n return (latestData.monitors?.length ?? 0) > 0 ? MONITOR_POLL_MS : 0;\n}\n\nfunction createFallbackChatDetail(chatId: string, modelId: string | null, timestamp: string): AgentChatDetail {\n return {\n chat: {\n createdAt: timestamp,\n id: chatId,\n lastMessageAt: timestamp,\n modelId,\n title: null,\n updatedAt: timestamp,\n },\n messages: [],\n pendingApproval: null,\n };\n}\n\nfunction getSeedBaseDetail(\n current: AgentChatDetail | undefined,\n createdChat: AgentChat | null,\n cachedDetail: AgentChatDetail | undefined,\n chatId: string,\n modelId: string | null,\n timestamp: string\n): AgentChatDetail {\n if (current) {\n return current;\n }\n\n if (createdChat) {\n return { chat: createdChat, messages: [], pendingApproval: null };\n }\n\n if (cachedDetail) {\n return cachedDetail;\n }\n\n return createFallbackChatDetail(chatId, modelId, timestamp);\n}\n\nfunction appendTurnToDetail(detail: AgentChatDetail, turn: AgentChatTurn): AgentChatDetail {\n const turnIds = new Set([turn.userMessage.id, turn.assistantMessage.id]);\n\n // Sorted: a turn started from a queued follow-up keeps that message's\n // place, and the assistant placeholder lands right behind it.\n return {\n ...detail,\n messages: sortChatMessages([\n ...detail.messages.filter((message) => !turnIds.has(message.id)),\n turn.userMessage,\n turn.assistantMessage,\n ]),\n };\n}\n\n/** Seeds a follow-up the user sent during a turn, so it shows before the next revalidation. */\nfunction appendMessageToDetail(detail: AgentChatDetail, message: AgentChatMessage): AgentChatDetail {\n return {\n ...detail,\n messages: sortChatMessages([...detail.messages.filter((item) => item.id !== message.id), message]),\n };\n}\n\nfunction resolveSeededChatDetail(\n seeds: { [chatId: string]: AgentChatDetail },\n chatId: string | undefined,\n detail: AgentChatDetail | undefined\n): AgentChatDetail | undefined {\n if (!chatId) {\n return detail;\n }\n\n return mergeChatDetail(seeds[chatId], detail);\n}\n\n/** Maps a chat turn status onto the record statuses the stream hook understands. */\n/** A composer reply answered the question of this assistant turn; a new object per answer. */\ninterface QuestionAnsweredSignal {\n messageId: string;\n}\n\nfunction getTurnRecordStatus(status: AgentChatMessageStatus): RunRecordStatus {\n if (status === 'awaiting_approval') {\n return 'awaiting_approval';\n }\n\n if (status === 'complete') {\n return 'success';\n }\n\n if (status === 'failed') {\n return 'failed';\n }\n\n return 'running';\n}\n\nfunction UserBubble({\n attachments = [],\n label,\n text,\n}: {\n attachments?: AgentChatAttachment[];\n /** Shown under a message sent during a turn, until it has been delivered. */\n label?: string | null;\n text: string;\n}): JSX.Element {\n const { textInput } = usePromptInputController();\n const [copied, setCopied] = useState(false);\n const hasText = text.trim().length > 0;\n\n async function handleCopy(): Promise<void> {\n await navigator.clipboard.writeText(text);\n setCopied(true);\n setTimeout(() => setCopied(false), 1500);\n }\n\n return (\n <div className=\"fk:group fk:ml-auto fk:flex fk:w-fit fk:max-w-[70%] fk:flex-col fk:items-end fk:gap-1\">\n <MessageAttachments attachments={attachments} />\n {hasText ? (\n <div className=\"fk:whitespace-pre-wrap fk:rounded-xl fk:bg-muted fk:dark:bg-white/20 fk:px-3.5 fk:py-2 fk:text-base fk:corner-squircle\">\n {text}\n </div>\n ) : null}\n {label ? (\n <span className=\"fk:inline-flex fk:items-center fk:gap-1 fk:text-xs fk:text-muted-foreground\">\n <CornerDownRightIcon className=\"fk:size-3 fk:shrink-0\" />\n {label}\n </span>\n ) : null}\n <div\n className={\n hasText ? 'fk:flex fk:gap-0.5 fk:opacity-0 fk:transition-opacity fk:group-hover:opacity-100' : 'fk:hidden'\n }\n >\n <Tooltip>\n <TooltipTrigger asChild>\n <Button\n aria-label=\"Copy prompt\"\n className=\"fk:size-6 fk:text-muted-foreground\"\n size=\"icon\"\n variant=\"ghost\"\n onClick={() => void handleCopy()}\n >\n {copied ? <CheckIcon className=\"fk:size-3.5\" /> : <CopyIcon className=\"fk:size-3.5\" />}\n </Button>\n </TooltipTrigger>\n <TooltipContent>Copy</TooltipContent>\n </Tooltip>\n <Tooltip>\n <TooltipTrigger asChild>\n <Button\n aria-label=\"Edit prompt\"\n className=\"fk:size-6 fk:text-muted-foreground\"\n size=\"icon\"\n variant=\"ghost\"\n onClick={() => textInput.setInput(text)}\n >\n <PencilIcon className=\"fk:size-3.5\" />\n </Button>\n </TooltipTrigger>\n <TooltipContent>Edit</TooltipContent>\n </Tooltip>\n </div>\n </div>\n );\n}\n\n/** The follow-up the turn offered, if the model was confident enough to offer one. */\nfunction getSuggestedPrompt(parts: ReadonlyArray<{ data?: unknown; type: string }>): string | null {\n const part = parts.find((candidate) => candidate.type === 'data-suggested-prompt');\n const prompt = (part?.data as { prompt?: unknown } | undefined)?.prompt;\n\n return typeof prompt === 'string' && prompt.trim() ? prompt : null;\n}\n\n/**\n * One subtle chip under the latest reply. Clicking fills the composer and\n * nothing more: the user edits or sends it.\n */\nfunction SuggestedPromptChip({ prompt }: { prompt: string }): JSX.Element {\n const { textInput } = usePromptInputController();\n\n return (\n <div className=\"fk:flex fk:justify-start\">\n <button\n className=\"fk:inline-flex fk:max-w-full fk:items-center fk:gap-1.5 fk:rounded-full fk:border fk:border-border/70 fk:bg-muted/40 fk:px-3 fk:py-1.5 fk:text-left fk:text-sm fk:text-muted-foreground fk:transition-colors fk:hover:border-border fk:hover:bg-muted fk:hover:ext-foreground fk:corner-squircle\"\n title=\"Use as your next message\"\n type=\"button\"\n onClick={() => textInput.setInput(prompt)}\n >\n <CornerDownRightIcon className=\"fk:size-3 fk:shrink-0\" />\n <span className=\"fk:truncate\">{prompt}</span>\n </button>\n </div>\n );\n}\n\n/**\n * Finished turns are stored as UIMessage-shaped parts. Reuse the live replay\n * renderer for `data-*` events (approvals, turn errors, tool status, artifacts,\n * specs) so history matches the in-flight `MessagePart` tree. `tool-*` parts\n * come from ModelMessage reconstruction and are ignored by `MessagePart`.\n */\nfunction PersistedPart({\n api,\n part,\n partIndex,\n parts,\n}: {\n api: ApiClient;\n part: AgentChatPart;\n partIndex: number;\n parts: AgentChatPart[];\n}): JSX.Element | null {\n // The live stream never showed a card for these calls, so history does not\n // either. Only a failed call leaves a trace.\n if (part.type.startsWith('tool-')) {\n return part.state === 'output-error' ? <ToolErrorLine message={part.errorText ?? 'The tool call failed.'} /> : null;\n }\n\n return (\n <MessagePart\n api={api}\n part={part as ReplayMessagePart}\n partIndex={partIndex}\n parts={parts as ReplayMessagePart[]}\n />\n );\n}\n\nfunction HistoryMessage({\n api,\n message,\n showSuggestion = false,\n}: {\n api: ApiClient;\n message: AgentChatMessage;\n /** Only the latest reply offers its follow-up; older ones would compete with it. */\n showSuggestion?: boolean;\n}): JSX.Element | null {\n if (message.kind === 'monitor_event') {\n const monitorEvent = getMonitorEventData(message);\n\n return monitorEvent ? <MonitorEventCard data={monitorEvent} error={message.error} /> : null;\n }\n\n if (message.kind === 'plugin_connected') {\n const connected = getPluginConnectedData(message.parts);\n\n return connected ? (\n <PluginConnectedNotice data={connected} error={message.error} label={getFollowUpLabel(message.status)} />\n ) : null;\n }\n\n if (message.role === 'user') {\n return (\n <UserBubble\n attachments={getAttachmentsFromParts(message.parts)}\n label={getFollowUpLabel(message.status)}\n text={message.textContent}\n />\n );\n }\n\n // Reasoning stays persisted for debugging, but is never displayed in chat.\n // Rolling-status tool parts are only meaningful while the call is in flight.\n const parts = (Array.isArray(message.parts) ? message.parts : []).filter(\n (part) =>\n !isHiddenReplayPart(part as ReplayMessagePart) &&\n !(part.type.startsWith('tool-') && part.state !== 'output-error')\n );\n const hasTurnErrorPart = parts.some((part) => part.type === 'data-turn-error');\n const suggestedPrompt = showSuggestion && !message.error ? getSuggestedPrompt(parts) : null;\n\n if (parts.length === 0 && !message.error) {\n return null;\n }\n\n return (\n <div className=\"fk:w-full fk:min-w-0 fk:space-y-8\">\n {parts.map((part, index) => (\n <PersistedPart\n api={api}\n key={part.toolCallId ?? `${message.id}-${index.toString()}`}\n part={part}\n partIndex={index}\n parts={parts}\n />\n ))}\n {message.error && !hasTurnErrorPart ? <ToolErrorLine message={message.error} /> : null}\n {suggestedPrompt ? <SuggestedPromptChip prompt={suggestedPrompt} /> : null}\n </div>\n );\n}\n\n/**\n * Streams the in-flight assistant turn from the workflow run stream, with the\n * same approval pause/resume handling as the automation run replay.\n */\nfunction LiveTurn({\n api,\n chatId,\n detail,\n message,\n onMidTurnDelivered,\n onStatusChange,\n onTurnUpdated,\n questionAnsweredSignal,\n}: {\n api: ApiClient;\n chatId: string;\n detail: AgentChatDetail;\n message: AgentChatMessage;\n /** Ids of the follow-ups the stream has shown inline so far. */\n onMidTurnDelivered: (_ids: string[]) => void;\n onStatusChange: (_status: TurnStatus) => void;\n onTurnUpdated: () => void;\n /** Set when a composer reply answered a question; applies only to the turn that asked it. */\n questionAnsweredSignal: QuestionAnsweredSignal | null;\n}): JSX.Element {\n const recordStatus = getTurnRecordStatus(message.status);\n const streamApi = message.workflowRunId ? api.getAgentChatStreamUrl(chatId, message.workflowRunId) : '';\n const [resumeToken, setResumeToken] = useState(0);\n const [suppressApprovalPause, setSuppressApprovalPause] = useState(false);\n const [decidedApprovals, setDecidedApprovals] = useState<DecidedApprovals>({});\n const lastDecidedApprovalIdRef = useRef<string | null>(null);\n const { message: streamMessage, status } = useRunStream(streamApi, {\n decidedApprovals,\n recordStatus,\n resumeToken,\n suppressApprovalPause,\n });\n // Filter only the presentation copy, before session splitting, so a\n // reasoning-only message cannot leave an empty wrapper and extra spacing.\n const rawMessages = useMemo(\n () =>\n streamMessage\n ? [{ ...streamMessage, parts: streamMessage.parts.filter((part) => !isHiddenReplayPart(part)) }]\n : [],\n [streamMessage]\n );\n const sessionMessages = useSessionMessages(rawMessages);\n const onTurnUpdatedRef = useRef(onTurnUpdated);\n onTurnUpdatedRef.current = onTurnUpdated;\n const onStatusChangeRef = useRef(onStatusChange);\n onStatusChangeRef.current = onStatusChange;\n const replayActions = useMemo<RunReplayActions>(\n () => ({\n answerQuestion: async (questionId, response) => {\n const { question } = await api.answerAgentChatQuestion(chatId, questionId, response);\n\n // Reconnect the stream right away, as after an approval decision, so the resumed turn shows without waiting for a poll.\n setSuppressApprovalPause(true);\n setResumeToken((current) => current + 1);\n onTurnUpdatedRef.current();\n\n return question ?? null;\n },\n onApprovalDecided: (approvalId, decidedStatus) => {\n if (approvalId && decidedStatus && decidedStatus !== 'pending') {\n setDecidedApprovals((current) => ({ ...current, [approvalId]: decidedStatus }));\n }\n\n if (approvalId && lastDecidedApprovalIdRef.current === approvalId) {\n return;\n }\n\n if (approvalId) {\n lastDecidedApprovalIdRef.current = approvalId;\n }\n\n setSuppressApprovalPause(true);\n setResumeToken((current) => current + 1);\n onTurnUpdatedRef.current();\n },\n }),\n [api, chatId]\n );\n\n useEffect(() => {\n setResumeToken(0);\n setSuppressApprovalPause(false);\n lastDecidedApprovalIdRef.current = null;\n setDecidedApprovals({});\n }, [message.id]);\n\n // A composer reply answered the open question: resume the stream as the card's own answer does.\n // Only a signal for this turn, newer than the one seen at mount, counts.\n const seenQuestionSignalRef = useRef(questionAnsweredSignal);\n\n useEffect(() => {\n if (questionAnsweredSignal === seenQuestionSignalRef.current) {\n return;\n }\n\n seenQuestionSignalRef.current = questionAnsweredSignal;\n\n if (questionAnsweredSignal?.messageId === message.id) {\n setSuppressApprovalPause(true);\n setResumeToken((current) => current + 1);\n }\n }, [message.id, questionAnsweredSignal]);\n\n // Clear the post-decide suppress window once the workflow has resumed.\n useEffect(() => {\n if (suppressApprovalPause && message.status === 'streaming') {\n setSuppressApprovalPause(false);\n }\n }, [message.status, suppressApprovalPause]);\n\n useEffect(() => {\n if (status === 'finished' || status === 'paused') {\n onTurnUpdatedRef.current();\n }\n }, [status]);\n\n // A follow-up the stream renders inline must leave the waiting list at once.\n const deliveredKey = (streamMessage?.parts ?? [])\n .filter((part) => part.type === 'data-mid-turn-message')\n .map((part) => String((part as { data?: { messageId?: unknown } }).data?.messageId ?? ''))\n .join('\\n');\n const onMidTurnDeliveredRef = useRef(onMidTurnDelivered);\n onMidTurnDeliveredRef.current = onMidTurnDelivered;\n\n useEffect(() => {\n if (deliveredKey) {\n onMidTurnDeliveredRef.current(deliveredKey.split('\\n'));\n }\n }, [deliveredKey]);\n\n // Prefer the turn record over a stale pending stream part once execution\n // has resumed (`streaming`). Keeping the previous replay on reconnect can\n // leave a pending data-mutation-approval part in memory until rebuild.\n const isAwaitingApproval =\n !suppressApprovalPause &&\n message.status !== 'streaming' &&\n (message.status === 'awaiting_approval' ||\n status === 'paused' ||\n messageHasPendingMutationApproval(streamMessage) ||\n messageHasPendingUserQuestion(streamMessage));\n // When the stream replay has no data-mutation-approval part yet (e.g. right\n // after a reload), fall back to the pending approval from the chat detail.\n const streamApprovalIds = useMemo(() => new Set(getMutationApprovalIds(streamMessage)), [streamMessage]);\n const fallbackApproval =\n detail.pendingApproval && !streamApprovalIds.has(detail.pendingApproval.id) ? detail.pendingApproval : null;\n // Growing text shows its own progress, so the status line fades while the\n // response streams. Between steps it names the activity: the model's own\n // reasoning, a tool call (\"Searching schema\"), or plain \"Thinking\".\n const lastPart = streamMessage?.parts[streamMessage.parts.length - 1];\n const contentIsStreaming = lastPart?.type === 'text' && lastPart.state === 'streaming';\n const awaitingLabel = messageHasPendingUserQuestion(streamMessage) ? 'Waiting for your answer' : 'Awaiting approval';\n const statusLabel = isAwaitingApproval ? awaitingLabel : (getLiveStatusLabel(streamMessage) ?? 'Thinking');\n const statusVisible = isAwaitingApproval\n ? status !== 'finished' && status !== 'error'\n : status === 'streaming' && !contentIsStreaming;\n\n // The status line itself lives in ChatConversation so it keeps one stable\n // slot from \"Sending\" through the whole turn; LiveTurn only reports to it.\n useEffect(() => {\n onStatusChangeRef.current({ label: statusLabel, visible: statusVisible });\n }, [statusLabel, statusVisible]);\n\n const showFallbackApproval = Boolean(fallbackApproval) && isAwaitingApproval;\n const liveSuggestedPrompt =\n status === 'finished'\n ? getSuggestedPrompt(sessionMessages.flatMap((sessionMessage) => sessionMessage.parts))\n : null;\n\n // Render no wrapper until there is content: an empty div still collects the\n // parent's vertical spacing and would shift the status line at mount.\n if (sessionMessages.length === 0 && !showFallbackApproval) {\n return <RunReplayActionsContext.Provider value={replayActions}>{null}</RunReplayActionsContext.Provider>;\n }\n\n return (\n <RunReplayActionsContext.Provider value={replayActions}>\n <div className=\"fk:w-full fk:min-w-0 fk:space-y-8\">\n {sessionMessages.map((sessionMessage) => (\n <div className=\"fk:space-y-8 fk:min-w-0\" key={sessionMessage.id}>\n {sessionMessage.parts.map((part, index) => (\n <MessagePart api={api} key={index} part={part} partIndex={index} parts={sessionMessage.parts} />\n ))}\n </div>\n ))}\n {fallbackApproval && showFallbackApproval ? (\n <MutationApprovalPart api={api} message={toMutationApprovalPartData(fallbackApproval)} />\n ) : null}\n {liveSuggestedPrompt ? <SuggestedPromptChip prompt={liveSuggestedPrompt} /> : null}\n </div>\n </RunReplayActionsContext.Provider>\n );\n}\n\n/**\n * Keeps the composer text in sync with the stored draft of the chat it is\n * showing: every change is stored under the chat's key, and when the page\n * moves to another chat (or is first shown) that chat's draft replaces the\n * text. The outgoing chat's draft was stored on its last change, so a switch\n * only has to load. A single effect handles both so the stale text of the\n * previous chat is never written under the new chat's key.\n */\nfunction ComposerDraftSync({ draftKey }: { draftKey: string }): null {\n const { textInput } = usePromptInputController();\n const { setInput, value } = textInput;\n const activeKeyRef = useRef<string | null>(null);\n\n useLayoutEffect(() => {\n if (activeKeyRef.current === draftKey) {\n writeComposerDraft(draftKey, value);\n\n return;\n }\n\n activeKeyRef.current = draftKey;\n const draft = readComposerDraft(draftKey);\n\n if (draft !== value) {\n setInput(draft);\n }\n }, [draftKey, setInput, value]);\n\n return null;\n}\n\n/** Puts a message that could not be sent back into the composer (and so into its stored draft). */\nfunction ComposerRestore({\n onRestored,\n text,\n}: {\n onRestored: (_text: null) => void;\n text: string | null;\n}): null {\n const { textInput } = usePromptInputController();\n const { setInput } = textInput;\n\n useEffect(() => {\n if (text !== null) {\n setInput(text);\n onRestored(null);\n }\n }, [onRestored, setInput, text]);\n\n return null;\n}\n\nfunction ChatComposer({\n api,\n effort,\n modelKey,\n modelPending,\n models,\n onEffortChange,\n onError,\n onModelChange,\n onSend,\n onStop,\n placeholder,\n sending,\n streaming,\n}: {\n api: ApiClient;\n effort: string | null;\n modelKey: string | null;\n modelPending: boolean;\n models: AutomationTools['models'];\n onEffortChange: (_effort: string) => void;\n onError: (_message: string | null) => void;\n onModelChange: (_modelKey: string) => void;\n onSend: (_text: string, _attachments: AgentChatAttachment[]) => Promise<void>;\n onStop: () => Promise<void>;\n placeholder: string;\n sending: boolean;\n streaming: boolean;\n}): JSX.Element {\n const { attachments, textInput } = usePromptInputController();\n const uploads = useAttachmentUploads(api, onError);\n const { currentProjectId } = useConfig();\n // Token formats of plugins that connect with a pasted token, to stop one being sent as a message.\n const { data: marketplace, error: marketplaceError } = useSWR<Marketplace>(\n currentProjectId ? `/api/flexkit/${currentProjectId}/plugins` : null,\n fetcher\n );\n // `sending` only flips on the next render, so track the in-flight send\n // synchronously to reject a duplicate submit before it clears the text.\n const submittingRef = useRef(false);\n const selectableModels = models.filter((model) => !model.deprecated || getModelKey(model) === modelKey);\n const selectedModel = findModelByKey(models, modelKey);\n const effortOptions = getEffortOptions(selectedModel);\n const effectiveEffort = coerceEffort(selectedModel, effort);\n const hasDraft = textInput.value.trim().length > 0 || attachments.files.length > 0;\n // The composer stays open during a turn: with nothing typed the button\n // stops the turn, with a draft it sends it as a follow-up.\n const action = getComposerAction({ hasDraft, streaming });\n const canSubmit = hasDraft && !uploads.isUploading && !sending && !modelPending;\n\n return (\n <PromptInput\n accept={ATTACHMENT_ACCEPT}\n className=\"fk:mx-auto fk:max-w-4xl\"\n maxFileSize={ATTACHMENT_MAX_BYTES}\n maxFiles={ATTACHMENTS_MAX_PER_MESSAGE}\n multiple\n onError={(error) => onError(error.message)}\n onSubmit={({ text }) => {\n const trimmed = text?.trim() ?? '';\n const sentAttachments = uploads.getUploaded(attachments.files.map((file) => file.id));\n\n // PromptInput clears the text and attachments whenever onSubmit returns\n // without throwing, so a blocked submit must reject to keep the draft.\n if (\n (!trimmed && sentAttachments.length === 0) ||\n uploads.isUploading ||\n sending ||\n submittingRef.current ||\n modelPending ||\n // Token formats are still loading; a failed load does not block chat.\n (!marketplace && !marketplaceError && Boolean(currentProjectId))\n ) {\n return Promise.reject(new Error('The message cannot be sent right now.'));\n }\n\n const pasted = findPastedPluginToken(trimmed, marketplace?.plugins ?? []);\n\n // A message is stored in the chat and sent to the model; a token belongs in the connect form.\n if (pasted) {\n // The rest of the message stays; the token leaves the composer so its stored draft never holds it.\n textInput.setInput(pasted.tokens.reduce((rest, token) => rest.split(token).join(''), text));\n onError(\n `That looks like a ${pasted.label}. It was removed from your message: connect ${pasted.plugin.name} from its connect card or AI → Plugins instead, where it is stored encrypted and never shown to the agent.`\n );\n\n return Promise.reject(new Error('The message contains a plugin token.'));\n }\n\n // Clear the text immediately; restore it if sending fails. Returning\n // the promise makes PromptInput clear the attachments only once the\n // send resolved, so a failed send keeps the uploaded files attached.\n submittingRef.current = true;\n textInput.clear();\n\n return onSend(trimmed, sentAttachments)\n .catch((error: unknown) => {\n textInput.setInput(text);\n throw error;\n })\n .finally(() => {\n submittingRef.current = false;\n });\n }}\n >\n {attachments.files.length > 0 ? (\n // The header addon carries its own padding, so it is only mounted\n // while there is an attachment strip to show.\n <PromptInputHeader>\n <ComposerAttachments uploads={uploads} />\n </PromptInputHeader>\n ) : null}\n <PromptInputBody>\n <PromptInputTextarea disabled={sending} placeholder={placeholder} />\n </PromptInputBody>\n <PromptInputFooter>\n <PromptInputTools>\n <PromptInputActionMenu>\n <PromptInputActionMenuTrigger\n aria-label=\"Add attachments\"\n className=\"fk:border-0 fk:bg-border fk:corner-round\"\n disabled={sending}\n tooltip=\"Add photos or files\"\n />\n <PromptInputActionMenuContent>\n <PromptInputActionAddAttachments />\n </PromptInputActionMenuContent>\n </PromptInputActionMenu>\n {selectableModels.length > 0 ? (\n <PromptInputSelect value={modelKey ?? undefined} onValueChange={onModelChange}>\n <PromptInputSelectTrigger aria-label=\"Model\" className=\"fk:min-w-44\">\n <PromptInputSelectValue placeholder=\"Model\" />\n </PromptInputSelectTrigger>\n <PromptInputSelectContent>\n {selectableModels.map((model) => (\n <PromptInputSelectItem key={getModelKey(model)} value={getModelKey(model)}>\n {model.name}\n </PromptInputSelectItem>\n ))}\n </PromptInputSelectContent>\n </PromptInputSelect>\n ) : null}\n {effortOptions.length > 1 && effectiveEffort ? (\n <PromptInputSelect value={effectiveEffort} onValueChange={onEffortChange}>\n <PromptInputSelectTrigger aria-label=\"Reasoning effort\" className=\"fk:min-w-28\">\n <PromptInputSelectValue placeholder=\"Effort\" />\n </PromptInputSelectTrigger>\n <PromptInputSelectContent>\n {effortOptions.map((option) => (\n <PromptInputSelectItem key={option.value} value={option.value}>\n {option.label}\n </PromptInputSelectItem>\n ))}\n </PromptInputSelectContent>\n </PromptInputSelect>\n ) : null}\n </PromptInputTools>\n <div className=\"fk:flex fk:items-center fk:gap-3\">\n <SpeechInput\n disabled={sending}\n onAudioRecorded={async (audioBlob, signal) => {\n const { text } = await api.transcribeAgentAudio(audioBlob, signal);\n\n return text;\n }}\n onError={(error) => onError(error.message)}\n onTranscriptionChange={(transcript) => {\n onError(null);\n textInput.setInput(appendDictatedText(textInput.value, transcript));\n }}\n />\n <PromptInputSubmit\n className=\"fk:corner-round\"\n disabled={action === 'stop' ? false : !canSubmit}\n status={action === 'stop' ? 'streaming' : undefined}\n onStop={() => void onStop()}\n />\n </div>\n </PromptInputFooter>\n </PromptInput>\n );\n}\n\ninterface PendingMessage {\n attachments: AgentChatAttachment[];\n text: string;\n}\n\n/** Pages loaded before the latest one, for a single chat. */\ninterface ChatHistoryState {\n chatId: string | null;\n error: string | null;\n loading: boolean;\n older: AgentChatMessage[];\n page: { cursor: string | null; hasMore: boolean } | null;\n}\n\nconst EMPTY_CHAT_HISTORY: ChatHistoryState = {\n chatId: null,\n error: null,\n loading: false,\n older: [],\n page: null,\n};\n\n/** Retry a queued follow-up's start no sooner than this after a failed attempt (the turn was still running). */\nconst QUEUED_START_RETRY_MS = 3_000;\n\nfunction ChatConversation({\n api,\n chatId,\n projectId,\n pendingFollowUp,\n pendingMessage,\n questionAnsweredSignal,\n resolveDetail,\n}: {\n api: ApiClient;\n /** Null while the first message of a new chat is being sent. */\n chatId: string | null;\n projectId: string;\n /** A message sent during the live turn, until the platform has stored it. */\n pendingFollowUp?: PendingMessage;\n pendingMessage?: PendingMessage;\n questionAnsweredSignal: QuestionAnsweredSignal | null;\n resolveDetail: (_detail: AgentChatDetail | undefined) => AgentChatDetail | undefined;\n}): JSX.Element {\n // SWR only re-arms its polling timer when the refreshInterval option (or\n // the key) changes. A module-level function has a stable identity, so the\n // timer was armed exactly once — at mount, with no data yet — where the\n // interval resolves to 0 and polling stays off forever. The chat then never\n // noticed a finished turn until a tab refocus revalidated it. The inline\n // arrow changes identity on every render, re-arming the timer whenever new\n // data (e.g. an active turn) arrives.\n const { data: rawDetail, mutate } = useSWR<AgentChatDetail>(\n chatId ? paths(projectId).agentChat(chatId) : null,\n fetcher,\n {\n refreshInterval: 0,\n }\n );\n const data = resolveDetail(rawDetail);\n // History pages are keyed by chat so that, with this component mounted\n // across chat navigation, the first render of another chat never shows this\n // chat's pages, and a late response for another chat is dropped.\n const [historyState, setHistoryState] = useState<ChatHistoryState>(EMPTY_CHAT_HISTORY);\n const history = historyState.chatId === chatId ? historyState : EMPTY_CHAT_HISTORY;\n const activeChatRef = useRef(chatId);\n activeChatRef.current = chatId;\n // A write for the chat the state already belongs to always applies, even\n // while that chat is off screen, so a request finishing after navigation\n // never parks it as loading. Only a chat on screen may claim the state.\n const updateHistory = (forChatId: string, patch: (_current: ChatHistoryState) => Partial<ChatHistoryState>) =>\n setHistoryState((current) => {\n if (current.chatId !== forChatId && activeChatRef.current !== forChatId) return current;\n const base = current.chatId === forChatId ? current : { ...EMPTY_CHAT_HISTORY, chatId: forChatId };\n return { ...base, ...patch(base) };\n });\n // Each GET returns only the latest page, so a new turn pushes the oldest\n // visible messages out of it. Keep them so the history never shows a gap.\n const windowRef = useRef<{ chatId: string | null; messages: AgentChatMessage[] }>({ chatId: null, messages: [] });\n const windowMessages = data?.messages;\n useEffect(() => {\n const previous = windowRef.current;\n const next = windowMessages ?? [];\n windowRef.current = { chatId, messages: next };\n if (!chatId || previous.chatId !== chatId) return;\n const nextIds = new Set(next.map((message) => message.id));\n const dropped = previous.messages.filter((message) => !nextIds.has(message.id));\n if (dropped.length > 0)\n updateHistory(chatId, (current) => ({ older: sortChatMessages([...current.older, ...dropped]) }));\n }, [chatId, windowMessages]);\n const currentIds = new Set(data?.messages.map((item) => item.id) ?? []);\n const messages = [...history.older.filter((item) => !currentIds.has(item.id)), ...(data?.messages ?? [])];\n type ChatStatus = {\n chat: AgentChat;\n latestMessage: { id: string; status: AgentChatMessageStatus; workflowRunId: string | null } | null;\n latestApproval: { id: string; status: string } | null;\n /** Active monitors; a change (one ended, a new one started) refreshes the detail. */\n activeMonitorCount?: number;\n };\n const detailRef = useRef(data);\n detailRef.current = data;\n const priorStatus = useRef<string | undefined>(undefined);\n useSWR<ChatStatus>(chatId ? `${paths(projectId).agentChat(chatId)}?view=status` : null, fetcher, {\n refreshInterval: () => getChatDetailRefreshInterval(detailRef.current),\n onSuccess: (status) => {\n const signature = JSON.stringify(status);\n const previous = priorStatus.current;\n priorStatus.current = signature;\n const { current } = detailRef;\n // The status reports the latest reply; a follow-up sent during the turn is newer than it.\n const latest = current\n ? [...current.messages].reverse().find((message) => message.role === 'assistant')\n : undefined;\n if (\n (previous && previous !== signature) ||\n (latest &&\n status.latestMessage &&\n (latest.id !== status.latestMessage.id ||\n latest.status !== status.latestMessage.status ||\n latest.workflowRunId !== status.latestMessage.workflowRunId ||\n current?.chat.updatedAt !== status.chat.updatedAt))\n )\n void mutate();\n },\n });\n const loadOlder = async () => {\n const cursor = history.page?.cursor ?? data?.nextCursor;\n if (!chatId || !cursor || history.loading) return;\n const requestChatId = chatId;\n updateHistory(requestChatId, () => ({ error: null, loading: true }));\n try {\n const result = await fetcher<AgentChatDetail>(\n `${paths(projectId).agentChat(requestChatId)}?before=${encodeURIComponent(cursor)}`\n );\n updateHistory(requestChatId, (current) => ({\n loading: false,\n older: sortChatMessages([...result.messages, ...current.older]),\n page: { cursor: result.nextCursor ?? null, hasMore: result.hasMore ?? false },\n }));\n } catch {\n updateHistory(requestChatId, () => ({ error: 'Could not load earlier messages. Try again.', loading: false }));\n }\n };\n // Follow-ups sent during the turn come after the live assistant message.\n // Once the agent has received one, the reply shows it where it landed, so\n // only the ones still waiting are listed here and delivered rows are\n // dropped from the history.\n const { after: followUpMessages, before: earlierMessages, live: liveMessage } = splitLiveTurn(messages);\n // Ids the live stream already renders inline; the rows catch up on the next refresh.\n const [liveDeliveredIds, setLiveDeliveredIds] = useState<{ messageId: string; ids: string[] }>({\n ids: [],\n messageId: '',\n });\n const deliveredIds = getDeliveredMidTurnMessageIds(messages);\n\n for (const id of liveMessage && liveDeliveredIds.messageId === liveMessage.id ? liveDeliveredIds.ids : []) {\n deliveredIds.add(id);\n }\n\n const waitingFollowUps = followUpMessages.filter(\n (message) => isFollowUpStatus(message.status) && !deliveredIds.has(message.id)\n );\n const historyMessages = earlierMessages.filter((message) => !deliveredIds.has(message.id));\n // A queued follow-up starts the next turn as soon as the previous one has\n // ended, whether this tab sent it or it was found on load. A failed start\n // (the turn still wrapping up, a network blip) is retried after a pause.\n const nextQueued = !liveMessage && !pendingMessage ? getNextQueuedMessage(messages) : null;\n const nextQueuedId = nextQueued?.id ?? null;\n const [queuedStartAttempt, setQueuedStartAttempt] = useState(0);\n const queuedStartInFlightRef = useRef<string | null>(null);\n\n useEffect(() => {\n if (!chatId || !nextQueuedId || queuedStartInFlightRef.current === nextQueuedId) {\n return;\n }\n\n queuedStartInFlightRef.current = nextQueuedId;\n let cancelled = false;\n let retry: ReturnType<typeof setTimeout> | null = null;\n\n void api\n .startQueuedAgentChatMessage(chatId, nextQueuedId)\n .then(\n () => undefined,\n () => {\n retry = setTimeout(() => {\n if (!cancelled) {\n setQueuedStartAttempt((attempt) => attempt + 1);\n }\n }, QUEUED_START_RETRY_MS);\n }\n )\n .finally(() => {\n queuedStartInFlightRef.current = null;\n void mutate();\n });\n\n return () => {\n cancelled = true;\n\n if (retry) {\n clearTimeout(retry);\n }\n };\n }, [api, chatId, mutate, nextQueuedId, queuedStartAttempt]);\n // Reported by LiveTurn; owned here so the status line keeps one stable slot\n // from \"Sending\" (no turn yet) through the live turn, rolling between labels\n // instead of remounting. Keyed by turn so a new turn never shows the\n // previous turn's last state.\n const [reportedStatus, setReportedStatus] = useState<{ messageId: string; status: TurnStatus } | null>(null);\n const liveStatus = liveMessage && reportedStatus?.messageId === liveMessage.id ? reportedStatus.status : null;\n\n if (chatId && !data && !pendingMessage) {\n return (\n <div className=\"fk:flex fk:flex-1 fk:items-center fk:justify-center fk:gap-2 fk:text-sm fk:text-muted-foreground\">\n <LoaderCircle className=\"fk:size-4 fk:animate-spin\" />\n Loading chat...\n </div>\n );\n }\n\n const turnActive = Boolean(pendingMessage) || Boolean(liveMessage);\n const latestAssistantId = [...historyMessages].reverse().find((message) => message.role === 'assistant')?.id ?? null;\n const statusLabel = liveMessage ? (liveStatus?.label ?? 'Thinking') : 'Sending';\n const statusVisible = liveMessage ? (liveStatus?.visible ?? true) : true;\n\n return (\n <Conversation className=\"fk:h-0 fk:min-h-0 fk:flex-1\">\n <ConversationContent className=\"fk:gap-0 fk:p-0\">\n <div className=\"fk:mx-auto fk:w-full fk:max-w-4xl fk:space-y-5 fk:pb-6 fk:pr-4\">\n {(history.page?.hasMore ?? data?.hasMore) ? (\n <Button variant=\"ghost\" disabled={history.loading} onClick={() => void loadOlder()}>\n {history.loading ? 'Loading…' : 'Load earlier messages'}\n </Button>\n ) : null}\n {history.error ? <p role=\"alert\">{history.error}</p> : null}\n {historyMessages.map((message) => (\n <HistoryMessage\n api={api}\n key={message.id}\n message={message}\n showSuggestion={!turnActive && message.id === latestAssistantId}\n />\n ))}\n {liveMessage && chatId && data ? (\n <LiveTurn\n api={api}\n chatId={chatId}\n detail={data}\n message={liveMessage}\n onMidTurnDelivered={(ids) => setLiveDeliveredIds({ ids, messageId: liveMessage.id })}\n onStatusChange={(status) => setReportedStatus({ messageId: liveMessage.id, status })}\n onTurnUpdated={() => void mutate()}\n questionAnsweredSignal={questionAnsweredSignal}\n />\n ) : null}\n {pendingMessage && !liveMessage ? (\n <UserBubble attachments={pendingMessage.attachments} text={pendingMessage.text} />\n ) : null}\n {turnActive ? <TurnStatusLine label={statusLabel} visible={statusVisible} /> : null}\n {waitingFollowUps.map((message) => (\n <HistoryMessage api={api} key={message.id} message={message} />\n ))}\n {pendingFollowUp && liveMessage ? (\n <UserBubble attachments={pendingFollowUp.attachments} text={pendingFollowUp.text} />\n ) : null}\n </div>\n </ConversationContent>\n <ConversationScrollButton />\n </Conversation>\n );\n}\n\nconst GENERIC_GREETINGS = [\n 'Where should we begin?',\n 'Ready when you are',\n 'What’s on the agenda today?',\n 'What’s on your mind today?',\n];\n\nfunction getNamedGreetings(name: string): string[] {\n return [`How can I help, ${name}?`, `Good to see you, ${name}.`, `Hey, ${name}. Ready to dive in?`];\n}\n\nfunction pickGreeting(preferredName: string | null): string {\n const greetings = preferredName ? [...GENERIC_GREETINGS, ...getNamedGreetings(preferredName)] : GENERIC_GREETINGS;\n\n return greetings[Math.floor(Math.random() * greetings.length)] ?? 'How can I help?';\n}\n\nconst LAST_AGENT_MODEL_STORAGE_KEY = 'flexkit-ai:lastModelId';\nconst LAST_AGENT_EFFORT_STORAGE_KEY = 'flexkit-ai:lastEffort';\n\nfunction readLastAgentModel(): ModelSelection | null {\n if (typeof localStorage === 'undefined') {\n return null;\n }\n\n try {\n const stored = localStorage.getItem(LAST_AGENT_MODEL_STORAGE_KEY);\n\n if (!stored) {\n return null;\n }\n\n // The stored value is a model key, which on an older API is the composite\n // model id. Older builds also remembered whatever was last sent, which\n // predates Auto and explicit picks; the catalog lookup in `lastUsed` drops\n // any key it no longer lists, so a new chat starts on Auto in that case.\n return { effort: localStorage.getItem(LAST_AGENT_EFFORT_STORAGE_KEY), modelKey: stored };\n } catch {\n return null;\n }\n}\n\nfunction resolveComposerSelection(input: {\n awaitingChatModel: boolean;\n chatSelection: ModelSelection | null;\n defaultModelKey: string | null;\n lastUsed: ModelSelection | null;\n selectedEffort: string | null;\n selectedModelKey: string | null;\n}): { effort: string | null; modelKey: string | null } {\n if (input.selectedModelKey) {\n return { effort: input.selectedEffort, modelKey: input.selectedModelKey };\n }\n\n // The chat detail request has not returned yet, so its model is unknown.\n // Falling through to the remembered model would display and send that one.\n if (input.awaitingChatModel) {\n return { effort: null, modelKey: null };\n }\n\n if (input.chatSelection) {\n return { effort: input.selectedEffort ?? input.chatSelection.effort, modelKey: input.chatSelection.modelKey };\n }\n\n if (input.lastUsed) {\n return { effort: input.selectedEffort ?? input.lastUsed.effort, modelKey: input.lastUsed.modelKey };\n }\n\n return { effort: input.selectedEffort, modelKey: input.defaultModelKey };\n}\n\nfunction writeLastAgentModel(selection: ModelSelection): void {\n if (typeof localStorage === 'undefined') {\n return;\n }\n\n try {\n localStorage.setItem(LAST_AGENT_MODEL_STORAGE_KEY, selection.modelKey);\n\n if (selection.effort) {\n localStorage.setItem(LAST_AGENT_EFFORT_STORAGE_KEY, selection.effort);\n } else {\n localStorage.removeItem(LAST_AGENT_EFFORT_STORAGE_KEY);\n }\n } catch {\n // Ignore storage access errors (private mode, blocked storage, etc.)\n }\n}\n\nfunction EmptyConversation({\n canSend,\n hasSchema,\n onPrompt,\n projectId,\n}: {\n canSend: boolean;\n /** False for a project without entities yet: the chat suggests how to design them. */\n hasSchema: boolean;\n onPrompt: (prompt: string) => void;\n projectId: string;\n}): JSX.Element {\n const { data, isLoading } = useSWR<{ preferredName: string | null }>(paths(projectId).agentProfile(), fetcher);\n // Pick once the profile resolves so the greeting never flashes from a\n // generic salute to a personalized one.\n const greeting = useMemo(() => {\n if (isLoading) {\n return null;\n }\n\n return pickGreeting(data?.preferredName ?? null);\n }, [data, isLoading]);\n\n return (\n <div className=\"fk:flex fk:flex-col fk:items-center fk:gap-6 fk:pb-2 fk:text-center\">\n <h2 className=\"fk:text-2xl fk:font-semibold\">{greeting ?? '\\u00A0'}</h2>\n <StarterPanel canSend={canSend} onPrompt={onPrompt} projectId={projectId} />\n {hasSchema ? null : <EmptySchemaPrompts canSend={canSend} onPrompt={onPrompt} projectId={projectId} />}\n </div>\n );\n}\n\n/** A project with no entities and no starter: ways to get a schema from the agent. */\nfunction EmptySchemaPrompts({\n canSend,\n onPrompt,\n projectId,\n}: {\n canSend: boolean;\n onPrompt: (prompt: string) => void;\n projectId: string;\n}): JSX.Element | null {\n // Shares the StarterPanel request; a project with a starter shows its progress there instead.\n const { data, error } = useSWR<{ starter: unknown }>(starterPath(projectId), fetcher, { revalidateOnFocus: false });\n\n if ((data === undefined && error === undefined) || data?.starter) {\n return null;\n }\n\n return (\n <div className=\"fk:mx-auto fk:flex fk:w-full fk:max-w-2xl fk:flex-col fk:items-center fk:gap-3\">\n <p className=\"fk:text-sm fk:text-muted-foreground\">This project has no schema yet. Start with:</p>\n <StarterPrompts canSend={canSend} onPrompt={onPrompt} prompts={EMPTY_STARTER_PROMPTS} />\n </div>\n );\n}\n\nexport function AgentChatPage(): JSX.Element {\n const { api, projectId } = useProjectApi();\n const { currentProject, projectSummaries } = useConfig();\n const { chatId } = useParams<{ chatId: string }>();\n const navigate = useNavigate();\n const location = useLocation();\n const agentBase = useAgentBasePath();\n const { mutate: globalMutate } = useSWRConfig();\n const { data: toolsData } = useSWR<ToolsResponse>(projectId ? paths(projectId).tools() : null, fetcher);\n const { data: rawChatDetail } = useSWR<AgentChatDetail>(\n projectId && chatId ? paths(projectId).agentChat(chatId) : null,\n fetcher\n );\n const seededDetailRef = useRef<{ [chatId: string]: AgentChatDetail }>({});\n\n function resolveDetail(detail: AgentChatDetail | undefined): AgentChatDetail | undefined {\n return resolveSeededChatDetail(seededDetailRef.current, chatId, detail);\n }\n\n const chatDetail = resolveDetail(rawChatDetail);\n const models = useMemo(() => toolsData?.tools.models ?? [], [toolsData]);\n const [selectedModelKey, setSelectedModelKey] = useState<string | null>(null);\n const [selectedEffort, setSelectedEffort] = useState<string | null>(null);\n // The chat's model id when Auto was last picked, so the selector only leaves\n // Auto once the chat reports a model the routed turn chose.\n const autoPickedOnModelIdRef = useRef<string | null>(null);\n const [rememberedModel, setRememberedModel] = useState<ModelSelection | null>(readLastAgentModel);\n const [sending, setSending] = useState(false);\n const sendingRef = useRef(false);\n const [pendingMessage, setPendingMessage] = useState<(PendingMessage & { chatId: string | undefined }) | null>(null);\n const visiblePendingMessage = pendingMessage && pendingMessage.chatId === chatId ? pendingMessage : undefined;\n const [pendingFollowUp, setPendingFollowUp] = useState<(PendingMessage & { chatId: string }) | null>(null);\n const [questionAnsweredSignal, setQuestionAnsweredSignal] = useState<QuestionAnsweredSignal | null>(null);\n const visiblePendingFollowUp = pendingFollowUp && pendingFollowUp.chatId === chatId ? pendingFollowUp : undefined;\n const [sendError, setSendError] = useState<string | null>(null);\n const chatModelId = chatDetail?.chat.modelId ?? null;\n const awaitingChatModel = Boolean(chatId) && chatDetail === undefined;\n // A stored id the catalog no longer lists is kept as-is so the chat keeps sending it.\n const chatSelection = useMemo(\n () => parseModelSelection(chatModelId, models) ?? (chatModelId ? { effort: null, modelKey: chatModelId } : null),\n [chatModelId, models]\n );\n // The API lists Auto first, so a new chat starts on Auto.\n const defaultModelKey = useMemo(() => {\n const model = models.find((item) => !item.deprecated);\n\n return model ? getModelKey(model) : null;\n }, [models]);\n const lastUsed = useMemo(() => {\n const model = findModelByKey(models, rememberedModel?.modelKey ?? null);\n\n return rememberedModel && model && !model.deprecated ? rememberedModel : null;\n }, [models, rememberedModel]);\n const { effort, modelKey } = resolveComposerSelection({\n awaitingChatModel,\n chatSelection,\n defaultModelKey,\n lastUsed,\n selectedEffort,\n selectedModelKey,\n });\n const modelId = modelKey ? formatModelSelection({ effort, modelKey }, models) : null;\n const modelPending = awaitingChatModel && !selectedModelKey;\n\n useEffect(() => {\n autoPickedOnModelIdRef.current = null;\n setSelectedModelKey(null);\n setSelectedEffort(null);\n setSendError(null);\n }, [chatId]);\n\n // Auto resolves to a concrete model on the next routed turn and the chat\n // keeps it; once the chat reports that choice, the selector shows it\n // instead of staying on Auto. The chat's model at the time Auto was picked\n // is not that choice: an existing chat already reports its stored model, and\n // snapping back to it would make Auto impossible to pick for later turns.\n useEffect(() => {\n if (\n selectedModelKey === AUTO_MODEL_KEY &&\n chatModelId &&\n chatModelId !== AUTO_MODEL_KEY &&\n chatModelId !== autoPickedOnModelIdRef.current\n ) {\n setSelectedModelKey(null);\n setSelectedEffort(null);\n }\n }, [chatModelId, selectedModelKey]);\n\n function rememberModel(next: ModelSelection): void {\n setRememberedModel(next);\n writeLastAgentModel(next);\n }\n\n function handleModelChange(nextModelKey: string): void {\n autoPickedOnModelIdRef.current = nextModelKey === AUTO_MODEL_KEY ? chatModelId : null;\n setSelectedModelKey(nextModelKey);\n // The new model's default effort applies until the user picks one.\n setSelectedEffort(null);\n rememberModel({ effort: null, modelKey: nextModelKey });\n }\n\n function handleEffortChange(nextEffort: string): void {\n setSelectedEffort(nextEffort);\n\n if (modelKey) {\n rememberModel({ effort: nextEffort, modelKey });\n }\n }\n\n // A new project whose owner described the business opens with that\n // description as the first message. Clear the navigation state first, so\n // going back to this page or reloading it never sends it again.\n const onboardingPrompt = (location.state as OnboardingNavigationState | null)?.onboardingPrompt;\n const handledPromptKeyRef = useRef<string | null>(null);\n // A first message that failed to send goes back into the composer, so it is not lost.\n const [promptToRestore, setPromptToRestore] = useState<string | null>(null);\n\n useEffect(() => {\n if (\n !onboardingPrompt ||\n handledPromptKeyRef.current === location.key ||\n chatId ||\n !projectId ||\n !api ||\n // Wait for the model catalog, so the first turn uses the remembered or default model.\n !toolsData ||\n modelPending ||\n sendingRef.current\n ) {\n return;\n }\n\n handledPromptKeyRef.current = location.key;\n navigate(location.pathname, { replace: true, state: null });\n void handleSend(onboardingPrompt, []).catch((error: unknown) => {\n setPromptToRestore(onboardingPrompt);\n setSendError(error instanceof Error ? error.message : 'Failed to send the message.');\n });\n // handleSend is redeclared every render; the guards above make this run once per navigation.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [api, chatId, location.key, modelPending, onboardingPrompt, projectId, toolsData]);\n\n if (!projectId || !api) {\n return (\n <div className=\"fk:flex fk:h-full fk:items-center fk:justify-center fk:text-sm fk:text-muted-foreground\">\n Select a project to chat with the agent.\n </div>\n );\n }\n\n const chatApi = api;\n const chatProjectId = projectId;\n const projectName =\n currentProject?.title ?? projectSummaries.find((project) => project.id === projectId)?.name ?? 'your project';\n // A new chat greets in the middle of the page, ChatGPT-style; the first\n // send (a pending message) moves the composer down to its usual place.\n const isNewChat = !chatId && !visiblePendingMessage;\n const turnInProgress = Boolean(chatDetail && splitLiveTurn(chatDetail.messages).live);\n\n async function sendFollowUp(targetChatId: string, text: string, attachments: AgentChatAttachment[]): Promise<void> {\n setPendingFollowUp({ attachments, chatId: targetChatId, text });\n\n try {\n const result = await chatApi.sendAgentChatFollowUp(targetChatId, { attachments, content: text, modelId });\n\n // The message answered the question the turn waited on: resume the live stream so the\n // card shows the reply, and refresh the turn status (no longer awaiting).\n if ('question' in result) {\n setQuestionAnsweredSignal({ messageId: result.question.chatMessageId });\n await globalMutate(paths(chatProjectId).agentChat(targetChatId));\n\n return;\n }\n\n await showSentMessage(targetChatId, result);\n } finally {\n setPendingFollowUp(null);\n }\n }\n\n /** Puts a message the platform stored (a started turn, or a follow-up waiting for one) into the chat at once. */\n async function showSentMessage(\n targetChatId: string,\n result: { followUp: { message: AgentChatMessage } } | { turn: AgentChatTurn }\n ): Promise<void> {\n await globalMutate<AgentChatDetail>(\n paths(chatProjectId).agentChat(targetChatId),\n (current) => {\n const base = getSeedBaseDetail(\n mergeChatDetail(seededDetailRef.current[targetChatId], current),\n null,\n rawChatDetail,\n targetChatId,\n modelId,\n 'turn' in result ? result.turn.userMessage.createdAt : result.followUp.message.createdAt\n );\n const next =\n 'turn' in result\n ? appendTurnToDetail(base, result.turn)\n : appendMessageToDetail(base, result.followUp.message);\n seededDetailRef.current[targetChatId] = next;\n\n return next;\n },\n { revalidate: false }\n );\n }\n\n // A plugin connected from a connect card: the agent continues in a new turn that can use it.\n const pluginConnect = {\n onConnected: async (pluginId: string): Promise<void> => {\n if (!chatId) {\n return;\n }\n\n const targetChatId = chatId;\n\n try {\n await showSentMessage(targetChatId, await chatApi.announcePluginConnected(targetChatId, pluginId));\n } catch (error) {\n setSendError(error instanceof Error ? error.message : 'The agent could not continue after the connection.');\n }\n },\n };\n\n async function handleSend(text: string, attachments: AgentChatAttachment[]): Promise<void> {\n // Reject rather than resolve so the composer does not treat a duplicate\n // submit as a successful send and clear the attachments of the in-flight one.\n if (sendingRef.current) {\n throw new Error('A message is already being sent.');\n }\n\n if (modelPending) {\n throw new Error('This chat is still loading.');\n }\n\n sendingRef.current = true;\n setSending(true);\n setSendError(null);\n\n // During a turn the message is a follow-up: stored at once, then either\n // steering the running turn or starting the next one. A queued follow-up\n // that has not started yet goes first, so the new message cannot jump\n // the queue or race the auto-start.\n const queuedBeforeThis = chatDetail ? getNextQueuedMessage(chatDetail.messages) : null;\n\n if (chatId && (turnInProgress || queuedBeforeThis)) {\n try {\n if (!turnInProgress && queuedBeforeThis) {\n // The auto-start may have won the race; either way a turn is now running.\n await chatApi.startQueuedAgentChatMessage(chatId, queuedBeforeThis.id).catch(() => undefined);\n }\n\n await sendFollowUp(chatId, text, attachments);\n } catch (error) {\n setSendError(error instanceof Error ? error.message : 'Failed to send the message.');\n throw error;\n } finally {\n sendingRef.current = false;\n setSending(false);\n }\n\n return;\n }\n\n setPendingMessage({ attachments, chatId, text });\n\n // Only explicit picks in the selector are remembered (see handleModelChange);\n // what a chat happened to run on, including a routed Auto choice, is not.\n try {\n // A new chat is created and its first message sent by one request: the\n // second round trip (and its auth) used to cost about half a second.\n const started = chatId\n ? { chat: null, turn: await chatApi.sendAgentChatMessage(chatId, { attachments, content: text, modelId }) }\n : await chatApi.startAgentChat({ attachments, content: text, modelId });\n const { chat, turn } = started;\n const targetChatId = chatId ?? chat!.id;\n\n // Seed the confirmed turn without waiting for another network round trip.\n // Keep a local overlay so an in-flight GET that started before POST cannot\n // replace this seed with a snapshot that omits the new messages.\n await globalMutate<AgentChatDetail>(\n paths(chatProjectId).agentChat(targetChatId),\n (current) => {\n const next = appendTurnToDetail(\n getSeedBaseDetail(\n mergeChatDetail(seededDetailRef.current[targetChatId], current),\n chat,\n rawChatDetail,\n targetChatId,\n modelId,\n turn.userMessage.createdAt\n ),\n turn\n );\n seededDetailRef.current[targetChatId] = next;\n\n return next;\n },\n { revalidate: false }\n );\n // Navigate before clearing the pending message so the conversation is\n // never left without a chat or a pending turn between the two updates.\n if (chat) {\n navigate(`${agentBase}/chats/${chat.id}`);\n }\n\n setPendingMessage(null);\n } catch (error) {\n setPendingMessage(null);\n setSendError(error instanceof Error ? error.message : 'Failed to send the message.');\n throw error;\n } finally {\n sendingRef.current = false;\n setSending(false);\n }\n }\n\n async function handleStop(): Promise<void> {\n if (!chatId) {\n return;\n }\n\n try {\n await chatApi.stopAgentChat(chatId);\n } catch (error) {\n setSendError(error instanceof Error ? error.message : 'Failed to stop the turn.');\n } finally {\n await globalMutate(paths(chatProjectId).agentChat(chatId));\n }\n }\n\n return (\n <PromptInputProvider>\n <ComposerDraftSync draftKey={getComposerDraftKey(chatProjectId, chatId)} />\n <ComposerRestore onRestored={setPromptToRestore} text={promptToRestore} />\n <div className=\"fk:flex fk:h-full fk:min-h-0 fk:flex-col fk:gap-2\">\n <div className=\"fk:mb-2 fk:flex fk:shrink-0 fk:items-start fk:gap-2\">\n <Tooltip>\n <TooltipTrigger asChild>\n <SidebarTrigger className=\"fk:-ml-1 fk:h-4 fk:w-4\" />\n </TooltipTrigger>\n <TooltipContent>Toggle Sidebar</TooltipContent>\n </Tooltip>\n <Separator orientation=\"vertical\" className=\"fk:mt-1 fk:h-4\" />\n <div className=\"fk:flex fk:flex-1 fk:items-center fk:gap-2\">\n <h1 className=\"fk:truncate fk:text-lg fk:font-semibold fk:leading-none fk:tracking-tight\">\n {chatId ? (chatDetail?.chat.title?.trim() ?? 'Chat') : 'Agent'}\n </h1>\n </div>\n </div>\n <div className=\"fk:flex fk:min-h-0 fk:flex-1 fk:gap-4\">\n <div\n className={cn(\n 'fk:flex fk:min-h-0 fk:min-w-0 fk:flex-1 fk:flex-col fk:gap-3',\n isNewChat && 'fk:justify-center fk:pb-[12vh]'\n )}\n >\n {!isNewChat ? (\n // One element type for the pending and the loaded chat, so the\n // status line survives the navigation after the chat is created.\n <ChatApprovalContext.Provider value>\n <PluginConnectContext.Provider value={pluginConnect}>\n <ChatConversation\n api={chatApi}\n chatId={chatId ?? null}\n pendingFollowUp={visiblePendingFollowUp}\n pendingMessage={visiblePendingMessage}\n projectId={projectId}\n questionAnsweredSignal={questionAnsweredSignal}\n resolveDetail={resolveDetail}\n />\n </PluginConnectContext.Provider>\n </ChatApprovalContext.Provider>\n ) : (\n <EmptyConversation\n canSend={!sending && !modelPending}\n hasSchema={currentProject ? currentProject.schema.some((entity) => !entity.name.startsWith('_')) : true}\n onPrompt={(prompt) => {\n void handleSend(prompt, []).catch((error: unknown) => {\n setSendError(error instanceof Error ? error.message : 'Failed to send the message.');\n });\n }}\n projectId={chatProjectId}\n />\n )}\n <div className=\"fk:shrink-0 fk:pb-3\">\n {chatId ? (\n <MonitorChips\n api={chatApi}\n chatId={chatId}\n projectId={projectId}\n sending={sending || modelPending}\n onTurnIntoAutomation={(monitor) => {\n // Like the composer: one send at a time.\n if (sendingRef.current || modelPending) {\n return;\n }\n\n void handleSend(`Turn the monitor “${monitor.description}” into an automation.`, []).catch(\n (error: unknown) =>\n setSendError(error instanceof Error ? error.message : 'Failed to send the message.')\n );\n }}\n />\n ) : null}\n {sendError ? (\n <p className=\"fk:mx-auto fk:mb-2 fk:max-w-4xl fk:text-xs fk:text-destructive\">{sendError}</p>\n ) : null}\n <ChatComposer\n api={chatApi}\n effort={effort}\n modelKey={modelKey}\n modelPending={modelPending}\n models={models}\n sending={sending}\n streaming={turnInProgress}\n onEffortChange={handleEffortChange}\n onError={setSendError}\n onModelChange={handleModelChange}\n onSend={handleSend}\n onStop={handleStop}\n placeholder={\n turnInProgress ? 'Add context or steer the agent...' : `Ask Flexkit anything about ${projectName}...`\n }\n />\n </div>\n </div>\n </div>\n </div>\n </PromptInputProvider>\n );\n}\n"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import'./index.css';import {a,c as c$1,d,f as f$1,g as g$1,e as e$1,i,h as h$2}from'./chunk-4ZWQ44NZ.js';import {b as b$1}from'./chunk-DSLPTDZX.js';import {h}from'./chunk-7KLXWCDS.js';import {f}from'./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import'./index.css';import {a,c as c$1,d,f as f$1,g as g$1,e as e$1,i,h as h$2}from'./chunk-4ZWQ44NZ.js';import {b as b$1}from'./chunk-DSLPTDZX.js';import {h}from'./chunk-7KLXWCDS.js';import {f}from'./chunk-TI3EHLRE.js';import {ma}from'./chunk-RULCANNM.js';import {e,g,h as h$1,j as j$1,o,n}from'./chunk-A4DPLZZF.js';import {b}from'./chunk-5JUG4BEF.js';import {c}from'./chunk-X3SHNHHM.js';import {put}from'@vercel/blob/client';import {useMemo,useRef,useEffect,useState}from'react';import {LoaderCircle,EllipsisVerticalIcon,DownloadIcon,ExternalLinkIcon,Trash2Icon}from'lucide-react';import {mutate}from'swr';import {Document}from'@untitledui/file-icons/dist/solid/document.mjs';import {Docx}from'@untitledui/file-icons/dist/solid/docx.mjs';import {Html}from'@untitledui/file-icons/dist/solid/html.mjs';import {Pdf}from'@untitledui/file-icons/dist/solid/pdf.mjs';import {Pptx}from'@untitledui/file-icons/dist/solid/pptx.mjs';import {Txt}from'@untitledui/file-icons/dist/solid/txt.mjs';import {jsx,jsxs,Fragment}from'react/jsx-runtime';var u=class extends Error{code;status;constructor(n,t,r=null){super(t),this.name="KnowledgeApiError",this.code=r,this.status=n;}},k=class extends Error{status;constructor(n,t="Request failed"){super(t),this.name="FetcherError",this.status=n;}},fe=async e=>{let n=await fetch(e,{credentials:"include"});if(!n.ok)throw new k(n.status);return await n.json()};function j(e){let n=`/api/flexkit/${e}/knowledge`;return {entitySources:t=>`${n}/entities/${encodeURIComponent(t)}/sources`,file:t=>`${n}/sources/${encodeURIComponent(t)}/file`,job:t=>`${n}/jobs/${encodeURIComponent(t)}`,links:t=>`${n}/sources/${encodeURIComponent(t)}/links`,passages:(t,{from:r,to:o})=>`${n}/sources/${encodeURIComponent(t)}/passages?from=${String(r)}&to=${String(o)}`,recordSources:({entity:t,recordId:r})=>`${n}/records/${encodeURIComponent(t)}/${encodeURIComponent(r)}/sources`,source:t=>`${n}/sources/${encodeURIComponent(t)}`,sources:(t={})=>{let{limit:r=25,offset:o=0,search:i,status:a}=t,l=new URLSearchParams({limit:r.toString(),offset:o.toString()}),c=i?.trim();return c&&l.set("q",c),a&&l.set("status",a),`${n}/sources?${l.toString()}`},spaces:`/api/flexkit/${e}/spaces`}}function N(e){return typeof e=="string"&&e.includes("/knowledge/sources?")}function J(e){return typeof e=="string"&&(e.includes("/knowledge/records/")||e.includes("/knowledge/entities/")||e.includes("/knowledge/sources/")&&e.endsWith("/links"))}async function L(e,n){let t={};try{t=await e.json();}catch{}return new u(e.status,t.error?String(t.error):n,t.code??null)}function O(e){let n=`/api/flexkit/${e}/knowledge`;async function t(o,i){let{fallback:a,...l}=i,c=await fetch(o,{credentials:"include",headers:{"Content-Type":"application/json",...l.headers??{}},...l});if(!c.ok)throw await L(c,a);return await c.json()}function r(o){return t(`${n}/sources`,{body:JSON.stringify(o),fallback:"The document could not be added.",method:"POST"})}return {addFile:async(o,i)=>{let a=await fetch(`${n}/uploads`,{body:JSON.stringify({filename:o.name,mediaType:o.type||null,sizeBytes:o.size}),credentials:"include",headers:{"Content-Type":"application/json"},method:"POST",signal:i?.signal});if(!a.ok)throw await L(a,"The file could not be uploaded.");let l=await a.json();if(!l.pathname||!l.token||!l.mediaType)throw new u(a.status,"The file could not be uploaded.");return await put(l.pathname,o,{abortSignal:i?.signal,access:"public",contentType:l.mediaType,token:l.token}),r({kind:"upload",pathname:l.pathname})},addUrl:({title:o,url:i})=>r({kind:"url",url:i,...o?{title:o}:{}}),addChatAttachment:({filename:o,url:i})=>r({filename:o,kind:"chat-attachment",url:i}),deleteSource:o=>t(`${n}/sources/${encodeURIComponent(o)}`,{fallback:"The document could not be removed.",method:"DELETE"}),linkSource:(o,i)=>t(`${n}/sources/${encodeURIComponent(o)}/links`,{body:JSON.stringify(i),fallback:"The document could not be attached.",method:"POST"}),reingestSource:o=>t(`${n}/sources/${encodeURIComponent(o)}/reingest`,{fallback:"The document could not be re-indexed.",method:"POST"}),unlinkSource:(o,{entity:i,recordId:a})=>t(`${n}/sources/${encodeURIComponent(o)}/links/${encodeURIComponent(i)}${a===void 0?"":`/${encodeURIComponent(a)}`}`,{fallback:"The document could not be detached.",method:"DELETE"}),updateSource:(o,i)=>t(`${n}/sources/${encodeURIComponent(o)}`,{body:JSON.stringify(i),fallback:"The document could not be updated.",method:"PATCH"})}}var ae={busy:"fk:bg-amber-500/15 fk:text-amber-700 fk:dark:text-amber-400",error:"fk:bg-destructive/15 fk:text-destructive",muted:"fk:bg-muted fk:text-muted-foreground",ready:"fk:bg-emerald-500/15 fk:text-emerald-700 fk:dark:text-emerald-400"};function le(){let{currentProjectId:e}=f();return {api:useMemo(()=>e?O(e):null,[e]),projectId:e}}function de(){return mutate(N,void 0,{revalidate:true})}function Pe(){return mutate(J,void 0,{revalidate:true})}function ce(e,n){return e instanceof u||e instanceof Error?e.message:n}function Ee(e,n){if(e.duplicate){ma.info(`"${e.source.title}" is already in Knowledge.`);return}ma.success(`Added ${n}. Indexing starts now.`);}function _e({children:e}){return jsx("div",{className:"fk:rounded-md fk:border fk:border-dashed fk:p-8 fk:text-center fk:text-sm fk:text-muted-foreground fk:corner-squircle",children:e})}function Me({label:e,tone:n}){return jsxs(b,{className:`fk:border-none fk:corner-squircle ${ae[n]}`,variant:"outline",children:[n==="busy"?jsx(LoaderCircle,{className:"fk:size-3 fk:animate-spin"}):null,e]})}var ue={document:Document,docx:Docx,html:Html,pdf:Pdf,pptx:Pptx,txt:Txt};function ge({className:e="",size:n=24,source:t}){let r=h(t),o=ue[r.icon];return jsx("span",{"aria-label":r.label,className:`fk:flex fk:shrink-0 fk:items-center fk:justify-center ${e}`,"data-knowledge-type":r.icon,role:"img",children:jsx(o,{size:n})})}function Ue({source:e}){return jsx(ge,{size:40,source:e})}function Le({onVisible:e}){let n=useRef(null),t=useRef(e);return t.current=e,useEffect(()=>{let r=n.current;if(!r)return;let o=new IntersectionObserver(i=>{i.some(a=>a.isIntersecting)&&t.current();});return o.observe(r),()=>{o.disconnect();}},[]),jsx("div",{"aria-hidden":true,className:"fk:h-px",ref:n})}function je({isBusy:e$2=false,onOpen:n$1,onRemoved:t,source:r,trigger:o$1="row"}){let{api:i$1,projectId:a$1}=le(),l=b$1(),[c$2,p]=useState(false),[f,b]=useState(false);if(!i$1||!a$1)return null;let X=i$1;async function H(){b(true);try{await X.deleteSource(r.id),ma.success(`Removed "${r.title}".`),p(!1),t(),de();}catch(w){ma.error(ce(w,"The document could not be removed."));}finally{b(false);}}return jsxs(Fragment,{children:[jsxs(e,{children:[jsx(g,{asChild:true,children:jsx(c,{"aria-label":`Actions for ${r.title}`,className:o$1==="row"?"fk:size-8 fk:shrink-0 fk:text-muted-foreground":void 0,"data-knowledge-menu":true,size:"icon-sm",variant:o$1==="row"?"ghost":"outline",children:jsx(EllipsisVerticalIcon,{className:"fk:size-4"})})}),jsxs(h$1,{align:"end",children:[n$1?jsx(j$1,{onSelect:n$1,children:"Open"}):null,r.path?jsx(j$1,{asChild:true,children:jsxs("a",{href:j(a$1).file(r.id),children:[jsx(DownloadIcon,{}),"Download"]})}):null,r.originUrl?jsx(j$1,{asChild:true,children:jsxs("a",{href:r.originUrl,rel:"noreferrer",target:"_blank",children:[jsx(ExternalLinkIcon,{}),"Open page"]})}):null,n$1||r.path||r.originUrl?jsx(o,{}):null,jsxs(j$1,{disabled:!l||e$2,variant:"destructive",onSelect:()=>p(true),children:[jsx(Trash2Icon,{}),"Remove"]}),l?null:jsx(n,{className:"fk:max-w-56 fk:whitespace-normal fk:text-xs fk:font-normal fk:text-muted-foreground",children:"Your member role cannot remove documents."})]})]}),jsx(a,{open:c$2,onOpenChange:p,children:jsxs(c$1,{children:[jsxs(d,{children:[jsx(f$1,{children:"Remove this document?"}),jsxs(g$1,{children:['"',r.title,'" and its indexed passages are deleted for everyone. Answers the agent gave earlier keep their citations, but the document can no longer be opened.']})]}),jsxs(e$1,{children:[jsx(i,{disabled:f,children:"Cancel"}),jsxs(h$2,{disabled:f,onClick:w=>{w.preventDefault(),H();},children:[f?jsx(LoaderCircle,{className:"fk:animate-spin"}):null,"Remove document"]})]})]})})]})}export{k as a,fe as b,j as c,O as d,le as e,de as f,Pe as g,ce as h,Ee as i,_e as j,Me as k,ge as l,Ue as m,Le as n,je as o};//# sourceMappingURL=chunk-7N3LTSVX.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-7N3LTSVX.js.map
|