coxpit 3.2.2 → 3.4.0

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
@@ -64,7 +64,7 @@ Your keys and login never touch coxpit's config or database.
64
64
  | env | default | what |
65
65
  |---|---|---|
66
66
  | `COXPIT_HOST` / `COXPIT_PORT` | `127.0.0.1` / `8210` | daemon bind |
67
- | `COXPIT_DB` | `./coxpit.db` | SQLite (libSQL) file |
67
+ | `COXPIT_DB` | `~/.coxpit/coxpit.db` | SQLite (libSQL) file (a legacy `./coxpit.db` in the cwd is still honored) |
68
68
  | `COXPIT_AUTH_PASS` / `COXPIT_AUTH_USER` | — / `admin` | basic auth (empty pass = open; set it) |
69
69
  | `COXPIT_AUTH_DISABLED` | — | `1` disables auth (local dev only) |
70
70
  | `COXPIT_SSH_KEY` | — | private key for remote machines (else ssh defaults/agent) |
@@ -75,6 +75,16 @@ Your keys and login never touch coxpit's config or database.
75
75
 
76
76
  Running on the open internet? Put it behind your own front door (Tailscale, Cloudflare Access, a reverse proxy with TLS) and keep basic auth on — it exposes shells.
77
77
 
78
+ ## Platform support
79
+
80
+ | platform | daemon | agent runs |
81
+ |---|---|---|
82
+ | macOS / Linux | ✅ first-class | ✅ |
83
+ | Windows (WSL2) | ✅ run the daemon inside WSL | ✅ |
84
+ | Windows (native) | ⚠️ board + remote machines only | ❌ needs a POSIX shell + tmux |
85
+
86
+ On Windows, install the daemon inside WSL2 (`npm i -g coxpit`) — WSL2 forwards `localhost`, so the Windows desktop app detects the WSL daemon and attaches to it automatically. A native Windows daemon still serves the board and can drive **remote** (ssh) machines, but the local machine will fail its readiness checks (no tmux).
87
+
78
88
  ## Architecture
79
89
 
80
90
  ```
@@ -87,6 +97,8 @@ machines — git worktrees · tmux sessions · agent CLIs
87
97
 
88
98
  One daemon, one SQLite file, zero external services. Machines are reached over SSH; the local machine is just `sh`.
89
99
 
100
+ **One daemon per machine.** Every install method shares `~/.coxpit/` — the daemon takes a lock there (`daemon.lock.json`) and refuses to start if another daemon already owns the database (running two would corrupt each other's live runs). The desktop app checks for a running daemon first and attaches to it (prompting for its basic auth if set); it only spawns its own embedded daemon when none is running. So npm CLI, launchd/systemd service, and the desktop app all see the same machines, tasks, and run history.
101
+
90
102
  ## Status
91
103
 
92
104
  `v3.0` — fleet, compare/merge, terminal, Design Mode, run destinations (merge · export · PR), swarm (plan fan-out + integrate with conflict-resolving agents), AI review, and sessions (work/ask + notifications) — all shipped and e2e-tested. Roadmap: ROADMAP.md.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "coxpit",
3
- "version": "3.2.2",
3
+ "version": "3.4.0",
4
4
  "description": "Self-hosted cockpit for running a fleet of AI coding agents across your own machines — parallel worktree runs, live board, compare & merge, web terminal, design capture.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/board.ts CHANGED
@@ -37,6 +37,9 @@ export const BOARD_HTML = /* html */ `<!doctype html>
37
37
  .brand{display:flex;align-items:baseline;gap:9px;font-family:var(--mono)}
38
38
  .brand .mark{color:var(--brand);font-size:15px;font-weight:700;letter-spacing:.01em}
39
39
  .brand .sub{color:var(--faint);font-size:11px;text-transform:uppercase;letter-spacing:.14em}
40
+ .daemon-badge{font-family:var(--mono);font-size:10.5px;color:var(--faint);padding:3px 9px;
41
+ border:1px solid var(--line);border-radius:999px;background:var(--surface);cursor:default}
42
+ .daemon-badge b{color:var(--muted);font-weight:500}
40
43
  .ws{display:flex;align-items:center;gap:7px;font-family:var(--mono);font-size:11px;color:var(--muted);
41
44
  padding:4px 10px;border:1px solid var(--line);border-radius:999px;background:var(--surface)}
42
45
  .dot{width:7px;height:7px;border-radius:50%;background:var(--s-failed);transition:background .3s}
