@flexkit/studio 0.2.36 → 0.2.37
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chat-page-NDVHLH5Q.js → chat-page-XYQOQPMW.js} +3 -3
- package/dist/{chat-page-NDVHLH5Q.js.map → chat-page-XYQOQPMW.js.map} +1 -1
- package/dist/{chunk-FXUD4JRG.js → chunk-337GX2BR.js} +2 -2
- package/dist/{chunk-FXUD4JRG.js.map → chunk-337GX2BR.js.map} +1 -1
- package/dist/{chunk-VIBGMCLS.js → chunk-36YXPN42.js} +2 -2
- package/dist/{chunk-VIBGMCLS.js.map → chunk-36YXPN42.js.map} +1 -1
- package/dist/{chunk-FF5EBXYN.js → chunk-6NRMVVU4.js} +3 -3
- package/dist/{chunk-FF5EBXYN.js.map → chunk-6NRMVVU4.js.map} +1 -1
- package/dist/{chunk-LXLEUEWT.js → chunk-AQSL5HBZ.js} +2 -2
- package/dist/{chunk-LXLEUEWT.js.map → chunk-AQSL5HBZ.js.map} +1 -1
- package/dist/{chunk-NKDQQHCL.js → chunk-BHHLWGZ4.js} +2 -2
- package/dist/{chunk-NKDQQHCL.js.map → chunk-BHHLWGZ4.js.map} +1 -1
- package/dist/{chunk-TWA6OG5U.js → chunk-CC2U7ASG.js} +3 -3
- package/dist/{chunk-TWA6OG5U.js.map → chunk-CC2U7ASG.js.map} +1 -1
- package/dist/{chunk-HXPETSXC.js → chunk-CRTUZ22E.js} +3 -3
- package/dist/{chunk-HXPETSXC.js.map → chunk-CRTUZ22E.js.map} +1 -1
- package/dist/{chunk-FJS4SN3K.js → chunk-DO32GATF.js} +3 -3
- package/dist/{chunk-FJS4SN3K.js.map → chunk-DO32GATF.js.map} +1 -1
- package/dist/{chunk-LTM3MW2D.js → chunk-KOM7G7WT.js} +2 -2
- package/dist/{chunk-LTM3MW2D.js.map → chunk-KOM7G7WT.js.map} +1 -1
- package/dist/{chunk-GTR4M2BQ.js → chunk-ND2RTUMM.js} +3 -3
- package/dist/{chunk-GTR4M2BQ.js.map → chunk-ND2RTUMM.js.map} +1 -1
- package/dist/{chunk-2PBDHGRR.js → chunk-OWY5BQER.js} +2 -2
- package/dist/{chunk-2PBDHGRR.js.map → chunk-OWY5BQER.js.map} +1 -1
- package/dist/{chunk-OJ4RI6IQ.js → chunk-PNGPE7QM.js} +3 -3
- package/dist/{chunk-OJ4RI6IQ.js.map → chunk-PNGPE7QM.js.map} +1 -1
- package/dist/{chunk-27JTWTU6.js → chunk-RGISZNQ2.js} +2 -2
- package/dist/{chunk-27JTWTU6.js.map → chunk-RGISZNQ2.js.map} +1 -1
- package/dist/{chunk-SOA2F7Z6.js → chunk-RX6QUDLZ.js} +3 -3
- package/dist/{chunk-SOA2F7Z6.js.map → chunk-RX6QUDLZ.js.map} +1 -1
- package/dist/{chunk-MHEFVYKP.js → chunk-U4DUXPZV.js} +2 -2
- package/dist/{chunk-MHEFVYKP.js.map → chunk-U4DUXPZV.js.map} +1 -1
- package/dist/{chunk-474MQNDK.js → chunk-UULPCFWK.js} +3 -3
- package/dist/{chunk-474MQNDK.js.map → chunk-UULPCFWK.js.map} +1 -1
- package/dist/{chunk-CGMKGENV.js → chunk-XV4QJKOJ.js} +2 -2
- package/dist/{chunk-CGMKGENV.js.map → chunk-XV4QJKOJ.js.map} +1 -1
- package/dist/chunk-ZV7I5RUM.js +10 -0
- package/dist/chunk-ZV7I5RUM.js.map +1 -0
- package/dist/{entry-XHH3NKN2.js → entry-6EWYXIS5.js} +2 -2
- package/dist/{entry-XHH3NKN2.js.map → entry-6EWYXIS5.js.map} +1 -1
- package/dist/index.js +2 -2
- package/dist/{list-R64THLZD.js → list-GBM53HFN.js} +2 -2
- package/dist/{list-R64THLZD.js.map → list-GBM53HFN.js.map} +1 -1
- package/dist/{list-XIE55HYD.js → list-N5W7G3LD.js} +3 -3
- package/dist/{list-XIE55HYD.js.map → list-N5W7G3LD.js.map} +1 -1
- package/dist/{pages-OWXBU64L.js → pages-HPR3UHT7.js} +3 -3
- package/dist/{pages-OWXBU64L.js.map → pages-HPR3UHT7.js.map} +1 -1
- package/dist/{plugin-pages-JBJQHBIN.js → plugin-pages-VDRT7RLY.js} +2 -2
- package/dist/{plugin-pages-JBJQHBIN.js.map → plugin-pages-VDRT7RLY.js.map} +1 -1
- package/dist/{project-selector-L2WZ3MB5.js → project-selector-RRG52TSX.js} +2 -2
- package/dist/{project-selector-L2WZ3MB5.js.map → project-selector-RRG52TSX.js.map} +1 -1
- package/dist/record-links-CI4OJPWW.js +2 -0
- package/dist/{record-links-BEKOPDDR.js.map → record-links-CI4OJPWW.js.map} +1 -1
- package/dist/{root-RUOT5OSO.js → root-DF2BNGOF.js} +3 -3
- package/dist/{root-RUOT5OSO.js.map → root-DF2BNGOF.js.map} +1 -1
- package/dist/{root-VLD6GNZL.js → root-IXK2ESCS.js} +3 -3
- package/dist/{root-VLD6GNZL.js.map → root-IXK2ESCS.js.map} +1 -1
- package/dist/{root-B5XP6VYU.js → root-JFYE2JRJ.js} +2 -2
- package/dist/{root-B5XP6VYU.js.map → root-JFYE2JRJ.js.map} +1 -1
- package/dist/{root-I22KNOFC.js → root-KF6EFGM6.js} +3 -3
- package/dist/{root-I22KNOFC.js.map → root-KF6EFGM6.js.map} +1 -1
- package/dist/{root-O4DMQLEH.js → root-LUWJS7SQ.js} +2 -2
- package/dist/{root-O4DMQLEH.js.map → root-LUWJS7SQ.js.map} +1 -1
- package/dist/{root-DUQULYRX.js → root-RGAV2YAF.js} +2 -2
- package/dist/{root-DUQULYRX.js.map → root-RGAV2YAF.js.map} +1 -1
- package/dist/{search-4UQR6ENH.js → search-DQLC3XDJ.js} +2 -2
- package/dist/{search-4UQR6ENH.js.map → search-DQLC3XDJ.js.map} +1 -1
- package/dist/{skills-pages-VUIOUEYQ.js → skills-pages-Q4YUDTC2.js} +2 -2
- package/dist/{skills-pages-VUIOUEYQ.js.map → skills-pages-Q4YUDTC2.js.map} +1 -1
- package/dist/{source-L54C4T3X.js → source-J3ZCTEWZ.js} +2 -2
- package/dist/{source-L54C4T3X.js.map → source-J3ZCTEWZ.js.map} +1 -1
- package/package.json +5 -5
- package/dist/chunk-YJ4NWJCC.js +0 -10
- package/dist/chunk-YJ4NWJCC.js.map +0 -1
- package/dist/record-links-BEKOPDDR.js +0 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/graphql-client/error-utils.ts","../src/graphql-client/graphql-context.tsx","../src/entities/actions-context.tsx"],"names":["hasCause","error","getServerError","ServerError","possibleServerError","getErrorMessage","message","parseErrorBody","bodyText","getGraphQLSchemaMismatchMessage","messages","getGraphQLValidationMessages","isMissingCountStoreFieldMessage","isMissingGraphQLFieldError","fieldName","CombinedGraphQLErrors","isSchemaValidationError","directMessage","isSchemaValidationMessage","serverError","responseBody","getServerErrorResult","getErrorCauseResponse","item","result","cause","causeMessage","extensions","ApolloProviderCompat","ApolloProvider","GraphQLErrorContext","createContext","useGraphQLError","ctx","useContext","USER_QUERY_CONTEXT","createErrorLink","setSchemaErrorMessage","ErrorLink","operation","schemaMismatchMessage","locations","path","CombinedProtocolErrors","responseError","errors","responseMessage","firstError","firstErrorMessage","additiveLink","currentProjectId","from","HttpLink","client","ApolloClient","InMemoryCache","responseObject","defaultDataIdFromObject","GraphQLProvider","children","useConfig","schemaErrorMessage","useState","useMemo","apolloClient","jsx","ActionsContext","EntityDispatchContext","actionsReducer","actions","action","actionType","uniqBy","props","ActionsProvider","entityActions","dispatchEntityActions","useReducer","useActions","useDispatch"],"mappings":"4eAsBA,SAASA,CAAAA,CAASC,EAA2C,CAC3D,OAAKA,EAIE,OAAA,GAAYA,CAAAA,CAHV,KAIX,CAEO,SAASC,CAAAA,CAAeD,CAAAA,CAAuC,CACpE,GAAI,CAACA,CAAAA,CACH,OAAO,IAAA,CAGT,GAAIE,YAAY,EAAA,CAAGF,CAAK,EACtB,OAAOA,CAAAA,CAGT,GAAID,CAAAA,CAASC,CAAK,CAAA,CAAG,CACnB,IAAMG,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474MQNDK.js","sourcesContent":["import type { ErrorLike } from '@apollo/client';\nimport { CombinedGraphQLErrors, ServerError } from '@apollo/client/errors';\n\ntype ErrorWithCause = ErrorLike & { cause?: unknown };\ntype ErrorWithMessage = {\n message?: unknown;\n};\ntype ServerErrorWithResult = ServerError & {\n result?: unknown;\n};\ntype GraphQLErrorResponse = {\n error?: unknown;\n errors?: unknown;\n message?: unknown;\n};\ntype GraphQLErrorItem = {\n extensions?: {\n code?: unknown;\n };\n message?: unknown;\n};\n\nfunction hasCause(error: ErrorLike): error is ErrorWithCause {\n if (!error) {\n return false;\n }\n\n return 'cause' in (error as ErrorWithCause);\n}\n\nexport function getServerError(error?: ErrorLike): ServerError | null {\n if (!error) {\n return null;\n }\n\n if (ServerError.is(error)) {\n return error;\n }\n\n if (hasCause(error)) {\n const possibleServerError = error.cause;\n\n if (ServerError.is(possibleServerError)) {\n return possibleServerError;\n }\n }\n\n return null;\n}\n\nfunction getErrorMessage(error: unknown): string | null {\n if (!error || typeof error !== 'object') {\n return null;\n }\n\n const { message } = error as ErrorWithMessage;\n\n return typeof message === 'string' ? message : null;\n}\n\nexport function parseErrorBody<T>(bodyText: string | undefined): T | null {\n if (!bodyText) {\n return null;\n }\n\n try {\n return JSON.parse(bodyText) as T;\n } catch {\n return null;\n }\n}\n\nexport function getGraphQLSchemaMismatchMessage(error?: ErrorLike): string | null {\n if (!error) {\n return null;\n }\n\n const messages = getGraphQLValidationMessages(error).filter((message) => !isMissingCountStoreFieldMessage(message));\n\n if (messages.length === 0) {\n return null;\n }\n\n return [\n 'The deployed schema is out of sync with your local Flexkit schema.',\n 'Run `flexkit deploy` using the CLI to apply your latest schema changes.',\n ...messages.map((message) => `- ${message}`),\n ].join('\\n');\n}\n\nexport function isMissingGraphQLFieldError(error: ErrorLike | undefined, fieldName: string): boolean {\n if (!error) {\n return false;\n }\n\n return getGraphQLValidationMessages(error).some((message) => {\n return message.includes(`Cannot query field \"${fieldName}\"`);\n });\n}\n\nfunction getGraphQLValidationMessages(error: ErrorLike): string[] {\n if (CombinedGraphQLErrors.is(error)) {\n return error.errors.filter(isSchemaValidationError).map(({ message }) => message);\n }\n\n const directMessage = getErrorMessage(error);\n\n if (directMessage && isSchemaValidationMessage(directMessage)) {\n return [directMessage];\n }\n\n const serverError = getServerError(error);\n\n if (serverError?.statusCode !== 400) {\n return [];\n }\n\n const responseBody =\n parseErrorBody<GraphQLErrorResponse>(serverError.bodyText) ??\n getServerErrorResult(serverError) ??\n getErrorCauseResponse(error);\n\n if (!responseBody) {\n return [];\n }\n\n if (Array.isArray(responseBody.errors)) {\n return responseBody.errors.filter(isSchemaValidationError).map((item) => item.message);\n }\n\n if (typeof responseBody.message === 'string' && isSchemaValidationMessage(responseBody.message)) {\n return [responseBody.message];\n }\n\n if (typeof responseBody.error === 'string' && isSchemaValidationMessage(responseBody.error)) {\n return [responseBody.error];\n }\n\n return [];\n}\n\nfunction getServerErrorResult(serverError: ServerError): GraphQLErrorResponse | null {\n const { result } = serverError as ServerErrorWithResult;\n\n if (!result || typeof result !== 'object') {\n return null;\n }\n\n return result as GraphQLErrorResponse;\n}\n\nfunction getErrorCauseResponse(error: ErrorLike): GraphQLErrorResponse | null {\n if (!hasCause(error)) {\n return null;\n }\n\n const { cause } = error;\n const causeMessage = getErrorMessage(cause);\n\n if (causeMessage && isSchemaValidationMessage(causeMessage)) {\n return { message: causeMessage };\n }\n\n if (!cause || typeof cause !== 'object') {\n return null;\n }\n\n const { result } = cause as { result?: unknown };\n\n if (result && typeof result === 'object') {\n return result as GraphQLErrorResponse;\n }\n\n return null;\n}\n\nfunction isSchemaValidationError(error: unknown): error is GraphQLErrorItem & { message: string } {\n if (!error || typeof error !== 'object') {\n return false;\n }\n\n const { extensions, message } = error as GraphQLErrorItem;\n const code = extensions?.code;\n\n if (code === 'GRAPHQL_VALIDATION_FAILED' && typeof message === 'string') {\n return true;\n }\n\n return typeof message === 'string' && isSchemaValidationMessage(message);\n}\n\nfunction isSchemaValidationMessage(message: string): boolean {\n return (\n message.startsWith('Cannot query field ') ||\n message.startsWith('Unknown type ') ||\n message.startsWith('Cannot query field \"') ||\n message.includes('GRAPHQL_VALIDATION_FAILED')\n );\n}\n\nfunction isMissingCountStoreFieldMessage(message: string): boolean {\n return /Cannot query field \"[_A-Za-z][_0-9A-Za-z]*Total\" on type \"Query\"/.test(message);\n}\n","'use client';\n\nimport type { JSX } from 'react';\nimport { ApolloClient, InMemoryCache, defaultDataIdFromObject, from, HttpLink } from '@apollo/client';\nimport type { ApolloLink } from '@apollo/client';\nimport { ApolloProvider } from '@apollo/client/react';\nimport { ErrorLink } from '@apollo/client/link/error';\nimport { CombinedGraphQLErrors, CombinedProtocolErrors } from '@apollo/client/errors';\nimport { getGraphQLSchemaMismatchMessage, getServerError, parseErrorBody } from './error-utils';\nimport { useConfig } from '../core/config/config-context';\nimport React, { createContext, useContext, useMemo, useState } from 'react';\n\nconst ApolloProviderCompat = ApolloProvider as unknown as React.ComponentType<{\n children?: React.ReactNode;\n client: ApolloClient;\n}>;\n\ntype GraphQLErrorContextValue = {\n schemaErrorMessage: string | null;\n setSchemaErrorMessage: React.Dispatch<React.SetStateAction<string | null>>;\n};\n\nconst GraphQLErrorContext = createContext<GraphQLErrorContextValue | undefined>(undefined);\n\nfunction useGraphQLError(): GraphQLErrorContextValue {\n const ctx = useContext(GraphQLErrorContext);\n\n if (!ctx) {\n throw new Error('useGraphQLError must be used within GraphQLProvider');\n }\n\n return ctx;\n}\n\n/**\n * Context flag for operations the user writes themselves (the Graph app's\n * Query view): any error there, a mismatch or a 400, is a typo, not a\n * deployment that drifted from the local schema, so it must not raise the\n * schema banner. The caller shows the error itself.\n */\nexport const USER_QUERY_CONTEXT = { userQuery: true } as const;\n\nfunction createErrorLink(setSchemaErrorMessage: (msg: string | null) => void): ApolloLink {\n return new ErrorLink(({ error, operation }) => {\n if (operation.getContext().userQuery === true) {\n return;\n }\n\n const schemaMismatchMessage = getGraphQLSchemaMismatchMessage(error);\n\n if (schemaMismatchMessage) {\n setSchemaErrorMessage(schemaMismatchMessage);\n\n return;\n }\n\n if (CombinedGraphQLErrors.is(error)) {\n error.errors.forEach(({ message, locations, path }) => {\n console.warn(`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`);\n });\n } else if (CombinedProtocolErrors.is(error)) {\n error.errors.forEach(({ message, extensions }) => {\n console.warn(`[Protocol error]: Message: ${message}, Extensions: ${JSON.stringify(extensions)}`);\n });\n }\n\n const serverError = getServerError(error);\n\n if (serverError?.statusCode === 400) {\n const responseBody = parseErrorBody<Record<string, unknown>>(serverError.bodyText);\n let message: string | null = null;\n\n if (responseBody && typeof responseBody === 'object') {\n const {\n error: responseError,\n errors,\n message: responseMessage,\n } = responseBody as {\n error?: unknown;\n errors?: unknown;\n message?: unknown;\n };\n\n if (typeof responseMessage === 'string') {\n message = responseMessage;\n } else if (Array.isArray(errors)) {\n const [firstError] = errors as { message?: unknown }[];\n\n if (firstError && typeof firstError.message === 'string') {\n const { message: firstErrorMessage } = firstError;\n message = firstErrorMessage;\n }\n } else if (typeof responseError === 'string') {\n message = responseError;\n } else {\n message = JSON.stringify(responseBody);\n }\n } else {\n message = serverError.bodyText;\n }\n\n setSchemaErrorMessage(\n message ?? 'There is an error in the deployed Flexkit schema. Fix flexkit.config.ts and run flexkit deploy.'\n );\n }\n\n if (serverError) {\n console.warn(`[Network error]: ${serverError.message}`);\n\n return;\n }\n\n if (error) {\n console.warn(`[Network error]: ${error.message}`);\n }\n });\n}\n\nfunction additiveLink(currentProjectId: string, setSchemaErrorMessage: (msg: string | null) => void): ApolloLink {\n return from([\n createErrorLink(setSchemaErrorMessage),\n new HttpLink({ uri: `/api/flexkit/${currentProjectId}/graphql` }),\n ]);\n}\n\nfunction client(\n currentProjectId: string | undefined,\n setSchemaErrorMessage: (msg: string | null) => void\n): ApolloClient {\n return new ApolloClient({\n link: additiveLink(currentProjectId ?? '', setSchemaErrorMessage),\n cache: new InMemoryCache({\n dataIdFromObject: (responseObject) => {\n return responseObject._id ? (responseObject._id as string) : defaultDataIdFromObject(responseObject);\n },\n }),\n });\n}\n\nexport function GraphQLProvider({ children }: { children: React.ReactNode }): JSX.Element {\n const { currentProjectId } = useConfig();\n const [schemaErrorMessage, setSchemaErrorMessage] = useState<string | null>(null);\n const ctx = useMemo(() => ({ schemaErrorMessage, setSchemaErrorMessage }), [schemaErrorMessage]);\n const apolloClient = useMemo(() => client(currentProjectId, setSchemaErrorMessage), [currentProjectId]);\n\n return (\n <GraphQLErrorContext.Provider value={ctx}>\n <ApolloProviderCompat client={apolloClient}>{children}</ApolloProviderCompat>\n </GraphQLErrorContext.Provider>\n );\n}\n\nexport { useGraphQLError };\n","'use client';\n\nimport { createContext, useContext, useReducer } from 'react';\nimport type { Dispatch, JSX, ReactNode } from 'react';\nimport { props, uniqBy } from 'ramda';\nimport type {\n Action,\n ActionAddEntity,\n ActionAlertDialog,\n ActionDeleteEntity,\n ActionEditEntity,\n ActionEditRelationship,\n} from './types';\n\nconst ActionsContext = createContext<Action[] | []>([]);\nconst EntityDispatchContext = createContext<Dispatch<Action>>(() => undefined);\n\nfunction actionsReducer(actions: Action[], action: Action): Action[] {\n const actionType = action.type;\n\n if (!action._id) {\n action._id = Date.now().toString();\n }\n\n switch (actionType) {\n case 'DeleteEntity': {\n return uniqBy(props(['type' as string, '_id']), [...(actions as ActionDeleteEntity[]), action]);\n }\n case 'AddEntity': {\n return uniqBy(props(['type' as string, '_id']), [...(actions as ActionAddEntity[]), action]);\n }\n case 'EditEntity': {\n return uniqBy(props(['type' as string, '_id']), [...(actions as ActionEditEntity[]), action]);\n }\n case 'EditRelationship': {\n return uniqBy(props(['type' as string, '_id']), [...(actions as ActionEditRelationship[]), action]);\n }\n case 'AlertDialog': {\n return uniqBy(props(['type' as string, '_id']), [...(actions as ActionAlertDialog[]), action]);\n }\n case 'Dismiss': {\n return actions.filter((item) => item._id !== action._id);\n }\n default: {\n throw Error(`Unknown action: ${actionType as string}`);\n }\n }\n}\n\nfunction ActionsProvider({ children }: { children: ReactNode }): JSX.Element {\n const [entityActions, dispatchEntityActions] = useReducer(actionsReducer, []);\n\n return (\n <ActionsContext.Provider value={entityActions}>\n <EntityDispatchContext.Provider value={dispatchEntityActions}>{children}</EntityDispatchContext.Provider>\n </ActionsContext.Provider>\n );\n}\n\nfunction useActions(): Action[] {\n return useContext(ActionsContext);\n}\n\nfunction useDispatch(): Dispatch<Action> {\n return useContext(EntityDispatchContext);\n}\n\nexport { ActionsProvider, useActions, useDispatch };\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/graphql-client/error-utils.ts","../src/graphql-client/graphql-context.tsx","../src/entities/actions-context.tsx"],"names":["hasCause","error","getServerError","ServerError","possibleServerError","getErrorMessage","message","parseErrorBody","bodyText","getGraphQLSchemaMismatchMessage","messages","getGraphQLValidationMessages","isMissingCountStoreFieldMessage","isMissingGraphQLFieldError","fieldName","CombinedGraphQLErrors","isSchemaValidationError","directMessage","isSchemaValidationMessage","serverError","responseBody","getServerErrorResult","getErrorCauseResponse","item","result","cause","causeMessage","extensions","ApolloProviderCompat","ApolloProvider","GraphQLErrorContext","createContext","useGraphQLError","ctx","useContext","USER_QUERY_CONTEXT","createErrorLink","setSchemaErrorMessage","ErrorLink","operation","schemaMismatchMessage","locations","path","CombinedProtocolErrors","responseError","errors","responseMessage","firstError","firstErrorMessage","additiveLink","currentProjectId","from","HttpLink","client","ApolloClient","InMemoryCache","responseObject","defaultDataIdFromObject","GraphQLProvider","children","useConfig","schemaErrorMessage","useState","useMemo","apolloClient","jsx","ActionsContext","EntityDispatchContext","actionsReducer","actions","action","actionType","uniqBy","props","ActionsProvider","entityActions","dispatchEntityActions","useReducer","useActions","useDispatch"],"mappings":"4eAsBA,SAASA,CAAAA,CAASC,EAA2C,CAC3D,OAAKA,EAIE,OAAA,GAAYA,CAAAA,CAHV,KAIX,CAEO,SAASC,CAAAA,CAAeD,CAAAA,CAAuC,CACpE,GAAI,CAACA,CAAAA,CACH,OAAO,IAAA,CAGT,G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,OAAO5C,UAAAA,CAAWgC,CAAc,CAClC,CAEA,SAASa,IAAgC,CACvC,OAAO7C,UAAAA,CAAWiC,CAAqB,CACzC","file":"chunk-UULPCFWK.js","sourcesContent":["import type { ErrorLike } from '@apollo/client';\nimport { CombinedGraphQLErrors, ServerError } from '@apollo/client/errors';\n\ntype ErrorWithCause = ErrorLike & { cause?: unknown };\ntype ErrorWithMessage = {\n message?: unknown;\n};\ntype ServerErrorWithResult = ServerError & {\n result?: unknown;\n};\ntype GraphQLErrorResponse = {\n error?: unknown;\n errors?: unknown;\n message?: unknown;\n};\ntype GraphQLErrorItem = {\n extensions?: {\n code?: unknown;\n };\n message?: unknown;\n};\n\nfunction hasCause(error: ErrorLike): error is ErrorWithCause {\n if (!error) {\n return false;\n }\n\n return 'cause' in (error as ErrorWithCause);\n}\n\nexport function getServerError(error?: ErrorLike): ServerError | null {\n if (!error) {\n return null;\n }\n\n if (ServerError.is(error)) {\n return error;\n }\n\n if (hasCause(error)) {\n const possibleServerError = error.cause;\n\n if (ServerError.is(possibleServerError)) {\n return possibleServerError;\n }\n }\n\n return null;\n}\n\nfunction getErrorMessage(error: unknown): string | null {\n if (!error || typeof error !== 'object') {\n return null;\n }\n\n const { message } = error as ErrorWithMessage;\n\n return typeof message === 'string' ? message : null;\n}\n\nexport function parseErrorBody<T>(bodyText: string | undefined): T | null {\n if (!bodyText) {\n return null;\n }\n\n try {\n return JSON.parse(bodyText) as T;\n } catch {\n return null;\n }\n}\n\nexport function getGraphQLSchemaMismatchMessage(error?: ErrorLike): string | null {\n if (!error) {\n return null;\n }\n\n const messages = getGraphQLValidationMessages(error).filter((message) => !isMissingCountStoreFieldMessage(message));\n\n if (messages.length === 0) {\n return null;\n }\n\n return [\n 'The deployed schema is out of sync with your local Flexkit schema.',\n 'Run `flexkit deploy` using the CLI to apply your latest schema changes.',\n ...messages.map((message) => `- ${message}`),\n ].join('\\n');\n}\n\nexport function isMissingGraphQLFieldError(error: ErrorLike | undefined, fieldName: string): boolean {\n if (!error) {\n return false;\n }\n\n return getGraphQLValidationMessages(error).some((message) => {\n return message.includes(`Cannot query field \"${fieldName}\"`);\n });\n}\n\nfunction getGraphQLValidationMessages(error: ErrorLike): string[] {\n if (CombinedGraphQLErrors.is(error)) {\n return error.errors.filter(isSchemaValidationError).map(({ message }) => message);\n }\n\n const directMessage = getErrorMessage(error);\n\n if (directMessage && isSchemaValidationMessage(directMessage)) {\n return [directMessage];\n }\n\n const serverError = getServerError(error);\n\n if (serverError?.statusCode !== 400) {\n return [];\n }\n\n const responseBody =\n parseErrorBody<GraphQLErrorResponse>(serverError.bodyText) ??\n getServerErrorResult(serverError) ??\n getErrorCauseResponse(error);\n\n if (!responseBody) {\n return [];\n }\n\n if (Array.isArray(responseBody.errors)) {\n return responseBody.errors.filter(isSchemaValidationError).map((item) => item.message);\n }\n\n if (typeof responseBody.message === 'string' && isSchemaValidationMessage(responseBody.message)) {\n return [responseBody.message];\n }\n\n if (typeof responseBody.error === 'string' && isSchemaValidationMessage(responseBody.error)) {\n return [responseBody.error];\n }\n\n return [];\n}\n\nfunction getServerErrorResult(serverError: ServerError): GraphQLErrorResponse | null {\n const { result } = serverError as ServerErrorWithResult;\n\n if (!result || typeof result !== 'object') {\n return null;\n }\n\n return result as GraphQLErrorResponse;\n}\n\nfunction getErrorCauseResponse(error: ErrorLike): GraphQLErrorResponse | null {\n if (!hasCause(error)) {\n return null;\n }\n\n const { cause } = error;\n const causeMessage = getErrorMessage(cause);\n\n if (causeMessage && isSchemaValidationMessage(causeMessage)) {\n return { message: causeMessage };\n }\n\n if (!cause || typeof cause !== 'object') {\n return null;\n }\n\n const { result } = cause as { result?: unknown };\n\n if (result && typeof result === 'object') {\n return result as GraphQLErrorResponse;\n }\n\n return null;\n}\n\nfunction isSchemaValidationError(error: unknown): error is GraphQLErrorItem & { message: string } {\n if (!error || typeof error !== 'object') {\n return false;\n }\n\n const { extensions, message } = error as GraphQLErrorItem;\n const code = extensions?.code;\n\n if (code === 'GRAPHQL_VALIDATION_FAILED' && typeof message === 'string') {\n return true;\n }\n\n return typeof message === 'string' && isSchemaValidationMessage(message);\n}\n\nfunction isSchemaValidationMessage(message: string): boolean {\n return (\n message.startsWith('Cannot query field ') ||\n message.startsWith('Unknown type ') ||\n message.startsWith('Cannot query field \"') ||\n message.includes('GRAPHQL_VALIDATION_FAILED')\n );\n}\n\nfunction isMissingCountStoreFieldMessage(message: string): boolean {\n return /Cannot query field \"[_A-Za-z][_0-9A-Za-z]*Total\" on type \"Query\"/.test(message);\n}\n","'use client';\n\nimport type { JSX } from 'react';\nimport { ApolloClient, InMemoryCache, defaultDataIdFromObject, from, HttpLink } from '@apollo/client';\nimport type { ApolloLink } from '@apollo/client';\nimport { ApolloProvider } from '@apollo/client/react';\nimport { ErrorLink } from '@apollo/client/link/error';\nimport { CombinedGraphQLErrors, CombinedProtocolErrors } from '@apollo/client/errors';\nimport { getGraphQLSchemaMismatchMessage, getServerError, parseErrorBody } from './error-utils';\nimport { useConfig } from '../core/config/config-context';\nimport React, { createContext, useContext, useMemo, useState } from 'react';\n\nconst ApolloProviderCompat = ApolloProvider as unknown as React.ComponentType<{\n children?: React.ReactNode;\n client: ApolloClient;\n}>;\n\ntype GraphQLErrorContextValue = {\n schemaErrorMessage: string | null;\n setSchemaErrorMessage: React.Dispatch<React.SetStateAction<string | null>>;\n};\n\nconst GraphQLErrorContext = createContext<GraphQLErrorContextValue | undefined>(undefined);\n\nfunction useGraphQLError(): GraphQLErrorContextValue {\n const ctx = useContext(GraphQLErrorContext);\n\n if (!ctx) {\n throw new Error('useGraphQLError must be used within GraphQLProvider');\n }\n\n return ctx;\n}\n\n/**\n * Context flag for operations the user writes themselves (the Graph app's\n * Query view): any error there, a mismatch or a 400, is a typo, not a\n * deployment that drifted from the local schema, so it must not raise the\n * schema banner. The caller shows the error itself.\n */\nexport const USER_QUERY_CONTEXT = { userQuery: true } as const;\n\nfunction createErrorLink(setSchemaErrorMessage: (msg: string | null) => void): ApolloLink {\n return new ErrorLink(({ error, operation }) => {\n if (operation.getContext().userQuery === true) {\n return;\n }\n\n const schemaMismatchMessage = getGraphQLSchemaMismatchMessage(error);\n\n if (schemaMismatchMessage) {\n setSchemaErrorMessage(schemaMismatchMessage);\n\n return;\n }\n\n if (CombinedGraphQLErrors.is(error)) {\n error.errors.forEach(({ message, locations, path }) => {\n console.warn(`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`);\n });\n } else if (CombinedProtocolErrors.is(error)) {\n error.errors.forEach(({ message, extensions }) => {\n console.warn(`[Protocol error]: Message: ${message}, Extensions: ${JSON.stringify(extensions)}`);\n });\n }\n\n const serverError = getServerError(error);\n\n if (serverError?.statusCode === 400) {\n const responseBody = parseErrorBody<Record<string, unknown>>(serverError.bodyText);\n let message: string | null = null;\n\n if (responseBody && typeof responseBody === 'object') {\n const {\n error: responseError,\n errors,\n message: responseMessage,\n } = responseBody as {\n error?: unknown;\n errors?: unknown;\n message?: unknown;\n };\n\n if (typeof responseMessage === 'string') {\n message = responseMessage;\n } else if (Array.isArray(errors)) {\n const [firstError] = errors as { message?: unknown }[];\n\n if (firstError && typeof firstError.message === 'string') {\n const { message: firstErrorMessage } = firstError;\n message = firstErrorMessage;\n }\n } else if (typeof responseError === 'string') {\n message = responseError;\n } else {\n message = JSON.stringify(responseBody);\n }\n } else {\n message = serverError.bodyText;\n }\n\n setSchemaErrorMessage(\n message ?? 'There is an error in the deployed Flexkit schema. Fix flexkit.config.ts and run flexkit deploy.'\n );\n }\n\n if (serverError) {\n console.warn(`[Network error]: ${serverError.message}`);\n\n return;\n }\n\n if (error) {\n console.warn(`[Network error]: ${error.message}`);\n }\n });\n}\n\nfunction additiveLink(currentProjectId: string, setSchemaErrorMessage: (msg: string | null) => void): ApolloLink {\n return from([\n createErrorLink(setSchemaErrorMessage),\n new HttpLink({ uri: `/api/flexkit/${currentProjectId}/graphql` }),\n ]);\n}\n\nfunction client(\n currentProjectId: string | undefined,\n setSchemaErrorMessage: (msg: string | null) => void\n): ApolloClient {\n return new ApolloClient({\n link: additiveLink(currentProjectId ?? '', setSchemaErrorMessage),\n cache: new InMemoryCache({\n dataIdFromObject: (responseObject) => {\n return responseObject._id ? (responseObject._id as string) : defaultDataIdFromObject(responseObject);\n },\n }),\n });\n}\n\nexport function GraphQLProvider({ children }: { children: React.ReactNode }): JSX.Element {\n const { currentProjectId } = useConfig();\n const [schemaErrorMessage, setSchemaErrorMessage] = useState<string | null>(null);\n const ctx = useMemo(() => ({ schemaErrorMessage, setSchemaErrorMessage }), [schemaErrorMessage]);\n const apolloClient = useMemo(() => client(currentProjectId, setSchemaErrorMessage), [currentProjectId]);\n\n return (\n <GraphQLErrorContext.Provider value={ctx}>\n <ApolloProviderCompat client={apolloClient}>{children}</ApolloProviderCompat>\n </GraphQLErrorContext.Provider>\n );\n}\n\nexport { useGraphQLError };\n","'use client';\n\nimport { createContext, useContext, useReducer } from 'react';\nimport type { Dispatch, JSX, ReactNode } from 'react';\nimport { props, uniqBy } from 'ramda';\nimport type {\n Action,\n ActionAddEntity,\n ActionAlertDialog,\n ActionDeleteEntity,\n ActionEditEntity,\n ActionEditRelationship,\n} from './types';\n\nconst ActionsContext = createContext<Action[] | []>([]);\nconst EntityDispatchContext = createContext<Dispatch<Action>>(() => undefined);\n\nfunction actionsReducer(actions: Action[], action: Action): Action[] {\n const actionType = action.type;\n\n if (!action._id) {\n action._id = Date.now().toString();\n }\n\n switch (actionType) {\n case 'DeleteEntity': {\n return uniqBy(props(['type' as string, '_id']), [...(actions as ActionDeleteEntity[]), action]);\n }\n case 'AddEntity': {\n return uniqBy(props(['type' as string, '_id']), [...(actions as ActionAddEntity[]), action]);\n }\n case 'EditEntity': {\n return uniqBy(props(['type' as string, '_id']), [...(actions as ActionEditEntity[]), action]);\n }\n case 'EditRelationship': {\n return uniqBy(props(['type' as string, '_id']), [...(actions as ActionEditRelationship[]), action]);\n }\n case 'AlertDialog': {\n return uniqBy(props(['type' as string, '_id']), [...(actions as ActionAlertDialog[]), action]);\n }\n case 'Dismiss': {\n return actions.filter((item) => item._id !== action._id);\n }\n default: {\n throw Error(`Unknown action: ${actionType as string}`);\n }\n }\n}\n\nfunction ActionsProvider({ children }: { children: ReactNode }): JSX.Element {\n const [entityActions, dispatchEntityActions] = useReducer(actionsReducer, []);\n\n return (\n <ActionsContext.Provider value={entityActions}>\n <EntityDispatchContext.Provider value={dispatchEntityActions}>{children}</EntityDispatchContext.Provider>\n </ActionsContext.Provider>\n );\n}\n\nfunction useActions(): Action[] {\n return useContext(ActionsContext);\n}\n\nfunction useDispatch(): Dispatch<Action> {\n return useContext(EntityDispatchContext);\n}\n\nexport { ActionsProvider, useActions, useDispatch };\n"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import'./index.css';import {x}from'./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import'./index.css';import {x}from'./chunk-ZV7I5RUM.js';import {g,f}from'./chunk-PLCI2RJA.js';import {e,g as g$1,h,j}from'./chunk-A4DPLZZF.js';import {b}from'./chunk-G5N6HEPW.js';import {k,p,q,s,r}from'./chunk-S7Z6KKIN.js';import {c}from'./chunk-X3SHNHHM.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$1,l]=useState(null),[g,d]=useState(t.title??""),[p$1,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(c,{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(k,{open:r$1==="rename",onOpenChange:m=>l(m?"rename":null),children:jsxs(p,{className:"fk:max-w-sm",children:[jsx(q,{children:jsx(s,{children:"Rename chat"})}),jsx(b,{value:g,onChange:m=>d(m.target.value),placeholder:"Chat title"}),jsx(r,{children:jsx(c,{disabled:p$1||!g.trim(),size:"sm",onClick:v,children:p$1?"Saving...":"Save"})})]})}),jsx(k,{open:r$1==="delete",onOpenChange:m=>l(m?"delete":null),children:jsxs(p,{className:"fk:max-w-sm",children:[jsx(q,{children:jsx(s,{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(r,{children:jsx(c,{disabled:p$1,size:"sm",variant:"destructive",onClick:y,children:p$1?"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}=x(),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(c,{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-XV4QJKOJ.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-XV4QJKOJ.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/apps/ai/agent/chat-list.tsx"],"names":["useAgentBasePath","location","useLocation","marker","index","useDebouncedValue","value","delayMs","debounced","setDebounced","useState","useEffect","timeout","getChatGroupLabel","chat","timestamp","now","startOfToday","groupChats","chats","groups","label","group","candidate","ChatListItem","active","api","onChanged","onDeleted","onOpen","dialog","setDialog","title","setTitle","isMutating","startMutation","useTransition","handleRename","handleDelete","jsxs","jsx","DropdownMenu","DropdownMenuTrigger","Button","MoreHorizontalIcon","DropdownMenuContent","DropdownMenuItem","PencilIcon","Trash2Icon","Dialog","open","DialogContent","DialogHeader","DialogTitle","Input","event","DialogFooter","SearchResults","projectId","query","data","isLoading","useSWR","paths","fetcher","LoaderCircle","result","AgentChatsSection","useProjectApi","navigate","useNavigate","globalMutate","useSWRConfig","activeChatId","mutate","setSize","size","useSWRInfinite","pageIndex","previousPage","activeChatDetail","useMemo","listed","page","generatedTitle","hasMore","chatApi","chatProjectId","openChat","chatId","handleDeleted","MessageSquareIcon"],"mappings":"gkBAwBO,SAASA,EAAAA,EAA2B,CACzC,IAAMC,CAAAA,CAAWC,WAAAA,EAAY,CACvBC,CAAAA,CAAS,QAAA,CACTC,CAAAA,CAAQH,CAAAA,CAAS,QAAA,CAAS,OAAA,CAAQE,CAAM,CAAA,CAE9C,OAAIC,CAAAA,GAAU,EAAA,CACL,CAAA,EAAGH,CAAAA,CAAS,SAAS,OAAA,CAAQ,KAAA,CAAO,EAAE,CAAC,CAAA,MAAA,CAAA,CAGzCA,CAAAA,CAAS,QAAA,CAAS,KAAA,CAAM,CAAA,CAAGG,CAAAA,CAAQD,CAAAA,CAAO,MAAM,CACzD,CAEO,SAASE,EAAAA,CAAkBC,CAAAA,CAAeC,CAAAA,CAAyB,CACxE,GAAM,CAACC,CAAAA,CAAWC,CAAY,CAAA,CAAIC,QAAAA,CAASJ,CAAK,CAAA,CAEhD,OAAAK,SAAAA,CAAU,IAAM,CACd,IAAMC,CAAAA,CAAU,MAAA,CAAO,UAAA,CAAW,IAAM,CACtCH,CAAAA,CAAaH,CAAK,EACpB,CAAA,CAAGC,CAAO,CAAA,CAEV,OAAO,IAAM,CACX,MAAA,CAAO,YAAA,CAAaK,CAAO,EAC7B,CACF,CAAA,CAAG,CAACL,CAAAA,CAASD,CAAK,CAAC,CAAA,CAEZE,CACT,CAEA,SAASK,CAAAA,CAAkBC,CAAAA,CAAyB,CAClD,IAAMC,CAAAA,CAAY,IAAI,IAAA,CAAKD,CAAAA,CAAK,aAAA,EAA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AK,QAAA,CAAA,oDAAA,CAAkD,CAAA,CAAA,CAC1D,CAAA,CACE,IAAA,CACH6C,CAAAA,CACC7C,GAAAA,CAACG,CAAAA,CAAA,CAAO,SAAA,CAAU,WAAA,CAAY,IAAA,CAAK,IAAA,CAAK,OAAA,CAAQ,OAAA,CAAQ,OAAA,CAAS,IAAG,CAAQgC,CAAAA,CAAQC,CAAAA,CAAO,CAAC,EAAA,CAAA,CAAG,QAAA,CAAA,WAAA,CAE/F,CAAA,CACE,IAAA,CAAA,CACN,CAAA,CAEJ,CAEJ","file":"chunk-CGMKGENV.js","sourcesContent":["import type { JSX } from 'react';\nimport { useEffect, useMemo, useState, useTransition } from 'react';\nimport { LoaderCircle, MessageSquareIcon, MoreHorizontalIcon, PencilIcon, Trash2Icon } from 'lucide-react';\nimport { useLocation, useNavigate } from 'react-router-dom';\nimport useSWR, { useSWRConfig } from 'swr';\nimport useSWRInfinite from 'swr/infinite';\nimport {\n Button,\n Dialog,\n DialogContent,\n DialogFooter,\n DialogHeader,\n DialogTitle,\n DropdownMenu,\n DropdownMenuContent,\n DropdownMenuItem,\n DropdownMenuTrigger,\n Input,\n} from '../../../ui';\nimport { fetcher, paths, type ApiClient } from '../api';\nimport { useProjectApi } from '../replay';\nimport type { AgentChat, AgentChatDetail, AgentChatSearchResult, AgentChatsList } from '../types';\n\n/** Returns the absolute route prefix of the agent app (`.../ai/agent`). */\nexport function useAgentBasePath(): string {\n const location = useLocation();\n const marker = '/agent';\n const index = location.pathname.indexOf(marker);\n\n if (index === -1) {\n return `${location.pathname.replace(/\\/$/, '')}/agent`;\n }\n\n return location.pathname.slice(0, index + marker.length);\n}\n\nexport function useDebouncedValue(value: string, delayMs: number): string {\n const [debounced, setDebounced] = useState(value);\n\n useEffect(() => {\n const timeout = window.setTimeout(() => {\n setDebounced(value);\n }, delayMs);\n\n return () => {\n window.clearTimeout(timeout);\n };\n }, [delayMs, value]);\n\n return debounced;\n}\n\nfunction getChatGroupLabel(chat: AgentChat): string {\n const timestamp = new Date(chat.lastMessageAt ?? chat.updatedAt).getTime();\n const now = new Date();\n const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();\n\n if (timestamp >= startOfToday) {\n return 'Today';\n }\n\n if (timestamp >= startOfToday - 86_400_000) {\n return 'Yesterday';\n }\n\n if (timestamp >= startOfToday - 7 * 86_400_000) {\n return 'Previous 7 days';\n }\n\n return 'Older';\n}\n\nfunction groupChats(chats: AgentChat[]): { chats: AgentChat[]; label: string }[] {\n const groups: { chats: AgentChat[]; label: string }[] = [];\n\n for (const chat of chats) {\n const label = getChatGroupLabel(chat);\n const group = groups.find((candidate) => candidate.label === label);\n\n if (group) {\n group.chats.push(chat);\n } else {\n groups.push({ chats: [chat], label });\n }\n }\n\n return groups;\n}\n\nfunction ChatListItem({\n active,\n api,\n chat,\n onChanged,\n onDeleted,\n onOpen,\n}: {\n active: boolean;\n api: ApiClient;\n chat: AgentChat;\n onChanged: () => void;\n onDeleted: () => void;\n onOpen: () => void;\n}): JSX.Element {\n const [dialog, setDialog] = useState<'rename' | 'delete' | null>(null);\n const [title, setTitle] = useState(chat.title ?? '');\n const [isMutating, startMutation] = useTransition();\n const label = chat.title?.trim() || 'New chat';\n\n function handleRename(): void {\n startMutation(async () => {\n await api.renameAgentChat(chat.id, title.trim());\n setDialog(null);\n onChanged();\n });\n }\n\n function handleDelete(): void {\n startMutation(async () => {\n await api.deleteAgentChat(chat.id);\n setDialog(null);\n onDeleted();\n });\n }\n\n return (\n <div\n className={`fk:group/chat fk:flex fk:items-center fk:gap-1 fk:rounded-md fk:pr-1 ${\n active ? 'fk:bg-sidebar-accent' : 'fk:hover:bg-accent/60'\n } fk:corner-squircle`}\n >\n <button\n className=\"fk:min-w-0 fk:flex-1 fk:truncate fk:px-2 fk:py-1.5 fk:text-left fk:text-sm\"\n title={label}\n type=\"button\"\n onClick={onOpen}\n >\n {label}\n </button>\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n className=\"fk:size-6 fk:shrink-0 fk:opacity-0 fk:group-hover/chat:opacity-100 fk:data-[state=open]:opacity-100\"\n size=\"icon\"\n variant=\"ghost\"\n >\n <MoreHorizontalIcon className=\"fk:size-4\" />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align=\"start\">\n <DropdownMenuItem\n onClick={() => {\n setTitle(chat.title ?? '');\n setDialog('rename');\n }}\n >\n <PencilIcon className=\"fk:size-4\" />\n Rename\n </DropdownMenuItem>\n <DropdownMenuItem className=\"fk:text-destructive\" onClick={() => setDialog('delete')}>\n <Trash2Icon className=\"fk:size-4\" />\n Delete\n </DropdownMenuItem>\n </DropdownMenuContent>\n </DropdownMenu>\n <Dialog open={dialog === 'rename'} onOpenChange={(open) => setDialog(open ? 'rename' : null)}>\n <DialogContent className=\"fk:max-w-sm\">\n <DialogHeader>\n <DialogTitle>Rename chat</DialogTitle>\n </DialogHeader>\n <Input value={title} onChange={(event) => setTitle(event.target.value)} placeholder=\"Chat title\" />\n <DialogFooter>\n <Button disabled={isMutating || !title.trim()} size=\"sm\" onClick={handleRename}>\n {isMutating ? 'Saving...' : 'Save'}\n </Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n <Dialog open={dialog === 'delete'} onOpenChange={(open) => setDialog(open ? 'delete' : null)}>\n <DialogContent className=\"fk:max-w-sm\">\n <DialogHeader>\n <DialogTitle>Delete chat?</DialogTitle>\n </DialogHeader>\n <p className=\"fk:text-sm fk:text-muted-foreground\">\n “{label}” and its messages will be permanently deleted.\n </p>\n <DialogFooter>\n <Button disabled={isMutating} size=\"sm\" variant=\"destructive\" onClick={handleDelete}>\n {isMutating ? 'Deleting...' : 'Delete'}\n </Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n </div>\n );\n}\n\nfunction SearchResults({\n onOpen,\n projectId,\n query,\n}: {\n onOpen: (_chatId: string) => void;\n projectId: string;\n query: string;\n}): JSX.Element {\n const { data, isLoading } = useSWR<{ results: AgentChatSearchResult[] }>(\n paths(projectId).agentChatSearch(query),\n fetcher,\n { keepPreviousData: true }\n );\n\n if (isLoading && !data) {\n return (\n <div className=\"fk:flex fk:items-center fk:gap-2 fk:px-2 fk:py-3 fk:text-xs fk:text-muted-foreground\">\n <LoaderCircle className=\"fk:size-3.5 fk:animate-spin\" />\n Searching...\n </div>\n );\n }\n\n if (!data?.results.length) {\n return <p className=\"fk:px-2 fk:py-3 fk:text-xs fk:text-muted-foreground\">No matching chats.</p>;\n }\n\n return (\n <div className=\"fk:space-y-1\">\n {data.results.map((result) => (\n <button\n 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\"\n key={result.messageId}\n type=\"button\"\n onClick={() => onOpen(result.chatId)}\n >\n <span className=\"fk:block fk:truncate fk:text-sm\">{result.chatTitle?.trim() || 'New chat'}</span>\n <span className=\"fk:block fk:truncate fk:text-xs fk:text-muted-foreground\">{result.snippet}</span>\n </button>\n ))}\n </div>\n );\n}\n\n/**\n * ChatGPT-style chats section embedded in the AI sidebar: new chat button and\n * the user's recent chats grouped by date with rename/delete. When `query` is\n * set, the recent list is replaced by hybrid keyword + semantic search results.\n * Rendered inside the app layout route, so relative navigation resolves\n * against the app root (`agent`, `agent/chats/:chatId`).\n */\nexport function AgentChatsSection({ query }: { query: string }): JSX.Element | null {\n const { api, projectId } = useProjectApi();\n const navigate = useNavigate();\n const location = useLocation();\n const { mutate: globalMutate } = useSWRConfig();\n const activeChatId = /\\/agent\\/chats\\/([^/]+)/.exec(location.pathname)?.[1];\n const { data, isLoading, mutate, setSize, size } = useSWRInfinite<AgentChatsList>(\n (pageIndex, previousPage: AgentChatsList | null) => {\n if (!projectId || (previousPage && !previousPage.hasMore)) {\n return null;\n }\n\n return paths(projectId).agentChats(pageIndex * 30);\n },\n fetcher,\n { revalidateFirstPage: true }\n );\n const { data: activeChatDetail } = useSWR<AgentChatDetail>(\n projectId && activeChatId ? paths(projectId).agentChat(activeChatId) : null,\n fetcher\n );\n const chats = useMemo(() => {\n const listed = (data ?? []).flatMap((page) => page.chats);\n const generatedTitle = activeChatDetail?.chat.title?.trim();\n\n if (!activeChatId || !generatedTitle) {\n return listed;\n }\n\n return listed.map((chat) => {\n if (chat.id !== activeChatId || chat.title?.trim()) {\n return chat;\n }\n\n return { ...chat, title: generatedTitle };\n });\n }, [activeChatDetail?.chat.title, activeChatId, data]);\n const hasMore = data?.[data.length - 1]?.hasMore ?? false;\n const groups = useMemo(() => groupChats(chats), [chats]);\n\n // Refresh the list when the user lands on a chat (new chats, fresh titles).\n useEffect(() => {\n void mutate();\n }, [activeChatId, mutate]);\n\n if (!projectId || !api) {\n return null;\n }\n\n const chatApi = api;\n const chatProjectId = projectId;\n\n function openChat(chatId: string): void {\n navigate(`agent/chats/${chatId}`);\n }\n\n function handleDeleted(chatId: string): void {\n void mutate();\n\n if (chatId === activeChatId) {\n navigate('agent');\n } else {\n // Drop the cached detail so a re-open does not show stale data.\n void globalMutate(paths(chatProjectId).agentChat(chatId), undefined, { revalidate: false });\n }\n }\n\n return (\n <div className=\"fk:space-y-2\">\n {query ? (\n <SearchResults projectId={chatProjectId} query={query} onOpen={openChat} />\n ) : (\n <div className=\"fk:space-y-3\">\n {groups.map((group) => (\n <div key={group.label}>\n <p className=\"fk:px-2 fk:pb-1 fk:text-xs fk:font-medium fk:text-muted-foreground\">{group.label}</p>\n <div className=\"fk:space-y-0.5\">\n {group.chats.map((chat) => (\n <ChatListItem\n active={chat.id === activeChatId}\n api={chatApi}\n chat={chat}\n key={chat.id}\n onChanged={() => void mutate()}\n onDeleted={() => handleDeleted(chat.id)}\n onOpen={() => openChat(chat.id)}\n />\n ))}\n </div>\n </div>\n ))}\n {isLoading ? (\n <div className=\"fk:flex fk:items-center fk:gap-2 fk:px-2 fk:py-3 fk:text-xs fk:text-muted-foreground\">\n <LoaderCircle className=\"fk:size-3.5 fk:animate-spin\" />\n Loading recent chats...\n </div>\n ) : null}\n {!isLoading && chats.length === 0 ? (\n <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\">\n <MessageSquareIcon className=\"fk:size-5\" />\n <span>No chats yet. Start a conversation with the agent.</span>\n </div>\n ) : null}\n {hasMore ? (\n <Button className=\"fk:w-full\" size=\"sm\" variant=\"ghost\" onClick={() => void setSize(size + 1)}>\n Load more\n </Button>\n ) : null}\n </div>\n )}\n </div>\n );\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/apps/ai/agent/chat-list.tsx"],"names":["useAgentBasePath","location","useLocation","marker","index","useDebouncedValue","value","delayMs","debounced","setDebounced","useState","useEffect","timeout","getChatGroupLabel","chat","timestamp","now","startOfToday","groupChats","chats","groups","label","group","candidate","ChatListItem","active","api","onChanged","onDeleted","onOpen","dialog","setDialog","title","setTitle","isMutating","startMutation","useTransition","handleRename","handleDelete","jsxs","jsx","DropdownMenu","DropdownMenuTrigger","Button","MoreHorizontalIcon","DropdownMenuContent","DropdownMenuItem","PencilIcon","Trash2Icon","Dialog","open","DialogContent","DialogHeader","DialogTitle","Input","event","DialogFooter","SearchResults","projectId","query","data","isLoading","useSWR","paths","fetcher","LoaderCircle","result","AgentChatsSection","useProjectApi","navigate","useNavigate","globalMutate","useSWRConfig","activeChatId","mutate","setSize","size","useSWRInfinite","pageIndex","previousPage","activeChatDetail","useMemo","listed","page","generatedTitle","hasMore","chatApi","chatProjectId","openChat","chatId","handleDeleted","MessageSquareIcon"],"mappings":"gkBAwBO,SAASA,EAAAA,EAA2B,CACzC,IAAMC,CAAAA,CAAWC,WAAAA,EAAY,CACvBC,CAAAA,CAAS,QAAA,CACTC,CAAAA,CAAQH,CAAAA,CAAS,QAAA,CAAS,OAAA,CAAQE,CAAM,CAAA,CAE9C,OAAIC,CAAAA,GAAU,EAAA,CACL,CAAA,EAAGH,CAAAA,CAAS,SAAS,OAAA,CAAQ,KAAA,CAAO,EAAE,CAAC,CAAA,MAAA,CAAA,CAGzCA,CA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,IAAM0E,CAAAA,CAAS1E,CAAAA,CAAK,EAAE,CAAA,CAAA,CAHzBA,CAAAA,CAAK,EAIZ,CACD,CAAA,CACH,CAAA,CAAA,CAAA,CAdQQ,CAAAA,CAAM,KAehB,CACD,CAAA,CACAuC,GAAAA,CACCtB,IAAAA,CAAC,KAAA,CAAA,CAAI,SAAA,CAAU,sFAAA,CACb,QAAA,CAAA,CAAAC,GAAAA,CAACyB,YAAAA,CAAA,CAAa,SAAA,CAAU,6BAAA,CAA8B,CAAA,CAAE,yBAAA,CAAA,CAE1D,CAAA,CACE,IAAA,CACH,CAACJ,GAAAA,EAAa1C,CAAAA,CAAM,MAAA,GAAW,CAAA,CAC9BoB,IAAAA,CAAC,KAAA,CAAA,CAAI,SAAA,CAAU,iHAAA,CACb,QAAA,CAAA,CAAAC,GAAAA,CAACmD,iBAAAA,CAAA,CAAkB,SAAA,CAAU,WAAA,CAAY,CAAA,CACzCnD,GAAAA,CAAC,MAAA,CAAA,CAAK,QAAA,CAAA,oDAAA,CAAkD,CAAA,CAAA,CAC1D,CAAA,CACE,IAAA,CACH6C,CAAAA,CACC7C,GAAAA,CAACG,CAAAA,CAAA,CAAO,SAAA,CAAU,WAAA,CAAY,IAAA,CAAK,IAAA,CAAK,OAAA,CAAQ,OAAA,CAAQ,OAAA,CAAS,IAAG,CAAQgC,CAAAA,CAAQC,CAAAA,CAAO,CAAC,EAAA,CAAA,CAAG,QAAA,CAAA,WAAA,CAE/F,CAAA,CACE,IAAA,CAAA,CACN,CAAA,CAEJ,CAEJ","file":"chunk-XV4QJKOJ.js","sourcesContent":["import type { JSX } from 'react';\nimport { useEffect, useMemo, useState, useTransition } from 'react';\nimport { LoaderCircle, MessageSquareIcon, MoreHorizontalIcon, PencilIcon, Trash2Icon } from 'lucide-react';\nimport { useLocation, useNavigate } from 'react-router-dom';\nimport useSWR, { useSWRConfig } from 'swr';\nimport useSWRInfinite from 'swr/infinite';\nimport {\n Button,\n Dialog,\n DialogContent,\n DialogFooter,\n DialogHeader,\n DialogTitle,\n DropdownMenu,\n DropdownMenuContent,\n DropdownMenuItem,\n DropdownMenuTrigger,\n Input,\n} from '../../../ui';\nimport { fetcher, paths, type ApiClient } from '../api';\nimport { useProjectApi } from '../replay';\nimport type { AgentChat, AgentChatDetail, AgentChatSearchResult, AgentChatsList } from '../types';\n\n/** Returns the absolute route prefix of the agent app (`.../ai/agent`). */\nexport function useAgentBasePath(): string {\n const location = useLocation();\n const marker = '/agent';\n const index = location.pathname.indexOf(marker);\n\n if (index === -1) {\n return `${location.pathname.replace(/\\/$/, '')}/agent`;\n }\n\n return location.pathname.slice(0, index + marker.length);\n}\n\nexport function useDebouncedValue(value: string, delayMs: number): string {\n const [debounced, setDebounced] = useState(value);\n\n useEffect(() => {\n const timeout = window.setTimeout(() => {\n setDebounced(value);\n }, delayMs);\n\n return () => {\n window.clearTimeout(timeout);\n };\n }, [delayMs, value]);\n\n return debounced;\n}\n\nfunction getChatGroupLabel(chat: AgentChat): string {\n const timestamp = new Date(chat.lastMessageAt ?? chat.updatedAt).getTime();\n const now = new Date();\n const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();\n\n if (timestamp >= startOfToday) {\n return 'Today';\n }\n\n if (timestamp >= startOfToday - 86_400_000) {\n return 'Yesterday';\n }\n\n if (timestamp >= startOfToday - 7 * 86_400_000) {\n return 'Previous 7 days';\n }\n\n return 'Older';\n}\n\nfunction groupChats(chats: AgentChat[]): { chats: AgentChat[]; label: string }[] {\n const groups: { chats: AgentChat[]; label: string }[] = [];\n\n for (const chat of chats) {\n const label = getChatGroupLabel(chat);\n const group = groups.find((candidate) => candidate.label === label);\n\n if (group) {\n group.chats.push(chat);\n } else {\n groups.push({ chats: [chat], label });\n }\n }\n\n return groups;\n}\n\nfunction ChatListItem({\n active,\n api,\n chat,\n onChanged,\n onDeleted,\n onOpen,\n}: {\n active: boolean;\n api: ApiClient;\n chat: AgentChat;\n onChanged: () => void;\n onDeleted: () => void;\n onOpen: () => void;\n}): JSX.Element {\n const [dialog, setDialog] = useState<'rename' | 'delete' | null>(null);\n const [title, setTitle] = useState(chat.title ?? '');\n const [isMutating, startMutation] = useTransition();\n const label = chat.title?.trim() || 'New chat';\n\n function handleRename(): void {\n startMutation(async () => {\n await api.renameAgentChat(chat.id, title.trim());\n setDialog(null);\n onChanged();\n });\n }\n\n function handleDelete(): void {\n startMutation(async () => {\n await api.deleteAgentChat(chat.id);\n setDialog(null);\n onDeleted();\n });\n }\n\n return (\n <div\n className={`fk:group/chat fk:flex fk:items-center fk:gap-1 fk:rounded-md fk:pr-1 ${\n active ? 'fk:bg-sidebar-accent' : 'fk:hover:bg-accent/60'\n } fk:corner-squircle`}\n >\n <button\n className=\"fk:min-w-0 fk:flex-1 fk:truncate fk:px-2 fk:py-1.5 fk:text-left fk:text-sm\"\n title={label}\n type=\"button\"\n onClick={onOpen}\n >\n {label}\n </button>\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n className=\"fk:size-6 fk:shrink-0 fk:opacity-0 fk:group-hover/chat:opacity-100 fk:data-[state=open]:opacity-100\"\n size=\"icon\"\n variant=\"ghost\"\n >\n <MoreHorizontalIcon className=\"fk:size-4\" />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align=\"start\">\n <DropdownMenuItem\n onClick={() => {\n setTitle(chat.title ?? '');\n setDialog('rename');\n }}\n >\n <PencilIcon className=\"fk:size-4\" />\n Rename\n </DropdownMenuItem>\n <DropdownMenuItem className=\"fk:text-destructive\" onClick={() => setDialog('delete')}>\n <Trash2Icon className=\"fk:size-4\" />\n Delete\n </DropdownMenuItem>\n </DropdownMenuContent>\n </DropdownMenu>\n <Dialog open={dialog === 'rename'} onOpenChange={(open) => setDialog(open ? 'rename' : null)}>\n <DialogContent className=\"fk:max-w-sm\">\n <DialogHeader>\n <DialogTitle>Rename chat</DialogTitle>\n </DialogHeader>\n <Input value={title} onChange={(event) => setTitle(event.target.value)} placeholder=\"Chat title\" />\n <DialogFooter>\n <Button disabled={isMutating || !title.trim()} size=\"sm\" onClick={handleRename}>\n {isMutating ? 'Saving...' : 'Save'}\n </Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n <Dialog open={dialog === 'delete'} onOpenChange={(open) => setDialog(open ? 'delete' : null)}>\n <DialogContent className=\"fk:max-w-sm\">\n <DialogHeader>\n <DialogTitle>Delete chat?</DialogTitle>\n </DialogHeader>\n <p className=\"fk:text-sm fk:text-muted-foreground\">\n “{label}” and its messages will be permanently deleted.\n </p>\n <DialogFooter>\n <Button disabled={isMutating} size=\"sm\" variant=\"destructive\" onClick={handleDelete}>\n {isMutating ? 'Deleting...' : 'Delete'}\n </Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n </div>\n );\n}\n\nfunction SearchResults({\n onOpen,\n projectId,\n query,\n}: {\n onOpen: (_chatId: string) => void;\n projectId: string;\n query: string;\n}): JSX.Element {\n const { data, isLoading } = useSWR<{ results: AgentChatSearchResult[] }>(\n paths(projectId).agentChatSearch(query),\n fetcher,\n { keepPreviousData: true }\n );\n\n if (isLoading && !data) {\n return (\n <div className=\"fk:flex fk:items-center fk:gap-2 fk:px-2 fk:py-3 fk:text-xs fk:text-muted-foreground\">\n <LoaderCircle className=\"fk:size-3.5 fk:animate-spin\" />\n Searching...\n </div>\n );\n }\n\n if (!data?.results.length) {\n return <p className=\"fk:px-2 fk:py-3 fk:text-xs fk:text-muted-foreground\">No matching chats.</p>;\n }\n\n return (\n <div className=\"fk:space-y-1\">\n {data.results.map((result) => (\n <button\n 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\"\n key={result.messageId}\n type=\"button\"\n onClick={() => onOpen(result.chatId)}\n >\n <span className=\"fk:block fk:truncate fk:text-sm\">{result.chatTitle?.trim() || 'New chat'}</span>\n <span className=\"fk:block fk:truncate fk:text-xs fk:text-muted-foreground\">{result.snippet}</span>\n </button>\n ))}\n </div>\n );\n}\n\n/**\n * ChatGPT-style chats section embedded in the AI sidebar: new chat button and\n * the user's recent chats grouped by date with rename/delete. When `query` is\n * set, the recent list is replaced by hybrid keyword + semantic search results.\n * Rendered inside the app layout route, so relative navigation resolves\n * against the app root (`agent`, `agent/chats/:chatId`).\n */\nexport function AgentChatsSection({ query }: { query: string }): JSX.Element | null {\n const { api, projectId } = useProjectApi();\n const navigate = useNavigate();\n const location = useLocation();\n const { mutate: globalMutate } = useSWRConfig();\n const activeChatId = /\\/agent\\/chats\\/([^/]+)/.exec(location.pathname)?.[1];\n const { data, isLoading, mutate, setSize, size } = useSWRInfinite<AgentChatsList>(\n (pageIndex, previousPage: AgentChatsList | null) => {\n if (!projectId || (previousPage && !previousPage.hasMore)) {\n return null;\n }\n\n return paths(projectId).agentChats(pageIndex * 30);\n },\n fetcher,\n { revalidateFirstPage: true }\n );\n const { data: activeChatDetail } = useSWR<AgentChatDetail>(\n projectId && activeChatId ? paths(projectId).agentChat(activeChatId) : null,\n fetcher\n );\n const chats = useMemo(() => {\n const listed = (data ?? []).flatMap((page) => page.chats);\n const generatedTitle = activeChatDetail?.chat.title?.trim();\n\n if (!activeChatId || !generatedTitle) {\n return listed;\n }\n\n return listed.map((chat) => {\n if (chat.id !== activeChatId || chat.title?.trim()) {\n return chat;\n }\n\n return { ...chat, title: generatedTitle };\n });\n }, [activeChatDetail?.chat.title, activeChatId, data]);\n const hasMore = data?.[data.length - 1]?.hasMore ?? false;\n const groups = useMemo(() => groupChats(chats), [chats]);\n\n // Refresh the list when the user lands on a chat (new chats, fresh titles).\n useEffect(() => {\n void mutate();\n }, [activeChatId, mutate]);\n\n if (!projectId || !api) {\n return null;\n }\n\n const chatApi = api;\n const chatProjectId = projectId;\n\n function openChat(chatId: string): void {\n navigate(`agent/chats/${chatId}`);\n }\n\n function handleDeleted(chatId: string): void {\n void mutate();\n\n if (chatId === activeChatId) {\n navigate('agent');\n } else {\n // Drop the cached detail so a re-open does not show stale data.\n void globalMutate(paths(chatProjectId).agentChat(chatId), undefined, { revalidate: false });\n }\n }\n\n return (\n <div className=\"fk:space-y-2\">\n {query ? (\n <SearchResults projectId={chatProjectId} query={query} onOpen={openChat} />\n ) : (\n <div className=\"fk:space-y-3\">\n {groups.map((group) => (\n <div key={group.label}>\n <p className=\"fk:px-2 fk:pb-1 fk:text-xs fk:font-medium fk:text-muted-foreground\">{group.label}</p>\n <div className=\"fk:space-y-0.5\">\n {group.chats.map((chat) => (\n <ChatListItem\n active={chat.id === activeChatId}\n api={chatApi}\n chat={chat}\n key={chat.id}\n onChanged={() => void mutate()}\n onDeleted={() => handleDeleted(chat.id)}\n onOpen={() => openChat(chat.id)}\n />\n ))}\n </div>\n </div>\n ))}\n {isLoading ? (\n <div className=\"fk:flex fk:items-center fk:gap-2 fk:px-2 fk:py-3 fk:text-xs fk:text-muted-foreground\">\n <LoaderCircle className=\"fk:size-3.5 fk:animate-spin\" />\n Loading recent chats...\n </div>\n ) : null}\n {!isLoading && chats.length === 0 ? (\n <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\">\n <MessageSquareIcon className=\"fk:size-5\" />\n <span>No chats yet. Start a conversation with the agent.</span>\n </div>\n ) : null}\n {hasMore ? (\n <Button className=\"fk:w-full\" size=\"sm\" variant=\"ghost\" onClick={() => void setSize(size + 1)}>\n Load more\n </Button>\n ) : null}\n </div>\n )}\n </div>\n );\n}\n"]}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import'./index.css';import {a}from'./chunk-QSTWBKPN.js';import {d as d$4}from'./chunk-L5Z56DDM.js';import {g,f as f$1,d}from'./chunk-PLCI2RJA.js';import {d as d$2,i,f as f$2,h}from'./chunk-36YXPN42.js';import {b as b$4}from'./chunk-DSLPTDZX.js';import {o,e as e$1}from'./chunk-7KLXWCDS.js';import {f,d as d$3}from'./chunk-CC2U7ASG.js';import {b as b$3}from'./chunk-5CVDMZUI.js';import {la as la$1,Lb,Ob,mb,Cc,Dc,Ec,ma as ma$1,n,ra as ra$1,Y,Z,aa as aa$1,ba as ba$1,_,ca as ca$1}from'./chunk-RULCANNM.js';import {t as t$1}from'./chunk-A4DPLZZF.js';import {d as d$1,b as b$5}from'./chunk-G5N6HEPW.js';import {b as b$1}from'./chunk-5JUG4BEF.js';import {k,p,q,s,t,r,n as n$1}from'./chunk-S7Z6KKIN.js';import {b as b$2,c,e}from'./chunk-N33S7BSG.js';import {c as c$1}from'./chunk-X3SHNHHM.js';import {lazy,createContext,useCallback,useState,useRef,useEffect,useMemo,useContext,useTransition,useId,Suspense,useSyncExternalStore}from'react';import Ya,{useSWRConfig}from'swr';import {formatDistance,format}from'date-fns';import {RadarIcon,BotIcon,XIcon,PlugIcon,XCircleIcon,LoaderCircle,CheckIcon,CloudUploadIcon,FileTextIcon,DownloadIcon,LinkIcon,MessageSquareIcon,SendIcon,LibraryIcon,ChevronDownIcon,BookOpenIcon,HistoryIcon,CheckCircle2Icon,CircleSlashIcon,ShieldIcon,DatabaseZapIcon,MessageCircleQuestionIcon,ShieldCheckIcon,TriangleAlertIcon,PlayIcon,ArrowRightIcon,FileIcon,BookOpenTextIcon,CornerDownRightIcon,CircleAlertIcon,MoveRightIcon}from'lucide-react';import {Link,useNavigate}from'react-router-dom';import {jsx,jsxs,Fragment}from'react/jsx-runtime';import {pipeJsonRender}from'@json-render/core';import {readUIMessageStream,parseJsonEventStream,uiMessageChunkSchema}from'ai';function Nt(){let{currentProjectId:e}=f(),{mutate:t}=useSWRConfig();return useCallback(n=>{if(!e)return;let a=g(e).approvalsCount;n?t(a,n,{revalidate:true}):t(a),t(g(e).activitySummary());},[e,t])}function At(e,t){let n=e.split(`
|
|
2
|
+
`),a=t.split(`
|
|
3
|
+
`);if(n.length*a.length>25e5)return null;let s=a.length+1,r=new Uint32Array((n.length+1)*s);for(let f=n.length-1;f>=0;f--)for(let c=a.length-1;c>=0;c--)r[f*s+c]=n[f]===a[c]?r[(f+1)*s+c+1]+1:Math.max(r[(f+1)*s+c],r[f*s+c+1]);let l=[],d=0,u=0;for(;d<n.length&&u<a.length;)n[d]===a[u]?(l.push({kind:"same",text:n[d]}),d++,u++):r[(d+1)*s+u]>=r[d*s+u+1]?(l.push({kind:"removed",text:n[d]}),d++):(l.push({kind:"added",text:a[u]}),u++);for(;d<n.length;d++)l.push({kind:"removed",text:n[d]});for(;u<a.length;u++)l.push({kind:"added",text:a[u]});return l}var Jn=5e3,Qn=150,Xe=new Set;function Hn(e){return async()=>{let t=await fetch(e,{credentials:"include",mode:"cors"});return t.status===404?"missing":t.ok?(await t.json()).approval??"missing":null}}function Kn(e,t,n=d$3){return !e||e.kind!=="schema"||e.status!=="approved"||e.error?false:e.executedAt?(n(t),false):true}function Ae({approvalId:e,approvalUrl:t,fetchApproval:n,projectId:a,revalidate:s=d$3,sleep:r=l=>new Promise(d=>setTimeout(d,l))}){let l=`${a}:${e}`,d=n??(t?Hn(t):null);!d||Xe.has(l)||(Xe.add(l),(async()=>{try{for(let u=0;u<Qn;u+=1){let f=null;try{f=await d();}catch{f=null;}if(f==="missing"||f!==null&&!Kn(f,a,s))return;await r(Jn);}}finally{Xe.delete(l);}})());}var na=lazy(()=>import('./skills-pages-Q4YUDTC2.js').then(e=>({default:e.SkillContentPane}))),aa={approved:"fk:bg-success/20 fk:text-success",cancelled:"fk:bg-secondary fk:text-secondary-foreground",expired:"fk:bg-secondary fk:text-secondary-foreground",pending:"fk:bg-amber-500/20 fk:text-amber-600",rejected:"fk:bg-destructive/15 fk:text-destructive"};function sa({status:e}){return jsx(b$1,{className:`fk:border-none fk:h-4.75 fk:text-[0.6875rem] fk:leading-4.5 fk:tracking-wide ${aa[e]}`,variant:"secondary",children:e})}function J(e){return e==null?"\u2014":typeof e=="object"?JSON.stringify(e):String(e)}function It({after:e,before:t}){let n=J(t),a=J(e);return n===a?jsx("span",{className:"fk:text-muted-foreground",children:n}):jsxs("span",{className:"fk:inline-flex fk:flex-wrap fk:items-center fk:gap-1.5",children:[jsx("span",{className:"fk:rounded fk:bg-destructive/10 fk:px-1 fk:text-destructive fk:line-through fk:corner-squircle",children:n}),jsx(MoveRightIcon,{className:"fk:size-3 fk:shrink-0 fk:text-muted-foreground"}),jsx("span",{className:"fk:rounded fk:bg-success/15 fk:px-1 fk:text-success fk:corner-squircle",children:a})]})}function ra(e){let t=e.entity??"entities",n=e.affectedCount!==null?` \xB7 ${e.affectedCount.toString()} affected`:"";return e.kind==="create"?`Create ${t}${n}`:e.kind==="update"?`Update ${t}${n}`:e.kind==="delete"?`Delete ${t}${n}`:`Mutation on ${t}${n}`}function oa({operation:e}){if(e.rows.length===0)return null;let t=(e.contextColumns??[]).filter(a=>a!=="_id");if(e.kind==="delete")return jsxs(Y,{children:[jsx(Z,{children:jsxs(aa$1,{children:[jsx(ba$1,{children:"Records to delete"}),t.map(a=>jsx(ba$1,{children:a},a))]})}),jsx(_,{children:e.rows.map((a,s)=>jsxs(aa$1,{className:"fk:bg-destructive/5",children:[jsx(ca$1,{className:"fk:font-mono fk:text-xs fk:text-destructive",children:a.id??J(a.before?._id)}),t.map(r=>jsx(ca$1,{className:"fk:text-xs fk:text-muted-foreground",children:J(a.before?.[r])},r))]},a.id??s.toString()))})]});let n=e.columns.filter(a=>a!=="_id"&&!t.includes(a));return jsxs(Y,{children:[jsx(Z,{children:jsxs(aa$1,{children:[jsx(ba$1,{children:"ID"}),t.map(a=>jsx(ba$1,{children:a},a)),n.map(a=>jsx(ba$1,{children:a},a))]})}),jsx(_,{children:e.rows.map((a,s)=>jsxs(aa$1,{children:[jsx(ca$1,{className:"fk:font-mono fk:text-xs fk:text-muted-foreground",children:a.id??"\u2014"}),t.map(r=>jsx(ca$1,{className:"fk:max-w-72 fk:text-xs fk:text-muted-foreground",children:jsx("span",{className:"fk:line-clamp-3",children:J(a.before?.[r])})},r)),n.map(r=>jsx(ca$1,{className:"fk:text-xs",children:e.kind==="create"?jsx("span",{className:"fk:rounded fk:bg-success/15 fk:px-1 fk:text-success fk:corner-squircle",children:J(a.after?.[r])}):jsx(It,{after:a.after?.[r],before:a.before?.[r]})},r))]},a.id??s.toString()))})]})}function ia({operations:e,plugin:t,chat:n,title:a}){return jsxs("details",{className:"fk:rounded-md fk:border fk:border-border fk:corner-squircle",children:[jsx("summary",{className:"fk:cursor-pointer fk:px-3 fk:py-2 fk:text-xs fk:font-medium fk:text-muted-foreground",children:a??(n?"Action details":t?"Plugin tool and arguments":`GraphQL documents (${e.length})`)}),jsx("div",{className:"fk:space-y-3 fk:border-t fk:border-border fk:p-3",children:e.map((s,r)=>jsxs("div",{className:"fk:space-y-2",children:[jsx("pre",{className:"fk:overflow-x-auto fk:rounded-md fk:bg-muted fk:p-3 fk:text-xs fk:corner-squircle",children:s.query}),s.variables&&Object.keys(s.variables).length>0?jsx("pre",{className:"fk:overflow-x-auto fk:rounded-md fk:bg-muted/60 fk:p-3 fk:text-xs fk:corner-squircle",children:JSON.stringify(s.variables,null,2)}):null]},r.toString()))})]})}function Et(e){if(e.kind!=="plugin")return null;let n=e.operations[0]?.query.split(`
|
|
4
|
+
`)[0]?.trim()?.split("/"),a=n?.at(-1),s=n?.[0];if(!a||!s||n?.length<2)return null;let r=a.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").toLowerCase(),l=s.replace(/[_-]+/g," ").replace(/\b\w/g,c=>c.toUpperCase()),d=e.operations[0]?.query??"",u=/^Connection:\s*(Project|Personal)\s+—\s+(.+)$/m.exec(d);if(u?.[1]&&u[2])return {action:r,app:l,account:u[2].trim(),scope:u[1]==="Project"?"project":"personal"};let f=/^Connection:.*?([^\s<>]+@[^\s<>]+)\s*$/m.exec(d)?.[1];return {action:r,app:l,account:f}}function la(e){let t=Et(e);if(t)return `${t.action.charAt(0).toUpperCase()}${t.action.slice(1)} in ${t.app}`;if(e.kind==="exec")return "Run a sandbox command";if(e.kind==="schema")return e.operationsSummary.replace(/^Schema: /,"");if(e.kind==="automation"&&e.preview?.automation)return `Create the automation \u201C${e.preview.automation.name}\u201D`;if(e.kind==="automation"&&e.preview?.automationChange)return `Change the automation \u201C${e.preview.automationChange.name}\u201D`;if(e.kind==="skill"&&e.preview?.skill){let{before:n,name:a}=e.preview.skill;return n?`Change the skill \u201C${n.name}\u201D`:`Create the skill \u201C${a}\u201D`}return e.kind==="plugin"?"Use a connected app":e.operationsSummary}function ua({operation:e}){if(e.rows.length===0)return null;let t=a=>a!=null&&a!==false,n=e.columns.filter(a=>e.rows.some(r=>t(r.before?.[a])||t(r.after?.[a]))?e.kind!=="update"?true:e.rows.some(r=>J(r.before?.[a])!==J(r.after?.[a])):false);return jsx("div",{className:"fk:overflow-x-auto fk:rounded-md fk:border fk:border-border fk:corner-squircle",children:jsxs(Y,{className:"fk:text-xs",children:[jsx(Z,{children:jsxs(aa$1,{children:[jsx(ba$1,{className:"fk:h-8",children:e.entity==="scopes"||e.entity==="spaces"||e.entity==="studio"?"Setting":"Attribute"}),n.map(a=>jsx(ba$1,{className:"fk:h-8",children:a},a))]})}),jsx(_,{children:e.rows.map((a,s)=>jsxs(aa$1,{children:[jsxs(ca$1,{className:"fk:py-1.5 fk:font-mono fk:text-[0.7rem]",children:[e.kind==="delete"?jsx("span",{className:"fk:line-through fk:text-destructive",children:a.id}):a.id,e.kind==="update"&&a.before===null?jsx(b$1,{className:"fk:ml-2",variant:"secondary",children:"new"}):null,e.kind==="update"&&a.after===null?jsx(b$1,{className:"fk:ml-2",variant:"destructive",children:"removed"}):null]}),n.map(r=>jsx(ca$1,{className:"fk:py-1.5",children:e.kind==="create"?jsx("span",{children:J(a.after?.[r])}):e.kind==="delete"?jsx("span",{className:"fk:text-muted-foreground",children:J(a.before?.[r])}):jsx(It,{after:a.after?.[r],before:a.before?.[r]})},r))]},a.id??s.toString()))})]})})}function da(e){let t=e.entity??"schema";return t==="scopes"||t==="spaces"||t==="studio"?`Change ${t==="studio"?"Studio settings":t}`:e.kind==="create"?`Add entity ${t} \xB7 ${e.rows.length.toString()} attribute${e.rows.length===1?"":"s"}`:e.kind==="delete"?`Remove entity ${t}`:`Change entity ${t}`}function ca({preview:e}){let t=e.schema;return jsxs("div",{className:"fk:space-y-4",children:[t&&t.breakingChanges.length>0?jsxs("div",{className:"fk:rounded-md fk:border fk:border-destructive/30 fk:bg-destructive/5 fk:p-3 fk:text-sm fk:corner-squircle",children:[jsxs("div",{className:"fk:mb-1 fk:flex fk:items-center fk:gap-2 fk:font-medium fk:text-destructive",children:[jsx(TriangleAlertIcon,{className:"fk:size-4"}),"Breaking changes: existing data becomes inaccessible"]}),jsx("ul",{className:"fk:list-disc fk:pl-5 fk:text-destructive",children:t.breakingChanges.map(n=>jsx("li",{children:n},n))})]}):null,t&&t.warnings.length>0?jsx("div",{className:"fk:rounded-md fk:border fk:border-amber-500/40 fk:bg-amber-500/10 fk:p-3 fk:text-sm fk:corner-squircle",children:jsx("ul",{className:"fk:list-disc fk:pl-5",children:t.warnings.map(n=>jsx("li",{children:n},n))})}):null,e.operations.map((n,a)=>jsxs("div",{className:"fk:space-y-2",children:[jsx("div",{className:`fk:text-sm fk:font-medium ${n.kind==="delete"?"fk:text-destructive":""}`,children:da(n)}),jsx(ua,{operation:n})]},`${n.entity??""}-${a.toString()}`)),e.operations.length===0?jsx("div",{className:"fk:rounded-md fk:border fk:border-dashed fk:p-3 fk:text-xs fk:text-muted-foreground fk:corner-squircle",children:"No visible entity changes. Review the operations below."}):null]})}function fa(e,t){return e.id===t.id&&e.status===t.status&&e.decidedAt===t.decidedAt&&e.decidedBy===t.decidedBy&&e.executedAt===t.executedAt&&e.error===t.error&&e.reason===t.reason&&e.expiresAt===t.expiresAt&&e.operationsSummary===t.operationsSummary&&e.affectedCount===t.affectedCount&&JSON.stringify(e.preview)===JSON.stringify(t.preview)}function Mt({api:e,approval:t,onDecided:n}){let[a,s]=useState(t),[r,l]=useState(t),[d,u]=useState(""),[f,c]=useTransition(),[p,x]=useState(false),[v,k]=useState(false),[g$1,w]=useState(""),y=Nt();t!==r&&(l(t),fa(t,r)||a.id===t.id&&a.status!=="pending"&&t.status==="pending"||s(t));function C(S){s(S),y(),S.kind==="schema"&&S.status==="approved"&&Ae({approvalId:S.id,approvalUrl:g(S.projectId).approval(S.id),projectId:S.projectId}),n?.(S);}function _({approved:S,automationEdits:R,force:$=false,reason:E,remember:Y=false,skillEdits:L}){c(async()=>{u("");try{let I=await e.decideApproval(a.id,{approved:S,...R?{automationEdits:R}:{},force:$,reason:E,remember:Y,...L?{skillEdits:L}:{}});if(I.errorCode==="stale_preview"){k(!0),I.approval&&s(I.approval);return}if(k(!1),x(!1),I.approval?C(I.approval):I.success?C({...a,decidedAt:a.decidedAt??new Date().toISOString(),reason:E??a.reason,status:S?"approved":"rejected"}):I.errorCode==="already_decided"&&n?.(a),!I.success&&(I.errorCode!=="already_decided"||!I.approval)){let ge=Array.isArray(I.errorMessage)?I.errorMessage.join(", "):I.errorMessage;u(ge||"Failed to submit the decision.");}}catch(I){u(I instanceof Error?I.message:"Failed to submit the decision.");}});}return {approval:a,decide:_,errorMessage:d,isDeciding:f,isPending:a.status==="pending",isRejectDialogOpen:p,isStale:v,rejectReason:g$1,setIsRejectDialogOpen:x,setRejectReason:w}}function $t({allowRemember:e=false,askForRejectionReason:t$1,decide:n$1,isDeciding:a,isRejectDialogOpen:s$1,isStale:r$1,rejectReason:l,setIsRejectDialogOpen:d,setRejectReason:u,variant:f}){let c=f==="header",p$1=c?"fk:px-8 fk:min-w-32":void 0,x=c?"default":"sm",[v,k$1]=useState(false),g=useId();return jsxs(Fragment,{children:[jsxs("div",{className:"fk:flex fk:flex-nowrap fk:items-center fk:gap-2",children:[jsxs(c$1,{className:p$1,disabled:a,size:x,onClick:()=>n$1({approved:true,force:r$1,remember:e&&v}),children:[a?jsx(LoaderCircle,{className:"fk:size-4 fk:animate-spin"}):jsx(CheckIcon,{className:"fk:size-4"}),r$1?"Approve anyway":"Approve"]}),jsxs(c$1,{className:p$1,disabled:a,size:x,variant:"outline",onClick:()=>{t$1?(u(""),d(true)):n$1({approved:false});},children:[jsx(XIcon,{className:"fk:size-4"}),"Reject"]}),e?jsxs("label",{className:"fk:ml-1 fk:flex fk:cursor-pointer fk:items-center fk:gap-1.5 fk:whitespace-nowrap fk:text-xs fk:text-muted-foreground",htmlFor:g,children:[jsx(n,{checked:v,id:g,onCheckedChange:w=>k$1(w===true)}),"Always allow this tool for this automation"]}):null]}),t$1?jsx(k,{open:s$1,onOpenChange:d,children:jsxs(p,{children:[jsxs(q,{children:[jsx(s,{children:"Reject this proposal?"}),jsx(t,{children:"The mutation will not be executed. The agent receives your reason and can adapt its plan."})]}),jsx(d$1,{placeholder:"Optional reason for the agent...",value:l,onChange:w=>u(w.target.value)}),jsxs(r,{children:[jsx(c$1,{disabled:a,size:"sm",variant:"outline",onClick:()=>d(false),children:"Cancel"}),jsxs(c$1,{disabled:a,size:"sm",variant:"destructive",onClick:()=>n$1({approved:false,reason:l.trim()||void 0}),children:[a?jsx(LoaderCircle,{className:"fk:size-4 fk:animate-spin"}):jsx(ArrowRightIcon,{className:"fk:size-4"}),"Reject proposal"]})]})]})}):null]})}var pa={always:"Every finished run",failures:"Failures only",never:"Never",when_flagged:"Results that need attention"};function zt(e){return e.visibility==="personal"?"Only you":e.visibility==="space"?`Space: ${e.spaceLabel??"unknown"}`:"Everyone in the project"}function ma({approval:e,instructions:t,isPending:n,proposal:a,onInstructionsChange:s}){let r=useId(),l=e.createdAutomation??null,d=[...a.replacesMonitor?[{label:"Replaces",value:`The monitor \u201C${a.replacesMonitor}\u201D, which stops once this exists`}]:[],{label:"Runs",value:a.triggers.join(`
|
|
5
|
+
`)},{label:"Visible to",value:zt(a)},{label:"Data changes",value:a.mutationPolicy==="auto_approve"?"Applied without review":"Wait for approval"},{label:"Notifications",value:`${pa[a.notifyRule]}${a.notifyCreator?", to you":""}${a.subscribers.length>0?` and ${a.subscribers.join(", ")}`:""}`},...a.plugins.length>0?[{label:"Plugins",value:a.plugins.map(u=>[u.account?`${u.name} as ${u.account}`:u.name,u.deliveryChannels.length>0?`posting to ${u.deliveryChannels.join(", ")}`:""].filter(Boolean).join(", ")).join(`
|
|
6
|
+
`)}]:[],...a.skills.length>0?[{label:"Skills",value:a.skills.join(", ")}]:[],...a.customTools.length>0?[{label:"Custom tools",value:a.customTools.join(", ")}]:[],{label:"Model",value:a.modelLabel}];return jsxs("div",{className:"fk:space-y-4",children:[a.mutationPolicy==="auto_approve"?jsxs("div",{className:"fk:flex fk:items-start fk:gap-2 fk:rounded-md fk:border fk:border-amber-500/40 fk:bg-amber-500/10 fk:p-3 fk:text-sm fk:corner-squircle",role:"status",children:[jsx(TriangleAlertIcon,{className:"fk:mt-0.5 fk:size-4 fk:shrink-0 fk:text-amber-600"}),jsxs("span",{children:["Every run will change data",a.plugins.length>0?" and call these plugins":""," without asking anyone first. Reject and ask for review if that is not what you want."]})]}):null,jsx("dl",{className:"fk:grid fk:grid-cols-[max-content_1fr] fk:gap-x-4 fk:gap-y-1.5 fk:text-sm",children:d.map(u=>jsxs("div",{className:"fk:contents",children:[jsx("dt",{className:"fk:text-muted-foreground",children:u.label}),jsx("dd",{className:"fk:whitespace-pre-line",children:u.value})]},u.label))}),jsxs("div",{className:"fk:space-y-1.5",children:[jsx("label",{className:"fk:text-sm fk:font-medium",htmlFor:r,children:"Instructions"}),n&&s?jsxs(Fragment,{children:[jsx("p",{className:"fk:text-xs fk:text-muted-foreground",children:"The automation never sees this chat, so these instructions are all it has to go on. Edit them before creating it."}),jsx(d$1,{className:"fk:min-h-40 fk:text-sm",id:r,value:t,onChange:u=>s(u.target.value)})]}):jsx("p",{className:"fk:whitespace-pre-wrap fk:rounded-md fk:border fk:p-3 fk:text-sm fk:corner-squircle",id:r,children:t})]}),l?jsxs("div",{className:"fk:flex fk:flex-wrap fk:gap-2",children:[jsx(c$1,{asChild:true,size:"sm",variant:"outline",children:jsx(Link,{to:`/${e.projectId}/ai/automations/${l.automationId}`,children:"Open the automation"})}),l.runId?jsx(c$1,{asChild:true,size:"sm",variant:"ghost",children:jsx(Link,{to:`/${e.projectId}/ai/automations/${l.automationId}/runs/${l.runId}`,children:"View its first run"})}):null]}):null]})}function ka({approval:e,change:t}){let n=t.changes.filter(s=>s.field!=="instructions"),a=t.changes.find(s=>s.field==="instructions");return jsxs("div",{className:"fk:space-y-4",children:[n.length>0?jsx("dl",{className:"fk:grid fk:grid-cols-[max-content_1fr] fk:gap-x-4 fk:gap-y-2 fk:text-sm",children:n.map(s=>jsxs("div",{className:"fk:contents",children:[jsx("dt",{className:"fk:text-muted-foreground",children:s.label}),jsxs("dd",{className:"fk:space-y-0.5",children:[jsx("div",{className:"fk:whitespace-pre-line fk:text-muted-foreground fk:line-through",children:s.before}),jsx("div",{className:"fk:whitespace-pre-line",children:s.after})]})]},s.field))}):null,a?jsx("div",{className:"fk:grid fk:gap-3 fk:md:grid-cols-2",children:[{label:"Current instructions",muted:true,text:a.before},{label:"New instructions",muted:false,text:a.after}].map(s=>jsxs("div",{className:"fk:min-w-0 fk:space-y-1.5",children:[jsx("div",{className:"fk:text-sm fk:font-medium",children:s.label}),jsx("p",{className:`fk:whitespace-pre-wrap fk:rounded-md fk:border fk:p-3 fk:text-sm fk:corner-squircle${s.muted?" fk:text-muted-foreground":""}`,children:s.text})]},s.label))}):null,jsx(c$1,{asChild:true,size:"sm",variant:"outline",children:jsx(Link,{to:`/${e.projectId}/ai/automations/${t.automationId}`,children:"Open the automation"})})]})}function _t({decide:e,instructions:t,isDeciding:n,proposal:a}){let s=t.trim(),r=s!==a.instructions.trim()?{instructions:s}:{};return jsxs("div",{className:"fk:flex fk:flex-wrap fk:items-center fk:gap-2",children:[jsxs(c$1,{disabled:n||s.length===0,size:"sm",variant:a.runOnceAfterCreate?"outline":"default",onClick:()=>e({approved:true,automationEdits:{...r,runOnce:false}}),children:[n?jsx(LoaderCircle,{className:"fk:size-4 fk:animate-spin"}):jsx(CheckIcon,{className:"fk:size-4"}),"Create"]}),jsxs(c$1,{disabled:n||s.length===0,size:"sm",variant:a.runOnceAfterCreate?"default":"outline",onClick:()=>e({approved:true,automationEdits:{...r,runOnce:true}}),children:[jsx(PlayIcon,{className:"fk:size-4"}),"Create and run once now"]}),jsxs(c$1,{disabled:n,size:"sm",variant:"outline",onClick:()=>e({approved:false}),children:[jsx(XIcon,{className:"fk:size-4"}),"Reject"]})]})}var Rt=3;function ga(e){let t=[],n=0;for(;n<e.length;){if(e[n].kind!=="same"){t.push(e[n]),n++;continue}let a=n;for(;a<e.length&&e[a].kind==="same";)a++;let s=e.slice(n,a),r=n===0?0:Rt,l=a===e.length?0:Rt;s.length>r+l+1?t.push(...s.slice(0,r),{count:s.length-r-l,kind:"folded"},...s.slice(s.length-l)):t.push(...s),n=a;}return t}var Tt={added:{className:"fk:bg-success/10",marker:"+"},removed:{className:"fk:bg-destructive/10 fk:text-muted-foreground",marker:"\u2212"},same:{className:"",marker:" "}};function ha({after:e,before:t}){let n=useMemo(()=>At(t,e),[e,t]);if(!n)return jsx("p",{className:"fk:rounded-md fk:border fk:border-dashed fk:p-3 fk:text-xs fk:text-muted-foreground fk:corner-squircle",children:"The skill is too long to compare line by line. Review the new content below."});let a=n.filter(r=>r.kind==="added").length,s=n.filter(r=>r.kind==="removed").length;return jsxs("div",{className:"fk:space-y-1.5",children:[jsxs("div",{className:"fk:text-xs fk:text-muted-foreground",children:[jsxs("span",{className:"fk:text-success",children:["+",a.toString()]})," ",jsxs("span",{className:"fk:text-destructive",children:["\u2212",s.toString()]})," lines"]}),jsx("div",{className:"fk:max-h-96 fk:overflow-auto fk:rounded-md fk:border fk:py-1 fk:font-mono fk:text-xs fk:corner-squircle",children:ga(n).map((r,l)=>r.kind==="folded"?jsxs("div",{className:"fk:px-3 fk:py-0.5 fk:text-muted-foreground",children:["\u22EF ",r.count.toString()," unchanged ",r.count===1?"line":"lines"]},l.toString()):jsxs("div",{className:`fk:flex fk:gap-2 fk:px-3 ${Tt[r.kind].className}`,children:[jsx("span",{"aria-hidden":true,className:"fk:w-2 fk:shrink-0 fk:select-none fk:text-muted-foreground",children:Tt[r.kind].marker}),jsx("span",{className:"fk:min-w-0 fk:whitespace-pre-wrap fk:break-words",children:r.text||" "})]},l.toString()))})]})}function Dt({after:e,before:t,label:n}){return e===t?null:jsxs("div",{className:"fk:contents",children:[jsx("dt",{className:"fk:text-muted-foreground",children:n}),jsxs("dd",{className:"fk:space-y-0.5",children:[jsx("div",{className:"fk:whitespace-pre-line fk:text-muted-foreground fk:line-through",children:t}),jsx("div",{className:"fk:whitespace-pre-line",children:e})]})]})}function va({approval:e,fields:t,isPending:n,proposal:a,onFieldsChange:s}){let r=useId(),l=useId(),{before:d}=a,u=e.savedSkillId??a.skillId,f=n&&s;return jsxs("div",{className:"fk:space-y-4",children:[jsxs("dl",{className:"fk:grid fk:grid-cols-[max-content_1fr] fk:gap-x-4 fk:gap-y-2 fk:text-sm",children:[jsx("dt",{className:"fk:text-muted-foreground",children:"Visible to"}),jsx("dd",{children:zt(a)}),d?jsxs(Fragment,{children:[jsx(Dt,{after:t.name,before:d.name,label:"Name"}),jsx(Dt,{after:t.description,before:d.description,label:"Description"})]}):null]}),d?d.content===t.content?jsx("p",{className:"fk:text-sm fk:text-muted-foreground",children:"The content stays the same."}):jsxs("div",{className:"fk:space-y-1.5",children:[jsx("div",{className:"fk:text-sm fk:font-medium",children:"Changes to the content"}),jsx(ha,{after:t.content,before:d.content})]}):null,f?jsxs("div",{className:"fk:space-y-3",children:[jsx("p",{className:"fk:text-xs fk:text-muted-foreground",children:"Every chat and automation that can see this skill picks it by its description and follows its content. Edit them before saving."}),jsxs("div",{className:"fk:space-y-1.5",children:[jsx("label",{className:"fk:text-sm fk:font-medium",htmlFor:r,children:"Name"}),jsx(b$5,{id:r,maxLength:120,value:t.name,onChange:c=>s({...t,name:c.target.value})})]}),jsxs("div",{className:"fk:space-y-1.5",children:[jsx("label",{className:"fk:text-sm fk:font-medium",htmlFor:l,children:"Description"}),jsx(d$1,{className:"fk:min-h-16 fk:text-sm",id:l,maxLength:1024,value:t.description,onChange:c=>s({...t,description:c.target.value})})]}),jsx("div",{className:"fk:flex fk:h-96 fk:min-w-0 fk:flex-col",children:jsx(Suspense,{fallback:jsx(t$1,{className:"fk:min-h-0 fk:flex-1 fk:rounded-md"}),children:jsx(na,{content:t.content,onChange:c=>s({...t,content:c})})})})]}):jsxs("div",{className:"fk:space-y-3 fk:text-sm",children:[d?null:jsxs("div",{className:"fk:space-y-0.5",children:[jsx("div",{className:"fk:font-medium",children:"Description"}),jsx("p",{className:"fk:whitespace-pre-line fk:text-muted-foreground",children:t.description})]}),jsxs("details",{className:"fk:rounded-md fk:border fk:corner-squircle",children:[jsx("summary",{className:"fk:cursor-pointer fk:px-3 fk:py-2 fk:font-medium",children:"Content"}),jsx("pre",{className:"fk:max-h-96 fk:overflow-auto fk:whitespace-pre-wrap fk:border-t fk:p-3 fk:font-mono fk:text-xs",children:t.content})]})]}),u&&(!n||d)?jsx(c$1,{asChild:true,size:"sm",variant:"outline",children:jsx(Link,{to:`/${e.projectId}/ai/skills/${u}`,children:"Open the skill"})}):null]})}function Lt({decide:e,fields:t,isDeciding:n,proposal:a}){let s={content:t.content.trim(),description:t.description.trim(),name:t.name.trim()},r=!s.name||!s.description||!s.content,l=Object.fromEntries(Object.keys(s).filter(d=>s[d]!==a[d].trim()).map(d=>[d,s[d]]));return jsxs("div",{className:"fk:flex fk:flex-wrap fk:items-center fk:gap-2",children:[jsxs(c$1,{disabled:n||r,size:"sm",onClick:()=>e({approved:true,...Object.keys(l).length>0?{skillEdits:l}:{}}),children:[n?jsx(LoaderCircle,{className:"fk:size-4 fk:animate-spin"}):jsx(CheckIcon,{className:"fk:size-4"}),a.before?"Save changes":"Save skill"]}),jsxs(c$1,{disabled:n,size:"sm",variant:"outline",onClick:()=>e({approved:false}),children:[jsx(XIcon,{className:"fk:size-4"}),"Reject"]})]})}function jt(e){let t=e.kind==="skill"?e.preview?.skill??null:null,[n,a]=useState(null);return {fields:n?.approvalId===e.id?n.fields:t?{content:t.content,description:t.description,name:t.name}:null,proposal:t,setFields:r=>a({approvalId:e.id,fields:r})}}function Ot({approval:e,automationInstructions:t,chat:n,errorMessage:a,isPending:s,isStale:r,onAutomationInstructionsChange:l,onSkillFieldsChange:d,skillFields:u}){let{preview:f}=e,c=n?Et(e):null;return jsxs("div",{className:"fk:min-w-0 fk:max-w-full fk:space-y-4",children:[jsxs("div",{className:"fk:flex fk:flex-wrap fk:items-center fk:gap-2",children:[jsx(sa,{status:e.status}),e.kind==="schema"?jsx(b$1,{variant:"outline",children:"Schema change"}):null,e.kind==="automation"?jsx(b$1,{variant:"outline",children:f?.automationChange?"Automation change":"New automation"}):null,e.kind==="skill"?jsx(b$1,{variant:"outline",children:f?.skill?.before?"Skill change":"New skill"}):null,jsx("span",{className:"fk:text-sm fk:font-medium",children:n?la(e):e.operationsSummary})]}),jsxs("div",{className:"fk:text-xs fk:text-muted-foreground",children:[e.automationName?`${e.automationName} \xB7 `:"","requested ",formatDistance(new Date(e.requestedAt),new Date,{addSuffix:true}),s?` \xB7 expires ${formatDistance(new Date(e.expiresAt),new Date,{addSuffix:true})}`:"",e.decidedAt?` \xB7 decided ${format(new Date(e.decidedAt),"PPpp")}`:""]}),r?jsxs("div",{className:"fk:flex fk:items-start fk:gap-2 fk:rounded-md fk:border fk:border-amber-500/40 fk:bg-amber-500/10 fk:p-3 fk:text-sm fk:corner-squircle",children:[jsx(TriangleAlertIcon,{className:"fk:mt-0.5 fk:size-4 fk:shrink-0 fk:text-amber-600"}),jsx("span",{children:"The affected data changed since this proposal was created. The preview below has been refreshed \u2014 review it and approve again to proceed."})]}):null,e.kind==="automation"&&f?.automation?jsx(ma,{approval:e,instructions:t??f.automation.instructions,isPending:s,proposal:f.automation,onInstructionsChange:l}):e.kind==="automation"&&f?.automationChange?jsx(ka,{approval:e,change:f.automationChange}):e.kind==="skill"&&f?.skill?jsx(va,{approval:e,fields:u??f.skill,isPending:s,proposal:f.skill,onFieldsChange:d}):e.kind==="schema"&&f?jsx(ca,{preview:f}):f&&f.operations.length>0?jsx("div",{className:"fk:space-y-4",children:f.operations.map((p,x)=>jsxs("div",{className:"fk:space-y-2",children:[jsx("div",{className:"fk:text-sm fk:font-medium",children:ra(p)}),p.kind==="delete"&&p.affectedCount!==null?jsxs("div",{className:"fk:rounded-md fk:border fk:border-destructive/30 fk:bg-destructive/5 fk:p-3 fk:text-sm fk:text-destructive fk:corner-squircle",children:[p.affectedCount.toString()," record",p.affectedCount===1?"":"s"," will be permanently deleted."]}):null,jsx(oa,{operation:p}),p.truncated?jsxs("div",{className:"fk:text-xs fk:text-muted-foreground",children:["Preview limited to the first ",p.rows.length.toString()," rows."]}):null]},x.toString()))}):jsx("div",{className:"fk:rounded-md fk:border fk:border-dashed fk:p-3 fk:text-xs fk:text-muted-foreground fk:corner-squircle",children:n?c?`This action uses ${c.scope==="project"?"the project's":"your"} ${c.app} account${c.account?` (${c.account})`:""}. Check the details before deciding.`:"The assistant wants to make this change. Check the details before deciding.":e.kind==="plugin"?"Review the account, tool, and arguments before allowing this external call.":e.kind==="exec"?"This command runs inside the run's ephemeral sandbox but may send data out or reach other hosts. Review the command line before allowing it.":"No structured preview is available for this proposal. Review the raw GraphQL documents below."}),e.kind==="automation"||e.kind==="skill"?null:jsx(ia,{chat:n,operations:e.operations,plugin:e.kind==="plugin"||e.kind==="exec",title:e.kind==="exec"?"Command and options":e.kind==="schema"?"Operations":void 0}),e.reason?jsxs("div",{className:"fk:text-sm",children:[jsx("span",{className:"fk:font-medium",children:"Reason:"})," ",e.reason]}):null,e.error?jsxs("div",{className:"fk:rounded-md fk:border fk:border-destructive/30 fk:bg-destructive/5 fk:p-3 fk:text-sm fk:corner-squircle",children:["Execution failed: ",e.error]}):null,e.executedAt&&!e.error?jsxs("div",{className:"fk:flex fk:items-center fk:gap-2 fk:text-sm fk:text-success",children:[jsx(CheckIcon,{className:"fk:size-4"}),"Executed ",format(new Date(e.executedAt),"PPpp")]}):null,a?jsx("div",{className:"fk:text-sm fk:text-destructive",children:a}):null]})}function Ft({api:e,approval:t,chat:n,onDecided:a}){let{approval:s,decide:r,errorMessage:l,isDeciding:d,isPending:u,isRejectDialogOpen:f,isStale:c,rejectReason:p,setIsRejectDialogOpen:x,setRejectReason:v}=Mt({api:e,approval:t,onDecided:a}),k=s.kind==="automation"?s.preview?.automation??null:null,[g,w]=useState(k?.instructions??""),y=jt(s);return jsxs(Fragment,{children:[jsx(Ot,{approval:s,automationInstructions:k?g:void 0,chat:n,errorMessage:l,isPending:u,isStale:c,onAutomationInstructionsChange:k?w:void 0,onSkillFieldsChange:y.proposal?y.setFields:void 0,skillFields:y.fields??void 0}),u&&y.proposal&&y.fields?jsx("div",{className:"fk:mt-4",children:jsx(Lt,{decide:r,fields:y.fields,isDeciding:d,proposal:y.proposal})}):u&&k?jsx("div",{className:"fk:mt-4",children:jsx(_t,{decide:r,instructions:g,isDeciding:d,proposal:k})}):u?jsx("div",{className:"fk:mt-4",children:jsx($t,{allowRemember:!n&&s.kind==="plugin"&&!!s.automationId,askForRejectionReason:!n,decide:r,isDeciding:d,isRejectDialogOpen:f,isStale:c,rejectReason:p,setIsRejectDialogOpen:x,setRejectReason:v,variant:"inline"})}):null]})}function Rr({api:e,approval:t,onClose:n,onDecided:a}){let{approval:s,decide:r,errorMessage:l,isDeciding:d,isPending:u,isRejectDialogOpen:f,isStale:c,rejectReason:p,setIsRejectDialogOpen:x,setRejectReason:v}=Mt({api:e,approval:t,onDecided:a}),k=s.kind==="automation"?s.preview?.automation??null:null,[g,w]=useState(k?.instructions??""),y=jt(s);return jsx(la$1,{actions:u&&y.proposal&&y.fields?jsx(Lt,{decide:r,fields:y.fields,isDeciding:d,proposal:y.proposal}):u&&k?jsx(_t,{decide:r,instructions:g,isDeciding:d,proposal:k}):u?jsx($t,{allowRemember:s.kind==="plugin"&&!!s.automationId,askForRejectionReason:true,decide:r,isDeciding:d,isRejectDialogOpen:f,isStale:c,rejectReason:p,setIsRejectDialogOpen:x,setRejectReason:v,variant:"header"}):null,depth:0,isFocused:true,onClose:n,title:k?"Automation proposal":s.preview?.automationChange?"Automation change":y.proposal?y.proposal.before?"Skill change":"Skill proposal":"Mutation proposal",children:jsx(Ot,{approval:s,automationInstructions:k?g:void 0,chat:false,errorMessage:l,isPending:u,isStale:c,onAutomationInstructionsChange:k?w:void 0,onSkillFieldsChange:y.proposal?y.setFields:void 0,skillFields:y.fields??void 0})})}var ya="Approved by Flexkit Jev policy",ba="Approved by automation tool allow rule",xa=new Set(["data-create-sandbox","data-execute-graphql","data-export-records","data-load-skill","data-plan","data-plugin-call","data-read-chat","data-read-source","data-run-command","data-search-schema","data-update-memory","data-validate-graphql","data-web-search"]);function me(e){return xa.has(e)}function b(e){return e.data}function He(e){return !e.decidedBy&&!!(e.reason?.startsWith(ya)||e.reason?.startsWith(ba))}function j(e,t=72){let n=e.trim();if(n.length<=t)return n;let a=n.slice(0,t),s=a.lastIndexOf(" ");return `${(s>=Math.floor(t*.6)?a.slice(0,s):a).trimEnd()}\u2026`}function wa(e){return e.replace(/^#{1,6}\s+/,"").replace(/^(?:[-*+]|\d+[.)])\s+/,"").replace(/!?\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/(\*\*|__)(.*?)\1/g,"$2").replace(/(\*|_)(.*?)\1/g,"$2").replace(/`([^`]*)`/g,"$1").replace(/[*_`#>]/g,"").replace(/\s+/g," ").trim().replace(/[.:]+$/,"")}function Sa(e){let t=e.lastIndexOf(`
|
|
7
|
+
`),n=-1,a=/[.!?](?=\s)/g,s;for(;(s=a.exec(e))!==null;)n=s.index;let r=Math.max(t,n);return r<0?"":e.slice(0,r+1)}function Na(e,t){let a=(Sa(e)).split(/\r?\n/).map(u=>u.trim()).filter(Boolean),s=a[a.length-1];if(!s)return null;let l=/^\*\*(.+?)\*\*:?$/.exec(s)?.[1]??/^#{1,6}\s+(.+)$/.exec(s)?.[1]??/^(.+?[.!?])(?:\s|$)/.exec(s)?.[1]??s,d=wa(l);return !d||/^reasoning$/i.test(d)?null:j(d)}function Ut(e){return e.replace(/[_-]+/g," ").trim()}function Aa(e){if(e.type==="data-load-skill"){let t=b(e);return t.status!=="loading"?null:t.skillName?j(`Loading skill "${t.skillName}"`):"Loading skill"}if(e.type==="data-search-schema")return b(e).status==="loading"?"Searching schema":null;if(e.type==="data-validate-graphql")return b(e).status==="loading"?"Validating GraphQL query":null;if(e.type==="data-execute-graphql"){let t=b(e);return t.status!=="loading"?null:t.operationType==="mutation"?"Executing GraphQL mutation":"Executing GraphQL query"}if(e.type==="data-export-records"){let t=b(e);return t.status!=="loading"?null:t.rowCount>0?`Exporting records (${t.rowCount.toLocaleString("en-US")} so far)`:"Exporting records"}if(e.type==="data-update-memory")return b(e).status==="loading"?"Updating memory":null;if(e.type==="data-web-search"){let t=b(e);return t.status!=="loading"?null:t.query?j(`Searching the web for "${t.query}"`):"Searching the web"}if(e.type==="data-run-command"){let t=b(e);return ["executing","running","waiting"].includes(t.status)?j(`Running ${[t.command,...t.args].join(" ")}`):null}if(e.type==="data-create-sandbox")return b(e).status==="loading"?"Creating sandbox":null;if(e.type==="data-plugin-call"){let t=b(e);return t.status!=="loading"?null:j(`Calling ${t.pluginId}: ${Ut(t.tool)}`)}if(e.type==="data-subtask"){let t=b(e);return t.status==="running"?j(`Running subtask: ${t.title}`):null}if(e.type==="data-knowledge-search"){let t=b(e);return t.status!=="loading"?null:t.query?j(`Searching knowledge for "${t.query}"`):"Searching knowledge"}if(e.type==="data-chat-search"){let t=b(e);return t.status!=="loading"?null:t.query?j(`Searching past chats for "${t.query}"`):"Searching past chats"}if(e.type==="data-read-chat"){let t=b(e);return t.status!=="loading"?null:t.chatTitle?j(`Reading the chat "${t.chatTitle}"`):"Reading a past chat"}if(e.type==="data-read-source"){let t=b(e);return t.status!=="loading"?null:t.sourceTitle?j(`Reading "${t.sourceTitle}"`):"Reading a document"}return null}var Ca=new Set(["data-execute-graphql","data-read-chat","data-read-source","data-search-schema","data-validate-graphql"]);function Ie(e){if(!me(e.type)||e.type==="data-plan"||Ca.has(e.type))return null;let t=b(e);if(t.status!=="error")return null;if(t.error?.message)return t.error.message;switch(e.type){case "data-web-search":return "Failed to search the web";case "data-run-command":return `Command failed: ${String(t.command??"")}`.trim();case "data-create-sandbox":return "Failed to create sandbox";case "data-load-skill":return "Failed to load skill";case "data-update-memory":return "Failed to update memory";case "data-plugin-call":return `Plugin call failed: ${String(t.pluginId??"")}: ${Ut(String(t.tool??""))}`;default:return "The tool call failed"}}function Ee(e){if(e.type==="step-start"||e.type==="reasoning")return true;if(me(e.type))return Ie(e)===null;if(e.type==="data-knowledge-search"||e.type==="data-chat-search")return b(e).status==="loading";if(e.type==="data-mutation-approval"){let t=b(e);return He(t)&&t.status!=="error"}return false}function pe(e){if(!e)return null;for(let t=e.parts.length-1;t>=0;t--){let n=e.parts[t];if(n?.type!=="data-plan")continue;let a=b(n),s=a.steps.findIndex(r=>r.status==="in_progress");return s<0?null:j(`Step ${(s+1).toString()} of ${a.steps.length.toString()}: ${a.steps[s].step}`)}return null}function Pa(e){if(!e)return null;for(let t=e.parts.length-1;t>=0;t--){let n=e.parts[t];if(!(!n||n.type==="step-start"))return n.type==="reasoning"?n.state==="streaming"?Na(n.text)??pe(e):pe(e):n.type==="data-mutation-approval"?b(n).status==="pending"?"Awaiting approval":pe(e):n.type==="data-user-question"?b(n).status==="pending"?"Waiting for your answer":pe(e):n.type==="text"?null:Aa(n)??pe(e)}return null}function Ke(e){return e?e.parts.some(t=>t.type!=="data-mutation-approval"?false:b(t).status==="pending"):false}function Ye(e,t={}){let n=false,a=[];for(let s of e.parts){if(s.type!=="data-mutation-approval"){a.push(s);continue}let r=b(s);if(r.status!=="pending"){a.push(s);continue}n=true;let l=t[r.approvalId];l&&l!=="pending"&&a.push({...s,data:{...r,status:l}});}return n?{...e,parts:a}:e}function qt(e,t){if(!e)return [];let n=[],a=t?.pendingOnly??false;for(let s of e.parts){if(s.type!=="data-mutation-approval")continue;let r=b(s);a&&r.status!=="pending"||n.push(r.approvalId);}return n}function Ra(e){return qt(e,{pendingOnly:true})}function Ve(e){return !!e?.parts.some(t=>t.type==="data-user-question"&&b(t).status==="pending")}function Bt(e){return e.map(()=>({other:"",selected:[]}))}function Xt(e,t,n){return e.multiSelect?{...t,selected:t.selected.includes(n)?t.selected.filter(a=>a!==n):[...t.selected,n]}:{other:"",selected:[n]}}function Jt(e,t,n){return e.multiSelect?{...t,other:n}:{other:n,selected:n.trim()?[]:t.selected}}function Qt(e){let t=[];for(let n of e){let a=n.other.trim();if(n.selected.length===0&&!a)return null;t.push(a?{other:a,selected:n.selected}:{selected:n.selected});}return t}function Ht(e){return e&&[...e.selected,...e.other?[`\u201C${e.other}\u201D`]:[]].join(", ")||"\u2014"}function Ta(e){return Array.isArray(e)?e.filter(t=>t.type==="file"&&typeof t.url=="string").map(t=>({filename:t.filename??"file",mediaType:t.mediaType??"application/octet-stream",sizeBytes:t.sizeBytes??0,url:t.url??"",...t.sha256?{sha256:t.sha256}:{},...t.knowledgeSourceId!==void 0?{knowledgeSourceId:t.knowledgeSourceId}:{}})):[]}function Kt(e,t){return e.kind!=="idle"?e:t.knowledgeSourceId?{kind:"added",sourceId:t.knowledgeSourceId}:e}function La(e){return typeof e=="string"&&e.includes("/agent/chats/")}function Yt({attachment:e$2}){let{currentProjectId:t}=f(),n=b$4(),a=useNavigate(),{mutate:s}=useSWRConfig(),r=useMemo(()=>t?d$2(t):null,[t]),[l,d]=useState({kind:"idle"}),u=Kt(l,e$2),f$1=e$1({name:e$2.filename,size:e$2.sizeBytes})===null;if(!r||!t||!n||!f$1)return null;let c$1=r,p=t;async function x(){d({kind:"adding"});try{let g=await c$1.addChatAttachment({filename:e$2.filename,url:e$2.url});i(g,e$2.filename),d({kind:"added",sourceId:g.source.id}),f$2(),s(La);}catch(g){ma$1.error(h(g,`${e$2.filename} could not be added to Knowledge.`)),d({kind:"idle"});}}let v="Add to Knowledge",k=jsx(BookOpenTextIcon,{className:"fk:size-3"});return u.kind==="adding"?k=jsx(LoaderCircle,{className:"fk:size-3 fk:animate-spin"}):u.kind==="added"&&(v="Open in Knowledge",k=jsx(CheckIcon,{className:"fk:size-3"})),jsxs(b$2,{children:[jsx(c,{asChild:true,children:jsx("button",{"aria-disabled":u.kind==="adding","aria-label":`${v}: ${e$2.filename}`,className:"fk:absolute fk:top-1 fk:right-1 fk:z-10 fk:flex fk:size-5 fk:items-center fk:justify-center fk:rounded-full fk:border fk:border-border fk:bg-background fk:text-foreground fk:shadow-sm fk:transition-colors fk:hover:bg-accent fk:focus-visible:outline-none fk:focus-visible:ring-2 fk:focus-visible:ring-ring fk:aria-disabled:cursor-default fk:aria-disabled:hover:bg-background fk:corner-squircle","data-knowledge-state":u.kind,type:"button",onClick:g=>{g.stopPropagation(),g.preventDefault(),u.kind==="idle"?x():u.kind==="added"&&a(o(p,u.sourceId));},children:k})}),jsx(e,{children:v})]})}var Vt=20*1024*1024,eo=10,Gt=new Set(["css","csv","gif","gql","graphql","htm","html","jpeg","jpg","js","json","jsx","log","markdown","md","mjs","ndjson","pdf","png","py","sql","ts","tsv","tsx","txt","webp","xml","yaml","yml"]),Zt=new Set(["application/pdf","image/gif","image/jpeg","image/png","image/webp"]),to=[...[...Gt].map(e=>`.${e}`),...Zt].join(",");function en(e){let t=e.lastIndexOf(".");return t<=0?"":e.slice(t+1).toLowerCase()}function qa(e){let t=en(e.name);return (t?Gt.has(t):Zt.has(e.type))?e.size===0?`"${e.name}" is empty.`:e.size>Vt?`"${e.name}" exceeds the ${String(Math.round(Vt/(1024*1024)))} MB limit.`:null:`"${e.name}" is not supported. Attach images, PDFs, or text files.`}async function Ba(e){let n=await(await fetch(e.url)).blob();return new File([n],e.filename??"file",{type:e.mediaType||n.type})}function no(e,t){let{attachments:n}=Lb(),a=useRef({}),[,s]=useState(0),r=useCallback(()=>s(f=>f+1),[]),l=useRef(n.remove);l.current=n.remove;let d=useRef(t);d.current=t,useEffect(()=>{let f=new Set(n.files.map(c=>c.id));for(let[c,p]of Object.entries(a.current))f.has(c)||(p.controller.abort(),delete a.current[c]);for(let c of n.files){if(a.current[c.id])continue;let p=new AbortController,x={controller:p,status:"uploading"};a.current[c.id]=x,(async()=>{try{let v=await Ba(c),k=qa(v);if(k)throw new Error(k);let g=await e.uploadAgentChatAttachment(v,p.signal);if(p.signal.aborted)return;x.attachment=g,x.status="done";}catch(v){if(p.signal.aborted)return;x.status="error",delete a.current[c.id],l.current(c.id),d.current(v instanceof Error?v.message:"The file could not be uploaded.");}finally{r();}})();}r();},[e,n.files,r]);let u=Object.values(a.current).some(f=>f.status==="uploading");return {getUploaded:f=>f.map(c=>a.current[c]?.attachment).filter(c=>!!c),isUploading:u,isUploadingFile:f=>a.current[f]?.status==="uploading"}}function Ge(e){return !!e?.startsWith("image/")}function tn({image:e,onClose:t}){return jsx(k,{onOpenChange:n=>n?void 0:t(),open:e!==null,children:jsxs(p,{className:"fk:h-dvh fk:w-dvw fk:max-w-none fk:sm:max-w-none fk:rounded-none fk:border-0 fk:bg-black/90 fk:p-4 fk:shadow-none fk:flex fk:items-center fk:justify-center fk:corner-squircle",showCloseButton:false,children:[jsx(s,{className:"fk:sr-only",children:e?.filename??"Image preview"}),e?jsx("img",{alt:e.filename,className:"fk:block fk:h-auto fk:w-auto fk:max-h-full fk:max-w-full fk:object-contain",src:e.url}):null,jsx(n$1,{"aria-label":"Close preview",className:"fk:absolute fk:top-4 fk:right-4 fk:flex fk:size-9 fk:items-center fk:justify-center fk:rounded-full fk:bg-white/10 fk:text-white fk:transition-colors fk:hover:bg-white/20 fk:focus-visible:outline-none fk:focus-visible:ring-2 fk:focus-visible:ring-white/60 fk:corner-squircle",children:jsx(XIcon,{className:"fk:size-5"})})]})})}function nn({label:e,onRemove:t}){return jsx("button",{"aria-label":e,className:"fk:absolute fk:top-1 fk:right-1 fk:z-10 fk:flex fk:size-5 fk:items-center fk:justify-center fk:rounded-full fk:border fk:border-border fk:bg-background fk:text-foreground fk:shadow-sm fk:transition-colors fk:hover:bg-accent fk:focus-visible:outline-none fk:focus-visible:ring-2 fk:focus-visible:ring-ring fk:corner-squircle",onClick:n=>{n.stopPropagation(),t();},type:"button",children:jsx(XIcon,{className:"fk:size-3"})})}function an({image:e,isUploading:t=false,onOpen:n,onRemove:a,sizeClassName:s}){return jsxs("div",{className:`fk:relative fk:shrink-0 fk:overflow-hidden fk:rounded-xl fk:bg-muted ${s} fk:corner-squircle`,children:[jsx("button",{"aria-label":`Preview ${e.filename}`,className:"fk:block fk:size-full fk:cursor-zoom-in fk:focus-visible:outline-none fk:focus-visible:ring-2 fk:focus-visible:ring-ring",onClick:n,type:"button",children:jsx("img",{alt:e.filename,className:"fk:size-full fk:object-cover",src:e.url})}),t?jsx("div",{className:"fk:pointer-events-none fk:absolute fk:inset-0 fk:flex fk:items-center fk:justify-center fk:bg-background/60",children:jsx(ra$1,{className:"fk:size-4"})}):null,a?jsx(nn,{label:`Remove ${e.filename}`,onRemove:a}):null]})}function Xa(e,t){let n=en(e);if(n)return n.toUpperCase();let a=t?.split("/")[1]?.split("+")[0];return a?a.toUpperCase():"FILE"}function sn({action:e,file:t,href:n,isUploading:a=false,onRemove:s}){let r=jsxs(Fragment,{children:[jsx("div",{className:"fk:flex fk:size-10 fk:shrink-0 fk:items-center fk:justify-center fk:rounded-lg fk:bg-muted fk:text-muted-foreground fk:corner-squircle",children:a?jsx(ra$1,{className:"fk:size-4"}):jsx(FileIcon,{className:"fk:size-5"})}),jsxs("div",{className:"fk:min-w-0 fk:pr-4 fk:text-left",children:[jsx("div",{className:"fk:truncate fk:text-sm fk:font-medium fk:text-foreground",children:t.filename}),jsx("div",{className:"fk:truncate fk:text-xs fk:text-muted-foreground",children:Xa(t.filename,t.mediaType)})]})]}),l="fk:flex fk:h-14 fk:max-w-64 fk:items-center fk:gap-2.5 fk:rounded-xl fk:border fk:border-border fk:bg-background fk:px-2 fk:corner-squircle";return jsxs("div",{className:"fk:relative fk:shrink-0",children:[n?jsx("a",{className:`${l} fk:transition-colors fk:hover:bg-accent/50 fk:focus-visible:outline-none fk:focus-visible:ring-2 fk:focus-visible:ring-ring`,href:n,rel:"noreferrer",target:"_blank",children:r}):jsx("div",{className:l,children:r}),s?jsx(nn,{label:`Remove ${t.filename}`,onRemove:s}):null,e]})}function ao({uploads:e}){let t=Ob(),[n,a]=useState(null);return t.files.length===0?null:jsxs(Fragment,{children:[jsx("div",{className:"fk:flex fk:flex-wrap fk:items-center fk:gap-2",children:t.files.map(s=>{if(Ge(s.mediaType)&&s.url){let r={filename:s.filename??"Image",url:s.url};return jsx(an,{image:r,isUploading:e.isUploadingFile(s.id),onOpen:()=>a(r),onRemove:()=>t.remove(s.id),sizeClassName:"fk:size-14"},s.id)}return jsx(sn,{file:{filename:s.filename??"file",mediaType:s.mediaType},isUploading:e.isUploadingFile(s.id),onRemove:()=>t.remove(s.id)},s.id)})}),jsx(tn,{image:n,onClose:()=>a(null)})]})}function rn({attachments:e}){let[t,n]=useState(null);if(e.length===0)return null;let a=e.filter(r=>Ge(r.mediaType)),s=e.filter(r=>!Ge(r.mediaType));return jsxs("div",{className:"fk:flex fk:flex-col fk:items-end fk:gap-2",children:[a.length>0?jsx("div",{className:"fk:flex fk:flex-wrap fk:justify-end fk:gap-2",children:a.map(r=>jsx(an,{image:r,onOpen:()=>n(r),sizeClassName:"fk:size-24"},r.url))}):null,jsx(tn,{image:t,onClose:()=>n(null)}),s.length>0?jsx("div",{className:"fk:flex fk:flex-wrap fk:justify-end fk:gap-2",children:s.map(r=>jsx(sn,{action:jsx(Yt,{attachment:r}),file:r,href:r.url},r.url))}):null]})}function mo(e){let t=(Array.isArray(e.parts)?e.parts:[]).find(n=>n.type==="data-monitor-event");return t&&typeof t.data=="object"&&t.data!==null?t.data:null}function un({data:e,error:t}){let n=e.total-e.events.length;return jsxs("div",{className:"fk:mr-auto fk:w-full fk:max-w-[85%] fk:space-y-1.5 fk:rounded-lg fk:border fk:border-border fk:bg-muted/40 fk:px-3.5 fk:py-2.5 fk:text-sm fk:corner-squircle",children:[jsxs("div",{className:"fk:flex fk:items-center fk:gap-2 fk:text-xs fk:text-muted-foreground",children:[jsx(RadarIcon,{className:"fk:size-3.5 fk:shrink-0"}),jsxs("span",{className:"fk:truncate",children:["Monitor \xB7 ",e.description]})]}),jsxs("ul",{className:"fk:space-y-0.5",children:[e.events.map(a=>jsx("li",{children:a.summary},a.id)),n>0?jsxs("li",{className:"fk:text-muted-foreground",children:["\u2026and ",n.toString()," more"]}):null]}),t?jsx("p",{className:"fk:text-xs fk:text-destructive",children:t}):null]})}function ko({api:e$1,chatId:t,onTurnIntoAutomation:n,projectId:a,sending:s=false}){let{data:r,mutate:l}=Ya(g(a).agentChat(t),f$1,{revalidateOnMount:false}),[d,u]=useState(null),f=r?.monitors??[];if(f.length===0)return null;async function c$2(p){u(p.id);try{await e$1.stopAgentChatMonitor(t,p.id),await l();}catch{ma$1.error("Unable to stop the monitor.");}finally{u(null);}}return jsx("div",{className:"fk:mx-auto fk:mb-2 fk:flex fk:max-w-4xl fk:flex-wrap fk:gap-2",children:f.map(p=>jsxs("div",{className:"fk:flex fk:max-w-full fk:items-center fk:gap-2 fk:rounded-full fk:border fk:border-border fk:py-1 fk:pl-3 fk:pr-1 fk:text-xs fk:text-muted-foreground",children:[jsx(RadarIcon,{className:"fk:size-3.5 fk:shrink-0 fk:animate-pulse"}),jsxs("span",{className:"fk:truncate",children:["Watching: ",p.description," \xB7 expires ",formatDistance(new Date(p.expiresAt),new Date,{addSuffix:true})]}),n&&p.sourceType&&p.sourceType!=="job"?jsxs(b$2,{children:[jsx(c,{asChild:true,children:jsx(c$1,{"aria-label":`Turn ${p.description} into an automation`,className:"fk:size-6 fk:rounded-full",disabled:s,size:"icon",variant:"ghost",onClick:()=>n(p),children:jsx(BotIcon,{className:"fk:size-3.5"})})}),jsx(e,{children:"Turn into automation"})]}):null,jsxs(b$2,{children:[jsx(c,{asChild:true,children:jsx(c$1,{"aria-label":`Stop watching ${p.description}`,className:"fk:size-6 fk:rounded-full",disabled:d===p.id,size:"icon",variant:"ghost",onClick:()=>{c$2(p);},children:jsx(XIcon,{className:"fk:size-3.5"})})}),jsx(e,{children:"Stop watching"})]})]},p.id))})}function cn(e,t){let n=t.trim();return !n||/window was closed|not completed/i.test(n)?`${e} authorization didn't finish`:/popups|different account/i.test(n)?n:`${e} authorization didn't finish: ${n.replace(/\.$/,"")}`}function Va(e){let t=e.connections.filter(n=>n.isPrimary&&n.status==="connected");return t.find(n=>n.scope==="personal")??t.find(n=>n.scope==="project")??null}function dn(e,t,n){return n==="personal"?e.allowPersonal:t}function fn(e,t,n){if(!e.enabled)return {kind:"disabled"};let a=n?e.connections.find(l=>l.id===n&&l.status==="needs_auth"):void 0;if(a)return dn(e,t,a.scope)?{kind:"reconnect",connection:a}:{kind:"not_permitted"};let s=Va(e);if(s)return {kind:"connected",connection:s};let r=e.scopes.filter(l=>dn(e,t,l));return r.length>0?{kind:"connect",scopes:r}:{kind:"not_permitted"}}var ss=createContext(null),Me=new Map,tt=new Set;function et(e,t){t?Me.set(e,t):Me.delete(e),tt.forEach(n=>n());}function rs(e){return tt.add(e),()=>tt.delete(e)}function os(e){return useSyncExternalStore(rs,()=>Me.get(e)??null,()=>null)}var kn={personal:{description:"Only you can use this connection in this project.",title:"Personal"},project:{description:"Shared with project members who can use this plugin.",title:"Project"}};function is({busy:e,logoUrl:t$1,name:n,onContinue:a$1,onOpenChange:s$1,open:r,scopes:l,connect:d}){let[u,f]=useState(l.length===1?l[0]??null:null),c=[...ls(n,d),{description:`Remove the connection to ${n} at any time.`,title:"You stay in control"}];return jsx(k,{onOpenChange:s$1,open:r,children:jsxs(p,{className:"fk:sm:max-w-md",children:[jsxs("div",{className:"fk:flex fk:flex-col fk:items-center fk:gap-3 fk:pt-2 fk:text-center",children:[jsx(a,{className:"fk:size-16 fk:rounded-xl",src:t$1}),jsxs(s,{className:"fk:text-xl",children:["Connect to ",n]}),jsxs(t,{children:["Let the Flexkit agent access and use ",n," on your behalf."]})]}),jsx("ul",{className:"fk:space-y-3 fk:rounded-xl fk:bg-muted/60 fk:p-4 fk:corner-squircle",children:c.map(p=>jsxs("li",{className:"fk:flex fk:gap-3",children:[jsx(CheckIcon,{className:"fk:mt-0.5 fk:size-4 fk:shrink-0"}),jsxs("span",{children:[jsx("span",{className:"fk:block fk:text-sm fk:font-medium",children:p.title}),jsx("span",{className:"fk:block fk:text-sm fk:text-muted-foreground",children:p.description})]})]},p.title))}),l.length>1?jsx("div",{className:"fk:space-y-1.5",role:"radiogroup","aria-label":"Connection",children:l.map(p=>jsxs("button",{"aria-checked":u===p,className:`fk:flex fk:w-full fk:flex-col fk:rounded-lg fk:border fk:px-3 fk:py-2 fk:text-left fk:corner-squircle ${u===p?"fk:border-primary fk:bg-primary/5":"fk:border-border fk:hover:bg-muted/60"}`,onClick:()=>f(p),role:"radio",type:"button",children:[jsx("span",{className:"fk:text-sm fk:font-medium",children:kn[p].title}),jsx("span",{className:"fk:text-xs fk:text-muted-foreground",children:kn[p].description})]},p))}):null,jsx("p",{className:"fk:text-center fk:text-xs fk:text-muted-foreground",children:"You can manage connections anytime in AI \u2192 Plugins."}),jsx(c$1,{className:"fk:w-full",disabled:e||!u,onClick:()=>u&&a$1(u),type:"button",children:"Continue"})]})})}function ls(e,t){switch(t?.type){case "api-token":return [{title:`Paste a ${t.tokenLabel}`,description:`Flexkit stores it encrypted and sends it only to ${e}. The agent never sees it.`},{title:"You decide what the agent can do",description:"The agent only gets the access the token has."}];case "credentials":return [{title:`Enter the credentials of your ${e} app`,description:`Flexkit checks them with ${e}, stores them encrypted and never shows them to the agent.`},{title:"You decide what the agent can do",description:`The agent only gets the access scopes you give the app in ${e}.`}];default:return [{title:`Sign in securely to your ${e} account`,description:"Flexkit never sees your password."},{title:"You decide what the agent can do",description:`The agent only gets the access you approve on ${e}'s sign-in page.`}]}}function us(e,t,n){if(!n)return `Let the Flexkit agent use ${e}`;switch(t?.type){case "api-token":return `Add a new ${t.tokenLabel} so the agent can keep using ${e}`;case "credentials":return `Enter the credentials again so the agent can keep using ${e}`;default:return `Sign in again so the agent can keep using ${e}`}}function vn({connectionId:e,pluginId:t}){let{currentProjectId:n}=f(),a$1=useMemo(()=>n?d(n):null,[n]),s=n?`/api/flexkit/${n}`:null,r=s?`${s}/plugins/${encodeURIComponent(t)}`:null,{data:l,error:d$1,mutate:u}=Ya(r,f$1),{mutate:f$2}=useSWRConfig(),c=useContext(ss),[p,x]=useState(false),v=`${n??""}:${t}:${e??""}`,k=os(v),g=k?.status==="connecting",w=k?.status==="failed"?k:null;if(!l)return jsxs("div",{className:"fk:flex fk:items-center fk:gap-2 fk:rounded-2xl fk:border fk:border-border fk:p-4 fk:text-sm fk:text-muted-foreground fk:corner-squircle",children:[d$1?jsx(CircleAlertIcon,{className:"fk:size-4"}):jsx(LoaderCircle,{className:"fk:size-4 fk:animate-spin"}),d$1?`${t} could not be loaded.`:`Loading ${t}\u2026`]});let{plugin:y}=l,C=fn(y,l.canManage,e),_=C.kind==="reconnect"?C.connection:null;function S(E){!a$1||Me.get(v)?.status==="connecting"||(x(false),et(v,{status:"connecting"}),d$4(a$1,y,E,_?{connectionId:_.id}:void 0).then(Y=>{et(v,null),Y&&(u().catch(()=>{}),s&&f$2(`${s}/plugins`).catch(()=>{}),c?.onConnected(t));},Y=>{let L=Y instanceof Error?Y.message:"";et(v,{message:cn(y.name,L),scope:E,status:"failed"});}));}let R=null,$=null;return C.kind==="connected"?R=jsxs("span",{className:"fk:flex fk:items-center fk:gap-1.5 fk:text-sm fk:text-muted-foreground",children:[jsx(CheckIcon,{className:"fk:size-4 fk:text-green-700"}),"Connected \xB7 ",C.connection.displayName]}):C.kind==="disabled"?R=jsxs("span",{className:"fk:text-sm fk:text-muted-foreground",children:["An owner turned ",y.name," off for this project."]}):C.kind==="not_permitted"?R=jsxs("span",{className:"fk:text-sm fk:text-muted-foreground",children:["Ask a project owner or developer to connect ",y.name,"."]}):w?(R=jsxs("span",{className:"fk:flex fk:items-center fk:gap-1.5 fk:text-sm fk:text-muted-foreground",children:[jsx(CircleAlertIcon,{className:"fk:size-4 fk:shrink-0 fk:text-amber-600"}),w.message]}),$=jsx(c$1,{disabled:g,onClick:()=>S(w.scope),size:"sm",type:"button",variant:"secondary",children:"Retry"})):$=jsxs(c$1,{disabled:g,onClick:()=>_?S(_.scope):x(true),size:"sm",type:"button",children:[g?jsx(LoaderCircle,{className:"fk:size-3.5 fk:animate-spin"}):null,_?"Reconnect":"Authorize"]}),jsxs("div",{className:"fk:space-y-2",children:[jsxs("div",{className:"fk:space-y-3 fk:rounded-2xl fk:border fk:border-border fk:bg-background fk:p-4 fk:corner-squircle",children:[jsxs("div",{className:"fk:flex fk:items-center fk:gap-3",children:[jsx(a,{className:"fk:size-11 fk:rounded-lg",src:y.logoUrl}),jsxs("div",{className:"fk:min-w-0 fk:flex-1",children:[jsx("div",{className:"fk:truncate fk:font-medium",children:y.name}),jsx("div",{className:"fk:truncate fk:text-sm fk:text-muted-foreground",children:us(y.name,y.connect,!!_)})]}),$&&!w?$:null]}),R?jsxs("div",{className:"fk:flex fk:items-center fk:justify-between fk:gap-3",children:[R,w?$:null]}):null]}),C.kind==="connect"||C.kind==="reconnect"?jsx("p",{className:"fk:px-1 fk:text-xs fk:text-muted-foreground",children:"Plugin actions follow your project's approval rules. Disconnect any time in AI \u2192 Plugins."}):null,C.kind==="connect"?jsx(is,{busy:g,logoUrl:y.logoUrl,name:y.name,onContinue:S,onOpenChange:x,open:p,scopes:C.scopes,connect:y.connect}):null]})}function Ro({data:e,error:t,label:n}){return jsxs("div",{className:"fk:mr-auto fk:flex fk:max-w-[85%] fk:flex-wrap fk:items-center fk:gap-x-2 fk:gap-y-1 fk:text-sm fk:text-muted-foreground",children:[jsx(PlugIcon,{className:"fk:size-3.5 fk:shrink-0"}),jsxs("span",{children:["Connected ",jsx("span",{className:"fk:font-medium fk:text-foreground",children:e.pluginName}),e.accountName?` \xB7 ${e.accountName}`:""]}),n?jsxs("span",{className:"fk:text-xs",children:["\xB7 ",n]}):null,t?jsx("span",{className:"fk:text-xs fk:text-destructive",children:t}):null]})}function To(e){let t=(Array.isArray(e)?e:[]).find(n=>n.type==="data-plugin-connected");return t&&typeof t.data=="object"&&t.data!==null?t.data:null}var ie=class extends Error{},$e=class extends Error{};function yn({url:e,signal:t,state:n,onState:a,wake:s,fetchStream:r=fetch,retryMs:l=2e3}){let d=0,u=0,f=new TransformStream,c=f.writable.getWriter(),p=new AbortController;c.closed.catch(g=>p.abort(g));let x=()=>{p.abort(t.reason),c.abort(t.reason).catch(()=>{});};t.addEventListener("abort",x,{once:true}),t.aborted&&x();let v=()=>new Promise(g=>{let w=()=>{clearTimeout(y),p.signal.removeEventListener("abort",w),s?.removeEventListener("wake",w),g();},y=setTimeout(w,l);p.signal.addEventListener("abort",w,{once:true}),s?.addEventListener("wake",w,{once:true}),p.signal.aborted&&w();});async function k(){try{for(await c.write({type:"start"});!p.signal.aborted;){try{let g=await r(`${e}${e.includes("?")?"&":"?"}wire=2&startIndex=${d}`,{credentials:"include",signal:p.signal});if(g.status===404){a("unavailable"),await c.close();return}if(g.status===401||g.status===403)throw new $e("Stream access denied");if(!g.ok||!g.body)throw new Error(`Stream request failed: ${g.status}`);if(g.headers.get("x-flexkit-stream-version")!=="2")throw await g.body.cancel(),new ie("Backend uses legacy replay");a("streaming");let w=g.body.pipeThrough(new TextDecoderStream).getReader(),y="",C=!1;try{for(;!p.signal.aborted;){let{value:_,done:S}=await w.read();if(S)break;y+=_;let R;for(;(R=y.indexOf(`
|
|
8
|
+
`))>=0;){let $=y.slice(0,R);if(y=y.slice(R+1),!$)continue;let E=JSON.parse($);if(!Number.isSafeInteger(E.index)||E.index<0)throw new Error("Invalid replay cursor");if(!(E.index<d)){if(E.index!==d)throw new Error("Replay cursor gap");E.chunk&&await c.write(E.chunk),d=E.index+1,u=0,E.chunk?.type==="finish"&&E.chunk.messageMetadata?.flexkitTerminal&&(C=!0);}}if(y.length>2e6)throw new Error("Oversized replay frame");if(C)break}}finally{await w.cancel().catch(()=>{}),w.releaseLock();}if(C||n().terminal&&!y){await c.write({type:"finish"}),await c.close(),a("finished");return}}catch(g){if(p.signal.aborted||g instanceof ie||g instanceof $e||++u>=5)throw g}do a(n().paused?"paused":"streaming"),await v();while(!p.signal.aborted&&n().paused&&!n().terminal)}}catch(g){await c.abort(g).catch(()=>{});}finally{t.removeEventListener("abort",x),c.releaseLock();}}return k(),pipeJsonRender(f.readable)}var fs={pending:"Waiting for an answer.",cancelled:"The turn was stopped before you answered.",dismissed:"You skipped these questions.",expired:"Nobody answered in time."};function ps({description:e,label:t,multiSelect:n,onClick:a,selected:s}){return jsxs("button",{"aria-checked":s,className:`fk:flex fk:w-full fk:items-start fk:gap-2.5 fk:rounded-lg fk:border fk:px-3 fk:py-2 fk:text-left fk:transition-colors fk:corner-squircle ${s?"fk:border-primary fk:bg-primary/5":"fk:border-border fk:hover:bg-muted/60"}`,onClick:a,role:n?"checkbox":"radio",type:"button",children:[jsx("span",{className:`fk:mt-0.5 fk:flex fk:size-4 fk:shrink-0 fk:items-center fk:justify-center fk:border ${n?"fk:rounded-sm":"fk:rounded-full"} ${s?"fk:border-primary fk:bg-primary fk:text-primary-foreground":"fk:border-muted-foreground/50"}`,children:s?jsx(CheckIcon,{className:"fk:size-3"}):null}),jsxs("span",{className:"fk:min-w-0",children:[jsx("span",{className:"fk:block fk:text-sm fk:font-medium",children:t}),e?jsx("span",{className:"fk:block fk:text-xs fk:text-muted-foreground",children:e}):null]})]})}function ms({disabled:e,draft:t,onChange:n,question:a}){return jsxs("fieldset",{className:"fk:space-y-2",disabled:e,children:[jsxs("legend",{className:"fk:mb-2 fk:flex fk:flex-wrap fk:items-center fk:gap-2",children:[jsx(b$1,{variant:"outline",children:a.header}),jsx("span",{className:"fk:text-sm fk:font-medium",children:a.question}),a.multiSelect?jsx("span",{className:"fk:text-xs fk:text-muted-foreground",children:"Pick any"}):null]}),jsxs("div",{className:"fk:space-y-1.5",role:a.multiSelect?"group":"radiogroup",children:[a.options.map(s=>jsx(ps,{description:s.description,label:s.label,multiSelect:a.multiSelect,onClick:()=>n(Xt(a,t,s.label)),selected:t.selected.includes(s.label)},s.label)),jsx(b$5,{"aria-label":`Your own answer to: ${a.question}`,className:"fk:h-9",maxLength:4e3,onChange:s=>n(Jt(a,t,s.target.value)),placeholder:"Other \u2014 type your own answer",value:t.other})]})]})}function ks({data:e}){return e.status==="answered"&&e.message!==void 0?jsxs("div",{className:"fk:space-y-1",children:[jsx("p",{className:"fk:text-xs fk:text-muted-foreground",children:e.questions.map(t=>t.question).join(" \xB7 ")}),jsxs("p",{className:"fk:text-sm",children:["You replied: ",jsxs("span",{className:"fk:whitespace-pre-wrap",children:["\u201C",e.message,"\u201D"]})]})]}):e.status!=="answered"?jsxs("div",{className:"fk:space-y-1",children:[jsx("p",{className:"fk:text-xs fk:text-muted-foreground",children:e.questions.map(t=>t.question).join(" \xB7 ")}),jsx("p",{className:"fk:text-sm fk:text-muted-foreground",children:fs[e.status]})]}):jsx("dl",{className:"fk:space-y-1.5",children:e.questions.map((t,n)=>jsxs("div",{className:"fk:flex fk:flex-wrap fk:items-baseline fk:gap-x-2",children:[jsx("dt",{className:"fk:text-xs fk:text-muted-foreground",children:t.question}),jsx("dd",{className:"fk:text-sm fk:font-medium",children:Ht(e.answers?.[n])})]},n))})}function xn({answer:e,data:t}){let[n,a]=useState(()=>Bt(t.questions)),[s,r]=useState(null),[l,d]=useState(null),[u,f]=useState(""),c=t.status==="pending"&&s?s:t;if(c.status!=="pending"||!e)return jsx(ks,{data:c});let p=Qt(n);async function x(v){if(e){d(v.action),f("");try{let k=await e(t.questionId,v);k&&r({...k.answers?{answers:k.answers}:{},...k.message!==null?{message:k.message}:{},questionId:k.id,questions:k.questions,status:k.status});}catch(k){f(k instanceof Error?k.message:"Could not send the answer.");}finally{d(null);}}}return jsxs("form",{className:"fk:space-y-5",onSubmit:v=>{v.preventDefault(),p&&x({action:"answer",answers:p});},children:[t.questions.map((v,k)=>jsx(ms,{disabled:l!==null,draft:n[k]??{other:"",selected:[]},onChange:g=>a(w=>w.map((y,C)=>C===k?g:y)),question:v},k)),u?jsx("p",{className:"fk:text-xs fk:text-destructive",children:u}):null,jsxs("div",{className:"fk:flex fk:flex-wrap fk:items-center fk:gap-2",children:[jsxs(c$1,{disabled:!p||l!==null,size:"sm",type:"submit",children:[l==="answer"?jsx(LoaderCircle,{className:"fk:size-3.5 fk:animate-spin"}):null,"Submit"]}),jsxs(c$1,{disabled:l!==null,onClick:()=>{x({action:"dismiss"});},size:"sm",type:"button",variant:"ghost",children:[l==="dismiss"?jsx(LoaderCircle,{className:"fk:size-3.5 fk:animate-spin"}):null,"Skip"]}),jsx("span",{className:"fk:text-xs fk:text-muted-foreground",children:"or reply in the chat"})]})]})}function gs(e){let t=[];return e.page!==void 0&&t.push(`p. ${String(e.page)}`),e.slide!==void 0&&t.push(`slide ${String(e.slide)}`),e.headingPath&&e.headingPath.length>0&&t.push(e.headingPath.join(" \u203A ")),t.join(" \xB7 ")}function wn(e){let t=new Map;for(let n of e??[]){let a=t.get(n.sourceId);a||(a={passages:[],sourceId:n.sourceId,sourceTitle:n.sourceTitle},t.set(n.sourceId,a)),!a.passages.some(s=>s.passageId===n.passageId)&&a.passages.push({excerpt:n.excerpt,locator:gs(n.locator),passageId:n.passageId});}return [...t.values()]}function Sn(e,t){let n=t.reduce((a,s)=>a+s.passages.length,0);return n===0?`No passages matched "${e}"`:`${String(n)} ${n===1?"passage":"passages"} from ${String(t.length)} ${t.length===1?"document":"documents"} for "${e}"`}function Nn(e,t){return `/${encodeURIComponent(e)}/ai/agent/chats/${encodeURIComponent(t)}`}function An(e){let t=new Set;return (e??[]).filter(n=>t.has(n.chatId)?false:(t.add(n.chatId),true))}function Cn(e,t){return t.length===0?`No past chats matched "${e}"`:`${String(t.length)} past ${t.length===1?"chat":"chats"} for "${e}"`}var $s=lazy(()=>import('./spec-renderer-Z6GVHLFU.js').then(e=>({default:e.RunSpecPart})));function zs(e){return jsx(Suspense,{fallback:null,children:jsx($s,{...e})})}function _s(){let{currentProjectId:e}=f();return {api:useMemo(()=>e?d(e):null,[e]),projectId:e}}var Dn=5,jn=2e3,On=120,nt="data-spec",Fn=createContext(null),Ls=createContext(false);function js(e){return new Promise(t=>window.setTimeout(t,e))}function Os(e){return e instanceof Error?e.name==="AbortError"||e.message.toLowerCase().includes("aborted"):false}function Fs(e){return e.some(t=>!Ee(t))}function Us(e){let t=new Set;for(let n of e)for(let a of n.parts)a.type==="data-user-message"&&a.id&&t.add(a.id);return t}function qs(e){let t=Us(e),n=[];for(let a of e){if(a.role==="user"){t.has(a.id)||n.push(a);continue}if(a.role!=="assistant"){n.push(a);continue}let s=[],r=0,l=()=>{Fs(s)&&n.push({...a,id:`${a.id}-${r.toString()}`,parts:s}),r++,s=[];};for(let d of a.parts){if(d.type==="data-user-message"){let u=b(d);l(),n.push({id:d.id??crypto.randomUUID(),parts:u.parts,role:"user"});continue}s.push(d);}l();}return n}function ci(e){return useMemo(()=>qs(e),[e])}function le(e){return e==="success"||e==="failed"||e==="cancelled"||e==="skipped"}function Un({latestMessage:e,recordStatus:t,suppressApprovalPause:n}){return le(t)||n||t==="running"?false:t==="awaiting_approval"?true:Ke(e)||Ve(e)}function fi(e,t){let[n,a]=useState(false),s=Bs(n?e:"",t),[r,l]=useState(),[d,u]=useState("streaming"),f=useRef(t);f.current=t;let c=useRef(null);c.current||(c.current=new EventTarget);let p=c.current,x=t?.resumeToken;return useEffect(()=>{p.dispatchEvent(new Event("wake"));},[x,p]),useEffect(()=>{if(a(false),l(void 0),!e){u("unavailable");return}let v=new AbortController,k,g,w=()=>{k=void 0,g&&!v.signal.aborted&&l({...g});},y=yn({url:e,signal:v.signal,state:()=>({terminal:le(f.current?.recordStatus),paused:Un({latestMessage:g,recordStatus:f.current?.recordStatus,suppressApprovalPause:f.current?.suppressApprovalPause??false})}),onState:C=>{v.signal.aborted||u(C);},wake:p});return (async()=>{try{for await(let C of readUIMessageStream({stream:y,terminateOnError:!0}))g=C,k||(k=setTimeout(w,On));w();}catch(C){if(v.signal.aborted)return;C instanceof ie?a(true):(console.error("Run stream error",C),u("error"));}})(),()=>{v.abort(),k&&clearTimeout(k);}},[e,p]),n?s:{message:r?Ye(r,t?.decidedApprovals??{}):void 0,status:d}}function Bs(e,t){let[n,a]=useState(),[s,r]=useState("streaming"),l=t?.recordStatus,d=t?.resumeToken??0,u=useRef(t?.decidedApprovals??{});u.current=t?.decidedApprovals??{};let f=useRef(t?.suppressApprovalPause??false);f.current=t?.suppressApprovalPause??false;let c=useRef(e),p=useRef(n);return p.current=n,useEffect(()=>{let x=c.current!==e;if(c.current=e,!e){a(void 0),r("unavailable");return}let v=new AbortController,k=x?void 0:p.current,g=x?0:k?.parts.length??0;if(x)a(void 0);else if(k&&(l==="running"||le(l))){let S=Ye(k,u.current);S!==k&&(k=S,a(S));}r("streaming");let w=e.includes("?")?"&":"?",y=async()=>{let S=await fetch(`${e}${w}startIndex=0`,{credentials:"include",signal:v.signal});if(S.status===404)return "unavailable";if(!S.ok||!S.body)throw new Error(`Failed to fetch the run stream (status ${S.status.toString()})`);let R=false,E=parseJsonEventStream({schema:uiMessageChunkSchema,stream:S.body}).pipeThrough(new TransformStream({transform:(U,qn)=>{if(!U.success)throw U.error;U.value.type==="finish"&&(R=true),qn.enqueue(U.value);}})),Y=readUIMessageStream({onError:U=>{v.signal.aborted||console.error("Run stream chunk error",U);},stream:E}),L=null,I=g===0,ge=(U=false)=>{v.signal.aborted||!k||!I&&(I=U||k.parts.length>=g,!I)||a({...k});};try{for await(let U of Y){if(v.signal.aborted)break;k=U,L===null&&(L=window.setTimeout(()=>{L=null,ge();},On));}}finally{L!==null&&(window.clearTimeout(L),L=null),ge(true);}return R?"finished":"incomplete"},C=async()=>{let S=0;for(;!v.signal.aborted;){S>0&&await js(jn);try{let R=await y();if(v.signal.aborted)return;if(R==="unavailable"){r("unavailable");return}if(R==="finished"&&le(l)){r("finished");return}if(le(l)){r("finished");return}if(Un({latestMessage:k,recordStatus:l,suppressApprovalPause:f.current})){r("paused");return}if(!(l==="running"||f.current)&&S>=Dn-1){r("error");return}}catch(R){if(v.signal.aborted||Os(R))return;if(console.error("Run stream error",R),le(l)){r("finished");return}if(!(l==="running"||f.current)&&S>=Dn-1){r("error");return}}S+=1;}},_=window.setTimeout(()=>{C();},0);return ()=>{window.clearTimeout(_),v.abort("Run replay unmounted");}},[l,d,e]),{message:n,status:s}}function pi(e){return {affectedCount:e.affectedCount,approvalId:e.id,decidedBy:e.decidedBy??void 0,operationsSummary:e.operationsSummary,reason:e.reason??void 0,status:e.status}}function Xs(e){let t=e.trim();return t?t.split(`
|
|
9
|
+
`).every(n=>/^`{3,}[\w-]*$/.test(n.trim())):false}function Js({attachments:e,text:t}){return jsxs("div",{className:"fk:ml-auto fk:flex fk:w-fit fk:max-w-[70%] fk:flex-col fk:items-end fk:gap-1",children:[jsx(rn,{attachments:e}),t.trim()?jsx("div",{className:"fk:whitespace-pre-wrap fk:rounded-xl fk:bg-muted fk:dark:bg-white/20 fk:px-3.5 fk:py-2 fk:text-base fk:corner-squircle",children:t}):null,jsxs("span",{className:"fk:inline-flex fk:items-center fk:gap-1 fk:text-xs fk:text-muted-foreground",children:[jsx(CornerDownRightIcon,{className:"fk:size-3 fk:shrink-0"}),"Added while the agent was working"]})]})}function mi({api:e,part:t,partIndex:n,parts:a}){if(Ee(t))return null;if(me(t.type)){let s=Ie(t);return s?jsx(Hs,{message:s}):null}if(t.type==="text")return Xs(t.text)&&a.some(r=>r.type===nt)?null:jsx(Qs,{part:t});if(t.type==="data-chat-search")return jsx(nr,{message:b(t)});if(t.type==="data-knowledge-search")return jsx(tr,{message:b(t)});if(t.type==="data-generating-files")return jsx(Gs,{message:b(t)});if(t.type==="data-run-artifact")return jsx(Zs,{api:e,message:b(t)});if(t.type==="data-tool-delivery")return jsx(er,{message:b(t)});if(t.type==="data-run-summary")return jsx(ar,{message:b(t)});if(t.type==="data-subtask"){let s=b(t),r=s.status==="running"?`Running "${s.title}"`:s.status==="done"?`Completed "${s.title}"${typeof s.stepsUsed=="number"?` in ${s.stepsUsed.toString()} steps`:""}`:`"${s.title}" failed: ${s.error?.message??"unknown error"}`;return jsxs(O,{children:[jsxs(F,{children:[jsx(BotIcon,{className:"fk:size-3.5"}),"Subtask"]}),jsxs("div",{className:"fk:relative fk:min-h-5 fk:pl-6",children:[jsx("span",{className:"fk:absolute fk:left-0 fk:top-0",children:jsx(Le,{isError:s.status==="error",loading:s.status==="running"})}),jsx("span",{className:"fk:text-xs",children:r}),s.resultPreview?jsx("p",{className:"fk:mt-1 fk:text-xs fk:text-muted-foreground",children:s.resultPreview}):null]})]})}if(t.type==="data-mid-turn-message"){let s=b(t);return s.monitorEvent?jsx(un,{data:s.monitorEvent}):jsx(Js,{attachments:s.attachments,text:s.text})}if(t.type==="data-context-compaction"){let s=b(t);return jsxs("p",{className:"fk:text-xs fk:text-muted-foreground",children:["Earlier messages (",s.summarizedMessageCount.toString(),") were summarized to keep this conversation within the model's context. Details may need to be re-fetched."]})}if(t.type==="data-plugin-connection"){let s=b(t);return jsx(vn,{connectionId:s.connectionId,pluginId:s.pluginId})}if(t.type==="data-suggested-prompt")return null;if(t.type==="data-turn-error"){let s=b(t);return jsxs(O,{className:"fk:border-red-700/40",children:[jsxs(F,{children:[jsx(XCircleIcon,{className:"fk:size-3.5 fk:text-red-700"}),jsx("span",{children:"Turn failed"})]}),jsx("p",{className:"fk:whitespace-pre-wrap fk:text-xs",children:s.message})]})}if(t.type==="data-mutation-approval"){let s=b(t);return He(s)?jsx(or,{message:s}):jsx(sr,{api:e,message:s})}return t.type==="data-user-question"?jsx(rr,{data:b(t)}):t.type==="data-bulk-graphql-action"?jsx(ir,{message:b(t)}):t.type===nt?a.slice(n+1).find(r=>r.type===nt)?null:jsx(zs,{parts:a}):t.type.startsWith("data-")?jsx(lr,{part:t}):null}function Qs({part:e}){return jsx(mb,{className:"fk:min-w-0 fk:max-w-full fk:overflow-x-auto fk:text-base fk:leading-relaxed fk:text-foreground",isAnimating:e.state==="streaming",children:e.text})}function Hs({message:e}){return jsxs("div",{className:"fk:flex fk:items-start fk:gap-2 fk:rounded-xl fk:border fk:border-red-700/40 fk:bg-destructive/5 fk:px-3.5 fk:py-3 fk:text-sm fk:corner-squircle",children:[jsx(XCircleIcon,{className:"fk:mt-0.5 fk:size-3.5 fk:shrink-0 fk:text-red-700"}),jsx("span",{className:"fk:whitespace-pre-wrap fk:text-xs",children:e})]})}var Ks=1e3;function Ys({text:e}){let t=useRef(typeof performance>"u"?0:performance.now()),n=()=>-(((typeof performance>"u"?0:performance.now())-t.current)%Ks),[a,s]=useState({current:e,currentDelayMs:0,key:0,previous:null,previousDelayMs:0});return useEffect(()=>{s(r=>r.current===e?r:{current:e,currentDelayMs:n(),key:r.key+1,previous:r.current,previousDelayMs:r.currentDelayMs});},[e]),jsxs("span",{className:"fk:relative fk:block fk:h-5 fk:min-w-0 fk:flex-1 fk:overflow-hidden",children:[a.previous?jsx("span",{"aria-hidden":true,className:"fk:absolute fk:inset-x-0 fk:top-0 fk:block fk:animate-roll-up-out",children:jsx("span",{className:"fk:block fk:truncate fk:shimmer fk:shimmer-duration-1000",style:{animationDelay:`${a.previousDelayMs.toString()}ms`},children:a.previous})},`previous-${a.key.toString()}`):null,jsx("span",{className:a.previous?"fk:block fk:animate-roll-up-in":"fk:block",role:"status",children:jsx("span",{className:"fk:block fk:truncate fk:shimmer fk:shimmer-duration-1000",style:{animationDelay:`${a.currentDelayMs.toString()}ms`},children:a.current})},`current-${a.key.toString()}`)]})}var Vs=1e3;function Ws(e,t){let n=Vs,[a,s]=useState(e),r=useRef(Date.now()),l=useRef(e);return l.current=e,useEffect(()=>{if(e===a)return;let d=Math.max(0,n-(Date.now()-r.current)),u=window.setTimeout(()=>{r.current=Date.now(),s(l.current);},d);return ()=>{window.clearTimeout(u);}},[a,e,n]),a}function ki({label:e,visible:t}){let n=Ws(e);return jsx("div",{"aria-hidden":!t,className:`fk:flex fk:h-9 fk:items-center fk:text-sm fk:text-muted-foreground fk:transition-[opacity,visibility] fk:duration-200 ${t?"fk:visible fk:opacity-100":"fk:invisible fk:opacity-0"}`,children:jsx(Ys,{text:n})})}function O({children:e,className:t=""}){return jsx("div",{className:`fk:min-w-0 fk:max-w-full fk:overflow-x-auto fk:rounded-xl fk:border fk:border-border fk:bg-background fk:px-3.5 fk:py-3 fk:text-sm ${t} fk:corner-squircle`,children:e})}function F({children:e}){return jsx("div",{className:"fk:flex fk:items-center fk:gap-2 fk:font-medium fk:text-muted-foreground",children:e})}function Le({isError:e,loading:t}){return t?jsx(LoaderCircle,{className:"fk:size-4 fk:animate-spin"}):e?jsx(XIcon,{className:"fk:size-4 fk:text-red-700"}):jsx(CheckIcon,{className:"fk:size-4"})}function ke({error:e,icon:t,loading:n,message:a,title:s}){return jsxs(O,{children:[jsxs(F,{children:[t,s]}),jsxs("div",{className:"fk:relative fk:min-h-5 fk:pl-6",children:[jsx("span",{className:"fk:absolute fk:left-0 fk:top-0",children:jsx(Le,{isError:!!e,loading:n})}),jsx("span",{className:"fk:text-xs",children:a})]})]})}function Gs({message:e}){let t=["error","uploading","generating"].includes(e.status),n=t?e.paths.slice(0,e.paths.length-1):e.paths,a=t?e.paths[e.paths.length-1]??"":null;return jsxs(O,{children:[jsxs(F,{children:[jsx(CloudUploadIcon,{className:"fk:size-3.5"}),jsx("span",{children:e.status==="done"?"Uploaded files":"Generating files"})]}),jsxs("div",{className:"fk:space-y-1 fk:text-sm",children:[n.map((s,r)=>jsxs("div",{className:"fk:flex fk:items-center fk:gap-2",children:[jsx(CheckIcon,{className:"fk:size-4"}),jsx("span",{className:"fk:whitespace-pre-wrap",children:s})]},`${s}-${r.toString()}`)),typeof a=="string"?jsxs("div",{className:"fk:flex fk:items-center fk:gap-2",children:[jsx(Le,{isError:e.status==="error",loading:e.status!=="error"}),jsx("span",{children:e.status==="error"?e.error?.message??a:a})]}):null]})]})}function Zs({api:e,message:t}){let n=t.status==="done"&&t.artifactId,a=n?b$3()&&t.url||e.getArtifactUrl(t.artifactId??""):"",s=n?e.getArtifactUrl(t.artifactId??"",{download:true}):"",r=ur(t.sizeBytes);return jsxs(O,{children:[jsxs(F,{children:[jsx(FileTextIcon,{className:"fk:size-3.5"}),t.kind==="csv"||t.kind==="json"?"Exported file":t.status==="done"?"Published artifact":"Publishing artifact"]}),jsxs("div",{className:"fk:relative fk:min-h-5 fk:pl-6",children:[jsx("span",{className:"fk:absolute fk:left-0 fk:top-0",children:jsx(Le,{isError:t.status==="error",loading:t.status==="uploading"})}),jsxs("div",{className:"fk:min-w-0 fk:space-y-2",children:[jsxs("div",{className:"fk:min-w-0",children:[jsx("div",{className:"fk:truncate fk:font-medium",children:t.filename}),jsxs("div",{className:"fk:text-xs fk:text-muted-foreground",children:[t.status==="uploading"&&"Uploading to artifacts",t.status==="done"&&[dr(t),r].filter(Boolean).join(" \xB7 "),t.status==="error"&&(t.error?.message??"Failed to publish artifact")]})]}),n?jsxs("div",{className:"fk:flex fk:flex-wrap fk:gap-2",children:[t.kind==="csv"?null:jsx(c$1,{asChild:true,size:"sm",variant:"outline",children:jsx("a",{href:a,rel:"noreferrer",target:"_blank",children:"Preview"})}),jsx(c$1,{asChild:true,size:"sm",variant:"outline",children:jsxs("a",{href:s,children:[jsx(DownloadIcon,{className:"fk:size-3"}),"Download"]})}),t.url?jsx(c$1,{asChild:true,size:"sm",variant:"outline",children:jsxs("a",{href:t.url,rel:"noreferrer",target:"_blank",children:[jsx(LinkIcon,{className:"fk:size-3"}),"Permanent link"]})}):null]}):null]})]})]})}function er({message:e}){let t=e.provider==="slack"?"Slack":"Microsoft Teams",n=e.provider==="slack"?jsx(MessageSquareIcon,{className:"fk:size-3.5"}):jsx(SendIcon,{className:"fk:size-3.5"});return jsx(ke,{error:e.error?.message,icon:n,loading:e.status==="loading",message:e.status==="error"?e.error?.message??`Failed to send result to ${e.channelName}`:`${e.status==="done"?"Sent":"Sending"} result to ${e.channelName}`,title:`${t} Delivery`})}function tr({message:e}){let{currentProjectId:t}=f(),n=useMemo(()=>wn(e.results),[e.results]);return e.status==="error"?jsx(ke,{error:e.error?.message??"The knowledge search failed",icon:jsx(LibraryIcon,{className:"fk:size-3.5"}),loading:false,message:e.error?.message??"The knowledge search failed",title:"Knowledge search"}):jsxs(O,{children:[jsxs(F,{children:[jsx(LibraryIcon,{className:"fk:size-3.5"}),jsx("span",{children:"Knowledge search"})]}),jsx("p",{className:"fk:mt-1 fk:text-xs fk:text-muted-foreground",children:Sn(e.query,n)}),n.length>0?jsxs(Cc,{className:"fk:mb-0 fk:mt-2",children:[jsxs(Dc,{count:n.length,children:[jsx("p",{className:"fk:font-medium",children:n.length===1?"Show the cited passages":`Show passages from ${String(n.length)} documents`}),jsx(ChevronDownIcon,{className:"fk:size-4"})]}),jsx(Ec,{className:"fk:w-full",children:n.map(a=>jsxs("div",{className:"fk:flex fk:flex-col fk:gap-1.5",children:[t?jsxs(Link,{className:"fk:flex fk:w-fit fk:items-center fk:gap-2 fk:font-medium fk:text-foreground fk:underline-offset-2 fk:hover:underline",to:o(t,a.sourceId),children:[jsx(BookOpenIcon,{className:"fk:size-4"}),jsx("span",{children:a.sourceTitle})]}):jsxs("span",{className:"fk:flex fk:items-center fk:gap-2 fk:font-medium fk:text-foreground",children:[jsx(BookOpenIcon,{className:"fk:size-4"}),jsx("span",{children:a.sourceTitle})]}),jsx("ul",{className:"fk:flex fk:flex-col fk:gap-1.5 fk:pl-6",children:a.passages.map(s=>jsxs("li",{className:"fk:text-xs fk:text-muted-foreground",children:[s.locator?jsxs("span",{className:"fk:mr-1 fk:font-medium fk:text-foreground/80",children:[s.locator,":"]}):null,jsxs("span",{className:"fk:italic",children:["\u201C",s.excerpt,"\u201D"]})]},s.passageId))})]},a.sourceId))})]}):null]})}function nr({message:e}){let{currentProjectId:t}=f(),n=useMemo(()=>An(e.results),[e.results]);return e.status==="error"?jsx(ke,{error:e.error?.message??"The search of past chats failed",icon:jsx(HistoryIcon,{className:"fk:size-3.5"}),loading:false,message:e.error?.message??"The search of past chats failed",title:"Past chats"}):jsxs(O,{children:[jsxs(F,{children:[jsx(HistoryIcon,{className:"fk:size-3.5"}),jsx("span",{children:"Past chats"})]}),jsx("p",{className:"fk:mt-1 fk:text-xs fk:text-muted-foreground",children:Cn(e.query,n)}),n.length>0?jsxs(Cc,{className:"fk:mb-0 fk:mt-2",children:[jsxs(Dc,{count:n.length,children:[jsx("p",{className:"fk:font-medium",children:n.length===1?"Show the chat":`Show ${String(n.length)} chats`}),jsx(ChevronDownIcon,{className:"fk:size-4"})]}),jsx(Ec,{className:"fk:w-full",children:n.map(a=>jsxs("div",{className:"fk:flex fk:flex-col fk:gap-1",children:[t?jsxs(Link,{className:"fk:flex fk:w-fit fk:items-center fk:gap-2 fk:font-medium fk:text-foreground fk:underline-offset-2 fk:hover:underline",to:Nn(t,a.chatId),children:[jsx(MessageSquareIcon,{className:"fk:size-4"}),jsx("span",{children:a.chatTitle})]}):jsxs("span",{className:"fk:flex fk:items-center fk:gap-2 fk:font-medium fk:text-foreground",children:[jsx(MessageSquareIcon,{className:"fk:size-4"}),jsx("span",{children:a.chatTitle})]}),jsxs("p",{className:"fk:pl-6 fk:text-xs fk:text-muted-foreground",children:[jsxs("span",{className:"fk:mr-1 fk:font-medium fk:text-foreground/80",children:[a.date,":"]}),jsxs("span",{className:"fk:italic",children:["\u201C",a.excerpt,"\u201D"]})]})]},a.chatId))})]}):null]})}function ar({message:e}){let t=e.status==="success"?jsx(CheckCircle2Icon,{className:"fk:size-3.5 fk:text-green-700"}):e.status==="skipped"?jsx(CircleSlashIcon,{className:"fk:size-3.5"}):jsx(XCircleIcon,{className:"fk:size-3.5 fk:text-red-700"}),n=e.status==="success"?"Run completed":e.status==="skipped"?"Run skipped":"Run failed";return jsxs(O,{className:e.status==="failed"?"fk:border-red-700/40":"fk:border-green-700/40",children:[jsxs(F,{children:[t,jsx("span",{children:n})]}),e.status==="failed"?jsx("p",{className:"fk:whitespace-pre-wrap fk:text-xs",children:e.summary}):null]})}function sr({api:e,message:t}){let{projectId:n}=_s(),a=useContext(Fn),s=useContext(Ls),r=useRef(void 0),{data:l,error:d,isValidating:u,mutate:f}=Ya(n?g(n).approval(t.approvalId):null,f$1,{refreshInterval:g=>t.status!=="pending"||g?.approval?.status&&g.approval.status!=="pending"?0:jn}),c=l?.approval?.status,p=(c??t.status)==="pending",x=l?.approval?.kind==="schema"&&l.approval.status==="approved";useEffect(()=>{!x||!n||Ae({approvalId:t.approvalId,approvalUrl:g(n).approval(t.approvalId),projectId:n});},[x,t.approvalId,n]),useEffect(()=>{f();},[t.status,f]),useEffect(()=>{let g=r.current;r.current=c,!(t.status!=="pending"||!c||c==="pending")&&g==="pending"&&a?.onApprovalDecided(l?.approval?.id??t.approvalId,c);},[c,l?.approval?.id,t.approvalId,t.status,a]);function v(g){g.status!=="pending"&&(r.current=g.status),f(),a?.onApprovalDecided(g.id,g.status);}let k;if(l?.approval)k=jsx(Ft,{api:e,approval:l.approval,chat:s,onDecided:v},l.approval.status);else if(d&&!u){let g=d instanceof Error&&d.message?d.message:"Request failed";k=jsxs("div",{className:"fk:space-y-2",children:[jsxs("p",{className:"fk:text-xs fk:text-destructive",children:["Failed to load proposal ",t.operationsSummary,": ",g]}),jsx(c$1,{size:"sm",variant:"outline",onClick:()=>{f();},children:"Retry"})]});}else k=jsxs("div",{className:"fk:flex fk:items-center fk:gap-2 fk:text-xs fk:text-muted-foreground",children:[jsx(LoaderCircle,{className:"fk:size-3.5 fk:animate-spin"}),jsxs("span",{children:["Loading proposal ",t.operationsSummary,"..."]})]});return jsxs(O,{children:[jsxs(F,{children:[s?jsx(ShieldIcon,{className:"fk:size-3.5"}):jsx(DatabaseZapIcon,{className:"fk:size-3.5"}),s?"Approval request":"Mutation approval",p?jsx(LoaderCircle,{className:"fk:ml-1 fk:size-3.5 fk:animate-spin"}):null]}),jsx("div",{className:"fk:mt-2",children:k}),t.status==="error"&&t.error?jsx("p",{className:"fk:mt-2 fk:text-xs fk:text-destructive",children:t.error.message}):null]})}function rr({data:e}){let t=useContext(Fn),n=e.questions.length>1;return jsxs(O,{children:[jsxs(F,{children:[jsx(MessageCircleQuestionIcon,{className:"fk:size-3.5"}),e.status==="pending"?n?"The agent has questions":"The agent has a question":n?"Questions":"Question"]}),jsx("div",{className:"fk:mt-3",children:jsx(xn,{answer:t?.answerQuestion,data:e},e.status)})]})}function or({message:e}){let t=e.operationsSummary.replace(/^Call /,"");return jsx(ke,{error:e.status==="error"?e.error?.message??"The call failed.":void 0,icon:jsx(ShieldCheckIcon,{className:"fk:size-3.5"}),loading:false,message:e.status==="error"?`${t}: ${e.error?.message??"The call failed."}`:`${t} \xB7 Auto-approved by Jev`,title:"Plugin call"})}function ir({message:e}){let t=[typeof e.processedItems=="number"?`${e.processedItems.toString()} processed`:"",typeof e.changedItems=="number"?`${e.changedItems.toString()} changed`:"",typeof e.failedItems=="number"?`${e.failedItems.toString()} failed`:"",typeof e.totalItems=="number"?`${e.totalItems.toString()} total`:""].filter(Boolean);return jsx(ke,{error:e.error?.message,icon:jsx(DatabaseZapIcon,{className:"fk:size-3.5"}),loading:e.status==="loading"||e.status==="running",message:e.status==="error"?e.error?.message??`Failed bulk ${e.operationName}`:`${e.status==="done"?"Completed":"Running"} ${e.operationName}${t.length>0?` (${t.join(", ")})`:""}`,title:"Bulk GraphQL action"})}function lr({part:e}){return jsxs(O,{className:"fk:bg-muted/30",children:[jsxs(F,{children:[jsx(CheckCircle2Icon,{className:"fk:size-3.5"}),e.type.replace(/^data-/,"").replaceAll("-"," ")]}),jsx("p",{className:"fk:text-xs fk:text-muted-foreground",children:"This run emitted a structured event that is not yet rendered by Studio."})]})}function ur(e){if(typeof e!="number")return "";if(e<1024)return `${e.toString()} B`;let t=e/1024;return t<1024?`${t.toFixed(1)} KB`:`${(t/1024).toFixed(1)} MB`}function dr(e){return e.kind==="pdf"?"PDF artifact":e.kind==="html"?"HTML artifact":e.kind==="csv"?"CSV file":e.kind==="json"?"JSON file":"Artifact"}export{Ls as A,ci as B,le as C,fi as D,pi as E,mi as F,Hs as G,ki as H,sr as I,Nt as a,sa as b,Ft as c,Rr as d,Ee as e,Pa as f,Ke as g,qt as h,Ra as i,Ve as j,Ta as k,Vt as l,eo as m,to as n,no as o,ao as p,rn as q,mo as r,un as s,ko as t,ss as u,Ro as v,To as w,_s as x,jn as y,Fn as z};//# sourceMappingURL=chunk-ZV7I5RUM.js.map
|
|
10
|
+
//# sourceMappingURL=chunk-ZV7I5RUM.js.map
|