Skip to content

feat(byteplus): record/replay BytePlus Ark (Seedance) video task lifecycle - #424

Merged
jpr5 merged 16 commits into
mainfrom
feat/byteplus-ark-video
Sep 10, 2026
Merged

jpr5 merged 16 commits into
mainfrom
feat/byteplus-ark-video

Conversation

@jpr5

@jpr5 jpr5 commented Sep 10, 2026

Copy link
Copy Markdown
Contributor

Closes #415. Built to the reviewed design spec (7 decisions, 4 reviewers, 3 confirmation rounds).

POST /api/v3/contents/generations/tasks + GET /api/v3/contents/generations/tasks/{id}, with replay, record, and a drift leg.

The decision everything else follows from

The fixture format is the Ark task envelope itself, stored as a RawJSONResponse ({ response: { json: … } }) — not a VideoResponse. VideoResponse is consequently not edited at all.

That buys four things that a hand-built serializer cannot:

  • cancelled and expired record and replay natively. They have no representation in the 3-value VideoResponse.status union, so the alternative was warn-and-drop: cancel a task from the Ark console mid-record and you'd get a warning and an empty fixture directory. Now you get an artifact.
  • No error code is ever invented. Ark's code vocabulary is open-ended and the client splices whatever code it finds into the consumer-visible error string, so a minted token would land in someone's assertion. A recorded error replays byte-for-byte; a fixture with no code emits no code.
  • usage is not lossy. completion_tokens, total_tokens, tool_usage, and the number|string union all replay as recorded — including the client's own completionTokens ?? totalTokens fallback path.
  • Vendor drift is survivable. framespersecond, draft_task_id, and anything BytePlus ships next year replay because they were recorded, not because this PR enumerated them.

The governing rule: the mock never authors a wire value it did not observe. On replay exactly three things are synthesized — the id rewrite, the queued/running token on a non-terminal poll, and withholding content/error/usage until terminal. No default code, no default message, no fabricated usage, and — diverging from grok-video deliberately — no placeholder video URL. A terminal fixture missing content.video_url gets a warn naming the exact client error it will hit, because a URL aimock invented is strictly harder to debug than a named warning.

Three things that are load-bearing, not incidental

URL composition. record.providers.byteplus is an origin; the handler owns the whole path including /api/v3. That matches how every async-video handler here passes a handler-owned constant to resolveUpstreamUrl, and it's what stops /api/v3/chat/completions (whose prefix rides in req.url) from composing the prefix twice.

Anchored route regexes. The /api/v3 prefix is enumerated, not wildcarded. These routes dispatch in the pre-rewrite band, ~1,100 lines ahead of every fal branch, so a tolerant prefix would claim /fal/contents/generations/tasks and take it away from the fal proxy — a live behavior change for a shipped provider.

The attribution gate. Chat/images attribution requires record.providers.byteplus to be configured. A path prefix is not evidence of a vendor — the COMPAT_SUFFIXES comment exists precisely because vendors ride arbitrary prefixes. Ungated, anyone serving an OpenAI-compatible vendor under /api/v3 would silently lose record mode.

Red-green, with mutation proofs

Every headline property was observed red first. Five were mutation-proofed — a guard nobody has watched fail is a claim, not a test:

Mutation Result
(none — against main @ 7323e81) route 404s; and /api/v3/chat/completions asserted green first, since the attribution work rests on that being existing behavior
bare TASKS_PATH (drop the /api/v3 the handler owns) origin-only composition test fails
ungate the attribution (prefix alone decides) openai-attribution regression test fails
drop case "byteplus": from the SSE arm "no unknown SSE provider warn" test fails
text-only match key (drop the media digest) both media-collision tests fail
rename emitted content.video_url → videoUrl drift check (a) reports API DRIFT DETECTED … Path: content.video_url

The drift mutation had to be run locally — test-drift.yml gates that lane off PRs, so no CI run here can produce it:

$ npx vitest run --config vitest.config.drift.ts src/__tests__/drift/byteplus-video.drift.ts
 × BytePlus video-proxy envelope shapes > a succeeded poll returns the recorded envelope with the mock id
API DRIFT DETECTED: BytePlus video succeeded poll
     Path:    content.video_url
: expected [ { path: 'content.video_url', …(5) } ] to deeply equal []

Restored: Tests 3 passed | 1 skipped.

The match key is not just the prompt

