comfy-ts 0.2.0 → 0.4.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.
Files changed (161) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +363 -0
  3. package/dist/cli.js +764 -0
  4. package/dist/cli.js.map +1 -0
  5. package/dist/index.cjs +4171 -0
  6. package/dist/index.cjs.map +1 -0
  7. package/dist/index.d.cts +9910 -0
  8. package/dist/index.d.ts +9894 -58
  9. package/dist/index.js +4092 -2
  10. package/dist/index.js.map +1 -1
  11. package/dist/log-CdfgILde.js +10 -0
  12. package/dist/log-CdfgILde.js.map +1 -0
  13. package/dist/run-tui-SDSJo1Qf.js +3896 -0
  14. package/dist/run-tui-SDSJo1Qf.js.map +1 -0
  15. package/package.json +103 -75
  16. package/src/cli/comfy-ts-cli.ts +36 -0
  17. package/src/cli/gen.ts +47 -0
  18. package/src/cli/outline.ts +82 -0
  19. package/src/cli/tui/components/DraftsOverlay.tsx +44 -0
  20. package/src/cli/tui/components/EditField.tsx +27 -0
  21. package/src/cli/tui/components/Header.tsx +56 -0
  22. package/src/cli/tui/components/HostPanel.tsx +37 -0
  23. package/src/cli/tui/components/LogsPanel.tsx +23 -0
  24. package/src/cli/tui/components/LorasOverlay.tsx +49 -0
  25. package/src/cli/tui/components/OverlayList.tsx +25 -0
  26. package/src/cli/tui/components/PickerOverlays.tsx +66 -0
  27. package/src/cli/tui/components/PreviewPanel.tsx +78 -0
  28. package/src/cli/tui/components/PromptOverlay.tsx +16 -0
  29. package/src/cli/tui/components/StatusBar.tsx +171 -0
  30. package/src/cli/tui/components/TextOverlay.tsx +72 -0
  31. package/src/cli/tui/components/TreePanel.tsx +51 -0
  32. package/src/cli/tui/components/TuiApp.tsx +246 -0
  33. package/src/cli/tui/components/VarsPanel.tsx +86 -0
  34. package/src/cli/tui/findDefinedWorkflow.ts +16 -0
  35. package/src/cli/tui/keys.ts +20 -0
  36. package/src/cli/tui/protocolImagePainter.ts +95 -0
  37. package/src/cli/tui/run-tui.tsx +76 -0
  38. package/src/cli/tui/state/DraftsSt.ts +273 -0
  39. package/src/cli/tui/state/EditorSt.ts +289 -0
  40. package/src/cli/tui/state/ExecSt.ts +173 -0
  41. package/src/cli/tui/state/HostSt.ts +230 -0
  42. package/src/cli/tui/state/LogsSt.ts +107 -0
  43. package/src/cli/tui/state/LorasSt.ts +185 -0
  44. package/src/cli/tui/state/PickerSt.ts +112 -0
  45. package/src/cli/tui/state/PreviewSt.ts +288 -0
  46. package/src/cli/tui/state/QueueSt.ts +59 -0
  47. package/src/cli/tui/state/SettingsSt.ts +100 -0
  48. package/src/cli/tui/state/TreeSt.ts +122 -0
  49. package/src/cli/tui/state/TuiSt.ts +175 -0
  50. package/src/cli/tui/state/WorkflowsSt.ts +93 -0
  51. package/src/cli/tui-env.ts +8 -0
  52. package/src/errors/InvalidPromptError.ts +12 -0
  53. package/src/graph/ComfyNode.ts +403 -0
  54. package/src/graph/ComfyNodeID.ts +28 -0
  55. package/src/graph/ComfyNodeOutput.ts +16 -0
  56. package/src/graph/NodeSlotSize.ts +4 -0
  57. package/src/graph/autoValue.ts +17 -0
  58. package/src/host/ComfyHost.ts +690 -0
  59. package/src/host/ComfyInstallType.ts +15 -0
  60. package/src/host/ComfyManager.ts +232 -0
  61. package/src/host/ComfyUploader.ts +110 -0
  62. package/src/host/ComfyWorkflowBuilder.ts +60 -0
  63. package/src/host/Requirements.ts +55 -0
  64. package/src/host/ResilientWebsocket.ts +147 -0
  65. package/src/host/loraManagerApi.ts +98 -0
  66. package/src/image-utils/_getPngMetadata.ts +53 -0
  67. package/src/image-utils/_getWebpMetadata.ts +38 -0
  68. package/src/image-utils/_parseExifData.ts +53 -0
  69. package/src/index.ts +89 -0
  70. package/src/litegraph/LiteGraphGroup.ts +22 -0
  71. package/src/litegraph/LiteGraphJSON.ts +46 -0
  72. package/src/litegraph/LiteGraphLink.ts +23 -0
  73. package/src/litegraph/LiteGraphLinkID.ts +6 -0
  74. package/src/litegraph/LiteGraphNode.ts +69 -0
  75. package/src/litegraph/LiteGraphNodeInput.ts +27 -0
  76. package/src/litegraph/LiteGraphNodeOutput.ts +23 -0
  77. package/src/litegraph/LiteGraphSlotIndex.ts +6 -0
  78. package/src/litegraph/convertFlowToLiteGraphJSON.ts +114 -0
  79. package/src/manager/ComfyRegistry.ts +124 -0
  80. package/src/manager/generated/KnownComfyCustomNodeName.ts +19280 -0
  81. package/src/manager/generated/KnownComfyPluginTitle.ts +5130 -0
  82. package/src/manager/generated/KnownComfyPluginURL.ts +2589 -0
  83. package/src/manager/generated/KnownModel_Base.ts +126 -0
  84. package/src/manager/generated/KnownModel_FileName.ts +2287 -0
  85. package/src/manager/generated/KnownModel_Name.ts +2287 -0
  86. package/src/manager/generated/KnownModel_SavePath.ts +263 -0
  87. package/src/manager/generated/KnownModel_Type.ts +97 -0
  88. package/src/manager/json/alter-list.json +224 -0
  89. package/src/manager/json/custom-node-list.extra.ts +13 -0
  90. package/src/manager/json/custom-node-list.json +21948 -0
  91. package/src/manager/json/extension-node-map.json +31282 -0
  92. package/src/manager/json/github-stats.json +12602 -0
  93. package/src/manager/json/model-list.extra.ts +26 -0
  94. package/src/manager/json/model-list.json +5052 -0
  95. package/src/manager/loaders/step1_downloadComfyManagerJSONs.ts +56 -0
  96. package/src/manager/loaders/step2_custom-node-list-loader.ts +149 -0
  97. package/src/manager/loaders/step3_extension-node-map-loader.ts +189 -0
  98. package/src/manager/loaders/step4_model-list-loader.ts +159 -0
  99. package/src/manager/script-update-manager.bun.ts +18 -0
  100. package/src/manager/types/ComfyManagerAPIFetchPolicy.ts +9 -0
  101. package/src/manager/types/ComfyManagerAPIModelList.ts +10 -0
  102. package/src/manager/types/ComfyManagerAPIPluginList.ts +11 -0
  103. package/src/manager/types/ComfyManagerFileModelInfo.ts +5 -0
  104. package/src/manager/types/ComfyManagerFilePluginContent.ts +13 -0
  105. package/src/manager/types/ComfyManagerFilePluginList.ts +5 -0
  106. package/src/manager/types/ComfyManagerModelInfo.ts +18 -0
  107. package/src/manager/types/ComfyManagerPluginContentMetadata.ts +16 -0
  108. package/src/manager/types/ComfyManagerPluginEnums.ts +8 -0
  109. package/src/manager/types/ComfyManagerPluginInfo.ts +50 -0
  110. package/src/runner/ComfyExecution.ts +301 -0
  111. package/src/runner/ComfyExecutionStatus.ts +2 -0
  112. package/src/runner/ComfyWorkflow.ts +395 -0
  113. package/src/runner/ComfyWorkflowLayout.ts +96 -0
  114. package/src/runner/ComfyWsApi.ts +170 -0
  115. package/src/runner/MediaImage.ts +262 -0
  116. package/src/sdk-generator/ComfyNodeSchema.ts +79 -0
  117. package/src/sdk-generator/ComfySchema.ts +369 -0
  118. package/src/sdk-generator/ComfyUIObjectInfoTypes.ts +95 -0
  119. package/src/sdk-generator/Primitives.ts +76 -0
  120. package/src/sdk-generator/_getUnionNameBasedOnFirstFoundEnumName.ts +39 -0
  121. package/src/sdk-generator/_pythonModuleToNamespace.ts +27 -0
  122. package/src/sdk-generator/_toQualifiedNodeKey.ts +5 -0
  123. package/src/sdk-generator/comfy-api-json.ts +16 -0
  124. package/src/sdk-generator/comfyui-sdk-codegen.ts +287 -0
  125. package/src/sdk-generator/comfyui-types.ts +56 -0
  126. package/src/sdk-generator/litegraphToApiRequestPayload.ts +157 -0
  127. package/src/ssh-host-manager/ssh-config-manager.ts +89 -0
  128. package/src/ssh-host-manager/ssh-config.windows.md +32 -0
  129. package/src/ssh-host-manager/ssh-manager.ts +114 -0
  130. package/src/state.ts +136 -0
  131. package/src/types/comfy-sdk.ts +106 -0
  132. package/src/types/index.ts +55 -0
  133. package/src/utils/CodeBuffer.ts +61 -0
  134. package/src/utils/ComfyColors.ts +38 -0
  135. package/src/utils/ansi.ts +33 -0
  136. package/src/utils/ansiImage.ts +36 -0
  137. package/src/utils/bang.ts +39 -0
  138. package/src/utils/deepCopyNaive.ts +1 -0
  139. package/src/utils/downloadFile.ts +77 -0
  140. package/src/utils/escapeJSKey.ts +32 -0
  141. package/src/utils/exhaust.ts +4 -0
  142. package/src/utils/extractErrorMessage.ts +11 -0
  143. package/src/utils/fuzzyMatch.ts +8 -0
  144. package/src/utils/githubRegexes.ts +2 -0
  145. package/src/utils/hashArrayBuffer.ts +6 -0
  146. package/src/utils/log.ts +9 -0
  147. package/src/utils/loraTag.ts +10 -0
  148. package/src/utils/mojibake.ts +60 -0
  149. package/src/utils/printArkResultInConsole.ts +16 -0
  150. package/src/utils/softValidate.ts +8 -0
  151. package/src/utils/stringifyReadable.ts +32 -0
  152. package/src/utils/toposort.ts +59 -0
  153. package/src/utils/tryExtracting.ts +41 -0
  154. package/src/utils/writeFile.ts +16 -0
  155. package/src/vars/ComfyVars.ts +531 -0
  156. package/src/vars/DefinedWorkflow.ts +112 -0
  157. package/src/vars/loraKeywords.ts +56 -0
  158. package/dist/index.d.mts +0 -74
  159. package/dist/index.mjs +0 -3
  160. package/dist/index.mjs.map +0 -1
  161. package/readme.md +0 -40
