@fish-under-sea/dsh-client-ui-task-board-fish 1.0.2 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/NOTICE +1 -1
  2. package/README.en.md +6 -4
  3. package/README.md +6 -4
  4. package/README.zh.md +6 -4
  5. package/icon.png +0 -0
  6. package/lib/client.js +4428 -1508
  7. package/lib/client.js.map +1 -1
  8. package/lib/index.js +2670 -496
  9. package/lib/types/client/CardDefaultPresetField.d.ts +35 -0
  10. package/lib/types/client/PluginSettingsCard.d.ts +130 -19
  11. package/lib/types/client/RangeBubble.d.ts +46 -0
  12. package/lib/types/client/SegmentGroup.d.ts +28 -0
  13. package/lib/types/client/TaskBoardSettingsCard.d.ts +63 -0
  14. package/lib/types/client/board/AttachmentField.d.ts +70 -0
  15. package/lib/types/client/board/ExecutionLog.d.ts +24 -0
  16. package/lib/types/client/board/ReasoningEffortField.d.ts +25 -0
  17. package/lib/types/client/board/TaskForm.d.ts +4 -0
  18. package/lib/types/client/board/VerificationReport.d.ts +2 -15
  19. package/lib/types/client/board/model-options.d.ts +87 -0
  20. package/lib/types/client/board/preset-label.d.ts +21 -0
  21. package/lib/types/client/board/preset-roster.d.ts +45 -0
  22. package/lib/types/client/board/source-group.d.ts +27 -0
  23. package/lib/types/client/body-mutations.d.ts +45 -0
  24. package/lib/types/client/host-api.d.ts +25 -0
  25. package/lib/types/client/locales.d.ts +87 -9
  26. package/lib/types/client/pending-verify.d.ts +47 -0
  27. package/lib/types/client/plugin-card-seat.d.ts +3 -1
  28. package/lib/types/client/service.d.ts +4 -1
  29. package/lib/types/client/settings-form.d.ts +73 -51
  30. package/lib/types/core/attachment.d.ts +132 -0
  31. package/lib/types/core/card-defaults.d.ts +78 -0
  32. package/lib/types/core/controller.d.ts +57 -8
  33. package/lib/types/core/execution-summary.d.ts +52 -0
  34. package/lib/types/core/extension.d.ts +116 -0
  35. package/lib/types/core/launch-width.d.ts +31 -0
  36. package/lib/types/core/reasoning-effort.d.ts +57 -0
  37. package/lib/types/core/session-reuse.d.ts +7 -1
  38. package/lib/types/core/spend-budget.d.ts +28 -0
  39. package/lib/types/core/subtask.d.ts +100 -37
  40. package/lib/types/core/tasks.d.ts +94 -10
  41. package/lib/types/core/use-cases/task-create.d.ts +10 -5
  42. package/lib/types/core/use-cases/task-tag.d.ts +36 -0
  43. package/lib/types/core/use-cases/task-update.d.ts +22 -1
  44. package/lib/types/core/wire-projection.d.ts +35 -0
  45. package/lib/types/core/workspace-target.d.ts +23 -3
  46. package/lib/types/host/attachments.d.ts +250 -0
  47. package/lib/types/host/extension-registry.d.ts +40 -0
  48. package/lib/types/host/launch-admission.d.ts +71 -0
  49. package/lib/types/host-ledger.d.ts +114 -47
  50. package/lib/types/host-routes.d.ts +63 -0
  51. package/lib/types/host-runner.d.ts +164 -18
  52. package/lib/types/host-service.d.ts +182 -46
  53. package/lib/types/host-spend.d.ts +52 -0
  54. package/lib/types/index.d.ts +173 -54
  55. package/lib/types/loopback.d.ts +41 -1
  56. package/lib/types/protocol.d.ts +52 -11
  57. package/lib/types/tool-surface.d.ts +1 -0
  58. package/locale/en.json +6 -0
  59. package/locale/zh.json +6 -0
  60. package/package.json +36 -29
  61. package/src/client/CardDefaultPresetField.tsx +101 -0
  62. package/src/client/PluginSettingsCard.tsx +385 -111
  63. package/src/client/RangeBubble.tsx +164 -0
  64. package/src/client/SegmentGroup.tsx +93 -0
  65. package/src/client/TaskBoardSettingsCard.tsx +332 -37
  66. package/src/client/board/AttachmentField.tsx +383 -0
  67. package/src/client/board/EditTaskModal.tsx +63 -0
  68. package/src/client/board/ExecutionLog.tsx +154 -0
  69. package/src/client/board/LinkSubtaskModal.tsx +1 -1
  70. package/src/client/board/NewTaskModal.tsx +154 -45
  71. package/src/client/board/ReasoningEffortField.tsx +50 -0
  72. package/src/client/board/TagManagerModal.tsx +151 -2
  73. package/src/client/board/TaskBoard.tsx +47 -10
  74. package/src/client/board/TaskCard.tsx +45 -23
  75. package/src/client/board/TaskDetail.tsx +468 -258
  76. package/src/client/board/TaskForm.tsx +19 -4
  77. package/src/client/board/VerificationReport.tsx +143 -104
  78. package/src/client/board/model-options.ts +208 -0
  79. package/src/client/board/preset-label.ts +32 -0
  80. package/src/client/board/preset-roster.ts +58 -0
  81. package/src/client/board/source-group.ts +94 -0
  82. package/src/client/board/task-markdown.module.css +11 -8
  83. package/src/client/board-settings.module.css +35 -7
  84. package/src/client/board.module.css +1044 -105
  85. package/src/client/body-mutations.ts +133 -0
  86. package/src/client/host-api.ts +70 -0
  87. package/src/client/index.ts +109 -95
  88. package/src/client/locales.ts +205 -48
  89. package/src/client/pending-verify.ts +90 -0
  90. package/src/client/plugin-card-seat.ts +8 -2
  91. package/src/client/service.ts +24 -0
  92. package/src/client/settings-card.module.css +466 -89
  93. package/src/client/settings-entry-form.ts +0 -1
  94. package/src/client/settings-form.ts +102 -60
  95. package/src/core/attachment.ts +287 -0
  96. package/src/core/card-defaults.ts +132 -0
  97. package/src/core/controller.ts +90 -11
  98. package/src/core/execution-summary.ts +96 -0
  99. package/src/core/extension.ts +120 -0
  100. package/src/core/launch-width.ts +38 -0
  101. package/src/core/reasoning-effort.ts +92 -0
  102. package/src/core/session-reuse.ts +7 -1
  103. package/src/core/spend-budget.ts +35 -0
  104. package/src/core/store.ts +19 -1
  105. package/src/core/subtask.ts +144 -68
  106. package/src/core/tasks.ts +117 -10
  107. package/src/core/use-cases/task-create.ts +27 -16
  108. package/src/core/use-cases/task-tag.ts +56 -0
  109. package/src/core/use-cases/task-update.ts +33 -5
  110. package/src/core/wire-projection.ts +81 -0
  111. package/src/core/workspace-target.ts +27 -3
  112. package/src/host/agent-tools.ts +33 -21
  113. package/src/host/attachments.ts +650 -0
  114. package/src/host/extension-registry.ts +150 -5
  115. package/src/host/launch-admission.ts +139 -0
  116. package/src/host-ledger.ts +248 -117
  117. package/src/host-routes.ts +233 -15
  118. package/src/host-runner.ts +395 -61
  119. package/src/host-service.ts +512 -139
  120. package/src/host-spend.ts +105 -0
  121. package/src/index.ts +312 -92
  122. package/src/loopback.ts +57 -1
  123. package/src/protocol.ts +83 -18
  124. package/src/tool-surface.ts +1 -0
  125. package/icon.svg +0 -3
