@bun-native/core 0.33.0 → 0.33.2

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,20 @@
1
1
  import {
2
+ OperationList,
2
3
  parseRootId,
3
4
  ProtocolError,
5
+ type ApplicationEvent,
4
6
  type Capability,
5
7
  type FileDialogOptions,
8
+ type HostEvent,
6
9
  type Limits,
7
- type Operation,
10
+ type WindowEvent,
8
11
  } from '@bun-native/protocol'
9
12
  import {
10
13
  NativeCommandError,
11
14
  NativeHost,
12
- type ApplicationEvent,
13
15
  type HostOptions,
14
- type WindowEvent,
16
+ type WindowCommand,
15
17
  } from '@bun-native/runtime'
16
- import { planStagedCommit, sendStagedCommit } from './commit-plan.ts'
17
18
  import { dispatchPlan, EventBindings, prunePlan, type DispatchPlan } from './events.ts'
18
19
  import { DisplaySubscription } from './display.ts'
19
20
  import {
@@ -95,6 +96,7 @@ import {
95
96
  type MessageDialogOptions,
96
97
  type MessageDialogResult,
97
98
  } from './message-dialogs.ts'
99
+ import { runBatches, type BatchEntry } from './batches.ts'
98
100
  import { CommittedText, makeNode, own, Transaction, type NodeState } from './tree.ts'
99
101
  import {
100
102
  NativeStateError,
@@ -114,15 +116,48 @@ import {
114
116
 
115
117
  const MAX_QUEUED_TRANSACTIONS = 128
116
118
  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 }
119
+ /**
120
+ * One queued application callback. `run` delivers it; `retain` decides, when
121
+ * its window cancels callbacks, whether it stays queued. Without a window it
122
+ * belongs to the application (the menu bar).
123
+ */
124
+ interface Callback {
125
+ readonly windowId?: number | undefined
126
+ retain(): boolean
127
+ run(): Promise<void>
128
+ }
129
+
130
+ /** A service registration whose listener receives its own events. */
131
+ interface Delivery<T> {
132
+ readonly live: boolean
133
+ readonly listener: Listener<T> | undefined
134
+ readonly controller: AbortController
135
+ }
136
+
137
+ function listenerCallback<T>(
138
+ windowId: number | undefined,
139
+ registration: Delivery<T>,
140
+ event: T
141
+ ): Callback {
142
+ return { windowId, retain: () => registration.live, run: () => deliver(registration, event) }
143
+ }
144
+
145
+ /** Monotonic identities of one kind: never reused, never wrapped. */
146
+ class Identities {
147
+ next = 1
148
+ constructor(private readonly kind: string) {}
149
+
150
+ allocate(): number {
151
+ if (!Number.isSafeInteger(this.next))
152
+ throw new NativeStateError('limit_exceeded', this.kind + ' identity space exhausted')
153
+ return this.next++
154
+ }
155
+
156
+ /** Whether `id` names an identity this space has already handed out. */
157
+ has(id: number): boolean {
158
+ return id < this.next
159
+ }
160
+ }
126
161
 
127
162
  class Application implements NativeApplication {
128
163
  readonly closed: Promise<void>
@@ -132,32 +167,39 @@ class Application implements NativeApplication {
132
167
  readonly serviceCapabilities: Readonly<ServiceCapabilities>
133
168
  readonly windows = new Map<number, Window>()
134
169
  readonly shortcuts = new Map<number, ShortcutRegistration>()
135
- private nextShortcut = 1
136
170
  readonly notifications = new Map<number, NotificationRegistration>()
137
- private nextNotification = 1
138
171
  readonly fileGrants = new Map<number, FileGrantRegistration>()
139
- private nextFileGrant = 1
140
172
  readonly processes = new Map<number, ProcessRegistration>()
141
- private nextProcess = 1
142
173
  readonly dialogs = new Map<number, FileDialogRequest>()
143
- private nextDialog = 1
144
174
  readonly contextMenus = new Map<number, ContextMenuRequest>()
145
- private nextContextMenu = 1
146
- private nextMessageDialog = 1
147
175
  readonly dropTargets = new Map<number, DropTargetRegistration>()
148
- private nextDropTarget = 1
176
+ /** Every identity space this session allocates from. */
177
+ readonly ids = {
178
+ window: new Identities('Native window'),
179
+ node: new Identities('Native node'),
180
+ shortcut: new Identities('Global shortcut'),
181
+ notification: new Identities('Notification'),
182
+ fileGrant: new Identities('File grant'),
183
+ process: new Identities('Process'),
184
+ dialog: new Identities('File dialog'),
185
+ contextMenu: new Identities('Context menu'),
186
+ messageDialog: new Identities('Message dialog'),
187
+ dropTarget: new Identities('Drop target'),
188
+ menuBar: new Identities('Menu bar'),
189
+ }
149
190
  private lastDrop = 0
150
191
  /** The installed (or installing) menu bar; replaced bars are revoked. */
151
192
  private menuBar: MenuBarRegistration | undefined
152
- private nextMenuBar = 1
153
193
  private tail: Promise<void> = Promise.resolve()
154
194
  private queued = 0
195
+ /** The last queued operation while it is a batch group that has not started. */
196
+ private openGroup: { window: Window; entries: BatchEntry[] } | undefined
155
197
  private readonly services = new Set<Promise<void>>()
156
198
  private callbacks: Callback[] = []
157
199
  private dispatching: Promise<void> | undefined
158
200
  private activeCallbacks = 0
159
- private nextWindow = 1
160
- private nextNode = 1
201
+ /** Callbacks taken for dispatch; progress while ingestion is paused. */
202
+ private dispatched = 0
161
203
  private stopping: Promise<void> | undefined
162
204
  private failure: Error | undefined
163
205
  private phase: 'running' | 'stopping' | 'closed' = 'running'
@@ -190,93 +232,11 @@ class Application implements NativeApplication {
190
232
  })
191
233
  }
192
234
 
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
235
  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
- })
236
+ if (!this.callbacks.length) return
237
+ this.callbacks = this.callbacks.filter(
238
+ (callback) => callback.windowId !== windowId || callback.retain()
239
+ )
280
240
  }
281
241
 
