Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

refactor(core): move license + context-link onto CorePlatform

enes67f00887a598
diff --git a/src/main/context-link.ts b/src/core/context-link.ts
similarity index 89%
rename from src/main/context-link.ts
rename to src/core/context-link.ts
index 2113e709a..15dec237d 100644
--- a/src/main/context-link.ts
+++ b/src/core/context-link.ts
@@ -10,18 +10,18 @@
import fs from 'fs'
import os from 'os'
import path from 'path'
-import { app, ipcMain, type BrowserWindow } from 'electron'
+import { platform } from './platform'
import { IPC } from '../shared/ipc'
import type { ContextLinkMap } from '../shared/types'
-import { type PtyManager } from '../core/pty-manager'
-import { TMUX_SOCKET } from '../core/tmux-naming'
-import { CLI_SCRIPT, buildLinkDoc, transcriptPathOf } from '../core/context-link-core'
+import { type PtyManager } from './pty-manager'
+import { TMUX_SOCKET } from './tmux-naming'
+import { CLI_SCRIPT, buildLinkDoc, transcriptPathOf } from './context-link-core'
-export { setNodeTranscript } from '../core/context-link-core'
+export { setNodeTranscript } from './context-link-core'
let dir = ''
export function contextLinkDir(): string {
- if (!dir) dir = path.join(app.getPath('userData'), 'context-links')
+ if (!dir) dir = path.join(platform().userDataDir, 'context-links')
return dir
}
function cliScriptPath(): string {
@@ -119,7 +119,7 @@ async function writeLinkFiles(map: ContextLinkMap): Promise<void> {
}
}
-export function initContextLink(win: BrowserWindow, ptyManager: PtyManager): void {
+export function initContextLink(ptyManager: PtyManager): void {
pty = ptyManager
try {
const d = contextLinkDir()
@@ -137,10 +137,8 @@ export function initContextLink(win: BrowserWindow, ptyManager: PtyManager): voi
// calls could interleave (B's clear runs before A's writes land) and leave a just-removed
// link file behind — which is a read-authorization leak, not just a perf nit.
let writeChain: Promise<void> = Promise.resolve()
- ipcMain.handle(IPC.contextLinkSetLinks, (_e, map: ContextLinkMap) => {
+ platform().handle(IPC.contextLinkSetLinks, (map: ContextLinkMap) => {
writeChain = writeChain.then(() => writeLinkFiles(map && typeof map === 'object' ? map : {}))
return writeChain
})
- // win is reserved for future link-activity events; referenced to satisfy noUnusedParameters.
- void win
}
diff --git a/src/main/license.test.ts b/src/core/license.test.ts
similarity index 74%
rename from src/main/license.test.ts
rename to src/core/license.test.ts
index ad34471d7..d009a3e96 100644
--- a/src/main/license.test.ts
+++ b/src/core/license.test.ts
@@ -6,24 +6,13 @@ import path from 'path'
import { IPC } from '../shared/ipc'
import type { LicenseStatus } from '../shared/types'
-// One temp userData dir per run; hoisted so the electron mock factory can see it.
+// One temp userData dir per run; hoisted so the entitlement-key mock factory can see it.
const h = vi.hoisted(() => ({
userData: '',
- publicKeyPem: '',
- handlers: {} as Record<string, (...args: unknown[]) => unknown>
+ publicKeyPem: ''
}))
-vi.mock('electron', () => ({
- app: { getPath: () => h.userData, isPackaged: false },
- ipcMain: {
- handle: (channel: string, fn: (...args: unknown[]) => unknown) => {
- h.handlers[channel] = fn
- }
- },
- shell: { openExternal: vi.fn() }
-}))
-
-vi.mock('../core/entitlement-key', () => ({
+vi.mock('./entitlement-key', () => ({
get ENTITLEMENT_PUBLIC_KEY() {
return h.publicKeyPem
}
@@ -51,19 +40,6 @@ function jsonResponse(body: unknown): { ok: boolean; status: number; json: () =>
return { ok: true, status: 200, json: async () => body }
}
-function fakeWindow(): { win: never; sent: LicenseStatus[] } {
- const sent: LicenseStatus[] = []
- const win = {
- isDestroyed: () => false,
- webContents: {
- send: (channel: string, status: LicenseStatus) => {
- if (channel === IPC.licenseChanged) sent.push(status)
- }
- }
- }
- return { win: win as never, sent }
-}
-
const HOUR = 60 * 60 * 1000
/** Let real I/O (fs writes in save()) and microtasks settle — setTimeout stays unfaked. */
@@ -73,13 +49,17 @@ async function flush(): Promise<void> {
describe('license entitlement refresh', () => {
let fetchMock: ReturnType<typeof vi.fn>
+ let fake: import('./platform-fake').FakePlatform
+
+ // The licenseChanged statuses broadcast so far (fake.sent records {to, channel, args}).
+ const sent = (): LicenseStatus[] =>
+ fake.sent.filter((s) => s.channel === IPC.licenseChanged).map((s) => s.args[0] as LicenseStatus)
beforeEach(async () => {
// Only the refresh interval and the clock are faked: fetch/fs promises and the
// 8s abort timers stay on the real event loop so awaits actually settle.
vi.useFakeTimers({ toFake: ['setInterval', 'Date'] })
h.userData = mkdtempSync(path.join(tmpdir(), 'nt-license-test-'))
- h.handlers = {}
// Pin this "machine"'s device id so minted tokens match it (device-bound verification).
writeFileSync(path.join(h.userData, 'device-id'), 'test-device')
delete process.env.DO_NOT_TRACK
@@ -91,15 +71,16 @@ describe('license entitlement refresh', () => {
// device-id (imported transitively by license) reads userData through the core platform,
// so point the fake at this run's temp dir. Init on the post-reset module graph the
// dynamic `import('./license')` below will resolve against.
- const { initPlatform } = await import('../core/platform')
- const { fakePlatform } = await import('../core/platform-fake')
- initPlatform(fakePlatform({ userDataDir: h.userData }))
+ const { initPlatform } = await import('./platform')
+ const { fakePlatform } = await import('./platform-fake')
+ fake = fakePlatform({ userDataDir: h.userData, isPackaged: false })
+ initPlatform(fake)
})
afterEach(async () => {
vi.unstubAllGlobals()
vi.useRealTimers()
- const { resetPlatformForTests } = await import('../core/platform')
+ const { resetPlatformForTests } = await import('./platform')
resetPlatformForTests()
rmSync(h.userData, { recursive: true, force: true })
})
@@ -108,14 +89,13 @@ describe('license entitlement refresh', () => {
const token = mint(7 * 24 * 60 * 60)
fetchMock.mockResolvedValue(jsonResponse({ active: true, token }))
const { initLicense } = await import('./license')
- const { win, sent } = fakeWindow()
- initLicense(win)
+ initLicense()
await flush()
expect(fetchMock).toHaveBeenCalledTimes(1)
- expect(sent.length).toBe(1)
- expect(sent[0].active).toBe(true)
- expect(sent[0].tier).toBe('pro')
+ expect(sent().length).toBe(1)
+ expect(sent()[0].active).toBe(true)
+ expect(sent()[0].tier).toBe('pro')
})
it('keeps refreshing periodically so a mid-session token expiry re-mints instead of dropping Pro', async () => {
@@ -125,8 +105,7 @@ describe('license entitlement refresh', () => {
jsonResponse({ active: true, token: mint(7 * 24 * 60 * 60) })
)
const { initLicense } = await import('./license')
- const { win, sent } = fakeWindow()
- initLicense(win)
+ initLicense()
await flush()
expect(fetchMock).toHaveBeenCalledTimes(1)
@@ -135,7 +114,7 @@ describe('license entitlement refresh', () => {
await vi.advanceTimersByTimeAsync(24 * HOUR)
await flush()
expect(fetchMock.mock.calls.length).toBeGreaterThanOrEqual(2)
- const last = sent[sent.length - 1]
+ const last = sent().at(-1)!
expect(last.active).toBe(true)
})
@@ -144,16 +123,15 @@ describe('license entitlement refresh', () => {
jsonResponse({ active: true, token: mint(7 * 24 * 60 * 60) })
)
const { initLicense } = await import('./license')
- const { win, sent } = fakeWindow()
- initLicense(win)
+ initLicense()
await flush()
- expect(sent[sent.length - 1].active).toBe(true)
+ expect(sent().at(-1)!.active).toBe(true)
// From now on the server says: not entitled (canceled subscription).
fetchMock.mockResolvedValue(jsonResponse({ active: false }))
await vi.advanceTimersByTimeAsync(24 * HOUR)
await flush()
- expect(sent[sent.length - 1].active).toBe(false)
+ expect(sent().at(-1)!.active).toBe(false)
})
it('rejects a token minted for a different device (copied license.json)', async () => {
@@ -162,12 +140,11 @@ describe('license entitlement refresh', () => {
jsonResponse({ active: true, token: mint(7 * 24 * 60 * 60, 'other-device') })
)
const { initLicense } = await import('./license')
- const { win, sent } = fakeWindow()
- initLicense(win)
+ initLicense()
await flush()
- expect(sent.length).toBeGreaterThan(0)
- expect(sent[sent.length - 1].active).toBe(false)
+ expect(sent().length).toBeGreaterThan(0)
+ expect(sent().at(-1)!.active).toBe(false)
})
it('does not revive an expired token when the system clock is rolled back', async () => {
@@ -175,10 +152,9 @@ describe('license entitlement refresh', () => {
jsonResponse({ active: true, token: mint(7 * 24 * 60 * 60) })
)
const { initLicense } = await import('./license')
- const { win, sent } = fakeWindow()
- initLicense(win)
+ initLicense()
await flush()
- expect(sent[sent.length - 1].active).toBe(true)
+ expect(sent().at(-1)!.active).toBe(true)
// Server unreachable from now on (offline grace path), and the token expires in-session.
fetchMock.mockRejectedValue(new Error('offline'))
@@ -188,7 +164,7 @@ describe('license entitlement refresh', () => {
// Attacker rolls the clock back before the expiry: exp is "in the future" again,
// but the app has already observed a later time — the token must stay dead.
vi.setSystemTime(Date.now() - 9 * 24 * HOUR)
- const status = (await h.handlers[IPC.licenseStatus]()) as LicenseStatus
+ const status = (await fake.handlers[IPC.licenseStatus]()) as LicenseStatus
expect(status.active).toBe(false)
})
})
diff --git a/src/main/license.ts b/src/core/license.ts
similarity index 92%
rename from src/main/license.ts
rename to src/core/license.ts
index f5f906aca..4a8ff18a1 100644
--- a/src/main/license.ts
+++ b/src/core/license.ts
@@ -6,11 +6,11 @@
import { promises as fs, readFileSync } from 'fs'
import path from 'path'
import crypto from 'node:crypto'
-import { app, ipcMain, shell, type BrowserWindow } from 'electron'
+import { platform } from './platform'
import { IPC } from '../shared/ipc'
import type { LicenseStatus } from '../shared/types'
-import { getDeviceId } from '../core/device-id'
-import { ENTITLEMENT_PUBLIC_KEY } from '../core/entitlement-key'
+import { getDeviceId } from './device-id'
+import { ENTITLEMENT_PUBLIC_KEY } from './entitlement-key'
const API_BASE = process.env.NODETERM_API_BASE || 'https://api.nodeterm.dev'
@@ -28,7 +28,7 @@ const REFRESH_INTERVAL_MS = 6 * 60 * 60 * 1000
// local server is targeted explicitly, and honor DO_NOT_TRACK / the kill switch.
function allowed(): boolean {
if (process.env.DO_NOT_TRACK || process.env.NODETERM_TELEMETRY_DISABLED) return false
- if (!app.isPackaged && !process.env.NODETERM_API_BASE) return false
+ if (!platform().isPackaged && !process.env.NODETERM_API_BASE) return false
return true
}
@@ -40,7 +40,7 @@ interface Stored {
}
function file(): string {
- return path.join(app.getPath('userData'), 'license.json')
+ return path.join(platform().userDataDir, 'license.json')
}
function load(): Stored {
try {
@@ -140,20 +140,20 @@ export function isPremium(): boolean {
return verify(load().token) !== null
}
-export function initLicense(win: BrowserWindow): void {
+export function initLicense(): void {
const deviceId = getDeviceId()
const broadcast = (s: LicenseStatus) => {
- if (!win.isDestroyed()) win.webContents.send(IPC.licenseChanged, s)
+ platform().broadcast(IPC.licenseChanged, s)
}
- ipcMain.handle(IPC.licenseStatus, () => statusFrom(load().token))
+ platform().handle(IPC.licenseStatus, () => statusFrom(load().token))
// Device-bound upgrade: open Stripe checkout (carrying our deviceId), then poll the status
// endpoint until the webhook has bound + minted the entitlement. Status arrives via broadcast.
let polling = false
- ipcMain.handle(IPC.licenseUpgrade, async () => {
+ platform().handle(IPC.licenseUpgrade, async () => {
const url = `${CHECKOUT_URL}${CHECKOUT_URL.includes('?') ? '&' : '?'}client_reference_id=${encodeURIComponent(deviceId)}`
- await shell.openExternal(url)
+ await platform().openExternal(url)
if (!polling) {
polling = true
const deadline = Date.now() + 6 * 60 * 1000 // poll up to 6 min after opening checkout
@@ -176,7 +176,7 @@ export function initLicense(win: BrowserWindow): void {
return statusFrom(load().token)
})
- ipcMain.handle(IPC.licenseActivate, async (_e, key: string) => {
+ platform().handle(IPC.licenseActivate, async (key: string) => {
const r = await call('/v1/license/activate', { key: String(key).trim(), deviceId })
if (r.token) await save({ ...load(), key: String(key).trim(), token: r.token })
const status = statusFrom(r.token, r.error ?? null)
@@ -184,7 +184,7 @@ export function initLicense(win: BrowserWindow): void {
return status
})
- ipcMain.handle(IPC.licenseDeactivate, async () => {
+ platform().handle(IPC.licenseDeactivate, async () => {
const stored = load()
if (stored.key) await call('/v1/license/deactivate', { key: stored.key, deviceId })
await save({ lastSeen: stored.lastSeen }) // keep the clock anchor across deactivations
diff --git a/src/main/index.ts b/src/main/index.ts
index 93b354266..71d2663fc 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -37,12 +37,12 @@ import { childArgs } from '../core/remote-ssh/control-master'
import { posixQuote } from '../shared/ssh'
import { buildHandoff } from './handoff'
import { ChatDriver } from '../core/chat-driver'
-import { initContextLink, setNodeTranscript } from './context-link'
+import { initContextLink, setNodeTranscript } from '../core/context-link'
import { initCanvasControl, installCanvasSkillInto } from './canvas-control'
import { initTranscriptIndex, searchTranscripts } from '../core/transcript-index'
import { initTelemetry } from './telemetry'
import { initClaudeUsage } from './claude-usage'
-import { initLicense } from './license'
+import { initLicense } from '../core/license'
import { initClaudeAccounts } from './claude-accounts'
import { claudeConfigDirFor } from '../core/claude-config-dir'
import { isSafeLocalTranscriptPath } from '../core/claude-accounts-core'
@@ -817,11 +817,11 @@ app.whenReady().then(async () => {
await hookServer.start()
initMediaProtocol()
- initContextLink(win, ptyManager)
+ initContextLink(ptyManager)
initCanvasControl()
initClaudeUsage(win)
initTelemetry(() => settingsStore.get())
- initLicense(win)
+ initLicense()
// Lazy getter: sshProjectManager is created just below, so a remote account op (which only runs
// after the user has connected an SSH project) always sees the live manager.
initClaudeAccounts(() => sshProjectManager)
diff --git a/src/main/remote/host-service.ts b/src/main/remote/host-service.ts
index fd60db8eb..fa146d327 100644
--- a/src/main/remote/host-service.ts
+++ b/src/main/remote/host-service.ts
@@ -27,7 +27,7 @@ import type { CanvasMutation, CanvasState, DirEntry, PtyCreateOptions } from '..
import type { AgentId } from '../../shared/agents/config'
import { PtyManager, type DetachedSinks } from '../../core/pty-manager'
import * as fsOps from '../../core/fs-ops'
-import { getStoredEntitlement, isPremium } from '../license'
+import { getStoredEntitlement, isPremium } from '../../core/license'
import { genKeyPair, publicKeyToB64, type KeyPair } from './e2ee'
import { OP, type Frame } from './framing'
import { encodeOffer } from './pairing'