comfy-ts 2.10.0 → 2.12.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 (110) hide show
  1. package/README.md +1 -0
  2. package/dist/{LogsSt-DFxzQfDc.js → LogsSt-U1H0mP1m.js} +35 -5
  3. package/dist/LogsSt-U1H0mP1m.js.map +1 -0
  4. package/dist/cli.js +4 -4
  5. package/dist/index.cjs +565 -62
  6. package/dist/index.cjs.map +1 -1
  7. package/dist/index.d.cts +210 -31
  8. package/dist/index.d.ts +210 -31
  9. package/dist/index.js +561 -63
  10. package/dist/index.js.map +1 -1
  11. package/dist/{run-serve-_nrvJYyt.js → run-serve-BeAznay5.js} +549 -43
  12. package/dist/run-serve-BeAznay5.js.map +1 -0
  13. package/dist/{run-tui-Atvf9vb3.js → run-tui-BTGjvnKk.js} +75 -18
  14. package/dist/run-tui-BTGjvnKk.js.map +1 -0
  15. package/dist/{DefinedWorkflow-BatWaZO1.js → schemaDrift-Cg39vs53.js} +644 -60
  16. package/dist/schemaDrift-Cg39vs53.js.map +1 -0
  17. package/dist/serve-web.js +523 -133
  18. package/dist/{state-6RFDIQwJ.js → state-C7REnHan.js} +18 -3
  19. package/dist/{state-6RFDIQwJ.js.map → state-C7REnHan.js.map} +1 -1
  20. package/dist/web.d.ts +210 -31
  21. package/dist/web.js +561 -63
  22. package/dist/web.js.map +1 -1
  23. package/examples/comfy-cloud/capybara-i2v.cflow.ts +2 -0
  24. package/examples/comfy-cloud/wan22-5b-t2v.cflow.ts +2 -0
  25. package/examples/comfy-cloud/wan22-i2v.cflow.ts +2 -0
  26. package/examples/comfy-cloud/wan22-t2v.cflow.ts +2 -0
  27. package/examples/rvion/06-qwen-image-edit.cflow.ts +3 -2
  28. package/examples/rvion/07-local-llm-text-gen.cflow.ts +2 -2
  29. package/examples/rvion/10-anima-t2i.cflow.ts +229 -0
  30. package/extra/README.md +4 -0
  31. package/extra/comfyui-fresh-model-lists/README.md +25 -0
  32. package/extra/comfyui-fresh-model-lists/__init__.py +36 -0
  33. package/extra/comfyui-fresh-model-lists/test_fresh_model_lists.py +97 -0
  34. package/package.json +17 -7
  35. package/src/cli/draftMeta.ts +39 -0
  36. package/src/cli/serve/ServeApp.ts +242 -12
  37. package/src/cli/serve/applyVarPayload.ts +50 -22
  38. package/src/cli/serve/describeVar.ts +49 -6
  39. package/src/cli/serve/favicon.ts +3 -0
  40. package/src/cli/serve/llmConfigShape.ts +51 -0
  41. package/src/cli/serve/llmConfigs.ts +52 -0
  42. package/src/cli/serve/tagList.ts +92 -0
  43. package/src/cli/serve/tagSource.ts +69 -0
  44. package/src/cli/serve/web/api.ts +60 -0
  45. package/src/cli/serve/web/components/App.tsx +336 -44
  46. package/src/cli/serve/web/components/Gallery.tsx +105 -28
  47. package/src/cli/serve/web/components/HistoryPicker.tsx +149 -0
  48. package/src/cli/serve/web/components/Icon.tsx +18 -2
  49. package/src/cli/serve/web/components/MenuButton.tsx +53 -0
  50. package/src/cli/serve/web/components/Omnibox.tsx +85 -0
  51. package/src/cli/serve/web/components/PromptEnhancer.tsx +476 -180
  52. package/src/cli/serve/web/components/TooltipLayer.tsx +45 -0
  53. package/src/cli/serve/web/components/VarIcon.tsx +24 -0
  54. package/src/cli/serve/web/components/VarsForm.tsx +341 -177
  55. package/src/cli/serve/web/components/controls/BasicControls.tsx +57 -32
  56. package/src/cli/serve/web/components/controls/LorasControl.tsx +708 -285
  57. package/src/cli/serve/web/components/controls/PresetPicker.tsx +1 -1
  58. package/src/cli/serve/web/components/controls/PromptControl.tsx +279 -0
  59. package/src/cli/serve/web/components/controls/PromptEditor.tsx +113 -0
  60. package/src/cli/serve/web/components/controls/SeedControl.tsx +17 -10
  61. package/src/cli/serve/web/components/controls/SizeControl.tsx +111 -18
  62. package/src/cli/serve/web/components/modKey.ts +2 -0
  63. package/src/cli/serve/web/llm.ts +23 -12
  64. package/src/cli/serve/web/promptEditor/promptExtensions.ts +281 -0
  65. package/src/cli/serve/web/state/EnhancerSt.ts +415 -100
  66. package/src/cli/serve/web/state/FormSt.ts +193 -29
  67. package/src/cli/serve/web/state/OmniboxSt.ts +57 -0
  68. package/src/cli/serve/web/state/WebSt.ts +281 -57
  69. package/src/cli/serve/web/state/choiceButtons.ts +61 -0
  70. package/src/cli/serve/web/state/generateButton.ts +16 -0
  71. package/src/cli/serve/web/state/history.ts +54 -0
  72. package/src/cli/serve/web/state/host.ts +5 -2
  73. package/src/cli/serve/web/state/keptLines.ts +53 -0
  74. package/src/cli/serve/web/state/latentMode.ts +20 -0
  75. package/src/cli/serve/web/state/loraSort.ts +57 -0
  76. package/src/cli/serve/web/state/moduleTree.ts +2 -2
  77. package/src/cli/serve/web/state/omnibox.ts +69 -0
  78. package/src/cli/serve/web/state/payload.ts +38 -58
  79. package/src/cli/serve/web/state/shortcuts.ts +54 -0
  80. package/src/cli/serve/web/state/sizeStars.ts +31 -0
  81. package/src/cli/serve/web/state/stableSlots.ts +21 -0
  82. package/src/cli/serve/web/state/varGroups.ts +24 -0
  83. package/src/cli/serve/web/styles.ts +472 -118
  84. package/src/cli/serve/webBundle.ts +54 -10
  85. package/src/cli/tui/components/Header.tsx +2 -0
  86. package/src/cli/tui/components/PickerOverlays.tsx +9 -2
  87. package/src/cli/tui/imagePicker/ImagePickerSt.ts +1 -1
  88. package/src/cli/tui/state/DraftsSt.ts +18 -2
  89. package/src/cli/tui/state/EditorSt.ts +1 -1
  90. package/src/cli/tui/state/HostSt.ts +34 -0
  91. package/src/cli/tui/state/LorasSt.ts +1 -1
  92. package/src/cli/tui/state/PickerSt.ts +25 -7
  93. package/src/cli/tui/state/SettingsSt.ts +1 -1
  94. package/src/cli/tui/state/TuiSt.ts +10 -0
  95. package/src/coreExports.ts +20 -0
  96. package/src/host/ComfyHost.ts +15 -0
  97. package/src/host/loraInfoCache.ts +70 -0
  98. package/src/host/loraManagerApi.ts +27 -0
  99. package/src/host/schemaDrift.ts +87 -0
  100. package/src/state.ts +5 -0
  101. package/src/vars/ComfyVars.ts +337 -67
  102. package/src/vars/DefinedWorkflow.ts +40 -19
  103. package/src/vars/lanes.ts +238 -0
  104. package/src/vars/loraEntry.ts +101 -0
  105. package/src/vars/promptSyntax.ts +382 -0
  106. package/dist/DefinedWorkflow-BatWaZO1.js.map +0 -1
  107. package/dist/LogsSt-DFxzQfDc.js.map +0 -1
  108. package/dist/run-serve-_nrvJYyt.js.map +0 -1
  109. package/dist/run-tui-Atvf9vb3.js.map +0 -1
  110. package/src/cli/serve/web/components/Sidebar.tsx +0 -66
