comfy-ts 2.6.0 → 2.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +22 -13
- package/dist/{DefinedWorkflow-BJgt5t0x.js → DefinedWorkflow-BatWaZO1.js} +199 -16
- package/dist/DefinedWorkflow-BatWaZO1.js.map +1 -0
- package/dist/{DraftsSt-dizp3VcC.js → LogsSt-DFxzQfDc.js} +152 -4
- package/dist/LogsSt-DFxzQfDc.js.map +1 -0
- package/dist/cli.js +8 -6
- package/dist/cli.js.map +1 -1
- package/dist/index.cjs +288 -35
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +128 -7
- package/dist/index.d.ts +128 -7
- package/dist/index.js +286 -37
- package/dist/index.js.map +1 -1
- package/dist/run-serve-_nrvJYyt.js +1948 -0
- package/dist/run-serve-_nrvJYyt.js.map +1 -0
- package/dist/{run-tui-idFhdO4f.js → run-tui-BPw-SZYW.js} +107 -158
- package/dist/run-tui-BPw-SZYW.js.map +1 -0
- package/dist/serve-web.js +434 -81
- package/dist/{state-C90kdjtB.js → state-B-boDz-Z.js} +184 -45
- package/dist/state-B-boDz-Z.js.map +1 -0
- package/dist/web.d.ts +112 -7
- package/dist/web.js +239 -36
- package/dist/web.js.map +1 -1
- package/examples/README.md +1 -0
- package/examples/comfy-cloud/sdk.d.ts +4066 -321
- package/examples/rvion/04-krea2-turbo-t2i.cflow.ts +18 -2
- package/examples/rvion/07-local-llm-text-gen.cflow.ts +220 -0
- package/examples/web/tsconfig.json +7 -1
- package/extra/README.md +32 -0
- package/extra/comfyui-textgen-stream/README.md +35 -0
- package/extra/comfyui-textgen-stream/__init__.py +166 -0
- package/extra/scripts/fetch_text_encoder.py +137 -0
- package/package.json +6 -3
- package/src/cli/comfy-ts-cli.ts +4 -2
- package/src/cli/serve/ServeApp.ts +825 -43
- package/src/cli/serve/applyVarPayload.ts +10 -3
- package/src/cli/serve/describeVar.ts +47 -7
- package/src/cli/serve/managerOnlyLoras.ts +27 -0
- package/src/cli/serve/run-serve.ts +58 -29
- package/src/cli/serve/serveSettings.ts +86 -0
- package/src/cli/serve/startupPrint.ts +111 -0
- package/src/cli/serve/web/api.ts +120 -1
- package/src/cli/serve/web/components/App.tsx +61 -22
- package/src/cli/serve/web/components/Gallery.tsx +243 -30
- package/src/cli/serve/web/components/Icon.tsx +160 -0
- package/src/cli/serve/web/components/PromptEnhancer.tsx +85 -38
- package/src/cli/serve/web/components/Sidebar.tsx +43 -19
- package/src/cli/serve/web/components/VarsForm.tsx +440 -80
- package/src/cli/serve/web/components/controls/BasicControls.tsx +38 -5
- package/src/cli/serve/web/components/controls/ImageControl.tsx +3 -2
- package/src/cli/serve/web/components/controls/LorasControl.tsx +498 -81
- package/src/cli/serve/web/components/controls/PresetPicker.tsx +60 -0
- package/src/cli/serve/web/components/controls/SeedControl.tsx +38 -20
- package/src/cli/serve/web/components/controls/SizeControl.tsx +3 -2
- package/src/cli/serve/web/llm.ts +254 -0
- package/src/cli/serve/web/logWeb.ts +6 -0
- package/src/cli/serve/web/state/EnhancerSt.ts +261 -157
- package/src/cli/serve/web/state/FormSt.ts +70 -18
- package/src/cli/serve/web/state/RunSt.ts +22 -1
- package/src/cli/serve/web/state/WebSt.ts +542 -13
- package/src/cli/serve/web/state/lightbox.ts +44 -0
- package/src/cli/serve/web/state/moduleTree.ts +52 -0
- package/src/cli/serve/web/state/payload.ts +44 -2
- package/src/cli/serve/web/state/urlSelection.ts +53 -0
- package/src/cli/serve/web/styles.ts +415 -57
- package/src/cli/serve/web/tsconfig.json +4 -0
- package/src/cli/tui/components/PickerOverlays.tsx +37 -0
- package/src/cli/tui/components/StatusBar.tsx +14 -1
- package/src/cli/tui/components/TuiApp.tsx +5 -2
- package/src/cli/tui/state/HostSt.ts +3 -2
- package/src/cli/tui/state/PickerSt.ts +48 -2
- package/src/cli/tui/state/TreeSt.ts +1 -1
- package/src/cli/tui/state/TuiSt.ts +2 -1
- package/src/coreExports.ts +8 -1
- package/src/graph/ComfyNode.ts +58 -1
- package/src/host/ComfyHost.ts +13 -2
- package/src/host/ComfyManager.ts +31 -13
- package/src/host/loraInfoCache.ts +35 -1
- package/src/host/loraManagerApi.ts +94 -0
- package/src/index.ts +2 -0
- package/src/promptEnhancers.ts +102 -0
- package/src/runner/ComfyExecution.ts +61 -6
- package/src/runner/ComfyWorkflow.ts +18 -4
- package/src/runner/ComfyWsApi.ts +3 -0
- package/src/runner/describePromptRejection.ts +34 -0
- package/src/sdk-generator/ComfySchema.ts +17 -4
- package/src/sdk-generator/comfyui-sdk-codegen.ts +56 -2
- package/src/state.ts +6 -0
- package/src/utils/ansi.ts +13 -0
- package/src/utils/matchesRegex.ts +13 -0
- package/src/utils/safeName.ts +29 -0
- package/src/utils/stringMap.ts +9 -0
- package/src/vars/ComfyVars.ts +61 -10
- package/src/vars/presets.ts +17 -0
- package/dist/DefinedWorkflow-BJgt5t0x.js.map +0 -1
- package/dist/DraftsSt-dizp3VcC.js.map +0 -1
- package/dist/run-serve-CVu39RNd.js +0 -1002
- package/dist/run-serve-CVu39RNd.js.map +0 -1
- package/dist/run-tui-idFhdO4f.js.map +0 -1
- package/dist/state-C90kdjtB.js.map +0 -1
- package/src/cli/serve/web/openrouter.ts +0 -142
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
// the presets button of a text/prompt var (`v.text(…, { presets })`). Picking one REPLACES
|
|
2
|
+
// the field, so the row's own revert dot is what undoes it — nothing here is a mode.
|
|
3
|
+
import { observer } from 'mobx-react-lite'
|
|
4
|
+
import { useState } from 'react'
|
|
5
|
+
import { Icon } from 'src/cli/serve/web/components/Icon.tsx'
|
|
6
|
+
import type { VarSt } from 'src/cli/serve/web/state/FormSt.ts'
|
|
7
|
+
import { activePresetLabel } from 'src/vars/presets.ts'
|
|
8
|
+
|
|
9
|
+
/** one line of a preset's text, enough to tell two of them apart in the menu */
|
|
10
|
+
function firstLine(text: string): string {
|
|
11
|
+
const line = text.split('\n').find((l) => l.trim() !== '') ?? ''
|
|
12
|
+
return line.length <= 90 ? line : `${line.slice(0, 89)}…`
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export const PresetPicker = observer(function PresetPicker(p: { v: VarSt }) {
|
|
16
|
+
const presets = p.v.desc.textPresets ?? []
|
|
17
|
+
const [open, setOpen] = useState(false)
|
|
18
|
+
if (presets.length === 0) return null
|
|
19
|
+
const value = typeof p.v.value === 'string' ? p.v.value : ''
|
|
20
|
+
const active = activePresetLabel(presets, value)
|
|
21
|
+
return (
|
|
22
|
+
<div className="preset-box" onKeyDown={(e) => (e.key === 'Escape' ? setOpen(false) : undefined)}>
|
|
23
|
+
<button
|
|
24
|
+
type="button"
|
|
25
|
+
className="preset-btn"
|
|
26
|
+
aria-expanded={open}
|
|
27
|
+
data-tip="named starting texts — picking one replaces the field"
|
|
28
|
+
onClick={() => setOpen(!open)}
|
|
29
|
+
>
|
|
30
|
+
<Icon name="tag" /> presets ▾
|
|
31
|
+
</button>
|
|
32
|
+
{open ? (
|
|
33
|
+
<>
|
|
34
|
+
{/* a backdrop closes the menu on any outside click: no document listener, and
|
|
35
|
+
nothing to leak when the form is swapped under it */}
|
|
36
|
+
<div className="preset-backdrop" onClick={() => setOpen(false)} />
|
|
37
|
+
<div className="preset-menu">
|
|
38
|
+
{presets.map((preset) => (
|
|
39
|
+
<button
|
|
40
|
+
key={preset.label}
|
|
41
|
+
type="button"
|
|
42
|
+
className={preset.label === active ? 'preset-item on' : 'preset-item'}
|
|
43
|
+
onClick={() => {
|
|
44
|
+
p.v.set(preset.text)
|
|
45
|
+
setOpen(false)
|
|
46
|
+
}}
|
|
47
|
+
>
|
|
48
|
+
<span className="preset-name">
|
|
49
|
+
{preset.label === active ? '• ' : ' '}
|
|
50
|
+
{preset.label}
|
|
51
|
+
</span>
|
|
52
|
+
<span className="preset-peek">{firstLine(preset.text)}</span>
|
|
53
|
+
</button>
|
|
54
|
+
))}
|
|
55
|
+
</div>
|
|
56
|
+
</>
|
|
57
|
+
) : null}
|
|
58
|
+
</div>
|
|
59
|
+
)
|
|
60
|
+
})
|
|
@@ -1,17 +1,27 @@
|
|
|
1
1
|
// seed: mode buttons + value + 🎲. Drafts are live, so the mode configures the
|
|
2
2
|
// SERVER's per-draft seed policy (generate posts no seed key; step 4 applies
|
|
3
|
-
// the draft's {mode, value})
|
|
3
|
+
// the draft's {mode, value}). The buttons are the SYMBOLS the mode actually is,
|
|
4
|
+
// with the sentence in the tooltip: `fixed / +1 / -1 / random` spelled out was a
|
|
5
|
+
// row of prose wider than the input it belongs to
|
|
6
|
+
import { Icon } from 'src/cli/serve/web/components/Icon.tsx'
|
|
4
7
|
import { observer } from 'mobx-react-lite'
|
|
5
8
|
import type { VarSt } from 'src/cli/serve/web/state/FormSt.ts'
|
|
6
9
|
import { asSeedForm, randomSeed } from 'src/cli/serve/web/state/payload.ts'
|
|
7
10
|
|
|
8
|
-
const MODES: { mode: string;
|
|
9
|
-
{ mode: '=',
|
|
10
|
-
{ mode: '+',
|
|
11
|
-
{ mode: '
|
|
12
|
-
{ mode: '?', label: 'random', hint: 'a fresh random seed each run' },
|
|
11
|
+
const MODES: { mode: string; hint: string }[] = [
|
|
12
|
+
{ mode: '=', hint: 'fixed: this exact seed, every run' },
|
|
13
|
+
{ mode: '+', hint: 'increments after each run' },
|
|
14
|
+
{ mode: '?', hint: 'a fresh random seed each run' },
|
|
13
15
|
]
|
|
14
16
|
|
|
17
|
+
/** `-` is a real mode a draft can hold (the TUI offers it), it is just not worth a permanent
|
|
18
|
+
* button here. It appears only while it IS the mode, so the row never misreports the draft,
|
|
19
|
+
* and it disappears once you pick another one */
|
|
20
|
+
function visibleModes(current: string): { mode: string; hint: string }[] {
|
|
21
|
+
if (MODES.some((m) => m.mode === current)) return MODES
|
|
22
|
+
return [...MODES, { mode: current, hint: current === '-' ? 'decrements after each run' : `mode '${current}'` }]
|
|
23
|
+
}
|
|
24
|
+
|
|
15
25
|
export const SeedControl = observer(function SeedControl(p: { v: VarSt }) {
|
|
16
26
|
const seed = asSeedForm(p.v.value)
|
|
17
27
|
const setValue = (n: number): void => {
|
|
@@ -20,24 +30,32 @@ export const SeedControl = observer(function SeedControl(p: { v: VarSt }) {
|
|
|
20
30
|
}
|
|
21
31
|
return (
|
|
22
32
|
<div>
|
|
33
|
+
{/* one control: the modes are a segmented group, and every element on the row is
|
|
34
|
+
input-height so buttons and the number line up instead of stepping over each other */}
|
|
23
35
|
<div className="row-inline">
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
36
|
+
<span className="btn-group field-height">
|
|
37
|
+
{visibleModes(seed.mode).map((m) => (
|
|
38
|
+
<button
|
|
39
|
+
key={m.mode}
|
|
40
|
+
type="button"
|
|
41
|
+
className={seed.mode === m.mode ? 'sel' : ''}
|
|
42
|
+
data-tip={m.hint}
|
|
43
|
+
onClick={() => p.v.set({ mode: m.mode, value: seed.value })}
|
|
44
|
+
>
|
|
45
|
+
{m.mode}
|
|
46
|
+
</button>
|
|
47
|
+
))}
|
|
48
|
+
</span>
|
|
35
49
|
<input type="number" min={0} value={seed.value} onChange={(e) => setValue(parseInt(e.target.value, 10))} />
|
|
36
|
-
<button
|
|
37
|
-
|
|
50
|
+
<button
|
|
51
|
+
type="button"
|
|
52
|
+
className="field-height"
|
|
53
|
+
data-tip="roll a random seed now"
|
|
54
|
+
onClick={() => setValue(randomSeed())}
|
|
55
|
+
>
|
|
56
|
+
<Icon name="dice" />
|
|
38
57
|
</button>
|
|
39
58
|
</div>
|
|
40
|
-
<div className="hint">{MODES.find((m) => m.mode === seed.mode)?.hint ?? seed.mode}</div>
|
|
41
59
|
</div>
|
|
42
60
|
)
|
|
43
61
|
})
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
// size: preset select + free WxH inputs + ⇄ swap
|
|
2
|
+
import { Icon } from 'src/cli/serve/web/components/Icon.tsx'
|
|
2
3
|
import { observer } from 'mobx-react-lite'
|
|
3
4
|
import type { VarSt } from 'src/cli/serve/web/state/FormSt.ts'
|
|
4
5
|
import { asSizeForm } from 'src/cli/serve/web/state/payload.ts'
|
|
@@ -39,10 +40,10 @@ export const SizeControl = observer(function SizeControl(p: { v: VarSt }) {
|
|
|
39
40
|
/>
|
|
40
41
|
<button
|
|
41
42
|
type="button"
|
|
42
|
-
|
|
43
|
+
data-tip="swap width and height"
|
|
43
44
|
onClick={() => p.v.set({ width: size.height, height: size.width })}
|
|
44
45
|
>
|
|
45
|
-
|
|
46
|
+
<Icon name="swap" />
|
|
46
47
|
</button>
|
|
47
48
|
</div>
|
|
48
49
|
)
|
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
// browser → an OpenAI-wire LLM. Two providers: openrouter (cloud) and open webui
|
|
2
|
+
// (a local box). The second http module after api.ts, and the only one that leaves
|
|
3
|
+
// this origin. Keys are parameters, never module state: they live in localStorage
|
|
4
|
+
// (EnhancerSt) and never reach the serve process.
|
|
5
|
+
// parsing is pure and DOM-free so tests/serve-web-enhancer.test.ts covers it.
|
|
6
|
+
|
|
7
|
+
export type ProviderId = 'openrouter' | 'openwebui'
|
|
8
|
+
|
|
9
|
+
export type Endpoint = { provider: ProviderId; baseUrl: string; key: string }
|
|
10
|
+
|
|
11
|
+
export const OPENROUTER_BASE = 'https://openrouter.ai/api/v1'
|
|
12
|
+
export const OPENWEBUI_BASE = 'http://localhost:3000'
|
|
13
|
+
|
|
14
|
+
export function defaultBaseUrl(provider: ProviderId): string {
|
|
15
|
+
return provider === 'openrouter' ? OPENROUTER_BASE : OPENWEBUI_BASE
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function trimSlash(url: string): string {
|
|
19
|
+
return url.trim().replace(/\/+$/, '')
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** open webui hangs its OpenAI-compatible api under /api, openrouter's base already carries /v1 */
|
|
23
|
+
export function modelsUrl(e: Endpoint): string {
|
|
24
|
+
const base = trimSlash(e.baseUrl) === '' ? defaultBaseUrl(e.provider) : trimSlash(e.baseUrl)
|
|
25
|
+
return e.provider === 'openrouter' ? `${base}/models` : `${base}/api/models`
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function chatUrl(e: Endpoint): string {
|
|
29
|
+
const base = trimSlash(e.baseUrl) === '' ? defaultBaseUrl(e.provider) : trimSlash(e.baseUrl)
|
|
30
|
+
return e.provider === 'openrouter' ? `${base}/chat/completions` : `${base}/api/chat/completions`
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** reasoning: true = says so · false = says it cannot · null = the provider does not tell
|
|
34
|
+
* (open webui reports no capabilities, and hiding every local model would be the wrong answer) */
|
|
35
|
+
export type LlmModel = { id: string; name: string; reasoning: boolean | null }
|
|
36
|
+
|
|
37
|
+
export type ReasoningEffort = 'off' | 'low' | 'medium' | 'high'
|
|
38
|
+
|
|
39
|
+
/** an external api drifts: every field is shape-checked before it is kept (coding.md cast family 10) */
|
|
40
|
+
function obj(raw: unknown): Record<string, unknown> {
|
|
41
|
+
return typeof raw === 'object' && raw !== null && !Array.isArray(raw) ? (raw as Record<string, unknown>) : {}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function str(raw: unknown): string {
|
|
45
|
+
return typeof raw === 'string' ? raw : ''
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function parseModelsReply(raw: unknown): LlmModel[] {
|
|
49
|
+
const data = obj(raw).data
|
|
50
|
+
if (!Array.isArray(data)) return []
|
|
51
|
+
const out: LlmModel[] = []
|
|
52
|
+
for (const entry of data) {
|
|
53
|
+
const m = obj(entry)
|
|
54
|
+
const id = str(m.id)
|
|
55
|
+
if (id === '') continue
|
|
56
|
+
const params = m.supported_parameters
|
|
57
|
+
const reasoning = Array.isArray(params) ? params.includes('reasoning') : null
|
|
58
|
+
out.push({ id, name: str(m.name) === '' ? id : str(m.name), reasoning })
|
|
59
|
+
}
|
|
60
|
+
out.sort((a, b) => a.id.localeCompare(b.id))
|
|
61
|
+
return out
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async function failure(res: Response, what: string): Promise<Error> {
|
|
65
|
+
// never fail silently, and never let a gateway's html body masquerade as json
|
|
66
|
+
const body = await res.text().catch(() => '')
|
|
67
|
+
return new Error(`llm ${what} failed: http ${res.status} ${body.slice(0, 300)}`)
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** a browser fetch that dies on CORS throws a bare TypeError with no detail — say what it
|
|
71
|
+
* probably is, because "Failed to fetch" against a local box is otherwise unactionable */
|
|
72
|
+
function transportError(e: unknown, url: string): Error {
|
|
73
|
+
if (e instanceof Error && e.name === 'AbortError') return e
|
|
74
|
+
const msg = e instanceof Error ? e.message : String(e)
|
|
75
|
+
return new Error(
|
|
76
|
+
`could not reach ${url} (${msg}) — is it running, and does it allow this origin? open webui needs CORS_ALLOW_ORIGIN`,
|
|
77
|
+
)
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export async function fetchModels(e: Endpoint): Promise<LlmModel[]> {
|
|
81
|
+
const url = modelsUrl(e)
|
|
82
|
+
let res: Response
|
|
83
|
+
try {
|
|
84
|
+
res = await fetch(url, { headers: authHeaders(e) })
|
|
85
|
+
} catch (err) {
|
|
86
|
+
throw transportError(err, url)
|
|
87
|
+
}
|
|
88
|
+
if (!res.ok) throw await failure(res, 'model list')
|
|
89
|
+
return parseModelsReply(await res.json())
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function authHeaders(e: Endpoint): Record<string, string> {
|
|
93
|
+
// open webui on a trusted local box may run without a key: send the header only when there is one
|
|
94
|
+
return e.key.trim() === '' ? {} : { Authorization: `Bearer ${e.key.trim()}` }
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export type RefineRequest = { model: string; system: string; user: string; effort: ReasoningEffort }
|
|
98
|
+
|
|
99
|
+
/** the chat body. `reasoning` rides OPENROUTER only: a local backend rejects the unknown field,
|
|
100
|
+
* and its thinking models think on their own (see ThinkSplitter) */
|
|
101
|
+
export function buildRefineBody(p: RefineRequest & { provider: ProviderId }): Record<string, unknown> {
|
|
102
|
+
const reasoning = p.provider === 'openrouter' && p.effort !== 'off' ? { reasoning: { effort: p.effort } } : {}
|
|
103
|
+
return {
|
|
104
|
+
model: p.model,
|
|
105
|
+
stream: true,
|
|
106
|
+
messages: [
|
|
107
|
+
{ role: 'system', content: p.system },
|
|
108
|
+
{ role: 'user', content: p.user },
|
|
109
|
+
],
|
|
110
|
+
...reasoning,
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** SSE framing: complete lines come out, the trailing partial stays in `rest` for the next chunk */
|
|
115
|
+
export function splitSseBuffer(buffer: string): { events: string[]; rest: string } {
|
|
116
|
+
const lines = buffer.split('\n')
|
|
117
|
+
const rest = lines.pop() ?? ''
|
|
118
|
+
const events: string[] = []
|
|
119
|
+
for (const line of lines) {
|
|
120
|
+
const trimmed = line.trim()
|
|
121
|
+
// ": OPENROUTER PROCESSING" keep-alive comments are not events
|
|
122
|
+
if (trimmed === '' || trimmed.startsWith(':')) continue
|
|
123
|
+
if (trimmed.startsWith('data:')) events.push(trimmed.slice(5).trim())
|
|
124
|
+
}
|
|
125
|
+
return { events, rest }
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export type StreamDelta = { content: string; reasoning: string }
|
|
129
|
+
|
|
130
|
+
/** one `data:` payload → what it adds. Cloud thinking models put the answer in `content`
|
|
131
|
+
* and their work in `reasoning`; both are streamed, only content is the prompt */
|
|
132
|
+
export function readStreamDelta(payload: string): StreamDelta | null {
|
|
133
|
+
if (payload === '' || payload === '[DONE]') return null
|
|
134
|
+
let parsed: unknown
|
|
135
|
+
try {
|
|
136
|
+
parsed = JSON.parse(payload)
|
|
137
|
+
} catch {
|
|
138
|
+
return null
|
|
139
|
+
}
|
|
140
|
+
const root = obj(parsed)
|
|
141
|
+
const err = obj(root.error)
|
|
142
|
+
if (str(err.message) !== '') throw new Error(`llm stream error: ${str(err.message)}`)
|
|
143
|
+
const choices = root.choices
|
|
144
|
+
if (!Array.isArray(choices)) return null
|
|
145
|
+
const delta = obj(obj(choices[0]).delta)
|
|
146
|
+
const content = str(delta.content)
|
|
147
|
+
// some backends spell it reasoning_content
|
|
148
|
+
const reasoning = str(delta.reasoning) === '' ? str(delta.reasoning_content) : str(delta.reasoning)
|
|
149
|
+
if (content === '' && reasoning === '') return null
|
|
150
|
+
return { content, reasoning }
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* local thinking models (qwen3, deepseek-r1 through ollama) stream their reasoning INLINE,
|
|
155
|
+
* as `<think>…</think>` at the head of content. Left alone it lands in the prompt, so it is
|
|
156
|
+
* routed to the thinking pane instead. Stateful because a tag can straddle two chunks.
|
|
157
|
+
*/
|
|
158
|
+
export class ThinkSplitter {
|
|
159
|
+
private inside = false
|
|
160
|
+
/** a partial tag held back until the next chunk decides what it is */
|
|
161
|
+
private pending = ''
|
|
162
|
+
|
|
163
|
+
feed(chunk: string): StreamDelta {
|
|
164
|
+
let text = this.pending + chunk
|
|
165
|
+
this.pending = ''
|
|
166
|
+
let content = ''
|
|
167
|
+
let reasoning = ''
|
|
168
|
+
for (;;) {
|
|
169
|
+
const tag = this.inside ? '</think>' : '<think>'
|
|
170
|
+
const at = text.indexOf(tag)
|
|
171
|
+
if (at === -1) break
|
|
172
|
+
const before = text.slice(0, at)
|
|
173
|
+
if (this.inside) reasoning += before
|
|
174
|
+
else content += before
|
|
175
|
+
text = text.slice(at + tag.length)
|
|
176
|
+
this.inside = !this.inside
|
|
177
|
+
}
|
|
178
|
+
// a trailing '<' or '</thin' may be the start of a tag: hold it, do not emit it
|
|
179
|
+
const cut = lastOpenTagStart(text)
|
|
180
|
+
if (cut !== -1) {
|
|
181
|
+
this.pending = text.slice(cut)
|
|
182
|
+
text = text.slice(0, cut)
|
|
183
|
+
}
|
|
184
|
+
if (this.inside) reasoning += text
|
|
185
|
+
else content += text
|
|
186
|
+
return { content, reasoning }
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** end of stream: whatever was held back was never a tag, so it is real text */
|
|
190
|
+
flush(): StreamDelta {
|
|
191
|
+
const rest = this.pending
|
|
192
|
+
this.pending = ''
|
|
193
|
+
return this.inside ? { content: '', reasoning: rest } : { content: rest, reasoning: '' }
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** index of a trailing fragment that could still become `<think>` or `</think>`, else -1 */
|
|
198
|
+
function lastOpenTagStart(text: string): number {
|
|
199
|
+
const at = text.lastIndexOf('<')
|
|
200
|
+
if (at === -1) return -1
|
|
201
|
+
const tail = text.slice(at)
|
|
202
|
+
return '<think>'.startsWith(tail) || '</think>'.startsWith(tail) ? at : -1
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** streamed refine. onDelta fires per chunk so a slow thinking model shows work, not a spinner */
|
|
206
|
+
export async function streamRefine(
|
|
207
|
+
p: RefineRequest & { endpoint: Endpoint; signal: AbortSignal; onDelta: (d: StreamDelta) => void },
|
|
208
|
+
): Promise<StreamDelta> {
|
|
209
|
+
if (p.endpoint.provider === 'openrouter' && p.endpoint.key.trim() === '')
|
|
210
|
+
throw new Error('no openrouter api key — paste one in the enhancer settings')
|
|
211
|
+
if (p.model.trim() === '') throw new Error('no model selected')
|
|
212
|
+
const url = chatUrl(p.endpoint)
|
|
213
|
+
let res: Response
|
|
214
|
+
try {
|
|
215
|
+
res = await fetch(url, {
|
|
216
|
+
method: 'POST',
|
|
217
|
+
headers: { ...authHeaders(p.endpoint), 'content-type': 'application/json' },
|
|
218
|
+
body: JSON.stringify(buildRefineBody({ ...p, provider: p.endpoint.provider })),
|
|
219
|
+
signal: p.signal,
|
|
220
|
+
})
|
|
221
|
+
} catch (e) {
|
|
222
|
+
throw transportError(e, url)
|
|
223
|
+
}
|
|
224
|
+
if (!res.ok) throw await failure(res, 'refine')
|
|
225
|
+
const reader = res.body?.getReader()
|
|
226
|
+
if (reader == null) throw new Error('llm refine failed: the response carried no stream')
|
|
227
|
+
const decoder = new TextDecoder()
|
|
228
|
+
const splitter = new ThinkSplitter()
|
|
229
|
+
const total: StreamDelta = { content: '', reasoning: '' }
|
|
230
|
+
const emit = (d: StreamDelta): void => {
|
|
231
|
+
if (d.content === '' && d.reasoning === '') return
|
|
232
|
+
total.content += d.content
|
|
233
|
+
total.reasoning += d.reasoning
|
|
234
|
+
p.onDelta(d)
|
|
235
|
+
}
|
|
236
|
+
let buffer = ''
|
|
237
|
+
for (;;) {
|
|
238
|
+
const chunk = await reader.read()
|
|
239
|
+
if (chunk.done) break
|
|
240
|
+
buffer += decoder.decode(chunk.value, { stream: true })
|
|
241
|
+
const split = splitSseBuffer(buffer)
|
|
242
|
+
buffer = split.rest
|
|
243
|
+
for (const event of split.events) {
|
|
244
|
+
const delta = readStreamDelta(event)
|
|
245
|
+
if (delta == null) continue
|
|
246
|
+
// inline <think> is split out of CONTENT; a provider-reported reasoning field rides along
|
|
247
|
+
const parts = splitter.feed(delta.content)
|
|
248
|
+
emit({ content: parts.content, reasoning: parts.reasoning + delta.reasoning })
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
emit(splitter.flush())
|
|
252
|
+
if (total.content.trim() === '') throw new Error('the model returned no prompt text — try another model')
|
|
253
|
+
return total
|
|
254
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
// the panel's loud channel. src/utils/log.ts is node-shaped, and a browser failure that only
|
|
2
|
+
// updates a state field disappears the moment something re-renders: a console line survives,
|
|
3
|
+
// and it is the first thing anyone reads when the ui does something inexplicable.
|
|
4
|
+
export function logWebError(what: string, e: unknown): void {
|
|
5
|
+
console.error(`🔴 [comfy-ts serve] ${what}: ${e instanceof Error ? e.message : String(e)}`)
|
|
6
|
+
}
|