comfy-ts 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (158) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +363 -0
  3. package/dist/cli.js +764 -0
  4. package/dist/cli.js.map +1 -0
  5. package/dist/index.cjs +4128 -0
  6. package/dist/index.cjs.map +1 -0
  7. package/dist/index.d.cts +9862 -0
  8. package/dist/index.d.ts +9846 -58
  9. package/dist/index.js +4049 -2
  10. package/dist/index.js.map +1 -1
  11. package/dist/log-CdfgILde.js +10 -0
  12. package/dist/log-CdfgILde.js.map +1 -0
  13. package/dist/run-tui-Io8Xea0L.js +3340 -0
  14. package/dist/run-tui-Io8Xea0L.js.map +1 -0
  15. package/package.json +104 -75
  16. package/src/cli/comfy-ts-cli.ts +36 -0
  17. package/src/cli/gen.ts +47 -0
  18. package/src/cli/outline.ts +82 -0
  19. package/src/cli/tui/components/DraftsOverlay.tsx +44 -0
  20. package/src/cli/tui/components/EditField.tsx +27 -0
  21. package/src/cli/tui/components/Header.tsx +51 -0
  22. package/src/cli/tui/components/HostPanel.tsx +37 -0
  23. package/src/cli/tui/components/LorasOverlay.tsx +49 -0
  24. package/src/cli/tui/components/OverlayList.tsx +25 -0
  25. package/src/cli/tui/components/PickerOverlays.tsx +66 -0
  26. package/src/cli/tui/components/PreviewPanel.tsx +33 -0
  27. package/src/cli/tui/components/PromptOverlay.tsx +16 -0
  28. package/src/cli/tui/components/StatusBar.tsx +165 -0
  29. package/src/cli/tui/components/TextOverlay.tsx +72 -0
  30. package/src/cli/tui/components/TreePanel.tsx +51 -0
  31. package/src/cli/tui/components/TuiApp.tsx +223 -0
  32. package/src/cli/tui/components/VarsPanel.tsx +86 -0
  33. package/src/cli/tui/findDefinedWorkflow.ts +16 -0
  34. package/src/cli/tui/keys.ts +20 -0
  35. package/src/cli/tui/protocolImagePainter.ts +59 -0
  36. package/src/cli/tui/run-tui.tsx +73 -0
  37. package/src/cli/tui/state/DraftsSt.ts +273 -0
  38. package/src/cli/tui/state/EditorSt.ts +289 -0
  39. package/src/cli/tui/state/ExecSt.ts +170 -0
  40. package/src/cli/tui/state/HostSt.ts +107 -0
  41. package/src/cli/tui/state/LorasSt.ts +185 -0
  42. package/src/cli/tui/state/PickerSt.ts +112 -0
  43. package/src/cli/tui/state/PreviewSt.ts +138 -0
  44. package/src/cli/tui/state/QueueSt.ts +59 -0
  45. package/src/cli/tui/state/SettingsSt.ts +73 -0
  46. package/src/cli/tui/state/TreeSt.ts +122 -0
  47. package/src/cli/tui/state/TuiSt.ts +169 -0
  48. package/src/cli/tui/state/WorkflowsSt.ts +92 -0
  49. package/src/cli/tui-env.ts +8 -0
  50. package/src/errors/InvalidPromptError.ts +12 -0
  51. package/src/graph/ComfyNode.ts +403 -0
  52. package/src/graph/ComfyNodeID.ts +28 -0
  53. package/src/graph/ComfyNodeOutput.ts +16 -0
  54. package/src/graph/NodeSlotSize.ts +4 -0
  55. package/src/graph/autoValue.ts +17 -0
  56. package/src/host/ComfyHost.ts +646 -0
  57. package/src/host/ComfyInstallType.ts +15 -0
  58. package/src/host/ComfyManager.ts +232 -0
  59. package/src/host/ComfyUploader.ts +110 -0
  60. package/src/host/ComfyWorkflowBuilder.ts +60 -0
  61. package/src/host/Requirements.ts +55 -0
  62. package/src/host/ResilientWebsocket.ts +147 -0
  63. package/src/host/loraManagerApi.ts +98 -0
  64. package/src/image-utils/_getPngMetadata.ts +53 -0
  65. package/src/image-utils/_getWebpMetadata.ts +38 -0
  66. package/src/image-utils/_parseExifData.ts +53 -0
  67. package/src/index.ts +89 -0
  68. package/src/litegraph/LiteGraphGroup.ts +22 -0
  69. package/src/litegraph/LiteGraphJSON.ts +46 -0
  70. package/src/litegraph/LiteGraphLink.ts +23 -0
  71. package/src/litegraph/LiteGraphLinkID.ts +6 -0
  72. package/src/litegraph/LiteGraphNode.ts +69 -0
  73. package/src/litegraph/LiteGraphNodeInput.ts +27 -0
  74. package/src/litegraph/LiteGraphNodeOutput.ts +23 -0
  75. package/src/litegraph/LiteGraphSlotIndex.ts +6 -0
  76. package/src/litegraph/convertFlowToLiteGraphJSON.ts +114 -0
  77. package/src/manager/ComfyRegistry.ts +124 -0
  78. package/src/manager/generated/KnownComfyCustomNodeName.ts +19280 -0
  79. package/src/manager/generated/KnownComfyPluginTitle.ts +5130 -0
  80. package/src/manager/generated/KnownComfyPluginURL.ts +2589 -0
  81. package/src/manager/generated/KnownModel_Base.ts +126 -0
  82. package/src/manager/generated/KnownModel_FileName.ts +2287 -0
  83. package/src/manager/generated/KnownModel_Name.ts +2287 -0
  84. package/src/manager/generated/KnownModel_SavePath.ts +263 -0
  85. package/src/manager/generated/KnownModel_Type.ts +97 -0
  86. package/src/manager/json/alter-list.json +224 -0
  87. package/src/manager/json/custom-node-list.extra.ts +13 -0
  88. package/src/manager/json/custom-node-list.json +21948 -0
  89. package/src/manager/json/extension-node-map.json +31282 -0
  90. package/src/manager/json/github-stats.json +12602 -0
  91. package/src/manager/json/model-list.extra.ts +26 -0
  92. package/src/manager/json/model-list.json +5052 -0
  93. package/src/manager/loaders/step1_downloadComfyManagerJSONs.ts +56 -0
  94. package/src/manager/loaders/step2_custom-node-list-loader.ts +149 -0
  95. package/src/manager/loaders/step3_extension-node-map-loader.ts +189 -0
  96. package/src/manager/loaders/step4_model-list-loader.ts +159 -0
  97. package/src/manager/script-update-manager.bun.ts +18 -0
  98. package/src/manager/types/ComfyManagerAPIFetchPolicy.ts +9 -0
  99. package/src/manager/types/ComfyManagerAPIModelList.ts +10 -0
  100. package/src/manager/types/ComfyManagerAPIPluginList.ts +11 -0
  101. package/src/manager/types/ComfyManagerFileModelInfo.ts +5 -0
  102. package/src/manager/types/ComfyManagerFilePluginContent.ts +13 -0
  103. package/src/manager/types/ComfyManagerFilePluginList.ts +5 -0
  104. package/src/manager/types/ComfyManagerModelInfo.ts +18 -0
  105. package/src/manager/types/ComfyManagerPluginContentMetadata.ts +16 -0
  106. package/src/manager/types/ComfyManagerPluginEnums.ts +8 -0
  107. package/src/manager/types/ComfyManagerPluginInfo.ts +50 -0
  108. package/src/runner/ComfyExecution.ts +301 -0
  109. package/src/runner/ComfyExecutionStatus.ts +2 -0
  110. package/src/runner/ComfyWorkflow.ts +395 -0
  111. package/src/runner/ComfyWorkflowLayout.ts +96 -0
  112. package/src/runner/ComfyWsApi.ts +159 -0
  113. package/src/runner/MediaImage.ts +262 -0
  114. package/src/sdk-generator/ComfyNodeSchema.ts +79 -0
  115. package/src/sdk-generator/ComfySchema.ts +369 -0
  116. package/src/sdk-generator/ComfyUIObjectInfoTypes.ts +95 -0
  117. package/src/sdk-generator/Primitives.ts +76 -0
  118. package/src/sdk-generator/_getUnionNameBasedOnFirstFoundEnumName.ts +39 -0
  119. package/src/sdk-generator/_pythonModuleToNamespace.ts +27 -0
  120. package/src/sdk-generator/_toQualifiedNodeKey.ts +5 -0
  121. package/src/sdk-generator/comfy-api-json.ts +16 -0
  122. package/src/sdk-generator/comfyui-sdk-codegen.ts +287 -0
  123. package/src/sdk-generator/comfyui-types.ts +56 -0
  124. package/src/sdk-generator/litegraphToApiRequestPayload.ts +157 -0
  125. package/src/ssh-host-manager/ssh-config-manager.ts +89 -0
  126. package/src/ssh-host-manager/ssh-config.windows.md +32 -0
  127. package/src/ssh-host-manager/ssh-manager.ts +129 -0
  128. package/src/state.ts +136 -0
  129. package/src/types/comfy-sdk.ts +106 -0
  130. package/src/types/index.ts +55 -0
  131. package/src/utils/CodeBuffer.ts +61 -0
  132. package/src/utils/ComfyColors.ts +38 -0
  133. package/src/utils/ansi.ts +26 -0
  134. package/src/utils/ansiImage.ts +36 -0
  135. package/src/utils/bang.ts +39 -0
  136. package/src/utils/deepCopyNaive.ts +1 -0
  137. package/src/utils/downloadFile.ts +77 -0
  138. package/src/utils/escapeJSKey.ts +32 -0
  139. package/src/utils/exhaust.ts +4 -0
  140. package/src/utils/extractErrorMessage.ts +11 -0
  141. package/src/utils/fuzzyMatch.ts +8 -0
  142. package/src/utils/githubRegexes.ts +2 -0
  143. package/src/utils/hashArrayBuffer.ts +6 -0
  144. package/src/utils/log.ts +9 -0
  145. package/src/utils/loraTag.ts +10 -0
  146. package/src/utils/printArkResultInConsole.ts +16 -0
  147. package/src/utils/softValidate.ts +8 -0
  148. package/src/utils/stringifyReadable.ts +32 -0
  149. package/src/utils/toposort.ts +59 -0
  150. package/src/utils/tryExtracting.ts +41 -0
  151. package/src/utils/writeFile.ts +16 -0
  152. package/src/vars/ComfyVars.ts +531 -0
  153. package/src/vars/DefinedWorkflow.ts +112 -0
  154. package/src/vars/loraKeywords.ts +56 -0
  155. package/dist/index.d.mts +0 -74
  156. package/dist/index.mjs +0 -3
  157. package/dist/index.mjs.map +0 -1
  158. package/readme.md +0 -40
