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