@morscherlab/mint-sdk 1.5.0-beta.6 → 1.5.0-beta.8

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 (106) hide show
  1. package/dist/{AlertBox-CexONPhA.js → AlertBox-Cai0w7gF.js} +3 -3
  2. package/dist/{AlertBox-CexONPhA.js.map → AlertBox-Cai0w7gF.js.map} +1 -1
  3. package/dist/{AppSidebar-FxlF5_dI.js → AppSidebar-C1DT4nsZ.js} +351 -90
  4. package/dist/AppSidebar-C1DT4nsZ.js.map +1 -0
  5. package/dist/{ConfirmDialog-D9QXFpsy.js → ConfirmDialog-BjFsOpBe.js} +2 -2
  6. package/dist/{ConfirmDialog-D9QXFpsy.js.map → ConfirmDialog-BjFsOpBe.js.map} +1 -1
  7. package/dist/{ExperimentPopover-Bbd6RaoH.js → ExperimentPopover-DYy_s0kI.js} +25 -37
  8. package/dist/ExperimentPopover-DYy_s0kI.js.map +1 -0
  9. package/dist/{ExperimentSelectorModal-CUkKmgfr.js → ExperimentSelectorModal-Bfh5bdkv.js} +5 -5
  10. package/dist/{ExperimentSelectorModal-CUkKmgfr.js.map → ExperimentSelectorModal-Bfh5bdkv.js.map} +1 -1
  11. package/dist/{SegmentedControl-C-sckoJZ.js → SegmentedControl-B8KgyOjd.js} +2 -2
  12. package/dist/{SegmentedControl-C-sckoJZ.js.map → SegmentedControl-B8KgyOjd.js.map} +1 -1
  13. package/dist/{SettingsModal-BIC0dAYc.js → SettingsModal-DPNblTe9.js} +7 -7
  14. package/dist/{SettingsModal-BIC0dAYc.js.map → SettingsModal-DPNblTe9.js.map} +1 -1
  15. package/dist/__tests__/components/AppTopBarCompact.test.d.ts +1 -0
  16. package/dist/__tests__/components/AppTopBarCompactReset.test.d.ts +1 -0
  17. package/dist/__tests__/components/AutoGroupModal.experimentLoad.test.d.ts +1 -0
  18. package/dist/components/AppTopBar.compact.d.ts +5 -0
  19. package/dist/components/AppTopBar.vue.d.ts +17 -17
  20. package/dist/components/PluginWorkspaceView.vue.d.ts +4 -0
  21. package/dist/components/internal/AppTopBarPageSelectorInternal.vue.d.ts +2 -2
  22. package/dist/components/internal/LucideIconInternal.vue.d.ts +17 -0
  23. package/dist/composables/appLayoutSidebar.d.ts +9 -0
  24. package/dist/composables/useVersionedSave.d.ts +5 -2
  25. package/dist/{controlSchemaModel-C_XqpkgE.js → controlSchemaModel-BtFNZj8t.js} +2 -2
  26. package/dist/{controlSchemaModel-C_XqpkgE.js.map → controlSchemaModel-BtFNZj8t.js.map} +1 -1
  27. package/dist/{data-CfY7o8QC.js → data-CJztFns8.js} +31 -15
  28. package/dist/{data-CfY7o8QC.js.map → data-CJztFns8.js.map} +1 -1
  29. package/dist/data.js +8 -8
  30. package/dist/{experimentStatus-DCn2QKG7.js → experimentStatus-Deokk7Br.js} +2 -2
  31. package/dist/{experimentStatus-DCn2QKG7.js.map → experimentStatus-Deokk7Br.js.map} +1 -1
  32. package/dist/index.js +14 -14
  33. package/dist/{install-QF3Sh82O.js → install-9FkKs0iW.js} +14 -15
  34. package/dist/{install-QF3Sh82O.js.map → install-9FkKs0iW.js.map} +1 -1
  35. package/dist/install.js +1 -1
  36. package/dist/{lab-BcX5JBSY.js → lab-BYhb_cJI.js} +22 -14
  37. package/dist/lab-BYhb_cJI.js.map +1 -0
  38. package/dist/lab.js +4 -4
  39. package/dist/{records-BAymyHAn.js → records-GtiVMlTQ.js} +198 -62
  40. package/dist/records-GtiVMlTQ.js.map +1 -0
  41. package/dist/{runtime-DngeJtdq.js → runtime-DcMsvlaS.js} +29 -12
  42. package/dist/runtime-DcMsvlaS.js.map +1 -0
  43. package/dist/runtime.js +6 -6
  44. package/dist/{shell-CWZi97nW.js → shell-XZYkAZS_.js} +5 -5
  45. package/dist/{shell-CWZi97nW.js.map → shell-XZYkAZS_.js.map} +1 -1
  46. package/dist/shell.js +5 -5
  47. package/dist/styles.css +136 -12
  48. package/dist/types/components.d.ts +22 -2
  49. package/dist/types/index.d.ts +1 -1
  50. package/dist/{useDropdownState-uFIz6Yv8.js → useDropdownState-CcBzUYZ6.js} +14 -5
  51. package/dist/useDropdownState-CcBzUYZ6.js.map +1 -0
  52. package/dist/{useExperimentSamples-DEDAKa2E.js → useExperimentSamples-CpNXvpUn.js} +3 -3
  53. package/dist/{useExperimentSamples-DEDAKa2E.js.map → useExperimentSamples-CpNXvpUn.js.map} +1 -1
  54. package/dist/{useListReorder-W1bzK_bo.js → useListReorder-Bp4EAI2w.js} +3 -3
  55. package/dist/{useListReorder-W1bzK_bo.js.map → useListReorder-Bp4EAI2w.js.map} +1 -1
  56. package/dist/{useRackEditor-Bmtuo0aj.js → useRackEditor-i2bdPUFf.js} +8 -8
  57. package/dist/{useRackEditor-Bmtuo0aj.js.map → useRackEditor-i2bdPUFf.js.map} +1 -1
  58. package/dist/{useRealtime-jOetF2mM.js → useRealtime-BLQEjbuq.js} +3 -3
  59. package/dist/{useRealtime-jOetF2mM.js.map → useRealtime-BLQEjbuq.js.map} +1 -1
  60. package/dist/useRequest-CXyPw3eh.js +76 -0
  61. package/dist/useRequest-CXyPw3eh.js.map +1 -0
  62. package/dist/utils/deprecation.d.ts +2 -0
  63. package/dist/utils/lucideIcon.d.ts +4 -0
  64. package/package.json +1 -1
  65. package/src/__tests__/components/AppTopBar.test.ts +102 -20
  66. package/src/__tests__/components/AppTopBarCompact.test.ts +65 -0
  67. package/src/__tests__/components/AppTopBarCompactReset.test.ts +24 -0
  68. package/src/__tests__/components/AutoGroupModal.experimentLoad.test.ts +58 -0
  69. package/src/__tests__/components/BaseModal.test.ts +33 -2
  70. package/src/__tests__/components/ExperimentPopover.test.ts +32 -0
  71. package/src/__tests__/components/PluginWorkspaceView.test.ts +1 -1
  72. package/src/__tests__/composables/useJobCenter.test.ts +35 -0
  73. package/src/__tests__/composables/useVersionedSave.test.ts +71 -6
  74. package/src/__tests__/styles/menusShellRefresh.test.ts +5 -0
  75. package/src/components/AppLayout.story.vue +5 -5
  76. package/src/components/AppLayout.vue +13 -1
  77. package/src/components/AppTopBar.compact.ts +60 -0
  78. package/src/components/AppTopBar.story.vue +39 -14
  79. package/src/components/AppTopBar.vue +222 -89
  80. package/src/components/BaseModal.vue +16 -5
  81. package/src/components/ExperimentPopover.story.vue +2 -2
  82. package/src/components/ExperimentPopover.vue +6 -22
  83. package/src/components/GeneratedPluginView.vue +0 -1
  84. package/src/components/PluginWorkspaceView.vue +8 -0
  85. package/src/components/internal/AppTopBarPageSelectorInternal.vue +12 -0
  86. package/src/components/internal/AutoGroupModalInternal.vue +14 -3
  87. package/src/components/internal/LucideIconInternal.vue +23 -0
  88. package/src/composables/appLayoutSidebar.ts +11 -0
  89. package/src/composables/useJobCenter.ts +21 -1
  90. package/src/composables/usePluginWorkspace.ts +1 -1
  91. package/src/composables/useVersionedSave.ts +32 -7
  92. package/src/styles/components/app-layout.css +5 -0
  93. package/src/styles/components/app-top-bar.css +128 -8
  94. package/src/types/components.ts +23 -2
  95. package/src/types/index.ts +1 -0
  96. package/src/utils/deprecation.ts +8 -0
  97. package/src/utils/lucideIcon.ts +25 -0
  98. package/src/utils/lucideIconIndex.d.ts +2 -0
  99. package/dist/AppSidebar-FxlF5_dI.js.map +0 -1
  100. package/dist/ExperimentPopover-Bbd6RaoH.js.map +0 -1
  101. package/dist/lab-BcX5JBSY.js.map +0 -1
  102. package/dist/records-BAymyHAn.js.map +0 -1
  103. package/dist/runtime-DngeJtdq.js.map +0 -1
  104. package/dist/useDropdownState-uFIz6Yv8.js.map +0 -1
  105. package/dist/useRequest-D9-3BS-3.js +0 -215
  106. package/dist/useRequest-D9-3BS-3.js.map +0 -1
@@ -1,5 +1,5 @@
1
- import { d as isActiveJobStatus, p as jobStatusLabel } from "./records-BAymyHAn.js";
2
- import { t as ConfirmDialog_default } from "./ConfirmDialog-D9QXFpsy.js";
1
+ import { d as isActiveJobStatus, p as jobStatusLabel } from "./records-GtiVMlTQ.js";
2
+ import { t as ConfirmDialog_default } from "./ConfirmDialog-BjFsOpBe.js";
3
3
  import { Fragment, Teleport, Transition, computed, createBlock, createCommentVNode, createElementBlock, createElementVNode, createTextVNode, createVNode, defineComponent, getCurrentScope, nextTick, normalizeClass, normalizeStyle, onBeforeUnmount, onScopeDispose, openBlock, readonly, ref, renderList, renderSlot, resolveDynamicComponent, toDisplayString, toValue, unref, watch, withCtx } from "vue";
4
4
  import { CircleAlert, CircleCheck, CircleSlash, CircleX, Clock, LoaderCircle, RefreshCw, Square, Trash2, X } from "lucide-vue-next";
5
5
  //#region src/components/JobsStatusTray.vue?vue&type=script&setup=true&lang.ts
