"""Audio and video reach a model that reads them, and no other. Catches a clip sent to a wire or model that refuses it, which fails every request after it: the gate between a session's history and its provider spans the kernel, uploads, the transcript and each wire, and a model switch reaches it with clips already saved. OpenCode Go is the adapter because it picks the Gemini, Chat Completions or Messages wire from the model's name; the models.dev catalogue says which of them reads audio and video. The catalogue is daemon-wide, so the class is exclusive. A fake ffmpeg on the daemon's PATH, ahead of any real one, stands in for the encoder that copies clips to what each model takes in: it logs its arguments and answers the file a test left for the output's extension, or fails when there is none. """ import base64 import hashlib import inspect import json import os import sqlite3 import struct import threading import time import unittest import urllib.error from _imagegen_support import png from fake_provider import error from harness import ( Albedo, Provider, cell_result, exclusive_class, operation_id, python, text, ) GEMINI = "gemini-media-fixture" CLAUDE = "claude-media-fixture" CHAT = "glm-media-fixture" # unpriced clips cost a token per 400 bytes, so a full budget needs a big window. GEMINI_LONG = "gemini-long-media-fixture" CHAT_LONG = "glm-long-media-fixture" LONG = (GEMINI_LONG, CHAT_LONG) MODALITIES = { GEMINI: ["text", "image", "audio", "video"], GEMINI_LONG: ["text", "image", "audio", "video"], CLAUDE: ["text", "image"], CHAT: ["text", "audio"], CHAT_LONG: ["text", "audio"], } MODELS_DEV = { "fixture": { "id": "fixture", "name": "Fixture", "api": "http://127.0.0.1", "models": { model: { "limit": { "context": 2_000_000 if model in LONG else 200000, "output": 4096, }, "modalities": {"input": modalities, "output": ["text"]}, } for model, modalities in MODALITIES.items() }, } } def wav(samples: int = 4) -> bytes: """A whole 16-bit mono WAV of silent samples.""" fmt = struct.pack(" bytes: """An EBML header naming WebM, then a segment that runs to the end.""" doctype = b"\x42\x82\x84webm" segment = b"\xec\x81\x00" return ( b"\x1a\x45\xdf\xa3" + bytes([0x80 | len(doctype)]) + doctype + b"\x18\x53\x80\x67" + bytes([0x80 | len(segment)]) + segment ) def long_webm(size: int) -> bytes: """A WebM whose segment, of unknown size, runs `size` bytes.""" doctype = b"\x42\x82\x84webm" return ( b"\x1a\x45\xdf\xa3" + bytes([0x80 | len(doctype)]) + doctype + b"\x18\x53\x80\x67\x01\xff\xff\xff\xff\xff\xff\xff" + b"\x00" * size ) def mp4() -> bytes: """An ISO BMFF file of brand isom: an ftyp box and an empty moov.""" return ( struct.pack(">I", 20) + b"ftypisom" + struct.pack(">I", 0) + b"isom" + (struct.pack(">I", 8) + b"moov") ) def mp3(frames: int) -> bytes: """MPEG-1 layer III frames at 128 kbps and 44.1 kHz, silent.""" return (b"\xff\xfb\x90\x64" + b"\x00" * 413) * frames WAV, WEBM = wav(), webm() WAV_DATA = base64.b64encode(WAV).decode() WEBM_DATA = base64.b64encode(WEBM).decode() OMITTED = "[1 clip(s) omitted: this model does not read audio/wav]" # past a picture's 5 MiB bound, within a clip's 20 MiB. LONG_MP3 = mp3(15_000) LONG_MP3_DATA = base64.b64encode(LONG_MP3).decode() # past the 256 KiB floor, so it gets a copy. SPOKEN_WAV = wav(200_000) SPOKEN_WAV_DATA = base64.b64encode(SPOKEN_WAV).decode() SHORT_MP3 = mp3(3) SHORT_MP3_DATA = base64.b64encode(SHORT_MP3).decode() # two fill most of opencode go's 12 MiB clip budget as base64, a third won't fit. FULL_FRAMES = 11_000 # about 5 MiB as base64: three fit the 64 MiB budget an openai chat profile has, # two fit opencode go's. WAV_FRAMES = 2_050_000 SHAKEN_WAV = "[audio/wav clip removed by shake]" FFMPEG = """#!/bin/sh tools=$(dirname "$0") printf '%s\\n' "$*" >> "$tools/calls" [ -f "$tools/slow" ] && sleep 2 for out; do :; done [ -f "$tools/encoded.${out##*.}" ] || exit 1 cp "$tools/encoded.${out##*.}" "$out" touch "$tools/finished" """ def answered(request: dict) -> bool: """Whether the request carries a tool result, on the Gemini or Messages wire.""" return "functionResponse" in json.dumps(request) or '"tool_result"' in json.dumps( request ) def asking(provider: Provider, words: str) -> list[dict]: """The requests whose conversation holds `words`.""" return [ request["request"] for request in provider.requests if words in json.dumps(request["request"]) ] def inline_parts(request: dict) -> list[dict]: """Every Gemini part of a request that carries inline data.""" return [ part for content in request["contents"] for part in content["parts"] if "inlineData" in part ] def inline(request: dict) -> list[tuple[str, str]]: """Every Gemini inline part of a request, as (MIME type, base64).""" return [ (part["inlineData"]["mimeType"], part["inlineData"]["data"]) for part in inline_parts(request) ] @exclusive_class class MediaInputTests(unittest.TestCase): def start(self, model: str, script) -> tuple[Albedo, Provider]: provider = Provider( script, catalog={"data": [{"id": model_id} for model_id in MODALITIES]} ) self.addCleanup(provider.close) def offline(app: Albedo) -> None: (app.home / "models.json").write_text(json.dumps(MODELS_DEV)) (app.home / "models.json.index").unlink(missing_ok=True) app.write_extensions({"models": {"refreshHours": 0}}) tools = app.root / "media-tools" tools.mkdir(exist_ok=True) (tools / "ffmpeg").write_text(FFMPEG) (tools / "ffmpeg").chmod(0o755) app.env["PATH"] = str(tools) + os.pathsep + app.env["PATH"] app = Albedo( provider, providers={ "go": { "extension": "opencode-go", "baseUrl": provider.url, "apiKey": "go-key", "model": model, "protocol": "chat_completions", }, # the openai wire keeps albedo's own 64 MiB clip budget. "open": { "baseUrl": provider.url, "apiKey": "open-key", "model": CHAT, "protocol": "chat_completions", }, }, prepare=offline, ) app.__enter__() self.addCleanup(app.__exit__, None, None, None) # tests on one daemon share its fake ffmpeg, so start clears what was left. tools = app.root / "media-tools" for left in [tools / "calls", tools / "slow", tools / "finished"]: left.unlink(missing_ok=True) for left in tools.glob("encoded.*"): left.unlink(missing_ok=True) return app, provider def encodes(self, app: Albedo, extension: str, data: bytes) -> None: """Make the fake ffmpeg answer `data` for an output of `extension`.""" (app.root / "media-tools" / f"encoded.{extension}").write_bytes(data) def encoded(self, app: Albedo) -> list[str]: """The arguments of every ffmpeg run so far.""" calls = app.root / "media-tools" / "calls" return calls.read_text().splitlines() if calls.exists() else [] def use(self, app: Albedo, session: str, model: str, profile: str = "") -> None: with app.api(f"/sessions/{session}/configuration") as response: response.read() etag = response.headers["ETag"] change = {"model": model, **({"provider_profile": profile} if profile else {})} app.api( f"/sessions/{session}/configuration", change, method="PATCH", headers={"If-Match": etag}, ).close() def attach(self, app: Albedo, session: str, mime: str, data: str): return app.api( f"/sessions/{session}/inputs/{operation_id()}", { "kind": "message", "text": "listen", "images": [{"mime_type": mime, "data": data}], }, method="PUT", ) def upload(self, app: Albedo, session: str, upload: str, mime: str, data: bytes): return app.api( f"/sessions/{session}/uploads/{upload}", data, method="PUT", headers={"Content-Type": mime}, ) def send(self, app: Albedo, session: str, words: str, upload: str): return app.api( f"/sessions/{session}/inputs/{operation_id()}", {"kind": "message", "text": words, "images": [{"upload": upload}]}, method="PUT", ) def send_all(self, app: Albedo, session: str, words: str, uploads: list[str]): return app.api( f"/sessions/{session}/inputs/{operation_id()}", { "kind": "message", "text": words, "images": [{"upload": upload} for upload in uploads], }, method="PUT", ) def refusal(self, call) -> tuple[int, str]: with self.assertRaises(urllib.error.HTTPError) as refused: call().close() return refused.exception.code, json.load(refused.exception)["code"] def problem(self, call) -> dict: with self.assertRaises(urllib.error.HTTPError) as refused: call().close() return {"status": refused.exception.code, **json.load(refused.exception)} def edit_queued( self, app: Albedo, provider: Provider, session: str, images: list[dict] ) -> dict: """The problem refusing an edit that puts `images` in a message waiting behind a running turn.""" started, release = threading.Event(), threading.Event() def hold(request: dict): started.set() release.wait(timeout=30) return text("ok") provider.script = hold app.prompt(session, "hold on").close() try: self.assertTrue(started.wait(timeout=30)) waiting = operation_id() app.api( f"/sessions/{session}/inputs/{waiting}", {"kind": "message", "text": "waiting"}, method="PUT", ).close() return self.problem( lambda: app.api( f"/sessions/{session}/inputs/{waiting}/edit", {"kind": "message", "text": "edited", "images": images}, method="POST", ) ) finally: release.set() app.idle(session) def media(self, app: Albedo, session: str) -> dict: with app.api(f"/sessions/{session}/media") as response: return json.load(response) def shake(self, app: Albedo, session: str, media: str): return app.api( f"/sessions/{session}/media/shake", {"media": media}, method="POST" ) def stored(self, app: Albedo, data: bytes) -> bool: """Whether the image store still holds the payload of `data`.""" digest = hashlib.sha256(base64.b64encode(data)).hexdigest() with sqlite3.connect(app.home / "albedo.sqlite") as db: [(count,)] = db.execute( "SELECT count(*) FROM images WHERE hash=?", (digest,) ).fetchall() return count == 1 def test_a_raw_upload_reaches_the_model_once(self) -> None: app, provider = self.start(GEMINI, lambda request: text("ok")) session = app.session() upload = operation_id() with self.upload(app, session, upload, "audio/mpeg", LONG_MP3) as response: kept = json.load(response) self.assertEqual( (kept["id"], kept["mime_type"], kept["size"], kept["width"]), (upload, "audio/mpeg", len(LONG_MP3), 0), ) with self.upload(app, session, upload, "audio/mpeg", LONG_MP3) as response: self.assertEqual(json.load(response), kept) self.assertEqual( self.refusal(lambda: self.upload(app, session, upload, "audio/wav", WAV)), (409, "id_conflict"), ) for mime, data in (("audio/wav", WAV[:-1]), ("video/webm", WAV)): self.assertEqual( self.refusal( lambda: self.upload(app, session, operation_id(), mime, data) ), (400, "image_invalid"), ) sent = {"kind": "message", "text": "listen up", "images": [{"upload": upload}]} operation = operation_id() with app.api( f"/sessions/{session}/inputs/{operation}", sent, method="PUT" ) as response: self.assertEqual(response.status, 202) app.idle(session) # a client that lost the answer re-sends, and the model gets the clip once. self.upload(app, session, upload, "audio/mpeg", LONG_MP3).close() app.api(f"/sessions/{session}/inputs/{operation}", sent, method="PUT").close() self.assertFalse((app.home / "uploads" / session / upload).exists()) self.assertEqual( inline(asking(provider, "listen up")[-1]), [("audio/mpeg", LONG_MP3_DATA)] ) for name in (upload, operation_id()): self.assertEqual( self.refusal(lambda: self.send(app, session, "again", name)), (409, "upload_unknown"), ) self.upload(app, session, operation_id(), "audio/mpeg", LONG_MP3).close() app.delete_tree(session) self.assertFalse((app.home / "uploads" / session).exists()) def test_an_upload_waits_out_a_model_that_cannot_hear_it(self) -> None: app, provider = self.start(CLAUDE, lambda request: text("ok")) session = app.session() upload = operation_id() self.upload(app, session, upload, "audio/wav", WAV).close() self.assertEqual( self.refusal(lambda: self.send(app, session, "hear this", upload)), (409, "image_rejected"), ) self.use(app, session, GEMINI) self.send(app, session, "hear this", upload).close() app.idle(session) self.assertEqual( inline(asking(provider, "hear this")[-1]), [("audio/wav", WAV_DATA)] ) def test_a_cell_shows_clips_to_a_model_that_reads_them(self) -> None: code = ( "import base64\n" f"print(show_image(base64.b64decode({WAV_DATA!r}), base64.b64decode({WEBM_DATA!r})))" ) app, provider = self.start( GEMINI, lambda request: text("heard it") if answered(request) else python(code), ) session = app.session() app.prompt(session, "play them").close() app.idle(session) [sent] = [ request for request in asking(provider, "play them") if answered(request) ] self.assertEqual( inline(sent), [("audio/wav", WAV_DATA), ("video/webm", WEBM_DATA)] ) self.assertIn("Tool result media:", json.dumps(sent)) result = next( part["functionResponse"]["response"]["output"] for content in sent["contents"] for part in content["parts"] if "functionResponse" in part ) self.assertIn("attached audio/wav, 52 bytes", cell_result(result)["output"]) def test_a_cell_shows_a_clip_larger_than_a_result_frame(self) -> None: # past the kernel link's 8 MiB frame, so the clip crosses in raw parts, # and within opencode go's 12 MiB budget as base64. frames = 20_400 code = f"{inspect.getsource(mp3)}\nprint(show_media(mp3({frames})))" app, provider = self.start( GEMINI, lambda request: text("heard it") if answered(request) else python(code), ) session = app.session() app.prompt(session, "play the long one").close() app.idle(session) [sent] = [ request for request in asking(provider, "play the long one") if answered(request) ] clip = mp3(frames) self.assertGreater(len(clip), 8 * 1024 * 1024) self.assertEqual( [ (mime, hashlib.sha256(base64.b64decode(data)).hexdigest()) for mime, data in inline(sent) ], [("audio/mpeg", hashlib.sha256(clip).hexdigest())], ) def test_a_switch_away_from_clips_leaves_a_note_and_refuses_new_ones(self) -> None: app, provider = self.start(GEMINI, lambda request: text("ok")) session = app.session() self.attach(app, session, "audio/wav", WAV_DATA).close() app.idle(session) self.assertEqual( inline(asking(provider, "listen")[-1]), [("audio/wav", WAV_DATA)] ) self.use(app, session, CLAUDE) sent = len(provider.requests) with self.assertRaises(urllib.error.HTTPError) as refused: self.attach(app, session, "audio/wav", WAV_DATA).close() self.assertEqual(refused.exception.code, 409) self.assertIn( "this model does not read audio/wav", json.load(refused.exception)["detail"] ) self.assertEqual(len(provider.requests), sent) edited = self.edit_queued( app, provider, session, [{"mime_type": "audio/wav", "data": WAV_DATA}] ) self.assertEqual((edited["status"], edited["code"]), (409, "image_rejected")) show = f"import base64\nshow_media(base64.b64decode({WAV_DATA!r}))" provider.script = lambda request: ( text("done") if answered(request) else python(show) ) app.prompt(session, "after the switch").close() app.idle(session) switched = asking(provider, "after the switch") self.assertEqual(len(switched), 2) for request in switched: # the cell's source quotes the clip, so only an attachment would carry it. blocks = [ block for message in request["messages"] if isinstance(message["content"], list) for block in message["content"] ] self.assertEqual( [ block for block in blocks if block.get("type") in ("image", "document") ], [], ) self.assertNotIn('"audio/wav"', json.dumps(request)) self.assertIn(OMITTED, json.dumps(request)) result = next( block for message in switched[-1]["messages"] if isinstance(message["content"], list) for block in message["content"] if block.get("type") == "tool_result" ) failed = cell_result(result["content"][0]["text"]) self.assertEqual(failed["status"], "error") self.assertIn( "ValueError: this model does not read audio/wav; it reads no audio or video", failed["output"], ) def test_uploaded_clips_are_served_and_reload_after_a_restart(self) -> None: app, provider = self.start(GEMINI, lambda request: text("ok")) session = app.session() with self.attach(app, session, "video/webm", WEBM_DATA) as response: self.assertEqual(response.status, 202) app.idle(session) self.attach(app, session, "audio/mpeg", LONG_MP3_DATA).close() app.idle(session) [image, long] = [ part["image"] for entry in app.history(session)["items"] if entry["kind"] == "user" for part in entry["content"] if part["kind"] == "image" ] self.assertEqual(long["original_bytes"], len(LONG_MP3)) self.assertEqual( ( image["mime_type"], image["width"], image["height"], image["original_bytes"], ), ("video/webm", 0, 0, len(WEBM)), ) url = image["reference"]["url"] for query in ("", "?edge=256"): with app.api(url + query) as response: self.assertEqual(response.headers["content-type"], "video/webm") self.assertEqual(response.read(), WEBM) for query in ("", "?edge=256"): with app.api(url + query, headers={"Range": "bytes=4-9"}) as response: self.assertEqual(response.status, 206) self.assertEqual( response.headers["content-range"], f"bytes 4-9/{len(WEBM)}" ) self.assertEqual(response.read(), WEBM[4:10]) app.restart() app.prompt(session, "once more").close() app.idle(session) self.assertEqual( inline(asking(provider, "once more")[-1]), [("video/webm", WEBM_DATA), ("audio/mpeg", LONG_MP3_DATA)], ) with app.api(url) as response: self.assertEqual(response.read(), WEBM) with app.api(long["reference"]["url"]) as response: self.assertEqual(response.read(), LONG_MP3) def test_each_model_is_sent_its_own_copy_of_a_long_wav(self) -> None: app, provider = self.start(GEMINI, lambda request: text("ok")) gemini_copy, chat_copy = mp3(3), mp3(4) self.encodes(app, "mp3", gemini_copy) session = app.session() self.attach(app, session, "audio/wav", SPOKEN_WAV_DATA).close() app.idle(session) app.prompt(session, "again").close() app.idle(session) heard = "[1 clip(s) sent re-encoded as 16 kHz mono MP3]" first, second = asking(provider, "listen")[0], asking(provider, "again")[-1] for sent in (first, second): self.assertEqual( inline(sent), [("audio/mpeg", base64.b64encode(gemini_copy).decode())] ) self.assertIn(heard, json.dumps(first["contents"][0])) # the turn after sends the same bytes, so the cached prefix holds. self.assertEqual(first["contents"][0], second["contents"][0]) [run] = self.encoded(app) self.assertIn("-ac 1 -ar 16000 -c:a libmp3lame -b:a 32k", run) self.encodes(app, "mp3", chat_copy) self.use(app, session, CHAT) app.prompt(session, "on chat").close() app.idle(session) sent = asking(provider, "on chat")[-1] [part] = [ part for message in sent["messages"] if isinstance(message["content"], list) for part in message["content"] if part["type"] == "input_audio" ] self.assertEqual( part["input_audio"], {"data": base64.b64encode(chat_copy).decode(), "format": "mp3"}, ) self.assertIn( "[1 clip(s) sent re-encoded as 24 kHz mono MP3]", json.dumps(sent) ) self.assertNotIn(heard, json.dumps(sent)) self.assertIn("-ac 1 -ar 24000 -c:a libmp3lame -b:a 64k", self.encoded(app)[-1]) self.use(app, session, GEMINI) app.prompt(session, "back again").close() app.idle(session) self.assertEqual( asking(provider, "back again")[-1]["contents"][0], first["contents"][0] ) self.assertEqual(len(self.encoded(app)), 2) [clip] = [ part["image"] for entry in app.history(session)["items"] if entry["kind"] == "user" for part in entry["content"] if part["kind"] == "image" ] self.assertEqual( (clip["mime_type"], clip["original_bytes"]), ("audio/wav", len(SPOKEN_WAV)) ) with app.api(clip["reference"]["url"]) as response: self.assertEqual(response.read(), SPOKEN_WAV) source = hashlib.sha256(SPOKEN_WAV_DATA.encode()).hexdigest() copies = "SELECT source, profile FROM image_copies" with sqlite3.connect(app.home / "albedo.sqlite") as db: self.assertEqual( sorted(db.execute(copies).fetchall()), [(source, "1:mp3:16000:32"), (source, "1:mp3:24000:64")], ) self.assertEqual( db.execute( "SELECT count(*) FROM images WHERE hash=?", (source,) ).fetchone(), (1,), ) app.delete_tree(session) with sqlite3.connect(app.home / "albedo.sqlite") as db: self.assertEqual(db.execute(copies).fetchall(), []) def facts(self, app: Albedo, *entries: dict) -> None: """A local model-facts.json of `entries`, gone once the test ends.""" path = app.home / "model-facts.json" path.write_text(json.dumps({"entries": list(entries)})) self.addCleanup(path.unlink, missing_ok=True) def test_a_local_model_fact_changes_the_copy_a_model_is_sent(self) -> None: app, provider = self.start(GEMINI, lambda request: text("ok")) self.facts( app, { "id": "fixture-hearing", "match": {"model": GEMINI}, "media": { "audio": {"sources": ["audio/wav"], "rate": 22000, "kbps": 48} }, }, ) self.encodes(app, "mp3", mp3(3)) session = app.session() self.attach(app, session, "audio/wav", SPOKEN_WAV_DATA).close() app.idle(session) sent = asking(provider, "listen")[-1] self.assertIn( "[1 clip(s) sent re-encoded as 22 kHz mono MP3]", json.dumps(sent) ) [run] = self.encoded(app) self.assertIn("-ac 1 -ar 22000 -c:a libmp3lame -b:a 48k", run) def test_a_wire_without_frame_rates_drops_the_models_bound(self) -> None: show = f"import base64\nshow_media(base64.b64decode({WEBM_DATA!r}), fps=5)" app, provider = self.start( GEMINI, lambda request: text("done") if answered(request) else python(show), ) self.facts( app, {"id": "fixture-slow", "match": {"model": GEMINI}, "media": {"maxFps": 2}}, {"id": "fixture-chat", "match": {"model": CHAT}, "media": {"maxFps": 24}}, ) session = app.session() app.prompt(session, "on gemini").close() app.idle(session) self.assertIn( "this model samples a video at 2 fps at most, not 5", json.dumps(asking(provider, "on gemini")[-1]), ) self.use(app, session, CHAT) show = f"import base64\nshow_media(base64.b64decode({WAV_DATA!r}), fps=1)" provider.script = lambda request: ( text("done") if request["messages"][-1]["role"] == "tool" else python(show) ) app.prompt(session, "on chat").close() app.idle(session) self.assertIn( "ValueError: this model takes no fps for a video", json.dumps(asking(provider, "on chat")[-1]), ) def test_a_copy_finished_after_its_clip_is_deleted_is_not_kept(self) -> None: app, provider = self.start(GEMINI, lambda request: text("ok")) self.encodes(app, "mp3", mp3(3)) tools = app.root / "media-tools" (tools / "slow").touch() session = app.session() self.attach(app, session, "audio/wav", SPOKEN_WAV_DATA).close() deadline = time.monotonic() + 20 while not self.encoded(app) and time.monotonic() < deadline: time.sleep(0.05) self.assertEqual(len(self.encoded(app)), 1) app.delete_tree(session) while not (tools / "finished").exists() and time.monotonic() < deadline: time.sleep(0.05) self.assertTrue((tools / "finished").exists()) time.sleep(1) with sqlite3.connect(app.home / "albedo.sqlite") as db: self.assertEqual( db.execute("SELECT count(*) FROM image_copies").fetchone(), (0,) ) def test_a_model_the_catalog_forgets_keeps_its_clips(self) -> None: app, provider = self.start(GEMINI, lambda request: text("ok")) session = app.session() self.attach(app, session, "audio/wav", WAV_DATA).close() app.idle(session) catalog = app.home / "models.json" kept = catalog.read_bytes() self.addCleanup(catalog.write_bytes, kept) forgot = json.loads(kept) del forgot["fixture"]["models"][GEMINI] catalog.write_text(json.dumps(forgot)) (app.home / "models.json.index").unlink(missing_ok=True) app.prompt(session, "still there").close() app.idle(session) self.assertEqual( inline(asking(provider, "still there")[-1]), [("audio/wav", WAV_DATA)] ) def test_a_long_wav_is_sized_by_how_long_it_plays(self) -> None: app, provider = self.start(GEMINI, lambda request: text("ok")) session = app.session() # opencode go's 12 MiB clip budget takes no 13 MB wav, the openai wire's does. self.use(app, session, GEMINI, "open") route = f"/sessions/{session}/configuration" with app.api(route) as response: etag = response.headers["ETag"] app.api( route, {"context_window": 60000}, method="PATCH", headers={"If-Match": etag}, ).close() for words in ("first", "second"): app.prompt(session, words).close() app.idle(session) # gemini bills audio at 32 tokens a second: 75 seconds of CD audio is 2,400 # tokens, where 400 bytes a token would give 33,000. fmt = struct.pack(" None: app, provider = self.start(GEMINI, lambda request: text("ok")) session = app.session() # ten seconds of movie: a 1000 timescale and a duration of 10000. mvhd = b"mvhd" + bytes(12) + struct.pack(">II", 1000, 10_000) + bytes(80) moov = struct.pack(">I", 8 + 4 + len(mvhd)) + b"moov" movie = mp4()[:20] + moov + struct.pack(">I", 4 + len(mvhd)) + mvhd media = [ ("image/png", png(1, 1)), # fifteen seconds of 8 kHz audio, under the size a copy is made from. ("audio/wav", wav(120_000)), ("video/mp4", movie), ] uploads = [operation_id() for _ in media] for upload, (mime, data) in zip(uploads, media): self.upload(app, session, upload, mime, data).close() self.send_all(app, session, "look and listen", uploads).close() app.idle(session) with app.api(f"/sessions/{session}/context") as response: context = json.load(response) # a picture's 512 px tile, gemini's 32 tokens a second of sound and 66 a # frame at 1 fps, each with 20 for its part. self.assertEqual( context["media_tokens"], {"images": 255 + 20, "audio": 15 * 32 + 20, "video": 10 * (32 + 66) + 20}, ) def test_a_compaction_names_the_clips_it_summarized(self) -> None: app, provider = self.start(GEMINI, lambda request: text("ok")) clip = f"\\n[clip audio/wav, {len(WAV)} bytes; binary omitted]" # rolling recaps the user messages it summarized; coding-lcm keeps the # rows themselves when its summarizer answers nothing. for strategy, summary in (("rolling", "ok"), ("coding-lcm", "")): provider.script = lambda request, summary=summary: text( summary if "newly-evicted-history" in json.dumps(request) else "ok" ) session = app.session() self.attach(app, session, "audio/wav", WAV_DATA).close() app.idle(session) for words in ("first", "second", "third"): app.prompt(session, words + " " + "x" * 6000).close() app.idle(session) response = app.compact(session, {"strategy": strategy}) self.assertEqual(response["state"], "compacted") app.idle(session) app.prompt(session, "after").close() app.idle(session) self.assertIn(clip, json.dumps(provider.requests[-1]), strategy) def test_a_clip_with_no_copy_is_sent_as_it_is(self) -> None: app, provider = self.start(GEMINI, lambda request: text("ok")) session = app.session() # under the 256 KiB floor, so no copy is tried. self.attach(app, session, "audio/mpeg", SHORT_MP3_DATA).close() app.idle(session) self.assertEqual(self.encoded(app), []) # the failed encode is kept and never tried again. self.attach(app, session, "audio/wav", SPOKEN_WAV_DATA).close() app.idle(session) app.prompt(session, "still there").close() app.idle(session) self.assertEqual( inline(asking(provider, "still there")[-1]), [("audio/mpeg", SHORT_MP3_DATA), ("audio/wav", SPOKEN_WAV_DATA)], ) self.assertNotIn("re-encoded", json.dumps(provider.requests)) self.assertEqual(len(self.encoded(app)), 1) def test_chat_copies_only_lossless_audio(self) -> None: app, provider = self.start(CHAT, lambda request: text("ok")) self.encodes(app, "mp3", mp3(3)) session = app.session() self.attach(app, session, "audio/mpeg", LONG_MP3_DATA).close() app.idle(session) self.assertEqual(self.encoded(app), []) self.assertIn(LONG_MP3_DATA, json.dumps(asking(provider, "listen")[-1])) def test_a_video_shown_at_an_fps_keeps_it_across_a_restart(self) -> None: video = long_webm(300_000) code = f"{inspect.getsource(long_webm)}\nprint(show_media(long_webm(300_000), fps=5))" app, provider = self.start( GEMINI, lambda request: text("seen") if answered(request) else python(code), ) self.encodes(app, "mp4", mp4()) session = app.session() app.prompt(session, "watch it").close() app.idle(session) app.restart() provider.script = lambda request: text("still seen") app.prompt(session, "after the restart").close() app.idle(session) copied = { "inlineData": { "mimeType": "video/mp4", "data": base64.b64encode(mp4()).decode(), }, "videoMetadata": {"fps": 5}, } note = ( "[1 clip(s) sent re-encoded as H.264 MP4 at 5 fps within 768 px, " "with 16 kHz mono sound]" ) shown = next( request for request in asking(provider, "watch it") if answered(request) ) for sent in (shown, asking(provider, "after the restart")[-1]): self.assertEqual(inline_parts(sent), [copied]) self.assertIn(note, json.dumps(sent)) [run] = self.encoded(app) self.assertIn("-vf fps=5.0,scale=w='min(768,iw)'", run) self.assertIn("-c:v libx264", run) self.assertIn("-ac 1 -ar 16000 -c:a aac -b:a 32k", run) [clip] = [ part["image"] for entry in app.history(session)["items"] if entry["kind"] == "tool_result" for part in entry["content"] if part["kind"] == "image" ] self.assertEqual( (clip["mime_type"], clip["original_bytes"]), ("video/webm", len(video)) ) with app.api(clip["reference"]["url"]) as response: self.assertEqual(response.read(), video) def test_a_clip_a_cell_shows_while_albedo_is_down_survives_its_recovery( self, ) -> None: # the kernel holds the parts in its outbox while no daemon listens. video = long_webm(5 * 1024 * 1024) app, provider = self.start(GEMINI, lambda request: text("ok")) clip, started, release = ( app.root / "down.webm", app.root / "down.started", app.root / "down.release", ) clip.write_bytes(video) code = ( "import asyncio, pathlib\n" f"pathlib.Path({str(started)!r}).touch()\n" f"while not pathlib.Path({str(release)!r}).exists():\n" " await asyncio.sleep(0.05)\n" f"show_media({str(clip)!r})\n" "print('shown while albedo was down')" ) provider.script = lambda request: ( text("seen") if answered(request) else python(code) ) session = app.session() app.prompt(session, "show it while down").close() deadline = time.monotonic() + 30 while not started.exists(): self.assertLess(time.monotonic(), deadline, "the cell never started") time.sleep(0.05) def finish(_: Albedo) -> None: release.touch() time.sleep(2) app.restart(crash=True, prepare=finish) app.idle(session) [entry] = [ entry for entry in app.history(session)["items"] if entry["kind"] == "tool_result" ] result = cell_result( next(part["value"] for part in entry["content"] if part["kind"] == "json") ) self.assertEqual(result["status"], "ok") self.assertIn("shown while albedo was down", result["output"]) self.assertEqual(result.get("image_errors", []), []) [shown] = [ part["image"] for part in entry["content"] if part["kind"] == "image" ] with app.api(shown["reference"]["url"]) as response: self.assertEqual(response.read(), video) def test_a_clip_a_restart_interrupts_survives_its_recovery(self) -> None: # the old daemon acks the parts before it stops, the new one claims the result. video = long_webm(5 * 1024 * 1024) app, provider = self.start(GEMINI, lambda request: text("ok")) clip, shown = app.root / "stopped.webm", app.root / "stopped.shown" clip.write_bytes(video) code = ( "import asyncio, pathlib\n" f"show_media({str(clip)!r})\n" f"pathlib.Path({str(shown)!r}).touch()\n" "await asyncio.sleep(60)" ) provider.script = lambda request: ( text("seen") if answered(request) else python(code) ) session = app.session() app.prompt(session, "show it, then stop").close() deadline = time.monotonic() + 30 while not shown.exists(): self.assertLess(time.monotonic(), deadline, "the cell never showed it") time.sleep(0.05) app.restart() app.idle(session) [entry] = [ entry for entry in app.history(session)["items"] if entry["kind"] == "tool_result" ] result = cell_result( next(part["value"] for part in entry["content"] if part["kind"] == "json") ) self.assertEqual(result.get("image_errors", []), []) [image] = [ part["image"] for part in entry["content"] if part["kind"] == "image" ] with app.api(image["reference"]["url"]) as response: self.assertEqual(response.read(), video) def test_show_media_refuses_an_fps_the_model_cannot_take(self) -> None: tries = [ ("wav", f"base64.b64decode({WAV_DATA!r})", 5), ("over", f"base64.b64decode({WEBM_DATA!r})", 25), ("zero", f"base64.b64decode({WEBM_DATA!r})", 0), ( "mixed", f"base64.b64decode({WEBM_DATA!r}), base64.b64decode({WAV_DATA!r})", 5, ), ] code = "import base64\n" + "".join( f"try:\n show_media({items}, fps={fps})\n" f"except ValueError as refused:\n print({name!r}, refused)\n" for name, items, fps in tries ) # past the kernel's check, the daemon refuses the rate itself. code += ( "import albedo_cells\n" "albedo_cells.CELL.get().max_fps = 100\n" f"show_media(base64.b64decode({WEBM_DATA!r}), fps=30)\n" # one attachment carries one rate, so the same bytes at another are refused. f"try:\n show_media(base64.b64decode({WEBM_DATA!r}), fps=10)\n" "except ValueError as refused:\n print('again', refused)\n" ) app, provider = self.start( GEMINI, lambda request: text("done") if answered(request) else python(code), ) session = app.session() app.prompt(session, "try them").close() app.idle(session) [sent] = [ request for request in asking(provider, "try them") if answered(request) ] self.assertEqual(inline_parts(sent), []) result = cell_result( next( part["functionResponse"]["response"]["output"] for content in sent["contents"] for part in content["parts"] if "functionResponse" in part ) ) self.assertEqual( result["image_errors"], ["this model samples a video at 24 fps at most, not 30"], ) self.assertEqual( result["output"].splitlines(), [ "wav fps is for a video, not audio/wav; show it without fps", "over this model samples a video at 24 fps at most, not 25", "zero fps must be a number above 0, not 0", "mixed fps is for a video, not audio/wav; show it without fps", "again this video is already attached at 30 fps in this cell; " "show it once per cell", ], ) self.use(app, session, CHAT) show = f"import base64\nshow_media(base64.b64decode({WAV_DATA!r}), fps=1)" provider.script = lambda request: ( text("done") if request["messages"][-1]["role"] == "tool" else python(show) ) app.prompt(session, "on chat").close() app.idle(session) self.assertIn( "ValueError: this model takes no fps for a video; " "it samples video at its own rate", json.dumps(asking(provider, "on chat")[-1]), ) def cell_results(self, request: dict) -> list[dict]: return [ cell_result(part["functionResponse"]["response"]["output"]) for content in request["contents"] for part in content["parts"] if "functionResponse" in part ] def test_show_media_holds_to_the_room_only_the_clips_it_attaches(self) -> None: # room for one wav, and a clip shown twice still takes it once. code = ( "import albedo_cells\n" f"albedo_cells.CELL.get().clip_room = {len(WAV_DATA)}\n" f"print(show_media({WAV!r}, {WAV!r}))\n" f"show_media({png(2, 2)!r}, {png(3, 3)!r}, {png(4, 4)!r})\n" f"print(show_media({wav(50)!r}))\n" ) app, provider = self.start( GEMINI, lambda request: text("done") if answered(request) else python(code) ) session = app.session() app.prompt(session, "show them").close() app.idle(session) sent = asking(provider, "show them")[-1] [result] = self.cell_results(sent) self.assertEqual(result["status"], "ok", result["output"]) self.assertIn( f"attached audio/wav, {len(WAV)} bytes\n" f"already attached audio/wav, {len(WAV)} bytes\n", result["output"], ) self.assertIn( "not attached, this cell's 4 attachments is full: saved to", result["output"], ) self.assertEqual(len(inline(sent)), 4) def test_a_nested_cell_names_where_its_overflow_went(self) -> None: inner = "show_media(" + ", ".join(repr(png(n, n)) for n in (5, 6)) + ")\n" outer = ( "show_media(" + ", ".join(repr(png(n, n)) for n in (2, 3, 4)) + ")\n" "saved = (await cells.list(limit=2))[1]['id']\n" "await cells.run(saved, replacements=[('fail()', 'pass')], " "allow_partial=True)\n" ) cells = iter([python(inner + "fail()\n"), python(outer)]) app, provider = self.start(GEMINI, lambda request: next(cells, text("done"))) session = app.session() app.prompt(session, "nest them").close() app.idle(session) [_, result] = self.cell_results(asking(provider, "nest them")[-1]) self.assertEqual(result["status"], "ok", result["output"]) self.assertRegex( result["output"], r"\[image from cell \w+ not attached, this cell's 4 attachments " r"is full: saved to \S+", ) def test_chat_completions_sends_audio_as_input_audio(self) -> None: app, provider = self.start(CHAT, lambda request: text("ok")) session = app.session() self.attach(app, session, "audio/wav", WAV_DATA).close() app.idle(session) [part] = [ part for message in asking(provider, "listen")[-1]["messages"] if isinstance(message["content"], list) for part in message["content"] if part["type"] == "input_audio" ] self.assertEqual(part["input_audio"], {"data": WAV_DATA, "format": "wav"}) with self.assertRaises(urllib.error.HTTPError) as refused: self.attach(app, session, "video/webm", WEBM_DATA).close() self.assertEqual(refused.exception.code, 409) def test_clips_past_the_request_budget_are_refused_where_they_arrive(self) -> None: app, provider = self.start(GEMINI_LONG, lambda request: text("ok")) session = app.session() full = mp3(FULL_FRAMES) uploads = [operation_id() for _ in range(3)] for upload in uploads: self.upload(app, session, upload, "audio/mpeg", full).close() refused = self.problem(lambda: self.send_all(app, session, "all", uploads)) self.assertEqual((refused["status"], refused["code"]), (409, "media_budget")) self.assertIn("/shake", refused["detail"]) self.send_all(app, session, "these two", uploads[:2]).close() app.idle(session) self.assertEqual(len(inline(asking(provider, "these two")[-1])), 2) # the history's clips count toward the budget too. refused = self.problem(lambda: self.send(app, session, "a third", uploads[2])) self.assertEqual((refused["status"], refused["code"]), (409, "media_budget")) self.assertIn("already hold 11.7 MiB of the 12 MiB", refused["detail"]) edited = self.edit_queued(app, provider, session, [{"upload": uploads[2]}]) self.assertEqual((edited["status"], edited["code"]), (409, "media_budget")) listed = self.media(app, session) self.assertEqual(listed["clips_held"], 2 * len(base64.b64encode(full))) self.assertEqual(listed["clip_budget"], 12 * 1024 * 1024) # past the kernel's check, the daemon holds the clip back itself. code = ( f"{inspect.getsource(mp3)}\n" "try:\n show_media(mp3(30_000))\n" "except ValueError as refused:\n print(refused)\n" "import albedo_cells\n" "albedo_cells.CELL.get().clip_room = None\n" "show_media(mp3(30_000))\n" ) provider.script = lambda request: ( text("done") if answered(request) else python(code) ) provider.requests.clear() app.prompt(session, "one more").close() app.idle(session) [sent] = [ request for request in asking(provider, "one more") if answered(request) ] self.assertEqual(len(inline(sent)), 2) result = cell_result( next( part["functionResponse"]["response"]["output"] for content in sent["contents"] for part in content["parts"] if "functionResponse" in part ) ) adding = len(base64.b64encode(mp3(30_000))) / 2**20 room = (12 * 2**20 - listed["clips_held"]) / 2**20 self.assertIn( f"these clips take {adding:.1f} MiB as base64, and the session's next " f"request has room for {room:.1f} MiB more; await commands.shake()", result["output"], ) [kept_back] = result["image_errors"] self.assertTrue(kept_back.startswith("audio/mpeg clip not attached: ")) self.assertIn("await commands.shake()", kept_back) def test_clips_a_compaction_left_out_free_their_room(self) -> None: app, provider = self.start(GEMINI_LONG, lambda request: text("ok")) session = app.session() clips = [mp3(FULL_FRAMES + index) for index in range(3)] uploads = [operation_id() for _ in clips] for upload, clip in zip(uploads, clips): self.upload(app, session, upload, "audio/mpeg", clip).close() for index in range(2): self.send(app, session, f"clip {index}", uploads[index]).close() app.idle(session) held = sum(len(base64.b64encode(clip)) for clip in clips[:2]) self.assertEqual(self.media(app, session)["clips_held"], held) for index in range(4): app.prompt(session, f"filler {index} " + "words " * 50).close() app.idle(session) self.assertEqual(app.compact(session)["state"], "compacted") room = "import albedo_cells\nprint(albedo_cells.CELL.get().clip_room)" provider.script = lambda request: ( text("done") if answered(request) else python(room) ) app.prompt(session, "after compaction").close() app.idle(session) [first, sent] = asking(provider, "after compaction") self.assertEqual(inline(first), []) [result] = self.cell_results(sent) self.assertEqual(result["output"].strip(), str(12 * 1024 * 1024)) self.assertEqual(self.media(app, session)["clips_held"], 0) provider.script = lambda request: text("ok") # after a restart every clip counts until the next request is prepared. app.restart() self.assertEqual(self.media(app, session)["clips_held"], held) refused = self.problem(lambda: self.send(app, session, "a third", uploads[2])) self.assertEqual((refused["status"], refused["code"]), (409, "media_budget")) app.prompt(session, "after the restart").close() app.idle(session) with self.send(app, session, "a third", uploads[2]) as response: self.assertEqual(response.status, 202) def test_a_switch_to_a_wire_with_a_smaller_budget_trims_the_same_each_time( self, ) -> None: app, provider = self.start(GEMINI_LONG, lambda request: text("ok")) session = app.session() self.use(app, session, CHAT_LONG, "open") self.assertEqual(self.media(app, session)["clip_budget"], 64 * 1024 * 1024) # no ffmpeg copy, so every clip goes as it is. clips = [wav(WAV_FRAMES + index) for index in range(3)] for index, clip in enumerate(clips): upload = operation_id() self.upload(app, session, upload, "audio/wav", clip).close() with self.send(app, session, f"clip {index}", upload) as response: self.assertEqual(response.status, 202) app.idle(session) self.use(app, session, GEMINI_LONG, "go") listed = self.media(app, session) self.assertEqual(listed["clip_budget"], 12 * 1024 * 1024) self.assertGreater(listed["clips_held"], listed["clip_budget"]) provider.requests.clear() for words in ("first after", "second after"): app.prompt(session, words).close() app.idle(session) first, second = ( asking(provider, "first after")[0], asking(provider, "second after")[-1], ) sent = [ hashlib.sha256(base64.b64decode(data)).hexdigest() for _, data in inline(first) ] self.assertEqual(sent, [hashlib.sha256(clip).hexdigest() for clip in clips[1:]]) self.assertIn( "[1 clip(s) omitted: newer clips fill this request's media budget]", json.dumps(first["contents"][0]), ) self.assertEqual( second["contents"][: len(first["contents"])], first["contents"] ) refused = self.problem(lambda: self.attach(app, session, "audio/wav", WAV_DATA)) self.assertEqual((refused["status"], refused["code"]), (409, "media_budget")) self.assertIn("of the 12 MiB one request carries", refused["detail"]) room = "import albedo_cells\nprint(albedo_cells.CELL.get().clip_room)" provider.script = lambda request: ( text("done") if answered(request) else python(room) ) app.prompt(session, "how much room").close() app.idle(session) [result] = self.cell_results( next(r for r in asking(provider, "how much room") if answered(r)) ) self.assertEqual(result["output"].strip(), "0") def test_shake_drops_media_by_kind_and_by_id(self) -> None: picture = png(2, 2) show = ( "import base64\n" f"show_media(base64.b64decode({WEBM_DATA!r}), base64.b64decode({WAV_DATA!r}))" ) app, provider = self.start( GEMINI, lambda request: text("seen") if answered(request) else python(show), ) session = app.session() app.api( f"/sessions/{session}/inputs/{operation_id()}", { "kind": "message", "text": "look and listen", "images": [ {"mime_type": "audio/wav", "data": WAV_DATA}, { "mime_type": "image/png", "data": base64.b64encode(picture).decode(), }, ], }, method="PUT", ).close() app.idle(session) listed = {item["mime_type"]: item for item in self.media(app, session)["media"]} self.assertEqual(sorted(listed), ["audio/wav", "image/png", "video/webm"]) heard = listed["audio/wav"] self.assertEqual(len(heard["id"]), 8) self.assertEqual( [place["from"] for place in heard["places"]], ["message", "tool_result"] ) self.assertEqual( self.refusal(lambda: self.shake(app, session, "0000ffff")), (409, "shake_refused"), ) with self.shake(app, session, "audio") as response: shaken = json.load(response) self.assertEqual([item["id"] for item in shaken["shaken"]], [heard["id"]]) self.assertEqual(shaken["rows"], 2) self.assertIn("prompt cache", shaken["message"]) self.assertFalse(self.stored(app, WAV)) provider.script = lambda request: text("after") app.prompt(session, "after the shake").close() app.idle(session) sent = asking(provider, "after the shake")[-1] self.assertEqual( sorted(mime for mime, _ in inline(sent)), ["image/png", "video/webm"] ) self.assertEqual(json.dumps(sent).count(SHAKEN_WAV), 2) history = json.dumps(app.history(session)) self.assertEqual(history.count(SHAKEN_WAV), 2) self.assertNotIn('"audio/wav"', history) # the fork still names the picture, so shaking it here keeps its payload. checkpoint = [ entry["checkpoint_id"] for entry in app.history(session)["items"] if entry["kind"] == "user" ][-1] fork = operation_id() app.api( f"/sessions/{fork}", {"kind": "fork", "source_session_id": session, "checkpoint_id": checkpoint}, method="PUT", headers={"If-None-Match": "*"}, ).close() self.shake(app, session, listed["image/png"]["id"]).close() self.assertTrue(self.stored(app, picture)) self.assertIn( "[image/png image removed by shake]", json.dumps(app.history(session)) ) self.shake(app, fork, "image").close() self.assertFalse(self.stored(app, picture)) self.assertTrue(self.stored(app, WEBM)) self.assertEqual( [item["mime_type"] for item in self.media(app, session)["media"]], ["video/webm"], ) def test_a_shake_between_attempts_leaves_the_retry_its_clip(self) -> None: started, release = threading.Event(), threading.Event() attempts = [] def script(request: dict): attempts.append(request) if len(attempts) == 1: started.set() release.wait(timeout=30) return error(503) return text("heard") app, provider = self.start(GEMINI, script) session = app.session() self.attach(app, session, "audio/wav", WAV_DATA).close() self.assertTrue(started.wait(timeout=30)) try: with self.shake(app, session, "all") as response: self.assertEqual(response.status, 200) finally: release.set() snapshot = app.idle(session) self.assertEqual(snapshot["status"]["phase"], "idle") # the retry resends the request built before the shake. self.assertEqual(len(attempts), 2) self.assertEqual(inline(attempts[1]), [("audio/wav", WAV_DATA)]) history = json.dumps(app.history(session)) self.assertIn("heard", history) self.assertIn(SHAKEN_WAV, history) # with the turn over, nothing reads the payload. self.assertFalse(self.stored(app, WAV)) def test_the_model_shakes_a_clip_out_of_its_own_turn(self) -> None: shake = "print((await commands.shake('audio'))['message'])" app, provider = self.start( GEMINI, lambda request: text("lighter") if answered(request) else python(shake), ) session = app.session() self.attach(app, session, "audio/wav", WAV_DATA).close() app.idle(session) before, after = asking(provider, "listen") self.assertEqual(inline(before), [("audio/wav", WAV_DATA)]) # the turn's next request reads the history the shake rewrote. self.assertEqual(inline(after), []) self.assertIn(SHAKEN_WAV, json.dumps(after)) self.assertIn("Removed 1 audio clip(s)", json.dumps(after)) if __name__ == "__main__": unittest.main()