comfy-ts 0.3.0 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +349 -255
- package/dist/DefinedWorkflow-O3ynII3Y.js +598 -0
- package/dist/DefinedWorkflow-O3ynII3Y.js.map +1 -0
- package/dist/cli.js +3969 -128
- package/dist/cli.js.map +1 -1
- package/dist/index.cjs +1208 -170
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +449 -115
- package/dist/index.d.ts +449 -115
- package/dist/index.js +1200 -171
- package/dist/index.js.map +1 -1
- package/dist/{run-tui-Io8Xea0L.js → run-tui-BFhba_oG.js} +744 -665
- package/dist/run-tui-BFhba_oG.js.map +1 -0
- package/examples/01-txt2img.cflow.ts +50 -0
- package/examples/02-img2img-upload.cflow.ts +66 -0
- package/examples/03-export-workflow-json.cflow.ts +56 -0
- package/examples/04-krea2-turbo-t2i.cflow.ts +125 -0
- package/examples/05-comfy-cloud.cflow.ts +67 -0
- package/examples/comfy-cloud/sdk.d.ts +122674 -0
- package/guide-for-agents.md +166 -0
- package/package.json +7 -3
- package/src/cli/comfy-ts-cli.ts +19 -2
- package/src/cli/gen.ts +21 -12
- package/src/cli/tui/components/Header.tsx +5 -0
- package/src/cli/tui/components/LogsPanel.tsx +23 -0
- package/src/cli/tui/components/PreviewPanel.tsx +52 -7
- package/src/cli/tui/components/StatusBar.tsx +10 -4
- package/src/cli/tui/components/TreePanel.tsx +15 -2
- package/src/cli/tui/components/TuiApp.tsx +26 -3
- package/src/cli/tui/discoverWorkflows.ts +79 -0
- package/src/cli/tui/protocolImagePainter.ts +54 -18
- package/src/cli/tui/run-tui.tsx +55 -24
- package/src/cli/tui/state/ExecSt.ts +4 -1
- package/src/cli/tui/state/HostSt.ts +123 -1
- package/src/cli/tui/state/LogsSt.ts +107 -0
- package/src/cli/tui/state/PreviewSt.ts +173 -23
- package/src/cli/tui/state/SettingsSt.ts +48 -21
- package/src/cli/tui/state/TreeSt.ts +30 -6
- package/src/cli/tui/state/TuiSt.ts +27 -3
- package/src/cli/tui/state/WorkflowsSt.ts +16 -1
- package/src/host/ComfyHost.ts +241 -71
- package/src/host/ComfyManager.ts +10 -9
- package/src/host/ComfyUploader.ts +1 -2
- package/src/host/ResilientWebsocket.ts +3 -1
- package/src/host/hostUrl.ts +59 -0
- package/src/host/loraManagerApi.ts +5 -4
- package/src/index.ts +20 -1
- package/src/litegraph/CanonicalWorkflow.ts +77 -0
- package/src/litegraph/LiteGraphGroup.ts +9 -7
- package/src/litegraph/LiteGraphJSON.ts +34 -13
- package/src/litegraph/LiteGraphLink.ts +32 -2
- package/src/litegraph/LiteGraphNode.ts +18 -33
- package/src/litegraph/LiteGraphNodeInput.ts +10 -8
- package/src/litegraph/LiteGraphNodeOutput.ts +2 -3
- package/src/litegraph/LiteGraphSubgraphDef.ts +74 -0
- package/src/litegraph/convertFlowToLiteGraphJSON.ts +4 -4
- package/src/litegraph/expandSubgraphs.ts +352 -0
- package/src/litegraph/normalizeWorkflow.ts +141 -0
- package/src/runner/ComfyExecution.ts +4 -5
- package/src/runner/ComfyWorkflow.ts +2 -2
- package/src/runner/ComfyWsApi.ts +12 -1
- package/src/runner/wsBinaryFrame.ts +48 -0
- package/src/sdk-generator/Primitives.ts +6 -24
- package/src/sdk-generator/comfy-api-json.ts +3 -1
- package/src/sdk-generator/inputWidgetKind.ts +179 -0
- package/src/sdk-generator/litegraphToApiRequestPayload.ts +372 -96
- package/src/ssh-host-manager/ssh-manager.ts +0 -15
- package/src/state.ts +13 -2
- package/src/utils/ansi.ts +7 -0
- package/src/utils/mojibake.ts +60 -0
- package/dist/log-CdfgILde.js +0 -10
- package/dist/log-CdfgILde.js.map +0 -1
- package/dist/run-tui-Io8Xea0L.js.map +0 -1
|
@@ -4,55 +4,91 @@ import type { TuiSt } from 'src/cli/tui/state/TuiSt.ts'
|
|
|
4
4
|
|
|
5
5
|
type WriteCb = (err?: Error | null) => void
|
|
6
6
|
|
|
7
|
+
const SYNC_BEGIN = '\u001b[?2026h'
|
|
8
|
+
const SYNC_END = '\u001b[?2026l'
|
|
9
|
+
/** below this a write is a terminal query/reply, not a frame — no cells damaged */
|
|
10
|
+
const MIN_FRAME_BYTES = 64
|
|
11
|
+
|
|
7
12
|
/**
|
|
8
13
|
* paints the REAL image (OSC 1337) over the preview panel's cell rect.
|
|
9
14
|
* Protocol images cannot go THROUGH ink (layout shreds the escape) and every
|
|
10
15
|
* ink frame write ERASES the image's cells — so this hooks stdout.write and
|
|
11
|
-
* re-paints
|
|
12
|
-
*
|
|
16
|
+
* re-paints SYNCHRONOUSLY within the same flush, the whole batch wrapped in
|
|
17
|
+
* DEC 2026 synchronized-update markers: the terminal never presents the
|
|
18
|
+
* erased-frame intermediate state. (The previous deferred setImmediate
|
|
19
|
+
* repaint WAS the native-mode flicker — his repro.) A mobx reaction covers
|
|
20
|
+
* byte-only changes (fresh latent/output/lora bytes with no frame write).
|
|
13
21
|
* NOT React: effects only fire for the component that re-rendered, which is
|
|
14
22
|
* why a useEffect painter missed frames (his report: image waited for input).
|
|
15
23
|
*/
|
|
16
24
|
export function installProtocolImagePainter(st: TuiSt): () => void {
|
|
17
|
-
// capability, not current
|
|
18
|
-
//
|
|
25
|
+
// capability, not current setting: the menu can switch to native at any
|
|
26
|
+
// time — imageEscapes() is empty while pixel/hidden, so painting no-ops
|
|
19
27
|
if (!protocolCapable() || process.stdout.isTTY !== true) return () => {}
|
|
20
28
|
const original = process.stdout.write.bind(process.stdout)
|
|
21
29
|
|
|
22
|
-
const
|
|
23
|
-
const
|
|
24
|
-
|
|
30
|
+
const imageEscape = (bytes: Uint8Array, row: number, col: number, w: number, h: number): string => {
|
|
31
|
+
const b64 = Buffer.from(bytes).toString('base64')
|
|
32
|
+
// cursor save → CUP → image sized in CELLS → cursor restore
|
|
33
|
+
return `\u001b7\u001b[${row};${col}H\u001b]1337;File=inline=1;size=${bytes.byteLength};width=${w};height=${h};preserveAspectRatio=1:${b64}\u0007\u001b8`
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// first image row: header(3) + panel border(1) + 1 content row — row 6,
|
|
37
|
+
// calibrated by playtest on iTerm2 (2026-07-27: row 5 painted one line too high)
|
|
38
|
+
const CONTENT_ROW = 6
|
|
39
|
+
|
|
40
|
+
/** both images as ONE escape string ('' when nothing to paint) */
|
|
41
|
+
const imageEscapes = (): string => {
|
|
25
42
|
const pv = st.preview
|
|
26
|
-
|
|
43
|
+
const main = pv.protocolImage
|
|
44
|
+
const corner = pv.protocolImageCorner
|
|
45
|
+
if (main == null && corner == null) return ''
|
|
46
|
+
// panel outer left edge +1 border +1 padding
|
|
27
47
|
const col = Math.max(1, st.termCols - (pv.width + 4) + 3)
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
//
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
48
|
+
let out = ''
|
|
49
|
+
if (main != null) out += imageEscape(main, CONTENT_ROW, col, pv.width, pv.height)
|
|
50
|
+
// small latent AFTER the big image so it stays on top; its cell box
|
|
51
|
+
// matches the latent's aspect (cornerBox) — a mismatched rect letterboxes
|
|
52
|
+
if (corner != null) {
|
|
53
|
+
const box = pv.cornerBox
|
|
54
|
+
out += imageEscape(corner, CONTENT_ROW, col + pv.width - box.w, box.w, box.h)
|
|
55
|
+
}
|
|
56
|
+
return out
|
|
34
57
|
}
|
|
35
58
|
|
|
59
|
+
// disposed kills PENDING paints too: a repaint queued around ink's final
|
|
60
|
+
// frame must never fire after the alt-screen restore (ghost image after q)
|
|
61
|
+
let disposed = false
|
|
62
|
+
|
|
63
|
+
/** byte-only changes (no frame write erased anything): paint alone, atomically */
|
|
36
64
|
let scheduled = false
|
|
37
65
|
const schedule = (): void => {
|
|
38
|
-
if (scheduled) return
|
|
66
|
+
if (scheduled || disposed) return
|
|
39
67
|
scheduled = true
|
|
40
68
|
setImmediate(() => {
|
|
41
|
-
paint()
|
|
42
69
|
scheduled = false
|
|
70
|
+
if (disposed) return
|
|
71
|
+
const images = imageEscapes()
|
|
72
|
+
if (images !== '') original(SYNC_BEGIN + images + SYNC_END)
|
|
43
73
|
})
|
|
44
74
|
}
|
|
45
75
|
|
|
46
76
|
// cast: whitelist item 8 (agent/coding.md) — reimplements the exact overload set
|
|
47
77
|
const patched = ((chunk: Uint8Array | string, encodingOrCb?: BufferEncoding | WriteCb, cb?: WriteCb): boolean => {
|
|
78
|
+
// frame writes damage the image cells: repaint in the SAME flush, the
|
|
79
|
+
// whole batch synchronized so no intermediate state is ever presented
|
|
80
|
+
const isFrame = !disposed && (typeof chunk === 'string' ? chunk.length : chunk.byteLength) >= MIN_FRAME_BYTES
|
|
81
|
+
const images = isFrame ? imageEscapes() : ''
|
|
82
|
+
if (images !== '') original(SYNC_BEGIN)
|
|
48
83
|
const res = typeof encodingOrCb === 'function' ? original(chunk, encodingOrCb) : original(chunk, encodingOrCb, cb)
|
|
49
|
-
|
|
84
|
+
if (images !== '') original(images + SYNC_END)
|
|
50
85
|
return res
|
|
51
86
|
}) as typeof process.stdout.write
|
|
52
87
|
|
|
53
88
|
process.stdout.write = patched
|
|
54
|
-
const disposeReaction = reaction(() => st.preview.protocolImage, schedule)
|
|
89
|
+
const disposeReaction = reaction(() => [st.preview.protocolImage, st.preview.protocolImageCorner], schedule)
|
|
55
90
|
return () => {
|
|
91
|
+
disposed = true
|
|
56
92
|
process.stdout.write = original
|
|
57
93
|
disposeReaction()
|
|
58
94
|
}
|
package/src/cli/tui/run-tui.tsx
CHANGED
|
@@ -1,50 +1,78 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { realpathSync, statSync } from 'node:fs'
|
|
2
2
|
import { pathToFileURL } from 'node:url'
|
|
3
3
|
import { render } from 'ink'
|
|
4
|
-
import { dirname,
|
|
4
|
+
import { dirname, resolve } from 'pathe'
|
|
5
5
|
import { COMFY_TS_TUI_ENV } from 'src/cli/tui-env.ts'
|
|
6
|
+
import { bundledExamplesDir, mergeWorkflowSources, scanCflowFiles } from 'src/cli/tui/discoverWorkflows.ts'
|
|
6
7
|
import { findDefinedWorkflow } from 'src/cli/tui/findDefinedWorkflow.ts'
|
|
7
8
|
import { installProtocolImagePainter } from 'src/cli/tui/protocolImagePainter.ts'
|
|
8
9
|
import { TuiApp } from 'src/cli/tui/components/TuiApp.tsx'
|
|
9
10
|
import { TuiSt } from 'src/cli/tui/state/TuiSt.ts'
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
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
|
-
}
|
|
11
|
+
import { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'
|
|
12
|
+
import { logError } from 'src/utils/log.ts'
|
|
13
|
+
import type { DefinedWorkflow } from 'src/vars/DefinedWorkflow.ts'
|
|
18
14
|
|
|
19
15
|
export async function runTui(args: string[]): Promise<number> {
|
|
20
|
-
// no arg =
|
|
21
|
-
|
|
16
|
+
// no arg = cwd scan MERGED with the examples packaged with comfy-ts; an
|
|
17
|
+
// explicit dir/file arg keeps that scope only (a file arg is preselected)
|
|
18
|
+
const target = args.find((a) => !a.startsWith('--'))
|
|
22
19
|
|
|
23
20
|
// the module contract: files check `import.meta.main` (false here) so their
|
|
24
21
|
// standalone run block is skipped; this env var covers in-run tweaks
|
|
25
22
|
process.env[COMFY_TS_TUI_ENV] = '1'
|
|
26
23
|
process.env.COMFY_TS_QUIET = '1' // info chatter off; the TUI owns the screen
|
|
27
24
|
|
|
28
|
-
|
|
25
|
+
// realpath both sides: scanned paths derive from cwd, bundled ones from
|
|
26
|
+
// import.meta — a symlinked cwd must not defeat the dedupe
|
|
27
|
+
const abs = realpathSync(resolve(target ?? '.'))
|
|
29
28
|
const isDir = statSync(abs).isDirectory()
|
|
30
29
|
const scanned = scanCflowFiles(isDir ? abs : dirname(abs))
|
|
31
|
-
const
|
|
32
|
-
|
|
33
|
-
|
|
30
|
+
const scannedPlusArg = isDir || scanned.includes(abs) ? scanned : [abs, ...scanned]
|
|
31
|
+
// no bun = no bundled examples: node refuses to import TypeScript under
|
|
32
|
+
// node_modules (the cli re-execs into bun when it can, comfy-ts-cli.ts)
|
|
33
|
+
const canImportBundled = process.versions.bun != null
|
|
34
|
+
const examplesDir = canImportBundled ? bundledExamplesDir() : null
|
|
35
|
+
if (!canImportBundled && target == null)
|
|
36
|
+
logError('packaged examples skipped: importing .cflow.ts from node_modules needs bun (bunx --bun comfy-ts tui)')
|
|
37
|
+
const discovery = mergeWorkflowSources({
|
|
38
|
+
explicitTarget: target != null,
|
|
39
|
+
scanned: scannedPlusArg,
|
|
40
|
+
bundledFiles: examplesDir == null ? [] : scanCflowFiles(realpathSync(examplesDir)),
|
|
41
|
+
})
|
|
42
|
+
const workflowFiles = discovery.files
|
|
43
|
+
if (workflowFiles.length === 0) {
|
|
34
44
|
console.error(`[comfy-ts tui] no **/*.cflow.ts found under ${abs}`)
|
|
35
45
|
return 1
|
|
36
46
|
}
|
|
37
47
|
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
48
|
+
// initial module = the file arg, else the first candidate that LOADS: a
|
|
49
|
+
// module whose import throws (missing schema cache, bad code) or that
|
|
50
|
+
// exports no DefinedWorkflow becomes a red row in the tree, never a crash
|
|
51
|
+
const candidates =
|
|
52
|
+
!isDir && workflowFiles.includes(abs) ? [abs, ...workflowFiles.filter((f) => f !== abs)] : workflowFiles
|
|
53
|
+
const loadErrors = new Map<string, string>()
|
|
54
|
+
let first: string | null = null
|
|
55
|
+
let wf: DefinedWorkflow | null = null
|
|
56
|
+
for (const file of candidates) {
|
|
57
|
+
try {
|
|
58
|
+
const mod: Record<string, unknown> = await import(pathToFileURL(file).href)
|
|
59
|
+
const found = findDefinedWorkflow(mod)
|
|
60
|
+
if (found == null)
|
|
61
|
+
throw new Error(`${file} exports no DefinedWorkflow — export the result of host.defineWorkflow(...)`)
|
|
62
|
+
first = file
|
|
63
|
+
wf = found
|
|
64
|
+
break
|
|
65
|
+
} catch (e) {
|
|
66
|
+
loadErrors.set(file, extractErrorMessage(e))
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
if (first == null || wf == null) {
|
|
70
|
+
console.error(`[comfy-ts tui] no loadable workflow module among ${candidates.length} file(s):`)
|
|
71
|
+
for (const [file, err] of loadErrors) console.error(` ${file}: ${err}`)
|
|
44
72
|
return 1
|
|
45
73
|
}
|
|
46
74
|
|
|
47
|
-
const st = new TuiSt(wf, { workflowFiles, currentFile: first })
|
|
75
|
+
const st = new TuiSt(wf, { workflowFiles, currentFile: first, bundledFiles: discovery.bundled, loadErrors })
|
|
48
76
|
// ALT SCREEN (TTY only): deterministic absolute coordinates for the protocol
|
|
49
77
|
// image painter + no scrollback pollution / clipped first row.
|
|
50
78
|
// modifyOtherKeys mode 1 rides along: vscode/xterm.js then ENCODES modified ⏎
|
|
@@ -67,7 +95,10 @@ export async function runTui(args: string[]): Promise<number> {
|
|
|
67
95
|
st.dispose()
|
|
68
96
|
} finally {
|
|
69
97
|
uninstallPainter()
|
|
70
|
-
|
|
98
|
+
// reset colors + erase WHILE STILL in the alt screen: ED deletes iTerm
|
|
99
|
+
// inline images too — without this the last protocol image and stray
|
|
100
|
+
// background colors survive into the shell (his repro)
|
|
101
|
+
if (altScreen) process.stdout.write('\u001b[0m\u001b[2J\u001b[H\u001b[>4;0m\u001b[?1049l')
|
|
71
102
|
}
|
|
72
103
|
return 0
|
|
73
104
|
}
|
|
@@ -50,7 +50,10 @@ export class ExecSt {
|
|
|
50
50
|
this.progress = null
|
|
51
51
|
this.notice = null
|
|
52
52
|
this.currentPromptId = null
|
|
53
|
-
|
|
53
|
+
// latents only: the LAST OUTPUT must survive the run start — the
|
|
54
|
+
// 'latent small' / 'last output' preview settings show it while
|
|
55
|
+
// running (full reset belongs to workflow switches)
|
|
56
|
+
this.st.preview.clearLatent()
|
|
54
57
|
// installed while ANY run is in flight, so queued prompts keep painting latents
|
|
55
58
|
host.onLatentPreview = (p) => void this.st.preview.renderLatent(p.bytes)
|
|
56
59
|
}
|
|
@@ -1,14 +1,129 @@
|
|
|
1
|
-
import { makeAutoObservable, runInAction } from 'mobx'
|
|
1
|
+
import { makeAutoObservable, reaction, runInAction } from 'mobx'
|
|
2
2
|
import { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'
|
|
3
3
|
import type { ComfyHost } from 'src/host/ComfyHost.ts'
|
|
4
4
|
import type { TuiSt } from 'src/cli/tui/state/TuiSt.ts'
|
|
5
5
|
|
|
6
6
|
type HostAction = { key: 'refresh' | 'restart' | 'clear-queue' | 'interrupt'; label: string }
|
|
7
7
|
|
|
8
|
+
export type HostStatus = 'unknown' | 'up' | 'down'
|
|
9
|
+
|
|
10
|
+
const PROBE_EVERY_MS = 5000
|
|
11
|
+
const PROBE_TIMEOUT_MS = 3000
|
|
12
|
+
|
|
13
|
+
const SPIN_FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
|
|
14
|
+
|
|
8
15
|
/** host panel (`h`): stats about the connected host + maintenance actions */
|
|
9
16
|
export class HostSt {
|
|
10
17
|
constructor(private st: TuiSt) {
|
|
11
18
|
makeAutoObservable<HostSt, 'st'>(this, { st: false })
|
|
19
|
+
void this.probeLoop()
|
|
20
|
+
this.st.disposers.push(() => {
|
|
21
|
+
this.disposed = true
|
|
22
|
+
if (this.loopTimer != null) clearTimeout(this.loopTimer)
|
|
23
|
+
if (this.spinTimer != null) clearInterval(this.spinTimer)
|
|
24
|
+
if (this.countdownTimer != null) clearInterval(this.countdownTimer)
|
|
25
|
+
})
|
|
26
|
+
// switching workflows can switch hosts: back to unknown, re-probe now.
|
|
27
|
+
// probeGen++ kills a chain that is mid-await (its loopTimer isn't set yet,
|
|
28
|
+
// clearing timers alone would leave it alive → duplicate chains forever)
|
|
29
|
+
this.st.disposers.push(
|
|
30
|
+
reaction(
|
|
31
|
+
() => this.st.wf,
|
|
32
|
+
() => {
|
|
33
|
+
runInAction(() => {
|
|
34
|
+
this.status = 'unknown'
|
|
35
|
+
this.statusVia = null
|
|
36
|
+
})
|
|
37
|
+
this.probeGen++
|
|
38
|
+
if (this.loopTimer != null) clearTimeout(this.loopTimer)
|
|
39
|
+
if (this.countdownTimer != null) clearInterval(this.countdownTimer)
|
|
40
|
+
void this.probeLoop()
|
|
41
|
+
},
|
|
42
|
+
),
|
|
43
|
+
)
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** live reachability — down is a state, not an error: the dot is the loud surface */
|
|
47
|
+
status: HostStatus = 'unknown'
|
|
48
|
+
/** 'ws' when the live socket is open, 'http' when only the probe reaches the host */
|
|
49
|
+
statusVia: 'ws' | 'http' | null = null
|
|
50
|
+
/** a probe is in flight (drives the spinner while down) */
|
|
51
|
+
probing: boolean = false
|
|
52
|
+
/** seconds until the next probe (shown while down) */
|
|
53
|
+
retryInS: number = 0
|
|
54
|
+
spinFrame: number = 0
|
|
55
|
+
|
|
56
|
+
private disposed = false
|
|
57
|
+
private probeGen = 0
|
|
58
|
+
private loopTimer: NodeJS.Timeout | null = null
|
|
59
|
+
private spinTimer: NodeJS.Timeout | null = null
|
|
60
|
+
private countdownTimer: NodeJS.Timeout | null = null
|
|
61
|
+
|
|
62
|
+
get spinner(): string {
|
|
63
|
+
return SPIN_FRAMES[this.spinFrame % SPIN_FRAMES.length] ?? '⠋'
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** probe → schedule the next one (setTimeout chain: the countdown is exact) */
|
|
67
|
+
private async probeLoop(): Promise<void> {
|
|
68
|
+
const gen = this.probeGen
|
|
69
|
+
await this.probe()
|
|
70
|
+
if (this.disposed || gen !== this.probeGen) return
|
|
71
|
+
const nextAt = Date.now() + PROBE_EVERY_MS
|
|
72
|
+
runInAction(() => {
|
|
73
|
+
this.retryInS = Math.ceil(PROBE_EVERY_MS / 1000)
|
|
74
|
+
})
|
|
75
|
+
if (this.countdownTimer != null) clearInterval(this.countdownTimer)
|
|
76
|
+
this.countdownTimer = setInterval(() => {
|
|
77
|
+
runInAction(() => {
|
|
78
|
+
this.retryInS = Math.max(0, Math.ceil((nextAt - Date.now()) / 1000))
|
|
79
|
+
})
|
|
80
|
+
}, 250)
|
|
81
|
+
this.countdownTimer.unref?.()
|
|
82
|
+
this.loopTimer = setTimeout(() => {
|
|
83
|
+
if (this.countdownTimer != null) clearInterval(this.countdownTimer)
|
|
84
|
+
void this.probeLoop()
|
|
85
|
+
}, PROBE_EVERY_MS)
|
|
86
|
+
this.loopTimer.unref?.()
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** http is the ground truth: a half-open ws keeps isOpen=true forever, and
|
|
90
|
+
* trusting it would re-create the exact silent-death this dot exists to expose */
|
|
91
|
+
private async probe(): Promise<void> {
|
|
92
|
+
const host = this.host
|
|
93
|
+
runInAction(() => {
|
|
94
|
+
this.probing = true
|
|
95
|
+
})
|
|
96
|
+
// spin interval is LOCAL: an old probe overlapping a reaction-started new
|
|
97
|
+
// one must only clear its own, and only the installed one drives the flag
|
|
98
|
+
const spin = setInterval(() => {
|
|
99
|
+
runInAction(() => {
|
|
100
|
+
this.spinFrame++
|
|
101
|
+
})
|
|
102
|
+
}, 120)
|
|
103
|
+
spin.unref?.()
|
|
104
|
+
this.spinTimer = spin
|
|
105
|
+
let ok = false
|
|
106
|
+
try {
|
|
107
|
+
// host.fetch: /api preferred + auth header, so cloud hosts probe up too
|
|
108
|
+
const res = await host.fetch('/prompt', { signal: AbortSignal.timeout(PROBE_TIMEOUT_MS) })
|
|
109
|
+
void res.body?.cancel()
|
|
110
|
+
ok = res.ok
|
|
111
|
+
} catch {
|
|
112
|
+
ok = false
|
|
113
|
+
} finally {
|
|
114
|
+
clearInterval(spin)
|
|
115
|
+
if (this.spinTimer === spin) {
|
|
116
|
+
this.spinTimer = null
|
|
117
|
+
runInAction(() => {
|
|
118
|
+
this.probing = false
|
|
119
|
+
})
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
if (this.host !== host) return // workflow switched mid-flight: stale verdict
|
|
123
|
+
runInAction(() => {
|
|
124
|
+
this.status = ok ? 'up' : 'down'
|
|
125
|
+
this.statusVia = ok ? (host.isConnected ? 'ws' : 'http') : null
|
|
126
|
+
})
|
|
12
127
|
}
|
|
13
128
|
|
|
14
129
|
ix: number = 0
|
|
@@ -29,6 +144,13 @@ export class HostSt {
|
|
|
29
144
|
get stats(): { label: string; value: string }[] {
|
|
30
145
|
const schema = this.host.schema
|
|
31
146
|
return [
|
|
147
|
+
{
|
|
148
|
+
label: 'status',
|
|
149
|
+
value:
|
|
150
|
+
this.status === 'down'
|
|
151
|
+
? `down · ${this.probing ? `${this.spinner} probing…` : `retry in ${this.retryInS}s`}`
|
|
152
|
+
: this.status + (this.statusVia != null ? ` (${this.statusVia})` : ''),
|
|
153
|
+
},
|
|
32
154
|
{ label: 'node types', value: String(schema.nodes.length) },
|
|
33
155
|
{ label: 'loras', value: String(schema.getLoras().length) },
|
|
34
156
|
{ label: 'embeddings', value: String(schema.data.embeddings.length) },
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { makeAutoObservable, runInAction } from 'mobx'
|
|
2
|
+
import { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'
|
|
3
|
+
import { stripAnsi } from 'src/utils/ansi.ts'
|
|
4
|
+
import { repairMojibake } from 'src/utils/mojibake.ts'
|
|
5
|
+
import type { LogEntry } from 'src/runner/ComfyWsApi.ts'
|
|
6
|
+
import type { ComfyHost } from 'src/host/ComfyHost.ts'
|
|
7
|
+
import type { TuiSt } from 'src/cli/tui/state/TuiSt.ts'
|
|
8
|
+
|
|
9
|
+
const MAX_LINES = 400
|
|
10
|
+
|
|
11
|
+
/** fold write chunks into p.lines (mutated), returns the new partial tail.
|
|
12
|
+
* `\n` commits a line, `\r` resets the partial (tqdm redraws collapse to
|
|
13
|
+
* their last state), ANSI stripped, blank lines dropped. */
|
|
14
|
+
export function assembleLogChunks(p: { lines: string[]; partial: string; entries: LogEntry[] }): string {
|
|
15
|
+
let partial = p.partial
|
|
16
|
+
for (const entry of p.entries) {
|
|
17
|
+
for (const piece of stripAnsi(repairMojibake(entry.m)).split(/(\r\n|\n|\r)/)) {
|
|
18
|
+
if (piece === '\n' || piece === '\r\n') {
|
|
19
|
+
if (partial.trim() !== '') p.lines.push(partial)
|
|
20
|
+
partial = ''
|
|
21
|
+
} else if (piece === '\r') {
|
|
22
|
+
partial = ''
|
|
23
|
+
} else if (piece !== '') {
|
|
24
|
+
partial += piece
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
return partial
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** server console mirror: /internal/logs/raw backfill + ws 'logs' stream.
|
|
32
|
+
* Entries are write CHUNKS, not lines — assembled here (`\n` commits,
|
|
33
|
+
* `\r` resets the partial, so tqdm redraws collapse to their last state). */
|
|
34
|
+
export class LogsSt {
|
|
35
|
+
constructor(private st: TuiSt) {
|
|
36
|
+
makeAutoObservable<LogsSt, 'st'>(this, { st: false })
|
|
37
|
+
this.attach(this.st.wf.host)
|
|
38
|
+
this.st.disposers.push(() => {
|
|
39
|
+
if (this.attached != null) {
|
|
40
|
+
this.attached.onLogs = null
|
|
41
|
+
this.attached.onSession = null
|
|
42
|
+
}
|
|
43
|
+
})
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
lines: string[] = []
|
|
47
|
+
/** chunk tail not yet closed by \n — rendered live (tqdm progress) */
|
|
48
|
+
partial: string = ''
|
|
49
|
+
|
|
50
|
+
private attached: ComfyHost | null = null
|
|
51
|
+
|
|
52
|
+
/** follow the CURRENT workflow's host (re-called on workflow switch) */
|
|
53
|
+
attach(host: ComfyHost): void {
|
|
54
|
+
if (this.attached === host) return
|
|
55
|
+
if (this.attached != null) {
|
|
56
|
+
this.attached.onLogs = null
|
|
57
|
+
this.attached.onSession = null
|
|
58
|
+
// best-effort: switched-away hosts stay connected (loadedHosts), so
|
|
59
|
+
// without this their ws keeps carrying chunks nobody reads; the
|
|
60
|
+
// server drops the sub on disconnect anyway, hence the swallowed error
|
|
61
|
+
if (this.attached.isConnected && this.attached.comfySessionId !== 'temp') {
|
|
62
|
+
void this.attached.subscribeLogs({ enabled: false, clientId: this.attached.comfySessionId }).catch(() => {})
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
this.attached = host
|
|
66
|
+
this.lines = []
|
|
67
|
+
this.partial = ''
|
|
68
|
+
host.onLogs = (p) => this.feed(p.entries)
|
|
69
|
+
// per-sid server state: every (re)connect needs a fresh subscribe
|
|
70
|
+
host.onSession = (sid) => void this.hydrate(host, sid)
|
|
71
|
+
if (host.isConnected && host.comfySessionId !== 'temp') void this.hydrate(host, host.comfySessionId)
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** backfill BEFORE subscribe: entries emitted in the gap are lost, which is
|
|
75
|
+
* the right trade — the reverse order would clobber streamed entries at the
|
|
76
|
+
* reset, and the backfill re-covers the recent past anyway */
|
|
77
|
+
private async hydrate(host: ComfyHost, sid: string): Promise<void> {
|
|
78
|
+
try {
|
|
79
|
+
const raw = await host.fetchRawLogs()
|
|
80
|
+
// attach() switched hosts or the sid rolled again mid-fetch: stale snapshot
|
|
81
|
+
if (this.attached !== host || host.comfySessionId !== sid) return
|
|
82
|
+
runInAction(() => {
|
|
83
|
+
this.lines = []
|
|
84
|
+
this.partial = ''
|
|
85
|
+
})
|
|
86
|
+
this.feed(raw.entries)
|
|
87
|
+
await host.subscribeLogs({ enabled: true, clientId: sid })
|
|
88
|
+
} catch (e) {
|
|
89
|
+
if (this.attached !== host) return
|
|
90
|
+
// the panel is the loud surface: stream failures land as a log line
|
|
91
|
+
this.feed([{ t: '', m: `[comfy-ts] server log stream unavailable: ${extractErrorMessage(e)}\n` }])
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
feed(entries: LogEntry[]): void {
|
|
96
|
+
runInAction(() => {
|
|
97
|
+
this.partial = assembleLogChunks({ lines: this.lines, partial: this.partial, entries })
|
|
98
|
+
if (this.lines.length > MAX_LINES) this.lines.splice(0, this.lines.length - MAX_LINES)
|
|
99
|
+
})
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** last rows to render, live partial included */
|
|
103
|
+
tail(n: number): string[] {
|
|
104
|
+
const rows = this.partial.trim() !== '' ? [...this.lines, this.partial] : this.lines
|
|
105
|
+
return rows.slice(-n)
|
|
106
|
+
}
|
|
107
|
+
}
|