@@ -1,78 +1,70 @@
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.
1
+ // the prompt enhancer: LLM configs + the master-prompt library + one refine run
2
+ // (architecture item 12, web ui). Hangs off the WebSt root.
3
+ // SPLIT OF TRUTH: the LLM configs (`.comfy-ts/llm-configs/*.json`) and the master
4
+ // prompts (`.comfy-ts/prompt-enhancers/*.md`) are FILES on the server, autosaved like a
5
+ // draft, so every browser and app window shares one setup. Only the api keys and which
6
+ // entry is selected stay in a localStorage blob: the serve process never holds a key.
7
+ // normalizeSettings/nextPresetName are PURE and headless-tested.
7
8
  import { makeAutoObservable, reaction, runInAction, type IReactionDisposer } from 'mobx'
8
9
  import { stringMap } from 'src/utils/stringMap.ts'
9
10
  import {
11
+ deleteLlmConfig,
10
12
  deletePromptEnhancer,
13
+ fetchLlmConfigs,
11
14
  fetchPromptEnhancers,
15
+ saveLlmConfig,
12
16
  savePromptEnhancer,
13
17
  type PromptEnhancer,
14
18
  } from 'src/cli/serve/web/api.ts'
15
19
  import {
16
- defaultBaseUrl,
20
+ isEffort,
21
+ isProvider,
22
+ normalizeLlmConfig,
23
+ withProvider,
24
+ type LlmConfig,
25
+ type LlmConfigEntry,
26
+ } from 'src/cli/serve/llmConfigShape.ts'
27
+ import {
17
28
  fetchModels,
18
29
  streamRefine,
19
30
  type LlmModel,
20
31
  type ProviderId,
21
32
  type ReasoningEffort,
22
33
  } from 'src/cli/serve/web/llm.ts'
