@bun-native/core 0.33.0 → 0.33.1

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.
@@ -1,19 +1,19 @@
1
1
  import {
2
2
  parseRootId,
3
3
  ProtocolError,
4
+ type ApplicationEvent,
4
5
  type Capability,
5
6
  type FileDialogOptions,
7
+ type HostEvent,
6
8
  type Limits,
7
- type Operation,
9
+ type WindowEvent,
8
10
  } from '@bun-native/protocol'
9
11
  import {
10
12
  NativeCommandError,
11
13
  NativeHost,
12
- type ApplicationEvent,
13
14
  type HostOptions,
14
- type WindowEvent,
15
+ type WindowCommand,
15
16
  } from '@bun-native/runtime'
16
- import { planStagedCommit, sendStagedCommit } from './commit-plan.ts'
17
17
  import { dispatchPlan, EventBindings, prunePlan, type DispatchPlan } from './events.ts'
18
18
  import { DisplaySubscription } from './display.ts'
19
19
  import {
@@ -114,15 +114,48 @@ import {
114
114
 
115
115
  const MAX_QUEUED_TRANSACTIONS = 128
116
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 }
117
+ /**
118
+ * One queued application callback. `run` delivers it; `retain` decides, when
119
+ * its window cancels callbacks, whether it stays queued. Without a window it
120
+ * belongs to the application (the menu bar).
121
+ */
122
+ interface Callback {
123
+ readonly windowId?: number | undefined
124
+ retain(): boolean
125
+ run(): Promise<void>
126
+ }
127
+
128
+ /** A service registration whose listener receives its own events. */
129
+ interface Delivery<T> {
130
+ readonly live: boolean
131
+ readonly listener: Listener<T> | undefined
132
+ readonly controller: AbortController
133
+ }
134
+
135
+ function listenerCallback<T>(
136
+ windowId: number | undefined,
137
+ registration: Delivery<T>,
138
+ event: T
139
+ ): Callback {
140
+ return { windowId, retain: () => registration.live, run: () => deliver(registration, event) }
141
+ }
142
+
143
+ /** Monotonic identities of one kind: never reused, never wrapped. */
144
+ class Identities {
145
+ next = 1
146
+ constructor(private readonly kind: string) {}
147
+
148
+ allocate(): number {
149
+ if (!Number.isSafeInteger(this.next))
150
+ throw new NativeStateError('limit_exceeded', this.kind + ' identity space exhausted')
151
+ return this.next++
152
+ }
153
+
154
+ /** Whether `id` names an identity this space has already handed out. */
155
+ has(id: number): boolean {
156
+ return id < this.next
157
+ }
158
+ }
126
159
 
127
160
  class Application implements NativeApplication {
128
161
  readonly closed: Promise<void>
@@ -132,32 +165,37 @@ class Application implements NativeApplication {
132
165
  readonly serviceCapabilities: Readonly<ServiceCapabilities>
133
166
  readonly windows = new Map<number, Window>()
134
167
  readonly shortcuts = new Map<number, ShortcutRegistration>()
135
- private nextShortcut = 1
136
168
  readonly notifications = new Map<number, NotificationRegistration>()
137
- private nextNotification = 1
138
169
  readonly fileGrants = new Map<number, FileGrantRegistration>()
139
- private nextFileGrant = 1
140
170
  readonly processes = new Map<number, ProcessRegistration>()
141
- private nextProcess = 1
142
171
  readonly dialogs = new Map<number, FileDialogRequest>()
143
- private nextDialog = 1
144
172
  readonly contextMenus = new Map<number, ContextMenuRequest>()
145
- private nextContextMenu = 1
146
- private nextMessageDialog = 1
147
173
  readonly dropTargets = new Map<number, DropTargetRegistration>()
148
- private nextDropTarget = 1
174
+ /** Every identity space this session allocates from. */
175
+ readonly ids = {
176
+ window: new Identities('Native window'),
177
+ node: new Identities('Native node'),
178
+ shortcut: new Identities('Global shortcut'),
179
+ notification: new Identities('Notification'),
180
+ fileGrant: new Identities('File grant'),
181
+ process: new Identities('Process'),
182
+ dialog: new Identities('File dialog'),
183
+ contextMenu: new Identities('Context menu'),
184
+ messageDialog: new Identities('Message dialog'),
185
+ dropTarget: new Identities('Drop target'),
186
+ menuBar: new Identities('Menu bar'),
187
+ }
149
188
  private lastDrop = 0
150
189
  /** The installed (or installing) menu bar; replaced bars are revoked. */
151
190
  private menuBar: MenuBarRegistration | undefined
152
- private nextMenuBar = 1
153
191
  private tail: Promise<void> = Promise.resolve()
154
192
  private queued = 0
155
193
  private readonly services = new Set<Promise<void>>()
156
194
  private callbacks: Callback[] = []
157
195
  private dispatching: Promise<void> | undefined
158
196
  private activeCallbacks = 0
159
- private nextWindow = 1
160
- private nextNode = 1
197
+ /** Callbacks taken for dispatch; progress while ingestion is paused. */
198
+ private dispatched = 0
161
199
  private stopping: Promise<void> | undefined
162
200
  private failure: Error | undefined
163
201
  private phase: 'running' | 'stopping' | 'closed' = 'running'
@@ -190,93 +228,11 @@ class Application implements NativeApplication {
190
228
  })
191
229
  }
192
230
 
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
231
  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
- })
232
+ if (!this.callbacks.length) return
233
+ this.callbacks = this.callbacks.filter(
234
+ (callback) => callback.windowId !== windowId || callback.retain()
235
+ )
280
236
  }
281
237
 
