feat: Claude Code Monitor — lanes, pipelines and a merged workspace
Internal SmartGift build of a Claude Code monitoring dashboard. Lanes: a durable unit of parallel agent work, one per working directory, tracked across session restarts. Managed lanes are git worktrees the dashboard provisions and can reset or remove behind a three-check destroy guard and a counted preflight; adopted lanes are directories you already own and are never destroyable. Pipelines: a lane moves through pipeline stages. A stage the agent declares with evidence renders green; a stage inferred from the tool-event stream renders dashed amber and never counts as done. Detection is forward-only within a 30-minute window, and never writes the declared stage. Workspace: one page at /run with a lane grid, the selected lane's pipeline, and a full Claude console behind a disclosure.
This commit is contained in:
@@ -0,0 +1,126 @@
|
||||
/**
|
||||
* @file constants.ts
|
||||
* @description Shared compile-time constants for the Electron desktop shell.
|
||||
* Values here must stay aligned with `electron-builder.yml` (app ID), the
|
||||
* documented default dashboard port, and the embedded server health probe in
|
||||
* `server-host.ts`.
|
||||
*
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
/* =============================================================================
|
||||
* MODULE_GUIDE — extended in-file reference (comments only; safe to read, never executed)
|
||||
* =============================================================================
|
||||
* **Purpose:** Dashboard module consumed by the React client, MCP tools, or desktop shell depending on deployment mode.
|
||||
*
|
||||
* ## Design constraints
|
||||
* - Local-first: no telemetry leaves the machine unless the user configures webhooks.
|
||||
* - Fail-safe hooks path on the server must never block Claude Code; UI mirrors that
|
||||
* philosophy by degrading gracefully (empty states, stale badges, reconnect loops).
|
||||
* - Destructive flows stay behind explicit confirmation modals and server-side gates.
|
||||
* - Internationalization: user-visible strings belong in i18n JSON, not literals here.
|
||||
*
|
||||
* ## Remote data & SSH
|
||||
* Remote Data Sources let operators aggregate multiple machines. SSH entries describe
|
||||
* how to reach a peer dashboard; the global data scope (`dataScope.ts`) narrows every
|
||||
* scoped GET via `?sources=`. Health checks and import history surface in Settings.
|
||||
*
|
||||
* ## Observability
|
||||
* Prometheus scrapes `GET /api/metrics` (see `monitoring/`). Grafana ships four
|
||||
* provisioned boards (overview, sessions, tools, alerts). Native npm scripts and
|
||||
* Docker Compose profiles are documented in `monitoring/README.md`.
|
||||
*
|
||||
* ## Public surface
|
||||
* - `APP_NAME` — exported API; see TSDoc on the symbol for behavior.
|
||||
* - `APP_ID` — exported API; see TSDoc on the symbol for behavior.
|
||||
* - `PREFERRED_PORT` — exported API; see TSDoc on the symbol for behavior.
|
||||
* - `FALLBACK_PORT_RANGE` — exported API; see TSDoc on the symbol for behavior.
|
||||
* - `HEALTH_TIMEOUT_MS` — exported API; see TSDoc on the symbol for behavior.
|
||||
* - `DEFAULT_WINDOW` — exported API; see TSDoc on the symbol for behavior.
|
||||
*
|
||||
* ## Testing pointers
|
||||
* - Prefer colocated `__tests__` with Vitest + Testing Library for UI.
|
||||
* - Server contract changes require `npm run test:server` and OpenAPI sync.
|
||||
* - MCP edits: `npm run mcp:typecheck` and `npm run mcp:build`.
|
||||
*
|
||||
* ## Related docs
|
||||
* - `ARCHITECTURE.md` — hooks → API → SQLite → WebSocket → UI pipeline.
|
||||
* - `docs/API.md` — REST reference.
|
||||
* - `.claude/skills/file-headers/` — mandatory `@author` header policy.
|
||||
* ============================================================================= */
|
||||
/* -----------------------------------------------------------------------------
|
||||
* EXPORT CATALOG — quick index of symbols defined below (documentation only).
|
||||
* -----------------------------------------------------------------------------
|
||||
* **APP_NAME**
|
||||
* Part of this module's public contract. Downstream imports should treat
|
||||
* the signature and return type as stable unless release notes say otherwise.
|
||||
* When behavior changes, update the `@file` overview and relevant tests.
|
||||
*
|
||||
* **APP_ID**
|
||||
* Part of this module's public contract. Downstream imports should treat
|
||||
* the signature and return type as stable unless release notes say otherwise.
|
||||
* When behavior changes, update the `@file` overview and relevant tests.
|
||||
*
|
||||
* **PREFERRED_PORT**
|
||||
* Part of this module's public contract. Downstream imports should treat
|
||||
* the signature and return type as stable unless release notes say otherwise.
|
||||
* When behavior changes, update the `@file` overview and relevant tests.
|
||||
*
|
||||
* **FALLBACK_PORT_RANGE**
|
||||
* Part of this module's public contract. Downstream imports should treat
|
||||
* the signature and return type as stable unless release notes say otherwise.
|
||||
* When behavior changes, update the `@file` overview and relevant tests.
|
||||
*
|
||||
* **HEALTH_TIMEOUT_MS**
|
||||
* Part of this module's public contract. Downstream imports should treat
|
||||
* the signature and return type as stable unless release notes say otherwise.
|
||||
* When behavior changes, update the `@file` overview and relevant tests.
|
||||
*
|
||||
* **DEFAULT_WINDOW**
|
||||
* Part of this module's public contract. Downstream imports should treat
|
||||
* the signature and return type as stable unless release notes say otherwise.
|
||||
* When behavior changes, update the `@file` overview and relevant tests.
|
||||
*
|
||||
* ----------------------------------------------------------------------------- */
|
||||
|
||||
/** Human-readable product name shown in window title and About menu. */
|
||||
export const APP_NAME = "Claude Code Monitor";
|
||||
|
||||
/**
|
||||
* Application identifier. Must match `appId` in electron-builder.yml: on Windows
|
||||
* we hand it to `app.setAppUserModelId()` so toast notifications attribute to
|
||||
* the installed Start-Menu shortcut (NSIS writes the same AUMID there) instead
|
||||
* of appearing as a generic "electron.app" toast — and so taskbar windows group
|
||||
* under one icon. Ignored on macOS/Linux.
|
||||
*/
|
||||
export const APP_ID = "com.vn.smartgift.ccam.desktop";
|
||||
|
||||
/**
|
||||
* Preferred dashboard port — matches the project's documented default. Also
|
||||
* the only port `server-host.ts`'s `startEmbeddedServer` will *adopt* an
|
||||
* already-healthy server on; a server found on any other port is never
|
||||
* treated as "ours" to reuse.
|
||||
*/
|
||||
export const PREFERRED_PORT = 4820;
|
||||
|
||||
/**
|
||||
* Last-resort port scan range when `PREFERRED_PORT` and its nine immediate
|
||||
* fallbacks (4821–4829) are all taken. Set to the IANA-registered
|
||||
* dynamic/private port range (49152–65535, truncated here to 49500 — far more
|
||||
* headroom than `pickFreePort()` should ever need) so we never guess at a
|
||||
* port some other, unrelated service might be registered on.
|
||||
*/
|
||||
export const FALLBACK_PORT_RANGE = { min: 49152, max: 49500 } as const;
|
||||
|
||||
/**
|
||||
* How long `server-host.ts`'s `waitForHealthy()` polls a freshly bound port
|
||||
* for `/api/health` before giving up and surfacing an error dialog to the
|
||||
* user. 30s comfortably covers a cold start on a slow disk (SQLite file
|
||||
* creation, migrations) without leaving the user staring at a spinner
|
||||
* indefinitely if something is actually broken.
|
||||
*/
|
||||
export const HEALTH_TIMEOUT_MS = 30_000;
|
||||
|
||||
/** Default window size, used only when no `window-state.json` exists yet
|
||||
* (first launch). Persisted to `app.getPath('userData')` after that — see
|
||||
* `window.ts`'s `loadState`/`saveState`. */
|
||||
export const DEFAULT_WINDOW = { width: 1280, height: 800 } as const;
|
||||
@@ -0,0 +1,125 @@
|
||||
/**
|
||||
* @file Lightweight file logger for the desktop shell.
|
||||
*
|
||||
* Electron's main process has no console attached when launched from Finder,
|
||||
* so all diagnostics go to a per-user log file under app.getPath('logs').
|
||||
* We deliberately avoid the `electron-log` dependency — the project keeps a
|
||||
* small dependency tree and this file does the only three things we need.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
/* =============================================================================
|
||||
* MODULE_GUIDE — extended in-file reference (comments only; safe to read, never executed)
|
||||
* =============================================================================
|
||||
* **Purpose:** Dashboard module consumed by the React client, MCP tools, or desktop shell depending on deployment mode.
|
||||
*
|
||||
* ## Design constraints
|
||||
* - Local-first: no telemetry leaves the machine unless the user configures webhooks.
|
||||
* - Fail-safe hooks path on the server must never block Claude Code; UI mirrors that
|
||||
* philosophy by degrading gracefully (empty states, stale badges, reconnect loops).
|
||||
* - Destructive flows stay behind explicit confirmation modals and server-side gates.
|
||||
* - Internationalization: user-visible strings belong in i18n JSON, not literals here.
|
||||
*
|
||||
* ## Remote data & SSH
|
||||
* Remote Data Sources let operators aggregate multiple machines. SSH entries describe
|
||||
* how to reach a peer dashboard; the global data scope (`dataScope.ts`) narrows every
|
||||
* scoped GET via `?sources=`. Health checks and import history surface in Settings.
|
||||
*
|
||||
* ## Observability
|
||||
* Prometheus scrapes `GET /api/metrics` (see `monitoring/`). Grafana ships four
|
||||
* provisioned boards (overview, sessions, tools, alerts). Native npm scripts and
|
||||
* Docker Compose profiles are documented in `monitoring/README.md`.
|
||||
*
|
||||
* ## Public surface
|
||||
* - `log` — exported API; see TSDoc on the symbol for behavior.
|
||||
*
|
||||
* ## Testing pointers
|
||||
* - Prefer colocated `__tests__` with Vitest + Testing Library for UI.
|
||||
* - Server contract changes require `npm run test:server` and OpenAPI sync.
|
||||
* - MCP edits: `npm run mcp:typecheck` and `npm run mcp:build`.
|
||||
*
|
||||
* ## Related docs
|
||||
* - `ARCHITECTURE.md` — hooks → API → SQLite → WebSocket → UI pipeline.
|
||||
* - `docs/API.md` — REST reference.
|
||||
* - `.claude/skills/file-headers/` — mandatory `@author` header policy.
|
||||
* ============================================================================= */
|
||||
/* -----------------------------------------------------------------------------
|
||||
* EXPORT CATALOG — quick index of symbols defined below (documentation only).
|
||||
* -----------------------------------------------------------------------------
|
||||
* **log**
|
||||
* Part of this module's public contract. Downstream imports should treat
|
||||
* the signature and return type as stable unless release notes say otherwise.
|
||||
* When behavior changes, update the `@file` overview and relevant tests.
|
||||
*
|
||||
* ----------------------------------------------------------------------------- */
|
||||
|
||||
import { app } from "electron";
|
||||
import * as fs from "node:fs";
|
||||
import * as path from "node:path";
|
||||
|
||||
let stream: fs.WriteStream | null = null;
|
||||
let logPath = "";
|
||||
|
||||
/**
|
||||
* Lazily open the append-mode write stream to `desktop.log`, creating the
|
||||
* `app.getPath('logs')` directory if this is the first write of the process.
|
||||
* Cached in the module-level `stream` so every subsequent `write()` call
|
||||
* reuses the same file descriptor instead of re-opening the file.
|
||||
*/
|
||||
function ensureStream(): fs.WriteStream {
|
||||
if (stream) return stream;
|
||||
const dir = app.getPath("logs");
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
logPath = path.join(dir, "desktop.log");
|
||||
stream = fs.createWriteStream(logPath, { flags: "a" });
|
||||
return stream;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format one log line (ISO timestamp + level + space-joined parts) and fan it
|
||||
* out to the log file and, conditionally, to the process streams:
|
||||
* - `error` always echoes to `stderr`, so a crash is visible even without
|
||||
* `CCAM_DESKTOP_VERBOSE` (e.g. when Electron is launched from a terminal).
|
||||
* - `info`/`warn` only echo to `stdout` when `CCAM_DESKTOP_VERBOSE` is set,
|
||||
* keeping a normal launch quiet.
|
||||
* The file write is wrapped in try/catch — a logging failure (e.g. a full
|
||||
* disk) must never take down the app.
|
||||
*/
|
||||
function write(level: "info" | "warn" | "error", parts: unknown[]): void {
|
||||
const line = `${new Date().toISOString()} [${level}] ${parts
|
||||
.map((p) => (typeof p === "string" ? p : safeStringify(p)))
|
||||
.join(" ")}\n`;
|
||||
try {
|
||||
ensureStream().write(line);
|
||||
} catch {
|
||||
// Logging must never crash the app.
|
||||
}
|
||||
if (level === "error") {
|
||||
process.stderr.write(line);
|
||||
} else if (process.env.CCAM_DESKTOP_VERBOSE) {
|
||||
process.stdout.write(line);
|
||||
}
|
||||
}
|
||||
|
||||
/** `JSON.stringify` a non-string log argument, falling back to `String()` for
|
||||
* values it can't serialize (e.g. circular objects or `BigInt`). */
|
||||
function safeStringify(value: unknown): string {
|
||||
try {
|
||||
return JSON.stringify(value);
|
||||
} catch {
|
||||
return String(value);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The desktop shell's only logging surface. Electron's main process has no
|
||||
* attached console when launched from Finder/Dock, so every call here is
|
||||
* durably persisted to `desktop.log` (see `ensureStream`) in addition to the
|
||||
* conditional stdout/stderr echo described in `write`.
|
||||
*/
|
||||
export const log = {
|
||||
info: (...parts: unknown[]) => write("info", parts),
|
||||
warn: (...parts: unknown[]) => write("warn", parts),
|
||||
error: (...parts: unknown[]) => write("error", parts),
|
||||
/** Absolute path to the active log file (populated after first write). */
|
||||
path: () => logPath,
|
||||
};
|
||||
@@ -0,0 +1,163 @@
|
||||
/**
|
||||
* @file Open-at-login integration (macOS Login Items + Windows startup).
|
||||
*
|
||||
* Both platforms go through Electron's first-party `app.*LoginItemSettings`
|
||||
* API — no third-party deps, no hand-rolled plist or registry edits:
|
||||
* - macOS: wraps the modern `SMAppService` / `ServiceManagement` framework
|
||||
* (macOS 13+), so the toggle appears in System Settings → General →
|
||||
* Login Items where users expect to manage it.
|
||||
* - Windows: writes an entry under the per-user
|
||||
* `HKCU\Software\Microsoft\Windows\CurrentVersion\Run` registry key (the
|
||||
* standard startup location), which shows up in Task Manager → Startup.
|
||||
*
|
||||
* Linux has no Electron-supported equivalent, so the toggle is a no-op there.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
/* =============================================================================
|
||||
* MODULE_GUIDE — extended in-file reference (comments only; safe to read, never executed)
|
||||
* =============================================================================
|
||||
* **Purpose:** Dashboard module consumed by the React client, MCP tools, or desktop shell depending on deployment mode.
|
||||
*
|
||||
* ## Design constraints
|
||||
* - Local-first: no telemetry leaves the machine unless the user configures webhooks.
|
||||
* - Fail-safe hooks path on the server must never block Claude Code; UI mirrors that
|
||||
* philosophy by degrading gracefully (empty states, stale badges, reconnect loops).
|
||||
* - Destructive flows stay behind explicit confirmation modals and server-side gates.
|
||||
* - Internationalization: user-visible strings belong in i18n JSON, not literals here.
|
||||
*
|
||||
* ## Remote data & SSH
|
||||
* Remote Data Sources let operators aggregate multiple machines. SSH entries describe
|
||||
* how to reach a peer dashboard; the global data scope (`dataScope.ts`) narrows every
|
||||
* scoped GET via `?sources=`. Health checks and import history surface in Settings.
|
||||
*
|
||||
* ## Observability
|
||||
* Prometheus scrapes `GET /api/metrics` (see `monitoring/`). Grafana ships four
|
||||
* provisioned boards (overview, sessions, tools, alerts). Native npm scripts and
|
||||
* Docker Compose profiles are documented in `monitoring/README.md`.
|
||||
*
|
||||
* ## Public surface
|
||||
* - `isOpenAtLogin` — exported API; see TSDoc on the symbol for behavior.
|
||||
* - `setOpenAtLogin` — exported API; see TSDoc on the symbol for behavior.
|
||||
* - `toggleOpenAtLogin` — exported API; see TSDoc on the symbol for behavior.
|
||||
* - `launchedAtLogin` — exported API; see TSDoc on the symbol for behavior.
|
||||
*
|
||||
* ## Testing pointers
|
||||
* - Prefer colocated `__tests__` with Vitest + Testing Library for UI.
|
||||
* - Server contract changes require `npm run test:server` and OpenAPI sync.
|
||||
* - MCP edits: `npm run mcp:typecheck` and `npm run mcp:build`.
|
||||
*
|
||||
* ## Related docs
|
||||
* - `ARCHITECTURE.md` — hooks → API → SQLite → WebSocket → UI pipeline.
|
||||
* - `docs/API.md` — REST reference.
|
||||
* - `.claude/skills/file-headers/` — mandatory `@author` header policy.
|
||||
* ============================================================================= */
|
||||
/* -----------------------------------------------------------------------------
|
||||
* EXPORT CATALOG — quick index of symbols defined below (documentation only).
|
||||
* -----------------------------------------------------------------------------
|
||||
* **isOpenAtLogin**
|
||||
* Part of this module's public contract. Downstream imports should treat
|
||||
* the signature and return type as stable unless release notes say otherwise.
|
||||
* When behavior changes, update the `@file` overview and relevant tests.
|
||||
*
|
||||
* **setOpenAtLogin**
|
||||
* Part of this module's public contract. Downstream imports should treat
|
||||
* the signature and return type as stable unless release notes say otherwise.
|
||||
* When behavior changes, update the `@file` overview and relevant tests.
|
||||
*
|
||||
* **toggleOpenAtLogin**
|
||||
* Part of this module's public contract. Downstream imports should treat
|
||||
* the signature and return type as stable unless release notes say otherwise.
|
||||
* When behavior changes, update the `@file` overview and relevant tests.
|
||||
*
|
||||
* **launchedAtLogin**
|
||||
* Part of this module's public contract. Downstream imports should treat
|
||||
* the signature and return type as stable unless release notes say otherwise.
|
||||
* When behavior changes, update the `@file` overview and relevant tests.
|
||||
*
|
||||
* ----------------------------------------------------------------------------- */
|
||||
|
||||
import { app } from "electron";
|
||||
|
||||
/**
|
||||
* CLI flag we register the Windows startup entry with, then look for in
|
||||
* `process.argv` to recognise a login-triggered launch (Windows has no
|
||||
* `wasOpenedAtLogin`). Harmless if it ever reaches another code path.
|
||||
*/
|
||||
const WIN_LAUNCH_FLAG = "--ccam-hidden";
|
||||
|
||||
/** True on macOS and Windows — the only platforms Electron can register an
|
||||
* auto-start entry for. Every exported function below is a no-op on Linux. */
|
||||
function supported(): boolean {
|
||||
return process.platform === "darwin" || process.platform === "win32";
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the current auto-start state directly from the OS (macOS Login Items
|
||||
* or the Windows `Run` key), not from any value cached by this module — so it
|
||||
* stays correct even if the user disables the entry from outside the app
|
||||
* (e.g. macOS System Settings, or Windows Task Manager → Startup).
|
||||
*/
|
||||
export function isOpenAtLogin(): boolean {
|
||||
if (!supported()) return false;
|
||||
return app.getLoginItemSettings().openAtLogin;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enable or disable launching the app at login. Delegates entirely to
|
||||
* `app.setLoginItemSettings`, which picks the platform mechanism:
|
||||
* - **Windows** — writes/removes the per-user
|
||||
* `HKCU\Software\Microsoft\Windows\CurrentVersion\Run` entry, tagged with
|
||||
* `WIN_LAUNCH_FLAG` so a subsequent launch can be recognised as
|
||||
* login-triggered (see `launchedAtLogin`).
|
||||
* - **macOS** — registers via the modern `SMAppService` API and starts the
|
||||
* app hidden (see the `openAsHidden` comment below).
|
||||
* No-op on Linux, where Electron has no supported mechanism.
|
||||
*/
|
||||
export function setOpenAtLogin(enabled: boolean): void {
|
||||
if (!supported()) return;
|
||||
if (process.platform === "win32") {
|
||||
app.setLoginItemSettings({
|
||||
openAtLogin: enabled,
|
||||
// Tag the registry Run entry so launchedAtLogin() can tell a login-time
|
||||
// start apart from the user double-clicking the app.
|
||||
args: [WIN_LAUNCH_FLAG],
|
||||
});
|
||||
return;
|
||||
}
|
||||
app.setLoginItemSettings({
|
||||
openAtLogin: enabled,
|
||||
// Start hidden — the user just logged in, they didn't ask for a window
|
||||
// to appear. The tray icon makes the app's presence obvious. (macOS only;
|
||||
// `openAsHidden` is ignored on other platforms.)
|
||||
openAsHidden: true,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Flip the auto-start setting and return the new state. Used by both the
|
||||
* tray "Open at Login" checkbox and the application menu item — each reads
|
||||
* `isOpenAtLogin()` to render its own checked state, then calls this on click.
|
||||
*/
|
||||
export function toggleOpenAtLogin(): boolean {
|
||||
const next = !isOpenAtLogin();
|
||||
setOpenAtLogin(next);
|
||||
return next;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the current process was launched at login (as opposed to the
|
||||
* user double-clicking the app). When true, we keep the window hidden and only
|
||||
* show the tray icon.
|
||||
*
|
||||
* macOS reports this directly via `wasOpenedAtLogin`. Windows has no such flag,
|
||||
* so we detect the marker argument we registered the startup entry with.
|
||||
*/
|
||||
export function launchedAtLogin(): boolean {
|
||||
if (process.platform === "darwin") {
|
||||
return app.getLoginItemSettings().wasOpenedAtLogin;
|
||||
}
|
||||
if (process.platform === "win32") {
|
||||
return process.argv.includes(WIN_LAUNCH_FLAG);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -0,0 +1,377 @@
|
||||
/**
|
||||
* @file Electron main process entry point.
|
||||
*
|
||||
* Lifecycle:
|
||||
* 1. App ready → start (or adopt) the embedded Express server.
|
||||
* 2. Build the application menu + system tray.
|
||||
* 3. Open the dashboard window (skipped when launched at login).
|
||||
* 4. On `window-all-closed`: keep the app running (tray-only mode).
|
||||
* 5. On `before-quit`: gracefully stop the server if we own it.
|
||||
*
|
||||
* Single-instance is enforced on every platform via `requestSingleInstanceLock`
|
||||
* so double-launching (a second Dock click, or the Windows Start-Menu shortcut)
|
||||
* just focuses the existing window instead of spawning a second tray + server.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
/* =============================================================================
|
||||
* MODULE_GUIDE — extended in-file reference (comments only; safe to read, never executed)
|
||||
* =============================================================================
|
||||
* **Purpose:** Dashboard module consumed by the React client, MCP tools, or desktop shell depending on deployment mode.
|
||||
*
|
||||
* ## Design constraints
|
||||
* - Local-first: no telemetry leaves the machine unless the user configures webhooks.
|
||||
* - Fail-safe hooks path on the server must never block Claude Code; UI mirrors that
|
||||
* philosophy by degrading gracefully (empty states, stale badges, reconnect loops).
|
||||
* - Destructive flows stay behind explicit confirmation modals and server-side gates.
|
||||
* - Internationalization: user-visible strings belong in i18n JSON, not literals here.
|
||||
*
|
||||
* ## Remote data & SSH
|
||||
* Remote Data Sources let operators aggregate multiple machines. SSH entries describe
|
||||
* how to reach a peer dashboard; the global data scope (`dataScope.ts`) narrows every
|
||||
* scoped GET via `?sources=`. Health checks and import history surface in Settings.
|
||||
*
|
||||
* ## Observability
|
||||
* Prometheus scrapes `GET /api/metrics` (see `monitoring/`). Grafana ships four
|
||||
* provisioned boards (overview, sessions, tools, alerts). Native npm scripts and
|
||||
* Docker Compose profiles are documented in `monitoring/README.md`.
|
||||
*
|
||||
* ## Internal dependencies
|
||||
* - `./constants`
|
||||
* - `./login-item`
|
||||
* - `./logger`
|
||||
* - `./menu`
|
||||
* - `./server-host`
|
||||
* - `./shell-path`
|
||||
* - `./tray`
|
||||
* - `./window`
|
||||
*
|
||||
* ## Testing pointers
|
||||
* - Prefer colocated `__tests__` with Vitest + Testing Library for UI.
|
||||
* - Server contract changes require `npm run test:server` and OpenAPI sync.
|
||||
* - MCP edits: `npm run mcp:typecheck` and `npm run mcp:build`.
|
||||
*
|
||||
* ## Related docs
|
||||
* - `ARCHITECTURE.md` — hooks → API → SQLite → WebSocket → UI pipeline.
|
||||
* - `docs/API.md` — REST reference.
|
||||
* - `.claude/skills/file-headers/` — mandatory `@author` header policy.
|
||||
* ============================================================================= */
|
||||
|
||||
import { BrowserWindow, Notification, app, dialog, shell } from "electron";
|
||||
|
||||
import { APP_ID, APP_NAME } from "./constants";
|
||||
import { isOpenAtLogin, launchedAtLogin, toggleOpenAtLogin } from "./login-item";
|
||||
import { log } from "./logger";
|
||||
import { focusOrCreateWindow, installApplicationMenu } from "./menu";
|
||||
import {
|
||||
closeEmbeddedDatabase,
|
||||
getServerSnapshot,
|
||||
refreshServerSnapshot,
|
||||
startEmbeddedServer,
|
||||
startSnapshotPolling,
|
||||
type ServerHandle,
|
||||
} from "./server-host";
|
||||
import { ensureUserPath } from "./shell-path";
|
||||
import { createTray } from "./tray";
|
||||
import { appIconPath, createDashboardWindow } from "./window";
|
||||
|
||||
/** Single mutable record of process-wide state, held in the module-level
|
||||
* `state` singleton below rather than passed around — this main-process
|
||||
* entry point has exactly one window, one tray, and one server, so a class
|
||||
* or a dependency-injected context would add indirection without benefit. */
|
||||
interface AppState {
|
||||
/** `null` until `startEmbeddedServer()` resolves during `boot()`. */
|
||||
serverHandle: ServerHandle | null;
|
||||
/** `null` when hidden/not-yet-created; a live window still counts even
|
||||
* while hidden by a `close` — see the `win.on("close", ...)` handler. */
|
||||
win: BrowserWindow | null;
|
||||
// Hold a reference to the tray so the GC doesn't collect it (electron quirk).
|
||||
tray: Electron.Tray | null;
|
||||
/** Set once teardown has begun (inside `requestQuit`'s confirm callback or
|
||||
* the bypass path in `before-quit`); gates re-entrant quit handling. */
|
||||
quitting: boolean;
|
||||
/** True while the quit-confirmation dialog is open; a second ⌘Q in this
|
||||
* window bypasses the dialog and lets macOS quit immediately. */
|
||||
confirmingQuit: boolean;
|
||||
}
|
||||
|
||||
const state: AppState = {
|
||||
serverHandle: null,
|
||||
win: null,
|
||||
tray: null,
|
||||
quitting: false,
|
||||
confirmingQuit: false,
|
||||
};
|
||||
|
||||
/**
|
||||
* Show the "Quit Claude Code Monitor?" confirmation dialog. Clicking Quit
|
||||
* runs the synchronous teardown and exits. Pressing ⌘Q again while the
|
||||
* dialog is open is caught by `before-quit` below and skips this prompt.
|
||||
*/
|
||||
function requestQuit(): void {
|
||||
if (state.quitting || state.confirmingQuit) return;
|
||||
state.confirmingQuit = true;
|
||||
// On macOS a second ⌘Q while this dialog is open bypasses it (handled in
|
||||
// `before-quit`); mention that shortcut only where it applies.
|
||||
const quitAccel = process.platform === "darwin" ? "⌘Q" : "Ctrl+Q";
|
||||
const opts: Electron.MessageBoxOptions = {
|
||||
type: "question",
|
||||
buttons: ["Quit", "Cancel"],
|
||||
defaultId: 0,
|
||||
cancelId: 1,
|
||||
title: APP_NAME,
|
||||
message: "Quit Claude Code Monitor?",
|
||||
detail:
|
||||
"The embedded server will stop and your dashboard window will close. " +
|
||||
`Press ${quitAccel} again to skip this prompt and quit immediately.`,
|
||||
noLink: true,
|
||||
};
|
||||
const parent = state.win && !state.win.isDestroyed() ? state.win : undefined;
|
||||
const promise = parent ? dialog.showMessageBox(parent, opts) : dialog.showMessageBox(opts);
|
||||
void promise
|
||||
.then((result) => {
|
||||
state.confirmingQuit = false;
|
||||
if (result.response === 0) {
|
||||
state.quitting = true;
|
||||
if (state.serverHandle?.ownedByUs) closeEmbeddedDatabase();
|
||||
app.exit(0);
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
state.confirmingQuit = false;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The single entry point every "open the dashboard" action goes through
|
||||
* (dock/tray click, menu item, `second-instance`, macOS `activate`). Delegates
|
||||
* to `focusOrCreateWindow` to reuse an existing window when possible, and
|
||||
* otherwise builds one with `createDashboardWindow` and wires its `close`
|
||||
* handler to hide-not-destroy (see the inline comment below).
|
||||
*
|
||||
* @throws If called before `startEmbeddedServer()` has resolved — there is no
|
||||
* URL to point the window at yet. `boot()` guarantees this can't happen on
|
||||
* the normal startup path.
|
||||
*/
|
||||
function ensureWindow(): BrowserWindow {
|
||||
if (!state.serverHandle) {
|
||||
throw new Error("Cannot create window before the server is up.");
|
||||
}
|
||||
return focusOrCreateWindow(state.win, () => {
|
||||
const win = createDashboardWindow(state.serverHandle!.url);
|
||||
state.win = win;
|
||||
win.on("close", (event) => {
|
||||
if (state.quitting) return;
|
||||
// On macOS, "close" means "hide" — the tray stays, the server stays.
|
||||
// We deliberately do NOT call `app.dock.hide()` here. With the red
|
||||
// close button leaving the app running, the user needs a visible
|
||||
// indication that it is still alive. The dock icon (clickable to
|
||||
// re-open the window) is exactly that signal; the menu-bar tray
|
||||
// icon backs it up. Login-launched startup is the only path that
|
||||
// hides the dock, since that user explicitly asked for unobtrusive
|
||||
// background behaviour.
|
||||
event.preventDefault();
|
||||
win.hide();
|
||||
});
|
||||
return win;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Handler for the "Restart Server" menu/tray action. Stops the current
|
||||
* server only if we own it (an adopted external server is left untouched —
|
||||
* we have no business killing a process we didn't start), starts a fresh
|
||||
* one via `startEmbeddedServer()` (which re-runs port adoption/selection
|
||||
* from scratch), reloads the dashboard window at the new URL if one is
|
||||
* open, and surfaces a native notification so the user has confirmation the
|
||||
* click did something.
|
||||
*/
|
||||
async function restartServer(): Promise<void> {
|
||||
log.info("restarting server");
|
||||
if (state.serverHandle?.ownedByUs) {
|
||||
await state.serverHandle.stop();
|
||||
}
|
||||
state.serverHandle = await startEmbeddedServer();
|
||||
if (state.win && !state.win.isDestroyed()) {
|
||||
state.win
|
||||
.loadURL(state.serverHandle.url)
|
||||
.catch((err) => log.error("reload after restart failed", err));
|
||||
}
|
||||
new Notification({ title: APP_NAME, body: "Server restarted." }).show();
|
||||
}
|
||||
|
||||
/** Reveal `desktop.log` in the OS file browser (Finder/Explorer), or log a
|
||||
* no-op note if no line has been written yet (so `log.path()` is empty). */
|
||||
function openLogs(): void {
|
||||
const p = log.path();
|
||||
if (p) {
|
||||
void shell.showItemInFolder(p);
|
||||
} else {
|
||||
log.info("(no log file yet)");
|
||||
}
|
||||
}
|
||||
|
||||
/** Open the dashboard's URL in the user's default system browser. A no-op
|
||||
* before the server has started, since there is no URL yet. */
|
||||
function openInBrowser(): void {
|
||||
if (state.serverHandle) void shell.openExternal(state.serverHandle.url);
|
||||
}
|
||||
|
||||
/** Show a blocking native error dialog. Used only for conditions the user
|
||||
* must see immediately and cannot recover from without restarting the app
|
||||
* (e.g. the embedded server failing to boot at all). */
|
||||
function showFatalDialog(message: string, detail?: string): void {
|
||||
dialog.showErrorBox(`${APP_NAME} — Error`, detail ? `${message}\n\n${detail}` : message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs once, after Electron fires `app.whenReady()`. Performs the full
|
||||
* startup sequence documented in the file header: recover the shell `PATH`,
|
||||
* boot (or adopt) the embedded server, install the application menu and
|
||||
* tray, start the tray's snapshot poller, then open the dashboard window —
|
||||
* unless this launch was triggered by the OS at login, in which case the app
|
||||
* stays tray-only. A server-boot failure here is fatal: it shows a blocking
|
||||
* error dialog and exits the process, since there is nothing useful the app
|
||||
* can do without its server.
|
||||
*/
|
||||
async function boot(): Promise<void> {
|
||||
// macOS only shows the bundle's .icns in the Dock; an unpackaged `desktop:dev`
|
||||
// run otherwise displays the generic Electron icon. Set it explicitly so the
|
||||
// dev Dock matches the packaged app (Windows/Linux get theirs via the
|
||||
// BrowserWindow `icon`). Wrapped in try/catch — purely cosmetic.
|
||||
if (process.platform === "darwin" && !app.isPackaged) {
|
||||
const icon = appIconPath();
|
||||
if (icon) {
|
||||
try {
|
||||
app.dock?.setIcon(icon);
|
||||
} catch (err) {
|
||||
log.warn("could not set dev dock icon", err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Recover the user's shell PATH before the server boots — a Finder/Dock or
|
||||
// login-launched app only inherits launchd's minimal PATH, which makes the
|
||||
// "Run Claude" feature unable to find the `claude` CLI.
|
||||
ensureUserPath();
|
||||
|
||||
try {
|
||||
state.serverHandle = await startEmbeddedServer();
|
||||
} catch (err) {
|
||||
log.error("server failed to start", err);
|
||||
showFatalDialog(
|
||||
"The dashboard server failed to start.",
|
||||
err instanceof Error ? err.message : String(err)
|
||||
);
|
||||
app.exit(1);
|
||||
return;
|
||||
}
|
||||
|
||||
installApplicationMenu({
|
||||
showDashboard: () => ensureWindow(),
|
||||
reloadDashboard: () => state.win?.webContents.reload(),
|
||||
restartServer: () => {
|
||||
void restartServer().catch((err) =>
|
||||
showFatalDialog("Could not restart the server.", String(err))
|
||||
);
|
||||
},
|
||||
openLogs,
|
||||
toggleOpenAtLogin: () => {
|
||||
const next = toggleOpenAtLogin();
|
||||
log.info("open-at-login set to", next);
|
||||
},
|
||||
isOpenAtLogin,
|
||||
});
|
||||
|
||||
state.tray = createTray({
|
||||
showDashboard: () => ensureWindow(),
|
||||
restartServer: () => {
|
||||
void restartServer().catch((err) =>
|
||||
showFatalDialog("Could not restart the server.", String(err))
|
||||
);
|
||||
},
|
||||
openLogs,
|
||||
openInBrowser,
|
||||
toggleOpenAtLogin: () => toggleOpenAtLogin(),
|
||||
isOpenAtLogin,
|
||||
serverPort: () => state.serverHandle?.port ?? null,
|
||||
getSnapshot: () => getServerSnapshot(),
|
||||
refreshSnapshot: () => void refreshServerSnapshot(state.serverHandle?.port ?? null),
|
||||
requestQuit,
|
||||
});
|
||||
|
||||
// Keep the tray's live counts fresh by polling the running server's stats
|
||||
// API on an interval (and on each menu open via refreshSnapshot above).
|
||||
startSnapshotPolling(() => state.serverHandle?.port ?? null);
|
||||
|
||||
// Skip the dashboard window when macOS launched us at login — the user just
|
||||
// logged in, they don't want a window jumping in their face. Tray only.
|
||||
if (!launchedAtLogin()) {
|
||||
ensureWindow();
|
||||
} else {
|
||||
log.info("launched at login — staying tray-only");
|
||||
if (process.platform === "darwin") app.dock?.hide();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the app-level lifecycle handlers. Called synchronously before
|
||||
* `app.whenReady()` so the single-instance lock and `before-quit` interception
|
||||
* are in place from the very first tick — there is no window yet to race
|
||||
* against.
|
||||
*
|
||||
* `requestSingleInstanceLock()` is what makes a second launch (a second Dock
|
||||
* click, or double-clicking the Start-Menu shortcut again) just focus the
|
||||
* existing window instead of spawning a second tray + embedded server, which
|
||||
* would otherwise fight over the same port and SQLite file.
|
||||
*/
|
||||
function wireLifecycle(): void {
|
||||
// Single-instance lock: second launches just focus the first window.
|
||||
const gotLock = app.requestSingleInstanceLock();
|
||||
if (!gotLock) {
|
||||
app.exit(0);
|
||||
return;
|
||||
}
|
||||
app.on("second-instance", () => {
|
||||
if (state.serverHandle) ensureWindow();
|
||||
});
|
||||
|
||||
app.on("activate", () => {
|
||||
if (state.serverHandle) ensureWindow();
|
||||
});
|
||||
|
||||
app.on("window-all-closed", () => {
|
||||
// Stay alive: tray + server keep running on every platform.
|
||||
});
|
||||
|
||||
app.on("before-quit", (event) => {
|
||||
// Second ⌘Q while the confirm dialog is up — bypass the prompt and let
|
||||
// macOS quit. We still close the SQLite handle on the way out so WAL is
|
||||
// checkpointed cleanly.
|
||||
if (state.confirmingQuit) {
|
||||
state.quitting = true;
|
||||
if (state.serverHandle?.ownedByUs) closeEmbeddedDatabase();
|
||||
return;
|
||||
}
|
||||
if (state.quitting) return;
|
||||
if (state.serverHandle?.ownedByUs) {
|
||||
event.preventDefault();
|
||||
requestQuit();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
app.setName(APP_NAME);
|
||||
// Windows: associate this process with the installed app's AppUserModelID so
|
||||
// `new Notification()` toasts (e.g. "Server restarted") render under the app's
|
||||
// name/icon and taskbar windows group correctly. Must be set before any window
|
||||
// or notification is created. No-op on macOS/Linux.
|
||||
if (process.platform === "win32") app.setAppUserModelId(APP_ID);
|
||||
wireLifecycle();
|
||||
app
|
||||
.whenReady()
|
||||
.then(boot)
|
||||
.catch((err) => {
|
||||
log.error("fatal during boot", err);
|
||||
showFatalDialog("Fatal error during startup.", String(err));
|
||||
app.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,258 @@
|
||||
/**
|
||||
* @file Native application menu (the macOS top-bar menu).
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
/* =============================================================================
|
||||
* MODULE_GUIDE — extended in-file reference (comments only; safe to read, never executed)
|
||||
* =============================================================================
|
||||
* **Purpose:** Dashboard module consumed by the React client, MCP tools, or desktop shell depending on deployment mode.
|
||||
*
|
||||
* ## Design constraints
|
||||
* - Local-first: no telemetry leaves the machine unless the user configures webhooks.
|
||||
* - Fail-safe hooks path on the server must never block Claude Code; UI mirrors that
|
||||
* philosophy by degrading gracefully (empty states, stale badges, reconnect loops).
|
||||
* - Destructive flows stay behind explicit confirmation modals and server-side gates.
|
||||
* - Internationalization: user-visible strings belong in i18n JSON, not literals here.
|
||||
*
|
||||
* ## Remote data & SSH
|
||||
* Remote Data Sources let operators aggregate multiple machines. SSH entries describe
|
||||
* how to reach a peer dashboard; the global data scope (`dataScope.ts`) narrows every
|
||||
* scoped GET via `?sources=`. Health checks and import history surface in Settings.
|
||||
*
|
||||
* ## Observability
|
||||
* Prometheus scrapes `GET /api/metrics` (see `monitoring/`). Grafana ships four
|
||||
* provisioned boards (overview, sessions, tools, alerts). Native npm scripts and
|
||||
* Docker Compose profiles are documented in `monitoring/README.md`.
|
||||
*
|
||||
* ## Internal dependencies
|
||||
* - `./constants`
|
||||
*
|
||||
* ## Public surface
|
||||
* - `MenuActions` — exported API; see TSDoc on the symbol for behavior.
|
||||
* - `installApplicationMenu` — exported API; see TSDoc on the symbol for behavior.
|
||||
* - `focusOrCreateWindow` — exported API; see TSDoc on the symbol for behavior.
|
||||
*
|
||||
* ## Testing pointers
|
||||
* - Prefer colocated `__tests__` with Vitest + Testing Library for UI.
|
||||
* - Server contract changes require `npm run test:server` and OpenAPI sync.
|
||||
* - MCP edits: `npm run mcp:typecheck` and `npm run mcp:build`.
|
||||
*
|
||||
* ## Related docs
|
||||
* - `ARCHITECTURE.md` — hooks → API → SQLite → WebSocket → UI pipeline.
|
||||
* - `docs/API.md` — REST reference.
|
||||
* - `.claude/skills/file-headers/` — mandatory `@author` header policy.
|
||||
* ============================================================================= */
|
||||
/* -----------------------------------------------------------------------------
|
||||
* EXPORT CATALOG — quick index of symbols defined below (documentation only).
|
||||
* -----------------------------------------------------------------------------
|
||||
* **MenuActions**
|
||||
* Part of this module's public contract. Downstream imports should treat
|
||||
* the signature and return type as stable unless release notes say otherwise.
|
||||
* When behavior changes, update the `@file` overview and relevant tests.
|
||||
*
|
||||
* **installApplicationMenu**
|
||||
* Part of this module's public contract. Downstream imports should treat
|
||||
* the signature and return type as stable unless release notes say otherwise.
|
||||
* When behavior changes, update the `@file` overview and relevant tests.
|
||||
*
|
||||
* **focusOrCreateWindow**
|
||||
* Part of this module's public contract. Downstream imports should treat
|
||||
* the signature and return type as stable unless release notes say otherwise.
|
||||
* When behavior changes, update the `@file` overview and relevant tests.
|
||||
*
|
||||
* ----------------------------------------------------------------------------- */
|
||||
|
||||
import { BrowserWindow, Menu, app, shell, type MenuItemConstructorOptions } from "electron";
|
||||
|
||||
import { APP_NAME } from "./constants";
|
||||
|
||||
/** Callbacks the menu wires to its items. `main.ts` supplies these, sharing
|
||||
* the same handlers passed to `createTray` so both surfaces stay consistent. */
|
||||
export interface MenuActions {
|
||||
/** Bring the dashboard window to front, creating it if it doesn't exist. */
|
||||
showDashboard: () => void;
|
||||
/** Reload the currently loaded dashboard page (`webContents.reload()`). */
|
||||
reloadDashboard: () => void;
|
||||
/** Stop and re-launch the embedded server, then reload the window. */
|
||||
restartServer: () => void;
|
||||
/** Reveal `desktop.log` in the OS file browser. */
|
||||
openLogs: () => void;
|
||||
/** Flip the OS auto-start-at-login registration. */
|
||||
toggleOpenAtLogin: () => void;
|
||||
/** Read the current auto-start state, used to render the checkbox. */
|
||||
isOpenAtLogin: () => boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build and install the native application menu (the macOS global menu bar;
|
||||
* the per-window menu on Windows/Linux) and return it.
|
||||
*
|
||||
* Structure: an macOS-only app submenu (About, Open at Login, Services,
|
||||
* Hide/Quit) prepended to standard File / Edit / View / Window / Help menus.
|
||||
* Item visibility and roles branch on `process.platform === "darwin"` in a
|
||||
* handful of places — see the inline comments on the `File ▸ Open Dashboard`
|
||||
* item and the `Window` submenu for why those specific items are macOS-only.
|
||||
*/
|
||||
export function installApplicationMenu(actions: MenuActions): Menu {
|
||||
const isMac = process.platform === "darwin";
|
||||
|
||||
const template: MenuItemConstructorOptions[] = [
|
||||
...(isMac
|
||||
? ([
|
||||
{
|
||||
label: APP_NAME,
|
||||
submenu: [
|
||||
{ role: "about" },
|
||||
{ type: "separator" },
|
||||
{
|
||||
label: "Open at Login",
|
||||
type: "checkbox",
|
||||
checked: actions.isOpenAtLogin(),
|
||||
click: () => actions.toggleOpenAtLogin(),
|
||||
},
|
||||
{ type: "separator" },
|
||||
{ role: "services" },
|
||||
{ type: "separator" },
|
||||
{ role: "hide" },
|
||||
{ role: "hideOthers" },
|
||||
{ role: "unhide" },
|
||||
{ type: "separator" },
|
||||
{ role: "quit" },
|
||||
],
|
||||
},
|
||||
] satisfies MenuItemConstructorOptions[])
|
||||
: []),
|
||||
{
|
||||
label: "File",
|
||||
submenu: [
|
||||
// "Open Dashboard" is macOS-only. On macOS the menu bar is global and
|
||||
// persists after the window is closed/hidden, so this item (and Cmd+1)
|
||||
// genuinely reopens it. On Windows/Linux the menu is attached to the
|
||||
// window itself and a menu accelerator only fires while that window is
|
||||
// already focused/foreground — so the item could only ever run when the
|
||||
// window is already up, making it a confusing no-op. Reopening from a
|
||||
// hidden/tray state is handled by the tray's own "Open Dashboard" there.
|
||||
...(isMac
|
||||
? ([
|
||||
{
|
||||
label: "Open Dashboard",
|
||||
accelerator: "CmdOrCtrl+1",
|
||||
click: () => actions.showDashboard(),
|
||||
},
|
||||
] satisfies MenuItemConstructorOptions[])
|
||||
: []),
|
||||
{
|
||||
// No accelerator here: the View menu's `reload` role already owns
|
||||
// CmdOrCtrl+R. Two menu items sharing one accelerator triggers an
|
||||
// Electron duplicate-accelerator warning at startup.
|
||||
label: "Reload Dashboard",
|
||||
click: () => actions.reloadDashboard(),
|
||||
},
|
||||
{ type: "separator" },
|
||||
{
|
||||
label: "Restart Server",
|
||||
click: () => actions.restartServer(),
|
||||
},
|
||||
{
|
||||
label: "Show Logs",
|
||||
click: () => actions.openLogs(),
|
||||
},
|
||||
{ type: "separator" },
|
||||
isMac ? { role: "close" } : { role: "quit" },
|
||||
],
|
||||
},
|
||||
{
|
||||
label: "Edit",
|
||||
submenu: [
|
||||
{ role: "undo" },
|
||||
{ role: "redo" },
|
||||
{ type: "separator" },
|
||||
{ role: "cut" },
|
||||
{ role: "copy" },
|
||||
{ role: "paste" },
|
||||
{ role: "selectAll" },
|
||||
],
|
||||
},
|
||||
{
|
||||
label: "View",
|
||||
submenu: [
|
||||
{ role: "reload" },
|
||||
{ role: "forceReload" },
|
||||
{ role: "toggleDevTools" },
|
||||
{ type: "separator" },
|
||||
{ role: "resetZoom" },
|
||||
{ role: "zoomIn" },
|
||||
{ role: "zoomOut" },
|
||||
{ type: "separator" },
|
||||
{ role: "togglefullscreen" },
|
||||
],
|
||||
},
|
||||
{
|
||||
label: "Window",
|
||||
submenu: [
|
||||
{ role: "minimize" },
|
||||
{ role: "zoom" },
|
||||
...(isMac
|
||||
? ([
|
||||
{ type: "separator" },
|
||||
{ role: "front" },
|
||||
{ type: "separator" },
|
||||
{ role: "window" },
|
||||
] satisfies MenuItemConstructorOptions[])
|
||||
: ([{ role: "close" }] satisfies MenuItemConstructorOptions[])),
|
||||
],
|
||||
},
|
||||
{
|
||||
role: "help",
|
||||
submenu: [
|
||||
{
|
||||
label: "Project on GitHub",
|
||||
click: () =>
|
||||
void shell.openExternal("https://git.smartgift.io.vn/Smartgift-AI/Claude-Code-Monitor"),
|
||||
},
|
||||
{
|
||||
label: "Report an Issue",
|
||||
click: () =>
|
||||
void shell.openExternal(
|
||||
"https://git.smartgift.io.vn/Smartgift-AI/Claude-Code-Monitor/issues/new/choose"
|
||||
),
|
||||
},
|
||||
{
|
||||
label: `${APP_NAME} v${app.getVersion()}`,
|
||||
enabled: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const menu = Menu.buildFromTemplate(template);
|
||||
Menu.setApplicationMenu(menu);
|
||||
return menu;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bring the dashboard window to focus, creating one via the supplied factory
|
||||
* if needed. Shared by `main.ts`'s `ensureWindow` for every "open the
|
||||
* dashboard" entry point (dock click, tray click, menu item, second-instance
|
||||
* relaunch) so they all get the same restore/show/focus sequence.
|
||||
*
|
||||
* @param existing The current window reference, or `null`/destroyed if none.
|
||||
* @param create Factory invoked only when `existing` is missing or destroyed.
|
||||
* @returns The existing (now focused) window, or the newly created one.
|
||||
*/
|
||||
export function focusOrCreateWindow(
|
||||
existing: BrowserWindow | null,
|
||||
create: () => BrowserWindow
|
||||
): BrowserWindow {
|
||||
if (existing && !existing.isDestroyed()) {
|
||||
if (existing.isMinimized()) existing.restore();
|
||||
// Call show() unconditionally (not just when hidden): on Windows a bare
|
||||
// focus() on a visible-but-background window often only flashes the taskbar
|
||||
// button instead of raising it, whereas show() reliably activates and
|
||||
// brings it to the foreground. Harmless when the window is already frontmost.
|
||||
existing.show();
|
||||
existing.focus();
|
||||
return existing;
|
||||
}
|
||||
return create();
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
* @file Preload script.
|
||||
*
|
||||
* The dashboard runs as standard web content loaded from
|
||||
* `http://127.0.0.1:<port>`. It does not need privileged APIs to function;
|
||||
* keeping this preload empty is intentional and keeps the attack surface
|
||||
* minimal. Renderer-side desktop helpers (e.g. native notification routing)
|
||||
* can be added here later via `contextBridge.exposeInMainWorld` if the
|
||||
* dashboard ever wants to call them.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
/* =============================================================================
|
||||
* MODULE_GUIDE — extended in-file reference (comments only; safe to read, never executed)
|
||||
* =============================================================================
|
||||
* **Purpose:** Dashboard module consumed by the React client, MCP tools, or desktop shell depending on deployment mode.
|
||||
*
|
||||
* ## Design constraints
|
||||
* - Local-first: no telemetry leaves the machine unless the user configures webhooks.
|
||||
* - Fail-safe hooks path on the server must never block Claude Code; UI mirrors that
|
||||
* philosophy by degrading gracefully (empty states, stale badges, reconnect loops).
|
||||
* - Destructive flows stay behind explicit confirmation modals and server-side gates.
|
||||
* - Internationalization: user-visible strings belong in i18n JSON, not literals here.
|
||||
*
|
||||
* ## Remote data & SSH
|
||||
* Remote Data Sources let operators aggregate multiple machines. SSH entries describe
|
||||
* how to reach a peer dashboard; the global data scope (`dataScope.ts`) narrows every
|
||||
* scoped GET via `?sources=`. Health checks and import history surface in Settings.
|
||||
*
|
||||
* ## Observability
|
||||
* Prometheus scrapes `GET /api/metrics` (see `monitoring/`). Grafana ships four
|
||||
* provisioned boards (overview, sessions, tools, alerts). Native npm scripts and
|
||||
* Docker Compose profiles are documented in `monitoring/README.md`.
|
||||
*
|
||||
* ## Testing pointers
|
||||
* - Prefer colocated `__tests__` with Vitest + Testing Library for UI.
|
||||
* - Server contract changes require `npm run test:server` and OpenAPI sync.
|
||||
* - MCP edits: `npm run mcp:typecheck` and `npm run mcp:build`.
|
||||
*
|
||||
* ## Related docs
|
||||
* - `ARCHITECTURE.md` — hooks → API → SQLite → WebSocket → UI pipeline.
|
||||
* - `docs/API.md` — REST reference.
|
||||
* - `.claude/skills/file-headers/` — mandatory `@author` header policy.
|
||||
* ============================================================================= */
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,556 @@
|
||||
/**
|
||||
* @file Hosts the existing Express server in-process.
|
||||
*
|
||||
* The dashboard's `server/index.js` already exports `{ createApp, startServer }`
|
||||
* and serves the built React client (`client/dist`) as static assets in
|
||||
* production. We import that module directly — no child process, no IPC, no
|
||||
* port marshalling — and start it on a free port. The whole thing keeps the
|
||||
* desktop shell to "Electron is a window onto the same code."
|
||||
*
|
||||
* If another process is already listening on the preferred port and that
|
||||
* process answers `/api/health` with `{ status: "ok" }`, we adopt it instead
|
||||
* of starting a second server. This covers the case where the user already
|
||||
* runs `npm start` in a terminal — we should not double-bind.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
/* =============================================================================
|
||||
* MODULE_GUIDE — extended in-file reference (comments only; safe to read, never executed)
|
||||
* =============================================================================
|
||||
* **Purpose:** Dashboard module consumed by the React client, MCP tools, or desktop shell depending on deployment mode.
|
||||
*
|
||||
* ## Design constraints
|
||||
* - Local-first: no telemetry leaves the machine unless the user configures webhooks.
|
||||
* - Fail-safe hooks path on the server must never block Claude Code; UI mirrors that
|
||||
* philosophy by degrading gracefully (empty states, stale badges, reconnect loops).
|
||||
* - Destructive flows stay behind explicit confirmation modals and server-side gates.
|
||||
* - Internationalization: user-visible strings belong in i18n JSON, not literals here.
|
||||
*
|
||||
* ## Remote data & SSH
|
||||
* Remote Data Sources let operators aggregate multiple machines. SSH entries describe
|
||||
* how to reach a peer dashboard; the global data scope (`dataScope.ts`) narrows every
|
||||
* scoped GET via `?sources=`. Health checks and import history surface in Settings.
|
||||
*
|
||||
* ## Observability
|
||||
* Prometheus scrapes `GET /api/metrics` (see `monitoring/`). Grafana ships four
|
||||
* provisioned boards (overview, sessions, tools, alerts). Native npm scripts and
|
||||
* Docker Compose profiles are documented in `monitoring/README.md`.
|
||||
*
|
||||
* ## Internal dependencies
|
||||
* - `./constants`
|
||||
* - `./logger`
|
||||
*
|
||||
* ## Public surface
|
||||
* - `ServerHandle` — exported API; see TSDoc on the symbol for behavior.
|
||||
* - `ServerSnapshot` — exported API; see TSDoc on the symbol for behavior.
|
||||
* - `getServerSnapshot` — exported API; see TSDoc on the symbol for behavior.
|
||||
* - `refreshServerSnapshot` — exported API; see TSDoc on the symbol for behavior.
|
||||
* - `startSnapshotPolling` — exported API; see TSDoc on the symbol for behavior.
|
||||
* - `closeEmbeddedDatabase` — exported API; see TSDoc on the symbol for behavior.
|
||||
* - `startEmbeddedServer` — exported API; see TSDoc on the symbol for behavior.
|
||||
*
|
||||
* ## Testing pointers
|
||||
* - Prefer colocated `__tests__` with Vitest + Testing Library for UI.
|
||||
* - Server contract changes require `npm run test:server` and OpenAPI sync.
|
||||
* - MCP edits: `npm run mcp:typecheck` and `npm run mcp:build`.
|
||||
*
|
||||
* ## Related docs
|
||||
* - `ARCHITECTURE.md` — hooks → API → SQLite → WebSocket → UI pipeline.
|
||||
* - `docs/API.md` — REST reference.
|
||||
* - `.claude/skills/file-headers/` — mandatory `@author` header policy.
|
||||
* ============================================================================= */
|
||||
/* -----------------------------------------------------------------------------
|
||||
* EXPORT CATALOG — quick index of symbols defined below (documentation only).
|
||||
* -----------------------------------------------------------------------------
|
||||
* **ServerHandle**
|
||||
* Part of this module's public contract. Downstream imports should treat
|
||||
* the signature and return type as stable unless release notes say otherwise.
|
||||
* When behavior changes, update the `@file` overview and relevant tests.
|
||||
*
|
||||
* **ServerSnapshot**
|
||||
* Part of this module's public contract. Downstream imports should treat
|
||||
* the signature and return type as stable unless release notes say otherwise.
|
||||
* When behavior changes, update the `@file` overview and relevant tests.
|
||||
*
|
||||
* **getServerSnapshot**
|
||||
* Part of this module's public contract. Downstream imports should treat
|
||||
* the signature and return type as stable unless release notes say otherwise.
|
||||
* When behavior changes, update the `@file` overview and relevant tests.
|
||||
*
|
||||
* **refreshServerSnapshot**
|
||||
* Part of this module's public contract. Downstream imports should treat
|
||||
* the signature and return type as stable unless release notes say otherwise.
|
||||
* When behavior changes, update the `@file` overview and relevant tests.
|
||||
*
|
||||
* **startSnapshotPolling**
|
||||
* Part of this module's public contract. Downstream imports should treat
|
||||
* the signature and return type as stable unless release notes say otherwise.
|
||||
* When behavior changes, update the `@file` overview and relevant tests.
|
||||
*
|
||||
* **closeEmbeddedDatabase**
|
||||
* Part of this module's public contract. Downstream imports should treat
|
||||
* the signature and return type as stable unless release notes say otherwise.
|
||||
* When behavior changes, update the `@file` overview and relevant tests.
|
||||
*
|
||||
* **startEmbeddedServer**
|
||||
* Part of this module's public contract. Downstream imports should treat
|
||||
* the signature and return type as stable unless release notes say otherwise.
|
||||
* When behavior changes, update the `@file` overview and relevant tests.
|
||||
*
|
||||
* ----------------------------------------------------------------------------- */
|
||||
|
||||
import * as fs from "node:fs";
|
||||
import * as http from "node:http";
|
||||
import Module from "node:module";
|
||||
import * as net from "node:net";
|
||||
import * as path from "node:path";
|
||||
import { app } from "electron";
|
||||
|
||||
import { FALLBACK_PORT_RANGE, HEALTH_TIMEOUT_MS, PREFERRED_PORT } from "./constants";
|
||||
import { log } from "./logger";
|
||||
|
||||
/**
|
||||
* Redirect `require("better-sqlite3")` from anywhere in the embedded server
|
||||
* to the copy in `desktop/node_modules`, which has been rebuilt against
|
||||
* Electron's Node ABI by `electron-builder install-app-deps`. The repo-root
|
||||
* copy is intentionally left built for the system Node so `npm run test:server`
|
||||
* continues to work for contributors. This patch is process-local — it does
|
||||
* not affect any other Node process.
|
||||
*
|
||||
* The patch is installed exactly once before we require the server module.
|
||||
*/
|
||||
let nativeModulesPatched = false;
|
||||
function ensureNativeModulesPatched(): void {
|
||||
if (nativeModulesPatched) return;
|
||||
nativeModulesPatched = true;
|
||||
|
||||
// Resolve the desktop-local better-sqlite3 from this file's location so we
|
||||
// get the ABI-correct binary regardless of where the require originates.
|
||||
let desktopBetterSqlite: string;
|
||||
try {
|
||||
desktopBetterSqlite = require.resolve("better-sqlite3");
|
||||
} catch (err) {
|
||||
log.warn("could not pre-resolve desktop better-sqlite3; server may fall back", err);
|
||||
return;
|
||||
}
|
||||
|
||||
// Module._resolveFilename is Node's internal lookup. We override it to
|
||||
// short-circuit "better-sqlite3" requests; everything else passes through.
|
||||
// Using a typed shim instead of `any` to keep strict mode honest.
|
||||
type ResolveFn = (
|
||||
request: string,
|
||||
parent: NodeJS.Module | null | undefined,
|
||||
isMain: boolean,
|
||||
options?: { paths?: string[] }
|
||||
) => string;
|
||||
const mod = Module as unknown as { _resolveFilename: ResolveFn };
|
||||
const original = mod._resolveFilename.bind(Module);
|
||||
mod._resolveFilename = function (request, parent, isMain, options) {
|
||||
if (request === "better-sqlite3") return desktopBetterSqlite;
|
||||
return original(request, parent, isMain, options);
|
||||
};
|
||||
log.info("native module redirect installed", { betterSqlite3: desktopBetterSqlite });
|
||||
}
|
||||
|
||||
export interface ServerHandle {
|
||||
/** Origin (e.g. `http://127.0.0.1:4820`) used by the window. */
|
||||
url: string;
|
||||
port: number;
|
||||
/** True when the server is owned by us (and we should stop it on quit). */
|
||||
ownedByUs: boolean;
|
||||
/** Gracefully close the HTTP server. A no-op when `ownedByUs` is false —
|
||||
* an adopted server belongs to whatever process started it, and this app
|
||||
* must never shut it down out from under that process. */
|
||||
stop: () => Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* The subset of `server/index.js`'s exports this file calls. Kept as an
|
||||
* `unknown`-typed shim (rather than importing the JS module's real types)
|
||||
* because `server/` is plain JavaScript with no `.d.ts`, and the desktop
|
||||
* workspace's `tsconfig.json` builds in `strict` mode — this interface is the
|
||||
* hand-written contract between the two.
|
||||
*/
|
||||
interface ServerModule {
|
||||
createApp: () => unknown;
|
||||
startServer: (app: unknown, port: number) => Promise<http.Server>;
|
||||
startBackgroundServices: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* One-time bootstrap of the services that the standalone `node server/index.js`
|
||||
* path runs from its `require.main === module` block — the update scheduler,
|
||||
* the Claude Code config watcher, orphaned-run reconciliation, and Claude Code
|
||||
* hook installation. The desktop shell `require()`s the server module, so that
|
||||
* block never fires; without this the embedded server is a degraded copy.
|
||||
*
|
||||
* Guarded so a "Restart Server" does not double-register schedulers/watchers.
|
||||
*/
|
||||
let backgroundServicesStarted = false;
|
||||
function bootstrapOwnedServer(appRoot: string, serverModule: ServerModule): void {
|
||||
if (backgroundServicesStarted) return;
|
||||
backgroundServicesStarted = true;
|
||||
|
||||
try {
|
||||
serverModule.startBackgroundServices();
|
||||
log.info("background services started");
|
||||
} catch (err) {
|
||||
log.warn("startBackgroundServices failed", err);
|
||||
}
|
||||
|
||||
// Auto-install Claude Code hooks so a DMG-only user gets events flowing
|
||||
// without having to run `npm run install-hooks` from a checkout.
|
||||
try {
|
||||
const hooks = require(path.join(appRoot, "scripts", "install-hooks.js")) as {
|
||||
installHooks: (silent?: boolean) => boolean;
|
||||
};
|
||||
hooks.installHooks(true);
|
||||
log.info("Claude Code hooks ensured");
|
||||
} catch (err) {
|
||||
log.warn("hook auto-install failed", err);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Status snapshot for the tray menu. Sourced from the live server's
|
||||
* `/api/stats` endpoint rather than a direct SQLite read, so the numbers stay
|
||||
* correct whether we started the server in-process or adopted an external one
|
||||
* already listening on the port. (A second SQLite handle opened from the
|
||||
* desktop process can point at a different/empty database file — or fail
|
||||
* against the read-only `.app` bundle path — which previously pinned the menu
|
||||
* at 0/0/0.)
|
||||
*
|
||||
* The HTTP fetch is asynchronous but the tray menu is built synchronously on
|
||||
* click, so we poll on an interval and serve the last cached value. Returns
|
||||
* `null` until the first successful poll completes.
|
||||
*/
|
||||
export interface ServerSnapshot {
|
||||
/** Count of sessions the dashboard currently considers active. */
|
||||
activeSessions: number;
|
||||
/** Count of agents specifically in the `working` status (not idle/waiting). */
|
||||
workingAgents: number;
|
||||
/** Hook events received since the user's local midnight. */
|
||||
eventsToday: number;
|
||||
}
|
||||
|
||||
let lastSnapshot: ServerSnapshot | null = null;
|
||||
let snapshotTimer: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
/** Synchronous accessor for the tray menu's build step — always returns the
|
||||
* last value `refreshServerSnapshot` cached, never blocks on a network call. */
|
||||
export function getServerSnapshot(): ServerSnapshot | null {
|
||||
return lastSnapshot;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch a fresh snapshot from the running server's stats API. Resolves to
|
||||
* `null` on any error (server not up yet, non-200, malformed JSON) so the
|
||||
* poller can simply keep the previous cached value.
|
||||
*/
|
||||
function fetchSnapshotOverHttp(port: number, timeoutMs = 2500): Promise<ServerSnapshot | null> {
|
||||
// Server expects tz_offset in minutes (Date#getTimezoneOffset) to compute
|
||||
// "events today" against the user's local midnight.
|
||||
const tzOffset = new Date().getTimezoneOffset();
|
||||
return new Promise((resolve) => {
|
||||
const req = http.get(
|
||||
{
|
||||
host: "127.0.0.1",
|
||||
port,
|
||||
path: `/api/stats?tz_offset=${tzOffset}`,
|
||||
timeout: timeoutMs,
|
||||
},
|
||||
(res) => {
|
||||
if (res.statusCode !== 200) {
|
||||
res.resume();
|
||||
resolve(null);
|
||||
return;
|
||||
}
|
||||
let buf = "";
|
||||
res.setEncoding("utf8");
|
||||
res.on("data", (chunk) => (buf += chunk));
|
||||
res.on("end", () => {
|
||||
try {
|
||||
const j = JSON.parse(buf) as {
|
||||
active_sessions?: number;
|
||||
events_today?: number;
|
||||
agents_by_status?: Record<string, number>;
|
||||
};
|
||||
resolve({
|
||||
activeSessions: Number(j.active_sessions) || 0,
|
||||
// "working" specifically — waiting/idle agents are not working.
|
||||
workingAgents: Number(j.agents_by_status?.working) || 0,
|
||||
eventsToday: Number(j.events_today) || 0,
|
||||
});
|
||||
} catch {
|
||||
resolve(null);
|
||||
}
|
||||
});
|
||||
}
|
||||
);
|
||||
req.on("error", () => resolve(null));
|
||||
req.on("timeout", () => {
|
||||
req.destroy();
|
||||
resolve(null);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/** Poll once now and update the cache. Safe to call on demand (e.g. menu open). */
|
||||
export async function refreshServerSnapshot(port: number | null): Promise<void> {
|
||||
if (!port) return;
|
||||
const snap = await fetchSnapshotOverHttp(port);
|
||||
if (snap) lastSnapshot = snap;
|
||||
}
|
||||
|
||||
/**
|
||||
* Begin polling the server's stats endpoint so the tray menu always reflects
|
||||
* recent state. Idempotent — a second call (e.g. after "Restart Server") is a
|
||||
* no-op. The timer is unref'd so it never keeps the event loop alive on quit.
|
||||
*/
|
||||
export function startSnapshotPolling(getPort: () => number | null, intervalMs = 4000): void {
|
||||
if (snapshotTimer) return;
|
||||
const tick = (): void => {
|
||||
void refreshServerSnapshot(getPort());
|
||||
};
|
||||
tick();
|
||||
snapshotTimer = setInterval(tick, intervalMs);
|
||||
snapshotTimer.unref?.();
|
||||
}
|
||||
|
||||
/**
|
||||
* Close the embedded SQLite handle so WAL is checkpointed cleanly. Call once on
|
||||
* application quit — never between restarts, since `server/db.js` is a cached
|
||||
* singleton and a closed handle would break a subsequent server start.
|
||||
*/
|
||||
export function closeEmbeddedDatabase(): void {
|
||||
try {
|
||||
const dbModule = require(path.join(resolveAppRoot(), "server", "db.js")) as {
|
||||
db?: { open?: boolean; close: () => void };
|
||||
};
|
||||
if (dbModule.db && dbModule.db.open !== false) {
|
||||
dbModule.db.close();
|
||||
log.info("embedded database closed");
|
||||
}
|
||||
} catch (err) {
|
||||
log.warn("failed to close embedded database", err);
|
||||
}
|
||||
// Remove our entry from the multi-server discovery file so the hook
|
||||
// handler doesn't try to POST to this PID after the process is gone.
|
||||
// (Stale entries also self-prune via the liveness check on read, but the
|
||||
// explicit removal closes the window between quit and the next reader.)
|
||||
try {
|
||||
const serverInfo = require(path.join(resolveAppRoot(), "server", "lib", "server-info.js")) as {
|
||||
removeServerInfo: () => void;
|
||||
};
|
||||
serverInfo.removeServerInfo();
|
||||
} catch (err) {
|
||||
log.warn("failed to remove discovery file entry", err);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the directory that contains the bundled `server/` and `client/dist/`.
|
||||
* In the packaged DMG these live under `Resources/app/`. In `npm run dev` they
|
||||
* live at the repo root (one directory up from `desktop/`).
|
||||
*/
|
||||
function resolveAppRoot(): string {
|
||||
if (app.isPackaged) {
|
||||
return path.join(process.resourcesPath, "app");
|
||||
}
|
||||
// Dev: desktop/out/main.js → ../.. = repo root.
|
||||
return path.resolve(__dirname, "..", "..");
|
||||
}
|
||||
|
||||
/**
|
||||
* Classify a TCP port on `127.0.0.1` in two steps:
|
||||
* 1. Attempt a raw socket connection — if nothing answers, the port is
|
||||
* `"free"`.
|
||||
* 2. If something is listening, `GET /api/health` and check for
|
||||
* `{ status: "ok" }` — a match means it is *our* kind of server
|
||||
* (`"healthy"`, safe to adopt); anything else (wrong app, wrong
|
||||
* response, timeout) means the port is occupied by something unrelated
|
||||
* (`"busy"`, must be avoided).
|
||||
*
|
||||
* Used both for startup port selection (`pickFreePort`) and for deciding
|
||||
* whether to adopt an already-running server (`startEmbeddedServer`).
|
||||
*/
|
||||
async function probePort(port: number, timeoutMs = 1500): Promise<"healthy" | "busy" | "free"> {
|
||||
// 1. Is anything listening? Try to connect.
|
||||
const reachable = await new Promise<boolean>((resolve) => {
|
||||
const socket = net.createConnection({ host: "127.0.0.1", port });
|
||||
const done = (v: boolean) => {
|
||||
socket.destroy();
|
||||
resolve(v);
|
||||
};
|
||||
socket.setTimeout(timeoutMs);
|
||||
socket.once("connect", () => done(true));
|
||||
socket.once("error", () => done(false));
|
||||
socket.once("timeout", () => done(false));
|
||||
});
|
||||
|
||||
if (!reachable) return "free";
|
||||
|
||||
// 2. Does it answer /api/health like our server would?
|
||||
const healthy = await new Promise<boolean>((resolve) => {
|
||||
const req = http.get(
|
||||
{ host: "127.0.0.1", port, path: "/api/health", timeout: timeoutMs },
|
||||
(res) => {
|
||||
let buf = "";
|
||||
res.setEncoding("utf8");
|
||||
res.on("data", (chunk) => (buf += chunk));
|
||||
res.on("end", () => {
|
||||
try {
|
||||
const parsed = JSON.parse(buf);
|
||||
resolve(parsed?.status === "ok");
|
||||
} catch {
|
||||
resolve(false);
|
||||
}
|
||||
});
|
||||
}
|
||||
);
|
||||
req.on("error", () => resolve(false));
|
||||
req.on("timeout", () => {
|
||||
req.destroy();
|
||||
resolve(false);
|
||||
});
|
||||
});
|
||||
|
||||
return healthy ? "healthy" : "busy";
|
||||
}
|
||||
|
||||
/**
|
||||
* Choose a port for a server we are about to start ourselves (i.e. we already
|
||||
* know `PREFERRED_PORT` has nothing healthy to adopt). Tries, in order:
|
||||
* 1. `PREFERRED_PORT` (4820) — the project's documented default.
|
||||
* 2. The next nine ports (4821–4829) — small, predictable fallbacks that
|
||||
* are still easy for a user to guess/bookmark.
|
||||
* 3. The full `FALLBACK_PORT_RANGE` (49152–49500, the IANA dynamic/private
|
||||
* range) — scanned sequentially as a last resort.
|
||||
*
|
||||
* @throws If every port in both ranges is occupied (practically never).
|
||||
*/
|
||||
async function pickFreePort(): Promise<number> {
|
||||
// Prefer the project's documented port. Otherwise scan a private range.
|
||||
const initial = await probePort(PREFERRED_PORT);
|
||||
if (initial === "free") return PREFERRED_PORT;
|
||||
|
||||
// Try the next 9 well-known fallbacks first (4821..4829) before going random.
|
||||
for (let p = PREFERRED_PORT + 1; p < PREFERRED_PORT + 10; p++) {
|
||||
if ((await probePort(p)) === "free") return p;
|
||||
}
|
||||
for (let p = FALLBACK_PORT_RANGE.min; p <= FALLBACK_PORT_RANGE.max; p++) {
|
||||
if ((await probePort(p)) === "free") return p;
|
||||
}
|
||||
throw new Error("Could not find a free TCP port for the dashboard server.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Block until `probePort` reports `"healthy"` for the port we just bound, or
|
||||
* throw once `timeoutMs` (default `HEALTH_TIMEOUT_MS`, 30s) elapses. Called
|
||||
* right after `startServer()` returns, before the caller treats the server as
|
||||
* usable — Express's `listen()` callback fires as soon as the socket is
|
||||
* bound, which can be before the app has finished any async initialization
|
||||
* that gates `/api/health`.
|
||||
*/
|
||||
async function waitForHealthy(port: number, timeoutMs = HEALTH_TIMEOUT_MS): Promise<void> {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
while (Date.now() < deadline) {
|
||||
if ((await probePort(port, 500)) === "healthy") return;
|
||||
await new Promise((r) => setTimeout(r, 250));
|
||||
}
|
||||
throw new Error(`Server on port ${port} did not become healthy within ${timeoutMs}ms.`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Bring up the dashboard server. Returns a handle the caller uses to point
|
||||
* the BrowserWindow and to shut down cleanly on quit.
|
||||
*
|
||||
* Two environment overrides exist primarily for testing:
|
||||
* - `CCAM_DESKTOP_BIND_PORT`: bind exactly this port (no adoption, no fallback).
|
||||
* Used by the smoke test to verify the spawned process actually started a
|
||||
* server rather than finding an unrelated one.
|
||||
* - `CCAM_DESKTOP_NO_ADOPT=1`: skip the "is there already a healthy server
|
||||
* on 4820?" check and always start our own.
|
||||
*/
|
||||
export async function startEmbeddedServer(): Promise<ServerHandle> {
|
||||
const forcedPort = process.env.CCAM_DESKTOP_BIND_PORT
|
||||
? parseInt(process.env.CCAM_DESKTOP_BIND_PORT, 10)
|
||||
: null;
|
||||
const noAdopt = process.env.CCAM_DESKTOP_NO_ADOPT === "1" || forcedPort !== null;
|
||||
|
||||
if (!noAdopt) {
|
||||
// Adopt an already-running healthy server (e.g. user has `npm start` open).
|
||||
const adopt = await probePort(PREFERRED_PORT);
|
||||
if (adopt === "healthy") {
|
||||
log.info("adopting existing healthy server on port", PREFERRED_PORT);
|
||||
return {
|
||||
url: `http://127.0.0.1:${PREFERRED_PORT}`,
|
||||
port: PREFERRED_PORT,
|
||||
ownedByUs: false,
|
||||
stop: async () => {
|
||||
/* not ours to stop */
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const port = forcedPort ?? (await pickFreePort());
|
||||
const appRoot = resolveAppRoot();
|
||||
const serverEntry = path.join(appRoot, "server", "index.js");
|
||||
|
||||
// The server reads from process.env. Set everything up before require()ing.
|
||||
process.env.NODE_ENV = "production";
|
||||
process.env.DASHBOARD_PORT = String(port);
|
||||
|
||||
// The server now defaults its writable state (SQLite DB, VAPID keys,
|
||||
// transcript snapshots) to the shared user-global `~/.claude/agent-dashboard/`
|
||||
// — outside the read-only `.app`/installed bundle AND identical to what
|
||||
// `npm start`/`npm run dev` use, so the desktop app and the web app share ONE
|
||||
// database. We therefore no longer override DASHBOARD_DATA_DIR to this app's
|
||||
// private `userData/data`.
|
||||
//
|
||||
// Earlier desktop builds DID write there, so point the server's one-time
|
||||
// migration at that old per-user DB: on first launch with no shared DB yet,
|
||||
// it copies this app's accumulated history into the canonical location
|
||||
// (non-destructively — the old file is left untouched as a backup).
|
||||
if (!process.env.DASHBOARD_DATA_DIR && !process.env.DASHBOARD_LEGACY_DB_PATH) {
|
||||
const legacyDbPath = path.join(app.getPath("userData"), "data", "dashboard.db");
|
||||
if (fs.existsSync(legacyDbPath)) {
|
||||
process.env.DASHBOARD_LEGACY_DB_PATH = legacyDbPath;
|
||||
log.info("legacy desktop database available for migration", { legacyDbPath });
|
||||
}
|
||||
}
|
||||
|
||||
// Make sure server's `require("better-sqlite3")` finds the ABI-correct copy.
|
||||
ensureNativeModulesPatched();
|
||||
|
||||
log.info("starting embedded server", { port, serverEntry, appRoot });
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||
const serverModule = require(serverEntry) as ServerModule;
|
||||
|
||||
const expressApp = serverModule.createApp();
|
||||
const httpServer = await serverModule.startServer(expressApp, port);
|
||||
|
||||
await waitForHealthy(port);
|
||||
log.info("embedded server healthy", { port });
|
||||
|
||||
// Bring up the same background services the standalone server path runs.
|
||||
// Skipped automatically on a "Restart Server" via the one-time guard.
|
||||
bootstrapOwnedServer(appRoot, serverModule);
|
||||
|
||||
return {
|
||||
url: `http://127.0.0.1:${port}`,
|
||||
port,
|
||||
ownedByUs: true,
|
||||
stop: () =>
|
||||
new Promise<void>((resolve) => {
|
||||
try {
|
||||
httpServer.close(() => resolve());
|
||||
// Force-close lingering websocket connections after a short grace.
|
||||
setTimeout(() => resolve(), 2000).unref();
|
||||
} catch {
|
||||
resolve();
|
||||
}
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
/**
|
||||
* @file Recover the user's real shell `PATH`.
|
||||
*
|
||||
* A macOS app launched from Finder/Dock (or the Login Items auto-start) is
|
||||
* spawned by `launchd`, which gives it a minimal `PATH` — roughly
|
||||
* `/usr/bin:/bin:/usr/sbin:/sbin`. It does **not** source the user's shell
|
||||
* profile (`.zshrc` / `.zprofile` / `.bash_profile`).
|
||||
*
|
||||
* The dashboard's "Run Claude" feature spawns the `claude` CLI, which is
|
||||
* almost always installed somewhere only the shell `PATH` knows about —
|
||||
* `/opt/homebrew/bin`, `~/.local/bin`, `~/.claude/local`, a Node
|
||||
* version-manager's bin dir, etc. Under the minimal `launchd` `PATH`,
|
||||
* `which claude` fails and the dashboard reports *"the `claude` CLI isn't on
|
||||
* your PATH"* — even though the exact same server works when started from a
|
||||
* terminal, because a terminal hands down the full shell `PATH`.
|
||||
*
|
||||
* We run the user's login shell once at startup, capture its `PATH`, and merge
|
||||
* it into `process.env.PATH`. The embedded server runs in this same process,
|
||||
* so it (and every `claude` it spawns) inherits the corrected `PATH`.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
/* =============================================================================
|
||||
* MODULE_GUIDE — extended in-file reference (comments only; safe to read, never executed)
|
||||
* =============================================================================
|
||||
* **Purpose:** Dashboard module consumed by the React client, MCP tools, or desktop shell depending on deployment mode.
|
||||
*
|
||||
* ## Design constraints
|
||||
* - Local-first: no telemetry leaves the machine unless the user configures webhooks.
|
||||
* - Fail-safe hooks path on the server must never block Claude Code; UI mirrors that
|
||||
* philosophy by degrading gracefully (empty states, stale badges, reconnect loops).
|
||||
* - Destructive flows stay behind explicit confirmation modals and server-side gates.
|
||||
* - Internationalization: user-visible strings belong in i18n JSON, not literals here.
|
||||
*
|
||||
* ## Remote data & SSH
|
||||
* Remote Data Sources let operators aggregate multiple machines. SSH entries describe
|
||||
* how to reach a peer dashboard; the global data scope (`dataScope.ts`) narrows every
|
||||
* scoped GET via `?sources=`. Health checks and import history surface in Settings.
|
||||
*
|
||||
* ## Observability
|
||||
* Prometheus scrapes `GET /api/metrics` (see `monitoring/`). Grafana ships four
|
||||
* provisioned boards (overview, sessions, tools, alerts). Native npm scripts and
|
||||
* Docker Compose profiles are documented in `monitoring/README.md`.
|
||||
*
|
||||
* ## Internal dependencies
|
||||
* - `./logger`
|
||||
*
|
||||
* ## Public surface
|
||||
* - `ensureUserPath` — exported API; see TSDoc on the symbol for behavior.
|
||||
*
|
||||
* ## Testing pointers
|
||||
* - Prefer colocated `__tests__` with Vitest + Testing Library for UI.
|
||||
* - Server contract changes require `npm run test:server` and OpenAPI sync.
|
||||
* - MCP edits: `npm run mcp:typecheck` and `npm run mcp:build`.
|
||||
*
|
||||
* ## Related docs
|
||||
* - `ARCHITECTURE.md` — hooks → API → SQLite → WebSocket → UI pipeline.
|
||||
* - `docs/API.md` — REST reference.
|
||||
* - `.claude/skills/file-headers/` — mandatory `@author` header policy.
|
||||
* ============================================================================= */
|
||||
/* -----------------------------------------------------------------------------
|
||||
* EXPORT CATALOG — quick index of symbols defined below (documentation only).
|
||||
* -----------------------------------------------------------------------------
|
||||
* **ensureUserPath**
|
||||
* Part of this module's public contract. Downstream imports should treat
|
||||
* the signature and return type as stable unless release notes say otherwise.
|
||||
* When behavior changes, update the `@file` overview and relevant tests.
|
||||
*
|
||||
* ----------------------------------------------------------------------------- */
|
||||
|
||||
import { spawnSync } from "node:child_process";
|
||||
import * as os from "node:os";
|
||||
import * as path from "node:path";
|
||||
|
||||
import { log } from "./logger";
|
||||
|
||||
// Markers fence the PATH off from any shell-startup noise (banners, MOTD, …).
|
||||
// An interactive login shell may print arbitrary text before running our
|
||||
// `-c` command (e.g. a `.zshrc` `neofetch` call); scanning for this sentinel
|
||||
// pair — rather than trusting the last line of stdout — makes extraction
|
||||
// robust to whatever the user's shell profile prints.
|
||||
const DELIM = "__CCAM_SHELL_PATH__";
|
||||
|
||||
/**
|
||||
* Run the user's login+interactive shell and capture its `PATH`. Returns null
|
||||
* on any failure (timeout, missing shell, unparseable output).
|
||||
*/
|
||||
function loginShellPath(): string | null {
|
||||
if (process.platform === "win32") return null;
|
||||
const shell = process.env.SHELL || "/bin/zsh";
|
||||
try {
|
||||
// -i interactive (sources .zshrc/.bashrc), -l login (sources .zprofile),
|
||||
// -c command. printf avoids the trailing newline `echo` would add.
|
||||
const res = spawnSync(shell, ["-ilc", `printf '%s' "${DELIM}$PATH${DELIM}"`], {
|
||||
encoding: "utf8",
|
||||
timeout: 5000,
|
||||
});
|
||||
const out = `${res.stdout || ""}`;
|
||||
const start = out.indexOf(DELIM);
|
||||
const end = out.indexOf(DELIM, start + DELIM.length);
|
||||
if (start === -1 || end === -1) return null;
|
||||
const captured = out.slice(start + DELIM.length, end).trim();
|
||||
return captured || null;
|
||||
} catch (err) {
|
||||
log.warn("could not capture login-shell PATH", err);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge the login-shell `PATH` — plus the common directories CLIs install
|
||||
* into — onto `process.env.PATH`. Idempotent: deduplicates entries, so it is
|
||||
* safe even if called more than once. No-op on Windows.
|
||||
*/
|
||||
export function ensureUserPath(): void {
|
||||
if (process.platform === "win32") return;
|
||||
|
||||
const ordered: string[] = [];
|
||||
const seen = new Set<string>();
|
||||
const add = (value?: string | null): void => {
|
||||
if (!value) return;
|
||||
for (const seg of value.split(path.delimiter)) {
|
||||
if (seg && !seen.has(seg)) {
|
||||
seen.add(seg);
|
||||
ordered.push(seg);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// 1. The user's real shell PATH — the authoritative source.
|
||||
add(loginShellPath());
|
||||
|
||||
// 2. Common install locations, as a fallback if the shell capture missed
|
||||
// them (or failed entirely).
|
||||
const home = os.homedir();
|
||||
add(
|
||||
[
|
||||
"/opt/homebrew/bin",
|
||||
"/usr/local/bin",
|
||||
path.join(home, ".local", "bin"),
|
||||
path.join(home, ".claude", "local"),
|
||||
path.join(home, ".bun", "bin"),
|
||||
path.join(home, ".deno", "bin"),
|
||||
path.join(home, ".npm-global", "bin"),
|
||||
].join(path.delimiter)
|
||||
);
|
||||
|
||||
// 3. Whatever launchd already gave us, last.
|
||||
add(process.env.PATH);
|
||||
|
||||
process.env.PATH = ordered.join(path.delimiter);
|
||||
log.info("user PATH resolved for spawned CLIs", { entries: ordered.length });
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
/**
|
||||
* @file Menu-bar / notification-area (system tray) icon and its context menu.
|
||||
*
|
||||
* The tray is the "always-on" surface of the app. A single click opens the
|
||||
* menu showing live status snapshots from the embedded server plus an Open
|
||||
* Dashboard action.
|
||||
*
|
||||
* The image is platform-specific: macOS uses a black "template" PNG so the OS
|
||||
* tints it for light/dark menu bars; Windows uses the colored `icon.ico`,
|
||||
* because a black template glyph would be invisible on the (usually dark)
|
||||
* Windows taskbar notification area.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
/* =============================================================================
|
||||
* MODULE_GUIDE — extended in-file reference (comments only; safe to read, never executed)
|
||||
* =============================================================================
|
||||
* **Purpose:** Dashboard module consumed by the React client, MCP tools, or desktop shell depending on deployment mode.
|
||||
*
|
||||
* ## Design constraints
|
||||
* - Local-first: no telemetry leaves the machine unless the user configures webhooks.
|
||||
* - Fail-safe hooks path on the server must never block Claude Code; UI mirrors that
|
||||
* philosophy by degrading gracefully (empty states, stale badges, reconnect loops).
|
||||
* - Destructive flows stay behind explicit confirmation modals and server-side gates.
|
||||
* - Internationalization: user-visible strings belong in i18n JSON, not literals here.
|
||||
*
|
||||
* ## Remote data & SSH
|
||||
* Remote Data Sources let operators aggregate multiple machines. SSH entries describe
|
||||
* how to reach a peer dashboard; the global data scope (`dataScope.ts`) narrows every
|
||||
* scoped GET via `?sources=`. Health checks and import history surface in Settings.
|
||||
*
|
||||
* ## Observability
|
||||
* Prometheus scrapes `GET /api/metrics` (see `monitoring/`). Grafana ships four
|
||||
* provisioned boards (overview, sessions, tools, alerts). Native npm scripts and
|
||||
* Docker Compose profiles are documented in `monitoring/README.md`.
|
||||
*
|
||||
* ## Internal dependencies
|
||||
* - `./constants`
|
||||
* - `./logger`
|
||||
*
|
||||
* ## Public surface
|
||||
* - `TrayActions` — exported API; see TSDoc on the symbol for behavior.
|
||||
* - `ServerSnapshot` — exported API; see TSDoc on the symbol for behavior.
|
||||
* - `createTray` — exported API; see TSDoc on the symbol for behavior.
|
||||
*
|
||||
* ## Testing pointers
|
||||
* - Prefer colocated `__tests__` with Vitest + Testing Library for UI.
|
||||
* - Server contract changes require `npm run test:server` and OpenAPI sync.
|
||||
* - MCP edits: `npm run mcp:typecheck` and `npm run mcp:build`.
|
||||
*
|
||||
* ## Related docs
|
||||
* - `ARCHITECTURE.md` — hooks → API → SQLite → WebSocket → UI pipeline.
|
||||
* - `docs/API.md` — REST reference.
|
||||
* - `.claude/skills/file-headers/` — mandatory `@author` header policy.
|
||||
* ============================================================================= */
|
||||
/* -----------------------------------------------------------------------------
|
||||
* EXPORT CATALOG — quick index of symbols defined below (documentation only).
|
||||
* -----------------------------------------------------------------------------
|
||||
* **TrayActions**
|
||||
* Part of this module's public contract. Downstream imports should treat
|
||||
* the signature and return type as stable unless release notes say otherwise.
|
||||
* When behavior changes, update the `@file` overview and relevant tests.
|
||||
*
|
||||
* **ServerSnapshot**
|
||||
* Part of this module's public contract. Downstream imports should treat
|
||||
* the signature and return type as stable unless release notes say otherwise.
|
||||
* When behavior changes, update the `@file` overview and relevant tests.
|
||||
*
|
||||
* **createTray**
|
||||
* Part of this module's public contract. Downstream imports should treat
|
||||
* the signature and return type as stable unless release notes say otherwise.
|
||||
* When behavior changes, update the `@file` overview and relevant tests.
|
||||
*
|
||||
* ----------------------------------------------------------------------------- */
|
||||
|
||||
import { Menu, Tray, app, nativeImage } from "electron";
|
||||
import * as path from "node:path";
|
||||
|
||||
import { APP_NAME } from "./constants";
|
||||
import { log } from "./logger";
|
||||
|
||||
/** Callbacks the tray menu wires to its rows. `main.ts` supplies these —
|
||||
* several are shared verbatim with `installApplicationMenu`'s `MenuActions`
|
||||
* so the tray and the application menu never disagree about behavior. */
|
||||
export interface TrayActions {
|
||||
/** Bring the dashboard window to front, creating it if it doesn't exist. */
|
||||
showDashboard: () => void;
|
||||
/** Stop and re-launch the embedded server, then reload the window. */
|
||||
restartServer: () => void;
|
||||
/** Reveal `desktop.log` in the OS file browser. */
|
||||
openLogs: () => void;
|
||||
/** Open the dashboard URL in the user's default system browser. */
|
||||
openInBrowser: () => void;
|
||||
/** Flip the OS auto-start-at-login registration. */
|
||||
toggleOpenAtLogin: () => void;
|
||||
/** Read the current auto-start state, used to render the checkbox. */
|
||||
isOpenAtLogin: () => boolean;
|
||||
/** The embedded server's live port, or `null` before it has started. */
|
||||
serverPort: () => number | null;
|
||||
/** Last cached status snapshot (refreshed by the background poller). */
|
||||
getSnapshot: () => ServerSnapshot | null;
|
||||
/** Kick an immediate async snapshot refresh (fire-and-forget on menu open). */
|
||||
refreshSnapshot: () => void;
|
||||
/** Prompt the same quit-confirmation dialog ⌘Q triggers. */
|
||||
requestQuit: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Structurally identical to `server-host.ts`'s `ServerSnapshot` — redeclared
|
||||
* here so this module has no compile-time dependency on `server-host.ts`,
|
||||
* only on the `TrayActions` callbacks `main.ts` wires between them. `main.ts`
|
||||
* passes `getServerSnapshot`/`refreshServerSnapshot` straight through, so the
|
||||
* two types must stay in sync by hand if the stats API response shape changes.
|
||||
*/
|
||||
export interface ServerSnapshot {
|
||||
activeSessions: number;
|
||||
workingAgents: number;
|
||||
eventsToday: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tray icon image location. In dev `__dirname` is `desktop/out/`, so `../assets`
|
||||
* resolves to `desktop/assets/`. In the packaged app the images ship outside
|
||||
* the asar archive via `extraResources` (see electron-builder.yml), so we
|
||||
* read them from `process.resourcesPath/assets/`. Loading these from inside
|
||||
* asar can yield empty `nativeImage` results, which is why we keep them
|
||||
* unpacked.
|
||||
*
|
||||
* Windows gets the colored `icon.ico`; macOS gets the black template PNG that
|
||||
* the menu bar tints automatically.
|
||||
*/
|
||||
/** Pick the platform-appropriate tray image filename — a colored `.ico` on
|
||||
* Windows (a black glyph would vanish on the usually-dark taskbar), or the
|
||||
* black "template" PNG on macOS (the menu bar auto-tints it for light/dark). */
|
||||
function trayImageFile(): string {
|
||||
return process.platform === "win32" ? "icon.ico" : "tray-icon-Template.png";
|
||||
}
|
||||
|
||||
/** Resolve `trayImageFile()` to an absolute path, branching on dev vs
|
||||
* packaged layout — see the file-level doc comment for why these assets are
|
||||
* read from disk (`extraResources`) rather than bundled inside the asar. */
|
||||
function trayImagePath(): string {
|
||||
const file = trayImageFile();
|
||||
if (app.isPackaged) {
|
||||
return path.join(process.resourcesPath, "assets", file);
|
||||
}
|
||||
return path.join(__dirname, "..", "assets", file);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the menu-bar / notification-area tray icon and wire its dropdown
|
||||
* menu. The menu is deliberately rebuilt from `actions` on every open (see
|
||||
* `showMenu` below) rather than mutated in place, so the port label, the
|
||||
* live `{sessions, agents, events-today}` snapshot, and the "Open at Login"
|
||||
* checkbox are always current — Electron menus have no live-binding, so a
|
||||
* cached template would show stale values until the app happened to rebuild
|
||||
* it for an unrelated reason.
|
||||
*
|
||||
* Left- and right-click both pop the same dropdown via `popUpContextMenu`
|
||||
* (`tray.on('click', ...)` and `tray.on('right-click', ...)`) instead of
|
||||
* `Tray#setContextMenu` — a static, pre-assigned menu that Electron shows
|
||||
* automatically on click, with no hook for the `refreshSnapshot()` call that
|
||||
* needs to run first so the dropdown reflects the very latest counts.
|
||||
*/
|
||||
export function createTray(actions: TrayActions): Tray {
|
||||
const imagePath = trayImagePath();
|
||||
const image = nativeImage.createFromPath(imagePath);
|
||||
if (image.isEmpty()) {
|
||||
log.warn("tray image is empty; falling back to in-memory placeholder", imagePath);
|
||||
} else if (process.platform === "darwin") {
|
||||
// Template tinting is a macOS concept; on Windows the icon is colored and
|
||||
// must be shown as-is.
|
||||
image.setTemplateImage(true);
|
||||
}
|
||||
|
||||
const tray = new Tray(image.isEmpty() ? nativeImage.createEmpty() : image);
|
||||
tray.setToolTip(APP_NAME);
|
||||
|
||||
// Singular/plural helper so "1 active session" doesn't read as "1 active sessions".
|
||||
const plural = (n: number, singular: string, pluralForm?: string): string =>
|
||||
`${n.toLocaleString()} ${n === 1 ? singular : (pluralForm ?? singular + "s")}`;
|
||||
|
||||
// Built fresh on each click so the port, status snapshot, and the
|
||||
// "Open at Login" checkbox always reflect current state. Snapshot rows
|
||||
// are intentionally `enabled` (with a click handler that opens the
|
||||
// dashboard) instead of `enabled: false` — disabled menu items get
|
||||
// dimmed by macOS, which looked sickly next to the actionable rows
|
||||
// below them. Clicking any row now lands on the dashboard where the
|
||||
// user can see the same numbers in context.
|
||||
const buildMenu = (): Menu => {
|
||||
const port = actions.serverPort();
|
||||
const portLabel = port ? `🟢 Listening on :${port}` : "🔴 Server not running";
|
||||
const snap = actions.getSnapshot();
|
||||
const open = (): void => actions.showDashboard();
|
||||
const snapshotItems: Electron.MenuItemConstructorOptions[] = snap
|
||||
? [
|
||||
{ type: "separator" },
|
||||
{ label: `📊 ${plural(snap.activeSessions, "active session")}`, click: open },
|
||||
{ label: `🤖 ${plural(snap.workingAgents, "working agent")}`, click: open },
|
||||
{ label: `📥 ${plural(snap.eventsToday, "event")} today`, click: open },
|
||||
]
|
||||
: [{ type: "separator" }, { label: "Snapshot unavailable", enabled: false }];
|
||||
|
||||
return Menu.buildFromTemplate([
|
||||
{ label: APP_NAME, enabled: false },
|
||||
{ label: portLabel, enabled: false },
|
||||
...snapshotItems,
|
||||
{ type: "separator" },
|
||||
{ label: "Open Dashboard", accelerator: "CmdOrCtrl+O", click: open },
|
||||
{ label: "Open in Browser…", click: () => actions.openInBrowser() },
|
||||
{ type: "separator" },
|
||||
{ label: "Restart Server", click: () => actions.restartServer() },
|
||||
{ label: "Show Logs", click: () => actions.openLogs() },
|
||||
{ type: "separator" },
|
||||
{
|
||||
label: "Open at Login",
|
||||
type: "checkbox",
|
||||
checked: actions.isOpenAtLogin(),
|
||||
click: () => actions.toggleOpenAtLogin(),
|
||||
},
|
||||
{ type: "separator" },
|
||||
{ label: `Version ${app.getVersion()}`, enabled: false },
|
||||
{
|
||||
label: "Quit Claude Code Monitor",
|
||||
accelerator: "CmdOrCtrl+Q",
|
||||
click: () => actions.requestQuit(),
|
||||
},
|
||||
]);
|
||||
};
|
||||
|
||||
// Single click (left or right) opens the menu — the conventional macOS
|
||||
// menu-bar utility pattern. Opening the dashboard is the first action in
|
||||
// the menu, so it's still one click + Enter to surface the window.
|
||||
// We kick an async refresh on open so the next interaction reflects the
|
||||
// very latest counts; this open renders the most recent cached snapshot.
|
||||
const showMenu = (): void => {
|
||||
actions.refreshSnapshot();
|
||||
tray.popUpContextMenu(buildMenu());
|
||||
};
|
||||
tray.on("click", showMenu);
|
||||
tray.on("right-click", showMenu);
|
||||
return tray;
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
/**
|
||||
* @file Dashboard window creation + state persistence.
|
||||
*
|
||||
* We persist size/position to a JSON file under `app.getPath('userData')`.
|
||||
* Avoids the `electron-window-state` dependency for ~30 lines of code.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
/* =============================================================================
|
||||
* MODULE_GUIDE — extended in-file reference (comments only; safe to read, never executed)
|
||||
* =============================================================================
|
||||
* **Purpose:** Dashboard module consumed by the React client, MCP tools, or desktop shell depending on deployment mode.
|
||||
*
|
||||
* ## Design constraints
|
||||
* - Local-first: no telemetry leaves the machine unless the user configures webhooks.
|
||||
* - Fail-safe hooks path on the server must never block Claude Code; UI mirrors that
|
||||
* philosophy by degrading gracefully (empty states, stale badges, reconnect loops).
|
||||
* - Destructive flows stay behind explicit confirmation modals and server-side gates.
|
||||
* - Internationalization: user-visible strings belong in i18n JSON, not literals here.
|
||||
*
|
||||
* ## Remote data & SSH
|
||||
* Remote Data Sources let operators aggregate multiple machines. SSH entries describe
|
||||
* how to reach a peer dashboard; the global data scope (`dataScope.ts`) narrows every
|
||||
* scoped GET via `?sources=`. Health checks and import history surface in Settings.
|
||||
*
|
||||
* ## Observability
|
||||
* Prometheus scrapes `GET /api/metrics` (see `monitoring/`). Grafana ships four
|
||||
* provisioned boards (overview, sessions, tools, alerts). Native npm scripts and
|
||||
* Docker Compose profiles are documented in `monitoring/README.md`.
|
||||
*
|
||||
* ## Internal dependencies
|
||||
* - `./constants`
|
||||
* - `./logger`
|
||||
*
|
||||
* ## Public surface
|
||||
* - `appIconPath` — exported API; see TSDoc on the symbol for behavior.
|
||||
* - `createDashboardWindow` — exported API; see TSDoc on the symbol for behavior.
|
||||
*
|
||||
* ## Testing pointers
|
||||
* - Prefer colocated `__tests__` with Vitest + Testing Library for UI.
|
||||
* - Server contract changes require `npm run test:server` and OpenAPI sync.
|
||||
* - MCP edits: `npm run mcp:typecheck` and `npm run mcp:build`.
|
||||
*
|
||||
* ## Related docs
|
||||
* - `ARCHITECTURE.md` — hooks → API → SQLite → WebSocket → UI pipeline.
|
||||
* - `docs/API.md` — REST reference.
|
||||
* - `.claude/skills/file-headers/` — mandatory `@author` header policy.
|
||||
* ============================================================================= */
|
||||
/* -----------------------------------------------------------------------------
|
||||
* EXPORT CATALOG — quick index of symbols defined below (documentation only).
|
||||
* -----------------------------------------------------------------------------
|
||||
* **appIconPath**
|
||||
* Part of this module's public contract. Downstream imports should treat
|
||||
* the signature and return type as stable unless release notes say otherwise.
|
||||
* When behavior changes, update the `@file` overview and relevant tests.
|
||||
*
|
||||
* **createDashboardWindow**
|
||||
* Part of this module's public contract. Downstream imports should treat
|
||||
* the signature and return type as stable unless release notes say otherwise.
|
||||
* When behavior changes, update the `@file` overview and relevant tests.
|
||||
*
|
||||
* ----------------------------------------------------------------------------- */
|
||||
|
||||
import { BrowserWindow, app, shell } from "electron";
|
||||
import * as fs from "node:fs";
|
||||
import * as path from "node:path";
|
||||
|
||||
import { APP_NAME, DEFAULT_WINDOW } from "./constants";
|
||||
import { log } from "./logger";
|
||||
|
||||
/** Persisted window geometry. `x`/`y` are omitted until the window has been
|
||||
* moved at least once — a fresh install lets Electron pick the OS default
|
||||
* placement rather than forcing `(0, 0)`. */
|
||||
interface WindowState {
|
||||
width: number;
|
||||
height: number;
|
||||
x?: number;
|
||||
y?: number;
|
||||
}
|
||||
|
||||
/** Absolute path to the JSON file geometry is persisted to, under this
|
||||
* platform's `userData` directory (e.g. `~/Library/Application Support/…`
|
||||
* on macOS, `%APPDATA%` on Windows). */
|
||||
function statePath(): string {
|
||||
return path.join(app.getPath("userData"), "window-state.json");
|
||||
}
|
||||
|
||||
/**
|
||||
* Absolute path to the colored application icon used for the window title bar
|
||||
* and the Windows taskbar / Linux launcher — the same logo the macOS app shows
|
||||
* in its Dock (rendered from `assets/icon.svg`). Without this, an unpackaged
|
||||
* `electron out/main.js` run falls back to the generic Electron icon.
|
||||
*
|
||||
* Windows wants the multi-size `.ico` (crisp at every taskbar scale); other
|
||||
* platforms take the `.png`. macOS ignores `BrowserWindow#icon` entirely (its
|
||||
* window has no icon and the Dock uses the bundle's `.icns`), so the value is
|
||||
* harmless there. Resolves dev (`desktop/assets`) vs packaged
|
||||
* (`Resources/assets`, shipped via `extraResources`); returns `undefined` if
|
||||
* the file is absent so we cleanly fall back instead of throwing.
|
||||
*/
|
||||
export function appIconPath(): string | undefined {
|
||||
const file = process.platform === "win32" ? "icon.ico" : "icon.png";
|
||||
const base = app.isPackaged
|
||||
? path.join(process.resourcesPath, "assets")
|
||||
: path.join(__dirname, "..", "assets");
|
||||
const p = path.join(base, file);
|
||||
return fs.existsSync(p) ? p : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the persisted window geometry, falling back field-by-field to
|
||||
* `DEFAULT_WINDOW` (and to `undefined` for position) whenever the file is
|
||||
* missing, unreadable, or contains a field of the wrong type — so a
|
||||
* corrupted or partially-written state file degrades gracefully instead of
|
||||
* preventing the window from opening at all.
|
||||
*/
|
||||
function loadState(): WindowState {
|
||||
try {
|
||||
const raw = fs.readFileSync(statePath(), "utf8");
|
||||
const parsed = JSON.parse(raw) as Partial<WindowState>;
|
||||
return {
|
||||
width: typeof parsed.width === "number" ? parsed.width : DEFAULT_WINDOW.width,
|
||||
height: typeof parsed.height === "number" ? parsed.height : DEFAULT_WINDOW.height,
|
||||
x: typeof parsed.x === "number" ? parsed.x : undefined,
|
||||
y: typeof parsed.y === "number" ? parsed.y : undefined,
|
||||
};
|
||||
} catch {
|
||||
return { width: DEFAULT_WINDOW.width, height: DEFAULT_WINDOW.height };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Write the window's current bounds to `statePath()`. Skipped while the
|
||||
* window is destroyed or minimized, since `getBounds()` on a minimized
|
||||
* window reports the pre-minimize size on some platforms — persisting it
|
||||
* would silently discard the user's last real resize/move. Failures (e.g.
|
||||
* a read-only `userData` dir) are logged, not thrown — losing the saved
|
||||
* geometry is cosmetic, not fatal.
|
||||
*/
|
||||
function saveState(win: BrowserWindow): void {
|
||||
if (win.isDestroyed() || win.isMinimized()) return;
|
||||
const { width, height, x, y } = win.getBounds();
|
||||
try {
|
||||
fs.writeFileSync(statePath(), JSON.stringify({ width, height, x, y }));
|
||||
} catch (err) {
|
||||
log.warn("could not persist window state", err);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the single dashboard `BrowserWindow` and point it at the embedded
|
||||
* server's origin. Restores the last persisted size/position (see
|
||||
* `loadState`), re-saves it (debounced) on every resize/move/close, routes
|
||||
* all external navigation to the system browser instead of inside Electron,
|
||||
* and defers `show()` until `ready-to-show` so the window never flashes an
|
||||
* unstyled blank frame while the page loads.
|
||||
*
|
||||
* @param targetUrl The embedded server's origin, e.g. `http://127.0.0.1:4820`.
|
||||
* @returns The newly created, not-yet-visible `BrowserWindow`.
|
||||
*/
|
||||
export function createDashboardWindow(targetUrl: string): BrowserWindow {
|
||||
const state = loadState();
|
||||
|
||||
const win = new BrowserWindow({
|
||||
width: state.width,
|
||||
height: state.height,
|
||||
x: state.x,
|
||||
y: state.y,
|
||||
minWidth: 720,
|
||||
minHeight: 480,
|
||||
show: false,
|
||||
title: APP_NAME,
|
||||
// Colored app logo for the title bar + taskbar (matches the macOS Dock
|
||||
// icon). No-op on macOS; falls through to the Electron default if missing.
|
||||
icon: appIconPath(),
|
||||
// Use the standard macOS title bar rather than `hiddenInset`. With a hidden
|
||||
// title bar the traffic-light buttons float directly over the React app's
|
||||
// top edge and visually blend into the dashboard chrome; a native title bar
|
||||
// gives them their own clearly-separated row, shows the app name, and
|
||||
// restores the conventional double-click-to-maximize / drag-from-anywhere
|
||||
// behaviour without needing custom drag regions in the renderer.
|
||||
titleBarStyle: "default",
|
||||
backgroundColor: "#0b0f1a",
|
||||
webPreferences: {
|
||||
preload: path.join(__dirname, "preload.js"),
|
||||
contextIsolation: true,
|
||||
nodeIntegration: false,
|
||||
sandbox: false,
|
||||
// We're loading our own localhost-only origin, never remote content.
|
||||
webSecurity: true,
|
||||
},
|
||||
});
|
||||
|
||||
win.once("ready-to-show", () => win.show());
|
||||
|
||||
// Persist size/position on resize/move (debounced via the close handler too).
|
||||
let saveTimer: NodeJS.Timeout | null = null;
|
||||
const debounced = () => {
|
||||
if (saveTimer) clearTimeout(saveTimer);
|
||||
saveTimer = setTimeout(() => saveState(win), 400);
|
||||
};
|
||||
win.on("resize", debounced);
|
||||
win.on("move", debounced);
|
||||
win.on("close", () => saveState(win));
|
||||
|
||||
// External links open in the user's browser, not inside Electron.
|
||||
win.webContents.setWindowOpenHandler(({ url }) => {
|
||||
void shell.openExternal(url);
|
||||
return { action: "deny" };
|
||||
});
|
||||
win.webContents.on("will-navigate", (event, url) => {
|
||||
if (!url.startsWith(targetUrl)) {
|
||||
event.preventDefault();
|
||||
void shell.openExternal(url);
|
||||
}
|
||||
});
|
||||
|
||||
win.loadURL(targetUrl).catch((err) => log.error("failed to load dashboard URL", err));
|
||||
return win;
|
||||
}
|
||||
Reference in New Issue
Block a user