@flexkit/studio 0.2.1 → 0.2.3

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 (105) hide show
  1. package/dist/activity-nav-button-Z6M3FURW.js +2 -0
  2. package/dist/activity-nav-button-Z6M3FURW.js.map +1 -0
  3. package/dist/chat-page-J7I5V6G4.js +4 -0
  4. package/dist/chat-page-J7I5V6G4.js.map +1 -0
  5. package/dist/chunk-32ZU4MLE.js +2 -0
  6. package/dist/{chunk-ODORXGGY.js.map → chunk-32ZU4MLE.js.map} +1 -1
  7. package/dist/chunk-3C2EG3SI.js +2 -0
  8. package/dist/{chunk-S7M5CQ5S.js.map → chunk-3C2EG3SI.js.map} +1 -1
  9. package/dist/chunk-6NRQMG26.js +2 -0
  10. package/dist/chunk-6NRQMG26.js.map +1 -0
  11. package/dist/chunk-72TZUR4Q.js +2 -0
  12. package/dist/{chunk-JYHZU2UZ.js.map → chunk-72TZUR4Q.js.map} +1 -1
  13. package/dist/chunk-76CL7HSO.js +3 -0
  14. package/dist/chunk-76CL7HSO.js.map +1 -0
  15. package/dist/chunk-AN4APNXO.js +2 -0
  16. package/dist/chunk-AN4APNXO.js.map +1 -0
  17. package/dist/chunk-BP27UNNR.js +2 -0
  18. package/dist/{chunk-LQVZWFM2.js.map → chunk-BP27UNNR.js.map} +1 -1
  19. package/dist/{chunk-2IRKGO2B.js → chunk-G74PT7Z7.js} +5 -5
  20. package/dist/{chunk-2IRKGO2B.js.map → chunk-G74PT7Z7.js.map} +1 -1
  21. package/dist/chunk-IAA4CEBW.js +2 -0
  22. package/dist/{chunk-GM5OZTHL.js.map → chunk-IAA4CEBW.js.map} +1 -1
  23. package/dist/chunk-K7FD54PW.js +6 -0
  24. package/dist/chunk-K7FD54PW.js.map +1 -0
  25. package/dist/chunk-MM356YIK.js +3 -0
  26. package/dist/chunk-MM356YIK.js.map +1 -0
  27. package/dist/chunk-MPLNRUP3.js +4 -0
  28. package/dist/{chunk-ANVO5P65.js.map → chunk-MPLNRUP3.js.map} +1 -1
  29. package/dist/chunk-QDXGSL5B.js +2 -0
  30. package/dist/chunk-QDXGSL5B.js.map +1 -0
  31. package/dist/{chunk-5TQF5UQQ.js → chunk-QJDD73JR.js} +2 -2
  32. package/dist/{chunk-5TQF5UQQ.js.map → chunk-QJDD73JR.js.map} +1 -1
  33. package/dist/chunk-TWMX2IQ2.js +3 -0
  34. package/dist/chunk-TWMX2IQ2.js.map +1 -0
  35. package/dist/chunk-U45E5X3H.js +2 -0
  36. package/dist/chunk-U45E5X3H.js.map +1 -0
  37. package/dist/chunk-USNXQOMJ.js +2 -0
  38. package/dist/chunk-USNXQOMJ.js.map +1 -0
  39. package/dist/chunk-YCCFUGWJ.js +7 -0
  40. package/dist/chunk-YCCFUGWJ.js.map +1 -0
  41. package/dist/index.css +400 -0
  42. package/dist/index.d.ts +1 -1
  43. package/dist/index.js +11 -11
  44. package/dist/index.js.map +1 -1
  45. package/dist/list-IBUZ2LXU.js +2 -0
  46. package/dist/{list-ZQJ6NHKQ.js.map → list-IBUZ2LXU.js.map} +1 -1
  47. package/dist/logo-JAWR6P43.js +2 -0
  48. package/dist/logo-JAWR6P43.js.map +1 -0
  49. package/dist/pages-ZKDDV5T3.js +3 -0
  50. package/dist/pages-ZKDDV5T3.js.map +1 -0
  51. package/dist/plugin-pages-HQPZQSZT.js +2 -0
  52. package/dist/{plugin-pages-E5TUDDT5.js.map → plugin-pages-HQPZQSZT.js.map} +1 -1
  53. package/dist/root-4UVGZZRU.js +2 -0
  54. package/dist/{root-HC5QZ2JM.js.map → root-4UVGZZRU.js.map} +1 -1
  55. package/dist/root-HUJPHUHL.js +23 -0
  56. package/dist/{root-TXKDRPOK.js.map → root-HUJPHUHL.js.map} +1 -1
  57. package/dist/root-XGNAKO5P.js +2 -0
  58. package/dist/root-XGNAKO5P.js.map +1 -0
  59. package/dist/root-ZY2HGDBT.js +31 -0
  60. package/dist/{root-BD4VN3RD.js.map → root-ZY2HGDBT.js.map} +1 -1
  61. package/dist/search-N7G6BVN6.js +2 -0
  62. package/dist/{search-PVXTPIYJ.js.map → search-N7G6BVN6.js.map} +1 -1
  63. package/dist/skills-pages-VP32HFUN.js +2 -0
  64. package/dist/{skills-pages-N5KDEHLT.js.map → skills-pages-VP32HFUN.js.map} +1 -1
  65. package/dist/spec-renderer-EX7SCFWH.js +2 -0
  66. package/dist/{spec-renderer-ZZ3GPVKU.js.map → spec-renderer-EX7SCFWH.js.map} +1 -1
  67. package/dist/ui.d.ts +28 -4
  68. package/dist/ui.js +1 -1
  69. package/dist/user-nav-QZTYBG45.js +2 -0
  70. package/dist/user-nav-QZTYBG45.js.map +1 -0
  71. package/package.json +4 -4
  72. package/dist/chat-page-H6I3XOKS.js +0 -2
  73. package/dist/chat-page-H6I3XOKS.js.map +0 -1
  74. package/dist/chunk-5DHOBLAE.js +0 -2
  75. package/dist/chunk-5DHOBLAE.js.map +0 -1
  76. package/dist/chunk-ANVO5P65.js +0 -4
  77. package/dist/chunk-BURKG2UC.js +0 -6
  78. package/dist/chunk-BURKG2UC.js.map +0 -1
  79. package/dist/chunk-GM5OZTHL.js +0 -2
  80. package/dist/chunk-HROHAMPM.js +0 -3
  81. package/dist/chunk-HROHAMPM.js.map +0 -1
  82. package/dist/chunk-JYHZU2UZ.js +0 -2
  83. package/dist/chunk-LQVZWFM2.js +0 -2
  84. package/dist/chunk-ODORXGGY.js +0 -2
  85. package/dist/chunk-QHDL6CA2.js +0 -7
  86. package/dist/chunk-QHDL6CA2.js.map +0 -1
  87. package/dist/chunk-S7M5CQ5S.js +0 -2
  88. package/dist/chunk-ZBI744KS.js +0 -3
  89. package/dist/chunk-ZBI744KS.js.map +0 -1
  90. package/dist/list-ZQJ6NHKQ.js +0 -2
  91. package/dist/logo-MU7MGYDH.js +0 -3
  92. package/dist/logo-MU7MGYDH.js.map +0 -1
  93. package/dist/pages-2GQVTLL2.js +0 -3
  94. package/dist/pages-2GQVTLL2.js.map +0 -1
  95. package/dist/plugin-pages-E5TUDDT5.js +0 -2
  96. package/dist/root-BD4VN3RD.js +0 -31
  97. package/dist/root-HC5QZ2JM.js +0 -2
  98. package/dist/root-P6CVZ5ZB.js +0 -2
  99. package/dist/root-P6CVZ5ZB.js.map +0 -1
  100. package/dist/root-TXKDRPOK.js +0 -23
  101. package/dist/search-PVXTPIYJ.js +0 -2
  102. package/dist/skills-pages-N5KDEHLT.js +0 -2
  103. package/dist/spec-renderer-ZZ3GPVKU.js +0 -2
  104. package/dist/user-nav-QZFCICK3.js +0 -2
  105. package/dist/user-nav-QZFCICK3.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/apps/ai/agent/attachments.tsx","../src/apps/ai/agent/chat-history.ts","../src/apps/ai/agent/chat-page.tsx"],"names":["ATTACHMENT_MAX_BYTES","ATTACHMENTS_MAX_PER_MESSAGE","SUPPORTED_EXTENSIONS","SUPPORTED_UNNAMED_TYPES","ATTACHMENT_ACCEPT","extension","getExtension","filename","dotIndex","getAttachmentValidationError","file","readComposerFile","blob","useAttachmentUploads","api","onError","attachments","usePromptInputController","entriesRef","useRef","setVersion","useState","bump","useCallback","current","removeRef","onErrorRef","useEffect","currentIds","fileId","entry","controller","nativeFile","validationError","uploaded","error","isUploading","fileIds","attachment","isImageMediaType","mediaType","ImagePreviewDialog","image","onClose","jsx","Dialog","open","jsxs","DialogContent","DialogTitle","DialogClose","XIcon","ChipRemoveButton","label","onRemove","event","ImageThumbnail","onOpen","sizeClassName","Spinner","getFileTypeLabel","subtype","FileChip","href","content","Fragment","FileIcon","chipClassName","ComposerAttachments","uploads","usePromptInputAttachments","preview","setPreview","getAttachmentsFromParts","parts","part","MessageAttachments","images","files","compareChatMessages","a","b","byTime","sortChatMessages","messages","message","mergeChatDetail","incoming","incomingIds","newest","retained","TITLE_POLL_TIMEOUT_MS","isActiveTurnStatus","status","getChatDetailRefreshInterval","latestData","lastMessage","STREAM_RETRY_DELAY_MS","lastActivity","createFallbackChatDetail","chatId","modelId","timestamp","getSeedBaseDetail","createdChat","cachedDetail","appendTurnToDetail","detail","turn","turnIds","resolveSeededChatDetail","seeds","getTurnRecordStatus","UserBubble","text","textInput","copied","setCopied","hasText","handleCopy","Tooltip","TooltipTrigger","Button","CheckIcon","CopyIcon","TooltipContent","PencilIcon","getSuggestedPrompt","prompt","candidate","SuggestedPromptChip","CornerDownRightIcon","PersistedPart","partIndex","ToolErrorLine","MessagePart","HistoryMessage","showSuggestion","isHiddenReplayPart","hasTurnErrorPart","suggestedPrompt","index","LiveTurn","onStatusChange","onTurnUpdated","recordStatus","streamApi","resumeToken","setResumeToken","suppressApprovalPause","setSuppressApprovalPause","decidedApprovals","setDecidedApprovals","lastDecidedApprovalIdRef","streamMessage","useRunStream","rawMessages","useMemo","sessionMessages","useSessionMessages","onTurnUpdatedRef","onStatusChangeRef","replayActions","approvalId","decidedStatus","isAwaitingApproval","messageHasPendingMutationApproval","streamApprovalIds","getMutationApprovalIds","fallbackApproval","lastPart","contentIsStreaming","statusLabel","getLiveStatusLabel","statusVisible","showFallbackApproval","liveSuggestedPrompt","sessionMessage","RunReplayActionsContext","MutationApprovalPart","toMutationApprovalPartData","ChatComposer","effort","modelKey","modelPending","models","onEffortChange","onModelChange","onSend","onStop","sending","streaming","submittingRef","selectableModels","model","getModelKey","selectedModel","findModelByKey","effortOptions","getEffortOptions","effectiveEffort","coerceEffort","isBusy","canSubmit","PromptInput","trimmed","sentAttachments","PromptInputHeader","PromptInputBody","PromptInputTextarea","PromptInputFooter","PromptInputTools","PromptInputActionMenu","PromptInputActionMenuTrigger","PromptInputActionMenuContent","PromptInputActionAddAttachments","PromptInputSelect","PromptInputSelectTrigger","PromptInputSelectValue","PromptInputSelectContent","PromptInputSelectItem","option","SpeechInput","audioBlob","signal","transcript","appendDictatedText","PromptInputSubmit","EMPTY_CHAT_HISTORY","ChatConversation","projectId","pendingMessage","resolveDetail","rawDetail","mutate","useSWR","paths","fetcher","data","historyState","setHistoryState","history","activeChatRef","updateHistory","forChatId","patch","base","windowRef","windowMessages","previous","next","nextIds","dropped","item","detailRef","priorStatus","signature","latest","loadOlder","cursor","requestChatId","result","liveMessage","historyMessages","reportedStatus","setReportedStatus","liveStatus","LoaderCircle","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","input","writeLastAgentModel","selection","EmptyConversation","isLoading","greeting","AgentChatPage","useProjectApi","useParams","navigate","useNavigate","agentBase","useAgentBasePath","globalMutate","useSWRConfig","toolsData","rawChatDetail","seededDetailRef","chatDetail","selectedModelKey","setSelectedModelKey","selectedEffort","setSelectedEffort","autoPickedOnModelIdRef","rememberedModel","setRememberedModel","setSending","sendingRef","setPendingMessage","visiblePendingMessage","sendError","setSendError","chatModelId","awaitingChatModel","chatSelection","parseModelSelection","defaultModelKey","lastUsed","formatModelSelection","AUTO_MODEL_KEY","rememberModel","handleModelChange","nextModelKey","handleEffortChange","nextEffort","chatApi","chatProjectId","turnInProgress","handleSend","chat","targetChatId","handleStop","PromptInputProvider","SidebarTrigger","Separator","ChatApprovalContext"],"mappings":"q6BAgBO,IAAMA,EAAAA,CAAuB,EAAA,CAAK,IAAA,CAAO,IAAA,CACnCC,EAAAA,CAA8B,EAAA,CAErCC,GAAuB,IAAI,GAAA,CAAI,CACnC,KAAA,CACA,KAAA,CACA,KAAA,CACA,KAAA,CACA,SAAA,CACA,KAAA,CACA,MAAA,CACA,MAAA,CACA,KAAA,CACA,IAAA,CACA,MAAA,CACA,KAAA,CACA,KAAA,CACA,WACA,IAAA,CACA,KAAA,CACA,QAAA,CACA,KAAA,CACA,KAAA,CACA,IAAA,CACA,KAAA,CACA,IAAA,CACA,KAAA,CACA,KAAA,CACA,KAAA,CACA,MAAA,CACA,KAAA,CACA,MAAA,CACA,KACF,CA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AA,CAAC,KAAA,CAAA,CAAI,SAAA,CAAU,qBAAA,CACZ,QAAA,CAAA,CAAA4Q,CAAAA,CACC/Q,GAAAA,CAAC,GAAA,CAAA,CAAE,SAAA,CAAU,gEAAA,CAAkE,SAAA+Q,CAAAA,CAAU,CAAA,CACvF,IAAA,CACJ/Q,GAAAA,CAACyI,EAAAA,CAAA,CACC,GAAA,CAAKqJ,CAAAA,CACL,MAAA,CAAQpJ,CAAAA,CACR,QAAA,CAAUC,CAAAA,CACV,YAAA,CAAcC,EAAAA,CACd,MAAA,CAAQC,GAAAA,CACR,QAASK,CAAAA,CACT,SAAA,CAAW8I,EAAAA,CACX,cAAA,CAAgBJ,EAAAA,CAChB,OAAA,CAASZ,CAAAA,CACT,aAAA,CAAeU,GACf,MAAA,CAAQO,EAAAA,CACR,MAAA,CAAQG,EAAAA,CACV,CAAA,CAAA,CACF,CAAA,CAAA,CACF,CAAA,CACF,CAAA,CAAA,CACF,EACF,CAEJ","file":"chat-page-H6I3XOKS.js","sourcesContent":["import type { JSX } from 'react';\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport { FileIcon, XIcon } from 'lucide-react';\nimport {\n Dialog,\n DialogClose,\n DialogContent,\n DialogTitle,\n Spinner,\n usePromptInputAttachments,\n usePromptInputController,\n} from '../../../ui';\nimport type { ApiClient } from '../api';\nimport type { AgentChatAttachment, AgentChatPart } from '../types';\n\n/** Mirrors the platform limits so invalid files are rejected before upload. */\nexport const ATTACHMENT_MAX_BYTES = 20 * 1024 * 1024;\nexport const ATTACHMENTS_MAX_PER_MESSAGE = 10;\n\nconst SUPPORTED_EXTENSIONS = new Set([\n 'css',\n 'csv',\n 'gif',\n 'gql',\n 'graphql',\n 'htm',\n 'html',\n 'jpeg',\n 'jpg',\n 'js',\n 'json',\n 'jsx',\n 'log',\n 'markdown',\n 'md',\n 'mjs',\n 'ndjson',\n 'pdf',\n 'png',\n 'py',\n 'sql',\n 'ts',\n 'tsv',\n 'tsx',\n 'txt',\n 'webp',\n 'xml',\n 'yaml',\n 'yml',\n]);\n\nconst SUPPORTED_UNNAMED_TYPES = new Set(['application/pdf', 'image/gif', 'image/jpeg', 'image/png', 'image/webp']);\n\n/** Comma-separated `accept` value for the file picker. */\nexport const ATTACHMENT_ACCEPT = [\n ...[...SUPPORTED_EXTENSIONS].map((extension) => `.${extension}`),\n ...SUPPORTED_UNNAMED_TYPES,\n].join(',');\n\nfunction getExtension(filename: string): string {\n const dotIndex = filename.lastIndexOf('.');\n\n return dotIndex <= 0 ? '' : filename.slice(dotIndex + 1).toLowerCase();\n}\n\n/** Why a file cannot be attached, or null when it can. */\nexport function getAttachmentValidationError(file: { name: string; size: number; type: string }): string | null {\n const extension = getExtension(file.name);\n const supported = extension ? SUPPORTED_EXTENSIONS.has(extension) : SUPPORTED_UNNAMED_TYPES.has(file.type);\n\n if (!supported) {\n return `\"${file.name}\" is not supported. Attach images, PDFs, or text files.`;\n }\n\n if (file.size === 0) {\n return `\"${file.name}\" is empty.`;\n }\n\n if (file.size > ATTACHMENT_MAX_BYTES) {\n return `\"${file.name}\" exceeds the ${String(Math.round(ATTACHMENT_MAX_BYTES / (1024 * 1024)))} MB limit.`;\n }\n\n return null;\n}\n\ntype UploadStatus = 'uploading' | 'done' | 'error';\n\ninterface UploadEntry {\n attachment?: AgentChatAttachment;\n controller: AbortController;\n status: UploadStatus;\n}\n\nexport interface AttachmentUploads {\n /** Uploaded attachments for the given composer file ids, in the same order. */\n getUploaded: (_fileIds: string[]) => AgentChatAttachment[];\n isUploading: boolean;\n /** Whether the composer file with this id is still uploading. */\n isUploadingFile: (_fileId: string) => boolean;\n}\n\nasync function readComposerFile(file: { filename?: string; mediaType?: string; url: string }): Promise<File> {\n const response = await fetch(file.url);\n const blob = await response.blob();\n\n return new File([blob], file.filename ?? 'file', { type: file.mediaType || blob.type });\n}\n\n/**\n * Uploads every file added to the composer as soon as it appears, so the\n * message can be sent as soon as the user is done typing. Files that fail\n * validation or are refused by the platform (unsupported type, size, daily\n * cap, restricted project) are removed again with an explanation.\n */\nexport function useAttachmentUploads(api: ApiClient, onError: (_message: string) => void): AttachmentUploads {\n const { attachments } = usePromptInputController();\n const entriesRef = useRef<{ [fileId: string]: UploadEntry }>({});\n const [, setVersion] = useState(0);\n const bump = useCallback(() => setVersion((current) => current + 1), []);\n const removeRef = useRef(attachments.remove);\n removeRef.current = attachments.remove;\n const onErrorRef = useRef(onError);\n onErrorRef.current = onError;\n\n useEffect(() => {\n const currentIds = new Set(attachments.files.map((file) => file.id));\n\n // Abort and forget uploads whose file was removed from the composer.\n for (const [fileId, entry] of Object.entries(entriesRef.current)) {\n if (!currentIds.has(fileId)) {\n entry.controller.abort();\n delete entriesRef.current[fileId];\n }\n }\n\n for (const file of attachments.files) {\n if (entriesRef.current[file.id]) {\n continue;\n }\n\n const controller = new AbortController();\n const entry: UploadEntry = { controller, status: 'uploading' };\n entriesRef.current[file.id] = entry;\n\n void (async () => {\n try {\n const nativeFile = await readComposerFile(file);\n const validationError = getAttachmentValidationError(nativeFile);\n\n if (validationError) {\n throw new Error(validationError);\n }\n\n const uploaded = await api.uploadAgentChatAttachment(nativeFile, controller.signal);\n\n if (controller.signal.aborted) {\n return;\n }\n\n entry.attachment = uploaded;\n entry.status = 'done';\n } catch (error) {\n if (controller.signal.aborted) {\n return;\n }\n\n entry.status = 'error';\n delete entriesRef.current[file.id];\n removeRef.current(file.id);\n onErrorRef.current(error instanceof Error ? error.message : 'The file could not be uploaded.');\n } finally {\n bump();\n }\n })();\n }\n\n bump();\n }, [api, attachments.files, bump]);\n\n const isUploading = Object.values(entriesRef.current).some((entry) => entry.status === 'uploading');\n\n return {\n getUploaded: (fileIds) =>\n fileIds\n .map((fileId) => entriesRef.current[fileId]?.attachment)\n .filter((attachment): attachment is AgentChatAttachment => Boolean(attachment)),\n isUploading,\n isUploadingFile: (fileId) => entriesRef.current[fileId]?.status === 'uploading',\n };\n}\n\ninterface PreviewableImage {\n filename: string;\n url: string;\n}\n\nfunction isImageMediaType(mediaType: string | undefined): boolean {\n return Boolean(mediaType?.startsWith('image/'));\n}\n\n/**\n * Fullscreen view of one image attachment. The image is centred and grows to\n * fill the viewport but never beyond its intrinsic size.\n */\nfunction ImagePreviewDialog({\n image,\n onClose,\n}: {\n image: PreviewableImage | null;\n onClose: () => void;\n}): JSX.Element {\n return (\n <Dialog onOpenChange={(open) => (open ? undefined : onClose())} open={image !== null}>\n <DialogContent\n 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\"\n showCloseButton={false}\n >\n <DialogTitle className=\"fk:sr-only\">{image?.filename ?? 'Image preview'}</DialogTitle>\n {image ? (\n <img\n alt={image.filename}\n className=\"fk:block fk:h-auto fk:w-auto fk:max-h-full fk:max-w-full fk:object-contain\"\n src={image.url}\n />\n ) : null}\n <DialogClose\n aria-label=\"Close preview\"\n 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\"\n >\n <XIcon className=\"fk:size-5\" />\n </DialogClose>\n </DialogContent>\n </Dialog>\n );\n}\n\n/** Small round \"×\" pinned to the top-right corner of a chip. */\nfunction ChipRemoveButton({ label, onRemove }: { label: string; onRemove: () => void }): JSX.Element {\n return (\n <button\n aria-label={label}\n 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\"\n onClick={(event) => {\n event.stopPropagation();\n onRemove();\n }}\n type=\"button\"\n >\n <XIcon className=\"fk:size-3\" />\n </button>\n );\n}\n\n/** Square image thumbnail that opens the fullscreen preview when clicked. */\nfunction ImageThumbnail({\n image,\n isUploading = false,\n onOpen,\n onRemove,\n sizeClassName,\n}: {\n image: PreviewableImage;\n isUploading?: boolean;\n onOpen: () => void;\n onRemove?: () => void;\n sizeClassName: string;\n}): JSX.Element {\n return (\n <div className={`fk:relative fk:shrink-0 fk:overflow-hidden fk:rounded-xl fk:bg-muted ${sizeClassName} fk:corner-squircle`}>\n <button\n aria-label={`Preview ${image.filename}`}\n 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\"\n onClick={onOpen}\n type=\"button\"\n >\n <img alt={image.filename} className=\"fk:size-full fk:object-cover\" src={image.url} />\n </button>\n {isUploading ? (\n <div className=\"fk:pointer-events-none fk:absolute fk:inset-0 fk:flex fk:items-center fk:justify-center fk:bg-background/60\">\n <Spinner className=\"fk:size-4\" />\n </div>\n ) : null}\n {onRemove ? <ChipRemoveButton label={`Remove ${image.filename}`} onRemove={onRemove} /> : null}\n </div>\n );\n}\n\n/** Uppercase type label for a file chip, e.g. `NDJSON` or `PDF`. */\nfunction getFileTypeLabel(filename: string, mediaType: string | undefined): string {\n const extension = getExtension(filename);\n\n if (extension) {\n return extension.toUpperCase();\n }\n\n const subtype = mediaType?.split('/')[1]?.split('+')[0];\n\n return subtype ? subtype.toUpperCase() : 'FILE';\n}\n\n/** Card-style chip for non-image files: icon tile, filename, and type. */\nfunction FileChip({\n file,\n href,\n isUploading = false,\n onRemove,\n}: {\n file: { filename: string; mediaType?: string };\n href?: string;\n isUploading?: boolean;\n onRemove?: () => void;\n}): JSX.Element {\n const content = (\n <>\n <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\">\n {isUploading ? <Spinner className=\"fk:size-4\" /> : <FileIcon className=\"fk:size-5\" />}\n </div>\n <div className=\"fk:min-w-0 fk:pr-4 fk:text-left\">\n <div className=\"fk:truncate fk:text-sm fk:font-medium fk:text-foreground\">{file.filename}</div>\n <div className=\"fk:truncate fk:text-xs fk:text-muted-foreground\">{getFileTypeLabel(file.filename, file.mediaType)}</div>\n </div>\n </>\n );\n const chipClassName =\n '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';\n\n return (\n <div className=\"fk:relative fk:shrink-0\">\n {href ? (\n <a\n className={`${chipClassName} fk:transition-colors fk:hover:bg-accent/50 fk:focus-visible:outline-none fk:focus-visible:ring-2 fk:focus-visible:ring-ring`}\n href={href}\n rel=\"noreferrer\"\n target=\"_blank\"\n >\n {content}\n </a>\n ) : (\n <div className={chipClassName}>{content}</div>\n )}\n {onRemove ? <ChipRemoveButton label={`Remove ${file.filename}`} onRemove={onRemove} /> : null}\n </div>\n );\n}\n\n/**\n * Attachment chips shown above the composer textarea while drafting: images\n * as bare thumbnails, other files as labelled chips.\n */\nexport function ComposerAttachments({ uploads }: { uploads: AttachmentUploads }): JSX.Element | null {\n const attachments = usePromptInputAttachments();\n const [preview, setPreview] = useState<PreviewableImage | null>(null);\n\n if (attachments.files.length === 0) {\n return null;\n }\n\n return (\n <>\n <div className=\"fk:flex fk:flex-wrap fk:items-center fk:gap-2\">\n {attachments.files.map((file) => {\n if (isImageMediaType(file.mediaType) && file.url) {\n const image = { filename: file.filename ?? 'Image', url: file.url };\n\n return (\n <ImageThumbnail\n image={image}\n isUploading={uploads.isUploadingFile(file.id)}\n key={file.id}\n onOpen={() => setPreview(image)}\n onRemove={() => attachments.remove(file.id)}\n sizeClassName=\"fk:size-14\"\n />\n );\n }\n\n return (\n <FileChip\n file={{ filename: file.filename ?? 'file', mediaType: file.mediaType }}\n isUploading={uploads.isUploadingFile(file.id)}\n key={file.id}\n onRemove={() => attachments.remove(file.id)}\n />\n );\n })}\n </div>\n <ImagePreviewDialog image={preview} onClose={() => setPreview(null)} />\n </>\n );\n}\n\n/** Attachments of a persisted user message, read from its `file` parts. */\nexport function getAttachmentsFromParts(parts: AgentChatPart[] | null | undefined): AgentChatAttachment[] {\n if (!Array.isArray(parts)) {\n return [];\n }\n\n return parts\n .filter((part) => part.type === 'file' && typeof part.url === 'string')\n .map((part) => ({\n filename: part.filename ?? 'file',\n mediaType: part.mediaType ?? 'application/octet-stream',\n sizeBytes: part.sizeBytes ?? 0,\n url: part.url ?? '',\n }));\n}\n\n/** Attachments rendered with a sent user message: image thumbnails plus file chips. */\nexport function MessageAttachments({ attachments }: { attachments: AgentChatAttachment[] }): JSX.Element | null {\n const [preview, setPreview] = useState<PreviewableImage | null>(null);\n\n if (attachments.length === 0) {\n return null;\n }\n\n const images = attachments.filter((attachment) => isImageMediaType(attachment.mediaType));\n const files = attachments.filter((attachment) => !isImageMediaType(attachment.mediaType));\n\n return (\n <div className=\"fk:flex fk:flex-col fk:items-end fk:gap-2\">\n {images.length > 0 ? (\n <div className=\"fk:flex fk:flex-wrap fk:justify-end fk:gap-2\">\n {images.map((attachment) => (\n <ImageThumbnail\n image={attachment}\n key={attachment.url}\n onOpen={() => setPreview(attachment)}\n sizeClassName=\"fk:size-24\"\n />\n ))}\n </div>\n ) : null}\n <ImagePreviewDialog image={preview} onClose={() => setPreview(null)} />\n {files.length > 0 ? (\n <div className=\"fk:flex fk:flex-wrap fk:justify-end fk:gap-2\">\n {files.map((attachment) => (\n <FileChip file={attachment} href={attachment.url} key={attachment.url} />\n ))}\n </div>\n ) : null}\n </div>\n );\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 { JSX } from 'react';\nimport { useEffect, useMemo, useRef, useState } from 'react';\nimport { CheckIcon, CopyIcon, CornerDownRightIcon, LoaderCircle, PencilIcon } from 'lucide-react';\nimport { 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 {\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 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 { useAgentBasePath } from './chat-list';\nimport { appendDictatedText } from './dictation';\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\nfunction isActiveTurnStatus(status: AgentChatMessageStatus): boolean {\n return status === 'pending' || status === 'streaming' || status === 'awaiting_approval';\n}\n\nfunction getChatDetailRefreshInterval(latestData: AgentChatDetail | undefined): number {\n if (!latestData) {\n return 0;\n }\n\n const lastMessage = latestData.messages[latestData.messages.length - 1];\n\n if (lastMessage && lastMessage.role === 'assistant' && isActiveTurnStatus(lastMessage.status)) {\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 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 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 return {\n ...detail,\n messages: [\n ...detail.messages.filter((message) => !turnIds.has(message.id)),\n turn.userMessage,\n turn.assistantMessage,\n ],\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. */\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({ attachments = [], text }: { attachments?: AgentChatAttachment[]; text: string }): 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 <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.role === 'user') {\n return <UserBubble attachments={getAttachmentsFromParts(message.parts)} text={message.textContent} />;\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 onStatusChange,\n onTurnUpdated,\n}: {\n api: ApiClient;\n chatId: string;\n detail: AgentChatDetail;\n message: AgentChatMessage;\n onStatusChange: (_status: TurnStatus) => void;\n onTurnUpdated: () => void;\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 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 []\n );\n\n useEffect(() => {\n setResumeToken(0);\n setSuppressApprovalPause(false);\n lastDecidedApprovalIdRef.current = null;\n setDecidedApprovals({});\n }, [message.id]);\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 // 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' || status === 'paused' || messageHasPendingMutationApproval(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 statusLabel = isAwaitingApproval ? 'Awaiting approval' : (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\nfunction ChatComposer({\n api,\n effort,\n modelKey,\n modelPending,\n models,\n onEffortChange,\n onError,\n onModelChange,\n onSend,\n onStop,\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 sending: boolean;\n streaming: boolean;\n}): JSX.Element {\n const { attachments, textInput } = usePromptInputController();\n const uploads = useAttachmentUploads(api, onError);\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 status = streaming ? ('streaming' as const) : sending ? ('submitted' as const) : undefined;\n const isBusy = sending || streaming;\n const hasDraft = textInput.value.trim().length > 0 || attachments.files.length > 0;\n const canSubmit = hasDraft && !uploads.isUploading && !isBusy && !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 isBusy ||\n submittingRef.current ||\n modelPending\n ) {\n return Promise.reject(new Error('The message cannot be sent right now.'));\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={isBusy} placeholder=\"Ask the agent anything about your project...\" />\n </PromptInputBody>\n <PromptInputFooter>\n <PromptInputTools>\n <PromptInputActionMenu>\n <PromptInputActionMenuTrigger\n aria-label=\"Add attachments\"\n disabled={isBusy}\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={isBusy}\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 disabled={!isBusy && !canSubmit} status={status} onStop={() => void onStop()} />\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\nfunction ChatConversation({\n api,\n chatId,\n projectId,\n pendingMessage,\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 pendingMessage?: PendingMessage;\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 };\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 const latest = current?.messages.at(-1);\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 const lastMessage = messages[messages.length - 1];\n const liveMessage =\n lastMessage && lastMessage.role === 'assistant' && isActiveTurnStatus(lastMessage.status) ? lastMessage : null;\n const historyMessages = liveMessage ? messages.slice(0, -1) : messages;\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 onStatusChange={(status) => setReportedStatus({ messageId: liveMessage.id, status })}\n onTurnUpdated={() => void mutate()}\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 </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({ projectId }: { projectId: string }): 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-1 fk:flex-col fk:items-center fk:justify-center fk:gap-3 fk:text-center\">\n <h2 className=\"fk:text-2xl fk:font-semibold\">{greeting ?? '\\u00A0'}</h2>\n <p className=\"fk:max-w-md fk:text-sm fk:text-muted-foreground\">\n Ask about your project data, run analyses, or propose changes. The agent works with your own role and space\n access, and every data change needs your approval.\n </p>\n </div>\n );\n}\n\nexport function AgentChatPage(): JSX.Element {\n const { api, projectId } = useProjectApi();\n const { chatId } = useParams<{ chatId: string }>();\n const navigate = useNavigate();\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 [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 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 lastMessage = chatDetail?.messages[chatDetail.messages.length - 1];\n const turnInProgress = Boolean(\n lastMessage && lastMessage.role === 'assistant' && isActiveTurnStatus(lastMessage.status)\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 setPendingMessage({ attachments, chatId, text });\n setSendError(null);\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 const chat = chatId ? null : (await chatApi.createAgentChat({ modelId })).chat;\n const targetChatId = chatId ?? chat!.id;\n const turn = await chatApi.sendAgentChatMessage(targetChatId, { attachments, content: text, modelId });\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 <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 className=\"fk:flex fk:min-h-0 fk:min-w-0 fk:flex-1 fk:flex-col fk:gap-3\">\n {chatId || visiblePendingMessage ? (\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 <ChatConversation\n api={chatApi}\n chatId={chatId ?? null}\n pendingMessage={visiblePendingMessage}\n projectId={projectId}\n resolveDetail={resolveDetail}\n />\n </ChatApprovalContext.Provider>\n ) : (\n <EmptyConversation projectId={chatProjectId} />\n )}\n <div className=\"fk:shrink-0 fk:pb-3\">\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 />\n </div>\n </div>\n </div>\n </div>\n </PromptInputProvider>\n );\n}\n"]}
@@ -1,2 +0,0 @@
1
- import'./index.css';import {a}from'./chunk-O2QMYUPS.js';import {createContext,useState,useCallback,useEffect,useMemo,useContext}from'react';import {jsx}from'react/jsx-runtime';import {Slot}from'radix-ui';import {cva}from'class-variance-authority';var U=["light","dark"],P="(prefers-color-scheme: dark)",z=createContext(void 0);function F({attribute:e="data-theme",children:i,defaultTheme:t,disableTransitionOnChange:a=false,enableColorScheme:m=true,enableSystem:r=true,forcedTheme:o,storageKey:l="theme",themes:d=U,value:k}){let[f,E]=useState(()=>I(l,t,r)),[c,g]=useState(()=>N()),p=y(o??f,r,c),v=useCallback(n=>{if(!o&&(E(n),!!u()))try{window.localStorage.setItem(l,n);}catch{}},[o,l]);useEffect(()=>{if(!u()||!r)return;let n=window.matchMedia(P);function h(s){g(s.matches?"dark":"light");}return g(n.matches?"dark":"light"),n.addEventListener("change",h),()=>{n.removeEventListener("change",h);}},[r]),useEffect(()=>{if(!u())return;let n=window.document.documentElement,s=y(o??f??t,r,c);if(!s)return;let S=a?q():void 0,V=k?Object.values(k):d,b=k?.[s]??s;e==="class"&&(n.classList.remove(...V),n.classList.add(b)),e!=="class"&&n.setAttribute(e,b),m&&(s==="dark"||s==="light")&&(n.style.colorScheme=s),S?.();},[e,t,a,m,r,o,c,f,d,k]);let C=useMemo(()=>({forcedTheme:o,resolvedTheme:p,setTheme:v,systemTheme:c,theme:o??f,themes:r?[...d,"system"]:d}),[r,o,p,v,c,f,d]);return jsx(z.Provider,{value:C,children:i})}function H(){let e=useContext(z);if(!e)throw new Error("useTheme must be used within ThemeProvider");return e}function q(){let e=window.document.createElement("style");return e.appendChild(window.document.createTextNode("*{-webkit-transition:none!important;-moz-transition:none!important;-o-transition:none!important;-ms-transition:none!important;transition:none!important}")),window.document.head.appendChild(e),()=>{window.getComputedStyle(window.document.body),window.setTimeout(()=>{e.remove();},0);}}function I(e,i,t){if(!u())return i??(t?"system":"light");try{let a=window.localStorage.getItem(e);if(a)return a}catch{}return i??(t?"system":"light")}function N(){if(u())return window.matchMedia(P).matches?"dark":"light"}function u(){return typeof window<"u"}function y(e,i,t){if(e)return e!=="system"?e:i?t??"light":"light"}var D=cva("fk:inline-flex fk:shrink-0 fk:items-center fk:justify-center fk:gap-1 fk:rounded-md fk:text-sm fk:font-medium fk:whitespace-nowrap fk:transition-all fk:outline-none fk:focus-visible:border-ring fk:focus-visible:ring-[3px] fk:focus-visible:ring-ring/50 fk:disabled:pointer-events-none fk:disabled:opacity-50 fk:aria-invalid:border-destructive fk:aria-invalid:ring-destructive/20 fk:dark:aria-invalid:ring-destructive/40 fk:[&_svg]:pointer-events-none fk:[&_svg]:shrink-0 fk:[&_svg:not([class*='size-'])]:size-4 fk:corner-squircle",{variants:{variant:{default:"fk:bg-primary fk:text-primary-foreground fk:hover:bg-primary/90",destructive:"fk:bg-destructive fk:text-white fk:hover:bg-destructive/90 fk:focus-visible:ring-destructive/20 fk:dark:bg-destructive/60 fk:dark:focus-visible:ring-destructive/40",outline:"fk:border fk:bg-background fk:shadow-xs fk:hover:bg-accent fk:hover:text-accent-foreground fk:dark:border-input",secondary:"fk:bg-secondary fk:text-secondary-foreground fk:hover:bg-secondary/80",ghost:"fk:hover:bg-accent fk:hover:text-accent-foreground fk:dark:hover:bg-accent/50",link:"fk:text-primary fk:underline-offset-4 fk:hover:underline"},size:{default:"fk:h-9 fk:px-4 fk:py-2 fk:has-[>svg]:px-3",xs:"fk:h-6 fk:rounded-md fk:px-2 fk:text-xs fk:has-[>svg]:px-1.5 fk:[&_svg:not([class*='size-'])]:size-3 fk:corner-squircle",sm:"fk:h-8 fk:rounded-md fk:px-3 fk:has-[>svg]:px-2.5 fk:corner-squircle",lg:"fk:h-10 fk:rounded-md fk:px-6 fk:has-[>svg]:px-4 fk:corner-squircle",icon:"fk:size-9","icon-xs":"fk:size-6 fk:rounded-md fk:[&_svg:not([class*='size-'])]:size-3 fk:corner-squircle","icon-sm":"fk:size-8","icon-lg":"fk:size-10"}},defaultVariants:{variant:"default",size:"default"}});function Z({className:e,variant:i="default",size:t="default",asChild:a$1=false,...m}){let r=a$1?Slot.Root:"button";return jsx(r,{"data-slot":"button","data-variant":i,"data-size":t,className:a(D({variant:i,size:t,className:e})),...m})}export{F as a,H as b,D as c,Z as d};//# sourceMappingURL=chunk-5DHOBLAE.js.map
2
- //# sourceMappingURL=chunk-5DHOBLAE.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/ui/theme-context.tsx","../src/ui/primitives/button.tsx"],"names":["DEFAULT_THEMES","MEDIA_QUERY","ThemeContext","createContext","ThemeProvider","attribute","children","defaultTheme","disableTransitionOnChange","enableColorScheme","enableSystem","forcedTheme","storageKey","themes","value","theme","setThemeState","useState","getInitialTheme","systemTheme","setSystemTheme","getSystemTheme","resolvedTheme","resolveTheme","setTheme","useCallback","nextTheme","isBrowser","useEffect","mediaQuery","handleChange","event","root","nextResolvedTheme","cleanupTransitions","disableTransitions","themeValues","attributeValue","context","useMemo","jsx","useTheme","useContext","style","storedTheme","buttonVariants","cva","Button","className","variant","size","asChild","props","Comp","Slot","cn"],"mappings":"uPAiCA,IAAMA,CAAAA,CAAiB,CAAC,OAAA,CAAS,MAAM,EACjCC,CAAAA,CAAc,8BAAA,CACdC,CAAAA,CAAeC,aAA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IAAA,CAAAC,CAAAA,CAAO,SAAA,CACP,OAAA,CAAAC,GAAAA,CAAU,MACV,GAAGC,CACL,CAAA,CAGK,CACH,IAAMC,CAAAA,CAAOF,GAAAA,CAAUG,IAAAA,CAAK,IAAA,CAAO,QAAA,CAEnC,OACEd,GAAAA,CAACa,CAAAA,CAAA,CACC,WAAA,CAAU,QAAA,CACV,eAAcJ,CAAAA,CACd,WAAA,CAAWC,CAAAA,CACX,SAAA,CAAWK,CAAAA,CAAGV,CAAAA,CAAe,CAAE,OAAA,CAAAI,EAAS,IAAA,CAAAC,CAAAA,CAAM,SAAA,CAAAF,CAAU,CAAC,CAAC,CAAA,CACzD,GAAGI,EACN,CAEJ","file":"chunk-5DHOBLAE.js","sourcesContent":["'use client';\n\nimport { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react';\nimport type { JSX } from 'react';\n\ntype SystemTheme = 'dark' | 'light';\n\ninterface ThemeValue {\n [themeName: string]: string;\n}\n\nexport interface UseThemeProps {\n themes: string[];\n forcedTheme?: string;\n setTheme: (theme: string) => void;\n theme?: string;\n resolvedTheme?: string;\n systemTheme?: SystemTheme;\n}\n\nexport interface ThemeProviderProps {\n themes?: string[];\n forcedTheme?: string;\n enableSystem?: boolean;\n disableTransitionOnChange?: boolean;\n enableColorScheme?: boolean;\n storageKey?: string;\n defaultTheme?: string;\n attribute?: string | 'class';\n value?: ThemeValue;\n children?: React.ReactNode;\n}\n\nconst DEFAULT_THEMES = ['light', 'dark'];\nconst MEDIA_QUERY = '(prefers-color-scheme: dark)';\nconst ThemeContext = createContext<UseThemeProps | undefined>(undefined);\n\nexport function ThemeProvider({\n attribute = 'data-theme',\n children,\n defaultTheme,\n disableTransitionOnChange = false,\n enableColorScheme = true,\n enableSystem = true,\n forcedTheme,\n storageKey = 'theme',\n themes = DEFAULT_THEMES,\n value,\n}: ThemeProviderProps): JSX.Element {\n const [theme, setThemeState] = useState<string | undefined>(() =>\n getInitialTheme(storageKey, defaultTheme, enableSystem)\n );\n const [systemTheme, setSystemTheme] = useState<SystemTheme | undefined>(() => getSystemTheme());\n const resolvedTheme = resolveTheme(forcedTheme ?? theme, enableSystem, systemTheme);\n\n const setTheme = useCallback(\n (nextTheme: string) => {\n if (forcedTheme) {\n return;\n }\n\n setThemeState(nextTheme);\n\n if (!isBrowser()) {\n return;\n }\n\n try {\n window.localStorage.setItem(storageKey, nextTheme);\n } catch {\n //\n }\n },\n [forcedTheme, storageKey]\n );\n\n useEffect(() => {\n if (!isBrowser() || !enableSystem) {\n return;\n }\n\n const mediaQuery = window.matchMedia(MEDIA_QUERY);\n\n function handleChange(event: MediaQueryListEvent): void {\n setSystemTheme(event.matches ? 'dark' : 'light');\n }\n\n setSystemTheme(mediaQuery.matches ? 'dark' : 'light');\n mediaQuery.addEventListener('change', handleChange);\n\n return () => {\n mediaQuery.removeEventListener('change', handleChange);\n };\n }, [enableSystem]);\n\n useEffect(() => {\n if (!isBrowser()) {\n return;\n }\n\n const root = window.document.documentElement;\n const selectedTheme = forcedTheme ?? theme ?? defaultTheme;\n const nextResolvedTheme = resolveTheme(selectedTheme, enableSystem, systemTheme);\n\n if (!nextResolvedTheme) {\n return;\n }\n\n const cleanupTransitions = disableTransitionOnChange ? disableTransitions() : undefined;\n const themeValues = value ? Object.values(value) : themes;\n const attributeValue = value?.[nextResolvedTheme] ?? nextResolvedTheme;\n\n if (attribute === 'class') {\n root.classList.remove(...themeValues);\n root.classList.add(attributeValue);\n }\n\n if (attribute !== 'class') {\n root.setAttribute(attribute, attributeValue);\n }\n\n if (enableColorScheme && (nextResolvedTheme === 'dark' || nextResolvedTheme === 'light')) {\n root.style.colorScheme = nextResolvedTheme;\n }\n\n cleanupTransitions?.();\n }, [\n attribute,\n defaultTheme,\n disableTransitionOnChange,\n enableColorScheme,\n enableSystem,\n forcedTheme,\n systemTheme,\n theme,\n themes,\n value,\n ]);\n\n const context = useMemo<UseThemeProps>(() => {\n return {\n forcedTheme,\n resolvedTheme,\n setTheme,\n systemTheme,\n theme: forcedTheme ?? theme,\n themes: enableSystem ? [...themes, 'system'] : themes,\n };\n }, [enableSystem, forcedTheme, resolvedTheme, setTheme, systemTheme, theme, themes]);\n\n return <ThemeContext.Provider value={context}>{children}</ThemeContext.Provider>;\n}\n\nexport function useTheme(): UseThemeProps {\n const context = useContext(ThemeContext);\n\n if (!context) {\n throw new Error('useTheme must be used within ThemeProvider');\n }\n\n return context;\n}\n\nfunction disableTransitions(): () => void {\n const style = window.document.createElement('style');\n style.appendChild(\n window.document.createTextNode(\n '*{-webkit-transition:none!important;-moz-transition:none!important;-o-transition:none!important;-ms-transition:none!important;transition:none!important}'\n )\n );\n window.document.head.appendChild(style);\n\n return () => {\n window.getComputedStyle(window.document.body);\n\n window.setTimeout(() => {\n style.remove();\n }, 0);\n };\n}\n\nfunction getInitialTheme(storageKey: string, defaultTheme: string | undefined, enableSystem: boolean): string {\n if (!isBrowser()) {\n return defaultTheme ?? (enableSystem ? 'system' : 'light');\n }\n\n try {\n const storedTheme = window.localStorage.getItem(storageKey);\n\n if (storedTheme) {\n return storedTheme;\n }\n } catch {\n //\n }\n\n return defaultTheme ?? (enableSystem ? 'system' : 'light');\n}\n\nfunction getSystemTheme(): SystemTheme | undefined {\n if (!isBrowser()) {\n return undefined;\n }\n\n return window.matchMedia(MEDIA_QUERY).matches ? 'dark' : 'light';\n}\n\nfunction isBrowser(): boolean {\n return typeof window !== 'undefined';\n}\n\nfunction resolveTheme(\n theme: string | undefined,\n enableSystem: boolean,\n systemTheme: SystemTheme | undefined\n): string | undefined {\n if (!theme) {\n return undefined;\n }\n\n if (theme !== 'system') {\n return theme;\n }\n\n if (!enableSystem) {\n return 'light';\n }\n\n return systemTheme ?? 'light';\n}\n","import * as React from 'react';\nimport { Slot } from 'radix-ui';\nimport { cva, type VariantProps } from 'class-variance-authority';\nimport { cn } from '../lib/utils';\n\nconst buttonVariants = cva(\n \"fk:inline-flex fk:shrink-0 fk:items-center fk:justify-center fk:gap-1 fk:rounded-md fk:text-sm fk:font-medium fk:whitespace-nowrap fk:transition-all fk:outline-none fk:focus-visible:border-ring fk:focus-visible:ring-[3px] fk:focus-visible:ring-ring/50 fk:disabled:pointer-events-none fk:disabled:opacity-50 fk:aria-invalid:border-destructive fk:aria-invalid:ring-destructive/20 fk:dark:aria-invalid:ring-destructive/40 fk:[&_svg]:pointer-events-none fk:[&_svg]:shrink-0 fk:[&_svg:not([class*='size-'])]:size-4 fk:corner-squircle\",\n {\n variants: {\n variant: {\n default: 'fk:bg-primary fk:text-primary-foreground fk:hover:bg-primary/90',\n destructive:\n 'fk:bg-destructive fk:text-white fk:hover:bg-destructive/90 fk:focus-visible:ring-destructive/20 fk:dark:bg-destructive/60 fk:dark:focus-visible:ring-destructive/40',\n outline:\n 'fk:border fk:bg-background fk:shadow-xs fk:hover:bg-accent fk:hover:text-accent-foreground fk:dark:border-input',\n secondary: 'fk:bg-secondary fk:text-secondary-foreground fk:hover:bg-secondary/80',\n ghost: 'fk:hover:bg-accent fk:hover:text-accent-foreground fk:dark:hover:bg-accent/50',\n link: 'fk:text-primary fk:underline-offset-4 fk:hover:underline',\n },\n size: {\n default: 'fk:h-9 fk:px-4 fk:py-2 fk:has-[>svg]:px-3',\n xs: \"fk:h-6 fk:rounded-md fk:px-2 fk:text-xs fk:has-[>svg]:px-1.5 fk:[&_svg:not([class*='size-'])]:size-3 fk:corner-squircle\",\n sm: 'fk:h-8 fk:rounded-md fk:px-3 fk:has-[>svg]:px-2.5 fk:corner-squircle',\n lg: 'fk:h-10 fk:rounded-md fk:px-6 fk:has-[>svg]:px-4 fk:corner-squircle',\n icon: 'fk:size-9',\n 'icon-xs': \"fk:size-6 fk:rounded-md fk:[&_svg:not([class*='size-'])]:size-3 fk:corner-squircle\",\n 'icon-sm': 'fk:size-8',\n 'icon-lg': 'fk:size-10',\n },\n },\n defaultVariants: {\n variant: 'default',\n size: 'default',\n },\n }\n);\n\nfunction Button({\n className,\n variant = 'default',\n size = 'default',\n asChild = false,\n ...props\n}: React.ComponentProps<'button'> &\n VariantProps<typeof buttonVariants> & {\n asChild?: boolean;\n }) {\n const Comp = asChild ? Slot.Root : 'button';\n\n return (\n <Comp\n data-slot=\"button\"\n data-variant={variant}\n data-size={size}\n className={cn(buttonVariants({ variant, size, className }))}\n {...props}\n />\n );\n}\n\nexport { Button, buttonVariants };\n"]}
@@ -1,4 +0,0 @@
1
- import'./index.css';import {A,C,B,p,o as o$1,h as h$1,i}from'./chunk-2IRKGO2B.js';import {d as d$1,c}from'./chunk-P6BZ4QP7.js';import {b}from'./chunk-7SK5YPHT.js';import {g as g$1}from'./chunk-ZBI744KS.js';import {ra}from'./chunk-QHDL6CA2.js';import {e,g,h,j,o,n,k}from'./chunk-SZEGGBOC.js';import {d}from'./chunk-5DHOBLAE.js';import {a,d as d$2,c as c$1,e as e$1,g as g$2}from'./chunk-HDOIOXMP.js';import {PencilIcon,Trash2Icon,Ellipsis,Settings2,RefreshCw,Loader2,Trash2}from'lucide-react';import {jsxs,jsx}from'react/jsx-runtime';import {useState}from'react';import {find,propEq}from'ramda';import {gql}from'@apollo/client';import {useApolloClient}from'@apollo/client/react';import {toast}from'sonner';function Me({entityName:l,entityNamePlural:a,row:r,options:s={canDelete:true,canEdit:true}}){let f=A(),E=b(),c=r.original._id,D=(s.canDelete??true)&&E,p=s.canEdit??true;function h$1(){f({type:"EditEntity",payload:{entityId:c,entityNamePlural:a}});}function d$1(){f({type:"DeleteEntity",payload:{entityId:c,entityName:l}});}return jsxs("div",{className:"fk:flex",children:[p&&jsxs(d,{className:"fk:flex fk:h-7 fk:w-7 fk:p-0 fk:mr-1",onClick:h$1,variant:"ghost",children:[jsx(PencilIcon,{className:"fk:h-4 fk:w-4"}),jsx("span",{className:"fk:sr-only",children:"Edit"})]}),D&&!p&&jsxs(d,{className:"fk:flex fk:h-7 fk:w-7 fk:p-0 fk:mr-1",onClick:d$1,variant:"ghost",children:[jsx(Trash2Icon,{className:"fk:h-4 fk:w-4"}),jsx("span",{className:"fk:sr-only",children:"Delete"})]}),p&&D&&jsxs(e,{children:[jsx(g,{asChild:true,children:jsxs(d,{className:"fk:flex fk:h-7 fk:w-7 fk:p-0",variant:"ghost",children:[jsx(Ellipsis,{className:"fk:h-4 fk:w-4"}),jsx("span",{className:"fk:sr-only",children:"Additional actions"})]})}),jsxs(h,{align:"end",className:"w-[160px]",children:[jsxs(j,{onClick:h$1,children:[jsx(PencilIcon,{className:"fk:mr-2 fk:h-4 fk:w-4"}),"Edit"]}),jsx(o,{}),jsxs(j,{className:"fk:text-destructive",onClick:d$1,children:[jsx(Trash2Icon,{className:"fk:mr-2 fk:h-4 fk:w-4"}),"Delete"]})]})]})]})}function Y({table:l}){return jsxs(e,{children:[jsx(g,{asChild:true,children:jsxs(d,{className:"fk:hidden fk:h-8 fk:lg:flex",size:"sm",variant:"outline",children:[jsx(Settings2,{className:"fk:mr-2 fk:h-4 fk:w-4"}),"View"]})}),jsxs(h,{align:"end",className:"fk:w-[150px]",children:[jsx(n,{children:"Toggle columns"}),jsx(o,{}),l.getAllColumns().filter(a=>typeof a.accessorFn<"u"&&a.getCanHide()).map(a=>jsx(k,{checked:a.getIsVisible(),className:"capitalize",onCheckedChange:r=>{a.toggleVisibility(!!r);},children:a.id},a.id))]})]})}function Ue({entityName:l,isReloading:a$1=false,onReload:r,table:s}){let f=A(),E=d$1(),c$2=c(),D=useApolloClient(),{currentProject:p$1,currentProjectId:h}=g$1(),d$3=p$1?.schema??[],w=p$1?.scopes,[ee,te,ae]=C(),[b$1,B$1]=useState(false),y=b(),m=s.getSelectedRowModel().rows.map(e=>e.original._id);function oe(){f({type:"AddEntity",payload:{entityName:l}});}function ne(e){E({type:"setScope",payload:{projectId:h,scope:e}});}async function le(e){if(e.length===0)return;let u=h$1(l,d$3,e);await new Promise((se,re)=>{te(gql`
2
- ${u}
3
- `),ae({variables:{where:i(e)},update(x){for(let ce of e)x.evict({id:ce});},onCompleted:()=>{se();},onError:x=>{re(x);}}),ee(true);});}function ie(){let e=l==="_asset"?"asset":l.toLowerCase();f({type:"AlertDialog",payload:{options:{dialogTitle:`Delete ${m.length} ${e}${m.length>1?"s":""}`,dialogMessage:m.length>1?`Are you sure you want to delete the selected ${e}s? They will be deleted permanently.`:`Are you sure you want to delete the selected ${e}? The item will be deleted permanently.`,dialogCancelTitle:"Cancel",dialogActionLabel:"Delete",isDestructive:true,dialogActionSubmit:async()=>{B$1(true);try{let u=[...m];await le(u),s.resetRowSelection(),await p(D,o$1(l,d$3),u),toast.success(u.length>1?"Items successfully deleted.":"Item successfully deleted.");}catch{toast.error("Failed to delete selected items.");}finally{B$1(false);}},dialogActionCancel:()=>{}}}});}return jsxs("div",{className:"fk:flex fk:items-center fk:justify-between",children:[jsxs("div",{className:"fk:flex fk:flex-1 fk:items-center fk:space-x-2",children:[w&&w.length>0?jsxs(a,{defaultValue:c$2.scope,onValueChange:e=>{ne(e);},value:c$2.scope,children:[jsxs(d$2,{className:"fk:w-48!",id:"project",size:"sm",children:[jsx("span",{className:"fk:text-muted-foreground",children:"Scope:"}),jsx(c$1,{children:(find(propEq(c$2.scope??"","name"))(w)||null)?.label})]}),jsx(e$1,{children:w.map(e=>jsx(g$2,{value:e.name,children:e.label},e.name))})]}):null,jsx(Y,{table:s}),r?jsx(d,{"aria-label":"Reload",className:"fk:h-8",disabled:b$1||a$1,onClick:r,size:"icon-sm",variant:"outline",children:jsx(RefreshCw,{className:a$1?"fk:animate-spin":void 0})}):null,jsx(B,{table:s})]}),m.length>0?jsx(ra,{disabled:!y,children:jsxs(d,{className:"fk:h-8 fk:mr-2 fk:lg:flex",disabled:b$1||!y,onClick:ie,size:"sm",variant:"destructive",children:[b$1?jsx(Loader2,{className:"fk:mr-2 fk:h-4 fk:w-4 fk:animate-spin"}):jsx(Trash2,{className:"fk:mr-2 fk:h-4 fk:w-4"}),"Delete (",m.length,")"]})}):null,jsx(ra,{disabled:!y,children:jsx(d,{className:"fk:ml-auto fk:h-8 fk:lg:flex",disabled:b$1||!y,onClick:oe,size:"sm",variant:"default",children:"Create"})})]})}export{Me as a,Y as b,Ue as c};//# sourceMappingURL=chunk-ANVO5P65.js.map
4
- //# sourceMappingURL=chunk-ANVO5P65.js.map
@@ -1,6 +0,0 @@
1
- import'./index.css';import {g as g$2,d,f}from'./chunk-HROHAMPM.js';import {g as g$1,d as d$2}from'./chunk-ZBI744KS.js';import {sa as sa$1,ub,o,pa as pa$1,da as da$1,ea as ea$1,ha as ha$1,ia as ia$1,fa as fa$1,ja}from'./chunk-QHDL6CA2.js';import {b,c,h,i,k,l,j as j$1}from'./chunk-ODORXGGY.js';import {d as d$1}from'./chunk-5DHOBLAE.js';import {lazy,createContext,useCallback,useMemo,useState,useRef,useEffect,useContext,useTransition,useId,Suspense}from'react';import Wt,{useSWRConfig}from'swr';import {formatDistance,format}from'date-fns';import {BotIcon,XCircleIcon,LoaderCircle,XIcon,CheckIcon,CloudUploadIcon,FileTextIcon,DownloadIcon,LinkIcon,MessageSquareIcon,SendIcon,CheckCircle2Icon,CircleSlashIcon,ShieldIcon,DatabaseZapIcon,ShieldCheckIcon,TriangleAlertIcon,ArrowRightIcon,MoveRightIcon}from'lucide-react';import {jsx,jsxs,Fragment}from'react/jsx-runtime';import {pipeJsonRender}from'@json-render/core';import {useLocation,Link}from'react-router-dom';import {readUIMessageStream,parseJsonEventStream,uiMessageChunkSchema}from'ai';function Ne(){let{currentProjectId:e}=g$1(),{mutate:t}=useSWRConfig();return useCallback(n=>{if(!e)return;let a=g$2(e).approvalsCount;n?t(a,n,{revalidate:true}):t(a);},[e,t])}var rt=5e3,st=150,ie=new Set;function ot(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 it(e,t,n=d$2){return !e||e.kind!=="schema"||e.status!=="approved"||e.error?false:e.executedAt?(n(t),false):true}function Z({approvalId:e,approvalUrl:t,fetchApproval:n,projectId:a,revalidate:r=d$2,sleep:s=l=>new Promise(u=>setTimeout(u,l))}){let l=`${a}:${e}`,u=n??(t?ot(t):null);!u||ie.has(l)||(ie.add(l),(async()=>{try{for(let c=0;c<st;c+=1){let k=null;try{k=await u();}catch{k=null;}if(k==="missing"||k!==null&&!it(k,a,r))return;await s(rt);}}finally{ie.delete(l);}})());}var ft={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 mt({status:e}){return jsx(b,{className:`fk:border-none fk:h-4.75 fk:text-[0.6875rem] fk:leading-4.5 fk:tracking-wide ${ft[e]}`,variant:"secondary",children:e})}function M(e){return e==null?"\u2014":typeof e=="object"?JSON.stringify(e):String(e)}function $e({after:e,before:t}){let n=M(t),a=M(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 kt(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 gt({operation:e}){if(e.rows.length===0)return null;let t=(e.contextColumns??[]).filter(a=>a!=="_id");if(e.kind==="delete")return jsxs(da$1,{children:[jsx(ea$1,{children:jsxs(ha$1,{children:[jsx(ia$1,{children:"Records to delete"}),t.map(a=>jsx(ia$1,{children:a},a))]})}),jsx(fa$1,{children:e.rows.map((a,r)=>jsxs(ha$1,{className:"fk:bg-destructive/5",children:[jsx(ja,{className:"fk:font-mono fk:text-xs fk:text-destructive",children:a.id??M(a.before?._id)}),t.map(s=>jsx(ja,{className:"fk:text-xs fk:text-muted-foreground",children:M(a.before?.[s])},s))]},a.id??r.toString()))})]});let n=e.columns.filter(a=>a!=="_id"&&!t.includes(a));return jsxs(da$1,{children:[jsx(ea$1,{children:jsxs(ha$1,{children:[jsx(ia$1,{children:"ID"}),t.map(a=>jsx(ia$1,{children:a},a)),n.map(a=>jsx(ia$1,{children:a},a))]})}),jsx(fa$1,{children:e.rows.map((a,r)=>jsxs(ha$1,{children:[jsx(ja,{className:"fk:font-mono fk:text-xs fk:text-muted-foreground",children:a.id??"\u2014"}),t.map(s=>jsx(ja,{className:"fk:max-w-72 fk:text-xs fk:text-muted-foreground",children:jsx("span",{className:"fk:line-clamp-3",children:M(a.before?.[s])})},s)),n.map(s=>jsx(ja,{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:M(a.after?.[s])}):jsx($e,{after:a.after?.[s],before:a.before?.[s]})},s))]},a.id??r.toString()))})]})}function yt({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((r,s)=>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:r.query}),r.variables&&Object.keys(r.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(r.variables,null,2)}):null]},s.toString()))})]})}function _e(e){if(e.kind!=="plugin")return null;let n=e.operations[0]?.query.split(`
2
- `)[0]?.trim()?.split("/"),a=n?.at(-1),r=n?.[0];if(!a||!r||n?.length<2)return null;let s=a.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").toLowerCase(),l=r.replace(/[_-]+/g," ").replace(/\b\w/g,m=>m.toUpperCase()),u=e.operations[0]?.query??"",c=/^Connection:\s*(Project|Personal)\s+—\s+(.+)$/m.exec(u);if(c?.[1]&&c[2])return {action:s,app:l,account:c[2].trim(),scope:c[1]==="Project"?"project":"personal"};let k=/^Connection:.*?([^\s<>]+@[^\s<>]+)\s*$/m.exec(u)?.[1];return {action:s,app:l,account:k}}function vt(e){let t=_e(e);return t?`${t.action.charAt(0).toUpperCase()}${t.action.slice(1)} in ${t.app}`:e.kind==="exec"?"Run a sandbox command":e.kind==="schema"?e.operationsSummary.replace(/^Schema: /,""):e.kind==="plugin"?"Use a connected app":e.operationsSummary}function bt({operation:e}){if(e.rows.length===0)return null;let t=a=>a!=null&&a!==false,n=e.columns.filter(a=>e.rows.some(s=>t(s.before?.[a])||t(s.after?.[a]))?e.kind!=="update"?true:e.rows.some(s=>M(s.before?.[a])!==M(s.after?.[a])):false);return jsx("div",{className:"fk:overflow-x-auto fk:rounded-md fk:border fk:border-border fk:corner-squircle",children:jsxs(da$1,{className:"fk:text-xs",children:[jsx(ea$1,{children:jsxs(ha$1,{children:[jsx(ia$1,{className:"fk:h-8",children:e.entity==="scopes"||e.entity==="spaces"||e.entity==="studio"?"Setting":"Attribute"}),n.map(a=>jsx(ia$1,{className:"fk:h-8",children:a},a))]})}),jsx(fa$1,{children:e.rows.map((a,r)=>jsxs(ha$1,{children:[jsxs(ja,{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,{className:"fk:ml-2",variant:"secondary",children:"new"}):null,e.kind==="update"&&a.after===null?jsx(b,{className:"fk:ml-2",variant:"destructive",children:"removed"}):null]}),n.map(s=>jsx(ja,{className:"fk:py-1.5",children:e.kind==="create"?jsx("span",{children:M(a.after?.[s])}):e.kind==="delete"?jsx("span",{className:"fk:text-muted-foreground",children:M(a.before?.[s])}):jsx($e,{after:a.after?.[s],before:a.before?.[s]})},s))]},a.id??r.toString()))})]})})}function ht(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 xt({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:ht(n)}),jsx(bt,{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 Rt(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 Le({api:e,approval:t,onDecided:n}){let[a,r]=useState(t),[s,l]=useState(t),[u,c]=useState(""),[k,m]=useTransition(),[y,x]=useState(false),[h,b]=useState(false),[d,R]=useState(""),w=Ne();t!==s&&(l(t),Rt(t,s)||a.id===t.id&&a.status!=="pending"&&t.status==="pending"||r(t));function A(v){r(v),w(),v.kind==="schema"&&v.status==="approved"&&Z({approvalId:v.id,approvalUrl:g$2(v.projectId).approval(v.id),projectId:v.projectId}),n?.(v);}function H({approved:v,force:P=false,reason:E,remember:T=false}){m(async()=>{c("");try{let S=await e.decideApproval(a.id,{approved:v,force:P,reason:E,remember:T});if(S.errorCode==="stale_preview"){b(!0),S.approval&&r(S.approval);return}if(b(!1),x(!1),S.approval?A(S.approval):S.success?A({...a,decidedAt:a.decidedAt??new Date().toISOString(),reason:E??a.reason,status:v?"approved":"rejected"}):S.errorCode==="already_decided"&&n?.(a),!S.success&&(S.errorCode!=="already_decided"||!S.approval)){let $=Array.isArray(S.errorMessage)?S.errorMessage.join(", "):S.errorMessage;c($||"Failed to submit the decision.");}}catch(S){c(S instanceof Error?S.message:"Failed to submit the decision.");}});}return {approval:a,decide:H,errorMessage:u,isDeciding:k,isPending:a.status==="pending",isRejectDialogOpen:y,isStale:h,rejectReason:d,setIsRejectDialogOpen:x,setRejectReason:R}}function Oe({allowRemember:e=false,askForRejectionReason:t,decide:n,isDeciding:a,isRejectDialogOpen:r,isStale:s,rejectReason:l$1,setIsRejectDialogOpen:u,setRejectReason:c$1,variant:k$1}){let m=k$1==="header",y=m?"fk:px-8 fk:min-w-32":void 0,x=m?"default":"sm",[h$1,b]=useState(false),d=useId();return jsxs(Fragment,{children:[jsxs("div",{className:"fk:flex fk:flex-nowrap fk:items-center fk:gap-2",children:[jsxs(d$1,{className:y,disabled:a,size:x,onClick:()=>n({approved:true,force:s,remember:e&&h$1}),children:[a?jsx(LoaderCircle,{className:"fk:size-4 fk:animate-spin"}):jsx(CheckIcon,{className:"fk:size-4"}),s?"Approve anyway":"Approve"]}),jsxs(d$1,{className:y,disabled:a,size:x,variant:"outline",onClick:()=>{t?(c$1(""),u(true)):n({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:d,children:[jsx(o,{checked:h$1,id:d,onCheckedChange:R=>b(R===true)}),"Always allow this tool for this automation"]}):null]}),t?jsx(c,{open:r,onOpenChange:u,children:jsxs(h,{children:[jsxs(i,{children:[jsx(k,{children:"Reject this proposal?"}),jsx(l,{children:"The mutation will not be executed. The agent receives your reason and can adapt its plan."})]}),jsx(pa$1,{placeholder:"Optional reason for the agent...",value:l$1,onChange:R=>c$1(R.target.value)}),jsxs(j$1,{children:[jsx(d$1,{disabled:a,size:"sm",variant:"outline",onClick:()=>u(false),children:"Cancel"}),jsxs(d$1,{disabled:a,size:"sm",variant:"destructive",onClick:()=>n({approved:false,reason:l$1.trim()||void 0}),children:[a?jsx(LoaderCircle,{className:"fk:size-4 fk:animate-spin"}):jsx(ArrowRightIcon,{className:"fk:size-4"}),"Reject proposal"]})]})]})}):null]})}function je({approval:e,chat:t,errorMessage:n,isPending:a,isStale:r}){let{preview:s}=e,l=t?_e(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(mt,{status:e.status}),e.kind==="schema"?jsx(b,{variant:"outline",children:"Schema change"}):null,jsx("span",{className:"fk:text-sm fk:font-medium",children:t?vt(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}),a?` \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==="schema"&&s?jsx(xt,{preview:s}):s&&s.operations.length>0?jsx("div",{className:"fk:space-y-4",children:s.operations.map((u,c)=>jsxs("div",{className:"fk:space-y-2",children:[jsx("div",{className:"fk:text-sm fk:font-medium",children:kt(u)}),u.kind==="delete"&&u.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:[u.affectedCount.toString()," record",u.affectedCount===1?"":"s"," will be permanently deleted."]}):null,jsx(gt,{operation:u}),u.truncated?jsxs("div",{className:"fk:text-xs fk:text-muted-foreground",children:["Preview limited to the first ",u.rows.length.toString()," rows."]}):null]},c.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:t?l?`This action uses ${l.scope==="project"?"the project's":"your"} ${l.app} account${l.account?` (${l.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."}),jsx(yt,{chat:t,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,n?jsx("div",{className:"fk:text-sm fk:text-destructive",children:n}):null]})}function ze({api:e,approval:t,chat:n,onDecided:a}){let{approval:r,decide:s,errorMessage:l,isDeciding:u,isPending:c,isRejectDialogOpen:k,isStale:m,rejectReason:y,setIsRejectDialogOpen:x,setRejectReason:h}=Le({api:e,approval:t,onDecided:a});return jsxs(Fragment,{children:[jsx(je,{approval:r,chat:n,errorMessage:l,isPending:c,isStale:m}),c?jsx("div",{className:"fk:mt-4",children:jsx(Oe,{allowRemember:!n&&r.kind==="plugin"&&!!r.automationId,askForRejectionReason:!n,decide:s,isDeciding:u,isRejectDialogOpen:k,isStale:m,rejectReason:y,setIsRejectDialogOpen:x,setRejectReason:h,variant:"inline"})}):null]})}function Ja({api:e,approval:t,onClose:n,onDecided:a}){let{approval:r,decide:s,errorMessage:l,isDeciding:u,isPending:c,isRejectDialogOpen:k,isStale:m,rejectReason:y,setIsRejectDialogOpen:x,setRejectReason:h}=Le({api:e,approval:t,onDecided:a});return jsx(sa$1,{actions:c?jsx(Oe,{allowRemember:r.kind==="plugin"&&!!r.automationId,askForRejectionReason:true,decide:s,isDeciding:u,isRejectDialogOpen:k,isStale:m,rejectReason:y,setIsRejectDialogOpen:x,setRejectReason:h,variant:"header"}):null,depth:0,isFocused:true,onClose:n,title:"Mutation proposal",children:jsx(je,{approval:r,chat:false,errorMessage:l,isPending:c,isStale:m})})}var St="Approved by Flexkit Jev policy",wt="Approved by automation tool allow rule",At=new Set(["data-create-sandbox","data-execute-graphql","data-load-skill","data-plan","data-plugin-call","data-run-command","data-search-schema","data-update-memory","data-validate-graphql","data-web-search"]);function V(e){return At.has(e)}function g(e){return e.data}function le(e){return !e.decidedBy&&!!(e.reason?.startsWith(St)||e.reason?.startsWith(wt))}function q(e,t=72){let n=e.trim();if(n.length<=t)return n;let a=n.slice(0,t),r=a.lastIndexOf(" ");return `${(r>=Math.floor(t*.6)?a.slice(0,r):a).trimEnd()}\u2026`}function Pt(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 Tt(e){let t=e.lastIndexOf(`
3
- `),n=-1,a=/[.!?](?=\s)/g,r;for(;(r=a.exec(e))!==null;)n=r.index;let s=Math.max(t,n);return s<0?"":e.slice(0,s+1)}function Nt(e,t){let a=(Tt(e)).split(/\r?\n/).map(c=>c.trim()).filter(Boolean),r=a[a.length-1];if(!r)return null;let l=/^\*\*(.+?)\*\*:?$/.exec(r)?.[1]??/^#{1,6}\s+(.+)$/.exec(r)?.[1]??/^(.+?[.!?])(?:\s|$)/.exec(r)?.[1]??r,u=Pt(l);return !u||/^reasoning$/i.test(u)?null:q(u)}function Je(e){return e.replace(/[_-]+/g," ").trim()}function Dt(e){if(e.type==="data-load-skill"){let t=g(e);return t.status!=="loading"?null:t.skillName?q(`Loading skill "${t.skillName}"`):"Loading skill"}if(e.type==="data-search-schema")return g(e).status==="loading"?"Searching schema":null;if(e.type==="data-validate-graphql")return g(e).status==="loading"?"Validating GraphQL query":null;if(e.type==="data-execute-graphql"){let t=g(e);return t.status!=="loading"?null:t.operationType==="mutation"?"Executing GraphQL mutation":"Executing GraphQL query"}if(e.type==="data-update-memory")return g(e).status==="loading"?"Updating memory":null;if(e.type==="data-web-search"){let t=g(e);return t.status!=="loading"?null:t.query?q(`Searching the web for "${t.query}"`):"Searching the web"}if(e.type==="data-run-command"){let t=g(e);return ["executing","running","waiting"].includes(t.status)?q(`Running ${[t.command,...t.args].join(" ")}`):null}if(e.type==="data-create-sandbox")return g(e).status==="loading"?"Creating sandbox":null;if(e.type==="data-plugin-call"){let t=g(e);return t.status!=="loading"?null:q(`Calling ${t.pluginId}: ${Je(t.tool)}`)}if(e.type==="data-subtask"){let t=g(e);return t.status==="running"?q(`Running subtask: ${t.title}`):null}return null}var Mt=new Set(["data-execute-graphql","data-search-schema","data-validate-graphql"]);function te(e){if(!V(e.type)||e.type==="data-plan"||Mt.has(e.type))return null;let t=g(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??"")}: ${Je(String(t.tool??""))}`;default:return "The tool call failed"}}function ae(e){if(e.type==="step-start"||e.type==="reasoning")return true;if(V(e.type))return te(e)===null;if(e.type==="data-mutation-approval"){let t=g(e);return le(t)&&t.status!=="error"}return false}function ee(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=g(n),r=a.steps.findIndex(s=>s.status==="in_progress");return r<0?null:q(`Step ${(r+1).toString()} of ${a.steps.length.toString()}: ${a.steps[r].step}`)}return null}function Ct(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"?Nt(n.text)??ee(e):ee(e):n.type==="data-mutation-approval"?g(n).status==="pending"?"Awaiting approval":ee(e):n.type==="text"?null:Dt(n)??ee(e)}return null}function ue(e){return e?e.parts.some(t=>t.type!=="data-mutation-approval"?false:g(t).status==="pending"):false}function de(e,t={}){let n=false,a=[];for(let r of e.parts){if(r.type!=="data-mutation-approval"){a.push(r);continue}let s=g(r);if(s.status!=="pending"){a.push(r);continue}n=true;let l=t[s.approvalId];l&&l!=="pending"&&a.push({...r,data:{...s,status:l}});}return n?{...e,parts:a}:e}function qe(e,t){if(!e)return [];let n=[],a=t?.pendingOnly??false;for(let r of e.parts){if(r.type!=="data-mutation-approval")continue;let s=g(r);a&&s.status!=="pending"||n.push(s.approvalId);}return n}function It(e){return qe(e,{pendingOnly:true})}var X=class extends Error{},ne=class extends Error{};function Ue({url:e,signal:t,state:n,onState:a,wake:r,fetchStream:s=fetch,retryMs:l=2e3}){let u=0,c=0,k=new TransformStream,m=k.writable.getWriter(),y=new AbortController;m.closed.catch(d=>y.abort(d));let x=()=>{y.abort(t.reason),m.abort(t.reason).catch(()=>{});};t.addEventListener("abort",x,{once:true}),t.aborted&&x();let h=()=>new Promise(d=>{let R=()=>{clearTimeout(w),y.signal.removeEventListener("abort",R),r?.removeEventListener("wake",R),d();},w=setTimeout(R,l);y.signal.addEventListener("abort",R,{once:true}),r?.addEventListener("wake",R,{once:true}),y.signal.aborted&&R();});async function b(){try{for(await m.write({type:"start"});!y.signal.aborted;){try{let d=await s(`${e}${e.includes("?")?"&":"?"}wire=2&startIndex=${u}`,{credentials:"include",signal:y.signal});if(d.status===404){a("unavailable"),await m.close();return}if(d.status===401||d.status===403)throw new ne("Stream access denied");if(!d.ok||!d.body)throw new Error(`Stream request failed: ${d.status}`);if(d.headers.get("x-flexkit-stream-version")!=="2")throw await d.body.cancel(),new X("Backend uses legacy replay");a("streaming");let R=d.body.pipeThrough(new TextDecoderStream).getReader(),w="",A=!1;try{for(;!y.signal.aborted;){let{value:H,done:v}=await R.read();if(v)break;w+=H;let P;for(;(P=w.indexOf(`
4
- `))>=0;){let E=w.slice(0,P);if(w=w.slice(P+1),!E)continue;let T=JSON.parse(E);if(!Number.isSafeInteger(T.index)||T.index<0)throw new Error("Invalid replay cursor");if(!(T.index<u)){if(T.index!==u)throw new Error("Replay cursor gap");T.chunk&&await m.write(T.chunk),u=T.index+1,c=0,T.chunk?.type==="finish"&&T.chunk.messageMetadata?.flexkitTerminal&&(A=!0);}}if(w.length>2e6)throw new Error("Oversized replay frame");if(A)break}}finally{await R.cancel().catch(()=>{}),R.releaseLock();}if(A||n().terminal&&!w){await m.write({type:"finish"}),await m.close(),a("finished");return}}catch(d){if(y.signal.aborted||d instanceof X||d instanceof ne||++c>=5)throw d}do a(n().paused?"paused":"streaming"),await h();while(!y.signal.aborted&&n().paused&&!n().terminal)}}catch(d){await m.abort(d).catch(()=>{});}finally{t.removeEventListener("abort",x),m.releaseLock();}}return b(),pipeJsonRender(k.readable)}var Kt=lazy(()=>import('./spec-renderer-ZZ3GPVKU.js').then(e=>({default:e.RunSpecPart})));function Zt(e){return jsx(Suspense,{fallback:null,children:jsx(Kt,{...e})})}function ea(){let{currentProjectId:e}=g$1();return {api:useMemo(()=>e?d(e):null,[e]),projectId:e}}var Fe=5,Ke=2e3,Ze=120,ce="data-spec",ta=createContext(null),aa=createContext(false);function na(e){return new Promise(t=>window.setTimeout(t,e))}function ra(e){return e instanceof Error?e.name==="AbortError"||e.message.toLowerCase().includes("aborted"):false}function sa(e){return e.some(t=>!ae(t))}function oa(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 ia(e){let t=oa(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 r=[],s=0,l=()=>{sa(r)&&n.push({...a,id:`${a.id}-${s.toString()}`,parts:r}),s++,r=[];};for(let u of a.parts){if(u.type==="data-user-message"){let c=g(u);l(),n.push({id:u.id??crypto.randomUUID(),parts:c.parts,role:"user"});continue}r.push(u);}l();}return n}function dn(e){return useMemo(()=>ia(e),[e])}function F(e){return e==="success"||e==="failed"||e==="cancelled"||e==="skipped"}function et({latestMessage:e,recordStatus:t,suppressApprovalPause:n}){return F(t)||n||t==="running"?false:t==="awaiting_approval"?true:ue(e)}function cn(e,t){let[n,a]=useState(false),r=la(n?e:"",t),[s,l]=useState(),[u,c]=useState("streaming"),k=useRef(t);k.current=t;let m=useRef(null);m.current||(m.current=new EventTarget);let y=m.current,x=t?.resumeToken;return useEffect(()=>{y.dispatchEvent(new Event("wake"));},[x,y]),useEffect(()=>{if(a(false),l(void 0),!e){c("unavailable");return}let h=new AbortController,b,d,R=()=>{b=void 0,d&&!h.signal.aborted&&l({...d});},w=Ue({url:e,signal:h.signal,state:()=>({terminal:F(k.current?.recordStatus),paused:et({latestMessage:d,recordStatus:k.current?.recordStatus,suppressApprovalPause:k.current?.suppressApprovalPause??false})}),onState:A=>{h.signal.aborted||c(A);},wake:y});return (async()=>{try{for await(let A of readUIMessageStream({stream:w,terminateOnError:!0}))d=A,b||(b=setTimeout(R,Ze));R();}catch(A){if(h.signal.aborted)return;A instanceof X?a(true):(console.error("Run stream error",A),c("error"));}})(),()=>{h.abort(),b&&clearTimeout(b);}},[e,y]),n?r:{message:s?de(s,t?.decidedApprovals??{}):void 0,status:u}}function la(e,t){let[n,a]=useState(),[r,s]=useState("streaming"),l=t?.recordStatus,u=t?.resumeToken??0,c=useRef(t?.decidedApprovals??{});c.current=t?.decidedApprovals??{};let k=useRef(t?.suppressApprovalPause??false);k.current=t?.suppressApprovalPause??false;let m=useRef(e),y=useRef(n);return y.current=n,useEffect(()=>{let x=m.current!==e;if(m.current=e,!e){a(void 0),s("unavailable");return}let h=new AbortController,b=x?void 0:y.current,d=x?0:b?.parts.length??0;if(x)a(void 0);else if(b&&(l==="running"||F(l))){let v=de(b,c.current);v!==b&&(b=v,a(v));}s("streaming");let R=e.includes("?")?"&":"?",w=async()=>{let v=await fetch(`${e}${R}startIndex=0`,{credentials:"include",signal:h.signal});if(v.status===404)return "unavailable";if(!v.ok||!v.body)throw new Error(`Failed to fetch the run stream (status ${v.status.toString()})`);let P=false,T=parseJsonEventStream({schema:uiMessageChunkSchema,stream:v.body}).pipeThrough(new TransformStream({transform:(D,tt)=>{if(!D.success)throw D.error;D.value.type==="finish"&&(P=true),tt.enqueue(D.value);}})),S=readUIMessageStream({onError:D=>{h.signal.aborted||console.error("Run stream chunk error",D);},stream:T}),$=null,se=d===0,ke=(D=false)=>{h.signal.aborted||!b||!se&&(se=D||b.parts.length>=d,!se)||a({...b});};try{for await(let D of S){if(h.signal.aborted)break;b=D,$===null&&($=window.setTimeout(()=>{$=null,ke();},Ze));}}finally{$!==null&&(window.clearTimeout($),$=null),ke(true);}return P?"finished":"incomplete"},A=async()=>{let v=0;for(;!h.signal.aborted;){v>0&&await na(Ke);try{let P=await w();if(h.signal.aborted)return;if(P==="unavailable"){s("unavailable");return}if(P==="finished"&&F(l)){s("finished");return}if(F(l)){s("finished");return}if(et({latestMessage:b,recordStatus:l,suppressApprovalPause:k.current})){s("paused");return}if(!(l==="running"||k.current)&&v>=Fe-1){s("error");return}}catch(P){if(h.signal.aborted||ra(P))return;if(console.error("Run stream error",P),F(l)){s("finished");return}if(!(l==="running"||k.current)&&v>=Fe-1){s("error");return}}v+=1;}},H=window.setTimeout(()=>{A();},0);return ()=>{window.clearTimeout(H),h.abort("Run replay unmounted");}},[l,u,e]),{message:n,status:r}}function pn(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 ua(e){let t=e.trim();return t?t.split(`
5
- `).every(n=>/^`{3,}[\w-]*$/.test(n.trim())):false}function fn({api:e,part:t,partIndex:n,parts:a}){if(ae(t))return null;if(V(t.type)){let r=te(t);return r?jsx(ca,{message:r}):null}if(t.type==="text")return ua(t.text)&&a.some(s=>s.type===ce)?null:jsx(da,{part:t});if(t.type==="data-generating-files")return jsx(ga,{message:g(t)});if(t.type==="data-run-artifact")return jsx(ya,{api:e,message:g(t)});if(t.type==="data-tool-delivery")return jsx(va,{message:g(t)});if(t.type==="data-run-summary")return jsx(ba,{message:g(t)});if(t.type==="data-subtask"){let r=g(t),s=r.status==="running"?`Running "${r.title}"`:r.status==="done"?`Completed "${r.title}"${typeof r.stepsUsed=="number"?` in ${r.stepsUsed.toString()} steps`:""}`:`"${r.title}" failed: ${r.error?.message??"unknown error"}`;return jsxs(I,{children:[jsxs(j,{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(re,{isError:r.status==="error",loading:r.status==="running"})}),jsx("span",{className:"fk:text-xs",children:s}),r.resultPreview?jsx("p",{className:"fk:mt-1 fk:text-xs fk:text-muted-foreground",children:r.resultPreview}):null]})]})}if(t.type==="data-context-compaction"){let r=g(t);return jsxs("p",{className:"fk:text-xs fk:text-muted-foreground",children:["Earlier messages (",r.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 r=g(t);return jsx(Pa,{pluginId:r.pluginId})}if(t.type==="data-suggested-prompt")return null;if(t.type==="data-turn-error"){let r=g(t);return jsxs(I,{className:"fk:border-red-700/40",children:[jsxs(j,{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:r.message})]})}if(t.type==="data-mutation-approval"){let r=g(t);return le(r)?jsx(xa,{message:r}):jsx(ha,{api:e,message:r})}return t.type==="data-bulk-graphql-action"?jsx(Ra,{message:g(t)}):t.type===ce?a.slice(n+1).find(s=>s.type===ce)?null:jsx(Zt,{parts:a}):t.type.startsWith("data-")?jsx(Sa,{part:t}):null}function da({part:e}){return jsx(ub,{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 ca({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 pa=1e3;function fa({text:e}){let t=useRef(typeof performance>"u"?0:performance.now()),n=()=>-(((typeof performance>"u"?0:performance.now())-t.current)%pa),[a,r]=useState({current:e,currentDelayMs:0,key:0,previous:null,previousDelayMs:0});return useEffect(()=>{r(s=>s.current===e?s:{current:e,currentDelayMs:n(),key:s.key+1,previous:s.current,previousDelayMs:s.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 ma=1e3;function ka(e,t){let n=ma,[a,r]=useState(e),s=useRef(Date.now()),l=useRef(e);return l.current=e,useEffect(()=>{if(e===a)return;let u=Math.max(0,n-(Date.now()-s.current)),c=window.setTimeout(()=>{s.current=Date.now(),r(l.current);},u);return ()=>{window.clearTimeout(c);}},[a,e,n]),a}function mn({label:e,visible:t}){let n=ka(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(fa,{text:n})})}function I({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 j({children:e}){return jsx("div",{className:"fk:flex fk:items-center fk:gap-2 fk:font-medium fk:text-muted-foreground",children:e})}function re({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 me({error:e,icon:t,loading:n,message:a,title:r}){return jsxs(I,{children:[jsxs(j,{children:[t,r]}),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(re,{isError:!!e,loading:n})}),jsx("span",{className:"fk:text-xs",children:a})]})]})}function ga({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(I,{children:[jsxs(j,{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((r,s)=>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:r})]},`${r}-${s.toString()}`)),typeof a=="string"?jsxs("div",{className:"fk:flex fk:items-center fk:gap-2",children:[jsx(re,{isError:e.status==="error",loading:e.status!=="error"}),jsx("span",{children:e.status==="error"?e.error?.message??a:a})]}):null]})]})}function ya({api:e,message:t}){let n=t.status==="done"&&t.artifactId,a=n?e.getArtifactUrl(t.artifactId??""):"",r=n?e.getArtifactUrl(t.artifactId??"",{download:true}):"",s=wa(t.sizeBytes);return jsxs(I,{children:[jsxs(j,{children:[jsx(FileTextIcon,{className:"fk:size-3.5"}),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(re,{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"&&[Aa(t),s].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:[jsx(d$1,{asChild:true,size:"sm",variant:"outline",children:jsx("a",{href:a,rel:"noreferrer",target:"_blank",children:"Preview"})}),jsx(d$1,{asChild:true,size:"sm",variant:"outline",children:jsxs("a",{href:r,children:[jsx(DownloadIcon,{className:"fk:size-3"}),"Download"]})}),t.url?jsx(d$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 va({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(me,{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 ba({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(I,{className:e.status==="failed"?"fk:border-red-700/40":"fk:border-green-700/40",children:[jsxs(j,{children:[t,jsx("span",{children:n})]}),e.status==="failed"?jsx("p",{className:"fk:whitespace-pre-wrap fk:text-xs",children:e.summary}):null]})}function ha({api:e,message:t}){let{projectId:n}=ea(),a=useContext(ta),r=useContext(aa),s=useRef(void 0),{data:l,error:u,isValidating:c,mutate:k}=Wt(n?g$2(n).approval(t.approvalId):null,f,{refreshInterval:d=>t.status!=="pending"||d?.approval?.status&&d.approval.status!=="pending"?0:Ke}),m=l?.approval?.status,y=(m??t.status)==="pending",x=l?.approval?.kind==="schema"&&l.approval.status==="approved";useEffect(()=>{!x||!n||Z({approvalId:t.approvalId,approvalUrl:g$2(n).approval(t.approvalId),projectId:n});},[x,t.approvalId,n]),useEffect(()=>{k();},[t.status,k]),useEffect(()=>{let d=s.current;s.current=m,!(t.status!=="pending"||!m||m==="pending")&&d==="pending"&&a?.onApprovalDecided(l?.approval?.id??t.approvalId,m);},[m,l?.approval?.id,t.approvalId,t.status,a]);function h(d){d.status!=="pending"&&(s.current=d.status),k(),a?.onApprovalDecided(d.id,d.status);}let b;if(l?.approval)b=jsx(ze,{api:e,approval:l.approval,chat:r,onDecided:h},l.approval.status);else if(u&&!c){let d=u instanceof Error&&u.message?u.message:"Request failed";b=jsxs("div",{className:"fk:space-y-2",children:[jsxs("p",{className:"fk:text-xs fk:text-destructive",children:["Failed to load proposal ",t.operationsSummary,": ",d]}),jsx(d$1,{size:"sm",variant:"outline",onClick:()=>{k();},children:"Retry"})]});}else b=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(I,{children:[jsxs(j,{children:[r?jsx(ShieldIcon,{className:"fk:size-3.5"}):jsx(DatabaseZapIcon,{className:"fk:size-3.5"}),r?"Approval request":"Mutation approval",y?jsx(LoaderCircle,{className:"fk:ml-1 fk:size-3.5 fk:animate-spin"}):null]}),jsx("div",{className:"fk:mt-2",children:b}),t.status==="error"&&t.error?jsx("p",{className:"fk:mt-2 fk:text-xs fk:text-destructive",children:t.error.message}):null]})}function xa({message:e}){let t=e.operationsSummary.replace(/^Call /,"");return jsx(me,{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 Ra({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(me,{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 Sa({part:e}){return jsxs(I,{className:"fk:bg-muted/30",children:[jsxs(j,{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 wa(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 Aa(e){return e.kind==="pdf"?"PDF artifact":e.kind==="html"?"HTML artifact":"Artifact"}function Pa({pluginId:e}){let{pathname:t}=useLocation(),[n]=t.split("/ai/");return jsxs(I,{children:[jsxs("p",{className:"fk:text-sm",children:["Connect ",e," to use it in this conversation."]}),jsx(d$1,{asChild:true,size:"sm",variant:"outline",children:jsxs(Link,{to:`${n}/ai/plugins/${encodeURIComponent(e)}`,children:["Connect ",e]})})]})}export{Ne as a,mt as b,Ja as c,ae as d,Ct as e,ue as f,qe as g,It as h,ea as i,Ke as j,ta as k,aa as l,dn as m,F as n,cn as o,pn as p,fn as q,ca as r,mn as s,ha as t};//# sourceMappingURL=chunk-BURKG2UC.js.map
6
- //# sourceMappingURL=chunk-BURKG2UC.js.map