282
238
  queueCallback(callback: Callback): void {
@@ -287,6 +243,20 @@ class Application implements NativeApplication {
287
243
  this.startDispatch()
288
244
  }
289
245
 
246
+ /**
247
+ * A burst can outpace dispatch while every listener is finishing. Over the
248
+ * cap, ingestion pauses for macrotask turns while callbacks complete, and
249
+ * fails only a turn in which none did: a stalled listener.
250
+ */
251
+ private async drainCallbacks(): Promise<void> {
252
+ while (this.callbacks.length >= MAX_QUEUED_CALLBACKS) {
253
+ const dispatched = this.dispatched
254
+ await new Promise<void>((resolve) => setImmediate(resolve))
255
+ if (this.dispatched === dispatched)
256
+ throw new ProtocolError('Application callback queue limit exceeded')
257
+ }
258
+ }
259
+
290
260
  /** Record the first failure and end the application with it. */
291
261
  async fail(cause: unknown): Promise<void> {
292
262
  this.failure ??= cause instanceof Error ? cause : new Error(String(cause))
@@ -307,27 +277,11 @@ class Application implements NativeApplication {
307
277
  private async dispatchCallbacks(): Promise<void> {
308
278
  while (this.callbacks.length) {
309
279
  const callback = this.callbacks.shift()!
310
- const window = 'menuBar' in callback ? undefined : this.windows.get(callback.windowId)
311
- if (!window && !('menuBar' in callback)) continue
280
+ this.dispatched += 1
281
+ if (callback.windowId !== undefined && !this.windows.has(callback.windowId)) continue
312
282
  this.activeCallbacks = 1
313
283
  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)
284
+ await callback.run()
331
285
  } finally {
332
286
  this.activeCallbacks = 0
333
287
  }
@@ -370,9 +324,7 @@ class Application implements NativeApplication {
370
324
  return this.enqueue(async () => {
371
325
  if (this.windows.size >= this.limits.max_windows)
372
326
  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())
327
+ const window = new Window(this, this.ids.window.allocate(), this.ids.node.allocate())
376
328
  this.windows.set(window.id, window)
377
329
  try {
378
330
  await this.host.send({
@@ -456,7 +408,7 @@ class Application implements NativeApplication {
456
408
  if (typeof listener !== 'function')
457
409
  throw new TypeError('A menu bar listener must be a function')
458
410
  this.checkMenuBar()
459
- const registration = new MenuBarRegistration(this.allocateMenuBar(), listener, (item) =>
411
+ const registration = new MenuBarRegistration(this.ids.menuBar.allocate(), listener, (item) =>
460
412
  item === this.menuBar ? this.clearMenuBar() : Promise.resolve()
461
413
  )
462
414
  // Revoked at submission: no selection of the old bar is delivered after this call.
@@ -474,7 +426,7 @@ class Application implements NativeApplication {
474
426
 
475
427
  async clearMenuBar(): Promise<void> {
476
428
  this.checkMenuBar()
477
- const id = this.allocateMenuBar()
429
+ const id = this.ids.menuBar.allocate()
478
430
  this.menuBar?.revoke()
479
431
  this.menuBar = undefined
480
432
  await this.sendMenuBar(id, [])
@@ -498,12 +450,6 @@ class Application implements NativeApplication {
498
450
  )
499
451
  }
500
452
 
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
453
  private async sendMenuBar(id: number, menus: ReturnType<typeof menuBarRequest>): Promise<void> {
508
454
  try {
509
455
  await this.service(() => this.host.send({ type: 'set_app_menu', menu_id: id, menus }))
@@ -512,72 +458,70 @@ class Application implements NativeApplication {
512
458
  this.menuBar.revoke()
513
459
  this.menuBar = undefined
514
460
  }
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
461
+ throw serviceError('app_menu', MENU_ERRORS, error)
525
462
  }
526
463
  }
527
464
 
528
465
  private receiveMenuItem(event: ApplicationEvent): void {
529
466
  if (!this.capabilities.includes('app_menu_v1'))
530
467
  throw new ProtocolError('Native menu selection arrived without app_menu_v1')
531
- if (event.menu_id >= this.nextMenuBar)
468
+ if (!this.ids.menuBar.has(event.menu_id))
532
469
  throw new ProtocolError('Native event names an unallocated menu bar')
533
470
  const registration = this.menuBar
534
471
  // A replaced or cleared bar's selection is stale and never delivered.
535
472
  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
- })
473
+ this.queueCallback(
474
+ listenerCallback(
475
+ undefined,
476
+ registration,
477
+ Object.freeze({
478
+ type: 'app_menu_item' as const,
479
+ sequence: event.sequence,
480
+ itemId: event.item_id,
481
+ menuBar: registration.handle,
482
+ signal: registration.controller.signal,
483
+ })
484
+ )
485
+ )
486
+ }
487
+
488
+ /** The service identity a native event names, checked before routing. */
489
+ private ownedIdentity(event: HostEvent): [Identities, number, string] | undefined {
490
+ switch (event.type) {
491
+ case 'global_shortcut':
492
+ return [this.ids.shortcut, event.shortcut_id, 'global shortcut']
493
+ case 'notification_activated':
494
+ case 'notification_dismissed':
495
+ return [this.ids.notification, event.notification_id, 'notification']
496
+ case 'process_output':
497
+ case 'process_exited':
498
+ return [this.ids.process, event.process_id, 'process']
499
+ case 'file_dialog_completed':
500
+ return [this.ids.dialog, event.dialog_id, 'file dialog']
501
+ case 'message_dialog_completed':
502
+ return [this.ids.messageDialog, event.dialog_id, 'message dialog']
503
+ case 'context_menu_completed':
504
+ return [this.ids.contextMenu, event.menu_id, 'context menu']
505
+ case 'drop_target_drag':
506
+ case 'drop_received':
507
+ case 'drop_rejected':
508
+ return [this.ids.dropTarget, event.target_id, 'drop target']
509
+ default:
510
+ return undefined
511
+ }
546
512
  }
547
513
 
548
514
  private async consume(): Promise<void> {
549
515
  try {
550
516
  for await (const event of this.host) {
517
+ if (this.callbacks.length >= MAX_QUEUED_CALLBACKS) await this.drainCallbacks()
551
518
  if (event.type === 'app_menu_item') {
552
519
  this.receiveMenuItem(event)
553
520
  continue
554
521
  }
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')
522
+ const owned = this.ownedIdentity(event)
523
+ if (owned && !owned[0].has(owned[1]))
524
+ throw new ProtocolError('Native event names an unallocated ' + owned[2])
581
525
  if (event.type === 'drop_received') {
582
526
  if (event.drop_id <= this.lastDrop)
583
527
  throw new ProtocolError('Native drop identities must increase')
@@ -585,11 +529,11 @@ class Application implements NativeApplication {
585
529
  }
586
530
  const window = this.windows.get(event.window_id)
587
531
  if (!window) {
588
- if (event.window_id >= this.nextWindow)
532
+ if (!this.ids.window.has(event.window_id))
589
533
  throw new ProtocolError('Native event names an unallocated window')
590
534
  continue // Revoked window: late events must not retain or invoke callbacks.
591
535
  }
592
- window.receive(event, this.nextNode)
536
+ window.receive(event, this.ids.node.next)
593
537
  }
594
538
  } catch (cause) {
595
539
  this.failure ??= cause instanceof Error ? cause : new Error(String(cause))
@@ -606,10 +550,7 @@ class Application implements NativeApplication {
606
550
  }
607
551
  }
608
552
 
609
- async function dispatchShortcut(
610
- registration: ShortcutRegistration,
611
- event: GlobalShortcutEvent
612
- ): Promise<void> {
553
+ async function deliver<T>(registration: Delivery<T>, event: T): Promise<void> {
613
554
  const listener = registration.listener
614
555
  if (!listener || !registration.live) return
615
556
  await dispatchOwned(listener, event, registration.controller.signal)
@@ -629,15 +570,6 @@ async function dispatchNotification(
629
570
  }
630
571
  }
631
572
 
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
573
  async function dispatchOwned<T>(
642
574
  listener: (event: T) => void | Promise<void>,
643
575
  event: T,
@@ -657,79 +589,40 @@ async function dispatchOwned<T>(
657
589
  }
658
590
  }
659
591
 
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
592
+ /** A host-owned file dialog or context menu awaiting its result. */
593
+ interface PendingRequest {
594
+ readonly id: number
595
+ readonly windowId: number
596
+ readonly live: boolean
597
+ readonly result: Promise<unknown>
598
+ fail(error: Error): void
599
+ }
600
+
601
+ /** A native command error with one of `codes` as `service`'s public error; any other error unchanged. */
602
+ function serviceError(
603
+ service: NativeServiceError['service'],
604
+ codes: ReadonlySet<string>,
605
+ error: unknown
606
+ ): unknown {
607
+ return error instanceof NativeCommandError && codes.has(error.code)
608
+ ? new NativeServiceError(service, error.code as NativeServiceError['code'], error.message)
609
+ : error
610
+ }
611
+
612
+ // Native error codes each service reports as its own NativeServiceError.
613
+ const SERVICE = ['permission_denied', 'service_unavailable'] as const
614
+ const REQUEST = [...SERVICE, 'cancelled', 'native_failure', 'limit_exceeded'] as const
615
+ const DISPLAY_ERRORS: ReadonlySet<string> = new Set(SERVICE)
616
+ const MENU_ERRORS: ReadonlySet<string> = new Set(REQUEST)
617
+ const DIALOG_ERRORS: ReadonlySet<string> = new Set([...REQUEST, 'operation_timed_out'])
618
+ const NOTIFICATION_ERRORS = DIALOG_ERRORS
619
+ const SHORTCUT_ERRORS: ReadonlySet<string> = new Set([...DIALOG_ERRORS, 'conflict'])
620
+ const CLIPBOARD_ERRORS: ReadonlySet<string> = new Set([...DIALOG_ERRORS, 'payload_too_large'])
621
+ const PATH_ERRORS = [...REQUEST, 'not_found', 'path_denied'] as const
622
+ const DROP_ERRORS: ReadonlySet<string> = new Set([...PATH_ERRORS, 'conflict'])
623
+ const ACCESS_ERRORS = [...PATH_ERRORS, 'wrong_kind', 'access_denied'] as const
624
+ const PROCESS_ERRORS: ReadonlySet<string> = new Set([...ACCESS_ERRORS, 'invalid_state'])
625
+ const FILE_ERRORS: ReadonlySet<string> = new Set([...ACCESS_ERRORS, 'already_exists', 'not_empty'])
733
626
 
734
627
  class Window implements NativeWindow {
735
628
  readonly root: NativeNode<'box'>
@@ -770,7 +663,7 @@ class Window implements NativeWindow {
770
663
  const transaction = new Transaction(
771
664
  this.nodes,
772
665
  this.rootId,
773
- () => this.application.allocateNode(),
666
+ () => this.application.ids.node.allocate(),
774
667
  this.application.limits,
775
668
  this.application.capabilities,
776
669
  this.text
@@ -793,45 +686,24 @@ class Window implements NativeWindow {
793
686
  transaction.finish()
794
687
  }
795
688
  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
- })
689
+ // One transaction is one native batch: the host applies it atomically.
690
+ const reply = await this.application.host.send({
691
+ type: 'batch',
692
+ window_id: this.id,
693
+ base_revision: this.revision,
694
+ operations: transaction.operations,
695
+ })
803
696
  // 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
697
+ this.assertActive()
698
+ transaction.commit(this.nodes, this.text)
699
+ this.revision = reply.tree_revision
700
+ this.listeners.forget(transaction.nodes.deletes)
701
+ // The host revokes a target whose node a committed tree removed.
702
+ for (const registration of this.application.dropTargets.values())
703
+ if (registration.windowId === this.id && !this.nodes.has(registration.nodeId)) {
704
+ registration.revoke()
705
+ this.application.dropTargets.delete(registration.id)
833
706
  }
834
- })
835
707
  return value
836
708
  })
837
709
  }
@@ -895,12 +767,7 @@ class Window implements NativeWindow {
895
767
  if (error instanceof ProtocolError) throw error
896
768
  this.assertActive()
897
769
  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
770
+ throw serviceError('window_display', DISPLAY_ERRORS, error)
904
771
  }
905
772
  })
906
773
  }
@@ -935,17 +802,22 @@ class Window implements NativeWindow {
935
802
  // Validate even when nobody listens: a malformed frame is a host fault.
936
803
  const snapshot = publicDisplaySnapshot(event.snapshot, this.application.capabilities)
937
804
  if (!this.active) return
938
- for (const subscription of this.displayChanges)
805
+ for (const subscription of this.displayChanges) {
806
+ const change: DisplayChangeEvent = Object.freeze({
807
+ type: 'display_change',
808
+ sequence: event.sequence,
809
+ snapshot,
810
+ signal: subscription.controller.signal,
811
+ })
939
812
  this.application.queueCallback({
940
813
  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
- }),
814
+ retain: () => subscription.live,
815
+ run: async () => {
816
+ const listener = subscription.current
817
+ if (listener) await dispatchOwned(listener, change, subscription.controller.signal)
818
+ },
948
819
  })
820
+ }
949
821
  }
950
822
 
951
823
  private revokeDisplayChanges(): void {
@@ -990,24 +862,7 @@ class Window implements NativeWindow {
990
862
  if (error instanceof ProtocolError) throw error
991
863
  this.assertActive()
992
864
  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
865
+ throw serviceError(service, CLIPBOARD_ERRORS, error)
1011
866
  }
1012
867
  })
1013
868
  }
@@ -1020,18 +875,20 @@ class Window implements NativeWindow {
1020
875
  if (typeof listener !== 'function')
1021
876
  throw new TypeError('A global shortcut listener must be a function')
1022
877
  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 {
878
+ return this.register(
879
+ 'global_shortcuts',
880
+ SHORTCUT_ERRORS,
881
+ this.application.shortcuts,
882
+ () =>
883
+ new ShortcutRegistration(
884
+ this.application.ids.shortcut.allocate(),
885
+ this.id,
886
+ key,
887
+ modifiers,
888
+ listener,
889
+ (item) => this.releaseShortcut(item)
890
+ ),
891
+ async (registration) => {
1035
892
  await this.application.host.send({
1036
893
  type: 'register_global_shortcut',
1037
894
  window_id: this.id,
@@ -1039,56 +896,21 @@ class Window implements NativeWindow {
1039
896
  key,
1040
897
  modifiers,
1041
898
  })
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
- })
899
+ },
900
+ (registration) => registration.live,
901
+ 'Global shortcut was revoked during registration'
902
+ )
1067
903
  }
1068
904
 
1069
905
  private releaseShortcut(registration: ShortcutRegistration): Promise<void> {
1070
906
  // Local revocation first: no activation is delivered after this call.
1071
907
  registration.revoke()
1072
908
  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
- )
909
+ return this.releaseNative({
910
+ type: 'unregister_global_shortcut',
911
+ window_id: this.id,
912
+ shortcut_id: registration.id,
913
+ })
1092
914
  }
