Line data Source code
1 : import { refDebounced } from '@vueuse/core'
2 : import { orderBy } from 'es-toolkit/array'
3 : import { computed, onUnmounted, ref, watch } from 'vue'
4 : import { useI18n } from 'vue-i18n'
5 :
6 : import { useQueueProgress } from '@/composables/queue/useQueueProgress'
7 : import { isCloud } from '@/platform/distribution/types'
8 : import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore'
9 : import { useExecutionStore } from '@/stores/executionStore'
10 : import { useJobPreviewStore } from '@/stores/jobPreviewStore'
11 : import { useJobModelDownloadStore } from '@/stores/jobModelDownloadStore'
12 : import type { JobModelDownload } from '@/stores/jobModelDownloadStore'
13 : import { useQueueStore } from '@/stores/queueStore'
14 : import type { TaskItemImpl } from '@/stores/queueStore'
15 : import type { JobState } from '@/types/queue'
16 : import {
17 : dateKey,
18 : formatClockTime,
19 : formatShortMonthDay,
20 : isToday,
21 : isYesterday
22 : } from '@/utils/dateTimeUtil'
23 : import { resolveNodeDisplayName } from '@/utils/nodeTitleUtil'
24 : import { buildJobDisplay } from '@/utils/queueDisplay'
25 : import { isActiveJobState, jobStateFromTask } from '@/utils/queueUtil'
26 :
27 : import type { JobTab } from '@/composables/queue/jobTabs'
28 :
29 : export type { JobTab } from '@/composables/queue/jobTabs'
30 :
31 2355 : export const jobSortModes = ['mostRecent', 'totalGenerationTime'] as const
32 : export type JobSortMode = (typeof jobSortModes)[number]
33 :
34 : /**
35 : * UI item in the job list. Mirrors data previously prepared inline.
36 : */
37 : export type JobListItem = {
38 : id: string
39 : title: string
40 : meta: string
41 : state: JobState
42 : iconName?: string
43 : iconImageUrl?: string
44 : showClear?: boolean
45 : taskRef?: TaskItemImpl
46 : progressTotalPercent?: number
47 : progressCurrentPercent?: number
48 : runningNodeName?: string
49 : executionTimeMs?: number
50 : computeHours?: number
51 : }
52 :
53 : export type JobGroup = {
54 : key: string
55 : label: string
56 : items: JobListItem[]
57 : }
58 :
59 2355 : const ADDED_HINT_DURATION_MS = 3000
60 2355 : const relativeTimeFormatterCache = new Map<string, Intl.RelativeTimeFormat>()
61 2355 : const optionalValue = <T>(value: T | null | undefined): T | undefined =>
62 : value ?? undefined
63 2355 : const taskIdToKey = (id: string | number | undefined) => {
64 97 : if (id === undefined) return null
65 97 : const key = String(id)
66 97 : return key.length ? key : null
67 : }
68 :
69 : /**
70 : * Returns localized Today/Yesterday (capitalized) or localized Mon DD.
71 : */
72 2355 : const dateLabelForTimestamp = (
73 : ts: number,
74 : locale: string,
75 : relativeFormatter: Intl.RelativeTimeFormat
76 : ) => {
77 24 : const formatRelativeDay = (value: number) => {
78 1 : const formatted = relativeFormatter.format(value, 'day')
79 1 : return formatted
80 : ? formatted[0].toLocaleUpperCase(locale) + formatted.slice(1)
81 : : formatted
82 : }
83 24 : if (isToday(ts)) {
84 1 : return formatRelativeDay(0)
85 : }
86 23 : if (isYesterday(ts)) {
87 0 : return formatRelativeDay(-1)
88 : }
89 23 : return formatShortMonthDay(ts, locale)
90 : }
91 :
92 : type TaskWithState = {
93 : task: TaskItemImpl
94 : state: JobState
95 : }
96 :
97 0 : function downloadPercent({ progress }: JobModelDownload) {
98 0 : return progress === null ? undefined : progress * 100
99 : }
100 :
101 : /**
102 : * Builds the reactive job list, filters, and grouped view for the queue overlay.
103 : */
104 2008 : export function useJobList() {
105 2008 : const { t, locale } = useI18n()
106 2008 : const queueStore = useQueueStore()
107 2008 : const executionStore = useExecutionStore()
108 2008 : const modelDownloadStore = useJobModelDownloadStore()
109 2008 : const jobPreviewStore = useJobPreviewStore()
110 2008 : const workflowStore = useWorkflowStore()
111 :
112 2008 : const seenPendingIds = ref<Set<string>>(new Set())
113 2008 : const recentlyAddedPendingIds = ref<Set<string>>(new Set())
114 2008 : const addedHintTimeouts = new Map<string, ReturnType<typeof setTimeout>>()
115 :
116 2008 : const clearAddedHintTimeout = (id: string) => {
117 8 : const timeoutId = addedHintTimeouts.get(id)
118 8 : if (timeoutId !== undefined) {
119 1 : clearTimeout(timeoutId)
120 1 : addedHintTimeouts.delete(id)
121 : }
122 : }
123 :
124 2008 : const scheduleAddedHintExpiry = (id: string) => {
125 7 : clearAddedHintTimeout(id)
126 7 : const timeoutId = setTimeout(() => {
127 0 : addedHintTimeouts.delete(id)
128 0 : const updated = new Set(recentlyAddedPendingIds.value)
129 0 : if (updated.delete(id)) {
130 0 : recentlyAddedPendingIds.value = updated
131 : }
132 : }, ADDED_HINT_DURATION_MS)
133 7 : addedHintTimeouts.set(id, timeoutId)
134 : }
135 :
136 2008 : watch(
137 : () =>
138 : queueStore.pendingTasks
139 : .map((task) => taskIdToKey(task.jobId))
140 : .filter((id): id is string => !!id),
141 : (pendingIds) => {
142 4196 : const pendingSet = new Set(pendingIds)
143 4196 : const nextAdded = new Set(recentlyAddedPendingIds.value)
144 4196 : const nextSeen = new Set(seenPendingIds.value)
145 :
146 4196 : pendingIds.forEach((id) => {
147 8 : if (!nextSeen.has(id)) {
148 7 : nextSeen.add(id)
149 7 : nextAdded.add(id)
150 7 : scheduleAddedHintExpiry(id)
151 : }
152 : })
153 :
154 4196 : for (const id of Array.from(nextSeen)) {
155 9 : if (!pendingSet.has(id)) {
156 1 : nextSeen.delete(id)
157 1 : nextAdded.delete(id)
158 1 : clearAddedHintTimeout(id)
159 : }
160 : }
161 :
162 4196 : recentlyAddedPendingIds.value = nextAdded
163 4196 : seenPendingIds.value = nextSeen
164 : },
165 : { immediate: true }
166 : )
167 :
168 2008 : const shouldShowAddedHint = (task: TaskItemImpl, state: JobState) => {
169 81 : if (state !== 'pending') return false
170 8 : const id = taskIdToKey(task.jobId)
171 44 : if (!id) return false
172 8 : return recentlyAddedPendingIds.value.has(id)
173 : }
174 :
175 2008 : onUnmounted(() => {
176 74 : addedHintTimeouts.forEach((timeoutId) => clearTimeout(timeoutId))
177 74 : addedHintTimeouts.clear()
178 74 : seenPendingIds.value = new Set<string>()
179 74 : recentlyAddedPendingIds.value = new Set<string>()
180 : })
181 :
182 2008 : const { totalPercent, currentNodePercent } = useQueueProgress()
183 :
184 2008 : const relativeTimeFormatter = computed(() => {
185 16 : const localeValue = locale.value
186 16 : let formatter = relativeTimeFormatterCache.get(localeValue)
187 16 : if (!formatter) {
188 15 : formatter = new Intl.RelativeTimeFormat(localeValue, { numeric: 'auto' })
189 15 : relativeTimeFormatterCache.set(localeValue, formatter)
190 : }
191 16 : return formatter
192 : })
193 2008 : const undatedLabel = computed(() => t('queue.jobList.undated') || 'Undated')
194 :
195 2008 : const isJobInitializing = (jobId: string | number | undefined) =>
196 : executionStore.isJobInitializing(jobId)
197 :
198 2008 : const currentNodeName = computed(() => {
199 183 : return resolveNodeDisplayName(executionStore.executingNode, {
200 : emptyLabel: t('g.emDash'),
201 : untitledLabel: t('g.untitled')
202 : })
203 : })
204 :
205 2008 : const selectedJobTab = ref<JobTab>('All')
206 2008 : const selectedWorkflowFilter = ref<'all' | 'current'>('all')
207 2008 : const selectedSortMode = ref<JobSortMode>('mostRecent')
208 2008 : const searchQuery = ref('')
209 2008 : const debouncedSearchQuery = refDebounced(searchQuery, 150)
210 :
211 2008 : const mostRecentTimestamp = (task: TaskItemImpl) =>
212 : optionalValue(task.createTime) ?? 0
213 :
214 2008 : const allTasksSorted = computed<TaskItemImpl[]>(() => {
215 4196 : const all = [
216 : ...queueStore.pendingTasks,
217 : ...queueStore.runningTasks,
218 : ...queueStore.historyTasks
219 : ]
220 4196 : return orderBy(all, [mostRecentTimestamp], ['desc'])
221 : })
222 :
223 2008 : const tasksWithJobState = computed<TaskWithState[]>(() =>
224 : allTasksSorted.value.map((task) => ({
225 : task,
226 : state: jobStateFromTask(task, isJobInitializing(task.jobId))
227 : }))
228 : )
229 :
230 2008 : const hasFailedJobs = computed(() =>
231 : tasksWithJobState.value.some(({ state }) => state === 'failed')
232 : )
233 :
234 2008 : watch(
235 : () => hasFailedJobs.value,
236 : (hasFailed) => {
237 336 : if (!hasFailed && selectedJobTab.value === 'Failed') {
238 0 : selectedJobTab.value = 'All'
239 : }
240 : }
241 : )
242 :
243 2008 : const filteredTaskEntries = computed<TaskWithState[]>(() => {
244 37 : let entries = tasksWithJobState.value
245 37 : if (selectedJobTab.value === 'Completed') {
246 2 : entries = entries.filter(({ state }) => state === 'completed')
247 35 : } else if (selectedJobTab.value === 'Failed') {
248 1 : entries = entries.filter(({ state }) => state === 'failed')
249 : }
250 :
251 37 : if (selectedWorkflowFilter.value === 'current') {
252 1 : const activeWorkflow = optionalValue<
253 : typeof workflowStore.activeWorkflow | null
254 : >(workflowStore.activeWorkflow)
255 1 : if (!activeWorkflow) return []
256 1 : const activeId = optionalValue<typeof activeWorkflow.activeState | null>(
257 : activeWorkflow.activeState
258 : )?.id
259 1 : if (!activeId) return []
260 1 : entries = entries.filter(({ task }) => {
261 0 : const wid = task.workflowId
262 0 : return !!wid && wid === activeId
263 : })
264 : }
265 37 : return entries
266 : })
267 :
268 2008 : const normalizedSearchQuery = computed(() =>
269 : debouncedSearchQuery.value.trim().toLocaleLowerCase()
270 : )
271 :
272 2008 : const filteredTasks = computed<TaskItemImpl[]>(() =>
273 : searchableTaskEntries.value.map(({ task }) => task)
274 : )
275 :
276 81 : function activeDownload(jobId: string, state: JobState) {
277 81 : return isActiveJobState(state)
278 : ? modelDownloadStore.downloadFor(jobId)
279 : : undefined
280 : }
281 :
282 81 : function progressFills(
283 : state: JobState,
284 : isActive: boolean,
285 : modelDownload: JobModelDownload | undefined
286 : ) {
287 81 : if (modelDownload) {
288 0 : return {
289 : progressTotalPercent: undefined,
290 : progressCurrentPercent: downloadPercent(modelDownload)
291 : }
292 : }
293 81 : const running = state === 'running' && isActive
294 81 : return {
295 : progressTotalPercent: running ? totalPercent.value : undefined,
296 : progressCurrentPercent: running ? currentNodePercent.value : undefined
297 : }
298 : }
299 :
300 2008 : const jobItems = computed<JobListItem[]>(() => {
301 21 : return filteredTaskEntries.value.map(({ task, state }) => {
302 81 : const isActive = task.jobId === (executionStore.activeJobId ?? '')
303 81 : const modelDownload = activeDownload(task.jobId, state)
304 81 : const showAddedHint = shouldShowAddedHint(task, state)
305 81 : const promptKey = taskIdToKey(task.jobId)
306 81 : const promptPreviewUrl =
307 : state === 'running' && jobPreviewStore.isPreviewEnabled && promptKey
308 : ? jobPreviewStore.previewsByPromptId[promptKey]
309 : : undefined
310 :
311 81 : const display = buildJobDisplay(task, state, {
312 : t,
313 : locale: locale.value,
314 : formatClockTimeFn: formatClockTime,
315 : isActive,
316 : totalPercent: isActive ? totalPercent.value : undefined,
317 : currentNodePercent: isActive ? currentNodePercent.value : undefined,
318 : currentNodeName: isActive ? currentNodeName.value : undefined,
319 : showAddedHint,
320 : isCloud,
321 : modelDownload
322 : })
323 :
324 81 : return {
325 : id: task.jobId,
326 : title: display.primary,
327 : meta: display.secondary,
328 : state,
329 : iconName: display.iconName,
330 : iconImageUrl: promptPreviewUrl ?? display.iconImageUrl,
331 : showClear: display.showClear,
332 : taskRef: task,
333 : ...progressFills(state, isActive, modelDownload),
334 : runningNodeName:
335 : state === 'running' && isActive ? currentNodeName.value : undefined,
336 : executionTimeMs: task.executionTime,
337 : computeHours:
338 : task.executionTime !== undefined
339 : ? task.executionTime / 3_600_000
340 : : undefined
341 : }
342 : })
343 : })
344 :
345 2008 : const jobItemById = computed(() => {
346 21 : const m = new Map<string, JobListItem>()
347 21 : jobItems.value.forEach((ji) => m.set(ji.id, ji))
348 21 : return m
349 : })
350 :
351 2008 : const searchableTaskEntries = computed<TaskWithState[]>(() => {
352 40 : if (!normalizedSearchQuery.value) return filteredTaskEntries.value
353 :
354 2 : return filteredTaskEntries.value.filter(({ task }) => {
355 10 : const taskId = task.jobId.toLocaleLowerCase()
356 10 : const item = jobItemById.value.get(task.jobId)
357 10 : if (!item) {
358 0 : return taskId.includes(normalizedSearchQuery.value)
359 : }
360 :
361 10 : const title = item.title.toLocaleLowerCase()
362 10 : const meta = item.meta.toLocaleLowerCase()
363 10 : return (
364 : title.includes(normalizedSearchQuery.value) ||
365 : meta.includes(normalizedSearchQuery.value) ||
366 : taskId.includes(normalizedSearchQuery.value)
367 : )
368 : })
369 : })
370 :
371 : const groupedJobItems = computed<JobGroup[]>(() => {
372 41 : const groups: JobGroup[] = []
373 41 : const index = new Map<string, number>()
374 41 : const localeValue = locale.value
375 41 : for (const { task, state } of searchableTaskEntries.value) {
376 88 : let ts: number | undefined
377 88 : if (state === 'completed' || state === 'failed') {
378 68 : ts = optionalValue(task.executionEndTimestamp ?? task.createTime)
379 : } else {
380 20 : ts = optionalValue(task.createTime)
381 : }
382 88 : const key = ts === undefined ? 'undated' : dateKey(ts)
383 88 : let groupIdx = index.get(key)
384 88 : if (groupIdx === undefined) {
385 24 : const label =
386 : ts === undefined
387 : ? undatedLabel.value
388 : : dateLabelForTimestamp(
389 : ts,
390 : localeValue,
391 : relativeTimeFormatter.value
392 : )
393 24 : groups.push({ key, label, items: [] })
394 24 : groupIdx = groups.length - 1
395 24 : index.set(key, groupIdx)
396 : }
397 88 : const ji = jobItemById.value.get(task.jobId)
398 88 : if (ji) groups[groupIdx].items.push(ji)
399 : }
400 :
401 41 : if (selectedSortMode.value === 'totalGenerationTime') {
402 1 : const valueOrDefault = (value: JobListItem['executionTimeMs']) =>
403 : typeof value === 'number' && !Number.isNaN(value) ? value : -1
404 1 : const sortByExecutionTimeDesc = (a: JobListItem, b: JobListItem) =>
405 : valueOrDefault(b.executionTimeMs) - valueOrDefault(a.executionTimeMs)
406 :
407 1 : groups.forEach((group) => {
408 0 : group.items.sort(sortByExecutionTimeDesc)
409 : })
410 : }
411 :
412 41 : return groups
413 : })
414 :
415 2008 : return {
416 : // filters/state
417 : selectedJobTab,
418 : selectedWorkflowFilter,
419 : selectedSortMode,
420 : searchQuery,
421 : hasFailedJobs,
422 : // data sources
423 : allTasksSorted,
424 : filteredTasks,
425 : jobItems,
426 : groupedJobItems,
427 : currentNodeName
428 : }
429 : }
|