comfy-ts 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +363 -0
- package/dist/cli.js +764 -0
- package/dist/cli.js.map +1 -0
- package/dist/index.cjs +4128 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +9862 -0
- package/dist/index.d.ts +9846 -58
- package/dist/index.js +4049 -2
- package/dist/index.js.map +1 -1
- package/dist/log-CdfgILde.js +10 -0
- package/dist/log-CdfgILde.js.map +1 -0
- package/dist/run-tui-Io8Xea0L.js +3340 -0
- package/dist/run-tui-Io8Xea0L.js.map +1 -0
- package/package.json +104 -75
- package/src/cli/comfy-ts-cli.ts +36 -0
- package/src/cli/gen.ts +47 -0
- package/src/cli/outline.ts +82 -0
- package/src/cli/tui/components/DraftsOverlay.tsx +44 -0
- package/src/cli/tui/components/EditField.tsx +27 -0
- package/src/cli/tui/components/Header.tsx +51 -0
- package/src/cli/tui/components/HostPanel.tsx +37 -0
- package/src/cli/tui/components/LorasOverlay.tsx +49 -0
- package/src/cli/tui/components/OverlayList.tsx +25 -0
- package/src/cli/tui/components/PickerOverlays.tsx +66 -0
- package/src/cli/tui/components/PreviewPanel.tsx +33 -0
- package/src/cli/tui/components/PromptOverlay.tsx +16 -0
- package/src/cli/tui/components/StatusBar.tsx +165 -0
- package/src/cli/tui/components/TextOverlay.tsx +72 -0
- package/src/cli/tui/components/TreePanel.tsx +51 -0
- package/src/cli/tui/components/TuiApp.tsx +223 -0
- package/src/cli/tui/components/VarsPanel.tsx +86 -0
- package/src/cli/tui/findDefinedWorkflow.ts +16 -0
- package/src/cli/tui/keys.ts +20 -0
- package/src/cli/tui/protocolImagePainter.ts +59 -0
- package/src/cli/tui/run-tui.tsx +73 -0
- package/src/cli/tui/state/DraftsSt.ts +273 -0
- package/src/cli/tui/state/EditorSt.ts +289 -0
- package/src/cli/tui/state/ExecSt.ts +170 -0
- package/src/cli/tui/state/HostSt.ts +107 -0
- package/src/cli/tui/state/LorasSt.ts +185 -0
- package/src/cli/tui/state/PickerSt.ts +112 -0
- package/src/cli/tui/state/PreviewSt.ts +138 -0
- package/src/cli/tui/state/QueueSt.ts +59 -0
- package/src/cli/tui/state/SettingsSt.ts +73 -0
- package/src/cli/tui/state/TreeSt.ts +122 -0
- package/src/cli/tui/state/TuiSt.ts +169 -0
- package/src/cli/tui/state/WorkflowsSt.ts +92 -0
- package/src/cli/tui-env.ts +8 -0
- package/src/errors/InvalidPromptError.ts +12 -0
- package/src/graph/ComfyNode.ts +403 -0
- package/src/graph/ComfyNodeID.ts +28 -0
- package/src/graph/ComfyNodeOutput.ts +16 -0
- package/src/graph/NodeSlotSize.ts +4 -0
- package/src/graph/autoValue.ts +17 -0
- package/src/host/ComfyHost.ts +646 -0
- package/src/host/ComfyInstallType.ts +15 -0
- package/src/host/ComfyManager.ts +232 -0
- package/src/host/ComfyUploader.ts +110 -0
- package/src/host/ComfyWorkflowBuilder.ts +60 -0
- package/src/host/Requirements.ts +55 -0
- package/src/host/ResilientWebsocket.ts +147 -0
- package/src/host/loraManagerApi.ts +98 -0
- package/src/image-utils/_getPngMetadata.ts +53 -0
- package/src/image-utils/_getWebpMetadata.ts +38 -0
- package/src/image-utils/_parseExifData.ts +53 -0
- package/src/index.ts +89 -0
- package/src/litegraph/LiteGraphGroup.ts +22 -0
- package/src/litegraph/LiteGraphJSON.ts +46 -0
- package/src/litegraph/LiteGraphLink.ts +23 -0
- package/src/litegraph/LiteGraphLinkID.ts +6 -0
- package/src/litegraph/LiteGraphNode.ts +69 -0
- package/src/litegraph/LiteGraphNodeInput.ts +27 -0
- package/src/litegraph/LiteGraphNodeOutput.ts +23 -0
- package/src/litegraph/LiteGraphSlotIndex.ts +6 -0
- package/src/litegraph/convertFlowToLiteGraphJSON.ts +114 -0
- package/src/manager/ComfyRegistry.ts +124 -0
- package/src/manager/generated/KnownComfyCustomNodeName.ts +19280 -0
- package/src/manager/generated/KnownComfyPluginTitle.ts +5130 -0
- package/src/manager/generated/KnownComfyPluginURL.ts +2589 -0
- package/src/manager/generated/KnownModel_Base.ts +126 -0
- package/src/manager/generated/KnownModel_FileName.ts +2287 -0
- package/src/manager/generated/KnownModel_Name.ts +2287 -0
- package/src/manager/generated/KnownModel_SavePath.ts +263 -0
- package/src/manager/generated/KnownModel_Type.ts +97 -0
- package/src/manager/json/alter-list.json +224 -0
- package/src/manager/json/custom-node-list.extra.ts +13 -0
- package/src/manager/json/custom-node-list.json +21948 -0
- package/src/manager/json/extension-node-map.json +31282 -0
- package/src/manager/json/github-stats.json +12602 -0
- package/src/manager/json/model-list.extra.ts +26 -0
- package/src/manager/json/model-list.json +5052 -0
- package/src/manager/loaders/step1_downloadComfyManagerJSONs.ts +56 -0
- package/src/manager/loaders/step2_custom-node-list-loader.ts +149 -0
- package/src/manager/loaders/step3_extension-node-map-loader.ts +189 -0
- package/src/manager/loaders/step4_model-list-loader.ts +159 -0
- package/src/manager/script-update-manager.bun.ts +18 -0
- package/src/manager/types/ComfyManagerAPIFetchPolicy.ts +9 -0
- package/src/manager/types/ComfyManagerAPIModelList.ts +10 -0
- package/src/manager/types/ComfyManagerAPIPluginList.ts +11 -0
- package/src/manager/types/ComfyManagerFileModelInfo.ts +5 -0
- package/src/manager/types/ComfyManagerFilePluginContent.ts +13 -0
- package/src/manager/types/ComfyManagerFilePluginList.ts +5 -0
- package/src/manager/types/ComfyManagerModelInfo.ts +18 -0
- package/src/manager/types/ComfyManagerPluginContentMetadata.ts +16 -0
- package/src/manager/types/ComfyManagerPluginEnums.ts +8 -0
- package/src/manager/types/ComfyManagerPluginInfo.ts +50 -0
- package/src/runner/ComfyExecution.ts +301 -0
- package/src/runner/ComfyExecutionStatus.ts +2 -0
- package/src/runner/ComfyWorkflow.ts +395 -0
- package/src/runner/ComfyWorkflowLayout.ts +96 -0
- package/src/runner/ComfyWsApi.ts +159 -0
- package/src/runner/MediaImage.ts +262 -0
- package/src/sdk-generator/ComfyNodeSchema.ts +79 -0
- package/src/sdk-generator/ComfySchema.ts +369 -0
- package/src/sdk-generator/ComfyUIObjectInfoTypes.ts +95 -0
- package/src/sdk-generator/Primitives.ts +76 -0
- package/src/sdk-generator/_getUnionNameBasedOnFirstFoundEnumName.ts +39 -0
- package/src/sdk-generator/_pythonModuleToNamespace.ts +27 -0
- package/src/sdk-generator/_toQualifiedNodeKey.ts +5 -0
- package/src/sdk-generator/comfy-api-json.ts +16 -0
- package/src/sdk-generator/comfyui-sdk-codegen.ts +287 -0
- package/src/sdk-generator/comfyui-types.ts +56 -0
- package/src/sdk-generator/litegraphToApiRequestPayload.ts +157 -0
- package/src/ssh-host-manager/ssh-config-manager.ts +89 -0
- package/src/ssh-host-manager/ssh-config.windows.md +32 -0
- package/src/ssh-host-manager/ssh-manager.ts +129 -0
- package/src/state.ts +136 -0
- package/src/types/comfy-sdk.ts +106 -0
- package/src/types/index.ts +55 -0
- package/src/utils/CodeBuffer.ts +61 -0
- package/src/utils/ComfyColors.ts +38 -0
- package/src/utils/ansi.ts +26 -0
- package/src/utils/ansiImage.ts +36 -0
- package/src/utils/bang.ts +39 -0
- package/src/utils/deepCopyNaive.ts +1 -0
- package/src/utils/downloadFile.ts +77 -0
- package/src/utils/escapeJSKey.ts +32 -0
- package/src/utils/exhaust.ts +4 -0
- package/src/utils/extractErrorMessage.ts +11 -0
- package/src/utils/fuzzyMatch.ts +8 -0
- package/src/utils/githubRegexes.ts +2 -0
- package/src/utils/hashArrayBuffer.ts +6 -0
- package/src/utils/log.ts +9 -0
- package/src/utils/loraTag.ts +10 -0
- package/src/utils/printArkResultInConsole.ts +16 -0
- package/src/utils/softValidate.ts +8 -0
- package/src/utils/stringifyReadable.ts +32 -0
- package/src/utils/toposort.ts +59 -0
- package/src/utils/tryExtracting.ts +41 -0
- package/src/utils/writeFile.ts +16 -0
- package/src/vars/ComfyVars.ts +531 -0
- package/src/vars/DefinedWorkflow.ts +112 -0
- package/src/vars/loraKeywords.ts +56 -0
- package/dist/index.d.mts +0 -74
- package/dist/index.mjs +0 -3
- package/dist/index.mjs.map +0 -1
- package/readme.md +0 -40
|
@@ -0,0 +1,531 @@
|
|
|
1
|
+
// Vars: the standard "tweak & re-run" contract. A workflow defined via
|
|
2
|
+
// host.defineWorkflow({ vars, build }) rebuilds its graph from current var
|
|
3
|
+
// values on every run — drivers (scripts, the TUI) edit vars between runs.
|
|
4
|
+
import { action, makeObservable, observable } from 'mobx'
|
|
5
|
+
import { getLoraKeyword } from 'src/vars/loraKeywords.ts'
|
|
6
|
+
|
|
7
|
+
export type VarKind = 'text' | 'int' | 'float' | 'seed' | 'toggle' | 'choice' | 'loras' | 'size'
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* full base: T is what's STORED/edited, Out what the GRAPH consumes at build
|
|
11
|
+
* time. They usually coincide — extend `ComfyVar<T>` for that. PromptVar is
|
|
12
|
+
* the one Out-specialized var (string in, PromptValue out); the split keeps
|
|
13
|
+
* outValue() cast-free.
|
|
14
|
+
*/
|
|
15
|
+
export abstract class ComfyVarBase<T, Out> {
|
|
16
|
+
abstract readonly kind: VarKind
|
|
17
|
+
value: T
|
|
18
|
+
constructor(
|
|
19
|
+
public readonly defaultValue: T,
|
|
20
|
+
public label?: string,
|
|
21
|
+
) {
|
|
22
|
+
this.value = defaultValue
|
|
23
|
+
// observable value: the TUI (mobx) re-renders when drivers mutate vars.
|
|
24
|
+
// explicit makeObservable (not makeAutoObservable): base-class + subclass
|
|
25
|
+
// combo. All mutators funnel through set()/reset()/parse() so they are
|
|
26
|
+
// actions — subclass helpers call this.set(...) rather than assigning.
|
|
27
|
+
makeObservable(this, { value: observable, set: action, reset: action, parse: action, loadJSON: action })
|
|
28
|
+
}
|
|
29
|
+
set(value: T): this {
|
|
30
|
+
this.value = value
|
|
31
|
+
return this
|
|
32
|
+
}
|
|
33
|
+
/** what drafts persist for this var (subclasses may add fields, e.g. seed mode) */
|
|
34
|
+
toJSON(): unknown {
|
|
35
|
+
return this.value
|
|
36
|
+
}
|
|
37
|
+
/** what the GRAPH consumes at build time (varValues maps these return types) */
|
|
38
|
+
abstract outValue(): Out
|
|
39
|
+
/**
|
|
40
|
+
* restore a value produced by toJSON() (drafts). The cast is sanctioned:
|
|
41
|
+
* drafts are our own round-trip, subclasses re-validate via set().
|
|
42
|
+
*/
|
|
43
|
+
loadJSON(value: unknown): this {
|
|
44
|
+
return this.set(value as T)
|
|
45
|
+
}
|
|
46
|
+
reset(): this {
|
|
47
|
+
this.value = this.defaultValue
|
|
48
|
+
return this
|
|
49
|
+
}
|
|
50
|
+
/** parse a raw string (TUI text input) into this var's value; returns false when invalid */
|
|
51
|
+
abstract parse(raw: string): boolean
|
|
52
|
+
/** how the value renders in a var list */
|
|
53
|
+
display(): string {
|
|
54
|
+
return String(this.value)
|
|
55
|
+
}
|
|
56
|
+
/** the string the inline editor starts from (round-trips through parse) */
|
|
57
|
+
toEditBuffer(): string {
|
|
58
|
+
return String(this.value)
|
|
59
|
+
}
|
|
60
|
+
/** hook run after every DefinedWorkflow.run() (default no-op; SeedVar advances) */
|
|
61
|
+
afterRun(): void {}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** the standard var: the graph consumes the stored value AS-IS (Out = T) */
|
|
65
|
+
export abstract class ComfyVar<T> extends ComfyVarBase<T, T> {
|
|
66
|
+
outValue(): T {
|
|
67
|
+
return this.value
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export class TextVar extends ComfyVar<string> {
|
|
72
|
+
readonly kind = 'text' as const
|
|
73
|
+
parse(raw: string): boolean {
|
|
74
|
+
this.set(raw)
|
|
75
|
+
return true
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const commentLineRe = /^\s*\/\//
|
|
80
|
+
const negativeLineRe = /^\s*- (.*)$/
|
|
81
|
+
|
|
82
|
+
/** what PromptVar needs from a loras var: covariant face, so LorasVar<'a'|'b'> fits */
|
|
83
|
+
export type ActiveLoraSource = { activeNames(): string[] }
|
|
84
|
+
|
|
85
|
+
/** what a prompt CONTRIBUTES to build: `vars.prompt.positive` / `.negative` */
|
|
86
|
+
export type PromptValue = { positive: string; negative: string }
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* prompt text with editor comforts, all resolved at BUILD time (the editor and
|
|
90
|
+
* drafts keep the raw text):
|
|
91
|
+
* - `//` lines are COMMENTS — stripped
|
|
92
|
+
* - `- ` lines are NEGATIVE prompt lines — removed from `.positive`,
|
|
93
|
+
* comma-joined into `.negative`
|
|
94
|
+
* - with `loraKeywordsFrom`, the ACTIVE loras' hand-assigned keywords
|
|
95
|
+
* (src/vars/loraKeywords.ts, ⌃K in the TUI) prefix `.positive` —
|
|
96
|
+
* `injectedKeywords()` is public so the TUI can PREVIEW the injection.
|
|
97
|
+
*/
|
|
98
|
+
export class PromptVar extends ComfyVarBase<string, PromptValue> {
|
|
99
|
+
readonly kind = 'text' as const
|
|
100
|
+
constructor(
|
|
101
|
+
defaultValue: string,
|
|
102
|
+
public promptOpts: { label?: string; loraKeywordsFrom?: ActiveLoraSource } = {},
|
|
103
|
+
) {
|
|
104
|
+
super(defaultValue, promptOpts.label)
|
|
105
|
+
}
|
|
106
|
+
parse(raw: string): boolean {
|
|
107
|
+
this.set(raw)
|
|
108
|
+
return true
|
|
109
|
+
}
|
|
110
|
+
static isCommentLine(line: string): boolean {
|
|
111
|
+
return commentLineRe.test(line)
|
|
112
|
+
}
|
|
113
|
+
static isNegativeLine(line: string): boolean {
|
|
114
|
+
return negativeLineRe.test(line)
|
|
115
|
+
}
|
|
116
|
+
/** the keyword prefix the flag will inject (deduped, lora-list order) — the TUI previews this */
|
|
117
|
+
injectedKeywords(): string[] {
|
|
118
|
+
const src = this.promptOpts.loraKeywordsFrom
|
|
119
|
+
if (src == null) return []
|
|
120
|
+
return [
|
|
121
|
+
...new Set(
|
|
122
|
+
src
|
|
123
|
+
.activeNames()
|
|
124
|
+
.map(getLoraKeyword)
|
|
125
|
+
.filter((k) => k !== ''),
|
|
126
|
+
),
|
|
127
|
+
]
|
|
128
|
+
}
|
|
129
|
+
outValue(): PromptValue {
|
|
130
|
+
const pos: string[] = []
|
|
131
|
+
const neg: string[] = []
|
|
132
|
+
for (const line of this.value.split('\n')) {
|
|
133
|
+
if (commentLineRe.test(line)) continue
|
|
134
|
+
const m = negativeLineRe.exec(line)
|
|
135
|
+
if (m != null) {
|
|
136
|
+
const text = (m[1] ?? '').trim()
|
|
137
|
+
if (text !== '') neg.push(text)
|
|
138
|
+
} else pos.push(line)
|
|
139
|
+
}
|
|
140
|
+
const body = pos.join('\n').trim()
|
|
141
|
+
const keywords = this.injectedKeywords()
|
|
142
|
+
const positive =
|
|
143
|
+
keywords.length === 0 ? body : body === '' ? keywords.join(', ') : `${keywords.join(', ')}, ${body}`
|
|
144
|
+
return { positive, negative: neg.join(', ') }
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export class IntVar extends ComfyVar<number> {
|
|
149
|
+
readonly kind = 'int' as const
|
|
150
|
+
constructor(
|
|
151
|
+
defaultValue: number,
|
|
152
|
+
public opts: { min?: number; max?: number; label?: string } = {},
|
|
153
|
+
) {
|
|
154
|
+
super(defaultValue, opts.label)
|
|
155
|
+
}
|
|
156
|
+
override set(value: number): this {
|
|
157
|
+
const clamped = Math.round(Math.min(this.opts.max ?? Infinity, Math.max(this.opts.min ?? -Infinity, value)))
|
|
158
|
+
return super.set(clamped)
|
|
159
|
+
}
|
|
160
|
+
parse(raw: string): boolean {
|
|
161
|
+
const n = Number(raw)
|
|
162
|
+
if (Number.isNaN(n)) return false
|
|
163
|
+
this.set(n)
|
|
164
|
+
return true
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
export class FloatVar extends ComfyVar<number> {
|
|
169
|
+
readonly kind = 'float' as const
|
|
170
|
+
constructor(
|
|
171
|
+
defaultValue: number,
|
|
172
|
+
public opts: { min?: number; max?: number; label?: string } = {},
|
|
173
|
+
) {
|
|
174
|
+
super(defaultValue, opts.label)
|
|
175
|
+
}
|
|
176
|
+
override set(value: number): this {
|
|
177
|
+
return super.set(Math.min(this.opts.max ?? Infinity, Math.max(this.opts.min ?? -Infinity, value)))
|
|
178
|
+
}
|
|
179
|
+
parse(raw: string): boolean {
|
|
180
|
+
const n = Number(raw)
|
|
181
|
+
if (Number.isNaN(n)) return false
|
|
182
|
+
this.set(n)
|
|
183
|
+
return true
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** '=' fixed · '+' increment each run · '-' decrement each run · '?' reroll each run */
|
|
188
|
+
export type SeedMode = '=' | '+' | '-' | '?'
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* a seed is a MODE + a number. `value` stays a plain number (what the graph
|
|
192
|
+
* consumes); `mode` decides how it advances after each run (afterRun()):
|
|
193
|
+
* `= 12` fixed · `+ 0` auto-increment · `- 0` auto-decrement · `? 0` random.
|
|
194
|
+
* The number shown is always the seed the NEXT run will use.
|
|
195
|
+
*/
|
|
196
|
+
export class SeedVar extends ComfyVar<number> {
|
|
197
|
+
readonly kind = 'seed' as const
|
|
198
|
+
mode: SeedMode = '='
|
|
199
|
+
constructor(defaultValue: number = 0, label?: string) {
|
|
200
|
+
super(defaultValue, label)
|
|
201
|
+
// subclass-owned observable field (base makeObservable already ran in super)
|
|
202
|
+
makeObservable(this, { mode: observable, setMode: action, randomize: action, advance: action })
|
|
203
|
+
}
|
|
204
|
+
setMode(mode: SeedMode): this {
|
|
205
|
+
this.mode = mode
|
|
206
|
+
return this
|
|
207
|
+
}
|
|
208
|
+
randomize(): this {
|
|
209
|
+
return this.set(Math.floor(Math.random() * 2 ** 32))
|
|
210
|
+
}
|
|
211
|
+
override set(value: number): this {
|
|
212
|
+
// seeds are unsigned: clamp at 0 so decrement can't go negative
|
|
213
|
+
return super.set(Math.max(0, Math.floor(value)))
|
|
214
|
+
}
|
|
215
|
+
/** move the seed to what the NEXT run should use, per mode */
|
|
216
|
+
advance(): this {
|
|
217
|
+
if (this.mode === '+') return this.set(this.value + 1)
|
|
218
|
+
if (this.mode === '-') return this.set(this.value - 1)
|
|
219
|
+
if (this.mode === '?') return this.randomize()
|
|
220
|
+
return this // '=' stays fixed
|
|
221
|
+
}
|
|
222
|
+
override afterRun(): void {
|
|
223
|
+
this.advance()
|
|
224
|
+
}
|
|
225
|
+
/** parse `+` `- 12` `= 5` `?` or a bare number (=> fixed). Keeps the current number when none given */
|
|
226
|
+
parse(raw: string): boolean {
|
|
227
|
+
const m = raw.trim().match(/^([+\-=?])?\s*(\d+)?$/)
|
|
228
|
+
if (m == null) return false
|
|
229
|
+
const modeChar = m[1]
|
|
230
|
+
const numStr = m[2]
|
|
231
|
+
if (modeChar == null && numStr == null) return false
|
|
232
|
+
this.setMode(modeChar == null ? '=' : (modeChar as SeedMode))
|
|
233
|
+
if (numStr != null) this.set(Number(numStr))
|
|
234
|
+
return true
|
|
235
|
+
}
|
|
236
|
+
override display(): string {
|
|
237
|
+
return `${this.mode} ${this.value}`
|
|
238
|
+
}
|
|
239
|
+
override toEditBuffer(): string {
|
|
240
|
+
return `${this.mode} ${this.value}`
|
|
241
|
+
}
|
|
242
|
+
override toJSON(): unknown {
|
|
243
|
+
return { mode: this.mode, value: this.value }
|
|
244
|
+
}
|
|
245
|
+
override loadJSON(value: unknown): this {
|
|
246
|
+
if (typeof value === 'number') return this.set(value) // legacy plain-number drafts
|
|
247
|
+
if (value != null && typeof value === 'object') {
|
|
248
|
+
const o = value as { mode?: unknown; value?: unknown }
|
|
249
|
+
if (o.mode === '=' || o.mode === '+' || o.mode === '-' || o.mode === '?') this.setMode(o.mode)
|
|
250
|
+
if (typeof o.value === 'number') this.set(o.value)
|
|
251
|
+
}
|
|
252
|
+
return this
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
export class ToggleVar extends ComfyVar<boolean> {
|
|
257
|
+
readonly kind = 'toggle' as const
|
|
258
|
+
toggle(): this {
|
|
259
|
+
return this.set(!this.value)
|
|
260
|
+
}
|
|
261
|
+
parse(raw: string): boolean {
|
|
262
|
+
if (raw !== 'true' && raw !== 'false') return false
|
|
263
|
+
this.set(raw === 'true')
|
|
264
|
+
return true
|
|
265
|
+
}
|
|
266
|
+
override display(): string {
|
|
267
|
+
return this.value ? 'ON' : 'OFF'
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
export class ChoiceVar<T extends string> extends ComfyVar<T> {
|
|
272
|
+
readonly kind = 'choice' as const
|
|
273
|
+
constructor(
|
|
274
|
+
public readonly choices: readonly T[],
|
|
275
|
+
defaultValue: T,
|
|
276
|
+
label?: string,
|
|
277
|
+
) {
|
|
278
|
+
super(defaultValue, label)
|
|
279
|
+
}
|
|
280
|
+
next(delta: number = 1): this {
|
|
281
|
+
const ix = this.choices.indexOf(this.value)
|
|
282
|
+
const nextIx = (ix + delta + this.choices.length) % this.choices.length
|
|
283
|
+
return this.set(this.choices[nextIx] ?? this.value)
|
|
284
|
+
}
|
|
285
|
+
parse(raw: string): boolean {
|
|
286
|
+
const hit = this.choices.find((c) => c === raw)
|
|
287
|
+
if (hit == null) return false
|
|
288
|
+
this.set(hit)
|
|
289
|
+
return true
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/**
|
|
294
|
+
* per-lora setting: false = off, true = 1/1, number = both strengths,
|
|
295
|
+
* [strength_model, strength_clip] = each explicitly
|
|
296
|
+
*/
|
|
297
|
+
export type LoraStrength = boolean | number | [strengthModel: number, strengthClip: number]
|
|
298
|
+
|
|
299
|
+
export type ActiveLora<T extends string> = { lora_name: T; strength_model: number; strength_clip: number }
|
|
300
|
+
|
|
301
|
+
/** normalize a loras record into what a standard LoraLoader chain consumes */
|
|
302
|
+
export function activeLoras<T extends string>(loras: Partial<Record<T, LoraStrength>>): ActiveLora<T>[] {
|
|
303
|
+
const out: ActiveLora<T>[] = []
|
|
304
|
+
for (const [lora_name, s] of Object.entries(loras) as [T, LoraStrength | undefined][]) {
|
|
305
|
+
if (s == null || s === false) continue
|
|
306
|
+
const [strength_model, strength_clip] = Array.isArray(s) ? s : s === true ? [1, 1] : [s, s]
|
|
307
|
+
out.push({ lora_name, strength_model, strength_clip })
|
|
308
|
+
}
|
|
309
|
+
return out
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/** what LorasVar.bindHost needs — structural, so ComfyVars never imports ComfyHost */
|
|
313
|
+
export type LorasHost = { schema: { getLoras(filter?: RegExp): string[] } }
|
|
314
|
+
|
|
315
|
+
/**
|
|
316
|
+
* multi-select lora stack over a DYNAMIC options list — a RegExp resolves
|
|
317
|
+
* against the host's loras at define time (DefinedWorkflow calls bindHost),
|
|
318
|
+
* or feed it host discovery (`host.schema.getLoras(regex?)`) directly; never
|
|
319
|
+
* a hardcoded inventory. Selection is empty by default.
|
|
320
|
+
*/
|
|
321
|
+
export class LorasVar<T extends string> extends ComfyVar<Partial<Record<T, LoraStrength>>> {
|
|
322
|
+
readonly kind = 'loras' as const
|
|
323
|
+
/** last non-false strength per lora, so untick → re-tick restores it */
|
|
324
|
+
private prev: Partial<Record<T, LoraStrength>> = {}
|
|
325
|
+
/** a RegExp source resolves lazily (bindHost) — null until then */
|
|
326
|
+
private resolvedOptions: readonly T[] | null = null
|
|
327
|
+
|
|
328
|
+
constructor(
|
|
329
|
+
private readonly optionsSource: readonly T[] | RegExp,
|
|
330
|
+
initial: Partial<Record<T, LoraStrength>> = {},
|
|
331
|
+
label?: string,
|
|
332
|
+
) {
|
|
333
|
+
super(initial, label)
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
get options(): readonly T[] {
|
|
337
|
+
if (!(this.optionsSource instanceof RegExp)) return this.optionsSource
|
|
338
|
+
if (this.resolvedOptions == null)
|
|
339
|
+
throw new Error(
|
|
340
|
+
`v.loras(${String(this.optionsSource)}) is host-bound — it only works inside defineWorkflow({ vars }) (pass a name list otherwise)`,
|
|
341
|
+
)
|
|
342
|
+
return this.resolvedOptions
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/** DefinedWorkflow binds the host at define time: a RegExp source resolves here.
|
|
346
|
+
* cast: whitelist family 1 (agent/coding.md) — getLoras() returns the runtime
|
|
347
|
+
* values of the SAME object_info enum the generated E_LoraName union comes from */
|
|
348
|
+
bindHost(host: LorasHost): void {
|
|
349
|
+
if (!(this.optionsSource instanceof RegExp)) return
|
|
350
|
+
this.resolvedOptions = host.schema.getLoras(this.optionsSource) as T[]
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
get names(): T[] {
|
|
354
|
+
return [...this.options]
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/** loras currently ON (PromptVar keyword prefixing consumes this) */
|
|
358
|
+
activeNames(): T[] {
|
|
359
|
+
return this.names.filter((n) => this.isOn(n))
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
isOn(name: T): boolean {
|
|
363
|
+
const s = this.value[name]
|
|
364
|
+
return s != null && s !== false
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
toggleItem(name: T): this {
|
|
368
|
+
const cur = this.value[name]
|
|
369
|
+
if (cur == null || cur === false) return this.set({ ...this.value, [name]: this.prev[name] ?? true })
|
|
370
|
+
this.prev[name] = cur
|
|
371
|
+
return this.set({ ...this.value, [name]: false })
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/** step both strengths by delta (true becomes 1 first); no-op when off */
|
|
375
|
+
adjustItem(name: T, delta: number): this {
|
|
376
|
+
const cur = this.value[name]
|
|
377
|
+
if (cur == null || cur === false) return this
|
|
378
|
+
const step = (n: number): number => Math.max(0, Math.round((n + delta) * 100) / 100)
|
|
379
|
+
const next: LoraStrength = Array.isArray(cur) ? [step(cur[0]), step(cur[1])] : step(cur === true ? 1 : cur)
|
|
380
|
+
return this.set({ ...this.value, [name]: next })
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
/** compact per-item strength label for lists */
|
|
384
|
+
strengthLabel(name: T): string {
|
|
385
|
+
const s = this.value[name]
|
|
386
|
+
if (s == null || s === false) return ''
|
|
387
|
+
if (s === true) return '1.00'
|
|
388
|
+
if (Array.isArray(s)) return `m:${s[0].toFixed(2)} c:${s[1].toFixed(2)}`
|
|
389
|
+
return s.toFixed(2)
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
parse(raw: string): boolean {
|
|
393
|
+
try {
|
|
394
|
+
const parsed: unknown = JSON.parse(raw)
|
|
395
|
+
if (typeof parsed !== 'object' || parsed == null || Array.isArray(parsed)) return false
|
|
396
|
+
this.set(parsed as Partial<Record<T, LoraStrength>>)
|
|
397
|
+
return true
|
|
398
|
+
} catch {
|
|
399
|
+
return false
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
/** short human name: subfolder + extension stripped */
|
|
404
|
+
static shortName(name: string): string {
|
|
405
|
+
return (name.split(/[\\/]/).pop() ?? name).replace(/\.safetensors$/, '')
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
/** tick (true) or untick (false) every lora in `names` (default: all options) */
|
|
409
|
+
setAll(on: boolean, names: readonly T[] = this.options): this {
|
|
410
|
+
const next = { ...this.value }
|
|
411
|
+
for (const name of names) {
|
|
412
|
+
const cur = next[name]
|
|
413
|
+
if (on) {
|
|
414
|
+
if (cur == null || cur === false) next[name] = this.prev[name] ?? true
|
|
415
|
+
} else {
|
|
416
|
+
if (cur != null && cur !== false) this.prev[name] = cur
|
|
417
|
+
next[name] = false
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
return this.set(next)
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
override display(): string {
|
|
424
|
+
const on = this.activeNames()
|
|
425
|
+
if (on.length === 0) return `(0/${this.options.length}) none`
|
|
426
|
+
return `(${on.length}/${this.options.length}) ${on.map((n) => LorasVar.shortName(n)).join(', ')}`
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
export type SizeValue = { width: number; height: number }
|
|
431
|
+
export type SizePreset = { label: string; width: number; height: number }
|
|
432
|
+
|
|
433
|
+
/** SDXL-style ~1MP buckets, multiples of 64 — safe for most latent models */
|
|
434
|
+
export const DEFAULT_SIZE_PRESETS: SizePreset[] = [
|
|
435
|
+
{ label: '1:1 square', width: 1024, height: 1024 },
|
|
436
|
+
{ label: '4:3 landscape', width: 1152, height: 896 },
|
|
437
|
+
{ label: '3:4 portrait', width: 896, height: 1152 },
|
|
438
|
+
{ label: '3:2 landscape', width: 1216, height: 832 },
|
|
439
|
+
{ label: '2:3 portrait', width: 832, height: 1216 },
|
|
440
|
+
{ label: '16:9 widescreen', width: 1344, height: 768 },
|
|
441
|
+
{ label: '9:16 tall', width: 768, height: 1344 },
|
|
442
|
+
]
|
|
443
|
+
|
|
444
|
+
/** width/height picker: presets + free `WxH` entry */
|
|
445
|
+
export class SizeVar extends ComfyVar<SizeValue> {
|
|
446
|
+
readonly kind = 'size' as const
|
|
447
|
+
constructor(
|
|
448
|
+
defaultValue: SizeValue = { width: 1024, height: 1024 },
|
|
449
|
+
public readonly presets: SizePreset[] = DEFAULT_SIZE_PRESETS,
|
|
450
|
+
label?: string,
|
|
451
|
+
) {
|
|
452
|
+
super(defaultValue, label)
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
/** accepts '1024x768' / '1024×768' / a preset label */
|
|
456
|
+
parse(raw: string): boolean {
|
|
457
|
+
const m = raw.trim().match(/^(\d+)\s*[x×]\s*(\d+)$/)
|
|
458
|
+
if (m != null) {
|
|
459
|
+
this.set({ width: Number(m[1]), height: Number(m[2]) })
|
|
460
|
+
return true
|
|
461
|
+
}
|
|
462
|
+
const preset = this.presets.find((p) => p.label === raw.trim())
|
|
463
|
+
if (preset != null) {
|
|
464
|
+
this.set({ width: preset.width, height: preset.height })
|
|
465
|
+
return true
|
|
466
|
+
}
|
|
467
|
+
return false
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
override display(): string {
|
|
471
|
+
const { width, height } = this.value
|
|
472
|
+
const hit = this.presets.find((p) => p.width === width && p.height === height)
|
|
473
|
+
return `${width}×${height}${hit ? ` (${hit.label})` : ''}`
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
/** the var constructors: v.text / v.prompt / v.int / v.float / v.seed / v.toggle / v.choice / v.loras / v.size */
|
|
478
|
+
export const v = {
|
|
479
|
+
text: (defaultValue: string, label?: string): TextVar => new TextVar(defaultValue, label),
|
|
480
|
+
prompt: (defaultValue: string, opts: { label?: string; loraKeywordsFrom?: ActiveLoraSource } = {}): PromptVar =>
|
|
481
|
+
new PromptVar(defaultValue, opts),
|
|
482
|
+
int: (defaultValue: number, opts: { min?: number; max?: number; label?: string } = {}): IntVar =>
|
|
483
|
+
new IntVar(defaultValue, opts),
|
|
484
|
+
float: (defaultValue: number, opts: { min?: number; max?: number; label?: string } = {}): FloatVar =>
|
|
485
|
+
new FloatVar(defaultValue, opts),
|
|
486
|
+
seed: (defaultValue: number = 0, label?: string): SeedVar => new SeedVar(defaultValue, label),
|
|
487
|
+
toggle: (defaultValue: boolean, label?: string): ToggleVar => new ToggleVar(defaultValue, label),
|
|
488
|
+
choice: <const T extends string>(choices: readonly T[], defaultValue: T, label?: string): ChoiceVar<T> =>
|
|
489
|
+
new ChoiceVar(choices, defaultValue, label),
|
|
490
|
+
loras: <T extends string = string>(
|
|
491
|
+
options: readonly T[] | RegExp,
|
|
492
|
+
initial: Partial<Record<T, LoraStrength>> = {},
|
|
493
|
+
label?: string,
|
|
494
|
+
): LorasVar<T> => new LorasVar(options, initial, label),
|
|
495
|
+
size: (defaultValue?: SizeValue, opts: { presets?: SizePreset[]; label?: string } = {}): SizeVar =>
|
|
496
|
+
new SizeVar(defaultValue, opts.presets, opts.label),
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
/**
|
|
500
|
+
* structural face of any var: readonly `value` keeps ComfyVar<T> assignable
|
|
501
|
+
* despite T-invariance on the mutable field. VarValues re-derives the exact
|
|
502
|
+
* value types via infer.
|
|
503
|
+
*/
|
|
504
|
+
export type AnyVar = {
|
|
505
|
+
readonly kind: VarKind
|
|
506
|
+
readonly value: unknown
|
|
507
|
+
readonly label?: string
|
|
508
|
+
parse(raw: string): boolean
|
|
509
|
+
loadJSON(value: unknown): unknown
|
|
510
|
+
toJSON(): unknown
|
|
511
|
+
outValue(): unknown
|
|
512
|
+
display(): string
|
|
513
|
+
toEditBuffer(): string
|
|
514
|
+
afterRun(): void
|
|
515
|
+
/** host-dependent vars (LorasVar regex) resolve here — DefinedWorkflow calls it at define time */
|
|
516
|
+
bindHost?(host: LorasHost): void
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
export type VarsSpec = { [key: string]: AnyVar }
|
|
520
|
+
|
|
521
|
+
export type VarValues<V extends VarsSpec> = {
|
|
522
|
+
// outValue() return type, not the stored type: PromptVar stores string, contributes PromptValue
|
|
523
|
+
[K in keyof V]: V[K] extends { outValue(): infer O } ? O : never
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
export function varValues<V extends VarsSpec>(vars: V): VarValues<V> {
|
|
527
|
+
const out: Record<string, unknown> = {}
|
|
528
|
+
// outValue, not value: PromptVar strips comments / prefixes lora keywords here
|
|
529
|
+
for (const [k, varDef] of Object.entries(vars)) out[k] = varDef.outValue()
|
|
530
|
+
return out as VarValues<V>
|
|
531
|
+
}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import type { ComfyHost } from 'src/host/ComfyHost.ts'
|
|
2
|
+
import type { ComfyExecution } from 'src/runner/ComfyExecution.ts'
|
|
3
|
+
import type { ComfyWorkflow, RunSettings } from 'src/runner/ComfyWorkflow.ts'
|
|
4
|
+
import type { SdkForHost } from 'src/types/comfy-sdk.ts'
|
|
5
|
+
import {
|
|
6
|
+
type AnyVar,
|
|
7
|
+
type LorasVar,
|
|
8
|
+
type LoraStrength,
|
|
9
|
+
v,
|
|
10
|
+
type VarsSpec,
|
|
11
|
+
type VarValues,
|
|
12
|
+
varValues,
|
|
13
|
+
} from 'src/vars/ComfyVars.ts'
|
|
14
|
+
|
|
15
|
+
/** the host's generated lora-name union (plain string when no sdk is generated) */
|
|
16
|
+
export type LoraNameOf<ID extends string> = 'E_LoraName' extends keyof SdkForHost<ID>['Union']
|
|
17
|
+
? SdkForHost<ID>['Union']['E_LoraName'] & string
|
|
18
|
+
: string
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* the `v` handed to a vars LAMBDA: the global factory, host-typed —
|
|
22
|
+
* `v.loras(regex)` yields the host's lora-name union (resolved via bindHost)
|
|
23
|
+
*/
|
|
24
|
+
export type BoundVars<ID extends string> = Omit<typeof v, 'loras'> & {
|
|
25
|
+
loras(
|
|
26
|
+
options: RegExp,
|
|
27
|
+
initial?: Partial<Record<LoraNameOf<ID>, LoraStrength>>,
|
|
28
|
+
label?: string,
|
|
29
|
+
): LorasVar<LoraNameOf<ID>>
|
|
30
|
+
loras<T extends string>(
|
|
31
|
+
options: readonly T[],
|
|
32
|
+
initial?: Partial<Record<T, LoraStrength>>,
|
|
33
|
+
label?: string,
|
|
34
|
+
): LorasVar<T>
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export type DefineWorkflowSpec<ID extends string, V extends VarsSpec> = {
|
|
38
|
+
/** short id; also names the workflow instances */
|
|
39
|
+
id?: string
|
|
40
|
+
/** the tweakable knobs; drivers (scripts, TUI) edit these between runs.
|
|
41
|
+
* A LAMBDA gives cross-referencing vars a scope (loras + prompt with
|
|
42
|
+
* loraKeywordsFrom created inline) — resolved ONCE at define time, and it
|
|
43
|
+
* RECEIVES the host-typed `v` (no import needed) */
|
|
44
|
+
vars: V | ((v: BoundVars<ID>) => V)
|
|
45
|
+
/** builds the graph from the CURRENT var values; re-executed on every run().
|
|
46
|
+
* may be async (e.g. image uploads through the wf param) */
|
|
47
|
+
build: (b: SdkForHost<ID>['Builder'], vars: VarValues<V>, wf: ComfyWorkflow<ID>) => void | Promise<void>
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** type predicate (not a cast): a VarsSpec is a plain record, never callable */
|
|
51
|
+
function isVarsThunk<ID extends string, V extends VarsSpec>(
|
|
52
|
+
vars: V | ((v: BoundVars<ID>) => V),
|
|
53
|
+
): vars is (v: BoundVars<ID>) => V {
|
|
54
|
+
return typeof vars === 'function'
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* a re-runnable workflow definition: `build` re-executes per run with the
|
|
59
|
+
* current var values, so every run gets a fresh, deterministic graph.
|
|
60
|
+
*/
|
|
61
|
+
export class DefinedWorkflow<ID extends string = string, V extends VarsSpec = VarsSpec> {
|
|
62
|
+
/** spec.vars resolved once (may be given as a thunk) — the SAME instances for the workflow's lifetime */
|
|
63
|
+
readonly vars: V
|
|
64
|
+
|
|
65
|
+
constructor(
|
|
66
|
+
public host: ComfyHost<ID>,
|
|
67
|
+
public spec: DefineWorkflowSpec<ID, V>,
|
|
68
|
+
) {
|
|
69
|
+
// cast: whitelist family 1 (agent/coding.md) — the runtime `v` IS the
|
|
70
|
+
// factory BoundVars describes; the regex-loras typing claim it adds is
|
|
71
|
+
// resolved from the same object_info enum via bindHost below
|
|
72
|
+
this.vars = isVarsThunk(spec.vars) ? spec.vars(v as BoundVars<ID>) : spec.vars
|
|
73
|
+
// host-dependent vars (v.loras(regex)) resolve NOW, at define time
|
|
74
|
+
for (const [, varDef] of this.entries()) varDef.bindHost?.(this.host)
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** [name, var] pairs, for drivers that enumerate the knobs */
|
|
78
|
+
entries(): [string, AnyVar][] {
|
|
79
|
+
return Object.entries(this.vars)
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** the workflow built by the latest run() (null before the first run) */
|
|
83
|
+
lastWorkflow: ComfyWorkflow<ID> | null = null
|
|
84
|
+
/** the latest execution (null before the first run) */
|
|
85
|
+
lastExecution: ComfyExecution | null = null
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* build a fresh graph from the CURRENT var values (no send). `p.advance`
|
|
89
|
+
* (set by run()) fires each var's afterRun() right after snapshotting the
|
|
90
|
+
* values — atomically, before any await — so the graph uses this run's seed
|
|
91
|
+
* while the var moves to the next (queued runs get distinct seeds; a bare
|
|
92
|
+
* build() for copy/export never advances).
|
|
93
|
+
*/
|
|
94
|
+
async build(p: { advance?: boolean } = {}): Promise<ComfyWorkflow<ID>> {
|
|
95
|
+
const wf = this.host.workflow({ id: this.spec.id })
|
|
96
|
+
const values = varValues(this.vars)
|
|
97
|
+
if (p.advance) for (const varDef of Object.values(this.vars)) varDef.afterRun()
|
|
98
|
+
await this.spec.build(wf.builder, values, wf)
|
|
99
|
+
this.lastWorkflow = wf
|
|
100
|
+
return wf
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** build a fresh graph from the current var values, send it, wait for outputs.
|
|
104
|
+
* connects first (idempotent) — modules can import offline from the schema cache */
|
|
105
|
+
async run(settings: RunSettings = {}): Promise<ComfyExecution> {
|
|
106
|
+
await this.host.connect()
|
|
107
|
+
const wf = await this.build({ advance: true })
|
|
108
|
+
const execution = await wf.run(settings)
|
|
109
|
+
this.lastExecution = execution
|
|
110
|
+
return execution
|
|
111
|
+
}
|
|
112
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
|
2
|
+
import { observable, runInAction } from 'mobx'
|
|
3
|
+
import { dirname, join } from 'pathe'
|
|
4
|
+
import { logError } from 'src/utils/log.ts'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* hand-assigned trigger keyword(s) per lora name — set via ⌃K in the TUI loras
|
|
8
|
+
* overlay, consumed by PromptVar's `loraKeywordsFrom` prefixing. Persisted at
|
|
9
|
+
* `.comfy-ts/lora-keywords.json` (NOT under cache/: this is hand-entered data
|
|
10
|
+
* and must survive a cache wipe). Observable map: overlay rows re-render on
|
|
11
|
+
* assignment. Keys are the RAW lora names (folder/file.safetensors).
|
|
12
|
+
*/
|
|
13
|
+
const keywords = observable.map<string, string>()
|
|
14
|
+
let loaded = false
|
|
15
|
+
|
|
16
|
+
function filePath(): string {
|
|
17
|
+
return join(comfyts.baseFolder, 'lora-keywords.json')
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function loadOnce(): void {
|
|
21
|
+
if (loaded) return
|
|
22
|
+
loaded = true
|
|
23
|
+
const path = filePath()
|
|
24
|
+
if (!existsSync(path)) return
|
|
25
|
+
try {
|
|
26
|
+
const raw: unknown = JSON.parse(readFileSync(path, 'utf8'))
|
|
27
|
+
if (raw == null || typeof raw !== 'object') return
|
|
28
|
+
runInAction(() => {
|
|
29
|
+
for (const [name, kw] of Object.entries(raw)) if (typeof kw === 'string') keywords.set(name, kw)
|
|
30
|
+
})
|
|
31
|
+
} catch (e) {
|
|
32
|
+
logError(`[loraKeywords] unreadable ${path}: ${String(e)}`)
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function getLoraKeyword(name: string): string {
|
|
37
|
+
loadOnce()
|
|
38
|
+
return keywords.get(name) ?? ''
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** empty keyword deletes the entry; every set writes the file (tiny, rare) */
|
|
42
|
+
export function setLoraKeyword(name: string, keyword: string): void {
|
|
43
|
+
loadOnce()
|
|
44
|
+
const trimmed = keyword.trim()
|
|
45
|
+
runInAction(() => {
|
|
46
|
+
if (trimmed === '') keywords.delete(name)
|
|
47
|
+
else keywords.set(name, trimmed)
|
|
48
|
+
})
|
|
49
|
+
const path = filePath()
|
|
50
|
+
try {
|
|
51
|
+
mkdirSync(dirname(path), { recursive: true })
|
|
52
|
+
writeFileSync(path, JSON.stringify(Object.fromEntries([...keywords.entries()].sort()), null, 2))
|
|
53
|
+
} catch (e) {
|
|
54
|
+
logError(`[loraKeywords] write failed ${path}: ${String(e)}`)
|
|
55
|
+
}
|
|
56
|
+
}
|