comfy-ts 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "comfy-ts",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "Type-safe generative AI pipeline creation and execution using ComfyUI",
5
5
  "keywords": [
6
6
  "comfyui",
@@ -42,7 +42,6 @@
42
42
  "files": [
43
43
  "dist",
44
44
  "src",
45
- "!src/__private__",
46
45
  "README.md",
47
46
  "LICENSE"
48
47
  ],
@@ -71,7 +70,7 @@
71
70
  },
72
71
  "rvt": {
73
72
  "skip": [
74
- "src/__private__",
73
+ ".rv-private",
75
74
  "tmp",
76
75
  ".comfy-ts"
77
76
  ]
@@ -37,6 +37,7 @@ export const Header = observer((p: { st: TuiSt }) => {
37
37
  </HeaderBox>
38
38
  <HeaderBox title="(h)ost">
39
39
  <Text>
40
+ <Text color={s.host.status === 'up' ? 'green' : s.host.status === 'down' ? 'red' : 'gray'}>● </Text>
40
41
  <Text bold color="green">
41
42
  {s.wf.host.data.id}
42
43
  </Text>
@@ -44,6 +45,10 @@ export const Header = observer((p: { st: TuiSt }) => {
44
45
  {' '}
45
46
  ({s.wf.host.data.host}:{s.wf.host.data.port})
46
47
  </Text>
48
+ {/* while down, show the probe loop living: spinner in flight, countdown between tries */}
49
+ {s.host.status === 'down' && (
50
+ <Text color="red"> {s.host.probing ? s.host.spinner : `↻ ${s.host.retryInS}s`}</Text>
51
+ )}
47
52
  </Text>
48
53
  </HeaderBox>
49
54
  </Box>
@@ -0,0 +1,23 @@
1
+ import { Box, Text } from 'ink'
2
+ import { observer } from 'mobx-react-lite'
3
+ import type { TuiSt } from 'src/cli/tui/state/TuiSt.ts'
4
+
5
+ const ERROR_RE = /error|exception|traceback|failed/i
6
+
7
+ /** last server console lines (LogsSt), below the vars panel */
8
+ export const LogsPanel = observer((p: { st: TuiSt }) => {
9
+ const rows = p.st.logs.tail(p.st.termRows < 30 ? 4 : 8)
10
+ if (rows.length === 0) return null
11
+ return (
12
+ <Box borderStyle="round" borderColor="gray" paddingX={1} flexDirection="column" flexShrink={0}>
13
+ <Box marginTop={-1}>
14
+ <Text color="gray">comfy host logs</Text>
15
+ </Box>
16
+ {rows.map((line, ix) => (
17
+ <Text key={ix} color={ERROR_RE.test(line) ? 'red' : 'gray'} wrap="truncate-end">
18
+ {line}
19
+ </Text>
20
+ ))}
21
+ </Box>
22
+ )
23
+ })
@@ -2,23 +2,68 @@ import { Box, Text } from 'ink'
2
2
  import { observer } from 'mobx-react-lite'
3
3
  import type { TuiSt } from 'src/cli/tui/state/TuiSt.ts'
4
4
 
5
- /** right-side panel: selected-lora preview in the loras overlay, live latent while running, last output after.
5
+ /** right-side panel: selected-lora preview in the loras overlay, live latent while running,
6
+ * last output after — plus the `p` settings menu (mode 'preview') rendered in place.
6
7
  * protocol terminals: the body is BLANK cells — useProtocolImage paints the real image over them */
7
8
  export const PreviewPanel = observer((p: { st: TuiSt }) => {
8
9
  const s = p.st
9
10
  const pv = s.preview
11
+
12
+ if (pv.menuOpen) {
13
+ return (
14
+ <Box borderStyle="double" paddingX={1} flexDirection="column" flexShrink={0} width={pv.width + 4}>
15
+ <Box marginTop={-1}>
16
+ <Text color="gray">(p)review · settings</Text>
17
+ </Box>
18
+ {pv.menuRows.map((row, ix) => {
19
+ const sel = ix === pv.menuIx
20
+ return (
21
+ <Text key={row.key} inverse={sel} wrap="truncate">
22
+ {sel ? '▸ ' : ' '}
23
+ {row.label.padEnd(14)}
24
+ <Text bold>{row.value}</Text>
25
+ </Text>
26
+ )
27
+ })}
28
+ <Text> </Text>
29
+ <Text color="gray" wrap="truncate">
30
+ ←→ change · ↑↓ move · ⏎/p/esc done
31
+ </Text>
32
+ </Box>
33
+ )
34
+ }
35
+
10
36
  const loraMode = s.mode === 'overlay-loras'
11
- const showLatent = !loraMode && s.exec.running && (pv.latentAnsi != null || pv.latentBytes != null)
12
- const label = loraMode ? `lora ${s.loras.previewName ?? 'lora'}` : showLatent ? 'latent' : 'output'
13
- const placeholder = loraMode ? (s.loras.previewNote ?? '(pick a lora)') : '(no image yet)'
14
- const content = pv.useNative ? null : loraMode ? s.loras.previewAnsi : showLatent ? pv.latentAnsi : pv.outputAnsi
15
- const reserveRect = pv.useNative && pv.protocolImage != null
37
+ const running = s.exec.running
38
+ const wantLatent = running && pv.duringRun !== 'last-output'
39
+ const showLatent = !loraMode && wantLatent && (pv.latentAnsi != null || pv.latentBytes != null)
40
+ const label = loraMode
41
+ ? `lora ${s.loras.previewName ?? 'lora'}`
42
+ : showLatent
43
+ ? pv.duringRun === 'latent-small'
44
+ ? 'latent small'
45
+ : 'latent'
46
+ : 'output'
47
+ const placeholder = loraMode
48
+ ? (s.loras.previewNote ?? '(pick a lora)')
49
+ : pv.latentsMissing
50
+ ? '(no latents from the server — launch comfy with --preview-method auto)'
51
+ : '(no image yet)'
52
+ const content = pv.useNative
53
+ ? null
54
+ : loraMode
55
+ ? s.loras.previewAnsi
56
+ : showLatent
57
+ ? (pv.latentAnsi ?? pv.outputAnsi)
58
+ : pv.outputAnsi
59
+ const reserveRect = pv.useNative && (pv.protocolImage != null || pv.protocolImageCorner != null)
16
60
  return (
17
61
  <Box borderStyle="round" paddingX={1} flexDirection="column" flexShrink={0} width={pv.width + 4}>
18
62
  {/* marginTop -1 lifts the label onto the border line: the panel key IS its title */}
19
63
  <Box marginTop={-1}>
20
64
  <Text color="gray" wrap="truncate">
21
- (p)review · {label}
65
+ (p)review · {label} · {pv.renderer}
66
+ {pv.latentsMissing ? <Text color="red"> · no latents!</Text> : null}
22
67
  </Text>
23
68
  </Box>
24
69
  {reserveRect ? (
@@ -125,6 +125,11 @@ const MODE_KEYS: Partial<Record<string, Hint[]>> = {
125
125
  ['↑↓', 'move'],
126
126
  ['h/esc', 'back'],
127
127
  ],
128
+ preview: [
129
+ ['←→', 'change'],
130
+ ['↑↓', 'move'],
131
+ ['⏎/p/esc', 'done'],
132
+ ],
128
133
  }
129
134
 
130
135
  /** persistent 2-line keybar: EVERYTHING available right now, always visible */
@@ -139,16 +144,17 @@ export const KeyBar = observer((p: { st: TuiSt }) => {
139
144
  // keys already advertised by a panel title (t/v/p) or a header box (w/d/h)
140
145
  // are NOT repeated here — one letter, one place
141
146
  const globalHints: Hint[] =
142
- s.mode === 'nav' || s.mode === 'tree' || s.mode === 'host'
147
+ s.mode === 'nav' || s.mode === 'tree' || s.mode === 'host' || s.mode === 'preview'
143
148
  ? [
144
149
  ['r', 'run'],
145
150
  ['s', 'reroll+run'],
146
151
  ...(s.mode === 'nav' ? ([['e', 'rename draft']] as Hint[]) : []),
147
152
  // the preview panel carries `p` in its title — unless it is hidden
148
- ...(s.preview.show ? [] : ([['p', 'preview off']] as Hint[])),
153
+ ...(s.preview.show || s.mode === 'preview' ? [] : ([['p', 'preview (off)']] as Hint[])),
149
154
  ['o', 'open image'],
150
- // c is duplicate inside the tree — don't advertise the copy pair there
151
- ...(s.mode === 'tree' ? [] : ([['c/C', 'copy wf/api']] as Hint[])),
155
+ // c is duplicate inside the tree — don't advertise the copy pair
156
+ // there; the preview menu doesn't forward it either
157
+ ...(s.mode === 'tree' || s.mode === 'preview' ? [] : ([['c/C', 'copy wf/api']] as Hint[])),
152
158
  ['q', 'quit'],
153
159
  ]
154
160
  : [
@@ -9,6 +9,7 @@ import { ChoiceOverlay, SizeOverlay } from 'src/cli/tui/components/PickerOverlay
9
9
  import { PreviewPanel } from 'src/cli/tui/components/PreviewPanel.tsx'
10
10
  import { PromptOverlay } from 'src/cli/tui/components/PromptOverlay.tsx'
11
11
  import { KeyBar, ProgressLine } from 'src/cli/tui/components/StatusBar.tsx'
12
+ import { LogsPanel } from 'src/cli/tui/components/LogsPanel.tsx'
12
13
  import { TextOverlay } from 'src/cli/tui/components/TextOverlay.tsx'
13
14
  import { TreePanel } from 'src/cli/tui/components/TreePanel.tsx'
14
15
  import { VarsPanel } from 'src/cli/tui/components/VarsPanel.tsx'
@@ -114,7 +115,7 @@ export const TuiApp = observer((p: { st: TuiSt }) => {
114
115
  if (input === 's') return s.exec.randomizeSeedAndRun()
115
116
  if (input === 'd') return s.drafts.begin()
116
117
  if (input === 'h') return s.host.begin()
117
- if (input === 'p') return s.settings.cyclePreviewMode()
118
+ if (input === 'p') return s.preview.beginMenu()
118
119
  if (input === 'o') return s.exec.openLastOutput()
119
120
  if (input === 'q') {
120
121
  s.onExit()
@@ -134,6 +135,26 @@ export const TuiApp = observer((p: { st: TuiSt }) => {
134
135
  }
135
136
  return
136
137
  }
138
+ if (s.mode === 'preview') {
139
+ const pv = s.preview
140
+ // ⏎ CONFIRMS (closes): ←→ already changed the value in place
141
+ if (key.escape || key.return || input === 'p' || input === 'v') return pv.blurMenu()
142
+ if (key.upArrow) return pv.menuMove(-1)
143
+ if (key.downArrow) return pv.menuMove(1)
144
+ if (key.leftArrow) return pv.menuCycle(-1)
145
+ if (key.rightArrow || input === ' ') return pv.menuCycle(1)
146
+ // global keys keep working from the menu (mirrors the tree)
147
+ if (input === 'r') return void s.exec.run()
148
+ if (input === 's') return s.exec.randomizeSeedAndRun()
149
+ if (input === 'd') return s.drafts.begin()
150
+ if (input === 'h') return s.host.begin()
151
+ if (input === 'o') return s.exec.openLastOutput()
152
+ if (input === 'q') {
153
+ s.onExit()
154
+ return app.exit()
155
+ }
156
+ return
157
+ }
137
158
  if (s.mode === 'overlay-drafts') {
138
159
  const d = s.drafts
139
160
  if (key.escape) return s.editor.cancel()
@@ -167,7 +188,7 @@ export const TuiApp = observer((p: { st: TuiSt }) => {
167
188
  if (input === 't' || input === 'w') return s.tree.focus()
168
189
  if (input === 'h') return s.host.begin()
169
190
  if (input === 'd') return s.drafts.begin()
170
- if (input === 'p') return s.settings.cyclePreviewMode()
191
+ if (input === 'p') return s.preview.beginMenu()
171
192
  if (input === 'o') return s.exec.openLastOutput()
172
193
  if (input === 'c') return void s.exec.copyWorkflowJson()
173
194
  if (input === 'C') return void s.exec.copyApiJson()
@@ -214,8 +235,10 @@ export const TuiApp = observer((p: { st: TuiSt }) => {
214
235
  ))}
215
236
  </Box>
216
237
  )}
238
+ {/* hidden while an overlay owns the vars area: typing space > logs */}
239
+ {!s.mode.startsWith('overlay-') && !(s.mode === 'edit' && s.editor.isCustom) && <LogsPanel st={s} />}
217
240
  </Box>
218
- {s.preview.show && <PreviewPanel st={s} />}
241
+ {(s.preview.show || s.preview.menuOpen) && <PreviewPanel st={s} />}
219
242
  </Box>
220
243
  <KeyBar st={s} />
221
244
  </Box>
@@ -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 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).
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 mode: `p` can switch to native at any time —
18
- // protocolImage returns null while the mode is ansi/off, so painting no-ops
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 paint = (): void => {
23
- const bytes = st.preview.protocolImage
24
- if (bytes == null) return
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
- // panel outer left edge +1 border +1 padding; content row = header(3) + border(1) + 1
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
- 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
- )
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
- schedule()
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
  }
@@ -67,7 +67,10 @@ export async function runTui(args: string[]): Promise<number> {
67
67
  st.dispose()
68
68
  } finally {
69
69
  uninstallPainter()
70
- if (altScreen) process.stdout.write('\u001b[>4;0m\u001b[?1049l')
70
+ // reset colors + erase WHILE STILL in the alt screen: ED deletes iTerm
71
+ // inline images too — without this the last protocol image and stray
72
+ // background colors survive into the shell (his repro)
73
+ if (altScreen) process.stdout.write('\u001b[0m\u001b[2J\u001b[H\u001b[>4;0m\u001b[?1049l')
71
74
  }
72
75
  return 0
73
76
  }
@@ -50,7 +50,10 @@ export class ExecSt {
50
50
  this.progress = null
51
51
  this.notice = null
52
52
  this.currentPromptId = null
53
- this.st.preview.reset()
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,130 @@
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
+ const res = await fetch(`${host.getServerHostHTTP()}/api/prompt`, {
108
+ signal: AbortSignal.timeout(PROBE_TIMEOUT_MS),
109
+ })
110
+ void res.body?.cancel()
111
+ ok = res.ok
112
+ } catch {
113
+ ok = false
114
+ } finally {
115
+ clearInterval(spin)
116
+ if (this.spinTimer === spin) {
117
+ this.spinTimer = null
118
+ runInAction(() => {
119
+ this.probing = false
120
+ })
121
+ }
122
+ }
123
+ if (this.host !== host) return // workflow switched mid-flight: stale verdict
124
+ runInAction(() => {
125
+ this.status = ok ? 'up' : 'down'
126
+ this.statusVia = ok ? (host.isConnected ? 'ws' : 'http') : null
127
+ })
12
128
  }
13
129
 
14
130
  ix: number = 0
@@ -29,6 +145,13 @@ export class HostSt {
29
145
  get stats(): { label: string; value: string }[] {
30
146
  const schema = this.host.schema
31
147
  return [
148
+ {
149
+ label: 'status',
150
+ value:
151
+ this.status === 'down'
152
+ ? `down · ${this.probing ? `${this.spinner} probing…` : `retry in ${this.retryInS}s`}`
153
+ : this.status + (this.statusVia != null ? ` (${this.statusVia})` : ''),
154
+ },
32
155
  { label: 'node types', value: String(schema.nodes.length) },
33
156
  { label: 'loras', value: String(schema.getLoras().length) },
34
157
  { 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
+ }