@@ -0,0 +1,20 @@
1
+ /** the key flags a modified-⏎ translation produces (subset of ink's Key) */
2
+ export type EnterKeyBits = { return: boolean; shift: boolean; meta: boolean; ctrl: boolean }
3
+
4
+ /**
5
+ * xterm modifyOtherKeys (vscode/xterm.js — enabled by run-tui via `CSI > 4;1 m`)
6
+ * encodes modified ⏎ as `CSI 27;<mods>;13~`. ink 7 leaves that sequence
7
+ * unparsed: it reaches useInput as the LITERAL input `[27;<mods>;13~` with no
8
+ * key flags, which would otherwise be typed into editors/filters. Translate it
9
+ * back into return + modifier bits (mods is xterm's modifier-1 bitfield:
10
+ * 1 shift · 2 alt · 4 ctrl · 8 meta — alt|meta fold into ink's `meta`, same
11
+ * mask ink uses for legacy fn-keys). Kitty-protocol terminals never hit this:
12
+ * their `CSI 13;2u` is parsed natively by ink. Returns null when `input` is
13
+ * not a modified enter.
14
+ */
15
+ export function parseModifyOtherKeysEnter(input: string): EnterKeyBits | null {
16
+ const m = /^\[27;(\d+);13~$/.exec(input)
17
+ if (m == null) return null
18
+ const mods = Number(m[1]) - 1
19
+ return { return: true, shift: (mods & 1) !== 0, meta: (mods & 10) !== 0, ctrl: (mods & 4) !== 0 }
20
+ }
@@ -0,0 +1,59 @@
1
+ import { reaction } from 'mobx'
2
+ import { protocolCapable } from 'src/cli/tui/state/PreviewSt.ts'
3
+ import type { TuiSt } from 'src/cli/tui/state/TuiSt.ts'
4
+
5
+ type WriteCb = (err?: Error | null) => void
6
+
7
+ /**
8
+ * paints the REAL image (OSC 1337) over the preview panel's cell rect.
9
+ * Protocol images cannot go THROUGH ink (layout shreds the escape) and every
10
+ * ink frame write ERASES the image's cells — so this hooks stdout.write and
11
+ * re-paints right after each flush, plus a mobx reaction for byte changes that
12
+ * do not move a single frame cell (fresh output/latent/lora bytes).
13
+ * NOT React: effects only fire for the component that re-rendered, which is
14
+ * why a useEffect painter missed frames (his report: image waited for input).
15
+ */
16
+ export function installProtocolImagePainter(st: TuiSt): () => void {
17
+ // capability, not current mode: `p` can switch to native at any time —
18
+ // protocolImage returns null while the mode is ansi/off, so painting no-ops
19
+ if (!protocolCapable() || process.stdout.isTTY !== true) return () => {}
20
+ const original = process.stdout.write.bind(process.stdout)
21
+
22
+ const paint = (): void => {
23
+ const bytes = st.preview.protocolImage
24
+ if (bytes == null) return
25
+ const pv = st.preview
26
+ // panel outer left edge +1 border +1 padding; content row = header(3) + border(1) + 1
27
+ const col = Math.max(1, st.termCols - (pv.width + 4) + 3)
28
+ const b64 = Buffer.from(bytes).toString('base64')
29
+ // cursor save → CUP → image sized in CELLS → cursor restore; via the
30
+ // ORIGINAL write so the hook never re-triggers itself
31
+ original(
32
+ `\u001b7\u001b[5;${col}H\u001b]1337;File=inline=1;size=${bytes.byteLength};width=${pv.width};height=${pv.height};preserveAspectRatio=1:${b64}\u0007\u001b8`,
33
+ )
34
+ }
35
+
36
+ let scheduled = false
37
+ const schedule = (): void => {
38
+ if (scheduled) return
39
+ scheduled = true
40
+ setImmediate(() => {
41
+ paint()
42
+ scheduled = false
43
+ })
44
+ }
45
+
46
+ // cast: whitelist item 8 (agent/coding.md) — reimplements the exact overload set
47
+ const patched = ((chunk: Uint8Array | string, encodingOrCb?: BufferEncoding | WriteCb, cb?: WriteCb): boolean => {
48
+ const res = typeof encodingOrCb === 'function' ? original(chunk, encodingOrCb) : original(chunk, encodingOrCb, cb)
49
+ schedule()
50
+ return res
51
+ }) as typeof process.stdout.write
52
+
53
+ process.stdout.write = patched
54
+ const disposeReaction = reaction(() => st.preview.protocolImage, schedule)
55
+ return () => {
56
+ process.stdout.write = original
57
+ disposeReaction()
58
+ }
59
+ }
@@ -0,0 +1,73 @@
1
+ import { readdirSync, statSync } from 'node:fs'
2
+ import { pathToFileURL } from 'node:url'
3
+ import { render } from 'ink'
4
+ import { dirname, join, resolve } from 'pathe'
5
+ import { COMFY_TS_TUI_ENV } from 'src/cli/tui-env.ts'
6
+ import { findDefinedWorkflow } from 'src/cli/tui/findDefinedWorkflow.ts'
7
+ import { installProtocolImagePainter } from 'src/cli/tui/protocolImagePainter.ts'
8
+ import { TuiApp } from 'src/cli/tui/components/TuiApp.tsx'
9
+ import { TuiSt } from 'src/cli/tui/state/TuiSt.ts'
10
+
11
+ /** recursive scan for the workflow-module naming convention */
12
+ function scanCflowFiles(dir: string): string[] {
13
+ const hits = readdirSync(dir, { recursive: true })
14
+ .map((f) => join(dir, String(f)))
15
+ .filter((f) => f.endsWith('.cflow.ts') || f.endsWith('.cflow.tsx'))
16
+ return hits.sort()
17
+ }
18
+
19
+ export async function runTui(args: string[]): Promise<number> {
20
+ // no arg = scan cwd; a file arg ALSO scans its folder (file preselected)
21
+ const target = args.find((a) => !a.startsWith('--')) ?? '.'
22
+
23
+ // the module contract: files check `import.meta.main` (false here) so their
24
+ // standalone run block is skipped; this env var covers in-run tweaks
25
+ process.env[COMFY_TS_TUI_ENV] = '1'
26
+ process.env.COMFY_TS_QUIET = '1' // info chatter off; the TUI owns the screen
27
+
28
+ const abs = resolve(target)
29
+ const isDir = statSync(abs).isDirectory()
30
+ const scanned = scanCflowFiles(isDir ? abs : dirname(abs))
31
+ const workflowFiles = isDir || scanned.includes(abs) ? scanned : [abs, ...scanned]
32
+ const first = isDir ? workflowFiles[0] : abs
33
+ if (first == null) {
34
+ console.error(`[comfy-ts tui] no **/*.cflow.ts found under ${abs}`)
35
+ return 1
36
+ }
37
+
38
+ const mod: Record<string, unknown> = await import(pathToFileURL(first).href)
39
+ const wf = findDefinedWorkflow(mod)
40
+ if (wf == null) {
41
+ console.error(
42
+ `[comfy-ts tui] ${first} exports no DefinedWorkflow — export the result of host.defineWorkflow(...)`,
43
+ )
44
+ return 1
45
+ }
46
+
47
+ const st = new TuiSt(wf, { workflowFiles, currentFile: first })
48
+ // ALT SCREEN (TTY only): deterministic absolute coordinates for the protocol
49
+ // image painter + no scrollback pollution / clipped first row.
50
+ // modifyOtherKeys mode 1 rides along: vscode/xterm.js then ENCODES modified ⏎
51
+ // (so ⇧⏎ stops arriving as a plain-`\r` commit) as `CSI 27;mods;13~` —
52
+ // translated in TuiApp via keys.ts. Mode 1 only touches keys without
53
+ // well-known sequences (mode 2 would re-encode ctrl+letters and break the
54
+ // editor keys); unsupporting terminals ignore it.
55
+ const altScreen = process.stdout.isTTY === true
56
+ if (altScreen) process.stdout.write('\u001b[?1049h\u001b[H\u001b[>4;1m')
57
+ // REAL images over the preview panel rect on OSC-1337 terminals (repaints
58
+ // after every stdout flush + on image change — NOT a React effect)
59
+ const uninstallPainter = installProtocolImagePainter(st)
60
+ try {
61
+ // kittyKeyboard auto: ink queries `CSI ? u` and enables CSI-u encoding
62
+ // where supported (iTerm2 3.5+/WezTerm/kitty/ghostty) — ⇧⏎ parsed natively
63
+ const app = render(<TuiApp st={st} />, { kittyKeyboard: { mode: 'auto' } })
64
+ // dispose: flush reactions/listeners + close every ws opened by loaded modules
65
+ st.onExit = () => st.dispose()
66
+ await app.waitUntilExit()
67
+ st.dispose()
68
+ } finally {
69
+ uninstallPainter()
70
+ if (altScreen) process.stdout.write('\u001b[>4;0m\u001b[?1049l')
71
+ }
72
+ return 0
73
+ }
@@ -0,0 +1,273 @@
1
+ import {
2
+ copyFileSync,
3
+ existsSync,
4
+ mkdirSync,
5
+ readdirSync,
6
+ readFileSync,
7
+ renameSync,
8
+ rmSync,
9
+ writeFileSync,
10
+ } from 'node:fs'
11
+ import { makeAutoObservable, reaction } from 'mobx'
12
+ import { basename, dirname, join } from 'pathe'
13
+ import { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'
14
+ import type { TuiMode, TuiSt } from 'src/cli/tui/state/TuiSt.ts'
15
+
16
+ /** module basename (`01-txt2img`) keys the draft folder — knowable for EVERY tree file without importing it */
17
+ export function draftKeyForFile(file: string): string {
18
+ return basename(file).replace(/\.cflow\.tsx?$/, '')
19
+ }
20
+
21
+ export function draftsDirForFile(file: string): string {
22
+ return comfyts.resolveFromDrafts(draftKeyForFile(file))
23
+ }
24
+
25
+ function listDraftsInDir(dir: string): string[] {
26
+ if (!existsSync(dir)) return []
27
+ return readdirSync(dir)
28
+ .filter((f) => f.endsWith('.json'))
29
+ .map((f) => f.slice(0, -'.json'.length))
30
+ .sort()
31
+ }
32
+
33
+ /** draft names stored for a workflow module (fs read — pair with DraftsSt.version for reactivity) */
34
+ export function listDraftsForFile(file: string): string[] {
35
+ return listDraftsInDir(draftsDirForFile(file))
36
+ }
37
+
38
+ /**
39
+ * named var-value snapshots at `.comfy-ts/drafts/<module-basename>/<name>.json`
40
+ * (LOCAL state, gitignored). The active draft autosaves debounced; the TUI is
41
+ * ALWAYS in a draft (`default` unless another one is activated).
42
+ */
43
+ export class DraftsSt {
44
+ constructor(private st: TuiSt) {
45
+ makeAutoObservable<DraftsSt, 'st'>(this, { st: false })
46
+ // active-draft autosave: var values + draft name are observable
47
+ this.st.disposers.push(
48
+ reaction(
49
+ () => (this.active == null ? null : JSON.stringify(this.snapshot())),
50
+ (json) => {
51
+ if (json != null && this.active != null) this.write(this.active, json)
52
+ },
53
+ { delay: 300 },
54
+ ),
55
+ )
56
+ }
57
+
58
+ /** ALWAYS set after construction; null only transiently while activate() loads values */
59
+ active: string | null = null
60
+ list: string[] = []
61
+ ix: number = 0
62
+ /** bumped on every fs write/rename so fs-derived getters (tree rows) recompute */
63
+ version: number = 0
64
+
65
+ private get dir(): string {
66
+ const cur = this.st.workflows.currentPath
67
+ return cur != null ? draftsDirForFile(cur) : comfyts.resolveFromDrafts(this.st.wf.spec.id ?? 'workflow')
68
+ }
69
+
70
+ private snapshot(): Record<string, unknown> {
71
+ // toJSON so seed persists {mode, value}; other vars round-trip their value
72
+ return Object.fromEntries(this.st.entries.map(([k, varDef]) => [k, varDef.toJSON()]))
73
+ }
74
+
75
+ private write(name: string, json: string): void {
76
+ const path = join(this.dir, `${name}.json`)
77
+ mkdirSync(dirname(path), { recursive: true })
78
+ writeFileSync(path, json)
79
+ this.version++
80
+ }
81
+
82
+ /** module key of the currently loaded workflow (settings.lastDraft is keyed by it) */
83
+ private get moduleKey(): string {
84
+ const cur = this.st.workflows.currentPath
85
+ return cur != null ? draftKeyForFile(cur) : (this.st.wf.spec.id ?? 'workflow')
86
+ }
87
+
88
+ /** switch to a draft: load its stored values when the file exists, else it starts from current values */
89
+ activate(name: string): void {
90
+ this.active = null // the autosave expression must not see old values under the new name
91
+ const path = join(this.dir, `${name}.json`)
92
+ if (existsSync(path)) {
93
+ try {
94
+ const values: Record<string, unknown> = JSON.parse(readFileSync(path, 'utf8'))
95
+ for (const [k, varDef] of this.st.entries) if (k in values) varDef.loadJSON(values[k])
96
+ } catch (e) {
97
+ this.st.exec.error = extractErrorMessage(e)
98
+ }
99
+ }
100
+ this.active = name
101
+ this.st.settings.rememberDraft(this.moduleKey, name)
102
+ }
103
+
104
+ /** open the draft this workflow was last in (settings), else 'default' */
105
+ activateRemembered(): void {
106
+ const remembered = this.st.settings.lastDraft[this.moduleKey]
107
+ if (remembered != null && remembered !== 'default' && existsSync(join(this.dir, `${remembered}.json`)))
108
+ this.activate(remembered)
109
+ else this.activate('default')
110
+ }
111
+
112
+ /** every workflow starts in a draft; kept for callers that want 'default' explicitly */
113
+ activateDefault(): void {
114
+ this.activate('default')
115
+ }
116
+
117
+ // ---- draft CRUD (also drives the tree's draft rows — `file` overrides the target workflow) ----
118
+
119
+ private dirFor(file: string | undefined): string {
120
+ return file != null ? draftsDirForFile(file) : this.dir
121
+ }
122
+
123
+ /** true when ops on `file` touch the ACTIVE draft bookkeeping */
124
+ private isCurrent(file: string | undefined): boolean {
125
+ return file == null || file === this.st.workflows.currentPath
126
+ }
127
+
128
+ private validName(rawName: string): string | null {
129
+ const name = rawName.trim()
130
+ if (/^[\w][\w .-]*$/.test(name)) return name
131
+ this.st.exec.notice = `invalid draft name: '${rawName}'`
132
+ return null
133
+ }
134
+
135
+ /** create a NEW draft from the current var values (current workflow only) */
136
+ createNamed(rawName: string): boolean {
137
+ const name = this.validName(rawName)
138
+ if (name == null) return false
139
+ if (existsSync(join(this.dir, `${name}.json`))) {
140
+ this.st.exec.notice = `draft '${name}' already exists`
141
+ return false
142
+ }
143
+ this.write(name, JSON.stringify(this.snapshot(), null, 2))
144
+ this.active = name
145
+ this.st.settings.rememberDraft(this.moduleKey, name)
146
+ this.st.exec.notice = `new draft: ${name} (autosaves)`
147
+ return true
148
+ }
149
+
150
+ rename(oldName: string, rawName: string, file?: string): boolean {
151
+ const newName = this.validName(rawName)
152
+ if (newName == null) return false
153
+ if (newName === oldName) return true
154
+ const dir = this.dirFor(file)
155
+ const to = join(dir, `${newName}.json`)
156
+ if (existsSync(to)) {
157
+ this.st.exec.notice = `draft '${newName}' already exists`
158
+ return false
159
+ }
160
+ const from = join(dir, `${oldName}.json`)
161
+ if (existsSync(from)) renameSync(from, to)
162
+ else if (this.isCurrent(file)) this.write(newName, JSON.stringify(this.snapshot(), null, 2))
163
+ if (this.isCurrent(file) && this.active === oldName) {
164
+ this.active = newName
165
+ this.st.settings.rememberDraft(this.moduleKey, newName)
166
+ }
167
+ this.version++
168
+ this.st.exec.notice = `draft renamed: ${oldName} → ${newName}`
169
+ return true
170
+ }
171
+
172
+ duplicate(name: string, rawName: string, file?: string): boolean {
173
+ const newName = this.validName(rawName)
174
+ if (newName == null) return false
175
+ const dir = this.dirFor(file)
176
+ const from = join(dir, `${name}.json`)
177
+ const to = join(dir, `${newName}.json`)
178
+ if (!existsSync(from)) {
179
+ this.st.exec.notice = `draft '${name}' has no file yet (edit a var first)`
180
+ return false
181
+ }
182
+ if (existsSync(to)) {
183
+ this.st.exec.notice = `draft '${newName}' already exists`
184
+ return false
185
+ }
186
+ copyFileSync(from, to)
187
+ this.version++
188
+ this.st.exec.notice = `draft duplicated: ${name} → ${newName}`
189
+ return true
190
+ }
191
+
192
+ deleteDraft(name: string, file?: string): void {
193
+ const path = join(this.dirFor(file), `${name}.json`)
194
+ if (existsSync(path)) rmSync(path)
195
+ this.version++
196
+ // deleting the draft you are IN falls back to default
197
+ if (this.isCurrent(file) && this.active === name) this.activateDefault()
198
+ this.st.exec.notice = `draft deleted: ${name}`
199
+ }
200
+
201
+ // ---- name prompts (ONE mechanism: EditorSt custom session → PromptOverlay) ----
202
+
203
+ promptNew(returnMode: TuiMode = 'nav'): void {
204
+ this.st.editor.beginCustom({
205
+ title: 'new draft (from current values)',
206
+ initial: '',
207
+ onCommit: (raw) => {
208
+ const ok = this.createNamed(raw)
209
+ if (ok && returnMode === 'overlay-drafts') this.begin()
210
+ return ok
211
+ },
212
+ returnMode,
213
+ })
214
+ }
215
+
216
+ promptRename(name: string, file?: string, returnMode: TuiMode = 'nav'): void {
217
+ this.st.editor.beginCustom({
218
+ title: `rename draft '${name}'`,
219
+ initial: name,
220
+ onCommit: (raw) => {
221
+ const ok = this.rename(name, raw, file)
222
+ if (ok && returnMode === 'overlay-drafts') this.begin()
223
+ return ok
224
+ },
225
+ returnMode,
226
+ })
227
+ }
228
+
229
+ promptDuplicate(name: string, file?: string, returnMode: TuiMode = 'nav'): void {
230
+ this.st.editor.beginCustom({
231
+ title: `duplicate draft '${name}'`,
232
+ initial: `${name}-copy`,
233
+ onCommit: (raw) => {
234
+ const ok = this.duplicate(name, raw, file)
235
+ if (ok && returnMode === 'overlay-drafts') this.begin()
236
+ return ok
237
+ },
238
+ returnMode,
239
+ })
240
+ }
241
+
242
+ /** f2 in nav: rename the ACTIVE draft */
243
+ beginRename(): void {
244
+ this.promptRename(this.active ?? 'default')
245
+ }
246
+
247
+ begin(): void {
248
+ this.list = listDraftsInDir(this.dir)
249
+ this.st.mode = 'overlay-drafts'
250
+ const ix = this.active == null ? -1 : this.list.indexOf(this.active)
251
+ // row 0 = "new draft", rows 1.. = existing drafts
252
+ this.ix = ix === -1 ? 0 : ix + 1
253
+ }
254
+
255
+ move(delta: number): void {
256
+ const len = this.list.length + 1
257
+ this.ix = (this.ix + delta + len) % len
258
+ }
259
+
260
+ /** draft name under the overlay cursor (row 0 is 'new') */
261
+ get selectedName(): string | null {
262
+ return this.ix === 0 ? null : (this.list[this.ix - 1] ?? null)
263
+ }
264
+
265
+ commit(): void {
266
+ if (this.ix === 0) return this.promptNew('overlay-drafts')
267
+ const name = this.selectedName
268
+ if (name == null) return
269
+ this.activate(name)
270
+ this.st.exec.notice = `draft: ${name} (autosaves)`
271
+ this.st.mode = 'nav'
272
+ }
273
+ }