Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,19 @@ checkout path. The checkout instance id is the sanitized path to the checkout,
relative to your home directory, plus a short hash suffix. Separate worktrees
can run alongside each other and the packaged `npx bb-app@latest` instance.

To test the production bundle and serving path without switching to production
data or ports, use:

```bash
pnpm start:worktree
```

This builds the same optimized frontend and runtime artifacts as `pnpm start`,
then serves the app from the BB server on the checkout-specific dev server port.
It keeps the normal checkout-specific dev data directory and host-daemon port.
There is no Vite dev server or hot reload in this mode; rerun the command after
source changes. As with `pnpm dev`, worktree starts do not send telemetry.

To run that same source dev server with the Electron desktop shell:

```bash
Expand Down
14 changes: 11 additions & 3 deletions docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -926,9 +926,9 @@ enrolled to other servers. Atomic reservations under

## Source Development

For source development only, `pnpm dev` and `pnpm start` load the repo-root
dotenv cascade. Add a repo-root `.env` only when you need to override the
defaults described above.
For source development only, `pnpm dev`, `pnpm start:worktree`, and `pnpm start`
load the repo-root dotenv cascade. Add a repo-root `.env` only when you need to
override the defaults described above.

The standard [dotenv-cli](https://github.com/entropitor/dotenv-cli) cascade
applies to source development. `pnpm dev` loads `.env`, `.env.local`,
Expand All @@ -940,6 +940,14 @@ Vite app bind to loopback by default; an explicit `BB_DEV_APP_HOST` still
overrides the Vite listener. Remote HTTP dev via `BB_DEV_APP_HOST` also requires
`BB_SERVER_BIND_HOST=0.0.0.0` for realtime updates; the Tailscale Serve HTTPS
path avoids this because WebSocket traffic goes through the Vite proxy.
`pnpm start:worktree` loads the same development dotenv cascade and uses the
same checkout-specific data directory, server port, and host-daemon port. It
builds production artifacts and serves the frontend bundle from the main
server, so there is no separate Vite listener or hot reload. Telemetry remains
disabled for this source-development command. Its worktree data directory,
ports, inherited skills, listener host, absent Vite port, and telemetry policy
take precedence over conflicting values saved in that instance's `config.json`
or `env.json`.
`pnpm start` loads `.env`, `.env.local`, `.env.production`, and
`.env.production.local`.

Expand Down
1 change: 1 addition & 0 deletions docs/debugging-and-qa.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# Debugging And QA

- `pnpm dev` prints the active frontend URL, server API URL, host daemon port, data dir, and logs dir. Do not assume fixed dev ports.
- `pnpm start:worktree` builds production artifacts and serves the optimized app bundle from the checkout-specific dev server URL, while keeping the same dev data directory and deterministic server/host-daemon ports. It has no Vite dev server or hot reload.
- The packaged app defaults to server/frontend `:38886`, host daemon `:38887`, data dir `~/.bb/`, and logs under `~/.bb/logs/`.
- Entity IDs in URLs (`proj_*`, `thr_*`) are primary keys. Query them directly against the active data dir: `sqlite3 <data>/bb.db "SELECT * FROM threads WHERE id = 'thr_xxx';"`.
- API routes are under `/api/v1/`, for example `GET /api/v1/threads/:id`.
Expand Down
2 changes: 1 addition & 1 deletion docs/platform-support.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ Not available on the phone (use the web app or desktop for these):

- `npx bb-app`
- `npx --package bb-app bb ...`
- source checkout package startup with `pnpm start`
- source checkout package startup with `pnpm start` or `pnpm start:worktree`
- source checkout validation with `pnpm install`, `pnpm build`,
`pnpm exec turbo run typecheck`, and `pnpm exec turbo run test`
- app + server + host-daemon startup on supported persistent-host OSes
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"cli:prepare": "pnpm exec turbo run build --filter=@bb/scripts --filter=@bb/cli --output-logs=none --log-prefix=none --summarize=false",
"ensure-native-modules": "node scripts/ensure-native-modules.mjs",
"dev": "node scripts/ensure-native-modules.mjs && cross-env NODE_ENV=development dotenv -c development -- node --conditions=source --import tsx packages/scripts/src/commands/run-dev.ts",
"start:worktree": "cross-env NODE_ENV=development dotenv -c development -- node --conditions=source --import tsx packages/scripts/src/commands/run-dev.ts --worktree",
"dev:remote": "cross-env BB_DEV_APP_HOST=0.0.0.0 BB_SERVER_BIND_HOST=0.0.0.0 pnpm run dev",
"cloud:dev": "node --conditions=source --import tsx scripts/bb-cloud-dev.mjs",
"dev:desktop": "scripts/bb-dev-app current --desktop",
Expand Down
4 changes: 4 additions & 0 deletions packages/bb-app/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export {
resolveBbAppStartContext,
resolveDataDir,
resolvePort,
resolveWorktreeRuntimePolicy,
runBbApp,
runBbCli,
runBbHostDaemon,
Expand Down Expand Up @@ -37,5 +38,8 @@ export type {
ResolveBbAppStartContextArgs,
ResolveDataDirArgs,
ResolvePortArgs,
ResolveWorktreeRuntimePolicyArgs,
RunBbAppOptions,
StartCommand,
WorktreeRuntimePolicy,
} from "./launcher.js";
130 changes: 116 additions & 14 deletions packages/bb-app/src/launcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,11 +55,13 @@ import {
} from "@bb/config/inference-model";
import { validateLogLevel } from "@bb/config/log-level";
import { validateOptionalUrl } from "@bb/config/public-url";
import { parseServerBindHost } from "@bb/config/server";
import { parseServerBindHost, type ServerBindHost } from "@bb/config/server";
import {
BB_PROD_HOST_DAEMON_PORT,
BB_LOOPBACK_HOST,
BB_PROD_SERVER_PORT,
parseDataDirEnvValue,
parsePortValue,
resolveConfiguredDataDir,
resolveDataDirDatabasePath,
resolvePortFromEnv,
Expand Down Expand Up @@ -211,6 +213,26 @@ export interface ResolveBbAppRuntimeContextArgs {
homeDir: string;
options: LauncherCliOptions;
serverUrlMode: "local" | "managed";
worktreePolicy?: WorktreeRuntimePolicy;
}

export interface WorktreeRuntimePolicy {
dataDir: string;
devAppPort: null;
hostDaemonPort: number;
inheritedSkillsRoots: string;
serverBindHost: ServerBindHost;
serverPort: number;
telemetry: false;
}

export interface ResolveWorktreeRuntimePolicyArgs {
env: NodeJS.ProcessEnv;
homeDir: string;
}

export interface RunBbAppOptions {
worktreePolicy: WorktreeRuntimePolicy | null;
}

export interface BbAppStartContext {
Expand Down Expand Up @@ -564,6 +586,7 @@ interface ResolveBbAppRuntimeStateArgs {
homeDir: string;
options: LauncherCliOptions;
serverUrlMode: "local" | "managed";
worktreePolicy?: WorktreeRuntimePolicy;
}

interface RunConfigCommandArgs {
Expand Down Expand Up @@ -809,6 +832,72 @@ export function resolvePort(args: ResolvePortArgs): number {
return resolvePortFromEnv(args);
}

function requireWorktreePolicyEnvValue(
env: NodeJS.ProcessEnv,
name: string,
): string {
const value = env[name];
if (value === undefined) {
throw new Error(`${name} is required for worktree startup`);
}
return value;
}

export function resolveWorktreeRuntimePolicy(
args: ResolveWorktreeRuntimePolicyArgs,
): WorktreeRuntimePolicy {
const rawDataDir = requireWorktreePolicyEnvValue(args.env, "BB_DATA_DIR");
const rawHostDaemonPort = requireWorktreePolicyEnvValue(
args.env,
"BB_HOST_DAEMON_PORT",
);
const inheritedSkillsRoots = requireWorktreePolicyEnvValue(
args.env,
"BB_INHERITED_SKILLS_ROOTS",
);
const rawServerPort = requireWorktreePolicyEnvValue(
args.env,
"BB_SERVER_PORT",
);
return {
dataDir: parseDataDirEnvValue({
homeDir: args.homeDir,
rawDataDir,
}),
devAppPort: null,
hostDaemonPort: parsePortValue({
name: "BB_HOST_DAEMON_PORT",
rawPort: rawHostDaemonPort,
}),
inheritedSkillsRoots,
serverBindHost: parseServerBindHost(
args.env.BB_SERVER_BIND_HOST ?? BB_LOOPBACK_HOST,
),
serverPort: parsePortValue({
name: "BB_SERVER_PORT",
rawPort: rawServerPort,
}),
telemetry: false,
};
}

function applyWorktreeRuntimePolicy(
env: NodeJS.ProcessEnv,
policy: WorktreeRuntimePolicy,
): NodeJS.ProcessEnv {
const nextEnv: NodeJS.ProcessEnv = {
...env,
BB_DATA_DIR: policy.dataDir,
BB_HOST_DAEMON_PORT: String(policy.hostDaemonPort),
BB_INHERITED_SKILLS_ROOTS: policy.inheritedSkillsRoots,
BB_SERVER_BIND_HOST: policy.serverBindHost,
BB_SERVER_PORT: String(policy.serverPort),
BB_TELEMETRY: String(policy.telemetry),
};
delete nextEnv.BB_DEV_APP_PORT;
return nextEnv;
}

function createEnvFromOptions(
args: CreateEnvFromOptionsArgs,
): NodeJS.ProcessEnv {
Expand Down Expand Up @@ -1311,21 +1400,28 @@ export async function resolveBbAppRuntimeState(
});
const config = await readManagedConfig({ dataDir: initialContext.dataDir });
const envFile = await readManagedEnvFile({ dataDir: initialContext.dataDir });
const managedEnv = applyManagedConfigEnv({
const persistedEnv = applyManagedConfigEnv({
config,
envFile,
env: initialEnv,
});
const applyRuntimePolicy = (env: NodeJS.ProcessEnv): NodeJS.ProcessEnv =>
args.worktreePolicy === undefined
? env
: applyWorktreeRuntimePolicy(env, args.worktreePolicy);
const managedEnv = applyRuntimePolicy(persistedEnv);

if (args.serverUrlMode === "local") {
const localEnv = { ...managedEnv };
const localServerEnv = stripThreadContextEnv(
createServerBaseEnv({
config,
envFile,
env: initialEnv,
serverBindHostOverride: args.options.serverBindHost,
}),
applyRuntimePolicy(
createServerBaseEnv({
config,
envFile,
env: initialEnv,
serverBindHostOverride: args.options.serverBindHost,
}),
),
);
delete localEnv.BB_SERVER_URL;
delete localServerEnv.BB_SERVER_URL;
Expand Down Expand Up @@ -1359,12 +1455,14 @@ export async function resolveBbAppRuntimeState(
}),
env: finalEnv,
serverEnv: stripThreadContextEnv(
createServerBaseEnv({
config,
envFile,
env: initialEnv,
serverBindHostOverride: args.options.serverBindHost,
}),
applyRuntimePolicy(
createServerBaseEnv({
config,
envFile,
env: initialEnv,
serverBindHostOverride: args.options.serverBindHost,
}),
),
),
};
}
Expand Down Expand Up @@ -3186,6 +3284,7 @@ async function runStopCommand(args: { dataDir: string }): Promise<void> {

export async function runBbApp(
cliArgs: string[] = process.argv.slice(2),
options: RunBbAppOptions = { worktreePolicy: null },
): Promise<void> {
const parsedArgs = parseLauncherArgs(cliArgs);

Expand Down Expand Up @@ -3217,6 +3316,9 @@ export async function runBbApp(
command.kind === "host-daemon"
? "managed"
: "local",
...(options.worktreePolicy === null
? {}
: { worktreePolicy: options.worktreePolicy }),
});

if (command.kind === "start") {
Expand Down
59 changes: 59 additions & 0 deletions packages/bb-app/test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import {
resolvePort,
resolveBbAppStartContext,
resolveBbAppCommand,
resolveWorktreeRuntimePolicy,
runBbApp,
} from "../src/index.js";
import {
Expand Down Expand Up @@ -992,6 +993,64 @@ describe("bb-app launcher", () => {
expect(runtime.serverEnv.OPENAI_API_KEY).toBe("stored-openai-key");
});

it("applies the worktree policy after conflicting saved environment values", async () => {
const dataDir = mkdtempSync(join(tmpdir(), "bb-app-worktree-policy-"));
const storedDataDir = join(dataDir, "stored-data");
writeFileSync(
join(dataDir, "env.json"),
JSON.stringify({
env: {
BB_DATA_DIR: storedDataDir,
BB_DEV_APP_PORT: "4173",
BB_HOST_DAEMON_PORT: "48887",
BB_INHERITED_SKILLS_ROOTS: "/stored/skills",
BB_SERVER_BIND_HOST: "0.0.0.0",
BB_SERVER_PORT: "48886",
BB_TELEMETRY: "true",
OPENAI_API_KEY: "stored-openai-key",
},
}),
"utf8",
);
const worktreeEnv: NodeJS.ProcessEnv = {
BB_DATA_DIR: dataDir,
BB_HOST_DAEMON_PORT: "47887",
BB_INHERITED_SKILLS_ROOTS: "/worktree/skills",
BB_SERVER_PORT: "47886",
};

const runtime = await resolveBbAppRuntimeState({
entrypointUrl: pathToFileURL("/repo/packages/bb-app/dist/bb-app.js").href,
env: worktreeEnv,
homeDir: "/home/tester",
options: { help: false },
serverUrlMode: "local",
worktreePolicy: resolveWorktreeRuntimePolicy({
env: worktreeEnv,
homeDir: "/home/tester",
}),
});

expect(runtime.context).toMatchObject({
daemonPort: 47887,
dataDir,
serverPort: 47886,
serverUrl: "http://127.0.0.1:47886",
});
for (const env of [runtime.env, runtime.serverEnv]) {
expect(env).toMatchObject({
BB_DATA_DIR: dataDir,
BB_HOST_DAEMON_PORT: "47887",
BB_INHERITED_SKILLS_ROOTS: "/worktree/skills",
BB_SERVER_BIND_HOST: "127.0.0.1",
BB_SERVER_PORT: "47886",
BB_TELEMETRY: "false",
OPENAI_API_KEY: "stored-openai-key",
});
expect(env.BB_DEV_APP_PORT).toBeUndefined();
}
});

it("uses launcher flags over managed config and ambient server URL", async () => {
const dataDir = mkdtempSync(join(tmpdir(), "bb-app-flag-config-"));
writeFileSync(
Expand Down
Loading
Loading