Commit Graph
39 Commits
Author SHA1 Message Date
James VeitchandClaude Sonnet 5 09fe013ff9 fix(tests): update Dockerfile test to expect python:3.13-slim
docker/Dockerfile was bumped from 3.11 to 3.13 in 50076d7 without
updating the assertion, breaking the suite on main. Verified 3.13
compatibility by building the image and booting ComfyUI 0.27.0 in it
(custom node loads, DB migrations run, no errors) before updating the
pinned version the test enforces.

Fixes #20

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YArD9ZjBWKsAvazmS48amA
2026-07-22 20:20:33 +01:00
James VeitchandClaude Sonnet 5 1dcef77a2b fix: keep chat_structured retry's nested seed in sync with the top-level one
beacon-reviewer caught a real gap: when a caller pins options["seed"],
the retry loop set the new seed on ModelSettings' top-level "seed"
field but left the same request's extra_body.options.seed (the
Ollama-native passthrough) at the original pinned value. A backend
that honors the nested field over the top-level OpenAI one would keep
sending the identical effective seed on every retry, silently
defeating this fix for exactly the pinned-seed case it needs to cover.

Now both fields are kept in sync on every retry attempt, built via
fresh copies rather than mutating the caller's options dict in place
(that dict is shared across every attempt, and possibly across other
calls). Added a regression test asserting the caller's options dict is
untouched after a multi-attempt retry.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0132ojafeazQ3ephcBejEWFj
2026-07-20 08:59:06 +01:00
James VeitchandClaude Sonnet 5 09a173e552 fix: retry blank/failed LLM responses with a new seed and backoff
Reported live on a fresh runpod: structured_output extraction on
ChatCompletion would fail with

  RuntimeError: chat_structured: response failed validation against
  schema after 3 attempt(s) ... Last error: Exceeded maximum output
  retries (0)

...but succeed if a plain (non-structured) chat call with the same
prompt was run first. Root cause: pydantic-ai's Agent is built with
retries=0 (comfydv drives its own outer retry loop, not pydantic-ai's
internal one), so a single bad/empty tool-call response instantly
exhausts one attempt. comfydv's own retry loop then retried with the
*exact same request* every time — if the model is genuinely stuck
(e.g. still warming up on a freshly-started backend) or produces a
degenerate response for a given seed, every attempt fails identically.
Confirmed the seed was unset in the reporting user's workflow (Ollama
picks its own per call) and it still failed 3/3 in a row, which rules
out "stuck on one bad seed" and points at request-level determinism
plus zero backoff between attempts as the real gap.

Plain chat() had zero retry/validation logic at all before this change
— it silently returned whatever content came back, even blank. Given
the underlying failure mode (a fresh model's first response sometimes
being blank) is identical for both chat modes, this fix applies to
both, not just structured output.

Adds src/comfydv/_llm/retry.py: next_seed() (deterministic, starting
from any user-pinned options["seed"], incrementing per retry — attempt
1 is always the caller's original, untouched request) and
RETRY_BACKOFF_SECS (a flat delay between retries, giving a still-
loading model time to finish rather than hammering it with identical
requests back-to-back).

Both OllamaProvider.chat() and LlamaCppProvider.chat() now retry (per
the node's existing max_retries widget) when a response comes back
blank, injecting the incremented seed each retry — Ollama via the
native options.seed field, llama.cpp via the OpenAI spec's top-level
"seed" field (nesting it under "options" like the rest of the
Ollama-native passthrough would silently not work — llama-server's
OpenAI-compatible endpoint doesn't read seed from there, a pre-existing,
documented non-goal for general options passthrough that doesn't apply
to this internal retry mechanism). Neither raises if every retry stays
blank — matches chat()'s existing never-validates contract.

chat_structured() in _llm/chat.py now injects the same incrementing
seed via pydantic-ai's ModelSettings["seed"] (which correctly maps to
the OpenAI API's top-level seed param for both backends) and adds the
same backoff between attempts, on top of its existing validation-retry
loop.

Live-verified against real Ollama: the happy path (model responds
normally first try) still makes exactly one network call for chat()
and completes chat_structured() normally — no regression from the new
retry scaffolding. The specific cold/stuck-model failure itself is
runpod-cold-start-dependent and wasn't independently reproducible in
this session's environment (a second live attempt succeeded on the
very first try) — unit tests directly exercise the retry/seed/backoff
logic instead (test_llm_retry.py, and new cases in
test_ollama_provider.py, test_llamacpp_provider.py, and
test_llm_chat_structured.py), verified against both providers.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0132ojafeazQ3ephcBejEWFj
2026-07-20 08:49:35 +01:00
James VeitchandClaude Sonnet 5 1fe3bef663 docs(tests): stop overclaiming what the _run_async regression tests prove
beacon-reviewer caught it: reconstructing the old buggy _run_async and
running it against test_run_async_works_when_called_from_within_a_running_loop
and test_run_async_propagates_exceptions_from_within_a_running_loop shows
both pass against the old code too. asyncio.get_running_loop() never
spuriously raises under plain CPython/pytest, so the old conditional also
takes the safe worker-thread branch there — the actual reported bug is not
reproducible outside real ComfyUI's execution engine, and only the live
end-to-end run against it proved the fix.

Corrects the block comment to say what the tests actually do: lock in the
documented contract so a regression to a no-thread asyncio.run(coro) call
is caught immediately, without claiming they reproduce the specific
environment-dependent failure.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0132ojafeazQ3ephcBejEWFj
2026-07-12 09:39:55 +01:00
James VeitchandClaude Sonnet 5 3bd857f0ab fix: chat_structured() crashes with real asyncio.run() error in live ComfyUI
Found by running a genuine end-to-end test — real docker-compose
ComfyUI harness, real Ollama, real llama-server (router mode),
actual workflow graphs submitted via POST /prompt and polled via
/history, not direct Python calls to provider classes. Every
structured_output=True ChatCompletion call failed with:

  RuntimeError: asyncio.run() cannot be called from a running event loop

Root cause: _run_async() tried asyncio.get_running_loop() first and
only spun up an isolated worker thread if that succeeded; otherwise
it called asyncio.run(coro) directly on the current thread. Under
pytest or a standalone script, get_running_loop() never spuriously
raises, so this worked and the worker-thread path was rarely
exercised for real. Under ComfyUI's actual async execution engine
(Python 3.13, node functions invoked synchronously from inside an
already-running event loop), get_running_loop() sometimes raised
anyway — routing straight into asyncio.run(coro) on the one thread
guaranteed to already have a loop running, reproducing the crash
every time. Confirmed via a live-instrumented debug run against the
real container: the coroutine executed correctly whenever the
worker-thread path was taken (get_running_loop() succeeding), and
crashed only via the direct-call fallback.

Fixed by removing the conditional entirely: always run the coroutine
in a freshly spawned worker thread. A new thread never has an
ambient loop, so asyncio.run() is safe there unconditionally,
regardless of what the calling thread's loop state actually is.

Also traced down a second symptom from the same end-to-end run:
non-structured chat() calls sometimes returned an empty response
with no error. Verified via direct curl calls to Ollama and
llama-server (bypassing comfydv entirely) that this was a real,
transient GPU/Metal memory-pressure issue on the test machine
(`ggml_metal_synchronize: error: Insufficient Memory`, Ollama's own
backend left in a wedged state returning HTTP 200 with an empty
zero-value body) — not a comfydv bug. Restarting the backend
processes resolved it; no code change was needed for that part.

Added tests/test_ollama_provider.py coverage for the specific shape
that broke: _run_async called synchronously from within code that is
itself already executing inside asyncio.run() — the actual pattern
ComfyUI's execution engine uses, which no prior test exercised (every
existing call site invoked _run_async from a plain synchronous pytest
function with no ambient loop).

