@databricks/appkit-ui 0.94.1 → 0.96.0

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.
@@ -1,12 +1,17 @@
1
1
  import { METRIC_CONFIG_FILE } from "../../schemas/metric-fqn.js";
2
- import { acquireSpawnLock, getSpawnLockPath, releaseSpawnLock } from "./spawn-lock.js";
2
+ import { acquireSpawnLock, getSpawnLockPath, releaseSpawnLock, spawnLockStaleMsFor } from "./spawn-lock.js";
3
3
  import { spawn } from "node:child_process";
4
4
  import fs from "node:fs";
5
5
  import path from "node:path";
6
- import { Command, Option } from "commander";
6
+ import { Command, InvalidArgumentError, Option } from "commander";
7
7
 
8
8
  //#region src/cli/commands/generate-types.ts
9
9
  /**
10
+ * Env var for the warehouse wait limit, in seconds. Read by the type generator;
11
+ * the CLI only reads it to size the background worker's lock.
12
+ */
13
+ const WAIT_TIMEOUT_ENV = "APPKIT_TYPEGEN_WAIT_TIMEOUT";
14
+ /**
10
15
  * Resolve the typegen pre-flight mode for the CLI. Defaults to "non-blocking" —
11
16
  * a one-shot CLI can't describe in the background, so by default it never
12
17
  * describes at all: it skips the warehouse probe AND every DESCRIBE, emits
@@ -20,6 +25,26 @@ function resolveTypegenMode(options) {
20
25
  return options?.wait ? "blocking" : "non-blocking";
21
26
  }
22
27
  /**
28
+ * Parse `--wait-timeout <seconds>`: a non-negative number of seconds. `0` means
29
+ * "check the warehouse once, don't wait".
30
+ */
31
+ function parseWaitTimeoutSeconds(value) {
32
+ const seconds = Number(value);
33
+ if (value.trim() === "" || !Number.isFinite(seconds) || seconds < 0) throw new InvalidArgumentError("Expected a number of seconds (0 or more).");
34
+ return seconds;
35
+ }
36
+ /**
37
+ * The wait limit the background worker will use, in milliseconds, when one is
38
+ * configured (flag first, then env). `undefined` means the generator default.
39
+ */
40
+ function configuredWaitTimeoutMs(flagSeconds) {
41
+ if (flagSeconds !== void 0) return flagSeconds * 1e3;
42
+ const raw = process.env[WAIT_TIMEOUT_ENV]?.trim();
43
+ if (!raw) return void 0;
44
+ const seconds = Number(raw);
45
+ return Number.isFinite(seconds) && seconds >= 0 ? seconds * 1e3 : void 0;
46
+ }
47
+ /**
23
48
  * Generate types command implementation. Runs the library generate (which, in
24
49
  * non-blocking mode, writes degraded types and returns immediately). This is the
25
50
  * SAME work the worker performs in blocking mode in the background.
@@ -44,7 +69,8 @@ async function runGenerateTypes(rootDir, outFile, warehouseId, options) {
44
69
  outFile: resolvedOutFile,
45
70
  warehouseId: resolvedWarehouseId,
46
71
  noCache,
47
- mode
72
+ mode,
73
+ waitTimeoutMs: options?.waitTimeout === void 0 ? void 0 : options.waitTimeout * 1e3
48
74
  });
49
75
  if (hasQueries) console.log(`Generated query types: ${resolvedOutFile}`);
50
76
  const metricConfig = path.join(metricViewsFolder, METRIC_CONFIG_FILE);
@@ -121,6 +147,7 @@ function spawnTypegenWorker(lockPath, targets) {
121
147
  "--wait",
122
148
  "--worker-lock",
123
149
  lockPath,
150
+ ...targets.waitTimeout === void 0 ? [] : ["--wait-timeout", String(targets.waitTimeout)],
124
151
  ...positionals
125
152
  ];
126
153
  try {
@@ -159,21 +186,23 @@ async function generateTypesAction(rootDir, outFile, warehouseId, options) {
159
186
  }
160
187
  if (!isWorker && resolveTypegenMode(options) === "non-blocking") {
161
188
  const lockPath = getSpawnLockPath(rootDir || process.cwd());
162
- if (acquireSpawnLock(lockPath)) spawnTypegenWorker(lockPath, {
189
+ if (acquireSpawnLock(lockPath, spawnLockStaleMsFor(configuredWaitTimeoutMs(options.waitTimeout)))) spawnTypegenWorker(lockPath, {
163
190
  rootDir,
164
191
  outFile,
165
- warehouseId
192
+ warehouseId,
193
+ waitTimeout: options.waitTimeout
166
194
  });
167
195
  else console.log("Type refresh already in progress, skipping.");
168
196
  }
169
197
  }
170
- const generateTypesCommand = new Command("generate-types").description("Generate TypeScript types from AppKit configuration").argument("[rootDir]", "Root directory of the project", process.cwd()).argument("[outFile]", "Output file path", path.join(process.cwd(), "shared/appkit-types/analytics.d.ts")).argument("[warehouseId]", "Databricks warehouse ID").option("--no-cache", "Disable caching for type generation").option("--wait", "Wait for warehouse readiness instead of degrading (use for CI)").addOption(new Option("--worker-lock <path>", "Internal: detached worker lock path").hideHelp()).addHelpText("after", `
198
+ const generateTypesCommand = new Command("generate-types").description("Generate TypeScript types from AppKit configuration").argument("[rootDir]", "Root directory of the project", process.cwd()).argument("[outFile]", "Output file path", path.join(process.cwd(), "shared/appkit-types/analytics.d.ts")).argument("[warehouseId]", "Databricks warehouse ID").option("--no-cache", "Disable caching for type generation").option("--wait", "Wait for warehouse readiness instead of degrading (use for CI)").option("--wait-timeout <seconds>", "With --wait: give up waiting for the warehouse after this many seconds, then keep committed types or fail (default: $APPKIT_TYPEGEN_WAIT_TIMEOUT, else 300)", parseWaitTimeoutSeconds).addOption(new Option("--worker-lock <path>", "Internal: detached worker lock path").hideHelp()).addHelpText("after", `
171
199
  Examples:
172
200
  $ appkit generate-types
173
201
  $ appkit generate-types . shared/appkit-types/analytics.d.ts
174
202
  $ appkit generate-types . shared/appkit-types/analytics.d.ts my-warehouse-id
175
203
  $ appkit generate-types --no-cache
176
- $ appkit generate-types --wait # CI: wait for the warehouse and fail on a cold one`).action(generateTypesAction);
204
+ $ appkit generate-types --wait # CI: wait for the warehouse and fail on a cold one
205
+ $ appkit generate-types --wait --wait-timeout 120 # give up on the warehouse after 2 minutes`).action(generateTypesAction);
177
206
 
178
207
  //#endregion
179
208
  export { generateTypesCommand };
@@ -1 +1 @@
1
- {"version":3,"file":"generate-types.js","names":[],"sources":["../../../src/cli/commands/generate-types.ts"],"sourcesContent":["import { spawn } from \"node:child_process\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\n\nimport { Command, Option } from \"commander\";\n\nimport { METRIC_CONFIG_FILE } from \"../../schemas/metric-fqn\";\nimport {\n acquireSpawnLock,\n getSpawnLockPath,\n releaseSpawnLock,\n} from \"./spawn-lock.js\";\n\n/**\n * Resolve the typegen pre-flight mode for the CLI. Defaults to \"non-blocking\" —\n * a one-shot CLI can't describe in the background, so by default it never\n * describes at all: it skips the warehouse probe AND every DESCRIBE, emits\n * best-available types (cache where the SQL hash matches, else `result: unknown`)\n * and returns immediately, never blocking on — or failing because of — a\n * warehouse, even a RUNNING one. Pass `--wait` (commander sets `wait: true`)\n * for a deliberate/CI invocation that should wait for a starting warehouse and\n * fail fast on a stopped one.\n */\nexport function resolveTypegenMode(options?: {\n wait?: boolean;\n}): \"non-blocking\" | \"blocking\" {\n return options?.wait ? \"blocking\" : \"non-blocking\";\n}\n\n/** Options parsed by commander for the generate-types command. */\ninterface GenerateTypesOptions {\n noCache?: boolean;\n wait?: boolean;\n /**\n * Internal: present only on the detached worker invocation. Carries the path\n * of the single-flight lock this worker must release when it finishes. Its\n * presence is what marks an invocation as \"the worker\" — workers always run\n * with `--wait`, so they never spawn another worker (only non-blocking runs\n * spawn), which terminates the recursion.\n */\n workerLock?: string;\n}\n\n/**\n * Generate types command implementation. Runs the library generate (which, in\n * non-blocking mode, writes degraded types and returns immediately). This is the\n * SAME work the worker performs in blocking mode in the background.\n */\nasync function runGenerateTypes(\n rootDir?: string,\n outFile?: string,\n warehouseId?: string,\n options?: GenerateTypesOptions,\n) {\n try {\n const resolvedRootDir = rootDir || process.cwd();\n const noCache = options?.noCache || false;\n const mode = resolveTypegenMode(options);\n\n const typeGen = await import(\"@databricks/appkit/type-generator\");\n const resolvedOutFile =\n outFile || path.join(process.cwd(), \"shared/appkit-types/analytics.d.ts\");\n\n // Generate analytics query types (requires warehouse ID)\n const resolvedWarehouseId =\n warehouseId || process.env.DATABRICKS_WAREHOUSE_ID;\n\n if (resolvedWarehouseId) {\n const queryFolder = path.join(resolvedRootDir, \"config/queries\");\n const metricViewsFolder = path.join(\n resolvedRootDir,\n \"config/metric-views\",\n );\n const hasQueries = fs.existsSync(queryFolder);\n const hasMetricViews = fs.existsSync(metricViewsFolder);\n\n // Generate when either config surface exists. Metric-view types are\n // independent of `.sql` queries — an app can declare metric views in\n // `config/metric-views/` without a `config/queries/` folder.\n if (hasQueries || hasMetricViews) {\n await typeGen.generateFromEntryPoint({\n queryFolder: hasQueries ? queryFolder : undefined,\n metricViewsFolder: hasMetricViews ? metricViewsFolder : undefined,\n outFile: resolvedOutFile,\n warehouseId: resolvedWarehouseId,\n noCache,\n mode,\n });\n\n if (hasQueries) {\n console.log(`Generated query types: ${resolvedOutFile}`);\n }\n\n const metricConfig = path.join(metricViewsFolder, METRIC_CONFIG_FILE);\n if (fs.existsSync(metricConfig)) {\n const typesDir = path.dirname(resolvedOutFile);\n console.log(\n `Generated metric types: ${path.join(typesDir, \"metric-views.ts\")}`,\n );\n }\n }\n } else {\n console.error(\n \"Skipping query type generation: no warehouse ID. Set DATABRICKS_WAREHOUSE_ID or pass as argument.\",\n );\n }\n\n // Generate serving endpoint types (no warehouse required)\n const servingOutFile = path.join(\n process.cwd(),\n \"shared/appkit-types/serving.d.ts\",\n );\n await typeGen.generateServingTypes({\n outFile: servingOutFile,\n noCache,\n });\n console.log(`Generated serving types: ${servingOutFile}`);\n\n // Generate database declarations.\n const databaseSchemaFile = path.join(\n resolvedRootDir,\n \"config/database/schema.ts\",\n );\n const databaseOutFile = path.join(\n path.dirname(resolvedOutFile),\n typeGen.DATABASE_TYPES_FILE,\n );\n if (fs.existsSync(databaseSchemaFile) || fs.existsSync(databaseOutFile)) {\n await typeGen.generateDatabaseTypes({\n schemaFile: databaseSchemaFile,\n outFile: databaseOutFile,\n });\n console.log(`Generated database types: ${databaseOutFile}`);\n }\n } catch (error) {\n if (\n error instanceof Error &&\n error.message.includes(\"Cannot find module\")\n ) {\n console.error(\n \"Error: The 'generate-types' command is only available in @databricks/appkit.\",\n );\n console.error(\"Please install @databricks/appkit to use this command.\");\n process.exit(1);\n }\n // TypegenSyntaxError / TypegenFatalError carry a complete, actionable\n // message (which queries failed and how to debug them). The stack trace\n // points into appkit internals and is noise for app developers, so print\n // only the message and exit non-zero instead of letting it bubble up.\n if (\n error instanceof Error &&\n (error.name === \"TypegenSyntaxError\" ||\n error.name === \"TypegenFatalError\" ||\n error.name === \"DatabaseTypegenError\")\n ) {\n console.error(error.message);\n process.exit(1);\n }\n throw error;\n }\n}\n\n/**\n * Spawn the detached blocking worker that refreshes real types in the background\n * after the foreground non-blocking generate has already written degraded types.\n *\n * Re-invokes THIS CLI (`process.execPath` + `process.argv[1]` — the bin entry\n * that launched us) with `generate-types --wait --worker-lock <lockPath>` plus\n * the same positional target options the foreground used, so the worker writes\n * to the same out file / reads the same query folder. The worker is:\n * - `detached: true` + `.unref()` so it outlives this process (install/dev-setup\n * can finish and exit while the worker keeps warming the warehouse).\n * - `stdio: \"ignore\"` so it never holds the parent's pipes open or interleaves\n * output into the install/dev log.\n *\n * Spawning is wrapped so any failure is non-fatal: the caller still has degraded\n * types and exits 0.\n *\n * @param lockPath - the acquired single-flight lock; passed to the worker so it\n * releases the SAME lock when it finishes.\n * @param targets - the foreground's positional args, forwarded verbatim.\n * @returns true if the worker was spawned, false if spawning threw.\n */\nexport function spawnTypegenWorker(\n lockPath: string,\n targets: { rootDir?: string; outFile?: string; warehouseId?: string },\n): boolean {\n // The script the runtime launched us with (the `appkit` bin shim). Re-running\n // it under the same node binary reproduces this exact CLI in the worker.\n const cliEntry = process.argv[1];\n\n // Forward the positionals in declaration order (rootDir, outFile,\n // warehouseId). Stop at the first undefined so we never pass a literal\n // \"undefined\" — commander would treat it as a positional value. (rootDir is\n // effectively always set by commander's default, but guard anyway.)\n const positionals: string[] = [];\n for (const value of [targets.rootDir, targets.outFile, targets.warehouseId]) {\n if (value === undefined) break;\n positionals.push(value);\n }\n\n const args = [\n // Forward the parent's node/loader flags so the worker runs under the same\n // runtime. Critically this carries tsx's `--require`/`--import` when the CLI\n // is run from source (`tsx index.ts …`); without them the worker would be\n // `node index.ts …`, which can't parse TypeScript and dies silently — the\n // degraded types would then never refresh. Empty for the built bin (plain\n // `node bin/appkit.js`), so production behaviour is unchanged.\n ...process.execArgv,\n cliEntry,\n \"generate-types\",\n \"--wait\",\n \"--worker-lock\",\n lockPath,\n ...positionals,\n ];\n\n try {\n const child = spawn(process.execPath, args, {\n detached: true,\n stdio: \"ignore\",\n });\n child.unref();\n return true;\n } catch (error) {\n // Non-fatal: the foreground already wrote degraded types. Log and move on.\n console.error(\n `Could not start background type refresh: ${\n error instanceof Error ? error.message : String(error)\n }`,\n );\n return false;\n }\n}\n\n/**\n * The command action. Orchestrates the non-blocking foreground contract:\n * 1. Run the library generate (writes degraded types immediately in non-blocking\n * mode; does the full blocking lifecycle when this is the worker).\n * 2. If this is a non-blocking, non-worker invocation, try to spawn the detached\n * blocking worker behind the single-flight lock. If the lock is already held\n * by a live worker, skip (single-flight) with a one-line note. Either way the\n * foreground returns normally (exit 0).\n * 3. If this IS the worker (`--worker-lock` present), it ran blocking above and\n * releases the lock here (and via a process-exit guard, so a hard failure /\n * process.exit still frees it).\n */\nasync function generateTypesAction(\n rootDir: string | undefined,\n outFile: string | undefined,\n warehouseId: string | undefined,\n options: GenerateTypesOptions,\n) {\n const isWorker = typeof options.workerLock === \"string\";\n\n // A worker must always free its lock, even if the blocking generate throws or\n // calls process.exit (TypegenFatalError → exit 1). The exit handler covers the\n // process.exit / uncaught paths; the finally covers the normal return.\n if (isWorker && options.workerLock) {\n const lockPath = options.workerLock;\n process.once(\"exit\", () => releaseSpawnLock(lockPath));\n }\n\n try {\n await runGenerateTypes(rootDir, outFile, warehouseId, options);\n } finally {\n if (isWorker && options.workerLock) {\n releaseSpawnLock(options.workerLock);\n }\n }\n\n // Only a non-blocking, non-worker invocation spawns. A worker is always\n // --wait (so resolveTypegenMode → \"blocking\"), which both prevents recursion\n // and means we never get here for a worker.\n if (!isWorker && resolveTypegenMode(options) === \"non-blocking\") {\n const resolvedRootDir = rootDir || process.cwd();\n const lockPath = getSpawnLockPath(resolvedRootDir);\n\n if (acquireSpawnLock(lockPath)) {\n spawnTypegenWorker(lockPath, { rootDir, outFile, warehouseId });\n } else {\n console.log(\"Type refresh already in progress, skipping.\");\n }\n }\n}\n\nexport const generateTypesCommand = new Command(\"generate-types\")\n .description(\"Generate TypeScript types from AppKit configuration\")\n .argument(\"[rootDir]\", \"Root directory of the project\", process.cwd())\n .argument(\n \"[outFile]\",\n \"Output file path\",\n path.join(process.cwd(), \"shared/appkit-types/analytics.d.ts\"),\n )\n .argument(\"[warehouseId]\", \"Databricks warehouse ID\")\n .option(\"--no-cache\", \"Disable caching for type generation\")\n .option(\n \"--wait\",\n \"Wait for warehouse readiness instead of degrading (use for CI)\",\n )\n // Internal: marks the detached background worker and carries the lock it must\n // release. Hidden from --help; users should never pass it.\n .addOption(\n new Option(\n \"--worker-lock <path>\",\n \"Internal: detached worker lock path\",\n ).hideHelp(),\n )\n .addHelpText(\n \"after\",\n `\nExamples:\n $ appkit generate-types\n $ appkit generate-types . shared/appkit-types/analytics.d.ts\n $ appkit generate-types . shared/appkit-types/analytics.d.ts my-warehouse-id\n $ appkit generate-types --no-cache\n $ appkit generate-types --wait # CI: wait for the warehouse and fail on a cold one`,\n )\n .action(generateTypesAction);\n"],"mappings":";;;;;;;;;;;;;;;;;;AAuBA,SAAgB,mBAAmB,SAEH;AAC9B,QAAO,SAAS,OAAO,aAAa;;;;;;;AAsBtC,eAAe,iBACb,SACA,SACA,aACA,SACA;AACA,KAAI;EACF,MAAM,kBAAkB,WAAW,QAAQ,KAAK;EAChD,MAAM,UAAU,SAAS,WAAW;EACpC,MAAM,OAAO,mBAAmB,QAAQ;EAExC,MAAM,UAAU,MAAM,OAAO;EAC7B,MAAM,kBACJ,WAAW,KAAK,KAAK,QAAQ,KAAK,EAAE,qCAAqC;EAG3E,MAAM,sBACJ,eAAe,QAAQ,IAAI;AAE7B,MAAI,qBAAqB;GACvB,MAAM,cAAc,KAAK,KAAK,iBAAiB,iBAAiB;GAChE,MAAM,oBAAoB,KAAK,KAC7B,iBACA,sBACD;GACD,MAAM,aAAa,GAAG,WAAW,YAAY;GAC7C,MAAM,iBAAiB,GAAG,WAAW,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C,IAAI,OACF,wBACA,sCACD,CAAC,UAAU,CACb,CACA,YACC,SACA;;;;;;wFAOD,CACA,OAAO,oBAAoB"}
1
+ {"version":3,"file":"generate-types.js","names":[],"sources":["../../../src/cli/commands/generate-types.ts"],"sourcesContent":["import { spawn } from \"node:child_process\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\n\nimport { Command, InvalidArgumentError, Option } from \"commander\";\n\nimport { METRIC_CONFIG_FILE } from \"../../schemas/metric-fqn\";\nimport {\n acquireSpawnLock,\n getSpawnLockPath,\n releaseSpawnLock,\n spawnLockStaleMsFor,\n} from \"./spawn-lock.js\";\n\n/**\n * Env var for the warehouse wait limit, in seconds. Read by the type generator;\n * the CLI only reads it to size the background worker's lock.\n */\nconst WAIT_TIMEOUT_ENV = \"APPKIT_TYPEGEN_WAIT_TIMEOUT\";\n\n/**\n * Resolve the typegen pre-flight mode for the CLI. Defaults to \"non-blocking\" —\n * a one-shot CLI can't describe in the background, so by default it never\n * describes at all: it skips the warehouse probe AND every DESCRIBE, emits\n * best-available types (cache where the SQL hash matches, else `result: unknown`)\n * and returns immediately, never blocking on — or failing because of — a\n * warehouse, even a RUNNING one. Pass `--wait` (commander sets `wait: true`)\n * for a deliberate/CI invocation that should wait for a starting warehouse and\n * fail fast on a stopped one.\n */\nexport function resolveTypegenMode(options?: {\n wait?: boolean;\n}): \"non-blocking\" | \"blocking\" {\n return options?.wait ? \"blocking\" : \"non-blocking\";\n}\n\n/**\n * Parse `--wait-timeout <seconds>`: a non-negative number of seconds. `0` means\n * \"check the warehouse once, don't wait\".\n */\nexport function parseWaitTimeoutSeconds(value: string): number {\n const seconds = Number(value);\n if (value.trim() === \"\" || !Number.isFinite(seconds) || seconds < 0) {\n throw new InvalidArgumentError(\"Expected a number of seconds (0 or more).\");\n }\n return seconds;\n}\n\n/**\n * The wait limit the background worker will use, in milliseconds, when one is\n * configured (flag first, then env). `undefined` means the generator default.\n */\nfunction configuredWaitTimeoutMs(flagSeconds?: number): number | undefined {\n if (flagSeconds !== undefined) return flagSeconds * 1000;\n const raw = process.env[WAIT_TIMEOUT_ENV]?.trim();\n if (!raw) return undefined;\n const seconds = Number(raw);\n return Number.isFinite(seconds) && seconds >= 0 ? seconds * 1000 : undefined;\n}\n\n/** Options parsed by commander for the generate-types command. */\ninterface GenerateTypesOptions {\n noCache?: boolean;\n wait?: boolean;\n /**\n * `--wait-timeout <seconds>`: limit on waiting for the warehouse to reach\n * RUNNING under `--wait`. Unset → `APPKIT_TYPEGEN_WAIT_TIMEOUT`, else 5 min\n * (resolved by the type generator).\n */\n waitTimeout?: number;\n /**\n * Internal: present only on the detached worker invocation. Carries the path\n * of the single-flight lock this worker must release when it finishes. Its\n * presence is what marks an invocation as \"the worker\" — workers always run\n * with `--wait`, so they never spawn another worker (only non-blocking runs\n * spawn), which terminates the recursion.\n */\n workerLock?: string;\n}\n\n/**\n * Generate types command implementation. Runs the library generate (which, in\n * non-blocking mode, writes degraded types and returns immediately). This is the\n * SAME work the worker performs in blocking mode in the background.\n */\nasync function runGenerateTypes(\n rootDir?: string,\n outFile?: string,\n warehouseId?: string,\n options?: GenerateTypesOptions,\n) {\n try {\n const resolvedRootDir = rootDir || process.cwd();\n const noCache = options?.noCache || false;\n const mode = resolveTypegenMode(options);\n\n const typeGen = await import(\"@databricks/appkit/type-generator\");\n const resolvedOutFile =\n outFile || path.join(process.cwd(), \"shared/appkit-types/analytics.d.ts\");\n\n // Generate analytics query types (requires warehouse ID)\n const resolvedWarehouseId =\n warehouseId || process.env.DATABRICKS_WAREHOUSE_ID;\n\n if (resolvedWarehouseId) {\n const queryFolder = path.join(resolvedRootDir, \"config/queries\");\n const metricViewsFolder = path.join(\n resolvedRootDir,\n \"config/metric-views\",\n );\n const hasQueries = fs.existsSync(queryFolder);\n const hasMetricViews = fs.existsSync(metricViewsFolder);\n\n // Generate when either config surface exists. Metric-view types are\n // independent of `.sql` queries — an app can declare metric views in\n // `config/metric-views/` without a `config/queries/` folder.\n if (hasQueries || hasMetricViews) {\n await typeGen.generateFromEntryPoint({\n queryFolder: hasQueries ? queryFolder : undefined,\n metricViewsFolder: hasMetricViews ? metricViewsFolder : undefined,\n outFile: resolvedOutFile,\n warehouseId: resolvedWarehouseId,\n noCache,\n mode,\n waitTimeoutMs:\n options?.waitTimeout === undefined\n ? undefined\n : options.waitTimeout * 1000,\n });\n\n if (hasQueries) {\n console.log(`Generated query types: ${resolvedOutFile}`);\n }\n\n const metricConfig = path.join(metricViewsFolder, METRIC_CONFIG_FILE);\n if (fs.existsSync(metricConfig)) {\n const typesDir = path.dirname(resolvedOutFile);\n console.log(\n `Generated metric types: ${path.join(typesDir, \"metric-views.ts\")}`,\n );\n }\n }\n } else {\n console.error(\n \"Skipping query type generation: no warehouse ID. Set DATABRICKS_WAREHOUSE_ID or pass as argument.\",\n );\n }\n\n // Generate serving endpoint types (no warehouse required)\n const servingOutFile = path.join(\n process.cwd(),\n \"shared/appkit-types/serving.d.ts\",\n );\n await typeGen.generateServingTypes({\n outFile: servingOutFile,\n noCache,\n });\n console.log(`Generated serving types: ${servingOutFile}`);\n\n // Generate database declarations.\n const databaseSchemaFile = path.join(\n resolvedRootDir,\n \"config/database/schema.ts\",\n );\n const databaseOutFile = path.join(\n path.dirname(resolvedOutFile),\n typeGen.DATABASE_TYPES_FILE,\n );\n if (fs.existsSync(databaseSchemaFile) || fs.existsSync(databaseOutFile)) {\n await typeGen.generateDatabaseTypes({\n schemaFile: databaseSchemaFile,\n outFile: databaseOutFile,\n });\n console.log(`Generated database types: ${databaseOutFile}`);\n }\n } catch (error) {\n if (\n error instanceof Error &&\n error.message.includes(\"Cannot find module\")\n ) {\n console.error(\n \"Error: The 'generate-types' command is only available in @databricks/appkit.\",\n );\n console.error(\"Please install @databricks/appkit to use this command.\");\n process.exit(1);\n }\n // TypegenSyntaxError / TypegenFatalError carry a complete, actionable\n // message (which queries failed and how to debug them). The stack trace\n // points into appkit internals and is noise for app developers, so print\n // only the message and exit non-zero instead of letting it bubble up.\n if (\n error instanceof Error &&\n (error.name === \"TypegenSyntaxError\" ||\n error.name === \"TypegenFatalError\" ||\n error.name === \"DatabaseTypegenError\")\n ) {\n console.error(error.message);\n process.exit(1);\n }\n throw error;\n }\n}\n\n/**\n * Spawn the detached blocking worker that refreshes real types in the background\n * after the foreground non-blocking generate has already written degraded types.\n *\n * Re-invokes THIS CLI (`process.execPath` + `process.argv[1]` — the bin entry\n * that launched us) with `generate-types --wait --worker-lock <lockPath>` plus\n * the same positional target options the foreground used, so the worker writes\n * to the same out file / reads the same query folder. The worker is:\n * - `detached: true` + `.unref()` so it outlives this process (install/dev-setup\n * can finish and exit while the worker keeps warming the warehouse).\n * - `stdio: \"ignore\"` so it never holds the parent's pipes open or interleaves\n * output into the install/dev log.\n *\n * Spawning is wrapped so any failure is non-fatal: the caller still has degraded\n * types and exits 0.\n *\n * @param lockPath - the acquired single-flight lock; passed to the worker so it\n * releases the SAME lock when it finishes.\n * @param targets - the foreground's positional args, forwarded verbatim.\n * @returns true if the worker was spawned, false if spawning threw.\n */\nexport function spawnTypegenWorker(\n lockPath: string,\n targets: {\n rootDir?: string;\n outFile?: string;\n warehouseId?: string;\n waitTimeout?: number;\n },\n): boolean {\n // The script the runtime launched us with (the `appkit` bin shim). Re-running\n // it under the same node binary reproduces this exact CLI in the worker.\n const cliEntry = process.argv[1];\n\n // Forward the positionals in declaration order (rootDir, outFile,\n // warehouseId). Stop at the first undefined so we never pass a literal\n // \"undefined\" — commander would treat it as a positional value. (rootDir is\n // effectively always set by commander's default, but guard anyway.)\n const positionals: string[] = [];\n for (const value of [targets.rootDir, targets.outFile, targets.warehouseId]) {\n if (value === undefined) break;\n positionals.push(value);\n }\n\n const args = [\n // Forward the parent's node/loader flags so the worker runs under the same\n // runtime. Critically this carries tsx's `--require`/`--import` when the CLI\n // is run from source (`tsx index.ts …`); without them the worker would be\n // `node index.ts …`, which can't parse TypeScript and dies silently — the\n // degraded types would then never refresh. Empty for the built bin (plain\n // `node bin/appkit.js`), so production behaviour is unchanged.\n ...process.execArgv,\n cliEntry,\n \"generate-types\",\n \"--wait\",\n \"--worker-lock\",\n lockPath,\n ...(targets.waitTimeout === undefined\n ? []\n : [\"--wait-timeout\", String(targets.waitTimeout)]),\n ...positionals,\n ];\n\n try {\n const child = spawn(process.execPath, args, {\n detached: true,\n stdio: \"ignore\",\n });\n child.unref();\n return true;\n } catch (error) {\n // Non-fatal: the foreground already wrote degraded types. Log and move on.\n console.error(\n `Could not start background type refresh: ${\n error instanceof Error ? error.message : String(error)\n }`,\n );\n return false;\n }\n}\n\n/**\n * The command action. Orchestrates the non-blocking foreground contract:\n * 1. Run the library generate (writes degraded types immediately in non-blocking\n * mode; does the full blocking lifecycle when this is the worker).\n * 2. If this is a non-blocking, non-worker invocation, try to spawn the detached\n * blocking worker behind the single-flight lock. If the lock is already held\n * by a live worker, skip (single-flight) with a one-line note. Either way the\n * foreground returns normally (exit 0).\n * 3. If this IS the worker (`--worker-lock` present), it ran blocking above and\n * releases the lock here (and via a process-exit guard, so a hard failure /\n * process.exit still frees it).\n */\nasync function generateTypesAction(\n rootDir: string | undefined,\n outFile: string | undefined,\n warehouseId: string | undefined,\n options: GenerateTypesOptions,\n) {\n const isWorker = typeof options.workerLock === \"string\";\n\n // A worker must always free its lock, even if the blocking generate throws or\n // calls process.exit (TypegenFatalError → exit 1). The exit handler covers the\n // process.exit / uncaught paths; the finally covers the normal return.\n if (isWorker && options.workerLock) {\n const lockPath = options.workerLock;\n process.once(\"exit\", () => releaseSpawnLock(lockPath));\n }\n\n try {\n await runGenerateTypes(rootDir, outFile, warehouseId, options);\n } finally {\n if (isWorker && options.workerLock) {\n releaseSpawnLock(options.workerLock);\n }\n }\n\n // Only a non-blocking, non-worker invocation spawns. A worker is always\n // --wait (so resolveTypegenMode → \"blocking\"), which both prevents recursion\n // and means we never get here for a worker.\n if (!isWorker && resolveTypegenMode(options) === \"non-blocking\") {\n const resolvedRootDir = rootDir || process.cwd();\n const lockPath = getSpawnLockPath(resolvedRootDir);\n\n const staleMs = spawnLockStaleMsFor(\n configuredWaitTimeoutMs(options.waitTimeout),\n );\n if (acquireSpawnLock(lockPath, staleMs)) {\n spawnTypegenWorker(lockPath, {\n rootDir,\n outFile,\n warehouseId,\n waitTimeout: options.waitTimeout,\n });\n } else {\n console.log(\"Type refresh already in progress, skipping.\");\n }\n }\n}\n\nexport const generateTypesCommand = new Command(\"generate-types\")\n .description(\"Generate TypeScript types from AppKit configuration\")\n .argument(\"[rootDir]\", \"Root directory of the project\", process.cwd())\n .argument(\n \"[outFile]\",\n \"Output file path\",\n path.join(process.cwd(), \"shared/appkit-types/analytics.d.ts\"),\n )\n .argument(\"[warehouseId]\", \"Databricks warehouse ID\")\n .option(\"--no-cache\", \"Disable caching for type generation\")\n .option(\n \"--wait\",\n \"Wait for warehouse readiness instead of degrading (use for CI)\",\n )\n .option(\n \"--wait-timeout <seconds>\",\n \"With --wait: give up waiting for the warehouse after this many seconds, then keep committed types or fail (default: $APPKIT_TYPEGEN_WAIT_TIMEOUT, else 300)\",\n parseWaitTimeoutSeconds,\n )\n // Internal: marks the detached background worker and carries the lock it must\n // release. Hidden from --help; users should never pass it.\n .addOption(\n new Option(\n \"--worker-lock <path>\",\n \"Internal: detached worker lock path\",\n ).hideHelp(),\n )\n .addHelpText(\n \"after\",\n `\nExamples:\n $ appkit generate-types\n $ appkit generate-types . shared/appkit-types/analytics.d.ts\n $ appkit generate-types . shared/appkit-types/analytics.d.ts my-warehouse-id\n $ appkit generate-types --no-cache\n $ appkit generate-types --wait # CI: wait for the warehouse and fail on a cold one\n $ appkit generate-types --wait --wait-timeout 120 # give up on the warehouse after 2 minutes`,\n )\n .action(generateTypesAction);\n"],"mappings":";;;;;;;;;;;;AAkBA,MAAM,mBAAmB;;;;;;;;;;;AAYzB,SAAgB,mBAAmB,SAEH;AAC9B,QAAO,SAAS,OAAO,aAAa;;;;;;AAOtC,SAAgB,wBAAwB,OAAuB;CAC7D,MAAM,UAAU,OAAO,MAAM;AAC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F,EAJc,MAAM,QAAQ,UAAU,MAAM;GAC1C,UAAU;GACV,OAAO;GACR,CAAC,CACI,OAAO;AACb,SAAO;UACA,OAAO;AAEd,UAAQ,MACN,4CACE,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM,GAEzD;AACD,SAAO;;;;;;;;;;;;;;;AAgBX,eAAe,oBACb,SACA,SACA,aACA,SACA;CACA,MAAM,WAAW,OAAO,QAAQ,eAAe;AAK/C,KAAI,YAAY,QAAQ,YAAY;EAClC,MAAM,WAAW,QAAQ;AACzB,UAAQ,KAAK,cAAc,iBAAiB,SAAS,CAAC;;AAGxD,KAAI;AACF,QAAM,iBAAiB,SAAS,SAAS,aAAa,QAAQ;WACtD;AACR,MAAI,YAAY,QAAQ,WACtB,kBAAiB,QAAQ,WAAW;;AAOxC,KAAI,CAAC,YAAY,mBAAmB,QAAQ,KAAK,gBAAgB;EAE/D,MAAM,WAAW,iBADO,WAAW,QAAQ,KAAK,CACE;AAKlD,MAAI,iBAAiB,UAHL,oBACd,wBAAwB,QAAQ,YAAY,CAC7C,CACsC,CACrC,oBAAmB,UAAU;GAC3B;GACA;GACA;GACA,aAAa,QAAQ;GACtB,CAAC;MAEF,SAAQ,IAAI,8CAA8C;;;AAKhE,MAAa,uBAAuB,IAAI,QAAQ,iBAAiB,CAC9D,YAAY,sDAAsD,CAClE,SAAS,aAAa,iCAAiC,QAAQ,KAAK,CAAC,CACrE,SACC,aACA,oBACA,KAAK,KAAK,QAAQ,KAAK,EAAE,qCAAqC,CAC/D,CACA,SAAS,iBAAiB,0BAA0B,CACpD,OAAO,cAAc,sCAAsC,CAC3D,OACC,UACA,iEACD,CACA,OACC,4BACA,+JACA,wBACD,CAGA,UACC,IAAI,OACF,wBACA,sCACD,CAAC,UAAU,CACb,CACA,YACC,SACA;;;;;;;kGAQD,CACA,OAAO,oBAAoB"}
@@ -8,12 +8,25 @@ import path from "node:path";
8
8
  * older than this the lock is presumed orphaned (the worker crashed/was killed
9
9
  * before it could release) and is stolen.