@@ -505,4 +505,4 @@ function subscribeRealtime(topics, handler, withPresence) {
505
505
  //#endregion
506
506
  export { JobsStatusTray_default as i, subscribeRealtime as n, useRealtime as r, currentPresence as t };
507
507
 
508
- //# sourceMappingURL=useRealtime-jOetF2mM.js.map
508
+ //# sourceMappingURL=useRealtime-BLQEjbuq.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"useRealtime-jOetF2mM.js","names":[],"sources":["../src/components/JobsStatusTray.vue","../src/components/JobsStatusTray.vue","../src/composables/useRealtime.ts"],"sourcesContent":["<script setup lang=\"ts\">\n/**\n * Compact, non-modal job panel under the top bar, driven by a job center the parent owns.\n *\n * The parent passes the center's `topBarJob`, `completedCount` and `handleTopBarClick`\n * to `AppTopBar`; its run slot opens this panel. `PluginWorkspaceView` does this for you\n * when its spec sets `jobs`.\n *\n * @example Recommended\n * ```vue\n * <AppTopBar :job=\"center.topBarJob.value\" :jobs-done=\"center.completedCount.value\"\n * @job-click=\"center.handleTopBarClick(openResult)\" />\n * <JobsStatusTray :center=\"center\" @select=\"openResult\" />\n * ```\n */\nimport { computed, nextTick, onBeforeUnmount, ref, watch, type Component } from 'vue'\nimport {\n CircleAlert,\n CircleCheck,\n CircleSlash,\n CircleX,\n Clock,\n LoaderCircle,\n RefreshCw,\n Square,\n Trash2,\n X,\n} from 'lucide-vue-next'\n\nimport { isActiveJobStatus, jobStatusLabel } from '../jobs'\nimport type { UseJobCenterReturn } from '../composables/useJobCenter'\nimport type { JobState, JobStatus } from '../types/jobs'\nimport ConfirmDialog from './ConfirmDialog.vue'\n\ntype ConfirmAction = 'cancel' | 'delete' | 'clear'\n\ninterface Props {\n /** Job center from `useJobCenter()`; the parent owns it and opens the panel through it. */\n center: UseJobCenterReturn\n title?: string\n teleportTo?: string | HTMLElement | false\n /** Ask before Cancel, Delete and Clear (`true`), or before the named ones only. Default off. */\n confirm?: boolean | Partial<Record<ConfirmAction, boolean>>\n}\n\nconst props = withDefaults(defineProps<Props>(), {\n title: 'Jobs',\n teleportTo: 'body',\n confirm: false,\n})\n\nconst emit = defineEmits<{\n select: [job: JobState]\n error: [message: string]\n}>()\n\ndefineSlots<{\n /** Extra per-row actions, rendered before the built-in Cancel / Delete. */\n 'job-actions'?: (props: { job: JobState }) => unknown\n /** Row title. Default: the job name. */\n 'job-title'?: (props: { job: JobState }) => unknown\n /** Detail line under the title. Default: the error, progress message or status. */\n 'job-detail'?: (props: { job: JobState }) => unknown\n}>()\n\nconst STATUS_ICONS: Record<JobStatus, Component> = {\n running: LoaderCircle,\n awaiting_input: CircleAlert,\n queued: Clock,\n completed: CircleCheck,\n failed: CircleX,\n cancelled: CircleSlash,\n}\n\nconst panelRef = ref<HTMLElement | null>(null)\nconst teleportTarget = computed(() => props.teleportTo || 'body')\nconst tray = props.center\nconst titleId = `${tray.panelId}-title`\nconst rows = (jobs: JobState[]) => jobs.map(job => ({ job, view: tray.rowView(job) }))\n// A job waiting for input is the only one that needs a person: pin it first.\nconst activeRows = computed(() => {\n const active = rows(tray.activeJobs.value)\n return [\n ...active.filter(row => row.view.status === 'awaiting_input'),\n ...active.filter(row => row.view.status !== 'awaiting_input'),\n ]\n})\nconst sections = computed(() => [\n { key: 'active', title: 'Active', rows: activeRows.value },\n { key: 'finished', title: 'Finished', rows: rows(tray.historyJobs.value) },\n].filter(section => section.rows.length > 0))\nconst headCount = computed(() => {\n const parts = [\n [tray.activeJobs.value.length, 'active'],\n [tray.completedCount.value, 'done'],\n [tray.historyJobs.value.filter(job => job.status === 'failed').length, 'failed'],\n ].filter(([n]) => n).map(([n, word]) => `${n} ${word}`)\n return parts.length ? parts.join(' · ') : 'No jobs'\n})\nconst canClear = computed(() => (\n tray.deletableJobs.value.length > 0\n && tray.canClearFinished.value\n))\n\n// Escape returns focus to the element that opened the panel (the top-bar chip).\n// The panel is non-modal, so Escape is heard on the document while it is open.\n// An Escape that an inner control handled, or that belongs to a modal dialog\n// above the tray (its own confirm dialog too), leaves the tray open.\nlet opener: HTMLElement | null = null\nfunction onDocumentKeydown(event: KeyboardEvent): void {\n if (event.key !== 'Escape' || event.defaultPrevented || confirmOpen.value) return\n if (event.target instanceof Element && event.target.closest('[aria-modal=\"true\"]')) return\n closeTray()\n}\nwatch(tray.isOpen, async (open) => {\n if (!open) {\n document.removeEventListener('keydown', onDocumentKeydown)\n return\n }\n opener = document.activeElement instanceof HTMLElement ? document.activeElement : null\n document.addEventListener('keydown', onDocumentKeydown)\n await nextTick()\n panelRef.value?.focus()\n}, { flush: 'sync' })\nonBeforeUnmount(() => document.removeEventListener('keydown', onDocumentKeydown))\n\n// A focused row that leaves the list (an action or a refresh) drops focus to body:\n// note the focused element before the update and keep focus in the panel after it.\nlet focusedInPanel: Element | null = null\nwatch(tray.jobs, () => {\n const focused = document.activeElement\n focusedInPanel = focused && panelRef.value?.contains(focused) ? focused : null\n}, { flush: 'pre' })\nwatch(tray.jobs, () => {\n if (tray.isOpen.value && focusedInPanel && !focusedInPanel.isConnected) panelRef.value?.focus()\n focusedInPanel = null\n}, { flush: 'post' })\n\nfunction closeTray(): void {\n tray.close()\n // Safari leaves a clicked button unfocused (opener = body), and the chip node is\n // replaced when it switches between job chip and idle button: fall back to the\n // top-bar jobs control.\n const target = opener?.isConnected && opener !== document.body\n ? opener\n : document.querySelector<HTMLElement>('.mint-topbar__job')\n target?.focus()\n}\n\nfunction formatTime(value: string | null): string {\n if (!value) return ''\n const date = new Date(value)\n return Number.isNaN(date.getTime())\n ? ''\n : date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })\n}\n\n/** Right-hand value: the percent while a job moves, else when it ended or started. */\nfunction jobValue(job: JobState, percent: number | null): string {\n if (percent != null) return `${percent}%`\n return formatTime(job.completed_at || job.started_at || job.created_at)\n}\n\n// Confirmation: the action waits for the dialog; it runs on the live job.\n// `ids`: the finished jobs that the user confirmed to clear.\nconst pending = ref<{ action: ConfirmAction; job?: JobState; ids?: string[] } | null>(null)\nconst confirmOpen = ref(false)\n// Set on request and kept, so the dialog text stays while it fades out.\nconst confirmText = ref<{ title: string; message: string; confirmLabel: string; cancelLabel: string } | null>(null)\nconst confirmEnabled = computed(() => props.confirm === true\n || (typeof props.confirm === 'object' && Object.values(props.confirm).some(Boolean)))\n\nfunction textFor(action: ConfirmAction, job?: JobState) {\n if (action === 'clear') {\n const count = tray.deletableJobs.value.length\n return {\n title: 'Clear finished jobs?',\n message: `${count} finished ${count === 1 ? 'job' : 'jobs'} and their stored results are deleted.`,\n confirmLabel: 'Clear jobs',\n cancelLabel: 'Cancel',\n }\n }\n return action === 'cancel'\n ? { title: 'Cancel job?', message: `${job?.name} stops. Its partial results are lost.`, confirmLabel: 'Cancel job', cancelLabel: 'Keep running' }\n : { title: 'Delete job?', message: `${job?.name} and its stored result are deleted.`, confirmLabel: 'Delete job', cancelLabel: 'Cancel' }\n}\n\nfunction needsConfirm(action: ConfirmAction): boolean {\n return props.confirm === true || (typeof props.confirm === 'object' && props.confirm[action] === true)\n}\n\nfunction request(action: ConfirmAction, job?: JobState): void {\n if (!needsConfirm(action)) {\n void run(action, job)\n return\n }\n pending.value = { action, job, ids: action === 'clear' ? deletableIds() : undefined }\n confirmText.value = textFor(action, job)\n confirmOpen.value = true\n}\n\nfunction deletableIds(): string[] {\n return tray.deletableJobs.value.map(job => job.job_id).sort()\n}\n\n// A new source is a new job list: the confirmed target is gone.\nwatch(tray.source, () => onConfirmOpen(false))\n\nfunction onConfirmOpen(open: boolean): void {\n confirmOpen.value = open\n if (!open) pending.value = null\n}\n\nasync function confirmPending(): Promise<void> {\n // A second Confirm click while the dialog fades out does nothing.\n const current = pending.value\n if (!confirmOpen.value || !current) return\n if (current.action === 'clear') {\n // Polling changed the finished jobs: ask again with the new count.\n const ids = deletableIds()\n if (ids.join() !== current.ids?.join()) {\n pending.value = { ...current, ids }\n confirmText.value = textFor('clear')\n return\n }\n }\n confirmOpen.value = false\n pending.value = null\n if (current.action === 'clear') return clearFinished()\n // Polling can end or remove the job while the dialog is open: then do nothing.\n const live = tray.jobs.value.find(job => job.job_id === current.job?.job_id)\n const allowed = live && (current.action === 'cancel'\n ? isActiveJobStatus(live.status) && live.can_cancel\n : live.can_delete)\n if (allowed) await run(current.action, live)\n}\n\nfunction run(action: ConfirmAction, job?: JobState): Promise<void> {\n if (action === 'clear') return clearFinished()\n return action === 'cancel' ? cancelJob(job!) : deleteJob(job!)\n}\n\nasync function cancelJob(job: JobState): Promise<void> {\n const succeeded = await tray.cancelJob(job)\n if (!succeeded && tray.error.value) emit('error', tray.error.value)\n}\n\nasync function deleteJob(job: JobState): Promise<void> {\n const succeeded = await tray.deleteJob(job)\n if (!succeeded && tray.error.value) emit('error', tray.error.value)\n}\n\nasync function clearFinished(): Promise<void> {\n const succeeded = await tray.clearFinished()\n if (!succeeded && tray.error.value) emit('error', tray.error.value)\n}\n</script>\n\n<template>\n <Teleport :to=\"teleportTarget\" :disabled=\"teleportTo === false\">\n <div class=\"mint-jobs-tray\">\n <!-- Clicks outside close the panel; the page is not dimmed. -->\n <div\n v-if=\"tray.isOpen.value\"\n class=\"mint-jobs-tray__scrim\"\n aria-hidden=\"true\"\n @click=\"tray.close()\"\n />\n\n <Transition name=\"mint-jobs-tray-fade\">\n <section\n v-if=\"tray.isOpen.value\"\n :id=\"tray.panelId\"\n ref=\"panelRef\"\n class=\"mint-jobs-tray__panel\"\n :aria-labelledby=\"titleId\"\n tabindex=\"-1\"\n >\n <header class=\"mint-jobs-tray__head\">\n <h2 :id=\"titleId\" class=\"mint-jobs-tray__title\">{{ title }}</h2>\n <span class=\"mint-jobs-tray__head-count\">{{ headCount }}</span>\n <button\n v-if=\"tray.canRefresh.value\"\n type=\"button\"\n class=\"mint-jobs-tray__icon-button\"\n aria-label=\"Refresh jobs\"\n title=\"Refresh jobs\"\n :disabled=\"tray.isLoading.value\"\n @click=\"tray.refresh\"\n >\n <RefreshCw :size=\"14\" aria-hidden=\"true\" />\n </button>\n <button\n type=\"button\"\n class=\"mint-jobs-tray__icon-button\"\n aria-label=\"Close jobs\"\n title=\"Close\"\n @click=\"closeTray\"\n >\n <X :size=\"14\" aria-hidden=\"true\" />\n </button>\n </header>\n\n <p v-if=\"tray.error.value\" class=\"mint-jobs-tray__error\" role=\"alert\">\n {{ tray.error.value }}\n </p>\n\n <div class=\"mint-jobs-tray__body\">\n <p v-if=\"sections.length === 0\" class=\"mint-jobs-tray__empty\">No jobs yet</p>\n\n <template v-for=\"section in sections\" :key=\"section.key\">\n <div class=\"mint-jobs-tray__section\" :data-section=\"section.key\">\n {{ section.title }}\n <span class=\"mint-jobs-tray__section-count\">· {{ section.rows.length }}</span>\n <button\n v-if=\"section.key === 'finished' && canClear\"\n type=\"button\"\n class=\"mint-jobs-tray__section-action\"\n @click=\"request('clear')\"\n >\n Clear\n </button>\n </div>\n\n <div\n v-for=\"{ job, view } in section.rows\"\n :key=\"job.job_id\"\n class=\"mint-jobs-tray__row\"\n :class=\"{ 'mint-jobs-tray__row--awaiting-input': view.status === 'awaiting_input' }\"\n :data-status=\"job.status\"\n >\n <!-- data-status is the real job status; the row view only changes how it looks. -->\n <component\n :is=\"STATUS_ICONS[view.status]\"\n :size=\"15\"\n :class=\"['mint-jobs-tray__status', `mint-jobs-tray__status--${view.status.replace('_', '-')}`]\"\n role=\"img\"\n :aria-label=\"jobStatusLabel(view.status)\"\n />\n <button type=\"button\" class=\"mint-jobs-tray__row-title\" @click=\"emit('select', job)\">\n <slot name=\"job-title\" :job=\"job\">{{ job.name }}</slot>\n </button>\n <span class=\"mint-jobs-tray__tools\">\n <span class=\"mint-jobs-tray__value\">{{ jobValue(job, view.percent) }}</span>\n <slot name=\"job-actions\" :job=\"job\" />\n <button\n v-if=\"isActiveJobStatus(job.status) && job.can_cancel && tray.canCancel.value\"\n type=\"button\"\n class=\"mint-jobs-tray__icon-button mint-jobs-tray__icon-button--danger\"\n :aria-label=\"`Cancel ${job.name}`\"\n title=\"Cancel\"\n :disabled=\"tray.isPending(job)\"\n @click=\"request('cancel', job)\"\n >\n <Square :size=\"12\" aria-hidden=\"true\" />\n </button>\n <button\n v-if=\"job.can_delete && tray.canDelete.value\"\n type=\"button\"\n class=\"mint-jobs-tray__icon-button\"\n :aria-label=\"`Delete ${job.name}`\"\n title=\"Delete\"\n :disabled=\"tray.isPending(job)\"\n @click=\"request('delete', job)\"\n >\n <Trash2 :size=\"14\" aria-hidden=\"true\" />\n </button>\n </span>\n <div\n v-if=\"view.percent != null\"\n class=\"mint-jobs-tray__progress\"\n role=\"progressbar\"\n :aria-label=\"`${job.name} progress`\"\n aria-valuemin=\"0\"\n aria-valuemax=\"100\"\n :aria-valuenow=\"view.percent\"\n >\n <span :style=\"{ width: `${view.percent}%` }\" />\n </div>\n <span\n class=\"mint-jobs-tray__detail\"\n :class=\"{ 'mint-jobs-tray__detail--error': job.status === 'failed' }\"\n >\n <slot name=\"job-detail\" :job=\"job\">{{ view.message }}</slot>\n </span>\n </div>\n </template>\n </div>\n </section>\n </Transition>\n\n <ConfirmDialog\n v-if=\"confirmEnabled\"\n :open=\"confirmOpen\"\n tone=\"error\"\n :title=\"confirmText?.title\"\n :confirm-label=\"confirmText?.confirmLabel\"\n :cancel-label=\"confirmText?.cancelLabel\"\n @update:open=\"onConfirmOpen\"\n @confirm=\"confirmPending\"\n >\n <!-- The marker class lifts the dialog above the tray (jobs-status-tray.css). -->\n <p class=\"mint-confirm__message mint-jobs-tray__confirm\">{{ confirmText?.message }}</p>\n </ConfirmDialog>\n </div>\n </Teleport>\n</template>\n","<script setup lang=\"ts\">\n/**\n * Compact, non-modal job panel under the top bar, driven by a job center the parent owns.\n *\n * The parent passes the center's `topBarJob`, `completedCount` and `handleTopBarClick`\n * to `AppTopBar`; its run slot opens this panel. `PluginWorkspaceView` does this for you\n * when its spec sets `jobs`.\n *\n * @example Recommended\n * ```vue\n * <AppTopBar :job=\"center.topBarJob.value\" :jobs-done=\"center.completedCount.value\"\n * @job-click=\"center.handleTopBarClick(openResult)\" />\n * <JobsStatusTray :center=\"center\" @select=\"openResult\" />\n * ```\n */\nimport { computed, nextTick, onBeforeUnmount, ref, watch, type Component } from 'vue'\nimport {\n CircleAlert,\n CircleCheck,\n CircleSlash,\n CircleX,\n Clock,\n LoaderCircle,\n RefreshCw,\n Square,\n Trash2,\n X,\n} from 'lucide-vue-next'\n\nimport { isActiveJobStatus, jobStatusLabel } from '../jobs'\nimport type { UseJobCenterReturn } from '../composables/useJobCenter'\nimport type { JobState, JobStatus } from '../types/jobs'\nimport ConfirmDialog from './ConfirmDialog.vue'\n\ntype ConfirmAction = 'cancel' | 'delete' | 'clear'\n\ninterface Props {\n /** Job center from `useJobCenter()`; the parent owns it and opens the panel through it. */\n center: UseJobCenterReturn\n title?: string\n teleportTo?: string | HTMLElement | false\n /** Ask before Cancel, Delete and Clear (`true`), or before the named ones only. Default off. */\n confirm?: boolean | Partial<Record<ConfirmAction, boolean>>\n}\n\nconst props = withDefaults(defineProps<Props>(), {\n title: 'Jobs',\n teleportTo: 'body',\n confirm: false,\n})\n\nconst emit = defineEmits<{\n select: [job: JobState]\n error: [message: string]\n}>()\n\ndefineSlots<{\n /** Extra per-row actions, rendered before the built-in Cancel / Delete. */\n 'job-actions'?: (props: { job: JobState }) => unknown\n /** Row title. Default: the job name. */\n 'job-title'?: (props: { job: JobState }) => unknown\n /** Detail line under the title. Default: the error, progress message or status. */\n 'job-detail'?: (props: { job: JobState }) => unknown\n}>()\n\nconst STATUS_ICONS: Record<JobStatus, Component> = {\n running: LoaderCircle,\n awaiting_input: CircleAlert,\n queued: Clock,\n completed: CircleCheck,\n failed: CircleX,\n cancelled: CircleSlash,\n}\n\nconst panelRef = ref<HTMLElement | null>(null)\nconst teleportTarget = computed(() => props.teleportTo || 'body')\nconst tray = props.center\nconst titleId = `${tray.panelId}-title`\nconst rows = (jobs: JobState[]) => jobs.map(job => ({ job, view: tray.rowView(job) }))\n// A job waiting for input is the only one that needs a person: pin it first.\nconst activeRows = computed(() => {\n const active = rows(tray.activeJobs.value)\n return [\n ...active.filter(row => row.view.status === 'awaiting_input'),\n ...active.filter(row => row.view.status !== 'awaiting_input'),\n ]\n})\nconst sections = computed(() => [\n { key: 'active', title: 'Active', rows: activeRows.value },\n { key: 'finished', title: 'Finished', rows: rows(tray.historyJobs.value) },\n].filter(section => section.rows.length > 0))\nconst headCount = computed(() => {\n const parts = [\n [tray.activeJobs.value.length, 'active'],\n [tray.completedCount.value, 'done'],\n [tray.historyJobs.value.filter(job => job.status === 'failed').length, 'failed'],\n ].filter(([n]) => n).map(([n, word]) => `${n} ${word}`)\n return parts.length ? parts.join(' · ') : 'No jobs'\n})\nconst canClear = computed(() => (\n tray.deletableJobs.value.length > 0\n && tray.canClearFinished.value\n))\n\n// Escape returns focus to the element that opened the panel (the top-bar chip).\n// The panel is non-modal, so Escape is heard on the document while it is open.\n// An Escape that an inner control handled, or that belongs to a modal dialog\n// above the tray (its own confirm dialog too), leaves the tray open.\nlet opener: HTMLElement | null = null\nfunction onDocumentKeydown(event: KeyboardEvent): void {\n if (event.key !== 'Escape' || event.defaultPrevented || confirmOpen.value) return\n if (event.target instanceof Element && event.target.closest('[aria-modal=\"true\"]')) return\n closeTray()\n}\nwatch(tray.isOpen, async (open) => {\n if (!open) {\n document.removeEventListener('keydown', onDocumentKeydown)\n return\n }\n opener = document.activeElement instanceof HTMLElement ? document.activeElement : null\n document.addEventListener('keydown', onDocumentKeydown)\n await nextTick()\n panelRef.value?.focus()\n}, { flush: 'sync' })\nonBeforeUnmount(() => document.removeEventListener('keydown', onDocumentKeydown))\n\n// A focused row that leaves the list (an action or a refresh) drops focus to body:\n// note the focused element before the update and keep focus in the panel after it.\nlet focusedInPanel: Element | null = null\nwatch(tray.jobs, () => {\n const focused = document.activeElement\n focusedInPanel = focused && panelRef.value?.contains(focused) ? focused : null\n}, { flush: 'pre' })\nwatch(tray.jobs, () => {\n if (tray.isOpen.value && focusedInPanel && !focusedInPanel.isConnected) panelRef.value?.focus()\n focusedInPanel = null\n}, { flush: 'post' })\n\nfunction closeTray(): void {\n tray.close()\n // Safari leaves a clicked button unfocused (opener = body), and the chip node is\n // replaced when it switches between job chip and idle button: fall back to the\n // top-bar jobs control.\n const target = opener?.isConnected && opener !== document.body\n ? opener\n : document.querySelector<HTMLElement>('.mint-topbar__job')\n target?.focus()\n}\n\nfunction formatTime(value: string | null): string {\n if (!value) return ''\n const date = new Date(value)\n return Number.isNaN(date.getTime())\n ? ''\n : date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })\n}\n\n/** Right-hand value: the percent while a job moves, else when it ended or started. */\nfunction jobValue(job: JobState, percent: number | null): string {\n if (percent != null) return `${percent}%`\n return formatTime(job.completed_at || job.started_at || job.created_at)\n}\n\n// Confirmation: the action waits for the dialog; it runs on the live job.\n// `ids`: the finished jobs that the user confirmed to clear.\nconst pending = ref<{ action: ConfirmAction; job?: JobState; ids?: string[] } | null>(null)\nconst confirmOpen = ref(false)\n// Set on request and kept, so the dialog text stays while it fades out.\nconst confirmText = ref<{ title: string; message: string; confirmLabel: string; cancelLabel: string } | null>(null)\nconst confirmEnabled = computed(() => props.confirm === true\n || (typeof props.confirm === 'object' && Object.values(props.confirm).some(Boolean)))\n\nfunction textFor(action: ConfirmAction, job?: JobState) {\n if (action === 'clear') {\n const count = tray.deletableJobs.value.length\n return {\n title: 'Clear finished jobs?',\n message: `${count} finished ${count === 1 ? 'job' : 'jobs'} and their stored results are deleted.`,\n confirmLabel: 'Clear jobs',\n cancelLabel: 'Cancel',\n }\n }\n return action === 'cancel'\n ? { title: 'Cancel job?', message: `${job?.name} stops. Its partial results are lost.`, confirmLabel: 'Cancel job', cancelLabel: 'Keep running' }\n : { title: 'Delete job?', message: `${job?.name} and its stored result are deleted.`, confirmLabel: 'Delete job', cancelLabel: 'Cancel' }\n}\n\nfunction needsConfirm(action: ConfirmAction): boolean {\n return props.confirm === true || (typeof props.confirm === 'object' && props.confirm[action] === true)\n}\n\nfunction request(action: ConfirmAction, job?: JobState): void {\n if (!needsConfirm(action)) {\n void run(action, job)\n return\n }\n pending.value = { action, job, ids: action === 'clear' ? deletableIds() : undefined }\n confirmText.value = textFor(action, job)\n confirmOpen.value = true\n}\n\nfunction deletableIds(): string[] {\n return tray.deletableJobs.value.map(job => job.job_id).sort()\n}\n\n// A new source is a new job list: the confirmed target is gone.\nwatch(tray.source, () => onConfirmOpen(false))\n\nfunction onConfirmOpen(open: boolean): void {\n confirmOpen.value = open\n if (!open) pending.value = null\n}\n\nasync function confirmPending(): Promise<void> {\n // A second Confirm click while the dialog fades out does nothing.\n const current = pending.value\n if (!confirmOpen.value || !current) return\n if (current.action === 'clear') {\n // Polling changed the finished jobs: ask again with the new count.\n const ids = deletableIds()\n if (ids.join() !== current.ids?.join()) {\n pending.value = { ...current, ids }\n confirmText.value = textFor('clear')\n return\n }\n }\n confirmOpen.value = false\n pending.value = null\n if (current.action === 'clear') return clearFinished()\n // Polling can end or remove the job while the dialog is open: then do nothing.\n const live = tray.jobs.value.find(job => job.job_id === current.job?.job_id)\n const allowed = live && (current.action === 'cancel'\n ? isActiveJobStatus(live.status) && live.can_cancel\n : live.can_delete)\n if (allowed) await run(current.action, live)\n}\n\nfunction run(action: ConfirmAction, job?: JobState): Promise<void> {\n if (action === 'clear') return clearFinished()\n return action === 'cancel' ? cancelJob(job!) : deleteJob(job!)\n}\n\nasync function cancelJob(job: JobState): Promise<void> {\n const succeeded = await tray.cancelJob(job)\n if (!succeeded && tray.error.value) emit('error', tray.error.value)\n}\n\nasync function deleteJob(job: JobState): Promise<void> {\n const succeeded = await tray.deleteJob(job)\n if (!succeeded && tray.error.value) emit('error', tray.error.value)\n}\n\nasync function clearFinished(): Promise<void> {\n const succeeded = await tray.clearFinished()\n if (!succeeded && tray.error.value) emit('error', tray.error.value)\n}\n</script>\n\n<template>\n <Teleport :to=\"teleportTarget\" :disabled=\"teleportTo === false\">\n <div class=\"mint-jobs-tray\">\n <!-- Clicks outside close the panel; the page is not dimmed. -->\n <div\n v-if=\"tray.isOpen.value\"\n class=\"mint-jobs-tray__scrim\"\n aria-hidden=\"true\"\n @click=\"tray.close()\"\n />\n\n <Transition name=\"mint-jobs-tray-fade\">\n <section\n v-if=\"tray.isOpen.value\"\n :id=\"tray.panelId\"\n ref=\"panelRef\"\n class=\"mint-jobs-tray__panel\"\n :aria-labelledby=\"titleId\"\n tabindex=\"-1\"\n >\n <header class=\"mint-jobs-tray__head\">\n <h2 :id=\"titleId\" class=\"mint-jobs-tray__title\">{{ title }}</h2>\n <span class=\"mint-jobs-tray__head-count\">{{ headCount }}</span>\n <button\n v-if=\"tray.canRefresh.value\"\n type=\"button\"\n class=\"mint-jobs-tray__icon-button\"\n aria-label=\"Refresh jobs\"\n title=\"Refresh jobs\"\n :disabled=\"tray.isLoading.value\"\n @click=\"tray.refresh\"\n >\n <RefreshCw :size=\"14\" aria-hidden=\"true\" />\n </button>\n <button\n type=\"button\"\n class=\"mint-jobs-tray__icon-button\"\n aria-label=\"Close jobs\"\n title=\"Close\"\n @click=\"closeTray\"\n >\n <X :size=\"14\" aria-hidden=\"true\" />\n </button>\n </header>\n\n <p v-if=\"tray.error.value\" class=\"mint-jobs-tray__error\" role=\"alert\">\n {{ tray.error.value }}\n </p>\n\n <div class=\"mint-jobs-tray__body\">\n <p v-if=\"sections.length === 0\" class=\"mint-jobs-tray__empty\">No jobs yet</p>\n\n <template v-for=\"section in sections\" :key=\"section.key\">\n <div class=\"mint-jobs-tray__section\" :data-section=\"section.key\">\n {{ section.title }}\n <span class=\"mint-jobs-tray__section-count\">· {{ section.rows.length }}</span>\n <button\n v-if=\"section.key === 'finished' && canClear\"\n type=\"button\"\n class=\"mint-jobs-tray__section-action\"\n @click=\"request('clear')\"\n >\n Clear\n </button>\n </div>\n\n <div\n v-for=\"{ job, view } in section.rows\"\n :key=\"job.job_id\"\n class=\"mint-jobs-tray__row\"\n :class=\"{ 'mint-jobs-tray__row--awaiting-input': view.status === 'awaiting_input' }\"\n :data-status=\"job.status\"\n >\n <!-- data-status is the real job status; the row view only changes how it looks. -->\n <component\n :is=\"STATUS_ICONS[view.status]\"\n :size=\"15\"\n :class=\"['mint-jobs-tray__status', `mint-jobs-tray__status--${view.status.replace('_', '-')}`]\"\n role=\"img\"\n :aria-label=\"jobStatusLabel(view.status)\"\n />\n <button type=\"button\" class=\"mint-jobs-tray__row-title\" @click=\"emit('select', job)\">\n <slot name=\"job-title\" :job=\"job\">{{ job.name }}</slot>\n </button>\n <span class=\"mint-jobs-tray__tools\">\n <span class=\"mint-jobs-tray__value\">{{ jobValue(job, view.percent) }}</span>\n <slot name=\"job-actions\" :job=\"job\" />\n <button\n v-if=\"isActiveJobStatus(job.status) && job.can_cancel && tray.canCancel.value\"\n type=\"button\"\n class=\"mint-jobs-tray__icon-button mint-jobs-tray__icon-button--danger\"\n :aria-label=\"`Cancel ${job.name}`\"\n title=\"Cancel\"\n :disabled=\"tray.isPending(job)\"\n @click=\"request('cancel', job)\"\n >\n <Square :size=\"12\" aria-hidden=\"true\" />\n </button>\n <button\n v-if=\"job.can_delete && tray.canDelete.value\"\n type=\"button\"\n class=\"mint-jobs-tray__icon-button\"\n :aria-label=\"`Delete ${job.name}`\"\n title=\"Delete\"\n :disabled=\"tray.isPending(job)\"\n @click=\"request('delete', job)\"\n >\n <Trash2 :size=\"14\" aria-hidden=\"true\" />\n </button>\n </span>\n <div\n v-if=\"view.percent != null\"\n class=\"mint-jobs-tray__progress\"\n role=\"progressbar\"\n :aria-label=\"`${job.name} progress`\"\n aria-valuemin=\"0\"\n aria-valuemax=\"100\"\n :aria-valuenow=\"view.percent\"\n >\n <span :style=\"{ width: `${view.percent}%` }\" />\n </div>\n <span\n class=\"mint-jobs-tray__detail\"\n :class=\"{ 'mint-jobs-tray__detail--error': job.status === 'failed' }\"\n >\n <slot name=\"job-detail\" :job=\"job\">{{ view.message }}</slot>\n </span>\n </div>\n </template>\n </div>\n </section>\n </Transition>\n\n <ConfirmDialog\n v-if=\"confirmEnabled\"\n :open=\"confirmOpen\"\n tone=\"error\"\n :title=\"confirmText?.title\"\n :confirm-label=\"confirmText?.confirmLabel\"\n :cancel-label=\"confirmText?.cancelLabel\"\n @update:open=\"onConfirmOpen\"\n @confirm=\"confirmPending\"\n >\n <!-- The marker class lifts the dialog above the tray (jobs-status-tray.css). -->\n <p class=\"mint-confirm__message mint-jobs-tray__confirm\">{{ confirmText?.message }}</p>\n </ConfirmDialog>\n </div>\n </Teleport>\n</template>\n","import {\n getCurrentScope,\n onScopeDispose,\n readonly,\n ref,\n toValue,\n watch,\n type MaybeRefOrGetter,\n type Ref,\n} from 'vue'\n\n/**\n * One event of the platform's realtime stream (`GET /api/events`).\n *\n * Platform events carry no entity data: refetch the entity through REST.\n * `type` is `resync` (refetch everything you show), the audit action of a\n * committed write, such as `experiment.update` or `analysis.artifact_create`,\n * or the `\"<plugin>.<event>\"` name of a plugin event, which carries `payload`.\n * Only `usePresence` receives `presence.changed`.\n */\nexport interface RealtimeEvent {\n type: string\n id?: string\n /**\n * `experiment:{id}`, `project:{id}`, `experiments`, `user:{id}`, or a plugin's\n * `plugin:{name}` / `plugin:{name}:experiment:{id}`; absent on `resync`.\n */\n topic?: string\n /** A plugin event: the JSON payload the plugin published (at most 16 KiB). */\n payload?: unknown\n /** Changed fields of an update, when the write names them. */\n fields?: string[] | null\n actor_id?: string | null\n request_id?: string | null\n at?: string\n /** `presence.changed`: the topic's viewers (at most 20, `editing` first). */\n viewers?: { user_id: string, activity: string }[]\n /** `presence.changed`: the number of viewers, also those beyond `viewers`. */\n count?: number\n}\n\nexport type RealtimeHandler = (event: RealtimeEvent) => void\n\nexport interface UseRealtimeReturn {\n /** True while the shared stream is open. */\n connected: Readonly<Ref<boolean>>\n /** Unsubscribe; also runs when the calling component or effect scope is disposed. */\n stop: () => void\n}\n\nconst EVENTS_URL = '/api/events'\nconst RECONNECT_BASE_MS = 1_000\nconst RECONNECT_MAX_MS = 30_000\n/** Merges the subscriptions of components that mount together into one connection. */\nconst TOPIC_DEBOUNCE_MS = 50\nconst RESYNC: RealtimeEvent = { type: 'resync' }\n\ninterface Listener {\n topics: () => string[]\n handler: RealtimeHandler\n /** Receives `presence.changed`; a write listener would refetch on each viewer change. */\n presence: boolean\n}\n\nconst listeners = new Set<Listener>()\n/** The last `presence.changed` of each topic of the open stream; the server sends one per topic at open. */\nconst presence = new Map<string, RealtimeEvent>()\nconst connected = ref(false)\nlet source: EventSource | null = null\nlet sourceTopics = ''\nlet failures = 0\nlet syncTimer: ReturnType<typeof setTimeout> | null = null\nlet retryTimer: ReturnType<typeof setTimeout> | null = null\n\nfunction dispatch(event: RealtimeEvent): void {\n const isPresence = event.type === 'presence.changed'\n if (isPresence && event.topic) presence.set(event.topic, event)\n for (const listener of [...listeners]) {\n if (isPresence && !listener.presence) continue\n if (event.type === 'resync' || (event.topic && listener.topics().includes(event.topic))) {\n listener.handler(event)\n }\n }\n}\n\nfunction close(): void {\n source?.close()\n source = null\n sourceTopics = ''\n presence.clear()\n connected.value = false\n}\n\nfunction open(topics: string): void {\n const stream = new EventSource(`${EVENTS_URL}?topics=${encodeURIComponent(topics)}`)\n source = stream\n sourceTopics = topics\n stream.onopen = () => {\n connected.value = true\n // The server subscribes only now: a write between a caller's REST load (or\n // the close of the previous stream) and this point sent no event, so every caller refetches.\n dispatch(RESYNC)\n failures = 0\n }\n stream.onmessage = (message) => {\n dispatch(JSON.parse(message.data) as RealtimeEvent)\n }\n stream.onerror = () => {\n // EventSource retries a dropped connection itself but gives up after an\n // HTTP error, so one backoff path handles both.\n if (source !== stream) return\n close()\n // A topic change during the wait does not shorten it: the retry reads the topics when it runs.\n if (syncTimer !== null) clearTimeout(syncTimer)\n syncTimer = null\n retryTimer = setTimeout(() => {\n retryTimer = null\n sync()\n }, Math.min(RECONNECT_MAX_MS, RECONNECT_BASE_MS * 2 ** failures))\n failures += 1\n }\n}\n\nfunction sync(): void {\n syncTimer = null\n const topics = [...new Set([...listeners].flatMap(listener => listener.topics()))].sort().join(',')\n if (source && topics === sourceTopics) return\n close()\n if (topics) open(topics)\n}\n\nfunction schedule(): void {\n if (retryTimer !== null) return\n if (syncTimer !== null) clearTimeout(syncTimer)\n syncTimer = setTimeout(sync, TOPIC_DEBOUNCE_MS)\n}\n\n/**\n * Subscribe to topics of the platform's realtime stream.\n *\n * Every caller in a tab shares one `EventSource`, opened on the union of\n * their topics and reopened when that union changes. `handler` receives the\n * write events of the caller's own topics (not `presence.changed`, which goes\n * to `usePresence`) plus every `resync`: one comes from the\n * server when this tab fell behind, and one follows each open of the stream:\n * the first open, each reconnect (backoff from 1 s to 30 s) and each reopen for\n * a changed topic union. On `resync`, refetch. The union of all callers' topics\n * in a tab may hold at most 50 topics; the platform refuses a larger stream.\n *\n * The stream authenticates with the session cookie, so it works in the\n * platform and in plugin frontends served by it. It exists only when the\n * platform's `realtime` feature flag is on; check that flag first.\n *\n * A plugin topic reaches a caller whose role may use the plugin; an\n * experiment plugin topic also needs a caller who may view the experiment.\n *\n * @example\n * useRealtime(() => [`experiment:${id.value}`], () => refetch())\n * @example\n * useRealtime(['plugin:drp'], (event) => {\n * if (event.type === 'drp.run.progress') progress.value = event.payload as RunProgress\n * })\n */\nexport function useRealtime(\n topics: MaybeRefOrGetter<string[]>,\n handler: RealtimeHandler,\n): UseRealtimeReturn {\n return subscribeRealtime(topics, handler, false)\n}\n\n/** The last `presence.changed` of `topic` while the open stream views it (for `usePresence`). */\nexport function currentPresence(topic: string): RealtimeEvent | undefined {\n return presence.get(topic)\n}\n\n/** `useRealtime`, and with `withPresence` also the `presence.changed` events (for `usePresence`). */\nexport function subscribeRealtime(\n topics: MaybeRefOrGetter<string[]>,\n handler: RealtimeHandler,\n withPresence: boolean,\n): UseRealtimeReturn {\n const listener: Listener = { topics: () => toValue(topics), handler, presence: withPresence }\n listeners.add(listener)\n const stopWatch = watch(() => listener.topics().join(','), () => schedule())\n schedule()\n\n function stop(): void {\n stopWatch()\n if (listeners.delete(listener)) schedule()\n }\n\n if (getCurrentScope()) onScopeDispose(stop)\n return { connected: readonly(connected), stop }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA6CA,MAAM,QAAQ;EAMd,MAAM,OAAO;EAcb,MAAM,eAA6C;GACjD,SAAS;GACT,gBAAgB;GAChB,QAAQ;GACR,WAAW;GACX,QAAQ;GACR,WAAW;EACb;EAEA,MAAM,WAAW,IAAwB,IAAI;EAC7C,MAAM,iBAAiB,eAAe,MAAM,cAAc,MAAM;EAChE,MAAM,OAAO,MAAM;EACnB,MAAM,UAAU,GAAG,KAAK,QAAQ;EAChC,MAAM,QAAQ,SAAqB,KAAK,KAAI,SAAQ;GAAE;GAAK,MAAM,KAAK,QAAQ,GAAG;EAAE,EAAE;EAErF,MAAM,aAAa,eAAe;GAChC,MAAM,SAAS,KAAK,KAAK,WAAW,KAAK;GACzC,OAAO,CACL,GAAG,OAAO,QAAO,QAAO,IAAI,KAAK,WAAW,gBAAgB,GAC5D,GAAG,OAAO,QAAO,QAAO,IAAI,KAAK,WAAW,gBAAgB,CAC9D;EACF,CAAC;EACD,MAAM,WAAW,eAAe,CAC9B;GAAE,KAAK;GAAU,OAAO;GAAU,MAAM,WAAW;EAAM,GACzD;GAAE,KAAK;GAAY,OAAO;GAAY,MAAM,KAAK,KAAK,YAAY,KAAK;EAAE,CAC3E,CAAC,CAAC,QAAO,YAAW,QAAQ,KAAK,SAAS,CAAC,CAAC;EAC5C,MAAM,YAAY,eAAe;GAC/B,MAAM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,IAAI,eAAe,MAAM;CACzB,IAAI,cAAc,MAAM,aAAa,SAAS;CAC9C,YAAY,WAAW,MAAM,iBAAiB;AAChD;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,SAAgB,YACd,QACA,SACmB;CACnB,OAAO,kBAAkB,QAAQ,SAAS,KAAK;AACjD;;AAGA,SAAgB,gBAAgB,OAA0C;CACxE,OAAO,SAAS,IAAI,KAAK;AAC3B;;AAGA,SAAgB,kBACd,QACA,SACA,cACmB;CACnB,MAAM,WAAqB;EAAE,cAAc,QAAQ,MAAM;EAAG;EAAS,UAAU;CAAa;CAC5F,UAAU,IAAI,QAAQ;CACtB,MAAM,YAAY,YAAY,SAAS,OAAO,CAAC,CAAC,KAAK,GAAG,SAAS,SAAS,CAAC;CAC3E,SAAS;CAET,SAAS,OAAa;EACpB,UAAU;EACV,IAAI,UAAU,OAAO,QAAQ,GAAG,SAAS;CAC3C;CAEA,IAAI,gBAAgB,GAAG,eAAe,IAAI;CAC1C,OAAO;EAAE,WAAW,SAAS,SAAS;EAAG;CAAK;AAChD"}
1
+ {"version":3,"file":"useRealtime-BLQEjbuq.js","names":[],"sources":["../src/components/JobsStatusTray.vue","../src/components/JobsStatusTray.vue","../src/composables/useRealtime.ts"],"sourcesContent":["<script setup lang=\"ts\">\n/**\n * Compact, non-modal job panel under the top bar, driven by a job center the parent owns.\n *\n * The parent passes the center's `topBarJob`, `completedCount` and `handleTopBarClick`\n * to `AppTopBar`; its run slot opens this panel. `PluginWorkspaceView` does this for you\n * when its spec sets `jobs`.\n *\n * @example Recommended\n * ```vue\n * <AppTopBar :job=\"center.topBarJob.value\" :jobs-done=\"center.completedCount.value\"\n * @job-click=\"center.handleTopBarClick(openResult)\" />\n * <JobsStatusTray :center=\"center\" @select=\"openResult\" />\n * ```\n */\nimport { computed, nextTick, onBeforeUnmount, ref, watch, type Component } from 'vue'\nimport {\n CircleAlert,\n CircleCheck,\n CircleSlash,\n CircleX,\n Clock,\n LoaderCircle,\n RefreshCw,\n Square,\n Trash2,\n X,\n} from 'lucide-vue-next'\n\nimport { isActiveJobStatus, jobStatusLabel } from '../jobs'\nimport type { UseJobCenterReturn } from '../composables/useJobCenter'\nimport type { JobState, JobStatus } from '../types/jobs'\nimport ConfirmDialog from './ConfirmDialog.vue'\n\ntype ConfirmAction = 'cancel' | 'delete' | 'clear'\n\ninterface Props {\n /** Job center from `useJobCenter()`; the parent owns it and opens the panel through it. */\n center: UseJobCenterReturn\n title?: string\n teleportTo?: string | HTMLElement | false\n /** Ask before Cancel, Delete and Clear (`true`), or before the named ones only. Default off. */\n confirm?: boolean | Partial<Record<ConfirmAction, boolean>>\n}\n\nconst props = withDefaults(defineProps<Props>(), {\n title: 'Jobs',\n teleportTo: 'body',\n confirm: false,\n})\n\nconst emit = defineEmits<{\n select: [job: JobState]\n error: [message: string]\n}>()\n\ndefineSlots<{\n /** Extra per-row actions, rendered before the built-in Cancel / Delete. */\n 'job-actions'?: (props: { job: JobState }) => unknown\n /** Row title. Default: the job name. */\n 'job-title'?: (props: { job: JobState }) => unknown\n /** Detail line under the title. Default: the error, progress message or status. */\n 'job-detail'?: (props: { job: JobState }) => unknown\n}>()\n\nconst STATUS_ICONS: Record<JobStatus, Component> = {\n running: LoaderCircle,\n awaiting_input: CircleAlert,\n queued: Clock,\n completed: CircleCheck,\n failed: CircleX,\n cancelled: CircleSlash,\n}\n\nconst panelRef = ref<HTMLElement | null>(null)\nconst teleportTarget = computed(() => props.teleportTo || 'body')\nconst tray = props.center\nconst titleId = `${tray.panelId}-title`\nconst rows = (jobs: JobState[]) => jobs.map(job => ({ job, view: tray.rowView(job) }))\n// A job waiting for input is the only one that needs a person: pin it first.\nconst activeRows = computed(() => {\n const active = rows(tray.activeJobs.value)\n return [\n ...active.filter(row => row.view.status === 'awaiting_input'),\n ...active.filter(row => row.view.status !== 'awaiting_input'),\n ]\n})\nconst sections = computed(() => [\n { key: 'active', title: 'Active', rows: activeRows.value },\n { key: 'finished', title: 'Finished', rows: rows(tray.historyJobs.value) },\n].filter(section => section.rows.length > 0))\nconst headCount = computed(() => {\n const parts = [\n [tray.activeJobs.value.length, 'active'],\n [tray.completedCount.value, 'done'],\n [tray.historyJobs.value.filter(job => job.status === 'failed').length, 'failed'],\n ].filter(([n]) => n).map(([n, word]) => `${n} ${word}`)\n return parts.length ? parts.join(' · ') : 'No jobs'\n})\nconst canClear = computed(() => (\n tray.deletableJobs.value.length > 0\n && tray.canClearFinished.value\n))\n\n// Escape returns focus to the element that opened the panel (the top-bar chip).\n// The panel is non-modal, so Escape is heard on the document while it is open.\n// An Escape that an inner control handled, or that belongs to a modal dialog\n// above the tray (its own confirm dialog too), leaves the tray open.\nlet opener: HTMLElement | null = null\nfunction onDocumentKeydown(event: KeyboardEvent): void {\n if (event.key !== 'Escape' || event.defaultPrevented || confirmOpen.value) return\n if (event.target instanceof Element && event.target.closest('[aria-modal=\"true\"]')) return\n closeTray()\n}\nwatch(tray.isOpen, async (open) => {\n if (!open) {\n document.removeEventListener('keydown', onDocumentKeydown)\n return\n }\n opener = document.activeElement instanceof HTMLElement ? document.activeElement : null\n document.addEventListener('keydown', onDocumentKeydown)\n await nextTick()\n panelRef.value?.focus()\n}, { flush: 'sync' })\nonBeforeUnmount(() => document.removeEventListener('keydown', onDocumentKeydown))\n\n// A focused row that leaves the list (an action or a refresh) drops focus to body:\n// note the focused element before the update and keep focus in the panel after it.\nlet focusedInPanel: Element | null = null\nwatch(tray.jobs, () => {\n const focused = document.activeElement\n focusedInPanel = focused && panelRef.value?.contains(focused) ? focused : null\n}, { flush: 'pre' })\nwatch(tray.jobs, () => {\n if (tray.isOpen.value && focusedInPanel && !focusedInPanel.isConnected) panelRef.value?.focus()\n focusedInPanel = null\n}, { flush: 'post' })\n\nfunction closeTray(): void {\n tray.close()\n // Safari leaves a clicked button unfocused (opener = body), and the chip node is\n // replaced when it switches between job chip and idle button: fall back to the\n // top-bar jobs control.\n const target = opener?.isConnected && opener !== document.body\n ? opener\n : document.querySelector<HTMLElement>('.mint-topbar__job')\n target?.focus()\n}\n\nfunction formatTime(value: string | null): string {\n if (!value) return ''\n const date = new Date(value)\n return Number.isNaN(date.getTime())\n ? ''\n : date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })\n}\n\n/** Right-hand value: the percent while a job moves, else when it ended or started. */\nfunction jobValue(job: JobState, percent: number | null): string {\n if (percent != null) return `${percent}%`\n return formatTime(job.completed_at || job.started_at || job.created_at)\n}\n\n// Confirmation: the action waits for the dialog; it runs on the live job.\n// `ids`: the finished jobs that the user confirmed to clear.\nconst pending = ref<{ action: ConfirmAction; job?: JobState; ids?: string[] } | null>(null)\nconst confirmOpen = ref(false)\n// Set on request and kept, so the dialog text stays while it fades out.\nconst confirmText = ref<{ title: string; message: string; confirmLabel: string; cancelLabel: string } | null>(null)\nconst confirmEnabled = computed(() => props.confirm === true\n || (typeof props.confirm === 'object' && Object.values(props.confirm).some(Boolean)))\n\nfunction textFor(action: ConfirmAction, job?: JobState) {\n if (action === 'clear') {\n const count = tray.deletableJobs.value.length\n return {\n title: 'Clear finished jobs?',\n message: `${count} finished ${count === 1 ? 'job' : 'jobs'} and their stored results are deleted.`,\n confirmLabel: 'Clear jobs',\n cancelLabel: 'Cancel',\n }\n }\n return action === 'cancel'\n ? { title: 'Cancel job?', message: `${job?.name} stops. Its partial results are lost.`, confirmLabel: 'Cancel job', cancelLabel: 'Keep running' }\n : { title: 'Delete job?', message: `${job?.name} and its stored result are deleted.`, confirmLabel: 'Delete job', cancelLabel: 'Cancel' }\n}\n\nfunction needsConfirm(action: ConfirmAction): boolean {\n return props.confirm === true || (typeof props.confirm === 'object' && props.confirm[action] === true)\n}\n\nfunction request(action: ConfirmAction, job?: JobState): void {\n if (!needsConfirm(action)) {\n void run(action, job)\n return\n }\n pending.value = { action, job, ids: action === 'clear' ? deletableIds() : undefined }\n confirmText.value = textFor(action, job)\n confirmOpen.value = true\n}\n\nfunction deletableIds(): string[] {\n return tray.deletableJobs.value.map(job => job.job_id).sort()\n}\n\n// A new source is a new job list: the confirmed target is gone.\nwatch(tray.source, () => onConfirmOpen(false))\n\nfunction onConfirmOpen(open: boolean): void {\n confirmOpen.value = open\n if (!open) pending.value = null\n}\n\nasync function confirmPending(): Promise<void> {\n // A second Confirm click while the dialog fades out does nothing.\n const current = pending.value\n if (!confirmOpen.value || !current) return\n if (current.action === 'clear') {\n // Polling changed the finished jobs: ask again with the new count.\n const ids = deletableIds()\n if (ids.join() !== current.ids?.join()) {\n pending.value = { ...current, ids }\n confirmText.value = textFor('clear')\n return\n }\n }\n confirmOpen.value = false\n pending.value = null\n if (current.action === 'clear') return clearFinished()\n // Polling can end or remove the job while the dialog is open: then do nothing.\n const live = tray.jobs.value.find(job => job.job_id === current.job?.job_id)\n const allowed = live && (current.action === 'cancel'\n ? isActiveJobStatus(live.status) && live.can_cancel\n : live.can_delete)\n if (allowed) await run(current.action, live)\n}\n\nfunction run(action: ConfirmAction, job?: JobState): Promise<void> {\n if (action === 'clear') return clearFinished()\n return action === 'cancel' ? cancelJob(job!) : deleteJob(job!)\n}\n\nasync function cancelJob(job: JobState): Promise<void> {\n const succeeded = await tray.cancelJob(job)\n if (!succeeded && tray.error.value) emit('error', tray.error.value)\n}\n\nasync function deleteJob(job: JobState): Promise<void> {\n const succeeded = await tray.deleteJob(job)\n if (!succeeded && tray.error.value) emit('error', tray.error.value)\n}\n\nasync function clearFinished(): Promise<void> {\n const succeeded = await tray.clearFinished()\n if (!succeeded && tray.error.value) emit('error', tray.error.value)\n}\n</script>\n\n<template>\n <Teleport :to=\"teleportTarget\" :disabled=\"teleportTo === false\">\n <div class=\"mint-jobs-tray\">\n <!-- Clicks outside close the panel; the page is not dimmed. -->\n <div\n v-if=\"tray.isOpen.value\"\n class=\"mint-jobs-tray__scrim\"\n aria-hidden=\"true\"\n @click=\"tray.close()\"\n />\n\n <Transition name=\"mint-jobs-tray-fade\">\n <section\n v-if=\"tray.isOpen.value\"\n :id=\"tray.panelId\"\n ref=\"panelRef\"\n class=\"mint-jobs-tray__panel\"\n :aria-labelledby=\"titleId\"\n tabindex=\"-1\"\n >\n <header class=\"mint-jobs-tray__head\">\n <h2 :id=\"titleId\" class=\"mint-jobs-tray__title\">{{ title }}</h2>\n <span class=\"mint-jobs-tray__head-count\">{{ headCount }}</span>\n <button\n v-if=\"tray.canRefresh.value\"\n type=\"button\"\n class=\"mint-jobs-tray__icon-button\"\n aria-label=\"Refresh jobs\"\n title=\"Refresh jobs\"\n :disabled=\"tray.isLoading.value\"\n @click=\"tray.refresh\"\n >\n <RefreshCw :size=\"14\" aria-hidden=\"true\" />\n </button>\n <button\n type=\"button\"\n class=\"mint-jobs-tray__icon-button\"\n aria-label=\"Close jobs\"\n title=\"Close\"\n @click=\"closeTray\"\n >\n <X :size=\"14\" aria-hidden=\"true\" />\n </button>\n </header>\n\n <p v-if=\"tray.error.value\" class=\"mint-jobs-tray__error\" role=\"alert\">\n {{ tray.error.value }}\n </p>\n\n <div class=\"mint-jobs-tray__body\">\n <p v-if=\"sections.length === 0\" class=\"mint-jobs-tray__empty\">No jobs yet</p>\n\n <template v-for=\"section in sections\" :key=\"section.key\">\n <div class=\"mint-jobs-tray__section\" :data-section=\"section.key\">\n {{ section.title }}\n <span class=\"mint-jobs-tray__section-count\">· {{ section.rows.length }}</span>\n <button\n v-if=\"section.key === 'finished' && canClear\"\n type=\"button\"\n class=\"mint-jobs-tray__section-action\"\n @click=\"request('clear')\"\n >\n Clear\n </button>\n </div>\n\n <div\n v-for=\"{ job, view } in section.rows\"\n :key=\"job.job_id\"\n class=\"mint-jobs-tray__row\"\n :class=\"{ 'mint-jobs-tray__row--awaiting-input': view.status === 'awaiting_input' }\"\n :data-status=\"job.status\"\n >\n <!-- data-status is the real job status; the row view only changes how it looks. -->\n <component\n :is=\"STATUS_ICONS[view.status]\"\n :size=\"15\"\n :class=\"['mint-jobs-tray__status', `mint-jobs-tray__status--${view.status.replace('_', '-')}`]\"\n role=\"img\"\n :aria-label=\"jobStatusLabel(view.status)\"\n />\n <button type=\"button\" class=\"mint-jobs-tray__row-title\" @click=\"emit('select', job)\">\n <slot name=\"job-title\" :job=\"job\">{{ job.name }}</slot>\n </button>\n <span class=\"mint-jobs-tray__tools\">\n <span class=\"mint-jobs-tray__value\">{{ jobValue(job, view.percent) }}</span>\n <slot name=\"job-actions\" :job=\"job\" />\n <button\n v-if=\"isActiveJobStatus(job.status) && job.can_cancel && tray.canCancel.value\"\n type=\"button\"\n class=\"mint-jobs-tray__icon-button mint-jobs-tray__icon-button--danger\"\n :aria-label=\"`Cancel ${job.name}`\"\n title=\"Cancel\"\n :disabled=\"tray.isPending(job)\"\n @click=\"request('cancel', job)\"\n >\n <Square :size=\"12\" aria-hidden=\"true\" />\n </button>\n <button\n v-if=\"job.can_delete && tray.canDelete.value\"\n type=\"button\"\n class=\"mint-jobs-tray__icon-button\"\n :aria-label=\"`Delete ${job.name}`\"\n title=\"Delete\"\n :disabled=\"tray.isPending(job)\"\n @click=\"request('delete', job)\"\n >\n <Trash2 :size=\"14\" aria-hidden=\"true\" />\n </button>\n </span>\n <div\n v-if=\"view.percent != null\"\n class=\"mint-jobs-tray__progress\"\n role=\"progressbar\"\n :aria-label=\"`${job.name} progress`\"\n aria-valuemin=\"0\"\n aria-valuemax=\"100\"\n :aria-valuenow=\"view.percent\"\n >\n <span :style=\"{ width: `${view.percent}%` }\" />\n </div>\n <span\n class=\"mint-jobs-tray__detail\"\n :class=\"{ 'mint-jobs-tray__detail--error': job.status === 'failed' }\"\n >\n <slot name=\"job-detail\" :job=\"job\">{{ view.message }}</slot>\n </span>\n </div>\n </template>\n </div>\n </section>\n </Transition>\n\n <ConfirmDialog\n v-if=\"confirmEnabled\"\n :open=\"confirmOpen\"\n tone=\"error\"\n :title=\"confirmText?.title\"\n :confirm-label=\"confirmText?.confirmLabel\"\n :cancel-label=\"confirmText?.cancelLabel\"\n @update:open=\"onConfirmOpen\"\n @confirm=\"confirmPending\"\n >\n <!-- The marker class lifts the dialog above the tray (jobs-status-tray.css). -->\n <p class=\"mint-confirm__message mint-jobs-tray__confirm\">{{ confirmText?.message }}</p>\n </ConfirmDialog>\n </div>\n </Teleport>\n</template>\n","<script setup lang=\"ts\">\n/**\n * Compact, non-modal job panel under the top bar, driven by a job center the parent owns.\n *\n * The parent passes the center's `topBarJob`, `completedCount` and `handleTopBarClick`\n * to `AppTopBar`; its run slot opens this panel. `PluginWorkspaceView` does this for you\n * when its spec sets `jobs`.\n *\n * @example Recommended\n * ```vue\n * <AppTopBar :job=\"center.topBarJob.value\" :jobs-done=\"center.completedCount.value\"\n * @job-click=\"center.handleTopBarClick(openResult)\" />\n * <JobsStatusTray :center=\"center\" @select=\"openResult\" />\n * ```\n */\nimport { computed, nextTick, onBeforeUnmount, ref, watch, type Component } from 'vue'\nimport {\n CircleAlert,\n CircleCheck,\n CircleSlash,\n CircleX,\n Clock,\n LoaderCircle,\n RefreshCw,\n Square,\n Trash2,\n X,\n} from 'lucide-vue-next'\n\nimport { isActiveJobStatus, jobStatusLabel } from '../jobs'\nimport type { UseJobCenterReturn } from '../composables/useJobCenter'\nimport type { JobState, JobStatus } from '../types/jobs'\nimport ConfirmDialog from './ConfirmDialog.vue'\n\ntype ConfirmAction = 'cancel' | 'delete' | 'clear'\n\ninterface Props {\n /** Job center from `useJobCenter()`; the parent owns it and opens the panel through it. */\n center: UseJobCenterReturn\n title?: string\n teleportTo?: string | HTMLElement | false\n /** Ask before Cancel, Delete and Clear (`true`), or before the named ones only. Default off. */\n confirm?: boolean | Partial<Record<ConfirmAction, boolean>>\n}\n\nconst props = withDefaults(defineProps<Props>(), {\n title: 'Jobs',\n teleportTo: 'body',\n confirm: false,\n})\n\nconst emit = defineEmits<{\n select: [job: JobState]\n error: [message: string]\n}>()\n\ndefineSlots<{\n /** Extra per-row actions, rendered before the built-in Cancel / Delete. */\n 'job-actions'?: (props: { job: JobState }) => unknown\n /** Row title. Default: the job name. */\n 'job-title'?: (props: { job: JobState }) => unknown\n /** Detail line under the title. Default: the error, progress message or status. */\n 'job-detail'?: (props: { job: JobState }) => unknown\n}>()\n\nconst STATUS_ICONS: Record<JobStatus, Component> = {\n running: LoaderCircle,\n awaiting_input: CircleAlert,\n queued: Clock,\n completed: CircleCheck,\n failed: CircleX,\n cancelled: CircleSlash,\n}\n\nconst panelRef = ref<HTMLElement | null>(null)\nconst teleportTarget = computed(() => props.teleportTo || 'body')\nconst tray = props.center\nconst titleId = `${tray.panelId}-title`\nconst rows = (jobs: JobState[]) => jobs.map(job => ({ job, view: tray.rowView(job) }))\n// A job waiting for input is the only one that needs a person: pin it first.\nconst activeRows = computed(() => {\n const active = rows(tray.activeJobs.value)\n return [\n ...active.filter(row => row.view.status === 'awaiting_input'),\n ...active.filter(row => row.view.status !== 'awaiting_input'),\n ]\n})\nconst sections = computed(() => [\n { key: 'active', title: 'Active', rows: activeRows.value },\n { key: 'finished', title: 'Finished', rows: rows(tray.historyJobs.value) },\n].filter(section => section.rows.length > 0))\nconst headCount = computed(() => {\n const parts = [\n [tray.activeJobs.value.length, 'active'],\n [tray.completedCount.value, 'done'],\n [tray.historyJobs.value.filter(job => job.status === 'failed').length, 'failed'],\n ].filter(([n]) => n).map(([n, word]) => `${n} ${word}`)\n return parts.length ? parts.join(' · ') : 'No jobs'\n})\nconst canClear = computed(() => (\n tray.deletableJobs.value.length > 0\n && tray.canClearFinished.value\n))\n\n// Escape returns focus to the element that opened the panel (the top-bar chip).\n// The panel is non-modal, so Escape is heard on the document while it is open.\n// An Escape that an inner control handled, or that belongs to a modal dialog\n// above the tray (its own confirm dialog too), leaves the tray open.\nlet opener: HTMLElement | null = null\nfunction onDocumentKeydown(event: KeyboardEvent): void {\n if (event.key !== 'Escape' || event.defaultPrevented || confirmOpen.value) return\n if (event.target instanceof Element && event.target.closest('[aria-modal=\"true\"]')) return\n closeTray()\n}\nwatch(tray.isOpen, async (open) => {\n if (!open) {\n document.removeEventListener('keydown', onDocumentKeydown)\n return\n }\n opener = document.activeElement instanceof HTMLElement ? document.activeElement : null\n document.addEventListener('keydown', onDocumentKeydown)\n await nextTick()\n panelRef.value?.focus()\n}, { flush: 'sync' })\nonBeforeUnmount(() => document.removeEventListener('keydown', onDocumentKeydown))\n\n// A focused row that leaves the list (an action or a refresh) drops focus to body:\n// note the focused element before the update and keep focus in the panel after it.\nlet focusedInPanel: Element | null = null\nwatch(tray.jobs, () => {\n const focused = document.activeElement\n focusedInPanel = focused && panelRef.value?.contains(focused) ? focused : null\n}, { flush: 'pre' })\nwatch(tray.jobs, () => {\n if (tray.isOpen.value && focusedInPanel && !focusedInPanel.isConnected) panelRef.value?.focus()\n focusedInPanel = null\n}, { flush: 'post' })\n\nfunction closeTray(): void {\n tray.close()\n // Safari leaves a clicked button unfocused (opener = body), and the chip node is\n // replaced when it switches between job chip and idle button: fall back to the\n // top-bar jobs control.\n const target = opener?.isConnected && opener !== document.body\n ? opener\n : document.querySelector<HTMLElement>('.mint-topbar__job')\n target?.focus()\n}\n\nfunction formatTime(value: string | null): string {\n if (!value) return ''\n const date = new Date(value)\n return Number.isNaN(date.getTime())\n ? ''\n : date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })\n}\n\n/** Right-hand value: the percent while a job moves, else when it ended or started. */\nfunction jobValue(job: JobState, percent: number | null): string {\n if (percent != null) return `${percent}%`\n return formatTime(job.completed_at || job.started_at || job.created_at)\n}\n\n// Confirmation: the action waits for the dialog; it runs on the live job.\n// `ids`: the finished jobs that the user confirmed to clear.\nconst pending = ref<{ action: ConfirmAction; job?: JobState; ids?: string[] } | null>(null)\nconst confirmOpen = ref(false)\n// Set on request and kept, so the dialog text stays while it fades out.\nconst confirmText = ref<{ title: string; message: string; confirmLabel: string; cancelLabel: string } | null>(null)\nconst confirmEnabled = computed(() => props.confirm === true\n || (typeof props.confirm === 'object' && Object.values(props.confirm).some(Boolean)))\n\nfunction textFor(action: ConfirmAction, job?: JobState) {\n if (action === 'clear') {\n const count = tray.deletableJobs.value.length\n return {\n title: 'Clear finished jobs?',\n message: `${count} finished ${count === 1 ? 'job' : 'jobs'} and their stored results are deleted.`,\n confirmLabel: 'Clear jobs',\n cancelLabel: 'Cancel',\n }\n }\n return action === 'cancel'\n ? { title: 'Cancel job?', message: `${job?.name} stops. Its partial results are lost.`, confirmLabel: 'Cancel job', cancelLabel: 'Keep running' }\n : { title: 'Delete job?', message: `${job?.name} and its stored result are deleted.`, confirmLabel: 'Delete job', cancelLabel: 'Cancel' }\n}\n\nfunction needsConfirm(action: ConfirmAction): boolean {\n return props.confirm === true || (typeof props.confirm === 'object' && props.confirm[action] === true)\n}\n\nfunction request(action: ConfirmAction, job?: JobState): void {\n if (!needsConfirm(action)) {\n void run(action, job)\n return\n }\n pending.value = { action, job, ids: action === 'clear' ? deletableIds() : undefined }\n confirmText.value = textFor(action, job)\n confirmOpen.value = true\n}\n\nfunction deletableIds(): string[] {\n return tray.deletableJobs.value.map(job => job.job_id).sort()\n}\n\n// A new source is a new job list: the confirmed target is gone.\nwatch(tray.source, () => onConfirmOpen(false))\n\nfunction onConfirmOpen(open: boolean): void {\n confirmOpen.value = open\n if (!open) pending.value = null\n}\n\nasync function confirmPending(): Promise<void> {\n // A second Confirm click while the dialog fades out does nothing.\n const current = pending.value\n if (!confirmOpen.value || !current) return\n if (current.action === 'clear') {\n // Polling changed the finished jobs: ask again with the new count.\n const ids = deletableIds()\n if (ids.join() !== current.ids?.join()) {\n pending.value = { ...current, ids }\n confirmText.value = textFor('clear')\n return\n }\n }\n confirmOpen.value = false\n pending.value = null\n if (current.action === 'clear') return clearFinished()\n // Polling can end or remove the job while the dialog is open: then do nothing.\n const live = tray.jobs.value.find(job => job.job_id === current.job?.job_id)\n const allowed = live && (current.action === 'cancel'\n ? isActiveJobStatus(live.status) && live.can_cancel\n : live.can_delete)\n if (allowed) await run(current.action, live)\n}\n\nfunction run(action: ConfirmAction, job?: JobState): Promise<void> {\n if (action === 'clear') return clearFinished()\n return action === 'cancel' ? cancelJob(job!) : deleteJob(job!)\n}\n\nasync function cancelJob(job: JobState): Promise<void> {\n const succeeded = await tray.cancelJob(job)\n if (!succeeded && tray.error.value) emit('error', tray.error.value)\n}\n\nasync function deleteJob(job: JobState): Promise<void> {\n const succeeded = await tray.deleteJob(job)\n if (!succeeded && tray.error.value) emit('error', tray.error.value)\n}\n\nasync function clearFinished(): Promise<void> {\n const succeeded = await tray.clearFinished()\n if (!succeeded && tray.error.value) emit('error', tray.error.value)\n}\n</script>\n\n<template>\n <Teleport :to=\"teleportTarget\" :disabled=\"teleportTo === false\">\n <div class=\"mint-jobs-tray\">\n <!-- Clicks outside close the panel; the page is not dimmed. -->\n <div\n v-if=\"tray.isOpen.value\"\n class=\"mint-jobs-tray__scrim\"\n aria-hidden=\"true\"\n @click=\"tray.close()\"\n />\n\n <Transition name=\"mint-jobs-tray-fade\">\n <section\n v-if=\"tray.isOpen.value\"\n :id=\"tray.panelId\"\n ref=\"panelRef\"\n class=\"mint-jobs-tray__panel\"\n :aria-labelledby=\"titleId\"\n tabindex=\"-1\"\n >\n <header class=\"mint-jobs-tray__head\">\n <h2 :id=\"titleId\" class=\"mint-jobs-tray__title\">{{ title }}</h2>\n <span class=\"mint-jobs-tray__head-count\">{{ headCount }}</span>\n <button\n v-if=\"tray.canRefresh.value\"\n type=\"button\"\n class=\"mint-jobs-tray__icon-button\"\n aria-label=\"Refresh jobs\"\n title=\"Refresh jobs\"\n :disabled=\"tray.isLoading.value\"\n @click=\"tray.refresh\"\n >\n <RefreshCw :size=\"14\" aria-hidden=\"true\" />\n </button>\n <button\n type=\"button\"\n class=\"mint-jobs-tray__icon-button\"\n aria-label=\"Close jobs\"\n title=\"Close\"\n @click=\"closeTray\"\n >\n <X :size=\"14\" aria-hidden=\"true\" />\n </button>\n </header>\n\n <p v-if=\"tray.error.value\" class=\"mint-jobs-tray__error\" role=\"alert\">\n {{ tray.error.value }}\n </p>\n\n <div class=\"mint-jobs-tray__body\">\n <p v-if=\"sections.length === 0\" class=\"mint-jobs-tray__empty\">No jobs yet</p>\n\n <template v-for=\"section in sections\" :key=\"section.key\">\n <div class=\"mint-jobs-tray__section\" :data-section=\"section.key\">\n {{ section.title }}\n <span class=\"mint-jobs-tray__section-count\">· {{ section.rows.length }}</span>\n <button\n v-if=\"section.key === 'finished' && canClear\"\n type=\"button\"\n class=\"mint-jobs-tray__section-action\"\n @click=\"request('clear')\"\n >\n Clear\n </button>\n </div>\n\n <div\n v-for=\"{ job, view } in section.rows\"\n :key=\"job.job_id\"\n class=\"mint-jobs-tray__row\"\n :class=\"{ 'mint-jobs-tray__row--awaiting-input': view.status === 'awaiting_input' }\"\n :data-status=\"job.status\"\n >\n <!-- data-status is the real job status; the row view only changes how it looks. -->\n <component\n :is=\"STATUS_ICONS[view.status]\"\n :size=\"15\"\n :class=\"['mint-jobs-tray__status', `mint-jobs-tray__status--${view.status.replace('_', '-')}`]\"\n role=\"img\"\n :aria-label=\"jobStatusLabel(view.status)\"\n />\n <button type=\"button\" class=\"mint-jobs-tray__row-title\" @click=\"emit('select', job)\">\n <slot name=\"job-title\" :job=\"job\">{{ job.name }}</slot>\n </button>\n <span class=\"mint-jobs-tray__tools\">\n <span class=\"mint-jobs-tray__value\">{{ jobValue(job, view.percent) }}</span>\n <slot name=\"job-actions\" :job=\"job\" />\n <button\n v-if=\"isActiveJobStatus(job.status) && job.can_cancel && tray.canCancel.value\"\n type=\"button\"\n class=\"mint-jobs-tray__icon-button mint-jobs-tray__icon-button--danger\"\n :aria-label=\"`Cancel ${job.name}`\"\n title=\"Cancel\"\n :disabled=\"tray.isPending(job)\"\n @click=\"request('cancel', job)\"\n >\n <Square :size=\"12\" aria-hidden=\"true\" />\n </button>\n <button\n v-if=\"job.can_delete && tray.canDelete.value\"\n type=\"button\"\n class=\"mint-jobs-tray__icon-button\"\n :aria-label=\"`Delete ${job.name}`\"\n title=\"Delete\"\n :disabled=\"tray.isPending(job)\"\n @click=\"request('delete', job)\"\n >\n <Trash2 :size=\"14\" aria-hidden=\"true\" />\n </button>\n </span>\n <div\n v-if=\"view.percent != null\"\n class=\"mint-jobs-tray__progress\"\n role=\"progressbar\"\n :aria-label=\"`${job.name} progress`\"\n aria-valuemin=\"0\"\n aria-valuemax=\"100\"\n :aria-valuenow=\"view.percent\"\n >\n <span :style=\"{ width: `${view.percent}%` }\" />\n </div>\n <span\n class=\"mint-jobs-tray__detail\"\n :class=\"{ 'mint-jobs-tray__detail--error': job.status === 'failed' }\"\n >\n <slot name=\"job-detail\" :job=\"job\">{{ view.message }}</slot>\n </span>\n </div>\n </template>\n </div>\n </section>\n </Transition>\n\n <ConfirmDialog\n v-if=\"confirmEnabled\"\n :open=\"confirmOpen\"\n tone=\"error\"\n :title=\"confirmText?.title\"\n :confirm-label=\"confirmText?.confirmLabel\"\n :cancel-label=\"confirmText?.cancelLabel\"\n @update:open=\"onConfirmOpen\"\n @confirm=\"confirmPending\"\n >\n <!-- The marker class lifts the dialog above the tray (jobs-status-tray.css). -->\n <p class=\"mint-confirm__message mint-jobs-tray__confirm\">{{ confirmText?.message }}</p>\n </ConfirmDialog>\n </div>\n </Teleport>\n</template>\n","import {\n getCurrentScope,\n onScopeDispose,\n readonly,\n ref,\n toValue,\n watch,\n type MaybeRefOrGetter,\n type Ref,\n} from 'vue'\n\n/**\n * One event of the platform's realtime stream (`GET /api/events`).\n *\n * Platform events carry no entity data: refetch the entity through REST.\n * `type` is `resync` (refetch everything you show), the audit action of a\n * committed write, such as `experiment.update` or `analysis.artifact_create`,\n * or the `\"<plugin>.<event>\"` name of a plugin event, which carries `payload`.\n * Only `usePresence` receives `presence.changed`.\n */\nexport interface RealtimeEvent {\n type: string\n id?: string\n /**\n * `experiment:{id}`, `project:{id}`, `experiments`, `user:{id}`, or a plugin's\n * `plugin:{name}` / `plugin:{name}:experiment:{id}`; absent on `resync`.\n */\n topic?: string\n /** A plugin event: the JSON payload the plugin published (at most 16 KiB). */\n payload?: unknown\n /** Changed fields of an update, when the write names them. */\n fields?: string[] | null\n actor_id?: string | null\n request_id?: string | null\n at?: string\n /** `presence.changed`: the topic's viewers (at most 20, `editing` first). */\n viewers?: { user_id: string, activity: string }[]\n /** `presence.changed`: the number of viewers, also those beyond `viewers`. */\n count?: number\n}\n\nexport type RealtimeHandler = (event: RealtimeEvent) => void\n\nexport interface UseRealtimeReturn {\n /** True while the shared stream is open. */\n connected: Readonly<Ref<boolean>>\n /** Unsubscribe; also runs when the calling component or effect scope is disposed. */\n stop: () => void\n}\n\nconst EVENTS_URL = '/api/events'\nconst RECONNECT_BASE_MS = 1_000\nconst RECONNECT_MAX_MS = 30_000\n/** Merges the subscriptions of components that mount together into one connection. */\nconst TOPIC_DEBOUNCE_MS = 50\nconst RESYNC: RealtimeEvent = { type: 'resync' }\n\ninterface Listener {\n topics: () => string[]\n handler: RealtimeHandler\n /** Receives `presence.changed`; a write listener would refetch on each viewer change. */\n presence: boolean\n}\n\nconst listeners = new Set<Listener>()\n/** The last `presence.changed` of each topic of the open stream; the server sends one per topic at open. */\nconst presence = new Map<string, RealtimeEvent>()\nconst connected = ref(false)\nlet source: EventSource | null = null\nlet sourceTopics = ''\nlet failures = 0\nlet syncTimer: ReturnType<typeof setTimeout> | null = null\nlet retryTimer: ReturnType<typeof setTimeout> | null = null\n\nfunction dispatch(event: RealtimeEvent): void {\n const isPresence = event.type === 'presence.changed'\n if (isPresence && event.topic) presence.set(event.topic, event)\n for (const listener of [...listeners]) {\n if (isPresence && !listener.presence) continue\n if (event.type === 'resync' || (event.topic && listener.topics().includes(event.topic))) {\n listener.handler(event)\n }\n }\n}\n\nfunction close(): void {\n source?.close()\n source = null\n sourceTopics = ''\n presence.clear()\n connected.value = false\n}\n\nfunction open(topics: string): void {\n const stream = new EventSource(`${EVENTS_URL}?topics=${encodeURIComponent(topics)}`)\n source = stream\n sourceTopics = topics\n stream.onopen = () => {\n connected.value = true\n // The server subscribes only now: a write between a caller's REST load (or\n // the close of the previous stream) and this point sent no event, so every caller refetches.\n dispatch(RESYNC)\n failures = 0\n }\n stream.onmessage = (message) => {\n dispatch(JSON.parse(message.data) as RealtimeEvent)\n }\n stream.onerror = () => {\n // EventSource retries a dropped connection itself but gives up after an\n // HTTP error, so one backoff path handles both.\n if (source !== stream) return\n close()\n // A topic change during the wait does not shorten it: the retry reads the topics when it runs.\n if (syncTimer !== null) clearTimeout(syncTimer)\n syncTimer = null\n retryTimer = setTimeout(() => {\n retryTimer = null\n sync()\n }, Math.min(RECONNECT_MAX_MS, RECONNECT_BASE_MS * 2 ** failures))\n failures += 1\n }\n}\n\nfunction sync(): void {\n syncTimer = null\n const topics = [...new Set([...listeners].flatMap(listener => listener.topics()))].sort().join(',')\n if (source && topics === sourceTopics) return\n close()\n if (topics) open(topics)\n}\n\nfunction schedule(): void {\n if (retryTimer !== null) return\n if (syncTimer !== null) clearTimeout(syncTimer)\n syncTimer = setTimeout(sync, TOPIC_DEBOUNCE_MS)\n}\n\n/**\n * Subscribe to topics of the platform's realtime stream.\n *\n * Every caller in a tab shares one `EventSource`, opened on the union of\n * their topics and reopened when that union changes. `handler` receives the\n * write events of the caller's own topics (not `presence.changed`, which goes\n * to `usePresence`) plus every `resync`: one comes from the\n * server when this tab fell behind, and one follows each open of the stream:\n * the first open, each reconnect (backoff from 1 s to 30 s) and each reopen for\n * a changed topic union. On `resync`, refetch. The union of all callers' topics\n * in a tab may hold at most 50 topics; the platform refuses a larger stream.\n *\n * The stream authenticates with the session cookie, so it works in the\n * platform and in plugin frontends served by it. It exists only when the\n * platform's `realtime` feature flag is on; check that flag first.\n *\n * A plugin topic reaches a caller whose role may use the plugin; an\n * experiment plugin topic also needs a caller who may view the experiment.\n *\n * @example\n * useRealtime(() => [`experiment:${id.value}`], () => refetch())\n * @example\n * useRealtime(['plugin:drp'], (event) => {\n * if (event.type === 'drp.run.progress') progress.value = event.payload as RunProgress\n * })\n */\nexport function useRealtime(\n topics: MaybeRefOrGetter<string[]>,\n handler: RealtimeHandler,\n): UseRealtimeReturn {\n return subscribeRealtime(topics, handler, false)\n}\n\n/** The last `presence.changed` of `topic` while the open stream views it (for `usePresence`). */\nexport function currentPresence(topic: string): RealtimeEvent | undefined {\n return presence.get(topic)\n}\n\n/** `useRealtime`, and with `withPresence` also the `presence.changed` events (for `usePresence`). */\nexport function subscribeRealtime(\n topics: MaybeRefOrGetter<string[]>,\n handler: RealtimeHandler,\n withPresence: boolean,\n): UseRealtimeReturn {\n const listener: Listener = { topics: () => toValue(topics), handler, presence: withPresence }\n listeners.add(listener)\n const stopWatch = watch(() => listener.topics().join(','), () => schedule())\n schedule()\n\n function stop(): void {\n stopWatch()\n if (listeners.delete(listener)) schedule()\n }\n\n if (getCurrentScope()) onScopeDispose(stop)\n return { connected: readonly(connected), stop }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA6CA,MAAM,QAAQ;EAMd,MAAM,OAAO;EAcb,MAAM,eAA6C;GACjD,SAAS;GACT,gBAAgB;GAChB,QAAQ;GACR,WAAW;GACX,QAAQ;GACR,WAAW;EACb;EAEA,MAAM,WAAW,IAAwB,IAAI;EAC7C,MAAM,iBAAiB,eAAe,MAAM,cAAc,MAAM;EAChE,MAAM,OAAO,MAAM;EACnB,MAAM,UAAU,GAAG,KAAK,QAAQ;EAChC,MAAM,QAAQ,SAAqB,KAAK,KAAI,SAAQ;GAAE;GAAK,MAAM,KAAK,QAAQ,GAAG;EAAE,EAAE;EAErF,MAAM,aAAa,eAAe;GAChC,MAAM,SAAS,KAAK,KAAK,WAAW,KAAK;GACzC,OAAO,CACL,GAAG,OAAO,QAAO,QAAO,IAAI,KAAK,WAAW,gBAAgB,GAC5D,GAAG,OAAO,QAAO,QAAO,IAAI,KAAK,WAAW,gBAAgB,CAC9D;EACF,CAAC;EACD,MAAM,WAAW,eAAe,CAC9B;GAAE,KAAK;GAAU,OAAO;GAAU,MAAM,WAAW;EAAM,GACzD;GAAE,KAAK;GAAY,OAAO;GAAY,MAAM,KAAK,KAAK,YAAY,KAAK;EAAE,CAC3E,C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,UAAU,WAAW,cAAc;CACvC,MAAM;CACN,IAAI,QAAQ,KAAK,MAAM;AACzB;AAEA,SAAS,WAAiB;CACxB,IAAI,eAAe,MAAM;CACzB,IAAI,cAAc,MAAM,aAAa,SAAS;CAC9C,YAAY,WAAW,MAAM,iBAAiB;AAChD;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,SAAgB,YACd,QACA,SACmB;CACnB,OAAO,kBAAkB,QAAQ,SAAS,KAAK;AACjD;;AAGA,SAAgB,gBAAgB,OAA0C;CACxE,OAAO,SAAS,IAAI,KAAK;AAC3B;;AAGA,SAAgB,kBACd,QACA,SACA,cACmB;CACnB,MAAM,WAAqB;EAAE,cAAc,QAAQ,MAAM;EAAG;EAAS,UAAU;CAAa;CAC5F,UAAU,IAAI,QAAQ;CACtB,MAAM,YAAY,YAAY,SAAS,OAAO,CAAC,CAAC,KAAK,GAAG,SAAS,SAAS,CAAC;CAC3E,SAAS;CAET,SAAS,OAAa;EACpB,UAAU;EACV,IAAI,UAAU,OAAO,QAAQ,GAAG,SAAS;CAC3C;CAEA,IAAI,gBAAgB,GAAG,eAAe,IAAI;CAC1C,OAAO;EAAE,WAAW,SAAS,SAAS;EAAG;CAAK;AAChD"}
@@ -0,0 +1,76 @@
1
+ import { r as readErrorMessage } from "./experiment-DyO54FQB.js";
2
+ import { ref } from "vue";
3
+ //#region src/composables/useRequest.ts
4
+ /** Loading, error and timestamp state for one request at a time; `run()` drives it. */
5
+ function useRequest(defaultErrorMessage = "Request failed.") {
6
+ const isLoading = ref(false);
7
+ const error = ref(null);
8
+ const lastLoadedAt = ref(null);
9
+ const lastSavedAt = ref(null);
10
+ const lastRunAt = ref(null);
11
+ function clearError() {
12
+ error.value = null;
13
+ }
14
+ function readErrorMessage$1(value, fallback = defaultErrorMessage) {
15
+ return readErrorMessage(value, fallback);
16
+ }
17
+ function setError(value, fallback) {
18
+ const message = readErrorMessage$1(value, fallback);
19
+ error.value = message;
20
+ return message;
21
+ }
22
+ let runToken = 0;
23
+ let activeController = null;
24
+ function cancel() {
25
+ runToken += 1;
26
+ activeController?.abort();
27
+ activeController = null;
28
+ isLoading.value = false;
29
+ }
30
+ async function run(operation, options = {}) {
31
+ if (options.abortPrevious !== false) activeController?.abort();
32
+ const token = runToken += 1;
33
+ const controller = new AbortController();
34
+ activeController = controller;
35
+ const callerSignal = options.signal;
36
+ if (callerSignal) {
37
+ if (callerSignal.aborted) controller.abort(callerSignal.reason);
38
+ else callerSignal.addEventListener("abort", () => controller.abort(callerSignal.reason), { once: true });
39
+ }
40
+ const isCurrent = () => token === runToken;
41
+ isLoading.value = true;
42
+ clearError();
43
+ try {
44
+ const response = await operation(controller.signal);
45
+ if (isCurrent() && options.kind) {
46
+ const settledAt = /* @__PURE__ */ new Date();
47
+ if (options.kind === "load") lastLoadedAt.value = settledAt;
48
+ else if (options.kind === "save") lastSavedAt.value = settledAt;
49
+ else lastRunAt.value = settledAt;
50
+ }
51
+ return response;
52
+ } catch (err) {
53
+ if (isCurrent()) setError(err, options.errorMessage);
54
+ throw err;
55
+ } finally {
56
+ if (isCurrent()) isLoading.value = false;
57
+ if (activeController === controller) activeController = null;
58
+ }
59
+ }
60
+ return {
61
+ isLoading,
62
+ error,
63
+ lastLoadedAt,
64
+ lastSavedAt,
65
+ lastRunAt,
66
+ clearError,
67
+ readErrorMessage: readErrorMessage$1,
68
+ setError,
69
+ run,
70
+ cancel
71
+ };
72
+ }
73
+ //#endregion
74
+ export { useRequest as t };
75
+
76
+ //# sourceMappingURL=useRequest-CXyPw3eh.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useRequest-CXyPw3eh.js","names":[],"sources":["../src/composables/useRequest.ts"],"sourcesContent":["import { ref, type Ref } from 'vue'\nimport { readErrorMessage as readSharedErrorMessage } from '../utils/errors'\n\nexport type RequestKind = 'load' | 'save' | 'run'\n\n/**\n * The unit of work `run()` drives.\n *\n * It receives an `AbortSignal` that fires when the run is superseded by a\n * newer `run()` or by `cancel()`. Zero-argument operations stay valid and\n * simply ignore it.\n */\nexport type RequestOperation<T> = (signal: AbortSignal) => Promise<T>\n\nexport interface RequestRunOptions {\n /** Which timestamp a successful run moves: `lastLoadedAt`, `lastSavedAt` or `lastRunAt`. */\n kind?: RequestKind\n errorMessage?: string\n /**\n * Abort the previously started run when this one starts. Default `true`;\n * pass `false` to let overlapping runs finish their own work (the stale\n * guard on shared state still applies either way).\n */\n abortPrevious?: boolean\n /** Caller-owned signal; aborting it aborts this run's signal too. */\n signal?: AbortSignal\n}\n\nexport interface UseRequestReturn {\n /** Whether a request is in progress. */\n isLoading: Ref<boolean>\n /** Message from the last failed request, or null. */\n error: Ref<string | null>\n /** Timestamp of the last successful load operation, or null. */\n lastLoadedAt: Ref<Date | null>\n /** Timestamp of the last successful save operation, or null. */\n lastSavedAt: Ref<Date | null>\n /** Timestamp of the last successful run operation, or null. */\n lastRunAt: Ref<Date | null>\n /** Clear the current error without changing loading or timestamps. */\n clearError: () => void\n /** Convert thrown values into a developer-facing error message. */\n readErrorMessage: (value: unknown, fallback?: string) => string\n /** Store and return a normalized error message. */\n setError: (value: unknown, fallback?: string) => string\n /**\n * Run a request with shared loading/error handling and optional sync marking.\n *\n * ## Stale-response semantics\n *\n * Every call takes a monotonically increasing token. Starting a run\n * supersedes any run started before it, and a superseded run writes **no**\n * shared state when it finally settles: it does not clear `isLoading`, does not\n * set `error`, and does not move `lastLoadedAt` / `lastSavedAt` / `lastRunAt`.\n * Only the newest run owns those.\n *\n * The caller's own promise is untouched by the guard — a superseded run still\n * resolves with its value or rejects with its own error, exactly as the\n * operation did. The guard never invents a rejection, so a caller awaiting\n * `run()` never sees a \"superseded\" error it did not cause.\n *\n * The operation additionally receives an `AbortSignal` that fires when its\n * run is superseded or `cancel()` is called, so an operation that forwards\n * the signal (`fetch(url, { signal })`) stops work instead of racing.\n */\n run: <T>(operation: RequestOperation<T>, options?: RequestRunOptions) => Promise<T>\n /**\n * Abort the in-flight run and drop `isLoading`. The aborted run's completion\n * is treated as stale and writes no state.\n */\n cancel: () => void\n}\n\n/** Loading, error and timestamp state for one request at a time; `run()` drives it. */\nexport function useRequest(\n defaultErrorMessage = 'Request failed.',\n): UseRequestReturn {\n const isLoading = ref(false)\n const error = ref<string | null>(null)\n const lastLoadedAt = ref<Date | null>(null)\n const lastSavedAt = ref<Date | null>(null)\n const lastRunAt = ref<Date | null>(null)\n\n function clearError(): void {\n error.value = null\n }\n\n function readErrorMessage(value: unknown, fallback = defaultErrorMessage): string {\n return readSharedErrorMessage(value, fallback)\n }\n\n function setError(value: unknown, fallback?: string): string {\n const message = readErrorMessage(value, fallback)\n error.value = message\n return message\n }\n\n // Monotonic token guarding every write to the shared loading/error/timestamp\n // state. Overlapping runs settle in any order, and a superseded one must not\n // clear a newer run's loading flag or overwrite its error.\n let runToken = 0\n let activeController: AbortController | null = null\n\n function cancel(): void {\n runToken += 1\n activeController?.abort()\n activeController = null\n isLoading.value = false\n }\n\n async function run<T>(\n operation: RequestOperation<T>,\n options: RequestRunOptions = {},\n ): Promise<T> {\n if (options.abortPrevious !== false) {\n activeController?.abort()\n }\n\n const token = (runToken += 1)\n const controller = new AbortController()\n activeController = controller\n\n const callerSignal = options.signal\n if (callerSignal) {\n if (callerSignal.aborted) controller.abort(callerSignal.reason)\n else callerSignal.addEventListener(\n 'abort',\n () => controller.abort(callerSignal.reason),\n { once: true },\n )\n }\n\n const isCurrent = (): boolean => token === runToken\n\n isLoading.value = true\n clearError()\n try {\n const response = await operation(controller.signal)\n if (isCurrent() && options.kind) {\n const settledAt = new Date()\n if (options.kind === 'load') lastLoadedAt.value = settledAt\n else if (options.kind === 'save') lastSavedAt.value = settledAt\n else lastRunAt.value = settledAt\n }\n return response\n } catch (err) {\n if (isCurrent()) {\n setError(err, options.errorMessage)\n }\n throw err\n } finally {\n if (isCurrent()) {\n isLoading.value = false\n }\n if (activeController === controller) {\n activeController = null\n }\n }\n }\n\n return {\n isLoading,\n error,\n lastLoadedAt,\n lastSavedAt,\n lastRunAt,\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;SACjD,UAAU,QAAQ;GACzB;GACA,OAAO;EACT,SAAS,KAAK;GACZ,IAAI,UAAU,GACZ,SAAS,KAAK,QAAQ,YAAY;GAEpC,MAAM;EACR,UAAU;GACR,IAAI,UAAU,GACZ,UAAU,QAAQ;GAEpB,IAAI,qBAAqB,YACvB,mBAAmB;EAEvB;CACF;CAEA,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA,kBAAA;EACA;EACA;EACA;CACF;AACF"}
@@ -0,0 +1,2 @@
1
+ /** Warn once per page load that a deprecated SDK option or slot is in use. */
2
+ export declare function warnDeprecatedOnce(key: string, message: string): void;
@@ -0,0 +1,4 @@
1
+ import { Component } from 'vue';
2
+ export declare function isLucideIconName(value?: string): value is string;
3
+ /** The Lucide component for `name`, or undefined when Lucide has no such icon. */
4
+ export declare function loadLucideIcon(name: string): Promise<Component | undefined>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@morscherlab/mint-sdk",
3
- "version": "1.5.0-beta.6",
3
+ "version": "1.5.0-beta.8",
4
4
  "description": "MINT Platform SDK — Vue 3 components, composables, and types for plugin development. MINT = Mass-spec Infrastructure for Next-generation Toolkits.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,8 +1,9 @@
1
1
  import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
2
2
  import { enableAutoUnmount, flushPromises, mount, type VueWrapper } from '@vue/test-utils'
3
- import { computed, ref } from 'vue'
3
+ import { computed, h, ref } from 'vue'
4
4
  import { createPinia } from 'pinia'
5
5
  import AppTopBar from '../../components/AppTopBar.vue'
6
+ import AppLayout from '../../components/AppLayout.vue'
6
7
  import ExperimentPopover from '../../components/ExperimentPopover.vue'
7
8
  import ExperimentSelectorModal from '../../components/ExperimentSelectorModal.vue'
8
9
  import { usePlatform } from '../../composables/usePlatform'
@@ -13,6 +14,7 @@ import ThemeToggle from '../../components/ThemeToggle.vue'
13
14
  import SettingsModal from '../../components/SettingsModal.vue'
14
15
  import type { TopBarSettingsConfig } from '../../types/components'
15
16
  import type { TopBarJob } from '../../types/jobs'
17
+ import { loadLucideIcon } from '../../utils/lucideIcon'
16
18
 
17
19
  // Mock the usePlatform composable
18
20
  vi.mock('../../composables/usePlatform', () => ({
@@ -95,14 +97,17 @@ describe('AppTopBar', () => {
95
97
  expect(wrapper.props()).not.toHaveProperty('pluginSwitcher')
96
98
  })
97
99
 
98
- it('should render without ThemeToggle by default', () => {
99
- const wrapper = createWrapper({ title: 'Test App' })
100
- expect(wrapper.findComponent(ThemeToggle).exists()).toBe(false)
101
- })
100
+ it('should end with the theme toggle, the settings button and the account slot by default', () => {
101
+ const wrapper = createWrapper(
102
+ { title: 'Test App', spec: { actions: [{ id: 'export', label: 'Export', onSelect: () => {} }] } },
103
+ { account: '<span class="account" />' },
104
+ )
102
105
 
103
- it('should render without settings button by default', () => {
104
- const wrapper = createWrapper({ title: 'Test App' })
105
- expect(wrapper.find('.mint-topbar__settings-btn').exists()).toBe(false)
106
+ const tail = wrapper.get('.mint-topbar__right > :last-child')
107
+ expect(tail.classes()).toContain('mint-topbar__tail')
108
+ const [theme, settings, account] = Array.from(tail.element.children)
109
+ expect([theme === wrapper.findComponent(ThemeToggle).element, settings.className, account.className])
110
+ .toEqual([true, 'mint-topbar__settings-btn', 'account'])
106
111
  })
107
112
 
108
113
  it('should render without SettingsModal by default', () => {
@@ -118,12 +123,15 @@ describe('AppTopBar', () => {
118
123
  })
119
124
 
120
125
  describe('spec.themeToggle', () => {
121
- it('should not render ThemeToggle when spec.themeToggle is false', () => {
126
+ it('should ignore a deprecated spec.themeToggle false and warn about it', () => {
127
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
122
128
  const wrapper = createWrapper({
123
129
  spec: { themeToggle: false },
124
130
  title: 'Test App',
125
131
  })
126
- expect(wrapper.findComponent(ThemeToggle).exists()).toBe(false)
132
+ expect(wrapper.findComponent(ThemeToggle).exists()).toBe(true)
133
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('spec.themeToggle is ignored'))
134
+ warn.mockRestore()
127
135
  })
128
136
 
129
137
  it('should render ThemeToggle when spec.themeToggle is true', () => {
@@ -155,12 +163,14 @@ describe('AppTopBar', () => {
155
163
  })
156
164
 
157
165
  describe('spec.settings', () => {
158
- it('should not render settings button when spec.settings is false', () => {
166
+ it('should open an appearance-only modal when spec.settings is false', async () => {
159
167
  const wrapper = createWrapper({
160
168
  spec: { settings: false },
161
169
  title: 'Test App',
162
170
  })
163
- expect(wrapper.find('.mint-topbar__settings-btn').exists()).toBe(false)
171
+
172
+ const settingsModal = await openSettingsModal(wrapper)
173
+ expect([settingsModal.props('tabs'), settingsModal.props('showAppearance')]).toEqual([[], true])
164
174
  })
165
175
 
166
176
  it('should render settings button when spec.settings is set', () => {
@@ -181,7 +191,8 @@ describe('AppTopBar', () => {
181
191
  canConfigure.value = false
182
192
  await wrapper.vm.$nextTick()
183
193
 
184
- expect(wrapper.find('.mint-topbar__settings-btn').exists()).toBe(false)
194
+ expect(wrapper.find('.mint-topbar__settings-btn').exists()).toBe(true)
195
+ expect((await openSettingsModal(wrapper)).props('tabs')).toEqual([])
185
196
  })
186
197
 
187
198
  it('should render SettingsModal after settings is opened', async () => {
@@ -782,8 +793,8 @@ describe('AppTopBar', () => {
782
793
  })
783
794
 
784
795
  expect(wrapper.find('.mint-topbar').exists()).toBe(true)
785
- expect(wrapper.findComponent(ThemeToggle).exists()).toBe(false)
786
- expect(wrapper.find('.mint-topbar__settings-btn').exists()).toBe(false)
796
+ expect(wrapper.findComponent(ThemeToggle).exists()).toBe(true)
797
+ expect(wrapper.find('.mint-topbar__settings-btn').exists()).toBe(true)
787
798
  // Standalone badge still shows by default in standalone mode
788
799
  expect(wrapper.find('.mint-topbar__standalone-badge').exists()).toBe(true)
789
800
  })
@@ -1483,16 +1494,17 @@ describe('AppTopBar', () => {
1483
1494
  })
1484
1495
 
1485
1496
  it('should update the toast offset when the top bar resizes', () => {
1486
- let onResize: (() => void) | undefined
1497
+ // Every observer of the bar hears the resize (toast offset and label fit).
1498
+ const callbacks: (() => void)[] = []
1487
1499
  vi.stubGlobal('ResizeObserver', class {
1488
- constructor(callback: () => void) { onResize = callback }
1500
+ constructor(callback: () => void) { callbacks.push(callback) }
1489
1501
  observe() {}
1490
1502
  unobserve() {}
1491
1503
  disconnect() {}
1492
1504
  })
1493
1505
  createWrapper({ title: 'Test App' })
1494
1506
  rects['Test App'] = { top: 16, bottom: 120 }
1495
- onResize?.()
1507
+ callbacks.forEach(callback => callback())
1496
1508
 
1497
1509
  expect(toastOffset()).toBe('calc(120px + 1rem)')
1498
1510
  })
@@ -1654,8 +1666,8 @@ describe('AppTopBar', () => {
1654
1666
  })
1655
1667
 
1656
1668
  it.each([
1657
- [null, undefined, null, undefined],
1658
- [null, 0, null, undefined],
1669
+ [null, undefined, null, 'Jobs'],
1670
+ [null, 0, null, 'Jobs'],
1659
1671
  [null, 2, '2', 'Jobs, 2 completed'],
1660
1672
  [running, 2, null, 'Extracting 40%'],
1661
1673
  ])('should show the completed count only on the idle button when the job is %o and jobsDone %s', async (job, jobsDone, count, name) => {
@@ -1688,4 +1700,74 @@ describe('AppTopBar', () => {
1688
1700
  expect(wrapper.emitted('job-click')).toEqual([[]])
1689
1701
  })
1690
1702
  })
1703
+
1704
+ describe('spec.actions', () => {
1705
+ it('should show two actions and fold the rest into the More menu', async () => {
1706
+ const onSelect = vi.fn()
1707
+ const wrapper = createWrapper({
1708
+ title: 'Test App',
1709
+ spec: {
1710
+ actions: [
1711
+ { id: 'status', label: 'Database status', icon: 'database', dot: 'success', onSelect: () => {} },
1712
+ { id: 'export', label: 'Export', onSelect: () => {} },
1713
+ { id: 'reindex', label: 'Reindex', onSelect },
1714
+ ],
1715
+ },
1716
+ })
1717
+
1718
+ const context = wrapper.get('.mint-topbar__context')
1719
+ expect([
1720
+ context.get('[data-action="status"]').attributes('aria-label'),
1721
+ context.find('[data-action="status"] .mint-topbar__icon-btn-dot--success').exists(),
1722
+ context.get('[data-action="export"]').text(),
1723
+ context.find('[data-action="reindex"]').exists(),
1724
+ ]).toEqual(['Database status', true, 'Export', false])
1725
+
1726
+ await context.get('.mint-action-menu button').trigger('click')
1727
+ await flushPromises()
1728
+ await wrapper.findComponent({ name: 'ActionMenu' }).vm.$emit('select', { id: 'reindex', label: 'Reindex' })
1729
+ expect(onSelect).toHaveBeenCalledOnce()
1730
+ })
1731
+ })
1732
+
1733
+ describe('narrow layout', () => {
1734
+ it.each([
1735
+ [{}, false],
1736
+ [{ pills: [{ id: 'a', label: 'A' }] }, true],
1737
+ [{ actions: [{ id: 'export', label: 'Export', onSelect: () => {} }] }, true],
1738
+ ])('should make the bar stackable with spec %o: %s', (spec, stackable) => {
1739
+ const wrapper = createWrapper({ title: 'Test App', spec: { ...spec, standaloneLabel: false } })
1740
+
1741
+ expect(wrapper.get('.mint-topbar__container').classes('mint-topbar__container--stackable')).toBe(stackable)
1742
+ })
1743
+
1744
+ it('should hold the drawer button of a responsive AppLayout with a sidebar', async () => {
1745
+ const wrapper = mount(AppLayout, {
1746
+ props: { responsiveSidebar: true },
1747
+ slots: {
1748
+ topbar: () => h(AppTopBar, { title: 'Test App' }),
1749
+ sidebar: () => h('aside', 'tools'),
1750
+ },
1751
+ global: { plugins: [createPinia()] },
1752
+ })
1753
+
1754
+ const toggle = wrapper.get('.mint-topbar__sidebar-toggle')
1755
+ await toggle.trigger('click')
1756
+
1757
+ expect([toggle.attributes('aria-expanded'), wrapper.classes('mint-layout--sidebar-open')]).toEqual(['true', true])
1758
+ })
1759
+
1760
+ it('should render a Lucide page icon by name', async () => {
1761
+ // Under vitest the icon index loads module by module (about 2 s), longer than waitFor's 1 s.
1762
+ await loadLucideIcon('activity')
1763
+ const wrapper = createWrapper({
1764
+ pageSelector: [
1765
+ { id: 'monitor', label: 'Monitor', icon: 'activity' },
1766
+ { id: 'planner', label: 'Planner' },
1767
+ ],
1768
+ currentPageSelectorId: 'monitor',
1769
+ })
1770
+ await vi.waitFor(() => expect(wrapper.find('.mint-page-selector__trigger svg.lucide-activity-icon, .mint-page-selector__trigger svg.lucide-activity').exists()).toBe(true))
1771
+ }, 30_000)
1772
+ })
1691
1773
  })