llmtop 0.1.3 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -24,10 +24,10 @@
24
24
 
25
25
  ```bash
26
26
  npm install -g llmtop
27
- llmtop serve
27
+ llmtop start # Run in background (survives closing the terminal); llmtop stop to end
28
28
  ```
29
29
 
30
- Or run without installing: `npx llmtop serve`. Open <http://localhost:4310>.
30
+ Or run in the foreground with `llmtop serve`, or without installing via `npx llmtop serve`. Open <http://localhost:4310>.
31
31
 
32
32
  - **Local-only:** Binds `127.0.0.1` only; zero telemetry, zero background network requests (only `llmtop update` contacts npmjs when invoked), zero runtime npm dependencies.
33
33
  - **Zero setup:** Automatically reads `~/.claude/projects`, `~/.codex/sessions`, and `~/.gemini/antigravity-cli`, skipping absent tools.
@@ -90,19 +90,35 @@ Or run without installing: `npx llmtop serve`. Open <http://localhost:4310>.
90
90
  CLI and dashboard totals stay identical for the same window and filters (`--json` supported on listing commands).
91
91
 
92
92
  ```bash
93
- llmtop serve [--port n] # Dashboard at http://localhost:4310
93
+ llmtop start [--port n] # Start dashboard in background (log ~/.config/llmtop/data/serve.log)
94
+ llmtop serve [--port n] [--daemon] # Dashboard at http://localhost:4310 (--daemon detaches like start)
94
95
  llmtop stop # Stop the running dashboard server
95
96
  llmtop scan # Archive new transcript lines into usage.db
96
97
  llmtop usage [--days n | --since d --until d] [--by day|model|provider|effort|project|session|hour|tool|skill|subagent]
97
98
  [--provider name] [--project name] [--model family] [--effort level] [--json]
98
99
  llmtop prices [--json] # Verify prices.md against host cost records
99
100
  llmtop show <session>:<line> # Print one archived record
100
- llmtop update [--check] [--json] # Check npmjs or upgrade to the latest release
101
+ llmtop update [--check] [--json] [--force] # Check npmjs or upgrade to the latest release
101
102
  llmtop uninstall [--purge] [--dry-run] [--yes]
102
103
  # Stop llmtop and remove the global installation
103
104
  llmtop --help | --version
104
105
  ```
105
106
 
107
+ ## Update & Uninstall
108
+
109
+ ```bash
110
+ llmtop update --check # Check npmjs for a newer release (supports --json)
111
+ llmtop update # Upgrade the global installation to the latest release
112
+ llmtop stop # Stop a running llmtop serve process
113
+ llmtop uninstall --dry-run # Preview what uninstall will stop, remove, or keep
114
+ llmtop uninstall # Stop llmtop and remove the global package (keeps ~/.config/llmtop)
115
+ llmtop uninstall --purge # Also remove ~/.config/llmtop (config, archive, and usage.db)
116
+ ```
117
+
118
+ - **`llmtop start`** (or `llmtop serve --daemon`) detaches the dashboard from the terminal and writes logs to `~/.config/llmtop/data/serve.log` (using `systemd-run --user` on systemd Linux so closing the terminal will not stop it). Run `llmtop stop` to end it.
119
+ - **`llmtop update`** queries `registry.npmjs.org` only when invoked (never in the background), detects your global package manager (`npm`, `pnpm`, `yarn`, or `bun`), automatically stops a running background daemon (`llmtop start` / `--daemon`) before upgrading and restarts it on the new version, and warns if a foreground `llmtop serve` is running so you can restart it afterward. From a local Git checkout or `npx`, it prints manual steps unless `--force` is passed.
120
+ - **`llmtop uninstall`** stops running `llmtop serve` processes, removes the global package, and asks for confirmation in interactive terminals (pass `--yes` or `-y` in scripts). By default it keeps `~/.config/llmtop`; add `--purge` to delete local config, archive, and SQLite data. Original provider transcripts (`~/.claude`, `~/.codex`, `~/.gemini/antigravity-cli`) are never touched.
121
+
106
122
  ## Configuration
107
123
 
