comfy-ts 2.4.2 → 2.6.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 (62) hide show
  1. package/README.md +12 -1
  2. package/dist/{DefinedWorkflow-CnzmQrBh.js → DefinedWorkflow-BJgt5t0x.js} +14 -3
  3. package/dist/DefinedWorkflow-BJgt5t0x.js.map +1 -0
  4. package/dist/{DraftsSt-C1MbWnEp.js → DraftsSt-dizp3VcC.js} +2 -2
  5. package/dist/{DraftsSt-C1MbWnEp.js.map → DraftsSt-dizp3VcC.js.map} +1 -1
  6. package/dist/cli.js +4 -4
  7. package/dist/index.cjs +3 -2
  8. package/dist/index.cjs.map +1 -1
  9. package/dist/index.d.cts +3 -0
  10. package/dist/index.d.ts +3 -0
  11. package/dist/index.js +3 -2
  12. package/dist/index.js.map +1 -1
  13. package/dist/{run-serve-D47Zas-a.js → run-serve-CVu39RNd.js} +330 -16
  14. package/dist/run-serve-CVu39RNd.js.map +1 -0
  15. package/dist/{run-tui-BqNO9Ck0.js → run-tui-idFhdO4f.js} +707 -527
  16. package/dist/run-tui-idFhdO4f.js.map +1 -0
  17. package/dist/serve-web.js +280 -0
  18. package/dist/{state-D9w1aJow.js → state-C90kdjtB.js} +3 -13
  19. package/dist/state-C90kdjtB.js.map +1 -0
  20. package/dist/web.d.ts +3 -0
  21. package/dist/web.js +3 -2
  22. package/dist/web.js.map +1 -1
  23. package/package.json +9 -7
  24. package/src/cli/serve/ServeApp.ts +314 -13
  25. package/src/cli/serve/describeVar.ts +6 -1
  26. package/src/cli/serve/run-serve.ts +4 -2
  27. package/src/cli/serve/web/api.ts +105 -0
  28. package/src/cli/serve/web/clipboard.ts +25 -0
  29. package/src/cli/serve/web/components/App.tsx +53 -0
  30. package/src/cli/serve/web/components/Gallery.tsx +186 -0
  31. package/src/cli/serve/web/components/PromptEnhancer.tsx +210 -0
  32. package/src/cli/serve/web/components/Sidebar.tsx +42 -0
  33. package/src/cli/serve/web/components/VarsForm.tsx +173 -0
  34. package/src/cli/serve/web/components/controls/BasicControls.tsx +95 -0
  35. package/src/cli/serve/web/components/controls/ImageControl.tsx +71 -0
  36. package/src/cli/serve/web/components/controls/LorasControl.tsx +340 -0
  37. package/src/cli/serve/web/components/controls/SeedControl.tsx +43 -0
  38. package/src/cli/serve/web/components/controls/SizeControl.tsx +49 -0
  39. package/src/cli/serve/web/main.tsx +18 -0
  40. package/src/cli/serve/web/openrouter.ts +142 -0
  41. package/src/cli/serve/web/state/EnhancerSt.ts +370 -0
  42. package/src/cli/serve/web/state/FormSt.ts +177 -0
  43. package/src/cli/serve/web/state/RunSt.ts +136 -0
  44. package/src/cli/serve/web/state/WebSt.ts +210 -0
  45. package/src/cli/serve/web/state/payload.ts +110 -0
  46. package/src/cli/serve/web/styles.ts +259 -0
  47. package/src/cli/serve/web/tsconfig.json +15 -0
  48. package/src/cli/serve/webBundle.ts +66 -0
  49. package/src/cli/tui/imageEscapes.ts +105 -0
  50. package/src/cli/tui/imagePicker/ImagePickerSt.ts +21 -8
  51. package/src/cli/tui/protocolImage.ts +39 -0
  52. package/src/cli/tui/protocolImagePainter.ts +56 -23
  53. package/src/cli/tui/run-tui.tsx +3 -2
  54. package/src/cli/tui/state/LorasSt.ts +22 -9
  55. package/src/cli/tui/state/PreviewSt.ts +31 -13
  56. package/src/cli/tui/state/SettingsSt.ts +1 -1
  57. package/src/cli/tui/state/TuiSt.ts +4 -4
  58. package/src/vars/ComfyVars.ts +4 -1
  59. package/dist/DefinedWorkflow-CnzmQrBh.js.map +0 -1
  60. package/dist/run-serve-D47Zas-a.js.map +0 -1
  61. package/dist/run-tui-BqNO9Ck0.js.map +0 -1
  62. package/dist/state-D9w1aJow.js.map +0 -1