@@ -155,6 +158,7 @@ export const BOARD_HTML = /* html */ `<!doctype html>
155
158
  @media (prefers-reduced-motion:reduce){.chip.running i{animation:none}.card:hover{transform:none}}
156
159
  .meta{display:flex;gap:16px;padding:0 14px 10px;font-family:var(--mono);font-size:11px;color:var(--faint)}
157
160
  .meta b{color:var(--muted);font-weight:500;font-variant-numeric:tabular-nums}
161
+ .meta .resumable{color:var(--brand);opacity:.75}
158
162
  .log{border-top:1px solid var(--line);background:#0e1118;padding:10px 14px;font-family:var(--mono);
159
163
  font-size:11px;height:150px;overflow:auto;display:flex;flex-direction:column;gap:4px}
160
164
  .ev{display:flex;gap:9px;align-items:baseline;min-width:0}
@@ -302,6 +306,7 @@ export const BOARD_HTML = /* html */ `<!doctype html>
302
306
  <body>
303
307
  <header>
304
308
  <div class="brand"><span class="mark">coxpit</span><span class="sub">fleet console</span></div>
309
+ <span class="daemon-badge" id="daemonBadge" style="display:none"></span>
305
310
  <div class="ws"><span class="dot" id="wsdot"></span><span id="wstext">connecting</span></div>
306
311
  <button class="btn-ghost sm" id="bell" title="notify when a run settles">🔕</button>
307
312
  <div class="machines" id="machines"></div>
