comfy-ts 2.7.0 → 2.9.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 (104) hide show
  1. package/README.md +20 -13
  2. package/dist/{DefinedWorkflow-BJgt5t0x.js → DefinedWorkflow-BatWaZO1.js} +199 -16
  3. package/dist/DefinedWorkflow-BatWaZO1.js.map +1 -0
  4. package/dist/{DraftsSt-dizp3VcC.js → LogsSt-DFxzQfDc.js} +152 -4
  5. package/dist/LogsSt-DFxzQfDc.js.map +1 -0
  6. package/dist/cli.js +7 -5
  7. package/dist/cli.js.map +1 -1
  8. package/dist/index.cjs +284 -35
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.d.cts +125 -7
  11. package/dist/index.d.ts +125 -7
  12. package/dist/index.js +282 -37
  13. package/dist/index.js.map +1 -1
  14. package/dist/run-serve-_nrvJYyt.js +1948 -0
  15. package/dist/run-serve-_nrvJYyt.js.map +1 -0
  16. package/dist/{run-tui-JxlEbb_f.js → run-tui-BLEdTsOX.js} +106 -157
  17. package/dist/run-tui-BLEdTsOX.js.map +1 -0
  18. package/dist/serve-web.js +441 -72
  19. package/dist/{state-CaHeDL-0.js → state-BbgJeCe6.js} +180 -45
  20. package/dist/state-BbgJeCe6.js.map +1 -0
  21. package/dist/web.d.ts +185 -7
  22. package/dist/web.js +235 -36
  23. package/dist/web.js.map +1 -1
  24. package/examples/README.md +1 -0
  25. package/examples/comfy-cloud/sdk.d.ts +4066 -321
  26. package/examples/rvion/04-krea2-turbo-t2i.cflow.ts +18 -2
  27. package/examples/rvion/07-local-llm-text-gen.cflow.ts +220 -0
  28. package/examples/web/tsconfig.json +3 -0
  29. package/extra/README.md +32 -0
  30. package/extra/comfyui-textgen-stream/README.md +35 -0
  31. package/extra/comfyui-textgen-stream/__init__.py +166 -0
  32. package/extra/scripts/fetch_text_encoder.py +137 -0
  33. package/package.json +6 -3
  34. package/src/cli/comfy-ts-cli.ts +3 -1
  35. package/src/cli/serve/ServeApp.ts +754 -40
  36. package/src/cli/serve/applyVarPayload.ts +10 -3
  37. package/src/cli/serve/describeVar.ts +47 -7
  38. package/src/cli/serve/hostProtocol.ts +68 -0
  39. package/src/cli/serve/managerOnlyLoras.ts +27 -0
  40. package/src/cli/serve/run-serve.ts +35 -38
  41. package/src/cli/serve/serveSettings.ts +86 -0
  42. package/src/cli/serve/startupPrint.ts +111 -0
  43. package/src/cli/serve/web/api.ts +97 -1
  44. package/src/cli/serve/web/components/App.tsx +61 -22
  45. package/src/cli/serve/web/components/Gallery.tsx +306 -41
  46. package/src/cli/serve/web/components/Icon.tsx +160 -0
  47. package/src/cli/serve/web/components/PromptEnhancer.tsx +12 -9
  48. package/src/cli/serve/web/components/Sidebar.tsx +43 -19
  49. package/src/cli/serve/web/components/VarsForm.tsx +440 -91
  50. package/src/cli/serve/web/components/controls/BasicControls.tsx +38 -5
  51. package/src/cli/serve/web/components/controls/ImageControl.tsx +3 -2
  52. package/src/cli/serve/web/components/controls/LorasControl.tsx +498 -81
  53. package/src/cli/serve/web/components/controls/PresetPicker.tsx +60 -0
  54. package/src/cli/serve/web/components/controls/SeedControl.tsx +38 -20
  55. package/src/cli/serve/web/components/controls/SizeControl.tsx +3 -2
  56. package/src/cli/serve/web/llm.ts +1 -1
  57. package/src/cli/serve/web/logWeb.ts +6 -0
  58. package/src/cli/serve/web/state/EnhancerSt.ts +8 -15
  59. package/src/cli/serve/web/state/FormSt.ts +74 -18
  60. package/src/cli/serve/web/state/RunSt.ts +22 -1
  61. package/src/cli/serve/web/state/WebSt.ts +814 -22
  62. package/src/cli/serve/web/state/host.ts +206 -0
  63. package/src/cli/serve/web/state/lightbox.ts +44 -0
  64. package/src/cli/serve/web/state/moduleTree.ts +52 -0
  65. package/src/cli/serve/web/state/payload.ts +44 -2
  66. package/src/cli/serve/web/state/urlSelection.ts +53 -0
  67. package/src/cli/serve/web/styles.ts +422 -57
  68. package/src/cli/serve/web/tsconfig.json +4 -0
  69. package/src/cli/tui/components/PickerOverlays.tsx +37 -0
  70. package/src/cli/tui/components/StatusBar.tsx +14 -1
  71. package/src/cli/tui/components/TuiApp.tsx +5 -2
  72. package/src/cli/tui/state/HostSt.ts +3 -2
  73. package/src/cli/tui/state/PickerSt.ts +48 -2
  74. package/src/cli/tui/state/TreeSt.ts +1 -1
  75. package/src/cli/tui/state/TuiSt.ts +2 -1
  76. package/src/coreExports.ts +8 -1
  77. package/src/graph/ComfyNode.ts +58 -1
  78. package/src/host/ComfyHost.ts +13 -2
  79. package/src/host/ComfyManager.ts +31 -13
  80. package/src/host/loraInfoCache.ts +35 -1
  81. package/src/host/loraManagerApi.ts +94 -0
  82. package/src/index.ts +2 -0
  83. package/src/promptEnhancers.ts +102 -0
  84. package/src/runner/ComfyExecution.ts +61 -6
  85. package/src/runner/ComfyWorkflow.ts +18 -4
  86. package/src/runner/ComfyWsApi.ts +3 -0
  87. package/src/runner/describePromptRejection.ts +34 -0
  88. package/src/sdk-generator/ComfySchema.ts +17 -4
  89. package/src/sdk-generator/comfyui-sdk-codegen.ts +56 -2
  90. package/src/utils/ansi.ts +13 -0
  91. package/src/utils/matchesRegex.ts +13 -0
  92. package/src/utils/safeName.ts +29 -0
  93. package/src/utils/stringMap.ts +9 -0
  94. package/src/vars/ComfyVars.ts +61 -10
  95. package/src/vars/presets.ts +17 -0
  96. package/src/web.ts +12 -0
  97. package/dist/DefinedWorkflow-BJgt5t0x.js.map +0 -1
  98. package/dist/DraftsSt-dizp3VcC.js.map +0 -1
  99. package/dist/run-serve-D1Tsuru9.js +0 -1162
  100. package/dist/run-serve-D1Tsuru9.js.map +0 -1
  101. package/dist/run-tui-JxlEbb_f.js.map +0 -1
  102. package/dist/state-CaHeDL-0.js.map +0 -1
  103. package/src/cli/serve/promptEnhancers.ts +0 -69
  104. package/src/cli/serve/safeName.ts +0 -12
