@flexkit/studio 0.2.29 → 0.2.31
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-UT5M3PM3.js → chat-page-JS5SJ4OG.js} +3 -3
- package/dist/{chat-page-UT5M3PM3.js.map → chat-page-JS5SJ4OG.js.map} +1 -1
- package/dist/{chunk-FRTHKTAS.js → chunk-57X5WRMY.js} +2 -2
- package/dist/{chunk-FRTHKTAS.js.map → chunk-57X5WRMY.js.map} +1 -1
- package/dist/{chunk-BSUCDQYM.js → chunk-5NQ47SWN.js} +3 -3
- package/dist/{chunk-BSUCDQYM.js.map → chunk-5NQ47SWN.js.map} +1 -1
- package/dist/{chunk-D3TJCUTA.js → chunk-6GXNHR6H.js} +2 -2
- package/dist/{chunk-D3TJCUTA.js.map → chunk-6GXNHR6H.js.map} +1 -1
- package/dist/chunk-D76P4TER.js +378 -0
- package/dist/chunk-D76P4TER.js.map +1 -0
- package/dist/{chunk-7AN2E6TU.js → chunk-GQTWNWT7.js} +2 -2
- package/dist/{chunk-7AN2E6TU.js.map → chunk-GQTWNWT7.js.map} +1 -1
- package/dist/{chunk-6A6NT3H3.js → chunk-GXQSNOGM.js} +3 -3
- package/dist/{chunk-6A6NT3H3.js.map → chunk-GXQSNOGM.js.map} +1 -1
- package/dist/{chunk-UET5IDEW.js → chunk-KVYQ3O4F.js} +3 -3
- package/dist/{chunk-UET5IDEW.js.map → chunk-KVYQ3O4F.js.map} +1 -1
- package/dist/{chunk-T44KNWQD.js → chunk-LF4B2TQI.js} +4 -4
- package/dist/{chunk-T44KNWQD.js.map → chunk-LF4B2TQI.js.map} +1 -1
- package/dist/{chunk-AZG72R2F.js → chunk-OMYDXVWS.js} +3 -3
- package/dist/{chunk-AZG72R2F.js.map → chunk-OMYDXVWS.js.map} +1 -1
- package/dist/{chunk-BRGTUEFL.js → chunk-SZ3DX7XD.js} +2 -2
- package/dist/{chunk-BRGTUEFL.js.map → chunk-SZ3DX7XD.js.map} +1 -1
- package/dist/{chunk-BIFQCOZD.js → chunk-T4SEZXGL.js} +2 -2
- package/dist/{chunk-BIFQCOZD.js.map → chunk-T4SEZXGL.js.map} +1 -1
- package/dist/{chunk-ZUGTNE5M.js → chunk-W74OKBZG.js} +2 -2
- package/dist/{chunk-ZUGTNE5M.js.map → chunk-W74OKBZG.js.map} +1 -1
- package/dist/chunk-XLFAJBPN.js +3 -0
- package/dist/chunk-XLFAJBPN.js.map +1 -0
- package/dist/{entry-QGRB2B7V.js → entry-PFXS633U.js} +2 -2
- package/dist/{entry-QGRB2B7V.js.map → entry-PFXS633U.js.map} +1 -1
- package/dist/index.d.ts +4 -2
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/{list-L6YZSBWF.js → list-EWWRLK4I.js} +3 -3
- package/dist/{list-L6YZSBWF.js.map → list-EWWRLK4I.js.map} +1 -1
- package/dist/list-R7SJFXCX.js +2 -0
- package/dist/list-R7SJFXCX.js.map +1 -0
- package/dist/{pages-K4XZAMXY.js → pages-UKJWXOMO.js} +3 -3
- package/dist/{pages-K4XZAMXY.js.map → pages-UKJWXOMO.js.map} +1 -1
- package/dist/{plugin-pages-RCWAF6VC.js → plugin-pages-X3V2VPAU.js} +2 -2
- package/dist/{plugin-pages-RCWAF6VC.js.map → plugin-pages-X3V2VPAU.js.map} +1 -1
- package/dist/record-links-VH2TPCK4.js +2 -0
- package/dist/{record-links-R7OV4VVH.js.map → record-links-VH2TPCK4.js.map} +1 -1
- package/dist/{root-R4Y6L62R.js → root-4QRY7KAC.js} +3 -3
- package/dist/{root-R4Y6L62R.js.map → root-4QRY7KAC.js.map} +1 -1
- package/dist/{root-L6Y4PSSA.js → root-7YXE6DEA.js} +3 -3
- package/dist/{root-L6Y4PSSA.js.map → root-7YXE6DEA.js.map} +1 -1
- package/dist/{root-3M4DIRWC.js → root-FNXHGVQT.js} +2 -2
- package/dist/{root-3M4DIRWC.js.map → root-FNXHGVQT.js.map} +1 -1
- package/dist/{root-36COMEVE.js → root-HQQ4TNTR.js} +2 -2
- package/dist/{root-36COMEVE.js.map → root-HQQ4TNTR.js.map} +1 -1
- package/dist/{root-XMZYVO37.js → root-NYAXP66A.js} +3 -3
- package/dist/{root-XMZYVO37.js.map → root-NYAXP66A.js.map} +1 -1
- package/dist/{root-HETKL6EN.js → root-OJ4UFMRX.js} +2 -2
- package/dist/{root-HETKL6EN.js.map → root-OJ4UFMRX.js.map} +1 -1
- package/dist/{search-UXL3U2EH.js → search-LSIHN6OI.js} +2 -2
- package/dist/{search-UXL3U2EH.js.map → search-LSIHN6OI.js.map} +1 -1
- package/dist/{skills-pages-KEXNO6DN.js → skills-pages-W47HECK3.js} +2 -2
- package/dist/{skills-pages-KEXNO6DN.js.map → skills-pages-W47HECK3.js.map} +1 -1
- package/dist/{source-CWVJGMEZ.js → source-3N7BQVYO.js} +2 -2
- package/dist/{source-CWVJGMEZ.js.map → source-3N7BQVYO.js.map} +1 -1
- package/package.json +2 -2
- package/dist/chunk-H534S4KD.js +0 -3
- package/dist/chunk-H534S4KD.js.map +0 -1
- package/dist/chunk-RZZOOPEF.js +0 -378
- package/dist/chunk-RZZOOPEF.js.map +0 -1
- package/dist/list-OPL5OO32.js +0 -2
- package/dist/list-OPL5OO32.js.map +0 -1
- package/dist/record-links-R7OV4VVH.js +0 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/use-studio-version.ts","../src/core/telemetry.ts","../src/core/error/error-reporter.ts","../src/core/analytics/product-events.ts"],"names":["STUDIO_VERSION","WEB_VERSION","useStudioVersion","desktop","getDesktop","downloaded","setDownloaded","useState","useEffect","update","TELEMETRY_STORAGE_KEY","LEGACY_TELEMETRY_STORAGE_KEY","LOCAL_HOSTNAME","isTelemetryEnabled","env","readOverride","storage","getLocalStorage","isStudioTelemetryEnabled","hosted","flexkitDomain","postToUserApi","path","body","keepalive","LIMITS","MAX_ERRORS_PER_REPORT","MAX_REPORT_BYTES","MAX_ERRORS_PER_SESSION","FLUSH_INTERVAL_MS","PROJECT_ID_PATTERN","truncate","value","max","toReportPath","pathOrUrl","describeError","error","constructorName","NOISE_MESSAGES","EXTENSION_URL","EMAIL_ADDRESS","maskMessage","message","isNoiseError","details","sourceUrl","pattern","buildClientError","options","entry","errorKey","encoder","byteLength","buildReportBody","app","queue","maxBytes","size","errors","errorSize","createErrorReporter","send","getPath","now","setTimer","callback","ms","clearTimer","timer","seen","accepted","projectId","stopped","schedule","flush","sendNext","unloading","next","status","key","id","sendReportToBff","url","userApiPaths","installed","reportStudioError","source","componentStack","setErrorReportingProjectId","installErrorReporter","reporter","onError","event","onUnhandledRejection","onPageHide","productEventKey","studioEvent","createProductEventTracker","pending","delivered","onDelivered","settle","tracker","trackStudioEvent","DESKTOP_LAUNCH_STORAGE_KEY","readSessionFlag","writeSessionFlag","installProductEvents","current"],"mappings":"gLAeO,IAAMA,CAAAA,CAA0D,QAAA,CACjEC,CAAAA,CAA6B,CAAE,OAAA,CAASD,CAAAA,CAAgB,MAAA,CAAQA,CAAAA,CAAgB,SAAA,CAAW,IAAK,CAAA,CAO/F,SAASE,EAAAA,EAAkC,CAChD,IAAMC,CAAAA,CAAUC,CAAAA,EAAW,CACrB,CAACC,CAAAA,CAAYC,CAAa,CAAA,CAAIC,SAAwB,IAAI,CAAA,CAYhE,OAVAC,SAAAA,CAAU,IAAM,CACd,GAAKL,CAAAA,CAIL,OAAOA,CAAAA,CAAQ,kBAAA,CAAoBM,CAAAA,EAAW,CAC5CH,CAAAA,CAAcG,CAAAA,CAAO,OAAO,EAC9B,CAAC,CACH,CAAA,CAAG,CAACN,CAAO,CAAC,CAAA,CAEPA,CAAAA,CAIDE,CAAAA,GAAe,IAAA,CACV,CAAE,OAAA,CAASF,CAAAA,CAAQ,OAAA,CAAS,MAAA,CAAQA,CAAAA,CAAQ,QAAS,SAAA,CAAW,IAAK,CAAA,CAGvE,CAAE,OAAA,CAASA,CAAAA,CAAQ,OAAA,CAAS,MAAA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,CAA2B3E,CAAAA,EACzCF,EAAc+D,CAAAA,CAAa,aAAA,CAAe7D,EAAM,CAAE,SAAA,CAAW,IAAK,CAAC,CACrE,CAAA,CACMpB,EAAUC,CAAAA,EAAW,CAE3B,OAAAmG,CAAAA,CAAUM,CAAAA,CAEN1G,GAAW,CAACuG,EAAAA,CAAgBD,CAA0B,CAAA,EACxDI,CAAAA,CAAQ,KAAA,CACN,CAAE,UAAA,CAAY1G,CAAAA,CAAQ,QAAS,KAAA,CAAO,oBAAA,CAAsB,GAAIA,CAAAA,CAAQ,QAAS,CAAA,CACjF,CAAE,WAAA,CAAa,IAAMwG,GAAiBF,CAA0B,CAAE,CACpE,CAAA,CAGK,IAAM,CACPF,CAAAA,GAAYM,CAAAA,GACdN,CAAAA,CAAU,IAAA,EAEd,CACF","file":"chunk-UET5IDEW.js","sourcesContent":["'use client';\n\nimport { useEffect, useState } from 'react';\nimport { getDesktop } from './desktop';\n\nexport interface StudioVersion {\n current: string;\n latest: string;\n isCurrent: boolean;\n /** Applies the newer version (the desktop app restarts into it); undefined when there is nothing to apply. */\n upgrade?: () => void;\n}\n\n// `@flexkit/studio`'s own version, inlined at build time; a build without the\n// define (tests, tooling) shows a placeholder.\nexport const STUDIO_VERSION = typeof __STUDIO_VERSION__ === 'string' ? __STUDIO_VERSION__ : '0.0.0';\nconst WEB_VERSION: StudioVersion = { current: STUDIO_VERSION, latest: STUDIO_VERSION, isCurrent: true };\n\n/**\n * The Studio version shown in the app bar. The web Studio is always current\n * (the hosted Studio deploys with the packages); the desktop app reports its\n * own version and the update it has downloaded, if any.\n */\nexport function useStudioVersion(): StudioVersion {\n const desktop = getDesktop();\n const [downloaded, setDownloaded] = useState<string | null>(null);\n\n useEffect(() => {\n if (!desktop) {\n return;\n }\n\n return desktop.onUpdateDownloaded((update) => {\n setDownloaded(update.version);\n });\n }, [desktop]);\n\n if (!desktop) {\n return WEB_VERSION;\n }\n\n if (downloaded === null) {\n return { current: desktop.version, latest: desktop.version, isCurrent: true };\n }\n\n return { current: desktop.version, latest: downloaded, isCurrent: false, upgrade: () => desktop.installUpdate() };\n}\n","import { getDesktop } from './desktop';\nimport { flexkitDomain } from './domains';\nimport { getLocalStorage } from './local-storage';\nimport { STUDIO_VERSION } from './use-studio-version';\n\n/**\n * The on/off decision and the transport shared by the Studio's error reports\n * (core/error/error-reporter.ts) and product events\n * (core/analytics/product-events.ts).\n */\n\n/** Turns error reports and product events on (`on`) or off (`off`) in this browser, whatever the environment. */\nexport const TELEMETRY_STORAGE_KEY = 'flexkit:telemetry';\n/** The key error reporting shipped with; still honoured. */\nexport const LEGACY_TELEMETRY_STORAGE_KEY = 'flexkit:error-reporting';\n\nexport interface TelemetryEnvironment {\n /** The Studio lists the signed-in user's projects (hosted Studio, desktop app). */\n hosted: boolean;\n isDesktop: boolean;\n domain: string;\n hostname: string;\n version: string;\n /** The local storage setting in this browser, if any. */\n override: string | null;\n}\n\nconst LOCAL_HOSTNAME = /^(localhost|127\\.0\\.0\\.1|\\[::1\\]|0\\.0\\.0\\.0)$|\\.(localhost|test|local)$/i;\n\n/**\n * On for the hosted Studio and the desktop app against the production\n * backend, and off in development: a local backend (`flexkit.test`), a local\n * host, or a build without a version. The local storage setting forces it\n * `on` or `off`.\n */\nexport function isTelemetryEnabled(env: TelemetryEnvironment): boolean {\n if (env.override === 'on') {\n return true;\n }\n\n if (env.override === 'off') {\n return false;\n }\n\n if (!env.hosted || env.domain !== 'flexkit.io' || env.version === '0.0.0') {\n return false;\n }\n\n return env.isDesktop || !LOCAL_HOSTNAME.test(env.hostname);\n}\n\nfunction readOverride(): string | null {\n try {\n const storage = getLocalStorage();\n\n return storage?.getItem(TELEMETRY_STORAGE_KEY) ?? storage?.getItem(LEGACY_TELEMETRY_STORAGE_KEY) ?? null;\n } catch {\n return null;\n }\n}\n\n/** Whether this Studio sends error reports and product events to Flexkit. */\nexport function isStudioTelemetryEnabled({ hosted }: { hosted: boolean }): boolean {\n if (typeof window === 'undefined') {\n return false;\n }\n\n return isTelemetryEnabled({\n hosted,\n isDesktop: Boolean(getDesktop()),\n domain: flexkitDomain,\n hostname: window.location.hostname,\n version: STUDIO_VERSION,\n override: readOverride(),\n });\n}\n\n/**\n * POSTs JSON to a user-level backend route through the Studio's server proxy,\n * which adds the session. `keepalive` lets the request outlive the page.\n * Returns the response status.\n */\nexport async function postToUserApi(path: string, body: string, { keepalive = false } = {}): Promise<number> {\n const response = await fetch(path, {\n body,\n credentials: 'same-origin',\n headers: { 'Content-Type': 'application/json' },\n keepalive,\n method: 'POST',\n });\n\n return response.status;\n}\n","import { userApiPaths } from '../api-paths';\nimport { getDesktop } from '../desktop';\nimport { STUDIO_VERSION } from '../use-studio-version';\nimport { isStudioTelemetryEnabled, postToUserApi } from '../telemetry';\n\n/**\n * Reports unexpected Studio errors (uncaught errors, unhandled rejections and\n * errors caught by the error boundaries) to Flexkit through the Studio's own\n * BFF (`/api/flexkit/-/client-errors`), which forwards the session so the\n * report is attributed to the signed-in user.\n *\n * Reports carry the error, the Studio path (no query string or hash) and the\n * current project id; never request bodies, form values or record data.\n */\n\nexport type ClientErrorSource = 'window' | 'unhandledrejection' | 'react' | 'manual';\n\nexport interface ClientError {\n source: ClientErrorSource;\n name: string;\n message: string;\n stack?: string;\n componentStack?: string;\n path?: string;\n projectId?: string;\n occurredAt: string;\n}\n\nexport interface ClientErrorApp {\n platform: 'web' | 'desktop';\n version: string;\n userAgent?: string;\n}\n\nexport interface ClientErrorReport {\n app: ClientErrorApp;\n errors: ClientError[];\n}\n\n/** Field limits of the backend schema. */\nconst LIMITS = {\n componentStack: 4_000,\n message: 2_000,\n name: 200,\n path: 500,\n stack: 8_000,\n userAgent: 500,\n} as const;\n\n/** The backend accepts 1 to 10 errors per report. */\nexport const MAX_ERRORS_PER_REPORT = 10;\n/** The backend refuses bodies over 64 KB; `keepalive` requests share a 64 KB budget too. */\nexport const MAX_REPORT_BYTES = 60_000;\n/** Reports kept per page session; anything after that is dropped. */\nexport const MAX_ERRORS_PER_SESSION = 50;\n/** At most one report is sent per interval; errors in between are batched. */\nexport const FLUSH_INTERVAL_MS = 5_000;\n\n/** Kept for callers and tests that name the gate after error reporting. */\nexport {\n isTelemetryEnabled as isErrorReportingEnabled,\n LEGACY_TELEMETRY_STORAGE_KEY as ERROR_REPORTING_STORAGE_KEY,\n type TelemetryEnvironment as ErrorReportingEnvironment,\n} from '../telemetry';\n\nexport const PROJECT_ID_PATTERN = /^[a-z0-9]{1,64}$/;\n\nfunction truncate(value: string, max: number): string {\n return value.length > max ? value.slice(0, max) : value;\n}\n\n/** The pathname of a path or URL, without query string or hash. */\nexport function toReportPath(pathOrUrl: string): string {\n let path = pathOrUrl;\n\n try {\n if (/^[a-z][a-z0-9+.-]*:/i.test(pathOrUrl)) {\n path = new URL(pathOrUrl).pathname;\n }\n } catch {\n // Not a URL; strip by hand below.\n }\n\n return truncate(path.split(/[?#]/)[0] ?? '', LIMITS.path);\n}\n\nexport interface ErrorDetails {\n name: string;\n message: string;\n stack?: string;\n}\n\n/**\n * Name, message and stack of anything thrown. A non-Error value (a rejected\n * promise with a plain object) is described by its type only, so record data\n * someone rejected with never leaves the browser.\n */\nexport function describeError(error: unknown): ErrorDetails {\n if (error instanceof Error) {\n return {\n name: error.name || 'Error',\n message: typeof error.message === 'string' ? error.message : '',\n stack: typeof error.stack === 'string' ? error.stack : undefined,\n };\n }\n\n if (typeof error === 'string') {\n return { name: 'Error', message: error };\n }\n\n if (error === null || error === undefined) {\n return { name: 'Error', message: `Non-Error thrown: ${String(error)}` };\n }\n\n if (typeof error === 'object') {\n const constructorName = (error as { constructor?: { name?: unknown } }).constructor?.name;\n\n return {\n name: 'Error',\n message: `Non-Error thrown: ${typeof constructorName === 'string' && constructorName ? constructorName : 'object'}`,\n };\n }\n\n return { name: 'Error', message: `Non-Error thrown: ${typeof error}` };\n}\n\nconst NOISE_MESSAGES = [\n /ResizeObserver loop (limit exceeded|completed with undelivered notifications)/i,\n // Cross-origin script errors carry nothing to act on.\n /^Script error\\.?$/i,\n /The (operation|user) (was )?aborted/i,\n /signal is aborted without reason/i,\n];\n\nconst EXTENSION_URL = /\\b(chrome|moz|safari(-web)?|ms-browser)-extension:\\/\\//i;\n\nconst EMAIL_ADDRESS = /[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,}/gi;\n\n/** Masks email addresses an error message may quote from a record or form. */\nexport function maskMessage(message: string): string {\n return message.replace(EMAIL_ADDRESS, '<email>');\n}\n\n/** Errors that are not Studio bugs: browser quirks, aborted requests, browser extensions. */\nexport function isNoiseError(details: ErrorDetails, sourceUrl?: string): boolean {\n if (details.name === 'AbortError') {\n return true;\n }\n\n if (NOISE_MESSAGES.some((pattern) => pattern.test(details.message))) {\n return true;\n }\n\n if (sourceUrl && EXTENSION_URL.test(sourceUrl)) {\n return true;\n }\n\n return Boolean(details.stack && EXTENSION_URL.test(details.stack));\n}\n\nexport interface BuildClientErrorOptions {\n source: ClientErrorSource;\n componentStack?: string;\n path?: string;\n projectId?: string | null;\n /** The script the error came from (`ErrorEvent.filename`), checked for browser extensions. */\n sourceUrl?: string;\n now?: Date;\n}\n\n/** The report entry for an error, or null when it is noise. */\nexport function buildClientError(error: unknown, options: BuildClientErrorOptions): ClientError | null {\n const details = describeError(error);\n\n if (isNoiseError(details, options.sourceUrl)) {\n return null;\n }\n\n const entry: ClientError = {\n source: options.source,\n name: truncate(details.name, LIMITS.name),\n message: truncate(maskMessage(details.message), LIMITS.message),\n occurredAt: (options.now ?? new Date()).toISOString(),\n };\n\n if (details.stack) {\n entry.stack = truncate(details.stack, LIMITS.stack);\n }\n\n if (options.componentStack) {\n entry.componentStack = truncate(options.componentStack, LIMITS.componentStack);\n }\n\n if (options.path) {\n entry.path = toReportPath(options.path);\n }\n\n if (options.projectId && PROJECT_ID_PATTERN.test(options.projectId)) {\n entry.projectId = options.projectId;\n }\n\n return entry;\n}\n\n/** Identity of an error within a page session: the same message and stack are reported once. */\nexport function errorKey(error: Pick<ClientError, 'message' | 'name' | 'stack'>): string {\n return `${error.name}\\n${error.message}\\n${error.stack ?? ''}`;\n}\n\nconst encoder = new TextEncoder();\n\nfunction byteLength(value: string): number {\n return encoder.encode(value).length;\n}\n\n/**\n * Takes the errors that fit one report (at most 10 and `maxBytes` of JSON)\n * off the front of the queue. Returns the request body and how many errors it holds.\n */\nexport function buildReportBody(\n app: ClientErrorApp,\n queue: readonly ClientError[],\n maxBytes = MAX_REPORT_BYTES\n): { body: string; count: number } | null {\n // The envelope plus each error once, joined by commas.\n let size = byteLength(JSON.stringify({ app, errors: [] } satisfies ClientErrorReport));\n const errors: ClientError[] = [];\n\n for (const error of queue.slice(0, MAX_ERRORS_PER_REPORT)) {\n const errorSize = byteLength(JSON.stringify(error)) + (errors.length ? 1 : 0);\n\n if (size + errorSize > maxBytes) {\n break;\n }\n\n size += errorSize;\n errors.push(error);\n }\n\n if (errors.length === 0) {\n return null;\n }\n\n return { body: JSON.stringify({ app, errors } satisfies ClientErrorReport), count: errors.length };\n}\n\nexport type SendReport = (body: string, options: { unloading: boolean }) => Promise<number | null>;\n\nexport interface ErrorReporterOptions {\n app: ClientErrorApp;\n send: SendReport;\n /** The current Studio path; only its pathname is sent. */\n getPath?: () => string | undefined;\n now?: () => Date;\n setTimer?: (callback: () => void, ms: number) => unknown;\n clearTimer?: (timer: unknown) => void;\n}\n\nexport interface ErrorReporter {\n report: (error: unknown, options: Omit<BuildClientErrorOptions, 'path' | 'projectId' | 'now'>) => void;\n setProjectId: (projectId: string | null) => void;\n /** Sends the next report now; `unloading` uses a beacon or keepalive request that outlives the page. */\n flush: (options?: { unloading?: boolean }) => void;\n /** Errors waiting to be sent (tests). */\n pending: () => readonly ClientError[];\n dispose: () => void;\n}\n\n/** The queue, dedupe, cap and batching; the transport and the clock are injected. */\nexport function createErrorReporter({\n app,\n send,\n getPath,\n now = () => new Date(),\n setTimer = (callback, ms) => setTimeout(callback, ms),\n clearTimer = (timer) => clearTimeout(timer as ReturnType<typeof setTimeout>),\n}: ErrorReporterOptions): ErrorReporter {\n const queue: ClientError[] = [];\n const seen = new Set<string>();\n let accepted = 0;\n let projectId: string | null = null;\n let timer: unknown = null;\n let stopped = false;\n\n function schedule(): void {\n if (timer === null && queue.length > 0 && !stopped) {\n timer = setTimer(() => {\n timer = null;\n flush();\n }, FLUSH_INTERVAL_MS);\n }\n }\n\n function sendNext(unloading: boolean): boolean {\n const next = buildReportBody(app, queue);\n\n if (!next) {\n // An error that cannot fit a report on its own; drop it.\n queue.shift();\n\n return queue.length > 0;\n }\n\n queue.splice(0, next.count);\n send(next.body, { unloading })\n .then((status) => {\n // Rate limited or not allowed: stop for this page session rather than retry.\n if (status === 401 || status === 403 || status === 429) {\n stopped = true;\n queue.length = 0;\n }\n })\n .catch(() => {\n // Never report the reporter's own failures.\n });\n\n return queue.length > 0;\n }\n\n function flush({ unloading = false }: { unloading?: boolean } = {}): void {\n try {\n if (stopped) {\n return;\n }\n\n if (timer !== null && unloading) {\n clearTimer(timer);\n timer = null;\n }\n\n // One report per flush, also when the page goes away: beacons and\n // keepalive requests share a 64 KB budget, so a second would be refused.\n if (queue.length > 0) {\n sendNext(unloading);\n }\n\n schedule();\n } catch {\n // Error reporting must never break the Studio.\n }\n }\n\n return {\n report(error, options) {\n try {\n if (stopped || accepted >= MAX_ERRORS_PER_SESSION) {\n return;\n }\n\n const entry = buildClientError(error, {\n ...options,\n now: now(),\n path: getPath?.(),\n projectId,\n });\n\n if (!entry) {\n return;\n }\n\n const key = errorKey(entry);\n\n if (seen.has(key)) {\n return;\n }\n\n seen.add(key);\n accepted += 1;\n queue.push(entry);\n schedule();\n } catch {\n // Error reporting must never break the Studio.\n }\n },\n setProjectId(id) {\n projectId = id;\n },\n flush,\n pending: () => queue,\n dispose() {\n if (timer !== null) {\n clearTimer(timer);\n timer = null;\n }\n\n stopped = true;\n queue.length = 0;\n },\n };\n}\n\n/** Sends a report through the BFF; a beacon when the page is going away on the web. */\nexport const sendReportToBff: SendReport = async (body, { unloading }) => {\n const url = userApiPaths.clientErrors;\n\n // A beacon outlives the page. The BFF reads its JSON body like a fetch's\n // and the browser sends the session cookie with it (same origin). The\n // desktop app's BFF only answers script requests, so it uses `keepalive`.\n if (unloading && !getDesktop() && typeof navigator !== 'undefined' && typeof navigator.sendBeacon === 'function') {\n try {\n // text/plain is CORS-safelisted, so no browser refuses the beacon; the body is still JSON.\n if (navigator.sendBeacon(url, new Blob([body], { type: 'text/plain' }))) {\n return null;\n }\n } catch {\n // Fall back to a keepalive fetch.\n }\n }\n\n return postToUserApi(url, body, { keepalive: unloading });\n};\n\nlet installed: ErrorReporter | null = null;\n\n/** Reports an error caught by the Studio (an error boundary, for example). Does nothing when reporting is off. */\nexport function reportStudioError(\n error: unknown,\n { source = 'manual', componentStack }: { source?: ClientErrorSource; componentStack?: string } = {}\n): void {\n installed?.report(error, { source, componentStack });\n}\n\n/** The project the Studio shows, added to reports; null outside a project. */\nexport function setErrorReportingProjectId(projectId: string | null): void {\n installed?.setProjectId(projectId);\n}\n\n/**\n * Starts reporting uncaught errors and unhandled rejections when reporting is\n * enabled for this environment. Returns the function that stops it.\n */\nexport function installErrorReporter({ hosted }: { hosted: boolean }): () => void {\n if (typeof window === 'undefined' || installed) {\n return () => undefined;\n }\n\n if (!isStudioTelemetryEnabled({ hosted })) {\n return () => undefined;\n }\n\n const desktop = getDesktop();\n\n const reporter = createErrorReporter({\n app: {\n platform: desktop ? 'desktop' : 'web',\n version: STUDIO_VERSION,\n userAgent: truncate(navigator.userAgent, LIMITS.userAgent),\n },\n send: sendReportToBff,\n getPath: () => window.location.pathname,\n });\n\n function onError(event: ErrorEvent): void {\n reporter.report(event.error ?? event.message, { source: 'window', sourceUrl: event.filename });\n }\n\n function onUnhandledRejection(event: PromiseRejectionEvent): void {\n reporter.report(event.reason, { source: 'unhandledrejection' });\n }\n\n function onPageHide(): void {\n reporter.flush({ unloading: true });\n }\n\n window.addEventListener('error', onError);\n window.addEventListener('unhandledrejection', onUnhandledRejection);\n window.addEventListener('pagehide', onPageHide);\n installed = reporter;\n\n return () => {\n window.removeEventListener('error', onError);\n window.removeEventListener('unhandledrejection', onUnhandledRejection);\n window.removeEventListener('pagehide', onPageHide);\n reporter.flush({ unloading: true });\n reporter.dispose();\n\n if (installed === reporter) {\n installed = null;\n }\n };\n}\n","import { userApiPaths } from '../api-paths';\nimport { getDesktop } from '../desktop';\nimport { PROJECT_ID_PATTERN } from '../error/error-reporter';\nimport { isStudioTelemetryEnabled, postToUserApi } from '../telemetry';\n\n/**\n * Product events only the Studio can see, sent to Flexkit through the\n * Studio's own server proxy (`/api/flexkit/-/product-events`) with the\n * session: the Graph app opened, the desktop app launched. They follow the\n * Studio's telemetry setting (see core/telemetry.ts) and carry ids, the\n * desktop app version and the OS only.\n */\nexport type StudioProductEvent =\n | { event: 'graph_opened'; projectId: string }\n | { event: 'desktop_app_opened'; appVersion: string; os: 'darwin' | 'linux' | 'win32' };\n\n/** Identity of an event within a page session; the backend also counts each once per day. */\nexport function productEventKey(studioEvent: StudioProductEvent): string {\n return studioEvent.event === 'graph_opened' ? `graph_opened:${studioEvent.projectId}` : studioEvent.event;\n}\n\n/** Sends the event body; resolves with the response status. */\nexport type SendProductEvent = (body: string) => Promise<number>;\n\nexport interface ProductEventTracker {\n track: (studioEvent: StudioProductEvent, options?: { onDelivered?: () => void }) => void;\n}\n\n/**\n * Sends each event once per page session through `send`. An event counts as\n * sent only once the backend accepted it, so one sent while offline or signed\n * out is sent again next time. Never throws.\n */\nexport function createProductEventTracker(send: SendProductEvent): ProductEventTracker {\n const pending = new Set<string>();\n const delivered = new Set<string>();\n\n return {\n track(studioEvent, { onDelivered } = {}) {\n const key = productEventKey(studioEvent);\n\n if (pending.has(key) || delivered.has(key)) {\n return;\n }\n\n pending.add(key);\n\n const settle = (status: number | null): void => {\n pending.delete(key);\n\n if (status !== null && status >= 200 && status < 300) {\n delivered.add(key);\n onDelivered?.();\n }\n };\n\n try {\n send(JSON.stringify(studioEvent)).then(settle, () => settle(null));\n } catch {\n settle(null);\n }\n },\n };\n}\n\nlet tracker: ProductEventTracker | null = null;\n\n/** Records an event when product events are on (see `installProductEvents`); otherwise does nothing. */\nexport function trackStudioEvent(studioEvent: StudioProductEvent): void {\n if (studioEvent.event === 'graph_opened' && !PROJECT_ID_PATTERN.test(studioEvent.projectId)) {\n return;\n }\n\n tracker?.track(studioEvent);\n}\n\n/** Session storage flag: this desktop app launch was recorded (page reloads keep it, a relaunch does not). */\nexport const DESKTOP_LAUNCH_STORAGE_KEY = 'flexkit:desktop-launch-recorded';\n\nfunction readSessionFlag(key: string): boolean {\n try {\n return sessionStorage.getItem(key) === '1';\n } catch {\n return false;\n }\n}\n\nfunction writeSessionFlag(key: string): void {\n try {\n sessionStorage.setItem(key, '1');\n } catch {\n // Without session storage the backend's once-per-day count still applies.\n }\n}\n\n/**\n * Turns product events on for this environment and records the desktop app\n * launch (once per launch, once the user is signed in). Returns the function\n * that turns them off again.\n */\nexport function installProductEvents({ hosted }: { hosted: boolean }): () => void {\n if (!isStudioTelemetryEnabled({ hosted })) {\n return () => undefined;\n }\n\n const current = createProductEventTracker((body) =>\n postToUserApi(userApiPaths.productEvents, body, { keepalive: true })\n );\n const desktop = getDesktop();\n\n tracker = current;\n\n if (desktop && !readSessionFlag(DESKTOP_LAUNCH_STORAGE_KEY)) {\n current.track(\n { appVersion: desktop.version, event: 'desktop_app_opened', os: desktop.platform },\n { onDelivered: () => writeSessionFlag(DESKTOP_LAUNCH_STORAGE_KEY) }\n );\n }\n\n return () => {\n if (tracker === current) {\n tracker = null;\n }\n };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/core/use-studio-version.ts","../src/core/telemetry.ts","../src/core/error/error-reporter.ts","../src/core/analytics/product-events.ts"],"names":["STUDIO_VERSION","WEB_VERSION","useStudioVersion","desktop","getDesktop","downloaded","setDownloaded","useState","useEffect","update","TELEMETRY_STORAGE_KEY","LEGACY_TELEMETRY_STORAGE_KEY","LOCAL_HOSTNAME","isTelemetryEnabled","env","readOverride","storage","getLocalStorage","isStudioTelemetryEnabled","hosted","flexkitDomain","postToUserApi","path","body","keepalive","LIMITS","MAX_ERRORS_PER_REPORT","MAX_REPORT_BYTES","MAX_ERRORS_PER_SESSION","FLUSH_INTERVAL_MS","PROJECT_ID_PATTERN","truncate","value","max","toReportPath","pathOrUrl","describeError","error","constructorName","NOISE_MESSAGES","EXTENSION_URL","EMAIL_ADDRESS","maskMessage","message","isNoiseError","details","sourceUrl","pattern","buildClientError","options","entry","errorKey","encoder","byteLength","buildReportBody","app","queue","maxBytes","size","errors","errorSize","createErrorReporter","send","getPath","now","setTimer","callback","ms","clearTimer","timer","seen","accepted","projectId","stopped","schedule","flush","sendNext","unloading","next","status","key","id","sendReportToBff","url","userApiPaths","installed","reportStudioError","source","componentStack","setErrorReportingProjectId","installErrorReporter","reporter","onError","event","onUnhandledRejection","onPageHide","productEventKey","studioEvent","createProductEventTracker","pending","delivered","onDelivered","settle","tracker","trackStudioEvent","DESKTOP_LAUNCH_STORAGE_KEY","readSessionFlag","writeSessionFlag","installProductEvents","current"],"mappings":"gLAeO,IAAMA,CAAAA,CAA0D,QAAA,CACjEC,CAAAA,CAA6B,CAAE,OAAA,CAASD,CAAAA,CAAgB,MAAA,CAAQA,CAAAA,CAAgB,SAAA,CAAW,IAAK,CAAA,CAO/F,SAASE,EAAAA,EAAkC,CAChD,IAAMC,CAAAA,CAAUC,CAAAA,EAAW,CACrB,CAACC,CAAAA,CAAYC,CAAa,CAAA,CAAIC,SAAwB,IAAI,CAAA,CAYhE,OAVAC,SAAAA,CAAU,IAAM,CACd,GAAKL,CAAAA,CAIL,OAAOA,CAAAA,CAAQ,kBAAA,CAAoBM,CAAAA,EAAW,CAC5CH,CAAAA,CAAcG,CAAAA,CAAO,OAAO,EAC9B,CAAC,CACH,CAAA,CAAG,CAACN,CAAO,CAAC,CAAA,CAEPA,CAAAA,CAIDE,CAAAA,GAAe,IAAA,CACV,CAAE,OAAA,CAASF,CAAAA,CAAQ,OAAA,C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ChF,GAAI,CAACD,EAAyB,CAAE,MAAA,CAAAC,CAAO,CAAC,CAAA,CACtC,OAAO,IAAG,CAAA,CAAA,CAGZ,IAAM0F,EAAUX,EAAAA,CAA2B3E,CAAAA,EACzCF,EAAc+D,CAAAA,CAAa,aAAA,CAAe7D,EAAM,CAAE,SAAA,CAAW,IAAK,CAAC,CACrE,CAAA,CACMpB,EAAUC,CAAAA,EAAW,CAE3B,OAAAmG,CAAAA,CAAUM,CAAAA,CAEN1G,GAAW,CAACuG,EAAAA,CAAgBD,CAA0B,CAAA,EACxDI,CAAAA,CAAQ,KAAA,CACN,CAAE,UAAA,CAAY1G,CAAAA,CAAQ,QAAS,KAAA,CAAO,oBAAA,CAAsB,GAAIA,CAAAA,CAAQ,QAAS,CAAA,CACjF,CAAE,WAAA,CAAa,IAAMwG,GAAiBF,CAA0B,CAAE,CACpE,CAAA,CAGK,IAAM,CACPF,CAAAA,GAAYM,CAAAA,GACdN,CAAAA,CAAU,IAAA,EAEd,CACF","file":"chunk-KVYQ3O4F.js","sourcesContent":["'use client';\n\nimport { useEffect, useState } from 'react';\nimport { getDesktop } from './desktop';\n\nexport interface StudioVersion {\n current: string;\n latest: string;\n isCurrent: boolean;\n /** Applies the newer version (the desktop app restarts into it); undefined when there is nothing to apply. */\n upgrade?: () => void;\n}\n\n// `@flexkit/studio`'s own version, inlined at build time; a build without the\n// define (tests, tooling) shows a placeholder.\nexport const STUDIO_VERSION = typeof __STUDIO_VERSION__ === 'string' ? __STUDIO_VERSION__ : '0.0.0';\nconst WEB_VERSION: StudioVersion = { current: STUDIO_VERSION, latest: STUDIO_VERSION, isCurrent: true };\n\n/**\n * The Studio version shown in the app bar. The web Studio is always current\n * (the hosted Studio deploys with the packages); the desktop app reports its\n * own version and the update it has downloaded, if any.\n */\nexport function useStudioVersion(): StudioVersion {\n const desktop = getDesktop();\n const [downloaded, setDownloaded] = useState<string | null>(null);\n\n useEffect(() => {\n if (!desktop) {\n return;\n }\n\n return desktop.onUpdateDownloaded((update) => {\n setDownloaded(update.version);\n });\n }, [desktop]);\n\n if (!desktop) {\n return WEB_VERSION;\n }\n\n if (downloaded === null) {\n return { current: desktop.version, latest: desktop.version, isCurrent: true };\n }\n\n return { current: desktop.version, latest: downloaded, isCurrent: false, upgrade: () => desktop.installUpdate() };\n}\n","import { getDesktop } from './desktop';\nimport { flexkitDomain } from './domains';\nimport { getLocalStorage } from './local-storage';\nimport { STUDIO_VERSION } from './use-studio-version';\n\n/**\n * The on/off decision and the transport shared by the Studio's error reports\n * (core/error/error-reporter.ts) and product events\n * (core/analytics/product-events.ts).\n */\n\n/** Turns error reports and product events on (`on`) or off (`off`) in this browser, whatever the environment. */\nexport const TELEMETRY_STORAGE_KEY = 'flexkit:telemetry';\n/** The key error reporting shipped with; still honoured. */\nexport const LEGACY_TELEMETRY_STORAGE_KEY = 'flexkit:error-reporting';\n\nexport interface TelemetryEnvironment {\n /** The Studio lists the signed-in user's projects (hosted Studio, desktop app). */\n hosted: boolean;\n isDesktop: boolean;\n domain: string;\n hostname: string;\n version: string;\n /** The local storage setting in this browser, if any. */\n override: string | null;\n}\n\nconst LOCAL_HOSTNAME = /^(localhost|127\\.0\\.0\\.1|\\[::1\\]|0\\.0\\.0\\.0)$|\\.(localhost|test|local)$/i;\n\n/**\n * On for the hosted Studio and the desktop app against the production\n * backend, and off in development: a local backend (`flexkit.test`), a local\n * host, or a build without a version. The local storage setting forces it\n * `on` or `off`.\n */\nexport function isTelemetryEnabled(env: TelemetryEnvironment): boolean {\n if (env.override === 'on') {\n return true;\n }\n\n if (env.override === 'off') {\n return false;\n }\n\n if (!env.hosted || env.domain !== 'flexkit.io' || env.version === '0.0.0') {\n return false;\n }\n\n return env.isDesktop || !LOCAL_HOSTNAME.test(env.hostname);\n}\n\nfunction readOverride(): string | null {\n try {\n const storage = getLocalStorage();\n\n return storage?.getItem(TELEMETRY_STORAGE_KEY) ?? storage?.getItem(LEGACY_TELEMETRY_STORAGE_KEY) ?? null;\n } catch {\n return null;\n }\n}\n\n/** Whether this Studio sends error reports and product events to Flexkit. */\nexport function isStudioTelemetryEnabled({ hosted }: { hosted: boolean }): boolean {\n if (typeof window === 'undefined') {\n return false;\n }\n\n return isTelemetryEnabled({\n hosted,\n isDesktop: Boolean(getDesktop()),\n domain: flexkitDomain,\n hostname: window.location.hostname,\n version: STUDIO_VERSION,\n override: readOverride(),\n });\n}\n\n/**\n * POSTs JSON to a user-level backend route through the Studio's server proxy,\n * which adds the session. `keepalive` lets the request outlive the page.\n * Returns the response status.\n */\nexport async function postToUserApi(path: string, body: string, { keepalive = false } = {}): Promise<number> {\n const response = await fetch(path, {\n body,\n credentials: 'same-origin',\n headers: { 'Content-Type': 'application/json' },\n keepalive,\n method: 'POST',\n });\n\n return response.status;\n}\n","import { userApiPaths } from '../api-paths';\nimport { getDesktop } from '../desktop';\nimport { STUDIO_VERSION } from '../use-studio-version';\nimport { isStudioTelemetryEnabled, postToUserApi } from '../telemetry';\n\n/**\n * Reports unexpected Studio errors (uncaught errors, unhandled rejections and\n * errors caught by the error boundaries) to Flexkit through the Studio's own\n * BFF (`/api/flexkit/-/client-errors`), which forwards the session so the\n * report is attributed to the signed-in user.\n *\n * Reports carry the error, the Studio path (no query string or hash) and the\n * current project id; never request bodies, form values or record data.\n */\n\nexport type ClientErrorSource = 'window' | 'unhandledrejection' | 'react' | 'manual';\n\nexport interface ClientError {\n source: ClientErrorSource;\n name: string;\n message: string;\n stack?: string;\n componentStack?: string;\n path?: string;\n projectId?: string;\n occurredAt: string;\n}\n\nexport interface ClientErrorApp {\n platform: 'web' | 'desktop';\n version: string;\n userAgent?: string;\n}\n\nexport interface ClientErrorReport {\n app: ClientErrorApp;\n errors: ClientError[];\n}\n\n/** Field limits of the backend schema. */\nconst LIMITS = {\n componentStack: 4_000,\n message: 2_000,\n name: 200,\n path: 500,\n stack: 8_000,\n userAgent: 500,\n} as const;\n\n/** The backend accepts 1 to 10 errors per report. */\nexport const MAX_ERRORS_PER_REPORT = 10;\n/** The backend refuses bodies over 64 KB; `keepalive` requests share a 64 KB budget too. */\nexport const MAX_REPORT_BYTES = 60_000;\n/** Reports kept per page session; anything after that is dropped. */\nexport const MAX_ERRORS_PER_SESSION = 50;\n/** At most one report is sent per interval; errors in between are batched. */\nexport const FLUSH_INTERVAL_MS = 5_000;\n\n/** Kept for callers and tests that name the gate after error reporting. */\nexport {\n isTelemetryEnabled as isErrorReportingEnabled,\n LEGACY_TELEMETRY_STORAGE_KEY as ERROR_REPORTING_STORAGE_KEY,\n type TelemetryEnvironment as ErrorReportingEnvironment,\n} from '../telemetry';\n\nexport const PROJECT_ID_PATTERN = /^[a-z0-9]{1,64}$/;\n\nfunction truncate(value: string, max: number): string {\n return value.length > max ? value.slice(0, max) : value;\n}\n\n/** The pathname of a path or URL, without query string or hash. */\nexport function toReportPath(pathOrUrl: string): string {\n let path = pathOrUrl;\n\n try {\n if (/^[a-z][a-z0-9+.-]*:/i.test(pathOrUrl)) {\n path = new URL(pathOrUrl).pathname;\n }\n } catch {\n // Not a URL; strip by hand below.\n }\n\n return truncate(path.split(/[?#]/)[0] ?? '', LIMITS.path);\n}\n\nexport interface ErrorDetails {\n name: string;\n message: string;\n stack?: string;\n}\n\n/**\n * Name, message and stack of anything thrown. A non-Error value (a rejected\n * promise with a plain object) is described by its type only, so record data\n * someone rejected with never leaves the browser.\n */\nexport function describeError(error: unknown): ErrorDetails {\n if (error instanceof Error) {\n return {\n name: error.name || 'Error',\n message: typeof error.message === 'string' ? error.message : '',\n stack: typeof error.stack === 'string' ? error.stack : undefined,\n };\n }\n\n if (typeof error === 'string') {\n return { name: 'Error', message: error };\n }\n\n if (error === null || error === undefined) {\n return { name: 'Error', message: `Non-Error thrown: ${String(error)}` };\n }\n\n if (typeof error === 'object') {\n const constructorName = (error as { constructor?: { name?: unknown } }).constructor?.name;\n\n return {\n name: 'Error',\n message: `Non-Error thrown: ${typeof constructorName === 'string' && constructorName ? constructorName : 'object'}`,\n };\n }\n\n return { name: 'Error', message: `Non-Error thrown: ${typeof error}` };\n}\n\nconst NOISE_MESSAGES = [\n /ResizeObserver loop (limit exceeded|completed with undelivered notifications)/i,\n // Cross-origin script errors carry nothing to act on.\n /^Script error\\.?$/i,\n /The (operation|user) (was )?aborted/i,\n /signal is aborted without reason/i,\n];\n\nconst EXTENSION_URL = /\\b(chrome|moz|safari(-web)?|ms-browser)-extension:\\/\\//i;\n\nconst EMAIL_ADDRESS = /[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,}/gi;\n\n/** Masks email addresses an error message may quote from a record or form. */\nexport function maskMessage(message: string): string {\n return message.replace(EMAIL_ADDRESS, '<email>');\n}\n\n/** Errors that are not Studio bugs: browser quirks, aborted requests, browser extensions. */\nexport function isNoiseError(details: ErrorDetails, sourceUrl?: string): boolean {\n if (details.name === 'AbortError') {\n return true;\n }\n\n if (NOISE_MESSAGES.some((pattern) => pattern.test(details.message))) {\n return true;\n }\n\n if (sourceUrl && EXTENSION_URL.test(sourceUrl)) {\n return true;\n }\n\n return Boolean(details.stack && EXTENSION_URL.test(details.stack));\n}\n\nexport interface BuildClientErrorOptions {\n source: ClientErrorSource;\n componentStack?: string;\n path?: string;\n projectId?: string | null;\n /** The script the error came from (`ErrorEvent.filename`), checked for browser extensions. */\n sourceUrl?: string;\n now?: Date;\n}\n\n/** The report entry for an error, or null when it is noise. */\nexport function buildClientError(error: unknown, options: BuildClientErrorOptions): ClientError | null {\n const details = describeError(error);\n\n if (isNoiseError(details, options.sourceUrl)) {\n return null;\n }\n\n const entry: ClientError = {\n source: options.source,\n name: truncate(details.name, LIMITS.name),\n message: truncate(maskMessage(details.message), LIMITS.message),\n occurredAt: (options.now ?? new Date()).toISOString(),\n };\n\n if (details.stack) {\n entry.stack = truncate(details.stack, LIMITS.stack);\n }\n\n if (options.componentStack) {\n entry.componentStack = truncate(options.componentStack, LIMITS.componentStack);\n }\n\n if (options.path) {\n entry.path = toReportPath(options.path);\n }\n\n if (options.projectId && PROJECT_ID_PATTERN.test(options.projectId)) {\n entry.projectId = options.projectId;\n }\n\n return entry;\n}\n\n/** Identity of an error within a page session: the same message and stack are reported once. */\nexport function errorKey(error: Pick<ClientError, 'message' | 'name' | 'stack'>): string {\n return `${error.name}\\n${error.message}\\n${error.stack ?? ''}`;\n}\n\nconst encoder = new TextEncoder();\n\nfunction byteLength(value: string): number {\n return encoder.encode(value).length;\n}\n\n/**\n * Takes the errors that fit one report (at most 10 and `maxBytes` of JSON)\n * off the front of the queue. Returns the request body and how many errors it holds.\n */\nexport function buildReportBody(\n app: ClientErrorApp,\n queue: readonly ClientError[],\n maxBytes = MAX_REPORT_BYTES\n): { body: string; count: number } | null {\n // The envelope plus each error once, joined by commas.\n let size = byteLength(JSON.stringify({ app, errors: [] } satisfies ClientErrorReport));\n const errors: ClientError[] = [];\n\n for (const error of queue.slice(0, MAX_ERRORS_PER_REPORT)) {\n const errorSize = byteLength(JSON.stringify(error)) + (errors.length ? 1 : 0);\n\n if (size + errorSize > maxBytes) {\n break;\n }\n\n size += errorSize;\n errors.push(error);\n }\n\n if (errors.length === 0) {\n return null;\n }\n\n return { body: JSON.stringify({ app, errors } satisfies ClientErrorReport), count: errors.length };\n}\n\nexport type SendReport = (body: string, options: { unloading: boolean }) => Promise<number | null>;\n\nexport interface ErrorReporterOptions {\n app: ClientErrorApp;\n send: SendReport;\n /** The current Studio path; only its pathname is sent. */\n getPath?: () => string | undefined;\n now?: () => Date;\n setTimer?: (callback: () => void, ms: number) => unknown;\n clearTimer?: (timer: unknown) => void;\n}\n\nexport interface ErrorReporter {\n report: (error: unknown, options: Omit<BuildClientErrorOptions, 'path' | 'projectId' | 'now'>) => void;\n setProjectId: (projectId: string | null) => void;\n /** Sends the next report now; `unloading` uses a beacon or keepalive request that outlives the page. */\n flush: (options?: { unloading?: boolean }) => void;\n /** Errors waiting to be sent (tests). */\n pending: () => readonly ClientError[];\n dispose: () => void;\n}\n\n/** The queue, dedupe, cap and batching; the transport and the clock are injected. */\nexport function createErrorReporter({\n app,\n send,\n getPath,\n now = () => new Date(),\n setTimer = (callback, ms) => setTimeout(callback, ms),\n clearTimer = (timer) => clearTimeout(timer as ReturnType<typeof setTimeout>),\n}: ErrorReporterOptions): ErrorReporter {\n const queue: ClientError[] = [];\n const seen = new Set<string>();\n let accepted = 0;\n let projectId: string | null = null;\n let timer: unknown = null;\n let stopped = false;\n\n function schedule(): void {\n if (timer === null && queue.length > 0 && !stopped) {\n timer = setTimer(() => {\n timer = null;\n flush();\n }, FLUSH_INTERVAL_MS);\n }\n }\n\n function sendNext(unloading: boolean): boolean {\n const next = buildReportBody(app, queue);\n\n if (!next) {\n // An error that cannot fit a report on its own; drop it.\n queue.shift();\n\n return queue.length > 0;\n }\n\n queue.splice(0, next.count);\n send(next.body, { unloading })\n .then((status) => {\n // Rate limited or not allowed: stop for this page session rather than retry.\n if (status === 401 || status === 403 || status === 429) {\n stopped = true;\n queue.length = 0;\n }\n })\n .catch(() => {\n // Never report the reporter's own failures.\n });\n\n return queue.length > 0;\n }\n\n function flush({ unloading = false }: { unloading?: boolean } = {}): void {\n try {\n if (stopped) {\n return;\n }\n\n if (timer !== null && unloading) {\n clearTimer(timer);\n timer = null;\n }\n\n // One report per flush, also when the page goes away: beacons and\n // keepalive requests share a 64 KB budget, so a second would be refused.\n if (queue.length > 0) {\n sendNext(unloading);\n }\n\n schedule();\n } catch {\n // Error reporting must never break the Studio.\n }\n }\n\n return {\n report(error, options) {\n try {\n if (stopped || accepted >= MAX_ERRORS_PER_SESSION) {\n return;\n }\n\n const entry = buildClientError(error, {\n ...options,\n now: now(),\n path: getPath?.(),\n projectId,\n });\n\n if (!entry) {\n return;\n }\n\n const key = errorKey(entry);\n\n if (seen.has(key)) {\n return;\n }\n\n seen.add(key);\n accepted += 1;\n queue.push(entry);\n schedule();\n } catch {\n // Error reporting must never break the Studio.\n }\n },\n setProjectId(id) {\n projectId = id;\n },\n flush,\n pending: () => queue,\n dispose() {\n if (timer !== null) {\n clearTimer(timer);\n timer = null;\n }\n\n stopped = true;\n queue.length = 0;\n },\n };\n}\n\n/** Sends a report through the BFF; a beacon when the page is going away on the web. */\nexport const sendReportToBff: SendReport = async (body, { unloading }) => {\n const url = userApiPaths.clientErrors;\n\n // A beacon outlives the page. The BFF reads its JSON body like a fetch's\n // and the browser sends the session cookie with it (same origin). The\n // desktop app's BFF only answers script requests, so it uses `keepalive`.\n if (unloading && !getDesktop() && typeof navigator !== 'undefined' && typeof navigator.sendBeacon === 'function') {\n try {\n // text/plain is CORS-safelisted, so no browser refuses the beacon; the body is still JSON.\n if (navigator.sendBeacon(url, new Blob([body], { type: 'text/plain' }))) {\n return null;\n }\n } catch {\n // Fall back to a keepalive fetch.\n }\n }\n\n return postToUserApi(url, body, { keepalive: unloading });\n};\n\nlet installed: ErrorReporter | null = null;\n\n/** Reports an error caught by the Studio (an error boundary, for example). Does nothing when reporting is off. */\nexport function reportStudioError(\n error: unknown,\n { source = 'manual', componentStack }: { source?: ClientErrorSource; componentStack?: string } = {}\n): void {\n installed?.report(error, { source, componentStack });\n}\n\n/** The project the Studio shows, added to reports; null outside a project. */\nexport function setErrorReportingProjectId(projectId: string | null): void {\n installed?.setProjectId(projectId);\n}\n\n/**\n * Starts reporting uncaught errors and unhandled rejections when reporting is\n * enabled for this environment. Returns the function that stops it.\n */\nexport function installErrorReporter({ hosted }: { hosted: boolean }): () => void {\n if (typeof window === 'undefined' || installed) {\n return () => undefined;\n }\n\n if (!isStudioTelemetryEnabled({ hosted })) {\n return () => undefined;\n }\n\n const desktop = getDesktop();\n\n const reporter = createErrorReporter({\n app: {\n platform: desktop ? 'desktop' : 'web',\n version: STUDIO_VERSION,\n userAgent: truncate(navigator.userAgent, LIMITS.userAgent),\n },\n send: sendReportToBff,\n getPath: () => window.location.pathname,\n });\n\n function onError(event: ErrorEvent): void {\n reporter.report(event.error ?? event.message, { source: 'window', sourceUrl: event.filename });\n }\n\n function onUnhandledRejection(event: PromiseRejectionEvent): void {\n reporter.report(event.reason, { source: 'unhandledrejection' });\n }\n\n function onPageHide(): void {\n reporter.flush({ unloading: true });\n }\n\n window.addEventListener('error', onError);\n window.addEventListener('unhandledrejection', onUnhandledRejection);\n window.addEventListener('pagehide', onPageHide);\n installed = reporter;\n\n return () => {\n window.removeEventListener('error', onError);\n window.removeEventListener('unhandledrejection', onUnhandledRejection);\n window.removeEventListener('pagehide', onPageHide);\n reporter.flush({ unloading: true });\n reporter.dispose();\n\n if (installed === reporter) {\n installed = null;\n }\n };\n}\n","import { userApiPaths } from '../api-paths';\nimport { getDesktop } from '../desktop';\nimport { PROJECT_ID_PATTERN } from '../error/error-reporter';\nimport { isStudioTelemetryEnabled, postToUserApi } from '../telemetry';\n\n/**\n * Product events only the Studio can see, sent to Flexkit through the\n * Studio's own server proxy (`/api/flexkit/-/product-events`) with the\n * session: the Graph app opened, the desktop app launched. They follow the\n * Studio's telemetry setting (see core/telemetry.ts) and carry ids, the\n * desktop app version and the OS only.\n */\nexport type StudioProductEvent =\n | { event: 'graph_opened'; projectId: string }\n | { event: 'desktop_app_opened'; appVersion: string; os: 'darwin' | 'linux' | 'win32' };\n\n/** Identity of an event within a page session; the backend also counts each once per day. */\nexport function productEventKey(studioEvent: StudioProductEvent): string {\n return studioEvent.event === 'graph_opened' ? `graph_opened:${studioEvent.projectId}` : studioEvent.event;\n}\n\n/** Sends the event body; resolves with the response status. */\nexport type SendProductEvent = (body: string) => Promise<number>;\n\nexport interface ProductEventTracker {\n track: (studioEvent: StudioProductEvent, options?: { onDelivered?: () => void }) => void;\n}\n\n/**\n * Sends each event once per page session through `send`. An event counts as\n * sent only once the backend accepted it, so one sent while offline or signed\n * out is sent again next time. Never throws.\n */\nexport function createProductEventTracker(send: SendProductEvent): ProductEventTracker {\n const pending = new Set<string>();\n const delivered = new Set<string>();\n\n return {\n track(studioEvent, { onDelivered } = {}) {\n const key = productEventKey(studioEvent);\n\n if (pending.has(key) || delivered.has(key)) {\n return;\n }\n\n pending.add(key);\n\n const settle = (status: number | null): void => {\n pending.delete(key);\n\n if (status !== null && status >= 200 && status < 300) {\n delivered.add(key);\n onDelivered?.();\n }\n };\n\n try {\n send(JSON.stringify(studioEvent)).then(settle, () => settle(null));\n } catch {\n settle(null);\n }\n },\n };\n}\n\nlet tracker: ProductEventTracker | null = null;\n\n/** Records an event when product events are on (see `installProductEvents`); otherwise does nothing. */\nexport function trackStudioEvent(studioEvent: StudioProductEvent): void {\n if (studioEvent.event === 'graph_opened' && !PROJECT_ID_PATTERN.test(studioEvent.projectId)) {\n return;\n }\n\n tracker?.track(studioEvent);\n}\n\n/** Session storage flag: this desktop app launch was recorded (page reloads keep it, a relaunch does not). */\nexport const DESKTOP_LAUNCH_STORAGE_KEY = 'flexkit:desktop-launch-recorded';\n\nfunction readSessionFlag(key: string): boolean {\n try {\n return sessionStorage.getItem(key) === '1';\n } catch {\n return false;\n }\n}\n\nfunction writeSessionFlag(key: string): void {\n try {\n sessionStorage.setItem(key, '1');\n } catch {\n // Without session storage the backend's once-per-day count still applies.\n }\n}\n\n/**\n * Turns product events on for this environment and records the desktop app\n * launch (once per launch, once the user is signed in). Returns the function\n * that turns them off again.\n */\nexport function installProductEvents({ hosted }: { hosted: boolean }): () => void {\n if (!isStudioTelemetryEnabled({ hosted })) {\n return () => undefined;\n }\n\n const current = createProductEventTracker((body) =>\n postToUserApi(userApiPaths.productEvents, body, { keepalive: true })\n );\n const desktop = getDesktop();\n\n tracker = current;\n\n if (desktop && !readSessionFlag(DESKTOP_LAUNCH_STORAGE_KEY)) {\n current.track(\n { appVersion: desktop.version, event: 'desktop_app_opened', os: desktop.platform },\n { onDelivered: () => writeSessionFlag(DESKTOP_LAUNCH_STORAGE_KEY) }\n );\n }\n\n return () => {\n if (tracker === current) {\n tracker = null;\n }\n };\n}\n"]}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import'./index.css';import {a}from'./chunk-QSTWBKPN.js';import {d as d$3}from'./chunk-5LGIALCK.js';import {g,f as f$1,d}from'./chunk-U6VZY3V2.js';import {d as d$1,i as i$1,f as f$3,h as h$1}from'./chunk-
|
|
1
|
+
import'./index.css';import {a}from'./chunk-QSTWBKPN.js';import {d as d$3}from'./chunk-5LGIALCK.js';import {g,f as f$1,d}from'./chunk-U6VZY3V2.js';import {d as d$1,i as i$1,f as f$3,h as h$1}from'./chunk-6GXNHR6H.js';import {b as b$4}from'./chunk-V7C4EHK3.js';import {o,e as e$1}from'./chunk-7KLXWCDS.js';import {f,d as d$2}from'./chunk-XLFAJBPN.js';import {pa as pa$1,Pb,Sb,qb,Gc,Hc,Ic,qa as qa$1,o as o$1,la as la$1,va as va$1,s,$,aa as aa$1,da as da$1,ea as ea$1,ba as ba$1,fa as fa$1}from'./chunk-DGIY4SKN.js';import {t}from'./chunk-SZEGGBOC.js';import {b as b$1,c as c$1,h,i,k,l,j,f as f$2}from'./chunk-32ZU4MLE.js';import {b as b$2,c,e}from'./chunk-USNXQOMJ.js';import {b as b$3}from'./chunk-6NRQMG26.js';import {lazy,createContext,useCallback,useState,useRef,useEffect,useMemo,useContext,useTransition,useId,Suspense,useSyncExternalStore}from'react';import Ua,{useSWRConfig}from'swr';import {formatDistance,format}from'date-fns';import {RadarIcon,BotIcon,XIcon,PlugIcon,XCircleIcon,LoaderCircle,CheckIcon,CloudUploadIcon,FileTextIcon,DownloadIcon,LinkIcon,MessageSquareIcon,SendIcon,LibraryIcon,ChevronDownIcon,BookOpenIcon,CheckCircle2Icon,CircleSlashIcon,ShieldIcon,DatabaseZapIcon,MessageCircleQuestionIcon,ShieldCheckIcon,TriangleAlertIcon,PlayIcon,ArrowRightIcon,FileIcon,BookOpenTextIcon,CornerDownRightIcon,CircleAlertIcon,MoveRightIcon}from'lucide-react';import {Link,useNavigate}from'react-router-dom';import {jsx,jsxs,Fragment}from'react/jsx-runtime';import {pipeJsonRender}from'@json-render/core';import {readUIMessageStream,parseJsonEventStream,uiMessageChunkSchema}from'ai';function wt(){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 St(e,t){let n=e.split(`
|
|
2
2
|
`),a=t.split(`
|
|
3
|
-
`);if(n.length*a.length>25e5)return null;let s=a.length+1,r=new Uint32Array((n.length+1)*s);for(let f=n.length-1;f>=0;f--)for(let c=a.length-1;c>=0;c--)r[f*s+c]=n[f]===a[c]?r[(f+1)*s+c+1]+1:Math.max(r[(f+1)*s+c],r[f*s+c+1]);let i=[],d=0,u=0;for(;d<n.length&&u<a.length;)n[d]===a[u]?(i.push({kind:"same",text:n[d]}),d++,u++):r[(d+1)*s+u]>=r[d*s+u+1]?(i.push({kind:"removed",text:n[d]}),d++):(i.push({kind:"added",text:a[u]}),u++);for(;d<n.length;d++)i.push({kind:"removed",text:n[d]});for(;u<a.length;u++)i.push({kind:"added",text:a[u]});return i}var Ln=5e3,jn=150,Fe=new Set;function On(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 Fn(e,t,n=d$2){return !e||e.kind!=="schema"||e.status!=="approved"||e.error?false:e.executedAt?(n(t),false):true}function Ne({approvalId:e,approvalUrl:t,fetchApproval:n,projectId:a,revalidate:s=d$2,sleep:r=i=>new Promise(d=>setTimeout(d,i))}){let i=`${a}:${e}`,d=n??(t?On(t):null);!d||Fe.has(i)||(Fe.add(i),(async()=>{try{for(let u=0;u<jn;u+=1){let f=null;try{f=await d();}catch{f=null;}if(f==="missing"||f!==null&&!Fn(f,a,s))return;await r(Ln);}}finally{Fe.delete(i);}})());}var Kn=lazy(()=>import('./skills-pages-
|
|
3
|
+
`);if(n.length*a.length>25e5)return null;let s=a.length+1,r=new Uint32Array((n.length+1)*s);for(let f=n.length-1;f>=0;f--)for(let c=a.length-1;c>=0;c--)r[f*s+c]=n[f]===a[c]?r[(f+1)*s+c+1]+1:Math.max(r[(f+1)*s+c],r[f*s+c+1]);let i=[],d=0,u=0;for(;d<n.length&&u<a.length;)n[d]===a[u]?(i.push({kind:"same",text:n[d]}),d++,u++):r[(d+1)*s+u]>=r[d*s+u+1]?(i.push({kind:"removed",text:n[d]}),d++):(i.push({kind:"added",text:a[u]}),u++);for(;d<n.length;d++)i.push({kind:"removed",text:n[d]});for(;u<a.length;u++)i.push({kind:"added",text:a[u]});return i}var Ln=5e3,jn=150,Fe=new Set;function On(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 Fn(e,t,n=d$2){return !e||e.kind!=="schema"||e.status!=="approved"||e.error?false:e.executedAt?(n(t),false):true}function Ne({approvalId:e,approvalUrl:t,fetchApproval:n,projectId:a,revalidate:s=d$2,sleep:r=i=>new Promise(d=>setTimeout(d,i))}){let i=`${a}:${e}`,d=n??(t?On(t):null);!d||Fe.has(i)||(Fe.add(i),(async()=>{try{for(let u=0;u<jn;u+=1){let f=null;try{f=await d();}catch{f=null;}if(f==="missing"||f!==null&&!Fn(f,a,s))return;await r(Ln);}}finally{Fe.delete(i);}})());}var Kn=lazy(()=>import('./skills-pages-W47HECK3.js').then(e=>({default:e.SkillContentPane}))),Yn={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 Vn({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 ${Yn[e]}`,variant:"secondary",children:e})}function U(e){return e==null?"\u2014":typeof e=="object"?JSON.stringify(e):String(e)}function Tt({after:e,before:t}){let n=U(t),a=U(e);return n===a?jsx("span",{className:"fk:text-muted-foreground",children:n}):jsxs("span",{className:"fk:inline-flex fk:flex-wrap fk:items-center fk:gap-1.5",children:[jsx("span",{className:"fk:rounded fk:bg-destructive/10 fk:px-1 fk:text-destructive fk:line-through fk:corner-squircle",children:n}),jsx(MoveRightIcon,{className:"fk:size-3 fk:shrink-0 fk:text-muted-foreground"}),jsx("span",{className:"fk:rounded fk:bg-success/15 fk:px-1 fk:text-success fk:corner-squircle",children:a})]})}function Wn(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 Gn({operation:e}){if(e.rows.length===0)return null;let t=(e.contextColumns??[]).filter(a=>a!=="_id");if(e.kind==="delete")return jsxs($,{children:[jsx(aa$1,{children:jsxs(da$1,{children:[jsx(ea$1,{children:"Records to delete"}),t.map(a=>jsx(ea$1,{children:a},a))]})}),jsx(ba$1,{children:e.rows.map((a,s)=>jsxs(da$1,{className:"fk:bg-destructive/5",children:[jsx(fa$1,{className:"fk:font-mono fk:text-xs fk:text-destructive",children:a.id??U(a.before?._id)}),t.map(r=>jsx(fa$1,{className:"fk:text-xs fk:text-muted-foreground",children:U(a.before?.[r])},r))]},a.id??s.toString()))})]});let n=e.columns.filter(a=>a!=="_id"&&!t.includes(a));return jsxs($,{children:[jsx(aa$1,{children:jsxs(da$1,{children:[jsx(ea$1,{children:"ID"}),t.map(a=>jsx(ea$1,{children:a},a)),n.map(a=>jsx(ea$1,{children:a},a))]})}),jsx(ba$1,{children:e.rows.map((a,s)=>jsxs(da$1,{children:[jsx(fa$1,{className:"fk:font-mono fk:text-xs fk:text-muted-foreground",children:a.id??"\u2014"}),t.map(r=>jsx(fa$1,{className:"fk:max-w-72 fk:text-xs fk:text-muted-foreground",children:jsx("span",{className:"fk:line-clamp-3",children:U(a.before?.[r])})},r)),n.map(r=>jsx(fa$1,{className:"fk:text-xs",children:e.kind==="create"?jsx("span",{className:"fk:rounded fk:bg-success/15 fk:px-1 fk:text-success fk:corner-squircle",children:U(a.after?.[r])}):jsx(Tt,{after:a.after?.[r],before:a.before?.[r]})},r))]},a.id??s.toString()))})]})}function Zn({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 Dt(e){if(e.kind!=="plugin")return null;let n=e.operations[0]?.query.split(`
|
|
4
4
|
`)[0]?.trim()?.split("/"),a=n?.at(-1),s=n?.[0];if(!a||!s||n?.length<2)return null;let r=a.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").toLowerCase(),i=s.replace(/[_-]+/g," ").replace(/\b\w/g,c=>c.toUpperCase()),d=e.operations[0]?.query??"",u=/^Connection:\s*(Project|Personal)\s+—\s+(.+)$/m.exec(d);if(u?.[1]&&u[2])return {action:r,app:i,account:u[2].trim(),scope:u[1]==="Project"?"project":"personal"};let f=/^Connection:.*?([^\s<>]+@[^\s<>]+)\s*$/m.exec(d)?.[1];return {action:r,app:i,account:f}}function ea(e){let t=Dt(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 ta({operation:e}){if(e.rows.length===0)return null;let t=a=>a!=null&&a!==false,n=e.columns.filter(a=>e.rows.some(r=>t(r.before?.[a])||t(r.after?.[a]))?e.kind!=="update"?true:e.rows.some(r=>U(r.before?.[a])!==U(r.after?.[a])):false);return jsx("div",{className:"fk:overflow-x-auto fk:rounded-md fk:border fk:border-border fk:corner-squircle",children:jsxs($,{className:"fk:text-xs",children:[jsx(aa$1,{children:jsxs(da$1,{children:[jsx(ea$1,{className:"fk:h-8",children:e.entity==="scopes"||e.entity==="spaces"||e.entity==="studio"?"Setting":"Attribute"}),n.map(a=>jsx(ea$1,{className:"fk:h-8",children:a},a))]})}),jsx(ba$1,{children:e.rows.map((a,s)=>jsxs(da$1,{children:[jsxs(fa$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(fa$1,{className:"fk:py-1.5",children:e.kind==="create"?jsx("span",{children:U(a.after?.[r])}):e.kind==="delete"?jsx("span",{className:"fk:text-muted-foreground",children:U(a.before?.[r])}):jsx(Tt,{after:a.after?.[r],before:a.before?.[r]})},r))]},a.id??s.toString()))})]})})}function na(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 aa({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:na(n)}),jsx(ta,{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 sa(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 It({api:e,approval:t,onDecided:n}){let[a,s]=useState(t),[r,i]=useState(t),[d,u]=useState(""),[f,c]=useTransition(),[p,x]=useState(false),[v,k]=useState(false),[g$1,w]=useState(""),y=wt();t!==r&&(i(t),sa(t,r)||a.id===t.id&&a.status!=="pending"&&t.status==="pending"||s(t));function C(S){s(S),y(),S.kind==="schema"&&S.status==="approved"&&Ne({approvalId:S.id,approvalUrl:g(S.projectId).approval(S.id),projectId:S.projectId}),n?.(S);}function _({approved:S,automationEdits:R,force:$=false,reason:E,remember:Y=false,skillEdits:L}){c(async()=>{u("");try{let I=await e.decideApproval(a.id,{approved:S,...R?{automationEdits:R}:{},force:$,reason:E,remember:Y,...L?{skillEdits:L}:{}});if(I.errorCode==="stale_preview"){k(!0),I.approval&&s(I.approval);return}if(k(!1),x(!1),I.approval?C(I.approval):I.success?C({...a,decidedAt:a.decidedAt??new Date().toISOString(),reason:E??a.reason,status:S?"approved":"rejected"}):I.errorCode==="already_decided"&&n?.(a),!I.success&&(I.errorCode!=="already_decided"||!I.approval)){let ke=Array.isArray(I.errorMessage)?I.errorMessage.join(", "):I.errorMessage;u(ke||"Failed to submit the decision.");}}catch(I){u(I instanceof Error?I.message:"Failed to submit the decision.");}});}return {approval:a,decide:_,errorMessage:d,isDeciding:f,isPending:a.status==="pending",isRejectDialogOpen:p,isStale:v,rejectReason:g$1,setIsRejectDialogOpen:x,setRejectReason:w}}function Et({allowRemember:e=false,askForRejectionReason:t,decide:n,isDeciding:a,isRejectDialogOpen:s,isStale:r,rejectReason:i$1,setIsRejectDialogOpen:d,setRejectReason:u,variant:f}){let c=f==="header",p=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(b$3,{className:p,disabled:a,size:x,onClick:()=>n({approved:true,force:r,remember:e&&v}),children:[a?jsx(LoaderCircle,{className:"fk:size-4 fk:animate-spin"}):jsx(CheckIcon,{className:"fk:size-4"}),r?"Approve anyway":"Approve"]}),jsxs(b$3,{className:p,disabled:a,size:x,variant:"outline",onClick:()=>{t?(u(""),d(true)):n({approved:false});},children:[jsx(XIcon,{className:"fk:size-4"}),"Reject"]}),e?jsxs("label",{className:"fk:ml-1 fk:flex fk:cursor-pointer fk:items-center fk:gap-1.5 fk:whitespace-nowrap fk:text-xs fk:text-muted-foreground",htmlFor:g,children:[jsx(o$1,{checked:v,id:g,onCheckedChange:w=>k$1(w===true)}),"Always allow this tool for this automation"]}):null]}),t?jsx(c$1,{open:s,onOpenChange:d,children:jsxs(h,{children:[jsxs(i,{children:[jsx(k,{children:"Reject this proposal?"}),jsx(l,{children:"The mutation will not be executed. The agent receives your reason and can adapt its plan."})]}),jsx(la$1,{placeholder:"Optional reason for the agent...",value:i$1,onChange:w=>u(w.target.value)}),jsxs(j,{children:[jsx(b$3,{disabled:a,size:"sm",variant:"outline",onClick:()=>d(false),children:"Cancel"}),jsxs(b$3,{disabled:a,size:"sm",variant:"destructive",onClick:()=>n({approved:false,reason:i$1.trim()||void 0}),children:[a?jsx(LoaderCircle,{className:"fk:size-4 fk:animate-spin"}):jsx(ArrowRightIcon,{className:"fk:size-4"}),"Reject proposal"]})]})]})}):null]})}var ra={always:"Every finished run",failures:"Failures only",never:"Never",when_flagged:"Results that need attention"};function Mt(e){return e.visibility==="personal"?"Only you":e.visibility==="space"?`Space: ${e.spaceLabel??"unknown"}`:"Everyone in the project"}function oa({approval:e,instructions:t,isPending:n,proposal:a,onInstructionsChange:s}){let r=useId(),i=e.createdAutomation??null,d=[...a.replacesMonitor?[{label:"Replaces",value:`The monitor \u201C${a.replacesMonitor}\u201D, which stops once this exists`}]:[],{label:"Runs",value:a.triggers.join(`
|
|
5
5
|
`)},{label:"Visible to",value:Mt(a)},{label:"Data changes",value:a.mutationPolicy==="auto_approve"?"Applied without review":"Wait for approval"},{label:"Notifications",value:`${ra[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
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(la$1,{className:"fk:min-h-40 fk:text-sm",id:r,value:t,onChange:u=>s(u.target.value)})]}):jsx("p",{className:"fk:whitespace-pre-wrap fk:rounded-md fk:border fk:p-3 fk:text-sm fk:corner-squircle",id:r,children:t})]}),i?jsxs("div",{className:"fk:flex fk:flex-wrap fk:gap-2",children:[jsx(b$3,{asChild:true,size:"sm",variant:"outline",children:jsx(Link,{to:`/${e.projectId}/ai/automations/${i.automationId}`,children:"Open the automation"})}),i.runId?jsx(b$3,{asChild:true,size:"sm",variant:"ghost",children:jsx(Link,{to:`/${e.projectId}/ai/automations/${i.automationId}/runs/${i.runId}`,children:"View its first run"})}):null]}):null]})}function ia({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(b$3,{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(b$3,{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(b$3,{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(b$3,{disabled:n,size:"sm",variant:"outline",onClick:()=>e({approved:false}),children:[jsx(XIcon,{className:"fk:size-4"}),"Reject"]})]})}var Ct=3;function la(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:Ct,i=a===e.length?0:Ct;s.length>r+i+1?t.push(...s.slice(0,r),{count:s.length-r-i,kind:"folded"},...s.slice(s.length-i)):t.push(...s),n=a;}return t}var Pt={added:{className:"fk:bg-success/10",marker:"+"},removed:{className:"fk:bg-destructive/10 fk:text-muted-foreground",marker:"\u2212"},same:{className:"",marker:" "}};function ua({after:e,before:t}){let n=useMemo(()=>St(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:la(n).map((r,i)=>r.kind==="folded"?jsxs("div",{className:"fk:px-3 fk:py-0.5 fk:text-muted-foreground",children:["\u22EF ",r.count.toString()," unchanged ",r.count===1?"line":"lines"]},i.toString()):jsxs("div",{className:`fk:flex fk:gap-2 fk:px-3 ${Pt[r.kind].className}`,children:[jsx("span",{"aria-hidden":true,className:"fk:w-2 fk:shrink-0 fk:select-none fk:text-muted-foreground",children:Pt[r.kind].marker}),jsx("span",{className:"fk:min-w-0 fk:whitespace-pre-wrap fk:break-words",children:r.text||" "})]},i.toString()))})]})}function Rt({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 da({approval:e,fields:t$1,isPending:n,proposal:a,onFieldsChange:s$1}){let r=useId(),i=useId(),{before:d}=a,u=e.savedSkillId??a.skillId,f=n&&s$1;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:Mt(a)}),d?jsxs(Fragment,{children:[jsx(Rt,{after:t$1.name,before:d.name,label:"Name"}),jsx(Rt,{after:t$1.description,before:d.description,label:"Description"})]}):null]}),d?d.content===t$1.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(ua,{after:t$1.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(s,{id:r,maxLength:120,value:t$1.name,onChange:c=>s$1({...t$1,name:c.target.value})})]}),jsxs("div",{className:"fk:space-y-1.5",children:[jsx("label",{className:"fk:text-sm fk:font-medium",htmlFor:i,children:"Description"}),jsx(la$1,{className:"fk:min-h-16 fk:text-sm",id:i,maxLength:1024,value:t$1.description,onChange:c=>s$1({...t$1,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,{className:"fk:min-h-0 fk:flex-1 fk:rounded-md"}),children:jsx(Kn,{content:t$1.content,onChange:c=>s$1({...t$1,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$1.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$1.content})]})]}),u&&(!n||d)?jsx(b$3,{asChild:true,size:"sm",variant:"outline",children:jsx(Link,{to:`/${e.projectId}/ai/skills/${u}`,children:"Open the skill"})}):null]})}function zt({decide:e,fields:t,isDeciding:n,proposal:a}){let s={content:t.content.trim(),description:t.description.trim(),name:t.name.trim()},r=!s.name||!s.description||!s.content,i=Object.fromEntries(Object.keys(s).filter(d=>s[d]!==a[d].trim()).map(d=>[d,s[d]]));return jsxs("div",{className:"fk:flex fk:flex-wrap fk:items-center fk:gap-2",children:[jsxs(b$3,{disabled:n||r,size:"sm",onClick:()=>e({approved:true,...Object.keys(i).length>0?{skillEdits:i}:{}}),children:[n?jsx(LoaderCircle,{className:"fk:size-4 fk:animate-spin"}):jsx(CheckIcon,{className:"fk:size-4"}),a.before?"Save changes":"Save skill"]}),jsxs(b$3,{disabled:n,size:"sm",variant:"outline",onClick:()=>e({approved:false}),children:[jsx(XIcon,{className:"fk:size-4"}),"Reject"]})]})}function _t(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 Lt({approval:e,automationInstructions:t,chat:n,errorMessage:a,isPending:s,isStale:r,onAutomationInstructionsChange:i,onSkillFieldsChange:d,skillFields:u}){let{preview:f}=e,c=n?Dt(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(Vn,{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?ea(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(oa,{approval:e,instructions:t??f.automation.instructions,isPending:s,proposal:f.automation,onInstructionsChange:i}):e.kind==="automation"&&f?.automationChange?jsx(ia,{approval:e,change:f.automationChange}):e.kind==="skill"&&f?.skill?jsx(da,{approval:e,fields:u??f.skill,isPending:s,proposal:f.skill,onFieldsChange:d}):e.kind==="schema"&&f?jsx(aa,{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:Wn(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(Gn,{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(Zn,{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 jt({api:e,approval:t,chat:n,onDecided:a}){let{approval:s,decide:r,errorMessage:i,isDeciding:d,isPending:u,isRejectDialogOpen:f,isStale:c,rejectReason:p,setIsRejectDialogOpen:x,setRejectReason:v}=It({api:e,approval:t,onDecided:a}),k=s.kind==="automation"?s.preview?.automation??null:null,[g,w]=useState(k?.instructions??""),y=_t(s);return jsxs(Fragment,{children:[jsx(Lt,{approval:s,automationInstructions:k?g:void 0,chat:n,errorMessage:i,isPending:u,isStale:c,onAutomationInstructionsChange:k?w:void 0,onSkillFieldsChange:y.proposal?y.setFields:void 0,skillFields:y.fields??void 0}),u&&y.proposal&&y.fields?jsx("div",{className:"fk:mt-4",children:jsx(zt,{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(Et,{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 wr({api:e,approval:t,onClose:n,onDecided:a}){let{approval:s,decide:r,errorMessage:i,isDeciding:d,isPending:u,isRejectDialogOpen:f,isStale:c,rejectReason:p,setIsRejectDialogOpen:x,setRejectReason:v}=It({api:e,approval:t,onDecided:a}),k=s.kind==="automation"?s.preview?.automation??null:null,[g,w]=useState(k?.instructions??""),y=_t(s);return jsx(pa$1,{actions:u&&y.proposal&&y.fields?jsx(zt,{decide:r,fields:y.fields,isDeciding:d,proposal:y.proposal}):u&&k?jsx($t,{decide:r,instructions:g,isDeciding:d,proposal:k}):u?jsx(Et,{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(Lt,{approval:s,automationInstructions:k?g:void 0,chat:false,errorMessage:i,isPending:u,isStale:c,onAutomationInstructionsChange:k?w:void 0,onSkillFieldsChange:y.proposal?y.setFields:void 0,skillFields:y.fields??void 0})})}var ca="Approved by Flexkit Jev policy",fa="Approved by automation tool allow rule",pa=new Set(["data-create-sandbox","data-execute-graphql","data-export-records","data-load-skill","data-plan","data-plugin-call","data-read-source","data-run-command","data-search-schema","data-update-memory","data-validate-graphql","data-web-search"]);function me(e){return pa.has(e)}function b(e){return e.data}function Be(e){return !e.decidedBy&&!!(e.reason?.startsWith(ca)||e.reason?.startsWith(fa))}function H(e,t=72){let n=e.trim();if(n.length<=t)return n;let a=n.slice(0,t),s=a.lastIndexOf(" ");return `${(s>=Math.floor(t*.6)?a.slice(0,s):a).trimEnd()}\u2026`}function ma(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 ka(e){let t=e.lastIndexOf(`
|
|
7
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 ga(e,t){let a=(ka(e)).split(/\r?\n/).map(u=>u.trim()).filter(Boolean),s=a[a.length-1];if(!s)return null;let i=/^\*\*(.+?)\*\*:?$/.exec(s)?.[1]??/^#{1,6}\s+(.+)$/.exec(s)?.[1]??/^(.+?[.!?])(?:\s|$)/.exec(s)?.[1]??s,d=ma(i);return !d||/^reasoning$/i.test(d)?null:H(d)}function Ot(e){return e.replace(/[_-]+/g," ").trim()}function va(e){if(e.type==="data-load-skill"){let t=b(e);return t.status!=="loading"?null:t.skillName?H(`Loading skill "${t.skillName}"`):"Loading skill"}if(e.type==="data-search-schema")return b(e).status==="loading"?"Searching schema":null;if(e.type==="data-validate-graphql")return b(e).status==="loading"?"Validating GraphQL query":null;if(e.type==="data-execute-graphql"){let t=b(e);return t.status!=="loading"?null:t.operationType==="mutation"?"Executing GraphQL mutation":"Executing GraphQL query"}if(e.type==="data-export-records"){let t=b(e);return t.status!=="loading"?null:t.rowCount>0?`Exporting records (${t.rowCount.toLocaleString("en-US")} so far)`:"Exporting records"}if(e.type==="data-update-memory")return b(e).status==="loading"?"Updating memory":null;if(e.type==="data-web-search"){let t=b(e);return t.status!=="loading"?null:t.query?H(`Searching the web for "${t.query}"`):"Searching the web"}if(e.type==="data-run-command"){let t=b(e);return ["executing","running","waiting"].includes(t.status)?H(`Running ${[t.command,...t.args].join(" ")}`):null}if(e.type==="data-create-sandbox")return b(e).status==="loading"?"Creating sandbox":null;if(e.type==="data-plugin-call"){let t=b(e);return t.status!=="loading"?null:H(`Calling ${t.pluginId}: ${Ot(t.tool)}`)}if(e.type==="data-subtask"){let t=b(e);return t.status==="running"?H(`Running subtask: ${t.title}`):null}if(e.type==="data-knowledge-search"){let t=b(e);return t.status!=="loading"?null:t.query?H(`Searching knowledge for "${t.query}"`):"Searching knowledge"}if(e.type==="data-read-source"){let t=b(e);return t.status!=="loading"?null:t.sourceTitle?H(`Reading "${t.sourceTitle}"`):"Reading a document"}return null}var ha=new Set(["data-execute-graphql","data-read-source","data-search-schema","data-validate-graphql"]);function De(e){if(!me(e.type)||e.type==="data-plan"||ha.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??"")}: ${Ot(String(t.tool??""))}`;default:return "The tool call failed"}}function Ie(e){if(e.type==="step-start"||e.type==="reasoning")return true;if(me(e.type))return De(e)===null;if(e.type==="data-knowledge-search")return b(e).status==="loading";if(e.type==="data-mutation-approval"){let t=b(e);return Be(t)&&t.status!=="error"}return false}function pe(e){if(!e)return null;for(let t=e.parts.length-1;t>=0;t--){let n=e.parts[t];if(n?.type!=="data-plan")continue;let a=b(n),s=a.steps.findIndex(r=>r.status==="in_progress");return s<0?null:H(`Step ${(s+1).toString()} of ${a.steps.length.toString()}: ${a.steps[s].step}`)}return null}function ya(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"?ga(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:va(n)??pe(e)}return null}function Xe(e){return e?e.parts.some(t=>t.type!=="data-mutation-approval"?false:b(t).status==="pending"):false}function Je(e,t={}){let n=false,a=[];for(let s of e.parts){if(s.type!=="data-mutation-approval"){a.push(s);continue}let r=b(s);if(r.status!=="pending"){a.push(s);continue}n=true;let i=t[r.approvalId];i&&i!=="pending"&&a.push({...s,data:{...r,status:i}});}return n?{...e,parts:a}:e}function Ft(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 ba(e){return Ft(e,{pendingOnly:true})}function Qe(e){return !!e?.parts.some(t=>t.type==="data-user-question"&&b(t).status==="pending")}function Ut(e){return e.map(()=>({other:"",selected:[]}))}function qt(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 Bt(e,t,n){return e.multiSelect?{...t,other:n}:{other:n,selected:n.trim()?[]:t.selected}}function Xt(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 Jt(e){return e&&[...e.selected,...e.other?[`\u201C${e.other}\u201D`]:[]].join(", ")||"\u2014"}function xa(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 Qt(e,t){return e.kind!=="idle"?e:t.knowledgeSourceId?{kind:"added",sourceId:t.knowledgeSourceId}:e}function Ta(e){return typeof e=="string"&&e.includes("/agent/chats/")}function Ht({attachment:e$2}){let{currentProjectId:t}=f(),n=b$4(),a=useNavigate(),{mutate:s}=useSWRConfig(),r=useMemo(()=>t?d$1(t):null,[t]),[i,d]=useState({kind:"idle"}),u=Qt(i,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$1(g,e$2.filename),d({kind:"added",sourceId:g.source.id}),f$3(),s(Ta);}catch(g){qa$1.error(h$1(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 Kt=20*1024*1024,Kr=10,Vt=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"]),Wt=new Set(["application/pdf","image/gif","image/jpeg","image/png","image/webp"]),Yr=[...[...Vt].map(e=>`.${e}`),...Wt].join(",");function Gt(e){let t=e.lastIndexOf(".");return t<=0?"":e.slice(t+1).toLowerCase()}function $a(e){let t=Gt(e.name);return (t?Vt.has(t):Wt.has(e.type))?e.size===0?`"${e.name}" is empty.`:e.size>Kt?`"${e.name}" exceeds the ${String(Math.round(Kt/(1024*1024)))} MB limit.`:null:`"${e.name}" is not supported. Attach images, PDFs, or text files.`}async function za(e){let n=await(await fetch(e.url)).blob();return new File([n],e.filename??"file",{type:e.mediaType||n.type})}function Vr(e,t){let{attachments:n}=Pb(),a=useRef({}),[,s]=useState(0),r=useCallback(()=>s(f=>f+1),[]),i=useRef(n.remove);i.current=n.remove;let d=useRef(t);d.current=t,useEffect(()=>{let f=new Set(n.files.map(c=>c.id));for(let[c,p]of Object.entries(a.current))f.has(c)||(p.controller.abort(),delete a.current[c]);for(let c of n.files){if(a.current[c.id])continue;let p=new AbortController,x={controller:p,status:"uploading"};a.current[c.id]=x,(async()=>{try{let v=await za(c),k=$a(v);if(k)throw new Error(k);let g=await e.uploadAgentChatAttachment(v,p.signal);if(p.signal.aborted)return;x.attachment=g,x.status="done";}catch(v){if(p.signal.aborted)return;x.status="error",delete a.current[c.id],i.current(c.id),d.current(v instanceof Error?v.message:"The file could not be uploaded.");}finally{r();}})();}r();},[e,n.files,r]);let u=Object.values(a.current).some(f=>f.status==="uploading");return {getUploaded:f=>f.map(c=>a.current[c]?.attachment).filter(c=>!!c),isUploading:u,isUploadingFile:f=>a.current[f]?.status==="uploading"}}function Ke(e){return !!e?.startsWith("image/")}function Zt({image:e,onClose:t}){return jsx(c$1,{onOpenChange:n=>n?void 0:t(),open:e!==null,children:jsxs(h,{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(k,{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(f$2,{"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 en({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 tn({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(va$1,{className:"fk:size-4"})}):null,a?jsx(en,{label:`Remove ${e.filename}`,onRemove:a}):null]})}function _a(e,t){let n=Gt(e);if(n)return n.toUpperCase();let a=t?.split("/")[1]?.split("+")[0];return a?a.toUpperCase():"FILE"}function nn({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(va$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:_a(t.filename,t.mediaType)})]})]}),i="fk:flex fk:h-14 fk:max-w-64 fk:items-center fk:gap-2.5 fk:rounded-xl fk:border fk:border-border fk:bg-background fk:px-2 fk:corner-squircle";return jsxs("div",{className:"fk:relative fk:shrink-0",children:[n?jsx("a",{className:`${i} fk:transition-colors fk:hover:bg-accent/50 fk:focus-visible:outline-none fk:focus-visible:ring-2 fk:focus-visible:ring-ring`,href:n,rel:"noreferrer",target:"_blank",children:r}):jsx("div",{className:i,children:r}),s?jsx(en,{label:`Remove ${t.filename}`,onRemove:s}):null,e]})}function Wr({uploads:e}){let t=Sb(),[n,a]=useState(null);return t.files.length===0?null:jsxs(Fragment,{children:[jsx("div",{className:"fk:flex fk:flex-wrap fk:items-center fk:gap-2",children:t.files.map(s=>{if(Ke(s.mediaType)&&s.url){let r={filename:s.filename??"Image",url:s.url};return jsx(tn,{image:r,isUploading:e.isUploadingFile(s.id),onOpen:()=>a(r),onRemove:()=>t.remove(s.id),sizeClassName:"fk:size-14"},s.id)}return jsx(nn,{file:{filename:s.filename??"file",mediaType:s.mediaType},isUploading:e.isUploadingFile(s.id),onRemove:()=>t.remove(s.id)},s.id)})}),jsx(Zt,{image:n,onClose:()=>a(null)})]})}function an({attachments:e}){let[t,n]=useState(null);if(e.length===0)return null;let a=e.filter(r=>Ke(r.mediaType)),s=e.filter(r=>!Ke(r.mediaType));return jsxs("div",{className:"fk:flex fk:flex-col fk:items-end fk:gap-2",children:[a.length>0?jsx("div",{className:"fk:flex fk:flex-wrap fk:justify-end fk:gap-2",children:a.map(r=>jsx(tn,{image:r,onOpen:()=>n(r),sizeClassName:"fk:size-24"},r.url))}):null,jsx(Zt,{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(nn,{action:jsx(Ht,{attachment:r}),file:r,href:r.url},r.url))}):null]})}function io(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 on({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 lo({api:e$1,chatId:t,onTurnIntoAutomation:n,projectId:a,sending:s=false}){let{data:r,mutate:i}=Ua(g(a).agentChat(t),f$1,{revalidateOnMount:false}),[d,u]=useState(null),f=r?.monitors??[];if(f.length===0)return null;async function c$1(p){u(p.id);try{await e$1.stopAgentChatMonitor(t,p.id),await i();}catch{qa$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(b$3,{"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(b$3,{"aria-label":`Stop watching ${p.description}`,className:"fk:size-6 fk:rounded-full",disabled:d===p.id,size:"icon",variant:"ghost",onClick:()=>{c$1(p);},children:jsx(XIcon,{className:"fk:size-3.5"})})}),jsx(e,{children:"Stop watching"})]})]},p.id))})}function un(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 qa(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 ln(e,t,n){return n==="personal"?e.allowPersonal:t}function dn(e,t,n){if(!e.enabled)return {kind:"disabled"};let a=n?e.connections.find(i=>i.id===n&&i.status==="needs_auth"):void 0;if(a)return ln(e,t,a.scope)?{kind:"reconnect",connection:a}:{kind:"not_permitted"};let s=qa(e);if(s)return {kind:"connected",connection:s};let r=e.scopes.filter(i=>ln(e,t,i));return r.length>0?{kind:"connect",scopes:r}:{kind:"not_permitted"}}var Va=createContext(null),Ee=new Map,We=new Set;function Ve(e,t){t?Ee.set(e,t):Ee.delete(e),We.forEach(n=>n());}function Wa(e){return We.add(e),()=>We.delete(e)}function Ga(e){return useSyncExternalStore(Wa,()=>Ee.get(e)??null,()=>null)}var pn={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 Za({busy:e,logoUrl:t,name:n,onContinue:a$1,onOpenChange:s,open:r,scopes:i,connect:d}){let[u,f]=useState(i.length===1?i[0]??null:null),c=[...es(n,d),{description:`Remove the connection to ${n} at any time.`,title:"You stay in control"}];return jsx(c$1,{onOpenChange:s,open:r,children:jsxs(h,{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}),jsxs(k,{className:"fk:text-xl",children:["Connect to ",n]}),jsxs(l,{children:["Let the Flexkit agent access and use ",n," on your behalf."]})]}),jsx("ul",{className:"fk:space-y-3 fk:rounded-xl fk:bg-muted/60 fk:p-4 fk:corner-squircle",children:c.map(p=>jsxs("li",{className:"fk:flex fk:gap-3",children:[jsx(CheckIcon,{className:"fk:mt-0.5 fk:size-4 fk:shrink-0"}),jsxs("span",{children:[jsx("span",{className:"fk:block fk:text-sm fk:font-medium",children:p.title}),jsx("span",{className:"fk:block fk:text-sm fk:text-muted-foreground",children:p.description})]})]},p.title))}),i.length>1?jsx("div",{className:"fk:space-y-1.5",role:"radiogroup","aria-label":"Connection",children:i.map(p=>jsxs("button",{"aria-checked":u===p,className:`fk:flex fk:w-full fk:flex-col fk:rounded-lg fk:border fk:px-3 fk:py-2 fk:text-left fk:corner-squircle ${u===p?"fk:border-primary fk:bg-primary/5":"fk:border-border fk:hover:bg-muted/60"}`,onClick:()=>f(p),role:"radio",type:"button",children:[jsx("span",{className:"fk:text-sm fk:font-medium",children:pn[p].title}),jsx("span",{className:"fk:text-xs fk:text-muted-foreground",children:pn[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(b$3,{className:"fk:w-full",disabled:e||!u,onClick:()=>u&&a$1(u),type:"button",children:"Continue"})]})})}function es(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 ts(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 gn({connectionId:e,pluginId:t}){let{currentProjectId:n}=f(),a$1=useMemo(()=>n?d(n):null,[n]),s=n?`/api/flexkit/${n}`:null,r=s?`${s}/plugins/${encodeURIComponent(t)}`:null,{data:i,error:d$1,mutate:u}=Ua(r,f$1),{mutate:f$2}=useSWRConfig(),c=useContext(Va),[p,x]=useState(false),v=`${n??""}:${t}:${e??""}`,k=Ga(v),g=k?.status==="connecting",w=k?.status==="failed"?k:null;if(!i)return jsxs("div",{className:"fk:flex fk:items-center fk:gap-2 fk:rounded-2xl fk:border fk:border-border fk:p-4 fk:text-sm fk:text-muted-foreground fk:corner-squircle",children:[d$1?jsx(CircleAlertIcon,{className:"fk:size-4"}):jsx(LoaderCircle,{className:"fk:size-4 fk:animate-spin"}),d$1?`${t} could not be loaded.`:`Loading ${t}\u2026`]});let{plugin:y}=i,C=dn(y,i.canManage,e),_=C.kind==="reconnect"?C.connection:null;function S(E){!a$1||Ee.get(v)?.status==="connecting"||(x(false),Ve(v,{status:"connecting"}),d$3(a$1,y,E,_?{connectionId:_.id}:void 0).then(Y=>{Ve(v,null),Y&&(u().catch(()=>{}),s&&f$2(`${s}/plugins`).catch(()=>{}),c?.onConnected(t));},Y=>{let L=Y instanceof Error?Y.message:"";Ve(v,{message:un(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(b$3,{disabled:g,onClick:()=>S(w.scope),size:"sm",type:"button",variant:"secondary",children:"Retry"})):$=jsxs(b$3,{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:ts(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(Za,{busy:g,logoUrl:y.logoUrl,name:y.name,onContinue:S,onOpenChange:x,open:p,scopes:C.scopes,connect:y.connect}):null]})}function wo({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 So(e){let t=(Array.isArray(e)?e:[]).find(n=>n.type==="data-plugin-connected");return t&&typeof t.data=="object"&&t.data!==null?t.data:null}var ie=class extends Error{},Me=class extends Error{};function vn({url:e,signal:t,state:n,onState:a,wake:s,fetchStream:r=fetch,retryMs:i=2e3}){let d=0,u=0,f=new TransformStream,c=f.writable.getWriter(),p=new AbortController;c.closed.catch(g=>p.abort(g));let x=()=>{p.abort(t.reason),c.abort(t.reason).catch(()=>{});};t.addEventListener("abort",x,{once:true}),t.aborted&&x();let v=()=>new Promise(g=>{let w=()=>{clearTimeout(y),p.signal.removeEventListener("abort",w),s?.removeEventListener("wake",w),g();},y=setTimeout(w,i);p.signal.addEventListener("abort",w,{once:true}),s?.addEventListener("wake",w,{once:true}),p.signal.aborted&&w();});async function k(){try{for(await c.write({type:"start"});!p.signal.aborted;){try{let g=await r(`${e}${e.includes("?")?"&":"?"}wire=2&startIndex=${d}`,{credentials:"include",signal:p.signal});if(g.status===404){a("unavailable"),await c.close();return}if(g.status===401||g.status===403)throw new Me("Stream access denied");if(!g.ok||!g.body)throw new Error(`Stream request failed: ${g.status}`);if(g.headers.get("x-flexkit-stream-version")!=="2")throw await g.body.cancel(),new ie("Backend uses legacy replay");a("streaming");let w=g.body.pipeThrough(new TextDecoderStream).getReader(),y="",C=!1;try{for(;!p.signal.aborted;){let{value:_,done:S}=await w.read();if(S)break;y+=_;let R;for(;(R=y.indexOf(`
|
|
8
8
|
`))>=0;){let $=y.slice(0,R);if(y=y.slice(R+1),!$)continue;let E=JSON.parse($);if(!Number.isSafeInteger(E.index)||E.index<0)throw new Error("Invalid replay cursor");if(!(E.index<d)){if(E.index!==d)throw new Error("Replay cursor gap");E.chunk&&await c.write(E.chunk),d=E.index+1,u=0,E.chunk?.type==="finish"&&E.chunk.messageMetadata?.flexkitTerminal&&(C=!0);}}if(y.length>2e6)throw new Error("Oversized replay frame");if(C)break}}finally{await w.cancel().catch(()=>{}),w.releaseLock();}if(C||n().terminal&&!y){await c.write({type:"finish"}),await c.close(),a("finished");return}}catch(g){if(p.signal.aborted||g instanceof ie||g instanceof Me||++u>=5)throw g}do a(n().paused?"paused":"streaming"),await v();while(!p.signal.aborted&&n().paused&&!n().terminal)}}catch(g){await c.abort(g).catch(()=>{});}finally{t.removeEventListener("abort",x),c.releaseLock();}}return k(),pipeJsonRender(f.readable)}var ss={pending:"Waiting for an answer.",cancelled:"The turn was stopped before you answered.",dismissed:"You skipped these questions.",expired:"Nobody answered in time."};function rs({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 os({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(rs,{description:s.description,label:s.label,multiSelect:a.multiSelect,onClick:()=>n(qt(a,t,s.label)),selected:t.selected.includes(s.label)},s.label)),jsx(s,{"aria-label":`Your own answer to: ${a.question}`,className:"fk:h-9",maxLength:4e3,onChange:s=>n(Bt(a,t,s.target.value)),placeholder:"Other \u2014 type your own answer",value:t.other})]})]})}function is({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:ss[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:Jt(e.answers?.[n])})]},n))})}function yn({answer:e,data:t}){let[n,a]=useState(()=>Ut(t.questions)),[s,r]=useState(null),[i,d]=useState(null),[u,f]=useState(""),c=t.status==="pending"&&s?s:t;if(c.status!=="pending"||!e)return jsx(is,{data:c});let p=Xt(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(os,{disabled:i!==null,draft:n[k]??{other:"",selected:[]},onChange:g=>a(w=>w.map((y,C)=>C===k?g:y)),question:v},k)),u?jsx("p",{className:"fk:text-xs fk:text-destructive",children:u}):null,jsxs("div",{className:"fk:flex fk:flex-wrap fk:items-center fk:gap-2",children:[jsxs(b$3,{disabled:!p||i!==null,size:"sm",type:"submit",children:[i==="answer"?jsx(LoaderCircle,{className:"fk:size-3.5 fk:animate-spin"}):null,"Submit"]}),jsxs(b$3,{disabled:i!==null,onClick:()=>{x({action:"dismiss"});},size:"sm",type:"button",variant:"ghost",children:[i==="dismiss"?jsx(LoaderCircle,{className:"fk:size-3.5 fk:animate-spin"}):null,"Skip"]}),jsx("span",{className:"fk:text-xs fk:text-muted-foreground",children:"or reply in the chat"})]})]})}function ls(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 bn(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:ls(n.locator),passageId:n.passageId});}return [...t.values()]}function xn(e,t){let n=t.reduce((a,s)=>a+s.passages.length,0);return n===0?`No passages matched "${e}"`:`${String(n)} ${n===1?"passage":"passages"} from ${String(t.length)} ${t.length===1?"document":"documents"} for "${e}"`}var Ts=lazy(()=>import('./spec-renderer-3GAVSV52.js').then(e=>({default:e.RunSpecPart})));function Ds(e){return jsx(Suspense,{fallback:null,children:jsx(Ts,{...e})})}function Is(){let{currentProjectId:e}=f();return {api:useMemo(()=>e?d(e):null,[e]),projectId:e}}var Nn=5,Dn=2e3,In=120,Ge="data-spec",En=createContext(null),Es=createContext(false);function Ms(e){return new Promise(t=>window.setTimeout(t,e))}function $s(e){return e instanceof Error?e.name==="AbortError"||e.message.toLowerCase().includes("aborted"):false}function zs(e){return e.some(t=>!Ie(t))}function _s(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 Ls(e){let t=_s(e),n=[];for(let a of e){if(a.role==="user"){t.has(a.id)||n.push(a);continue}if(a.role!=="assistant"){n.push(a);continue}let s=[],r=0,i=()=>{zs(s)&&n.push({...a,id:`${a.id}-${r.toString()}`,parts:s}),r++,s=[];};for(let d of a.parts){if(d.type==="data-user-message"){let u=b(d);i(),n.push({id:d.id??crypto.randomUUID(),parts:u.parts,role:"user"});continue}s.push(d);}i();}return n}function ni(e){return useMemo(()=>Ls(e),[e])}function le(e){return e==="success"||e==="failed"||e==="cancelled"||e==="skipped"}function Mn({latestMessage:e,recordStatus:t,suppressApprovalPause:n}){return le(t)||n||t==="running"?false:t==="awaiting_approval"?true:Xe(e)||Qe(e)}function ai(e,t){let[n,a]=useState(false),s=js(n?e:"",t),[r,i]=useState(),[d,u]=useState("streaming"),f=useRef(t);f.current=t;let c=useRef(null);c.current||(c.current=new EventTarget);let p=c.current,x=t?.resumeToken;return useEffect(()=>{p.dispatchEvent(new Event("wake"));},[x,p]),useEffect(()=>{if(a(false),i(void 0),!e){u("unavailable");return}let v=new AbortController,k,g,w=()=>{k=void 0,g&&!v.signal.aborted&&i({...g});},y=vn({url:e,signal:v.signal,state:()=>({terminal:le(f.current?.recordStatus),paused:Mn({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,In));w();}catch(C){if(v.signal.aborted)return;C instanceof ie?a(true):(console.error("Run stream error",C),u("error"));}})(),()=>{v.abort(),k&&clearTimeout(k);}},[e,p]),n?s:{message:r?Je(r,t?.decidedApprovals??{}):void 0,status:d}}function js(e,t){let[n,a]=useState(),[s,r]=useState("streaming"),i=t?.recordStatus,d=t?.resumeToken??0,u=useRef(t?.decidedApprovals??{});u.current=t?.decidedApprovals??{};let f=useRef(t?.suppressApprovalPause??false);f.current=t?.suppressApprovalPause??false;let c=useRef(e),p=useRef(n);return p.current=n,useEffect(()=>{let x=c.current!==e;if(c.current=e,!e){a(void 0),r("unavailable");return}let v=new AbortController,k=x?void 0:p.current,g=x?0:k?.parts.length??0;if(x)a(void 0);else if(k&&(i==="running"||le(i))){let S=Je(k,u.current);S!==k&&(k=S,a(S));}r("streaming");let w=e.includes("?")?"&":"?",y=async()=>{let S=await fetch(`${e}${w}startIndex=0`,{credentials:"include",signal:v.signal});if(S.status===404)return "unavailable";if(!S.ok||!S.body)throw new Error(`Failed to fetch the run stream (status ${S.status.toString()})`);let R=false,E=parseJsonEventStream({schema:uiMessageChunkSchema,stream:S.body}).pipeThrough(new TransformStream({transform:(j,$n)=>{if(!j.success)throw j.error;j.value.type==="finish"&&(R=true),$n.enqueue(j.value);}})),Y=readUIMessageStream({onError:j=>{v.signal.aborted||console.error("Run stream chunk error",j);},stream:E}),L=null,I=g===0,ke=(j=false)=>{v.signal.aborted||!k||!I&&(I=j||k.parts.length>=g,!I)||a({...k});};try{for await(let j of Y){if(v.signal.aborted)break;k=j,L===null&&(L=window.setTimeout(()=>{L=null,ke();},In));}}finally{L!==null&&(window.clearTimeout(L),L=null),ke(true);}return R?"finished":"incomplete"},C=async()=>{let S=0;for(;!v.signal.aborted;){S>0&&await Ms(Dn);try{let R=await y();if(v.signal.aborted)return;if(R==="unavailable"){r("unavailable");return}if(R==="finished"&&le(i)){r("finished");return}if(le(i)){r("finished");return}if(Mn({latestMessage:k,recordStatus:i,suppressApprovalPause:f.current})){r("paused");return}if(!(i==="running"||f.current)&&S>=Nn-1){r("error");return}}catch(R){if(v.signal.aborted||$s(R))return;if(console.error("Run stream error",R),le(i)){r("finished");return}if(!(i==="running"||f.current)&&S>=Nn-1){r("error");return}}S+=1;}},_=window.setTimeout(()=>{C();},0);return ()=>{window.clearTimeout(_),v.abort("Run replay unmounted");}},[i,d,e]),{message:n,status:s}}function si(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 Os(e){let t=e.trim();return t?t.split(`
|
|
9
|
-
`).every(n=>/^`{3,}[\w-]*$/.test(n.trim())):false}function Fs({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(an,{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 ri({api:e,part:t,partIndex:n,parts:a}){if(Ie(t))return null;if(me(t.type)){let s=De(t);return s?jsx(qs,{message:s}):null}if(t.type==="text")return Os(t.text)&&a.some(r=>r.type===Ge)?null:jsx(Us,{part:t});if(t.type==="data-knowledge-search")return jsx(Vs,{message:b(t)});if(t.type==="data-generating-files")return jsx(Hs,{message:b(t)});if(t.type==="data-run-artifact")return jsx(Ks,{api:e,message:b(t)});if(t.type==="data-tool-delivery")return jsx(Ys,{message:b(t)});if(t.type==="data-run-summary")return jsx(Ws,{message:b(t)});if(t.type==="data-subtask"){let s=b(t),r=s.status==="running"?`Running "${s.title}"`:s.status==="done"?`Completed "${s.title}"${typeof s.stepsUsed=="number"?` in ${s.stepsUsed.toString()} steps`:""}`:`"${s.title}" failed: ${s.error?.message??"unknown error"}`;return jsxs(B,{children:[jsxs(X,{children:[jsx(BotIcon,{className:"fk:size-3.5"}),"Subtask"]}),jsxs("div",{className:"fk:relative fk:min-h-5 fk:pl-6",children:[jsx("span",{className:"fk:absolute fk:left-0 fk:top-0",children:jsx(ze,{isError:s.status==="error",loading:s.status==="running"})}),jsx("span",{className:"fk:text-xs",children:r}),s.resultPreview?jsx("p",{className:"fk:mt-1 fk:text-xs fk:text-muted-foreground",children:s.resultPreview}):null]})]})}if(t.type==="data-mid-turn-message"){let s=b(t);return s.monitorEvent?jsx(on,{data:s.monitorEvent}):jsx(Fs,{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(gn,{connectionId:s.connectionId,pluginId:s.pluginId})}if(t.type==="data-suggested-prompt")return null;if(t.type==="data-turn-error"){let s=b(t);return jsxs(B,{className:"fk:border-red-700/40",children:[jsxs(X,{children:[jsx(XCircleIcon,{className:"fk:size-3.5 fk:text-red-700"}),jsx("span",{children:"Turn failed"})]}),jsx("p",{className:"fk:whitespace-pre-wrap fk:text-xs",children:s.message})]})}if(t.type==="data-mutation-approval"){let s=b(t);return Be(s)?jsx(er,{message:s}):jsx(Gs,{api:e,message:s})}return t.type==="data-user-question"?jsx(Zs,{data:b(t)}):t.type==="data-bulk-graphql-action"?jsx(tr,{message:b(t)}):t.type===Ge?a.slice(n+1).find(r=>r.type===Ge)?null:jsx(Ds,{parts:a}):t.type.startsWith("data-")?jsx(nr,{part:t}):null}function Us({part:e}){return jsx(qb,{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 qs({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 Bs=1e3;function Xs({text:e}){let t=useRef(typeof performance>"u"?0:performance.now()),n=()=>-(((typeof performance>"u"?0:performance.now())-t.current)%Bs),[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 Js=1e3;function Qs(e,t){let n=Js,[a,s]=useState(e),r=useRef(Date.now()),i=useRef(e);return i.current=e,useEffect(()=>{if(e===a)return;let d=Math.max(0,n-(Date.now()-r.current)),u=window.setTimeout(()=>{r.current=Date.now(),s(i.current);},d);return ()=>{window.clearTimeout(u);}},[a,e,n]),a}function oi({label:e,visible:t}){let n=Qs(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(Xs,{text:n})})}function B({children:e,className:t=""}){return jsx("div",{className:`fk:min-w-0 fk:max-w-full fk:overflow-x-auto fk:rounded-xl fk:border fk:border-border fk:bg-background fk:px-3.5 fk:py-3 fk:text-sm ${t} fk:corner-squircle`,children:e})}function X({children:e}){return jsx("div",{className:"fk:flex fk:items-center fk:gap-2 fk:font-medium fk:text-muted-foreground",children:e})}function ze({isError:e,loading:t}){return t?jsx(LoaderCircle,{className:"fk:size-4 fk:animate-spin"}):e?jsx(XIcon,{className:"fk:size-4 fk:text-red-700"}):jsx(CheckIcon,{className:"fk:size-4"})}function _e({error:e,icon:t,loading:n,message:a,title:s}){return jsxs(B,{children:[jsxs(X,{children:[t,s]}),jsxs("div",{className:"fk:relative fk:min-h-5 fk:pl-6",children:[jsx("span",{className:"fk:absolute fk:left-0 fk:top-0",children:jsx(ze,{isError:!!e,loading:n})}),jsx("span",{className:"fk:text-xs",children:a})]})]})}function Hs({message:e}){let t=["error","uploading","generating"].includes(e.status),n=t?e.paths.slice(0,e.paths.length-1):e.paths,a=t?e.paths[e.paths.length-1]??"":null;return jsxs(B,{children:[jsxs(X,{children:[jsx(CloudUploadIcon,{className:"fk:size-3.5"}),jsx("span",{children:e.status==="done"?"Uploaded files":"Generating files"})]}),jsxs("div",{className:"fk:space-y-1 fk:text-sm",children:[n.map((s,r)=>jsxs("div",{className:"fk:flex fk:items-center fk:gap-2",children:[jsx(CheckIcon,{className:"fk:size-4"}),jsx("span",{className:"fk:whitespace-pre-wrap",children:s})]},`${s}-${r.toString()}`)),typeof a=="string"?jsxs("div",{className:"fk:flex fk:items-center fk:gap-2",children:[jsx(ze,{isError:e.status==="error",loading:e.status!=="error"}),jsx("span",{children:e.status==="error"?e.error?.message??a:a})]}):null]})]})}function Ks({api:e,message:t}){let n=t.status==="done"&&t.artifactId,a=n?e.getArtifactUrl(t.artifactId??""):"",s=n?e.getArtifactUrl(t.artifactId??"",{download:true}):"",r=ar(t.sizeBytes);return jsxs(B,{children:[jsxs(X,{children:[jsx(FileTextIcon,{className:"fk:size-3.5"}),t.kind==="csv"||t.kind==="json"?"Exported file":t.status==="done"?"Published artifact":"Publishing artifact"]}),jsxs("div",{className:"fk:relative fk:min-h-5 fk:pl-6",children:[jsx("span",{className:"fk:absolute fk:left-0 fk:top-0",children:jsx(ze,{isError:t.status==="error",loading:t.status==="uploading"})}),jsxs("div",{className:"fk:min-w-0 fk:space-y-2",children:[jsxs("div",{className:"fk:min-w-0",children:[jsx("div",{className:"fk:truncate fk:font-medium",children:t.filename}),jsxs("div",{className:"fk:text-xs fk:text-muted-foreground",children:[t.status==="uploading"&&"Uploading to artifacts",t.status==="done"&&[sr(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(b$3,{asChild:true,size:"sm",variant:"outline",children:jsx("a",{href:a,rel:"noreferrer",target:"_blank",children:"Preview"})}),jsx(b$3,{asChild:true,size:"sm",variant:"outline",children:jsxs("a",{href:s,children:[jsx(DownloadIcon,{className:"fk:size-3"}),"Download"]})}),t.url?jsx(b$3,{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 Ys({message:e}){let t=e.provider==="slack"?"Slack":"Microsoft Teams",n=e.provider==="slack"?jsx(MessageSquareIcon,{className:"fk:size-3.5"}):jsx(SendIcon,{className:"fk:size-3.5"});return jsx(_e,{error:e.error?.message,icon:n,loading:e.status==="loading",message:e.status==="error"?e.error?.message??`Failed to send result to ${e.channelName}`:`${e.status==="done"?"Sent":"Sending"} result to ${e.channelName}`,title:`${t} Delivery`})}function Vs({message:e}){let{currentProjectId:t}=f(),n=useMemo(()=>bn(e.results),[e.results]);return e.status==="error"?jsx(_e,{error:e.error?.message??"The knowledge search failed",icon:jsx(LibraryIcon,{className:"fk:size-3.5"}),loading:false,message:e.error?.message??"The knowledge search failed",title:"Knowledge search"}):jsxs(B,{children:[jsxs(X,{children:[jsx(LibraryIcon,{className:"fk:size-3.5"}),jsx("span",{children:"Knowledge search"})]}),jsx("p",{className:"fk:mt-1 fk:text-xs fk:text-muted-foreground",children:xn(e.query,n)}),n.length>0?jsxs(Gc,{className:"fk:mb-0 fk:mt-2",children:[jsxs(Hc,{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(Ic,{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 Ws({message:e}){let t=e.status==="success"?jsx(CheckCircle2Icon,{className:"fk:size-3.5 fk:text-green-700"}):e.status==="skipped"?jsx(CircleSlashIcon,{className:"fk:size-3.5"}):jsx(XCircleIcon,{className:"fk:size-3.5 fk:text-red-700"}),n=e.status==="success"?"Run completed":e.status==="skipped"?"Run skipped":"Run failed";return jsxs(B,{className:e.status==="failed"?"fk:border-red-700/40":"fk:border-green-700/40",children:[jsxs(X,{children:[t,jsx("span",{children:n})]}),e.status==="failed"?jsx("p",{className:"fk:whitespace-pre-wrap fk:text-xs",children:e.summary}):null]})}function Gs({api:e,message:t}){let{projectId:n}=Is(),a=useContext(En),s=useContext(Es),r=useRef(void 0),{data:i,error:d,isValidating:u,mutate:f}=Ua(n?g(n).approval(t.approvalId):null,f$1,{refreshInterval:g=>t.status!=="pending"||g?.approval?.status&&g.approval.status!=="pending"?0:Dn}),c=i?.approval?.status,p=(c??t.status)==="pending",x=i?.approval?.kind==="schema"&&i.approval.status==="approved";useEffect(()=>{!x||!n||Ne({approvalId:t.approvalId,approvalUrl:g(n).approval(t.approvalId),projectId:n});},[x,t.approvalId,n]),useEffect(()=>{f();},[t.status,f]),useEffect(()=>{let g=r.current;r.current=c,!(t.status!=="pending"||!c||c==="pending")&&g==="pending"&&a?.onApprovalDecided(i?.approval?.id??t.approvalId,c);},[c,i?.approval?.id,t.approvalId,t.status,a]);function v(g){g.status!=="pending"&&(r.current=g.status),f(),a?.onApprovalDecided(g.id,g.status);}let k;if(i?.approval)k=jsx(jt,{api:e,approval:i.approval,chat:s,onDecided:v},i.approval.status);else if(d&&!u){let g=d instanceof Error&&d.message?d.message:"Request failed";k=jsxs("div",{className:"fk:space-y-2",children:[jsxs("p",{className:"fk:text-xs fk:text-destructive",children:["Failed to load proposal ",t.operationsSummary,": ",g]}),jsx(b$3,{size:"sm",variant:"outline",onClick:()=>{f();},children:"Retry"})]});}else k=jsxs("div",{className:"fk:flex fk:items-center fk:gap-2 fk:text-xs fk:text-muted-foreground",children:[jsx(LoaderCircle,{className:"fk:size-3.5 fk:animate-spin"}),jsxs("span",{children:["Loading proposal ",t.operationsSummary,"..."]})]});return jsxs(B,{children:[jsxs(X,{children:[s?jsx(ShieldIcon,{className:"fk:size-3.5"}):jsx(DatabaseZapIcon,{className:"fk:size-3.5"}),s?"Approval request":"Mutation approval",p?jsx(LoaderCircle,{className:"fk:ml-1 fk:size-3.5 fk:animate-spin"}):null]}),jsx("div",{className:"fk:mt-2",children:k}),t.status==="error"&&t.error?jsx("p",{className:"fk:mt-2 fk:text-xs fk:text-destructive",children:t.error.message}):null]})}function Zs({data:e}){let t=useContext(En),n=e.questions.length>1;return jsxs(B,{children:[jsxs(X,{children:[jsx(MessageCircleQuestionIcon,{className:"fk:size-3.5"}),e.status==="pending"?n?"The agent has questions":"The agent has a question":n?"Questions":"Question"]}),jsx("div",{className:"fk:mt-3",children:jsx(yn,{answer:t?.answerQuestion,data:e},e.status)})]})}function er({message:e}){let t=e.operationsSummary.replace(/^Call /,"");return jsx(_e,{error:e.status==="error"?e.error?.message??"The call failed.":void 0,icon:jsx(ShieldCheckIcon,{className:"fk:size-3.5"}),loading:false,message:e.status==="error"?`${t}: ${e.error?.message??"The call failed."}`:`${t} \xB7 Auto-approved by Jev`,title:"Plugin call"})}function tr({message:e}){let t=[typeof e.processedItems=="number"?`${e.processedItems.toString()} processed`:"",typeof e.changedItems=="number"?`${e.changedItems.toString()} changed`:"",typeof e.failedItems=="number"?`${e.failedItems.toString()} failed`:"",typeof e.totalItems=="number"?`${e.totalItems.toString()} total`:""].filter(Boolean);return jsx(_e,{error:e.error?.message,icon:jsx(DatabaseZapIcon,{className:"fk:size-3.5"}),loading:e.status==="loading"||e.status==="running",message:e.status==="error"?e.error?.message??`Failed bulk ${e.operationName}`:`${e.status==="done"?"Completed":"Running"} ${e.operationName}${t.length>0?` (${t.join(", ")})`:""}`,title:"Bulk GraphQL action"})}function nr({part:e}){return jsxs(B,{className:"fk:bg-muted/30",children:[jsxs(X,{children:[jsx(CheckCircle2Icon,{className:"fk:size-3.5"}),e.type.replace(/^data-/,"").replaceAll("-"," ")]}),jsx("p",{className:"fk:text-xs fk:text-muted-foreground",children:"This run emitted a structured event that is not yet rendered by Studio."})]})}function ar(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 sr(e){return e.kind==="pdf"?"PDF artifact":e.kind==="html"?"HTML artifact":e.kind==="csv"?"CSV file":e.kind==="json"?"JSON file":"Artifact"}export{Es as A,ni as B,le as C,ai as D,si as E,ri as F,qs as G,oi as H,Gs as I,wt as a,Vn as b,jt as c,wr as d,Ie as e,ya as f,Xe as g,Ft as h,ba as i,Qe as j,xa as k,Kt as l,Kr as m,Yr as n,Vr as o,Wr as p,an as q,io as r,on as s,lo as t,Va as u,wo as v,So as w,Is as x,Dn as y,En as z};//# sourceMappingURL=chunk-T44KNWQD.js.map
|
|
10
|
-
//# sourceMappingURL=chunk-
|
|
9
|
+
`).every(n=>/^`{3,}[\w-]*$/.test(n.trim())):false}function Fs({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(an,{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 ri({api:e,part:t,partIndex:n,parts:a}){if(Ie(t))return null;if(me(t.type)){let s=De(t);return s?jsx(qs,{message:s}):null}if(t.type==="text")return Os(t.text)&&a.some(r=>r.type===Ge)?null:jsx(Us,{part:t});if(t.type==="data-knowledge-search")return jsx(Vs,{message:b(t)});if(t.type==="data-generating-files")return jsx(Hs,{message:b(t)});if(t.type==="data-run-artifact")return jsx(Ks,{api:e,message:b(t)});if(t.type==="data-tool-delivery")return jsx(Ys,{message:b(t)});if(t.type==="data-run-summary")return jsx(Ws,{message:b(t)});if(t.type==="data-subtask"){let s=b(t),r=s.status==="running"?`Running "${s.title}"`:s.status==="done"?`Completed "${s.title}"${typeof s.stepsUsed=="number"?` in ${s.stepsUsed.toString()} steps`:""}`:`"${s.title}" failed: ${s.error?.message??"unknown error"}`;return jsxs(B,{children:[jsxs(X,{children:[jsx(BotIcon,{className:"fk:size-3.5"}),"Subtask"]}),jsxs("div",{className:"fk:relative fk:min-h-5 fk:pl-6",children:[jsx("span",{className:"fk:absolute fk:left-0 fk:top-0",children:jsx(ze,{isError:s.status==="error",loading:s.status==="running"})}),jsx("span",{className:"fk:text-xs",children:r}),s.resultPreview?jsx("p",{className:"fk:mt-1 fk:text-xs fk:text-muted-foreground",children:s.resultPreview}):null]})]})}if(t.type==="data-mid-turn-message"){let s=b(t);return s.monitorEvent?jsx(on,{data:s.monitorEvent}):jsx(Fs,{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(gn,{connectionId:s.connectionId,pluginId:s.pluginId})}if(t.type==="data-suggested-prompt")return null;if(t.type==="data-turn-error"){let s=b(t);return jsxs(B,{className:"fk:border-red-700/40",children:[jsxs(X,{children:[jsx(XCircleIcon,{className:"fk:size-3.5 fk:text-red-700"}),jsx("span",{children:"Turn failed"})]}),jsx("p",{className:"fk:whitespace-pre-wrap fk:text-xs",children:s.message})]})}if(t.type==="data-mutation-approval"){let s=b(t);return Be(s)?jsx(er,{message:s}):jsx(Gs,{api:e,message:s})}return t.type==="data-user-question"?jsx(Zs,{data:b(t)}):t.type==="data-bulk-graphql-action"?jsx(tr,{message:b(t)}):t.type===Ge?a.slice(n+1).find(r=>r.type===Ge)?null:jsx(Ds,{parts:a}):t.type.startsWith("data-")?jsx(nr,{part:t}):null}function Us({part:e}){return jsx(qb,{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 qs({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 Bs=1e3;function Xs({text:e}){let t=useRef(typeof performance>"u"?0:performance.now()),n=()=>-(((typeof performance>"u"?0:performance.now())-t.current)%Bs),[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 Js=1e3;function Qs(e,t){let n=Js,[a,s]=useState(e),r=useRef(Date.now()),i=useRef(e);return i.current=e,useEffect(()=>{if(e===a)return;let d=Math.max(0,n-(Date.now()-r.current)),u=window.setTimeout(()=>{r.current=Date.now(),s(i.current);},d);return ()=>{window.clearTimeout(u);}},[a,e,n]),a}function oi({label:e,visible:t}){let n=Qs(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(Xs,{text:n})})}function B({children:e,className:t=""}){return jsx("div",{className:`fk:min-w-0 fk:max-w-full fk:overflow-x-auto fk:rounded-xl fk:border fk:border-border fk:bg-background fk:px-3.5 fk:py-3 fk:text-sm ${t} fk:corner-squircle`,children:e})}function X({children:e}){return jsx("div",{className:"fk:flex fk:items-center fk:gap-2 fk:font-medium fk:text-muted-foreground",children:e})}function ze({isError:e,loading:t}){return t?jsx(LoaderCircle,{className:"fk:size-4 fk:animate-spin"}):e?jsx(XIcon,{className:"fk:size-4 fk:text-red-700"}):jsx(CheckIcon,{className:"fk:size-4"})}function _e({error:e,icon:t,loading:n,message:a,title:s}){return jsxs(B,{children:[jsxs(X,{children:[t,s]}),jsxs("div",{className:"fk:relative fk:min-h-5 fk:pl-6",children:[jsx("span",{className:"fk:absolute fk:left-0 fk:top-0",children:jsx(ze,{isError:!!e,loading:n})}),jsx("span",{className:"fk:text-xs",children:a})]})]})}function Hs({message:e}){let t=["error","uploading","generating"].includes(e.status),n=t?e.paths.slice(0,e.paths.length-1):e.paths,a=t?e.paths[e.paths.length-1]??"":null;return jsxs(B,{children:[jsxs(X,{children:[jsx(CloudUploadIcon,{className:"fk:size-3.5"}),jsx("span",{children:e.status==="done"?"Uploaded files":"Generating files"})]}),jsxs("div",{className:"fk:space-y-1 fk:text-sm",children:[n.map((s,r)=>jsxs("div",{className:"fk:flex fk:items-center fk:gap-2",children:[jsx(CheckIcon,{className:"fk:size-4"}),jsx("span",{className:"fk:whitespace-pre-wrap",children:s})]},`${s}-${r.toString()}`)),typeof a=="string"?jsxs("div",{className:"fk:flex fk:items-center fk:gap-2",children:[jsx(ze,{isError:e.status==="error",loading:e.status!=="error"}),jsx("span",{children:e.status==="error"?e.error?.message??a:a})]}):null]})]})}function Ks({api:e,message:t}){let n=t.status==="done"&&t.artifactId,a=n?e.getArtifactUrl(t.artifactId??""):"",s=n?e.getArtifactUrl(t.artifactId??"",{download:true}):"",r=ar(t.sizeBytes);return jsxs(B,{children:[jsxs(X,{children:[jsx(FileTextIcon,{className:"fk:size-3.5"}),t.kind==="csv"||t.kind==="json"?"Exported file":t.status==="done"?"Published artifact":"Publishing artifact"]}),jsxs("div",{className:"fk:relative fk:min-h-5 fk:pl-6",children:[jsx("span",{className:"fk:absolute fk:left-0 fk:top-0",children:jsx(ze,{isError:t.status==="error",loading:t.status==="uploading"})}),jsxs("div",{className:"fk:min-w-0 fk:space-y-2",children:[jsxs("div",{className:"fk:min-w-0",children:[jsx("div",{className:"fk:truncate fk:font-medium",children:t.filename}),jsxs("div",{className:"fk:text-xs fk:text-muted-foreground",children:[t.status==="uploading"&&"Uploading to artifacts",t.status==="done"&&[sr(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(b$3,{asChild:true,size:"sm",variant:"outline",children:jsx("a",{href:a,rel:"noreferrer",target:"_blank",children:"Preview"})}),jsx(b$3,{asChild:true,size:"sm",variant:"outline",children:jsxs("a",{href:s,children:[jsx(DownloadIcon,{className:"fk:size-3"}),"Download"]})}),t.url?jsx(b$3,{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 Ys({message:e}){let t=e.provider==="slack"?"Slack":"Microsoft Teams",n=e.provider==="slack"?jsx(MessageSquareIcon,{className:"fk:size-3.5"}):jsx(SendIcon,{className:"fk:size-3.5"});return jsx(_e,{error:e.error?.message,icon:n,loading:e.status==="loading",message:e.status==="error"?e.error?.message??`Failed to send result to ${e.channelName}`:`${e.status==="done"?"Sent":"Sending"} result to ${e.channelName}`,title:`${t} Delivery`})}function Vs({message:e}){let{currentProjectId:t}=f(),n=useMemo(()=>bn(e.results),[e.results]);return e.status==="error"?jsx(_e,{error:e.error?.message??"The knowledge search failed",icon:jsx(LibraryIcon,{className:"fk:size-3.5"}),loading:false,message:e.error?.message??"The knowledge search failed",title:"Knowledge search"}):jsxs(B,{children:[jsxs(X,{children:[jsx(LibraryIcon,{className:"fk:size-3.5"}),jsx("span",{children:"Knowledge search"})]}),jsx("p",{className:"fk:mt-1 fk:text-xs fk:text-muted-foreground",children:xn(e.query,n)}),n.length>0?jsxs(Gc,{className:"fk:mb-0 fk:mt-2",children:[jsxs(Hc,{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(Ic,{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 Ws({message:e}){let t=e.status==="success"?jsx(CheckCircle2Icon,{className:"fk:size-3.5 fk:text-green-700"}):e.status==="skipped"?jsx(CircleSlashIcon,{className:"fk:size-3.5"}):jsx(XCircleIcon,{className:"fk:size-3.5 fk:text-red-700"}),n=e.status==="success"?"Run completed":e.status==="skipped"?"Run skipped":"Run failed";return jsxs(B,{className:e.status==="failed"?"fk:border-red-700/40":"fk:border-green-700/40",children:[jsxs(X,{children:[t,jsx("span",{children:n})]}),e.status==="failed"?jsx("p",{className:"fk:whitespace-pre-wrap fk:text-xs",children:e.summary}):null]})}function Gs({api:e,message:t}){let{projectId:n}=Is(),a=useContext(En),s=useContext(Es),r=useRef(void 0),{data:i,error:d,isValidating:u,mutate:f}=Ua(n?g(n).approval(t.approvalId):null,f$1,{refreshInterval:g=>t.status!=="pending"||g?.approval?.status&&g.approval.status!=="pending"?0:Dn}),c=i?.approval?.status,p=(c??t.status)==="pending",x=i?.approval?.kind==="schema"&&i.approval.status==="approved";useEffect(()=>{!x||!n||Ne({approvalId:t.approvalId,approvalUrl:g(n).approval(t.approvalId),projectId:n});},[x,t.approvalId,n]),useEffect(()=>{f();},[t.status,f]),useEffect(()=>{let g=r.current;r.current=c,!(t.status!=="pending"||!c||c==="pending")&&g==="pending"&&a?.onApprovalDecided(i?.approval?.id??t.approvalId,c);},[c,i?.approval?.id,t.approvalId,t.status,a]);function v(g){g.status!=="pending"&&(r.current=g.status),f(),a?.onApprovalDecided(g.id,g.status);}let k;if(i?.approval)k=jsx(jt,{api:e,approval:i.approval,chat:s,onDecided:v},i.approval.status);else if(d&&!u){let g=d instanceof Error&&d.message?d.message:"Request failed";k=jsxs("div",{className:"fk:space-y-2",children:[jsxs("p",{className:"fk:text-xs fk:text-destructive",children:["Failed to load proposal ",t.operationsSummary,": ",g]}),jsx(b$3,{size:"sm",variant:"outline",onClick:()=>{f();},children:"Retry"})]});}else k=jsxs("div",{className:"fk:flex fk:items-center fk:gap-2 fk:text-xs fk:text-muted-foreground",children:[jsx(LoaderCircle,{className:"fk:size-3.5 fk:animate-spin"}),jsxs("span",{children:["Loading proposal ",t.operationsSummary,"..."]})]});return jsxs(B,{children:[jsxs(X,{children:[s?jsx(ShieldIcon,{className:"fk:size-3.5"}):jsx(DatabaseZapIcon,{className:"fk:size-3.5"}),s?"Approval request":"Mutation approval",p?jsx(LoaderCircle,{className:"fk:ml-1 fk:size-3.5 fk:animate-spin"}):null]}),jsx("div",{className:"fk:mt-2",children:k}),t.status==="error"&&t.error?jsx("p",{className:"fk:mt-2 fk:text-xs fk:text-destructive",children:t.error.message}):null]})}function Zs({data:e}){let t=useContext(En),n=e.questions.length>1;return jsxs(B,{children:[jsxs(X,{children:[jsx(MessageCircleQuestionIcon,{className:"fk:size-3.5"}),e.status==="pending"?n?"The agent has questions":"The agent has a question":n?"Questions":"Question"]}),jsx("div",{className:"fk:mt-3",children:jsx(yn,{answer:t?.answerQuestion,data:e},e.status)})]})}function er({message:e}){let t=e.operationsSummary.replace(/^Call /,"");return jsx(_e,{error:e.status==="error"?e.error?.message??"The call failed.":void 0,icon:jsx(ShieldCheckIcon,{className:"fk:size-3.5"}),loading:false,message:e.status==="error"?`${t}: ${e.error?.message??"The call failed."}`:`${t} \xB7 Auto-approved by Jev`,title:"Plugin call"})}function tr({message:e}){let t=[typeof e.processedItems=="number"?`${e.processedItems.toString()} processed`:"",typeof e.changedItems=="number"?`${e.changedItems.toString()} changed`:"",typeof e.failedItems=="number"?`${e.failedItems.toString()} failed`:"",typeof e.totalItems=="number"?`${e.totalItems.toString()} total`:""].filter(Boolean);return jsx(_e,{error:e.error?.message,icon:jsx(DatabaseZapIcon,{className:"fk:size-3.5"}),loading:e.status==="loading"||e.status==="running",message:e.status==="error"?e.error?.message??`Failed bulk ${e.operationName}`:`${e.status==="done"?"Completed":"Running"} ${e.operationName}${t.length>0?` (${t.join(", ")})`:""}`,title:"Bulk GraphQL action"})}function nr({part:e}){return jsxs(B,{className:"fk:bg-muted/30",children:[jsxs(X,{children:[jsx(CheckCircle2Icon,{className:"fk:size-3.5"}),e.type.replace(/^data-/,"").replaceAll("-"," ")]}),jsx("p",{className:"fk:text-xs fk:text-muted-foreground",children:"This run emitted a structured event that is not yet rendered by Studio."})]})}function ar(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 sr(e){return e.kind==="pdf"?"PDF artifact":e.kind==="html"?"HTML artifact":e.kind==="csv"?"CSV file":e.kind==="json"?"JSON file":"Artifact"}export{Es as A,ni as B,le as C,ai as D,si as E,ri as F,qs as G,oi as H,Gs as I,wt as a,Vn as b,jt as c,wr as d,Ie as e,ya as f,Xe as g,Ft as h,ba as i,Qe as j,xa as k,Kt as l,Kr as m,Yr as n,Vr as o,Wr as p,an as q,io as r,on as s,lo as t,Va as u,wo as v,So as w,Is as x,Dn as y,En as z};//# sourceMappingURL=chunk-LF4B2TQI.js.map
|
|
10
|
+
//# sourceMappingURL=chunk-LF4B2TQI.js.map
|