@@ -761,6 +766,8 @@ function cardHTML(r){
761
766
  + '<div class="meta"><span>branch <b>'+esc(r.branch||'—')+'</b></span>'
762
767
  + '<span>files <b>'+(r.filesChanged??0)+'</b></span>'
763
768
  + '<span>'+esc(r.agent||'')+'</span>'
769
+ + (r.sessionId && ['done','failed','stopped'].includes(r.status)
770
+ ? '<span class="resumable" title="agent session preserved — open the run and Send a next instruction to continue">↻ resumable</span>' : '')
764
771
  + (r.prUrl ? '<a href="'+esc(r.prUrl)+'" target="_blank" rel="noopener" style="margin-left:auto">PR ↗</a>' : '')
765
772
  + '</div>'
766
773
  + '<div class="log">'+evs+'</div></div>';
@@ -781,6 +788,14 @@ async function hydrate(){
781
788
  (r.tasks||[]).forEach(t => tasks.set(t.id, t));
782
789
  runs.clear();
783
790
  (r.runs||[]).forEach(rn => runs.set(rn.id, { ...rn, events: rn.events||[] }));
791
+ if (r.daemon) {
792
+ const d = r.daemon;
793
+ const db = String(d.dbPath||'').replace(/^\\/(?:Users|home)\\/[^/]+/, '~');
794
+ const el = $('daemonBadge');
795
+ el.innerHTML = 'daemon <b>v'+esc(String(d.version||'?'))+'</b> · :'+esc(String(d.port||'?'));
796
+ el.title = 'pid '+d.pid+' · db '+db;
797
+ el.style.display = '';
798
+ }
784
799
  paintSidebar(); render();
785
800
  }
786
801
  function paintSidebar(){
package/src/config.ts CHANGED
@@ -1,4 +1,7 @@
1
1
  import 'dotenv/config';
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
2
5
 
3
6
  // GUI 앱(Finder/데스크톱)에서 뜨면 PATH 가 최소(/usr/bin:/bin...)라 brew 로 설치한
4
7
  // 도구(claude·tmux·git)를 못 찾는다 — 표준 설치 경로를 부팅 시 1회 보강한다.
@@ -24,13 +27,40 @@ import 'dotenv/config';
24
27
  if (process.env.LC_ALL && !/utf-?8/i.test(process.env.LC_ALL)) delete process.env.LC_ALL;
25
28
  }
26
29
 
30
+ // 기본 DB 경로 — npm/dmg 어느 설치든 같은 상태를 보도록 ~/.coxpit 로 통일한다.
31
+ // 구버전(cwd 상대 ./coxpit.db)로 쌓아온 사용자는 그 파일이 존재하는 한 그대로 존중.
32
+ function defaultDbPath(): string {
33
+ const legacy = path.resolve('./coxpit.db');
34
+ if (fs.existsSync(legacy)) {
35
+ console.log(`[coxpit] using legacy database at ${legacy} (move it to ~/.coxpit/coxpit.db to adopt the shared default)`);
36
+ return legacy;
37
+ }
38
+ const dir = path.join(os.homedir(), '.coxpit');
39
+ fs.mkdirSync(dir, { recursive: true });
40
+ return path.join(dir, 'coxpit.db');
41
+ }
42
+
43
+ const dbPath = process.env.COXPIT_DB || defaultDbPath();
44
+
45
+ // 버전 SSOT = package.json (하드코딩 문자열 이중화 방지)
46
+ const pkgVersion: string = (() => {
47
+ try {
48
+ return JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version ?? '0.0.0';
49
+ } catch {
50
+ return '0.0.0';
51
+ }
52
+ })();
53
+
27
54
  /** 런타임 설정. 시크릿은 전부 env 주입(번들 0). */
28
55
  export const config = {
56
+ version: pkgVersion,
29
57
  // UTF-8 보장된 로케일 — PTY/원격 셸에 명시 전달용
30
58
  lang: process.env.LANG!,
31
59
  host: process.env.COXPIT_HOST ?? '127.0.0.1',
32
60
  port: Number(process.env.COXPIT_PORT ?? 8210),
33
- dbPath: process.env.COXPIT_DB ?? './coxpit.db',
61
+ dbPath,
62
+ // 단일 데몬 락 파일 — DB 와 같은 폴더(그 DB 를 지키는 락이므로)
63
+ lockPath: path.join(path.dirname(path.resolve(dbPath)), 'daemon.lock.json'),
34
64
  // 원격 머신 SSH 개인키 경로(선택). 없으면 ssh 기본 키/에이전트 사용.
35
65
  sshKey: process.env.COXPIT_SSH_KEY ?? '',
36
66
  // run 정착 시 POST 할 웹훅(선택) — 텔레그램 브릿지 등 사용자 연결용.
package/src/index.ts CHANGED
@@ -1,9 +1,23 @@
1
1
  import { config } from './config';
2
2
  import { db, ensureSchema } from './db';
3
3
  import { machines } from './db/schema';
4
+ import { acquireDaemonLock } from './lock';
4
5
  import { reconcileOrphanRuns } from './orchestrator';
5
6
  import { buildServer } from './server';
6
7
 
8
+ // Windows 네이티브는 에이전트 실행 계층(sh·tmux·git worktree over sh)이 성립하지 않는다.
9
+ // 보드/원격 머신 관제는 되지만 로컬 run 은 불가 — WSL 데몬을 안내한다.
10
+ if (process.platform === 'win32') {
11
+ console.warn(
12
+ '[coxpit] Windows detected: local agent runs need a POSIX shell + tmux, which Windows lacks.\n' +
13
+ '[coxpit] Run the daemon inside WSL2 (npm i -g coxpit) and connect from the browser or desktop app,\n' +
14
+ '[coxpit] or register remote (ssh) machines only — the local machine will fail readiness checks.',
15
+ );
16
+ }
17
+
18
+ // DB 를 열기 전에 단일 데몬 보장 — 이미 떠 있으면 그 URL 을 안내하고 종료.
19
+ await acquireDaemonLock();
20
+
7
21
  await ensureSchema();
8
22
 
9
23
  // 첫 실행 시 로컬 머신 시드(데몬이 도는 이 기계).
@@ -16,4 +30,12 @@ const orphans = await reconcileOrphanRuns();
16
30
  if (orphans > 0) console.log(`[coxpit] settled ${orphans} orphaned run(s) from a previous daemon instance`);
17
31
 
18
32
  const app = await buildServer();
19
- await app.listen({ host: config.host, port: config.port });
33
+ try {
34
+ await app.listen({ host: config.host, port: config.port });
35
+ } catch (e) {
36
+ if ((e as NodeJS.ErrnoException)?.code === 'EADDRINUSE') {
37
+ console.error(`[coxpit] port ${config.port} is already in use — is another daemon (or app) running? Set COXPIT_PORT to change.`);
38
+ process.exit(1);
39
+ }
40
+ throw e;
41
+ }
package/src/lock.ts ADDED
@@ -0,0 +1,74 @@
1
+ import fs from 'node:fs';
2
+ import { config } from './config';
3
+
4
+ // 단일 데몬 락 — DB 폴더의 daemon.lock.json.
5
+ // 두 데몬이 같은 DB 를 잡으면 부팅 시 reconcileOrphanRuns() 가 상대 데몬의
6
+ // 살아있는 run 을 고아로 정산해버린다. 락 + 헬스 프로브로 원천 차단한다.
7
+
8
+ interface LockInfo {
9
+ pid: number;
10
+ host: string;
11
+ port: number;
12
+ }
13
+
14
+ /** 해당 주소에 살아있는 coxpit 데몬이 있는지 확인 (/api/health 는 인증 면제). */
15
+ export async function probeCoxpit(host: string, port: number, timeoutMs = 1500): Promise<boolean> {
16
+ try {
17
+ const ac = new AbortController();
18
+ const t = setTimeout(() => ac.abort(), timeoutMs);
19
+ const res = await fetch(`http://${host === '0.0.0.0' ? '127.0.0.1' : host}:${port}/api/health`, { signal: ac.signal });
20
+ clearTimeout(t);
21
+ if (!res.ok) return false;
22
+ const body = (await res.json()) as { name?: string };
23
+ return body?.name === 'coxpit';
24
+ } catch {
25
+ return false;
26
+ }
27
+ }
28
+
29
+ export function readLock(lockPath: string): LockInfo | null {
30
+ try {
31
+ const raw = JSON.parse(fs.readFileSync(lockPath, 'utf8')) as LockInfo;
32
+ return Number.isInteger(raw?.pid) && Number.isInteger(raw?.port) ? raw : null;
33
+ } catch {
34
+ return null;
35
+ }
36
+ }
37
+
38
+ function pidAlive(pid: number): boolean {
39
+ try { process.kill(pid, 0); return true; } catch { return false; }
40
+ }
41
+
42
+ /**
43
+ * 락 획득. 이미 살아있는 데몬이 같은 DB 를 잡고 있으면 안내 후 종료.
44
+ * 죽은 프로세스가 남긴 stale 락은 치우고 진행한다.
45
+ */
46
+ export async function acquireDaemonLock(): Promise<void> {
47
+ const existing = readLock(config.lockPath);
48
+ if (existing && existing.pid !== process.pid) {
49
+ // pid 재사용 오탐을 피하려고 헬스 프로브를 진실로 삼는다.
50
+ const alive = pidAlive(existing.pid) && (await probeCoxpit(existing.host ?? '127.0.0.1', existing.port));
51
+ if (alive) {
52
+ const url = `http://${(existing.host ?? '127.0.0.1') === '0.0.0.0' ? '127.0.0.1' : existing.host}:${existing.port}/`;
53
+ console.error(
54
+ `[coxpit] another daemon already owns this database (pid ${existing.pid}, ${url}).\n` +
55
+ `[coxpit] open that URL instead, or stop it first — running two daemons on one DB corrupts live runs.`,
56
+ );
57
+ process.exit(1);
58
+ }
59
+ try { fs.unlinkSync(config.lockPath); } catch { /* gone */ }
60
+ }
61
+
62
+ fs.writeFileSync(config.lockPath, JSON.stringify({ pid: process.pid, host: config.host, port: config.port } satisfies LockInfo));
63
+
64
+ const release = () => {
65
+ try {
66
+ const cur = readLock(config.lockPath);
67
+ if (cur?.pid === process.pid) fs.unlinkSync(config.lockPath);
68
+ } catch { /* best effort */ }
69
+ };
70
+ process.on('exit', release);
71
+ for (const sig of ['SIGINT', 'SIGTERM'] as const) {
72
+ process.on(sig, () => { release(); process.exit(0); });
73
+ }
74
+ }
@@ -42,6 +42,25 @@ async function setRun(runId: number, patch: Partial<typeof agentRuns.$inferInser
42
42
  const liveChildren = new Map<number, ChildProcess>();
43
43
  const stoppedRuns = new Set<number>();
44
44
 
45
+ /**
46
+ * 원격 에이전트 kill 스크립트 — pid 파일 기준.
47
+ * $$ 가 그룹 리더가 아닐 수 있어 ps 로 실제 pgid 를 조회해 그룹째 죽인다
48
+ * (pkill -P 폴백은 직계 자식만 잡아 에이전트가 띄운 손자 프로세스가 잔존했음).
49
+ * TERM 후에도 살아 있으면 KILL 로 에스컬레이션, 끝나면 pid 파일 제거.
50
+ */
51
+ function remoteKillScript(worktreePath: string): string {
52
+ const pidFile = shq(`${worktreePath}/.coxpit-agent.pid`);
53
+ return (
54
+ `P=$(cat ${pidFile} 2>/dev/null); [ -n "$P" ] && {` +
55
+ ` PG=$(ps -o pgid= -p "$P" 2>/dev/null | tr -d ' ');` +
56
+ ` kill -TERM -"\${PG:-$P}" 2>/dev/null || { pkill -TERM -P "$P" 2>/dev/null; kill -TERM "$P" 2>/dev/null; };` +
57
+ ` sleep 2;` +
58
+ ` kill -0 "$P" 2>/dev/null && { kill -KILL -"\${PG:-$P}" 2>/dev/null || { pkill -KILL -P "$P" 2>/dev/null; kill -KILL "$P" 2>/dev/null; }; };` +
59
+ ` rm -f ${pidFile};` +
60
+ ` } ; true`
61
+ );
62
+ }
63
+
45
64
  interface RunContext {
46
65
  runId: number;
47
66
  machine: MachineTarget;
@@ -313,13 +332,8 @@ export async function stopRun(runId: number): Promise<{ ok: boolean; detail: str
313
332
  const rr = await db.select().from(agentRuns).where(eq(agentRuns.id, runId)).limit(1);
314
333
  const run = rr[0];
315
334
  if (ctx && run && ctx.machine.kind !== 'local' && ctx.machine.address !== '' && run.worktreePath) {
316
- const pidFile = shq(`${run.worktreePath}/.coxpit-agent.pid`);
317
- // 그룹 kill(-P, sshd 는 커맨드 셸을 세션리더로 띄워 성립) → 실패 시 자식(pkill -P)+본체 순.
318
- await runShellOn(
319
- ctx.machine,
320
- `P=$(cat ${pidFile} 2>/dev/null) && { kill -TERM -"$P" 2>/dev/null || { pkill -TERM -P "$P" 2>/dev/null; kill -TERM "$P" 2>/dev/null; }; } || true`,
321
- 8000,
322
- );
335
+ // pgid 조회 그룹 kill + TERM→KILL 에스컬레이션(스크립트 내 sleep 2 포함 — 타임아웃 여유).
336
+ await runShellOn(ctx.machine, remoteKillScript(run.worktreePath), 15000);
323
337
  }
324
338
 
325
339
  // 로컬(또는 ssh 채널) 프로세스 그룹 종료 — sh 손자(실제 에이전트) 포함.
@@ -749,6 +763,10 @@ export async function cleanupRun(runId: number): Promise<{ ok: boolean; detail:
749
763
  const rr = await db.select().from(agentRuns).where(eq(agentRuns.id, runId)).limit(1);
750
764
  const run = rr[0];
751
765
  if (!ctx || !run || !run.worktreePath) return { ok: false, detail: 'no worktree' };
766
+ // 원격에 잔존 에이전트가 있으면 worktree 제거 전에 죽인다(파일 잠금·좀비 방지).
767
+ if (ctx.machine.kind !== 'local' && ctx.machine.address !== '') {
768
+ await runShellOn(ctx.machine, remoteKillScript(run.worktreePath), 15000);
769
+ }
752
770
  await runShellOn(ctx.machine, `tmux kill-session -t ${shq(`=coxpit-r${runId}`)} 2>/dev/null || true`, 8000);
753
771
  const rm = await runShellOn(
754
772
  ctx.machine,
package/src/server.ts CHANGED
@@ -33,7 +33,7 @@ export async function buildServer(): Promise<FastifyInstance> {
33
33
  app.addHook('onRequest', authGate);
34
34
 
35
35
  // 무인증 헬스(외부 감시용)
36
- app.get('/api/health', async () => ({ ok: true, name: 'coxpit', version: '3.2.2' }));
36
+ app.get('/api/health', async () => ({ ok: true, name: 'coxpit', version: config.version }));
37
37
 
38
38
  // 플릿 보드(단일 페이지). 인증 게이트 적용됨.
39
39
  app.get('/', async (_req, reply) => reply.type('text/html').send(BOARD_HTML));
@@ -57,6 +57,8 @@ export async function buildServer(): Promise<FastifyInstance> {
57
57
  return {
58
58
  machines: ms, repos: rs, tasks: ts, captures: dcs,
59
59
  runs: rns.map((r) => ({ ...r, events: byRun.get(r.id) ?? [] })),
60
+ // 보드 헤더 "어느 데몬에 붙어 있나" 표시용 (인증 뒤라 dbPath 노출 가능)
61
+ daemon: { version: config.version, pid: process.pid, port: config.port, dbPath: config.dbPath },
60
62
  };
61
63
  });
62
64
 
@@ -502,7 +504,7 @@ export async function buildServer(): Promise<FastifyInstance> {
502
504
  // 라이브 스트림 좌석 — 오케스트레이터가 run/event 를 여기로 broadcast.
503
505
  app.get('/ws', { websocket: true }, (socket) => {
504
506
  addSink(socket);
505
- socket.send(JSON.stringify({ type: 'hello', name: 'coxpit-fleet', version: '3.2.2' }));
507
+ socket.send(JSON.stringify({ type: 'hello', name: 'coxpit-fleet', version: config.version }));
506
508
  socket.on('close', () => removeSink(socket));
507
509
  });
508
510