comfy-ts 2.24.0 → 2.25.1

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 (321) hide show
  1. package/dist/chunk-6mgjbrp6.js +579 -0
  2. package/dist/chunk-6mgjbrp6.js.map +17 -0
  3. package/dist/chunk-6tsg7fm5.js +1876 -0
  4. package/dist/chunk-6tsg7fm5.js.map +31 -0
  5. package/dist/chunk-dvxjvwe7.js +2593 -0
  6. package/dist/chunk-dvxjvwe7.js.map +29 -0
  7. package/dist/chunk-dw0t1nye.js +457 -0
  8. package/dist/chunk-dw0t1nye.js.map +16 -0
  9. package/dist/chunk-he70ewwx.js +444 -0
  10. package/dist/chunk-he70ewwx.js.map +13 -0
  11. package/dist/chunk-n22qz0j1.js +6663 -0
  12. package/dist/chunk-n22qz0j1.js.map +95 -0
  13. package/dist/chunk-n35nffm8.js +4777 -0
  14. package/dist/chunk-n35nffm8.js.map +51 -0
  15. package/dist/cli/serve/hostProtocol.d.cts +74 -0
  16. package/dist/cli/serve/hostProtocol.d.ts +74 -0
  17. package/dist/cli/tui-env.d.cts +2 -0
  18. package/dist/cli/tui-env.d.ts +2 -0
  19. package/dist/cli.js +494 -485
  20. package/dist/cli.js.map +16 -1
  21. package/dist/coreExports.d.cts +45 -0
  22. package/dist/coreExports.d.ts +45 -0
  23. package/dist/errors/InvalidPromptError.d.cts +10 -0
  24. package/dist/errors/InvalidPromptError.d.ts +10 -0
  25. package/dist/exampleAssets.d.cts +24 -0
  26. package/dist/exampleAssets.d.ts +24 -0
  27. package/dist/graph/ComfyNode.d.cts +109 -0
  28. package/dist/graph/ComfyNode.d.ts +109 -0
  29. package/dist/graph/ComfyNodeID.d.cts +15 -0
  30. package/dist/graph/ComfyNodeID.d.ts +15 -0
  31. package/dist/graph/ComfyNodeOutput.d.cts +21 -0
  32. package/dist/graph/ComfyNodeOutput.d.ts +21 -0
  33. package/dist/graph/NodeSlotSize.d.cts +4 -0
  34. package/dist/graph/NodeSlotSize.d.ts +4 -0
  35. package/dist/graph/autoValue.d.cts +16 -0
  36. package/dist/graph/autoValue.d.ts +16 -0
  37. package/dist/host/ComfyHost.d.cts +383 -0
  38. package/dist/host/ComfyHost.d.ts +383 -0
  39. package/dist/host/ComfyInstallType.d.cts +11 -0
  40. package/dist/host/ComfyInstallType.d.ts +11 -0
  41. package/dist/host/ComfyManager.d.cts +152 -0
  42. package/dist/host/ComfyManager.d.ts +152 -0
  43. package/dist/host/ComfyUploader.d.cts +42 -0
  44. package/dist/host/ComfyUploader.d.ts +42 -0
  45. package/dist/host/ComfyWorkflowBuilder.d.cts +19 -0
  46. package/dist/host/ComfyWorkflowBuilder.d.ts +19 -0
  47. package/dist/host/Requirements.d.cts +43 -0
  48. package/dist/host/Requirements.d.ts +43 -0
  49. package/dist/host/ResilientWebsocket.d.cts +122 -0
  50. package/dist/host/ResilientWebsocket.d.ts +122 -0
  51. package/dist/host/hostFile.d.cts +23 -0
  52. package/dist/host/hostFile.d.ts +23 -0
  53. package/dist/host/hostUrl.d.cts +22 -0
  54. package/dist/host/hostUrl.d.ts +22 -0
  55. package/dist/host/leastBusy.d.cts +9 -0
  56. package/dist/host/leastBusy.d.ts +9 -0
  57. package/dist/host/loraInfoCache.d.cts +110 -0
  58. package/dist/host/loraInfoCache.d.ts +110 -0
  59. package/dist/host/loraManagerApi.d.cts +106 -0
  60. package/dist/host/loraManagerApi.d.ts +106 -0
  61. package/dist/host/previewMethod.d.cts +5 -0
  62. package/dist/host/previewMethod.d.ts +5 -0
  63. package/dist/host/schemaDrift.d.cts +54 -0
  64. package/dist/host/schemaDrift.d.ts +54 -0
  65. package/dist/image-utils/_getPngMetadata.d.cts +5 -0
  66. package/dist/image-utils/_getPngMetadata.d.ts +5 -0
  67. package/dist/index.cjs +8197 -8509
  68. package/dist/index.cjs.map +124 -1
  69. package/dist/index.d.cts +4 -19116
  70. package/dist/index.d.ts +4 -19116
  71. package/dist/index.js +8129 -8390
  72. package/dist/index.js.map +124 -1
  73. package/dist/litegraph/CanonicalWorkflow.d.cts +75 -0
  74. package/dist/litegraph/CanonicalWorkflow.d.ts +75 -0
  75. package/dist/litegraph/LiteGraphGroup.d.cts +17 -0
  76. package/dist/litegraph/LiteGraphGroup.d.ts +17 -0
  77. package/dist/litegraph/LiteGraphJSON.d.cts +242 -0
  78. package/dist/litegraph/LiteGraphJSON.d.ts +242 -0
  79. package/dist/litegraph/LiteGraphLink.d.cts +48 -0
  80. package/dist/litegraph/LiteGraphLink.d.ts +48 -0
  81. package/dist/litegraph/LiteGraphLinkID.d.cts +6 -0
  82. package/dist/litegraph/LiteGraphLinkID.d.ts +6 -0
  83. package/dist/litegraph/LiteGraphNode.d.cts +76 -0
  84. package/dist/litegraph/LiteGraphNode.d.ts +76 -0
  85. package/dist/litegraph/LiteGraphNodeInput.d.cts +25 -0
  86. package/dist/litegraph/LiteGraphNodeInput.d.ts +25 -0
  87. package/dist/litegraph/LiteGraphNodeOutput.d.cts +20 -0
  88. package/dist/litegraph/LiteGraphNodeOutput.d.ts +20 -0
  89. package/dist/litegraph/LiteGraphSlotIndex.d.cts +6 -0
  90. package/dist/litegraph/LiteGraphSlotIndex.d.ts +6 -0
  91. package/dist/litegraph/LiteGraphSubgraphDef.d.cts +174 -0
  92. package/dist/litegraph/LiteGraphSubgraphDef.d.ts +174 -0
  93. package/dist/litegraph/convertFlowToLiteGraphJSON.d.cts +12 -0
  94. package/dist/litegraph/convertFlowToLiteGraphJSON.d.ts +12 -0
  95. package/dist/litegraph/expandSubgraphs.d.cts +27 -0
  96. package/dist/litegraph/expandSubgraphs.d.ts +27 -0
  97. package/dist/litegraph/normalizeWorkflow.d.cts +21 -0
  98. package/dist/litegraph/normalizeWorkflow.d.ts +21 -0
  99. package/dist/manager/ComfyRegistry.d.cts +54 -0
  100. package/dist/manager/ComfyRegistry.d.ts +54 -0
  101. package/dist/manager/generated/KnownComfyCustomNodeName.d.cts +1 -0
  102. package/dist/manager/generated/KnownComfyCustomNodeName.d.ts +1 -0
  103. package/dist/manager/generated/KnownComfyPluginTitle.d.cts +12109 -0
  104. package/dist/manager/generated/KnownComfyPluginTitle.d.ts +12109 -0
  105. package/dist/manager/generated/KnownComfyPluginURL.d.cts +1 -0
  106. package/dist/manager/generated/KnownComfyPluginURL.d.ts +1 -0
  107. package/dist/manager/generated/KnownModel_Base.d.cts +2 -0
  108. package/dist/manager/generated/KnownModel_Base.d.ts +2 -0
  109. package/dist/manager/generated/KnownModel_Name.d.cts +2842 -0
  110. package/dist/manager/generated/KnownModel_Name.d.ts +2842 -0
  111. package/dist/manager/generated/KnownModel_SavePath.d.cts +2 -0
  112. package/dist/manager/generated/KnownModel_SavePath.d.ts +2 -0
  113. package/dist/manager/generated/KnownModel_Type.d.cts +2 -0
  114. package/dist/manager/generated/KnownModel_Type.d.ts +2 -0
  115. package/dist/manager/installedView.d.cts +65 -0
  116. package/dist/manager/installedView.d.ts +65 -0
  117. package/dist/manager/json/custom-node-list.extra.d.cts +2 -0
  118. package/dist/manager/json/custom-node-list.extra.d.ts +2 -0
  119. package/dist/manager/json/model-list.extra.d.cts +2 -0
  120. package/dist/manager/json/model-list.extra.d.ts +2 -0
  121. package/dist/manager/loaders/parseReport.d.cts +24 -0
  122. package/dist/manager/loaders/parseReport.d.ts +24 -0
  123. package/dist/manager/loaders/step1_downloadComfyManagerJSONs.d.cts +1 -0
  124. package/dist/manager/loaders/step1_downloadComfyManagerJSONs.d.ts +1 -0
  125. package/dist/manager/loaders/step2_custom-node-list-loader.d.cts +2 -0
  126. package/dist/manager/loaders/step2_custom-node-list-loader.d.ts +2 -0
  127. package/dist/manager/loaders/step3_extension-node-map-loader.d.cts +2 -0
  128. package/dist/manager/loaders/step3_extension-node-map-loader.d.ts +2 -0
  129. package/dist/manager/loaders/step4_model-list-loader.d.cts +2 -0
  130. package/dist/manager/loaders/step4_model-list-loader.d.ts +2 -0
  131. package/dist/manager/loaders/step5_alter-list-loader.d.cts +2 -0
  132. package/dist/manager/loaders/step5_alter-list-loader.d.ts +2 -0
  133. package/dist/manager/loaders/step6_github-stats-loader.d.cts +2 -0
  134. package/dist/manager/loaders/step6_github-stats-loader.d.ts +2 -0
  135. package/dist/manager/types/ComfyManagerAPIFetchPolicy.d.cts +7 -0
  136. package/dist/manager/types/ComfyManagerAPIFetchPolicy.d.ts +7 -0
  137. package/dist/manager/types/ComfyManagerAPIModelList.d.cts +10 -0
  138. package/dist/manager/types/ComfyManagerAPIModelList.d.ts +10 -0
  139. package/dist/manager/types/ComfyManagerAPIPluginList.d.cts +33 -0
  140. package/dist/manager/types/ComfyManagerAPIPluginList.d.ts +33 -0
  141. package/dist/manager/types/ComfyManagerAlterInfo.d.cts +12 -0
  142. package/dist/manager/types/ComfyManagerAlterInfo.d.ts +12 -0
  143. package/dist/manager/types/ComfyManagerFileModelInfo.d.cts +10 -0
  144. package/dist/manager/types/ComfyManagerFileModelInfo.d.ts +10 -0
  145. package/dist/manager/types/ComfyManagerFilePluginContent.d.cts +11 -0
  146. package/dist/manager/types/ComfyManagerFilePluginContent.d.ts +11 -0
  147. package/dist/manager/types/ComfyManagerFilePluginList.d.cts +5 -0
  148. package/dist/manager/types/ComfyManagerFilePluginList.d.ts +5 -0
  149. package/dist/manager/types/ComfyManagerGithubStats.d.cts +7 -0
  150. package/dist/manager/types/ComfyManagerGithubStats.d.ts +7 -0
  151. package/dist/manager/types/ComfyManagerModelInfo.d.cts +12 -0
  152. package/dist/manager/types/ComfyManagerModelInfo.d.ts +12 -0
  153. package/dist/manager/types/ComfyManagerPluginContentMetadata.d.cts +10 -0
  154. package/dist/manager/types/ComfyManagerPluginContentMetadata.d.ts +10 -0
  155. package/dist/manager/types/ComfyManagerPluginEnums.d.cts +5 -0
  156. package/dist/manager/types/ComfyManagerPluginEnums.d.ts +5 -0
  157. package/dist/manager/types/ComfyManagerPluginInfo.d.cts +54 -0
  158. package/dist/manager/types/ComfyManagerPluginInfo.d.ts +54 -0
  159. package/dist/promptEnhancers.d.cts +22 -0
  160. package/dist/promptEnhancers.d.ts +22 -0
  161. package/dist/runner/ComfyExecution.d.cts +230 -0
  162. package/dist/runner/ComfyExecution.d.ts +230 -0
  163. package/dist/runner/ComfyExecutionStatus.d.cts +1 -0
  164. package/dist/runner/ComfyExecutionStatus.d.ts +1 -0
  165. package/dist/runner/ComfyWorkflow.d.cts +141 -0
  166. package/dist/runner/ComfyWorkflow.d.ts +141 -0
  167. package/dist/runner/ComfyWorkflowLayout.d.cts +17 -0
  168. package/dist/runner/ComfyWorkflowLayout.d.ts +17 -0
  169. package/dist/runner/ComfyWsApi.d.cts +2174 -0
  170. package/dist/runner/ComfyWsApi.d.ts +2174 -0
  171. package/dist/runner/MediaImage.d.cts +127 -0
  172. package/dist/runner/MediaImage.d.ts +127 -0
  173. package/dist/runner/comfyOrgApiKey.d.cts +21 -0
  174. package/dist/runner/comfyOrgApiKey.d.ts +21 -0
  175. package/dist/runner/describePromptRejection.d.cts +1 -0
  176. package/dist/runner/describePromptRejection.d.ts +1 -0
  177. package/dist/runner/ephemeral.d.cts +10 -0
  178. package/dist/runner/ephemeral.d.ts +10 -0
  179. package/dist/runner/historyReplay.d.cts +13 -0
  180. package/dist/runner/historyReplay.d.ts +13 -0
  181. package/dist/runner/mediaKinds.d.cts +7 -0
  182. package/dist/runner/mediaKinds.d.ts +7 -0
  183. package/dist/runner/outputPath.d.cts +40 -0
  184. package/dist/runner/outputPath.d.ts +40 -0
  185. package/dist/runner/outputs3d.d.cts +3 -0
  186. package/dist/runner/outputs3d.d.ts +3 -0
  187. package/dist/runner/wsBinaryFrame.d.cts +25 -0
  188. package/dist/runner/wsBinaryFrame.d.ts +25 -0
  189. package/dist/sdk-generator/ComfyNodeSchema.d.cts +25 -0
  190. package/dist/sdk-generator/ComfyNodeSchema.d.ts +25 -0
  191. package/dist/sdk-generator/ComfySchema.d.cts +74 -0
  192. package/dist/sdk-generator/ComfySchema.d.ts +74 -0
  193. package/dist/sdk-generator/ComfyUIObjectInfoTypes.d.cts +3072 -0
  194. package/dist/sdk-generator/ComfyUIObjectInfoTypes.d.ts +3072 -0
  195. package/dist/sdk-generator/Primitives.d.cts +12 -0
  196. package/dist/sdk-generator/Primitives.d.ts +12 -0
  197. package/dist/sdk-generator/_getUnionNameBasedOnFirstFoundEnumName.d.cts +2 -0
  198. package/dist/sdk-generator/_getUnionNameBasedOnFirstFoundEnumName.d.ts +2 -0
  199. package/dist/sdk-generator/_pythonModuleToNamespace.d.cts +1 -0
  200. package/dist/sdk-generator/_pythonModuleToNamespace.d.ts +1 -0
  201. package/dist/sdk-generator/_toQualifiedNodeKey.d.cts +1 -0
  202. package/dist/sdk-generator/_toQualifiedNodeKey.d.ts +1 -0
  203. package/dist/sdk-generator/comfy-api-json.d.cts +16 -0
  204. package/dist/sdk-generator/comfy-api-json.d.ts +16 -0
  205. package/dist/sdk-generator/comfyui-sdk-codegen.d.cts +23 -0
  206. package/dist/sdk-generator/comfyui-sdk-codegen.d.ts +23 -0
  207. package/dist/sdk-generator/comfyui-types.d.cts +55 -0
  208. package/dist/sdk-generator/comfyui-types.d.ts +55 -0
  209. package/dist/sdk-generator/inputWidgetKind.d.cts +80 -0
  210. package/dist/sdk-generator/inputWidgetKind.d.ts +80 -0
  211. package/dist/sdk-generator/litegraphToApiRequestPayload.d.cts +41 -0
  212. package/dist/sdk-generator/litegraphToApiRequestPayload.d.ts +41 -0
  213. package/dist/serve-web.js +51 -51
  214. package/dist/ssh-host-manager/ssh-config-manager.d.cts +17 -0
  215. package/dist/ssh-host-manager/ssh-config-manager.d.ts +17 -0
  216. package/dist/state.d.cts +80 -0
  217. package/dist/state.d.ts +80 -0
  218. package/dist/storage/ComfyStorage.d.cts +55 -0
  219. package/dist/storage/ComfyStorage.d.ts +55 -0
  220. package/dist/storage/nodeStorage.d.cts +2 -0
  221. package/dist/storage/nodeStorage.d.ts +2 -0
  222. package/dist/types/comfy-sdk.d.cts +85 -0
  223. package/dist/types/comfy-sdk.d.ts +85 -0
  224. package/dist/types/index.d.cts +65 -0
  225. package/dist/types/index.d.ts +65 -0
  226. package/dist/utils/CodeBuffer.d.cts +20 -0
  227. package/dist/utils/CodeBuffer.d.ts +20 -0
  228. package/dist/utils/ComfyColors.d.cts +14 -0
  229. package/dist/utils/ComfyColors.d.ts +14 -0
  230. package/dist/utils/ansi.d.cts +22 -0
  231. package/dist/utils/ansi.d.ts +22 -0
  232. package/dist/utils/bang.d.cts +9 -0
  233. package/dist/utils/bang.d.ts +9 -0
  234. package/dist/utils/deepCopyNaive.d.cts +1 -0
  235. package/dist/utils/deepCopyNaive.d.ts +1 -0
  236. package/dist/utils/downloadFile.d.cts +2 -0
  237. package/dist/utils/downloadFile.d.ts +2 -0
  238. package/dist/utils/escapeJSKey.d.cts +2 -0
  239. package/dist/utils/escapeJSKey.d.ts +2 -0
  240. package/dist/utils/exhaust.d.cts +1 -0
  241. package/dist/utils/exhaust.d.ts +1 -0
  242. package/dist/utils/extractErrorMessage.d.cts +2 -0
  243. package/dist/utils/extractErrorMessage.d.ts +2 -0
  244. package/dist/utils/githubRegexes.d.cts +2 -0
  245. package/dist/utils/githubRegexes.d.ts +2 -0
  246. package/dist/utils/hashArrayBuffer.d.cts +1 -0
  247. package/dist/utils/hashArrayBuffer.d.ts +1 -0
  248. package/dist/utils/isRecord.d.cts +2 -0
  249. package/dist/utils/isRecord.d.ts +2 -0
  250. package/dist/utils/lazySharp.d.cts +3 -0
  251. package/dist/utils/lazySharp.d.ts +3 -0
  252. package/dist/utils/log.d.cts +4 -0
  253. package/dist/utils/log.d.ts +4 -0
  254. package/dist/utils/loraTag.d.cts +8 -0
  255. package/dist/utils/loraTag.d.ts +8 -0
  256. package/dist/utils/matchesRegex.d.cts +2 -0
  257. package/dist/utils/matchesRegex.d.ts +2 -0
  258. package/dist/utils/printArkResultInConsole.d.cts +2 -0
  259. package/dist/utils/printArkResultInConsole.d.ts +2 -0
  260. package/dist/utils/safeName.d.cts +6 -0
  261. package/dist/utils/safeName.d.ts +6 -0
  262. package/dist/utils/sha1.d.cts +2 -0
  263. package/dist/utils/sha1.d.ts +2 -0
  264. package/dist/utils/softValidate.d.cts +2 -0
  265. package/dist/utils/softValidate.d.ts +2 -0
  266. package/dist/utils/stringifyReadable.d.cts +1 -0
  267. package/dist/utils/stringifyReadable.d.ts +1 -0
  268. package/dist/utils/toposort.d.cts +3 -0
  269. package/dist/utils/toposort.d.ts +3 -0
  270. package/dist/vars/ComfyVars.d.cts +607 -0
  271. package/dist/vars/ComfyVars.d.ts +607 -0
  272. package/dist/vars/DefinedWorkflow.d.cts +104 -0
  273. package/dist/vars/DefinedWorkflow.d.ts +104 -0
  274. package/dist/vars/lanes.d.cts +81 -0
  275. package/dist/vars/lanes.d.ts +81 -0
  276. package/dist/vars/loraEntry.d.cts +26 -0
  277. package/dist/vars/loraEntry.d.ts +26 -0
  278. package/dist/vars/loraKeywords.d.cts +19 -0
  279. package/dist/vars/loraKeywords.d.ts +19 -0
  280. package/dist/vars/outputWidgets.d.cts +33 -0
  281. package/dist/vars/outputWidgets.d.ts +33 -0
  282. package/dist/vars/presets.d.cts +9 -0
  283. package/dist/vars/presets.d.ts +9 -0
  284. package/dist/vars/promptSyntax.d.cts +98 -0
  285. package/dist/vars/promptSyntax.d.ts +98 -0
  286. package/dist/web.d.cts +2 -0
  287. package/dist/web.d.ts +2 -19160
  288. package/dist/web.js +8040 -8292
  289. package/dist/web.js.map +119 -1
  290. package/examples/depth-explorer/web/tsconfig.json +1 -2
  291. package/examples/upscale-explorer/web/tsconfig.json +1 -2
  292. package/examples/web/tsconfig.json +1 -4
  293. package/examples/world-explorer/web/tsconfig.json +1 -2
  294. package/package.json +27 -32
  295. package/src/cli/serve/web/components/SideMenu.tsx +1 -1
  296. package/src/cli/serve/web/components/controls/LorasControl.tsx +2 -0
  297. package/src/cli/serve/web/components/controls/RichSelect.tsx +1 -0
  298. package/src/cli/serve/web/state/RunSt.poll.test.ts +2 -1
  299. package/src/cli/serve/web/tsconfig.json +1 -2
  300. package/src/cli/serve/web/widgets/RelightWidget.tsx +1 -0
  301. package/src/cli/tui/state/HostSt.ts +1 -1
  302. package/src/host/loraManagerApi.ts +8 -3
  303. package/src/runner/ComfyExecution.ts +3 -1
  304. package/src/runner/ComfyWsApi.ts +2 -1
  305. package/src/storage/ComfyStorage.ts +5 -4
  306. package/src/types/comfy-sdk.ts +1 -0
  307. package/src/utils/ansi.ts +1 -0
  308. package/dist/ServeApp-fsHtW5zG.js +0 -2689
  309. package/dist/ServeApp-fsHtW5zG.js.map +0 -1
  310. package/dist/exampleAssets-DZynSkZm.js +0 -6674
  311. package/dist/exampleAssets-DZynSkZm.js.map +0 -1
  312. package/dist/findDefinedWorkflow-qyqFea7q.js +0 -625
  313. package/dist/findDefinedWorkflow-qyqFea7q.js.map +0 -1
  314. package/dist/run-run-Cn2JzKlE.js +0 -449
  315. package/dist/run-run-Cn2JzKlE.js.map +0 -1
  316. package/dist/run-serve-BhGegaCI.js +0 -464
  317. package/dist/run-serve-BhGegaCI.js.map +0 -1
  318. package/dist/run-tui-CrM4ijkH.js +0 -4569
  319. package/dist/run-tui-CrM4ijkH.js.map +0 -1
  320. package/dist/schemaDrift-BGYJZGMD.js +0 -2225
  321. package/dist/schemaDrift-BGYJZGMD.js.map +0 -1
