comfy-ts 2.6.0 → 2.8.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 (101) hide show
  1. package/README.md +22 -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 +8 -6
  7. package/dist/cli.js.map +1 -1
  8. package/dist/index.cjs +288 -35
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.d.cts +128 -7
  11. package/dist/index.d.ts +128 -7
  12. package/dist/index.js +286 -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-idFhdO4f.js → run-tui-BPw-SZYW.js} +107 -158
  17. package/dist/run-tui-BPw-SZYW.js.map +1 -0
  18. package/dist/serve-web.js +434 -81
  19. package/dist/{state-C90kdjtB.js → state-B-boDz-Z.js} +184 -45
  20. package/dist/state-B-boDz-Z.js.map +1 -0
  21. package/dist/web.d.ts +112 -7
  22. package/dist/web.js +239 -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 +7 -1
  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 +4 -2
  35. package/src/cli/serve/ServeApp.ts +825 -43
  36. package/src/cli/serve/applyVarPayload.ts +10 -3
  37. package/src/cli/serve/describeVar.ts +47 -7
  38. package/src/cli/serve/managerOnlyLoras.ts +27 -0
  39. package/src/cli/serve/run-serve.ts +58 -29
  40. package/src/cli/serve/serveSettings.ts +86 -0
  41. package/src/cli/serve/startupPrint.ts +111 -0
  42. package/src/cli/serve/web/api.ts +120 -1
  43. package/src/cli/serve/web/components/App.tsx +61 -22
  44. package/src/cli/serve/web/components/Gallery.tsx +243 -30
  45. package/src/cli/serve/web/components/Icon.tsx +160 -0
  46. package/src/cli/serve/web/components/PromptEnhancer.tsx +85 -38
  47. package/src/cli/serve/web/components/Sidebar.tsx +43 -19
  48. package/src/cli/serve/web/components/VarsForm.tsx +440 -80
  49. package/src/cli/serve/web/components/controls/BasicControls.tsx +38 -5
  50. package/src/cli/serve/web/components/controls/ImageControl.tsx +3 -2
  51. package/src/cli/serve/web/components/controls/LorasControl.tsx +498 -81
  52. package/src/cli/serve/web/components/controls/PresetPicker.tsx +60 -0
  53. package/src/cli/serve/web/components/controls/SeedControl.tsx +38 -20
  54. package/src/cli/serve/web/components/controls/SizeControl.tsx +3 -2
  55. package/src/cli/serve/web/llm.ts +254 -0
  56. package/src/cli/serve/web/logWeb.ts +6 -0
  57. package/src/cli/serve/web/state/EnhancerSt.ts +261 -157
  58. package/src/cli/serve/web/state/FormSt.ts +70 -18
  59. package/src/cli/serve/web/state/RunSt.ts +22 -1
  60. package/src/cli/serve/web/state/WebSt.ts +542 -13
  61. package/src/cli/serve/web/state/lightbox.ts +44 -0
  62. package/src/cli/serve/web/state/moduleTree.ts +52 -0
  63. package/src/cli/serve/web/state/payload.ts +44 -2
  64. package/src/cli/serve/web/state/urlSelection.ts +53 -0
  65. package/src/cli/serve/web/styles.ts +415 -57
  66. package/src/cli/serve/web/tsconfig.json +4 -0
  67. package/src/cli/tui/components/PickerOverlays.tsx +37 -0
  68. package/src/cli/tui/components/StatusBar.tsx +14 -1
  69. package/src/cli/tui/components/TuiApp.tsx +5 -2
  70. package/src/cli/tui/state/HostSt.ts +3 -2
  71. package/src/cli/tui/state/PickerSt.ts +48 -2
  72. package/src/cli/tui/state/TreeSt.ts +1 -1
  73. package/src/cli/tui/state/TuiSt.ts +2 -1
  74. package/src/coreExports.ts +8 -1
  75. package/src/graph/ComfyNode.ts +58 -1
  76. package/src/host/ComfyHost.ts +13 -2
  77. package/src/host/ComfyManager.ts +31 -13
  78. package/src/host/loraInfoCache.ts +35 -1
  79. package/src/host/loraManagerApi.ts +94 -0
  80. package/src/index.ts +2 -0
  81. package/src/promptEnhancers.ts +102 -0
  82. package/src/runner/ComfyExecution.ts +61 -6
  83. package/src/runner/ComfyWorkflow.ts +18 -4
  84. package/src/runner/ComfyWsApi.ts +3 -0
  85. package/src/runner/describePromptRejection.ts +34 -0
  86. package/src/sdk-generator/ComfySchema.ts +17 -4
  87. package/src/sdk-generator/comfyui-sdk-codegen.ts +56 -2
  88. package/src/state.ts +6 -0
  89. package/src/utils/ansi.ts +13 -0
  90. package/src/utils/matchesRegex.ts +13 -0
  91. package/src/utils/safeName.ts +29 -0
  92. package/src/utils/stringMap.ts +9 -0
  93. package/src/vars/ComfyVars.ts +61 -10
  94. package/src/vars/presets.ts +17 -0
  95. package/dist/DefinedWorkflow-BJgt5t0x.js.map +0 -1
  96. package/dist/DraftsSt-dizp3VcC.js.map +0 -1
  97. package/dist/run-serve-CVu39RNd.js +0 -1002
  98. package/dist/run-serve-CVu39RNd.js.map +0 -1
  99. package/dist/run-tui-idFhdO4f.js.map +0 -1
  100. package/dist/state-C90kdjtB.js.map +0 -1
  101. package/src/cli/serve/web/openrouter.ts +0 -142