282
242
  queueCallback(callback: Callback): void {
@@ -287,6 +247,20 @@ class Application implements NativeApplication {
287
247
  this.startDispatch()
288
248
  }
289
249
 
250
+ /**
251
+ * A burst can outpace dispatch while every listener is finishing. Over the
252
+ * cap, ingestion pauses for macrotask turns while callbacks complete, and
253
+ * fails only a turn in which none did: a stalled listener.
254
+ */
255
+ private async drainCallbacks(): Promise<void> {
256
+ while (this.callbacks.length >= MAX_QUEUED_CALLBACKS) {
257
+ const dispatched = this.dispatched
258
+ await new Promise<void>((resolve) => setImmediate(resolve))
259
+ if (this.dispatched === dispatched)
260
+ throw new ProtocolError('Application callback queue limit exceeded')
261
+ }
262
+ }
263
+
290
264
  /** Record the first failure and end the application with it. */
291
265
  async fail(cause: unknown): Promise<void> {
292
266
  this.failure ??= cause instanceof Error ? cause : new Error(String(cause))
@@ -307,43 +281,70 @@ class Application implements NativeApplication {
307
281
  private async dispatchCallbacks(): Promise<void> {
308
282
  while (this.callbacks.length) {
309
283
  const callback = this.callbacks.shift()!
310
- const window = 'menuBar' in callback ? undefined : this.windows.get(callback.windowId)
311
- if (!window && !('menuBar' in callback)) continue
284
+ this.dispatched += 1
285
+ if (callback.windowId !== undefined && !this.windows.has(callback.windowId)) continue
312
286
  this.activeCallbacks = 1
313
287
  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)
288
+ await callback.run()
331
289
  } finally {
332
290
  this.activeCallbacks = 0
333
291
  }
334
292
  }
335
293
  }
336
294
 
337
- enqueue<T>(operation: () => Promise<T>, closingWindow = false): Promise<T> {
295
+ /** Why a new queued operation is refused, if it is. */
296
+ private refusal(closingWindow: boolean): Error | undefined {
338
297
  if (this.phase !== 'running')
339
- return Promise.reject(
340
- this.failure ?? new NativeStateError('invalid_state', 'Application is shutting down')
341
- )
298
+ return this.failure ?? new NativeStateError('invalid_state', 'Application is shutting down')
342
299
  // At most one close per live window may use the reserved cleanup capacity.
343
300
  if (!closingWindow && this.queued >= MAX_QUEUED_TRANSACTIONS)
344
- return Promise.reject(
345
- new NativeStateError('limit_exceeded', 'Application transaction queue is full')
346
- )
301
+ return new NativeStateError('limit_exceeded', 'Application transaction queue is full')
302
+ return undefined
303
+ }
304
+
305
+ /**
306
+ * Queue a window batch. Batches queued back to back for one window, while
307
+ * another operation is in flight, run as one group and share native batches
308
+ * (`runBatches`); each still counts against the queue limit.
309
+ */
310
+ batch<T>(window: Window, update: (batch: NativeBatch) => T): Promise<T> {
311
+ const refused = this.refusal(false)
312
+ if (refused) return Promise.reject(refused)
313
+ let entry!: BatchEntry
314
+ const result = new Promise<T>((resolve, reject) => {
315
+ entry = { update, resolve: resolve as (value: unknown) => void, reject }
316
+ })
317
+ const open = this.openGroup
318
+ if (open?.window === window) {
319
+ this.queued += 1
320
+ open.entries.push(entry)
321
+ return result
322
+ }
323
+ const group = { window, entries: [entry] }
324
+ const run = this.enqueue(() => {
325
+ if (this.openGroup === group) this.openGroup = undefined
326
+ return runBatches(window, group.entries, this.limits)
327
+ })
328
+ // The group holds one queue slot and its other entries one each. Its last
329
+ // callers settle once the queue has moved on, as a single batch's would.
330
+ run.then(
331
+ (release) => {
332
+ this.queued -= group.entries.length - 1
333
+ release()
334
+ },
335
+ (error: unknown) => {
336
+ this.queued -= group.entries.length - 1
337
+ for (const queued of group.entries) queued.reject(error)
338
+ }
339
+ )
340
+ this.openGroup = group
341
+ return result
342
+ }
343
+
344
+ enqueue<T>(operation: () => Promise<T>, closingWindow = false): Promise<T> {
345
+ const refused = this.refusal(closingWindow)
346
+ if (refused) return Promise.reject(refused)
347
+ this.openGroup = undefined
347
348
  this.queued += 1
348
349
  const result = this.tail
349
350
  .then(() => {
@@ -370,9 +371,7 @@ class Application implements NativeApplication {
370
371
  return this.enqueue(async () => {
371
372
  if (this.windows.size >= this.limits.max_windows)
372
373
  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())
374
+ const window = new Window(this, this.ids.window.allocate(), this.ids.node.allocate())
376
375
  this.windows.set(window.id, window)
377
376
  try {
378
377
  await this.host.send({
@@ -456,7 +455,7 @@ class Application implements NativeApplication {
456
455
  if (typeof listener !== 'function')
457
456
  throw new TypeError('A menu bar listener must be a function')
458
457
  this.checkMenuBar()
459
- const registration = new MenuBarRegistration(this.allocateMenuBar(), listener, (item) =>
458
+ const registration = new MenuBarRegistration(this.ids.menuBar.allocate(), listener, (item) =>
460
459
  item === this.menuBar ? this.clearMenuBar() : Promise.resolve()
461
460
  )
462
461
  // Revoked at submission: no selection of the old bar is delivered after this call.
@@ -474,7 +473,7 @@ class Application implements NativeApplication {
474
473
 
475
474
  async clearMenuBar(): Promise<void> {
476
475
  this.checkMenuBar()
477
- const id = this.allocateMenuBar()
476
+ const id = this.ids.menuBar.allocate()
478
477
  this.menuBar?.revoke()
479
478
  this.menuBar = undefined
480
479
  await this.sendMenuBar(id, [])
@@ -498,12 +497,6 @@ class Application implements NativeApplication {
498
497
  )
499
498
  }
500
499
 
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
500
  private async sendMenuBar(id: number, menus: ReturnType<typeof menuBarRequest>): Promise<void> {
508
501
  try {
509
502
  await this.service(() => this.host.send({ type: 'set_app_menu', menu_id: id, menus }))
@@ -512,72 +505,70 @@ class Application implements NativeApplication {
512
505
  this.menuBar.revoke()
513
506
  this.menuBar = undefined
514
507
  }
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
508
+ throw serviceError('app_menu', MENU_ERRORS, error)
525
509
  }
526
510
  }
527
511
 
528
512
  private receiveMenuItem(event: ApplicationEvent): void {
529
513
  if (!this.capabilities.includes('app_menu_v1'))
530
514
  throw new ProtocolError('Native menu selection arrived without app_menu_v1')
531
- if (event.menu_id >= this.nextMenuBar)
515
+ if (!this.ids.menuBar.has(event.menu_id))
532
516
  throw new ProtocolError('Native event names an unallocated menu bar')
533
517
  const registration = this.menuBar
534
518
  // A replaced or cleared bar's selection is stale and never delivered.
535
519
  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
- })
520
+ this.queueCallback(
521
+ listenerCallback(
522
+ undefined,
523
+ registration,
524
+ Object.freeze({
525
+ type: 'app_menu_item' as const,
526
+ sequence: event.sequence,
527
+ itemId: event.item_id,
528
+ menuBar: registration.handle,
529
+ signal: registration.controller.signal,
530
+ })
531
+ )
532
+ )
533
+ }
534
+
535
+ /** The service identity a native event names, checked before routing. */
536
+ private ownedIdentity(event: HostEvent): [Identities, number, string] | undefined {
537
+ switch (event.type) {
538
+ case 'global_shortcut':
539
+ return [this.ids.shortcut, event.shortcut_id, 'global shortcut']
540
+ case 'notification_activated':
541
+ case 'notification_dismissed':
542
+ return [this.ids.notification, event.notification_id, 'notification']
543
+ case 'process_output':
544
+ case 'process_exited':
545
+ return [this.ids.process, event.process_id, 'process']
546
+ case 'file_dialog_completed':
547
+ return [this.ids.dialog, event.dialog_id, 'file dialog']
548
+ case 'message_dialog_completed':
549
+ return [this.ids.messageDialog, event.dialog_id, 'message dialog']
550
+ case 'context_menu_completed':
551
+ return [this.ids.contextMenu, event.menu_id, 'context menu']
552
+ case 'drop_target_drag':
553
+ case 'drop_received':
554
+ case 'drop_rejected':
555
+ return [this.ids.dropTarget, event.target_id, 'drop target']
556
+ default:
557
+ return undefined
558
+ }
546
559
  }
547
560
 
548
561
  private async consume(): Promise<void> {
549
562
  try {
550
563
  for await (const event of this.host) {
564
+ if (this.callbacks.length >= MAX_QUEUED_CALLBACKS) await this.drainCallbacks()
551
565
  if (event.type === 'app_menu_item') {
552
566
  this.receiveMenuItem(event)
553
567
  continue
554
568
  }
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')
569
+ const owned = this.ownedIdentity(event)
570
+ if (owned && !owned[0].has(owned[1]))
571
+ throw new ProtocolError('Native event names an unallocated ' + owned[2])
581
572
  if (event.type === 'drop_received') {
582
573
  if (event.drop_id <= this.lastDrop)
583
574
  throw new ProtocolError('Native drop identities must increase')
@@ -585,11 +576,11 @@ class Application implements NativeApplication {
585
576
  }
586
577
  const window = this.windows.get(event.window_id)
587
578
  if (!window) {
588
- if (event.window_id >= this.nextWindow)
579
+ if (!this.ids.window.has(event.window_id))
589
580
  throw new ProtocolError('Native event names an unallocated window')
590
581
  continue // Revoked window: late events must not retain or invoke callbacks.
591
582
  }
592
- window.receive(event, this.nextNode)
583
+ window.receive(event, this.ids.node.next)
593
584
  }
594
585
  } catch (cause) {
595
586
  this.failure ??= cause instanceof Error ? cause : new Error(String(cause))
@@ -606,10 +597,7 @@ class Application implements NativeApplication {
606
597
  }
607
598
  }
608
599
 
609
- async function dispatchShortcut(
610
- registration: ShortcutRegistration,
611
- event: GlobalShortcutEvent
612
- ): Promise<void> {
600
+ async function deliver<T>(registration: Delivery<T>, event: T): Promise<void> {
613
601
  const listener = registration.listener
614
602
  if (!listener || !registration.live) return
615
603
  await dispatchOwned(listener, event, registration.controller.signal)
@@ -629,15 +617,6 @@ async function dispatchNotification(
629
617
  }
630
618
  }
631
619
 
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
620
  async function dispatchOwned<T>(
642
621
  listener: (event: T) => void | Promise<void>,
643
622
  event: T,
@@ -657,79 +636,40 @@ async function dispatchOwned<T>(
657
636
  }
658
637
  }
659
638
 
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
639
+ /** A host-owned file dialog or context menu awaiting its result. */
640
+ interface PendingRequest {
641
+ readonly id: number
642
+ readonly windowId: number
643
+ readonly live: boolean
644
+ readonly result: Promise<unknown>
645
+ fail(error: Error): void
646
+ }
647
+
648
+ /** A native command error with one of `codes` as `service`'s public error; any other error unchanged. */
649
+ function serviceError(
650
+ service: NativeServiceError['service'],
651
+ codes: ReadonlySet<string>,
652
+ error: unknown
653
+ ): unknown {
654
+ return error instanceof NativeCommandError && codes.has(error.code)
655
+ ? new NativeServiceError(service, error.code as NativeServiceError['code'], error.message)
656
+ : error
657
+ }
658
+
659
+ // Native error codes each service reports as its own NativeServiceError.
660
+ const SERVICE = ['permission_denied', 'service_unavailable'] as const
661
+ const REQUEST = [...SERVICE, 'cancelled', 'native_failure', 'limit_exceeded'] as const
662
+ const DISPLAY_ERRORS: ReadonlySet<string> = new Set(SERVICE)
663
+ const MENU_ERRORS: ReadonlySet<string> = new Set(REQUEST)
664
+ const DIALOG_ERRORS: ReadonlySet<string> = new Set([...REQUEST, 'operation_timed_out'])
665
+ const NOTIFICATION_ERRORS = DIALOG_ERRORS
666
+ const SHORTCUT_ERRORS: ReadonlySet<string> = new Set([...DIALOG_ERRORS, 'conflict'])
667
+ const CLIPBOARD_ERRORS: ReadonlySet<string> = new Set([...DIALOG_ERRORS, 'payload_too_large'])
668
+ const PATH_ERRORS = [...REQUEST, 'not_found', 'path_denied'] as const
669
+ const DROP_ERRORS: ReadonlySet<string> = new Set([...PATH_ERRORS, 'conflict'])
670
+ const ACCESS_ERRORS = [...PATH_ERRORS, 'wrong_kind', 'access_denied'] as const
671
+ const PROCESS_ERRORS: ReadonlySet<string> = new Set([...ACCESS_ERRORS, 'invalid_state'])
672
+ const FILE_ERRORS: ReadonlySet<string> = new Set([...ACCESS_ERRORS, 'already_exists', 'not_empty'])
733
673
 
734
674
  class Window implements NativeWindow {
735
675
  readonly root: NativeNode<'box'>
@@ -765,75 +705,47 @@ class Window implements NativeWindow {
765
705
  }
766
706
 
767
707
  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
708
+ return this.application.batch(this, update)
709
+ }
710
+
711
+ transaction(): Transaction {
712
+ this.assertActive()
713
+ return new Transaction(
714
+ this.nodes,
715
+ this.rootId,
716
+ () => this.application.ids.node.allocate(),
717
+ this.application.limits,
718
+ this.application.capabilities,
719
+ this.text
720
+ )
721
+ }
722
+
723
+ async apply(transactions: readonly Transaction[]): Promise<void> {
724
+ // One native batch applies every transaction atomically.
725
+ const reply = await this.application.host.send({
726
+ type: 'batch',
727
+ window_id: this.id,
728
+ base_revision: this.revision,
729
+ operations:
730
+ transactions.length === 1
731
+ ? transactions[0]!.operations
732
+ : OperationList.join(transactions.map((transaction) => transaction.operations)),
836
733
  })
734
+ // Publish in the reply's own continuation, before any later native event.
735
+ this.assertActive()
736
+ for (const transaction of transactions) {
737
+ // Each continues the one before it, which is now committed.
738
+ if (transaction.nodes.base !== this.nodes) transaction.rebase(this.nodes, this.text)
739
+ transaction.commit(this.nodes, this.text)
740
+ this.listeners.forget(transaction.nodes.deletes)
741
+ }
742
+ this.revision = reply.tree_revision
743
+ // The host revokes a target whose node a committed tree removed.
744
+ for (const registration of this.application.dropTargets.values())
745
+ if (registration.windowId === this.id && !this.nodes.has(registration.nodeId)) {
746
+ registration.revoke()
747
+ this.application.dropTargets.delete(registration.id)
748
+ }
837
749
  }
838
750
 
839
751
  on<T extends NativeEventType>(
@@ -895,12 +807,7 @@ class Window implements NativeWindow {
895
807
  if (error instanceof ProtocolError) throw error
896
808
  this.assertActive()
897
809
  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
810
+ throw serviceError('window_display', DISPLAY_ERRORS, error)
904
811
  }
905
812
  })
906
813
  }
@@ -935,17 +842,22 @@ class Window implements NativeWindow {
935
842
  // Validate even when nobody listens: a malformed frame is a host fault.
936
843
  const snapshot = publicDisplaySnapshot(event.snapshot, this.application.capabilities)
937
844
  if (!this.active) return
938
- for (const subscription of this.displayChanges)
845
+ for (const subscription of this.displayChanges) {
846
+ const change: DisplayChangeEvent = Object.freeze({
847
+ type: 'display_change',
848
+ sequence: event.sequence,
849
+ snapshot,
850
+ signal: subscription.controller.signal,
851
+ })
939
852
  this.application.queueCallback({
940
853
  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
- }),
854
+ retain: () => subscription.live,
855
+ run: async () => {
856
+ const listener = subscription.current
857
+ if (listener) await dispatchOwned(listener, change, subscription.controller.signal)
858
+ },
948
859
  })
860
+ }
949
861
  }
950
862
 
951
863
  private revokeDisplayChanges(): void {
@@ -990,24 +902,7 @@ class Window implements NativeWindow {
990
902
  if (error instanceof ProtocolError) throw error
991
903
  this.assertActive()
992
904
  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
905
+ throw serviceError(service, CLIPBOARD_ERRORS, error)
1011
906
  }
1012
907
  })
1013
908
  }
@@ -1020,18 +915,20 @@ class Window implements NativeWindow {
1020
915
  if (typeof listener !== 'function')
1021
916
  throw new TypeError('A global shortcut listener must be a function')
1022
917
  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 {
918
+ return this.register(
919
+ 'global_shortcuts',
920
+ SHORTCUT_ERRORS,
921
+ this.application.shortcuts,
922
+ () =>
923
+ new ShortcutRegistration(
924
+ this.application.ids.shortcut.allocate(),
925
+ this.id,
926
+ key,
927
+ modifiers,
928
+ listener,
929
+ (item) => this.releaseShortcut(item)
930
+ ),
931
+ async (registration) => {
1035
932
  await this.application.host.send({
1036
933
  type: 'register_global_shortcut',
1037
934
  window_id: this.id,
@@ -1039,56 +936,21 @@ class Window implements NativeWindow {
1039
936
  key,
1040
937
  modifiers,
1041
938
  })
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
- })
939
+ },
940
+ (registration) => registration.live,
941
+ 'Global shortcut was revoked during registration'
942
+ )
1067
943
  }
1068
944
 
1069
945
  private releaseShortcut(registration: ShortcutRegistration): Promise<void> {
1070
946
  // Local revocation first: no activation is delivered after this call.
1071
947
  registration.revoke()
1072
948
  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
- )
949
+ return this.releaseNative({
950
+ type: 'unregister_global_shortcut',
951
+ window_id: this.id,
952
+ shortcut_id: registration.id,
953
+ })
1092
954
  }
1093
955
 
1094
956
  async postNotification(
@@ -1099,18 +961,20 @@ class Window implements NativeWindow {
1099
961
  if (typeof listener !== 'function')
1100
962
  throw new TypeError('A notification listener must be a function')
1101
963
  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 {
964
+ return this.register(
965
+ 'notifications',
966
+ NOTIFICATION_ERRORS,
967
+ this.application.notifications,
968
+ () =>
969
+ new NotificationRegistration(
970
+ this.application.ids.notification.allocate(),
971
+ this.id,
972
+ title,
973
+ body,
974
+ listener,
975
+ (item) => this.withdrawNotification(item)
976
+ ),
977
+ async (registration) => {
1114
978
  const posted = await this.application.host.send({
1115
979
  type: 'post_notification',
1116
980
  window_id: this.id,
@@ -1119,48 +983,29 @@ class Window implements NativeWindow {
1119
983
  body,
1120
984
  })
1121
985
  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
- })
986
+ },
987
+ (registration) => registration.deliverable,
988
+ 'Notification was revoked while it was posted'
989
+ )
1147
990
  }
1148
991
 
1149
992
  async openFileGrant(root: string, options: FileGrantOptions = {}): Promise<NativeFileGrant> {
1150
993
  const request = fileGrantRequest(root, options)
1151
994
  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 {
995
+ return this.register(
996
+ 'filesystem_grants',
997
+ FILE_ERRORS,
998
+ this.application.fileGrants,
999
+ () =>
1000
+ new FileGrantRegistration(
1001
+ this.application.ids.fileGrant.allocate(),
1002
+ this.id,
1003
+ request.root,
1004
+ request.access,
1005
+ (item, call) => this.fileCall(item, call),
1006
+ (item) => this.closeFileGrant(item)
1007
+ ),
1008
+ async (registration) => {
1164
1009
  await this.application.host.send({
1165
1010
  type: 'open_file_grant',
1166
1011
  window_id: this.id,
@@ -1168,35 +1013,10 @@ class Window implements NativeWindow {
1168
1013
  root: request.root,
1169
1014
  access: request.access,
1170
1015
  })
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)
1016
+ },
1017
+ (registration) => registration.live,
1018
+ 'File grant was revoked while it opened'
1193
1019
  )
1194
- return new NativeServiceError(
1195
- 'filesystem_grants',
1196
- error.code as NativeServiceError['code'],
1197
- error.message
1198
- )
1199
- return error
1200
1020
  }
1201
1021
 
1202
1022
  private fileCall(registration: FileGrantRegistration, call: FileCall): Promise<unknown> {
@@ -1227,7 +1047,7 @@ class Window implements NativeWindow {
1227
1047
  if (error instanceof ProtocolError) throw error
1228
1048
  if (!registration.live) throw revoked()
1229
1049
  this.assertActive()
1230
- throw this.fileError(error)
1050
+ throw this.serviceFailure('filesystem_grants', FILE_ERRORS, error)
1231
1051
  }
1232
1052
  })
1233
1053
  }
@@ -1235,20 +1055,11 @@ class Window implements NativeWindow {
1235
1055
  private closeFileGrant(registration: FileGrantRegistration): Promise<void> {
1236
1056
  registration.revoke()
1237
1057
  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
- )
1058
+ return this.releaseNative({
1059
+ type: 'close_file_grant',
1060
+ window_id: this.id,
1061
+ grant_id: registration.id,
1062
+ })
1252
1063
  }
1253
1064
 
1254
1065
  async spawnProcess(
@@ -1268,54 +1079,31 @@ class Window implements NativeWindow {
1268
1079
  throw new TypeError('Process cwd must name a live file grant owned by this window')
1269
1080
  cwd = { grant_id: grant.id, path: request.cwd.path }
1270
1081
  }
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 {
1082
+ return this.register(
1083
+ 'processes',
1084
+ PROCESS_ERRORS,
1085
+ this.application.processes,
1086
+ () =>
1087
+ new ProcessRegistration(
1088
+ this.application.ids.process.allocate(),
1089
+ this.id,
1090
+ request.launch.executable,
1091
+ request.launch.terminal !== undefined,
1092
+ listener,
1093
+ (item, call) => this.processCall(item, call),
1094
+ (item) => this.releaseProcess(item)
1095
+ ),
1096
+ async (registration) => {
1284
1097
  await this.application.host.send({
1285
1098
  type: 'spawn_process',
1286
1099
  window_id: this.id,
1287
1100
  process_id: registration.id,
1288
1101
  launch: cwd ? { ...request.launch, cwd } : request.launch,
1289
1102
  })
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)
1103
+ },
1104
+ (registration) => registration.live,
1105
+ 'Process was released while it started'
1312
1106
  )
1313
- return new NativeServiceError(
1314
- 'processes',
1315
- error.code as NativeServiceError['code'],
1316
- error.message
1317
- )
1318
- return error
1319
1107
  }
1320
1108
 
1321
1109
  private processCall(registration: ProcessRegistration, call: ProcessCall): Promise<void> {
@@ -1335,7 +1123,7 @@ class Window implements NativeWindow {
1335
1123
  if (error instanceof ProtocolError) throw error
1336
1124
  if (!registration.live) throw revoked()
1337
1125
  this.assertActive()
1338
- throw this.processError(error)
1126
+ throw this.serviceFailure('processes', PROCESS_ERRORS, error)
1339
1127
  }
1340
1128
  })
1341
1129
  }
@@ -1343,20 +1131,11 @@ class Window implements NativeWindow {
1343
1131
  private releaseProcess(registration: ProcessRegistration): Promise<void> {
1344
1132
  registration.revoke()
1345
1133
  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
- )
1134
+ return this.releaseNative({
1135
+ type: 'release_process',
1136
+ window_id: this.id,
1137
+ process_id: registration.id,
1138
+ })
1360
1139
  }
1361
1140
 
1362
1141
  receiveProcess(event: Extract<WindowEvent, { type: 'process_output' | 'process_exited' }>): void {
@@ -1377,26 +1156,31 @@ class Window implements NativeWindow {
1377
1156
  if ((event.stream === 'terminal') !== registration.handle.terminal)
1378
1157
  throw new ProtocolError('Native process output names the wrong stream kind')
1379
1158
  registration.chunk = event.chunk
1159
+ const output: ProcessEvent = Object.freeze({
1160
+ type: 'process_output',
1161
+ stream: event.stream,
1162
+ bytes: Uint8Array.fromBase64(event.data),
1163
+ ...common,
1164
+ })
1165
+ const chunk = event.chunk
1380
1166
  this.application.queueCallback({
1381
1167
  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
- }),
1168
+ retain: () => registration.live,
1169
+ run: () => this.dispatchProcess(registration, output, chunk),
1390
1170
  })
1391
1171
  return
1392
1172
  }
1393
1173
  registration.end()
1394
1174
  registration.exit = Object.freeze({ ...event.exit })
1175
+ const exited: ProcessEvent = Object.freeze({
1176
+ type: 'process_exited',
1177
+ exit: registration.exit,
1178
+ ...common,
1179
+ })
1395
1180
  this.application.queueCallback({
1396
1181
  windowId: this.id,
1397
- process: registration,
1398
- chunk: 0,
1399
- event: Object.freeze({ type: 'process_exited', exit: registration.exit, ...common }),
1182
+ retain: () => registration.live,
1183
+ run: () => this.dispatchProcess(registration, exited, 0),
1400
1184
  })
1401
1185
  }
1402
1186
 
@@ -1426,9 +1210,12 @@ class Window implements NativeWindow {
1426
1210
  (error: unknown) => {
1427
1211
  // Release or window close can race the acknowledgement.
1428
1212
  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
1213
+ // Shutdown or a lost transport already owns the outcome, reported
1214
+ // through the application's closed promise; recording it here first
1215
+ // would hide the original cause. A rejection while the host still
1216
+ // runs (the runtime's own command limit) would otherwise lose the
1217
+ // credit silently.
1218
+ if (!this.application.running || !this.application.host.running) return
1432
1219
  // Not awaited: shutdown waits for this tracked operation.
1433
1220
  void this.application.fail(error)
1434
1221
  }
@@ -1444,82 +1231,54 @@ class Window implements NativeWindow {
1444
1231
  throw new TypeError('A drop target listener must be a function')
1445
1232
  this.assertActive()
1446
1233
  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
- })
1234
+ return this.register(
1235
+ 'drag_drop',
1236
+ DROP_ERRORS,
1237
+ this.application.dropTargets,
1238
+ () => {
1239
+ if (this.nodes.get(node.id)?.handle !== node.handle)
1240
+ throw new NativeStateError('invalid_handle', 'Drop target node was removed')
1241
+ return new DropTargetRegistration(
1242
+ this.application.ids.dropTarget.allocate(),
1243
+ this.id,
1244
+ node.id,
1245
+ node.handle,
1246
+ listener,
1247
+ (item) => this.releaseDropTarget(item)
1248
+ )
1249
+ },
1250
+ async (registration) => {
1251
+ try {
1252
+ await this.application.host.send({
1253
+ type: 'register_drop_target',
1254
+ window_id: this.id,
1255
+ target_id: registration.id,
1256
+ node_id: node.id,
1257
+ })
1258
+ } catch (error) {
1259
+ if (error instanceof NativeCommandError && error.code === 'invalid_handle' && this.active)
1260
+ throw new NativeStateError('invalid_handle', 'Drop target node is not committed')
1261
+ throw error
1262
+ }
1263
+ },
1264
+ (registration) => registration.live,
1265
+ 'Drop target was revoked during registration'
1266
+ )
1485
1267
  }
1486
1268
 
1487
1269
  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
1270
+ return serviceError('drag_drop', DROP_ERRORS, error)
1498
1271
  }
1499
1272
 
1500
1273
  private releaseDropTarget(registration: DropTargetRegistration): Promise<void> {
1501
1274
  // Local revocation first: no drag or drop is delivered after this call.
1502
1275
  registration.revoke()
1503
1276
  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
- )
1277
+ return this.releaseNative({
1278
+ type: 'unregister_drop_target',
1279
+ window_id: this.id,
1280
+ target_id: registration.id,
1281
+ })
1523
1282
  }
