@quazardous/qdadm 2.47.0 → 2.49.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 (35) hide show
  1. package/dist/styles/qdadm.css +1 -1
  2. package/package.json +1 -1
  3. package/src/chain/StackHydrator.ts +82 -0
  4. package/src/components/index.ts +3 -0
  5. package/src/components/layout/EntityItemLayout.vue +120 -0
  6. package/src/components/layout/PageNav.vue +24 -2
  7. package/src/components/tasks/TaskDialog.vue +13 -157
  8. package/src/components/tasks/TaskHost.vue +15 -2
  9. package/src/components/tasks/TaskRunView.vue +197 -0
  10. package/src/components/tasks/TaskSequenceDialog.vue +157 -0
  11. package/src/components/tasks/TaskTray.vue +33 -13
  12. package/src/composables/useLiveEntity.ts +3 -1
  13. package/src/composables/useNavigation.ts +3 -4
  14. package/src/entity/EntityManager.cache.ts +49 -8
  15. package/src/entity/EntityManager.interface.ts +6 -0
  16. package/src/entity/EntityManager.ts +8 -0
  17. package/src/i18n/defaults/core.en.generated.ts +13 -0
  18. package/src/i18n/defaults/core.en.yml +13 -0
  19. package/src/i18n/defaults/core.fr.generated.ts +13 -0
  20. package/src/i18n/defaults/core.fr.yml +13 -0
  21. package/src/index.ts +7 -0
  22. package/src/kernel/Kernel.routing.ts +22 -31
  23. package/src/kernel/KernelContext.routing.ts +9 -0
  24. package/src/kernel/KernelContext.ts +3 -0
  25. package/src/kernel/KernelContext.types.ts +6 -0
  26. package/src/kernel/itemTabs.ts +99 -0
  27. package/src/module/moduleRegistry.ts +26 -0
  28. package/src/security/index.ts +1 -0
  29. package/src/security/routeAccess.ts +94 -0
  30. package/src/styles/_item-tabs.scss +52 -0
  31. package/src/styles/_tasks.scss +102 -0
  32. package/src/styles/index.scss +1 -0
  33. package/src/tasks/taskStore.ts +503 -14
  34. package/src/tasks/useTaskNotifications.ts +6 -2
  35. package/src/tasks/useTaskRunner.ts +15 -1
@@ -43,6 +43,16 @@ export interface TaskFollow {
43
43
  intervalMs?: number
44
44
  }
45
45
 
46
+ /**
47
+ * A record (or a whole entity) a task changes, read again when it ends (#4961):
48
+ * `id` is a value, a function of the run (or of the sequence), or absent for
49
+ * the whole entity.
50
+ */
51
+ export interface TaskInvalidate<S = TaskRun> {
52
+ entity: string
53
+ id?: string | number | null | ((subject: S) => string | number | null | undefined)
54
+ }
55
+
46
56
  /** What a kind of task shares, whatever starts it: registered once, it lets runs resume after a reload. */