A Seedance image-to-video job carries no text part, so a prompt-only key records {endpoint, model} — a wildcard matching every i2v job in a suite for that model, which persistFixture's defective-fixture guard would not catch (its isEmptyMatch also requires endpoint to be undefined). The key folds a 12-hex sha256 of each media input in, so a data: URI never reaches the fixture and two recordings stay distinguishable.

What I did NOT touch, and why

src/router.ts. The tempting edit — relaxing its video row to accept { json } — would make an endpoint-less JSON fixture newly eligible for Grok, Veo, Sora and OpenRouter video requests, each of which then fails its own isVideoResponse guard and journals a 500. A clean skip becomes a 500 on four providers this PR doesn't touch. The cost is that a byteplus fixture must carry match.endpoint: "video"; the no-match diagnostic names that explicitly and a test pins both the omission and the fix.

Scope

Out: the HMAC-signed Assets control plane, task list/delete, byte capture (video.b64), Seed Speech, callback_url webhooks, Ark embeddings. Each is argued in the spec rather than merely listed.

Tests and gates

185 files, 5786 tests passing. 55 new. format / lint / typecheck / build clean.

Coverage, stated honestly: the new handler is 94.8% lines / 100% functions / 79.5% branches. The repo's global thresholds fail both before and after this change — the rest of the repo alone measures 86.72% lines / 81.94% branches — and this PR moves lines up (86.72 → 86.90). CI does not run coverage.

Open question, merge-blocking

byteplus vs ark as the provider key. I used byteplus: the adapter's own name is 'byteplus' as const, RecordProviderKey members are vendor names elsewhere, and "ark" collides with Volcengine's China deployment. Reversing it is mechanical now and effectively impossible after release — the value is a fixture filename prefix, so renaming post-release invalidates fixtures on disk.

Also unverified without a live key, and flagged in the spec: the submit response's HTTP status (200 assumed vs 201), and the drift canary's assumption that Ark 404s an unknown task id with its error envelope. The requester offered to test against real Ark keys — the canary is the highest-value thing to hand them.

🤖 Generated with Claude Code

https://claude.ai/code/session_01AvkmhXVLqSSEW6FvPQHSu5

…cycle

Closes #415. Adds a `byteplus` provider covering Ark's async video task API —
`POST /api/v3/contents/generations/tasks` and
`GET /api/v3/contents/generations/tasks/{id}` — with replay, record, and a
drift leg.

THE FIXTURE FORMAT IS THE ARK ENVELOPE ITSELF, stored as a RawJSONResponse
(`{ response: { json: … } }`), not a VideoResponse. That is the central
decision and `VideoResponse` is consequently NOT edited. It is what lets
`cancelled` and `expired` — terminal states the 3-value VideoResponse.status
union cannot express — record and replay natively instead of being dropped
with a warning; what lets a recorded `error` object replay without aimock
inventing a code from a vocabulary it has never observed; and what lets
`usage`, `framespersecond`, `draft_task_id` and any field BytePlus adds later
survive, because they were recorded rather than enumerated.

The governing rule is that the mock never authors a wire value it did not
observe. On replay exactly three things are synthesized: the `id` rewrite, the
queued/running token on a non-terminal poll, and withholding
content/error/usage until terminal. There is no default error code, no default
message, no fabricated usage, and — diverging from grok-video deliberately —
no placeholder video URL. A terminal fixture missing `content.video_url` gets a
warn naming the exact client error, because a URL aimock made up is harder to
debug than a named warning.

URL composition: `record.providers.byteplus` is an ORIGIN and the handler owns
the whole path including the `/api/v3` prefix, matching how every async-video
handler here passes a handler-owned constant to resolveUpstreamUrl. That is
what keeps `/api/v3/chat/completions` (whose prefix rides in req.url) from
composing the prefix twice.

Route regexes enumerate the optional `/api/v3` prefix rather than wildcarding
it. These routes dispatch in the pre-rewrite band, ~1,100 lines ahead of every
fal branch, so a tolerant prefix would take `/fal/contents/generations/tasks`
away from the fal proxy — a live behavior change for a shipped provider.

Chat/images attribution is GATED on `record.providers.byteplus` being
configured. A path prefix is not evidence of a vendor: ungated, anyone serving
an OpenAI-compatible vendor under `/api/v3` would silently lose record mode.

The match key folds a short sha256 digest of each media input into the
synthetic user message. A Seedance image-to-video job carries no text at all,
so a prompt-only key would record `{endpoint, model}` — a wildcard matching
every i2v job in a suite for that model, which persistFixture's defective-
fixture guard would not catch.