@@ -0,0 +1,4777 @@
1
+ import {
2
+ settingsPathFor,
3
+ bundledExamplesDir
4
+ } from "./chunk-n22qz0j1.js";
5
+ import {
6
+ extractErrorMessage,
7
+ logError,
8
+ importSharp,
9
+ extensionOf,
10
+ loraKey,
11
+ loraBasename,
12
+ fetchLoraList,
13
+ loraPreviewMapFrom,
14
+ fetchLoraPreviewBytes,
15
+ refreshLoraInfoCacheIfChanged,
16
+ getLoraDisplayName,
17
+ getLoraPreviewUrl,
18
+ loraMatchesFilter,
19
+ getLoraKeyword,
20
+ isLoraKeywordFromMirror,
21
+ loraKeywordFromMirror,
22
+ clearLoraKeywordOverride,
23
+ setLoraKeyword,
24
+ PromptVar,
25
+ LorasVar,
26
+ summarizeDrift
27
+ } from "./chunk-6tsg7fm5.js";
28
+ import {
29
+ familyOf,
30
+ assignFamilyColors,
31
+ buildFileRows,
32
+ LogsSt,
33
+ draftKeyForFile,
34
+ listDraftsForFile,
35
+ DraftsSt,
36
+ scanCflowFiles,
37
+ mergeWorkflowSources,
38
+ findDefinedWorkflow
39
+ } from "./chunk-6mgjbrp6.js";
40
+
41
+ // src/cli/tui/run-tui.tsx
42
+ import { readFileSync as readFileSync4, realpathSync, statSync as statSync3 } from "node:fs";
43
+ import { pathToFileURL as pathToFileURL2 } from "node:url";
44
+ import { render } from "ink";
45
+ import { dirname as dirname5, resolve as resolve3 } from "pathe";
46
+
47
+ // src/cli/tui-env.ts
48
+ var COMFY_TS_TUI_ENV = "COMFY_TS_TUI";
49
+
50
+ // src/cli/tui/protocolImagePainter.ts
51
+ import { reaction } from "mobx";
52
+
53
+ // src/cli/tui/imageEscapes.ts
54
+ import { imageMeta } from "image-meta";
55
+ var ESC = "\x1B";
56
+ var ST = "\x1B\\";
57
+ function itermImageEscape(bytes, row, col, w, h) {
58
+ const b64 = Buffer.from(bytes).toString("base64");
59
+ return `${ESC}7${ESC}[${row};${col}H${ESC}]1337;File=inline=1;size=${bytes.byteLength};width=${w};height=${h};preserveAspectRatio=1:${b64}\x07${ESC}8`;
60
+ }
61
+ function fitCellBox(p) {
62
+ if (p.imgW <= 0 || p.imgH <= 0)
63
+ return { w: p.w, h: p.h };
64
+ const aspect = p.imgW / p.imgH;
65
+ let w = p.w;
66
+ let h = Math.max(1, Math.round(w / aspect / 2));
67
+ if (h > p.h) {
68
+ h = p.h;
69
+ w = Math.max(1, Math.min(p.w, Math.round(h * aspect * 2)));
70
+ }
71
+ return { w, h };
72
+ }
73
+ var dimsCache = new WeakMap;
74
+ function imageDims(bytes) {
75
+ const hit = dimsCache.get(bytes);
76
+ if (hit != null)
77
+ return hit;
78
+ let dims = { w: 0, h: 0 };
79
+ try {
80
+ const meta = imageMeta(bytes);
81
+ if (meta.width != null && meta.height != null)
82
+ dims = { w: meta.width, h: meta.height };
83
+ } catch {}
84
+ dimsCache.set(bytes, dims);
85
+ return dims;
86
+ }
87
+ var KITTY_CHUNK = 4096;
88
+ function kittyTransmitEscape(bytes, id) {
89
+ const b64 = Buffer.from(bytes).toString("base64");
90
+ let out = "";
91
+ for (let i = 0;i < b64.length; i += KITTY_CHUNK) {
92
+ const last = i + KITTY_CHUNK >= b64.length;
93
+ const ctrl = i === 0 ? `a=t,f=100,t=d,i=${id},q=2,m=${last ? 0 : 1}` : `m=${last ? 0 : 1}`;
94
+ out += `${ESC}_G${ctrl};${b64.slice(i, i + KITTY_CHUNK)}${ST}`;
95
+ }
96
+ return out;
97
+ }
98
+ function kittyPlaceEscape(id, row, col, w, h, z) {
99
+ const zKey = z == null ? "" : `,z=${z}`;
100
+ return `${ESC}7${ESC}[${row};${col}H${ESC}_Ga=p,i=${id},p=1,c=${w},r=${h},C=1,q=2${zKey}${ST}${ESC}8`;
101
+ }
102
+ function kittyDeleteEscape(id) {
103
+ return `${ESC}_Ga=d,d=I,i=${id},q=2${ST}`;
104
+ }
105
+ var KITTY_DELETE_ALL = `${ESC}_Ga=d,d=A,q=2${ST}`;
106
+
107
+ class KittyImageSlot {
108
+ id;
109
+ transmitted = null;
110
+ constructor(id) {
111
+ this.id = id;
112
+ }
113
+ show(bytes, row, col, w, h, z) {
114
+ let out = "";
115
+ if (this.transmitted !== bytes) {
116
+ out += kittyDeleteEscape(this.id) + kittyTransmitEscape(bytes, this.id);
117
+ this.transmitted = bytes;
118
+ }
119
+ return out + kittyPlaceEscape(this.id, row, col, w, h, z);
120
+ }
121
+ drop() {
122
+ if (this.transmitted == null)
123
+ return "";
124
+ this.transmitted = null;
125
+ return kittyDeleteEscape(this.id);
126
+ }
127
+ }
128
+
129
+ // src/cli/tui/protocolImage.ts
130
+ import sharp from "sharp";
131
+ function imageProtocol() {
132
+ if (process.env.COMFY_TS_NO_ITERM_IMAGES === "1")
133
+ return null;
134
+ const term = process.env.TERM ?? "";
135
+ const program = process.env.TERM_PROGRAM ?? "";
136
+ const kitty = term.includes("kitty") || term.includes("ghostty") || process.env.KITTY_WINDOW_ID != null || process.env.GHOSTTY_RESOURCES_DIR != null;
137
+ if (kitty)
138
+ return "kitty";
139
+ const iterm = program === "iTerm.app" || program === "WezTerm" || program === "vscode" || process.env.LC_TERMINAL === "iTerm2";
140
+ return iterm ? "iterm" : null;
141
+ }
142
+ function protocolCapable() {
143
+ return imageProtocol() != null;
144
+ }
145
+ var PNG_MAGIC = [137, 80, 78, 71, 13, 10, 26, 10];
146
+ function isPng(bytes) {
147
+ return PNG_MAGIC.every((byte, ix) => bytes[ix] === byte);
148
+ }
149
+ async function protocolReadyBytes(bytes) {
150
+ if (imageProtocol() !== "kitty" || isPng(bytes))
151
+ return bytes;
152
+ return new Uint8Array(await sharp(bytes).png().toBuffer());
153
+ }
154
+
155
+ // src/cli/tui/protocolImagePainter.ts
156
+ var SYNC_BEGIN = "\x1B[?2026h";
157
+ var SYNC_END = "\x1B[?2026l";
158
+ var MIN_FRAME_BYTES = 64;
159
+ var MAIN_ID = 1;
160
+ var CORNER_ID = 2;
161
+ var CORNER_Z = 1;
162
+ function installProtocolImagePainter(st) {
163
+ const proto = imageProtocol();
164
+ if (proto == null || process.stdout.isTTY !== true)
165
+ return () => {};
166
+ const original = process.stdout.write.bind(process.stdout);
167
+ const CONTENT_ROW = 6;
168
+ const kittyMain = new KittyImageSlot(MAIN_ID);
169
+ const kittyCorner = new KittyImageSlot(CORNER_ID);
170
+ const imageEscapes = () => {
171
+ const pv = st.preview;
172
+ const main = pv.protocolImage;
173
+ const corner = pv.protocolImageCorner;
174
+ const col = Math.max(1, st.termCols - (pv.width + 4) + 3);
175
+ if (proto === "iterm") {
176
+ if (main == null && corner == null)
177
+ return "";
178
+ let out = "";
179
+ if (main != null)
180
+ out += itermImageEscape(main, CONTENT_ROW, col, pv.width, pv.height);
181
+ if (corner != null) {
182
+ const box = pv.cornerBox;
183
+ out += itermImageEscape(corner, CONTENT_ROW, col + pv.width - box.w, box.w, box.h);
184
+ }
185
+ return out;
186
+ }
187
+ let out = "";
188
+ if (main == null)
189
+ out += kittyMain.drop();
190
+ else {
191
+ const dims = imageDims(main);
192
+ const box = fitCellBox({ imgW: dims.w, imgH: dims.h, w: pv.width, h: pv.height });
193
+ const row = CONTENT_ROW + Math.max(0, Math.floor((pv.height - box.h) / 2));
194
+ const c = col + Math.max(0, Math.floor((pv.width - box.w) / 2));
195
+ out += kittyMain.show(main, row, c, box.w, box.h);
196
+ }
197
+ if (corner == null)
198
+ out += kittyCorner.drop();
199
+ else {
200
+ const box = pv.cornerBox;
201
+ out += kittyCorner.show(corner, CONTENT_ROW, col + pv.width - box.w, box.w, box.h, CORNER_Z);
202
+ }
203
+ return out;
204
+ };
205
+ let disposed = false;
206
+ let scheduled = false;
207
+ const schedule = () => {
208
+ if (scheduled || disposed)
209
+ return;
210
+ scheduled = true;
211
+ setImmediate(() => {
212
+ scheduled = false;
213
+ if (disposed)
214
+ return;
215
+ const images = imageEscapes();
216
+ if (images !== "")
217
+ original(SYNC_BEGIN + images + SYNC_END);
218
+ });
219
+ };
220
+ const patched = (chunk, encodingOrCb, cb) => {
221
+ const isFrame = !disposed && (typeof chunk === "string" ? chunk.length : chunk.byteLength) >= MIN_FRAME_BYTES;
222
+ const images = isFrame ? imageEscapes() : "";
223
+ if (images !== "")
224
+ original(SYNC_BEGIN);
225
+ const res = typeof encodingOrCb === "function" ? original(chunk, encodingOrCb) : original(chunk, encodingOrCb, cb);
226
+ if (images !== "")
227
+ original(images + SYNC_END);
228
+ return res;
229
+ };
230
+ process.stdout.write = patched;
231
+ const disposeReaction = reaction(() => [st.preview.protocolImage, st.preview.protocolImageCorner], schedule);
232
+ return () => {
233
+ disposed = true;
234
+ if (proto === "kitty")
235
+ original(KITTY_DELETE_ALL);
236
+ process.stdout.write = original;
237
+ disposeReaction();
238
+ };
239
+ }
240
+
241
+ // src/cli/tui/components/TuiApp.tsx
242
+ import { Box as Box13, Text as Text18, useApp, useInput, useStdin } from "ink";
243
+ import { observer as observer17 } from "mobx-react-lite";
244
+
245
+ // src/cli/tui/components/CopyOverlay.tsx
246
+ import { Box as Box2, Text as Text2 } from "ink";
247
+ import { observer as observer2 } from "mobx-react-lite";
248
+
249
+ // src/cli/tui/components/StatusBar.tsx
250
+ import { Box, Text } from "ink";
251
+ import { observer } from "mobx-react-lite";
252
+ import { jsx, jsxs } from "react/jsx-runtime";
253
+ var KeyHints = (p) => /* @__PURE__ */ jsx(Text, {
254
+ wrap: "wrap",
255
+ children: p.hints.map(([k, label], ix) => /* @__PURE__ */ jsxs(Text, {
256
+ children: [
257
+ ix > 0 ? /* @__PURE__ */ jsx(Text, {
258
+ color: "gray",
259
+ children: " · "
260
+ }) : null,
261
+ /* @__PURE__ */ jsx(Text, {
262
+ color: "cyan",
263
+ children: k
264
+ }),
265
+ /* @__PURE__ */ jsxs(Text, {
266
+ color: "gray",
267
+ children: [
268
+ " ",
269
+ label
270
+ ]
271
+ })
272
+ ]
273
+ }, `${k}·${label}`))
274
+ });
275
+ var ProgressLine = observer((p) => {
276
+ const s = p.st;
277
+ const e = s.exec;
278
+ const queued = s.queue.remaining;
279
+ if (s.mode === "edit" || s.mode === "overlay-text")
280
+ return /* @__PURE__ */ jsx(Text, {
281
+ color: "gray",
282
+ children: "editing…"
283
+ });
284
+ if (e.running) {
285
+ const prog = e.progress;
286
+ const width = 16;
287
+ const filled = prog ? Math.round(prog.percent / 100 * width) : 0;
288
+ const bar = "█".repeat(filled) + "░".repeat(width - filled);
289
+ return /* @__PURE__ */ jsxs(Text, {
290
+ children: [
291
+ ">> ",
292
+ "[",
293
+ bar,
294
+ "] ",
295
+ prog ? `${prog.percent.toFixed(0)}%` : "…",
296
+ prog?.nodeName ? ` · ${prog.nodeName}` : "",
297
+ prog ? ` · ${(prog.elapsedMs / 1000).toFixed(0)}s` : "",
298
+ queued > 0 ? ` · queue ${queued}` : ""
299
+ ]
300
+ });
301
+ }
302
+ if (e.error)
303
+ return /* @__PURE__ */ jsx(Text, {
304
+ color: "red",
305
+ children: e.error
306
+ });
307
+ if (e.notice)
308
+ return /* @__PURE__ */ jsx(Text, {
309
+ children: e.notice
310
+ });
311
+ if (queued > 0)
312
+ return /* @__PURE__ */ jsxs(Text, {
313
+ color: "yellow",
314
+ children: [
315
+ queued,
316
+ " queued on the server"
317
+ ]
318
+ });
319
+ if (e.runCount > 0)
320
+ return /* @__PURE__ */ jsxs(Text, {
321
+ color: e.lastStatus === "Success" ? "green" : "red",
322
+ children: [
323
+ "run #",
324
+ e.runCount,
325
+ " ",
326
+ e.lastStatus?.toLowerCase()
327
+ ]
328
+ });
329
+ return /* @__PURE__ */ jsx(Text, {
330
+ color: "gray",
331
+ children: "ready — r to run"
332
+ });
333
+ });
334
+ var KIND_KEYS = {
335
+ text: [["⏎/→", "edit"]],
336
+ prompt: [["⏎/→", "edit"]],
337
+ int: [["⏎/→", "edit"]],
338
+ float: [["⏎/→", "edit"]],
339
+ seed: [
340
+ ["+", "increment"],
341
+ ["-", "decrement"],
342
+ ["?", "random"],
343
+ ["=", "fixed"],
344
+ ["⏎/→", "type value"],
345
+ ["*", "reroll"]
346
+ ],
347
+ toggle: [["⏎/→", "flip"]],
348
+ choice: [["⏎/→", "pick"]],
349
+ size: [["⏎/→", "pick"]],
350
+ loras: [["⏎/→", "select"]],
351
+ image: [["⏎/→", "browse"]]
352
+ };
353
+ var TEXT_EDIT_HINTS = [
354
+ ["⏎", "save"],
355
+ ["⇧⏎/⌥⏎", "newline"],
356
+ ["esc", "cancel"],
357
+ ["⌥⌫", "del word"],
358
+ ["⌥←→", "jump"],
359
+ ["⌘←→/⌃A⌃E", "line ends"],
360
+ ["⌥↑↓", "move line"],
361
+ ["⌘/", "comment"],
362
+ ["⌃U/⌃K", "kill"]
363
+ ];
364
+ var DRAFT_OP_HINTS = [
365
+ ["n", "new"],
366
+ ["e", "rename"],
367
+ ["c", "duplicate"],
368
+ ["x", "delete"]
369
+ ];
370
+ var MODE_KEYS = {
371
+ edit: [
372
+ ["⏎", "apply"],
373
+ ["esc", "cancel"],
374
+ ["⌥⌫/⌃W", "del word"],
375
+ ["⌥←→", "jump"],
376
+ ["⌃A/⌃E", "line ends"],
377
+ ["⌃U/⌃K", "kill"]
378
+ ],
379
+ "overlay-text": TEXT_EDIT_HINTS,
380
+ "overlay-choice": [
381
+ ["⏎", "pick"],
382
+ ["↑↓", "move"],
383
+ ["type", "filter"],
384
+ ["esc", "cancel"]
385
+ ],
386
+ "overlay-preset": [
387
+ ["⏎", "use this text"],
388
+ ["↑↓", "move"],
389
+ ["type", "filter"],
390
+ ["esc", "cancel"]
391
+ ],
392
+ "overlay-size": [
393
+ ["⏎", "pick"],
394
+ ["↑↓", "move"],
395
+ ["type", "filter or WxH"],
396
+ ["esc", "cancel"]
397
+ ],
398
+ "overlay-loras": [
399
+ ["space/⏎", "tick"],
400
+ ["←→", "strength ±0.05"],
401
+ ["type", "filter"],
402
+ ["⌃K", "keyword"],
403
+ ["⌃D", "reset keyword"],
404
+ ["⌃A", "all"],
405
+ ["⌃N", "none"],
406
+ ["esc", "done"]
407
+ ],
408
+ "overlay-image": [
409
+ ["⏎", "pick / enter dir"],
410
+ ["←", "parent"],
411
+ ["→", "enter dir"],
412
+ ["tab", "pane"],
413
+ ["↑↓", "move"],
414
+ ["type", "filter"],
415
+ ["⌃F", "fav folder"],
416
+ ["esc", "cancel"]
417
+ ],
418
+ "overlay-drafts": [["⏎", "load / new"], ...DRAFT_OP_HINTS, ["↑↓", "move"], ["esc", "cancel"]],
419
+ "overlay-hosts": [
420
+ ["⏎", "pick run host"],
421
+ ["↑↓", "move"],
422
+ ["esc", "cancel"]
423
+ ],
424
+ "overlay-copy": [["⏎/esc", "close"]],
425
+ tree: [
426
+ ["⏎", "load"],
427
+ ["↑↓", "move"],
428
+ ["←", "fold"],
429
+ ["→", "unfold / vars"],
430
+ ["/", "filter"],
431
+ ...DRAFT_OP_HINTS,
432
+ ["t/esc", "back"]
433
+ ],
434
+ host: [
435
+ ["⏎", "run action"],
436
+ ["↑↓", "move"],
437
+ ["h", "change host"],
438
+ ["a/esc", "back"]
439
+ ],
440
+ preview: [
441
+ ["←→", "change"],
442
+ ["↑↓", "move"],
443
+ ["⏎/p/esc", "done"]
444
+ ]
445
+ };
446
+ var KeyBar = observer((p) => {
447
+ const s = p.st;
448
+ const kind = s.selected?.[1].kind;
449
+ const treeFiltering = s.mode === "tree" && s.tree.filtering;
450
+ const modeHints = treeFiltering ? [
451
+ ["type", "filter"],
452
+ ["⏎", "load"],
453
+ ["↑↓", "move"],
454
+ ["esc", "clear"]
455
+ ] : MODE_KEYS[s.mode] ?? [
456
+ ["↑↓", "select"],
457
+ ["←", "tree"],
458
+ ...kind ? KIND_KEYS[kind] ?? [] : [],
459
+ ...s.picker.presetVar != null ? [["P", "presets"]] : []
460
+ ];
461
+ const globalHints = !treeFiltering && (s.mode === "nav" || s.mode === "tree" || s.mode === "host" || s.mode === "preview") ? [
462
+ ["r", "run"],
463
+ ["s", "reroll+run"],
464
+ ...s.mode === "nav" ? [["e", "rename draft"]] : [],
465
+ ...s.preview.show || s.mode === "preview" ? [] : [["p", "preview (off)"]],
466
+ ["o", "open image"],
467
+ ["i", "copy image"],
468
+ ...s.mode === "tree" || s.mode === "preview" ? [] : [["c/C", "copy wf/api"]],
469
+ ["q", "quit"]
470
+ ] : [
471
+ ["⌃R", "run"],
472
+ ["esc", "back"]
473
+ ];
474
+ return /* @__PURE__ */ jsxs(Box, {
475
+ flexDirection: "column",
476
+ paddingX: 1,
477
+ children: [
478
+ s.mode !== "overlay-text" && /* @__PURE__ */ jsx(KeyHints, {
479
+ hints: modeHints
480
+ }),
481
+ /* @__PURE__ */ jsx(KeyHints, {
482
+ hints: globalHints
483
+ })
484
+ ]
485
+ });
486
+ });
487
+
488
+ // src/cli/tui/components/CopyOverlay.tsx
489
+ import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
490
+ var CopyOverlay = observer2((p) => {
491
+ const popup = p.st.exec.copyPopup;
492
+ if (popup == null)
493
+ return null;
494
+ return /* @__PURE__ */ jsxs2(Box2, {
495
+ borderStyle: "double",
496
+ borderColor: popup.ok ? "green" : "red",
497
+ paddingX: 1,
498
+ flexDirection: "column",
499
+ children: [
500
+ /* @__PURE__ */ jsxs2(Text2, {
501
+ bold: true,
502
+ color: popup.ok ? "green" : "red",
503
+ children: [
504
+ popup.ok ? "✓ " : "✗ ",
505
+ popup.title
506
+ ]
507
+ }),
508
+ popup.lines.slice(0, p.st.overlayLines).map((line, ix) => /* @__PURE__ */ jsx2(Text2, {
509
+ color: popup.ok ? undefined : "red",
510
+ wrap: "truncate",
511
+ children: line
512
+ }, `${ix}·${line.slice(0, 12)}`)),
513
+ /* @__PURE__ */ jsx2(KeyHints, {
514
+ hints: [["⏎/esc", "close"]]
515
+ })
516
+ ]
517
+ });
518
+ });
519
+
520
+ // src/cli/tui/components/DraftsOverlay.tsx
521
+ import { Text as Text4 } from "ink";
522
+ import { observer as observer3 } from "mobx-react-lite";
523
+
524
+ // src/cli/tui/components/OverlayList.tsx
525
+ import { Box as Box3, Text as Text3 } from "ink";
526
+ import { jsx as jsx3, jsxs as jsxs3 } from "react/jsx-runtime";
527
+ var OverlayList = (p) => {
528
+ const winStart = Math.max(0, Math.min(p.selectedIx - Math.floor(p.lines / 2), p.rows.length - p.lines));
529
+ const visible = p.rows.slice(winStart, winStart + p.lines);
530
+ return /* @__PURE__ */ jsxs3(Box3, {
531
+ borderStyle: "double",
532
+ paddingX: 1,
533
+ flexDirection: "column",
534
+ children: [
535
+ /* @__PURE__ */ jsx3(Text3, {
536
+ bold: true,
537
+ children: p.title
538
+ }),
539
+ p.extraHeader,
540
+ winStart > 0 && /* @__PURE__ */ jsx3(Text3, {
541
+ color: "gray",
542
+ children: "…"
543
+ }),
544
+ visible.map((r) => r.node),
545
+ winStart + p.lines < p.rows.length && /* @__PURE__ */ jsx3(Text3, {
546
+ color: "gray",
547
+ children: "…"
548
+ }),
549
+ p.footer
550
+ ]
551
+ });
552
+ };
553
+
554
+ // src/cli/tui/components/DraftsOverlay.tsx
555
+ import { jsx as jsx4, jsxs as jsxs4, Fragment } from "react/jsx-runtime";
556
+ var DraftsOverlay = observer3((p) => {
557
+ const s = p.st;
558
+ const d = s.drafts;
559
+ const rows = [
560
+ {
561
+ key: "·new·",
562
+ node: /* @__PURE__ */ jsxs4(Text4, {
563
+ inverse: d.ix === 0,
564
+ children: [
565
+ d.ix === 0 ? "▸ " : " ",
566
+ "new draft"
567
+ ]
568
+ }, "·new·")
569
+ },
570
+ ...d.list.map((name, ix) => ({
571
+ key: name,
572
+ node: /* @__PURE__ */ jsxs4(Text4, {
573
+ inverse: ix + 1 === d.ix,
574
+ children: [
575
+ ix + 1 === d.ix ? "▸ " : " ",
576
+ name === d.active ? "● " : " ",
577
+ name
578
+ ]
579
+ }, name)
580
+ }))
581
+ ];
582
+ return /* @__PURE__ */ jsx4(OverlayList, {
583
+ title: /* @__PURE__ */ jsxs4(Fragment, {
584
+ children: [
585
+ "drafts ",
586
+ /* @__PURE__ */ jsxs4(Text4, {
587
+ color: "gray",
588
+ children: [
589
+ "· ",
590
+ s.wf.spec.id ?? "workflow"
591
+ ]
592
+ })
593
+ ]
594
+ }),
595
+ selectedIx: d.ix,
596
+ lines: s.overlayLines,
597
+ rows,
598
+ footer: /* @__PURE__ */ jsx4(KeyHints, {
599
+ hints: DRAFT_OP_HINTS
600
+ })
601
+ });
602
+ });
603
+
604
+ // src/cli/tui/components/Header.tsx
605
+ import { Box as Box4, Text as Text5 } from "ink";
606
+ import { observer as observer4 } from "mobx-react-lite";
607
+ import { jsx as jsx5, jsxs as jsxs5 } from "react/jsx-runtime";
608
+ var HeaderBox = (p) => /* @__PURE__ */ jsxs5(Box4, {
609
+ borderStyle: "round",
610
+ borderColor: "gray",
611
+ paddingX: 1,
612
+ flexDirection: "column",
613
+ flexShrink: 0,
614
+ children: [
615
+ p.title != null && /* @__PURE__ */ jsx5(Box4, {
616
+ marginTop: -1,
617
+ children: /* @__PURE__ */ jsx5(Text5, {
618
+ color: "gray",
619
+ children: p.title
620
+ })
621
+ }),
622
+ /* @__PURE__ */ jsx5(Box4, {
623
+ children: p.children
624
+ })
625
+ ]
626
+ });
627
+ var Header = observer4((p) => {
628
+ const s = p.st;
629
+ const runHost = s.runHost;
630
+ return /* @__PURE__ */ jsxs5(Box4, {
631
+ flexDirection: "row",
632
+ children: [
633
+ /* @__PURE__ */ jsx5(HeaderBox, {
634
+ children: /* @__PURE__ */ jsx5(Text5, {
635
+ bold: true,
636
+ color: "magenta",
637
+ children: "comfy-ts"
638
+ })
639
+ }),
640
+ /* @__PURE__ */ jsx5(HeaderBox, {
641
+ title: "(w)orkflow",
642
+ children: /* @__PURE__ */ jsx5(Text5, {
643
+ bold: true,
644
+ color: "yellow",
645
+ children: s.wf.spec.id ?? "workflow"
646
+ })
647
+ }),
648
+ /* @__PURE__ */ jsx5(HeaderBox, {
649
+ title: "(d)raft",
650
+ children: /* @__PURE__ */ jsx5(Text5, {
651
+ bold: true,
652
+ color: "cyan",
653
+ children: s.drafts.active ?? "default"
654
+ })
655
+ }),
656
+ /* @__PURE__ */ jsx5(HeaderBox, {
657
+ title: "(h)ost · (a)ctions",
658
+ children: /* @__PURE__ */ jsxs5(Text5, {
659
+ children: [
660
+ /* @__PURE__ */ jsx5(Text5, {
661
+ color: s.host.status === "up" ? "green" : s.host.status === "down" ? "red" : "gray",
662
+ children: "● "
663
+ }),
664
+ /* @__PURE__ */ jsx5(Text5, {
665
+ bold: true,
666
+ color: "green",
667
+ children: runHost.data.id
668
+ }),
669
+ /* @__PURE__ */ jsxs5(Text5, {
670
+ color: "gray",
671
+ children: [
672
+ " (",
673
+ runHost.addressLabel,
674
+ ")"
675
+ ]
676
+ }),
677
+ s.hostOverride != null && s.hostOverride !== s.wf.host && /* @__PURE__ */ jsxs5(Text5, {
678
+ color: "yellow",
679
+ children: [
680
+ " ⇄ overrides ",
681
+ s.wf.host.data.id
682
+ ]
683
+ }),
684
+ s.host.drift !== "" && /* @__PURE__ */ jsxs5(Text5, {
685
+ color: "yellow",
686
+ children: [
687
+ " ⚠ changed: ",
688
+ s.host.drift,
689
+ " · a → re-codegen"
690
+ ]
691
+ }),
692
+ s.host.status === "down" && /* @__PURE__ */ jsxs5(Text5, {
693
+ color: "red",
694
+ children: [
695
+ " ",
696
+ s.host.probing ? s.host.spinner : `↻ ${s.host.retryInS}s`
697
+ ]
698
+ })
699
+ ]
700
+ })
701
+ })
702
+ ]
703
+ });
704
+ });
705
+
706
+ // src/cli/tui/components/HostPanel.tsx
707
+ import { Box as Box5, Text as Text6 } from "ink";
708
+ import { observer as observer5 } from "mobx-react-lite";
709
+ import { jsx as jsx6, jsxs as jsxs6 } from "react/jsx-runtime";
710
+ var HostPanel = observer5((p) => {
711
+ const s = p.st;
712
+ const h = s.host;
713
+ return /* @__PURE__ */ jsxs6(Box5, {
714
+ borderStyle: "double",
715
+ paddingX: 1,
716
+ flexDirection: "column",
717
+ children: [
718
+ /* @__PURE__ */ jsxs6(Text6, {
719
+ bold: true,
720
+ children: [
721
+ "host actions · ",
722
+ /* @__PURE__ */ jsx6(Text6, {
723
+ color: "green",
724
+ children: h.host.data.id
725
+ }),
726
+ " ",
727
+ /* @__PURE__ */ jsxs6(Text6, {
728
+ color: "gray",
729
+ children: [
730
+ "(",
731
+ h.host.addressLabel,
732
+ ")"
733
+ ]
734
+ }),
735
+ s.hostOverride != null && /* @__PURE__ */ jsx6(Text6, {
736
+ color: "yellow",
737
+ children: " ⇄ override"
738
+ })
739
+ ]
740
+ }),
741
+ h.stats.map((row) => /* @__PURE__ */ jsxs6(Text6, {
742
+ children: [
743
+ /* @__PURE__ */ jsx6(Text6, {
744
+ color: "gray",
745
+ children: row.label.padEnd(12)
746
+ }),
747
+ row.value
748
+ ]
749
+ }, row.label)),
750
+ /* @__PURE__ */ jsx6(Text6, {
751
+ children: " "
752
+ }),
753
+ h.actions.map((action, ix) => {
754
+ const sel = ix === h.ix;
755
+ const busy = h.running === action.key;
756
+ return /* @__PURE__ */ jsxs6(Text6, {
757
+ inverse: sel,
758
+ color: busy ? "yellow" : undefined,
759
+ children: [
760
+ sel ? "▸ " : " ",
761
+ action.label,
762
+ busy ? " …" : ""
763
+ ]
764
+ }, action.key);
765
+ })
766
+ ]
767
+ });
768
+ });
769
+
770
+ // src/cli/tui/components/HostsOverlay.tsx
771
+ import { Text as Text7 } from "ink";
772
+ import { observer as observer6 } from "mobx-react-lite";
773
+ import { jsx as jsx7, jsxs as jsxs7, Fragment as Fragment2 } from "react/jsx-runtime";
774
+ var HostsOverlay = observer6((p) => {
775
+ const s = p.st;
776
+ const h = s.host;
777
+ const rows = h.pickerRows.map((row, ix) => ({
778
+ key: row.host?.data.id ?? "·default·",
779
+ node: /* @__PURE__ */ jsxs7(Text7, {
780
+ inverse: ix === h.pickerIx,
781
+ children: [
782
+ ix === h.pickerIx ? "▸ " : " ",
783
+ row.active ? "● " : " ",
784
+ row.label
785
+ ]
786
+ }, row.host?.data.id ?? "·default·")
787
+ }));
788
+ return /* @__PURE__ */ jsx7(OverlayList, {
789
+ title: /* @__PURE__ */ jsxs7(Fragment2, {
790
+ children: [
791
+ "run host ",
792
+ /* @__PURE__ */ jsx7(Text7, {
793
+ color: "gray",
794
+ children: "· overrides the workflow's configured host"
795
+ })
796
+ ]
797
+ }),
798
+ selectedIx: h.pickerIx,
799
+ lines: s.overlayLines,
800
+ rows
801
+ });
802
+ });
803
+
804
+ // src/cli/tui/components/LorasOverlay.tsx
805
+ import { Text as Text8 } from "ink";
806
+ import { observer as observer7 } from "mobx-react-lite";
807
+ import { jsx as jsx8, jsxs as jsxs8, Fragment as Fragment3 } from "react/jsx-runtime";
808
+ var LorasOverlay = observer7((p) => {
809
+ const s = p.st;
810
+ const lo = s.loras;
811
+ const lv = lo.selectedVar;
812
+ if (lv == null)
813
+ return null;
814
+ const names = lo.filteredNames;
815
+ return /* @__PURE__ */ jsx8(OverlayList, {
816
+ title: /* @__PURE__ */ jsxs8(Fragment3, {
817
+ children: [
818
+ s.selected?.[1].label ?? s.selected?.[0],
819
+ " ",
820
+ /* @__PURE__ */ jsx8(Text8, {
821
+ color: "gray",
822
+ children: lv.display()
823
+ })
824
+ ]
825
+ }),
826
+ extraHeader: /* @__PURE__ */ jsxs8(Text8, {
827
+ color: "yellow",
828
+ children: [
829
+ "filter: ",
830
+ lo.filter,
831
+ "▌"
832
+ ]
833
+ }),
834
+ selectedIx: lo.ix,
835
+ lines: s.overlayLines,
836
+ rows: names.map((name, ix) => {
837
+ const on = lv.isOn(name);
838
+ const keyword = getLoraKeyword(name, lo.hostId);
839
+ const fromMirror = isLoraKeywordFromMirror(name, lo.hostId);
840
+ const file = loraBasename(name);
841
+ const display = getLoraDisplayName(name, lo.hostId);
842
+ return {
843
+ key: name,
844
+ node: /* @__PURE__ */ jsxs8(Text8, {
845
+ inverse: ix === lo.ix,
846
+ bold: on,
847
+ color: on ? "green" : "gray",
848
+ children: [
849
+ ix === lo.ix ? "▸ " : " ",
850
+ on ? "✔" : "·",
851
+ " ",
852
+ file,
853
+ on ? ` ${lv.strengthLabel(name)}` : "",
854
+ display !== file && /* @__PURE__ */ jsxs8(Text8, {
855
+ color: "cyan",
856
+ dimColor: true,
857
+ bold: false,
858
+ children: [
859
+ " ",
860
+ display
861
+ ]
862
+ }),
863
+ keyword !== "" && /* @__PURE__ */ jsxs8(Text8, {
864
+ color: fromMirror ? "gray" : "yellow",
865
+ dimColor: fromMirror,
866
+ bold: false,
867
+ children: [
868
+ " kw: ",
869
+ keyword
870
+ ]
871
+ })
872
+ ]
873
+ }, name)
874
+ };
875
+ }),
876
+ footer: names.length === 0 ? /* @__PURE__ */ jsx8(Text8, {
877
+ color: "red",
878
+ children: "no match"
879
+ }) : undefined
880
+ });
881
+ });
882
+
883
+ // src/cli/tui/components/PickerOverlays.tsx
884
+ import { Text as Text9 } from "ink";
885
+ import { observer as observer8 } from "mobx-react-lite";
886
+ import { jsx as jsx9, jsxs as jsxs9, Fragment as Fragment4 } from "react/jsx-runtime";
887
+ var ChoiceOverlay = observer8((p) => {
888
+ const s = p.st;
889
+ const pk = s.picker;
890
+ const options = pk.options;
891
+ return /* @__PURE__ */ jsx9(OverlayList, {
892
+ title: /* @__PURE__ */ jsxs9(Fragment4, {
893
+ children: [
894
+ "⌥ ",
895
+ s.selected ? s.selected[1].label ?? s.selected[0] : "",
896
+ " ",
897
+ /* @__PURE__ */ jsxs9(Text9, {
898
+ color: "gray",
899
+ children: [
900
+ "(",
901
+ options.length,
902
+ " option",
903
+ options.length === 1 ? "" : "s",
904
+ ")"
905
+ ]
906
+ })
907
+ ]
908
+ }),
909
+ extraHeader: /* @__PURE__ */ jsxs9(Text9, {
910
+ color: "yellow",
911
+ children: [
912
+ "filter: ",
913
+ pk.filter,
914
+ "▌"
915
+ ]
916
+ }),
917
+ selectedIx: pk.ix,
918
+ lines: s.overlayLines,
919
+ rows: options.map((opt, ix) => ({
920
+ key: opt,
921
+ node: /* @__PURE__ */ jsxs9(Text9, {
922
+ inverse: ix === pk.ix,
923
+ children: [
924
+ ix === pk.ix ? "▸ " : " ",
925
+ pk.isPicked(opt) ? "● " : "○ ",
926
+ opt
927
+ ]
928
+ }, opt)
929
+ })),
930
+ footer: options.length === 0 ? /* @__PURE__ */ jsx9(Text9, {
931
+ color: "red",
932
+ children: "no match"
933
+ }) : pk.choiceIsMany ? /* @__PURE__ */ jsx9(Text9, {
934
+ color: "gray",
935
+ children: "⏎ toggles · esc done"
936
+ }) : undefined
937
+ });
938
+ });
939
+ var PresetOverlay = observer8((p) => {
940
+ const s = p.st;
941
+ const pk = s.picker;
942
+ const options = pk.presetOptions;
943
+ const current = pk.presetVar?.toEditBuffer().trim() ?? "";
944
+ return /* @__PURE__ */ jsx9(OverlayList, {
945
+ title: /* @__PURE__ */ jsxs9(Fragment4, {
946
+ children: [
947
+ "presets ",
948
+ s.selected ? s.selected[1].label ?? s.selected[0] : "",
949
+ " ",
950
+ /* @__PURE__ */ jsx9(Text9, {
951
+ color: "gray",
952
+ children: "· ⏎ replaces the text"
953
+ })
954
+ ]
955
+ }),
956
+ extraHeader: /* @__PURE__ */ jsxs9(Text9, {
957
+ color: "yellow",
958
+ children: [
959
+ "filter: ",
960
+ pk.filter,
961
+ "▌"
962
+ ]
963
+ }),
964
+ selectedIx: pk.ix,
965
+ lines: s.overlayLines,
966
+ rows: options.map((opt, ix) => ({
967
+ key: opt.label,
968
+ node: /* @__PURE__ */ jsxs9(Text9, {
969
+ inverse: ix === pk.ix,
970
+ wrap: "truncate",
971
+ children: [
972
+ ix === pk.ix ? "▸ " : " ",
973
+ opt.text.trim() === current ? "• " : " ",
974
+ opt.label,
975
+ " ",
976
+ /* @__PURE__ */ jsx9(Text9, {
977
+ color: "gray",
978
+ children: firstLine(opt.text)
979
+ })
980
+ ]
981
+ }, opt.label)
982
+ })),
983
+ footer: options.length === 0 ? /* @__PURE__ */ jsx9(Text9, {
984
+ color: "red",
985
+ children: "no match"
986
+ }) : undefined
987
+ });
988
+ });
989
+ function firstLine(text) {
990
+ return text.split(`
991
+ `).find((l) => l.trim() !== "") ?? "";
992
+ }
993
+ var SizeOverlay = observer8((p) => {
994
+ const s = p.st;
995
+ const pk = s.picker;
996
+ const options = pk.options;
997
+ return /* @__PURE__ */ jsx9(OverlayList, {
998
+ title: /* @__PURE__ */ jsxs9(Fragment4, {
999
+ children: [
1000
+ "size ",
1001
+ s.selected ? s.selected[1].label ?? s.selected[0] : "",
1002
+ " ",
1003
+ /* @__PURE__ */ jsx9(Text9, {
1004
+ color: "gray",
1005
+ children: "· type WxH for custom"
1006
+ })
1007
+ ]
1008
+ }),
1009
+ extraHeader: /* @__PURE__ */ jsxs9(Text9, {
1010
+ color: pk.invalid ? "red" : "yellow",
1011
+ children: [
1012
+ "filter: ",
1013
+ pk.filter,
1014
+ "▌"
1015
+ ]
1016
+ }),
1017
+ selectedIx: pk.ix,
1018
+ lines: s.overlayLines,
1019
+ rows: options.map((opt, ix) => ({
1020
+ key: opt,
1021
+ node: /* @__PURE__ */ jsxs9(Text9, {
1022
+ inverse: ix === pk.ix,
1023
+ children: [
1024
+ ix === pk.ix ? "▸ " : " ",
1025
+ opt
1026
+ ]
1027
+ }, opt)
1028
+ })),
1029
+ footer: options.length === 0 ? /* @__PURE__ */ jsxs9(Text9, {
1030
+ color: "cyan",
1031
+ children: [
1032
+ "⏎ to use custom size “",
1033
+ pk.filter,
1034
+ "”"
1035
+ ]
1036
+ }) : undefined
1037
+ });
1038
+ });
1039
+
1040
+ // src/cli/tui/components/PreviewPanel.tsx
1041
+ import { Box as Box6, Text as Text10 } from "ink";
1042
+ import { observer as observer9 } from "mobx-react-lite";
1043
+ import { jsx as jsx10, jsxs as jsxs10 } from "react/jsx-runtime";
1044
+ var PreviewPanel = observer9((p) => {
1045
+ const s = p.st;
1046
+ const pv = s.preview;
1047
+ if (pv.menuOpen) {
1048
+ return /* @__PURE__ */ jsxs10(Box6, {
1049
+ borderStyle: "double",
1050
+ paddingX: 1,
1051
+ flexDirection: "column",
1052
+ flexShrink: 0,
1053
+ width: pv.width + 4,
1054
+ children: [
1055
+ /* @__PURE__ */ jsx10(Box6, {
1056
+ marginTop: -1,
1057
+ children: /* @__PURE__ */ jsx10(Text10, {
1058
+ color: "gray",
1059
+ children: "(p)review · settings"
1060
+ })
1061
+ }),
1062
+ pv.menuRows.map((row, ix) => {
1063
+ const sel = ix === pv.menuIx;
1064
+ return /* @__PURE__ */ jsxs10(Text10, {
1065
+ inverse: sel,
1066
+ wrap: "truncate",
1067
+ children: [
1068
+ sel ? "▸ " : " ",
1069
+ row.label.padEnd(14),
1070
+ /* @__PURE__ */ jsx10(Text10, {
1071
+ bold: true,
1072
+ children: row.value
1073
+ })
1074
+ ]
1075
+ }, row.key);
1076
+ }),
1077
+ /* @__PURE__ */ jsx10(Text10, {
1078
+ children: " "
1079
+ }),
1080
+ /* @__PURE__ */ jsx10(Text10, {
1081
+ color: "gray",
1082
+ wrap: "truncate",
1083
+ children: "←→ change · ↑↓ move · ⏎/p/esc done"
1084
+ })
1085
+ ]
1086
+ });
1087
+ }
1088
+ const overlayMode = pv.overlayActive;
1089
+ const running = s.exec.running;
1090
+ const wantLatent = running && pv.duringRun !== "last-output";
1091
+ const showLatent = !overlayMode && wantLatent && (pv.latentAnsi != null || pv.latentBytes != null);
1092
+ const label = overlayMode ? pv.overlay?.name ?? (s.mode === "overlay-loras" ? "lora" : "image") : showLatent ? pv.duringRun === "latent-small" ? "latent small" : "latent" : "output";
1093
+ const placeholder = overlayMode ? pv.overlay?.note ?? (s.mode === "overlay-loras" ? "(pick a lora)" : "(pick an image)") : pv.latentsMissing ? "(no latents from the server — launch comfy with --preview-method auto)" : "(no image yet)";
1094
+ const content = pv.useNative ? null : overlayMode ? pv.overlay?.ansi ?? null : showLatent ? pv.latentAnsi ?? pv.outputAnsi : pv.outputAnsi;
1095
+ const reserveRect = pv.useNative && (pv.protocolImage != null || pv.protocolImageCorner != null);
1096
+ return /* @__PURE__ */ jsxs10(Box6, {
1097
+ borderStyle: "round",
1098
+ paddingX: 1,
1099
+ flexDirection: "column",
1100
+ flexShrink: 0,
1101
+ width: pv.width + 4,
1102
+ children: [
1103
+ /* @__PURE__ */ jsx10(Box6, {
1104
+ marginTop: -1,
1105
+ children: /* @__PURE__ */ jsxs10(Text10, {
1106
+ color: "gray",
1107
+ wrap: "truncate",
1108
+ children: [
1109
+ "(p)review · ",
1110
+ label,
1111
+ " · ",
1112
+ pv.renderer,
1113
+ pv.latentsMissing ? /* @__PURE__ */ jsx10(Text10, {
1114
+ color: "red",
1115
+ children: " · no latents!"
1116
+ }) : null
1117
+ ]
1118
+ })
1119
+ }),
1120
+ reserveRect ? Array.from({ length: pv.height }, (_, ix) => /* @__PURE__ */ jsx10(Text10, {
1121
+ children: " "
1122
+ }, ix)) : content != null ? /* @__PURE__ */ jsx10(Text10, {
1123
+ children: content
1124
+ }) : /* @__PURE__ */ jsx10(Text10, {
1125
+ color: "gray",
1126
+ children: placeholder
1127
+ })
1128
+ ]
1129
+ });
1130
+ });
1131
+
1132
+ // src/cli/tui/components/PromptOverlay.tsx
1133
+ import { Box as Box7, Text as Text12 } from "ink";
1134
+ import { observer as observer11 } from "mobx-react-lite";
1135
+
1136
+ // src/cli/tui/components/EditField.tsx
1137
+ import { Text as Text11 } from "ink";
1138
+ import { observer as observer10 } from "mobx-react-lite";
1139
+ import { jsx as jsx11, jsxs as jsxs11 } from "react/jsx-runtime";
1140
+ var EDIT_WINDOW = 56;
1141
+ var EditField = observer10((p) => {
1142
+ const ed = p.st.editor;
1143
+ const cs = [...ed.buffer];
1144
+ const windowStart = Math.max(0, Math.min(ed.cursor - Math.floor(EDIT_WINDOW * 0.7), cs.length - EDIT_WINDOW));
1145
+ const before = cs.slice(windowStart, ed.cursor).join("");
1146
+ const at = cs[ed.cursor] ?? " ";
1147
+ const after = cs.slice(ed.cursor + 1, windowStart + EDIT_WINDOW).join("");
1148
+ const color = ed.invalid ? "red" : "yellow";
1149
+ return /* @__PURE__ */ jsxs11(Text11, {
1150
+ color,
1151
+ children: [
1152
+ windowStart > 0 ? "…" : "",
1153
+ before,
1154
+ /* @__PURE__ */ jsx11(Text11, {
1155
+ inverse: true,
1156
+ children: at
1157
+ }),
1158
+ after,
1159
+ windowStart + EDIT_WINDOW < cs.length ? "…" : ""
1160
+ ]
1161
+ });
1162
+ });
1163
+
1164
+ // src/cli/tui/components/PromptOverlay.tsx
1165
+ import { jsx as jsx12, jsxs as jsxs12 } from "react/jsx-runtime";
1166
+ var PromptOverlay = observer11((p) => {
1167
+ const ed = p.st.editor;
1168
+ return /* @__PURE__ */ jsxs12(Box7, {
1169
+ borderStyle: "double",
1170
+ paddingX: 1,
1171
+ flexDirection: "column",
1172
+ children: [
1173
+ /* @__PURE__ */ jsx12(Text12, {
1174
+ bold: true,
1175
+ children: ed.customTitle
1176
+ }),
1177
+ /* @__PURE__ */ jsx12(EditField, {
1178
+ st: p.st
1179
+ }),
1180
+ /* @__PURE__ */ jsx12(Text12, {
1181
+ color: "gray",
1182
+ children: "⏎ apply · esc cancel"
1183
+ })
1184
+ ]
1185
+ });
1186
+ });
1187
+
1188
+ // src/cli/tui/imagePicker/ImagePickerOverlay.tsx
1189
+ import { Box as Box8, Text as Text13 } from "ink";
1190
+ import { observer as observer12 } from "mobx-react-lite";
1191
+
1192
+ // src/cli/tui/imagePicker/ImagePickerSt.ts
1193
+ import { existsSync as existsSync2, readFileSync as readFileSync2, statSync as statSync2 } from "node:fs";
1194
+ import { homedir } from "node:os";
1195
+ import { makeAutoObservable as makeAutoObservable2, reaction as reaction2 } from "mobx";
1196
+ import { basename, dirname as dirname3, resolve } from "pathe";
1197
+
1198
+ // src/cli/tui/imagePicker/fsListing.ts
1199
+ import { readdirSync, statSync } from "node:fs";
1200
+ import { dirname, join } from "pathe";
1201
+ function hasImageExtension(name, extensions) {
1202
+ const dot = name.lastIndexOf(".");
1203
+ if (dot <= 0)
1204
+ return false;
1205
+ return extensions.includes(name.slice(dot + 1).toLowerCase());
1206
+ }
1207
+ function listImageDir(dir, extensions) {
1208
+ const dirs = [];
1209
+ const images = [];
1210
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
1211
+ let isDir = entry.isDirectory();
1212
+ let isFile = entry.isFile();
1213
+ if (entry.isSymbolicLink()) {
1214
+ try {
1215
+ const target = statSync(join(dir, entry.name));
1216
+ isDir = target.isDirectory();
1217
+ isFile = target.isFile();
1218
+ } catch {
1219
+ continue;
1220
+ }
1221
+ }
1222
+ if (entry.name.startsWith(".") && !isDir)
1223
+ continue;
1224
+ if (isDir)
1225
+ dirs.push(entry.name);
1226
+ else if (isFile && hasImageExtension(entry.name, extensions))
1227
+ images.push(entry.name);
1228
+ }
1229
+ dirs.sort((a, b) => a.localeCompare(b));
1230
+ images.sort((a, b) => a.localeCompare(b));
1231
+ return { dirs, images };
1232
+ }
1233
+ function parentDir(dir) {
1234
+ return dirname(dir);
1235
+ }
1236
+
1237
+ // src/cli/tui/imagePicker/pickerPrefs.ts
1238
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
1239
+ import { makeAutoObservable } from "mobx";
1240
+ import { dirname as dirname2, join as join2 } from "pathe";
1241
+ var RECENTS_CAP = 20;
1242
+
1243
+ class PickerPrefs {
1244
+ path;
1245
+ favorites = [];
1246
+ recents = [];
1247
+ lastFolder = null;
1248
+ constructor(path) {
1249
+ this.path = path;
1250
+ this.load();
1251
+ makeAutoObservable(this);
1252
+ }
1253
+ load() {
1254
+ if (!existsSync(this.path))
1255
+ return;
1256
+ try {
1257
+ const raw = JSON.parse(readFileSync(this.path, "utf8"));
1258
+ if (raw == null || typeof raw !== "object")
1259
+ throw new Error("not a json object");
1260
+ const o = raw;
1261
+ if (Array.isArray(o.favorites))
1262
+ this.favorites = o.favorites.filter((f) => typeof f === "string");
1263
+ if (Array.isArray(o.recents))
1264
+ this.recents = o.recents.filter((r) => typeof r === "string").slice(0, RECENTS_CAP);
1265
+ if (typeof o.lastFolder === "string")
1266
+ this.lastFolder = o.lastFolder;
1267
+ } catch (e) {
1268
+ logError(`[imagePicker] unreadable ${this.path} — starting fresh: ${String(e)}`);
1269
+ }
1270
+ }
1271
+ write() {
1272
+ try {
1273
+ mkdirSync(dirname2(this.path), { recursive: true });
1274
+ const json = { favorites: this.favorites, recents: this.recents, lastFolder: this.lastFolder };
1275
+ writeFileSync(this.path, `${JSON.stringify(json, null, 2)}
1276
+ `);
1277
+ } catch (e) {
1278
+ logError(`[imagePicker] write failed ${this.path}: ${String(e)}`);
1279
+ }
1280
+ }
1281
+ isFavorite(dir) {
1282
+ return this.favorites.includes(dir);
1283
+ }
1284
+ toggleFavorite(dir) {
1285
+ this.favorites = this.favorites.includes(dir) ? this.favorites.filter((f) => f !== dir) : [...this.favorites, dir];
1286
+ this.write();
1287
+ }
1288
+ recordPick(imagePath) {
1289
+ this.recents = [imagePath, ...this.recents.filter((r) => r !== imagePath)].slice(0, RECENTS_CAP);
1290
+ this.lastFolder = dirname2(imagePath);
1291
+ this.write();
1292
+ }
1293
+ }
1294
+ var _prefs = null;
1295
+ function pickerPrefs() {
1296
+ if (_prefs == null)
1297
+ _prefs = new PickerPrefs(join2(comfyts.baseFolder, "image-picker.json"));
1298
+ return _prefs;
1299
+ }
1300
+
1301
+ // src/utils/fuzzyMatch.ts
1302
+ function fuzzyMatch(needle, hay) {
1303
+ const n = needle.toLowerCase();
1304
+ const h = hay.toLowerCase();
1305
+ let i = 0;
1306
+ for (const ch of h)
1307
+ if (ch === n[i])
1308
+ i++;
1309
+ return i >= n.length;
1310
+ }
1311
+
1312
+ // src/utils/ansiImage.ts
1313
+ import sharp2 from "sharp";
1314
+ async function imageBufferToAnsi(input, p) {
1315
+ const { data, info } = await sharp2(input).flatten({ background: p.background ?? "#1e1e1e" }).resize(p.width, p.height * 2, { fit: "inside" }).raw().toBuffer({ resolveWithObject: true });
1316
+ const w = info.width;
1317
+ const h = info.height;
1318
+ const c = info.channels;
1319
+ const px = (x, y) => {
1320
+ const i = (y * w + x) * c;
1321
+ return [data[i] ?? 0, data[i + 1] ?? 0, data[i + 2] ?? 0];
1322
+ };
1323
+ const rows = [];
1324
+ for (let y = 0;y < h; y += 2) {
1325
+ let row = "";
1326
+ for (let x = 0;x < w; x++) {
1327
+ const [tr, tg, tb] = px(x, y);
1328
+ const [br, bg, bb] = y + 1 < h ? px(x, y + 1) : px(x, y);
1329
+ row += `\x1B[48;2;${tr};${tg};${tb}m\x1B[38;2;${br};${bg};${bb}m▄`;
1330
+ }
1331
+ rows.push(row + "\x1B[0m");
1332
+ }
1333
+ return rows.join(`
1334
+ `);
1335
+ }
1336
+
1337
+ // src/cli/tui/imagePicker/ImagePickerSt.ts
1338
+ var PICKER_PANES = ["browse", "favorites", "recents"];
1339
+ function contractHome(path) {
1340
+ const home = homedir();
1341
+ return path.startsWith(`${home}/`) ? `~${path.slice(home.length)}` : path;
1342
+ }
1343
+
1344
+ class ImagePickerSt {
1345
+ st;
1346
+ constructor(st) {
1347
+ this.st = st;
1348
+ makeAutoObservable2(this, { st: false });
1349
+ this.st.disposers.push(reaction2(() => this.st.mode === "overlay-image" ? this.highlightedImage : null, () => void this.refreshPreview(), { delay: this.st.timing.previewMs }));
1350
+ }
1351
+ pane = "browse";
1352
+ folder = process.cwd();
1353
+ ix = 0;
1354
+ filter = "";
1355
+ get selectedVar() {
1356
+ const sel = this.st.selected?.[1];
1357
+ return sel?.kind === "image" || sel?.kind === "audio" || sel?.kind === "video" ? sel : null;
1358
+ }
1359
+ get folderDisplay() {
1360
+ return contractHome(this.folder);
1361
+ }
1362
+ initialFolder(iv) {
1363
+ const candidates = [
1364
+ iv.isSet() ? dirname3(iv.absPath()) : null,
1365
+ pickerPrefs().lastFolder,
1366
+ iv.opts.folder != null ? resolve(iv.opts.folder) : null
1367
+ ];
1368
+ for (const c of candidates) {
1369
+ try {
1370
+ if (c != null && statSync2(c).isDirectory())
1371
+ return c;
1372
+ } catch {}
1373
+ }
1374
+ return process.cwd();
1375
+ }
1376
+ begin() {
1377
+ const iv = this.selectedVar;
1378
+ if (iv == null)
1379
+ return;
1380
+ this.st.mode = "overlay-image";
1381
+ this.pane = "browse";
1382
+ this.filter = "";
1383
+ this.ix = 0;
1384
+ this.folder = this.initialFolder(iv);
1385
+ this.st.preview.clearOverlayImage();
1386
+ }
1387
+ cancel() {
1388
+ this.st.mode = "nav";
1389
+ }
1390
+ get paneListing() {
1391
+ if (this.pane === "favorites")
1392
+ return {
1393
+ rows: pickerPrefs().favorites.map((dir) => ({ kind: "dir", name: contractHome(dir), path: dir })),
1394
+ error: null
1395
+ };
1396
+ if (this.pane === "recents")
1397
+ return {
1398
+ rows: this.recentsForVar().map((img) => ({
1399
+ kind: "image",
1400
+ name: contractHome(img),
1401
+ path: img,
1402
+ missing: !existsSync2(img)
1403
+ })),
1404
+ error: null
1405
+ };
1406
+ const iv = this.selectedVar;
1407
+ if (iv == null)
1408
+ return { rows: [], error: null };
1409
+ try {
1410
+ const listing = listImageDir(this.folder, iv.extensions);
1411
+ return {
1412
+ rows: [
1413
+ ...listing.dirs.map((d) => ({ kind: "dir", name: d, path: resolve(this.folder, d) })),
1414
+ ...listing.images.map((f) => ({ kind: "image", name: f, path: resolve(this.folder, f), missing: false }))
1415
+ ],
1416
+ error: null
1417
+ };
1418
+ } catch (e) {
1419
+ return { rows: [], error: extractErrorMessage(e) };
1420
+ }
1421
+ }
1422
+ recentsForVar() {
1423
+ const exts = this.selectedVar?.extensions ?? [];
1424
+ return pickerPrefs().recents.filter((f) => exts.includes(extensionOf(f)));
1425
+ }
1426
+ get listingError() {
1427
+ return this.paneListing.error;
1428
+ }
1429
+ get rows() {
1430
+ const all = this.paneListing.rows;
1431
+ if (this.filter === "")
1432
+ return all;
1433
+ return all.filter((r) => fuzzyMatch(this.filter, r.name));
1434
+ }
1435
+ get current() {
1436
+ return this.rows[this.ix] ?? null;
1437
+ }
1438
+ get highlightedImage() {
1439
+ if (this.selectedVar?.kind !== "image")
1440
+ return null;
1441
+ const row = this.current;
1442
+ return row?.kind === "image" && !row.missing ? row.path : null;
1443
+ }
1444
+ move(delta) {
1445
+ const len = this.rows.length;
1446
+ if (len === 0)
1447
+ return;
1448
+ this.ix = (this.ix + delta + len) % len;
1449
+ }
1450
+ cyclePane() {
1451
+ const ix = PICKER_PANES.indexOf(this.pane);
1452
+ this.pane = PICKER_PANES[(ix + 1) % PICKER_PANES.length] ?? "browse";
1453
+ this.ix = 0;
1454
+ this.filter = "";
1455
+ }
1456
+ goto(dir) {
1457
+ this.pane = "browse";
1458
+ this.folder = dir;
1459
+ this.ix = 0;
1460
+ this.filter = "";
1461
+ }
1462
+ enter() {
1463
+ const row = this.current;
1464
+ if (this.pane === "browse" && row?.kind === "dir")
1465
+ this.goto(row.path);
1466
+ }
1467
+ goParent() {
1468
+ if (this.pane !== "browse")
1469
+ return;
1470
+ const parent = parentDir(this.folder);
1471
+ if (parent !== this.folder)
1472
+ this.goto(parent);
1473
+ }
1474
+ commit() {
1475
+ const row = this.current;
1476
+ if (row == null)
1477
+ return;
1478
+ if (row.kind === "dir")
1479
+ return this.goto(row.path);
1480
+ if (row.missing)
1481
+ return;
1482
+ this.select(row.path);
1483
+ }
1484
+ select(absPath) {
1485
+ const iv = this.selectedVar;
1486
+ if (iv == null)
1487
+ return;
1488
+ iv.set(absPath);
1489
+ pickerPrefs().recordPick(absPath);
1490
+ this.st.mode = "nav";
1491
+ }
1492
+ toggleFavorite() {
1493
+ const row = this.current;
1494
+ const dir = row == null ? this.pane === "browse" ? this.folder : null : row.kind === "dir" ? row.path : this.pane === "browse" ? this.folder : dirname3(row.path);
1495
+ if (dir == null)
1496
+ return;
1497
+ pickerPrefs().toggleFavorite(dir);
1498
+ this.ix = Math.max(0, Math.min(this.ix, this.rows.length - 1));
1499
+ }
1500
+ isFavorite(dir) {
1501
+ return pickerPrefs().isFavorite(dir);
1502
+ }
1503
+ filterInput(chunk) {
1504
+ this.filter += chunk;
1505
+ this.ix = 0;
1506
+ }
1507
+ filterBackspace() {
1508
+ this.filter = this.filter.slice(0, -1);
1509
+ this.ix = 0;
1510
+ }
1511
+ filterDeleteWord() {
1512
+ this.filter = this.filter.replace(/\s*\S+\s*$/, "");
1513
+ this.ix = 0;
1514
+ }
1515
+ _busy = false;
1516
+ async refreshPreview() {
1517
+ if (this.st.mode !== "overlay-image") {
1518
+ if (!this.st.preview.overlayActive)
1519
+ this.st.preview.clearOverlayImage();
1520
+ return;
1521
+ }
1522
+ const path = this.highlightedImage;
1523
+ if (path == null) {
1524
+ this.st.preview.clearOverlayImage();
1525
+ return;
1526
+ }
1527
+ if (this._busy)
1528
+ return;
1529
+ this._busy = true;
1530
+ try {
1531
+ const bytes = new Uint8Array(readFileSync2(path));
1532
+ if (this.st.preview.useNative) {
1533
+ this.st.preview.setOverlayImage({
1534
+ bytes: await protocolReadyBytes(bytes),
1535
+ ansi: null,
1536
+ name: basename(path),
1537
+ note: null
1538
+ }, "overlay-image");
1539
+ } else {
1540
+ const ansi = await imageBufferToAnsi(bytes, {
1541
+ width: this.st.preview.width,
1542
+ height: this.st.preview.height
1543
+ });
1544
+ this.st.preview.setOverlayImage({ bytes: null, ansi, name: basename(path), note: null }, "overlay-image");
1545
+ }
1546
+ } catch (e) {
1547
+ this.st.preview.setOverlayImage({
1548
+ bytes: null,
1549
+ ansi: null,
1550
+ name: basename(path),
1551
+ note: extractErrorMessage(e)
1552
+ }, "overlay-image");
1553
+ } finally {
1554
+ this._busy = false;
1555
+ if (this.st.mode === "overlay-image" && this.highlightedImage !== path)
1556
+ this.refreshPreview();
1557
+ }
1558
+ }
1559
+ }
1560
+
1561
+ // src/cli/tui/imagePicker/ImagePickerOverlay.tsx
1562
+ import { jsx as jsx13, jsxs as jsxs13, Fragment as Fragment5 } from "react/jsx-runtime";
1563
+ var ImagePickerOverlay = observer12((p) => {
1564
+ const s = p.st;
1565
+ const ip = s.imagePicker;
1566
+ const iv = ip.selectedVar;
1567
+ if (iv == null)
1568
+ return null;
1569
+ const rows = ip.rows;
1570
+ return /* @__PURE__ */ jsx13(OverlayList, {
1571
+ title: /* @__PURE__ */ jsxs13(Fragment5, {
1572
+ children: [
1573
+ s.selected?.[1].label ?? s.selected?.[0],
1574
+ " ",
1575
+ /* @__PURE__ */ jsx13(Text13, {
1576
+ color: "gray",
1577
+ children: iv.display()
1578
+ })
1579
+ ]
1580
+ }),
1581
+ extraHeader: /* @__PURE__ */ jsxs13(Box8, {
1582
+ flexDirection: "column",
1583
+ children: [
1584
+ /* @__PURE__ */ jsxs13(Text13, {
1585
+ children: [
1586
+ PICKER_PANES.map((pane, ix) => /* @__PURE__ */ jsxs13(Text13, {
1587
+ children: [
1588
+ ix > 0 ? /* @__PURE__ */ jsx13(Text13, {
1589
+ color: "gray",
1590
+ children: " · "
1591
+ }) : null,
1592
+ /* @__PURE__ */ jsx13(Text13, {
1593
+ color: pane === ip.pane ? "cyan" : "gray",
1594
+ bold: pane === ip.pane,
1595
+ underline: pane === ip.pane,
1596
+ children: pane
1597
+ })
1598
+ ]
1599
+ }, pane)),
1600
+ ip.pane === "browse" ? /* @__PURE__ */ jsxs13(Text13, {
1601
+ color: "gray",
1602
+ children: [
1603
+ " ",
1604
+ ip.folderDisplay
1605
+ ]
1606
+ }) : null
1607
+ ]
1608
+ }),
1609
+ /* @__PURE__ */ jsxs13(Text13, {
1610
+ color: "yellow",
1611
+ children: [
1612
+ "filter: ",
1613
+ ip.filter,
1614
+ "▌"
1615
+ ]
1616
+ })
1617
+ ]
1618
+ }),
1619
+ selectedIx: ip.ix,
1620
+ lines: s.overlayLines,
1621
+ rows: rows.map((row, ix) => {
1622
+ const sel = ix === ip.ix;
1623
+ const fav = row.kind === "dir" && ip.isFavorite(row.path);
1624
+ const missing = row.kind === "image" && row.missing;
1625
+ return {
1626
+ key: `${row.kind}:${row.path}`,
1627
+ node: /* @__PURE__ */ jsxs13(Text13, {
1628
+ inverse: sel,
1629
+ color: row.kind === "dir" ? "blue" : missing ? "gray" : undefined,
1630
+ dimColor: missing,
1631
+ children: [
1632
+ sel ? "▸ " : " ",
1633
+ fav ? "★ " : " ",
1634
+ row.name,
1635
+ row.kind === "dir" ? "/" : "",
1636
+ missing ? " (missing)" : ""
1637
+ ]
1638
+ }, `${row.kind}:${row.path}`)
1639
+ };
1640
+ }),
1641
+ footer: rows.length === 0 ? /* @__PURE__ */ jsx13(Text13, {
1642
+ color: "red",
1643
+ children: ip.listingError ?? (ip.filter !== "" ? "no match" : `no ${ip.selectedVar?.kind ?? "image"} files here`)
1644
+ }) : undefined
1645
+ });
1646
+ });
1647
+
1648
+ // src/cli/tui/components/LogsPanel.tsx
1649
+ import { Box as Box9, Text as Text14 } from "ink";
1650
+ import { observer as observer13 } from "mobx-react-lite";
1651
+ import { jsx as jsx14, jsxs as jsxs14 } from "react/jsx-runtime";
1652
+ var ERROR_RE = /error|exception|traceback|failed/i;
1653
+ var LogsPanel = observer13((p) => {
1654
+ const rows = p.st.logs.tail(p.st.termRows < 30 ? 4 : 8);
1655
+ if (rows.length === 0)
1656
+ return null;
1657
+ return /* @__PURE__ */ jsxs14(Box9, {
1658
+ borderStyle: "round",
1659
+ borderColor: "gray",
1660
+ paddingX: 1,
1661
+ flexDirection: "column",
1662
+ flexShrink: 0,
1663
+ children: [
1664
+ /* @__PURE__ */ jsx14(Box9, {
1665
+ marginTop: -1,
1666
+ children: /* @__PURE__ */ jsx14(Text14, {
1667
+ color: "gray",
1668
+ children: "comfy host logs"
1669
+ })
1670
+ }),
1671
+ rows.map((line, ix) => /* @__PURE__ */ jsx14(Text14, {
1672
+ color: ERROR_RE.test(line) ? "red" : "gray",
1673
+ wrap: "truncate-end",
1674
+ children: line
1675
+ }, ix))
1676
+ ]
1677
+ });
1678
+ });
1679
+
1680
+ // src/cli/tui/components/TextOverlay.tsx
1681
+ import { Box as Box10, Text as Text15 } from "ink";
1682
+ import { observer as observer14 } from "mobx-react-lite";
1683
+ import { jsx as jsx15, jsxs as jsxs15 } from "react/jsx-runtime";
1684
+ var TextOverlay = observer14((p) => {
1685
+ const s = p.st;
1686
+ const ed = s.editor;
1687
+ const winLines = s.overlayLines;
1688
+ const selectedVar = s.selected?.[1];
1689
+ const promptVar = selectedVar?.kind === "prompt" ? selectedVar : null;
1690
+ const isPrompt = promptVar != null;
1691
+ const injected = promptVar?.injectedKeywords() ?? [];
1692
+ const lines = [];
1693
+ let start = 0;
1694
+ for (const text of ed.buffer.split(`
1695
+ `)) {
1696
+ lines.push({ text, start });
1697
+ start += [...text].length + 1;
1698
+ }
1699
+ let cursorLine = 0;
1700
+ for (let i = 0;i < lines.length; i++)
1701
+ if ((lines[i]?.start ?? 0) <= ed.cursor)
1702
+ cursorLine = i;
1703
+ const winStart = Math.max(0, Math.min(cursorLine - Math.floor(winLines / 2), lines.length - winLines));
1704
+ const visible = lines.slice(winStart, winStart + winLines);
1705
+ const color = ed.invalid ? "red" : "yellow";
1706
+ return /* @__PURE__ */ jsxs15(Box10, {
1707
+ borderStyle: "double",
1708
+ paddingX: 1,
1709
+ flexDirection: "column",
1710
+ children: [
1711
+ /* @__PURE__ */ jsx15(Text15, {
1712
+ bold: true,
1713
+ children: s.selected ? s.selected[1].label ?? s.selected[0] : ""
1714
+ }),
1715
+ injected.length > 0 && /* @__PURE__ */ jsxs15(Text15, {
1716
+ color: "magenta",
1717
+ wrap: "wrap",
1718
+ children: [
1719
+ "↳ loras: ",
1720
+ injected.join(", "),
1721
+ " ",
1722
+ /* @__PURE__ */ jsx15(Text15, {
1723
+ dimColor: true,
1724
+ children: "(injected)"
1725
+ })
1726
+ ]
1727
+ }),
1728
+ winStart > 0 && /* @__PURE__ */ jsxs15(Text15, {
1729
+ color: "gray",
1730
+ children: [
1731
+ "… ",
1732
+ winStart,
1733
+ " more line(s)"
1734
+ ]
1735
+ }),
1736
+ visible.map((line, ix) => {
1737
+ const globalIx = winStart + ix;
1738
+ const comment = isPrompt && PromptVar.isCommentLine(line.text);
1739
+ const negative = isPrompt && !comment && PromptVar.isNegativeLine(line.text);
1740
+ const lineColor = comment ? "gray" : negative ? "red" : color;
1741
+ if (globalIx !== cursorLine)
1742
+ return /* @__PURE__ */ jsx15(Text15, {
1743
+ color: lineColor,
1744
+ dimColor: comment,
1745
+ children: line.text === "" ? " " : line.text
1746
+ }, globalIx);
1747
+ const cs = [...line.text];
1748
+ const col = ed.cursor - line.start;
1749
+ const before = cs.slice(0, col).join("");
1750
+ const at = cs[col] ?? " ";
1751
+ const after = cs.slice(col + 1).join("");
1752
+ return /* @__PURE__ */ jsxs15(Text15, {
1753
+ color: lineColor,
1754
+ dimColor: comment,
1755
+ backgroundColor: "blackBright",
1756
+ children: [
1757
+ before,
1758
+ /* @__PURE__ */ jsx15(Text15, {
1759
+ inverse: true,
1760
+ children: at
1761
+ }),
1762
+ after
1763
+ ]
1764
+ }, globalIx);
1765
+ }),
1766
+ winStart + winLines < lines.length && /* @__PURE__ */ jsxs15(Text15, {
1767
+ color: "gray",
1768
+ children: [
1769
+ "… ",
1770
+ lines.length - winStart - winLines,
1771
+ " more line(s)"
1772
+ ]
1773
+ }),
1774
+ /* @__PURE__ */ jsx15(KeyHints, {
1775
+ hints: TEXT_EDIT_HINTS
1776
+ })
1777
+ ]
1778
+ });
1779
+ });
1780
+
1781
+ // src/cli/tui/components/TreePanel.tsx
1782
+ import { Box as Box11, measureElement, Text as Text16 } from "ink";
1783
+ import { observer as observer15 } from "mobx-react-lite";
1784
+ import { useEffect, useRef } from "react";
1785
+ import { jsx as jsx16, jsxs as jsxs16 } from "react/jsx-runtime";
1786
+ var TreePanel = observer15((p) => {
1787
+ const s = p.st;
1788
+ const tree = s.tree;
1789
+ const focused = s.mode === "tree";
1790
+ const boxRef = useRef(null);
1791
+ useEffect(() => {
1792
+ if (boxRef.current != null)
1793
+ tree.setViewH(measureElement(boxRef.current).height);
1794
+ });
1795
+ return /* @__PURE__ */ jsxs16(Box11, {
1796
+ ref: boxRef,
1797
+ borderStyle: "round",
1798
+ borderColor: focused ? "cyan" : "gray",
1799
+ flexDirection: "column",
1800
+ flexShrink: 0,
1801
+ width: s.treeWidth,
1802
+ paddingX: 1,
1803
+ overflow: "hidden",
1804
+ children: [
1805
+ /* @__PURE__ */ jsx16(Box11, {
1806
+ marginTop: -1,
1807
+ children: /* @__PURE__ */ jsx16(Text16, {
1808
+ color: focused ? "cyan" : "gray",
1809
+ bold: focused,
1810
+ children: "(t)ree"
1811
+ })
1812
+ }),
1813
+ (tree.filtering || tree.filter !== "") && /* @__PURE__ */ jsxs16(Text16, {
1814
+ color: "yellow",
1815
+ wrap: "truncate",
1816
+ children: [
1817
+ "/",
1818
+ tree.filter,
1819
+ tree.filtering ? "▌" : ""
1820
+ ]
1821
+ }),
1822
+ tree.window.moreAbove && /* @__PURE__ */ jsx16(Text16, {
1823
+ color: "gray",
1824
+ children: "…"
1825
+ }),
1826
+ tree.rows.slice(tree.window.start, tree.window.end).map((row, sliceIx) => {
1827
+ const ix = tree.window.start + sliceIx;
1828
+ const sel = focused && ix === tree.ix;
1829
+ const indent = " ".repeat(row.depth * 2);
1830
+ if (row.kind === "dir") {
1831
+ return /* @__PURE__ */ jsxs16(Text16, {
1832
+ inverse: sel,
1833
+ color: "gray",
1834
+ bold: true,
1835
+ wrap: "truncate",
1836
+ children: [
1837
+ indent,
1838
+ row.expanded ? "▾" : "▸",
1839
+ " ",
1840
+ row.label
1841
+ ]
1842
+ }, `dir·${row.path}`);
1843
+ }
1844
+ if (row.kind === "workflow") {
1845
+ const arrow = row.hasDrafts ? row.expanded ? "▾" : "▸" : " ";
1846
+ const marker = row.error != null ? "✗" : row.current ? "●" : " ";
1847
+ return /* @__PURE__ */ jsxs16(Text16, {
1848
+ inverse: sel,
1849
+ bold: row.current,
1850
+ color: row.error != null ? "red" : row.color,
1851
+ wrap: "truncate",
1852
+ children: [
1853
+ indent,
1854
+ arrow,
1855
+ marker,
1856
+ " ",
1857
+ row.name
1858
+ ]
1859
+ }, row.file);
1860
+ }
1861
+ return /* @__PURE__ */ jsxs16(Text16, {
1862
+ inverse: sel,
1863
+ color: row.active ? "cyan" : "gray",
1864
+ wrap: "truncate",
1865
+ children: [
1866
+ indent,
1867
+ " ",
1868
+ row.active ? "●" : "·",
1869
+ " ",
1870
+ row.draft
1871
+ ]
1872
+ }, `${row.file}·${row.draft}`);
1873
+ }),
1874
+ tree.window.moreBelow && /* @__PURE__ */ jsx16(Text16, {
1875
+ color: "gray",
1876
+ children: "…"
1877
+ }),
1878
+ s.workflows.loading ? /* @__PURE__ */ jsx16(Text16, {
1879
+ color: "yellow",
1880
+ children: "loading…"
1881
+ }) : null
1882
+ ]
1883
+ });
1884
+ });
1885
+
1886
+ // src/cli/tui/components/VarsPanel.tsx
1887
+ import { Box as Box12, measureElement as measureElement2, Text as Text17 } from "ink";
1888
+ import { observer as observer16 } from "mobx-react-lite";
1889
+ import { useEffect as useEffect2, useRef as useRef2 } from "react";
1890
+ import { jsx as jsx17, jsxs as jsxs17 } from "react/jsx-runtime";
1891
+ var VALUE_CAP = 300;
1892
+ var PromptCell = observer16((p) => {
1893
+ const injected = p.varDef.injectedKeywords();
1894
+ return /* @__PURE__ */ jsxs17(Box12, {
1895
+ flexDirection: "column",
1896
+ children: [
1897
+ injected.length > 0 && /* @__PURE__ */ jsxs17(Text17, {
1898
+ color: "magenta",
1899
+ wrap: "wrap",
1900
+ children: [
1901
+ "↳ loras: ",
1902
+ injected.join(", ")
1903
+ ]
1904
+ }),
1905
+ p.value.split(`
1906
+ `).map((line, ix) => {
1907
+ const comment = PromptVar.isCommentLine(line);
1908
+ const negative = !comment && PromptVar.isNegativeLine(line);
1909
+ return /* @__PURE__ */ jsx17(Text17, {
1910
+ color: comment ? "gray" : negative ? "red" : "cyan",
1911
+ dimColor: comment,
1912
+ wrap: "wrap",
1913
+ children: line === "" ? " " : line
1914
+ }, ix);
1915
+ })
1916
+ ]
1917
+ });
1918
+ });
1919
+ var VarRow = observer16((p) => {
1920
+ const editing = p.selected && p.st.mode === "edit" && !p.st.editor.isCustom;
1921
+ const label = p.varDef.label ?? p.name;
1922
+ const raw = p.varDef.display();
1923
+ const value = raw.length > VALUE_CAP ? `${raw.slice(0, VALUE_CAP)}…` : raw;
1924
+ const oneLine = p.compact && !p.selected;
1925
+ return /* @__PURE__ */ jsxs17(Box12, {
1926
+ flexDirection: "row",
1927
+ children: [
1928
+ /* @__PURE__ */ jsx17(Box12, {
1929
+ width: p.labelW,
1930
+ flexShrink: 0,
1931
+ children: /* @__PURE__ */ jsxs17(Text17, {
1932
+ inverse: p.selected,
1933
+ children: [
1934
+ p.selected ? "▸ " : " ",
1935
+ label
1936
+ ]
1937
+ })
1938
+ }),
1939
+ /* @__PURE__ */ jsx17(Box12, {
1940
+ width: 9,
1941
+ flexShrink: 0,
1942
+ children: /* @__PURE__ */ jsxs17(Text17, {
1943
+ color: "gray",
1944
+ children: [
1945
+ "[",
1946
+ p.varDef.kind,
1947
+ "]"
1948
+ ]
1949
+ })
1950
+ }),
1951
+ /* @__PURE__ */ jsx17(Box12, {
1952
+ flexGrow: 1,
1953
+ children: editing ? /* @__PURE__ */ jsx17(EditField, {
1954
+ st: p.st
1955
+ }) : oneLine ? /* @__PURE__ */ jsx17(Text17, {
1956
+ color: "cyan",
1957
+ wrap: "truncate",
1958
+ children: value.replaceAll(`
1959
+ `, " ")
1960
+ }) : p.varDef.kind === "prompt" ? /* @__PURE__ */ jsx17(PromptCell, {
1961
+ varDef: p.varDef,
1962
+ value
1963
+ }) : /* @__PURE__ */ jsx17(Text17, {
1964
+ color: "cyan",
1965
+ wrap: "wrap",
1966
+ children: value
1967
+ })
1968
+ })
1969
+ ]
1970
+ });
1971
+ });
1972
+ var VarsPanel = observer16((p) => {
1973
+ const s = p.st;
1974
+ const labelW = Math.max(12, ...s.entries.map(([name, v]) => (v.label ?? name).length)) + 3;
1975
+ const focused = s.mode === "nav" || s.mode === "edit";
1976
+ const boxRef = useRef2(null);
1977
+ useEffect2(() => {
1978
+ if (boxRef.current != null)
1979
+ s.setVarsViewH(measureElement2(boxRef.current).height);
1980
+ });
1981
+ const w = s.varsWindow;
1982
+ return /* @__PURE__ */ jsxs17(Box12, {
1983
+ ref: boxRef,
1984
+ borderStyle: "round",
1985
+ borderColor: focused ? "cyan" : "gray",
1986
+ paddingX: 1,
1987
+ flexDirection: "column",
1988
+ overflow: "hidden",
1989
+ children: [
1990
+ /* @__PURE__ */ jsx17(Box12, {
1991
+ marginTop: -1,
1992
+ children: /* @__PURE__ */ jsx17(Text17, {
1993
+ color: focused ? "cyan" : "gray",
1994
+ bold: focused,
1995
+ children: "(v)ars"
1996
+ })
1997
+ }),
1998
+ w.moreAbove && /* @__PURE__ */ jsx17(Text17, {
1999
+ color: "gray",
2000
+ children: "…"
2001
+ }),
2002
+ s.entries.slice(w.start, Math.min(w.end, s.entries.length)).map(([name, varDef], sliceIx) => /* @__PURE__ */ jsx17(VarRow, {
2003
+ name,
2004
+ varDef,
2005
+ selected: w.start + sliceIx === s.selIx,
2006
+ labelW,
2007
+ st: s,
2008
+ compact: s.varsCompact
2009
+ }, name)),
2010
+ w.end > s.entries.length && /* @__PURE__ */ jsxs17(Box12, {
2011
+ flexDirection: "row",
2012
+ children: [
2013
+ /* @__PURE__ */ jsx17(Box12, {
2014
+ width: labelW,
2015
+ flexShrink: 0,
2016
+ children: /* @__PURE__ */ jsxs17(Text17, {
2017
+ inverse: s.onSaveRow,
2018
+ children: [
2019
+ s.onSaveRow ? "▸ " : " ",
2020
+ "save to disk"
2021
+ ]
2022
+ })
2023
+ }),
2024
+ /* @__PURE__ */ jsx17(Box12, {
2025
+ width: 9,
2026
+ flexShrink: 0,
2027
+ children: /* @__PURE__ */ jsx17(Text17, {
2028
+ color: "gray",
2029
+ children: "[tui]"
2030
+ })
2031
+ }),
2032
+ /* @__PURE__ */ jsx17(Box12, {
2033
+ flexGrow: 1,
2034
+ children: /* @__PURE__ */ jsx17(Text17, {
2035
+ color: s.settings.saveToDisk ? "cyan" : "yellow",
2036
+ wrap: "truncate",
2037
+ children: s.settings.saveToDisk ? "on" : "off — outputs stay in memory"
2038
+ })
2039
+ })
2040
+ ]
2041
+ }),
2042
+ s.settings.saveToDisk && w.end > s.entries.length + 1 && /* @__PURE__ */ jsxs17(Box12, {
2043
+ flexDirection: "row",
2044
+ children: [
2045
+ /* @__PURE__ */ jsx17(Box12, {
2046
+ width: labelW,
2047
+ flexShrink: 0,
2048
+ children: /* @__PURE__ */ jsxs17(Text17, {
2049
+ inverse: s.onPrefixRow,
2050
+ children: [
2051
+ s.onPrefixRow ? "▸ " : " ",
2052
+ "save prefix"
2053
+ ]
2054
+ })
2055
+ }),
2056
+ /* @__PURE__ */ jsx17(Box12, {
2057
+ width: 9,
2058
+ flexShrink: 0,
2059
+ children: /* @__PURE__ */ jsx17(Text17, {
2060
+ color: "gray",
2061
+ children: "[tui]"
2062
+ })
2063
+ }),
2064
+ /* @__PURE__ */ jsx17(Box12, {
2065
+ flexGrow: 1,
2066
+ children: /* @__PURE__ */ jsxs17(Text17, {
2067
+ color: "cyan",
2068
+ wrap: "truncate",
2069
+ children: [
2070
+ ".comfy-ts/outputs/",
2071
+ s.savePrefix,
2072
+ "/"
2073
+ ]
2074
+ })
2075
+ })
2076
+ ]
2077
+ }),
2078
+ w.moreBelow && /* @__PURE__ */ jsx17(Text17, {
2079
+ color: "gray",
2080
+ children: "…"
2081
+ })
2082
+ ]
2083
+ });
2084
+ });
2085
+
2086
+ // src/cli/tui/keys.ts
2087
+ function parseModifyOtherKeysEnter(input) {
2088
+ const m = /^\[27;(\d+);13~$/.exec(input);
2089
+ if (m == null)
2090
+ return null;
2091
+ const mods = Number(m[1]) - 1;
2092
+ return { return: true, shift: (mods & 1) !== 0, meta: (mods & 10) !== 0, ctrl: (mods & 4) !== 0 };
2093
+ }
2094
+
2095
+ // src/cli/tui/components/TuiApp.tsx
2096
+ import { jsx as jsx18, jsxs as jsxs18 } from "react/jsx-runtime";
2097
+ var TuiApp = observer17((p) => {
2098
+ const app = useApp();
2099
+ const s = p.st;
2100
+ const stdin = useStdin();
2101
+ useInput((input, key) => {
2102
+ const modEnter = parseModifyOtherKeysEnter(input);
2103
+ if (modEnter != null) {
2104
+ input = "";
2105
+ key = { ...key, ...modEnter };
2106
+ }
2107
+ if (key.ctrl && input === "r")
2108
+ return void s.exec.run();
2109
+ if (s.mode === "edit" || s.mode === "overlay-text") {
2110
+ const ed = s.editor;
2111
+ const multi = s.mode === "overlay-text";
2112
+ if (key.escape)
2113
+ return ed.cancel();
2114
+ if (multi && key.ctrl && input === "s")
2115
+ return ed.commitMultiline();
2116
+ if (multi && key.return && (key.shift || key.meta))
2117
+ return ed.newline();
2118
+ if (key.return)
2119
+ return multi ? ed.commitMultiline() : ed.commitInline();
2120
+ if (key.meta && (key.backspace || key.delete) || key.ctrl && input === "w")
2121
+ return ed.deleteWordBack();
2122
+ if (key.backspace || key.delete)
2123
+ return ed.backspace();
2124
+ if (key.meta && key.leftArrow)
2125
+ return ed.wordLeft();
2126
+ if (key.meta && key.rightArrow)
2127
+ return ed.wordRight();
2128
+ if (key.meta && input === "b")
2129
+ return ed.wordLeft();
2130
+ if (key.meta && input === "f")
2131
+ return ed.wordRight();
2132
+ if (key.super && key.leftArrow || key.home || key.ctrl && input === "a")
2133
+ return ed.lineHome();
2134
+ if (key.super && key.rightArrow || key.end || key.ctrl && input === "e")
2135
+ return ed.lineEnd();
2136
+ if (multi && key.meta && key.upArrow)
2137
+ return ed.moveLine(-1);
2138
+ if (multi && key.meta && key.downArrow)
2139
+ return ed.moveLine(1);
2140
+ if (multi && input === "/" && (key.super || key.ctrl || key.meta))
2141
+ return ed.toggleComment();
2142
+ if (multi && input.length === 1 && input.charCodeAt(0) === 31)
2143
+ return ed.toggleComment();
2144
+ if (key.leftArrow)
2145
+ return ed.cursorLeft();
2146
+ if (key.rightArrow)
2147
+ return ed.cursorRight();
2148
+ if (multi && key.upArrow)
2149
+ return ed.cursorUp();
2150
+ if (multi && key.downArrow)
2151
+ return ed.cursorDown();
2152
+ if (key.ctrl && input === "u")
2153
+ return ed.killToStart();
2154
+ if (key.ctrl && input === "k")
2155
+ return ed.killToEnd();
2156
+ if (input && !key.ctrl && !key.meta)
2157
+ return ed.input(input);
2158
+ return;
2159
+ }
2160
+ if (s.mode === "overlay-choice" || s.mode === "overlay-size" || s.mode === "overlay-preset") {
2161
+ const pk = s.picker;
2162
+ if (key.escape)
2163
+ return s.editor.cancel();
2164
+ if (key.return)
2165
+ return pk.commit();
2166
+ if (key.upArrow)
2167
+ return pk.move(-1);
2168
+ if (key.downArrow)
2169
+ return pk.move(1);
2170
+ if (key.meta && (key.backspace || key.delete) || key.ctrl && input === "w")
2171
+ return pk.filterDeleteWord();
2172
+ if (key.backspace || key.delete)
2173
+ return pk.filterBackspace();
2174
+ if (input && !key.ctrl && !key.meta)
2175
+ return pk.filterInput(input);
2176
+ return;
2177
+ }
2178
+ if (s.mode === "overlay-loras") {
2179
+ const lo = s.loras;
2180
+ if (key.escape)
2181
+ return s.editor.cancel();
2182
+ if (key.ctrl && input === "a")
2183
+ return lo.setAll(true);
2184
+ if (key.ctrl && input === "n")
2185
+ return lo.setAll(false);
2186
+ if (key.ctrl && input === "k")
2187
+ return lo.beginKeyword();
2188
+ if (key.ctrl && input === "d")
2189
+ return lo.resetKeyword();
2190
+ if (key.return || input === " ")
2191
+ return lo.toggle();
2192
+ if (key.upArrow)
2193
+ return lo.move(-1);
2194
+ if (key.downArrow)
2195
+ return lo.move(1);
2196
+ if (key.leftArrow)
2197
+ return lo.adjust(-0.05);
2198
+ if (key.rightArrow)
2199
+ return lo.adjust(0.05);
2200
+ if (key.meta && (key.backspace || key.delete) || key.ctrl && input === "w")
2201
+ return lo.filterDeleteWord();
2202
+ if (key.backspace || key.delete)
2203
+ return lo.filterBackspace();
2204
+ if (input && !key.ctrl && !key.meta)
2205
+ return lo.filterInput(input);
2206
+ return;
2207
+ }
2208
+ if (s.mode === "overlay-image") {
2209
+ const ip = s.imagePicker;
2210
+ if (key.escape)
2211
+ return ip.cancel();
2212
+ if (key.tab || input === "\t")
2213
+ return ip.cyclePane();
2214
+ if (key.ctrl && input === "f")
2215
+ return ip.toggleFavorite();
2216
+ if (key.return)
2217
+ return ip.commit();
2218
+ if (key.upArrow)
2219
+ return ip.move(-1);
2220
+ if (key.downArrow)
2221
+ return ip.move(1);
2222
+ if (key.leftArrow)
2223
+ return ip.goParent();
2224
+ if (key.rightArrow)
2225
+ return ip.enter();
2226
+ if (key.meta && (key.backspace || key.delete) || key.ctrl && input === "w")
2227
+ return ip.filterDeleteWord();
2228
+ if (key.backspace || key.delete)
2229
+ return ip.filterBackspace();
2230
+ if (input && !key.ctrl && !key.meta)
2231
+ return ip.filterInput(input);
2232
+ return;
2233
+ }
2234
+ if (s.mode === "tree") {
2235
+ const tr = s.tree;
2236
+ if (tr.filtering) {
2237
+ if (key.escape)
2238
+ return tr.clearFilter();
2239
+ if (key.return)
2240
+ return void tr.commit();
2241
+ if (key.upArrow)
2242
+ return tr.move(-1);
2243
+ if (key.downArrow)
2244
+ return tr.move(1);
2245
+ if (key.leftArrow)
2246
+ return tr.fold();
2247
+ if (key.rightArrow)
2248
+ return tr.unfold();
2249
+ if (key.backspace || key.delete)
2250
+ return tr.filterBackspace();
2251
+ if (input && !key.ctrl && !key.meta)
2252
+ return tr.filterInput(input);
2253
+ return;
2254
+ }
2255
+ if (key.escape)
2256
+ return tr.filter !== "" ? tr.clearFilter() : tr.blur();
2257
+ if (input === "t")
2258
+ return tr.blur();
2259
+ if (input === "/")
2260
+ return tr.beginFilter();
2261
+ if (key.return || input === " ")
2262
+ return void tr.commit();
2263
+ if (key.upArrow)
2264
+ return tr.move(-1);
2265
+ if (key.downArrow)
2266
+ return tr.move(1);
2267
+ if (key.leftArrow)
2268
+ return tr.fold();
2269
+ if (key.rightArrow)
2270
+ return tr.unfold();
2271
+ if (input === "v")
2272
+ return tr.blur();
2273
+ if (input === "n")
2274
+ return tr.promptNewDraft();
2275
+ if (input === "e")
2276
+ return tr.draftOp("rename");
2277
+ if (input === "c")
2278
+ return tr.draftOp("duplicate");
2279
+ if (input === "x")
2280
+ return tr.draftOp("delete");
2281
+ if (input === "r")
2282
+ return void s.exec.run();
2283
+ if (input === "s")
2284
+ return s.exec.randomizeSeedAndRun();
2285
+ if (input === "d")
2286
+ return s.drafts.begin();
2287
+ if (input === "h")
2288
+ return s.host.beginPicker();
2289
+ if (input === "a")
2290
+ return s.host.begin();
2291
+ if (input === "p")
2292
+ return s.preview.beginMenu();
2293
+ if (input === "o")
2294
+ return s.exec.openLastOutput();
2295
+ if (input === "i")
2296
+ return void s.exec.copyLastImage();
2297
+ if (input === "q") {
2298
+ s.onExit();
2299
+ return app.exit();
2300
+ }
2301
+ return;
2302
+ }
2303
+ if (s.mode === "host") {
2304
+ const h = s.host;
2305
+ if (key.escape || input === "a" || input === "v")
2306
+ return h.blur();
2307
+ if (input === "h")
2308
+ return h.beginPicker();
2309
+ if (key.return || input === " ")
2310
+ return void h.commit();
2311
+ if (key.upArrow)
2312
+ return h.move(-1);
2313
+ if (key.downArrow)
2314
+ return h.move(1);
2315
+ if (input === "q") {
2316
+ s.onExit();
2317
+ return app.exit();
2318
+ }
2319
+ return;
2320
+ }
2321
+ if (s.mode === "overlay-hosts") {
2322
+ const h = s.host;
2323
+ if (key.escape || input === "h")
2324
+ return h.cancelPicker();
2325
+ if (key.return || input === " ")
2326
+ return h.commitPicker();
2327
+ if (key.upArrow)
2328
+ return h.pickerMove(-1);
2329
+ if (key.downArrow)
2330
+ return h.pickerMove(1);
2331
+ return;
2332
+ }
2333
+ if (s.mode === "overlay-copy") {
2334
+ if (key.escape || key.return || input === " " || input === "c" || input === "C" || input === "q")
2335
+ return s.exec.closeCopyPopup();
2336
+ return;
2337
+ }
2338
+ if (s.mode === "preview") {
2339
+ const pv = s.preview;
2340
+ if (key.escape || key.return || input === "p" || input === "v")
2341
+ return pv.blurMenu();
2342
+ if (key.upArrow)
2343
+ return pv.menuMove(-1);
2344
+ if (key.downArrow)
2345
+ return pv.menuMove(1);
2346
+ if (key.leftArrow)
2347
+ return pv.menuCycle(-1);
2348
+ if (key.rightArrow || input === " ")
2349
+ return pv.menuCycle(1);
2350
+ if (input === "r")
2351
+ return void s.exec.run();
2352
+ if (input === "s")
2353
+ return s.exec.randomizeSeedAndRun();
2354
+ if (input === "d")
2355
+ return s.drafts.begin();
2356
+ if (input === "h")
2357
+ return s.host.beginPicker();
2358
+ if (input === "a")
2359
+ return s.host.begin();
2360
+ if (input === "o")
2361
+ return s.exec.openLastOutput();
2362
+ if (input === "i")
2363
+ return void s.exec.copyLastImage();
2364
+ if (input === "q") {
2365
+ s.onExit();
2366
+ return app.exit();
2367
+ }
2368
+ return;
2369
+ }
2370
+ if (s.mode === "overlay-drafts") {
2371
+ const d = s.drafts;
2372
+ if (key.escape)
2373
+ return s.editor.cancel();
2374
+ if (key.return)
2375
+ return d.commit();
2376
+ if (key.upArrow)
2377
+ return d.move(-1);
2378
+ if (key.downArrow)
2379
+ return d.move(1);
2380
+ if (input === "n")
2381
+ return d.promptNew("overlay-drafts");
2382
+ if (input === "e" && d.selectedName != null)
2383
+ return d.promptRename(d.selectedName, undefined, "overlay-drafts");
2384
+ if (input === "c" && d.selectedName != null)
2385
+ return d.promptDuplicate(d.selectedName, undefined, "overlay-drafts");
2386
+ if (input === "x" && d.selectedName != null) {
2387
+ d.deleteDraft(d.selectedName);
2388
+ return d.begin();
2389
+ }
2390
+ return;
2391
+ }
2392
+ if (input === "q") {
2393
+ s.onExit();
2394
+ return app.exit();
2395
+ }
2396
+ if (key.upArrow)
2397
+ return s.moveSel(-1);
2398
+ if (key.downArrow)
2399
+ return s.moveSel(1);
2400
+ if (key.leftArrow)
2401
+ return s.tree.focus();
2402
+ if (key.rightArrow || key.return || input === " ")
2403
+ return s.activate();
2404
+ if (s.navKey(input))
2405
+ return;
2406
+ if (input === "/") {
2407
+ s.tree.focus();
2408
+ return s.tree.beginFilter();
2409
+ }
2410
+ if (input === "P")
2411
+ return s.picker.beginPresets();
2412
+ if (input === "e")
2413
+ return s.drafts.beginRename();
2414
+ if (input === "r")
2415
+ return void s.exec.run();
2416
+ if (input === "s")
2417
+ return s.exec.randomizeSeedAndRun();
2418
+ if (input === "t" || input === "w")
2419
+ return s.tree.focus();
2420
+ if (input === "h")
2421
+ return s.host.beginPicker();
2422
+ if (input === "a")
2423
+ return s.host.begin();
2424
+ if (input === "d")
2425
+ return s.drafts.begin();
2426
+ if (input === "p")
2427
+ return s.preview.beginMenu();
2428
+ if (input === "o")
2429
+ return s.exec.openLastOutput();
2430
+ if (input === "i")
2431
+ return void s.exec.copyLastImage();
2432
+ if (input === "c")
2433
+ return void s.exec.copyWorkflowJson();
2434
+ if (input === "C")
2435
+ return void s.exec.copyApiJson();
2436
+ }, { isActive: stdin.isRawModeSupported === true });
2437
+ return /* @__PURE__ */ jsxs18(Box13, {
2438
+ flexDirection: "column",
2439
+ height: s.termRows - 1,
2440
+ children: [
2441
+ /* @__PURE__ */ jsx18(Header, {
2442
+ st: s
2443
+ }),
2444
+ /* @__PURE__ */ jsxs18(Box13, {
2445
+ flexDirection: "row",
2446
+ flexGrow: 1,
2447
+ flexShrink: 1,
2448
+ overflow: "hidden",
2449
+ children: [
2450
+ /* @__PURE__ */ jsx18(TreePanel, {
2451
+ st: s
2452
+ }),
2453
+ /* @__PURE__ */ jsxs18(Box13, {
2454
+ flexDirection: "column",
2455
+ flexGrow: 1,
2456
+ children: [
2457
+ s.mode === "edit" && s.editor.isCustom ? /* @__PURE__ */ jsx18(PromptOverlay, {
2458
+ st: s
2459
+ }) : s.mode === "host" ? /* @__PURE__ */ jsx18(HostPanel, {
2460
+ st: s
2461
+ }) : s.mode === "overlay-text" ? /* @__PURE__ */ jsx18(TextOverlay, {
2462
+ st: s
2463
+ }) : s.mode === "overlay-choice" ? /* @__PURE__ */ jsx18(ChoiceOverlay, {
2464
+ st: s
2465
+ }) : s.mode === "overlay-preset" ? /* @__PURE__ */ jsx18(PresetOverlay, {
2466
+ st: s
2467
+ }) : s.mode === "overlay-size" ? /* @__PURE__ */ jsx18(SizeOverlay, {
2468
+ st: s
2469
+ }) : s.mode === "overlay-loras" ? /* @__PURE__ */ jsx18(LorasOverlay, {
2470
+ st: s
2471
+ }) : s.mode === "overlay-image" ? /* @__PURE__ */ jsx18(ImagePickerOverlay, {
2472
+ st: s
2473
+ }) : s.mode === "overlay-drafts" ? /* @__PURE__ */ jsx18(DraftsOverlay, {
2474
+ st: s
2475
+ }) : s.mode === "overlay-hosts" ? /* @__PURE__ */ jsx18(HostsOverlay, {
2476
+ st: s
2477
+ }) : s.mode === "overlay-copy" ? /* @__PURE__ */ jsx18(CopyOverlay, {
2478
+ st: s
2479
+ }) : /* @__PURE__ */ jsx18(VarsPanel, {
2480
+ st: s
2481
+ }),
2482
+ /* @__PURE__ */ jsx18(Box13, {
2483
+ paddingX: 1,
2484
+ children: /* @__PURE__ */ jsx18(ProgressLine, {
2485
+ st: s
2486
+ })
2487
+ }),
2488
+ s.exec.outputLabels.length > 0 && /* @__PURE__ */ jsx18(Box13, {
2489
+ borderStyle: "round",
2490
+ paddingX: 1,
2491
+ flexDirection: "column",
2492
+ children: s.exec.outputLabels.map((o, ix) => /* @__PURE__ */ jsxs18(Text18, {
2493
+ color: o.memory ? "yellow" : "green",
2494
+ wrap: "truncate",
2495
+ children: [
2496
+ o.name,
2497
+ " ",
2498
+ /* @__PURE__ */ jsx18(Text18, {
2499
+ color: "gray",
2500
+ children: o.detail
2501
+ })
2502
+ ]
2503
+ }, `${ix}-${o.name}`))
2504
+ }),
2505
+ !s.mode.startsWith("overlay-") && !(s.mode === "edit" && s.editor.isCustom) && /* @__PURE__ */ jsx18(LogsPanel, {
2506
+ st: s
2507
+ })
2508
+ ]
2509
+ }),
2510
+ (s.preview.show || s.preview.menuOpen) && /* @__PURE__ */ jsx18(PreviewPanel, {
2511
+ st: s
2512
+ })
2513
+ ]
2514
+ }),
2515
+ /* @__PURE__ */ jsx18(KeyBar, {
2516
+ st: s
2517
+ })
2518
+ ]
2519
+ });
2520
+ });
2521
+
2522
+ // src/cli/tui/state/TuiSt.ts
2523
+ import { makeAutoObservable as makeAutoObservable13, observableRef, runInAction as runInAction7 } from "mobx";
2524
+
2525
+ // src/cli/tui/listWindow.ts
2526
+ var listWindow = (p) => {
2527
+ if (p.count === 0 || p.budget <= 0) {
2528
+ const at = Math.max(0, Math.min(p.selected, p.count));
2529
+ return { start: at, end: at, moreAbove: false, moreBelow: false };
2530
+ }
2531
+ if (p.count <= p.budget)
2532
+ return { start: 0, end: p.count, moreAbove: false, moreBelow: false };
2533
+ const sel = Math.max(0, Math.min(p.selected, p.count - 1));
2534
+ if (p.budget <= 2) {
2535
+ const start = Math.min(sel, p.count - p.budget);
2536
+ return { start, end: start + p.budget, moreAbove: false, moreBelow: false };
2537
+ }
2538
+ if (sel < p.budget - 1)
2539
+ return { start: 0, end: p.budget - 1, moreAbove: false, moreBelow: true };
2540
+ if (sel >= p.count - (p.budget - 1))
2541
+ return { start: p.count - (p.budget - 1), end: p.count, moreAbove: true, moreBelow: false };
2542
+ const visible = p.budget - 2;
2543
+ const start = Math.max(1, Math.min(sel - Math.floor(visible / 2), p.count - visible - 1));
2544
+ return { start, end: start + visible, moreAbove: true, moreBelow: true };
2545
+ };
2546
+
2547
+ // src/cli/tui/state/EditorSt.ts
2548
+ import { makeAutoObservable as makeAutoObservable3 } from "mobx";
2549
+
2550
+ class EditorSt {
2551
+ st;
2552
+ constructor(st) {
2553
+ this.st = st;
2554
+ makeAutoObservable3(this, { st: false });
2555
+ }
2556
+ buffer = "";
2557
+ cursor = 0;
2558
+ invalid = false;
2559
+ static escapeForBuffer(raw) {
2560
+ return raw.replaceAll("\\", "\\\\").replaceAll(`\r
2561
+ `, `
2562
+ `).replaceAll("\r", `
2563
+ `).replaceAll(`
2564
+ `, "\\n");
2565
+ }
2566
+ static unescapeBuffer(buffer) {
2567
+ return buffer.replace(/\\\\|\\n/g, (m) => m === "\\\\" ? "\\" : `
2568
+ `);
2569
+ }
2570
+ customCommit = null;
2571
+ customTitle = "";
2572
+ returnMode = "nav";
2573
+ get isCustom() {
2574
+ return this.customCommit != null;
2575
+ }
2576
+ beginInline() {
2577
+ const sel = this.st.selected?.[1];
2578
+ if (sel == null)
2579
+ return;
2580
+ this.st.mode = "edit";
2581
+ this.buffer = EditorSt.escapeForBuffer(sel.toEditBuffer());
2582
+ this.cursor = [...this.buffer].length;
2583
+ this.invalid = false;
2584
+ }
2585
+ beginCustom(p) {
2586
+ this.st.mode = "edit";
2587
+ this.customCommit = p.onCommit;
2588
+ this.customTitle = p.title;
2589
+ this.returnMode = p.returnMode ?? "nav";
2590
+ this.buffer = EditorSt.escapeForBuffer(p.initial);
2591
+ this.cursor = [...this.buffer].length;
2592
+ this.invalid = false;
2593
+ }
2594
+ beginMultiline() {
2595
+ const sel = this.st.selected?.[1];
2596
+ if (sel == null)
2597
+ return;
2598
+ this.st.mode = "overlay-text";
2599
+ this.buffer = sel.toEditBuffer();
2600
+ this.cursor = [...this.buffer].length;
2601
+ this.invalid = false;
2602
+ }
2603
+ commitInline() {
2604
+ if (this.customCommit != null) {
2605
+ if (this.customCommit(EditorSt.unescapeBuffer(this.buffer))) {
2606
+ this.customCommit = null;
2607
+ this.st.mode = this.returnMode;
2608
+ } else
2609
+ this.invalid = true;
2610
+ return;
2611
+ }
2612
+ const sel = this.st.selected?.[1];
2613
+ if (sel == null)
2614
+ return;
2615
+ if (sel.parse(EditorSt.unescapeBuffer(this.buffer)))
2616
+ this.st.mode = "nav";
2617
+ else
2618
+ this.invalid = true;
2619
+ }
2620
+ commitMultiline() {
2621
+ const sel = this.st.selected?.[1];
2622
+ if (sel == null)
2623
+ return;
2624
+ if (sel.parse(this.buffer))
2625
+ this.st.mode = "nav";
2626
+ else
2627
+ this.invalid = true;
2628
+ }
2629
+ cancel() {
2630
+ this.st.mode = this.customCommit != null ? this.returnMode : "nav";
2631
+ this.invalid = false;
2632
+ this.customCommit = null;
2633
+ }
2634
+ get chars() {
2635
+ return [...this.buffer];
2636
+ }
2637
+ setChars(cs, cursor) {
2638
+ this.buffer = cs.join("");
2639
+ this.cursor = Math.max(0, Math.min(cursor, cs.length));
2640
+ this.invalid = false;
2641
+ }
2642
+ input(chunk) {
2643
+ const normalized = this.st.mode === "overlay-text" ? chunk.replaceAll(`\r
2644
+ `, `
2645
+ `).replaceAll("\r", `
2646
+ `) : EditorSt.escapeForBuffer(chunk);
2647
+ const insert = [...normalized];
2648
+ const cs = this.chars;
2649
+ cs.splice(this.cursor, 0, ...insert);
2650
+ this.setChars(cs, this.cursor + insert.length);
2651
+ }
2652
+ backspace() {
2653
+ if (this.cursor === 0)
2654
+ return;
2655
+ const cs = this.chars;
2656
+ cs.splice(this.cursor - 1, 1);
2657
+ this.setChars(cs, this.cursor - 1);
2658
+ }
2659
+ newline() {
2660
+ const cs = this.chars;
2661
+ cs.splice(this.cursor, 0, `
2662
+ `);
2663
+ this.setChars(cs, this.cursor + 1);
2664
+ }
2665
+ wordBoundLeft() {
2666
+ const cs = this.chars;
2667
+ let i = this.cursor;
2668
+ while (i > 0 && /\s/.test(cs[i - 1] ?? ""))
2669
+ i--;
2670
+ while (i > 0 && !/\s/.test(cs[i - 1] ?? ""))
2671
+ i--;
2672
+ return i;
2673
+ }
2674
+ wordBoundRight() {
2675
+ const cs = this.chars;
2676
+ let i = this.cursor;
2677
+ while (i < cs.length && /\s/.test(cs[i] ?? ""))
2678
+ i++;
2679
+ while (i < cs.length && !/\s/.test(cs[i] ?? ""))
2680
+ i++;
2681
+ return i;
2682
+ }
2683
+ deleteWordBack() {
2684
+ const from = this.wordBoundLeft();
2685
+ const cs = this.chars;
2686
+ cs.splice(from, this.cursor - from);
2687
+ this.setChars(cs, from);
2688
+ }
2689
+ killToStart() {
2690
+ this.setChars(this.chars.slice(this.cursor), 0);
2691
+ }
2692
+ killToEnd() {
2693
+ this.setChars(this.chars.slice(0, this.cursor), this.cursor);
2694
+ }
2695
+ cursorLeft() {
2696
+ if (this.cursor > 0)
2697
+ this.cursor--;
2698
+ }
2699
+ cursorRight() {
2700
+ if (this.cursor < this.chars.length)
2701
+ this.cursor++;
2702
+ }
2703
+ wordLeft() {
2704
+ this.cursor = this.wordBoundLeft();
2705
+ }
2706
+ wordRight() {
2707
+ this.cursor = this.wordBoundRight();
2708
+ }
2709
+ lineStartAt(ix) {
2710
+ const cs = this.chars;
2711
+ let i = ix;
2712
+ while (i > 0 && cs[i - 1] !== `
2713
+ `)
2714
+ i--;
2715
+ return i;
2716
+ }
2717
+ lineEndAt(ix) {
2718
+ const cs = this.chars;
2719
+ let i = ix;
2720
+ while (i < cs.length && cs[i] !== `
2721
+ `)
2722
+ i++;
2723
+ return i;
2724
+ }
2725
+ lineHome() {
2726
+ const start = this.lineStartAt(this.cursor);
2727
+ if (this.cursor !== start || start === 0)
2728
+ return void (this.cursor = start);
2729
+ this.cursor = this.lineStartAt(start - 1);
2730
+ }
2731
+ lineEnd() {
2732
+ const end = this.lineEndAt(this.cursor);
2733
+ if (this.cursor !== end || end === this.chars.length)
2734
+ return void (this.cursor = end);
2735
+ this.cursor = this.lineEndAt(end + 1);
2736
+ }
2737
+ moveLine(delta) {
2738
+ const cs = this.chars;
2739
+ const start = this.lineStartAt(this.cursor);
2740
+ const end = this.lineEndAt(this.cursor);
2741
+ const col = this.cursor - start;
2742
+ const cur = cs.slice(start, end);
2743
+ if (delta === -1) {
2744
+ if (start === 0)
2745
+ return;
2746
+ const prevStart = this.lineStartAt(start - 1);
2747
+ const prev = cs.slice(prevStart, start - 1);
2748
+ this.setChars([...cs.slice(0, prevStart), ...cur, `
2749
+ `, ...prev, ...cs.slice(end)], prevStart + Math.min(col, cur.length));
2750
+ } else {
2751
+ if (end === cs.length)
2752
+ return;
2753
+ const nextEnd = this.lineEndAt(end + 1);
2754
+ const next = cs.slice(end + 1, nextEnd);
2755
+ this.setChars([...cs.slice(0, start), ...next, `
2756
+ `, ...cur, ...cs.slice(nextEnd)], start + next.length + 1 + Math.min(col, cur.length));
2757
+ }
2758
+ }
2759
+ toggleComment() {
2760
+ const cs = this.chars;
2761
+ const start = this.lineStartAt(this.cursor);
2762
+ const end = this.lineEndAt(this.cursor);
2763
+ const line = cs.slice(start, end).join("");
2764
+ const m = /^(\s*)\/\/ ?/.exec(line);
2765
+ if (m == null) {
2766
+ cs.splice(start, 0, "/", "/", " ");
2767
+ this.setChars(cs, this.cursor + 3);
2768
+ return;
2769
+ }
2770
+ const indentLen = [...m[1] ?? ""].length;
2771
+ const removeLen = [...m[0]].length - indentLen;
2772
+ cs.splice(start + indentLen, removeLen);
2773
+ this.setChars(cs, Math.max(start, this.cursor - removeLen));
2774
+ }
2775
+ cursorUp() {
2776
+ const start = this.lineStartAt(this.cursor);
2777
+ if (start === 0) {
2778
+ this.cursor = 0;
2779
+ return;
2780
+ }
2781
+ const col = this.cursor - start;
2782
+ const prevStart = this.lineStartAt(start - 1);
2783
+ const prevLen = start - 1 - prevStart;
2784
+ this.cursor = prevStart + Math.min(col, prevLen);
2785
+ }
2786
+ cursorDown() {
2787
+ const cs = this.chars;
2788
+ const start = this.lineStartAt(this.cursor);
2789
+ const col = this.cursor - start;
2790
+ let end = this.cursor;
2791
+ while (end < cs.length && cs[end] !== `
2792
+ `)
2793
+ end++;
2794
+ if (end === cs.length) {
2795
+ this.cursor = cs.length;
2796
+ return;
2797
+ }
2798
+ const nextStart = end + 1;
2799
+ let nextEnd = nextStart;
2800
+ while (nextEnd < cs.length && cs[nextEnd] !== `
2801
+ `)
2802
+ nextEnd++;
2803
+ this.cursor = nextStart + Math.min(col, nextEnd - nextStart);
2804
+ }
2805
+ }
2806
+
2807
+ // src/cli/tui/state/ExecSt.ts
2808
+ import { spawn } from "node:child_process";
2809
+ import { existsSync as existsSync3, writeFileSync as writeFileSync2 } from "node:fs";
2810
+ import { tmpdir } from "node:os";
2811
+ import { makeAutoObservable as makeAutoObservable4, runInAction } from "mobx";
2812
+ import { basename as basename2, join as join3 } from "pathe";
2813
+
2814
+ // src/cli/tui/imageClipboard.ts
2815
+ var extOf = (path) => {
2816
+ const dot = path.lastIndexOf(".");
2817
+ return dot === -1 ? "" : path.slice(dot + 1).toLowerCase();
2818
+ };
2819
+ var imageClipboardStdinCommand = (platform, pngBytes) => {
2820
+ if (platform === "darwin") {
2821
+ const hex = Buffer.from(pngBytes).toString("hex").toUpperCase();
2822
+ return {
2823
+ cmd: "osascript",
2824
+ args: ["-"],
2825
+ stdin: new TextEncoder().encode(`set the clipboard to «data PNGf${hex}»`)
2826
+ };
2827
+ }
2828
+ if (platform === "win32") {
2829
+ const script = "$b=[Convert]::FromBase64String([Console]::In.ReadToEnd()); " + "$ms=New-Object System.IO.MemoryStream(,$b); " + "Add-Type -AssemblyName System.Windows.Forms,System.Drawing; " + "$img=[System.Drawing.Image]::FromStream($ms); " + "[System.Windows.Forms.Clipboard]::SetImage($img); $img.Dispose()";
2830
+ return {
2831
+ cmd: "powershell",
2832
+ args: ["-NoProfile", "-Sta", "-Command", script],
2833
+ stdin: new TextEncoder().encode(Buffer.from(pngBytes).toString("base64"))
2834
+ };
2835
+ }
2836
+ return { cmd: "xclip", args: ["-selection", "clipboard", "-t", "image/png"], stdin: pngBytes };
2837
+ };
2838
+ var imageClipboardCommand = (platform, path) => {
2839
+ const ext = extOf(path);
2840
+ if (platform === "darwin") {
2841
+ if (ext !== "png" && ext !== "jpg" && ext !== "jpeg")
2842
+ return null;
2843
+ const cls = ext === "png" ? "«class PNGf»" : "JPEG picture";
2844
+ return {
2845
+ cmd: "osascript",
2846
+ args: ["-e", `set the clipboard to (read (POSIX file ${JSON.stringify(path)}) as ${cls})`]
2847
+ };
2848
+ }
2849
+ if (platform === "win32") {
2850
+ const psQuoted = `'${path.replaceAll("'", "''")}'`;
2851
+ return {
2852
+ cmd: "powershell",
2853
+ args: [
2854
+ "-NoProfile",
2855
+ "-Sta",
2856
+ "-Command",
2857
+ `Add-Type -AssemblyName System.Windows.Forms,System.Drawing; $img=[System.Drawing.Image]::FromFile(${psQuoted}); [System.Windows.Forms.Clipboard]::SetImage($img); $img.Dispose()`
2858
+ ]
2859
+ };
2860
+ }
2861
+ const mime = ext === "jpg" || ext === "jpeg" ? "image/jpeg" : ext === "webp" ? "image/webp" : "image/png";
2862
+ return { cmd: "xclip", args: ["-selection", "clipboard", "-t", mime, "-i", path] };
2863
+ };
2864
+
2865
+ // src/cli/tui/state/ExecSt.ts
2866
+ function jsonHead(text, maxLines) {
2867
+ const lines = text.split(`
2868
+ `);
2869
+ const head = lines.slice(0, maxLines).map((l) => l.length > 76 ? `${l.slice(0, 75)}…` : l);
2870
+ if (lines.length > maxLines)
2871
+ head.push("…");
2872
+ return head;
2873
+ }
2874
+
2875
+ class ExecSt {
2876
+ st;
2877
+ constructor(st) {
2878
+ this.st = st;
2879
+ makeAutoObservable4(this, { st: false });
2880
+ }
2881
+ inFlight = 0;
2882
+ progress = null;
2883
+ outputImages = [];
2884
+ runCount = 0;
2885
+ lastStatus = null;
2886
+ error = null;
2887
+ notice = null;
2888
+ currentPromptId = null;
2889
+ latentHosts = new Set;
2890
+ get running() {
2891
+ return this.inFlight > 0;
2892
+ }
2893
+ resetForWorkflow(notice) {
2894
+ this.outputImages = [];
2895
+ this.error = null;
2896
+ this.notice = notice;
2897
+ this.runCount = 0;
2898
+ this.lastStatus = null;
2899
+ }
2900
+ get outputLabels() {
2901
+ return this.outputImages.map((img) => {
2902
+ if (img.absPath != null)
2903
+ return { name: basename2(img.absPath), detail: img.absPath, memory: false };
2904
+ const dims = img.width != null && img.height != null ? `${img.width}x${img.height}, ` : "";
2905
+ return { name: img.filename, detail: `(${dims}in memory — i copies, o opens)`, memory: true };
2906
+ });
2907
+ }
2908
+ materialize(img) {
2909
+ if (img.absPath != null)
2910
+ return img.absPath;
2911
+ const path = join3(tmpdir(), `comfy-ts-mem-${img.hash.slice(0, 8)}${img.extension}`);
2912
+ if (!existsSync3(path))
2913
+ writeFileSync2(path, img.buffer);
2914
+ return path;
2915
+ }
2916
+ async run() {
2917
+ const queued = this.running;
2918
+ const host = this.st.runHost;
2919
+ runInAction(() => {
2920
+ this.inFlight++;
2921
+ this.error = null;
2922
+ if (queued) {
2923
+ this.notice = `queued another run (server queue: ${this.st.queue.remaining + 1})`;
2924
+ } else {
2925
+ this.progress = null;
2926
+ this.notice = null;
2927
+ this.currentPromptId = null;
2928
+ this.st.preview.clearLatent();
2929
+ }
2930
+ host.onLatentPreview = (p) => void this.st.preview.renderLatent(p.bytes);
2931
+ this.latentHosts.add(host);
2932
+ });
2933
+ try {
2934
+ const execution = await this.st.wf.run({
2935
+ host: this.st.hostOverride ?? undefined,
2936
+ save: this.st.settings.saveToDisk ? { prefix: this.st.savePrefix } : false,
2937
+ onProgress: (p) => runInAction(() => this.onProgress(p))
2938
+ });
2939
+ runInAction(() => {
2940
+ this.outputImages = execution.images.slice();
2941
+ this.lastStatus = execution.status;
2942
+ this.runCount++;
2943
+ });
2944
+ const lastImage = execution.images[execution.images.length - 1];
2945
+ if (lastImage != null)
2946
+ this.st.preview.renderOutput(lastImage.absPath ?? lastImage.buffer);
2947
+ } catch (e) {
2948
+ runInAction(() => {
2949
+ this.error = extractErrorMessage(e);
2950
+ });
2951
+ } finally {
2952
+ runInAction(() => {
2953
+ this.inFlight--;
2954
+ this.progress = null;
2955
+ this.currentPromptId = null;
2956
+ this.st.preview.clearLatent();
2957
+ if (this.inFlight === 0) {
2958
+ for (const h of this.latentHosts)
2959
+ h.onLatentPreview = null;
2960
+ this.latentHosts.clear();
2961
+ }
2962
+ });
2963
+ }
2964
+ }
2965
+ onProgress(p) {
2966
+ if (p.promptId !== this.currentPromptId) {
2967
+ this.currentPromptId = p.promptId;
2968
+ this.notice = null;
2969
+ this.st.preview.clearLatent();
2970
+ }
2971
+ this.progress = p;
2972
+ }
2973
+ randomizeSeedAndRun() {
2974
+ for (const [, varDef] of this.st.entries) {
2975
+ if (varDef.kind === "seed")
2976
+ varDef.randomize();
2977
+ }
2978
+ this.run();
2979
+ }
2980
+ openLastOutput() {
2981
+ const lastImg = this.outputImages[this.outputImages.length - 1];
2982
+ if (lastImg == null) {
2983
+ this.notice = "no output image yet";
2984
+ return;
2985
+ }
2986
+ let last;
2987
+ try {
2988
+ last = this.materialize(lastImg);
2989
+ } catch (e) {
2990
+ this.notice = `open failed: ${extractErrorMessage(e)}`;
2991
+ return;
2992
+ }
2993
+ const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
2994
+ const proc = spawn(cmd, [last], { stdio: "ignore", detached: true });
2995
+ proc.on("error", () => {
2996
+ runInAction(() => {
2997
+ this.notice = `could not launch ${cmd}`;
2998
+ });
2999
+ });
3000
+ proc.unref();
3001
+ this.notice = `opened ${basename2(last)}${lastImg.absPath == null ? ` (memory image via ${last})` : ""}`;
3002
+ }
3003
+ copyPopup = null;
3004
+ copying = false;
3005
+ closeCopyPopup() {
3006
+ this.copyPopup = null;
3007
+ this.st.mode = "nav";
3008
+ }
3009
+ showCopyPopup(title, ok, lines) {
3010
+ const m = this.st.mode;
3011
+ if (m === "edit" || m.startsWith("overlay-")) {
3012
+ this.notice = `${ok ? "✓" : "✗"} ${title}`;
3013
+ return;
3014
+ }
3015
+ this.copyPopup = { title, ok, lines };
3016
+ this.st.mode = "overlay-copy";
3017
+ }
3018
+ async copyLastImage() {
3019
+ const lastImg = this.outputImages[this.outputImages.length - 1];
3020
+ if (lastImg == null) {
3021
+ this.showCopyPopup("image → clipboard", false, ["no output image yet — r runs the workflow first"]);
3022
+ return;
3023
+ }
3024
+ let pngBytes;
3025
+ try {
3026
+ pngBytes = lastImg.metadata.type === "png" ? lastImg.buffer : await this.toPngBytes(lastImg.buffer);
3027
+ } catch (e) {
3028
+ this.showCopyPopup("image → clipboard", false, [
3029
+ `COPY FAILED for ${lastImg.filename}`,
3030
+ `png transcode failed: ${extractErrorMessage(e)}`
3031
+ ]);
3032
+ return;
3033
+ }
3034
+ const piped = imageClipboardStdinCommand(process.platform, pngBytes);
3035
+ const pipedOk = await this.runWithStdin(piped);
3036
+ if (pipedOk) {
3037
+ this.showCopyPopup("image → clipboard", true, [
3038
+ `${lastImg.filename} — paste the pixels anywhere`,
3039
+ "",
3040
+ "nothing written to disk"
3041
+ ]);
3042
+ return;
3043
+ }
3044
+ let file;
3045
+ try {
3046
+ file = this.materialize(lastImg);
3047
+ } catch (e) {
3048
+ this.showCopyPopup("image → clipboard", false, [
3049
+ `COPY FAILED for ${lastImg.filename}`,
3050
+ `piped ${piped.cmd} failed, and the tmp-file fallback could not write: ${extractErrorMessage(e)}`
3051
+ ]);
3052
+ return;
3053
+ }
3054
+ const command = imageClipboardCommand(process.platform, file);
3055
+ const ok = command != null && await new Promise((resolve) => {
3056
+ const proc = spawn(command.cmd, command.args, { stdio: "ignore" });
3057
+ proc.on("error", () => resolve(false));
3058
+ proc.on("close", (code) => resolve(code === 0));
3059
+ });
3060
+ this.showCopyPopup("image → clipboard", ok, ok ? [`${basename2(file)} — paste the pixels anywhere`, "", `via fallback file ${file}`] : [`COPY FAILED for ${lastImg.filename}`, `could not run ${piped.cmd} — is it installed and allowed ?`]);
3061
+ }
3062
+ async toPngBytes(bytes) {
3063
+ const sharp = await importSharp("the clipboard png normalize");
3064
+ return new Uint8Array(await sharp(bytes).png().toBuffer());
3065
+ }
3066
+ runWithStdin(p) {
3067
+ return new Promise((resolve) => {
3068
+ const proc = spawn(p.cmd, p.args, { stdio: ["pipe", "ignore", "ignore"] });
3069
+ proc.on("error", () => resolve(false));
3070
+ proc.on("close", (code) => resolve(code === 0));
3071
+ proc.stdin.on("error", () => {});
3072
+ proc.stdin.write(p.stdin);
3073
+ proc.stdin.end();
3074
+ });
3075
+ }
3076
+ toClipboard(text) {
3077
+ const [cmd, ...args] = process.platform === "darwin" ? ["pbcopy"] : process.platform === "win32" ? ["clip"] : ["xclip", "-selection", "clipboard"];
3078
+ return new Promise((resolve) => {
3079
+ const proc = spawn(cmd ?? "pbcopy", args, { stdio: ["pipe", "ignore", "ignore"] });
3080
+ proc.on("error", () => resolve(false));
3081
+ proc.on("close", (code) => resolve(code === 0));
3082
+ proc.stdin.write(text);
3083
+ proc.stdin.end();
3084
+ });
3085
+ }
3086
+ async copyWorkflowJson() {
3087
+ if (this.copying)
3088
+ return;
3089
+ runInAction(() => {
3090
+ this.copying = true;
3091
+ this.notice = "building for copy… (i2i workflows upload their input image first)";
3092
+ });
3093
+ try {
3094
+ const wf = await this.st.wf.build({ host: this.st.hostOverride ?? undefined });
3095
+ const json = await wf.toWorkflowJson();
3096
+ const text = JSON.stringify(json, null, 2);
3097
+ const ok = await this.toClipboard(text);
3098
+ this.showCopyPopup("workflow.json → clipboard", ok, ok ? [
3099
+ `${json.nodes.length} nodes · ${text.length} chars — paste into the ComfyUI editor`,
3100
+ "",
3101
+ ...jsonHead(text, 10)
3102
+ ] : ["CLIPBOARD COPY FAILED — is a clipboard tool available (pbcopy/clip/xclip) ?"]);
3103
+ } catch (e) {
3104
+ this.showCopyPopup("workflow.json copy FAILED", false, [
3105
+ extractErrorMessage(e),
3106
+ "",
3107
+ "nothing was copied. i2i/i2v builds upload their input image first —",
3108
+ "an unreachable host fails the build itself, not just the run."
3109
+ ]);
3110
+ } finally {
3111
+ runInAction(() => {
3112
+ this.copying = false;
3113
+ });
3114
+ }
3115
+ }
3116
+ async copyApiJson() {
3117
+ if (this.copying)
3118
+ return;
3119
+ runInAction(() => {
3120
+ this.copying = true;
3121
+ this.notice = "building for copy… (i2i workflows upload their input image first)";
3122
+ });
3123
+ try {
3124
+ const wf = await this.st.wf.build({ host: this.st.hostOverride ?? undefined });
3125
+ const json = wf.toApiJson("use_stringified_numbers_only");
3126
+ const text = JSON.stringify(json, null, 2);
3127
+ const ok = await this.toClipboard(text);
3128
+ this.showCopyPopup("api.json → clipboard", ok, ok ? [
3129
+ `${Object.keys(json).length} nodes · ${text.length} chars — the POST /prompt payload`,
3130
+ "",
3131
+ ...jsonHead(text, 10)
3132
+ ] : ["CLIPBOARD COPY FAILED — is a clipboard tool available (pbcopy/clip/xclip) ?"]);
3133
+ } catch (e) {
3134
+ this.showCopyPopup("api.json copy FAILED", false, [
3135
+ extractErrorMessage(e),
3136
+ "",
3137
+ "nothing was copied. i2i/i2v builds upload their input image first —",
3138
+ "an unreachable host fails the build itself, not just the run."
3139
+ ]);
3140
+ } finally {
3141
+ runInAction(() => {
3142
+ this.copying = false;
3143
+ });
3144
+ }
3145
+ }
3146
+ }
3147
+
3148
+ // src/cli/tui/state/HostSt.ts
3149
+ import { makeAutoObservable as makeAutoObservable5, reaction as reaction3, runInAction as runInAction2 } from "mobx";
3150
+ var PROBE_EVERY_MS = 5000;
3151
+ var DRIFT_EVERY_MS = 60000;
3152
+ var PROBE_TIMEOUT_MS = 3000;
3153
+ var WS_ALIVE_MS = 1e4;
3154
+ var SPIN_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
3155
+ function probeVerdict(p) {
3156
+ if (p.httpOk)
3157
+ return { status: "up", via: p.wsOpen ? "ws" : "http" };
3158
+ if (p.wsOpen && p.lastWsMessageAt != null && p.now - p.lastWsMessageAt < WS_ALIVE_MS)
3159
+ return { status: "up", via: "ws" };
3160
+ return { status: "down", via: null };
3161
+ }
3162
+
3163
+ class HostSt {
3164
+ st;
3165
+ constructor(st) {
3166
+ this.st = st;
3167
+ makeAutoObservable5(this, { st: false });
3168
+ this.probeLoop();
3169
+ this.st.disposers.push(() => {
3170
+ this.disposed = true;
3171
+ if (this.loopTimer != null)
3172
+ clearTimeout(this.loopTimer);
3173
+ if (this.spinTimer != null)
3174
+ clearInterval(this.spinTimer);
3175
+ if (this.countdownTimer != null)
3176
+ clearInterval(this.countdownTimer);
3177
+ });
3178
+ this.st.disposers.push(reaction3(() => this.st.runHost, () => {
3179
+ runInAction2(() => {
3180
+ this.status = "unknown";
3181
+ this.statusVia = null;
3182
+ this.lastProbeError = null;
3183
+ this.drift = "";
3184
+ });
3185
+ this.probeGen++;
3186
+ if (this.loopTimer != null)
3187
+ clearTimeout(this.loopTimer);
3188
+ if (this.countdownTimer != null)
3189
+ clearInterval(this.countdownTimer);
3190
+ this.probeLoop();
3191
+ }));
3192
+ }
3193
+ status = "unknown";
3194
+ statusVia = null;
3195
+ lastProbeError = null;
3196
+ probing = false;
3197
+ retryInS = 0;
3198
+ spinFrame = 0;
3199
+ disposed = false;
3200
+ probeGen = 0;
3201
+ loopTimer = null;
3202
+ spinTimer = null;
3203
+ countdownTimer = null;
3204
+ get spinner() {
3205
+ return SPIN_FRAMES[this.spinFrame % SPIN_FRAMES.length] ?? "⠋";
3206
+ }
3207
+ async probeLoop() {
3208
+ const gen = this.probeGen;
3209
+ await this.probe();
3210
+ if (this.disposed || gen !== this.probeGen)
3211
+ return;
3212
+ const nextAt = Date.now() + PROBE_EVERY_MS;
3213
+ runInAction2(() => {
3214
+ this.retryInS = Math.ceil(PROBE_EVERY_MS / 1000);
3215
+ });
3216
+ if (this.countdownTimer != null)
3217
+ clearInterval(this.countdownTimer);
3218
+ this.countdownTimer = setInterval(() => {
3219
+ runInAction2(() => {
3220
+ this.retryInS = Math.max(0, Math.ceil((nextAt - Date.now()) / 1000));
3221
+ });
3222
+ }, 250);
3223
+ this.countdownTimer.unref?.();
3224
+ this.loopTimer = setTimeout(() => {
3225
+ if (this.countdownTimer != null)
3226
+ clearInterval(this.countdownTimer);
3227
+ this.probeLoop();
3228
+ }, PROBE_EVERY_MS);
3229
+ this.loopTimer.unref?.();
3230
+ }
3231
+ async probe() {
3232
+ const host = this.host;
3233
+ runInAction2(() => {
3234
+ this.probing = true;
3235
+ });
3236
+ const spin = setInterval(() => {
3237
+ runInAction2(() => {
3238
+ this.spinFrame++;
3239
+ });
3240
+ }, 120);
3241
+ spin.unref?.();
3242
+ this.spinTimer = spin;
3243
+ let ok;
3244
+ let probeError = null;
3245
+ try {
3246
+ const res = await host.fetch("/prompt", { signal: AbortSignal.timeout(PROBE_TIMEOUT_MS) });
3247
+ res.body?.cancel();
3248
+ ok = res.ok;
3249
+ if (!ok)
3250
+ probeError = `http ${res.status}`;
3251
+ } catch (e) {
3252
+ ok = false;
3253
+ probeError = extractErrorMessage(e);
3254
+ } finally {
3255
+ clearInterval(spin);
3256
+ if (this.spinTimer === spin) {
3257
+ this.spinTimer = null;
3258
+ runInAction2(() => {
3259
+ this.probing = false;
3260
+ });
3261
+ }
3262
+ }
3263
+ if (this.host !== host)
3264
+ return;
3265
+ const before = this.status;
3266
+ const verdict = probeVerdict({
3267
+ httpOk: ok,
3268
+ wsOpen: host.isConnected,
3269
+ lastWsMessageAt: host.lastWsMessageAt,
3270
+ now: Date.now()
3271
+ });
3272
+ runInAction2(() => {
3273
+ this.status = verdict.status;
3274
+ this.statusVia = verdict.via;
3275
+ this.lastProbeError = probeError;
3276
+ });
3277
+ if (verdict.status === "up") {
3278
+ if (before !== "up")
3279
+ this.checkDrift(true);
3280
+ else if (Date.now() - this.driftAt > DRIFT_EVERY_MS)
3281
+ this.checkDrift(false);
3282
+ }
3283
+ }
3284
+ drift = "";
3285
+ driftAt = 0;
3286
+ async checkDrift(full) {
3287
+ const host = this.host;
3288
+ if (host.data.sdkAutoWrite === false)
3289
+ return;
3290
+ this.driftAt = Date.now();
3291
+ try {
3292
+ const summary = summarizeDrift(await host.checkSchemaDrift({ full }));
3293
+ if (this.host !== host)
3294
+ return;
3295
+ runInAction2(() => {
3296
+ if (summary !== "")
3297
+ this.drift = summary;
3298
+ else if (full)
3299
+ this.drift = "";
3300
+ });
3301
+ } catch {}
3302
+ }
3303
+ ix = 0;
3304
+ running = null;
3305
+ actions = [
3306
+ { key: "refresh", label: "re-codegen SDK (refetch object_info + reload workflow)" },
3307
+ { key: "restart", label: "restart ComfyUI (manager reboot)" },
3308
+ { key: "clear-queue", label: "clear pending queue" },
3309
+ { key: "interrupt", label: "interrupt current run" }
3310
+ ];
3311
+ get host() {
3312
+ return this.st.runHost;
3313
+ }
3314
+ get stats() {
3315
+ const schema = this.host.schema;
3316
+ return [
3317
+ {
3318
+ label: "status",
3319
+ value: this.status === "down" ? `down · ${this.probing ? `${this.spinner} probing…` : `retry in ${this.retryInS}s`}` : this.status + (this.statusVia != null ? ` (${this.statusVia})` : "")
3320
+ },
3321
+ ...this.lastProbeError != null ? [{ label: "http probe", value: this.lastProbeError }] : [],
3322
+ { label: "node types", value: String(schema.nodes.length) },
3323
+ { label: "loras", value: String(schema.getLoras().length) },
3324
+ { label: "embeddings", value: String(schema.data.embeddings.length) },
3325
+ { label: "queue", value: String(this.st.queue.remaining) },
3326
+ { label: "ws", value: this.host.noAddress ?? this.host.getWSUrl() }
3327
+ ];
3328
+ }
3329
+ begin() {
3330
+ this.st.mode = "host";
3331
+ this.ix = 0;
3332
+ }
3333
+ blur() {
3334
+ this.st.mode = "nav";
3335
+ }
3336
+ pickerIx = 0;
3337
+ get pickerRows() {
3338
+ const wfHost = this.st.wf.host;
3339
+ const rows = [
3340
+ { host: null, label: `workflow default (${wfHost.data.id})`, active: this.st.hostOverride == null }
3341
+ ];
3342
+ for (const host of comfyts.hosts.values()) {
3343
+ rows.push({
3344
+ host,
3345
+ label: `${host.data.id} (${host.addressLabel})`,
3346
+ active: this.st.hostOverride === host
3347
+ });
3348
+ }
3349
+ return rows;
3350
+ }
3351
+ beginPicker() {
3352
+ this.st.mode = "overlay-hosts";
3353
+ const active = this.pickerRows.findIndex((r) => r.active);
3354
+ this.pickerIx = active === -1 ? 0 : active;
3355
+ }
3356
+ cancelPicker() {
3357
+ this.st.mode = "nav";
3358
+ }
3359
+ pickerMove(delta) {
3360
+ const len = this.pickerRows.length;
3361
+ if (len === 0)
3362
+ return;
3363
+ this.pickerIx = (this.pickerIx + delta + len) % len;
3364
+ }
3365
+ commitPicker() {
3366
+ const row = this.pickerRows[this.pickerIx];
3367
+ if (row == null)
3368
+ return;
3369
+ this.st.setHostOverride(row.host);
3370
+ this.st.mode = "nav";
3371
+ this.st.exec.notice = row.host == null ? `host override cleared — runs target the workflow's own host (${this.st.wf.host.data.id})` : `runs now target ${row.host.data.id} (overrides ${this.st.wf.host.data.id})`;
3372
+ }
3373
+ move(delta) {
3374
+ const len = this.actions.length;
3375
+ this.ix = (this.ix + delta + len) % len;
3376
+ }
3377
+ async commit() {
3378
+ const action = this.actions[this.ix];
3379
+ if (action == null || this.running != null)
3380
+ return;
3381
+ if (action.key === "refresh")
3382
+ return this.refreshSdk();
3383
+ if (action.key === "restart")
3384
+ return this.restartComfy();
3385
+ if (action.key === "clear-queue")
3386
+ return this.st.queue.clearPending();
3387
+ return this.st.queue.interrupt();
3388
+ }
3389
+ async refreshSdk() {
3390
+ runInAction2(() => {
3391
+ this.running = "refresh";
3392
+ });
3393
+ try {
3394
+ await this.host.fetchAndUpdateSchema();
3395
+ await this.st.workflows.reload(this.st.drafts.active ?? "default");
3396
+ runInAction2(() => {
3397
+ const schema = this.host.schema;
3398
+ this.st.exec.notice = `SDK regenerated: ${schema.nodes.length} node types, ${schema.getLoras().length} loras`;
3399
+ this.drift = "";
3400
+ });
3401
+ } catch (e) {
3402
+ runInAction2(() => {
3403
+ this.st.exec.error = extractErrorMessage(e);
3404
+ });
3405
+ } finally {
3406
+ runInAction2(() => {
3407
+ this.running = null;
3408
+ });
3409
+ }
3410
+ }
3411
+ async restartComfy() {
3412
+ runInAction2(() => {
3413
+ this.running = "restart";
3414
+ });
3415
+ try {
3416
+ await this.host.manager.restartComfyUI();
3417
+ runInAction2(() => {
3418
+ this.st.exec.notice = "reboot requested — the ws reconnects when the host is back";
3419
+ });
3420
+ } catch (e) {
3421
+ runInAction2(() => {
3422
+ this.st.exec.notice = `\uD83D\uDD34 reboot refused: ${extractErrorMessage(e)}`;
3423
+ });
3424
+ } finally {
3425
+ runInAction2(() => {
3426
+ this.running = null;
3427
+ });
3428
+ }
3429
+ }
3430
+ }
3431
+
3432
+ // src/cli/tui/state/LorasSt.ts
3433
+ import { makeAutoObservable as makeAutoObservable6, reaction as reaction4 } from "mobx";
3434
+ class LorasSt {
3435
+ st;
3436
+ constructor(st) {
3437
+ this.st = st;
3438
+ makeAutoObservable6(this, { st: false });
3439
+ this.st.disposers.push(reaction4(() => this.st.mode === "overlay-loras" ? this.selectedName : null, () => void this.refreshPreview(), { delay: this.st.timing.previewMs }));
3440
+ }
3441
+ ix = 0;
3442
+ filter = "";
3443
+ get selectedVar() {
3444
+ const sel = this.st.selected?.[1];
3445
+ return sel?.kind === "loras" ? sel : null;
3446
+ }
3447
+ get hostId() {
3448
+ return this.st.runHost.data.id;
3449
+ }
3450
+ get filteredNames() {
3451
+ const lv = this.selectedVar;
3452
+ if (lv == null)
3453
+ return [];
3454
+ if (this.filter === "")
3455
+ return lv.names;
3456
+ return lv.names.filter((n) => loraMatchesFilter(n, this.filter, this.hostId));
3457
+ }
3458
+ begin() {
3459
+ if (this.selectedVar == null)
3460
+ return;
3461
+ refreshLoraInfoCacheIfChanged();
3462
+ const lv = this.selectedVar;
3463
+ if (lv != null)
3464
+ lv.hostId = this.hostId;
3465
+ this.st.mode = "overlay-loras";
3466
+ this.ix = 0;
3467
+ this.filter = "";
3468
+ this.st.preview.clearOverlayImage();
3469
+ }
3470
+ move(delta) {
3471
+ const len = this.filteredNames.length;
3472
+ if (len === 0)
3473
+ return;
3474
+ this.ix = (this.ix + delta + len) % len;
3475
+ }
3476
+ filterInput(chunk) {
3477
+ this.filter += chunk;
3478
+ this.ix = 0;
3479
+ }
3480
+ filterBackspace() {
3481
+ this.filter = this.filter.slice(0, -1);
3482
+ this.ix = 0;
3483
+ }
3484
+ filterDeleteWord() {
3485
+ this.filter = this.filter.replace(/\s*\S+\s*$/, "");
3486
+ this.ix = 0;
3487
+ }
3488
+ toggle() {
3489
+ const lv = this.selectedVar;
3490
+ const name = this.filteredNames[this.ix];
3491
+ if (lv == null || name == null)
3492
+ return;
3493
+ lv.toggleItem(name);
3494
+ }
3495
+ setAll(on) {
3496
+ this.selectedVar?.setAll(on, this.filteredNames);
3497
+ }
3498
+ adjust(delta) {
3499
+ const lv = this.selectedVar;
3500
+ const name = this.filteredNames[this.ix];
3501
+ if (lv == null || name == null)
3502
+ return;
3503
+ lv.adjustItem(name, delta);
3504
+ }
3505
+ beginKeyword() {
3506
+ const name = this.selectedName;
3507
+ if (name == null)
3508
+ return;
3509
+ const fromMirror = loraKeywordFromMirror(name, this.hostId);
3510
+ const hint = fromMirror === "" ? "empty clears" : isLoraKeywordFromMirror(name, this.hostId) ? "from lora-manager · empty = inject nothing" : `overrides lora-manager · esc then ⌃D restores "${fromMirror}"`;
3511
+ this.st.editor.beginCustom({
3512
+ title: `keyword for ${LorasVar.shortName(name)} (${hint})`,
3513
+ initial: getLoraKeyword(name, this.hostId),
3514
+ onCommit: (raw) => {
3515
+ setLoraKeyword(name, raw, this.hostId);
3516
+ return true;
3517
+ },
3518
+ returnMode: "overlay-loras"
3519
+ });
3520
+ }
3521
+ resetKeyword() {
3522
+ const name = this.selectedName;
3523
+ if (name == null)
3524
+ return;
3525
+ clearLoraKeywordOverride(name);
3526
+ }
3527
+ get selectedName() {
3528
+ return this.filteredNames[this.ix] ?? null;
3529
+ }
3530
+ previewMap = undefined;
3531
+ previewMapHostId = null;
3532
+ previewSweepStatus = null;
3533
+ _busy = false;
3534
+ async refreshPreview() {
3535
+ if (this.st.mode !== "overlay-loras") {
3536
+ if (!this.st.preview.overlayActive)
3537
+ this.st.preview.clearOverlayImage();
3538
+ return;
3539
+ }
3540
+ const name = this.selectedName;
3541
+ if (name == null || this._busy)
3542
+ return;
3543
+ this._busy = true;
3544
+ try {
3545
+ const host = this.st.runHost;
3546
+ let url = getLoraPreviewUrl(name, host.data.id);
3547
+ let miss = "no preview available";
3548
+ if (url == null) {
3549
+ if (this.previewMap === undefined || this.previewMapHostId !== host.data.id) {
3550
+ const sweep = await fetchLoraList(host);
3551
+ this.previewMap = sweep.status === "absent" || sweep.status === "unreachable" ? null : loraPreviewMapFrom(sweep.items);
3552
+ this.previewSweepStatus = sweep.status;
3553
+ this.previewMapHostId = host.data.id;
3554
+ }
3555
+ url = this.previewMap?.get(loraKey(name)) ?? null;
3556
+ if (this.previewSweepStatus === "absent")
3557
+ miss = "lora-manager extension not detected";
3558
+ else if (this.previewSweepStatus === "unreachable")
3559
+ miss = "host unreachable";
3560
+ else if (this.previewSweepStatus === "partial")
3561
+ miss = "lora-manager answered only part of its list";
3562
+ }
3563
+ const note = url != null ? null : miss;
3564
+ if (url == null) {
3565
+ this.st.preview.setOverlayImage({ bytes: null, ansi: null, name: `lora ${name}`, note }, "overlay-loras");
3566
+ return;
3567
+ }
3568
+ const bytes = await fetchLoraPreviewBytes(host, url);
3569
+ if (bytes == null)
3570
+ throw new Error("no image preview on the server");
3571
+ if (this.st.preview.useNative) {
3572
+ this.st.preview.setOverlayImage({
3573
+ bytes: await protocolReadyBytes(bytes),
3574
+ ansi: null,
3575
+ name: `lora ${name}`,
3576
+ note: null
3577
+ }, "overlay-loras");
3578
+ return;
3579
+ }
3580
+ const ansi = await imageBufferToAnsi(bytes, { width: this.st.preview.width, height: this.st.preview.height });
3581
+ this.st.preview.setOverlayImage({ bytes: null, ansi, name: `lora ${name}`, note: null }, "overlay-loras");
3582
+ } catch (e) {
3583
+ this.st.preview.setOverlayImage({
3584
+ bytes: null,
3585
+ ansi: null,
3586
+ name: `lora ${name}`,
3587
+ note: extractErrorMessage(e)
3588
+ }, "overlay-loras");
3589
+ } finally {
3590
+ this._busy = false;
3591
+ if (this.st.mode === "overlay-loras" && this.selectedName !== name)
3592
+ this.refreshPreview();
3593
+ }
3594
+ }
3595
+ }
3596
+
3597
+ // src/cli/tui/state/PickerSt.ts
3598
+ import { makeAutoObservable as makeAutoObservable7 } from "mobx";
3599
+ class PickerSt {
3600
+ st;
3601
+ constructor(st) {
3602
+ this.st = st;
3603
+ makeAutoObservable7(this, { st: false });
3604
+ }
3605
+ filter = "";
3606
+ ix = 0;
3607
+ invalid = false;
3608
+ imageSizeRow = null;
3609
+ get choiceVar() {
3610
+ const sel = this.st.selected?.[1];
3611
+ return sel?.kind === "choice" ? sel : null;
3612
+ }
3613
+ isPicked(option) {
3614
+ const cv = this.choiceVar;
3615
+ if (cv == null)
3616
+ return false;
3617
+ return cv.select === "many" ? cv.value.includes(option) : cv.value === option;
3618
+ }
3619
+ get choiceIsMany() {
3620
+ return this.choiceVar?.select === "many";
3621
+ }
3622
+ get sizeVar() {
3623
+ const sel = this.st.selected?.[1];
3624
+ return sel?.kind === "size" ? sel : null;
3625
+ }
3626
+ get presetVar() {
3627
+ const sel = this.st.selected?.[1];
3628
+ if (sel == null || sel.kind !== "text" && sel.kind !== "prompt")
3629
+ return null;
3630
+ const withPresets = sel;
3631
+ return withPresets.presets.length === 0 ? null : withPresets;
3632
+ }
3633
+ get presetOptions() {
3634
+ const pv = this.presetVar;
3635
+ if (pv == null)
3636
+ return [];
3637
+ if (this.filter === "")
3638
+ return pv.presets;
3639
+ return pv.presets.filter((x) => fuzzyMatch(this.filter, `${x.label} ${x.text}`));
3640
+ }
3641
+ get options() {
3642
+ const pv = this.presetVar;
3643
+ if (pv != null)
3644
+ return this.presetOptions.map((x) => x.label);
3645
+ const cv = this.choiceVar;
3646
+ if (cv != null) {
3647
+ if (this.filter === "")
3648
+ return [...cv.choices];
3649
+ return cv.choices.filter((c) => fuzzyMatch(this.filter, c));
3650
+ }
3651
+ const sv = this.sizeVar;
3652
+ if (sv != null) {
3653
+ const labels = sv.presets.map((p) => `${p.width}×${p.height} ${p.label}`);
3654
+ if (this.imageSizeRow != null)
3655
+ labels.unshift(this.imageSizeRow);
3656
+ if (this.filter === "")
3657
+ return labels;
3658
+ return labels.filter((l) => fuzzyMatch(this.filter, l));
3659
+ }
3660
+ return [];
3661
+ }
3662
+ beginChoice() {
3663
+ const cv = this.choiceVar;
3664
+ if (cv == null)
3665
+ return;
3666
+ this.st.mode = "overlay-choice";
3667
+ this.filter = "";
3668
+ this.invalid = false;
3669
+ const first = cv.select === "many" ? cv.value[0] : cv.value;
3670
+ this.ix = Math.max(0, first == null ? 0 : cv.choices.indexOf(first));
3671
+ }
3672
+ beginPresets() {
3673
+ const pv = this.presetVar;
3674
+ if (pv == null)
3675
+ return;
3676
+ this.st.mode = "overlay-preset";
3677
+ this.filter = "";
3678
+ this.invalid = false;
3679
+ const value = pv.toEditBuffer().trim();
3680
+ const ix = pv.presets.findIndex((x) => x.text.trim() === value);
3681
+ this.ix = ix === -1 ? 0 : ix;
3682
+ }
3683
+ beginSize() {
3684
+ const sv = this.sizeVar;
3685
+ if (sv == null)
3686
+ return;
3687
+ this.st.mode = "overlay-size";
3688
+ this.filter = "";
3689
+ this.invalid = false;
3690
+ const img = sv.imageSize();
3691
+ this.imageSizeRow = img == null ? null : `${img.width}×${img.height} size of image '${img.name}'`;
3692
+ const presetIx = sv.presets.findIndex((p) => p.width === sv.value.width && p.height === sv.value.height);
3693
+ this.ix = presetIx === -1 ? 0 : presetIx + (this.imageSizeRow != null ? 1 : 0);
3694
+ }
3695
+ move(delta) {
3696
+ const len = this.options.length;
3697
+ if (len === 0)
3698
+ return;
3699
+ this.ix = (this.ix + delta + len) % len;
3700
+ }
3701
+ filterInput(chunk) {
3702
+ this.filter += chunk;
3703
+ this.ix = 0;
3704
+ this.invalid = false;
3705
+ }
3706
+ filterBackspace() {
3707
+ this.filter = this.filter.slice(0, -1);
3708
+ this.ix = 0;
3709
+ this.invalid = false;
3710
+ }
3711
+ filterDeleteWord() {
3712
+ this.filter = this.filter.replace(/\s*\S+\s*$/, "");
3713
+ this.ix = 0;
3714
+ this.invalid = false;
3715
+ }
3716
+ commit() {
3717
+ const pv = this.presetVar;
3718
+ if (pv != null) {
3719
+ const hit = this.presetOptions[this.ix];
3720
+ if (hit == null)
3721
+ return;
3722
+ pv.set(hit.text);
3723
+ this.st.mode = "nav";
3724
+ return;
3725
+ }
3726
+ const cv = this.choiceVar;
3727
+ if (cv != null) {
3728
+ const hit = cv.choices.find((c) => c === this.options[this.ix]);
3729
+ if (hit == null)
3730
+ return;
3731
+ if (cv.select === "many") {
3732
+ cv.toggle(hit);
3733
+ return;
3734
+ }
3735
+ if (cv.select === "zero-or-one")
3736
+ cv.toggle(hit);
3737
+ else
3738
+ cv.set(hit);
3739
+ this.st.mode = "nav";
3740
+ return;
3741
+ }
3742
+ const sv = this.sizeVar;
3743
+ if (sv == null)
3744
+ return;
3745
+ const hit = this.options[this.ix];
3746
+ if (hit != null) {
3747
+ const m = hit.match(/^(\d+)×(\d+)/);
3748
+ if (m != null)
3749
+ sv.set({ width: Number(m[1]), height: Number(m[2]) });
3750
+ this.st.mode = "nav";
3751
+ return;
3752
+ }
3753
+ if (sv.parse(this.filter))
3754
+ this.st.mode = "nav";
3755
+ else
3756
+ this.invalid = true;
3757
+ }
3758
+ }
3759
+
3760
+ // src/cli/tui/state/PreviewSt.ts
3761
+ import { makeAutoObservable as makeAutoObservable8, runInAction as runInAction3 } from "mobx";
3762
+ import sharp3 from "sharp";
3763
+ import { imageMeta as imageMeta2 } from "image-meta";
3764
+ var CORNER_FRACTION = 0.38;
3765
+ var PIXEL_SMALL_FRACTION = 0.4;
3766
+
3767
+ class PreviewSt {
3768
+ st;
3769
+ constructor(st) {
3770
+ this.st = st;
3771
+ makeAutoObservable8(this, { st: false });
3772
+ }
3773
+ outputAnsi = null;
3774
+ latentAnsi = null;
3775
+ outputBytes = null;
3776
+ latentBytes = null;
3777
+ latentDims = null;
3778
+ latentSeenThisRun = false;
3779
+ lastOutput = null;
3780
+ get show() {
3781
+ return this.st.settings.previewPanel;
3782
+ }
3783
+ get renderer() {
3784
+ return this.st.settings.previewRenderer;
3785
+ }
3786
+ get useNative() {
3787
+ return this.renderer === "native";
3788
+ }
3789
+ get duringRun() {
3790
+ return this.st.settings.previewDuringRun;
3791
+ }
3792
+ get menuOpen() {
3793
+ return this.st.mode === "preview";
3794
+ }
3795
+ overlay = null;
3796
+ get overlayActive() {
3797
+ return this.st.mode === "overlay-loras" || this.st.mode === "overlay-image";
3798
+ }
3799
+ setOverlayImage(p, owner) {
3800
+ if (this.st.mode !== owner)
3801
+ return;
3802
+ this.overlay = p;
3803
+ }
3804
+ clearOverlayImage() {
3805
+ this.overlay = null;
3806
+ }
3807
+ get latentsMissing() {
3808
+ return this.st.exec.running && this.duringRun !== "last-output" && (this.st.exec.progress?.percent ?? 0) >= 20 && !this.latentSeenThisRun;
3809
+ }
3810
+ menuIx = 0;
3811
+ get menuRows() {
3812
+ return [
3813
+ { key: "panel", label: "panel", value: this.show ? "on" : "off" },
3814
+ {
3815
+ key: "renderer",
3816
+ label: "renderer",
3817
+ value: this.renderer + (protocolCapable() ? "" : " (this terminal cannot show real images)")
3818
+ },
3819
+ {
3820
+ key: "during-run",
3821
+ label: "while running",
3822
+ value: this.duringRun === "latent" ? "latent" : this.duringRun === "latent-small" ? "latent small" : "last output"
3823
+ }
3824
+ ];
3825
+ }
3826
+ beginMenu() {
3827
+ this.st.mode = "preview";
3828
+ this.menuIx = 0;
3829
+ }
3830
+ blurMenu() {
3831
+ this.st.mode = "nav";
3832
+ }
3833
+ menuMove(delta) {
3834
+ const len = this.menuRows.length;
3835
+ this.menuIx = (this.menuIx + delta + len) % len;
3836
+ }
3837
+ menuCycle(delta) {
3838
+ const row = this.menuRows[this.menuIx];
3839
+ if (row == null)
3840
+ return;
3841
+ const s = this.st.settings;
3842
+ if (row.key === "panel") {
3843
+ s.previewPanel = !s.previewPanel;
3844
+ } else if (row.key === "renderer") {
3845
+ if (protocolCapable())
3846
+ s.previewRenderer = s.previewRenderer === "native" ? "pixel" : "native";
3847
+ } else {
3848
+ const order = ["latent", "latent-small", "last-output"];
3849
+ const ix = (order.indexOf(s.previewDuringRun) + delta + order.length) % order.length;
3850
+ s.previewDuringRun = order[ix] ?? "latent";
3851
+ }
3852
+ this.onSettingsChanged();
3853
+ }
3854
+ reset() {
3855
+ this.outputAnsi = null;
3856
+ this.latentAnsi = null;
3857
+ this.outputBytes = null;
3858
+ this.latentBytes = null;
3859
+ this.latentDims = null;
3860
+ this.latentSeenThisRun = false;
3861
+ this.lastOutput = null;
3862
+ }
3863
+ clearLatent() {
3864
+ this.latentAnsi = null;
3865
+ this.latentBytes = null;
3866
+ this.latentDims = null;
3867
+ this.latentSeenThisRun = false;
3868
+ }
3869
+ onSettingsChanged() {
3870
+ this.outputAnsi = null;
3871
+ this.outputBytes = null;
3872
+ if (this.show && this.lastOutput != null)
3873
+ this.renderOutput(this.lastOutput);
3874
+ }
3875
+ get protocolImage() {
3876
+ if (!this.useNative || !this.show || this.menuOpen)
3877
+ return null;
3878
+ if (this.overlayActive)
3879
+ return this.overlay?.bytes ?? null;
3880
+ if (this.st.exec.running) {
3881
+ if (this.duringRun === "latent")
3882
+ return this.latentBytes ?? this.outputBytes;
3883
+ return this.outputBytes;
3884
+ }
3885
+ return this.outputBytes;
3886
+ }
3887
+ get protocolImageCorner() {
3888
+ if (!this.useNative || !this.show || this.menuOpen)
3889
+ return null;
3890
+ if (this.overlayActive)
3891
+ return null;
3892
+ if (this.st.exec.running && this.duringRun === "latent-small")
3893
+ return this.latentBytes;
3894
+ return null;
3895
+ }
3896
+ get cornerBox() {
3897
+ let w = Math.max(8, Math.floor(this.width * CORNER_FRACTION));
3898
+ const maxH = Math.max(4, Math.floor(this.height * CORNER_FRACTION));
3899
+ const dims = this.latentDims;
3900
+ if (dims == null || dims.width === 0 || dims.height === 0)
3901
+ return { w, h: maxH };
3902
+ const aspect = dims.width / dims.height;
3903
+ let h = Math.max(2, Math.round(w / aspect / 2));
3904
+ if (h > maxH) {
3905
+ h = maxH;
3906
+ w = Math.max(4, Math.round(h * aspect * 2));
3907
+ }
3908
+ return { w, h };
3909
+ }
3910
+ get width() {
3911
+ return Math.max(24, Math.min(80, this.st.termCols - 68 - this.st.treeWidth));
3912
+ }
3913
+ get height() {
3914
+ return Math.max(10, this.st.termRows - 12);
3915
+ }
3916
+ async renderOutput(src) {
3917
+ this.lastOutput = src;
3918
+ if (!this.show)
3919
+ return;
3920
+ try {
3921
+ if (this.useNative) {
3922
+ const shrunk = await sharp3(src).resize(896, 896, { fit: "inside", withoutEnlargement: true }).png().toBuffer();
3923
+ runInAction3(() => {
3924
+ this.outputBytes = new Uint8Array(shrunk);
3925
+ });
3926
+ return;
3927
+ }
3928
+ const rendered = await imageBufferToAnsi(src, { width: this.width, height: this.height });
3929
+ runInAction3(() => {
3930
+ this.outputAnsi = rendered;
3931
+ });
3932
+ } catch (e) {
3933
+ runInAction3(() => {
3934
+ this.st.exec.notice = `preview: ${extractErrorMessage(e)}`;
3935
+ });
3936
+ }
3937
+ }
3938
+ _busy = false;
3939
+ async renderLatent(bytes) {
3940
+ runInAction3(() => {
3941
+ this.latentSeenThisRun = true;
3942
+ });
3943
+ if (!this.show || this.duringRun === "last-output")
3944
+ return;
3945
+ if (this.useNative) {
3946
+ const meta = imageMeta2(bytes);
3947
+ const dims = meta.width != null && meta.height != null ? { width: meta.width, height: meta.height } : null;
3948
+ if (imageProtocol() !== "kitty") {
3949
+ this.latentBytes = bytes;
3950
+ this.latentDims = dims;
3951
+ return;
3952
+ }
3953
+ if (this._busy)
3954
+ return;
3955
+ this._busy = true;
3956
+ try {
3957
+ const png = await protocolReadyBytes(bytes);
3958
+ runInAction3(() => {
3959
+ this.latentBytes = png;
3960
+ this.latentDims = dims;
3961
+ });
3962
+ } catch (e) {
3963
+ runInAction3(() => {
3964
+ this.st.exec.notice = `latent preview: ${extractErrorMessage(e)}`;
3965
+ });
3966
+ } finally {
3967
+ this._busy = false;
3968
+ }
3969
+ return;
3970
+ }
3971
+ if (this._busy)
3972
+ return;
3973
+ this._busy = true;
3974
+ try {
3975
+ const ansi = this.duringRun === "latent-small" ? await this.renderLatentSmallPixel(bytes) : await imageBufferToAnsi(bytes, { width: this.width, height: this.height });
3976
+ runInAction3(() => {
3977
+ this.latentAnsi = ansi;
3978
+ });
3979
+ } catch (e) {
3980
+ runInAction3(() => {
3981
+ this.st.exec.notice = `latent preview: ${extractErrorMessage(e)}`;
3982
+ });
3983
+ } finally {
3984
+ this._busy = false;
3985
+ }
3986
+ }
3987
+ async renderLatentSmallPixel(bytes) {
3988
+ const pxW = this.width;
3989
+ const pxH = this.height * 2;
3990
+ const thumb = await sharp3(bytes).resize(Math.max(8, Math.floor(pxW * PIXEL_SMALL_FRACTION)), Math.max(8, Math.floor(pxH * PIXEL_SMALL_FRACTION)), { fit: "inside" }).png().toBuffer();
3991
+ const out = this.lastOutput;
3992
+ if (out == null)
3993
+ return imageBufferToAnsi(thumb, { width: this.width, height: this.height });
3994
+ const base = await sharp3(out).resize(pxW, pxH, { fit: "inside" }).png().toBuffer();
3995
+ const composed = await sharp3(base).composite([{ input: thumb, gravity: "northeast" }]).png().toBuffer();
3996
+ return imageBufferToAnsi(composed, { width: this.width, height: this.height });
3997
+ }
3998
+ }
3999
+
4000
+ // src/cli/tui/state/QueueSt.ts
4001
+ import { makeAutoObservable as makeAutoObservable9, runInAction as runInAction4 } from "mobx";
4002
+ class QueueSt {
4003
+ st;
4004
+ constructor(st) {
4005
+ this.st = st;
4006
+ makeAutoObservable9(this, { st: false });
4007
+ this.attach(this.st.wf.host);
4008
+ this.st.disposers.push(() => {
4009
+ if (this.attached != null)
4010
+ this.attached.onStatus = null;
4011
+ });
4012
+ }
4013
+ remaining = 0;
4014
+ attached = null;
4015
+ attach(host) {
4016
+ if (this.attached === host)
4017
+ return;
4018
+ if (this.attached != null)
4019
+ this.attached.onStatus = null;
4020
+ this.attached = host;
4021
+ this.remaining = 0;
4022
+ host.onStatus = (p) => {
4023
+ runInAction4(() => {
4024
+ this.remaining = p.queueRemaining;
4025
+ });
4026
+ };
4027
+ }
4028
+ async clearPending() {
4029
+ try {
4030
+ await this.st.runHost.clearQueue();
4031
+ runInAction4(() => {
4032
+ this.st.exec.notice = "pending queue cleared";
4033
+ });
4034
+ } catch (e) {
4035
+ runInAction4(() => {
4036
+ this.st.exec.error = extractErrorMessage(e);
4037
+ });
4038
+ }
4039
+ }
4040
+ async interrupt() {
4041
+ try {
4042
+ await this.st.runHost.interrupt();
4043
+ runInAction4(() => {
4044
+ this.st.exec.notice = "interrupt requested";
4045
+ });
4046
+ } catch (e) {
4047
+ runInAction4(() => {
4048
+ this.st.exec.error = extractErrorMessage(e);
4049
+ });
4050
+ }
4051
+ }
4052
+ }
4053
+
4054
+ // src/cli/tui/state/SettingsSt.ts
4055
+ import { existsSync as existsSync4, mkdirSync as mkdirSync2, readFileSync as readFileSync3, writeFileSync as writeFileSync3 } from "node:fs";
4056
+ import { makeAutoObservable as makeAutoObservable10, reaction as reaction5, runInAction as runInAction5 } from "mobx";
4057
+ import { dirname as dirname4 } from "pathe";
4058
+ function migratePreviewSettings(raw, defaults) {
4059
+ const out = { ...defaults };
4060
+ const legacy = raw.previewMode;
4061
+ if (legacy === "native")
4062
+ out.previewRenderer = "native";
4063
+ if (legacy === "ansi")
4064
+ out.previewRenderer = "pixel";
4065
+ if (legacy === "off")
4066
+ out.previewPanel = false;
4067
+ if (typeof raw.previewPanel === "boolean")
4068
+ out.previewPanel = raw.previewPanel;
4069
+ if (raw.previewRenderer === "native" || raw.previewRenderer === "pixel")
4070
+ out.previewRenderer = raw.previewRenderer;
4071
+ if (raw.previewDuringRun === "latent" || raw.previewDuringRun === "latent-small" || raw.previewDuringRun === "last-output")
4072
+ out.previewDuringRun = raw.previewDuringRun;
4073
+ return out;
4074
+ }
4075
+
4076
+ class SettingsSt {
4077
+ st;
4078
+ constructor(st) {
4079
+ this.st = st;
4080
+ this.load();
4081
+ if (this.previewRenderer === "native" && !protocolCapable())
4082
+ this.previewRenderer = "pixel";
4083
+ makeAutoObservable10(this, { st: false });
4084
+ this.st.disposers.push(reaction5(() => this.snapshotJson(), (json) => this.write(json), { delay: this.st.timing.autosaveMs }));
4085
+ this.st.disposers.push(() => this.write(this.snapshotJson()));
4086
+ }
4087
+ snapshotJson() {
4088
+ return JSON.stringify({
4089
+ previewPanel: this.previewPanel,
4090
+ previewRenderer: this.previewRenderer,
4091
+ previewDuringRun: this.previewDuringRun,
4092
+ lastDraft: this.lastDraft,
4093
+ lastWorkflow: this.lastWorkflow,
4094
+ hostOverrideId: this.hostOverrideId,
4095
+ collapsedDirs: this.collapsedDirs,
4096
+ saveToDisk: this.saveToDisk,
4097
+ savePrefix: this.savePrefix
4098
+ });
4099
+ }
4100
+ previewPanel = true;
4101
+ previewRenderer = protocolCapable() ? "native" : "pixel";
4102
+ previewDuringRun = "latent";
4103
+ lastDraft = {};
4104
+ lastWorkflow = null;
4105
+ hostOverrideId = null;
4106
+ collapsedDirs = [];
4107
+ saveToDisk = true;
4108
+ savePrefix = {};
4109
+ rememberDraft(moduleKey, draft) {
4110
+ this.lastDraft[moduleKey] = draft;
4111
+ }
4112
+ load() {
4113
+ const path = comfyts.settingsPath;
4114
+ if (!existsSync4(path))
4115
+ return;
4116
+ try {
4117
+ const raw = JSON.parse(readFileSync3(path, "utf8"));
4118
+ if (raw == null || typeof raw !== "object")
4119
+ return;
4120
+ const o = raw;
4121
+ const preview = migratePreviewSettings(o, {
4122
+ previewPanel: this.previewPanel,
4123
+ previewRenderer: this.previewRenderer,
4124
+ previewDuringRun: this.previewDuringRun
4125
+ });
4126
+ this.previewPanel = preview.previewPanel;
4127
+ this.previewRenderer = preview.previewRenderer;
4128
+ this.previewDuringRun = preview.previewDuringRun;
4129
+ if (o.lastDraft != null && typeof o.lastDraft === "object")
4130
+ this.lastDraft = { ...o.lastDraft };
4131
+ if (typeof o.lastWorkflow === "string")
4132
+ this.lastWorkflow = o.lastWorkflow;
4133
+ if (typeof o.hostOverrideId === "string")
4134
+ this.hostOverrideId = o.hostOverrideId;
4135
+ if (Array.isArray(o.collapsedDirs))
4136
+ this.collapsedDirs = o.collapsedDirs.filter((d) => typeof d === "string");
4137
+ if (typeof o.saveToDisk === "boolean")
4138
+ this.saveToDisk = o.saveToDisk;
4139
+ if (o.savePrefix != null && typeof o.savePrefix === "object")
4140
+ this.savePrefix = Object.fromEntries(Object.entries(o.savePrefix).filter((kv) => typeof kv[1] === "string"));
4141
+ } catch {}
4142
+ }
4143
+ write(json) {
4144
+ const path = comfyts.settingsPath;
4145
+ try {
4146
+ mkdirSync2(dirname4(path), { recursive: true });
4147
+ writeFileSync3(path, json);
4148
+ } catch (e) {
4149
+ runInAction5(() => {
4150
+ this.st.exec.notice = `settings save failed: ${String(e)}`;
4151
+ });
4152
+ }
4153
+ }
4154
+ }
4155
+
4156
+ // src/cli/tui/state/TreeSt.ts
4157
+ import { makeAutoObservable as makeAutoObservable11 } from "mobx";
4158
+ class TreeSt {
4159
+ st;
4160
+ constructor(st) {
4161
+ this.st = st;
4162
+ this.collapsedDirs = new Set(st.settings.collapsedDirs);
4163
+ makeAutoObservable11(this, { st: false });
4164
+ }
4165
+ ix = 0;
4166
+ expandedFiles = new Set;
4167
+ collapsedDirs;
4168
+ persistFolds() {
4169
+ this.st.settings.collapsedDirs = [...this.collapsedDirs];
4170
+ }
4171
+ filter = "";
4172
+ filtering = false;
4173
+ get familyColors() {
4174
+ return assignFamilyColors(this.st.workflows.files);
4175
+ }
4176
+ get rows() {
4177
+ this.st.drafts.version;
4178
+ const w = this.st.workflows;
4179
+ const fileRows = buildFileRows({
4180
+ userFiles: w.files.filter((f) => !w.bundled.has(f)),
4181
+ bundledFiles: w.files.filter((f) => w.bundled.has(f)),
4182
+ collapsedDirs: this.collapsedDirs,
4183
+ filter: this.filter
4184
+ });
4185
+ const colors = this.familyColors;
4186
+ const rows = [];
4187
+ for (const row of fileRows) {
4188
+ if (row.kind === "dir") {
4189
+ rows.push(row);
4190
+ continue;
4191
+ }
4192
+ const current = row.file === w.currentPath;
4193
+ const expanded = this.expandedFiles.has(row.file);
4194
+ const drafts = listDraftsForFile(row.file);
4195
+ rows.push({
4196
+ kind: "workflow",
4197
+ file: row.file,
4198
+ name: row.name,
4199
+ depth: row.depth,
4200
+ expanded,
4201
+ current,
4202
+ hasDrafts: drafts.length > 0,
4203
+ error: w.loadErrors.get(row.file) ?? null,
4204
+ color: w.specColors.get(row.file) ?? colors.get(familyOf(row.name)) ?? "white"
4205
+ });
4206
+ if (!expanded)
4207
+ continue;
4208
+ for (const draft of drafts) {
4209
+ rows.push({
4210
+ kind: "draft",
4211
+ file: row.file,
4212
+ draft,
4213
+ active: current && draft === this.st.drafts.active,
4214
+ depth: row.depth + 1
4215
+ });
4216
+ }
4217
+ }
4218
+ return rows;
4219
+ }
4220
+ get selected() {
4221
+ return this.rows[this.ix];
4222
+ }
4223
+ focus() {
4224
+ const w = this.st.workflows;
4225
+ if (w.files.length === 0) {
4226
+ this.st.exec.notice = "no workflow tree — start the tui in a folder containing **/*.cflow.ts";
4227
+ return;
4228
+ }
4229
+ if (w.currentPath != null) {
4230
+ this.expandedFiles.add(w.currentPath);
4231
+ let changed = false;
4232
+ const collapsed = [...this.collapsedDirs];
4233
+ for (const dir of collapsed) {
4234
+ if (w.currentPath.startsWith(`${dir}/`)) {
4235
+ this.collapsedDirs.delete(dir);
4236
+ changed = true;
4237
+ }
4238
+ }
4239
+ if (changed)
4240
+ this.persistFolds();
4241
+ }
4242
+ this.st.mode = "tree";
4243
+ const rows = this.rows;
4244
+ const draftIx = rows.findIndex((r) => r.kind === "draft" && r.active);
4245
+ const ix = draftIx === -1 ? rows.findIndex((r) => r.kind === "workflow" && r.current) : draftIx;
4246
+ this.ix = ix === -1 ? 0 : ix;
4247
+ }
4248
+ viewH = 0;
4249
+ setViewH(h) {
4250
+ this.viewH = h;
4251
+ }
4252
+ get viewBudget() {
4253
+ const h = this.viewH > 0 ? this.viewH : Math.max(5, this.st.termRows - 5);
4254
+ const filterLine = this.filtering || this.filter !== "" ? 1 : 0;
4255
+ const loadingLine = this.st.workflows.loading ? 1 : 0;
4256
+ return Math.max(1, h - 2 - filterLine - loadingLine);
4257
+ }
4258
+ get window() {
4259
+ return listWindow({ count: this.rows.length, selected: this.ix, budget: this.viewBudget });
4260
+ }
4261
+ blur() {
4262
+ this.filtering = false;
4263
+ this.st.mode = "nav";
4264
+ }
4265
+ move(delta) {
4266
+ const len = this.rows.length;
4267
+ if (len === 0)
4268
+ return;
4269
+ this.ix = (this.ix + delta + len) % len;
4270
+ }
4271
+ beginFilter() {
4272
+ this.filtering = true;
4273
+ }
4274
+ filterInput(ch) {
4275
+ this.filter += ch;
4276
+ this.clampToSelectable();
4277
+ }
4278
+ filterBackspace() {
4279
+ this.filter = this.filter.slice(0, -1);
4280
+ this.clampToSelectable();
4281
+ }
4282
+ clearFilter() {
4283
+ this.filter = "";
4284
+ this.filtering = false;
4285
+ this.clampToSelectable();
4286
+ }
4287
+ clampToSelectable() {
4288
+ const rows = this.rows;
4289
+ this.ix = Math.min(this.ix, Math.max(0, rows.length - 1));
4290
+ if (rows[this.ix]?.kind !== "workflow") {
4291
+ const first = rows.findIndex((r) => r.kind === "workflow");
4292
+ if (first !== -1)
4293
+ this.ix = first;
4294
+ }
4295
+ }
4296
+ unfold() {
4297
+ const row = this.selected;
4298
+ if (row == null)
4299
+ return;
4300
+ if (row.kind === "dir") {
4301
+ this.collapsedDirs.delete(row.path);
4302
+ this.persistFolds();
4303
+ } else if (row.kind === "workflow")
4304
+ this.expandedFiles.add(row.file);
4305
+ else
4306
+ this.blur();
4307
+ }
4308
+ fold() {
4309
+ const row = this.selected;
4310
+ if (row == null)
4311
+ return;
4312
+ if (row.kind === "dir") {
4313
+ this.collapsedDirs.add(row.path);
4314
+ this.persistFolds();
4315
+ return;
4316
+ }
4317
+ if (row.kind === "draft") {
4318
+ const ix = this.rows.findIndex((r) => r.kind === "workflow" && r.file === row.file);
4319
+ if (ix !== -1)
4320
+ this.ix = ix;
4321
+ this.expandedFiles.delete(row.file);
4322
+ return;
4323
+ }
4324
+ if (row.expanded) {
4325
+ this.expandedFiles.delete(row.file);
4326
+ return;
4327
+ }
4328
+ for (let ix = this.ix - 1;ix >= 0; ix--) {
4329
+ const r = this.rows[ix];
4330
+ if (r?.kind === "dir" && r.depth < row.depth) {
4331
+ this.ix = ix;
4332
+ return;
4333
+ }
4334
+ }
4335
+ }
4336
+ async commit() {
4337
+ const row = this.selected;
4338
+ if (row == null)
4339
+ return;
4340
+ if (row.kind === "dir") {
4341
+ if (this.filter !== "")
4342
+ return;
4343
+ if (row.expanded)
4344
+ this.collapsedDirs.add(row.path);
4345
+ else
4346
+ this.collapsedDirs.delete(row.path);
4347
+ this.persistFolds();
4348
+ return;
4349
+ }
4350
+ this.filter = "";
4351
+ this.filtering = false;
4352
+ if (row.kind === "workflow")
4353
+ return this.st.workflows.commit(row.file);
4354
+ return this.st.workflows.commit(row.file, row.draft);
4355
+ }
4356
+ promptNewDraft() {
4357
+ const row = this.selected;
4358
+ if (row?.kind === "dir")
4359
+ return;
4360
+ if (row != null && row.file !== this.st.workflows.currentPath) {
4361
+ this.st.exec.notice = "load that workflow first (⏎) — a new draft snapshots its live vars";
4362
+ return;
4363
+ }
4364
+ this.st.drafts.promptNew("tree");
4365
+ }
4366
+ draftOp(op) {
4367
+ const row = this.selected;
4368
+ if (row?.kind !== "draft") {
4369
+ this.st.exec.notice = "select a draft row (unfold a workflow with →)";
4370
+ return;
4371
+ }
4372
+ if (op === "rename")
4373
+ return this.st.drafts.promptRename(row.draft, row.file, "tree");
4374
+ if (op === "duplicate")
4375
+ return this.st.drafts.promptDuplicate(row.draft, row.file, "tree");
4376
+ this.st.drafts.deleteDraft(row.draft, row.file);
4377
+ this.ix = Math.min(this.ix, Math.max(0, this.rows.length - 1));
4378
+ }
4379
+ }
4380
+
4381
+ // src/cli/tui/state/WorkflowsSt.ts
4382
+ import { pathToFileURL } from "node:url";
4383
+ import { makeAutoObservable as makeAutoObservable12, runInAction as runInAction6 } from "mobx";
4384
+ import { basename as basename3, resolve as resolve2 } from "pathe";
4385
+ class WorkflowsSt {
4386
+ st;
4387
+ files;
4388
+ constructor(st, files, currentPath = null, bundled = new Set, loadErrors = new Map) {
4389
+ this.st = st;
4390
+ this.files = files;
4391
+ this.currentPath = currentPath;
4392
+ this.bundled = bundled;
4393
+ this.loadErrors = loadErrors;
4394
+ makeAutoObservable12(this, { st: false });
4395
+ }
4396
+ currentPath;
4397
+ loading = false;
4398
+ bundled;
4399
+ loadErrors;
4400
+ specColors = new Map;
4401
+ recordSpecColor(path, wf) {
4402
+ if (wf.spec.color != null)
4403
+ this.specColors.set(path, wf.spec.color);
4404
+ }
4405
+ loadedHosts = new Set;
4406
+ disconnectAllHosts() {
4407
+ this.loadedHosts.add(this.st.wf.host);
4408
+ for (const host of this.loadedHosts)
4409
+ host.disconnect();
4410
+ }
4411
+ async commit(path, draft = null) {
4412
+ if (path === this.currentPath) {
4413
+ if (this.loading)
4414
+ return;
4415
+ if (draft == null)
4416
+ this.st.drafts.activateRemembered();
4417
+ else
4418
+ this.st.drafts.activate(draft);
4419
+ this.st.mode = "nav";
4420
+ return;
4421
+ }
4422
+ return this.load(path, draft, false);
4423
+ }
4424
+ async reload(draft) {
4425
+ const path = this.currentPath;
4426
+ if (path == null)
4427
+ return;
4428
+ return this.load(path, draft, true);
4429
+ }
4430
+ async load(path, draft, bustCache) {
4431
+ if (this.loading)
4432
+ return;
4433
+ runInAction6(() => {
4434
+ this.loading = true;
4435
+ });
4436
+ try {
4437
+ const url = pathToFileURL(resolve2(path)).href + (bustCache ? `?v=${Date.now()}` : "");
4438
+ const mod = await import(url);
4439
+ const wf = findDefinedWorkflow(mod);
4440
+ if (wf == null)
4441
+ throw new Error(`${path} exports no DefinedWorkflow`);
4442
+ runInAction6(() => {
4443
+ this.loadErrors.delete(path);
4444
+ this.loadedHosts.add(this.st.wf.host);
4445
+ this.loadedHosts.add(wf.host);
4446
+ this.recordSpecColor(path, wf);
4447
+ this.st.wf = wf;
4448
+ this.st.applyPersistedHostOverride();
4449
+ this.st.queue.attach(this.st.runHost);
4450
+ this.st.logs.attach(this.st.runHost);
4451
+ this.currentPath = path;
4452
+ this.st.settings.lastWorkflow = path;
4453
+ this.st.selIx = 0;
4454
+ this.st.mode = "nav";
4455
+ this.st.exec.resetForWorkflow(`${basename3(path)}`);
4456
+ if (draft == null)
4457
+ this.st.drafts.activateRemembered();
4458
+ else
4459
+ this.st.drafts.activate(draft);
4460
+ this.st.preview.reset();
4461
+ });
4462
+ } catch (e) {
4463
+ runInAction6(() => {
4464
+ const msg = extractErrorMessage(e);
4465
+ this.loadErrors.set(path, msg);
4466
+ this.st.mode = "nav";
4467
+ this.st.exec.error = msg;
4468
+ });
4469
+ } finally {
4470
+ runInAction6(() => {
4471
+ this.loading = false;
4472
+ });
4473
+ }
4474
+ }
4475
+ }
4476
+
4477
+ // src/cli/tui/state/TuiSt.ts
4478
+ var TUI_TIMING = { previewMs: 120, autosaveMs: 300 };
4479
+
4480
+ class TuiSt {
4481
+ wf;
4482
+ mode = "nav";
4483
+ selIx = 0;
4484
+ hostOverride = null;
4485
+ get runHost() {
4486
+ return this.hostOverride ?? this.wf.host;
4487
+ }
4488
+ setHostOverride(host) {
4489
+ this.hostOverride = host;
4490
+ if (host != null)
4491
+ this.workflows.loadedHosts.add(host);
4492
+ this.queue.attach(this.runHost);
4493
+ this.logs.attach(this.runHost);
4494
+ this.settings.hostOverrideId = host?.data.id ?? null;
4495
+ }
4496
+ applyPersistedHostOverride() {
4497
+ const id = this.settings.hostOverrideId;
4498
+ if (id == null || this.hostOverride != null)
4499
+ return;
4500
+ const host = comfyts.hosts.get(id);
4501
+ if (host != null)
4502
+ this.setHostOverride(host);
4503
+ }
4504
+ editor;
4505
+ picker;
4506
+ loras;
4507
+ imagePicker;
4508
+ workflows;
4509
+ tree;
4510
+ drafts;
4511
+ exec;
4512
+ preview;
4513
+ host;
4514
+ queue;
4515
+ logs;
4516
+ settings;
4517
+ timing;
4518
+ disposers = [];
4519
+ onExit = () => {};
4520
+ constructor(wf, opts = {}) {
4521
+ this.wf = wf;
4522
+ this.timing = opts.timing ?? TUI_TIMING;
4523
+ makeAutoObservable13(this, {
4524
+ wf: observableRef,
4525
+ hostOverride: observableRef,
4526
+ onExit: false,
4527
+ timing: false,
4528
+ editor: false,
4529
+ picker: false,
4530
+ loras: false,
4531
+ imagePicker: false,
4532
+ workflows: false,
4533
+ tree: false,
4534
+ drafts: false,
4535
+ exec: false,
4536
+ preview: false,
4537
+ host: false,
4538
+ queue: false,
4539
+ logs: false,
4540
+ settings: false
4541
+ });
4542
+ this.settings = new SettingsSt(this);
4543
+ this.editor = new EditorSt(this);
4544
+ this.picker = new PickerSt(this);
4545
+ this.loras = new LorasSt(this);
4546
+ this.imagePicker = new ImagePickerSt(this);
4547
+ this.workflows = new WorkflowsSt(this, opts.workflowFiles ?? [], opts.currentFile ?? null, opts.bundledFiles, opts.loadErrors);
4548
+ this.tree = new TreeSt(this);
4549
+ this.drafts = new DraftsSt(this);
4550
+ this.exec = new ExecSt(this);
4551
+ this.preview = new PreviewSt(this);
4552
+ this.host = new HostSt(this);
4553
+ this.queue = new QueueSt(this);
4554
+ this.logs = new LogsSt(this);
4555
+ this.applyPersistedHostOverride();
4556
+ this.drafts.activateRemembered();
4557
+ if (opts.currentFile != null) {
4558
+ const currentFile = opts.currentFile;
4559
+ runInAction7(() => {
4560
+ this.tree.expandedFiles.add(currentFile);
4561
+ this.workflows.recordSpecColor(currentFile, wf);
4562
+ this.settings.lastWorkflow = currentFile;
4563
+ });
4564
+ }
4565
+ const onResize = () => {
4566
+ runInAction7(() => {
4567
+ this.termCols = process.stdout.columns ?? 80;
4568
+ this.termRows = (process.stdout.rows ?? 24) - 1;
4569
+ });
4570
+ };
4571
+ process.stdout.on?.("resize", onResize);
4572
+ this.disposers.push(() => process.stdout.off?.("resize", onResize));
4573
+ }
4574
+ dispose() {
4575
+ for (const d of this.disposers.splice(0))
4576
+ d();
4577
+ this.workflows.disconnectAllHosts();
4578
+ }
4579
+ termCols = process.stdout.columns ?? 80;
4580
+ termRows = (process.stdout.rows ?? 24) - 1;
4581
+ get overlayLines() {
4582
+ return Math.max(8, this.termRows - 12);
4583
+ }
4584
+ get treeWidth() {
4585
+ const longest = Math.max(8, ...this.tree.rows.map((r) => r.depth * 2 + (r.kind === "workflow" ? r.name.length : r.kind === "draft" ? r.draft.length + 3 : r.label.length + 2)));
4586
+ return Math.min(34, longest + 7);
4587
+ }
4588
+ get entries() {
4589
+ return this.wf.entries();
4590
+ }
4591
+ get selected() {
4592
+ return this.entries[this.selIx];
4593
+ }
4594
+ get moduleKey() {
4595
+ const cur = this.workflows.currentPath;
4596
+ return cur != null ? draftKeyForFile(cur) : this.wf.spec.id ?? "workflow";
4597
+ }
4598
+ get savePrefix() {
4599
+ return this.settings.savePrefix[this.moduleKey] ?? this.moduleKey;
4600
+ }
4601
+ setSavePrefix(raw) {
4602
+ const trimmed = raw.trim().replace(/^\/+|\/+$/g, "");
4603
+ if (trimmed === "" || trimmed === this.moduleKey)
4604
+ delete this.settings.savePrefix[this.moduleKey];
4605
+ else
4606
+ this.settings.savePrefix[this.moduleKey] = trimmed;
4607
+ }
4608
+ get varRowCount() {
4609
+ return this.entries.length + (this.settings.saveToDisk ? 2 : 1);
4610
+ }
4611
+ get onSaveRow() {
4612
+ return this.selIx === this.entries.length;
4613
+ }
4614
+ get onPrefixRow() {
4615
+ return this.settings.saveToDisk && this.selIx === this.entries.length + 1;
4616
+ }
4617
+ moveSel(delta) {
4618
+ const len = this.varRowCount;
4619
+ this.selIx = (this.selIx + delta + len) % len;
4620
+ }
4621
+ varsViewH = 0;
4622
+ setVarsViewH(h) {
4623
+ this.varsViewH = h;
4624
+ }
4625
+ get varsBudget() {
4626
+ const h = this.varsViewH > 0 ? this.varsViewH : Math.max(5, this.termRows - 5);
4627
+ return Math.max(1, h - 2);
4628
+ }
4629
+ get varsWindow() {
4630
+ return listWindow({ count: this.varRowCount, selected: this.selIx, budget: this.varsBudget });
4631
+ }
4632
+ get varsCompact() {
4633
+ const w = this.varsWindow;
4634
+ if (w.moreAbove || w.moreBelow)
4635
+ return true;
4636
+ const h = this.varsViewH > 0 ? this.varsViewH : Math.max(5, this.termRows - 5);
4637
+ return this.varRowCount + 2 > h;
4638
+ }
4639
+ activate() {
4640
+ if (this.onSaveRow) {
4641
+ this.settings.saveToDisk = !this.settings.saveToDisk;
4642
+ return;
4643
+ }
4644
+ if (this.onPrefixRow) {
4645
+ this.editor.beginCustom({
4646
+ title: `save prefix — dir under .comfy-ts/outputs/ (empty = ${this.moduleKey})`,
4647
+ initial: this.savePrefix,
4648
+ onCommit: (raw) => {
4649
+ this.setSavePrefix(raw);
4650
+ return true;
4651
+ }
4652
+ });
4653
+ return;
4654
+ }
4655
+ const sel = this.selected?.[1];
4656
+ if (sel == null)
4657
+ return;
4658
+ if (sel.kind === "toggle")
4659
+ sel.toggle();
4660
+ else if (sel.kind === "text" || sel.kind === "prompt")
4661
+ this.editor.beginMultiline();
4662
+ else if (sel.kind === "choice")
4663
+ this.picker.beginChoice();
4664
+ else if (sel.kind === "size")
4665
+ this.picker.beginSize();
4666
+ else if (sel.kind === "loras")
4667
+ this.loras.begin();
4668
+ else if (sel.kind === "image" || sel.kind === "audio" || sel.kind === "video")
4669
+ this.imagePicker.begin();
4670
+ else
4671
+ this.editor.beginInline();
4672
+ }
4673
+ navKey(input) {
4674
+ const sel = this.selected?.[1];
4675
+ if (sel?.kind === "seed") {
4676
+ if (input === "+" || input === "-" || input === "=" || input === "?") {
4677
+ sel.setMode(input);
4678
+ return true;
4679
+ }
4680
+ if (input === "*") {
4681
+ sel.randomize();
4682
+ return true;
4683
+ }
4684
+ }
4685
+ return false;
4686
+ }
4687
+ }
4688
+
4689
+ // src/cli/tui/run-tui.tsx
4690
+ import { jsx as jsx19 } from "react/jsx-runtime";
4691
+ function rememberedWorkflow(workflowFiles, settingsPath = settingsPathFor(process.cwd())) {
4692
+ try {
4693
+ const raw = JSON.parse(readFileSync4(settingsPath, "utf8"));
4694
+ if (raw == null || typeof raw !== "object")
4695
+ return null;
4696
+ const last = raw.lastWorkflow;
4697
+ return typeof last === "string" && workflowFiles.includes(last) ? last : null;
4698
+ } catch {
4699
+ return null;
4700
+ }
4701
+ }
4702
+ async function runTui(args) {
4703
+ const target = args.find((a) => !a.startsWith("--"));
4704
+ process.env[COMFY_TS_TUI_ENV] = "1";
4705
+ process.env.COMFY_TS_QUIET = "1";
4706
+ const abs = realpathSync(resolve3(target ?? "."));
4707
+ const isDir = statSync3(abs).isDirectory();
4708
+ const scanned = scanCflowFiles(isDir ? abs : dirname5(abs));
4709
+ const scannedPlusArg = isDir || scanned.includes(abs) ? scanned : [abs, ...scanned];
4710
+ const canImportBundled = process.versions.bun != null;
4711
+ const examplesDir = canImportBundled ? bundledExamplesDir() : null;
4712
+ if (!canImportBundled && target == null)
4713
+ logError("packaged examples skipped: importing .cflow.ts from node_modules needs bun (bunx --bun comfy-ts tui)");
4714
+ const bundledFiles = examplesDir == null ? [] : scanCflowFiles(realpathSync(examplesDir)).sort((a, b) => Number(!a.includes("/rvion/")) - Number(!b.includes("/rvion/")) || a.localeCompare(b));
4715
+ const discovery = mergeWorkflowSources({
4716
+ explicitTarget: target != null,
4717
+ scanned: scannedPlusArg,
4718
+ bundledFiles
4719
+ });
4720
+ const workflowFiles = discovery.files;
4721
+ if (workflowFiles.length === 0) {
4722
+ console.error(`[comfy-ts tui] no **/*.cflow.ts found under ${abs}`);
4723
+ return 1;
4724
+ }
4725
+ const preferred = !isDir && workflowFiles.includes(abs) ? abs : target == null ? rememberedWorkflow(workflowFiles) : null;
4726
+ const candidates = preferred != null ? [preferred, ...workflowFiles.filter((f) => f !== preferred)] : workflowFiles;
4727
+ const loadErrors = new Map;
4728
+ let first = null;
4729
+ let wf = null;
4730
+ for (const file of candidates) {
4731
+ try {
4732
+ const mod = await import(pathToFileURL2(file).href);
4733
+ const found = findDefinedWorkflow(mod);
4734
+ if (found == null)
4735
+ throw new Error(`${file} exports no DefinedWorkflow — export the result of host.defineWorkflow(...)`);
4736
+ first = file;
4737
+ wf = found;
4738
+ break;
4739
+ } catch (e) {
4740
+ loadErrors.set(file, extractErrorMessage(e));
4741
+ }
4742
+ }
4743
+ if (first == null || wf == null) {
4744
+ console.error(`[comfy-ts tui] no loadable workflow module among ${candidates.length} file(s):`);
4745
+ for (const [file, err] of loadErrors)
4746
+ console.error(` ${file}: ${err}`);
4747
+ return 1;
4748
+ }
4749
+ const st = new TuiSt(wf, { workflowFiles, currentFile: first, bundledFiles: discovery.bundled, loadErrors });
4750
+ const altScreen = process.stdout.isTTY === true;
4751
+ if (altScreen)
4752
+ process.stdout.write("\x1B[?1049h\x1B[H\x1B[>4;1m");
4753
+ const uninstallPainter = installProtocolImagePainter(st);
4754
+ try {
4755
+ if (process.stdin.isTTY === true)
4756
+ process.stdin.setRawMode(true);
4757
+ const app = render(/* @__PURE__ */ jsx19(TuiApp, {
4758
+ st
4759
+ }), { kittyKeyboard: { mode: "auto" } });
4760
+ st.onExit = () => st.dispose();
4761
+ await app.waitUntilExit();
4762
+ st.dispose();
4763
+ } finally {
4764
+ if (process.stdin.isTTY === true)
4765
+ process.stdin.setRawMode(false);
4766
+ uninstallPainter();
4767
+ if (altScreen)
4768
+ process.stdout.write("\x1B[0m\x1B[2J\x1B[H\x1B[>4;0m\x1B[?1049l");
4769
+ }
4770
+ return 0;
4771
+ }
4772
+ export {
4773
+ runTui
4774
+ };
4775
+
4776
+ //# debugId=FD7B8EA2B3D7EE8B64756E2164756E21
4777
+ //# sourceMappingURL=chunk-n35nffm8.js.map