@flexkit/studio 0.2.35 → 0.2.37

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/dist/{activity-nav-button-ZHQOZBCC.js → activity-nav-button-KOOMUTOW.js} +2 -2
  2. package/dist/{activity-nav-button-ZHQOZBCC.js.map → activity-nav-button-KOOMUTOW.js.map} +1 -1
  3. package/dist/chat-page-XYQOQPMW.js +4 -0
  4. package/dist/chat-page-XYQOQPMW.js.map +1 -0
  5. package/dist/{chunk-W7JDZHCV.js → chunk-337GX2BR.js} +2 -2
  6. package/dist/{chunk-W7JDZHCV.js.map → chunk-337GX2BR.js.map} +1 -1
  7. package/dist/{chunk-7N3LTSVX.js → chunk-36YXPN42.js} +2 -2
  8. package/dist/{chunk-7N3LTSVX.js.map → chunk-36YXPN42.js.map} +1 -1
  9. package/dist/{chunk-DEG7QP5C.js → chunk-6NRMVVU4.js} +3 -3
  10. package/dist/{chunk-DEG7QP5C.js.map → chunk-6NRMVVU4.js.map} +1 -1
  11. package/dist/{chunk-PMLDA2FF.js → chunk-AQSL5HBZ.js} +2 -2
  12. package/dist/{chunk-PMLDA2FF.js.map → chunk-AQSL5HBZ.js.map} +1 -1
  13. package/dist/{chunk-Q4CWQHBJ.js → chunk-BHHLWGZ4.js} +2 -2
  14. package/dist/{chunk-Q4CWQHBJ.js.map → chunk-BHHLWGZ4.js.map} +1 -1
  15. package/dist/{chunk-TI3EHLRE.js → chunk-CC2U7ASG.js} +3 -3
  16. package/dist/{chunk-TI3EHLRE.js.map → chunk-CC2U7ASG.js.map} +1 -1
  17. package/dist/{chunk-J6EGNRRT.js → chunk-CRTUZ22E.js} +3 -3
  18. package/dist/{chunk-J6EGNRRT.js.map → chunk-CRTUZ22E.js.map} +1 -1
  19. package/dist/{chunk-KEGJNZLW.js → chunk-DO32GATF.js} +3 -3
  20. package/dist/{chunk-KEGJNZLW.js.map → chunk-DO32GATF.js.map} +1 -1
  21. package/dist/{chunk-RAUQCO6W.js → chunk-KOM7G7WT.js} +2 -2
  22. package/dist/{chunk-RAUQCO6W.js.map → chunk-KOM7G7WT.js.map} +1 -1
  23. package/dist/{chunk-WU2KCXBC.js → chunk-L5Z56DDM.js} +2 -2
  24. package/dist/{chunk-WU2KCXBC.js.map → chunk-L5Z56DDM.js.map} +1 -1
  25. package/dist/{chunk-36DLIVZF.js → chunk-LVKBKU6Q.js} +2 -2
  26. package/dist/{chunk-36DLIVZF.js.map → chunk-LVKBKU6Q.js.map} +1 -1
  27. package/dist/{chunk-PWGLA33F.js → chunk-ND2RTUMM.js} +3 -3
  28. package/dist/{chunk-PWGLA33F.js.map → chunk-ND2RTUMM.js.map} +1 -1
  29. package/dist/{chunk-PZWEC6KD.js → chunk-OWY5BQER.js} +2 -2
  30. package/dist/{chunk-PZWEC6KD.js.map → chunk-OWY5BQER.js.map} +1 -1
  31. package/dist/chunk-PLCI2RJA.js +3 -0
  32. package/dist/chunk-PLCI2RJA.js.map +1 -0
  33. package/dist/{chunk-ZMONKGWJ.js → chunk-PNGPE7QM.js} +3 -3
  34. package/dist/{chunk-ZMONKGWJ.js.map → chunk-PNGPE7QM.js.map} +1 -1
  35. package/dist/{chunk-XYE6ZAUB.js → chunk-RGISZNQ2.js} +2 -2
  36. package/dist/{chunk-XYE6ZAUB.js.map → chunk-RGISZNQ2.js.map} +1 -1
  37. package/dist/{chunk-R6DPAMLC.js → chunk-RX6QUDLZ.js} +3 -3
  38. package/dist/{chunk-R6DPAMLC.js.map → chunk-RX6QUDLZ.js.map} +1 -1
  39. package/dist/{chunk-BTH7HU5Y.js → chunk-U4DUXPZV.js} +2 -2
  40. package/dist/{chunk-BTH7HU5Y.js.map → chunk-U4DUXPZV.js.map} +1 -1
  41. package/dist/{chunk-ZRTWLY77.js → chunk-UULPCFWK.js} +3 -3
  42. package/dist/{chunk-ZRTWLY77.js.map → chunk-UULPCFWK.js.map} +1 -1
  43. package/dist/{chunk-RFKMFD2O.js → chunk-XV4QJKOJ.js} +2 -2
  44. package/dist/{chunk-RFKMFD2O.js.map → chunk-XV4QJKOJ.js.map} +1 -1
  45. package/dist/chunk-ZV7I5RUM.js +10 -0
  46. package/dist/chunk-ZV7I5RUM.js.map +1 -0
  47. package/dist/{entry-NQRN7SWV.js → entry-6EWYXIS5.js} +2 -2
  48. package/dist/{entry-NQRN7SWV.js.map → entry-6EWYXIS5.js.map} +1 -1
  49. package/dist/index.js +2 -2
  50. package/dist/{list-RPIG75US.js → list-GBM53HFN.js} +2 -2
  51. package/dist/{list-RPIG75US.js.map → list-GBM53HFN.js.map} +1 -1
  52. package/dist/{list-7SCWJXUE.js → list-N5W7G3LD.js} +3 -3
  53. package/dist/{list-7SCWJXUE.js.map → list-N5W7G3LD.js.map} +1 -1
  54. package/dist/{pages-KXERA5Z6.js → pages-HPR3UHT7.js} +3 -3
  55. package/dist/{pages-KXERA5Z6.js.map → pages-HPR3UHT7.js.map} +1 -1
  56. package/dist/{plugin-pages-NXA4BT7Y.js → plugin-pages-VDRT7RLY.js} +2 -2
  57. package/dist/{plugin-pages-NXA4BT7Y.js.map → plugin-pages-VDRT7RLY.js.map} +1 -1
  58. package/dist/{project-selector-SA6UUVBK.js → project-selector-RRG52TSX.js} +2 -2
  59. package/dist/{project-selector-SA6UUVBK.js.map → project-selector-RRG52TSX.js.map} +1 -1
  60. package/dist/record-links-CI4OJPWW.js +2 -0
  61. package/dist/{record-links-RTMCYEPM.js.map → record-links-CI4OJPWW.js.map} +1 -1
  62. package/dist/{root-IBZPU2D4.js → root-DF2BNGOF.js} +3 -3
  63. package/dist/{root-IBZPU2D4.js.map → root-DF2BNGOF.js.map} +1 -1
  64. package/dist/{root-TSZ3CSJU.js → root-IXK2ESCS.js} +3 -3
  65. package/dist/{root-TSZ3CSJU.js.map → root-IXK2ESCS.js.map} +1 -1
  66. package/dist/{root-MBFQXX4E.js → root-JFYE2JRJ.js} +2 -2
  67. package/dist/{root-MBFQXX4E.js.map → root-JFYE2JRJ.js.map} +1 -1
  68. package/dist/{root-6H6K3YQF.js → root-KF6EFGM6.js} +3 -3
  69. package/dist/{root-6H6K3YQF.js.map → root-KF6EFGM6.js.map} +1 -1
  70. package/dist/{root-W5ZPSNQ2.js → root-LUWJS7SQ.js} +2 -2
  71. package/dist/{root-W5ZPSNQ2.js.map → root-LUWJS7SQ.js.map} +1 -1
  72. package/dist/{root-TZIXWEZO.js → root-RGAV2YAF.js} +2 -2
  73. package/dist/{root-TZIXWEZO.js.map → root-RGAV2YAF.js.map} +1 -1
  74. package/dist/{search-ZLEYFT3T.js → search-DQLC3XDJ.js} +2 -2
  75. package/dist/{search-ZLEYFT3T.js.map → search-DQLC3XDJ.js.map} +1 -1
  76. package/dist/{skills-pages-RPMWIBLS.js → skills-pages-Q4YUDTC2.js} +2 -2
  77. package/dist/{skills-pages-RPMWIBLS.js.map → skills-pages-Q4YUDTC2.js.map} +1 -1
  78. package/dist/{source-VYWE5EB5.js → source-J3ZCTEWZ.js} +2 -2
  79. package/dist/{source-VYWE5EB5.js.map → source-J3ZCTEWZ.js.map} +1 -1
  80. package/package.json +6 -6
  81. package/dist/chat-page-IR4RF46H.js +0 -4
  82. package/dist/chat-page-IR4RF46H.js.map +0 -1
  83. package/dist/chunk-FJRDLP7V.js +0 -10
  84. package/dist/chunk-FJRDLP7V.js.map +0 -1
  85. package/dist/chunk-U6VZY3V2.js +0 -3
  86. package/dist/chunk-U6VZY3V2.js.map +0 -1
  87. package/dist/record-links-RTMCYEPM.js +0 -2