23
- import type { VarSt } from 'src/cli/serve/web/state/FormSt.ts'
34
+ import type { FormSt, VarSt } from 'src/cli/serve/web/state/FormSt.ts'
35
+ import { intentKey } from 'src/cli/draftMeta.ts'
36
+ import { finishRewrite, splitKeptLines } from 'src/cli/serve/web/state/keptLines.ts'
37
+ import { pushHistory, type HistoryEntry } from 'src/cli/serve/web/state/history.ts'
38
+ import { isPromptLanes, patchLane } from 'src/vars/lanes.ts'
24
39
 
25
40
  const STORAGE_KEY = 'comfy-ts-serve-enhancer'
26
41
 
27
- /** explicit model ids, never an alias: behaviour and cost stay reproducible */
28
- const DEFAULT_MODEL: Record<ProviderId, string> = {
29
- openrouter: 'anthropic/claude-sonnet-5',
30
- openwebui: '',
31
- }
32
-
33
- export const PROVIDERS: ProviderId[] = ['openrouter', 'openwebui']
42
+ export const PROVIDERS: ProviderId[] = ['openrouter', 'openwebui', 'openai']
34
43
 
44
+ /** what stays in the browser: the keys, and which config and master prompt are selected */
35
45
  export type EnhancerSettings = {
36
- provider: ProviderId
37
- /** per provider, so switching one cannot send an openrouter model id to a local box */
38
46
  keyByProvider: Record<string, string>
39
- baseUrlByProvider: Record<string, string>
40
- modelByProvider: Record<string, string>
41
- effort: ReasoningEffort
42
- thinkingOnly: boolean
47
+ /** selected LLM config, by FILE NAME */
48
+ configName: string
43
49
  /** selected master prompt, by FILE NAME */
44
50
  presetName: string
45
51
  /** last preset used per module: a workflow reopens on its own refiner */
46
52
  presetByModule: Record<string, string>
47
53
  }
48
54
 
49
- function isProvider(raw: unknown): raw is ProviderId {
50
- return raw === 'openrouter' || raw === 'openwebui'
51
- }
52
-
53
- function isEffort(raw: unknown): raw is ReasoningEffort {
54
- return raw === 'off' || raw === 'low' || raw === 'medium' || raw === 'high'
55
- }
56
-
57
55
  /** stored blob → usable settings. A hand-edited or half-written localStorage entry must
58
56
  * degrade to defaults, never break the modal (same wire tolerance as every stored blob) */
59
57
  export function normalizeSettings(raw: unknown): EnhancerSettings {
60
58
  const o = typeof raw === 'object' && raw !== null ? (raw as Record<string, unknown>) : {}
61
- const models = stringMap(o.modelByProvider)
62
- const bases = stringMap(o.baseUrlByProvider)
63
59
  return {
64
- provider: isProvider(o.provider) ? o.provider : 'openrouter',
65
60
  keyByProvider: stringMap(o.keyByProvider),
66
- baseUrlByProvider: { openrouter: defaultBaseUrl('openrouter'), openwebui: defaultBaseUrl('openwebui'), ...bases },
67
- modelByProvider: { ...DEFAULT_MODEL, ...models },
68
- effort: isEffort(o.effort) ? o.effort : 'medium',
69
- thinkingOnly: o.thinkingOnly !== false,
61
+ configName: typeof o.configName === 'string' ? o.configName : '',
70
62
  presetName: typeof o.presetName === 'string' ? o.presetName : '',
71
63
  presetByModule: stringMap(o.presetByModule),
72
64
  }
73
65
  }
74
66
 