1524
1283
 
1525
1284
  private resolveDroppedItem(
@@ -1599,36 +1358,20 @@ class Window implements NativeWindow {
1599
1358
  )
1600
1359
  delivered = { type: 'drop', items: Object.freeze(items), ...common }
1601
1360
  }
1602
- this.application.queueCallback({
1603
- windowId: this.id,
1604
- dropTarget: registration,
1605
- event: Object.freeze(delivered),
1606
- })
1361
+ this.application.queueCallback(
1362
+ listenerCallback(this.id, registration, Object.freeze(delivered))
1363
+ )
1607
1364
  }
1608
1365
 
1609
1366
  private withdrawNotification(registration: NotificationRegistration): Promise<void> {
1610
1367
  // Local revocation first: no activation is delivered after this call.
1611
1368
  registration.revoke()
1612
1369
  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
- )
1370
+ return this.releaseNative({
1371
+ type: 'withdraw_notification',
1372
+ window_id: this.id,
1373
+ notification_id: registration.id,
1374
+ })
1632
1375
  }
1633
1376
 
1634
1377
  receiveNotification(
@@ -1648,14 +1391,15 @@ class Window implements NativeWindow {
1648
1391
  registration.end()
1649
1392
  this.application.notifications.delete(registration.id)
1650
1393
  }
1394
+ const delivered: NotificationEvent = Object.freeze(
1395
+ event.type === 'notification_activated'
1396
+ ? { type: 'notification_activated', ...common }
1397
+ : { type: 'notification_dismissed', reason: event.reason, ...common }
1398
+ )
1651
1399
  this.application.queueCallback({
1652
1400
  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
- ),
1401
+ retain: () => registration.deliverable,
1402
+ run: () => dispatchNotification(registration, delivered),
1659
1403
  })
