Skip to content

The agent that grows with you

refactor(desktop): share the native gesture process lifecycle

brooklyn!f87577193c03
diff --git a/apps/desktop/electron/command-screenshot-monitor.ts b/apps/desktop/electron/command-screenshot-monitor.ts
index a53e519f906..8698a7d99a2 100644
--- a/apps/desktop/electron/command-screenshot-monitor.ts
+++ b/apps/desktop/electron/command-screenshot-monitor.ts
@@ -1,30 +1,18 @@
-import { spawn as nodeSpawn, type SpawnOptions } from 'node:child_process'
-import type { EventEmitter } from 'node:events'
import { dirname, resolve } from 'node:path'
-import type { Readable, Writable } from 'node:stream'
import { fileURLToPath } from 'node:url'
import type { ScreenshotWindow } from './command-screenshot-types'
+import { NativeGestureMonitor, type NativeGestureOptions, type NativeGestureStatus } from './native-gesture-monitor'
export interface CommandScreenshotCapture extends ScreenshotWindow {
type: 'capture'
}
-export type CommandScreenshotStatus =
- { type: 'starting' | 'ready' | 'stopped' } | { type: 'error'; code: 'permission-required' | 'unavailable' }
+export type CommandScreenshotStatus = NativeGestureStatus
-interface MonitorChild extends EventEmitter {
- stdin: Writable | null
- stdout: Readable | null
- kill(signal?: NodeJS.Signals): boolean
-}
-
-interface MonitorOptions {
+interface MonitorOptions extends NativeGestureOptions {
appPath?: string
platform?: NodeJS.Platform
- spawn?: (command: string, args: string[], options: SpawnOptions) => MonitorChild
- startupTimeoutMs?: number
- stopTimeoutMs?: number
}
export function resolveCommandScreenshotMonitorPath(
@@ -34,29 +22,7 @@ export function resolveCommandScreenshotMonitorPath(
return resolve(appPath, 'dist/native/command-screenshot-monitor').replace(/\.asar(?=[/\\])/g, '.asar.unpacked')
}
-function parseMessage(line: string): CommandScreenshotCapture | CommandScreenshotStatus | null {
- let value: unknown
-
- try {
- value = JSON.parse(line)
- } catch {
- return null
- }
-
- if (!value || typeof value !== 'object') {
- return null
- }
-
- const message = value as Record<string, unknown>
-
- if (message.type === 'ready') {
- return { type: 'ready' }
- }
-
- if (message.type === 'error' && (message.code === 'permission-required' || message.code === 'unavailable')) {
- return { type: 'error', code: message.code }
- }
-
+function parseCapture(message: Record<string, unknown>): CommandScreenshotCapture | null {
if (message.type !== 'capture') {
return null
}
@@ -83,9 +49,15 @@ function parseMessage(line: string): CommandScreenshotCapture | CommandScreensho
/** Own one passive native monitor. Call stop() before app quit or disabling the gesture. */
export class CommandScreenshotMonitor {
- private cleanup: (() => void) | undefined
-
- constructor(private readonly options: MonitorOptions = {}) {}
+ private readonly monitor: NativeGestureMonitor<CommandScreenshotCapture>
+
+ constructor(private readonly options: MonitorOptions = {}) {
+ this.monitor = new NativeGestureMonitor({
+ ...options,
+ path: resolveCommandScreenshotMonitorPath(options.appPath),
+ parseGesture: parseCapture
+ })
+ }
/** Only explicit user intent may pass requestPermission=true (opens the macOS prompt). */
start(
@@ -101,134 +73,10 @@ export class CommandScreenshotMonitor {
return
}
- let child: MonitorChild
-
- try {
- child = (this.options.spawn ?? nodeSpawn)(
- resolveCommandScreenshotMonitorPath(this.options.appPath),
- requestPermission ? ['--request-permission'] : [],
- { stdio: ['pipe', 'pipe', 'ignore'], shell: false, detached: false, windowsHide: true }
- )
- } catch {
- onStatus({ type: 'error', code: 'unavailable' })
-
- return
- }
-
- let ready = false
- let active = true
- let pending = ''
- let killTimer: ReturnType<typeof setTimeout> | undefined
- const startupTimer = setTimeout(() => fail(), this.options.startupTimeoutMs ?? (requestPermission ? 60_000 : 5_000))
- startupTimer.unref()
-
- const dispose = () => {
- active = false
- pending = ''
- clearTimeout(startupTimer)
- child.stdout?.removeListener('data', onData)
-
- if (this.cleanup === stop) {
- this.cleanup = undefined
- }
- }
-
- const terminate = (status: CommandScreenshotStatus) => {
- if (!active) {
- return
- }
-
- dispose()
- child.stdin?.end() // EOF also stops the helper if the parent exits unexpectedly.
- child.kill('SIGTERM')
- killTimer = setTimeout(() => child.kill('SIGKILL'), this.options.stopTimeoutMs ?? 1_000)
- killTimer.unref()
- onStatus(status)
- }
-
- const fail = () => terminate({ type: 'error', code: 'unavailable' })
-
- const onData = (chunk: Buffer | string) => {
- if (!active) {
- return
- }
-
- if (chunk.length > 65_536) {
- fail()
-
- return
- }
-
- pending += chunk.toString()
- const lines = pending.split('\n')
- pending = lines.pop() ?? ''
-
- if (pending.length > 4_096) {
- fail()
-
- return
- }
-
- for (const line of lines) {
- if (!active) {
- break
- }
-
- if (line.length > 4_096) {
- fail()
-
- break
- }
-
- const message = parseMessage(line)
-
- if (!message) {
- continue
- }
-
- if (message.type === 'capture') {
- if (ready) {
- onCapture(message)
- }
- } else if (message.type === 'ready' && !ready) {
- ready = true
- clearTimeout(startupTimer)
- onStatus(message)
- } else if (message.type === 'error') {
- terminate(message)
- }
- }
- }
-
- const onClose = () => {
- const unexpected = active
- dispose()
- clearTimeout(killTimer)
- child.removeListener('close', onClose)
- child.removeListener('error', fail)
- child.stdin?.removeListener('error', fail)
- child.stdout?.removeListener('error', fail)
-
- if (unexpected) {
- onStatus({ type: 'error', code: 'unavailable' })
- }
- }
-
- const stop = () => terminate({ type: 'stopped' })
- this.cleanup = stop
- child.stdout?.on('data', onData)
- child.stdout?.on('error', fail)
- child.stdin?.on('error', fail)
- child.once('close', onClose)
- child.on('error', fail)
- onStatus({ type: 'starting' })
-
- if (!child.stdout || !child.stdin) {
- fail()
- }
+ this.monitor.start(onCapture, onStatus, requestPermission)
}
stop(): void {
- this.cleanup?.()
+ this.monitor.stop()
}
}
diff --git a/apps/desktop/electron/native-gesture-monitor.ts b/apps/desktop/electron/native-gesture-monitor.ts
new file mode 100644
index 00000000000..d9d1a68a09f
--- /dev/null
+++ b/apps/desktop/electron/native-gesture-monitor.ts
@@ -0,0 +1,183 @@
+import { spawn as nodeSpawn, type SpawnOptions } from 'node:child_process'
+import type { EventEmitter } from 'node:events'
+import type { Readable, Writable } from 'node:stream'
+
+export type NativeGestureStatus =
+ { type: 'starting' | 'ready' | 'stopped' } | { type: 'error'; code: 'permission-required' | 'unavailable' }
+
+interface MonitorChild extends EventEmitter {
+ stdin: Writable | null
+ stdout: Readable | null
+ kill(signal?: NodeJS.Signals): boolean
+}
+
+export interface NativeGestureOptions {
+ spawn?: (command: string, args: string[], options: SpawnOptions) => MonitorChild
+ startupTimeoutMs?: number
+ stopTimeoutMs?: number
+}
+
+interface MonitorOptions<T> extends NativeGestureOptions {
+ path: string
+ parseGesture: (value: Record<string, unknown>) => T | null
+}
+
+/** Bounded JSON-lines lifecycle shared by the passive screenshot and HUD helpers. */
+export class NativeGestureMonitor<T> {
+ private cleanup: (() => void) | undefined
+
+ constructor(private readonly options: MonitorOptions<T>) {}
+
+ start(
+ onGesture: (gesture: T) => void,
+ onStatus: (status: NativeGestureStatus) => void,
+ requestPermission = false
+ ): void {
+ this.stop()
+ let child: MonitorChild
+
+ try {
+ child = (this.options.spawn ?? nodeSpawn)(this.options.path, requestPermission ? ['--request-permission'] : [], {
+ stdio: ['pipe', 'pipe', 'ignore'],
+ shell: false,
+ detached: false,
+ windowsHide: true
+ })
+ } catch {
+ onStatus({ type: 'error', code: 'unavailable' })
+
+ return
+ }
+
+ let ready = false
+ let active = true
+ let pending = ''
+ let killTimer: ReturnType<typeof setTimeout> | undefined
+ const startupTimer = setTimeout(() => fail(), this.options.startupTimeoutMs ?? (requestPermission ? 60_000 : 5_000))
+ startupTimer.unref()
+
+ const dispose = () => {
+ active = false
+ pending = ''
+ clearTimeout(startupTimer)
+ child.stdout?.removeListener('data', onData)
+
+ if (this.cleanup === stop) {
+ this.cleanup = undefined
+ }
+ }
+
+ const terminate = (status: NativeGestureStatus) => {
+ if (!active) {
+ return
+ }
+
+ dispose()
+ child.stdin?.end() // EOF also stops the helper if the parent exits unexpectedly.
+ child.kill('SIGTERM')
+ killTimer = setTimeout(() => child.kill('SIGKILL'), this.options.stopTimeoutMs ?? 1_000)
+ killTimer.unref()
+ onStatus(status)
+ }
+
+ const fail = () => terminate({ type: 'error', code: 'unavailable' })
+
+ const onData = (chunk: Buffer | string) => {
+ if (!active) {
+ return
+ }
+
+ if (chunk.length > 65_536) {
+ fail()
+
+ return
+ }
+
+ pending += chunk.toString()
+ const lines = pending.split('\n')
+ pending = lines.pop() ?? ''
+
+ if (pending.length > 4_096) {
+ fail()
+
+ return
+ }
+
+ for (const line of lines) {
+ if (!active) {
+ break
+ }
+
+ if (line.length > 4_096) {
+ fail()
+
+ break
+ }
+
+ let value: unknown
+
+ try {
+ value = JSON.parse(line)
+ } catch {
+ continue
+ }
+
+ if (!value || typeof value !== 'object') {
+ continue
+ }
+
+ const message = value as Record<string, unknown>
+
+ if (message.type === 'ready') {
+ if (!ready) {
+ ready = true
+ clearTimeout(startupTimer)
+ onStatus({ type: 'ready' })
+ }
+ } else if (
+ message.type === 'error' &&
+ (message.code === 'permission-required' || message.code === 'unavailable')
+ ) {
+ terminate({ type: 'error', code: message.code })
+ } else if (ready) {
+ const gesture = this.options.parseGesture(message)
+
+ if (gesture !== null) {
+ onGesture(gesture)
+ }
+ }
+ }
+ }
+
+ const onClose = () => {
+ const unexpected = active
+ dispose()
+ clearTimeout(killTimer)
+ child.removeListener('close', onClose)
+ child.removeListener('error', fail)
+ child.stdin?.removeListener('error', fail)
+ child.stdout?.removeListener('error', fail)
+
+ if (unexpected) {
+ onStatus({ type: 'error', code: 'unavailable' })
+ }
+ }
+
+ const stop = () => terminate({ type: 'stopped' })
+ this.cleanup = stop
+ child.stdout?.on('data', onData)
+ child.stdout?.on('error', fail)
+ child.stdin?.on('error', fail)
+ child.once('close', onClose)
+ child.on('error', fail)
+ onStatus({ type: 'starting' })
+
+ if (!child.stdout || !child.stdin) {
+ fail()
+ }
+ }
+
+ stop(): void {
+ this.cleanup?.()
+ }
+}