Skip to content

armgit / Ix

Public Imported from GitHub
0

Understand any codebase instantly. System intelligence for codebases, built for humans and AI.

fix(view): report the port the visualizer is actually serving on (#358)

Hiro-Chiba87cd9c0a8e0c
diff --git a/ix-cli/src/cli/__tests__/view-running-port.test.ts b/ix-cli/src/cli/__tests__/view-running-port.test.ts
new file mode 100644
index 00000000..c85314c5
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/view-running-port.test.ts
@@ -0,0 +1,153 @@
+import { EventEmitter } from "node:events";
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { Command } from "commander";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ execSync: vi.fn(),
+ spawn: vi.fn(),
+ createConnection: vi.fn(),
+}));
+
+vi.mock("child_process", () => ({
+ execSync: mocks.execSync,
+ spawn: mocks.spawn,
+}));
+
+vi.mock("net", () => ({
+ createConnection: mocks.createConnection,
+}));
+
+let ixHome: string;
+let originalIxHome: string | undefined;
+
+const pidFile = () => join(ixHome, "compass.pid");
+const scopeFile = () => join(ixHome, "compass.scope");
+const portFile = () => join(ixHome, "compass.port");
+const serverScriptFile = () => join(ixHome, "tmp", "compass-server.js");
+
+beforeEach(() => {
+ vi.resetModules();
+ vi.clearAllMocks();
+
+ originalIxHome = process.env.IX_HOME;
+ ixHome = mkdtempSync(join(tmpdir(), "ix-view-port-test-"));
+ process.env.IX_HOME = ixHome;
+
+ const compassDir = join(ixHome, "cli", "compass");
+ mkdirSync(compassDir, { recursive: true });
+ writeFileSync(join(compassDir, "index.html"), "<!doctype html>");
+
+ mocks.spawn.mockReturnValue({ pid: 4242, unref: vi.fn() });
+ mocks.createConnection.mockImplementation(() => {
+ const connection = new EventEmitter();
+ queueMicrotask(() => connection.emit("error", new Error("not listening")));
+ return connection;
+ });
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ rmSync(ixHome, { recursive: true, force: true });
+ if (originalIxHome === undefined) {
+ delete process.env.IX_HOME;
+ } else {
+ process.env.IX_HOME = originalIxHome;
+ }
+});
+
+async function runView(args: string[]): Promise<string> {
+ const { registerViewCommand } = await import("../commands/view.js");
+ const program = new Command();
+ program.name("ix").exitOverride();
+ registerViewCommand(program);
+
+ const output: string[] = [];
+ const log = vi.spyOn(console, "log").mockImplementation((...values: unknown[]) => {
+ output.push(values.join(" "));
+ });
+ try {
+ await program.parseAsync(["node", "ix", "view", ...args]);
+ } finally {
+ log.mockRestore();
+ }
+ return output.join("\n");
+}
+
+function seedRunningState(port?: number): void {
+ writeFileSync(pidFile(), "4242");
+ writeFileSync(scopeFile(), "*all*");
+ if (port !== undefined) writeFileSync(portFile(), String(port));
+}
+
+describe("view running port state", () => {
+ it("persists the port used to launch the visualizer", async () => {
+ const output = await runView(["-p", "19123", "start", "--no-open", "--all"]);
+
+ expect(readFileSync(portFile(), "utf-8")).toBe("19123");
+ expect(output).toContain("http://localhost:19123");
+ });
+
+ it("reports the persisted port instead of a new requested port", async () => {
+ seedRunningState(19123);
+ vi.spyOn(process, "kill").mockReturnValue(true);
+
+ const output = await runView(["-p", "19124", "start", "--no-open", "--all"]);
+
+ expect(output).toContain("Visualizer is already running (PID 4242)");
+ expect(output).toContain("http://localhost:19123");
+ expect(output).not.toContain("http://localhost:19124");
+ expect(mocks.spawn).not.toHaveBeenCalled();
+ });
+
+ it("recovers the running port from a pre-port-file server script", async () => {
+ seedRunningState();
+ mkdirSync(join(ixHome, "tmp"), { recursive: true });
+ writeFileSync(serverScriptFile(), "const PORT = 19123;\n");
+ vi.spyOn(process, "kill").mockReturnValue(true);
+
+ const output = await runView(["-p", "19124", "start", "--no-open", "--all"]);
+
+ expect(output).toContain("http://localhost:19123");
+ expect(readFileSync(portFile(), "utf-8")).toBe("19123");
+ });
+
+ it("does not print a requested port when legacy state cannot reveal the real one", async () => {
+ seedRunningState();
+ vi.spyOn(process, "kill").mockReturnValue(true);
+
+ const output = await runView(["-p", "19124", "start", "--no-open", "--all"]);
+
+ expect(output).toContain("The running visualizer's port is unknown.");
+ expect(output).not.toContain("http://localhost:19124");
+ });
+
+ it("removes port and scope state with a stale PID", async () => {
+ seedRunningState(19123);
+ vi.spyOn(process, "kill").mockImplementation(() => {
+ throw Object.assign(new Error("no such process"), { code: "ESRCH" });
+ });
+
+ const output = await runView(["status"]);
+
+ expect(output).toContain("Visualizer is not running.");
+ expect(existsSync(pidFile())).toBe(false);
+ expect(existsSync(scopeFile())).toBe(false);
+ expect(existsSync(portFile())).toBe(false);
+ });
+
+ it("removes persisted state when the visualizer stops", async () => {
+ seedRunningState(19123);
+ const kill = vi.spyOn(process, "kill").mockReturnValue(true);
+
+ const output = await runView(["stop"]);
+
+ expect(output).toContain("Visualizer stopped (PID 4242)");
+ expect(kill).toHaveBeenCalledWith(4242, "SIGTERM");
+ expect(existsSync(pidFile())).toBe(false);
+ expect(existsSync(scopeFile())).toBe(false);
+ expect(existsSync(portFile())).toBe(false);
+ });
+});
diff --git a/ix-cli/src/cli/commands/view.ts b/ix-cli/src/cli/commands/view.ts
index 9b83e37a..c13ba003 100644
--- a/ix-cli/src/cli/commands/view.ts
+++ b/ix-cli/src/cli/commands/view.ts
@@ -22,6 +22,8 @@ const PID_FILE = join(IX_HOME, "compass.pid");
// `ix view` launched from a different workspace can warn instead of silently showing the
// already-running (differently-scoped) instance.
const SCOPE_FILE = join(IX_HOME, "compass.scope");
+const PORT_FILE = join(IX_HOME, "compass.port");
+const SERVER_SCRIPT_FILE = join(IX_HOME, "tmp", "compass-server.js");
const BACKEND_URL = "http://localhost:8090";
/** Resolve the compass dist directory — installed path first, then dev fallback. */
@@ -38,18 +40,59 @@ function findCompassDist(): string | null {
return null;
}
+function removeCompassState(): void {
+ for (const path of [PID_FILE, SCOPE_FILE, PORT_FILE]) {
+ try { unlinkSync(path); } catch { /* ignore */ }
+ }
+}
+
+function parsePort(value: string): number | null {
+ const port = Number(value.trim());
+ return Number.isInteger(port) && port >= 1 && port <= 65535 ? port : null;
+}
+
+/** Read the persisted port, falling back to the server script written by older releases. */
+function readRunningPort(): number | null {
+ if (existsSync(PORT_FILE)) {
+ try {
+ const port = parsePort(readFileSync(PORT_FILE, "utf-8"));
+ if (port !== null) return port;
+ } catch {
+ // Fall through to the legacy server script.
+ }
+ }
+
+ if (!existsSync(SERVER_SCRIPT_FILE)) return null;
+ try {
+ const match = readFileSync(SERVER_SCRIPT_FILE, "utf-8").match(/^const PORT = (\d+);$/m);
+ const port = match?.[1] ? parsePort(match[1]) : null;
+ if (port !== null) {
+ // Best-effort migration for a visualizer started before compass.port existed.
+ try { writeFileSync(PORT_FILE, String(port)); } catch { /* ignore */ }
+ }
+ return port;
+ } catch {
+ return null;
+ }
+}
+
/** Read PID from file and check if the process is alive. */
function readAlivePid(): number | null {
- if (!existsSync(PID_FILE)) return null;
- const pid = parseInt(readFileSync(PID_FILE, "utf-8").trim(), 10);
- if (isNaN(pid)) return null;
+ if (!existsSync(PID_FILE)) {
+ removeCompassState();
+ return null;
+ }
+ const pid = Number(readFileSync(PID_FILE, "utf-8").trim());
+ if (!Number.isInteger(pid) || pid <= 0) {
+ removeCompassState();
+ return null;
+ }
try {
process.kill(pid, 0); // signal 0 = existence check
return pid;
} catch {
// Stale PID file
- try { unlinkSync(PID_FILE); } catch { /* ignore */ }
- try { unlinkSync(SCOPE_FILE); } catch { /* ignore */ }
+ removeCompassState();
return null;
}
}
@@ -243,7 +286,13 @@ export function registerViewCommand(program: Command): void {
const existing = readAlivePid();
if (existing) {
console.log(`[ok] Visualizer is already running (PID ${existing})`);
- console.log(` http://localhost:${port}`);
+ const runningPort = readRunningPort();
+ if (runningPort !== null) {
+ console.log(` http://localhost:${runningPort}`);
+ } else {
+ console.log("[!] The running visualizer's port is unknown.");
+ console.log(" Run 'ix view stop' then 'ix view' to restart it.");
+ }
// The running instance has a fixed scope (baked at launch). If this directory
// maps to a different workspace, say so rather than silently showing the old one.
const runningKey = existsSync(SCOPE_FILE) ? readFileSync(SCOPE_FILE, "utf-8").trim() : null;
@@ -282,13 +331,12 @@ export function registerViewCommand(program: Command): void {
}
// Write server script to temp location
- const scriptDir = join(IX_HOME, "tmp");
+ const scriptDir = dirname(SERVER_SCRIPT_FILE);
mkdirSync(scriptDir, { recursive: true });
- const scriptPath = join(scriptDir, "compass-server.js");
- writeFileSync(scriptPath, serverScript(distDir, port, workspaceId, systemId));
+ writeFileSync(SERVER_SCRIPT_FILE, serverScript(distDir, port, workspaceId, systemId));
// Spawn detached process
- const child = spawn("node", [scriptPath], {
+ const child = spawn("node", [SERVER_SCRIPT_FILE], {
detached: true,
stdio: "ignore",
});
@@ -299,10 +347,11 @@ export function registerViewCommand(program: Command): void {
process.exit(1);
}
- // Save PID + the scope it was launched with (for the mismatch warning above).
+ // Save PID, scope, and port for subsequent start/status/stop commands.
mkdirSync(dirname(PID_FILE), { recursive: true });
writeFileSync(PID_FILE, String(child.pid));
writeFileSync(SCOPE_FILE, scopeKey);
+ writeFileSync(PORT_FILE, String(port));
const url = `http://localhost:${port}`;
console.log(`[ok] Visualizer started (PID ${child.pid})`);
@@ -336,8 +385,7 @@ export function registerViewCommand(program: Command): void {
// Already dead
}
- try { unlinkSync(PID_FILE); } catch { /* ignore */ }
- try { unlinkSync(SCOPE_FILE); } catch { /* ignore */ }
+ removeCompassState();
console.log(`[ok] Visualizer stopped (PID ${pid})`);
});