Line data Source code
1 : import { computed } from 'vue'
2 :
3 : import { downloadFile } from '@/base/common/downloadUtil'
4 : import type { MenuItem } from '@comfyorg/design-system/lib/menu/types'
5 : import type { JobListItem } from '@/composables/queue/useJobList'
6 : import { useCopyToClipboard } from '@/composables/useCopyToClipboard'
7 : import { useErrorHandling } from '@/composables/useErrorHandling'
8 : import { st, t } from '@/i18n'
9 : import { useSettingStore } from '@/platform/settings/settingStore'
10 : import { withNodeAddSource } from '@/platform/telemetry/nodeAdded/nodeAddSource'
11 : import { useWorkflowService } from '@/platform/workflow/core/services/workflowService'
12 : import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore'
13 : import type { ResultItem } from '@comfyorg/api-client/executionTypes'
14 : import { api } from '@/scripts/api'
15 : import { downloadBlob } from '@/scripts/utils'
16 : import { useDialogService } from '@/services/dialogService'
17 : import { getJobWorkflow } from '@/services/jobOutputCache'
18 : import { useLitegraphService } from '@/services/litegraphService'
19 : import { useExecutionStore } from '@/stores/executionStore'
20 : import { useNodeDefStore } from '@/stores/nodeDefStore'
21 : import { useQueueStore } from '@/stores/queueStore'
22 : import type { TaskItemImpl } from '@/stores/queueStore'
23 : import type { AugmentedResultItem } from '@/utils/resultItem'
24 : import { resultItemUrl } from '@/utils/resultItemUrl'
25 : import { isAudioResult, isImageResult, isVideoResult } from '@/utils/resultItem'
26 : import { createAnnotatedPath } from '@/utils/createAnnotatedPath'
27 : import { appendJsonExt } from '@/utils/formatUtil'
28 : import { isResultItemType } from '@/utils/typeGuardUtil'
29 :
30 : /**
31 : * Provides job context menu entries and actions.
32 : *
33 : * @param currentMenuItem Getter for the currently targeted job list item
34 : * @param onInspectAsset Callback to trigger when inspecting a completed job's asset
35 : */
36 30 : export function useJobMenu(
37 : currentMenuItem: () => JobListItem | null = () => null,
38 : onInspectAsset?: (item: JobListItem) => void
39 : ) {
40 30 : const workflowStore = useWorkflowStore()
41 30 : const workflowService = useWorkflowService()
42 30 : const queueStore = useQueueStore()
43 30 : const executionStore = useExecutionStore()
44 30 : const { copyToClipboard } = useCopyToClipboard()
45 30 : const { wrapWithErrorHandlingAsync } = useErrorHandling()
46 30 : const litegraphService = useLitegraphService()
47 30 : const nodeDefStore = useNodeDefStore()
48 :
49 30 : const resolveItem = (item?: JobListItem | null): JobListItem | null =>
50 : item ?? currentMenuItem()
51 :
52 30 : const openJobWorkflow = async (item?: JobListItem | null) => {
53 0 : const target = resolveItem(item)
54 0 : if (!target) return
55 0 : const data = await getJobWorkflow(target.id)
56 0 : if (!data) return
57 0 : const filename = `Job ${target.id}.json`
58 0 : const temp = workflowStore.createTemporary(filename, data)
59 0 : try {
60 0 : await workflowService.openWorkflow(temp)
61 : } catch (error) {
62 0 : useDialogService().showErrorDialog(error, {
63 : title: t('errorDialog.queueOpenWorkflowFailedTitle'),
64 : reportType: 'queueOpenWorkflowError'
65 : })
66 : }
67 : }
68 :
69 30 : const copyJobId = async (item?: JobListItem | null) => {
70 0 : const target = resolveItem(item)
71 0 : if (!target) return
72 0 : await copyToClipboard(target.id)
73 : }
74 :
75 30 : const cancelJob = async (item?: JobListItem | null) => {
76 0 : const target = resolveItem(item)
77 0 : if (!target) return
78 0 : if (
79 : target.state === 'running' ||
80 : target.state === 'initialization' ||
81 : target.state === 'pending'
82 : ) {
83 : // State-agnostic cancel (see api.ts cancelJob for the runtime-parity caveat).
84 0 : await api.cancelJob(target.id)
85 : }
86 0 : executionStore.clearInitializationByJobId(target.id)
87 0 : await queueStore.update()
88 : }
89 :
90 30 : const copyErrorMessage = async (item?: JobListItem | null) => {
91 : const target = resolveItem(item)
92 0 : const message = target?.taskRef?.errorMessage
93 0 : if (message) await copyToClipboard(message)
94 : }
95 :
96 30 : const reportError = (item?: JobListItem | null) => {
97 0 : const target = resolveItem(item)
98 0 : if (!target) return
99 :
100 : // Use execution_error from list response if available
101 0 : const executionError = target.taskRef?.executionError
102 :
103 0 : if (executionError) {
104 0 : useDialogService().showExecutionErrorDialog(executionError)
105 0 : return
106 : }
107 :
108 : // Fall back to simple error dialog
109 0 : const message = target.taskRef?.errorMessage
110 0 : if (message) {
111 0 : useDialogService().showErrorDialog(new Error(message), {
112 : reportType: 'queueJobError'
113 : })
114 : }
115 : }
116 :
117 : // This is very magical only because it matches the respective backend implementation
118 : // There is or will be a better way to do this
119 30 : const addOutputLoaderNode = async () => {
120 0 : const item = currentMenuItem()
121 0 : if (!item) return
122 0 : const result: AugmentedResultItem | undefined = item.taskRef?.previewOutput
123 0 : if (!result) return
124 :
125 0 : let nodeType: 'LoadImage' | 'LoadVideo' | 'LoadAudio' | null = null
126 0 : let widgetName: 'image' | 'file' | 'audio' | null = null
127 0 : if (isImageResult(result)) {
128 0 : nodeType = 'LoadImage'
129 0 : widgetName = 'image'
130 0 : } else if (isVideoResult(result)) {
131 0 : nodeType = 'LoadVideo'
132 0 : widgetName = 'file'
133 0 : } else if (isAudioResult(result)) {
134 0 : nodeType = 'LoadAudio'
135 0 : widgetName = 'audio'
136 : }
137 0 : if (!nodeType || !widgetName) return
138 :
139 0 : const nodeDef = Object.hasOwn(nodeDefStore.nodeDefsByName, nodeType)
140 : ? nodeDefStore.nodeDefsByName[nodeType]
141 : : undefined
142 0 : if (!nodeDef) return
143 0 : const node = withNodeAddSource('programmatic', () =>
144 : litegraphService.addNodeOnGraph(nodeDef, {
145 : pos: litegraphService.getCanvasCenter()
146 : })
147 : )
148 :
149 0 : if (!node) return
150 :
151 0 : const apiItem: ResultItem = {
152 : filename: result.filename,
153 : subfolder: result.subfolder,
154 : type: isResultItemType(result.type) ? result.type : 'output'
155 : }
156 :
157 0 : const annotated = createAnnotatedPath(apiItem)
158 0 : const widget = node.widgets?.find((w) => w.name === widgetName)
159 0 : if (widget) {
160 0 : widget.value = annotated
161 0 : widget.callback?.(annotated)
162 : }
163 0 : node.graph?.setDirtyCanvas(true, true)
164 : }
165 :
166 : /**
167 : * Trigger a download of the job's previewable output asset.
168 : */
169 30 : const downloadPreviewAsset = () => {
170 0 : const item = currentMenuItem()
171 0 : if (!item) return
172 0 : const result: AugmentedResultItem | undefined = item.taskRef?.previewOutput
173 0 : if (!result) return
174 0 : downloadFile(resultItemUrl(result))
175 : }
176 :
177 : /**
178 : * Export the workflow JSON attached to the job.
179 : */
180 30 : const exportJobWorkflow = async () => {
181 0 : const item = currentMenuItem()
182 0 : if (!item) return
183 0 : const data = await getJobWorkflow(item.id)
184 0 : if (!data) return
185 :
186 0 : const settingStore = useSettingStore()
187 0 : let filename = `Job ${item.id}.json`
188 :
189 0 : if (settingStore.get('Comfy.PromptFilename')) {
190 0 : const input = await useDialogService().prompt({
191 : title: t('workflowService.exportWorkflow'),
192 : message: t('workflowService.enterFilenamePrompt'),
193 : defaultValue: filename
194 : })
195 0 : if (!input) return
196 0 : filename = appendJsonExt(input)
197 : }
198 :
199 0 : const json = JSON.stringify(data, null, 2)
200 0 : const blob = new Blob([json], { type: 'application/json' })
201 0 : downloadBlob(filename, blob)
202 : }
203 :
204 30 : const removeFailedJob = async (task?: TaskItemImpl | null) => {
205 0 : const target = task ?? currentMenuItem()?.taskRef
206 0 : if (!target) return
207 0 : await queueStore.delete(target)
208 : }
209 :
210 30 : const jobMenuOpenWorkflowLabel = computed(() =>
211 : st('queue.jobMenu.openAsWorkflowNewTab', 'Open as workflow in new tab')
212 : )
213 30 : const jobMenuOpenWorkflowFailedLabel = computed(() =>
214 : st('queue.jobMenu.openWorkflowNewTab', 'Open workflow in new tab')
215 : )
216 30 : const jobMenuCopyJobIdLabel = computed(() =>
217 : st('queue.jobMenu.copyJobId', 'Copy job ID')
218 : )
219 30 : const jobMenuCancelLabel = computed(() =>
220 : st('queue.jobMenu.cancelJob', 'Cancel job')
221 : )
222 :
223 30 : const jobMenuEntries = computed<MenuItem[]>(() => {
224 30 : const item = currentMenuItem()
225 30 : const state = item?.state
226 30 : if (!state) return []
227 30 : const hasPreviewAsset = !!item.taskRef?.previewOutput
228 30 : if (state === 'completed') {
229 0 : return handleErrors([
230 : {
231 : key: 'inspect-asset',
232 : label: st('queue.jobMenu.inspectAsset', 'Inspect asset'),
233 : icon: 'icon-[lucide--zoom-in]',
234 : disabled: !hasPreviewAsset || !onInspectAsset,
235 : command: onInspectAsset
236 : ? () => {
237 0 : const item = currentMenuItem()
238 0 : if (item) onInspectAsset(item)
239 : }
240 : : undefined
241 : },
242 : {
243 : key: 'add-to-current',
244 : label: st(
245 : 'queue.jobMenu.addToCurrentWorkflow',
246 : 'Add to current workflow'
247 : ),
248 : icon: 'icon-[comfy--node]',
249 : disabled: !hasPreviewAsset,
250 : command: () => addOutputLoaderNode()
251 : },
252 : {
253 : key: 'download',
254 : label: st('queue.jobMenu.download', 'Download'),
255 : icon: 'icon-[lucide--download]',
256 : disabled: !hasPreviewAsset,
257 : command: () => downloadPreviewAsset()
258 : },
259 : { separator: true, key: 'd1' },
260 : {
261 : key: 'open-workflow',
262 : label: jobMenuOpenWorkflowLabel.value,
263 : icon: 'icon-[comfy--workflow]',
264 : command: () => openJobWorkflow()
265 : },
266 : {
267 : key: 'export-workflow',
268 : label: st('queue.jobMenu.exportWorkflow', 'Export workflow'),
269 : icon: 'icon-[comfy--file-output]',
270 : command: () => exportJobWorkflow()
271 : },
272 : { separator: true, key: 'd2' },
273 : {
274 : key: 'copy-id',
275 : label: jobMenuCopyJobIdLabel.value,
276 : icon: 'icon-[lucide--copy]',
277 : command: () => copyJobId()
278 : }
279 : ])
280 : }
281 0 : if (state === 'failed') {
282 0 : return handleErrors([
283 : {
284 : key: 'open-workflow',
285 : label: jobMenuOpenWorkflowFailedLabel.value,
286 : icon: 'icon-[comfy--workflow]',
287 : command: () => openJobWorkflow()
288 : },
289 : { separator: true, key: 'd1' },
290 : {
291 : key: 'copy-id',
292 : label: jobMenuCopyJobIdLabel.value,
293 : icon: 'icon-[lucide--copy]',
294 : command: () => copyJobId()
295 : },
296 : {
297 : key: 'copy-error',
298 : label: st('queue.jobMenu.copyErrorMessage', 'Copy error message'),
299 : icon: 'icon-[lucide--copy]',
300 : command: () => copyErrorMessage()
301 : },
302 : {
303 : key: 'report-error',
304 : label: st('queue.jobMenu.reportError', 'Report error'),
305 : icon: 'icon-[lucide--message-circle-warning]',
306 : command: () => reportError()
307 : },
308 : { separator: true, key: 'd2' },
309 : {
310 : key: 'delete',
311 : label: st('queue.jobMenu.removeJob', 'Remove job'),
312 : icon: 'icon-[lucide--circle-minus]',
313 : command: () => removeFailedJob()
314 : }
315 : ])
316 : }
317 0 : return handleErrors([
318 : {
319 : key: 'open-workflow',
320 : label: jobMenuOpenWorkflowLabel.value,
321 : icon: 'icon-[comfy--workflow]',
322 : command: () => openJobWorkflow()
323 : },
324 : { separator: true, key: 'd1' },
325 : {
326 : key: 'copy-id',
327 : label: jobMenuCopyJobIdLabel.value,
328 : icon: 'icon-[lucide--copy]',
329 : command: () => copyJobId()
330 : },
331 : { separator: true, key: 'd2' },
332 : {
333 : key: 'cancel-job',
334 : label: jobMenuCancelLabel.value,
335 : icon: 'icon-[lucide--x]',
336 : command: () => cancelJob()
337 : }
338 : ])
339 : })
340 :
341 30 : const handleErrors = (items: MenuItem[]): MenuItem[] =>
342 : items.map((item) =>
343 : item.command
344 : ? { ...item, command: wrapWithErrorHandlingAsync(item.command) }
345 : : item
346 : )
347 :
348 30 : return {
349 : jobMenuEntries,
350 : openJobWorkflow,
351 : copyJobId,
352 : cancelJob,
353 : removeFailedJob
354 : }
355 : }
|