Re-verified end-to-end after the fix: 5/5 real workflows passing
through actual ComfyUI execution — Ollama basic chat, Ollama full
lifecycle (Load->Chat->Unload), Ollama structured output, llama.cpp
basic chat, llama.cpp structured output — all with real generated
content, not mocks.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0132ojafeazQ3ephcBejEWFj
2026-07-12 09:36:21 +01:00
James VeitchandClaude Sonnet 5 16b7e944f0 fix(tests): make the import-compat proof order-independent
beacon-reviewer caught a real gap: tests/test_comfyui_import_compat.py
ERRORed (not passed) when run in isolation or under a file-sharded
runner — the autouse _clear_ollama_caches fixture from conftest.py
does `from comfydv._llm.ollama_provider import ...`, and this file
was the one case where nothing had already bound `comfydv` in
sys.modules correctly first, so it resolved to the wrong package.
Only the full single-process suite happened to be green.

Fixed by shadowing that fixture with a local no-op override scoped
to this module: these tests exercise package import resolution
itself, not OllamaProvider/ChatCompletion state, so there is nothing
for the original fixture to reset here — and depending on it made
the test order-dependent on an unrelated file's import order, which
is exactly the kind of fragility this file exists to guard against.
Verified: passes standalone (`pytest tests/test_comfyui_import_compat.py`)
and as part of the full suite.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0132ojafeazQ3ephcBejEWFj
2026-07-11 18:02:57 +01:00
James VeitchandClaude Sonnet 5 1e9a8a3b6a fix: comfydv failed to load in real ComfyUI since PR #17 (critical)
Every internal `from comfydv._llm.X import Y`-style absolute
self-import broke the entire plugin the moment ComfyUI actually
loaded it — every node, not just the LLM ones, since the whole
src/comfydv/__init__.py chain aborted on the first such import.

ComfyUI's custom_nodes loader imports this plugin via a *relative*
chain (repo-root __init__.py does `from .src.comfydv import ...`),
nesting comfydv under whatever top-level name the folder gets —
never `comfydv` itself. An absolute `from comfydv...` self-import
only resolves if `src/` has separately been placed on sys.path,
which conftest.py does for every test — masking this completely.
No test ever exercised the real loading shape.

Confirmed via git bisection against the actual docker-compose dev
harness (built and ran real ComfyUI): this predates spec 008
entirely — checking out the commit right after PR #17 merged,
before llamacpp.py existed, reproduces the identical failure at
ollama.py's own absolute import. Fixed by converting every internal
self-import across src/comfydv/ to a relative import, which resolves
correctly under both loading shapes. Verified fixed by rebuilding
the harness and confirming all 21 nodes register via /object_info.

Added tests/test_comfyui_import_compat.py: a subprocess-based test
reproducing ComfyUI's exact nested-relative-import shape (not
conftest.py's sys.path-patched shape), plus a static AST guard
against any future absolute self-import creeping back in.

