Repository navigation
fix(ai): native video handoff to chat-completions providers + preflight video cost - #170920
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs maintainer review before merge. What this changesPreserves video attachments on their owning chat turns, forwards them to explicitly capable Chat Completions providers, and bounds their preflight cost. Example: Send a 1,415,341-byte MP4 to a Chat Completions model configured with input ["text", "image", "video"].
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review This PR fixes a concrete media handoff failure still present on main, resolves both prior findings, and contains useful unique work; exact-head CI admission remains unresolved. Priority: P2 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherInbound attachment facts pass through session message projections into a lazy provider context, which the Chat Completions transport converts into the outbound request. flowchart LR
A[Inbound video attachment] --> B[Exact message media facts]
B --> C[Session message projections]
C --> D[Provider context materialization]
D --> E[Chat Completions conversion]
E --> F[Bounded preflight estimate]
F --> G[Configured provider endpoint]
Technical reviewBest possible solution: Land the focused handoff repair after the existing CI admission workflow resolves the red gate. Do we have a high-confidence way to reproduce the issue? Current-main source exposes the missing handoff and dropped runtime facts, consistent with the recorded baseline Gateway captures; this review ran no target code. Is this the best way to solve the issue? The repair addresses the producer and transport boundaries, removes reinjection machinery, and preserves the approved provider-only video contract. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 51042e8c1a27. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +38, Tests +391, Docs +1, Config +1, Other +1. Total +432 across 31 files. Added test files: 2. View PR surface stats
Review metrics
LabelsLabel changes:
Label justifications:
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (7 earlier review cycles)
Reviewed October 16, 2026, 5:47 AM ET / 09:47 UTC (Revision 8). |
3de16ab to
094ca4f
Compare
|
Rebased and review fixes landed. Head is now 1. Rebase. Rebased onto current 2. Current-turn fact injection — canonical provenance. Active-turn detection in the media projection now uses the shared 3. No stale re-injection. 4. Model registry contract — provider-only boundary adopted. The canonical widening is reverted: 5. Test evidence. Targeted suites: 9 files / 133 tests, all passing — 6. End-to-end recorded proof (serialized outbound request body for a real video turn against a live OpenAI-compatible endpoint) will be posted separately in this thread once our staging build replays it. |
|
Recorded end-to-end behavior proof (live gateway → llama.cpp endpoint). Setup: OpenClaw dev install on Windows against a local llama.cpp server ( 1. Endpoint reference-shape proof. A direct 2. Pre-fix gateway capture (the bug, live). Diagnostic build, real Telegram video turn (clip IMG_6046, runId The canonical 3. Post-fix end-to-end pass (blind). With this PR's fix in the dev install (flag on; builds The model produced an accurate cold description of the blind clip (3D-printed phone stand with two tabs + center cable notch → BF4-skinned wired mouse → full-size Corsair keyboard, RGB blue/pink/green, ending on the G1–G6 macro column), matching ground truth that was sealed to a file before the description was generated. Caveats, stated plainly: the per-turn probe counters above came from transient instrumentation in the dev install (since stripped); no verbatim A fresh live capture against the final head can be arranged on request (re-instrument + rebuild + a new clip). |
7c24da4 to
b41c661
Compare
CI red on
|
b41c661 to
902ca04
Compare
Head updated: rebased onto current
|
Only remaining red:
|
902ca04 to
141338c
Compare
|
Head updated again: rebased onto current This main carries the CI timeout rework (Android test shards now get 24–25 min budgets), so the |
The lint red on this revision is an upstream-main regression (
|
Remaining reds on this revision are repo-wide, not from this PRAll three failures reproduce identically on unrelated PRs / plain
Nothing in this PR's diff ( |
2e121ad to
d84565f
Compare
Behavior-proof addendum: mapping the recorded proof to current head
|
Merge main and carry existing media facts through runtime projections. Resolve one provider context per stream call, keep declared video in the typed Completions projection, and bound video preflight independently of base64 size. Co-authored-by: evomach <[email protected]>
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
Merged via explicitly authorized admin squash with attributed pre-existing CI failures.
|
* commit 'ac03ca0b6d26a7dc55d0d262e40d2549631b1ea7': (25 commits) fix: apply shared plugin model policy to decisions (#156621) perf: shortlist transcript relevance scores before metadata reads (#174058) fix: strip standalone trailing NO_REPLY from replies (#171990) fix(ci): avoid repeated discovery during changed-test planning (#174069) fix(sqlite): preserve transaction outcomes when warnings throw (#157151) fix(ai): native video handoff to chat-completions providers + preflight video cost (#170920) fix(litellm): image generation fails when the backend returns image URLs (#173508) test(memory,gateway,infra,subagents): remove low-value tests (batch d152) (#174034) perf(memory): bound derived worker snapshot and pricing retention (#174067) fix(test): reduce eager imports during test startup (#174056) refactor(codex): share lifecycle preflight fixtures (#174062) test(gateway,matrix,agents,ui): remove low-value tests (batch d150) (#174025) perf(infra): batch usage refresh maintenance (#174050) fix(gateway): revert cold session list worker regression (#174052) refactor(config): consolidate browser meeting configuration (#173947) fix(cron): keep global-session deliveries on the selected agent (#173855) test(compaction): assert structured stale-writer failure (#174064) fix(cli): local terminal chat sends model requests without the configured proxy (#173530) test(ui): restore bootstrap preference locale after each case (#174065) fix: download session files through the development proxy (#173973) ...
…ht video cost (openclaw#170920) * fix(media-understanding): hand video to native vision models * fix(media-understanding): trust configured native video models * fix(ai): materialize provider context for completions transports OpenAI Completions ignored provider context handoff, so native video materialization never reached llm-local payloads. The handoff is now memoized and resolved by the transport before request construction. * fix(agents): install provider context for boundary transports * fix(ai): estimate video parts as fixed cost in completions preflight The proxy-like context guard JSON-stringified video_url parts, counting their base64 data URIs as text (~480k estimated tokens for a 1 MB clip) and rejecting the request before it reached the server, which bills the same clip as ~4k frame tokens. Mirrors the existing image_url fixed estimate. Regression test: a 1.05 MB clip passes the guard on a 64k-token context. * fix(agents): resolve provider-context handoff through @openclaw/ai package specifier Relative imports of packages/ai/src/provider-types.js made tsdown bundle a second copy of the module into the unified dist, so PROVIDER_CONTEXT_HANDOFF (a unique symbol) existed twice: the embedded wrapper set the copy bundled as llm-*.mjs while the completions transport imported the copy from packages/ai/dist. options[HANDOFF] was therefore always undefined in the transport, the handoff was never consumed, and the prune-time 'video omitted' marker survived into provider payloads. Import the published subpath so both sides share one symbol instance. * fix(agents): rehydrate non-canonical user media facts at provider materialization Freshly drained/queued runtime user turns can reach model context with facts only in top-level media fields; transcript append canonicalizes the DB copy but the in-memory copy stayed unprojected, so active-turn video (and any legacy-shaped media) was omitted while later history replays resolved fine. Fall back to canonicalizePersistedUserMessageMedia when neither runtime symbols nor __openclaw carry facts, and trace unprojected media under OPENCLAW_DEBUG_VIDEO_HANDOFF=1. Pinned by replay tests (top-level media fact and bake-then-rematerialize round trip). * fix(agents): carry non-enumerable runtime media facts across LLM boundary copies The probe round proved the provider pass sees a different active-user copy than hydration: normalizeMessagesForLlmBoundary re-projects user messages (runtime-context escape, timestamp stamping, blocked-metadata strip) with Object.assign/spread, which drops the non-enumerable symbol fact carriers, and inserts the runtime-context carrier so the active index shifts. The active turn's video therefore reached provider materialization with zero fact channels while history copies (enumerable __openclaw) survived. Re-attach runtime facts on every boundary projection; pinned by attempt-llm-boundary.runtime-facts.test.ts (fails without the fix). * fix(agents): inject current-turn media facts into provider transcript copies Census round proved provider-pass user rows are session-layer rebuilds with zero fact carriers (runtime symbols stripped, __openclaw absent), so the active turn's video could never materialize in its own turn regardless of hydration. The run now stashes canonical facts from onUserMessagePersisted/Suppressed on attempt.currentTurnMediaFacts and materializeProviderContext re-injects them onto the active user row when no channel resolves. activeUserIndex also skips runtime-context wrapper rows (fixes 336->337 shift). Two regression tests in images.replay.test.ts. * fix(tsconfig): map @openclaw/ai/provider-types so worker-graph tests build * fix(media): skip runtime prompt symbol tags on frozen hydrated message copies * fix(models): preserve declared video input modality through model resolution resolveProviderModelInput and the sessions model-registry filtered configured input lists to text|image, so a model declaring input:[text,image,video] reached the openai-completions transport without video. provider-transcript-transform then evaluated supportsVideo=false and replaced the active video block with the '(video omitted: provider does not support video input)' placeholder - canonical=1/converted=0 in the probe. Widen llm-core Model.input to include video, keep video in both resolvers, regression test for inline providers. * fix(agents): bind media-fact injection to canonical carrier contract and clear stale turn facts Review follow-up: active-turn detection now uses the shared isRuntimeContextCarrier structural check instead of delimiter-text sniffing, and currentTurnMediaFacts is cleared when a text-only turn replaces the active turn so previous-turn video cannot be re-injected. * fix(models): keep video capability at the provider boundary Review alignment: revert the canonical model-input widening (llm-core Model.input and the registry runtime projection stay text/image per the current-main contract test). Declared video now survives only through resolveProviderModelInput onto the provider runtime model, where the provider-side ProviderModel.input union (packages/ai/provider-types) and the openai-completions transport gate already legitimize it. Config schema (ModelDefinitionSchema) and prepared catalog entries already carried video on main; no canonical contract change is needed for native video on custom openai-completions providers. * fix(ci): satisfy lint and test-type shards Remove the boolean-to-boolean compare in the native-video capability check and a dead assignment in the media projection; annotate provider-scope video fixtures in the transport/params/inline/replay tests with provider-boundary downcasts matching production. * fix(ci): annotate provider-boundary assertions for safety ratchet Add // SAFETY: invariant comments to the new provider-boundary type assertions so the assertion-safety baseline ratchet holds, and drop the now-unused processCompletionsStream import from the transport test (oxlint no-unused-vars). * test(ci): annotate prepared-catalog mock isolation check:test-mock-exports requires first-party mock factories to spread the real module or carry a // mock-isolation: reason; the runner.video fixture intentionally stubs the prepared model catalog. * chore: shrink assertion allowance after native video repair * test(media): assert normalized queued text at the video boundary * test(media): complete model fixtures and wrapper imports --------- Co-authored-by: Peter Steinberger <[email protected]> Co-authored-by: evomach <[email protected]>
What Problem This Solves
Fixes missing video attachments and false context-overflow errors when an explicitly video-capable Chat Completions model receives a local video.
User Impact
Current, retained, and queued video turns keep their attachment on the original user message, including when a runtime-context row follows it. Video bytes no longer count as millions of prompt-text characters. Canonical runtime models remain text/image-only; the existing authored
input: ["text", "image", "video"]configuration enables video only at the compatible provider boundary.Remote video URLs remain unsupported by this native local-media path, and unsupported models retain an explicit omission outcome. The bounded video estimate is a preflight heuristic, not an exact count of backend frame tokens. No new configuration or migration is required.
Why This Change Was Made
Keep one authoritative media-fact owner through in-memory message projections, then lazily materialize provider media once per physical stream call. Enumerable symbols survive those copies without entering transcript JSON; guarded persistence owns normalization. The selected transport carries the existing provider handoff, and Chat Completions consumes it with a correctly typed provider-only capability projection.
This removes current-turn reinjection, debug tags/probe warnings, silent-skip catches, redundant hydration writes, and cast-based canonical modality widening. It preserves the separation introduced by #121887. The base64 estimate now assigns video parts a fixed 96,000-character cost.
This continues @evomach's original work and preserves all contributor commits. Main was merged, without rebasing or force-pushing. Credit also belongs to evomach's earlier Windows/llama.cpp observations; those observations do not establish behavior on this repaired head.
Production: +220/-182 (net +38); tests: +431/-40 (net +391). Nearby cleanup removes most added production cost; the remaining growth carries the typed provider capability and handoff. Documentation adds one line; configuration adds the package subpath alias and shrinks one assertion allowance from five to three. The maintained PR-wrapper inventory also gains the provider-types runtime module.
Evidence
Exact comparison base:
2afa400a0de8320ad915249b8e617b6a72654dc8. Both runs use an isolated macOS Gateway launched bypnpm openclaw --profile native-video-proof gateway run --port 19731 --bind loopback --auth none, then protocol-v4sessions.create → chat.send → agent.wait/chat.history.The baseline source tree matched that main commit: current, retained, and queued requests completed but sent zero video parts (40.1s, 6.5s, 2.0s). The synthetic MP4 is 1,415,341 bytes, SHA-256
883d6c1580b30db119857b148982cd55aeadc27c0e97259c9c3f432b81684464. On the repaired head, current video passed in 9.9s with one nativevideo_url.urlpart; retained history passed in 1.5s with one part in each request; queued input passed in 1.7s with counts[0, 1]and verified final completion. Every video matched the exact bytes/digest and remained on its original user message, with no media on the following runtime-context row and no duplicate attachment. User text stayed bounded and all requests retainedmaxTokens: 1024. Unsupported video produced the explicit omission marker (1.0s). The baseline Gateway used Node; the repaired CLI selected Bun. Timings are observations, not a performance comparison.Real local controls use already-loaded LM Studio
google/gemma-4-e4bthrough that same Gateway/provider path. Before repair, the image control correctly described an unseen red background with a centered blue square (20.1s), and the text control returned its exact requested marker (11.4s). After repair, the image control answered “The image displays a red background with a solid blue square centered in the middle.” (9.0s), and text returnedLOCAL_MODEL_CONTROL_OK(3.9s). The image had a neutral outbound filename and no answer hints.Regression proof: the real normalization/conversion/materialization test fails on main when current-turn facts disappear; restoring only the old estimator makes the managed request with 1.05 MB of base64 video data fail before fetch (93.92s). The repaired provider suites pass 81 tests across seven files (58.45s). The nine core files have 104 passing cases across the initial run and one corrected-file rerun (initial wall 1443.96s; rerun 710.55s, test body 459ms). The initial run exposed a test assertion that expected normalized queued plain text as content blocks; it was corrected to the existing string contract, retaining all media-ownership assertions. The full build passed in 1608.41s with repository-pinned pnpm 12.10.1 and Node 26.12.0. An earlier build was interrupted by a concurrent host Node/library upgrade; the complete rerun passed without skipping phases. The packed-package external-install/export check passed (one test; 127.25s Vitest, 93.39s test body, 1376.33s including runtime preparation). Independent committed-branch Codex autoreview on
afd700cd0d1e157012b8e53306053dd6e18fd7c9is scoped-clean through P2, with no accepted/actionable findings (573.83s).Scoped validation passed: core types 61.94s; three test type graphs 71.22s; lint 169.53s; format 1.39s; assertion ratchet 38.78s; line-cap, timeout-race, mock-export, config-docs, and plugin-inventory ratchets. Max-lines has an inherited suppression failure in
ui/src/pages/chat/components/chat-message.test.tsx, reproduced against the exact base (19.23s); no allowance was expanded.CI follow-up: the first run exposed a shared test fixture that cast an incomplete model without its required ID, plus a missing runtime import in the extracted PR-wrapper inventory. The follow-up uses the existing typed model fixture and adds exactly that inventory path. MCP/orphan integration tests pass six cases (774.28s including worker preparation), and both wrapper inventory/extraction tests pass (109.74s). The fresh agents-other test-type graph passes (30.46s); an incremental-only diagnostic is recorded separately. Production runtime code is unchanged from the completed build and Gateway proof at
24cf4ed3656d9f9adb45f3ec49f4c7fc4b5a7577. The local catalog-abort suite initially passed nine of ten cases (558.30s), with a missing direct-spawn outcome; a filtered replay failed similarly (339.97s). A temporary terminal-state diagnostic then passed with terminalokand the original outcome assertions (229.28s wall, 6.802s case). The diagnostic was removed and the checkout verified clean. This passing replay does not establish the prior failure’s cause. All ten catalog cases pass in exact-head CI.Exact-head CI run 38876932270 tests main base
ff13ebe1d6dd5d66befc1449ba71b1234df757cdand completed with 91 passed, 23 skipped, and four failed jobs (the three classified failures below plusopenclaw/ci-gate). The aggregate gate is red; a maintainer inherited-failure/tooling exception is needed before landing. The build, baseline ratchets, production/test types, native-video catalog, MCP, wrapper inventory, heartbeat, and Gateway cleanup checks pass. Two test failures are inherited from that exact base: the fake-Bun fixture lacks the revision response required by #173807 (1.23s owner-boundary reproduction; exact owner/fixture blobs unchanged at the final base), and #173972 moved the stale-writer check inside compaction’s existing result-catching block while its test still expects rejection. Executing both exact compaction owners reproduces rejection before that main change and the precise CI failure result afterward (0.49s), without entering the context engine. These are narrow owner-boundary reproductions, not full base-suite runs.A separate lint job passes its core stripe with zero errors (100.75s), then times out after 300 seconds preparing plugin SDK declarations for the extension stripe. The full build passes independently; this timeout remains a tooling limitation, and no extension-lint success is claimed. Earlier heartbeat and Gateway-cleanup failures did not reproduce locally and now pass in exact-head CI; their earlier causes remain unproven. No CI rerun was requested.
Limitations: video proof captures the exact Gateway-to-provider payload with a deterministic backend, while image/chat controls use a real local model. Native-video perception on this head, Windows/Linux, Telegram, and a stable-version upgrade are not claimed. No installed local backend was established as video-capable.
ClawSweeper: no review of
afd700cd0d1e157012b8e53306053dd6e18fd7c9arrived during the 15-minute polling window after the final push. Its latest comment still reviewsb41c66185f94e9febae6fc2a56ddf2a35860839c; both prior code findings are addressed above. The independent final-head review is clean, but no current-head ClawSweeper verdict is claimed.Landing gate update
The server-side main merge produced reviewed head
8cdb89b344f45a171be1fa81779d6a7ccdb0c31bwithout changing the repaired implementation. Exact-head CI run 38879350930, attempt 1 completed against main2a48809c5ce30ea4dc5c715fb599d8d21d92fb75, using tested merge77a4494afb6cbc60e7dc2aa6b09ac2e1c50812ec.The only failed root jobs are
checks-node-changed-compact-large-1(the inherited compaction rejection assertion from #173972) andchecks-node-compact-small-16(six inherited fake-Bun fixture cases from #173807). Their failure signatures match the independently reproduced baseline defects. All twelve relevant test and owner files are byte-identical between this exact CI base, the previously reproduced baseline, and this PR head. The CI comparison table reports unknown/new because its scheduled-main job scopes differ; independent exact-source attribution establishes these inherited failures. The aggregate CI gate remains failed. Landing uses the explicitly authorized nativepre-existing-failureexception; no CI success is claimed.Extension lint passed on this attempt, so no rerun was needed. Security-fast and the security-sensitive review passed. ClawSweeper completed the exact-head review on October 16 at 09:47 UTC with zero code findings and no Before merge items; both older findings are resolved. The reported video-perception, platform, and upgrade proof limits remain explicit.