10
10
  *
11
- * Must comfortably exceed the worker's worst-case runtime: the blocking preflight
12
- * wait cap (PREFLIGHT_WAIT_MAX_MS = 5 min in the type-generator) plus a DESCRIBE
13
- * budget. Six minutes leaves ~1 min of headroom over a worker that waits the full
14
- * preflight window and then describes.
11
+ * Must comfortably exceed the worker's worst-case runtime: the default warehouse
12
+ * wait limit (5 min in the type-generator) plus a DESCRIBE budget. Six minutes
13
+ * leaves ~1 min of headroom over a worker that waits the full limit and then
14
+ * describes. A longer configured limit stretches it — see
15
+ * {@link spawnLockStaleMsFor}.
15
16
  */
16
17
  const SPAWN_LOCK_STALE_MS = 360 * 1e3;
18
+ /** Headroom over the wait limit for the worker's DESCRIBE work. */
19
+ const DESCRIBE_HEADROOM_MS = 60 * 1e3;
20
+ /**
21
+ * Staleness threshold for a worker that may wait up to `waitTimeoutMs` for the
22
+ * warehouse: never shorter than {@link SPAWN_LOCK_STALE_MS}, and always at
23
+ * least the limit plus describe headroom, so a live worker on a long limit
24
+ * isn't mistaken for an orphan.
25
+ */
26
+ function spawnLockStaleMsFor(waitTimeoutMs) {
27
+ if (waitTimeoutMs === void 0 || !Number.isFinite(waitTimeoutMs)) return SPAWN_LOCK_STALE_MS;
28
+ return Math.max(SPAWN_LOCK_STALE_MS, waitTimeoutMs + DESCRIBE_HEADROOM_MS);
29
+ }
17
30
  /**
18
31
  * Resolve the on-disk path of the single-flight spawn lock for a project.
19
32
  *
@@ -112,5 +125,5 @@ function isErrnoException(error) {
112
125
  }
113
126
 
114
127
  //#endregion
115
- export { acquireSpawnLock, getSpawnLockPath, releaseSpawnLock };
128
+ export { acquireSpawnLock, getSpawnLockPath, releaseSpawnLock, spawnLockStaleMsFor };
116
129
  //# sourceMappingURL=spawn-lock.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"spawn-lock.js","names":[],"sources":["../../../src/cli/commands/spawn-lock.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\n\n/**\n * How long a spawn lock is considered fresh. A held lock newer than this means a\n * background worker is genuinely in flight, so the foreground skips spawning;\n * older than this the lock is presumed orphaned (the worker crashed/was killed\n * before it could release) and is stolen.\n *\n * Must comfortably exceed the worker's worst-case runtime: the blocking preflight\n * wait cap (PREFLIGHT_WAIT_MAX_MS = 5 min in the type-generator) plus a DESCRIBE\n * budget. Six minutes leaves ~1 min of headroom over a worker that waits the full\n * preflight window and then describes.\n */\nexport const SPAWN_LOCK_STALE_MS = 6 * 60 * 1000;\n\n/**\n * Resolve the on-disk path of the single-flight spawn lock for a project.\n *\n * Lives alongside the type-generator cache (`node_modules/.databricks/appkit/`)\n * so it shares the same already-creatable, gitignored, per-project location and\n * doesn't introduce a new directory. The lock is keyed only by project root, so\n * concurrent `generate-types` invocations for the same project (postinstall +\n * predev, say) contend for one lock and only one wins the spawn.\n *\n * @param rootDir - project root (the resolved first CLI argument / cwd).\n * @returns absolute path to the lock file.\n */\nexport function getSpawnLockPath(rootDir: string): string {\n return path.join(\n rootDir,\n \"node_modules\",\n \".databricks\",\n \"appkit\",\n \".appkit-typegen-worker.lock\",\n );\n}\n\n/**\n * Try to acquire the single-flight spawn lock.\n *\n * Atomic create via `fs.writeFileSync(lockPath, ..., { flag: \"wx\" })` — `wx`\n * fails (EEXIST) if the file already exists, so the create itself is the\n * mutual-exclusion primitive (no check-then-create race between two foreground\n * processes). The lock body records pid + timestamp purely for debugging.\n *\n * On EEXIST we stat the existing lock:\n * - fresh (mtime within {@link staleMs}) → a worker is in flight, return false.\n * - stale (mtime older than staleMs) → presumed orphaned; unlink and recreate.\n * The recreate also uses `wx`, so if a competing process steals it first we\n * lose the race cleanly and return false.\n *\n * Any unexpected error (permission, ENOENT on a missing parent dir we couldn't\n * create, …) is swallowed and reported as \"not acquired\": failing to take the\n * lock must never break the foreground — at worst we skip the background refresh.\n *\n * @param lockPath - path returned by {@link getSpawnLockPath}.\n * @param staleMs - age beyond which a held lock is stolen. Defaults to\n * {@link SPAWN_LOCK_STALE_MS}.\n * @returns true if this caller now owns the lock (and must release it), false if\n * another live worker holds it or the lock couldn't be taken.\n */\nexport function acquireSpawnLock(\n lockPath: string,\n staleMs: number = SPAWN_LOCK_STALE_MS,\n): boolean {\n const body = `${process.pid} ${Date.now()}\\n`;\n\n try {\n fs.mkdirSync(path.dirname(lockPath), { recursive: true });\n } catch {\n // Parent dir creation is best-effort; the create below will surface any real\n // problem and we'll treat it as \"not acquired\".\n }\n\n try {\n fs.writeFileSync(lockPath, body, { flag: \"wx\" });\n return true;\n } catch (error) {\n if (!isErrnoException(error) || error.code !== \"EEXIST\") {\n // Unexpected failure — don't let lock IO break the foreground.\n return false;\n }\n }\n\n // Lock exists — decide fresh vs stale.\n let mtimeMs: number;\n try {\n mtimeMs = fs.statSync(lockPath).mtimeMs;\n } catch {\n // It vanished between the failed create and the stat (released by the\n // worker). Try once more to take it.\n return tryCreate(lockPath, body);\n }\n\n if (Date.now() - mtimeMs < staleMs) {\n // A worker is genuinely in flight.\n return false;\n }\n\n // Stale: steal it. Unlink (ignore ENOENT — someone else may have cleaned up)\n // then re-create with `wx` so we still lose cleanly to a racing stealer.\n try {\n fs.unlinkSync(lockPath);\n } catch (error) {\n if (isErrnoException(error) && error.code !== \"ENOENT\") {\n return false;\n }\n }\n return tryCreate(lockPath, body);\n}\n\n/**\n * Release the spawn lock. Unlink, ignoring ENOENT (already gone — e.g. it was\n * stolen as stale by another process, or never existed). Any other error is\n * swallowed: a failed release at worst leaves a stale lock that the next caller\n * will steal after {@link SPAWN_LOCK_STALE_MS}.\n *\n * @param lockPath - path returned by {@link getSpawnLockPath}.\n */\nexport function releaseSpawnLock(lockPath: string): void {\n try {\n fs.unlinkSync(lockPath);\n } catch {\n // ENOENT or any other error — releasing is best-effort.\n }\n}\n\n/**\n * Attempt an atomic `wx` create, returning whether it succeeded. EEXIST (a\n * racing creator beat us) and any other error map to false.\n */\nfunction tryCreate(lockPath: string, body: string): boolean {\n try {\n fs.writeFileSync(lockPath, body, { flag: \"wx\" });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Narrow an unknown caught value to a Node errno exception so `.code` is safe to\n * read.\n */\nfunction isErrnoException(error: unknown): error is NodeJS.ErrnoException {\n return error instanceof Error && \"code\" in error;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAcA,MAAa,sBAAsB,MAAS;;;;;;;;;;;;;AAc5C,SAAgB,iBAAiB,SAAyB;AACxD,QAAO,KAAK,KACV,SACA,gBACA,eACA,UACA,8BACD;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BH,SAAgB,iBACd,UACA,UAAkB,qBACT;CACT,MAAM,OAAO,GAAG,QAAQ,IAAI,GAAG,KAAK,KAAK,CAAC;AAE1C,KAAI;AACF,KAAG,UAAU,KAAK,QAAQ,SAAS,EAAE,EAAE,WAAW,MAAM,CAAC;SACnD;AAKR,KAAI;AACF,KAAG,cAAc,UAAU,MAAM,EAAE,MAAM,MAAM,CAAC;AAChD,SAAO;UACA,OAAO;AACd,MAAI,CAAC,iBAAiB,MAAM,IAAI,MAAM,SAAS,SAE7C,QAAO;;CAKX,IAAI;AACJ,KAAI;AACF,YAAU,GAAG,SAAS,SAAS,CAAC;SAC1B;AAGN,SAAO,UAAU,UAAU,KAAK;;AAGlC,KAAI,KAAK,KAAK,GAAG,UAAU,QAEzB,QAAO;AAKT,KAAI;AACF,KAAG,WAAW,SAAS;UAChB,OAAO;AACd,MAAI,iBAAiB,MAAM,IAAI,MAAM,SAAS,SAC5C,QAAO;;AAGX,QAAO,UAAU,UAAU,KAAK;;;;;;;;;;AAWlC,SAAgB,iBAAiB,UAAwB;AACvD,KAAI;AACF,KAAG,WAAW,SAAS;SACjB;;;;;;AASV,SAAS,UAAU,UAAkB,MAAuB;AAC1D,KAAI;AACF,KAAG,cAAc,UAAU,MAAM,EAAE,MAAM,MAAM,CAAC;AAChD,SAAO;SACD;AACN,SAAO;;;;;;;AAQX,SAAS,iBAAiB,OAAgD;AACxE,QAAO,iBAAiB,SAAS,UAAU"}
1
+ {"version":3,"file":"spawn-lock.js","names":[],"sources":["../../../src/cli/commands/spawn-lock.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\n\n/**\n * How long a spawn lock is considered fresh. A held lock newer than this means a\n * background worker is genuinely in flight, so the foreground skips spawning;\n * older than this the lock is presumed orphaned (the worker crashed/was killed\n * before it could release) and is stolen.\n *\n * Must comfortably exceed the worker's worst-case runtime: the default warehouse\n * wait limit (5 min in the type-generator) plus a DESCRIBE budget. Six minutes\n * leaves ~1 min of headroom over a worker that waits the full limit and then\n * describes. A longer configured limit stretches it — see\n * {@link spawnLockStaleMsFor}.\n */\nexport const SPAWN_LOCK_STALE_MS = 6 * 60 * 1000;\n\n/** Headroom over the wait limit for the worker's DESCRIBE work. */\nconst DESCRIBE_HEADROOM_MS = 60 * 1000;\n\n/**\n * Staleness threshold for a worker that may wait up to `waitTimeoutMs` for the\n * warehouse: never shorter than {@link SPAWN_LOCK_STALE_MS}, and always at\n * least the limit plus describe headroom, so a live worker on a long limit\n * isn't mistaken for an orphan.\n */\nexport function spawnLockStaleMsFor(waitTimeoutMs?: number): number {\n if (waitTimeoutMs === undefined || !Number.isFinite(waitTimeoutMs)) {\n return SPAWN_LOCK_STALE_MS;\n }\n return Math.max(SPAWN_LOCK_STALE_MS, waitTimeoutMs + DESCRIBE_HEADROOM_MS);\n}\n\n/**\n * Resolve the on-disk path of the single-flight spawn lock for a project.\n *\n * Lives alongside the type-generator cache (`node_modules/.databricks/appkit/`)\n * so it shares the same already-creatable, gitignored, per-project location and\n * doesn't introduce a new directory. The lock is keyed only by project root, so\n * concurrent `generate-types` invocations for the same project (postinstall +\n * predev, say) contend for one lock and only one wins the spawn.\n *\n * @param rootDir - project root (the resolved first CLI argument / cwd).\n * @returns absolute path to the lock file.\n */\nexport function getSpawnLockPath(rootDir: string): string {\n return path.join(\n rootDir,\n \"node_modules\",\n \".databricks\",\n \"appkit\",\n \".appkit-typegen-worker.lock\",\n );\n}\n\n/**\n * Try to acquire the single-flight spawn lock.\n *\n * Atomic create via `fs.writeFileSync(lockPath, ..., { flag: \"wx\" })` — `wx`\n * fails (EEXIST) if the file already exists, so the create itself is the\n * mutual-exclusion primitive (no check-then-create race between two foreground\n * processes). The lock body records pid + timestamp purely for debugging.\n *\n * On EEXIST we stat the existing lock:\n * - fresh (mtime within {@link staleMs}) → a worker is in flight, return false.\n * - stale (mtime older than staleMs) → presumed orphaned; unlink and recreate.\n * The recreate also uses `wx`, so if a competing process steals it first we\n * lose the race cleanly and return false.\n *\n * Any unexpected error (permission, ENOENT on a missing parent dir we couldn't\n * create, …) is swallowed and reported as \"not acquired\": failing to take the\n * lock must never break the foreground — at worst we skip the background refresh.\n *\n * @param lockPath - path returned by {@link getSpawnLockPath}.\n * @param staleMs - age beyond which a held lock is stolen. Defaults to\n * {@link SPAWN_LOCK_STALE_MS}.\n * @returns true if this caller now owns the lock (and must release it), false if\n * another live worker holds it or the lock couldn't be taken.\n */\nexport function acquireSpawnLock(\n lockPath: string,\n staleMs: number = SPAWN_LOCK_STALE_MS,\n): boolean {\n const body = `${process.pid} ${Date.now()}\\n`;\n\n try {\n fs.mkdirSync(path.dirname(lockPath), { recursive: true });\n } catch {\n // Parent dir creation is best-effort; the create below will surface any real\n // problem and we'll treat it as \"not acquired\".\n }\n\n try {\n fs.writeFileSync(lockPath, body, { flag: \"wx\" });\n return true;\n } catch (error) {\n if (!isErrnoException(error) || error.code !== \"EEXIST\") {\n // Unexpected failure — don't let lock IO break the foreground.\n return false;\n }\n }\n\n // Lock exists — decide fresh vs stale.\n let mtimeMs: number;\n try {\n mtimeMs = fs.statSync(lockPath).mtimeMs;\n } catch {\n // It vanished between the failed create and the stat (released by the\n // worker). Try once more to take it.\n return tryCreate(lockPath, body);\n }\n\n if (Date.now() - mtimeMs < staleMs) {\n // A worker is genuinely in flight.\n return false;\n }\n\n // Stale: steal it. Unlink (ignore ENOENT — someone else may have cleaned up)\n // then re-create with `wx` so we still lose cleanly to a racing stealer.\n try {\n fs.unlinkSync(lockPath);\n } catch (error) {\n if (isErrnoException(error) && error.code !== \"ENOENT\") {\n return false;\n }\n }\n return tryCreate(lockPath, body);\n}\n\n/**\n * Release the spawn lock. Unlink, ignoring ENOENT (already gone — e.g. it was\n * stolen as stale by another process, or never existed). Any other error is\n * swallowed: a failed release at worst leaves a stale lock that the next caller\n * will steal after {@link SPAWN_LOCK_STALE_MS}.\n *\n * @param lockPath - path returned by {@link getSpawnLockPath}.\n */\nexport function releaseSpawnLock(lockPath: string): void {\n try {\n fs.unlinkSync(lockPath);\n } catch {\n // ENOENT or any other error — releasing is best-effort.\n }\n}\n\n/**\n * Attempt an atomic `wx` create, returning whether it succeeded. EEXIST (a\n * racing creator beat us) and any other error map to false.\n */\nfunction tryCreate(lockPath: string, body: string): boolean {\n try {\n fs.writeFileSync(lockPath, body, { flag: \"wx\" });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Narrow an unknown caught value to a Node errno exception so `.code` is safe to\n * read.\n */\nfunction isErrnoException(error: unknown): error is NodeJS.ErrnoException {\n return error instanceof Error && \"code\" in error;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAeA,MAAa,sBAAsB,MAAS;;AAG5C,MAAM,uBAAuB,KAAK;;;;;;;AAQlC,SAAgB,oBAAoB,eAAgC;AAClE,KAAI,kBAAkB,UAAa,CAAC,OAAO,SAAS,cAAc,CAChE,QAAO;AAET,QAAO,KAAK,IAAI,qBAAqB,gBAAgB,qBAAqB;;;;;;;;;;;;;;AAe5E,SAAgB,iBAAiB,SAAyB;AACxD,QAAO,KAAK,KACV,SACA,gBACA,eACA,UACA,8BACD;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BH,SAAgB,iBACd,UACA,UAAkB,qBACT;CACT,MAAM,OAAO,GAAG,QAAQ,IAAI,GAAG,KAAK,KAAK,CAAC;AAE1C,KAAI;AACF,KAAG,UAAU,KAAK,QAAQ,SAAS,EAAE,EAAE,WAAW,MAAM,CAAC;SACnD;AAKR,KAAI;AACF,KAAG,cAAc,UAAU,MAAM,EAAE,MAAM,MAAM,CAAC;AAChD,SAAO;UACA,OAAO;AACd,MAAI,CAAC,iBAAiB,MAAM,IAAI,MAAM,SAAS,SAE7C,QAAO;;CAKX,IAAI;AACJ,KAAI;AACF,YAAU,GAAG,SAAS,SAAS,CAAC;SAC1B;AAGN,SAAO,UAAU,UAAU,KAAK;;AAGlC,KAAI,KAAK,KAAK,GAAG,UAAU,QAEzB,QAAO;AAKT,KAAI;AACF,KAAG,WAAW,SAAS;UAChB,OAAO;AACd,MAAI,iBAAiB,MAAM,IAAI,MAAM,SAAS,SAC5C,QAAO;;AAGX,QAAO,UAAU,UAAU,KAAK;;;;;;;;;;AAWlC,SAAgB,iBAAiB,UAAwB;AACvD,KAAI;AACF,KAAG,WAAW,SAAS;SACjB;;;;;;AASV,SAAS,UAAU,UAAkB,MAAuB;AAC1D,KAAI;AACF,KAAG,cAAc,UAAU,MAAM,EAAE,MAAM,MAAM,CAAC;AAChD,SAAO;SACD;AACN,SAAO;;;;;;;AAQX,SAAS,iBAAiB,OAAgD;AACxE,QAAO,iBAAiB,SAAS,UAAU"}
@@ -1 +1 @@
1
- {"version":3,"file":"genie-chat-message-list.d.ts","names":[],"sources":["../../../src/react/genie/genie-chat-message-list.tsx"],"mappings":";;;;UAaU,yBAAA;;EAER,QAAA,EAAU,gBAAA;EAFF;EAIR,MAAA,EAAQ,eAAA;;EAER,SAAA;EAJA;EAMA,eAAA;EAJA;EAMA,mBAAA;AAAA;;iBAiIc,oBAAA,CAAA;EACd,QAAA;EACA,MAAA;EACA,SAAA;EACA,eAAA;EACA;AAAA,GACC,yBAAA,GAAyB,kBAAA,CAAA,GAAA,CAAA,OAAA"}
1
+ {"version":3,"file":"genie-chat-message-list.d.ts","names":[],"sources":["../../../src/react/genie/genie-chat-message-list.tsx"],"mappings":";;;;UAaU,yBAAA;;EAER,QAAA,EAAU,gBAAA;EAFF;EAIR,MAAA,EAAQ,eAAA;;EAER,SAAA;EAJA;EAMA,eAAA;EAJA;EAMA,mBAAA;AAAA;;iBAkIc,oBAAA,CAAA;EACd,QAAA;EACA,MAAA;EACA,SAAA;EACA,eAAA;EACA;AAAA,GACC,yBAAA,GAAyB,kBAAA,CAAA,GAAA,CAAA,OAAA"}
@@ -11,6 +11,7 @@ import { jsx, jsxs } from "react/jsx-runtime";
11
11
  const STATUS_LABELS = {
12
12
  ASKING_AI: "Asking AI...",
13
13
  EXECUTING_QUERY: "Executing query...",
14
+ GENERATING_VISUALIZATION: "Generating visualization...",
14
15
  FILTERING_RESULTS: "Filtering results...",
15
16
  COMPLETED: "Done"
16
17
  };
@@ -121,7 +122,7 @@ function GenieChatMessageList({ messages, status, className, hasPreviousPage = f
121
122
  /* @__PURE__ */ jsx(Skeleton, { className: "h-12 w-2/3 self-end" })
122
123
  ]
123
124
  }),
124
- messages.filter((msg) => msg.role !== "assistant" || msg.content || msg.id !== "" && TERMINAL_STATUSES.has(msg.status)).map((msg) => /* @__PURE__ */ jsx(GenieChatMessage, { message: msg }, msg.id)),
125
+ messages.filter((msg) => msg.role !== "assistant" || msg.content || msg.reasoning?.length || msg.id !== "" && TERMINAL_STATUSES.has(msg.status)).map((msg) => /* @__PURE__ */ jsx(GenieChatMessage, { message: msg }, msg.id)),
125
126
  showStreamingIndicator && /* @__PURE__ */ jsxs("div", {
126
127
  className: "flex items-center gap-2 text-sm text-muted-foreground px-11",
127
128
  children: [/* @__PURE__ */ jsx(Spinner, { className: "h-3 w-3" }), /* @__PURE__ */ jsx("span", { children: formatStatus(lastMessage.status) })]
@@ -1 +1 @@
1
- {"version":3,"file":"genie-chat-message-list.js","names":[],"sources":["../../../src/react/genie/genie-chat-message-list.tsx"],"sourcesContent":["import { useEffect, useLayoutEffect, useRef } from \"react\";\n\nimport { cn } from \"../lib/utils\";\nimport { ScrollArea } from \"../ui/scroll-area\";\nimport { Skeleton } from \"../ui/skeleton\";\nimport { Spinner } from \"../ui/spinner\";\nimport { GenieChatMessage } from \"./genie-chat-message\";\nimport {\n type GenieChatStatus,\n type GenieMessageItem,\n TERMINAL_STATUSES,\n} from \"./types\";\n\ninterface GenieChatMessageListProps {\n /** Array of messages to display */\n messages: GenieMessageItem[];\n /** Current chat status (controls loading indicators and skeleton placeholders) */\n status: GenieChatStatus;\n /** Additional CSS class for the scroll area */\n className?: string;\n /** Whether a previous page of older messages exists */\n hasPreviousPage?: boolean;\n /** Callback to fetch the previous page of messages */\n onFetchPreviousPage?: () => void;\n}\n\nconst STATUS_LABELS: Record<string, string> = {\n ASKING_AI: \"Asking AI...\",\n EXECUTING_QUERY: \"Executing query...\",\n FILTERING_RESULTS: \"Filtering results...\",\n COMPLETED: \"Done\",\n};\n\nfunction formatStatus(status: string): string {\n return STATUS_LABELS[status] ?? status.replace(/_/g, \" \").toLowerCase();\n}\n\nfunction getViewport(scrollRef: React.RefObject<HTMLDivElement | null>) {\n return scrollRef.current?.querySelector<HTMLElement>(\n '[data-slot=\"scroll-area-viewport\"]',\n );\n}\n\n/**\n * Manages scroll position: scrolls to bottom on append/initial load,\n * preserves position when older messages are prepended.\n */\nfunction useScrollManagement(\n scrollRef: React.RefObject<HTMLDivElement | null>,\n messages: GenieMessageItem[],\n status: GenieChatStatus,\n) {\n const prevFirstMessageIdRef = useRef<string | null>(null);\n const prevScrollHeightRef = useRef(0);\n const prevMessageCountRef = useRef(0);\n\n // Keep prevScrollHeightRef fresh when async content (images, embeds)\n // changes the viewport height between renders.\n useEffect(() => {\n const viewport = getViewport(scrollRef);\n if (!viewport) return;\n\n const observer = new ResizeObserver(() => {\n prevScrollHeightRef.current = viewport.scrollHeight;\n });\n observer.observe(viewport);\n return () => observer.disconnect();\n }, [scrollRef]);\n\n useLayoutEffect(() => {\n const viewport = getViewport(scrollRef);\n if (!viewport) return;\n\n const count = messages.length;\n const countChanged = count !== prevMessageCountRef.current;\n prevMessageCountRef.current = count;\n\n // Nothing to do if message count didn't change (e.g. status-only transition)\n if (!countChanged) {\n prevScrollHeightRef.current = viewport.scrollHeight;\n return;\n }\n\n const firstMessageId = messages[0]?.id ?? null;\n const wasPrepend =\n prevFirstMessageIdRef.current !== null &&\n firstMessageId !== prevFirstMessageIdRef.current;\n\n if (wasPrepend && prevScrollHeightRef.current > 0) {\n // Older messages prepended — preserve scroll position\n const delta = viewport.scrollHeight - prevScrollHeightRef.current;\n viewport.scrollTop += delta;\n } else {\n // Messages appended or initial load — scroll to bottom\n viewport.scrollTop = viewport.scrollHeight;\n }\n\n prevFirstMessageIdRef.current = firstMessageId;\n prevScrollHeightRef.current = viewport.scrollHeight;\n }, [messages.length, status]);\n}\n\n/**\n * Observes a sentinel element at the top of the scroll area and triggers\n * `onFetchPreviousPage` when the user scrolls to the top (only if content overflows).\n * Returns a ref to attach to the sentinel element.\n */\nfunction useLoadOlderOnScroll(\n scrollRef: React.RefObject<HTMLDivElement | null>,\n shouldObserve: boolean,\n onFetchPreviousPage?: () => void,\n) {\n const sentinelRef = useRef<HTMLDivElement>(null);\n const onFetchPreviousPageRef = useRef(onFetchPreviousPage);\n onFetchPreviousPageRef.current = onFetchPreviousPage;\n\n useEffect(() => {\n const sentinel = sentinelRef.current;\n const viewport = getViewport(scrollRef);\n if (!sentinel || !viewport || !shouldObserve) return;\n\n // The observer fires synchronously on observe() if the sentinel is\n // already visible. We arm it on the next frame so that synchronous\n // initial fire is ignored, but a real intersection (user genuinely\n // at the top on a short conversation) triggers on subsequent frames.\n let armed = false;\n const frameId = requestAnimationFrame(() => {\n armed = true;\n });\n\n const observer = new IntersectionObserver(\n (entries) => {\n if (!armed) return;\n const isScrollable = viewport.scrollHeight > viewport.clientHeight;\n if (entries[0]?.isIntersecting && isScrollable) {\n onFetchPreviousPageRef.current?.();\n }\n },\n { root: viewport, threshold: 0 },\n );\n\n observer.observe(sentinel);\n return () => {\n cancelAnimationFrame(frameId);\n observer.disconnect();\n };\n }, [scrollRef, shouldObserve]);\n\n return sentinelRef;\n}\n\n/** Scrollable message list that renders Genie chat messages with auto-scroll, skeleton loaders, and a streaming indicator. */\nexport function GenieChatMessageList({\n messages,\n status,\n className,\n hasPreviousPage = false,\n onFetchPreviousPage,\n}: GenieChatMessageListProps) {\n const scrollRef = useRef<HTMLDivElement>(null);\n\n const sentinelRef = useLoadOlderOnScroll(\n scrollRef,\n hasPreviousPage && status !== \"loading-older\",\n onFetchPreviousPage,\n );\n useScrollManagement(scrollRef, messages, status);\n\n const lastMessage = messages[messages.length - 1];\n const showStreamingIndicator =\n status === \"streaming\" &&\n lastMessage?.role === \"assistant\" &&\n !lastMessage.content &&\n !TERMINAL_STATUSES.has(lastMessage.status);\n\n return (\n <ScrollArea\n ref={scrollRef}\n className={cn(\n \"flex-1 min-h-0 p-4 [&_[data-slot=scroll-area-viewport]>div]:!block\",\n className,\n )}\n >\n <div className=\"flex flex-col gap-4 min-w-0\">\n {hasPreviousPage && <div ref={sentinelRef} className=\"h-px\" />}\n\n {status === \"loading-older\" && (\n <div className=\"flex items-center justify-center gap-2 py-2\">\n <Spinner className=\"h-3 w-3\" />\n <span className=\"text-sm text-muted-foreground\">\n Loading older messages...\n </span>\n </div>\n )}\n\n {status === \"loading-history\" && messages.length === 0 && (\n <div className=\"flex flex-col gap-4\">\n <Skeleton className=\"h-12 w-3/4\" />\n <Skeleton className=\"h-20 w-4/5 self-start\" />\n <Skeleton className=\"h-12 w-2/3 self-end\" />\n </div>\n )}\n\n {messages\n .filter(\n (msg) =>\n msg.role !== \"assistant\" ||\n msg.content ||\n (msg.id !== \"\" && TERMINAL_STATUSES.has(msg.status)),\n )\n .map((msg) => (\n <GenieChatMessage key={msg.id} message={msg} />\n ))}\n\n {showStreamingIndicator && (\n <div className=\"flex items-center gap-2 text-sm text-muted-foreground px-11\">\n <Spinner className=\"h-3 w-3\" />\n <span>{formatStatus(lastMessage.status)}</span>\n </div>\n )}\n\n {messages.length === 0 && status === \"idle\" && (\n <div className=\"flex items-center justify-center h-full text-muted-foreground text-sm py-12\">\n Start a conversation by typing a question below.\n </div>\n )}\n </div>\n </ScrollArea>\n );\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C;IAGP,SACE,QACE,QACC,IAAI,SAAS,eACb,IAAI,WACH,IAAI,OAAO,MAAM,kBAAkB,IAAI,IAAI,OAAO,CACtD,CACA,KAAK,QACJ,oBAAC,oBAA8B,SAAS,OAAjB,IAAI,GAAoB,CAC/C;IAEH,0BACC,qBAAC;KAAI,WAAU;gBACb,oBAAC,WAAQ,WAAU,YAAY,EAC/B,oBAAC,oBAAM,aAAa,YAAY,OAAO,GAAQ;MAC3C;IAGP,SAAS,WAAW,KAAK,WAAW,UACnC,oBAAC;KAAI,WAAU;eAA8E;MAEvF;;IAEJ;GACK"}
1
+ {"version":3,"file":"genie-chat-message-list.js","names":[],"sources":["../../../src/react/genie/genie-chat-message-list.tsx"],"sourcesContent":["import { useEffect, useLayoutEffect, useRef } from \"react\";\n\nimport { cn } from \"../lib/utils\";\nimport { ScrollArea } from \"../ui/scroll-area\";\nimport { Skeleton } from \"../ui/skeleton\";\nimport { Spinner } from \"../ui/spinner\";\nimport { GenieChatMessage } from \"./genie-chat-message\";\nimport {\n type GenieChatStatus,\n type GenieMessageItem,\n TERMINAL_STATUSES,\n} from \"./types\";\n\ninterface GenieChatMessageListProps {\n /** Array of messages to display */\n messages: GenieMessageItem[];\n /** Current chat status (controls loading indicators and skeleton placeholders) */\n status: GenieChatStatus;\n /** Additional CSS class for the scroll area */\n className?: string;\n /** Whether a previous page of older messages exists */\n hasPreviousPage?: boolean;\n /** Callback to fetch the previous page of messages */\n onFetchPreviousPage?: () => void;\n}\n\nconst STATUS_LABELS: Record<string, string> = {\n ASKING_AI: \"Asking AI...\",\n EXECUTING_QUERY: \"Executing query...\",\n GENERATING_VISUALIZATION: \"Generating visualization...\",\n FILTERING_RESULTS: \"Filtering results...\",\n COMPLETED: \"Done\",\n};\n\nfunction formatStatus(status: string): string {\n return STATUS_LABELS[status] ?? status.replace(/_/g, \" \").toLowerCase();\n}\n\nfunction getViewport(scrollRef: React.RefObject<HTMLDivElement | null>) {\n return scrollRef.current?.querySelector<HTMLElement>(\n '[data-slot=\"scroll-area-viewport\"]',\n );\n}\n\n/**\n * Manages scroll position: scrolls to bottom on append/initial load,\n * preserves position when older messages are prepended.\n */\nfunction useScrollManagement(\n scrollRef: React.RefObject<HTMLDivElement | null>,\n messages: GenieMessageItem[],\n status: GenieChatStatus,\n) {\n const prevFirstMessageIdRef = useRef<string | null>(null);\n const prevScrollHeightRef = useRef(0);\n const prevMessageCountRef = useRef(0);\n\n // Keep prevScrollHeightRef fresh when async content (images, embeds)\n // changes the viewport height between renders.\n useEffect(() => {\n const viewport = getViewport(scrollRef);\n if (!viewport) return;\n\n const observer = new ResizeObserver(() => {\n prevScrollHeightRef.current = viewport.scrollHeight;\n });\n observer.observe(viewport);\n return () => observer.disconnect();\n }, [scrollRef]);\n\n useLayoutEffect(() => {\n const viewport = getViewport(scrollRef);\n if (!viewport) return;\n\n const count = messages.length;\n const countChanged = count !== prevMessageCountRef.current;\n prevMessageCountRef.current = count;\n\n // Nothing to do if message count didn't change (e.g. status-only transition)\n if (!countChanged) {\n prevScrollHeightRef.current = viewport.scrollHeight;\n return;\n }\n\n const firstMessageId = messages[0]?.id ?? null;\n const wasPrepend =\n prevFirstMessageIdRef.current !== null &&\n firstMessageId !== prevFirstMessageIdRef.current;\n\n if (wasPrepend && prevScrollHeightRef.current > 0) {\n // Older messages prepended — preserve scroll position\n const delta = viewport.scrollHeight - prevScrollHeightRef.current;\n viewport.scrollTop += delta;\n } else {\n // Messages appended or initial load — scroll to bottom\n viewport.scrollTop = viewport.scrollHeight;\n }\n\n prevFirstMessageIdRef.current = firstMessageId;\n prevScrollHeightRef.current = viewport.scrollHeight;\n }, [messages.length, status]);\n}\n\n/**\n * Observes a sentinel element at the top of the scroll area and triggers\n * `onFetchPreviousPage` when the user scrolls to the top (only if content overflows).\n * Returns a ref to attach to the sentinel element.\n */\nfunction useLoadOlderOnScroll(\n scrollRef: React.RefObject<HTMLDivElement | null>,\n shouldObserve: boolean,\n onFetchPreviousPage?: () => void,\n) {\n const sentinelRef = useRef<HTMLDivElement>(null);\n const onFetchPreviousPageRef = useRef(onFetchPreviousPage);\n onFetchPreviousPageRef.current = onFetchPreviousPage;\n\n useEffect(() => {\n const sentinel = sentinelRef.current;\n const viewport = getViewport(scrollRef);\n if (!sentinel || !viewport || !shouldObserve) return;\n\n // The observer fires synchronously on observe() if the sentinel is\n // already visible. We arm it on the next frame so that synchronous\n // initial fire is ignored, but a real intersection (user genuinely\n // at the top on a short conversation) triggers on subsequent frames.\n let armed = false;\n const frameId = requestAnimationFrame(() => {\n armed = true;\n });\n\n const observer = new IntersectionObserver(\n (entries) => {\n if (!armed) return;\n const isScrollable = viewport.scrollHeight > viewport.clientHeight;\n if (entries[0]?.isIntersecting && isScrollable) {\n onFetchPreviousPageRef.current?.();\n }\n },\n { root: viewport, threshold: 0 },\n );\n\n observer.observe(sentinel);\n return () => {\n cancelAnimationFrame(frameId);\n observer.disconnect();\n };\n }, [scrollRef, shouldObserve]);\n\n return sentinelRef;\n}\n\n/** Scrollable message list that renders Genie chat messages with auto-scroll, skeleton loaders, and a streaming indicator. */\nexport function GenieChatMessageList({\n messages,\n status,\n className,\n hasPreviousPage = false,\n onFetchPreviousPage,\n}: GenieChatMessageListProps) {\n const scrollRef = useRef<HTMLDivElement>(null);\n\n const sentinelRef = useLoadOlderOnScroll(\n scrollRef,\n hasPreviousPage && status !== \"loading-older\",\n onFetchPreviousPage,\n );\n useScrollManagement(scrollRef, messages, status);\n\n const lastMessage = messages[messages.length - 1];\n const showStreamingIndicator =\n status === \"streaming\" &&\n lastMessage?.role === \"assistant\" &&\n !lastMessage.content &&\n !TERMINAL_STATUSES.has(lastMessage.status);\n\n return (\n <ScrollArea\n ref={scrollRef}\n className={cn(\n \"flex-1 min-h-0 p-4 [&_[data-slot=scroll-area-viewport]>div]:!block\",\n className,\n )}\n >\n <div className=\"flex flex-col gap-4 min-w-0\">\n {hasPreviousPage && <div ref={sentinelRef} className=\"h-px\" />}\n\n {status === \"loading-older\" && (\n <div className=\"flex items-center justify-center gap-2 py-2\">\n <Spinner className=\"h-3 w-3\" />\n <span className=\"text-sm text-muted-foreground\">\n Loading older messages...\n </span>\n </div>\n )}\n\n {status === \"loading-history\" && messages.length === 0 && (\n <div className=\"flex flex-col gap-4\">\n <Skeleton className=\"h-12 w-3/4\" />\n <Skeleton className=\"h-20 w-4/5 self-start\" />\n <Skeleton className=\"h-12 w-2/3 self-end\" />\n </div>\n )}\n\n {messages\n .filter(\n (msg) =>\n msg.role !== \"assistant\" ||\n msg.content ||\n msg.reasoning?.length ||\n (msg.id !== \"\" && TERMINAL_STATUSES.has(msg.status)),\n )\n .map((msg) => (\n <GenieChatMessage key={msg.id} message={msg} />\n ))}\n\n {showStreamingIndicator && (\n <div className=\"flex items-center gap-2 text-sm text-muted-foreground px-11\">\n <Spinner className=\"h-3 w-3\" />\n <span>{formatStatus(lastMessage.status)}</span>\n </div>\n )}\n\n {messages.length === 0 && status === \"idle\" && (\n <div className=\"flex items-center justify-center h-full text-muted-foreground text-sm py-12\">\n Start a conversation by typing a question below.\n </div>\n )}\n </div>\n </ScrollArea>\n );\n}\n"],"mappings":";;;;;;;;;;AA0BA,MAAM,gBAAwC;CAC5C,WAAW;CACX,iBAAiB;CACjB,0BAA0B;CAC1B,mBAAmB;CACnB,WAAW;CACZ;AAED,SAAS,aAAa,QAAwB;AAC5C,QAAO,cAAc,WAAW,OAAO,QAAQ,MAAM,IAAI,CAAC,aAAa;;AAGzE,SAAS,YAAY,WAAmD;AACtE,QAAO,UAAU,SAAS,cACxB,uCACD;;;;;;AAOH,SAAS,oBACP,WACA,UACA,QACA;CACA,MAAM,wBAAwB,OAAsB,KAAK;CACzD,MAAM,sBAAsB,OAAO,EAAE;CACrC,MAAM,sBAAsB,OAAO,EAAE;AAIrC,iBAAgB;EACd,MAAM,WAAW,YAAY,UAAU;AACvC,MAAI,CAAC,SAAU;EAEf,MAAM,WAAW,IAAI,qBAAqB;AACxC,uBAAoB,UAAU,SAAS;IACvC;AACF,WAA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,SAAA;AAAA;;iBAQc,gBAAA,CAAA;EACd,OAAA;EACA;AAAA,GACC,qBAAA,GAAqB,kBAAA,CAAA,GAAA,CAAA,OAAA"}
1
+ {"version":3,"file":"genie-chat-message.d.ts","names":[],"sources":["../../../src/react/genie/genie-chat-message.tsx"],"mappings":";;;;UA6BU,qBAAA;;EAER,OAAA,EAAS,gBAAA;EAFD;EAIR,SAAA;AAAA;;iBA4Bc,gBAAA,CAAA;EACd,OAAA;EACA;AAAA,GACC,qBAAA,GAAqB,kBAAA,CAAA,GAAA,CAAA,OAAA"}
@@ -21,10 +21,31 @@ const markdownStyles = cn("text-sm break-words", "[&_p]:my-1 [&_ul]:my-1 [&_ol]:
21
21
  function isQueryAttachment(att) {
22
22
  return !!(att.query?.title || att.query?.query);
23
23
  }
24
+ /** A chart Genie rendered, shown as the PNG the genie plugin serves. */
25
+ function GenieVisualizationImage({ viz }) {
26
+ return /* @__PURE__ */ jsx(Card, {
27
+ className: "w-full px-4 py-3 overflow-hidden",
28
+ children: /* @__PURE__ */ jsx("img", {
29
+ src: viz.url,
30
+ alt: viz.title ?? "Visualization",
31
+ loading: "lazy",
32
+ className: "w-full h-auto"
33
+ })
34
+ });
35
+ }
24
36
  /** Renders a single Genie message bubble with optional expandable SQL query attachments. */
25
37
  function GenieChatMessage({ message, className }) {
26
38
  const isUser = message.role === "user";
27
39
  const queryAttachments = message.attachments.filter(isQueryAttachment);
40
+ const visualizations = message.attachments.flatMap((att) => {
41
+ const url = att.attachmentId && message.visualizationUrls?.[att.attachmentId];
42
+ return att.viz && url ? [{
43
+ url,
44
+ ...att.viz
45
+ }] : [];
46
+ });
47
+ const queryIds = new Set(queryAttachments.map((att) => att.attachmentId));
48
+ const unmatchedVisualizations = visualizations.filter((viz) => !queryIds.has(viz.queryAttachmentId));
28
49
  const html = useMemo(() => message.content ? DOMPurify.sanitize(marked.parse(message.content)) : "", [message.content]);
29
50
  return /* @__PURE__ */ jsxs("div", {
30
51
  className: cn("flex gap-3", isUser ? "flex-row-reverse" : "flex-row", className),
@@ -36,44 +57,73 @@ function GenieChatMessage({ message, className }) {
36
57
  })
37
58
  }), /* @__PURE__ */ jsxs("div", {
38
59
  className: "flex flex-col gap-2 max-w-[80%] min-w-0 overflow-hidden",
39
- children: [/* @__PURE__ */ jsxs(Card, {
40
- className: cn("w-full px-4 py-3 overflow-hidden", isUser ? "bg-primary text-primary-foreground [&_*::selection]:bg-primary-foreground/30 [&::selection]:bg-primary-foreground/30" : "bg-muted"),
41
- children: [html && /* @__PURE__ */ jsx("div", {
42
- className: markdownStyles,
43
- dangerouslySetInnerHTML: { __html: html }
44
- }), message.error && /* @__PURE__ */ jsx("p", {
45
- className: "text-sm text-destructive mt-1",
46
- children: message.error
47
- })]
48
- }), queryAttachments.length > 0 && /* @__PURE__ */ jsx("div", {
49
- className: "flex flex-col gap-2 w-full min-w-0",
50
- children: queryAttachments.map((att) => {
51
- const key = att.attachmentId ?? "query";
52
- const queryResult = att.attachmentId ? message.queryResults.get(att.attachmentId) : void 0;
53
- return /* @__PURE__ */ jsxs("div", {
54
- className: "flex flex-col gap-2",
55
- children: [/* @__PURE__ */ jsx(Card, {
56
- className: "px-4 py-3 text-xs overflow-hidden shadow-none",
57
- children: /* @__PURE__ */ jsxs("details", { children: [/* @__PURE__ */ jsx("summary", {
60
+ children: [
61
+ /* @__PURE__ */ jsxs(Card, {
62
+ className: cn("w-full px-4 py-3 overflow-hidden", isUser ? "bg-primary text-primary-foreground [&_*::selection]:bg-primary-foreground/30 [&::selection]:bg-primary-foreground/30" : "bg-muted"),
63
+ children: [
64
+ message.reasoning && message.reasoning.length > 0 && /* @__PURE__ */ jsxs("details", {
65
+ open: !message.content,
66
+ className: "text-xs text-muted-foreground mb-2",
67
+ children: [/* @__PURE__ */ jsx("summary", {
58
68
  className: "cursor-pointer select-none font-medium",
59
- children: att.query?.title ?? "SQL Query"
60
- }), /* @__PURE__ */ jsxs("div", {
61
- className: "mt-2 flex flex-col gap-1",
62
- children: [att.query?.description && /* @__PURE__ */ jsx("span", {
63
- className: "text-muted-foreground",
64
- children: att.query.description
65
- }), att.query?.query && /* @__PURE__ */ jsx("pre", {
66
- className: "mt-1 p-2 rounded bg-background text-[11px] whitespace-pre-wrap break-all",
67
- children: att.query.query
68
- })]
69
- })] })
70
- }), queryResult != null && /* @__PURE__ */ jsx(Card, {
71
- className: "w-full px-4 py-3 overflow-hidden",
72
- children: /* @__PURE__ */ jsx(GenieQueryVisualization, { data: queryResult })
73
- })]
74
- }, key);
75
- })
76
- })]
69
+ children: "Thinking"
70
+ }), /* @__PURE__ */ jsx("ul", {
71
+ className: "mt-1 flex flex-col gap-1 list-disc pl-4",
72
+ children: message.reasoning.map((step, i) => /* @__PURE__ */ jsx("li", { children: step }, i))
73
+ })]
74
+ }),
75
+ html && /* @__PURE__ */ jsx("div", {
76
+ className: markdownStyles,
77
+ dangerouslySetInnerHTML: { __html: html }
78
+ }),
79
+ message.error && /* @__PURE__ */ jsx("p", {
80
+ className: "text-sm text-destructive mt-1",
81
+ children: message.error
82
+ })
83
+ ]
84
+ }),
85
+ queryAttachments.length > 0 && /* @__PURE__ */ jsx("div", {
86
+ className: "flex flex-col gap-2 w-full min-w-0",
87
+ children: queryAttachments.map((att) => {
88
+ const key = att.attachmentId ?? "query";
89
+ const queryResult = att.attachmentId ? message.queryResults.get(att.attachmentId) : void 0;
90
+ const queryVisualizations = visualizations.filter((viz) => viz.queryAttachmentId === att.attachmentId);
91
+ const [chartViz, ...otherVisualizations] = queryVisualizations;
92
+ const standaloneVisualizations = queryResult != null ? otherVisualizations : queryVisualizations;
93
+ return /* @__PURE__ */ jsxs("div", {
94
+ className: "flex flex-col gap-2",
95
+ children: [
96
+ /* @__PURE__ */ jsx(Card, {
97
+ className: "px-4 py-3 text-xs overflow-hidden shadow-none",
98
+ children: /* @__PURE__ */ jsxs("details", { children: [/* @__PURE__ */ jsx("summary", {
99
+ className: "cursor-pointer select-none font-medium",
100
+ children: att.query?.title ?? "SQL Query"
101
+ }), /* @__PURE__ */ jsxs("div", {
102
+ className: "mt-2 flex flex-col gap-1",
103
+ children: [att.query?.description && /* @__PURE__ */ jsx("span", {
104
+ className: "text-muted-foreground",
105
+ children: att.query.description
106
+ }), att.query?.query && /* @__PURE__ */ jsx("pre", {
107
+ className: "mt-1 p-2 rounded bg-background text-[11px] whitespace-pre-wrap break-all",
108
+ children: att.query.query
109
+ })]
110
+ })] })
111
+ }),
112
+ queryResult != null && /* @__PURE__ */ jsx(Card, {
113
+ className: "w-full px-4 py-3 overflow-hidden",
114
+ children: /* @__PURE__ */ jsx(GenieQueryVisualization, {
115
+ data: queryResult,
116
+ chartImageUrl: chartViz?.url,
117
+ chartImageAlt: chartViz?.title
118
+ })
119
+ }),
120
+ standaloneVisualizations.map((viz) => /* @__PURE__ */ jsx(GenieVisualizationImage, { viz }, viz.url))
121
+ ]
122
+ }, key);
123
+ })
124
+ }),
125
+ unmatchedVisualizations.map((viz) => /* @__PURE__ */ jsx(GenieVisualizationImage, { viz }, viz.url))
126
+ ]
77
127
  })]
78
128
  });
79
129
  }
@@ -1 +1 @@
1
- {"version":3,"file":"genie-chat-message.js","names":[],"sources":["../../../src/react/genie/genie-chat-message.tsx"],"sourcesContent":["import DOMPurify from \"dompurify\";\nimport { marked } from \"marked\";\nimport { useMemo } from \"react\";\n\nimport { cn } from \"../lib/utils\";\nimport { Avatar, AvatarFallback } from \"../ui/avatar\";\nimport { Card } from \"../ui/card\";\nimport { GenieQueryVisualization } from \"./genie-query-visualization\";\nimport type { GenieAttachmentResponse, GenieMessageItem } from \"./types\";\n\n/**\n * Using `marked` instead of `react-markdown` because `react-markdown` depends on\n * `micromark-util-symbol` which has broken ESM exports with `rolldown-vite`.\n * Output is sanitized with DOMPurify before being passed to `dangerouslySetInnerHTML`.\n */\nmarked.setOptions({ breaks: true, gfm: true });\n\nconst markdownStyles = cn(\n \"text-sm break-words\",\n \"[&_p]:my-1 [&_ul]:my-1 [&_ol]:my-1 [&_li]:my-0\",\n \"[&_pre]:bg-background/50 [&_pre]:p-2 [&_pre]:rounded [&_pre]:text-xs [&_pre]:overflow-x-auto\",\n \"[&_code]:text-xs [&_code]:bg-background/50 [&_code]:px-1 [&_code]:rounded\",\n \"[&_table]:text-xs [&_table]:block [&_table]:overflow-x-auto [&_table]:max-w-full\",\n \"[&_th]:px-2 [&_th]:py-1 [&_td]:px-2 [&_td]:py-1\",\n \"[&_table]:border-collapse [&_th]:border [&_td]:border\",\n \"[&_th]:border-border [&_td]:border-border\",\n \"[&_a]:underline\",\n);\n\ninterface GenieChatMessageProps {\n /** The message object to render */\n message: GenieMessageItem;\n /** Additional CSS class */\n className?: string;\n}\n\nfunction isQueryAttachment(att: GenieAttachmentResponse): boolean {\n return !!(att.query?.title || att.query?.query);\n}\n\n/** Renders a single Genie message bubble with optional expandable SQL query attachments. */\nexport function GenieChatMessage({\n message,\n className,\n}: GenieChatMessageProps) {\n const isUser = message.role === \"user\";\n const queryAttachments = message.attachments.filter(isQueryAttachment);\n const html = useMemo(\n () =>\n message.content\n ? DOMPurify.sanitize(marked.parse(message.content) as string)\n : \"\",\n [message.content],\n );\n\n return (\n <div\n className={cn(\n \"flex gap-3\",\n isUser ? \"flex-row-reverse\" : \"flex-row\",\n className,\n )}\n >\n <Avatar className=\"h-8 w-8 shrink-0 mt-1\">\n <AvatarFallback\n className={cn(\n \"text-xs font-medium\",\n isUser ? \"bg-primary text-primary-foreground\" : \"bg-muted\",\n )}\n >\n {isUser ? \"You\" : \"AI\"}\n </AvatarFallback>\n </Avatar>\n\n <div className=\"flex flex-col gap-2 max-w-[80%] min-w-0 overflow-hidden\">\n <Card\n className={cn(\n \"w-full px-4 py-3 overflow-hidden\",\n isUser\n ? \"bg-primary text-primary-foreground [&_*::selection]:bg-primary-foreground/30 [&::selection]:bg-primary-foreground/30\"\n : \"bg-muted\",\n )}\n >\n {html && (\n <div\n className={markdownStyles}\n dangerouslySetInnerHTML={{ __html: html }}\n />\n )}\n\n {message.error && (\n <p className=\"text-sm text-destructive mt-1\">{message.error}</p>\n )}\n </Card>\n\n {queryAttachments.length > 0 && (\n <div className=\"flex flex-col gap-2 w-full min-w-0\">\n {queryAttachments.map((att) => {\n const key = att.attachmentId ?? \"query\";\n const queryResult = att.attachmentId\n ? message.queryResults.get(att.attachmentId)\n : undefined;\n\n return (\n <div key={key} className=\"flex flex-col gap-2\">\n <Card className=\"px-4 py-3 text-xs overflow-hidden shadow-none\">\n <details>\n <summary className=\"cursor-pointer select-none font-medium\">\n {att.query?.title ?? \"SQL Query\"}\n </summary>\n <div className=\"mt-2 flex flex-col gap-1\">\n {att.query?.description && (\n <span className=\"text-muted-foreground\">\n {att.query.description}\n </span>\n )}\n {att.query?.query && (\n <pre className=\"mt-1 p-2 rounded bg-background text-[11px] whitespace-pre-wrap break-all\">\n {att.query.query}\n </pre>\n )}\n </div>\n </details>\n </Card>\n {queryResult != null && (\n <Card className=\"w-full px-4 py-3 overflow-hidden\">\n <GenieQueryVisualization data={queryResult} />\n </Card>\n )}\n </div>\n );\n })}\n </div>\n )}\n </div>\n </div>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;AAeA,OAAO,WAAW;CAAE,QAAQ;CAAM,KAAK;CAAM,CAAC;AAE9C,MAAM,iBAAiB,GACrB,uBACA,kDACA,gGACA,6EACA,oFACA,mDACA,yDACA,6CACA,kBACD;AASD,SAAS,kBAAkB,KAAuC;AAChE,QAAO,CAAC,EAAE,IAAI,OAAO,SAAS,IAAI,OAAO;;;AAI3C,SAAgB,iBAAiB,EAC/B,SACA,aACwB;CACxB,MAAM,SAAS,QAAQ,SAAS;CAChC,MAAM,mBAAmB,QAAQ,YAAY,OAAO,kBAAkB;CACtE,MAAM,OAAO,cAET,QAAQ,UACJ,UAAU,SAAS,OAAO,MAAM,QAAQ,QAAQ,CAAW,GAC3D,IACN,CAAC,QAAQ,QAAQ,CAClB;AAED,QACE,qBAAC;EACC,WAAW,GACT,cACA,SAAS,qBAAqB,YAC9B,UACD;aAED,oBAAC;GAAO,WAAU;aAChB,oBAAC;IACC,WAAW,GACT,uBACA,SAAS,uCAAuC,WACjD;cAEA,SAAS,QAAQ;KACH;IACV,EAET,qBAAC;GAAI,WAAU;cACb,qBAAC;IACC,WAAW,GACT,oCACA,SACI,yHACA,WACL;eAEA,QACC,oBAAC;KACC,WAAW;KACX,yBAAyB,EAAE,QAAQ,MAAM;MACzC,EAGH,QAAQ,SACP,oBAAC;KAAE,WAAU;eAAiC,QAAQ;MAAU;KAE7D,EAEN,iBAAiB,SAAS,KACzB,oBAAC;IAAI,WAAU;cACZ,iBAAiB,KAAK,QAAQ;KAC7B,MAAM,MAAM,IAAI,gBAAgB;KAChC,MAAM,cAAc,IAAI,eACpB,QAAQ,aAAa,IAAI,IAAI,aAAa,GAC1C;AAEJ,YACE,qBAAC;MAAc,WAAU;iBACvB,oBAAC;OAAK,WAAU;iBACd,qBAAC,wBACC,oBAAC;QAAQ,WAAU;kBAChB,IAAI,OAAO,SAAS;SACb,EACV,qBAAC;QAAI,WAAU;mBACZ,IAAI,OAAO,eACV,oBAAC;SAAK,WAAU;mBACb,IAAI,MAAM;UACN,EAER,IAAI,OAAO,SACV,oBAAC;SAAI,WAAU;mBACZ,IAAI,MAAM;UACP;SAEJ,IACE;QACL,EACN,eAAe,QACd,oBAAC;OAAK,WAAU;iBACd,oBAAC,2BAAwB,MAAM,cAAe;QACzC;QAvBD,IAyBJ;MAER;KACE;IAEJ;GACF"}
1
+ {"version":3,"file":"genie-chat-message.js","names":[],"sources":["../../../src/react/genie/genie-chat-message.tsx"],"sourcesContent":["import DOMPurify from \"dompurify\";\nimport { marked } from \"marked\";\nimport { useMemo } from \"react\";\n\nimport { cn } from \"../lib/utils\";\nimport { Avatar, AvatarFallback } from \"../ui/avatar\";\nimport { Card } from \"../ui/card\";\nimport { GenieQueryVisualization } from \"./genie-query-visualization\";\nimport type { GenieAttachmentResponse, GenieMessageItem } from \"./types\";\n\n/**\n * Using `marked` instead of `react-markdown` because `react-markdown` depends on\n * `micromark-util-symbol` which has broken ESM exports with `rolldown-vite`.\n * Output is sanitized with DOMPurify before being passed to `dangerouslySetInnerHTML`.\n */\nmarked.setOptions({ breaks: true, gfm: true });\n\nconst markdownStyles = cn(\n \"text-sm break-words\",\n \"[&_p]:my-1 [&_ul]:my-1 [&_ol]:my-1 [&_li]:my-0\",\n \"[&_pre]:bg-background/50 [&_pre]:p-2 [&_pre]:rounded [&_pre]:text-xs [&_pre]:overflow-x-auto\",\n \"[&_code]:text-xs [&_code]:bg-background/50 [&_code]:px-1 [&_code]:rounded\",\n \"[&_table]:text-xs [&_table]:block [&_table]:overflow-x-auto [&_table]:max-w-full\",\n \"[&_th]:px-2 [&_th]:py-1 [&_td]:px-2 [&_td]:py-1\",\n \"[&_table]:border-collapse [&_th]:border [&_td]:border\",\n \"[&_th]:border-border [&_td]:border-border\",\n \"[&_a]:underline\",\n);\n\ninterface GenieChatMessageProps {\n /** The message object to render */\n message: GenieMessageItem;\n /** Additional CSS class */\n className?: string;\n}\n\nfunction isQueryAttachment(att: GenieAttachmentResponse): boolean {\n return !!(att.query?.title || att.query?.query);\n}\n\ninterface Visualization {\n url: string;\n title?: string;\n queryAttachmentId?: string;\n}\n\n/** A chart Genie rendered, shown as the PNG the genie plugin serves. */\nfunction GenieVisualizationImage({ viz }: { viz: Visualization }) {\n return (\n <Card className=\"w-full px-4 py-3 overflow-hidden\">\n <img\n src={viz.url}\n alt={viz.title ?? \"Visualization\"}\n loading=\"lazy\"\n className=\"w-full h-auto\"\n />\n </Card>\n );\n}\n\n/** Renders a single Genie message bubble with optional expandable SQL query attachments. */\nexport function GenieChatMessage({\n message,\n className,\n}: GenieChatMessageProps) {\n const isUser = message.role === \"user\";\n const queryAttachments = message.attachments.filter(isQueryAttachment);\n const visualizations: Visualization[] = message.attachments.flatMap((att) => {\n const url =\n att.attachmentId && message.visualizationUrls?.[att.attachmentId];\n return att.viz && url ? [{ url, ...att.viz }] : [];\n });\n const queryIds = new Set(queryAttachments.map((att) => att.attachmentId));\n // Charts whose query isn't among the attachments still get shown, after the queries.\n const unmatchedVisualizations = visualizations.filter(\n (viz) => !queryIds.has(viz.queryAttachmentId),\n );\n const html = useMemo(\n () =>\n message.content\n ? DOMPurify.sanitize(marked.parse(message.content) as string)\n : \"\",\n [message.content],\n );\n\n return (\n <div\n className={cn(\n \"flex gap-3\",\n isUser ? \"flex-row-reverse\" : \"flex-row\",\n className,\n )}\n >\n <Avatar className=\"h-8 w-8 shrink-0 mt-1\">\n <AvatarFallback\n className={cn(\n \"text-xs font-medium\",\n isUser ? \"bg-primary text-primary-foreground\" : \"bg-muted\",\n )}\n >\n {isUser ? \"You\" : \"AI\"}\n </AvatarFallback>\n </Avatar>\n\n <div className=\"flex flex-col gap-2 max-w-[80%] min-w-0 overflow-hidden\">\n <Card\n className={cn(\n \"w-full px-4 py-3 overflow-hidden\",\n isUser\n ? \"bg-primary text-primary-foreground [&_*::selection]:bg-primary-foreground/30 [&::selection]:bg-primary-foreground/30\"\n : \"bg-muted\",\n )}\n >\n {message.reasoning && message.reasoning.length > 0 && (\n <details\n open={!message.content}\n className=\"text-xs text-muted-foreground mb-2\"\n >\n <summary className=\"cursor-pointer select-none font-medium\">\n Thinking\n </summary>\n <ul className=\"mt-1 flex flex-col gap-1 list-disc pl-4\">\n {message.reasoning.map((step, i) => (\n <li key={i}>{step}</li>\n ))}\n </ul>\n </details>\n )}\n\n {html && (\n <div\n className={markdownStyles}\n dangerouslySetInnerHTML={{ __html: html }}\n />\n )}\n\n {message.error && (\n <p className=\"text-sm text-destructive mt-1\">{message.error}</p>\n )}\n </Card>\n\n {queryAttachments.length > 0 && (\n <div className=\"flex flex-col gap-2 w-full min-w-0\">\n {queryAttachments.map((att) => {\n const key = att.attachmentId ?? \"query\";\n const queryResult = att.attachmentId\n ? message.queryResults.get(att.attachmentId)\n : undefined;\n const queryVisualizations = visualizations.filter(\n (viz) => viz.queryAttachmentId === att.attachmentId,\n );\n // The first chart goes into the result's Chart tab; any others, or all\n // of them while there's no result, are shown as plain images.\n const [chartViz, ...otherVisualizations] = queryVisualizations;\n const standaloneVisualizations =\n queryResult != null ? otherVisualizations : queryVisualizations;\n\n return (\n <div key={key} className=\"flex flex-col gap-2\">\n <Card className=\"px-4 py-3 text-xs overflow-hidden shadow-none\">\n <details>\n <summary className=\"cursor-pointer select-none font-medium\">\n {att.query?.title ?? \"SQL Query\"}\n </summary>\n <div className=\"mt-2 flex flex-col gap-1\">\n {att.query?.description && (\n <span className=\"text-muted-foreground\">\n {att.query.description}\n </span>\n )}\n {att.query?.query && (\n <pre className=\"mt-1 p-2 rounded bg-background text-[11px] whitespace-pre-wrap break-all\">\n {att.query.query}\n </pre>\n )}\n </div>\n </details>\n </Card>\n {queryResult != null && (\n <Card className=\"w-full px-4 py-3 overflow-hidden\">\n <GenieQueryVisualization\n data={queryResult}\n chartImageUrl={chartViz?.url}\n chartImageAlt={chartViz?.title}\n />\n </Card>\n )}\n {standaloneVisualizations.map((viz) => (\n <GenieVisualizationImage key={viz.url} viz={viz} />\n ))}\n </div>\n );\n })}\n </div>\n )}\n\n {unmatchedVisualizations.map((viz) => (\n <GenieVisualizationImage key={viz.url} viz={viz} />\n ))}\n </div>\n </div>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;AAeA,OAAO,WAAW;CAAE,QAAQ;CAAM,KAAK;CAAM,CAAC;AAE9C,MAAM,iBAAiB,GACrB,uBACA,kDACA,gGACA,6EACA,oFACA,mDACA,yDACA,6CACA,kBACD;AASD,SAAS,kBAAkB,KAAuC;AAChE,QAAO,CAAC,EAAE,IAAI,OAAO,SAAS,IAAI,OAAO;;;AAU3C,SAAS,wBAAwB,EAAE,OAA+B;AAChE,QACE,oBAAC;EAAK,WAAU;YACd,oBAAC;GACC,KAAK,IAAI;GACT,KAAK,IAAI,SAAS;GAClB,SAAQ;GACR,WAAU;IACV;GACG;;;AAKX,SAAgB,iBAAiB,EAC/B,SACA,aACwB;CACxB,MAAM,SAAS,QAAQ,SAAS;CAChC,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C,MAAM,cAAc,IAAI,eACpB,QAAQ,aAAa,IAAI,IAAI,aAAa,GAC1C;MACJ,MAAM,sBAAsB,eAAe,QACxC,QAAQ,IAAI,sBAAsB,IAAI,aACxC;MAGD,MAAM,CAAC,UAAU,GAAG,uBAAuB;MAC3C,MAAM,2BACJ,eAAe,OAAO,sBAAsB;AAE9C,aACE,qBAAC;OAAc,WAAU;;QACvB,oBAAC;SAAK,WAAU;mBACd,qBAAC,wBACC,oBAAC;UAAQ,WAAU;oBAChB,IAAI,OAAO,SAAS;WACb,EACV,qBAAC;UAAI,WAAU;qBACZ,IAAI,OAAO,eACV,oBAAC;WAAK,WAAU;qBACb,IAAI,MAAM;YACN,EAER,IAAI,OAAO,SACV,oBAAC;WAAI,WAAU;qBACZ,IAAI,MAAM;YACP;WAEJ,IACE;UACL;QACN,eAAe,QACd,oBAAC;SAAK,WAAU;mBACd,oBAAC;UACC,MAAM;UACN,eAAe,UAAU;UACzB,eAAe,UAAU;WACzB;UACG;QAER,yBAAyB,KAAK,QAC7B,oBAAC,2BAA2C,OAAd,IAAI,IAAiB,CACnD;;SA/BM,IAgCJ;OAER;MACE;IAGP,wBAAwB,KAAK,QAC5B,oBAAC,2BAA2C,OAAd,IAAI,IAAiB,CACnD;;IACE;GACF"}
@@ -6,18 +6,25 @@ import * as react_jsx_runtime0 from "react/jsx-runtime";
6
6
  interface GenieQueryVisualizationProps {
7
7
  /** Raw statement_response from the Genie API */
8
8
  data: GenieStatementResponse;
9
+ /** URL of a chart Genie rendered for this query, shown in place of the inferred chart */
10
+ chartImageUrl?: string;
11
+ /** Alt text for `chartImageUrl` */
12
+ chartImageAlt?: string;
9
13
  /** Additional CSS classes */
10
14
  className?: string;
11
15
  }
12
16
  /**
13
17
  * Renders a chart + data table for a Genie query result.
14
18
  *
19
+ * - When `chartImageUrl` is set: the Chart tab shows that image; if it fails to load, the inferred chart
15
20
  * - When a chart type can be inferred: shows Tabs with "Chart" (default) and "Table"
16
21
  * - When no chart fits: shows only the data table
17
- * - When data is empty/malformed: renders nothing
22
+ * - When data is empty/malformed: renders only the chart image, if any
18
23
  */
19
24
  declare function GenieQueryVisualization({
20
25
  data,
26
+ chartImageUrl,
27
+ chartImageAlt,
21
28
  className
22
29
  }: GenieQueryVisualizationProps): react_jsx_runtime0.JSX.Element | null;
23
30
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"genie-query-visualization.d.ts","names":[],"sources":["../../../src/react/genie/genie-query-visualization.tsx"],"mappings":";;;;;UA8CU,4BAAA;;EAER,IAAA,EAAM,sBAAA;;EAEN,SAAA;AAAA;;;;;;;;iBAUc,uBAAA,CAAA;EACd,IAAA;EACA;AAAA,GACC,4BAAA,GAA4B,kBAAA,CAAA,GAAA,CAAA,OAAA"}
1
+ {"version":3,"file":"genie-query-visualization.d.ts","names":[],"sources":["../../../src/react/genie/genie-query-visualization.tsx"],"mappings":";;;;;UA8CU,4BAAA;;EAER,IAAA,EAAM,sBAAA;;EAEN,aAAA;EAJoC;EAMpC,aAAA;EAJ4B;EAM5B,SAAA;AAAA;;;;;;AAWF;;;iBAAgB,uBAAA,CAAA;EACd,IAAA;EACA,aAAA;EACA,aAAA;EACA;AAAA,GACC,4BAAA,GAA4B,kBAAA,CAAA,GAAA,CAAA,OAAA"}