1093
915
 
1094
916
  async postNotification(
@@ -1099,18 +921,20 @@ class Window implements NativeWindow {
1099
921
  if (typeof listener !== 'function')
1100
922
  throw new TypeError('A notification listener must be a function')
1101
923
  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 {
924
+ return this.register(
925
+ 'notifications',
926
+ NOTIFICATION_ERRORS,
927
+ this.application.notifications,
928
+ () =>
929
+ new NotificationRegistration(
930
+ this.application.ids.notification.allocate(),
931
+ this.id,
932
+ title,
933
+ body,
934
+ listener,
935
+ (item) => this.withdrawNotification(item)
936
+ ),
937
+ async (registration) => {
1114
938
  const posted = await this.application.host.send({
1115
939
  type: 'post_notification',
1116
940
  window_id: this.id,
@@ -1119,48 +943,29 @@ class Window implements NativeWindow {
1119
943
  body,
1120
944
  })
1121
945
  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
- })
946
+ },
947
+ (registration) => registration.deliverable,
948
+ 'Notification was revoked while it was posted'
949
+ )
1147
950
  }
1148
951
 
1149
952
  async openFileGrant(root: string, options: FileGrantOptions = {}): Promise<NativeFileGrant> {
1150
953
  const request = fileGrantRequest(root, options)
1151
954
  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 {
955
+ return this.register(
956
+ 'filesystem_grants',
957
+ FILE_ERRORS,
958
+ this.application.fileGrants,
959
+ () =>
960
+ new FileGrantRegistration(
961
+ this.application.ids.fileGrant.allocate(),
962
+ this.id,
963
+ request.root,
964
+ request.access,
965
+ (item, call) => this.fileCall(item, call),
966
+ (item) => this.closeFileGrant(item)
967
+ ),
968
+ async (registration) => {
1164
969
  await this.application.host.send({
1165
970
  type: 'open_file_grant',
1166
971
  window_id: this.id,
@@ -1168,35 +973,10 @@ class Window implements NativeWindow {
1168
973
  root: request.root,
1169
974
  access: request.access,
1170
975
  })
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)
976
+ },
977
+ (registration) => registration.live,
978
+ 'File grant was revoked while it opened'
1193
979
  )
1194
- return new NativeServiceError(
1195
- 'filesystem_grants',
1196
- error.code as NativeServiceError['code'],
1197
- error.message
1198
- )
1199
- return error
1200
980
  }
1201
981
 
1202
982
  private fileCall(registration: FileGrantRegistration, call: FileCall): Promise<unknown> {
@@ -1227,7 +1007,7 @@ class Window implements NativeWindow {
1227
1007
  if (error instanceof ProtocolError) throw error
1228
1008
  if (!registration.live) throw revoked()
1229
1009
  this.assertActive()
1230
- throw this.fileError(error)
1010
+ throw this.serviceFailure('filesystem_grants', FILE_ERRORS, error)
1231
1011
  }
1232
1012
  })
1233
1013
  }
