comfy-ts 2.5.0 → 2.7.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 (67) hide show
  1. package/README.md +15 -2
  2. package/dist/{DefinedWorkflow-CnzmQrBh.js → DefinedWorkflow-BJgt5t0x.js} +14 -3
  3. package/dist/DefinedWorkflow-BJgt5t0x.js.map +1 -0
  4. package/dist/{DraftsSt-C1MbWnEp.js → DraftsSt-dizp3VcC.js} +2 -2
  5. package/dist/{DraftsSt-C1MbWnEp.js.map → DraftsSt-dizp3VcC.js.map} +1 -1
  6. package/dist/cli.js +5 -5
  7. package/dist/cli.js.map +1 -1
  8. package/dist/index.cjs +7 -2
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.d.cts +24 -18
  11. package/dist/index.d.ts +24 -18
  12. package/dist/index.js +7 -2
  13. package/dist/index.js.map +1 -1
  14. package/dist/{run-serve-D47Zas-a.js → run-serve-D1Tsuru9.js} +494 -20
  15. package/dist/run-serve-D1Tsuru9.js.map +1 -0
  16. package/dist/{run-tui-t2TRBN0H.js → run-tui-JxlEbb_f.js} +511 -331
  17. package/dist/run-tui-JxlEbb_f.js.map +1 -0
  18. package/dist/serve-web.js +273 -0
  19. package/dist/{state-DY3Mp9Cl.js → state-CaHeDL-0.js} +7 -13
  20. package/dist/state-CaHeDL-0.js.map +1 -0
  21. package/dist/web.d.ts +24 -18
  22. package/dist/web.js +7 -2
  23. package/dist/web.js.map +1 -1
  24. package/examples/web/tsconfig.json +4 -1
  25. package/package.json +7 -5
  26. package/src/cli/comfy-ts-cli.ts +1 -1
  27. package/src/cli/serve/ServeApp.ts +383 -14
  28. package/src/cli/serve/describeVar.ts +6 -1
  29. package/src/cli/serve/promptEnhancers.ts +69 -0
  30. package/src/cli/serve/run-serve.ts +41 -7
  31. package/src/cli/serve/safeName.ts +12 -0
  32. package/src/cli/serve/web/api.ts +128 -0
  33. package/src/cli/serve/web/clipboard.ts +25 -0
  34. package/src/cli/serve/web/components/App.tsx +53 -0
  35. package/src/cli/serve/web/components/Gallery.tsx +186 -0
  36. package/src/cli/serve/web/components/PromptEnhancer.tsx +254 -0
  37. package/src/cli/serve/web/components/Sidebar.tsx +42 -0
  38. package/src/cli/serve/web/components/VarsForm.tsx +184 -0
  39. package/src/cli/serve/web/components/controls/BasicControls.tsx +95 -0
  40. package/src/cli/serve/web/components/controls/ImageControl.tsx +71 -0
  41. package/src/cli/serve/web/components/controls/LorasControl.tsx +340 -0
  42. package/src/cli/serve/web/components/controls/SeedControl.tsx +43 -0
  43. package/src/cli/serve/web/components/controls/SizeControl.tsx +49 -0
  44. package/src/cli/serve/web/llm.ts +254 -0
  45. package/src/cli/serve/web/main.tsx +18 -0
  46. package/src/cli/serve/web/state/EnhancerSt.ts +481 -0
  47. package/src/cli/serve/web/state/FormSt.ts +180 -0
  48. package/src/cli/serve/web/state/RunSt.ts +136 -0
  49. package/src/cli/serve/web/state/WebSt.ts +235 -0
  50. package/src/cli/serve/web/state/payload.ts +110 -0
  51. package/src/cli/serve/web/styles.ts +261 -0
  52. package/src/cli/serve/web/tsconfig.json +15 -0
  53. package/src/cli/serve/webBundle.ts +66 -0
  54. package/src/cli/tui/imageEscapes.ts +105 -0
  55. package/src/cli/tui/imagePicker/ImagePickerSt.ts +21 -8
  56. package/src/cli/tui/protocolImage.ts +39 -0
  57. package/src/cli/tui/protocolImagePainter.ts +56 -23
  58. package/src/cli/tui/run-tui.tsx +3 -2
  59. package/src/cli/tui/state/LorasSt.ts +22 -9
  60. package/src/cli/tui/state/PreviewSt.ts +31 -13
  61. package/src/cli/tui/state/SettingsSt.ts +1 -1
  62. package/src/state.ts +6 -0
  63. package/src/vars/ComfyVars.ts +4 -1
  64. package/dist/DefinedWorkflow-CnzmQrBh.js.map +0 -1
  65. package/dist/run-serve-D47Zas-a.js.map +0 -1
  66. package/dist/run-tui-t2TRBN0H.js.map +0 -1
  67. package/dist/state-DY3Mp9Cl.js.map +0 -1
