Line data Source code
1 : import type { TemplateInput } from '@comfyorg/api-client/templateSchema'
2 : import { promiseTimeout } from '@vueuse/core'
3 :
4 : import type {
5 : ComfyDesktop2Bridge,
6 : ComfyTemplateInputAsset
7 : } from '@comfyorg/comfyui-desktop-bridge-types'
8 :
9 : type BridgeProvider = () => ComfyDesktop2Bridge | undefined
10 :
11 : /**
12 : * The detail view waits on this lookup before it can open, so a host that
13 : * never answers would leave the user with no way to reach Open now. Every
14 : * other failure here already degrades to "no assets"; this makes silence do
15 : * the same.
16 : */
17 2355 : const LOOKUP_TIMEOUT_MS = 10_000
18 2355 : const NO_ASSETS: readonly ComfyTemplateInputAsset[] = []
19 :
20 0 : export async function resolveTemplateInputAssets(
21 : templateId: string,
22 : getBridge: BridgeProvider
23 : ): Promise<readonly ComfyTemplateInputAsset[]> {
24 0 : const bridge = getBridge()
25 0 : if (!bridge?.getTemplateInputAssets || bridge.isRemote?.()) return []
26 :
27 0 : try {
28 0 : return (
29 : (await Promise.race([
30 : bridge.getTemplateInputAssets(templateId),
31 : promiseTimeout(LOOKUP_TIMEOUT_MS).then(() => NO_ASSETS)
32 : ])) ?? NO_ASSETS
33 : )
34 : } catch {
35 0 : return []
36 : }
37 : }
38 :
39 3 : export function getPendingTemplateSampleInputs(
40 : inputs: readonly TemplateInput[],
41 : assets: readonly ComfyTemplateInputAsset[]
42 : ): TemplateInput[] {
43 3 : return inputs.filter(
44 : (input) =>
45 : !assets.some(
46 : (asset) =>
47 : asset.filename === input.file &&
48 : asset.mediaType === input.mediaType &&
49 : asset.availability === 'present'
50 : )
51 : )
52 : }
53 :
54 0 : export function startMissingTemplateInputDownloads(
55 : templateId: string,
56 : assets: readonly ComfyTemplateInputAsset[],
57 : {
58 : getBridge,
59 : reportError
60 : }: {
61 : getBridge: BridgeProvider
62 : reportError: (error: unknown) => void
63 : }
64 : ): void {
65 0 : const missingAssets = assets.filter(
66 : ({ availability }) => availability === 'missing'
67 : )
68 0 : if (!missingAssets.length) return
69 :
70 0 : const bridge = getBridge()
71 0 : const downloadInput = bridge?.downloadTemplateInputAsset
72 0 : if (!downloadInput || bridge.isRemote?.()) {
73 0 : reportError(new Error('Template input download bridge unavailable'))
74 0 : return
75 : }
76 :
77 0 : let firstError: unknown
78 0 : const attempts = missingAssets.map(async ({ assetId }) => {
79 0 : try {
80 0 : const result = await downloadInput(templateId, assetId)
81 0 : if (result.status === 'not-started' && !firstError) {
82 0 : firstError = new Error(
83 : `Template input download not started: ${result.reason}`
84 : )
85 : }
86 : } catch (error) {
87 0 : firstError ??= error
88 : }
89 : })
90 :
91 0 : void Promise.all(attempts).then(() => {
92 0 : if (firstError) reportError(firstError)
93 : })
94 : }
|