feat: session-first workspace activity and installable daemon

Workspaces page:
- list the newest sessions across workspaces in the activity column; the
  daemon exposes GET /api/v1/sessions/recent as a disk projection and the
  browser enriches live rows from the per-workspace session relay
- put recent activity first below 1100px and fix the mobile page-header
  flex-basis gap

Smoke:
- pin PI2_HOST=127.0.0.1 in both smoke scripts and make the startup-line
  assertion follow the configured host; the daemon default stays 0.0.0.0

Install:
- standalone binary build/install scripts, packaging templates, CI/release
  hooks, CLI-first install docs and the supporting config/doctor changes
This commit is contained in:
yuez committed 2026-10-28 10:53:48 +08:00
1 parent fc51c3be37
commit d2e20d428a
50 files changed
+5104 -188

No files matched your search

+354
View File
@@ -0,0 +1,354 @@
import { describe, expect, it } from "vitest";
import { join } from "node:path";
import { main } from "../../src/cli/pi2.js";
import {
CONFIG_KEYS,
CONFIG_USAGE,
configToJson,
formatConfigTable,
resolveConfig,
type ConfigJsonOutput,
} from "../../src/cli/config.js";
describe("pi2 config", () => {
describe("resolveConfig", () => {
it("returns defaults and layout sources when env is empty", () => {
const resolution = resolveConfig({
env: {},
platform: "linux",
home: "/home/user",
uid: 1000,
version: "1.2.3",
runtime: "node 22.0.0",
installShape: "node",
staticDir: "/repo/web/dist",
});
expect(resolution.config).toEqual({
port: 7676,
host: "0.0.0.0",
publicUrl: null,
staticDir: "/repo/web/dist",
runtimeDir: "/tmp/pi2-1000/pi2",
dataDir: "/home/user/.local/share/pi2",
stateDir: "/home/user/.local/state/pi2",
codingAgentDir: "/home/user/.pi/agent",
workspaceRoots: ["/home/user"],
logLevel: "info",
version: "1.2.3",
platform: "linux",
runtime: "node 22.0.0",
installShape: "node",
});
expect(resolution.sources).toEqual({
port: "default",
host: "default",
publicUrl: "default",
staticDir: "install layout",
runtimeDir: "default",
dataDir: "default",
stateDir: "default",
codingAgentDir: "default",
workspaceRoots: "default",
logLevel: "default",
version: "install layout",
platform: "system",
runtime: "runtime",
installShape: "install layout",
});
});
it("resolves darwin paths when platform is darwin", () => {
const resolution = resolveConfig({
env: {},
platform: "darwin",
home: "/Users/testuser",
uid: 501,
});
expect(resolution.config.platform).toBe("darwin");
expect(resolution.config.runtimeDir).toBe("/Users/testuser/Library/Caches/pi2/run");
expect(resolution.config.dataDir).toBe("/Users/testuser/Library/Application Support/pi2");
expect(resolution.config.stateDir).toBe("/Users/testuser/Library/Logs/pi2");
expect(resolution.sources.runtimeDir).toBe("default");
expect(resolution.sources.dataDir).toBe("default");
expect(resolution.sources.stateDir).toBe("default");
});
it("attributes values to environment variables when set", () => {
const resolution = resolveConfig({
env: {
PI2_PORT: "0",
PI2_HOST: "127.0.0.1",
PI2_PUBLIC_URL: "https://pi2.local/",
PI2_STATIC_DIR: "/opt/pi2/ui",
PI2_RUNTIME_DIR: "/custom/run",
PI2_DATA_DIR: "/custom/data",
PI2_STATE_DIR: "/custom/state",
PI2_WORKSPACE_ROOTS: "/projects,/extra/work",
PI2_LOG_LEVEL: "DEBUG",
},
platform: "linux",
home: "/home/user",
uid: 1000,
});
expect(resolution.config.port).toBe(0);
expect(resolution.sources.port).toBe("PI2_PORT");
expect(resolution.config.host).toBe("127.0.0.1");
expect(resolution.sources.host).toBe("PI2_HOST");
expect(resolution.config.publicUrl).toBe("https://pi2.local");
expect(resolution.sources.publicUrl).toBe("PI2_PUBLIC_URL");
expect(resolution.config.staticDir).toBe("/opt/pi2/ui");
expect(resolution.sources.staticDir).toBe("PI2_STATIC_DIR");
expect(resolution.config.runtimeDir).toBe("/custom/run");
expect(resolution.sources.runtimeDir).toBe("PI2_RUNTIME_DIR");
expect(resolution.config.dataDir).toBe("/custom/data");
expect(resolution.sources.dataDir).toBe("PI2_DATA_DIR");
expect(resolution.config.stateDir).toBe("/custom/state");
expect(resolution.sources.stateDir).toBe("PI2_STATE_DIR");
expect(resolution.config.workspaceRoots).toEqual(["/projects", "/extra/work"]);
expect(resolution.sources.workspaceRoots).toBe("PI2_WORKSPACE_ROOTS");
expect(resolution.config.logLevel).toBe("debug");
expect(resolution.sources.logLevel).toBe("PI2_LOG_LEVEL");
});
it("does not throw when directories do not exist", () => {
expect(() => {
resolveConfig({
env: {
PI2_RUNTIME_DIR: "/nonexistent/path/for/runtime",
PI2_DATA_DIR: "/nonexistent/path/for/data",
PI2_STATE_DIR: "/nonexistent/path/for/state",
PI2_WORKSPACE_ROOTS: "/nonexistent/workspace/dir",
},
home: "/nonexistent/home",
});
}).not.toThrow();
});
it("throws when PI2_PORT is not a valid integer", () => {
expect(() => {
resolveConfig({ env: { PI2_PORT: "not-a-number" } });
}).toThrow('PI2_PORT must be an integer, got "not-a-number"');
});
it("throws when PI2_PORT is out of range", () => {
expect(() => {
resolveConfig({ env: { PI2_PORT: "70000" } });
}).toThrow('PI2_PORT must be between 0 and 65535, got "70000"');
});
});
describe("formatConfigTable", () => {
it("formats a three-column table with key, value, and source", () => {
const resolution = resolveConfig({
env: {
PI2_PORT: "0",
PI2_HOST: "127.0.0.1",
},
platform: "linux",
home: "/home/user",
uid: 1000,
version: "1.0.0",
runtime: "node 22.0.0",
installShape: "node",
staticDir: "/repo/web/dist",
});
const table = formatConfigTable(resolution);
const lines = table.split("\n");
// Header line has key, value, source
expect(lines[0]).toMatch(/^key\s+value\s+source$/);
// Separator line has dashes
expect(lines[1]).toMatch(/^--+\s+--+\s+--+$/);
// Check that all keys are present in order
for (const key of CONFIG_KEYS) {
expect(table).toContain(key);
}
// Port 0 and host 127.0.0.1 show up with source PI2_PORT / PI2_HOST
expect(table).toMatch(/port\s+0\s+PI2_PORT/);
expect(table).toMatch(/host\s+127\.0\.0\.1\s+PI2_HOST/);
// Unset publicUrl shows up as - with source default
expect(table).toMatch(/publicUrl\s+-\s+default/);
// staticDir shows source install layout
expect(table).toMatch(/staticDir\s+\/repo\/web\/dist\s+install layout/);
});
});
describe("configToJson", () => {
it("returns a JSON string with resolved keys and sources map", () => {
const resolution = resolveConfig({
env: {
PI2_PORT: "0",
PI2_HOST: "127.0.0.1",
},
platform: "linux",
home: "/home/user",
uid: 1000,
version: "1.0.0",
runtime: "node 22.0.0",
installShape: "node",
staticDir: "/repo/web/dist",
});
const jsonStr = configToJson(resolution);
const parsed = JSON.parse(jsonStr) as ConfigJsonOutput;
expect(parsed.port).toBe(0);
expect(parsed.host).toBe("127.0.0.1");
expect(parsed.publicUrl).toBeNull();
expect(parsed.staticDir).toBe("/repo/web/dist");
expect(parsed.logLevel).toBe("info");
expect(parsed.version).toBe("1.0.0");
expect(parsed.platform).toBe("linux");
expect(parsed.runtime).toBe("node 22.0.0");
expect(parsed.installShape).toBe("node");
expect(parsed.sources).toEqual({
port: "PI2_PORT",
host: "PI2_HOST",
publicUrl: "default",
staticDir: "install layout",
runtimeDir: "default",
dataDir: "default",
stateDir: "default",
codingAgentDir: "default",
workspaceRoots: "default",
logLevel: "default",
version: "install layout",
platform: "system",
runtime: "runtime",
installShape: "install layout",
});
});
});
describe("CLI integration (main)", () => {
it("prints formatted table with injectable env", async () => {
const out: string[] = [];
const err: string[] = [];
const code = await main(["config"], {
env: {
PI2_PORT: "0",
PI2_HOST: "127.0.0.1",
PI2_RUNTIME_DIR: "/tmp/c1",
PI2_DATA_DIR: "/tmp/c2",
PI2_STATE_DIR: "/tmp/c3",
},
out: (line) => out.push(line),
err: (line) => err.push(line),
});
expect(code).toBe(0);
expect(err).toHaveLength(0);
const text = out.join("\n");
expect(text).toMatch(/^key\s+value\s+source/);
expect(text).toMatch(/port\s+0\s+PI2_PORT/);
expect(text).toMatch(/host\s+127\.0\.0\.1\s+PI2_HOST/);
expect(text).toMatch(/runtimeDir\s+\/tmp\/c1\s+PI2_RUNTIME_DIR/);
expect(text).toMatch(/dataDir\s+\/tmp\/c2\s+PI2_DATA_DIR/);
expect(text).toMatch(/stateDir\s+\/tmp\/c3\s+PI2_STATE_DIR/);
});
it("prints JSON when --json is provided and matches table values", async () => {
const out: string[] = [];
const err: string[] = [];
const code = await main(["config", "--json"], {
env: {
PI2_PORT: "0",
PI2_HOST: "127.0.0.1",
},
out: (line) => out.push(line),
err: (line) => err.push(line),
});
expect(code).toBe(0);
expect(err).toHaveLength(0);
const parsed = JSON.parse(out.join("\n")) as ConfigJsonOutput;
expect(parsed.port).toBe(0);
expect(parsed.host).toBe("127.0.0.1");
expect(parsed.sources.port).toBe("PI2_PORT");
expect(parsed.sources.host).toBe("PI2_HOST");
expect(parsed.sources.runtimeDir).toBe("default");
});
it("prints usage on --help and exits 0", async () => {
const out: string[] = [];
const err: string[] = [];
const code = await main(["config", "--help"], {
out: (line) => out.push(line),
err: (line) => err.push(line),
});
expect(code).toBe(0);
expect(err).toHaveLength(0);
expect(out.join("\n")).toBe(CONFIG_USAGE);
});
it("prints usage on -h and exits 0", async () => {
const out: string[] = [];
const err: string[] = [];
const code = await main(["config", "-h"], {
out: (line) => out.push(line),
err: (line) => err.push(line),
});
expect(code).toBe(0);
expect(err).toHaveLength(0);
expect(out.join("\n")).toBe(CONFIG_USAGE);
});
it("exits 2 on unknown flags with usage error", async () => {
const out: string[] = [];
const err: string[] = [];
const code = await main(["config", "--unknown"], {
out: (line) => out.push(line),
err: (line) => err.push(line),
});
expect(code).toBe(2);
expect(out).toHaveLength(0);
expect(err.some((line) => line.includes("unknown option --unknown"))).toBe(true);
expect(err.some((line) => line.includes("pi2 config"))).toBe(true);
});
it("exits 2 on unexpected positional arguments", async () => {
const out: string[] = [];
const err: string[] = [];
const code = await main(["config", "extra-arg"], {
out: (line) => out.push(line),
err: (line) => err.push(line),
});
expect(code).toBe(2);
expect(out).toHaveLength(0);
expect(err.some((line) => line.includes('unexpected argument "extra-arg"'))).toBe(true);
});
it("exits 1 on invalid PI2_PORT error", async () => {
const out: string[] = [];
const err: string[] = [];
const code = await main(["config"], {
env: { PI2_PORT: "bad-port" },
out: (line) => out.push(line),
err: (line) => err.push(line),
});
expect(code).toBe(1);
expect(err.some((line) => line.includes("PI2_PORT must be an integer"))).toBe(true);
});
});
});
+78 -3
View File
@@ -1,12 +1,13 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { chmodSync, existsSync, mkdirSync, readFileSync, statSync } from "node:fs";
import { chmodSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { DEFAULT_PORT_RETRIES, main, parseDaemonArgs } from "../../src/cli/daemon.js";
import { DEFAULT_PORT_RETRIES, main, parseDaemonArgs, startupLine, USAGE } from "../../src/cli/daemon.js";
import { DEFAULT_HOST } from "../../src/config.js";
import { acquireLock } from "../../src/cli/lock.js";
import { readCliToken, tokenPerms, writeCliToken } from "../../src/cli/token.js";
import { UsageError } from "../../src/cli/util.js";
import { PROTOCOL_VERSION } from "../../src/protocol/types.js";
import { clearRuntimeEnv, removeDir, setRuntimeEnv, tempDir } from "./helpers.js";
import { clearRuntimeEnv, removeDir, setRuntimeEnv, silentLogger, tempDir } from "./helpers.js";
describe("parseDaemonArgs", () => {
it("defaults to nothing set (foreground daemon, config defaults)", () => {
@@ -52,6 +53,10 @@ describe("daemon main (non-listening paths)", () => {
expect(out[0]?.split("\n")[0]).toBe("pi2 daemon — pi2 daemon");
expect(out.join("\n")).toContain("Usage: pi2 daemon [start] [options]");
expect(out.join("\n")).toContain("--static-dir");
expect(out.join("\n")).toContain("0.0.0.0");
expect(out.join("\n")).toContain("--host <addr> bind address (default 0.0.0.0 (all interfaces))");
expect(out.join("\n")).toContain("PI2_HOST (0.0.0.0 (all interfaces))");
expect(USAGE).toContain("0.0.0.0");
});
it("prints the version for --version", async () => {
@@ -166,3 +171,73 @@ describe("daemon singleton lock vs cli.token", () => {
}
});
});
describe("daemon startup line", () => {
let dir: string;
beforeEach(() => {
dir = tempDir("pi2-daemon-startup-");
setRuntimeEnv(dir);
delete process.env.PI2_HOST;
mkdirSync(join(dir, "web"), { recursive: true });
writeFileSync(join(dir, "web", "index.html"), "<!doctype html><title>pi2</title>");
});
afterEach(() => {
clearRuntimeEnv();
delete process.env.PI2_HOST;
removeDir(dir);
});
it("formats startup line with verbatim configured host", () => {
const defaultLine = startupLine(DEFAULT_HOST, 7676);
expect(defaultLine).toMatch(/^pi2 daemon listening on http:\/\/\S+:\d+$/);
expect(defaultLine).toBe("pi2 daemon listening on http://0.0.0.0:7676");
const explicitLine = startupLine("127.0.0.1", 7676);
expect(explicitLine).toMatch(/^pi2 daemon listening on http:\/\/\S+:\d+$/);
expect(explicitLine).toBe("pi2 daemon listening on http://127.0.0.1:7676");
});
it("announces default wildcard host verbatim on start", async () => {
let handle: { close: () => Promise<void> } | undefined;
const out: string[] = [];
try {
const code = await main(["--port", "0"], {
out: (line) => out.push(line),
err: () => undefined,
logger: silentLogger,
onStarted: (h) => {
handle = h;
},
});
expect(code).toBe(0);
expect(out).toHaveLength(1);
expect(out[0]).toMatch(/^pi2 daemon listening on http:\/\/\S+:\d+$/);
expect(out[0]).toMatch(/^pi2 daemon listening on http:\/\/0\.0\.0\.0:\d+$/);
} finally {
if (handle !== undefined) await handle.close();
}
});
it("announces explicit --host 127.0.0.1 verbatim on start", async () => {
let handle: { close: () => Promise<void> } | undefined;
const out: string[] = [];
try {
const code = await main(["--port", "0", "--host", "127.0.0.1"], {
out: (line) => out.push(line),
err: () => undefined,
logger: silentLogger,
onStarted: (h) => {
handle = h;
},
});
expect(code).toBe(0);
expect(out).toHaveLength(1);
expect(out[0]).toMatch(/^pi2 daemon listening on http:\/\/\S+:\d+$/);
expect(out[0]).toMatch(/^pi2 daemon listening on http:\/\/127\.0\.0\.1:\d+$/);
} finally {
if (handle !== undefined) await handle.close();
}
});
});
+233 -3
View File
@@ -9,6 +9,7 @@ import {
checkNvim,
checkNode,
checkProtocol,
checkUnit,
collectContext,
defaultProbes,
formatReport,
@@ -73,6 +74,7 @@ describe("doctor checks (all passing)", () => {
"bind",
"service-manager",
"linger",
"unit",
"web-dist",
"protocol",
]);
@@ -89,6 +91,12 @@ describe("doctor checks (all passing)", () => {
expect(statusOf(report, "linger")).toBeUndefined();
expect(report.ok).toBe(true);
});
it("accepts bundled node runtime even when node version is low or unparsable", async () => {
const report = await checks({ nodeVersion: "v18.0.0", bundled: true });
expect(statusOf(report, "node")).toBe("ok");
expect(report.checks.find((check) => check.name === "node")?.detail).toContain("bundled runtime, no separate node needed");
});
});
describe("doctor bind check", () => {
@@ -184,12 +192,230 @@ describe("doctor curl check", () => {
});
});
describe("doctor unit check", () => {
it("reports ok when no unit file exists", () => {
const check = checkUnit({ path: "/home/u/.config/systemd/user/pi2.service", exists: false });
expect(check).toEqual({
name: "unit",
status: "ok",
detail: "no service unit installed (run `pi2 install-service --write` to keep the daemon running)",
});
expect(checkUnit(undefined).status).toBe("ok");
});
it("warns with the fix hint when unit points at a missing binary path", async () => {
const content = [
"[Unit]",
"Description=pi2 daemon",
"",
"[Service]",
"ExecStart=/home/u/.local/share/mise/installs/node/22.1.0/bin/node /repo/dist/cli/pi2.js daemon --foreground",
"",
].join("\n");
const check = checkUnit(
{
path: "/home/u/.config/systemd/user/pi2.service",
exists: true,
content,
pathExists: (p) => p !== "/home/u/.local/share/mise/installs/node/22.1.0/bin/node",
},
false,
"linux",
);
expect(check.status).toBe("warn");
expect(check.detail).toContain("/home/u/.local/share/mise/installs/node/22.1.0/bin/node");
expect(check.detail).toContain("re-run `pi2 install-service --write`");
const report = await checks({
unit: {
path: "/home/u/.config/systemd/user/pi2.service",
exists: true,
content,
pathExists: () => false,
},
});
expect(statusOf(report, "unit")).toBe("warn");
expect(report.ok).toBe(true);
});
it("warns with the fix hint when unit points at a missing script path", () => {
const content = "ExecStart=/usr/bin/node /missing/dist/cli/pi2.js daemon --foreground\n";
const check = checkUnit(
{
path: "/home/u/.config/systemd/user/pi2.service",
exists: true,
content,
pathExists: (p) => p === "/usr/bin/node",
},
false,
"linux",
);
expect(check.status).toBe("warn");
expect(check.detail).toContain("/missing/dist/cli/pi2.js");
expect(check.detail).toContain("re-run `pi2 install-service --write`");
});
it("warns with the fix hint when plist points at a missing executable", () => {
const content = [
'<?xml version="1.0" encoding="UTF-8"?>',
'<plist version="1.0">',
"<dict>",
" <key>ProgramArguments</key>",
" <array>",
" <string>/missing/node</string>",
" <string>daemon</string>",
" </array>",
"</dict>",
"</plist>",
].join("\n");
const check = checkUnit(
{
path: "/Users/u/Library/LaunchAgents/com.pi2.daemon.plist",
exists: true,
content,
pathExists: () => false,
},
false,
"darwin",
);
expect(check.status).toBe("warn");
expect(check.detail).toContain("/missing/node");
expect(check.detail).toContain("re-run `pi2 install-service --write`");
});
it("reports ok when unit points at an existing path of the current shape (node)", () => {
const content = "ExecStart=/usr/bin/node /repo/dist/cli/pi2.js daemon --foreground\n";
const check = checkUnit(
{
path: "/home/u/.config/systemd/user/pi2.service",
exists: true,
content,
pathExists: () => true,
},
false,
"linux",
);
expect(check).toEqual({
name: "unit",
status: "ok",
detail: "/usr/bin/node",
});
});
it("reports ok when unit points at an existing path of the current shape (bundled)", () => {
const content = 'ExecStart="/usr/local/bin/pi2" daemon --foreground\n';
const check = checkUnit(
{
path: "/home/u/.config/systemd/user/pi2.service",
exists: true,
content,
pathExists: () => true,
},
true,
"linux",
);
expect(check).toEqual({
name: "unit",
status: "ok",
detail: "/usr/local/bin/pi2",
});
});
it("reports ok for launchd plist with existing path of current shape", () => {
const content = [
'<?xml version="1.0" encoding="UTF-8"?>',
'<plist version="1.0">',
"<dict>",
" <key>ProgramArguments</key>",
" <array>",
" <string>/opt/homebrew/bin/node</string>",
" <string>/repo/dist/cli/pi2.js</string>",
" <string>daemon</string>",
" </array>",
"</dict>",
"</plist>",
].join("\n");
const check = checkUnit(
{
path: "/Users/u/Library/LaunchAgents/com.pi2.daemon.plist",
exists: true,
content,
pathExists: () => true,
},
false,
"darwin",
);
expect(check).toEqual({
name: "unit",
status: "ok",
detail: "/opt/homebrew/bin/node",
});
});
it("warns on shape mismatch when recorded executable is node while running bundled", () => {
const content = "ExecStart=/usr/bin/node /repo/dist/cli/pi2.js daemon --foreground\n";
const check = checkUnit(
{
path: "/home/u/.config/systemd/user/pi2.service",
exists: true,
content,
pathExists: () => true,
},
true, // bundled runtime
"linux",
);
expect(check.status).toBe("warn");
expect(check.detail).toBe("unit was rendered for a different install shape; re-run pi2 install-service --write");
});
it("warns on shape mismatch when recorded executable is bundled while running under node", () => {
const content = "ExecStart=/usr/local/bin/pi2 daemon --foreground\n";
const check = checkUnit(
{
path: "/home/u/.config/systemd/user/pi2.service",
exists: true,
content,
pathExists: () => true,
},
false, // node runtime
"linux",
);
expect(check.status).toBe("warn");
expect(check.detail).toBe("unit was rendered for a different install shape; re-run pi2 install-service --write");
});
it("appears in the doctor table output", async () => {
const report = await checks({
unit: {
path: "/home/u/.config/systemd/user/pi2.service",
exists: true,
content: "ExecStart=/usr/bin/node /repo/dist/cli/pi2.js daemon --foreground\n",
pathExists: () => true,
},
});
const text = formatReport(report);
expect(text).toMatch(/ok\s+unit\s+\/usr\/bin\/node/);
const noUnitReport = await checks({
unit: {
path: "/home/u/.config/systemd/user/pi2.service",
exists: false,
},
});
const noUnitText = formatReport(noUnitReport);
expect(noUnitText).toMatch(/ok\s+unit\s+no service unit installed/);
});
});
describe("doctor failure cases", () => {
it("fails on node < 22", async () => {
const report = await checks({ nodeVersion: "v20.11.0" });
it("fails on node < 20", async () => {
const report = await checks({ nodeVersion: "v18.19.0" });
expect(report.ok).toBe(false);
expect(statusOf(report, "node")).toBe("fail");
expect(report.checks.find((check) => check.name === "node")?.detail).toContain("< 22.0.0");
expect(report.checks.find((check) => check.name === "node")?.detail).toContain("< 20.0.0");
});
it("fails when nvim is missing", async () => {
@@ -312,7 +538,11 @@ describe("version helpers", () => {
expect(parseNvimVersion("NVIM v0.9.5")).toBe("0.9.5");
expect(parseNvimVersion("garbage")).toBeUndefined();
expect(checkNode("v22.0.0").status).toBe("ok");
expect(checkNode("v20.0.0").status).toBe("ok");
expect(checkNode("v18.0.0").status).toBe("fail");
expect(checkNode("garbage").status).toBe("fail");
expect(checkNode("v18.0.0", true).status).toBe("ok");
expect(checkNode("v18.0.0", true).detail).toMatch(/bundled runtime, no separate node needed$/);
expect(checkNvim({ found: true, path: "/n", version: "v0.10.0" }).status).toBe("ok");
expect(checkLinger({ checked: false }).status).toBe("ok");
});
+136
View File
@@ -1,7 +1,9 @@
import { describe, expect, it } from "vitest";
import { join } from "node:path";
import {
DEFAULT_SYSTEMD_ENV_FILE,
defaultScriptPath,
defaultServicePaths,
launchAgentDir,
renderLaunchAgent,
renderService,
@@ -20,6 +22,15 @@ const paths: ServicePaths = {
pathEnv: "/opt/node/bin:/usr/bin:/bin",
};
const bundledPaths: ServicePaths = {
bundled: true,
execPath: "/usr/local/bin/pi2",
envFile: "-%h/.config/pi2/env",
stateDir: "/home/u/.local/state/pi2",
homeDir: "/home/u",
pathEnv: "/usr/local/bin:/usr/bin:/bin",
};
const LINUX_UNIT = `[Unit]
Description=pi2 daemon
After=network.target
@@ -37,6 +48,24 @@ TimeoutStopSec=15
WantedBy=default.target
`;
const BUNDLED_LINUX_UNIT = `[Unit]
Description=pi2 daemon
After=network.target
[Service]
Type=simple
ExecStart=/usr/local/bin/pi2 daemon --foreground
EnvironmentFile=-%h/.config/pi2/env
Environment=PATH=/usr/local/bin:/usr/bin:/bin
Restart=on-failure
RestartSec=2
KillSignal=SIGTERM
TimeoutStopSec=15
[Install]
WantedBy=default.target
`;
const MAC_PLIST = `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
@@ -67,6 +96,35 @@ const MAC_PLIST = `<?xml version="1.0" encoding="UTF-8"?>
</plist>
`;
const BUNDLED_MAC_PLIST = `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.pi2.daemon</string>
<key>ProgramArguments</key>
<array>
<string>/usr/local/bin/pi2</string>
<string>daemon</string>
<string>--foreground</string>
</array>
<key>EnvironmentVariables</key>
<dict>
<key>PATH</key>
<string>/usr/local/bin:/usr/bin:/bin</string>
</dict>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<true/>
<key>StandardOutPath</key>
<string>/home/u/.local/state/pi2/pi2-daemon.log</string>
<key>StandardErrorPath</key>
<string>/home/u/.local/state/pi2/pi2-daemon.err.log</string>
</dict>
</plist>
`;
describe("systemd user unit", () => {
it("renders the unit (snapshot)", () => {
expect(renderSystemdUnit(paths)).toBe(LINUX_UNIT);
@@ -85,6 +143,33 @@ describe("systemd user unit", () => {
expect(unit).toContain('ExecStart=/opt/node/bin/node "/repo dir/cli/pi2.js" daemon --foreground');
});
it("renders the bundled unit (snapshot)", () => {
expect(renderSystemdUnit(bundledPaths)).toBe(BUNDLED_LINUX_UNIT);
});
it("renders bundled ExecStart with binary alone, no node or script path, and contains EnvironmentFile", () => {
const unit = renderSystemdUnit(bundledPaths);
expect(unit).toContain("ExecStart=/usr/local/bin/pi2 daemon --foreground");
expect(unit).not.toContain("/opt/node/bin/node");
expect(unit).not.toContain("dist/cli/pi2.js");
expect(unit).toContain("EnvironmentFile=-%h/.config/pi2/env");
expect(unit.indexOf("EnvironmentFile=")).toBeGreaterThan(unit.indexOf("ExecStart="));
expect(unit.indexOf("Environment=PATH")).toBeGreaterThan(unit.indexOf("EnvironmentFile="));
});
it("omits EnvironmentFile when envFile is empty string", () => {
const bundledUnit = renderSystemdUnit({ ...bundledPaths, envFile: "" });
expect(bundledUnit).not.toContain("EnvironmentFile=");
const nodeUnit = renderSystemdUnit({ ...paths, envFile: "" });
expect(nodeUnit).not.toContain("EnvironmentFile=");
});
it("quotes bundled executable with spaces", () => {
const unit = renderSystemdUnit({ ...bundledPaths, execPath: "/opt/custom bin/pi2" });
expect(unit).toContain('ExecStart="/opt/custom bin/pi2" daemon --foreground');
});
it("targets ~/.config/systemd/user and honours XDG_CONFIG_HOME", () => {
expect(systemdUserDir(paths)).toBe("/home/u/.config/systemd/user");
expect(systemdUserDir({ ...paths, configHome: "/xdg" })).toBe("/xdg/systemd/user");
@@ -110,6 +195,31 @@ describe("LaunchAgent plist", () => {
expect(plist).toContain("<string>/opt/a&amp;b/node</string>");
});
it("renders the bundled plist (snapshot)", () => {
expect(renderLaunchAgent(bundledPaths)).toBe(BUNDLED_MAC_PLIST);
});
it("renders bundled ProgramArguments with exactly [exe, daemon, --foreground]", () => {
const plist = renderLaunchAgent(bundledPaths);
const argsBlock = [
" <key>ProgramArguments</key>",
" <array>",
" <string>/usr/local/bin/pi2</string>",
" <string>daemon</string>",
" <string>--foreground</string>",
" </array>",
].join("\n");
expect(plist).toContain(argsBlock);
expect(plist).not.toContain("/opt/node/bin/node");
expect(plist).not.toContain("dist/cli/pi2.js");
expect(plist).not.toContain("EnvironmentFile");
});
it("escapes XML in bundled execPath", () => {
const plist = renderLaunchAgent({ ...bundledPaths, execPath: "/opt/a&b/pi2" });
expect(plist).toContain("<string>/opt/a&amp;b/pi2</string>");
});
it("targets ~/Library/LaunchAgents", () => {
expect(launchAgentDir(paths)).toBe("/home/u/Library/LaunchAgents");
const service = renderService("darwin", paths);
@@ -122,6 +232,15 @@ describe("LaunchAgent plist", () => {
it("resolves dist/cli/pi2.js next to the built CLI", () => {
expect(defaultScriptPath()).toMatch(/dist\/cli\/pi2\.js$/);
});
it("populates bundled, execPath, and default envFile in defaultServicePaths", () => {
const defaults = defaultServicePaths();
expect(typeof defaults.bundled).toBe("boolean");
expect(typeof defaults.execPath).toBe("string");
expect(defaults.envFile).toBe(DEFAULT_SYSTEMD_ENV_FILE);
expect(defaults.nodePath).toBe(process.execPath);
expect(defaults.scriptPath).toMatch(/dist\/cli\/pi2\.js$/);
});
});
describe("install-service / uninstall-service commands", () => {
@@ -158,6 +277,23 @@ describe("install-service / uninstall-service commands", () => {
expect(lines.join("\n")).toContain("systemctl --user daemon-reload");
});
it("writes bundled systemd unit on linux with --write", () => {
const lines: string[] = [];
const writes: { path: string; content: string }[] = [];
const code = runInstallService({
platform: "linux",
paths: bundledPaths,
write: true,
print: (line) => lines.push(line),
writeFile: (path, content) => writes.push({ path, content }),
});
expect(code).toBe(0);
expect(writes).toEqual([
{ path: join("/home/u/.config/systemd/user", "pi2.service"), content: BUNDLED_LINUX_UNIT },
]);
expect(lines[0]).toBe("wrote /home/u/.config/systemd/user/pi2.service (mode 0644)");
});
it("uninstall removes the unit only with --write", () => {
const removed: string[] = [];
const dry: string[] = [];
+47
View File
@@ -0,0 +1,47 @@
import { describe, expect, it } from "vitest";
import { readFileSync } from "node:fs";
import { dirname, isAbsolute, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import {
defaultStaticDir,
executablePath,
isBundledRuntime,
runtimeDescription,
staticDirCandidates,
version,
} from "../../src/core/install.js";
describe("install helpers", () => {
it("reports version matching package.json when running from a checkout", () => {
const pkgPath = fileURLToPath(new URL("../../package.json", import.meta.url));
const pkg = JSON.parse(readFileSync(pkgPath, "utf8")) as { version: string };
expect(version()).toBe(pkg.version);
});
it("returns three absolute candidates with share/pi2d/web/dist first", () => {
const candidates = staticDirCandidates();
expect(candidates).toHaveLength(3);
for (const candidate of candidates) {
expect(isAbsolute(candidate)).toBe(true);
}
const exeDir = dirname(executablePath());
const expectedFirst = resolve(exeDir, "..", "share", "pi2d", "web", "dist");
expect(candidates[0]).toBe(expectedFirst);
});
it("resolves defaultStaticDir without throwing and returns dev checkout web/dist", () => {
expect(() => defaultStaticDir()).not.toThrow();
const dir = defaultStaticDir();
expect(isAbsolute(dir)).toBe(true);
const expectedDevPath = resolve(fileURLToPath(new URL("../../web/dist", import.meta.url)));
expect(dir).toBe(expectedDevPath);
});
it("reports isBundledRuntime as false under vitest", () => {
expect(isBundledRuntime()).toBe(false);
});
it("reports runtimeDescription starting with 'node '", () => {
expect(runtimeDescription().startsWith("node ")).toBe(true);
});
});
+93
View File
@@ -0,0 +1,93 @@
import { homedir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { piAgentDir, sessionsRoot } from "../../src/core/paths.js";
describe("piAgentDir and sessionsRoot", () => {
const originalEnv = { ...process.env };
afterEach(() => {
process.env = { ...originalEnv };
});
it("prefers PI2_CODING_AGENT_DIR when both PI2_ and PI_ are set", () => {
const env = {
PI2_CODING_AGENT_DIR: "/custom/pi2/agent",
PI_CODING_AGENT_DIR: "/custom/pi/agent",
};
expect(piAgentDir(env)).toBe("/custom/pi2/agent");
expect(sessionsRoot(env)).toBe(join("/custom/pi2/agent", "sessions"));
});
it("uses PI_CODING_AGENT_DIR when PI2_CODING_AGENT_DIR is unset", () => {
const env = {
PI_CODING_AGENT_DIR: "/custom/pi/agent",
};
expect(piAgentDir(env)).toBe("/custom/pi/agent");
expect(sessionsRoot(env)).toBe(join("/custom/pi/agent", "sessions"));
});
it("falls back to ~/.pi/agent when neither variable is set", () => {
const env = {};
const expected = join(homedir(), ".pi", "agent");
expect(piAgentDir(env)).toBe(expected);
expect(piAgentDir(env).endsWith(join(".pi", "agent"))).toBe(true);
expect(sessionsRoot(env)).toBe(join(expected, "sessions"));
});
it("falls through empty strings to the next candidate", () => {
// PI2 is empty string -> falls through to PI
expect(
piAgentDir({
PI2_CODING_AGENT_DIR: "",
PI_CODING_AGENT_DIR: "/custom/pi/agent",
}),
).toBe("/custom/pi/agent");
// Both are empty strings -> falls through to ~/.pi/agent
const expected = join(homedir(), ".pi", "agent");
expect(
piAgentDir({
PI2_CODING_AGENT_DIR: "",
PI_CODING_AGENT_DIR: "",
}),
).toBe(expected);
// PI2 unset, PI is empty string -> falls through to ~/.pi/agent
expect(
piAgentDir({
PI_CODING_AGENT_DIR: "",
}),
).toBe(expected);
});
it("handles relative paths without crashing", () => {
const relative = "some/relative/agent";
expect(piAgentDir({ PI2_CODING_AGENT_DIR: relative })).toBe(relative);
expect(sessionsRoot({ PI2_CODING_AGENT_DIR: relative })).toBe(join(relative, "sessions"));
expect(piAgentDir({ PI_CODING_AGENT_DIR: relative })).toBe(relative);
expect(sessionsRoot({ PI_CODING_AGENT_DIR: relative })).toBe(join(relative, "sessions"));
});
it("respects daemon ambient environment injection via process.env", () => {
delete process.env.PI2_CODING_AGENT_DIR;
delete process.env.PI_CODING_AGENT_DIR;
process.env.PI2_CODING_AGENT_DIR = "/daemon/injected/pi2";
expect(piAgentDir()).toBe("/daemon/injected/pi2");
expect(sessionsRoot()).toBe(join("/daemon/injected/pi2", "sessions"));
process.env.PI_CODING_AGENT_DIR = "/daemon/injected/pi";
// PI2 still wins
expect(piAgentDir()).toBe("/daemon/injected/pi2");
// When PI2 is empty string in process.env, falls through to PI
process.env.PI2_CODING_AGENT_DIR = "";
expect(piAgentDir()).toBe("/daemon/injected/pi");
// When both are empty string in process.env, falls through to default
process.env.PI_CODING_AGENT_DIR = "";
expect(piAgentDir()).toBe(join(homedir(), ".pi", "agent"));
});
});
+7 -1
View File
@@ -11,7 +11,7 @@ import type {
PluginConnection,
WorkspaceStore,
} from "../../src/core/interfaces.js";
import type { InstanceState, SessionState, WorkspaceInfo } from "../../src/protocol/types.js";
import type { InstanceState, RecentSessionInfo, SessionState, WorkspaceInfo } from "../../src/protocol/types.js";
export interface CommandCall {
id: string;
@@ -211,6 +211,8 @@ export class FakeWorkspaceStore implements WorkspaceStore {
updateCalls: { workspaceId: string; patch: Record<string, unknown> }[] = [];
removeCalls: string[] = [];
refreshCalls: (string | undefined)[] = [];
/** Seeded answer for `recentSessions()`; the fake never touches disk. */
recentSessionRows: RecentSessionInfo[] = [];
constructor(seed: WorkspaceInfo[] = []) {
for (const workspace of seed) this.workspaces.set(workspace.workspaceId, workspace);
@@ -262,6 +264,10 @@ export class FakeWorkspaceStore implements WorkspaceStore {
async ensureForCwd(cwd: string): Promise<WorkspaceInfo> {
return this.byCwd(cwd) ?? this.add({ cwd });
}
recentSessions(limit = 20): RecentSessionInfo[] {
return this.recentSessionRows.slice(0, limit);
}
}
export class FakeBus implements Bus {
+34
View File
@@ -281,6 +281,40 @@ describe("HTTP API", () => {
);
});
it("serves the disk-projected recent-session feed for the activity column", async () => {
h.workspaces.recentSessionRows = [
{
sessionId: "s-new",
workspaceId: "ws-1",
workspaceName: "alpha",
cwd: "/work/alpha",
sessionFile: "/sessions/a/s-new.jsonl",
timestamp: 1_700_000_000_000,
modified: 1_700_000_100_000,
},
{
sessionId: "s-old",
workspaceId: "ws-1",
workspaceName: "alpha",
cwd: "/work/alpha",
sessionFile: "/sessions/a/s-old.jsonl",
timestamp: 1_600_000_000_000,
modified: 1_600_000_100_000,
},
];
// It must not relay to (or spawn) an instance — the fake store answers
// directly and the connection never sees a command.
const res = await fetch(`${h.url}/api/v1/sessions/recent?limit=1`, authed());
expect(res.status).toBe(200);
const body = (await res.json()) as { sessions: { sessionId: string }[] };
expect(body.sessions).toEqual([expect.objectContaining({ sessionId: "s-new", workspaceName: "alpha" })]);
expect(conn.commands).toHaveLength(0);
const fallback = await fetch(`${h.url}/api/v1/sessions/recent`, authed());
expect(((await fallback.json()) as { sessions: unknown[] }).sessions).toHaveLength(2);
});
it("routes a disk-only session's entries through workspaceId but keeps the sid", async () => {
// A row from disk discovery is not owned by the live instance, so the
// workspace hint is what routes it -- and the sid must survive that.
+30
View File
@@ -227,6 +227,36 @@ describe("workspace disk discovery", () => {
}
});
it("defaults the root to PI2_CODING_AGENT_DIR/sessions, taking precedence over PI_CODING_AGENT_DIR", () => {
const pi2Agent = join(sandbox, "pi2-agent");
const pi2Sessions = join(pi2Agent, "sessions");
mkdirSync(pi2Sessions, { recursive: true });
writeSessionDir(pi2Sessions, encodedDirName(sandbox), [
{ name: "2026-10-10T06-40-33-032Z_pi2.jsonl", cwd: sandbox, id: "pi2" },
]);
const piAgent = join(sandbox, "pi-agent");
const piSessions = join(piAgent, "sessions");
mkdirSync(piSessions, { recursive: true });
writeSessionDir(piSessions, encodedDirName(sandbox), [
{ name: "2026-10-10T06-40-33-032Z_pi.jsonl", cwd: sandbox, id: "pi" },
]);
const prevPi2 = process.env.PI2_CODING_AGENT_DIR;
const prevPi = process.env.PI_CODING_AGENT_DIR;
process.env.PI2_CODING_AGENT_DIR = pi2Agent;
process.env.PI_CODING_AGENT_DIR = piAgent;
try {
const discovered = createDiscovery().discover();
expect(discovered).toHaveLength(1);
expect(discovered[0]?.dir).toBe(join(pi2Sessions, encodedDirName(sandbox)));
} finally {
if (prevPi2 === undefined) delete process.env.PI2_CODING_AGENT_DIR;
else process.env.PI2_CODING_AGENT_DIR = prevPi2;
if (prevPi === undefined) delete process.env.PI_CODING_AGENT_DIR;
else process.env.PI_CODING_AGENT_DIR = prevPi;
}
});
it("ignores a vanished directory gracefully", () => {
const dir = writeSessionDir(root, encodedDirName(sandbox), [
{ name: "2026-10-10T06-40-33-032Z_a.jsonl", cwd: sandbox, id: "a" },
+51 -4
View File
@@ -53,14 +53,38 @@ describe("workspace store", () => {
for (const dir of [sessions, allowRoot, projectA, projectB, projectGhost]) mkdirSync(dir, { recursive: true });
writeSessionDir(sessions, encodedDirName(projectA), [
{ name: "2026-10-10T06-40-33-032Z_a1.jsonl", cwd: projectA, id: "a1" },
{ name: "2026-10-11T06-40-33-032Z_a2.jsonl", cwd: projectA, id: "a2" },
{
name: "2026-10-10T06-40-33-032Z_a1.jsonl",
cwd: projectA,
id: "a1",
timestamp: "2026-10-10T06:40:33.032Z",
mtime: new Date("2026-10-10T06:40:33.032Z"),
},
{
name: "2026-10-11T06-40-33-032Z_a2.jsonl",
cwd: projectA,
id: "a2",
timestamp: "2026-10-11T06:40:33.032Z",
mtime: new Date("2026-10-11T06:40:33.032Z"),
},
]);
writeSessionDir(sessions, encodedDirName(projectB), [
{ name: "2026-10-12T06-40-33-032Z_b1.jsonl", cwd: projectB, id: "b1" },
{
name: "2026-10-12T06-40-33-032Z_b1.jsonl",
cwd: projectB,
id: "b1",
timestamp: "2026-10-12T06:40:33.032Z",
mtime: new Date("2026-10-12T06:40:33.032Z"),
},
]);
writeSessionDir(sessions, encodedDirName(projectGhost), [
{ name: "2026-10-13T06-40-33-032Z_g1.jsonl", cwd: projectGhost, id: "g1" },
{
name: "2026-10-13T06-40-33-032Z_g1.jsonl",
cwd: projectGhost,
id: "g1",
timestamp: "2026-10-13T06:40:33.032Z",
mtime: new Date("2026-10-13T06:40:33.032Z"),
},
]);
rmSync(projectGhost, { recursive: true, force: true });
});
@@ -116,6 +140,29 @@ describe("workspace store", () => {
expect(ghost).toMatchObject({ exists: false, sessionCount: 1, lastActiveAt: expect.any(Number) });
});
it("lists the newest session files across workspaces for the activity feed", () => {
const { store } = setup();
const rows = store.recentSessions(3);
expect(rows.map((row) => row.sessionId)).toEqual(["g1", "b1", "a2"]);
expect(rows.map((row) => row.workspaceId)).toEqual([
workspaceIdForCwd(projectGhost),
workspaceIdForCwd(projectB),
workspaceIdForCwd(projectA),
]);
expect(rows[0]).toMatchObject({
workspaceName: "ghost",
cwd: projectGhost,
timestamp: Date.parse("2026-10-13T06:40:33.032Z"),
modified: Date.parse("2026-10-13T06:40:33.032Z"),
sessionFile: expect.stringContaining("g1"),
});
// The default (no limit) still returns every discovered session, and an
// out-of-range limit is clamped instead of exploding the header scan.
expect(store.recentSessions()).toHaveLength(4);
expect(store.recentSessions(0)).toHaveLength(4);
});
it("keeps hidden entries in list(); the UI decides ordering", async () => {
const { store } = setup();
const bId = workspaceIdForCwd(projectB);