@@ -15,6 +15,7 @@ import type { TaskBoardAction, TaskBoardSnapshot } from '../protocol.ts'
15
15
  import { canEditTaskContent } from '../core/use-cases/task-update.ts'
16
16
  import {
17
17
  TASK_BOARD_API_VERSION,
18
+ TASK_BOARD_MESSAGE_MAX_LENGTH,
18
19
  isTaskBoardExtensionPayload,
19
20
  taskBoardPayloadBytes,
20
21
  type TaskBoardCreateOptions,
@@ -26,7 +27,9 @@ import {
26
27
  type TaskBoardExtensionPayload,
27
28
  type TaskBoardIntegrationFace,
28
29
  type TaskBoardLinkedTask,
30
+ type TaskBoardSessionsFace,
29
31
  type TaskBoardStatusChangedEvent,
32
+ type TaskBoardTaskDraft,
30
33
  type TaskBoardTaskDeletedEvent,
31
34
  type TaskBoardTasksFace,
32
35
  } from '../core/extension.ts'
@@ -56,11 +59,27 @@ export interface TaskBoardExtensionToolRegistry {
56
59
  /** Applies one board action with every board gate intact (never an extension action). */
57
60
  export type TaskBoardActionApplier = (action: Exclude<TaskBoardAction, { kind: 'extension-action' }>, initiator?: string) => TaskBoardSnapshot
58
61
 
62
+ /** Delivers one follow-up message into an existing execution session. */
63
+ export type TaskBoardFollowUpDelivery = (sessionId: string, text: string) => Promise<void>
64
+
65
+ /** Applies one rework request through the board's own run path. */
66
+ export type TaskBoardReworkApplier = (taskId: string, instructions: string, initiator?: string) => void
67
+
59
68
  /** Registry dependencies. */
60
69
  export interface TaskBoardExtensionRegistryOptions {
61
70
  ledger: HostTaskLedger
62
71
  /** Apply an action through the board service (gates, run dispatch, schedule). */
63
72
  apply?: TaskBoardActionApplier
73
+ /**
74
+ * Queue one follow-up message into a session. Absent means this deployment
75
+ * serves no session delivery, which the capability face refuses visibly.
76
+ */
77
+ followUp?: TaskBoardFollowUpDelivery
78
+ /**
79
+ * Apply one rework run request (through the same gates a run takes). Absent
80
+ * means this deployment serves no rework, which the face refuses visibly.
81
+ */
82
+ rework?: TaskBoardReworkApplier
64
83
  /** Resolve the deployment's tool registry; absent loses the tool surface only. */
65
84
  toolRegistry?: () => TaskBoardExtensionToolRegistry | undefined
66
85
  now?: () => number
@@ -137,10 +156,54 @@ function readPayload(value: unknown): TaskBoardExtensionPayload | undefined {
137
156
  return isTaskBoardExtensionPayload(value) ? value : undefined
138
157
  }
139
158
 
159
+ /** One-line text of a delivery failure, for a diagnosable refusal. */
160
+ function failureText(error: unknown): string {
161
+ return error instanceof Error ? error.message : String(error)
162
+ }
163
+
164
+ /**
165
+ * Validate one free text a provider pushes into an execution. Blank text would
166
+ * queue an empty turn, and an unbounded one would let a single provider call
167
+ * inject an arbitrarily large instruction, so both are refused here rather
168
+ * than at the gateway.
169
+ */
170
+ function extensionText(value: string, what: string): string {
171
+ const text = typeof value === 'string' ? value.trim() : ''
172
+ if (text === '') throw new TaskBoardExtensionError('invalid-text', `a ${what} must be a non-blank string`)
173
+ if (text.length > TASK_BOARD_MESSAGE_MAX_LENGTH) {
174
+ throw new TaskBoardExtensionError('invalid-text', `a ${what} is limited to ${TASK_BOARD_MESSAGE_MAX_LENGTH} characters`)
175
+ }
176
+ return text
177
+ }
178
+
179
+ /**
180
+ * The session a follow-up message goes to, or the refusal that says why there
181
+ * is none. The open execution owns the answer while one is running: delivering
182
+ * into the previous conversation instead would answer a question the current
183
+ * run never asked.
184
+ */
185
+ function followUpTarget(task: TaskRecord): { sessionId: string } | { refusal: string; message: string } {
186
+ if (task.executions.length === 0) {
187
+ return { refusal: 'not-executed', message: `task ${task.id} has never executed, so it has no session to deliver to` }
188
+ }
189
+ const open = [...task.executions].reverse().find(record => record.endedAt === undefined)
190
+ if (open !== undefined) {
191
+ return open.sessionId === undefined
192
+ ? { refusal: 'session-unreachable', message: `the current execution of task ${task.id} has not attached a session yet` }
193
+ : { sessionId: open.sessionId }
194
+ }
195
+ const settled = [...task.executions].reverse().find(record => record.sessionId !== undefined)
196
+ return settled?.sessionId === undefined
197
+ ? { refusal: 'session-unreachable', message: `task ${task.id} records no execution session to deliver to` }
198
+ : { sessionId: settled.sessionId }
199
+ }
200
+
140
201
  export class TaskBoardExtensionRegistry {
141
202
  private readonly entries = new Map<string, RegistryEntry>()
142
203
  private readonly ledger: HostTaskLedger
143
204
  private readonly applyAction: TaskBoardActionApplier | undefined
205
+ private readonly followUpDelivery: TaskBoardFollowUpDelivery | undefined
206
+ private readonly reworkApply: TaskBoardReworkApplier | undefined
144
207
  private readonly now: () => number
145
208
  private readonly uuid: () => string
146
209
  private readonly logger: TaskBoardExtensionLogger
@@ -152,6 +215,8 @@ export class TaskBoardExtensionRegistry {
152
215
  constructor(options: TaskBoardExtensionRegistryOptions) {
153
216
  this.ledger = options.ledger
154
217
  this.applyAction = options.apply
218
+ this.followUpDelivery = options.followUp
219
+ this.reworkApply = options.rework
155
220
  this.now = options.now ?? Date.now
156
221
  this.uuid = options.uuid ?? (() => crypto.randomUUID())
157
222
  this.logger = options.logger ?? DEFAULT_LOGGER
@@ -381,6 +446,10 @@ export class TaskBoardExtensionRegistry {
381
446
  patchContent: (taskId, patch) => this.patchContent(entry, taskId, patch),
382
447
  setStatus: (taskId, status, initiator) => this.setStatus(entry, taskId, status, initiator),
383
448
  linked: () => this.linkedTasks(entry),
449
+ rework: (taskId, instructions, initiator) => { this.rework(entry, taskId, instructions, initiator) },
450
+ }
451
+ const sessions: TaskBoardSessionsFace = {
452
+ followUp: async (taskId, text) => { await this.followUp(entry, taskId, text) },
384
453
  }
385
454
  const integration: TaskBoardIntegrationFace = {
386
455
  read: (taskId) => {
@@ -396,6 +465,7 @@ export class TaskBoardExtensionRegistry {
396
465
  }
397
466
  return {
398
467
  tasks,
468
+ sessions,
399
469
  integration,
400
470
  events,
401
471
  publish: (summary) => { this.publish(entry, summary) },
@@ -403,7 +473,7 @@ export class TaskBoardExtensionRegistry {
403
473
  }
404
474
  }
405
475
 
406
- private createTask(entry: RegistryEntry, draft: { title: string; description: string; prompt: string; status?: TaskStatus; parentId?: string; workspaceId?: string }, options?: TaskBoardCreateOptions): TaskRecord {
476
+ private createTask(entry: RegistryEntry, draft: TaskBoardTaskDraft, options?: TaskBoardCreateOptions): TaskRecord {
407
477
  this.assertActive(entry, 'create a task')
408
478
  if (this.applyAction === undefined) throw new TaskBoardExtensionError('unavailable', 'this deployment serves no action applier')
409
479
  if (draft.status !== undefined && !isTaskStatus(draft.status)) throw new TaskBoardExtensionError('invalid-status', 'unknown task status')
@@ -422,6 +492,14 @@ export class TaskBoardExtensionRegistry {
422
492
  ...(draft.status === undefined ? {} : { status: draft.status }),
423
493
  ...(draft.parentId === undefined ? {} : { parentId: draft.parentId }),
424
494
  ...(draft.workspaceId === undefined ? {} : { workspaceId: draft.workspaceId }),
495
+ // Execution targets travel to the board's own creation path verbatim:
496
+ // what the caller sent wins there, the parent's pins fill the rest, and
497
+ // the board's new-card defaults stay out of it (this face never opts
498
+ // into them). Validating preset or route existence is the RUN's job, so
499
+ // an unknown value fails closed at launch instead of being judged here.
500
+ ...(draft.mode === undefined ? {} : { mode: draft.mode }),
501
+ ...(draft.model === undefined ? {} : { model: draft.model }),
502
+ ...(draft.reasoningEffort === undefined ? {} : { reasoningEffort: draft.reasoningEffort }),
425
503
  ...(payload === undefined ? {} : { integrations: { [entry.extension.id]: payload } }),
426
504
  ...(options?.hidden === true ? { hidden: true } : {}),
427
505
  },
@@ -434,8 +512,7 @@ export class TaskBoardExtensionRegistry {
434
512
  private patchContent(entry: RegistryEntry, taskId: string, patch: { title?: string; description?: string; prompt?: string }): void {
435
513
  this.assertActive(entry, 'patch content')
436
514
  if (this.applyAction === undefined) throw new TaskBoardExtensionError('unavailable', 'this deployment serves no action applier')
437
- const task = this.ledger.getTask(taskId)
438
- if (task === undefined) throw new TaskBoardExtensionError('task-not-found', `no task with id ${taskId}`)
515
+ const task = this.requireTask(taskId)
439
516
  // The board's own content authority: an executed (or archived) card keeps
440
517
  // the title/description/prompt that were actually planned and run.
441
518
  if (!canEditTaskContent(task)) throw new TaskBoardExtensionError('content-frozen', `task ${taskId} has started executing; its content is read-only`)
@@ -453,6 +530,75 @@ export class TaskBoardExtensionRegistry {
453
530
  this.applyAction({ kind: 'move', taskId, status }, initiator)
454
531
  }
455
532
 
533
+ /**
534
+ * Queue one follow-up message into the session of a card's current or most
535
+ * recent execution.
536
+ *
537
+ * A running card is the point of the capability, so an open execution is not
538
+ * a refusal: the message is queued behind the turn that is already going. What
539
+ * IS refused is a card with no conversation to deliver into, and a session
540
+ * this Host no longer reaches — the delivery refuses, and that refusal must
541
+ * reach the provider as such instead of looking like a silent success.
542
+ */
543
+ private async followUp(entry: RegistryEntry, taskId: string, text: string): Promise<void> {
544
+ this.assertActive(entry, 'deliver a follow-up message')
545
+ const task = this.requireTask(taskId)
546
+ const message = extensionText(text, 'follow-up message')
547
+ if (task.archivedAt !== undefined) {
548
+ throw new TaskBoardExtensionError('task-archived', `task ${taskId} is archived; an archived card's execution is closed`)
549
+ }
550
+ const target = followUpTarget(task)
551
+ if ('refusal' in target) throw new TaskBoardExtensionError(target.refusal, target.message)
552
+ if (this.followUpDelivery === undefined) {
553
+ throw new TaskBoardExtensionError('unavailable', 'this deployment serves no session delivery')
554
+ }
555
+ try {
556
+ await this.followUpDelivery(target.sessionId, message)
557
+ } catch (error) {
558
+ throw new TaskBoardExtensionError(
559
+ 'session-unreachable',
560
+ `session ${target.sessionId} of task ${taskId} did not accept the message: ${failureText(error)}`,
561
+ )
562
+ }
563
+ }
564
+
565
+ /**
566
+ * Re-run an executed card in its own session with rework instructions.
567
+ *
568
+ * The registry decides only what it can read from the ledger — the card
569
+ * exists, is not archived, is not running, and has a conversation to continue
570
+ * — and then hands the request to the board's own run path, so the running
571
+ * lock, the permission confirmation, the acceptance contract and the spend cap
572
+ * keep judging it. A board refusal surfaces unchanged, exactly as it does for
573
+ * {@link setStatus}, because those are the board's own words.
574
+ */
575
+ private rework(entry: RegistryEntry, taskId: string, instructions: string, initiator?: string): void {
576
+ this.assertActive(entry, 'rework a task')
577
+ if (this.reworkApply === undefined) throw new TaskBoardExtensionError('unavailable', 'this deployment serves no rework applier')
578
+ const task = this.requireTask(taskId)
579
+ const text = extensionText(instructions, 'rework instructions')
580
+ if (task.archivedAt !== undefined) {
581
+ throw new TaskBoardExtensionError('task-archived', `task ${taskId} is archived; an archived card is read-only`)
582
+ }
583
+ if (task.executions.some(record => record.endedAt === undefined)) {
584
+ throw new TaskBoardExtensionError('running', `task ${taskId} is still running; a card is reworked once its run settles`)
585
+ }
586
+ if (task.executions.length === 0) {
587
+ throw new TaskBoardExtensionError('not-executed', `task ${taskId} has never executed, so there is no run to rework`)
588
+ }
589
+ if (!task.executions.some(record => record.sessionId !== undefined)) {
590
+ throw new TaskBoardExtensionError('session-unreachable', `task ${taskId} records no execution session to continue`)
591
+ }
592
+ this.reworkApply(taskId, text, initiator)
593
+ }
594
+
595
+ /** One task by id, or the refusal that names the unknown id. */
596
+ private requireTask(taskId: string): TaskRecord {
597
+ const task = this.ledger.getTask(taskId)
598
+ if (task === undefined) throw new TaskBoardExtensionError('task-not-found', `no task with id ${taskId}`)
599
+ return task
600
+ }
601
+
456
602
  private linkedTasks(entry: RegistryEntry): readonly TaskBoardLinkedTask[] {
457
603
  const id = entry.extension.id
458
604
  const result: TaskBoardLinkedTask[] = []
@@ -469,8 +615,7 @@ export class TaskBoardExtensionRegistry {
469
615
  if (!isTaskBoardExtensionPayload(payload)) {
470
616
  throw new TaskBoardExtensionError('invalid-payload', 'integration payload must be a pure JSON object within the size limit')
471
617
  }
472
- const task = this.ledger.getTask(taskId)
473
- if (task === undefined) throw new TaskBoardExtensionError('task-not-found', `no task with id ${taskId}`)
618
+ const task = this.requireTask(taskId)
474
619
  const id = entry.extension.id
475
620
  const next = mergePayload(readPayload(task.integrations?.[id]), payload)
476
621
  if (!isTaskBoardExtensionPayload(next)) {
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Admission control for the session-creating half of a run.
3
+ *
4
+ * A run opens one session, so the burst this bounds is several runs starting at
5
+ * once — several cards run from different tabs, or a due schedule firing while
6
+ * a manual run is still launching. Unbounded, the Host asks DSH for N sessions
7
+ * in the same tick: the burst the repository's measured guidance caps at three
8
+ * heavy implementation subagents (docs/multi-agent-resources.md), with no
9
+ * mechanism enforcing it.
10
+ *
11
+ * The queue is SERVICE-wide, not per run group: the pressure it bounds is the
12
+ * machine's (the Host process's memory and the swap it drives), and two run
13
+ * groups opened from two tabs share one Host. Admission is round-robin across
14
+ * run groups — FIFO inside a group — so one run cannot starve another opened
15
+ * after it, and no entry can be starved.
16
+ *
17
+ * The width is read through a live callback, so a settings edit takes effect on
18
+ * the next admission without remounting anything.
19
+ *
20
+ * @module dsh-task-board/host/launch-admission
21
+ */
22
+
23
+ /** One launch the queue has not started yet. */
24
+ export interface QueuedLaunch {
25
+ /** Run group this launch belongs to; the unit of round-robin fairness. */
26
+ readonly groupId: string
27
+ /**
28
+ * Perform the launch. The slot is held until this promise settles, which
29
+ * makes "in flight" mean "still creating and prompting its session".
30
+ * A rejection is swallowed here so one broken launch can never wedge the
31
+ * slot; the caller owns reporting.
32
+ */
33
+ start(): Promise<void>
34
+ /**
35
+ * Called by {@link LaunchAdmissionQueue.drain} for a launch that never
36
+ * started, so the caller can take its execution out of the running column.
37
+ */
38
+ abandon(): void
39
+ }
40
+
41
+ export class LaunchAdmissionQueue {
42
+ /** Waiting launches per run group, in arrival order. */
43
+ private readonly waiting = new Map<string, QueuedLaunch[]>()
44
+ /** Run groups in round-robin order. */
45
+ private rotation: string[] = []
46
+ /** Slot holders of the launches in flight, one per admitted launch. */
47
+ private readonly inFlight = new Set<() => void>()
48
+ /** Highest number of launches in flight at once; observability and tests. */
49
+ peakInFlight = 0
50
+
51
+ /**
52
+ * @param width - live admission width (already normalized by the caller).
53
+ */
54
+ constructor(private readonly width: () => number) {}
55
+
56
+ /** Launches the queue has not admitted yet. */
57
+ get pendingCount(): number {
58
+ let total = 0
59
+ for (const queue of this.waiting.values()) total += queue.length
60
+ return total
61
+ }
62
+
63
+ /** Launches currently holding a slot. */
64
+ get inFlightCount(): number {
65
+ return this.inFlight.size
66
+ }
67
+
68
+ /** Admit one launch, immediately if a slot is free. */
69
+ enqueue(launch: QueuedLaunch): void {
70
+ const queue = this.waiting.get(launch.groupId)
71
+ if (queue === undefined) {
72
+ this.waiting.set(launch.groupId, [launch])
73
+ this.rotation.push(launch.groupId)
74
+ } else {
75
+ queue.push(launch)
76
+ }
77
+ this.pump()
78
+ }
79
+
80
+ /**
81
+ * Abandon every waiting launch: the queue is being torn down, so an entry
82
+ * that never started can never start. Launches already in flight are left
83
+ * alone — their session may already exist, and the callers that own them
84
+ * settle them through the normal path.
85
+ * @returns the abandoned launches, in abandonment order.
86
+ */
87
+ drain(): QueuedLaunch[] {
88
+ const abandoned: QueuedLaunch[] = []
89
+ for (const groupId of this.rotation) {
90
+ for (const launch of this.waiting.get(groupId) ?? []) abandoned.push(launch)
91
+ }
92
+ this.rotation = []
93
+ this.waiting.clear()
94
+ for (const launch of abandoned) launch.abandon()
95
+ return abandoned
96
+ }
97
+
98
+ private pump(): void {
99
+ while (this.inFlight.size < this.width()) {
100
+ const launch = this.takeNext()
101
+ if (launch === undefined) return
102
+ this.admit(launch)
103
+ }
104
+ }
105
+
106
+ /** The next launch by round-robin across groups and FIFO inside one. */
107
+ private takeNext(): QueuedLaunch | undefined {
108
+ while (this.rotation.length > 0) {
109
+ const groupId = this.rotation.shift()
110
+ if (groupId === undefined) return undefined
111
+ const queue = this.waiting.get(groupId)
112
+ if (queue === undefined || queue.length === 0) {
113
+ this.waiting.delete(groupId)
114
+ continue
115
+ }
116
+ const launch = queue.shift()
117
+ if (launch === undefined) continue
118
+ if (queue.length === 0) this.waiting.delete(groupId)
119
+ // A group that still has work goes to the back of the rotation, so every
120
+ // other run group gets its turn before this one's next member.
121
+ else this.rotation.push(groupId)
122
+ return launch
123
+ }
124
+ return undefined
125
+ }
126
+
127
+ private admit(launch: QueuedLaunch): void {
128
+ const release = (): void => {
129
+ this.inFlight.delete(release)
130
+ this.pump()
131
+ }
132
+ this.inFlight.add(release)
133
+ if (this.inFlight.size > this.peakInFlight) this.peakInFlight = this.inFlight.size
134
+ void Promise.resolve()
135
+ .then(() => launch.start())
136
+ .catch(() => { /* a rejected launch still releases its slot; the caller reports it */ })
137
+ .then(release)
138
+ }
139
+ }