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.
@@ -1,8 +1,9 @@
1
1
  import { makeAutoObservable, runInAction } from 'mobx'
2
2
  import sharp from 'sharp'
3
+ import { imageMeta } from 'image-meta'
3
4
  import { imageBufferToAnsi } from 'src/utils/ansiImage.ts'
4
5
  import { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'
5
- import type { PreviewMode } from 'src/cli/tui/state/SettingsSt.ts'
6
+ import type { PreviewDuringRun, PreviewRenderer } from 'src/cli/tui/state/SettingsSt.ts'
6
7
  import type { TuiSt } from 'src/cli/tui/state/TuiSt.ts'
7
8
 
8
9
  /** OSC 1337 support: the panel can show REAL images instead of half-blocks */
@@ -12,12 +13,19 @@ export function protocolCapable(): boolean {
12
13
  return term === 'iTerm.app' || term === 'WezTerm' || term === 'vscode' || process.env.LC_TERMINAL === 'iTerm2'
13
14
  }
14
15
 
16
+ type MenuRow = { key: 'panel' | 'renderer' | 'during-run'; label: string; value: string }
17
+
18
+ /** small-latent corner: fraction of the panel each dimension takes */
19
+ const CORNER_FRACTION = 0.38
20
+ /** pixel 'latent small': the sharp-composited thumb takes this fraction of the panel */
21
+ const PIXEL_SMALL_FRACTION = 0.4
22
+
15
23
  /**
16
- * right-side preview panel. The MODE (native/ansi/off) lives in SettingsSt and
17
- * is cycled with `p`. 'native' overlay-paints the REAL image over the panel rect
18
- * (protocolImagePainter.ts); 'ansi' renders truecolor half-blocks; 'off' hides
19
- * the panel. Sources: live latent while running, last output after, selected
20
- * lora while the loras overlay is open.
24
+ * right-side preview panel + its `p` settings menu (mode 'preview').
25
+ * Three independent axes live in SettingsSt: panel on/off, renderer
26
+ * native/pixel, and what to show while running (latent / latent small /
27
+ * last output). Sources: live latent while running, last output after,
28
+ * selected lora while the loras overlay is open.
21
29
  */
22
30
  export class PreviewSt {
23
31
  constructor(private st: TuiSt) {
@@ -31,18 +39,94 @@ export class PreviewSt {
31
39
  /** native mode: pre-shrunk output bytes / raw latent jpeg for the painter */
32
40
  outputBytes: Uint8Array | null = null
33
41
  latentBytes: Uint8Array | null = null
34
- /** last output path, so a mode switch can re-render it */
42
+ /** the latent's pixel dimensions (image-meta) — sizes the native corner box */
43
+ latentDims: { width: number; height: number } | null = null
44
+ /** at least one latent frame arrived this run — false + progress = server sends none */
45
+ latentSeenThisRun: boolean = false
46
+ /** last output path, so a settings change can re-render it */
35
47
  private lastOutputPath: string | null = null
36
48
 
37
- get mode(): PreviewMode {
38
- return this.st.settings.previewMode
39
- }
40
49
  get show(): boolean {
41
- return this.mode !== 'off'
50
+ return this.st.settings.previewPanel
51
+ }
52
+ get renderer(): PreviewRenderer {
53
+ return this.st.settings.previewRenderer
42
54
  }
43
- /** SettingsSt already downgrades native → ansi on incapable terminals */
44
55
  get useNative(): boolean {
45
- return this.mode === 'native'
56
+ return this.renderer === 'native'
57
+ }
58
+ get duringRun(): PreviewDuringRun {
59
+ return this.st.settings.previewDuringRun
60
+ }
61
+ get menuOpen(): boolean {
62
+ return this.st.mode === 'preview'
63
+ }
64
+ /** running + latents wanted + sampling well underway + none arrived = server
65
+ * sends none. The ≥20% gate keeps healthy runs from red-flashing: the first
66
+ * progress tick lands a beat before the first preview frame */
67
+ get latentsMissing(): boolean {
68
+ return (
69
+ this.st.exec.running &&
70
+ this.duringRun !== 'last-output' &&
71
+ (this.st.exec.progress?.percent ?? 0) >= 20 &&
72
+ !this.latentSeenThisRun
73
+ )
74
+ }
75
+
76
+ // ---- `p` settings menu (rendered by PreviewPanel while mode === 'preview') ----
77
+ menuIx: number = 0
78
+
79
+ get menuRows(): MenuRow[] {
80
+ return [
81
+ { key: 'panel', label: 'panel', value: this.show ? 'on' : 'off' },
82
+ {
83
+ key: 'renderer',
84
+ label: 'renderer',
85
+ value: this.renderer + (protocolCapable() ? '' : ' (no protocol support)'),
86
+ },
87
+ {
88
+ key: 'during-run',
89
+ label: 'while running',
90
+ value:
91
+ this.duringRun === 'latent'
92
+ ? 'latent'
93
+ : this.duringRun === 'latent-small'
94
+ ? 'latent small'
95
+ : 'last output',
96
+ },
97
+ ]
98
+ }
99
+
100
+ beginMenu(): void {
101
+ this.st.mode = 'preview'
102
+ this.menuIx = 0
103
+ }
104
+
105
+ blurMenu(): void {
106
+ this.st.mode = 'nav'
107
+ }
108
+
109
+ menuMove(delta: number): void {
110
+ const len = this.menuRows.length
111
+ this.menuIx = (this.menuIx + delta + len) % len
112
+ }
113
+
114
+ /** cycle the selected row's value (settings persist via SettingsSt reaction) */
115
+ menuCycle(delta: number): void {
116
+ const row = this.menuRows[this.menuIx]
117
+ if (row == null) return
118
+ const s = this.st.settings
119
+ if (row.key === 'panel') {
120
+ s.previewPanel = !s.previewPanel
121
+ } else if (row.key === 'renderer') {
122
+ // no protocol support → native is unreachable, pixel is the only value
123
+ if (protocolCapable()) s.previewRenderer = s.previewRenderer === 'native' ? 'pixel' : 'native'
124
+ } else {
125
+ const order: PreviewDuringRun[] = ['latent', 'latent-small', 'last-output']
126
+ const ix = (order.indexOf(s.previewDuringRun) + delta + order.length) % order.length
127
+ s.previewDuringRun = order[ix] ?? 'latent'
128
+ }
129
+ this.onSettingsChanged()
46
130
  }
47
131
 
48
132
  reset(): void {
@@ -50,6 +134,8 @@ export class PreviewSt {
50
134
  this.latentAnsi = null
51
135
  this.outputBytes = null
52
136
  this.latentBytes = null
137
+ this.latentDims = null
138
+ this.latentSeenThisRun = false
53
139
  this.lastOutputPath = null
54
140
  }
55
141
 
@@ -57,23 +143,54 @@ export class PreviewSt {
57
143
  clearLatent(): void {
58
144
  this.latentAnsi = null
59
145
  this.latentBytes = null
146
+ this.latentDims = null
147
+ this.latentSeenThisRun = false
60
148
  }
61
149
 
62
- /** re-render the last output in the newly chosen mode */
63
- onModeChanged(): void {
150
+ /** re-render the last output for the newly chosen settings */
151
+ onSettingsChanged(): void {
64
152
  this.outputAnsi = null
65
153
  this.outputBytes = null
66
- if (this.mode !== 'off' && this.lastOutputPath != null) void this.renderOutput(this.lastOutputPath)
154
+ if (this.show && this.lastOutputPath != null) void this.renderOutput(this.lastOutputPath)
67
155
  }
68
156
 
69
- /** what the painter should show RIGHT NOW (native mode only; mirrors the panel's source) */
157
+ /** what the painter should show RIGHT NOW (native renderer only; mirrors the panel's source) */
70
158
  get protocolImage(): Uint8Array | null {
71
- if (!this.useNative || !this.show) return null
159
+ if (!this.useNative || !this.show || this.menuOpen) return null
72
160
  if (this.st.mode === 'overlay-loras') return this.st.loras.previewBytes
73
- if (this.st.exec.running && this.latentBytes != null) return this.latentBytes
161
+ if (this.st.exec.running) {
162
+ if (this.duringRun === 'latent') return this.latentBytes ?? this.outputBytes
163
+ // latent-small keeps the OUTPUT big (corner carries the latent) — last-output too
164
+ return this.outputBytes
165
+ }
74
166
  return this.outputBytes
75
167
  }
76
168
 
169
+ /** small latent painted over the panel's top-right corner (native + 'latent small' only) */
170
+ get protocolImageCorner(): Uint8Array | null {
171
+ if (!this.useNative || !this.show || this.menuOpen) return null
172
+ if (this.st.mode === 'overlay-loras') return null
173
+ if (this.st.exec.running && this.duringRun === 'latent-small') return this.latentBytes
174
+ return null
175
+ }
176
+
177
+ /** corner cell box matched to the latent's REAL aspect (a mismatched box
178
+ * letterboxes in iTerm — his repro: "some vertical rectangle"). Cells are
179
+ * ~1:2 (w:h), hence the ×2 when converting image aspect to cells. */
180
+ get cornerBox(): { w: number; h: number } {
181
+ let w = Math.max(8, Math.floor(this.width * CORNER_FRACTION))
182
+ const maxH = Math.max(4, Math.floor(this.height * CORNER_FRACTION))
183
+ const dims = this.latentDims
184
+ if (dims == null || dims.width === 0 || dims.height === 0) return { w, h: maxH }
185
+ const aspect = dims.width / dims.height
186
+ let h = Math.max(2, Math.round(w / aspect / 2))
187
+ if (h > maxH) {
188
+ h = maxH
189
+ w = Math.max(4, Math.round(h * aspect * 2))
190
+ }
191
+ return { w, h }
192
+ }
193
+
77
194
  get width(): number {
78
195
  // leave ~64 cols to the vars panel (plus the tree), keep the image between 24 and 80 cells
79
196
  return Math.max(24, Math.min(80, this.st.termCols - 68 - this.st.treeWidth))
@@ -86,7 +203,7 @@ export class PreviewSt {
86
203
 
87
204
  async renderOutput(path: string): Promise<void> {
88
205
  this.lastOutputPath = path
89
- if (this.mode === 'off') return
206
+ if (!this.show) return
90
207
  try {
91
208
  if (this.useNative) {
92
209
  // pre-shrink ONCE: the painter re-uploads on every repaint, so ~100KB beats ~2MB
@@ -114,16 +231,25 @@ export class PreviewSt {
114
231
  /** skip-while-busy: latent frames arrive faster than sharp renders them */
115
232
  private _busy: boolean = false
116
233
  async renderLatent(bytes: Uint8Array): Promise<void> {
117
- if (this.mode === 'off') return
234
+ runInAction(() => {
235
+ this.latentSeenThisRun = true
236
+ })
237
+ if (!this.show || this.duringRun === 'last-output') return
118
238
  if (this.useNative) {
119
- // server jpegs pass through untouched — the terminal scales them
239
+ // server jpegs pass through untouched — the terminal scales them;
240
+ // dims feed cornerBox so the corner rect matches the image aspect
241
+ const meta = imageMeta(bytes)
120
242
  this.latentBytes = bytes
243
+ this.latentDims = meta.width != null && meta.height != null ? { width: meta.width, height: meta.height } : null
121
244
  return
122
245
  }
123
246
  if (this._busy) return
124
247
  this._busy = true
125
248
  try {
126
- const ansi = await imageBufferToAnsi(bytes, { width: this.width, height: this.height })
249
+ const ansi =
250
+ this.duringRun === 'latent-small'
251
+ ? await this.renderLatentSmallPixel(bytes)
252
+ : await imageBufferToAnsi(bytes, { width: this.width, height: this.height })
127
253
  runInAction(() => {
128
254
  this.latentAnsi = ansi
129
255
  })
@@ -135,4 +261,28 @@ export class PreviewSt {
135
261
  this._busy = false
136
262
  }
137
263
  }
264
+
265
+ /** pixel 'latent small': sharp-composite the latent thumb onto the last
266
+ * output (top-right), then ONE half-block render — a string-level overlay
267
+ * was tried and dropped: its space padding reads as black bars */
268
+ private async renderLatentSmallPixel(bytes: Uint8Array): Promise<string> {
269
+ const pxW = this.width
270
+ const pxH = this.height * 2
271
+ const thumb = await sharp(bytes)
272
+ .resize(
273
+ Math.max(8, Math.floor(pxW * PIXEL_SMALL_FRACTION)),
274
+ Math.max(8, Math.floor(pxH * PIXEL_SMALL_FRACTION)),
275
+ { fit: 'inside' },
276
+ )
277
+ .png()
278
+ .toBuffer()
279
+ const outPath = this.lastOutputPath
280
+ if (outPath == null) return imageBufferToAnsi(thumb, { width: this.width, height: this.height })
281
+ const base = await sharp(outPath).resize(pxW, pxH, { fit: 'inside' }).png().toBuffer()
282
+ const composed = await sharp(base)
283
+ .composite([{ input: thumb, gravity: 'northeast' }])
284
+ .png()
285
+ .toBuffer()
286
+ return imageBufferToAnsi(composed, { width: this.width, height: this.height })
287
+ }
138
288
  }
@@ -4,41 +4,62 @@ import { dirname } from 'pathe'
4
4
  import { protocolCapable } from 'src/cli/tui/state/PreviewSt.ts'
5
5
  import type { TuiSt } from 'src/cli/tui/state/TuiSt.ts'
6
6
 
7
- export type PreviewMode = 'native' | 'ansi' | 'off'
7
+ export type PreviewRenderer = 'native' | 'pixel'
8
+ export type PreviewDuringRun = 'latent' | 'latent-small' | 'last-output'
9
+
10
+ export type PreviewSettings = {
11
+ previewPanel: boolean
12
+ previewRenderer: PreviewRenderer
13
+ previewDuringRun: PreviewDuringRun
14
+ }
15
+
16
+ /** read stored preview settings, migrating the legacy single `previewMode`
17
+ * (native|ansi|off) into the three independent axes */
18
+ export function migratePreviewSettings(raw: Record<string, unknown>, defaults: PreviewSettings): PreviewSettings {
19
+ const out = { ...defaults }
20
+ const legacy = raw.previewMode
21
+ if (legacy === 'native') out.previewRenderer = 'native'
22
+ if (legacy === 'ansi') out.previewRenderer = 'pixel'
23
+ if (legacy === 'off') out.previewPanel = false
24
+ if (typeof raw.previewPanel === 'boolean') out.previewPanel = raw.previewPanel
25
+ if (raw.previewRenderer === 'native' || raw.previewRenderer === 'pixel') out.previewRenderer = raw.previewRenderer
26
+ if (
27
+ raw.previewDuringRun === 'latent' ||
28
+ raw.previewDuringRun === 'latent-small' ||
29
+ raw.previewDuringRun === 'last-output'
30
+ )
31
+ out.previewDuringRun = raw.previewDuringRun
32
+ return out
33
+ }
8
34
 
9
35
  /** persisted TUI settings at `.comfy-ts/settings.json` (LOCAL state, gitignored) */
10
36
  export class SettingsSt {
11
37
  constructor(private st: TuiSt) {
12
38
  this.load()
13
- // a non-protocol terminal can't do native — fall the stored setting back to ansi
14
- if (this.previewMode === 'native' && !protocolCapable()) this.previewMode = 'ansi'
39
+ // a non-protocol terminal can't do native — fall the stored setting back to pixel
40
+ if (this.previewRenderer === 'native' && !protocolCapable()) this.previewRenderer = 'pixel'
15
41
  makeAutoObservable<SettingsSt, 'st'>(this, { st: false })
16
42
  this.st.disposers.push(
17
43
  reaction(
18
- () => JSON.stringify({ previewMode: this.previewMode, lastDraft: this.lastDraft }),
44
+ () =>
45
+ JSON.stringify({
46
+ previewPanel: this.previewPanel,
47
+ previewRenderer: this.previewRenderer,
48
+ previewDuringRun: this.previewDuringRun,
49
+ lastDraft: this.lastDraft,
50
+ }),
19
51
  (json) => this.write(json),
20
52
  { delay: 300 },
21
53
  ),
22
54
  )
23
55
  }
24
56
 
25
- previewMode: PreviewMode = protocolCapable() ? 'native' : 'ansi'
57
+ previewPanel: boolean = true
58
+ previewRenderer: PreviewRenderer = protocolCapable() ? 'native' : 'pixel'
59
+ previewDuringRun: PreviewDuringRun = 'latent'
26
60
  /** module basename → the draft that was active last time (reopened on load) */
27
61
  lastDraft: Record<string, string> = {}
28
62
 
29
- setPreviewMode(mode: PreviewMode): void {
30
- this.previewMode = mode
31
- this.st.preview.onModeChanged()
32
- }
33
-
34
- /** `p` cycles native → ansi → off (native skipped when the terminal can't do it) */
35
- cyclePreviewMode(): void {
36
- const order: PreviewMode[] = protocolCapable() ? ['native', 'ansi', 'off'] : ['ansi', 'off']
37
- const next = order[(order.indexOf(this.previewMode) + 1) % order.length] ?? 'off'
38
- this.setPreviewMode(next)
39
- this.st.exec.notice = `preview: ${next}`
40
- }
41
-
42
63
  rememberDraft(moduleKey: string, draft: string): void {
43
64
  this.lastDraft[moduleKey] = draft
44
65
  }
@@ -49,9 +70,15 @@ export class SettingsSt {
49
70
  try {
50
71
  const raw: unknown = JSON.parse(readFileSync(path, 'utf8'))
51
72
  if (raw == null || typeof raw !== 'object') return
52
- const o = raw as { previewMode?: unknown; lastDraft?: unknown }
53
- if (o.previewMode === 'native' || o.previewMode === 'ansi' || o.previewMode === 'off')
54
- this.previewMode = o.previewMode
73
+ const o = raw as Record<string, unknown>
74
+ const preview = migratePreviewSettings(o, {
75
+ previewPanel: this.previewPanel,
76
+ previewRenderer: this.previewRenderer,
77
+ previewDuringRun: this.previewDuringRun,
78
+ })
79
+ this.previewPanel = preview.previewPanel
80
+ this.previewRenderer = preview.previewRenderer
81
+ this.previewDuringRun = preview.previewDuringRun
55
82
  if (o.lastDraft != null && typeof o.lastDraft === 'object')
56
83
  this.lastDraft = { ...(o.lastDraft as Record<string, string>) }
57
84
  } catch {
@@ -4,6 +4,7 @@ import { DraftsSt } from 'src/cli/tui/state/DraftsSt.ts'
4
4
  import { EditorSt } from 'src/cli/tui/state/EditorSt.ts'
5
5
  import { ExecSt } from 'src/cli/tui/state/ExecSt.ts'
6
6
  import { HostSt } from 'src/cli/tui/state/HostSt.ts'
7
+ import { LogsSt } from 'src/cli/tui/state/LogsSt.ts'
7
8
  import { LorasSt } from 'src/cli/tui/state/LorasSt.ts'
8
9
  import { PickerSt } from 'src/cli/tui/state/PickerSt.ts'
9
10
  import { PreviewSt } from 'src/cli/tui/state/PreviewSt.ts'
@@ -14,11 +15,13 @@ import { WorkflowsSt } from 'src/cli/tui/state/WorkflowsSt.ts'
14
15
  import type { DefinedWorkflow } from 'src/vars/DefinedWorkflow.ts'
15
16
 
16
17
  // nav = vars list · tree = left workflow panel · host = host stats/actions ·
18
+ // preview = `p` settings menu in the preview panel ·
17
19
  // edit = inline single-line (numbers + custom prompts) · overlay-* = modal popups
18
20
  export type TuiMode =
19
21
  | 'nav'
20
22
  | 'tree'
21
23
  | 'host'
24
+ | 'preview'
22
25
  | 'edit'
23
26
  | 'overlay-text'
24
27
  | 'overlay-choice'
@@ -45,6 +48,7 @@ export class TuiSt {
45
48
  preview: PreviewSt
46
49
  host: HostSt
47
50
  queue: QueueSt
51
+ logs: LogsSt
48
52
  settings: SettingsSt
49
53
 
50
54
  /** owned cleanups (reactions, listeners) — flushed by dispose() */
@@ -68,6 +72,7 @@ export class TuiSt {
68
72
  preview: false,
69
73
  host: false,
70
74
  queue: false,
75
+ logs: false,
71
76
  settings: false,
72
77
  })
73
78
  this.settings = new SettingsSt(this)
@@ -81,6 +86,7 @@ export class TuiSt {
81
86
  this.preview = new PreviewSt(this)
82
87
  this.host = new HostSt(this)
83
88
  this.queue = new QueueSt(this)
89
+ this.logs = new LogsSt(this)
84
90
  // the TUI is ALWAYS in a draft from the very first frame: the one this
85
91
  // workflow was last in (settings), else 'default'; the current workflow
86
92
  // starts unfolded so its drafts are visible in the tree
@@ -69,6 +69,7 @@ export class WorkflowsSt {
69
69
  this.loadedHosts.add(wf.host)
70
70
  this.st.wf = wf
71
71
  this.st.queue.attach(wf.host)
72
+ this.st.logs.attach(wf.host)
72
73
  this.currentPath = path
73
74
  this.st.selIx = 0
74
75
  this.st.mode = 'nav'
@@ -11,10 +11,12 @@ import { convertLiteGraphToPrompt } from 'src/sdk-generator/litegraphToApiReques
11
11
  import { asComfyWorkflowID, ComfyWorkflow } from 'src/runner/ComfyWorkflow.ts'
12
12
  import {
13
13
  type ComfyStatusData,
14
+ type LogEntry,
14
15
  type PromptID,
15
16
  type PromptRelated_WsMsg,
16
17
  type WsMsg,
17
18
  WsMsg_ark,
19
+ WsMsgLogsData_ark,
18
20
  } from 'src/runner/ComfyWsApi.ts'
19
21
  import { ComfySchema } from 'src/sdk-generator/ComfySchema.ts'
20
22
  import { type ComfySchemaJSON, ComfySchemaJSON_ark } from 'src/sdk-generator/ComfyUIObjectInfoTypes.ts'
@@ -432,6 +434,34 @@ export class ComfyHost<ID extends string = string> {
432
434
  return this.postJSON_('/interrupt', {})
433
435
  }
434
436
 
437
+ // SERVER LOGS ----------------------------------------------------------------------
438
+ // /internal routes are served bare (no /api prefix, no custom-node hijacks)
439
+
440
+ /** the server's recent console buffer (entries are write CHUNKS, not lines) */
441
+ fetchRawLogs = async (): Promise<{ entries: LogEntry[] }> => {
442
+ const res = await fetch(`${this.getServerHostHTTP()}/internal/logs/raw`)
443
+ if (!res.ok) throw new Error(`GET /internal/logs/raw failed: ${res.status}`)
444
+ const json: unknown = await res.json()
445
+ // wire tolerance (agent/coding.md cast #4): soft-validate, log, still cast
446
+ const checked = WsMsgLogsData_ark(json)
447
+ if (checked instanceof type.errors) {
448
+ console.log(`[🔴] /!\\ /internal/logs/raw payload does not match schema.`)
449
+ printArkResultInConsole(checked)
450
+ }
451
+ return json as { entries: LogEntry[] }
452
+ }
453
+
454
+ /** (un)subscribe THIS session to ws 'logs' messages — per-sid server state,
455
+ * must be re-sent after every reconnect (see onSession) */
456
+ subscribeLogs = async (p: { enabled: boolean; clientId: string }): Promise<void> => {
457
+ const res = await fetch(`${this.getServerHostHTTP()}/internal/logs/subscribe`, {
458
+ method: 'PATCH',
459
+ headers: { 'Content-Type': 'application/json' },
460
+ body: JSON.stringify({ enabled: p.enabled, clientId: p.clientId }),
461
+ })
462
+ if (!res.ok) throw new Error(`PATCH /internal/logs/subscribe failed: ${res.status}`)
463
+ }
464
+
435
465
  /** GET a JSON route, preferring the /api prefix, falling back to the bare route */
436
466
  private fetchJSON_ = async <T>(route: string): Promise<T> => {
437
467
  const base = this.getServerHostHTTP()
@@ -531,6 +561,13 @@ export class ComfyHost<ID extends string = string> {
531
561
  /** fires on every ws 'status' message (queue length lives there) */
532
562
  onStatus: Maybe<(p: { queueRemaining: number }) => void> = null
533
563
 
564
+ /** fires when the server assigns a NEW session id (first connect AND every
565
+ * reconnect — per-sid server state like log subscriptions must be redone) */
566
+ onSession: Maybe<(sid: string) => void> = null
567
+
568
+ /** fires on ws 'logs' messages (server console stream, see subscribeLogs) */
569
+ onLogs: Maybe<(p: { entries: LogEntry[] }) => void> = null
570
+
534
571
  /** the session assigned to us by the server */
535
572
  comfySessionId: string = 'temp' /** send by ComfyUI server */
536
573
 
@@ -601,9 +638,11 @@ export class ComfyHost<ID extends string = string> {
601
638
 
602
639
  if (msg.type === 'status') {
603
640
  if (msg.data.sid) {
641
+ const sidChanged = msg.data.sid !== this.comfySessionId
604
642
  this.comfySessionId = msg.data.sid
605
643
  this._sessionResolve?.()
606
644
  this._sessionResolve = null
645
+ if (sidChanged) this.onSession?.(msg.data.sid)
607
646
  }
608
647
  this.status = msg.data.status
609
648
  this.onStatus?.({ queueRemaining: msg.data.status?.exec_info?.queue_remaining ?? 0 })
@@ -637,6 +676,11 @@ export class ComfyHost<ID extends string = string> {
637
676
  this.addLog(msg.data.data)
638
677
  return
639
678
  }
679
+
680
+ if (msg.type === 'logs') {
681
+ this.onLogs?.(msg.data)
682
+ return
683
+ }
640
684
  exhaust(msg)
641
685
  console.log('❌', 'Unknown message:', msg)
642
686
 
@@ -103,6 +103,14 @@ const tempScope = scope({
103
103
  data: 'WSMsgManagerFeedbackData',
104
104
  },
105
105
 
106
+ // server console stream (/internal/logs): entries are WRITE CHUNKS, not lines
107
+ LogEntry: { t: 'string', m: 'string' },
108
+ _WsMsgLogsData: { entries: 'LogEntry[]', 'size?': 'unknown' },
109
+ WsMsgLogs: {
110
+ type: "'logs'",
111
+ data: '_WsMsgLogsData',
112
+ },
113
+
106
114
  // WsMsgProgress must be after NodeProgress
107
115
  WsMsgProgress: { type: "'progress'", data: 'NodeProgress' },
108
116
 
@@ -119,7 +127,7 @@ const tempScope = scope({
119
127
  // UNION TYPES
120
128
  PromptRelated_WsMsg:
121
129
  'WsMsgExecutionStart | WsMsgExecutionCached | WsMsgExecuting | WsMsgProgress | WsMsgProgressState | WsMsgExecuted | WsMsgExecutionError | WsMsgExecutionSuccess',
122
- WsMsg: 'WsMsgStatus | WSMsgManagerFeedback | PromptRelated_WsMsg',
130
+ WsMsg: 'WsMsgStatus | WSMsgManagerFeedback | WsMsgLogs | PromptRelated_WsMsg',
123
131
  })
124
132
 
125
133
  export const types = tempScope.export()
@@ -145,6 +153,8 @@ export type WsMsgExecuted = typeof types.WsMsgExecuted.infer
145
153
  export type WsMsgExecutionSuccess = typeof types.WsMsgExecutionSuccess.infer
146
154
  export type WsMsgExecutionError = typeof types.WsMsgExecutionError.infer
147
155
  export type WSMsgManagerFeedback = typeof types.WSMsgManagerFeedback.infer
156
+ export type LogEntry = typeof types.LogEntry.infer
157
+ export type WsMsgLogs = typeof types.WsMsgLogs.infer
148
158
  export type _WsMsgExecutionStartData = typeof types._WsMsgExecutionStartData.infer
149
159
  export type _WsMsgExecutionCachedData = typeof types._WsMsgExecutionCachedData.infer
150
160
  export type ComfyImageInfo = typeof types.ComfyImageInfo.infer
@@ -157,3 +167,4 @@ export const PromptInfo_ark = type({ prompt_id: types.PromptID }).as<PromptInfo>
157
167
 
158
168
  export const WsMsg_ark = types.WsMsg
159
169
  export const ComfyImageInfo_ark = types.ComfyImageInfo
170
+ export const WsMsgLogsData_ark = types._WsMsgLogsData
@@ -12,21 +12,6 @@ export class SSHHost {
12
12
  this.activeProcesses = new Set()
13
13
  }
14
14
 
15
- async ensurePortForward(port: number): Promise<void> {
16
- try {
17
- // Check if master connection exists
18
- await execAsync(`ssh -O check ${this.host} 2>/dev/null`)
19
- console.log('✅ SSH connection already active')
20
- } catch {
21
- // Establish master connection
22
- console.log('🔌 Establishing SSH connection...')
23
- // reverse tunnel form: ssh -fN -R 8084:localhost:8084 <ssh-host>
24
- // https://explainshell.com/explain?cmd=ssh+-fN+-L
25
- await execAsync(`ssh -fN -L ${port}:127.0.0.1:${port} ${this.host}`)
26
- console.log('✅ SSH connection established')
27
- }
28
- }
29
-
30
15
  async executeCommand(command: string): Promise<string> {
31
16
  const { stdout, stderr } = await execAsync(`ssh ${this.host} "${command}"`)
32
17
  if (stderr) console.error('SSH Error:', stderr)
package/src/utils/ansi.ts CHANGED
@@ -24,3 +24,10 @@ function styler(open: string = '', close: string = ''): Styler {
24
24
  }
25
25
 
26
26
  export const ansi: Styler = styler()
27
+
28
+ // CSI sequences + lone ESC-letter escapes (server logs re-rendered inside ink)
29
+ const ANSI_RE = /\x1b\[[0-9;?]*[A-Za-z]|\x1b[A-Za-z]/g
30
+
31
+ export function stripAnsi(s: string): string {
32
+ return s.replace(ANSI_RE, '')
33
+ }
@@ -0,0 +1,60 @@
1
+ // cp1252's 0x80-0x9F specials, unicode → original byte (the rest is latin1: code = byte)
2
+ const CP1252_REVERSE: Record<string, number> = {
3
+ '€': 0x80,
4
+ '‚': 0x82,
5
+ ƒ: 0x83,
6
+ '„': 0x84,
7
+ '…': 0x85,
8
+ '†': 0x86,
9
+ '‡': 0x87,
10
+ ˆ: 0x88,
11
+ '‰': 0x89,
12
+ Š: 0x8a,
13
+ '‹': 0x8b,
14
+ Œ: 0x8c,
15
+ Ž: 0x8e,
16
+ '‘': 0x91,
17
+ '’': 0x92,
18
+ '“': 0x93,
19
+ '”': 0x94,
20
+ '•': 0x95,
21
+ '–': 0x96,
22
+ '—': 0x97,
23
+ '˜': 0x98,
24
+ '™': 0x99,
25
+ š: 0x9a,
26
+ '›': 0x9b,
27
+ œ: 0x9c,
28
+ ž: 0x9e,
29
+ Ÿ: 0x9f,
30
+ }
31
+
32
+ /**
33
+ * repair UTF-8 that was decoded as cp1252 (a Windows server re-reading its own
34
+ * output: `█` E2 96 88 arrives as `â–ˆ`). Reverses the cp1252 map back to
35
+ * bytes and re-decodes as UTF-8; any unmappable char or invalid byte sequence
36
+ * means the text was NOT mojibake — the original is returned untouched.
37
+ */
38
+ export function repairMojibake(s: string): string {
39
+ let suspicious = false
40
+ for (let i = 0; i < s.length; i++) {
41
+ if (s.charCodeAt(i) > 0x7f) {
42
+ suspicious = true
43
+ break
44
+ }
45
+ }
46
+ if (!suspicious) return s
47
+ const bytes = new Uint8Array(s.length)
48
+ for (let i = 0; i < s.length; i++) {
49
+ const code = s.charCodeAt(i)
50
+ if (code <= 0xff) {
51
+ bytes[i] = code
52
+ continue
53
+ }
54
+ const mapped = CP1252_REVERSE[s[i] ?? '']
55
+ if (mapped == null) return s
56
+ bytes[i] = mapped
57
+ }
58
+ const decoded = Buffer.from(bytes).toString('utf8')
59
+ return decoded.includes('�') ? s : decoded
60
+ }