@@ -1235,20 +1015,11 @@ class Window implements NativeWindow {
1235
1015
  private closeFileGrant(registration: FileGrantRegistration): Promise<void> {
1236
1016
  registration.revoke()
1237
1017
  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
- )
1018
+ return this.releaseNative({
1019
+ type: 'close_file_grant',
1020
+ window_id: this.id,
1021
+ grant_id: registration.id,
1022
+ })
1252
1023
  }
1253
1024
 
1254
1025
  async spawnProcess(
@@ -1268,54 +1039,31 @@ class Window implements NativeWindow {
1268
1039
  throw new TypeError('Process cwd must name a live file grant owned by this window')
1269
1040
  cwd = { grant_id: grant.id, path: request.cwd.path }
1270
1041
  }
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 {
1042
+ return this.register(
1043
+ 'processes',
1044
+ PROCESS_ERRORS,
1045
+ this.application.processes,
1046
+ () =>
1047
+ new ProcessRegistration(
1048
+ this.application.ids.process.allocate(),
1049
+ this.id,
1050
+ request.launch.executable,
1051
+ request.launch.terminal !== undefined,
1052
+ listener,
1053
+ (item, call) => this.processCall(item, call),
1054
+ (item) => this.releaseProcess(item)
1055
+ ),
1056
+ async (registration) => {
1284
1057
  await this.application.host.send({
1285
1058
  type: 'spawn_process',
1286
1059
  window_id: this.id,
1287
1060
  process_id: registration.id,
1288
1061
  launch: cwd ? { ...request.launch, cwd } : request.launch,
1289
1062
  })
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)
1063
+ },
1064
+ (registration) => registration.live,
1065
+ 'Process was released while it started'
1312
1066
  )
1313
- return new NativeServiceError(
1314
- 'processes',
1315
- error.code as NativeServiceError['code'],
1316
- error.message
1317
- )
1318
- return error
1319
1067
  }
