comfy-ts 2.13.0 → 2.15.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 (75) hide show
  1. package/README.md +1 -0
  2. package/dist/{LogsSt-CUeo843w.js → LogsSt-C3UIWR-o.js} +2 -2
  3. package/dist/{LogsSt-CUeo843w.js.map → LogsSt-C3UIWR-o.js.map} +1 -1
  4. package/dist/cli.js +4 -4
  5. package/dist/index.cjs +213 -53
  6. package/dist/index.cjs.map +1 -1
  7. package/dist/index.d.cts +123 -21
  8. package/dist/index.d.ts +123 -21
  9. package/dist/index.js +207 -54
  10. package/dist/index.js.map +1 -1
  11. package/dist/{run-serve-DlRBv_Nk.js → run-serve-B5PfIuhK.js} +310 -88
  12. package/dist/run-serve-B5PfIuhK.js.map +1 -0
  13. package/dist/{run-tui-B5uxm2_l.js → run-tui-D-N4_yyX.js} +15 -9
  14. package/dist/run-tui-D-N4_yyX.js.map +1 -0
  15. package/dist/{schemaDrift-E95iTF7E.js → schemaDrift-BkN8rLiZ.js} +163 -25
  16. package/dist/schemaDrift-BkN8rLiZ.js.map +1 -0
  17. package/dist/serve-web.js +160 -71
  18. package/dist/{state-CUp2J1Zy.js → state-CZsYJqB6.js} +45 -35
  19. package/dist/state-CZsYJqB6.js.map +1 -0
  20. package/dist/web.d.ts +120 -21
  21. package/dist/web.js +196 -51
  22. package/dist/web.js.map +1 -1
  23. package/examples/media/README.md +8 -0
  24. package/examples/media/sine_440hz_3s.flac +0 -0
  25. package/examples/media/testsrc_256x256_3s.mp4 +0 -0
  26. package/examples/rvion/14-video-soundtrack.cflow.ts +47 -0
  27. package/guide-for-agents.md +2 -1
  28. package/package.json +2 -2
  29. package/src/cli/serve/ServeApp.ts +189 -110
  30. package/src/cli/serve/applyVarPayload.ts +5 -3
  31. package/src/cli/serve/describeVar.ts +5 -3
  32. package/src/cli/serve/resultHistory.ts +141 -0
  33. package/src/cli/serve/run-serve.ts +4 -1
  34. package/src/cli/serve/runError.ts +23 -0
  35. package/src/cli/serve/serveSettings.ts +17 -1
  36. package/src/cli/serve/web/api.ts +33 -2
  37. package/src/cli/serve/web/components/App.tsx +6 -4
  38. package/src/cli/serve/web/components/Gallery.tsx +116 -11
  39. package/src/cli/serve/web/components/Icon.tsx +4 -0
  40. package/src/cli/serve/web/components/MemoryBudget.tsx +98 -0
  41. package/src/cli/serve/web/components/RunError.tsx +19 -0
  42. package/src/cli/serve/web/components/ShortcutsModal.tsx +54 -0
  43. package/src/cli/serve/web/components/SideMenu.tsx +14 -0
  44. package/src/cli/serve/web/components/VarsForm.tsx +75 -55
  45. package/src/cli/serve/web/components/controls/BasicControls.tsx +8 -1
  46. package/src/cli/serve/web/components/controls/LorasControl.tsx +6 -3
  47. package/src/cli/serve/web/components/controls/MediaControl.tsx +111 -0
  48. package/src/cli/serve/web/promptEditor/promptExtensions.ts +3 -1
  49. package/src/cli/serve/web/state/FormSt.ts +70 -2
  50. package/src/cli/serve/web/state/RunSt.ts +61 -3
  51. package/src/cli/serve/web/state/WebSt.ts +26 -2
  52. package/src/cli/serve/web/state/formRows.ts +9 -0
  53. package/src/cli/serve/web/state/host.ts +2 -0
  54. package/src/cli/serve/web/state/keptResults.ts +26 -0
  55. package/src/cli/serve/web/state/lightbox.ts +17 -0
  56. package/src/cli/serve/web/state/mediaDrop.ts +76 -0
  57. package/src/cli/serve/web/state/shortcutCatalog.ts +100 -0
  58. package/src/cli/serve/web/state/shortcuts.ts +10 -0
  59. package/src/cli/serve/web/styles.ts +112 -24
  60. package/src/cli/tui/imagePicker/ImagePickerOverlay.tsx +4 -1
  61. package/src/cli/tui/imagePicker/ImagePickerSt.ts +15 -6
  62. package/src/cli/tui/state/TuiSt.ts +1 -1
  63. package/src/coreExports.ts +10 -0
  64. package/src/exampleAssets.ts +13 -3
  65. package/src/host/ComfyUploader.ts +34 -27
  66. package/src/index.ts +1 -1
  67. package/src/runner/ComfyExecution.ts +38 -20
  68. package/src/runner/ComfyWsApi.ts +3 -0
  69. package/src/runner/mediaKinds.ts +51 -0
  70. package/src/vars/ComfyVars.ts +96 -22
  71. package/dist/run-serve-DlRBv_Nk.js.map +0 -1
  72. package/dist/run-tui-B5uxm2_l.js.map +0 -1
  73. package/dist/schemaDrift-E95iTF7E.js.map +0 -1
  74. package/dist/state-CUp2J1Zy.js.map +0 -1
  75. package/src/cli/serve/web/components/controls/ImageControl.tsx +0 -72
