Skip to content

feat(cli): add add-app command for additional frontend apps - #1185

Open
JimiPatel2023 wants to merge 2 commits into
AmanVarshney01:mainfrom
JimiPatel2023:feat/add-app
Open

JimiPatel2023 wants to merge 2 commits into
AmanVarshney01:mainfrom
JimiPatel2023:feat/add-app

Conversation

@JimiPatel2023

@JimiPatel2023 JimiPatel2023 commented Aug 19, 2026 •

Copy link
Copy Markdown

Closes #170, closes #201 — the multi-frontend requests (admin panel + storefront + landing sharing one backend) open since April 2025.

What

Two ways to get additional web frontends into a project, sharing its API, auth, and workspace packages:

# at creation time — one command; apps land before install and the initial git commit
bun create better-t-stack@latest my-app --frontend tanstack-router --api orpc --apps admin:next landing:astro

# on an existing project
create-better-t-stack add-app admin --frontend next

Each app lands in apps/<name> with:

  • its own package name and a unique dev port (3002+, always pinned — including for react-router/svelte/astro which normally rely on framework defaults; substitution is verified, never a silent no-op)
  • its own env module packages/env/src/<name>.ts + exports["./<name>"] entry with rewritten imports (frameworks have different client prefixes, so a Next admin next to a TanStack web app needs its own validation module — same pattern as the existing native.ts); the export is only written when the module is
  • wiring to the project's @{project}/api, @{project}/auth, @{project}/ui and a root dev:<name> script using the project's task-runner filter syntax
  • a bts.jsonc record under a new optional apps array ({ name, frontend, port }), so re-runs allocate the next port and later commands see the extra apps; create --apps also records the flag in reproducibleCommand

Framework choice may differ from the primary web app and is validated against the stack via the existing helpers: tRPC and Clerk imply React-family, Convex excludes Solid/Astro, backend: self is refused (checked before any prompt opens). App names are validated against ^[a-z][a-z0-9-]*$ and a reserved set (web, server, env, ui, …) — the reserved set is also surfaced in the published JSON Schema.

Also exposed as add-app-json, programmatic addApp(), and MCP bts_plan_app / bts_add_app (mirroring the addon plan/apply pair; install: true is rejected like project creation, to avoid MCP client timeouts).

Stack Builder

A compact Extra apps section below the web-frontend grid — zero footprint until used (one dashed "Add app" button), then an inline name + framework form with live validation and framework chips disabled-with-reason using the same gating as the CLI. Planned apps:

  • append --apps to the generated create command — the builder output stays a single command
  • render as apps/<name> chips in the Selected stack panel (framework name on hover, click jumps to the section, × removes) and as removable chips in the section itself
  • persist in builder URLs (?apps=admin:next), saved stacks, and presets/reset behave correctly
  • auto-drop with a toast via the existing analyzeStackCompatibility engine when a stack change makes them incompatible; the whole section hides for fullstack self backends
  • show on the shared /stack page

State is encoded as "name:frontend" strings in a new StackState.apps: string[], so URL/localStorage/share serialization work unchanged. No ports in the UI — the CLI allocates them.

How

No destPrefix threading through the template handlers. The handler builds a synthetic single-frontend config from the project's bts.jsonc (deploy forced to none, addons filtered to task runners so vite-plus/turbo conditionals render correctly) and runs the existing exported generate() in memory, then cherry-picks apps/web/** into apps/<name>/** with the identity rewrites above. Files outside the new app dir touched: root package.json (script + npm allowScripts/overrides union), packages/env/package.json (exports + missing framework deps), bts.jsonc, and on pnpm pnpm-workspace.yaml (union of framework-conditional allowBuilds map entries and minimumReleaseAgeExclude). Catalog references ("catalog:") in cherry-picked package.jsons are resolved back to concrete versions.

create --apps reuses the exact same flow inside createProject, after files are written and before install/git — so the single install and the initial commit include the apps.

Deliberately conservative about user-owned code: the CLI never edits server source; it prints the exact CORS / better-auth trustedOrigins origin additions instead. Two small shared fixes: updateEnvPackageJson preserves export entries it doesn't manage (a later add <addon> would otherwise delete per-app entries — regression-tested), and the add path preloads extra-app manifests.

Out of scope (v1)

Deploy wiring for extra apps (alchemy/vercel/docker assume a single web identity — apps scaffold without it and warn), a second native app, addons targeting extra apps, interactive prompting for --apps during create (use add-app interactively instead), regenerating the project README, and app removal/renaming.

Verification

  • bun run check clean; bun run build clean
  • CLI: apps/cli/test/add-app.test.ts (19 tests: refusals incl. reserved names and per-stack framework gating, dry-run, full write, port allocation, create --apps end-to-end, pnpm allowBuilds/release-age union regression, env-export survival across a later add), MCP contract tests for the new tool pair, schema/input/programmatic API updates — full suite run with no regressions vs a pristine-main baseline
  • Web: apps/web/test/extra-apps.test.ts (encoding, validation messages, compat gating, sanitize, --apps command generation, compat-engine drops); full web suite green including the random-stack invariant tests carrying the new field
  • Manual E2E with the built CLI on Windows: one-command create with 2 cross-framework apps (--apps admin:next landing:astro) → single initial commit includes both apps, bun install + turbo run check-types pass across all 5 workspaces; tanstack+trpc project + add-app admin --frontend next → same; trpc+astro correctly refused before any writes; dry-run writes nothing

Note for maintainer

BetterTStackConfigSchema gained the optional apps field, so apps/web/scripts/generate-schema.ts needs a rerun to republish schema.json to R2 (editors fetch it live; no runtime impact since the CLI reads bts.jsonc with a plain jsonc parse).

Summary by CodeRabbit

  • New Features
    • Added support for creating additional frontend apps during setup or in existing projects.
    • Added interactive, JSON, programmatic, and MCP workflows with dry-run planning.
    • Added Stack Builder controls for selecting, validating, displaying, and removing extra apps.
    • Added automatic ports, configuration, environment integration, workspace wiring, and dependency installation.
  • Bug Fixes
    • Added validation for duplicate, reserved, incompatible, or conflicting app configurations.
  • Documentation
    • Documented CLI commands, APIs, configuration, project structure, and MCP workflows.