@@ -1 +0,0 @@
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,C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AAkD,IACCjD,GAAAA,CAACqX,CAAAA,CAAA,CACC,GAAA,CAAKtB,EAAAA,CACL,OAAQ9S,GAAAA,CACR,SAAA,CAAW5E,GAAAA,CACX,OAAA,CAASwM,CAAAA,EAAWR,CAAAA,CACpB,qBAAuBiN,CAAAA,EAAY,CAE7BjD,IAAW,OAAA,EAAWhK,CAAAA,EAIrByL,GAAW,CAAA,uBAAA,EAAqBwB,CAAAA,CAAQ,WAAW,CAAA,0BAAA,CAAA,CAAyB,EAAE,CAAA,CAAE,KAAA,CAClFjL,GACCuI,CAAAA,CAAavI,CAAAA,YAAiB,MAAQA,CAAAA,CAAM,OAAA,CAAU,6BAA6B,CACvF,EACF,CAAA,CACF,EACE,IAAA,CACHsI,EAAAA,CACC3U,IAAC,GAAA,CAAA,CAAE,SAAA,CAAU,iEAAkE,QAAA,CAAA2U,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,10 +0,0 @@
1
- import'./index.css';import {a}from'./chunk-QSTWBKPN.js';import {d as d$4}from'./chunk-WU2KCXBC.js';import {g,f as f$1,d}from'./chunk-U6VZY3V2.js';import {d as d$2,i,f as f$2,h}from'./chunk-7N3LTSVX.js';import {b as b$4}from'./chunk-DSLPTDZX.js';import {o,e as e$1}from'./chunk-7KLXWCDS.js';import {f,d as d$3}from'./chunk-TI3EHLRE.js';import {b as b$3}from'./chunk-5CVDMZUI.js';import {la as la$1,Lb,Ob,mb,Cc,Dc,Ec,ma as ma$1,n,ra as ra$1,Y,Z,aa as aa$1,ba as ba$1,_,ca as ca$1}from'./chunk-RULCANNM.js';import {t as t$1}from'./chunk-A4DPLZZF.js';import {d as d$1,b as b$5}from'./chunk-G5N6HEPW.js';import {b as b$1}from'./chunk-5JUG4BEF.js';import {k,p,q,s,t,r,n as n$1}from'./chunk-S7Z6KKIN.js';import {b as b$2,c,e}from'./chunk-N33S7BSG.js';import {c as c$1}from'./chunk-X3SHNHHM.js';import {lazy,createContext,useCallback,useState,useRef,useEffect,useMemo,useContext,useTransition,useId,Suspense,useSyncExternalStore}from'react';import qa,{useSWRConfig}from'swr';import {formatDistance,format}from'date-fns';import {RadarIcon,BotIcon,XIcon,PlugIcon,XCircleIcon,LoaderCircle,CheckIcon,CloudUploadIcon,FileTextIcon,DownloadIcon,LinkIcon,MessageSquareIcon,SendIcon,LibraryIcon,ChevronDownIcon,BookOpenIcon,CheckCircle2Icon,CircleSlashIcon,ShieldIcon,DatabaseZapIcon,MessageCircleQuestionIcon,ShieldCheckIcon,TriangleAlertIcon,PlayIcon,ArrowRightIcon,FileIcon,BookOpenTextIcon,CornerDownRightIcon,CircleAlertIcon,MoveRightIcon}from'lucide-react';import {Link,useNavigate}from'react-router-dom';import {jsx,jsxs,Fragment}from'react/jsx-runtime';import {pipeJsonRender}from'@json-render/core';import {readUIMessageStream,parseJsonEventStream,uiMessageChunkSchema}from'ai';function St(){let{currentProjectId:e}=f(),{mutate:t}=useSWRConfig();return useCallback(n=>{if(!e)return;let a=g(e).approvalsCount;n?t(a,n,{revalidate:true}):t(a),t(g(e).activitySummary());},[e,t])}function Nt(e,t){let n=e.split(`
2
- `),a=t.split(`
3
- `);if(n.length*a.length>25e5)return null;let s=a.length+1,r=new Uint32Array((n.length+1)*s);for(let f=n.length-1;f>=0;f--)for(let c=a.length-1;c>=0;c--)r[f*s+c]=n[f]===a[c]?r[(f+1)*s+c+1]+1:Math.max(r[(f+1)*s+c],r[f*s+c+1]);let i=[],d=0,u=0;for(;d<n.length&&u<a.length;)n[d]===a[u]?(i.push({kind:"same",text:n[d]}),d++,u++):r[(d+1)*s+u]>=r[d*s+u+1]?(i.push({kind:"removed",text:n[d]}),d++):(i.push({kind:"added",text:a[u]}),u++);for(;d<n.length;d++)i.push({kind:"removed",text:n[d]});for(;u<a.length;u++)i.push({kind:"added",text:a[u]});return i}var jn=5e3,On=150,Fe=new Set;function Fn(e){return async()=>{let t=await fetch(e,{credentials:"include",mode:"cors"});return t.status===404?"missing":t.ok?(await t.json()).approval??"missing":null}}function Un(e,t,n=d$3){return !e||e.kind!=="schema"||e.status!=="approved"||e.error?false:e.executedAt?(n(t),false):true}function Ne({approvalId:e,approvalUrl:t,fetchApproval:n,projectId:a,revalidate:s=d$3,sleep:r=i=>new Promise(d=>setTimeout(d,i))}){let i=`${a}:${e}`,d=n??(t?Fn(t):null);!d||Fe.has(i)||(Fe.add(i),(async()=>{try{for(let u=0;u<On;u+=1){let f=null;try{f=await d();}catch{f=null;}if(f==="missing"||f!==null&&!Un(f,a,s))return;await r(jn);}}finally{Fe.delete(i);}})());}var Yn=lazy(()=>import('./skills-pages-RPMWIBLS.js').then(e=>({default:e.SkillContentPane}))),Vn={approved:"fk:bg-success/20 fk:text-success",cancelled:"fk:bg-secondary fk:text-secondary-foreground",expired:"fk:bg-secondary fk:text-secondary-foreground",pending:"fk:bg-amber-500/20 fk:text-amber-600",rejected:"fk:bg-destructive/15 fk:text-destructive"};function Wn({status:e}){return jsx(b$1,{className:`fk:border-none fk:h-4.75 fk:text-[0.6875rem] fk:leading-4.5 fk:tracking-wide ${Vn[e]}`,variant:"secondary",children:e})}function U(e){return e==null?"\u2014":typeof e=="object"?JSON.stringify(e):String(e)}function Dt({after:e,before:t}){let n=U(t),a=U(e);return n===a?jsx("span",{className:"fk:text-muted-foreground",children:n}):jsxs("span",{className:"fk:inline-flex fk:flex-wrap fk:items-center fk:gap-1.5",children:[jsx("span",{className:"fk:rounded fk:bg-destructive/10 fk:px-1 fk:text-destructive fk:line-through fk:corner-squircle",children:n}),jsx(MoveRightIcon,{className:"fk:size-3 fk:shrink-0 fk:text-muted-foreground"}),jsx("span",{className:"fk:rounded fk:bg-success/15 fk:px-1 fk:text-success fk:corner-squircle",children:a})]})}function Gn(e){let t=e.entity??"entities",n=e.affectedCount!==null?` \xB7 ${e.affectedCount.toString()} affected`:"";return e.kind==="create"?`Create ${t}${n}`:e.kind==="update"?`Update ${t}${n}`:e.kind==="delete"?`Delete ${t}${n}`:`Mutation on ${t}${n}`}function Zn({operation:e}){if(e.rows.length===0)return null;let t=(e.contextColumns??[]).filter(a=>a!=="_id");if(e.kind==="delete")return jsxs(Y,{children:[jsx(Z,{children:jsxs(aa$1,{children:[jsx(ba$1,{children:"Records to delete"}),t.map(a=>jsx(ba$1,{children:a},a))]})}),jsx(_,{children:e.rows.map((a,s)=>jsxs(aa$1,{className:"fk:bg-destructive/5",children:[jsx(ca$1,{className:"fk:font-mono fk:text-xs fk:text-destructive",children:a.id??U(a.before?._id)}),t.map(r=>jsx(ca$1,{className:"fk:text-xs fk:text-muted-foreground",children:U(a.before?.[r])},r))]},a.id??s.toString()))})]});let n=e.columns.filter(a=>a!=="_id"&&!t.includes(a));return jsxs(Y,{children:[jsx(Z,{children:jsxs(aa$1,{children:[jsx(ba$1,{children:"ID"}),t.map(a=>jsx(ba$1,{children:a},a)),n.map(a=>jsx(ba$1,{children:a},a))]})}),jsx(_,{children:e.rows.map((a,s)=>jsxs(aa$1,{children:[jsx(ca$1,{className:"fk:font-mono fk:text-xs fk:text-muted-foreground",children:a.id??"\u2014"}),t.map(r=>jsx(ca$1,{className:"fk:max-w-72 fk:text-xs fk:text-muted-foreground",children:jsx("span",{className:"fk:line-clamp-3",children:U(a.before?.[r])})},r)),n.map(r=>jsx(ca$1,{className:"fk:text-xs",children:e.kind==="create"?jsx("span",{className:"fk:rounded fk:bg-success/15 fk:px-1 fk:text-success fk:corner-squircle",children:U(a.after?.[r])}):jsx(Dt,{after:a.after?.[r],before:a.before?.[r]})},r))]},a.id??s.toString()))})]})}function ea({operations:e,plugin:t,chat:n,title:a}){return jsxs("details",{className:"fk:rounded-md fk:border fk:border-border fk:corner-squircle",children:[jsx("summary",{className:"fk:cursor-pointer fk:px-3 fk:py-2 fk:text-xs fk:font-medium fk:text-muted-foreground",children:a??(n?"Action details":t?"Plugin tool and arguments":`GraphQL documents (${e.length})`)}),jsx("div",{className:"fk:space-y-3 fk:border-t fk:border-border fk:p-3",children:e.map((s,r)=>jsxs("div",{className:"fk:space-y-2",children:[jsx("pre",{className:"fk:overflow-x-auto fk:rounded-md fk:bg-muted fk:p-3 fk:text-xs fk:corner-squircle",children:s.query}),s.variables&&Object.keys(s.variables).length>0?jsx("pre",{className:"fk:overflow-x-auto fk:rounded-md fk:bg-muted/60 fk:p-3 fk:text-xs fk:corner-squircle",children:JSON.stringify(s.variables,null,2)}):null]},r.toString()))})]})}function It(e){if(e.kind!=="plugin")return null;let n=e.operations[0]?.query.split(`
4
- `)[0]?.trim()?.split("/"),a=n?.at(-1),s=n?.[0];if(!a||!s||n?.length<2)return null;let r=a.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").toLowerCase(),i=s.replace(/[_-]+/g," ").replace(/\b\w/g,c=>c.toUpperCase()),d=e.operations[0]?.query??"",u=/^Connection:\s*(Project|Personal)\s+—\s+(.+)$/m.exec(d);if(u?.[1]&&u[2])return {action:r,app:i,account:u[2].trim(),scope:u[1]==="Project"?"project":"personal"};let f=/^Connection:.*?([^\s<>]+@[^\s<>]+)\s*$/m.exec(d)?.[1];return {action:r,app:i,account:f}}function ta(e){let t=It(e);if(t)return `${t.action.charAt(0).toUpperCase()}${t.action.slice(1)} in ${t.app}`;if(e.kind==="exec")return "Run a sandbox command";if(e.kind==="schema")return e.operationsSummary.replace(/^Schema: /,"");if(e.kind==="automation"&&e.preview?.automation)return `Create the automation \u201C${e.preview.automation.name}\u201D`;if(e.kind==="automation"&&e.preview?.automationChange)return `Change the automation \u201C${e.preview.automationChange.name}\u201D`;if(e.kind==="skill"&&e.preview?.skill){let{before:n,name:a}=e.preview.skill;return n?`Change the skill \u201C${n.name}\u201D`:`Create the skill \u201C${a}\u201D`}return e.kind==="plugin"?"Use a connected app":e.operationsSummary}function na({operation:e}){if(e.rows.length===0)return null;let t=a=>a!=null&&a!==false,n=e.columns.filter(a=>e.rows.some(r=>t(r.before?.[a])||t(r.after?.[a]))?e.kind!=="update"?true:e.rows.some(r=>U(r.before?.[a])!==U(r.after?.[a])):false);return jsx("div",{className:"fk:overflow-x-auto fk:rounded-md fk:border fk:border-border fk:corner-squircle",children:jsxs(Y,{className:"fk:text-xs",children:[jsx(Z,{children:jsxs(aa$1,{children:[jsx(ba$1,{className:"fk:h-8",children:e.entity==="scopes"||e.entity==="spaces"||e.entity==="studio"?"Setting":"Attribute"}),n.map(a=>jsx(ba$1,{className:"fk:h-8",children:a},a))]})}),jsx(_,{children:e.rows.map((a,s)=>jsxs(aa$1,{children:[jsxs(ca$1,{className:"fk:py-1.5 fk:font-mono fk:text-[0.7rem]",children:[e.kind==="delete"?jsx("span",{className:"fk:line-through fk:text-destructive",children:a.id}):a.id,e.kind==="update"&&a.before===null?jsx(b$1,{className:"fk:ml-2",variant:"secondary",children:"new"}):null,e.kind==="update"&&a.after===null?jsx(b$1,{className:"fk:ml-2",variant:"destructive",children:"removed"}):null]}),n.map(r=>jsx(ca$1,{className:"fk:py-1.5",children:e.kind==="create"?jsx("span",{children:U(a.after?.[r])}):e.kind==="delete"?jsx("span",{className:"fk:text-muted-foreground",children:U(a.before?.[r])}):jsx(Dt,{after:a.after?.[r],before:a.before?.[r]})},r))]},a.id??s.toString()))})]})})}function aa(e){let t=e.entity??"schema";return t==="scopes"||t==="spaces"||t==="studio"?`Change ${t==="studio"?"Studio settings":t}`:e.kind==="create"?`Add entity ${t} \xB7 ${e.rows.length.toString()} attribute${e.rows.length===1?"":"s"}`:e.kind==="delete"?`Remove entity ${t}`:`Change entity ${t}`}function sa({preview:e}){let t=e.schema;return jsxs("div",{className:"fk:space-y-4",children:[t&&t.breakingChanges.length>0?jsxs("div",{className:"fk:rounded-md fk:border fk:border-destructive/30 fk:bg-destructive/5 fk:p-3 fk:text-sm fk:corner-squircle",children:[jsxs("div",{className:"fk:mb-1 fk:flex fk:items-center fk:gap-2 fk:font-medium fk:text-destructive",children:[jsx(TriangleAlertIcon,{className:"fk:size-4"}),"Breaking changes: existing data becomes inaccessible"]}),jsx("ul",{className:"fk:list-disc fk:pl-5 fk:text-destructive",children:t.breakingChanges.map(n=>jsx("li",{children:n},n))})]}):null,t&&t.warnings.length>0?jsx("div",{className:"fk:rounded-md fk:border fk:border-amber-500/40 fk:bg-amber-500/10 fk:p-3 fk:text-sm fk:corner-squircle",children:jsx("ul",{className:"fk:list-disc fk:pl-5",children:t.warnings.map(n=>jsx("li",{children:n},n))})}):null,e.operations.map((n,a)=>jsxs("div",{className:"fk:space-y-2",children:[jsx("div",{className:`fk:text-sm fk:font-medium ${n.kind==="delete"?"fk:text-destructive":""}`,children:aa(n)}),jsx(na,{operation:n})]},`${n.entity??""}-${a.toString()}`)),e.operations.length===0?jsx("div",{className:"fk:rounded-md fk:border fk:border-dashed fk:p-3 fk:text-xs fk:text-muted-foreground fk:corner-squircle",children:"No visible entity changes. Review the operations below."}):null]})}function ra(e,t){return e.id===t.id&&e.status===t.status&&e.decidedAt===t.decidedAt&&e.decidedBy===t.decidedBy&&e.executedAt===t.executedAt&&e.error===t.error&&e.reason===t.reason&&e.expiresAt===t.expiresAt&&e.operationsSummary===t.operationsSummary&&e.affectedCount===t.affectedCount&&JSON.stringify(e.preview)===JSON.stringify(t.preview)}function Et({api:e,approval:t,onDecided:n}){let[a,s]=useState(t),[r,i]=useState(t),[d,u]=useState(""),[f,c]=useTransition(),[p,x]=useState(false),[v,k]=useState(false),[g$1,w]=useState(""),y=St();t!==r&&(i(t),ra(t,r)||a.id===t.id&&a.status!=="pending"&&t.status==="pending"||s(t));function C(S){s(S),y(),S.kind==="schema"&&S.status==="approved"&&Ne({approvalId:S.id,approvalUrl:g(S.projectId).approval(S.id),projectId:S.projectId}),n?.(S);}function _({approved:S,automationEdits:R,force:$=false,reason:E,remember:Y=false,skillEdits:L}){c(async()=>{u("");try{let I=await e.decideApproval(a.id,{approved:S,...R?{automationEdits:R}:{},force:$,reason:E,remember:Y,...L?{skillEdits:L}:{}});if(I.errorCode==="stale_preview"){k(!0),I.approval&&s(I.approval);return}if(k(!1),x(!1),I.approval?C(I.approval):I.success?C({...a,decidedAt:a.decidedAt??new Date().toISOString(),reason:E??a.reason,status:S?"approved":"rejected"}):I.errorCode==="already_decided"&&n?.(a),!I.success&&(I.errorCode!=="already_decided"||!I.approval)){let ke=Array.isArray(I.errorMessage)?I.errorMessage.join(", "):I.errorMessage;u(ke||"Failed to submit the decision.");}}catch(I){u(I instanceof Error?I.message:"Failed to submit the decision.");}});}return {approval:a,decide:_,errorMessage:d,isDeciding:f,isPending:a.status==="pending",isRejectDialogOpen:p,isStale:v,rejectReason:g$1,setIsRejectDialogOpen:x,setRejectReason:w}}function Mt({allowRemember:e=false,askForRejectionReason:t$1,decide:n$1,isDeciding:a,isRejectDialogOpen:s$1,isStale:r$1,rejectReason:i,setIsRejectDialogOpen:d,setRejectReason:u,variant:f}){let c=f==="header",p$1=c?"fk:px-8 fk:min-w-32":void 0,x=c?"default":"sm",[v,k$1]=useState(false),g=useId();return jsxs(Fragment,{children:[jsxs("div",{className:"fk:flex fk:flex-nowrap fk:items-center fk:gap-2",children:[jsxs(c$1,{className:p$1,disabled:a,size:x,onClick:()=>n$1({approved:true,force:r$1,remember:e&&v}),children:[a?jsx(LoaderCircle,{className:"fk:size-4 fk:animate-spin"}):jsx(CheckIcon,{className:"fk:size-4"}),r$1?"Approve anyway":"Approve"]}),jsxs(c$1,{className:p$1,disabled:a,size:x,variant:"outline",onClick:()=>{t$1?(u(""),d(true)):n$1({approved:false});},children:[jsx(XIcon,{className:"fk:size-4"}),"Reject"]}),e?jsxs("label",{className:"fk:ml-1 fk:flex fk:cursor-pointer fk:items-center fk:gap-1.5 fk:whitespace-nowrap fk:text-xs fk:text-muted-foreground",htmlFor:g,children:[jsx(n,{checked:v,id:g,onCheckedChange:w=>k$1(w===true)}),"Always allow this tool for this automation"]}):null]}),t$1?jsx(k,{open:s$1,onOpenChange:d,children:jsxs(p,{children:[jsxs(q,{children:[jsx(s,{children:"Reject this proposal?"}),jsx(t,{children:"The mutation will not be executed. The agent receives your reason and can adapt its plan."})]}),jsx(d$1,{placeholder:"Optional reason for the agent...",value:i,onChange:w=>u(w.target.value)}),jsxs(r,{children:[jsx(c$1,{disabled:a,size:"sm",variant:"outline",onClick:()=>d(false),children:"Cancel"}),jsxs(c$1,{disabled:a,size:"sm",variant:"destructive",onClick:()=>n$1({approved:false,reason:i.trim()||void 0}),children:[a?jsx(LoaderCircle,{className:"fk:size-4 fk:animate-spin"}):jsx(ArrowRightIcon,{className:"fk:size-4"}),"Reject proposal"]})]})]})}):null]})}var oa={always:"Every finished run",failures:"Failures only",never:"Never",when_flagged:"Results that need attention"};function $t(e){return e.visibility==="personal"?"Only you":e.visibility==="space"?`Space: ${e.spaceLabel??"unknown"}`:"Everyone in the project"}function ia({approval:e,instructions:t,isPending:n,proposal:a,onInstructionsChange:s}){let r=useId(),i=e.createdAutomation??null,d=[...a.replacesMonitor?[{label:"Replaces",value:`The monitor \u201C${a.replacesMonitor}\u201D, which stops once this exists`}]:[],{label:"Runs",value:a.triggers.join(`
5
- `)},{label:"Visible to",value:$t(a)},{label:"Data changes",value:a.mutationPolicy==="auto_approve"?"Applied without review":"Wait for approval"},{label:"Notifications",value:`${oa[a.notifyRule]}${a.notifyCreator?", to you":""}${a.subscribers.length>0?` and ${a.subscribers.join(", ")}`:""}`},...a.plugins.length>0?[{label:"Plugins",value:a.plugins.map(u=>[u.account?`${u.name} as ${u.account}`:u.name,u.deliveryChannels.length>0?`posting to ${u.deliveryChannels.join(", ")}`:""].filter(Boolean).join(", ")).join(`
6
- `)}]:[],...a.skills.length>0?[{label:"Skills",value:a.skills.join(", ")}]:[],...a.customTools.length>0?[{label:"Custom tools",value:a.customTools.join(", ")}]:[],{label:"Model",value:a.modelLabel}];return jsxs("div",{className:"fk:space-y-4",children:[a.mutationPolicy==="auto_approve"?jsxs("div",{className:"fk:flex fk:items-start fk:gap-2 fk:rounded-md fk:border fk:border-amber-500/40 fk:bg-amber-500/10 fk:p-3 fk:text-sm fk:corner-squircle",role:"status",children:[jsx(TriangleAlertIcon,{className:"fk:mt-0.5 fk:size-4 fk:shrink-0 fk:text-amber-600"}),jsxs("span",{children:["Every run will change data",a.plugins.length>0?" and call these plugins":""," without asking anyone first. Reject and ask for review if that is not what you want."]})]}):null,jsx("dl",{className:"fk:grid fk:grid-cols-[max-content_1fr] fk:gap-x-4 fk:gap-y-1.5 fk:text-sm",children:d.map(u=>jsxs("div",{className:"fk:contents",children:[jsx("dt",{className:"fk:text-muted-foreground",children:u.label}),jsx("dd",{className:"fk:whitespace-pre-line",children:u.value})]},u.label))}),jsxs("div",{className:"fk:space-y-1.5",children:[jsx("label",{className:"fk:text-sm fk:font-medium",htmlFor:r,children:"Instructions"}),n&&s?jsxs(Fragment,{children:[jsx("p",{className:"fk:text-xs fk:text-muted-foreground",children:"The automation never sees this chat, so these instructions are all it has to go on. Edit them before creating it."}),jsx(d$1,{className:"fk:min-h-40 fk:text-sm",id:r,value:t,onChange:u=>s(u.target.value)})]}):jsx("p",{className:"fk:whitespace-pre-wrap fk:rounded-md fk:border fk:p-3 fk:text-sm fk:corner-squircle",id:r,children:t})]}),i?jsxs("div",{className:"fk:flex fk:flex-wrap fk:gap-2",children:[jsx(c$1,{asChild:true,size:"sm",variant:"outline",children:jsx(Link,{to:`/${e.projectId}/ai/automations/${i.automationId}`,children:"Open the automation"})}),i.runId?jsx(c$1,{asChild:true,size:"sm",variant:"ghost",children:jsx(Link,{to:`/${e.projectId}/ai/automations/${i.automationId}/runs/${i.runId}`,children:"View its first run"})}):null]}):null]})}function la({approval:e,change:t}){let n=t.changes.filter(s=>s.field!=="instructions"),a=t.changes.find(s=>s.field==="instructions");return jsxs("div",{className:"fk:space-y-4",children:[n.length>0?jsx("dl",{className:"fk:grid fk:grid-cols-[max-content_1fr] fk:gap-x-4 fk:gap-y-2 fk:text-sm",children:n.map(s=>jsxs("div",{className:"fk:contents",children:[jsx("dt",{className:"fk:text-muted-foreground",children:s.label}),jsxs("dd",{className:"fk:space-y-0.5",children:[jsx("div",{className:"fk:whitespace-pre-line fk:text-muted-foreground fk:line-through",children:s.before}),jsx("div",{className:"fk:whitespace-pre-line",children:s.after})]})]},s.field))}):null,a?jsx("div",{className:"fk:grid fk:gap-3 fk:md:grid-cols-2",children:[{label:"Current instructions",muted:true,text:a.before},{label:"New instructions",muted:false,text:a.after}].map(s=>jsxs("div",{className:"fk:min-w-0 fk:space-y-1.5",children:[jsx("div",{className:"fk:text-sm fk:font-medium",children:s.label}),jsx("p",{className:`fk:whitespace-pre-wrap fk:rounded-md fk:border fk:p-3 fk:text-sm fk:corner-squircle${s.muted?" fk:text-muted-foreground":""}`,children:s.text})]},s.label))}):null,jsx(c$1,{asChild:true,size:"sm",variant:"outline",children:jsx(Link,{to:`/${e.projectId}/ai/automations/${t.automationId}`,children:"Open the automation"})})]})}function zt({decide:e,instructions:t,isDeciding:n,proposal:a}){let s=t.trim(),r=s!==a.instructions.trim()?{instructions:s}:{};return jsxs("div",{className:"fk:flex fk:flex-wrap fk:items-center fk:gap-2",children:[jsxs(c$1,{disabled:n||s.length===0,size:"sm",variant:a.runOnceAfterCreate?"outline":"default",onClick:()=>e({approved:true,automationEdits:{...r,runOnce:false}}),children:[n?jsx(LoaderCircle,{className:"fk:size-4 fk:animate-spin"}):jsx(CheckIcon,{className:"fk:size-4"}),"Create"]}),jsxs(c$1,{disabled:n||s.length===0,size:"sm",variant:a.runOnceAfterCreate?"default":"outline",onClick:()=>e({approved:true,automationEdits:{...r,runOnce:true}}),children:[jsx(PlayIcon,{className:"fk:size-4"}),"Create and run once now"]}),jsxs(c$1,{disabled:n,size:"sm",variant:"outline",onClick:()=>e({approved:false}),children:[jsx(XIcon,{className:"fk:size-4"}),"Reject"]})]})}var Pt=3;function ua(e){let t=[],n=0;for(;n<e.length;){if(e[n].kind!=="same"){t.push(e[n]),n++;continue}let a=n;for(;a<e.length&&e[a].kind==="same";)a++;let s=e.slice(n,a),r=n===0?0:Pt,i=a===e.length?0:Pt;s.length>r+i+1?t.push(...s.slice(0,r),{count:s.length-r-i,kind:"folded"},...s.slice(s.length-i)):t.push(...s),n=a;}return t}var Rt={added:{className:"fk:bg-success/10",marker:"+"},removed:{className:"fk:bg-destructive/10 fk:text-muted-foreground",marker:"\u2212"},same:{className:"",marker:" "}};function da({after:e,before:t}){let n=useMemo(()=>Nt(t,e),[e,t]);if(!n)return jsx("p",{className:"fk:rounded-md fk:border fk:border-dashed fk:p-3 fk:text-xs fk:text-muted-foreground fk:corner-squircle",children:"The skill is too long to compare line by line. Review the new content below."});let a=n.filter(r=>r.kind==="added").length,s=n.filter(r=>r.kind==="removed").length;return jsxs("div",{className:"fk:space-y-1.5",children:[jsxs("div",{className:"fk:text-xs fk:text-muted-foreground",children:[jsxs("span",{className:"fk:text-success",children:["+",a.toString()]})," ",jsxs("span",{className:"fk:text-destructive",children:["\u2212",s.toString()]})," lines"]}),jsx("div",{className:"fk:max-h-96 fk:overflow-auto fk:rounded-md fk:border fk:py-1 fk:font-mono fk:text-xs fk:corner-squircle",children:ua(n).map((r,i)=>r.kind==="folded"?jsxs("div",{className:"fk:px-3 fk:py-0.5 fk:text-muted-foreground",children:["\u22EF ",r.count.toString()," unchanged ",r.count===1?"line":"lines"]},i.toString()):jsxs("div",{className:`fk:flex fk:gap-2 fk:px-3 ${Rt[r.kind].className}`,children:[jsx("span",{"aria-hidden":true,className:"fk:w-2 fk:shrink-0 fk:select-none fk:text-muted-foreground",children:Rt[r.kind].marker}),jsx("span",{className:"fk:min-w-0 fk:whitespace-pre-wrap fk:break-words",children:r.text||" "})]},i.toString()))})]})}function Tt({after:e,before:t,label:n}){return e===t?null:jsxs("div",{className:"fk:contents",children:[jsx("dt",{className:"fk:text-muted-foreground",children:n}),jsxs("dd",{className:"fk:space-y-0.5",children:[jsx("div",{className:"fk:whitespace-pre-line fk:text-muted-foreground fk:line-through",children:t}),jsx("div",{className:"fk:whitespace-pre-line",children:e})]})]})}function ca({approval:e,fields:t,isPending:n,proposal:a,onFieldsChange:s}){let r=useId(),i=useId(),{before:d}=a,u=e.savedSkillId??a.skillId,f=n&&s;return jsxs("div",{className:"fk:space-y-4",children:[jsxs("dl",{className:"fk:grid fk:grid-cols-[max-content_1fr] fk:gap-x-4 fk:gap-y-2 fk:text-sm",children:[jsx("dt",{className:"fk:text-muted-foreground",children:"Visible to"}),jsx("dd",{children:$t(a)}),d?jsxs(Fragment,{children:[jsx(Tt,{after:t.name,before:d.name,label:"Name"}),jsx(Tt,{after:t.description,before:d.description,label:"Description"})]}):null]}),d?d.content===t.content?jsx("p",{className:"fk:text-sm fk:text-muted-foreground",children:"The content stays the same."}):jsxs("div",{className:"fk:space-y-1.5",children:[jsx("div",{className:"fk:text-sm fk:font-medium",children:"Changes to the content"}),jsx(da,{after:t.content,before:d.content})]}):null,f?jsxs("div",{className:"fk:space-y-3",children:[jsx("p",{className:"fk:text-xs fk:text-muted-foreground",children:"Every chat and automation that can see this skill picks it by its description and follows its content. Edit them before saving."}),jsxs("div",{className:"fk:space-y-1.5",children:[jsx("label",{className:"fk:text-sm fk:font-medium",htmlFor:r,children:"Name"}),jsx(b$5,{id:r,maxLength:120,value:t.name,onChange:c=>s({...t,name:c.target.value})})]}),jsxs("div",{className:"fk:space-y-1.5",children:[jsx("label",{className:"fk:text-sm fk:font-medium",htmlFor:i,children:"Description"}),jsx(d$1,{className:"fk:min-h-16 fk:text-sm",id:i,maxLength:1024,value:t.description,onChange:c=>s({...t,description:c.target.value})})]}),jsx("div",{className:"fk:flex fk:h-96 fk:min-w-0 fk:flex-col",children:jsx(Suspense,{fallback:jsx(t$1,{className:"fk:min-h-0 fk:flex-1 fk:rounded-md"}),children:jsx(Yn,{content:t.content,onChange:c=>s({...t,content:c})})})})]}):jsxs("div",{className:"fk:space-y-3 fk:text-sm",children:[d?null:jsxs("div",{className:"fk:space-y-0.5",children:[jsx("div",{className:"fk:font-medium",children:"Description"}),jsx("p",{className:"fk:whitespace-pre-line fk:text-muted-foreground",children:t.description})]}),jsxs("details",{className:"fk:rounded-md fk:border fk:corner-squircle",children:[jsx("summary",{className:"fk:cursor-pointer fk:px-3 fk:py-2 fk:font-medium",children:"Content"}),jsx("pre",{className:"fk:max-h-96 fk:overflow-auto fk:whitespace-pre-wrap fk:border-t fk:p-3 fk:font-mono fk:text-xs",children:t.content})]})]}),u&&(!n||d)?jsx(c$1,{asChild:true,size:"sm",variant:"outline",children:jsx(Link,{to:`/${e.projectId}/ai/skills/${u}`,children:"Open the skill"})}):null]})}function _t({decide:e,fields:t,isDeciding:n,proposal:a}){let s={content:t.content.trim(),description:t.description.trim(),name:t.name.trim()},r=!s.name||!s.description||!s.content,i=Object.fromEntries(Object.keys(s).filter(d=>s[d]!==a[d].trim()).map(d=>[d,s[d]]));return jsxs("div",{className:"fk:flex fk:flex-wrap fk:items-center fk:gap-2",children:[jsxs(c$1,{disabled:n||r,size:"sm",onClick:()=>e({approved:true,...Object.keys(i).length>0?{skillEdits:i}:{}}),children:[n?jsx(LoaderCircle,{className:"fk:size-4 fk:animate-spin"}):jsx(CheckIcon,{className:"fk:size-4"}),a.before?"Save changes":"Save skill"]}),jsxs(c$1,{disabled:n,size:"sm",variant:"outline",onClick:()=>e({approved:false}),children:[jsx(XIcon,{className:"fk:size-4"}),"Reject"]})]})}function Lt(e){let t=e.kind==="skill"?e.preview?.skill??null:null,[n,a]=useState(null);return {fields:n?.approvalId===e.id?n.fields:t?{content:t.content,description:t.description,name:t.name}:null,proposal:t,setFields:r=>a({approvalId:e.id,fields:r})}}function jt({approval:e,automationInstructions:t,chat:n,errorMessage:a,isPending:s,isStale:r,onAutomationInstructionsChange:i,onSkillFieldsChange:d,skillFields:u}){let{preview:f}=e,c=n?It(e):null;return jsxs("div",{className:"fk:min-w-0 fk:max-w-full fk:space-y-4",children:[jsxs("div",{className:"fk:flex fk:flex-wrap fk:items-center fk:gap-2",children:[jsx(Wn,{status:e.status}),e.kind==="schema"?jsx(b$1,{variant:"outline",children:"Schema change"}):null,e.kind==="automation"?jsx(b$1,{variant:"outline",children:f?.automationChange?"Automation change":"New automation"}):null,e.kind==="skill"?jsx(b$1,{variant:"outline",children:f?.skill?.before?"Skill change":"New skill"}):null,jsx("span",{className:"fk:text-sm fk:font-medium",children:n?ta(e):e.operationsSummary})]}),jsxs("div",{className:"fk:text-xs fk:text-muted-foreground",children:[e.automationName?`${e.automationName} \xB7 `:"","requested ",formatDistance(new Date(e.requestedAt),new Date,{addSuffix:true}),s?` \xB7 expires ${formatDistance(new Date(e.expiresAt),new Date,{addSuffix:true})}`:"",e.decidedAt?` \xB7 decided ${format(new Date(e.decidedAt),"PPpp")}`:""]}),r?jsxs("div",{className:"fk:flex fk:items-start fk:gap-2 fk:rounded-md fk:border fk:border-amber-500/40 fk:bg-amber-500/10 fk:p-3 fk:text-sm fk:corner-squircle",children:[jsx(TriangleAlertIcon,{className:"fk:mt-0.5 fk:size-4 fk:shrink-0 fk:text-amber-600"}),jsx("span",{children:"The affected data changed since this proposal was created. The preview below has been refreshed \u2014 review it and approve again to proceed."})]}):null,e.kind==="automation"&&f?.automation?jsx(ia,{approval:e,instructions:t??f.automation.instructions,isPending:s,proposal:f.automation,onInstructionsChange:i}):e.kind==="automation"&&f?.automationChange?jsx(la,{approval:e,change:f.automationChange}):e.kind==="skill"&&f?.skill?jsx(ca,{approval:e,fields:u??f.skill,isPending:s,proposal:f.skill,onFieldsChange:d}):e.kind==="schema"&&f?jsx(sa,{preview:f}):f&&f.operations.length>0?jsx("div",{className:"fk:space-y-4",children:f.operations.map((p,x)=>jsxs("div",{className:"fk:space-y-2",children:[jsx("div",{className:"fk:text-sm fk:font-medium",children:Gn(p)}),p.kind==="delete"&&p.affectedCount!==null?jsxs("div",{className:"fk:rounded-md fk:border fk:border-destructive/30 fk:bg-destructive/5 fk:p-3 fk:text-sm fk:text-destructive fk:corner-squircle",children:[p.affectedCount.toString()," record",p.affectedCount===1?"":"s"," will be permanently deleted."]}):null,jsx(Zn,{operation:p}),p.truncated?jsxs("div",{className:"fk:text-xs fk:text-muted-foreground",children:["Preview limited to the first ",p.rows.length.toString()," rows."]}):null]},x.toString()))}):jsx("div",{className:"fk:rounded-md fk:border fk:border-dashed fk:p-3 fk:text-xs fk:text-muted-foreground fk:corner-squircle",children:n?c?`This action uses ${c.scope==="project"?"the project's":"your"} ${c.app} account${c.account?` (${c.account})`:""}. Check the details before deciding.`:"The assistant wants to make this change. Check the details before deciding.":e.kind==="plugin"?"Review the account, tool, and arguments before allowing this external call.":e.kind==="exec"?"This command runs inside the run's ephemeral sandbox but may send data out or reach other hosts. Review the command line before allowing it.":"No structured preview is available for this proposal. Review the raw GraphQL documents below."}),e.kind==="automation"||e.kind==="skill"?null:jsx(ea,{chat:n,operations:e.operations,plugin:e.kind==="plugin"||e.kind==="exec",title:e.kind==="exec"?"Command and options":e.kind==="schema"?"Operations":void 0}),e.reason?jsxs("div",{className:"fk:text-sm",children:[jsx("span",{className:"fk:font-medium",children:"Reason:"})," ",e.reason]}):null,e.error?jsxs("div",{className:"fk:rounded-md fk:border fk:border-destructive/30 fk:bg-destructive/5 fk:p-3 fk:text-sm fk:corner-squircle",children:["Execution failed: ",e.error]}):null,e.executedAt&&!e.error?jsxs("div",{className:"fk:flex fk:items-center fk:gap-2 fk:text-sm fk:text-success",children:[jsx(CheckIcon,{className:"fk:size-4"}),"Executed ",format(new Date(e.executedAt),"PPpp")]}):null,a?jsx("div",{className:"fk:text-sm fk:text-destructive",children:a}):null]})}function Ot({api:e,approval:t,chat:n,onDecided:a}){let{approval:s,decide:r,errorMessage:i,isDeciding:d,isPending:u,isRejectDialogOpen:f,isStale:c,rejectReason:p,setIsRejectDialogOpen:x,setRejectReason:v}=Et({api:e,approval:t,onDecided:a}),k=s.kind==="automation"?s.preview?.automation??null:null,[g,w]=useState(k?.instructions??""),y=Lt(s);return jsxs(Fragment,{children:[jsx(jt,{approval:s,automationInstructions:k?g:void 0,chat:n,errorMessage:i,isPending:u,isStale:c,onAutomationInstructionsChange:k?w:void 0,onSkillFieldsChange:y.proposal?y.setFields:void 0,skillFields:y.fields??void 0}),u&&y.proposal&&y.fields?jsx("div",{className:"fk:mt-4",children:jsx(_t,{decide:r,fields:y.fields,isDeciding:d,proposal:y.proposal})}):u&&k?jsx("div",{className:"fk:mt-4",children:jsx(zt,{decide:r,instructions:g,isDeciding:d,proposal:k})}):u?jsx("div",{className:"fk:mt-4",children:jsx(Mt,{allowRemember:!n&&s.kind==="plugin"&&!!s.automationId,askForRejectionReason:!n,decide:r,isDeciding:d,isRejectDialogOpen:f,isStale:c,rejectReason:p,setIsRejectDialogOpen:x,setRejectReason:v,variant:"inline"})}):null]})}function Sr({api:e,approval:t,onClose:n,onDecided:a}){let{approval:s,decide:r,errorMessage:i,isDeciding:d,isPending:u,isRejectDialogOpen:f,isStale:c,rejectReason:p,setIsRejectDialogOpen:x,setRejectReason:v}=Et({api:e,approval:t,onDecided:a}),k=s.kind==="automation"?s.preview?.automation??null:null,[g,w]=useState(k?.instructions??""),y=Lt(s);return jsx(la$1,{actions:u&&y.proposal&&y.fields?jsx(_t,{decide:r,fields:y.fields,isDeciding:d,proposal:y.proposal}):u&&k?jsx(zt,{decide:r,instructions:g,isDeciding:d,proposal:k}):u?jsx(Mt,{allowRemember:s.kind==="plugin"&&!!s.automationId,askForRejectionReason:true,decide:r,isDeciding:d,isRejectDialogOpen:f,isStale:c,rejectReason:p,setIsRejectDialogOpen:x,setRejectReason:v,variant:"header"}):null,depth:0,isFocused:true,onClose:n,title:k?"Automation proposal":s.preview?.automationChange?"Automation change":y.proposal?y.proposal.before?"Skill change":"Skill proposal":"Mutation proposal",children:jsx(jt,{approval:s,automationInstructions:k?g:void 0,chat:false,errorMessage:i,isPending:u,isStale:c,onAutomationInstructionsChange:k?w:void 0,onSkillFieldsChange:y.proposal?y.setFields:void 0,skillFields:y.fields??void 0})})}var fa="Approved by Flexkit Jev policy",pa="Approved by automation tool allow rule",ma=new Set(["data-create-sandbox","data-execute-graphql","data-export-records","data-load-skill","data-plan","data-plugin-call","data-read-source","data-run-command","data-search-schema","data-update-memory","data-validate-graphql","data-web-search"]);function me(e){return ma.has(e)}function b(e){return e.data}function Be(e){return !e.decidedBy&&!!(e.reason?.startsWith(fa)||e.reason?.startsWith(pa))}function H(e,t=72){let n=e.trim();if(n.length<=t)return n;let a=n.slice(0,t),s=a.lastIndexOf(" ");return `${(s>=Math.floor(t*.6)?a.slice(0,s):a).trimEnd()}\u2026`}function ka(e){return e.replace(/^#{1,6}\s+/,"").replace(/^(?:[-*+]|\d+[.)])\s+/,"").replace(/!?\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/(\*\*|__)(.*?)\1/g,"$2").replace(/(\*|_)(.*?)\1/g,"$2").replace(/`([^`]*)`/g,"$1").replace(/[*_`#>]/g,"").replace(/\s+/g," ").trim().replace(/[.:]+$/,"")}function ga(e){let t=e.lastIndexOf(`
7
- `),n=-1,a=/[.!?](?=\s)/g,s;for(;(s=a.exec(e))!==null;)n=s.index;let r=Math.max(t,n);return r<0?"":e.slice(0,r+1)}function va(e,t){let a=(ga(e)).split(/\r?\n/).map(u=>u.trim()).filter(Boolean),s=a[a.length-1];if(!s)return null;let i=/^\*\*(.+?)\*\*:?$/.exec(s)?.[1]??/^#{1,6}\s+(.+)$/.exec(s)?.[1]??/^(.+?[.!?])(?:\s|$)/.exec(s)?.[1]??s,d=ka(i);return !d||/^reasoning$/i.test(d)?null:H(d)}function Ft(e){return e.replace(/[_-]+/g," ").trim()}function ha(e){if(e.type==="data-load-skill"){let t=b(e);return t.status!=="loading"?null:t.skillName?H(`Loading skill "${t.skillName}"`):"Loading skill"}if(e.type==="data-search-schema")return b(e).status==="loading"?"Searching schema":null;if(e.type==="data-validate-graphql")return b(e).status==="loading"?"Validating GraphQL query":null;if(e.type==="data-execute-graphql"){let t=b(e);return t.status!=="loading"?null:t.operationType==="mutation"?"Executing GraphQL mutation":"Executing GraphQL query"}if(e.type==="data-export-records"){let t=b(e);return t.status!=="loading"?null:t.rowCount>0?`Exporting records (${t.rowCount.toLocaleString("en-US")} so far)`:"Exporting records"}if(e.type==="data-update-memory")return b(e).status==="loading"?"Updating memory":null;if(e.type==="data-web-search"){let t=b(e);return t.status!=="loading"?null:t.query?H(`Searching the web for "${t.query}"`):"Searching the web"}if(e.type==="data-run-command"){let t=b(e);return ["executing","running","waiting"].includes(t.status)?H(`Running ${[t.command,...t.args].join(" ")}`):null}if(e.type==="data-create-sandbox")return b(e).status==="loading"?"Creating sandbox":null;if(e.type==="data-plugin-call"){let t=b(e);return t.status!=="loading"?null:H(`Calling ${t.pluginId}: ${Ft(t.tool)}`)}if(e.type==="data-subtask"){let t=b(e);return t.status==="running"?H(`Running subtask: ${t.title}`):null}if(e.type==="data-knowledge-search"){let t=b(e);return t.status!=="loading"?null:t.query?H(`Searching knowledge for "${t.query}"`):"Searching knowledge"}if(e.type==="data-read-source"){let t=b(e);return t.status!=="loading"?null:t.sourceTitle?H(`Reading "${t.sourceTitle}"`):"Reading a document"}return null}var ya=new Set(["data-execute-graphql","data-read-source","data-search-schema","data-validate-graphql"]);function De(e){if(!me(e.type)||e.type==="data-plan"||ya.has(e.type))return null;let t=b(e);if(t.status!=="error")return null;if(t.error?.message)return t.error.message;switch(e.type){case "data-web-search":return "Failed to search the web";case "data-run-command":return `Command failed: ${String(t.command??"")}`.trim();case "data-create-sandbox":return "Failed to create sandbox";case "data-load-skill":return "Failed to load skill";case "data-update-memory":return "Failed to update memory";case "data-plugin-call":return `Plugin call failed: ${String(t.pluginId??"")}: ${Ft(String(t.tool??""))}`;default:return "The tool call failed"}}function Ie(e){if(e.type==="step-start"||e.type==="reasoning")return true;if(me(e.type))return De(e)===null;if(e.type==="data-knowledge-search")return b(e).status==="loading";if(e.type==="data-mutation-approval"){let t=b(e);return Be(t)&&t.status!=="error"}return false}function pe(e){if(!e)return null;for(let t=e.parts.length-1;t>=0;t--){let n=e.parts[t];if(n?.type!=="data-plan")continue;let a=b(n),s=a.steps.findIndex(r=>r.status==="in_progress");return s<0?null:H(`Step ${(s+1).toString()} of ${a.steps.length.toString()}: ${a.steps[s].step}`)}return null}function ba(e){if(!e)return null;for(let t=e.parts.length-1;t>=0;t--){let n=e.parts[t];if(!(!n||n.type==="step-start"))return n.type==="reasoning"?n.state==="streaming"?va(n.text)??pe(e):pe(e):n.type==="data-mutation-approval"?b(n).status==="pending"?"Awaiting approval":pe(e):n.type==="data-user-question"?b(n).status==="pending"?"Waiting for your answer":pe(e):n.type==="text"?null:ha(n)??pe(e)}return null}function Xe(e){return e?e.parts.some(t=>t.type!=="data-mutation-approval"?false:b(t).status==="pending"):false}function Je(e,t={}){let n=false,a=[];for(let s of e.parts){if(s.type!=="data-mutation-approval"){a.push(s);continue}let r=b(s);if(r.status!=="pending"){a.push(s);continue}n=true;let i=t[r.approvalId];i&&i!=="pending"&&a.push({...s,data:{...r,status:i}});}return n?{...e,parts:a}:e}function Ut(e,t){if(!e)return [];let n=[],a=t?.pendingOnly??false;for(let s of e.parts){if(s.type!=="data-mutation-approval")continue;let r=b(s);a&&r.status!=="pending"||n.push(r.approvalId);}return n}function xa(e){return Ut(e,{pendingOnly:true})}function Qe(e){return !!e?.parts.some(t=>t.type==="data-user-question"&&b(t).status==="pending")}function qt(e){return e.map(()=>({other:"",selected:[]}))}function Bt(e,t,n){return e.multiSelect?{...t,selected:t.selected.includes(n)?t.selected.filter(a=>a!==n):[...t.selected,n]}:{other:"",selected:[n]}}function Xt(e,t,n){return e.multiSelect?{...t,other:n}:{other:n,selected:n.trim()?[]:t.selected}}function Jt(e){let t=[];for(let n of e){let a=n.other.trim();if(n.selected.length===0&&!a)return null;t.push(a?{other:a,selected:n.selected}:{selected:n.selected});}return t}function Qt(e){return e&&[...e.selected,...e.other?[`\u201C${e.other}\u201D`]:[]].join(", ")||"\u2014"}function wa(e){return Array.isArray(e)?e.filter(t=>t.type==="file"&&typeof t.url=="string").map(t=>({filename:t.filename??"file",mediaType:t.mediaType??"application/octet-stream",sizeBytes:t.sizeBytes??0,url:t.url??"",...t.sha256?{sha256:t.sha256}:{},...t.knowledgeSourceId!==void 0?{knowledgeSourceId:t.knowledgeSourceId}:{}})):[]}function Ht(e,t){return e.kind!=="idle"?e:t.knowledgeSourceId?{kind:"added",sourceId:t.knowledgeSourceId}:e}function Da(e){return typeof e=="string"&&e.includes("/agent/chats/")}function Kt({attachment:e$2}){let{currentProjectId:t}=f(),n=b$4(),a=useNavigate(),{mutate:s}=useSWRConfig(),r=useMemo(()=>t?d$2(t):null,[t]),[i$1,d]=useState({kind:"idle"}),u=Ht(i$1,e$2),f$1=e$1({name:e$2.filename,size:e$2.sizeBytes})===null;if(!r||!t||!n||!f$1)return null;let c$1=r,p=t;async function x(){d({kind:"adding"});try{let g=await c$1.addChatAttachment({filename:e$2.filename,url:e$2.url});i(g,e$2.filename),d({kind:"added",sourceId:g.source.id}),f$2(),s(Da);}catch(g){ma$1.error(h(g,`${e$2.filename} could not be added to Knowledge.`)),d({kind:"idle"});}}let v="Add to Knowledge",k=jsx(BookOpenTextIcon,{className:"fk:size-3"});return u.kind==="adding"?k=jsx(LoaderCircle,{className:"fk:size-3 fk:animate-spin"}):u.kind==="added"&&(v="Open in Knowledge",k=jsx(CheckIcon,{className:"fk:size-3"})),jsxs(b$2,{children:[jsx(c,{asChild:true,children:jsx("button",{"aria-disabled":u.kind==="adding","aria-label":`${v}: ${e$2.filename}`,className:"fk:absolute fk:top-1 fk:right-1 fk:z-10 fk:flex fk:size-5 fk:items-center fk:justify-center fk:rounded-full fk:border fk:border-border fk:bg-background fk:text-foreground fk:shadow-sm fk:transition-colors fk:hover:bg-accent fk:focus-visible:outline-none fk:focus-visible:ring-2 fk:focus-visible:ring-ring fk:aria-disabled:cursor-default fk:aria-disabled:hover:bg-background fk:corner-squircle","data-knowledge-state":u.kind,type:"button",onClick:g=>{g.stopPropagation(),g.preventDefault(),u.kind==="idle"?x():u.kind==="added"&&a(o(p,u.sourceId));},children:k})}),jsx(e,{children:v})]})}var Yt=20*1024*1024,Yr=10,Wt=new Set(["css","csv","gif","gql","graphql","htm","html","jpeg","jpg","js","json","jsx","log","markdown","md","mjs","ndjson","pdf","png","py","sql","ts","tsv","tsx","txt","webp","xml","yaml","yml"]),Gt=new Set(["application/pdf","image/gif","image/jpeg","image/png","image/webp"]),Vr=[...[...Wt].map(e=>`.${e}`),...Gt].join(",");function Zt(e){let t=e.lastIndexOf(".");return t<=0?"":e.slice(t+1).toLowerCase()}function za(e){let t=Zt(e.name);return (t?Wt.has(t):Gt.has(e.type))?e.size===0?`"${e.name}" is empty.`:e.size>Yt?`"${e.name}" exceeds the ${String(Math.round(Yt/(1024*1024)))} MB limit.`:null:`"${e.name}" is not supported. Attach images, PDFs, or text files.`}async function _a(e){let n=await(await fetch(e.url)).blob();return new File([n],e.filename??"file",{type:e.mediaType||n.type})}function Wr(e,t){let{attachments:n}=Lb(),a=useRef({}),[,s]=useState(0),r=useCallback(()=>s(f=>f+1),[]),i=useRef(n.remove);i.current=n.remove;let d=useRef(t);d.current=t,useEffect(()=>{let f=new Set(n.files.map(c=>c.id));for(let[c,p]of Object.entries(a.current))f.has(c)||(p.controller.abort(),delete a.current[c]);for(let c of n.files){if(a.current[c.id])continue;let p=new AbortController,x={controller:p,status:"uploading"};a.current[c.id]=x,(async()=>{try{let v=await _a(c),k=za(v);if(k)throw new Error(k);let g=await e.uploadAgentChatAttachment(v,p.signal);if(p.signal.aborted)return;x.attachment=g,x.status="done";}catch(v){if(p.signal.aborted)return;x.status="error",delete a.current[c.id],i.current(c.id),d.current(v instanceof Error?v.message:"The file could not be uploaded.");}finally{r();}})();}r();},[e,n.files,r]);let u=Object.values(a.current).some(f=>f.status==="uploading");return {getUploaded:f=>f.map(c=>a.current[c]?.attachment).filter(c=>!!c),isUploading:u,isUploadingFile:f=>a.current[f]?.status==="uploading"}}function Ke(e){return !!e?.startsWith("image/")}function en({image:e,onClose:t}){return jsx(k,{onOpenChange:n=>n?void 0:t(),open:e!==null,children:jsxs(p,{className:"fk:h-dvh fk:w-dvw fk:max-w-none fk:sm:max-w-none fk:rounded-none fk:border-0 fk:bg-black/90 fk:p-4 fk:shadow-none fk:flex fk:items-center fk:justify-center fk:corner-squircle",showCloseButton:false,children:[jsx(s,{className:"fk:sr-only",children:e?.filename??"Image preview"}),e?jsx("img",{alt:e.filename,className:"fk:block fk:h-auto fk:w-auto fk:max-h-full fk:max-w-full fk:object-contain",src:e.url}):null,jsx(n$1,{"aria-label":"Close preview",className:"fk:absolute fk:top-4 fk:right-4 fk:flex fk:size-9 fk:items-center fk:justify-center fk:rounded-full fk:bg-white/10 fk:text-white fk:transition-colors fk:hover:bg-white/20 fk:focus-visible:outline-none fk:focus-visible:ring-2 fk:focus-visible:ring-white/60 fk:corner-squircle",children:jsx(XIcon,{className:"fk:size-5"})})]})})}function tn({label:e,onRemove:t}){return jsx("button",{"aria-label":e,className:"fk:absolute fk:top-1 fk:right-1 fk:z-10 fk:flex fk:size-5 fk:items-center fk:justify-center fk:rounded-full fk:border fk:border-border fk:bg-background fk:text-foreground fk:shadow-sm fk:transition-colors fk:hover:bg-accent fk:focus-visible:outline-none fk:focus-visible:ring-2 fk:focus-visible:ring-ring fk:corner-squircle",onClick:n=>{n.stopPropagation(),t();},type:"button",children:jsx(XIcon,{className:"fk:size-3"})})}function nn({image:e,isUploading:t=false,onOpen:n,onRemove:a,sizeClassName:s}){return jsxs("div",{className:`fk:relative fk:shrink-0 fk:overflow-hidden fk:rounded-xl fk:bg-muted ${s} fk:corner-squircle`,children:[jsx("button",{"aria-label":`Preview ${e.filename}`,className:"fk:block fk:size-full fk:cursor-zoom-in fk:focus-visible:outline-none fk:focus-visible:ring-2 fk:focus-visible:ring-ring",onClick:n,type:"button",children:jsx("img",{alt:e.filename,className:"fk:size-full fk:object-cover",src:e.url})}),t?jsx("div",{className:"fk:pointer-events-none fk:absolute fk:inset-0 fk:flex fk:items-center fk:justify-center fk:bg-background/60",children:jsx(ra$1,{className:"fk:size-4"})}):null,a?jsx(tn,{label:`Remove ${e.filename}`,onRemove:a}):null]})}function La(e,t){let n=Zt(e);if(n)return n.toUpperCase();let a=t?.split("/")[1]?.split("+")[0];return a?a.toUpperCase():"FILE"}function an({action:e,file:t,href:n,isUploading:a=false,onRemove:s}){let r=jsxs(Fragment,{children:[jsx("div",{className:"fk:flex fk:size-10 fk:shrink-0 fk:items-center fk:justify-center fk:rounded-lg fk:bg-muted fk:text-muted-foreground fk:corner-squircle",children:a?jsx(ra$1,{className:"fk:size-4"}):jsx(FileIcon,{className:"fk:size-5"})}),jsxs("div",{className:"fk:min-w-0 fk:pr-4 fk:text-left",children:[jsx("div",{className:"fk:truncate fk:text-sm fk:font-medium fk:text-foreground",children:t.filename}),jsx("div",{className:"fk:truncate fk:text-xs fk:text-muted-foreground",children:La(t.filename,t.mediaType)})]})]}),i="fk:flex fk:h-14 fk:max-w-64 fk:items-center fk:gap-2.5 fk:rounded-xl fk:border fk:border-border fk:bg-background fk:px-2 fk:corner-squircle";return jsxs("div",{className:"fk:relative fk:shrink-0",children:[n?jsx("a",{className:`${i} fk:transition-colors fk:hover:bg-accent/50 fk:focus-visible:outline-none fk:focus-visible:ring-2 fk:focus-visible:ring-ring`,href:n,rel:"noreferrer",target:"_blank",children:r}):jsx("div",{className:i,children:r}),s?jsx(tn,{label:`Remove ${t.filename}`,onRemove:s}):null,e]})}function Gr({uploads:e}){let t=Ob(),[n,a]=useState(null);return t.files.length===0?null:jsxs(Fragment,{children:[jsx("div",{className:"fk:flex fk:flex-wrap fk:items-center fk:gap-2",children:t.files.map(s=>{if(Ke(s.mediaType)&&s.url){let r={filename:s.filename??"Image",url:s.url};return jsx(nn,{image:r,isUploading:e.isUploadingFile(s.id),onOpen:()=>a(r),onRemove:()=>t.remove(s.id),sizeClassName:"fk:size-14"},s.id)}return jsx(an,{file:{filename:s.filename??"file",mediaType:s.mediaType},isUploading:e.isUploadingFile(s.id),onRemove:()=>t.remove(s.id)},s.id)})}),jsx(en,{image:n,onClose:()=>a(null)})]})}function sn({attachments:e}){let[t,n]=useState(null);if(e.length===0)return null;let a=e.filter(r=>Ke(r.mediaType)),s=e.filter(r=>!Ke(r.mediaType));return jsxs("div",{className:"fk:flex fk:flex-col fk:items-end fk:gap-2",children:[a.length>0?jsx("div",{className:"fk:flex fk:flex-wrap fk:justify-end fk:gap-2",children:a.map(r=>jsx(nn,{image:r,onOpen:()=>n(r),sizeClassName:"fk:size-24"},r.url))}):null,jsx(en,{image:t,onClose:()=>n(null)}),s.length>0?jsx("div",{className:"fk:flex fk:flex-wrap fk:justify-end fk:gap-2",children:s.map(r=>jsx(an,{action:jsx(Kt,{attachment:r}),file:r,href:r.url},r.url))}):null]})}function lo(e){let t=(Array.isArray(e.parts)?e.parts:[]).find(n=>n.type==="data-monitor-event");return t&&typeof t.data=="object"&&t.data!==null?t.data:null}function ln({data:e,error:t}){let n=e.total-e.events.length;return jsxs("div",{className:"fk:mr-auto fk:w-full fk:max-w-[85%] fk:space-y-1.5 fk:rounded-lg fk:border fk:border-border fk:bg-muted/40 fk:px-3.5 fk:py-2.5 fk:text-sm fk:corner-squircle",children:[jsxs("div",{className:"fk:flex fk:items-center fk:gap-2 fk:text-xs fk:text-muted-foreground",children:[jsx(RadarIcon,{className:"fk:size-3.5 fk:shrink-0"}),jsxs("span",{className:"fk:truncate",children:["Monitor \xB7 ",e.description]})]}),jsxs("ul",{className:"fk:space-y-0.5",children:[e.events.map(a=>jsx("li",{children:a.summary},a.id)),n>0?jsxs("li",{className:"fk:text-muted-foreground",children:["\u2026and ",n.toString()," more"]}):null]}),t?jsx("p",{className:"fk:text-xs fk:text-destructive",children:t}):null]})}function uo({api:e$1,chatId:t,onTurnIntoAutomation:n,projectId:a,sending:s=false}){let{data:r,mutate:i}=qa(g(a).agentChat(t),f$1,{revalidateOnMount:false}),[d,u]=useState(null),f=r?.monitors??[];if(f.length===0)return null;async function c$2(p){u(p.id);try{await e$1.stopAgentChatMonitor(t,p.id),await i();}catch{ma$1.error("Unable to stop the monitor.");}finally{u(null);}}return jsx("div",{className:"fk:mx-auto fk:mb-2 fk:flex fk:max-w-4xl fk:flex-wrap fk:gap-2",children:f.map(p=>jsxs("div",{className:"fk:flex fk:max-w-full fk:items-center fk:gap-2 fk:rounded-full fk:border fk:border-border fk:py-1 fk:pl-3 fk:pr-1 fk:text-xs fk:text-muted-foreground",children:[jsx(RadarIcon,{className:"fk:size-3.5 fk:shrink-0 fk:animate-pulse"}),jsxs("span",{className:"fk:truncate",children:["Watching: ",p.description," \xB7 expires ",formatDistance(new Date(p.expiresAt),new Date,{addSuffix:true})]}),n&&p.sourceType&&p.sourceType!=="job"?jsxs(b$2,{children:[jsx(c,{asChild:true,children:jsx(c$1,{"aria-label":`Turn ${p.description} into an automation`,className:"fk:size-6 fk:rounded-full",disabled:s,size:"icon",variant:"ghost",onClick:()=>n(p),children:jsx(BotIcon,{className:"fk:size-3.5"})})}),jsx(e,{children:"Turn into automation"})]}):null,jsxs(b$2,{children:[jsx(c,{asChild:true,children:jsx(c$1,{"aria-label":`Stop watching ${p.description}`,className:"fk:size-6 fk:rounded-full",disabled:d===p.id,size:"icon",variant:"ghost",onClick:()=>{c$2(p);},children:jsx(XIcon,{className:"fk:size-3.5"})})}),jsx(e,{children:"Stop watching"})]})]},p.id))})}function dn(e,t){let n=t.trim();return !n||/window was closed|not completed/i.test(n)?`${e} authorization didn't finish`:/popups|different account/i.test(n)?n:`${e} authorization didn't finish: ${n.replace(/\.$/,"")}`}function Ba(e){let t=e.connections.filter(n=>n.isPrimary&&n.status==="connected");return t.find(n=>n.scope==="personal")??t.find(n=>n.scope==="project")??null}function un(e,t,n){return n==="personal"?e.allowPersonal:t}function cn(e,t,n){if(!e.enabled)return {kind:"disabled"};let a=n?e.connections.find(i=>i.id===n&&i.status==="needs_auth"):void 0;if(a)return un(e,t,a.scope)?{kind:"reconnect",connection:a}:{kind:"not_permitted"};let s=Ba(e);if(s)return {kind:"connected",connection:s};let r=e.scopes.filter(i=>un(e,t,i));return r.length>0?{kind:"connect",scopes:r}:{kind:"not_permitted"}}var Wa=createContext(null),Ee=new Map,We=new Set;function Ve(e,t){t?Ee.set(e,t):Ee.delete(e),We.forEach(n=>n());}function Ga(e){return We.add(e),()=>We.delete(e)}function Za(e){return useSyncExternalStore(Ga,()=>Ee.get(e)??null,()=>null)}var mn={personal:{description:"Only you can use this connection in this project.",title:"Personal"},project:{description:"Shared with project members who can use this plugin.",title:"Project"}};function es({busy:e,logoUrl:t$1,name:n,onContinue:a$1,onOpenChange:s$1,open:r,scopes:i,connect:d}){let[u,f]=useState(i.length===1?i[0]??null:null),c=[...ts(n,d),{description:`Remove the connection to ${n} at any time.`,title:"You stay in control"}];return jsx(k,{onOpenChange:s$1,open:r,children:jsxs(p,{className:"fk:sm:max-w-md",children:[jsxs("div",{className:"fk:flex fk:flex-col fk:items-center fk:gap-3 fk:pt-2 fk:text-center",children:[jsx(a,{className:"fk:size-16 fk:rounded-xl",src:t$1}),jsxs(s,{className:"fk:text-xl",children:["Connect to ",n]}),jsxs(t,{children:["Let the Flexkit agent access and use ",n," on your behalf."]})]}),jsx("ul",{className:"fk:space-y-3 fk:rounded-xl fk:bg-muted/60 fk:p-4 fk:corner-squircle",children:c.map(p=>jsxs("li",{className:"fk:flex fk:gap-3",children:[jsx(CheckIcon,{className:"fk:mt-0.5 fk:size-4 fk:shrink-0"}),jsxs("span",{children:[jsx("span",{className:"fk:block fk:text-sm fk:font-medium",children:p.title}),jsx("span",{className:"fk:block fk:text-sm fk:text-muted-foreground",children:p.description})]})]},p.title))}),i.length>1?jsx("div",{className:"fk:space-y-1.5",role:"radiogroup","aria-label":"Connection",children:i.map(p=>jsxs("button",{"aria-checked":u===p,className:`fk:flex fk:w-full fk:flex-col fk:rounded-lg fk:border fk:px-3 fk:py-2 fk:text-left fk:corner-squircle ${u===p?"fk:border-primary fk:bg-primary/5":"fk:border-border fk:hover:bg-muted/60"}`,onClick:()=>f(p),role:"radio",type:"button",children:[jsx("span",{className:"fk:text-sm fk:font-medium",children:mn[p].title}),jsx("span",{className:"fk:text-xs fk:text-muted-foreground",children:mn[p].description})]},p))}):null,jsx("p",{className:"fk:text-center fk:text-xs fk:text-muted-foreground",children:"You can manage connections anytime in AI \u2192 Plugins."}),jsx(c$1,{className:"fk:w-full",disabled:e||!u,onClick:()=>u&&a$1(u),type:"button",children:"Continue"})]})})}function ts(e,t){switch(t?.type){case "api-token":return [{title:`Paste a ${t.tokenLabel}`,description:`Flexkit stores it encrypted and sends it only to ${e}. The agent never sees it.`},{title:"You decide what the agent can do",description:"The agent only gets the access the token has."}];case "credentials":return [{title:`Enter the credentials of your ${e} app`,description:`Flexkit checks them with ${e}, stores them encrypted and never shows them to the agent.`},{title:"You decide what the agent can do",description:`The agent only gets the access scopes you give the app in ${e}.`}];default:return [{title:`Sign in securely to your ${e} account`,description:"Flexkit never sees your password."},{title:"You decide what the agent can do",description:`The agent only gets the access you approve on ${e}'s sign-in page.`}]}}function ns(e,t,n){if(!n)return `Let the Flexkit agent use ${e}`;switch(t?.type){case "api-token":return `Add a new ${t.tokenLabel} so the agent can keep using ${e}`;case "credentials":return `Enter the credentials again so the agent can keep using ${e}`;default:return `Sign in again so the agent can keep using ${e}`}}function vn({connectionId:e,pluginId:t}){let{currentProjectId:n}=f(),a$1=useMemo(()=>n?d(n):null,[n]),s=n?`/api/flexkit/${n}`:null,r=s?`${s}/plugins/${encodeURIComponent(t)}`:null,{data:i,error:d$1,mutate:u}=qa(r,f$1),{mutate:f$2}=useSWRConfig(),c=useContext(Wa),[p,x]=useState(false),v=`${n??""}:${t}:${e??""}`,k=Za(v),g=k?.status==="connecting",w=k?.status==="failed"?k:null;if(!i)return jsxs("div",{className:"fk:flex fk:items-center fk:gap-2 fk:rounded-2xl fk:border fk:border-border fk:p-4 fk:text-sm fk:text-muted-foreground fk:corner-squircle",children:[d$1?jsx(CircleAlertIcon,{className:"fk:size-4"}):jsx(LoaderCircle,{className:"fk:size-4 fk:animate-spin"}),d$1?`${t} could not be loaded.`:`Loading ${t}\u2026`]});let{plugin:y}=i,C=cn(y,i.canManage,e),_=C.kind==="reconnect"?C.connection:null;function S(E){!a$1||Ee.get(v)?.status==="connecting"||(x(false),Ve(v,{status:"connecting"}),d$4(a$1,y,E,_?{connectionId:_.id}:void 0).then(Y=>{Ve(v,null),Y&&(u().catch(()=>{}),s&&f$2(`${s}/plugins`).catch(()=>{}),c?.onConnected(t));},Y=>{let L=Y instanceof Error?Y.message:"";Ve(v,{message:dn(y.name,L),scope:E,status:"failed"});}));}let R=null,$=null;return C.kind==="connected"?R=jsxs("span",{className:"fk:flex fk:items-center fk:gap-1.5 fk:text-sm fk:text-muted-foreground",children:[jsx(CheckIcon,{className:"fk:size-4 fk:text-green-700"}),"Connected \xB7 ",C.connection.displayName]}):C.kind==="disabled"?R=jsxs("span",{className:"fk:text-sm fk:text-muted-foreground",children:["An owner turned ",y.name," off for this project."]}):C.kind==="not_permitted"?R=jsxs("span",{className:"fk:text-sm fk:text-muted-foreground",children:["Ask a project owner or developer to connect ",y.name,"."]}):w?(R=jsxs("span",{className:"fk:flex fk:items-center fk:gap-1.5 fk:text-sm fk:text-muted-foreground",children:[jsx(CircleAlertIcon,{className:"fk:size-4 fk:shrink-0 fk:text-amber-600"}),w.message]}),$=jsx(c$1,{disabled:g,onClick:()=>S(w.scope),size:"sm",type:"button",variant:"secondary",children:"Retry"})):$=jsxs(c$1,{disabled:g,onClick:()=>_?S(_.scope):x(true),size:"sm",type:"button",children:[g?jsx(LoaderCircle,{className:"fk:size-3.5 fk:animate-spin"}):null,_?"Reconnect":"Authorize"]}),jsxs("div",{className:"fk:space-y-2",children:[jsxs("div",{className:"fk:space-y-3 fk:rounded-2xl fk:border fk:border-border fk:bg-background fk:p-4 fk:corner-squircle",children:[jsxs("div",{className:"fk:flex fk:items-center fk:gap-3",children:[jsx(a,{className:"fk:size-11 fk:rounded-lg",src:y.logoUrl}),jsxs("div",{className:"fk:min-w-0 fk:flex-1",children:[jsx("div",{className:"fk:truncate fk:font-medium",children:y.name}),jsx("div",{className:"fk:truncate fk:text-sm fk:text-muted-foreground",children:ns(y.name,y.connect,!!_)})]}),$&&!w?$:null]}),R?jsxs("div",{className:"fk:flex fk:items-center fk:justify-between fk:gap-3",children:[R,w?$:null]}):null]}),C.kind==="connect"||C.kind==="reconnect"?jsx("p",{className:"fk:px-1 fk:text-xs fk:text-muted-foreground",children:"Plugin actions follow your project's approval rules. Disconnect any time in AI \u2192 Plugins."}):null,C.kind==="connect"?jsx(es,{busy:g,logoUrl:y.logoUrl,name:y.name,onContinue:S,onOpenChange:x,open:p,scopes:C.scopes,connect:y.connect}):null]})}function So({data:e,error:t,label:n}){return jsxs("div",{className:"fk:mr-auto fk:flex fk:max-w-[85%] fk:flex-wrap fk:items-center fk:gap-x-2 fk:gap-y-1 fk:text-sm fk:text-muted-foreground",children:[jsx(PlugIcon,{className:"fk:size-3.5 fk:shrink-0"}),jsxs("span",{children:["Connected ",jsx("span",{className:"fk:font-medium fk:text-foreground",children:e.pluginName}),e.accountName?` \xB7 ${e.accountName}`:""]}),n?jsxs("span",{className:"fk:text-xs",children:["\xB7 ",n]}):null,t?jsx("span",{className:"fk:text-xs fk:text-destructive",children:t}):null]})}function No(e){let t=(Array.isArray(e)?e:[]).find(n=>n.type==="data-plugin-connected");return t&&typeof t.data=="object"&&t.data!==null?t.data:null}var ie=class extends Error{},Me=class extends Error{};function hn({url:e,signal:t,state:n,onState:a,wake:s,fetchStream:r=fetch,retryMs:i=2e3}){let d=0,u=0,f=new TransformStream,c=f.writable.getWriter(),p=new AbortController;c.closed.catch(g=>p.abort(g));let x=()=>{p.abort(t.reason),c.abort(t.reason).catch(()=>{});};t.addEventListener("abort",x,{once:true}),t.aborted&&x();let v=()=>new Promise(g=>{let w=()=>{clearTimeout(y),p.signal.removeEventListener("abort",w),s?.removeEventListener("wake",w),g();},y=setTimeout(w,i);p.signal.addEventListener("abort",w,{once:true}),s?.addEventListener("wake",w,{once:true}),p.signal.aborted&&w();});async function k(){try{for(await c.write({type:"start"});!p.signal.aborted;){try{let g=await r(`${e}${e.includes("?")?"&":"?"}wire=2&startIndex=${d}`,{credentials:"include",signal:p.signal});if(g.status===404){a("unavailable"),await c.close();return}if(g.status===401||g.status===403)throw new Me("Stream access denied");if(!g.ok||!g.body)throw new Error(`Stream request failed: ${g.status}`);if(g.headers.get("x-flexkit-stream-version")!=="2")throw await g.body.cancel(),new ie("Backend uses legacy replay");a("streaming");let w=g.body.pipeThrough(new TextDecoderStream).getReader(),y="",C=!1;try{for(;!p.signal.aborted;){let{value:_,done:S}=await w.read();if(S)break;y+=_;let R;for(;(R=y.indexOf(`
8
- `))>=0;){let $=y.slice(0,R);if(y=y.slice(R+1),!$)continue;let E=JSON.parse($);if(!Number.isSafeInteger(E.index)||E.index<0)throw new Error("Invalid replay cursor");if(!(E.index<d)){if(E.index!==d)throw new Error("Replay cursor gap");E.chunk&&await c.write(E.chunk),d=E.index+1,u=0,E.chunk?.type==="finish"&&E.chunk.messageMetadata?.flexkitTerminal&&(C=!0);}}if(y.length>2e6)throw new Error("Oversized replay frame");if(C)break}}finally{await w.cancel().catch(()=>{}),w.releaseLock();}if(C||n().terminal&&!y){await c.write({type:"finish"}),await c.close(),a("finished");return}}catch(g){if(p.signal.aborted||g instanceof ie||g instanceof Me||++u>=5)throw g}do a(n().paused?"paused":"streaming"),await v();while(!p.signal.aborted&&n().paused&&!n().terminal)}}catch(g){await c.abort(g).catch(()=>{});}finally{t.removeEventListener("abort",x),c.releaseLock();}}return k(),pipeJsonRender(f.readable)}var rs={pending:"Waiting for an answer.",cancelled:"The turn was stopped before you answered.",dismissed:"You skipped these questions.",expired:"Nobody answered in time."};function os({description:e,label:t,multiSelect:n,onClick:a,selected:s}){return jsxs("button",{"aria-checked":s,className:`fk:flex fk:w-full fk:items-start fk:gap-2.5 fk:rounded-lg fk:border fk:px-3 fk:py-2 fk:text-left fk:transition-colors fk:corner-squircle ${s?"fk:border-primary fk:bg-primary/5":"fk:border-border fk:hover:bg-muted/60"}`,onClick:a,role:n?"checkbox":"radio",type:"button",children:[jsx("span",{className:`fk:mt-0.5 fk:flex fk:size-4 fk:shrink-0 fk:items-center fk:justify-center fk:border ${n?"fk:rounded-sm":"fk:rounded-full"} ${s?"fk:border-primary fk:bg-primary fk:text-primary-foreground":"fk:border-muted-foreground/50"}`,children:s?jsx(CheckIcon,{className:"fk:size-3"}):null}),jsxs("span",{className:"fk:min-w-0",children:[jsx("span",{className:"fk:block fk:text-sm fk:font-medium",children:t}),e?jsx("span",{className:"fk:block fk:text-xs fk:text-muted-foreground",children:e}):null]})]})}function is({disabled:e,draft:t,onChange:n,question:a}){return jsxs("fieldset",{className:"fk:space-y-2",disabled:e,children:[jsxs("legend",{className:"fk:mb-2 fk:flex fk:flex-wrap fk:items-center fk:gap-2",children:[jsx(b$1,{variant:"outline",children:a.header}),jsx("span",{className:"fk:text-sm fk:font-medium",children:a.question}),a.multiSelect?jsx("span",{className:"fk:text-xs fk:text-muted-foreground",children:"Pick any"}):null]}),jsxs("div",{className:"fk:space-y-1.5",role:a.multiSelect?"group":"radiogroup",children:[a.options.map(s=>jsx(os,{description:s.description,label:s.label,multiSelect:a.multiSelect,onClick:()=>n(Bt(a,t,s.label)),selected:t.selected.includes(s.label)},s.label)),jsx(b$5,{"aria-label":`Your own answer to: ${a.question}`,className:"fk:h-9",maxLength:4e3,onChange:s=>n(Xt(a,t,s.target.value)),placeholder:"Other \u2014 type your own answer",value:t.other})]})]})}function ls({data:e}){return e.status==="answered"&&e.message!==void 0?jsxs("div",{className:"fk:space-y-1",children:[jsx("p",{className:"fk:text-xs fk:text-muted-foreground",children:e.questions.map(t=>t.question).join(" \xB7 ")}),jsxs("p",{className:"fk:text-sm",children:["You replied: ",jsxs("span",{className:"fk:whitespace-pre-wrap",children:["\u201C",e.message,"\u201D"]})]})]}):e.status!=="answered"?jsxs("div",{className:"fk:space-y-1",children:[jsx("p",{className:"fk:text-xs fk:text-muted-foreground",children:e.questions.map(t=>t.question).join(" \xB7 ")}),jsx("p",{className:"fk:text-sm fk:text-muted-foreground",children:rs[e.status]})]}):jsx("dl",{className:"fk:space-y-1.5",children:e.questions.map((t,n)=>jsxs("div",{className:"fk:flex fk:flex-wrap fk:items-baseline fk:gap-x-2",children:[jsx("dt",{className:"fk:text-xs fk:text-muted-foreground",children:t.question}),jsx("dd",{className:"fk:text-sm fk:font-medium",children:Qt(e.answers?.[n])})]},n))})}function bn({answer:e,data:t}){let[n,a]=useState(()=>qt(t.questions)),[s,r]=useState(null),[i,d]=useState(null),[u,f]=useState(""),c=t.status==="pending"&&s?s:t;if(c.status!=="pending"||!e)return jsx(ls,{data:c});let p=Jt(n);async function x(v){if(e){d(v.action),f("");try{let k=await e(t.questionId,v);k&&r({...k.answers?{answers:k.answers}:{},...k.message!==null?{message:k.message}:{},questionId:k.id,questions:k.questions,status:k.status});}catch(k){f(k instanceof Error?k.message:"Could not send the answer.");}finally{d(null);}}}return jsxs("form",{className:"fk:space-y-5",onSubmit:v=>{v.preventDefault(),p&&x({action:"answer",answers:p});},children:[t.questions.map((v,k)=>jsx(is,{disabled:i!==null,draft:n[k]??{other:"",selected:[]},onChange:g=>a(w=>w.map((y,C)=>C===k?g:y)),question:v},k)),u?jsx("p",{className:"fk:text-xs fk:text-destructive",children:u}):null,jsxs("div",{className:"fk:flex fk:flex-wrap fk:items-center fk:gap-2",children:[jsxs(c$1,{disabled:!p||i!==null,size:"sm",type:"submit",children:[i==="answer"?jsx(LoaderCircle,{className:"fk:size-3.5 fk:animate-spin"}):null,"Submit"]}),jsxs(c$1,{disabled:i!==null,onClick:()=>{x({action:"dismiss"});},size:"sm",type:"button",variant:"ghost",children:[i==="dismiss"?jsx(LoaderCircle,{className:"fk:size-3.5 fk:animate-spin"}):null,"Skip"]}),jsx("span",{className:"fk:text-xs fk:text-muted-foreground",children:"or reply in the chat"})]})]})}function us(e){let t=[];return e.page!==void 0&&t.push(`p. ${String(e.page)}`),e.slide!==void 0&&t.push(`slide ${String(e.slide)}`),e.headingPath&&e.headingPath.length>0&&t.push(e.headingPath.join(" \u203A ")),t.join(" \xB7 ")}function xn(e){let t=new Map;for(let n of e??[]){let a=t.get(n.sourceId);a||(a={passages:[],sourceId:n.sourceId,sourceTitle:n.sourceTitle},t.set(n.sourceId,a)),!a.passages.some(s=>s.passageId===n.passageId)&&a.passages.push({excerpt:n.excerpt,locator:us(n.locator),passageId:n.passageId});}return [...t.values()]}function wn(e,t){let n=t.reduce((a,s)=>a+s.passages.length,0);return n===0?`No passages matched "${e}"`:`${String(n)} ${n===1?"passage":"passages"} from ${String(t.length)} ${t.length===1?"document":"documents"} for "${e}"`}var Ds=lazy(()=>import('./spec-renderer-Z6GVHLFU.js').then(e=>({default:e.RunSpecPart})));function Is(e){return jsx(Suspense,{fallback:null,children:jsx(Ds,{...e})})}function Es(){let{currentProjectId:e}=f();return {api:useMemo(()=>e?d(e):null,[e]),projectId:e}}var An=5,In=2e3,En=120,Ge="data-spec",Mn=createContext(null),Ms=createContext(false);function $s(e){return new Promise(t=>window.setTimeout(t,e))}function zs(e){return e instanceof Error?e.name==="AbortError"||e.message.toLowerCase().includes("aborted"):false}function _s(e){return e.some(t=>!Ie(t))}function Ls(e){let t=new Set;for(let n of e)for(let a of n.parts)a.type==="data-user-message"&&a.id&&t.add(a.id);return t}function js(e){let t=Ls(e),n=[];for(let a of e){if(a.role==="user"){t.has(a.id)||n.push(a);continue}if(a.role!=="assistant"){n.push(a);continue}let s=[],r=0,i=()=>{_s(s)&&n.push({...a,id:`${a.id}-${r.toString()}`,parts:s}),r++,s=[];};for(let d of a.parts){if(d.type==="data-user-message"){let u=b(d);i(),n.push({id:d.id??crypto.randomUUID(),parts:u.parts,role:"user"});continue}s.push(d);}i();}return n}function si(e){return useMemo(()=>js(e),[e])}function le(e){return e==="success"||e==="failed"||e==="cancelled"||e==="skipped"}function $n({latestMessage:e,recordStatus:t,suppressApprovalPause:n}){return le(t)||n||t==="running"?false:t==="awaiting_approval"?true:Xe(e)||Qe(e)}function ri(e,t){let[n,a]=useState(false),s=Os(n?e:"",t),[r,i]=useState(),[d,u]=useState("streaming"),f=useRef(t);f.current=t;let c=useRef(null);c.current||(c.current=new EventTarget);let p=c.current,x=t?.resumeToken;return useEffect(()=>{p.dispatchEvent(new Event("wake"));},[x,p]),useEffect(()=>{if(a(false),i(void 0),!e){u("unavailable");return}let v=new AbortController,k,g,w=()=>{k=void 0,g&&!v.signal.aborted&&i({...g});},y=hn({url:e,signal:v.signal,state:()=>({terminal:le(f.current?.recordStatus),paused:$n({latestMessage:g,recordStatus:f.current?.recordStatus,suppressApprovalPause:f.current?.suppressApprovalPause??false})}),onState:C=>{v.signal.aborted||u(C);},wake:p});return (async()=>{try{for await(let C of readUIMessageStream({stream:y,terminateOnError:!0}))g=C,k||(k=setTimeout(w,En));w();}catch(C){if(v.signal.aborted)return;C instanceof ie?a(true):(console.error("Run stream error",C),u("error"));}})(),()=>{v.abort(),k&&clearTimeout(k);}},[e,p]),n?s:{message:r?Je(r,t?.decidedApprovals??{}):void 0,status:d}}function Os(e,t){let[n,a]=useState(),[s,r]=useState("streaming"),i=t?.recordStatus,d=t?.resumeToken??0,u=useRef(t?.decidedApprovals??{});u.current=t?.decidedApprovals??{};let f=useRef(t?.suppressApprovalPause??false);f.current=t?.suppressApprovalPause??false;let c=useRef(e),p=useRef(n);return p.current=n,useEffect(()=>{let x=c.current!==e;if(c.current=e,!e){a(void 0),r("unavailable");return}let v=new AbortController,k=x?void 0:p.current,g=x?0:k?.parts.length??0;if(x)a(void 0);else if(k&&(i==="running"||le(i))){let S=Je(k,u.current);S!==k&&(k=S,a(S));}r("streaming");let w=e.includes("?")?"&":"?",y=async()=>{let S=await fetch(`${e}${w}startIndex=0`,{credentials:"include",signal:v.signal});if(S.status===404)return "unavailable";if(!S.ok||!S.body)throw new Error(`Failed to fetch the run stream (status ${S.status.toString()})`);let R=false,E=parseJsonEventStream({schema:uiMessageChunkSchema,stream:S.body}).pipeThrough(new TransformStream({transform:(j,zn)=>{if(!j.success)throw j.error;j.value.type==="finish"&&(R=true),zn.enqueue(j.value);}})),Y=readUIMessageStream({onError:j=>{v.signal.aborted||console.error("Run stream chunk error",j);},stream:E}),L=null,I=g===0,ke=(j=false)=>{v.signal.aborted||!k||!I&&(I=j||k.parts.length>=g,!I)||a({...k});};try{for await(let j of Y){if(v.signal.aborted)break;k=j,L===null&&(L=window.setTimeout(()=>{L=null,ke();},En));}}finally{L!==null&&(window.clearTimeout(L),L=null),ke(true);}return R?"finished":"incomplete"},C=async()=>{let S=0;for(;!v.signal.aborted;){S>0&&await $s(In);try{let R=await y();if(v.signal.aborted)return;if(R==="unavailable"){r("unavailable");return}if(R==="finished"&&le(i)){r("finished");return}if(le(i)){r("finished");return}if($n({latestMessage:k,recordStatus:i,suppressApprovalPause:f.current})){r("paused");return}if(!(i==="running"||f.current)&&S>=An-1){r("error");return}}catch(R){if(v.signal.aborted||zs(R))return;if(console.error("Run stream error",R),le(i)){r("finished");return}if(!(i==="running"||f.current)&&S>=An-1){r("error");return}}S+=1;}},_=window.setTimeout(()=>{C();},0);return ()=>{window.clearTimeout(_),v.abort("Run replay unmounted");}},[i,d,e]),{message:n,status:s}}function oi(e){return {affectedCount:e.affectedCount,approvalId:e.id,decidedBy:e.decidedBy??void 0,operationsSummary:e.operationsSummary,reason:e.reason??void 0,status:e.status}}function Fs(e){let t=e.trim();return t?t.split(`
9
- `).every(n=>/^`{3,}[\w-]*$/.test(n.trim())):false}function Us({attachments:e,text:t}){return jsxs("div",{className:"fk:ml-auto fk:flex fk:w-fit fk:max-w-[70%] fk:flex-col fk:items-end fk:gap-1",children:[jsx(sn,{attachments:e}),t.trim()?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:t}):null,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"}),"Added while the agent was working"]})]})}function ii({api:e,part:t,partIndex:n,parts:a}){if(Ie(t))return null;if(me(t.type)){let s=De(t);return s?jsx(Bs,{message:s}):null}if(t.type==="text")return Fs(t.text)&&a.some(r=>r.type===Ge)?null:jsx(qs,{part:t});if(t.type==="data-knowledge-search")return jsx(Ws,{message:b(t)});if(t.type==="data-generating-files")return jsx(Ks,{message:b(t)});if(t.type==="data-run-artifact")return jsx(Ys,{api:e,message:b(t)});if(t.type==="data-tool-delivery")return jsx(Vs,{message:b(t)});if(t.type==="data-run-summary")return jsx(Gs,{message:b(t)});if(t.type==="data-subtask"){let s=b(t),r=s.status==="running"?`Running "${s.title}"`:s.status==="done"?`Completed "${s.title}"${typeof s.stepsUsed=="number"?` in ${s.stepsUsed.toString()} steps`:""}`:`"${s.title}" failed: ${s.error?.message??"unknown error"}`;return jsxs(B,{children:[jsxs(X,{children:[jsx(BotIcon,{className:"fk:size-3.5"}),"Subtask"]}),jsxs("div",{className:"fk:relative fk:min-h-5 fk:pl-6",children:[jsx("span",{className:"fk:absolute fk:left-0 fk:top-0",children:jsx(ze,{isError:s.status==="error",loading:s.status==="running"})}),jsx("span",{className:"fk:text-xs",children:r}),s.resultPreview?jsx("p",{className:"fk:mt-1 fk:text-xs fk:text-muted-foreground",children:s.resultPreview}):null]})]})}if(t.type==="data-mid-turn-message"){let s=b(t);return s.monitorEvent?jsx(ln,{data:s.monitorEvent}):jsx(Us,{attachments:s.attachments,text:s.text})}if(t.type==="data-context-compaction"){let s=b(t);return jsxs("p",{className:"fk:text-xs fk:text-muted-foreground",children:["Earlier messages (",s.summarizedMessageCount.toString(),") were summarized to keep this conversation within the model's context. Details may need to be re-fetched."]})}if(t.type==="data-plugin-connection"){let s=b(t);return jsx(vn,{connectionId:s.connectionId,pluginId:s.pluginId})}if(t.type==="data-suggested-prompt")return null;if(t.type==="data-turn-error"){let s=b(t);return jsxs(B,{className:"fk:border-red-700/40",children:[jsxs(X,{children:[jsx(XCircleIcon,{className:"fk:size-3.5 fk:text-red-700"}),jsx("span",{children:"Turn failed"})]}),jsx("p",{className:"fk:whitespace-pre-wrap fk:text-xs",children:s.message})]})}if(t.type==="data-mutation-approval"){let s=b(t);return Be(s)?jsx(tr,{message:s}):jsx(Zs,{api:e,message:s})}return t.type==="data-user-question"?jsx(er,{data:b(t)}):t.type==="data-bulk-graphql-action"?jsx(nr,{message:b(t)}):t.type===Ge?a.slice(n+1).find(r=>r.type===Ge)?null:jsx(Is,{parts:a}):t.type.startsWith("data-")?jsx(ar,{part:t}):null}function qs({part:e}){return jsx(mb,{className:"fk:min-w-0 fk:max-w-full fk:overflow-x-auto fk:text-base fk:leading-relaxed fk:text-foreground",isAnimating:e.state==="streaming",children:e.text})}function Bs({message:e}){return jsxs("div",{className:"fk:flex fk:items-start fk:gap-2 fk:rounded-xl fk:border fk:border-red-700/40 fk:bg-destructive/5 fk:px-3.5 fk:py-3 fk:text-sm fk:corner-squircle",children:[jsx(XCircleIcon,{className:"fk:mt-0.5 fk:size-3.5 fk:shrink-0 fk:text-red-700"}),jsx("span",{className:"fk:whitespace-pre-wrap fk:text-xs",children:e})]})}var Xs=1e3;function Js({text:e}){let t=useRef(typeof performance>"u"?0:performance.now()),n=()=>-(((typeof performance>"u"?0:performance.now())-t.current)%Xs),[a,s]=useState({current:e,currentDelayMs:0,key:0,previous:null,previousDelayMs:0});return useEffect(()=>{s(r=>r.current===e?r:{current:e,currentDelayMs:n(),key:r.key+1,previous:r.current,previousDelayMs:r.currentDelayMs});},[e]),jsxs("span",{className:"fk:relative fk:block fk:h-5 fk:min-w-0 fk:flex-1 fk:overflow-hidden",children:[a.previous?jsx("span",{"aria-hidden":true,className:"fk:absolute fk:inset-x-0 fk:top-0 fk:block fk:animate-roll-up-out",children:jsx("span",{className:"fk:block fk:truncate fk:shimmer fk:shimmer-duration-1000",style:{animationDelay:`${a.previousDelayMs.toString()}ms`},children:a.previous})},`previous-${a.key.toString()}`):null,jsx("span",{className:a.previous?"fk:block fk:animate-roll-up-in":"fk:block",role:"status",children:jsx("span",{className:"fk:block fk:truncate fk:shimmer fk:shimmer-duration-1000",style:{animationDelay:`${a.currentDelayMs.toString()}ms`},children:a.current})},`current-${a.key.toString()}`)]})}var Qs=1e3;function Hs(e,t){let n=Qs,[a,s]=useState(e),r=useRef(Date.now()),i=useRef(e);return i.current=e,useEffect(()=>{if(e===a)return;let d=Math.max(0,n-(Date.now()-r.current)),u=window.setTimeout(()=>{r.current=Date.now(),s(i.current);},d);return ()=>{window.clearTimeout(u);}},[a,e,n]),a}function li({label:e,visible:t}){let n=Hs(e);return jsx("div",{"aria-hidden":!t,className:`fk:flex fk:h-9 fk:items-center fk:text-sm fk:text-muted-foreground fk:transition-[opacity,visibility] fk:duration-200 ${t?"fk:visible fk:opacity-100":"fk:invisible fk:opacity-0"}`,children:jsx(Js,{text:n})})}function B({children:e,className:t=""}){return jsx("div",{className:`fk:min-w-0 fk:max-w-full fk:overflow-x-auto fk:rounded-xl fk:border fk:border-border fk:bg-background fk:px-3.5 fk:py-3 fk:text-sm ${t} fk:corner-squircle`,children:e})}function X({children:e}){return jsx("div",{className:"fk:flex fk:items-center fk:gap-2 fk:font-medium fk:text-muted-foreground",children:e})}function ze({isError:e,loading:t}){return t?jsx(LoaderCircle,{className:"fk:size-4 fk:animate-spin"}):e?jsx(XIcon,{className:"fk:size-4 fk:text-red-700"}):jsx(CheckIcon,{className:"fk:size-4"})}function _e({error:e,icon:t,loading:n,message:a,title:s}){return jsxs(B,{children:[jsxs(X,{children:[t,s]}),jsxs("div",{className:"fk:relative fk:min-h-5 fk:pl-6",children:[jsx("span",{className:"fk:absolute fk:left-0 fk:top-0",children:jsx(ze,{isError:!!e,loading:n})}),jsx("span",{className:"fk:text-xs",children:a})]})]})}function Ks({message:e}){let t=["error","uploading","generating"].includes(e.status),n=t?e.paths.slice(0,e.paths.length-1):e.paths,a=t?e.paths[e.paths.length-1]??"":null;return jsxs(B,{children:[jsxs(X,{children:[jsx(CloudUploadIcon,{className:"fk:size-3.5"}),jsx("span",{children:e.status==="done"?"Uploaded files":"Generating files"})]}),jsxs("div",{className:"fk:space-y-1 fk:text-sm",children:[n.map((s,r)=>jsxs("div",{className:"fk:flex fk:items-center fk:gap-2",children:[jsx(CheckIcon,{className:"fk:size-4"}),jsx("span",{className:"fk:whitespace-pre-wrap",children:s})]},`${s}-${r.toString()}`)),typeof a=="string"?jsxs("div",{className:"fk:flex fk:items-center fk:gap-2",children:[jsx(ze,{isError:e.status==="error",loading:e.status!=="error"}),jsx("span",{children:e.status==="error"?e.error?.message??a:a})]}):null]})]})}function Ys({api:e,message:t}){let n=t.status==="done"&&t.artifactId,a=n?b$3()&&t.url||e.getArtifactUrl(t.artifactId??""):"",s=n?e.getArtifactUrl(t.artifactId??"",{download:true}):"",r=sr(t.sizeBytes);return jsxs(B,{children:[jsxs(X,{children:[jsx(FileTextIcon,{className:"fk:size-3.5"}),t.kind==="csv"||t.kind==="json"?"Exported file":t.status==="done"?"Published artifact":"Publishing artifact"]}),jsxs("div",{className:"fk:relative fk:min-h-5 fk:pl-6",children:[jsx("span",{className:"fk:absolute fk:left-0 fk:top-0",children:jsx(ze,{isError:t.status==="error",loading:t.status==="uploading"})}),jsxs("div",{className:"fk:min-w-0 fk:space-y-2",children:[jsxs("div",{className:"fk:min-w-0",children:[jsx("div",{className:"fk:truncate fk:font-medium",children:t.filename}),jsxs("div",{className:"fk:text-xs fk:text-muted-foreground",children:[t.status==="uploading"&&"Uploading to artifacts",t.status==="done"&&[rr(t),r].filter(Boolean).join(" \xB7 "),t.status==="error"&&(t.error?.message??"Failed to publish artifact")]})]}),n?jsxs("div",{className:"fk:flex fk:flex-wrap fk:gap-2",children:[t.kind==="csv"?null:jsx(c$1,{asChild:true,size:"sm",variant:"outline",children:jsx("a",{href:a,rel:"noreferrer",target:"_blank",children:"Preview"})}),jsx(c$1,{asChild:true,size:"sm",variant:"outline",children:jsxs("a",{href:s,children:[jsx(DownloadIcon,{className:"fk:size-3"}),"Download"]})}),t.url?jsx(c$1,{asChild:true,size:"sm",variant:"outline",children:jsxs("a",{href:t.url,rel:"noreferrer",target:"_blank",children:[jsx(LinkIcon,{className:"fk:size-3"}),"Permanent link"]})}):null]}):null]})]})]})}function Vs({message:e}){let t=e.provider==="slack"?"Slack":"Microsoft Teams",n=e.provider==="slack"?jsx(MessageSquareIcon,{className:"fk:size-3.5"}):jsx(SendIcon,{className:"fk:size-3.5"});return jsx(_e,{error:e.error?.message,icon:n,loading:e.status==="loading",message:e.status==="error"?e.error?.message??`Failed to send result to ${e.channelName}`:`${e.status==="done"?"Sent":"Sending"} result to ${e.channelName}`,title:`${t} Delivery`})}function Ws({message:e}){let{currentProjectId:t}=f(),n=useMemo(()=>xn(e.results),[e.results]);return e.status==="error"?jsx(_e,{error:e.error?.message??"The knowledge search failed",icon:jsx(LibraryIcon,{className:"fk:size-3.5"}),loading:false,message:e.error?.message??"The knowledge search failed",title:"Knowledge search"}):jsxs(B,{children:[jsxs(X,{children:[jsx(LibraryIcon,{className:"fk:size-3.5"}),jsx("span",{children:"Knowledge search"})]}),jsx("p",{className:"fk:mt-1 fk:text-xs fk:text-muted-foreground",children:wn(e.query,n)}),n.length>0?jsxs(Cc,{className:"fk:mb-0 fk:mt-2",children:[jsxs(Dc,{count:n.length,children:[jsx("p",{className:"fk:font-medium",children:n.length===1?"Show the cited passages":`Show passages from ${String(n.length)} documents`}),jsx(ChevronDownIcon,{className:"fk:size-4"})]}),jsx(Ec,{className:"fk:w-full",children:n.map(a=>jsxs("div",{className:"fk:flex fk:flex-col fk:gap-1.5",children:[t?jsxs(Link,{className:"fk:flex fk:w-fit fk:items-center fk:gap-2 fk:font-medium fk:text-foreground fk:underline-offset-2 fk:hover:underline",to:o(t,a.sourceId),children:[jsx(BookOpenIcon,{className:"fk:size-4"}),jsx("span",{children:a.sourceTitle})]}):jsxs("span",{className:"fk:flex fk:items-center fk:gap-2 fk:font-medium fk:text-foreground",children:[jsx(BookOpenIcon,{className:"fk:size-4"}),jsx("span",{children:a.sourceTitle})]}),jsx("ul",{className:"fk:flex fk:flex-col fk:gap-1.5 fk:pl-6",children:a.passages.map(s=>jsxs("li",{className:"fk:text-xs fk:text-muted-foreground",children:[s.locator?jsxs("span",{className:"fk:mr-1 fk:font-medium fk:text-foreground/80",children:[s.locator,":"]}):null,jsxs("span",{className:"fk:italic",children:["\u201C",s.excerpt,"\u201D"]})]},s.passageId))})]},a.sourceId))})]}):null]})}function Gs({message:e}){let t=e.status==="success"?jsx(CheckCircle2Icon,{className:"fk:size-3.5 fk:text-green-700"}):e.status==="skipped"?jsx(CircleSlashIcon,{className:"fk:size-3.5"}):jsx(XCircleIcon,{className:"fk:size-3.5 fk:text-red-700"}),n=e.status==="success"?"Run completed":e.status==="skipped"?"Run skipped":"Run failed";return jsxs(B,{className:e.status==="failed"?"fk:border-red-700/40":"fk:border-green-700/40",children:[jsxs(X,{children:[t,jsx("span",{children:n})]}),e.status==="failed"?jsx("p",{className:"fk:whitespace-pre-wrap fk:text-xs",children:e.summary}):null]})}function Zs({api:e,message:t}){let{projectId:n}=Es(),a=useContext(Mn),s=useContext(Ms),r=useRef(void 0),{data:i,error:d,isValidating:u,mutate:f}=qa(n?g(n).approval(t.approvalId):null,f$1,{refreshInterval:g=>t.status!=="pending"||g?.approval?.status&&g.approval.status!=="pending"?0:In}),c=i?.approval?.status,p=(c??t.status)==="pending",x=i?.approval?.kind==="schema"&&i.approval.status==="approved";useEffect(()=>{!x||!n||Ne({approvalId:t.approvalId,approvalUrl:g(n).approval(t.approvalId),projectId:n});},[x,t.approvalId,n]),useEffect(()=>{f();},[t.status,f]),useEffect(()=>{let g=r.current;r.current=c,!(t.status!=="pending"||!c||c==="pending")&&g==="pending"&&a?.onApprovalDecided(i?.approval?.id??t.approvalId,c);},[c,i?.approval?.id,t.approvalId,t.status,a]);function v(g){g.status!=="pending"&&(r.current=g.status),f(),a?.onApprovalDecided(g.id,g.status);}let k;if(i?.approval)k=jsx(Ot,{api:e,approval:i.approval,chat:s,onDecided:v},i.approval.status);else if(d&&!u){let g=d instanceof Error&&d.message?d.message:"Request failed";k=jsxs("div",{className:"fk:space-y-2",children:[jsxs("p",{className:"fk:text-xs fk:text-destructive",children:["Failed to load proposal ",t.operationsSummary,": ",g]}),jsx(c$1,{size:"sm",variant:"outline",onClick:()=>{f();},children:"Retry"})]});}else k=jsxs("div",{className:"fk:flex fk:items-center fk:gap-2 fk:text-xs fk:text-muted-foreground",children:[jsx(LoaderCircle,{className:"fk:size-3.5 fk:animate-spin"}),jsxs("span",{children:["Loading proposal ",t.operationsSummary,"..."]})]});return jsxs(B,{children:[jsxs(X,{children:[s?jsx(ShieldIcon,{className:"fk:size-3.5"}):jsx(DatabaseZapIcon,{className:"fk:size-3.5"}),s?"Approval request":"Mutation approval",p?jsx(LoaderCircle,{className:"fk:ml-1 fk:size-3.5 fk:animate-spin"}):null]}),jsx("div",{className:"fk:mt-2",children:k}),t.status==="error"&&t.error?jsx("p",{className:"fk:mt-2 fk:text-xs fk:text-destructive",children:t.error.message}):null]})}function er({data:e}){let t=useContext(Mn),n=e.questions.length>1;return jsxs(B,{children:[jsxs(X,{children:[jsx(MessageCircleQuestionIcon,{className:"fk:size-3.5"}),e.status==="pending"?n?"The agent has questions":"The agent has a question":n?"Questions":"Question"]}),jsx("div",{className:"fk:mt-3",children:jsx(bn,{answer:t?.answerQuestion,data:e},e.status)})]})}function tr({message:e}){let t=e.operationsSummary.replace(/^Call /,"");return jsx(_e,{error:e.status==="error"?e.error?.message??"The call failed.":void 0,icon:jsx(ShieldCheckIcon,{className:"fk:size-3.5"}),loading:false,message:e.status==="error"?`${t}: ${e.error?.message??"The call failed."}`:`${t} \xB7 Auto-approved by Jev`,title:"Plugin call"})}function nr({message:e}){let t=[typeof e.processedItems=="number"?`${e.processedItems.toString()} processed`:"",typeof e.changedItems=="number"?`${e.changedItems.toString()} changed`:"",typeof e.failedItems=="number"?`${e.failedItems.toString()} failed`:"",typeof e.totalItems=="number"?`${e.totalItems.toString()} total`:""].filter(Boolean);return jsx(_e,{error:e.error?.message,icon:jsx(DatabaseZapIcon,{className:"fk:size-3.5"}),loading:e.status==="loading"||e.status==="running",message:e.status==="error"?e.error?.message??`Failed bulk ${e.operationName}`:`${e.status==="done"?"Completed":"Running"} ${e.operationName}${t.length>0?` (${t.join(", ")})`:""}`,title:"Bulk GraphQL action"})}function ar({part:e}){return jsxs(B,{className:"fk:bg-muted/30",children:[jsxs(X,{children:[jsx(CheckCircle2Icon,{className:"fk:size-3.5"}),e.type.replace(/^data-/,"").replaceAll("-"," ")]}),jsx("p",{className:"fk:text-xs fk:text-muted-foreground",children:"This run emitted a structured event that is not yet rendered by Studio."})]})}function sr(e){if(typeof e!="number")return "";if(e<1024)return `${e.toString()} B`;let t=e/1024;return t<1024?`${t.toFixed(1)} KB`:`${(t/1024).toFixed(1)} MB`}function rr(e){return e.kind==="pdf"?"PDF artifact":e.kind==="html"?"HTML artifact":e.kind==="csv"?"CSV file":e.kind==="json"?"JSON file":"Artifact"}export{Ms as A,si as B,le as C,ri as D,oi as E,ii as F,Bs as G,li as H,Zs as I,St as a,Wn as b,Ot as c,Sr as d,Ie as e,ba as f,Xe as g,Ut as h,xa as i,Qe as j,wa as k,Yt as l,Yr as m,Vr as n,Wr as o,Gr as p,sn as q,lo as r,ln as s,uo as t,Wa as u,So as v,No as w,Es as x,In as y,Mn as z};//# sourceMappingURL=chunk-FJRDLP7V.js.map
10
- //# sourceMappingURL=chunk-FJRDLP7V.js.map