47
57
  export interface TaskKind {
48
58
  label?: string
@@ -57,6 +67,18 @@ export interface TaskKind {
57
67
  notify?: boolean
58
68
  /** Called once the run ends, whatever the outcome (read `run.status`). */
59
69
  onSettled?: (run: TaskRun) => void
70
+ /**
71
+ * What the run changes, read again when it ends, whatever the outcome
72
+ * (#4961). A run's own list adds to its kind's.
73
+ */
74
+ invalidates?: TaskInvalidate<TaskRun>[]
75
+ /**
76
+ * Awaited before `invalidates` apply: for a backend that is still refreshing
77
+ * what the task changed once the task itself has ended.
78
+ */
79
+ ready?: (run: TaskRun) => unknown
80
+ /** How long `ready` may take before the invalidation goes ahead anyway. Default 30 000 ms. */
81
+ readyTimeoutMs?: number
60
82
  /** The follow dialog's window options for this kind, over the app's (#4334). */
61
83
  dialog?: TaskDialogOptions
62
84
  /** What the log flags as an error or a timestamp for this kind, over the app's (#4386). */
@@ -72,6 +94,13 @@ export interface TaskKind {
72
94
  slots?: TaskUiOptions['slots']
73
95
  /** A dialog of its own for this kind, instead of TaskDialog. */
74
96
  component?: TaskUiOptions['component']
97
+ /**
98
+ * Start a task of this kind from its meta alone. With it, `run({ kind, meta })`
99
+ * needs no `start`, and a sequence of such kinds goes on after a reload (#4934).
100
+ */
101
+ start?: (meta: Record<string, unknown> | null) => Promise<unknown>
102
+ /** A run's line in a sequence's list (#4934). Default: the error, else the step. */
103
+ summary?: (run: TaskRun) => string | null | undefined
75
104
  }
76
105
 
77
106
  export interface TaskConfirm {
@@ -84,11 +113,15 @@ export interface TaskConfirm {
84
113
  severity?: 'primary' | 'secondary' | 'success' | 'info' | 'warn' | 'danger' | 'contrast'
85
114
  }
86
115
 
87
- export interface RunOptions extends Omit<Partial<TaskKind>, 'label'> {
116
+ export interface RunOptions extends Omit<Partial<TaskKind>, 'label' | 'start'> {
88
117
  /** A string, or a function read each time it shows (tray, dialog, toast), so it follows the locale (#4692) */
89
118
  label: string | (() => string)
90
- /** Queue the task; returns its id, or `{ task_id | taskId | id }`. */
91
- start: () => Promise<unknown>
119
+ /**
120
+ * Queue the task; returns its id, or `{ task_id | taskId | id }`. In a
121
+ * sequence it gets the previous step's run (#4934). Optional when the kind
122
+ * has a `start`.
123
+ */
124
+ start?: (previous: TaskRun | null) => Promise<unknown>
92
125
  /** A registered kind; its settings are the defaults of this run, and the run resumes after a reload. */
93
126
  kind?: string
94
127
  confirm?: TaskConfirm
@@ -116,16 +149,74 @@ export interface TaskRun {
116
149
  cancelling: boolean
117
150
  /** What the run is about, as given to run() (#4687) */
118
151
  meta: Record<string, unknown> | null
152
+ /** The sequence this run is a step of, or null (#4934) */
153
+ sequenceId: string | null
119
154
  /** Settles with the run once it ends: succeeded, failed or cancelled (it never rejects). */
120
155
  finished: Promise<TaskRun>
121
156
  }
122
157
 
158
+ /** A step of a sequence: run options, or a function of the previous step's run that returns them (#4934). */
159
+ export type SequenceStep = RunOptions | ((previous: TaskRun | null) => RunOptions)
160
+
161
+ export interface SequenceOptions {
162
+ /** A failure stops the steps that follow (they show "not run"). Default true. */
163
+ stopOnError?: boolean
164
+ /** Open the sequence's window at once. Default true. */
165
+ open?: boolean
166
+ /** Asked once, before the first step. */
167
+ confirm?: TaskConfirm
168
+ /** What the sequence is about, for a page to find it again (sequenceFor). Plain values only. */
169
+ meta?: Record<string, unknown>
170
+ /** One toast when it ends. Default true. */
171
+ notify?: boolean
172
+ /** Called once the sequence ends. */
173
+ onSettled?: (sequence: TaskSequence) => void
174
+ /** What the sequence changes, read again when it ends (#4961); each step's own apply as it ends. */
175
+ invalidates?: TaskInvalidate<TaskSequence>[]
176
+ /** Awaited before the sequence's `invalidates` apply. */
177
+ ready?: (sequence: TaskSequence) => unknown
178
+ /** How long `ready` may take. Default 30 000 ms. */
179
+ readyTimeoutMs?: number
180
+ }
181
+
182
+ /** A step that has no run: waiting its turn, or never run (and why). */
183
+ export type SequenceStepStatus = TaskStatus | 'pending' | 'skipped'
184
+
185
+ export interface TaskSequenceStep {
186
+ /** The run's label once started, else the declared one ("Step 2" for a step given as a function) */
187
+ label: string
188
+ runId: string | null
189
+ /** The state recorded: pending, skipped, or the run's once it ended. Live: `store.stepStatus(step)` */
190
+ status: SequenceStepStatus
191
+ /** Why a step was not run: an earlier step failed, the sequence was cancelled, the page was reloaded */
192
+ skipped: 'error' | 'cancelled' | 'reload' | null
193
+ }
194
+
195
+ export interface TaskSequence {
196
+ id: string
197
+ label: string
198
+ status: 'running' | 'succeeded' | 'failed' | 'cancelled'
199
+ steps: TaskSequenceStep[]
200
+ /** The index of the step running, or of the last one run */
201
+ current: number
202
+ stopOnError: boolean
203
+ cancelling: boolean
204
+ startedAt: number
205
+ endedAt: number | null
206
+ meta: Record<string, unknown> | null
207
+ /** Settles with the sequence once it ends (it never rejects). */
208
+ finished: Promise<TaskSequence>
209
+ }
210
+
123
211
  interface TaskHostDeps {
124
212
  orchestrator?: {
125
213
  get: (name: string) => unknown
126
214
  toast?: Record<'success' | 'error' | 'warn' | 'info', (summary: string, detail?: string, options?: unknown) => void>
127
215
  } | null
128
- signals?: { on: (name: string, handler: (event: { data: unknown }) => void) => () => void } | null
216
+ signals?: {
217
+ on: (name: string, handler: (event: { data: unknown }) => void) => () => void
218
+ emit?: (name: string, data?: unknown) => unknown
219
+ } | null
129
220
  }
130
221
 
131
222
  interface PendingConfirm {
@@ -135,7 +226,9 @@ interface PendingConfirm {
135
226
  }
136
227
 
137
228
  const FINAL: TaskStatus[] = ['succeeded', 'failed', 'cancelled']
229
+ const READY_TIMEOUT_MS = 30_000
138
230
  const STORAGE_KEY = 'qdadm:tasks'
231
+ const SEQUENCES_KEY = 'qdadm:task-sequences'
139
232
  const KEEP_FINISHED = 20
140
233
 
141
234
  const USUAL: Record<string, Exclude<TaskStatus, 'starting'>> = {
@@ -173,6 +266,9 @@ function errorText(err: unknown): string {
173
266
  function createTaskStore() {
174
267
  const state = reactive({
175
268
  runs: [] as TaskRun[],
269
+ /** Runs chained in one window (#4934) */
270
+ sequences: [] as TaskSequence[],
271
+ /** The run or the sequence whose window is open */
176
272
  openId: null as string | null,
177
273
  pendingConfirm: null as PendingConfirm | null,
178
274
  hosts: 0,
@@ -191,7 +287,7 @@ function createTaskStore() {
191
287
  try {
192
288
  const saved = state.runs
193
289
  .filter((r) => r.kind && kinds.has(r.kind) && r.taskId !== null && !FINAL.includes(r.status))
194
- .map((r) => ({ id: r.id, kind: r.kind, label: r.label, taskId: r.taskId, startedAt: r.startedAt, meta: r.meta }))
290
+ .map((r) => ({ id: r.id, kind: r.kind, label: r.label, taskId: r.taskId, startedAt: r.startedAt, meta: r.meta, sequenceId: r.sequenceId }))
195
291
  if (saved.length) sessionStorage.setItem(STORAGE_KEY, JSON.stringify(saved))
196
292
  else sessionStorage.removeItem(STORAGE_KEY)
197
293
  } catch {
@@ -202,7 +298,7 @@ function createTaskStore() {
202
298
  function restore(): void {
203
299
  if (restored) return
204
300
  restored = true
205
- let saved: Array<Pick<TaskRun, 'id' | 'kind' | 'label' | 'taskId' | 'startedAt'> & { meta?: TaskRun['meta'] }> = []
301
+ let saved: Array<Pick<TaskRun, 'id' | 'kind' | 'label' | 'taskId' | 'startedAt'> & { meta?: TaskRun['meta']; sequenceId?: string | null }> = []
206
302
  try {
207
303
  saved = JSON.parse(sessionStorage.getItem(STORAGE_KEY) ?? '[]')
208
304
  } catch {
@@ -211,10 +307,12 @@ function createTaskStore() {
211
307
  for (const s of saved) {
212
308
  const kind = s.kind ? kinds.get(s.kind) : undefined
213
309
  if (!kind || s.taskId === null || state.runs.some((r) => r.id === s.id)) continue
214
- const run = addRun({ id: s.id, kind: s.kind, label: s.label, taskId: s.taskId, status: 'running', startedAt: s.startedAt, meta: s.meta ?? null })
215
- defs.set(run.id, kind)
310
+ const run = addRun({ id: s.id, kind: s.kind, label: s.label, taskId: s.taskId, status: 'running', startedAt: s.startedAt, meta: s.meta ?? null, sequenceId: s.sequenceId ?? null })
311
+ // A step of a sequence: the sequence gives the one toast
312
+ defs.set(run.id, s.sequenceId ? { ...kind, notify: false } : kind)
216
313
  follow(run.id)
217
314
  }
315
+ restoreSequences()
218
316
  }
219
317
 
220
318
  // --- Runs ---
@@ -235,6 +333,7 @@ function createTaskStore() {
235
333
  endedAt: null,
236
334
  cancelling: false,
237
335
  meta: partial.meta ?? null,
336
+ sequenceId: partial.sequenceId ?? null,
238
337
  // A promise is not made reactive: run.finished stays the raw promise.
239
338
  finished: new Promise<TaskRun>((resolve) => settles.set(id, resolve)),
240
339
  }
@@ -263,11 +362,65 @@ function createTaskStore() {
263
362
  notifyEnd(run)
264
363
  settles.get(id)?.(run)
265
364
  settles.delete(id)
365
+ const def = defs.get(id)
266
366
  try {
267
- defs.get(id)?.onSettled?.(run)
367
+ def?.onSettled?.(run)
268
368
  } catch (err) {
269
369
  console.error(`[qdadm] Task "${run.label}": onSettled threw`, err)
270
370
  }
371
+ emit('task:settled', { run, kind: run.kind, status: run.status, meta: run.meta })
372
+ void applyInvalidates(def, run, `Task "${run.label}"`)
373
+ }
374
+
375
+ function emit(name: string, data: unknown): void {
376
+ try {
377
+ void deps.signals?.emit?.(name, data)
378
+ } catch (err) {
379
+ console.error(`[qdadm] ${name}: a listener threw`, err)
380
+ }
381
+ }
382
+
383
+ /**
384
+ * Read again what a run or a sequence changed (#4961): once `ready` settles
385
+ * (or times out, or fails: a view a little early beats one never refreshed),
386
+ * each target's manager drops it and the views showing it reload.
387
+ */
388
+ async function applyInvalidates<S>(
389
+ source: { invalidates?: TaskInvalidate<S>[]; ready?: (subject: S) => unknown; readyTimeoutMs?: number } | undefined,
390
+ subject: S,
391
+ what: string
392
+ ): Promise<void> {
393
+ const targets = source?.invalidates
394
+ if (!targets?.length) return
395
+ if (source!.ready) {
396
+ const ms = source!.readyTimeoutMs ?? READY_TIMEOUT_MS
397
+ let timer: ReturnType<typeof setTimeout> | undefined
398
+ try {
399
+ await Promise.race([
400
+ Promise.resolve().then(() => source!.ready!(subject)),
401
+ new Promise((_, reject) => {
402
+ timer = setTimeout(() => reject(new Error(`not ready after ${ms} ms`)), ms)
403
+ }),
404
+ ])
405
+ } catch (err) {
406
+ console.warn(`[qdadm] ${what}: ready failed, invalidating anyway —`, errorText(err))
407
+ } finally {
408
+ if (timer) clearTimeout(timer)
409
+ }
410
+ }
411
+ for (const target of targets) {
412
+ try {
413
+ const id = typeof target.id === 'function' ? target.id(subject) : target.id
414
+ const manager = deps.orchestrator?.get(target.entity) as { invalidate?: (id?: string | number | null) => void } | null | undefined
415
+ if (typeof manager?.invalidate !== 'function') {
416
+ console.warn(`[qdadm] ${what}: cannot invalidate "${target.entity}", no such entity`)
417
+ continue
418
+ }
419
+ manager.invalidate(id ?? undefined)
420
+ } catch (err) {
421
+ console.warn(`[qdadm] ${what}: invalidating "${target.entity}" failed —`, errorText(err))
422
+ }
423
+ }
271
424
  }
272
425
 
273
426
  function notifyEnd(run: TaskRun): void {
@@ -400,20 +553,33 @@ function createTaskStore() {
400
553
  * pass `onSettled`) for its outcome.
401
554
  */
402
555
  async function run(options: RunOptions): Promise<TaskRun | null> {
556
+ return startRun(options, {})
557
+ }
558
+
559
+ async function startRun(options: RunOptions, ctx: { previous?: TaskRun | null; sequenceId?: string }): Promise<TaskRun | null> {
403
560
  const base = options.kind ? kinds.get(options.kind) : undefined
404
561
  if (options.kind && !base && !options.task) {
405
562
  throw new Error(`TaskRunner: unknown task kind "${options.kind}"`)
406
563
  }
407
564
  const def: TaskKind = { ...base, ...options, task: { ...base?.task, ...options.task } } as TaskKind
565
+ // A run's targets add to its kind's
566
+ if (base?.invalidates?.length && options.invalidates?.length) def.invalidates = [...base.invalidates, ...options.invalidates]
408
567
  const labelOf = typeof options.label === 'function' ? options.label : undefined
409
568
  const label = labelOf ? labelOf() : (options.label as string)
569
+ const meta = options.meta ? { ...options.meta } : null
570
+ const start = options.start
571
+ ? () => options.start!(ctx.previous ?? null)
572
+ : base?.start
573
+ ? () => base.start!(meta)
574
+ : null
575
+ if (!start) throw new Error(`TaskRunner: "${label}" has no start, and its kind none either`)
410
576
  if (options.confirm && !(await requestConfirm(label, options.confirm))) return null
411
577
 
412
- const r = addRun({ label, kind: options.kind ?? null, meta: options.meta ? { ...options.meta } : null }, labelOf)
578
+ const r = addRun({ label, kind: options.kind ?? null, meta, sequenceId: ctx.sequenceId ?? null }, labelOf)
413
579
  defs.set(r.id, def)
414
580
  if (options.open !== false) state.openId = r.id
415
581
  try {
416
- const taskId = taskIdOf(await options.start())
582
+ const taskId = taskIdOf(await start())
417
583
  if (taskId === null) throw new Error('the start handler returned no task id')
418
584
  const current = find(r.id)!
419
585
  current.taskId = taskId
@@ -454,6 +620,7 @@ function createTaskStore() {
454
620
 
455
621
  function clearFinished(): void {
456
622
  for (const r of state.runs.filter((x) => FINAL.includes(x.status))) dismiss(r.id)
623
+ for (const x of state.sequences.filter((x) => x.status !== 'running')) dismissSequence(x.id)
457
624
  }
458
625
 
459
626
  /** Wire the orchestrator (manager reads, toasts) and the signal bus (live). Called by useTaskRunner. */
@@ -465,6 +632,315 @@ function createTaskStore() {
465
632
 
466
633
  const active: ComputedRef<TaskRun[]> = computed(() => state.runs.filter((r) => !FINAL.includes(r.status)))
467
634
 
635
+ // --- Sequences: runs chained in one window (#4934) ---
636
+
637
+ interface SequenceInternals {
638
+ /** Each step's options; null for a step that cannot start again after a reload */
639
+ specs: Array<SequenceStep | null>
640
+ options: SequenceOptions
641
+ /** One step only: it is a plain run, with its own window and toast */
642
+ single: boolean
643
+ settle: (sequence: TaskSequence) => void
644
+ }
645
+ const sequenceInternals = new Map<string, SequenceInternals>()
646
+ let sequenceSeq = 0
647
+
648
+ const findSequence = (id: string) => state.sequences.find((s) => s.id === id)
649
+
650
+ /** A step's state: its run's while the run is in the store, else what was recorded */
651
+ function stepStatus(step: TaskSequenceStep): SequenceStepStatus {
652
+ const run = step.runId ? find(step.runId) : undefined
653
+ return run?.status ?? step.status ?? 'pending'
654
+ }
655
+
656
+ /** What the list shows on a step's line: the kind's summary, else the error, else the step reached */
657
+ function stepSummary(step: TaskSequenceStep): string | null {
658
+ const run = step.runId ? find(step.runId) : undefined
659
+ if (!run) return null
660
+ const custom = defs.get(run.id)?.summary
661
+ if (custom) {
662
+ try {
663
+ const text = custom(run)
664
+ if (text !== undefined) return text
665
+ } catch (err) {
666
+ console.error(`[qdadm] Task "${run.label}": summary threw`, err)
667
+ }
668
+ }
669
+ if (run.status === 'failed') return run.error
670
+ if (run.status === 'succeeded' && run.result !== null && typeof run.result !== 'object') return String(run.result)
671
+ return run.step
672
+ }
673
+
674
+ const declaredLabel = (spec: SequenceStep | null | undefined): string | (() => string) =>
675
+ !spec || typeof spec === 'function' ? '' : spec.label
676
+
677
+ function addSequence(
678
+ partial: Pick<TaskSequence, 'label' | 'stopOnError' | 'meta'> & Partial<Pick<TaskSequence, 'id' | 'startedAt' | 'current' | 'cancelling'>>,
679
+ steps: Array<{ label: string | (() => string); runId?: string | null; status?: SequenceStepStatus; skipped?: TaskSequenceStep['skipped'] }>,
680
+ internals: Omit<SequenceInternals, 'settle'>,
681
+ labelOf?: () => string
682
+ ): TaskSequence {
683
+ const id = partial.id ?? `seq-${Date.now().toString(36)}-${++sequenceSeq}`
684
+ let settle!: (sequence: TaskSequence) => void
685
+ const sequence: TaskSequence = {
686
+ id,
687
+ label: partial.label,
688
+ status: 'running',
689
+ steps: steps.map((st) => {
690
+ const declared = st.label
691
+ return {
692
+ runId: st.runId ?? null,
693
+ status: st.status ?? 'pending',
694
+ skipped: st.skipped ?? null,
695
+ // The run's label once started (it follows the locale), else the declared one
696
+ get label(): string {
697
+ const run = this.runId ? find(this.runId) : undefined
698
+ if (run) return run.label
699
+ return typeof declared === 'function' ? declared() : declared
700
+ },
701
+ } as TaskSequenceStep
702
+ }),
703
+ current: partial.current ?? 0,
704
+ stopOnError: partial.stopOnError,
705
+ cancelling: partial.cancelling ?? false,
706
+ startedAt: partial.startedAt ?? Date.now(),
707
+ endedAt: null,
708
+ meta: partial.meta,
709
+ finished: new Promise<TaskSequence>((resolve) => (settle = resolve)),
710
+ }
711
+ if (labelOf) Object.defineProperty(sequence, 'label', { get: labelOf, enumerable: true, configurable: true })
712
+ sequenceInternals.set(id, { ...internals, settle })
713
+ state.sequences.unshift(sequence)
714
+ const finished = state.sequences.filter((x) => FINAL.includes(x.status as TaskStatus))
715
+ for (const old of finished.slice(KEEP_FINISHED)) dismissSequence(old.id)
716
+ return findSequence(id)!
717
+ }
718
+
719
+ function persistSequences(): void {
720
+ try {
721
+ const saved = state.sequences
722
+ .filter((x) => x.status === 'running' && !sequenceInternals.get(x.id)?.single)
723
+ .map((x) => {
724
+ const specs = sequenceInternals.get(x.id)?.specs ?? []
725
+ return {
726
+ id: x.id,
727
+ label: x.label,
728
+ meta: x.meta,
729
+ stopOnError: x.stopOnError,
730
+ startedAt: x.startedAt,
731
+ current: x.current,
732
+ cancelling: x.cancelling,
733
+ steps: x.steps.map((st, i) => {
734
+ const spec = specs[i]
735
+ const plain = spec && typeof spec !== 'function' ? spec : null
736
+ return { label: st.label, runId: st.runId, status: stepStatus(st), skipped: st.skipped, kind: plain?.kind ?? null, meta: plain?.meta ?? null }
737
+ }),
738
+ }
739
+ })
740
+ if (saved.length) sessionStorage.setItem(SEQUENCES_KEY, JSON.stringify(saved))
741
+ else sessionStorage.removeItem(SEQUENCES_KEY)
742
+ } catch {
743
+ // no storage: a sequence does not survive a reload
744
+ }
745
+ }
746
+
747
+ /** A sequence that was running before a reload: its running step was restored with the runs; the steps after it start again when their kind can */
748
+ function restoreSequences(): void {
749
+ type Saved = Pick<TaskSequence, 'id' | 'label' | 'meta' | 'stopOnError' | 'startedAt' | 'current' | 'cancelling'> & {
750
+ steps: Array<{ label: string; runId: string | null; status: SequenceStepStatus; skipped: TaskSequenceStep['skipped']; kind: string | null; meta: Record<string, unknown> | null }>
751
+ }
752
+ let saved: Saved[] = []
753
+ try {
754
+ saved = JSON.parse(sessionStorage.getItem(SEQUENCES_KEY) ?? '[]')
755
+ } catch {
756
+ return
757
+ }
758
+ for (const x of saved) {
759
+ if (findSequence(x.id)) continue
760
+ const specs = x.steps.map((st) => {
761
+ const kind = st.kind ? kinds.get(st.kind) : undefined
762
+ return kind?.start ? ({ kind: st.kind!, label: st.label, meta: st.meta ?? undefined } as RunOptions) : null
763
+ })
764
+ const steps = x.steps.map((st) => ({
765
+ label: st.label,
766
+ // A run that is not back (its kind is not registered) cannot be followed
767
+ runId: st.runId && find(st.runId) ? st.runId : null,
768
+ status: st.runId && !find(st.runId) && !FINAL.includes(st.status as TaskStatus) ? ('skipped' as const) : st.status,
769
+ skipped: st.runId && !find(st.runId) && !FINAL.includes(st.status as TaskStatus) ? ('reload' as const) : st.skipped,
770
+ }))
771
+ const sequence = addSequence(x, steps, { specs, options: {}, single: false })
772
+ const current = sequence.steps[sequence.current]
773
+ const previous = current?.runId ? find(current.runId) ?? null : null
774
+ void drive(sequence.id, previous)
775
+ }
776
+ }
777
+
778
+ function skipFrom(sequence: TaskSequence, index: number, why: NonNullable<TaskSequenceStep['skipped']>): void {
779
+ for (const step of sequence.steps.slice(index)) {
780
+ if (step.runId) continue
781
+ step.status = 'skipped'
782
+ step.skipped = why
783
+ }
784
+ }
785
+
786
+ /** Run the steps one after another, from the sequence's current one */
787
+ async function drive(id: string, previous: TaskRun | null): Promise<void> {
788
+ const internals = sequenceInternals.get(id)
789
+ if (!internals) return
790
+ let failed = false
791
+ for (let i = findSequence(id)?.current ?? 0; i < (findSequence(id)?.steps.length ?? 0); i++) {
792
+ const sequence = findSequence(id)
793
+ if (!sequence) return
794
+ const step = sequence.steps[i]!
795
+ if (step.status === 'skipped') continue
796
+ if (step.runId && FINAL.includes(stepStatus(step) as TaskStatus)) {
797
+ // Already over before a reload
798
+ failed ||= stepStatus(step) === 'failed'
799
+ continue
800
+ }
801
+ if (sequence.cancelling) {
802
+ skipFrom(sequence, i, 'cancelled')
803
+ break
804
+ }
805
+ if (failed && sequence.stopOnError) {
806
+ skipFrom(sequence, i, 'error')
807
+ break
808
+ }
809
+ sequence.current = i
810
+ let run: TaskRun | null = step.runId ? find(step.runId) ?? null : null
811
+ if (!run) {
812
+ const spec = internals.specs[i]
813
+ if (!spec) {
814
+ skipFrom(sequence, i, 'reload')
815
+ break
816
+ }
817
+ let options: RunOptions
818
+ try {
819
+ options = typeof spec === 'function' ? spec(previous) : spec
820
+ } catch (err) {
821
+ options = { label: step.label || `#${i + 1}`, start: () => Promise.reject(err), task: {} }
822
+ }
823
+ const stepOptions: RunOptions = {
824
+ ...options,
825
+ confirm: undefined,
826
+ open: internals.single ? internals.options.open !== false : false,
827
+ ...(internals.single ? {} : { notify: false }),
828
+ }
829
+ try {
830
+ run = await startRun(stepOptions, { previous, sequenceId: id })
831
+ } catch (err) {
832
+ run = await startRun({ label: options.label, start: () => Promise.reject(err), task: {}, open: false, notify: internals.single ? undefined : false }, { sequenceId: id })
833
+ }
834
+ if (!run) break
835
+ step.runId = run.id
836
+ persistSequences()
837
+ }
838
+ const end = await run.finished
839
+ step.status = end.status
840
+ if (end.status === 'failed') failed = true
841
+ if (end.status === 'cancelled') findSequence(id)!.cancelling = true
842
+ previous = end
843
+ persistSequences()
844
+ }
845
+ finishSequence(id)
846
+ }
847
+
848
+ function finishSequence(id: string): void {
849
+ const sequence = findSequence(id)
850
+ const internals = sequenceInternals.get(id)
851
+ if (!sequence || !internals || sequence.status !== 'running') return
852
+ const statuses = sequence.steps.map((st) => stepStatus(st))
853
+ sequence.status = statuses.includes('failed')
854
+ ? 'failed'
855
+ : statuses.some((st) => st === 'cancelled' || st === 'skipped')
856
+ ? 'cancelled'
857
+ : 'succeeded'
858
+ sequence.endedAt = Date.now()
859
+ sequence.cancelling = false
860
+ persistSequences()
861
+ if (!internals.single && internals.options.notify !== false) notifySequenceEnd(sequence)
862
+ internals.settle(sequence)
863
+ try {
864
+ internals.options.onSettled?.(sequence)
865
+ } catch (err) {
866
+ console.error(`[qdadm] Task sequence "${sequence.label}": onSettled threw`, err)
867
+ }
868
+ emit('task:sequence-settled', { sequence, status: sequence.status, meta: sequence.meta })
869
+ void applyInvalidates(internals.options, sequence, `Task sequence "${sequence.label}"`)
870
+ }
871
+
872
+ const MARKS: Partial<Record<SequenceStepStatus, string>> = { succeeded: '✓', failed: '✗', cancelled: '⊘', skipped: '–' }
873
+
874
+ /** One toast for the whole sequence: each step marked, the failure's error after it */
875
+ function notifySequenceEnd(sequence: TaskSequence): void {
876
+ const toast = deps.orchestrator?.toast
877
+ if (!toast) return
878
+ const detail = sequence.steps
879
+ .map((st, i) => {
880
+ const status = stepStatus(st)
881
+ const label = st.label || `#${i + 1}`
882
+ const error = status === 'failed' && st.runId ? find(st.runId)?.error : null
883
+ return `${MARKS[status] ?? '…'} ${label}${error ? `: ${error}` : ''}`
884
+ })
885
+ .join(' · ')
886
+ const opts = { emitter: 'TaskRunner' }
887
+ if (sequence.status === 'succeeded') toast.success(sequence.label, detail, opts)
888
+ else if (sequence.status === 'failed') toast.error(sequence.label, detail, { ...opts, keep: 'long' })
889
+ else toast.warn(sequence.label, detail, opts)
890
+ }
891
+
892
+ /**
893
+ * Run tasks one after another, followed in one window: the list of steps,
894
+ * each step's detail on a click (#4934). Resolves once the sequence is
895
+ * under way (null when its confirmation is declined); await
896
+ * `sequence.finished` for its end. One step only is a plain run.
897
+ */
898
+ async function sequence(
899
+ label: string | (() => string),
900
+ steps: SequenceStep[],
901
+ options: SequenceOptions = {}
902
+ ): Promise<TaskSequence | null> {
903
+ if (!steps.length) throw new Error('TaskRunner: a sequence needs at least one step')
904
+ const labelOf = typeof label === 'function' ? label : undefined
905
+ const text = labelOf ? labelOf() : (label as string)
906
+ if (options.confirm && !(await requestConfirm(text, options.confirm))) return null
907
+ const single = steps.length === 1
908
+ const created = addSequence(
909
+ { label: text, stopOnError: options.stopOnError !== false, meta: options.meta ? { ...options.meta } : null },
910
+ steps.map((spec) => ({ label: declaredLabel(spec) })),
911
+ { specs: steps.slice(), options, single },
912
+ labelOf
913
+ )
914
+ if (!single && options.open !== false) state.openId = created.id
915
+ void drive(created.id, null)
916
+ return created
917
+ }
918
+
919
+ /** Stop a sequence: its running step is cancelled when its kind can, and the steps after it are not run. */
920
+ async function cancelSequence(id: string): Promise<void> {
921
+ const sequence = findSequence(id)
922
+ if (!sequence || sequence.status !== 'running') return
923
+ sequence.cancelling = true
924
+ persistSequences()
925
+ const runId = sequence.steps[sequence.current]?.runId
926
+ if (runId) await cancel(runId)
927
+ }
928
+
929
+ function dismissSequence(id: string): void {
930
+ const i = state.sequences.findIndex((x) => x.id === id)
931
+ if (i !== -1) state.sequences.splice(i, 1)
932
+ sequenceInternals.delete(id)
933
+ if (state.openId === id) state.openId = null
934
+ persistSequences()
935
+ }
936
+
937
+ /** The sequences matching a meta (each given key equal), newest first. */
938
+ function sequencesFor(meta: Record<string, unknown> = {}): TaskSequence[] {
939
+ return state.sequences
940
+ .filter((x) => Object.entries(meta).every(([k, v]) => x.meta?.[k] === v))
941
+ .sort((a, b) => b.startedAt - a.startedAt)
942
+ }
943
+
468
944
  // --- Finding a run again (#4687) ---
469
945
 
470
946
  /** The runs matching a kind and/or a meta (each given key equal), newest first. */
@@ -500,9 +976,20 @@ function createTaskStore() {
500
976
  definition: (id: string) => defs.get(id),
501
977
  runFor,
502
978
  runsFor,
503
- isFinal: (status: TaskStatus) => FINAL.includes(status),
504
- /** A run still going: starting, queued or running (#4695) */
505
- isActive: (run: TaskRun | null | undefined) => !!run && !FINAL.includes(run.status),
979
+ isFinal: (status: TaskStatus | SequenceStepStatus | TaskSequence['status']) => FINAL.includes(status as TaskStatus),
980
+ /** A run or a sequence still going (#4695, #4934) */
981
+ isActive: (run: TaskRun | TaskSequence | null | undefined) => !!run && !FINAL.includes(run.status as TaskStatus),
982
+ sequence,
983
+ cancelSequence,
984
+ dismissSequence,
985
+ /** The sequence a run is a step of, or a sequence by its id */
986
+ sequenceOf: (id: string | null | undefined): TaskSequence | null =>
987
+ !id ? null : (findSequence(id) ?? (find(id)?.sequenceId ? findSequence(find(id)!.sequenceId!) ?? null : null)),
988
+ sequencesFor,
989
+ /** The latest sequence about a record: `sequenceFor({ box: 'b1' })` */
990
+ sequenceFor: (meta: Record<string, unknown>) => sequencesFor(meta)[0] ?? null,
991
+ stepStatus,
992
+ stepSummary,
506
993
  /** For tests: stop everything and forget every run. */
507
994
  reset(): void {
508
995
  for (const stop of stops.values()) stop()
@@ -512,6 +999,8 @@ function createTaskStore() {
512
999
  defs.clear()
513
1000
  kinds.clear()
514
1001
  state.runs.splice(0)
1002
+ state.sequences.splice(0)
1003
+ sequenceInternals.clear()
515
1004
  state.openId = null
516
1005
  state.pendingConfirm = null
517
1006
  state.hosts = 0
@@ -46,12 +46,16 @@ export function useTaskNotifications(): void {
46
46
  for (const { run } of entries) {
47
47
  const id = STATUS_PREFIX + run.id
48
48
  ids.add(id)
49
+ // A step of a sequence says which sequence, and opens its window (#4934)
50
+ const sequence = run.sequenceId ? store.sequenceOf(run.sequenceId) : null
51
+ const index = sequence ? sequence.steps.findIndex((st) => st.runId === run.id) : -1
52
+ const label = sequence && index !== -1 ? `${sequence.label} · ${run.label} (${index + 1}/${sequence.steps.length})` : run.label
49
53
  notifications.registerStatus({
50
54
  id,
51
- label: `${run.label} — ${stateText(run)}`,
55
+ label: `${label} — ${stateText(run)}`,
52
56
  severity: 'nominal',
53
57
  icon: 'pi pi-spin pi-spinner',
54
- onClick: () => store.open(run.id),
58
+ onClick: () => store.open(sequence ? sequence.id : run.id),
55
59
  })
56
60
  shown.add(id)
57
61
  if (!tracked.has(run.id)) {