@bun-native/core 0.0.0-bootstrap.0 → 0.33.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2168 @@
1
+ import {
2
+ parseRootId,
3
+ ProtocolError,
4
+ type Capability,
5
+ type FileDialogOptions,
6
+ type Limits,
7
+ type Operation,
8
+ } from '@bun-native/protocol'
9
+ import {
10
+ NativeCommandError,
11
+ NativeHost,
12
+ type ApplicationEvent,
13
+ type HostOptions,
14
+ type WindowEvent,
15
+ } from '@bun-native/runtime'
16
+ import { planStagedCommit, sendStagedCommit } from './commit-plan.ts'
17
+ import { dispatchPlan, EventBindings, prunePlan, type DispatchPlan } from './events.ts'
18
+ import { DisplaySubscription } from './display.ts'
19
+ import {
20
+ checkServiceCancellation,
21
+ NativeServiceError,
22
+ publicDisplaySnapshot,
23
+ serviceCapabilities,
24
+ serviceSignal,
25
+ type DisplayChangeEvent,
26
+ type NativeDisplaySnapshot,
27
+ type NativeClipboardText,
28
+ type ServiceCapabilities,
29
+ type ServiceRequestOptions,
30
+ } from './services.ts'
31
+ import {
32
+ shortcutRequest,
33
+ ShortcutRegistration,
34
+ type GlobalShortcutEvent,
35
+ type GlobalShortcutOptions,
36
+ type NativeGlobalShortcut,
37
+ } from './shortcuts.ts'
38
+ import {
39
+ notificationRequest,
40
+ NotificationRegistration,
41
+ type NativeNotification,
42
+ type NotificationEvent,
43
+ type NotificationOptions,
44
+ } from './notifications.ts'
45
+ import {
46
+ menuBarRequest,
47
+ MenuBarRegistration,
48
+ type AppMenuItemEvent,
49
+ type MenuEntryOptions,
50
+ type MenuOptions,
51
+ type NativeMenuBar,
52
+ } from './app-menu.ts'
53
+ import {
54
+ contextMenuRequest,
55
+ ContextMenuRequest,
56
+ itemIds,
57
+ type ContextMenuPosition,
58
+ } from './context-menus.ts'
59
+ import {
60
+ DropTargetRegistration,
61
+ type DropTargetEvent,
62
+ type NativeDropTarget,
63
+ type NativeDroppedItem,
64
+ } from './drops.ts'
65
+ import {
66
+ fileGrantRequest,
67
+ FileGrantRegistration,
68
+ type FileCall,
69
+ type FileGrantOptions,
70
+ type NativeFileGrant,
71
+ } from './files.ts'
72
+ import {
73
+ processRequest,
74
+ ProcessRegistration,
75
+ type NativeProcess,
76
+ type ProcessCall,
77
+ type ProcessEvent,
78
+ type ProcessOptions,
79
+ } from './processes.ts'
80
+ import {
81
+ FileDialogRequest,
82
+ openDialogRequest,
83
+ saveDialogRequest,
84
+ type OpenDialogOptions,
85
+ type OpenDialogResult,
86
+ type SaveDialogOptions,
87
+ type SaveDialogResult,
88
+ } from './dialogs.ts'
89
+ import {
90
+ confirmDialogSpec,
91
+ messageDialogSpec,
92
+ MessageDialogs,
93
+ type ConfirmDialogOptions,
94
+ type NativeMessageDialogBackend,
95
+ type MessageDialogOptions,
96
+ type MessageDialogResult,
97
+ } from './message-dialogs.ts'
98
+ import { CommittedText, makeNode, own, Transaction, type NodeState } from './tree.ts'
99
+ import {
100
+ NativeStateError,
101
+ UnsupportedFeatureError,
102
+ type ClickEvent,
103
+ type InputEvent,
104
+ type Listener,
105
+ type ListenerOptions,
106
+ type NativeEventMap,
107
+ type NativeEventType,
108
+ type NativeApplication,
109
+ type NativeBatch,
110
+ type NativeNode,
111
+ type NativeWindow,
112
+ type WindowOptions,
113
+ } from './types.ts'
114
+
115
+ const MAX_QUEUED_TRANSACTIONS = 128
116
+ const MAX_QUEUED_CALLBACKS = 128
117
+ type Callback =
118
+ | { windowId: number; nodeId: number; plan: DispatchPlan }
119
+ | { windowId: number; shortcut: ShortcutRegistration; event: GlobalShortcutEvent }
120
+ | { windowId: number; notification: NotificationRegistration; event: NotificationEvent }
121
+ | { windowId: number; process: ProcessRegistration; event: ProcessEvent; chunk: number }
122
+ | { windowId: number; display: DisplaySubscription; event: DisplayChangeEvent }
123
+ | { windowId: number; dropTarget: DropTargetRegistration; event: DropTargetEvent }
124
+ /** Application-scoped: no window owns the menu bar. */
125
+ | { menuBar: MenuBarRegistration; event: AppMenuItemEvent }
126
+
127
+ class Application implements NativeApplication {
128
+ readonly closed: Promise<void>
129
+ readonly limits: Readonly<Limits>
130
+ // NativeHost.launch has negotiated every mandatory protocol feature.
131
+ readonly capabilities: readonly Capability[]
132
+ readonly serviceCapabilities: Readonly<ServiceCapabilities>
133
+ readonly windows = new Map<number, Window>()
134
+ readonly shortcuts = new Map<number, ShortcutRegistration>()
135
+ private nextShortcut = 1
136
+ readonly notifications = new Map<number, NotificationRegistration>()
137
+ private nextNotification = 1
138
+ readonly fileGrants = new Map<number, FileGrantRegistration>()
139
+ private nextFileGrant = 1
140
+ readonly processes = new Map<number, ProcessRegistration>()
141
+ private nextProcess = 1
142
+ readonly dialogs = new Map<number, FileDialogRequest>()
143
+ private nextDialog = 1
144
+ readonly contextMenus = new Map<number, ContextMenuRequest>()
145
+ private nextContextMenu = 1
146
+ private nextMessageDialog = 1
147
+ readonly dropTargets = new Map<number, DropTargetRegistration>()
148
+ private nextDropTarget = 1
149
+ private lastDrop = 0
150
+ /** The installed (or installing) menu bar; replaced bars are revoked. */
151
+ private menuBar: MenuBarRegistration | undefined
152
+ private nextMenuBar = 1
153
+ private tail: Promise<void> = Promise.resolve()
154
+ private queued = 0
155
+ private readonly services = new Set<Promise<void>>()
156
+ private callbacks: Callback[] = []
157
+ private dispatching: Promise<void> | undefined
158
+ private activeCallbacks = 0
159
+ private nextWindow = 1
160
+ private nextNode = 1
161
+ private stopping: Promise<void> | undefined
162
+ private failure: Error | undefined
163
+ private phase: 'running' | 'stopping' | 'closed' = 'running'
164
+
165
+ constructor(readonly host: NativeHost) {
166
+ this.limits = host.limits
167
+ this.capabilities = host.capabilities
168
+ this.serviceCapabilities = serviceCapabilities(host.servicePolicy, host.capabilities)
169
+ this.closed = this.consume()
170
+ // Keep background failures observable through closed/shutdown without an
171
+ // unhandled rejection while the application is still installing listeners.
172
+ void this.closed.catch(() => {})
173
+ }
174
+
175
+ get diagnostics() {
176
+ let nodes = 0
177
+ let callbacks = 0
178
+ for (const window of this.windows.values()) {
179
+ nodes += window.nodes.size
180
+ callbacks += window.listeners.size + window.displayChanges.size
181
+ }
182
+ return Object.freeze({
183
+ windows: this.windows.size,
184
+ nodes,
185
+ callbacks,
186
+ queuedTransactions: this.queued,
187
+ queuedCallbacks: this.callbacks.length,
188
+ activeCallbacks: this.activeCallbacks,
189
+ serviceRequests: this.services.size,
190
+ })
191
+ }
192
+
193
+ allocateNode(): number {
194
+ if (!Number.isSafeInteger(this.nextNode))
195
+ throw new NativeStateError('limit_exceeded', 'Native node identity space exhausted')
196
+ return this.nextNode++
197
+ }
198
+
199
+ allocateShortcut(): number {
200
+ if (!Number.isSafeInteger(this.nextShortcut))
201
+ throw new NativeStateError('limit_exceeded', 'Global shortcut identity space exhausted')
202
+ return this.nextShortcut++
203
+ }
204
+
205
+ isAllocatedShortcut(id: number): boolean {
206
+ return id < this.nextShortcut
207
+ }
208
+
209
+ allocateNotification(): number {
210
+ if (!Number.isSafeInteger(this.nextNotification))
211
+ throw new NativeStateError('limit_exceeded', 'Notification identity space exhausted')
212
+ return this.nextNotification++
213
+ }
214
+
215
+ isAllocatedNotification(id: number): boolean {
216
+ return id < this.nextNotification
217
+ }
218
+
219
+ allocateFileGrant(): number {
220
+ if (!Number.isSafeInteger(this.nextFileGrant))
221
+ throw new NativeStateError('limit_exceeded', 'File grant identity space exhausted')
222
+ return this.nextFileGrant++
223
+ }
224
+
225
+ allocateProcess(): number {
226
+ if (!Number.isSafeInteger(this.nextProcess))
227
+ throw new NativeStateError('limit_exceeded', 'Process identity space exhausted')
228
+ return this.nextProcess++
229
+ }
230
+
231
+ isAllocatedProcess(id: number): boolean {
232
+ return id < this.nextProcess
233
+ }
234
+
235
+ allocateDialog(): number {
236
+ if (!Number.isSafeInteger(this.nextDialog))
237
+ throw new NativeStateError('limit_exceeded', 'File dialog identity space exhausted')
238
+ return this.nextDialog++
239
+ }
240
+
241
+ allocateContextMenu(): number {
242
+ if (!Number.isSafeInteger(this.nextContextMenu))
243
+ throw new NativeStateError('limit_exceeded', 'Context menu identity space exhausted')
244
+ return this.nextContextMenu++
245
+ }
246
+
247
+ isAllocatedDialog(id: number): boolean {
248
+ return id < this.nextDialog
249
+ }
250
+
251
+ allocateMessageDialog(): number {
252
+ if (!Number.isSafeInteger(this.nextMessageDialog))
253
+ throw new NativeStateError('limit_exceeded', 'Message dialog identity space exhausted')
254
+ return this.nextMessageDialog++
255
+ }
256
+
257
+ isAllocatedMessageDialog(id: number): boolean {
258
+ return id < this.nextMessageDialog
259
+ }
260
+
261
+ allocateDropTarget(): number {
262
+ if (!Number.isSafeInteger(this.nextDropTarget))
263
+ throw new NativeStateError('limit_exceeded', 'Drop target identity space exhausted')
264
+ return this.nextDropTarget++
265
+ }
266
+
267
+ cancelCallbacks(windowId: number): void {
268
+ const window = this.windows.get(windowId)
269
+ this.callbacks = this.callbacks.filter((callback) => {
270
+ if ('menuBar' in callback || callback.windowId !== windowId) return true
271
+ if ('shortcut' in callback) return callback.shortcut.live
272
+ if ('notification' in callback) return callback.notification.deliverable
273
+ if ('dropTarget' in callback) return callback.dropTarget.live
274
+ if ('process' in callback) return callback.process.live
275
+ if ('display' in callback) return callback.display.live
276
+ if (window?.isTargetLive(callback.nodeId) && prunePlan(callback.plan)) return true
277
+ window?.listeners.release(callback.plan)
278
+ return false
279
+ })
280
+ }
281
+
282
+ queueCallback(callback: Callback): void {
283
+ if (this.phase !== 'running') return
284
+ if (this.callbacks.length >= MAX_QUEUED_CALLBACKS)
285
+ throw new ProtocolError('Application callback queue limit exceeded')
286
+ this.callbacks.push(callback)
287
+ this.startDispatch()
288
+ }
289
+
290
+ /** Record the first failure and end the application with it. */
291
+ async fail(cause: unknown): Promise<void> {
292
+ this.failure ??= cause instanceof Error ? cause : new Error(String(cause))
293
+ await this.shutdown().catch(() => {})
294
+ }
295
+
296
+ private startDispatch(): void {
297
+ if (!this.callbacks.length) return
298
+ if (this.dispatching) return
299
+ this.dispatching = this.dispatchCallbacks()
300
+ .catch((cause) => this.fail(cause))
301
+ .finally(() => {
302
+ this.dispatching = undefined
303
+ this.startDispatch()
304
+ })
305
+ }
306
+
307
+ private async dispatchCallbacks(): Promise<void> {
308
+ while (this.callbacks.length) {
309
+ const callback = this.callbacks.shift()!
310
+ const window = 'menuBar' in callback ? undefined : this.windows.get(callback.windowId)
311
+ if (!window && !('menuBar' in callback)) continue
312
+ this.activeCallbacks = 1
313
+ try {
314
+ if ('menuBar' in callback) {
315
+ const listener = callback.menuBar.listener
316
+ if (listener && callback.menuBar.live)
317
+ await dispatchOwned(listener, callback.event, callback.menuBar.controller.signal)
318
+ } else if (!window) continue
319
+ else if ('shortcut' in callback) await dispatchShortcut(callback.shortcut, callback.event)
320
+ else if ('dropTarget' in callback)
321
+ await dispatchDropTarget(callback.dropTarget, callback.event)
322
+ else if ('notification' in callback)
323
+ await dispatchNotification(callback.notification, callback.event)
324
+ else if ('process' in callback)
325
+ await window.dispatchProcess(callback.process, callback.event, callback.chunk)
326
+ else if ('display' in callback) {
327
+ const listener = callback.display.current
328
+ if (listener)
329
+ await dispatchOwned(listener, callback.event, callback.display.controller.signal)
330
+ } else await window.dispatch(callback.nodeId, callback.plan)
331
+ } finally {
332
+ this.activeCallbacks = 0
333
+ }
334
+ }
335
+ }
336
+
337
+ enqueue<T>(operation: () => Promise<T>, closingWindow = false): Promise<T> {
338
+ if (this.phase !== 'running')
339
+ return Promise.reject(
340
+ this.failure ?? new NativeStateError('invalid_state', 'Application is shutting down')
341
+ )
342
+ // At most one close per live window may use the reserved cleanup capacity.
343
+ if (!closingWindow && this.queued >= MAX_QUEUED_TRANSACTIONS)
344
+ return Promise.reject(
345
+ new NativeStateError('limit_exceeded', 'Application transaction queue is full')
346
+ )
347
+ this.queued += 1
348
+ const result = this.tail
349
+ .then(() => {
350
+ if (this.phase !== 'running')
351
+ throw (
352
+ this.failure ??
353
+ new NativeStateError('invalid_state', 'Transaction cancelled during shutdown')
354
+ )
355
+ return operation()
356
+ })
357
+ .finally(() => {
358
+ this.queued -= 1
359
+ })
360
+ this.tail = result.then(
361
+ () => {},
362
+ () => {}
363
+ )
364
+ return result
365
+ }
366
+
367
+ openWindow(options: WindowOptions): Promise<NativeWindow> {
368
+ // Copy options at submission so later consumer mutation cannot change work.
369
+ const requested = { ...options }
370
+ return this.enqueue(async () => {
371
+ if (this.windows.size >= this.limits.max_windows)
372
+ throw new NativeStateError('limit_exceeded', 'Application window limit exceeded')
373
+ if (!Number.isSafeInteger(this.nextWindow))
374
+ throw new NativeStateError('limit_exceeded', 'Native window identity space exhausted')
375
+ const window = new Window(this, this.nextWindow++, this.allocateNode())
376
+ this.windows.set(window.id, window)
377
+ try {
378
+ await this.host.send({
379
+ type: 'open',
380
+ window_id: window.id,
381
+ root_id: window.rootId,
382
+ title: requested.title,
383
+ width: requested.width ?? 560,
384
+ height: requested.height ?? 380,
385
+ })
386
+ window.assertActive()
387
+ return window
388
+ } catch (error) {
389
+ window.revoke()
390
+ throw error
391
+ }
392
+ })
393
+ }
394
+
395
+ // Clipboard transfers must not hold the shared tree commit queue. This
396
+ // bounded set joins their results on shutdown while the transport continues
397
+ // to route independent native acknowledgements and input.
398
+ service<T>(operation: () => Promise<T>): Promise<T> {
399
+ if (this.phase !== 'running')
400
+ return Promise.reject(new NativeStateError('invalid_state', 'Application is shutting down'))
401
+ if (this.services.size >= this.limits.max_service_requests)
402
+ return Promise.reject(
403
+ new NativeStateError('limit_exceeded', 'Native service request limit exceeded')
404
+ )
405
+ const result = Promise.resolve().then(() => {
406
+ if (this.phase !== 'running')
407
+ throw new NativeStateError('invalid_state', 'Service request cancelled during shutdown')
408
+ return operation()
409
+ })
410
+ const settled = result
411
+ .then(
412
+ () => {},
413
+ () => {}
414
+ )
415
+ .finally(() => this.services.delete(settled))
416
+ this.services.add(settled)
417
+ return result
418
+ }
419
+
420
+ /** Joins an operation at shutdown without consuming a new-request slot. */
421
+ track(operation: Promise<void>): Promise<void> {
422
+ const settled = operation
423
+ .then(
424
+ () => {},
425
+ () => {}
426
+ )
427
+ .finally(() => this.services.delete(settled))
428
+ this.services.add(settled)
429
+ return operation
430
+ }
431
+
432
+ get running(): boolean {
433
+ return this.phase === 'running'
434
+ }
435
+
436
+ async shutdown(): Promise<void> {
437
+ if (!this.stopping) {
438
+ this.phase = 'stopping'
439
+ this.menuBar?.revoke()
440
+ for (const window of this.windows.values()) window.revoke()
441
+ this.stopping = (async () => {
442
+ await this.tail
443
+ await this.host.shutdown()
444
+ await Promise.all(this.services)
445
+ })()
446
+ }
447
+ await this.stopping
448
+ if (this.failure) throw this.failure
449
+ }
450
+
451
+ async setMenuBar(
452
+ menus: readonly MenuOptions[],
453
+ listener: (event: AppMenuItemEvent) => void | Promise<void>
454
+ ): Promise<NativeMenuBar> {
455
+ const request = menuBarRequest(menus)
456
+ if (typeof listener !== 'function')
457
+ throw new TypeError('A menu bar listener must be a function')
458
+ this.checkMenuBar()
459
+ const registration = new MenuBarRegistration(this.allocateMenuBar(), listener, (item) =>
460
+ item === this.menuBar ? this.clearMenuBar() : Promise.resolve()
461
+ )
462
+ // Revoked at submission: no selection of the old bar is delivered after this call.
463
+ this.menuBar?.revoke()
464
+ this.menuBar = registration
465
+ await this.sendMenuBar(registration.id, request)
466
+ if (!registration.live)
467
+ throw new NativeServiceError(
468
+ 'app_menu',
469
+ 'cancelled',
470
+ 'Menu bar was replaced or revoked while it was set'
471
+ )
472
+ return registration.handle
473
+ }
474
+
475
+ async clearMenuBar(): Promise<void> {
476
+ this.checkMenuBar()
477
+ const id = this.allocateMenuBar()
478
+ this.menuBar?.revoke()
479
+ this.menuBar = undefined
480
+ await this.sendMenuBar(id, [])
481
+ }
482
+
483
+ private checkMenuBar(): void {
484
+ if (this.phase !== 'running')
485
+ throw new NativeStateError('invalid_state', 'Application is shutting down')
486
+ const capability = this.serviceCapabilities.appMenu
487
+ if (capability.availability !== 'available')
488
+ throw new NativeServiceError(
489
+ 'app_menu',
490
+ 'service_unavailable',
491
+ 'This native backend has no application menu bar'
492
+ )
493
+ if (capability.permission !== 'allow')
494
+ throw new NativeServiceError(
495
+ 'app_menu',
496
+ 'permission_denied',
497
+ 'the application menu was not granted at native process launch'
498
+ )
499
+ }
500
+
501
+ private allocateMenuBar(): number {
502
+ if (!Number.isSafeInteger(this.nextMenuBar))
503
+ throw new NativeStateError('limit_exceeded', 'Menu bar identity space exhausted')
504
+ return this.nextMenuBar++
505
+ }
506
+
507
+ private async sendMenuBar(id: number, menus: ReturnType<typeof menuBarRequest>): Promise<void> {
508
+ try {
509
+ await this.service(() => this.host.send({ type: 'set_app_menu', menu_id: id, menus }))
510
+ } catch (error) {
511
+ if (this.menuBar?.id === id) {
512
+ this.menuBar.revoke()
513
+ this.menuBar = undefined
514
+ }
515
+ if (
516
+ error instanceof NativeCommandError &&
517
+ (MENU_ERRORS as readonly string[]).includes(error.code)
518
+ )
519
+ throw new NativeServiceError(
520
+ 'app_menu',
521
+ error.code as NativeServiceError['code'],
522
+ error.message
523
+ )
524
+ throw error
525
+ }
526
+ }
527
+
528
+ private receiveMenuItem(event: ApplicationEvent): void {
529
+ if (!this.capabilities.includes('app_menu_v1'))
530
+ throw new ProtocolError('Native menu selection arrived without app_menu_v1')
531
+ if (event.menu_id >= this.nextMenuBar)
532
+ throw new ProtocolError('Native event names an unallocated menu bar')
533
+ const registration = this.menuBar
534
+ // A replaced or cleared bar's selection is stale and never delivered.
535
+ if (!registration?.live || registration.id !== event.menu_id) return
536
+ this.queueCallback({
537
+ menuBar: registration,
538
+ event: Object.freeze({
539
+ type: 'app_menu_item',
540
+ sequence: event.sequence,
541
+ itemId: event.item_id,
542
+ menuBar: registration.handle,
543
+ signal: registration.controller.signal,
544
+ }),
545
+ })
546
+ }
547
+
548
+ private async consume(): Promise<void> {
549
+ try {
550
+ for await (const event of this.host) {
551
+ if (event.type === 'app_menu_item') {
552
+ this.receiveMenuItem(event)
553
+ continue
554
+ }
555
+ if (event.type === 'global_shortcut' && !this.isAllocatedShortcut(event.shortcut_id))
556
+ throw new ProtocolError('Native event names an unallocated global shortcut')
557
+ if (
558
+ (event.type === 'notification_activated' || event.type === 'notification_dismissed') &&
559
+ !this.isAllocatedNotification(event.notification_id)
560
+ )
561
+ throw new ProtocolError('Native event names an unallocated notification')
562
+ if (
563
+ (event.type === 'process_output' || event.type === 'process_exited') &&
564
+ !this.isAllocatedProcess(event.process_id)
565
+ )
566
+ throw new ProtocolError('Native event names an unallocated process')
567
+ if (event.type === 'file_dialog_completed' && !this.isAllocatedDialog(event.dialog_id))
568
+ throw new ProtocolError('Native event names an unallocated file dialog')
569
+ if (
570
+ event.type === 'message_dialog_completed' &&
571
+ !this.isAllocatedMessageDialog(event.dialog_id)
572
+ )
573
+ throw new ProtocolError('Native event names an unallocated message dialog')
574
+ if (
575
+ (event.type === 'drop_target_drag' ||
576
+ event.type === 'drop_received' ||
577
+ event.type === 'drop_rejected') &&
578
+ event.target_id >= this.nextDropTarget
579
+ )
580
+ throw new ProtocolError('Native event names an unallocated drop target')
581
+ if (event.type === 'drop_received') {
582
+ if (event.drop_id <= this.lastDrop)
583
+ throw new ProtocolError('Native drop identities must increase')
584
+ this.lastDrop = event.drop_id
585
+ }
586
+ const window = this.windows.get(event.window_id)
587
+ if (!window) {
588
+ if (event.window_id >= this.nextWindow)
589
+ throw new ProtocolError('Native event names an unallocated window')
590
+ continue // Revoked window: late events must not retain or invoke callbacks.
591
+ }
592
+ window.receive(event, this.nextNode)
593
+ }
594
+ } catch (cause) {
595
+ this.failure ??= cause instanceof Error ? cause : new Error(String(cause))
596
+ this.phase = 'stopping'
597
+ await this.host.shutdown().catch(() => {})
598
+ } finally {
599
+ this.menuBar?.revoke()
600
+ for (const window of this.windows.values()) window.revoke()
601
+ await this.dispatching
602
+ await Promise.all(this.services)
603
+ this.phase = 'closed'
604
+ }
605
+ if (this.failure) throw this.failure
606
+ }
607
+ }
608
+
609
+ async function dispatchShortcut(
610
+ registration: ShortcutRegistration,
611
+ event: GlobalShortcutEvent
612
+ ): Promise<void> {
613
+ const listener = registration.listener
614
+ if (!listener || !registration.live) return
615
+ await dispatchOwned(listener, event, registration.controller.signal)
616
+ }
617
+
618
+ async function dispatchNotification(
619
+ registration: NotificationRegistration,
620
+ event: NotificationEvent
621
+ ): Promise<void> {
622
+ const listener = registration.listener
623
+ if (!listener) return
624
+ try {
625
+ await dispatchOwned(listener, event, registration.controller.signal)
626
+ } finally {
627
+ // The dismissal is the last delivery for its registration.
628
+ if (event.type === 'notification_dismissed') registration.revoke()
629
+ }
630
+ }
631
+
632
+ async function dispatchDropTarget(
633
+ registration: DropTargetRegistration,
634
+ event: DropTargetEvent
635
+ ): Promise<void> {
636
+ const listener = registration.listener
637
+ if (!listener || !registration.live) return
638
+ await dispatchOwned(listener, event, registration.controller.signal)
639
+ }
640
+
641
+ async function dispatchOwned<T>(
642
+ listener: (event: T) => void | Promise<void>,
643
+ event: T,
644
+ signal: AbortSignal
645
+ ): Promise<void> {
646
+ if (signal.aborted) return
647
+ let cancel!: () => void
648
+ const cancelled = new Promise<void>((resolve) => {
649
+ cancel = resolve
650
+ })
651
+ signal.addEventListener('abort', cancel, { once: true })
652
+ try {
653
+ // Revocation releases an uncooperative listener without blocking ingestion.
654
+ await Promise.race([listener(event), cancelled])
655
+ } finally {
656
+ signal.removeEventListener('abort', cancel)
657
+ }
658
+ }
659
+
660
+ const FILE_ERRORS = [
661
+ 'permission_denied',
662
+ 'service_unavailable',
663
+ 'cancelled',
664
+ 'native_failure',
665
+ 'limit_exceeded',
666
+ 'not_found',
667
+ 'already_exists',
668
+ 'path_denied',
669
+ 'wrong_kind',
670
+ 'not_empty',
671
+ 'access_denied',
672
+ ] as const
673
+
674
+ const PROCESS_ERRORS = [
675
+ 'permission_denied',
676
+ 'service_unavailable',
677
+ 'cancelled',
678
+ 'native_failure',
679
+ 'limit_exceeded',
680
+ 'not_found',
681
+ 'path_denied',
682
+ 'wrong_kind',
683
+ 'access_denied',
684
+ 'invalid_state',
685
+ ] as const
686
+
687
+ const DROP_ERRORS = [
688
+ 'permission_denied',
689
+ 'service_unavailable',
690
+ 'conflict',
691
+ 'cancelled',
692
+ 'native_failure',
693
+ 'limit_exceeded',
694
+ 'not_found',
695
+ 'path_denied',
696
+ ] as const
697
+
698
+ const NOTIFICATION_ERRORS = [
699
+ 'permission_denied',
700
+ 'service_unavailable',
701
+ 'cancelled',
702
+ 'native_failure',
703
+ 'operation_timed_out',
704
+ 'limit_exceeded',
705
+ ] as const
706
+
707
+ const DIALOG_ERRORS = [
708
+ 'permission_denied',
709
+ 'service_unavailable',
710
+ 'cancelled',
711
+ 'native_failure',
712
+ 'operation_timed_out',
713
+ 'limit_exceeded',
714
+ ] as const
715
+
716
+ const MENU_ERRORS = [
717
+ 'permission_denied',
718
+ 'service_unavailable',
719
+ 'cancelled',
720
+ 'native_failure',
721
+ 'limit_exceeded',
722
+ ] as const
723
+
724
+ const SHORTCUT_ERRORS = [
725
+ 'permission_denied',
726
+ 'service_unavailable',
727
+ 'conflict',
728
+ 'cancelled',
729
+ 'native_failure',
730
+ 'operation_timed_out',
731
+ 'limit_exceeded',
732
+ ] as const
733
+
734
+ class Window implements NativeWindow {
735
+ readonly root: NativeNode<'box'>
736
+ readonly closed: Promise<void>
737
+ readonly listeners: EventBindings
738
+ // Replaced, never cleared, on close: an open batch still reads its own base.
739
+ nodes = new Map<number, NodeState>()
740
+ text: CommittedText
741
+ revision = 0
742
+ private active = true
743
+ private resolveClosed!: () => void
744
+ private closing: Promise<void> | undefined
745
+ readonly displayChanges = new Set<DisplaySubscription>()
746
+ private readonly messages = new MessageDialogs(this, () => this.nativeMessageDialogs())
747
+
748
+ constructor(
749
+ private readonly application: Application,
750
+ readonly id: number,
751
+ readonly rootId: number
752
+ ) {
753
+ const node = makeNode(rootId, { kind: 'box' })
754
+ this.root = node.handle
755
+ this.nodes.set(rootId, node)
756
+ this.text = new CommittedText(application.limits.max_text_bytes, [node])
757
+ this.listeners = new EventBindings(() => this.application.cancelCallbacks(this.id))
758
+ this.closed = new Promise((resolve) => {
759
+ this.resolveClosed = resolve
760
+ })
761
+ }
762
+
763
+ assertActive(): void {
764
+ if (!this.active) throw new NativeStateError('invalid_handle', 'Window is closed')
765
+ }
766
+
767
+ batch<T>(update: (batch: NativeBatch) => T): Promise<T> {
768
+ return this.application.enqueue(async () => {
769
+ this.assertActive()
770
+ const transaction = new Transaction(
771
+ this.nodes,
772
+ this.rootId,
773
+ () => this.application.allocateNode(),
774
+ this.application.limits,
775
+ this.application.capabilities,
776
+ this.text
777
+ )
778
+ let value: T
779
+ try {
780
+ value = update(transaction)
781
+ if (
782
+ value !== null &&
783
+ (typeof value === 'object' || typeof value === 'function') &&
784
+ typeof (value as { then?: unknown }).then === 'function'
785
+ ) {
786
+ // Reject the async contract while consuming a later rejection from
787
+ // the already-started callback. Its escaped transaction is revoked.
788
+ void Promise.resolve(value).catch(() => {})
789
+ throw new NativeStateError('invalid_state', 'Batch callbacks must be synchronous')
790
+ }
791
+ transaction.validate()
792
+ } finally {
793
+ transaction.finish()
794
+ }
795
+ if (!transaction.operations.length) return value
796
+ const send = (operations: readonly Operation[]) =>
797
+ this.application.host.send({
798
+ type: 'batch',
799
+ window_id: this.id,
800
+ base_revision: this.revision,
801
+ operations,
802
+ })
803
+ // Publish in the reply's own continuation, before any later native event.
804
+ const publish = (revision: number) => {
805
+ this.assertActive()
806
+ transaction.commit(this.nodes, this.text)
807
+ this.revision = revision
808
+ this.listeners.retain(this.nodes)
809
+ // The host revokes a target whose node a committed tree removed.
810
+ for (const registration of this.application.dropTargets.values())
811
+ if (registration.windowId === this.id && !this.nodes.has(registration.nodeId)) {
812
+ registration.revoke()
813
+ this.application.dropTargets.delete(registration.id)
814
+ }
815
+ }
816
+ if (transaction.operations.length <= this.application.limits.max_operations) {
817
+ publish((await send(transaction.operations)).tree_revision)
818
+ return value
819
+ }
820
+ const plan = planStagedCommit(
821
+ this.nodes,
822
+ transaction,
823
+ this.rootId,
824
+ () => this.application.allocateNode(),
825
+ this.application.limits
826
+ )
827
+ await sendStagedCommit(plan, send, (reply, final) => {
828
+ if (final) publish(reply.tree_revision)
829
+ else {
830
+ this.assertActive()
831
+ // Staging changed only nodes this window has not committed.
832
+ this.revision = reply.tree_revision
833
+ }
834
+ })
835
+ return value
836
+ })
837
+ }
838
+
839
+ on<T extends NativeEventType>(
840
+ handle: NativeNode,
841
+ type: T,
842
+ listener: Listener<NativeEventMap[T]>,
843
+ options?: ListenerOptions
844
+ ): () => void {
845
+ this.assertActive()
846
+ const node = own(this.nodes, handle)
847
+ if (type === 'split_resize' && !this.application.capabilities.includes('split_resize_v1'))
848
+ throw new UnsupportedFeatureError('event:split_resize')
849
+ return this.listeners.register(node.id, node.handle, type, listener, options)
850
+ }
851
+
852
+ onClick(handle: NativeNode<'button'>, listener: Listener<ClickEvent>): () => void {
853
+ this.assertActive()
854
+ const node = own(this.nodes, handle)
855
+ if (node.element.kind !== 'button')
856
+ throw new NativeStateError('invalid_state', 'Click listeners require a button and a function')
857
+ return this.listeners.register(node.id, node.handle, 'click', listener)
858
+ }
859
+
860
+ onInput(handle: NativeNode<'input'>, listener: Listener<InputEvent>): () => void {
861
+ this.assertActive()
862
+ const node = own(this.nodes, handle)
863
+ if (node.element.kind !== 'input')
864
+ throw new NativeStateError('invalid_state', 'Input listeners require an input and a function')
865
+ return this.listeners.register(node.id, node.handle, 'input', listener)
866
+ }
867
+
868
+ input(handle: NativeNode<'input'>) {
869
+ this.assertActive()
870
+ const node = own(this.nodes, handle)
871
+ if (node.element.kind !== 'input')
872
+ throw new NativeStateError('invalid_state', 'Only an input has an edit state')
873
+ return Object.freeze({ value: node.element.value, revision: node.inputRevision })
874
+ }
875
+
876
+ async displaySnapshot(options: ServiceRequestOptions = {}): Promise<NativeDisplaySnapshot> {
877
+ const signal = serviceSignal(options)
878
+ this.assertActive()
879
+ checkServiceCancellation(signal, 'window_display')
880
+ return this.application.enqueue(async () => {
881
+ this.assertActive()
882
+ checkServiceCancellation(signal, 'window_display')
883
+ try {
884
+ const response = await this.application.host.send({
885
+ type: 'display_snapshot',
886
+ window_id: this.id,
887
+ })
888
+ const snapshot = publicDisplaySnapshot(response.snapshot, this.application.capabilities)
889
+ // Cancellation and owner revocation suppress data after a submitted
890
+ // read, while the transport still drains and validates its response.
891
+ this.assertActive()
892
+ checkServiceCancellation(signal, 'window_display')
893
+ return snapshot
894
+ } catch (error) {
895
+ if (error instanceof ProtocolError) throw error
896
+ this.assertActive()
897
+ checkServiceCancellation(signal, 'window_display')
898
+ if (
899
+ error instanceof NativeCommandError &&
900
+ (error.code === 'permission_denied' || error.code === 'service_unavailable')
901
+ )
902
+ throw new NativeServiceError('window_display', error.code, error.message)
903
+ throw error
904
+ }
905
+ })
906
+ }
907
+
908
+ onDisplayChange(listener: (event: DisplayChangeEvent) => void | Promise<void>): () => void {
909
+ this.assertActive()
910
+ if (typeof listener !== 'function')
911
+ throw new TypeError('Display change listener must be a function')
912
+ if (this.application.serviceCapabilities.windowDisplay.changes !== 'available')
913
+ throw new NativeServiceError(
914
+ 'window_display',
915
+ 'service_unavailable',
916
+ 'This native backend does not report display changes'
917
+ )
918
+ if (this.application.serviceCapabilities.windowDisplay.permission !== 'allow')
919
+ throw new NativeServiceError(
920
+ 'window_display',
921
+ 'permission_denied',
922
+ 'window display access was not granted at native process launch'
923
+ )
924
+ const subscription = new DisplaySubscription(listener)
925
+ this.displayChanges.add(subscription)
926
+ return () => {
927
+ subscription.revoke()
928
+ if (this.displayChanges.delete(subscription)) this.application.cancelCallbacks(this.id)
929
+ }
930
+ }
931
+
932
+ private receiveDisplayChange(event: Extract<WindowEvent, { type: 'display_changed' }>): void {
933
+ if (!this.application.capabilities.includes('display_changes_v1'))
934
+ throw new ProtocolError('Native display change arrived without display_changes_v1')
935
+ // Validate even when nobody listens: a malformed frame is a host fault.
936
+ const snapshot = publicDisplaySnapshot(event.snapshot, this.application.capabilities)
937
+ if (!this.active) return
938
+ for (const subscription of this.displayChanges)
939
+ this.application.queueCallback({
940
+ windowId: this.id,
941
+ display: subscription,
942
+ event: Object.freeze({
943
+ type: 'display_change',
944
+ sequence: event.sequence,
945
+ snapshot,
946
+ signal: subscription.controller.signal,
947
+ }),
948
+ })
949
+ }
950
+
951
+ private revokeDisplayChanges(): void {
952
+ for (const subscription of this.displayChanges) subscription.revoke()
953
+ this.displayChanges.clear()
954
+ }
955
+
956
+ async readClipboardText(options: ServiceRequestOptions = {}): Promise<NativeClipboardText> {
957
+ const signal = serviceSignal(options)
958
+ return this.clipboard('clipboard_read', signal, async () => {
959
+ const response = await this.application.host.send({
960
+ type: 'clipboard_read',
961
+ window_id: this.id,
962
+ })
963
+ return Object.freeze(response.result)
964
+ })
965
+ }
966
+
967
+ writeClipboardText(text: string): Promise<void> {
968
+ // Transport validation occurs before native I/O, including JS callers.
969
+ return this.clipboard('clipboard_write', undefined, async () => {
970
+ await this.application.host.send({ type: 'clipboard_write', window_id: this.id, text })
971
+ })
972
+ }
973
+
974
+ private async clipboard<T>(
975
+ service: 'clipboard_read' | 'clipboard_write',
976
+ signal: AbortSignal | undefined,
977
+ operation: () => Promise<T>
978
+ ): Promise<T> {
979
+ this.assertActive()
980
+ checkServiceCancellation(signal, service)
981
+ return this.application.service(async () => {
982
+ this.assertActive()
983
+ checkServiceCancellation(signal, service)
984
+ try {
985
+ const result = await operation()
986
+ this.assertActive()
987
+ checkServiceCancellation(signal, service)
988
+ return result
989
+ } catch (error) {
990
+ if (error instanceof ProtocolError) throw error
991
+ this.assertActive()
992
+ checkServiceCancellation(signal, service)
993
+ if (
994
+ error instanceof NativeCommandError &&
995
+ [
996
+ 'permission_denied',
997
+ 'service_unavailable',
998
+ 'cancelled',
999
+ 'native_failure',
1000
+ 'operation_timed_out',
1001
+ 'payload_too_large',
1002
+ 'limit_exceeded',
1003
+ ].includes(error.code)
1004
+ )
1005
+ throw new NativeServiceError(
1006
+ service,
1007
+ error.code as NativeServiceError['code'],
1008
+ error.message
1009
+ )
1010
+ throw error
1011
+ }
1012
+ })
1013
+ }
1014
+
1015
+ async registerGlobalShortcut(
1016
+ options: GlobalShortcutOptions,
1017
+ listener: (event: GlobalShortcutEvent) => void | Promise<void>
1018
+ ): Promise<NativeGlobalShortcut> {
1019
+ const { key, modifiers } = shortcutRequest(options)
1020
+ if (typeof listener !== 'function')
1021
+ throw new TypeError('A global shortcut listener must be a function')
1022
+ this.assertActive()
1023
+ return this.application.service(async () => {
1024
+ this.assertActive()
1025
+ const registration = new ShortcutRegistration(
1026
+ this.application.allocateShortcut(),
1027
+ this.id,
1028
+ key,
1029
+ modifiers,
1030
+ listener,
1031
+ (item) => this.releaseShortcut(item)
1032
+ )
1033
+ this.application.shortcuts.set(registration.id, registration)
1034
+ try {
1035
+ await this.application.host.send({
1036
+ type: 'register_global_shortcut',
1037
+ window_id: this.id,
1038
+ shortcut_id: registration.id,
1039
+ key,
1040
+ modifiers,
1041
+ })
1042
+ this.assertActive()
1043
+ if (!registration.live)
1044
+ throw new NativeServiceError(
1045
+ 'global_shortcuts',
1046
+ 'cancelled',
1047
+ 'Global shortcut was revoked during registration'
1048
+ )
1049
+ return registration.handle
1050
+ } catch (error) {
1051
+ registration.revoke()
1052
+ this.application.shortcuts.delete(registration.id)
1053
+ if (error instanceof ProtocolError) throw error
1054
+ this.assertActive()
1055
+ if (
1056
+ error instanceof NativeCommandError &&
1057
+ (SHORTCUT_ERRORS as readonly string[]).includes(error.code)
1058
+ )
1059
+ throw new NativeServiceError(
1060
+ 'global_shortcuts',
1061
+ error.code as NativeServiceError['code'],
1062
+ error.message
1063
+ )
1064
+ throw error
1065
+ }
1066
+ })
1067
+ }
1068
+
1069
+ private releaseShortcut(registration: ShortcutRegistration): Promise<void> {
1070
+ // Local revocation first: no activation is delivered after this call.
1071
+ registration.revoke()
1072
+ this.application.shortcuts.delete(registration.id)
1073
+ // Window close and application shutdown release the native grab.
1074
+ if (!this.active || !this.application.running) return Promise.resolve()
1075
+ return this.application.track(
1076
+ this.application.host
1077
+ .send({
1078
+ type: 'unregister_global_shortcut',
1079
+ window_id: this.id,
1080
+ shortcut_id: registration.id,
1081
+ })
1082
+ .then(
1083
+ () => {},
1084
+ (error: unknown) => {
1085
+ // The owner window can close while the request is in flight.
1086
+ if (error instanceof NativeCommandError && error.code === 'invalid_handle') return
1087
+ if (!this.application.running) return
1088
+ throw error
1089
+ }
1090
+ )
1091
+ )
1092
+ }
1093
+
1094
+ async postNotification(
1095
+ options: NotificationOptions,
1096
+ listener: (event: NotificationEvent) => void | Promise<void>
1097
+ ): Promise<NativeNotification> {
1098
+ const { title, body } = notificationRequest(options)
1099
+ if (typeof listener !== 'function')
1100
+ throw new TypeError('A notification listener must be a function')
1101
+ this.assertActive()
1102
+ return this.application.service(async () => {
1103
+ this.assertActive()
1104
+ const registration = new NotificationRegistration(
1105
+ this.application.allocateNotification(),
1106
+ this.id,
1107
+ title,
1108
+ body,
1109
+ listener,
1110
+ (item) => this.withdrawNotification(item)
1111
+ )
1112
+ this.application.notifications.set(registration.id, registration)
1113
+ try {
1114
+ const posted = await this.application.host.send({
1115
+ type: 'post_notification',
1116
+ window_id: this.id,
1117
+ notification_id: registration.id,
1118
+ title,
1119
+ body,
1120
+ })
1121
+ registration.activatable = posted.activatable
1122
+ this.assertActive()
1123
+ if (!registration.deliverable)
1124
+ throw new NativeServiceError(
1125
+ 'notifications',
1126
+ 'cancelled',
1127
+ 'Notification was revoked while it was posted'
1128
+ )
1129
+ return registration.handle
1130
+ } catch (error) {
1131
+ registration.revoke()
1132
+ this.application.notifications.delete(registration.id)
1133
+ if (error instanceof ProtocolError) throw error
1134
+ this.assertActive()
1135
+ if (
1136
+ error instanceof NativeCommandError &&
1137
+ (NOTIFICATION_ERRORS as readonly string[]).includes(error.code)
1138
+ )
1139
+ throw new NativeServiceError(
1140
+ 'notifications',
1141
+ error.code as NativeServiceError['code'],
1142
+ error.message
1143
+ )
1144
+ throw error
1145
+ }
1146
+ })
1147
+ }
1148
+
1149
+ async openFileGrant(root: string, options: FileGrantOptions = {}): Promise<NativeFileGrant> {
1150
+ const request = fileGrantRequest(root, options)
1151
+ this.assertActive()
1152
+ return this.application.service(async () => {
1153
+ this.assertActive()
1154
+ const registration = new FileGrantRegistration(
1155
+ this.application.allocateFileGrant(),
1156
+ this.id,
1157
+ request.root,
1158
+ request.access,
1159
+ (item, call) => this.fileCall(item, call),
1160
+ (item) => this.closeFileGrant(item)
1161
+ )
1162
+ this.application.fileGrants.set(registration.id, registration)
1163
+ try {
1164
+ await this.application.host.send({
1165
+ type: 'open_file_grant',
1166
+ window_id: this.id,
1167
+ grant_id: registration.id,
1168
+ root: request.root,
1169
+ access: request.access,
1170
+ })
1171
+ this.assertActive()
1172
+ if (!registration.live)
1173
+ throw new NativeServiceError(
1174
+ 'filesystem_grants',
1175
+ 'cancelled',
1176
+ 'File grant was revoked while it opened'
1177
+ )
1178
+ return registration.handle
1179
+ } catch (error) {
1180
+ registration.revoke()
1181
+ this.application.fileGrants.delete(registration.id)
1182
+ throw this.fileError(error)
1183
+ }
1184
+ })
1185
+ }
1186
+
1187
+ private fileError(error: unknown): unknown {
1188
+ if (error instanceof ProtocolError) return error
1189
+ this.assertActive()
1190
+ if (
1191
+ error instanceof NativeCommandError &&
1192
+ (FILE_ERRORS as readonly string[]).includes(error.code)
1193
+ )
1194
+ return new NativeServiceError(
1195
+ 'filesystem_grants',
1196
+ error.code as NativeServiceError['code'],
1197
+ error.message
1198
+ )
1199
+ return error
1200
+ }
1201
+
1202
+ private fileCall(registration: FileGrantRegistration, call: FileCall): Promise<unknown> {
1203
+ const revoked = () =>
1204
+ new NativeServiceError(
1205
+ 'filesystem_grants',
1206
+ 'cancelled',
1207
+ 'File grant is closed; no result is delivered'
1208
+ )
1209
+ if (!registration.live) return Promise.reject(revoked())
1210
+ this.assertActive()
1211
+ return this.application.service(async () => {
1212
+ this.assertActive()
1213
+ if (!registration.live) throw revoked()
1214
+ try {
1215
+ const response = await this.application.host.send({
1216
+ type: 'file_request',
1217
+ window_id: this.id,
1218
+ grant_id: registration.id,
1219
+ path: call.path,
1220
+ operation: call.operation,
1221
+ })
1222
+ // Revocation withholds a result the worker already produced.
1223
+ if (!registration.live) throw revoked()
1224
+ this.assertActive()
1225
+ return call.finish(response.result)
1226
+ } catch (error) {
1227
+ if (error instanceof ProtocolError) throw error
1228
+ if (!registration.live) throw revoked()
1229
+ this.assertActive()
1230
+ throw this.fileError(error)
1231
+ }
1232
+ })
1233
+ }
1234
+
1235
+ private closeFileGrant(registration: FileGrantRegistration): Promise<void> {
1236
+ registration.revoke()
1237
+ this.application.fileGrants.delete(registration.id)
1238
+ // Window close and application shutdown close the descriptor natively.
1239
+ if (!this.active || !this.application.running) return Promise.resolve()
1240
+ return this.application.track(
1241
+ this.application.host
1242
+ .send({ type: 'close_file_grant', window_id: this.id, grant_id: registration.id })
1243
+ .then(
1244
+ () => {},
1245
+ (error: unknown) => {
1246
+ if (error instanceof NativeCommandError && error.code === 'invalid_handle') return
1247
+ if (!this.application.running) return
1248
+ throw error
1249
+ }
1250
+ )
1251
+ )
1252
+ }
1253
+
1254
+ async spawnProcess(
1255
+ executable: string,
1256
+ options: ProcessOptions,
1257
+ listener: (event: ProcessEvent) => void | Promise<void>
1258
+ ): Promise<NativeProcess> {
1259
+ const request = processRequest(executable, options)
1260
+ if (typeof listener !== 'function') throw new TypeError('A process listener must be a function')
1261
+ this.assertActive()
1262
+ let cwd: { grant_id: number; path: string } | undefined
1263
+ if (request.cwd) {
1264
+ const grant = [...this.application.fileGrants.values()].find(
1265
+ (registration) => registration.handle === request.cwd!.grant
1266
+ )
1267
+ if (!grant || grant.windowId !== this.id)
1268
+ throw new TypeError('Process cwd must name a live file grant owned by this window')
1269
+ cwd = { grant_id: grant.id, path: request.cwd.path }
1270
+ }
1271
+ return this.application.service(async () => {
1272
+ this.assertActive()
1273
+ const registration = new ProcessRegistration(
1274
+ this.application.allocateProcess(),
1275
+ this.id,
1276
+ request.launch.executable,
1277
+ request.launch.terminal !== undefined,
1278
+ listener,
1279
+ (item, call) => this.processCall(item, call),
1280
+ (item) => this.releaseProcess(item)
1281
+ )
1282
+ this.application.processes.set(registration.id, registration)
1283
+ try {
1284
+ await this.application.host.send({
1285
+ type: 'spawn_process',
1286
+ window_id: this.id,
1287
+ process_id: registration.id,
1288
+ launch: cwd ? { ...request.launch, cwd } : request.launch,
1289
+ })
1290
+ this.assertActive()
1291
+ if (!registration.live)
1292
+ throw new NativeServiceError(
1293
+ 'processes',
1294
+ 'cancelled',
1295
+ 'Process was released while it started'
1296
+ )
1297
+ return registration.handle
1298
+ } catch (error) {
1299
+ registration.revoke()
1300
+ this.application.processes.delete(registration.id)
1301
+ throw this.processError(error)
1302
+ }
1303
+ })
1304
+ }
1305
+
1306
+ private processError(error: unknown): unknown {
1307
+ if (error instanceof ProtocolError) return error
1308
+ this.assertActive()
1309
+ if (
1310
+ error instanceof NativeCommandError &&
1311
+ (PROCESS_ERRORS as readonly string[]).includes(error.code)
1312
+ )
1313
+ return new NativeServiceError(
1314
+ 'processes',
1315
+ error.code as NativeServiceError['code'],
1316
+ error.message
1317
+ )
1318
+ return error
1319
+ }
1320
+
1321
+ private processCall(registration: ProcessRegistration, call: ProcessCall): Promise<void> {
1322
+ const revoked = () => new NativeServiceError('processes', 'cancelled', 'Process is released')
1323
+ if (!registration.live) return Promise.reject(revoked())
1324
+ this.assertActive()
1325
+ return this.application.service(async () => {
1326
+ this.assertActive()
1327
+ if (!registration.live) throw revoked()
1328
+ try {
1329
+ await this.application.host.send({
1330
+ ...call,
1331
+ window_id: this.id,
1332
+ process_id: registration.id,
1333
+ })
1334
+ } catch (error) {
1335
+ if (error instanceof ProtocolError) throw error
1336
+ if (!registration.live) throw revoked()
1337
+ this.assertActive()
1338
+ throw this.processError(error)
1339
+ }
1340
+ })
1341
+ }
1342
+
1343
+ private releaseProcess(registration: ProcessRegistration): Promise<void> {
1344
+ registration.revoke()
1345
+ this.application.processes.delete(registration.id)
1346
+ // Window close and application shutdown stop the process group natively.
1347
+ if (!this.active || !this.application.running) return Promise.resolve()
1348
+ return this.application.track(
1349
+ this.application.host
1350
+ .send({ type: 'release_process', window_id: this.id, process_id: registration.id })
1351
+ .then(
1352
+ () => {},
1353
+ (error: unknown) => {
1354
+ if (error instanceof NativeCommandError && error.code === 'invalid_handle') return
1355
+ if (!this.application.running) return
1356
+ throw error
1357
+ }
1358
+ )
1359
+ )
1360
+ }
1361
+
1362
+ receiveProcess(event: Extract<WindowEvent, { type: 'process_output' | 'process_exited' }>): void {
1363
+ if (!this.active) return
1364
+ const registration = this.application.processes.get(event.process_id)
1365
+ if (!registration?.live) return // Released: the host may already have queued output.
1366
+ if (registration.windowId !== this.id)
1367
+ throw new ProtocolError('Native event names a process outside its owner')
1368
+ if (registration.ended) throw new ProtocolError('Native process event follows its exit')
1369
+ const common = {
1370
+ sequence: event.sequence,
1371
+ process: registration.handle,
1372
+ signal: registration.controller.signal,
1373
+ }
1374
+ if (event.type === 'process_output') {
1375
+ if (event.chunk !== registration.chunk + 1)
1376
+ throw new ProtocolError('Native process output chunk is out of order')
1377
+ if ((event.stream === 'terminal') !== registration.handle.terminal)
1378
+ throw new ProtocolError('Native process output names the wrong stream kind')
1379
+ registration.chunk = event.chunk
1380
+ this.application.queueCallback({
1381
+ windowId: this.id,
1382
+ process: registration,
1383
+ chunk: event.chunk,
1384
+ event: Object.freeze({
1385
+ type: 'process_output',
1386
+ stream: event.stream,
1387
+ bytes: Uint8Array.fromBase64(event.data),
1388
+ ...common,
1389
+ }),
1390
+ })
1391
+ return
1392
+ }
1393
+ registration.end()
1394
+ registration.exit = Object.freeze({ ...event.exit })
1395
+ this.application.queueCallback({
1396
+ windowId: this.id,
1397
+ process: registration,
1398
+ chunk: 0,
1399
+ event: Object.freeze({ type: 'process_exited', exit: registration.exit, ...common }),
1400
+ })
1401
+ }
1402
+
1403
+ async dispatchProcess(
1404
+ registration: ProcessRegistration,
1405
+ event: ProcessEvent,
1406
+ chunk: number
1407
+ ): Promise<void> {
1408
+ const listener = registration.listener
1409
+ if (!listener || !registration.live) return
1410
+ await dispatchOwned(listener, event, registration.controller.signal)
1411
+ // The settled callback returns one delivery credit to the host.
1412
+ if (event.type !== 'process_output' || !registration.live) return
1413
+ if (!this.active || !this.application.running) return
1414
+ // A lost delivery credit stalls the stream, so a failed acknowledgement ends
1415
+ // the application with that error instead of an unhandled rejection.
1416
+ void this.application.track(
1417
+ this.application.host
1418
+ .send({
1419
+ type: 'acknowledge_process_output',
1420
+ window_id: this.id,
1421
+ process_id: registration.id,
1422
+ chunk,
1423
+ })
1424
+ .then(
1425
+ () => {},
1426
+ (error: unknown) => {
1427
+ // Release or window close can race the acknowledgement.
1428
+ if (error instanceof NativeCommandError && error.code === 'invalid_handle') return
1429
+ // A lost transport is reported by the application's own closed promise;
1430
+ // recording it here first would hide the original cause.
1431
+ if (!(error instanceof NativeCommandError) || !this.application.running) return
1432
+ // Not awaited: shutdown waits for this tracked operation.
1433
+ void this.application.fail(error)
1434
+ }
1435
+ )
1436
+ )
1437
+ }
1438
+
1439
+ async registerDropTarget(
1440
+ handle: NativeNode,
1441
+ listener: (event: DropTargetEvent) => void | Promise<void>
1442
+ ): Promise<NativeDropTarget> {
1443
+ if (typeof listener !== 'function')
1444
+ throw new TypeError('A drop target listener must be a function')
1445
+ this.assertActive()
1446
+ const node = own(this.nodes, handle)
1447
+ return this.application.service(async () => {
1448
+ this.assertActive()
1449
+ if (this.nodes.get(node.id)?.handle !== node.handle)
1450
+ throw new NativeStateError('invalid_handle', 'Drop target node was removed')
1451
+ const registration = new DropTargetRegistration(
1452
+ this.application.allocateDropTarget(),
1453
+ this.id,
1454
+ node.id,
1455
+ node.handle,
1456
+ listener,
1457
+ (item) => this.releaseDropTarget(item)
1458
+ )
1459
+ this.application.dropTargets.set(registration.id, registration)
1460
+ try {
1461
+ await this.application.host.send({
1462
+ type: 'register_drop_target',
1463
+ window_id: this.id,
1464
+ target_id: registration.id,
1465
+ node_id: node.id,
1466
+ })
1467
+ this.assertActive()
1468
+ if (!registration.live)
1469
+ throw new NativeServiceError(
1470
+ 'drag_drop',
1471
+ 'cancelled',
1472
+ 'Drop target was revoked during registration'
1473
+ )
1474
+ return registration.handle
1475
+ } catch (error) {
1476
+ registration.revoke()
1477
+ this.application.dropTargets.delete(registration.id)
1478
+ if (error instanceof ProtocolError) throw error
1479
+ this.assertActive()
1480
+ if (error instanceof NativeCommandError && error.code === 'invalid_handle')
1481
+ throw new NativeStateError('invalid_handle', 'Drop target node is not committed')
1482
+ throw this.dropError(error)
1483
+ }
1484
+ })
1485
+ }
1486
+
1487
+ private dropError(error: unknown): unknown {
1488
+ if (
1489
+ error instanceof NativeCommandError &&
1490
+ (DROP_ERRORS as readonly string[]).includes(error.code)
1491
+ )
1492
+ return new NativeServiceError(
1493
+ 'drag_drop',
1494
+ error.code as NativeServiceError['code'],
1495
+ error.message
1496
+ )
1497
+ return error
1498
+ }
1499
+
1500
+ private releaseDropTarget(registration: DropTargetRegistration): Promise<void> {
1501
+ // Local revocation first: no drag or drop is delivered after this call.
1502
+ registration.revoke()
1503
+ this.application.dropTargets.delete(registration.id)
1504
+ // Window close and application shutdown remove it natively.
1505
+ if (!this.active || !this.application.running) return Promise.resolve()
1506
+ return this.application.track(
1507
+ this.application.host
1508
+ .send({
1509
+ type: 'unregister_drop_target',
1510
+ window_id: this.id,
1511
+ target_id: registration.id,
1512
+ })
1513
+ .then(
1514
+ () => {},
1515
+ (error: unknown) => {
1516
+ // A tree commit or the owner window can remove it while in flight.
1517
+ if (error instanceof NativeCommandError && error.code === 'invalid_handle') return
1518
+ if (!this.application.running) return
1519
+ throw error
1520
+ }
1521
+ )
1522
+ )
1523
+ }
1524
+
1525
+ private resolveDroppedItem(
1526
+ registration: DropTargetRegistration,
1527
+ dropId: number,
1528
+ item: number,
1529
+ requested: string
1530
+ ): Promise<Readonly<{ root: string; path: string }>> {
1531
+ const stale = () =>
1532
+ new NativeServiceError(
1533
+ 'drag_drop',
1534
+ 'cancelled',
1535
+ 'The drop was replaced or its target revoked; no result is delivered'
1536
+ )
1537
+ let root: string
1538
+ try {
1539
+ root = parseRootId(requested)
1540
+ } catch (error) {
1541
+ return Promise.reject(new TypeError((error as Error).message))
1542
+ }
1543
+ const live = () => registration.live && registration.latestDrop === dropId
1544
+ if (!live()) return Promise.reject(stale())
1545
+ this.assertActive()
1546
+ return this.application.service(async () => {
1547
+ this.assertActive()
1548
+ if (!live()) throw stale()
1549
+ try {
1550
+ const response = await this.application.host.send({
1551
+ type: 'resolve_dropped_item',
1552
+ window_id: this.id,
1553
+ target_id: registration.id,
1554
+ drop_id: dropId,
1555
+ item,
1556
+ root,
1557
+ })
1558
+ // Revocation withholds a result the host already produced.
1559
+ this.assertActive()
1560
+ if (!live()) throw stale()
1561
+ return Object.freeze({ root: response.root, path: response.path })
1562
+ } catch (error) {
1563
+ if (error instanceof ProtocolError) throw error
1564
+ this.assertActive()
1565
+ if (!live()) throw stale()
1566
+ if (error instanceof NativeCommandError && error.code === 'invalid_handle') throw stale()
1567
+ throw this.dropError(error)
1568
+ }
1569
+ })
1570
+ }
1571
+
1572
+ receiveDrop(
1573
+ event: Extract<WindowEvent, { type: 'drop_target_drag' | 'drop_received' | 'drop_rejected' }>
1574
+ ): void {
1575
+ if (!this.active) return
1576
+ const registration = this.application.dropTargets.get(event.target_id)
1577
+ if (!registration?.live) return // Revoked: the host may already have queued this event.
1578
+ if (registration.windowId !== this.id)
1579
+ throw new ProtocolError('Native event names a drop target outside its owner')
1580
+ const common = {
1581
+ sequence: event.sequence,
1582
+ target: registration.handle,
1583
+ signal: registration.controller.signal,
1584
+ }
1585
+ let delivered: DropTargetEvent
1586
+ if (event.type === 'drop_target_drag')
1587
+ delivered = { type: event.state === 'entered' ? 'drag_entered' : 'drag_left', ...common }
1588
+ else if (event.type === 'drop_rejected') {
1589
+ registration.latestDrop = undefined
1590
+ delivered = { type: 'drop_rejected', reason: event.reason, ...common }
1591
+ } else {
1592
+ registration.latestDrop = event.drop_id
1593
+ const dropId = event.drop_id
1594
+ const items: NativeDroppedItem[] = event.items.map((item, index) =>
1595
+ Object.freeze({
1596
+ name: item.name,
1597
+ resolve: (root: string) => this.resolveDroppedItem(registration, dropId, index, root),
1598
+ })
1599
+ )
1600
+ delivered = { type: 'drop', items: Object.freeze(items), ...common }
1601
+ }
1602
+ this.application.queueCallback({
1603
+ windowId: this.id,
1604
+ dropTarget: registration,
1605
+ event: Object.freeze(delivered),
1606
+ })
1607
+ }
1608
+
1609
+ private withdrawNotification(registration: NotificationRegistration): Promise<void> {
1610
+ // Local revocation first: no activation is delivered after this call.
1611
+ registration.revoke()
1612
+ this.application.notifications.delete(registration.id)
1613
+ // Window close and application shutdown withdraw it natively.
1614
+ if (!this.active || !this.application.running) return Promise.resolve()
1615
+ return this.application.track(
1616
+ this.application.host
1617
+ .send({
1618
+ type: 'withdraw_notification',
1619
+ window_id: this.id,
1620
+ notification_id: registration.id,
1621
+ })
1622
+ .then(
1623
+ () => {},
1624
+ (error: unknown) => {
1625
+ // The server or the owner can end it while the request is in flight.
1626
+ if (error instanceof NativeCommandError && error.code === 'invalid_handle') return
1627
+ if (!this.application.running) return
1628
+ throw error
1629
+ }
1630
+ )
1631
+ )
1632
+ }
1633
+
1634
+ receiveNotification(
1635
+ event: Extract<WindowEvent, { type: 'notification_activated' | 'notification_dismissed' }>
1636
+ ): void {
1637
+ if (!this.active) return
1638
+ const registration = this.application.notifications.get(event.notification_id)
1639
+ if (!registration?.live) return // Withdrawn: the host may already have queued an event.
1640
+ if (registration.windowId !== this.id)
1641
+ throw new ProtocolError('Native event names a notification outside its owner')
1642
+ const common = {
1643
+ sequence: event.sequence,
1644
+ notification: registration.handle,
1645
+ signal: registration.controller.signal,
1646
+ }
1647
+ if (event.type === 'notification_dismissed') {
1648
+ registration.end()
1649
+ this.application.notifications.delete(registration.id)
1650
+ }
1651
+ this.application.queueCallback({
1652
+ windowId: this.id,
1653
+ notification: registration,
1654
+ event: Object.freeze(
1655
+ event.type === 'notification_activated'
1656
+ ? { type: 'notification_activated', ...common }
1657
+ : { type: 'notification_dismissed', reason: event.reason, ...common }
1658
+ ),
1659
+ })
1660
+ }
1661
+
1662
+ async showOpenDialog(
1663
+ options: OpenDialogOptions,
1664
+ request: ServiceRequestOptions = {}
1665
+ ): Promise<OpenDialogResult> {
1666
+ const wire = openDialogRequest(options)
1667
+ const result = await this.fileDialog(wire, serviceSignal(request))
1668
+ return result.kind === 'selected'
1669
+ ? Object.freeze({ kind: 'selected', paths: Object.freeze([...result.paths]) })
1670
+ : Object.freeze({ kind: 'cancelled' })
1671
+ }
1672
+
1673
+ async showSaveDialog(
1674
+ options: SaveDialogOptions,
1675
+ request: ServiceRequestOptions = {}
1676
+ ): Promise<SaveDialogResult> {
1677
+ const wire = saveDialogRequest(options)
1678
+ const result = await this.fileDialog(wire, serviceSignal(request))
1679
+ return result.kind === 'selected'
1680
+ ? Object.freeze({ kind: 'selected', path: result.paths[0]! })
1681
+ : Object.freeze({ kind: 'cancelled' })
1682
+ }
1683
+
1684
+ private async fileDialog(options: FileDialogOptions, signal: AbortSignal | undefined) {
1685
+ this.assertActive()
1686
+ checkServiceCancellation(signal, 'file_dialogs')
1687
+ const dialog = await this.application.service(async () => {
1688
+ this.assertActive()
1689
+ checkServiceCancellation(signal, 'file_dialogs')
1690
+ for (const other of this.application.dialogs.values())
1691
+ if (other.windowId === this.id)
1692
+ throw new NativeServiceError(
1693
+ 'file_dialogs',
1694
+ 'limit_exceeded',
1695
+ 'This window already has an open file dialog'
1696
+ )
1697
+ const dialog = new FileDialogRequest(this.application.allocateDialog(), this.id, options.mode)
1698
+ this.application.dialogs.set(dialog.id, dialog)
1699
+ try {
1700
+ await this.application.host.send({
1701
+ type: 'show_file_dialog',
1702
+ window_id: this.id,
1703
+ dialog_id: dialog.id,
1704
+ options,
1705
+ })
1706
+ this.assertActive()
1707
+ return dialog
1708
+ } catch (error) {
1709
+ dialog.fail(error instanceof Error ? error : new Error(String(error)))
1710
+ this.application.dialogs.delete(dialog.id)
1711
+ if (error instanceof ProtocolError) throw error
1712
+ this.assertActive()
1713
+ if (
1714
+ error instanceof NativeCommandError &&
1715
+ (DIALOG_ERRORS as readonly string[]).includes(error.code)
1716
+ )
1717
+ throw new NativeServiceError(
1718
+ 'file_dialogs',
1719
+ error.code as NativeServiceError['code'],
1720
+ error.message
1721
+ )
1722
+ throw error
1723
+ }
1724
+ })
1725
+ // An abort while the host was showing it closes the now-live dialog.
1726
+ const cancel = () => this.closeFileDialog(dialog)
1727
+ if (signal?.aborted) cancel()
1728
+ else signal?.addEventListener('abort', cancel, { once: true })
1729
+ try {
1730
+ return await dialog.result
1731
+ } finally {
1732
+ signal?.removeEventListener('abort', cancel)
1733
+ }
1734
+ }
1735
+
1736
+ async showContextMenu(
1737
+ items: readonly MenuEntryOptions[],
1738
+ position: ContextMenuPosition,
1739
+ request: ServiceRequestOptions = {}
1740
+ ): Promise<string | null> {
1741
+ const wire = contextMenuRequest(items, position)
1742
+ if (!this.application.capabilities.includes('context_menus_v1'))
1743
+ throw new UnsupportedFeatureError('context_menu')
1744
+ const signal = serviceSignal(request)
1745
+ this.assertActive()
1746
+ checkServiceCancellation(signal, 'context_menus')
1747
+ const menu = await this.application.service(async () => {
1748
+ this.assertActive()
1749
+ checkServiceCancellation(signal, 'context_menus')
1750
+ for (const other of this.application.contextMenus.values())
1751
+ if (other.live)
1752
+ throw new NativeServiceError(
1753
+ 'context_menus',
1754
+ 'limit_exceeded',
1755
+ 'Another context menu is already open'
1756
+ )
1757
+ const menu = new ContextMenuRequest(
1758
+ this.application.allocateContextMenu(),
1759
+ this.id,
1760
+ itemIds(wire.items)
1761
+ )
1762
+ this.application.contextMenus.set(menu.id, menu)
1763
+ try {
1764
+ await this.application.host.send({
1765
+ type: 'show_context_menu',
1766
+ window_id: this.id,
1767
+ menu_id: menu.id,
1768
+ ...wire,
1769
+ })
1770
+ this.assertActive()
1771
+ return menu
1772
+ } catch (error) {
1773
+ menu.fail(error instanceof Error ? error : new Error(String(error)))
1774
+ this.application.contextMenus.delete(menu.id)
1775
+ if (error instanceof ProtocolError) throw error
1776
+ this.assertActive()
1777
+ if (
1778
+ error instanceof NativeCommandError &&
1779
+ (DIALOG_ERRORS as readonly string[]).includes(error.code)
1780
+ )
1781
+ throw new NativeServiceError(
1782
+ 'context_menus',
1783
+ error.code as NativeServiceError['code'],
1784
+ error.message
1785
+ )
1786
+ throw error
1787
+ }
1788
+ })
1789
+ // An abort while the host was showing it closes the now-live menu.
1790
+ const cancel = () => this.closeContextMenu(menu)
1791
+ if (signal?.aborted) cancel()
1792
+ else signal?.addEventListener('abort', cancel, { once: true })
1793
+ try {
1794
+ return await menu.result
1795
+ } finally {
1796
+ signal?.removeEventListener('abort', cancel)
1797
+ }
1798
+ }
1799
+
1800
+ private closeContextMenu(menu: ContextMenuRequest): void {
1801
+ if (!menu.live) return
1802
+ menu.fail(
1803
+ new NativeServiceError('context_menus', 'cancelled', 'The context menu was cancelled')
1804
+ )
1805
+ this.application.contextMenus.delete(menu.id)
1806
+ // Window close and application shutdown close it natively.
1807
+ if (!this.active || !this.application.running) return
1808
+ void this.application
1809
+ .track(
1810
+ this.application.host
1811
+ .send({ type: 'close_context_menu', window_id: this.id, menu_id: menu.id })
1812
+ .then(
1813
+ () => {},
1814
+ (error: unknown) => {
1815
+ // The user can end it, or the owner close, while this is in flight.
1816
+ if (error instanceof NativeCommandError && error.code === 'invalid_handle') return
1817
+ if (!this.application.running) return
1818
+ throw error
1819
+ }
1820
+ )
1821
+ )
1822
+ .catch(() => {})
1823
+ }
1824
+
1825
+ receiveContextMenu(event: Extract<WindowEvent, { type: 'context_menu_completed' }>): void {
1826
+ if (!this.active) return
1827
+ const menu = this.application.contextMenus.get(event.menu_id)
1828
+ if (!menu) return // Cancelled: the host may already have queued a result.
1829
+ if (menu.windowId !== this.id)
1830
+ throw new ProtocolError('Native event names a context menu outside its owner')
1831
+ this.application.contextMenus.delete(menu.id)
1832
+ menu.complete(event.item_id)
1833
+ }
1834
+
1835
+ async showMessageDialog(
1836
+ options: MessageDialogOptions,
1837
+ request: ServiceRequestOptions = {}
1838
+ ): Promise<MessageDialogResult> {
1839
+ return this.messageDialog(messageDialogSpec(options), request)
1840
+ }
1841
+
1842
+ async showConfirmDialog(
1843
+ options: ConfirmDialogOptions,
1844
+ request: ServiceRequestOptions = {}
1845
+ ): Promise<boolean> {
1846
+ const result = await this.messageDialog(confirmDialogSpec(options), request)
1847
+ return result.kind === 'button' && result.id === 'confirm'
1848
+ }
1849
+
1850
+ /** The OS backend, only when the host offers it and the application granted it. */
1851
+ private nativeMessageDialogs(): NativeMessageDialogBackend | undefined {
1852
+ const capability = this.application.serviceCapabilities.messageDialogs
1853
+ if (capability.availability !== 'available' || capability.backend === 'modal_overlay')
1854
+ return undefined
1855
+ return {
1856
+ allocate: () => this.application.allocateMessageDialog(),
1857
+ show: async (id, options) => {
1858
+ try {
1859
+ await this.application.service(() =>
1860
+ this.application.host.send({
1861
+ type: 'show_message_dialog',
1862
+ window_id: this.id,
1863
+ dialog_id: id,
1864
+ options,
1865
+ })
1866
+ )
1867
+ } catch (error) {
1868
+ if (
1869
+ error instanceof NativeCommandError &&
1870
+ (DIALOG_ERRORS as readonly string[]).includes(error.code)
1871
+ )
1872
+ throw new NativeServiceError(
1873
+ 'message_dialogs',
1874
+ error.code as NativeServiceError['code'],
1875
+ error.message
1876
+ )
1877
+ throw error
1878
+ }
1879
+ },
1880
+ close: async (id) => {
1881
+ // Window close and application shutdown close it natively.
1882
+ if (!this.active || !this.application.running) return
1883
+ try {
1884
+ await this.application.track(
1885
+ this.application.host
1886
+ .send({ type: 'close_message_dialog', window_id: this.id, dialog_id: id })
1887
+ .then(() => {})
1888
+ )
1889
+ } catch (error) {
1890
+ // The user can finish it, or the owner close, while this is in flight.
1891
+ if (error instanceof NativeCommandError && error.code === 'invalid_handle') return
1892
+ if (!this.application.running) return
1893
+ throw error
1894
+ }
1895
+ },
1896
+ }
1897
+ }
1898
+
1899
+ private messageDialog(
1900
+ spec: Parameters<MessageDialogs['show']>[0],
1901
+ request: ServiceRequestOptions
1902
+ ): Promise<MessageDialogResult> {
1903
+ const signal = serviceSignal(request)
1904
+ this.assertActive()
1905
+ if (this.application.serviceCapabilities.messageDialogs.availability !== 'available')
1906
+ throw new NativeServiceError(
1907
+ 'message_dialogs',
1908
+ 'service_unavailable',
1909
+ 'The native host does not advertise modal overlays with focus requests'
1910
+ )
1911
+ return this.messages.show(spec, signal)
1912
+ }
1913
+
1914
+ /** Delivery stops at once; the OS dialog is then closed natively. */
1915
+ private closeFileDialog(dialog: FileDialogRequest): void {
1916
+ if (!dialog.live) return
1917
+ dialog.fail(
1918
+ new NativeServiceError('file_dialogs', 'cancelled', 'The file dialog was cancelled')
1919
+ )
1920
+ this.application.dialogs.delete(dialog.id)
1921
+ // Window close and application shutdown close it natively.
1922
+ if (!this.active || !this.application.running) return
1923
+ void this.application
1924
+ .track(
1925
+ this.application.host
1926
+ .send({ type: 'close_file_dialog', window_id: this.id, dialog_id: dialog.id })
1927
+ .then(
1928
+ () => {},
1929
+ (error: unknown) => {
1930
+ // The user can finish it, or the owner close, while this is in flight.
1931
+ if (error instanceof NativeCommandError && error.code === 'invalid_handle') return
1932
+ if (!this.application.running) return
1933
+ throw error
1934
+ }
1935
+ )
1936
+ )
1937
+ .catch(() => {})
1938
+ }
1939
+
1940
+ receiveFileDialog(event: Extract<WindowEvent, { type: 'file_dialog_completed' }>): void {
1941
+ if (!this.active) return
1942
+ const dialog = this.application.dialogs.get(event.dialog_id)
1943
+ if (!dialog) return // Cancelled: the host may already have queued a result.
1944
+ if (dialog.windowId !== this.id)
1945
+ throw new ProtocolError('Native event names a file dialog outside its owner')
1946
+ this.application.dialogs.delete(dialog.id)
1947
+ dialog.complete(event.result)
1948
+ }
1949
+
1950
+ receiveShortcut(event: Extract<WindowEvent, { type: 'global_shortcut' }>): void {
1951
+ if (!this.active) return
1952
+ const registration = this.application.shortcuts.get(event.shortcut_id)
1953
+ if (!registration) return // Released: the host may already have queued a press.
1954
+ if (registration.windowId !== this.id)
1955
+ throw new ProtocolError('Native event names a global shortcut outside its owner')
1956
+ this.application.queueCallback({
1957
+ windowId: this.id,
1958
+ shortcut: registration,
1959
+ event: Object.freeze({
1960
+ type: 'global_shortcut',
1961
+ sequence: event.sequence,
1962
+ shortcut: registration.handle,
1963
+ signal: registration.controller.signal,
1964
+ }),
1965
+ })
1966
+ }
1967
+
1968
+ async close(): Promise<void> {
1969
+ if (!this.active) {
1970
+ await this.closing
1971
+ return
1972
+ }
1973
+ this.active = false
1974
+ this.listeners.clear()
1975
+ this.nodes = new Map()
1976
+ this.text = new CommittedText(this.application.limits.max_text_bytes)
1977
+ this.revokeDisplayChanges()
1978
+ this.revokeOwned()
1979
+ this.closing = this.application.enqueue(async () => {
1980
+ try {
1981
+ await this.application.host.send({ type: 'close', window_id: this.id })
1982
+ } catch (error) {
1983
+ // An OS close can race an application close after revocation.
1984
+ if (!(error instanceof NativeCommandError && error.code === 'invalid_handle')) {
1985
+ // Do not leave an unreachable native window alive after close fails.
1986
+ void this.application.shutdown().catch(() => {})
1987
+ throw error
1988
+ }
1989
+ }
1990
+ this.revoke()
1991
+ }, true)
1992
+ await this.closing
1993
+ }
1994
+
1995
+ /**
1996
+ * Revoke every service registration this window owns. `close()` runs it as
1997
+ * soon as the close starts, so an in-flight grant or process call settles as
1998
+ * `cancelled`, not as `invalid_handle` after the host acknowledges the close.
1999
+ */
2000
+ private revokeOwned(): void {
2001
+ for (const registration of this.application.shortcuts.values())
2002
+ if (registration.windowId === this.id) {
2003
+ registration.revoke()
2004
+ this.application.shortcuts.delete(registration.id)
2005
+ }
2006
+ for (const registration of this.application.notifications.values())
2007
+ if (registration.windowId === this.id) {
2008
+ registration.revoke()
2009
+ this.application.notifications.delete(registration.id)
2010
+ }
2011
+ for (const registration of this.application.fileGrants.values())
2012
+ if (registration.windowId === this.id) {
2013
+ registration.revoke()
2014
+ this.application.fileGrants.delete(registration.id)
2015
+ }
2016
+ for (const registration of this.application.processes.values())
2017
+ if (registration.windowId === this.id) {
2018
+ registration.revoke()
2019
+ this.application.processes.delete(registration.id)
2020
+ }
2021
+ for (const registration of this.application.dropTargets.values())
2022
+ if (registration.windowId === this.id) {
2023
+ registration.revoke()
2024
+ this.application.dropTargets.delete(registration.id)
2025
+ }
2026
+ }
2027
+
2028
+ revoke(): void {
2029
+ this.active = false
2030
+ this.listeners.clear()
2031
+ this.nodes = new Map()
2032
+ this.text = new CommittedText(this.application.limits.max_text_bytes)
2033
+ this.revokeDisplayChanges()
2034
+ this.revokeOwned()
2035
+ for (const dialog of this.application.dialogs.values())
2036
+ if (dialog.windowId === this.id) {
2037
+ dialog.fail(new NativeStateError('invalid_handle', 'File dialog owner window was closed'))
2038
+ this.application.dialogs.delete(dialog.id)
2039
+ }
2040
+ for (const menu of this.application.contextMenus.values())
2041
+ if (menu.windowId === this.id) {
2042
+ menu.fail(new NativeStateError('invalid_handle', 'Context menu owner window was closed'))
2043
+ this.application.contextMenus.delete(menu.id)
2044
+ }
2045
+ this.messages.revoke()
2046
+ this.application.windows.delete(this.id)
2047
+ this.resolveClosed()
2048
+ }
2049
+
2050
+ isTargetLive(id: number): boolean {
2051
+ return this.active && this.nodes.has(id)
2052
+ }
2053
+
2054
+ receive(event: WindowEvent, nextNode: number): void {
2055
+ if (event.type === 'closed') {
2056
+ this.revoke()
2057
+ return
2058
+ }
2059
+ if (event.type === 'display_changed') {
2060
+ this.receiveDisplayChange(event)
2061
+ return
2062
+ }
2063
+ if (event.type === 'global_shortcut') {
2064
+ this.receiveShortcut(event)
2065
+ return
2066
+ }
2067
+ if (event.type === 'notification_activated' || event.type === 'notification_dismissed') {
2068
+ this.receiveNotification(event)
2069
+ return
2070
+ }
2071
+ if (event.type === 'process_output' || event.type === 'process_exited') {
2072
+ this.receiveProcess(event)
2073
+ return
2074
+ }
2075
+ if (event.type === 'file_dialog_completed') {
2076
+ this.receiveFileDialog(event)
2077
+ return
2078
+ }
2079
+ if (event.type === 'context_menu_completed') {
2080
+ this.receiveContextMenu(event)
2081
+ return
2082
+ }
2083
+ if (event.type === 'message_dialog_completed') {
2084
+ if (this.active) this.messages.completeNative(event.dialog_id, event.result)
2085
+ return
2086
+ }
2087
+ if (
2088
+ event.type === 'drop_target_drag' ||
2089
+ event.type === 'drop_received' ||
2090
+ event.type === 'drop_rejected'
2091
+ ) {
2092
+ this.receiveDrop(event)
2093
+ return
2094
+ }
2095
+ if (!this.active) return
2096
+ if (event.tree_revision > this.revision)
2097
+ throw new ProtocolError('Native event tree revision is ahead of its acknowledgement')
2098
+ if (event.path[0] !== this.rootId)
2099
+ throw new ProtocolError('Native event path starts outside its window root')
2100
+ const ownedPath: NodeState[] = []
2101
+ for (const id of event.path) {
2102
+ if (id >= nextNode) throw new ProtocolError('Native event names a node outside its owner')
2103
+ const node = this.nodes.get(id)
2104
+ if (node) ownedPath.push(node)
2105
+ else
2106
+ for (const window of this.application.windows.values())
2107
+ if (window !== this && window.nodes.has(id))
2108
+ throw new ProtocolError('Native event names a node outside its owner')
2109
+ }
2110
+ // Already revoked ownership cannot be recovered by a delayed native frame.
2111
+ if (ownedPath.length !== event.path.length) return
2112
+ if (
2113
+ event.tree_revision === this.revision &&
2114
+ ownedPath.some((node, index) => index > 0 && node.parent !== event.path[index - 1])
2115
+ )
2116
+ throw new ProtocolError('Native event path does not match its committed tree revision')
2117
+ const node = ownedPath.at(-1)!
2118
+ if (event.type === 'input') {
2119
+ if (node.element.kind !== 'input' || event.input_revision <= node.inputRevision)
2120
+ throw new ProtocolError('Native input kind or edit revision is invalid')
2121
+ const element = { ...node.element, value: event.value }
2122
+ this.text.replace(node.id, node.element, element)
2123
+ node.inputRevision = event.input_revision
2124
+ node.element = element
2125
+ } else if (event.type === 'click') {
2126
+ if (node.element.kind !== 'button')
2127
+ throw new ProtocolError('Native click targeted a non-button node')
2128
+ if (node.element.disabled) return
2129
+ } else if (event.type === 'dismiss') {
2130
+ if (node.element.kind !== 'overlay' || node.element.surface !== 'window')
2131
+ throw new ProtocolError('Native dismissal targeted a non-popup node')
2132
+ } else if (event.type === 'split_resize') {
2133
+ if (
2134
+ node.element.kind !== 'split' ||
2135
+ !this.application.capabilities.includes('split_resize_v1')
2136
+ )
2137
+ throw new ProtocolError(
2138
+ 'Native split resize targeted a non-split node or was not advertised'
2139
+ )
2140
+ }
2141
+ // Input inside a message dialog settles it during ingestion.
2142
+ if (
2143
+ this.messages.receive(
2144
+ event,
2145
+ ownedPath.map((item) => item.handle),
2146
+ node.handle
2147
+ )
2148
+ )
2149
+ return
2150
+ const plan = this.listeners.prepare(
2151
+ event,
2152
+ ownedPath.map((item) => item.handle)
2153
+ )
2154
+ if (plan) this.application.queueCallback({ windowId: this.id, nodeId: node.id, plan })
2155
+ }
2156
+
2157
+ async dispatch(nodeId: number, plan: DispatchPlan): Promise<void> {
2158
+ try {
2159
+ await dispatchPlan(plan, () => this.isTargetLive(nodeId))
2160
+ } finally {
2161
+ this.listeners.release(plan)
2162
+ }
2163
+ }
2164
+ }
2165
+
2166
+ export async function createApplication(options: HostOptions): Promise<NativeApplication> {
2167
+ return new Application(await NativeHost.launch(options))
2168
+ }