1320
1068
 
1321
1069
  private processCall(registration: ProcessRegistration, call: ProcessCall): Promise<void> {
@@ -1335,7 +1083,7 @@ class Window implements NativeWindow {
1335
1083
  if (error instanceof ProtocolError) throw error
1336
1084
  if (!registration.live) throw revoked()
1337
1085
  this.assertActive()
1338
- throw this.processError(error)
1086
+ throw this.serviceFailure('processes', PROCESS_ERRORS, error)
1339
1087
  }
1340
1088
  })
1341
1089
  }
@@ -1343,20 +1091,11 @@ class Window implements NativeWindow {
1343
1091
  private releaseProcess(registration: ProcessRegistration): Promise<void> {
1344
1092
  registration.revoke()
1345
1093
  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
- )
1094
+ return this.releaseNative({
1095
+ type: 'release_process',
1096
+ window_id: this.id,
1097
+ process_id: registration.id,
1098
+ })
1360
1099
  }
1361
1100
 
1362
1101
  receiveProcess(event: Extract<WindowEvent, { type: 'process_output' | 'process_exited' }>): void {
@@ -1377,26 +1116,31 @@ class Window implements NativeWindow {
1377
1116
  if ((event.stream === 'terminal') !== registration.handle.terminal)
1378
1117
  throw new ProtocolError('Native process output names the wrong stream kind')
1379
1118
  registration.chunk = event.chunk
1119
+ const output: ProcessEvent = Object.freeze({
1120
+ type: 'process_output',
1121
+ stream: event.stream,
1122
+ bytes: Uint8Array.fromBase64(event.data),
1123
+ ...common,
1124
+ })
1125
+ const chunk = event.chunk
1380
1126
  this.application.queueCallback({
1381
1127
  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
- }),
1128
+ retain: () => registration.live,
1129
+ run: () => this.dispatchProcess(registration, output, chunk),
1390
1130
  })
1391
1131
  return
1392
1132
  }
1393
1133
  registration.end()
1394
1134
  registration.exit = Object.freeze({ ...event.exit })
1135
+ const exited: ProcessEvent = Object.freeze({
1136
+ type: 'process_exited',
1137
+ exit: registration.exit,
1138
+ ...common,
1139
+ })
1395
1140
  this.application.queueCallback({
1396
1141
  windowId: this.id,
1397
- process: registration,
1398
- chunk: 0,
1399
- event: Object.freeze({ type: 'process_exited', exit: registration.exit, ...common }),
1142
+ retain: () => registration.live,
1143
+ run: () => this.dispatchProcess(registration, exited, 0),
1400
1144
  })
1401
1145
  }
1402
1146
 
