Skip to content
Open
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
7 changes: 7 additions & 0 deletions apps/desktop/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -463,6 +463,13 @@ npx bb-app@latest
pnpm exec turbo run dev --filter=@bb/desktop
```

When the app starts its own `bb-app`, it waits for the server with no deadline
for as long as that process runs: the server upgrades its database before it
listens, and that can take minutes on a large `bb.db` or a busy computer. After
10 seconds the window shows "Still starting bb". The `bb-app` launcher likewise
waits for its server child without a deadline. Startup fails only when the
process exits, and that screen offers **Try again** and **Choose server…**.

The desktop supervisor handles normal quits plus `SIGINT` and `SIGTERM`, and it
writes a PID file so the next launch can reap a stale Electron-owned `bb-app`
launcher. Hard crashes such as process aborts, segfaults, or kernel-level kills
Expand Down
117 changes: 66 additions & 51 deletions apps/desktop/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,11 +107,11 @@ import {
reapStaleOwnedRuntime,
writeOwnedRuntimePidFile,
} from "./owned-runtime-supervisor.js";
import { waitForOwnedRuntimeStartup } from "./owned-runtime-startup.js";
import {
probeBbServer,
waitForCompatibleServer,
type CompatibleServerProbeResult,
type ServerProbeResult,
} from "./server-probe.js";
import { loadRemoteServerPage } from "./remote-server-load.js";
import {
Expand Down Expand Up @@ -291,8 +291,9 @@ import {
ATTACH_PROBE_TIMEOUT_MS,
DEFAULT_BB_SERVER_URL,
PROCESS_LOG_LINE_LIMIT,
MACHINE_READY_TIMEOUT_MS,
OWNED_RUNTIME_SLOW_START_NOTICE_MS,
STARTUP_POLL_INTERVAL_MS,
STARTUP_TIMEOUT_MS,
type RuntimeOwnership,
type WindowStateKey,
} from "./types.js";
Expand Down Expand Up @@ -359,20 +360,6 @@ interface LoadLogViewerWindowArgs {
preloadPath: string;
}

type StartupRaceResult =
| ProcessExitedStartupRaceResult
| ServerProbeStartupRaceResult;

interface ProcessExitedStartupRaceResult {
exit: BbAppProcessExit;
kind: "process-exited";
}

interface ServerProbeStartupRaceResult {
kind: "server-probe";
result: ServerProbeResult;
}

interface ResolveDataDirFromEnvArgs {
env: NodeJS.ProcessEnv;
homeDir: string;
Expand Down Expand Up @@ -2205,17 +2192,33 @@ async function loadWindowUrl(args: LoadWindowUrlArgs): Promise<void> {
await desktopWindowFactory.loadUrl({ url: args.url });
}

const LOADING_VIEW_URL = createLocalViewUrl({
viewModel: {
kind: "loading",
message: "Starting local services and opening the bb workspace.",
title: "Opening bb",
},
});

const SLOW_START_VIEW_URL = createLocalViewUrl({
viewModel: {
kind: "loading",
message:
"bb may be upgrading its data after an update. On a large database or a busy computer this can take several minutes. bb opens when it is ready.",
title: "Still starting bb",
},
});

async function loadLoadingView(): Promise<void> {
bbAppLoaded = false;
await loadWindowUrl({
url: createLocalViewUrl({
viewModel: {
kind: "loading",
message: "Starting local services and opening the bb workspace.",
title: "Opening bb",
},
}),
});
await loadWindowUrl({ url: LOADING_VIEW_URL });
}

async function loadSlowStartView(): Promise<void> {
if (currentWindowUrl !== LOADING_VIEW_URL) {
return;
}
await loadWindowUrl({ url: SLOW_START_VIEW_URL });
}

async function loadWindowsInstallerWaitView(): Promise<void> {
Expand All @@ -2240,7 +2243,7 @@ async function loadStartupError(args: LoadStartupErrorArgs): Promise<void> {
await loadActionView({
...args,
details:
args.actions.length === 0
args.actions.length === 0 || args.logs.length > 0
? `${args.details} Logs are under ${formatLogDirectory()}/.`
: args.details,
});
Expand Down Expand Up @@ -2609,6 +2612,11 @@ async function spawnOwnedRuntime(
return { bbProcess, runtime };
}

const OWNED_RUNTIME_EXIT_ACTIONS: StartupAction[] = [
{ id: "retry", label: "Try again" },
{ id: "choose-server", label: "Choose server…" },
];

function reportOwnedRuntimeExit({ bbProcess, runtime }: OwnedRuntime): void {
void bbProcess.exit.then((exit) => {
if (quitting || currentRuntime !== runtime) {
Expand All @@ -2626,7 +2634,7 @@ function reportOwnedRuntimeExit({ bbProcess, runtime }: OwnedRuntime): void {
exit,
)}.`,
logs: bbProcess.logs.text(),
actions: [],
actions: OWNED_RUNTIME_EXIT_ACTIONS,
title: "bb stopped",
});
});
Expand Down Expand Up @@ -2656,18 +2664,23 @@ async function waitForWindowsInstallerToFinish(): Promise<boolean> {
return result === "finished" && !quitting;
}