1660
1404
  }
1661
1405
 
@@ -1681,56 +1425,34 @@ class Window implements NativeWindow {
1681
1425
  : Object.freeze({ kind: 'cancelled' })
1682
1426
  }
1683
1427
 
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({
1428
+ private fileDialog(options: FileDialogOptions, signal: AbortSignal | undefined) {
1429
+ return this.openPending(
1430
+ 'file_dialogs',
1431
+ signal,
1432
+ this.application.dialogs,
1433
+ (other) => other.windowId === this.id,
1434
+ 'This window already has an open file dialog',
1435
+ () => new FileDialogRequest(this.application.ids.dialog.allocate(), this.id, options.mode),
1436
+ (dialog) =>
1437
+ this.application.host.send({
1701
1438
  type: 'show_file_dialog',
1702
1439
  window_id: this.id,
1703
1440
  dialog_id: dialog.id,
1704
1441
  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)
1442
+ }),
1443
+ (dialog) =>
1444
+ this.cancelPending(
1445
+ 'file_dialogs',
1446
+ this.application.dialogs,
1447
+ dialog,
1448
+ 'The file dialog was cancelled',
1449
+ {
1450
+ type: 'close_file_dialog',
1451
+ window_id: this.id,
1452
+ dialog_id: dialog.id,
1453
+ }
1716
1454
  )
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
- }
1455
+ )
1734
1456
  }
