@flexkit/studio 0.2.3 → 0.2.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/activity-nav-button-AESIPODJ.js +2 -0
- package/dist/{activity-nav-button-Z6M3FURW.js.map → activity-nav-button-AESIPODJ.js.map} +1 -1
- package/dist/{chat-page-J7I5V6G4.js → chat-page-S2YGOKO5.js} +3 -3
- package/dist/{chat-page-J7I5V6G4.js.map → chat-page-S2YGOKO5.js.map} +1 -1
- package/dist/{chunk-BP27UNNR.js → chunk-2AHDTE5T.js} +2 -2
- package/dist/{chunk-BP27UNNR.js.map → chunk-2AHDTE5T.js.map} +1 -1
- package/dist/chunk-3TGCCDOR.js +2 -0
- package/dist/chunk-3TGCCDOR.js.map +1 -0
- package/dist/{chunk-QJDD73JR.js → chunk-6RDPFMLK.js} +2 -2
- package/dist/{chunk-QJDD73JR.js.map → chunk-6RDPFMLK.js.map} +1 -1
- package/dist/{chunk-MM356YIK.js → chunk-CKNFYN3O.js} +3 -3
- package/dist/chunk-CKNFYN3O.js.map +1 -0
- package/dist/chunk-J2G4C6I5.js +2 -0
- package/dist/chunk-J2G4C6I5.js.map +1 -0
- package/dist/{chunk-G74PT7Z7.js → chunk-KWS3NAYS.js} +3 -3
- package/dist/{chunk-G74PT7Z7.js.map → chunk-KWS3NAYS.js.map} +1 -1
- package/dist/{chunk-76CL7HSO.js → chunk-LN55VJ35.js} +3 -3
- package/dist/{chunk-76CL7HSO.js.map → chunk-LN55VJ35.js.map} +1 -1
- package/dist/{chunk-IAA4CEBW.js → chunk-NOFQHWES.js} +2 -2
- package/dist/{chunk-IAA4CEBW.js.map → chunk-NOFQHWES.js.map} +1 -1
- package/dist/{chunk-MPLNRUP3.js → chunk-NYKATVPZ.js} +3 -3
- package/dist/{chunk-MPLNRUP3.js.map → chunk-NYKATVPZ.js.map} +1 -1
- package/dist/{chunk-QDXGSL5B.js → chunk-PWQPA2QL.js} +2 -2
- package/dist/{chunk-QDXGSL5B.js.map → chunk-PWQPA2QL.js.map} +1 -1
- package/dist/chunk-SVZY7ZZD.js +8 -0
- package/dist/chunk-SVZY7ZZD.js.map +1 -0
- package/dist/index.css +19 -0
- package/dist/index.d.ts +11 -1
- package/dist/index.js +1 -1
- package/dist/{list-IBUZ2LXU.js → list-PNKQAYUK.js} +2 -2
- package/dist/{list-IBUZ2LXU.js.map → list-PNKQAYUK.js.map} +1 -1
- package/dist/pages-KHFSZ3PH.js +3 -0
- package/dist/pages-KHFSZ3PH.js.map +1 -0
- package/dist/{plugin-pages-HQPZQSZT.js → plugin-pages-SE52XFFW.js} +2 -2
- package/dist/{plugin-pages-HQPZQSZT.js.map → plugin-pages-SE52XFFW.js.map} +1 -1
- package/dist/{root-XGNAKO5P.js → root-44ZJLA4E.js} +2 -2
- package/dist/{root-XGNAKO5P.js.map → root-44ZJLA4E.js.map} +1 -1
- package/dist/{root-ZY2HGDBT.js → root-BH3PQS2H.js} +3 -3
- package/dist/{root-ZY2HGDBT.js.map → root-BH3PQS2H.js.map} +1 -1
- package/dist/{root-4UVGZZRU.js → root-LFQA2VSE.js} +2 -2
- package/dist/{root-4UVGZZRU.js.map → root-LFQA2VSE.js.map} +1 -1
- package/dist/{root-HUJPHUHL.js → root-X5NDURAN.js} +3 -3
- package/dist/{root-HUJPHUHL.js.map → root-X5NDURAN.js.map} +1 -1
- package/dist/{search-N7G6BVN6.js → search-Q65IC67C.js} +2 -2
- package/dist/{search-N7G6BVN6.js.map → search-Q65IC67C.js.map} +1 -1
- package/dist/{skills-pages-VP32HFUN.js → skills-pages-TWOIIU5J.js} +2 -2
- package/dist/{skills-pages-VP32HFUN.js.map → skills-pages-TWOIIU5J.js.map} +1 -1
- package/package.json +3 -3
- package/dist/activity-nav-button-Z6M3FURW.js +0 -2
- package/dist/chunk-72TZUR4Q.js +0 -2
- package/dist/chunk-72TZUR4Q.js.map +0 -1
- package/dist/chunk-AN4APNXO.js +0 -2
- package/dist/chunk-AN4APNXO.js.map +0 -1
- package/dist/chunk-K7FD54PW.js +0 -6
- package/dist/chunk-K7FD54PW.js.map +0 -1
- package/dist/chunk-MM356YIK.js.map +0 -1
- package/dist/pages-ZKDDV5T3.js +0 -3
- package/dist/pages-ZKDDV5T3.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
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,EAAE,SAAA,CAAYC,CAAAA,CAAE,UAAY,EAAA,CAAK,CAAA,CAGtCD,EAAE,EAAA,GAAOC,CAAAA,CAAE,EAAA,CACN,CAAA,CAGFD,EAAE,EAAA,CAAKC,CAAAA,CAAE,G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AAA,CACb,SAAAD,IAAAA,CAAC,KAAA,CAAA,CACC,UAAWgR,GAAAA,CACT,8DAAA,CACAZ,IAAa,gCACf,CAAA,CAEC,QAAA,CAAA,CAACA,EAAAA,CAcAnQ,IAACgN,EAAAA,CAAA,CAAkB,SAAA,CAAWgD,CAAAA,CAAe,EAX7ChQ,GAAAA,CAACgR,CAAAA,CAAoB,QAAA,CAApB,CAA6B,MAAK,IAAA,CACjC,QAAA,CAAAhR,IAACwI,EAAAA,CAAA,CACC,IAAKuH,CAAAA,CACL,MAAA,CAAQlT,CAAAA,EAAU,IAAA,CAClB,gBAAiBkS,EAAAA,CACjB,cAAA,CAAgBF,IAChB,SAAA,CAAWjS,GAAAA,CACX,cAAe+L,CAAAA,CACjB,CAAA,CACF,CAAA,CAIF5I,IAAAA,CAAC,OAAI,SAAA,CAAU,qBAAA,CACZ,UAAAiP,CAAAA,CACChP,GAAAA,CAAC,KAAE,SAAA,CAAU,gEAAA,CAAkE,QAAA,CAAAgP,CAAAA,CAAU,EACvF,IAAA,CACJhP,GAAAA,CAAC4E,GAAA,CACC,GAAA,CAAKmL,EACL,MAAA,CAAQlL,EAAAA,CACR,QAAA,CAAUC,CAAAA,CACV,aAAcC,EAAAA,CACd,MAAA,CAAQC,EACR,OAAA,CAASO,CAAAA,CACT,UAAW6K,EAAAA,CACX,cAAA,CAAgBP,CAAAA,CAChB,OAAA,CAASZ,EACT,aAAA,CAAeU,CAAAA,CACf,OAAQY,EAAAA,CACR,MAAA,CAAQI,GACR,WAAA,CACEP,EAAAA,CAAiB,mCAAA,CAAsC,CAAA,2BAAA,EAA8BH,EAAW,CAAA,GAAA,CAAA,CAEpG,CAAA,CAAA,CACF,GACF,CAAA,CACF,CAAA,CAAA,CACF,GACF,CAEJ","file":"chat-page-J7I5V6G4.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
|
+
{"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,EAAE,SAAA,CAAYC,CAAAA,CAAE,UAAY,EAAA,CAAK,CAAA,CAGtCD,EAAE,EAAA,GAAOC,CAAAA,CAAE,EAAA,CACN,CAAA,CAGFD,EAAE,EAAA,CAAKC,CAAAA,CAAE,GAAK,EAAA,CAAK,CAC5B,CAGO,SAASE,EAAAA,CAAiBC,CAAAA,CAAkD,CAGjF,OAAO,CAAC,GAFK,IAAI,GAAA,CAAIA,EAAS,GAAA,CAAKC,CAAAA,EAAY,CAACA,CAAAA,CAAQ,GAAIA,CAAO,CAAC,CAAC,CAAA,CAErD,MAAA,EAAQ,CAAA,CAAE,IAAA,CAAKN,EAAmB,CACpD,CAWO,SAASO,EAAAA,CACdC,CAAAA,CACAC,CAAAA,CAC6B,CAC7B,GAAI,CAACA,CAAAA,CACH,OAAOD,EAGT,GAAI,CAACA,EACH,OAAOC,CAAAA,CAGT,IAAMC,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B,cAAA,CAAgBF,IAChB,SAAA,CAAWjS,GAAAA,CACX,cAAe+L,CAAAA,CACjB,CAAA,CACF,CAAA,CAIF5I,IAAAA,CAAC,OAAI,SAAA,CAAU,qBAAA,CACZ,UAAAiP,CAAAA,CACChP,GAAAA,CAAC,KAAE,SAAA,CAAU,gEAAA,CAAkE,QAAA,CAAAgP,CAAAA,CAAU,EACvF,IAAA,CACJhP,GAAAA,CAAC4E,GAAA,CACC,GAAA,CAAKmL,EACL,MAAA,CAAQlL,EAAAA,CACR,QAAA,CAAUC,CAAAA,CACV,aAAcC,EAAAA,CACd,MAAA,CAAQC,EACR,OAAA,CAASO,CAAAA,CACT,UAAW6K,EAAAA,CACX,cAAA,CAAgBP,CAAAA,CAChB,OAAA,CAASZ,EACT,aAAA,CAAeU,CAAAA,CACf,OAAQY,EAAAA,CACR,MAAA,CAAQI,GACR,WAAA,CACEP,EAAAA,CAAiB,mCAAA,CAAsC,CAAA,2BAAA,EAA8BH,EAAW,CAAA,GAAA,CAAA,CAEpG,CAAA,CAAA,CACF,GACF,CAAA,CACF,CAAA,CAAA,CACF,GACF,CAEJ","file":"chat-page-S2YGOKO5.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,2 +1,2 @@
|
|
|
1
|
-
import'./index.css';import {q}from'./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import'./index.css';import {q}from'./chunk-SVZY7ZZD.js';import {g,f}from'./chunk-CKNFYN3O.js';import {s}from'./chunk-YCCFUGWJ.js';import {c,h as h$1,i,k,j as j$1}from'./chunk-32ZU4MLE.js';import {e,g as g$1,h,j}from'./chunk-SZEGGBOC.js';import {b}from'./chunk-6NRQMG26.js';import {useState,useEffect,useMemo,useTransition}from'react';import {LoaderCircle,MessageSquareIcon,MoreHorizontalIcon,PencilIcon,Trash2Icon}from'lucide-react';import {useLocation,useNavigate}from'react-router-dom';import H,{useSWRConfig}from'swr';import U from'swr/infinite';import {jsx,jsxs}from'react/jsx-runtime';function ue(){let a=useLocation(),n="/agent",t=a.pathname.indexOf(n);return t===-1?`${a.pathname.replace(/\/$/,"")}/agent`:a.pathname.slice(0,t+n.length)}function de(a,n){let[t,o]=useState(a);return useEffect(()=>{let f=window.setTimeout(()=>{o(a);},n);return ()=>{window.clearTimeout(f);}},[n,a]),t}function Z(a){let n=new Date(a.lastMessageAt??a.updatedAt).getTime(),t=new Date,o=new Date(t.getFullYear(),t.getMonth(),t.getDate()).getTime();return n>=o?"Today":n>=o-864e5?"Yesterday":n>=o-7*864e5?"Previous 7 days":"Older"}function ee(a){let n=[];for(let t of a){let o=Z(t),f=n.find(u=>u.label===o);f?f.chats.push(t):n.push({chats:[t],label:o});}return n}function te({active:a,api:n,chat:t,onChanged:o,onDeleted:f,onOpen:u}){let[r,l]=useState(null),[g,d]=useState(t.title??""),[p,D]=useTransition(),k$1=t.title?.trim()||"New chat";function v(){D(async()=>{await n.renameAgentChat(t.id,g.trim()),l(null),o();});}function y(){D(async()=>{await n.deleteAgentChat(t.id),l(null),f();});}return jsxs("div",{className:`fk:group/chat fk:flex fk:items-center fk:gap-1 fk:rounded-md fk:pr-1 ${a?"fk:bg-sidebar-accent":"fk:hover:bg-accent/60"} fk:corner-squircle`,children:[jsx("button",{className:"fk:min-w-0 fk:flex-1 fk:truncate fk:px-2 fk:py-1.5 fk:text-left fk:text-sm",title:k$1,type:"button",onClick:u,children:k$1}),jsxs(e,{children:[jsx(g$1,{asChild:true,children:jsx(b,{className:"fk:size-6 fk:shrink-0 fk:opacity-0 fk:group-hover/chat:opacity-100 fk:data-[state=open]:opacity-100",size:"icon",variant:"ghost",children:jsx(MoreHorizontalIcon,{className:"fk:size-4"})})}),jsxs(h,{align:"start",children:[jsxs(j,{onClick:()=>{d(t.title??""),l("rename");},children:[jsx(PencilIcon,{className:"fk:size-4"}),"Rename"]}),jsxs(j,{className:"fk:text-destructive",onClick:()=>l("delete"),children:[jsx(Trash2Icon,{className:"fk:size-4"}),"Delete"]})]})]}),jsx(c,{open:r==="rename",onOpenChange:m=>l(m?"rename":null),children:jsxs(h$1,{className:"fk:max-w-sm",children:[jsx(i,{children:jsx(k,{children:"Rename chat"})}),jsx(s,{value:g,onChange:m=>d(m.target.value),placeholder:"Chat title"}),jsx(j$1,{children:jsx(b,{disabled:p||!g.trim(),size:"sm",onClick:v,children:p?"Saving...":"Save"})})]})}),jsx(c,{open:r==="delete",onOpenChange:m=>l(m?"delete":null),children:jsxs(h$1,{className:"fk:max-w-sm",children:[jsx(i,{children:jsx(k,{children:"Delete chat?"})}),jsxs("p",{className:"fk:text-sm fk:text-muted-foreground",children:["\u201C",k$1,"\u201D and its messages will be permanently deleted."]}),jsx(j$1,{children:jsx(b,{disabled:p,size:"sm",variant:"destructive",onClick:y,children:p?"Deleting...":"Delete"})})]})})]})}function ne({onOpen:a,projectId:n,query:t}){let{data:o,isLoading:f$1}=H(g(n).agentChatSearch(t),f,{keepPreviousData:true});return f$1&&!o?jsxs("div",{className:"fk:flex fk:items-center fk:gap-2 fk:px-2 fk:py-3 fk:text-xs fk:text-muted-foreground",children:[jsx(LoaderCircle,{className:"fk:size-3.5 fk:animate-spin"}),"Searching..."]}):o?.results.length?jsx("div",{className:"fk:space-y-1",children:o.results.map(u=>jsxs("button",{className:"fk:block fk:w-full fk:rounded-md fk:px-2 fk:py-1.5 fk:text-left fk:hover:bg-accent/60 fk:corner-squircle",type:"button",onClick:()=>a(u.chatId),children:[jsx("span",{className:"fk:block fk:truncate fk:text-sm",children:u.chatTitle?.trim()||"New chat"}),jsx("span",{className:"fk:block fk:truncate fk:text-xs fk:text-muted-foreground",children:u.snippet})]},u.messageId))}):jsx("p",{className:"fk:px-2 fk:py-3 fk:text-xs fk:text-muted-foreground",children:"No matching chats."})}function me({query:a}){let{api:n,projectId:t}=q(),o=useNavigate(),f$1=useLocation(),{mutate:u}=useSWRConfig(),r=/\/agent\/chats\/([^/]+)/.exec(f$1.pathname)?.[1],{data:l,isLoading:g$1,mutate:d,setSize:p,size:D}=U((s,c)=>!t||c&&!c.hasMore?null:g(t).agentChats(s*30),f,{revalidateFirstPage:true}),{data:k}=H(t&&r?g(t).agentChat(r):null,f),v=useMemo(()=>{let s=(l??[]).flatMap(h=>h.chats),c=k?.chat.title?.trim();return !r||!c?s:s.map(h=>h.id!==r||h.title?.trim()?h:{...h,title:c})},[k?.chat.title,r,l]),y=l?.[l.length-1]?.hasMore??false,m=useMemo(()=>ee(v),[v]);if(useEffect(()=>{d();},[r,d]),!t||!n)return null;let J=n,z=t;function L(s){o(`agent/chats/${s}`);}function X(s){d(),s===r?o("agent"):u(g(z).agentChat(s),void 0,{revalidate:false});}return jsx("div",{className:"fk:space-y-2",children:a?jsx(ne,{projectId:z,query:a,onOpen:L}):jsxs("div",{className:"fk:space-y-3",children:[m.map(s=>jsxs("div",{children:[jsx("p",{className:"fk:px-2 fk:pb-1 fk:text-xs fk:font-medium fk:text-muted-foreground",children:s.label}),jsx("div",{className:"fk:space-y-0.5",children:s.chats.map(c=>jsx(te,{active:c.id===r,api:J,chat:c,onChanged:()=>{d();},onDeleted:()=>X(c.id),onOpen:()=>L(c.id)},c.id))})]},s.label)),g$1?jsxs("div",{className:"fk:flex fk:items-center fk:gap-2 fk:px-2 fk:py-3 fk:text-xs fk:text-muted-foreground",children:[jsx(LoaderCircle,{className:"fk:size-3.5 fk:animate-spin"}),"Loading recent chats..."]}):null,!g$1&&v.length===0?jsxs("div",{className:"fk:flex fk:flex-col fk:items-center fk:gap-2 fk:px-2 fk:py-6 fk:text-center fk:text-xs fk:text-muted-foreground",children:[jsx(MessageSquareIcon,{className:"fk:size-5"}),jsx("span",{children:"No chats yet. Start a conversation with the agent."})]}):null,y?jsx(b,{className:"fk:w-full",size:"sm",variant:"ghost",onClick:()=>{p(D+1);},children:"Load more"}):null]})})}export{ue as a,de as b,me as c};//# sourceMappingURL=chunk-2AHDTE5T.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-2AHDTE5T.js.map
|