Also: `byteplus` joins the OpenAI SSE arm of collapseSSE (Ark chat is
OpenAI-shaped SSE; without the case every recorded Ark stream logs "unknown
SSE provider"), and handleImages gains an optional trailing recordProviderKey
passed only at the OpenAI-images call site.

`src/router.ts` is deliberately NOT edited: relaxing its video row to accept
`{ json }` would make an endpoint-less JSON fixture newly eligible for Grok,
Veo, Sora and OpenRouter video requests, each of which would then 500. The
cost is that a byteplus fixture MUST carry `match.endpoint: "video"`; the
no-match diagnostic names that requirement and a test pins it.

Tests: 55 new (39 replay, 24 record incl. shared cases), plus 3 static drift
checks. Every headline property was observed red before it was made green, and
five were mutation-proofed:

  - route red on main @ 7323e81 (404 before the route existed); compat-path
    asserted GREEN on main first, since §6.4 rests on existing behavior
  - bare TASKS_PATH → the origin-only composition test fails
  - ungated attribution → the openai-attribution regression test fails
  - dropped SSE case → the "no unknown SSE provider warn" test fails
  - text-only match key → both media-collision tests fail
  - content.video_url renamed to videoUrl → drift check (a) reports
    "API DRIFT DETECTED … Path: content.video_url"

Coverage: the new handler is 94.8% lines / 100% functions / 79.5% branches.
The repo's global thresholds fail both before and after this change — the rest
of the repo alone is 86.72% lines / 81.94% branches — and this PR moves lines
up (86.72 → 86.90). CI does not run coverage.

Full suite: 185 files, 5786 tests passing.
@pkg-pr-new

pkg-pr-new Bot commented Sep 10, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

npm i https://pkg.pr.new/@copilotkit/aimock@424

commit: 0abc9a3

jpr5 added 11 commits September 10, 2026 15:45
The leg registered `byteplus-video` as a covered drift surface while running
three `triangulate(sdkShape, sdkShape, mockShape)` checks whose "vendor truth"
side was a hand-copy, in the same file, of the fixture driving the mock. It
could not go red for anything BytePlus does, and its stand-in values
(`QuotaExceeded`, a token count, an `ark-content.example.com` URL) were
invented — inside the check meant to catch invented values. Its only
vendor-facing check was `describe.skipIf(!ARK_API_KEY)`, and there is no
`ARK_API_KEY` in repo secrets, so it skipped to green.

Replace them with a FREE, KEYLESS live canary. An unauthenticated (and a
malformed-bearer) GET on the real Ark task endpoint is answered by Ark's auth
layer before any billing or resource lookup: HTTP 401, an `x-error-code`
header, and the `{ error: { code, message, param, type } }` envelope this
surface's 4xx handling is modelled on. Verified live 2026-09-10 on both
ap-southeast and cn-beijing; every constant is observed, none authored.

- Network failure / 429 / 5xx becomes an honest skip, never a drift finding.
- 401/403 on the authenticated canary reports a stale key or region mismatch
  as configuration, not drift; region is overridable via `ARK_BASE_URL`.
- An always-on offline pin drives the real probe through a stubbed transport
  over ten envelope mutations, so a grader that can no longer fail is caught.
- Registry entry now documents what is covered (the error envelope) and what
  is not (the success/poll shapes), and points `sdkShapesFile` at the drift
  leg, where the observed vendor truth actually lives.
- Fix the orphaned `listOpenRouterVideoModels` doc comment.

The deleted checks' mock-side pass-through property is already pinned by
`expect(body).toEqual({ ...stored, id })` in the always-on unit lane.
…claims

`record.providers.byteplus` is an ORIGIN — the video handler appends the
full `/api/v3/contents/generations/tasks` path and the chat/images proxies
relay the client's raw `/api/v3/...` url. BytePlus publishes
`https://ark.<region>.bytepluses.com/api/v3` as the OpenAI-SDK `base_url`,
so pasting it into `--provider-byteplus` composed, observed on a stub
upstream:

  ["/api/v3/api/v3/contents/generations/tasks",
   "/api/v3/api/v3/chat/completions"]

Every such request fails upstream and the operator sees a relayed 404 that
does not name its cause. The docs said "origin only", but a doc is not a
guard. createServer now throws at startup naming the cause and the fix.
It throws rather than stripping: the doubled form cannot serve any BytePlus
request, so nothing working is taken away, and a silent strip would be
wrong for a deliberately path-mounted reverse proxy.

Also:
- restore two doc comments to the code they document — the OpenRouter
  discovery-endpoint note (wedged above the BytePlus routes in server.ts)
  and `listOpenRouterVideoModels`'s JSDoc (wedged above the BytePlus drift
  probe).
