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build an installed app's UI bundle on demand, per APP.md's declared\n * `ui.build` (`@agentproto/app`'s `AppUiBuildConfig`) — the piece that\n * lets a repo declare \"how to build the UI\" instead of committing the\n * generated `.agentproto/ui/index.html`.\n *\n * `ensureAppUiBuilt` is the one entry point, called from every path that's\n * about to serve or install an app's UI (`app_install` in app-tools.ts,\n * `GET /apps/:appId/ui` in http-server.ts, the MCP panel cache in\n * app-ui-apps.ts, and the CLI's `agentproto app serve`): if the declared\n * `uiPath` is missing, or older than the newest file matching `ui.build`'s\n * `sources` globs (default `[\"src/**\"]`, resolved against `ui.build.cwd` —\n * default the app dir), it runs `ui.build.command` once, captures output to\n * `~/.agentproto/logs/app-ui-build/` (see `appUiBuildLogPath`), and returns a result the caller turns\n * into either a served page or a readable error. Concurrent callers for the\n * same `uiPath` share one in-flight build (single-flight, keyed on the\n * absolute `uiPath` — an app's bundle lives at one path regardless of which\n * route is asking).\n *\n * Staleness is two-tier. The mtime comparison above is only the fast path:\n * when it says \"stale\", the sources' CONTENT is hashed and compared with the\n * hash recorded after the last successful build (`appUiBuildStampPath`, under\n * the daemon state dir). A matching hash means nothing that feeds the bundle\n * actually changed — a `git checkout`/`stash`/hook that rewrote files with\n * identical bytes only bumped their mtimes — so no build runs. Test files\n * (`DEFAULT_SOURCE_EXCLUDES`) never count as sources, and a `!pattern` entry\n * in `sources` excludes more.\n *\n * Page renders go through `resolveAppUiBuildState`, which never makes a user\n * wait on a REbuild: when a bundle already exists it is served as-is while\n * the rebuild runs in the background (stale-while-revalidate), and a failed\n * background rebuild keeps serving it, without retrying until the sources\n * change again. Only a MISSING bundle shows the \"building\" placeholder.\n *\n * An app with no `ui.build` declared keeps today's behavior exactly: the\n * bundle must already exist on disk, and a missing one is a clear error\n * naming the path rather than a bare 404.\n */\n\nimport { spawn } from \"node:child_process\"\nimport { createHash } from \"node:crypto\"\nimport { mkdir, readdir, readFile, stat, writeFile } from \"node:fs/promises\"\nimport type { Dirent, Stats } from \"node:fs\"\nimport { homedir } from \"node:os\"\nimport { basename, dirname, isAbsolute, join, relative, resolve, sep } from \"node:path\"\nimport type { AppUiBuildConfig } from \"@agentproto/app\"\n\n/**\n * Deliberately NOT `command-tools.ts`'s `runCommand` — that pulls in\n * `sessions.ts` (session identity, spawn bookkeeping — thousands of lines\n * unrelated to running a build), which would drag the whole session\n * subsystem into this module's own `tsup` entry (`./app-ui-build`,\n * `tsup.config.ts`), a lean subpath the CLI imports on its own (same\n * pattern as `app-ui-delivery.ts`, which only imports node builtins). A\n * one-shot build command doesn't need `runCommand`'s process-group\n * bookkeeping either — it has no long-lived subtree to reap beyond its own\n * (possibly shell-spawned) child.\n */\ninterface RunResult {\n  readonly exitCode: number\n  readonly timedOut: boolean\n  readonly stdout: string\n  readonly stderr: string\n}\n\nfunction runShellCommand(command: string, cwd: string, timeoutMs: number): Promise<RunResult> {\n  return new Promise(resolvePromise => {\n    const child = spawn(command, {\n      cwd,\n      shell: true,\n      stdio: [\"ignore\", \"pipe\", \"pipe\"],\n    })\n    let stdout = \"\"\n    let stderr = \"\"\n    let timedOut = false\n    child.stdout?.on(\"data\", d => {\n      stdout += d.toString(\"utf8\")\n    })\n    child.stderr?.on(\"data\", d => {\n      stderr += d.toString(\"utf8\")\n    })\n    const timer = setTimeout(() => {\n      timedOut = true\n      child.kill(\"SIGTERM\")\n      setTimeout(() => child.kill(\"SIGKILL\"), 2_000).unref()\n    }, timeoutMs)\n    timer.unref()\n    child.on(\"error\", err => {\n      clearTimeout(timer)\n      resolvePromise({ exitCode: -1, timedOut, stdout, stderr: stderr + (err as Error).message })\n    })\n    child.on(\"close\", code => {\n      clearTimeout(timer)\n      resolvePromise({ exitCode: code ?? -1, timedOut, stdout, stderr })\n    })\n  })\n}\n\nfunction resolveAgainst(dir: string, path: string): string {\n  return isAbsolute(path) ? path : join(dir, path)\n}\n\n/** Turn one glob SEGMENT (no `/`) into a regex — `*` matches any run of\n *  characters within the segment, everything else is literal. */\nfunction segmentToRegex(segment: string): RegExp {\n  const escaped = segment.replace(/[.+^${}()|[\\]\\\\]/g, \"\\\\$&\").replace(/\\*/g, \".*\")\n  return new RegExp(`^${escaped}$`)\n}\n\n/**\n * Resolve one glob pattern (already split into path segments, relative to\n * `baseDir`) to the absolute paths of every FILE it matches. Supports `**`\n * (zero or more path segments, so `\"src/**\"` matches every file anywhere\n * under `src/`, including `src/` itself) and `*` within a single segment —\n * not full glob syntax (no brace expansion, no negation, no `?`). That\n * subset covers the documented default (`src/**`) and the common overrides\n * (`package.json`, `public/**`, `*.html`) without pulling in a glob\n * dependency for a staleness check.\n */\nasync function collectGlobFiles(baseDir: string, segments: readonly string[]): Promise<string[]> {\n  if (segments.length === 0) {\n    try {\n      const st = await stat(baseDir)\n      return st.isFile() ? [baseDir] : []\n    } catch {\n      return []\n    }\n  }\n  const [head, ...rest] = segments\n  if (head === \"**\") {\n    const results: string[] = [...(await collectGlobFiles(baseDir, rest))]\n    let entries: Dirent[]\n    try {\n      entries = await readdir(baseDir, { withFileTypes: true })\n    } catch {\n      return results\n    }\n    for (const entry of entries) {\n      const full = join(baseDir, entry.name)\n      if (entry.isDirectory()) {\n        results.push(...(await collectGlobFiles(full, segments)))\n      } else if (rest.length === 0) {\n        results.push(full)\n      }\n    }\n    return results\n  }\n  const regex = segmentToRegex(head!)\n  let entries: Dirent[]\n  try {\n    entries = await readdir(baseDir, { withFileTypes: true })\n  } catch {\n    return []\n  }\n  const results: string[] = []\n  for (const entry of entries) {\n    if (!regex.test(entry.name)) continue\n    results.push(...(await collectGlobFiles(join(baseDir, entry.name), rest)))\n  }\n  return results\n}\n\n/** Whole-path glob → regex, for EXCLUDE patterns matched against a source's\n *  `/`-separated path relative to `cwd`: `**` spans any number of segments\n *  (a leading or trailing `**` segment also matches zero), `*` stays within\n *  one segment. */\nfunction pathGlobToRegex(pattern: string): RegExp {\n  let out = \"\"\n  let i = 0\n  while (i < pattern.length) {\n    if (pattern.startsWith(\"**/\", i)) {\n      out += \"(?:.*/)?\"\n      i += 3\n    } else if (pattern.startsWith(\"/**\", i) && i + 3 === pattern.length) {\n      out += \"(?:/.*)?\"\n      i += 3\n    } else if (pattern.startsWith(\"**\", i)) {\n      out += \".*\"\n      i += 2\n    } else if (pattern[i] === \"*\") {\n      out += \"[^/]*\"\n      i += 1\n    } else {\n      out += pattern[i]!.replace(/[.+?^${}()|[\\]\\\\]/g, \"\\\\$&\")\n      i += 1\n    }\n  }\n  return new RegExp(`^${out}$`)\n}\n\n/** Never sources, whatever `ui.build.sources` says: tests don't feed a UI\n *  bundle, so editing one must not trigger a multi-second rebuild. */\nexport const DEFAULT_SOURCE_EXCLUDES: readonly string[] = [\"**/__tests__/**\", \"**/*.test.*\", \"**/*.spec.*\"]\n\n/**\n * Every file matched by `patterns` (relative to `cwd`), minus\n * {@link DEFAULT_SOURCE_EXCLUDES} and any `!pattern` entry in `patterns`.\n * Returned sorted by relative path, deduped (two patterns can match the same\n * file), as `{ abs, rel }` with `rel` always `/`-separated.\n */\nexport async function collectSourceFiles(\n  cwd: string,\n  patterns: readonly string[],\n): Promise<{ readonly abs: string; readonly rel: string }[]> {\n  const normalize = (p: string) => p.replace(/^\\.\\//, \"\")\n  const excludes = [\n    ...DEFAULT_SOURCE_EXCLUDES,\n    ...patterns.filter(p => p.startsWith(\"!\")).map(p => normalize(p.slice(1))),\n  ].map(pathGlobToRegex)\n  const byRel = new Map<string, string>()\n  for (const pattern of patterns) {\n    if (pattern.startsWith(\"!\")) continue\n    const segments = normalize(pattern).split(\"/\").filter(s => s.length > 0)\n    if (segments.length === 0) continue\n    for (const abs of await collectGlobFiles(cwd, segments)) {\n      const rel = relative(cwd, abs).split(sep).join(\"/\")\n      if (excludes.some(re => re.test(rel))) continue\n      byRel.set(rel, abs)\n    }\n  }\n  return [...byRel.entries()]\n    .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n    .map(([rel, abs]) => ({ abs, rel }))\n}\n\n/** Newest mtime (ms) among every source file `patterns` selects (relative\n *  to `cwd`, see {@link collectSourceFiles}), or `undefined` if none. */\nexport async function newestSourceMtime(\n  cwd: string,\n  patterns: readonly string[],\n): Promise<number | undefined> {\n  let max: number | undefined\n  for (const { abs } of await collectSourceFiles(cwd, patterns)) {\n    try {\n      const st = await stat(abs)\n      if (max === undefined || st.mtimeMs > max) max = st.mtimeMs\n    } catch {\n      // Vanished between listing and stat — ignore.\n    }\n  }\n  return max\n}\n\n/** Last content hash computed per `uiPath`, with the stat signature\n *  (path + mtime + size of every source) it was computed under — so a page\n *  re-rendered while mtimes still read \"stale\" re-stats the sources but\n *  doesn't re-read every one of them. */\nconst hashMemo = new Map<string, { readonly signature: string; readonly hash: string }>()\n\n/**\n * Content hash of everything that decides what `build` produces: the\n * selected source files (relative path + bytes, in sorted order) and the\n * build command itself. Identical inputs hash identically whatever their\n * mtimes — the point of the second staleness tier.\n */\nexport async function hashAppUiSources(\n  uiPath: string,\n  cwd: string,\n  build: AppUiBuildConfig,\n): Promise<string> {\n  const files = await collectSourceFiles(cwd, build.sources ?? DEFAULT_SOURCE_GLOBS)\n  const sig = createHash(\"sha1\").update(`${cwd}\\0${build.command}`)\n  const present: { readonly abs: string; readonly rel: string }[] = []\n  for (const file of files) {\n    try {\n      const st = await stat(file.abs)\n      sig.update(`\\0${file.rel}\\0${st.mtimeMs}\\0${st.size}`)\n      present.push(file)\n    } catch {\n      // Vanished between listing and stat — not a source anymore.\n    }\n  }\n  const signature = sig.digest(\"hex\")\n  const memo = hashMemo.get(uiPath)\n  if (memo && memo.signature === signature) return memo.hash\n\n  const content = createHash(\"sha256\").update(`command\\0${build.command}\\0`)\n  for (const file of present) {\n    let bytes: Buffer\n    try {\n      bytes = await readFile(file.abs)\n    } catch {\n      continue\n    }\n    content.update(`file\\0${file.rel}\\0${bytes.length}\\0`).update(bytes)\n  }\n  const hash = content.digest(\"hex\")\n  hashMemo.set(uiPath, { signature, hash })\n  return hash\n}\n\n/** What the last successful build recorded: the source hash it was built\n *  from, and the bundle it produced (mtime + size) — the stamp only vouches\n *  for THAT bundle, so a bundle replaced behind our back (a checkout of an\n *  older committed one) doesn't inherit it. */\ninterface AppUiBuildStamp {\n  readonly sourcesHash: string\n  readonly bundleMtimeMs: number\n  readonly bundleSize: number\n}\n\n/** Where the build stamp for `uiPath` lives — the daemon state dir, never\n *  the app dir (same reasoning as {@link appUiBuildLogPath}); `<hash>` is\n *  over the absolute `uiPath`, the same key single-flight uses. */\nexport function appUiBuildStampPath(uiPath: string): string {\n  const abs = resolve(uiPath)\n  const home = process.env.AGENTPROTO_HOME ?? join(homedir(), \".agentproto\")\n  const name = basename(dirname(dirname(dirname(abs)))).replace(/[^A-Za-z0-9._-]+/g, \"-\") || \"app\"\n  const hash = createHash(\"sha1\").update(abs).digest(\"hex\").slice(0, 12)\n  return join(home, \"state\", \"app-ui-build\", `${name}-${hash}.json`)\n}\n\nasync function readStamp(uiPath: string): Promise<AppUiBuildStamp | undefined> {\n  try {\n    const raw = JSON.parse(await readFile(appUiBuildStampPath(uiPath), \"utf8\")) as Partial<AppUiBuildStamp>\n    if (\n      typeof raw.sourcesHash === \"string\" &&\n      typeof raw.bundleMtimeMs === \"number\" &&\n      typeof raw.bundleSize === \"number\"\n    ) {\n      return { sourcesHash: raw.sourcesHash, bundleMtimeMs: raw.bundleMtimeMs, bundleSize: raw.bundleSize }\n    }\n  } catch {\n    // Missing or unreadable — no stamp, so mtime alone decides.\n  }\n  return undefined\n}\n\nasync function writeStamp(uiPath: string, stamp: AppUiBuildStamp): Promise<void> {\n  const path = appUiBuildStampPath(uiPath)\n  try {\n    await mkdir(dirname(path), { recursive: true })\n    await writeFile(path, JSON.stringify(stamp), \"utf8\")\n  } catch {\n    // Best-effort — without a stamp the next mtime-stale check just rebuilds.\n  }\n}\n\nconst DEFAULT_BUILD_TIMEOUT_MS = 120_000\nconst DEFAULT_SOURCE_GLOBS = [\"src/**\"]\nconst LOG_TAIL_LINES = 40\n\n/** Where a `ui.build` run's captured output lands — read this on a build\n *  failure for the full log; the returned error carries only a tail.\n *  Lives under the daemon state dir\n *  (`$AGENTPROTO_HOME|~/.agentproto/logs/app-ui-build/<name>-<hash>.log`),\n *  never inside the app dir: an installed app's dir is replaceable code\n *  (swapped on reinstall, packed into `.agentapp`s), not a place for\n *  runtime output. `<hash>` is over the absolute app dir, so two apps with\n *  the same folder name never share a log. */\nexport function appUiBuildLogPath(appDir: string): string {\n  const abs = resolve(appDir)\n  const home = process.env.AGENTPROTO_HOME ?? join(homedir(), \".agentproto\")\n  const name = basename(abs).replace(/[^A-Za-z0-9._-]+/g, \"-\") || \"app\"\n  const hash = createHash(\"sha1\").update(abs).digest(\"hex\").slice(0, 12)\n  return join(home, \"logs\", \"app-ui-build\", `${name}-${hash}.log`)\n}\n\nfunction tailLines(text: string, n: number): string {\n  const lines = text.split(\"\\n\")\n  return lines.slice(-n).join(\"\\n\")\n}\n\n/** A built single-file bundle should never reference `./assets/…` — the\n *  daemon serves `ui.path` standalone (no adjacent static server for a\n *  split build's chunks outside the one `assets/` convention `GET\n *  /apps/:appId/ui/assets/:file` already covers for a *committed* bundle).\n *  A build step that emits a split bundle anyway gets a loud warning, not a\n *  failure — the app may still work if its bundler also copied the chunks\n *  next to `ui.path`. */\nconst ASSET_REFERENCE_RE = /(?:src|href)\\s*=\\s*[\"'](?:\\.{0,2}\\/)?assets\\//i\n\nasync function warnIfNotSingleFile(uiPath: string): Promise<void> {\n  let html: string\n  try {\n    html = await readFile(uiPath, \"utf8\")\n  } catch {\n    return\n  }\n  if (ASSET_REFERENCE_RE.test(html)) {\n    console.warn(\n      `[app-ui-build] \"${uiPath}\" references \"./assets\" after a ui.build run. ` +\n        \"The daemon expects a single-file bundle here — a split build (separate \" +\n        \"JS/CSS chunks under an assets/ dir) may 404 those chunks unless the \" +\n        \"app's bundler inlines everything into one file.\",\n    )\n  }\n}\n\nexport interface EnsureAppUiBuiltInput {\n  /** Absolute app directory — anchors a relative `build.cwd` and the build\n   *  log's location. */\n  readonly dir: string\n  /** Absolute path to the ui bundle's entry file (APP.md's `ui.path`,\n   *  already resolved absolute). Also the single-flight key. */\n  readonly uiPath: string\n  readonly build?: AppUiBuildConfig\n  /** Hard timeout for the build command. Defaults to 120s. */\n  readonly timeoutMs?: number\n  /** Return the previous build's failure, without re-running the command,\n   *  when the sources hash to what that failed build saw. Set by page\n   *  renders (`resolveAppUiBuildState`), which would otherwise re-run a\n   *  broken build on every panel open; left off for explicit callers\n   *  (`app_install`, `app serve`), where re-running IS the retry. */\n  readonly reuseFailure?: boolean\n}\n\nexport type EnsureAppUiBuiltResult =\n  | { readonly ok: true; readonly built: boolean }\n  | { readonly ok: false; readonly error: string }\n\n/** The last failed build per `uiPath` and the source hash it ran on —\n *  see {@link EnsureAppUiBuiltInput.reuseFailure}. Cleared by a success. */\nconst lastFailure = new Map<string, { readonly sourcesHash: string; readonly result: EnsureAppUiBuiltResult }>()\n\n/** In-flight builds keyed on the absolute `uiPath` — an app's bundle lives\n *  at one path regardless of which route (app_install, GET .../ui, the MCP\n *  panel cache, `app serve`) asked for it, so keying here (rather than on\n *  appId, which isn't always known yet — see app-tools.ts's `performInstall`\n *  calling this BEFORE the app has an id) still dedupes every caller. */\nconst inFlight = new Map<string, Promise<EnsureAppUiBuiltResult>>()\n\n/** When the CURRENTLY in-flight build (if any) actually started running its\n *  `build.command` — set right before `runShellCommand`, read by a\n *  non-blocking caller (`resolveAppUiBuildState` below) to render \"building\n *  for Ns\" without itself timing anything. Not set for a call that resolves\n *  from `existing`/freshness alone (no command ever ran). */\nconst buildStartedAt = new Map<string, number>()\n\n/** Peek whether `uiPath` has a build running right now without starting one\n *  — a non-blocking caller (`resolveAppUiBuildState`) uses this to join an\n *  ALREADY-showing build instead of racing a fresh `ensureAppUiBuilt` call\n *  (which would itself re-do the cheap stat/freshness check every time). */\nexport function peekInFlightBuild(uiPath: string): Promise<EnsureAppUiBuiltResult> | undefined {\n  return inFlight.get(uiPath)\n}\n\n/** Paired with {@link peekInFlightBuild}: when that returns a promise, this\n *  is the wall-clock time (`Date.now()`) its build command actually started\n *  — `undefined` if the in-flight promise hasn't reached `runShellCommand`\n *  yet (a handful of stat calls out), in which case \"now\" is as good a\n *  start time as any. */\nexport function peekBuildStartedAt(uiPath: string): number | undefined {\n  return buildStartedAt.get(uiPath)\n}\n\nasync function runEnsure(input: EnsureAppUiBuiltInput): Promise<EnsureAppUiBuiltResult> {\n  const { dir, uiPath, build } = input\n\n  let existing: Stats | undefined\n  try {\n    existing = await stat(uiPath)\n  } catch {\n    existing = undefined\n  }\n\n  if (!build) {\n    if (existing) return { ok: true, built: false }\n    return {\n      ok: false,\n      error:\n        `app ui bundle \"${uiPath}\" is missing and the app declares no \\`ui.build\\` — ` +\n        \"either commit the built bundle, or add a `ui.build` step to APP.md's `ui` \" +\n        \"frontmatter (`ui.build.command`, run with cwd `ui.build.cwd` or the app dir).\",\n    }\n  }\n\n  const buildCwd = build.cwd ? resolveAgainst(dir, build.cwd) : dir\n  const sources = build.sources ?? DEFAULT_SOURCE_GLOBS\n\n  if (existing) {\n    const newest = await newestSourceMtime(buildCwd, sources)\n    if (newest === undefined || newest <= existing.mtimeMs) {\n      return { ok: true, built: false }\n    }\n  }\n\n  // mtime says stale (or there's no bundle): hash the inputs. A hash equal\n  // to the one the CURRENT bundle was built from means only mtimes moved.\n  const sourcesHash = await hashAppUiSources(uiPath, buildCwd, build)\n  if (existing) {\n    const stamp = await readStamp(uiPath)\n    if (\n      stamp &&\n      stamp.sourcesHash === sourcesHash &&\n      stamp.bundleMtimeMs === existing.mtimeMs &&\n      stamp.bundleSize === existing.size\n    ) {\n      return { ok: true, built: false }\n    }\n  }\n  if (input.reuseFailure) {\n    const failed = lastFailure.get(uiPath)\n    if (failed && failed.sourcesHash === sourcesHash) return failed.result\n  }\n\n  const logPath = appUiBuildLogPath(dir)\n  const startedAt = new Date().toISOString()\n  buildStartedAt.set(uiPath, Date.now())\n  const result = await runShellCommand(build.command, buildCwd, input.timeoutMs ?? DEFAULT_BUILD_TIMEOUT_MS)\n\n  const logBody =\n    `[${startedAt}] ui.build: ${build.command}\\n` +\n    `cwd: ${buildCwd}\\n` +\n    `exit: ${result.exitCode}${result.timedOut ? \" (timed out)\" : \"\"}\\n\\n` +\n    `--- stdout ---\\n${result.stdout}\\n--- stderr ---\\n${result.stderr}\\n`\n  try {\n    await mkdir(dirname(logPath), { recursive: true })\n    await writeFile(logPath, logBody, \"utf8\")\n  } catch {\n    // Best-effort — a log write failure must not hide a build failure.\n  }\n\n  if (result.exitCode !== 0) {\n    const failed: EnsureAppUiBuiltResult = {\n      ok: false,\n      error:\n        `ui.build command \"${build.command}\" failed (exit ${result.exitCode}` +\n        `${result.timedOut ? \", timed out\" : \"\"}). See \"${logPath}\" for full output. ` +\n        `Last lines:\\n${tailLines(result.stderr || result.stdout, LOG_TAIL_LINES)}`,\n    }\n    lastFailure.set(uiPath, { sourcesHash, result: failed })\n    return failed\n  }\n\n  let rebuilt: Stats | undefined\n  try {\n    rebuilt = await stat(uiPath)\n  } catch {\n    rebuilt = undefined\n  }\n  if (!rebuilt) {\n    return {\n      ok: false,\n      error:\n        `ui.build command \"${build.command}\" exited 0 but \"${uiPath}\" is still missing — ` +\n        `check the command actually writes its output there. See \"${logPath}\" for full output.`,\n    }\n  }\n\n  await warnIfNotSingleFile(uiPath)\n\n  lastFailure.delete(uiPath)\n  await writeStamp(uiPath, { sourcesHash, bundleMtimeMs: rebuilt.mtimeMs, bundleSize: rebuilt.size })\n  return { ok: true, built: true }\n}\n\n/**\n * Ensure `uiPath` exists and is at least as new as its declared sources,\n * building it first if not. Single-flight per `uiPath`: a second call for\n * the same path while a build is running awaits the same result instead of\n * starting a second build.\n */\nexport async function ensureAppUiBuilt(\n  input: EnsureAppUiBuiltInput,\n): Promise<EnsureAppUiBuiltResult> {\n  const key = input.uiPath\n  const inflight = inFlight.get(key)\n  if (inflight) return inflight\n  const promise = runEnsure(input).finally(() => {\n    inFlight.delete(key)\n    buildStartedAt.delete(key)\n  })\n  inFlight.set(key, promise)\n  return promise\n}\n\nconst RESOLVE_FAST_PATH_MS = 300\nconst READABLE_LOG_TAIL_LINES = 20\nconst RESOLVE_TIMEOUT = Symbol(\"app-ui-build-resolve-timeout\")\n\nasync function readLogTailSafe(dir: string, n: number): Promise<string | undefined> {\n  try {\n    const text = await readFile(appUiBuildLogPath(dir), \"utf8\")\n    const lines = text.split(\"\\n\").filter(line => line.length > 0)\n    const tail = lines.slice(-n).join(\"\\n\")\n    return tail.length > 0 ? tail : undefined\n  } catch {\n    return undefined\n  }\n}\n\nexport type AppUiBuildState =\n  /** Serve `uiPath`. `stale` is set when the bundle on disk is NOT the\n   *  current sources' build — `\"rebuilding\"` (a background build is running;\n   *  the next render picks up its output) or `\"build-failed\"` (the last\n   *  rebuild failed; see the build log) — but is still the best page there\n   *  is. */\n  | { readonly kind: \"ready\"; readonly stale?: \"rebuilding\" | \"build-failed\" }\n  | { readonly kind: \"building\"; readonly startedAt: number; readonly logTail?: string }\n  | { readonly kind: \"error\"; readonly message: string; readonly logPath: string; readonly logTail?: string }\n\n/**\n * Non-blocking status check for `ensureAppUiBuilt`'s outcome — the piece\n * that lets a PAGE render (the `ui://app_ui_<id>/view` MCP resource in\n * app-ui-apps.ts, `GET /apps/:appId/ui` in http-server.ts) never stall on a\n * multi-second `ui.build` run. Joins an already-running build via\n * {@link peekInFlightBuild} (or starts one — still single-flight, since\n * `ensureAppUiBuilt` itself owns `inFlight`) and waits only up to\n * `RESOLVE_FAST_PATH_MS`: long enough that the common \"already built and\n * fresh\" case (a handful of `stat` calls) resolves as `\"ready\"` without ever\n * showing a placeholder, short enough that a real build never blocks the\n * caller — it keeps running in the background regardless, and the NEXT call\n * (after the page's own reload) picks up wherever that build landed.\n *\n * Stale-while-revalidate: when a bundle already exists, a REbuild never\n * shows the \"building\" placeholder or a failure page — the existing bundle\n * is served (`ready` + `stale`) while the build runs, and after it fails.\n * A failed rebuild isn't re-run on each render until its sources change\n * (`reuseFailure`). Only a missing bundle yields `building`/`error`, and that\n * case always retries, since there's nothing else to serve.\n */\nexport async function resolveAppUiBuildState(input: EnsureAppUiBuiltInput): Promise<AppUiBuildState> {\n  const { dir, uiPath } = input\n  let hasBundle: boolean\n  try {\n    hasBundle = (await stat(uiPath)).isFile()\n  } catch {\n    hasBundle = false\n  }\n  const pending = peekInFlightBuild(uiPath) ?? ensureAppUiBuilt({ ...input, reuseFailure: hasBundle })\n\n  const timeout = new Promise<typeof RESOLVE_TIMEOUT>(resolve => {\n    const timer = setTimeout(() => resolve(RESOLVE_TIMEOUT), RESOLVE_FAST_PATH_MS)\n    timer.unref()\n  })\n  const raced = await Promise.race([pending, timeout])\n\n  if (raced === RESOLVE_TIMEOUT) {\n    if (hasBundle) return { kind: \"ready\", stale: \"rebuilding\" }\n    const startedAt = peekBuildStartedAt(uiPath) ?? Date.now()\n    return { kind: \"building\", startedAt, logTail: await readLogTailSafe(dir, READABLE_LOG_TAIL_LINES) }\n  }\n  const result = raced as EnsureAppUiBuiltResult\n  if (!result.ok) {\n    if (hasBundle) return { kind: \"ready\", stale: \"build-failed\" }\n    return {\n      kind: \"error\",\n      message: result.error,\n      logPath: appUiBuildLogPath(dir),\n      logTail: await readLogTailSafe(dir, READABLE_LOG_TAIL_LINES),\n    }\n  }\n  return { kind: \"ready\" }\n}\n"]}