@vercel

vercel Bot commented Aug 19, 2026

Copy link
Copy Markdown

@JimiPatel2023 is attempting to deploy a commit to the Better T Stack Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai

coderabbitai Bot commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

Changes

This PR adds support for additional frontend apps during project creation and after creation. It adds shared validation, stack-builder state, app scaffolding, CLI, programmatic, MCP, configuration, tests, and documentation.

Additional frontend app workflow

Layer / File(s) Summary
App contracts and compatibility
packages/types/..., apps/cli/src/prompts/add-app.ts, apps/cli/src/utils/compatibility-rules.ts
Defines app names, frontend frameworks, ports, input schemas, prompts, project configuration fields, and compatibility validation.
Stack-builder app planning
apps/web/src/lib/..., apps/web/src/app/(home)/new/_components/stack-builder/*, apps/web/src/app/(home)/stack/_components/stack-display.tsx
Stores extra apps in stack state, validates and sanitizes entries, synchronizes URL state, displays app badges and summaries, and generates --apps commands.
Generation and package support
packages/template-generator/src/...
Adds virtual-file collection, workspace command generation, package metadata, and preservation of unmanaged environment exports.
App scaffolding and project updates
apps/cli/src/helpers/core/add-app-handler.ts, apps/cli/src/helpers/core/add-handler.ts, apps/cli/src/utils/bts-config.ts
Scaffolds additional apps, configures ports, updates workspace and environment metadata, supports dry runs, persists bts.jsonc, and optionally installs dependencies.
Creation, CLI, and MCP integration
apps/cli/src/helpers/core/command-handlers.ts, apps/cli/src/helpers/core/create-project.ts, apps/cli/src/index.ts, apps/cli/src/mcp.ts
Adds create --apps, add-app, add-app-json, the programmatic addApp API, and the bts_plan_app and bts_add_app MCP tools.
Validation and regression coverage
apps/cli/test/*, apps/web/test/extra-apps.test.ts
Tests invalid configurations, dry runs, generated files, ports, persistence, workspace metadata, MCP operations, schemas, and command generation.
Documentation and agent guidance
apps/web/content/docs/..., plugin/..., README.md
Documents additional-app commands, configuration, APIs, MCP planning, compatibility, and agent workflows.

Possibly related PRs

Merge Risk: 🟡 Moderate · up to 2b4c3

The new multi-frontend scaffolding can leave projects with conflicting app records, recorded ports that do not match generated apps, or apparent success after incomplete configuration or installation; generated shell commands may also behave unsafely for unexpected values. These are bounded but concrete merge-readiness issues that should be fixed or explicitly accepted before merging.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Linked Issues check ⚠️ Warning The PR meets Astro and multiple web-framework goals [#201] but does not implement React Native/Expo or shared web/mobile routing [#170]. Implement the React Native/Expo and shared routing requirements, or explicitly split and defer those requirements from [#170].
Docstring Coverage ⚠️ Warning Docstring coverage is 25.93% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly describes the primary change: adding the add-app command for additional frontend applications.
Out of Scope Changes check ✅ Passed The changes support additional frontend apps across CLI, APIs, MCP, Stack Builder, templates, tests, and documentation without unrelated scope.
✨ Finishing Touches 💡 1
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 8

🧹 Nitpick comments (2)
plugin/skills/add-to-project/SKILL.md (1)

31-31: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Name the supported app frameworks.

Replace “React-family frameworks” with the natural-language names and WebFrontendSchema values. Identify the React-family subset separately: TanStack Router (tanstack-router), React Router (react-router), TanStack Start (tanstack-start), and Next.js (next). Also document Nuxt (nuxt), Svelte (svelte), Solid (solid), and Astro (astro) as the other supported web frameworks.

Source: Learnings

apps/cli/src/utils/bts-config.ts (1)

30-61: 📐 Maintainability & Code Quality | 🔵 Trivial | 🏗️ Heavy lift

Consider returning a Result instead of a boolean.

The change correctly stops hiding write failures. The boolean still discards the reason, so add-app-handler.ts Line 448 can only print a generic warning and cannot distinguish a missing file from a permission error or a JSONC parse failure.

The CLI coding guideline states: "In CLI code, prefer better-result over ad-hoc try/catch for recoverable flows; return typed Result<T, E> and use Result.ok, Result.err, Result.try, and Result.tryPromise."

This is not a regression from this PR, because the previous version already used try/catch. Treat it as a follow-up if you prefer to keep the caller changes small.

♻️ Sketch of a Result-based signature
-): Promise<boolean> {
-  try {
-    const configPath = path.join(projectDir, BTS_CONFIG_FILE);
-
-    if (!(await fs.pathExists(configPath))) {
-      return false;
-    }
+): Promise<Result<void, CLIError>> {
+  const configPath = path.join(projectDir, BTS_CONFIG_FILE);
+
+  if (!(await fs.pathExists(configPath))) {
+    return Result.err(new CLIError({ message: `${BTS_CONFIG_FILE} not found in ${projectDir}` }));
+  }
+
+  return Result.tryPromise({
+    try: async () => {
+      let content = await fs.readFile(configPath, "utf-8");
+      for (const [key, value] of Object.entries(updates)) {
+        const edits = modify(content, [key], value, { formattingOptions: { tabSize: 2 } });
+        content = applyEdits(content, edits);
+      }
+      await fs.writeFile(configPath, content, "utf-8");
+    },
+    catch: (e) =>
+      new CLIError({
+        message: `Failed to update ${BTS_CONFIG_FILE}: ${e instanceof Error ? e.message : String(e)}`,
+        cause: e,
+      }),
+  });
+}

Update add-handler.ts Line 455 and add-app-handler.ts Line 444 accordingly.

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 4215d43f-6ae4-49b9-a866-e969c10a1f5d

📥 Commits

Reviewing files that changed from the base of the PR and between 93f9b5c and d8a7e49.

📒 Files selected for processing (29)
  • apps/cli/src/helpers/core/add-app-handler.ts
  • apps/cli/src/helpers/core/add-handler.ts
  • apps/cli/src/helpers/core/detect-project-config.ts
  • apps/cli/src/index.ts
  • apps/cli/src/mcp.ts
  • apps/cli/src/prompts/add-app.ts
  • apps/cli/src/utils/bts-config.ts
  • apps/cli/src/utils/compatibility-rules.ts
  • apps/cli/test/add-app.test.ts
  • apps/cli/test/input-schemas.test.ts
  • apps/cli/test/mcp.test.ts
  • apps/cli/test/programmatic-api.test.ts
  • apps/cli/test/schema-command.test.ts
  • apps/web/content/docs/bts-config.mdx
  • apps/web/content/docs/cli/agent-workflows.mdx
  • apps/web/content/docs/cli/index.mdx
  • apps/web/content/docs/cli/options.mdx
  • apps/web/content/docs/cli/programmatic-api.mdx
  • apps/web/content/docs/project-structure.mdx
  • packages/template-generator/src/core/virtual-fs.ts
  • packages/template-generator/src/index.ts
  • packages/template-generator/src/post-process/index.ts
  • packages/template-generator/src/post-process/package-configs.ts
  • packages/types/src/json-schema.ts
  • packages/types/src/schemas.ts
  • packages/types/src/types.ts
  • plugin/agents/stack-architect.md
  • plugin/commands/add.md
  • plugin/skills/add-to-project/SKILL.md

Included review availability: Your plan provides up to 8 included reviews per hour; 7 remain after this review.

Comment on lines +258 to +281
// Examples that remain compatible with the new app's framework
const keptExamples = (existingConfig.examples ?? []).filter((example) => {
if (example === "todo") {
return isExampleTodoAllowed(
existingConfig.backend,
existingConfig.database,
existingConfig.api,
);
}
if (example === "ai") {
return isExampleAIAllowed(existingConfig.backend, [frontend]);
}
return false;
});
const droppedExamples = (existingConfig.examples ?? []).filter(
(example) => example !== "none" && !keptExamples.includes(example),
);
if (!isSilent() && droppedExamples.length > 0) {
log.info(
pc.dim(
`Skipping example${droppedExamples.length > 1 ? "s" : ""} not supported by ${frontend}: ${droppedExamples.join(", ")}`,
),
);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Correct the dropped-example message attribution.

The message states the examples are "not supported by ${frontend}". The todo example is filtered by isExampleTodoAllowed(backend, database, api), which does not consider the frontend. If todo is dropped because of the backend or database, the message names the wrong cause.

Report the framework only for the examples that the frontend actually gates.

💡 Proposed message fix
   if (!isSilent() && droppedExamples.length > 0) {
     log.info(
       pc.dim(
-        `Skipping example${droppedExamples.length > 1 ? "s" : ""} not supported by ${frontend}: ${droppedExamples.join(", ")}`,
+        `Skipping example${droppedExamples.length > 1 ? "s" : ""} not supported by this stack: ${droppedExamples.join(", ")}`,
       ),
     );
   }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Examples that remain compatible with the new app's framework
const keptExamples = (existingConfig.examples ?? []).filter((example) => {
if (example === "todo") {
return isExampleTodoAllowed(
existingConfig.backend,
existingConfig.database,
existingConfig.api,
);
}
if (example === "ai") {
return isExampleAIAllowed(existingConfig.backend, [frontend]);
}
return false;
});
const droppedExamples = (existingConfig.examples ?? []).filter(
(example) => example !== "none" && !keptExamples.includes(example),
);
if (!isSilent() && droppedExamples.length > 0) {
log.info(
pc.dim(
`Skipping example${droppedExamples.length > 1 ? "s" : ""} not supported by ${frontend}: ${droppedExamples.join(", ")}`,
),
);
}
// Examples that remain compatible with the new app's framework
const keptExamples = (existingConfig.examples ?? []).filter((example) => {
if (example === "todo") {
return isExampleTodoAllowed(
existingConfig.backend,
existingConfig.database,
existingConfig.api,
);
}
if (example === "ai") {
return isExampleAIAllowed(existingConfig.backend, [frontend]);
}
return false;
});
const droppedExamples = (existingConfig.examples ?? []).filter(
(example) => example !== "none" && !keptExamples.includes(example),
);
if (!isSilent() && droppedExamples.length > 0) {
log.info(
pc.dim(
`Skipping example${droppedExamples.length > 1 ? "s" : ""} not supported by this stack: ${droppedExamples.join(", ")}`,
),
);
}

Comment on lines +444 to +457
const configUpdated = await updateBtsConfig(projectDir, {
apps: [...existingApps, { name: appName, frontend, port }],
});
if (!configUpdated && !isSilent()) {
log.warn(
pc.yellow(
"Could not update bts.jsonc. Add the new app to its 'apps' array manually so future commands see it.",
),
);
}

if (input.install) {
await installDependencies({ projectDir, packageManager });
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Report the bts.jsonc write failure in silent mode, and wrap installDependencies.

Two problems in this block:

  1. configUpdated === false is surfaced only when !isSilent(). In silent mode, which is the MCP and programmatic path, the function still returns success: true at Line 473 while bts.jsonc does not contain the new app. The next add-app call then reuses the same port, and add-handler.ts Line 344 does not preload the new app manifest. Propagate the failure in the result so an agent can react.

  2. installDependencies is awaited without Result.tryPromise. If it rejects, the error escapes addAppHandlerInternal and addAppHandler as an unhandled rejection. The app files are already written at this point, so a dependency-install failure must not crash the command.

Based on the coding guideline "In CLI code, prefer better-result over ad-hoc try/catch for recoverable flows; return typed Result<T, E>".

🛠️ Proposed fix
   const configUpdated = await updateBtsConfig(projectDir, {
     apps: [...existingApps, { name: appName, frontend, port }],
   });
-  if (!configUpdated && !isSilent()) {
-    log.warn(
-      pc.yellow(
-        "Could not update bts.jsonc. Add the new app to its 'apps' array manually so future commands see it.",
-      ),
-    );
-  }
+  const configWarning = configUpdated
+    ? undefined
+    : `Could not update bts.jsonc. Add {"name":"${appName}","frontend":"${frontend}","port":${port}} to its 'apps' array manually so future commands see it.`;
+  if (configWarning && !isSilent()) {
+    log.warn(pc.yellow(configWarning));
+  }
 
   if (input.install) {
-    await installDependencies({ projectDir, packageManager });
+    const installResult = await Result.tryPromise({
+      try: () => installDependencies({ projectDir, packageManager }),
+      catch: (e) =>
+        new CLIError({
+          message: `Failed to install dependencies: ${e instanceof Error ? e.message : String(e)}`,
+          cause: e,
+        }),
+    });
+    if (installResult.isErr() && !isSilent()) {
+      log.warn(pc.yellow(installResult.error.message));
+    }
   }

Then include configWarning in the returned AddAppResult (add an optional warning?: string field to the interface at Line 41) so silent callers see it.

Source: Coding guidelines

Comment on lines +571 to +597
function getPortConfigPath(appDir: string, frontend: AddedApp["frontend"]): string | undefined {
switch (frontend) {
case "tanstack-router":
case "tanstack-start":
case "solid":
return `${appDir}/vite.config.ts`;
case "nuxt":
return `${appDir}/nuxt.config.ts`;
default:
return undefined;
}
}

function pinDevPortInConfigFiles(
vfs: VirtualFileSystem,
appDir: string,
frontend: AddedApp["frontend"],
port: number,
): void {
const configPath = getPortConfigPath(appDir, frontend);
if (!configPath) return;

const content = vfs.readFile(configPath);
if (!content) return;

vfs.writeFile(configPath, content.replaceAll("port: 3001", `port: ${port}`));
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

The new app's port is applied by unverified string substitution. Both sites pin the dev port by matching a template-specific literal. Neither site confirms that the substitution occurred, and there is no exhaustive mapping from every AddedApp["frontend"] value to a pinning strategy. When a match fails, the app keeps the template default, collides with an existing app, and the command still reports and persists the requested port.

  • apps/cli/src/helpers/core/add-app-handler.ts#L571-L597: make the getPortConfigPath switch exhaustive over the frontend union so a new frontend is a compile error, and warn when replaceAll("port: 3001", ...) changes nothing.
  • apps/cli/src/helpers/core/add-app-handler.ts#L557-L565: append --port ${port} when the next dev script contains no --port flag, instead of relying on a replace that can be a no-op.
📍 Affects 1 file
  • apps/cli/src/helpers/core/add-app-handler.ts#L571-L597 (this comment)
  • apps/cli/src/helpers/core/add-app-handler.ts#L557-L565

Comment thread apps/cli/src/mcp.ts Resolved
Comment on lines +90 to +97
const options = WEB_FRONTEND_OPTIONS.filter((option) =>
validateAddAppFrontendCompatibility(option.value, config).isOk(),
);

const response = await navigableSelect<AddAppFrontend>({
message: "Choose a framework for the new app",
options,
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Return the compatibility error before opening an empty selector.

When config.backend === "self", validateAddAppFrontendCompatibility() rejects every frontend. Lines 90-92 then produce an empty options array. Line 94 opens navigableSelect() with no valid selection.

Return a CLIError before the prompt, or validate this project state in the handler before calling getAppFrontend(). This gives the user the required reason instead of an empty selection flow.

Comment thread packages/types/src/schemas.ts Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: cdb5941e-a11d-4054-a554-159b9342ecba

📥 Commits

Reviewing files that changed from the base of the PR and between d8a7e49 and 6531d33.

📒 Files selected for processing (14)
  • apps/web/content/docs/cli/index.mdx
  • apps/web/src/app/(home)/new/_components/stack-builder/add-app-commands-box.tsx
  • apps/web/src/app/(home)/new/_components/stack-builder/extra-apps-section.tsx
  • apps/web/src/app/(home)/new/_components/stack-builder/index.tsx
  • apps/web/src/app/(home)/new/_components/stack-builder/tech-categories.tsx
  • apps/web/src/app/(home)/new/_components/utils.ts
  • apps/web/src/app/(home)/stack/_components/stack-display.tsx
  • apps/web/src/lib/constant.ts
  • apps/web/src/lib/extra-apps.ts
  • apps/web/src/lib/sanitize-stack-addons.ts
  • apps/web/src/lib/stack-url-keys.ts
  • apps/web/src/lib/stack-url-state.client.ts
  • apps/web/src/lib/stack-url-state.ts
  • apps/web/test/extra-apps.test.ts

Included review availability: Your plan provides up to 8 included reviews per hour; 6 remain after this review.

Comment thread apps/web/src/lib/extra-apps.ts Outdated
Comment on lines +142 to +156
export function generateAddAppCommands(stack: StackState): string[] {
const apps = stack.apps.map(parseExtraApp).filter((app): app is ExtraApp => app !== null);
if (apps.length === 0) return [];

const runners = {
npm: "npx",
pnpm: "pnpm dlx",
default: "bunx",
};
const runner = runners[stack.packageManager as keyof typeof runners] || runners.default;

return apps.map(
(app) =>
`${runner} create-better-t-stack@latest add-app ${app.name} --frontend ${app.frontend}`,
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Validate every dynamic shell token before rendering copied commands.

These commands do not execute in the browser. They can execute unintended shell syntax after a user copies and runs them. generateAddAppCommands only parses apps, and AddAppCommandsBox uses projectName without validation or shell-safe encoding.

  • apps/web/src/lib/extra-apps.ts#L142-L156: sanitize stack.apps with sanitizeExtraApps(stack.apps, stack) before generating commands.
  • apps/web/src/app/(home)/new/_components/stack-builder/add-app-commands-box.tsx#L34-L35: use the same validated project-name token as the create command, or safely quote the directory argument.
  • apps/web/test/extra-apps.test.ts#L134-L153: add cases for malformed app values and project names containing shell metacharacters.
📍 Affects 3 files
  • apps/web/src/lib/extra-apps.ts#L142-L156 (this comment)
  • apps/web/src/app/(home)/new/_components/stack-builder/add-app-commands-box.tsx#L34-L35
  • apps/web/test/extra-apps.test.ts#L134-L153

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Nitpick comments (4)
apps/cli/src/helpers/core/command-handlers.ts (1)

426-431: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Share the --apps suffix construction with create-project.ts.

This block builds the --apps name:frontend ... suffix for the returned reproducibleCommand and for history. apps/cli/src/helpers/core/create-project.ts Lines 148-155 builds the same suffix again for the value persisted in bts.jsonc. The two strings must stay identical. Extract one helper and call it from both sites.

apps/cli/test/add-app.test.ts (1)

86-94: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Remove the directory before you create it.

writeSyntheticProject calls rm(..., { recursive: true, force: true }) first, but this test does not. If SMOKE_DIR survives between runs and a previous run left a bts.jsonc in add-app-missing-config, the assertion fails. Add the same reset for determinism.

Based on the coding guideline "Keep CLI tests deterministic and reuse shared setup utilities from apps/cli/test/setup.ts".

🛠️ Proposed change
       const projectDir = join(SMOKE_DIR, "add-app-missing-config");
+      await rm(projectDir, { recursive: true, force: true });
       await mkdir(projectDir, { recursive: true });

Source: Coding guidelines

apps/web/test/extra-apps.test.ts (1)

128-131: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Tighten the "keeps compatible apps" assertion.

result.adjustedStack?.apps ?? ["admin:next"] passes when adjustedStack is undefined and also when adjustedStack.apps is undefined. The test therefore cannot detect a regression that drops the apps key from the adjusted stack. Assert the intended contract directly.

🛠️ Proposed change
   test("keeps compatible apps untouched", () => {
     const result = analyzeStackCompatibility(createStack({ apps: ["admin:next"] }));
-    expect(result.adjustedStack?.apps ?? ["admin:next"]).toEqual(["admin:next"]);
+    expect(result.changes.some((change) => change.category === "apps")).toBe(false);
+    if (result.adjustedStack) {
+      expect(result.adjustedStack.apps).toEqual(["admin:next"]);
+    }
   });
packages/types/src/schemas.ts (1)

478-537: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚖️ Poor tradeoff

Use camelCase for the new schema values.

WebFrontendSchema, AppNameSchema, AddedAppSchema, AddedAppSpecSchema, AddAppInputSchema, RESERVED_APP_NAMES, and WEB_FRONTEND_VALUES are runtime values. Rename these exports to camelCase and update their imports.

As per coding guidelines, **/*.{ts,tsx} requires camelCase for functions and variables. PascalCase is for types and components.