1735
1457
 
1736
1458
  async showContextMenu(
@@ -1741,85 +1463,38 @@ class Window implements NativeWindow {
1741
1463
  const wire = contextMenuRequest(items, position)
1742
1464
  if (!this.application.capabilities.includes('context_menus_v1'))
1743
1465
  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({
1466
+ return this.openPending(
1467
+ 'context_menus',
1468
+ serviceSignal(request),
1469
+ this.application.contextMenus,
1470
+ (other) => other.live,
1471
+ 'Another context menu is already open',
1472
+ () =>
1473
+ new ContextMenuRequest(
1474
+ this.application.ids.contextMenu.allocate(),
1475
+ this.id,
1476
+ itemIds(wire.items)
1477
+ ),
1478
+ (menu) =>
1479
+ this.application.host.send({
1765
1480
  type: 'show_context_menu',
1766
1481
  window_id: this.id,
1767
1482
  menu_id: menu.id,
1768
1483
  ...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)
1484
+ }),
1485
+ (menu) =>
1486
+ this.cancelPending(
1487
+ 'context_menus',
1488
+ this.application.contextMenus,
1489
+ menu,
1490
+ 'The context menu was cancelled',
1491
+ {
1492
+ type: 'close_context_menu',
1493
+ window_id: this.id,
1494
+ menu_id: menu.id,
1495
+ }
1780
1496
  )
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
1497
  )
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
1498
  }
1824
1499
 
1825
1500
  receiveContextMenu(event: Extract<WindowEvent, { type: 'context_menu_completed' }>): void {
@@ -1853,7 +1528,7 @@ class Window implements NativeWindow {
1853
1528
  if (capability.availability !== 'available' || capability.backend === 'modal_overlay')
1854
1529
  return undefined
1855
1530
  return {
1856
- allocate: () => this.application.allocateMessageDialog(),
1531
+ allocate: () => this.application.ids.messageDialog.allocate(),
1857
1532
  show: async (id, options) => {
1858
1533
  try {
1859
1534
  await this.application.service(() =>
@@ -1865,34 +1540,11 @@ class Window implements NativeWindow {
1865
1540
  })
1866
1541
  )
1867
1542
  } 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
1543
+ throw serviceError('message_dialogs', DIALOG_ERRORS, error)
1894
1544
  }
1895
1545
  },
1546
+ close: (id) =>
1547
+ this.releaseNative({ type: 'close_message_dialog', window_id: this.id, dialog_id: id }),
1896
1548
  }
1897
1549
  }
1898
1550
 
@@ -1911,32 +1563,6 @@ class Window implements NativeWindow {
1911
1563
  return this.messages.show(spec, signal)
1912
1564
  }
1913
1565
 
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
1566
  receiveFileDialog(event: Extract<WindowEvent, { type: 'file_dialog_completed' }>): void {
1941
1567
  if (!this.active) return
1942
1568
  const dialog = this.application.dialogs.get(event.dialog_id)
@@ -1953,18 +1579,137 @@ class Window implements NativeWindow {
1953
1579
  if (!registration) return // Released: the host may already have queued a press.
1954
1580
  if (registration.windowId !== this.id)
1955
1581
  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
- }),
1582
+ this.application.queueCallback(
1583
+ listenerCallback(
1584
+ this.id,
1585
+ registration,
1586
+ Object.freeze({
1587
+ type: 'global_shortcut' as const,
1588
+ sequence: event.sequence,
1589
+ shortcut: registration.handle,
1590
+ signal: registration.controller.signal,
1591
+ })
1592
+ )
1593
+ )
1594
+ }
1595
+
1596
+ /** A failed service request's public error: protocol faults and a closed owner first. */
1597
+ private serviceFailure(
1598
+ service: NativeServiceError['service'],
1599
+ codes: ReadonlySet<string>,
1600
+ error: unknown
1601
+ ): unknown {
1602
+ if (error instanceof ProtocolError) return error
1603
+ this.assertActive()
1604
+ return serviceError(service, codes, error)
1605
+ }
1606
+
1607
+ /**
1608
+ * Allocate, record and natively register one service handle. A failure, or
1609
+ * a revocation while the host registered it, forgets the record again.
1610
+ */
1611
+ private register<R extends { readonly id: number; readonly handle: unknown; revoke(): void }>(
1612
+ service: NativeServiceError['service'],
1613
+ codes: ReadonlySet<string>,
1614
+ registrations: Map<number, R>,
1615
+ create: () => R,
1616
+ send: (registration: R) => Promise<void>,
1617
+ accepted: (registration: R) => boolean,
1618
+ revoked: string
1619
+ ): Promise<R['handle']> {
1620
+ return this.application.service(async () => {
1621
+ this.assertActive()
1622
+ const registration = create()
1623
+ registrations.set(registration.id, registration)
1624
+ try {
1625
+ await send(registration)
1626
+ this.assertActive()
1627
+ if (!accepted(registration)) throw new NativeServiceError(service, 'cancelled', revoked)
1628
+ return registration.handle
1629
+ } catch (error) {
1630
+ registration.revoke()
1631
+ registrations.delete(registration.id)
1632
+ throw this.serviceFailure(service, codes, error)
1633
+ }
1965
1634
  })
1966
1635
  }