75
- /** unique name for a new/duplicated master prompt — the name IS the filename */
67
+ /** unique name for a new/duplicated entry (master prompt or config): the name IS the filename */
76
68
  export function nextPresetName(base: string, taken: readonly string[]): string {
77
69
  if (!taken.includes(base)) return base
78
70
  for (let i = 2; i < 1000; i++) {
@@ -82,6 +74,58 @@ export function nextPresetName(base: string, taken: readonly string[]): string {
82
74
  return `${base} ${taken.length + 1}`
83
75
  }
84
76
 
77
+ /** the master prompt a workflow opens on when none was picked for it yet: the one whose name
78
+ * shares the most words with the module (`10-anima-t2i` → `refine-anima-prompt`), the full
79
+ * name before a `-basic` variant. null when no name shares a word */
80
+ export function guessPreset(module: string, names: readonly string[]): string | null {
81
+ const words = (x: string): string[] =>
82
+ x
83
+ .toLowerCase()
84
+ .split(/[^a-z0-9]+/)
85
+ .filter((w) => w.length > 2 && !/^\d+$/.test(w))
86
+ const mod = new Set(words(module))
87
+ let best: { name: string; score: number } | null = null
88
+ for (const name of names) {
89
+ const score = words(name).filter((w) => mod.has(w)).length
90
+ if (score === 0) continue
91
+ if (best == null || score > best.score || (score === best.score && name.length < best.name.length))
92
+ best = { name, score }
93
+ }
94
+ return best?.name ?? null
95
+ }
96
+
97
+ /** the text a prompt var holds: the string, or one lane's text, '' for anything else */
98
+ export function promptTextOf(value: unknown, lane: number | null): string {
99
+ if (lane != null) return isPromptLanes(value) ? (value.lanes[lane]?.prompt ?? '') : ''
100
+ return typeof value === 'string' ? value : ''
101
+ }
102
+
103
+ /** the var's value with the candidate in place of what was refined: the whole prompt, or only
104
+ * its lane (the others and their order stay). What `try` sends, the form keeps its own value */
105
+ export function withCandidate(value: unknown, lane: number | null, text: string): unknown {
106
+ if (lane != null && isPromptLanes(value)) return { lanes: patchLane(value.lanes, lane, { prompt: text }) }
107
+ return text
108
+ }
109
+
110
+ /** what a generate sends in place of the form's values: while the enhancer is open with a
111
+ * rewrite, that rewrite TRIED in place of the refined prompt (the form keeps its own value);
112
+ * otherwise nothing, the draft as it is. ⌘⏎ and the try button both go through this */
113
+ export function generateOverride(p: {
114
+ open: boolean
115
+ target: { name: string; value: unknown } | null
116
+ lane: number | null
117
+ result: string
118
+ }): Record<string, unknown> | undefined {
119
+ const text = p.result.trim()
120
+ if (!p.open || p.target == null || text === '') return undefined
121
+ return { [p.target.name]: withCandidate(p.target.value, p.lane, text) }
122
+ }
123
+
124
+ /** what the input holds when the modal opens: the previous one, or the prompt the first time */
125
+ export function openingInput(p: { previous: string; prompt: string }): string {
126
+ return p.previous !== '' ? p.previous : p.prompt
127
+ }
128
+
85
129
  function readStored(): EnhancerSettings {
86
130
  try {
87
131
  return normalizeSettings(JSON.parse(localStorage.getItem(STORAGE_KEY) ?? '{}'))
@@ -90,86 +134,138 @@ function readStored(): EnhancerSettings {
90
134
  }
91
135
  }
92
136
 
137
+ /** where a library's save stands, shown beside its bar */
138
+ export type SaveState = 'saved' | 'saving' | 'error'
139
+
93
140
  export class EnhancerSt {
94
- provider: ProviderId
95
141
  keyByProvider: Record<string, string>
96
- baseUrlByProvider: Record<string, string>
97
- modelByProvider: Record<string, string>
98
- effort: ReasoningEffort
99
- thinkingOnly: boolean
142
+ configName: string
100
143
  presetName: string
101
144
  presetByModule: Record<string, string>
102
145
 
146
+ /** the LLM configs, mirrored from the server (files) */
147
+ configs: LlmConfigEntry[] = []
148
+ configsState: 'idle' | 'loading' | 'error' = 'idle'
149
+ configsError = ''
150
+ configSaveState: SaveState = 'saved'
151
+ configSaveError = ''
152
+
103
153
  /** the master prompts, mirrored from the server (files) */
104
154
  presets: PromptEnhancer[] = []
105
155
  presetsState: 'idle' | 'loading' | 'error' = 'idle'
106
156
  presetsError = ''
107
- saveState: 'saved' | 'saving' | 'error' = 'saved'
157
+ saveState: SaveState = 'saved'
108
158
  saveError = ''
109
159
 
160
+ /** per config name: does its endpoint answer the model list right now */
161
+ configStatus = new Map<string, 'checking' | 'up' | 'down'>()
162
+ configStatusError = new Map<string, string>()
163
+
110
164
  models: LlmModel[] = []
111
165
  modelsState: 'idle' | 'loading' | 'error' = 'idle'
112
166
  modelsError = ''
113
167
 
168
+ /** the editor open over the job: the selected LLM's settings, or the master prompt's text.
169
+ * null = the modal shows only yours → rewrite */
170
+ editing: 'llm' | 'preset' | null = null
171
+
172
+ /** every text an enhance started from, for the history picker (this page only) */
173
+ inputHistory: HistoryEntry<string>[] = []
174
+
114
175
  /** the prompt var being refined — non-null IS the modal being open */
115
176
  target: VarSt | null = null
177
+ /** in lanes mode, the lane being refined; null = the whole prompt */
178
+ targetLane: number | null = null
116
179
  targetModule = ''
117
- original = ''
118
180
  result = ''
119
181
  thinking = ''
120
182
  phase: 'idle' | 'running' | 'done' | 'error' = 'idle'
121
183
  error = ''
122
184
  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 */
185
+ private disposers: IReactionDisposer[]
186
+ /** the json the server last confirmed, per library — the autosave no-ops on it, so loading a
187
+ * library (or switching entry) never writes the file back unchanged */
126
188
  private lastSaved = ''
189
+ private lastSavedConfig = ''
127
190
 
128
- constructor() {
191
+ /** the open draft: the input is ITS intent, stored in its file */
192
+ constructor(private getForm: () => FormSt | null = () => null) {
129
193
  const s = readStored()
130
- this.provider = s.provider
131
194
  this.keyByProvider = s.keyByProvider
132
- this.baseUrlByProvider = s.baseUrlByProvider
133
- this.modelByProvider = s.modelByProvider
134
- this.effort = s.effort
135
- this.thinkingOnly = s.thinkingOnly
195
+ this.configName = s.configName
136
196
  this.presetName = s.presetName
137
197
  this.presetByModule = s.presetByModule
138
- makeAutoObservable<EnhancerSt, 'abort' | 'disposer' | 'lastSaved'>(this, {
198
+ makeAutoObservable<EnhancerSt, 'abort' | 'disposers' | 'lastSaved' | 'lastSavedConfig' | 'getForm'>(this, {
139
199
  abort: false,
140
- disposer: false,
200
+ disposers: false,
141
201
  lastSaved: false,
202
+ lastSavedConfig: false,
203
+ getForm: false,
142
204
  })
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
- )
205
+ // both libraries autosave to their file, the live-drafts model (the json is change
206
+ // detector AND payload, the house persistence idiom)
207
+ this.disposers = [
208
+ reaction(
209
+ () => {
210
+ const p = this.preset
211
+ return p == null ? null : JSON.stringify(p)
212
+ },
213
+ (encoded) => {
214
+ if (encoded == null || encoded === this.lastSaved) return
215
+ void this.savePresetNow(JSON.parse(encoded) as PromptEnhancer)
216
+ },
217
+ { delay: 600 },
218
+ ),
219
+ reaction(
220
+ () => {
221
+ const c = this.configEntry
222
+ return c == null ? null : JSON.stringify(c)
223
+ },
224
+ (encoded) => {
225
+ if (encoded == null || encoded === this.lastSavedConfig) return
226
+ void this.saveConfigNow(JSON.parse(encoded) as LlmConfigEntry)
227
+ },
228
+ { delay: 600 },
229
+ ),
230
+ ]
156
231
  }
157
232
 
158
233
  dispose(): void {
159
- this.disposer()
234
+ for (const d of this.disposers) d()
235
+ }
236
+
237
+ // #region llm configs (server files) ----------------------------------------
238
+ get configEntry(): LlmConfigEntry | null {
239
+ return this.configs.find((c) => c.name === this.configName) ?? this.configs[0] ?? null
240
+ }
241
+
242
+ /** the active config; before any exists, the defaults (nothing is written for them) */
243
+ get config(): LlmConfig {
244
+ return this.configEntry?.config ?? normalizeLlmConfig({})
245
+ }
246
+
247
+ get provider(): ProviderId {
248
+ return this.config.provider
160
249
  }
161
250
 
162
- // #region settings ---------------------------------------------------------
163
251
  get apiKey(): string {
164
252
  return this.keyByProvider[this.provider] ?? ''
165
253
  }
166
254
 
167
255
  get baseUrl(): string {
168
- return this.baseUrlByProvider[this.provider] ?? defaultBaseUrl(this.provider)
256
+ return this.config.baseUrl
169
257
  }
170
258
 
171
259
  get model(): string {
172
- return this.modelByProvider[this.provider] ?? ''
260
+ return this.config.model
261
+ }
262
+
263
+ get effort(): ReasoningEffort {
264
+ return this.config.effort
265
+ }
266
+
267
+ get thinkingOnly(): boolean {
268
+ return this.config.thinkingOnly
173
269
  }
174
270
 
175
271
  get endpoint(): { provider: ProviderId; baseUrl: string; key: string } {
@@ -192,12 +288,8 @@ export class EnhancerSt {
192
288
 
193
289
  settingsJSON(): EnhancerSettings {
194
290
  return {
195
- provider: this.provider,
196
291
  keyByProvider: this.keyByProvider,
197
- baseUrlByProvider: this.baseUrlByProvider,
198
- modelByProvider: this.modelByProvider,
199
- effort: this.effort,
200
- thinkingOnly: this.thinkingOnly,
292
+ configName: this.configName,
201
293
  presetName: this.presetName,
202
294
  presetByModule: this.presetByModule,
203
295
  }
@@ -207,19 +299,179 @@ export class EnhancerSt {
207
299
  try {
208
300
  localStorage.setItem(STORAGE_KEY, JSON.stringify(this.settingsJSON()))
209
301
  } catch {
210
- // storage full/blocked: settings just won't survive the reload
302
+ // storage full/blocked: the selection just won't survive the reload
303
+ }
304
+ }
305
+
306
+ async loadConfigs(): Promise<void> {
307
+ runInAction(() => {
308
+ this.configsState = 'loading'
309
+ this.configsError = ''
310
+ })
311
+ try {
312
+ const reply = await fetchLlmConfigs()
313
+ runInAction(() => {
314
+ this.configs = reply.configs
315
+ this.configsState = 'idle'
316
+ if (!this.configs.some((c) => c.name === this.configName)) this.configName = this.configs[0]?.name ?? ''
317
+ this.lastSavedConfig = JSON.stringify(this.configEntry)
318
+ })
319
+ void this.probeConfigs()
320
+ } catch (e) {
321
+ runInAction(() => {
322
+ this.configsState = 'error'
323
+ this.configsError = e instanceof Error ? e.message : String(e)
324
+ })
325
+ }
326
+ }
327
+
328
+ private async saveConfigNow(entry: LlmConfigEntry): Promise<void> {
329
+ runInAction(() => {
330
+ this.configSaveState = 'saving'
331
+ this.lastSavedConfig = JSON.stringify(entry)
332
+ })
333
+ try {
334
+ const reply = await saveLlmConfig(entry)
335
+ runInAction(() => {
336
+ // the local copy of the saved entry wins over the server's normalized one: a base url
337
+ // cleared to be retyped must not snap back to its default mid-typing
338
+ this.configs = reply.configs.map((c) => this.configs.find((x) => x.name === c.name) ?? c)
339
+ this.configSaveState = 'saved'
340
+ this.configSaveError = ''
341
+ })
342
+ } catch (e) {
343
+ runInAction(() => {
344
+ this.configSaveState = 'error'
345
+ this.configSaveError = e instanceof Error ? e.message : String(e)
346
+ })
347
+ }
348
+ }
349
+
350
+ /** ask every config's endpoint for its model list, in parallel: the tabs show which ones
351
+ * answer, and the selected one's list fills the model picker without a click */
352
+ async probeConfigs(): Promise<void> {
353
+ const entries = this.configs.map((c) => ({ name: c.name, config: c.config }))
354
+ await Promise.all(
355
+ entries.map(async (c) => {
356
+ runInAction(() => this.configStatus.set(c.name, 'checking'))
357
+ const endpoint = {
358
+ provider: c.config.provider,
359
+ baseUrl: c.config.baseUrl,
360
+ key: this.keyByProvider[c.config.provider] ?? '',
361
+ }
362
+ try {
363
+ const models = await fetchModels(endpoint)
364
+ runInAction(() => {
365
+ this.configStatus.set(c.name, 'up')
366
+ this.configStatusError.delete(c.name)
367
+ if (c.name === this.configEntry?.name && this.models.length === 0) {
368
+ this.models = models
369
+ this.modelsState = 'idle'
370
+ }
371
+ })
372
+ } catch (e) {
373
+ runInAction(() => {
374
+ this.configStatus.set(c.name, 'down')
375
+ this.configStatusError.set(c.name, e instanceof Error ? e.message : String(e))
376
+ })
377
+ }
378
+ }),
379
+ )
380
+ }
381
+
382
+ selectConfig(name: string): void {
383
+ if (!this.configs.some((c) => c.name === name)) return
384
+ this.configName = name
385
+ this.lastSavedConfig = JSON.stringify(this.configEntry)
386
+ // the loaded list belongs to the other config's endpoint
387
+ this.clearModels()
388
+ this.persist()
389
+ if (this.configStatus.get(name) === 'up') void this.loadModels()
390
+ }
391
+
392
+ /** create (or duplicate): a new FILE, saved immediately so it exists on disk */
393
+ addConfig(name: string, config: LlmConfig = normalizeLlmConfig({})): void {
394
+ if (name.trim() === '') return
395
+ const clean = nextPresetName(
396
+ name.trim(),
397
+ this.configs.map((c) => c.name),
398
+ )
399
+ this.configs = [...this.configs, { name: clean, config }]
400
+ this.configName = clean
401
+ this.clearModels()
402
+ this.persist()
403
+ void this.saveConfigNow({ name: clean, config })
404
+ }
405
+
406
+ duplicateConfig(): void {
407
+ const c = this.configEntry
408
+ if (c != null) this.addConfig(`${c.name} copy`, c.config)
409
+ }
410
+
411
+ /** rename = write the new file, delete the old one (the filename IS the identity) */
412
+ async renameConfig(rawName: string): Promise<void> {
413
+ const c = this.configEntry
414
+ const clean = nextPresetName(
415
+ rawName.trim(),
416
+ this.configs.filter((x) => x.name !== c?.name).map((x) => x.name),
417
+ )
418
+ if (c == null || clean === '' || clean === c.name) return
419
+ await this.saveConfigNow({ name: clean, config: c.config })
420
+ runInAction(() => {
421
+ this.configName = clean
422
+ this.persist()
423
+ })
424
+ await this.removeConfigFile(c.name)
425
+ }
426
+
427
+ async deleteConfig(): Promise<void> {
428
+ const c = this.configEntry
429
+ if (c == null) return
430
+ await this.removeConfigFile(c.name)
431
+ runInAction(() => {
432
+ if (!this.configs.some((x) => x.name === this.configName)) this.configName = this.configs[0]?.name ?? ''
433
+ this.lastSavedConfig = JSON.stringify(this.configEntry)
434
+ this.persist()
435
+ })
436
+ }
437
+
438
+ private async removeConfigFile(name: string): Promise<void> {
439
+ try {
440
+ const reply = await deleteLlmConfig({ name })
441
+ runInAction(() => {
442
+ this.configs = reply.configs
443
+ })
444
+ } catch (e) {
445
+ runInAction(() => {
446
+ this.configSaveState = 'error'
447
+ this.configSaveError = e instanceof Error ? e.message : String(e)
448
+ })
449
+ }
450
+ }
451
+
452
+ /** every edit replaces the ENTRY, so the autosave reaction sees a change. With no config yet,
453
+ * the first edit creates one: a setting typed into an empty modal is never dropped */
454
+ private patchConfig(patch: (c: LlmConfig) => LlmConfig): void {
455
+ const c = this.configEntry
456
+ if (c == null) {
457
+ this.addConfig('default', patch(this.config))
458
+ return
211
459
  }
460
+ this.configs = this.configs.map((x) => (x.name === c.name ? { name: x.name, config: patch(x.config) } : x))
461
+ }
462
+
463
+ private clearModels(): void {
464
+ this.models = []
465
+ this.modelsState = 'idle'
466
+ this.modelsError = ''
212
467
  }
213
468
 
214
469
  setProvider(v: string): void {
215
470
  if (!isProvider(v)) return
216
- this.provider = v
471
+ this.patchConfig((c) => withProvider(c, v))
217
472
  // the loaded list belongs to the OTHER provider: showing it would offer models this
218
473
  // endpoint has never heard of
219
- this.models = []
220
- this.modelsState = 'idle'
221
- this.modelsError = ''
222
- this.persist()
474
+ this.clearModels()
223
475
  }
224
476
 
225
477
  setApiKey(v: string): void {
@@ -228,24 +480,20 @@ export class EnhancerSt {
228
480
  }
229
481
 
230
482
  setBaseUrl(v: string): void {
231
- this.baseUrlByProvider[this.provider] = v.trim()
232
- this.persist()
483
+ this.patchConfig((c) => ({ ...c, baseUrl: v.trim() }))
233
484
  }
234
485
 
235
486
  setModel(v: string): void {
236
- this.modelByProvider[this.provider] = v
237
- this.persist()
487
+ this.patchConfig((c) => ({ ...c, model: v }))
238
488
  }
239
489
 
240
490
  setEffort(v: string): void {
241
491
  if (!isEffort(v)) return
242
- this.effort = v
243
- this.persist()
492
+ this.patchConfig((c) => ({ ...c, effort: v }))
244
493
  }
245
494
 
246
495
  toggleThinkingOnly(): void {
247
- this.thinkingOnly = !this.thinkingOnly
248
- this.persist()
496
+ this.patchConfig((c) => ({ ...c, thinkingOnly: !c.thinkingOnly }))
249
497
  }
250
498
 
251
499
  // #region master prompts (server files) -------------------------------------
@@ -366,22 +614,68 @@ export class EnhancerSt {
366
614
  }
367
615
 
368
616
  // #region the run ----------------------------------------------------------
369
- openFor(p: { v: VarSt; module: string }): void {
617
+ openFor(p: { v: VarSt; module: string; lane?: number }): void {
370
618
  this.target = p.v
619
+ this.targetLane = p.lane ?? null
371
620
  this.targetModule = p.module
372
- this.original = typeof p.v.value === 'string' ? p.v.value : ''
373
- this.result = ''
374
- this.thinking = ''
621
+ // the input is the draft's own intent for this prompt (`original`), the last rewrite stays
375
622
  this.error = ''
376
- this.phase = 'idle'
377
623
  const remembered = this.presetByModule[p.module]
378
624
  if (remembered != null) this.presetName = remembered
379
- if (this.presets.length === 0) void this.loadPresets()
625
+ if (this.presets.length === 0) void this.loadPresets().then(() => this.guessFor(p.module))
626
+ else this.guessFor(p.module)
627
+ // re-read every open: a config edited in another window or by hand is picked up
628
+ void this.loadConfigs()
629
+ }
630
+
631
+ /** no preset picked for this workflow yet: take the one its name points at */
632
+ private guessFor(module: string): void {
633
+ if (this.presetByModule[module] != null) return
634
+ const guess = guessPreset(
635
+ module,
636
+ this.presets.map((x) => x.name),
637
+ )
638
+ if (guess == null) return
639
+ this.presetName = guess
640
+ this.lastSaved = JSON.stringify(this.preset)
641
+ }
642
+
643
+ setEditing(v: 'llm' | 'preset' | null): void {
644
+ this.editing = v
645
+ }
646
+
647
+ /** the override a generate sends right now (generateOverride) */
648
+ get tryOverride(): Record<string, unknown> | undefined {
649
+ return generateOverride({ open: this.isOpen, target: this.target, lane: this.targetLane, result: this.result })
650
+ }
651
+
652
+ /** where this prompt's intent lives in the draft's `$enhance`, null while closed */
653
+ get intentKey(): string | null {
654
+ return this.target == null ? null : intentKey(this.target.name, this.targetLane)
655
+ }
656
+
657
+ /** the input: the intent the DRAFT keeps for this prompt (or lane), saved with it, so each
658
+ * draft has its own and a reload opens on it. None yet = the prompt itself */
659
+ get original(): string {
660
+ const key = this.intentKey
661
+ if (key == null || this.target == null) return ''
662
+ return openingInput({
663
+ previous: this.getForm()?.intentFor(key) ?? '',
664
+ prompt: promptTextOf(this.target.value, this.targetLane),
665
+ })
666
+ }
667
+
668
+ /** back to the prompt: the intent is cleared, so the input follows the prompt again */
669
+ usePrompt(): void {
670
+ const key = this.intentKey
671
+ if (key != null) this.getForm()?.setIntent(key, '')
380
672
  }
381
673
 
382
674
  close(): void {
675
+ this.editing = null
383
676
  this.cancel()
384
677
  this.target = null
678
+ this.targetLane = null
385
679
  this.targetModule = ''
386
680
  }
387
681
 
@@ -392,7 +686,8 @@ export class EnhancerSt {
392
686
  /** what gets SENT is editable too: sharpen the sketch, then refine, without closing the
393
687
  * modal. It stays a copy, only apply() writes the var */
394
688
  setOriginal(v: string): void {
395
- this.original = v
689
+ const key = this.intentKey
690
+ if (key != null) this.getForm()?.setIntent(key, v)
396
691
  }
397
692
 
398
693
  async loadModels(): Promise<void> {
@@ -405,11 +700,15 @@ export class EnhancerSt {
405
700
  runInAction(() => {
406
701
  this.models = models
407
702
  this.modelsState = 'idle'
703
+ const name = this.configEntry?.name
704
+ if (name != null) this.configStatus.set(name, 'up')
408
705
  })
409
706
  } catch (e) {
410
707
  runInAction(() => {
411
708
  this.modelsState = 'error'
412
709
  this.modelsError = e instanceof Error ? e.message : String(e)
710
+ const name = this.configEntry?.name
711
+ if (name != null) this.configStatus.set(name, 'down')
413
712
  })
414
713
  }
415
714
  }
@@ -429,6 +728,15 @@ export class EnhancerSt {
429
728
  if (preset == null || this.phase === 'running') return
430
729
  const controller = new AbortController()
431
730
  this.abort = controller
731
+ // the negatives and comments never go to the model: they come back verbatim, on their own
732
+ // lines, once it is done (keptLines.ts owns why)
733
+ const split = splitKeptLines(this.original)
734
+ this.inputHistory = pushHistory(this.inputHistory, {
735
+ text: this.original,
736
+ value: this.original,
737
+ at: Date.now(),
738
+ source: this.targetModule,
739
+ })
432
740
  runInAction(() => {
433
741
  this.phase = 'running'
434
742
  this.error = ''
@@ -440,7 +748,7 @@ export class EnhancerSt {
440
748
  endpoint: this.endpoint,
441
749
  model: this.model,
442
750
  system: preset.text,
443
- user: this.original,
751
+ user: split.body,
444
752
  effort: this.effort,
445
753
  signal: controller.signal,
446
754
  onDelta: (d) =>
@@ -450,12 +758,14 @@ export class EnhancerSt {
450
758
  }),
451
759
  })
452
760
  runInAction(() => {
761
+ this.result = finishRewrite(this.result, split.kept)
453
762
  this.phase = 'done'
454
763
  })
455
764
  } catch (e) {
456
765
  // an abort is a user gesture, not a failure to shout about
457
766
  const aborted = controller.signal.aborted
458
767
  runInAction(() => {
768
+ if (aborted && this.result !== '') this.result = finishRewrite(this.result, split.kept)
459
769
  this.phase = aborted ? (this.result === '' ? 'idle' : 'done') : 'error'
460
770
  if (!aborted) this.error = e instanceof Error ? e.message : String(e)
461
771
  })
@@ -468,7 +778,12 @@ export class EnhancerSt {
468
778
  apply(): void {
469
779
  const text = this.result.trim()
470
780
  if (this.target == null || text === '') return
471
- this.target.set(text)
781
+ const value = this.target.value
782
+ const lane = this.targetLane
783
+ // a lane rewrite replaces that lane's text only, the others and their order stay
784
+ if (lane != null && isPromptLanes(value))
785
+ this.target.set({ lanes: patchLane(value.lanes, lane, { prompt: text }) })
786
+ else this.target.set(text)
472
787
  this.close()
473
788
  }
474
789
  }