Also fixed, found via the same live-harness investigation:
- src/js/ollama.js matched on pre-rename node names
  (OllamaModelSelector/OllamaLoadModel/OllamaChatCompletion), so the
  "Refresh models" button and live structured-output socket preview
  were silently absent from every node in the real UI.
- The /dv/ollama/models route always spoke Ollama's wire protocol
  regardless of which backend was actually connected — pointing it
  at a llama.cpp host could never populate real models. Route now
  takes a `backend` param; getHostAndBackendFromNode() in ollama.js
  determines it from the connected client node's registered type;
  LlamaCppProvider gained a matching _fetch_models() name-only view
  (mirrors OllamaProvider's, same graceful-degradation contract).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0132ojafeazQ3ephcBejEWFj
2026-07-11 17:48:20 +01:00
James VeitchandClaude Sonnet 5 15bb25efa8 test(llamacpp): live-verify chat_structured(), strengthen idempotency tests
Ran a second live smoke test — load_model() then chat_structured()
with a real pydantic.BaseModel schema — against the same router-mode
llama-server used for the earlier fix. Confirmed pydantic-ai's
Agent/OpenAIProvider mechanism works against llama-server's
OpenAI-compatible endpoint, not just Ollama's (the only one verified
live in the prerequisite epic). No gap found; every LlamaCppProvider
method has now been exercised against a real server, not just mocks.

Also strengthened the two idempotency regression tests added in the
previous commit: they previously asserted only "does not raise", which
would also pass if the method silently no-op'd for an unrelated bug.
Now assert the mocked _post_json was actually called with the expected
request, so the test verifies real behavior, not just absence of a
crash.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0132ojafeazQ3ephcBejEWFj
2026-07-11 16:24:52 +01:00
James VeitchandClaude Sonnet 5 282198a7df fix(llamacpp): make load_model/unload_model actually idempotent
Ran the live smoke test (T017) that had been wrongly marked deferred
for "no llama-server reachable" — llama-server was installed via
Homebrew the whole time and a router-mode server was launched against
a real local GGUF model to verify.

This caught a real gap the mocked suite couldn't: router mode's
/models/load and /models/unload are NOT idempotent at the wire level.
Calling load on an already-loaded model returns HTTP 400 "model is
already running" (and unload/"model is not running" symmetrically),
not the {"success": true} the conformance contract assumed without
live verification. LlamaCppProvider now absorbs exactly those two
error messages as the desired end-state already reached; any other
error still propagates. Contract doc corrected to describe the real
behavior; regression tests added (mocked, run in CI).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0132ojafeazQ3ephcBejEWFj
2026-07-11 16:10:51 +01:00
James VeitchandClaude Sonnet 5 cf3f7fc174 fix(llamacpp): surface a clear error for non-router-mode servers (FR-006)
LlamaCppProvider.list_models() caught every exception and returned [],
indistinguishable from "no models installed". Fixed _get_json to raise
on HTTP error status (matching _post_json's existing behavior — its
docstring already claimed this), and list_models() to distinguish
OSError (genuinely unreachable, degrades to []) from RuntimeError
(server responded with an error — surfaced with a router-mode hint).

Found by beacon-reviewer ahead of PR open.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0132ojafeazQ3ephcBejEWFj
2026-07-11 15:43:12 +01:00
James VeitchandClaude Sonnet 5 5af502d07e feat(llamacpp): add LlamaCppProvider + LlamaCppClient node (spec 008)
Second LLMProvider (ADR-007), backed by llama-server's router mode. Only
one new ComfyUI node — LlamaCppClient, emitting the same LLM_CLIENT socket
Ollama Client does. ChatCompletion, LLMModelSelector, LLMLoadModel,
LLMUnloadModel work unmodified once wired to it — the actual proof the
provider abstraction generalizes, not just Ollama-shaped in practice.

API shape verified live against ggml-org/llama.cpp's tools/server/README.md
(research.md) rather than assumed: model identifier field is "id" (not
"name"), status is a nested {"value": "..."} object. list_models() needs
no normalization — llama.cpp's status vocabulary is exactly ModelStatus's
full set, unlike Ollama's narrower one.

38 new tests (test_llamacpp_provider.py, test_llamacpp.py), including a
dedicated US4 test proving no generic node branches on provider type —
the same call sequence succeeds against an Ollama-shaped or llama.cpp-
shaped fake provider.

README/docs updated for the new node this time, not left stale.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0132ojafeazQ3ephcBejEWFj
2026-07-11 15:27:29 +01:00
James VeitchandClaude Sonnet 5 8e227790a9 fix(llm): forward options through to structured output (beacon-reviewer finding)
chat_structured() silently dropped the options dict (temperature, seed,
num_predict, repeat_penalty, etc. — set via the OllamaOption* nodes) in
structured_output mode: OllamaProvider.chat_structured() only used it for
the cache key, and the shared comfydv._llm.chat.chat_structured() helper
had no options parameter at all. On main, the hand-rolled implementation
sent options verbatim in the request body; this migration silently lost it,
contradicting FR-008 (structured-output behavior must be unchanged).

Fixed by forwarding options as pydantic-ai's model_settings.extra_body,
matching the original payload shape exactly rather than lossily remapping
onto ModelSettings' own standardized field names (which don't cover
Ollama-native params like num_predict/repeat_penalty/top_k anyway).