- reword every claim of live/vendor verification on this surface to name
  its real provenance: `@tanstack/[email protected]`, the requester's
  client library and a secondary source, not BytePlus. The submit-shape
  assertion no longer claims a "live-verified shape"; the drift leg no
  longer calls its 404 expectation "documented".
- note the canary's hard-coded `ap-southeast` region: a key from another
  region reads as drift when it is a configuration mismatch.
- README: 13 providers -> 14, 15 surfaces -> 16 (BytePlus Ark chat/images).
…space

Every BytePlus Ark fixture is required to carry `match.endpoint: "video"`,
which puts a RawJSONResponse into the namespace Sora, Grok, Veo and OpenRouter
share. The router treated a declared endpoint as the end of the shape
discussion, so one BytePlus fixture became a first-class candidate for all four
other handlers, each of which then failed its own isVideoResponse guard and
returned 500. A single addFixture call broke every other video provider in the
same suite.

Filter the raw-JSON half of the video namespace out of the non-BytePlus
handlers, keyed on the request's own `_videoProvider`. Deliberately narrow:
every other wrong-shape fixture still reaches its handler, which names the
problem itself, rather than vanishing into a silent no-match.
The media marker was a conditional suffix, so the text-only key "a guitar" was
a prefix of the image-to-video key "a guitar\n[media: first_frame:…]". The
router substring-matches userMessage by default, so a text-to-video recording
silently served its own video_url to an image-to-video request sharing the
prompt — a 200 with the wrong bytes.

Parts the media table could not resolve were dropped entirely, so a content
array of only unrecognised parts returned "", buildFixtureMatch then omitted
userMessage, and the fixture became `{ endpoint: "video", model }` — the
model-wide wildcard this key exists to prevent, which isEmptyMatch cannot
catch because endpoint is set.

Emit `[media: …]` unconditionally (`[media: ]` when there is none) so no key is
a substring of another, and digest an unresolvable part over its own JSON so it
still contributes and two different ones stay distinguishable.
…me the hang

Five findings from the PR #424 review, all in `src/byteplus-video.ts`, each with
a regression test observed failing first.

The 24h-expiry warn was gated on `updated_at` alone. It told the operator that a
`failed`/`cancelled`/`expired` envelope — which carries no `content` at all —
"has a content.video_url that expired at 1970-01-02T00:00:02.000Z", and since any
committed fixture is older than 24h it fired on every replay forever. Gate it on
the same two facts the adjacent missing-url warn already uses: a `succeeded`
status and a url that is actually there.

`X-AIMock-Record-Error` was unreachable: `relayJson()` had already sent the
response before the capture ran, so `!res.headersSent` was never true and a
persist failure reached the operator only as a log line behind an
indistinguishable 200. Follow grok-video.ts:1105 and capture before relaying —
the capture is a synchronous persist with no byte download, so nothing else
changes.

A fixture whose envelope carries `queued` or `running` replayed that status
forever with no diagnostic: both tokens are in the known-status set so the
unknown-status warn stayed silent, and a non-empty string keeps the 502 path
silent too. This mode exists only because the fixture is the raw envelope, and it
was the one authoring error on this surface left unnamed. Warn once at the
terminal poll, naming the hang.

`job.capturing` was dead state — the capture sequence is fully synchronous, so
the flag was set and cleared inside one tick and could never be observed set, and
its comment claimed an await that did not exist. Removing it left the capture
body's identity check unreachable too (no await separates it from the outer one).
Consolidate to a single map-identity gate that both serializes concurrent
terminal polls and guards the world generation. `RecordJob.phase` went with them:
write-only after the flag left.

Also: derive the terminal vocabulary as the complement of `queued`/`running`
instead of a second hardcoded list of four, so an unrecognized end state is
captured rather than proxied until the client times out; withhold `updated_at`
until terminal, since on a recorded envelope it is the terminal transition's
timestamp; and key the warn latches on the envelope object rather than the job,
so one aged fixture replayed across a suite warns once instead of once per test.