@@ -0,0 +1,69 @@
1
+ // the master prompts of the web ui's prompt enhancer, as FILES:
2
+ // `.comfy-ts/prompt-enhancers/<name>.md`, the drafts model applied to prose.
3
+ // Markdown, not json: these are hand-edited paragraphs, and a json string field
4
+ // would be one escaped line. The FILENAME is the identity (a rename is a write
5
+ // plus a delete); validStoreName is the same gate the draft routes use.
6
+ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
7
+ import { join } from 'pathe'
8
+ import { validStoreName } from 'src/cli/serve/safeName.ts'
9
+
10
+ const EXT = '.md'
11
+
12
+ export type PromptEnhancer = { name: string; text: string }
13
+
14
+ export function promptEnhancersDir(): string {
15
+ return comfyts.resolveFromPromptEnhancers('')
16
+ }
17
+
18
+ export function promptEnhancerPath(name: string): string | null {
19
+ const safe = validStoreName(name)
20
+ return safe == null ? null : join(promptEnhancersDir(), `${safe}${EXT}`)
21
+ }
22
+
23
+ /** the shipped starting point. It is a FILE from the first read on, so it can be edited
24
+ * on disk like everything else — the browser ships no copy of this text */
25
+ const SEED: PromptEnhancer = {
26
+ name: 'refine-krea2-prompt',
27
+ text: `You rewrite image prompts for krea2 turbo, a distilled 8 step text to image model whose text encoder reads flowing natural language, not tag soup, and which is steered by adjectives rather than by negatives.
28
+
29
+ Rewrite the user's prompt into ONE dense paragraph someone could picture with their eyes closed:
30
+ - keep every noun and every named subject the user wrote, they are the point
31
+ - add what is missing to make it fun to look at: lighting, palette, material, texture, camera angle, composition, mood
32
+ - prefer concrete visual nouns over praise, never write "masterpiece", "8k", "highly detailed", "award winning"
33
+ - stay under about 80 words, no lists, no headings, no quotes around the result
34
+ - keep any "// " comment line and any "- " negative line from the input verbatim, each on its own line
35
+
36
+ Answer with the rewritten prompt and nothing else: no preamble, no explanation.
37
+ `,
38
+ }
39
+
40
+ /** seeds ONCE, on an absent folder. A folder he emptied on purpose stays empty */
41
+ export function listPromptEnhancers(): PromptEnhancer[] {
42
+ const dir = promptEnhancersDir()
43
+ if (!existsSync(dir)) writePromptEnhancer(SEED.name, SEED.text)
44
+ if (!existsSync(dir)) return []
45
+ const out: PromptEnhancer[] = []
46
+ for (const file of readdirSync(dir).sort()) {
47
+ if (!file.endsWith(EXT)) continue
48
+ const name = file.slice(0, -EXT.length)
49
+ if (validStoreName(name) == null) continue
50
+ out.push({ name, text: readFileSync(join(dir, file), 'utf8') })
51
+ }
52
+ return out
53
+ }
54
+
55
+ export function writePromptEnhancer(name: string, text: string): string | null {
56
+ const path = promptEnhancerPath(name)
57
+ if (path == null) return null
58
+ mkdirSync(promptEnhancersDir(), { recursive: true })
59
+ writeFileSync(path, text)
60
+ return path
61
+ }
62
+
63
+ /** a missing file is still a success: the caller asked for it to be gone, and it is */
64
+ export function deletePromptEnhancer(name: string): boolean {
65
+ const path = promptEnhancerPath(name)
66
+ if (path == null) return false
67
+ if (existsSync(path)) rmSync(path)
68
+ return true
69
+ }
@@ -1,7 +1,8 @@
1
- // `comfy-ts serve [dir | module.cflow.ts] [--port N] [--bind ADDR]`
1
+ // `comfy-ts serve [dir | module.cflow.ts] [--port N] [--host ADDR]`
2
2
  // drafts as a local HTTP generation API — agent/architecture.md item 12