@@ -1426,9 +1170,12 @@ class Window implements NativeWindow {
1426
1170
  (error: unknown) => {
1427
1171
  // Release or window close can race the acknowledgement.
1428
1172
  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
1173
+ // Shutdown or a lost transport already owns the outcome, reported
1174
+ // through the application's closed promise; recording it here first
1175
+ // would hide the original cause. A rejection while the host still
1176
+ // runs (the runtime's own command limit) would otherwise lose the
1177
+ // credit silently.
1178
+ if (!this.application.running || !this.application.host.running) return
1432
1179
  // Not awaited: shutdown waits for this tracked operation.
1433
1180
  void this.application.fail(error)
1434
1181
  }
@@ -1444,82 +1191,54 @@ class Window implements NativeWindow {
1444
1191
  throw new TypeError('A drop target listener must be a function')
1445
1192
  this.assertActive()
1446
1193
  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
- })
1194
+ return this.register(
1195
+ 'drag_drop',
1196
+ DROP_ERRORS,
1197
+ this.application.dropTargets,
1198
+ () => {
1199
+ if (this.nodes.get(node.id)?.handle !== node.handle)
1200
+ throw new NativeStateError('invalid_handle', 'Drop target node was removed')
1201
+ return new DropTargetRegistration(
1202
+ this.application.ids.dropTarget.allocate(),
1203
+ this.id,
1204
+ node.id,
1205
+ node.handle,
1206
+ listener,
1207
+ (item) => this.releaseDropTarget(item)
1208
+ )
1209
+ },
1210
+ async (registration) => {
1211
+ try {
1212
+ await this.application.host.send({
1213
+ type: 'register_drop_target',
1214
+ window_id: this.id,
1215
+ target_id: registration.id,
1216
+ node_id: node.id,
1217
+ })
1218
+ } catch (error) {
1219
+ if (error instanceof NativeCommandError && error.code === 'invalid_handle' && this.active)
1220
+ throw new NativeStateError('invalid_handle', 'Drop target node is not committed')
1221
+ throw error
1222
+ }
1223
+ },
1224
+ (registration) => registration.live,
1225
+ 'Drop target was revoked during registration'
1226
+ )
1485
1227
  }
1486
1228
 
1487
1229
  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
1230
+ return serviceError('drag_drop', DROP_ERRORS, error)
1498
1231
  }
1499
1232
 
1500
1233
  private releaseDropTarget(registration: DropTargetRegistration): Promise<void> {
1501
1234
  // Local revocation first: no drag or drop is delivered after this call.
1502
1235
  registration.revoke()
1503
1236
  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
- )
1237
+ return this.releaseNative({
1238
+ type: 'unregister_drop_target',
1239
+ window_id: this.id,
1240
+ target_id: registration.id,
1241
+ })
1523
1242
  }
1524
1243
 
1525
1244
  private resolveDroppedItem(
@@ -1599,36 +1318,20 @@ class Window implements NativeWindow {
1599
1318
  )
1600
1319
  delivered = { type: 'drop', items: Object.freeze(items), ...common }
1601
1320
  }
1602
- this.application.queueCallback({
1603
- windowId: this.id,
1604
- dropTarget: registration,
1605
- event: Object.freeze(delivered),
1606
- })
1321
+ this.application.queueCallback(
1322
+ listenerCallback(this.id, registration, Object.freeze(delivered))
1323
+ )
1607
1324
  }
1608
1325
 
1609
1326
  private withdrawNotification(registration: NotificationRegistration): Promise<void> {
1610
1327
  // Local revocation first: no activation is delivered after this call.
1611
1328
  registration.revoke()
1612
1329
  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
- )
1330
+ return this.releaseNative({
1331
+ type: 'withdraw_notification',
1332
+ window_id: this.id,
1333
+ notification_id: registration.id,
1334
+ })
1632
1335
  }
1633
1336
 
1634
1337
  receiveNotification(
@@ -1648,14 +1351,15 @@ class Window implements NativeWindow {
1648
1351
  registration.end()
1649
1352
  this.application.notifications.delete(registration.id)
1650
1353
  }
1354
+ const delivered: NotificationEvent = Object.freeze(
1355
+ event.type === 'notification_activated'
1356
+ ? { type: 'notification_activated', ...common }
1357
+ : { type: 'notification_dismissed', reason: event.reason, ...common }
1358
+ )
1651
1359
  this.application.queueCallback({
1652
1360
  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
- ),
1361
+ retain: () => registration.deliverable,
1362
+ run: () => dispatchNotification(registration, delivered),
1659
1363
  })
1660
1364
  }
1661
1365
 
@@ -1681,56 +1385,34 @@ class Window implements NativeWindow {
1681
1385
  : Object.freeze({ kind: 'cancelled' })
1682
1386
  }
1683
1387
 
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({
1388
+ private fileDialog(options: FileDialogOptions, signal: AbortSignal | undefined) {
1389
+ return this.openPending(
1390
+ 'file_dialogs',
1391
+ signal,
1392
+ this.application.dialogs,
1393
+ (other) => other.windowId === this.id,
1394
+ 'This window already has an open file dialog',
1395
+ () => new FileDialogRequest(this.application.ids.dialog.allocate(), this.id, options.mode),
1396
+ (dialog) =>
1397
+ this.application.host.send({
1701
1398
  type: 'show_file_dialog',
1702
1399
  window_id: this.id,
1703
1400
  dialog_id: dialog.id,
1704
1401
  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)
1402
+ }),
1403
+ (dialog) =>
1404
+ this.cancelPending(
1405
+ 'file_dialogs',
1406
+ this.application.dialogs,
1407
+ dialog,
1408
+ 'The file dialog was cancelled',
1409
+ {
1410
+ type: 'close_file_dialog',
1411
+ window_id: this.id,
1412
+ dialog_id: dialog.id,
1413
+ }
1716
1414
  )
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
- }
1415
+ )
1734
1416
  }