@@ -0,0 +1,206 @@
1
+ // the HOST protocol: the panel inside an <iframe>, talking to the page that embeds it. A host
2
+ // cannot read a cross-origin frame (url, dom, storage), so everything it learns is something the
3
+ // panel SAYS. Every message carries a `comfyTs` discriminator, so an unrelated message on the
4
+ // window is ignored. The message types live in src/cli/serve/hostProtocol.ts (re-exported as
5
+ // types by `comfy-ts/web`); the full contract is agent/architecture.md → HOST PROTOCOL.
6
+ //
7
+ // WHO IS THE HOST: only `window.parent`. A message whose `source` is another window is ignored,
8
+ // and the parent's origin is pinned from its first host message (WebSt.onHostMessage).
9
+ // WHAT GOES OUT BEFORE THE PIN: `ready`, `selection` and `error {code:'boot'}` only, to '*'. They
10
+ // carry no draft value. `state` and everything else waits for the host to speak (postTarget).
11
+ //
12
+ // Host messages run IN ORDER, and not before the boot is done: a message that lands while the
13
+ // panel is still loading waits for the form instead of being dropped (WebSt.hostChain).
14
+ // PURE and DOM-free below `isEmbedded`: the parsers are headless-tested.
15
+ import type { VarDescriptor } from 'src/cli/serve/describeVar.ts'
16
+ import type { HostToPanel, PanelHostAction, PanelToHost } from 'src/cli/serve/hostProtocol.ts'
17
+ import { asSeedForm, pruneLorasRecord } from 'src/cli/serve/web/state/payload.ts'
18
+
19
+ function isRecord(v: unknown): v is Record<string, unknown> {
20
+ return v != null && typeof v === 'object'
21
+ }
22
+
23
+ function isPlainRecord(v: unknown): v is Record<string, unknown> {
24
+ return isRecord(v) && !Array.isArray(v)
25
+ }
26
+
27
+ /** a host message, or null for anything else on the window (other frames, devtools, ads).
28
+ * Never throws: a malformed message is simply not ours */
29
+ export function parseFromHost(data: unknown): HostToPanel | null {
30
+ if (!isRecord(data)) return null
31
+ switch (data.comfyTs) {
32
+ case 'set-prompt':
33
+ return typeof data.text === 'string' ? { comfyTs: 'set-prompt', text: data.text } : null
34
+ case 'host-actions': {
35
+ if (!Array.isArray(data.actions)) return null
36
+ const actions: PanelHostAction[] = []
37
+ for (const a of data.actions) {
38
+ if (!isRecord(a) || typeof a.id !== 'string' || a.id === '' || typeof a.label !== 'string') continue
39
+ // a button with no label is invisible, and a second id would make a click ambiguous
40
+ if (a.label === '' || actions.some((x) => x.id === a.id)) continue
41
+ actions.push({ id: a.id, label: a.label, ...(typeof a.title === 'string' ? { title: a.title } : {}) })
42
+ }
43
+ return { comfyTs: 'host-actions', actions }
44
+ }
45
+ case 'set-selection':
46
+ return typeof data.module === 'string' && data.module !== '' && typeof data.draft === 'string'
47
+ ? { comfyTs: 'set-selection', module: data.module, draft: data.draft }
48
+ : null
49
+ case 'set-values':
50
+ return isPlainRecord(data.values) ? { comfyTs: 'set-values', values: data.values } : null
51
+ case 'get-state':
52
+ return { comfyTs: 'get-state' }
53
+ default:
54
+ return null
55
+ }
56
+ }
57
+
58
+ /** where a host's set-selection lands. Same fallback as a url (resolveSelection) with one
59
+ * difference: an unknown MODULE is null, "change nothing", because the panel is already showing
60
+ * something and replacing it with an arbitrary first workflow is not what the host asked */
61
+ export function resolveHostSelection(p: {
62
+ want: { module: string; draft: string }
63
+ modules: readonly { module: string; drafts: readonly string[] }[]
64
+ }): { module: string; draft: string } | null {
65
+ const mod = p.modules.find((m) => m.module === p.want.module)
66
+ if (mod == null) return null
67
+ return { module: mod.module, draft: mod.drafts.includes(p.want.draft) ? p.want.draft : 'default' }
68
+ }
69
+
70
+ export type Coerced = { ok: true; value: unknown } | { ok: false }
71
+
72
+ const REJECT: Coerced = { ok: false }
73
+ const SEED_MODES: readonly string[] = ['=', '+', '-', '?']
74
+
75
+ function isFiniteNumber(v: unknown): v is number {
76
+ return typeof v === 'number' && Number.isFinite(v)
77
+ }
78
+
79
+ /** a strength a lora record may hold: off, on, one strength, or [model, clip] */
80
+ function isLoraEntry(v: unknown): boolean {
81
+ if (typeof v === 'boolean' || isFiniteNumber(v)) return true
82
+ return Array.isArray(v) && v.length === 2 && isFiniteNumber(v[0]) && isFiniteNumber(v[1])
83
+ }
84
+
85
+ /**
86
+ * a value a host sent for one var, held to what the var's CONTROL can produce: a text box
87
+ * gives a string, a number box a finite number (int truncated like parseInt), a select one of
88
+ * its choices, the seed row `{mode, value ≥ 0}`. Anything else is rejected rather than
89
+ * repaired, so a host bug shows up as an unchanged field, not a silently different one.
90
+ * `current` is the var's value now: a bare seed number keeps the current mode, as the box does.
91
+ */
92
+ export function coerceHostValue(desc: VarDescriptor, raw: unknown, current: unknown): Coerced {
93
+ switch (desc.kind) {
94
+ case 'prompt':
95
+ case 'text':
96
+ case 'image':
97
+ return typeof raw === 'string' ? { ok: true, value: raw } : REJECT
98
+ case 'int':
99
+ return isFiniteNumber(raw) ? { ok: true, value: Math.trunc(raw) } : REJECT
100
+ case 'float':
101
+ return isFiniteNumber(raw) ? { ok: true, value: raw } : REJECT
102
+ case 'toggle':
103
+ return typeof raw === 'boolean' ? { ok: true, value: raw } : REJECT
104
+ case 'choice':
105
+ return typeof raw === 'string' && (desc.choices ?? []).includes(raw) ? { ok: true, value: raw } : REJECT
106
+ case 'seed': {
107
+ const cur = asSeedForm(current)
108
+ if (isFiniteNumber(raw)) return { ok: true, value: { mode: cur.mode, value: Math.max(0, Math.floor(raw)) } }
109
+ if (!isPlainRecord(raw)) return REJECT
110
+ if (raw.mode !== undefined && !(typeof raw.mode === 'string' && SEED_MODES.includes(raw.mode))) return REJECT
111
+ if (raw.value !== undefined && !isFiniteNumber(raw.value)) return REJECT
112
+ return {
113
+ ok: true,
114
+ value: {
115
+ mode: typeof raw.mode === 'string' ? raw.mode : cur.mode,
116
+ value: isFiniteNumber(raw.value) ? Math.max(0, Math.floor(raw.value)) : cur.value,
117
+ },
118
+ }
119
+ }
120
+ case 'size': {
121
+ let width: unknown = null
122
+ let height: unknown = null
123
+ if (typeof raw === 'string') {
124
+ const m = /^\s*(\d+)\s*x\s*(\d+)\s*$/i.exec(raw)
125
+ if (m != null) {
126
+ width = Number(m[1])
127
+ height = Number(m[2])
128
+ }
129
+ } else if (isPlainRecord(raw)) {
130
+ width = raw.width
131
+ height = raw.height
132
+ }
133
+ if (!isFiniteNumber(width) || !isFiniteNumber(height) || width < 1 || height < 1) return REJECT
134
+ return { ok: true, value: { width: Math.floor(width), height: Math.floor(height) } }
135
+ }
136
+ case 'loras': {
137
+ if (!isPlainRecord(raw)) return REJECT
138
+ for (const st of Object.values(raw)) if (!isLoraEntry(st)) return REJECT
139
+ // the record the form keeps: known loras that are ON (payload.ts owns the why)
140
+ return { ok: true, value: pruneLorasRecord(raw, desc.options ?? []) }
141
+ }
142
+ default:
143
+ return REJECT
144
+ }
145
+ }
146
+
147
+ /** the var `set-prompt` and `?prompt=` fill: the one declared `kind:'prompt'`, else a TEXT var
148
+ * named like a prompt that is not the negative one. A name alone is not enough: a float
149
+ * `prompt_strength` or a `negative_prompt` declared first must never receive the prompt */
150
+ export function pickPromptVar<V extends { name: string; desc: VarDescriptor }>(vars: readonly V[]): V | null {
151
+ return (
152
+ vars.find((v) => v.desc.kind === 'prompt') ??
153
+ vars.find(
154
+ (v) => (v.desc.kind === 'text' || v.desc.kind === 'prompt') && /prompt/i.test(v.name) && !/neg/i.test(v.name),
155
+ ) ??
156
+ null
157
+ )
158
+ }
159
+
160
+ /** the targetOrigin a panel message goes out with, or null when it must not go out yet.
161
+ * Before the host origin is pinned only messages carrying no draft value may leave, to '*'.
162
+ * An opaque parent origin ("null") cannot be a targetOrigin (postMessage throws), so it is
163
+ * posted with '*': the post goes to window.parent only, which is the window that pinned it */
164
+ export function postTarget(msg: PanelToHost, pinnedOrigin: string | null): string | null {
165
+ if (pinnedOrigin == null) {
166
+ const unpinnedOk =
167
+ msg.comfyTs === 'ready' || msg.comfyTs === 'selection' || (msg.comfyTs === 'error' && msg.code === 'boot')
168
+ return unpinnedOk ? '*' : null
169
+ }
170
+ return pinnedOrigin === 'null' ? '*' : pinnedOrigin
171
+ }
172
+
173
+ /** a host value for a log line. JSON.stringify throws on a BigInt or a cycle, and a throw
174
+ * there used to abort the whole message, reply included */
175
+ export function safeStringify(v: unknown): string {
176
+ try {
177
+ const out = JSON.stringify(v, (_k, x: unknown) => (typeof x === 'bigint' ? `${x}n` : x))
178
+ if (typeof v === 'bigint') return `${v}n`
179
+ return out ?? String(v)
180
+ } catch {
181
+ try {
182
+ return String(v)
183
+ } catch {
184
+ return '[unprintable]'
185
+ }
186
+ }
187
+ }
188
+
189
+ /** `?prompt=<text>` — a host opens the panel with the prompt already in the box */
190
+ export function readUrlPrompt(search: string): string | null {
191
+ try {
192
+ const params = new URLSearchParams(search.startsWith('?') ? search.slice(1) : search)
193
+ const p = params.get('prompt')
194
+ return p == null || p === '' ? null : p
195
+ } catch {
196
+ return null
197
+ }
198
+ }
199
+
200
+ export function isEmbedded(): boolean {
201
+ try {
202
+ return typeof window !== 'undefined' && window.parent !== window
203
+ } catch {
204
+ return false
205
+ }
206
+ }
@@ -0,0 +1,44 @@
1
+ // what the lightbox SHOWS, derived rather than captured. PURE and DOM-free on purpose:
2
+ // headless-tested by tests/serve-web-lightbox.test.ts.
3
+ import { runPreviewSrc } from 'src/cli/serve/web/api.ts'
4
+
5
+ /** an IMAGE target is a fixed file. A LATENT target names the running MODULE instead of a url,
6
+ * because the url carries the frame tick: capturing it froze the lightbox on the frame you
7
+ * happened to click, through every later frame and past the end of the run */
8
+ export type LightboxTarget =
9
+ | { kind: 'image'; url: string; title: string; promptId: string | null }
10
+ /** `after` is how many results that module already had when the latent was opened: the run
11
+ * being watched is the one that ADDS to it. Without it, a run that fails promotes the
12
+ * lightbox to the PREVIOUS run's image, as if the one you watched had produced it */
13
+ | { kind: 'latent'; module: string; after: number }
14
+
15
+ export type LightboxRun = {
16
+ module: string
17
+ promptId: string
18
+ images: { url: string | null; filename: string }[]
19
+ }
20
+
21
+ export type LightboxView = { url: string; title: string; promptId: string | null }
22
+
23
+ /** a latent target follows the live frame, and the moment the run ends it promotes itself to
24
+ * the image that run produced, watching a latent become the picture is the point of opening
25
+ * it big, so stopping at the last frame loses exactly what you opened it for */
26
+ export function lightboxView(p: {
27
+ target: LightboxTarget
28
+ isRunning: boolean
29
+ previewTick: number
30
+ /** newest first */
31
+ results: readonly LightboxRun[]
32
+ }): LightboxView {
33
+ if (p.target.kind === 'image') return { url: p.target.url, title: p.target.title, promptId: p.target.promptId }
34
+ const module = p.target.module
35
+ const done = p.results.filter((r) => r.module === module)
36
+ // only a NEW result counts as "the run you were watching finished"
37
+ const finished = done.length > p.target.after ? done[0] : undefined
38
+ // an image with no url is one this run could not serve: stay on the latent rather than
39
+ // blank the lightbox at the very moment the run pays off
40
+ const image = finished?.images.find((i) => i.url != null)
41
+ if (!p.isRunning && image?.url != null)
42
+ return { url: image.url, title: image.filename, promptId: finished?.promptId ?? null }
43
+ return { url: runPreviewSrc({ module, tick: p.previewTick }), title: 'latent preview', promptId: null }
44
+ }
@@ -0,0 +1,52 @@
1
+ // the sidebar is a TREE, not a list: modules keep the folder they came from.
2
+ // PURE and DOM-free (browser side, so no node:path), tests/serve-web-tree.test.ts.
3
+ // the module KEY stays the basename (it is the api identity); this only decides
4
+ // what the sidebar shows above it.
5
+
6
+ export type TreeItem = { module: string; file: string }
7
+
8
+ export type ModuleGroup<T extends TreeItem> = { folder: string; modules: T[] }
9
+
10
+ function segmentsOf(path: string): string[] {
11
+ return path.split(/[/\\]/).filter((s) => s !== '')
12
+ }
13
+
14
+ function dirSegments(file: string): string[] {
15
+ return segmentsOf(file).slice(0, -1)
16
+ }
17
+
18
+ /** longest shared leading path of every module, as segments */
19
+ function commonPrefix(dirs: string[][]): string[] {
20
+ const first = dirs[0]
21
+ if (first == null) return []
22
+ const out: string[] = []
23
+ for (let i = 0; i < first.length; i++) {
24
+ const seg = first[i]
25
+ if (seg == null || !dirs.every((d) => d[i] === seg)) break
26
+ out.push(seg)
27
+ }
28
+ return out
29
+ }
30
+
31
+ /**
32
+ * group by folder, labelled from ONE level above the shared root, so serving a single
33
+ * folder still says `rvion` instead of showing a flat list with the prefix eaten. Groups
34
+ * and modules stay in a stable alphabetical order, drafts keep the server's order.
35
+ */
36
+ export function groupModulesByFolder<T extends TreeItem>(modules: readonly T[]): ModuleGroup<T>[] {
37
+ if (modules.length === 0) return []
38
+ const dirs = modules.map((m) => dirSegments(m.file))
39
+ // one level up from the shared root: that last segment is the label worth seeing
40
+ const shared = commonPrefix(dirs)
41
+ const cut = Math.max(0, shared.length - 1)
42
+ const groups = new Map<string, T[]>()
43
+ for (const [i, mod] of modules.entries()) {
44
+ const folder = (dirs[i] ?? []).slice(cut).join('/')
45
+ const list = groups.get(folder)
46
+ if (list == null) groups.set(folder, [mod])
47
+ else list.push(mod)
48
+ }
49
+ return [...groups.entries()]
50
+ .map(([folder, list]) => ({ folder, modules: [...list].sort((a, b) => a.module.localeCompare(b.module)) }))
51
+ .sort((a, b) => a.folder.localeCompare(b.folder))
52
+ }
@@ -40,7 +40,7 @@ export function asSizeForm(raw: unknown): SizeFormValue {
40
40
 
41
41
  /** the record the web keeps holds ON loras ONLY, so it always reads as "what is in the
42
42
  * palette". Two things are dropped: keys the host no longer offers (dead weight the ui
43
- * cannot display, and a server-side build failure), and `false` entries — LorasVar writes
43
+ * cannot display, and a server-side build failure), and `false` entries, LorasVar writes
44
44
  * one for every lora ever unticked, so treating them as palette members put the WHOLE
45
45
  * catalog in the row. Off is off: `activeLoras` skips both spellings, so nothing changes
46
46
  * in the graph, and with live drafts the next autosave heals the file */
@@ -92,7 +92,11 @@ export function setLoraEnabled(
92
92
  prev?: LoraStrengthPair,
93
93
  ): Record<string, unknown> {
94
94
  const next = { ...record }
95
- if (!on) delete next[name]
95
+ // PAUSE KEEPS THE KEY (as `false`): deleting it dropped the lora out of the record's
96
+ // insertion order, so pausing a card sent it to the end of the row. `false` is the same
97
+ // "selected but off" spelling LorasVar uses, every reader ignores it, and normalizeInitial
98
+ // prunes it on load, so nothing accumulates in the draft file
99
+ if (!on) next[name] = false
96
100
  else {
97
101
  const pair = prev ?? loraStrengthPair(record[name])
98
102
  next[name] = [pair.model, pair.clip]
@@ -100,6 +104,44 @@ export function setLoraEnabled(
100
104
  return next
101
105
  }
102
106
 
107
+ /**
108
+ * the palette, IN ORDER: the record's own key order (newest last on disk, shown newest FIRST),
109
+ * plus loras paused in this session that already left the record. Pure, because the order is
110
+ * the thing a drag rewrites and a pause must not touch.
111
+ */
112
+ export function paletteOrder(p: {
113
+ record: Record<string, unknown>
114
+ options: readonly string[]
115
+ /** paused in this session — kept in the palette even when the record no longer lists them */
116
+ paused: ReadonlySet<string>
117
+ }): string[] {
118
+ const known = new Set(p.options)
119
+ const inRecord = Object.keys(p.record).filter((n) => known.has(n) && (loraIsOn(p.record[n]) || p.paused.has(n)))
120
+ const pausedOnly = [...p.paused].filter((n) => known.has(n) && !inRecord.includes(n))
121
+ return [...inRecord, ...pausedOnly].reverse()
122
+ }
123
+
124
+ /** move a lora to a new slot in the PALETTE (what the row shows, newest first) and give back the
125
+ * record rewritten in that order, the record's key order IS the stored order */
126
+ export function reorderLoras(p: {
127
+ record: Record<string, unknown>
128
+ /** palette order, as displayed */
129
+ displayed: readonly string[]
130
+ from: number
131
+ to: number
132
+ }): Record<string, unknown> {
133
+ const next = [...p.displayed]
134
+ const [moved] = next.splice(p.from, 1)
135
+ if (moved == null) return p.record
136
+ next.splice(p.to, 0, moved)
137
+ const out: Record<string, unknown> = {}
138
+ // displayed is newest-first; the record stores the opposite, so it is written back reversed
139
+ for (const name of [...next].reverse()) if (name in p.record) out[name] = p.record[name]
140
+ // anything the palette does not show (a key pruned from view) keeps its entry
141
+ for (const [k, v] of Object.entries(p.record)) if (!(k in out)) out[k] = v
142
+ return out
143
+ }
144
+
103
145
  /** set both strengths; an OFF lora stays off (its strength is edited on re-enable) */
104
146
  export function setLoraStrength(
105
147
  record: Record<string, unknown>,
@@ -0,0 +1,53 @@
1
+ // the selection lives in the URL, so a panel you are looking at can be SENT to someone and
2
+ // they land on the same workflow and draft. PURE and DOM-free: headless-tested by
3
+ // tests/serve-web-url-selection.test.ts, the browser side is two calls in WebSt.
4
+
5
+ export type UrlSelection = { module: string | null; draft: string | null }
6
+
7
+ const MODULE_PARAM = 'workflow'
8
+ const DRAFT_PARAM = 'draft'
9
+
10
+ /** what a url asks for. Never throws: a hand-edited or truncated query is simply "nothing
11
+ * asked", because a bad link must open the panel, not break it */
12
+ export function readUrlSelection(search: string): UrlSelection {
13
+ try {
14
+ const params = new URLSearchParams(search.startsWith('?') ? search.slice(1) : search)
15
+ const module = params.get(MODULE_PARAM)
16
+ const draft = params.get(DRAFT_PARAM)
17
+ return { module: module === '' ? null : module, draft: draft === '' ? null : draft }
18
+ } catch {
19
+ return { module: null, draft: null }
20
+ }
21
+ }
22
+
23
+ /**
24
+ * the query for a selection, with everything else in the url PRESERVED, the panel does not
25
+ * own the whole query string, and eating an unrelated param someone appended would be rude.
26
+ * returns the full search string, `''` when there is nothing to carry.
27
+ */
28
+ export function writeUrlSelection(p: { search: string; module: string; draft: string }): string {
29
+ const params = new URLSearchParams(p.search.startsWith('?') ? p.search.slice(1) : p.search)
30
+ params.set(MODULE_PARAM, p.module)
31
+ params.set(DRAFT_PARAM, p.draft)
32
+ const text = params.toString()
33
+ return text === '' ? '' : `?${text}`
34
+ }
35
+
36
+ /** the selection to open with: THE URL WINS over what this browser last had. A link is an
37
+ * explicit instruction from whoever sent it; the stored selection is only a memory of your
38
+ * own last visit, and it must never override the link you just clicked. */
39
+ export function resolveSelection(p: {
40
+ url: UrlSelection
41
+ stored: UrlSelection
42
+ /** module key → its drafts */
43
+ modules: readonly { module: string; drafts: readonly string[] }[]
44
+ }): { module: string; draft: string } | null {
45
+ const pick = (key: string | null): { module: string; drafts: readonly string[] } | null =>
46
+ key == null ? null : (p.modules.find((m) => m.module === key) ?? null)
47
+ // a url naming a module this server does not serve falls back rather than showing nothing
48
+ const mod = pick(p.url.module) ?? pick(p.stored.module) ?? p.modules[0]
49
+ if (mod == null) return null
50
+ const wanted = p.url.module != null && p.url.module === mod.module ? p.url.draft : p.stored.draft
51
+ const draft = wanted != null && mod.drafts.includes(wanted) ? wanted : 'default'
52
+ return { module: mod.module, draft }
53
+ }