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
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,14 @@ All notable changes to `sessionpipe-gui`. The format follows

## [Unreleased]

### Fixed

- **A second receiver on the same state folder no longer hides the first.** Stopping a
receiver started on another `--port` with the same `--state` left no `run.json` while
the first one still ran, so `service status` (and the desktop app, for a first receiver
off the default port) lost it; the stopping receiver now writes the first one's entry
back.

## [0.8.19] - 2026-12-04

### Added
Expand Down
10 changes: 6 additions & 4 deletions server/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import { lanAddresses } from "./http/net.js";
import { runKeyCommand } from "./keyCommand.js";
import { DEFAULT_HOST, listenErrorMessage } from "./listen-error.js";
import { addPlugin, formatPluginList, linkPlugin, listPlugins, removePlugin } from "./plugins/index.js";
import { removeRunFile, writeRunFile } from "./runfile.js";
import { readRunFile, releaseRunFile, writeRunFile } from "./runfile.js";
import { processEnv, runService, type Verb } from "./service/index.js";
import { sameMachine } from "./setup/index.js";
import { addSkin, formatSkinList, linkSkin, listSkins, removeSkin } from "./skins/index.js";
Expand Down Expand Up @@ -891,7 +891,9 @@ async function main(): Promise<void> {
}
if (parsed.open) openBrowser(app.info().urls.local);
// run.json: how the desktop app finds a receiver on a port other than the default.
// Removed on a clean stop; a crash leaves a dead pid, which readers ignore.
// Removed on a clean stop; a crash leaves a dead pid, which readers ignore. Another
// receiver already running on this state dir gets its entry back when this one stops.
const previous = readRunFile(app.stateDir);
try {
writeRunFile(app.stateDir, {
port: app.port,
Expand All @@ -903,7 +905,7 @@ async function main(): Promise<void> {
} catch (e) {
process.stderr.write(`sessionpipe-gui: could not write run.json: ${(e as Error).message}\n`);
}
process.on("exit", () => removeRunFile(app.stateDir));
process.on("exit", () => releaseRunFile(app.stateDir, previous));

let closing = false;
// The output may be gone by the time a signal comes (a closed terminal, or a `| tee`
Expand All @@ -919,7 +921,7 @@ async function main(): Promise<void> {
if (closing) return;
closing = true;
if (!parsed.quiet) process.stdout.write(`\n${signal}: stopping\n`);
removeRunFile(app.stateDir);
releaseRunFile(app.stateDir, previous);
const force = setTimeout(() => process.exit(0), 3000);
force.unref();
void app.close().then(() => process.exit(0));
Expand Down
106 changes: 105 additions & 1 deletion server/runfile.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,15 @@ import path from "node:path";
import { fileURLToPath } from "node:url";
import { build } from "esbuild";
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
import { pidAlive, readRunFile, readRunFileRaw, removeRunFile, runFilePath, writeRunFile } from "./runfile.js";
import {
pidAlive,
readRunFile,
readRunFileRaw,
releaseRunFile,
removeRunFile,
runFilePath,
writeRunFile,
} from "./runfile.js";

let dir: string;
beforeEach(() => {
Expand Down Expand Up @@ -62,6 +70,49 @@ describe("run.json", () => {
expect(removeRunFile(dir)).toBe(false);
});

it("is given back on release to the receiver it replaced, while that one runs", () => {
const other = info(process.pid + 100000);
const alive = (pid: number) => pid === other.pid;
writeRunFile(dir, info());
expect(releaseRunFile(dir, other, process.pid, alive)).toBe(true);
expect(readRunFileRaw(dir)).toEqual(other);
expect(readdirSync(dir)).toEqual(["run.json"]);
// No longer ours (given back, or a third receiver took it): left alone.
expect(releaseRunFile(dir, other, process.pid, alive)).toBe(false);
expect(readRunFileRaw(dir)).toEqual(other);
});

it("is removed on release when the receiver it replaced is gone, or there was none", () => {
const other = info(process.pid + 100000);
writeRunFile(dir, info());
expect(releaseRunFile(dir, other, process.pid, () => false)).toBe(true);
expect(existsSync(runFilePath(dir))).toBe(false);
writeRunFile(dir, info());
expect(releaseRunFile(dir, null)).toBe(true);
expect(existsSync(runFilePath(dir))).toBe(false);
writeRunFile(dir, info());
expect(releaseRunFile(dir, info(), process.pid, () => true)).toBe(true);
expect(existsSync(runFilePath(dir))).toBe(false);
});

it("is removed on release when the previous entry cannot be written back", () => {
const other = info(process.pid + 100000);
writeRunFile(dir, info());
// A folder where the temporary file goes makes the write-back fail.
mkdirSync(`${runFilePath(dir)}.${process.pid}.tmp`);
expect(releaseRunFile(dir, other, process.pid, () => true)).toBe(true);
expect(existsSync(runFilePath(dir))).toBe(false);
});

it("leaves no temporary file when the rename fails", () => {
// A folder (not empty) where run.json goes makes the rename fail.
mkdirSync(path.join(runFilePath(dir), "x"), { recursive: true });
expect(() => writeRunFile(dir, info())).toThrow();
expect(readdirSync(dir)).toEqual(["run.json"]);
expect(releaseRunFile(dir, info(process.pid + 100000), process.pid, () => true)).toBe(false);
expect(readdirSync(dir)).toEqual(["run.json"]);
});

it("treats pid 1 (someone else's, EPERM) as alive and pid 0 as not", () => {
expect(pidAlive(1)).toBe(true);
expect(pidAlive(0)).toBe(false);
Expand Down Expand Up @@ -167,6 +218,59 @@ describe("the receiver's run.json lifecycle", () => {
);
}

// Two receivers on one state folder (a second one on another --port): the second takes
// run.json at listen, and gives it back to the first when it stops, instead of leaving
// no file while the first still answers.
for (const signal of ["SIGTERM", "SIGINT"] as const) {
it(`a second receiver stopped by ${signal} gives run.json back to the first, still running`, async () => {
const state = path.join(dir, "state");
const first = start(state);
let second: ChildProcess | undefined;
try {
await waitFor(() => readRunFile(state)?.pid === first.pid);
const a = readRunFile(state)!;
second = start(state);
const b = second;
await waitFor(() => readRunFile(state)?.pid === b.pid);
const exited = new Promise((resolve) => b.on("exit", (code) => resolve(code)));
b.kill(signal);
expect(await exited).toBe(0);
expect(readRunFile(state)).toEqual(a);
expect((await fetch(`${a.url}/api/ui/info`)).status).toBe(200);
const firstExited = new Promise((resolve) => first.on("exit", (code) => resolve(code)));
first.kill("SIGTERM");
expect(await firstExited).toBe(0);
expect(existsSync(runFilePath(state))).toBe(false);
} finally {
second?.kill("SIGKILL");
first.kill("SIGKILL");
}
}, 30_000);
}

it("the first receiver stopped first leaves the second one's run.json, which then removes it", async () => {
const state = path.join(dir, "state");
const first = start(state);
let second: ChildProcess | undefined;
try {
await waitFor(() => readRunFile(state)?.pid === first.pid);
second = start(state);
const b = second;
await waitFor(() => readRunFile(state)?.pid === b.pid);
const firstExited = new Promise((resolve) => first.on("exit", (code) => resolve(code)));
first.kill("SIGTERM");
expect(await firstExited).toBe(0);
expect(readRunFile(state)?.pid).toBe(b.pid);
const exited = new Promise((resolve) => b.on("exit", (code) => resolve(code)));
b.kill("SIGTERM");
expect(await exited).toBe(0);
expect(existsSync(runFilePath(state))).toBe(false);
} finally {
second?.kill("SIGKILL");
first.kill("SIGKILL");
}
}, 30_000);

it("a killed receiver leaves a stale file that readers ignore", async () => {
const state = path.join(dir, "state");
const child = start(state);
Expand Down
35 changes: 31 additions & 4 deletions server/runfile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
// Owned by: packaging. `<state>/run.json`: where a running receiver can be found. Written
// atomically when it listens, removed when it stops cleanly, so the desktop app (and
// anything else on this machine) finds a receiver on a port other than 7373 without
// scanning. A file left behind by a crash names a dead pid, and readers ignore it.
// scanning. A second receiver on the same state dir takes the file over and, when it
// stops, gives it back to the one it took it from if that one still runs. A file left
// behind by a crash names a dead pid, and readers ignore it.
import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
import path from "node:path";

Expand All @@ -20,13 +22,19 @@ export interface RunInfo {

export const runFilePath = (stateDir: string): string => path.join(stateDir, RUN_FILE);

/** Write `run.json`: a temporary file beside it, then a rename, so a reader never sees half of it. */
/** Write `run.json`: a temporary file beside it, then a rename, so a reader never sees half of
* it. A failed write or rename throws, and leaves no temporary file behind. */
export function writeRunFile(stateDir: string, info: RunInfo): string {
mkdirSync(stateDir, { recursive: true });
const file = runFilePath(stateDir);
const tmp = `${file}.${process.pid}.tmp`;
writeFileSync(tmp, `${JSON.stringify(info, null, 2)}\n`, { mode: 0o644 });
renameSync(tmp, file);
try {
writeFileSync(tmp, `${JSON.stringify(info, null, 2)}\n`, { mode: 0o644 });
renameSync(tmp, file);
} catch (e) {
rmSync(tmp, { force: true });
throw e;
}
return file;
}

Expand Down Expand Up @@ -81,3 +89,22 @@ export function removeRunFile(stateDir: string, pid = process.pid): boolean {
return false;
}
}

/** On a clean stop: when the run file is ours and the receiver whose live file we replaced
* at listen (`previous`) still runs, write its entry back; else remove ours as
* removeRunFile does. Returns whether it changed the file. */
export function releaseRunFile(
stateDir: string,
previous: RunInfo | null,
pid = process.pid,
alive: (pid: number) => boolean = pidAlive,
): boolean {
if (!previous || previous.pid === pid || !alive(previous.pid)) return removeRunFile(stateDir, pid);
if (readRunFileRaw(stateDir)?.pid !== pid) return false;
try {
writeRunFile(stateDir, previous);
return true;
} catch {
return removeRunFile(stateDir, pid);
}
}