async function waitForOwnedRuntimeReady(bbProcess: BbAppProcess): Promise<void> {
async function waitForOwnedRuntimeReady(
bbProcess: BbAppProcess,
): Promise<void> {
let timer: NodeJS.Timeout | undefined;
const result = await Promise.race([
bbProcess.ready.then(() => "ready" as const),
new Promise<"timed-out">((resolveTimeout) => {
timer = setTimeout(() => resolveTimeout("timed-out"), STARTUP_TIMEOUT_MS);
timer = setTimeout(
() => resolveTimeout("timed-out"),
MACHINE_READY_TIMEOUT_MS,
);
}),
]);
clearTimeout(timer);
if (result === "timed-out") {
desktopLogger.warn(
`[desktop] bb-app did not report this computer connected within ${STARTUP_TIMEOUT_MS}ms; opening bb anyway`,
`[desktop] bb-app did not report this computer connected within ${MACHINE_READY_TIMEOUT_MS}ms; opening bb anyway`,
);
}
}
Expand All @@ -2678,49 +2691,51 @@ async function startOwnedRuntime(
const ownedRuntime = await spawnOwnedRuntime(args);
const { bbProcess, runtime } = ownedRuntime;

const raceResult = await Promise.race<StartupRaceResult>([
waitForCompatibleServer({
intervalMs: STARTUP_POLL_INTERVAL_MS,
serverUrl: args.serverUrl,
timeoutMs: STARTUP_TIMEOUT_MS,
}).then(async (result) => {
const startup = await waitForOwnedRuntimeStartup({
exit: bbProcess.exit,
onSlowStart: () => {
desktopLogger.info(
`[desktop] bb-app is still starting after ${OWNED_RUNTIME_SLOW_START_NOTICE_MS}ms; waiting for it while the process runs`,
);
void loadSlowStartView();
},
slowStartNoticeMs: OWNED_RUNTIME_SLOW_START_NOTICE_MS,
waitForServer: async (signal) => {
const result = await waitForCompatibleServer({
intervalMs: STARTUP_POLL_INTERVAL_MS,
serverUrl: args.serverUrl,
signal,
});
if (result.kind === "compatible") {
await waitForOwnedRuntimeReady(bbProcess);
}
return { kind: "server-probe", result };
}),
bbProcess.exit.then((exit) => ({
exit,
kind: "process-exited",
})),
]);
return result;
},
});

if (raceResult.kind === "process-exited") {
if (startup.kind === "process-exited") {
setCurrentRuntime(null);
if (await waitForWindowsInstallerToFinish()) {
return startOwnedRuntime(args);
}
await loadStartupError({
details: `bb-app exited before the server was ready with ${formatExitResult(
raceResult.exit,
startup.exit,
)}.`,
logs: bbProcess.logs.text(),
actions: [],
actions: OWNED_RUNTIME_EXIT_ACTIONS,
title: "Could not start bb",
});
return null;
}

if (raceResult.result.kind === "compatible") {
if (startup.result.kind === "compatible") {
reportOwnedRuntimeExit(ownedRuntime);
return runtime;
}

await loadStartupError({
details:
raceResult.result.kind === "incompatible"
? `Port ${args.serverUrl} is responding, but it does not look like bb: ${raceResult.result.reason}.`
: `Timed out waiting for bb at ${args.serverUrl}: ${raceResult.result.reason}.`,
details: `Port ${args.serverUrl} is responding, but it does not look like bb: ${startup.result.reason}.`,
logs: bbProcess.logs.text(),
actions: [],
title: "Could not start bb",
Expand Down
41 changes: 41 additions & 0 deletions apps/desktop/src/owned-runtime-startup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import type { BbAppProcessExit } from "./bb-process.js";
import type { SettledServerProbeResult } from "./server-probe.js";

export type OwnedRuntimeStartupResult =
| ProcessExitedStartupResult
| ServerProbeStartupResult;

interface ProcessExitedStartupResult {
exit: BbAppProcessExit;
kind: "process-exited";
}

interface ServerProbeStartupResult {
kind: "server-probe";
result: SettledServerProbeResult;
}

interface WaitForOwnedRuntimeStartupArgs {
exit: Promise<BbAppProcessExit>;
onSlowStart(): void;
slowStartNoticeMs: number;
waitForServer(signal: AbortSignal): Promise<SettledServerProbeResult>;
}

export async function waitForOwnedRuntimeStartup(
args: WaitForOwnedRuntimeStartupArgs,
): Promise<OwnedRuntimeStartupResult> {
const probe = new AbortController();
const slowStartNotice = setTimeout(args.onSlowStart, args.slowStartNoticeMs);
try {
return await Promise.race<OwnedRuntimeStartupResult>([
args
.waitForServer(probe.signal)
.then((result) => ({ kind: "server-probe", result })),
args.exit.then((exit) => ({ exit, kind: "process-exited" })),
]);
} finally {
clearTimeout(slowStartNotice);
probe.abort();
}
}
45 changes: 20 additions & 25 deletions apps/desktop/src/server-probe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ export interface CompatibleServerProbeResult {
serverUrl: string;
}

export type SettledServerProbeResult =
| CompatibleServerProbeResult
| IncompatibleServerProbeResult;

interface IncompatibleServerProbeResult {
kind: "incompatible";
reason: string;
Expand All @@ -52,7 +56,7 @@ interface WaitForCompatibleServerArgs {
fetchImpl?: ServerProbeFetch;
intervalMs: number;
serverUrl: string;
timeoutMs: number;
signal: AbortSignal;
}

interface FetchJsonArgs<TValue> {
Expand Down Expand Up @@ -95,11 +99,18 @@ interface FetchJsonNetworkErrorResult {

interface SleepArgs {
delayMs: number;
signal: AbortSignal;
}

async function sleep(args: SleepArgs): Promise<void> {
await new Promise<void>((resolvePromise) => {
setTimeout(resolvePromise, args.delayMs);
const finish = (): void => {
clearTimeout(timer);
args.signal.removeEventListener("abort", finish);
resolvePromise();
};
const timer = setTimeout(finish, args.delayMs);
args.signal.addEventListener("abort", finish, { once: true });
});
}

Expand Down Expand Up @@ -223,35 +234,19 @@ export async function probeBbServer(

export async function waitForCompatibleServer(
args: WaitForCompatibleServerArgs,
): Promise<ServerProbeResult> {
const deadline = Date.now() + args.timeoutMs;
let lastResult: ServerProbeResult = {
kind: "unavailable",
reason: "Probe has not started",
serverUrl: args.serverUrl,
};

while (Date.now() <= deadline) {
lastResult = await probeBbServer({
): Promise<SettledServerProbeResult> {
for (;;) {
args.signal.throwIfAborted();
const result = await probeBbServer({
...(args.fetchImpl === undefined ? {} : { fetchImpl: args.fetchImpl }),
serverUrl: args.serverUrl,
timeoutMs: Math.min(args.intervalMs, 1_000),
});

if (lastResult.kind === "compatible") {
return lastResult;
}

if (lastResult.kind === "incompatible") {
return lastResult;
if (result.kind !== "unavailable") {
return result;
}

await sleep({ delayMs: args.intervalMs });
await sleep({ delayMs: args.intervalMs, signal: args.signal });
}

return {
kind: "unavailable",
reason: `Timed out after ${args.timeoutMs}ms waiting for bb server. Last probe: ${lastResult.reason}`,
serverUrl: args.serverUrl,
};
}
3 changes: 2 additions & 1 deletion apps/desktop/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ const DEFAULT_WINDOW_WIDTH = 1280;
export const MIN_WINDOW_HEIGHT = 600;
export const MIN_WINDOW_WIDTH = 500;
export const STARTUP_POLL_INTERVAL_MS = 250;
export const STARTUP_TIMEOUT_MS = 60_000;
export const OWNED_RUNTIME_SLOW_START_NOTICE_MS = 10_000;
export const MACHINE_READY_TIMEOUT_MS = 60_000;
export const ATTACH_PROBE_TIMEOUT_MS = 1_500;
export const PROCESS_LOG_LINE_LIMIT = 200;

Expand Down
Loading
Loading