Verified against the live local Ollama server: structured output with
temperature=0.0/seed=42 succeeds on first attempt.

Caught by an independent beacon-reviewer pass on the diff before opening a
PR — exactly what that review step is for.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0132ojafeazQ3ephcBejEWFj
2026-07-11 14:35:51 +01:00
James VeitchandClaude Sonnet 5 1879ca2265 test(llm): complete atomic node cutover — test_ollama.py rewrite (T-CUT-08/10/12)
Rewrote tests/test_ollama.py against a _FakeProvider double per
atomic-cutover-plan.md's D4/D5 test-layer split: node-contract/delegation
tests only, no aiohttp/_post_json mocking (that lives in
test_ollama_provider.py now). 98 unit tests, collapsed from the original
~125 largely mechanical monkeypatch-per-scenario tests where the retry/
validation coverage they duplicated already lives in
test_llm_chat_structured.py.

Fixed a real gap the rename surfaced along the way: comfy-manager-entry.json
(ComfyUI Manager registry listing) still had the old Ollama-specific
display names — updated it and its matching test expectation.

Full validation (T-CUT-10): 218 tests green (only the pre-existing,
unrelated Dockerfile-python-version test fails); ruff/ty clean (confirmed
via git stash comparison that the remaining ty diagnostics pre-date this
work); beacon doctor --strict shows only already-disclosed items.

Manual smoke test (T-CUT-12): Ollama was reachable in this environment, so
ran the real integration suite rather than a walkthrough. 6/8 passed
including the critical paths (real load/unload, real structured-output
retry-then-raise, real error handling). 2 failures traced via direct curl
to Ollama's /api/chat (bypassing this codebase) to a pre-existing,
ADR-006-documented unreliability in the specific test model, not a
regression.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0132ojafeazQ3ephcBejEWFj
2026-07-11 14:28:34 +01:00
James VeitchandClaude Sonnet 5 d90ae98fed feat(llm): atomic node cutover — generic ChatCompletion/LLM* nodes (T-CUT-01/04-07/11)
OllamaClient now emits an OllamaProvider via the generic LLM_CLIENT socket
(was OllamaClientType/OLLAMA_CLIENT). OllamaChatCompletion, OllamaModelSelector,
OllamaLoadModel, OllamaUnloadModel renamed to ChatCompletion, LLMModelSelector,
LLMLoadModel, LLMUnloadModel — all delegate to client.* (LLMProvider protocol)
instead of building Ollama URLs/payloads inline. Structured output now goes
through client.chat_structured() (pydantic-ai), not hand-rolled tool-calling.

ollama.py's own duplicate HTTP/cache infra (_post_json, _TTLLRUCache,
_MODEL_LIST_CACHE, _CHAT_RESPONSE_CACHE) is gone — single source of truth in
comfydv._llm.ollama_provider (plan D1); the combo-widget path
(_load_default_models, /dv/ollama/models) imports _fetch_models/_run_async
from there instead of duplicating them. _client_headers deleted (dead code
once nodes delegate to client.*).

Added MIGRATION_MAP (old->new node/socket names, FR-009). NODE_CLASS_MAPPINGS
keys changed to match (breaking rename, confirmed acceptable per ADR-007).

conftest.py's autouse cache-clearing fixture repointed to the single cache
source and ChatCompletion (plan D8).

tests/test_ollama.py itself is NOT yet updated (T-CUT-08, next commit) — it
will fail to collect until then; this is the expected atomic-cutover
intermediate state, not a regression to fix independently.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0132ojafeazQ3ephcBejEWFj
2026-07-11 14:19:07 +01:00
James VeitchandClaude Sonnet 5 fb111c0142 feat(llm): implement OllamaProvider method bodies (T-CUT-02/03)
list_models()/load_model()/unload_model()/chat()/chat_structured() —
behavior-preserving ports of the existing inline ollama.py logic, plus one
genuinely new capability: list_models() also queries /api/ps to report
real loaded/unloaded status (the old OllamaModelSelector only ever showed
names via /api/tags, never live status).

15 new tests in tests/test_ollama_provider.py, mocking at the module's own
_post_json/_get_json seam per atomic-cutover-plan.md's D4 test-layer split.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0132ojafeazQ3ephcBejEWFj
2026-07-11 14:14:51 +01:00
James VeitchandClaude Sonnet 5 736ffd1e77 feat(llm): shared chat_structured() via pydantic-ai (T011-T013)
Provider-layer only — src/comfydv/_llm/chat.py doesn't touch ollama.py, so
it's safe to land ahead of the deferred atomic node cutover (issue #16).
Ports ADR-006's exact retry/validation contract: bounded retries (0-5,
clamped), RuntimeError naming model/attempt-count/truncated-last-response
on exhaustion. Agent's own internal retries disabled so the error contract
is comfydv's, not pydantic-ai's.

Required an API-discovery spike (Agent/OpenAIProvider/OpenAIChatModel
constructors and exception surface aren't reliably knowable from training
data for a fast-moving library) before tests could be written meaningfully
— tests and implementation were validated together rather than strictly
red-first; noted in tasks.md rather than presented as pure TDD.

