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,10 @@
|
||||
node_modules/
|
||||
out/
|
||||
release/
|
||||
*.log
|
||||
.DS_Store
|
||||
|
||||
# Generated icon binaries — regenerable from assets/icon.svg via scripts/build-icons.sh.
|
||||
# Committed copies live alongside the SVG so users without iconutil can still build.
|
||||
# Local rebuilds are ignored.
|
||||
assets/icon.iconset/
|
||||
@@ -0,0 +1,833 @@
|
||||
# `desktop/` — Native macOS App (Electron)
|
||||
|
||||
The **desktop workspace** ships the Claude Code Agent Monitor dashboard as a
|
||||
native macOS `.app` (distributed as a `.dmg`). It is an Electron shell that
|
||||
**embeds the existing Express server in-process** and renders the already-built
|
||||
React client in a `BrowserWindow`.
|
||||
|
||||
> **One-line mental model:** *Electron is a window onto the same code.* The
|
||||
> desktop app does not reimplement the dashboard — it `require()`s
|
||||
> `server/index.js` directly, in the same Node runtime as the Electron main
|
||||
> process, and points a Chromium window at it.
|
||||
|
||||
For the **user-facing** guide (download, install, Gatekeeper, tray menu,
|
||||
auto-start) see [`../DESKTOP.md`](../DESKTOP.md). This file is the
|
||||
**contributor / architecture** reference.
|
||||
|
||||
---
|
||||
|
||||
## Table of contents
|
||||
|
||||
- [TL;DR](#tldr)
|
||||
- [Where the desktop app sits](#where-the-desktop-app-sits)
|
||||
- [Process model](#process-model)
|
||||
- [Boot lifecycle](#boot-lifecycle)
|
||||
- [Server hosting & port discovery](#server-hosting--port-discovery)
|
||||
- [`better-sqlite3` native-module handling](#better-sqlite3-native-module-handling)
|
||||
- [Background services & hook bootstrap](#background-services--hook-bootstrap)
|
||||
- [Window, tray & menu](#window-tray--menu)
|
||||
- [Auto-start (Login Items)](#auto-start-login-items)
|
||||
- [Source tree](#source-tree)
|
||||
- [Packaged app layout](#packaged-app-layout)
|
||||
- [Build pipeline](#build-pipeline)
|
||||
- [Commands](#commands)
|
||||
- [Build performance — read this](#build-performance--read-this)
|
||||
- [Code signing & notarization](#code-signing--notarization)
|
||||
- [Continuous integration](#continuous-integration)
|
||||
- [Smoke test](#smoke-test)
|
||||
- [Environment variables](#environment-variables)
|
||||
- [Logs & troubleshooting](#logs--troubleshooting)
|
||||
- [What this workspace does *not* touch](#what-this-workspace-does-not-touch)
|
||||
|
||||
---
|
||||
|
||||
## TL;DR
|
||||
|
||||
```bash
|
||||
# From the repo root:
|
||||
npm run setup # install root + client deps, build client, install hooks
|
||||
npm run build # build client/dist (the SPA the Electron window loads)
|
||||
npm run desktop:install # install Electron, electron-builder, types into desktop/
|
||||
npm run desktop:dev # tsc → launch Electron pointing at out/main.js
|
||||
npm run desktop:test # smoke test (spawn Electron + probe /api/health)
|
||||
|
||||
# Build a DMG (macOS):
|
||||
npm run desktop:dmg # both per-arch DMGs (arm64 + x64) — correct for release, SLOWER
|
||||
npm run desktop:dmg:arm64 # Apple Silicon only — fast, for your own machine
|
||||
npm run desktop:dmg:x64 # Intel only — fast
|
||||
|
||||
# Build a Windows .exe (run on Windows x64):
|
||||
npm run desktop:win # NSIS installer → release/ClaudeCodeMonitor-Setup-<ver>-x64.exe
|
||||
npm run desktop:win:portable # no-install portable → release/ClaudeCodeMonitor-<ver>-x64-portable.exe
|
||||
```
|
||||
|
||||
> ⚠️ `desktop:dmg` is slower because it builds the app **twice** — once per
|
||||
> architecture — and emits **two** per-arch DMGs (`arm64` + `x64`). It does not
|
||||
> merge them into a universal binary. For running on your own Mac, use the
|
||||
> arch-specific command. See [Build performance](#build-performance--read-this).
|
||||
|
||||
> 🪟 **Windows builds run on Windows** (DMGs build on macOS). `desktop:win`
|
||||
> produces an **unsigned** installer — fine to run; SmartScreen may show a
|
||||
> "More info → Run anyway" prompt on first launch. The icon (`assets/icon.ico`)
|
||||
> is generated from `assets/icon.png` by `npm run build:win-icon`
|
||||
> (PowerShell + .NET, no extra tooling). `better-sqlite3` is fetched as a
|
||||
> prebuilt Electron binary by `npm run desktop:install`, so no Visual Studio
|
||||
> C++ toolchain is required for the common case. If that fetch/rebuild *does*
|
||||
> fail (no C++ toolchain, or a Node version with no prebuilt binary),
|
||||
> `npm run desktop:install` — and any `desktop:*` build, gated by `prebuild.js` —
|
||||
> prints the exact per-OS prerequisite (Windows: Visual Studio Build Tools with
|
||||
> the "Desktop development with C++" workload; macOS: `xcode-select --install`;
|
||||
> Linux: build-essential + python3) plus a no-toolchain alternative, then exits
|
||||
> non-zero rather than crashing at runtime:
|
||||
>
|
||||
> ```bash
|
||||
> cd desktop
|
||||
> npm install --ignore-scripts
|
||||
> node node_modules/electron/install.js
|
||||
> npx electron-builder install-app-deps
|
||||
> ```
|
||||
>
|
||||
> A Node LTS (20/22) ships prebuilt binaries and avoids the compile entirely.
|
||||
|
||||
---
|
||||
|
||||
## Where the desktop app sits
|
||||
|
||||
`desktop/` is a **sibling workspace** — not a npm-workspaces conversion. It has
|
||||
its own `package.json`, its own `node_modules`, and its own toolchain. It
|
||||
consumes the rest of the repo as plain files.
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
subgraph repo["Claude-Code-Agent-Monitor (repo root)"]
|
||||
server["server/<br/>Express API · SQLite · WebSocket"]
|
||||
client["client/<br/>React + Vite SPA"]
|
||||
scripts["scripts/<br/>hook installer/handler, import, seed"]
|
||||
mcp["mcp/<br/>local MCP server"]
|
||||
vscode["vscode-extension/"]
|
||||
desktop["desktop/<br/>★ Electron shell (this workspace)"]
|
||||
end
|
||||
|
||||
desktop -- "require() in-process" --> server
|
||||
desktop -- "loads built SPA from" --> client
|
||||
desktop -- "auto-installs hooks via" --> scripts
|
||||
server -- "serves static" --> client
|
||||
|
||||
style desktop fill:#1f6feb,stroke:#1158c7,color:#fff
|
||||
style server fill:#238636,stroke:#196c2e,color:#fff
|
||||
```
|
||||
|
||||
The desktop app touches **no other workspace's runtime behavior**. The only
|
||||
change outside `desktop/` is a behavior-preserving refactor of
|
||||
`server/index.js` (see [the last section](#what-this-workspace-does-not-touch)).
|
||||
|
||||
---
|
||||
|
||||
## Process model
|
||||
|
||||
Electron runs a **main process** (Node.js) and one or more **renderer
|
||||
processes** (Chromium). In this app:
|
||||
|
||||
- The **main process** hosts the embedded Express server *and* manages the
|
||||
window, tray, and menus. There is **no child process and no IPC** for the
|
||||
server — it runs inside the main process's own event loop.
|
||||
- The **renderer** is just Chromium loading `http://127.0.0.1:<port>` — exactly
|
||||
the same origin a normal browser would. The `preload.ts` is intentionally
|
||||
empty, so the renderer has zero privileged surface.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
subgraph main["Electron Main Process (Node 22 / Electron 35)"]
|
||||
boot["main.ts<br/>lifecycle"]
|
||||
host["server-host.ts<br/>embedded server"]
|
||||
express["server/index.js<br/>Express + WS + SQLite"]
|
||||
tray["tray.ts"]
|
||||
menu["menu.ts"]
|
||||
host --> express
|
||||
boot --> host
|
||||
boot --> tray
|
||||
boot --> menu
|
||||
end
|
||||
|
||||
subgraph renderer["Renderer Process (Chromium)"]
|
||||
win["BrowserWindow<br/>React dashboard"]
|
||||
preload["preload.ts<br/>(empty — no bridge)"]
|
||||
end
|
||||
|
||||
express -- "http + ws on 127.0.0.1:port" --> win
|
||||
win -.->|loads| preload
|
||||
|
||||
hooks["Claude Code hooks<br/>(separate node processes)"] -- "POST /api/hooks/event" --> express
|
||||
|
||||
style main fill:#0d1117,stroke:#30363d,color:#e6edf3
|
||||
style renderer fill:#161b22,stroke:#30363d,color:#e6edf3
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Boot lifecycle
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
autonumber
|
||||
participant OS as macOS
|
||||
participant Main as main.ts
|
||||
participant Host as server-host.ts
|
||||
participant Srv as server/index.js
|
||||
participant UI as BrowserWindow
|
||||
|
||||
OS->>Main: launch app
|
||||
Main->>Main: requestSingleInstanceLock()
|
||||
alt lock not acquired
|
||||
Main->>OS: exit(0) — focus existing instance
|
||||
end
|
||||
Main->>Host: startEmbeddedServer()
|
||||
Host->>Host: probe port 4820 — adopt if a healthy server answers
|
||||
alt no server to adopt
|
||||
Host->>Host: pickFreePort() · patch better-sqlite3 ABI
|
||||
Host->>Srv: require() · createApp() · startServer(port)
|
||||
Host->>Srv: waitForHealthy() — poll /api/health
|
||||
Host->>Srv: bootstrapOwnedServer() — schedulers, cc-watcher, install hooks
|
||||
end
|
||||
Host-->>Main: ServerHandle { url, port, ownedByUs, stop }
|
||||
Main->>Main: installApplicationMenu() · createTray()
|
||||
alt launched at login
|
||||
Main->>OS: stay tray-only, hide dock
|
||||
else normal launch
|
||||
Main->>UI: createDashboardWindow(url)
|
||||
UI->>Srv: GET http://127.0.0.1:port
|
||||
end
|
||||
Note over Main: window "close" → hide (server keeps running)
|
||||
Note over Main: before-quit → stop server + closeEmbeddedDatabase()
|
||||
```
|
||||
|
||||
Key behaviors:
|
||||
|
||||
| Event | Behavior |
|
||||
|---|---|
|
||||
| Second launch | `requestSingleInstanceLock()` fails → the new process exits and the existing window is focused. |
|
||||
| Window close | Intercepted — the window **hides**, the server and tray keep running. |
|
||||
| `window-all-closed` | App stays alive (tray-only mode). |
|
||||
| Launched at login | The dashboard window is **not** shown — only the tray icon. |
|
||||
| `before-quit` | If we own the server: stop the HTTP server, then `closeEmbeddedDatabase()` for a clean WAL checkpoint, then `app.exit(0)`. |
|
||||
|
||||
---
|
||||
|
||||
## Server hosting & port discovery
|
||||
|
||||
`server-host.ts` is the **only file** that imports `server/index.js`. It picks
|
||||
a port, boots the server, and returns a `ServerHandle`.
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
start["startEmbeddedServer()"] --> forced{"CCAM_DESKTOP_BIND_PORT set?"}
|
||||
forced -->|yes| bind["bind exactly that port<br/>(no adoption, no fallback)"]
|
||||
forced -->|no| adopt{"healthy server<br/>already on :4820?"}
|
||||
adopt -->|yes| reuse["adopt it<br/>ownedByUs = false"]
|
||||
adopt -->|no| pick["pickFreePort()"]
|
||||
|
||||
pick --> p1{":4820 free?"}
|
||||
p1 -->|yes| use4820["use 4820"]
|
||||
p1 -->|no| p2{"any of<br/>:4821–:4829 free?"}
|
||||
p2 -->|yes| usefb["use that"]
|
||||
p2 -->|no| p3{"any of<br/>:49152–:49500 free?"}
|
||||
p3 -->|yes| userand["use that"]
|
||||
p3 -->|no| fail["throw — no free port"]
|
||||
|
||||
bind --> boot["createApp() + startServer()"]
|
||||
use4820 --> boot
|
||||
usefb --> boot
|
||||
userand --> boot
|
||||
boot --> healthy["waitForHealthy()<br/>poll /api/health ≤ 30s"]
|
||||
healthy --> bg["bootstrapOwnedServer()"]
|
||||
bg --> handle["ServerHandle ownedByUs = true"]
|
||||
reuse --> handleR["ServerHandle ownedByUs = false"]
|
||||
|
||||
style reuse fill:#9e6a03,stroke:#7d5300,color:#fff
|
||||
style fail fill:#da3633,stroke:#b62324,color:#fff
|
||||
```
|
||||
|
||||
**Adoption** — `probePort()` connects, then checks that the listener answers
|
||||
`GET /api/health` with `{ status: "ok" }`. If a healthy dashboard server is
|
||||
already on `:4820` (e.g. you ran `npm start` in a terminal), the desktop app
|
||||
**adopts** it rather than double-binding. An adopted server is *not* owned by
|
||||
the app — quitting the app leaves it running.
|
||||
|
||||
**`ServerHandle`:**
|
||||
|
||||
```ts
|
||||
interface ServerHandle {
|
||||
url: string; // e.g. "http://127.0.0.1:4820"
|
||||
port: number;
|
||||
ownedByUs: boolean; // false when adopted
|
||||
stop: () => Promise<void>;
|
||||
}
|
||||
```
|
||||
|
||||
**Hook port discovery** — because the embedded server may bind a fallback port
|
||||
(4821+) when 4820 is taken, the Claude Code hook handler must not assume 4820.
|
||||
On startup the server writes its live port to `~/.claude/.agent-dashboard.json`
|
||||
(`server/lib/server-info.js`); `scripts/hook-handler.js` reads that file to
|
||||
target the running server. Without this, hook events would be POSTed to 4820 —
|
||||
nothing would receive them and the dashboard would stay empty.
|
||||
|
||||
---
|
||||
|
||||
## `better-sqlite3` native-module handling
|
||||
|
||||
`better-sqlite3` is the only **native** module in the dependency tree, and a
|
||||
native module must be compiled against the exact Node ABI it runs on. The repo
|
||||
root's copy is built for the **system Node** (so `npm run test:server` works);
|
||||
Electron ships its **own Node ABI**.
|
||||
|
||||
The desktop workspace solves this without disturbing the root install:
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
subgraph desk["desktop/node_modules"]
|
||||
d1["better-sqlite3<br/>rebuilt for Electron's ABI<br/>(by electron-builder install-app-deps)"]
|
||||
end
|
||||
subgraph root["node_modules (repo root)"]
|
||||
r1["better-sqlite3<br/>built for system Node<br/>(used by npm run test:server)"]
|
||||
end
|
||||
|
||||
patch["ensureNativeModulesPatched()<br/>overrides Module._resolveFilename"]
|
||||
srv["server/db.js<br/>require('better-sqlite3')"]
|
||||
|
||||
srv -->|"request intercepted"| patch
|
||||
patch -->|"redirected to"| d1
|
||||
patch -.->|"everything else<br/>passes through"| root
|
||||
|
||||
style d1 fill:#238636,stroke:#196c2e,color:#fff
|
||||
style patch fill:#1f6feb,stroke:#1158c7,color:#fff
|
||||
```
|
||||
|
||||
- The patch is **process-local** and installed exactly once, before
|
||||
`server/index.js` is `require()`d.
|
||||
- It rewrites *only* `require("better-sqlite3")`; every other module resolves
|
||||
normally.
|
||||
- `electron-builder.yml` therefore **excludes** the root `better-sqlite3` from
|
||||
the bundle (it would trip `@electron/universal`'s identical-file detector)
|
||||
and `asarUnpack`s the desktop copy (native `.node` files cannot live inside
|
||||
an `asar` archive).
|
||||
- PR #37's `compat-sqlite` (`node:sqlite`) fallback remains as a safety net —
|
||||
one reason the desktop app pins **Electron 35** (its bundled Node 22.16 has
|
||||
`node:sqlite`; Electron 31's Node 20 did not).
|
||||
- **No toolchain needed in the common case** — `npm run desktop:install` runs
|
||||
`scripts/install.js`, which wraps `npm install` (whose `postinstall` runs
|
||||
`electron-builder install-app-deps`). On success it behaves like a bare
|
||||
`npm install`. On failure — or if the native binary is missing afterward — it
|
||||
prints actionable help (`scripts/preflight.js`'s `printNativeDepHelp()`) and
|
||||
exits non-zero, never leaving a half-set-up `node_modules`. The help lists the
|
||||
per-OS C++ prerequisite (Windows: Visual Studio Build Tools with the "Desktop
|
||||
development with C++" workload; macOS: `xcode-select --install`; Linux:
|
||||
build-essential + python3), notes that a Node LTS (20/22) ships prebuilt
|
||||
binaries (avoiding the compile), and gives a no-toolchain alternative:
|
||||
|
||||
```bash
|
||||
cd desktop
|
||||
npm install --ignore-scripts
|
||||
node node_modules/electron/install.js
|
||||
npx electron-builder install-app-deps
|
||||
```
|
||||
|
||||
`prebuild.js` runs the same check (`hasBetterSqliteBinary()`) before **every**
|
||||
`desktop:*` build/dev script and fails fast with the same help if the binary
|
||||
is missing — turning what was a runtime fatal-dialog crash into a build-time,
|
||||
copy-pasteable error.
|
||||
|
||||
---
|
||||
|
||||
## Background services & hook bootstrap
|
||||
|
||||
`node server/index.js` runs its production bootstrap from an
|
||||
`if (require.main === module)` block. Because the desktop app **`require()`s**
|
||||
that module, the block never fires — so the bootstrap was extracted into an
|
||||
exported `startBackgroundServices()` that both paths call.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
subgraph standalone["node server/index.js"]
|
||||
s1["require.main === module"] --> s2["startBackgroundServices()"]
|
||||
end
|
||||
subgraph desktopapp["desktop app"]
|
||||
d1["server-host.ts<br/>bootstrapOwnedServer()"] --> d2["startBackgroundServices()"]
|
||||
d1 --> d3["installHooks()"]
|
||||
end
|
||||
|
||||
d2 --> svc
|
||||
s2 --> svc
|
||||
subgraph svc["Background services"]
|
||||
u["update scheduler"]
|
||||
w["cc-watcher (Claude config watcher)"]
|
||||
r["orphaned-run reconciliation"]
|
||||
end
|
||||
|
||||
style d1 fill:#1f6feb,stroke:#1158c7,color:#fff
|
||||
```
|
||||
|
||||
`bootstrapOwnedServer()` runs **once** (guarded by a module-level flag so a
|
||||
*Restart Server* does not double-register schedulers/watchers) and:
|
||||
|
||||
1. Calls `startBackgroundServices()` — the update scheduler, the `cc-watcher`
|
||||
config watcher, and one-time orphaned-run reconciliation.
|
||||
2. Calls `installHooks()` — writes the Claude Code hook configuration to
|
||||
`~/.claude/settings.json`, so a **DMG-only user gets events flowing**
|
||||
without ever running `npm run install-hooks` from a checkout.
|
||||
|
||||
It runs only when the server is **owned** by the app — an adopted server has
|
||||
already done its own bootstrap.
|
||||
|
||||
---
|
||||
|
||||
## Window, tray & menu
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
tray["Menu-bar (tray) icon"]
|
||||
tray -->|left-click| toggle["toggle dashboard window"]
|
||||
tray -->|right-click| menu["context menu (built fresh)"]
|
||||
|
||||
menu --> m1["Open Dashboard"]
|
||||
menu --> m2["Open in Browser…"]
|
||||
menu --> m3["Restart Server"]
|
||||
menu --> m4["Show Logs"]
|
||||
menu --> m5["Open at Login ☑"]
|
||||
menu --> m6["Quit"]
|
||||
|
||||
win["BrowserWindow"]
|
||||
win -->|"close"| hide["hide() — server stays up"]
|
||||
win -->|"resize / move"| persist["debounced save →<br/>userData/window-state.json"]
|
||||
win -->|"external link"| ext["shell.openExternal()"]
|
||||
|
||||
style tray fill:#1f6feb,stroke:#1158c7,color:#fff
|
||||
```
|
||||
|
||||
- **Tray** — the always-on surface. Left-click toggles the window; right-click
|
||||
pops the context menu. The menu is rebuilt on each open so the port label and
|
||||
*Open at Login* checkbox are always current. (The tray deliberately does
|
||||
**not** use `setContextMenu`, which on macOS would make a left-click open the
|
||||
menu and collide with the toggle behavior.)
|
||||
- **Window** — `BrowserWindow` with `contextIsolation: true`,
|
||||
`nodeIntegration: false`, an empty preload, and `webSecurity: true`. Geometry
|
||||
is persisted to `window-state.json` under `app.getPath('userData')`. External
|
||||
links open in the system browser, never inside Electron. Its `icon` is set to
|
||||
the colored app logo via `appIconPath()` (`icon.ico` on Windows, `icon.png`
|
||||
elsewhere — the same logo as the macOS Dock, rendered from `assets/icon.svg`),
|
||||
resolving dev vs packaged asset paths, so an unpackaged `desktop:dev` run shows
|
||||
the real logo in the title bar / taskbar instead of the generic Electron icon.
|
||||
macOS ignores `BrowserWindow#icon` (the dev Dock icon is set separately in
|
||||
`main.ts`; packaged apps get theirs from the bundle `.icns`/`.exe`).
|
||||
- **Application menu** — standard menu (`About`, `Open at Login`, `File`,
|
||||
`Edit`, `View`, `Window`, `Help`). `⌘R` / `Ctrl+R` is owned by `View ▸ reload`.
|
||||
The `File ▸ Open Dashboard` item (`⌘1`) is gated behind `isMac`: macOS keeps a
|
||||
global menu bar after the window hides so it can reopen it, but on
|
||||
Windows/Linux the menu is attached to the window and a menu accelerator can't
|
||||
fire while it's hidden — reopening there is the tray's *Open Dashboard*, and
|
||||
`focusOrCreateWindow` calls `show()` unconditionally so it reliably raises a
|
||||
backgrounded/minimized window (a bare `focus()` on Windows often only flashes
|
||||
the taskbar button).
|
||||
|
||||
---
|
||||
|
||||
## Auto-start (Login Items)
|
||||
|
||||
Auto-start uses Electron's first-party `app.setLoginItemSettings` — which wraps
|
||||
the modern macOS `SMAppService` / `ServiceManagement` framework — **not** a
|
||||
`LaunchAgent` plist. The toggle therefore appears in
|
||||
**System Settings → General → Login Items** where users expect to manage it.
|
||||
|
||||
```mermaid
|
||||
stateDiagram-v2
|
||||
[*] --> Disabled
|
||||
Disabled --> Enabled: tray / menu "Open at Login"
|
||||
Enabled --> Disabled: toggle again
|
||||
Enabled --> LaunchedAtLogin: macOS login
|
||||
LaunchedAtLogin --> TrayOnly: window hidden,<br/>dock hidden
|
||||
TrayOnly --> WindowShown: user clicks tray
|
||||
```
|
||||
|
||||
When macOS launches the app at login (`wasOpenedAtLogin`), it starts
|
||||
**tray-only** with `openAsHidden: true` — no window jumps into the user's face.
|
||||
|
||||
---
|
||||
|
||||
## Source tree
|
||||
|
||||
```
|
||||
desktop/
|
||||
├── src/
|
||||
│ ├── main.ts # main process entry — lifecycle, dialogs, wiring
|
||||
│ ├── server-host.ts # ★ in-process Express boot, port discovery, adoption,
|
||||
│ │ # better-sqlite3 ABI patch, DB + discovery-file close,
|
||||
│ │ # /api/stats snapshot poller for the tray dropdown
|
||||
│ ├── window.ts # BrowserWindow + persisted geometry; native macOS
|
||||
│ │ # titleBarStyle: 'default' (clear traffic-light row)
|
||||
│ ├── menu.ts # native application menu
|
||||
│ ├── tray.ts # menu-bar icon + single-click dropdown w/ live
|
||||
│ │ # {sessions, agents, events-today} snapshot
|
||||
│ ├── login-item.ts # macOS Login Items (SMAppService)
|
||||
│ ├── shell-path.ts # recover the user's shell PATH (so `claude` is found)
|
||||
│ ├── logger.ts # file logger → app.getPath('logs')/desktop.log
|
||||
│ ├── constants.ts # APP_NAME, ports, timeouts, window size
|
||||
│ └── preload.ts # intentionally empty (zero renderer privilege)
|
||||
├── scripts/
|
||||
│ ├── install.js # desktop:install wrapper: npm install + actionable
|
||||
│ │ # native-dep help on failure (exits non-zero)
|
||||
│ ├── preflight.js # shared hasBetterSqliteBinary() + printNativeDepHelp()
|
||||
│ ├── prebuild.js # ensures client/dist + root node_modules exist; fails
|
||||
│ │ # fast with setup help if better-sqlite3 binary missing
|
||||
│ ├── notarize.js # electron-builder afterSign hook (opt-in)
|
||||
│ └── build-icons.sh # regenerate icon.icns + tray PNGs from SVG
|
||||
├── assets/ # icon.icns, icon.png, tray-icon-Template*.png, SVGs
|
||||
├── tests/
|
||||
│ └── smoke.test.mjs # spawn Electron + probe /api/health
|
||||
├── electron-builder.yml # DMG packaging config
|
||||
├── tsconfig.json # strict; src/ → out/
|
||||
└── package.json
|
||||
```
|
||||
|
||||
Compiled output lands in `desktop/out/` (git-ignored); packaged artifacts in
|
||||
`desktop/release/` (git-ignored).
|
||||
|
||||
---
|
||||
|
||||
## Packaged app layout
|
||||
|
||||
`electron-builder` produces `Claude Code Monitor.app`. The Electron main
|
||||
process code is packed into `app.asar`; the rest of the repo is shipped as
|
||||
**`extraResources`** (plain files under `Resources/app/`):
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
app["Claude Code Monitor.app"]
|
||||
app --> contents["Contents/"]
|
||||
contents --> macos["MacOS/ — Electron binary"]
|
||||
contents --> res["Resources/"]
|
||||
res --> asar["app.asar<br/>(compiled out/**, package.json)"]
|
||||
res --> unpacked["app.asar.unpacked/<br/>node_modules/better-sqlite3 (.node)"]
|
||||
res --> appdir["app/"]
|
||||
appdir --> a1["server/ — Express server (no tests)"]
|
||||
appdir --> a2["client/dist/ — built React SPA"]
|
||||
appdir --> a3["scripts/ — hook-handler, install-hooks"]
|
||||
appdir --> a4["node_modules/ — server runtime deps"]
|
||||
appdir --> a5["package.json"]
|
||||
|
||||
style asar fill:#1f6feb,stroke:#1158c7,color:#fff
|
||||
style appdir fill:#238636,stroke:#196c2e,color:#fff
|
||||
```
|
||||
|
||||
At runtime `server-host.ts` resolves this root: `process.resourcesPath/app`
|
||||
when packaged, or the repo root in development.
|
||||
|
||||
---
|
||||
|
||||
## Build pipeline
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
src["src/*.ts"] -->|prebuild guard| pre["scripts/prebuild.js<br/>verify client/dist + node_modules"]
|
||||
pre --> tsc["tsc → out/*.js"]
|
||||
tsc --> eb["electron-builder"]
|
||||
eb --> dl["download Electron runtime"]
|
||||
eb --> rebuild["@electron/rebuild<br/>better-sqlite3 per arch"]
|
||||
eb --> asar["pack out/** → app.asar"]
|
||||
eb --> extra["copy server/ client/dist/ scripts/ node_modules/<br/>→ Resources/app/"]
|
||||
asar --> appbundle[".app bundle"]
|
||||
extra --> appbundle
|
||||
rebuild --> appbundle
|
||||
appbundle --> sign["codesign (ad-hoc by default)"]
|
||||
sign --> notarize["notarize (opt-in, afterSign hook)"]
|
||||
notarize --> dmg["hdiutil → .dmg"]
|
||||
|
||||
style tsc fill:#1f6feb,stroke:#1158c7,color:#fff
|
||||
style dmg fill:#238636,stroke:#196c2e,color:#fff
|
||||
```
|
||||
|
||||
`desktop:dmg` runs the *packaging → rebuild → sign → DMG* steps **twice**
|
||||
(once per architecture) and emits two separate DMGs (`…-arm64.dmg` +
|
||||
`…-x64.dmg`). There is no `@electron/universal` merge step — the release ships
|
||||
the two per-arch DMGs rather than one fat universal binary.
|
||||
|
||||
---
|
||||
|
||||
## Commands
|
||||
|
||||
All commands are runnable from the **repo root** (`desktop:*`) or from inside
|
||||
`desktop/`. Every script that packages first runs `npm run build`, so you never
|
||||
need to invoke `electron-builder` bare (doing so skips the TypeScript compile
|
||||
and fails with *"entry file out/main.js does not exist"*).
|
||||
|
||||
| Repo-root command | `desktop/` command | What it does |
|
||||
|---|---|---|
|
||||
| `npm run desktop:install` | `node scripts/install.js` | Install Electron, electron-builder, types; rebuild `better-sqlite3` for Electron's ABI (`postinstall`). Preflights native deps — on failure (or a missing binary) prints per-OS setup help + a no-toolchain alternative and exits non-zero. |
|
||||
| `npm run desktop:build` | `npm run build` | Prebuild guard + `tsc` → `out/`. |
|
||||
| `npm run desktop:dev` | `npm run dev` | Build, then launch Electron against `out/main.js`. |
|
||||
| `npm run desktop:test` | `npm test` | Build, then run the smoke test. |
|
||||
| `npm run desktop:dmg` | `npm run dmg` | **macOS:** both per-arch DMGs (arm64 + x64). Correct for release. **Slower.** |
|
||||
| `npm run desktop:dmg:arm64` | `npm run dmg:arm64` | **macOS:** Apple-Silicon-only DMG. **Fast.** |
|
||||
| `npm run desktop:dmg:x64` | `npm run dmg:x64` | **macOS:** Intel-only DMG. **Fast.** |
|
||||
| `npm run desktop:dmg:universal` | `npm run dmg:universal` | **macOS:** one merged universal DMG (arm64 + x86_64 via `@electron/universal`). Optional — not what the release ships. **Slowest.** |
|
||||
| `npm run desktop:win` | `npm run win` | **Windows:** NSIS installer `.exe` (x64). |
|
||||
| `npm run desktop:win:portable` | `npm run win:portable` | **Windows:** no-install portable `.exe` (x64). |
|
||||
| — | `npm run build:icons` | **macOS:** regenerate `icon.icns` + tray PNGs from the SVGs. |
|
||||
| — | `npm run build:win-icon` | **Windows:** regenerate `icon.ico` from `icon.png` (PowerShell + .NET). |
|
||||
| — | `npm run clean` | Remove `out/` and `release/`. |
|
||||
|
||||
> **After `npm run clean`** you must `npm run build` again before packaging —
|
||||
> `clean` deletes `out/`, and `electron-builder` only *packages*, it does not
|
||||
> compile. The `dmg*` scripts chain the build for you; a bare
|
||||
> `electron-builder` call does not.
|
||||
|
||||
---
|
||||
|
||||
## Build performance — read this
|
||||
|
||||
**`desktop:dmg` is slower than a single-arch build.** This is expected — it is
|
||||
the standard Electron packaging cost, paid **once per architecture**:
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
u["npm run desktop:dmg (both arches)"] --> b1["build x64 app tree → sign → …-x64.dmg"]
|
||||
u --> b2["build arm64 app tree → sign → …-arm64.dmg"]
|
||||
|
||||
a["npm run desktop:dmg:arm64 (single arch)"] --> sb["build one app tree"]
|
||||
sb --> ssign["sign"]
|
||||
ssign --> sdmg["hdiutil → …-arm64.dmg"]
|
||||
|
||||
style u fill:#9e6a03,stroke:#7d5300,color:#fff
|
||||
style a fill:#238636,stroke:#196c2e,color:#fff
|
||||
```
|
||||
|
||||
Why `desktop:dmg` is slow:
|
||||
|
||||
1. **Everything happens twice** — electron-builder builds a full x64 app tree
|
||||
*and* a full arm64 app tree, rebuilding `better-sqlite3` and packaging a DMG
|
||||
for each. (There is no universal merge; each arch produces its own DMG.)
|
||||
2. **The app tree is large** — the server's entire production dependency tree
|
||||
(`express`, `swagger-ui-express`, `ws`, …) ships as `extraResources`; that's
|
||||
tens of thousands of files, walked and copied for each architecture.
|
||||
3. **Per-binary code signing** runs over each architecture's bundle.
|
||||
|
||||
Net effect: a ~250 MB app is built, copied, and signed once per architecture —
|
||||
gigabytes of disk I/O. The Electron runtime downloads (~110 MB each) are *not*
|
||||
the bottleneck; packaging two architectures back-to-back is.
|
||||
|
||||
**Guidance:**
|
||||
|
||||
- Building for **your own Mac** → use `desktop:dmg:arm64` (Apple Silicon) or
|
||||
`desktop:dmg:x64` (Intel). One architecture — finishes in roughly a minute
|
||||
instead of two.
|
||||
- Building the **release artifacts for everyone** → use `desktop:dmg` (builds
|
||||
both arches) and expect it to take about twice as long. CI runs `desktop:dmg`
|
||||
and uploads both DMGs as the `ClaudeCodeMonitor-dmg` artifact, so you rarely
|
||||
need to build them locally.
|
||||
- Each DMG is **~80 MB / ~250 MB on disk** — the standard Electron tax.
|
||||
|
||||
---
|
||||
|
||||
## Code signing & notarization
|
||||
|
||||
The DMG is **ad-hoc signed by default** so anyone can build a working `.dmg`
|
||||
without a paid Apple Developer account.
|
||||
|
||||
- The `package` script sets **`CSC_IDENTITY_AUTO_DISCOVERY=false`** so a
|
||||
code-signing certificate already in the contributor's macOS keychain is
|
||||
**never** picked up. (Without this, electron-builder auto-discovers such a
|
||||
cert and attempts `type=distribution` signing, which fails on a non–Developer
|
||||
ID cert with *"Application … could not be found"*.)
|
||||
- **Real Developer ID signing** activates when `CSC_LINK` (a base64-encoded
|
||||
`.p12`) and `CSC_KEY_PASSWORD` are provided — `CSC_LINK` is an *explicit*
|
||||
certificate and is unaffected by the auto-discovery flag.
|
||||
- **Notarization** is opt-in: `desktop/scripts/notarize.js` (an
|
||||
`electron-builder` `afterSign` hook) runs only when `APPLE_ID`,
|
||||
`APPLE_TEAM_ID`, and `APPLE_APP_SPECIFIC_PASSWORD` are all set. Otherwise it
|
||||
is a no-op.
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
build["DMG build"] --> q{"CSC_LINK set?"}
|
||||
q -->|yes| real["sign with Developer ID cert"]
|
||||
q -->|no| adhoc["ad-hoc sign<br/>(keychain scan disabled)"]
|
||||
real --> n{"APPLE_ID + TEAM_ID + PASSWORD set?"}
|
||||
adhoc --> n
|
||||
n -->|yes| notar["notarize via notarytool"]
|
||||
n -->|no| skip["skip notarization"]
|
||||
notar --> out[".dmg"]
|
||||
skip --> out
|
||||
|
||||
style adhoc fill:#9e6a03,stroke:#7d5300,color:#fff
|
||||
style real fill:#238636,stroke:#196c2e,color:#fff
|
||||
```
|
||||
|
||||
An ad-hoc DMG triggers a Gatekeeper warning on first launch. The one-line
|
||||
workaround is in [`../DESKTOP.md`](../DESKTOP.md):
|
||||
`xattr -cr "/Applications/Claude Code Monitor.app"`.
|
||||
|
||||
---
|
||||
|
||||
## Continuous integration
|
||||
|
||||
The `🍎 macOS Desktop (DMG)` job in `.github/workflows/ci.yml`:
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
ch["changes job<br/>dorny/paths-filter"] -->|"desktop/** changed?"| gate{run?}
|
||||
push["push to any branch"] --> gate
|
||||
label["PR has 'desktop' label"] --> gate
|
||||
gate -->|yes| job["desktop job (macos-latest)"]
|
||||
job --> j1["npm ci (root, client, desktop)"]
|
||||
j1 --> j2["tsc build"]
|
||||
j2 --> j3["smoke test"]
|
||||
j3 --> j4["build both per-arch DMGs<br/>(retry on flaky hdiutil detach)"]
|
||||
j4 --> j5["upload ClaudeCodeMonitor-dmg artifact"]
|
||||
j5 --> rel["release job (master only)<br/>publish vX.Y.Z if new"]
|
||||
|
||||
style job fill:#1f6feb,stroke:#1158c7,color:#fff
|
||||
style rel fill:#238636,stroke:#1a6e2c,color:#fff
|
||||
```
|
||||
|
||||
- The job is **path-filtered** — a `changes` job (`dorny/paths-filter`)
|
||||
detects `desktop/**` edits; the desktop job also runs on any `push` or when a
|
||||
PR carries the `desktop` label.
|
||||
- **DMG build resilience** — `electron-builder` finalizes the DMG with
|
||||
`hdiutil detach`, which is intermittently flaky on GitHub macOS runners. The
|
||||
step disables Spotlight indexing and retries the build up to 3 times,
|
||||
force-detaching any stale volume between attempts.
|
||||
- The built DMG is uploaded as the **`ClaudeCodeMonitor-dmg`** artifact
|
||||
(downloadable from the workflow run).
|
||||
- On `master`, a follow-on **`release`** job reads the version from
|
||||
`package.json` and publishes `vX.Y.Z` as a GitHub Release with the DMG
|
||||
attached — but only when no release exists for that version yet, so bumping
|
||||
the version is what cuts a release. The result is a permanent, anonymous
|
||||
download URL at `releases/latest`.
|
||||
|
||||
---
|
||||
|
||||
## Smoke test
|
||||
|
||||
`tests/smoke.test.mjs` is intentionally minimal — it proves the embedded server
|
||||
boots, without needing a display (so CI needs no `xvfb`).
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
autonumber
|
||||
participant T as smoke.test.mjs
|
||||
participant E as Electron (out/main.js)
|
||||
participant S as embedded server
|
||||
|
||||
T->>T: pick a unique high port
|
||||
T->>E: spawn with CCAM_DESKTOP_BIND_PORT=<port>
|
||||
E->>S: startEmbeddedServer() — bind exactly <port>
|
||||
loop until healthy or 60s
|
||||
T->>S: GET /api/health
|
||||
end
|
||||
T->>T: assert status == "ok" AND <port> matched
|
||||
T->>T: assert Electron process still alive
|
||||
T->>E: SIGTERM
|
||||
```
|
||||
|
||||
`CCAM_DESKTOP_BIND_PORT` forces the server onto an exact port (no adoption, no
|
||||
fallback) so the test can be certain it probed *this* process and not an
|
||||
unrelated server on `:4820`.
|
||||
|
||||
---
|
||||
|
||||
## Environment variables
|
||||
|
||||
| Variable | Used by | Effect |
|
||||
|---|---|---|
|
||||
| `CCAM_DESKTOP_BIND_PORT` | `server-host.ts` | Bind exactly this port — disables adoption and fallback. Used by the smoke test. |
|
||||
| `CCAM_DESKTOP_NO_ADOPT` | `server-host.ts` | `=1` → never adopt an existing `:4820` server; always start our own. |
|
||||
| `CCAM_DESKTOP_VERBOSE` | `logger.ts` | Mirror `info`/`warn` log lines to stdout (errors always go to stderr). |
|
||||
| `DASHBOARD_DATA_DIR` | `server-host.ts` → server | Set automatically to `app.getPath('userData')/data` so the SQLite database and VAPID keys live in the per-user Application Support directory, never inside the (possibly read-only) `.app` bundle. |
|
||||
| `CSC_IDENTITY_AUTO_DISCOVERY` | electron-builder | Set to `false` by the `package` script — forces ad-hoc signing. |
|
||||
| `CSC_LINK` / `CSC_KEY_PASSWORD` | electron-builder | Explicit Developer ID `.p12` for real signing. |
|
||||
| `APPLE_ID` / `APPLE_TEAM_ID` / `APPLE_APP_SPECIFIC_PASSWORD` | `notarize.js` | Enable Apple notarization when all three are set. |
|
||||
|
||||
The embedded server also honors the dashboard's own env vars (`DASHBOARD_PORT`
|
||||
and `DASHBOARD_DATA_DIR` are set automatically by `server-host.ts`; everything
|
||||
else in [`../SETUP.md`](../SETUP.md) applies).
|
||||
|
||||
> **Writable state never lives in the `.app` bundle.** A packaged, code-signed,
|
||||
> or app-translocated bundle is read-only; a database written there would break
|
||||
> History Import and event persistence. `server-host.ts` points
|
||||
> `DASHBOARD_DATA_DIR` at `~/Library/Application Support/Claude Code Monitor/data/`,
|
||||
> which is also why your imported history survives an app reinstall or update.
|
||||
|
||||
---
|
||||
|
||||
## Logs & troubleshooting
|
||||
|
||||
The Electron main process has no console when launched from Finder, so
|
||||
`logger.ts` writes to a per-user file:
|
||||
|
||||
```
|
||||
~/Library/Logs/Claude Code Monitor/desktop.log
|
||||
```
|
||||
|
||||
Reach it from the tray menu → **Show Logs**.
|
||||
|
||||
| Symptom | Cause / fix |
|
||||
|---|---|
|
||||
| `entry file out/main.js does not exist` | You ran `electron-builder` without building first. Run `npm run build` (or use a `dmg*` script). |
|
||||
| Signing fails: `Application … could not be found` after retries | A keychain cert was auto-discovered. The `package` script now sets `CSC_IDENTITY_AUTO_DISCOVERY=false`; ensure you build via `npm run dmg*`, not bare `electron-builder`. |
|
||||
| DMG build seems slow | Not hung — `desktop:dmg` packages two architectures back-to-back. See [Build performance](#build-performance--read-this). Use `dmg:arm64` / `dmg:x64` for a single arch. |
|
||||
| `hdiutil detach … exit code 1` in CI | Flaky GitHub runner; the CI step already retries with Spotlight disabled. Re-run the job if it still fails. |
|
||||
| Dashboard window is blank | The embedded server failed `/api/health` within 30 s — check `desktop.log`. |
|
||||
| Gatekeeper blocks the app | Ad-hoc DMG. `xattr -cr "/Applications/Claude Code Monitor.app"`. |
|
||||
| Hooks not firing | The app installs hooks on first owned-server boot; start a **new** Claude Code session afterwards. Verify entries in `~/.claude/settings.json`. |
|
||||
| "Run Claude" says `claude` isn't on your PATH | `shell-path.ts` recovers the login-shell PATH at startup. If `claude` is a shell _alias_ or _function_ (not a real binary), it cannot be spawned — install the `claude` CLI as an executable. Check `desktop.log` for the `user PATH resolved` line. |
|
||||
| `desktop:dev` / `desktop:test` fail with `ERR_DLOPEN_FAILED` | A prior DMG build left `better-sqlite3` built for the other CPU arch. `prebuild.js` auto-heals this on the next build; if needed, run `npm run desktop:install`. |
|
||||
| Imported history disappeared after reinstall | Fixed — the database now lives in `~/Library/Application Support/Claude Code Monitor/data/`, outside the bundle. A one-time gap exists only across the upgrade from a build that predated this fix; re-run **Import History → Rescan**. |
|
||||
|
||||
---
|
||||
|
||||
## What this workspace does *not* touch
|
||||
|
||||
By design, changes outside `desktop/` are kept to a minimum:
|
||||
|
||||
- **`server/index.js`** — its post-listen bootstrap was extracted into an
|
||||
exported `startBackgroundServices()` so the embedded server boots the same
|
||||
one-time legacy-session import, update scheduler, `cc-watcher`, and
|
||||
orphaned-run reconciliation that `node server/index.js` does. A
|
||||
**behavior-preserving refactor** — the standalone server path is functionally
|
||||
unchanged. (The legacy-session import previously lived in the
|
||||
`require.main === module` block, so the embedded server never ran it and the
|
||||
desktop dashboard started empty; moving it into `startBackgroundServices()`
|
||||
fixes that.) The server also publishes its live port on startup.
|
||||
- **`server/lib/server-info.js`** *(new)* — multi-server discovery file at
|
||||
`~/.claude/.agent-dashboard.json`. Every running dashboard appends its
|
||||
`{port, pid, startedAt}` entry on startup, removes it on clean shutdown,
|
||||
and stale entries are pruned by a `process.kill(pid, 0)` liveness check on
|
||||
read. Exposes `writeServerInfo`, `removeServerInfo`,
|
||||
`resolveAllDashboardPorts` (fan-out targets), and the legacy single-port
|
||||
`resolveDashboardPort`. The file also carries legacy root-level
|
||||
`port`/`pid`/`startedAt` fields populated from the most recently started
|
||||
live server, so older hook handlers bundled inside an already-installed
|
||||
`.app` still resolve to a reachable port.
|
||||
- **`scripts/hook-handler.js`** — `Promise.all` fan-out of every hook
|
||||
payload to every live server returned by `resolveAllDashboardPorts()`
|
||||
(`CLAUDE_DASHBOARD_PORT` overrides to a single target). This is what lets
|
||||
the desktop app coexist with `npm run dev` — both dashboards receive every
|
||||
event and both stay real-time.
|
||||
- **`server/lib/push.js`** — `sendPushToAll()` now also fires a **native
|
||||
Electron notification** when `process.versions.electron` is set, so the
|
||||
desktop app surfaces notifications via the OS API instead of relying on Web
|
||||
Push (which fails inside Electron — no FCM credentials in the Chromium
|
||||
build). The standalone server path is unchanged: the native leg is a no-op
|
||||
there, and Web Push delivers as before.
|
||||
- **`scripts/dev.js`** *(new)* — `npm run dev`'s entry point. Probes both
|
||||
`127.0.0.1` and `::1` for a free port in `4820–4859` (so an SSH
|
||||
`LocalForward` with loopback-specific binds can't shadow Node's wildcard
|
||||
listen), exports `DASHBOARD_PORT`, then spawns the existing
|
||||
`concurrently` server + client pipeline. `npm run dev:raw` bypasses it
|
||||
for parity with the old behaviour.
|
||||
|
||||
`client/`, `mcp/`, and `vscode-extension/` are **untouched**. If you find
|
||||
yourself wanting to edit those, that belongs in a separate PR.
|
||||
|
||||
---
|
||||
|
||||
*User-facing docs: [`../DESKTOP.md`](../DESKTOP.md) · Project architecture:
|
||||
[`../ARCHITECTURE.md`](../ARCHITECTURE.md) · Setup: [`../SETUP.md`](../SETUP.md)*
|
||||
Binary file not shown.
Binary file not shown.
|
After Width: | Height: | Size: 364 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 647 KiB |
@@ -0,0 +1,34 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024" width="1024" height="1024">
|
||||
<defs>
|
||||
<linearGradient id="bg" x1="0%" y1="0%" x2="100%" y2="100%">
|
||||
<stop offset="0%" stop-color="#6366f1"/>
|
||||
<stop offset="100%" stop-color="#818cf8"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="glow" x1="0%" y1="0%" x2="100%" y2="100%">
|
||||
<stop offset="0%" stop-color="#a5b4fc" stop-opacity="0.95"/>
|
||||
<stop offset="100%" stop-color="#c7d2fe" stop-opacity="0.7"/>
|
||||
</linearGradient>
|
||||
<radialGradient id="centerGlow" cx="50%" cy="50%" r="50%">
|
||||
<stop offset="0%" stop-color="#ffffff" stop-opacity="1"/>
|
||||
<stop offset="100%" stop-color="#ffffff" stop-opacity="0.85"/>
|
||||
</radialGradient>
|
||||
</defs>
|
||||
|
||||
<!-- Rounded rectangle backplate to match macOS Big Sur+ icon style -->
|
||||
<rect x="96" y="96" width="832" height="832" rx="184" ry="184" fill="url(#bg)"/>
|
||||
|
||||
<!-- Hexagon glyph (scaled from the project's 32px favicon, centered) -->
|
||||
<g transform="translate(512 512) scale(20) translate(-16 -16)">
|
||||
<polygon points="16,2 28,9 28,23 16,30 4,23 4,9" fill="none" stroke="white" stroke-width="0.9" stroke-linejoin="round" opacity="0.55"/>
|
||||
<!-- Center node -->
|
||||
<circle cx="16" cy="16" r="3" fill="url(#centerGlow)"/>
|
||||
<!-- Connector lines -->
|
||||
<line x1="16" y1="13" x2="16" y2="7" stroke="white" stroke-width="1.5" stroke-linecap="round" opacity="0.85"/>
|
||||
<line x1="18.6" y1="17.5" x2="24" y2="20.5" stroke="white" stroke-width="1.5" stroke-linecap="round" opacity="0.85"/>
|
||||
<line x1="13.4" y1="17.5" x2="8" y2="20.5" stroke="white" stroke-width="1.5" stroke-linecap="round" opacity="0.85"/>
|
||||
<!-- Outer nodes -->
|
||||
<circle cx="16" cy="6" r="1.8" fill="url(#glow)"/>
|
||||
<circle cx="24.5" cy="21" r="1.8" fill="url(#glow)"/>
|
||||
<circle cx="7.5" cy="21" r="1.8" fill="url(#glow)"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.8 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 95 B |
Binary file not shown.
|
After Width: | Height: | Size: 124 B |
@@ -0,0 +1,19 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 22 22" width="22" height="22">
|
||||
<!--
|
||||
macOS menu-bar (tray) glyph. Three ascending bars — a "monitor activity"
|
||||
silhouette that reads cleanly at 18-22 px. Solid black on transparent so
|
||||
macOS template tinting (filename ends in "Template.png" + nativeImage
|
||||
setTemplateImage(true)) handles light and dark menu bars automatically.
|
||||
No thin strokes — they collapse to a blob at small sizes.
|
||||
|
||||
NOTE: this SVG is the design intent only. The PNGs in this folder are
|
||||
generated pixel-by-pixel by `scripts/build-icons.sh` (using Python's
|
||||
stdlib `zlib` + a tiny RGBA encoder) — `qlmanage` flattens SVG against
|
||||
an opaque white background and would yield an all-white tray icon.
|
||||
-->
|
||||
<g fill="black">
|
||||
<rect x="2" y="14" width="4" height="7"/>
|
||||
<rect x="9" y="11" width="4" height="10"/>
|
||||
<rect x="16" y="5" width="4" height="16"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 939 B |
@@ -0,0 +1,167 @@
|
||||
# electron-builder configuration for Claude Code Agent Monitor (macOS + Windows).
|
||||
#
|
||||
# Defaults to ad-hoc signing so the project can build distributable DMGs
|
||||
# without a paid Apple Developer account. When the following environment
|
||||
# variables are set in CI (typically as repository secrets), the same
|
||||
# config produces a Developer ID–signed and Apple-notarized DMG:
|
||||
#
|
||||
# APPLE_ID Apple ID email
|
||||
# APPLE_TEAM_ID Developer team identifier
|
||||
# APPLE_APP_SPECIFIC_PASSWORD App-specific password for notarytool
|
||||
# CSC_LINK Base64-encoded .p12 cert (optional)
|
||||
# CSC_KEY_PASSWORD Password for the .p12 (optional)
|
||||
#
|
||||
# No code changes are required to enable notarization later.
|
||||
|
||||
appId: com.vn.smartgift.ccam.desktop
|
||||
productName: Claude Code Monitor
|
||||
copyright: Copyright (c) 2026 SmartGift. All rights reserved.
|
||||
|
||||
directories:
|
||||
output: release
|
||||
buildResources: assets
|
||||
|
||||
# We pre-build with tsc into out/, and we ship the existing server/ and
|
||||
# client/dist/ from the parent repo as extraResources. Keeping the bundle
|
||||
# small: no source maps, no parent node_modules tree.
|
||||
files:
|
||||
- "out/**/*"
|
||||
- "package.json"
|
||||
|
||||
extraResources:
|
||||
- from: "../server"
|
||||
to: "app/server"
|
||||
filter:
|
||||
- "**/*"
|
||||
- "!__tests__/**"
|
||||
- "!**/*.test.js"
|
||||
- from: "../client/dist"
|
||||
to: "app/client/dist"
|
||||
filter: ["**/*"]
|
||||
- from: "../scripts"
|
||||
to: "app/scripts"
|
||||
filter:
|
||||
- "**/*"
|
||||
- "!**/*.test.js"
|
||||
- from: "../package.json"
|
||||
to: "app/package.json"
|
||||
- from: "../node_modules"
|
||||
to: "app/node_modules"
|
||||
filter:
|
||||
- "**/*"
|
||||
- "!**/*.md"
|
||||
- "!**/test/**"
|
||||
- "!**/tests/**"
|
||||
- "!**/*.d.ts"
|
||||
# better-sqlite3 ships from desktop/node_modules (per-arch rebuilt by
|
||||
# install-app-deps). The root copy is built for the system Node and
|
||||
# would trip @electron/universal's identical-file detector.
|
||||
- "!**/better-sqlite3/**"
|
||||
# Tray icon images need to live OUTSIDE the asar archive: `nativeImage` can't
|
||||
# always read them from an asar path, and `files` here (out/**, package.json)
|
||||
# would otherwise leave them out of the bundle entirely. Ship them as plain
|
||||
# files at `Resources/assets/`; `trayImagePath()` reads them via
|
||||
# `process.resourcesPath` in production. macOS uses the template PNGs; Windows
|
||||
# uses the colored `icon.ico` (a template/black glyph would vanish on the
|
||||
# dark Windows taskbar).
|
||||
- from: "assets"
|
||||
to: "assets"
|
||||
filter:
|
||||
- "tray-icon-Template*.png"
|
||||
- "icon.ico"
|
||||
|
||||
asar: true
|
||||
asarUnpack:
|
||||
# better-sqlite3 native bindings cannot live inside asar.
|
||||
- "**/node_modules/better-sqlite3/**"
|
||||
|
||||
mac:
|
||||
category: public.app-category.developer-tools
|
||||
icon: assets/icon.icns
|
||||
hardenedRuntime: true
|
||||
gatekeeperAssess: false
|
||||
# Ad-hoc signed by default: the `package` npm script sets
|
||||
# CSC_IDENTITY_AUTO_DISCOVERY=false so a code-signing cert already in the
|
||||
# contributor's keychain is never picked up (it would fail distribution
|
||||
# signing). Real Developer ID signing activates only when CSC_LINK (an
|
||||
# explicit .p12) is provided — that path is unaffected by the flag.
|
||||
# No `arch:` here on purpose. Pinning the arch list in the config makes
|
||||
# electron-builder build *every* listed architecture regardless of the CLI
|
||||
# flag, so `electron-builder --mac --arm64` would still emit an x64 DMG too.
|
||||
# With arch left unspecified, the `--arm64` / `--x64` / `--universal` flags
|
||||
# the `dmg:*` npm scripts pass are what decide which single DMG is produced.
|
||||
target:
|
||||
- dmg
|
||||
extendInfo:
|
||||
LSUIElement: false
|
||||
NSHighResolutionCapable: true
|
||||
NSRequiresAquaSystemAppearance: false
|
||||
|
||||
dmg:
|
||||
artifactName: "ClaudeCodeMonitor-${version}-${arch}.dmg"
|
||||
# The mounted-volume title carries the architecture so that, when a release/
|
||||
# directory holds more than one DMG, the Finder windows are distinguishable
|
||||
# and nobody drags an x64 build onto Apple Silicon (which triggers a Rosetta
|
||||
# prompt). The arch label is NOT set here: the `${arch}` macro expands
|
||||
# inconsistently inside `title` — it yields `-arm64` / an empty string rather
|
||||
# than `arm64` / `x64`. The per-arch `dmg:*` scripts in package.json override
|
||||
# `dmg.title` with an explicit, clean label instead.
|
||||
title: "Claude Code Monitor"
|
||||
icon: assets/icon.icns
|
||||
contents:
|
||||
# Left slot: the .app bundle. Do NOT set `type: file` here — electron-builder
|
||||
# auto-fills the app at this slot when type/path are omitted. With an
|
||||
# explicit `type: file` and no `path`, recent electron-builder resolves
|
||||
# `path: ""` against the project dir and stat's `<repo>/desktop`, then
|
||||
# bombs with `<repo>/desktop not a file`. Omitting both is the canonical
|
||||
# form documented in the electron-builder DMG layout examples.
|
||||
- x: 130
|
||||
y: 220
|
||||
- x: 410
|
||||
y: 220
|
||||
type: link
|
||||
path: /Applications
|
||||
window:
|
||||
width: 540
|
||||
height: 380
|
||||
|
||||
win:
|
||||
# Multi-size BMP icon generated by `scripts/build-win-icon.ps1` from the same
|
||||
# `icon.png` the macOS pipeline renders — see that script's header. Embedded
|
||||
# in the .exe and reused for the installer + taskbar.
|
||||
icon: assets/icon.ico
|
||||
# Emit both an NSIS installer (.exe) and a no-install portable .exe. The
|
||||
# `win` / `win:portable` npm scripts pass an explicit target so each produces
|
||||
# exactly one artifact; a bare `electron-builder --win` builds both. No
|
||||
# `arch:` is pinned here for the same reason as macOS above — the per-arch
|
||||
# CLI flag (`--x64`) is what decides the architecture.
|
||||
target:
|
||||
- nsis
|
||||
- portable
|
||||
# Unsigned by default. Unlike macOS there is no keychain identity to suppress:
|
||||
# Windows signing activates only when an explicit certificate is provided via
|
||||
# CSC_LINK + CSC_KEY_PASSWORD (or win.certificateFile). Unsigned builds run
|
||||
# fine; SmartScreen may show a "more info" prompt on first launch.
|
||||
|
||||
nsis:
|
||||
# A two-step installer (not oneClick) so the user can pick the install dir.
|
||||
# Per-user install (perMachine: false) writes to %LOCALAPPDATA%\Programs and
|
||||
# needs no administrator elevation.
|
||||
oneClick: false
|
||||
perMachine: false
|
||||
allowToChangeInstallationDirectory: true
|
||||
createDesktopShortcut: true
|
||||
createStartMenuShortcut: true
|
||||
shortcutName: "Claude Code Monitor"
|
||||
uninstallDisplayName: "Claude Code Monitor ${version}"
|
||||
artifactName: "ClaudeCodeMonitor-Setup-${version}-${arch}.${ext}"
|
||||
# Keep the per-user SQLite database + settings (under userData) on uninstall,
|
||||
# mirroring macOS where dragging the .app to Trash never touches user data.
|
||||
deleteAppDataOnUninstall: false
|
||||
|
||||
portable:
|
||||
artifactName: "ClaudeCodeMonitor-${version}-${arch}-portable.${ext}"
|
||||
|
||||
# Notarization runs only when the Apple credentials are present (macOS only;
|
||||
# the hook is a no-op on Windows).
|
||||
afterSign: scripts/notarize.js
|
||||
Generated
+5176
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"name": "agent-dashboard-desktop",
|
||||
"version": "1.4.6",
|
||||
"private": true,
|
||||
"description": "Native macOS and Windows desktop shell for Claude Code Agent Monitor.",
|
||||
"author": "Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>",
|
||||
"license": "UNLICENSED",
|
||||
"homepage": "https://git.smartgift.io.vn/Smartgift-AI/Claude-Code-Monitor",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://git.smartgift.io.vn/Smartgift-AI/Claude-Code-Monitor.git"
|
||||
},
|
||||
"main": "out/main.js",
|
||||
"scripts": {
|
||||
"clean": "rm -rf out release",
|
||||
"prebuild": "node scripts/prebuild.js",
|
||||
"build": "npm run prebuild && tsc -p tsconfig.json",
|
||||
"build:icons": "bash scripts/build-icons.sh",
|
||||
"build:win-icon": "powershell -NoProfile -ExecutionPolicy Bypass -File scripts/build-win-icon.ps1",
|
||||
"dev": "npm run build && electron out/main.js",
|
||||
"package": "rm -rf release && npm run build && CSC_IDENTITY_AUTO_DISCOVERY=false electron-builder --mac --arm64 --x64 --publish never",
|
||||
"dmg": "npm run package",
|
||||
"dmg:arm64": "rm -rf release && npm run build && CSC_IDENTITY_AUTO_DISCOVERY=false electron-builder --mac --arm64 --publish never --config.dmg.title='Claude Code Monitor (Apple Silicon)'",
|
||||
"dmg:x64": "rm -rf release && npm run build && CSC_IDENTITY_AUTO_DISCOVERY=false electron-builder --mac --x64 --publish never --config.dmg.title='Claude Code Monitor (Intel)'",
|
||||
"dmg:universal": "rm -rf release && npm run build && CSC_IDENTITY_AUTO_DISCOVERY=false electron-builder --mac --universal --publish never --config.dmg.title='Claude Code Monitor (Universal)'",
|
||||
"win": "npm run build && electron-builder --win nsis --x64 --publish never",
|
||||
"win:portable": "npm run build && electron-builder --win portable --x64 --publish never",
|
||||
"test": "npm run build && node --test --test-reporter=spec tests/smoke.test.mjs",
|
||||
"postinstall": "electron-builder install-app-deps"
|
||||
},
|
||||
"dependencies": {
|
||||
"better-sqlite3": "^11.7.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.10.0",
|
||||
"electron": "^35.7.0",
|
||||
"electron-builder": "^25.1.8",
|
||||
"typescript": "^5.5.4"
|
||||
}
|
||||
}
|
||||
Executable
+91
@@ -0,0 +1,91 @@
|
||||
#!/bin/bash
|
||||
# Generate icon.icns + tray-icon-Template.png{,@2x.png} from the SVG sources.
|
||||
#
|
||||
# Uses macOS-built-in tools only — no Homebrew or npm dependencies:
|
||||
# * qlmanage : SVG → PNG via Quick Look (always present on macOS)
|
||||
# * sips : PNG resize/format
|
||||
# * iconutil : .iconset directory → .icns
|
||||
#
|
||||
# This script is idempotent. Run from desktop/ or from anywhere.
|
||||
# Author: Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
# @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
set -euo pipefail
|
||||
|
||||
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
ASSETS="$(cd "$HERE/../assets" && pwd)"
|
||||
|
||||
require() {
|
||||
command -v "$1" >/dev/null 2>&1 || {
|
||||
echo "error: required tool '$1' not found. This script only runs on macOS." >&2
|
||||
exit 1
|
||||
}
|
||||
}
|
||||
require qlmanage
|
||||
require sips
|
||||
require iconutil
|
||||
|
||||
cd "$ASSETS"
|
||||
|
||||
echo ">>> rendering icon.svg → icon.png (1024)"
|
||||
TMP="$(mktemp -d)"
|
||||
trap 'rm -rf "$TMP"' EXIT
|
||||
qlmanage -t -s 1024 -o "$TMP" icon.svg >/dev/null 2>&1
|
||||
mv "$TMP/icon.svg.png" icon.png
|
||||
|
||||
echo ">>> building icon.iconset"
|
||||
rm -rf icon.iconset
|
||||
mkdir -p icon.iconset
|
||||
for s in 16 32 64 128 256 512 1024; do
|
||||
sips -z "$s" "$s" icon.png --out "icon.iconset/icon_${s}x${s}.png" >/dev/null
|
||||
done
|
||||
# Apple's @2x naming convention.
|
||||
cp icon.iconset/icon_32x32.png icon.iconset/icon_16x16@2x.png
|
||||
cp icon.iconset/icon_64x64.png icon.iconset/icon_32x32@2x.png
|
||||
cp icon.iconset/icon_256x256.png icon.iconset/icon_128x128@2x.png
|
||||
cp icon.iconset/icon_512x512.png icon.iconset/icon_256x256@2x.png
|
||||
cp icon.iconset/icon_1024x1024.png icon.iconset/icon_512x512@2x.png
|
||||
# Drop the 64-only file; iconutil dislikes unknown sizes.
|
||||
rm -f icon.iconset/icon_64x64.png
|
||||
|
||||
echo ">>> compiling icon.icns"
|
||||
iconutil -c icns icon.iconset -o icon.icns
|
||||
rm -rf icon.iconset
|
||||
|
||||
echo ">>> rendering tray-icon-Template.png{,@2x.png} via Python"
|
||||
# qlmanage flattens SVG against an opaque white background — the tray PNG
|
||||
# ends up with alpha=255 everywhere and macOS template tinting turns the
|
||||
# whole 22x22 bounding box white in the menu bar. Generate the RGBA PNG
|
||||
# pixel-by-pixel instead. Geometry mirrors tray-icon.svg (22-unit viewBox).
|
||||
require python3
|
||||
python3 - <<'PY'
|
||||
import struct, zlib
|
||||
|
||||
def make_png(width, height, pixels):
|
||||
def chunk(tag, data):
|
||||
return struct.pack('>I', len(data)) + tag + data + struct.pack('>I', zlib.crc32(tag + data))
|
||||
sig = b'\x89PNG\r\n\x1a\n'
|
||||
ihdr = struct.pack('>IIBBBBB', width, height, 8, 6, 0, 0, 0) # 8-bit RGBA
|
||||
raw = bytearray()
|
||||
for y in range(height):
|
||||
raw.append(0)
|
||||
raw.extend(pixels[y*width*4:(y+1)*width*4])
|
||||
return sig + chunk(b'IHDR', ihdr) + chunk(b'IDAT', zlib.compress(bytes(raw), 9)) + chunk(b'IEND', b'')
|
||||
|
||||
def draw(w, h, s):
|
||||
px = bytearray(w * h * 4) # alpha=0 -> transparent
|
||||
def rect(x, y, rw, rh):
|
||||
for j in range(y, min(y+rh, h)):
|
||||
for i in range(x, min(x+rw, w)):
|
||||
o = (j*w + i) * 4
|
||||
px[o:o+4] = b'\x00\x00\x00\xff' # opaque black
|
||||
rect(2*s, 14*s, 4*s, 7*s)
|
||||
rect(9*s, 11*s, 4*s, 10*s)
|
||||
rect(16*s, 5*s, 4*s, 16*s)
|
||||
return px
|
||||
|
||||
with open('tray-icon-Template.png', 'wb') as f: f.write(make_png(22, 22, draw(22, 22, 1)))
|
||||
with open('tray-icon-Template@2x.png', 'wb') as f: f.write(make_png(44, 44, draw(44, 44, 2)))
|
||||
PY
|
||||
|
||||
echo ">>> done."
|
||||
ls -la icon.icns tray-icon-Template.png tray-icon-Template@2x.png
|
||||
@@ -0,0 +1,121 @@
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Generate assets/icon.ico from assets/icon.png — the Windows counterpart to
|
||||
scripts/build-icons.sh (which produces icon.icns + the macOS tray PNGs).
|
||||
|
||||
.DESCRIPTION
|
||||
Uses only the .NET Framework's System.Drawing (always present on Windows) —
|
||||
no ImageMagick, no npm dependency. icon.png is the 1024x1024 raster already
|
||||
rendered from assets/icon.svg by the macOS icon pipeline; this script
|
||||
downscales it to the standard Windows icon sizes and packs them into a
|
||||
classic, maximally-compatible BMP-based .ico (32bpp BGRA + AND mask). That
|
||||
format is what electron-builder embeds in the .exe and what NSIS uses for
|
||||
the installer icon, and it renders correctly on Windows 7 through 11.
|
||||
|
||||
Idempotent. Run from anywhere:
|
||||
powershell -ExecutionPolicy Bypass -File desktop/scripts/build-win-icon.ps1
|
||||
|
||||
.NOTES
|
||||
Author: Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
#>
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Add-Type -AssemblyName System.Drawing
|
||||
|
||||
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
|
||||
$assets = Join-Path (Split-Path -Parent $here) 'assets'
|
||||
$srcPng = Join-Path $assets 'icon.png'
|
||||
$outIco = Join-Path $assets 'icon.ico'
|
||||
|
||||
if (-not (Test-Path $srcPng)) {
|
||||
throw "icon.png not found at $srcPng. Generate it first (scripts/build-icons.sh renders it from icon.svg)."
|
||||
}
|
||||
|
||||
# Standard Windows icon ladder. 256 is required by electron-builder; the small
|
||||
# sizes keep the taskbar / Alt-Tab / tray crisp.
|
||||
$sizes = 16, 24, 32, 48, 64, 128, 256
|
||||
|
||||
$src = [System.Drawing.Image]::FromFile($srcPng)
|
||||
$entries = New-Object System.Collections.ArrayList
|
||||
|
||||
try {
|
||||
foreach ($s in $sizes) {
|
||||
$bmp = New-Object System.Drawing.Bitmap($s, $s, [System.Drawing.Imaging.PixelFormat]::Format32bppArgb)
|
||||
$g = [System.Drawing.Graphics]::FromImage($bmp)
|
||||
$g.InterpolationMode = [System.Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic
|
||||
$g.PixelOffsetMode = [System.Drawing.Drawing2D.PixelOffsetMode]::HighQuality
|
||||
$g.SmoothingMode = [System.Drawing.Drawing2D.SmoothingMode]::HighQuality
|
||||
$g.CompositingQuality = [System.Drawing.Drawing2D.CompositingQuality]::HighQuality
|
||||
$g.Clear([System.Drawing.Color]::Transparent)
|
||||
$g.DrawImage($src, 0, 0, $s, $s)
|
||||
$g.Dispose()
|
||||
|
||||
# Pull raw pixels: Format32bppArgb is stored little-endian as B,G,R,A —
|
||||
# exactly the byte order a 32bpp DIB wants. Rows are top-down here.
|
||||
$rect = New-Object System.Drawing.Rectangle(0, 0, $s, $s)
|
||||
$data = $bmp.LockBits($rect, [System.Drawing.Imaging.ImageLockMode]::ReadOnly, [System.Drawing.Imaging.PixelFormat]::Format32bppArgb)
|
||||
$stride = $data.Stride
|
||||
$buf = New-Object byte[] ($stride * $s)
|
||||
[System.Runtime.InteropServices.Marshal]::Copy($data.Scan0, $buf, 0, $buf.Length)
|
||||
$bmp.UnlockBits($data)
|
||||
$bmp.Dispose()
|
||||
|
||||
# Build the DIB: BITMAPINFOHEADER(40) + XOR bitmap (bottom-up BGRA) +
|
||||
# 1bpp AND mask (bottom-up, all zeros — alpha channel does the masking).
|
||||
$ms = New-Object System.IO.MemoryStream
|
||||
$bw = New-Object System.IO.BinaryWriter($ms)
|
||||
$bw.Write([int]40) # biSize
|
||||
$bw.Write([int]$s) # biWidth
|
||||
$bw.Write([int]($s * 2)) # biHeight = XOR height + AND height
|
||||
$bw.Write([int16]1) # biPlanes
|
||||
$bw.Write([int16]32) # biBitCount
|
||||
$bw.Write([int]0) # biCompression = BI_RGB
|
||||
$bw.Write([int]0) # biSizeImage
|
||||
$bw.Write([int]0) # biXPelsPerMeter
|
||||
$bw.Write([int]0) # biYPelsPerMeter
|
||||
$bw.Write([int]0) # biClrUsed
|
||||
$bw.Write([int]0) # biClrImportant
|
||||
|
||||
# XOR pixels, bottom-up.
|
||||
for ($y = $s - 1; $y -ge 0; $y--) {
|
||||
$bw.Write($buf, $y * $stride, 4 * $s)
|
||||
}
|
||||
# AND mask: 1 bit/pixel, each row padded to a 4-byte boundary, all zero.
|
||||
$maskRow = [int]([math]::Floor((($s + 31) / 32)) * 4)
|
||||
$zeros = New-Object byte[] ($maskRow)
|
||||
for ($y = 0; $y -lt $s; $y++) { $bw.Write($zeros, 0, $maskRow) }
|
||||
|
||||
$bw.Flush()
|
||||
[void]$entries.Add([pscustomobject]@{ Size = $s; Data = $ms.ToArray() })
|
||||
$bw.Dispose(); $ms.Dispose()
|
||||
}
|
||||
}
|
||||
finally {
|
||||
$src.Dispose()
|
||||
}
|
||||
|
||||
# Assemble the .ico: ICONDIR header, then one ICONDIRENTRY per image, then data.
|
||||
$out = New-Object System.IO.MemoryStream
|
||||
$w = New-Object System.IO.BinaryWriter($out)
|
||||
$w.Write([int16]0) # reserved
|
||||
$w.Write([int16]1) # type = icon
|
||||
$w.Write([int16]$entries.Count) # image count
|
||||
|
||||
$offset = 6 + 16 * $entries.Count
|
||||
foreach ($e in $entries) {
|
||||
$dim = if ($e.Size -ge 256) { 0 } else { $e.Size } # 0 means 256 in the dir
|
||||
$w.Write([byte]$dim) # width
|
||||
$w.Write([byte]$dim) # height
|
||||
$w.Write([byte]0) # palette color count
|
||||
$w.Write([byte]0) # reserved
|
||||
$w.Write([int16]1) # color planes
|
||||
$w.Write([int16]32) # bits per pixel
|
||||
$w.Write([int]$e.Data.Length) # size of image data
|
||||
$w.Write([int]$offset) # offset of image data
|
||||
$offset += $e.Data.Length
|
||||
}
|
||||
foreach ($e in $entries) { $w.Write($e.Data, 0, $e.Data.Length) }
|
||||
$w.Flush()
|
||||
[System.IO.File]::WriteAllBytes($outIco, $out.ToArray())
|
||||
$w.Dispose(); $out.Dispose()
|
||||
|
||||
Write-Output ("Wrote {0} ({1:N0} bytes, sizes: {2})" -f $outIco, (Get-Item $outIco).Length, ($sizes -join ', '))
|
||||
@@ -0,0 +1,40 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* @file Desktop dependency installer with actionable failure help.
|
||||
*
|
||||
* Thin wrapper around `npm install` (which still runs the `postinstall`
|
||||
* `electron-builder install-app-deps` to rebuild native modules for Electron).
|
||||
* On success it behaves exactly like a bare `npm install`. On failure — almost
|
||||
* always the `better-sqlite3` native build — it prints the prerequisite
|
||||
* guidance + the no-toolchain alternative commands, then exits non-zero so the
|
||||
* normal command still fails loudly rather than silently leaving a half-set-up
|
||||
* `node_modules`.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
const { spawnSync } = require("node:child_process");
|
||||
const path = require("node:path");
|
||||
const { printNativeDepHelp, hasBetterSqliteBinary } = require("./preflight");
|
||||
|
||||
const desktopRoot = path.resolve(__dirname, "..");
|
||||
|
||||
// On Windows `npm` is a `.cmd` shim that `spawnSync` can only launch via a
|
||||
// shell; without this it fails with ENOENT. POSIX is unaffected.
|
||||
const result = spawnSync("npm", ["install"], {
|
||||
cwd: desktopRoot,
|
||||
stdio: "inherit",
|
||||
shell: process.platform === "win32",
|
||||
});
|
||||
|
||||
// `npm install` failed outright (e.g. node-gyp could not find a compiler), or
|
||||
// it "succeeded" but the native binary never landed (a prebuilt download was
|
||||
// skipped). Either way the desktop app cannot boot — surface the fix and fail.
|
||||
if (result.status !== 0) {
|
||||
printNativeDepHelp("`npm install` failed while building the native better-sqlite3 module.");
|
||||
process.exit(result.status || 1);
|
||||
}
|
||||
|
||||
if (!hasBetterSqliteBinary()) {
|
||||
printNativeDepHelp("Dependencies installed, but the better-sqlite3 native binary is missing.");
|
||||
process.exit(1);
|
||||
}
|
||||
Executable
+48
@@ -0,0 +1,48 @@
|
||||
/**
|
||||
* @file electron-builder afterSign hook for Apple notarization.
|
||||
*
|
||||
* This is opt-in: it only does anything when all three Apple credentials
|
||||
* are present as environment variables. In every other case (local builds,
|
||||
* fork CI without secrets) the hook is a no-op. That keeps the default
|
||||
* `npm run dmg` working for contributors without an Apple Developer
|
||||
* account while letting the project maintainer flip a switch later.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
exports.default = async function notarizeIfConfigured(context) {
|
||||
const { electronPlatformName, appOutDir, packager } = context;
|
||||
if (electronPlatformName !== "darwin") return;
|
||||
|
||||
const { APPLE_ID, APPLE_TEAM_ID, APPLE_APP_SPECIFIC_PASSWORD } = process.env;
|
||||
if (!APPLE_ID || !APPLE_TEAM_ID || !APPLE_APP_SPECIFIC_PASSWORD) {
|
||||
console.log("[notarize] Apple credentials not set — skipping notarization (ad-hoc only).");
|
||||
return;
|
||||
}
|
||||
|
||||
// Lazy-require: @electron/notarize is only needed when we actually notarize,
|
||||
// so contributors without Apple credentials don't have to install it.
|
||||
let notarize;
|
||||
try {
|
||||
({ notarize } = require("@electron/notarize"));
|
||||
} catch {
|
||||
console.log(
|
||||
"[notarize] Apple credentials present but @electron/notarize is not installed. Run `npm install --save-dev @electron/notarize` in desktop/."
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const appName = packager.appInfo.productFilename;
|
||||
const appPath = `${appOutDir}/${appName}.app`;
|
||||
console.log(`[notarize] notarizing ${appPath}`);
|
||||
|
||||
await notarize({
|
||||
tool: "notarytool",
|
||||
appBundleId: packager.appInfo.id,
|
||||
appPath,
|
||||
appleId: APPLE_ID,
|
||||
appleIdPassword: APPLE_APP_SPECIFIC_PASSWORD,
|
||||
teamId: APPLE_TEAM_ID,
|
||||
});
|
||||
|
||||
console.log("[notarize] done");
|
||||
};
|
||||
Executable
+100
@@ -0,0 +1,100 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* @file Pre-build guard.
|
||||
*
|
||||
* Ensures the desktop bundle has everything it needs before TypeScript
|
||||
* compiles. Specifically:
|
||||
* 1. The root repo's node_modules exists (Express + friends).
|
||||
* 2. The client has been built (client/dist exists). In production mode the
|
||||
* Express server serves the SPA from client/dist; if it's missing the
|
||||
* DMG would ship a 404-only dashboard.
|
||||
* 3. Asset PNGs exist (or we leave a clear warning — icons can be
|
||||
* regenerated via scripts/build-icons.sh).
|
||||
* 4. The desktop-local better-sqlite3 native binary matches this machine's
|
||||
* CPU architecture. A prior `electron-builder --mac --x64/--arm64` build
|
||||
* rebuilds it for the target arch; left mismatched it breaks `desktop:dev`
|
||||
* and `desktop:test` with ERR_DLOPEN_FAILED. We rebuild it if so.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const { spawnSync } = require("node:child_process");
|
||||
const { hasBetterSqliteBinary, printNativeDepHelp } = require("./preflight");
|
||||
|
||||
const desktopRoot = path.resolve(__dirname, "..");
|
||||
const repoRoot = path.resolve(__dirname, "..", "..");
|
||||
const clientDist = path.join(repoRoot, "client", "dist");
|
||||
const rootNodeModules = path.join(repoRoot, "node_modules");
|
||||
const assets = path.join(desktopRoot, "assets");
|
||||
|
||||
function run(cmd, args, opts = {}) {
|
||||
// On Windows `npm`/`npx` are `.cmd` shims that `spawnSync` can only launch
|
||||
// through a shell; without this it fails with ENOENT. POSIX is unaffected.
|
||||
const result = spawnSync(cmd, args, {
|
||||
stdio: "inherit",
|
||||
shell: process.platform === "win32",
|
||||
...opts,
|
||||
});
|
||||
if (result.status !== 0) {
|
||||
throw new Error(`${cmd} ${args.join(" ")} failed with exit ${result.status}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (!fs.existsSync(rootNodeModules)) {
|
||||
console.log("[prebuild] installing root dependencies…");
|
||||
run("npm", ["ci"], { cwd: repoRoot });
|
||||
}
|
||||
|
||||
if (!fs.existsSync(clientDist) || !fs.existsSync(path.join(clientDist, "index.html"))) {
|
||||
console.log("[prebuild] building client (client/dist missing)…");
|
||||
run("npm", ["ci"], { cwd: path.join(repoRoot, "client") });
|
||||
run("npm", ["run", "build"], { cwd: repoRoot });
|
||||
}
|
||||
|
||||
const trayIcon = path.join(assets, "tray-icon-Template.png");
|
||||
if (!fs.existsSync(trayIcon)) {
|
||||
console.warn(
|
||||
"[prebuild] WARN: tray-icon-Template.png missing. Run `npm run build:icons` to regenerate from assets/icon.svg."
|
||||
);
|
||||
}
|
||||
|
||||
// Heal a better-sqlite3 native binary left built for the wrong CPU arch by a
|
||||
// prior `electron-builder --mac --x64/--arm64` run. Without this, `desktop:dev`
|
||||
// and `desktop:test` fail to load the module (ERR_DLOPEN_FAILED) until the
|
||||
// contributor manually re-runs `npm run desktop:install`.
|
||||
if (process.platform === "darwin") {
|
||||
const bsNode = path.join(
|
||||
desktopRoot,
|
||||
"node_modules",
|
||||
"better-sqlite3",
|
||||
"build",
|
||||
"Release",
|
||||
"better_sqlite3.node"
|
||||
);
|
||||
if (fs.existsSync(bsNode)) {
|
||||
const desc = spawnSync("file", ["-b", bsNode], { encoding: "utf8" }).stdout || "";
|
||||
// A universal binary works on both arches; only act on a clear mismatch.
|
||||
const universal = /universal/i.test(desc);
|
||||
const wrongArch =
|
||||
!universal &&
|
||||
((process.arch === "arm64" && !/arm64/.test(desc)) ||
|
||||
(process.arch === "x64" && !/x86_64/.test(desc)));
|
||||
if (wrongArch) {
|
||||
console.log(
|
||||
"[prebuild] better-sqlite3 is built for the wrong CPU arch (a prior DMG build left it that way) — rebuilding for this machine…"
|
||||
);
|
||||
run("npx", ["electron-builder", "install-app-deps"], { cwd: desktopRoot });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The embedded server `require`s better-sqlite3 at boot; without its native
|
||||
// binary the desktop app dies with a fatal dialog after compiling cleanly.
|
||||
// Catch it here (a build-time, copy-pasteable failure) rather than at runtime.
|
||||
if (!hasBetterSqliteBinary()) {
|
||||
printNativeDepHelp("The desktop-local better-sqlite3 native binary is missing.");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.log("[prebuild] ok");
|
||||
@@ -0,0 +1,82 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* @file Shared native-dependency preflight checks + actionable failure help.
|
||||
*
|
||||
* The desktop shell embeds the dashboard server in-process, which `require`s
|
||||
* the native `better-sqlite3` module rebuilt against Electron's Node ABI. That
|
||||
* build is the single most common setup failure: it needs either a C++ toolchain
|
||||
* (to compile from source) or a Node version new enough to have a prebuilt
|
||||
* binary. When it's missing we want a clear, copy-pasteable message instead of a
|
||||
* raw node-gyp stack trace or a runtime "Cannot find module" deep inside boot.
|
||||
*
|
||||
* This module is shared by `install.js` (wraps the dependency install) and
|
||||
* `prebuild.js` (gates every `desktop:*` build/dev script) so both surfaces
|
||||
* print the same guidance.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
|
||||
const desktopRoot = path.resolve(__dirname, "..");
|
||||
|
||||
/** Absolute path to the compiled/prebuilt better-sqlite3 native binary. */
|
||||
function betterSqliteBinary() {
|
||||
return path.join(
|
||||
desktopRoot,
|
||||
"node_modules",
|
||||
"better-sqlite3",
|
||||
"build",
|
||||
"Release",
|
||||
"better_sqlite3.node"
|
||||
);
|
||||
}
|
||||
|
||||
/** True when the Electron-ABI better-sqlite3 binary is present on disk. */
|
||||
function hasBetterSqliteBinary() {
|
||||
return fs.existsSync(betterSqliteBinary());
|
||||
}
|
||||
|
||||
/**
|
||||
* Print prerequisite guidance and the no-toolchain alternative commands to
|
||||
* stderr. Callers should `process.exit(1)` after this so the failing npm
|
||||
* command exits non-zero (never leave the user thinking setup succeeded).
|
||||
*/
|
||||
function printNativeDepHelp(reason) {
|
||||
const line = "─".repeat(74);
|
||||
const out = (s) => process.stderr.write(s + "\n");
|
||||
out("");
|
||||
out(line);
|
||||
out(" Claude Code Monitor — desktop native dependency setup did not complete");
|
||||
out(line);
|
||||
if (reason) {
|
||||
out(` ${reason}`);
|
||||
out("");
|
||||
}
|
||||
out(" The desktop app embeds the dashboard server, which needs the native");
|
||||
out(" 'better-sqlite3' module built for Electron's Node ABI. This typically");
|
||||
out(" fails for one of two reasons:");
|
||||
out("");
|
||||
out(" 1. No C++ build toolchain, so the module can't compile from source:");
|
||||
out(' • Windows: install "Visual Studio Build Tools" with the');
|
||||
out(' "Desktop development with C++" workload.');
|
||||
out(" • macOS: xcode-select --install");
|
||||
out(" • Linux: install build-essential + python3.");
|
||||
out("");
|
||||
out(" 2. Your Node.js is newer than any published better-sqlite3 prebuilt");
|
||||
out(` binary (you are on Node ${process.version}). A Node LTS (20 or 22)`);
|
||||
out(" ships prebuilt binaries and avoids the compile entirely.");
|
||||
out("");
|
||||
out(" Or skip the source build and fetch Electron's prebuilt binary directly");
|
||||
out(" (no C++ toolchain needed):");
|
||||
out("");
|
||||
out(" cd desktop");
|
||||
out(" npm install --ignore-scripts");
|
||||
out(" node node_modules/electron/install.js");
|
||||
out(" npx electron-builder install-app-deps");
|
||||
out("");
|
||||
out(line);
|
||||
out("");
|
||||
}
|
||||
|
||||
module.exports = { betterSqliteBinary, hasBetterSqliteBinary, printNativeDepHelp };
|
||||
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
/**
|
||||
* @file Desktop smoke test.
|
||||
*
|
||||
* Boots the compiled main process under Electron, then probes the embedded
|
||||
* dashboard server's /api/health endpoint. This is intentionally minimal:
|
||||
* it does not exercise the BrowserWindow (which requires a display) so it
|
||||
* runs on headless CI without xvfb. The window itself is covered by manual
|
||||
* QA in the PR description.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
import { describe, it, before, after } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { spawn } from "node:child_process";
|
||||
import { once } from "node:events";
|
||||
import http from "node:http";
|
||||
import { createRequire } from "node:module";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const DESKTOP_ROOT = path.resolve(__dirname, "..");
|
||||
const MAIN_JS = path.join(DESKTOP_ROOT, "out", "main.js");
|
||||
// Resolve the actual Electron executable (electron.exe on Windows, the binary
|
||||
// under Electron.app on macOS). The `.bin/electron` shim is extension-less and
|
||||
// cannot be spawned without a shell on Windows; `require("electron")` returns
|
||||
// the real binary path on every platform.
|
||||
const ELECTRON_BIN = createRequire(import.meta.url)("electron");
|
||||
|
||||
const HEALTH_TIMEOUT_MS = 60_000;
|
||||
const POLL_INTERVAL_MS = 500;
|
||||
|
||||
/** Resolve when GET /api/health on any of these ports answers ok. */
|
||||
async function waitForHealth(ports, deadline) {
|
||||
while (Date.now() < deadline) {
|
||||
for (const port of ports) {
|
||||
const ok = await probeHealth(port);
|
||||
if (ok) return port;
|
||||
}
|
||||
await new Promise((r) => setTimeout(r, POLL_INTERVAL_MS));
|
||||
}
|
||||
throw new Error(`No port answered /api/health within ${HEALTH_TIMEOUT_MS}ms (tried ${ports})`);
|
||||
}
|
||||
|
||||
function probeHealth(port) {
|
||||
return new Promise((resolve) => {
|
||||
const req = http.get({ host: "127.0.0.1", port, path: "/api/health", timeout: 1500 }, (res) => {
|
||||
let buf = "";
|
||||
res.setEncoding("utf8");
|
||||
res.on("data", (chunk) => (buf += chunk));
|
||||
res.on("end", () => {
|
||||
try {
|
||||
resolve(JSON.parse(buf)?.status === "ok");
|
||||
} catch {
|
||||
resolve(false);
|
||||
}
|
||||
});
|
||||
});
|
||||
req.on("error", () => resolve(false));
|
||||
req.on("timeout", () => {
|
||||
req.destroy();
|
||||
resolve(false);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
let electronProc;
|
||||
// Pick a unique high port for each test run so we never accidentally probe an
|
||||
// unrelated server (e.g. the user's own `npm start` on 4820). The env var
|
||||
// `CCAM_DESKTOP_BIND_PORT` tells the desktop process to bind exactly this port,
|
||||
// skipping the "adopt an existing healthy server" code path.
|
||||
const TEST_PORT = 50000 + Math.floor(Math.random() * 5000);
|
||||
|
||||
// On POSIX, spawn the Electron parent as a process-group leader so we can
|
||||
// signal the whole tree (helpers, embedded server) with one kill(-pid).
|
||||
// Without this, SIGTERM only hits the parent and leaves helpers alive,
|
||||
// keeping the stdio pipes open and hanging `node --test` indefinitely.
|
||||
const IS_POSIX = process.platform !== "win32";
|
||||
|
||||
/** Kill the Electron process tree and resolve when it's actually gone. */
|
||||
async function killElectronTree(proc, { timeoutMs = 5_000 } = {}) {
|
||||
if (!proc || proc.exitCode !== null || proc.signalCode !== null) return;
|
||||
proc.killedByTest = true;
|
||||
|
||||
const signalGroup = (sig) => {
|
||||
try {
|
||||
if (IS_POSIX && proc.pid) process.kill(-proc.pid, sig);
|
||||
else proc.kill(sig);
|
||||
} catch {
|
||||
/* group may already be gone */
|
||||
}
|
||||
};
|
||||
|
||||
const exited = once(proc, "exit");
|
||||
signalGroup("SIGTERM");
|
||||
|
||||
const timer = new Promise((resolve) => setTimeout(resolve, timeoutMs, "timeout"));
|
||||
const winner = await Promise.race([exited.then(() => "exit"), timer]);
|
||||
if (winner === "timeout") {
|
||||
signalGroup("SIGKILL");
|
||||
await Promise.race([exited, new Promise((r) => setTimeout(r, 2_000))]);
|
||||
}
|
||||
}
|
||||
|
||||
describe("desktop smoke", () => {
|
||||
before(async () => {
|
||||
electronProc = spawn(ELECTRON_BIN, [MAIN_JS], {
|
||||
cwd: DESKTOP_ROOT,
|
||||
detached: IS_POSIX,
|
||||
env: {
|
||||
...process.env,
|
||||
// Suppress the BrowserWindow on the test runner; we only care that
|
||||
// the server boots cleanly.
|
||||
ELECTRON_DISABLE_GPU: "1",
|
||||
ELECTRON_ENABLE_LOGGING: "1",
|
||||
CCAM_DESKTOP_VERBOSE: "1",
|
||||
CCAM_DESKTOP_BIND_PORT: String(TEST_PORT),
|
||||
},
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
|
||||
electronProc.stdout.on("data", (b) => process.stdout.write(`[electron] ${b}`));
|
||||
electronProc.stderr.on("data", (b) => process.stderr.write(`[electron] ${b}`));
|
||||
|
||||
electronProc.on("exit", (code, signal) => {
|
||||
if (!electronProc.killedByTest) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(`electron exited unexpectedly: code=${code} signal=${signal}`);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
after(async () => {
|
||||
await killElectronTree(electronProc);
|
||||
});
|
||||
|
||||
it("brings up the embedded server and serves /api/health on the bound port", async () => {
|
||||
const deadline = Date.now() + HEALTH_TIMEOUT_MS;
|
||||
const port = await waitForHealth([TEST_PORT], deadline);
|
||||
assert.equal(
|
||||
port,
|
||||
TEST_PORT,
|
||||
`desktop process should have bound CCAM_DESKTOP_BIND_PORT=${TEST_PORT}`
|
||||
);
|
||||
assert.ok(
|
||||
electronProc && !electronProc.killed && electronProc.exitCode === null,
|
||||
"electron process should still be alive when /api/health answers"
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "Node16",
|
||||
"moduleResolution": "Node16",
|
||||
"lib": ["ES2022"],
|
||||
"outDir": "out",
|
||||
"rootDir": "src",
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noUncheckedIndexedAccess": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"esModuleInterop": true,
|
||||
"resolveJsonModule": true,
|
||||
"skipLibCheck": true,
|
||||
"sourceMap": true,
|
||||
"declaration": false
|
||||
},
|
||||
"include": ["src/**/*.ts"],
|
||||
"exclude": ["node_modules", "out", "release", "tests"]
|
||||
}
|
||||
Reference in New Issue
Block a user