108
124
  Optional settings live in `~/.config/llmtop/config.json` (see [llmtop.config.example.json](https://github.com/nguyencanhtrung/llmtop/blob/main/llmtop.config.example.json)). Override paths with `XDG_CONFIG_HOME`, `LLMTOP_CONFIG`, or `LLMTOP_DATA`. Token rates come from [prices.md](https://github.com/nguyencanhtrung/llmtop/blob/main/prices.md).
package/bin/llmtop.mjs CHANGED
@@ -4,7 +4,7 @@ import { join } from "node:path";
4
4
  import { defaultConfigDir, defaultConfigPath, loadConfig, ROOT } from "../src/config.mjs";
5
5
  import { localTime } from "../src/format.mjs";
6
6
  import { pricesCommand } from "../src/prices-command.mjs";
7
- import { stopCommand, writeServerState } from "../src/process.mjs";
7
+ import { startCommand, stopCommand, writeServerState } from "../src/process.mjs";
8
8
  import { scan, scanReport } from "../src/scan.mjs";
9
9
  import { serve } from "../src/serve.mjs";
10
10
  import { show } from "../src/show.mjs";
@@ -21,7 +21,8 @@ const USAGE = `usage: llmtop <command> [options]
21
21
  usage [--days n | --since d --until d] [--by day|model|provider|effort|project|session|hour|tool|skill|subagent]
22
22
  [--provider name] [--project name] [--model family] [--effort level]
23
23
  prices the price table checked against the host's cost records
24
- serve [--port n] the built dashboard on http://localhost:<port>
24
+ serve [--port n] [--daemon] the built dashboard on http://localhost:<port>
25
+ start [--port n] start the dashboard in the background
25
26
  stop stop the running llmtop serve process
26
27
  update [--check] [--force] check npmjs or upgrade llmtop to the latest version
27
28
  uninstall [--purge] [--dry-run] [--yes]
@@ -46,6 +47,14 @@ function loadConfigOrDefault() {
46
47
  }
47
48
  }
48
49
 
50
+ function parsePort(options, config) {
51
+ const port = options.port === undefined ? config.port : Number(options.port);
52
+ if (!Number.isInteger(port) || port < 0 || port > 65535) {
53
+ throw new UsageError(`--port needs a port number, got ${options.port}`);
54
+ }
55
+ return port;
56
+ }
57
+
49
58
  const COMMANDS = {
50
59
  async scan({ config, out }) {
51
60
  const t = await scan(config);
@@ -57,11 +66,22 @@ const COMMANDS = {
57
66
  },
58
67
  usage: usageCommand,
59
68
  async serve({ config, options, out }) {
60
- const port = options.port === undefined ? config.port : Number(options.port);
61
- if (!Number.isInteger(port) || port < 0 || port > 65535) throw new UsageError(`--port needs a port number, got ${options.port}`);
69
+ const port = parsePort(options, config);
70
+ if (options.daemon) {
71
+ return startCommand({ config, options: { ...options, port }, out });
72
+ }
73
+ if (process.env.LLMTOP_DAEMON === "1") {
74
+ process.on("SIGHUP", () => {});
75
+ }
62
76
  const at = localTime(config.timeZone);
63
77
  const server = await serve(config, { port, onScan: (t) => reportScan(t, out, `${at(new Date().toISOString())} `) });
64
- const cleanup = writeServerState(config, { pid: process.pid, port: server.address().port, version: VERSION });
78
+ const cleanup = writeServerState(config, {
79
+ pid: process.pid,
80
+ port: server.address().port,
81
+ version: VERSION,
82
+ token: process.env.LLMTOP_DAEMON_TOKEN,
83
+ daemon: process.env.LLMTOP_DAEMON === "1",
84
+ });
65
85
  server.once("close", cleanup);
66
86
  let closing = false;
67
87
  const shutdown = () => {
@@ -75,6 +95,10 @@ const COMMANDS = {
75
95
  process.once("SIGTERM", shutdown);
76
96
  out.write(`dashboard at http://localhost:${server.address().port}: its Refresh button scans again, Ctrl+C to stop\n`);
77
97
  },
98
+ async start({ config, options, out }) {
99
+ const port = parsePort(options, config);
100
+ return startCommand({ config, options: { ...options, port }, out });
101
+ },
78
102
  prices: pricesCommand,
79
103
  stop: stopCommand,
80
104
  update: updateCommand,
@@ -82,7 +106,7 @@ const COMMANDS = {
82
106
  };
83
107
 
84
108
  // Options are --name value or --flag; FLAGS lists the ones without a value.
85
- const FLAGS = new Set(["json", "check", "force", "purge", "dry-run", "yes"]);
109
+ const FLAGS = new Set(["json", "check", "force", "purge", "dry-run", "yes", "daemon"]);
86
110
  const LENIENT_CONFIG_COMMANDS = new Set(["stop", "update", "uninstall"]);
87
111
  function parseArgs(argv) {
88
112
  const positional = [];
@@ -93,6 +117,10 @@ function parseArgs(argv) {
93
117
  options.yes = true;
94
118
  continue;
95
119
  }
120
+ if (arg === "-d") {
121
+ options.daemon = true;
122
+ continue;
123
+ }
96
124
  if (!arg.startsWith("--")) {
97
125
  positional.push(arg);
98
126
  continue;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "llmtop",
3
- "version": "0.1.3",
3
+ "version": "0.1.4",
4
4
  "type": "module",
5
5
  "description": "Local usage and cost analytics dashboard and CLI for Claude Code, Codex and Antigravity",
6
6
  "author": "Trung Nguyen",
package/src/process.mjs CHANGED
@@ -1,18 +1,24 @@
1
- import { spawnSync } from "node:child_process";
2
- import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
3
- import { join } from "node:path";
4
- import { ROOT } from "./config.mjs";
1
+ import { spawn, spawnSync } from "node:child_process";
2
+ import { closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
3
+ import { join, resolve } from "node:path";
4
+ import { defaultConfigDir, ROOT } from "./config.mjs";
5
5
 
6
6
  export function serverStatePath(config) {
7
7
  return join(config.data, "serve.json");
8
8
  }
9
9
 
10
+ export function serverLogPath(config) {
11
+ return join(config.data, "serve.log");
12
+ }
13
+
10
14
  // Writes serve.json atomically and returns a cleanup callback that removes it only if the PID still matches.
11
- export function writeServerState(config, { pid = process.pid, port, version }) {
15
+ export function writeServerState(config, { pid = process.pid, port, version, token, daemon = false }) {
12
16
  const path = serverStatePath(config);
13
17
  mkdirSync(config.data, { recursive: true });
14
18
  const tmp = join(config.data, `.serve.${pid}.${process.hrtime.bigint()}.tmp`);
15
- const payload = JSON.stringify({ pid, port, startedAt: new Date().toISOString(), version }, null, 2);
19
+ const body = { pid, port, startedAt: new Date().toISOString(), version, daemon: Boolean(daemon) };
20
+ if (token !== undefined) body.token = token;
21
+ const payload = JSON.stringify(body, null, 2);
16
22
  writeFileSync(tmp, `${payload}\n`);
17
23
  renameSync(tmp, path);
18
24
  return () => {
@@ -88,16 +94,44 @@ function parsePortFromCommand(command) {
88
94
  return match ? Number(match[1]) : null;
89
95
  }
90
96
 
97
+ function readProcEnv(pid, readFile = readFileSync) {
98
+ try {
99
+ const raw = readFile(`/proc/${pid}/environ`, "utf8");
100
+ const env = {};
101
+ for (const entry of raw.split("\0")) {
102
+ const idx = entry.indexOf("=");
103
+ if (idx > 0) env[entry.slice(0, idx)] = entry.slice(idx + 1);
104
+ }
105
+ return env;
106
+ } catch {
107
+ return null;
108
+ }
109
+ }
110
+
111
+ function belongsToConfig(pid, config, env, readFile) {
112
+ const procEnv = readProcEnv(pid, readFile);
113
+ if (!procEnv) return true;
114
+ if (procEnv.LLMTOP_DATA && resolve(procEnv.LLMTOP_DATA) !== resolve(config.data)) return false;
115
+ if (procEnv.LLMTOP_CONFIG && config.configPath && resolve(procEnv.LLMTOP_CONFIG) !== resolve(config.configPath)) return false;
116
+ if (procEnv.XDG_CONFIG_HOME !== env.XDG_CONFIG_HOME) return false;
117
+ return true;
118
+ }
119
+
91
120
  export function findRunningServers(config, deps = {}) {
92
121
  const {
93
- listProcesses = listOsProcesses,
122
+ listProcesses,
94
123
  isAlive = isPidAlive,
95
124
  selfPid = process.pid,
96
125
  root = ROOT,
126
+ env = process.env,
97
127
  exists = existsSync,
98
128
  readFile = readFileSync,
99
129
  } = deps;
100
- const osList = listProcesses();
130
+ const defaultDataDir = resolve(join(defaultConfigDir(env), "data"));
131
+ const isDefaultData = resolve(config.data) === defaultDataDir;
132
+ const isRepoData = resolve(config.data) === resolve(join(root, "data"));
133
+ const scanProcesses = deps.includeProcessScan ?? (Boolean(listProcesses) || isDefaultData);
134
+ const osList = (listProcesses ?? listOsProcesses)();
101
135
  const osByPid = new Map(osList.map((p) => [p.pid, p]));
102
136
  const byPid = new Map();
103
137
  let staleState = false;
@@ -110,7 +144,7 @@ export function findRunningServers(config, deps = {}) {
110
144
  const osEntry = osByPid.get(state.pid);
111
145
  const matchesOs = osList.length === 0 || (osEntry && isLlmtopServeCommand(osEntry.command));
112
146
  if (isAlive(state.pid) && matchesOs) {
113
- byPid.set(state.pid, { pid: state.pid, port: state.port ?? null, source: "state" });
147
+ byPid.set(state.pid, { pid: state.pid, port: state.port ?? null, source: "state", daemon: Boolean(state.daemon) });
114
148
  } else {
115
149
  staleState = true;
116
150
  }
@@ -121,7 +155,7 @@ export function findRunningServers(config, deps = {}) {
121
155
  }
122
156
 
123
157
  const pidFile = join(root, "data", "serve.pid");
124
- if (exists(pidFile)) {
158
+ if (isRepoData && exists(pidFile)) {
125
159
  try {
126
160
  const pid = Number(readFile(pidFile, "utf8").trim());
127
161
  if (Number.isInteger(pid) && pid > 0 && pid !== selfPid && isAlive(pid)) {
@@ -129,7 +163,7 @@ export function findRunningServers(config, deps = {}) {
129
163
  if (osEntry && isLlmtopServeCommand(osEntry.command)) {
130
164
  const existing = byPid.get(pid);
131
165
  if (existing) existing.pidFile = pidFile;
132
- else byPid.set(pid, { pid, port: parsePortFromCommand(osEntry.command), source: "pidfile", pidFile });
166
+ else byPid.set(pid, { pid, port: parsePortFromCommand(osEntry.command), source: "pidfile", pidFile, daemon: false });
133
167
  }
134
168
  }
135
169
  } catch {
@@ -137,9 +171,12 @@ export function findRunningServers(config, deps = {}) {
137
171
  }
138
172
  }
139
173
 
140
- for (const proc of osList) {
141
- if (proc.pid === selfPid || byPid.has(proc.pid) || !isLlmtopServeCommand(proc.command)) continue;
142
- byPid.set(proc.pid, { pid: proc.pid, port: parsePortFromCommand(proc.command), source: "process" });
174
+ if (scanProcesses) {
175
+ for (const proc of osList) {
176
+ if (proc.pid === selfPid || byPid.has(proc.pid) || !isLlmtopServeCommand(proc.command)) continue;
177
+ if (!listProcesses && !belongsToConfig(proc.pid, config, env, readFile)) continue;
178
+ byPid.set(proc.pid, { pid: proc.pid, port: parsePortFromCommand(proc.command), source: "process", daemon: false });
179
+ }
143
180
  }
144
181
 
145
182
  return { servers: [...byPid.values()].sort((a, b) => a.pid - b.pid), staleState };
@@ -235,3 +272,157 @@ export async function stopCommand({ config, out, err = process.stderr, deps = {}
235
272
  }
236
273
  return 0;
237
274
  }
275
+
276
+ const FORWARDED_DAEMON_ENV = [
277
+ "HOME",
278
+ "PATH",
279
+ "USER",
280
+ "TZ",
281
+ "XDG_CONFIG_HOME",
282
+ "LLMTOP_CONFIG",
283
+ "LLMTOP_DATA",
284
+ "NODE_OPTIONS",
285
+ ];
286
+
287
+ export function canUseSystemdUser({ platform = process.platform, spawn: spawnCmd = spawnSync, env = process.env } = {}) {
288
+ if (platform !== "linux" || env.LLMTOP_NO_SYSTEMD === "1") return false;
289
+ try {
290
+ const version = spawnCmd("systemd-run", ["--version"], { encoding: "utf8", stdio: "pipe" });
291
+ if (version.status !== 0) return false;
292
+ const mgr = spawnCmd("systemctl", ["--user", "show-environment"], { encoding: "utf8", stdio: "pipe" });
293
+ return mgr.status === 0;
294
+ } catch {
295
+ return false;
296
+ }
297
+ }
298
+
299
+ function readAppendedLog(logPath, startOffset, exists, readFile) {
300
+ if (!exists(logPath)) return "";
301
+ try {
302
+ const buf = readFile(logPath);
303
+ return buf.subarray(startOffset).toString("utf8").trim();
304
+ } catch {
305
+ return "";
306
+ }
307
+ }
308
+
309
+ export async function startBackgroundServer(config, { port, deps = {} } = {}) {
310
+ const {
311
+ env = process.env,
312
+ platform = process.platform,
313
+ root = ROOT,
314
+ binPath = join(ROOT, "bin", "llmtop.mjs"),
315
+ execPath = process.execPath,
316
+ spawn: spawnChild = spawn,
317
+ spawnSync: spawnCmd = spawnSync,
318
+ sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
319
+ timeoutMs = 5000,
320
+ isAlive = isPidAlive,
321
+ exists = existsSync,
322
+ readFile = readFileSync,
323
+ stat = statSync,
324
+ mkdir = mkdirSync,
325
+ unlink = unlinkSync,
326
+ open = openSync,
327
+ close = closeSync,
328
+ canUseSystemd = canUseSystemdUser,
329
+ } = deps;
330
+
331
+ const { servers, staleState } = findRunningServers(config, { ...deps, root, isAlive, exists, readFile });
332
+ if (servers.length > 0) {
333
+ return { ok: false, alreadyRunning: true, server: servers[0] };
334
+ }
335
+ if (staleState) {
336
+ try {
337
+ unlink(serverStatePath(config));
338
+ } catch {
339
+ // Ignore already-deleted stale state file.
340
+ }
341
+ }
342
+
343
+ mkdir(config.data, { recursive: true });
344
+ const logPath = serverLogPath(config);
345
+ const startOffset = exists(logPath) ? stat(logPath).size : 0;
346
+ const token = `${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
347
+ const childArgs = [binPath, "serve", ...(port !== undefined ? ["--port", String(port)] : [])];
348
+
349
+ let mode = null;
350
+ let unit = null;
351
+ let child = null;
352
+
353
+ if (canUseSystemd({ platform, spawn: spawnCmd, env })) {
354
+ unit = `llmtop-serve-${Date.now()}-${process.pid}`;
355
+ const setenvArgs = [];
356
+ for (const key of FORWARDED_DAEMON_ENV) {
357
+ if (env[key] !== undefined) setenvArgs.push(`--setenv=${key}=${env[key]}`);
358
+ }
359
+ setenvArgs.push("--setenv=LLMTOP_DAEMON=1", `--setenv=LLMTOP_DAEMON_TOKEN=${token}`);
360
+ const systemdArgs = [
361
+ "--user",
362
+ "--collect",
363
+ "--no-block",
364
+ `--unit=${unit}`,
365
+ "--description=llmtop local dashboard",
366
+ `--property=WorkingDirectory=${config.data}`,
367
+ `--property=StandardOutput=append:${logPath}`,
368
+ `--property=StandardError=append:${logPath}`,
369
+ ...setenvArgs,
370
+ execPath,
371
+ ...childArgs,
372
+ ];
373
+ const res = spawnCmd("systemd-run", systemdArgs, { encoding: "utf8", stdio: "pipe" });
374
+ if (res.status === 0) mode = "systemd";
375
+ else unit = null;
376
+ }
377
+
378
+ if (!mode) {
379
+ const logFd = open(logPath, "a");
380
+ try {
381
+ child = spawnChild(execPath, childArgs, {
382
+ detached: true,
383
+ stdio: ["ignore", logFd, logFd],
384
+ env: { ...env, LLMTOP_DAEMON: "1", LLMTOP_DAEMON_TOKEN: token },
385
+ });
386
+ } finally {
387
+ close(logFd);
388
+ }
389
+ child.unref();
390
+ mode = "detached";
391
+ }
392
+
393
+ const deadline = Date.now() + timeoutMs;
394
+ while (Date.now() < deadline) {
395
+ const state = readServerState(config, { exists, readFile });
396
+ if (state && state.token === token && isAlive(state.pid)) {
397
+ return { ok: true, pid: state.pid, port: state.port, logPath, mode, unit };
398
+ }
399
+ if (mode === "detached" && child?.exitCode !== null) break;
400
+ if (mode === "systemd") {
401
+ const appended = readAppendedLog(logPath, startOffset, exists, readFile);
402
+ if (/^error:/m.test(appended)) break;
403
+ }
404
+ await sleep(50);
405
+ }
406
+
407
+ const appended = readAppendedLog(logPath, startOffset, exists, readFile);
408
+ return {
409
+ ok: false,
410
+ error: appended || "timed out waiting for llmtop serve to start",
411
+ logPath,
412
+ };
413
+ }
414
+
415
+ export async function startCommand({ config, options = {}, out, err = process.stderr, deps = {} }) {
416
+ const res = await startBackgroundServer(config, { port: options.port, deps });
417
+ if (res.alreadyRunning) {
418
+ const where = res.server.port ? `, http://localhost:${res.server.port}` : "";
419
+ err.write(`llmtop serve is already running (pid ${res.server.pid}${where}); run \`llmtop stop\` first\n`);
420
+ return 1;
421
+ }
422
+ if (!res.ok) {
423
+ err.write(`${res.error}\n`);
424
+ return 1;
425
+ }
426
+ out.write(`dashboard at http://localhost:${res.port} in the background (pid ${res.pid}, log ${res.logPath}); run \`llmtop stop\` to stop\n`);
427
+ return 0;
428
+ }
package/src/update.mjs CHANGED
@@ -1,8 +1,9 @@
1
+ import { spawnSync } from "node:child_process";
1
2
  import { readFileSync } from "node:fs";
2
3
  import { join } from "node:path";
3
4
  import { ROOT } from "./config.mjs";
4
5
  import { detectInstallMode, runPackageManager } from "./install.mjs";
5
- import { findRunningServers } from "./process.mjs";
6
+ import { findRunningServers, stopRunningServers } from "./process.mjs";
6
7
 
7
8
  const VERSION = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8")).version;
8
9
 
@@ -80,6 +81,20 @@ export async function fetchLatestVersion({
80
81
  return data.version.trim();
81
82
  }
82
83
 
84
+ export function restartInstalledDaemon({ port, env = process.env, platform = process.platform, spawn = spawnSync } = {}) {
85
+ const args = ["start", ...(port ? ["--port", String(port)] : [])];
86
+ let res = spawn("llmtop", args, { encoding: "utf8", stdio: "pipe", env, shell: platform === "win32" });
87
+ if (res.error?.code === "ENOENT") {
88
+ res = spawn(process.execPath, [join(ROOT, "bin", "llmtop.mjs"), ...args], { encoding: "utf8", stdio: "pipe", env });
89
+ }
90
+ return {
91
+ ok: !res.error && res.status === 0,
92
+ stdout: res.stdout ?? "",
93
+ stderr: res.stderr ?? "",
94
+ error: res.error?.message ?? "",
95
+ };
96
+ }
97
+
83
98
  export async function updateCommand({ config, options = {}, out, err = process.stderr, deps = {} }) {
84
99
  const current = deps.currentVersion ?? VERSION;
85
100
  const env = deps.env ?? process.env;
@@ -120,6 +135,27 @@ export async function updateCommand({ config, options = {}, out, err = process.s
120
135
  }
121
136
  }
122
137
 
138
+ const findServers = deps.findRunningServers ?? findRunningServers;
139
+ const stopServers = deps.stopRunningServers ?? stopRunningServers;
140
+ const restartDaemon = deps.restartDaemon ?? restartInstalledDaemon;
141
+
142
+ const before = findServers(config);
143
+ const daemons = before.servers.filter((s) => s.daemon);
144
+ let restartPort;
145
+
146
+ if (daemons.length > 0) {
147
+ restartPort = daemons[0].port;
148
+ const stopped = await stopServers(config);
149
+ if (stopped.failed.length > 0) {
150
+ for (const f of stopped.failed) {
151
+ err.write(`error: could not stop background llmtop serve (pid ${f.pid}) before upgrade: ${f.error}\n`);
152
+ }
153
+ return 1;
154
+ }
155
+ const details = stopped.stopped.map((s) => `pid ${s.pid}`).join(", ");
156
+ out.write(`stopped background llmtop serve before upgrade (${details})\n`);
157
+ }
158
+
123
159
  const pm = install.packageManager || "npm";
124
160
  const res = (deps.runPackageManager ?? runPackageManager)(pm, "install", `llmtop@${latest}`);
125
161
  if (!res.ok) {
@@ -127,14 +163,32 @@ export async function updateCommand({ config, options = {}, out, err = process.s
127
163
  if (res.permissionDenied) {
128
164
  err.write(`hint: try running \`sudo ${res.command}\`\n`);
129
165
  }
166
+ if (daemons.length > 0) {
167
+ const restored = restartDaemon({ port: restartPort, env });
168
+ if (restored.ok) {
169
+ out.write(`${restored.stdout.trim() || "restarted previous background llmtop serve"}\n`);
170
+ } else {
171
+ err.write(`warning: failed to restore background server: ${restored.stderr.trim() || restored.error}; run \`llmtop start\` manually\n`);
172
+ }
173
+ }
130
174
  return 1;
131
175
  }
132
176
 
133
177
  out.write(`updated llmtop ${current} -> ${latest}\n`);
134
- const { servers } = (deps.findRunningServers ?? findRunningServers)(config);
135
- if (servers.length > 0) {
136
- const details = servers.map((s) => `pid ${s.pid}${s.port ? ` on port ${s.port}` : ""}`).join(", ");
137
- out.write(`note: llmtop serve is still running (${details}); run \`llmtop stop\` and \`llmtop serve\` to use ${latest}.\n`);
178
+ if (daemons.length > 0) {
179
+ const restarted = restartDaemon({ port: restartPort, env });
180
+ if (restarted.ok) {
181
+ out.write(`${restarted.stdout.trim() || "restarted background llmtop serve"}\n`);
182
+ } else {
183
+ err.write(`warning: updated to ${latest} but failed to restart background server: ${restarted.stderr.trim() || restarted.error}; run \`llmtop start\` manually\n`);
184
+ return 1;
185
+ }
186
+ } else {
187
+ const { servers } = findServers(config);
188
+ if (servers.length > 0) {
189
+ const details = servers.map((s) => `pid ${s.pid}${s.port ? ` on port ${s.port}` : ""}`).join(", ");
190
+ out.write(`note: llmtop serve is still running (${details}); run \`llmtop stop\` and \`llmtop start\` (or \`llmtop serve\`) to use ${latest}.\n`);
191
+ }
138
192
  }
139
193
  return 0;
140
194
  }