Also fixes a pre-existing gap in test_packaging.py's requirements.txt/
pyproject.toml consistency check: it stripped `[extras]` on one side of the
comparison but not the other, which this change's pydantic-ai-slim[openai]
entry exposed as the first dependency with an extras marker.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0132ojafeazQ3ephcBejEWFj
2026-07-11 13:37:16 +01:00
James VeitchandClaude Sonnet 5 9d90f39854 feat(llm): scaffold LLMProvider protocol and OllamaProvider (T001-T006)
Adds pydantic-ai-slim[openai] per ADR-007, the Message/ModelStatus/
ModelInfo/LLMProvider protocol, and an OllamaProvider skeleton carrying
host/headers as instance state — ported _post_json/_fetch_models/_run_async/
_TTLLRUCache infra from comfydv.ollama unchanged. Method bodies land per
user story in specs/007-llm-provider-abstraction/tasks.md.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0132ojafeazQ3ephcBejEWFj
2026-07-11 13:25:47 +01:00
James VeitchandClaude Sonnet 5 253569d483 feat(ollama): live dynamic output sockets for structured_output
Adds a POST /dv/ollama/update_structured_outputs route and a matching JS
extension so editing structured_output/output_schema on
OllamaChatCompletion updates the node's output sockets immediately in the
UI — one per schema property — mirroring FormatString's existing live
dynamic-output pattern. No need to run the graph first to see the extracted
fields appear. Invalid/incomplete JSON while typing falls back to the base
3-output shape rather than erroring the request.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-09 17:37:41 +01:00
James VeitchandClaude Sonnet 5 40e851588d feat(ollama): opt-in structured output via tool-calling + pydantic validation
Adds structured_output/output_schema/max_retries inputs to
OllamaChatCompletion, fixing three real reliability problems: models
prepending commentary, wrapping responses in code fences, and occasionally
returning blank output. When enabled, requests go through Ollama's
OpenAI-compatible tool-calling endpoint (a single forced tool call matching
output_schema) instead of native /api/chat, and each response is validated
against a dynamically-built pydantic model — invalid/blank responses retry
with fresh network calls, exhausting into a clear RuntimeError rather than
silently passing bad data downstream. One additional ComfyUI output socket
is exposed per schema property, mirroring FormatString's existing
dynamic-output pattern. Fully backward compatible: structured_output
defaults off and non-structured behavior is untouched.

Ollama's native /api/chat "format" field (JSON-Schema-constrained decoding)
was tried first but proved unreliable against a real local model during
implementation — see ADR-006 for the full investigation and why
tool-calling was chosen over both native format and pydantic-ai (the latter
would reintroduce httpx/openai-sdk, reversing ADR-004).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-09 12:50:54 +01:00
James VeitchandClaude Sonnet 5 eef0f1ff59 feat(format-string): inline read-only display of formatted_string
FormatString is now OUTPUT_NODE=True and returns {"ui": {"text": [...]},
"result": (...)} instead of a bare tuple, so the rendered output shows
directly on the node — no separate Show Text node needed to inspect it.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-04 13:43:37 +01:00
James VeitchandClaude Sonnet 5 fcb95fadfa feat(ollama): per-client auth headers and local response caching
Adds an OLLAMA_HEADERS socket type (Basic Auth, Bearer Token, Custom) that
composes onto OllamaClient, so requests to a proxied/authenticated Ollama
server carry the right Authorization header through model discovery,
load/unload, and chat.

Also adds a bounded local cache: a short-TTL LRU for model discovery
(avoids duplicate /api/tags round-trips from repeated node creation/refresh)
and an unbounded-TTL LRU for chat responses, keyed on the full request
signature — needed because OllamaChatCompletion is OUTPUT_NODE=True and so
is re-executed by ComfyUI on every queue run even when nothing changed.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-04 13:43:28 +01:00
James VeitchandClaude Sonnet 4.6 4c64e2b6da feat(chat): I-commit — model→STRING, OLLAMA_HOST docker support, dynamic test fixtures
- OllamaChatCompletion.model changed from COMBO to plain STRING so it can
  receive a wired value from OllamaLoadModel without a separate model_name
  socket (removes dual-input UX confusion and COMBO validation errors)
- Removed model_name optional input — model STRING is the single entry point
- _load_default_models() tries OLLAMA_HOST env var → host.docker.internal →
  localhost so COMBO nodes pre-populate on server start inside Docker
- docker-compose.dev.yml: OLLAMA_HOST=http://host.docker.internal:11434 so
  model dropdowns are populated at startup without a manual Refresh click
- JS: refreshModelWidget handles both COMBO and STRING widget types; keeps
  user-typed/wired value when it is already a known model
- Tests: first_generative_model fixture dynamically selects the first
  installed model instead of hardcoding embeddinggemma:latest (which is an
  embedding-only model that rejects /api/generate with HTTP 400)
- Tests: test_multi_turn_receives_context passes think=False to prevent
  Qwen3 thinking-mode models from returning empty content fields
- Screenshots retaken: ollama_chat.png, ollama_lifecycle.png, ollama_workflow.png

All 80 unit + 9 integration tests pass.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RWysE6jYn4YjNorLBQ1cXb
2026-06-29 12:49:53 +01:00
James VeitchandClaude Sonnet 4.6 da88e4cdaf test(chat): T-commit — model must be STRING, model_name input removed
2 failing tests:
- test_chat_completion_model_is_plain_string: model must be STRING not COMBO
- test_chat_has_no_model_name_input: redundant optional input removed

