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.

feat(server): ServerPlatform — CorePlatform over a WS sink registry + RPC dispatch

enesb80ca287c745
diff --git a/src/server/no-electron.test.ts b/src/server/no-electron.test.ts
new file mode 100644
index 000000000..c4a57d641
--- /dev/null
+++ b/src/server/no-electron.test.ts
@@ -0,0 +1,50 @@
+import { describe, it, expect } from 'vitest'
+import fs from 'fs'
+import path from 'path'
+
+function walk(dir: string): string[] {
+ return fs.readdirSync(dir, { withFileTypes: true }).flatMap((e) => {
+ const p = path.join(dir, e.name)
+ return e.isDirectory() ? walk(p) : p.endsWith('.ts') ? [p] : []
+ })
+}
+
+// Catches: bare `electron`, electron subpaths (`electron/main`), and any reach-back
+// into the Electron shell (`../main/`, `../../main/`) — via import or require.
+const OFFENDERS =
+ /from ['"]electron(\/[^'"]*)?['"]|require\(['"]electron(\/[^'"]*)?['"]\)|from ['"](\.\.\/)+main\//
+
+describe('server boundary', () => {
+ it('no file under src/server imports electron or reaches back into ../main', () => {
+ const offenders = walk(__dirname)
+ // This test file itself contains sample offender strings (below) to prove the regex.
+ .filter((f) => f !== __filename)
+ .filter((f) => OFFENDERS.test(fs.readFileSync(f, 'utf8')))
+ expect(offenders).toEqual([])
+ })
+
+ it('offenders regex catches electron, electron subpaths, and ../main reach-backs', () => {
+ // These must all be flagged:
+ for (const bad of [
+ `import { app } from 'electron'`,
+ `import { BrowserWindow } from "electron"`,
+ `const { ipcMain } = require('electron')`,
+ `import { x } from 'electron/main'`,
+ `const y = require("electron/common")`,
+ `import { PtyManager } from '../main/pty-manager'`,
+ `import { z } from '../../main/index'`
+ ]) {
+ expect(OFFENDERS.test(bad), bad).toBe(true)
+ }
+ // These must NOT be flagged (legitimate server imports):
+ for (const ok of [
+ `import fs from 'fs'`,
+ `import { CorePlatform } from '../core/platform'`,
+ `import { foo } from '../core/foo'`,
+ `import { bar } from '@shared/ipc'`,
+ `import electronBuilder from 'electron-builder'`
+ ]) {
+ expect(OFFENDERS.test(ok), ok).toBe(false)
+ }
+ })
+})
diff --git a/src/server/platform-server.test.ts b/src/server/platform-server.test.ts
new file mode 100644
index 000000000..5a355df55
--- /dev/null
+++ b/src/server/platform-server.test.ts
@@ -0,0 +1,77 @@
+import { describe, it, expect } from 'vitest'
+import { ServerPlatform, type UiSink } from './platform-server'
+import { E_NO_HANDLER } from '../shared/rpc'
+import { decodePtyData } from '../shared/rpc'
+
+function fakeSink() {
+ const texts: string[] = []
+ const bins: Uint8Array[] = []
+ const sink: UiSink = { sendText: (j) => texts.push(j), sendBinary: (b) => bins.push(b) }
+ return { sink, texts, bins }
+}
+
+describe('ServerPlatform', () => {
+ it('dispatches req to handle and handleWithSender (sender = uiId)', async () => {
+ const p = new ServerPlatform({ userDataDir: '/tmp/x', appVersion: '1.0.0' })
+ p.handle('a:b', (n: number) => n + 1)
+ p.handleWithSender('a:c', (sender: number, s: string) => `${sender}:${s}`)
+ const { sink } = fakeSink()
+ const ui = p.attach(sink)
+ expect(await p.dispatch(ui, { t: 'req', id: 1, method: 'a:b', args: [41] })).toEqual({
+ t: 'res', id: 1, ok: true, result: 42
+ })
+ expect(await p.dispatch(ui, { t: 'req', id: 2, method: 'a:c', args: ['x'] })).toEqual({
+ t: 'res', id: 2, ok: true, result: `${ui}:x`
+ })
+ })
+
+ it('unknown method → E_NO_HANDLER; throwing handler → E_HANDLER with message', async () => {
+ const p = new ServerPlatform({ userDataDir: '/tmp/x', appVersion: '1.0.0' })
+ p.handle('boom', () => { throw new Error('kapow') })
+ const ui = p.attach(fakeSink().sink)
+ const missing = await p.dispatch(ui, { t: 'req', id: 3, method: 'nope', args: [] })
+ expect(missing).toMatchObject({ ok: false, error: { code: E_NO_HANDLER } })
+ const thrown = await p.dispatch(ui, { t: 'req', id: 4, method: 'boom', args: [] })
+ expect(thrown).toMatchObject({ ok: false, error: { code: 'E_HANDLER', message: 'kapow' } })
+ })
+
+ it('cast runs on-listeners and ignores unknown methods silently', () => {
+ const p = new ServerPlatform({ userDataDir: '/tmp/x', appVersion: '1.0.0' })
+ const got: unknown[] = []
+ p.on('w', (a: string) => got.push(a))
+ const ui = p.attach(fakeSink().sink)
+ p.cast(ui, 'w', ['hello'])
+ p.cast(ui, 'unknown', ['ignored'])
+ expect(got).toEqual(['hello'])
+ })
+
+ it('sendTo routes pty:data as binary, other channels as JSON events, drops when detached', () => {
+ const p = new ServerPlatform({ userDataDir: '/tmp/x', appVersion: '1.0.0' })
+ const a = fakeSink()
+ const ui = p.attach(a.sink)
+ p.sendTo(ui, 'pty:data:s1', 'output')
+ p.sendTo(ui, 'pty:exit:s1', 0)
+ expect(decodePtyData(a.bins[0])).toEqual({ sessionId: 's1', data: 'output' })
+ expect(JSON.parse(a.texts[0])).toEqual({ t: 'ev', channel: 'pty:exit:s1', args: [0] })
+ p.detach(ui)
+ p.sendTo(ui, 'pty:exit:s1', 1) // must not throw
+ expect(a.texts).toHaveLength(1)
+ })
+
+ it('broadcast reaches every attached sink', () => {
+ const p = new ServerPlatform({ userDataDir: '/tmp/x', appVersion: '1.0.0' })
+ const a = fakeSink(); const b = fakeSink()
+ p.attach(a.sink); p.attach(b.sink)
+ p.broadcast('license:changed', { tier: 'x' })
+ expect(a.texts).toHaveLength(1)
+ expect(b.texts).toHaveLength(1)
+ })
+
+ it('exposes userDataDir/appVersion/isPackaged; openExternal rejects', async () => {
+ const p = new ServerPlatform({ userDataDir: '/data', appVersion: '9.9.9' })
+ expect(p.userDataDir).toBe('/data')
+ expect(p.appVersion).toBe('9.9.9')
+ expect(p.isPackaged).toBe(true)
+ await expect(p.openExternal('https://x')).rejects.toThrow()
+ })
+})
diff --git a/src/server/platform-server.ts b/src/server/platform-server.ts
new file mode 100644
index 000000000..2afcb2226
--- /dev/null
+++ b/src/server/platform-server.ts
@@ -0,0 +1,99 @@
+import type { CorePlatform } from '../core/platform'
+import {
+ E_NO_HANDLER,
+ encodePtyData,
+ type RpcErr,
+ type RpcOk,
+ type RpcRequest
+} from '../shared/rpc'
+
+export interface UiSink {
+ sendText(json: string): void
+ sendBinary(buf: Uint8Array): void
+}
+
+const PTY_DATA_PREFIX = 'pty:data:'
+
+type Handler = { fn: (...args: any[]) => unknown; withSender: boolean }
+
+/** The Linux-server CorePlatform: RPC registries + a WS-connection (UiSink) registry.
+ * One instance per server process; each authenticated WebSocket attaches as one UI. */
+export class ServerPlatform implements CorePlatform {
+ readonly userDataDir: string
+ readonly appVersion: string
+ readonly isPackaged = true
+
+ private handlers = new Map<string, Handler>()
+ private listeners = new Map<string, (...args: any[]) => void>()
+ private sinks = new Map<number, UiSink>()
+ private nextUiId = 1
+
+ constructor(opts: { userDataDir: string; appVersion: string }) {
+ this.userDataDir = opts.userDataDir
+ this.appVersion = opts.appVersion
+ }
+
+ handle(channel: string, fn: (...args: any[]) => unknown): void {
+ this.handlers.set(channel, { fn, withSender: false })
+ }
+
+ handleWithSender(channel: string, fn: (senderId: number, ...args: any[]) => unknown): void {
+ this.handlers.set(channel, { fn, withSender: true })
+ }
+
+ on(channel: string, fn: (...args: any[]) => void): void {
+ this.listeners.set(channel, fn)
+ }
+
+ sendTo(uiId: number, channel: string, ...args: any[]): void {
+ const sink = this.sinks.get(uiId)
+ if (!sink) return
+ if (channel.startsWith(PTY_DATA_PREFIX)) {
+ sink.sendBinary(encodePtyData(channel.slice(PTY_DATA_PREFIX.length), String(args[0] ?? '')))
+ } else {
+ sink.sendText(JSON.stringify({ t: 'ev', channel, args }))
+ }
+ }
+
+ broadcast(channel: string, ...args: any[]): void {
+ for (const uiId of this.sinks.keys()) this.sendTo(uiId, channel, ...args)
+ }
+
+ openExternal(_url: string): Promise<void> {
+ return Promise.reject(new Error('openExternal is not available on a headless server'))
+ }
+
+ attach(sink: UiSink): number {
+ const id = this.nextUiId++
+ this.sinks.set(id, sink)
+ return id
+ }
+
+ detach(uiId: number): void {
+ this.sinks.delete(uiId)
+ }
+
+ async dispatch(uiId: number, req: RpcRequest): Promise<RpcOk | RpcErr> {
+ const h = this.handlers.get(req.method)
+ if (!h) {
+ return {
+ t: 'res', id: req.id, ok: false,
+ error: { code: E_NO_HANDLER, message: `no handler for ${req.method}` }
+ }
+ }
+ try {
+ const result = h.withSender ? await h.fn(uiId, ...req.args) : await h.fn(...req.args)
+ return { t: 'res', id: req.id, ok: true, result: result ?? null }
+ } catch (err) {
+ return {
+ t: 'res', id: req.id, ok: false,
+ error: { code: 'E_HANDLER', message: err instanceof Error ? err.message : String(err) }
+ }
+ }
+ }
+
+ cast(uiId: number, method: string, args: unknown[]): void {
+ void uiId
+ this.listeners.get(method)?.(...args)
+ }
+}
diff --git a/tsconfig.node.json b/tsconfig.node.json
index e019f9560..0083908c5 100644
--- a/tsconfig.node.json
+++ b/tsconfig.node.json
@@ -18,6 +18,7 @@
"src/main/**/*",
"src/preload/**/*",
"src/shared/**/*",
- "src/core/**/*"
+ "src/core/**/*",
+ "src/server/**/*"
]
}
diff --git a/vitest.config.ts b/vitest.config.ts
index 9f6958f9f..6e9374a86 100644
--- a/vitest.config.ts
+++ b/vitest.config.ts
@@ -8,6 +8,8 @@ export default defineConfig({
'src/shared/**/*.test.ts',
'src/main/**/*.test.ts',
'src/renderer/**/*.test.ts',
+ 'src/server/**/*.test.ts',
+ 'test/server/**/*.test.ts',
'test/remote/**/*.test.ts'
],
environment: 'node'