The Open Standard for Generative UI
cli: preflight git check and network retries in `openui create` (#1223)
devin-ai-integration[bot]b7d6a72c4d49
diff --git a/.changeset/cli-create-preflight-retry.md b/.changeset/cli-create-preflight-retry.mdnew file mode 100644index 000000000..f09b84277--- /dev/null+++ b/.changeset/cli-create-preflight-retry.md@@ -0,0 +1,5 @@+---+"@openuidev/cli": patch+---++Add a preflight git check with per-OS install hints, retry network failures with backoff during source checkout, catalog fetch, and dependency installation, and record retry attempts in failure telemetry alongside a new `cli_network_retry` event.diff --git a/packages/openui-cli/src/commands/create/lib/create-example.ts b/packages/openui-cli/src/commands/create/lib/create-example.tsindex d3b4c5896..15c21196f 100644--- a/packages/openui-cli/src/commands/create/lib/create-example.ts+++ b/packages/openui-cli/src/commands/create/lib/create-example.ts@@ -57,6 +57,7 @@ export async function runCreateExample(params: {targetDir,name,packageManager: packageManager.name,+ onRetry: tel.reportNetworkRetry("source_checkout"),});layout = verbose ? await runScaffold() : await withSpinner("Scaffolding...", runScaffold);if (!verbose) {diff --git a/packages/openui-cli/src/commands/create/lib/examples-catalog.ts b/packages/openui-cli/src/commands/create/lib/examples-catalog.tsindex e0204166c..5fc9e1e84 100644--- a/packages/openui-cli/src/commands/create/lib/examples-catalog.ts+++ b/packages/openui-cli/src/commands/create/lib/examples-catalog.ts@@ -2,6 +2,7 @@ import { styleText } from "node:util";import { fetchSourceFile } from "../../../lib/checkout";import { CreateError } from "../../../lib/errors";+import type { RetryAttemptInfo } from "../../../lib/retry";export const EXAMPLES_CATALOG_PATH = "examples/examples.json";@@ -65,8 +66,12 @@ function parseExamplesCatalog(raw: string): ExampleProject[] {}/** Prefetch the examples catalog from GitHub. */-export async function loadExamplesCatalog(): Promise<ExampleProject[]> {- const { content } = await fetchSourceFile(EXAMPLES_CATALOG_PATH);+export async function loadExamplesCatalog(+ opts: {+ onRetry?: (info: RetryAttemptInfo) => void;+ } = {},+): Promise<ExampleProject[]> {+ const { content } = await fetchSourceFile(EXAMPLES_CATALOG_PATH, { onRetry: opts.onRetry });return parseExamplesCatalog(content);}diff --git a/packages/openui-cli/src/commands/create/lib/install.ts b/packages/openui-cli/src/commands/create/lib/install.tsindex f11802157..831ffb55b 100644--- a/packages/openui-cli/src/commands/create/lib/install.ts+++ b/packages/openui-cli/src/commands/create/lib/install.ts@@ -3,8 +3,9 @@ import * as path from "node:path";import { printLogTail, QUIET_COMMAND_CAPTURE_LIMIT } from "../../../lib/command-output";import type { PackageManager } from "../../../lib/detect-package-manager";-import { CliCancelledError, CreateError, processErrorProperties } from "../../../lib/errors";+import { CliCancelledError, cliErrorProperties, throwCommandFailure } from "../../../lib/errors";import { mutedNpmEnv, runCommand } from "../../../lib/process-runner";+import { withRetry } from "../../../lib/retry";import { withSpinner } from "../../../lib/spinner";import type { OverlayName, TemplateName } from "./create-types";import type { CreateTelemetryClient } from "./telemetry";@@ -82,53 +83,47 @@ export async function installProjectDependencies(params: {if (verbose) {console.info(`Installing dependencies with: ${installCmd}\n`);}- const installResult = verbose- ? await runInstall()- : await withSpinner("Installing dependencies...", runInstall);- if (!installResult.error && installResult.status === 0) {+ const attemptInstall = async () => {+ const result = await runInstall();+ if (!result.error && result.status === 0) return result;+if (!verbose) {- console.info("✓ Dependencies installed");+ printLogTail(result.diagnosticTail, "install log (tail)");}- tel.trackDependencyInstallSucceeded({- template,- ai_setup: aiSetup,- dependency_installed: true,+ throwCommandFailure(result, "dependency_install", "dependency install failed", {+ error_class: "dependency",+ error_code: "NONZERO_EXIT",});- return true;- }+ };- if (!verbose) {- printLogTail(installResult.diagnosticTail, "install log (tail)");- }- const properties = processErrorProperties(installResult, "dependency_install", {- error_class: "dependency",- error_code: "NONZERO_EXIT",- });- if (properties.error_class === "user_cancelled") {- tel.trackDependencyInstallCancelled({+ try {+ const runWithRetry = () =>+ withRetry("Dependency install", attemptInstall, {+ onRetry: tel.reportNetworkRetry("dependency_install"),+ });+ await (verbose ? runWithRetry() : withSpinner("Installing dependencies...", runWithRetry));+ } catch (err) {+ const properties = {template,ai_setup: aiSetup,dependency_installed: false,- ...properties,- });- throw new CliCancelledError(- "dependency_install",- properties.cancellation_exit_code ?? 0,- properties,- );+ ...cliErrorProperties(err),+ };+ if (err instanceof CliCancelledError) {+ tel.trackDependencyInstallCancelled(properties);+ } else {+ tel.trackDependencyInstallFailed(properties);+ }+ throw err;+ }++ if (!verbose) {+ console.info("✓ Dependencies installed");}- tel.trackDependencyInstallFailed({+ tel.trackDependencyInstallSucceeded({template,ai_setup: aiSetup,- dependency_installed: false,- ...properties,+ dependency_installed: true,});- const { failure_stage, error_class, error_code, ...metadata } = properties;- throw new CreateError(- failure_stage,- "dependency install failed",- error_class,- error_code,- metadata,- );+ return true;}diff --git a/packages/openui-cli/src/commands/create/lib/resolve.ts b/packages/openui-cli/src/commands/create/lib/resolve.tsindex b1b44ff9a..3e1e12a4e 100644--- a/packages/openui-cli/src/commands/create/lib/resolve.ts+++ b/packages/openui-cli/src/commands/create/lib/resolve.ts@@ -1,5 +1,6 @@import { CliCancelledError, CreateError } from "../../../lib/errors";import { resolveArgs } from "../../../lib/resolve-args";+import type { RetryAttemptInfo } from "../../../lib/retry";import type { OverlayName, TemplateName } from "./create-types";import {findExample,@@ -40,8 +41,9 @@ export async function loadCreateCatalog(params: {template?: TemplateName;backendFramework?: OverlayName;interactive: boolean;+ onRetry?: (info: RetryAttemptInfo) => void;}): Promise<CreateCatalog> {- const { example, template: requestedTemplate, backendFramework, interactive } = params;+ const { example, template: requestedTemplate, backendFramework, interactive, onRetry } = params;rejectConflictingScaffoldSelectors({example,@@ -61,13 +63,16 @@ export async function loadCreateCatalog(params: {}if (example) {- const examples = await loadExamplesCatalog();+ const examples = await loadExamplesCatalog({ onRetry });findExample(example, examples);return { examples };}if (interactive) {- const [catalog, examples] = await Promise.all([loadTemplatesCatalog(), loadExamplesCatalog()]);+ const [catalog, examples] = await Promise.all([+ loadTemplatesCatalog({ onRetry }),+ loadExamplesCatalog({ onRetry }),+ ]);const template = requestedTemplate ?? DEFAULT_TEMPLATE_KEY;const templateEntry = findCatalogTemplate(catalog, template);if (backendFramework) {@@ -76,7 +81,7 @@ export async function loadCreateCatalog(params: {return { examples, template, templateEntry };}- const catalog = await loadTemplatesCatalog();+ const catalog = await loadTemplatesCatalog({ onRetry });const template = requestedTemplate ?? DEFAULT_TEMPLATE_KEY;const templateEntry = findCatalogTemplate(catalog, template);if (backendFramework) {diff --git a/packages/openui-cli/src/commands/create/lib/scaffold-example.ts b/packages/openui-cli/src/commands/create/lib/scaffold-example.tsindex b64c264be..7ba210c8d 100644--- a/packages/openui-cli/src/commands/create/lib/scaffold-example.ts+++ b/packages/openui-cli/src/commands/create/lib/scaffold-example.ts@@ -5,6 +5,7 @@ import * as path from "node:path";import { checkoutSource } from "../../../lib/checkout";import type { PackageManagerName } from "../../../lib/detect-package-manager";import { CreateError } from "../../../lib/errors";+import type { RetryAttemptInfo } from "../../../lib/retry";import type { ExampleProject } from "./examples-catalog";const ARTIFACT_DIRS = new Set(["node_modules", ".next", ".turbo", "dist", ".nuxt", ".svelte-kit"]);@@ -159,11 +160,12 @@ export async function scaffoldExample(params: {targetDir: string;name: string;packageManager: PackageManagerName;+ onRetry?: (info: RetryAttemptInfo) => void;}): Promise<ExampleLayout> {- const { example, targetDir, name, packageManager } = params;+ const { example, targetDir, name, packageManager, onRetry } = params;try {- await checkoutSource(example.path, { dest: targetDir });+ await checkoutSource(example.path, { dest: targetDir, onRetry });} catch (err) {if (err instanceof CreateError) throw err;throw new CreateError(diff --git a/packages/openui-cli/src/commands/create/lib/templates-catalog.ts b/packages/openui-cli/src/commands/create/lib/templates-catalog.tsindex 88999b7e1..60ec7fc34 100644--- a/packages/openui-cli/src/commands/create/lib/templates-catalog.ts+++ b/packages/openui-cli/src/commands/create/lib/templates-catalog.ts@@ -1,5 +1,6 @@import { fetchSourceFile } from "../../../lib/checkout";import { CreateError } from "../../../lib/errors";+import type { RetryAttemptInfo } from "../../../lib/retry";export const TEMPLATES_CATALOG_PATH = "templates/templates.json";@@ -62,8 +63,12 @@ function parseTemplatesCatalog(raw: string): CatalogTemplate[] {}/** Prefetch the template catalog from GitHub. */-export async function loadTemplatesCatalog(): Promise<CatalogTemplate[]> {- const { content } = await fetchSourceFile(TEMPLATES_CATALOG_PATH);+export async function loadTemplatesCatalog(+ opts: {+ onRetry?: (info: RetryAttemptInfo) => void;+ } = {},+): Promise<CatalogTemplate[]> {+ const { content } = await fetchSourceFile(TEMPLATES_CATALOG_PATH, { onRetry: opts.onRetry });return parseTemplatesCatalog(content);}diff --git a/packages/openui-cli/src/commands/create/run.ts b/packages/openui-cli/src/commands/create/run.tsindex cfdeef8f9..398030db7 100644--- a/packages/openui-cli/src/commands/create/run.ts+++ b/packages/openui-cli/src/commands/create/run.ts@@ -1,8 +1,10 @@import * as fs from "node:fs";+import { localSourceDir } from "../../lib/checkout";import type { CliContext } from "../../lib/context";import { resolveInstallPackageManager } from "../../lib/detect-package-manager";import { cliErrorProperties, CreateError, processErrorProperties } from "../../lib/errors";+import { ensureGitAvailable } from "../../lib/git-preflight";import { applyScaffoldFiles, resolveTemplateSource } from "../../lib/scaffold";import { withSpinner } from "../../lib/spinner";import { runCreateExample } from "./lib/create-example";@@ -46,11 +48,14 @@ export async function runCreateApp(options: CreateAppOptions, ctx: CliContext):immediate_arg: options.immediate,});+ if (!localSourceDir()) await ensureGitAvailable();+ const sourceRetryReporter = tel.reportNetworkRetry("source_checkout");const catalog = await loadCreateCatalog({example: options.example,template: options.template,backendFramework: options.backendFramework,interactive,+ onRetry: sourceRetryReporter,});const { name, targetDir } = await resolveProjectIdentity(options.name, interactive, tel);@@ -123,7 +128,9 @@ export async function runCreateApp(options: CreateAppOptions, ctx: CliContext):let overlay: TemplateOverlay | undefined;const runScaffold = async () => {- const { dir: templateDir } = await resolveTemplateSource(template);+ const { dir: templateDir } = await resolveTemplateSource(template, {+ onRetry: sourceRetryReporter,+ });tel.trackScaffoldStarted({ template, ai_setup: aiSetup });try {overlay = applyScaffoldFiles({diff --git a/packages/openui-cli/src/lib/checkout.ts b/packages/openui-cli/src/lib/checkout.tsindex 21e22993b..6cb16e188 100644--- a/packages/openui-cli/src/lib/checkout.ts+++ b/packages/openui-cli/src/lib/checkout.ts@@ -5,6 +5,8 @@ import * as path from "node:path";import { isTruthyEnv } from "./env";import { CreateError } from "./errors";+import { gitMissingMessage } from "./git-preflight";+import { type RetryAttemptInfo, withRetry } from "./retry";const GIT_TIMEOUT_MS = 60_000;const FETCH_TIMEOUT_MS = 30_000;@@ -19,7 +21,7 @@ const SOURCE_GIT_URL = `https://github.com/${SOURCE_OWNER}/${SOURCE_REPO}.git`;* instead of fetching `main` from GitHub, so CI can scaffold the templates of* the commit under test. Undocumented: requires `OPENUI_DEBUG`.*/-function localSourceDir(): string | undefined {+export function localSourceDir(): string | undefined {if (!isTruthyEnv(process.env["OPENUI_DEBUG"])) return undefined;const dir = process.env["OPENUI_SOURCE_DIR"]?.trim();return dir || undefined;@@ -40,6 +42,7 @@ function localSourcePath(sourceDir: string, normalizedPath: string): string {export type SourceFetchOptions = {dest?: string;+ onRetry?: (info: RetryAttemptInfo) => void;};export type FetchedFile = {@@ -90,14 +93,7 @@ function runGit(child.once("error", (error: NodeJS.ErrnoException) => {clearTimeout(timeout);if (error.code === "ENOENT") {- reject(- new CreateError(- "source_checkout",- "git is not installed or not found in PATH.",- "process",- "GIT_MISSING",- ),- );+ reject(new CreateError("source_checkout", gitMissingMessage(), "process", "GIT_MISSING"));return;}reject(error);@@ -112,7 +108,7 @@ function runGit(reject(new CreateError("source_checkout",- `git ${args[0]} failed: ${detail}`,+ `git ${args[0]} failed: ${detail}. Check your network connection and try again.`,"network","CHECKOUT_FAILED",),@@ -121,41 +117,47 @@ function runGit(});}-export async function fetchSourceFile(repoPath: string): Promise<FetchedFile> {+export async function fetchSourceFile(+ repoPath: string,+ opts: { onRetry?: (info: RetryAttemptInfo) => void } = {},+): Promise<FetchedFile> {const normalizedPath = posixRepoPath(repoPath);const sourceDir = localSourceDir();if (sourceDir) {return { content: fs.readFileSync(localSourcePath(sourceDir, normalizedPath), "utf8") };}- const url = `https://raw.githubusercontent.com/${SOURCE_OWNER}/${SOURCE_REPO}/${SOURCE_REF}/${normalizedPath}`;- const controller = new AbortController();- const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);- try {- const response = await fetch(url, {- headers: { Accept: "text/plain" },- signal: controller.signal,- });- if (!response.ok) {+ const fetchOnce = async (): Promise<FetchedFile> => {+ const url = `https://raw.githubusercontent.com/${SOURCE_OWNER}/${SOURCE_REPO}/${SOURCE_REF}/${normalizedPath}`;+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);+ try {+ const response = await fetch(url, {+ headers: { Accept: "text/plain" },+ signal: controller.signal,+ });+ if (!response.ok) {+ throw new CreateError(+ "source_checkout",+ `Failed to fetch ${normalizedPath} (${response.status}).`,+ response.status === 404 ? "filesystem" : "network",+ response.status === 404 ? "SOURCE_MISSING" : "CHECKOUT_FAILED",+ );+ }+ return { content: await response.text() };+ } catch (error) {+ if (error instanceof CreateError) throw error;+ const aborted = error instanceof Error && error.name === "AbortError";throw new CreateError("source_checkout",- `Failed to fetch ${normalizedPath} (${response.status}).`,+ `${aborted ? "Timed out fetching" : "Failed to fetch"} ${normalizedPath} from GitHub. Check your network connection and try again.`,"network",- response.status === 404 ? "SOURCE_MISSING" : "CHECKOUT_FAILED",+ "CHECKOUT_FAILED",);+ } finally {+ clearTimeout(timer);}- return { content: await response.text() };- } catch (error) {- if (error instanceof CreateError) throw error;- const aborted = error instanceof Error && error.name === "AbortError";- throw new CreateError(- "source_checkout",- aborted ? `Timed out fetching ${normalizedPath}.` : `Failed to fetch ${normalizedPath}.`,- "network",- "CHECKOUT_FAILED",- );- } finally {- clearTimeout(timer);- }+ };+ return withRetry(`Fetching ${normalizedPath}`, fetchOnce, { onRetry: opts.onRetry });}export async function checkoutSource(@@ -169,32 +171,35 @@ export async function checkoutSource(copyDir(localSourcePath(sourceDir, normalizedPath), dest);return { dir: dest };}- const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "openui-src-"));- try {- await runGit(["init", "--quiet"], { cwd: tmpDir });- await runGit(["remote", "add", "origin", SOURCE_GIT_URL], { cwd: tmpDir });- await runGit(["fetch", "--depth", "1", "--filter=blob:none", "origin", SOURCE_REF], {- cwd: tmpDir,- });- await runGit(["sparse-checkout", "set", "--cone", normalizedPath], { cwd: tmpDir });- await runGit(["checkout", "--quiet", "FETCH_HEAD"], { cwd: tmpDir });+ const checkoutOnce = async (): Promise<CheckedOutSource> => {+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "openui-src-"));+ try {+ await runGit(["init", "--quiet"], { cwd: tmpDir });+ await runGit(["remote", "add", "origin", SOURCE_GIT_URL], { cwd: tmpDir });+ await runGit(["fetch", "--depth", "1", "--filter=blob:none", "origin", SOURCE_REF], {+ cwd: tmpDir,+ });+ await runGit(["sparse-checkout", "set", "--cone", normalizedPath], { cwd: tmpDir });+ await runGit(["checkout", "--quiet", "FETCH_HEAD"], { cwd: tmpDir });- const extracted = path.join(tmpDir, ...normalizedPath.split("/"));- if (!fs.existsSync(extracted)) {- throw new CreateError(- "source_checkout",- `Path "${normalizedPath}" was not in ${SOURCE_OWNER}/${SOURCE_REPO}@${SOURCE_REF}.`,- "filesystem",- "SOURCE_MISSING",- );- }+ const extracted = path.join(tmpDir, ...normalizedPath.split("/"));+ if (!fs.existsSync(extracted)) {+ throw new CreateError(+ "source_checkout",+ `Path "${normalizedPath}" was not in ${SOURCE_OWNER}/${SOURCE_REPO}@${SOURCE_REF}.`,+ "filesystem",+ "SOURCE_MISSING",+ );+ }- const dest = opts.dest ?? fs.mkdtempSync(path.join(os.tmpdir(), "openui-src-"));- copyDir(extracted, dest);- return { dir: dest };- } finally {- fs.rmSync(tmpDir, { recursive: true, force: true });- }+ const dest = opts.dest ?? fs.mkdtempSync(path.join(os.tmpdir(), "openui-src-"));+ copyDir(extracted, dest);+ return { dir: dest };+ } finally {+ fs.rmSync(tmpDir, { recursive: true, force: true });+ }+ };+ return withRetry("Source checkout", checkoutOnce, { onRetry: opts.onRetry });}function copyDir(from: string, to: string) {diff --git a/packages/openui-cli/src/lib/errors.ts b/packages/openui-cli/src/lib/errors.tsindex 1cd49f74f..e1cdafea7 100644--- a/packages/openui-cli/src/lib/errors.ts+++ b/packages/openui-cli/src/lib/errors.ts@@ -24,6 +24,7 @@ export type CliErrorMetadata = {http_status?: number;cancellation_exit_code?: number;auth_failure_stage?: string;+ attempts?: number;};export class CreateError extends Error {diff --git a/packages/openui-cli/src/lib/git-preflight.ts b/packages/openui-cli/src/lib/git-preflight.tsnew file mode 100644index 000000000..15c49dad5--- /dev/null+++ b/packages/openui-cli/src/lib/git-preflight.ts@@ -0,0 +1,51 @@+import { spawn } from "node:child_process";++import { CreateError } from "./errors";++export function gitInstallHint(platform: NodeJS.Platform = process.platform): string {+ if (platform === "win32") {+ return "Install it with `winget install --id Git.Git -e --source winget` or `choco install git`, or download it from https://git-scm.com/download/win. Then open a new terminal and rerun this command.";+ }+ if (platform === "darwin") {+ return "Install it with `brew install git` or `xcode-select --install`, then rerun this command.";+ }+ return "Install it with your package manager, e.g. `sudo apt install git` (Debian/Ubuntu) or `sudo dnf install git` (Fedora), then rerun this command.";+}++export function gitMissingMessage(platform?: NodeJS.Platform): string {+ return `git is required to download the template but was not found in PATH.\n${gitInstallHint(platform)}`;+}++export async function ensureGitAvailable(+ options: { command?: string; platform?: NodeJS.Platform } = {},+): Promise<void> {+ await new Promise<void>((resolve, reject) => {+ let settled = false;+ const finish = (result: () => void) => {+ if (settled) return;+ settled = true;+ result();+ };+ const child = spawn(options.command ?? "git", ["--version"], {+ stdio: "ignore",+ env: { ...process.env, GIT_TERMINAL_PROMPT: "0" },+ });+ child.once("error", (error: NodeJS.ErrnoException) => {+ if (error.code === "ENOENT") {+ finish(() =>+ reject(+ new CreateError(+ "preflight",+ gitMissingMessage(options.platform),+ "process",+ "GIT_MISSING",+ ),+ ),+ );+ return;+ }+ finish(resolve);+ });+ child.once("close", () => finish(resolve));+ });+}diff --git a/packages/openui-cli/src/lib/retry.ts b/packages/openui-cli/src/lib/retry.tsnew file mode 100644index 000000000..904361ce3--- /dev/null+++ b/packages/openui-cli/src/lib/retry.ts@@ -0,0 +1,64 @@+import { CreateError } from "./errors";++const DEFAULT_MAX_ATTEMPTS = 3;+const DEFAULT_BASE_DELAY_MS = 1000;++export type RetryAttemptInfo = {+ attempt: number;+ maxAttempts: number;+ delayMs: number;+ error: unknown;+};++export type RetryOptions = {+ maxAttempts?: number;+ baseDelayMs?: number;+ shouldRetry?: (error: unknown) => boolean;+ onRetry?: (info: RetryAttemptInfo) => void;+ sleep?: (ms: number) => Promise<void>;+};++function defaultSleep(ms: number): Promise<void> {+ return new Promise((resolve) => {+ const timer = setTimeout(resolve, ms);+ timer.unref();+ });+}++export function isNetworkError(error: unknown): boolean {+ return error instanceof CreateError && error.errorClass === "network";+}++export async function withRetry<T>(+ label: string,+ fn: (attempt: number) => Promise<T>,+ options: RetryOptions = {},+): Promise<T> {+ const maxAttempts = options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;+ const baseDelayMs = options.baseDelayMs ?? DEFAULT_BASE_DELAY_MS;+ const shouldRetry = options.shouldRetry ?? isNetworkError;+ const sleep = options.sleep ?? defaultSleep;++ for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {+ try {+ return await fn(attempt);+ } catch (error) {+ if (attempt < maxAttempts && shouldRetry(error)) {+ const delayMs = baseDelayMs * 2 ** (attempt - 1);+ const errorCode = error instanceof CreateError ? error.errorCode : "error";+ console.warn(+ `${label} failed (${errorCode}); retrying in ${delayMs / 1000}s (attempt ${attempt + 1}/${maxAttempts})...`,+ );+ options.onRetry?.({ attempt, maxAttempts, delayMs, error });+ await sleep(delayMs);+ continue;+ }+ if (error instanceof CreateError) {+ error.errorMetadata.attempts = attempt;+ }+ throw error;+ }+ }++ throw new Error(`${label} failed without an error`);+}diff --git a/packages/openui-cli/src/lib/scaffold/source.ts b/packages/openui-cli/src/lib/scaffold/source.tsindex 51893bd12..2c580add4 100644--- a/packages/openui-cli/src/lib/scaffold/source.ts+++ b/packages/openui-cli/src/lib/scaffold/source.ts@@ -3,7 +3,8 @@ import * as os from "node:os";import * as path from "node:path";import { checkoutSource } from "../checkout";-import { CreateError } from "../errors";+import { cliErrorProperties, CreateError } from "../errors";+import type { RetryAttemptInfo } from "../retry";export const TEMPLATES_DIR = "templates";@@ -11,19 +12,39 @@ export type ResolvedTemplate = {dir: string;};-export async function resolveTemplateSource(template: string): Promise<ResolvedTemplate> {+export function throwTemplateSourceError(err: unknown, template: string): never {+ const properties = cliErrorProperties(err, {+ failure_stage: "preflight",+ error_class: "network",+ error_code: "TEMPLATE_MISSING",+ });+ const detail = err instanceof Error ? err.message : String(err);+ const message =+ properties.error_class === "network"+ ? `Could not download template "${template}" from GitHub: ${detail}. Check your network connection and try again.`+ : `Could not prepare template "${template}": ${detail}`;+ throw new CreateError(+ properties.failure_stage,+ message,+ properties.error_class,+ properties.error_code,+ );+}++export async function resolveTemplateSource(+ template: string,+ opts: { onRetry?: (info: RetryAttemptInfo) => void } = {},+): Promise<ResolvedTemplate> {const dest = fs.mkdtempSync(path.join(os.tmpdir(), "openui-template-"));try {- const checkedOut = await checkoutSource(`${TEMPLATES_DIR}/${template}`, { dest });+ const checkedOut = await checkoutSource(`${TEMPLATES_DIR}/${template}`, {+ dest,+ onRetry: opts.onRetry,+ });return { dir: checkedOut.dir };} catch (err) {fs.rmSync(dest, { recursive: true, force: true });if (err instanceof CreateError) throw err;- throw new CreateError(- "preflight",- err instanceof Error ? err.message : String(err),- "network",- "TEMPLATE_MISSING",- );+ throwTemplateSourceError(err, template);}}diff --git a/packages/openui-cli/src/lib/telemetry.ts b/packages/openui-cli/src/lib/telemetry.tsindex 68c6eb6bb..b7693b0bf 100644--- a/packages/openui-cli/src/lib/telemetry.ts+++ b/packages/openui-cli/src/lib/telemetry.ts@@ -4,6 +4,8 @@ import * as path from "node:path";import { PostHog } from "posthog-node";import { isTruthyEnv } from "./env";+import { cliErrorProperties } from "./errors";+import type { RetryAttemptInfo } from "./retry";// Public ingestion keyconst POSTHOG_KEY =@@ -143,6 +145,20 @@ export class Telemetry {this.capture("cli_invoked");}+ reportNetworkRetry(stage: string): (info: RetryAttemptInfo) => void {+ return (info) => {+ const properties = cliErrorProperties(info.error);+ this.capture("cli_network_retry", {+ failure_stage: stage,+ attempt: info.attempt,+ max_attempts: info.maxAttempts,+ delay_ms: info.delayMs,+ error_class: properties.error_class,+ error_code: properties.error_code,+ });+ };+ }+capture(event: string, properties: Record<string, unknown> = {}) {const { enabled, client, distinctId, superProps } = this.session;if (!enabled || !client) return;