A local-first multi-agent app development platform, built on PenguinHarness
fix(server,web): 视频判定两边读同一份,并补上真浏览器用例
lmlihengd162438bafd8
diff --git a/changelog/unreleased/2026-10-26-video-input.md b/changelog/unreleased/2026-10-26-video-input.mdindex 9655bdd3..476a57e2 100644--- a/changelog/unreleased/2026-10-26-video-input.md+++ b/changelog/unreleased/2026-10-26-video-input.md@@ -42,10 +42,21 @@ with its own tools. The frontend never asks you which kind of model this is; the`GET /api/sessions/:id/trace-video?file=&ordinal=`, in `services/trace-media.ts` — the old`trace-images.ts` was renamed into it), or one page would read tens of megabytes of base64 whole.Recalling an undelivered message (#287) hands an inline video back to the composer as submitted.+- **Both sides read the same two sources.** Whether a clip rides inline or becomes a file is+ decided twice — by the composer, from the model it is given, and by the task/steer routes. Those+ answers have to agree: a model marked `video = true` by hand (a row the catalog does not know)+ was offered video input by the composer while the routes, reading the catalog alone, filed the+ clip away as a scratchpad attachment without a word. The routes now read the Project entry first+ and fall back to the catalog, exactly as the model list does.- Docs: the notes in `models.zh.md` / `models.en.md` carry the **Video** label and both paths.- Tests: `server/test/video-input.test.ts` (inline / written to disk / a nameless clip named after- its type / a non-video data URL / the 413 / both steering paths) and- `server/test/trace-media.test.ts` (video by reference, its bytes and type, the 404s and 400s).+ its type / a non-video data URL / the 413 / both steering paths / a Project entry marked+ `video = true` on a model the catalog never heard of) and+ `server/test/trace-media.test.ts` (video by reference, its bytes and type, the 404s and 400s);+ `web/e2e/video-input.spec.mjs` runs the whole path in a real browser — the composer stages a real+ 1-second WebM, the model is handed the `video_url` part with the very bytes that were picked+ (answered by the mock's new Chat Completions branch), the browser decodes the clip in the+ transcript, and a reloaded page is served it by reference.## Compatibilitydiff --git a/changelog/unreleased/2026-10-26-video-input.zh.md b/changelog/unreleased/2026-10-26-video-input.zh.mdindex a51707f0..36f0b4bd 100644--- a/changelog/unreleased/2026-10-26-video-input.zh.md+++ b/changelog/unreleased/2026-10-26-video-input.zh.md@@ -34,9 +34,17 @@`GET /api/sessions/:id/trace-video?file=&ordinal=`,由 `services/trace-media.ts` 提供,旧的`trace-images.ts` 一并改名合并),否则一页历史要把几十兆 base64 整份读回来。撤回未发出的消息(#287)也会把内联视频原样还回输入框。+- **两边读同一份答案**:一段片子是内联发出去还是落成文件,要判两次——一次在输入框(按它拿到的模型),一次在+ 任务与 steer 两条路由上。这两个答案必须一致:手工标了 `video = true` 的模型(目录里没有这一条),输入框会+ 给出视频入口,而路由只看目录,于是把片子悄悄落成暂存目录的附件。现在路由先读 Project 里那一条、再退回目录,+ 与模型列表的算法完全相同。- 文档:`models.zh.md` / `models.en.md` 的笔记里写明「视频」标签与两种走法。- 测试:`server/test/video-input.test.ts`(内联 / 落盘 / 无名视频按类型命名 / 非视频数据 URL / 超限 413 /- 中途 steering 的两种走法)、`server/test/trace-media.test.ts`(视频按引用、字节与类型、404 与 400)。+ 中途 steering 的两种走法 / Project 里手工标了 `video = true` 的目录外模型)、+ `server/test/trace-media.test.ts`(视频按引用、字节与类型、404 与 400);`web/e2e/video-input.spec.mjs`+ 在真浏览器里跑完整条路——输入框放进去一段真的 1 秒 WebM,模型收到的是带**原来那些字节**的 `video_url` 部件+ (由假模型新增的 Chat Completions 分支回话证实),浏览器在消息里真的解出了这段片子,刷新后同一段片子改按引用+ 取回。## 兼容性diff --git a/packages/server/src/http/routes/sessions.ts b/packages/server/src/http/routes/sessions.tsindex af28d086..e4d418c0 100644--- a/packages/server/src/http/routes/sessions.ts+++ b/packages/server/src/http/routes/sessions.ts@@ -473,15 +473,39 @@ interface ParsedTaskInput {videos: string[];}+/**+ * Whether the Session's model takes video input — the answer the composer was handed for the+ * same Session, read from the same two places in the same order (`ModelInfo.video`): the+ * Project's own entry may carry the `video` annotation (a model the catalog does not know, added+ * by hand), otherwise the built-in catalog records it for a preset (core's+ * `catalogSupportsVideo`).+ *+ * The two must agree or a clip is silently misdelivered: the composer offers video input because+ * `ModelInfo.video` is true, so a send hands over a `video_url` part — and this is the only+ * thing that decides whether that part rides inline or becomes a file attachment.+ */+async function sessionTakesVideo(deps: SessionsRouteDeps, row: SessionRow): Promise<boolean> {+ if (catalogSupportsVideo(row.provider, row.modelId)) return true;+ try {+ const project = await deps.projectConfigService.loadConfig(row.projectId);+ const entry = (project.models ?? []).find(+ (m) => m.provider === row.provider && m.model_id === row.modelId,+ );+ return entry?.video === true;+ } catch {+ // An unreadable config leaves the catalog's answer, which was already "no".+ return false;+ }+}+/*** Validate Prompt input parts: text, image (data: / http(s) URL), video (same, when the* Session's model takes one) or an uploaded file.*- * `videoInput` = whether the Session's model takes video input (core's- * `catalogSupportsVideo`, matching what the model entry is built with). A `video_url` part is- * accepted either way, but only rides inline when it is true: on any other model the clip is- * turned into an ordinary file attachment, so one composer draft is sendable to either kind of- * model and the user is not left to guess which one they are talking to.+ * `videoInput` = whether the Session's model takes video input (see sessionTakesVideo). A+ * `video_url` part is accepted either way, but only rides inline when it is true: on any other+ * model the clip is turned into an ordinary file attachment, so one composer draft is sendable+ * to either kind of model and the user is not left to guess which one they are talking to.*/function parseTaskInput(body: Record<string, unknown>,@@ -1397,8 +1421,8 @@ export function sessionsRoutes(deps: SessionsRouteDeps): Hono<AppEnv> {const limits = toAttachmentLimits(deps.serverSettingsRepo.getAttachmentLimitsMb());// Whether the Session's model takes video input decides how a `video_url` part travels:// inline on a video model, as an ordinary file attachment on any other (see- // parseTaskInput). Read from the same catalog the model entry is built from.- const videoInput = catalogSupportsVideo(row.provider, row.modelId);+ // parseTaskInput). The same answer the composer's own send path was built from.+ const videoInput = await sessionTakesVideo(deps, row);if (goal) {// Goal mode: the input needs non-empty text, since its marker-stripped text becomes the// objective that every round re-injects and an image on its own doesn't say what the@@ -1484,8 +1508,8 @@ export function sessionsRoutes(deps: SessionsRouteDeps): Hono<AppEnv> {const text = typeof body.text === "string" ? body.text.trim() : "";const images = parseSteerImages(body);// Inline video only where the model takes it: a mid-run message has no model picker of- // its own, so the same catalog answer the Session was built with decides.- const videos = parseSteerVideos(body, catalogSupportsVideo(row.provider, row.modelId));+ // its own, so the same answer the Session (and its composer) was built with decides.+ const videos = parseSteerVideos(body, await sessionTakesVideo(deps, row));const files = parseSteerFiles(body,toAttachmentLimits(deps.serverSettingsRepo.getAttachmentLimitsMb()),diff --git a/packages/server/test/video-input.test.ts b/packages/server/test/video-input.test.tsindex fe1ac3d7..045e2083 100644--- a/packages/server/test/video-input.test.ts+++ b/packages/server/test/video-input.test.ts@@ -3,8 +3,9 @@* `videos` field.** - On a Session whose model takes video input (the Volcengine Ark Seed family — core's- * `catalogSupportsVideo`), the clip rides inline as a user video message, which is the shape- * the provider's request is assembled from, and nothing is written to disk.+ * `catalogSupportsVideo`, or the Project's own `video` annotation for a model the catalog does+ * not know), the clip rides inline as a user video message, which is the shape the provider's+ * request is assembled from, and nothing is written to disk.* - On any other model it becomes an ordinary file attachment: the bytes land in the scratchpad* and the Prompt gains an `[attached file: <path>]` line, so one composer draft is sendable* to either kind of model instead of being refused for the model's choice.@@ -22,6 +23,7 @@ import {approvalDecision,assistantText,modelVisiblePath,+ saveProjectConfig,scratchpadDir,toolCall,userText,@@ -130,6 +132,50 @@ describe("video input", () => {expect(await fs.readdir(dir).catch(() => [])).toEqual([]);});+ it("a Project entry marked video rides inline even when the catalog never heard of the model", async () => {+ // The other half of the composer's own answer (`ModelInfo.video`): a row the user marked+ // `video = true` by hand. The catalog knows nothing about it, so the Project config is the+ // only place that says the model takes a clip — and if the two sides disagreed, the+ // composer would inline a video into a part the route would quietly file away instead.+ const own = { provider: "custom", modelId: "my-own-video-model" };+ await saveProjectConfig(t.root, PROJECT, {+ models: [+ { provider: own.provider, model_id: own.modelId, client_type: "openai-chat", video: true },+ ],+ });+ adoptSession(t.deps, recordingFakeSession(SID, runs), { projectId: PROJECT, ...own });+ const res = await api.post(`/api/sessions/${SID}/tasks`, {+ input: [+ { type: "text", text: "what happens in this clip?" },+ { type: "video_url", videoUrl: CLIP, fileName: "clip.mp4" },+ ],+ });+ expect(res.status).toBe(202);+ await waitFor(() => runs.length === 1);++ expect(videoOf(runs[0]!)?.video_url).toBe(CLIP);+ expect(await fs.readdir(dir).catch(() => [])).toEqual([]);+ });++ it("the same Project annotation lets a steered video ride inline", async () => {+ const own = { provider: "custom", modelId: "my-own-video-model" };+ await saveProjectConfig(t.root, PROJECT, {+ models: [{ provider: own.provider, model_id: own.modelId, video: true }],+ });+ const steered: OmniMessage[][] = [];+ adoptSession(t.deps, steeringFakeSession(SID, steered), {+ projectId: PROJECT,+ approvalMode: "always-ask",+ ...own,+ });+ await t.deps.manager.startTask(SID, [userText("go")]);+ await waitFor(() => t.deps.manager.pendingApprovalCount(SID) === 1);++ const posted = await api.post(`/api/sessions/${SID}/steer`, { videos: [CLIP] });+ expect(posted.status).toBe(202);+ expect(videoOf(steered[0]!)?.video_url).toBe(CLIP);+ });+it("a video on a model without video input lands in the scratchpad as a file attachment", async () => {adoptSession(t.deps, recordingFakeSession(SID, runs), { projectId: PROJECT });const res = await api.post(`/api/sessions/${SID}/tasks`, {diff --git a/packages/web/e2e/mock-llm.mjs b/packages/web/e2e/mock-llm.mjsindex dc803fea..5aaf6078 100644--- a/packages/web/e2e/mock-llm.mjs+++ b/packages/web/e2e/mock-llm.mjs@@ -1,6 +1,9 @@/**- * Mock Anthropic Messages API (streaming SSE) for E2E.- * Branches on request body:+ * Mock LLM for E2E. Two protocols, chosen by the request's own path:+ * - `/chat/completions` -> the OpenAI Chat Completions branch (openAiChatCompletion), which is+ * where a model pinned to `client_type = "openai-chat"` reaches this process (every Volcengine+ * Ark row of the catalog does).+ * - anything else -> the Anthropic Messages API branch below, which "Branches on request body:"* - title request (the prompt opens with "You are a title generator.") -> short text* - files-card probe ("files card test") -> text with two backtick paths (one real, one missing)* - "files rewrite test <cmd>" -> tool_use(exec_command) running <cmd>, then a short final text@@ -97,6 +100,68 @@ function block(res, index, start, deltas, extra) {sse(res, "content_block_stop", { type: "content_block_stop", index });}+/**+ * One OpenAI Chat Completions request: `chat.completion.chunk` frames, closed by `data: [DONE]`.+ *+ * video-input.spec drives the video case: the composer inlines a clip on a model that takes one,+ * and this answer says back what the model was handed — the media type and the payload's own byte+ * length — so the spec can prove the `video_url` part reached the provider through AgentHub's+ * patched transformer rather than being dropped, and that it was still the bytes the person+ * picked. A request with no video part says so instead (which is how the spec catches a+ * "silently filed away as an attachment" regression).+ *+ * Core's session-title request goes to the same model, so it is answered here too (a one-line+ * title) rather than being mistaken for a conversation turn needing a video.+ */+function openAiChatCompletion(res, json) {+ const messages = Array.isArray(json.messages) ? json.messages : [];+ const parts = messages.flatMap((m) => (Array.isArray(m.content) ? m.content : []));+ const text = parts+ .filter((p) => p !== null && p.type === "text" && typeof p.text === "string")+ .map((p) => p.text)+ .join("\n");+ const video = parts.find((p) => p !== null && p.type === "video_url");+ const url = video !== undefined && video.video_url ? String(video.video_url.url ?? "") : "";+ const comma = url.indexOf(",");+ const mime = /^data:([^;,]*)/.exec(url)?.[1] ?? "";+ const bytes =+ comma < 0 ? 0 : Math.floor((url.slice(comma + 1).replace(/[=\s]/g, "").length * 3) / 4);+ const answer = text.includes("You are a title generator.")+ ? "Clip check"+ : video !== undefined+ ? `Saw a video: ${mime}, ${bytes} bytes.`+ : "No video in this request.";++ res.writeHead(200, {+ "content-type": "text/event-stream",+ "cache-control": "no-cache",+ connection: "keep-alive",+ });+ const chunk = (delta, finish = null) =>+ `data: ${JSON.stringify({+ id: "chatcmpl-mock",+ object: "chat.completion.chunk",+ created: 0,+ model: json.model ?? "mock",+ choices: [{ index: 0, delta, finish_reason: finish }],+ })}\n\n`;+ res.write(chunk({ role: "assistant", content: "" }));+ res.write(chunk({ content: answer }));+ res.write(chunk({}, "stop"));+ res.write(+ `data: ${JSON.stringify({+ id: "chatcmpl-mock",+ object: "chat.completion.chunk",+ created: 0,+ model: json.model ?? "mock",+ choices: [],+ usage: { prompt_tokens: 20, completion_tokens: 8, total_tokens: 28 },+ })}\n\n`,+ );+ res.write("data: [DONE]\n\n");+ res.end();+}+const server = http.createServer((req, res) => {if (req.method !== "POST") {res.writeHead(404).end();@@ -109,6 +174,12 @@ const server = http.createServer((req, res) => {try {json = JSON.parse(body);} catch {}+ // A model pinned to Chat Completions reaches this process on `/chat/completions`; the+ // Anthropic-shaped branches below never see such a request.+ if ((req.url ?? "").includes("chat/completions")) {+ openAiChatCompletion(res, json);+ return;+ }const messages = json.messages || [];const flat = JSON.stringify(messages);// Title requests are core's `buildTitlePrompt` (packages/core/src/internal/session-title.ts):diff --git a/packages/web/e2e/video-input.spec.mjs b/packages/web/e2e/video-input.spec.mjsnew file mode 100644index 00000000..f8660b0e--- /dev/null+++ b/packages/web/e2e/video-input.spec.mjs@@ -0,0 +1,129 @@+/**+ * Video input, in a real browser: the composer stages a clip, the model is handed it as a video+ * part, and a reloaded page is served the same clip by reference instead of by value.+ *+ * The model is a Volcengine Ark row of the built-in catalog — the group this was built for — so+ * the whole chain is exercised as shipped: `catalogSupportsVideo` makes the composer offer video+ * input and the task route inline it, AgentHub's patched Chat Completions transformer turns it+ * into the `{"type":"video_url","video_url":{"url":…}}` part the vendor takes, and the mock+ * answers with what it saw. That answer is the load-bearing assertion: if the patch were missing+ * or the clip were quietly filed away as a scratchpad attachment, the reply would say+ * "No video in this request." and the test would fail on the wording, not on a shape.+ *+ * The clip is a real 1-second 32×32 VP8 WebM (base64 below, generated with+ * `ffmpeg -f lavfi -i color=c=navy:s=32x32:d=1 -c:v libvpx -b:v 40k -an clip.webm`), so the+ * browser can actually decode it: the metadata and the first frame are waited for, and the frame's+ * width is asserted — a `<video>` carrying bytes no decoder accepts would render an element while+ * staying at `readyState` 0.+ *+ * The reload half is the windowed-history path: the initial load asks for a tail window+ * (`stream-controller`'s `TAIL_UNITS`), and the server answers a video by reference+ * (`/api/sessions/<id>/trace-video?file=&ordinal=`) — one page of history must not carry tens of+ * megabytes of base64. Fetching that reference returns the clip's bytes.+ */+import { test, expect } from "@playwright/test";+import { provisionAndLogin } from "./auth.mjs";++const BASE = process.env.BASE_URL;+const MOCK = process.env.MOCK_URL;+const U = "videouser";+const P = "password123";+/** A Volcengine Ark row whose card the catalog marks as taking video input. */+const MODEL = { provider: "volcengine", modelId: "doubao-seed-2-1-pro-260915" };++/** 1-second 32×32 navy VP8 clip (1107 bytes), generated with the ffmpeg command in the header. */+const CLIP_BASE64 =+ "GkXfo59ChoEBQveBAULygQRC84EIQoKEd2VibUKHgQJChYECGFOAZwEAAAAAAAQjEU2bdLpNu4tTq4QVSalmU6yBoU27i1Or" ++ "hBZUrmtTrIHYTbuMU6uEElTDZ1OsggEeTbuMU6uEHFO7a1OsggQN7AEAAAAAAABZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" ++ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVSalmsirX" ++ "sYMPQkBNgI1MYXZmNTkuMjcuMTAwV0GNTGF2ZjU5LjI3LjEwMESJiECPQAAAAAAAFlSua8GuAQAAAAAAADjXgQFzxYi0mKpc" ++ "u2I6AZyBACK1nIN1bmSIgQCGhVZfVlA4g4EBI+ODhAJiWgDgibCBILqBIJqBAhJUw2f9c3OgY8CAZ8iaRaOHRU5DT0RFUkSH" ++ "jUxhdmY1OS4yNy4xMDBzc9djwItjxYi0mKpcu2I6AWfIoUWjh0VOQ09ERVJEh5RMYXZjNTkuMzcuMTAwIGxpYnZweGfIokWj" ++ "iERVUkFUSU9ORIeUMDA6MDA6MDEuMDAwMDAwMDAwAAAfQ7Z1QmfngQCjuoEAAICQAgCdASogACAAAEcIhYWIhYSIAgICdaoC" ++ "B/kV3mD+/43k//20D/9tA//bQP/toH+N5vNasQCjlYEAKACxAQABEBAAGAAYWC/0AAhwAKOVgQBQALEBAAEQEAAYABhYL/QA" ++ "CHAAo5WBAHgAsQEAARAQABgAGFgv9AAIcACjlYEAoACxAQABEBAAGAAYWC/0AAhwAKOVgQDIALEBAAEQEAAYABhYL/QACHAA" ++ "o5WBAPAAsQEAARAQABgAGFgv9AAIcACjlYEBGACxAQABEBAUYABhYL/QACHAAKOVgQFAALEBAAEQEAAYABhYL/QACHAAo5WB" ++ "AWgAsQEAARAQABgAGFgv9AAIcACjlYEBkACxAQABEBAAGAAYWC/0AAhwAKOVgQG4ALEBAAEQEAAYABhYL/QACHAAo5WBAeAA" ++ "sQEAARAQABgAGFgv9AAIcACjlYECCACxAQABEBAAGAAYWC/0AAhwAKOVgQIwALEBAAEQEAAYABhYL/QACHAAo5WBAlgAsQEA" ++ "ARAQABgAGFgv9AAIcACjlYECgACxAQABEBAAGAAYWC/0AAhwAKOVgQKoALEBAAEQEAAYABhYL/QACHAAo5WBAtAAsQEAARAQ" ++ "FGAAYWC/0AAhwACjlYEC+ACxAQABEBAAGAAYWC/0AAhwAKOVgQMgALEBAAEQEAAYABhYL/QACHAAo5WBA0gAsQEAARAQABgA" ++ "GFgv9AAIcACjlYEDcACxAQABEBAAGAAYWC/0AAhwAKOVgQOYALEBAAEQEAAYABhYL/QACHAAo5WBA8AAsQEAARAQABgAGFgv" ++ "9AAIcAAcU7trkbuPs4EAt4r3gQHxggGg8IED";+const CLIP = Buffer.from(CLIP_BASE64, "base64");++test("a picked video reaches the model and comes back by reference", async ({ page }) => {+ await provisionAndLogin(page.request, U, P);+ const project = (await (await page.request.get(`${BASE}/api/projects`)).json()).projects[0];+ // One OpenAI-compatible endpoint for the whole group; the mock stands in for Ark.+ const put = await page.request.put(`${BASE}/api/projects/${project.projectId}/models`, {+ data: {+ defaultModel: MODEL,+ models: [+ {+ ...MODEL,+ apiKey: "sk-mock",+ baseUrl: MOCK,+ clientType: "openai-chat",+ contextWindow: 262144,+ },+ ],+ },+ });+ expect(put.ok(), "put models").toBeTruthy();++ const sess = await (+ await page.request.post(+ `${BASE}/api/projects/${project.projectId}/agents/default_agent/sessions`,+ { data: { ...MODEL, approvalMode: "allow-all" } },+ )+ ).json();+ const sessionId = sess.session.sessionId;++ await page.goto(`${BASE}/chat/${sessionId}`);+ const composer = page.getByPlaceholder(/输入消息/);+ await composer.waitFor();++ // The "+" menu offers the video entry for a model that takes one.+ await page.getByRole("button", { name: "更多输入方式" }).click();+ await expect(page.getByText("上传视频")).toBeVisible();+ await page.keyboard.press("Escape");++ // Stage the clip exactly as the picker would: the hidden input takes `video/*`.+ await page.locator('input[type="file"][accept="video/*"]').setInputFiles({+ name: "clip.webm",+ mimeType: "video/webm",+ buffer: CLIP,+ });+ await expect(page.getByText("clip.webm")).toBeVisible();++ await composer.fill("这个视频里有什么?");+ await page.getByRole("button", { name: "发送" }).click();++ // The model was handed the clip itself, as a video part — the proof that the request carried+ // it and that AgentHub's patched transformer built the shape Ark takes.+ await expect(page.getByText(`Saw a video: video/webm, ${CLIP.length} bytes.`)).toBeVisible();++ // The sent message carries a playable clip: metadata and the first frame really load, and the+ // frame is the one that was picked (the live stream's own copy, inline bytes).+ const sent = page.locator("video");+ await expect(sent).toHaveCount(1);+ const liveSrc = await sent.getAttribute("src");+ expect(liveSrc?.startsWith("data:video/webm;base64,")).toBe(true);+ await expect.poll(async () => sent.evaluate((v) => v.readyState)).toBeGreaterThanOrEqual(1);+ expect(await sent.evaluate((v) => v.videoWidth)).toBe(32);+ expect(await sent.evaluate((v) => v.duration)).toBeGreaterThan(0);++ // Reload: the windowed history page hands the same clip over by reference, not by value.+ await page.reload();+ const replayed = page.locator("video");+ await expect(replayed).toHaveCount(1);+ const ref = await replayed.getAttribute("src");+ expect(ref).toMatch(new RegExp(`^/api/sessions/${sessionId}/trace-video\\?`));+ await expect.poll(async () => replayed.evaluate((v) => v.readyState)).toBeGreaterThanOrEqual(1);++ // The reference serves the very bytes that were picked.+ const fetched = await page.request.get(`${BASE}${ref}`);+ expect(fetched.status()).toBe(200);+ expect(fetched.headers()["content-type"] ?? "").toContain("video/webm");+ expect(Buffer.from(await fetched.body()).equals(CLIP)).toBe(true);+});