`arkErrorBody` still omits `error.code` and now says why at length: no Ark error
body has ever been observed here, the drift canary that asserts a string `code`
has never run, and the client library is not installed — so the value is unknown,
and an honest absence beats a plausible invention.
…ndler

Comments here appealed to vendor documentation that nobody read. BytePlus's docs
are client-rendered SPAs; every wire fact in this surface comes from the client
library `@tanstack/[email protected]` — its `wire-types.ts`, its request
builders, and its author's note of live calls made on 2026-07-31. That is a
secondary source, and aimock has never called Ark.

Add a PROVENANCE block to the file header stating exactly that, then reword each
site to match: the status sets are the client library's union rather than "the
vendor's six" (in the comments and in the unknown-status warn the operator
reads); the `first_frame` role default is what the library applies, not an "API
documented default"; `model` is required because the library always sends it,
with whether Ark itself rejects a request without it named as unverified.

Two comments asserted unverified facts outright. The unknown-task 404 said "real
Ark 404s an aged-out record with a dotted code" — nobody has seen an Ark error
body; it now says so and points at `arkErrorBody`. The non-terminal poll said
`updated_at` mid-flight is a combination "never observed live", which claims
knowledge of live behaviour; it now says the design has never seen it and cannot
source it from the library either.

No behaviour change.
…video

Keeps BytePlus raw-JSON fixtures out of the shared video namespace, and
makes the submit match key unshadowable and never empty.
…ideo

Correct poll-warning gating, capture-before-relay, the infinite-poll warn,
removal of the inert job.capturing / RecordJob.phase guards, and the
provenance rewrite of the handler's wire claims.
…Text

The namespace fix inserted digest12/unresolvedPartToken between the
docblock and the function it documents, so the block landed on
digest12. Move the helpers above it.
Replaces the self-referential triangulate checks with a FREE, keyless live
auth-envelope canary against real Ark, plus a region-overridable base URL.
Rejects an /api/v3-suffixed BytePlus upstream base at startup, and corrects
the doc and test claims that overstated what this repo verified.

# Conflicts:
#	src/__tests__/drift/byteplus-video.drift.ts
#	src/__tests__/drift/providers.ts
…vation

The handler/provenance work and the drift leg landed on separate branches and
were never reconciled. Six sites now say what is actually true post-merge:

- arkErrorBody's docblock and the unknown-task 404 comment claimed the canary
  has never run and aimock has never seen an Ark error body. The keyless canary
  runs on every drift run and observed Ark's AUTH envelope live on 2026-09-10.
  The design decision (omit code) is unchanged — the observed code is the auth
  class, and none of the five aimock-authored error classes is an auth error —
  but the premise was wrong. type and param get the same treatment.
- The drift test title said Ark's "documented" 401 envelope. It is observed;
  BytePlus's docs have never been read here.
- server.ts, byteplus-provider-base.test.ts and the docs page said BytePlus
  "publishes" .../api/v3 as the OpenAI-SDK base_url. That value is
  @tanstack/[email protected]'s own BYTEPLUS_ARK_BASE_URL constant, which its
  author labels "Docs-derived" — a secondary source, not a vendor publication.
- The cgt- id prefix was attributed to "what live Ark returns"; this repo has
  not observed a real Ark task id. It comes from the same package's wire-types.
- byteplus-video.test.ts's "nothing verified against live Ark" is now scoped to
  the create/poll shapes, which remain unobserved.
The page claimed "a key of just the bare prompt matches nothing". It matches
everything with that prompt: match.userMessage is substring-matched by default,
so a bare prompt is a substring of both `p\n[media: ]` and
`p\n[media: first_frame:...]`, and the router serves whichever fixture it
reaches first — HTTP 200 with the wrong video. video-namespace.test.ts test 4
demonstrates the same behaviour.

What the unconditional [media: ...] suffix actually buys is that no RECORDED key
is a substring of another recorded key, so a text-to-video recording cannot
shadow an image-to-video request. That is a property of recorded keys, not of
the router, and the page now says so. Also notes the reverse direction (a
media-only key shadows a text+media request sharing that media) and points at
requestTransform as the exact-match escape hatch.

Prose only; the code is correct.
Both branches were unpinned: deleting them left the full suite green, and
metrics.test.ts had zero byteplus references. Without them Prometheus label
cardinality is unbounded — one label per cgt-<uuid> task id, a failure that only
shows up in a customer's TSDB, never in a test run.

