Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 | 22x 20x 1x 63x 63x 70x 70x 7x 63x 8x 4x 4x 9x 9x 9x 4x 4x 4x 8x 8x 7x 7x 4x 71x 8x 63x 63x 1x 62x 62x 62x 2x 2x 3x 3x 2x 5x 2x 2x 2x 3x 3x 2x 2x 8x 8x 1x 7x 7x 11x 11x 4x 4x 4x 2x 7x 2x 2x 7x 1x 55x 55x 55x 55x 55x 55x 55x 55x 1x 55x 34x 31x 495x 493x 1x 2x 1270x 22x 22x 22x 174x 174x 1319x 1309x 64x 823x 823x 294x 294x 294x 54x 54x 762x 762x 64x 64x 1x 64x 1x 64x 56x 56x 5x 64x 64x 128x 126x 126x 8x 8x 8x 8x 35x 64x 32x 32x 19x 19x 19x 16x 16x 16x 11x 16x 3x 3x 3x 64x 4x 4x 3x 3x 3x 3x 11x 11x 64x 64x 64x 64x 64x 65x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 54x 45x 45x 16x 15x 15x 15x 54x 496x 496x 447x 444x 22x 5x 5x 3x 5x 17x 24x 23x 23x 23x 21x 86x 74x 74x 28x 28x 3x 3x 28x 6x 6x 22x 22x 22x 22x 22x 22x 8x 1x 7x 22x 22x 22x 2x 2x 2x | import type { ChildProcess } from "child_process";
import type { Readable } from "stream";
import type { ServerState } from "./types";
import { LOG_FILE, LOGS_DIR, PLATFORM, SERVER_STATE } from "./types";
import { node } from "./binary-manager";
import { appendCapped } from "./utils/capped-log";
/** Human-readable cause for a child that went away: signal beats exit code. */
function describeExit(code: number | null, signal: NodeJS.Signals | null): string {
if (signal) return `signal ${signal}`;
if (code !== null) return `exit code ${code}`;
return "unknown cause";
}
interface ProcRow {
pid: number;
ppid: number;
command: string;
}
/** Parse `ps -axo pid=,ppid=,command=` rows; ignores malformed lines. */
export function parsePsOutput(stdout: string): ProcRow[] {
const rows: ProcRow[] = [];
for (const line of stdout.split("\n")) {
const match = line.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);
if (!match) continue;
rows.push({ pid: Number(match[1]), ppid: Number(match[2]), command: match[3] });
}
return rows;
}
/** A `lilbee serve` process is ours if it carries this vault's data dir. */
function isServerFor(command: string, dataDir: string): boolean {
return command.includes("lilbee") && command.includes("serve") && command.includes(dataDir);
}
/** Collect the given roots plus every descendant (the server's worker forks). */
export function collectProcessTree(rows: ProcRow[], roots: number[]): number[] {
const childrenOf = new Map<number, number[]>();
for (const row of rows) {
const kids = childrenOf.get(row.ppid) ?? [];
kids.push(row.pid);
childrenOf.set(row.ppid, kids);
}
const seen = new Set<number>();
const stack = [...roots];
while (stack.length > 0) {
const pid = stack.pop()!;
if (seen.has(pid)) continue;
seen.add(pid);
for (const child of childrenOf.get(pid) ?? []) stack.push(child);
}
return [...seen];
}
/**
* Kill orphaned `lilbee serve` processes bound to *dataDir* — and their worker
* forks — left behind by a session that ended without a clean stop. Returns the
* pids it terminated. Best-effort: enumeration or kill failures are swallowed.
*/
export async function reapOrphanServers(dataDir: string): Promise<number[]> {
if (process.platform === PLATFORM.WIN32) {
return reapOrphanServersWindows(dataDir);
}
let stdout: string;
try {
// -A all processes, -ww no command-line truncation (a long --data-dir
// must survive), portable across macOS and Linux.
({ stdout } = await node.execFile("ps", ["-A", "-ww", "-o", "pid=,ppid=,command="]));
} catch {
return [];
}
const rows = parsePsOutput(stdout);
const roots = rows.filter((r) => isServerFor(r.command, dataDir)).map((r) => r.pid);
if (roots.length === 0) return [];
const tree = collectProcessTree(rows, roots);
for (const pid of tree) {
try {
node.processKill(pid, "SIGKILL");
} catch {
// already gone
}
}
return tree;
}
/** Force-kill a known server pid and its worker forks. Best-effort. */
export async function killServerTree(pid: number): Promise<void> {
if (process.platform === PLATFORM.WIN32) {
try {
await node.execFile("taskkill", ["/pid", String(pid), "/f", "/t"]);
} catch {
// already gone
}
return;
}
try {
node.processKill(-pid, "SIGKILL");
} catch {
try {
node.processKill(pid, "SIGKILL");
} catch {
// already gone
}
}
}
/** Windows can't signal a group; taskkill /t tree-kills each matching root. */
async function reapOrphanServersWindows(dataDir: string): Promise<number[]> {
let stdout: string;
try {
({ stdout } = await node.execFile("powershell", [
"-NoProfile",
"-Command",
'Get-CimInstance Win32_Process | ForEach-Object { "$($_.ProcessId)`t$($_.CommandLine)" }',
]));
} catch {
return [];
}
const roots: number[] = [];
for (const line of stdout.split("\n")) {
const tab = line.indexOf("\t");
if (tab < 0) continue;
const pid = Number(line.slice(0, tab).trim());
const command = line.slice(tab + 1);
if (Number.isNaN(pid) || !isServerFor(command, dataDir)) continue;
roots.push(pid);
}
for (const pid of roots) {
try {
await node.execFile("taskkill", ["/pid", String(pid), "/f", "/t"]);
} catch {
// already gone
}
}
return roots;
}
const SERVER_MANAGER_CONFIG = {
HEALTH_POLL_INTERVAL_MS: 1000,
HEALTH_POLL_MAX_ATTEMPTS: 120,
STOP_GRACE_MS: 5000,
CRASH_RESTART_DELAY_MS: 3000,
MAX_CRASH_RESTARTS: 3,
PORT_FILE_POLL_INTERVAL_MS: 500,
PORT_FILE_MAX_ATTEMPTS: 240,
SPAWN_CRASH_LOG_MAX_BYTES: 262_144,
} as const;
export interface ServerManagerOptions {
binaryPath: string;
dataDir: string;
/**
* HuggingFace cache and GGUF storage. Set via `LILBEE_MODELS_DIR` so the
* server uses the same path across all vaults — without it, lilbee would
* scope models to each per-vault data-dir and re-download per vault.
*/
modelsDir: string;
ragSystemPrompt: string;
generalSystemPrompt: string;
onStateChange?: (state: ServerState) => void;
onRestartsExhausted?: (output: string) => void;
onShutdownFailure?: (error: Error) => void;
}
export class ServerManager {
private opts: ServerManagerOptions;
private child: ChildProcess | null = null;
private _state: ServerState = SERVER_STATE.STOPPED;
private crashCount = 0;
private stopping = false;
private restartTimer: number | null = null;
private _actualPort: number | null = null;
private _outputLines: string[] = [];
/** Set when the child can no longer come up (spawn error, restarts exhausted); aborts discovery. */
private fatalStartError: Error | null = null;
private static readonly MAX_OUTPUT_LINES = 20;
constructor(opts: ServerManagerOptions) {
this.opts = opts;
}
get lastOutput(): string {
return this._outputLines.join("\n");
}
get state(): ServerState {
return this._state;
}
get serverUrl(): string {
if (this._actualPort === null) return "";
return `http://127.0.0.1:${this._actualPort}`;
}
get dataDir(): string {
return this.opts.dataDir;
}
/** PID of the running server child, for the vault lock. Null when stopped. */
get serverPid(): number | null {
return this.child?.pid ?? null;
}
private get portFilePath(): string {
return `${this.opts.dataDir}/data/server.port`;
}
private get crashLogPath(): string {
return `${this.opts.dataDir}/${LOGS_DIR}/${LOG_FILE.SPAWN_CRASH}`;
}
/** Persist the output ring buffer so a crash survives an Obsidian restart. */
private snapshotCrashOutput(): void {
const header = `=== crash ${new Date().toISOString()} ===\n`;
appendCapped(
this.crashLogPath,
`${header}${this.lastOutput}\n`,
SERVER_MANAGER_CONFIG.SPAWN_CRASH_LOG_MAX_BYTES,
);
}
private setState(s: ServerState): void {
this._state = s;
this.opts.onStateChange?.(s);
}
/** Throws when waiting any longer is pointless: the child is unrecoverable or the user stopped us. */
private assertStartupViable(): void {
if (this.fatalStartError) throw this.fatalStartError;
if (this.stopping) throw new Error("Server was stopped during startup");
}
private async waitForPortFile(): Promise<void> {
for (let i = 0; i < SERVER_MANAGER_CONFIG.PORT_FILE_MAX_ATTEMPTS; i++) {
this.assertStartupViable();
if (node.existsSync(this.portFilePath)) {
const content = node.readFileSync(this.portFilePath, "utf-8").trim();
const port = parseInt(content, 10);
if (!isNaN(port) && port > 0 && port <= 65535) {
this._actualPort = port;
return;
}
}
await new Promise((r) => window.setTimeout(r, SERVER_MANAGER_CONFIG.PORT_FILE_POLL_INTERVAL_MS));
}
throw new Error("Port file not found within timeout");
}
private buildSpawnEnv(): Record<string, string | undefined> {
const env: Record<string, string | undefined> = {
...process.env,
// Force UTF-8 locale/stdio: GUI-spawned children inherit no locale,
// so the server defaults to ASCII and crashes crawling non-ASCII output.
LANG: "en_US.UTF-8",
LC_ALL: "en_US.UTF-8",
PYTHONIOENCODING: "utf-8",
PYTHONUTF8: "1",
LILBEE_CORS_ORIGINS: "app://obsidian.md",
LILBEE_PARENT_PID: String(process.pid),
LILBEE_MODELS_DIR: this.opts.modelsDir,
};
if (this.opts.ragSystemPrompt) {
env.LILBEE_RAG_SYSTEM_PROMPT = this.opts.ragSystemPrompt;
}
if (this.opts.generalSystemPrompt) {
env.LILBEE_GENERAL_SYSTEM_PROMPT = this.opts.generalSystemPrompt;
}
return env;
}
private pushOutputLine(line: string): void {
this._outputLines.push(line);
if (this._outputLines.length > ServerManager.MAX_OUTPUT_LINES) {
this._outputLines.shift();
}
}
private attachOutputCapture(child: ChildProcess): void {
this.attachStreamCapture(child.stdout);
this.attachStreamCapture(child.stderr);
}
private attachStreamCapture(stream: Readable | null): void {
if (!stream) return;
let partial = "";
stream.on("data", (chunk: Buffer) => {
partial += chunk.toString();
const lines = partial.split("\n");
partial = lines.pop()!;
for (const line of lines) {
if (line.length > 0) this.pushOutputLine(line);
}
});
}
private attachLifecycleHandlers(child: ChildProcess): void {
child.on("exit", (code: number | null, signal: NodeJS.Signals | null) => {
this.child = null;
if (this.stopping) return;
this.pushOutputLine(`server exited (${describeExit(code, signal)})`);
this.snapshotCrashOutput();
if (this.crashCount < SERVER_MANAGER_CONFIG.MAX_CRASH_RESTARTS) {
this.crashCount++;
this.setState(SERVER_STATE.ERROR);
this.restartTimer = window.setTimeout(() => {
this.restartTimer = null;
/* v8 ignore next -- stop() clears this timer before setting stopping, so the false branch is unreachable */
if (!this.stopping) void this.startForRestart();
}, SERVER_MANAGER_CONFIG.CRASH_RESTART_DELAY_MS);
return;
}
this.fatalStartError = new Error(
`Server exited (${describeExit(code, signal)}) and did not come back after ${SERVER_MANAGER_CONFIG.MAX_CRASH_RESTARTS} restarts`,
);
this.setState(SERVER_STATE.ERROR);
this.opts.onRestartsExhausted?.(this.lastOutput);
});
child.on("error", (err: Error) => {
this.child = null;
if (this.stopping) return;
this.pushOutputLine(`failed to launch server: ${err.message}`);
this.snapshotCrashOutput();
this.fatalStartError = new Error(`Failed to launch server: ${err.message}`);
this.setState(SERVER_STATE.ERROR);
});
}
/** Crash-loop restart: failures already surface via state + onRestartsExhausted, so don't rethrow. */
private async startForRestart(): Promise<void> {
try {
await this.start();
} catch {
// already reported
}
}
private spawnChild(): ChildProcess {
// No --port: the server binds 0, the kernel picks a free port, and
// the chosen value is written to data/server.port for us to read.
const args = ["serve", "--host", "127.0.0.1", "--data-dir", this.opts.dataDir];
const child = node.spawn(this.opts.binaryPath, args, {
env: this.buildSpawnEnv(),
stdio: ["ignore", "pipe", "pipe"],
// POSIX: own process group so stop() can signal the server *and* its
// worker forks as a unit. Windows uses taskkill /t for the tree.
detached: process.platform !== PLATFORM.WIN32,
});
this.attachOutputCapture(child);
this.attachLifecycleHandlers(child);
return child;
}
async start(): Promise<void> {
if (this.child) return;
this.stopping = false;
this._actualPort = null;
this.fatalStartError = null;
this.setState(SERVER_STATE.STARTING);
this._outputLines = [];
// A leftover server.port from a previous run would be adopted as this
// child's port, so it must be gone before the spawn.
this.cleanupPortFile();
// Clear orphaned servers from a prior session before spawning; two
// servers on one data dir contend and SIGKILL each other.
await reapOrphanServers(this.opts.dataDir);
this.child = this.spawnChild();
try {
await this.waitForPortFile();
await this.waitForReady();
this.crashCount = 0;
this.setState(SERVER_STATE.READY);
} catch (err) {
// A stop() mid-startup aborted the discovery on purpose; not a failure.
if (this.stopping) return;
// Kill the child we spawned so it doesn't outlive the failure and block retries.
if (this.child) await this.stop();
this.setState(SERVER_STATE.ERROR);
throw err;
}
}
private async waitForReady(): Promise<void> {
for (let i = 0; i < SERVER_MANAGER_CONFIG.HEALTH_POLL_MAX_ATTEMPTS; i++) {
this.assertStartupViable();
const url = this.serverUrl;
/* v8 ignore next -- waitForReady runs only after waitForPortFile sets the port, so url is always non-empty */
if (url) {
try {
const res = await node.fetch(`${url}/api/health`);
if (res.ok) return;
} catch {
// not ready yet
}
}
await new Promise((r) => window.setTimeout(r, SERVER_MANAGER_CONFIG.HEALTH_POLL_INTERVAL_MS));
}
throw new Error("Server did not become ready within timeout");
}
private async terminateChild(child: ChildProcess): Promise<void> {
if (process.platform === PLATFORM.WIN32) {
try {
await node.execFile("taskkill", ["/pid", String(child.pid), "/f", "/t"]);
} catch (err) {
this.opts.onShutdownFailure?.(err instanceof Error ? err : new Error(String(err)));
}
return;
}
this.signalGroup(child, "SIGTERM");
}
/**
* Signal the child's whole process group (server + worker forks). The child
* leads its own group because it was spawned detached; fall back to the bare
* child if the group send fails (e.g. it already exited).
*/
private signalGroup(child: ChildProcess, signal: NodeJS.Signals): void {
if (child.pid) {
try {
node.processKill(-child.pid, signal);
return;
} catch {
// group gone; fall through to the direct kill
}
}
child.kill(signal);
}
private cleanupPortFile(): void {
if (!node.existsSync(this.portFilePath)) return;
try {
node.unlinkSync(this.portFilePath);
} catch {
// ignore cleanup errors
}
}
async stop(): Promise<void> {
this.stopping = true;
if (this.restartTimer) {
window.clearTimeout(this.restartTimer);
this.restartTimer = null;
}
if (!this.child) {
this.setState(SERVER_STATE.STOPPED);
return;
}
const child = this.child;
await this.terminateChild(child);
const exited = await Promise.race([
new Promise<boolean>((resolve) => child.on("exit", () => resolve(true))),
new Promise<boolean>((resolve) =>
window.setTimeout(() => resolve(false), SERVER_MANAGER_CONFIG.STOP_GRACE_MS),
),
]);
if (!exited && this.child) {
if (process.platform === PLATFORM.WIN32) {
this.child.kill("SIGKILL");
} else {
this.signalGroup(this.child, "SIGKILL");
}
}
this.child = null;
this.setState(SERVER_STATE.STOPPED);
this.cleanupPortFile();
}
async restart(): Promise<void> {
await this.stop();
this.crashCount = 0;
await this.start();
}
}
|