Also applies to: 589-600, 689-689

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: d6e35ebc-0b0e-4235-8940-620233e7617d

📥 Commits

Reviewing files that changed from the base of the PR and between 6531d33 and 46a42d8.

📒 Files selected for processing (20)
  • apps/cli/src/helpers/core/add-app-handler.ts
  • apps/cli/src/helpers/core/command-handlers.ts
  • apps/cli/src/helpers/core/create-project.ts
  • apps/cli/src/index.ts
  • apps/cli/src/mcp.ts
  • apps/cli/src/utils/bts-config.ts
  • apps/cli/test/add-app.test.ts
  • apps/cli/test/input-schemas.test.ts
  • apps/cli/test/schema-command.test.ts
  • apps/web/content/docs/cli/index.mdx
  • apps/web/content/docs/cli/options.mdx
  • apps/web/src/app/(home)/new/_components/stack-builder/extra-apps-section.tsx
  • apps/web/src/app/(home)/new/_components/stack-builder/index.tsx
  • apps/web/src/app/(home)/new/_components/stack-builder/selected-stack-badges.tsx
  • apps/web/src/app/(home)/stack/_components/stack-display.tsx
  • apps/web/src/lib/extra-apps.ts
  • apps/web/src/lib/stack-utils.ts
  • apps/web/test/extra-apps.test.ts
  • packages/types/src/json-schema.ts
  • packages/types/src/schemas.ts