@@ -1,87 +1,78 @@
1
- // the prompt enhancer: settings + one refine run (architecture item 12, web ui).
2
- // Hangs off the WebSt root. Its own localStorage blob, the api key included —
3
- // browser-only by design, so the serve process never sees a credential.
4
- // normalizeSettings/nextPresetName are PURE and headless-tested.
5
- import { makeAutoObservable, runInAction } from 'mobx'
6
- import { fetchModels, streamRefine, type OpenRouterModel, type ReasoningEffort } from 'src/cli/serve/web/openrouter.ts'
1
+ // the prompt enhancer: provider settings + the master-prompt library + one refine
2
+ // run (architecture item 12, web ui). Hangs off the WebSt root.
3
+ // SPLIT OF TRUTH: the master prompts are FILES on the server
4
+ // (`.comfy-ts/prompt-enhancers/*.md`, autosaved like a draft), everything else is
5
+ // browser-local in a localStorage blob, keys included, so the serve process never
6
+ // holds a credential. normalizeSettings/nextPresetName are PURE and headless-tested.
7
+ import { makeAutoObservable, reaction, runInAction, type IReactionDisposer } from 'mobx'
8
+ import { stringMap } from 'src/utils/stringMap.ts'
9
+ import {
10
+ deletePromptEnhancer,
11
+ fetchPromptEnhancers,
12
+ savePromptEnhancer,
13
+ type PromptEnhancer,
14
+ } from 'src/cli/serve/web/api.ts'
15
+ import {
16
+ defaultBaseUrl,
17
+ fetchModels,
18
+ streamRefine,
19
+ type LlmModel,
20
+ type ProviderId,
21
+ type ReasoningEffort,
22
+ } from 'src/cli/serve/web/llm.ts'
7
23
  import type { VarSt } from 'src/cli/serve/web/state/FormSt.ts'
8
24
 
9
25
  const STORAGE_KEY = 'comfy-ts-serve-enhancer'
10
26
 
11
27
  /** explicit model ids, never an alias: behaviour and cost stay reproducible */