Removed test_wired_model_name_overrides_combo (behaviour going away).
Added test_chat_model_receives_wired_string (STRING wiring works directly).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RWysE6jYn4YjNorLBQ1cXb
2026-06-29 12:32:01 +01:00
James VeitchandClaude Sonnet 4.6 1377c9fbe6 feat(chat): I-commit — inline response display via OUTPUT_NODE
OllamaChatCompletion now sets OUTPUT_NODE = True and returns
{"ui": {"text": [...]}, "result": (...)} so ComfyUI renders the
response text directly in the node body after each run.

On first turn, the full response is displayed.
On subsequent turns, the response is shown with a compact history
summary (last 6 messages, 100-char snippets) so multi-turn context
is visible at a glance without a separate display node.

_history_preview() helper added for the summary rendering.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RWysE6jYn4YjNorLBQ1cXb
2026-06-29 09:50:09 +01:00
James VeitchandClaude Sonnet 4.6 ca4c322b9d test(chat): T-commit — inline display (OUTPUT_NODE + dict return)
5 failing unit tests:
- test_chat_is_output_node
- test_chat_returns_ui_result_dict
- test_chat_ui_contains_response_text
- test_chat_result_is_3_tuple
- test_wired_model_name_overrides_combo (updated to unpack from ["result"])

Integration tests updated to unpack from ["result"] for API consistency.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RWysE6jYn4YjNorLBQ1cXb
2026-06-29 09:49:29 +01:00
James VeitchandClaude Sonnet 4.6 5ccd569f63 chore: ruff format pass — no logic changes
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RWysE6jYn4YjNorLBQ1cXb
2026-06-29 01:34:54 +01:00
James VeitchandClaude Sonnet 4.6 c80e488b49 test(ollama): T-commit — failing tests for all 6 correctness issues
9 new tests cover:
- _run_async: event-loop safety when called from a running loop
- _post_json: raises RuntimeError on 4xx/5xx; timeout kwarg forwarded
- LoadModel/UnloadModel: must use /api/generate, keep_alive must be int
- ChatCompletion: must expose timeout_secs widget and forward it

58 pre-existing unit tests remain green. Integration tests excluded.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RWysE6jYn4YjNorLBQ1cXb
2026-06-29 01:32:49 +01:00
James VeitchandClaude Sonnet 4.6 eca1517b65 fix(ollama): OllamaUnloadModel pass-through + OllamaChatCompletion model_name output
OllamaUnloadModel now works as a pass-through node: wire
OllamaChatCompletion.response into the optional `passthrough` input and
OllamaChatCompletion.model_name into `model` — ComfyUI's data-flow graph
then guarantees Load → Chat → Unload execution order.