@@ -0,0 +1,173 @@
1
+ import { spawn } from 'node:child_process'
2
+ import { makeAutoObservable, runInAction } from 'mobx'
3
+ import { basename } from 'pathe'
4
+ import type { ExecutionProgress } from 'src/runner/ComfyExecution.ts'
5
+ import { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'
6
+ import type { SeedVar } from 'src/vars/ComfyVars.ts'
7
+ import type { TuiSt } from 'src/cli/tui/state/TuiSt.ts'
8
+
9
+ /** run lifecycle + outputs + status line + clipboard/open actions */
10
+ export class ExecSt {
11
+ constructor(private st: TuiSt) {
12
+ makeAutoObservable<ExecSt, 'st'>(this, { st: false })
13
+ }
14
+
15
+ /** runs we launched that have not finished (the server executes them FIFO) */
16
+ inFlight: number = 0
17
+ progress: ExecutionProgress | null = null
18
+ outputs: string[] = []
19
+ runCount: number = 0
20
+ lastStatus: string | null = null
21
+ error: string | null = null
22
+ /** transient status line (copy feedback, draft changes, …) */
23
+ notice: string | null = null
24
+ /** the prompt currently executing on the server (progress belongs to it) */
25
+ private currentPromptId: string | null = null
26
+
27
+ get running(): boolean {
28
+ return this.inFlight > 0
29
+ }
30
+
31
+ /** workflow switch: wipe run artifacts, keep a hello notice */
32
+ resetForWorkflow(notice: string): void {
33
+ this.outputs = []
34
+ this.error = null
35
+ this.notice = notice
36
+ this.runCount = 0
37
+ this.lastStatus = null
38
+ }
39
+
40
+ /** every run takes THIS path, queued ones included: same progress, outputs, previews */
41
+ async run(): Promise<void> {
42
+ const queued = this.running
43
+ const host = this.st.wf.host
44
+ runInAction(() => {
45
+ this.inFlight++
46
+ this.error = null
47
+ if (queued) {
48
+ this.notice = `queued another run (server queue: ${this.st.queue.remaining + 1})`
49
+ } else {
50
+ this.progress = null
51
+ this.notice = null
52
+ this.currentPromptId = null
53
+ // latents only: the LAST OUTPUT must survive the run start — the
54
+ // 'latent small' / 'last output' preview settings show it while
55
+ // running (full reset belongs to workflow switches)
56
+ this.st.preview.clearLatent()
57
+ // installed while ANY run is in flight, so queued prompts keep painting latents
58
+ host.onLatentPreview = (p) => void this.st.preview.renderLatent(p.bytes)
59
+ }
60
+ })
61
+ try {
62
+ const execution = await this.st.wf.run({
63
+ onProgress: (p) => runInAction(() => this.onProgress(p)),
64
+ })
65
+ runInAction(() => {
66
+ this.outputs = execution.images.map((i) => i.absPath)
67
+ this.lastStatus = execution.status
68
+ this.runCount++
69
+ })
70
+ const lastImage = execution.images[execution.images.length - 1]
71
+ if (lastImage) void this.st.preview.renderOutput(lastImage.absPath)
72
+ } catch (e) {
73
+ runInAction(() => {
74
+ this.error = extractErrorMessage(e)
75
+ })
76
+ } finally {
77
+ runInAction(() => {
78
+ this.inFlight--
79
+ // a queued run is next: blank the bar until its first progress message
80
+ this.progress = null
81
+ this.currentPromptId = null
82
+ this.st.preview.clearLatent()
83
+ if (this.inFlight === 0) host.onLatentPreview = null
84
+ })
85
+ }
86
+ }
87
+
88
+ /** the server runs prompts one at a time: a NEW promptId = the next queued run just started */
89
+ private onProgress(p: ExecutionProgress): void {
90
+ if (p.promptId !== this.currentPromptId) {
91
+ this.currentPromptId = p.promptId
92
+ this.notice = null
93
+ // stale latents from the previous run must not linger over the new one
94
+ this.st.preview.clearLatent()
95
+ }
96
+ this.progress = p
97
+ }
98
+
99
+ randomizeSeedAndRun(): void {
100
+ for (const [, varDef] of this.st.entries) {
101
+ // kind-narrowing cast sanctioned (agent/coding.md)
102
+ if (varDef.kind === 'seed') (varDef as SeedVar).randomize()
103
+ }
104
+ void this.run()
105
+ }
106
+
107
+ /** 'o': real pixels in the OS viewer — the in-terminal ceiling is half-blocks */
108
+ openLastOutput(): void {
109
+ const last = this.outputs[this.outputs.length - 1]
110
+ if (last == null) {
111
+ this.notice = 'no output image yet'
112
+ return
113
+ }
114
+ const cmd = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'start' : 'xdg-open'
115
+ const proc = spawn(cmd, [last], { stdio: 'ignore', detached: true })
116
+ proc.on('error', () => {
117
+ runInAction(() => {
118
+ this.notice = `could not launch ${cmd}`
119
+ })
120
+ })
121
+ proc.unref()
122
+ this.notice = `opened ${basename(last)}`
123
+ }
124
+
125
+ // ---- clipboard ----
126
+ private toClipboard(text: string): Promise<boolean> {
127
+ const [cmd, ...args] =
128
+ process.platform === 'darwin'
129
+ ? ['pbcopy']
130
+ : process.platform === 'win32'
131
+ ? ['clip']
132
+ : ['xclip', '-selection', 'clipboard']
133
+ return new Promise((resolve) => {
134
+ const proc = spawn(cmd ?? 'pbcopy', args, { stdio: ['pipe', 'ignore', 'ignore'] })
135
+ proc.on('error', () => resolve(false))
136
+ proc.on('close', (code) => resolve(code === 0))
137
+ proc.stdin.write(text)
138
+ proc.stdin.end()
139
+ })
140
+ }
141
+
142
+ /** 'c': copy workflow.json (litegraph, drag into the ComfyUI editor) */
143
+ async copyWorkflowJson(): Promise<void> {
144
+ try {
145
+ const wf = await this.st.wf.build()
146
+ const json = await wf.toWorkflowJson()
147
+ const ok = await this.toClipboard(JSON.stringify(json, null, 2))
148
+ runInAction(() => {
149
+ this.notice = ok ? `workflow.json copied (${json.nodes.length} nodes)` : 'clipboard copy failed'
150
+ })
151
+ } catch (e) {
152
+ runInAction(() => {
153
+ this.notice = `${extractErrorMessage(e)}`
154
+ })
155
+ }
156
+ }
157
+
158
+ /** 'C': copy api.json (the POST /prompt payload) */
159
+ async copyApiJson(): Promise<void> {
160
+ try {
161
+ const wf = await this.st.wf.build()
162
+ const json = wf.toApiJson('use_stringified_numbers_only')
163
+ const ok = await this.toClipboard(JSON.stringify(json, null, 2))
164
+ runInAction(() => {
165
+ this.notice = ok ? `api.json copied (${Object.keys(json).length} nodes)` : 'clipboard copy failed'
166
+ })
167
+ } catch (e) {
168
+ runInAction(() => {
169
+ this.notice = `${extractErrorMessage(e)}`
170
+ })
171
+ }
172
+ }
173
+ }
@@ -0,0 +1,230 @@
1
+ import { makeAutoObservable, reaction, runInAction } from 'mobx'
2
+ import { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'
3
+ import type { ComfyHost } from 'src/host/ComfyHost.ts'
4
+ import type { TuiSt } from 'src/cli/tui/state/TuiSt.ts'
5
+
6
+ type HostAction = { key: 'refresh' | 'restart' | 'clear-queue' | 'interrupt'; label: string }
7
+
8
+ export type HostStatus = 'unknown' | 'up' | 'down'
9
+
10
+ const PROBE_EVERY_MS = 5000
11
+ const PROBE_TIMEOUT_MS = 3000
12
+
13
+ const SPIN_FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
14
+
15
+ /** host panel (`h`): stats about the connected host + maintenance actions */
16
+ export class HostSt {
17
+ constructor(private st: TuiSt) {
18
+ makeAutoObservable<HostSt, 'st'>(this, { st: false })
19
+ void this.probeLoop()
20
+ this.st.disposers.push(() => {
21
+ this.disposed = true
22
+ if (this.loopTimer != null) clearTimeout(this.loopTimer)
23
+ if (this.spinTimer != null) clearInterval(this.spinTimer)
24
+ if (this.countdownTimer != null) clearInterval(this.countdownTimer)
25
+ })
26
+ // switching workflows can switch hosts: back to unknown, re-probe now.
27
+ // probeGen++ kills a chain that is mid-await (its loopTimer isn't set yet,
28
+ // clearing timers alone would leave it alive → duplicate chains forever)
29
+ this.st.disposers.push(
30
+ reaction(
31
+ () => this.st.wf,
32
+ () => {
33
+ runInAction(() => {
34
+ this.status = 'unknown'
35
+ this.statusVia = null
36
+ })
37
+ this.probeGen++
38
+ if (this.loopTimer != null) clearTimeout(this.loopTimer)
39
+ if (this.countdownTimer != null) clearInterval(this.countdownTimer)
40
+ void this.probeLoop()
41
+ },
42
+ ),
43
+ )
44
+ }
45
+
46
+ /** live reachability — down is a state, not an error: the dot is the loud surface */
47
+ status: HostStatus = 'unknown'
48
+ /** 'ws' when the live socket is open, 'http' when only the probe reaches the host */
49
+ statusVia: 'ws' | 'http' | null = null
50
+ /** a probe is in flight (drives the spinner while down) */
51
+ probing: boolean = false
52
+ /** seconds until the next probe (shown while down) */
53
+ retryInS: number = 0
54
+ spinFrame: number = 0
55
+
56
+ private disposed = false
57
+ private probeGen = 0
58
+ private loopTimer: NodeJS.Timeout | null = null
59
+ private spinTimer: NodeJS.Timeout | null = null
60
+ private countdownTimer: NodeJS.Timeout | null = null
61
+
62
+ get spinner(): string {
63
+ return SPIN_FRAMES[this.spinFrame % SPIN_FRAMES.length] ?? '⠋'
64
+ }
65
+
66
+ /** probe → schedule the next one (setTimeout chain: the countdown is exact) */
67
+ private async probeLoop(): Promise<void> {
68
+ const gen = this.probeGen
69
+ await this.probe()
70
+ if (this.disposed || gen !== this.probeGen) return
71
+ const nextAt = Date.now() + PROBE_EVERY_MS
72
+ runInAction(() => {
73
+ this.retryInS = Math.ceil(PROBE_EVERY_MS / 1000)
74
+ })
75
+ if (this.countdownTimer != null) clearInterval(this.countdownTimer)
76
+ this.countdownTimer = setInterval(() => {
77
+ runInAction(() => {
78
+ this.retryInS = Math.max(0, Math.ceil((nextAt - Date.now()) / 1000))
79
+ })
80
+ }, 250)
81
+ this.countdownTimer.unref?.()
82
+ this.loopTimer = setTimeout(() => {
83
+ if (this.countdownTimer != null) clearInterval(this.countdownTimer)
84
+ void this.probeLoop()
85
+ }, PROBE_EVERY_MS)
86
+ this.loopTimer.unref?.()
87
+ }
88
+
89
+ /** http is the ground truth: a half-open ws keeps isOpen=true forever, and
90
+ * trusting it would re-create the exact silent-death this dot exists to expose */
91
+ private async probe(): Promise<void> {
92
+ const host = this.host
93
+ runInAction(() => {
94
+ this.probing = true
95
+ })
96
+ // spin interval is LOCAL: an old probe overlapping a reaction-started new
97
+ // one must only clear its own, and only the installed one drives the flag
98
+ const spin = setInterval(() => {
99
+ runInAction(() => {
100
+ this.spinFrame++
101
+ })
102
+ }, 120)
103
+ spin.unref?.()
104
+ this.spinTimer = spin
105
+ let ok = false
106
+ try {
107
+ const res = await fetch(`${host.getServerHostHTTP()}/api/prompt`, {
108
+ signal: AbortSignal.timeout(PROBE_TIMEOUT_MS),
109
+ })
110
+ void res.body?.cancel()
111
+ ok = res.ok
112
+ } catch {
113
+ ok = false
114
+ } finally {
115
+ clearInterval(spin)
116
+ if (this.spinTimer === spin) {
117
+ this.spinTimer = null
118
+ runInAction(() => {
119
+ this.probing = false
120
+ })
121
+ }
122
+ }
123
+ if (this.host !== host) return // workflow switched mid-flight: stale verdict
124
+ runInAction(() => {
125
+ this.status = ok ? 'up' : 'down'
126
+ this.statusVia = ok ? (host.isConnected ? 'ws' : 'http') : null
127
+ })
128
+ }
129
+
130
+ ix: number = 0
131
+ /** action key while one runs (actions are serialized) */
132
+ running: HostAction['key'] | null = null
133
+
134
+ readonly actions: HostAction[] = [
135
+ { key: 'refresh', label: 're-codegen SDK (refetch object_info + reload workflow)' },
136
+ { key: 'restart', label: 'restart ComfyUI (manager reboot)' },
137
+ { key: 'clear-queue', label: 'clear pending queue' },
138
+ { key: 'interrupt', label: 'interrupt current run' },
139
+ ]
140
+
141
+ get host(): ComfyHost {
142
+ return this.st.wf.host
143
+ }
144
+
145
+ get stats(): { label: string; value: string }[] {
146
+ const schema = this.host.schema
147
+ return [
148
+ {
149
+ label: 'status',
150
+ value:
151
+ this.status === 'down'
152
+ ? `down · ${this.probing ? `${this.spinner} probing…` : `retry in ${this.retryInS}s`}`
153
+ : this.status + (this.statusVia != null ? ` (${this.statusVia})` : ''),
154
+ },
155
+ { label: 'node types', value: String(schema.nodes.length) },
156
+ { label: 'loras', value: String(schema.getLoras().length) },
157
+ { label: 'embeddings', value: String(schema.data.embeddings.length) },
158
+ { label: 'queue', value: String(this.st.queue.remaining) },
159
+ { label: 'ws', value: this.host.getWSUrl() },
160
+ ]
161
+ }
162
+
163
+ begin(): void {
164
+ this.st.mode = 'host'
165
+ this.ix = 0
166
+ }
167
+
168
+ blur(): void {
169
+ this.st.mode = 'nav'
170
+ }
171
+
172
+ move(delta: number): void {
173
+ const len = this.actions.length
174
+ this.ix = (this.ix + delta + len) % len
175
+ }
176
+
177
+ async commit(): Promise<void> {
178
+ const action = this.actions[this.ix]
179
+ if (action == null || this.running != null) return
180
+ if (action.key === 'refresh') return this.refreshSdk()
181
+ if (action.key === 'restart') return this.restartComfy()
182
+ if (action.key === 'clear-queue') return this.st.queue.clearPending()
183
+ return this.st.queue.interrupt()
184
+ }
185
+
186
+ /** refetch object_info, regen the sdk, then cache-busted reload of the current
187
+ * module so dynamic var options (v.loras…) see the new values */
188
+ private async refreshSdk(): Promise<void> {
189
+ runInAction(() => {
190
+ this.running = 'refresh'
191
+ })
192
+ try {
193
+ await this.host.fetchAndUpdateSchema()
194
+ await this.st.workflows.reload(this.st.drafts.active ?? 'default')
195
+ runInAction(() => {
196
+ const schema = this.host.schema
197
+ this.st.exec.notice = `SDK regenerated: ${schema.nodes.length} node types, ${schema.getLoras().length} loras`
198
+ })
199
+ } catch (e) {
200
+ runInAction(() => {
201
+ this.st.exec.error = extractErrorMessage(e)
202
+ })
203
+ } finally {
204
+ runInAction(() => {
205
+ this.running = null
206
+ })
207
+ }
208
+ }
209
+
210
+ private async restartComfy(): Promise<void> {
211
+ runInAction(() => {
212
+ this.running = 'restart'
213
+ })
214
+ try {
215
+ await this.host.manager.restartComfyUI()
216
+ runInAction(() => {
217
+ this.st.exec.notice = 'reboot requested — the ws reconnects when the host is back'
218
+ })
219
+ } catch (e) {
220
+ // the server dropping the connection mid-reboot IS the expected shape
221
+ runInAction(() => {
222
+ this.st.exec.notice = `reboot requested (${extractErrorMessage(e)}) — the ws reconnects when the host is back`
223
+ })
224
+ } finally {
225
+ runInAction(() => {
226
+ this.running = null
227
+ })
228
+ }
229
+ }
230
+ }
@@ -0,0 +1,107 @@
1
+ import { makeAutoObservable, runInAction } from 'mobx'
2
+ import { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'
3
+ import { stripAnsi } from 'src/utils/ansi.ts'
4
+ import { repairMojibake } from 'src/utils/mojibake.ts'
5
+ import type { LogEntry } from 'src/runner/ComfyWsApi.ts'
6
+ import type { ComfyHost } from 'src/host/ComfyHost.ts'
7
+ import type { TuiSt } from 'src/cli/tui/state/TuiSt.ts'
8
+
9
+ const MAX_LINES = 400
10
+
11
+ /** fold write chunks into p.lines (mutated), returns the new partial tail.
12
+ * `\n` commits a line, `\r` resets the partial (tqdm redraws collapse to
13
+ * their last state), ANSI stripped, blank lines dropped. */
14
+ export function assembleLogChunks(p: { lines: string[]; partial: string; entries: LogEntry[] }): string {
15
+ let partial = p.partial
16
+ for (const entry of p.entries) {
17
+ for (const piece of stripAnsi(repairMojibake(entry.m)).split(/(\r\n|\n|\r)/)) {
18
+ if (piece === '\n' || piece === '\r\n') {
19
+ if (partial.trim() !== '') p.lines.push(partial)
20
+ partial = ''
21
+ } else if (piece === '\r') {
22
+ partial = ''
23
+ } else if (piece !== '') {
24
+ partial += piece
25
+ }
26
+ }
27
+ }
28
+ return partial
29
+ }
30
+
31
+ /** server console mirror: /internal/logs/raw backfill + ws 'logs' stream.
32
+ * Entries are write CHUNKS, not lines — assembled here (`\n` commits,
33
+ * `\r` resets the partial, so tqdm redraws collapse to their last state). */
34
+ export class LogsSt {
35
+ constructor(private st: TuiSt) {
36
+ makeAutoObservable<LogsSt, 'st'>(this, { st: false })
37
+ this.attach(this.st.wf.host)
38
+ this.st.disposers.push(() => {
39
+ if (this.attached != null) {
40
+ this.attached.onLogs = null
41
+ this.attached.onSession = null
42
+ }
43
+ })
44
+ }
45
+
46
+ lines: string[] = []
47
+ /** chunk tail not yet closed by \n — rendered live (tqdm progress) */
48
+ partial: string = ''
49
+
50
+ private attached: ComfyHost | null = null
51
+
52
+ /** follow the CURRENT workflow's host (re-called on workflow switch) */
53
+ attach(host: ComfyHost): void {
54
+ if (this.attached === host) return
55
+ if (this.attached != null) {
56
+ this.attached.onLogs = null
57
+ this.attached.onSession = null
58
+ // best-effort: switched-away hosts stay connected (loadedHosts), so
59
+ // without this their ws keeps carrying chunks nobody reads; the
60
+ // server drops the sub on disconnect anyway, hence the swallowed error
61
+ if (this.attached.isConnected && this.attached.comfySessionId !== 'temp') {
62
+ void this.attached.subscribeLogs({ enabled: false, clientId: this.attached.comfySessionId }).catch(() => {})
63
+ }
64
+ }
65
+ this.attached = host
66
+ this.lines = []
67
+ this.partial = ''
68
+ host.onLogs = (p) => this.feed(p.entries)
69
+ // per-sid server state: every (re)connect needs a fresh subscribe
70
+ host.onSession = (sid) => void this.hydrate(host, sid)
71
+ if (host.isConnected && host.comfySessionId !== 'temp') void this.hydrate(host, host.comfySessionId)
72
+ }
73
+
74
+ /** backfill BEFORE subscribe: entries emitted in the gap are lost, which is
75
+ * the right trade — the reverse order would clobber streamed entries at the
76
+ * reset, and the backfill re-covers the recent past anyway */
77
+ private async hydrate(host: ComfyHost, sid: string): Promise<void> {
78
+ try {
79
+ const raw = await host.fetchRawLogs()
80
+ // attach() switched hosts or the sid rolled again mid-fetch: stale snapshot
81
+ if (this.attached !== host || host.comfySessionId !== sid) return
82
+ runInAction(() => {
83
+ this.lines = []
84
+ this.partial = ''
85
+ })
86
+ this.feed(raw.entries)
87
+ await host.subscribeLogs({ enabled: true, clientId: sid })
88
+ } catch (e) {
89
+ if (this.attached !== host) return
90
+ // the panel is the loud surface: stream failures land as a log line
91
+ this.feed([{ t: '', m: `[comfy-ts] server log stream unavailable: ${extractErrorMessage(e)}\n` }])
92
+ }
93
+ }
94
+
95
+ feed(entries: LogEntry[]): void {
96
+ runInAction(() => {
97
+ this.partial = assembleLogChunks({ lines: this.lines, partial: this.partial, entries })
98
+ if (this.lines.length > MAX_LINES) this.lines.splice(0, this.lines.length - MAX_LINES)
99
+ })
100
+ }
101
+
102
+ /** last rows to render, live partial included */
103
+ tail(n: number): string[] {
104
+ const rows = this.partial.trim() !== '' ? [...this.lines, this.partial] : this.lines
105
+ return rows.slice(-n)
106
+ }
107
+ }
@@ -0,0 +1,185 @@
1
+ import { makeAutoObservable, reaction, runInAction } from 'mobx'
2
+ import { fetchLoraPreviewBytes, fetchLoraPreviewMap, loraPreviewKey } from 'src/host/loraManagerApi.ts'
3
+ import { imageBufferToAnsi } from 'src/utils/ansiImage.ts'
4
+ import { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'
5
+ import { fuzzyMatch } from 'src/utils/fuzzyMatch.ts'
6
+ import { LorasVar } from 'src/vars/ComfyVars.ts'
7
+ import { getLoraKeyword, setLoraKeyword } from 'src/vars/loraKeywords.ts'
8
+ import type { TuiSt } from 'src/cli/tui/state/TuiSt.ts'
9
+
10
+ /** loras overlay: fuzzy filter + tick/untick + strengths + bulk ops + lora-manager preview */
11
+ export class LorasSt {
12
+ constructor(private st: TuiSt) {
13
+ makeAutoObservable<LorasSt, 'st'>(this, { st: false })
14
+ // the selected lora's preview follows the cursor (debounced; renders into the preview panel)
15
+ this.st.disposers.push(
16
+ reaction(
17
+ () => (this.st.mode === 'overlay-loras' ? this.selectedName : null),
18
+ () => void this.refreshPreview(),
19
+ { delay: 120 },
20
+ ),
21
+ )
22
+ }
23
+
24
+ ix: number = 0
25
+ filter: string = ''
26
+
27
+ /** kind-narrowing cast sanctioned (agent/coding.md), `kind` is the tag */
28
+ get selectedVar(): LorasVar<string> | null {
29
+ const sel = this.st.selected?.[1]
30
+ return sel?.kind === 'loras' ? (sel as LorasVar<string>) : null
31
+ }
32
+
33
+ /** options surviving the fuzzy filter (bulk ops apply to exactly these) */
34
+ get filteredNames(): string[] {
35
+ const lv = this.selectedVar
36
+ if (lv == null) return []
37
+ if (this.filter === '') return lv.names
38
+ return lv.names.filter((n) => fuzzyMatch(this.filter, n))
39
+ }
40
+
41
+ begin(): void {
42
+ if (this.selectedVar == null) return
43
+ this.st.mode = 'overlay-loras'
44
+ this.ix = 0
45
+ this.filter = ''
46
+ }
47
+
48
+ move(delta: number): void {
49
+ const len = this.filteredNames.length
50
+ if (len === 0) return
51
+ this.ix = (this.ix + delta + len) % len
52
+ }
53
+
54
+ filterInput(chunk: string): void {
55
+ this.filter += chunk
56
+ this.ix = 0
57
+ }
58
+
59
+ filterBackspace(): void {
60
+ this.filter = this.filter.slice(0, -1)
61
+ this.ix = 0
62
+ }
63
+
64
+ /** ⌥⌫ / ⌃W: drop the last word of the filter */
65
+ filterDeleteWord(): void {
66
+ this.filter = this.filter.replace(/\s*\S+\s*$/, '')
67
+ this.ix = 0
68
+ }
69
+
70
+ toggle(): void {
71
+ const lv = this.selectedVar
72
+ const name = this.filteredNames[this.ix]
73
+ if (lv == null || name == null) return
74
+ lv.toggleItem(name)
75
+ }
76
+
77
+ /** ⌃A / ⌃N: tick / untick every lora surviving the filter */
78
+ setAll(on: boolean): void {
79
+ this.selectedVar?.setAll(on, this.filteredNames)
80
+ }
81
+
82
+ adjust(delta: number): void {
83
+ const lv = this.selectedVar
84
+ const name = this.filteredNames[this.ix]
85
+ if (lv == null || name == null) return
86
+ lv.adjustItem(name, delta)
87
+ }
88
+
89
+ /** ⌃K: assign the selected lora's trigger keyword (PromptVar prefixes actives with it) */
90
+ beginKeyword(): void {
91
+ const name = this.selectedName
92
+ if (name == null) return
93
+ this.st.editor.beginCustom({
94
+ title: `keyword for ${LorasVar.shortName(name)} (empty clears)`,
95
+ initial: getLoraKeyword(name),
96
+ onCommit: (raw) => {
97
+ setLoraKeyword(name, raw)
98
+ return true
99
+ },
100
+ returnMode: 'overlay-loras',
101
+ })
102
+ }
103
+
104
+ // ---- lora-manager previews (optional extension, quiet degrade) ----
105
+ get selectedName(): string | null {
106
+ return this.filteredNames[this.ix] ?? null
107
+ }
108
+
109
+ previewAnsi: string | null = null
110
+ /** protocol mode: raw preview bytes for the overlay painter */
111
+ previewBytes: Uint8Array | null = null
112
+ previewName: string | null = null
113
+ /** placeholder line when no image can be shown (missing extension, no preview, video preview…) */
114
+ previewNote: string | null = null
115
+
116
+ /** undefined = not fetched yet · null = extension absent */
117
+ private previewMap: Map<string, string> | null | undefined = undefined
118
+ private previewMapHostId: string | null = null
119
+ private _busy: boolean = false
120
+
121
+ async refreshPreview(): Promise<void> {
122
+ if (this.st.mode !== 'overlay-loras') {
123
+ runInAction(() => {
124
+ this.previewAnsi = null
125
+ this.previewBytes = null
126
+ this.previewName = null
127
+ this.previewNote = null
128
+ })
129
+ return
130
+ }
131
+ const name = this.selectedName
132
+ if (name == null || this._busy) return
133
+ this._busy = true
134
+ try {
135
+ const host = this.st.wf.host
136
+ if (this.previewMap === undefined || this.previewMapHostId !== host.data.id) {
137
+ this.previewMap = await fetchLoraPreviewMap(host)
138
+ this.previewMapHostId = host.data.id
139
+ }
140
+ const map = this.previewMap
141
+ const url = map?.get(loraPreviewKey(name))
142
+ const note = map == null ? 'lora-manager extension not detected' : url == null ? 'no preview available' : null
143
+ if (url == null) {
144
+ runInAction(() => {
145
+ this.previewAnsi = null
146
+ this.previewBytes = null
147
+ this.previewName = name
148
+ this.previewNote = note
149
+ })
150
+ return
151
+ }
152
+ const bytes = await fetchLoraPreviewBytes(host, url)
153
+ // null covers the SPA index.html fallback (non-image response) too
154
+ if (bytes == null) throw new Error('no image preview on the server')
155
+ if (this.st.preview.useNative) {
156
+ // the overlay painter shows the REAL image — no ansi rendering needed
157
+ runInAction(() => {
158
+ this.previewBytes = bytes
159
+ this.previewAnsi = null
160
+ this.previewName = name
161
+ this.previewNote = null
162
+ })
163
+ return
164
+ }
165
+ const ansi = await imageBufferToAnsi(bytes, { width: this.st.preview.width, height: this.st.preview.height })
166
+ runInAction(() => {
167
+ this.previewAnsi = ansi
168
+ this.previewName = name
169
+ this.previewNote = null
170
+ })
171
+ } catch (e) {
172
+ // e.g. video previews sharp can't decode — placeholder, not an incident
173
+ runInAction(() => {
174
+ this.previewAnsi = null
175
+ this.previewBytes = null
176
+ this.previewName = name
177
+ this.previewNote = extractErrorMessage(e)
178
+ })
179
+ } finally {
180
+ this._busy = false
181
+ // the cursor may have moved while we rendered: catch up once
182
+ if (this.st.mode === 'overlay-loras' && this.selectedName !== name) void this.refreshPreview()
183
+ }
184
+ }
185
+ }