12
- const DEFAULT_MODEL = 'anthropic/claude-sonnet-5'
13
-
14
- export type MasterPrompt = { id: string; name: string; text: string }
15
-
16
- const KREA2_MASTER = `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.
17
-
18
- Rewrite the user's prompt into ONE dense paragraph someone could picture with their eyes closed:
19
- - keep every noun and every named subject the user wrote, they are the point
20
- - add what is missing to make it fun to look at: lighting, palette, material, texture, camera angle, composition, mood
21
- - prefer concrete visual nouns over praise, never write "masterpiece", "8k", "highly detailed", "award winning"
22
- - stay under about 80 words, no lists, no headings, no quotes around the result
23
- - keep any "// " comment line and any "- " negative line from the input verbatim, each on its own line
24
-
25
- Answer with the rewritten prompt and nothing else: no preamble, no explanation.`
26
-
27
- /** shipped starting point, not a contract: a refiner is specific to the image model it feeds,
28
- * so the library is editable and this one is just the first entry */
29
- export function defaultPresets(): MasterPrompt[] {
30
- return [{ id: 'refine-krea2-prompt', name: 'refine-krea2-prompt', text: KREA2_MASTER }]
28
+ const DEFAULT_MODEL: Record<ProviderId, string> = {
29
+ openrouter: 'anthropic/claude-sonnet-5',
30
+ openwebui: '',
31
31
  }
32
32
 
33
+ export const PROVIDERS: ProviderId[] = ['openrouter', 'openwebui']
34
+
33
35
  export type EnhancerSettings = {
34
- apiKey: string
35
- model: string
36
+ provider: ProviderId
37
+ /** per provider, so switching one cannot send an openrouter model id to a local box */
38
+ keyByProvider: Record<string, string>
39
+ baseUrlByProvider: Record<string, string>
40
+ modelByProvider: Record<string, string>
36
41
  effort: ReasoningEffort
37
42
  thinkingOnly: boolean
38
- presets: MasterPrompt[]
39
- presetId: string
43
+ /** selected master prompt, by FILE NAME */
44
+ presetName: string
40
45
  /** last preset used per module: a workflow reopens on its own refiner */
41
46
  presetByModule: Record<string, string>
42
47
  }
43
48
 
44
- function str(raw: unknown, fallback: string): string {
45
- return typeof raw === 'string' && raw !== '' ? raw : fallback
49
+ function isProvider(raw: unknown): raw is ProviderId {
50
+ return raw === 'openrouter' || raw === 'openwebui'
46
51
  }
47
52
 
48
53
  function isEffort(raw: unknown): raw is ReasoningEffort {
49
54
  return raw === 'off' || raw === 'low' || raw === 'medium' || raw === 'high'
50
55
  }
51
56
 
52
- /** stored blob → usable settings. Same wire tolerance as every other stored blob: a hand-edited
53
- * or half-written localStorage entry must degrade to defaults, never break the modal */
57
+ /** stored blob → usable settings. A hand-edited or half-written localStorage entry must
58
+ * degrade to defaults, never break the modal (same wire tolerance as every stored blob) */
54
59
  export function normalizeSettings(raw: unknown): EnhancerSettings {
55
60
  const o = typeof raw === 'object' && raw !== null ? (raw as Record<string, unknown>) : {}
56
- const presets: MasterPrompt[] = []
57
- if (Array.isArray(o.presets)) {
58
- for (const entry of o.presets) {
59
- const p = typeof entry === 'object' && entry !== null ? (entry as Record<string, unknown>) : {}
60
- const id = str(p.id, '')
61
- if (id === '') continue
62
- presets.push({ id, name: str(p.name, id), text: typeof p.text === 'string' ? p.text : '' })
63
- }
64
- }
65
- // an EMPTY library means first run, so seed it; a library he emptied on purpose keeps
66
- // one entry anyway, because the modal needs something to send
67
- const library = presets.length > 0 ? presets : defaultPresets()
68
- const byModule: Record<string, string> = {}
69
- if (typeof o.presetByModule === 'object' && o.presetByModule !== null) {
70
- for (const [k, v] of Object.entries(o.presetByModule)) if (typeof v === 'string') byModule[k] = v
71
- }
72
- const wantedId = str(o.presetId, '')
61
+ const models = stringMap(o.modelByProvider)
62
+ const bases = stringMap(o.baseUrlByProvider)
73
63
  return {
74
- apiKey: typeof o.apiKey === 'string' ? o.apiKey : '',
75
- model: str(o.model, DEFAULT_MODEL),
64
+ provider: isProvider(o.provider) ? o.provider : 'openrouter',
65
+ keyByProvider: stringMap(o.keyByProvider),
66
+ baseUrlByProvider: { openrouter: defaultBaseUrl('openrouter'), openwebui: defaultBaseUrl('openwebui'), ...bases },
67
+ modelByProvider: { ...DEFAULT_MODEL, ...models },
76
68
  effort: isEffort(o.effort) ? o.effort : 'medium',
77
69
  thinkingOnly: o.thinkingOnly !== false,
78
- presets: library,
79
- presetId: library.some((p) => p.id === wantedId) ? wantedId : (library[0]?.id ?? ''),
80
- presetByModule: byModule,
70
+ presetName: typeof o.presetName === 'string' ? o.presetName : '',
71
+ presetByModule: stringMap(o.presetByModule),
81
72
  }
82
73
  }
83
74
 
84
- /** unique name for a new/duplicated preset — a library of three "copy" entries is unusable */
75
+ /** unique name for a new/duplicated master prompt — the name IS the filename */
85
76
  export function nextPresetName(base: string, taken: readonly string[]): string {
86
77
  if (!taken.includes(base)) return base
87
78
  for (let i = 2; i < 1000; i++) {
@@ -91,10 +82,6 @@ export function nextPresetName(base: string, taken: readonly string[]): string {
91
82
  return `${base} ${taken.length + 1}`
92
83
  }
93
84
 
94
- function newId(): string {
95
- return `mp-${Math.random().toString(36).slice(2, 10)}`
96
- }
97
-
98
85
  function readStored(): EnhancerSettings {
99
86
  try {
100
87
  return normalizeSettings(JSON.parse(localStorage.getItem(STORAGE_KEY) ?? '{}'))
@@ -104,15 +91,23 @@ function readStored(): EnhancerSettings {
104
91
  }
105
92
 
106
93
  export class EnhancerSt {
107
- apiKey: string
108
- model: string
94
+ provider: ProviderId
95
+ keyByProvider: Record<string, string>
96
+ baseUrlByProvider: Record<string, string>
97
+ modelByProvider: Record<string, string>
109
98
  effort: ReasoningEffort
110
99
  thinkingOnly: boolean
111
- presets: MasterPrompt[]
112
- presetId: string
100
+ presetName: string
113
101
  presetByModule: Record<string, string>
114
102
 
115
- models: OpenRouterModel[] = []
103
+ /** the master prompts, mirrored from the server (files) */
104
+ presets: PromptEnhancer[] = []
105
+ presetsState: 'idle' | 'loading' | 'error' = 'idle'
106
+ presetsError = ''
107
+ saveState: 'saved' | 'saving' | 'error' = 'saved'
108
+ saveError = ''
109
+
110
+ models: LlmModel[] = []
116
111
  modelsState: 'idle' | 'loading' | 'error' = 'idle'
117
112
  modelsError = ''
118
113
 
@@ -125,58 +120,85 @@ export class EnhancerSt {
125
120
  phase: 'idle' | 'running' | 'done' | 'error' = 'idle'
126
121
  error = ''
127
122
  private abort: AbortController | null = null
123
+ private disposer: IReactionDisposer
124
+ /** the preset json the server last confirmed — the autosave no-ops on it, so loading a
125
+ * library (or switching preset) never writes the files back unchanged */
126
+ private lastSaved = ''
128
127
 
129
128
  constructor() {
130
129
  const s = readStored()
131
- this.apiKey = s.apiKey
132
- this.model = s.model
130
+ this.provider = s.provider
131
+ this.keyByProvider = s.keyByProvider
132
+ this.baseUrlByProvider = s.baseUrlByProvider
133
+ this.modelByProvider = s.modelByProvider
133
134
  this.effort = s.effort
134
135
  this.thinkingOnly = s.thinkingOnly
135
- this.presets = s.presets
136
- this.presetId = s.presetId
136
+ this.presetName = s.presetName
137
137
  this.presetByModule = s.presetByModule
138
- makeAutoObservable<EnhancerSt, 'abort'>(this, { abort: false })
138
+ makeAutoObservable<EnhancerSt, 'abort' | 'disposer' | 'lastSaved'>(this, {
139
+ abort: false,
140
+ disposer: false,
141
+ lastSaved: false,
142
+ })
143
+ // the master prompt autosaves to its file, the live-drafts model (the values json is
144
+ // change-detector AND payload, the house persistence idiom)
145
+ this.disposer = reaction(
146
+ () => {
147
+ const p = this.preset
148
+ return p == null ? null : JSON.stringify(p)
149
+ },
150
+ (encoded) => {
151
+ if (encoded == null || encoded === this.lastSaved) return
152
+ void this.savePresetNow(JSON.parse(encoded) as PromptEnhancer)
153
+ },
154
+ { delay: 600 },
155
+ )
139
156
  }
140
157
 
141
- get preset(): MasterPrompt | null {
142
- return this.presets.find((p) => p.id === this.presetId) ?? this.presets[0] ?? null
158
+ dispose(): void {
159
+ this.disposer()
143
160
  }
144
161
 
145
- get isOpen(): boolean {
146
- return this.target != null
162
+ // #region settings ---------------------------------------------------------
163
+ get apiKey(): string {
164
+ return this.keyByProvider[this.provider] ?? ''
147
165
  }
148
166
 
149
- /** the list the selector shows: thinking models only unless the toggle is off */
150
- get visibleModels(): OpenRouterModel[] {
151
- return this.thinkingOnly ? this.models.filter((m) => m.reasoning) : this.models
167
+ get baseUrl(): string {
168
+ return this.baseUrlByProvider[this.provider] ?? defaultBaseUrl(this.provider)
152
169
  }
153
170
 
154
- openFor(p: { v: VarSt; module: string }): void {
155
- this.target = p.v
156
- this.targetModule = p.module
157
- this.original = typeof p.v.value === 'string' ? p.v.value : ''
158
- this.result = ''
159
- this.thinking = ''
160
- this.error = ''
161
- this.phase = 'idle'
162
- const remembered = this.presetByModule[p.module]
163
- if (remembered != null && this.presets.some((x) => x.id === remembered)) this.presetId = remembered
171
+ get model(): string {
172
+ return this.modelByProvider[this.provider] ?? ''
164
173
  }
165
174
 
166
- close(): void {
167
- this.cancel()
168
- this.target = null
169
- this.targetModule = ''
175
+ get endpoint(): { provider: ProviderId; baseUrl: string; key: string } {
176
+ return { provider: this.provider, baseUrl: this.baseUrl, key: this.apiKey }
177
+ }
178
+
179
+ /** the list the selector shows. A model whose capability is UNKNOWN (open webui reports
180
+ * none) stays visible: only an explicit "no reasoning" is filtered out */
181
+ get visibleModels(): LlmModel[] {
182
+ return this.thinkingOnly ? this.models.filter((m) => m.reasoning !== false) : this.models
183
+ }
184
+
185
+ get preset(): PromptEnhancer | null {
186
+ return this.presets.find((p) => p.name === this.presetName) ?? this.presets[0] ?? null
187
+ }
188
+
189
+ get isOpen(): boolean {
190
+ return this.target != null
170
191
  }
171
192
 
172
193
  settingsJSON(): EnhancerSettings {
173
194
  return {
174
- apiKey: this.apiKey,
175
- model: this.model,
195
+ provider: this.provider,
196
+ keyByProvider: this.keyByProvider,
197
+ baseUrlByProvider: this.baseUrlByProvider,
198
+ modelByProvider: this.modelByProvider,
176
199
  effort: this.effort,
177
200
  thinkingOnly: this.thinkingOnly,
178
- presets: this.presets,
179
- presetId: this.presetId,
201
+ presetName: this.presetName,
180
202
  presetByModule: this.presetByModule,
181
203
  }
182
204
  }
@@ -189,82 +211,111 @@ export class EnhancerSt {
189
211
  }
190
212
  }
191
213
 
214
+ setProvider(v: string): void {
215
+ if (!isProvider(v)) return
216
+ this.provider = v
217
+ // the loaded list belongs to the OTHER provider: showing it would offer models this
218
+ // endpoint has never heard of
219
+ this.models = []
220
+ this.modelsState = 'idle'
221
+ this.modelsError = ''
222
+ this.persist()
223
+ }
224
+
192
225
  setApiKey(v: string): void {
193
- this.apiKey = v.trim()
226
+ this.keyByProvider[this.provider] = v.trim()
227
+ this.persist()
228
+ }
229
+
230
+ setBaseUrl(v: string): void {
231
+ this.baseUrlByProvider[this.provider] = v.trim()
194
232
  this.persist()
195
233
  }
196
234
 
197
235
  setModel(v: string): void {
198
- this.model = v
236
+ this.modelByProvider[this.provider] = v
199
237
  this.persist()
200
238
  }
201
239
 
202
- /** takes the raw select value: validating here keeps the component cast-free */
203
240
  setEffort(v: string): void {
204
241
  if (!isEffort(v)) return
205
242
  this.effort = v
206
243
  this.persist()
207
244
  }
208
245
 
209
- /** the rewrite is editable before it is applied */
210
- setResult(v: string): void {
211
- this.result = v
212
- }
213
-
214
- /** what gets SENT is editable too: sharpen the sketch, then refine, without closing the modal.
215
- * It stays a copy — only apply() writes the var */
216
- setOriginal(v: string): void {
217
- this.original = v
218
- }
219
-
220
246
  toggleThinkingOnly(): void {
221
247
  this.thinkingOnly = !this.thinkingOnly
222
248
  this.persist()
223
249
  }
224
250
 
225
- selectPreset(id: string): void {
226
- if (!this.presets.some((p) => p.id === id)) return
227
- this.presetId = id
228
- if (this.targetModule !== '') this.presetByModule[this.targetModule] = id
229
- this.persist()
251
+ // #region master prompts (server files) -------------------------------------
252
+ async loadPresets(): Promise<void> {
253
+ runInAction(() => {
254
+ this.presetsState = 'loading'
255
+ this.presetsError = ''
256
+ })
257
+ try {
258
+ const reply = await fetchPromptEnhancers()
259
+ runInAction(() => {
260
+ this.presets = reply.enhancers
261
+ this.presetsState = 'idle'
262
+ if (!this.presets.some((p) => p.name === this.presetName)) this.presetName = this.presets[0]?.name ?? ''
263
+ this.lastSaved = JSON.stringify(this.preset)
264
+ })
265
+ } catch (e) {
266
+ runInAction(() => {
267
+ this.presetsState = 'error'
268
+ this.presetsError = e instanceof Error ? e.message : String(e)
269
+ })
270
+ }
230
271
  }
231
272
 
232
- private replacePreset(next: MasterPrompt): void {
233
- this.presets = this.presets.map((p) => (p.id === next.id ? next : p))
234
- this.persist()
273
+ private async savePresetNow(entry: PromptEnhancer): Promise<void> {
274
+ runInAction(() => {
275
+ this.saveState = 'saving'
276
+ this.lastSaved = JSON.stringify(entry)
277
+ })
278
+ try {
279
+ const reply = await savePromptEnhancer(entry)
280
+ runInAction(() => {
281
+ this.presets = reply.enhancers
282
+ this.saveState = 'saved'
283
+ this.saveError = ''
284
+ })
285
+ } catch (e) {
286
+ runInAction(() => {
287
+ this.saveState = 'error'
288
+ this.saveError = e instanceof Error ? e.message : String(e)
289
+ })
290
+ }
235
291
  }
236
292
 
237
- setPresetText(text: string): void {
238
- const p = this.preset
239
- if (p != null) this.replacePreset({ ...p, text })
293
+ selectPreset(name: string): void {
294
+ if (!this.presets.some((p) => p.name === name)) return
295
+ this.presetName = name
296
+ this.lastSaved = JSON.stringify(this.preset)
297
+ if (this.targetModule !== '') this.presetByModule[this.targetModule] = name
298
+ this.persist()
240
299
  }
241
300
 
242
- renamePreset(name: string): void {
301
+ setPresetText(text: string): void {
243
302
  const p = this.preset
244
- const clean = name.trim()
245
- if (p == null || clean === '') return
246
- this.replacePreset({
247
- ...p,
248
- name: nextPresetName(
249
- clean,
250
- this.presets.filter((x) => x.id !== p.id).map((x) => x.name),
251
- ),
252
- })
303
+ if (p == null) return
304
+ // replace the ENTRY, so the autosave reaction sees a change (the array is observable)
305
+ this.presets = this.presets.map((x) => (x.name === p.name ? { ...x, text } : x))
253
306
  }
254
307
 
308
+ /** create (or duplicate): a new FILE, saved immediately so it exists on disk */
255
309
  addPreset(name: string, text = ''): void {
256
- const clean = name.trim()
257
- if (clean === '') return
258
- const entry: MasterPrompt = {
259
- id: newId(),
260
- name: nextPresetName(
261
- clean,
262
- this.presets.map((p) => p.name),
263
- ),
264
- text,
265
- }
266
- this.presets = [...this.presets, entry]
267
- this.selectPreset(entry.id)
310
+ if (name.trim() === '') return
311
+ const clean = nextPresetName(
312
+ name.trim(),
313
+ this.presets.map((p) => p.name),
314
+ )
315
+ this.presets = [...this.presets, { name: clean, text }]
316
+ this.presetName = clean
317
+ this.persist()
318
+ void this.savePresetNow({ name: clean, text })
268
319
  }
269
320
 
270
321
  duplicatePreset(): void {
@@ -272,23 +323,76 @@ export class EnhancerSt {
272
323
  if (p != null) this.addPreset(`${p.name} copy`, p.text)
273
324
  }
274
325
 
275
- deletePreset(): void {
326
+ /** rename = write the new file, delete the old one (the filename IS the identity) */
327
+ async renamePreset(rawName: string): Promise<void> {
328
+ const p = this.preset
329
+ const clean = nextPresetName(
330
+ rawName.trim(),
331
+ this.presets.filter((x) => x.name !== p?.name).map((x) => x.name),
332
+ )
333
+ if (p == null || clean === '' || clean === p.name) return
334
+ await this.savePresetNow({ name: clean, text: p.text })
335
+ runInAction(() => {
336
+ this.presetName = clean
337
+ this.persist()
338
+ })
339
+ await this.removePresetFile(p.name)
340
+ }
341
+
342
+ async deletePreset(): Promise<void> {
276
343
  const p = this.preset
277
344
  if (p == null) return
278
- const rest = this.presets.filter((x) => x.id !== p.id)
279
- this.presets = rest.length > 0 ? rest : defaultPresets()
280
- this.presetId = this.presets[0]?.id ?? ''
281
- // a deleted preset must not stay pinned to a module
282
- for (const [k, v] of Object.entries(this.presetByModule)) if (v === p.id) delete this.presetByModule[k]
283
- this.persist()
345
+ await this.removePresetFile(p.name)
346
+ runInAction(() => {
347
+ // a deleted preset must not stay pinned to a module
348
+ for (const [k, v] of Object.entries(this.presetByModule)) if (v === p.name) delete this.presetByModule[k]
349
+ if (!this.presets.some((x) => x.name === this.presetName)) this.presetName = this.presets[0]?.name ?? ''
350
+ this.persist()
351
+ })
284
352
  }
285
353
 
286
- /** put the shipped library back WITHOUT dropping the ones written since */
287
- restoreDefaults(): void {
288
- const mine = this.presets.filter((p) => !defaultPresets().some((d) => d.id === p.id))
289
- this.presets = [...defaultPresets(), ...mine]
290
- this.presetId = this.presets[0]?.id ?? ''
291
- this.persist()
354
+ private async removePresetFile(name: string): Promise<void> {
355
+ try {
356
+ const reply = await deletePromptEnhancer({ name })
357
+ runInAction(() => {
358
+ this.presets = reply.enhancers
359
+ })
360
+ } catch (e) {
361
+ runInAction(() => {
362
+ this.saveState = 'error'
363
+ this.saveError = e instanceof Error ? e.message : String(e)
364
+ })
365
+ }
366
+ }
367
+
368
+ // #region the run ----------------------------------------------------------
369
+ openFor(p: { v: VarSt; module: string }): void {
370
+ this.target = p.v
371
+ this.targetModule = p.module
372
+ this.original = typeof p.v.value === 'string' ? p.v.value : ''
373
+ this.result = ''
374
+ this.thinking = ''
375
+ this.error = ''
376
+ this.phase = 'idle'
377
+ const remembered = this.presetByModule[p.module]
378
+ if (remembered != null) this.presetName = remembered
379
+ if (this.presets.length === 0) void this.loadPresets()
380
+ }
381
+
382
+ close(): void {
383
+ this.cancel()
384
+ this.target = null
385
+ this.targetModule = ''
386
+ }
387
+
388
+ setResult(v: string): void {
389
+ this.result = v
390
+ }
391
+
392
+ /** what gets SENT is editable too: sharpen the sketch, then refine, without closing the
393
+ * modal. It stays a copy, only apply() writes the var */
394
+ setOriginal(v: string): void {
395
+ this.original = v
292
396
  }
293
397
 
294
398
  async loadModels(): Promise<void> {
@@ -297,7 +401,7 @@ export class EnhancerSt {
297
401
  this.modelsError = ''
298
402
  })
299
403
  try {
300
- const models = await fetchModels({ key: this.apiKey })
404
+ const models = await fetchModels(this.endpoint)
301
405
  runInAction(() => {
302
406
  this.models = models
303
407
  this.modelsState = 'idle'
@@ -333,7 +437,7 @@ export class EnhancerSt {
333
437
  })
334
438
  try {
335
439
  await streamRefine({
336
- key: this.apiKey,
440
+ endpoint: this.endpoint,
337
441
  model: this.model,
338
442
  system: preset.text,
339
443
  user: this.original,