diff --git a/README.md b/README.md index 5a59945..52e3c24 100644 --- a/README.md +++ b/README.md @@ -80,7 +80,7 @@ See [docs/reference.md](docs/reference.md) for every key, the message box, diffs t3tui finds the local T3 Code server from `~/.t3/userdata/server-runtime.json` (override with `T3TUI_SERVER`). On first run it issues itself a session with `t3 auth session issue --label t3tui`, scoped to what it needs, and stores it in `~/.config/t3tui/credentials.json`. Revoke it any time with `t3 auth session revoke`. For a remote server, pass a token in `T3TUI_TOKEN`. -No desktop app needed: the flake in this repo also packages the headless server CLI, so `nix develop --command t3 serve` (or `nix build .#t3` and run `result/bin/t3 serve`) starts T3 Code with no browser — it writes the same `server-runtime.json` that t3tui reads. +No desktop app needed: if no local server answers when t3tui starts, it runs `t3 serve` itself (found via `T3TUI_T3_BIN`, `~/.t3/bin/t3`, or `PATH` — the flake in this repo also packages it, so `nix develop` provides it) and stops that server again on quit. Its output goes to `~/.config/t3tui/server.log`. If a server is already running, t3tui just connects to it. To run the server separately instead, `nix develop --command t3 serve` (or `nix build .#t3` and run `result/bin/t3 serve`) starts T3 Code with no browser. The scopes, the protocol and how to update for a newer T3 Code are in [docs/development.md](docs/development.md). diff --git a/flake.nix b/flake.nix index 61073bc..41e9a2b 100644 --- a/flake.nix +++ b/flake.nix @@ -61,7 +61,7 @@ runHook preInstall mkdir -p $out/lib $out/bin cp -r . $out/lib/t3 - ${pkgs.lib.optionalString pkgs.stdenv.isLinux '' + ${pkgs.lib.optionalString pkgs.stdenv.hostPlatform.isLinux '' libPath="${pkgs.lib.makeLibraryPath [ pkgs.stdenv.cc.cc.lib pkgs.zlib diff --git a/src/bin.ts b/src/bin.ts index ba44a57..541f50f 100755 --- a/src/bin.ts +++ b/src/bin.ts @@ -2,6 +2,7 @@ import type { OrchestrationV2ShellSnapshot, ThreadId } from "@t3tools/contracts"; import { migrateConfigDir } from "./client/auth.ts"; +import { ensureLocalServer } from "./client/spawnServer.ts"; import { T3Session } from "./client/session.ts"; import { isCompiled, removeOldBinaries, upgrade, VERSION } from "./upgrade.ts"; import { findThread, lastActivity, relativeTime, rowTime, shortId, statusLabel, threadRows } from "./model/threads.ts"; @@ -20,7 +21,10 @@ usage: env: T3TUI_SERVER server origin (default: the local server from ~/.t3) - T3TUI_TOKEN bearer token for a remote server (local servers mint one via \`t3\`)`; + T3TUI_TOKEN bearer token for a remote server (local servers mint one via \`t3\`) + T3TUI_T3_BIN the \`t3\` binary to run \`t3 serve\` with when no local server is up + +with no local server running, t3tui starts \`t3 serve\` itself and stops it on quit;` async function main(argv: string[]) { migrateConfigDir(); @@ -76,21 +80,28 @@ async function connectedSession(): Promise<{ session: T3Session; snapshot: Orche } async function list(json: boolean) { - const { session, snapshot } = await connectedSession(); - const rows = threadRows(snapshot, { settledLimit: 20 }); - if (json) { - console.log(JSON.stringify(rows.map((row) => ({ id: row.thread.id, title: row.thread.title, project: row.projectName, section: row.section, status: row.status, unread: row.unread, updatedAt: new Date(lastActivity(row.thread)).toISOString() })), null, 2)); - } else { - for (const row of rows) { - const status = statusLabel(row)?.text ?? relativeTime(rowTime(row.thread)); - console.log(`${shortId(row.thread.id)} ${row.section.padEnd(8)} ${status.padEnd(12)} ${row.projectName.padEnd(20).slice(0, 20)} ${row.thread.title}`); + const server = await ensureLocalServer(); + try { + const { session, snapshot } = await connectedSession(); + const rows = threadRows(snapshot, { settledLimit: 20 }); + if (json) { + console.log(JSON.stringify(rows.map((row) => ({ id: row.thread.id, title: row.thread.title, project: row.projectName, section: row.section, status: row.status, unread: row.unread, updatedAt: new Date(lastActivity(row.thread)).toISOString() })), null, 2)); + } else { + for (const row of rows) { + const status = statusLabel(row)?.text ?? relativeTime(rowTime(row.thread)); + console.log(`${shortId(row.thread.id)} ${row.section.padEnd(8)} ${status.padEnd(12)} ${row.projectName.padEnd(20).slice(0, 20)} ${row.thread.title}`); + } } + await session.stop(); + } finally { + await server?.stop(); } - await session.stop(); } async function tmuxCommand(args: string[]) { if (process.platform === "win32") return fail("t3tui tmux needs tmux, which doesn't run on Windows. Run it inside WSL instead."); + const server = await ensureLocalServer(); + try { const { syncTmux } = await import("./mux/tmux.ts"); const sessionFlag = args.indexOf("--session"); const name = sessionFlag >= 0 ? args[sessionFlag + 1] : "t3tui"; @@ -129,9 +140,14 @@ async function tmuxCommand(args: string[]) { // A dropped connection retries by itself; sync runs again once the shell is back. session.onShell(() => void sync()); await new Promise(() => {}); + } finally { + await server?.stop(); + } } async function runUi(attachNeedle?: string) { + // No server socket answering: start `t3 serve` ourselves and stop it on quit. + const server = await ensureLocalServer(); let session: T3Session; let attachThreadId: ThreadId | undefined; if (!attachNeedle) { @@ -164,7 +180,7 @@ async function runUi(attachNeedle?: string) { // session's socket would keep a closed terminal's t3tui running for good. // The terminal is restored once `closed` settles, after the destroy event. renderer.once("destroy", () => { - void Promise.allSettled([Promise.race([session.stop(), Bun.sleep(1000)]), renderer.closed]).finally(() => process.exit(0)); + void Promise.allSettled([Promise.race([session.stop(), Bun.sleep(1000)]), Promise.race([server?.stop() ?? Promise.resolve(), Bun.sleep(2000)]), renderer.closed]).finally(() => process.exit(0)); }); // Bun collects so lazily that a streaming thread takes t3tui past 500 MB of garbage. A full // collection pauses for up to ~150 ms, so it waits for a few seconds without keys or clicks. diff --git a/src/client/spawnServer.ts b/src/client/spawnServer.ts new file mode 100644 index 0000000..4acfa42 --- /dev/null +++ b/src/client/spawnServer.ts @@ -0,0 +1,105 @@ +import { mkdirSync, openSync } from "node:fs"; +import { readFile } from "node:fs/promises"; +import { homedir } from "node:os"; +import { dirname, join } from "node:path"; + +import { configDir, t3Command } from "./auth.ts"; + +const t3Home = () => process.env.T3CODE_HOME ?? join(homedir(), ".t3"); +const runtimePath = () => join(t3Home(), "userdata", "server-runtime.json"); + +export interface SpawnedServer { + /** The origin the spawned server came up on. */ + readonly origin: string; + /** Stops the server and its process group, if t3tui started it. */ + stop(): Promise; +} + +/** The origin the runtime file names, or null when there is no runtime file. */ +async function localOrigin(): Promise { + try { + const runtime = JSON.parse(await readFile(runtimePath(), "utf8")) as { origin?: string; port?: number }; + return runtime.origin ?? (runtime.port != null ? `http://127.0.0.1:${runtime.port}` : null); + } catch { + return null; + } +} + +/** True when something answers HTTP at the origin — the runtime file alone can be stale. */ +async function serverAlive(origin: string): Promise { + try { + await fetch(origin, { signal: AbortSignal.timeout(1_000) }); + return true; + } catch { + return false; + } +} + +function killGroup(child: Bun.Subprocess, signal: NodeJS.Signals): void { + // detached gives the server its own process group, so this takes down its children too. + try { + process.kill(-child.pid, signal); + } catch { + try { + child.kill(signal); + } catch { + // already gone + } + } +} + +/** + * Makes sure a local T3 Code server is up before connecting: if the runtime file's origin + * answers, the existing server is used as-is; otherwise `t3 serve` is spawned and waited + * for. Returns a handle that stops the server on quit — but only when t3tui started it. + * An explicit T3TUI_SERVER or T3TUI_TOKEN never spawns. + */ +export async function ensureLocalServer(): Promise { + if (process.env.T3TUI_SERVER || process.env.T3TUI_TOKEN) return null; + const existing = await localOrigin(); + if (existing && (await serverAlive(existing))) return null; + + let child: Bun.Subprocess; + try { + // Output goes to a log file: before the UI starts it is useful, after it would corrupt the screen. + const logPath = join(configDir(), "server.log"); + mkdirSync(dirname(logPath), { recursive: true }); + const log = openSync(logPath, "a"); + child = Bun.spawn([...t3Command(), "serve"], { + detached: true, + stdio: ["ignore", log, log], + // Spread explicitly: Bun.spawn can read the process's original environ, missing + // variables set at runtime (tests, wrappers that set T3CODE_HOME). + env: { ...process.env }, + }); + } catch { + return null; // no `t3` binary: fall through to the usual "no server" reconnecting state + } + + let stopped = false; + const stop = async (): Promise => { + if (stopped) return; + stopped = true; + killGroup(child, "SIGTERM"); + const exited = await Promise.race([child.exited, Bun.sleep(5_000).then(() => null)]); + if (exited === null) { + killGroup(child, "SIGKILL"); + await child.exited.catch(() => {}); + } + }; + // Backstop for exits that bypass the UI's destroy handler (list, tmux, crashes). + process.on("exit", () => { + if (!stopped) killGroup(child, "SIGKILL"); + }); + + const deadline = Date.now() + 30_000; + let origin: string | null = null; + while (Date.now() < deadline) { + origin = await localOrigin(); + if (origin && (await serverAlive(origin))) return { origin, stop }; + if (child.exitCode !== null) break; // the server died on startup + await Bun.sleep(200); + } + await stop(); + return null; +} diff --git a/test/spawnServer.test.ts b/test/spawnServer.test.ts new file mode 100644 index 0000000..053b2a9 --- /dev/null +++ b/test/spawnServer.test.ts @@ -0,0 +1,98 @@ +import { afterEach, describe, expect, test } from "bun:test"; +import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import { ensureLocalServer } from "../src/client/spawnServer.ts"; + +// A fake `t3` binary: ignores its args, serves one HTTP 200 and writes the runtime file +// the real server writes, so ensureLocalServer's probe sees it come up. +const fakeServerTs = ` + const server = Bun.serve({ port: 0, fetch: () => new Response("ok") }); + const fs = await import("node:fs"); + const dir = process.env.T3CODE_HOME + "/userdata"; + fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync(dir + "/server-runtime.json", JSON.stringify({ origin: "http://127.0.0.1:" + server.port, port: server.port })); + setInterval(() => {}, 60_000); +`; + +const saved: Record = {}; +const setEnv = (key: string, value: string | undefined) => { + if (!(key in saved)) saved[key] = process.env[key]; + if (value === undefined) delete process.env[key]; + else process.env[key] = value; +}; + +let scratch: string | null = null; +afterEach(() => { + for (const [key, value] of Object.entries(saved)) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + delete saved[key]; + } + if (scratch) rmSync(scratch, { recursive: true, force: true }); + scratch = null; +}); + +function setup(t3Bin?: string) { + scratch = mkdtempSync(join(tmpdir(), "t3tui-spawn-")); + setEnv("T3CODE_HOME", join(scratch, "t3home")); + setEnv("XDG_CONFIG_HOME", join(scratch, "xdg")); + setEnv("T3TUI_SERVER", undefined); + setEnv("T3TUI_TOKEN", undefined); + setEnv("T3TUI_T3_BIN", t3Bin); + return scratch; +} + +function fakeT3(dir: string): string { + writeFileSync(join(dir, "fake-server.ts"), fakeServerTs); + const bin = join(dir, "t3"); + writeFileSync(bin, `#!/bin/sh\nexec ${process.execPath} ${join(dir, "fake-server.ts")} "$@"\n`); + chmodSync(bin, 0o755); + return bin; +} + +describe("ensureLocalServer", () => { + test("spawns `t3 serve` when nothing answers, and stops it", async () => { + const dir = setup(); + const server = await ensureLocalServerWith(fakeT3(dir)); + expect(server).not.toBeNull(); + // The spawned server answers at its origin. + const response = await fetch(server!.origin); + expect(response.status).toBe(200); + await server!.stop(); + // After stop, the origin is dead again. + await expect(fetch(server!.origin, { signal: AbortSignal.timeout(1_000) })).rejects.toThrow(); + }); + + test("connects to the existing server when one answers, without spawning", async () => { + const dir = setup(); + // A server that is already up, with its runtime file in place. + const running = Bun.serve({ port: 0, fetch: () => new Response("ok") }); + const { mkdirSync, writeFileSync: write } = await import("node:fs"); + mkdirSync(join(process.env.T3CODE_HOME!, "userdata"), { recursive: true }); + write(join(process.env.T3CODE_HOME!, "userdata", "server-runtime.json"), JSON.stringify({ origin: `http://127.0.0.1:${running.port}`, port: running.port })); + // A t3 binary that would fail the test if spawned: it exits immediately. + const bin = join(dir, "t3"); + writeFileSync(bin, "#!/bin/sh\nexit 1\n"); + const server = await ensureLocalServerWith(bin); + expect(server).toBeNull(); + running.stop(true); + }); + + test("never spawns for an explicit T3TUI_SERVER or T3TUI_TOKEN", async () => { + setup(); + setEnv("T3TUI_SERVER", "http://127.0.0.1:1"); + expect(await ensureLocalServer()).toBeNull(); + setEnv("T3TUI_SERVER", undefined); + setEnv("T3TUI_TOKEN", "token"); + expect(await ensureLocalServer()).toBeNull(); + }); +}); + +// ensureLocalServer reads T3TUI_T3_BIN at call time via t3Command, so setting it after +// setup() is enough; this wrapper just keeps the tests readable. +async function ensureLocalServerWith(t3Bin: string) { + setEnv("T3TUI_T3_BIN", t3Bin); + return ensureLocalServer(); +}