OllamaChatCompletion gains an optional `model_name` forceInput so
OllamaLoadModel.model_name can wire in (creating Load → Chat ordering) and
overrides the COMBO dropdown. It also returns `model_name` as a 3rd output
so the model can flow downstream to UnloadModel without duplication.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RWysE6jYn4YjNorLBQ1cXb
2026-06-29 01:16:30 +01:00
James VeitchandClaude Sonnet 4.6 f3574c0202 feat(006): Ollama model integration — 14 nodes for LLM inference in ComfyUI workflows (#8)
* fix: eliminate all identified broken windows before Ollama implementation

- pyproject.toml: add requires-python>=3.11, real description, remove dead
  [project.scripts] entry (no main() exists), add system/integration markers
- __init__.py: replace pytest-in-sys.modules guard with comfy-in-sys.modules
  (checks the actual condition; cleaner semantics)
- tests/conftest.py: remove duplicate module-level class definitions and the
  aiohttp mock (real aiohttp is installed; mock blocked integration tests)
- circuit_breaker.py: remove copy-pasted INPUT_TYPES boilerplate docstring;
  logger.debug → logger.warning for ComfyUI-absent branch (degraded state)
- random_choice.py: remove copy-pasted INPUT_TYPES boilerplate and dead
  triple-quoted string literal; fix bare re-raise to log before propagating
- format_string.py: print() → logger.warning(); remove # type: ignore on
  two dict assignments; remove cargo-culted # noqa: F401 (ruff doesn't flag)
- scripts/take_screenshots.py: remove unused h_pad and v_pad parameters

All 76 tests pass; ruff clean.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RWysE6jYn4YjNorLBQ1cXb

* design(006): full DESIGN phase artefacts for Ollama model integration

Adds spec, plan, tasks, 6 BDD feature files, ADRs, and epic file for
spec 006-ollama-model-integration (14 nodes ported from
darth-veitcher/comfyui-ollama-model-manager, Issue #1 fix, logging
harmonisation, live-service integration tests).

- specs/006-ollama-model-integration/{spec,plan,tasks}.md
- specs/006-ollama-model-integration/features/us{1-6}_*.feature
- specs/006-ollama-model-integration/{.beacon.toml,checklists/}
- project-management/ADRs/ADR-004-aiohttp-over-httpx-for-ollama.md
- project-management/ADRs/ADR-005-ollama-host-config-via-client-node.md
- project-management/Roadmap/epics/ollama-integration.md

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RWysE6jYn4YjNorLBQ1cXb

* chore(006): Phase 1 setup — Ollama fixtures, Justfile recipes, test skeleton

- conftest.py: add ollama_host (session), ollama_available (session),
  skip_if_no_ollama fixtures for @pytest.mark.integration tests
- Justfile: add test, test-unit, test-integration, test-system recipes
- tests/test_ollama.py: empty skeleton with module docstring and lazy-import
  block (uncommented phase-by-phase as ollama.py is built)

Closes T001 (system marker — done in broken-windows commit), T002, T003, T004.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RWysE6jYn4YjNorLBQ1cXb

* feat(006): Phase 3 foundational — ollama.py, ollama.js, __init__ wiring (T011-T014)

- src/comfydv/ollama.py: OllamaClientType, _run_async, _fetch_models,
  _post_json, _DEFAULT_MODELS (populated at import), /dv/ollama/models route,
  all 14 node classes (US1-US6) with correct ComfyUI contract
- src/js/ollama.js: app.registerExtension for OllamaModelSelector/LoadModel/
  ChatCompletion — refreshModelDropdown + ⟳ refresh button
- src/comfydv/__init__.py: register all 14 Ollama nodes in
  NODE_CLASS_MAPPINGS and NODE_DISPLAY_NAME_MAPPINGS

Closes T011, T012, T013, T014.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RWysE6jYn4YjNorLBQ1cXb

* test(006): full Ollama test suite — T015-T031 all US TDD-T commits (T-T032)

Add tests/test_ollama.py with 6 test classes covering all 14 nodes:
  - TestUS1OllamaConnection: client type, custom host, unreachable error
  - TestUS2ModelSelection: fetch list, selector output, COMBO type, empty fallback
  - TestUS3ModelLifecycle: COMBO type, empty-model guard, load/unload integration
  - TestUS4ChatCompletion: COMBO type, single-turn, multi-turn, history growth
  - TestUS5ComposableOptions: all 7 option nodes + chaining + deterministic
  - TestUS6HistoryInspection: debug output, length counts
  - TestNodeContracts: parametrised over all 14 nodes for ComfyUI contract

Also remove tests/__init__.py — its presence caused pytest to walk up past the
repo root and add the parent directory to sys.path, making the root-level
__init__.py win the 'comfydv' namespace over src/comfydv/.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RWysE6jYn4YjNorLBQ1cXb

* style: ruff format test_ollama.py

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RWysE6jYn4YjNorLBQ1cXb

* feat(006): T032/T034 — extend packaging tests and manager entry for 14 Ollama nodes

Update EXPECTED_NODENAMES in test_packaging.py to include all 14 Ollama node
display names. Update comfy-manager-entry.json nodename array and description
to register all 14 nodes with ComfyUI Manager.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RWysE6jYn4YjNorLBQ1cXb

* docs(006): T033 — add Ollama section to README and docs/index.md

Add all 14 Ollama nodes to the node reference table and add a dedicated
Ollama section covering minimal workflow, option nodes, and multi-turn
conversation patterns.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RWysE6jYn4YjNorLBQ1cXb

* test(006): T035-T/I — TestLoggingConsistency: no print(), correct log levels

Add TestLoggingConsistency class to tests/test_logging.py:
- AST scan: assert zero print() calls across all src/comfydv/*.py
- circuit_breaker: ComfyUI-absent branch uses logger.warning() not debug
- random_choice: exception path calls logger.error() and uses plain raise
- ollama: absent-ComfyUI paths emit at least 2 logger.warning() calls

All checks pass (fixes were already in Phase 2 broken windows commit).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RWysE6jYn4YjNorLBQ1cXb

* docs: add Quickstart section to README — satisfies beacon doctor readme-completeness

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RWysE6jYn4YjNorLBQ1cXb

* chore(006): mark all 55 tasks complete in tasks.md — spec fully implemented

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RWysE6jYn4YjNorLBQ1cXb

* docs(006): T036/T037 — add Ollama screenshots and docker extra_hosts for host Ollama routing

Captures 4 Ollama node screenshots (client, chat, workflow, options) via
Playwright against the live dev ComfyUI instance. Adds extra_hosts to
docker-compose.dev.yml so the container can reach host-machine Ollama.
Updates README and docs/index.md to embed all 8 screenshots.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RWysE6jYn4YjNorLBQ1cXb

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-29 00:55:15 +01:00
James VeitchandClaude Sonnet 4.6 526b00953d chore(002): archive logging epic, fix roadmap ADR links, add pyyaml dev dep
- Roadmap: move logging-modernisation to Done; fix ADR links (root-relative
  paths corrected from ../../ADRs/ to project-management/ADRs/); add ADR-003
- epics/logging-modernisation.md: emptied after beacon epic finish archive
- uv.lock: updated after `uv add --dev pyyaml` (needed by TestDockerCompose)
- tests/test_packaging.py: ruff line-length formatting only
- scripts/gen_ref_pages.py: trailing blank line (ruff)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RWysE6jYn4YjNorLBQ1cXb
2026-06-28 21:21:16 +01:00
James VeitchandClaude Sonnet 4.6 a3ed53636d fix(lint): remove unused import and fix noqa directive (ruff clean)
Removed unused `import sys` from test_logging.py (left over after
stripping MockInterruptProcessingException). Fixed invalid noqa comment
format on format_string.py:31.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-28 16:29:47 +01:00
James VeitchandClaude Sonnet 4.6 44c57c0356 test(002): failing tests for Docker Compose harness (T040-T, T041-T)
5 tests RED: docker-compose.yml and docker/Dockerfile don't exist yet.
Added pyyaml>=6.0.2 to dev deps for YAML parsing in tests.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-28 16:25:42 +01:00
James VeitchandClaude Sonnet 4.6 75a3efe021 test(002): failing tests for @description accuracy in __init__.py (T030-T)
2 tests RED: @description mentions non-existent 'model memory management'
and omits 'circuit' (CircuitBreaker). One test already passes (no Model
Unloader mention) — correct baseline.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-28 16:24:48 +01:00
James VeitchandClaude Sonnet 4.6 62a0250939 test(002): failing tests for Manager entry JSON (T020-T)
4 tests RED: comfy-manager-entry.json does not exist yet. Tests validate
required fields, install_type=git-clone, and nodename list.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-28 16:24:09 +01:00
James VeitchandClaude Sonnet 4.6 67dff3efef test(002): failing tests for requirements.txt correctness and aiohttp dep (T010-T, T011-T)
5 tests RED as expected: jinja2 missing, colorama/termcolor/bare-dot
still present, aiohttp not in [project.dependencies].

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-28 16:23:21 +01:00
James VeitchandClaude Sonnet 4.6 80ecf9cc39 test(002): scaffold test_packaging.py and BDD feature files (T001, T002)
18 stub tests pass; 4 Gherkin feature files cover US1–US4 acceptance
scenarios verbatim from spec.md. No assertions yet — TDD pairs T010-T
through T041-T will fill these in next.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-28 16:22:49 +01:00
3322f6f05e feat: standardise logging across all comfydv nodes (#5)
* chore: initialise BEACON framework with all bootstrap artefacts

- Problem statement, constitution, architecture doc, roadmap populated
- CHANGELOG.md created (Keep a Changelog); README expanded with
  What-is-this, Install, and Quickstart sections
- pyproject.toml gains [project.urls] (repository + documentation)
- beacon doctor: 32 pass, 2 pre-commit warns, 0 failures

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* chore: Phase 1 — add NullHandler to package root, remove hardcoded setLevel

T001: logging.getLogger("comfydv").addHandler(NullHandler()) in __init__.py
T002: remove logger.setLevel(logging.DEBUG) from format_string.py
Also fix pyproject.toml TOML structure (project.urls was inside [project] block)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* test: failing tests for logging modernisation (T010-T through T030-T)

RED phase — 5 tests fail for the correct reasons before implementation:
T010-T: format_string produces stdout (print block)
T011-T: update_widget emits INFO records on hot path
T012-T: random_choice produces stdout (colorama/rich prints)
T020-T: load_node_state uses print() on error instead of logger.error
T021-T: circuit_breaker uses print() instead of logger

T001/T002/T030-T already green: NullHandler registered, setLevel removed.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat: standardise logging across all nodes (T010-I through T044)

GREEN phase — all 11 logging tests pass:

T010-I: Remove 8-line diagnostic print block from format_string()
T011-I: Downgrade all hot-path logger.info() calls to logger.debug();
        switch all logger calls to %-style formatting; remove rich import
T012-I: Replace colorama/termcolor/rich print calls in random_choice with
        logger.debug(); add logger = logging.getLogger(__name__)
T020-I: Convert print() on load_node_state error to logger.error()
T021-I: Add logger to circuit_breaker; replace print() with logger.debug();
        fix logic so status=False triggers the interrupt (per BDD spec)
T040:   Remove colorama, rich, termcolor from pyproject.toml dependencies
T042:   ruff check + format clean
T044:   beacon doctor --strict passes (34/34)

Also adds ADR-001 and ADR-002 capturing the stdlib logging and NullHandler
decisions, linked from the logging-modernisation epic.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* chore: mark all 001-standardise-logging tasks complete in tasks.md

All [x] checkboxes flipped after 11/11 tests pass and beacon doctor --strict
reports 0 failures.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* chore: mark logging-modernisation epic success criteria complete

All success criteria verified: NullHandler added, setLevel removed, print()
calls converted, colorama/rich/termcolor removed from deps, zero stdout in
normal operation, errors surface at ERROR level, all tests pass.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* chore: commit spec artefacts and dependency lock for 001-standardise-logging

Includes spec.md, plan.md, research.md, BDD feature files, contracts, .beacon.toml
backlink, and uv.lock after removing colorama/rich/termcolor.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: James Veitch <darthveitcher@office-mac-mini.local>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-28 16:00:43 +01:00
darth-veitcher 522b7978e0 progress 2025-11-05 12:54:02 +00:00
darth-veitcher 130c57f88b Add comprehensive pytest test suite and fix FormatString node issues
- Fixed Jinja2 regex pattern to handle spaces around filters ({{ var | filter }})
- Added null safety in IS_CHANGED method for empty/None templates
- Restored dynamic output functionality for variable chaining
- Created 47 comprehensive tests with 78% coverage on format_string.py
- Set up test infrastructure with ComfyUI dependency mocking
- Used importlib to bypass package imports during testing
- Added conditional imports in root __init__.py for test compatibility
- Configured pytest in pyproject.toml (removed outdated pytest.ini)
- Added pytest and pytest-cov to dev dependencies
- Updated .gitignore for test artifacts
- Removed deprecated model_unload.py
2025-11-05 11:59:31 +00:00