@@ -0,0 +1,141 @@
1
+ // the serve process's memory of its last runs: a page reload (or a second window) shows them
2
+ // again. Unsaved outputs keep their bytes here, the ONLY copy, under one byte budget, FIFO.
3
+ // Nothing is written to disk: a server restart forgets it all. PURE, headless-tested
4
+
5
+ export type RunOutput = { filename: string; url: string | null; absPath: string | null }
6
+ export type RunAudioOutput = RunOutput & { mime: string }
7
+
8
+ /** the run reply `POST /generate` answers, and what `GET /results` lists */
9
+ export type RunRecord = {
10
+ ok: true
11
+ module: string
12
+ draft: string
13
+ promptId: string
14
+ durationMs: number
15
+ /** epoch ms: the panel formats it, the server's clock is the one every window shares */
16
+ finishedAt: number
17
+ seeds: Record<string, number>
18
+ savedToDisk: boolean
19
+ texts: { nodeKey: string | null; text: string }[]
20
+ images: RunOutput[]
21
+ audios: RunAudioOutput[]
22
+ /** absent on a record from an older server */
23
+ videos?: RunAudioOutput[]
24
+ }
25
+
26
+ export type MemoryUsage = { usedBytes: number; budgetBytes: number; outputs: number; runs: number }
27
+
28
+ /** the bytes of one unsaved output, under the key its url names */
29
+ export type KeptBlob = { key: string; bytes: Uint8Array; contentType: string }
30
+
31
+ /** how many runs the list keeps, saved or not. The panel shows as many */
32
+ export const KEPT_RUNS = 50
33
+
34
+ export const DEFAULT_MEMORY_BUDGET_MB = 100
35
+
36
+ /** a run and the memory key of each output (null = saved on disk, or never had bytes) */
37
+ type Kept = {
38
+ record: RunRecord
39
+ imageKeys: (string | null)[]
40
+ audioKeys: (string | null)[]
41
+ videoKeys: (string | null)[]
42
+ }
43
+
44
+ export class ResultHistory {
45
+ /** newest first */
46
+ private runs: Kept[] = []
47
+ /** insertion order IS the eviction order */
48
+ private blobs = new Map<string, { bytes: Uint8Array; contentType: string }>()
49
+ private used = 0
50
+
51
+ constructor(private budgetBytes: number) {}
52
+
53
+ add(p: {
54
+ record: RunRecord
55
+ imageKeys: (string | null)[]
56
+ audioKeys: (string | null)[]
57
+ videoKeys?: (string | null)[]
58
+ blobs: KeptBlob[]
59
+ }): void {
60
+ this.remove(p.record.promptId)
61
+ for (const b of p.blobs) {
62
+ this.blobs.set(b.key, { bytes: b.bytes, contentType: b.contentType })
63
+ this.used += b.bytes.byteLength
64
+ }
65
+ const kept = { record: p.record, imageKeys: p.imageKeys, audioKeys: p.audioKeys, videoKeys: p.videoKeys ?? [] }
66
+ this.runs = [kept, ...this.runs]
67
+ for (const dropped of this.runs.slice(KEPT_RUNS)) this.freeRun(dropped)
68
+ this.runs = this.runs.slice(0, KEPT_RUNS)
69
+ this.evict()
70
+ }
71
+
72
+ blob(key: string): { bytes: Uint8Array; contentType: string } | null {
73
+ return this.blobs.get(key) ?? null
74
+ }
75
+
76
+ /** an output whose bytes were evicted lists with url null: the panel says it is gone */
77
+ list(): RunRecord[] {
78
+ return this.runs.map((k) => ({
79
+ ...k.record,
80
+ images: k.record.images.map((img, ix) => this.withLiveUrl(img, k.imageKeys[ix])),
81
+ audios: k.record.audios.map((a, ix) => this.withLiveUrl(a, k.audioKeys[ix])),
82
+ videos: (k.record.videos ?? []).map((a, ix) => this.withLiveUrl(a, k.videoKeys[ix])),
83
+ }))
84
+ }
85
+
86
+ remove(promptId: string): void {
87
+ const hit = this.runs.find((k) => k.record.promptId === promptId)
88
+ if (hit == null) return
89
+ this.freeRun(hit)
90
+ this.runs = this.runs.filter((k) => k !== hit)
91
+ }
92
+
93
+ clear(): void {
94
+ this.runs = []
95
+ this.blobs.clear()
96
+ this.used = 0
97
+ }
98
+
99
+ setBudget(bytes: number): void {
100
+ this.budgetBytes = bytes
101
+ this.evict()
102
+ }
103
+
104
+ usage(): MemoryUsage {
105
+ return { usedBytes: this.used, budgetBytes: this.budgetBytes, outputs: this.blobs.size, runs: this.runs.length }
106
+ }
107
+
108
+ private withLiveUrl<T extends RunOutput>(out: T, key: string | null | undefined): T {
109
+ if (key == null || this.blobs.has(key)) return out
110
+ return { ...out, url: null }
111
+ }
112
+
113
+ private freeRun(k: Kept): void {
114
+ for (const key of [...k.imageKeys, ...k.audioKeys, ...k.videoKeys]) {
115
+ if (key == null) continue
116
+ const b = this.blobs.get(key)
117
+ if (b == null) continue
118
+ this.used -= b.bytes.byteLength
119
+ this.blobs.delete(key)
120
+ }
121
+ }
122
+
123
+ /** the NEWEST output always stays, even alone over budget: the run that just finished must
124
+ * not reply with a url that already 404s */
125
+ private evict(): void {
126
+ while (this.used > this.budgetBytes && this.blobs.size > 1) {
127
+ const oldest = this.blobs.entries().next()
128
+ if (oldest.done === true) break
129
+ this.used -= oldest.value[1].bytes.byteLength
130
+ this.blobs.delete(oldest.value[0])
131
+ }
132
+ // a run with nothing left to show is noise in the list
133
+ this.runs = this.runs.filter((k) => {
134
+ const live = (keys: (string | null)[]): boolean => keys.some((key) => key == null || this.blobs.has(key))
135
+ const hasText = k.record.texts.length > 0
136
+ const hasNothing =
137
+ k.record.images.length === 0 && k.record.audios.length === 0 && (k.record.videos ?? []).length === 0
138
+ return hasText || hasNothing || live(k.imageKeys) || live(k.audioKeys) || live(k.videoKeys)
139
+ })
140
+ }
141
+ }
@@ -18,6 +18,8 @@ import { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'
18
18
 
19
19
  const DEFAULT_PORT = 8288
20
20
  const BODY_CAP = 10_000_000
21
+ /** a video dropped on a media var rides POST /upload as base64 json: ~200 MB of file */
22
+ export const UPLOAD_BODY_CAP = 280_000_000
21
23
 
22
24
  export function parseArgs(args: string[]): { target?: string; port: number; bind: string } | { error: string } {
23
25
  let target: string | undefined
@@ -56,6 +58,7 @@ export function makeRequestListener(app: ServeApp): (req: IncomingMessage, res:
56
58
  'access-control-allow-headers': 'content-type, accept',
57
59
  }
58
60
  return (req, res) => {
61
+ const cap = req.method === 'POST' && (req.url ?? '').split('?')[0] === '/upload' ? UPLOAD_BODY_CAP : BODY_CAP
59
62
  const chunks: Buffer[] = []
60
63
  let size = 0
61
64
  let overflow = false
@@ -63,7 +66,7 @@ export function makeRequestListener(app: ServeApp): (req: IncomingMessage, res:
63
66
  req.on('data', (c: Buffer) => {
64
67
  if (overflow) return
65
68
  size += c.length
66
- if (size > BODY_CAP) {
69
+ if (size > cap) {
67
70
  // answer NOW: a destroyed request never emits 'end'
68
71
  overflow = true
69
72
  res.writeHead(413, { 'content-type': 'application/json', ...cors })
@@ -0,0 +1,23 @@
1
+ // a failed run's error as ONE readable line. ComfyExecution stores ComfyUI's whole
2
+ // execution_error message; every client reads `error` as text
3
+ export function describeRunError(error: unknown): string {
4
+ if (error == null) return 'execution failed'
5
+ if (typeof error === 'string') return error
6
+ if (error instanceof Error) return error.message
7
+ if (typeof error === 'object') {
8
+ const data = (error as { data?: unknown }).data
9
+ if (typeof data === 'object' && data !== null) {
10
+ const d = data as Record<string, unknown>
11
+ if (typeof d.exception_message === 'string') {
12
+ const where = typeof d.node_type === 'string' ? `${d.node_type} (node ${String(d.node_id)}): ` : ''
13
+ const kind = typeof d.exception_type === 'string' && d.exception_type !== '' ? `${d.exception_type}: ` : ''
14
+ return `${where}${kind}${d.exception_message.trim()}`
15
+ }
16
+ }
17
+ }
18
+ try {
19
+ return JSON.stringify(error)
20
+ } catch {
21
+ return String(error)
22
+ }
23
+ }
@@ -7,6 +7,7 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
7
7
  import { stringMap } from 'src/utils/stringMap.ts'
8
8
  import { validSavePrefix } from 'src/utils/safeName.ts'
9
9
  import { dirname } from 'pathe'
10
+ import { DEFAULT_MEMORY_BUDGET_MB } from 'src/cli/serve/resultHistory.ts'
10
11
 
11
12
  export type ServeSettings = {
12
13
  /** false = generations stay in memory, streamed to the client, nothing written to outputs/ */
@@ -17,9 +18,23 @@ export type ServeSettings = {
17
18
  /** module key → subfolder under outputs/ its images land in. Empty/absent = the module key,
18
19
  * which is what serve always used before it was choosable */
19
20
  savePrefix: Record<string, string>
21
+ /** byte budget of the unsaved outputs the process keeps for a reload, oldest dropped first */
22
+ memoryBudgetMb: number
20
23
  }
21
24
 
22
- const DEFAULT_SERVE_SETTINGS: ServeSettings = { saveToDisk: true, hostOverride: {}, savePrefix: {} }
25
+ const DEFAULT_SERVE_SETTINGS: ServeSettings = {
26
+ saveToDisk: true,
27
+ hostOverride: {},
28
+ savePrefix: {},
29
+ memoryBudgetMb: DEFAULT_MEMORY_BUDGET_MB,
30
+ }
31
+
32
+ /** null = not a budget. A hand-written file goes through the same gate as PUT /settings */
33
+ export function validMemoryBudgetMb(raw: unknown): number | null {
34
+ if (typeof raw !== 'number' || !Number.isFinite(raw)) return null
35
+ if (raw < 1 || raw > 100_000) return null
36
+ return Math.round(raw)
37
+ }
23
38
 
24
39
  /** null when no comfyts is registered yet: a ServeApp can be constructed before the global
25
40
  * exists (tests do), and reading a setting must degrade to defaults, never throw */
@@ -69,6 +84,7 @@ export function readServeSettings(): ServeSettings {
69
84
  // hand-written file did not go through that route, and this value becomes an output
70
85
  // directory. One gate on one side is not a gate
71
86
  savePrefix: cleanValues(stringMap(o.savePrefix), validSavePrefix),
87
+ memoryBudgetMb: validMemoryBudgetMb(o.memoryBudgetMb) ?? DEFAULT_SERVE_SETTINGS.memoryBudgetMb,
72
88
  }
73
89
  }
74
90
 
@@ -32,6 +32,9 @@ export type GeneratedText = { nodeKey: string | null; text: string }
32
32
  /** an audio file (SaveAudio*, PreviewAudio): the panel plays it in an <audio> player */
33
33
  export type GeneratedAudio = { filename: string; mime: string; url: string | null; absPath: string | null }
34
34
 
35
+ /** a video file (SaveVideo, SaveWEBM, VHS_VideoCombine): the panel plays it in a <video> player */
36
+ export type GeneratedVideo = GeneratedAudio
37
+
35
38
  export type GenerateOk = {
36
39
  ok: true
37
40
  module: string
@@ -39,15 +42,24 @@ export type GenerateOk = {
39
42
  promptId: string
40
43
  durationMs: number
41
44
  seeds: Record<string, number>
45
+ /** epoch ms, stamped by the server */
46
+ finishedAt?: number
42
47
  images: GeneratedImage[]
43
48
  texts?: GeneratedText[]
44
49
  audios?: GeneratedAudio[]
50
+ videos?: GeneratedVideo[]
45
51
  }
46
52
 
47
53
  async function jsonFetch<T>(url: string, init?: RequestInit): Promise<T> {
48
54
  const res = await fetch(url, init)
49
55
  const body = (await res.json().catch(() => null)) as (T & { error?: string }) | null
50
- if (!res.ok || body == null) throw new Error(body?.error ?? `http ${res.status} on ${url}`)
56
+ if (!res.ok || body == null) {
57
+ // a non-string error would print as "[object Object]"
58
+ const error: unknown = body?.error
59
+ throw new Error(
60
+ typeof error === 'string' ? error : error != null ? JSON.stringify(error) : `http ${res.status} on ${url}`,
61
+ )
62
+ }
51
63
  return body
52
64
  }
53
65
 
@@ -71,6 +83,20 @@ export function postGenerate(p: {
71
83
  })
72
84
  }
73
85
 
86
+ /** the unsaved outputs the serve process holds, against its byte budget */
87
+ export type MemoryUsage = { usedBytes: number; budgetBytes: number; outputs: number; runs: number }
88
+
89
+ /** the last runs the serve process kept: a reload shows them again */
90
+ export function fetchKeptResults(): Promise<{ runs: GenerateOk[]; memory: MemoryUsage }> {
91
+ return jsonFetch('/results')
92
+ }
93
+
94
+ /** no promptId = every kept run */
95
+ export function deleteKeptResults(p: { promptId?: string } = {}): Promise<{ memory: MemoryUsage }> {
96
+ const url = p.promptId == null ? '/results' : `/results/${encodeURIComponent(p.promptId)}`
97
+ return jsonFetch(url, { method: 'DELETE' })
98
+ }
99
+
74
100
  /** the workflow's previews for these values: nothing runs, nothing is written */
75
101
  export function fetchPreviews(p: {
76
102
  module: string
@@ -181,6 +207,7 @@ export type ServeSettings = {
181
207
  saveToDisk: boolean
182
208
  hostOverride: Record<string, string>
183
209
  savePrefix: Record<string, string>
210
+ memoryBudgetMb: number
184
211
  effectivePrefix: Record<string, string>
185
212
  }
186
213
 
@@ -188,7 +215,11 @@ export function fetchSettings(): Promise<ServeSettings> {
188
215
  return jsonFetch('/settings')
189
216
  }
190
217
 
191
- export function saveSettings(p: { saveToDisk?: boolean; savePrefix?: Record<string, string> }): Promise<ServeSettings> {
218
+ export function saveSettings(p: {
219
+ saveToDisk?: boolean
220
+ savePrefix?: Record<string, string>
221
+ memoryBudgetMb?: number
222
+ }): Promise<ServeSettings> {
192
223
  return jsonFetch('/settings', {
193
224
  method: 'PUT',
194
225
  headers: { 'content-type': 'application/json' },
@@ -9,12 +9,15 @@ import { Icon, type IconName } from 'src/cli/serve/web/components/Icon.tsx'
9
9
  import { LATENT_MODES, type LatentMode } from 'src/cli/serve/web/state/latentMode.ts'
10
10
  import { Omnibox, useOmniboxShortcut } from 'src/cli/serve/web/components/Omnibox.tsx'
11
11
  import { TooltipLayer } from 'src/cli/serve/web/components/TooltipLayer.tsx'
12
+ import { MemoryBudgetButton } from 'src/cli/serve/web/components/MemoryBudget.tsx'
13
+ import { RunError } from 'src/cli/serve/web/components/RunError.tsx'
12
14
  import { MOD_KEY } from 'src/cli/serve/web/components/modKey.ts'
13
15
  import { SHORTCUT_KEYS, shortcutOf } from 'src/cli/serve/web/state/shortcuts.ts'
14
16
  import { reaction } from 'mobx'
15
17
  import { collapsedPreview } from 'src/cli/serve/web/state/stableSlots.ts'
16
18
  import { GenerateButton, VarsForm } from 'src/cli/serve/web/components/VarsForm.tsx'
17
19
  import { DraftTabs, useTabShortcuts } from 'src/cli/serve/web/components/DraftTabs.tsx'
20
+ import { ShortcutsModal } from 'src/cli/serve/web/components/ShortcutsModal.tsx'
18
21
  import type { WebSt } from 'src/cli/serve/web/state/WebSt.ts'
19
22
 
20
23
  /** ⌘A / ctrl+A selects the field you are in. The browser does this on its own until something
@@ -217,6 +220,7 @@ const ResultsHead = observer(function ResultsHead(p: { st: WebSt }) {
217
220
  {SHORTCUT_KEYS['toggle-blur']}
218
221
  </span>
219
222
  </button>
223
+ <MemoryBudgetButton st={p.st} />
220
224
  </span>
221
225
  </div>
222
226
  )
@@ -452,13 +456,10 @@ export const App = observer(function App(p: { st: WebSt }) {
452
456
  {p.st.generateInResults ? (
453
457
  <div className="results-run">
454
458
  <GenerateButton st={p.st} />
455
- {/* one line, always reserved: an error arriving never pushes the gallery down */}
456
- <span className="run-error" data-tip={p.st.run.error ?? undefined}>
457
- {p.st.run.error == null ? '' : `🔴 ${p.st.run.error}`}
458
- </span>
459
459
  </div>
460
460
  ) : null}
461
461
  <LivePreviews st={p.st} />
462
+ <RunError st={p.st} />
462
463
  <Gallery st={p.st} compact={layout === 'pinned'} />
463
464
  </div>
464
465
  )
@@ -527,6 +528,7 @@ export const App = observer(function App(p: { st: WebSt }) {
527
528
  </div>
528
529
  {narrow ? <MenuDrawer st={p.st} /> : null}
529
530
  <Omnibox st={p.st} />
531
+ <ShortcutsModal st={p.st} />
530
532
  <TooltipLayer />
531
533
  </div>
532
534
  )
@@ -4,15 +4,30 @@
4
4
  // the button hides where the clipboard api is absent
5
5
  import { Icon } from 'src/cli/serve/web/components/Icon.tsx'
6
6
  import { observer, useLocalObservable } from 'mobx-react-lite'
7
- import { useEffect, useRef } from 'react'
7
+ import { useEffect, useRef, type DragEvent, type ReactNode } from 'react'
8
+ import { encodeDraggedOutput, OUTPUT_DRAG_MIME, type DraggedOutput } from 'src/cli/serve/web/state/mediaDrop.ts'
9
+ import { isEphemeral } from 'src/cli/serve/web/state/keptResults.ts'
8
10
  import { runPreviewSrc } from 'src/cli/serve/web/api.ts'
9
11
  import { asSizeForm } from 'src/cli/serve/web/state/payload.ts'
10
- import { lightboxView, type LightboxTarget } from 'src/cli/serve/web/state/lightbox.ts'
12
+ import { lightboxStep, lightboxView, type LightboxTarget } from 'src/cli/serve/web/state/lightbox.ts'
11
13
  import { copyImageToClipboard } from 'src/cli/serve/web/clipboard.ts'
12
14
  import type { WebSt } from 'src/cli/serve/web/state/WebSt.ts'
13
15
  import { MOD_KEY } from 'src/cli/serve/web/components/modKey.ts'
14
16
  import { SHORTCUT_KEYS } from 'src/cli/serve/web/state/shortcuts.ts'
15
17
 
18
+ /** on an output only the serve process holds: a restart, or the memory budget, loses it */
19
+ function EphemeralPill(p: { out: { url: string | null; absPath: string | null } }): ReactNode {
20
+ if (!isEphemeral(p.out)) return null
21
+ return (
22
+ <span
23
+ className="ephemeral-pill"
24
+ data-tip="not saved: kept in the server memory only, lost on a restart or past the memory budget"
25
+ >
26
+ <Icon name="warn" /> ephemeral
27
+ </span>
28
+ )
29
+ }
30
+
16
31
  /** the unblur shortcut, said ON a blurred image: the place you look when you want it gone */
17
32
  const BlurHint = observer(function BlurHint(p: { st: WebSt }) {
18
33
  if (!p.st.blurResults) return null
@@ -24,6 +39,38 @@ const BlurHint = observer(function BlurHint(p: { st: WebSt }) {
24
39
  )
25
40
  })
26
41
 
42
+ /** one output's drag + its `→ var` buttons: every media var of the SAME kind in the open form */
43
+ function outputDrag(o: DraggedOutput): { draggable: true; onDragStart: (e: DragEvent) => void } {
44
+ return {
45
+ draggable: true,
46
+ onDragStart: (e) => {
47
+ e.dataTransfer.effectAllowed = 'copy'
48
+ e.dataTransfer.setData(OUTPUT_DRAG_MIME, encodeDraggedOutput(o))
49
+ },
50
+ }
51
+ }
52
+
53
+ const UseAs = observer(function UseAs(p: { st: WebSt; out: DraggedOutput }) {
54
+ const targets = (p.st.form?.vars ?? []).filter((v) => v.mediaKind === p.out.kind)
55
+ if (targets.length === 0 || (p.out.url == null && p.out.absPath == null)) return null
56
+ return (
57
+ <div className="use-as">
58
+ {targets.map((v) => (
59
+ <button
60
+ key={v.name}
61
+ type="button"
62
+ className="host-action"
63
+ disabled={v.mediaBusy}
64
+ data-tip={`use this ${p.out.kind} as the '${v.name}' input of the open workflow`}
65
+ onClick={() => void v.takeOutput(p.out)}
66
+ >
67
+ → {v.name}
68
+ </button>
69
+ ))}
70
+ </div>
71
+ )
72
+ })
73
+
27
74
  const canCopy = typeof navigator !== 'undefined' && navigator.clipboard != null
28
75
 
29
76
  type GalleryLocal = {
@@ -97,14 +144,23 @@ const Lightbox = observer(function Lightbox(p: { st: WebSt; local: GalleryLocal
97
144
  previewTick: p.st.run.previewTick,
98
145
  results: p.st.run.results,
99
146
  })
147
+ // ↑ / ↓ step from what is SHOWN: a latent that became its image steps from that image
148
+ const url = box?.url
100
149
  useEffect(() => {
101
150
  if (target == null) return
102
151
  const onKey = (e: KeyboardEvent): void => {
103
- if (e.key === 'Escape') p.local.closeLightbox()
152
+ if (e.key === 'Escape') return p.local.closeLightbox()
153
+ const dir =
154
+ e.key === 'ArrowDown' || e.key === 'ArrowRight' ? 1 : e.key === 'ArrowUp' || e.key === 'ArrowLeft' ? -1 : 0
155
+ if (dir === 0) return
156
+ if (e.metaKey || e.ctrlKey || e.altKey || e.shiftKey || url == null) return
157
+ e.preventDefault()
158
+ const next = lightboxStep({ results: p.st.run.results, url, dir })
159
+ if (next != null) p.local.openLightbox(next)
104
160
  }
105
161
  window.addEventListener('keydown', onKey)
106
162
  return () => window.removeEventListener('keydown', onKey)
107
- }, [target, p.local])
163
+ }, [target, url, p.local, p.st])
108
164
  // wheel is registered BY HAND, non-passive. React attaches wheel at the root as passive, so
109
165
  // its onWheel cannot preventDefault: zooming also scrolled the results column behind the
110
166
  // lightbox, and every tick logged a console error
@@ -170,7 +226,7 @@ const Lightbox = observer(function Lightbox(p: { st: WebSt; local: GalleryLocal
170
226
  {p.local.zoom.toFixed(1)}× · fit
171
227
  </button>
172
228
  ) : (
173
- <span className="hint">scroll to zoom</span>
229
+ <span className="hint">scroll to zoom, ↑ ↓ for the other images</span>
174
230
  )}
175
231
  {canCopy ? (
176
232
  <button type="button" onClick={copy}>
@@ -466,7 +522,16 @@ export const Gallery = observer(function Gallery(p: { st: WebSt; compact?: boole
466
522
  <div className="imgs">
467
523
  {r.images.map((img, ix) =>
468
524
  img.url != null ? (
469
- <div key={img.filename} className="img-cell">
525
+ <div
526
+ key={img.filename}
527
+ className="img-cell"
528
+ {...outputDrag({
529
+ kind: 'image',
530
+ url: img.url,
531
+ absPath: img.absPath,
532
+ filename: img.filename,
533
+ })}
534
+ >
470
535
  <button
471
536
  type="button"
472
537
  className="img-button"
@@ -481,9 +546,14 @@ export const Gallery = observer(function Gallery(p: { st: WebSt; compact?: boole
481
546
  })
482
547
  }}
483
548
  >
484
- <img src={img.url} alt={img.filename} />
549
+ <img src={img.url} alt={img.filename} loading="lazy" />
485
550
  <BlurHint st={p.st} />
551
+ <EphemeralPill out={img} />
486
552
  </button>
553
+ <UseAs
554
+ st={p.st}
555
+ out={{ kind: 'image', url: img.url, absPath: img.absPath, filename: img.filename }}
556
+ />
487
557
  {/* the EMBEDDING page's buttons (host protocol): what it does with the
488
558
  image is its business — send it somewhere, keep it as something */}
489
559
  {p.st.hostActions.length > 0 ? (
@@ -520,25 +590,60 @@ export const Gallery = observer(function Gallery(p: { st: WebSt; compact?: boole
520
590
  </div>
521
591
  ) : (
522
592
  <div key={img.filename} className="noimg">
523
- {img.filename} (not saved locally — no preview)
593
+ {img.filename} (not saved, and no longer in memory)
524
594
  </div>
525
595
  ),
526
596
  )}
527
597
  {(r.audios ?? []).map((a, ix) =>
528
598
  a.url != null ? (
529
- <div key={`${r.promptId}-audio-${ix}`} className="audio-cell">
599
+ <div
600
+ key={`${r.promptId}-audio-${ix}`}
601
+ className="audio-cell"
602
+ {...outputDrag({ kind: 'audio', url: a.url, absPath: a.absPath, filename: a.filename })}
603
+ >
530
604
  <audio controls preload="metadata" src={a.url} />
531
605
  <a className="hint" href={a.url} download={a.filename}>
532
606
  {a.filename}
533
607
  </a>
608
+ <EphemeralPill out={a} />
609
+ <UseAs
610
+ st={p.st}
611
+ out={{ kind: 'audio', url: a.url, absPath: a.absPath, filename: a.filename }}
612
+ />
534
613
  </div>
535
614
  ) : (
536
615
  <div key={`${r.promptId}-audio-${ix}`} className="noimg">
537
- {a.filename} (not kept — no preview)
616
+ {a.filename} (not saved, and no longer in memory)
617
+ </div>
618
+ ),
619
+ )}
620
+ {(r.videos ?? []).map((a, ix) =>
621
+ a.url != null ? (
622
+ <div
623
+ key={`${r.promptId}-video-${ix}`}
624
+ className="video-cell"
625
+ {...outputDrag({ kind: 'video', url: a.url, absPath: a.absPath, filename: a.filename })}
626
+ >
627
+ <video controls muted loop preload="metadata" src={a.url} />
628
+ <a className="hint" href={a.url} download={a.filename}>
629
+ {a.filename}
630
+ </a>
631
+ <EphemeralPill out={a} />
632
+ <UseAs
633
+ st={p.st}
634
+ out={{ kind: 'video', url: a.url, absPath: a.absPath, filename: a.filename }}
635
+ />
636
+ </div>
637
+ ) : (
638
+ <div key={`${r.promptId}-video-${ix}`} className="noimg">
639
+ {a.filename} (not saved, and no longer in memory)
538
640
  </div>
539
641
  ),
540
642
  )}
541
- {r.images.length === 0 && (r.texts ?? []).length === 0 && (r.audios ?? []).length === 0 ? (
643
+ {r.images.length === 0 &&
644
+ (r.texts ?? []).length === 0 &&
645
+ (r.audios ?? []).length === 0 &&
646
+ (r.videos ?? []).length === 0 ? (
542
647
  <div className="noimg">no outputs</div>
543
648
  ) : null}
544
649
  </div>
@@ -55,6 +55,8 @@ export type IconName =
55
55
  | 'folder-tree'
56
56
  | 'server'
57
57
  | 'menu'
58
+ | 'memory'
59
+ | 'keyboard'
58
60
 
59
61
  /** 24x24 viewBox paths, stroked (fill: none) unless the shape reads better solid */
60
62
  const PATHS: Record<IconName, ReactNode> = {
@@ -191,6 +193,8 @@ const PATHS: Record<IconName, ReactNode> = {
191
193
  </>
192
194
  ),
193
195
  menu: <path d="M4 7h16M4 12h16M4 17h16" />,
196
+ memory: <path d="M6 6h12v12H6zM9 9h6v6H9zM9 3v3M15 3v3M9 18v3M15 18v3M3 9h3M3 15h3M18 9h3M18 15h3" />,
197
+ keyboard: <path d="M3 6h18v12H3zM7 10h.01M11 10h.01M15 10h.01M19 10h.01M8 14h8" />,
194
198
  }
195
199
 
196
200
  /** `size` is a multiplier of the surrounding font size, so icons scale with their button */