3
3
  import { statSync } from 'node:fs'
4
4
  import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'
5
+ import { networkInterfaces } from 'node:os'
5
6
  import { pathToFileURL } from 'node:url'
6
7
  import { resolve } from 'pathe'
7
8
  import { scanCflowFiles } from 'src/cli/tui/discoverWorkflows.ts'
@@ -9,12 +10,13 @@ import { findDefinedWorkflow } from 'src/cli/tui/findDefinedWorkflow.ts'
9
10
  import { draftKeyForFile } from 'src/cli/tui/state/DraftsSt.ts'
10
11
  import { describeVar, renderDescriptorLine } from 'src/cli/serve/describeVar.ts'
11
12
  import { ServeApp, type ServeModule } from 'src/cli/serve/ServeApp.ts'
13
+ import { loadOrBuildWebJs } from 'src/cli/serve/webBundle.ts'
12
14
  import { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'
13
15
 
14
16
  const DEFAULT_PORT = 8288
15
17
  const BODY_CAP = 10_000_000
16
18
 
17
- function parseArgs(args: string[]): { target?: string; port: number; bind: string } | { error: string } {
19
+ export function parseArgs(args: string[]): { target?: string; port: number; bind: string } | { error: string } {
18
20
  let target: string | undefined
19
21
  let port = DEFAULT_PORT
20
22
  let bind = '127.0.0.1'
@@ -24,9 +26,10 @@ function parseArgs(args: string[]): { target?: string; port: number; bind: strin
24
26
  const n = Number(args[++i])
25
27
  if (!Number.isInteger(n) || n <= 0 || n > 65535) return { error: `--port expects 1..65535, got '${args[i]}'` }
26
28
  port = n
27
- } else if (a === '--bind') {
29
+ } else if (a === '--host' || a === '--bind') {
30
+ // --host is the spelling; --bind stays an alias so an old command line keeps working
28
31
  const b = args[++i]
29
- if (b == null) return { error: '--bind expects an address' }
32
+ if (b == null) return { error: `${a} expects an address (0.0.0.0 to reach it from another machine)` }
30
33
  bind = b
31
34
  } else if (a != null && a.startsWith('--')) return { error: `unknown flag '${a}'` }
32
35
  else if (a != null) {
@@ -43,7 +46,7 @@ export function makeRequestListener(app: ServeApp): (req: IncomingMessage, res:
43
46
  // local bridge, no auth by design: open CORS so browser frontends can call it
44
47
  const cors = {
45
48
  'access-control-allow-origin': '*',
46
- 'access-control-allow-methods': 'GET, POST, OPTIONS',
49
+ 'access-control-allow-methods': 'GET, POST, PUT, DELETE, OPTIONS',
47
50
  'access-control-allow-headers': 'content-type, accept',
48
51
  }
49
52
  const chunks: Buffer[] = []
@@ -129,7 +132,7 @@ export async function runServe(args: string[]): Promise<number> {
129
132
  return 1
130
133
  }
131
134
 
132
- const app = new ServeApp(modules, { loadErrors })
135
+ const app = new ServeApp(modules, { loadErrors, webJs: loadOrBuildWebJs })
133
136
  printStartup(app, parsed.bind, parsed.port)
134
137
 
135
138
  const server = createServer(makeRequestListener(app))
@@ -147,11 +150,41 @@ export async function runServe(args: string[]): Promise<number> {
147
150
  })
148
151
  }
149
152
 
153
+ export type Nic = { address: string; family: string | number; internal: boolean }
154
+
155
+ /** the addresses this bind actually answers on. `0.0.0.0` means every interface, so printing
156
+ * only that back is useless: the LAN ip and the tailnet 100.x are the urls a phone can open */
157
+ export function reachableAddresses(bind: string, nics: Record<string, Nic[] | undefined>): string[] {
158
+ if (bind !== '0.0.0.0' && bind !== '::') return [bind]
159
+ const found: string[] = []
160
+ for (const list of Object.values(nics)) {
161
+ for (const nic of list ?? []) {
162
+ // node reports family as 'IPv4' or 4 depending on the version
163
+ if (nic.internal || (nic.family !== 'IPv4' && nic.family !== 4)) continue
164
+ found.push(nic.address)
165
+ }
166
+ }
167
+ return ['127.0.0.1', ...found]
168
+ }
169
+
170
+ /** 100.64.0.0/10 is the CGNAT range tailscale hands out — worth naming, it is the one he wants */
171
+ function addressNote(addr: string): string {
172
+ const octets = addr.split('.').map(Number)
173
+ const second = octets[1] ?? 0
174
+ return octets[0] === 100 && second >= 64 && second <= 127 ? ' (tailnet)' : ''
175
+ }
176
+
150
177
  function printStartup(app: ServeApp, bind: string, port: number): void {
151
178
  const base = `http://${bind}:${port}`
152
179
  console.log(`comfy-ts serve · ${app.modules.length} workflow(s) · ${base}/`)
153
- if (bind !== '127.0.0.1' && bind !== 'localhost')
180
+ if (bind !== '127.0.0.1' && bind !== 'localhost') {
154
181
  console.log(`⚠️ bound to ${bind} — this API has NO AUTH and runs workflows on your ComfyUI host`)
182
+ const urls = reachableAddresses(bind, networkInterfaces())
183
+ if (urls.length > 1) {
184
+ console.log('reachable at:')
185
+ for (const addr of urls) console.log(` http://${addr}:${port}/${addressNote(addr)}`)
186
+ }
187
+ }
155
188
  for (const mod of app.modules) {
156
189
  console.log(`\n${mod.key} (host: ${mod.dw.host.data.id})`)
157
190
  for (const draft of app.draftsFor(mod))
@@ -166,4 +199,5 @@ function printStartup(app: ServeApp, bind: string, port: number): void {
166
199
  `\ntry: curl -X POST ${base}/generate/${encodeURIComponent(firstMod.key)}/default -H 'content-type: application/json' -d '{}'`,
167
200
  )
168
201
  console.log(`docs: GET ${base}/drafts (json index of everything above)`)
202
+ console.log(`ui: open ${base}/ in a browser (every var as a form control)`)
169
203
  }
@@ -0,0 +1,12 @@
1
+ // THE name gate for every serve route that turns a url segment into a file path.
2
+ // SECURITY-CRITICAL and deliberately shared: handle() decodes per segment, so
3
+ // `%2F` arrives as a real `/` while the segment count still looks right. One
4
+ // function, because a second regex somewhere else is a second traversal hole.
5
+
6
+ /** the accepted name, or null. Rejects traversal, absolute paths, leading dots and empties */
7
+ export function validStoreName(raw: string): string | null {
8
+ const name = raw.trim()
9
+ // length cap: past it the fs answers ENAMETOOLONG as a raw 500
10
+ if (name.length > 100) return null
11
+ return /^[\w][\w .-]*$/.test(name) ? name : null
12
+ }
@@ -0,0 +1,128 @@
1
+ // typed fetch layer over the serve json api — the ONLY web-ui module that talks http
2
+ import type { VarDescriptor } from 'src/cli/serve/describeVar.ts'
3
+
4
+ export type ModuleDescription = {
5
+ module: string
6
+ file: string
7
+ host: string
8
+ drafts: string[]
9
+ vars: Record<string, VarDescriptor>
10
+ }
11
+
12
+ export type IndexPayload = {
13
+ workflows: ModuleDescription[]
14
+ loadErrors?: Record<string, string>
15
+ }
16
+
17
+ export type GeneratedImage = { filename: string; url: string | null; absPath: string | null }
18
+
19
+ export type GenerateOk = {
20
+ ok: true
21
+ module: string
22
+ draft: string
23
+ promptId: string
24
+ durationMs: number
25
+ seeds: Record<string, number>
26
+ images: GeneratedImage[]
27
+ }
28
+
29
+ async function jsonFetch<T>(url: string, init?: RequestInit): Promise<T> {
30
+ const res = await fetch(url, init)
31
+ const body = (await res.json().catch(() => null)) as (T & { error?: string }) | null
32
+ if (!res.ok || body == null) throw new Error(body?.error ?? `http ${res.status} on ${url}`)
33
+ return body
34
+ }
35
+
36
+ export function fetchIndex(): Promise<IndexPayload> {
37
+ return jsonFetch('/drafts')
38
+ }
39
+
40
+ export function fetchDraftValues(p: { module: string; draft: string }): Promise<{ values: Record<string, unknown> }> {
41
+ return jsonFetch(`/drafts/${encodeURIComponent(p.module)}/${encodeURIComponent(p.draft)}`)
42
+ }
43
+
44
+ export function postGenerate(p: {
45
+ module: string
46
+ draft: string
47
+ payload: Record<string, unknown>
48
+ }): Promise<GenerateOk> {
49
+ return jsonFetch(`/generate/${encodeURIComponent(p.module)}/${encodeURIComponent(p.draft)}`, {
50
+ method: 'POST',
51
+ headers: { 'content-type': 'application/json' },
52
+ body: JSON.stringify(p.payload),
53
+ })
54
+ }
55
+
56
+ export function saveDraft(
57
+ p: { module: string; draft: string; values: Record<string, unknown> },
58
+ opts: { keepalive?: boolean } = {},
59
+ ): Promise<{ ok: true; drafts: string[] }> {
60
+ return jsonFetch(`/drafts/${encodeURIComponent(p.module)}/${encodeURIComponent(p.draft)}`, {
61
+ method: 'PUT',
62
+ headers: { 'content-type': 'application/json' },
63
+ body: JSON.stringify(p.values),
64
+ // keepalive survives page teardown — the beforeunload flush rides it
65
+ keepalive: opts.keepalive === true,
66
+ })
67
+ }
68
+
69
+ export function deleteDraft(p: { module: string; draft: string }): Promise<{ ok: true; drafts: string[] }> {
70
+ return jsonFetch(`/drafts/${encodeURIComponent(p.module)}/${encodeURIComponent(p.draft)}`, { method: 'DELETE' })
71
+ }
72
+
73
+ export type RunStatus = {
74
+ running: boolean
75
+ status: string
76
+ percent: number | null
77
+ hasPreview: boolean
78
+ previewSeq: number | null
79
+ }
80
+
81
+ export function fetchRunStatus(p: { module: string }): Promise<RunStatus> {
82
+ return jsonFetch(`/run/${encodeURIComponent(p.module)}`)
83
+ }
84
+
85
+ export function runPreviewSrc(p: { module: string; tick: number }): string {
86
+ // tick busts the browser cache: same url, new latent every poll
87
+ return `/run/${encodeURIComponent(p.module)}/preview?t=${p.tick}`
88
+ }
89
+
90
+ export type LoraInfo = { name: string; displayName: string; triggerWords: string[] }
91
+
92
+ export function fetchLoraInfo(p: { host: string; name: string }): Promise<LoraInfo> {
93
+ return jsonFetch(`/lora-info/${encodeURIComponent(p.host)}/${encodeURIComponent(p.name)}`)
94
+ }
95
+
96
+ export function loraPreviewSrc(p: { host: string; name: string }): string {
97
+ return `/lora-preview/${encodeURIComponent(p.host)}/${encodeURIComponent(p.name)}`
98
+ }
99
+
100
+ /** master prompts of the enhancer, files under `.comfy-ts/prompt-enhancers/` (server-owned) */
101
+ export type PromptEnhancer = { name: string; text: string }
102
+
103
+ export function fetchPromptEnhancers(): Promise<{ enhancers: PromptEnhancer[] }> {
104
+ return jsonFetch('/prompt-enhancers')
105
+ }
106
+
107
+ export function savePromptEnhancer(p: PromptEnhancer): Promise<{ ok: true; enhancers: PromptEnhancer[] }> {
108
+ return jsonFetch(`/prompt-enhancers/${encodeURIComponent(p.name)}`, {
109
+ method: 'PUT',
110
+ headers: { 'content-type': 'application/json' },
111
+ body: JSON.stringify({ text: p.text }),
112
+ })
113
+ }
114
+
115
+ export function deletePromptEnhancer(p: { name: string }): Promise<{ ok: true; enhancers: PromptEnhancer[] }> {
116
+ return jsonFetch(`/prompt-enhancers/${encodeURIComponent(p.name)}`, { method: 'DELETE' })
117
+ }
118
+
119
+ export async function uploadFile(p: { file: File }): Promise<{ path: string; url: string | null }> {
120
+ const bytes = new Uint8Array(await p.file.arrayBuffer())
121
+ let bin = ''
122
+ for (let i = 0; i < bytes.length; i += 0x8000) bin += String.fromCharCode(...bytes.subarray(i, i + 0x8000))
123
+ return jsonFetch('/upload', {
124
+ method: 'POST',
125
+ headers: { 'content-type': 'application/json' },
126
+ body: JSON.stringify({ name: p.file.name, dataBase64: btoa(bin) }),
127
+ })
128
+ }
@@ -0,0 +1,25 @@
1
+ // copy a served image to the clipboard. ClipboardItem accepts image/png and
2
+ // nothing else that matters, so non-png outputs re-encode through a canvas
3
+ export async function copyImageToClipboard(url: string): Promise<void> {
4
+ const res = await fetch(url)
5
+ if (!res.ok) throw new Error(`fetch failed (http ${res.status})`)
6
+ const blob = await res.blob()
7
+ const png = blob.type === 'image/png' ? blob : await reencodeToPng(blob)
8
+ await navigator.clipboard.write([new ClipboardItem({ 'image/png': png })])
9
+ }
10
+
11
+ async function reencodeToPng(blob: Blob): Promise<Blob> {
12
+ const bitmap = await createImageBitmap(blob)
13
+ const canvas = document.createElement('canvas')
14
+ canvas.width = bitmap.width
15
+ canvas.height = bitmap.height
16
+ const ctx = canvas.getContext('2d')
17
+ if (ctx == null) throw new Error('canvas 2d context unavailable')
18
+ ctx.drawImage(bitmap, 0, 0)
19
+ return await new Promise<Blob>((resolve, reject) => {
20
+ canvas.toBlob((out) => {
21
+ if (out == null) reject(new Error('png encode failed'))
22
+ else resolve(out)
23
+ }, 'image/png')
24
+ })
25
+ }
@@ -0,0 +1,53 @@
1
+ // layout root: topbar (burger toggles the sidebar), sidebar drawer, form
2
+ // column + results column (right on wide screens, below on narrow ones)
3
+ import { observer } from 'mobx-react-lite'
4
+ import { Gallery } from 'src/cli/serve/web/components/Gallery.tsx'
5
+ import { Sidebar } from 'src/cli/serve/web/components/Sidebar.tsx'
6
+ import { VarsForm } from 'src/cli/serve/web/components/VarsForm.tsx'
7
+ import type { WebSt } from 'src/cli/serve/web/state/WebSt.ts'
8
+
9
+ export const App = observer(function App(p: { st: WebSt }) {
10
+ if (p.st.phase === 'loading') return <div className="center">loading…</div>
11
+ if (p.st.phase === 'error')
12
+ return (
13
+ <div className="center">
14
+ <div className="error">🔴 {p.st.bootError}</div>
15
+ </div>
16
+ )
17
+ return (
18
+ <div className="app">
19
+ <div className="topbar">
20
+ <button
21
+ type="button"
22
+ className="burger"
23
+ title="toggle the workflow menu"
24
+ onClick={() => p.st.toggleSidebar()}
25
+ >
26
+ ☰
27
+ </button>
28
+ <h1>comfy-ts serve</h1>
29
+ <span className="dim">
30
+ {p.st.modules.length} workflow{p.st.modules.length === 1 ? '' : 's'} · drafts are the base, edits
31
+ override per run
32
+ </span>
33
+ </div>
34
+ <div className="cols">
35
+ {p.st.sidebarOpen ? <div className="backdrop" onClick={() => p.st.toggleSidebar()} /> : null}
36
+ {p.st.sidebarOpen ? <Sidebar st={p.st} /> : null}
37
+ <div className="main">
38
+ {p.st.formError != null ? <div className="center error">🔴 {p.st.formError}</div> : null}
39
+ {p.st.formLoading && p.st.form == null ? <div className="center">loading draft…</div> : null}
40
+ {p.st.modules.length === 0 ? <div className="center">no workflow modules loaded</div> : null}
41
+ <div className="work">
42
+ <div className="form-col">
43
+ <VarsForm st={p.st} />
44
+ </div>
45
+ <div className="results-col">
46
+ <Gallery st={p.st} />
47
+ </div>
48
+ </div>
49
+ </div>
50
+ </div>
51
+ </div>
52
+ )
53
+ })
@@ -0,0 +1,186 @@
1
+ // results, newest first: per-run delete + clear all; clicking any image (latent
2
+ // included) opens the LIGHTBOX (esc/backdrop closes; copy / open / delete
3
+ // inside). copy needs a secure context (localhost is one, LAN http is not) —
4
+ // the button hides where the clipboard api is absent
5
+ import { observer, useLocalObservable } from 'mobx-react-lite'
6
+ import { useEffect } from 'react'
7
+ import { runPreviewSrc } from 'src/cli/serve/web/api.ts'
8
+ import { copyImageToClipboard } from 'src/cli/serve/web/clipboard.ts'
9
+ import type { WebSt } from 'src/cli/serve/web/state/WebSt.ts'
10
+
11
+ const canCopy = typeof navigator !== 'undefined' && navigator.clipboard != null
12
+
13
+ type LightboxTarget = { url: string; title: string; promptId: string | null }
14
+
15
+ type GalleryLocal = {
16
+ copyNote: { url: string; text: string } | null
17
+ lightbox: LightboxTarget | null
18
+ setCopyNote(url: string, text: string): void
19
+ openLightbox(target: LightboxTarget): void
20
+ closeLightbox(): void
21
+ }
22
+
23
+ function useGalleryLocal(): GalleryLocal {
24
+ return useLocalObservable<GalleryLocal>(() => ({
25
+ copyNote: null,
26
+ lightbox: null,
27
+ setCopyNote(url: string, text: string) {
28
+ this.copyNote = { url, text }
29
+ },
30
+ openLightbox(target: LightboxTarget) {
31
+ this.lightbox = target
32
+ },
33
+ closeLightbox() {
34
+ this.lightbox = null
35
+ },
36
+ }))
37
+ }
38
+
39
+ const Lightbox = observer(function Lightbox(p: { st: WebSt; local: GalleryLocal }) {
40
+ const box = p.local.lightbox
41
+ useEffect(() => {
42
+ if (box == null) return
43
+ const onKey = (e: KeyboardEvent): void => {
44
+ if (e.key === 'Escape') p.local.closeLightbox()
45
+ }
46
+ window.addEventListener('keydown', onKey)
47
+ return () => window.removeEventListener('keydown', onKey)
48
+ }, [box, p.local])
49
+ if (box == null) return null
50
+ const copy = (): void => {
51
+ copyImageToClipboard(box.url)
52
+ .then(() => p.local.setCopyNote(box.url, 'copied ✓'))
53
+ .catch((e: unknown) =>
54
+ p.local.setCopyNote(box.url, `copy failed: ${e instanceof Error ? e.message : String(e)}`),
55
+ )
56
+ }
57
+ return (
58
+ <div className="modal-overlay" onClick={() => p.local.closeLightbox()}>
59
+ <div className="lightbox" onClick={(e) => e.stopPropagation()}>
60
+ <img src={box.url} alt={box.title} />
61
+ <div className="lightbox-bar">
62
+ <span className="hint" title={box.title}>
63
+ {box.title}
64
+ </span>
65
+ {canCopy ? (
66
+ <button type="button" onClick={copy}>
67
+ copy
68
+ </button>
69
+ ) : null}
70
+ <a href={box.url} target="_blank" rel="noreferrer">
71
+ open ↗
72
+ </a>
73
+ {box.promptId != null ? (
74
+ <button
75
+ type="button"
76
+ title="remove this result"
77
+ onClick={() => {
78
+ if (box.promptId != null) p.st.run.remove(box.promptId)
79
+ p.local.closeLightbox()
80
+ }}
81
+ >
82
+ delete
83
+ </button>
84
+ ) : null}
85
+ {p.local.copyNote?.url === box.url ? <span className="hint">{p.local.copyNote.text}</span> : null}
86
+ <button type="button" title="close (esc)" onClick={() => p.local.closeLightbox()}>
87
+ ✕
88
+ </button>
89
+ </div>
90
+ </div>
91
+ </div>
92
+ )
93
+ })
94
+
95
+ /** live card while a run is in flight: progress bar + the latest latent frame */
96
+ const RunningCard = observer(function RunningCard(p: { st: WebSt; local: GalleryLocal }) {
97
+ // the RUNNING module, never the selection: switching modules mid-run must not retarget the card
98
+ const moduleKey = p.st.run.runningModule
99
+ if (!p.st.run.isRunning || moduleKey == null) return null
100
+ const percent = p.st.run.progressPercent
101
+ const previewUrl = runPreviewSrc({ module: moduleKey, tick: p.st.run.previewTick })
102
+ return (
103
+ <div className="run-card running">
104
+ <div className="meta">
105
+ <span>generating {moduleKey}…</span>
106
+ <span>{percent != null ? `${Math.round(percent)}%` : ''}</span>
107
+ </div>
108
+ <div className="progress-track">
109
+ <div className="progress-fill" style={{ width: `${percent ?? 0}%` }} />
110
+ </div>
111
+ {p.st.run.hasPreview ? (
112
+ <div className="imgs">
113
+ <button
114
+ type="button"
115
+ className="img-button"
116
+ onClick={() => p.local.openLightbox({ url: previewUrl, title: 'latent preview', promptId: null })}
117
+ >
118
+ <img src={previewUrl} alt="latent preview" />
119
+ </button>
120
+ </div>
121
+ ) : null}
122
+ </div>
123
+ )
124
+ })
125
+
126
+ export const Gallery = observer(function Gallery(p: { st: WebSt }) {
127
+ const local = useGalleryLocal()
128
+ if (p.st.run.results.length === 0 && !p.st.run.isRunning) return null
129
+ return (
130
+ <div className="gallery">
131
+ <RunningCard st={p.st} local={local} />
132
+ {p.st.run.results.length > 0 ? (
133
+ <div className="gallery-head">
134
+ <span>
135
+ {p.st.run.results.length} result{p.st.run.results.length === 1 ? '' : 's'}
136
+ </span>
137
+ <button type="button" className="link" onClick={() => p.st.run.clear()}>
138
+ clear all
139
+ </button>
140
+ </div>
141
+ ) : null}
142
+ {p.st.run.results.map((r) => (
143
+ <div key={r.promptId} className="run-card">
144
+ <div className="meta">
145
+ <span>
146
+ {r.at} · {r.module}/{r.draft} · {(r.durationMs / 1000).toFixed(1)}s
147
+ {Object.entries(r.seeds).map(([k, seed]) => ` · ${k}: ${seed}`)}
148
+ </span>
149
+ <button
150
+ type="button"
151
+ className="link"
152
+ title="remove this result"
153
+ onClick={() => p.st.run.remove(r.promptId)}
154
+ >
155
+ ✕
156
+ </button>
157
+ </div>
158
+ <div className="imgs">
159
+ {r.images.map((img) =>
160
+ img.url != null ? (
161
+ <button
162
+ key={img.filename}
163
+ type="button"
164
+ className="img-button"
165
+ title={img.filename}
166
+ onClick={() => {
167
+ if (img.url != null)
168
+ local.openLightbox({ url: img.url, title: img.filename, promptId: r.promptId })
169
+ }}
170
+ >
171
+ <img src={img.url} alt={img.filename} />
172
+ </button>
173
+ ) : (
174
+ <div key={img.filename} className="noimg">
175
+ {img.filename} (not saved locally — no preview)
176
+ </div>
177
+ ),
178
+ )}
179
+ {r.images.length === 0 ? <div className="noimg">no image outputs</div> : null}
180
+ </div>
181
+ </div>
182
+ ))}
183
+ <Lightbox st={p.st} local={local} />
184
+ </div>
185
+ )
186
+ })