@flexkit/studio 0.2.5 → 0.2.6

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 (59) hide show
  1. package/dist/activity-nav-button-SIJTREEC.js +2 -0
  2. package/dist/{activity-nav-button-AESIPODJ.js.map → activity-nav-button-SIJTREEC.js.map} +1 -1
  3. package/dist/chat-page-YALTEYVY.js +4 -0
  4. package/dist/chat-page-YALTEYVY.js.map +1 -0
  5. package/dist/chunk-3GUFJ6KL.js +2 -0
  6. package/dist/chunk-3GUFJ6KL.js.map +1 -0
  7. package/dist/{chunk-XWC47CBM.js → chunk-52DYWQBF.js} +2 -2
  8. package/dist/{chunk-XWC47CBM.js.map → chunk-52DYWQBF.js.map} +1 -1
  9. package/dist/{chunk-26UJ2WUB.js → chunk-5C2GT7MI.js} +2 -2
  10. package/dist/{chunk-26UJ2WUB.js.map → chunk-5C2GT7MI.js.map} +1 -1
  11. package/dist/{chunk-EUGE3XWF.js → chunk-7KCER62Q.js} +3 -3
  12. package/dist/{chunk-EUGE3XWF.js.map → chunk-7KCER62Q.js.map} +1 -1
  13. package/dist/{chunk-UULO2DWJ.js → chunk-7UZJLTR2.js} +2 -2
  14. package/dist/{chunk-UULO2DWJ.js.map → chunk-7UZJLTR2.js.map} +1 -1
  15. package/dist/{chunk-UM74MG43.js → chunk-DTO6OBC7.js} +2 -2
  16. package/dist/{chunk-UM74MG43.js.map → chunk-DTO6OBC7.js.map} +1 -1
  17. package/dist/{chunk-NDM2RAQE.js → chunk-GJQQZFER.js} +3 -3
  18. package/dist/{chunk-NDM2RAQE.js.map → chunk-GJQQZFER.js.map} +1 -1
  19. package/dist/chunk-JK3IOLJZ.js +3 -0
  20. package/dist/chunk-JK3IOLJZ.js.map +1 -0
  21. package/dist/{chunk-Y7ZSQPKF.js → chunk-MYUV2B6S.js} +3 -3
  22. package/dist/{chunk-Y7ZSQPKF.js.map → chunk-MYUV2B6S.js.map} +1 -1
  23. package/dist/chunk-W2SMMUXR.js +8 -0
  24. package/dist/chunk-W2SMMUXR.js.map +1 -0
  25. package/dist/{chunk-PWQPA2QL.js → chunk-XAGCVHPZ.js} +2 -2
  26. package/dist/{chunk-PWQPA2QL.js.map → chunk-XAGCVHPZ.js.map} +1 -1
  27. package/dist/index.css +6 -0
  28. package/dist/index.d.ts +3 -1
  29. package/dist/index.js +1 -1
  30. package/dist/{list-WETJWRMH.js → list-CLP77KU3.js} +2 -2
  31. package/dist/{list-WETJWRMH.js.map → list-CLP77KU3.js.map} +1 -1
  32. package/dist/pages-4NDELS2U.js +3 -0
  33. package/dist/pages-4NDELS2U.js.map +1 -0
  34. package/dist/{plugin-pages-QLMZNHSK.js → plugin-pages-IHHXP7QL.js} +2 -2
  35. package/dist/{plugin-pages-QLMZNHSK.js.map → plugin-pages-IHHXP7QL.js.map} +1 -1
  36. package/dist/{root-R7URTGY7.js → root-4IOF2PC6.js} +2 -2
  37. package/dist/{root-R7URTGY7.js.map → root-4IOF2PC6.js.map} +1 -1
  38. package/dist/{root-L4SMLNEV.js → root-ALGRTN7S.js} +3 -3
  39. package/dist/{root-L4SMLNEV.js.map → root-ALGRTN7S.js.map} +1 -1
  40. package/dist/{root-QN7KVPCD.js → root-N45KARKK.js} +2 -2
  41. package/dist/{root-QN7KVPCD.js.map → root-N45KARKK.js.map} +1 -1
  42. package/dist/{root-N6PIMO2T.js → root-SG2H2IAC.js} +3 -3
  43. package/dist/{root-N6PIMO2T.js.map → root-SG2H2IAC.js.map} +1 -1
  44. package/dist/{search-3LHBSNDF.js → search-2WY6JMGS.js} +2 -2
  45. package/dist/{search-3LHBSNDF.js.map → search-2WY6JMGS.js.map} +1 -1
  46. package/dist/{skills-pages-ZN4LII2R.js → skills-pages-ANAOWXPJ.js} +2 -2
  47. package/dist/{skills-pages-ZN4LII2R.js.map → skills-pages-ANAOWXPJ.js.map} +1 -1
  48. package/package.json +3 -3
  49. package/dist/activity-nav-button-AESIPODJ.js +0 -2
  50. package/dist/chat-page-EXKQ2EYM.js +0 -4
  51. package/dist/chat-page-EXKQ2EYM.js.map +0 -1
  52. package/dist/chunk-CKNFYN3O.js +0 -3
  53. package/dist/chunk-CKNFYN3O.js.map +0 -1
  54. package/dist/chunk-LP2JI25S.js +0 -2
  55. package/dist/chunk-LP2JI25S.js.map +0 -1
  56. package/dist/chunk-NGO6CTAU.js +0 -8
  57. package/dist/chunk-NGO6CTAU.js.map +0 -1
  58. package/dist/pages-PIZB3YDN.js +0 -3
  59. package/dist/pages-PIZB3YDN.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/apps/ai/agent/chat-history.ts","../src/apps/ai/agent/composer-draft.ts","../src/apps/ai/agent/follow-ups.ts","../src/apps/ai/agent/chat-page.tsx"],"names":["compareChatMessages","a","b","byTime","sortChatMessages","messages","message","mergeChatDetail","current","incoming","incomingIds","newest","retained","COMPOSER_DRAFT_STORAGE_PREFIX","defaultStorage","getComposerDraftKey","projectId","chatId","readComposerDraft","key","storage","writeComposerDraft","value","isActiveTurnStatus","status","isFollowUpStatus","splitLiveTurn","index","getFollowUpLabel","getDeliveredMidTurnMessageIds","ids","part","messageId","getNextQueuedMessage","getComposerAction","input","TITLE_POLL_TIMEOUT_MS","getChatDetailRefreshInterval","latestData","STREAM_RETRY_DELAY_MS","lastActivity","createFallbackChatDetail","modelId","timestamp","getSeedBaseDetail","createdChat","cachedDetail","appendTurnToDetail","detail","turn","turnIds","appendMessageToDetail","item","resolveSeededChatDetail","seeds","getTurnRecordStatus","UserBubble","attachments","label","text","textInput","usePromptInputController","copied","setCopied","useState","hasText","handleCopy","jsxs","jsx","MessageAttachments","CornerDownRightIcon","Tooltip","TooltipTrigger","Button","CheckIcon","CopyIcon","TooltipContent","PencilIcon","getSuggestedPrompt","parts","prompt","candidate","SuggestedPromptChip","PersistedPart","api","partIndex","ToolErrorLine","MessagePart","HistoryMessage","showSuggestion","getAttachmentsFromParts","isHiddenReplayPart","hasTurnErrorPart","suggestedPrompt","LiveTurn","onMidTurnDelivered","onStatusChange","onTurnUpdated","recordStatus","streamApi","resumeToken","setResumeToken","suppressApprovalPause","setSuppressApprovalPause","decidedApprovals","setDecidedApprovals","lastDecidedApprovalIdRef","useRef","streamMessage","useRunStream","rawMessages","useMemo","sessionMessages","useSessionMessages","onTurnUpdatedRef","onStatusChangeRef","replayActions","approvalId","decidedStatus","useEffect","deliveredKey","onMidTurnDeliveredRef","isAwaitingApproval","messageHasPendingMutationApproval","streamApprovalIds","getMutationApprovalIds","fallbackApproval","lastPart","contentIsStreaming","statusLabel","getLiveStatusLabel","statusVisible","showFallbackApproval","liveSuggestedPrompt","sessionMessage","RunReplayActionsContext","MutationApprovalPart","toMutationApprovalPartData","ComposerDraftSync","draftKey","setInput","activeKeyRef","useLayoutEffect","draft","ChatComposer","effort","modelKey","modelPending","models","onEffortChange","onError","onModelChange","onSend","onStop","placeholder","sending","streaming","uploads","useAttachmentUploads","submittingRef","selectableModels","model","getModelKey","selectedModel","findModelByKey","effortOptions","getEffortOptions","effectiveEffort","coerceEffort","hasDraft","action","canSubmit","PromptInput","ATTACHMENT_ACCEPT","ATTACHMENT_MAX_BYTES","ATTACHMENTS_MAX_PER_MESSAGE","error","trimmed","sentAttachments","file","PromptInputHeader","ComposerAttachments","PromptInputBody","PromptInputTextarea","PromptInputFooter","PromptInputTools","PromptInputActionMenu","PromptInputActionMenuTrigger","PromptInputActionMenuContent","PromptInputActionAddAttachments","PromptInputSelect","PromptInputSelectTrigger","PromptInputSelectValue","PromptInputSelectContent","PromptInputSelectItem","option","SpeechInput","audioBlob","signal","transcript","appendDictatedText","PromptInputSubmit","EMPTY_CHAT_HISTORY","QUEUED_START_RETRY_MS","ChatConversation","pendingFollowUp","pendingMessage","resolveDetail","rawDetail","mutate","useSWR","paths","fetcher","data","historyState","setHistoryState","history","activeChatRef","updateHistory","forChatId","patch","base","windowRef","windowMessages","previous","next","nextIds","dropped","currentIds","detailRef","priorStatus","signature","latest","loadOlder","cursor","requestChatId","result","followUpMessages","earlierMessages","liveMessage","liveDeliveredIds","setLiveDeliveredIds","deliveredIds","id","waitingFollowUps","historyMessages","nextQueuedId","queuedStartAttempt","setQueuedStartAttempt","queuedStartInFlightRef","cancelled","retry","attempt","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","writeLastAgentModel","selection","EmptyConversation","isLoading","greeting","AgentChatPage","useProjectApi","currentProject","projectSummaries","useConfig","useParams","navigate","useNavigate","agentBase","useAgentBasePath","globalMutate","useSWRConfig","toolsData","rawChatDetail","seededDetailRef","chatDetail","selectedModelKey","setSelectedModelKey","selectedEffort","setSelectedEffort","autoPickedOnModelIdRef","rememberedModel","setRememberedModel","setSending","sendingRef","setPendingMessage","visiblePendingMessage","setPendingFollowUp","visiblePendingFollowUp","sendError","setSendError","chatModelId","awaitingChatModel","chatSelection","parseModelSelection","defaultModelKey","lastUsed","formatModelSelection","AUTO_MODEL_KEY","rememberModel","handleModelChange","nextModelKey","handleEffortChange","nextEffort","chatApi","chatProjectId","projectName","project","isNewChat","turnInProgress","sendFollowUp","targetChatId","handleSend","queuedBeforeThis","started","chat","handleStop","PromptInputProvider","SidebarTrigger","Separator","cn","ChatApprovalContext"],"mappings":"u+BAGO,SAASA,EAAAA,CAAoBC,CAAAA,CAAqBC,EAA6B,CACpF,IAAMC,CAAAA,CAAS,IAAA,CAAK,MAAMF,CAAAA,CAAE,SAAS,CAAA,CAAI,IAAA,CAAK,MAAMC,CAAAA,CAAE,SAAS,CAAA,CAE/D,OAAI,OAAO,QAAA,CAASC,CAAM,GAAKA,CAAAA,GAAW,CAAA,CACjCA,EAKLF,CAAAA,CAAE,SAAA,GAAcC,CAAAA,CAAE,SAAA,CACbD,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ACF,GACF,CAEJ","file":"chat-page-EXKQ2EYM.js","sourcesContent":["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","/**\n * Unsent composer text, kept per chat so leaving a chat (or reloading the\n * Studio) and coming back restores what was typed.\n */\n\nexport const COMPOSER_DRAFT_STORAGE_PREFIX = 'flexkit:agent:draft:';\n\n/** The draft id of the New chat page, which has no chat id yet. */\nexport const NEW_CHAT_DRAFT_ID = 'new';\n\nexport type DraftStorage = Pick<Storage, 'getItem' | 'removeItem' | 'setItem'>;\n\nfunction defaultStorage(): DraftStorage | null {\n return typeof localStorage === 'undefined' ? null : localStorage;\n}\n\nexport function getComposerDraftKey(projectId: string, chatId: string | undefined): string {\n return `${COMPOSER_DRAFT_STORAGE_PREFIX}${projectId}:${chatId ?? NEW_CHAT_DRAFT_ID}`;\n}\n\nexport function readComposerDraft(key: string, storage: DraftStorage | null = defaultStorage()): string {\n try {\n return storage?.getItem(key) ?? '';\n } catch {\n return '';\n }\n}\n\n/** Stores the draft, or forgets it once the composer is blank again (e.g. after a send). */\nexport function writeComposerDraft(key: string, value: string, storage: DraftStorage | null = defaultStorage()): void {\n try {\n if (value.trim().length === 0) {\n storage?.removeItem(key);\n } else {\n storage?.setItem(key, value);\n }\n } catch {\n // Storage can be full or blocked (private mode); the draft then only lives in memory.\n }\n}\n","import type { AgentChatMessage, AgentChatMessageStatus } from '../types';\n\n/**\n * Pure helpers for messages sent while a turn runs. The composer stays open\n * during a turn; what the user sends then is stored at once and either\n * steers the running turn or waits as the next one.\n */\n\nexport function isActiveTurnStatus(status: AgentChatMessageStatus): boolean {\n return status === 'pending' || status === 'streaming' || status === 'awaiting_approval';\n}\n\nexport function isFollowUpStatus(status: AgentChatMessageStatus): status is 'queued' | 'steering' {\n return status === 'queued' || status === 'steering';\n}\n\nexport interface LiveTurnSplit {\n /** Messages sent after the live turn started: follow-ups waiting on it. */\n after: AgentChatMessage[];\n before: AgentChatMessage[];\n /** The assistant message still being produced, if any. */\n live: AgentChatMessage | null;\n}\n\n/**\n * Finds the running assistant turn. It is no longer necessarily the last\n * message: follow-ups the user sent meanwhile come after it.\n */\nexport function splitLiveTurn(messages: AgentChatMessage[]): LiveTurnSplit {\n for (let index = messages.length - 1; index >= 0; index--) {\n const message = messages[index]!;\n\n if (message.role !== 'assistant') {\n continue;\n }\n\n if (!isActiveTurnStatus(message.status)) {\n break;\n }\n\n return { after: messages.slice(index + 1), before: messages.slice(0, index), live: message };\n }\n\n return { after: [], before: messages, live: null };\n}\n\n/** The line shown under a follow-up bubble while it waits; null once it was sent normally. */\nexport function getFollowUpLabel(status: AgentChatMessageStatus): string | null {\n if (status === 'steering') {\n return 'Picked up at the next step';\n }\n\n if (status === 'queued') {\n return 'Sends when this turn ends';\n }\n\n return null;\n}\n\n/**\n * Messages the user sent mid-turn that the agent has received: the reply\n * shows them where they landed, so their own rows are not shown again.\n */\nexport function getDeliveredMidTurnMessageIds(messages: AgentChatMessage[]): Set<string> {\n const ids = new Set<string>();\n\n for (const message of messages) {\n if (message.role !== 'assistant' || !Array.isArray(message.parts)) {\n continue;\n }\n\n for (const part of message.parts) {\n const messageId = part.type === 'data-mid-turn-message' ? (part.data as { messageId?: unknown } | undefined)?.messageId : null;\n\n if (typeof messageId === 'string') {\n ids.add(messageId);\n }\n }\n }\n\n return ids;\n}\n\n/** The oldest queued follow-up: the one that starts the next turn. */\nexport function getNextQueuedMessage(messages: AgentChatMessage[]): AgentChatMessage | null {\n return messages.find((message) => message.role === 'user' && message.status === 'queued') ?? null;\n}\n\n/**\n * What the composer's main button does: the turn is stopped while nothing is\n * typed; as soon as there is a draft, the same button sends it, during a turn\n * as a follow-up.\n */\nexport function getComposerAction(input: { hasDraft: boolean; streaming: boolean }): 'send' | 'stop' {\n return input.streaming && !input.hasDraft ? 'stop' : 'send';\n}\n","import type { JSX } from 'react';\nimport { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';\nimport { CheckIcon, CopyIcon, CornerDownRightIcon, LoaderCircle, PencilIcon } from 'lucide-react';\nimport { 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 { useConfig } from '../../../core/config/config-context';\nimport { cn } from '../../../ui/lib/utils';\nimport { useAgentBasePath } from './chat-list';\nimport { getComposerDraftKey, readComposerDraft, writeComposerDraft } from './composer-draft';\nimport { appendDictatedText } from './dictation';\nimport {\n getComposerAction,\n getDeliveredMidTurnMessageIds,\n getFollowUpLabel,\n getNextQueuedMessage,\n isFollowUpStatus,\n splitLiveTurn,\n} from './follow-ups';\nimport {\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 getChatDetailRefreshInterval(latestData: AgentChatDetail | undefined): number {\n if (!latestData) {\n return 0;\n }\n\n // A live turn, or a follow-up waiting to start the next one, keeps polling.\n if (splitLiveTurn(latestData.messages).live || getNextQueuedMessage(latestData.messages)) {\n return STREAM_RETRY_DELAY_MS;\n }\n\n const hasCompletedAssistant = latestData.messages.some(\n (message) => message.role === 'assistant' && message.status === 'complete'\n );\n\n if (!hasCompletedAssistant) {\n return 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 // Sorted: a turn started from a queued follow-up keeps that message's\n // place, and the assistant placeholder lands right behind it.\n return {\n ...detail,\n messages: sortChatMessages([\n ...detail.messages.filter((message) => !turnIds.has(message.id)),\n turn.userMessage,\n turn.assistantMessage,\n ]),\n };\n}\n\n/** Seeds a follow-up the user sent during a turn, so it shows before the next revalidation. */\nfunction appendMessageToDetail(detail: AgentChatDetail, message: AgentChatMessage): AgentChatDetail {\n return {\n ...detail,\n messages: sortChatMessages([...detail.messages.filter((item) => item.id !== message.id), message]),\n };\n}\n\nfunction resolveSeededChatDetail(\n seeds: { [chatId: string]: AgentChatDetail },\n chatId: string | undefined,\n detail: AgentChatDetail | undefined\n): AgentChatDetail | undefined {\n if (!chatId) {\n return detail;\n }\n\n return mergeChatDetail(seeds[chatId], detail);\n}\n\n/** Maps a chat turn status onto the record statuses the stream hook understands. */\nfunction getTurnRecordStatus(status: AgentChatMessageStatus): RunRecordStatus {\n if (status === 'awaiting_approval') {\n return 'awaiting_approval';\n }\n\n if (status === 'complete') {\n return 'success';\n }\n\n if (status === 'failed') {\n return 'failed';\n }\n\n return 'running';\n}\n\nfunction UserBubble({\n attachments = [],\n label,\n text,\n}: {\n attachments?: AgentChatAttachment[];\n /** Shown under a message sent during a turn, until it has been delivered. */\n label?: string | null;\n text: string;\n}): JSX.Element {\n const { textInput } = usePromptInputController();\n const [copied, setCopied] = useState(false);\n const hasText = text.trim().length > 0;\n\n async function handleCopy(): Promise<void> {\n await navigator.clipboard.writeText(text);\n setCopied(true);\n setTimeout(() => setCopied(false), 1500);\n }\n\n return (\n <div className=\"fk:group fk:ml-auto fk:flex fk:w-fit fk:max-w-[70%] fk:flex-col fk:items-end fk:gap-1\">\n <MessageAttachments attachments={attachments} />\n {hasText ? (\n <div className=\"fk:whitespace-pre-wrap fk:rounded-xl fk:bg-muted fk:dark:bg-white/20 fk:px-3.5 fk:py-2 fk:text-base fk:corner-squircle\">\n {text}\n </div>\n ) : null}\n {label ? (\n <span className=\"fk:inline-flex fk:items-center fk:gap-1 fk:text-xs fk:text-muted-foreground\">\n <CornerDownRightIcon className=\"fk:size-3 fk:shrink-0\" />\n {label}\n </span>\n ) : null}\n <div\n className={\n hasText ? 'fk:flex fk:gap-0.5 fk:opacity-0 fk:transition-opacity fk:group-hover:opacity-100' : 'fk:hidden'\n }\n >\n <Tooltip>\n <TooltipTrigger asChild>\n <Button\n aria-label=\"Copy prompt\"\n className=\"fk:size-6 fk:text-muted-foreground\"\n size=\"icon\"\n variant=\"ghost\"\n onClick={() => void handleCopy()}\n >\n {copied ? <CheckIcon className=\"fk:size-3.5\" /> : <CopyIcon className=\"fk:size-3.5\" />}\n </Button>\n </TooltipTrigger>\n <TooltipContent>Copy</TooltipContent>\n </Tooltip>\n <Tooltip>\n <TooltipTrigger asChild>\n <Button\n aria-label=\"Edit prompt\"\n className=\"fk:size-6 fk:text-muted-foreground\"\n size=\"icon\"\n variant=\"ghost\"\n onClick={() => textInput.setInput(text)}\n >\n <PencilIcon className=\"fk:size-3.5\" />\n </Button>\n </TooltipTrigger>\n <TooltipContent>Edit</TooltipContent>\n </Tooltip>\n </div>\n </div>\n );\n}\n\n/** The follow-up the turn offered, if the model was confident enough to offer one. */\nfunction getSuggestedPrompt(parts: ReadonlyArray<{ data?: unknown; type: string }>): string | null {\n const part = parts.find((candidate) => candidate.type === 'data-suggested-prompt');\n const prompt = (part?.data as { prompt?: unknown } | undefined)?.prompt;\n\n return typeof prompt === 'string' && prompt.trim() ? prompt : null;\n}\n\n/**\n * One subtle chip under the latest reply. Clicking fills the composer and\n * nothing more: the user edits or sends it.\n */\nfunction SuggestedPromptChip({ prompt }: { prompt: string }): JSX.Element {\n const { textInput } = usePromptInputController();\n\n return (\n <div className=\"fk:flex fk:justify-start\">\n <button\n className=\"fk:inline-flex fk:max-w-full fk:items-center fk:gap-1.5 fk:rounded-full fk:border fk:border-border/70 fk:bg-muted/40 fk:px-3 fk:py-1.5 fk:text-left fk:text-sm fk:text-muted-foreground fk:transition-colors fk:hover:border-border fk:hover:bg-muted fk:hover:ext-foreground fk:corner-squircle\"\n title=\"Use as your next message\"\n type=\"button\"\n onClick={() => textInput.setInput(prompt)}\n >\n <CornerDownRightIcon className=\"fk:size-3 fk:shrink-0\" />\n <span className=\"fk:truncate\">{prompt}</span>\n </button>\n </div>\n );\n}\n\n/**\n * Finished turns are stored as UIMessage-shaped parts. Reuse the live replay\n * renderer for `data-*` events (approvals, turn errors, tool status, artifacts,\n * specs) so history matches the in-flight `MessagePart` tree. `tool-*` parts\n * come from ModelMessage reconstruction and are ignored by `MessagePart`.\n */\nfunction PersistedPart({\n api,\n part,\n partIndex,\n parts,\n}: {\n api: ApiClient;\n part: AgentChatPart;\n partIndex: number;\n parts: AgentChatPart[];\n}): JSX.Element | null {\n // The live stream never showed a card for these calls, so history does not\n // either. Only a failed call leaves a trace.\n if (part.type.startsWith('tool-')) {\n return part.state === 'output-error' ? <ToolErrorLine message={part.errorText ?? 'The tool call failed.'} /> : null;\n }\n\n return (\n <MessagePart\n api={api}\n part={part as ReplayMessagePart}\n partIndex={partIndex}\n parts={parts as ReplayMessagePart[]}\n />\n );\n}\n\nfunction HistoryMessage({\n api,\n message,\n showSuggestion = false,\n}: {\n api: ApiClient;\n message: AgentChatMessage;\n /** Only the latest reply offers its follow-up; older ones would compete with it. */\n showSuggestion?: boolean;\n}): JSX.Element | null {\n if (message.role === 'user') {\n return (\n <UserBubble\n attachments={getAttachmentsFromParts(message.parts)}\n label={getFollowUpLabel(message.status)}\n text={message.textContent}\n />\n );\n }\n\n // Reasoning stays persisted for debugging, but is never displayed in chat.\n // Rolling-status tool parts are only meaningful while the call is in flight.\n const parts = (Array.isArray(message.parts) ? message.parts : []).filter(\n (part) =>\n !isHiddenReplayPart(part as ReplayMessagePart) &&\n !(part.type.startsWith('tool-') && part.state !== 'output-error')\n );\n const hasTurnErrorPart = parts.some((part) => part.type === 'data-turn-error');\n const suggestedPrompt = showSuggestion && !message.error ? getSuggestedPrompt(parts) : null;\n\n if (parts.length === 0 && !message.error) {\n return null;\n }\n\n return (\n <div className=\"fk:w-full fk:min-w-0 fk:space-y-8\">\n {parts.map((part, index) => (\n <PersistedPart\n api={api}\n key={part.toolCallId ?? `${message.id}-${index.toString()}`}\n part={part}\n partIndex={index}\n parts={parts}\n />\n ))}\n {message.error && !hasTurnErrorPart ? <ToolErrorLine message={message.error} /> : null}\n {suggestedPrompt ? <SuggestedPromptChip prompt={suggestedPrompt} /> : null}\n </div>\n );\n}\n\n/**\n * Streams the in-flight assistant turn from the workflow run stream, with the\n * same approval pause/resume handling as the automation run replay.\n */\nfunction LiveTurn({\n api,\n chatId,\n detail,\n message,\n onMidTurnDelivered,\n onStatusChange,\n onTurnUpdated,\n}: {\n api: ApiClient;\n chatId: string;\n detail: AgentChatDetail;\n message: AgentChatMessage;\n /** Ids of the follow-ups the stream has shown inline so far. */\n onMidTurnDelivered: (_ids: string[]) => void;\n onStatusChange: (_status: TurnStatus) => void;\n onTurnUpdated: () => void;\n}): 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 // A follow-up the stream renders inline must leave the waiting list at once.\n const deliveredKey = (streamMessage?.parts ?? [])\n .filter((part) => part.type === 'data-mid-turn-message')\n .map((part) => String((part as { data?: { messageId?: unknown } }).data?.messageId ?? ''))\n .join('\\n');\n const onMidTurnDeliveredRef = useRef(onMidTurnDelivered);\n onMidTurnDeliveredRef.current = onMidTurnDelivered;\n\n useEffect(() => {\n if (deliveredKey) {\n onMidTurnDeliveredRef.current(deliveredKey.split('\\n'));\n }\n }, [deliveredKey]);\n\n // Prefer the turn record over a stale pending stream part once execution\n // has resumed (`streaming`). Keeping the previous replay on reconnect can\n // leave a pending data-mutation-approval part in memory until rebuild.\n const isAwaitingApproval =\n !suppressApprovalPause &&\n message.status !== 'streaming' &&\n (message.status === 'awaiting_approval' || 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\n/**\n * Keeps the composer text in sync with the stored draft of the chat it is\n * showing: every change is stored under the chat's key, and when the page\n * moves to another chat (or is first shown) that chat's draft replaces the\n * text. The outgoing chat's draft was stored on its last change, so a switch\n * only has to load. A single effect handles both so the stale text of the\n * previous chat is never written under the new chat's key.\n */\nfunction ComposerDraftSync({ draftKey }: { draftKey: string }): null {\n const { textInput } = usePromptInputController();\n const { setInput, value } = textInput;\n const activeKeyRef = useRef<string | null>(null);\n\n useLayoutEffect(() => {\n if (activeKeyRef.current === draftKey) {\n writeComposerDraft(draftKey, value);\n\n return;\n }\n\n activeKeyRef.current = draftKey;\n const draft = readComposerDraft(draftKey);\n\n if (draft !== value) {\n setInput(draft);\n }\n }, [draftKey, setInput, value]);\n\n return null;\n}\n\nfunction ChatComposer({\n api,\n effort,\n modelKey,\n modelPending,\n models,\n onEffortChange,\n onError,\n onModelChange,\n onSend,\n onStop,\n placeholder,\n sending,\n streaming,\n}: {\n api: ApiClient;\n effort: string | null;\n modelKey: string | null;\n modelPending: boolean;\n models: AutomationTools['models'];\n onEffortChange: (_effort: string) => void;\n onError: (_message: string | null) => void;\n onModelChange: (_modelKey: string) => void;\n onSend: (_text: string, _attachments: AgentChatAttachment[]) => Promise<void>;\n onStop: () => Promise<void>;\n placeholder: string;\n sending: boolean;\n streaming: boolean;\n}): JSX.Element {\n const { attachments, textInput } = usePromptInputController();\n const uploads = useAttachmentUploads(api, onError);\n // `sending` only flips on the next render, so track the in-flight send\n // synchronously to reject a duplicate submit before it clears the text.\n const submittingRef = useRef(false);\n const selectableModels = models.filter((model) => !model.deprecated || getModelKey(model) === modelKey);\n const selectedModel = findModelByKey(models, modelKey);\n const effortOptions = getEffortOptions(selectedModel);\n const effectiveEffort = coerceEffort(selectedModel, effort);\n const hasDraft = textInput.value.trim().length > 0 || attachments.files.length > 0;\n // The composer stays open during a turn: with nothing typed the button\n // stops the turn, with a draft it sends it as a follow-up.\n const action = getComposerAction({ hasDraft, streaming });\n const canSubmit = hasDraft && !uploads.isUploading && !sending && !modelPending;\n\n return (\n <PromptInput\n accept={ATTACHMENT_ACCEPT}\n className=\"fk:mx-auto fk:max-w-4xl\"\n maxFileSize={ATTACHMENT_MAX_BYTES}\n maxFiles={ATTACHMENTS_MAX_PER_MESSAGE}\n multiple\n onError={(error) => onError(error.message)}\n onSubmit={({ text }) => {\n const trimmed = text?.trim() ?? '';\n const sentAttachments = uploads.getUploaded(attachments.files.map((file) => file.id));\n\n // PromptInput clears the text and attachments whenever onSubmit returns\n // without throwing, so a blocked submit must reject to keep the draft.\n if (\n (!trimmed && sentAttachments.length === 0) ||\n uploads.isUploading ||\n sending ||\n submittingRef.current ||\n modelPending\n ) {\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={sending} placeholder={placeholder} />\n </PromptInputBody>\n <PromptInputFooter>\n <PromptInputTools>\n <PromptInputActionMenu>\n <PromptInputActionMenuTrigger\n aria-label=\"Add attachments\"\n className=\"fk:border-0 fk:bg-border fk:corner-round\"\n disabled={sending}\n tooltip=\"Add photos or files\"\n />\n <PromptInputActionMenuContent>\n <PromptInputActionAddAttachments />\n </PromptInputActionMenuContent>\n </PromptInputActionMenu>\n {selectableModels.length > 0 ? (\n <PromptInputSelect value={modelKey ?? undefined} onValueChange={onModelChange}>\n <PromptInputSelectTrigger aria-label=\"Model\" className=\"fk:min-w-44\">\n <PromptInputSelectValue placeholder=\"Model\" />\n </PromptInputSelectTrigger>\n <PromptInputSelectContent>\n {selectableModels.map((model) => (\n <PromptInputSelectItem key={getModelKey(model)} value={getModelKey(model)}>\n {model.name}\n </PromptInputSelectItem>\n ))}\n </PromptInputSelectContent>\n </PromptInputSelect>\n ) : null}\n {effortOptions.length > 1 && effectiveEffort ? (\n <PromptInputSelect value={effectiveEffort} onValueChange={onEffortChange}>\n <PromptInputSelectTrigger aria-label=\"Reasoning effort\" className=\"fk:min-w-28\">\n <PromptInputSelectValue placeholder=\"Effort\" />\n </PromptInputSelectTrigger>\n <PromptInputSelectContent>\n {effortOptions.map((option) => (\n <PromptInputSelectItem key={option.value} value={option.value}>\n {option.label}\n </PromptInputSelectItem>\n ))}\n </PromptInputSelectContent>\n </PromptInputSelect>\n ) : null}\n </PromptInputTools>\n <div className=\"fk:flex fk:items-center fk:gap-3\">\n <SpeechInput\n disabled={sending}\n onAudioRecorded={async (audioBlob, signal) => {\n const { text } = await api.transcribeAgentAudio(audioBlob, signal);\n\n return text;\n }}\n onError={(error) => onError(error.message)}\n onTranscriptionChange={(transcript) => {\n onError(null);\n textInput.setInput(appendDictatedText(textInput.value, transcript));\n }}\n />\n <PromptInputSubmit\n className=\"fk:corner-round\"\n disabled={action === 'stop' ? false : !canSubmit}\n status={action === 'stop' ? 'streaming' : undefined}\n onStop={() => void onStop()}\n />\n </div>\n </PromptInputFooter>\n </PromptInput>\n );\n}\n\ninterface PendingMessage {\n attachments: AgentChatAttachment[];\n text: string;\n}\n\n/** Pages loaded before the latest one, for a single chat. */\ninterface ChatHistoryState {\n chatId: string | null;\n error: string | null;\n loading: boolean;\n older: AgentChatMessage[];\n page: { cursor: string | null; hasMore: boolean } | null;\n}\n\nconst EMPTY_CHAT_HISTORY: ChatHistoryState = {\n chatId: null,\n error: null,\n loading: false,\n older: [],\n page: null,\n};\n\n/** Retry a queued follow-up's start no sooner than this after a failed attempt (the turn was still running). */\nconst QUEUED_START_RETRY_MS = 3_000;\n\nfunction ChatConversation({\n api,\n chatId,\n projectId,\n pendingFollowUp,\n pendingMessage,\n resolveDetail,\n}: {\n api: ApiClient;\n /** Null while the first message of a new chat is being sent. */\n chatId: string | null;\n projectId: string;\n /** A message sent during the live turn, until the platform has stored it. */\n pendingFollowUp?: PendingMessage;\n pendingMessage?: PendingMessage;\n 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 // The status reports the latest reply; a follow-up sent during the turn is newer than it.\n const latest = current ? [...current.messages].reverse().find((message) => message.role === 'assistant') : undefined;\n if (\n (previous && previous !== signature) ||\n (latest &&\n status.latestMessage &&\n (latest.id !== status.latestMessage.id ||\n latest.status !== status.latestMessage.status ||\n latest.workflowRunId !== status.latestMessage.workflowRunId ||\n current?.chat.updatedAt !== status.chat.updatedAt))\n )\n void mutate();\n },\n });\n const loadOlder = async () => {\n const cursor = history.page?.cursor ?? data?.nextCursor;\n if (!chatId || !cursor || history.loading) return;\n const requestChatId = chatId;\n updateHistory(requestChatId, () => ({ error: null, loading: true }));\n try {\n const result = await fetcher<AgentChatDetail>(\n `${paths(projectId).agentChat(requestChatId)}?before=${encodeURIComponent(cursor)}`\n );\n updateHistory(requestChatId, (current) => ({\n loading: false,\n older: sortChatMessages([...result.messages, ...current.older]),\n page: { cursor: result.nextCursor ?? null, hasMore: result.hasMore ?? false },\n }));\n } catch {\n updateHistory(requestChatId, () => ({ error: 'Could not load earlier messages. Try again.', loading: false }));\n }\n };\n // Follow-ups sent during the turn come after the live assistant message.\n // Once the agent has received one, the reply shows it where it landed, so\n // only the ones still waiting are listed here and delivered rows are\n // dropped from the history.\n const { after: followUpMessages, before: earlierMessages, live: liveMessage } = splitLiveTurn(messages);\n // Ids the live stream already renders inline; the rows catch up on the next refresh.\n const [liveDeliveredIds, setLiveDeliveredIds] = useState<{ messageId: string; ids: string[] }>({ ids: [], messageId: '' });\n const deliveredIds = getDeliveredMidTurnMessageIds(messages);\n\n for (const id of liveMessage && liveDeliveredIds.messageId === liveMessage.id ? liveDeliveredIds.ids : []) {\n deliveredIds.add(id);\n }\n\n const waitingFollowUps = followUpMessages.filter(\n (message) => isFollowUpStatus(message.status) && !deliveredIds.has(message.id)\n );\n const historyMessages = earlierMessages.filter((message) => !deliveredIds.has(message.id));\n // A queued follow-up starts the next turn as soon as the previous one has\n // ended, whether this tab sent it or it was found on load. A failed start\n // (the turn still wrapping up, a network blip) is retried after a pause.\n const nextQueued = !liveMessage && !pendingMessage ? getNextQueuedMessage(messages) : null;\n const nextQueuedId = nextQueued?.id ?? null;\n const [queuedStartAttempt, setQueuedStartAttempt] = useState(0);\n const queuedStartInFlightRef = useRef<string | null>(null);\n\n useEffect(() => {\n if (!chatId || !nextQueuedId || queuedStartInFlightRef.current === nextQueuedId) {\n return;\n }\n\n queuedStartInFlightRef.current = nextQueuedId;\n let cancelled = false;\n let retry: ReturnType<typeof setTimeout> | null = null;\n\n void api\n .startQueuedAgentChatMessage(chatId, nextQueuedId)\n .then(\n () => undefined,\n () => {\n retry = setTimeout(() => {\n if (!cancelled) {\n setQueuedStartAttempt((attempt) => attempt + 1);\n }\n }, QUEUED_START_RETRY_MS);\n }\n )\n .finally(() => {\n queuedStartInFlightRef.current = null;\n void mutate();\n });\n\n return () => {\n cancelled = true;\n\n if (retry) {\n clearTimeout(retry);\n }\n };\n }, [api, chatId, mutate, nextQueuedId, queuedStartAttempt]);\n // Reported by LiveTurn; owned here so the status line keeps one stable slot\n // from \"Sending\" (no turn yet) through the live turn, rolling between labels\n // instead of remounting. Keyed by turn so a new turn never shows the\n // previous turn's last state.\n const [reportedStatus, setReportedStatus] = useState<{ messageId: string; status: TurnStatus } | null>(null);\n const liveStatus = liveMessage && reportedStatus?.messageId === liveMessage.id ? reportedStatus.status : null;\n\n if (chatId && !data && !pendingMessage) {\n return (\n <div className=\"fk:flex fk:flex-1 fk:items-center fk:justify-center fk:gap-2 fk:text-sm fk:text-muted-foreground\">\n <LoaderCircle className=\"fk:size-4 fk:animate-spin\" />\n Loading chat...\n </div>\n );\n }\n\n const turnActive = Boolean(pendingMessage) || Boolean(liveMessage);\n const latestAssistantId = [...historyMessages].reverse().find((message) => message.role === 'assistant')?.id ?? null;\n const statusLabel = liveMessage ? (liveStatus?.label ?? 'Thinking') : 'Sending';\n const statusVisible = liveMessage ? (liveStatus?.visible ?? true) : true;\n\n return (\n <Conversation className=\"fk:h-0 fk:min-h-0 fk:flex-1\">\n <ConversationContent className=\"fk:gap-0 fk:p-0\">\n <div className=\"fk:mx-auto fk:w-full fk:max-w-4xl fk:space-y-5 fk:pb-6 fk:pr-4\">\n {(history.page?.hasMore ?? data?.hasMore) ? (\n <Button variant=\"ghost\" disabled={history.loading} onClick={() => void loadOlder()}>\n {history.loading ? 'Loading…' : 'Load earlier messages'}\n </Button>\n ) : null}\n {history.error ? <p role=\"alert\">{history.error}</p> : null}\n {historyMessages.map((message) => (\n <HistoryMessage\n api={api}\n key={message.id}\n message={message}\n showSuggestion={!turnActive && message.id === latestAssistantId}\n />\n ))}\n {liveMessage && chatId && data ? (\n <LiveTurn\n api={api}\n chatId={chatId}\n detail={data}\n message={liveMessage}\n onMidTurnDelivered={(ids) => setLiveDeliveredIds({ ids, messageId: liveMessage.id })}\n onStatusChange={(status) => setReportedStatus({ messageId: liveMessage.id, status })}\n onTurnUpdated={() => void mutate()}\n />\n ) : null}\n {pendingMessage && !liveMessage ? (\n <UserBubble attachments={pendingMessage.attachments} text={pendingMessage.text} />\n ) : null}\n {turnActive ? <TurnStatusLine label={statusLabel} visible={statusVisible} /> : null}\n {waitingFollowUps.map((message) => (\n <HistoryMessage api={api} key={message.id} message={message} />\n ))}\n {pendingFollowUp && liveMessage ? (\n <UserBubble attachments={pendingFollowUp.attachments} text={pendingFollowUp.text} />\n ) : null}\n </div>\n </ConversationContent>\n <ConversationScrollButton />\n </Conversation>\n );\n}\n\nconst GENERIC_GREETINGS = [\n 'Where should we begin?',\n 'Ready when you are',\n 'What’s on the agenda today?',\n 'What’s on your mind today?',\n];\n\nfunction getNamedGreetings(name: string): string[] {\n return [`How can I help, ${name}?`, `Good to see you, ${name}.`, `Hey, ${name}. Ready to dive in?`];\n}\n\nfunction pickGreeting(preferredName: string | null): string {\n const greetings = preferredName ? [...GENERIC_GREETINGS, ...getNamedGreetings(preferredName)] : GENERIC_GREETINGS;\n\n return greetings[Math.floor(Math.random() * greetings.length)] ?? 'How can I help?';\n}\n\nconst LAST_AGENT_MODEL_STORAGE_KEY = 'flexkit-ai:lastModelId';\nconst LAST_AGENT_EFFORT_STORAGE_KEY = 'flexkit-ai:lastEffort';\n\nfunction readLastAgentModel(): ModelSelection | null {\n if (typeof localStorage === 'undefined') {\n return null;\n }\n\n try {\n const stored = localStorage.getItem(LAST_AGENT_MODEL_STORAGE_KEY);\n\n if (!stored) {\n return null;\n }\n\n // The stored value is a model key, which on an older API is the composite\n // model id. Older builds also remembered whatever was last sent, which\n // predates Auto and explicit picks; the catalog lookup in `lastUsed` drops\n // any key it no longer lists, so a new chat starts on Auto in that case.\n return { effort: localStorage.getItem(LAST_AGENT_EFFORT_STORAGE_KEY), modelKey: stored };\n } catch {\n return null;\n }\n}\n\nfunction resolveComposerSelection(input: {\n awaitingChatModel: boolean;\n chatSelection: ModelSelection | null;\n defaultModelKey: string | null;\n lastUsed: ModelSelection | null;\n selectedEffort: string | null;\n selectedModelKey: string | null;\n}): { effort: string | null; modelKey: string | null } {\n if (input.selectedModelKey) {\n return { effort: input.selectedEffort, modelKey: input.selectedModelKey };\n }\n\n // The chat detail request has not returned yet, so its model is unknown.\n // Falling through to the remembered model would display and send that one.\n if (input.awaitingChatModel) {\n return { effort: null, modelKey: null };\n }\n\n if (input.chatSelection) {\n return { effort: input.selectedEffort ?? input.chatSelection.effort, modelKey: input.chatSelection.modelKey };\n }\n\n if (input.lastUsed) {\n return { effort: input.selectedEffort ?? input.lastUsed.effort, modelKey: input.lastUsed.modelKey };\n }\n\n return { effort: input.selectedEffort, modelKey: input.defaultModelKey };\n}\n\nfunction writeLastAgentModel(selection: ModelSelection): void {\n if (typeof localStorage === 'undefined') {\n return;\n }\n\n try {\n localStorage.setItem(LAST_AGENT_MODEL_STORAGE_KEY, selection.modelKey);\n\n if (selection.effort) {\n localStorage.setItem(LAST_AGENT_EFFORT_STORAGE_KEY, selection.effort);\n } else {\n localStorage.removeItem(LAST_AGENT_EFFORT_STORAGE_KEY);\n }\n } catch {\n // Ignore storage access errors (private mode, blocked storage, etc.)\n }\n}\n\nfunction EmptyConversation({ 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-col fk:items-center fk:pb-2 fk:text-center\">\n <h2 className=\"fk:text-2xl fk:font-semibold\">{greeting ?? '\\u00A0'}</h2>\n </div>\n );\n}\n\nexport function AgentChatPage(): JSX.Element {\n const { api, projectId } = useProjectApi();\n const { currentProject, projectSummaries } = useConfig();\n const { chatId } = useParams<{ chatId: string }>();\n const navigate = useNavigate();\n const agentBase = useAgentBasePath();\n const { mutate: globalMutate } = useSWRConfig();\n const { data: toolsData } = useSWR<ToolsResponse>(projectId ? paths(projectId).tools() : null, fetcher);\n const { data: rawChatDetail } = useSWR<AgentChatDetail>(\n projectId && chatId ? paths(projectId).agentChat(chatId) : null,\n fetcher\n );\n const seededDetailRef = useRef<{ [chatId: string]: AgentChatDetail }>({});\n\n function resolveDetail(detail: AgentChatDetail | undefined): AgentChatDetail | undefined {\n return resolveSeededChatDetail(seededDetailRef.current, chatId, detail);\n }\n\n const chatDetail = resolveDetail(rawChatDetail);\n const models = useMemo(() => toolsData?.tools.models ?? [], [toolsData]);\n const [selectedModelKey, setSelectedModelKey] = useState<string | null>(null);\n const [selectedEffort, setSelectedEffort] = useState<string | null>(null);\n // The chat's model id when Auto was last picked, so the selector only leaves\n // Auto once the chat reports a model the routed turn chose.\n const autoPickedOnModelIdRef = useRef<string | null>(null);\n const [rememberedModel, setRememberedModel] = useState<ModelSelection | null>(readLastAgentModel);\n const [sending, setSending] = useState(false);\n const sendingRef = useRef(false);\n const [pendingMessage, setPendingMessage] = useState<(PendingMessage & { chatId: string | undefined }) | null>(null);\n const visiblePendingMessage = pendingMessage && pendingMessage.chatId === chatId ? pendingMessage : undefined;\n const [pendingFollowUp, setPendingFollowUp] = useState<(PendingMessage & { chatId: string }) | null>(null);\n const visiblePendingFollowUp = pendingFollowUp && pendingFollowUp.chatId === chatId ? pendingFollowUp : undefined;\n const [sendError, setSendError] = useState<string | null>(null);\n const chatModelId = chatDetail?.chat.modelId ?? null;\n const awaitingChatModel = Boolean(chatId) && chatDetail === undefined;\n // A stored id the catalog no longer lists is kept as-is so the chat keeps sending it.\n const chatSelection = useMemo(\n () => parseModelSelection(chatModelId, models) ?? (chatModelId ? { effort: null, modelKey: chatModelId } : null),\n [chatModelId, models]\n );\n // The API lists Auto first, so a new chat starts on Auto.\n const defaultModelKey = useMemo(() => {\n const model = models.find((item) => !item.deprecated);\n\n return model ? getModelKey(model) : null;\n }, [models]);\n const lastUsed = useMemo(() => {\n const model = findModelByKey(models, rememberedModel?.modelKey ?? null);\n\n return rememberedModel && model && !model.deprecated ? rememberedModel : null;\n }, [models, rememberedModel]);\n const { effort, modelKey } = resolveComposerSelection({\n awaitingChatModel,\n chatSelection,\n defaultModelKey,\n lastUsed,\n selectedEffort,\n selectedModelKey,\n });\n const modelId = modelKey ? formatModelSelection({ effort, modelKey }, models) : null;\n const modelPending = awaitingChatModel && !selectedModelKey;\n\n useEffect(() => {\n autoPickedOnModelIdRef.current = null;\n setSelectedModelKey(null);\n setSelectedEffort(null);\n setSendError(null);\n }, [chatId]);\n\n // Auto resolves to a concrete model on the next routed turn and the chat\n // keeps it; once the chat reports that choice, the selector shows it\n // instead of staying on Auto. The chat's model at the time Auto was picked\n // is not that choice: an existing chat already reports its stored model, and\n // snapping back to it would make Auto impossible to pick for later turns.\n useEffect(() => {\n if (\n selectedModelKey === AUTO_MODEL_KEY &&\n chatModelId &&\n chatModelId !== AUTO_MODEL_KEY &&\n chatModelId !== autoPickedOnModelIdRef.current\n ) {\n setSelectedModelKey(null);\n setSelectedEffort(null);\n }\n }, [chatModelId, selectedModelKey]);\n\n function rememberModel(next: ModelSelection): void {\n setRememberedModel(next);\n writeLastAgentModel(next);\n }\n\n function handleModelChange(nextModelKey: string): void {\n autoPickedOnModelIdRef.current = nextModelKey === AUTO_MODEL_KEY ? chatModelId : null;\n setSelectedModelKey(nextModelKey);\n // The new model's default effort applies until the user picks one.\n setSelectedEffort(null);\n rememberModel({ effort: null, modelKey: nextModelKey });\n }\n\n function handleEffortChange(nextEffort: string): void {\n setSelectedEffort(nextEffort);\n\n if (modelKey) {\n rememberModel({ effort: nextEffort, modelKey });\n }\n }\n\n if (!projectId || !api) {\n return (\n <div className=\"fk:flex fk:h-full fk:items-center fk:justify-center fk:text-sm fk:text-muted-foreground\">\n Select a project to chat with the agent.\n </div>\n );\n }\n\n const chatApi = api;\n const chatProjectId = projectId;\n const projectName =\n currentProject?.title ?? projectSummaries.find((project) => project.id === projectId)?.name ?? 'your project';\n // A new chat greets in the middle of the page, ChatGPT-style; the first\n // send (a pending message) moves the composer down to its usual place.\n const isNewChat = !chatId && !visiblePendingMessage;\n const turnInProgress = Boolean(chatDetail && splitLiveTurn(chatDetail.messages).live);\n\n async function sendFollowUp(targetChatId: string, text: string, attachments: AgentChatAttachment[]): Promise<void> {\n setPendingFollowUp({ attachments, chatId: targetChatId, text });\n\n try {\n const result = await chatApi.sendAgentChatFollowUp(targetChatId, { attachments, content: text, modelId });\n\n await globalMutate<AgentChatDetail>(\n paths(chatProjectId).agentChat(targetChatId),\n (current) => {\n const base = getSeedBaseDetail(\n mergeChatDetail(seededDetailRef.current[targetChatId], current),\n null,\n rawChatDetail,\n targetChatId,\n modelId,\n 'turn' in result ? result.turn.userMessage.createdAt : result.followUp.message.createdAt\n );\n const next =\n 'turn' in result ? appendTurnToDetail(base, result.turn) : appendMessageToDetail(base, result.followUp.message);\n seededDetailRef.current[targetChatId] = next;\n\n return next;\n },\n { revalidate: false }\n );\n } finally {\n setPendingFollowUp(null);\n }\n }\n\n async function handleSend(text: string, attachments: AgentChatAttachment[]): Promise<void> {\n // Reject rather than resolve so the composer does not treat a duplicate\n // submit as a successful send and clear the attachments of the in-flight one.\n if (sendingRef.current) {\n throw new Error('A message is already being sent.');\n }\n\n if (modelPending) {\n throw new Error('This chat is still loading.');\n }\n\n sendingRef.current = true;\n setSending(true);\n setSendError(null);\n\n // During a turn the message is a follow-up: stored at once, then either\n // steering the running turn or starting the next one. A queued follow-up\n // that has not started yet goes first, so the new message cannot jump\n // the queue or race the auto-start.\n const queuedBeforeThis = chatDetail ? getNextQueuedMessage(chatDetail.messages) : null;\n\n if (chatId && (turnInProgress || queuedBeforeThis)) {\n try {\n if (!turnInProgress && queuedBeforeThis) {\n // The auto-start may have won the race; either way a turn is now running.\n await chatApi.startQueuedAgentChatMessage(chatId, queuedBeforeThis.id).catch(() => undefined);\n }\n\n await sendFollowUp(chatId, text, attachments);\n } catch (error) {\n setSendError(error instanceof Error ? error.message : 'Failed to send the message.');\n throw error;\n } finally {\n sendingRef.current = false;\n setSending(false);\n }\n\n return;\n }\n\n setPendingMessage({ attachments, chatId, text });\n\n // Only explicit picks in the selector are remembered (see handleModelChange);\n // what a chat happened to run on, including a routed Auto choice, is not.\n try {\n // A new chat is created and its first message sent by one request: the\n // second round trip (and its auth) used to cost about half a second.\n const started = chatId\n ? { chat: null, turn: await chatApi.sendAgentChatMessage(chatId, { attachments, content: text, modelId }) }\n : await chatApi.startAgentChat({ attachments, content: text, modelId });\n const { chat, turn } = started;\n const targetChatId = chatId ?? chat!.id;\n\n // Seed the confirmed turn without waiting for another network round trip.\n // Keep a local overlay so an in-flight GET that started before POST cannot\n // replace this seed with a snapshot that omits the new messages.\n await globalMutate<AgentChatDetail>(\n paths(chatProjectId).agentChat(targetChatId),\n (current) => {\n const next = appendTurnToDetail(\n getSeedBaseDetail(\n mergeChatDetail(seededDetailRef.current[targetChatId], current),\n chat,\n rawChatDetail,\n targetChatId,\n modelId,\n turn.userMessage.createdAt\n ),\n turn\n );\n seededDetailRef.current[targetChatId] = next;\n\n return next;\n },\n { revalidate: false }\n );\n // Navigate before clearing the pending message so the conversation is\n // never left without a chat or a pending turn between the two updates.\n if (chat) {\n navigate(`${agentBase}/chats/${chat.id}`);\n }\n\n setPendingMessage(null);\n } catch (error) {\n setPendingMessage(null);\n setSendError(error instanceof Error ? error.message : 'Failed to send the message.');\n throw error;\n } finally {\n sendingRef.current = false;\n setSending(false);\n }\n }\n\n async function handleStop(): Promise<void> {\n if (!chatId) {\n return;\n }\n\n try {\n await chatApi.stopAgentChat(chatId);\n } catch (error) {\n setSendError(error instanceof Error ? error.message : 'Failed to stop the turn.');\n } finally {\n await globalMutate(paths(chatProjectId).agentChat(chatId));\n }\n }\n\n return (\n <PromptInputProvider>\n <ComposerDraftSync draftKey={getComposerDraftKey(chatProjectId, chatId)} />\n <div className=\"fk:flex fk:h-full fk:min-h-0 fk:flex-col fk:gap-2\">\n <div className=\"fk:mb-2 fk:flex fk:shrink-0 fk:items-start fk:gap-2\">\n <Tooltip>\n <TooltipTrigger asChild>\n <SidebarTrigger className=\"fk:-ml-1 fk:h-4 fk:w-4\" />\n </TooltipTrigger>\n <TooltipContent>Toggle Sidebar</TooltipContent>\n </Tooltip>\n <Separator orientation=\"vertical\" className=\"fk:mt-1 fk:h-4\" />\n <div className=\"fk:flex fk:flex-1 fk:items-center fk:gap-2\">\n <h1 className=\"fk:truncate fk:text-lg fk:font-semibold fk:leading-none fk:tracking-tight\">\n {chatId ? (chatDetail?.chat.title?.trim() ?? 'Chat') : 'Agent'}\n </h1>\n </div>\n </div>\n <div className=\"fk:flex fk:min-h-0 fk:flex-1 fk:gap-4\">\n <div\n className={cn(\n 'fk:flex fk:min-h-0 fk:min-w-0 fk:flex-1 fk:flex-col fk:gap-3',\n isNewChat && 'fk:justify-center fk:pb-[12vh]'\n )}\n >\n {!isNewChat ? (\n // One element type for the pending and the loaded chat, so the\n // status line survives the navigation after the chat is created.\n <ChatApprovalContext.Provider value>\n <ChatConversation\n api={chatApi}\n chatId={chatId ?? null}\n pendingFollowUp={visiblePendingFollowUp}\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 placeholder={\n turnInProgress ? 'Add context or steer the agent...' : `Ask Flexkit anything about ${projectName}...`\n }\n />\n </div>\n </div>\n </div>\n </div>\n </PromptInputProvider>\n );\n}\n"]}
@@ -1,3 +0,0 @@
1
- import'./index.css';import {put}from'@vercel/blob/client';function I(i,e){let l=e.trim();return l?i.trim()?/\s$/.test(i)||/^[.,!?;:]/.test(l)?`${i}${l}`:`${i} ${l}`:i.length===0?l:`${i}${l}`:i}async function h(i){if(typeof window>"u")throw new Error("Dictation is only available in the browser.");let e=window.AudioContext??window.webkitAudioContext;if(!e)throw new Error("This browser cannot decode recorded audio.");let l=await i.arrayBuffer(),u=new e;try{let n=await u.decodeAudioData(l.slice(0)),s=C(n),t=y(s,n.sampleRate,24e3),o=$(t),r=t.length/24e3;if(r<.25)throw new Error("No speech was captured. Try again.");if(r>60)throw new Error(`Dictation is limited to ${String(60)} seconds.`);return {durationSeconds:r,pcm:new Blob([o],{type:"audio/pcm"})}}finally{await u.close();}}function C(i){let{length:e,numberOfChannels:l}=i;if(l===1)return i.getChannelData(0).slice();let u=new Float32Array(e);for(let n=0;n<e;n+=1){let s=0;for(let t=0;t<l;t+=1)s+=i.getChannelData(t)[n]??0;u[n]=s/l;}return u}function y(i,e,l){if(e===l)return i;let u=e/l,n=Math.max(1,Math.round(i.length/u)),s=new Float32Array(n);for(let t=0;t<n;t+=1){let o=t*u,r=Math.floor(o),a=Math.min(r+1,i.length-1),c=o-r,m=i[r]??0,g=i[a]??0;s[t]=m+(g-m)*c;}return s}function $(i){let e=new ArrayBuffer(i.length*2),l=new DataView(e);for(let u=0;u<i.length;u+=1){let n=Math.max(-1,Math.min(1,i[u]??0));l.setInt16(u*2,n<0?n*32768:n*32767,true);}return e}var d=class extends Error{code;status;constructor(e,l,u=null){super(l),this.name="AgentUploadError",this.code=u,this.status=e;}};function f(){if(typeof window>"u")return "flexkit.io";let{hostname:i}=window.location;return i==="localhost"||i==="127.0.0.1"||i==="flexkit.test"||i.endsWith(".flexkit.test")?"flexkit.test":"flexkit.io"}function T(){return `https://${f()}`}function _(i,e){return `https://${i}.api.${f()}/automations/webhook/${encodeURIComponent(e)}`}function w(i){let e=`/api/flexkit/${i}`,l=`${e}/automations`,u=`${e}/skills`,n=`${e}/agent/chats`;async function s(t,o){let r=await fetch(t,{credentials:"include",headers:{"Content-Type":"application/json",...o?.headers??{}},...o}),a=await r.json();if(!r.ok){let c=a&&typeof a=="object"&&"error"in a?String(a.error):"Request failed";throw new Error(c)}return a}return {connectPlugins:t=>s(`${e}/plugins/connect`,{method:"POST",body:JSON.stringify(t)}),pluginOAuthStatus:t=>s(`${e}/plugins/oauth-transactions/${encodeURIComponent(t)}`),updatePluginConnection:(t,o)=>s(`${e}/plugin-connections/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(o)}),disconnectPlugin:t=>s(`${e}/plugin-connections/${encodeURIComponent(t)}`,{method:"DELETE"}),installPlugin:t=>s(`${e}/plugins/${encodeURIComponent(t)}/installation`,{method:"PUT",body:JSON.stringify({})}),setPluginPolicy:(t,o)=>s(`${e}/plugins/${encodeURIComponent(t)}/policy`,{method:"PATCH",body:JSON.stringify(o)}),refreshPluginTools:t=>s(`${e}/plugin-connections/${encodeURIComponent(t)}/tools/refresh`,{method:"POST"}),cancelRun:async t=>s(`${l}/runs/${encodeURIComponent(t)}/cancel`,{method:"POST"}),createAgentChat:async t=>s(n,{body:JSON.stringify({modelId:t?.modelId??null}),method:"POST"}),deleteAgentChat:async t=>s(`${n}/${encodeURIComponent(t)}`,{method:"DELETE"}),getAgentChatStreamUrl:(t,o)=>`${n}/${encodeURIComponent(t)}/stream?workflowRunId=${encodeURIComponent(o)}`,renameAgentChat:async(t,o)=>s(`${n}/${encodeURIComponent(t)}`,{body:JSON.stringify({title:o}),method:"PATCH"}),sendAgentChatMessage:async(t,o)=>s(`${n}/${encodeURIComponent(t)}/messages`,{body:JSON.stringify(o),method:"POST"}),sendAgentChatFollowUp:async(t,o)=>s(`${n}/${encodeURIComponent(t)}/follow-ups`,{body:JSON.stringify(o),method:"POST"}),startAgentChat:async({attachments:t,content:o,modelId:r})=>s(n,{body:JSON.stringify({message:{attachments:t,content:o},modelId:r??null}),method:"POST"}),startQueuedAgentChatMessage:async(t,o)=>s(`${n}/${encodeURIComponent(t)}/follow-ups/${encodeURIComponent(o)}/start`,{method:"POST"}),stopAgentChat:async t=>s(`${n}/${encodeURIComponent(t)}/stop`,{method:"POST"}),transcribeAgentAudio:async(t,o)=>{let{durationSeconds:r,pcm:a}=await h(t),c=new FormData;c.append("file",a,"audio.pcm"),c.append("durationSeconds",String(r));let m=await fetch(`${e}/agent/transcribe`,{body:c,credentials:"include",method:"POST",signal:o}),g=await m.json();if(!m.ok){let A=g&&typeof g=="object"&&g.error?String(g.error):"Request failed";throw new Error(A)}if(!g.text?.trim())throw new Error("No speech was recognized. Try again.");return {text:g.text}},uploadAgentChatAttachment:async(t,o)=>{let r=await fetch(`${e}/agent/uploads`,{body:JSON.stringify({filename:t.name,mediaType:t.type||null,sizeBytes:t.size}),credentials:"include",headers:{"Content-Type":"application/json"},method:"POST",signal:o}),a=await r.json();if(!r.ok||!a.pathname||!a.token||!a.mediaType)throw new d(r.status,a.error?String(a.error):"The file could not be uploaded.",a.code??null);let c=await put(a.pathname,t,{abortSignal:o,access:"public",contentType:a.mediaType,token:a.token});return {filename:t.name,mediaType:a.mediaType,sizeBytes:t.size,url:c.url}},decideApproval:async(t,o)=>{let r=await fetch(`${l}/approvals/${encodeURIComponent(t)}/decide`,{body:JSON.stringify(o),credentials:"include",headers:{"Content-Type":"application/json"},method:"POST"}),a=await r.json();if(!r.ok&&typeof a.success!="boolean")throw new Error(a.error?String(a.error):"Request failed");return a},markActivityRead:async t=>s(`${e}/activity/read`,{body:JSON.stringify(t==="all"?{all:true}:{ids:t}),method:"POST"}),setActivityItemState:async(t,o)=>s(`${e}/activity/${encodeURIComponent(t)}`,{body:JSON.stringify({state:o}),method:"PATCH"}),createAutomation:async t=>s(l,{body:JSON.stringify(t),method:"POST"}),createSkill:async t=>s(u,{body:JSON.stringify(t),method:"POST"}),deleteAutomation:async t=>s(`${l}/${encodeURIComponent(t)}`,{method:"DELETE"}),deleteSkill:async t=>s(`${u}/${encodeURIComponent(t)}`,{method:"DELETE"}),getArtifactUrl:(t,o)=>{let r=o?.download?"?download=1":"";return `${l}/artifacts/${encodeURIComponent(t)}/content${r}`},getRunArtifacts:async t=>s(`${l}/runs/${encodeURIComponent(t)}/artifacts`).then(o=>o.artifacts),getStreamUrl:t=>`${l}/runs/${encodeURIComponent(t)}/stream`,getTranscriptUrl:t=>`${l}/runs/${encodeURIComponent(t)}/transcript`,listChannels:async(t,o)=>{let r=o?`${e}/plugin-connections/${encodeURIComponent(o)}/channels`:`${e}/plugins/${t}/channels`,a=await fetch(r,{credentials:"include",headers:{"Content-Type":"application/json"}}),c=await a.json();if(a.ok)return {channels:c.channels??[],errorMessage:c.errorMessage,success:c.success??true};if(c.success===false)return {channels:c.channels??[],errorMessage:c.errorMessage??`Failed to load ${t==="slack"?"Slack":"Teams"} channels.`,success:false};let m=c.error?String(c.error):"Request failed";throw new Error(m)},runAutomation:async t=>s(`${l}/${encodeURIComponent(t)}/runs`,{method:"POST"}),updateAutomation:async(t,o)=>s(`${l}/${encodeURIComponent(t)}`,{body:JSON.stringify(o),method:"PATCH"}),updateSkill:async(t,o)=>s(`${u}/${encodeURIComponent(t)}`,{body:JSON.stringify(o),method:"PATCH"})}}var p=class extends Error{status;constructor(e,l="Request failed"){super(l),this.name="FetcherError",this.status=e;}},k=async i=>{let e=await fetch(i,{credentials:"include"});if(!e.ok)throw new p(e.status);return await e.json()};function U(i){let e=`/api/flexkit/${i}/automations`,l=`/api/flexkit/${i}/skills`,u=`/api/flexkit/${i}/agent/chats`;return {activity:(n={})=>{let{filter:s="all",limit:t=25,offset:o=0}=n,r=new URLSearchParams({filter:s,limit:t.toString(),offset:o.toString()});return `/api/flexkit/${i}/activity?${r.toString()}`},activityItem:n=>`/api/flexkit/${i}/activity/${encodeURIComponent(n)}`,activitySummary:n=>n?`/api/flexkit/${i}/activity/summary?since=${encodeURIComponent(n)}`:`/api/flexkit/${i}/activity/summary`,agentChat:n=>`${u}/${encodeURIComponent(n)}`,agentChatSearch:n=>`${u}/search?q=${encodeURIComponent(n)}`,agentChats:(n=0)=>`${u}?offset=${n.toString()}`,agentProfile:()=>`/api/flexkit/${i}/agent/profile`,approval:n=>`${e}/approvals/${encodeURIComponent(n)}`,approvals:(n={})=>{let{limit:s=25,offset:t=0,runId:o,status:r}=n,a=new URLSearchParams({limit:s.toString(),offset:t.toString()});return r&&a.set("status",r),o&&a.set("runId",o),`${e}/approvals?${a.toString()}`},approvalsCount:`${e}/approvals?limit=1`,automation:n=>`${e}/${encodeURIComponent(n)}`,automationRuns:(n,s=0,t=25)=>`${e}/${encodeURIComponent(n)}/runs?offset=${s.toString()}&limit=${t.toString()}`,automations:(n={})=>{let{enabled:s,limit:t=25,offset:o=0,search:r,visibility:a}=n,c=new URLSearchParams({limit:t.toString(),offset:o.toString()});s&&s.length>0&&c.set("enabled",s.map(g=>g?"true":"false").join(",")),a&&a.length>0&&c.set("visibility",a.join(","));let m=r?.trim();return m&&c.set("q",m),`${e}?${c.toString()}`},creditBalance:`${e}/credits`,entities:`${e}/entities`,run:n=>`${e}/runs/${encodeURIComponent(n)}`,runHistory:(n,s=0,t=25)=>`${e}/runs?scope=${n}&offset=${s.toString()}&limit=${t.toString()}`,skill:n=>`${l}/${encodeURIComponent(n)}`,skills:(n={})=>{let{limit:s=25,offset:t=0,search:o,visibility:r}=n,a=new URLSearchParams({limit:s.toString(),offset:t.toString()});r&&r.length>0&&a.set("visibility",r.join(","));let c=o?.trim();return c&&a.set("q",c),`${l}?${a.toString()}`},spaces:`/api/flexkit/${i}/spaces`,members:n=>n?`/api/flexkit/${i}/members?spaceId=${encodeURIComponent(n)}`:`/api/flexkit/${i}/members`,tools:n=>n?`${e}/${encodeURIComponent(n)}/tools`:`${e}/tools`}}
2
- export{I as a,T as b,_ as c,w as d,p as e,k as f,U as g};//# sourceMappingURL=chunk-CKNFYN3O.js.map
3
- //# sourceMappingURL=chunk-CKNFYN3O.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/apps/ai/agent/dictation.ts","../src/apps/ai/api.ts"],"names":["appendDictatedText","existing","transcript","dictated","convertRecordedAudioToPcm","blob","AudioContextCtor","arrayBuffer","audioContext","audioBuffer","mono","mixToMono","resampled","resample","pcm","floatToPcm16","durationSeconds","buffer","length","channelCount","index","sum","channel","samples","sourceRate","targetRate","ratio","outputLength","output","sourceIndex","left","right","fraction","leftSample","rightSample","view","sample","AgentUploadError","status","message","code","getApiRootDomain","hostname","getPlatformOrigin","getWebhookTriggerUrl","projectId","token","createApiClient","projectBasePath","automationsBasePath","skillsBasePath","agentChatsBasePath","request","url","init","response","data","error","input","id","runId","chatId","workflowRunId","title","attachments","content","modelId","messageId","audio","signal","formData","file","tokenResponse","tokenData","put","approvalId","ids","itemId","state","automationId","skillId","artifactId","options","suffix","provider","connectionId","FetcherError","fetcher","paths","basePath","filter","limit","offset","params","since","query","enabled","search","visibility","value","trimmedSearch","scope","spaceId"],"mappings":"0DAIO,SAASA,CAAAA,CAAmBC,CAAAA,CAAkBC,CAAAA,CAA4B,CAC/E,IAAMC,CAAAA,CAAWD,CAAAA,CAAW,IAAA,EAAK,CAEjC,OAAKC,CAAAA,CAIAF,CAAAA,CAAS,IAAA,GAIV,KAAA,CAAM,IAAA,CAAKA,CAAQ,CAAA,EAAK,WAAA,CAAY,IAAA,CAAKE,CAAQ,CAAA,CAC5C,CAAA,EAAGF,CAAQ,CAAA,EAAGE,CAAQ,CAAA,CAAA,CAGxB,CAAA,EAAGF,CAAQ,CAAA,CAAA,EAAIE,CAAQ,CAAA,CAAA,CAPrBF,CAAAA,CAAS,MAAA,GAAW,CAAA,CAAIE,CAAAA,CAAW,CAAA,EAAGF,CAAQ,CAAA,EAAGE,CAAQ,CAAA,CAAA,CAJzDF,CAYX,CAEA,eAAsBG,CAAAA,CAA0BC,CAAAA,CAA6D,CAC3G,GAAI,OAAO,MAAA,CAAW,GAAA,CACpB,MAAM,IAAI,KAAA,CAAM,6CAA6C,CAAA,CAG/D,IAAMC,CAAAA,CAAmB,OAAO,YAAA,EAAgB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Q,EAAA,CAAI,MAAA,CAAAC,CAAAA,CAAS,CAAA,CAAG,MAAA,CAAAK,CAAAA,CAAQ,UAAA,CAAAC,CAAW,CAAA,CAAIhB,CAAAA,CACjDW,CAAAA,CAAS,IAAI,eAAA,CAAgB,CACjC,KAAA,CAAOF,CAAAA,CAAM,QAAA,EAAS,CACtB,MAAA,CAAQC,CAAAA,CAAO,QAAA,EACjB,CAAC,CAAA,CAEGM,CAAAA,EAAcA,CAAAA,CAAW,MAAA,CAAS,GACpCL,CAAAA,CAAO,GAAA,CAAI,YAAA,CAAcK,CAAAA,CAAW,IAAA,CAAK,GAAG,CAAC,CAAA,CAG/C,IAAME,CAAAA,CAAgBH,CAAAA,EAAQ,IAAA,EAAK,CAEnC,OAAIG,GACFP,CAAAA,CAAO,GAAA,CAAI,GAAA,CAAKO,CAAa,CAAA,CAGxB,CAAA,EAAGlD,CAAc,CAAA,CAAA,EAAI2C,CAAAA,CAAO,QAAA,EAAU,CAAA,CAC/C,CAAA,CACA,MAAA,CAAQ,gBAAgBhD,CAAS,CAAA,OAAA,CAAA,CACjC,OAAA,CAAUyD,CAAAA,EACRA,CAAAA,CACI,CAAA,aAAA,EAAgBzD,CAAS,CAAA,iBAAA,EAAoB,kBAAA,CAAmByD,CAAO,CAAC,CAAA,CAAA,CACxE,CAAA,aAAA,EAAgBzD,CAAS,CAAA,QAAA,CAAA,CAC/B,KAAA,CAAQkC,CAAAA,EACNA,CAAAA,CAAe,CAAA,EAAGU,CAAQ,CAAA,CAAA,EAAI,kBAAA,CAAmBV,CAAY,CAAC,CAAA,MAAA,CAAA,CAAW,CAAA,EAAGU,CAAQ,CAAA,MAAA,CACxF,CACF","file":"chunk-CKNFYN3O.js","sourcesContent":["export const DICTATION_SAMPLE_RATE = 24_000;\nexport const DICTATION_MAX_DURATION_SECONDS = 60;\nexport const DICTATION_MIN_DURATION_SECONDS = 0.25;\n\nexport function appendDictatedText(existing: string, transcript: string): string {\n const dictated = transcript.trim();\n\n if (!dictated) {\n return existing;\n }\n\n if (!existing.trim()) {\n return existing.length === 0 ? dictated : `${existing}${dictated}`;\n }\n\n if (/\\s$/.test(existing) || /^[.,!?;:]/.test(dictated)) {\n return `${existing}${dictated}`;\n }\n\n return `${existing} ${dictated}`;\n}\n\nexport async function convertRecordedAudioToPcm(blob: Blob): Promise<{ durationSeconds: number; pcm: Blob }> {\n if (typeof window === 'undefined') {\n throw new Error('Dictation is only available in the browser.');\n }\n\n const AudioContextCtor = window.AudioContext ?? window.webkitAudioContext;\n\n if (!AudioContextCtor) {\n throw new Error('This browser cannot decode recorded audio.');\n }\n\n const arrayBuffer = await blob.arrayBuffer();\n const audioContext = new AudioContextCtor();\n\n try {\n const audioBuffer = await audioContext.decodeAudioData(arrayBuffer.slice(0));\n const mono = mixToMono(audioBuffer);\n const resampled = resample(mono, audioBuffer.sampleRate, DICTATION_SAMPLE_RATE);\n const pcm = floatToPcm16(resampled);\n const durationSeconds = resampled.length / DICTATION_SAMPLE_RATE;\n\n if (durationSeconds < DICTATION_MIN_DURATION_SECONDS) {\n throw new Error('No speech was captured. Try again.');\n }\n\n if (durationSeconds > DICTATION_MAX_DURATION_SECONDS) {\n throw new Error(`Dictation is limited to ${String(DICTATION_MAX_DURATION_SECONDS)} seconds.`);\n }\n\n return {\n durationSeconds,\n pcm: new Blob([pcm], { type: 'audio/pcm' }),\n };\n } finally {\n await audioContext.close();\n }\n}\n\nfunction mixToMono(buffer: AudioBuffer): Float32Array {\n const { length, numberOfChannels: channelCount } = buffer;\n\n if (channelCount === 1) {\n return buffer.getChannelData(0).slice();\n }\n\n const mono = new Float32Array(length);\n\n for (let index = 0; index < length; index += 1) {\n let sum = 0;\n\n for (let channel = 0; channel < channelCount; channel += 1) {\n sum += buffer.getChannelData(channel)[index] ?? 0;\n }\n\n mono[index] = sum / channelCount;\n }\n\n return mono;\n}\n\nfunction resample(samples: Float32Array, sourceRate: number, targetRate: number): Float32Array {\n if (sourceRate === targetRate) {\n return samples;\n }\n\n const ratio = sourceRate / targetRate;\n const outputLength = Math.max(1, Math.round(samples.length / ratio));\n const output = new Float32Array(outputLength);\n\n for (let index = 0; index < outputLength; index += 1) {\n const sourceIndex = index * ratio;\n const left = Math.floor(sourceIndex);\n const right = Math.min(left + 1, samples.length - 1);\n const fraction = sourceIndex - left;\n const leftSample = samples[left] ?? 0;\n const rightSample = samples[right] ?? 0;\n output[index] = leftSample + (rightSample - leftSample) * fraction;\n }\n\n return output;\n}\n\nfunction floatToPcm16(samples: Float32Array): ArrayBuffer {\n const buffer = new ArrayBuffer(samples.length * 2);\n const view = new DataView(buffer);\n\n for (let index = 0; index < samples.length; index += 1) {\n const sample = Math.max(-1, Math.min(1, samples[index] ?? 0));\n view.setInt16(index * 2, sample < 0 ? sample * 0x8000 : sample * 0x7fff, true);\n }\n\n return buffer;\n}\n\ndeclare global {\n interface Window {\n webkitAudioContext?: typeof AudioContext;\n }\n}\n","import type { PluginConnection, PluginScope, PluginTools } from './plugin-types';\nimport { put } from '@vercel/blob/client';\nimport { convertRecordedAudioToPcm } from './agent/dictation';\nimport type {\n ActivityItem,\n ActivityItemState,\n AgentChat,\n AgentChatAttachment,\n AgentChatFollowUpResult,\n AgentChatMessage,\n AgentChatTurn,\n Automation,\n AutomationApproval,\n AutomationApprovalStatus,\n AutomationArtifact,\n AutomationInput,\n AutomationToolChannel,\n AutomationToolProvider,\n AutomationVisibility,\n MutationResult,\n Skill,\n SkillInput,\n} from './types';\n\nexport interface DecideApprovalInput {\n /** Approve and always allow this plugin tool for the automation. */\n remember?: boolean;\n approved: boolean;\n /** For a proposed automation: the approver's edited instructions and whether to run it once now. */\n automationEdits?: { instructions?: string; runOnce?: boolean };\n force?: boolean;\n reason?: string;\n}\n\nexport interface SendAgentChatMessageInput {\n attachments?: AgentChatAttachment[];\n content: string;\n modelId?: string | null;\n}\n\n/** A new chat and its first turn, started by one request. */\nexport interface StartAgentChatResult {\n chat: AgentChat;\n turn: AgentChatTurn;\n}\n\n/** Thrown when the API refuses an upload; `code` lets the UI tailor the message. */\nexport class AgentUploadError extends Error {\n code: string | null;\n status: number;\n\n constructor(status: number, message: string, code: string | null = null) {\n super(message);\n this.name = 'AgentUploadError';\n this.code = code;\n this.status = status;\n }\n}\n\nexport interface ApiClient {\n /** Starts OAuth for a new account, or for `connectionId` to reconnect that specific account. */\n connectPlugins: (_input: {\n pluginId: string;\n scope: PluginScope;\n studioOrigin: string;\n connectionId?: string;\n }) => Promise<{ transactionId: string; authorizeUrl: string; completionOrigin: string; launchTicket: string }>;\n /** Renames (label null resets to the provider name) or makes a connection primary. */\n updatePluginConnection: (\n _id: string,\n _input: { label?: string | null; primary?: true }\n ) => Promise<{ connection: PluginConnection }>;\n pluginOAuthStatus: (_id: string) => Promise<{ id: string; status: 'pending' | 'exchanging' | 'complete' | 'failed'; expires_at: string }>;\n disconnectPlugin: (_id: string) => Promise<{ success: boolean }>;\n installPlugin: (_id: string) => Promise<unknown>;\n setPluginPolicy: (_id: string, _input: { enabled: boolean; allowPersonal: boolean }) => Promise<{ success: boolean }>;\n refreshPluginTools: (_id: string) => Promise<PluginTools>;\n\n cancelRun: (_runId: string) => Promise<MutationResult>;\n createAgentChat: (_input?: { modelId?: string | null }) => Promise<{ chat: AgentChat }>;\n deleteAgentChat: (_chatId: string) => Promise<{ success: boolean }>;\n getAgentChatStreamUrl: (_chatId: string, _workflowRunId: string) => string;\n renameAgentChat: (_chatId: string, _title: string) => Promise<{ chat: AgentChat }>;\n sendAgentChatMessage: (_chatId: string, _input: SendAgentChatMessageInput) => Promise<AgentChatTurn>;\n /**\n * Sends a message while the chat's turn is running. The platform decides\n * whether it steers that turn or waits as the next one; if the turn has\n * meanwhile ended, the message starts the next turn.\n */\n sendAgentChatFollowUp: (_chatId: string, _input: SendAgentChatMessageInput) => Promise<AgentChatFollowUpResult>;\n /** Creates a chat and sends its first message in one request. */\n startAgentChat: (_input: SendAgentChatMessageInput) => Promise<StartAgentChatResult>;\n /** Starts the next turn from a queued follow-up once the previous turn has ended. */\n startQueuedAgentChatMessage: (_chatId: string, _messageId: string) => Promise<AgentChatTurn>;\n stopAgentChat: (_chatId: string) => Promise<{ message: AgentChatMessage }>;\n transcribeAgentAudio: (_audio: Blob, _signal?: AbortSignal) => Promise<{ text: string }>;\n /** Uploads a chat attachment straight to the platform file store. */\n uploadAgentChatAttachment: (_file: File, _signal?: AbortSignal) => Promise<AgentChatAttachment>;\n decideApproval: (\n _approvalId: string,\n _input: DecideApprovalInput\n ) => Promise<MutationResult & { approval?: AutomationApproval }>;\n createAutomation: (_input: AutomationInput) => Promise<MutationResult & { automation?: Automation }>;\n createSkill: (_input: SkillInput) => Promise<MutationResult & { skill?: Skill }>;\n deleteAutomation: (_automationId: string) => Promise<MutationResult>;\n deleteSkill: (_skillId: string) => Promise<MutationResult>;\n getArtifactUrl: (_artifactId: string, _options?: { download?: boolean }) => string;\n getRunArtifacts: (_workflowRunId: string) => Promise<AutomationArtifact[]>;\n getStreamUrl: (_workflowRunId: string) => string;\n /** JSON transcript of a finished run (owners and developers). */\n getTranscriptUrl: (_runId: string) => string;\n /** Lists delivery channels of `connectionId`, or of the provider's primary project account when omitted. */\n listChannels: (_provider: AutomationToolProvider, _connectionId?: string | null) => Promise<{\n channels: AutomationToolChannel[];\n errorMessage?: string;\n success: boolean;\n }>;\n runAutomation: (_automationId: string) => Promise<MutationResult & { runId?: string }>;\n updateAutomation: (\n _automationId: string,\n _input: AutomationInput\n ) => Promise<MutationResult & { automation?: Automation }>;\n updateSkill: (_skillId: string, _input: SkillInput) => Promise<MutationResult & { skill?: Skill }>;\n /** Marks the caller's Activity items read; `'all'` marks every unread item. */\n markActivityRead: (_ids: string[] | 'all') => Promise<{ success: boolean }>;\n setActivityItemState: (\n _itemId: string,\n _state: Extract<ActivityItemState, 'unread' | 'read' | 'dismissed'>\n ) => Promise<{ item: ActivityItem }>;\n}\n\n\nfunction getApiRootDomain(): string {\n if (typeof window === 'undefined') {\n return 'flexkit.io';\n }\n\n const { hostname } = window.location;\n const isDevHost =\n hostname === 'localhost' ||\n hostname === '127.0.0.1' ||\n hostname === 'flexkit.test' ||\n hostname.endsWith('.flexkit.test');\n\n return isDevHost ? 'flexkit.test' : 'flexkit.io';\n}\n\n/** Origin that hosts plugin OAuth start and completion. */\nexport function getPlatformOrigin(): string {\n return `https://${getApiRootDomain()}`;\n}\n\n/** Public URL an external system calls to fire a webhook trigger. */\nexport function getWebhookTriggerUrl(projectId: string, token: string): string {\n return `https://${projectId}.api.${getApiRootDomain()}/automations/webhook/${encodeURIComponent(token)}`;\n}\n\nexport function createApiClient(projectId: string): ApiClient {\n const projectBasePath = `/api/flexkit/${projectId}`;\n const automationsBasePath = `${projectBasePath}/automations`;\n const skillsBasePath = `${projectBasePath}/skills`;\n const agentChatsBasePath = `${projectBasePath}/agent/chats`;\n\n async function request<T>(url: string, init?: RequestInit): Promise<T> {\n const response = await fetch(url, {\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n ...(init?.headers ?? {}),\n },\n ...init,\n });\n const data = (await response.json()) as T;\n\n if (!response.ok) {\n const error = data && typeof data === 'object' && 'error' in data ? String(data.error) : 'Request failed';\n\n throw new Error(error);\n }\n\n return data;\n }\n\n return {\n connectPlugins: (input) => request(`${projectBasePath}/plugins/connect`, { method: 'POST', body: JSON.stringify(input) }),\n pluginOAuthStatus: (id) => request(`${projectBasePath}/plugins/oauth-transactions/${encodeURIComponent(id)}`),\n updatePluginConnection: (id, input) =>\n request(`${projectBasePath}/plugin-connections/${encodeURIComponent(id)}`, { method: 'PATCH', body: JSON.stringify(input) }),\n disconnectPlugin: (id) => request(`${projectBasePath}/plugin-connections/${encodeURIComponent(id)}`, { method: 'DELETE' }),\n installPlugin: (id) => request(`${projectBasePath}/plugins/${encodeURIComponent(id)}/installation`, { method: 'PUT', body: JSON.stringify({}) }),\n setPluginPolicy: (id, input) => request(`${projectBasePath}/plugins/${encodeURIComponent(id)}/policy`, { method: 'PATCH', body: JSON.stringify(input) }),\n refreshPluginTools: (id) => request(`${projectBasePath}/plugin-connections/${encodeURIComponent(id)}/tools/refresh`, { method: 'POST' }),\n cancelRun: async (runId) =>\n request<MutationResult>(`${automationsBasePath}/runs/${encodeURIComponent(runId)}/cancel`, { method: 'POST' }),\n createAgentChat: async (input) =>\n request<{ chat: AgentChat }>(agentChatsBasePath, {\n body: JSON.stringify({ modelId: input?.modelId ?? null }),\n method: 'POST',\n }),\n deleteAgentChat: async (chatId) =>\n request<{ success: boolean }>(`${agentChatsBasePath}/${encodeURIComponent(chatId)}`, { method: 'DELETE' }),\n getAgentChatStreamUrl: (chatId, workflowRunId) =>\n `${agentChatsBasePath}/${encodeURIComponent(chatId)}/stream?workflowRunId=${encodeURIComponent(workflowRunId)}`,\n renameAgentChat: async (chatId, title) =>\n request<{ chat: AgentChat }>(`${agentChatsBasePath}/${encodeURIComponent(chatId)}`, {\n body: JSON.stringify({ title }),\n method: 'PATCH',\n }),\n sendAgentChatMessage: async (chatId, input) =>\n request<AgentChatTurn>(`${agentChatsBasePath}/${encodeURIComponent(chatId)}/messages`, {\n body: JSON.stringify(input),\n method: 'POST',\n }),\n sendAgentChatFollowUp: async (chatId, input) =>\n request<AgentChatFollowUpResult>(`${agentChatsBasePath}/${encodeURIComponent(chatId)}/follow-ups`, {\n body: JSON.stringify(input),\n method: 'POST',\n }),\n startAgentChat: async ({ attachments, content, modelId }) =>\n request<StartAgentChatResult>(agentChatsBasePath, {\n body: JSON.stringify({ message: { attachments, content }, modelId: modelId ?? null }),\n method: 'POST',\n }),\n startQueuedAgentChatMessage: async (chatId, messageId) =>\n request<AgentChatTurn>(\n `${agentChatsBasePath}/${encodeURIComponent(chatId)}/follow-ups/${encodeURIComponent(messageId)}/start`,\n { method: 'POST' }\n ),\n stopAgentChat: async (chatId) =>\n request<{ message: AgentChatMessage }>(`${agentChatsBasePath}/${encodeURIComponent(chatId)}/stop`, {\n method: 'POST',\n }),\n transcribeAgentAudio: async (audio, signal) => {\n const { durationSeconds, pcm } = await convertRecordedAudioToPcm(audio);\n const formData = new FormData();\n formData.append('file', pcm, 'audio.pcm');\n formData.append('durationSeconds', String(durationSeconds));\n\n const response = await fetch(`${projectBasePath}/agent/transcribe`, {\n body: formData,\n credentials: 'include',\n method: 'POST',\n signal,\n });\n const data = (await response.json()) as { error?: string; text?: string };\n\n if (!response.ok) {\n const error = data && typeof data === 'object' && data.error ? String(data.error) : 'Request failed';\n\n throw new Error(error);\n }\n\n if (!data.text?.trim()) {\n throw new Error('No speech was recognized. Try again.');\n }\n\n return { text: data.text };\n },\n uploadAgentChatAttachment: async (file, signal) => {\n // The platform issues a token scoped to one pathname, type and size; the\n // browser then writes the bytes to the store directly, so large files\n // never pass through the API function body limit.\n const tokenResponse = await fetch(`${projectBasePath}/agent/uploads`, {\n body: JSON.stringify({ filename: file.name, mediaType: file.type || null, sizeBytes: file.size }),\n credentials: 'include',\n headers: { 'Content-Type': 'application/json' },\n method: 'POST',\n signal,\n });\n const tokenData = (await tokenResponse.json()) as {\n code?: string;\n error?: string;\n mediaType?: string;\n pathname?: string;\n token?: string;\n };\n\n if (!tokenResponse.ok || !tokenData.pathname || !tokenData.token || !tokenData.mediaType) {\n throw new AgentUploadError(\n tokenResponse.status,\n tokenData.error ? String(tokenData.error) : 'The file could not be uploaded.',\n tokenData.code ?? null\n );\n }\n\n const blob = await put(tokenData.pathname, file, {\n abortSignal: signal,\n access: 'public',\n contentType: tokenData.mediaType,\n token: tokenData.token,\n });\n\n return {\n filename: file.name,\n mediaType: tokenData.mediaType,\n sizeBytes: file.size,\n url: blob.url,\n };\n },\n decideApproval: async (approvalId, input) => {\n const response = await fetch(`${automationsBasePath}/approvals/${encodeURIComponent(approvalId)}/decide`, {\n body: JSON.stringify(input),\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n });\n const data = (await response.json()) as MutationResult & { approval?: AutomationApproval; error?: string };\n\n // Business errors (stale_preview, already_decided) come back as 400\n // with a structured body the caller must be able to inspect.\n if (!response.ok && typeof data.success !== 'boolean') {\n throw new Error(data.error ? String(data.error) : 'Request failed');\n }\n\n return data;\n },\n markActivityRead: async (ids) =>\n request<{ success: boolean }>(`${projectBasePath}/activity/read`, {\n body: JSON.stringify(ids === 'all' ? { all: true } : { ids }),\n method: 'POST',\n }),\n setActivityItemState: async (itemId, state) =>\n request<{ item: ActivityItem }>(`${projectBasePath}/activity/${encodeURIComponent(itemId)}`, {\n body: JSON.stringify({ state }),\n method: 'PATCH',\n }),\n createAutomation: async (input) =>\n request<MutationResult & { automation?: Automation }>(automationsBasePath, {\n body: JSON.stringify(input),\n method: 'POST',\n }),\n createSkill: async (input) =>\n request<MutationResult & { skill?: Skill }>(skillsBasePath, {\n body: JSON.stringify(input),\n method: 'POST',\n }),\n deleteAutomation: async (automationId) =>\n request<MutationResult>(`${automationsBasePath}/${encodeURIComponent(automationId)}`, { method: 'DELETE' }),\n deleteSkill: async (skillId) =>\n request<MutationResult>(`${skillsBasePath}/${encodeURIComponent(skillId)}`, { method: 'DELETE' }),\n getArtifactUrl: (artifactId, options) => {\n const suffix = options?.download ? '?download=1' : '';\n\n return `${automationsBasePath}/artifacts/${encodeURIComponent(artifactId)}/content${suffix}`;\n },\n getRunArtifacts: async (workflowRunId) =>\n request<{ artifacts: AutomationArtifact[] }>(\n `${automationsBasePath}/runs/${encodeURIComponent(workflowRunId)}/artifacts`\n ).then((response) => response.artifacts),\n getStreamUrl: (workflowRunId) => `${automationsBasePath}/runs/${encodeURIComponent(workflowRunId)}/stream`,\n getTranscriptUrl: (runId) => `${automationsBasePath}/runs/${encodeURIComponent(runId)}/transcript`,\n listChannels: async (provider, connectionId) => {\n const url = connectionId\n ? `${projectBasePath}/plugin-connections/${encodeURIComponent(connectionId)}/channels`\n : `${projectBasePath}/plugins/${provider}/channels`;\n const response = await fetch(url, {\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n const data = (await response.json()) as {\n channels?: AutomationToolChannel[];\n error?: string;\n errorMessage?: string;\n success?: boolean;\n };\n\n if (response.ok) {\n return {\n channels: data.channels ?? [],\n errorMessage: data.errorMessage,\n success: data.success ?? true,\n };\n }\n\n if (data.success === false) {\n return {\n channels: data.channels ?? [],\n errorMessage: data.errorMessage ?? `Failed to load ${provider === 'slack' ? 'Slack' : 'Teams'} channels.`,\n success: false,\n };\n }\n\n const error = data.error ? String(data.error) : 'Request failed';\n\n throw new Error(error);\n },\n runAutomation: async (automationId) =>\n request<MutationResult & { runId?: string }>(`${automationsBasePath}/${encodeURIComponent(automationId)}/runs`, {\n method: 'POST',\n }),\n updateAutomation: async (automationId, input) =>\n request<MutationResult & { automation?: Automation }>(\n `${automationsBasePath}/${encodeURIComponent(automationId)}`,\n {\n body: JSON.stringify(input),\n method: 'PATCH',\n }\n ),\n updateSkill: async (skillId, input) =>\n request<MutationResult & { skill?: Skill }>(`${skillsBasePath}/${encodeURIComponent(skillId)}`, {\n body: JSON.stringify(input),\n method: 'PATCH',\n }),\n };\n}\n\nexport class FetcherError extends Error {\n status: number;\n\n constructor(status: number, message = 'Request failed') {\n super(message);\n this.name = 'FetcherError';\n this.status = status;\n }\n}\n\nexport const fetcher = async <T>(url: string): Promise<T> => {\n const response = await fetch(url, { credentials: 'include' });\n\n if (!response.ok) {\n throw new FetcherError(response.status);\n }\n\n return (await response.json()) as T;\n};\n\nexport function paths(projectId: string): {\n activity: (_options?: { filter?: 'all' | 'needs_action'; limit?: number; offset?: number }) => string;\n activityItem: (_itemId: string) => string;\n /** Badge counts; with `since`, also the unread items created after it. */\n activitySummary: (_since?: string | null) => string;\n agentChat: (_chatId: string) => string;\n agentChatSearch: (_query: string) => string;\n agentChats: (_offset?: number) => string;\n agentProfile: () => string;\n approval: (_approvalId: string) => string;\n approvals: (_options?: {\n limit?: number;\n offset?: number;\n runId?: string;\n status?: AutomationApprovalStatus;\n }) => string;\n approvalsCount: string;\n automation: (_automationId: string) => string;\n automationRuns: (_automationId: string, _offset?: number, _limit?: number) => string;\n automations: (_options?: {\n enabled?: boolean[];\n limit?: number;\n offset?: number;\n search?: string;\n visibility?: AutomationVisibility[];\n }) => string;\n creditBalance: string;\n entities: string;\n run: (_runId: string) => string;\n runHistory: (_scope: 'mine' | 'team', _offset?: number, _limit?: number) => string;\n skill: (_skillId: string) => string;\n skills: (_options?: { limit?: number; offset?: number; search?: string; visibility?: AutomationVisibility[] }) => string;\n spaces: string;\n /** Members for pickers; with a space id, only members who can see that space. */\n members: (_spaceId?: string | null) => string;\n tools: (_automationId?: string) => string;\n} {\n const basePath = `/api/flexkit/${projectId}/automations`;\n const skillsBasePath = `/api/flexkit/${projectId}/skills`;\n const agentChatsBasePath = `/api/flexkit/${projectId}/agent/chats`;\n\n return {\n activity: (options = {}) => {\n const { filter = 'all', limit = 25, offset = 0 } = options;\n const params = new URLSearchParams({ filter, limit: limit.toString(), offset: offset.toString() });\n\n return `/api/flexkit/${projectId}/activity?${params.toString()}`;\n },\n activityItem: (itemId) => `/api/flexkit/${projectId}/activity/${encodeURIComponent(itemId)}`,\n activitySummary: (since) =>\n since\n ? `/api/flexkit/${projectId}/activity/summary?since=${encodeURIComponent(since)}`\n : `/api/flexkit/${projectId}/activity/summary`,\n agentChat: (chatId) => `${agentChatsBasePath}/${encodeURIComponent(chatId)}`,\n agentChatSearch: (query) => `${agentChatsBasePath}/search?q=${encodeURIComponent(query)}`,\n agentChats: (offset = 0) => `${agentChatsBasePath}?offset=${offset.toString()}`,\n agentProfile: () => `/api/flexkit/${projectId}/agent/profile`,\n approval: (approvalId) => `${basePath}/approvals/${encodeURIComponent(approvalId)}`,\n approvals: (options = {}) => {\n const { limit = 25, offset = 0, runId, status } = options;\n const params = new URLSearchParams({\n limit: limit.toString(),\n offset: offset.toString(),\n });\n\n if (status) {\n params.set('status', status);\n }\n\n if (runId) {\n params.set('runId', runId);\n }\n\n return `${basePath}/approvals?${params.toString()}`;\n },\n approvalsCount: `${basePath}/approvals?limit=1`,\n automation: (automationId) => `${basePath}/${encodeURIComponent(automationId)}`,\n automationRuns: (automationId, offset = 0, limit = 25) =>\n `${basePath}/${encodeURIComponent(automationId)}/runs?offset=${offset.toString()}&limit=${limit.toString()}`,\n automations: (options = {}) => {\n const { enabled, limit = 25, offset = 0, search, visibility } = options;\n const params = new URLSearchParams({\n limit: limit.toString(),\n offset: offset.toString(),\n });\n\n if (enabled && enabled.length > 0) {\n params.set('enabled', enabled.map((value) => (value ? 'true' : 'false')).join(','));\n }\n\n if (visibility && visibility.length > 0) {\n params.set('visibility', visibility.join(','));\n }\n\n const trimmedSearch = search?.trim();\n\n if (trimmedSearch) {\n params.set('q', trimmedSearch);\n }\n\n return `${basePath}?${params.toString()}`;\n },\n creditBalance: `${basePath}/credits`,\n entities: `${basePath}/entities`,\n run: (runId) => `${basePath}/runs/${encodeURIComponent(runId)}`,\n runHistory: (scope, offset = 0, limit = 25) =>\n `${basePath}/runs?scope=${scope}&offset=${offset.toString()}&limit=${limit.toString()}`,\n skill: (skillId) => `${skillsBasePath}/${encodeURIComponent(skillId)}`,\n skills: (options = {}) => {\n const { limit = 25, offset = 0, search, visibility } = options;\n const params = new URLSearchParams({\n limit: limit.toString(),\n offset: offset.toString(),\n });\n\n if (visibility && visibility.length > 0) {\n params.set('visibility', visibility.join(','));\n }\n\n const trimmedSearch = search?.trim();\n\n if (trimmedSearch) {\n params.set('q', trimmedSearch);\n }\n\n return `${skillsBasePath}?${params.toString()}`;\n },\n spaces: `/api/flexkit/${projectId}/spaces`,\n members: (spaceId) =>\n spaceId\n ? `/api/flexkit/${projectId}/members?spaceId=${encodeURIComponent(spaceId)}`\n : `/api/flexkit/${projectId}/members`,\n tools: (automationId) =>\n automationId ? `${basePath}/${encodeURIComponent(automationId)}/tools` : `${basePath}/tools`,\n };\n}\n"]}
@@ -1,2 +0,0 @@
1
- import'./index.css';import {d}from'./chunk-TYDYAOQ7.js';import {createContext,useState,useEffect,useContext}from'react';import m from'swr';var v=createContext(true);function A(){return useContext(v)}function f(){return typeof document>"u"||document.visibilityState==="visible"&&document.hasFocus()}function P(){let t=A(),[i,n]=useState(f);return useEffect(()=>{let e=()=>n(f());return e(),window.addEventListener("focus",e),window.addEventListener("blur",e),document.addEventListener("visibilitychange",e),()=>{window.removeEventListener("focus",e),window.removeEventListener("blur",e),document.removeEventListener("visibilitychange",e);}},[]),t&&i}var g="1970-01-01T00:00:00.000Z";function T(t){return t.chatId?`agent/chats/${t.chatId}`:t.automationId&&t.automationRunId?`automations/${t.automationId}/runs/${t.automationRunId}`:null}function R(t){return t.chatId?"View chat":t.automationId&&t.automationRunId?"View run":null}var b={approved:"Approved",cancelled:"Cancelled",expired:"Expired",rejected:"Rejected"};function L(t){return t.kind==="automation_failure"?"Failed":t.kind==="automation_result"?"Result":t.resolution?b[t.resolution]:t.requiresAction&&t.state!=="done"&&t.state!=="dismissed"?"Needs approval":null}function O(t){return t.kind==="automation_failure"?"failure":I(t)?"attention":"neutral"}function I(t){return t.requiresAction&&t.resolvedAt===null&&t.state!=="dismissed"&&t.state!=="done"}function K({mutedKinds:t=[],newItems:i,since:n}){let e=i.reduce((o,u)=>o===null||u.createdAt>o?u.createdAt:o,null);if(n===null)return {notifications:[],since:e??g};let r=i.filter(o=>o.createdAt>n&&!t.includes(o.kind)),a=e!==null&&e>n?e:n;return r.length===0?{notifications:[],since:a}:r.length>3?{notifications:[{body:"Open Activity in Flexkit Studio to review them.",path:"activity",tag:`flexkit-activity-batch:${a}`,title:`${r.length.toString()} new items in Activity`}],since:a}:{notifications:r.map(o=>({body:o.body??"",path:`activity/${encodeURIComponent(o.id)}`,tag:`flexkit-activity:${o.id}`,title:o.title})),since:a}}var h={approvalEmail:true,desktopMutedKinds:[]};async function c(t,i){let n=await fetch(t,{credentials:"same-origin",...i,headers:{"Content-Type":"application/json",...i?.headers}});if(!n.ok)throw new Error(`Request failed with ${n.status.toString()}.`);return await n.json()}function _(){let{data:t,error:i,mutate:n}=m(d.notificationPreferences,e=>c(e));return {isLoaded:t!==void 0||i!==void 0,mutate:n,preferences:t?.preferences??h}}function $(t){return c(d.notificationPreferences,{body:JSON.stringify(t),method:"PUT"})}function w(){return typeof window<"u"&&typeof Notification<"u"&&"serviceWorker"in navigator&&"PushManager"in window}function S(t){let i=`${t}${"=".repeat((4-t.length%4)%4)}`.replace(/-/g,"+").replace(/_/g,"/"),n=atob(i),e=new Uint8Array(new ArrayBuffer(n.length));for(let r=0;r<n.length;r+=1)e[r]=n.charCodeAt(r);return e}async function M(){if(!w()||Notification.permission!=="granted")return false;let{publicKey:t}=await c(d.push);if(!t)return false;await navigator.serviceWorker.register("/sw.js",{scope:"/"});let{pushManager:i}=await navigator.serviceWorker.ready,n=S(t),e=await i.getSubscription();return e&&!N(e.options.applicationServerKey,n)&&(await e.unsubscribe(),e=null),e??=await i.subscribe({applicationServerKey:n,userVisibleOnly:true}),await c(d.push,{body:JSON.stringify(e.toJSON()),method:"POST"}),true}function N(t,i){return !t||t.byteLength!==i.byteLength?false:new Uint8Array(t).every((e,r)=>e===i[r])}export{v as a,P as b,T as c,R as d,L as e,O as f,I as g,K as h,_ as i,$ as j,M as k};//# sourceMappingURL=chunk-LP2JI25S.js.map
2
- //# sourceMappingURL=chunk-LP2JI25S.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/core/apps/app-active.ts","../src/apps/ai/activity.ts","../src/apps/ai/notification-settings.ts"],"names":["AppActiveContext","createContext","useIsAppActive","useContext","isWindowInFront","useIsViewing","isAppActive","isInFront","setIsInFront","useState","useEffect","update","EPOCH","getActivitySourcePath","item","getActivitySourceLabel","RESOLUTION_LABELS","getActivityStatusLabel","getActivityStatusTone","isActivityItemOpen","planActivityNotifications","mutedKinds","newItems","since","newest","latest","fresh","nextSince","DEFAULT_NOTIFICATION_PREFERENCES","userRequest","url","init","response","useNotificationPreferences","data","error","mutate","useSWR","userApiPaths","saveNotificationPreferences","preferences","isWebPushSupported","decodeApplicationServerKey","base64Url","base64","binary","bytes","index","ensurePushSubscription","publicKey","pushManager","applicationServerKey","subscription","sameKey","current","expected","byte"],"mappings":"2IAO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CAAAA,EAAWA,EAAQ,UAAA,GAAeC,CAAAA,CAAS,UAAA,CACvC,KAAA,CAGK,IAAI,UAAA,CAAWD,CAAO,CAAA,CAEvB,KAAA,CAAM,CAACE,CAAAA,CAAMT,CAAAA,GAAUS,IAASD,CAAAA,CAASR,CAAK,CAAC,CAC9D","file":"chunk-LP2JI25S.js","sourcesContent":["import { createContext, useContext, useEffect, useState } from 'react';\n\n/**\n * Whether the app around a component is the one in front. Opened apps stay\n * mounted behind the active one (see `AppOutlet`), so their effects keep\n * running; this tells them apart. Outside an app it is `true`.\n */\nexport const AppActiveContext = createContext(true);\n\nexport function useIsAppActive(): boolean {\n return useContext(AppActiveContext);\n}\n\nfunction isWindowInFront(): boolean {\n return typeof document === 'undefined' || (document.visibilityState === 'visible' && document.hasFocus());\n}\n\n/**\n * The person is looking at this app right now: it is the app in front, the\n * tab is visible and the browser window has focus.\n */\nexport function useIsViewing(): boolean {\n const isAppActive = useIsAppActive();\n const [isInFront, setIsInFront] = useState(isWindowInFront);\n\n useEffect(() => {\n const update = (): void => setIsInFront(isWindowInFront());\n\n update();\n window.addEventListener('focus', update);\n window.addEventListener('blur', update);\n document.addEventListener('visibilitychange', update);\n\n return () => {\n window.removeEventListener('focus', update);\n window.removeEventListener('blur', update);\n document.removeEventListener('visibilitychange', update);\n };\n }, []);\n\n return isAppActive && isInFront;\n}\n","import type { ActivityItem, ActivityItemKind, ActivityItemResolution } from './types';\n\n/** More new items than this in one poll are announced by a single summary notification. */\nconst MAX_SEPARATE_NOTIFICATIONS = 3;\n\n/** Watermark before the first item exists: every later unread item is new. */\nconst EPOCH = '1970-01-01T00:00:00.000Z';\n\nexport interface ActivityNotification {\n body: string;\n /** AI-app relative path opened on click, e.g. `activity/<id>`. */\n path: string;\n /** Same tag = same notification across tabs and repeated polls. */\n tag: string;\n title: string;\n}\n\n/** Path, relative to the AI app, of the chat or run an item came from. */\nexport function getActivitySourcePath(item: ActivityItem): string | null {\n if (item.chatId) {\n return `agent/chats/${item.chatId}`;\n }\n\n if (item.automationId && item.automationRunId) {\n return `automations/${item.automationId}/runs/${item.automationRunId}`;\n }\n\n return null;\n}\n\nexport function getActivitySourceLabel(item: ActivityItem): string | null {\n if (item.chatId) {\n return 'View chat';\n }\n\n return item.automationId && item.automationRunId ? 'View run' : null;\n}\n\nconst RESOLUTION_LABELS: { [key in ActivityItemResolution]: string } = {\n approved: 'Approved',\n cancelled: 'Cancelled',\n expired: 'Expired',\n rejected: 'Rejected',\n};\n\n/** Short status for a row: what happened to it, or that it still waits on the viewer. */\nexport function getActivityStatusLabel(item: ActivityItem): string | null {\n if (item.kind === 'automation_failure') {\n return 'Failed';\n }\n\n if (item.kind === 'automation_result') {\n return 'Result';\n }\n\n if (item.resolution) {\n return RESOLUTION_LABELS[item.resolution];\n }\n\n return item.requiresAction && item.state !== 'done' && item.state !== 'dismissed' ? 'Needs approval' : null;\n}\n\n/** How a row's status badge reads: waiting on the viewer, a failure, or neutral. */\nexport function getActivityStatusTone(item: ActivityItem): 'attention' | 'failure' | 'neutral' {\n if (item.kind === 'automation_failure') {\n return 'failure';\n }\n\n return isActivityItemOpen(item) ? 'attention' : 'neutral';\n}\n\n/** True while the item still waits on the viewer. */\nexport function isActivityItemOpen(item: ActivityItem): boolean {\n return item.requiresAction && item.resolvedAt === null && item.state !== 'dismissed' && item.state !== 'done';\n}\n\n/**\n * Turns one summary poll into desktop notifications and the next watermark.\n * The first poll (no watermark yet) only seeds it, so opening Studio never\n * replays notifications for items the user already had.\n */\nexport function planActivityNotifications({\n mutedKinds = [],\n newItems,\n since,\n}: {\n /** Kinds the viewer turned off for desktop notifications; they still move the watermark. */\n mutedKinds?: ActivityItemKind[];\n newItems: ActivityItem[];\n since: string | null;\n}): { notifications: ActivityNotification[]; since: string } {\n const newest = newItems.reduce<string | null>(\n (latest, item) => (latest === null || item.createdAt > latest ? item.createdAt : latest),\n null\n );\n\n if (since === null) {\n return { notifications: [], since: newest ?? EPOCH };\n }\n\n const fresh = newItems.filter((item) => item.createdAt > since && !mutedKinds.includes(item.kind));\n const nextSince = newest !== null && newest > since ? newest : since;\n\n if (fresh.length === 0) {\n return { notifications: [], since: nextSince };\n }\n\n if (fresh.length > MAX_SEPARATE_NOTIFICATIONS) {\n return {\n notifications: [\n {\n body: 'Open Activity in Flexkit Studio to review them.',\n path: 'activity',\n tag: `flexkit-activity-batch:${nextSince}`,\n title: `${fresh.length.toString()} new items in Activity`,\n },\n ],\n since: nextSince,\n };\n }\n\n return {\n notifications: fresh.map((item) => ({\n body: item.body ?? '',\n path: `activity/${encodeURIComponent(item.id)}`,\n tag: `flexkit-activity:${item.id}`,\n title: item.title,\n })),\n since: nextSince,\n };\n}\n","import useSWR, { type KeyedMutator } from 'swr';\nimport { userApiPaths } from '../../core/api-paths';\nimport type { ActivityItemKind } from './types';\n\n/** A person's notification choices, shared by every project they open. */\nexport interface NotificationPreferences {\n /** Email an approval request left unread past the project's delay. */\n approvalEmail: boolean;\n /** Kinds that never raise a desktop notification. */\n desktopMutedKinds: ActivityItemKind[];\n}\n\nexport const DEFAULT_NOTIFICATION_PREFERENCES: NotificationPreferences = { approvalEmail: true, desktopMutedKinds: [] };\n\nasync function userRequest<T>(url: string, init?: RequestInit): Promise<T> {\n const response = await fetch(url, {\n credentials: 'same-origin',\n ...init,\n headers: { 'Content-Type': 'application/json', ...init?.headers },\n });\n\n if (!response.ok) {\n throw new Error(`Request failed with ${response.status.toString()}.`);\n }\n\n return (await response.json()) as T;\n}\n\nexport function useNotificationPreferences(): {\n /** False until the stored preferences arrived (or could not be loaded, which means the defaults). */\n isLoaded: boolean;\n mutate: KeyedMutator<{ preferences: NotificationPreferences }>;\n preferences: NotificationPreferences;\n} {\n const { data, error, mutate } = useSWR<{ preferences: NotificationPreferences }>(\n userApiPaths.notificationPreferences,\n (url: string) => userRequest<{ preferences: NotificationPreferences }>(url)\n );\n\n return {\n isLoaded: data !== undefined || error !== undefined,\n mutate,\n preferences: data?.preferences ?? DEFAULT_NOTIFICATION_PREFERENCES,\n };\n}\n\nexport function saveNotificationPreferences(preferences: NotificationPreferences): Promise<{ preferences: NotificationPreferences }> {\n return userRequest(userApiPaths.notificationPreferences, { body: JSON.stringify(preferences), method: 'PUT' });\n}\n\nexport function isWebPushSupported(): boolean {\n return (\n typeof window !== 'undefined' &&\n typeof Notification !== 'undefined' &&\n 'serviceWorker' in navigator &&\n 'PushManager' in window\n );\n}\n\n/** The VAPID public key as the bytes `PushManager.subscribe` expects. */\nexport function decodeApplicationServerKey(base64Url: string): Uint8Array<ArrayBuffer> {\n const base64 = `${base64Url}${'='.repeat((4 - (base64Url.length % 4)) % 4)}`.replace(/-/g, '+').replace(/_/g, '/');\n const binary = atob(base64);\n const bytes = new Uint8Array(new ArrayBuffer(binary.length));\n\n for (let index = 0; index < binary.length; index += 1) {\n bytes[index] = binary.charCodeAt(index);\n }\n\n return bytes;\n}\n\n/**\n * Hosted Studio only: registers the service worker and saves this browser's\n * push subscription for the signed-in user, so Activity items arrive while no\n * Studio tab is open. Needs notification permission; never asks for it.\n * Safe to call on every load: an existing subscription is saved again.\n * Returns false when Web Push is unavailable here.\n */\nexport async function ensurePushSubscription(): Promise<boolean> {\n if (!isWebPushSupported() || Notification.permission !== 'granted') {\n return false;\n }\n\n const { publicKey } = await userRequest<{ publicKey: string | null }>(userApiPaths.push);\n\n if (!publicKey) {\n return false;\n }\n\n await navigator.serviceWorker.register('/sw.js', { scope: '/' });\n\n const { pushManager } = await navigator.serviceWorker.ready;\n const applicationServerKey = decodeApplicationServerKey(publicKey);\n let subscription = await pushManager.getSubscription();\n\n // A subscription made with an older key would never receive again.\n if (subscription && !sameKey(subscription.options.applicationServerKey, applicationServerKey)) {\n await subscription.unsubscribe();\n subscription = null;\n }\n\n subscription ??= await pushManager.subscribe({ applicationServerKey, userVisibleOnly: true });\n\n await userRequest(userApiPaths.push, { body: JSON.stringify(subscription.toJSON()), method: 'POST' });\n\n return true;\n}\n\nfunction sameKey(current: ArrayBuffer | null, expected: Uint8Array): boolean {\n if (!current || current.byteLength !== expected.byteLength) {\n return false;\n }\n\n const bytes = new Uint8Array(current);\n\n return bytes.every((byte, index) => byte === expected[index]);\n}\n"]}