1735
1417
 
1736
1418
  async showContextMenu(
@@ -1741,85 +1423,38 @@ class Window implements NativeWindow {
1741
1423
  const wire = contextMenuRequest(items, position)
1742
1424
  if (!this.application.capabilities.includes('context_menus_v1'))
1743
1425
  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({
1426
+ return this.openPending(
1427
+ 'context_menus',
1428
+ serviceSignal(request),
1429
+ this.application.contextMenus,
1430
+ (other) => other.live,
1431
+ 'Another context menu is already open',
1432
+ () =>
1433
+ new ContextMenuRequest(
1434
+ this.application.ids.contextMenu.allocate(),
1435
+ this.id,
1436
+ itemIds(wire.items)
1437
+ ),
1438
+ (menu) =>
1439
+ this.application.host.send({
1765
1440
  type: 'show_context_menu',
1766
1441
  window_id: this.id,
1767
1442
  menu_id: menu.id,
1768
1443
  ...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)
1444
+ }),
1445
+ (menu) =>
1446
+ this.cancelPending(
1447
+ 'context_menus',
1448
+ this.application.contextMenus,
1449
+ menu,
1450
+ 'The context menu was cancelled',
1451
+ {
1452
+ type: 'close_context_menu',
1453
+ window_id: this.id,
1454
+ menu_id: menu.id,
1455
+ }
1780
1456
  )
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
1457
  )
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
1458
  }
1824
1459
 
1825
1460
  receiveContextMenu(event: Extract<WindowEvent, { type: 'context_menu_completed' }>): void {
@@ -1853,7 +1488,7 @@ class Window implements NativeWindow {
1853
1488
  if (capability.availability !== 'available' || capability.backend === 'modal_overlay')
1854
1489
  return undefined
1855
1490
  return {
1856
- allocate: () => this.application.allocateMessageDialog(),
1491
+ allocate: () => this.application.ids.messageDialog.allocate(),
1857
1492
  show: async (id, options) => {
1858
1493
  try {
1859
1494
  await this.application.service(() =>
@@ -1865,34 +1500,11 @@ class Window implements NativeWindow {
1865
1500
  })
1866
1501
  )
1867
1502
  } 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
1503
+ throw serviceError('message_dialogs', DIALOG_ERRORS, error)
1894
1504
  }
1895
1505
  },
1506
+ close: (id) =>
1507
+ this.releaseNative({ type: 'close_message_dialog', window_id: this.id, dialog_id: id }),
1896
1508
  }
1897
1509
  }
1898
1510
 
@@ -1911,32 +1523,6 @@ class Window implements NativeWindow {
1911
1523
  return this.messages.show(spec, signal)
1912
1524
  }
1913
1525
 
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
1526
  receiveFileDialog(event: Extract<WindowEvent, { type: 'file_dialog_completed' }>): void {
1941
1527
  if (!this.active) return
1942
1528
  const dialog = this.application.dialogs.get(event.dialog_id)
@@ -1953,18 +1539,137 @@ class Window implements NativeWindow {
1953
1539
  if (!registration) return // Released: the host may already have queued a press.
1954
1540
  if (registration.windowId !== this.id)
1955
1541
  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
- }),
1542
+ this.application.queueCallback(
1543
+ listenerCallback(
1544
+ this.id,
1545
+ registration,
1546
+ Object.freeze({
1547
+ type: 'global_shortcut' as const,
1548
+ sequence: event.sequence,
1549
+ shortcut: registration.handle,
1550
+ signal: registration.controller.signal,
1551
+ })
1552
+ )
1553
+ )
1554
+ }
1555
+
1556
+ /** A failed service request's public error: protocol faults and a closed owner first. */
1557
+ private serviceFailure(
1558
+ service: NativeServiceError['service'],
1559
+ codes: ReadonlySet<string>,
1560
+ error: unknown
1561
+ ): unknown {
1562
+ if (error instanceof ProtocolError) return error
1563
+ this.assertActive()
1564
+ return serviceError(service, codes, error)
1565
+ }
1566
+
1567
+ /**
1568
+ * Allocate, record and natively register one service handle. A failure, or
1569
+ * a revocation while the host registered it, forgets the record again.
1570
+ */
1571
+ private register<R extends { readonly id: number; readonly handle: unknown; revoke(): void }>(
1572
+ service: NativeServiceError['service'],
1573
+ codes: ReadonlySet<string>,
1574
+ registrations: Map<number, R>,
1575
+ create: () => R,
1576
+ send: (registration: R) => Promise<void>,
1577
+ accepted: (registration: R) => boolean,
1578
+ revoked: string
1579
+ ): Promise<R['handle']> {
1580
+ return this.application.service(async () => {
1581
+ this.assertActive()
1582
+ const registration = create()
1583
+ registrations.set(registration.id, registration)
1584
+ try {
1585
+ await send(registration)
1586
+ this.assertActive()
1587
+ if (!accepted(registration)) throw new NativeServiceError(service, 'cancelled', revoked)
1588
+ return registration.handle
1589
+ } catch (error) {
1590
+ registration.revoke()
1591
+ registrations.delete(registration.id)
1592
+ throw this.serviceFailure(service, codes, error)
1593
+ }
1965
1594
  })
1966
1595
  }
1967
1596
 