1967
1636
 
1637
+ /**
1638
+ * Natively release a handle already revoked locally. Window close and
1639
+ * application shutdown release it natively instead, and the owner can end
1640
+ * it while the request is in flight (`invalid_handle`).
1641
+ */
1642
+ private releaseNative(command: WindowCommand): Promise<void> {
1643
+ if (!this.active || !this.application.running) return Promise.resolve()
1644
+ return this.application.track(
1645
+ this.application.host.send(command).then(
1646
+ () => {},
1647
+ (error: unknown) => {
1648
+ if (error instanceof NativeCommandError && error.code === 'invalid_handle') return
1649
+ if (!this.application.running) return
1650
+ throw error
1651
+ }
1652
+ )
1653
+ )
1654
+ }
1655
+
1656
+ /**
1657
+ * Show one host-owned dialog or menu and wait for its result. An abort
1658
+ * while the host was showing it closes the now-live request.
1659
+ */
1660
+ private async openPending<P extends PendingRequest>(
1661
+ service: 'file_dialogs' | 'context_menus',
1662
+ signal: AbortSignal | undefined,
1663
+ pending: Map<number, P>,
1664
+ busy: (other: P) => boolean,
1665
+ busyMessage: string,
1666
+ create: () => P,
1667
+ send: (request: P) => Promise<unknown>,
1668
+ cancel: (request: P) => void
1669
+ ): Promise<Awaited<P['result']>> {
1670
+ this.assertActive()
1671
+ checkServiceCancellation(signal, service)
1672
+ const request = await this.application.service(async () => {
1673
+ this.assertActive()
1674
+ checkServiceCancellation(signal, service)
1675
+ for (const other of pending.values())
1676
+ if (busy(other)) throw new NativeServiceError(service, 'limit_exceeded', busyMessage)
1677
+ const request = create()
1678
+ pending.set(request.id, request)
1679
+ try {
1680
+ await send(request)
1681
+ this.assertActive()
1682
+ return request
1683
+ } catch (error) {
1684
+ request.fail(error instanceof Error ? error : new Error(String(error)))
1685
+ pending.delete(request.id)
1686
+ throw this.serviceFailure(service, DIALOG_ERRORS, error)
1687
+ }
1688
+ })
1689
+ const abort = () => cancel(request)
1690
+ if (signal?.aborted) abort()
1691
+ else signal?.addEventListener('abort', abort, { once: true })
1692
+ try {
1693
+ return (await request.result) as Awaited<P['result']>
1694
+ } finally {
1695
+ signal?.removeEventListener('abort', abort)
1696
+ }
1697
+ }
1698
+
1699
+ /** Delivery stops at once; the OS dialog or menu is then closed natively. */
1700
+ private cancelPending<P extends PendingRequest>(
1701
+ service: 'file_dialogs' | 'context_menus',
1702
+ pending: Map<number, P>,
1703
+ request: P,
1704
+ message: string,
1705
+ command: WindowCommand
1706
+ ): void {
1707
+ if (!request.live) return
1708
+ request.fail(new NativeServiceError(service, 'cancelled', message))
1709
+ pending.delete(request.id)
1710
+ void this.releaseNative(command).catch(() => {})
1711
+ }
1712
+
1968
1713
  async close(): Promise<void> {
1969
1714
  if (!this.active) {
1970
1715
  await this.closing
@@ -1998,31 +1743,13 @@ class Window implements NativeWindow {
1998
1743
  * `cancelled`, not as `invalid_handle` after the host acknowledges the close.
1999
1744
  */
2000
1745
  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
- }
1746
+ const { shortcuts, notifications, fileGrants, processes, dropTargets } = this.application
1747
+ for (const registrations of [shortcuts, notifications, fileGrants, processes, dropTargets])
1748
+ for (const registration of registrations.values())
1749
+ if (registration.windowId === this.id) {
1750
+ registration.revoke()
1751
+ registrations.delete(registration.id)
1752
+ }
2026
1753
  }
2027
1754
 
2028
1755
  revoke(): void {
@@ -2032,16 +1759,16 @@ class Window implements NativeWindow {
2032
1759
  this.text = new CommittedText(this.application.limits.max_text_bytes)
2033
1760
  this.revokeDisplayChanges()
2034
1761
  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
- }
1762
+ const { dialogs, contextMenus } = this.application
1763
+ for (const [pending, name] of [
1764
+ [dialogs, 'File dialog'],
1765
+ [contextMenus, 'Context menu'],
1766
+ ] as const)
1767
+ for (const request of pending.values())
1768
+ if (request.windowId === this.id) {
1769
+ request.fail(new NativeStateError('invalid_handle', name + ' owner window was closed'))
1770
+ pending.delete(request.id)
1771
+ }
2045
1772
  this.messages.revoke()
2046
1773
  this.application.windows.delete(this.id)
2047
1774
  this.resolveClosed()
@@ -2138,20 +1865,23 @@ class Window implements NativeWindow {
2138
1865
  'Native split resize targeted a non-split node or was not advertised'
2139
1866
  )
2140
1867
  }
1868
+ const route = ownedPath.map((item) => item.handle)
2141
1869
  // 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 })
1870
+ if (this.messages.receive(event, route, node.handle)) return
1871
+ const plan = this.listeners.prepare(event, route)
1872
+ if (!plan) return
1873
+ const nodeId = node.id
1874
+ this.application.queueCallback({
1875
+ windowId: this.id,
1876
+ retain: () => {
1877
+ // A callback whose target or every binding is gone is dropped.
1878
+ const window = this.application.windows.get(this.id)
1879
+ if (window?.isTargetLive(nodeId) && prunePlan(plan)) return true
1880
+ window?.listeners.release(plan)
1881
+ return false
1882
+ },
1883
+ run: () => this.dispatch(nodeId, plan),
1884
+ })
2155
1885
  }
2156
1886
 
2157
1887
  async dispatch(nodeId: number, plan: DispatchPlan): Promise<void> {