Included review availability: Your plan provides up to 8 included reviews per hour; 5 remain after this review.

Comment on lines +614 to +639
function pinDevPortInConfigFiles(
vfs: VirtualFileSystem,
appDir: string,
frontend: AddedApp["frontend"],
port: number,
): void {
const configPath = getPortConfigPath(appDir, frontend);
if (!configPath) return;

const content = vfs.readFile(configPath);
if (!content) return;

const updated = content.replaceAll("port: 3001", `port: ${port}`);
if (updated === content) {
// The template no longer matches the expected literal — don't record a
// port that was never applied without telling the user.
if (!isSilent()) {
log.warn(
pc.yellow(`Could not pin the dev port in ${configPath}. Set port ${port} manually.`),
);
}
return;
}

vfs.writeFile(configPath, updated);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Propagate the failed port pin to the result in silent mode.

pinDevPortInConfigFiles reports the failure only through log.warn when !isSilent(). The silent path is used by addApp(), the MCP tools, and create --apps. In that path the function returns without a signal, and the handler still records port in bts.jsonc and in AddAppResult. The new app then starts on the template default port and can collide with the primary web app, while the recorded state says otherwise.

The handler already collects a warnings array at Line 458. Return the failure from this helper and add it to that array so silent callers receive it in result.warning.

🛠️ Proposed change
-function pinDevPortInConfigFiles(
+function pinDevPortInConfigFiles(
   vfs: VirtualFileSystem,
   appDir: string,
   frontend: AddedApp["frontend"],
   port: number,
-): void {
+): string | undefined {
   const configPath = getPortConfigPath(appDir, frontend);
-  if (!configPath) return;
+  if (!configPath) return undefined;
 
   const content = vfs.readFile(configPath);
-  if (!content) return;
+  if (!content) return undefined;
 
   const updated = content.replaceAll("port: 3001", `port: ${port}`);
   if (updated === content) {
-    // The template no longer matches the expected literal — don't record a
-    // port that was never applied without telling the user.
-    if (!isSilent()) {
-      log.warn(
-        pc.yellow(`Could not pin the dev port in ${configPath}. Set port ${port} manually.`),
-      );
-    }
-    return;
+    return `Could not pin the dev port in ${configPath}. Set port ${port} manually.`;
   }
 
   vfs.writeFile(configPath, updated);
+  return undefined;
 }

Then capture the return value at Line 385 and push it into warnings before the result is built.

Comment on lines +132 to +146
for (const app of extraApps) {
const appResult = await addAppHandler(
{ projectDir, name: app.name, frontend: app.frontend, install: false },
{ silent: true },
);
const appPort = appResult?.success ? appResult.port : undefined;
if (appPort === undefined) {
yield* new ProjectCreationError({
phase: "extra-apps",
message: appResult?.error ?? `Failed to add app '${app.name}'.`,
});
} else {
addedApps.push({ name: app.name, frontend: app.frontend, port: appPort });
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Surface appResult.warning for each scaffolded app.

addAppHandler returns a warning field for non-fatal problems, for example a failed bts.jsonc update. This loop reads only success and port, so those warnings are discarded. A user who runs create --apps then receives a project whose bts.jsonc does not list an app that exists on disk, with no message.

Collect the warnings and print them with the wiring note when not silent.

🛠️ Proposed change
       const addedApps: AddedApp[] = [];
+      const appWarnings: string[] = [];
 
       for (const app of extraApps) {
         const appResult = await addAppHandler(
           { projectDir, name: app.name, frontend: app.frontend, install: false },
           { silent: true },
         );
         const appPort = appResult?.success ? appResult.port : undefined;
         if (appPort === undefined) {
           yield* new ProjectCreationError({
             phase: "extra-apps",
             message: appResult?.error ?? `Failed to add app '${app.name}'.`,
           });
         } else {
+          if (appResult?.warning) appWarnings.push(appResult.warning);
           addedApps.push({ name: app.name, frontend: app.frontend, port: appPort });
         }
       }

Then log appWarnings inside the existing if (!isSilent()) block.

Comment on lines +113 to +124
export function getAddAppInputJsonSchema() {
const schema = z.toJSONSchema(AddAppInputSchema) as {
properties?: { name?: { not?: { enum: string[] } } };
};

// The reserved-name rule lives in a zod refinement, which does not
// serialize; surface it so JSON-Schema consumers see it too.
if (schema.properties?.name) {
schema.properties.name.not = { enum: [...RESERVED_APP_NAMES].sort() };
}

return schema;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -eu

printf '%s\n' '--- candidate files ---'
git ls-files 'packages/types/src/json-schema.ts' 'packages/types/src/*' | sed -n '1,120p'

printf '%s\n' '--- relevant declarations and uses ---'
rg -n -C 5 'get(AddAppInput|CreateInput)JsonSchema|CreateInputSchema|AddedAppSpecSchema|RESERVED_APP_NAMES|reserved|web:next' packages/types/src packages/types 2>/dev/null | sed -n '1,260p'

printf '%s\n' '--- json-schema.ts outline ---'
ast-grep outline packages/types/src/json-schema.ts 2>/dev/null || true

printf '%s\n' '--- json-schema.ts relevant lines ---'
sed -n '1,180p' packages/types/src/json-schema.ts

Repository: AmanVarshney01/create-better-t-stack

Length of output: 22922


🏁 Script executed:

#!/bin/bash
set -eu

printf '%s\n' '--- package and test context ---'
rg -n -C 4 '"zod"|json schema|JSON Schema|getCreateInputJsonSchema|createInput' package.json packages/*/package.json pnpm-lock.yaml yarn.lock package-lock.json 2>/dev/null | sed -n '1,260p'

printf '%s\n' '--- complete schema definitions ---'
sed -n '491,565p' packages/types/src/schemas.ts

printf '%s\n' '--- JSON Schema exports and tests ---'
rg -n -C 5 'getAllJsonSchemas|getCreateInputJsonSchema|getAddAppInputJsonSchema|toJSONSchema' --glob '*.{ts,tsx,js,jsx,json}' . | sed -n '1,320p'

printf '%s\n' '--- standalone structural verifier ---'
python3 - <<'PY'
import re
from pathlib import Path

source = Path("packages/types/src/schemas.ts").read_text()
reserved = re.search(r'RESERVED_APP_NAMES\s*=\s*new Set\(\s*\[(.*?)\]\s*\)', source, re.S)
spec = re.search(r'AddedAppSpecSchema\s*=\s*z\s*\.\s*string\(\)\s*\.regex\(\s*new RegExp\(`([^`]+)`', source, re.S)
create = re.search(r'CreateInputSchema\s*=\s*z\s*\.\s*object\(\s*\{(.*?)\n\s*\}\)', source, re.S)

assert reserved and spec and create, "Could not locate the expected schema declarations"
names = re.findall(r'"([^"]+)"', reserved.group(1))
pattern = spec.group(1)
create_body = create.group(1)

assert "apps: z.array(AddedAppSpecSchema).optional()" in create_body
assert "refine" in source[source.index("AddedAppSpecSchema"):source.index("CreateInputSchema")]
assert "web" in names and "next" in pattern

# The serialized regex validates the reserved spec because the refinement is
# not part of the regex; the Zod refinement rejects it separately.
candidate = "web:next"
regex = re.compile(pattern.replace("${WebFrontendSchema.options.join('|')}", "(?:tanstack-router|next|react|vue|svelte|solid|astro)"))
assert regex.fullmatch(candidate), candidate
assert candidate.split(":")[0] in names

print("CreateInputSchema.apps -> AddedAppSpecSchema")
print("Serialized regex accepts:", candidate)
print("Zod refinement rejects reserved prefix:", candidate.split(":")[0])
print("A JSON-Schema exclusion is required to preserve this refinement.")
PY

Repository: AmanVarshney01/create-better-t-stack

Length of output: 13109


🏁 Script executed:

#!/bin/bash
set -eu

printf '%s\n' '--- package and test context ---'
rg -n -C 4 '"zod"|json schema|JSON Schema|getCreateInputJsonSchema|createInput' package.json packages/*/package.json pnpm-lock.yaml yarn.lock package-lock.json 2>/dev/null | sed -n '1,260p'

printf '%s\n' '--- complete schema definitions ---'
sed -n '491,565p' packages/types/src/schemas.ts

printf '%s\n' '--- JSON Schema exports and tests ---'
rg -n -C 5 'getAllJsonSchemas|getCreateInputJsonSchema|getAddAppInputJsonSchema|toJSONSchema' --glob '*.{ts,tsx,js,jsx,json}' . | sed -n '1,320p'

printf '%s\n' '--- standalone structural verifier ---'
python3 - <<'PY'
import re
from pathlib import Path

source = Path("packages/types/src/schemas.ts").read_text()
reserved = re.search(r'RESERVED_APP_NAMES\s*=\s*new Set\(\s*\[(.*?)\]\s*\)', source, re.S)
spec = re.search(r'AddedAppSpecSchema\s*=\s*z\s*\.\s*string\(\)\s*\.regex\(\s*new RegExp\(`([^`]+)`', source, re.S)
create = re.search(r'CreateInputSchema\s*=\s*z\s*\.\s*object\(\s*\{(.*?)\n\s*\}\)', source, re.S)

assert reserved and spec and create, "Could not locate the expected schema declarations"
names = re.findall(r'"([^"]+)"', reserved.group(1))
pattern = spec.group(1)
create_body = create.group(1)

assert "apps: z.array(AddedAppSpecSchema).optional()" in create_body
assert "refine" in source[source.index("AddedAppSpecSchema"):source.index("CreateInputSchema")]
assert "web" in names and "next" in pattern

candidate = "web:next"
regex = re.compile(pattern.replace("${WebFrontendSchema.options.join('|')}", "(?:tanstack-router|next|react|vue|svelte|solid|astro)"))
assert regex.fullmatch(candidate), candidate
assert candidate.split(":")[0] in names

print("CreateInputSchema.apps -> AddedAppSpecSchema")
print("Serialized regex accepts:", candidate)
print("Zod refinement rejects reserved prefix:", candidate.split(":")[0])
print("A JSON-Schema exclusion is required to preserve this refinement.")
PY

Repository: AmanVarshney01/create-better-t-stack

Length of output: 13109


🌐 Web query:

Zod 4 z.toJSONSchema refinements unrepresentable refinements omitted JSON Schema

💡 Result:

In Zod 4, the z.toJSONSchema function converts Zod schemas into their closest JSON Schema equivalents [1][2]. Because Zod supports types and runtime logic that have no direct analog in the JSON Schema specification, the conversion process is inherently lossy [3][4]. Handling Unrepresentable Refinements and Types: By default, when z.toJSONSchema encounters an unrepresentable construct—such as custom .refine() logic, .transform() operations, or specialized types like z.bigint(), z.date(), z.map(), z.set(), and z.function()—it will throw an error [3][2][5]. This is intended to prevent the creation of misleading or invalid schemas [2][5]. Options for Unrepresentable Constructs: You can manage this behavior using the unrepresentable option in the z.toJSONSchema configuration [1][2]: 1. "throw" (Default): The process throws an error if any unrepresentable type or refinement is encountered [1][6]. 2. "any": Unrepresentable types are converted to {} (the JSON Schema equivalent of unknown), allowing the generation to proceed without throwing [1][7]. 3. Custom Function: You can provide a function to the unrepresentable option to return a specific JSON Schema representation for identified unrepresentable types [6]. Additionally, an override function can be provided to z.toJSONSchema to manually inject logic for modifying the generated schema for specific Zod types, which is often used to map Zod-specific types to standard JSON Schema formats (e.g., converting a z.date() to {"type": "string", "format": "date-time"}) [8][6]. Because custom refinements (like those created with .refine() or .superRefine()) cannot be converted into standard JSON Schema keywords, they are omitted from the output entirely [3][4]. Consequently, the resulting JSON Schema will represent the base data structure but will not enforce the custom business logic or constraints defined within those refinements [3][4].

Citations:


🏁 Script executed:

#!/bin/bash
set -eu

python3 - <<'PY'
import re
from pathlib import Path

source = Path("packages/types/src/schemas.ts").read_text()

reserved_match = re.search(
    r'RESERVED_APP_NAMES\s*=\s*new Set\(\s*\[(.*?)\]\s*\)',
    source,
    re.S,
)
assert reserved_match, "RESERVED_APP_NAMES declaration not found"
reserved = re.findall(r'"([^"]+)"', reserved_match.group(1))

spec_start = source.index("export const AddedAppSpecSchema")
spec_end = source.index("export const CreateInputSchema")
spec_source = source[spec_start:spec_end]

create_start = source.index("export const CreateInputSchema")
create_end = source.index("export const CLIInputSchema")
create_source = source[create_start:create_end]

assert "AddedAppSpecSchema" in spec_source
assert ".refine(" in spec_source
assert "apps: z.array(AddedAppSpecSchema).optional()" in create_source
assert "web" in reserved

# The regex accepts the reserved prefix because the reserved-name check is a
# separate refinement.
assert re.fullmatch(r"[a-z][a-z0-9-]{0,29}:(?:[a-z-]+)", "web:next")
print("CreateInputSchema.apps uses AddedAppSpecSchema")
print("AddedAppSpecSchema has a separate reserved-name refinement")
print("web:next matches the serializable shape and is rejected only by the refinement")
PY

Repository: AmanVarshney01/create-better-t-stack

Length of output: 359


🌐 Web query:

site:zod.dev/json-schema refinements unrepresentable z.toJSONSchema default

💡 Result:

When using z.toJSONSchema in Zod, the unrepresentable option determines how the library handles Zod schemas that lack a direct equivalent in JSON Schema, such as dates or BigInts [1]. By default, Zod throws an error when it encounters an unrepresentable schema [1]. You can modify this behavior using the unrepresentable option: 1. Setting unrepresentable to "any": This converts any unrepresentable types into an empty JSON Schema object {}, which is equivalent to unknown [1]. 2. Providing a custom handler function: You can pass a function to handle specific cases [1]. This function receives the Zod schema, its path, and an error message [1]. It should return a valid JSON Schema object, the string "any", or "throw" (the default behavior) [1]. Regarding default values, if a schema uses.default with a value that cannot be serialized into JSON, it is also treated as unrepresentable and processed through the same unrepresentable handler mechanism [1]. If the handler returns a schema, that schema is used; otherwise, the default behavior of throwing an error applies [1].

Citations:


🏁 Script executed:

#!/bin/bash
set -eu

curl -fsSL https://raw.githubusercontent.com/colinhacks/zod/v4.4.3/packages/docs/content/json-schema.mdx \
  | rg -n -C 5 'unrepresentable|refine|refinement|override' \
  | sed -n '1,220p'

curl -fsSL https://raw.githubusercontent.com/colinhacks/zod/v4.4.3/packages/zod/src/v4/core/to-json-schema.ts \
  | rg -n -C 8 'refinement|unrepresentable|onattach|ZodTransform' \
  | sed -n '1,260p'

Repository: AmanVarshney01/create-better-t-stack

Length of output: 7301


🏁 Script executed:

#!/bin/bash
set -eu

curl -fsSL https://raw.githubusercontent.com/colinhacks/zod/v4.4.3/packages/zod/src/v4/core/to-json-schema.ts \
  | sed -n '300,430p;620,760p' \
  | sed -n '1,280p'

Repository: AmanVarshney01/create-better-t-stack

Length of output: 4160


Preserve reserved-name validation in getCreateInputJsonSchema().

CreateInputSchema.apps uses AddedAppSpecSchema, whose refinement rejects reserved prefixes such as web in web:next. Add a constraint under apps.items that rejects reserved-name specifications, and test that both Zod and the generated JSON Schema reject web:next.

auth: AuthSchema.optional(),
payments: PaymentsSchema.optional(),
frontend: z.array(FrontendSchema).optional(),
apps: z.array(AddedAppSpecSchema).optional(),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Reject duplicate app identities and ports.

The schemas validate each app independently but do not validate the app collection. This permits duplicate names in create input and duplicate names or ports in persisted configuration. These values can produce conflicting apps/<name> targets and dev-server assignments.

  • packages/types/src/schemas.ts#L553-L553: reject duplicate app names after parsing each name:framework spec.
  • packages/types/src/schemas.ts#L649-L649: reject duplicate app names and duplicate ports in persisted app records.
📍 Affects 1 file
  • packages/types/src/schemas.ts#L553-L553 (this comment)
  • packages/types/src/schemas.ts#L649-L649

Adds two ways to get additional web frontends (admin panel, landing page, ...) into a project, sharing its API, auth, and workspace packages:

- add-app <name> --frontend <framework> scaffolds an app into apps/<name> of an existing project: unique dev port (3002+), per-app env module with rewritten imports, root dev:<name> script using the project's task-runner filter syntax, catalog resolution, pnpm allowBuilds/npm allowScripts unioning, and a bts.jsonc record under a new optional 'apps' array. Framework choice is validated against the stack (trpc/clerk imply react-family, convex excludes solid/astro, backend self is refused). The CLI never edits user server code; it prints the CORS/trustedOrigins steps instead.
- create --apps name:framework runs the same flow during project creation, before install and git init, so the initial commit and single install include the apps; the reproducibleCommand records the flag.

Also exposed as add-app-json, programmatic addApp(), and MCP bts_plan_app/bts_add_app. Two shared fixes: packages/env exports rebuilding now preserves unmanaged entries, and the add path preloads extra-app manifests.

Closes AmanVarshney01#170, closes AmanVarshney01#201.
Adds an Extra Apps section below the web-frontend grid: plan additional frontend apps (name + framework) with the same validation and compatibility gating as the CLI. Planned apps append --apps to the generated create command, render as apps/<name> chips in the Selected stack panel (framework on hover, click jumps to the section), persist in builder URLs and saved stacks, auto-drop with a toast when a stack change makes them incompatible, and show on the shared /stack page. Hidden entirely for fullstack (self) backends.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (2)
apps/cli/src/helpers/core/add-app-handler.ts (2)

427-429: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Report pnpm workspace merge failures, and use the async read.

Two points in mergePnpmWorkspaceEntries:

  1. The function returns void, and catch: () => null discards every parse or merge error. If the merge fails, the new app's allowBuilds and minimumReleaseAgeExclude entries are dropped without any signal. The handler already collects warnings; return a message and push it there. The coding guideline asks CLI code to return typed Result<T, E> for recoverable flows.
  2. Line 814 calls fs.readFileSync inside an async function. Use await fs.readFile and pass the content into the synchronous merge step.

As per coding guidelines: "In CLI code, prefer better-result over ad-hoc try/catch for recoverable flows; return typed Result<T, E>".

♻️ Proposed shape
-): Promise<void> {
+): Promise<string | undefined> {
   const workspaceRelPath = "pnpm-workspace.yaml";
   const workspaceDiskPath = path.join(projectDir, workspaceRelPath);
   const scratchWorkspace = scratchFiles.get(workspaceRelPath);
-  if (!scratchWorkspace) return;
-  if (!(await fs.pathExists(workspaceDiskPath))) return;
+  if (!scratchWorkspace) return undefined;
+  if (!(await fs.pathExists(workspaceDiskPath))) return undefined;
+
+  const realContent = await fs.readFile(workspaceDiskPath, "utf-8");
 
   const merged = Result.try({
     try: () => {
       const scratchParsed = YAML.parse(scratchWorkspace.content) as PnpmWorkspaceConfig;
-      const realContent = fs.readFileSync(workspaceDiskPath, "utf-8");
       const doc = YAML.parseDocument(realContent);
@@
-  if (merged.isOk() && merged.value) {
-    vfs.writeFile(workspaceRelPath, merged.value);
-  }
+  if (merged.isErr()) {
+    return "Could not merge pnpm-workspace.yaml entries for the new app. Check its allowBuilds and minimumReleaseAgeExclude entries manually.";
+  }
+  if (merged.value) {
+    vfs.writeFile(workspaceRelPath, merged.value);
+  }
+  return undefined;
 }

Also applies to: 800-850

Source: Coding guidelines


853-862: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low value

Format files concurrently to shorten the add-app run.

formatVfsFiles awaits formatCode once per file in a sequential loop. A scaffolded app contains many files, so the total latency is the sum of every format call. Collect the results with Promise.all over the file list, then write the changed contents back.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 1f1ebea0-23d4-436f-9e39-7f9fcf433c18

📥 Commits

Reviewing files that changed from the base of the PR and between 0d3d88e and 2b4c371.

📒 Files selected for processing (5)
  • apps/cli/src/helpers/core/add-app-handler.ts
  • apps/cli/src/prompts/add-app.ts
  • apps/web/src/app/(home)/new/_components/stack-builder/extra-apps-section.tsx
  • apps/web/src/lib/extra-apps.ts
  • packages/types/src/json-schema.ts

Included review availability: Your plan provides up to 8 included reviews per hour; 4 remain after this review.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[FT] Astro support && Multiple frontend frameworks Request for Multi-Frontend Architecture Support: Next.js, TanStack Router, and React Native

1 participant