1597
+ /**
1598
+ * Natively release a handle already revoked locally. Window close and
1599
+ * application shutdown release it natively instead, and the owner can end
1600
+ * it while the request is in flight (`invalid_handle`).
1601
+ */
1602
+ private releaseNative(command: WindowCommand): Promise<void> {
1603
+ if (!this.active || !this.application.running) return Promise.resolve()
1604
+ return this.application.track(
1605
+ this.application.host.send(command).then(
1606
+ () => {},
1607
+ (error: unknown) => {
1608
+ if (error instanceof NativeCommandError && error.code === 'invalid_handle') return
1609
+ if (!this.application.running) return
1610
+ throw error
1611
+ }
1612
+ )
1613
+ )
1614
+ }
1615
+
1616
+ /**
1617
+ * Show one host-owned dialog or menu and wait for its result. An abort
1618
+ * while the host was showing it closes the now-live request.
1619
+ */
1620
+ private async openPending<P extends PendingRequest>(
1621
+ service: 'file_dialogs' | 'context_menus',
1622
+ signal: AbortSignal | undefined,
1623
+ pending: Map<number, P>,
1624
+ busy: (other: P) => boolean,
1625
+ busyMessage: string,
1626
+ create: () => P,
1627
+ send: (request: P) => Promise<unknown>,
1628
+ cancel: (request: P) => void
1629
+ ): Promise<Awaited<P['result']>> {
1630
+ this.assertActive()
1631
+ checkServiceCancellation(signal, service)
1632
+ const request = await this.application.service(async () => {
1633
+ this.assertActive()
1634
+ checkServiceCancellation(signal, service)
1635
+ for (const other of pending.values())
1636
+ if (busy(other)) throw new NativeServiceError(service, 'limit_exceeded', busyMessage)
1637
+ const request = create()
1638
+ pending.set(request.id, request)
1639
+ try {
1640
+ await send(request)
1641
+ this.assertActive()
1642
+ return request
1643
+ } catch (error) {
1644
+ request.fail(error instanceof Error ? error : new Error(String(error)))
1645
+ pending.delete(request.id)
1646
+ throw this.serviceFailure(service, DIALOG_ERRORS, error)
1647
+ }
1648
+ })
1649
+ const abort = () => cancel(request)
1650
+ if (signal?.aborted) abort()
1651
+ else signal?.addEventListener('abort', abort, { once: true })
1652
+ try {
1653
+ return (await request.result) as Awaited<P['result']>
1654
+ } finally {
1655
+ signal?.removeEventListener('abort', abort)
1656
+ }
1657
+ }
1658
+
1659
+ /** Delivery stops at once; the OS dialog or menu is then closed natively. */
1660
+ private cancelPending<P extends PendingRequest>(
1661
+ service: 'file_dialogs' | 'context_menus',
1662
+ pending: Map<number, P>,
1663
+ request: P,
1664
+ message: string,
1665
+ command: WindowCommand
1666
+ ): void {
1667
+ if (!request.live) return
1668
+ request.fail(new NativeServiceError(service, 'cancelled', message))
1669
+ pending.delete(request.id)
1670
+ void this.releaseNative(command).catch(() => {})
1671
+ }
1672
+
1968
1673
  async close(): Promise<void> {
1969
1674
  if (!this.active) {
1970
1675
  await this.closing
@@ -1998,31 +1703,13 @@ class Window implements NativeWindow {
1998
1703
  * `cancelled`, not as `invalid_handle` after the host acknowledges the close.
1999
1704
  */
2000
1705
  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
- }
1706
+ const { shortcuts, notifications, fileGrants, processes, dropTargets } = this.application
1707
+ for (const registrations of [shortcuts, notifications, fileGrants, processes, dropTargets])
1708
+ for (const registration of registrations.values())
1709
+ if (registration.windowId === this.id) {
1710
+ registration.revoke()
1711
+ registrations.delete(registration.id)
1712
+ }
2026
1713
  }
2027
1714
 
2028
1715
  revoke(): void {
@@ -2032,16 +1719,16 @@ class Window implements NativeWindow {
2032
1719
  this.text = new CommittedText(this.application.limits.max_text_bytes)
2033
1720
  this.revokeDisplayChanges()
2034
1721
  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
- }
1722
+ const { dialogs, contextMenus } = this.application
1723
+ for (const [pending, name] of [
1724
+ [dialogs, 'File dialog'],
1725
+ [contextMenus, 'Context menu'],
1726
+ ] as const)
1727
+ for (const request of pending.values())
1728
+ if (request.windowId === this.id) {
1729
+ request.fail(new NativeStateError('invalid_handle', name + ' owner window was closed'))
1730
+ pending.delete(request.id)
1731
+ }
2045
1732
  this.messages.revoke()
2046
1733
  this.application.windows.delete(this.id)
2047
1734
  this.resolveClosed()
@@ -2138,20 +1825,23 @@ class Window implements NativeWindow {
2138
1825
  'Native split resize targeted a non-split node or was not advertised'
2139
1826
  )
2140
1827
  }
1828
+ const route = ownedPath.map((item) => item.handle)
2141
1829
  // 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 })
1830
+ if (this.messages.receive(event, route, node.handle)) return
1831
+ const plan = this.listeners.prepare(event, route)
1832
+ if (!plan) return
1833
+ const nodeId = node.id
1834
+ this.application.queueCallback({
1835
+ windowId: this.id,
1836
+ retain: () => {
1837
+ // A callback whose target or every binding is gone is dropped.
1838
+ const window = this.application.windows.get(this.id)
1839
+ if (window?.isTargetLive(nodeId) && prunePlan(plan)) return true
1840
+ window?.listeners.release(plan)
1841
+ return false
1842
+ },
1843
+ run: () => this.dispatch(nodeId, plan),
1844
+ })
2155
1845
  }
2156
1846
 
2157
1847
  async dispatch(nodeId: number, plan: DispatchPlan): Promise<void> {