Two assertions matching the peer /v1/videos/{id} idiom. The /api/v3-prefixed
form is the load-bearing half for the submit path: the bare form is already its
own label when the branch is absent.

Red-green, per branch, against src/metrics.ts:
  delete the STATUS branch -> 1 failed | 59 passed; restore -> 60 passed
  delete the SUBMIT branch -> 1 failed | 59 passed; restore -> 60 passed
…nary

The provenance header claimed aimock had never called Ark and that no Ark
response had ever been observed. That stopped being true when the drift leg
gained a keyless canary: it calls live Ark and observed the AUTH-layer 401
error envelope on 2026-09-10, which the comment on arkErrorBody already says.

Draw the line where reality draws it: the task shapes (create, poll,
succeeded/failed, the status tokens, the unknown-task 404) are still
secondhand from @tanstack/[email protected], the auth layer is firsthand, and
no success or resource-layer response has been observed because the
authenticated canary is still skipIf-gated for want of ARK_API_KEY.
@jpr5
jpr5 merged commit 7040a2d into main Sep 10, 2026
33 checks passed
@jpr5
jpr5 deleted the feat/byteplus-ark-video branch September 10, 2026 23:37
jpr5 added a commit that referenced this pull request Sep 10, 2026
…lformed status (#429)

Three defects an independent review found on `main` after PR #424
merged. All three were reproduced on `origin/main` @ `7040a2d` before
any change was made.

## 1. P2 — the docs page is visually broken

`docs/byteplus-video/index.html` used `<main class="content">`. Every
other page in `docs/` uses `docs-content` — a sweep of all 40+ pages
found this one as the sole exception, so it is template drift, not an
alternate layout.

`docs/style.css` puts the content margin, padding, sizing, max/min width
and word-wrapping on `.docs-content`, and `docs/sidebar.js:151` selects
`.docs-content` and returns early when it is absent, before assigning
heading ids or building the TOC. One root cause, two visible effects.

Verified by Playwright screenshots on a locally served `docs/` tree at
1440x900, 375x667 and 430x932, with `docs/video/` as the control, and
the images inspected directly rather than trusting measurements.

**Before** — 1440x900: the fixed sidebar overlays the content; the title
renders as "…eedance) Video" with its left half hidden, and every
paragraph and code block is clipped on the left. 375x667 and 430x932:
content has no gutter at all, starting flush at x=0, and every line runs
off the right edge.

**After** — 1440x900: full title, padded content column clear of the
sidebar, and the "ON THIS PAGE" TOC rendered on the right, matching the
control. 375x667 and 430x932: proper gutters, title and prose wrap,
nothing clipped.

| | before | after | control (`/video/`) |
|---|---|---|---|
| TOC links | 0 | 6 | 8 |
| populated h2 ids | 0 / 6 | 6 / 6 | 6 / 6 |
| `.docs-content` found | no | yes | yes |

Residual horizontal overflow from long `<pre>` lines at mobile widths is
pre-existing and site-wide (`grok-video` 527px, `veo-video` 905px,
`fal-ai` 726px against a 375px viewport), unrelated to this class, and
left alone.

## 2. P2 — a malformed poll status persists an unusable fixture

`src/byteplus-video.ts` coerced the upstream status with
`String(upstreamBody.status ?? "")`, so an absent status became `""` and
a numeric `123` became `"123"`. Terminal is derived as the complement of
the non-terminal pair, so both coerced values read as terminal. Record
mode then persisted an envelope that `serializeBytePlusVideoTask`
rejects and swapped the job to replay — so every later poll 502s on that
same envelope and a corrected upstream response is never fetched for
that job, with the unusable fixture left on disk.

The status now has to clear the same predicate replay applies — a
non-empty string — before it can be terminal. Otherwise it is relayed
verbatim and the job stays upstream-backed.

**Scope, stated honestly:** this is malformed-upstream robustness only.
There is no evidence Ark emits such a body. 4xx/5xx, non-JSON and
non-object bodies are out of scope and are already rejected upstream of
this check.

### The reviewer's own repro, before and after

Run with the repo's `tsx` against a real aimock server, a real HTTP
upstream, the real recorder and real filesystem persistence.

Before:
```
missing: submit 200; poll 1 200; poll 2 502   upstreamPolls 1   persisted {"json":{}}
numeric: submit 200; poll 1 200; poll 2 502   upstreamPolls 1   persisted {"json":{"status":123}}
valid:   submit 200; poll 1 200; poll 2 200   upstreamPolls 1   persisted {"json":{"status":"cancelled"}}
```

After:
```
missing: submit 200; poll 1 200; poll 2 200   upstreamPolls 2   persisted (nothing)
numeric: submit 200; poll 1 200; poll 2 200   upstreamPolls 2   persisted (nothing)
valid:   submit 200; poll 1 200; poll 2 200   upstreamPolls 1   persisted {"json":{"status":"cancelled"}}
```

`upstreamPolls` going 1 -> 2 is the job staying upstream-backed. The
valid control is unchanged.

### Regression test, observed red before the fix

Three tests added to `src/__tests__/byteplus-video-record.test.ts`, run
against the unmodified handler first:

```
× a absent status keeps the job upstream-backed instead of persisting an unusable fixture
  → expected 502 to be 200
× a numeric status keeps the job upstream-backed instead of persisting an unusable fixture
  → expected 502 to be 200
× a corrected upstream status on a LATER poll still records normally
  → expected [ { match: {…}, response: {…} } ] to deeply equal []
Tests  3 failed | 28 skipped (31)
```

After the fix, on the same tests:

```
✓ src/__tests__/byteplus-video-record.test.ts (31 tests | 28 skipped)
Tests  3 passed | 28 skipped (31)
```

## 3. P3 — two inaccurate descriptions

Neither is a runtime change.

The docs said aimock "warns once **per job**" on an expired URL. The
implementation latches per shared fixture envelope object, and the
existing test named *"the staleness warn latches per FIXTURE"* submits
four jobs and asserts exactly one warning — the test contradicts the
doc. Corrected to "once per fixture envelope", noting a new envelope
object can warn again.

The `buildBytePlusMatchText` docblock promised "ALWAYS a newline and
`[media: …]`", but the code is `return text ? \`\${text}\n\${suffix}\` :
suffix` — a text-free key is the bare suffix with no newline. Corrected
to say the separator is present only when there is text.

## Gates

Raw exit codes, all from the worktree root:

| gate | exit |
|---|---|
| `prettier --check .` | 0 |
| `npx eslint .` | 0 |
| `pnpm typecheck` | 0 |
| `npx vitest run` | 0 — 188 files passed, 5782 tests passed, 46 skipped
|
@jpr5 jpr5 mentioned this pull request Sep 11, 2026
jpr5 added a commit that referenced this pull request Sep 11, 2026
Cuts the accumulated `[Unreleased]` work. **MINOR** — a new provider
surface (BytePlus Ark video) and new endpoints, no breaking changes.

**Prepared, not merged.** `publish-release.yml` fires on push-to-main,
so merging this publishes to npm, tags `v1.41.0`, cuts the GitHub
Release, dispatches the Docker build, and posts to Slack. Merge when you
want it live.

## What ships

Only **#424** (plus its follow-up **#429**, which fixes the same
never-released BytePlus code) touches the published package. Verified
against `package.json` `files` + `tsconfig` include/exclude:

```
git log v1.40.0..origin/main --oneline -- src/ ':(exclude)src/__tests__/' fixtures/ .claude-plugin/ skills/ CHANGELOG.md
```

…returns byteplus commits only. #422, #423, #425, #426, #427, #428 touch
scripts/, .github/ and docs/ exclusively and are deliberately **not** in
the CHANGELOG.

### Added
- BytePlus Ark (Seedance) video record/replay — submit, poll and
retrieve, stored as the raw Ark task envelope
- `--provider-byteplus` flag

### Changed
- `/api/v3` chat and image requests are attributed to the `byteplus`
provider
- `aimock-pytest` pin moves to 1.41.0

### Fixed
- Startup error when a BytePlus provider base already ends in `/api/v3`

## Version surfaces — seven, all bumped

Found by grepping the tree for `1.40.0`, not from a checklist. **Zero
occurrences of the old string remain** (excluding `CHANGELOG.md`
history, `fixtures/` and `pnpm-lock.yaml`):

| File | Field | 1.40.0 → 1.41.0 |
| --- | --- | --- |
| `package.json` | `version` | ✔ |
| `charts/aimock/Chart.yaml` | `appVersion` (chart `version` stays
`0.1.0`) | ✔ |
| `.claude-plugin/plugin.json` | `version` | ✔ |
| `.claude-plugin/marketplace.json` | `plugins[0].source.version`
(`^1.41.0`) | ✔ |
| `docs/index.html` | demo banner `aimock v…` | ✔ |
| `packages/aimock-pytest/src/aimock_pytest/_version.py` |
`AIMOCK_VERSION` npm pin | ✔ |
| `packages/aimock-pytest/README.md` | `--aimock-version` default | ✔ |

`AIMOCK_VERSION` **must** move this release:
`/api/v3/contents/generations/tasks` is a new server route, so a
default-download pytest user on the 1.40.0 pin would run a server
without it. `packages/aimock-pytest/pyproject.toml` is deliberately
untouched — that package versions on its own PyPI cadence.

There is **no version constant in `src/cli.ts`** and **no
`metadata.version` in `marketplace.json`** in this tree; both surfaces
exist only in the release checklist, not in the repo.

## Drive-by: the npm description has been `<div align="center">` since
the README got a centered header

`npm view @copilotkit/[email protected] description` returns the literal
string `<div align="center">`.

Both README-subtitle extractors — the inline `node -e` in
`publish-release.yml` and `syncDescriptionFromReadme()` in
`scripts/drift-sync.ts` — skip `#`, `[`, `![` and `http` lines but not
raw HTML, so they latch onto the README's opening `<div>` wrapper
instead of the bold subtitle two lines below. Both now also skip `<`,
and `package.json.description` is synced to what the fixed extractor
yields:

> Mock infrastructure for AI application testing — point your SDK at one
local port and every provider, protocol, and service answers
deterministically.

Without this the v1.41.0 npm page ships the same broken description.

## Gates (raw exit codes, local)

| Gate | Exit |
| --- | --- |
| `prettier --check .` | 0 |
| `npx eslint .` | 0 |
| `pnpm typecheck` | 0 |
| `npx vitest run` (5794 passed, 46 skipped, 189 files) | 0 |
| `pnpm build` | 0 |
| `npx commitlint --from origin/main --to HEAD` | 0 |

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01AvkmhXVLqSSEW6FvPQHSu5
pull Bot pushed a commit to TheTechOddBug/aimock that referenced this pull request Sep 11, 2026
…lformed status

Three post-merge defects from PR CopilotKit#424.

The docs page used `<main class="content">` where every one of the 40+ sibling
pages uses `docs-content`. That class owns the content margin, padding, sizing
and word-wrapping, and `sidebar.js` selects `.docs-content` to build the page
TOC, returning early when it is absent. One root cause, two visible effects: the
fixed sidebar overlaid the title, prose and code examples at 1440x900 and
content lost its gutter at 375x667 and 430x932, and the page generated zero TOC
links with all six h2 ids left empty. Verified by screenshot at all three
viewports against `docs/video/` as the control; TOC links go 0 -> 6 and every
heading id populates. No other page in `docs/` carries the wrong class.

The poll handler coerced the upstream status with `String(status ?? "")`, so an
absent status became `""` and a numeric `123` became `"123"`. Terminal is the
complement of the non-terminal pair, so both read as terminal: record mode
persisted an envelope replay cannot serve and swapped the job to replay, after
which every later poll 502s on that same envelope and a corrected upstream
response is never fetched for that job. The status now has to clear the same
predicate replay applies — a non-empty string — before it can be terminal.

This is malformed-upstream robustness only. Ark is not known to emit such a
body, and 4xx/5xx, non-JSON and non-object bodies are out of scope, already
rejected upstream of this check.

Also corrects two inaccurate descriptions, neither a runtime change: the docs
promised the stale-URL warning fires once per job when it latches once per
shared fixture envelope, and the match-key docblock promised an unconditional
newline when a text-free key is the bare `[media: ...]` suffix.
pull Bot pushed a commit to TheTechOddBug/aimock that referenced this pull request Sep 11, 2026
### Added

- **BytePlus Ark (Seedance) video record/replay** — submit, poll, retrieve raw Ark tasks (CopilotKit#424)
- New `--provider-byteplus` flag to proxy BytePlus Ark to an upstream base (CopilotKit#424)

### Changed

- `/api/v3` chat and image requests are attributed to the `byteplus` provider (CopilotKit#424)
- `aimock-pytest` now defaults to `@copilotkit/aimock` 1.41.0.

### Fixed

- aimock now fails at startup if a BytePlus base already ends in `/api/v3` (CopilotKit#424)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Support BytePlus Ark (Seedance / Seedream) video job lifecycle for record & replay

1 participant