@@ -0,0 +1,43 @@
1
+ // seed: mode buttons + value + 🎲. Drafts are live, so the mode configures the
2
+ // SERVER's per-draft seed policy (generate posts no seed key; step 4 applies
3
+ // the draft's {mode, value})
4
+ import { observer } from 'mobx-react-lite'
5
+ import type { VarSt } from 'src/cli/serve/web/state/FormSt.ts'
6
+ import { asSeedForm, randomSeed } from 'src/cli/serve/web/state/payload.ts'
7
+
8
+ const MODES: { mode: string; label: string; hint: string }[] = [
9
+ { mode: '=', label: 'fixed', hint: 'this exact seed, every run' },
10
+ { mode: '+', label: '+1', hint: 'increments after each run' },
11
+ { mode: '-', label: '-1', hint: 'decrements after each run' },
12
+ { mode: '?', label: 'random', hint: 'a fresh random seed each run' },
13
+ ]
14
+
15
+ export const SeedControl = observer(function SeedControl(p: { v: VarSt }) {
16
+ const seed = asSeedForm(p.v.value)
17
+ const setValue = (n: number): void => {
18
+ // parseInt('') is NaN, so clearing the box never snaps the seed to 0
19
+ if (Number.isFinite(n)) p.v.set({ mode: seed.mode, value: Math.max(0, Math.floor(n)) })
20
+ }
21
+ return (
22
+ <div>
23
+ <div className="row-inline">
24
+ {MODES.map((m) => (
25
+ <button
26
+ key={m.mode}
27
+ type="button"
28
+ className={seed.mode === m.mode ? 'mode sel' : 'mode'}
29
+ title={m.hint}
30
+ onClick={() => p.v.set({ mode: m.mode, value: seed.value })}
31
+ >
32
+ {m.label}
33
+ </button>
34
+ ))}
35
+ <input type="number" min={0} value={seed.value} onChange={(e) => setValue(parseInt(e.target.value, 10))} />
36
+ <button type="button" title="roll a random seed now" onClick={() => setValue(randomSeed())}>
37
+ 🎲
38
+ </button>
39
+ </div>
40
+ <div className="hint">{MODES.find((m) => m.mode === seed.mode)?.hint ?? seed.mode}</div>
41
+ </div>
42
+ )
43
+ })
@@ -0,0 +1,49 @@
1
+ // size: preset select + free WxH inputs + ⇄ swap
2
+ import { observer } from 'mobx-react-lite'
3
+ import type { VarSt } from 'src/cli/serve/web/state/FormSt.ts'
4
+ import { asSizeForm } from 'src/cli/serve/web/state/payload.ts'
5
+
6
+ export const SizeControl = observer(function SizeControl(p: { v: VarSt }) {
7
+ const size = asSizeForm(p.v.value)
8
+ const presets = p.v.desc.presets ?? []
9
+ const current = presets.find((pr) => pr.width === size.width && pr.height === size.height)
10
+ const setDim = (patch: { width?: number; height?: number }): void => {
11
+ const width = patch.width ?? size.width
12
+ const height = patch.height ?? size.height
13
+ if (Number.isFinite(width) && Number.isFinite(height) && width > 0 && height > 0)
14
+ p.v.set({ width: Math.floor(width), height: Math.floor(height) })
15
+ }
16
+ return (
17
+ <div className="row-inline">
18
+ <select
19
+ value={current?.label ?? '__custom__'}
20
+ onChange={(e) => {
21
+ const preset = presets.find((pr) => pr.label === e.target.value)
22
+ if (preset != null) p.v.set({ width: preset.width, height: preset.height })
23
+ }}
24
+ >
25
+ {current == null ? <option value="__custom__">custom</option> : null}
26
+ {presets.map((pr) => (
27
+ <option key={pr.label} value={pr.label}>
28
+ {pr.label} ({pr.width}×{pr.height})
29
+ </option>
30
+ ))}
31
+ </select>
32
+ <input type="number" min={1} value={size.width} onChange={(e) => setDim({ width: Number(e.target.value) })} />
33
+ ×
34
+ <input
35
+ type="number"
36
+ min={1}
37
+ value={size.height}
38
+ onChange={(e) => setDim({ height: Number(e.target.value) })}
39
+ />
40
+ <button
41
+ type="button"
42
+ title="swap width and height"
43
+ onClick={() => p.v.set({ width: size.height, height: size.width })}
44
+ >
45
+ ⇄
46
+ </button>
47
+ </div>
48
+ )
49
+ })
@@ -0,0 +1,18 @@
1
+ // browser entry: inject the stylesheet, mount the root store + app
2
+ import { createRoot } from 'react-dom/client'
3
+ import { App } from 'src/cli/serve/web/components/App.tsx'
4
+ import { WebSt } from 'src/cli/serve/web/state/WebSt.ts'
5
+ import { STYLES } from 'src/cli/serve/web/styles.ts'
6
+
7
+ const styleEl = document.createElement('style')
8
+ styleEl.textContent = STYLES
9
+ document.head.appendChild(styleEl)
10
+
11
+ const st = new WebSt()
12
+ // console debugging path (app-state-tree: expose the root) — globalThis probe,
13
+ // agent/coding.md cast whitelist family 3
14
+ ;(globalThis as { webst?: WebSt }).webst = st
15
+
16
+ const rootEl = document.getElementById('root')
17
+ if (rootEl == null) throw new Error('[serve web] #root element missing from the shell html')
18
+ createRoot(rootEl).render(<App st={st} />)
@@ -0,0 +1,142 @@
1
+ // browser → openrouter. The second http module after api.ts, and the ONLY one
2
+ // that leaves this machine. The key is a parameter on every call: it lives in
3
+ // localStorage (EnhancerSt) and never reaches the serve process or the disk.
4
+ // Parsing is pure and DOM-free so tests/serve-web-enhancer.test.ts covers it.
5
+
6
+ const BASE = 'https://openrouter.ai/api/v1'
7
+
8
+ export type OpenRouterModel = { id: string; name: string; reasoning: boolean }
9
+
10
+ export type ReasoningEffort = 'off' | 'low' | 'medium' | 'high'
11
+
12
+ /** an external api drifts: every field is shape-checked before it is kept (coding.md cast family 10) */
13
+ function obj(raw: unknown): Record<string, unknown> {
14
+ return typeof raw === 'object' && raw !== null && !Array.isArray(raw) ? (raw as Record<string, unknown>) : {}
15
+ }
16
+
17
+ function str(raw: unknown): string {
18
+ return typeof raw === 'string' ? raw : ''
19
+ }
20
+
21
+ /** `supported_parameters` carrying "reasoning" is what makes a model a THINKING model here */
22
+ export function parseModelsReply(raw: unknown): OpenRouterModel[] {
23
+ const data = obj(raw).data
24
+ if (!Array.isArray(data)) return []
25
+ const out: OpenRouterModel[] = []
26
+ for (const entry of data) {
27
+ const m = obj(entry)
28
+ const id = str(m.id)
29
+ if (id === '') continue
30
+ const params = Array.isArray(m.supported_parameters) ? m.supported_parameters : []
31
+ out.push({ id, name: str(m.name) === '' ? id : str(m.name), reasoning: params.includes('reasoning') })
32
+ }
33
+ out.sort((a, b) => a.id.localeCompare(b.id))
34
+ return out
35
+ }
36
+
37
+ async function failure(res: Response, what: string): Promise<Error> {
38
+ // never fail silently, and never let a gateway's html body masquerade as json
39
+ const body = await res.text().catch(() => '')
40
+ return new Error(`openrouter ${what} failed: http ${res.status} ${body.slice(0, 300)}`)
41
+ }
42
+
43
+ export async function fetchModels(p: { key: string }): Promise<OpenRouterModel[]> {
44
+ if (p.key.trim() === '') throw new Error('no openrouter api key — paste one in the enhancer settings')
45
+ const res = await fetch(`${BASE}/models`, { headers: { Authorization: `Bearer ${p.key.trim()}` } })
46
+ if (!res.ok) throw await failure(res, 'model list')
47
+ return parseModelsReply(await res.json())
48
+ }
49
+
50
+ export type RefineRequest = {
51
+ model: string
52
+ system: string
53
+ user: string
54
+ effort: ReasoningEffort
55
+ }
56
+
57
+ /** the chat body. `reasoning` is OMITTED at effort 'off': a model without thinking support rejects it */
58
+ export function buildRefineBody(p: RefineRequest): Record<string, unknown> {
59
+ return {
60
+ model: p.model,
61
+ stream: true,
62
+ messages: [
63
+ { role: 'system', content: p.system },
64
+ { role: 'user', content: p.user },
65
+ ],
66
+ ...(p.effort === 'off' ? {} : { reasoning: { effort: p.effort } }),
67
+ }
68
+ }
69
+
70
+ /** SSE framing: complete lines come out, the trailing partial stays in `rest` for the next chunk */
71
+ export function splitSseBuffer(buffer: string): { events: string[]; rest: string } {
72
+ const lines = buffer.split('\n')
73
+ const rest = lines.pop() ?? ''
74
+ const events: string[] = []
75
+ for (const line of lines) {
76
+ const trimmed = line.trim()
77
+ // ": OPENROUTER PROCESSING" keep-alive comments are not events
78
+ if (trimmed === '' || trimmed.startsWith(':')) continue
79
+ if (trimmed.startsWith('data:')) events.push(trimmed.slice(5).trim())
80
+ }
81
+ return { events, rest }
82
+ }
83
+
84
+ export type StreamDelta = { content: string; reasoning: string }
85
+
86
+ /** one `data:` payload → what it adds. Thinking models put the visible answer in `content`
87
+ * and their work in `reasoning`; both are streamed, only content is the prompt */
88
+ export function readStreamDelta(payload: string): StreamDelta | null {
89
+ if (payload === '' || payload === '[DONE]') return null
90
+ let parsed: unknown
91
+ try {
92
+ parsed = JSON.parse(payload)
93
+ } catch {
94
+ return null
95
+ }
96
+ const root = obj(parsed)
97
+ const err = obj(root.error)
98
+ if (str(err.message) !== '') throw new Error(`openrouter stream error: ${str(err.message)}`)
99
+ const choices = root.choices
100
+ if (!Array.isArray(choices)) return null
101
+ const delta = obj(obj(choices[0]).delta)
102
+ const content = str(delta.content)
103
+ const reasoning = str(delta.reasoning)
104
+ if (content === '' && reasoning === '') return null
105
+ return { content, reasoning }
106
+ }
107
+
108
+ /** streamed refine. onDelta fires per chunk so a slow thinking model shows work, not a spinner */
109
+ export async function streamRefine(
110
+ p: RefineRequest & { key: string; signal: AbortSignal; onDelta: (d: StreamDelta) => void },
111
+ ): Promise<StreamDelta> {
112
+ if (p.key.trim() === '') throw new Error('no openrouter api key — paste one in the enhancer settings')
113
+ if (p.model.trim() === '') throw new Error('no model selected')
114
+ const res = await fetch(`${BASE}/chat/completions`, {
115
+ method: 'POST',
116
+ headers: { Authorization: `Bearer ${p.key.trim()}`, 'content-type': 'application/json' },
117
+ body: JSON.stringify(buildRefineBody(p)),
118
+ signal: p.signal,
119
+ })
120
+ if (!res.ok) throw await failure(res, 'refine')
121
+ const reader = res.body?.getReader()
122
+ if (reader == null) throw new Error('openrouter refine failed: the response carried no stream')
123
+ const decoder = new TextDecoder()
124
+ const total: StreamDelta = { content: '', reasoning: '' }
125
+ let buffer = ''
126
+ for (;;) {
127
+ const chunk = await reader.read()
128
+ if (chunk.done) break
129
+ buffer += decoder.decode(chunk.value, { stream: true })
130
+ const split = splitSseBuffer(buffer)
131
+ buffer = split.rest
132
+ for (const event of split.events) {
133
+ const delta = readStreamDelta(event)
134
+ if (delta == null) continue
135
+ total.content += delta.content
136
+ total.reasoning += delta.reasoning
137
+ p.onDelta(delta)
138
+ }
139
+ }
140
+ if (total.content.trim() === '') throw new Error('openrouter refine returned no text — try another model')
141
+ return total
142
+ }
@@ -0,0 +1,370 @@
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'
7
+ import type { VarSt } from 'src/cli/serve/web/state/FormSt.ts'
8
+
9
+ const STORAGE_KEY = 'comfy-ts-serve-enhancer'
10
+
11
+ /** 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 }]
31
+ }
32
+
33
+ export type EnhancerSettings = {
34
+ apiKey: string
35
+ model: string
36
+ effort: ReasoningEffort
37
+ thinkingOnly: boolean
38
+ presets: MasterPrompt[]
39
+ presetId: string
40
+ /** last preset used per module: a workflow reopens on its own refiner */
41
+ presetByModule: Record<string, string>
42
+ }
43
+
44
+ function str(raw: unknown, fallback: string): string {
45
+ return typeof raw === 'string' && raw !== '' ? raw : fallback
46
+ }
47
+
48
+ function isEffort(raw: unknown): raw is ReasoningEffort {
49
+ return raw === 'off' || raw === 'low' || raw === 'medium' || raw === 'high'
50
+ }
51
+
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 */
54
+ export function normalizeSettings(raw: unknown): EnhancerSettings {
55
+ 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, '')
73
+ return {
74
+ apiKey: typeof o.apiKey === 'string' ? o.apiKey : '',
75
+ model: str(o.model, DEFAULT_MODEL),
76
+ effort: isEffort(o.effort) ? o.effort : 'medium',
77
+ thinkingOnly: o.thinkingOnly !== false,
78
+ presets: library,
79
+ presetId: library.some((p) => p.id === wantedId) ? wantedId : (library[0]?.id ?? ''),
80
+ presetByModule: byModule,
81
+ }
82
+ }
83
+
84
+ /** unique name for a new/duplicated preset — a library of three "copy" entries is unusable */
85
+ export function nextPresetName(base: string, taken: readonly string[]): string {
86
+ if (!taken.includes(base)) return base
87
+ for (let i = 2; i < 1000; i++) {
88
+ const candidate = `${base} ${i}`
89
+ if (!taken.includes(candidate)) return candidate
90
+ }
91
+ return `${base} ${taken.length + 1}`
92
+ }
93
+
94
+ function newId(): string {
95
+ return `mp-${Math.random().toString(36).slice(2, 10)}`
96
+ }
97
+
98
+ function readStored(): EnhancerSettings {
99
+ try {
100
+ return normalizeSettings(JSON.parse(localStorage.getItem(STORAGE_KEY) ?? '{}'))
101
+ } catch {
102
+ return normalizeSettings({})
103
+ }
104
+ }
105
+
106
+ export class EnhancerSt {
107
+ apiKey: string
108
+ model: string
109
+ effort: ReasoningEffort
110
+ thinkingOnly: boolean
111
+ presets: MasterPrompt[]
112
+ presetId: string
113
+ presetByModule: Record<string, string>
114
+
115
+ models: OpenRouterModel[] = []
116
+ modelsState: 'idle' | 'loading' | 'error' = 'idle'
117
+ modelsError = ''
118
+
119
+ /** the prompt var being refined — non-null IS the modal being open */
120
+ target: VarSt | null = null
121
+ targetModule = ''
122
+ original = ''
123
+ result = ''
124
+ thinking = ''
125
+ phase: 'idle' | 'running' | 'done' | 'error' = 'idle'
126
+ error = ''
127
+ private abort: AbortController | null = null
128
+
129
+ constructor() {
130
+ const s = readStored()
131
+ this.apiKey = s.apiKey
132
+ this.model = s.model
133
+ this.effort = s.effort
134
+ this.thinkingOnly = s.thinkingOnly
135
+ this.presets = s.presets
136
+ this.presetId = s.presetId
137
+ this.presetByModule = s.presetByModule
138
+ makeAutoObservable<EnhancerSt, 'abort'>(this, { abort: false })
139
+ }
140
+
141
+ get preset(): MasterPrompt | null {
142
+ return this.presets.find((p) => p.id === this.presetId) ?? this.presets[0] ?? null
143
+ }
144
+
145
+ get isOpen(): boolean {
146
+ return this.target != null
147
+ }
148
+
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
152
+ }
153
+
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
164
+ }
165
+
166
+ close(): void {
167
+ this.cancel()
168
+ this.target = null
169
+ this.targetModule = ''
170
+ }
171
+
172
+ settingsJSON(): EnhancerSettings {
173
+ return {
174
+ apiKey: this.apiKey,
175
+ model: this.model,
176
+ effort: this.effort,
177
+ thinkingOnly: this.thinkingOnly,
178
+ presets: this.presets,
179
+ presetId: this.presetId,
180
+ presetByModule: this.presetByModule,
181
+ }
182
+ }
183
+
184
+ private persist(): void {
185
+ try {
186
+ localStorage.setItem(STORAGE_KEY, JSON.stringify(this.settingsJSON()))
187
+ } catch {
188
+ // storage full/blocked: settings just won't survive the reload
189
+ }
190
+ }
191
+
192
+ setApiKey(v: string): void {
193
+ this.apiKey = v.trim()
194
+ this.persist()
195
+ }
196
+
197
+ setModel(v: string): void {
198
+ this.model = v
199
+ this.persist()
200
+ }
201
+
202
+ /** takes the raw select value: validating here keeps the component cast-free */
203
+ setEffort(v: string): void {
204
+ if (!isEffort(v)) return
205
+ this.effort = v
206
+ this.persist()
207
+ }
208
+
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
+ toggleThinkingOnly(): void {
221
+ this.thinkingOnly = !this.thinkingOnly
222
+ this.persist()
223
+ }
224
+
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()
230
+ }
231
+
232
+ private replacePreset(next: MasterPrompt): void {
233
+ this.presets = this.presets.map((p) => (p.id === next.id ? next : p))
234
+ this.persist()
235
+ }
236
+
237
+ setPresetText(text: string): void {
238
+ const p = this.preset
239
+ if (p != null) this.replacePreset({ ...p, text })
240
+ }
241
+
242
+ renamePreset(name: string): void {
243
+ 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
+ })
253
+ }
254
+
255
+ 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)
268
+ }
269
+
270
+ duplicatePreset(): void {
271
+ const p = this.preset
272
+ if (p != null) this.addPreset(`${p.name} copy`, p.text)
273
+ }
274
+
275
+ deletePreset(): void {
276
+ const p = this.preset
277
+ 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()
284
+ }
285
+
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()
292
+ }
293
+
294
+ async loadModels(): Promise<void> {
295
+ runInAction(() => {
296
+ this.modelsState = 'loading'
297
+ this.modelsError = ''
298
+ })
299
+ try {
300
+ const models = await fetchModels({ key: this.apiKey })
301
+ runInAction(() => {
302
+ this.models = models
303
+ this.modelsState = 'idle'
304
+ })
305
+ } catch (e) {
306
+ runInAction(() => {
307
+ this.modelsState = 'error'
308
+ this.modelsError = e instanceof Error ? e.message : String(e)
309
+ })
310
+ }
311
+ }
312
+
313
+ cancel(): void {
314
+ this.abort?.abort()
315
+ this.abort = null
316
+ if (this.phase === 'running') this.phase = this.result === '' ? 'idle' : 'done'
317
+ }
318
+
319
+ run(): void {
320
+ void this.runNow()
321
+ }
322
+
323
+ private async runNow(): Promise<void> {
324
+ const preset = this.preset
325
+ if (preset == null || this.phase === 'running') return
326
+ const controller = new AbortController()
327
+ this.abort = controller
328
+ runInAction(() => {
329
+ this.phase = 'running'
330
+ this.error = ''
331
+ this.result = ''
332
+ this.thinking = ''
333
+ })
334
+ try {
335
+ await streamRefine({
336
+ key: this.apiKey,
337
+ model: this.model,
338
+ system: preset.text,
339
+ user: this.original,
340
+ effort: this.effort,
341
+ signal: controller.signal,
342
+ onDelta: (d) =>
343
+ runInAction(() => {
344
+ this.result += d.content
345
+ this.thinking += d.reasoning
346
+ }),
347
+ })
348
+ runInAction(() => {
349
+ this.phase = 'done'
350
+ })
351
+ } catch (e) {
352
+ // an abort is a user gesture, not a failure to shout about
353
+ const aborted = controller.signal.aborted
354
+ runInAction(() => {
355
+ this.phase = aborted ? (this.result === '' ? 'idle' : 'done') : 'error'
356
+ if (!aborted) this.error = e instanceof Error ? e.message : String(e)
357
+ })
358
+ } finally {
359
+ if (this.abort === controller) this.abort = null
360
+ }
361
+ }
362
+
363
+ /** the ONLY write into the form: nothing lands on the var until this is clicked */
364
+ apply(): void {
365
+ const text = this.result.trim()
366
+ if (this.target == null || text === '') return
367
+ this.target.set(text)
368
+ this.close()
369
+ }
370
+ }